@runfusion/fusion 0.29.0 → 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 (73) hide show
  1. package/dist/bin.js +10858 -3408
  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-CIH4Acck.js +34 -0
  7. package/dist/client/assets/ChatView-DqJoFquZ.js +1 -0
  8. package/dist/client/assets/DevServerView-Bd8JZ-3C.js +1 -0
  9. package/dist/client/assets/{DirectoryPicker-Bb3TIWEa.js → DirectoryPicker-BOGqZNiq.js} +1 -1
  10. package/dist/client/assets/DocumentsView-B-ELcw4o.js +1 -0
  11. package/dist/client/assets/EvalsView-Ccl9QBYN.js +1 -0
  12. package/dist/client/assets/{ExperimentalAgentOnboardingModal-AsmRLMxm.js → ExperimentalAgentOnboardingModal-BM7EnSvJ.js} +1 -1
  13. package/dist/client/assets/{InsightsView-j7J_vUME.js → InsightsView-DLF49bzu.js} +3 -3
  14. package/dist/client/assets/{MemoryView-QWiqVDuQ.js → MemoryView-CE1D9euM.js} +2 -2
  15. package/dist/client/assets/{NodesView-Cr4CXr7b.js → NodesView-Zxusnhxu.js} +2 -2
  16. package/dist/client/assets/{PiExtensionsManager-CPZ-82Wl.js → PiExtensionsManager-BlMmxtLZ.js} +2 -2
  17. package/dist/client/assets/PluginManager-D4eZ0zA4.js +1 -0
  18. package/dist/client/assets/ReliabilityView-KmH60I_5.js +1 -0
  19. package/dist/client/assets/ReliabilityView-rxA_HgEG.css +1 -0
  20. package/dist/client/assets/ResearchView-C14Zh7c9.js +1 -0
  21. package/dist/client/assets/ResearchView-DTh8FLUm.css +1 -0
  22. package/dist/client/assets/{SettingsModal-8l8vfXns.js → SettingsModal-DRnZ6eBW.js} +1 -1
  23. package/dist/client/assets/SettingsModal-c1QwWno0.js +31 -0
  24. package/dist/client/assets/{SettingsModal-ChnabMhF.css → SettingsModal-sp7SNwS9.css} +1 -1
  25. package/dist/client/assets/SetupWizardModal-BmmRM3g-.js +1 -0
  26. package/dist/client/assets/SkillsView-DWVtT2-8.js +1 -0
  27. package/dist/client/assets/StashRecoveryView-CKkaWzzc.js +1 -0
  28. package/dist/client/assets/{TodoView-rSn0aPsb.js → TodoView-hbD0NOCY.js} +2 -2
  29. package/dist/client/assets/dashboard-view-VNPB3ca0.js +21 -0
  30. package/dist/client/assets/{folder-open-Bq_TweLR.js → folder-open-BTN2_Wuv.js} +1 -1
  31. package/dist/client/assets/index-CZFBq256.css +1 -0
  32. package/dist/client/assets/index-DzSLVOnp.js +695 -0
  33. package/dist/client/assets/{upload-D1y22Www.js → upload-euJEs_N2.js} +1 -1
  34. package/dist/client/assets/{users-UQdBpweI.js → users-B7miEHCZ.js} +1 -1
  35. package/dist/client/assets/vendor-codemirror-jBKmHyH0.js +27 -0
  36. package/dist/client/index.html +3 -2
  37. package/dist/client/version.json +1 -1
  38. package/dist/droid-cli/package.json +1 -1
  39. package/dist/extension.js +7898 -1725
  40. package/dist/pi-claude-cli/package.json +1 -1
  41. package/dist/plugins/fusion-plugin-cli-printing-press/package.json +1 -1
  42. package/dist/plugins/fusion-plugin-cli-printing-press/src/__tests__/workflow-steps-verdict-contract.test.ts +42 -0
  43. package/dist/plugins/fusion-plugin-cursor-runtime/package.json +1 -1
  44. package/dist/plugins/fusion-plugin-dependency-graph/package.json +1 -1
  45. package/dist/plugins/fusion-plugin-droid-runtime/package.json +1 -1
  46. package/dist/plugins/fusion-plugin-hermes-runtime/package.json +1 -1
  47. package/dist/plugins/fusion-plugin-openclaw-runtime/package.json +1 -1
  48. package/dist/plugins/fusion-plugin-paperclip-runtime/package.json +1 -1
  49. package/dist/plugins/fusion-plugin-reports/package.json +1 -1
  50. package/dist/plugins/fusion-plugin-roadmap/package.json +1 -1
  51. package/dist/plugins/fusion-plugin-whatsapp-chat/package.json +1 -1
  52. package/package.json +1 -1
  53. package/skill/fusion/SKILL.md +2 -2
  54. package/skill/fusion/references/extension-tools.md +23 -0
  55. package/skill/fusion/references/fusion-capabilities.md +2 -0
  56. package/dist/client/assets/AgentDetailView-CWyOv8HJ.js +0 -18
  57. package/dist/client/assets/AgentDetailView-ChIKbcEi.css +0 -1
  58. package/dist/client/assets/AgentsView-DljrBNE1.js +0 -34
  59. package/dist/client/assets/ChatView-BklDUi5_.js +0 -1
  60. package/dist/client/assets/DevServerView-BqcI1wXr.js +0 -1
  61. package/dist/client/assets/DocumentsView-BhrdTTh3.js +0 -1
  62. package/dist/client/assets/EvalsView-DrFp2cLg.js +0 -1
  63. package/dist/client/assets/PluginManager-DShC4UiM.js +0 -1
  64. package/dist/client/assets/ResearchView-B5wYC1KE.js +0 -1
  65. package/dist/client/assets/ResearchView-C7uXon3o.css +0 -1
  66. package/dist/client/assets/SettingsModal-CYetgxZj.js +0 -31
  67. package/dist/client/assets/SetupWizardModal-_IK6hTA7.js +0 -1
  68. package/dist/client/assets/SkillsView-Dilmj1nh.js +0 -1
  69. package/dist/client/assets/StashRecoveryView-BtL9aAn3.js +0 -1
  70. package/dist/client/assets/dashboard-view-C_G8JVU7.js +0 -21
  71. package/dist/client/assets/index-DjfAYMGG.css +0 -1
  72. package/dist/client/assets/index-tbwUVj8p.js +0 -696
  73. package/dist/client/assets/star-Dn0V0Cnq.js +0 -6
@@ -1,696 +0,0 @@
1
- const __vite__mapDeps=(i,m=__vite__mapDeps,d=(m.f||(m.f=["assets/AgentDetailView-CWyOv8HJ.js","assets/vendor-react-K0fH_qHe.js","assets/star-Dn0V0Cnq.js","assets/ExperimentalAgentOnboardingModal-AsmRLMxm.js","assets/ExperimentalAgentOnboardingModal-BNpveCEk.css","assets/vendor-xterm-DzcZoU0P.js","assets/vendor-xterm-LZoznX6r.css","assets/AgentDetailView-ChIKbcEi.css","assets/addon-fit-C7jRorKK.js","assets/addon-web-links-CkJwd4cQ.js","assets/addon-webgl-BjvOw43o.js","assets/TodoView-rSn0aPsb.js","assets/TodoView-Cx9cVhq7.css","assets/SetupWizardModal-_IK6hTA7.js","assets/DirectoryPicker-Bb3TIWEa.js","assets/folder-open-Bq_TweLR.js","assets/DirectoryPicker-DzKVmxOf.css","assets/projectDetection-G3XuxD2X.js","assets/SetupWizardModal-CGYGKurR.css","assets/SettingsModal-CYetgxZj.js","assets/SettingsModal-8l8vfXns.js","assets/SettingsModal-ChnabMhF.css","assets/users-UQdBpweI.js","assets/SettingsModal-BAx4gt2A.css","assets/dashboard-view-C_G8JVU7.js","assets/createLucideIcon-BazL2hk5.js","assets/dashboard-view-DqWnXEbq.css","assets/dashboard-view-BWGH_fAq.js","assets/dashboard-view-DdGlfuu-.css","assets/AgentsView-DljrBNE1.js","assets/upload-D1y22Www.js","assets/AgentsView-BI_CESkd.css","assets/DocumentsView-BhrdTTh3.js","assets/DocumentsView-gv4zG3aT.css","assets/InsightsView-j7J_vUME.js","assets/InsightsView-B0J4mhzV.css","assets/ResearchView-B5wYC1KE.js","assets/ResearchView-C7uXon3o.css","assets/EvalsView-DrFp2cLg.js","assets/EvalsView-CUNJ1TLc.css","assets/NodesView-Cr4CXr7b.js","assets/NodesView-DT4pXowv.css","assets/ChatView-BklDUi5_.js","assets/ChatView-DwJAd5G1.css","assets/SkillsView-Dilmj1nh.js","assets/SkillsView-CUbSBeZ2.css","assets/MemoryView-QWiqVDuQ.js","assets/MemoryView-zaXewZzi.css","assets/DevServerView-BqcI1wXr.js","assets/DevServerView-DlZpuAnj.css","assets/StashRecoveryView-BtL9aAn3.js","assets/StashRecoveryView-B_8WIQEo.css"])))=>i.map(i=>d[i]);
2
- import{r as i,j as t,R as ga,a as $a,g as sb,c as Ty}from"./vendor-react-K0fH_qHe.js";import"./vendor-xterm-DzcZoU0P.js";(function(){const n=document.createElement("link").relList;if(n&&n.supports&&n.supports("modulepreload"))return;for(const r of document.querySelectorAll('link[rel="modulepreload"]'))a(r);new MutationObserver(r=>{for(const o of r)if(o.type==="childList")for(const l of o.addedNodes)l.tagName==="LINK"&&l.rel==="modulepreload"&&a(l)}).observe(document,{childList:!0,subtree:!0});function s(r){const o={};return r.integrity&&(o.integrity=r.integrity),r.referrerPolicy&&(o.referrerPolicy=r.referrerPolicy),r.crossOrigin==="use-credentials"?o.credentials="include":r.crossOrigin==="anonymous"?o.credentials="omit":o.credentials="same-origin",o}function a(r){if(r.ep)return;r.ep=!0;const o=s(r);fetch(r.href,o)}})();/**
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 ib=(...e)=>e.filter((n,s,a)=>!!n&&n.trim()!==""&&a.indexOf(n)===s).join(" ").trim();/**
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 Py=e=>e.replace(/([a-z0-9])([A-Z])/g,"$1-$2").toLowerCase();/**
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 $y=e=>e.replace(/^([A-Z])|[\s-_]+(\w)/g,(n,s,a)=>a?a.toUpperCase():s.toLowerCase());/**
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 Dm=e=>{const n=$y(e);return n.charAt(0).toUpperCase()+n.slice(1)};/**
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
- */var Hc={xmlns:"http://www.w3.org/2000/svg",width:24,height:24,viewBox:"0 0 24 24",fill:"none",stroke:"currentColor",strokeWidth:2,strokeLinecap:"round",strokeLinejoin:"round"};/**
28
- * @license lucide-react v1.7.0 - ISC
29
- *
30
- * This source code is licensed under the ISC license.
31
- * See the LICENSE file in the root directory of this source tree.
32
- */const Dy=e=>{for(const n in e)if(n.startsWith("aria-")||n==="role"||n==="title")return!0;return!1},Ly=i.createContext({}),Oy=()=>i.useContext(Ly),Fy=i.forwardRef(({color:e,size:n,strokeWidth:s,absoluteStrokeWidth:a,className:r="",children:o,iconNode:l,...c},d)=>{const{size:u=24,strokeWidth:h=2,absoluteStrokeWidth:m=!1,color:f="currentColor",className:p=""}=Oy()??{},g=a??m?Number(s??h)*24/Number(n??u):s??h;return i.createElement("svg",{ref:d,...Hc,width:n??u??Hc.width,height:n??u??Hc.height,stroke:e??f,strokeWidth:g,className:ib("lucide",p,r),...!o&&!Dy(c)&&{"aria-hidden":"true"},...c},[...l.map(([w,v])=>i.createElement(w,v)),...Array.isArray(o)?o:[o]])});/**
33
- * @license lucide-react v1.7.0 - ISC
34
- *
35
- * This source code is licensed under the ISC license.
36
- * See the LICENSE file in the root directory of this source tree.
37
- */const lt=(e,n)=>{const s=i.forwardRef(({className:a,...r},o)=>i.createElement(Fy,{ref:o,iconNode:n,className:ib(`lucide-${Py(Dm(e))}`,`lucide-${e}`,a),...r}));return s.displayName=Dm(e),s};/**
38
- * @license lucide-react v1.7.0 - ISC
39
- *
40
- * This source code is licensed under the ISC license.
41
- * See the LICENSE file in the root directory of this source tree.
42
- */const zy=[["path",{d:"M22 12h-2.48a2 2 0 0 0-1.93 1.46l-2.35 8.36a.25.25 0 0 1-.48 0L9.24 2.18a.25.25 0 0 0-.48 0l-2.35 8.36A2 2 0 0 1 4.49 12H2",key:"169zse"}]],Vs=lt("activity",zy);/**
43
- * @license lucide-react v1.7.0 - ISC
44
- *
45
- * This source code is licensed under the ISC license.
46
- * See the LICENSE file in the root directory of this source tree.
47
- */const By=[["rect",{width:"20",height:"5",x:"2",y:"3",rx:"1",key:"1wp1u1"}],["path",{d:"M4 8v11a2 2 0 0 0 2 2h2",key:"tvwodi"}],["path",{d:"M20 8v11a2 2 0 0 1-2 2h-2",key:"1gkqxj"}],["path",{d:"m9 15 3-3 3 3",key:"1pd0qc"}],["path",{d:"M12 12v9",key:"192myk"}]],Uy=lt("archive-restore",By);/**
48
- * @license lucide-react v1.7.0 - ISC
49
- *
50
- * This source code is licensed under the ISC license.
51
- * See the LICENSE file in the root directory of this source tree.
52
- */const Hy=[["rect",{width:"20",height:"5",x:"2",y:"3",rx:"1",key:"1wp1u1"}],["path",{d:"M4 8v11a2 2 0 0 0 2 2h12a2 2 0 0 0 2-2V8",key:"1s80jp"}],["path",{d:"M10 12h4",key:"a56b0p"}]],Fr=lt("archive",Hy);/**
53
- * @license lucide-react v1.7.0 - ISC
54
- *
55
- * This source code is licensed under the ISC license.
56
- * See the LICENSE file in the root directory of this source tree.
57
- */const qy=[["path",{d:"M12 5v14",key:"s699le"}],["path",{d:"m19 12-7 7-7-7",key:"1idqje"}]],Uo=lt("arrow-down",qy);/**
58
- * @license lucide-react v1.7.0 - ISC
59
- *
60
- * This source code is licensed under the ISC license.
61
- * See the LICENSE file in the root directory of this source tree.
62
- */const Vy=[["path",{d:"m12 19-7-7 7-7",key:"1l729n"}],["path",{d:"M19 12H5",key:"x3x0zl"}]],Ka=lt("arrow-left",Vy);/**
63
- * @license lucide-react v1.7.0 - ISC
64
- *
65
- * This source code is licensed under the ISC license.
66
- * See the LICENSE file in the root directory of this source tree.
67
- */const Wy=[["path",{d:"M5 12h14",key:"1ays0h"}],["path",{d:"m12 5 7 7-7 7",key:"xquz4c"}]],Ho=lt("arrow-right",Wy);/**
68
- * @license lucide-react v1.7.0 - ISC
69
- *
70
- * This source code is licensed under the ISC license.
71
- * See the LICENSE file in the root directory of this source tree.
72
- */const Gy=[["path",{d:"m21 16-4 4-4-4",key:"f6ql7i"}],["path",{d:"M17 20V4",key:"1ejh1v"}],["path",{d:"m3 8 4-4 4 4",key:"11wl7u"}],["path",{d:"M7 4v16",key:"1glfcx"}]],ab=lt("arrow-up-down",Gy);/**
73
- * @license lucide-react v1.7.0 - ISC
74
- *
75
- * This source code is licensed under the ISC license.
76
- * See the LICENSE file in the root directory of this source tree.
77
- */const Ky=[["path",{d:"m5 12 7-7 7 7",key:"hav0vg"}],["path",{d:"M12 19V5",key:"x0mq9r"}]],La=lt("arrow-up",Ky);/**
78
- * @license lucide-react v1.7.0 - ISC
79
- *
80
- * This source code is licensed under the ISC license.
81
- * See the LICENSE file in the root directory of this source tree.
82
- */const Jy=[["path",{d:"M12 7v14",key:"1akyts"}],["path",{d:"M3 18a1 1 0 0 1-1-1V4a1 1 0 0 1 1-1h5a4 4 0 0 1 4 4 4 4 0 0 1 4-4h5a1 1 0 0 1 1 1v13a1 1 0 0 1-1 1h-6a3 3 0 0 0-3 3 3 3 0 0 0-3-3z",key:"ruj8y"}]],Yy=lt("book-open",Jy);/**
83
- * @license lucide-react v1.7.0 - ISC
84
- *
85
- * This source code is licensed under the ISC license.
86
- * See the LICENSE file in the root directory of this source tree.
87
- */const Qy=[["path",{d:"M12 8V4H8",key:"hb8ula"}],["rect",{width:"16",height:"12",x:"4",y:"8",rx:"2",key:"enze0r"}],["path",{d:"M2 14h2",key:"vft8re"}],["path",{d:"M20 14h2",key:"4cs60a"}],["path",{d:"M15 13v2",key:"1xurst"}],["path",{d:"M9 13v2",key:"rq6x2g"}]],Xn=lt("bot",Qy);/**
88
- * @license lucide-react v1.7.0 - ISC
89
- *
90
- * This source code is licensed under the ISC license.
91
- * See the LICENSE file in the root directory of this source tree.
92
- */const Xy=[["path",{d:"M21 8a2 2 0 0 0-1-1.73l-7-4a2 2 0 0 0-2 0l-7 4A2 2 0 0 0 3 8v8a2 2 0 0 0 1 1.73l7 4a2 2 0 0 0 2 0l7-4A2 2 0 0 0 21 16Z",key:"hh9hay"}],["path",{d:"m3.3 7 8.7 5 8.7-5",key:"g66t2b"}],["path",{d:"M12 22V12",key:"d0xqtd"}]],iu=lt("box",Xy);/**
93
- * @license lucide-react v1.7.0 - ISC
94
- *
95
- * This source code is licensed under the ISC license.
96
- * See the LICENSE file in the root directory of this source tree.
97
- */const Zy=[["path",{d:"M12 18V5",key:"adv99a"}],["path",{d:"M15 13a4.17 4.17 0 0 1-3-4 4.17 4.17 0 0 1-3 4",key:"1e3is1"}],["path",{d:"M17.598 6.5A3 3 0 1 0 12 5a3 3 0 1 0-5.598 1.5",key:"1gqd8o"}],["path",{d:"M17.997 5.125a4 4 0 0 1 2.526 5.77",key:"iwvgf7"}],["path",{d:"M18 18a4 4 0 0 0 2-7.464",key:"efp6ie"}],["path",{d:"M19.967 17.483A4 4 0 1 1 12 18a4 4 0 1 1-7.967-.517",key:"1gq6am"}],["path",{d:"M6 18a4 4 0 0 1-2-7.464",key:"k1g0md"}],["path",{d:"M6.003 5.125a4 4 0 0 0-2.526 5.77",key:"q97ue3"}]],Po=lt("brain",Zy);/**
98
- * @license lucide-react v1.7.0 - ISC
99
- *
100
- * This source code is licensed under the ISC license.
101
- * See the LICENSE file in the root directory of this source tree.
102
- */const ew=[["path",{d:"M8 2v4",key:"1cmpym"}],["path",{d:"M16 2v4",key:"4m81vk"}],["rect",{width:"18",height:"18",x:"3",y:"4",rx:"2",key:"1hopcy"}],["path",{d:"M3 10h18",key:"8toen8"}]],rb=lt("calendar",ew);/**
103
- * @license lucide-react v1.7.0 - ISC
104
- *
105
- * This source code is licensed under the ISC license.
106
- * See the LICENSE file in the root directory of this source tree.
107
- */const tw=[["path",{d:"M18 6 7 17l-5-5",key:"116fxf"}],["path",{d:"m22 10-7.5 7.5L13 16",key:"ke71qq"}]],Lm=lt("check-check",tw);/**
108
- * @license lucide-react v1.7.0 - ISC
109
- *
110
- * This source code is licensed under the ISC license.
111
- * See the LICENSE file in the root directory of this source tree.
112
- */const nw=[["path",{d:"M20 6 9 17l-5-5",key:"1gmf2c"}]],gs=lt("check",nw);/**
113
- * @license lucide-react v1.7.0 - ISC
114
- *
115
- * This source code is licensed under the ISC license.
116
- * See the LICENSE file in the root directory of this source tree.
117
- */const sw=[["path",{d:"m6 9 6 6 6-6",key:"qrunsl"}]],vn=lt("chevron-down",sw);/**
118
- * @license lucide-react v1.7.0 - ISC
119
- *
120
- * This source code is licensed under the ISC license.
121
- * See the LICENSE file in the root directory of this source tree.
122
- */const iw=[["path",{d:"m15 18-6-6 6-6",key:"1wnfg3"}]],gc=lt("chevron-left",iw);/**
123
- * @license lucide-react v1.7.0 - ISC
124
- *
125
- * This source code is licensed under the ISC license.
126
- * See the LICENSE file in the root directory of this source tree.
127
- */const aw=[["path",{d:"m9 18 6-6-6-6",key:"mthhwq"}]],Wn=lt("chevron-right",aw);/**
128
- * @license lucide-react v1.7.0 - ISC
129
- *
130
- * This source code is licensed under the ISC license.
131
- * See the LICENSE file in the root directory of this source tree.
132
- */const rw=[["path",{d:"m18 15-6-6-6 6",key:"153udz"}]],mi=lt("chevron-up",rw);/**
133
- * @license lucide-react v1.7.0 - ISC
134
- *
135
- * This source code is licensed under the ISC license.
136
- * See the LICENSE file in the root directory of this source tree.
137
- */const ow=[["circle",{cx:"12",cy:"12",r:"10",key:"1mglay"}],["line",{x1:"12",x2:"12",y1:"8",y2:"12",key:"1pkeuh"}],["line",{x1:"12",x2:"12.01",y1:"16",y2:"16",key:"4dfq90"}]],zs=lt("circle-alert",ow);/**
138
- * @license lucide-react v1.7.0 - ISC
139
- *
140
- * This source code is licensed under the ISC license.
141
- * See the LICENSE file in the root directory of this source tree.
142
- */const lw=[["path",{d:"M21.801 10A10 10 0 1 1 17 3.335",key:"yps3ct"}],["path",{d:"m9 11 3 3L22 4",key:"1pflzl"}]],Zn=lt("circle-check-big",lw);/**
143
- * @license lucide-react v1.7.0 - ISC
144
- *
145
- * This source code is licensed under the ISC license.
146
- * See the LICENSE file in the root directory of this source tree.
147
- */const cw=[["circle",{cx:"12",cy:"12",r:"10",key:"1mglay"}],["circle",{cx:"12",cy:"12",r:"1",key:"41hilf"}]],bc=lt("circle-dot",cw);/**
148
- * @license lucide-react v1.7.0 - ISC
149
- *
150
- * This source code is licensed under the ISC license.
151
- * See the LICENSE file in the root directory of this source tree.
152
- */const dw=[["circle",{cx:"12",cy:"12",r:"10",key:"1mglay"}],["path",{d:"M9.09 9a3 3 0 0 1 5.83 1c0 2-3 3-3 3",key:"1u773s"}],["path",{d:"M12 17h.01",key:"p32p05"}]],au=lt("circle-question-mark",dw);/**
153
- * @license lucide-react v1.7.0 - ISC
154
- *
155
- * This source code is licensed under the ISC license.
156
- * See the LICENSE file in the root directory of this source tree.
157
- */const uw=[["circle",{cx:"12",cy:"12",r:"10",key:"1mglay"}],["rect",{x:"9",y:"9",width:"6",height:"6",rx:"1",key:"1ssd4o"}]],mw=lt("circle-stop",uw);/**
158
- * @license lucide-react v1.7.0 - ISC
159
- *
160
- * This source code is licensed under the ISC license.
161
- * See the LICENSE file in the root directory of this source tree.
162
- */const hw=[["circle",{cx:"12",cy:"12",r:"10",key:"1mglay"}],["path",{d:"m15 9-6 6",key:"1uzhvr"}],["path",{d:"m9 9 6 6",key:"z0biqf"}]],qo=lt("circle-x",hw);/**
163
- * @license lucide-react v1.7.0 - ISC
164
- *
165
- * This source code is licensed under the ISC license.
166
- * See the LICENSE file in the root directory of this source tree.
167
- */const pw=[["rect",{width:"8",height:"4",x:"8",y:"2",rx:"1",ry:"1",key:"tgr4d6"}],["path",{d:"M16 4h2a2 2 0 0 1 2 2v14a2 2 0 0 1-2 2H6a2 2 0 0 1-2-2V6a2 2 0 0 1 2-2h2",key:"116196"}],["path",{d:"M12 11h4",key:"1jrz19"}],["path",{d:"M12 16h4",key:"n85exb"}],["path",{d:"M8 11h.01",key:"1dfujw"}],["path",{d:"M8 16h.01",key:"18s6g9"}]],fw=lt("clipboard-list",pw);/**
168
- * @license lucide-react v1.7.0 - ISC
169
- *
170
- * This source code is licensed under the ISC license.
171
- * See the LICENSE file in the root directory of this source tree.
172
- */const gw=[["circle",{cx:"12",cy:"12",r:"10",key:"1mglay"}],["path",{d:"M12 6v6l4 2",key:"mmk7yg"}]],Yi=lt("clock",gw);/**
173
- * @license lucide-react v1.7.0 - ISC
174
- *
175
- * This source code is licensed under the ISC license.
176
- * See the LICENSE file in the root directory of this source tree.
177
- */const bw=[["path",{d:"m16 18 6-6-6-6",key:"eg8j8"}],["path",{d:"m8 6-6 6 6 6",key:"ppft3o"}]],ob=lt("code",bw);/**
178
- * @license lucide-react v1.7.0 - ISC
179
- *
180
- * This source code is licensed under the ISC license.
181
- * See the LICENSE file in the root directory of this source tree.
182
- */const xw=[["rect",{width:"18",height:"18",x:"3",y:"3",rx:"2",key:"afitv7"}],["path",{d:"M9 3v18",key:"fh3hqa"}],["path",{d:"M15 3v18",key:"14nvp0"}]],Om=lt("columns-3",xw);/**
183
- * @license lucide-react v1.7.0 - ISC
184
- *
185
- * This source code is licensed under the ISC license.
186
- * See the LICENSE file in the root directory of this source tree.
187
- */const vw=[["rect",{width:"14",height:"14",x:"8",y:"8",rx:"2",ry:"2",key:"17jyea"}],["path",{d:"M4 16c-1.1 0-2-.9-2-2V4c0-1.1.9-2 2-2h10c1.1 0 2 .9 2 2",key:"zix9uf"}]],ba=lt("copy",vw);/**
188
- * @license lucide-react v1.7.0 - ISC
189
- *
190
- * This source code is licensed under the ISC license.
191
- * See the LICENSE file in the root directory of this source tree.
192
- */const yw=[["path",{d:"M12 20v2",key:"1lh1kg"}],["path",{d:"M12 2v2",key:"tus03m"}],["path",{d:"M17 20v2",key:"1rnc9c"}],["path",{d:"M17 2v2",key:"11trls"}],["path",{d:"M2 12h2",key:"1t8f8n"}],["path",{d:"M2 17h2",key:"7oei6x"}],["path",{d:"M2 7h2",key:"asdhe0"}],["path",{d:"M20 12h2",key:"1q8mjw"}],["path",{d:"M20 17h2",key:"1fpfkl"}],["path",{d:"M20 7h2",key:"1o8tra"}],["path",{d:"M7 20v2",key:"4gnj0m"}],["path",{d:"M7 2v2",key:"1i4yhu"}],["rect",{x:"4",y:"4",width:"16",height:"16",rx:"2",key:"1vbyd7"}],["rect",{x:"8",y:"8",width:"8",height:"8",rx:"1",key:"z9xiuo"}]],lb=lt("cpu",yw);/**
193
- * @license lucide-react v1.7.0 - ISC
194
- *
195
- * This source code is licensed under the ISC license.
196
- * See the LICENSE file in the root directory of this source tree.
197
- */const ww=[["path",{d:"M12 15V3",key:"m9g1x1"}],["path",{d:"M21 15v4a2 2 0 0 1-2 2H5a2 2 0 0 1-2-2v-4",key:"ih7n3h"}],["path",{d:"m7 10 5 5 5-5",key:"brsn70"}]],kw=lt("download",ww);/**
198
- * @license lucide-react v1.7.0 - ISC
199
- *
200
- * This source code is licensed under the ISC license.
201
- * See the LICENSE file in the root directory of this source tree.
202
- */const jw=[["circle",{cx:"12",cy:"12",r:"1",key:"41hilf"}],["circle",{cx:"12",cy:"5",r:"1",key:"gxeob9"}],["circle",{cx:"12",cy:"19",r:"1",key:"lyex9k"}]],Nw=lt("ellipsis-vertical",jw);/**
203
- * @license lucide-react v1.7.0 - ISC
204
- *
205
- * This source code is licensed under the ISC license.
206
- * See the LICENSE file in the root directory of this source tree.
207
- */const Sw=[["circle",{cx:"12",cy:"12",r:"1",key:"41hilf"}],["circle",{cx:"19",cy:"12",r:"1",key:"1wjl8i"}],["circle",{cx:"5",cy:"12",r:"1",key:"1pcz8c"}]],ru=lt("ellipsis",Sw);/**
208
- * @license lucide-react v1.7.0 - ISC
209
- *
210
- * This source code is licensed under the ISC license.
211
- * See the LICENSE file in the root directory of this source tree.
212
- */const Cw=[["path",{d:"M15 3h6v6",key:"1q9fwt"}],["path",{d:"M10 14 21 3",key:"gplh6r"}],["path",{d:"M18 13v6a2 2 0 0 1-2 2H5a2 2 0 0 1-2-2V8a2 2 0 0 1 2-2h6",key:"a6xqqp"}]],cb=lt("external-link",Cw);/**
213
- * @license lucide-react v1.7.0 - ISC
214
- *
215
- * This source code is licensed under the ISC license.
216
- * See the LICENSE file in the root directory of this source tree.
217
- */const Ew=[["path",{d:"M10.733 5.076a10.744 10.744 0 0 1 11.205 6.575 1 1 0 0 1 0 .696 10.747 10.747 0 0 1-1.444 2.49",key:"ct8e1f"}],["path",{d:"M14.084 14.158a3 3 0 0 1-4.242-4.242",key:"151rxh"}],["path",{d:"M17.479 17.499a10.75 10.75 0 0 1-15.417-5.151 1 1 0 0 1 0-.696 10.75 10.75 0 0 1 4.446-5.143",key:"13bj9a"}],["path",{d:"m2 2 20 20",key:"1ooewy"}]],qu=lt("eye-off",Ew);/**
218
- * @license lucide-react v1.7.0 - ISC
219
- *
220
- * This source code is licensed under the ISC license.
221
- * See the LICENSE file in the root directory of this source tree.
222
- */const _w=[["path",{d:"M2.062 12.348a1 1 0 0 1 0-.696 10.75 10.75 0 0 1 19.876 0 1 1 0 0 1 0 .696 10.75 10.75 0 0 1-19.876 0",key:"1nclc0"}],["circle",{cx:"12",cy:"12",r:"3",key:"1v7zrd"}]],zr=lt("eye",_w);/**
223
- * @license lucide-react v1.7.0 - ISC
224
- *
225
- * This source code is licensed under the ISC license.
226
- * See the LICENSE file in the root directory of this source tree.
227
- */const Mw=[["path",{d:"M6 22a2 2 0 0 1-2-2V4a2 2 0 0 1 2-2h8a2.4 2.4 0 0 1 1.704.706l3.588 3.588A2.4 2.4 0 0 1 20 8v12a2 2 0 0 1-2 2z",key:"1oefj6"}],["path",{d:"M14 2v5a1 1 0 0 0 1 1h5",key:"wfsgrz"}],["path",{d:"M10 12.5 8 15l2 2.5",key:"1tg20x"}],["path",{d:"m14 12.5 2 2.5-2 2.5",key:"yinavb"}]],ki=lt("file-code",Mw);/**
228
- * @license lucide-react v1.7.0 - ISC
229
- *
230
- * This source code is licensed under the ISC license.
231
- * See the LICENSE file in the root directory of this source tree.
232
- */const Aw=[["path",{d:"M6 22a2 2 0 0 1-2-2V4a2 2 0 0 1 2-2h8a2.4 2.4 0 0 1 1.704.706l3.588 3.588A2.4 2.4 0 0 1 20 8v12a2 2 0 0 1-2 2z",key:"1oefj6"}],["path",{d:"M9 10h6",key:"9gxzsh"}],["path",{d:"M12 13V7",key:"h0r20n"}],["path",{d:"M9 17h6",key:"r8uit2"}]],ou=lt("file-diff",Aw);/**
233
- * @license lucide-react v1.7.0 - ISC
234
- *
235
- * This source code is licensed under the ISC license.
236
- * See the LICENSE file in the root directory of this source tree.
237
- */const Rw=[["path",{d:"M6 22a2 2 0 0 1-2-2V4a2 2 0 0 1 2-2h8a2.4 2.4 0 0 1 1.704.706l3.588 3.588A2.4 2.4 0 0 1 20 8v12a2 2 0 0 1-2 2z",key:"1oefj6"}],["path",{d:"M14 2v5a1 1 0 0 0 1 1h5",key:"wfsgrz"}],["path",{d:"M9 15h6",key:"cctwl0"}]],Iw=lt("file-minus",Rw);/**
238
- * @license lucide-react v1.7.0 - ISC
239
- *
240
- * This source code is licensed under the ISC license.
241
- * See the LICENSE file in the root directory of this source tree.
242
- */const Tw=[["path",{d:"M12.659 22H18a2 2 0 0 0 2-2V8a2.4 2.4 0 0 0-.706-1.706l-3.588-3.588A2.4 2.4 0 0 0 14 2H6a2 2 0 0 0-2 2v9.34",key:"o6klzx"}],["path",{d:"M14 2v5a1 1 0 0 0 1 1h5",key:"wfsgrz"}],["path",{d:"M10.378 12.622a1 1 0 0 1 3 3.003L8.36 20.637a2 2 0 0 1-.854.506l-2.867.837a.5.5 0 0 1-.62-.62l.836-2.869a2 2 0 0 1 .506-.853z",key:"zhnas1"}]],db=lt("file-pen",Tw);/**
243
- * @license lucide-react v1.7.0 - ISC
244
- *
245
- * This source code is licensed under the ISC license.
246
- * See the LICENSE file in the root directory of this source tree.
247
- */const Pw=[["path",{d:"M6 22a2 2 0 0 1-2-2V4a2 2 0 0 1 2-2h8a2.4 2.4 0 0 1 1.704.706l3.588 3.588A2.4 2.4 0 0 1 20 8v12a2 2 0 0 1-2 2z",key:"1oefj6"}],["path",{d:"M14 2v5a1 1 0 0 0 1 1h5",key:"wfsgrz"}],["path",{d:"M9 15h6",key:"cctwl0"}],["path",{d:"M12 18v-6",key:"17g6i2"}]],$w=lt("file-plus",Pw);/**
248
- * @license lucide-react v1.7.0 - ISC
249
- *
250
- * This source code is licensed under the ISC license.
251
- * See the LICENSE file in the root directory of this source tree.
252
- */const Dw=[["path",{d:"M6 22a2 2 0 0 1-2-2V4a2 2 0 0 1 2-2h8a2.4 2.4 0 0 1 1.704.706l3.588 3.588A2.4 2.4 0 0 1 20 8v12a2 2 0 0 1-2 2z",key:"1oefj6"}],["path",{d:"M12 17h.01",key:"p32p05"}],["path",{d:"M9.1 9a3 3 0 0 1 5.82 1c0 2-3 3-3 3",key:"mhlwft"}]],Lw=lt("file-question-mark",Dw);/**
253
- * @license lucide-react v1.7.0 - ISC
254
- *
255
- * This source code is licensed under the ISC license.
256
- * See the LICENSE file in the root directory of this source tree.
257
- */const Ow=[["path",{d:"M6 22a2 2 0 0 1-2-2V4a2 2 0 0 1 2-2h8a2.4 2.4 0 0 1 1.704.706l3.588 3.588A2.4 2.4 0 0 1 20 8v12a2 2 0 0 1-2 2z",key:"1oefj6"}],["path",{d:"M14 2v5a1 1 0 0 0 1 1h5",key:"wfsgrz"}],["path",{d:"M10 9H8",key:"b1mrlr"}],["path",{d:"M16 13H8",key:"t4e002"}],["path",{d:"M16 17H8",key:"z1uh3a"}]],xa=lt("file-text",Ow);/**
258
- * @license lucide-react v1.7.0 - ISC
259
- *
260
- * This source code is licensed under the ISC license.
261
- * See the LICENSE file in the root directory of this source tree.
262
- */const Fw=[["path",{d:"M6 22a2 2 0 0 1-2-2V4a2 2 0 0 1 2-2h8a2.4 2.4 0 0 1 1.704.706l3.588 3.588A2.4 2.4 0 0 1 20 8v12a2 2 0 0 1-2 2z",key:"1oefj6"}],["path",{d:"M14 2v5a1 1 0 0 0 1 1h5",key:"wfsgrz"}],["path",{d:"M11 18h2",key:"12mj7e"}],["path",{d:"M12 12v6",key:"3ahymv"}],["path",{d:"M9 13v-.5a.5.5 0 0 1 .5-.5h5a.5.5 0 0 1 .5.5v.5",key:"qbrxap"}]],zw=lt("file-type",Fw);/**
263
- * @license lucide-react v1.7.0 - ISC
264
- *
265
- * This source code is licensed under the ISC license.
266
- * See the LICENSE file in the root directory of this source tree.
267
- */const Bw=[["path",{d:"M6 22a2 2 0 0 1-2-2V4a2 2 0 0 1 2-2h8a2.4 2.4 0 0 1 1.704.706l3.588 3.588A2.4 2.4 0 0 1 20 8v12a2 2 0 0 1-2 2z",key:"1oefj6"}],["path",{d:"M14 2v5a1 1 0 0 0 1 1h5",key:"wfsgrz"}]],ub=lt("file",Bw);/**
268
- * @license lucide-react v1.7.0 - ISC
269
- *
270
- * This source code is licensed under the ISC license.
271
- * See the LICENSE file in the root directory of this source tree.
272
- */const Uw=[["path",{d:"M4 22V4a1 1 0 0 1 .4-.8A6 6 0 0 1 8 2c3 0 5 2 7.333 2q2 0 3.067-.8A1 1 0 0 1 20 4v10a1 1 0 0 1-.4.8A6 6 0 0 1 16 16c-3 0-5-2-8-2a6 6 0 0 0-4 1.528",key:"1jaruq"}]],Hw=lt("flag",Uw);/**
273
- * @license lucide-react v1.7.0 - ISC
274
- *
275
- * This source code is licensed under the ISC license.
276
- * See the LICENSE file in the root directory of this source tree.
277
- */const qw=[["path",{d:"M18 19a5 5 0 0 1-5-5v8",key:"sz5oeg"}],["path",{d:"M9 20H4a2 2 0 0 1-2-2V5a2 2 0 0 1 2-2h3.9a2 2 0 0 1 1.69.9l.81 1.2a2 2 0 0 0 1.67.9H20a2 2 0 0 1 2 2v5",key:"1w6njk"}],["circle",{cx:"13",cy:"12",r:"2",key:"1j92g6"}],["circle",{cx:"20",cy:"19",r:"2",key:"1obnsp"}]],lu=lt("folder-git-2",qw);/**
278
- * @license lucide-react v1.7.0 - ISC
279
- *
280
- * This source code is licensed under the ISC license.
281
- * See the LICENSE file in the root directory of this source tree.
282
- */const Vw=[["path",{d:"M4 20h16a2 2 0 0 0 2-2V8a2 2 0 0 0-2-2h-7.93a2 2 0 0 1-1.66-.9l-.82-1.2A2 2 0 0 0 7.93 3H4a2 2 0 0 0-2 2v13c0 1.1.9 2 2 2Z",key:"1fr9dc"}],["circle",{cx:"12",cy:"13",r:"2",key:"1c1ljs"}],["path",{d:"M12 15v5",key:"11xva1"}]],Fm=lt("folder-root",Vw);/**
283
- * @license lucide-react v1.7.0 - ISC
284
- *
285
- * This source code is licensed under the ISC license.
286
- * See the LICENSE file in the root directory of this source tree.
287
- */const Ww=[["path",{d:"M20 20a2 2 0 0 0 2-2V8a2 2 0 0 0-2-2h-7.9a2 2 0 0 1-1.69-.9L9.6 3.9A2 2 0 0 0 7.93 3H4a2 2 0 0 0-2 2v13a2 2 0 0 0 2 2Z",key:"1kt360"}]],ws=lt("folder",Ww);/**
288
- * @license lucide-react v1.7.0 - ISC
289
- *
290
- * This source code is licensed under the ISC license.
291
- * See the LICENSE file in the root directory of this source tree.
292
- */const Gw=[["path",{d:"M10 20a1 1 0 0 0 .553.895l2 1A1 1 0 0 0 14 21v-7a2 2 0 0 1 .517-1.341L21.74 4.67A1 1 0 0 0 21 3H3a1 1 0 0 0-.742 1.67l7.225 7.989A2 2 0 0 1 10 14z",key:"sc7q7i"}]],Gl=lt("funnel",Gw);/**
293
- * @license lucide-react v1.7.0 - ISC
294
- *
295
- * This source code is licensed under the ISC license.
296
- * See the LICENSE file in the root directory of this source tree.
297
- */const Kw=[["path",{d:"M15 6a9 9 0 0 0-9 9V3",key:"1cii5b"}],["circle",{cx:"18",cy:"6",r:"3",key:"1h7g24"}],["circle",{cx:"6",cy:"18",r:"3",key:"fqmcym"}]],Is=lt("git-branch",Kw);/**
298
- * @license lucide-react v1.7.0 - ISC
299
- *
300
- * This source code is licensed under the ISC license.
301
- * See the LICENSE file in the root directory of this source tree.
302
- */const Jw=[["circle",{cx:"12",cy:"12",r:"3",key:"1v7zrd"}],["line",{x1:"3",x2:"9",y1:"12",y2:"12",key:"1dyftd"}],["line",{x1:"15",x2:"21",y1:"12",y2:"12",key:"oup4p8"}]],Sr=lt("git-commit-horizontal",Jw);/**
303
- * @license lucide-react v1.7.0 - ISC
304
- *
305
- * This source code is licensed under the ISC license.
306
- * See the LICENSE file in the root directory of this source tree.
307
- */const Yw=[["circle",{cx:"18",cy:"18",r:"3",key:"1xkwt0"}],["circle",{cx:"6",cy:"6",r:"3",key:"1lh9wr"}],["path",{d:"M6 21V9a9 9 0 0 0 9 9",key:"7kw0sc"}]],mb=lt("git-merge",Yw);/**
308
- * @license lucide-react v1.7.0 - ISC
309
- *
310
- * This source code is licensed under the ISC license.
311
- * See the LICENSE file in the root directory of this source tree.
312
- */const Qw=[["circle",{cx:"18",cy:"18",r:"3",key:"1xkwt0"}],["circle",{cx:"6",cy:"6",r:"3",key:"1lh9wr"}],["path",{d:"M13 6h3a2 2 0 0 1 2 2v7",key:"1yeb86"}],["line",{x1:"6",x2:"6",y1:"9",y2:"21",key:"rroup"}]],Qs=lt("git-pull-request",Qw);/**
313
- * @license lucide-react v1.7.0 - ISC
314
- *
315
- * This source code is licensed under the ISC license.
316
- * See the LICENSE file in the root directory of this source tree.
317
- */const Xw=[["circle",{cx:"12",cy:"12",r:"10",key:"1mglay"}],["path",{d:"M12 2a14.5 14.5 0 0 0 0 20 14.5 14.5 0 0 0 0-20",key:"13o1zl"}],["path",{d:"M2 12h20",key:"9i4pu4"}]],xc=lt("globe",Xw);/**
318
- * @license lucide-react v1.7.0 - ISC
319
- *
320
- * This source code is licensed under the ISC license.
321
- * See the LICENSE file in the root directory of this source tree.
322
- */const Zw=[["rect",{width:"18",height:"18",x:"3",y:"3",rx:"2",key:"afitv7"}],["path",{d:"M3 9h18",key:"1pudct"}],["path",{d:"M3 15h18",key:"5xshup"}],["path",{d:"M9 3v18",key:"fh3hqa"}],["path",{d:"M15 3v18",key:"14nvp0"}]],vc=lt("grid-3x3",Zw);/**
323
- * @license lucide-react v1.7.0 - ISC
324
- *
325
- * This source code is licensed under the ISC license.
326
- * See the LICENSE file in the root directory of this source tree.
327
- */const ek=[["circle",{cx:"9",cy:"12",r:"1",key:"1vctgf"}],["circle",{cx:"9",cy:"5",r:"1",key:"hp0tcf"}],["circle",{cx:"9",cy:"19",r:"1",key:"fkjjf6"}],["circle",{cx:"15",cy:"12",r:"1",key:"1tmaij"}],["circle",{cx:"15",cy:"5",r:"1",key:"19l28e"}],["circle",{cx:"15",cy:"19",r:"1",key:"f4zoj3"}]],yc=lt("grip-vertical",ek);/**
328
- * @license lucide-react v1.7.0 - ISC
329
- *
330
- * This source code is licensed under the ISC license.
331
- * See the LICENSE file in the root directory of this source tree.
332
- */const tk=[["path",{d:"M10 16h.01",key:"1bzywj"}],["path",{d:"M2.212 11.577a2 2 0 0 0-.212.896V18a2 2 0 0 0 2 2h16a2 2 0 0 0 2-2v-5.527a2 2 0 0 0-.212-.896L18.55 5.11A2 2 0 0 0 16.76 4H7.24a2 2 0 0 0-1.79 1.11z",key:"18tbho"}],["path",{d:"M21.946 12.013H2.054",key:"zqlbp7"}],["path",{d:"M6 16h.01",key:"1pmjb7"}]],nk=lt("hard-drive",tk);/**
333
- * @license lucide-react v1.7.0 - ISC
334
- *
335
- * This source code is licensed under the ISC license.
336
- * See the LICENSE file in the root directory of this source tree.
337
- */const sk=[["path",{d:"M2 9.5a5.5 5.5 0 0 1 9.591-3.676.56.56 0 0 0 .818 0A5.49 5.49 0 0 1 22 9.5c0 2.29-1.5 4-3 5.5l-5.492 5.313a2 2 0 0 1-3 .019L5 15c-1.5-1.5-3-3.2-3-5.5",key:"mvr1a0"}]],ik=lt("heart",sk);/**
338
- * @license lucide-react v1.7.0 - ISC
339
- *
340
- * This source code is licensed under the ISC license.
341
- * See the LICENSE file in the root directory of this source tree.
342
- */const ak=[["path",{d:"M3 12a9 9 0 1 0 9-9 9.75 9.75 0 0 0-6.74 2.74L3 8",key:"1357e3"}],["path",{d:"M3 3v5h5",key:"1xhq8a"}],["path",{d:"M12 7v5l4 2",key:"1fdv2h"}]],Oa=lt("history",ak);/**
343
- * @license lucide-react v1.7.0 - ISC
344
- *
345
- * This source code is licensed under the ISC license.
346
- * See the LICENSE file in the root directory of this source tree.
347
- */const rk=[["polyline",{points:"22 12 16 12 14 15 10 15 8 12 2 12",key:"o97t9d"}],["path",{d:"M5.45 5.11 2 12v6a2 2 0 0 0 2 2h16a2 2 0 0 0 2-2v-6l-3.45-6.89A2 2 0 0 0 16.76 4H7.24a2 2 0 0 0-1.79 1.11z",key:"oot6mr"}]],ma=lt("inbox",rk);/**
348
- * @license lucide-react v1.7.0 - ISC
349
- *
350
- * This source code is licensed under the ISC license.
351
- * See the LICENSE file in the root directory of this source tree.
352
- */const ok=[["path",{d:"m15.5 7.5 2.3 2.3a1 1 0 0 0 1.4 0l2.1-2.1a1 1 0 0 0 0-1.4L19 4",key:"g0fldk"}],["path",{d:"m21 2-9.6 9.6",key:"1j0ho8"}],["circle",{cx:"7.5",cy:"15.5",r:"5.5",key:"yqb3hr"}]],hb=lt("key",ok);/**
353
- * @license lucide-react v1.7.0 - ISC
354
- *
355
- * This source code is licensed under the ISC license.
356
- * See the LICENSE file in the root directory of this source tree.
357
- */const lk=[["path",{d:"M10 8h.01",key:"1r9ogq"}],["path",{d:"M12 12h.01",key:"1mp3jc"}],["path",{d:"M14 8h.01",key:"1primd"}],["path",{d:"M16 12h.01",key:"1l6xoz"}],["path",{d:"M18 8h.01",key:"emo2bl"}],["path",{d:"M6 8h.01",key:"x9i8wu"}],["path",{d:"M7 16h10",key:"wp8him"}],["path",{d:"M8 12h.01",key:"czm47f"}],["rect",{width:"20",height:"16",x:"2",y:"4",rx:"2",key:"18n3k1"}]],ck=lt("keyboard",lk);/**
358
- * @license lucide-react v1.7.0 - ISC
359
- *
360
- * This source code is licensed under the ISC license.
361
- * See the LICENSE file in the root directory of this source tree.
362
- */const dk=[["path",{d:"M12.83 2.18a2 2 0 0 0-1.66 0L2.6 6.08a1 1 0 0 0 0 1.83l8.58 3.91a2 2 0 0 0 1.66 0l8.58-3.9a1 1 0 0 0 0-1.83z",key:"zw3jo"}],["path",{d:"M2 12a1 1 0 0 0 .58.91l8.6 3.91a2 2 0 0 0 1.65 0l8.58-3.9A1 1 0 0 0 22 12",key:"1wduqc"}],["path",{d:"M2 17a1 1 0 0 0 .58.91l8.6 3.91a2 2 0 0 0 1.65 0l8.58-3.9A1 1 0 0 0 22 17",key:"kqbvx6"}]],Fa=lt("layers",dk);/**
363
- * @license lucide-react v1.7.0 - ISC
364
- *
365
- * This source code is licensed under the ISC license.
366
- * See the LICENSE file in the root directory of this source tree.
367
- */const uk=[["rect",{width:"7",height:"7",x:"3",y:"3",rx:"1",key:"1g98yp"}],["rect",{width:"7",height:"7",x:"14",y:"3",rx:"1",key:"6d4xhi"}],["rect",{width:"7",height:"7",x:"14",y:"14",rx:"1",key:"nxv5o0"}],["rect",{width:"7",height:"7",x:"3",y:"14",rx:"1",key:"1bb6yr"}]],va=lt("layout-grid",uk);/**
368
- * @license lucide-react v1.7.0 - ISC
369
- *
370
- * This source code is licensed under the ISC license.
371
- * See the LICENSE file in the root directory of this source tree.
372
- */const mk=[["path",{d:"M15 14c.2-1 .7-1.7 1.5-2.5 1-.9 1.5-2.2 1.5-3.5A6 6 0 0 0 6 8c0 1 .2 2.2 1.5 3.5.7.7 1.3 1.5 1.5 2.5",key:"1gvzjb"}],["path",{d:"M9 18h6",key:"x1upvd"}],["path",{d:"M10 22h4",key:"ceow96"}]],Di=lt("lightbulb",mk);/**
373
- * @license lucide-react v1.7.0 - ISC
374
- *
375
- * This source code is licensed under the ISC license.
376
- * See the LICENSE file in the root directory of this source tree.
377
- */const hk=[["path",{d:"M10 13a5 5 0 0 0 7.54.54l3-3a5 5 0 0 0-7.07-7.07l-1.72 1.71",key:"1cjeqo"}],["path",{d:"M14 11a5 5 0 0 0-7.54-.54l-3 3a5 5 0 0 0 7.07 7.07l1.71-1.71",key:"19qd67"}]],Cr=lt("link",hk);/**
378
- * @license lucide-react v1.7.0 - ISC
379
- *
380
- * This source code is licensed under the ISC license.
381
- * See the LICENSE file in the root directory of this source tree.
382
- */const pk=[["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"}],["path",{d:"m3 7 2 2 4-4",key:"1obspn"}]],fk=lt("list-checks",pk);/**
383
- * @license lucide-react v1.7.0 - ISC
384
- *
385
- * This source code is licensed under the ISC license.
386
- * See the LICENSE file in the root directory of this source tree.
387
- */const gk=[["path",{d:"M11 5h10",key:"1cz7ny"}],["path",{d:"M11 12h10",key:"1438ji"}],["path",{d:"M11 19h10",key:"11t30w"}],["path",{d:"M4 4h1v5",key:"10yrso"}],["path",{d:"M4 9h2",key:"r1h2o0"}],["path",{d:"M6.5 20H3.4c0-1 2.6-1.925 2.6-3.5a1.5 1.5 0 0 0-2.6-1.02",key:"xtkcd5"}]],zm=lt("list-ordered",gk);/**
388
- * @license lucide-react v1.7.0 - ISC
389
- *
390
- * This source code is licensed under the ISC license.
391
- * See the LICENSE file in the root directory of this source tree.
392
- */const bk=[["path",{d:"M16 5H3",key:"m91uny"}],["path",{d:"M11 12H3",key:"51ecnj"}],["path",{d:"M16 19H3",key:"zzsher"}],["path",{d:"M18 9v6",key:"1twb98"}],["path",{d:"M21 12h-6",key:"bt1uis"}]],xk=lt("list-plus",bk);/**
393
- * @license lucide-react v1.7.0 - ISC
394
- *
395
- * This source code is licensed under the ISC license.
396
- * See the LICENSE file in the root directory of this source tree.
397
- */const vk=[["path",{d:"M8 5h13",key:"1pao27"}],["path",{d:"M13 12h8",key:"h98zly"}],["path",{d:"M13 19h8",key:"c3s6r1"}],["path",{d:"M3 10a2 2 0 0 0 2 2h3",key:"1npucw"}],["path",{d:"M3 5v12a2 2 0 0 0 2 2h3",key:"x1gjn2"}]],wc=lt("list-tree",vk);/**
398
- * @license lucide-react v1.7.0 - ISC
399
- *
400
- * This source code is licensed under the ISC license.
401
- * See the LICENSE file in the root directory of this source tree.
402
- */const yk=[["path",{d:"M3 5h.01",key:"18ugdj"}],["path",{d:"M3 12h.01",key:"nlz23k"}],["path",{d:"M3 19h.01",key:"noohij"}],["path",{d:"M8 5h13",key:"1pao27"}],["path",{d:"M8 12h13",key:"1za7za"}],["path",{d:"M8 19h13",key:"m83p4d"}]],cu=lt("list",yk);/**
403
- * @license lucide-react v1.7.0 - ISC
404
- *
405
- * This source code is licensed under the ISC license.
406
- * See the LICENSE file in the root directory of this source tree.
407
- */const wk=[["path",{d:"M21 12a9 9 0 1 1-6.219-8.56",key:"13zald"}]],St=lt("loader-circle",wk);/**
408
- * @license lucide-react v1.7.0 - ISC
409
- *
410
- * This source code is licensed under the ISC license.
411
- * See the LICENSE file in the root directory of this source tree.
412
- */const kk=[["rect",{width:"18",height:"11",x:"3",y:"11",rx:"2",ry:"2",key:"1w4ew1"}],["path",{d:"M7 11V7a5 5 0 0 1 10 0v4",key:"fwvmzm"}]],kc=lt("lock",kk);/**
413
- * @license lucide-react v1.7.0 - ISC
414
- *
415
- * This source code is licensed under the ISC license.
416
- * See the LICENSE file in the root directory of this source tree.
417
- */const jk=[["path",{d:"m22 7-8.991 5.727a2 2 0 0 1-2.009 0L2 7",key:"132q7q"}],["rect",{x:"2",y:"4",width:"20",height:"16",rx:"2",key:"izxlao"}]],za=lt("mail",jk);/**
418
- * @license lucide-react v1.7.0 - ISC
419
- *
420
- * This source code is licensed under the ISC license.
421
- * See the LICENSE file in the root directory of this source tree.
422
- */const Nk=[["path",{d:"M14.106 5.553a2 2 0 0 0 1.788 0l3.659-1.83A1 1 0 0 1 21 4.619v12.764a1 1 0 0 1-.553.894l-4.553 2.277a2 2 0 0 1-1.788 0l-4.212-2.106a2 2 0 0 0-1.788 0l-3.659 1.83A1 1 0 0 1 3 19.381V6.618a1 1 0 0 1 .553-.894l4.553-2.277a2 2 0 0 1 1.788 0z",key:"169xi5"}],["path",{d:"M15 5.764v15",key:"1pn4in"}],["path",{d:"M9 3.236v15",key:"1uimfh"}]],Sk=lt("map",Nk);/**
423
- * @license lucide-react v1.7.0 - ISC
424
- *
425
- * This source code is licensed under the ISC license.
426
- * See the LICENSE file in the root directory of this source tree.
427
- */const Ck=[["path",{d:"M15 3h6v6",key:"1q9fwt"}],["path",{d:"m21 3-7 7",key:"1l2asr"}],["path",{d:"m3 21 7-7",key:"tjx5ai"}],["path",{d:"M9 21H3v-6",key:"wtvkvv"}]],jc=lt("maximize-2",Ck);/**
428
- * @license lucide-react v1.7.0 - ISC
429
- *
430
- * This source code is licensed under the ISC license.
431
- * See the LICENSE file in the root directory of this source tree.
432
- */const Ek=[["path",{d:"M22 17a2 2 0 0 1-2 2H6.828a2 2 0 0 0-1.414.586l-2.202 2.202A.71.71 0 0 1 2 21.286V5a2 2 0 0 1 2-2h16a2 2 0 0 1 2 2z",key:"18887p"}],["path",{d:"M12 8v6",key:"1ib9pf"}],["path",{d:"M9 11h6",key:"1fldmi"}]],_k=lt("message-square-plus",Ek);/**
433
- * @license lucide-react v1.7.0 - ISC
434
- *
435
- * This source code is licensed under the ISC license.
436
- * See the LICENSE file in the root directory of this source tree.
437
- */const Mk=[["path",{d:"M22 17a2 2 0 0 1-2 2H6.828a2 2 0 0 0-1.414.586l-2.202 2.202A.71.71 0 0 1 2 21.286V5a2 2 0 0 1 2-2h16a2 2 0 0 1 2 2z",key:"18887p"}]],Ki=lt("message-square",Mk);/**
438
- * @license lucide-react v1.7.0 - ISC
439
- *
440
- * This source code is licensed under the ISC license.
441
- * See the LICENSE file in the root directory of this source tree.
442
- */const Ak=[["path",{d:"m14 10 7-7",key:"oa77jy"}],["path",{d:"M20 10h-6V4",key:"mjg0md"}],["path",{d:"m3 21 7-7",key:"tjx5ai"}],["path",{d:"M4 14h6v6",key:"rmj7iw"}]],Vo=lt("minimize-2",Ak);/**
443
- * @license lucide-react v1.7.0 - ISC
444
- *
445
- * This source code is licensed under the ISC license.
446
- * See the LICENSE file in the root directory of this source tree.
447
- */const Rk=[["path",{d:"M5 12h14",key:"1ays0h"}]],Ik=lt("minus",Rk);/**
448
- * @license lucide-react v1.7.0 - ISC
449
- *
450
- * This source code is licensed under the ISC license.
451
- * See the LICENSE file in the root directory of this source tree.
452
- */const Tk=[["rect",{width:"20",height:"14",x:"2",y:"3",rx:"2",key:"48i651"}],["line",{x1:"8",x2:"16",y1:"21",y2:"21",key:"1svkeh"}],["line",{x1:"12",x2:"12",y1:"17",y2:"21",key:"vw1qmm"}]],Er=lt("monitor",Tk);/**
453
- * @license lucide-react v1.7.0 - ISC
454
- *
455
- * This source code is licensed under the ISC license.
456
- * See the LICENSE file in the root directory of this source tree.
457
- */const Pk=[["path",{d:"M12 2v20",key:"t6zp3m"}],["path",{d:"m15 19-3 3-3-3",key:"11eu04"}],["path",{d:"m19 9 3 3-3 3",key:"1mg7y2"}],["path",{d:"M2 12h20",key:"9i4pu4"}],["path",{d:"m5 9-3 3 3 3",key:"j64kie"}],["path",{d:"m9 5 3-3 3 3",key:"l8vdw6"}]],$k=lt("move",Pk);/**
458
- * @license lucide-react v1.7.0 - ISC
459
- *
460
- * This source code is licensed under the ISC license.
461
- * See the LICENSE file in the root directory of this source tree.
462
- */const Dk=[["rect",{x:"16",y:"16",width:"6",height:"6",rx:"1",key:"4q2zg0"}],["rect",{x:"2",y:"16",width:"6",height:"6",rx:"1",key:"8cvhb9"}],["rect",{x:"9",y:"2",width:"6",height:"6",rx:"1",key:"1egb70"}],["path",{d:"M5 16v-3a1 1 0 0 1 1-1h12a1 1 0 0 1 1 1v3",key:"1jsf9p"}],["path",{d:"M12 12V8",key:"2874zd"}]],Lk=lt("network",Dk);/**
463
- * @license lucide-react v1.7.0 - ISC
464
- *
465
- * This source code is licensed under the ISC license.
466
- * See the LICENSE file in the root directory of this source tree.
467
- */const Ok=[["path",{d:"M11 21.73a2 2 0 0 0 2 0l7-4A2 2 0 0 0 21 16V8a2 2 0 0 0-1-1.73l-7-4a2 2 0 0 0-2 0l-7 4A2 2 0 0 0 3 8v8a2 2 0 0 0 1 1.73z",key:"1a0edw"}],["path",{d:"M12 22V12",key:"d0xqtd"}],["polyline",{points:"3.29 7 12 12 20.71 7",key:"ousv84"}],["path",{d:"m7.5 4.27 9 5.15",key:"1c824w"}]],du=lt("package",Ok);/**
468
- * @license lucide-react v1.7.0 - ISC
469
- *
470
- * This source code is licensed under the ISC license.
471
- * See the LICENSE file in the root directory of this source tree.
472
- */const Fk=[["path",{d:"m16 6-8.414 8.586a2 2 0 0 0 2.829 2.829l8.414-8.586a4 4 0 1 0-5.657-5.657l-8.379 8.551a6 6 0 1 0 8.485 8.485l8.379-8.551",key:"1miecu"}]],pb=lt("paperclip",Fk);/**
473
- * @license lucide-react v1.7.0 - ISC
474
- *
475
- * This source code is licensed under the ISC license.
476
- * See the LICENSE file in the root directory of this source tree.
477
- */const zk=[["rect",{x:"14",y:"3",width:"5",height:"18",rx:"1",key:"kaeet6"}],["rect",{x:"5",y:"3",width:"5",height:"18",rx:"1",key:"1wsw3u"}]],di=lt("pause",zk);/**
478
- * @license lucide-react v1.7.0 - ISC
479
- *
480
- * This source code is licensed under the ISC license.
481
- * See the LICENSE file in the root directory of this source tree.
482
- */const Bk=[["path",{d:"M21.174 6.812a1 1 0 0 0-3.986-3.987L3.842 16.174a2 2 0 0 0-.5.83l-1.321 4.352a.5.5 0 0 0 .623.622l4.353-1.32a2 2 0 0 0 .83-.497z",key:"1a8usu"}],["path",{d:"m15 5 4 4",key:"1mk7zo"}]],Os=lt("pencil",Bk);/**
483
- * @license lucide-react v1.7.0 - ISC
484
- *
485
- * This source code is licensed under the ISC license.
486
- * See the LICENSE file in the root directory of this source tree.
487
- */const Uk=[["path",{d:"M5 5a2 2 0 0 1 3.008-1.728l11.997 6.998a2 2 0 0 1 .003 3.458l-12 7A2 2 0 0 1 5 19z",key:"10ikf1"}]],is=lt("play",Uk);/**
488
- * @license lucide-react v1.7.0 - ISC
489
- *
490
- * This source code is licensed under the ISC license.
491
- * See the LICENSE file in the root directory of this source tree.
492
- */const Hk=[["path",{d:"M5 12h14",key:"1ays0h"}],["path",{d:"M12 5v14",key:"s699le"}]],Tn=lt("plus",Hk);/**
493
- * @license lucide-react v1.7.0 - ISC
494
- *
495
- * This source code is licensed under the ISC license.
496
- * See the LICENSE file in the root directory of this source tree.
497
- */const qk=[["path",{d:"M15.39 4.39a1 1 0 0 0 1.68-.474 2.5 2.5 0 1 1 3.014 3.015 1 1 0 0 0-.474 1.68l1.683 1.682a2.414 2.414 0 0 1 0 3.414L19.61 15.39a1 1 0 0 1-1.68-.474 2.5 2.5 0 1 0-3.014 3.015 1 1 0 0 1 .474 1.68l-1.683 1.682a2.414 2.414 0 0 1-3.414 0L8.61 19.61a1 1 0 0 0-1.68.474 2.5 2.5 0 1 1-3.014-3.015 1 1 0 0 0 .474-1.68l-1.683-1.682a2.414 2.414 0 0 1 0-3.414L4.39 8.61a1 1 0 0 1 1.68.474 2.5 2.5 0 1 0 3.014-3.015 1 1 0 0 1-.474-1.68l1.683-1.682a2.414 2.414 0 0 1 3.414 0z",key:"w46dr5"}]],Vk=lt("puzzle",qk);/**
498
- * @license lucide-react v1.7.0 - ISC
499
- *
500
- * This source code is licensed under the ISC license.
501
- * See the LICENSE file in the root directory of this source tree.
502
- */const Wk=[["path",{d:"M16.247 7.761a6 6 0 0 1 0 8.478",key:"1fwjs5"}],["path",{d:"M19.075 4.933a10 10 0 0 1 0 14.134",key:"ehdyv1"}],["path",{d:"M4.925 19.067a10 10 0 0 1 0-14.134",key:"1q22gi"}],["path",{d:"M7.753 16.239a6 6 0 0 1 0-8.478",key:"r2q7qm"}],["circle",{cx:"12",cy:"12",r:"2",key:"1c9p78"}]],fb=lt("radio",Wk);/**
503
- * @license lucide-react v1.7.0 - ISC
504
- *
505
- * This source code is licensed under the ISC license.
506
- * See the LICENSE file in the root directory of this source tree.
507
- */const Gk=[["path",{d:"M3 12a9 9 0 0 1 9-9 9.75 9.75 0 0 1 6.74 2.74L21 8",key:"v9h5vc"}],["path",{d:"M21 3v5h-5",key:"1q7to0"}],["path",{d:"M21 12a9 9 0 0 1-9 9 9.75 9.75 0 0 1-6.74-2.74L3 16",key:"3uifl3"}],["path",{d:"M8 16H3v5",key:"1cv678"}]],us=lt("refresh-cw",Gk);/**
508
- * @license lucide-react v1.7.0 - ISC
509
- *
510
- * This source code is licensed under the ISC license.
511
- * See the LICENSE file in the root directory of this source tree.
512
- */const Kk=[["path",{d:"M12 15v5s3.03-.55 4-2c1.08-1.62 0-5 0-5",key:"qeys4"}],["path",{d:"M4.5 16.5c-1.5 1.26-2 5-2 5s3.74-.5 5-2c.71-.84.7-2.13-.09-2.91a2.18 2.18 0 0 0-2.91-.09",key:"u4xsad"}],["path",{d:"M9 12a22 22 0 0 1 2-3.95A12.88 12.88 0 0 1 22 2c0 2.72-.78 7.5-6 11a22.4 22.4 0 0 1-4 2z",key:"676m9"}],["path",{d:"M9 12H4s.55-3.03 2-4c1.62-1.08 5 .05 5 .05",key:"92ym6u"}]],Bm=lt("rocket",Kk);/**
513
- * @license lucide-react v1.7.0 - ISC
514
- *
515
- * This source code is licensed under the ISC license.
516
- * See the LICENSE file in the root directory of this source tree.
517
- */const Jk=[["path",{d:"M3 12a9 9 0 1 0 9-9 9.75 9.75 0 0 0-6.74 2.74L3 8",key:"1357e3"}],["path",{d:"M3 3v5h5",key:"1xhq8a"}]],Yk=lt("rotate-ccw",Jk);/**
518
- * @license lucide-react v1.7.0 - ISC
519
- *
520
- * This source code is licensed under the ISC license.
521
- * See the LICENSE file in the root directory of this source tree.
522
- */const Qk=[["path",{d:"M21 12a9 9 0 1 1-9-9c2.52 0 4.93 1 6.74 2.74L21 8",key:"1p45f6"}],["path",{d:"M21 3v5h-5",key:"1q7to0"}]],Xk=lt("rotate-cw",Qk);/**
523
- * @license lucide-react v1.7.0 - ISC
524
- *
525
- * This source code is licensed under the ISC license.
526
- * See the LICENSE file in the root directory of this source tree.
527
- */const Zk=[["path",{d:"M15.2 3a2 2 0 0 1 1.4.6l3.8 3.8a2 2 0 0 1 .6 1.4V19a2 2 0 0 1-2 2H5a2 2 0 0 1-2-2V5a2 2 0 0 1 2-2z",key:"1c8476"}],["path",{d:"M17 21v-7a1 1 0 0 0-1-1H8a1 1 0 0 0-1 1v7",key:"1ydtos"}],["path",{d:"M7 3v4a1 1 0 0 0 1 1h7",key:"t51u73"}]],gb=lt("save",Zk);/**
528
- * @license lucide-react v1.7.0 - ISC
529
- *
530
- * This source code is licensed under the ISC license.
531
- * See the LICENSE file in the root directory of this source tree.
532
- */const ej=[["path",{d:"m21 21-4.34-4.34",key:"14j7rj"}],["circle",{cx:"11",cy:"11",r:"8",key:"4ej97u"}]],Gi=lt("search",ej);/**
533
- * @license lucide-react v1.7.0 - ISC
534
- *
535
- * This source code is licensed under the ISC license.
536
- * See the LICENSE file in the root directory of this source tree.
537
- */const tj=[["path",{d:"M14.536 21.686a.5.5 0 0 0 .937-.024l6.5-19a.496.496 0 0 0-.635-.635l-19 6.5a.5.5 0 0 0-.024.937l7.93 3.18a2 2 0 0 1 1.112 1.11z",key:"1ffxy3"}],["path",{d:"m21.854 2.147-10.94 10.939",key:"12cjpa"}]],Da=lt("send",tj);/**
538
- * @license lucide-react v1.7.0 - ISC
539
- *
540
- * This source code is licensed under the ISC license.
541
- * See the LICENSE file in the root directory of this source tree.
542
- */const nj=[["rect",{width:"20",height:"8",x:"2",y:"2",rx:"2",ry:"2",key:"ngkwjq"}],["rect",{width:"20",height:"8",x:"2",y:"14",rx:"2",ry:"2",key:"iecqi9"}],["line",{x1:"6",x2:"6.01",y1:"6",y2:"6",key:"16zg32"}],["line",{x1:"6",x2:"6.01",y1:"18",y2:"18",key:"nzw8ys"}]],$o=lt("server",nj);/**
543
- * @license lucide-react v1.7.0 - ISC
544
- *
545
- * This source code is licensed under the ISC license.
546
- * See the LICENSE file in the root directory of this source tree.
547
- */const sj=[["path",{d:"M9.671 4.136a2.34 2.34 0 0 1 4.659 0 2.34 2.34 0 0 0 3.319 1.915 2.34 2.34 0 0 1 2.33 4.033 2.34 2.34 0 0 0 0 3.831 2.34 2.34 0 0 1-2.33 4.033 2.34 2.34 0 0 0-3.319 1.915 2.34 2.34 0 0 1-4.659 0 2.34 2.34 0 0 0-3.32-1.915 2.34 2.34 0 0 1-2.33-4.033 2.34 2.34 0 0 0 0-3.831A2.34 2.34 0 0 1 6.35 6.051a2.34 2.34 0 0 0 3.319-1.915",key:"1i5ecw"}],["circle",{cx:"12",cy:"12",r:"3",key:"1v7zrd"}]],_o=lt("settings",sj);/**
548
- * @license lucide-react v1.7.0 - ISC
549
- *
550
- * This source code is licensed under the ISC license.
551
- * See the LICENSE file in the root directory of this source tree.
552
- */const ij=[["path",{d:"M20 13c0 5-3.5 7.5-7.66 8.95a1 1 0 0 1-.67-.01C7.5 20.5 4 18 4 13V6a1 1 0 0 1 1-1c2 0 4.5-1.2 6.24-2.72a1.17 1.17 0 0 1 1.52 0C14.51 3.81 17 5 19 5a1 1 0 0 1 1 1z",key:"oel41y"}],["path",{d:"M12 8v4",key:"1got3b"}],["path",{d:"M12 16h.01",key:"1drbdi"}]],aj=lt("shield-alert",ij);/**
553
- * @license lucide-react v1.7.0 - ISC
554
- *
555
- * This source code is licensed under the ISC license.
556
- * See the LICENSE file in the root directory of this source tree.
557
- */const rj=[["path",{d:"M20 13c0 5-3.5 7.5-7.66 8.95a1 1 0 0 1-.67-.01C7.5 20.5 4 18 4 13V6a1 1 0 0 1 1-1c2 0 4.5-1.2 6.24-2.72a1.17 1.17 0 0 1 1.52 0C14.51 3.81 17 5 19 5a1 1 0 0 1 1 1z",key:"oel41y"}]],oj=lt("shield",rj);/**
558
- * @license lucide-react v1.7.0 - ISC
559
- *
560
- * This source code is licensed under the ISC license.
561
- * See the LICENSE file in the root directory of this source tree.
562
- */const lj=[["path",{d:"m12.5 17-.5-1-.5 1h1z",key:"3me087"}],["path",{d:"M15 22a1 1 0 0 0 1-1v-1a2 2 0 0 0 1.56-3.25 8 8 0 1 0-11.12 0A2 2 0 0 0 8 20v1a1 1 0 0 0 1 1z",key:"1o5pge"}],["circle",{cx:"15",cy:"12",r:"1",key:"1tmaij"}],["circle",{cx:"9",cy:"12",r:"1",key:"1vctgf"}]],cj=lt("skull",lj);/**
563
- * @license lucide-react v1.7.0 - ISC
564
- *
565
- * This source code is licensed under the ISC license.
566
- * See the LICENSE file in the root directory of this source tree.
567
- */const dj=[["path",{d:"M11.017 2.814a1 1 0 0 1 1.966 0l1.051 5.558a2 2 0 0 0 1.594 1.594l5.558 1.051a1 1 0 0 1 0 1.966l-5.558 1.051a2 2 0 0 0-1.594 1.594l-1.051 5.558a1 1 0 0 1-1.966 0l-1.051-5.558a2 2 0 0 0-1.594-1.594l-5.558-1.051a1 1 0 0 1 0-1.966l5.558-1.051a2 2 0 0 0 1.594-1.594z",key:"1s2grr"}],["path",{d:"M20 2v4",key:"1rf3ol"}],["path",{d:"M22 4h-4",key:"gwowj6"}],["circle",{cx:"4",cy:"20",r:"2",key:"6kqj1y"}]],cs=lt("sparkles",dj);/**
568
- * @license lucide-react v1.7.0 - ISC
569
- *
570
- * This source code is licensed under the ISC license.
571
- * See the LICENSE file in the root directory of this source tree.
572
- */const uj=[["path",{d:"M21 10.656V19a2 2 0 0 1-2 2H5a2 2 0 0 1-2-2V5a2 2 0 0 1 2-2h12.344",key:"2acyp4"}],["path",{d:"m9 11 3 3L22 4",key:"1pflzl"}]],Vu=lt("square-check-big",uj);/**
573
- * @license lucide-react v1.7.0 - ISC
574
- *
575
- * This source code is licensed under the ISC license.
576
- * See the LICENSE file in the root directory of this source tree.
577
- */const mj=[["rect",{width:"18",height:"18",x:"3",y:"3",rx:"2",key:"afitv7"}]],Pi=lt("square",mj);/**
578
- * @license lucide-react v1.7.0 - ISC
579
- *
580
- * This source code is licensed under the ISC license.
581
- * See the LICENSE file in the root directory of this source tree.
582
- */const hj=[["circle",{cx:"12",cy:"12",r:"10",key:"1mglay"}],["circle",{cx:"12",cy:"12",r:"6",key:"1vlfrh"}],["circle",{cx:"12",cy:"12",r:"2",key:"1c9p78"}]],js=lt("target",hj);/**
583
- * @license lucide-react v1.7.0 - ISC
584
- *
585
- * This source code is licensed under the ISC license.
586
- * See the LICENSE file in the root directory of this source tree.
587
- */const pj=[["path",{d:"M12 19h8",key:"baeox8"}],["path",{d:"m4 17 6-6-6-6",key:"1yngyt"}]],Ji=lt("terminal",pj);/**
588
- * @license lucide-react v1.7.0 - ISC
589
- *
590
- * This source code is licensed under the ISC license.
591
- * See the LICENSE file in the root directory of this source tree.
592
- */const fj=[["path",{d:"m16 16-3 3 3 3",key:"117b85"}],["path",{d:"M3 12h14.5a1 1 0 0 1 0 7H13",key:"18xa6z"}],["path",{d:"M3 19h6",key:"1ygdsz"}],["path",{d:"M3 5h18",key:"1u36vt"}]],Kl=lt("text-wrap",fj);/**
593
- * @license lucide-react v1.7.0 - ISC
594
- *
595
- * This source code is licensed under the ISC license.
596
- * See the LICENSE file in the root directory of this source tree.
597
- */const gj=[["path",{d:"M10 11v6",key:"nco0om"}],["path",{d:"M14 11v6",key:"outv1u"}],["path",{d:"M19 6v14a2 2 0 0 1-2 2H7a2 2 0 0 1-2-2V6",key:"miytrc"}],["path",{d:"M3 6h18",key:"d0wm0j"}],["path",{d:"M8 6V4a2 2 0 0 1 2-2h4a2 2 0 0 1 2 2v2",key:"e791ji"}]],In=lt("trash-2",gj);/**
598
- * @license lucide-react v1.7.0 - ISC
599
- *
600
- * This source code is licensed under the ISC license.
601
- * See the LICENSE file in the root directory of this source tree.
602
- */const bj=[["path",{d:"M16 7h6v6",key:"box55l"}],["path",{d:"m22 7-8.5 8.5-5-5L2 17",key:"1t1m79"}]],xj=lt("trending-up",bj);/**
603
- * @license lucide-react v1.7.0 - ISC
604
- *
605
- * This source code is licensed under the ISC license.
606
- * See the LICENSE file in the root directory of this source tree.
607
- */const vj=[["path",{d:"m21.73 18-8-14a2 2 0 0 0-3.48 0l-8 14A2 2 0 0 0 4 21h16a2 2 0 0 0 1.73-3",key:"wmoenq"}],["path",{d:"M12 9v4",key:"juzpu7"}],["path",{d:"M12 17h.01",key:"p32p05"}]],Br=lt("triangle-alert",vj);/**
608
- * @license lucide-react v1.7.0 - ISC
609
- *
610
- * This source code is licensed under the ISC license.
611
- * See the LICENSE file in the root directory of this source tree.
612
- */const yj=[["path",{d:"m18.84 12.25 1.72-1.71h-.02a5.004 5.004 0 0 0-.12-7.07 5.006 5.006 0 0 0-6.95 0l-1.72 1.71",key:"yqzxt4"}],["path",{d:"m5.17 11.75-1.71 1.71a5.004 5.004 0 0 0 .12 7.07 5.006 5.006 0 0 0 6.95 0l1.71-1.71",key:"4qinb0"}],["line",{x1:"8",x2:"8",y1:"2",y2:"5",key:"1041cp"}],["line",{x1:"2",x2:"5",y1:"8",y2:"8",key:"14m1p5"}],["line",{x1:"16",x2:"16",y1:"19",y2:"22",key:"rzdirn"}],["line",{x1:"19",x2:"22",y1:"16",y2:"16",key:"ox905f"}]],Um=lt("unlink",yj);/**
613
- * @license lucide-react v1.7.0 - ISC
614
- *
615
- * This source code is licensed under the ISC license.
616
- * See the LICENSE file in the root directory of this source tree.
617
- */const wj=[["path",{d:"M19 21v-2a4 4 0 0 0-4-4H9a4 4 0 0 0-4 4v2",key:"975kel"}],["circle",{cx:"12",cy:"7",r:"4",key:"17ys0d"}]],Ra=lt("user",wj);/**
618
- * @license lucide-react v1.7.0 - ISC
619
- *
620
- * This source code is licensed under the ISC license.
621
- * See the LICENSE file in the root directory of this source tree.
622
- */const kj=[["path",{d:"M18 16.98h-5.99c-1.1 0-1.95.94-2.48 1.9A4 4 0 0 1 2 17c.01-.7.2-1.4.57-2",key:"q3hayz"}],["path",{d:"m6 17 3.13-5.78c.53-.97.1-2.18-.5-3.1a4 4 0 1 1 6.89-4.06",key:"1go1hn"}],["path",{d:"m12 6 3.13 5.73C15.66 12.7 16.9 13 18 13a4 4 0 0 1 0 8",key:"qlwsc0"}]],bb=lt("webhook",kj);/**
623
- * @license lucide-react v1.7.0 - ISC
624
- *
625
- * This source code is licensed under the ISC license.
626
- * See the LICENSE file in the root directory of this source tree.
627
- */const jj=[["rect",{width:"8",height:"8",x:"3",y:"3",rx:"2",key:"by2w9f"}],["path",{d:"M7 11v4a2 2 0 0 0 2 2h4",key:"xkn7yn"}],["rect",{width:"8",height:"8",x:"13",y:"13",rx:"2",key:"1cgmvn"}]],Jl=lt("workflow",jj);/**
628
- * @license lucide-react v1.7.0 - ISC
629
- *
630
- * This source code is licensed under the ISC license.
631
- * See the LICENSE file in the root directory of this source tree.
632
- */const Nj=[["path",{d:"M14.7 6.3a1 1 0 0 0 0 1.4l1.6 1.6a1 1 0 0 0 1.4 0l3.106-3.105c.32-.322.863-.22.983.218a6 6 0 0 1-8.259 7.057l-7.91 7.91a1 1 0 0 1-2.999-3l7.91-7.91a6 6 0 0 1 7.057-8.259c.438.12.54.662.219.984z",key:"1ngwbx"}]],Hm=lt("wrench",Nj);/**
633
- * @license lucide-react v1.7.0 - ISC
634
- *
635
- * This source code is licensed under the ISC license.
636
- * See the LICENSE file in the root directory of this source tree.
637
- */const Sj=[["path",{d:"M18 6 6 18",key:"1bl5f8"}],["path",{d:"m6 6 12 12",key:"d8bk6v"}]],bn=lt("x",Sj);/**
638
- * @license lucide-react v1.7.0 - ISC
639
- *
640
- * This source code is licensed under the ISC license.
641
- * See the LICENSE file in the root directory of this source tree.
642
- */const Cj=[["path",{d:"M4 14a1 1 0 0 1-.78-1.63l9.9-10.2a.5.5 0 0 1 .86.46l-1.92 6.02A1 1 0 0 0 13 10h7a1 1 0 0 1 .78 1.63l-9.9 10.2a.5.5 0 0 1-.86-.46l1.92-6.02A1 1 0 0 0 11 14z",key:"1xq2db"}]],as=lt("zap",Cj),uu="fusion:version-reload",mu="fusion:version-update";let Wu=!0;function qc(e){Wu=e}function Ej(){try{if(sessionStorage.getItem(mu))return sessionStorage.removeItem(mu),!0}catch{}return!1}function Gu(e){if(sessionStorage.getItem(uu)){console.warn("[versionCheck] reload already attempted, suppressing",e);return}if(sessionStorage.setItem(uu,"1"),!Wu){console.info("[versionCheck] auto-reload disabled by setting, skipping reload:",e);return}console.info("[versionCheck] reloading:",e),window.location.reload()}function _j(e){const n=e instanceof Error?e.message:typeof e=="string"?e:"";return/Failed to fetch dynamically imported module|error loading dynamically imported module|Importing a module script failed|is not a valid JavaScript MIME type|ChunkLoadError|Unable to preload (?:CSS|module) for/i.test(n)}function Mj(e){return _j(e)?(Gu(`chunk load error: ${e?.message??e}`),!0):!1}async function Aj(){try{const e=await fetch("/version.json",{cache:"no-store",headers:{Accept:"application/json"}});if(!e.ok||!(e.headers.get("content-type")??"").includes("application/json"))return null;const s=await e.json();return typeof s.version=="string"?s.version:null}catch{return null}}async function Rj(){try{const e=new AbortController,n=setTimeout(()=>e.abort(),3e3),s=await fetch("/api/settings",{headers:{Accept:"application/json"},signal:e.signal});clearTimeout(n),s.ok&&(await s.json()).autoReloadOnVersionChange===!1&&(Wu=!1)}catch{}}const Ij=6e4;let qm=0,Vc=!1;async function Wc(){if(!(Vc||document.visibilityState!=="visible")&&!(Date.now()-qm<Ij)){qm=Date.now(),Vc=!0;try{const e=await Aj();if(e&&e!=="3afc08699-2a15a380"){try{sessionStorage.setItem(mu,"1")}catch{}Gu(`build version changed: 3afc08699-2a15a380 -> ${e}`)}}finally{Vc=!1}}}function Tj(){Rj(),window.setTimeout(()=>sessionStorage.removeItem(uu),5e3),document.addEventListener("visibilitychange",()=>{Wc()}),window.addEventListener("focus",()=>{Wc()}),window.setTimeout(()=>void Wc(),2e3)}class Wo extends i.Component{constructor(n){super(n),this.state={hasError:!1,error:null}}static getDerivedStateFromError(n){return{hasError:!0,error:n}}componentDidCatch(n,s){console.error("[ErrorBoundary]",n,s),!Mj(n)&&this.props.onError?.(n,s)}resetErrorBoundary=()=>{this.setState({hasError:!1,error:null})};render(){if(!this.state.hasError)return this.props.children;if(this.props.fallback)return this.props.fallback;const n=this.props.level??"page",a=n==="modal"?"This section encountered an error":"Something went wrong";return t.jsxs("div",{className:`error-boundary error-boundary--${n}`,children:[t.jsx("div",{className:"error-boundary__icon",children:t.jsx(Br,{size:40})}),t.jsx("div",{className:"error-boundary__title",children:a}),this.state.error&&t.jsx("pre",{className:"error-boundary__message",children:this.state.error.message}),t.jsxs("div",{className:"error-boundary__actions",children:[t.jsx("button",{className:"btn btn-primary",onClick:this.resetErrorBoundary,children:"Retry"}),t.jsx("button",{className:"btn",onClick:()=>window.location.reload(),children:"Reload page"})]})]})}}function Cs({children:e,onError:n}){return t.jsx(Wo,{level:"page",onError:n,children:e})}function Ia({children:e,onError:n}){return t.jsx(Wo,{level:"modal",onError:n,children:e})}function Pj({children:e,onError:n}){return t.jsx(Wo,{level:"root",onError:n,children:e})}const $j="modulepreload",Dj=function(e){return"/"+e},Vm={},Sn=function(n,s,a){let r=Promise.resolve();if(s&&s.length>0){let l=function(u){return Promise.all(u.map(h=>Promise.resolve(h).then(m=>({status:"fulfilled",value:m}),m=>({status:"rejected",reason:m}))))};document.getElementsByTagName("link");const c=document.querySelector("meta[property=csp-nonce]"),d=c?.nonce||c?.getAttribute("nonce");r=l(s.map(u=>{if(u=Dj(u),u in Vm)return;Vm[u]=!0;const h=u.endsWith(".css"),m=h?'[rel="stylesheet"]':"";if(document.querySelector(`link[href="${u}"]${m}`))return;const f=document.createElement("link");if(f.rel=h?"stylesheet":$j,h||(f.as="script"),f.crossOrigin="",f.href=u,d&&f.setAttribute("nonce",d),document.head.appendChild(f),h)return new Promise((p,g)=>{f.addEventListener("load",p),f.addEventListener("error",()=>g(new Error(`Unable to preload CSS for ${u}`)))})}))}function o(l){const c=new Event("vite:preloadError",{cancelable:!0});if(c.payload=l,window.dispatchEvent(c),!c.defaultPrevented)throw l}return r.then(l=>{for(const c of l||[])c.status==="rejected"&&o(c.reason);return n().catch(o)})},Lj=20;function Oj(e){const n=e.todoCount>e.threshold&&e.idleNonEphemeralAgentCount===0;return{atRisk:n,todoCount:e.todoCount,inProgressCount:e.inProgressCount,inReviewCount:e.inReviewCount,idleNonEphemeralAgentCount:e.idleNonEphemeralAgentCount,threshold:e.threshold,reason:n?"todo-exceeds-threshold-and-no-idle-agents":"ok"}}const Fj={themeMode:"dark",colorTheme:"default",dashboardFontScalePct:100,defaultProvider:void 0,defaultModelId:void 0,fallbackProvider:void 0,fallbackModelId:void 0,defaultThinkingLevel:void 0,ntfyEnabled:!1,ntfyTopic:void 0,ntfyBaseUrl:void 0,ntfyAccessToken:void 0,ntfyEvents:["in-review","merged","failed","awaiting-approval","awaiting-user-review","planning-awaiting-input","message:agent-to-user","message:agent-to-agent","message:room","gridlock","fallback-used","memory-dreams-processed"],ntfyDashboardHost:void 0,failureNotificationDelayMs:3e4,failureNotificationMode:"sticky-only",webhookEnabled:!1,webhookUrl:void 0,webhookFormat:"generic",webhookEvents:[],notificationProviders:[],customProviders:[],defaultProjectId:void 0,setupComplete:void 0,favoriteProviders:void 0,favoriteModels:void 0,openrouterModelSync:!0,opencodeGoModelSync:!0,updateCheckEnabled:!0,fnBinaryCheckEnabled:!0,updateCheckFrequency:"daily",autoReloadOnVersionChange:!0,showGitHubStarButton:!0,githubTrackingDefaultRepo:void 0,modelOnboardingComplete:void 0,useClaudeCli:void 0,useDroidCli:void 0,useLlamaCpp:void 0,executionGlobalProvider:void 0,executionGlobalModelId:void 0,planningGlobalProvider:void 0,planningGlobalModelId:void 0,validatorGlobalProvider:void 0,validatorGlobalModelId:void 0,titleSummarizerGlobalProvider:void 0,titleSummarizerGlobalModelId:void 0,daemonToken:void 0,daemonPort:4040,daemonHost:"127.0.0.1",settingsSyncEnabled:!1,settingsSyncAuth:!1,settingsSyncInterval:9e5,settingsSyncConflictResolution:"last-write-wins",dashboardCurrentNodeId:void 0,dashboardCurrentProjectIdByNode:void 0,vitestAutoKillEnabled:!0,vitestKillThresholdPct:90,persistAgentToolOutput:!0,persistAgentThinkingLogPermanent:!1,persistAgentThinkingLogEphemeral:!1,persistAgentThinkingLog:!1,researchGlobalDefaults:{searchProvider:void 0,synthesisProvider:void 0,synthesisModelId:void 0,enabledSources:{webSearch:!0,pageFetch:!0,github:!1,localDocs:!0,llmSynthesis:!0},maxSourcesPerRun:20,defaultExportFormat:"markdown"},researchGlobalEnabled:!0,researchGlobalMaxConcurrentRuns:3,researchGlobalDefaultTimeout:3e5,researchGlobalMaxSourcesPerRun:20,researchGlobalMaxSynthesisRounds:2,researchGlobalWebSearchProvider:"builtin",researchGlobalSearxngUrl:void 0,researchGlobalBraveApiKey:void 0,researchGlobalGoogleSearchApiKey:void 0,researchGlobalGoogleSearchCx:void 0,researchGlobalTavilyApiKey:void 0,researchGlobalGitHubEnabled:!1,researchGlobalLocalDocsEnabled:!0,researchGlobalMaxSearchResults:10,researchGlobalFetchTimeoutMs:3e4,researchGlobalUserAgent:"FusionResearchBot/1.0",remoteAccess:{activeProvider:null,providers:{tailscale:{enabled:!1,hostname:"",targetPort:0,acceptRoutes:!1},cloudflare:{enabled:!1,quickTunnel:!0,tunnelName:"",tunnelToken:null,ingressUrl:""}},tokenStrategy:{persistent:{enabled:!0,token:null},shortLived:{enabled:!1,ttlMs:9e5,maxTtlMs:864e5}},lifecycle:{rememberLastRunning:!1,wasRunningOnShutdown:!1,lastRunningProvider:null}},experimentalFeatures:{}},zj={globalPause:!1,globalPauseReason:void 0,enginePaused:!1,maxConcurrent:2,maxTriageConcurrent:2,globalMaxConcurrent:4,maxWorktrees:4,pollIntervalMs:15e3,heartbeatMultiplier:1,groupOverlappingFiles:!0,overlapIgnorePaths:[],autoMerge:!0,mergeStrategy:"direct",directMergeCommitStrategy:"auto",requirePrApproval:!1,pushAfterMerge:!1,pushRemote:"origin",unavailableNodePolicy:"block",defaultNodeId:void 0,worktreeInitCommand:void 0,testCommand:void 0,buildCommand:void 0,recycleWorktrees:!1,executorAllowSiblingBranchRename:!1,worktreeNaming:"random",taskPrefix:"FN",includeTaskIdInCommit:!0,commitAuthorEnabled:!0,commitAuthorName:"Fusion",commitAuthorEmail:"noreply@runfusion.ai",planningProvider:void 0,planningModelId:void 0,planningFallbackProvider:void 0,planningFallbackModelId:void 0,defaultProviderOverride:void 0,defaultModelIdOverride:void 0,executionProvider:void 0,executionModelId:void 0,validatorProvider:void 0,validatorModelId:void 0,validatorFallbackProvider:void 0,validatorFallbackModelId:void 0,modelPresets:[],autoSelectModelPreset:!1,completionDocumentationMode:"off",defaultPresetBySize:{},autoResolveConflicts:!0,smartConflictResolution:!0,mergerAutostashMaxAgeHours:24,worktreeRebaseBeforeMerge:!0,worktreeRebaseRemote:"",worktreeRebaseLocalBase:!0,mergeConflictStrategy:"smart-prefer-main",mergeDiffVolumeMinLines:void 0,mergeDiffVolumeThreshold:void 0,mergeDiffVolumeAllowlist:void 0,mergeStrategyOverlapBehavior:"flip-to-prefer-branch",postMergeAuditMode:"warn",mergeAuditAutoRecovery:"ai-assisted",workflowStepTimeoutMs:36e4,workflowStepScopeEnforcement:"block",workflowRevisionForkOnScopeMismatch:!0,strictScopeEnforcement:!1,buildRetryCount:0,verificationFixRetries:3,buildTimeoutMs:3e5,requirePlanApproval:!1,ephemeralAgentsEnabled:!0,agentProvisioning:{},specStalenessEnabled:!1,specStalenessMaxAgeMs:360*60*1e3,taskStuckTimeoutMs:6e5,capacityRiskBannerEnabled:!1,capacityRiskTodoThreshold:20,staleHighFanoutBlockerAgeThresholdMs:7200*1e3,aiSessionTtlMs:10080*60*1e3,aiSessionCleanupIntervalMs:3600*1e3,autoUnpauseEnabled:!0,autoUnpauseBaseDelayMs:3e5,autoUnpauseMaxDelayMs:36e5,maxStuckKills:6,preserveProgressOnStuckRequeue:!0,maxPostReviewFixes:1,maxSpawnedAgentsPerParent:5,maxSpawnedAgentsGlobal:20,maintenanceIntervalMs:3e5,autoArchiveDoneTasksEnabled:!0,autoArchiveDoneAfterMs:2880*60*1e3,archiveAgentLogMode:"compact",autoUpdatePrStatus:!1,githubCommentOnDone:!1,githubCommentTemplate:void 0,githubTrackingEnabledByDefault:!1,githubTrackingDefaultRepo:void 0,githubAuthMode:"gh-cli",githubAuthToken:void 0,autoBackupEnabled:!1,autoBackupSchedule:"0 2 * * *",autoBackupRetention:7,autoBackupDir:".fusion/backups",memoryBackupEnabled:!1,memoryBackupSchedule:"0 3 * * *",memoryBackupRetention:14,memoryBackupDir:".fusion/backups/memory",memoryBackupScope:"all",autoSummarizeTitles:!1,useAiMergeCommitSummary:!0,titleSummarizerProvider:void 0,titleSummarizerModelId:void 0,titleSummarizerFallbackProvider:void 0,titleSummarizerFallbackModelId:void 0,scripts:void 0,setupScript:void 0,insightExtractionEnabled:!1,insightExtractionSchedule:"0 2 * * *",insightExtractionMinIntervalMs:864e5,taskEvaluationEnabled:!1,taskEvaluationSchedule:"0 5 * * *",taskEvaluationProvider:void 0,taskEvaluationModelId:void 0,taskEvaluationFollowUpPolicy:"off",taskEvaluationRetention:void 0,memoryEnabled:!0,memoryBackendType:"qmd",memoryAutoSummarizeEnabled:!1,memoryAutoSummarizeThresholdChars:5e4,memoryAutoSummarizeSchedule:"0 3 * * *",memoryDreamsEnabled:!1,memoryDreamsSchedule:"0 4 * * *",tokenCap:void 0,runStepsInNewSessions:!1,maxParallelSteps:2,missionStaleThresholdMs:6e5,missionMaxTaskRetries:3,missionHealthCheckIntervalMs:3e5,agentPrompts:void 0,promptOverrides:void 0,reflectionEnabled:!1,reflectionIntervalMs:36e5,reflectionAfterTask:!0,reviewHandoffPolicy:"disabled",showQuickChatFAB:!1,researchSettings:{enabled:!0,searchProvider:void 0,synthesisProvider:void 0,synthesisModelId:void 0,enabledSources:{webSearch:!0,pageFetch:!0,github:!1,localDocs:!0,llmSynthesis:!0},limits:{maxConcurrentRuns:3,maxSourcesPerRun:20,maxDurationMs:3e5,requestTimeoutMs:3e4}},evalSettings:{enabled:!1,intervalMs:864e5,evaluatorProvider:void 0,evaluatorModelId:void 0,followUpPolicy:"suggest-only",retentionDays:30},researchEnabled:!0,researchMaxConcurrentRuns:3,researchDefaultTimeout:3e5,researchMaxSourcesPerRun:20,researchMaxSynthesisRounds:2},Bj=Object.freeze(Object.keys(Fj)),Uj=Object.freeze(Object.keys(zj));function W6(e){return Bj.includes(e)}function G6(e){return Uj.includes(e)}function K6(e,n){const s=n.ephemeral?e?.persistAgentThinkingLogEphemeral:e?.persistAgentThinkingLogPermanent;return typeof s=="boolean"?s:typeof e?.persistAgentThinkingLog=="boolean"?e.persistAgentThinkingLog:!1}function Ie(e){if(e instanceof Error)return e.message;if(typeof e=="string")return e;try{return JSON.stringify(e)}catch{return String(e)}}function Hj(e){return!!(e?.provider&&e?.modelId)}function ya(...e){for(const n of e)if(Hj(n))return{provider:n.provider,modelId:n.modelId};return{}}function Nc(e){return ya({provider:e?.defaultProviderOverride,modelId:e?.defaultModelIdOverride},{provider:e?.defaultProvider,modelId:e?.defaultModelId})}function qj(e){return ya({provider:e?.executionProvider,modelId:e?.executionModelId},{provider:e?.executionGlobalProvider,modelId:e?.executionGlobalModelId},Nc(e))}function Vj(e){return ya({provider:e?.planningProvider,modelId:e?.planningModelId},{provider:e?.planningGlobalProvider,modelId:e?.planningGlobalModelId},Nc(e))}function Wj(e){return ya({provider:e?.validatorProvider,modelId:e?.validatorModelId},{provider:e?.validatorGlobalProvider,modelId:e?.validatorGlobalModelId},Nc(e))}function J6(e){return ya({provider:e?.titleSummarizerProvider,modelId:e?.titleSummarizerModelId},{provider:e?.titleSummarizerGlobalProvider,modelId:e?.titleSummarizerGlobalModelId},{provider:e?.planningProvider,modelId:e?.planningModelId},Nc(e))}function xb(e,n){return ya({provider:e.modelProvider,modelId:e.modelId},qj(n))}function vb(e,n){return ya({provider:e.validatorModelProvider,modelId:e.validatorModelId},Wj(n))}function yb(e,n){return ya({provider:e.planningModelProvider,modelId:e.planningModelId},Vj(n))}const Y6=["off","minimal","low","medium","high"],ha=["triage","todo","in-progress","in-review","done","archived"],Yl="triage";function Ku(e){return typeof e=="string"&&ha.includes(e)}function wb(e,n=Yl){return Ku(e)?e:n}const wa=["low","normal","high","urgent"],_s="normal",Ju=5,kb=7200*1e3,Gj=["default","ocean","forest","sunset","zen","berry","high-contrast","industrial","monochrome","slate","ash","graphite","silver","solarized","factory","ayu","one-dark","nord","dracula","gruvbox","tokyo-night","catppuccin-mocha","github-dark","everforest","rose-pine","kanagawa","night-owl","palenight","monokai-pro","slime","brutalist","neon-city","parchment","terminal","glass","horizon","vitesse","outrun","snazzy","porple","espresso","mars","poimandres","ember","rust","copper","foundry","carbon","sandstone","lagoon","frost","lavender","neon-bloom","sepia"],Sc=/^[A-Za-z0-9._-]+\/[A-Za-z0-9._-]+$/,ds={triage:"Planning",todo:"Todo","in-progress":"In Progress","in-review":"In Review",done:"Done",archived:"Archived"},Kj={triage:"Raw ideas — AI will plan these",todo:"Specified and ready to start","in-progress":"AI is working on this in a worktree","in-review":"Complete — ready to merge",done:"Merged and closed",archived:"Completed and archived"},hu={triage:["todo"],todo:["in-progress","triage"],"in-progress":["in-review","todo","triage","done"],"in-review":["done","in-progress","todo","triage"],done:["todo","triage","archived"],archived:["done"]};function Jj(e){const n=e.metadata??{};return!!(n.agentKind==="task-worker"||n.taskWorker===!0||n.managedBy==="task-executor"||n.type==="spawned"||n.internal===!0||e.role==="executor"&&typeof e.name=="string"&&e.name.startsWith("executor-")&&e.reportsTo==null||e.role==="executor"&&e.name==="verification-agent"&&e.reportsTo==null)}const Yu="fn.authToken",Wm="token",Yj="fn_token";let yr,Gm=!1,Ql=!1;const pu="fn:auth-token-recovery-required";function Qj(){try{const e=window.localStorage.getItem(Yu);return e&&e.length>0?e:void 0}catch{return}}function jb(e){try{window.localStorage.setItem(Yu,e)}catch{}}function Xj(){if(!(Gm||typeof window>"u")){Gm=!0;try{const e=new URL(window.location.href),n=e.searchParams.get(Wm);if(!n)return;jb(n),e.searchParams.delete(Wm);const s=e.pathname+(e.search?e.search:"")+e.hash;return window.history.replaceState(window.history.state,"",s),n}catch{return}}}function _r(){if(yr!==void 0)return yr;const e=Xj();if(e)return yr=e,e;const n=Qj();if(n)return yr=n,n}function Zj(e){yr=e,Ql=!1,jb(e)}function eN(){yr=void 0,Ql=!1;try{window.localStorage.removeItem(Yu)}catch{}}function Km(e){return e==="ws:"?"http:":e==="wss:"?"https:":e}function tN(e){return e==="http:"||e==="https:"||e==="ws:"||e==="wss:"}function nN(e){if(typeof window>"u")return!1;const n=new URL(window.location.origin);if(!tN(e.protocol))return!1;const s=e.hostname===n.hostname,a=e.port===n.port,r=Km(e.protocol)===Km(n.protocol);return s&&a&&r}function sN(e){if(!(typeof window>"u"))try{const n=new URL(e,window.location.origin),s=e.startsWith("/");return{parsed:n,preserveRelativePath:s}}catch{return}}function Li(e){const n=_r();if(!n||typeof window>"u")return e;const s=sN(e);return!s||!nN(s.parsed)?e:(s.parsed.searchParams.set(Yj,n),s.preserveRelativePath?`${s.parsed.pathname}${s.parsed.search}${s.parsed.hash}`:s.parsed.toString())}function Ni(e){const n=_r();if(!n)return e;const s=new Headers(e??{});return s.has("Authorization")||s.set("Authorization",`Bearer ${n}`),s}function iN(e){if(!e||typeof e!="object")return!1;const n=e;return n.error==="Unauthorized"&&n.message==="Valid bearer token required"}function aN(){typeof window>"u"||Ql||(Ql=!0,window.dispatchEvent(new CustomEvent(pu)))}async function rN(e){if(e.status===401)try{const n=e.clone();if(!(n.headers.get("content-type")??"").toLowerCase().includes("application/json"))return;const a=await n.json();iN(a)&&aN()}catch{}}function oN(){if(typeof window>"u"||window.__fnAuthFetchInstalled)return;window.__fnAuthFetchInstalled=!0,_r();const e=window.fetch.bind(window);window.fetch=function(s,a){const r=_r(),o=typeof s=="string"?s:s instanceof URL?s.toString():s.url;if(!(()=>{try{const d=new URL(o,window.location.origin);return d.origin!==window.location.origin?!1:d.pathname.startsWith("/api/")||d.pathname==="/api"}catch{return o.startsWith("/api/")||o==="/api"}})())return e(s,a);const c=new Headers(a?.headers??(s instanceof Request?s.headers:void 0));return r&&!c.has("Authorization")&&c.set("Authorization",`Bearer ${r}`),e(s,{...a,headers:c}).then(d=>(rN(d),d))}}class Xl extends Error{status;details;constructor(n,s,a){super(n),this.name="ApiRequestError",this.status=s,this.details=a}}function lN(e){const n=e.trim();return n.startsWith("<!DOCTYPE")||n.startsWith("<html")||n.startsWith("<HTML")}function Ss(e){return`/api${e}`}async function I(e,n={}){const s=Ss(e),a=_r(),r=(()=>{if(a){const f=new Headers(n.headers??{});return f.has("Content-Type")||f.set("Content-Type","application/json"),Ni(f)}if(!n.headers)return{"Content-Type":"application/json"};const m=new Headers(n.headers);return m.has("Content-Type")||m.set("Content-Type","application/json"),Object.fromEntries(m.entries())})(),o=await fetch(s,{...n,headers:r});if(o.status===204){if(!o.ok)throw new Error(`Request failed for ${s}: ${o.status} ${o.statusText}`);return}const l=o.headers.get("content-type")??"",c=await o.text(),d=l.includes("application/json");if(l.includes("text/html")||lN(c))throw new Error(`API returned HTML instead of JSON for ${s}. The endpoint may not be properly configured. (${o.status} ${o.statusText})`);if(!d){const m=c.length>160?`${c.slice(0,160)}...`:c;throw new Error(`API returned ${l||"an unknown content type"} instead of JSON for ${s}. (${o.status} ${o.statusText})${m?` Response: ${m}`:""}`)}let h;try{h=c?JSON.parse(c):null}catch{throw new Error(`API returned invalid JSON for ${s}. (${o.status} ${o.statusText})`)}if(!o.ok){const m=h;throw new Xl(m?.error||`Request failed for ${s}: ${o.status} ${o.statusText}`,o.status,m?.details)}return h}function cN(){return I("/health")}function dN(){return I("/health/refresh",{method:"POST"})}function Q6(){return I("/updates/check")}function uN(e,n,s,a,r){const o=new URLSearchParams;e!==void 0&&o.set("limit",String(e)),n!==void 0&&o.set("offset",String(n)),s&&o.set("projectId",s),a&&o.set("q",a),r&&o.set("includeArchived","1");const l=o.size>0?`?${o.toString()}`:"";return I(`/tasks${l}`)}async function Ba(e,n){const a=Ss(V(`/tasks/${e}`,n));for(let r=1;r<=2;r++){const o=await fetch(a,{headers:Ni({"Content-Type":"application/json"})}),l=await o.json();if(o.ok)return l;if(r===2)throw new Error(l.error||"Request failed")}throw new Error("Request failed")}function Nb(e,n,s){const{title:a,description:r,column:o,dependencies:l,breakIntoSubtasks:c,enabledWorkflowSteps:d,assignedAgentId:u,modelPresetId:h,modelProvider:m,modelId:f,validatorModelProvider:p,validatorModelId:g,planningModelProvider:w,planningModelId:v,thinkingLevel:b,summarize:y,reviewLevel:j,executionMode:S,priority:C,source:x,nodeId:k,branch:R,baseBranch:O,githubTracking:E}=e;return Yo(V("/tasks",n),{method:"POST",nodeId:s?.transportNodeId,localNodeId:s?.localNodeId,body:JSON.stringify({title:a,description:r,column:o,dependencies:l,breakIntoSubtasks:c,enabledWorkflowSteps:d,assignedAgentId:u,modelPresetId:h,modelProvider:m,modelId:f,validatorModelProvider:p,validatorModelId:g,planningModelProvider:w,planningModelId:v,thinkingLevel:b,summarize:y,reviewLevel:j,executionMode:S,priority:C,source:x,nodeId:k,branch:R,baseBranch:O,githubTracking:E})})}function Ls(e,n,s){return I(V(`/tasks/${e}`,s),{method:"PATCH",body:JSON.stringify(n)})}function mN(e,n,s,a,r,o,l,c,d){return I(V("/tasks/batch-update-models",d),{method:"POST",body:JSON.stringify({taskIds:e,modelProvider:n,modelId:s,validatorModelProvider:a,validatorModelId:r,planningModelProvider:o,planningModelId:l,nodeId:c})})}function hN(e,n,s,a){return I(V(`/tasks/${e}/move`,s),{method:"POST",body:JSON.stringify({column:n,...typeof a=="object"&&a?.preserveProgress?{preserveProgress:!0}:{}})})}function pN(e,n,s){const a=new URLSearchParams;s?.removeDependencyReferences&&a.set("removeDependencyReferences","true"),s?.githubIssueAction&&a.set("githubIssueAction",s.githubIssueAction);const r=a.size>0?`?${a.toString()}`:"";return I(V(`/tasks/${e}${r}`,n),{method:"DELETE"})}function fN(e,n){return I(V(`/tasks/${e}/merge`,n),{method:"POST"})}function gN(e,n){return I(V(`/tasks/${e}/retry`,n),{method:"POST"})}function bN(e,n){return I(V(`/tasks/${e}/reset`,n),{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify({confirm:!0})})}function xN(e,n){return I(V(`/tasks/${e}/duplicate`,n),{method:"POST"})}function Sb(e,n){return I(V(`/tasks/${e}/pause`,n),{method:"POST"})}function Cb(e,n){return I(V(`/tasks/${e}/unpause`,n),{method:"POST"})}function vN(e,n){return I(V(`/tasks/${e}/archive`,n),{method:"POST"})}function yN(e,n){return I(V(`/tasks/${e}/unarchive`,n),{method:"POST"})}function wN(e){return I(V("/tasks/archive-all-done",e),{method:"POST"}).then(n=>n.archived)}function kN(e,n){return I(V(`/tasks/${e}/approve-plan`,n),{method:"POST"})}function jN(e,n){return I(V(`/tasks/${e}/reject-plan`,n),{method:"POST"})}function NN(e){return I(V("/config",e))}function Cc(e){return I(V("/settings",e))}function al(e,n){return I(V("/settings",n),{method:"PUT",body:JSON.stringify(e)})}function SN(e){return I(V("/update-check",e))}function X6(e){return I(V("/remote/settings",e))}function Z6(e,n){return I(V("/remote/settings",n),{method:"PUT",body:JSON.stringify(e)})}function e3(e){return I(V("/remote/status",e))}function t3(e){return I(V("/remote/install-cloudflared",e),{method:"POST"})}function n3(e){return I(V("/remote/tunnel/start",e),{method:"POST"})}function s3(e){return I(V("/remote/tunnel/stop",e),{method:"POST"})}function i3(e){return I(V("/remote/tunnel/kill-external",e),{method:"POST"})}function a3(e){return I(V("/remote/token/persistent/regenerate",e),{method:"POST"})}function r3(e,n){return I(V("/remote/token/short-lived/generate",n),{method:"POST",body:JSON.stringify({ttlMs:e})})}function Eb(e,n,s){const a=new URLSearchParams;e&&a.set("format",e),a.set("tokenType",n),n==="short-lived"&&typeof s=="number"&&Number.isFinite(s)&&a.set("ttlMs",String(s));const r=a.toString();return r?`?${r}`:""}function o3(e={}){const{projectId:n,tokenType:s="persistent",ttlMs:a}=e,r=Eb(null,s,a);return I(V(`/remote/url${r}`,n))}function l3(e="text",n={}){const{projectId:s,tokenType:a="persistent",ttlMs:r}=n,o=Eb(e,a,r);return I(V(`/remote/qr${o}`,s))}function c3(e){return I(V("/memory",e))}function d3(e,n){return I(V("/memory",n),{method:"PUT",body:JSON.stringify({content:e})})}function u3(e){return I(V("/memory/files",e))}function m3(e,n){const s=`path=${encodeURIComponent(e)}`;return I(V(`/memory/file?${s}`,n))}function h3(e,n,s){return I(V("/memory/file",s),{method:"PUT",body:JSON.stringify({path:e,content:n})})}function p3(e,n){let s,a=n;if(n!==void 0)s=e;else if(typeof e=="string"&&e.trim().length>0){const r=e.trim();r.includes("/")||r.endsWith(".md")||r.startsWith(".")?s=r:a=r}return I(V("/memory/compact",a),{method:"POST",body:JSON.stringify(s?{path:s}:{})})}function f3(e){return I(V("/memory/dream",e),{method:"POST"})}function g3(e){return I(V("/memory/insights",e))}function b3(e,n){return I(V("/memory/insights",n),{method:"PUT",body:JSON.stringify({content:e})})}function x3(e){return I(V("/memory/extract",e),{method:"POST"})}function v3(e){return I(V("/memory/audit",e))}function y3(e){return I(V("/memory/stats",e))}function w3(e){return I(V("/memory/backend",e))}function k3(e){return I(V("/memory/install-qmd",e),{method:"POST"})}function j3(e,n){return I(V("/memory/test",n),{method:"POST",body:JSON.stringify({query:e})})}function Qi(){return I("/settings/global")}function Fn(e){return I("/settings/global",{method:"PUT",body:JSON.stringify(e)})}function N3(e){return I(V("/settings/scopes",e))}function S3(e){return I(V("/settings/pi-extensions",e))}function C3(e,n){return I(V("/settings/pi-extensions",n),{method:"PUT",body:JSON.stringify({disabledIds:e})})}function E3(e,n,s){return I(V("/settings/test-notification",s),{method:"POST",body:JSON.stringify({providerId:e,...n??{}})})}function _3(){return I("/pi-settings")}async function M3(e){return I("/pi-settings",{method:"PUT",body:JSON.stringify(e)})}async function A3(e){return I("/pi-settings/packages",{method:"POST",body:JSON.stringify({source:e})})}async function R3(e){return I(V("/pi-settings/reinstall-fusion",e),{method:"POST"})}async function Ec(e,n,s){const a=new FormData;a.append("file",n);const r=await fetch(Ss(V(`/tasks/${e}/attachments`,s)),{method:"POST",headers:Ni(),body:a}),o=await r.json();if(!r.ok)throw new Error(o.error||"Upload failed");return o}async function CN(e,n,s){return I(V(`/tasks/${e}/attachments/${n}`,s),{method:"DELETE"})}async function Jm(e,n,s){const a=new URLSearchParams;s?.limit!==void 0&&a.set("limit",String(s.limit)),s?.offset!==void 0&&a.set("offset",String(s.offset));const r=a.toString()?`?${a.toString()}`:"",o=V(`/tasks/${e}/logs${r}`,n),l=await fetch(Ss(o),{headers:Ni()});if(!l.ok){const h=await l.json().catch(()=>({error:"Failed to fetch agent logs"}));throw new Error(h.error||`HTTP ${l.status}`)}const c=await l.json(),d=l.headers.has("X-Total-Count")?parseInt(l.headers.get("X-Total-Count"),10):c.length,u=l.headers.has("X-Has-More")?l.headers.get("X-Has-More")==="true":!1;return{entries:c,total:d,hasMore:u}}function EN(e,n,s,a){return I(V(`/tasks/${e}/comments/${n}`,a),{method:"PATCH",body:JSON.stringify({text:s})})}function _N(e,n,s){return I(V(`/tasks/${e}/comments/${n}`,s),{method:"DELETE"})}function MN(e,n){return I(V(`/tasks/${e}/documents`,n))}function AN(e,n,s){return I(V(`/tasks/${e}/documents/${n}/revisions`,s))}async function I3(e,n){const s=new URLSearchParams;e?.q&&s.set("q",e.q),e?.limit!==void 0&&s.set("limit",String(e.limit)),e?.offset!==void 0&&s.set("offset",String(e.offset));const a=s.toString(),r=`/documents${a?`?${a}`:""}`;return I(V(r,n))}function T3(e,n){const s=new URLSearchParams;n?.showHidden&&s.set("showHidden","1");const a=s.toString(),r=`/files/markdown-list${a?`?${a}`:""}`;return I(V(r,e))}function Ym(e,n,s,a,r){return I(V(`/tasks/${e}/documents/${n}`,r),{method:"PUT",body:JSON.stringify({content:s,author:a?.author,metadata:a?.metadata})})}function RN(e,n,s){return I(V(`/tasks/${e}/documents/${n}`,s),{method:"DELETE"})}function IN(e,n,s){return I(V(`/tasks/${e}/steer`,s),{method:"POST",body:JSON.stringify({text:n})})}function TN(e,n,s){return I(V(`/tasks/${e}/spec/revise`,s),{method:"POST",body:JSON.stringify({feedback:n})})}function PN(e,n){return I(V(`/tasks/${e}/spec/rebuild`,n),{method:"POST"})}function $N(e,n,s){return I(V(`/tasks/${e}/refine`,s),{method:"POST",body:JSON.stringify({feedback:n})})}function Bs(){return I("/models")}function DN(){return I("/usage")}function LN(){return I("/providers/claude-cli/status")}function ON(){return I("/system/fn-binary/status")}function FN(){return I("/system/fn-binary/install",{method:"POST"})}function zN(){return I("/providers/droid-cli/status")}function BN(){return I("/providers/cursor-cli/status")}function UN(){return I("/providers/llama-cpp/status")}async function P3(e){const n=e?.binaryPath?`?binaryPath=${encodeURIComponent(e.binaryPath)}`:"";return I(`/providers/hermes/status${n}`)}async function $3(e){const n=e?.binaryPath?`?binaryPath=${encodeURIComponent(e.binaryPath)}`:"";return(await I(`/providers/hermes/profiles${n}`)).profiles??[]}async function D3(e){const n=e?.binaryPath?`?binaryPath=${encodeURIComponent(e.binaryPath)}`:"";return I(`/providers/openclaw/status${n}`)}async function L3(e){const n=new URLSearchParams({apiUrl:e.apiUrl});return e.apiKey&&n.set("apiKey",e.apiKey),I(`/providers/paperclip/status?${n.toString()}`)}async function O3(e){const n=new URLSearchParams({apiUrl:e.apiUrl});return e.apiKey&&n.set("apiKey",e.apiKey),(await I(`/providers/paperclip/companies?${n.toString()}`)).companies??[]}async function F3(e){const n=new URLSearchParams({apiUrl:e.apiUrl,companyId:e.companyId});return e.apiKey&&n.set("apiKey",e.apiKey),(await I(`/providers/paperclip/agents?${n.toString()}`)).agents??[]}async function z3(e){return I("/providers/paperclip/cli-mint-key",{method:"POST",body:JSON.stringify(e)})}async function B3(e){const n=new URLSearchParams;e.cliBinaryPath&&n.set("cliBinaryPath",e.cliBinaryPath),e.cliConfigPath&&n.set("cliConfigPath",e.cliConfigPath);const s=n.toString();return I(`/providers/paperclip/cli-status${s?`?${s}`:""}`)}async function U3(e){const n=new URLSearchParams;e.cliBinaryPath&&n.set("cliBinaryPath",e.cliBinaryPath),e.cliConfigPath&&n.set("cliConfigPath",e.cliConfigPath);const s=n.toString();return(await I(`/providers/paperclip/cli-companies${s?`?${s}`:""}`)).companies??[]}async function H3(e){const n=new URLSearchParams({companyId:e.companyId});return e.cliBinaryPath&&n.set("cliBinaryPath",e.cliBinaryPath),e.cliConfigPath&&n.set("cliConfigPath",e.cliConfigPath),(await I(`/providers/paperclip/cli-agents?${n.toString()}`)).agents??[]}async function q3(e={}){const n=new URLSearchParams;e.cliConfigPath&&n.set("cliConfigPath",e.cliConfigPath);const s=n.toString();return I(`/providers/paperclip/cli-discovery${s?`?${s}`:""}`)}function HN(e){return I("/auth/claude-cli",{method:"POST",body:JSON.stringify({enabled:e})})}function qN(e){return I("/auth/droid-cli",{method:"POST",body:JSON.stringify({enabled:e})})}function VN(e){return I("/auth/cursor-cli",{method:"POST",body:JSON.stringify({enabled:e})})}function WN(e){return I("/auth/llama-cpp",{method:"POST",body:JSON.stringify({enabled:e})})}async function GN(){const n=(await I("/custom-providers")).map(s=>({id:s.id,name:s.name,baseUrl:s.baseUrl,api:s.apiType==="anthropic-compatible"?"anthropic-messages":"openai-completions",apiKey:s.apiKey,models:(s.models??[]).map(a=>({id:a.id,name:a.name}))}));return Object.assign(n,{providers:n})}function KN(e){return I("/custom-providers",{method:"POST",body:JSON.stringify(e)})}function V3(e,n){const s=n,a={...typeof s.name=="string"?{name:s.name}:{},...typeof s.baseUrl=="string"?{baseUrl:s.baseUrl}:{},...typeof s.apiKey=="string"?{apiKey:s.apiKey}:{},...Array.isArray(s.models)?{models:s.models.map(r=>({id:r.id,name:r.name??r.id}))}:{},...s.api?{apiType:s.api==="anthropic-messages"?"anthropic-compatible":"openai-compatible"}:{},..."apiType"in n?{apiType:n.apiType}:{}};return I(`/custom-providers/${encodeURIComponent(e)}`,{method:"PUT",body:JSON.stringify(a)})}function W3(e){return I(`/custom-providers/${encodeURIComponent(e)}`,{method:"DELETE"})}function JN(e){const n=e.api==="anthropic-messages"?"anthropic-compatible":"openai-compatible";return KN({name:e.name?.trim()||e.id,apiType:n,baseUrl:e.baseUrl,apiKey:e.apiKey,models:e.models?.map(s=>({id:s.id,name:s.name??s.id}))})}function Do(){return I("/auth/status")}function YN(e){return I("/auth/login",{method:"POST",body:JSON.stringify({provider:e,origin:window.location.origin})})}function QN(e,n){return I("/auth/manual-code",{method:"POST",body:JSON.stringify({provider:e,code:n})})}function XN(e){return I("/auth/logout",{method:"POST",body:JSON.stringify({provider:e})})}function ZN(e){return I("/auth/cancel",{method:"POST",body:JSON.stringify({provider:e})})}function eS(e,n){return I("/auth/api-key",{method:"POST",body:JSON.stringify({provider:e,apiKey:n})})}function tS(e){return I("/auth/api-key",{method:"DELETE",body:JSON.stringify({provider:e})})}function nS(e,n,s,a){return I("/github/issues/fetch",{method:"POST",body:JSON.stringify({owner:e,repo:n,limit:s,labels:a})})}function sS(e,n,s,a){return I(V("/github/issues/import",a),{method:"POST",body:JSON.stringify({owner:e,repo:n,issueNumber:s})})}function iS(e,n,s){return I("/github/pulls/fetch",{method:"POST",body:JSON.stringify({owner:e,repo:n,limit:s})})}function aS(e,n,s,a){return I(V("/github/pulls/import",a),{method:"POST",body:JSON.stringify({owner:e,repo:n,prNumber:s})})}function rS(e){return I(V("/git/remotes",e))}function oS(e){return I(V("/git/remotes/detailed",e))}function lS(e,n,s){return I(V("/git/remotes",s),{method:"POST",body:JSON.stringify({name:e,url:n})})}function cS(e,n){return I(V(`/git/remotes/${encodeURIComponent(e)}`,n),{method:"DELETE"})}function dS(e,n,s){return I(V(`/git/remotes/${encodeURIComponent(e)}`,s),{method:"PATCH",body:JSON.stringify({newName:n})})}function uS(e,n,s){return I(V(`/git/remotes/${encodeURIComponent(e)}/url`,s),{method:"PUT",body:JSON.stringify({url:n})})}function mS(e,n,s){return I(V(`/tasks/${e}/pr/create`,s),{method:"POST",body:JSON.stringify(n)})}function hS(e,n){return I(V(`/tasks/${e}/pr/refresh`,n),{method:"POST"})}function rl(e,n,s,a){return I(V("/terminal/sessions",a),{method:"POST",body:JSON.stringify({cwd:e,cols:n,rows:s})})}function Qm(e,n){return I(V(`/terminal/sessions/${encodeURIComponent(e)}`,n),{method:"DELETE"})}function pS(e){return I(V("/terminal/sessions",e))}function yi(e){return I(V("/git/status",e))}function fS(e,n){const s=e?`?limit=${e}`:"";return I(V(`/git/commits${s}`,n))}function Zl(e,n){return I(V(`/git/commits/${e}/diff`,n))}function gS(e){return I(V("/git/commits/ahead",e))}function bS(e,n,s,a){const r=new URLSearchParams;r.set("limit",String(s));const o=r.size>0?`?${r.toString()}`:"";return I(V(`/git/remotes/${encodeURIComponent(e)}/commits${o}`,a))}function eo(e){return I(V("/git/branches",e))}function xS(e,n,s){const a=`?limit=${n}`;return I(V(`/git/branches/${encodeURIComponent(e)}/commits${a}`,s))}function vS(e){return I(V("/git/worktrees",e))}function yS(e,n,s){return I(V("/git/branches",s),{method:"POST",body:JSON.stringify({name:e,base:n})})}function wS(e,n){return I(V(`/git/branches/${encodeURIComponent(e)}/checkout`,n),{method:"POST"})}function Xm(e,n,s){const a=n?"?force=true":"";return I(V(`/git/branches/${encodeURIComponent(e)}${a}`,s),{method:"DELETE"})}function kS(e,n){return I(V("/git/fetch",n),{method:"POST",body:JSON.stringify({remote:e})})}function jS(e,n){const s=typeof e=="string"?void 0:e;return I(V("/git/pull",typeof e=="string"?e:n),{method:"POST",body:JSON.stringify({rebase:s?.rebase??!1})})}function NS(e){return I(V("/git/push",e),{method:"POST"})}function ol(e){return I(V("/git/stashes",e))}function SS(e,n){return I(V("/git/stashes",n),{method:"POST",body:JSON.stringify({message:e})})}function CS(e,n,s){return I(V(`/git/stashes/${e}/apply`,s),{method:"POST",body:JSON.stringify({drop:n})})}function ES(e,n){return I(V(`/git/stashes/${e}`,n),{method:"DELETE"})}function _S(e,n){return I(V(`/git/stashes/${e}/diff`,n))}function MS(e,n,s){const a=new URLSearchParams;return a.set("path",e),a.set("staged",String(n)),I(V(`/git/diff/file?${a.toString()}`,s))}function dr(e){return I(V("/git/changes",e))}function Zm(e,n){return I(V("/git/stage",n),{method:"POST",body:JSON.stringify({files:e})})}function AS(e,n){return I(V("/git/unstage",n),{method:"POST",body:JSON.stringify({files:e})})}function eh(e,n){return I(V("/git/commit",n),{method:"POST",body:JSON.stringify({message:e})})}function RS(e,n){return I(V("/git/discard",n),{method:"POST",body:JSON.stringify({files:e})})}function IS(e){return I(V("/workspaces",e))}function TS(e,n,s){const a=new URLSearchParams({workspace:e});return n&&a.set("path",n),s&&a.set("projectId",s),I(`/files?${a.toString()}`)}function PS(e,n,s){const a=new URLSearchParams({workspace:e});return s&&a.set("projectId",s),I(`/files/${encodeURIComponent(n)}?${a.toString()}`)}function $S(e,n,s,a){const r=new URLSearchParams({workspace:e});return a&&r.set("projectId",a),I(`/files/${encodeURIComponent(n)}?${r.toString()}`,{method:"POST",body:JSON.stringify({content:s})})}function DS(e,n,s){const a=new URLSearchParams({q:e});return n&&a.set("workspace",n),s&&a.set("projectId",s),I(`/files/search?${a.toString()}`)}function LS(e,n,s,a){const r=new URLSearchParams({workspace:e});return a&&r.set("projectId",a),I(`/files/${encodeURIComponent(n)}/copy?${r.toString()}`,{method:"POST",body:JSON.stringify({destination:s})})}function OS(e,n,s,a){const r=new URLSearchParams({workspace:e});return a&&r.set("projectId",a),I(`/files/${encodeURIComponent(n)}/move?${r.toString()}`,{method:"POST",body:JSON.stringify({destination:s})})}function FS(e,n,s){const a=new URLSearchParams({workspace:e});return s&&a.set("projectId",s),I(`/files/${encodeURIComponent(n)}/delete?${a.toString()}`,{method:"POST"})}function zS(e,n,s,a){const r=new URLSearchParams({workspace:e});return a&&r.set("projectId",a),I(`/files/${encodeURIComponent(n)}/rename?${r.toString()}`,{method:"POST",body:JSON.stringify({newName:s})})}function _b(e,n,s){const a=new URLSearchParams({workspace:e});return s&&a.set("projectId",s),`/api/files/${encodeURIComponent(n)}/download?${a.toString()}`}function BS(e,n,s){const a=new URLSearchParams({workspace:e});return s&&a.set("projectId",s),`/api/files/${encodeURIComponent(n)}/download-zip?${a.toString()}`}function US(e,n,s){return I(V("/planning/create-draft",n),{method:"POST",body:JSON.stringify({initialPlan:e,planningModelProvider:s?.planningModelProvider,planningModelId:s?.planningModelId})})}function HS(e,n,s,a,r){return I(V("/planning/start-streaming",n),{method:"POST",body:JSON.stringify({initialPlan:e,planningModelProvider:s?.planningModelProvider,planningModelId:s?.planningModelId,planningDepth:a?.planningDepth,customQuestionCount:a?.customQuestionCount,...r?{existingSessionId:r}:{}})})}function th(e,n,s,a){return I(V("/planning/respond",s),{method:"POST",body:JSON.stringify({sessionId:e,responses:n,tabId:a})})}function qS(e,n,s){return I(V(`/planning/${encodeURIComponent(e)}/back`,n),{method:"POST",...s?{body:JSON.stringify({tabId:s})}:{}})}function VS(e,n,s){return I(V(`/planning/${encodeURIComponent(e)}/retry`,n),{method:"POST",...s?{body:JSON.stringify({tabId:s})}:{}})}function WS(e,n,s){return I(V(`/planning/${encodeURIComponent(e)}/stop`,n),{method:"POST",...s?{body:JSON.stringify({tabId:s})}:{}})}function Mb(e,n,s){return I(V("/planning/cancel",n),{method:"POST",body:JSON.stringify({sessionId:e,tabId:s})})}function G3(e,n,s,a){return I(V("/agents/onboarding/start-streaming",s),{method:"POST",body:JSON.stringify({intent:e,context:n,mode:n.mode,existingAgentConfig:n.existingAgentConfig,planningModelProvider:a?.planningModelProvider,planningModelId:a?.planningModelId})})}function K3(e,n,s){return I(V("/agents/onboarding/respond",s),{method:"POST",body:JSON.stringify({sessionId:e,responses:n})})}function J3(e,n){return I(V("/agents/onboarding/cancel",n),{method:"POST",body:JSON.stringify({sessionId:e})})}function GS(e,n,s){return I(V("/planning/create-task",s),{method:"POST",body:JSON.stringify(n?{sessionId:e,summary:n}:{sessionId:e})})}function KS(e,n,s){return I(V("/planning/start-breakdown",s),{method:"POST",body:JSON.stringify(n?{sessionId:e,summary:n}:{sessionId:e})})}function JS(e,n,s){return I(V("/planning/create-tasks",s),{method:"POST",body:JSON.stringify({planningSessionId:e,subtasks:n})})}const fu=new Set;if(typeof window<"u"){const e=()=>{for(const n of Array.from(fu))try{n.close()}catch{}};window.addEventListener("pagehide",e),window.addEventListener("beforeunload",e)}function YS(e,n){if(n===null||n<=0)return e;const s=e.includes("?")?"&":"?";return`${e}${s}lastEventId=${encodeURIComponent(String(n))}`}function Ur(e,n,s={}){const a=s.maxReconnectAttempts??10;let r=null,o=!1,l=0,c=null,d=null,u=!1;const h=p=>{const g=p.lastEventId;if(!g)return!0;const w=Number.parseInt(g,10);return Number.isFinite(w)?d!==null&&w<=d?!1:(d=w,!0):!0},m=()=>{if(o)return;const p=YS(e,d),g=new EventSource(Li(p));r=g,g.onopen=()=>{l=0,u=!1,s.onConnectionStateChange?.("connected"),n.onOpen?.()},g.onmessage=w=>{const v=w;h(v)&&n.onMessage?.(v)};for(const[w,v]of Object.entries(n.events??{}))g.addEventListener(w,b=>{const y=b;h(y)&&v(y)});g.onerror=()=>{if(o||r!==g)return;if(g.readyState===EventSource.CONNECTING){u||(u=!0,s.onConnectionStateChange?.("reconnecting"));return}if(g.close(),l>=a){s.onFatalError?.("Connection lost");return}u=!0,s.onConnectionStateChange?.("reconnecting"),l+=1;const v=Math.min(1e3*2**(l-1),3e4);c=setTimeout(()=>{c=null,m()},v)}};m();const f={close:()=>{o=!0,c&&(clearTimeout(c),c=null),r?.close(),fu.delete(f)},isConnected:()=>!o&&r?.readyState===EventSource.OPEN};return fu.add(f),f}function nh(e){const n=typeof e.source=="string"&&e.source.trim().length>0?e.source.trim():"root",s=n==="root"?".":n,a=e.name,r=typeof e.packagePath=="string"&&e.packagePath.trim().length>0?e.packagePath.trim():s,o=typeof e.confidence=="number"?e.confidence:1,l=n==="root"?"root":n,c=typeof e.packageName=="string"&&e.packageName.trim().length>0?e.packageName.trim():"project";return{name:e.name,command:e.command,scriptName:a,packagePath:r,confidence:o,cwd:s,source:n,workspaceName:typeof e.packageName=="string"?e.packageName:void 0,label:`${c} · ${a} (${l})`}}function Mr(e){const n=e.status,s=n==="starting"||n==="running"||n==="failed"||n==="stopped"?n:"stopped",a=typeof e.previewUrl=="string"?e.previewUrl:e.detectedUrl,r=typeof e.manualPreviewUrl=="string"?e.manualPreviewUrl:e.manualUrl;return{id:typeof e.id=="string"?e.id:"",name:typeof e.name=="string"&&e.name.length>0?e.name:"default",status:s,command:typeof e.command=="string"?e.command:"",scriptName:typeof e.scriptId=="string"?e.scriptId:"",cwd:typeof e.cwd=="string"?e.cwd:"",pid:e.pid,startedAt:e.startedAt,previewUrl:a,detectedUrl:typeof e.detectedUrl=="string"?e.detectedUrl:a,detectedPort:e.detectedPort,manualPreviewUrl:r,manualUrl:typeof e.manualUrl=="string"?e.manualUrl:r,logs:Array.isArray(e.logHistory)?e.logHistory:[],exitCode:e.exitCode}}function QS(e,n){return{id:typeof e.id=="number"&&Number.isFinite(e.id)?e.id:n,text:typeof e.text=="string"?e.text:typeof e.line=="string"?e.line:"",stream:e.stream==="stderr"?"stderr":"stdout",timestamp:typeof e.timestamp=="string"?e.timestamp:""}}function XS(e){const s=(Array.isArray(e.lines)?e.lines:[]).map((a,r)=>QS(a,r+1));return{lines:s,totalLines:typeof e.totalLines=="number"&&Number.isFinite(e.totalLines)?e.totalLines:s.length}}function ZS(e,n){const s=typeof n.maxLines=="number"&&Number.isFinite(n.maxLines)?Math.max(1,Math.floor(n.maxLines)):100,a=typeof n.offset=="number"&&Number.isFinite(n.offset)?Math.max(0,Math.floor(n.offset)):0,r=typeof n.lastEventId=="number"&&Number.isFinite(n.lastEventId)?Math.max(0,Math.floor(n.lastEventId)):null,o=e.length,l=e.map((u,h)=>({id:h+1,text:u,stream:"stdout",timestamp:""}));if(r!==null)return{lines:l.filter(u=>u.id>r).slice(0,s),totalLines:o};const c=Math.max(o-a,0),d=Math.max(c-s,0);return{lines:l.slice(d,c),totalLines:o}}function sh(e){return Array.isArray(e)?e.map(nh):(e.candidates??[]).map(nh)}async function e1(e){try{const n=await I(V("/dev-server/candidates",e));return sh(n)}catch(n){if(n instanceof Error&&/\/dev-server\/candidates/.test(n.message)){const s=await I(V("/dev-server/detect",e));return sh(s)}throw n}}function Qu(e){return I(V("/dev-server/status",e)).then(Mr)}async function Y3(e={},n){const s=new URLSearchParams;typeof e.maxLines=="number"&&Number.isFinite(e.maxLines)&&s.set("maxLines",String(Math.max(1,Math.floor(e.maxLines)))),typeof e.offset=="number"&&Number.isFinite(e.offset)&&s.set("offset",String(Math.max(0,Math.floor(e.offset)))),typeof e.lastEventId=="number"&&Number.isFinite(e.lastEventId)&&s.set("lastEventId",String(Math.max(0,Math.floor(e.lastEventId))));const a=s.size>0?`?${s.toString()}`:"";try{const r=await I(V(`/dev-server/logs/history${a}`,n));return XS(r)}catch(r){if(r instanceof Error&&/\/dev-server\/logs\/history/.test(r.message)){const o=await Qu(n);return ZS(o.logs,e)}throw r}}function t1(e,n){const s=e.cwd??e.packagePath??".",a=e.scriptName;return I(V("/dev-server/start",n),{method:"POST",body:JSON.stringify({command:e.command,scriptName:a,scriptId:a,cwd:s,packagePath:e.packagePath})}).then(Mr)}function n1(e){return I(V("/dev-server/stop",e),{method:"POST"}).then(Mr)}function s1(e){return I(V("/dev-server/restart",e),{method:"POST"}).then(Mr)}async function i1(e,n){const s=typeof e=="string"?{url:e}:e;try{const a=await I(V("/dev-server/preview-url",n),{method:"POST",body:JSON.stringify(s)});return Mr(a)}catch(a){if(a instanceof Error&&/\/dev-server\/preview-url/.test(a.message)){const r=await I(V("/dev-server/preview-url",n),{method:"PUT",body:JSON.stringify(s)});return Mr(r)}throw a}}function Q3(e){return Ss(V("/dev-server/logs/stream",e))}async function X3(e){try{return(await I(V("/devserver",e))).sessions??[]}catch{try{const n=await Qu(e);return[{config:{id:n.id??"default",name:n.name??"Dev Server",command:n.command??"",cwd:n.cwd??"."},status:n.status,runtime:n.pid?{pid:n.pid,startedAt:n.startedAt??new Date().toISOString(),exitCode:n.exitCode??void 0,previewUrl:n.previewUrl}:void 0,previewUrl:n.previewUrl??n.detectedUrl??void 0,logHistory:(n.logs??[]).map(a=>({timestamp:new Date().toISOString(),stream:a.startsWith("[stderr]")?"stderr":"stdout",text:a.replace(/^\[stderr\]\s*/,"")}))}]}catch{return[]}}}async function Z3(e,n){try{return await I(V(`/devserver/${encodeURIComponent(e)}`,n))}catch{try{const s=await Qu(n);return!e||e==="default"||e===s.id?{config:{id:s.id??"default",name:s.name??"Dev Server",command:s.command??"",cwd:s.cwd??"."},status:s.status,runtime:s.pid?{pid:s.pid,startedAt:s.startedAt??new Date().toISOString(),exitCode:s.exitCode??void 0,previewUrl:s.previewUrl}:void 0,previewUrl:s.previewUrl??s.detectedUrl??void 0,logHistory:(s.logs??[]).map(a=>({timestamp:new Date().toISOString(),stream:a.startsWith("[stderr]")?"stderr":"stdout",text:a.replace(/^\[stderr\]\s*/,"")}))}:null}catch{return null}}}async function e5(e,n){try{return await I(V(`/devserver/${encodeURIComponent(e)}/start`,n),{method:"POST"})}catch{const s=await t1({command:""},n);return{config:{id:s.id??e,name:s.name??"Dev Server",command:s.command??"",cwd:s.cwd??"."},status:s.status,runtime:s.pid?{pid:s.pid,startedAt:s.startedAt??new Date().toISOString(),exitCode:s.exitCode??void 0,previewUrl:s.previewUrl}:void 0,previewUrl:s.previewUrl??s.detectedUrl??void 0,logHistory:(s.logs??[]).map(a=>({timestamp:new Date().toISOString(),stream:a.startsWith("[stderr]")?"stderr":"stdout",text:a.replace(/^\[stderr\]\s*/,"")}))}}}async function t5(e,n){try{return await I(V(`/devserver/${encodeURIComponent(e)}/stop`,n),{method:"POST"})}catch{const s=await n1(n);return{config:{id:s.id??e,name:s.name??"Dev Server",command:s.command??"",cwd:s.cwd??"."},status:s.status,runtime:s.pid?{pid:s.pid,startedAt:s.startedAt??new Date().toISOString(),exitCode:s.exitCode??void 0,previewUrl:s.previewUrl}:void 0,previewUrl:s.previewUrl??s.detectedUrl??void 0,logHistory:(s.logs??[]).map(a=>({timestamp:new Date().toISOString(),stream:a.startsWith("[stderr]")?"stderr":"stdout",text:a.replace(/^\[stderr\]\s*/,"")}))}}}async function n5(e,n){try{return await I(V(`/devserver/${encodeURIComponent(e)}/restart`,n),{method:"POST"})}catch{const s=await s1(n);return{config:{id:s.id??e,name:s.name??"Dev Server",command:s.command??"",cwd:s.cwd??"."},status:s.status,runtime:s.pid?{pid:s.pid,startedAt:s.startedAt??new Date().toISOString(),exitCode:s.exitCode??void 0,previewUrl:s.previewUrl}:void 0,previewUrl:s.previewUrl??s.detectedUrl??void 0,logHistory:(s.logs??[]).map(a=>({timestamp:new Date().toISOString(),stream:a.startsWith("[stderr]")?"stderr":"stdout",text:a.replace(/^\[stderr\]\s*/,"")}))}}}async function s5(e,n,s){try{const a=await I(V(`/devserver/${encodeURIComponent(e)}/preview`,s),{method:"POST",body:JSON.stringify({url:n})});return{url:a.url??null,source:a.source??null}}catch{const a=await i1({url:n},s);return{url:a.previewUrl??a.manualUrl??null,source:"manual"}}}async function i5(e){try{return(await I(V("/devserver/detect",e))).candidates??[]}catch{try{return(await e1(e)).map(s=>({name:s.name,command:s.command,cwd:s.cwd,scriptName:s.scriptName,packagePath:s.packagePath}))}catch{return[]}}}function a5(e,n){return Ss(V(`/devserver/${encodeURIComponent(e)}/logs/stream`,n))}function Go(e,n,s=25e3){const a=setInterval(()=>{Z0(e,n).catch(()=>{})},s);return{stop:()=>{clearInterval(a)}}}function a1(e,n){return Ss(V(`/planning/${encodeURIComponent(e)}/stream`,n))}function r1(e,n){return Ss(V(`/agents/onboarding/${encodeURIComponent(e)}/stream`,n))}function r5(e,n,s,a){const r=r1(e,n),o=Ur(r,{events:{thinking:l=>{try{s.onThinking?.(JSON.parse(l.data))}catch{s.onThinking?.(l.data)}},question:l=>{try{s.onQuestion?.(JSON.parse(l.data))}catch{}},summary:l=>{try{s.onSummary?.(JSON.parse(l.data))}catch{}},error:l=>{try{const c=JSON.parse(l.data);s.onError?.(c.message||c)}catch{s.onError?.(l.data||"Stream error")}},complete:()=>{s.onComplete?.()}}},{maxReconnectAttempts:a?.maxReconnectAttempts,onConnectionStateChange:s.onConnectionStateChange,onFatalError:l=>s.onError?.(l)});return{close:o.close,isConnected:o.isConnected}}function o1(e,n,s,a){const r=a1(e,n);let o=null,l=null;const c=()=>{o?.stop(),o=null},d=Ur(r,{onOpen:()=>{c(),o=Go(e,n)},onMessage:u=>{u.data.startsWith(":")},events:{thinking:u=>{try{s.onThinking?.(JSON.parse(u.data))}catch{s.onThinking?.(u.data)}},question:u=>{try{s.onQuestion?.(JSON.parse(u.data))}catch(h){console.error("[planning] Failed to parse question event:",h)}},summary:u=>{try{s.onSummary?.(JSON.parse(u.data))}catch(h){console.error("[planning] Failed to parse summary event:",h)}},error:u=>{try{const h=JSON.parse(u.data);s.onError?.(h.message||h)}catch{s.onError?.(u.data||"Stream error")}l?.close()},complete:()=>{s.onComplete?.(),l?.close()}}},{maxReconnectAttempts:a?.maxReconnectAttempts,onConnectionStateChange:s.onConnectionStateChange,onFatalError:u=>{c(),s.onError?.(u)}});return l={close:()=>{c(),d.close()},isConnected:d.isConnected},l}function Ko(e,n){const s=new URLSearchParams;n?.scope&&s.set("scope",n.scope),n?.projectId&&s.set("projectId",n.projectId);const a=s.toString();return a?`${e}?${a}`:e}function l1(e){return I(Ko("/routines",e))}function c1(e,n){return I(Ko("/routines",n),{method:"POST",body:JSON.stringify(e)})}function ih(e,n,s){return I(Ko(`/routines/${e}`,s),{method:"PATCH",body:JSON.stringify(n)})}async function d1(e,n){await I(Ko(`/routines/${e}`,n),{method:"DELETE"})}function u1(e,n){return I(Ko(`/routines/${e}/trigger`,n),{method:"POST"})}function ah(e){const n=new URLSearchParams;e?.limit!==void 0&&n.set("limit",String(e.limit)),e?.since!==void 0&&n.set("since",e.since),e?.type!==void 0&&n.set("type",e.type),e?.projectId&&n.set("projectId",e.projectId);const s=n.size>0?`?${n.toString()}`:"";return I(`/activity${s}`)}function m1(e){const n=V("/activity",e);return I(n,{method:"DELETE"})}function Jo(e){return I(V("/workflow-steps",e))}function rh(e,n){return I(V("/workflow-steps",n),{method:"POST",body:JSON.stringify(e)})}function h1(e,n,s){return I(V(`/workflow-steps/${e}`,s),{method:"PATCH",body:JSON.stringify(n)})}function p1(e,n){return I(V(`/workflow-steps/${e}`,n),{method:"DELETE"})}function oh(e,n){return I(V(`/workflow-steps/${e}/refine`,n),{method:"POST"})}function f1(e,n){return I(V(`/tasks/${encodeURIComponent(e)}/workflow-results`,n))}function g1(){return I("/workflow-step-templates")}function b1(){return I("/plugin-workflow-step-templates")}function x1(e,n){return I(V(`/workflow-step-templates/${encodeURIComponent(e)}/create`,n),{method:"POST"})}function Lo(e){return I(V("/scripts",e))}function v1(e,n,s){return I(V("/scripts",s),{method:"POST",body:JSON.stringify({name:e,command:n})})}function y1(e,n){return I(V(`/scripts/${encodeURIComponent(e)}`,n),{method:"DELETE"})}async function Ab(e,n,s){return(await I(V("/ai/refine-text",s),{method:"POST",body:JSON.stringify({text:e,type:n})})).refined}const ll={RATE_LIMIT:"Too many refinement requests. Please wait an hour.",INVALID_TYPE:"Invalid refinement option selected.",NETWORK:"Failed to refine text. Please try again."};function Rb(e){if(!(e instanceof Error))return ll.NETWORK;const n=e.message.toLowerCase();return n.includes("rate limit")||n.includes("429")?ll.RATE_LIMIT:n.includes("invalid")&&n.includes("type")?ll.INVALID_TYPE:n.startsWith("text must")||n.includes("text is required")||n.includes("type is required")?e.message:ll.NETWORK}function w1(e,n){return I(V("/subtasks/start-streaming",n),{method:"POST",body:JSON.stringify({description:e})})}function k1(e,n,s){return I(V(`/subtasks/${encodeURIComponent(e)}/retry`,n),{method:"POST",...s?{body:JSON.stringify({tabId:s})}:{}})}function j1(e,n){return Ss(V(`/subtasks/${encodeURIComponent(e)}/stream`,n))}function N1(e,n,s,a){let r=null,o=null;const l=()=>{r?.stop(),r=null},c=Ur(j1(e,n),{onOpen:()=>{l(),r=Go(e,n)},events:{thinking:d=>{try{s.onThinking?.(JSON.parse(d.data))}catch{s.onThinking?.(d.data)}},subtasks:d=>{try{s.onSubtasks?.(JSON.parse(d.data))}catch(u){console.error("[subtasks] Failed to parse subtasks event:",u)}},error:d=>{try{const u=JSON.parse(d.data),h=typeof u=="string"&&u.length>0?u:null;s.onError?.(h||"Stream error")}catch{s.onError?.("Stream error")}o?.close()},complete:()=>{s.onComplete?.(),o?.close()}}},{maxReconnectAttempts:a?.maxReconnectAttempts,onConnectionStateChange:s.onConnectionStateChange,onFatalError:d=>{l(),s.onError?.(d)}});return o={close:()=>{l(),c.close()},isConnected:c.isConnected},o}function S1(e,n,s,a,r){return I(V("/subtasks/create-tasks",a),{method:"POST",body:JSON.stringify({sessionId:e,parentTaskId:s,...r?.branch!==void 0?{branch:r.branch}:{},...r?.baseBranch!==void 0?{baseBranch:r.baseBranch}:{},...r?.branchSelection?{branchSelection:r.branchSelection}:{},...r?.branchAssignment?{branchAssignment:r.branchAssignment}:{},subtasks:n.map(o=>({tempId:o.id,title:o.title,description:o.description,size:o.suggestedSize,dependsOn:o.dependsOn}))})})}function Ib(e,n,s){return I(V("/subtasks/cancel",n),{method:"POST",body:JSON.stringify({sessionId:e,tabId:s})})}function V(e,n){if(!n)return e;const s=e.includes("?")?"&":"?";return`${e}${s}projectId=${encodeURIComponent(n)}`}function C1(e,n,s){if(!n||n===s)return e;const a="/api",r=e.startsWith(a)?e.slice(a.length):e;return`/proxy/${encodeURIComponent(n)}${r}`}function Yo(e,n){const{nodeId:s,localNodeId:a,...r}=n??{},o=C1(e,s,a);return I(o,r)}function Hr(e,n){const s=new URLSearchParams;e?.state&&s.set("state",e.state),e?.role&&s.set("role",e.role),e?.includeEphemeral===!0&&s.set("includeEphemeral","true"),n&&s.set("projectId",n);const a=s.size>0?`?${s.toString()}`:"";return I(`/agents${a}`)}function gu(e,n){return I(V(`/agents/${encodeURIComponent(e)}`,n))}function E1(e,n){return I(V("/agents",n),{method:"POST",body:JSON.stringify(e)})}function _1(e,n,s){return I(V(`/agents/${encodeURIComponent(e)}`,s),{method:"PATCH",body:JSON.stringify(n)})}async function o5(e,n,s){const a=new FormData;a.append("file",n);const r=await fetch(Ss(V(`/agents/${encodeURIComponent(e)}/avatar`,s)),{method:"POST",headers:Ni(),body:a}),o=await r.json();if(!r.ok)throw new Error(o.error||"Avatar upload failed");return o}function l5(e,n){return I(V(`/agents/${encodeURIComponent(e)}/avatar`,n),{method:"DELETE"})}function c5(e,n){return I(V(`/agents/${encodeURIComponent(e)}/upgrade-heartbeat-procedure`,n),{method:"POST"})}function d5(e,n,s){return I(V(`/agents/${encodeURIComponent(e)}/instructions`,s),{method:"PATCH",body:JSON.stringify(n)})}function u5(e,n,s){return I(V(`/agents/${encodeURIComponent(e)}/soul`,s),{method:"PATCH",body:JSON.stringify({soul:n})})}function m5(e,n,s){return I(V(`/agents/${encodeURIComponent(e)}/memory`,s),{method:"PATCH",body:JSON.stringify({memory:n})})}function h5(e,n){return I(V(`/agents/${encodeURIComponent(e)}/memory/files`,n))}function p5(e,n,s){const a=`path=${encodeURIComponent(n)}`;return I(V(`/agents/${encodeURIComponent(e)}/memory/file?${a}`,s))}function f5(e,n,s,a){return I(V(`/agents/${encodeURIComponent(e)}/memory/file`,a),{method:"PUT",body:JSON.stringify({path:n,content:s})})}function M1(e,n,s){return I(V(`/agents/${encodeURIComponent(e)}/state`,s),{method:"POST",body:JSON.stringify({state:n})})}function A1(e,n){return I(V(`/agents/${encodeURIComponent(e)}`,n),{method:"DELETE"})}function g5(e,n,s){const a=new URLSearchParams;n!==void 0&&a.set("limit",String(n)),s&&a.set("projectId",s);const r=a.size>0?`?${a.toString()}`:"";return I(`/agents/${encodeURIComponent(e)}/runs${r}`)}function b5(e,n,s){return I(V(`/agents/${encodeURIComponent(e)}/runs/${encodeURIComponent(n)}`,s))}function x5(e,n,s){return I(V(`/agents/${encodeURIComponent(e)}/runs/${encodeURIComponent(n)}/logs`,s))}function v5(e,n,s){const a=s?.source??"manual",r=s?.triggerDetail??"Agent activated via dashboard";return I(V(`/agents/${encodeURIComponent(e)}/runs`,n),{method:"POST",body:JSON.stringify({source:a,triggerDetail:r})})}function y5(e,n){return I(V(`/agents/${encodeURIComponent(e)}/runs/stop`,n),{method:"POST"})}function R1(e){return I(V("/agents/stats",e))}function w5(e,n){return I(V(`/agents/${encodeURIComponent(e)}/chain-of-command`,n))}function k5(e,n){const s=new URLSearchParams;e&&s.set("projectId",e),n?.includeEphemeral&&s.set("includeEphemeral","true");const a=s.toString();return I(`/agents/org-tree${a?`?${a}`:""}`)}function j5(e,n){return I(V(`/agents/${encodeURIComponent(e)}/children`,n)).catch(s=>{if(s.message.includes("not found"))return[];throw s})}function lh(e,n,s){return I(V(`/tasks/${encodeURIComponent(e)}/assign`,s),{method:"PATCH",body:JSON.stringify({agentId:n})})}function Tb(e){return{reviewState:{source:e.mode,summary:e.summary??void 0,items:e.items.map(n=>({id:n.itemId,body:n.body,author:{login:n.author},createdAt:n.createdAt??new Date(0).toISOString(),updatedAt:n.updatedAt??void 0,path:n.filePath,threadId:n.threadId,htmlUrl:n.url,state:n.reviewState??void 0,isResolved:n.isResolved})),addressing:[],lastRefreshedAt:e.fetchedAt??void 0,refreshStatus:"ready",refreshSource:"initial-load"},automationStatus:null}}async function I1(e,n){const s=await I(V(`/tasks/${encodeURIComponent(e)}/review`,n));return Tb(s)}async function T1(e,n){const s=await I(V(`/tasks/${encodeURIComponent(e)}/review/refresh`,n),{method:"POST"});return Tb(s)}function P1(e,n,s){return I(V(`/tasks/${encodeURIComponent(e)}/review/address`,s),{method:"POST",body:JSON.stringify({selectedItems:n,tab:"review"})})}function N5(e,n){return I(V(`/agents/${encodeURIComponent(e)}/tasks`,n))}function S5(){return I("/agents/companies")}function C5(e,n){return I(V("/agents/generate/start",n),{method:"POST",body:JSON.stringify({role:e})})}function E5(e,n){return I(V("/agents/generate/spec",n),{method:"POST",body:JSON.stringify({sessionId:e})})}function _5(e,n){return I(V(`/agents/generate/${encodeURIComponent(e)}`,n),{method:"DELETE"})}function M5(e){return I(V("/backups",e))}function A5(e){return I(V("/backups",e),{method:"POST"})}function R5(e,n){const s=V("/settings/export",n),a=`${s}${s.includes("?")?"&":"?"}scope=${encodeURIComponent(e)}`;return I(a)}function I5(e,n,s){return I(V("/settings/import",s),{method:"POST",body:JSON.stringify({data:e,scope:n?.scope??"both",merge:n?.merge??!0})})}function $1(e){return Array.isArray(e.nodeMappings)||Array.isArray(e.projectNodeMappings)||Array.isArray(e.pathMappings)}function ch(){return I("/projects/across-nodes")}function ec(){return I("/nodes")}function T5(){return I("/docker/nodes")}function P5(e){return I(`/docker/nodes/${encodeURIComponent(e)}/container-status`)}function $5(e,n){const s=new URLSearchParams;typeof n?.tail=="number"&&s.set("tail",String(n.tail));const a=s.size>0?`?${s.toString()}`:"";return I(`/docker/nodes/${encodeURIComponent(e)}/logs${a}`)}function D5(e){return I("/docker-nodes",{method:"POST",body:JSON.stringify(e)})}function D1(e){return I("/nodes",{method:"POST",body:JSON.stringify(e)})}function L1(e){return I("/nodes/discover-projects",{method:"POST",body:JSON.stringify(e)})}function O1(e,n){return I(`/nodes/${encodeURIComponent(e)}`,{method:"PATCH",body:JSON.stringify(n)})}function F1(e){return I(`/nodes/${encodeURIComponent(e)}/docker-config`)}function z1(e,n){return I(`/nodes/${encodeURIComponent(e)}/docker-config`,{method:"PATCH",body:JSON.stringify(n)})}function B1(e){return I(`/nodes/${encodeURIComponent(e)}/docker-config/diff`)}function dh(e){return I(`/nodes/${encodeURIComponent(e)}`,{method:"DELETE"})}async function U1(e){const n=await I(`/nodes/${encodeURIComponent(e)}/health-check`,{method:"POST"});return{nodeId:n.nodeId??e,status:n.status,responseTimeMs:n.responseTimeMs,error:n.error,checkedAt:n.checkedAt??new Date().toISOString()}}async function L5(){return I("/mesh/state")}function O5(e,n,s,a){const r=s&&s!==a?s:void 0,o=new URLSearchParams;e&&o.set("path",e),n&&o.set("showHidden","true"),r&&o.set("nodeId",r);const l=_r();l&&o.set("fn_token",l);const c=o.toString(),d=`/browse-directory${c?`?${c}`:""}`;return I(d)}function H1(e){return I("/projects",{method:"POST",body:JSON.stringify(e)})}function Pb(e){return I(`/projects/${encodeURIComponent(e)}`,{method:"DELETE"})}function q1(e,n,s){return I(`/projects/${encodeURIComponent(e)}/path-mappings/${encodeURIComponent(n)}`,{method:"PUT",body:JSON.stringify({path:s})})}function uh(e){return I(`/projects/${encodeURIComponent(e)}/health`)}function V1(e){return I(V("/executor/stats",e))}function W1(e){return I(V("/system-stats",e))}function G1(e){return I(V("/kill-vitest",e),{method:"POST"})}function mh(e){const n=new URLSearchParams;e?.limit!==void 0&&n.set("limit",String(e.limit)),e?.since&&n.set("since",e.since),e?.projectId&&n.set("projectId",e.projectId),e?.type&&n.set("type",e.type);const s=n.size>0?`?${n.toString()}`:"";return I(`/activity-feed${s}`)}function K1(e){return I(`/projects/${encodeURIComponent(e)}/pause`,{method:"POST"})}function J1(e){return I(`/projects/${encodeURIComponent(e)}/resume`,{method:"POST"})}function F5(){return I("/global-concurrency")}function z5(e){return I("/global-concurrency",{method:"PUT",body:JSON.stringify(e)})}function Y1(e,n){return I(`/projects/${encodeURIComponent(e)}`,{method:"PATCH",body:JSON.stringify(n)})}function $b(e,n,s){const a=new URLSearchParams;n&&a.set("worktree",n),s&&a.set("projectId",s);const r=a.size>0?`?${a.toString()}`:"";return I(`/tasks/${encodeURIComponent(e)}/diff${r}`)}function Q1(e,n){return I(V(`/tasks/${encodeURIComponent(e)}/commit-associations`,n))}function X1(e){return I(V("/missions",e))}function Z1(e,n){return I(V("/missions",n),{method:"POST",body:JSON.stringify(e)})}function Db(e,n){return I(V(`/missions/${encodeURIComponent(e)}`,n))}function e0(e,n,s){return I(V(`/missions/${encodeURIComponent(e)}`,s),{method:"PATCH",body:JSON.stringify(n)})}function t0(e,n){return I(V(`/missions/${encodeURIComponent(e)}`,n),{method:"DELETE"})}function n0(e,n,s){const a=new URLSearchParams;a.set("limit",String(n.limit)),n?.offset!==void 0&&a.set("offset",String(n.offset));const r=a.size>0?`?${a.toString()}`:"";return I(V(`/missions/${encodeURIComponent(e)}/events${r}`,s))}function s0(e){return I(V("/missions/health",e))}function i0(e,n,s){return I(V(`/missions/${encodeURIComponent(e)}/milestones`,s),{method:"POST",body:JSON.stringify(n)})}function a0(e,n,s){return I(V(`/missions/milestones/${encodeURIComponent(e)}`,s),{method:"PATCH",body:JSON.stringify(n)})}function r0(e,n){return I(V(`/missions/milestones/${encodeURIComponent(e)}`,n),{method:"DELETE"})}function o0(e,n,s){return I(V(`/missions/milestones/${encodeURIComponent(e)}/slices`,s),{method:"POST",body:JSON.stringify(n)})}function l0(e,n,s){return I(V(`/missions/slices/${encodeURIComponent(e)}`,s),{method:"PATCH",body:JSON.stringify(n)})}function c0(e,n){return I(V(`/missions/slices/${encodeURIComponent(e)}`,n),{method:"DELETE"})}function d0(e,n){return I(V(`/missions/slices/${encodeURIComponent(e)}/activate`,n),{method:"POST"})}function u0(e,n,s){return I(V(`/missions/slices/${encodeURIComponent(e)}/features`,s),{method:"POST",body:JSON.stringify(n)})}function m0(e,n,s){return I(V(`/missions/features/${encodeURIComponent(e)}`,s),{method:"PATCH",body:JSON.stringify(n)})}function h0(e,n){return I(V(`/missions/features/${encodeURIComponent(e)}`,n),{method:"DELETE"})}function p0(e,n,s){return I(V(`/missions/features/${encodeURIComponent(e)}/link-task`,s),{method:"POST",body:JSON.stringify({taskId:n})})}function f0(e,n){return I(V(`/missions/features/${encodeURIComponent(e)}/unlink-task`,n),{method:"POST"})}function g0(e,n,s,a,r){return I(V(`/missions/features/${encodeURIComponent(e)}/triage`,a),{method:"POST",body:JSON.stringify({taskTitle:n,taskDescription:s,...r})})}function b0(e,n,s){return I(V(`/missions/slices/${encodeURIComponent(e)}/triage-all`,n),{method:"POST",body:JSON.stringify({})})}function Gc(e,n){return I(V(`/missions/milestones/${encodeURIComponent(e)}/assertions`,n))}function x0(e,n,s){return I(V(`/missions/milestones/${encodeURIComponent(e)}/assertions`,s),{method:"POST",body:JSON.stringify(n)})}function v0(e,n,s){return I(V(`/missions/assertions/${encodeURIComponent(e)}`,s),{method:"PATCH",body:JSON.stringify(n)})}function y0(e,n,s){return I(V(`/missions/features/${encodeURIComponent(e)}/assertions/${encodeURIComponent(n)}/link`,s),{method:"POST"})}function w0(e,n,s){return I(V(`/missions/features/${encodeURIComponent(e)}/assertions/${encodeURIComponent(n)}/unlink`,s),{method:"POST"})}function k0(e,n){return I(V(`/missions/assertions/${encodeURIComponent(e)}/features`,n))}function Kc(e,n){return I(V(`/missions/milestones/${encodeURIComponent(e)}/validation`,n))}function hh(e,n){return I(V(`/missions/milestones/${encodeURIComponent(e)}/validation-telemetry`,n))}function j0(e,n){return I(V(`/missions/features/${encodeURIComponent(e)}/validate`,n),{method:"POST"})}function ph(e,n){return I(V(`/missions/features/${encodeURIComponent(e)}/validation-loop`,n))}function N0(e,n,s){const a=new URLSearchParams;a.set("limit",String(n.limit)),n?.offset!==void 0&&a.set("offset",String(n.offset));const r=a.size>0?`?${a.toString()}`:"";return I(V(`/missions/features/${encodeURIComponent(e)}/validation-runs${r}`,s)).then(o=>o.runs)}function S0(e,n){return I(V(`/missions/validation-runs/${encodeURIComponent(e)}`,n))}function C0(e,n){return I(V(`/missions/${encodeURIComponent(e)}/resume`,n),{method:"POST"})}function E0(e,n){return I(V(`/missions/${encodeURIComponent(e)}/stop`,n),{method:"POST"})}function _0(e,n){return I(V(`/missions/${encodeURIComponent(e)}/start`,n),{method:"POST"})}function M0(e,n,s){return I(V(`/missions/${encodeURIComponent(e)}/autopilot`,s),{method:"PATCH",body:JSON.stringify(n)})}function A0(e,n,s){return I(V("/missions/interview/start",n),{method:"POST",body:JSON.stringify({missionTitle:e,modelProvider:s?.modelProvider,modelId:s?.modelId})})}function R0(e,n,s,a){return I(V("/missions/interview/respond",s),{method:"POST",body:JSON.stringify({sessionId:e,responses:n,tabId:a})})}function I0(e,n,s){return I(V(`/missions/interview/${encodeURIComponent(e)}/retry`,n),{method:"POST",...s?{body:JSON.stringify({tabId:s})}:{}})}function Lb(e,n,s){return I(V("/missions/interview/cancel",n),{method:"POST",body:JSON.stringify({sessionId:e,tabId:s})})}async function T0(e){const n=e?`?${new URLSearchParams({projectId:e}).toString()}`:"";return(await I(`/missions/interview/drafts${n}`)).drafts??[]}function P0(e,n,s){return I(V(`/missions/interview/drafts/${encodeURIComponent(e)}/discard`,n),{method:"POST",body:JSON.stringify({tabId:s})})}function $0(e,n,s,a){return I(V("/missions/interview/create-mission",s),{method:"POST",body:JSON.stringify({sessionId:e,summary:n})})}function D0(e,n,s,a){const r=Ss(V(`/missions/interview/${encodeURIComponent(e)}/stream`,n));let o=null,l=null;const c=()=>{o?.stop(),o=null},d=Ur(r,{onOpen:()=>{c(),o=Go(e,n)},onMessage:u=>{u.data.startsWith(":")},events:{thinking:u=>{try{s.onThinking?.(JSON.parse(u.data))}catch{s.onThinking?.(u.data)}},question:u=>{try{s.onQuestion?.(JSON.parse(u.data))}catch(h){console.error("[mission-interview] Failed to parse question event:",h)}},summary:u=>{try{s.onSummary?.(JSON.parse(u.data))}catch(h){console.error("[mission-interview] Failed to parse summary event:",h)}},error:u=>{try{const h=JSON.parse(u.data);s.onError?.(h.message||h)}catch{s.onError?.(u.data||"Stream error")}l?.close()},complete:()=>{s.onComplete?.(),l?.close()}}},{maxReconnectAttempts:a?.maxReconnectAttempts,onConnectionStateChange:s.onConnectionStateChange,onFatalError:u=>{c(),s.onError?.(u)}});return l={close:()=>{c(),d.close()},isConnected:d.isConnected},l}function Qo(e,n,s){return V(`/missions/milestones/${encodeURIComponent(e)}/interview${n}`,s)}function Xo(e,n,s){return V(`/missions/slices/${encodeURIComponent(e)}/interview${n}`,s)}function L0(e,n){return I(Qo(e,"/start",n),{method:"POST"})}function O0(e,n,s,a){return I(Qo(e,"/respond",s),{method:"POST",body:JSON.stringify({sessionId:e,responses:n,tabId:a})})}function F0(e,n,s,a){const r=Ss(Qo(e,`/${encodeURIComponent(e)}/stream`,n));let o=null,l=null;const c=()=>{o?.stop(),o=null},d=Ur(r,{onOpen:()=>{c(),o=Go(e,n)},onMessage:u=>{u.data.startsWith(":")},events:{thinking:u=>{try{s.onThinking?.(JSON.parse(u.data))}catch{s.onThinking?.(u.data)}},question:u=>{try{s.onQuestion?.(JSON.parse(u.data))}catch(h){console.error("[milestone-interview] Failed to parse question event:",h)}},summary:u=>{try{s.onSummary?.(JSON.parse(u.data))}catch(h){console.error("[milestone-interview] Failed to parse summary event:",h)}},error:u=>{try{const h=JSON.parse(u.data);s.onError?.(h.message||h)}catch{s.onError?.(u.data||"Stream error")}l?.close()},complete:()=>{s.onComplete?.(),l?.close()}}},{maxReconnectAttempts:a?.maxReconnectAttempts,onConnectionStateChange:s.onConnectionStateChange,onFatalError:u=>{c(),s.onError?.(u)}});return l={close:()=>{c(),d.close()},isConnected:d.isConnected},l}function z0(e,n,s){return I(Qo(e,"/apply",s),{method:"POST",body:JSON.stringify({sessionId:e,summary:n})})}function B0(e,n){return I(Qo(e,"/skip",n),{method:"POST"})}function U0(e,n){return I(Xo(e,"/start",n),{method:"POST"})}function H0(e,n,s,a){return I(Xo(e,"/respond",s),{method:"POST",body:JSON.stringify({sessionId:e,responses:n,tabId:a})})}function q0(e,n,s,a){const r=Ss(Xo(e,`/${encodeURIComponent(e)}/stream`,n));let o=null,l=null;const c=()=>{o?.stop(),o=null},d=Ur(r,{onOpen:()=>{c(),o=Go(e,n)},onMessage:u=>{u.data.startsWith(":")},events:{thinking:u=>{try{s.onThinking?.(JSON.parse(u.data))}catch{s.onThinking?.(u.data)}},question:u=>{try{s.onQuestion?.(JSON.parse(u.data))}catch(h){console.error("[slice-interview] Failed to parse question event:",h)}},summary:u=>{try{s.onSummary?.(JSON.parse(u.data))}catch(h){console.error("[slice-interview] Failed to parse summary event:",h)}},error:u=>{try{const h=JSON.parse(u.data);s.onError?.(h.message||h)}catch{s.onError?.(u.data||"Stream error")}l?.close()},complete:()=>{s.onComplete?.(),l?.close()}}},{maxReconnectAttempts:a?.maxReconnectAttempts,onConnectionStateChange:s.onConnectionStateChange,onFatalError:u=>{c(),s.onError?.(u)}});return l={close:()=>{c(),d.close()},isConnected:d.isConnected},l}function V0(e,n,s){return I(Xo(e,"/apply",s),{method:"POST",body:JSON.stringify({sessionId:e,summary:n})})}function W0(e,n){return I(Xo(e,"/skip",n),{method:"POST"})}async function G0(e,n){try{return await I(V(`/missions/features/${encodeURIComponent(e)}/preview-description`,n),{method:"POST"})}catch{throw new Error("Preview endpoint not available")}}function B5(e){return I(V("/todos",e))}function U5(e,n){const s={title:e};return I(V("/todos",n),{method:"POST",body:JSON.stringify(s)})}function H5(e,n,s){const a={title:n};return I(V(`/todos/${encodeURIComponent(e)}`,s),{method:"PATCH",body:JSON.stringify(a)})}function q5(e,n){return I(V(`/todos/${encodeURIComponent(e)}`,n),{method:"DELETE"})}function V5(e,n,s){const a={text:n};return I(V(`/todos/${encodeURIComponent(e)}/items`,s),{method:"POST",body:JSON.stringify(a)})}function W5(e,n,s){const a=n;return I(V(`/todos/items/${encodeURIComponent(e)}`,s),{method:"PATCH",body:JSON.stringify(a)})}function G5(e,n){return I(V(`/todos/items/${encodeURIComponent(e)}`,n),{method:"DELETE"})}function K5(e,n,s){return I(V(`/todos/${encodeURIComponent(e)}/items/reorder`,s),{method:"POST",body:JSON.stringify({itemIds:n})})}function Ar(e){if(!e)return[];try{const n=JSON.parse(e);return Array.isArray(n)?n:[]}catch{return[]}}async function Xu(e,n){const s=new URLSearchParams;e&&s.set("projectId",e),n?.includeCompleted&&s.set("includeCompleted","1"),n?.includeArchived&&s.set("includeArchived","1");const a=s.toString(),r=await fetch(Ss(`/ai-sessions${a?`?${a}`:""}`),{headers:Ni()});return r.ok?(await r.json()).sessions??[]:[]}async function K0(e){return I(`/ai-sessions/${encodeURIComponent(e)}/archive`,{method:"POST"})}async function J0(e){return I(`/ai-sessions/${encodeURIComponent(e)}/unarchive`,{method:"POST"})}async function $i(e){const n=await fetch(Ss(`/ai-sessions/${encodeURIComponent(e)}`),{headers:Ni()});return n.ok?n.json():null}async function Y0(e,n){const s=await I(`/ai-sessions/${encodeURIComponent(e)}/lock`,{method:"POST",body:JSON.stringify({tabId:n})});return{acquired:s.acquired,currentHolder:s.currentHolder??null}}function Q0(e,n){return I(`/ai-sessions/${encodeURIComponent(e)}/lock`,{method:"DELETE",body:JSON.stringify({tabId:n})})}function X0(e,n){return I(`/ai-sessions/${encodeURIComponent(e)}/lock/force`,{method:"POST",body:JSON.stringify({tabId:n})})}async function Ob(e){await fetch(Ss(`/ai-sessions/${encodeURIComponent(e)}`),{method:"DELETE",headers:Ni()})}function Z0(e,n){return I(V(`/ai-sessions/${encodeURIComponent(e)}/ping`,n),{method:"POST"})}function eC(e,n,s){return I(V(`/ai-sessions/${encodeURIComponent(e)}/draft`,s),{method:"PATCH",body:JSON.stringify(n)})}function tC(e,n){return I(V(`/planning/${encodeURIComponent(e)}/summarize-draft-title`,n),{method:"POST"})}function nC(e,n){const s=new URLSearchParams;s.set("limit",String(e.limit)),e?.offset!==void 0&&s.set("offset",String(e.offset)),e?.unreadOnly&&s.set("unreadOnly","true"),e?.type&&s.set("type",e.type),n&&s.set("projectId",n);const a=s.size>0?`?${s.toString()}`:"";return I(`/messages/inbox${a}`)}function sC(e,n){const s=new URLSearchParams;s.set("limit",String(e.limit)),e?.offset!==void 0&&s.set("offset",String(e.offset)),e?.type&&s.set("type",e.type),n&&s.set("projectId",n);const a=s.size>0?`?${s.toString()}`:"";return I(`/messages/outbox${a}`)}function Fb(e){return I(V("/messages/unread-count",e))}function iC(e,n){return I(V("/messages",n),{method:"POST",body:JSON.stringify(e)})}function aC(e,n){return I(V(`/messages/${encodeURIComponent(e)}/read`,n),{method:"POST"})}function rC(e){return I(V("/messages/read-all",e),{method:"POST"})}function oC(e,n){return I(V(`/messages/${encodeURIComponent(e)}`,n),{method:"DELETE"})}function lC(e,n,s){const a=`/messages/conversation/${encodeURIComponent(n)}/${encodeURIComponent(e)}`;return I(V(a,s))}function cC(e,n){return I(V(`/agents/${encodeURIComponent(e)}/mailbox`,n))}function dC(e){return I(V("/agents/mailbox/all",e))}function cl(e,n){const s=new URLSearchParams;e?.status&&s.set("status",e.status),e?.limit!==void 0&&s.set("limit",String(e.limit)),e?.offset!==void 0&&s.set("offset",String(e.offset)),n&&s.set("projectId",n);const a=s.size>0?`?${s.toString()}`:"";return I(`/approvals${a}`)}function fh(e,n){return I(V(`/approvals/${encodeURIComponent(e)}`,n))}function uC(e,n,s){return I(V(`/approvals/${encodeURIComponent(e)}/decision`,s),{method:"POST",body:JSON.stringify(n)})}function J5(e,n,s){const a=new URLSearchParams;a.set("limit",String(n)),s&&a.set("projectId",s);const r=a.size>0?`?${a.toString()}`:"";return I(`/agents/${encodeURIComponent(e)}/reflections${r}`)}function Y5(e,n){return I(V(`/agents/${encodeURIComponent(e)}/reflections`,n),{method:"POST"})}function Q5(e,n,s){const a=new URLSearchParams;s&&a.set("projectId",s);const r=a.size>0?`?${a.toString()}`:"";return I(`/agents/${encodeURIComponent(e)}/performance${r}`)}function X5(e,n,s){const a=new URLSearchParams;a.set("limit",String(n.limit)),n?.category&&a.set("category",n.category),s&&a.set("projectId",s);const r=a.size>0?`?${a.toString()}`:"";return I(`/agents/${encodeURIComponent(e)}/ratings${r}`)}function Z5(e,n,s){return I(V(`/agents/${encodeURIComponent(e)}/ratings`,s),{method:"POST",body:JSON.stringify(n)})}function e8(e,n){return I(V(`/agents/${encodeURIComponent(e)}/ratings/summary`,n))}function t8(e,n,s){return I(V(`/agents/${encodeURIComponent(e)}/ratings/${encodeURIComponent(n)}`,s),{method:"DELETE"})}function n8(e,n){return I(V(`/agents/${encodeURIComponent(e)}/budget`,n))}function s8(e,n){return I(V(`/agents/${encodeURIComponent(e)}/budget/reset`,n),{method:"POST"})}async function i8(e){return I(V("/plugins",e))}async function a8(e,n){return I(V("/plugins",n),{method:"POST",body:JSON.stringify({mode:"install",...e})})}async function r8(e,n){return I(V(`/plugins/${encodeURIComponent(e)}/enable`,n),{method:"POST"})}async function o8(e,n){return I(V(`/plugins/${encodeURIComponent(e)}/disable`,n),{method:"POST"})}async function l8(e,n){return I(V(`/plugins/${encodeURIComponent(e)}`,n),{method:"DELETE"})}async function c8(e,n){return I(V(`/plugins/${encodeURIComponent(e)}/settings`,n))}async function d8(e,n,s){return I(V(`/plugins/${encodeURIComponent(e)}/settings`,s),{method:"PUT",body:JSON.stringify({settings:n})})}async function u8(e,n){return I(V(`/plugins/${encodeURIComponent(e)}/setup-status`,n))}async function m8(e,n){return I(V(`/plugins/${encodeURIComponent(e)}/setup/install`,n),{method:"POST"})}async function h8(e,n){return I(V(`/plugins/${encodeURIComponent(e)}/reload`,n),{method:"POST"})}async function p8(e,n,s){return I(V(`/plugins/${encodeURIComponent(e)}`,s),{method:"PATCH",body:JSON.stringify(n)})}async function f8(e,n){return I(V(`/plugins/${encodeURIComponent(e)}/rescan`,n),{method:"POST"})}async function mC(e){return I(V("/plugins/ui-slots",e))}async function hC(e){return I(V("/plugins/dashboard-views",e))}async function g8(e){return I(V("/plugins/runtimes",e))}async function pC(e){return(await I(V("/skills/discovered",e))).skills}async function b8(e,n,s){return I(V("/skills/execution",s),{method:"PATCH",body:JSON.stringify({skillId:e,enabled:n})})}async function x8(e,n,s){const a=new URLSearchParams;e&&a.set("q",e),a.set("limit",String(n));const r=a.size>0?`?${a.toString()}`:"";return I(V(`/skills/catalog${r}`,s))}async function v8(e,n){return(await I(V(`/skills/${encodeURIComponent(e)}/content`,n))).content}function gh(e,n){const s=new URLSearchParams;e&&s.set("projectId",e);const a=s.toString();return I(`/chat/sessions${a?`?${a}`:""}`)}async function fC(e,n){const s=e.agentId.trim();if(!s)throw new Error("agentId is required");const a=e.modelProvider?.trim(),r=e.modelId?.trim();if(a&&!r||!a&&r)throw new Error("Both modelProvider and modelId must be provided together, or neither should be provided");const o=new URLSearchParams;return o.set("lookup","resume"),o.set("agentId",s),n&&o.set("projectId",n),a&&r&&(o.set("modelProvider",a),o.set("modelId",r)),{session:(await I(`/chat/sessions?${o.toString()}`)).sessions[0]??null}}function gC(e,n){return I(V("/chat/sessions",n),{method:"POST",body:JSON.stringify(e)})}function Jc(e,n){return I(V(`/chat/sessions/${encodeURIComponent(e)}`,n))}function y8(e,n,s){return I(V(`/chat/sessions/${encodeURIComponent(e)}`,s),{method:"PATCH",body:JSON.stringify(n)})}function w8(e,n){return I(V(`/chat/sessions/${encodeURIComponent(e)}`,n),{method:"DELETE"})}function to(e,n,s){const a=new URLSearchParams;n?.limit!==void 0&&a.set("limit",String(n.limit)),n?.offset!==void 0&&a.set("offset",String(n.offset)),n?.before&&a.set("before",n.before);const r=a.toString();return I(V(`/chat/sessions/${encodeURIComponent(e)}/messages${r?`?${r}`:""}`,s))}function k8(e={},n){const s=new URLSearchParams;n&&s.set("projectId",n),e.status&&s.set("status",e.status),e.agentId&&s.set("agentId",e.agentId);const a=s.toString();return I(`/chat/rooms${a?`?${a}`:""}`)}function j8(e,n){const s={...e,...n?{projectId:n}:{}};return I(V("/chat/rooms",n),{method:"POST",body:JSON.stringify(s)})}function N8(e,n){return I(V(`/chat/rooms/${encodeURIComponent(e)}`,n),{method:"DELETE"})}function S8(e,n){return I(V(`/chat/rooms/${encodeURIComponent(e)}/members`,n))}function C8(e,n,s){const a=new URLSearchParams;n?.limit!==void 0&&a.set("limit",String(n.limit)),n?.offset!==void 0&&a.set("offset",String(n.offset)),n?.before&&a.set("before",n.before);const r=a.toString();return I(V(`/chat/rooms/${encodeURIComponent(e)}/messages${r?`?${r}`:""}`,s))}function E8(e,n,s){return I(V(`/chat/rooms/${encodeURIComponent(e)}/messages`,s),{method:"POST",body:JSON.stringify(n)})}function bC(e,n){return I(V(`/chat/sessions/${encodeURIComponent(e)}/cancel`,n),{method:"POST"})}function xC(e){if(!e||typeof e!="object")return null;const n=e,s=typeof n.summary=="string"?n.summary.trim():"";if(!s)return null;const a=(()=>{const r=n.reference;if(!r||typeof r!="object")return;const o=r,l=typeof o.kind=="string"?o.kind.trim():"",c=typeof o.id=="string"?o.id.trim():"";if(!(!l||!c))return{kind:l,id:c,...typeof o.label=="string"&&o.label.trim()?{label:o.label.trim()}:{}}})();return{summary:s,...typeof n.errorClass=="string"&&n.errorClass.trim()?{errorClass:n.errorClass.trim()}:{},...typeof n.code=="string"&&n.code.trim()?{code:n.code.trim()}:{},...typeof n.detail=="string"&&n.detail.trim()?{detail:n.detail.trim()}:{},...a?{reference:a}:{}}}function zb(e){try{const n=JSON.parse(e),s=xC(n);return s||(n&&typeof n=="object"&&typeof n.message=="string"?n.message:typeof n=="string"?n:e||"Stream error")}catch{return e||"Stream error"}}function vC(e,n,s,a,r,o){const l=Ss(V(`/chat/sessions/${encodeURIComponent(e)}/messages`,r)),c=new AbortController;let d=!1,u=!1,h=!1;const m=Math.max(1e3,6e4);let f=null;const p=()=>{f&&(clearTimeout(f),f=null)},g=()=>{h||(h=!0,p())},w=(v,b)=>{if(v)switch(g(),v){case"thinking":try{s.onThinking?.(JSON.parse(b))}catch{s.onThinking?.(b)}break;case"text":try{s.onText?.(JSON.parse(b))}catch{s.onText?.(b)}break;case"tool_start":try{s.onToolStart?.(JSON.parse(b))}catch{}break;case"tool_end":try{s.onToolEnd?.(JSON.parse(b))}catch{}break;case"fallback":try{s.onFallback?.(JSON.parse(b))}catch{}break;case"done":u=!0;try{const y=JSON.parse(b);s.onDone?.({messageId:typeof y.messageId=="string"?y.messageId:"",...y.message&&typeof y.message=="object"?{message:y.message}:{}})}catch{s.onDone?.({messageId:""})}break;case"error":u=!0,s.onError?.(zb(b));break}};return(async()=>{try{const v=Array.isArray(a)&&a.length>0,b=v?(()=>{const E=new FormData;return E.append("content",n),a.forEach(_=>E.append("attachments",_)),E})():JSON.stringify({content:n}),y=await fetch(l,{method:"POST",headers:v?Ni():Ni({"Content-Type":"application/json"}),body:b,signal:c.signal});if(!y.ok){const E=await y.text();let _=`Request failed: ${y.status}`;try{_=JSON.parse(E).error||_}catch{}s.onError?.(_);return}if(!y.body){s.onError?.("No response body");return}s.onConnectionStateChange?.("connected"),f=setTimeout(()=>{u||d||h||(u=!0,s.onError?.("Timed out waiting for first response event"),c.abort())},m);const j=y.body.getReader(),S=new TextDecoder;let C="",x="",k=[];const R=(E,_=!1)=>{C+=E;const G=C.split(`
643
- `);C=G.pop()||"",_&&C.length>0&&(G.push(C),C="");for(const H of G){const A=H.endsWith("\r")?H.slice(0,-1):H;if(A.startsWith("event:"))x=A.slice(6).trim();else if(A.startsWith("data:")){const P=A.slice(5);k.push(P.startsWith(" ")?P.slice(1):P)}else if(A===""){const P=k.join(`
644
- `);w(x,P),x="",k=[]}}if(_&&x&&k.length>0){const H=k.join(`
645
- `);w(x,H),x="",k=[]}};for(;;){const{done:E,value:_}=await j.read();if(E){R(S.decode(),!0);break}R(S.decode(_,{stream:!0}))}const O=C.length>0||x.length>0||k.length>0;!u&&!d&&!O&&s.onError?.("Connection closed unexpectedly"),p()}catch(v){if(v instanceof DOMException&&v.name==="AbortError"){!d&&!u&&s.onError?.("Connection aborted"),p();return}if(d){p();return}p(),s.onError?.(v instanceof Error?v.message:"Connection error")}})(),{close:()=>{d=!0,p(),c.abort()},isConnected:()=>!d}}function yC(e,n,s,a){const r=Ss(V(`/chat/sessions/${encodeURIComponent(e)}/stream`,s)),o=new AbortController;let l=!1,c=!1;const d=(u,h)=>{if(u)switch(u){case"thinking":try{n.onThinking?.(JSON.parse(h))}catch{n.onThinking?.(h)}break;case"text":try{n.onText?.(JSON.parse(h))}catch{n.onText?.(h)}break;case"tool_start":try{n.onToolStart?.(JSON.parse(h))}catch{}break;case"tool_end":try{n.onToolEnd?.(JSON.parse(h))}catch{}break;case"fallback":try{n.onFallback?.(JSON.parse(h))}catch{}break;case"done":c=!0;try{const m=JSON.parse(h);n.onDone?.({messageId:typeof m.messageId=="string"?m.messageId:"",...m.message&&typeof m.message=="object"?{message:m.message}:{}})}catch{n.onDone?.({messageId:""})}break;case"error":c=!0,n.onError?.(zb(h));break}};return(async()=>{try{const u=new Headers(Ni());typeof a?.lastEventId=="number"&&u.set("Last-Event-ID",String(a.lastEventId));const h=await fetch(r,{method:"GET",headers:u,signal:o.signal});if(!h.ok){const y=await h.text();let j=`Request failed: ${h.status}`;try{j=JSON.parse(y).error||j}catch{}n.onError?.(j);return}if(!h.body){n.onError?.("No response body");return}n.onConnectionStateChange?.("connected");const m=h.body.getReader(),f=new TextDecoder;let p="",g="",w=[];const v=(y,j=!1)=>{p+=y;const S=p.split(`
646
- `);p=S.pop()||"",j&&p.length>0&&(S.push(p),p="");for(const C of S){const x=C.endsWith("\r")?C.slice(0,-1):C;if(x.startsWith("event:"))g=x.slice(6).trim();else if(x.startsWith("data:")){const k=x.slice(5);w.push(k.startsWith(" ")?k.slice(1):k)}else if(x===""){const k=w.join(`
647
- `);d(g,k),g="",w=[]}}if(j&&g&&w.length>0){const C=w.join(`
648
- `);d(g,C),g="",w=[]}};for(;;){const{done:y,value:j}=await m.read();if(y){v(f.decode(),!0);break}v(f.decode(j,{stream:!0}))}const b=p.length>0||g.length>0||w.length>0;if(!c&&!l&&!b)return}catch(u){if(u instanceof DOMException&&u.name==="AbortError"){!l&&!c&&n.onError?.("Connection aborted");return}if(l)return;n.onError?.(u instanceof Error?u.message:"Connection error")}})(),{close:()=>{l=!0,o.abort()},isConnected:()=>!l}}function _8(e={},n){const s=new URLSearchParams;e.category&&s.set("category",e.category),e.status&&s.set("status",e.status),e.runId&&s.set("runId",e.runId),e.limit!==void 0&&s.set("limit",String(e.limit)),e.offset!==void 0&&s.set("offset",String(e.offset));const a=s.size>0?`?${s.toString()}`:"";return I(V(`/insights${a}`,n))}function M8(e,n){return I(V(`/insights/${encodeURIComponent(e)}/dismiss`,n),{method:"POST"})}function A8(e,n){return I(V(`/insights/${encodeURIComponent(e)}/archive`,n),{method:"POST"})}function R8(e,n){return I(V(`/insights/${encodeURIComponent(e)}/unarchive`,n),{method:"POST"})}function I8(e="manual",n,s,a,r){const o={trigger:e,inputMetadata:n};return a&&(o.modelProvider=a),r&&(o.modelId=r),I(V("/insights/run",s),{method:"POST",body:JSON.stringify(o)})}function T8(e){return I(V("/insights/runs",e))}function P8(e,n){return I(V(`/insights/runs/${encodeURIComponent(e)}`,n))}function $8(e,n){return I(V(`/insights/${encodeURIComponent(e)}/create-task`,n),{method:"POST"})}function D8(e={},n){const s=new URLSearchParams;e.q&&s.set("q",e.q),e.runId&&s.set("runId",e.runId),e.scoreMin!==void 0&&s.set("scoreMin",String(e.scoreMin)),e.scoreMax!==void 0&&s.set("scoreMax",String(e.scoreMax)),e.limit!==void 0&&s.set("limit",String(e.limit)),e.offset!==void 0&&s.set("offset",String(e.offset));const a=s.size>0?`?${s.toString()}`:"";return I(V(`/evals${a}`,n))}function L8(e,n){return I(V(`/evals/${encodeURIComponent(e)}`,n))}function O8(e){return I(V("/evals/runs",e))}function F8(e={},n){const s=new URLSearchParams;e.q&&s.set("q",e.q),e.status&&s.set("status",e.status),e.limit!==void 0&&s.set("limit",String(e.limit));const a=s.size>0?`?${s.toString()}`:"";return I(V(`/research/runs${a}`,n))}function z8(e,n){return I(V("/research/runs",n),{method:"POST",body:JSON.stringify(e)})}function B8(e,n){return I(V(`/research/runs/${encodeURIComponent(e)}`,n))}function Bb(e){if(e instanceof Xl){const n=e.details?.code,s=typeof n=="string"?n:"INTERNAL_ERROR",a=typeof e.details?.setupHint=="string"?e.details.setupHint:void 0,r=typeof e.details?.retryable=="boolean"?e.details.retryable:void 0,o=e;throw o.researchCode=s,o.setupHint=a,o.retryable=r,o}throw e}async function U8(e,n){try{return await I(V(`/research/runs/${encodeURIComponent(e)}/cancel`,n),{method:"POST"})}catch(s){Bb(s)}}async function H8(e,n){try{return await I(V(`/research/runs/${encodeURIComponent(e)}/retry`,n),{method:"POST"})}catch(s){Bb(s)}}function q8(e,n,s){return I(V(`/research/runs/${encodeURIComponent(e)}/export?format=${encodeURIComponent(n)}`,s))}function V8(e,n,s){const a=n.findingId??"finding-1";return I(V(`/research/runs/${encodeURIComponent(e)}/findings/${encodeURIComponent(a)}/task`,s),{method:"POST",body:JSON.stringify({title:n.title,description:n.description,priority:n.priority,attachExport:n.attachExport})})}function W8(e,n,s){const a=n.findingId??"finding-1";return I(V(`/research/runs/${encodeURIComponent(e)}/findings/${encodeURIComponent(a)}/tasks/${encodeURIComponent(n.taskId)}/enrich`,s),{method:"POST",body:JSON.stringify({attachExport:n.attachExport})})}async function wC(e){return Yo("/health",{nodeId:e})}async function kC(e){return Yo("/projects",{nodeId:e})}async function jC(e,n,s){const a=new URLSearchParams({projectId:n});return s&&s.trim()&&a.set("q",s.trim()),Yo(`/tasks?${a.toString()}`,{nodeId:e})}async function NC(e,n){return Yo(`/project-health?projectId=${encodeURIComponent(n)}`,{nodeId:e})}async function G8(e){return I(`/nodes/${encodeURIComponent(e)}/settings/push`,{method:"POST",body:JSON.stringify({})})}async function K8(e){return I(`/nodes/${encodeURIComponent(e)}/settings/pull`,{method:"POST",body:JSON.stringify({conflictResolution:"last-write-wins"})})}async function J8(e){return I(`/nodes/${encodeURIComponent(e)}/settings/sync-status`)}async function Y8(e){return I(`/nodes/${encodeURIComponent(e)}/auth/sync`,{method:"POST",body:JSON.stringify({})})}async function SC(e,n){return Promise.all(n.map(({projectId:s,path:a})=>q1(s,e,a)))}function CC(e){switch(e){case"online":return{label:"Online",dotClass:"node-status-indicator__dot--online"};case"offline":return{label:"Offline",dotClass:"node-status-indicator__dot--offline"};case"connecting":return{label:"Connecting",dotClass:"node-status-indicator__dot--connecting"};case"error":return{label:"Error",dotClass:"node-status-indicator__dot--error"};default:return{label:"Unknown",dotClass:"node-status-indicator__dot--offline"}}}function EC({node:e,showDetails:n=!1}){if(!e||e.type==="local")return t.jsx("div",{className:"node-status-indicator node-status-indicator--local",children:t.jsx("span",{className:"node-status-indicator__label",children:"Local"})});const{label:s,dotClass:a}=CC(e.status),r=e.status==="connecting";return t.jsxs("div",{className:"node-status-indicator node-status-indicator--remote",children:[t.jsx("span",{className:`node-status-indicator__dot ${a}`,children:r&&t.jsx("span",{className:"node-status-indicator__spinner"})}),t.jsx("span",{className:"node-status-indicator__name",children:e.name}),n&&t.jsxs("span",{className:"node-status-indicator__details",children:[e.type," · ",s]})]})}function _C(e){return e.charAt(0).toUpperCase()+e.slice(1)}function Ua({status:e,showLabel:n=!1,className:s,compact:a=!1}){const r=_C(e);return t.jsxs("span",{className:`node-health-dot${a?" node-health-dot--compact":""}${s?` ${s}`:""}`,title:r,"aria-label":`Node status: ${r}`,children:[t.jsx("span",{className:`status-dot status-dot--${e}`}),n?t.jsx("span",{className:"node-health-dot__label",children:r}):null]})}const bh=new Map,MC=6e4;function Ub(e){const[n,s]=i.useState([]),[a,r]=i.useState(!0),[o,l]=i.useState(null),c=i.useRef(!1),d=i.useRef(!1),u=i.useCallback(h=>n.filter(m=>m.slot.slotId===h),[n]);return i.useEffect(()=>{const h=e??"default";let m=!1;async function f(){const p=bh.get(h);if(p&&Date.now()<p.expiresAt){if(m||d.current)return;s(p.slots),r(!1);return}!c.current&&r(!0),l(null);try{const w=await mC(e);if(m||d.current)return;bh.set(h,{slots:w,expiresAt:Date.now()+MC}),s(w),c.current=!0}catch(w){if(m||d.current)return;l(w instanceof Error?w.message:"Failed to fetch UI slots"),c.current=!0}finally{!m&&!d.current&&r(!1)}}return f(),()=>{m=!0}},[e]),i.useEffect(()=>{c.current=!1,d.current=!1},[e]),i.useEffect(()=>()=>{d.current=!0},[]),i.useMemo(()=>({slots:n,getSlotsForId:u,loading:a,error:o}),[n,u,a,o])}function xh({size:e,color:n,label:s="llama.cpp"}){return t.jsx(lb,{size:e,color:n,"aria-label":s,"data-testid":"llama-cpp-icon"})}const AC={sm:16,md:20,lg:24};function RC({size:e,color:n,label:s="Anthropic"}){return t.jsx("svg",{width:e,height:e,viewBox:"0 0 24 24",fill:"none",xmlns:"http://www.w3.org/2000/svg","data-testid":"anthropic-icon","aria-label":s,children:t.jsx("path",{d:"M17.3041 3.541h-3.6718l6.696 16.918H24Zm-10.6082 0L0 20.459h3.7442l1.3693-3.5527h7.0052l1.3693 3.5528h3.7442L10.5363 3.5409Zm-.3712 10.2232 2.2914-5.9456 2.2914 5.9456Z",fill:n})})}function vh({size:e,color:n,label:s="OpenAI"}){return t.jsx("svg",{width:e,height:e,viewBox:"0 0 24 24",fill:"none",xmlns:"http://www.w3.org/2000/svg","data-testid":"openai-icon","aria-label":s,children:t.jsx("path",{d:"M22.282 9.821a6 6 0 0 0-.516-4.91a6.05 6.05 0 0 0-6.51-2.9A6.065 6.065 0 0 0 4.981 4.18a6 6 0 0 0-3.998 2.9a6.05 6.05 0 0 0 .743 7.097a5.98 5.98 0 0 0 .51 4.911a6.05 6.05 0 0 0 6.515 2.9A6 6 0 0 0 13.26 24a6.06 6.06 0 0 0 5.772-4.206a6 6 0 0 0 3.997-2.9a6.06 6.06 0 0 0-.747-7.073M13.26 22.43a4.48 4.48 0 0 1-2.876-1.04l.141-.081l4.779-2.758a.8.8 0 0 0 .392-.681v-6.737l2.02 1.168a.07.07 0 0 1 .038.052v5.583a4.504 4.504 0 0 1-4.494 4.494M3.6 18.304a4.47 4.47 0 0 1-.535-3.014l.142.085l4.783 2.759a.77.77 0 0 0 .78 0l5.843-3.369v2.332a.08.08 0 0 1-.033.062L9.74 19.95a4.5 4.5 0 0 1-6.14-1.646M2.34 7.896a4.5 4.5 0 0 1 2.366-1.973V11.6a.77.77 0 0 0 .388.677l5.815 3.354l-2.02 1.168a.08.08 0 0 1-.071 0l-4.83-2.786A4.504 4.504 0 0 1 2.34 7.872zm16.597 3.855l-5.833-3.387L15.119 7.2a.08.08 0 0 1 .071 0l4.83 2.791a4.494 4.494 0 0 1-.676 8.105v-5.678a.79.79 0 0 0-.407-.667m2.01-3.023l-.141-.085l-4.774-2.782a.78.78 0 0 0-.785 0L9.409 9.23V6.897a.07.07 0 0 1 .028-.061l4.83-2.787a4.5 4.5 0 0 1 6.68 4.66zm-12.64 4.135l-2.02-1.164a.08.08 0 0 1-.038-.057V6.075a4.5 4.5 0 0 1 7.375-3.453l-.142.08L8.704 5.46a.8.8 0 0 0-.393.681zm1.097-2.365l2.602-1.5l2.607 1.5v2.999l-2.597 1.5l-2.607-1.5Z",fill:n})})}function Ai({size:e,color:n,label:s="Google Gemini"}){return t.jsx("svg",{width:e,height:e,viewBox:"0 0 24 24",fill:"none",xmlns:"http://www.w3.org/2000/svg","data-testid":"gemini-icon","aria-label":s,children:t.jsx("path",{d:"M11.04 19.32Q12 21.51 12 24q0-2.49.93-4.68.96-2.19 2.58-3.81t3.81-2.55Q21.51 12 24 12q-2.49 0-4.68-.93a12.3 12.3 0 0 1-3.81-2.58 12.3 12.3 0 0 1-2.58-3.81Q12 2.49 12 0q0 2.49-.96 4.68-.93 2.19-2.55 3.81a12.3 12.3 0 0 1-3.81 2.58Q2.49 12 0 12q2.49 0 4.68.96 2.19.93 3.81 2.55t2.55 3.81",fill:n})})}function IC({size:e,color:n,label:s="Ollama"}){return t.jsx("svg",{width:e,height:e,viewBox:"0 0 24 24",fill:"none",xmlns:"http://www.w3.org/2000/svg","data-testid":"ollama-icon","aria-label":s,children:t.jsx("path",{d:"M16.361 10.26a.894.894 0 0 0-.558.47l-.072.148.001.207c0 .193.004.217.059.353.076.193.152.312.291.448.24.238.51.3.872.205a.86.86 0 0 0 .517-.436.752.752 0 0 0 .08-.498c-.064-.453-.33-.782-.724-.897a1.06 1.06 0 0 0-.466 0zm-9.203.005c-.305.096-.533.32-.65.639a1.187 1.187 0 0 0-.06.52c.057.309.31.59.598.667.362.095.632.033.872-.205.14-.136.215-.255.291-.448.055-.136.059-.16.059-.353l.001-.207-.072-.148a.894.894 0 0 0-.565-.472 1.02 1.02 0 0 0-.474.007Zm4.184 2c-.131.071-.223.25-.195.383.031.143.157.288.353.407.105.063.112.072.117.136.004.038-.01.146-.029.243-.02.094-.036.194-.036.222.002.074.07.195.143.253.064.052.076.054.255.059.164.005.198.001.264-.03.169-.082.212-.234.15-.525-.052-.243-.042-.28.087-.355.137-.08.281-.219.324-.314a.365.365 0 0 0-.175-.48.394.394 0 0 0-.181-.033c-.126 0-.207.03-.355.124l-.085.053-.053-.032c-.219-.13-.259-.145-.391-.143a.396.396 0 0 0-.193.032zm.39-2.195c-.373.036-.475.05-.654.086-.291.06-.68.195-.951.328-.94.46-1.589 1.226-1.787 2.114-.04.176-.045.234-.045.53 0 .294.005.357.043.524.264 1.16 1.332 2.017 2.714 2.173.3.033 1.596.033 1.896 0 1.11-.125 2.064-.727 2.493-1.571.114-.226.169-.372.22-.602.039-.167.044-.23.044-.523 0-.297-.005-.355-.045-.531-.288-1.29-1.539-2.304-3.072-2.497a6.873 6.873 0 0 0-.855-.031zm.645.937a3.283 3.283 0 0 1 1.44.514c.223.148.537.458.671.662.166.251.26.508.303.82.02.143.01.251-.043.482-.08.345-.332.705-.672.957a3.115 3.115 0 0 1-.689.348c-.382.122-.632.144-1.525.138-.582-.006-.686-.01-.853-.042-.57-.107-1.022-.334-1.35-.68-.264-.28-.385-.535-.45-.946-.03-.192.025-.509.137-.776.136-.326.488-.73.836-.963.403-.269.934-.46 1.422-.512.187-.02.586-.02.773-.002zm-5.503-11a1.653 1.653 0 0 0-.683.298C5.617.74 5.173 1.666 4.985 2.819c-.07.436-.119 1.04-.119 1.503 0 .544.064 1.24.155 1.721.02.107.031.202.023.208a8.12 8.12 0 0 1-.187.152 5.324 5.324 0 0 0-.949 1.02 5.49 5.49 0 0 0-.94 2.339 6.625 6.625 0 0 0-.023 1.357c.091.78.325 1.438.727 2.04l.13.195-.037.064c-.269.452-.498 1.105-.605 1.732-.084.496-.095.629-.095 1.294 0 .67.009.803.088 1.266.095.555.288 1.143.503 1.534.071.128.243.393.264.407.007.003-.014.067-.046.141a7.405 7.405 0 0 0-.548 1.873c-.062.417-.071.552-.071.991 0 .56.031.832.148 1.279L3.42 24h1.478l-.05-.091c-.297-.552-.325-1.575-.068-2.597.117-.472.25-.819.498-1.296l.148-.29v-.177c0-.165-.003-.184-.057-.293a.915.915 0 0 0-.194-.25 1.74 1.74 0 0 1-.385-.543c-.424-.92-.506-2.286-.208-3.451.124-.486.329-.918.544-1.154a.787.787 0 0 0 .223-.531c0-.195-.07-.355-.224-.522a3.136 3.136 0 0 1-.817-1.729c-.14-.96.114-2.005.69-2.834.563-.814 1.353-1.336 2.237-1.475.199-.033.57-.028.776.01.226.04.367.028.512-.041.179-.085.268-.19.374-.431.093-.215.165-.333.36-.576.234-.29.46-.489.822-.729.413-.27.884-.467 1.352-.561.17-.035.25-.04.569-.04.319 0 .398.005.569.04a4.07 4.07 0 0 1 1.914.997c.117.109.398.457.488.602.034.057.095.177.132.267.105.241.195.346.374.43.14.068.286.082.503.045.343-.058.607-.053.943.016 1.144.23 2.14 1.173 2.581 2.437.385 1.108.276 2.267-.296 3.153-.097.15-.193.27-.333.419-.301.322-.301.722-.001 1.053.493.539.801 1.866.708 3.036-.062.772-.26 1.463-.533 1.854a2.096 2.096 0 0 1-.224.258.916.916 0 0 0-.194.25c-.054.109-.057.128-.057.293v.178l.148.29c.248.476.38.823.498 1.295.253 1.008.231 2.01-.059 2.581a.845.845 0 0 0-.044.098c0 .006.329.009.732.009h.73l.02-.074.036-.134c.019-.076.057-.3.088-.516.029-.217.029-1.016 0-1.258-.11-.875-.295-1.57-.597-2.226-.032-.074-.053-.138-.046-.141.008-.005.057-.074.108-.152.376-.569.607-1.284.724-2.228.031-.26.031-1.378 0-1.628-.083-.645-.182-1.082-.348-1.525a6.083 6.083 0 0 0-.329-.7l-.038-.064.131-.194c.402-.604.636-1.262.727-2.04a6.625 6.625 0 0 0-.024-1.358 5.512 5.512 0 0 0-.939-2.339 5.325 5.325 0 0 0-.95-1.02 8.097 8.097 0 0 1-.186-.152.692.692 0 0 1 .023-.208c.208-1.087.201-2.443-.017-3.503-.19-.924-.535-1.658-.98-2.082-.354-.338-.716-.482-1.15-.455-.996.059-1.8 1.205-2.116 3.01a6.805 6.805 0 0 0-.097.726c0 .036-.007.066-.015.066a.96.96 0 0 1-.149-.078A4.857 4.857 0 0 0 12 3.03c-.832 0-1.687.243-2.456.698a.958.958 0 0 1-.148.078c-.008 0-.015-.03-.015-.066a6.71 6.71 0 0 0-.097-.725C8.997 1.392 8.337.319 7.46.048a2.096 2.096 0 0 0-.585-.041Zm.293 1.402c.248.197.523.759.682 1.388.03.113.06.244.069.292.007.047.026.152.041.233.067.365.098.76.102 1.24l.002.475-.12.175-.118.178h-.278c-.324 0-.646.041-.954.124l-.238.06c-.033.007-.038-.003-.057-.144a8.438 8.438 0 0 1 .016-2.323c.124-.788.413-1.501.696-1.711.067-.05.079-.049.157.013zm9.825-.012c.17.126.358.46.498.888.28.854.36 2.028.212 3.145-.019.14-.024.151-.057.144l-.238-.06a3.693 3.693 0 0 0-.954-.124h-.278l-.119-.178-.119-.175.002-.474c.004-.669.066-1.19.214-1.772.157-.623.434-1.185.68-1.382.078-.062.09-.063.159-.012z",fill:n})})}function yh({size:e,color:n,label:s="MiniMax"}){return t.jsx("svg",{width:e,height:e,viewBox:"0 0 24 24",fill:"none",xmlns:"http://www.w3.org/2000/svg","data-testid":"minimax-icon","aria-label":s,children:t.jsx("path",{d:"M11.43 3.92a.86.86 0 1 0-1.718 0v14.236a1.999 1.999 0 0 1-3.997 0V9.022a.86.86 0 1 0-1.718 0v3.87a1.999 1.999 0 0 1-3.997 0V11.49a.57.57 0 0 1 1.139 0v1.404a.86.86 0 0 0 1.719 0V9.022a1.999 1.999 0 0 1 3.997 0v9.134a.86.86 0 0 0 1.719 0V3.92a1.998 1.998 0 1 1 3.996 0v11.788a.57.57 0 1 1-1.139 0zm10.572 3.105a2 2 0 0 0-1.999 1.997v7.63a.86.86 0 0 1-1.718 0V3.923a1.999 1.999 0 0 0-3.997 0v16.16a.86.86 0 0 1-1.719 0V18.08a.57.57 0 1 0-1.138 0v2a1.998 1.998 0 0 0 3.996 0V3.92a.86.86 0 0 1 1.719 0v12.73a1.999 1.999 0 0 0 3.996 0V9.023a.86.86 0 1 1 1.72 0v6.686a.57.57 0 0 0 1.138 0V9.022a2 2 0 0 0-1.998-1.997",fill:n})})}function TC({size:e,color:n,label:s="Z.ai"}){return t.jsx("svg",{width:e,height:e,viewBox:"0 0 24 24",fill:"none",xmlns:"http://www.w3.org/2000/svg","data-testid":"zai-icon","aria-label":s,children:t.jsx("path",{d:"M3 5H21V8.5L7 17.5H21V21H3V17.5L17 8.5H3Z",fill:n})})}function Yc({size:e,color:n,label:s="Kimi"}){return t.jsx("svg",{width:e,height:e,viewBox:"0 0 24 24",fill:"none",xmlns:"http://www.w3.org/2000/svg","data-testid":"kimi-icon","aria-label":s,children:t.jsx("path",{d:"M12 3a9 9 0 1 0 9 9c0-.46-.04-.92-.1-1.36a5.39 5.39 0 0 1-4.4 2.26 5.4 5.4 0 0 1-3.14-9.8c.2-.07.4-.1.64-.1z",fill:n})})}function wh({size:e,color:n,label:s="Amazon Bedrock"}){return t.jsx("svg",{width:e,height:e,viewBox:"0 0 24 24",fill:"none",xmlns:"http://www.w3.org/2000/svg","data-testid":"bedrock-icon","aria-label":s,children:t.jsx("path",{d:"M.045 18.02c.072-.116.187-.124.348-.022 2.344 1.476 4.878 2.212 7.607 2.212 1.86 0 3.68-.398 5.453-1.198.386-.168.71-.298.972-.39.26-.092.478-.113.654-.06.176.052.263.2.263.443 0 .222-.12.453-.358.693-.96.962-2.16 1.71-3.592 2.242A12.126 12.126 0 0 1 7.297 23c-2.456 0-4.583-.665-6.378-1.992a.39.39 0 0 1-.098-.096c-.05-.078-.05-.156 0-.234zm6.609-3.26c0-.37.093-.665.282-.886.188-.222.43-.332.727-.332.282 0 .524.105.726.314.2.21.3.498.3.866v4.116c0 .382-.098.676-.294.882-.196.206-.436.31-.72.31-.294 0-.54-.108-.738-.324-.198-.216-.296-.506-.296-.868v-4.078h.014zm-2.986 2.3c0-.376.096-.672.288-.89.192-.216.434-.324.726-.324.292 0 .534.108.726.324.192.218.288.514.288.89v1.778c0 .376-.096.672-.288.89-.192.216-.434.324-.726.324-.292 0-.534-.108-.726-.324-.192-.218-.288-.514-.288-.89v-1.778zm-2.92 1.334c0-.36.09-.65.27-.868.18-.218.42-.328.722-.328s.544.11.73.328c.186.218.278.508.278.868v.444c0 .36-.092.65-.278.868-.186.218-.428.328-.73.328s-.542-.11-.722-.328c-.18-.218-.27-.508-.27-.868v-.444zM21.93 16.4c.804.456 1.39.87 1.758 1.242.368.372.552.7.552.984 0 .208-.102.37-.308.488-.206.118-.462.128-.768.032-.306-.096-.674-.316-1.104-.66a12.728 12.728 0 0 1-1.864-1.75c-1.592.644-3.342.966-5.25.966-1.354 0-2.604-.178-3.752-.534a8.103 8.103 0 0 1-.09-.032l.03.012c-.136-.048.056.022-.042-.014-.04-.016-.04-.016 0 0l.012.004-.012-.004c-.32-.122-.528-.222-.624-.3-.096-.078-.144-.178-.144-.3 0-.098.04-.186.122-.264.082-.078.19-.116.326-.116.076 0 .284.054.624.162 1.078.34 2.264.51 3.558.51 1.642 0 3.194-.286 4.658-.856a17.018 17.018 0 0 1-1.904-3.326c-.416-.94-.726-1.86-.93-2.758-.206-.898-.308-1.728-.308-2.49 0-.664.094-1.194.28-1.592.188-.396.456-.594.804-.594.2 0 .392.074.576.224.184.148.312.354.384.614.1.358.178.758.234 1.198.056.44.084.876.084 1.306 0 .898-.116 1.862-.348 2.894-.232 1.032-.614 2.11-1.146 3.234a16.217 16.217 0 0 0 1.916 1.694z",fill:n})})}function kh({size:e,color:n,label:s="xAI"}){return t.jsx("svg",{width:e,height:e,viewBox:"0 0 24 24",fill:"none",xmlns:"http://www.w3.org/2000/svg","data-testid":"xai-icon","aria-label":s,children:t.jsx("path",{d:"M2.21 3l7.964 11.386L2.13 21h1.974l6.843-7.07L17.165 21H22.1l-8.392-11.97L21.17 3h-1.974l-6.349 6.56L6.845 3z",fill:n})})}function jh({size:e,color:n,label:s="Opencode"}){return t.jsx("svg",{width:e,height:e,viewBox:"0 0 24 24",fill:"none",xmlns:"http://www.w3.org/2000/svg","data-testid":"opencode-icon","aria-label":s,children:t.jsx("path",{d:"M9.4 16.6L4.8 12l4.6-4.6L8 6l-6 6 6 6zm5.2 0l4.6-4.6-4.6-4.6L16 6l6 6-6 6z",fill:n})})}function Qc({size:e,color:n,label:s="DeepSeek"}){return t.jsx("svg",{width:e,height:e,viewBox:"0 0 24 24",fill:"none",xmlns:"http://www.w3.org/2000/svg","data-testid":"deepseek-icon","aria-label":s,children:t.jsx("path",{d:"M4 12a8 8 0 1 1 12.7 6.4L12 16h4a4 4 0 1 0-1.6 3.2L12 22l7-1-1.2-3.6A10 10 0 1 0 2 12z",fill:n})})}function Nh({size:e,color:n,label:s="Cloudflare"}){return t.jsx("svg",{width:e,height:e,viewBox:"0 0 24 24",fill:"none",xmlns:"http://www.w3.org/2000/svg","data-testid":"cloudflare-icon","aria-label":s,children:t.jsx("path",{d:"M7 16.5h10.8a2.9 2.9 0 0 0 .3-5.8 4.9 4.9 0 0 0-9.3-1.6A3.6 3.6 0 0 0 7 16.5m-1.9 0h3.2a2.5 2.5 0 0 0 .2-5 3.4 3.4 0 0 0-3.4 3.4c0 .6 0 1 .2 1.6",fill:n})})}function no({size:e,color:n,label:s="Qwen"}){return t.jsxs("svg",{width:e,height:e,viewBox:"0 0 24 24",fill:"none",xmlns:"http://www.w3.org/2000/svg","data-testid":"qwen-icon","aria-label":s,children:[t.jsx("circle",{cx:"11",cy:"12",r:"7.5",stroke:n,strokeWidth:"2",fill:"none"}),t.jsx("path",{d:"M14 15 L21 22",stroke:n,strokeWidth:"2.6",strokeLinecap:"round"})]})}function Sh({size:e,color:n,label:s="LM Studio"}){return t.jsxs("svg",{width:e,height:e,viewBox:"0 0 24 24",fill:"none",xmlns:"http://www.w3.org/2000/svg","data-testid":"lmstudio-icon","aria-label":s,children:[t.jsx("rect",{x:"2",y:"2",width:"20",height:"20",rx:"4.5",fill:n}),t.jsx("text",{x:"12",y:"16",textAnchor:"middle",fontFamily:"-apple-system, system-ui, sans-serif",fontSize:"9.5",fontWeight:"700",fill:"var(--provider-icon-contrast)",letterSpacing:"-0.4",children:"LM"})]})}function Xc({size:e,color:n,label:s="Hugging Face"}){return t.jsxs("svg",{width:e,height:e,viewBox:"0 0 24 24",fill:"none",xmlns:"http://www.w3.org/2000/svg","data-testid":"huggingface-icon","aria-label":s,children:[t.jsx("circle",{cx:"12",cy:"12",r:"9",fill:n}),t.jsx("circle",{cx:"8.5",cy:"10.5",r:"1.4",fill:"var(--provider-icon-contrast)"}),t.jsx("circle",{cx:"15.5",cy:"10.5",r:"1.4",fill:"var(--provider-icon-contrast)"}),t.jsx("path",{d:"M7.5 14.5 Q12 18.5 16.5 14.5",stroke:"var(--provider-icon-contrast)",strokeWidth:"1.6",strokeLinecap:"round",fill:"none"}),t.jsx("path",{d:"M3.5 16 Q5 13.5 7 14.5 M20.5 16 Q19 13.5 17 14.5",stroke:n,strokeWidth:"1.8",strokeLinecap:"round",fill:"none"})]})}function Ch({size:e,color:n,label:s="Mistral AI"}){return t.jsx("svg",{width:e,height:e,viewBox:"0 0 24 24",fill:"none",xmlns:"http://www.w3.org/2000/svg","data-testid":"mistral-icon","aria-label":s,children:t.jsx("path",{d:"M2 4h3v16H2zM7 4h3v12H7zM12 4h3v16h-3zM17 4h3v8h-3zM7 16h3v4H7zM17 8h3v12h-3z",fill:n})})}function Zc({size:e,color:n,label:s="Azure"}){return t.jsx("svg",{width:e,height:e,viewBox:"0 0 24 24",fill:"none",xmlns:"http://www.w3.org/2000/svg","data-testid":"azure-icon","aria-label":s,children:t.jsx("path",{d:"M10.4 3.2 4.5 16.6l3.5.5L13 6 9.6 19.5h9.9zM3 19.5l4.6.6 8.6-1.7-7-1.6z",fill:n})})}function PC({size:e,color:n,label:s="Cerebras"}){return t.jsxs("svg",{width:e,height:e,viewBox:"0 0 24 24",fill:"none",xmlns:"http://www.w3.org/2000/svg","data-testid":"cerebras-icon","aria-label":s,children:[t.jsx("path",{d:"M19.5 6.5A8.5 8.5 0 1 0 19.5 17.5",stroke:n,strokeWidth:"2.4",strokeLinecap:"round",fill:"none"}),t.jsx("path",{d:"M16.5 9A4.6 4.6 0 1 0 16.5 15",stroke:n,strokeWidth:"1.8",strokeLinecap:"round",fill:"none"}),t.jsx("circle",{cx:"11",cy:"12",r:"1.6",fill:n})]})}function $C({size:e,color:n,label:s="Groq"}){return t.jsx("svg",{width:e,height:e,viewBox:"0 0 24 24",fill:"none",xmlns:"http://www.w3.org/2000/svg","data-testid":"groq-icon","aria-label":s,children:t.jsx("path",{d:"M14 2 4 13h6l-2 9 10-11h-6z",fill:n})})}function Eh({size:e,color:n,label:s="Vercel"}){return t.jsx("svg",{width:e,height:e,viewBox:"0 0 24 24",fill:"none",xmlns:"http://www.w3.org/2000/svg","data-testid":"vercel-icon","aria-label":s,children:t.jsx("path",{d:"M12 2 22 21H2z",fill:n})})}function ed({size:e,color:n,label:s="Fireworks AI"}){return t.jsxs("svg",{width:e,height:e,viewBox:"0 0 24 24",fill:"none",xmlns:"http://www.w3.org/2000/svg","data-testid":"fireworks-icon","aria-label":s,children:[t.jsx("circle",{cx:"12",cy:"12",r:"2.4",fill:n}),t.jsx("circle",{cx:"12",cy:"3.5",r:"1.4",fill:n}),t.jsx("circle",{cx:"12",cy:"20.5",r:"1.4",fill:n}),t.jsx("circle",{cx:"3.5",cy:"12",r:"1.4",fill:n}),t.jsx("circle",{cx:"20.5",cy:"12",r:"1.4",fill:n}),t.jsx("circle",{cx:"6",cy:"6",r:"1.2",fill:n}),t.jsx("circle",{cx:"18",cy:"6",r:"1.2",fill:n}),t.jsx("circle",{cx:"6",cy:"18",r:"1.2",fill:n}),t.jsx("circle",{cx:"18",cy:"18",r:"1.2",fill:n}),t.jsx("path",{d:"M12 5.5v3M12 15.5v3M5.5 12h3M15.5 12h3",stroke:n,strokeWidth:"1.4",strokeLinecap:"round"})]})}function DC({size:e,color:n,label:s="OpenRouter"}){return t.jsx("svg",{width:e,height:e,viewBox:"0 0 24 24",fill:"none",xmlns:"http://www.w3.org/2000/svg","data-testid":"openrouter-icon","aria-label":s,children:t.jsx("path",{d:"M12 2.5a9.5 9.5 0 1 0 9.5 9.5h-2.7a6.8 6.8 0 1 1-2-4.8l-3.1 3.1H22V2.5l-3.2 3.2A9.45 9.45 0 0 0 12 2.5",fill:n})})}function _h({size:e,color:n,label:s="GitHub"}){return t.jsx("svg",{width:e,height:e,viewBox:"0 0 24 24",fill:"none",xmlns:"http://www.w3.org/2000/svg","data-testid":"github-icon","aria-label":s,children:t.jsx("path",{d:"M12 0a12 12 0 0 0-3.79 23.39c.6.11.82-.26.82-.58v-2.23c-3.34.73-4.04-1.41-4.04-1.41-.55-1.39-1.34-1.76-1.34-1.76-1.09-.75.08-.74.08-.74 1.2.08 1.84 1.24 1.84 1.24 1.08 1.84 2.82 1.31 3.5 1 .1-.78.42-1.31.77-1.62-2.67-.3-5.47-1.34-5.47-5.95 0-1.31.47-2.38 1.24-3.22-.12-.31-.54-1.56.12-3.24 0 0 1.01-.32 3.3 1.23a11.3 11.3 0 0 1 6 0c2.29-1.55 3.3-1.23 3.3-1.23.66 1.68.24 2.93.12 3.24.77.84 1.24 1.91 1.24 3.22 0 4.62-2.8 5.64-5.48 5.94.43.37.82 1.1.82 2.22v3.29c0 .32.22.69.83.58A12 12 0 0 0 12 0",fill:n})})}function td({size:e,color:n,label:s="Hermes"}){return t.jsxs("svg",{width:e,height:e,viewBox:"0 0 64 64",fill:"none",xmlns:"http://www.w3.org/2000/svg",role:"img","aria-label":s,children:[t.jsx("rect",{x:"30",y:"10",width:"4",height:"46",rx:"2",fill:n}),t.jsx("path",{d:"M30 18 C24 14, 14 14, 10 18 C14 16, 22 16, 28 20",fill:n,opacity:"0.9"}),t.jsx("path",{d:"M30 22 C26 19, 18 19, 14 22 C18 20, 24 20, 28 24",fill:n,opacity:"0.7"}),t.jsx("path",{d:"M34 18 C40 14, 50 14, 54 18 C50 16, 42 16, 36 20",fill:n,opacity:"0.9"}),t.jsx("path",{d:"M34 22 C38 19, 46 19, 50 22 C46 20, 40 20, 36 24",fill:n,opacity:"0.7"}),t.jsx("path",{d:"M32 48 C22 44, 20 38, 26 34 C20 36, 18 42, 24 46 C18 40, 22 30, 30 28 C24 32, 22 38, 28 42",fill:"none",stroke:n,strokeWidth:"2.5",strokeLinecap:"round"}),t.jsx("path",{d:"M32 48 C42 44, 44 38, 38 34 C44 36, 46 42, 40 46 C46 40, 42 30, 34 28 C40 32, 42 38, 36 42",fill:"none",stroke:n,strokeWidth:"2.5",strokeLinecap:"round",opacity:"0.8"}),t.jsx("circle",{cx:"32",cy:"10",r:"4",fill:n})]})}function Mh({size:e,label:n="OpenClaw"}){return t.jsxs("svg",{width:e,height:e,viewBox:"0 0 16 16",xmlns:"http://www.w3.org/2000/svg",role:"img","aria-label":n,children:[t.jsx("rect",{width:"16",height:"16",fill:"none"}),t.jsxs("g",{fill:"#3a0a0d",children:[t.jsx("rect",{x:"1",y:"5",width:"1",height:"3"}),t.jsx("rect",{x:"2",y:"4",width:"1",height:"1"}),t.jsx("rect",{x:"2",y:"8",width:"1",height:"1"}),t.jsx("rect",{x:"3",y:"3",width:"1",height:"1"}),t.jsx("rect",{x:"3",y:"9",width:"1",height:"1"}),t.jsx("rect",{x:"4",y:"2",width:"1",height:"1"}),t.jsx("rect",{x:"4",y:"10",width:"1",height:"1"}),t.jsx("rect",{x:"5",y:"2",width:"6",height:"1"}),t.jsx("rect",{x:"11",y:"2",width:"1",height:"1"}),t.jsx("rect",{x:"12",y:"3",width:"1",height:"1"}),t.jsx("rect",{x:"12",y:"9",width:"1",height:"1"}),t.jsx("rect",{x:"13",y:"4",width:"1",height:"1"}),t.jsx("rect",{x:"13",y:"8",width:"1",height:"1"}),t.jsx("rect",{x:"14",y:"5",width:"1",height:"3"}),t.jsx("rect",{x:"5",y:"11",width:"6",height:"1"}),t.jsx("rect",{x:"4",y:"12",width:"1",height:"1"}),t.jsx("rect",{x:"11",y:"12",width:"1",height:"1"}),t.jsx("rect",{x:"3",y:"13",width:"1",height:"1"}),t.jsx("rect",{x:"12",y:"13",width:"1",height:"1"}),t.jsx("rect",{x:"5",y:"14",width:"6",height:"1"})]}),t.jsxs("g",{fill:"#ff4f40",children:[t.jsx("rect",{x:"5",y:"3",width:"6",height:"1"}),t.jsx("rect",{x:"4",y:"4",width:"8",height:"1"}),t.jsx("rect",{x:"3",y:"5",width:"10",height:"1"}),t.jsx("rect",{x:"3",y:"6",width:"10",height:"1"}),t.jsx("rect",{x:"3",y:"7",width:"10",height:"1"}),t.jsx("rect",{x:"4",y:"8",width:"8",height:"1"}),t.jsx("rect",{x:"5",y:"9",width:"6",height:"1"}),t.jsx("rect",{x:"5",y:"12",width:"6",height:"1"}),t.jsx("rect",{x:"6",y:"13",width:"4",height:"1"})]}),t.jsxs("g",{fill:"#ff775f",children:[t.jsx("rect",{x:"1",y:"6",width:"2",height:"1"}),t.jsx("rect",{x:"2",y:"5",width:"1",height:"1"}),t.jsx("rect",{x:"2",y:"7",width:"1",height:"1"}),t.jsx("rect",{x:"13",y:"6",width:"2",height:"1"}),t.jsx("rect",{x:"13",y:"5",width:"1",height:"1"}),t.jsx("rect",{x:"13",y:"7",width:"1",height:"1"})]}),t.jsxs("g",{fill:"#081016",children:[t.jsx("rect",{x:"6",y:"5",width:"1",height:"1"}),t.jsx("rect",{x:"9",y:"5",width:"1",height:"1"})]}),t.jsxs("g",{fill:"#f5fbff",children:[t.jsx("rect",{x:"6",y:"4",width:"1",height:"1"}),t.jsx("rect",{x:"9",y:"4",width:"1",height:"1"})]})]})}function nd({size:e,color:n,label:s="Paperclip"}){return t.jsx("svg",{width:e,height:e,viewBox:"0 0 24 24",fill:"none",xmlns:"http://www.w3.org/2000/svg",role:"img","aria-label":s,children:t.jsx("path",{d:"m16 6-8.414 8.586a2 2 0 0 0 2.829 2.829l8.414-8.586a4 4 0 1 0-5.657-5.657l-8.379 8.551a6 6 0 1 0 8.485 8.485l8.379-8.551",stroke:n,strokeWidth:"2",strokeLinecap:"round",strokeLinejoin:"round"})})}function Ah({size:e,color:n,label:s="Anthropic — via Claude CLI"}){return t.jsxs("svg",{width:e,height:e,viewBox:"0 0 24 24",fill:"none",xmlns:"http://www.w3.org/2000/svg","data-testid":"claude-cli-icon","aria-label":s,children:[t.jsx("g",{transform:"translate(-1 -1.5) scale(0.82)",children:t.jsx("path",{d:"M17.3041 3.541h-3.6718l6.696 16.918H24Zm-10.6082 0L0 20.459h3.7442l1.3693-3.5527h7.0052l1.3693 3.5528h3.7442L10.5363 3.5409Zm-.3712 10.2232 2.2914-5.9456 2.2914 5.9456Z",fill:n})}),t.jsx("rect",{x:"13",y:"13",width:"10",height:"9",rx:"1.5",fill:n}),t.jsx("path",{d:"M15.2 16.2l1.6 1.4-1.6 1.4M18.6 19.6h2.4",stroke:"var(--provider-icon-contrast)",strokeWidth:"1.2",strokeLinecap:"round",strokeLinejoin:"round",fill:"none"})]})}function LC({size:e,color:n,label:s="Factory AI — via Droid CLI"}){return t.jsxs("svg",{width:e,height:e,viewBox:"0 0 24 24",fill:"none",xmlns:"http://www.w3.org/2000/svg","data-testid":"droid-cli-icon","aria-label":s,children:[t.jsx("rect",{x:"2",y:"3",width:"14",height:"14",rx:"3",fill:n}),t.jsx("path",{d:"M6.5 7.5h2.6a2.9 2.9 0 1 1 0 5.8H6.5zM9 7.5v5.8",stroke:"var(--provider-icon-contrast)",strokeWidth:"1.4",strokeLinecap:"round",strokeLinejoin:"round"}),t.jsx("rect",{x:"13",y:"13",width:"10",height:"9",rx:"1.5",fill:n}),t.jsx("path",{d:"M15.2 16.2l1.6 1.4-1.6 1.4M18.6 19.6h2.4",stroke:"var(--provider-icon-contrast)",strokeWidth:"1.2",strokeLinecap:"round",strokeLinejoin:"round",fill:"none"})]})}function OC({size:e,color:n,label:s="Cursor — via Cursor CLI"}){return t.jsxs("svg",{width:e,height:e,viewBox:"0 0 24 24",fill:"none",xmlns:"http://www.w3.org/2000/svg","data-testid":"cursor-cli-icon","aria-label":s,children:[t.jsx("rect",{x:"2",y:"3",width:"14",height:"14",rx:"3",fill:n}),t.jsx("path",{d:"M10.8 7.2a3.6 3.6 0 1 0 0 5.6",stroke:"var(--provider-icon-contrast)",strokeWidth:"1.4",strokeLinecap:"round",strokeLinejoin:"round"}),t.jsx("rect",{x:"13",y:"13",width:"10",height:"9",rx:"1.5",fill:n}),t.jsx("path",{d:"M15.2 16.2l1.6 1.4-1.6 1.4M18.6 19.6h2.4",stroke:"var(--provider-icon-contrast)",strokeWidth:"1.2",strokeLinecap:"round",strokeLinejoin:"round",fill:"none"})]})}const FC={anthropic:{component:RC,color:"var(--provider-anthropic)"},"claude-cli":{component:Ah,color:"var(--provider-anthropic)",label:"Anthropic — via Claude CLI"},"pi-claude-cli":{component:Ah,color:"var(--provider-anthropic)",label:"Anthropic — via Claude CLI"},"droid-cli":{component:LC,color:"var(--provider-openai)",label:"Factory AI — via Droid CLI"},"cursor-cli":{component:OC,color:"var(--provider-cursor-cli)",label:"Cursor — via Cursor CLI"},"llama-cpp":{component:xh,color:"var(--provider-ollama)",label:"llama.cpp"},"llama-server":{component:xh,color:"var(--provider-ollama)",label:"llama.cpp"},openai:{component:vh,color:"var(--provider-openai)"},"openai-codex":{component:vh,color:"var(--provider-openai)",label:"OpenAI Codex"},google:{component:Ai,color:"var(--provider-gemini)"},gemini:{component:Ai,color:"var(--provider-gemini)"},"google-antigravity":{component:Ai,color:"var(--provider-gemini)",label:"Google Gemini"},antigravity:{component:Ai,color:"var(--provider-gemini)",label:"Google Gemini"},"google-vertex":{component:Ai,color:"var(--provider-gemini)",label:"Google Vertex AI"},vertex:{component:Ai,color:"var(--provider-gemini)",label:"Google Vertex AI"},"google-cloud-code":{component:Ai,color:"var(--provider-gemini)",label:"Google Cloud Code"},"cloud-code":{component:Ai,color:"var(--provider-gemini)",label:"Google Cloud Code"},"google-gemini-cli":{component:Ai,color:"var(--provider-gemini)",label:"Google Gemini CLI"},"google-generative-ai":{component:Ai,color:"var(--provider-gemini)",label:"Google Generative AI"},ollama:{component:IC,color:"var(--text)"},github:{component:_h,color:"var(--text)"},"github-copilot":{component:_h,color:"var(--text)",label:"GitHub Copilot"},openrouter:{component:DC,color:"var(--provider-openrouter)"},minimax:{component:yh,color:"var(--provider-minimax)"},"minimax-cn":{component:yh,color:"var(--provider-minimax)",label:"MiniMax (CN)"},zai:{component:TC,color:"var(--provider-zai)"},kimi:{component:Yc,color:"var(--provider-kimi)"},moonshot:{component:Yc,color:"var(--provider-kimi)"},"kimi-coding":{component:Yc,color:"var(--provider-kimi)",label:"Kimi"},bedrock:{component:wh,color:"var(--provider-bedrock)"},"amazon-bedrock":{component:wh,color:"var(--provider-bedrock)",label:"Amazon Bedrock"},xai:{component:kh,color:"var(--text)"},grok:{component:kh,color:"var(--text)",label:"xAI"},opencode:{component:jh,color:"var(--provider-opencode)"},"opencode-go":{component:jh,color:"var(--provider-opencode)",label:"Opencode (Go)"},deepseek:{component:Qc,color:"var(--provider-deepseek)",label:"DeepSeek"},"deepseek-ai":{component:Qc,color:"var(--provider-deepseek)",label:"DeepSeek"},"deep-seek":{component:Qc,color:"var(--provider-deepseek)",label:"DeepSeek"},cloudflare:{component:Nh,color:"var(--provider-cloudflare)",label:"Cloudflare"},cloudflared:{component:Nh,color:"var(--provider-cloudflare)",label:"Cloudflare"},qwen:{component:no,color:"var(--provider-qwen)"},"qwen-ai":{component:no,color:"var(--provider-qwen)",label:"Qwen"},"qwen-coder":{component:no,color:"var(--provider-qwen)",label:"Qwen Coder"},alibaba:{component:no,color:"var(--provider-qwen)",label:"Qwen"},tongyi:{component:no,color:"var(--provider-qwen)",label:"Qwen"},lmstudio:{component:Sh,color:"var(--provider-lmstudio)",label:"LM Studio"},"lm-studio":{component:Sh,color:"var(--provider-lmstudio)",label:"LM Studio"},huggingface:{component:Xc,color:"var(--provider-huggingface)",label:"Hugging Face"},"hugging-face":{component:Xc,color:"var(--provider-huggingface)",label:"Hugging Face"},hf:{component:Xc,color:"var(--provider-huggingface)",label:"Hugging Face"},mistral:{component:Ch,color:"var(--provider-mistral)",label:"Mistral AI"},"mistral-ai":{component:Ch,color:"var(--provider-mistral)",label:"Mistral AI"},azure:{component:Zc,color:"var(--provider-azure)"},"azure-openai":{component:Zc,color:"var(--provider-azure)",label:"Azure OpenAI"},"azure-openai-responses":{component:Zc,color:"var(--provider-azure)",label:"Azure OpenAI"},fireworks:{component:ed,color:"var(--provider-fireworks)",label:"Fireworks AI"},"fireworks-ai":{component:ed,color:"var(--provider-fireworks)",label:"Fireworks AI"},fireworksai:{component:ed,color:"var(--provider-fireworks)",label:"Fireworks AI"},cerebras:{component:PC,color:"var(--provider-cerebras)"},groq:{component:$C,color:"var(--provider-groq)"},vercel:{component:Eh,color:"var(--provider-vercel)"},"vercel-ai-gateway":{component:Eh,color:"var(--provider-vercel)",label:"Vercel AI Gateway"},hermes:{component:td,color:"var(--provider-hermes)",label:"Hermes"},"hermes-agent":{component:td,color:"var(--provider-hermes)",label:"Hermes"},hermesagent:{component:td,color:"var(--provider-hermes)",label:"Hermes"},openclaw:{component:Mh,color:"var(--provider-openclaw)",label:"OpenClaw"},"open-claw":{component:Mh,color:"var(--provider-openclaw)",label:"OpenClaw"},paperclip:{component:nd,color:"var(--provider-paperclip)",label:"Paperclip"},paperclipai:{component:nd,color:"var(--provider-paperclip)",label:"Paperclip"},"paperclip-ai":{component:nd,color:"var(--provider-paperclip)",label:"Paperclip"}};function On({provider:e,size:n="sm"}){const s=e.toLowerCase(),a=FC[s],r=a?.component,o=a?.color??"var(--text-muted)",l=a?.label,c=AC[n];return t.jsx("span",{className:"provider-icon",style:{color:o},"data-provider":s,children:r?t.jsx(r,{size:c,color:o,label:l}):t.jsx(lb,{size:c})})}function Hb({authenticated:e,onToggled:n,compact:s=!1}){const[a,r]=i.useState(null),[o,l]=i.useState(null),[c,d]=i.useState(null),u=i.useRef(!0);i.useEffect(()=>(u.current=!0,()=>{u.current=!1}),[]);const h=i.useCallback(async()=>{try{const b=await zN();return u.current&&r(b),b}catch(b){return u.current&&d({kind:"error",message:b instanceof Error?b.message:String(b)}),null}},[]);i.useEffect(()=>{h()},[h]);const m=i.useCallback(async()=>{l("testing"),d(null),await h(),u.current&&l(null)},[h]),f=i.useCallback(async b=>{l(b?"enabling":"disabling"),d(null);try{const y=await qN(b);u.current&&d({kind:y.enabled?"enabled":"disabled",restartRequired:y.restartRequired}),n?.(y.enabled),await h()}catch(y){u.current&&d({kind:"error",message:y instanceof Error?y.message:String(y)})}finally{u.current&&l(null)}},[n,h]),p=a?.binary.available??!1,g=a?.enabled??e,w=t.jsxs("span",{className:"onboarding-provider-card__description",children:["Route AI calls through your locally-installed ",t.jsx("code",{children:"droid"})," CLI. Uses your existing Factory AI subscription / quota instead of an API key."]}),v=t.jsxs(t.Fragment,{children:[t.jsx("button",{type:"button",className:"btn btn-sm",onClick:m,disabled:o!==null,children:o==="testing"?t.jsxs(t.Fragment,{children:[t.jsx(St,{size:12,className:"animate-spin"}),"Testing…"]}):"Test"}),g?t.jsx("button",{type:"button",className:"btn btn-sm",onClick:()=>void f(!1),disabled:o!==null,children:o==="disabling"?"Disabling…":"Disable"}):t.jsx("button",{type:"button",className:"btn btn-primary btn-sm",onClick:()=>void f(!0),disabled:o!==null||!p,title:p?void 0:"`droid` binary not detected on PATH — install Droid CLI first.",children:o==="enabling"?"Enabling…":"Enable"})]});return s?t.jsxs("div",{className:`auth-provider-card auth-provider-card--cli${e?" auth-provider-card--authenticated":""}`,"data-testid":"droid-cli-provider-card",children:[t.jsxs("div",{className:"auth-provider-header",children:[t.jsxs("div",{className:"auth-provider-info",children:[t.jsx(On,{provider:"droid-cli",size:"sm"}),t.jsx("strong",{children:"Factory AI — via Droid CLI"}),t.jsx(zC,{status:a,authenticated:e})]}),t.jsx("div",{className:"auth-provider-cli-actions",children:v})]}),t.jsxs("details",{className:"auth-provider-cli-details",children:[t.jsx("summary",{children:"Details"}),t.jsxs("div",{className:"auth-provider-cli-details-body",children:[w,t.jsx(Rh,{status:a,authenticated:e}),c&&t.jsx(Ih,{action:c})]})]})]}):t.jsxs("div",{className:`onboarding-provider-card${e?" onboarding-provider-card--connected":""}`,"data-testid":"droid-cli-provider-card",children:[t.jsx("div",{className:"onboarding-provider-card__icon",children:t.jsx(On,{provider:"droid-cli",size:"md"})}),t.jsxs("div",{className:"onboarding-provider-card__body",children:[t.jsx("strong",{className:"onboarding-provider-card__name",children:"Factory AI — via Droid CLI"}),w,t.jsx(Rh,{status:a,authenticated:e})]}),t.jsx("div",{className:"onboarding-provider-card__actions",children:v}),c&&t.jsx(Ih,{action:c})]})}function zC({status:e,authenticated:n}){const s=e?.enabled??n,a=e?.binary.available??!1;return s?t.jsx("span",{className:"auth-status-badge authenticated",children:"✓ Active"}):!a&&e?t.jsx("span",{className:"auth-status-badge not-authenticated",children:"✗ Not installed"}):t.jsx("span",{className:"auth-status-badge not-authenticated",children:"✗ Not connected"})}function Rh({status:e,authenticated:n}){if(!e)return t.jsxs("small",{className:"settings-muted",children:[t.jsx(St,{size:10,className:"animate-spin"})," Probing local CLI…"]});const{binary:s,enabled:a,extension:r,ready:o}=e;return s.available?a?r&&r.status!=="ok"?t.jsxs("small",{className:"onboarding-provider-card__status onboarding-provider-card__status--warning",children:["⚠ Extension load failed: ",r.reason??r.status]}):o||n?t.jsxs("small",{className:"onboarding-provider-card__status onboarding-provider-card__status--connected",children:["✓ Connected",s.version?` — ${s.version}`:""]}):t.jsx("small",{className:"settings-muted",children:"Enabled. Validating…"}):t.jsxs("small",{className:"settings-muted",children:[t.jsx("code",{children:"droid"})," ",s.version?`(${s.version})`:""," detected",s.binaryPath?` at ${s.binaryPath}`:"",". Click Enable to route AI calls through it."]}):t.jsxs("small",{className:"onboarding-provider-card__status onboarding-provider-card__status--error",children:["✗ ",s.reason??"`droid` not found on PATH"]})}function Ih({action:e}){if(e.kind==="error")return t.jsx("p",{className:"onboarding-helper-text onboarding-helper-text--error",children:e.message});const n=e.kind==="enabled"?"Enabled":"Disabled";return t.jsxs("p",{className:"onboarding-helper-text",children:[n,"."," ",e.kind==="enabled"?"Factory AI (via Droid CLI) models are now visible in the model picker.":"Factory AI (via Droid CLI) models are hidden from the model picker.",e.restartRequired?" Restart required: restart your active CLI/chat session for routing changes to take effect.":""]})}function Th({actions:e}){return t.jsx(Hb,{compact:!0,authenticated:!1,onToggled:()=>{e?.refreshAuthProviders?.()}})}function BC({actions:e}){return t.jsx(Hb,{authenticated:!1,onToggled:()=>{e?.refreshAuthProviders?.()}})}function UC(){return t.jsx("p",{className:"onboarding-helper-text","data-testid":"droid-onboarding-setup-help",children:"Tip: Enable Droid CLI to reuse your Factory AI subscription without adding an API key."})}function HC({actions:e}){return t.jsxs("div",{className:"post-onboarding-recommendations__item","data-testid":"droid-post-onboarding-recommendation",children:[t.jsxs("span",{className:"post-onboarding-recommendations__item-text",children:[t.jsx("strong",{children:"Enable Droid CLI"}),t.jsx("span",{children:"Use your local Droid CLI session as an AI provider in Fusion."})]}),t.jsx("button",{type:"button",className:"btn btn-sm",onClick:()=>e?.openSettingsSection?.("authentication"),children:"Open Authentication"}),t.jsx("button",{type:"button",className:"btn btn-sm",onClick:()=>e?.openModelOnboarding?.(),children:"Open Onboarding"})]})}const qC=[{pluginId:"fusion-plugin-droid-runtime",slotId:"settings-provider-card",componentPath:"./components/settings-provider-card.js",component:Th},{pluginId:"fusion-plugin-droid-runtime",slotId:"settings-integration-card",componentPath:"./components/settings-integration-card.js",component:Th},{pluginId:"fusion-plugin-droid-runtime",slotId:"onboarding-provider-card",componentPath:"./components/onboarding-provider-card.js",component:BC},{pluginId:"fusion-plugin-droid-runtime",slotId:"onboarding-setup-help",componentPath:"./components/onboarding-setup-help.js",component:UC},{pluginId:"fusion-plugin-droid-runtime",slotId:"post-onboarding-recommendation",componentPath:"./components/post-onboarding-recommendation.js",component:HC}];function VC(e){return qC.find(s=>s.pluginId===e.pluginId&&s.slotId===e.slot.slotId&&s.componentPath===e.slot.componentPath)?.component??null}function WC({slotId:e,pluginId:n}){return t.jsxs("section",{className:"plugin-slot-shell","data-plugin-slot":!0,"data-slot-id":e,"data-plugin-id":n,"data-plugin-slot-state":"missing-component",role:"status","aria-live":"polite",children:[t.jsx("p",{className:"plugin-slot-shell__title",children:"Plugin component unavailable"}),t.jsx("p",{className:"plugin-slot-shell__message",children:"The dashboard could not resolve this plugin surface from the static host registry."})]})}function pa({slotId:e,projectId:n,pluginIds:s,renderPlaceholder:a=!0,actions:r}){const{getSlotsForId:o,loading:l,error:c}=Ub(n);if(l||c||!e)return null;const d=o(e).filter(u=>s&&s.length>0?s.includes(u.pluginId):!0);return d.length===0?null:t.jsx(Wo,{level:"page",children:t.jsx(t.Fragment,{children:d.map((u,h)=>{const m=`${u.pluginId}-${u.slot.slotId}-${h}`,f=VC(u);return f?t.jsx(f,{entry:u,actions:r},m):a?t.jsx(WC,{slotId:u.slot.slotId,pluginId:u.pluginId},m):null})})})}function GC(){return typeof window>"u"?"desktop":window.matchMedia("(max-width: 768px)").matches?"mobile":window.matchMedia("(min-width: 769px) and (max-width: 1024px)").matches?"tablet":"desktop"}function ei(){const[e,n]=i.useState(GC);return i.useEffect(()=>{if(typeof window>"u")return;const s=window.matchMedia("(max-width: 768px)"),a=window.matchMedia("(min-width: 769px) and (max-width: 1024px)"),r=()=>{s.matches?n("mobile"):a.matches?n("tablet"):n("desktop")};return s.addEventListener("change",r),a.addEventListener("change",r),()=>{s.removeEventListener("change",r),a.removeEventListener("change",r)}},[]),e}function qr(e){return e.replace(/\\/g,"/")}function Zu(e){return e.replace(/[\\/]+$/g,"")}function em(e){const n=qr(Zu(e));return n?n.split("/").filter(Boolean):[]}function tm(e){const n=qr(Zu(e));if(!n)return e;const s=n.split("/").filter(Boolean);return s[s.length-1]||n}function qb(e,n){const s=em(e);return s.length===0?qr(e):s.slice(-2).join("/")}function KC(e){const n=qr(Zu(e)),s=n.lastIndexOf("/");return s<0?"":n.slice(0,s+1)}function JC(e,n){return!e||e==="."?n:[...em(e),n].join("/")}function YC(e){const n=em(e);return n.length===0?".":(n.pop(),n.length===0?".":n.join("/"))}function Q8(e){const n=qr(e),s=n.match(/^([A-Za-z]:)(?:\/(.*))?$/);if(s){const r=`${s[1]}/`,o=(s[2]??"").split("/").filter(Boolean),l=[{label:s[1],path:r}];for(let c=0;c<o.length;c+=1)l.push({label:o[c],path:`${r}${o.slice(0,c+1).join("/")}`});return l}if(n.startsWith("/")){const r=n.split("/").filter(Boolean),o=[{label:"/",path:"/"}];for(let l=0;l<r.length;l+=1)o.push({label:r[l],path:`/${r.slice(0,l+1).join("/")}`});return o}const a=n.split("/").filter(Boolean);return a.map((r,o)=>({label:r,path:a.slice(0,o+1).join("/")}))}const nm=new Map;function Zo(e,n){return`plugin:${e}:${n}`}function Vb(e){const n=/^plugin:([^:]+):(.+)$/u.exec(e);return n?{pluginId:n[1],viewId:n[2]}:null}function kr(e){return Vb(e)!==null}function dl(e,n,s){nm.set(Zo(e,n),s)}function QC(e,n){return nm.get(Zo(e,n))??null}function Wb(e,n){return nm.has(Zo(e,n))}function sd({viewId:e}){return t.jsxs("section",{className:"card plugin-dashboard-view-missing","data-testid":"plugin-view-unavailable",children:[t.jsxs("h2",{className:"plugin-dashboard-view-missing-title",children:[t.jsx(Br,{}),"Plugin view unavailable"]}),t.jsxs("p",{className:"plugin-dashboard-view-missing-description",children:["No host registration found for ",t.jsx("code",{children:e}),"."]})]})}function XC({viewId:e,context:n}){const s=Vb(e);if(!s)return t.jsx(sd,{viewId:e});const a=QC(s.pluginId,s.viewId);return a?t.jsx(Wo,{fallback:t.jsx(sd,{viewId:e}),children:t.jsx(i.Suspense,{fallback:null,children:t.jsx(a,{context:n})})}):t.jsx(sd,{viewId:e})}const Mo=Zo,ZC={activity:Vs,bot:Xn,brain:Po,checksquare:Vu,clock:Yi,filetext:xa,folder:ws,gitbranch:Is,grid3x3:vc,layoutgrid:va,mail:za,map:Sk,messagesquare:Ki,monitor:Er,search:Gi,sparkles:cs,target:js,workflow:Jl,zap:as};function eE(e){return(e??"").trim().toLowerCase().replace(/[-_\s]/g,"")}function tc(e){return ZC[eE(e)]??vc}const ul="__fusion:no-branch__",Gb={active:{color:"var(--success)"},paused:{color:"var(--warning)"},errored:{color:"var(--color-error)"},initializing:{color:"var(--info)"}};function tE({projects:e,currentProject:n,onViewAll:s,onSelectProject:a}){const[r,o]=i.useState(!1),l=i.useRef(null);i.useEffect(()=>{if(!r)return;const d=u=>{l.current&&!l.current.contains(u.target)&&o(!1)};return document.addEventListener("mousedown",d),()=>document.removeEventListener("mousedown",d)},[r]),i.useEffect(()=>{if(!r)return;const d=u=>{u.key==="Escape"&&o(!1)};return document.addEventListener("keydown",d),()=>document.removeEventListener("keydown",d)},[r]);const c=i.useCallback(d=>{a?.(d),o(!1)},[a]);return t.jsx("div",{className:"project-selector",ref:l,children:e.length>0&&t.jsxs(t.Fragment,{children:[t.jsxs("button",{className:`project-selector-trigger${r?" project-selector-trigger--open":""}`,onClick:()=>o(d=>!d),title:n?.name?`Switch project (current: ${n.name})`:"Switch project","aria-label":"Switch project","aria-expanded":r,"aria-haspopup":"listbox","data-testid":"project-selector-trigger",children:[t.jsx("span",{className:"project-selector-trigger-label",children:n?.name??"Projects"}),t.jsx(vn,{size:12,className:`project-selector-chevron${r?" project-selector-chevron--open":""}`})]}),r&&t.jsxs("div",{className:"project-selector-dropdown",role:"listbox","aria-label":"Select project","data-testid":"project-selector-dropdown",children:[e.map(d=>{const u=n?.id===d.id,h=Gb[d.status]?.color;return t.jsxs("button",{className:`project-selector-item${u?" project-selector-item--current":""}`,onClick:()=>c(d),role:"option","aria-selected":u,children:[t.jsx("span",{className:"project-selector-dot",style:{backgroundColor:h||"var(--text-muted)"}}),t.jsxs("div",{className:"project-selector-info",children:[t.jsx("span",{className:"project-selector-name",children:d.name}),t.jsx("span",{className:"project-selector-path",children:qb(d.path)})]}),u&&t.jsx(gs,{size:14,className:"project-selector-check"})]},d.id)}),t.jsx("div",{className:"project-selector-divider",role:"presentation"}),t.jsx("button",{className:"project-selector-manage",onClick:()=>{s(),o(!1)},"data-testid":"manage-projects-action",children:"Manage Projects"})]})]})})}function Ph({size:e=16}){return t.jsx("svg",{width:e,height:e,viewBox:"0 0 24 24",fill:"currentColor","aria-hidden":"true",children:t.jsx("path",{d:"M12 2C6.477 2 2 6.484 2 12.017c0 4.425 2.865 8.18 6.839 9.504.5.092.682-.217.682-.483 0-.237-.008-.868-.013-1.703-2.782.605-3.369-1.343-3.369-1.343-.454-1.158-1.11-1.466-1.11-1.466-.908-.62.069-.608.069-.608 1.003.07 1.531 1.032 1.531 1.032.892 1.53 2.341 1.088 2.91.832.092-.647.35-1.088.636-1.338-2.22-.253-4.555-1.113-4.555-4.951 0-1.093.39-1.988 1.029-2.688-.103-.253-.446-1.272.098-2.65 0 0 .84-.27 2.75 1.026A9.564 9.564 0 0112 6.844c.85.004 1.705.115 2.504.337 1.909-1.296 2.747-1.027 2.747-1.027.546 1.379.203 2.398.1 2.651.64.7 1.028 1.595 1.028 2.688 0 3.848-2.339 4.695-4.566 4.942.359.309.678.92.678 1.855 0 1.338-.012 2.419-.012 2.747 0 .268.18.58.688.482A10.019 10.019 0 0022 12.017C22 6.484 17.522 2 12 2z"})})}function nE({onOpenSettings:e,onOpenGitHubImport:n,onOpenPlanning:s,onResumePlanning:a,activePlanningSessionCount:r=0,onOpenUsage:o,onOpenActivityLog:l,onOpenSystemStats:c,onOpenMailbox:d,mailboxUnreadCount:u=0,mailboxPendingApprovalCount:h=0,chatHasUnreadResponse:m=!1,stashOrphanCount:f=0,onOpenSchedules:p,onOpenGitManager:g,onOpenNodes:w,showNodesButton:v,onOpenWorkflowSteps:b,onOpenScripts:y,onRunScript:j,onToggleTerminal:S,onOpenFiles:C,filesOpen:x,onOpenTodos:k,todosOpen:R,todosEnabled:O,globalPaused:E,enginePaused:_,onToggleGlobalPause:G,onToggleEnginePause:H,view:A="board",onChangeView:P,showSkillsTab:q,showAgentsTab:Y,searchQuery:ge="",onSearchChange:L,branchFilter:M="",baseBranchFilter:$="",branchOptions:D=[],baseBranchOptions:N=[],onBranchFilterChange:W,onBaseBranchFilterChange:de,projects:me=[],currentProject:Ne,onSelectProject:ve,onViewAllProjects:Me,projectId:ie,shellHost:ye={kind:"browser"},mobileNavEnabled:Z,availableNodes:fe=[],currentNode:Q,onSelectNode:F,isRemote:X=!1,experimentalFeatures:re,pluginDashboardViews:U=[],shellConnectionControl:be}){const Ue=ei(),se=Ue==="mobile",Le=se||Ue==="tablet",ct=se&&Z,[Ke,oe]=i.useState(!1),[Te,Fe]=i.useState(!1),[mt,We]=i.useState(!1),[he,pe]=i.useState(!1),[De,ut]=i.useState(!1),[ht,et]=i.useState(!1),[vt,Oe]=i.useState(!1),[tt,ft]=i.useState(!1),[Mt,yt]=i.useState(!1),[Ge,K]=i.useState(!1),[ue,ot]=i.useState(!1),[xe,dt]=i.useState({}),[Je,ke]=i.useState(!1),[nt,bt]=i.useState(-1),[kt,wt]=i.useState(null),[At,Ft]=i.useState({}),[ln,Vt]=i.useState(!1),hn=i.useRef(null),un=i.useRef(null),pn=i.useRef(null),an=i.useRef(null),Wt=i.useRef(null),gn=i.useRef(null),cn=i.useRef(!1),tn=i.useRef(null),Yt=i.useRef(null),Qt=i.useRef(null),Kt=i.useRef(null),Jt=i.useRef(null),rn=i.useRef(null),qt=i.useRef(null),we=i.useRef(null),ze=i.useRef(!1),rt=i.useMemo(()=>fe.filter(z=>z.type==="remote"),[fe]),He=rt.length>0,Ae=i.useMemo(()=>Object.entries(xe).sort(([z],[_e])=>z.localeCompare(_e)),[xe]),pt=Ae.length>0,Ct=Ae.length+(pt?1:0),Tt=i.useMemo(()=>Object.entries(At).sort(([z],[_e])=>z.localeCompare(_e)),[At]),Gt=i.useMemo(()=>!!(P||re?.researchView||O||re?.insights||q||re?.memoryView||re?.devServerView||!ct||U.some(z=>z.view.placement!=="primary")),[P,re,O,q,ct,U]),nn=i.useCallback(()=>{const z=window.visualViewport;return z&&z.width>0&&z.height>0?{width:z.width,height:z.height,offsetTop:z.offsetTop,offsetLeft:z.offsetLeft}:{width:window.innerWidth,height:window.innerHeight,offsetTop:0,offsetLeft:0}},[]),Ht=i.useCallback(()=>{const z=qt.current;if(!z)return;const _e=z.getBoundingClientRect(),Rt=we.current,{width:Ot,height:Lt,offsetTop:fn,offsetLeft:kn}=nn(),es=16,ms=16,Gn=6,hs=Rt?.offsetWidth||Math.max(_e.width,260),Cn=Math.min(hs,Math.max(Ot-es*2,160)),Bt=Rt?.offsetHeight||280,Bn=Math.min(Bt,Math.max(Lt-ms*2,160)),En=_e.top-fn,bs=_e.bottom-fn,$s=_e.right-kn,ss=Lt-bs,Un=En,Kn=ss<Bn&&Un>ss,Ms=Math.min(Math.max($s-Cn,es),Ot-es-Cn)+kn,xs=Kn?Math.max(ms+fn,En-Bn-Gn+fn):Math.min(bs+Gn+fn,Lt+fn-ms-Bn);wt({top:xs,left:Ms,width:Cn})},[nn]),on=i.useCallback((z,_e)=>{j?.(z,_e),ot(!1),bt(-1)},[j]),ae=i.useCallback(()=>{y?.(),ot(!1),bt(-1)},[y]),le=i.useCallback(z=>{switch(z.key){case"ArrowDown":z.preventDefault(),Ct>0&&bt(_e=>_e<Ct-1?_e+1:0);break;case"ArrowUp":z.preventDefault(),Ct>0&&bt(_e=>_e>0?_e-1:Ct-1);break;case"Enter":if(z.preventDefault(),nt>=0)if(nt<Ae.length){const[_e,Rt]=Ae[nt];on(_e,Rt)}else pt&&nt===Ae.length&&ae();break;case"Home":z.preventDefault(),Ct>0&&bt(0);break;case"End":z.preventDefault(),Ct>0&&bt(Ct-1);break}},[ae,on,nt,Ae,pt,Ct]);i.useEffect(()=>{cn.current=De},[De]),i.useEffect(()=>{ze.current=ue},[ue]),i.useEffect(()=>{if(!De||!Le)return;let z=!1;return Vt(!0),Lo(ie).then(_e=>{z||Ft(_e)}).catch(()=>{z||Ft({})}).finally(()=>{z||Vt(!1)}),()=>{z=!0}},[De,Le,ie]),i.useEffect(()=>{if(!ue||Le)return;let z=!1;return ke(!0),Lo(ie).then(_e=>{z||dt(_e)}).catch(()=>{z||dt({})}).finally(()=>{z||ke(!1)}),()=>{z=!0}},[ue,Le,ie]),i.useEffect(()=>{if(!ue)return;const z=_e=>{rn.current&&!rn.current.contains(_e.target)&&ot(!1)};return document.addEventListener("mousedown",z),()=>document.removeEventListener("mousedown",z)},[ue]),i.useEffect(()=>{if(!ue)return;const z=_e=>{_e.key==="Escape"&&(ot(!1),qt.current?.focus())};return document.addEventListener("keydown",z),()=>document.removeEventListener("keydown",z)},[ue]),i.useEffect(()=>{if(ue){bt(-1);const z=window.setTimeout(()=>we.current?.focus(),0);return()=>window.clearTimeout(z)}wt(null)},[ue]),i.useEffect(()=>{if(!ue)return;const z=requestAnimationFrame(()=>{Ht()});return()=>cancelAnimationFrame(z)},[ue,Je,Ae.length,pt,Ht]),i.useEffect(()=>{if(!ue)return;const z=()=>Ht();window.addEventListener("resize",z),window.addEventListener("scroll",z,!0);const _e=window.visualViewport;return _e&&(_e.addEventListener("resize",z),_e.addEventListener("scroll",z)),()=>{window.removeEventListener("resize",z),window.removeEventListener("scroll",z,!0),_e&&(_e.removeEventListener("resize",z),_e.removeEventListener("scroll",z))}},[ue,Ht]),i.useEffect(()=>{Le&&(ot(!1),bt(-1))},[Le]);const Qe=Ke||ge.length>0,xt=(Te||ge.length>0)&&!mt,zt=(A==="board"||A==="list")&&!se&&L&&!mt&&ge.length===0,sn=(A==="board"||A==="list")&&!se&&L,xn=A==="board";i.useEffect(()=>{ge===""&&We(!1)},[ge]),i.useEffect(()=>{if(!he)return;const z=_e=>{un.current&&!un.current.contains(_e.target)&&hn.current&&!hn.current.contains(_e.target)&&pe(!1)};return document.addEventListener("mousedown",z),()=>document.removeEventListener("mousedown",z)},[he]),i.useEffect(()=>{if(!Mt)return;const z=_e=>{an.current&&!an.current.contains(_e.target)&&pn.current&&!pn.current.contains(_e.target)&&yt(!1)};return document.addEventListener("mousedown",z),()=>document.removeEventListener("mousedown",z)},[Mt]),i.useEffect(()=>{if(!ht)return;const z=_e=>{tn.current&&!tn.current.contains(_e.target)&&et(!1)};return document.addEventListener("mousedown",z),()=>document.removeEventListener("mousedown",z)},[ht]),i.useEffect(()=>{const z=_e=>{if(_e.key==="Escape"){if(ft(!1),yt(!1),cn.current){ut(!1);return}if(ze.current){ot(!1),qt.current?.focus();return}pe(!1),oe(!1),et(!1),Oe(!1)}};return document.addEventListener("keydown",z),()=>document.removeEventListener("keydown",z)},[]),i.useEffect(()=>{if(!vt)return;const z=_e=>{Yt.current&&!Yt.current.contains(_e.target)&&Oe(!1)};return document.addEventListener("mousedown",z),()=>document.removeEventListener("mousedown",z)},[vt]),i.useEffect(()=>{if(!Ge)return;const z=_e=>{Jt.current&&!Jt.current.contains(_e.target)&&K(!1)};return document.addEventListener("mousedown",z),()=>document.removeEventListener("mousedown",z)},[Ge]),i.useEffect(()=>{if(!Ge)return;const z=_e=>{_e.key==="Escape"&&K(!1)};return document.addEventListener("keydown",z),()=>document.removeEventListener("keydown",z)},[Ge]),i.useEffect(()=>{if(!tt)return;const z=_e=>{Qt.current&&!Qt.current.contains(_e.target)&&Kt.current&&!Kt.current.contains(_e.target)&&ft(!1)};return document.addEventListener("mousedown",z),()=>document.removeEventListener("mousedown",z)},[tt]);const $n=i.useCallback(()=>{oe(z=>!z)},[]),wn=i.useCallback(()=>{Fe(!0),We(!1)},[]),zn=i.useCallback(()=>{Fe(!1),We(!0),L&&L("")},[L]),ce=i.useCallback(()=>{pe(z=>!z)},[]),ee=i.useCallback(z=>{z&&z(),pe(!1),ut(!1)},[]),Se=i.useCallback(()=>{oe(!1),L&&L("")},[L]),qe=ye.kind==="desktop-shell";return t.jsxs("div",{className:"header-wrapper",children:[t.jsxs("header",{className:"header","data-shell-kind":ye.kind,children:[t.jsxs("div",{className:"header-left",children:[t.jsxs("div",{className:"header-brand",children:[t.jsxs("svg",{className:"header-logo",width:24,height:24,viewBox:"0 0 128 128",fill:"none","aria-label":"Fusion logo",role:"img",children:[t.jsx("circle",{cx:"64",cy:"64",r:"52",stroke:"currentColor",strokeWidth:"8"}),t.jsx("path",{d:"M26 101C44 82 62 64 82 45C90 37 98 30 104 24C96 35 89 47 81 60C70 79 57 95 43 108C38 112 32 108 26 101Z",fill:"currentColor"})]}),t.jsx("h1",{className:"logo",children:"Fusion"})]}),se&&me.length>=1&&ve&&t.jsxs("div",{className:"mobile-project-switch",ref:Yt,children:[t.jsx("button",{className:`mobile-project-switch-trigger${vt?" mobile-project-switch-trigger--open":""}`,onClick:()=>Oe(z=>!z),title:"Switch project","aria-label":"Switch project","aria-expanded":vt,"aria-haspopup":"listbox","data-testid":"mobile-project-switch-trigger",children:t.jsx(vn,{size:14,className:`mobile-project-switch-chevron${vt?" mobile-project-switch-chevron--open":""}`})}),vt&&t.jsx("div",{className:"mobile-project-switch-dropdown",role:"listbox","aria-label":"Select project","data-testid":"mobile-project-switch-dropdown",children:me.map(z=>{const _e=Ne?.id===z.id,Rt=Gb[z.status]?.color;return t.jsxs("button",{className:`mobile-project-switch-item${_e?" mobile-project-switch-item--current":""}`,onClick:()=>{ve(z),Oe(!1)},role:"option","aria-selected":_e,"data-testid":`mobile-project-switch-item-${z.id}`,children:[t.jsx("span",{className:"mobile-project-switch-dot",style:{backgroundColor:Rt||"var(--text-muted)"}}),t.jsxs("div",{className:"mobile-project-switch-info",children:[t.jsx("span",{className:"mobile-project-switch-name",children:z.name}),t.jsx("span",{className:"mobile-project-switch-path",children:qb(z.path)})]}),_e&&t.jsx(gs,{size:14,className:"mobile-project-switch-check"})]},z.id)})})]}),!Le&&me.length>=1&&Me&&t.jsx(tE,{projects:me,currentProject:Ne??null,onViewAll:Me,onSelectProject:ve}),He&&t.jsxs("div",{className:`header-node-selector${se?" header-node-selector--mobile":""}`,ref:se?void 0:tn,children:[t.jsx(EC,{node:Q??null,showDetails:!se}),!se&&t.jsxs(t.Fragment,{children:[t.jsx("button",{className:`btn-icon node-selector-trigger${ht?" node-selector-trigger--open":""}`,onClick:()=>et(z=>!z),title:"Switch node","aria-label":"Switch node","aria-expanded":ht,"aria-haspopup":"listbox","data-testid":"node-selector-trigger",children:t.jsx(Wn,{size:12,className:`node-selector-chevron${ht?" node-selector-chevron--open":""}`})}),ht&&t.jsxs("div",{className:"node-selector-dropdown",role:"listbox","aria-label":"Select node",children:[t.jsxs("button",{className:`node-selector-option${X?"":" node-selector-option--active"}`,onClick:()=>{F?.(null),et(!1)},role:"option","aria-selected":!X,"data-testid":"node-option-local",children:[t.jsx(Ua,{status:"online",compact:!0}),t.jsx("span",{className:"node-selector-option-label",children:"Local"})]}),rt.map(z=>t.jsxs("button",{className:`node-selector-option${Q?.id===z.id?" node-selector-option--active":""}`,onClick:()=>{F?.(z),et(!1)},role:"option","aria-selected":Q?.id===z.id,"data-testid":`node-option-${z.id}`,children:[t.jsx(Ua,{status:z.status,compact:!0}),t.jsx("span",{className:"node-selector-option-label",children:z.name}),t.jsx("span",{className:"node-selector-option-status",children:z.status})]},z.id))]})]})]})]}),t.jsxs("div",{className:"header-actions",children:[be,ct&&P&&(A==="board"||A==="list")&&t.jsxs("div",{className:"view-toggle","data-testid":"mobile-view-toggle",children:[t.jsx("button",{className:`view-toggle-btn${A==="board"?" active":""}`,onClick:()=>P("board"),title:"Board view","aria-label":"Board view","aria-pressed":A==="board","data-testid":"mobile-view-toggle-board",children:t.jsx(va,{size:16})}),t.jsx("button",{className:`view-toggle-btn${A==="list"?" active":""}`,onClick:()=>P("list"),title:"List view","aria-label":"List view","aria-pressed":A==="list","data-testid":"mobile-view-toggle-list",children:t.jsx(cu,{size:16})})]}),L&&se&&(ct||A==="board"||A==="list")&&!Qe&&t.jsx("button",{className:"btn-icon mobile-search-trigger",onClick:$n,title:"Open search","aria-label":"Open search","aria-expanded":!1,"data-testid":"mobile-header-search-btn",children:t.jsx(Gi,{size:16})}),zt&&t.jsx("button",{className:"btn-icon",onClick:wn,title:"Open search","aria-label":"Open search","data-testid":"desktop-header-search-btn",children:t.jsx(Gi,{size:16})}),se&&ct&&o&&t.jsx("button",{className:"btn-icon",onClick:z=>o(z.currentTarget.getBoundingClientRect()),title:"View usage","data-testid":"mobile-header-usage-btn",children:t.jsx(Vs,{size:16})}),!ct&&P&&t.jsxs("div",{className:"view-toggle",children:[t.jsx("button",{className:`view-toggle-btn${A==="board"?" active":""}`,onClick:()=>P("board"),title:"Board view","aria-label":"Board view","aria-pressed":A==="board",children:t.jsx(va,{size:16})}),t.jsx("button",{className:`view-toggle-btn${A==="list"?" active":""}`,onClick:()=>P("list"),title:"List view","aria-label":"List view","aria-pressed":A==="list",children:t.jsx(cu,{size:16})}),Y&&t.jsx("button",{className:`view-toggle-btn${A==="agents"?" active":""}`,onClick:()=>P("agents"),title:"Agents view","aria-label":"Agents view","aria-pressed":A==="agents",children:t.jsx(Xn,{size:16})}),t.jsx("button",{className:`view-toggle-btn${A==="missions"?" active":""}`,onClick:()=>P("missions"),title:"Missions view","aria-label":"Missions view","aria-pressed":A==="missions",children:t.jsx(js,{size:16})}),t.jsxs("button",{className:`view-toggle-btn${A==="chat"?" active":""}`,onClick:()=>P("chat"),title:"Chat view","aria-label":"Chat view","aria-pressed":A==="chat","data-testid":"header-chat-view-btn",children:[t.jsx(Ki,{size:16}),m&&A!=="chat"&&t.jsx("span",{className:"status-dot status-dot--pending header-chat-unread-dot","aria-label":"Unread chat response"})]}),t.jsx("button",{className:`view-toggle-btn${A==="documents"?" active":""}`,onClick:()=>P("documents"),title:"Documents view","aria-label":"Documents view","aria-pressed":A==="documents",children:t.jsx(xa,{size:16})}),t.jsxs("button",{className:`view-toggle-btn${A==="mailbox"?" active":""}`,onClick:()=>P("mailbox"),title:"Mailbox view","aria-label":"Mailbox view","aria-pressed":A==="mailbox",children:[t.jsx(za,{size:16}),h>0&&A!=="mailbox"&&t.jsx("span",{className:"status-dot status-dot--pending header-chat-unread-dot","aria-label":"Pending approvals"})]}),U.filter(z=>z.view.placement==="primary").sort((z,_e)=>(z.view.order??Number.MAX_SAFE_INTEGER)-(_e.view.order??Number.MAX_SAFE_INTEGER)).map(z=>{const _e=Mo(z.pluginId,z.view.viewId),Rt=tc(z.view.icon);return t.jsx("button",{className:`view-toggle-btn${A===_e||A==="graph"&&z.pluginId==="fusion-plugin-dependency-graph"&&z.view.viewId==="graph"?" active":""}`,onClick:()=>P(z.pluginId==="fusion-plugin-dependency-graph"&&z.view.viewId==="graph"?"graph":_e),title:`${z.view.label} view`,"aria-label":`${z.view.label} view`,"aria-pressed":A===_e,"data-testid":`view-toggle-plugin-${z.pluginId}-${z.view.viewId}`,children:t.jsx(Rt,{size:16})},`${z.pluginId}:${z.view.viewId}`)}),Gt&&t.jsxs(t.Fragment,{children:[t.jsx("button",{ref:Kt,className:`view-toggle-btn${["research","skills","insights","memory","dev-server","devserver","graph","stash-recovery"].includes(A)||re?.evalsView&&A==="evals"||O&&R||kr(A)?" active":""}`,onClick:()=>ft(z=>!z),title:"More views","aria-label":"More views","aria-haspopup":"menu","aria-expanded":tt,"data-testid":"view-toggle-overflow-trigger",children:t.jsx(vn,{size:12})}),tt&&t.jsxs("div",{ref:Qt,className:"view-toggle-overflow-menu",role:"menu","aria-label":"More views",children:[re?.evalsView&&t.jsxs("button",{className:`view-toggle-overflow-item${A==="evals"?" active":""}`,onClick:()=>{P("evals"),ft(!1)},role:"menuitem","data-testid":"view-overflow-evals",children:[t.jsx(js,{size:14}),t.jsx("span",{children:"Evals"})]}),t.jsxs("button",{className:`view-toggle-overflow-item${A==="stash-recovery"?" active":""}`,onClick:()=>{P("stash-recovery"),ft(!1)},role:"menuitem","data-testid":"view-overflow-stash-recovery",children:[t.jsx(Oa,{size:14}),t.jsx("span",{children:"Stash Recovery"}),f>0?t.jsx("span",{className:"btn-badge",children:f}):null]}),re?.researchView&&t.jsxs("button",{className:`view-toggle-overflow-item${A==="research"?" active":""}`,onClick:()=>{P("research"),ft(!1)},role:"menuitem","data-testid":"view-overflow-research",children:[t.jsx(Gi,{size:14}),t.jsx("span",{children:"Research"})]}),re?.insights&&t.jsxs("button",{className:`view-toggle-overflow-item${A==="insights"?" active":""}`,onClick:()=>{P("insights"),ft(!1)},role:"menuitem","data-testid":"view-overflow-insights",children:[t.jsx(cs,{size:14}),t.jsx("span",{children:"Insights"})]}),q&&t.jsxs("button",{className:`view-toggle-overflow-item${A==="skills"?" active":""}`,onClick:()=>{P("skills"),ft(!1)},role:"menuitem","data-testid":"view-overflow-skills",children:[t.jsx(as,{size:14}),t.jsx("span",{children:"Skills"})]}),re?.memoryView&&t.jsxs("button",{className:`view-toggle-overflow-item${A==="memory"?" active":""}`,onClick:()=>{P("memory"),ft(!1)},role:"menuitem","data-testid":"view-toggle-memory",children:[t.jsx(Po,{size:14}),t.jsx("span",{children:"Memory"})]}),re?.devServerView&&t.jsxs("button",{className:`view-toggle-overflow-item${A==="dev-server"||A==="devserver"?" active":""}`,onClick:()=>{P("devserver"),ft(!1)},role:"menuitem","data-testid":"view-toggle-devserver",children:[t.jsx(Er,{size:14}),t.jsx("span",{children:"Dev Server"}),t.jsx("span",{className:"visually-hidden","data-testid":"view-toggle-dev-server"})]}),O&&k&&t.jsxs("button",{className:`view-toggle-overflow-item${R?" active":""}`,onClick:()=>{k(),ft(!1)},role:"menuitem","data-testid":"view-overflow-todos",children:[t.jsx(Vu,{size:14}),t.jsx("span",{children:"Todos"})]}),U.filter(z=>z.view.placement!=="primary").sort((z,_e)=>(z.view.order??Number.MAX_SAFE_INTEGER)-(_e.view.order??Number.MAX_SAFE_INTEGER)).map(z=>{const _e=Mo(z.pluginId,z.view.viewId),Rt=tc(z.view.icon);return t.jsxs("button",{className:`view-toggle-overflow-item${A===_e||A==="graph"&&z.pluginId==="fusion-plugin-dependency-graph"&&z.view.viewId==="graph"?" active":""}`,onClick:()=>{P(z.pluginId==="fusion-plugin-dependency-graph"&&z.view.viewId==="graph"?"graph":_e),ft(!1)},role:"menuitem","data-testid":`view-overflow-plugin-${z.pluginId}-${z.view.viewId}`,children:[t.jsx(Rt,{size:14}),t.jsx("span",{children:z.view.label})]},`${z.pluginId}:${z.view.viewId}`)})]})]})]}),!Le&&o&&t.jsx("button",{className:"btn-icon",onClick:z=>o(z.currentTarget.getBoundingClientRect()),title:"View usage","data-testid":"desktop-header-usage-btn",children:t.jsx(Vs,{size:16})}),!Le&&c&&t.jsx("button",{className:"btn-icon",onClick:c,title:"System Stats","data-testid":"desktop-header-system-stats-btn",children:t.jsx(Er,{size:16})}),!Le&&l&&t.jsx("button",{className:"btn-icon",onClick:l,title:"View Activity Log",children:t.jsx(Oa,{size:16})}),!Le&&!qe&&t.jsx("button",{className:"btn-icon",onClick:n,title:"Import from GitHub",children:t.jsx(Ph,{size:16})}),!Le&&t.jsxs("button",{className:`btn-icon${r>0?" btn-icon--has-indicator":""}`,onClick:r>0&&a?a:s,title:r>0?"Resume planning session":"Create a task with AI planning","data-testid":"planning-btn",style:{position:"relative"},children:[t.jsx(Di,{size:16}),r>0&&t.jsx("span",{className:"header-badge header-badge--pulse","data-testid":"planning-badge","aria-label":`${r} active planning session${r!==1?"s":""}`,children:r})]}),!Le&&t.jsxs("div",{className:"terminal-split-btn",ref:rn,children:[t.jsx("button",{className:"btn-icon btn-icon--terminal terminal-split-btn__main",onClick:S,title:"Open Terminal","data-testid":"terminal-toggle-btn",children:t.jsx(Ji,{size:16})}),y&&j&&t.jsxs(t.Fragment,{children:[t.jsx("span",{className:"terminal-split-btn__divider"}),t.jsx("button",{ref:qt,className:`btn-icon terminal-split-btn__chevron${ue?" btn-icon--active":""}`,onClick:()=>ot(z=>!z),title:"Scripts","aria-haspopup":"listbox","aria-expanded":ue,"aria-label":"Quick scripts","data-testid":"scripts-btn",children:t.jsx(vn,{size:12,className:`quick-scripts-dropdown__trigger-chevron${ue?" rotate":""}`})}),ue&&t.jsx("div",{ref:we,tabIndex:-1,className:"quick-scripts-dropdown__menu",role:"listbox","aria-label":"Scripts",onKeyDown:le,"data-testid":"quick-scripts-dropdown",style:kt?{position:"fixed",top:`${kt.top}px`,left:`${kt.left}px`,width:`${kt.width}px`,right:"auto"}:void 0,children:Je?t.jsxs("div",{className:"quick-scripts-dropdown__loading","data-testid":"quick-scripts-loading",children:[t.jsx(St,{size:16,className:"animate-spin"}),t.jsx("span",{children:"Loading scripts..."})]}):Ae.length===0?t.jsxs("div",{className:"quick-scripts-dropdown__empty","data-testid":"quick-scripts-empty",children:[t.jsx("div",{className:"quick-scripts-dropdown__empty-icon",children:t.jsx(Ji,{size:16})}),t.jsx("p",{children:"No scripts configured"}),t.jsx("button",{className:"quick-scripts-dropdown__empty-action btn",onClick:ae,children:"Add your first script"})]}):t.jsxs(t.Fragment,{children:[t.jsx("div",{className:"quick-scripts-dropdown__list",children:Ae.map(([z,_e],Rt)=>t.jsxs("button",{className:`quick-scripts-dropdown__item ${nt===Rt?"highlighted":""}`,onClick:()=>on(z,_e),role:"option","aria-selected":nt===Rt,"data-testid":`quick-script-item-${z}`,children:[t.jsx(is,{size:14,className:"quick-scripts-dropdown__item-icon"}),t.jsxs("div",{className:"quick-scripts-dropdown__item-info",children:[t.jsx("span",{className:"quick-scripts-dropdown__item-name",children:z}),t.jsx("span",{className:"quick-scripts-dropdown__item-command",title:_e,children:_e.length>50?`${_e.slice(0,50)}...`:_e})]})]},z))}),t.jsx("div",{className:"quick-scripts-dropdown__footer",children:t.jsxs("button",{className:`quick-scripts-dropdown__manage ${pt&&nt===Ae.length?"highlighted":""}`,onClick:ae,"data-testid":"quick-scripts-manage",children:[t.jsx(_o,{size:14}),t.jsx("span",{children:"Manage Scripts..."})]})})]})})]})]}),!Le&&C&&t.jsx("button",{className:`btn-icon${x?" btn-icon--active":""}`,onClick:C,title:"Browse files","data-testid":"files-toggle-btn",children:t.jsx(ws,{size:16})}),!Le&&g&&t.jsx("button",{className:"btn-icon",onClick:g,title:"Git Manager","data-testid":"git-manager-btn",children:t.jsx(Is,{size:16})}),!Le&&b&&t.jsx("button",{className:"btn-icon",onClick:b,title:"Workflow Steps","data-testid":"workflow-steps-btn",children:t.jsx(Jl,{size:16})}),!Le&&t.jsxs("div",{style:{position:"relative"},children:[t.jsx("button",{ref:pn,className:"btn-icon",onClick:()=>yt(z=>!z),title:"More actions","aria-label":"More actions","aria-expanded":Mt,"aria-haspopup":"menu","data-testid":"desktop-overflow-trigger",children:t.jsx(ru,{size:16})}),Mt&&t.jsxs("div",{ref:an,className:"desktop-overflow-menu",role:"menu","aria-label":"More actions",children:[w&&v!==!1&&t.jsxs("button",{className:"view-toggle-overflow-item",onClick:()=>{w(),yt(!1)},role:"menuitem","data-testid":"desktop-overflow-nodes-btn",children:[t.jsx($o,{size:14}),t.jsx("span",{children:"Nodes"})]}),t.jsxs("button",{className:"view-toggle-overflow-item",onClick:()=>{ee(p),yt(!1)},role:"menuitem","data-testid":"desktop-overflow-schedules-btn",children:[t.jsx(Yi,{size:14}),t.jsx("span",{children:"Automation"})]})]})]}),t.jsxs("div",{className:"engine-control-split-btn",ref:Jt,children:[t.jsx("button",{className:`btn-icon engine-control-split-btn__main${E?" btn-icon--stopped":""}`,onClick:G,title:E?"Start AI engine":"Stop AI engine","data-testid":"engine-control-main-btn",children:E?t.jsx(is,{size:16}):t.jsx(Pi,{size:16})}),t.jsx("span",{className:"engine-control-split-btn__divider"}),t.jsx("button",{className:`btn-icon engine-control-split-btn__chevron${Ge?" btn-icon--active":""}`,onClick:()=>K(z=>!z),title:"Engine options","aria-haspopup":"menu","aria-expanded":Ge,"data-testid":"engine-control-chevron-btn",children:t.jsx(vn,{size:12})}),Ge&&t.jsx("div",{className:"engine-control-split-btn__menu",role:"menu",children:t.jsxs("button",{className:`engine-control-split-btn__menu-item${_?" engine-control-split-btn__menu-item--active":""}`,onClick:()=>{H?.(),K(!1)},role:"menuitem",title:_?"Resume scheduling":"Pause triage",disabled:!!E,"data-testid":"engine-control-pause-triage-btn",children:[_?t.jsx(is,{size:14}):t.jsx(di,{size:14}),t.jsx("span",{children:_?"Resume scheduling":"Pause triage"})]})})]}),!Le&&t.jsx("button",{className:"btn-icon",onClick:e,title:"Settings",children:t.jsx(_o,{size:16})}),t.jsx(pa,{slotId:"header-action",projectId:ie}),Le&&!ct&&t.jsx("button",{ref:hn,className:"btn-icon compact-overflow-trigger",onClick:ce,title:"More header actions","aria-label":"More header actions","aria-expanded":he,"aria-haspopup":"menu",children:t.jsx(ru,{size:16})}),Le&&!ct&&he&&t.jsxs("div",{ref:un,className:"mobile-overflow-menu",role:"menu","aria-label":"Additional header actions",children:[me.length>=1&&Me&&t.jsxs("button",{className:"mobile-overflow-item",onClick:()=>ee(Me),role:"menuitem","data-testid":"overflow-project-selector-btn",children:[t.jsx(vc,{size:16}),t.jsx("span",{children:"Projects"})]}),C&&t.jsxs("button",{className:"mobile-overflow-item",onClick:()=>ee(C),role:"menuitem","data-testid":"overflow-files-btn",children:[t.jsx(ws,{size:16}),t.jsx("span",{children:"Browse Files"})]}),t.jsxs("button",{className:`mobile-overflow-item${r>0?" mobile-overflow-item--has-indicator":""}`,onClick:()=>ee(r>0&&a?a:s),role:"menuitem","data-testid":"overflow-planning-btn",children:[t.jsxs("span",{className:"mobile-overflow-icon-wrapper",children:[t.jsx(Di,{size:16}),r>0&&t.jsx("span",{className:"header-badge header-badge--pulse","data-testid":"overflow-planning-badge",children:r})]}),t.jsx("span",{children:r>0?`Resume planning session (${r})`:"Create a task with AI planning"})]}),g&&t.jsxs("button",{className:"mobile-overflow-item",onClick:()=>ee(g),role:"menuitem","data-testid":"overflow-git-btn",children:[t.jsx(Is,{size:16}),t.jsx("span",{children:"Git Manager"})]}),w&&v!==!1&&t.jsxs("button",{className:"mobile-overflow-item",onClick:()=>ee(w),role:"menuitem","data-testid":"overflow-nodes-btn",children:[t.jsx($o,{size:16}),t.jsx("span",{children:"Nodes"})]}),!qe&&t.jsxs("button",{className:"mobile-overflow-item",onClick:()=>ee(n),role:"menuitem",children:[t.jsx(Ph,{size:16}),t.jsx("span",{children:"Import from GitHub"})]}),t.jsxs("div",{className:"mobile-overflow-group","data-testid":"overflow-terminal-group",children:[t.jsxs("div",{className:"mobile-overflow-split-row",children:[t.jsxs("button",{className:"mobile-overflow-item mobile-overflow-split-primary",onClick:()=>ee(S),role:"menuitem","data-testid":"overflow-terminal-primary-btn",children:[t.jsx(Ji,{size:16}),t.jsx("span",{children:"Terminal"})]}),t.jsx("button",{className:"mobile-overflow-split-toggle",onClick:()=>ut(z=>!z),role:"menuitem","aria-expanded":De,"aria-haspopup":"menu","aria-label":"Show scripts","data-testid":"overflow-terminal-submenu-toggle",children:t.jsx(Wn,{size:14,className:`mobile-overflow-chevron${De?" mobile-overflow-chevron--open":""}`})})]}),De&&t.jsx("div",{className:"mobile-overflow-submenu",role:"menu","aria-label":"Scripts submenu",children:ln?t.jsxs("div",{className:"mobile-overflow-submenu-loading","data-testid":"overflow-scripts-loading",children:[t.jsx(St,{size:14,className:"animate-spin"}),t.jsx("span",{children:"Loading scripts…"})]}):Tt.length>0?t.jsxs(t.Fragment,{children:[Tt.map(([z,_e])=>t.jsxs("button",{className:"mobile-overflow-item mobile-overflow-subitem",onClick:()=>{j&&j(z,_e),pe(!1),ut(!1)},role:"menuitem","data-testid":`overflow-script-item-${z}`,children:[t.jsx(is,{size:14}),t.jsx("span",{children:z})]},z)),y&&t.jsxs("button",{className:"mobile-overflow-item mobile-overflow-subitem mobile-overflow-subitem--manage",onClick:()=>ee(y),role:"menuitem","data-testid":"overflow-scripts-manage",children:[t.jsx(ki,{size:14}),t.jsx("span",{children:"Manage Scripts…"})]})]}):y&&t.jsxs("button",{className:"mobile-overflow-item mobile-overflow-subitem",onClick:()=>ee(y),role:"menuitem","data-testid":"overflow-scripts-manage",children:[t.jsx(ki,{size:14}),t.jsx("span",{children:"No scripts — add one…"})]})})]}),t.jsxs("button",{className:"mobile-overflow-item",onClick:()=>ee(p),role:"menuitem","data-testid":"overflow-schedules-btn",children:[t.jsx(Yi,{size:16}),t.jsx("span",{children:"Automation"})]}),l&&t.jsxs("button",{className:"mobile-overflow-item",onClick:()=>ee(l),role:"menuitem","data-testid":"overflow-activity-log-btn",children:[t.jsx(Oa,{size:16}),t.jsx("span",{children:"View Activity Log"})]}),d&&t.jsxs("button",{className:"mobile-overflow-item",onClick:()=>ee(d),role:"menuitem","data-testid":"overflow-mailbox-btn",children:[t.jsx(za,{size:16}),t.jsxs("span",{children:["Mailbox",u>0?` (${u})`:""]}),h>0&&t.jsx("span",{className:"header-badge","data-testid":"overflow-mailbox-approval-badge",children:h})]}),o&&t.jsxs("button",{className:"mobile-overflow-item",onClick:z=>ee(()=>o(z.currentTarget.getBoundingClientRect())),role:"menuitem","data-testid":"overflow-usage-btn",children:[t.jsx(Vs,{size:16}),t.jsx("span",{children:"View Usage"})]}),b&&t.jsxs("button",{className:"mobile-overflow-item",onClick:()=>ee(b),role:"menuitem","data-testid":"overflow-workflow-steps-btn",children:[t.jsx(Jl,{size:16}),t.jsx("span",{children:"Workflow Steps"})]}),t.jsxs("button",{className:"mobile-overflow-item",onClick:()=>ee(e),role:"menuitem",children:[t.jsx(_o,{size:16}),t.jsx("span",{children:"Settings"})]})]})]})]}),sn&&xt&&t.jsxs("div",{className:"header-floating-search",children:[t.jsxs("div",{className:"header-search",children:[t.jsx(Gi,{size:14,className:"header-search-icon"}),t.jsx("input",{autoFocus:!0,type:"text",placeholder:"Search tasks...",value:ge,onChange:z=>L(z.target.value),className:"header-search-input"}),t.jsx("button",{className:"header-search-clear",onClick:zn,"aria-label":"Close search",children:t.jsx(bn,{size:14})})]}),xn&&t.jsxs("div",{className:"header-branch-filters","data-testid":"header-branch-filters-desktop",children:[t.jsxs("label",{className:"header-branch-filter-label",children:[t.jsx("span",{children:"Working branch"}),t.jsxs("select",{className:"header-branch-filter-select",value:M,onChange:z=>W?.(z.target.value),"data-testid":"working-branch-filter",children:[t.jsx("option",{value:"",children:"All working branches"}),t.jsx("option",{value:ul,children:"No working branch"}),D.map(z=>t.jsx("option",{value:z,children:z},z))]})]}),t.jsxs("label",{className:"header-branch-filter-label",children:[t.jsx("span",{children:"Base branch"}),t.jsxs("select",{className:"header-branch-filter-select",value:$,onChange:z=>de?.(z.target.value),"data-testid":"target-branch-filter",children:[t.jsx("option",{value:"",children:"All base branches"}),t.jsx("option",{value:ul,children:"No base branch"}),N.map(z=>t.jsx("option",{value:z,children:z},z))]})]})]})]}),L&&se&&Qe&&t.jsxs("div",{className:"header-floating-search",children:[t.jsxs("div",{ref:Wt,className:"header-search mobile-search-expanded",children:[t.jsx(Gi,{size:14,className:"header-search-icon"}),t.jsx("input",{ref:gn,autoFocus:!0,type:"text",placeholder:"Search tasks...",value:ge,onChange:z=>L(z.target.value),className:"header-search-input"}),t.jsx("button",{className:"header-search-clear",onClick:Se,"aria-label":"Close search",children:t.jsx(bn,{size:14})})]}),xn&&t.jsxs("div",{className:"header-branch-filters","data-testid":"header-branch-filters-mobile",children:[t.jsxs("label",{className:"header-branch-filter-label",children:[t.jsx("span",{children:"Working branch"}),t.jsxs("select",{className:"header-branch-filter-select",value:M,onChange:z=>W?.(z.target.value),"data-testid":"working-branch-filter-mobile",children:[t.jsx("option",{value:"",children:"All working branches"}),t.jsx("option",{value:ul,children:"No working branch"}),D.map(z=>t.jsx("option",{value:z,children:z},z))]})]}),t.jsxs("label",{className:"header-branch-filter-label",children:[t.jsx("span",{children:"Base branch"}),t.jsxs("select",{className:"header-branch-filter-select",value:$,onChange:z=>de?.(z.target.value),"data-testid":"target-branch-filter-mobile",children:[t.jsx("option",{value:"",children:"All base branches"}),t.jsx("option",{value:ul,children:"No base branch"}),N.map(z=>t.jsx("option",{value:z,children:z},z))]})]})]})]})]})}function $h(e){return e==="urgent"?3:e==="high"?2:e==="low"?0:1}function Dh(e,n){return $h(n)-$h(e)}function id(e,n){const s=Number.parseInt(e.slice(e.lastIndexOf("-")+1),10),a=Number.parseInt(n.slice(n.lastIndexOf("-")+1),10);return Number.isFinite(s)&&Number.isFinite(a)&&s!==a?s-a:e.localeCompare(n)}function Lh(e){const n=e.columnMovedAt??e.updatedAt??e.createdAt,s=Date.parse(n);return Number.isFinite(s)?s:0}function Oh(e){return e==="merging"||e==="merging-pr"||e==="merging-fix"}function Kb(e,n){return n==="todo"?[...e].sort((s,a)=>{const r=Dh(s.priority,a.priority);return r!==0?r:s.createdAt!==a.createdAt?s.createdAt.localeCompare(a.createdAt):id(s.id,a.id)}):[...e].sort((s,a)=>{if(n==="done"){const o=Lh(a)-Lh(s);return o!==0?o:id(s.id,a.id)}if(n==="in-review"){const o=Oh(s.status),l=Oh(a.status);if(o!==l)return o?-1:1}const r=Dh(s.priority,a.priority);return r!==0?r:id(s.id,a.id)})}function sE(e,n=1400){const s=i.useRef(null),[a,r]=i.useState(!1),o=i.useRef(null);return i.useEffect(()=>(s.current!==null&&e>s.current&&(r(!0),o.current=setTimeout(()=>r(!1),n)),s.current=e,()=>{o.current!==null&&clearTimeout(o.current)}),[e,n]),a}function iE({isOpen:e,options:n,onConfirm:s,onCancel:a}){const r=i.useRef(null);return i.useEffect(()=>{if(!e)return;r.current?.focus();const o=l=>{l.key==="Escape"&&(l.preventDefault(),a())};return document.addEventListener("keydown",o),()=>document.removeEventListener("keydown",o)},[e,a]),!e||!n?null:t.jsx("div",{className:"modal-overlay open confirm-dialog-overlay",onClick:a,children:t.jsxs("div",{className:"modal confirm-dialog",onClick:o=>o.stopPropagation(),role:"dialog","aria-modal":"true","aria-label":n.title,children:[t.jsxs("div",{className:"modal-header",children:[t.jsx("h3",{children:n.title}),t.jsx("button",{className:"modal-close",onClick:a,"aria-label":"Close confirmation dialog",children:"×"})]}),t.jsx("div",{className:"confirm-dialog__body",children:n.message}),t.jsxs("div",{className:"modal-actions confirm-dialog__actions",children:[t.jsx("button",{ref:r,className:"btn",onClick:a,children:n.cancelLabel??"Cancel"}),t.jsx("button",{className:`btn ${n.danger?"btn-danger":"btn-primary"}`,onClick:s,children:n.confirmLabel??"Confirm"})]})]})})}const Jb=i.createContext(null);function aE({children:e}){const[n,s]=i.useState([]),a=i.useRef([]),r=i.useCallback(u=>{s(h=>{const m=u(h);return a.current=m,m})},[]),o=i.useCallback(u=>new Promise(h=>{r(m=>[...m,{options:u,resolve:h}])}),[r]),l=i.useCallback(u=>{const h=a.current[0];h&&(h.resolve(u),r(m=>m.slice(1)))},[r]),c=n[0]??null,d=i.useMemo(()=>({confirm:o}),[o]);return ga.createElement(Jb.Provider,{value:d},e,ga.createElement(iE,{isOpen:c!==null,options:c?.options??null,onConfirm:()=>l(!0),onCancel:()=>l(!1)}))}function ti(){const e=i.useContext(Jb);return e||{confirm:async n=>!1}}function rE(e,n){return e==="open"?"card-github-badge--open":n==="completed"?"card-github-badge--completed":n==="not_planned"?"card-github-badge--not-planned":"card-github-badge--closed"}function oE({prInfo:e,issueInfo:n,onIssueRefresh:s}){return t.jsxs(t.Fragment,{children:[e&&t.jsxs("a",{className:`card-github-badge card-github-badge--${e.status}`,title:`PR #${e.number}: ${e.title}`,href:e.url,target:"_blank",rel:"noopener noreferrer",children:[t.jsx(Qs,{size:12}),t.jsxs("span",{children:["#",e.number]})]}),n&&t.jsxs("a",{className:`card-github-badge ${rE(n.state,n.stateReason)}`,title:`Issue #${n.number}: ${n.title}`,href:n.url,target:"_blank",rel:"noopener noreferrer",children:[t.jsx(bc,{size:12}),t.jsxs("span",{children:["#",n.number]})]})]})}function ml(e,n){return`${e??"default"}:${n}`}class sm{ws=null;listeners=new Set;badgeUpdates=new Map;retainedBadgeUpdates=new Map;subscriptionsByTask=new Map;reconnectTimeout=null;reconnectDelayMs=1e3;shouldReconnect=!1;isConnected=!1;projectId=null;snapshot={badgeUpdates:new Map,isConnected:!1};previousProjectIdRef=null;projectContextVersionRef=0;contextVersionAtStart=0;static RETAINED_BADGE_CAP=200;subscribe(n){return this.listeners.add(n),()=>{this.listeners.delete(n)}}getSnapshot(){return this.snapshot}setProjectId(n){if(this.projectId===n)return;this.previousProjectIdRef=this.projectId,this.projectContextVersionRef++,this.contextVersionAtStart=this.projectContextVersionRef;const s=this.subscriptionsByTask.size>0,a=[];for(const[r,o]of this.subscriptionsByTask){const l=r.split(":").slice(1).join(":");for(const c of o)a.push({hookId:c,taskId:l})}if(this.projectId=n,this.reset(),s){for(const{hookId:r,taskId:o}of a){const l=ml(this.projectId,o);this.subscriptionsByTask.set(l,new Set([r]))}this.shouldReconnect=this.subscriptionsByTask.size>0,this.connect()}}subscribeTask(n,s){const a=ml(this.projectId,s),r=this.retainedBadgeUpdates.get(a);r&&!this.badgeUpdates.has(a)&&(this.badgeUpdates.set(a,r),this.retainedBadgeUpdates.delete(a),this.emit());const o=this.subscriptionsByTask.get(a)??new Set,l=!o.has(n);o.add(n),this.subscriptionsByTask.set(a,o),this.shouldReconnect=this.subscriptionsByTask.size>0,this.connect(),l&&this.send({type:"subscribe",taskId:s,projectId:this.projectId})}unsubscribeTask(n,s){const a=ml(this.projectId,s),r=this.subscriptionsByTask.get(a);if(r){if(r.delete(n),r.size===0){this.subscriptionsByTask.delete(a);const o=this.badgeUpdates.get(a);if(o)for(this.retainedBadgeUpdates.delete(a),this.retainedBadgeUpdates.set(a,o);this.retainedBadgeUpdates.size>sm.RETAINED_BADGE_CAP;){const l=this.retainedBadgeUpdates.keys().next().value;if(!l)break;this.retainedBadgeUpdates.delete(l)}this.badgeUpdates.delete(a),this.send({type:"unsubscribe",taskId:s,projectId:this.projectId}),this.emit()}this.shouldReconnect=this.subscriptionsByTask.size>0,this.shouldReconnect||this.disconnect()}}cleanupHook(n){for(const s of[...this.subscriptionsByTask.keys()]){const a=s.split(":").slice(1).join(":");this.unsubscribeTask(n,a)}}reset(){this.disconnect(),this.badgeUpdates.clear(),this.retainedBadgeUpdates.clear(),this.subscriptionsByTask.clear(),this.shouldReconnect=!1,this.emit()}connect(){if(!this.shouldReconnect||typeof window>"u"||this.ws&&(this.ws.readyState===WebSocket.OPEN||this.ws.readyState===WebSocket.CONNECTING))return;const n=this.projectContextVersionRef;let a=`${window.location.protocol==="https:"?"wss:":"ws:"}//${window.location.host}/api/ws`;this.projectId&&(a+=`?projectId=${encodeURIComponent(this.projectId)}`);const r=new WebSocket(Li(a));this.ws=r,r.onopen=()=>{if(this.projectContextVersionRef!==n){r.close();return}this.isConnected=!0,this.reconnectDelayMs=1e3,this.emit();const o=new Set;for(const l of this.subscriptionsByTask.keys()){const c=l.split(":").slice(1).join(":");o.add(c)}for(const l of o)this.send({type:"subscribe",taskId:l,projectId:this.projectId})},r.onmessage=o=>{if(this.projectContextVersionRef===n)try{const l=JSON.parse(o.data);if(l.type!=="badge:updated"||l.projectId!==void 0&&l.projectId!==this.projectId)return;const c=ml(this.projectId,l.taskId),d=this.badgeUpdates.get(c);this.badgeUpdates.set(c,{prInfo:Fh(l,"prInfo")?l.prInfo??null:d?.prInfo,issueInfo:Fh(l,"issueInfo")?l.issueInfo??null:d?.issueInfo,timestamp:l.timestamp}),this.emit()}catch{}},r.onclose=()=>{this.projectContextVersionRef===n&&(this.ws=null,this.isConnected&&(this.isConnected=!1,this.emit()),this.shouldReconnect&&this.scheduleReconnect(n))},r.onerror=()=>{}}disconnect(){if(this.reconnectTimeout&&(clearTimeout(this.reconnectTimeout),this.reconnectTimeout=null),this.ws){const n=this.ws;this.ws=null,n.close()}this.isConnected&&(this.isConnected=!1,this.emit())}scheduleReconnect(n){if(this.reconnectTimeout)return;const s=n??this.projectContextVersionRef,a=Math.min(this.reconnectDelayMs,5e3);this.reconnectTimeout=setTimeout(()=>{this.reconnectTimeout=null,this.projectContextVersionRef===s&&this.shouldReconnect&&this.connect()},a),this.reconnectDelayMs=Math.min(this.reconnectDelayMs*2,5e3)}send(n){!this.ws||this.ws.readyState!==WebSocket.OPEN||this.ws.send(JSON.stringify(n))}emit(){this.snapshot={badgeUpdates:new Map(this.badgeUpdates),isConnected:this.isConnected};for(const n of this.listeners)n()}}const Ta=new sm;let lE=0;function Fh(e,n){return Object.prototype.hasOwnProperty.call(e,n)}function cE(e){const n=i.useRef(null);n.current===null&&(n.current=`badge-hook-${lE++}`);const s=i.useSyncExternalStore(o=>Ta.subscribe(o),()=>Ta.getSnapshot(),()=>Ta.getSnapshot()),a=i.useCallback(o=>{Ta.subscribeTask(n.current,o)},[]),r=i.useCallback(o=>{Ta.unsubscribeTask(n.current,o)},[]);return i.useEffect(()=>{Ta.setProjectId(e??null)},[e]),i.useEffect(()=>()=>{Ta.cleanupHook(n.current)},[]),{badgeUpdates:s.badgeUpdates,isConnected:s.isConnected,subscribeToBadge:a,unsubscribeFromBadge:r}}const dE={data:new Map},uE=5e3;function mE(e,n){return n?`${n}::${e}`:e}function hE(e,n){const s=dE.data.get(mE(e,n));if(!(!s||Date.now()-s.timestamp>uE))return s}const bu=new Map,pE=3e4;function Yb(e,n,s,a){return`${e}:${n??""}:${s??""}:${a??""}`}function fE(e,n,s,a){const r=Yb(e,n,s,a),o=bu.get(r);return o?Date.now()>o.expiresAt?(bu.delete(r),null):o.stats:null}function gE(e,n,s,a,r){const o=Yb(e,n,s,a);bu.set(o,{stats:r,expiresAt:Date.now()+pE})}function bE(e,n,s,a,r={}){const o=r.enabled??!0,l=r.worktree,c=r.stepVersion,d=r.pollIntervalMs,[u,h]=i.useState(null),[m,f]=i.useState(!1);return i.useEffect(()=>{if(!o){h(null),f(!1);return}const p=n==="done",g=(n==="in-progress"||n==="in-review")&&!!l;if(!e||!p&&!g){h(null),f(!1);return}const w=g?l:void 0,v=c!==void 0?String(c):void 0;let b=!1;async function y(S=!1){if(!S){const C=fE(e,a,w,v);if(C){b||(h(C),f(!1));return}}f(!0);try{const C=await $b(e,w,a);b||(h(C.stats),gE(e,a,w,v,C.stats))}catch{b||h(null)}finally{b||f(!1)}}y();let j;return d&&g&&(j=setInterval(()=>{y(!0)},d)),()=>{b=!0,j&&clearInterval(j)}},[e,n,s,a,o,l,c,d]),{stats:u,loading:m}}const xE=new Set(["failed","stuck-killed"]);function nc(e,n,s){if(e.column!=="in-progress"||e.status&&xE.has(e.status)||!n||n<=0)return!1;const a=new Date(e.updatedAt).getTime();return(s??Date.now())-a>n}function vE(e){return e.stalledReview}const Qb="Stall",yE={"merge-blocker":{headline:"Merge blocked by a pre-merge check",description:"A workflow step or merge precondition is reporting a blocker. The task is waiting for that check to pass before it can finalize.",suggestedAction:"Open the Review tab to see which step is blocking, then fix the failure or override the step."},"transient-merge-status-no-owner":{headline:"Stuck in a transient merge state with no active merger",description:"The task is parked in a merging/merging-pr/merging-fix status but no merger process owns it. Self-healing will retry, but if this repeats the merge worker may need attention.",suggestedAction:"Wait one self-healing cycle; if it persists, inspect engine logs for crashed merger runs."},"merge-retries-exhausted":{headline:"Auto-merge retries exhausted",description:"The merger hit its retry ceiling without confirming a merge. The task will not be re-enqueued automatically.",suggestedAction:"Resolve the underlying merge problem manually and re-run the merge from the Review tab, or move the task back to in-progress."},"no-worktree-no-merge-confirmed":{headline:"No worktree on disk and merge not confirmed",description:"The task's working tree is gone but the merge was never confirmed. Either the worktree was removed prematurely or the merge metadata is incomplete.",suggestedAction:"Check the Changes tab and Git history; if the work landed, mark the merge confirmed, otherwise re-create the worktree."}};function wE(e){return{badgeLabel:Qb,code:e.code,headline:"In-review stall surfaced",description:e.reason,suggestedAction:"Open the activity log for details."}}function Xb(e){const n=yE[e.code];return n?{badgeLabel:Qb,code:e.code,...n}:wE(e)}function Zb(e){return e.column==="in-review"&&e.paused!==!0&&e.inReviewStall!=null}function kE(e){switch(e){case"passed":return"done";case"failed":return"failed";case"skipped":return"skipped";case"pending":default:return"pending"}}function jE(e){return e==="done"||e==="skipped"}function NE(e,n,s){const a=s?.get(e)?.trim();if(a)return a;const r=n?.workflowStepName?.trim();return r||e}function ex(e,n){const s=(e.steps??[]).map((d,u)=>({id:`step-${u}`,name:d.name,status:d.status,source:"step",phase:"pre-merge"})),a=new Map((e.workflowStepResults??[]).map(d=>[d.workflowStepId,d])),r=(e.enabledWorkflowSteps??[]).map(d=>{const u=a.get(d);return{id:`workflow-${d}`,name:NE(d,u,n),status:u?kE(u.status):"pending",source:"workflow",phase:u?.phase??"pre-merge"}}),o=[...s,...r],l=o.length,c=o.filter(d=>jE(d.status)).length;return{total:l,completed:c,items:o}}function SE(e){return(e.action||e.outcome||"").replace(/^\[timing\]\s*/i,"").replace(/^\[[^\]]+\]\s*/i,"").replace(/\s+in\s+\d+(?:\.\d+)?ms\b/i,"").replace(/\s+after\s+\d+(?:\.\d+)?ms\b/i,"").trim()||"Timing event"}function tx(e){return e.filter(n=>{const s=typeof n.action=="string"?n.action:"",a=typeof n.outcome=="string"?n.outcome:"";return s.includes("[timing]")||a.includes("[timing]")}).map(n=>{const a=`${n.action??""}
649
- ${n.outcome??""}`.match(/(\d+(?:\.\d+)?)ms\b/i),r=a?Number(a[1]):void 0;return{timestamp:n.timestamp,durationMs:Number.isFinite(r)?r:void 0,summary:SE(n)}})}function nx(e){if(!e||e.length===0)return null;let n=0,s=0;for(const a of tx(e))typeof a.durationMs=="number"&&(n+=a.durationMs,s+=1);return s>0?n:null}function Ha(e){if(!e)return null;const n=Date.parse(e);return Number.isFinite(n)?n:null}function sx(e,n){if(!e||e.length===0)return null;let s=0,a=0;for(const r of e){if(!r.startedAt)continue;const o=Ha(r.startedAt);if(o==null)continue;let l;if(r.completedAt){const c=Ha(r.completedAt);if(c==null||c<o)continue;l=c}else l=Math.max(o,n);s+=l-o,a+=1}return a>0?s:null}function ix(e,n,s){const a=Ha(e);if(a==null)return null;const r=Ha(n),o=r!=null&&r>=a?r:s;return Math.max(0,o-a)}function im(e){if(!(e instanceof Error))return null;const n=e.details;if(n?.code==="TASK_HAS_DEPENDENTS"&&Array.isArray(n.dependentIds))return{dependentIds:n.dependentIds.filter(a=>typeof a=="string")};const s=e.message.match(/[A-Z]+-\d+/g)??[];return s.length>1?{dependentIds:[...new Set(s.slice(1))]}:null}const xu=new Map;async function CE(e,n){const s=xu.get(e);if(s)return s;try{const a=await Db(e,n);return xu.set(e,a.title),a.title}catch{return e}}const zh=12;function EE(e){return e.length<=zh?e:e.slice(0,zh-3)+"..."}const vu=new Map;async function _E(e,n){const s=vu.get(e);if(s)return s;try{const a=await gu(e,n);return vu.set(e,a.name),a.name}catch{return e}}function ME(e){return typeof e=="string"&&wa.includes(e)?e:_s}function AE(e,n){return e.length<=n?e:e.slice(0,n-3)+"..."}function ax(e){const n=e.sourceMetadata?.agentName;if(typeof n=="string"&&n.trim().length>0)return n.trim();if(typeof e.sourceAgentId=="string"&&e.sourceAgentId.trim().length>0)return e.sourceAgentId.trim()}function RE(e){return e.sourceType==="agent_heartbeat"||e.sourceType==="automation"||!!ax(e)}const IE=new Set(["triage","todo"]),Bh=new Set(["planning","researching","executing","finalizing","merging","merging-fix"]),Uh=new Set(["merging","merging-pr","merging-fix"]),TE={triage:"var(--triage)",todo:"var(--todo)","in-progress":"var(--in-progress)","in-review":"var(--in-review)",done:"var(--done)",archived:"var(--text-muted)"},PE=new Set(["in-progress","in-review","done"]),$E=3e4;function DE(e){return e==="merging-fix"?"Merging fixes…":e}function LE(e){const n=Ha(e.columnMovedAt??e.updatedAt);if(n==null)return null;const s=Date.now();return n>s?null:n}function Hh(e,n){const s=Ha(e.columnMovedAt??e.updatedAt);return s==null?null:Math.max(0,n-s)}function wo(e,n){return ix(e.executionStartedAt,e.executionCompletedAt,n)}function OE(e){return e.column==="done"?LE(e):null}function rx(e,n){const s=Ha(e.updatedAt);return s==null?null:Math.max(0,n-s)}function FE(e,n){const s=wo(e,n);if(s!=null)return s;const a=rx(e,n),r=ko(e,n);return r!=null?r+(a??0):a}function ko(e,n){if(typeof e.timedExecutionMs=="number")return e.timedExecutionMs;const s=nx(e.log),a=sx(e.workflowStepResults,n);return s==null&&a==null?null:(s??0)+(a??0)}function qh(e){if(!Number.isFinite(e)||e<0)return"";if(e<6e4)return"<1m";const n=Math.floor(e/6e4);if(n<60)return`${n}m`;const s=Math.floor(n/60);return s<24?`${s}h`:`${Math.floor(s/24)}d`}function Vh(e){if(!e)return null;const n=e.trim();return n.length>0?n:null}function zE(e){const n=Vh(e.branch),s=Vh(e.baseBranch),a=`fusion/${e.id.toLowerCase()}`,r=n&&(n===a||n.startsWith(`${a}-`))?null:n,o=s?.toLowerCase()==="main"?null:s;return{branch:r,baseBranch:o??null}}function Wh(e){if(!Number.isFinite(e)||e<0||e===0)return"";const n=Math.ceil(e/6e4);if(n<59)return`${n}m`;const s=Math.ceil(e/36e5);return s<24?`${s}h`:`${Math.ceil(e/864e5)}d`}function Gh(e,n){if(!e&&!n)return!0;if(!e||!n)return!1;const s=Object.keys(e),a=Object.keys(n);return s.length!==a.length?!1:s.every(r=>e[r]===n[r])}function BE(e,n){return e.length!==n.length?!1:e.every((s,a)=>s.name===n[a]?.name&&s.status===n[a]?.status)}function ad(e,n){return e.length!==n.length?!1:e.every((s,a)=>s===n[a])}function UE(e,n){return!e&&!n?!0:!e||!n||e.length!==n.length?!1:e.every((s,a)=>s===n[a])}function HE(e){const n=e?.issueUrl;return typeof n=="string"&&n.length>0?n:void 0}function Kh(e){if(!e)return null;const n=e.match(/^https?:\/\/github\.com\/([^/]+)\/([^/]+)\/issues\/(\d+)(?:$|[/?#])/i);if(!n)return null;const s=Number(n[3]);return!Number.isInteger(s)||s<=0?null:{owner:n[1],repo:n[2],number:s}}function qE(e,n){return!e&&!n?!0:!e||!n||e.length!==n.length?!1:e.every((s,a)=>{const r=n[a];return r?s.workflowStepId===r.workflowStepId&&s.workflowStepName===r.workflowStepName&&s.phase===r.phase&&s.status===r.status&&s.output===r.output&&s.startedAt===r.startedAt&&s.completedAt===r.completedAt:!1})}function VE(e,n){return!e&&!n?!0:!e||!n||e.length!==n.length?!1:e.every((s,a)=>{const r=n[a];return r?s.filename===r.filename&&s.mimeType===r.mimeType&&s.size===r.size:!1})}function WE(e,n){return!e&&!n?!0:!e||!n||e.length!==n.length?!1:e.every((s,a)=>{const r=n[a];return r?s.author===r.author&&s.text===r.text&&s.createdAt===r.createdAt:!1})}function GE(e,n){const s=e.task,a=n.task;return e.queued===n.queued&&e.projectId===n.projectId&&e.globalPaused===n.globalPaused&&e.taskStuckTimeoutMs===n.taskStuckTimeoutMs&&e.onOpenDetail===n.onOpenDetail&&e.addToast===n.addToast&&e.onUpdateTask===n.onUpdateTask&&e.onArchiveTask===n.onArchiveTask&&e.onUnarchiveTask===n.onUnarchiveTask&&e.onDeleteTask===n.onDeleteTask&&e.onRetryTask===n.onRetryTask&&e.onOpenDetailWithTab===n.onOpenDetailWithTab&&e.onOpenMission===n.onOpenMission&&e.onMoveTask===n.onMoveTask&&e.workflowStepNameLookup===n.workflowStepNameLookup&&e.disableDrag===n.disableDrag&&e.fanout?.totalCount===n.fanout?.totalCount&&e.fanout?.activeTodoCount===n.fanout?.activeTodoCount&&e.fanout?.isHighFanout===n.fanout?.isHighFanout&&e.fanout?.escalation?.blockingAgeMs===n.fanout?.escalation?.blockingAgeMs&&ad(e.fanout?.dependentIds??[],n.fanout?.dependentIds??[])&&ad(e.fanout?.staleBlockedByDependentIds??[],n.fanout?.staleBlockedByDependentIds??[])&&s.id===a.id&&s.title===a.title&&s.description===a.description&&s.column===a.column&&s.columnMovedAt===a.columnMovedAt&&s.timedExecutionMs===a.timedExecutionMs&&s.updatedAt===a.updatedAt&&s.createdAt===a.createdAt&&s.status===a.status&&s.priority===a.priority&&s.executionMode===a.executionMode&&s.paused===a.paused&&s.error===a.error&&s.size===a.size&&s.blockedBy===a.blockedBy&&s.worktree===a.worktree&&s.branch===a.branch&&s.baseBranch===a.baseBranch&&s.breakIntoSubtasks===a.breakIntoSubtasks&&s.currentStep===a.currentStep&&s.modelProvider===a.modelProvider&&s.modelId===a.modelId&&s.validatorModelProvider===a.validatorModelProvider&&s.validatorModelId===a.validatorModelId&&s.planningModelProvider===a.planningModelProvider&&s.planningModelId===a.planningModelId&&s.reviewLevel===a.reviewLevel&&s.missionId===a.missionId&&s.assignedAgentId===a.assignedAgentId&&s.mergeRetries===a.mergeRetries&&s.sourceType===a.sourceType&&s.sourceAgentId===a.sourceAgentId&&s.sourceMetadata?.issueUrl===a.sourceMetadata?.issueUrl&&s.sourceMetadata?.agentName===a.sourceMetadata?.agentName&&s.stalledReview?.reason===a.stalledReview?.reason&&s.stalledReview?.heuristic===a.stalledReview?.heuristic&&s.stalledReview?.matchCount===a.stalledReview?.matchCount&&s.stalledReview?.firstMatchAt===a.stalledReview?.firstMatchAt&&s.stalledReview?.lastMatchAt===a.stalledReview?.lastMatchAt&&VE(s.attachments,a.attachments)&&WE(s.comments,a.comments)&&ad(s.dependencies,a.dependencies)&&BE(s.steps,a.steps)&&UE(s.enabledWorkflowSteps,a.enabledWorkflowSteps)&&qE(s.workflowStepResults,a.workflowStepResults)&&Gh(s.prInfo,a.prInfo)&&Gh(s.issueInfo,a.issueInfo)}function KE({task:e,projectId:n,queued:s,onOpenDetail:a,addToast:r,globalPaused:o,onUpdateTask:l,onArchiveTask:c,onUnarchiveTask:d,onDeleteTask:u,onRetryTask:h,onOpenDetailWithTab:m,taskStuckTimeoutMs:f,onOpenMission:p,onMoveTask:g,lastFetchTimeMs:w,workflowStepNameLookup:v,disableDrag:b,fanout:y}){const[j,S]=i.useState(!1),[C,x]=i.useState(!1),[k,R]=i.useState(!1),[O,E]=i.useState(e.description||""),[_,G]=i.useState(!1),[H,A]=i.useState(e.column==="in-progress"||e.column==="triage"&&e.steps.some(ee=>ee.status==="done"||ee.status==="skipped")),[P,q]=i.useState(null),[Y,ge]=i.useState(null),[L,M]=i.useState(!1),[$,D]=i.useState(!1),[N,W]=i.useState(()=>Date.now()),de=i.useRef(null),me=i.useRef(!1),Ne=i.useRef(null),ve=i.useRef(null),[Me,ie]=i.useState(!1),{badgeUpdates:ye,subscribeToBadge:Z,unsubscribeFromBadge:fe}=cE(n),{confirm:Q}=ti(),F=i.useRef(null),X=i.useRef(!1),re=i.useCallback(ee=>ee instanceof Element?!!ee.closest("button, a, input, textarea, select, label, [role='button']"):!1,[]);i.useEffect(()=>{E(e.description||"")},[e.id,e.description]),i.useEffect(()=>{if(!L)return;const ee=Se=>{ve.current&&!ve.current.contains(Se.target)&&M(!1)};return document.addEventListener("click",ee),()=>document.removeEventListener("click",ee)},[L]),i.useEffect(()=>{if(!e.missionId){q(null);return}const ee=xu.get(e.missionId);if(ee){q(ee);return}let Se=!1;return CE(e.missionId,n).then(qe=>{Se||q(qe)}),()=>{Se=!0}},[e.missionId,n]),i.useEffect(()=>{if(!e.assignedAgentId){ge(null);return}const ee=vu.get(e.assignedAgentId);if(ee){ge(ee);return}ge(null);let Se=!1;return _E(e.assignedAgentId,n).then(qe=>{Se||ge(qe)}),()=>{Se=!0}},[e.assignedAgentId,n]),i.useEffect(()=>{if(k&&de.current){const ee=de.current;ee.focus(),ee.style.height="auto",ee.style.height=ee.scrollHeight+"px"}},[k]),i.useEffect(()=>{if(typeof IntersectionObserver>"u"){ie(!0);return}const ee=Ne.current;if(!ee)return;const Se=new IntersectionObserver(([qe])=>{ie(qe?.isIntersecting??!0)},{rootMargin:"200px"});return Se.observe(ee),()=>Se.disconnect()},[k,e.id]);const U=i.useCallback(ee=>{ee.dataTransfer.setData("text/plain",e.id),ee.dataTransfer.effectAllowed="move",S(!0)},[e.id]),be=i.useCallback(()=>{S(!1)},[]),Ue=i.useCallback(ee=>ee.dataTransfer.types.includes("Files"),[]),se=i.useCallback(ee=>{Ue(ee)&&(ee.preventDefault(),ee.stopPropagation(),ee.dataTransfer.dropEffect="copy",x(!0))},[Ue]),Ve=i.useCallback(ee=>{Ue(ee)&&(ee.preventDefault(),ee.stopPropagation(),x(!1))},[Ue]),Le=i.useCallback(async ee=>{if(!Ue(ee))return;ee.preventDefault(),ee.stopPropagation(),x(!1);const Se=Array.from(ee.dataTransfer.files);for(const qe of Se)try{await Ec(e.id,qe,n),r(`Attached ${qe.name} to ${e.id}`,"success")}catch(z){r(`Failed to attach ${qe.name}: ${Ie(z)}`,"error")}},[e.id,Ue,r]),ct=i.useCallback(()=>{k||a(e)},[e,a,k]),Ke=i.useCallback(ee=>{if(me.current){me.current=!1;return}re(ee.target)||ct()},[ct,re]),oe=i.useCallback(ee=>{const Se=ee.touches[0];Se&&(F.current={x:Se.clientX,y:Se.clientY,time:Date.now()},X.current=!1)},[]),Te=i.useCallback(ee=>{if(!F.current)return;const Se=ee.touches[0];if(!Se)return;const qe=Math.abs(Se.clientX-F.current.x),z=Math.abs(Se.clientY-F.current.y);(qe>Jh||z>Jh)&&(X.current=!0)},[]),Fe=i.useCallback(ee=>{if(re(ee.target)||!F.current)return;const qe=Date.now()-F.current.time<JE,z=!X.current;qe&&z&&(me.current=!0,ct()),F.current=null,X.current=!1},[ct,re]),mt=i.useCallback(async(ee,Se)=>{ee.stopPropagation();try{const qe=await Ba(Se,n);a(qe)}catch{r(`Failed to load dependency ${Se}`,"error")}},[a,r]),We=e.status==="failed",he=e.paused===!0,pe=!!(e.paused&&e.pausedByAgentId),De=ME(e.priority),ut=De!==_s,ht=nc(e,f,w),et=vE(e),vt=!!(et&&e.column==="in-review"&&!he),Oe=Zb(e),tt=e.inReviewStall?Xb(e.inReviewStall):void 0,ft=e.column==="triage"&&e.status==="awaiting-approval",Mt=e.column==="archived",yt=!o&&!s&&!We&&!he&&!ht&&!ft&&(e.column==="in-progress"||Bh.has(e.status)),Ge=!b&&!s&&!he&&!k&&!Mt,K=IE.has(e.column)&&!yt&&!he&&!s&&l,ue=e.githubTracking?.issue,ot=!!ue,xe=e.sourceType==="github_import",dt=HE(e.sourceMetadata),Je=i.useMemo(()=>Kh(dt),[dt]),ke=i.useMemo(()=>Kh(e.issueInfo?.url),[e.issueInfo?.url]),nt=ke?.owner,bt=ke?.repo,kt=!!(e.issueInfo&&ue&&e.issueInfo.number===ue.number&&nt===ue.owner&&bt===ue.repo),wt=!!(Je&&ue&&Je.number===ue.number&&Je.owner===ue.owner&&Je.repo===ue.repo),At=ot&&!kt&&!wt,Ft=i.useMemo(()=>zE(e),[e.id,e.branch,e.baseBranch]),ln=!!(Ft.branch||Ft.baseBranch),Vt=RE(e),hn=ax(e),un=hn?`Created by agent: ${hn}`:"Created by agent",pn=!!(e.assignedAgentId&&Y===null),an=i.useMemo(()=>{const ee=[];return e.modelProvider&&ee.push(e.modelProvider),e.validatorModelProvider&&!ee.includes(e.validatorModelProvider)&&ee.push(e.validatorModelProvider),e.planningModelProvider&&!ee.includes(e.planningModelProvider)&&ee.push(e.planningModelProvider),ee},[e.modelProvider,e.validatorModelProvider,e.planningModelProvider]),Wt=i.useMemo(()=>ex(e,v),[e.steps,e.enabledWorkflowSteps,e.workflowStepResults,v]),gn=Wt.total>0&&(e.status==="executing"||e.column==="in-progress");i.useEffect(()=>{if(e.column!=="in-progress"&&e.column!=="in-review")return;const ee=e.status!=null&&Uh.has(e.status);if(e.column==="in-progress"){const qe=wo(e,Date.now()),z=Hh(e,Date.now()),_e=ko(e,Date.now());if(qe==null&&z==null&&_e==null)return}if(!ee&&e.column==="in-review"){const qe=wo(e,Date.now()),z=ko(e,Date.now());if(qe==null&&z==null)return}W(Date.now());const Se=window.setInterval(()=>{W(Date.now())},$E);return()=>window.clearInterval(Se)},[e.column,e.status,e.columnMovedAt,e.updatedAt,e.workflowStepResults,e.timedExecutionMs,e.executionStartedAt,e.executionCompletedAt]);const cn=i.useMemo(()=>{if(!PE.has(e.column))return null;if(e.status!=null&&Uh.has(e.status)){const Rt=FE(e,N);if(Rt!=null){const Ot=Wh(Rt);if(Ot){const Lt=rx(e,N),fn=Lt==null?null:qh(Lt),kn=fn?`Execution time ${Ot}. Merge phase ${fn}`:`Execution time ${Ot}. Merging`;return{label:Ot,title:kn,ariaLabel:kn}}}}if(e.column==="in-progress"){const Rt=wo(e,N)??Hh(e,N)??ko(e,N);if(Rt==null)return null;const Ot=qh(Rt);return Ot?{label:Ot,title:`In progress ${Ot}`,ariaLabel:`In progress ${Ot}`}:null}const Se=wo(e,N)??ko(e,N);if(Se==null)return null;const qe=Wh(Se);if(!qe)return null;const z=OE(e);if(z==null)return{label:qe,title:`Execution time ${qe}`,ariaLabel:`Execution time ${qe}`};const _e=new Date(z).toLocaleString();return{label:qe,title:`Execution time ${qe}. Completed ${_e}`,ariaLabel:`Execution time ${qe}. Completed ${_e}`}},[e.column,e.status,e.columnMovedAt,e.timedExecutionMs,e.updatedAt,e.workflowStepResults,e.log,e.executionStartedAt,e.executionCompletedAt,N]),tn=ye.get(`${n??"default"}:${e.id}`),Yt=i.useMemo(()=>hE(e.id,n),[e.id,n]),Qt=i.useRef(!1),Kt=!!(e.prInfo||e.issueInfo||tn?.prInfo||tn?.issueInfo||Yt?.result?.prInfo||Yt?.result?.issueInfo);Kt&&(Qt.current=!0);const Jt=Kt||Qt.current;i.useEffect(()=>{if(!Jt||!Me){fe(e.id);return}return Z(e.id),()=>{fe(e.id)}},[Jt,Me,Z,e.id,fe]);const rn=e.column==="in-progress"||e.column==="in-review",qt=i.useMemo(()=>e.steps.map(ee=>`${ee.name}:${ee.status}`).join("|"),[e.steps]),{stats:we}=bE(e.id,e.column,e.mergeDetails?.commitSha,n,{enabled:Me,worktree:e.worktree,stepVersion:rn?qt:void 0,pollIntervalMs:rn?3e4:void 0}),ze=i.useMemo(()=>{const ee=tn?.prInfo,Se=tn?.timestamp,qe=Yt?.result?.prInfo,z=Yt?.timestamp?new Date(Yt.timestamp).toISOString():void 0,_e=e.prInfo,Rt=e.prInfo?.lastCheckedAt??e.updatedAt;let Ot=_e,Lt=Rt;return ee&&(!Lt||Se!=null&&Se>=Lt)&&(Ot=ee,Lt=Se??Lt),qe&&(!Lt||z!=null&&z>=Lt)&&(Ot=qe),Ot},[tn,Yt,e.prInfo,e.updatedAt]),rt=i.useMemo(()=>{const ee=tn?.issueInfo,Se=tn?.timestamp,qe=Yt?.result?.issueInfo,z=Yt?.timestamp?new Date(Yt.timestamp).toISOString():void 0,_e=e.issueInfo,Rt=e.issueInfo?.lastCheckedAt??e.updatedAt;let Ot=_e,Lt=Rt;return ee&&(!Lt||Se!=null&&Se>=Lt)&&(Ot=ee,Lt=Se??Lt),qe&&(!Lt||z!=null&&z>=Lt)&&(Ot=qe),Ot},[tn,Yt,e.issueInfo,e.updatedAt]),He=i.useCallback(ee=>{ee?.stopPropagation(),!(!K||_)&&(R(!0),E(e.description||""))},[K,_,e.description]),Ae=i.useCallback(()=>{R(!1),E(e.description||"")},[e.description]),pt=i.useCallback(()=>O!==(e.description||""),[O,e.description]),Ct=i.useCallback(async()=>{if(!(!l||_)){if(!pt()){Ae();return}G(!0);try{await l(e.id,{description:O.trim()||void 0}),r(`Updated ${e.id}`,"success"),R(!1)}catch(ee){r(`Failed to update ${e.id}: ${Ie(ee)}`,"error")}finally{G(!1)}}},[l,e.id,O,_,pt,Ae,r]),Tt=i.useCallback(ee=>{ee.key==="Enter"&&!ee.shiftKey?(ee.preventDefault(),Ct()):ee.key==="Escape"&&(ee.preventDefault(),Ae())},[Ct,Ae]),Gt=i.useCallback(()=>{setTimeout(()=>{const ee=document.activeElement;ee===de.current||ee?.closest(".card-editing-content")||(pt()?Ct():Ae())},0)},[pt,Ct,Ae]),nn=i.useCallback(ee=>{K&&(ee.stopPropagation(),He(ee))},[K,He]),Ht=i.useCallback(ee=>{ee.stopPropagation(),He(ee)},[He]),on=i.useCallback(ee=>{E(ee.target.value);const Se=ee.target;Se.style.height="auto",Se.style.height=Se.scrollHeight+"px"},[]),ae=i.useCallback(ee=>{ee.stopPropagation(),c&&c(e.id).then(()=>{r(`Archived ${e.id}`,"success")}).catch(Se=>{r(`Failed to archive ${e.id}: ${Ie(Se)}`,"error")})},[r,c,e.id]),le=i.useCallback(ee=>{ee.stopPropagation(),d&&d(e.id).then(()=>{r(`Unarchived ${e.id}`,"success")}).catch(Se=>{r(`Failed to unarchive ${e.id}: ${Ie(Se)}`,"error")})},[r,d,e.id]),Qe=i.useCallback(async ee=>{if(ee.stopPropagation(),!u||!await Q({title:"Delete Task",message:`Delete ${e.id}?`,danger:!0}))return;const qe=e.githubTracking?.enabled===!0?e.githubTracking.issue:void 0;let z;if(qe?.owner&&qe.repo&&qe.number){const _e=`${qe.owner}/${qe.repo}#${qe.number}`;await Q({title:"Linked GitHub Issue",message:`Choose what to do with ${_e} when deleting ${e.id}.
650
-
651
- Close the issue?`,confirmLabel:"Close Issue",cancelLabel:"More Options"})?z="close":z=await Q({title:"Delete Linked GitHub Issue",message:`Delete ${_e} on GitHub, or leave it unchanged?`,confirmLabel:"Delete Issue",cancelLabel:"Leave Unchanged",danger:!0})?"delete":"leave"}try{z?await u(e.id,{githubIssueAction:z}):await u(e.id);const _e=qe?.owner&&qe.repo&&qe.number&&z?` and ${z==="close"?"closed":z==="delete"?"deleted":"left"} issue ${qe.owner}/${qe.repo}#${qe.number}`:"";r(`Deleted ${e.id}${_e}`,"success")}catch(_e){const Rt=im(_e);if(!Rt||Rt.dependentIds.length===0){r(`Failed to delete ${e.id}: ${Ie(_e)}`,"error");return}const Ot=Rt.dependentIds.join(", ");if(!await Q({title:"Force Delete Task",message:`${e.id} is a dependency of ${Ot}.
652
-
653
- Delete anyway by removing these dependency references first?`,danger:!0}))return;try{await u(e.id,{removeDependencyReferences:!0,githubIssueAction:z}),r(`Deleted ${e.id} after removing dependency references`,"success")}catch(fn){r(`Failed to delete ${e.id}: ${Ie(fn)}`,"error")}}},[r,Q,u,e.githubTracking?.enabled,e.githubTracking?.issue,e.id]),xt=i.useCallback(ee=>{ee.stopPropagation(),m?.(e,"changes")},[e,m]),zt=i.useCallback(ee=>{ee.stopPropagation(),A(Se=>!Se)},[]),sn=i.useCallback(ee=>{ee.stopPropagation(),e.missionId&&p&&p(e.missionId)},[e.missionId,p]),xn=i.useCallback(ee=>{ee.stopPropagation(),M(Se=>!Se)},[]),$n=i.useCallback(async(ee,Se)=>{if(ee.stopPropagation(),M(!1),!!g)try{const qe=e.steps.some(Rt=>Rt.status!=="pending"),z=(Se==="todo"||Se==="triage")&&qe;let _e;if(z){if(await Q({title:"Preserve Progress?",message:"This task has completed steps. Keep progress before moving?",confirmLabel:"Keep Progress",cancelLabel:"Reset Progress"}))_e={preserveProgress:!0};else if(!await Q({title:"Reset Progress?",message:"Reset all step progress before moving this task?",confirmLabel:"Reset Progress",cancelLabel:"Cancel Move",danger:!0}))return}await g(e.id,Se,_e),r(`Moved ${e.id} to ${ds[Se]}`,"success")}catch(qe){r(`Failed to move ${e.id}: ${Ie(qe)}`,"error")}},[r,Q,g,e.id,e.steps]),wn=i.useCallback(async ee=>{if(ee.stopPropagation(),!(!h||$)){D(!0);try{await h(e.id)}catch(Se){r(`Failed to retry ${e.id}: ${Ie(Se)}`,"error")}finally{D(!1)}}},[r,$,h,e.id]),zn=`card${j?" dragging":""}${s?" queued":""}${yt?" agent-active":""}${We?" failed":""}${he?" paused":""}${ht?" stuck":""}${ft?" awaiting-approval":""}${C?" file-drop-target":""}${k?" card-editing":""}${_?" card-saving":""}`,ce=(()=>{if(e.column==="in-progress"){const ee=we?.filesChanged,Se=ee==null||ee===0?e.modifiedFiles?.length:void 0,qe=ee!=null&&ee>0?ee:Se;return qe==null||qe===0?null:t.jsxs("button",{type:"button",className:"card-session-files",onClick:xt,disabled:!m,children:[t.jsx(ws,{size:12}),t.jsxs("span",{children:[qe," ",qe===1?"file":"files"," changed"]})]})}if(e.column==="in-review"){const ee=we?.filesChanged,Se=ee==null||ee===0?e.modifiedFiles?.length:void 0,qe=ee!=null&&ee>0?ee:Se;return qe==null||qe===0?null:t.jsxs("button",{type:"button",className:"card-session-files",onClick:xt,disabled:!m,children:[t.jsx(ws,{size:12}),t.jsxs("span",{children:[qe," ",qe===1?"file":"files"," changed"]})]})}if(e.column==="done"){const ee=we?.filesChanged,Se=e.mergeDetails?.filesChanged,qe=ee??Se;if(qe!=null&&qe>0)return t.jsxs("button",{type:"button",className:"card-session-files",onClick:xt,disabled:!m,children:[t.jsx(ws,{size:12}),t.jsxs("span",{children:[qe," ",qe===1?"file":"files"," changed"]})]});const z=e.modifiedFiles?.length;if(z!=null&&z>0)return t.jsxs("button",{type:"button",className:"card-session-files",onClick:xt,disabled:!m,children:[t.jsx(ws,{size:12}),t.jsxs("span",{children:[z," ",z===1?"file":"files"," changed"]})]})}return null})();return k?t.jsx("div",{ref:Ne,className:zn,"data-id":e.id,"data-column":e.column,onDoubleClick:nn,children:t.jsxs("div",{className:"card-editing-content",children:[t.jsx("textarea",{ref:de,className:"card-edit-desc-textarea",placeholder:"Task description",value:O,onChange:on,onKeyDown:Tt,onBlur:Gt,disabled:_,rows:4}),_&&t.jsxs("div",{className:"card-edit-loading",children:[t.jsx("span",{className:"card-edit-loading-spinner"}),t.jsx("span",{className:"card-edit-loading-text",children:"Saving..."})]})]})}):t.jsxs("div",{ref:Ne,className:zn,"data-id":e.id,"data-column":e.column,draggable:Ge,onDragStart:Ge?U:void 0,onDragEnd:Ge?be:void 0,onDragOver:se,onDragLeave:Ve,onDrop:Le,onClick:Ke,onTouchStart:oe,onTouchMove:Te,onTouchEnd:Fe,onDoubleClick:nn,children:[t.jsxs("div",{className:"card-header",children:[t.jsx("span",{className:"card-id",children:e.id}),he&&t.jsx("span",{className:"card-status-badge paused",children:pe?"paused by agent":"paused"}),!he&&e.status&&e.status!=="queued"&&t.jsx("span",{className:`card-status-badge card-status-badge--${e.column}${ft?" awaiting-approval":""}${Bh.has(e.status)?" pulsing":""}${We?" failed":""}${ht?" stuck":""}`,children:ht?"Stuck":ft?"Awaiting Approval":DE(e.status)}),Oe&&tt&&t.jsx("span",{className:`card-status-badge card-status-badge--in-review in-review-stall in-review-stall--${tt.code}`,title:`${tt.headline} — ${tt.description}`,"data-stall-code":tt.code,children:tt.badgeLabel}),ht&&(he||!e.status||e.status==="queued")&&t.jsx("span",{className:"card-status-badge stuck",children:"Stuck"}),vt&&et&&t.jsx("span",{className:"card-status-badge card-status-badge--in-review stalled-review",title:et.reason,children:"Stalled"}),(ze||rt)&&t.jsx(oE,{prInfo:ze,issueInfo:rt}),Vt&&t.jsxs("span",{className:"card-agent-created-badge",title:un,"aria-label":un,children:[t.jsx(Xn,{size:11,"aria-hidden":"true"}),t.jsx("span",{className:"visually-hidden",children:un}),t.jsx("span",{"aria-hidden":"true",children:"Agent"})]}),ut&&t.jsx("span",{className:`card-priority-badge card-priority-badge--${De}`,children:De}),e.executionMode==="fast"&&t.jsxs("span",{className:"card-execution-mode-badge card-execution-mode-badge--fast",title:"Fast mode","aria-label":"Fast mode",children:[t.jsx(as,{"aria-hidden":"true"}),t.jsx("span",{className:"visually-hidden",children:"Fast mode"})]}),e.missionId&&t.jsxs("span",{className:"card-mission-badge",onClick:sn,title:`Mission: ${P??e.missionId}`,role:p?"button":void 0,tabIndex:p?0:void 0,style:{overflow:"hidden",textOverflow:"ellipsis",whiteSpace:"nowrap"},children:[t.jsx(js,{size:11}),EE(P??e.missionId)]}),t.jsxs("div",{className:"card-header-actions",children:[K&&t.jsx("button",{className:"card-edit-btn",onClick:Ht,title:"Edit task","aria-label":"Edit task",children:t.jsx(Os,{size:12})}),e.column==="triage"&&u&&t.jsx("button",{className:"card-delete-btn",onClick:Qe,title:"Delete task","aria-label":"Delete task",children:t.jsx(In,{size:12})}),e.column==="done"&&c&&t.jsx("button",{className:"card-archive-btn",onClick:ae,title:"Archive task","aria-label":"Archive task",children:"Archive"}),e.column==="archived"&&d&&t.jsx("button",{className:"card-unarchive-btn",onClick:le,title:"Unarchive task","aria-label":"Unarchive task",children:"Unarchive"}),e.column==="in-progress"&&g&&t.jsxs("div",{className:"card-send-back",ref:ve,children:[t.jsxs("button",{className:"card-send-back-btn",onClick:xn,title:"Send back","aria-label":"Send back","aria-haspopup":"menu","aria-expanded":L,children:["Send back",t.jsx(vn,{size:10})]}),L&&t.jsx("div",{className:"card-send-back-menu",role:"menu",children:hu["in-progress"].filter(ee=>ee!=="in-review").map(ee=>t.jsx("button",{className:"card-send-back-menu-item",role:"menuitem",onClick:Se=>$n(Se,ee),children:ds[ee]},ee))})]}),e.column==="in-review"&&g&&t.jsxs("div",{className:"card-send-back",ref:ve,children:[t.jsxs("button",{className:"card-send-back-btn",onClick:xn,title:"Move task","aria-label":"Move task","aria-haspopup":"menu","aria-expanded":L,children:["Move",t.jsx(vn,{size:10})]}),L&&t.jsx("div",{className:"card-send-back-menu",role:"menu",children:hu["in-review"].map(ee=>t.jsx("button",{className:"card-send-back-menu-item",role:"menuitem",onClick:Se=>$n(Se,ee),children:ee==="done"?"Done (no merge)":ds[ee]},ee))})]}),e.size&&t.jsx("span",{className:`card-size-badge size-${e.size.toLowerCase()}`,children:e.size})]})]}),vt&&et&&t.jsx("div",{className:"card-stalled-review-reason",title:et.reason,children:et.reason}),We&&e.error&&t.jsxs("div",{className:"card-error",title:e.error,children:[t.jsx("span",{className:"card-error-icon",children:"⚠"}),t.jsx("span",{className:"card-error-text",children:e.error.length>60?e.error.slice(0,60)+"…":e.error}),h&&t.jsxs("button",{type:"button",className:"btn btn-sm card-error-retry-btn",onClick:wn,disabled:$,children:[t.jsx(Xk,{size:12}),$?"Retrying…":"Retry"]})]}),t.jsx("div",{className:"card-title",title:e.title||e.description||void 0,children:Qh(e.title,Yh)||Qh(e.description,Yh)||e.id}),ln&&t.jsxs("div",{className:"card-branch-row","aria-label":"Branch metadata",children:[Ft.branch&&t.jsxs("span",{className:"card-branch-chip",title:Ft.branch,children:[t.jsx("span",{className:"card-branch-label",children:"Branch"}),t.jsx("span",{className:"card-branch-value",children:Ft.branch})]}),Ft.baseBranch&&t.jsxs("span",{className:"card-branch-chip",title:Ft.baseBranch,children:[t.jsx("span",{className:"card-branch-label",children:"Base"}),t.jsx("span",{className:"card-branch-value",children:Ft.baseBranch})]})]}),gn&&(()=>{const ee=Wt.completed/Wt.total*100;return t.jsxs(t.Fragment,{children:[t.jsxs("div",{className:"card-progress",children:[t.jsx("div",{className:"card-progress-bar",children:t.jsx("div",{className:"card-progress-fill",style:{width:`${ee}%`,backgroundColor:TE[e.column]}})}),t.jsxs("span",{className:"card-progress-label",children:[Wt.completed,"/",Wt.total]})]}),t.jsxs("button",{type:"button",className:"card-steps-toggle",onClick:zt,"aria-expanded":H,"aria-label":H?"Hide steps":"Show steps",children:[t.jsxs("span",{children:[Wt.total," step",Wt.total===1?"":"s"]}),t.jsx(vn,{size:14,className:`card-steps-toggle-icon${H?" expanded":""}`})]}),H&&t.jsx("div",{className:"card-steps-list",children:Wt.items.map(Se=>{const qe=Se.source==="workflow"&&Se.status==="failed";return t.jsxs("div",{className:"card-step-item",children:[t.jsx("span",{className:`card-step-dot card-step-dot--${Se.status}${qe?" card-step-dot--workflow-failed":""}`,"aria-hidden":"true"}),t.jsx("span",{className:`card-step-name${Se.status==="done"?" completed":""}`,children:Se.name}),Se.source==="workflow"&&t.jsx("span",{className:`card-step-workflow-badge card-step-workflow-badge--${Se.phase}`,title:"Workflow check",children:"workflow"})]},Se.id)})})]})})(),(ce||cn||xe)&&t.jsxs("div",{className:"card-footer-row",children:[ce,xe&&t.jsx("span",{className:"card-source-provenance",title:dt?`Imported from GitHub: ${dt}`:"Imported from GitHub","aria-label":"Imported from GitHub",children:t.jsx(On,{provider:"github",size:"sm"})}),cn&&t.jsxs("span",{className:"card-time-indicator",title:cn.title,"aria-label":cn.ariaLabel,children:[t.jsx(Yi,{size:12}),t.jsx("span",{children:cn.label})]})]}),(e.dependencies&&e.dependencies.length>0||s||e.status==="queued"||e.blockedBy||y&&y.totalCount>0)&&t.jsxs("div",{className:"card-meta",children:[e.dependencies&&e.dependencies.length>0&&t.jsx("div",{className:"card-dep-list",children:e.dependencies.map(ee=>t.jsxs("span",{className:"card-dep-badge clickable",onClick:Se=>void mt(Se,ee),title:`Click to view ${ee}`,children:[t.jsx(Cr,{size:12,style:{verticalAlign:"middle"}})," ",ee]},ee))}),e.blockedBy&&t.jsxs("span",{className:"card-scope-badge","data-tooltip":`Blocked by ${e.blockedBy} (file overlap)`,children:[t.jsx(Fa,{size:12,style:{verticalAlign:"middle"}})," ",e.blockedBy]}),y&&y.totalCount>0&&t.jsxs("span",{className:`card-fanout-badge${y.staleBlockedByDependentIds.length>0?" card-fanout-badge--stale":""}`,"data-tooltip":`Blocking ${y.totalCount} active task(s); ${y.activeTodoCount} waiting in todo${y.isHighFanout?` (high fan-out threshold: ${Ju})`:""}${y.escalation?` · escalated after ${Math.floor(y.escalation.blockingAgeMs/6e4)}m in blocking column`:""}`,children:[t.jsx(Is,{size:12,style:{verticalAlign:"middle"}}),t.jsxs("span",{children:[y.escalation?"Escalated":y.isHighFanout?"High fan-out":"Blocks"," ",t.jsx("span",{className:"card-fanout-count",children:y.totalCount}),y.staleBlockedByDependentIds.length>0?` (${y.staleBlockedByDependentIds.length} stale)`:""]})]}),(s||e.status==="queued")&&e.column!=="in-progress"&&t.jsxs("span",{className:"queued-badge",children:[t.jsx(Yi,{size:12,style:{verticalAlign:"middle"}})," Queued"]})]}),(e.assignedAgentId||an.length>0)&&t.jsxs("div",{className:"card-agent-row",children:[an.length>0&&t.jsx("span",{className:"card-provider-icons","data-testid":"card-provider-icons",children:an.map(ee=>t.jsx(On,{provider:ee,size:"sm"},ee))}),e.assignedAgentId&&t.jsxs("span",{className:`card-agent-badge${pn?" card-agent-badge--loading":""}`,title:`Assigned to ${Y??e.assignedAgentId}`,children:[t.jsx(Xn,{size:11}),t.jsx("span",{className:"card-agent-badge-text","aria-hidden":"true",children:AE(Y??e.assignedAgentId,15)}),t.jsxs("span",{className:"visually-hidden",children:["Assigned to ",Y??e.assignedAgentId]})]})]}),At&&ue&&t.jsx("div",{className:"card-bottom-right-row",children:t.jsxs("a",{className:"card-github-tracking-chip card-github-tracking-link",href:ue.url,target:"_blank",rel:"noopener noreferrer",title:`Linked GitHub issue: ${ue.owner}/${ue.repo}#${ue.number}`,"aria-label":`Linked GitHub issue #${ue.number}`,onClick:ee=>ee.stopPropagation(),children:[t.jsx(On,{provider:"github",size:"sm"}),t.jsx("span",{children:`#${ue.number}`})]})}),t.jsx(pa,{slotId:"task-card-badge",projectId:n})]})}const Jh=10,JE=300,Yh=140;function Qh(e,n){return e?e.length>n?e.slice(0,n)+"…":e:""}const Oo=i.memo(KE,GE);Oo.displayName="TaskCard";function YE({label:e,activeTasks:n,queuedTasks:s,projectId:a,onOpenDetail:r,addToast:o,globalPaused:l,onUpdateTask:c,onRetryTask:d,onOpenDetailWithTab:u,taskStuckTimeoutMs:h,onOpenMission:m,lastFetchTimeMs:f,workflowStepNameLookup:p,blockerFanoutMap:g}){return t.jsxs("div",{className:"worktree-group",children:[t.jsxs("div",{className:"worktree-group-header",children:[t.jsx("span",{className:"worktree-icon",children:e==="Up Next"||e==="Unassigned"?t.jsx(fw,{size:14}):t.jsx(Is,{size:14})}),t.jsx("span",{className:"worktree-label",children:e})]}),n.map(w=>t.jsx(Oo,{task:w,projectId:a,onOpenDetail:r,addToast:o,globalPaused:l,onUpdateTask:c,onRetryTask:d,onOpenDetailWithTab:u,taskStuckTimeoutMs:h,onOpenMission:m,lastFetchTimeMs:f,workflowStepNameLookup:p,fanout:g?.get(w.id)},w.id)),s.map(w=>t.jsx(Oo,{task:w,projectId:a,queued:!0,onOpenDetail:r,addToast:o,globalPaused:l,onUpdateTask:c,onRetryTask:d,onOpenDetailWithTab:u,taskStuckTimeoutMs:h,onOpenMission:m,lastFetchTimeMs:f,workflowStepNameLookup:p,fanout:g?.get(w.id)},w.id))]})}const ox=i.memo(YE);ox.displayName="WorktreeGroup";function Xh(e){return e.toLowerCase().replace(/[-_./]/g,"")}function QE(e,n){let s=0;for(let a=0;a<n.length&&s<e.length;a++)e[s]===n[a]&&s++;return s===e.length}function XE(e,n,s){const a=e.length,r=n.length;if(a===0)return!0;if(r===0)return!1;let o=new Array(r+1).fill(0),l=new Array(r+1).fill(0);for(let c=1;c<=a;c++){const d=new Array(r+1);d[0]=c;for(let u=1;u<=r;u++){const h=e[c-1]===n[u-1]?0:1;d[u]=Math.min(l[u]+1,d[u-1]+1,l[u-1]+h),c>=2&&u>=2&&e[c-1]===n[u-2]&&e[c-2]===n[u-1]&&(d[u]=Math.min(d[u],o[u-2]+1))}o=l,l=d}for(let c=0;c<=r;c++)if(l[c]<=s)return!0;return!1}function ZE(e,n){const s=Xh(e),a=Xh(n);if(s.length===0||a.includes(s))return!0;const r=a.split(/\s+/).filter(Boolean);for(const o of r)if(s.length>=3&&QE(s,o)||s.length>=4&&XE(s,o,1))return!0;return!1}function e_(e,n){const s=n.toLowerCase().trim().split(/\s+/).filter(Boolean);return s.length===0?e:e.filter(a=>{const r=`${a.provider} ${a.id} ${a.name}`;return s.every(o=>ZE(o,r))})}function Ns({models:e,value:n,onChange:s,placeholder:a="Select a model…",disabled:r=!1,id:o,label:l,favoriteProviders:c=[],onToggleFavorite:d,favoriteModels:u=[],onToggleModelFavorite:h,noChangeValue:m,noChangeLabel:f="No change"}){const[p,g]=i.useState(!1),[w,v]=i.useState(""),[b,y]=i.useState(0),[j,S]=i.useState(null),[C,x]=i.useState(null),k=i.useRef(null),R=i.useRef(null),O=i.useRef(null),E=i.useRef(null),_=i.useRef(null),G=i.useMemo(()=>e_(e,w),[e,w]),H=i.useMemo(()=>G.reduce((Z,fe)=>((Z[fe.provider]??=[]).push(fe),Z),{}),[G]),A=i.useMemo(()=>{const Z=[];for(const fe of u){const Q=fe.indexOf("/");if(Q===-1)continue;const F=fe.slice(0,Q),X=fe.slice(Q+1),re=G.find(U=>U.provider===F&&U.id===X);re&&Z.push({model:re,fullId:fe})}return Z},[u,G]),P=i.useMemo(()=>{const Z=Object.entries(H),fe=new Set(c);return Z.sort(([Q],[F])=>{const X=fe.has(Q),re=fe.has(F);if(X&&!re)return-1;if(!X&&re)return 1;if(X&&re){const U=c.indexOf(Q),be=c.indexOf(F);if(U!==be)return U-be}return Q.localeCompare(F)})},[H,c]),q=typeof m=="string"&&m.length>0,Y=i.useMemo(()=>{if(!n||q&&n===m)return null;const Z=n.indexOf("/");return Z===-1?null:n.slice(0,Z)},[q,m,n]),ge=i.useMemo(()=>{const Z=[];return q&&Z.push({type:"no-change",value:m,label:f}),Z.push({type:"default",value:"",label:"Use default"}),Z},[q,f,m]),L=i.useMemo(()=>{const Z=[...ge];for(const{model:fe,fullId:Q}of A)Z.push({type:"favorite",value:Q,label:fe.name,provider:fe.provider});return P.forEach(([fe,Q])=>{Z.push({type:"provider",value:`__group_${fe}`,label:fe,provider:fe}),Q.forEach(F=>{Z.push({type:"model",value:`${F.provider}/${F.id}`,label:F.name,provider:F.provider})})}),Z},[A,P,ge]),M=i.useMemo(()=>{if(q&&n===m)return f;if(!n)return"Use default";const Z=n.indexOf("/");if(Z===-1)return n;const fe=n.slice(0,Z),Q=n.slice(Z+1);return e.find(X=>X.provider===fe&&X.id===Q)?.name||n},[q,f,m,n,e]),$=i.useMemo(()=>L.findIndex(Z=>Z.value===n),[L,n]),D=i.useCallback(()=>{const Z=window.visualViewport;return Z&&Z.height>0&&Z.width>0?{width:Z.width,height:Z.height,offsetTop:Z.offsetTop,offsetLeft:Z.offsetLeft}:{width:window.innerWidth,height:window.innerHeight,offsetTop:0,offsetLeft:0}},[]),N=i.useCallback(()=>{const{height:Z}=D(),fe=typeof window.matchMedia=="function",Q=fe?window.matchMedia("(max-width: 640px)").matches:!1,F=fe?window.matchMedia("(max-width: 768px)").matches:!1;return Z<=0?320:Q?Math.min(Z*.6,360):F?Math.min(Z*.7,420):320},[D]),W=i.useCallback(()=>{const Z=R.current;if(!Z)return;const fe=Z.getBoundingClientRect(),{width:Q,height:F,offsetTop:X,offsetLeft:re}=D(),U=16,be=16,Ue=4,se=N(),Ve=fe.bottom-X,Le=fe.top-X,ct=fe.left-re,Ke=F-Ve,oe=Le,Te=Math.max(Ke-be-Ue,160),Fe=Math.max(oe-be-Ue,160),mt=Ke<se&&oe>Ke,We=Math.max(Math.min(mt?Fe:Te,se),160),he=Math.min(fe.width,Q-U*2),pe=Math.min(Math.max(ct,U),Q-U-he)+re,De=mt?Math.max(be+X,Le-We-Ue+X):Math.min(Ve+Ue+X,F+X-be-We);S({top:De,left:pe,width:he,maxHeight:We})},[D,N]);i.useEffect(()=>{x(document.body)},[]);const de=i.useRef(!1);i.useEffect(()=>{if(!p){de.current=!1;return}if(de.current||L.length===0)return;const Z=L.findIndex((fe,Q)=>Q>=($>=0?$:0)&&fe.type!=="provider");y(Z>=0?Z:0),de.current=!0},[p,L,$]),i.useEffect(()=>{p&&de.current&&(y(0),_.current&&(_.current.scrollTop=0))},[w,p]),i.useEffect(()=>{if(!p)return;W();const Z=requestAnimationFrame(()=>E.current?.focus());return()=>cancelAnimationFrame(Z)},[p,W]),i.useEffect(()=>{if(!p)return;const Z=()=>W();window.addEventListener("resize",Z),window.addEventListener("scroll",Z,!0);const fe=window.visualViewport;return fe&&(fe.addEventListener("resize",Z),fe.addEventListener("scroll",Z)),()=>{window.removeEventListener("resize",Z),window.removeEventListener("scroll",Z,!0),fe&&(fe.removeEventListener("resize",Z),fe.removeEventListener("scroll",Z))}},[p,W]),i.useEffect(()=>{if(!p)return;const Z=fe=>{const Q=fe.target,F=k.current?.contains(Q),X=O.current?.contains(Q);!F&&!X&&(g(!1),v(""))};return document.addEventListener("mousedown",Z),()=>document.removeEventListener("mousedown",Z)},[p]);const me=i.useCallback(Z=>{switch(Z.key){case"ArrowDown":if(Z.preventDefault(),!p)g(!0);else{let fe=b;for(let Q=1;Q<=L.length;Q++){const F=(b+Q)%L.length;if(L[F]?.type!=="provider"){fe=F;break}}y(fe)}break;case"ArrowUp":if(Z.preventDefault(),p){let fe=b;for(let Q=1;Q<=L.length;Q++){const F=(b-Q+L.length)%L.length;if(L[F]?.type!=="provider"){fe=F;break}}y(fe)}break;case"Enter":if(Z.preventDefault(),p){const fe=L[b];fe&&fe.type!=="provider"&&fe.type!=="favorite"&&(s(fe.value),g(!1),v(""))}else g(!0);break;case"Escape":Z.preventDefault(),g(!1),v("");break;case"Tab":p&&(g(!1),v(""));break}},[p,b,L,s]),Ne=i.useCallback(Z=>{s(Z),g(!1),v("")},[s]),ve=i.useCallback(()=>{v(""),E.current?.focus()},[]),Me=i.useCallback(()=>{r||g(Z=>!Z)},[r]);i.useEffect(()=>{if(p&&_.current){const Z=_.current.querySelector(`[data-index="${b}"]`);Z&&typeof Z.scrollIntoView=="function"&&Z.scrollIntoView({block:"nearest"})}},[b,p]);const ie=w.length>0,ye=p&&j?t.jsxs("div",{ref:O,className:"model-combobox-dropdown model-combobox-dropdown--portal",role:"listbox","data-testid":"model-combobox-portal",onKeyDown:me,style:{top:`${j.top}px`,left:`${j.left}px`,width:`${j.width}px`,maxHeight:`${j.maxHeight}px`},children:[t.jsxs("div",{className:"model-combobox-search-wrapper",children:[t.jsx("input",{ref:E,type:"text",className:"model-combobox-search",placeholder:"Filter models…",value:w,onChange:Z=>v(Z.target.value),onClick:Z=>Z.stopPropagation()}),ie&&t.jsx("button",{type:"button",className:"model-combobox-clear",onClick:ve,"aria-label":"Clear filter",children:"×"})]}),t.jsxs("div",{className:"model-combobox-results-count",children:[G.length," model",G.length!==1?"s":""]}),t.jsxs("div",{ref:_,className:"model-combobox-list",children:[ge.map((Z,fe)=>t.jsx("div",{"data-index":fe,className:`model-combobox-option ${b===fe?"model-combobox-option--highlighted":""} ${n===Z.value?"model-combobox-option--selected":""}`,onClick:()=>Ne(Z.value),onMouseEnter:()=>y(fe),role:"option","aria-selected":n===Z.value,children:t.jsx("span",{className:"model-combobox-option-text model-combobox-option-text--default",children:Z.label})},`${Z.type}-${Z.value}`)),A.length>0&&t.jsxs(t.Fragment,{children:[t.jsx("div",{className:"model-combobox-divider"}),A.map(({model:Z,fullId:fe},Q)=>{const F=Q+ge.length,X=b===F,re=n===fe;return t.jsxs("div",{"data-index":F,className:`model-combobox-option model-combobox-option--favorite ${X?"model-combobox-option--highlighted":""} ${re?"model-combobox-option--selected":""}`,onClick:()=>Ne(fe),onMouseEnter:()=>y(F),role:"option","aria-selected":re,children:[t.jsxs("span",{className:"model-combobox-option-main",children:[t.jsx("span",{className:"model-combobox-option-icon",children:t.jsx(On,{provider:Z.provider,size:"sm"})}),t.jsx("span",{className:"model-combobox-option-text",children:Z.name})]}),t.jsx("span",{className:"model-combobox-option-id",children:Z.id}),h&&t.jsx("button",{type:"button",className:"model-combobox-option-favorite model-combobox-option-favorite--active",onClick:U=>{U.stopPropagation(),h(fe)},title:"Remove from favorites","aria-label":`Remove ${Z.name} from favorites`,children:"★"})]},fe)}),t.jsx("div",{className:"model-combobox-divider"})]}),P.map(([Z,fe])=>{const Q=L.findIndex(re=>re.value===`__group_${Z}`),F=c.includes(Z),X=fe.filter(re=>{const U=`${re.provider}/${re.id}`;return!u.includes(U)});return X.length===0?null:t.jsxs("div",{className:"model-combobox-group",children:[t.jsxs("div",{className:"model-combobox-optgroup","data-index":Q,children:[t.jsx(On,{provider:Z,size:"sm"}),t.jsx("span",{className:"model-combobox-optgroup-text",children:Z}),d&&t.jsx("button",{type:"button",className:`model-combobox-optgroup-favorite ${F?"model-combobox-optgroup-favorite--active":""}`,onClick:re=>{re.stopPropagation(),d(Z)},title:F?"Remove from favorites":"Add to favorites","aria-label":F?`Remove ${Z} from favorites`:`Add ${Z} to favorites`,children:"★"})]}),X.map(re=>{const U=`${re.provider}/${re.id}`,be=L.findIndex(Le=>Le.value===U),Ue=b===be,se=n===U,Ve=u.includes(U);return t.jsxs("div",{"data-index":be,className:`model-combobox-option ${Ue?"model-combobox-option--highlighted":""} ${se?"model-combobox-option--selected":""}`,onClick:()=>Ne(U),onMouseEnter:()=>y(be),role:"option","aria-selected":se,children:[t.jsx("span",{className:"model-combobox-option-text",children:re.name}),t.jsx("span",{className:"model-combobox-option-id",children:re.id}),h&&t.jsx("button",{type:"button",className:`model-combobox-option-favorite ${Ve?"model-combobox-option-favorite--active":""}`,onClick:Le=>{Le.stopPropagation(),h(U)},title:Ve?"Remove from favorites":"Add to favorites","aria-label":Ve?`Remove ${re.name} from favorites`:`Add ${re.name} to favorites`,children:Ve?"★":"☆"})]},U)})]},Z)}),G.length===0&&ie&&t.jsxs("div",{className:"model-combobox-no-results",children:["No models match '",w,"'"]})]})]}):null;return t.jsxs(t.Fragment,{children:[t.jsx("div",{ref:k,className:"model-combobox",onKeyDown:me,children:t.jsxs("button",{ref:R,type:"button",id:o,className:"model-combobox-trigger",onClick:Me,disabled:r,"aria-haspopup":"listbox","aria-expanded":p,"aria-label":l,children:[Y&&t.jsx("span",{className:"model-combobox-trigger-icon",children:t.jsx(On,{provider:Y,size:"sm"})}),t.jsx("span",{className:"model-combobox-trigger-text",children:M||a}),t.jsx("span",{className:"model-combobox-trigger-arrow",children:"▼"})]})}),C&&ye?$a.createPortal(ye,C):null]})}function am(e,n){return typeof n!="string"||n.length===0?e:`kb:${n}:${e}`}function Ln(e,n){if(typeof window>"u")return null;const s=window.localStorage?.getItem;return typeof s!="function"?null:s.call(window.localStorage,am(e,n))}function rs(e,n,s){if(typeof window>"u")return;const a=window.localStorage?.setItem;typeof a=="function"&&a.call(window.localStorage,am(e,s),n)}function qa(e,n){if(typeof window>"u")return;const s=window.localStorage?.removeItem;typeof s=="function"&&s.call(window.localStorage,am(e,n))}const t_=1e4,n_=1e3;function _c(){const[e,n]=i.useState([]),[s,a]=i.useState(!0),[r,o]=i.useState(null),l=i.useRef(null),c=i.useRef(0),d=i.useCallback(async()=>{try{o(null);const b=await ec();n(b)}catch(b){o(b instanceof Error?b.message:"Failed to fetch nodes")}},[]);i.useEffect(()=>{let b=!1;async function y(){a(!0);try{const S=await ec();b||(n(S),o(null))}catch(S){b||o(S instanceof Error?S.message:"Failed to fetch nodes")}finally{b||a(!1)}}y();const j=()=>{if(document.visibilityState!=="visible")return;const S=Date.now();S-c.current<n_||(c.current=S,d())};return document.addEventListener("visibilitychange",j),()=>{b=!0,document.removeEventListener("visibilitychange",j)}},[d]),i.useEffect(()=>{if(!s)return l.current=setInterval(()=>{d()},t_),()=>{l.current&&(clearInterval(l.current),l.current=null)}},[s,d]);const u=i.useCallback(async b=>{const{projectMappings:y,...j}=b,S=await D1(j);if(y.length>0)try{await SC(S.id,y)}catch(C){const x=C instanceof Error?C.message:"Failed to persist project mappings";let k="";try{await dh(S.id)}catch(R){k=R instanceof Error?R.message:"Failed to unregister node after mapping failure"}throw await d(),k?new Error(`${x}. Cleanup also failed: ${k}`):new Error(x)}return await d(),S},[d]),h=i.useCallback(async(b,y)=>{const j=await O1(b,y);return n(S=>S.map(C=>C.id===b?j:C)),j},[]),m=i.useCallback(async b=>{await dh(b),n(y=>y.filter(j=>j.id!==b))},[]),f=i.useCallback(async b=>{const y=await U1(b);n(j=>j.map(S=>S.id===b?{...S,status:y.status,updatedAt:y.checkedAt}:S))},[]),p=i.useCallback(b=>F1(b),[]),g=i.useCallback(async(b,y)=>{const j=await z1(b,y);return n(S=>S.map(C=>C.id===b?{...C,dockerConfig:j}:C)),j},[]),w=i.useCallback(async b=>{const y=await B1(b);return"persistedVersion"in y?y:{persistedVersion:0,deployedVersion:null,needsRecreate:!1}},[]),v=i.useCallback(async b=>L1(b),[]);return{nodes:e,loading:s,error:r,refresh:d,register:u,update:h,unregister:m,healthCheck:f,fetchDockerConfig:p,patchDockerConfig:g,fetchDockerDiff:w,discoverRemoteProjects:v}}const so="kb-quick-entry-text",s_=["image/png","image/jpeg","image/gif","image/webp"];function i_(e){return e==="online"?"Online":e==="connecting"?"Connecting":e==="error"?"Error":"Offline"}function rd(e,n){return e&&n?`${e}/${n}`:""}function od(e){if(!e)return{provider:void 0,modelId:void 0};const n=e.indexOf("/");return n===-1?{provider:void 0,modelId:void 0}:{provider:e.slice(0,n),modelId:e.slice(n+1)}}function lx({onCreate:e,addToast:n,tasks:s=[],availableModels:a,onPlanningMode:r,onSubtaskBreakdown:o,projectId:l,autoExpand:c=!0,favoriteProviders:d,favoriteModels:u,onToggleFavorite:h,onToggleModelFavorite:m}){const[f,p]=i.useState(()=>typeof window<"u"&&Ln(so,l)||""),[g,w]=i.useState(!1),[v,b]=i.useState(!1),[y,j]=i.useState(!1),S=i.useRef(null),C=i.useRef(null),x=i.useRef(!1),k=i.useRef(l),[R,O]=i.useState([]),E=i.useRef([]),[_,G]=i.useState([]),[H,A]=i.useState(!1),[P,q]=i.useState(""),[Y,ge]=i.useState(null),[L,M]=i.useState([]),[$,D]=i.useState(void 0),[N,W]=i.useState(!1),[de,me]=i.useState(!1),[Ne,ve]=i.useState(!1),[Me,ie]=i.useState(!1),[ye,Z]=i.useState(!1),[fe,Q]=i.useState(null),[F,X]=i.useState(void 0),[re,U]=i.useState(void 0),[be,Ue]=i.useState(void 0),[se,Ve]=i.useState(void 0),[Le,ct]=i.useState(void 0),[Ke,oe]=i.useState(void 0),Te=i.useRef(null),Fe=i.useRef(null),mt=i.useRef(null),We=i.useRef(null),he=i.useRef(null),pe=i.useRef(null),De=i.useRef(null),ut=i.useRef(null),[ht,et]=i.useState(null),[vt,Oe]=i.useState(null),[tt,ft]=i.useState(null),[Mt,yt]=i.useState(null),Ge=i.useRef(null),K=i.useRef(null),[ue,ot]=i.useState(null),[xe]=i.useState(()=>typeof document<"u"?document.body:null),[dt,Je]=i.useState(!1),[ke,nt]=i.useState(null),[bt,kt]=i.useState(a??[]),[wt,At]=i.useState([]),[Ft,ln]=i.useState([]),[Vt,hn]=i.useState(null),[un,pn]=i.useState(void 0),[an,Wt]=i.useState(!1),[gn,cn]=i.useState(_s),[tn,Yt]=i.useState(void 0),{nodes:Qt}=_c(),[Kt,Jt]=i.useState(!1),[rn,qt]=i.useState(!1),we=i.useRef(null),ze=i.useRef(null),[rt,He]=i.useState(null),Ae=d??wt,pt=u??Ft,Ct=!e;i.useEffect(()=>{if(a)kt(a),Je(!1),nt(null);else{let te=!1;return Je(!0),nt(null),Bs().then(Ee=>{te||(kt(Ee.models),d||At(Ee.favoriteProviders),u||ln(Ee.favoriteModels))}).catch(Ee=>{te||nt(Ie(Ee)||"Failed to load models")}).finally(()=>{te||Je(!1)}),Cc(l).then(Ee=>{te||hn(Ee)}).catch(()=>{}),()=>{te=!0}}},[a,d,u,l]);const Tt=rd(F,re),Gt=rd(be,se),nn=rd(Le,Ke),Ht=!!(F&&re),on=!!(be&&se),ae=!!(Le&&Ke),le=Number(Ht)+Number(on)+Number(ae),Qe=un?Vt?.modelPresets?.find(te=>te.id===un)?.name??"Models":le>0?`${le} model${le===1?"":"s"}`:"Models",xt=i.useCallback((te,Ee)=>{if(!te||!Ee)return"Using default";const T=bt.find(je=>je.provider===te&&je.id===Ee);return T?`${T.provider}/${T.id}`:`${te}/${Ee}`},[bt]);i.useEffect(()=>{p(Ln(so,l)||"")},[l]),i.useEffect(()=>{typeof window<"u"&&rs(so,f,l)},[f,l]),i.useEffect(()=>{k.current!==l&&(k.current=l,M([]),D(void 0),ge(null),W(!1),et(null))},[l]),i.useEffect(()=>{typeof window<"u"&&localStorage.removeItem("kb-quick-entry-expanded")},[]),i.useEffect(()=>{E.current=R},[R]),i.useEffect(()=>()=>{E.current.forEach(te=>URL.revokeObjectURL(te.previewUrl))},[]);const zt=i.useCallback(()=>{const te=S.current;if(!te)return;te.style.height="auto";const Ee=Math.min(te.scrollHeight,200);te.style.height=`${Ee}px`},[]);i.useEffect(()=>{v&&zt()},[f,v,zt]),i.useEffect(()=>{if(!g&&f===""&&S.current){const te=setTimeout(()=>{S.current?.focus()},0);return()=>clearTimeout(te)}},[g,f]),i.useEffect(()=>{H||q("")},[H]),i.useEffect(()=>{if(!Kt)return;const te=Ee=>{const T=Ee.target,je=we.current?.contains(T),Pe=ze.current?.contains(T);!je&&!Pe&&Jt(!1)};return document.addEventListener("mousedown",te),()=>document.removeEventListener("mousedown",te)},[Kt]),i.useEffect(()=>{if(!ye)return;const te=Ee=>{const T=Ee.target,je=Te.current?.contains(T),Pe=Fe.current?.contains(T),st=T instanceof Element&&T.closest?.(".model-combobox-dropdown--portal")!=null;!je&&!Pe&&!st&&(Z(!1),Q(null))};return document.addEventListener("mousedown",te),()=>document.removeEventListener("mousedown",te)},[ye]),i.useEffect(()=>{if(!de)return;const te=Ee=>{const T=Ee.target;he.current?.contains(T)||pe.current?.contains(T)||(me(!1),Oe(null))};return document.addEventListener("mousedown",te),()=>document.removeEventListener("mousedown",te)},[de]),i.useEffect(()=>{if(!N)return;const te=Ee=>{const T=Ee.target;mt.current?.contains(T)||We.current?.contains(T)||(W(!1),et(null))};return document.addEventListener("mousedown",te),()=>document.removeEventListener("mousedown",te)},[N]),i.useEffect(()=>{if(!Ne)return;const te=Ee=>{const T=Ee.target;De.current?.contains(T)||ut.current?.contains(T)||(ve(!1),ft(null))};return document.addEventListener("mousedown",te),()=>document.removeEventListener("mousedown",te)},[Ne]);const sn=i.useCallback(()=>{R.forEach(te=>URL.revokeObjectURL(te.previewUrl)),O([]),C.current&&(C.current.value=""),p(""),G([]),ge(null),W(!1),et(null),me(!1),Oe(null),ve(!1),ft(null),X(void 0),U(void 0),Ue(void 0),Ve(void 0),ct(void 0),oe(void 0),pn(void 0),Wt(!1),cn(_s),Yt(void 0),A(!1),Z(!1),yt(null),Q(null),Jt(!1),qt(!1),b(!1),j(!1),x.current=!0,S.current&&(S.current.style.height="auto"),typeof window<"u"&&qa(so,l)},[R,l]),xn=i.useCallback(te=>{if(!te||te.length===0)return;const Ee=[];for(let T=0;T<te.length;T++){const je=te[T];s_.includes(je.type)&&Ee.push({file:je,previewUrl:URL.createObjectURL(je)})}Ee.length>0&&O(T=>[...T,...Ee])},[]),$n=i.useCallback(te=>{g||xn(te.clipboardData?.files)},[xn,g]),wn=i.useCallback(te=>{O(Ee=>{const T=Ee[te];return T&&URL.revokeObjectURL(T.previewUrl),Ee.filter((je,Pe)=>Pe!==te)})},[]),zn=i.useCallback(async()=>{const te=f.trim();if(!te||g||!e)return;const Ee=f;w(!0),p("");try{const T=await e({description:te,column:"triage",dependencies:_.length?_:void 0,...Y?{assignedAgentId:Y}:{},modelPresetId:un,modelProvider:Ht?F:void 0,modelId:Ht?re:void 0,validatorModelProvider:on?be:void 0,validatorModelId:on?se:void 0,planningModelProvider:ae?Le:void 0,planningModelId:ae?Ke:void 0,...an?{executionMode:"fast"}:{},priority:gn,nodeId:tn});if(T&&R.length>0){const je=[];for(const Pe of R)try{await Ec(T.id,Pe.file,l)}catch{je.push(Pe.file.name)}je.length>0&&n(`Failed to upload: ${je.join(", ")}`,"error")}sn()}catch(T){p(Ee),n(Ie(T)||"Failed to create task","error")}finally{w(!1)}},[f,g,e,_,Y,Ht,F,re,on,be,se,ae,Le,Ke,R,l,n,sn,an,gn,tn]),ce=i.useCallback(te=>{if(te.key==="Enter"){if(te.shiftKey&&v)return;te.preventDefault(),zn()}else if(te.key==="Escape"){if(te.preventDefault(),fe){Q(null);return}if(ye){Z(!1),yt(null);return}if(H){A(!1);return}if(Kt){Jt(!1);return}if(de){me(!1),Oe(null);return}if(Ne){ve(!1),ft(null);return}if(N){W(!1),et(null);return}f.trim()&&(p(""),S.current&&(S.current.style.height="auto"),typeof window<"u"&&qa(so,l)),b(!1),j(!1),S.current?.blur()}},[zn,f,v,H,N,de,ye,fe,Kt,Ne,l,j]),ee=i.useCallback(()=>{x.current&&(x.current=!1)},[]),Se=i.useCallback(()=>{c&&b(!0)},[c]),qe=i.useCallback(te=>{G(Ee=>Ee.includes(te)?Ee.filter(T=>T!==te):[...Ee,te])},[]),z=i.useCallback(()=>{const te=window.visualViewport;return te&&te.width>0&&te.height>0?{width:te.width,height:te.height,offsetTop:te.offsetTop,offsetLeft:te.offsetLeft}:{width:window.innerWidth,height:window.innerHeight,offsetTop:0,offsetLeft:0}},[]),_e=i.useCallback(()=>{const te=Te.current;if(!te)return;const Ee=te.getBoundingClientRect(),{width:T,height:je,offsetTop:Pe,offsetLeft:st}=z(),gt=16,Et=16,Pt=4,dn=T<=768,Nn=Math.min(dn?je*.6:je*.5,360),Hn=Math.max(Ee.width*1.35,320),ne=dn?Math.min(T-gt*2,360):Hn,Be=Math.min(ne,Math.max(T-gt*2,240)),Xe=Ee.top-Pe,Dt=Ee.bottom-Pe,Xt=Ee.left-st,mn=je-Dt,qn=Xe,Dn=Math.max(mn-Et-Pt,160),ts=Math.max(qn-Et-Pt,160),Vn=mn<Nn&&qn>mn,os=Math.max(Math.min(Vn?ts:Dn,Nn),160),ns=Math.min(Math.max(Xt,gt),T-gt-Be)+st,ja=Vn?Math.max(Et+Pe,Xe-os-Pt+Pe):Math.min(Dt+Pt+Pe,je+Pe-Et-os);yt({top:ja,left:ns,width:Be,maxHeight:os})},[z]),Rt=i.useCallback(()=>{const te=we.current?.querySelector(".refine-button");if(!te)return;const Ee=te.getBoundingClientRect(),{width:T,height:je,offsetTop:Pe,offsetLeft:st}=z(),gt=8,Et=12,Pt=4,dn=Math.min(200,Math.max(je-Et*2,160)),Nn=Math.min(200,T-gt*2),Hn=Ee.top-Pe,ne=Ee.bottom-Pe,Be=Ee.left-st,Xe=je-ne,Dt=Hn,Xt=Xe<dn&&Dt>Xe,mn=Math.min(Math.max(Be,gt),T-gt-Nn)+st,qn=Xt?Math.max(Et+Pe,Hn-dn-Pt+Pe):Math.min(ne+Pt+Pe,je+Pe-Et-dn);He({top:qn,left:mn})},[z]),Ot=i.useCallback(()=>{const te=Ge.current;if(!te)return;const Ee=te.getBoundingClientRect(),{width:T,height:je,offsetTop:Pe,offsetLeft:st}=z(),gt=16,Et=16,Pt=4,dn=T<=768,Nn=Math.min(dn?je*.6:je*.5,320),Hn=dn?Math.min(T-gt*2,360):Math.max(Ee.width,280),ne=Math.min(Hn,Math.max(T-gt*2,240)),Be=Ee.top-Pe,Xe=Ee.bottom-Pe,Dt=Ee.left-st,Xt=je-Xe,mn=Be,qn=Math.max(Xt-Et-Pt,200),Dn=Math.max(mn-Et-Pt,200),ts=Xt<Nn&&mn>Xt,Vn=Math.max(Math.min(ts?Dn:qn,Nn),200),os=Math.min(Math.max(Dt,gt),T-gt-ne)+st,ns=ts?Math.max(Et+Pe,Be-Vn-Pt+Pe):Math.min(Xe+Pt+Pe,je+Pe-Et-Vn);ot({top:ns,left:os,width:ne,maxHeight:Vn})},[z]),Lt=i.useCallback(()=>{const te=mt.current?.querySelector("button");if(!te)return;const Ee=te.getBoundingClientRect(),{width:T,height:je,offsetTop:Pe,offsetLeft:st}=z(),gt=16,Et=16,Pt=4,dn=T<=768,Nn=Math.min(dn?je*.6:je*.5,320),Hn=dn?Math.min(T-gt*2,280):Math.max(Ee.width,240),ne=Math.min(Hn,Math.max(T-gt*2,200)),Be=Ee.top-Pe,Xe=Ee.bottom-Pe,Dt=Ee.left-st,Xt=je-Xe,mn=Be,qn=Math.max(Xt-Et-Pt,160),Dn=Math.max(mn-Et-Pt,160),ts=Xt<Nn&&mn>Xt,Vn=Math.max(Math.min(ts?Dn:qn,Nn),160),os=Math.min(Math.max(Dt,gt),T-gt-ne)+st,ns=ts?Math.max(Et+Pe,Be-Vn-Pt+Pe):Math.min(Xe+Pt+Pe,je+Pe-Et-Vn);et({top:ns,left:os,width:ne,maxHeight:Vn})},[z]),fn=i.useCallback(()=>{const te=he.current?.querySelector("button");if(!te)return;const Ee=te.getBoundingClientRect(),{width:T,height:je,offsetTop:Pe,offsetLeft:st}=z(),gt=16,Et=16,Pt=4,dn=T<=768,Nn=Math.min(dn?je*.6:je*.5,320),Hn=dn?Math.min(T-gt*2,280):Math.max(Ee.width,240),ne=Math.min(Hn,Math.max(T-gt*2,200)),Be=Ee.top-Pe,Xe=Ee.bottom-Pe,Dt=Ee.left-st,Xt=je-Xe,mn=Be,qn=Math.max(Xt-Et-Pt,160),Dn=Math.max(mn-Et-Pt,160),ts=Xt<Nn&&mn>Xt,Vn=Math.max(Math.min(ts?Dn:qn,Nn),160),os=Math.min(Math.max(Dt,gt),T-gt-ne)+st,ns=ts?Math.max(Et+Pe,Be-Vn-Pt+Pe):Math.min(Xe+Pt+Pe,je+Pe-Et-Vn);Oe({top:ns,left:os,width:ne,maxHeight:Vn})},[z]),kn=i.useCallback(()=>{const te=De.current?.querySelector("button");if(!te)return;const Ee=te.getBoundingClientRect(),{width:T,height:je,offsetTop:Pe,offsetLeft:st}=z(),gt=16,Et=16,Pt=4,dn=220,Nn=Math.min(Math.max(Ee.width,200),Math.max(T-gt*2,200)),Hn=Ee.top-Pe,ne=Ee.bottom-Pe,Be=Ee.left-st,Xe=je-ne,Dt=Hn,Xt=Math.max(Xe-Et-Pt,160),mn=Math.max(Dt-Et-Pt,160),qn=Xe<dn&&Dt>Xe,Dn=Math.max(Math.min(qn?mn:Xt,dn),160),ts=Math.min(Math.max(Be,gt),T-gt-Nn)+st,Vn=qn?Math.max(Et+Pe,Hn-Dn-Pt+Pe):Math.min(ne+Pt+Pe,je+Pe-Et-Dn);ft({top:Vn,left:ts,width:Nn,maxHeight:Dn})},[z]);i.useEffect(()=>{if(!ye)return;const te=()=>_e();window.addEventListener("resize",te),window.addEventListener("scroll",te,!0);const Ee=window.visualViewport;return Ee&&(Ee.addEventListener("resize",te),Ee.addEventListener("scroll",te)),()=>{window.removeEventListener("resize",te),window.removeEventListener("scroll",te,!0),Ee&&(Ee.removeEventListener("resize",te),Ee.removeEventListener("scroll",te))}},[ye,_e]),i.useEffect(()=>{if(!Kt)return;const te=()=>Rt();window.addEventListener("resize",te),window.addEventListener("scroll",te,!0);const Ee=window.visualViewport;return Ee&&(Ee.addEventListener("resize",te),Ee.addEventListener("scroll",te)),()=>{window.removeEventListener("resize",te),window.removeEventListener("scroll",te,!0),Ee&&(Ee.removeEventListener("resize",te),Ee.removeEventListener("scroll",te))}},[Kt,Rt]),i.useEffect(()=>{if(!H)return;const te=()=>Ot();window.addEventListener("resize",te),window.addEventListener("scroll",te,!0);const Ee=window.visualViewport;return Ee&&(Ee.addEventListener("resize",te),Ee.addEventListener("scroll",te)),()=>{window.removeEventListener("resize",te),window.removeEventListener("scroll",te,!0),Ee&&(Ee.removeEventListener("resize",te),Ee.removeEventListener("scroll",te))}},[H,Ot]),i.useEffect(()=>{if(!N)return;const te=()=>Lt();window.addEventListener("resize",te),window.addEventListener("scroll",te,!0);const Ee=window.visualViewport;return Ee&&(Ee.addEventListener("resize",te),Ee.addEventListener("scroll",te)),()=>{window.removeEventListener("resize",te),window.removeEventListener("scroll",te,!0),Ee&&(Ee.removeEventListener("resize",te),Ee.removeEventListener("scroll",te))}},[N,Lt]),i.useEffect(()=>{if(!de)return;const te=()=>fn();window.addEventListener("resize",te),window.addEventListener("scroll",te,!0);const Ee=window.visualViewport;return Ee&&(Ee.addEventListener("resize",te),Ee.addEventListener("scroll",te)),()=>{window.removeEventListener("resize",te),window.removeEventListener("scroll",te,!0),Ee&&(Ee.removeEventListener("resize",te),Ee.removeEventListener("scroll",te))}},[de,fn]),i.useEffect(()=>{if(!Ne)return;const te=()=>kn();window.addEventListener("resize",te),window.addEventListener("scroll",te,!0);const Ee=window.visualViewport;return Ee&&(Ee.addEventListener("resize",te),Ee.addEventListener("scroll",te)),()=>{window.removeEventListener("resize",te),window.removeEventListener("scroll",te,!0),Ee&&(Ee.removeEventListener("resize",te),Ee.removeEventListener("scroll",te))}},[Ne,kn]);const es=i.useCallback(te=>{const Ee=od(te);ct(Ee.provider),oe(Ee.modelId)},[]),ms=i.useCallback(te=>{const Ee=od(te);X(Ee.provider),U(Ee.modelId)},[]),Gn=i.useCallback(te=>{const Ee=od(te);Ue(Ee.provider),Ve(Ee.modelId)},[]),hs=i.useCallback(async te=>{if(h){h(te);return}const Ee=wt,je=Ee.includes(te)?Ee.filter(Pe=>Pe!==te):[te,...Ee];At(je);try{await Fn({favoriteProviders:je,favoriteModels:Ft})}catch{At(Ee)}},[wt,Ft,h]),Cn=i.useCallback(async te=>{if(m){m(te);return}const Ee=Ft,je=Ee.includes(te)?Ee.filter(Pe=>Pe!==te):[te,...Ee];ln(je);try{await Fn({favoriteProviders:wt,favoriteModels:je})}catch{ln(Ee)}},[Ft,wt,m]),Bt=i.useCallback(()=>{const te=f.trim();if(!te){n("Enter a description first","error");return}r?.(te),sn()},[f,r,n,sn]),Bn=i.useCallback(()=>{const te=f.trim();if(!te){n("Enter a description first","error");return}o?.(te),sn()},[f,o,n,sn]),En=i.useCallback(()=>{zn()},[zn]),bs=i.useCallback(async te=>{const Ee=f.trim();if(!(!Ee||rn)){Jt(!1),qt(!0);try{const T=await Ab(Ee,te,l);p(T),n("Description refined with AI","success"),S.current&&(S.current.style.height="auto",S.current.style.height=`${Math.min(S.current.scrollHeight,200)}px`)}catch(T){const je=Rb(T);n(je,"error")}finally{qt(!1)}}},[f,rn,n,l]),$s=(te,Ee)=>te.length>Ee?te.slice(0,Ee)+"…":te,ss=i.useCallback(async()=>{if(a){kt(a),nt(null),Je(!1);return}Je(!0),nt(null);try{const te=await Bs();kt(te.models),d||At(te.favoriteProviders),u||ln(te.favoriteModels)}catch(te){nt(Ie(te)||"Failed to load models")}finally{Je(!1)}},[a,d,u]),Un=i.useCallback(async()=>{if(L.length>0&&$===l){W(!0),Lt();return}ie(!0);try{const te=await Hr(void 0,l);M(te),D(l),W(!0),Lt()}catch(te){const Ee=Ie(te);n(Ee?`Failed to load agents: ${Ee}`:"Failed to load agents","error"),W(!1)}finally{ie(!1)}},[L.length,$,l,n,Lt]),Ms=(Y?L.find(te=>te.id===Y):void 0)?.name??Y,xs=tn?Qt.find(te=>te.id===tn):void 0,As=y,vs=i.useCallback(()=>{j(te=>{const Ee=!te;return b(Ee),Ee})},[]);return t.jsxs("div",{className:`quick-entry-box ${y?"quick-entry-box--expanded":"quick-entry-box--collapsed"}`,"data-testid":"quick-entry-box",children:[t.jsx("div",{className:"description-with-refine",children:t.jsxs("div",{className:"quick-entry-main-row",children:[t.jsx("div",{className:"quick-entry-textarea-wrap",children:t.jsx("textarea",{ref:S,className:`quick-entry-input ${v?"quick-entry-input--expanded":""}`,placeholder:g?"Creating...":"Add a task...",value:f,onChange:te=>p(te.target.value),onKeyDown:ce,onPaste:$n,onFocus:Se,onBlur:ee,disabled:g||Ct,"data-testid":"quick-entry-input",rows:2,"aria-controls":"quick-entry-controls","aria-expanded":y})}),t.jsx("button",{type:"button",className:"btn btn-sm quick-entry-toggle",onClick:vs,"aria-expanded":y,"aria-controls":"quick-entry-controls","data-testid":"quick-entry-toggle",title:y?"Collapse":"Expand",children:y?t.jsx(mi,{size:14}):t.jsx(vn,{size:14})})]})}),t.jsxs("div",{id:"quick-entry-controls",className:"quick-entry-controls",hidden:!As,"aria-hidden":!As,children:[As&&!g&&t.jsxs("div",{className:"quick-entry-actions","data-testid":"quick-entry-actions",children:[t.jsxs("button",{type:"button",className:"btn btn-sm",onClick:Bt,onMouseDown:te=>te.preventDefault(),disabled:!f.trim(),"data-testid":"plan-button",title:"Open planning mode with current description",children:[t.jsx(Di,{size:12,style:{verticalAlign:"middle",marginRight:4}}),"Plan"]}),t.jsxs("button",{type:"button",className:"btn btn-sm",onClick:Bn,onMouseDown:te=>te.preventDefault(),disabled:!f.trim(),"data-testid":"subtask-button",title:"Break down into AI-generated subtasks",children:[t.jsx(wc,{size:12,style:{verticalAlign:"middle",marginRight:4}}),"Subtask"]}),t.jsxs("div",{className:"refine-trigger-wrap",ref:we,children:[t.jsxs("button",{type:"button",className:`btn btn-sm refine-button ${rn?"refine-button--loading":""}`,onClick:()=>{Jt(te=>{const Ee=!te;return Ee?Rt():He(null),Ee})},disabled:!f.trim()||rn,"data-testid":"refine-button",title:"Refine description with AI",children:[t.jsx(cs,{size:12,style:{verticalAlign:"middle"}}),rn?"Refining...":"Refine"]}),Kt&&xe&&rt&&$a.createPortal(t.jsxs("div",{ref:ze,className:"refine-menu refine-menu--portal",onMouseDown:te=>te.preventDefault(),style:{position:"fixed",top:`${rt.top}px`,left:`${rt.left}px`},children:[t.jsxs("div",{className:"refine-menu-item",onClick:()=>bs("clarify"),"data-testid":"refine-clarify",children:[t.jsx("div",{className:"refine-menu-item-title",children:"Clarify"}),t.jsx("div",{className:"refine-menu-item-desc",children:"Make the description clearer and more specific"})]}),t.jsxs("div",{className:"refine-menu-item",onClick:()=>bs("add-details"),"data-testid":"refine-add-details",children:[t.jsx("div",{className:"refine-menu-item-title",children:"Add details"}),t.jsx("div",{className:"refine-menu-item-desc",children:"Add implementation details and context"})]}),t.jsxs("div",{className:"refine-menu-item",onClick:()=>bs("expand"),"data-testid":"refine-expand",children:[t.jsx("div",{className:"refine-menu-item-title",children:"Expand"}),t.jsx("div",{className:"refine-menu-item-desc",children:"Expand into a more comprehensive description"})]}),t.jsxs("div",{className:"refine-menu-item",onClick:()=>bs("simplify"),"data-testid":"refine-simplify",children:[t.jsx("div",{className:"refine-menu-item-title",children:"Simplify"}),t.jsx("div",{className:"refine-menu-item-desc",children:"Simplify and make more concise"})]})]}),xe)]}),t.jsx("div",{className:"dep-trigger-wrap",children:t.jsxs("button",{ref:Ge,type:"button",className:"btn btn-sm dep-trigger","data-testid":"quick-entry-deps",onClick:()=>{A(te=>{const Ee=!te;return Ee?(Z(!1),yt(null),Q(null),W(!1),et(null),me(!1),Oe(null),ve(!1),ft(null),Ot()):ot(null),Ee})},children:[t.jsx(Cr,{size:12,style:{verticalAlign:"middle"}}),_.length>0?`${_.length} deps`:"Deps"]})}),H&&xe&&ue&&(()=>{const te=P.toLowerCase(),Ee=(te?s.filter(T=>T.id.toLowerCase().includes(te)||T.title&&T.title.toLowerCase().includes(te)||T.description&&T.description.toLowerCase().includes(te)):[...s]).sort((T,je)=>{const Pe=je.createdAt.localeCompare(T.createdAt);if(Pe!==0)return Pe;const st=parseInt(T.id.slice(T.id.lastIndexOf("-")+1),10)||0;return(parseInt(je.id.slice(je.id.lastIndexOf("-")+1),10)||0)-st});return $a.createPortal(t.jsxs("div",{ref:K,className:"dep-dropdown dep-dropdown--portal",onMouseDown:T=>T.preventDefault(),style:{position:"fixed",top:`${ue.top}px`,left:`${ue.left}px`,width:`${ue.width}px`,maxHeight:ue.maxHeight?`${ue.maxHeight}px`:void 0,overflowY:ue.maxHeight?"auto":void 0},children:[t.jsx("input",{className:"dep-dropdown-search",placeholder:"Search tasks…",autoFocus:!0,value:P,onChange:T=>q(T.target.value),onClick:T=>T.stopPropagation()}),Ee.length===0?t.jsx("div",{className:"dep-dropdown-empty",children:"No existing tasks"}):Ee.map(T=>t.jsxs("div",{className:`dep-dropdown-item${_.includes(T.id)?" selected":""}`,onMouseDown:je=>je.preventDefault(),onClick:()=>qe(T.id),children:[t.jsx("span",{className:"dep-dropdown-id",children:T.id}),t.jsx("span",{className:"dep-dropdown-title",children:$s(T.title||T.description||T.id,60)})]},T.id))]}),xe)})(),t.jsxs("button",{type:"button",className:"btn btn-sm","data-testid":"quick-entry-attach",onClick:()=>C.current?.click(),children:[t.jsx(pb,{size:12,style:{verticalAlign:"middle"}}),R.length>0?`Attach (${R.length})`:"Attach"]}),t.jsxs("button",{ref:Te,type:"button",className:"btn btn-sm","data-testid":"quick-entry-models",onClick:()=>{A(!1),W(!1),et(null),me(!1),Oe(null),ve(!1),ft(null),Q(null),Z(!0),_e()},children:[t.jsx(Po,{size:12,style:{verticalAlign:"middle"}}),Qe]}),t.jsx("div",{className:"node-trigger-wrap",ref:he,children:t.jsxs("button",{type:"button",className:"btn btn-sm dep-trigger","data-testid":"quick-entry-node-button",onClick:()=>{A(!1),W(!1),et(null),Z(!1),yt(null),Q(null),ve(!1),ft(null),me(te=>{const Ee=!te;return Ee?fn():Oe(null),Ee})},children:[t.jsx($o,{size:12,style:{verticalAlign:"middle"}}),` ${xs?.name??"Node"}`,xs&&t.jsx("span",{className:"quick-entry-node-status",children:t.jsx(Ua,{status:xs.status,showLabel:!0})})]})}),de&&xe&&vt&&$a.createPortal(t.jsxs("div",{ref:pe,className:"dep-dropdown node-picker-dropdown node-picker-dropdown--portal",onMouseDown:te=>te.preventDefault(),style:{position:"fixed",top:`${vt.top}px`,left:`${vt.left}px`,width:`${vt.width}px`,maxHeight:vt.maxHeight?`${vt.maxHeight}px`:void 0,overflowY:vt.maxHeight?"auto":void 0},children:[t.jsx("div",{className:"dep-dropdown-search-header",children:"Select execution node"}),t.jsx("div",{className:`dep-dropdown-item node-picker-item${tn==null?" selected":""}`,onMouseDown:te=>te.preventDefault(),onClick:()=>{Yt(void 0),me(!1),Oe(null)},children:t.jsx("span",{className:"node-picker-item-name",children:"Project default / local"})}),Qt.map(te=>t.jsxs("div",{className:`dep-dropdown-item node-picker-item${tn===te.id?" selected":""}`,onMouseDown:Ee=>Ee.preventDefault(),onClick:()=>{Yt(te.id),me(!1),Oe(null)},children:[t.jsx("span",{className:"quick-entry-node-status",children:t.jsx(Ua,{status:te.status})}),t.jsx("span",{className:"node-picker-item-name",children:te.name}),t.jsx("span",{className:"node-picker-item-status",children:i_(te.status)})]},te.id))]}),xe),t.jsx("div",{className:"agent-trigger-wrap",ref:mt,children:t.jsxs("button",{type:"button",className:"btn btn-sm dep-trigger",onClick:()=>{N?(W(!1),et(null)):(me(!1),Oe(null),ve(!1),ft(null),Un())},"data-testid":"quick-entry-agent-button",children:[t.jsx(Xn,{size:12,style:{verticalAlign:"middle"}}),Ms?` ${Ms}`:" Agent"]})}),N&&xe&&ht&&$a.createPortal(t.jsxs("div",{ref:We,className:"dep-dropdown agent-picker-dropdown agent-picker-dropdown--portal",onMouseDown:te=>te.preventDefault(),style:{position:"fixed",top:`${ht.top}px`,left:`${ht.left}px`,width:`${ht.width}px`,maxHeight:ht.maxHeight?`${ht.maxHeight}px`:void 0,overflowY:ht.maxHeight?"auto":void 0},children:[t.jsx("div",{className:"dep-dropdown-search-header",children:"Select agent"}),Me&&t.jsx("div",{className:"dep-dropdown-empty",children:"Loading agents..."}),!Me&&L.map(te=>t.jsxs("div",{className:`dep-dropdown-item${Y===te.id?" selected":""}`,onMouseDown:Ee=>Ee.preventDefault(),onClick:()=>{ge(te.id===Y?null:te.id),W(!1),et(null)},children:[t.jsx(Xn,{size:12,style:{marginRight:6}}),t.jsx("span",{className:"dep-dropdown-id",children:te.role}),t.jsx("span",{className:"dep-dropdown-title",children:te.name})]},te.id)),!Me&&L.length===0&&t.jsx("div",{className:"dep-dropdown-empty",children:"No agents available"}),Y&&t.jsx("div",{className:"dep-dropdown-item",onMouseDown:te=>te.preventDefault(),onClick:()=>{ge(null),W(!1),et(null)},children:t.jsx("span",{className:"dep-dropdown-title",children:"Clear selection"})})]}),xe),t.jsx("div",{className:"priority-trigger-wrap",ref:De,children:t.jsxs("button",{type:"button",className:"btn btn-sm dep-trigger","data-testid":"quick-entry-priority-button",onClick:()=>{A(!1),W(!1),et(null),me(!1),Oe(null),Z(!1),yt(null),Q(null),ve(te=>{const Ee=!te;return Ee?kn():ft(null),Ee})},children:[t.jsx(Hw,{size:12,style:{verticalAlign:"middle"}}),` ${gn[0].toUpperCase()}${gn.slice(1)}`]})}),Ne&&xe&&tt&&$a.createPortal(t.jsxs("div",{ref:ut,className:"dep-dropdown priority-picker-dropdown priority-picker-dropdown--portal",onMouseDown:te=>te.preventDefault(),style:{position:"fixed",top:`${tt.top}px`,left:`${tt.left}px`,width:`${tt.width}px`,maxHeight:tt.maxHeight?`${tt.maxHeight}px`:void 0,overflowY:tt.maxHeight?"auto":void 0},children:[t.jsx("div",{className:"dep-dropdown-search-header",children:"Select priority"}),wa.map(te=>{const Ee=`${te[0].toUpperCase()}${te.slice(1)}`;return t.jsx("div",{className:`dep-dropdown-item${gn===te?" selected":""}`,"data-testid":`quick-entry-priority-option-${te}`,onMouseDown:T=>T.preventDefault(),onClick:()=>{cn(te),ve(!1),ft(null)},children:t.jsx("span",{className:"dep-dropdown-title",children:Ee})},te)})]}),xe),t.jsx("button",{type:"button",className:`btn btn-sm ${an?"btn-primary":""}`,onClick:()=>Wt(te=>!te),onMouseDown:te=>te.preventDefault(),"aria-pressed":an,"data-testid":"quick-entry-fast-toggle",title:"Toggle fast execution mode",children:"Fast"}),t.jsxs("button",{type:"button",className:"btn btn-task-create btn-sm",onClick:En,onMouseDown:te=>te.preventDefault(),disabled:!f.trim()||g,"data-testid":"quick-entry-save",title:"Create task",children:[t.jsx(gb,{size:12,style:{verticalAlign:"middle",marginRight:4}}),"Save"]})]}),R.length>0&&t.jsx("div",{className:"inline-create-previews",children:R.map((te,Ee)=>t.jsxs("div",{className:"inline-create-preview",children:[t.jsx("img",{src:te.previewUrl,alt:te.file.name}),t.jsx("button",{type:"button",className:"inline-create-preview-remove",onClick:()=>wn(Ee),disabled:g,title:"Remove image","data-testid":`quick-entry-preview-remove-${Ee}`,children:"×"})]},te.previewUrl))}),ye&&xe&&Mt&&$a.createPortal(t.jsx("div",{ref:Fe,className:"model-nested-menu model-nested-menu--portal",onMouseDown:te=>te.preventDefault(),"data-testid":"model-nested-menu",style:{position:"fixed",top:`${Mt.top}px`,left:`${Mt.left}px`,width:`${Mt.width}px`,maxHeight:Mt.maxHeight?`${Mt.maxHeight}px`:void 0,overflowY:Mt.maxHeight?"auto":void 0},children:fe===null?t.jsxs("div",{className:"model-menu-items",children:[t.jsxs("button",{type:"button",className:`model-menu-item ${ae?"model-menu-item--active":""}`,onClick:()=>Q("plan"),"data-testid":"model-menu-plan",children:[t.jsxs("span",{className:"model-menu-item-label",children:[t.jsx(Di,{size:12,style:{verticalAlign:"middle",marginRight:6}}),"Plan"]}),t.jsx("span",{className:"model-menu-item-value",children:ae?xt(Le,Ke):"Using default"}),t.jsx(Wn,{size:12,style:{marginLeft:"auto",color:"var(--text-dim)"}})]}),t.jsxs("button",{type:"button",className:`model-menu-item ${Ht?"model-menu-item--active":""}`,onClick:()=>Q("executor"),"data-testid":"model-menu-executor",children:[t.jsxs("span",{className:"model-menu-item-label",children:[t.jsx(cs,{size:12,style:{verticalAlign:"middle",marginRight:6}}),"Executor"]}),t.jsx("span",{className:"model-menu-item-value",children:Ht?xt(F,re):"Using default"}),t.jsx(Wn,{size:12,style:{marginLeft:"auto",color:"var(--text-dim)"}})]}),t.jsxs("button",{type:"button",className:`model-menu-item ${on?"model-menu-item--active":""}`,onClick:()=>Q("validator"),"data-testid":"model-menu-validator",children:[t.jsxs("span",{className:"model-menu-item-label",children:[t.jsx(Po,{size:12,style:{verticalAlign:"middle",marginRight:6}}),"Reviewer"]}),t.jsx("span",{className:"model-menu-item-value",children:on?xt(be,se):"Using default"}),t.jsx(Wn,{size:12,style:{marginLeft:"auto",color:"var(--text-dim)"}})]})]}):t.jsxs("div",{className:"model-submenu",children:[t.jsxs("button",{type:"button",className:"model-submenu-back",onClick:()=>Q(null),"data-testid":"model-submenu-back",children:[t.jsx(vn,{size:12,style:{transform:"rotate(90deg)",marginRight:4}}),"Back"]}),t.jsxs("div",{className:"model-submenu-header",children:[fe==="plan"&&"Plan Model",fe==="executor"&&"Executor Model",fe==="validator"&&"Reviewer Model"]}),t.jsx(Ns,{models:bt,value:fe==="plan"?nn:fe==="executor"?Tt:Gt,onChange:fe==="plan"?es:fe==="executor"?ms:Gn,placeholder:"Using default",disabled:dt,id:`model-${fe}-select`,label:`${fe} model`,favoriteProviders:Ae,onToggleFavorite:hs,favoriteModels:pt,onToggleModelFavorite:Cn}),ke&&t.jsxs("div",{className:"model-submenu-error",children:[t.jsx("span",{children:ke}),t.jsx("button",{type:"button",className:"btn btn-sm",onClick:ss,children:"Retry"})]})]})}),xe)]}),t.jsx("input",{ref:C,type:"file",accept:"image/*",multiple:!0,style:{display:"none"},onChange:te=>{xn(te.target.files),te.currentTarget.value=""},"data-testid":"quick-entry-file-input"}),t.jsx("div",{className:"quick-entry-hint",children:"Enter to create · Esc to cancel"})]})}function a_(e){return tm(e)||e}function r_(e){const n=new Map(e.map(l=>[l.id,l])),s=[],a=new Set,r=new Set;function o(l){if(a.has(l)||r.has(l))return;r.add(l);const c=n.get(l);if(c)for(const d of c.dependencies||[])n.has(d)&&o(d);r.delete(l),a.add(l),s.push(l)}for(const l of e)o(l.id);return s}function o_(e,n,s){const a=e.filter(g=>g.worktree),r=e.filter(g=>!g.worktree),o=new Map;for(const g of a){const w=g.worktree,v=o.get(w)||[];v.push(g),o.set(w,v)}const l=new Map(n.map(g=>[g.id,g])),d=n.filter(g=>g.column==="todo").filter(g=>!g.paused&&(g.dependencies||[]).every(w=>{const v=l.get(w);return v&&(v.column==="done"||v.column==="in-review"||v.column==="archived")})),h=r_(d).map(g=>l.get(g)).filter(g=>g!==void 0&&d.includes(g)),m=[],f=Array.from(o.keys());for(const g of f)m.push({label:a_(g),activeTasks:o.get(g),queuedTasks:[]});r.length>0&&m.push({label:"Unassigned",activeTasks:r,queuedTasks:[]});const p=h.slice(0,s);return p.length>0&&m.push({label:"Up Next",activeTasks:[],queuedTasks:p}),m}const Zh=100,ld=50,ep=25;function l_({column:e,tasks:n,projectId:s,maxConcurrent:a,onMoveTask:r,onPauseTask:o,onOpenDetail:l,addToast:c,onQuickCreate:d,onNewTask:u,autoMerge:h,onToggleAutoMerge:m,globalPaused:f,onUpdateTask:p,onRetryTask:g,onArchiveTask:w,onUnarchiveTask:v,onDeleteTask:b,onArchiveAllDone:y,collapsed:j,onToggleCollapse:S,allTasks:C,availableModels:x,onPlanningMode:k,onSubtaskBreakdown:R,onOpenDetailWithTab:O,favoriteProviders:E,favoriteModels:_,onToggleFavorite:G,onToggleModelFavorite:H,isSearchActive:A,taskStuckTimeoutMs:P,onOpenMission:q,lastFetchTimeMs:Y,workflowStepNameLookup:ge,blockerFanoutMap:L}){const[M,$]=i.useState(!1),[D,N]=i.useState(ld),[W,de]=i.useState(!1),[me,Ne]=i.useState(!1),[ve,Me]=i.useState(!1),[ie,ye]=i.useState(!1),Z=i.useRef(null),fe=sE(n.length),{confirm:Q}=ti();i.useEffect(()=>{if(!W)return;function De(ht){Z.current?.contains(ht.target)||de(!1)}function ut(ht){ht.key==="Escape"&&de(!1)}return document.addEventListener("mousedown",De),document.addEventListener("keydown",ut),()=>{document.removeEventListener("mousedown",De),document.removeEventListener("keydown",ut)}},[W]);const F=e==="archived",X=F&&j,re=!F&&!A&&e!=="in-progress"&&n.length>Zh;i.useEffect(()=>{N(De=>e==="in-progress"||F||n.length<=Zh?ld:Math.min(Math.max(De,ld),n.length))},[e,F,n.length]);const U=i.useCallback(De=>{F||(De.preventDefault(),De.dataTransfer.dropEffect="move",$(!0))},[F]),be=i.useCallback(De=>{De.currentTarget.contains(De.relatedTarget)||$(!1)},[]),Ue=i.useCallback(async De=>{De.preventDefault(),$(!1);const ut=De.dataTransfer.getData("text/plain");if(!ut)return;const ht=n.find(et=>et.id===ut);if(!(ht&&ht.column===e))try{const vt=(C?.find(ft=>ft.id===ut)??ht)?.steps.some(ft=>ft.status!=="pending")??!1,Oe=(e==="todo"||e==="triage")&&vt;let tt;if(Oe){if(await Q({title:"Preserve Progress?",message:"This task has completed steps. Keep progress before moving?",confirmLabel:"Keep Progress",cancelLabel:"Reset Progress"}))tt={preserveProgress:!0};else if(!await Q({title:"Reset Progress?",message:"Reset all step progress before moving this task?",confirmLabel:"Reset Progress",cancelLabel:"Cancel Move",danger:!0}))return}await r(ut,e,tt)}catch(et){c(Ie(et),"error")}},[c,C,e,Q,r,n]),se=i.useMemo(()=>e!=="in-progress"?[]:o_(n,n,a),[e,n,a]),Ve=i.useMemo(()=>re?n.slice(0,D):n,[re,n,D]),Le=Math.max(0,n.length-Ve.length),ct=i.useCallback(()=>{N(De=>Math.min(De+ep,n.length))},[n.length]),Ke=i.useCallback(async()=>{if(de(!1),!(n.length===0||!await Q({title:"Replan All Tasks",message:`Move all ${n.length} todo task${n.length===1?"":"s"} back to planning to be replanned?`}))){Ne(!0);try{const ut=await Promise.allSettled(n.map(vt=>r(vt.id,"triage"))),ht=ut.filter(vt=>vt.status==="rejected").length,et=ut.length-ht;ht===0?c(`Moved ${et} task${et===1?"":"s"} to planning for replanning`,"success"):c(`Moved ${et} of ${ut.length} tasks; ${ht} failed`,"error")}finally{Ne(!1)}}},[n,r,c,Q]),oe=i.useMemo(()=>n.filter(De=>!De.paused&&!De.assignedAgentId),[n]),Te=oe.length,Fe=e==="todo"||e==="in-progress"||e==="in-review",mt=me||ve||ie,We=i.useCallback(async()=>{if(!(!o||(de(!1),Te===0)||!await Q({title:"Stop All Tasks",message:`Stop all ${Te} ${ds[e].toLowerCase()} task${Te===1?"":"s"}?`,danger:!0}))){Me(!0);try{const ut=await Promise.allSettled(oe.map(vt=>o(vt.id))),ht=ut.filter(vt=>vt.status==="rejected").length,et=ut.length-ht;ht===0?c(`Stopped ${et} task${et===1?"":"s"}`,"success"):c(`Stopped ${et} of ${ut.length} tasks; ${ht} failed`,"error")}finally{Me(!1)}}},[o,Te,e,oe,c,Q]),he=i.useCallback(async()=>{if(de(!1),n.length===0||!await Q({title:"Move All to Todo",message:`Move all ${n.length} ${ds[e].toLowerCase()} task${n.length===1?"":"s"} to Todo?`}))return;const ut=n.some(et=>et.steps.some(vt=>vt.status!=="pending"));let ht=!1;if(ut){if(await Q({title:"Preserve Progress?",message:"Some tasks have completed steps. Keep progress before moving to Todo?",confirmLabel:"Keep Progress",cancelLabel:"Reset Progress"}))ht=!0;else if(!await Q({title:"Reset Progress?",message:"Reset step progress for tasks before moving to Todo?",confirmLabel:"Reset Progress",cancelLabel:"Cancel Move",danger:!0}))return}ye(!0);try{const et=await Promise.allSettled(n.map(tt=>r(tt.id,"todo",ht?{preserveProgress:!0}:void 0))),vt=et.filter(tt=>tt.status==="rejected").length,Oe=et.length-vt;vt===0?c(`Moved ${Oe} task${Oe===1?"":"s"} to Todo`,"success"):c(`Moved ${Oe} of ${et.length} tasks to Todo; ${vt} failed`,"error")}finally{ye(!1)}},[n,e,r,c,Q]),pe=i.useCallback(async()=>{if(!(!y||n.length===0||!await Q({title:"Archive All Done",message:`Archive all ${n.length} done tasks?`,danger:!0})))try{const ut=await y();c(`Archived ${ut.length} tasks`,"success")}catch(ut){c(Ie(ut)||"Failed to archive tasks","error")}},[y,n.length,c,Q]);return t.jsxs("div",{className:`column${M?" drag-over":""}${F?" column-archived":""}${X?" column-collapsed":""}`,"data-column":e,onDragOver:U,onDragLeave:be,onDrop:Ue,children:[t.jsxs("div",{className:"column-header",children:[t.jsx("div",{className:`column-dot dot-${e}`}),t.jsx("h2",{children:ds[e]}),t.jsx("span",{className:`column-count${fe?" count-flash":""}`,children:n.length}),e==="in-review"&&m&&t.jsxs("label",{className:"auto-merge-toggle",title:h?"Auto-merge enabled":"Auto-merge disabled",children:[t.jsx("input",{type:"checkbox",checked:!!h,onChange:m}),t.jsx("span",{className:"toggle-slider"}),t.jsx("span",{className:"toggle-label",children:"Auto-merge"})]}),u&&t.jsx("button",{className:"btn btn-task-create btn-sm",onClick:u,children:"+ New Task"}),e==="done"&&y&&t.jsx("button",{className:"btn btn-icon btn-sm",onClick:pe,disabled:n.length===0,title:"Archive all done tasks","aria-label":"Archive all done tasks",children:t.jsx(Fr,{})}),F&&S&&t.jsx("button",{className:"btn btn-icon btn-sm",onClick:S,title:j?"Expand archived tasks":"Collapse archived tasks","aria-label":j?"Expand archived tasks":"Collapse archived tasks",children:j?t.jsx(vn,{size:16}):t.jsx(mi,{size:16})}),Fe&&t.jsxs("div",{className:"column-menu",ref:Z,children:[t.jsx("button",{type:"button",className:"btn btn-icon btn-sm",onClick:()=>de(De=>!De),"aria-haspopup":"menu","aria-expanded":W,"aria-label":`${ds[e]} column actions`,title:"Column actions",disabled:mt,children:t.jsx(Nw,{})}),W&&t.jsxs("div",{className:"column-menu-popover",role:"menu",children:[e==="todo"&&t.jsxs("button",{type:"button",role:"menuitem",className:"column-menu-item",onClick:()=>void Ke(),disabled:n.length===0||me,children:["Replan All",t.jsxs("span",{className:"column-menu-item-hint",children:["Move ",n.length," task",n.length===1?"":"s"," to Planning"]})]}),(e==="in-progress"||e==="in-review")&&t.jsxs(t.Fragment,{children:[t.jsxs("button",{type:"button",role:"menuitem",className:"column-menu-item",onClick:()=>void We(),disabled:Te===0||ve||!o,children:["Stop All",t.jsx("span",{className:"column-menu-item-hint",children:n.length===0?"No tasks in this column":Te===0?"No manually pausable tasks":`Pause ${Te} active unassigned task${Te===1?"":"s"}`})]}),t.jsxs("button",{type:"button",role:"menuitem",className:"column-menu-item",onClick:()=>void he(),disabled:n.length===0||ie,children:["Move All to Todo",t.jsxs("span",{className:"column-menu-item-hint",children:["Move ",n.length," task",n.length===1?"":"s"," to Todo"]})]})]})]})]})]}),!X&&t.jsx("p",{className:"column-desc",children:Kj[e]}),!X&&t.jsxs("div",{className:"column-body",children:[e==="triage"&&d&&t.jsx(lx,{onCreate:d,addToast:c,tasks:C??[],availableModels:x,onPlanningMode:k,onSubtaskBreakdown:R,projectId:s,autoExpand:!1,favoriteProviders:E,favoriteModels:_,onToggleFavorite:G,onToggleModelFavorite:H}),e==="in-progress"?se.length===0?t.jsx("div",{className:"empty-column",children:"No tasks"}):se.map(De=>t.jsx(ox,{label:De.label,activeTasks:De.activeTasks,queuedTasks:De.queuedTasks,projectId:s,onOpenDetail:l,addToast:c,globalPaused:f,onUpdateTask:p,onRetryTask:g,onOpenDetailWithTab:O,taskStuckTimeoutMs:P,onOpenMission:q,lastFetchTimeMs:Y,workflowStepNameLookup:ge,blockerFanoutMap:L},De.label)):n.length===0?t.jsx("div",{className:"empty-column",children:"No tasks"}):t.jsxs(t.Fragment,{children:[Ve.map(De=>t.jsx(Oo,{task:De,projectId:s,onOpenDetail:l,addToast:c,globalPaused:f,onUpdateTask:p,onRetryTask:g,onArchiveTask:w,onUnarchiveTask:v,onDeleteTask:b,onOpenDetailWithTab:O,taskStuckTimeoutMs:P,onOpenMission:q,onMoveTask:r,lastFetchTimeMs:Y,workflowStepNameLookup:ge,fanout:L?.get(De.id)},De.id)),re&&Le>0&&t.jsxs("button",{type:"button",className:"btn btn-secondary btn-sm",onClick:ct,children:["Load ",Math.min(ep,Le)," more (",Le," remaining)"]})]}),t.jsx(pa,{slotId:"board-column-footer",projectId:s})]})]})}const cx=i.memo(l_);cx.displayName="Column";const c_=new Set(["in-progress","in-review"]),d_=new Set(["triage","todo","in-progress","in-review"]);function u_(e,n){return!e||e.column==="done"||e.column==="archived"||e.column==="in-review"&&e.paused===!0||e.column==="in-review"&&e.status==="failed"&&(e.mergeRetries??0)>=n}function m_(e,n){const s=Date.parse(e.columnMovedAt??e.updatedAt);return Number.isFinite(s)?Math.max(0,n-s):0}function h_(e,n,s={}){const a=s.nowMs??Date.now(),r=s.highFanoutTodoThreshold??Ju,o=s.staleHighFanoutAgeThresholdMs??kb,l=new Map(e.map(h=>[h.id,h])),c=new Map,d=h=>{let m=c.get(h);return m||(m={dependentIds:[],blockedByDependentIds:[],activeCount:0,activeTodoCount:0},c.set(h,m)),m};for(const h of e){const m=d_.has(h.column),f=h.column==="todo";for(const p of h.dependencies??[]){if(!p)continue;const g=d(p);g.dependentIds.push(h.id),m&&(g.activeCount+=1),f&&(g.activeTodoCount+=1)}if(h.blockedBy){const p=d(h.blockedBy);p.dependentIds.push(h.id),p.blockedByDependentIds.push(h.id),m&&(p.activeCount+=1),f&&(p.activeTodoCount+=1)}}const u=new Map;for(const[h,m]of c){const f=l.get(h),p=u_(f,n)?[...m.blockedByDependentIds]:[],g=m.activeTodoCount>=r,w=f?m_(f,a):0,v=f?.column,b=v!==void 0&&g&&c_.has(v)&&w>=o;u.set(h,{totalCount:m.activeCount,activeTodoCount:m.activeTodoCount,dependentIds:m.dependentIds,staleBlockedByDependentIds:p,isHighFanout:g,escalation:b?{blockerId:h,activeTodoCount:m.activeTodoCount,totalActiveCount:m.activeCount,blockingAgeMs:w}:void 0})}return u}const p_=3;function rm(e,n={}){return h_(e,p_,{staleHighFanoutAgeThresholdMs:n.staleHighFanoutAgeThresholdMs})}function f_(e,n={}){return i.useMemo(()=>rm(e,n),[e,n.staleHighFanoutAgeThresholdMs])}function g_(e,n){return e.length!==n.length?!1:e.every((s,a)=>s===n[a])}const tp=new Map;function b_(e,n){if(e.size!==n.size)return!1;for(const[s,a]of e)if(n.get(s)!==a)return!1;return!0}function x_({tasks:e,projectId:n,maxConcurrent:s,onMoveTask:a,onPauseTask:r,onOpenDetail:o,addToast:l,onQuickCreate:c,onNewTask:d,autoMerge:u,onToggleAutoMerge:h,globalPaused:m,onUpdateTask:f,onRetryTask:p,onArchiveTask:g,onUnarchiveTask:w,onDeleteTask:v,onArchiveAllDone:b,onLoadArchivedTasks:y,searchQuery:j="",availableModels:S,onPlanningMode:C,onSubtaskBreakdown:x,onOpenDetailWithTab:k,favoriteProviders:R,favoriteModels:O,onToggleFavorite:E,onToggleModelFavorite:_,taskStuckTimeoutMs:G,onOpenMission:H,staleHighFanoutBlockerAgeThresholdMs:A,lastFetchTimeMs:P}){const[q,Y]=i.useState(!0),ge=i.useRef(!1),[L,M]=i.useState(tp),$=f_(e,{staleHighFanoutAgeThresholdMs:A}),D=j.trim()!=="",N=i.useRef({triage:[],todo:[],"in-progress":[],"in-review":[],done:[],archived:[]}),W=i.useCallback(()=>{Y(me=>{const Ne=!me;return!Ne&&!ge.current&&y&&(ge.current=!0,y()),Ne})},[y]),de=i.useMemo(()=>{const me={triage:[],todo:[],"in-progress":[],"in-review":[],done:[],archived:[]};for(const Me of e){const ie=Ku(Me.column)?Me.column:Yl;(me[ie]??me[Yl]).push(Me)}const Ne=N.current,ve={};for(const Me of ha){const ie=Kb(me[Me],Me);ve[Me]=g_(Ne[Me],ie)?Ne[Me]:ie}return N.current=ve,ve},[e]);return i.useEffect(()=>{let me=!1;return Jo(n).then(Ne=>{if(me)return;const ve=new Map(Ne.map(Me=>[Me.id,Me.name]));M(Me=>b_(Me,ve)?Me:ve)}).catch(()=>{me||M(Ne=>Ne.size===0?Ne:tp)}),()=>{me=!0}},[n]),t.jsx(t.Fragment,{children:t.jsx("main",{className:"board",id:"board",children:ha.map(me=>t.jsx(cx,{column:me,tasks:de[me],projectId:n,maxConcurrent:s,onMoveTask:a,onPauseTask:r,onOpenDetail:o,addToast:l,globalPaused:m,onUpdateTask:f,onRetryTask:p,onArchiveTask:g,onUnarchiveTask:w,onDeleteTask:v,allTasks:e,availableModels:S,onOpenDetailWithTab:k,favoriteProviders:R,favoriteModels:O,onToggleFavorite:E,onToggleModelFavorite:_,isSearchActive:D,taskStuckTimeoutMs:G,onOpenMission:H,lastFetchTimeMs:P,workflowStepNameLookup:L,blockerFanoutMap:$,...me==="triage"?{onQuickCreate:c,onNewTask:d,onPlanningMode:C,onSubtaskBreakdown:x}:{},...me==="in-review"?{autoMerge:u,onToggleAutoMerge:h}:{},...me==="done"?{onArchiveAllDone:b}:{},...me==="archived"?{collapsed:q,onToggleCollapse:W}:{}},me))})})}function Oi(e,n,s){i.useEffect(()=>{if(!n)return;const a=e.current;if(!a)return;if(typeof window<"u"&&("ontouchstart"in window||navigator.maxTouchPoints>0)&&window.innerWidth<=768){a.style.removeProperty("width"),a.style.removeProperty("height");return}try{const u=localStorage.getItem(s);if(u){const{width:h,height:m}=JSON.parse(u);typeof h=="number"&&h>0&&(a.style.width=`${h}px`),typeof m=="number"&&m>0&&(a.style.height=`${m}px`)}}catch{}if(typeof ResizeObserver>"u")return;let o=a.offsetWidth,l=a.offsetHeight,c=null;const d=new ResizeObserver(()=>{const u=a.offsetWidth,h=a.offsetHeight;u===o&&h===l||(o=u,l=h,c&&clearTimeout(c),c=setTimeout(()=>{try{localStorage.setItem(s,JSON.stringify({width:u,height:h}))}catch{}},200))});return d.observe(a),()=>{d.disconnect(),c&&clearTimeout(c)}},[e,n,s])}function v_(){if(typeof window>"u")return!1;const e="ontouchstart"in window||navigator.maxTouchPoints>0,n=window.innerWidth<=768;return e&&n}let jr=0,Ao=null;function y_(){if(typeof window>"u")return;if(jr>0){jr+=1;return}const e=document.documentElement,n=document.body;Ao={htmlOverflow:e.style.overflow,bodyPosition:n.style.position,bodyTop:n.style.top,bodyLeft:n.style.left,bodyRight:n.style.right,bodyWidth:n.style.width,bodyOverflow:n.style.overflow,scrollY:window.scrollY},e.style.overflow="hidden",n.style.position="fixed",n.style.top=`-${Ao.scrollY}px`,n.style.left="0",n.style.right="0",n.style.width="100%",n.style.overflow="hidden",jr=1}function w_(){if(typeof window>"u"||jr===0||(jr-=1,jr>0||!Ao))return;const e=document.documentElement,n=document.body,{htmlOverflow:s,bodyPosition:a,bodyTop:r,bodyLeft:o,bodyRight:l,bodyWidth:c,bodyOverflow:d,scrollY:u}=Ao;e.style.overflow=s,n.style.position=a,n.style.top=r,n.style.left=o,n.style.right=l,n.style.width=c,n.style.overflow=d,Ao=null,window.scrollTo(0,0)}function Si(e){i.useEffect(()=>{if(!(!e||!v_()))return y_(),()=>{w_()}},[e])}function Xi(e){const n=i.useRef(!1),s=i.useCallback(r=>{n.current=r.target===r.currentTarget},[]),a=i.useCallback(r=>{const o=n.current&&r.target===r.currentTarget;n.current=!1,o&&e()},[e]);return{onMouseDown:s,onMouseUp:a}}function k_(e,n){const s={};return(e[e.length-1]===""?[...e,""]:e).join((s.padRight?" ":"")+","+(s.padLeft===!1?"":" ")).trim()}const j_=/^[$_\p{ID_Start}][$_\u{200C}\u{200D}\p{ID_Continue}]*$/u,N_=/^[$_\p{ID_Start}][-$_\u{200C}\u{200D}\p{ID_Continue}]*$/u,S_={};function np(e,n){return(S_.jsx?N_:j_).test(e)}const C_=/[ \t\n\f\r]/g;function E_(e){return typeof e=="object"?e.type==="text"?sp(e.value):!1:sp(e)}function sp(e){return e.replace(C_,"")===""}class el{constructor(n,s,a){this.normal=s,this.property=n,a&&(this.space=a)}}el.prototype.normal={};el.prototype.property={};el.prototype.space=void 0;function dx(e,n){const s={},a={};for(const r of e)Object.assign(s,r.property),Object.assign(a,r.normal);return new el(s,a,n)}function yu(e){return e.toLowerCase()}class Ks{constructor(n,s){this.attribute=s,this.property=n}}Ks.prototype.attribute="";Ks.prototype.booleanish=!1;Ks.prototype.boolean=!1;Ks.prototype.commaOrSpaceSeparated=!1;Ks.prototype.commaSeparated=!1;Ks.prototype.defined=!1;Ks.prototype.mustUseProperty=!1;Ks.prototype.number=!1;Ks.prototype.overloadedBoolean=!1;Ks.prototype.property="";Ks.prototype.spaceSeparated=!1;Ks.prototype.space=void 0;let __=0;const yn=Ja(),fs=Ja(),wu=Ja(),_t=Ja(),Qn=Ja(),Nr=Ja(),Ys=Ja();function Ja(){return 2**++__}const ku=Object.freeze(Object.defineProperty({__proto__:null,boolean:yn,booleanish:fs,commaOrSpaceSeparated:Ys,commaSeparated:Nr,number:_t,overloadedBoolean:wu,spaceSeparated:Qn},Symbol.toStringTag,{value:"Module"})),cd=Object.keys(ku);class om extends Ks{constructor(n,s,a,r){let o=-1;if(super(n,s),ip(this,"space",r),typeof a=="number")for(;++o<cd.length;){const l=cd[o];ip(this,cd[o],(a&ku[l])===ku[l])}}}om.prototype.defined=!0;function ip(e,n,s){s&&(e[n]=s)}function Vr(e){const n={},s={};for(const[a,r]of Object.entries(e.properties)){const o=new om(a,e.transform(e.attributes||{},a),r,e.space);e.mustUseProperty&&e.mustUseProperty.includes(a)&&(o.mustUseProperty=!0),n[a]=o,s[yu(a)]=a,s[yu(o.attribute)]=a}return new el(n,s,e.space)}const ux=Vr({properties:{ariaActiveDescendant:null,ariaAtomic:fs,ariaAutoComplete:null,ariaBusy:fs,ariaChecked:fs,ariaColCount:_t,ariaColIndex:_t,ariaColSpan:_t,ariaControls:Qn,ariaCurrent:null,ariaDescribedBy:Qn,ariaDetails:null,ariaDisabled:fs,ariaDropEffect:Qn,ariaErrorMessage:null,ariaExpanded:fs,ariaFlowTo:Qn,ariaGrabbed:fs,ariaHasPopup:null,ariaHidden:fs,ariaInvalid:null,ariaKeyShortcuts:null,ariaLabel:null,ariaLabelledBy:Qn,ariaLevel:_t,ariaLive:null,ariaModal:fs,ariaMultiLine:fs,ariaMultiSelectable:fs,ariaOrientation:null,ariaOwns:Qn,ariaPlaceholder:null,ariaPosInSet:_t,ariaPressed:fs,ariaReadOnly:fs,ariaRelevant:null,ariaRequired:fs,ariaRoleDescription:Qn,ariaRowCount:_t,ariaRowIndex:_t,ariaRowSpan:_t,ariaSelected:fs,ariaSetSize:_t,ariaSort:null,ariaValueMax:_t,ariaValueMin:_t,ariaValueNow:_t,ariaValueText:null,role:null},transform(e,n){return n==="role"?n:"aria-"+n.slice(4).toLowerCase()}});function mx(e,n){return n in e?e[n]:n}function hx(e,n){return mx(e,n.toLowerCase())}const M_=Vr({attributes:{acceptcharset:"accept-charset",classname:"class",htmlfor:"for",httpequiv:"http-equiv"},mustUseProperty:["checked","multiple","muted","selected"],properties:{abbr:null,accept:Nr,acceptCharset:Qn,accessKey:Qn,action:null,allow:null,allowFullScreen:yn,allowPaymentRequest:yn,allowUserMedia:yn,alt:null,as:null,async:yn,autoCapitalize:null,autoComplete:Qn,autoFocus:yn,autoPlay:yn,blocking:Qn,capture:null,charSet:null,checked:yn,cite:null,className:Qn,cols:_t,colSpan:null,content:null,contentEditable:fs,controls:yn,controlsList:Qn,coords:_t|Nr,crossOrigin:null,data:null,dateTime:null,decoding:null,default:yn,defer:yn,dir:null,dirName:null,disabled:yn,download:wu,draggable:fs,encType:null,enterKeyHint:null,fetchPriority:null,form:null,formAction:null,formEncType:null,formMethod:null,formNoValidate:yn,formTarget:null,headers:Qn,height:_t,hidden:wu,high:_t,href:null,hrefLang:null,htmlFor:Qn,httpEquiv:Qn,id:null,imageSizes:null,imageSrcSet:null,inert:yn,inputMode:null,integrity:null,is:null,isMap:yn,itemId:null,itemProp:Qn,itemRef:Qn,itemScope:yn,itemType:Qn,kind:null,label:null,lang:null,language:null,list:null,loading:null,loop:yn,low:_t,manifest:null,max:null,maxLength:_t,media:null,method:null,min:null,minLength:_t,multiple:yn,muted:yn,name:null,nonce:null,noModule:yn,noValidate:yn,onAbort:null,onAfterPrint:null,onAuxClick:null,onBeforeMatch:null,onBeforePrint:null,onBeforeToggle:null,onBeforeUnload:null,onBlur:null,onCancel:null,onCanPlay:null,onCanPlayThrough:null,onChange:null,onClick:null,onClose:null,onContextLost:null,onContextMenu:null,onContextRestored:null,onCopy:null,onCueChange:null,onCut:null,onDblClick:null,onDrag:null,onDragEnd:null,onDragEnter:null,onDragExit:null,onDragLeave:null,onDragOver:null,onDragStart:null,onDrop:null,onDurationChange:null,onEmptied:null,onEnded:null,onError:null,onFocus:null,onFormData:null,onHashChange:null,onInput:null,onInvalid:null,onKeyDown:null,onKeyPress:null,onKeyUp:null,onLanguageChange:null,onLoad:null,onLoadedData:null,onLoadedMetadata:null,onLoadEnd:null,onLoadStart:null,onMessage:null,onMessageError:null,onMouseDown:null,onMouseEnter:null,onMouseLeave:null,onMouseMove:null,onMouseOut:null,onMouseOver:null,onMouseUp:null,onOffline:null,onOnline:null,onPageHide:null,onPageShow:null,onPaste:null,onPause:null,onPlay:null,onPlaying:null,onPopState:null,onProgress:null,onRateChange:null,onRejectionHandled:null,onReset:null,onResize:null,onScroll:null,onScrollEnd:null,onSecurityPolicyViolation:null,onSeeked:null,onSeeking:null,onSelect:null,onSlotChange:null,onStalled:null,onStorage:null,onSubmit:null,onSuspend:null,onTimeUpdate:null,onToggle:null,onUnhandledRejection:null,onUnload:null,onVolumeChange:null,onWaiting:null,onWheel:null,open:yn,optimum:_t,pattern:null,ping:Qn,placeholder:null,playsInline:yn,popover:null,popoverTarget:null,popoverTargetAction:null,poster:null,preload:null,readOnly:yn,referrerPolicy:null,rel:Qn,required:yn,reversed:yn,rows:_t,rowSpan:_t,sandbox:Qn,scope:null,scoped:yn,seamless:yn,selected:yn,shadowRootClonable:yn,shadowRootDelegatesFocus:yn,shadowRootMode:null,shape:null,size:_t,sizes:null,slot:null,span:_t,spellCheck:fs,src:null,srcDoc:null,srcLang:null,srcSet:null,start:_t,step:null,style:null,tabIndex:_t,target:null,title:null,translate:null,type:null,typeMustMatch:yn,useMap:null,value:fs,width:_t,wrap:null,writingSuggestions:null,align:null,aLink:null,archive:Qn,axis:null,background:null,bgColor:null,border:_t,borderColor:null,bottomMargin:_t,cellPadding:null,cellSpacing:null,char:null,charOff:null,classId:null,clear:null,code:null,codeBase:null,codeType:null,color:null,compact:yn,declare:yn,event:null,face:null,frame:null,frameBorder:null,hSpace:_t,leftMargin:_t,link:null,longDesc:null,lowSrc:null,marginHeight:_t,marginWidth:_t,noResize:yn,noHref:yn,noShade:yn,noWrap:yn,object:null,profile:null,prompt:null,rev:null,rightMargin:_t,rules:null,scheme:null,scrolling:fs,standby:null,summary:null,text:null,topMargin:_t,valueType:null,version:null,vAlign:null,vLink:null,vSpace:_t,allowTransparency:null,autoCorrect:null,autoSave:null,disablePictureInPicture:yn,disableRemotePlayback:yn,prefix:null,property:null,results:_t,security:null,unselectable:null},space:"html",transform:hx}),A_=Vr({attributes:{accentHeight:"accent-height",alignmentBaseline:"alignment-baseline",arabicForm:"arabic-form",baselineShift:"baseline-shift",capHeight:"cap-height",className:"class",clipPath:"clip-path",clipRule:"clip-rule",colorInterpolation:"color-interpolation",colorInterpolationFilters:"color-interpolation-filters",colorProfile:"color-profile",colorRendering:"color-rendering",crossOrigin:"crossorigin",dataType:"datatype",dominantBaseline:"dominant-baseline",enableBackground:"enable-background",fillOpacity:"fill-opacity",fillRule:"fill-rule",floodColor:"flood-color",floodOpacity:"flood-opacity",fontFamily:"font-family",fontSize:"font-size",fontSizeAdjust:"font-size-adjust",fontStretch:"font-stretch",fontStyle:"font-style",fontVariant:"font-variant",fontWeight:"font-weight",glyphName:"glyph-name",glyphOrientationHorizontal:"glyph-orientation-horizontal",glyphOrientationVertical:"glyph-orientation-vertical",hrefLang:"hreflang",horizAdvX:"horiz-adv-x",horizOriginX:"horiz-origin-x",horizOriginY:"horiz-origin-y",imageRendering:"image-rendering",letterSpacing:"letter-spacing",lightingColor:"lighting-color",markerEnd:"marker-end",markerMid:"marker-mid",markerStart:"marker-start",navDown:"nav-down",navDownLeft:"nav-down-left",navDownRight:"nav-down-right",navLeft:"nav-left",navNext:"nav-next",navPrev:"nav-prev",navRight:"nav-right",navUp:"nav-up",navUpLeft:"nav-up-left",navUpRight:"nav-up-right",onAbort:"onabort",onActivate:"onactivate",onAfterPrint:"onafterprint",onBeforePrint:"onbeforeprint",onBegin:"onbegin",onCancel:"oncancel",onCanPlay:"oncanplay",onCanPlayThrough:"oncanplaythrough",onChange:"onchange",onClick:"onclick",onClose:"onclose",onCopy:"oncopy",onCueChange:"oncuechange",onCut:"oncut",onDblClick:"ondblclick",onDrag:"ondrag",onDragEnd:"ondragend",onDragEnter:"ondragenter",onDragExit:"ondragexit",onDragLeave:"ondragleave",onDragOver:"ondragover",onDragStart:"ondragstart",onDrop:"ondrop",onDurationChange:"ondurationchange",onEmptied:"onemptied",onEnd:"onend",onEnded:"onended",onError:"onerror",onFocus:"onfocus",onFocusIn:"onfocusin",onFocusOut:"onfocusout",onHashChange:"onhashchange",onInput:"oninput",onInvalid:"oninvalid",onKeyDown:"onkeydown",onKeyPress:"onkeypress",onKeyUp:"onkeyup",onLoad:"onload",onLoadedData:"onloadeddata",onLoadedMetadata:"onloadedmetadata",onLoadStart:"onloadstart",onMessage:"onmessage",onMouseDown:"onmousedown",onMouseEnter:"onmouseenter",onMouseLeave:"onmouseleave",onMouseMove:"onmousemove",onMouseOut:"onmouseout",onMouseOver:"onmouseover",onMouseUp:"onmouseup",onMouseWheel:"onmousewheel",onOffline:"onoffline",onOnline:"ononline",onPageHide:"onpagehide",onPageShow:"onpageshow",onPaste:"onpaste",onPause:"onpause",onPlay:"onplay",onPlaying:"onplaying",onPopState:"onpopstate",onProgress:"onprogress",onRateChange:"onratechange",onRepeat:"onrepeat",onReset:"onreset",onResize:"onresize",onScroll:"onscroll",onSeeked:"onseeked",onSeeking:"onseeking",onSelect:"onselect",onShow:"onshow",onStalled:"onstalled",onStorage:"onstorage",onSubmit:"onsubmit",onSuspend:"onsuspend",onTimeUpdate:"ontimeupdate",onToggle:"ontoggle",onUnload:"onunload",onVolumeChange:"onvolumechange",onWaiting:"onwaiting",onZoom:"onzoom",overlinePosition:"overline-position",overlineThickness:"overline-thickness",paintOrder:"paint-order",panose1:"panose-1",pointerEvents:"pointer-events",referrerPolicy:"referrerpolicy",renderingIntent:"rendering-intent",shapeRendering:"shape-rendering",stopColor:"stop-color",stopOpacity:"stop-opacity",strikethroughPosition:"strikethrough-position",strikethroughThickness:"strikethrough-thickness",strokeDashArray:"stroke-dasharray",strokeDashOffset:"stroke-dashoffset",strokeLineCap:"stroke-linecap",strokeLineJoin:"stroke-linejoin",strokeMiterLimit:"stroke-miterlimit",strokeOpacity:"stroke-opacity",strokeWidth:"stroke-width",tabIndex:"tabindex",textAnchor:"text-anchor",textDecoration:"text-decoration",textRendering:"text-rendering",transformOrigin:"transform-origin",typeOf:"typeof",underlinePosition:"underline-position",underlineThickness:"underline-thickness",unicodeBidi:"unicode-bidi",unicodeRange:"unicode-range",unitsPerEm:"units-per-em",vAlphabetic:"v-alphabetic",vHanging:"v-hanging",vIdeographic:"v-ideographic",vMathematical:"v-mathematical",vectorEffect:"vector-effect",vertAdvY:"vert-adv-y",vertOriginX:"vert-origin-x",vertOriginY:"vert-origin-y",wordSpacing:"word-spacing",writingMode:"writing-mode",xHeight:"x-height",playbackOrder:"playbackorder",timelineBegin:"timelinebegin"},properties:{about:Ys,accentHeight:_t,accumulate:null,additive:null,alignmentBaseline:null,alphabetic:_t,amplitude:_t,arabicForm:null,ascent:_t,attributeName:null,attributeType:null,azimuth:_t,bandwidth:null,baselineShift:null,baseFrequency:null,baseProfile:null,bbox:null,begin:null,bias:_t,by:null,calcMode:null,capHeight:_t,className:Qn,clip:null,clipPath:null,clipPathUnits:null,clipRule:null,color:null,colorInterpolation:null,colorInterpolationFilters:null,colorProfile:null,colorRendering:null,content:null,contentScriptType:null,contentStyleType:null,crossOrigin:null,cursor:null,cx:null,cy:null,d:null,dataType:null,defaultAction:null,descent:_t,diffuseConstant:_t,direction:null,display:null,dur:null,divisor:_t,dominantBaseline:null,download:yn,dx:null,dy:null,edgeMode:null,editable:null,elevation:_t,enableBackground:null,end:null,event:null,exponent:_t,externalResourcesRequired:null,fill:null,fillOpacity:_t,fillRule:null,filter:null,filterRes:null,filterUnits:null,floodColor:null,floodOpacity:null,focusable:null,focusHighlight:null,fontFamily:null,fontSize:null,fontSizeAdjust:null,fontStretch:null,fontStyle:null,fontVariant:null,fontWeight:null,format:null,fr:null,from:null,fx:null,fy:null,g1:Nr,g2:Nr,glyphName:Nr,glyphOrientationHorizontal:null,glyphOrientationVertical:null,glyphRef:null,gradientTransform:null,gradientUnits:null,handler:null,hanging:_t,hatchContentUnits:null,hatchUnits:null,height:null,href:null,hrefLang:null,horizAdvX:_t,horizOriginX:_t,horizOriginY:_t,id:null,ideographic:_t,imageRendering:null,initialVisibility:null,in:null,in2:null,intercept:_t,k:_t,k1:_t,k2:_t,k3:_t,k4:_t,kernelMatrix:Ys,kernelUnitLength:null,keyPoints:null,keySplines:null,keyTimes:null,kerning:null,lang:null,lengthAdjust:null,letterSpacing:null,lightingColor:null,limitingConeAngle:_t,local:null,markerEnd:null,markerMid:null,markerStart:null,markerHeight:null,markerUnits:null,markerWidth:null,mask:null,maskContentUnits:null,maskUnits:null,mathematical:null,max:null,media:null,mediaCharacterEncoding:null,mediaContentEncodings:null,mediaSize:_t,mediaTime:null,method:null,min:null,mode:null,name:null,navDown:null,navDownLeft:null,navDownRight:null,navLeft:null,navNext:null,navPrev:null,navRight:null,navUp:null,navUpLeft:null,navUpRight:null,numOctaves:null,observer:null,offset:null,onAbort:null,onActivate:null,onAfterPrint:null,onBeforePrint:null,onBegin:null,onCancel:null,onCanPlay:null,onCanPlayThrough:null,onChange:null,onClick:null,onClose:null,onCopy:null,onCueChange:null,onCut:null,onDblClick:null,onDrag:null,onDragEnd:null,onDragEnter:null,onDragExit:null,onDragLeave:null,onDragOver:null,onDragStart:null,onDrop:null,onDurationChange:null,onEmptied:null,onEnd:null,onEnded:null,onError:null,onFocus:null,onFocusIn:null,onFocusOut:null,onHashChange:null,onInput:null,onInvalid:null,onKeyDown:null,onKeyPress:null,onKeyUp:null,onLoad:null,onLoadedData:null,onLoadedMetadata:null,onLoadStart:null,onMessage:null,onMouseDown:null,onMouseEnter:null,onMouseLeave:null,onMouseMove:null,onMouseOut:null,onMouseOver:null,onMouseUp:null,onMouseWheel:null,onOffline:null,onOnline:null,onPageHide:null,onPageShow:null,onPaste:null,onPause:null,onPlay:null,onPlaying:null,onPopState:null,onProgress:null,onRateChange:null,onRepeat:null,onReset:null,onResize:null,onScroll:null,onSeeked:null,onSeeking:null,onSelect:null,onShow:null,onStalled:null,onStorage:null,onSubmit:null,onSuspend:null,onTimeUpdate:null,onToggle:null,onUnload:null,onVolumeChange:null,onWaiting:null,onZoom:null,opacity:null,operator:null,order:null,orient:null,orientation:null,origin:null,overflow:null,overlay:null,overlinePosition:_t,overlineThickness:_t,paintOrder:null,panose1:null,path:null,pathLength:_t,patternContentUnits:null,patternTransform:null,patternUnits:null,phase:null,ping:Qn,pitch:null,playbackOrder:null,pointerEvents:null,points:null,pointsAtX:_t,pointsAtY:_t,pointsAtZ:_t,preserveAlpha:null,preserveAspectRatio:null,primitiveUnits:null,propagate:null,property:Ys,r:null,radius:null,referrerPolicy:null,refX:null,refY:null,rel:Ys,rev:Ys,renderingIntent:null,repeatCount:null,repeatDur:null,requiredExtensions:Ys,requiredFeatures:Ys,requiredFonts:Ys,requiredFormats:Ys,resource:null,restart:null,result:null,rotate:null,rx:null,ry:null,scale:null,seed:null,shapeRendering:null,side:null,slope:null,snapshotTime:null,specularConstant:_t,specularExponent:_t,spreadMethod:null,spacing:null,startOffset:null,stdDeviation:null,stemh:null,stemv:null,stitchTiles:null,stopColor:null,stopOpacity:null,strikethroughPosition:_t,strikethroughThickness:_t,string:null,stroke:null,strokeDashArray:Ys,strokeDashOffset:null,strokeLineCap:null,strokeLineJoin:null,strokeMiterLimit:_t,strokeOpacity:_t,strokeWidth:null,style:null,surfaceScale:_t,syncBehavior:null,syncBehaviorDefault:null,syncMaster:null,syncTolerance:null,syncToleranceDefault:null,systemLanguage:Ys,tabIndex:_t,tableValues:null,target:null,targetX:_t,targetY:_t,textAnchor:null,textDecoration:null,textRendering:null,textLength:null,timelineBegin:null,title:null,transformBehavior:null,type:null,typeOf:Ys,to:null,transform:null,transformOrigin:null,u1:null,u2:null,underlinePosition:_t,underlineThickness:_t,unicode:null,unicodeBidi:null,unicodeRange:null,unitsPerEm:_t,values:null,vAlphabetic:_t,vMathematical:_t,vectorEffect:null,vHanging:_t,vIdeographic:_t,version:null,vertAdvY:_t,vertOriginX:_t,vertOriginY:_t,viewBox:null,viewTarget:null,visibility:null,width:null,widths:null,wordSpacing:null,writingMode:null,x:null,x1:null,x2:null,xChannelSelector:null,xHeight:_t,y:null,y1:null,y2:null,yChannelSelector:null,z:null,zoomAndPan:null},space:"svg",transform:mx}),px=Vr({properties:{xLinkActuate:null,xLinkArcRole:null,xLinkHref:null,xLinkRole:null,xLinkShow:null,xLinkTitle:null,xLinkType:null},space:"xlink",transform(e,n){return"xlink:"+n.slice(5).toLowerCase()}}),fx=Vr({attributes:{xmlnsxlink:"xmlns:xlink"},properties:{xmlnsXLink:null,xmlns:null},space:"xmlns",transform:hx}),gx=Vr({properties:{xmlBase:null,xmlLang:null,xmlSpace:null},space:"xml",transform(e,n){return"xml:"+n.slice(3).toLowerCase()}}),R_={classId:"classID",dataType:"datatype",itemId:"itemID",strokeDashArray:"strokeDasharray",strokeDashOffset:"strokeDashoffset",strokeLineCap:"strokeLinecap",strokeLineJoin:"strokeLinejoin",strokeMiterLimit:"strokeMiterlimit",typeOf:"typeof",xLinkActuate:"xlinkActuate",xLinkArcRole:"xlinkArcrole",xLinkHref:"xlinkHref",xLinkRole:"xlinkRole",xLinkShow:"xlinkShow",xLinkTitle:"xlinkTitle",xLinkType:"xlinkType",xmlnsXLink:"xmlnsXlink"},I_=/[A-Z]/g,ap=/-[a-z]/g,T_=/^data[-\w.:]+$/i;function P_(e,n){const s=yu(n);let a=n,r=Ks;if(s in e.normal)return e.property[e.normal[s]];if(s.length>4&&s.slice(0,4)==="data"&&T_.test(n)){if(n.charAt(4)==="-"){const o=n.slice(5).replace(ap,D_);a="data"+o.charAt(0).toUpperCase()+o.slice(1)}else{const o=n.slice(4);if(!ap.test(o)){let l=o.replace(I_,$_);l.charAt(0)!=="-"&&(l="-"+l),n="data"+l}}r=om}return new r(a,n)}function $_(e){return"-"+e.toLowerCase()}function D_(e){return e.charAt(1).toUpperCase()}const L_=dx([ux,M_,px,fx,gx],"html"),lm=dx([ux,A_,px,fx,gx],"svg");function O_(e){return e.join(" ").trim()}var ur={},dd,rp;function F_(){if(rp)return dd;rp=1;var e=/\/\*[^*]*\*+([^/*][^*]*\*+)*\//g,n=/\n/g,s=/^\s*/,a=/^(\*?[-#/*\\\w]+(\[[0-9a-z_-]+\])?)\s*/,r=/^:\s*/,o=/^((?:'(?:\\'|.)*?'|"(?:\\"|.)*?"|\([^)]*?\)|[^};])+)/,l=/^[;\s]*/,c=/^\s+|\s+$/g,d=`
654
- `,u="/",h="*",m="",f="comment",p="declaration";function g(v,b){if(typeof v!="string")throw new TypeError("First argument must be a string");if(!v)return[];b=b||{};var y=1,j=1;function S(A){var P=A.match(n);P&&(y+=P.length);var q=A.lastIndexOf(d);j=~q?A.length-q:j+A.length}function C(){var A={line:y,column:j};return function(P){return P.position=new x(A),O(),P}}function x(A){this.start=A,this.end={line:y,column:j},this.source=b.source}x.prototype.content=v;function k(A){var P=new Error(b.source+":"+y+":"+j+": "+A);if(P.reason=A,P.filename=b.source,P.line=y,P.column=j,P.source=v,!b.silent)throw P}function R(A){var P=A.exec(v);if(P){var q=P[0];return S(q),v=v.slice(q.length),P}}function O(){R(s)}function E(A){var P;for(A=A||[];P=_();)P!==!1&&A.push(P);return A}function _(){var A=C();if(!(u!=v.charAt(0)||h!=v.charAt(1))){for(var P=2;m!=v.charAt(P)&&(h!=v.charAt(P)||u!=v.charAt(P+1));)++P;if(P+=2,m===v.charAt(P-1))return k("End of comment missing");var q=v.slice(2,P-2);return j+=2,S(q),v=v.slice(P),j+=2,A({type:f,comment:q})}}function G(){var A=C(),P=R(a);if(P){if(_(),!R(r))return k("property missing ':'");var q=R(o),Y=A({type:p,property:w(P[0].replace(e,m)),value:q?w(q[0].replace(e,m)):m});return R(l),Y}}function H(){var A=[];E(A);for(var P;P=G();)P!==!1&&(A.push(P),E(A));return A}return O(),H()}function w(v){return v?v.replace(c,m):m}return dd=g,dd}var op;function z_(){if(op)return ur;op=1;var e=ur&&ur.__importDefault||function(a){return a&&a.__esModule?a:{default:a}};Object.defineProperty(ur,"__esModule",{value:!0}),ur.default=s;const n=e(F_());function s(a,r){let o=null;if(!a||typeof a!="string")return o;const l=(0,n.default)(a),c=typeof r=="function";return l.forEach(d=>{if(d.type!=="declaration")return;const{property:u,value:h}=d;c?r(u,h,d):h&&(o=o||{},o[u]=h)}),o}return ur}var io={},lp;function B_(){if(lp)return io;lp=1,Object.defineProperty(io,"__esModule",{value:!0}),io.camelCase=void 0;var e=/^--[a-zA-Z0-9_-]+$/,n=/-([a-z])/g,s=/^[^-]+$/,a=/^-(webkit|moz|ms|o|khtml)-/,r=/^-(ms)-/,o=function(u){return!u||s.test(u)||e.test(u)},l=function(u,h){return h.toUpperCase()},c=function(u,h){return"".concat(h,"-")},d=function(u,h){return h===void 0&&(h={}),o(u)?u:(u=u.toLowerCase(),h.reactCompat?u=u.replace(r,c):u=u.replace(a,c),u.replace(n,l))};return io.camelCase=d,io}var ao,cp;function U_(){if(cp)return ao;cp=1;var e=ao&&ao.__importDefault||function(r){return r&&r.__esModule?r:{default:r}},n=e(z_()),s=B_();function a(r,o){var l={};return!r||typeof r!="string"||(0,n.default)(r,function(c,d){c&&d&&(l[(0,s.camelCase)(c,o)]=d)}),l}return a.default=a,ao=a,ao}var H_=U_();const q_=sb(H_),bx=xx("end"),cm=xx("start");function xx(e){return n;function n(s){const a=s&&s.position&&s.position[e]||{};if(typeof a.line=="number"&&a.line>0&&typeof a.column=="number"&&a.column>0)return{line:a.line,column:a.column,offset:typeof a.offset=="number"&&a.offset>-1?a.offset:void 0}}}function V_(e){const n=cm(e),s=bx(e);if(n&&s)return{start:n,end:s}}function Ro(e){return!e||typeof e!="object"?"":"position"in e||"type"in e?dp(e.position):"start"in e||"end"in e?dp(e):"line"in e||"column"in e?ju(e):""}function ju(e){return up(e&&e.line)+":"+up(e&&e.column)}function dp(e){return ju(e&&e.start)+"-"+ju(e&&e.end)}function up(e){return e&&typeof e=="number"?e:1}class Ps extends Error{constructor(n,s,a){super(),typeof s=="string"&&(a=s,s=void 0);let r="",o={},l=!1;if(s&&("line"in s&&"column"in s?o={place:s}:"start"in s&&"end"in s?o={place:s}:"type"in s?o={ancestors:[s],place:s.position}:o={...s}),typeof n=="string"?r=n:!o.cause&&n&&(l=!0,r=n.message,o.cause=n),!o.ruleId&&!o.source&&typeof a=="string"){const d=a.indexOf(":");d===-1?o.ruleId=a:(o.source=a.slice(0,d),o.ruleId=a.slice(d+1))}if(!o.place&&o.ancestors&&o.ancestors){const d=o.ancestors[o.ancestors.length-1];d&&(o.place=d.position)}const c=o.place&&"start"in o.place?o.place.start:o.place;this.ancestors=o.ancestors||void 0,this.cause=o.cause||void 0,this.column=c?c.column:void 0,this.fatal=void 0,this.file="",this.message=r,this.line=c?c.line:void 0,this.name=Ro(o.place)||"1:1",this.place=o.place||void 0,this.reason=this.message,this.ruleId=o.ruleId||void 0,this.source=o.source||void 0,this.stack=l&&o.cause&&typeof o.cause.stack=="string"?o.cause.stack:"",this.actual=void 0,this.expected=void 0,this.note=void 0,this.url=void 0}}Ps.prototype.file="";Ps.prototype.name="";Ps.prototype.reason="";Ps.prototype.message="";Ps.prototype.stack="";Ps.prototype.column=void 0;Ps.prototype.line=void 0;Ps.prototype.ancestors=void 0;Ps.prototype.cause=void 0;Ps.prototype.fatal=void 0;Ps.prototype.place=void 0;Ps.prototype.ruleId=void 0;Ps.prototype.source=void 0;const dm={}.hasOwnProperty,W_=new Map,G_=/[A-Z]/g,K_=new Set(["table","tbody","thead","tfoot","tr"]),J_=new Set(["td","th"]),vx="https://github.com/syntax-tree/hast-util-to-jsx-runtime";function Y_(e,n){if(!n||n.Fragment===void 0)throw new TypeError("Expected `Fragment` in options");const s=n.filePath||void 0;let a;if(n.development){if(typeof n.jsxDEV!="function")throw new TypeError("Expected `jsxDEV` in options when `development: true`");a=i2(s,n.jsxDEV)}else{if(typeof n.jsx!="function")throw new TypeError("Expected `jsx` in production options");if(typeof n.jsxs!="function")throw new TypeError("Expected `jsxs` in production options");a=s2(s,n.jsx,n.jsxs)}const r={Fragment:n.Fragment,ancestors:[],components:n.components||{},create:a,elementAttributeNameCase:n.elementAttributeNameCase||"react",evaluater:n.createEvaluater?n.createEvaluater():void 0,filePath:s,ignoreInvalidStyle:n.ignoreInvalidStyle||!1,passKeys:n.passKeys!==!1,passNode:n.passNode||!1,schema:n.space==="svg"?lm:L_,stylePropertyNameCase:n.stylePropertyNameCase||"dom",tableCellAlignToStyle:n.tableCellAlignToStyle!==!1},o=yx(r,e,void 0);return o&&typeof o!="string"?o:r.create(e,r.Fragment,{children:o||void 0},void 0)}function yx(e,n,s){if(n.type==="element")return Q_(e,n,s);if(n.type==="mdxFlowExpression"||n.type==="mdxTextExpression")return X_(e,n);if(n.type==="mdxJsxFlowElement"||n.type==="mdxJsxTextElement")return e2(e,n,s);if(n.type==="mdxjsEsm")return Z_(e,n);if(n.type==="root")return t2(e,n,s);if(n.type==="text")return n2(e,n)}function Q_(e,n,s){const a=e.schema;let r=a;n.tagName.toLowerCase()==="svg"&&a.space==="html"&&(r=lm,e.schema=r),e.ancestors.push(n);const o=kx(e,n.tagName,!1),l=a2(e,n);let c=mm(e,n);return K_.has(n.tagName)&&(c=c.filter(function(d){return typeof d=="string"?!E_(d):!0})),wx(e,l,o,n),um(l,c),e.ancestors.pop(),e.schema=a,e.create(n,o,l,s)}function X_(e,n){if(n.data&&n.data.estree&&e.evaluater){const a=n.data.estree.body[0];return a.type,e.evaluater.evaluateExpression(a.expression)}Fo(e,n.position)}function Z_(e,n){if(n.data&&n.data.estree&&e.evaluater)return e.evaluater.evaluateProgram(n.data.estree);Fo(e,n.position)}function e2(e,n,s){const a=e.schema;let r=a;n.name==="svg"&&a.space==="html"&&(r=lm,e.schema=r),e.ancestors.push(n);const o=n.name===null?e.Fragment:kx(e,n.name,!0),l=r2(e,n),c=mm(e,n);return wx(e,l,o,n),um(l,c),e.ancestors.pop(),e.schema=a,e.create(n,o,l,s)}function t2(e,n,s){const a={};return um(a,mm(e,n)),e.create(n,e.Fragment,a,s)}function n2(e,n){return n.value}function wx(e,n,s,a){typeof s!="string"&&s!==e.Fragment&&e.passNode&&(n.node=a)}function um(e,n){if(n.length>0){const s=n.length>1?n:n[0];s&&(e.children=s)}}function s2(e,n,s){return a;function a(r,o,l,c){const u=Array.isArray(l.children)?s:n;return c?u(o,l,c):u(o,l)}}function i2(e,n){return s;function s(a,r,o,l){const c=Array.isArray(o.children),d=cm(a);return n(r,o,l,c,{columnNumber:d?d.column-1:void 0,fileName:e,lineNumber:d?d.line:void 0},void 0)}}function a2(e,n){const s={};let a,r;for(r in n.properties)if(r!=="children"&&dm.call(n.properties,r)){const o=o2(e,r,n.properties[r]);if(o){const[l,c]=o;e.tableCellAlignToStyle&&l==="align"&&typeof c=="string"&&J_.has(n.tagName)?a=c:s[l]=c}}if(a){const o=s.style||(s.style={});o[e.stylePropertyNameCase==="css"?"text-align":"textAlign"]=a}return s}function r2(e,n){const s={};for(const a of n.attributes)if(a.type==="mdxJsxExpressionAttribute")if(a.data&&a.data.estree&&e.evaluater){const o=a.data.estree.body[0];o.type;const l=o.expression;l.type;const c=l.properties[0];c.type,Object.assign(s,e.evaluater.evaluateExpression(c.argument))}else Fo(e,n.position);else{const r=a.name;let o;if(a.value&&typeof a.value=="object")if(a.value.data&&a.value.data.estree&&e.evaluater){const c=a.value.data.estree.body[0];c.type,o=e.evaluater.evaluateExpression(c.expression)}else Fo(e,n.position);else o=a.value===null?!0:a.value;s[r]=o}return s}function mm(e,n){const s=[];let a=-1;const r=e.passKeys?new Map:W_;for(;++a<n.children.length;){const o=n.children[a];let l;if(e.passKeys){const d=o.type==="element"?o.tagName:o.type==="mdxJsxFlowElement"||o.type==="mdxJsxTextElement"?o.name:void 0;if(d){const u=r.get(d)||0;l=d+"-"+u,r.set(d,u+1)}}const c=yx(e,o,l);c!==void 0&&s.push(c)}return s}function o2(e,n,s){const a=P_(e.schema,n);if(!(s==null||typeof s=="number"&&Number.isNaN(s))){if(Array.isArray(s)&&(s=a.commaSeparated?k_(s):O_(s)),a.property==="style"){let r=typeof s=="object"?s:l2(e,String(s));return e.stylePropertyNameCase==="css"&&(r=c2(r)),["style",r]}return[e.elementAttributeNameCase==="react"&&a.space?R_[a.property]||a.property:a.attribute,s]}}function l2(e,n){try{return q_(n,{reactCompat:!0})}catch(s){if(e.ignoreInvalidStyle)return{};const a=s,r=new Ps("Cannot parse `style` attribute",{ancestors:e.ancestors,cause:a,ruleId:"style",source:"hast-util-to-jsx-runtime"});throw r.file=e.filePath||void 0,r.url=vx+"#cannot-parse-style-attribute",r}}function kx(e,n,s){let a;if(!s)a={type:"Literal",value:n};else if(n.includes(".")){const r=n.split(".");let o=-1,l;for(;++o<r.length;){const c=np(r[o])?{type:"Identifier",name:r[o]}:{type:"Literal",value:r[o]};l=l?{type:"MemberExpression",object:l,property:c,computed:!!(o&&c.type==="Literal"),optional:!1}:c}a=l}else a=np(n)&&!/^[a-z]/.test(n)?{type:"Identifier",name:n}:{type:"Literal",value:n};if(a.type==="Literal"){const r=a.value;return dm.call(e.components,r)?e.components[r]:r}if(e.evaluater)return e.evaluater.evaluateExpression(a);Fo(e)}function Fo(e,n){const s=new Ps("Cannot handle MDX estrees without `createEvaluater`",{ancestors:e.ancestors,place:n,ruleId:"mdx-estree",source:"hast-util-to-jsx-runtime"});throw s.file=e.filePath||void 0,s.url=vx+"#cannot-handle-mdx-estrees-without-createevaluater",s}function c2(e){const n={};let s;for(s in e)dm.call(e,s)&&(n[d2(s)]=e[s]);return n}function d2(e){let n=e.replace(G_,u2);return n.slice(0,3)==="ms-"&&(n="-"+n),n}function u2(e){return"-"+e.toLowerCase()}const ud={action:["form"],cite:["blockquote","del","ins","q"],data:["object"],formAction:["button","input"],href:["a","area","base","link"],icon:["menuitem"],itemId:null,manifest:["html"],ping:["a","area"],poster:["video"],src:["audio","embed","iframe","img","input","script","source","track","video"]},m2={};function hm(e,n){const s=m2,a=typeof s.includeImageAlt=="boolean"?s.includeImageAlt:!0,r=typeof s.includeHtml=="boolean"?s.includeHtml:!0;return jx(e,a,r)}function jx(e,n,s){if(h2(e)){if("value"in e)return e.type==="html"&&!s?"":e.value;if(n&&"alt"in e&&e.alt)return e.alt;if("children"in e)return mp(e.children,n,s)}return Array.isArray(e)?mp(e,n,s):""}function mp(e,n,s){const a=[];let r=-1;for(;++r<e.length;)a[r]=jx(e[r],n,s);return a.join("")}function h2(e){return!!(e&&typeof e=="object")}const hp=document.createElement("i");function pm(e){const n="&"+e+";";hp.innerHTML=n;const s=hp.textContent;return s.charCodeAt(s.length-1)===59&&e!=="semi"||s===n?!1:s}function Xs(e,n,s,a){const r=e.length;let o=0,l;if(n<0?n=-n>r?0:r+n:n=n>r?r:n,s=s>0?s:0,a.length<1e4)l=Array.from(a),l.unshift(n,s),e.splice(...l);else for(s&&e.splice(n,s);o<a.length;)l=a.slice(o,o+1e4),l.unshift(n,0),e.splice(...l),o+=1e4,n+=1e4}function ci(e,n){return e.length>0?(Xs(e,e.length,0,n),e):n}const pp={}.hasOwnProperty;function Nx(e){const n={};let s=-1;for(;++s<e.length;)p2(n,e[s]);return n}function p2(e,n){let s;for(s in n){const r=(pp.call(e,s)?e[s]:void 0)||(e[s]={}),o=n[s];let l;if(o)for(l in o){pp.call(r,l)||(r[l]=[]);const c=o[l];f2(r[l],Array.isArray(c)?c:c?[c]:[])}}}function f2(e,n){let s=-1;const a=[];for(;++s<n.length;)(n[s].add==="after"?e:a).push(n[s]);Xs(e,0,0,a)}function Sx(e,n){const s=Number.parseInt(e,n);return s<9||s===11||s>13&&s<32||s>126&&s<160||s>55295&&s<57344||s>64975&&s<65008||(s&65535)===65535||(s&65535)===65534||s>1114111?"�":String.fromCodePoint(s)}function ji(e){return e.replace(/[\t\n\r ]+/g," ").replace(/^ | $/g,"").toLowerCase().toUpperCase()}const Fs=ka(/[A-Za-z]/),Ts=ka(/[\dA-Za-z]/),g2=ka(/[#-'*+\--9=?A-Z^-~]/);function sc(e){return e!==null&&(e<32||e===127)}const Nu=ka(/\d/),b2=ka(/[\dA-Fa-f]/),x2=ka(/[!-/:-@[-`{-~]/);function en(e){return e!==null&&e<-2}function Yn(e){return e!==null&&(e<0||e===32)}function jn(e){return e===-2||e===-1||e===32}const Mc=ka(/\p{P}|\p{S}/u),Va=ka(/\s/);function ka(e){return n;function n(s){return s!==null&&s>-1&&e.test(String.fromCharCode(s))}}function Wr(e){const n=[];let s=-1,a=0,r=0;for(;++s<e.length;){const o=e.charCodeAt(s);let l="";if(o===37&&Ts(e.charCodeAt(s+1))&&Ts(e.charCodeAt(s+2)))r=2;else if(o<128)/[!#$&-;=?-Z_a-z~]/.test(String.fromCharCode(o))||(l=String.fromCharCode(o));else if(o>55295&&o<57344){const c=e.charCodeAt(s+1);o<56320&&c>56319&&c<57344?(l=String.fromCharCode(o,c),r=1):l="�"}else l=String.fromCharCode(o);l&&(n.push(e.slice(a,s),encodeURIComponent(l)),a=s+r+1,l=""),r&&(s+=r,r=0)}return n.join("")+e.slice(a)}function Mn(e,n,s,a){const r=a?a-1:Number.POSITIVE_INFINITY;let o=0;return l;function l(d){return jn(d)?(e.enter(s),c(d)):n(d)}function c(d){return jn(d)&&o++<r?(e.consume(d),c):(e.exit(s),n(d))}}const v2={tokenize:y2};function y2(e){const n=e.attempt(this.parser.constructs.contentInitial,a,r);let s;return n;function a(c){if(c===null){e.consume(c);return}return e.enter("lineEnding"),e.consume(c),e.exit("lineEnding"),Mn(e,n,"linePrefix")}function r(c){return e.enter("paragraph"),o(c)}function o(c){const d=e.enter("chunkText",{contentType:"text",previous:s});return s&&(s.next=d),s=d,l(c)}function l(c){if(c===null){e.exit("chunkText"),e.exit("paragraph"),e.consume(c);return}return en(c)?(e.consume(c),e.exit("chunkText"),o):(e.consume(c),l)}}const w2={tokenize:k2},fp={tokenize:j2};function k2(e){const n=this,s=[];let a=0,r,o,l;return c;function c(j){if(a<s.length){const S=s[a];return n.containerState=S[1],e.attempt(S[0].continuation,d,u)(j)}return u(j)}function d(j){if(a++,n.containerState._closeFlow){n.containerState._closeFlow=void 0,r&&y();const S=n.events.length;let C=S,x;for(;C--;)if(n.events[C][0]==="exit"&&n.events[C][1].type==="chunkFlow"){x=n.events[C][1].end;break}b(a);let k=S;for(;k<n.events.length;)n.events[k][1].end={...x},k++;return Xs(n.events,C+1,0,n.events.slice(S)),n.events.length=k,u(j)}return c(j)}function u(j){if(a===s.length){if(!r)return f(j);if(r.currentConstruct&&r.currentConstruct.concrete)return g(j);n.interrupt=!!(r.currentConstruct&&!r._gfmTableDynamicInterruptHack)}return n.containerState={},e.check(fp,h,m)(j)}function h(j){return r&&y(),b(a),f(j)}function m(j){return n.parser.lazy[n.now().line]=a!==s.length,l=n.now().offset,g(j)}function f(j){return n.containerState={},e.attempt(fp,p,g)(j)}function p(j){return a++,s.push([n.currentConstruct,n.containerState]),f(j)}function g(j){if(j===null){r&&y(),b(0),e.consume(j);return}return r=r||n.parser.flow(n.now()),e.enter("chunkFlow",{_tokenizer:r,contentType:"flow",previous:o}),w(j)}function w(j){if(j===null){v(e.exit("chunkFlow"),!0),b(0),e.consume(j);return}return en(j)?(e.consume(j),v(e.exit("chunkFlow")),a=0,n.interrupt=void 0,c):(e.consume(j),w)}function v(j,S){const C=n.sliceStream(j);if(S&&C.push(null),j.previous=o,o&&(o.next=j),o=j,r.defineSkip(j.start),r.write(C),n.parser.lazy[j.start.line]){let x=r.events.length;for(;x--;)if(r.events[x][1].start.offset<l&&(!r.events[x][1].end||r.events[x][1].end.offset>l))return;const k=n.events.length;let R=k,O,E;for(;R--;)if(n.events[R][0]==="exit"&&n.events[R][1].type==="chunkFlow"){if(O){E=n.events[R][1].end;break}O=!0}for(b(a),x=k;x<n.events.length;)n.events[x][1].end={...E},x++;Xs(n.events,R+1,0,n.events.slice(k)),n.events.length=x}}function b(j){let S=s.length;for(;S-- >j;){const C=s[S];n.containerState=C[1],C[0].exit.call(n,e)}s.length=j}function y(){r.write([null]),o=void 0,r=void 0,n.containerState._closeFlow=void 0}}function j2(e,n,s){return Mn(e,e.attempt(this.parser.constructs.document,n,s),"linePrefix",this.parser.constructs.disable.null.includes("codeIndented")?void 0:4)}function Rr(e){if(e===null||Yn(e)||Va(e))return 1;if(Mc(e))return 2}function Ac(e,n,s){const a=[];let r=-1;for(;++r<e.length;){const o=e[r].resolveAll;o&&!a.includes(o)&&(n=o(n,s),a.push(o))}return n}const Su={name:"attention",resolveAll:N2,tokenize:S2};function N2(e,n){let s=-1,a,r,o,l,c,d,u,h;for(;++s<e.length;)if(e[s][0]==="enter"&&e[s][1].type==="attentionSequence"&&e[s][1]._close){for(a=s;a--;)if(e[a][0]==="exit"&&e[a][1].type==="attentionSequence"&&e[a][1]._open&&n.sliceSerialize(e[a][1]).charCodeAt(0)===n.sliceSerialize(e[s][1]).charCodeAt(0)){if((e[a][1]._close||e[s][1]._open)&&(e[s][1].end.offset-e[s][1].start.offset)%3&&!((e[a][1].end.offset-e[a][1].start.offset+e[s][1].end.offset-e[s][1].start.offset)%3))continue;d=e[a][1].end.offset-e[a][1].start.offset>1&&e[s][1].end.offset-e[s][1].start.offset>1?2:1;const m={...e[a][1].end},f={...e[s][1].start};gp(m,-d),gp(f,d),l={type:d>1?"strongSequence":"emphasisSequence",start:m,end:{...e[a][1].end}},c={type:d>1?"strongSequence":"emphasisSequence",start:{...e[s][1].start},end:f},o={type:d>1?"strongText":"emphasisText",start:{...e[a][1].end},end:{...e[s][1].start}},r={type:d>1?"strong":"emphasis",start:{...l.start},end:{...c.end}},e[a][1].end={...l.start},e[s][1].start={...c.end},u=[],e[a][1].end.offset-e[a][1].start.offset&&(u=ci(u,[["enter",e[a][1],n],["exit",e[a][1],n]])),u=ci(u,[["enter",r,n],["enter",l,n],["exit",l,n],["enter",o,n]]),u=ci(u,Ac(n.parser.constructs.insideSpan.null,e.slice(a+1,s),n)),u=ci(u,[["exit",o,n],["enter",c,n],["exit",c,n],["exit",r,n]]),e[s][1].end.offset-e[s][1].start.offset?(h=2,u=ci(u,[["enter",e[s][1],n],["exit",e[s][1],n]])):h=0,Xs(e,a-1,s-a+3,u),s=a+u.length-h-2;break}}for(s=-1;++s<e.length;)e[s][1].type==="attentionSequence"&&(e[s][1].type="data");return e}function S2(e,n){const s=this.parser.constructs.attentionMarkers.null,a=this.previous,r=Rr(a);let o;return l;function l(d){return o=d,e.enter("attentionSequence"),c(d)}function c(d){if(d===o)return e.consume(d),c;const u=e.exit("attentionSequence"),h=Rr(d),m=!h||h===2&&r||s.includes(d),f=!r||r===2&&h||s.includes(a);return u._open=!!(o===42?m:m&&(r||!f)),u._close=!!(o===42?f:f&&(h||!m)),n(d)}}function gp(e,n){e.column+=n,e.offset+=n,e._bufferIndex+=n}const C2={name:"autolink",tokenize:E2};function E2(e,n,s){let a=0;return r;function r(p){return e.enter("autolink"),e.enter("autolinkMarker"),e.consume(p),e.exit("autolinkMarker"),e.enter("autolinkProtocol"),o}function o(p){return Fs(p)?(e.consume(p),l):p===64?s(p):u(p)}function l(p){return p===43||p===45||p===46||Ts(p)?(a=1,c(p)):u(p)}function c(p){return p===58?(e.consume(p),a=0,d):(p===43||p===45||p===46||Ts(p))&&a++<32?(e.consume(p),c):(a=0,u(p))}function d(p){return p===62?(e.exit("autolinkProtocol"),e.enter("autolinkMarker"),e.consume(p),e.exit("autolinkMarker"),e.exit("autolink"),n):p===null||p===32||p===60||sc(p)?s(p):(e.consume(p),d)}function u(p){return p===64?(e.consume(p),h):g2(p)?(e.consume(p),u):s(p)}function h(p){return Ts(p)?m(p):s(p)}function m(p){return p===46?(e.consume(p),a=0,h):p===62?(e.exit("autolinkProtocol").type="autolinkEmail",e.enter("autolinkMarker"),e.consume(p),e.exit("autolinkMarker"),e.exit("autolink"),n):f(p)}function f(p){if((p===45||Ts(p))&&a++<63){const g=p===45?f:m;return e.consume(p),g}return s(p)}}const tl={partial:!0,tokenize:_2};function _2(e,n,s){return a;function a(o){return jn(o)?Mn(e,r,"linePrefix")(o):r(o)}function r(o){return o===null||en(o)?n(o):s(o)}}const Cx={continuation:{tokenize:A2},exit:R2,name:"blockQuote",tokenize:M2};function M2(e,n,s){const a=this;return r;function r(l){if(l===62){const c=a.containerState;return c.open||(e.enter("blockQuote",{_container:!0}),c.open=!0),e.enter("blockQuotePrefix"),e.enter("blockQuoteMarker"),e.consume(l),e.exit("blockQuoteMarker"),o}return s(l)}function o(l){return jn(l)?(e.enter("blockQuotePrefixWhitespace"),e.consume(l),e.exit("blockQuotePrefixWhitespace"),e.exit("blockQuotePrefix"),n):(e.exit("blockQuotePrefix"),n(l))}}function A2(e,n,s){const a=this;return r;function r(l){return jn(l)?Mn(e,o,"linePrefix",a.parser.constructs.disable.null.includes("codeIndented")?void 0:4)(l):o(l)}function o(l){return e.attempt(Cx,n,s)(l)}}function R2(e){e.exit("blockQuote")}const Ex={name:"characterEscape",tokenize:I2};function I2(e,n,s){return a;function a(o){return e.enter("characterEscape"),e.enter("escapeMarker"),e.consume(o),e.exit("escapeMarker"),r}function r(o){return x2(o)?(e.enter("characterEscapeValue"),e.consume(o),e.exit("characterEscapeValue"),e.exit("characterEscape"),n):s(o)}}const _x={name:"characterReference",tokenize:T2};function T2(e,n,s){const a=this;let r=0,o,l;return c;function c(m){return e.enter("characterReference"),e.enter("characterReferenceMarker"),e.consume(m),e.exit("characterReferenceMarker"),d}function d(m){return m===35?(e.enter("characterReferenceMarkerNumeric"),e.consume(m),e.exit("characterReferenceMarkerNumeric"),u):(e.enter("characterReferenceValue"),o=31,l=Ts,h(m))}function u(m){return m===88||m===120?(e.enter("characterReferenceMarkerHexadecimal"),e.consume(m),e.exit("characterReferenceMarkerHexadecimal"),e.enter("characterReferenceValue"),o=6,l=b2,h):(e.enter("characterReferenceValue"),o=7,l=Nu,h(m))}function h(m){if(m===59&&r){const f=e.exit("characterReferenceValue");return l===Ts&&!pm(a.sliceSerialize(f))?s(m):(e.enter("characterReferenceMarker"),e.consume(m),e.exit("characterReferenceMarker"),e.exit("characterReference"),n)}return l(m)&&r++<o?(e.consume(m),h):s(m)}}const bp={partial:!0,tokenize:$2},xp={concrete:!0,name:"codeFenced",tokenize:P2};function P2(e,n,s){const a=this,r={partial:!0,tokenize:C};let o=0,l=0,c;return d;function d(x){return u(x)}function u(x){const k=a.events[a.events.length-1];return o=k&&k[1].type==="linePrefix"?k[2].sliceSerialize(k[1],!0).length:0,c=x,e.enter("codeFenced"),e.enter("codeFencedFence"),e.enter("codeFencedFenceSequence"),h(x)}function h(x){return x===c?(l++,e.consume(x),h):l<3?s(x):(e.exit("codeFencedFenceSequence"),jn(x)?Mn(e,m,"whitespace")(x):m(x))}function m(x){return x===null||en(x)?(e.exit("codeFencedFence"),a.interrupt?n(x):e.check(bp,w,S)(x)):(e.enter("codeFencedFenceInfo"),e.enter("chunkString",{contentType:"string"}),f(x))}function f(x){return x===null||en(x)?(e.exit("chunkString"),e.exit("codeFencedFenceInfo"),m(x)):jn(x)?(e.exit("chunkString"),e.exit("codeFencedFenceInfo"),Mn(e,p,"whitespace")(x)):x===96&&x===c?s(x):(e.consume(x),f)}function p(x){return x===null||en(x)?m(x):(e.enter("codeFencedFenceMeta"),e.enter("chunkString",{contentType:"string"}),g(x))}function g(x){return x===null||en(x)?(e.exit("chunkString"),e.exit("codeFencedFenceMeta"),m(x)):x===96&&x===c?s(x):(e.consume(x),g)}function w(x){return e.attempt(r,S,v)(x)}function v(x){return e.enter("lineEnding"),e.consume(x),e.exit("lineEnding"),b}function b(x){return o>0&&jn(x)?Mn(e,y,"linePrefix",o+1)(x):y(x)}function y(x){return x===null||en(x)?e.check(bp,w,S)(x):(e.enter("codeFlowValue"),j(x))}function j(x){return x===null||en(x)?(e.exit("codeFlowValue"),y(x)):(e.consume(x),j)}function S(x){return e.exit("codeFenced"),n(x)}function C(x,k,R){let O=0;return E;function E(P){return x.enter("lineEnding"),x.consume(P),x.exit("lineEnding"),_}function _(P){return x.enter("codeFencedFence"),jn(P)?Mn(x,G,"linePrefix",a.parser.constructs.disable.null.includes("codeIndented")?void 0:4)(P):G(P)}function G(P){return P===c?(x.enter("codeFencedFenceSequence"),H(P)):R(P)}function H(P){return P===c?(O++,x.consume(P),H):O>=l?(x.exit("codeFencedFenceSequence"),jn(P)?Mn(x,A,"whitespace")(P):A(P)):R(P)}function A(P){return P===null||en(P)?(x.exit("codeFencedFence"),k(P)):R(P)}}}function $2(e,n,s){const a=this;return r;function r(l){return l===null?s(l):(e.enter("lineEnding"),e.consume(l),e.exit("lineEnding"),o)}function o(l){return a.parser.lazy[a.now().line]?s(l):n(l)}}const md={name:"codeIndented",tokenize:L2},D2={partial:!0,tokenize:O2};function L2(e,n,s){const a=this;return r;function r(u){return e.enter("codeIndented"),Mn(e,o,"linePrefix",5)(u)}function o(u){const h=a.events[a.events.length-1];return h&&h[1].type==="linePrefix"&&h[2].sliceSerialize(h[1],!0).length>=4?l(u):s(u)}function l(u){return u===null?d(u):en(u)?e.attempt(D2,l,d)(u):(e.enter("codeFlowValue"),c(u))}function c(u){return u===null||en(u)?(e.exit("codeFlowValue"),l(u)):(e.consume(u),c)}function d(u){return e.exit("codeIndented"),n(u)}}function O2(e,n,s){const a=this;return r;function r(l){return a.parser.lazy[a.now().line]?s(l):en(l)?(e.enter("lineEnding"),e.consume(l),e.exit("lineEnding"),r):Mn(e,o,"linePrefix",5)(l)}function o(l){const c=a.events[a.events.length-1];return c&&c[1].type==="linePrefix"&&c[2].sliceSerialize(c[1],!0).length>=4?n(l):en(l)?r(l):s(l)}}const F2={name:"codeText",previous:B2,resolve:z2,tokenize:U2};function z2(e){let n=e.length-4,s=3,a,r;if((e[s][1].type==="lineEnding"||e[s][1].type==="space")&&(e[n][1].type==="lineEnding"||e[n][1].type==="space")){for(a=s;++a<n;)if(e[a][1].type==="codeTextData"){e[s][1].type="codeTextPadding",e[n][1].type="codeTextPadding",s+=2,n-=2;break}}for(a=s-1,n++;++a<=n;)r===void 0?a!==n&&e[a][1].type!=="lineEnding"&&(r=a):(a===n||e[a][1].type==="lineEnding")&&(e[r][1].type="codeTextData",a!==r+2&&(e[r][1].end=e[a-1][1].end,e.splice(r+2,a-r-2),n-=a-r-2,a=r+2),r=void 0);return e}function B2(e){return e!==96||this.events[this.events.length-1][1].type==="characterEscape"}function U2(e,n,s){let a=0,r,o;return l;function l(m){return e.enter("codeText"),e.enter("codeTextSequence"),c(m)}function c(m){return m===96?(e.consume(m),a++,c):(e.exit("codeTextSequence"),d(m))}function d(m){return m===null?s(m):m===32?(e.enter("space"),e.consume(m),e.exit("space"),d):m===96?(o=e.enter("codeTextSequence"),r=0,h(m)):en(m)?(e.enter("lineEnding"),e.consume(m),e.exit("lineEnding"),d):(e.enter("codeTextData"),u(m))}function u(m){return m===null||m===32||m===96||en(m)?(e.exit("codeTextData"),d(m)):(e.consume(m),u)}function h(m){return m===96?(e.consume(m),r++,h):r===a?(e.exit("codeTextSequence"),e.exit("codeText"),n(m)):(o.type="codeTextData",u(m))}}class H2{constructor(n){this.left=n?[...n]:[],this.right=[]}get(n){if(n<0||n>=this.left.length+this.right.length)throw new RangeError("Cannot access index `"+n+"` in a splice buffer of size `"+(this.left.length+this.right.length)+"`");return n<this.left.length?this.left[n]:this.right[this.right.length-n+this.left.length-1]}get length(){return this.left.length+this.right.length}shift(){return this.setCursor(0),this.right.pop()}slice(n,s){const a=s??Number.POSITIVE_INFINITY;return a<this.left.length?this.left.slice(n,a):n>this.left.length?this.right.slice(this.right.length-a+this.left.length,this.right.length-n+this.left.length).reverse():this.left.slice(n).concat(this.right.slice(this.right.length-a+this.left.length).reverse())}splice(n,s,a){const r=s||0;this.setCursor(Math.trunc(n));const o=this.right.splice(this.right.length-r,Number.POSITIVE_INFINITY);return a&&ro(this.left,a),o.reverse()}pop(){return this.setCursor(Number.POSITIVE_INFINITY),this.left.pop()}push(n){this.setCursor(Number.POSITIVE_INFINITY),this.left.push(n)}pushMany(n){this.setCursor(Number.POSITIVE_INFINITY),ro(this.left,n)}unshift(n){this.setCursor(0),this.right.push(n)}unshiftMany(n){this.setCursor(0),ro(this.right,n.reverse())}setCursor(n){if(!(n===this.left.length||n>this.left.length&&this.right.length===0||n<0&&this.left.length===0))if(n<this.left.length){const s=this.left.splice(n,Number.POSITIVE_INFINITY);ro(this.right,s.reverse())}else{const s=this.right.splice(this.left.length+this.right.length-n,Number.POSITIVE_INFINITY);ro(this.left,s.reverse())}}}function ro(e,n){let s=0;if(n.length<1e4)e.push(...n);else for(;s<n.length;)e.push(...n.slice(s,s+1e4)),s+=1e4}function Mx(e){const n={};let s=-1,a,r,o,l,c,d,u;const h=new H2(e);for(;++s<h.length;){for(;s in n;)s=n[s];if(a=h.get(s),s&&a[1].type==="chunkFlow"&&h.get(s-1)[1].type==="listItemPrefix"&&(d=a[1]._tokenizer.events,o=0,o<d.length&&d[o][1].type==="lineEndingBlank"&&(o+=2),o<d.length&&d[o][1].type==="content"))for(;++o<d.length&&d[o][1].type!=="content";)d[o][1].type==="chunkText"&&(d[o][1]._isInFirstContentOfListItem=!0,o++);if(a[0]==="enter")a[1].contentType&&(Object.assign(n,q2(h,s)),s=n[s],u=!0);else if(a[1]._container){for(o=s,r=void 0;o--;)if(l=h.get(o),l[1].type==="lineEnding"||l[1].type==="lineEndingBlank")l[0]==="enter"&&(r&&(h.get(r)[1].type="lineEndingBlank"),l[1].type="lineEnding",r=o);else if(!(l[1].type==="linePrefix"||l[1].type==="listItemIndent"))break;r&&(a[1].end={...h.get(r)[1].start},c=h.slice(r,s),c.unshift(a),h.splice(r,s-r+1,c))}}return Xs(e,0,Number.POSITIVE_INFINITY,h.slice(0)),!u}function q2(e,n){const s=e.get(n)[1],a=e.get(n)[2];let r=n-1;const o=[];let l=s._tokenizer;l||(l=a.parser[s.contentType](s.start),s._contentTypeTextTrailing&&(l._contentTypeTextTrailing=!0));const c=l.events,d=[],u={};let h,m,f=-1,p=s,g=0,w=0;const v=[w];for(;p;){for(;e.get(++r)[1]!==p;);o.push(r),p._tokenizer||(h=a.sliceStream(p),p.next||h.push(null),m&&l.defineSkip(p.start),p._isInFirstContentOfListItem&&(l._gfmTasklistFirstContentOfListItem=!0),l.write(h),p._isInFirstContentOfListItem&&(l._gfmTasklistFirstContentOfListItem=void 0)),m=p,p=p.next}for(p=s;++f<c.length;)c[f][0]==="exit"&&c[f-1][0]==="enter"&&c[f][1].type===c[f-1][1].type&&c[f][1].start.line!==c[f][1].end.line&&(w=f+1,v.push(w),p._tokenizer=void 0,p.previous=void 0,p=p.next);for(l.events=[],p?(p._tokenizer=void 0,p.previous=void 0):v.pop(),f=v.length;f--;){const b=c.slice(v[f],v[f+1]),y=o.pop();d.push([y,y+b.length-1]),e.splice(y,2,b)}for(d.reverse(),f=-1;++f<d.length;)u[g+d[f][0]]=g+d[f][1],g+=d[f][1]-d[f][0]-1;return u}const V2={resolve:G2,tokenize:K2},W2={partial:!0,tokenize:J2};function G2(e){return Mx(e),e}function K2(e,n){let s;return a;function a(c){return e.enter("content"),s=e.enter("chunkContent",{contentType:"content"}),r(c)}function r(c){return c===null?o(c):en(c)?e.check(W2,l,o)(c):(e.consume(c),r)}function o(c){return e.exit("chunkContent"),e.exit("content"),n(c)}function l(c){return e.consume(c),e.exit("chunkContent"),s.next=e.enter("chunkContent",{contentType:"content",previous:s}),s=s.next,r}}function J2(e,n,s){const a=this;return r;function r(l){return e.exit("chunkContent"),e.enter("lineEnding"),e.consume(l),e.exit("lineEnding"),Mn(e,o,"linePrefix")}function o(l){if(l===null||en(l))return s(l);const c=a.events[a.events.length-1];return!a.parser.constructs.disable.null.includes("codeIndented")&&c&&c[1].type==="linePrefix"&&c[2].sliceSerialize(c[1],!0).length>=4?n(l):e.interrupt(a.parser.constructs.flow,s,n)(l)}}function Ax(e,n,s,a,r,o,l,c,d){const u=d||Number.POSITIVE_INFINITY;let h=0;return m;function m(b){return b===60?(e.enter(a),e.enter(r),e.enter(o),e.consume(b),e.exit(o),f):b===null||b===32||b===41||sc(b)?s(b):(e.enter(a),e.enter(l),e.enter(c),e.enter("chunkString",{contentType:"string"}),w(b))}function f(b){return b===62?(e.enter(o),e.consume(b),e.exit(o),e.exit(r),e.exit(a),n):(e.enter(c),e.enter("chunkString",{contentType:"string"}),p(b))}function p(b){return b===62?(e.exit("chunkString"),e.exit(c),f(b)):b===null||b===60||en(b)?s(b):(e.consume(b),b===92?g:p)}function g(b){return b===60||b===62||b===92?(e.consume(b),p):p(b)}function w(b){return!h&&(b===null||b===41||Yn(b))?(e.exit("chunkString"),e.exit(c),e.exit(l),e.exit(a),n(b)):h<u&&b===40?(e.consume(b),h++,w):b===41?(e.consume(b),h--,w):b===null||b===32||b===40||sc(b)?s(b):(e.consume(b),b===92?v:w)}function v(b){return b===40||b===41||b===92?(e.consume(b),w):w(b)}}function Rx(e,n,s,a,r,o){const l=this;let c=0,d;return u;function u(p){return e.enter(a),e.enter(r),e.consume(p),e.exit(r),e.enter(o),h}function h(p){return c>999||p===null||p===91||p===93&&!d||p===94&&!c&&"_hiddenFootnoteSupport"in l.parser.constructs?s(p):p===93?(e.exit(o),e.enter(r),e.consume(p),e.exit(r),e.exit(a),n):en(p)?(e.enter("lineEnding"),e.consume(p),e.exit("lineEnding"),h):(e.enter("chunkString",{contentType:"string"}),m(p))}function m(p){return p===null||p===91||p===93||en(p)||c++>999?(e.exit("chunkString"),h(p)):(e.consume(p),d||(d=!jn(p)),p===92?f:m)}function f(p){return p===91||p===92||p===93?(e.consume(p),c++,m):m(p)}}function Ix(e,n,s,a,r,o){let l;return c;function c(f){return f===34||f===39||f===40?(e.enter(a),e.enter(r),e.consume(f),e.exit(r),l=f===40?41:f,d):s(f)}function d(f){return f===l?(e.enter(r),e.consume(f),e.exit(r),e.exit(a),n):(e.enter(o),u(f))}function u(f){return f===l?(e.exit(o),d(l)):f===null?s(f):en(f)?(e.enter("lineEnding"),e.consume(f),e.exit("lineEnding"),Mn(e,u,"linePrefix")):(e.enter("chunkString",{contentType:"string"}),h(f))}function h(f){return f===l||f===null||en(f)?(e.exit("chunkString"),u(f)):(e.consume(f),f===92?m:h)}function m(f){return f===l||f===92?(e.consume(f),h):h(f)}}function Io(e,n){let s;return a;function a(r){return en(r)?(e.enter("lineEnding"),e.consume(r),e.exit("lineEnding"),s=!0,a):jn(r)?Mn(e,a,s?"linePrefix":"lineSuffix")(r):n(r)}}const Y2={name:"definition",tokenize:X2},Q2={partial:!0,tokenize:Z2};function X2(e,n,s){const a=this;let r;return o;function o(p){return e.enter("definition"),l(p)}function l(p){return Rx.call(a,e,c,s,"definitionLabel","definitionLabelMarker","definitionLabelString")(p)}function c(p){return r=ji(a.sliceSerialize(a.events[a.events.length-1][1]).slice(1,-1)),p===58?(e.enter("definitionMarker"),e.consume(p),e.exit("definitionMarker"),d):s(p)}function d(p){return Yn(p)?Io(e,u)(p):u(p)}function u(p){return Ax(e,h,s,"definitionDestination","definitionDestinationLiteral","definitionDestinationLiteralMarker","definitionDestinationRaw","definitionDestinationString")(p)}function h(p){return e.attempt(Q2,m,m)(p)}function m(p){return jn(p)?Mn(e,f,"whitespace")(p):f(p)}function f(p){return p===null||en(p)?(e.exit("definition"),a.parser.defined.push(r),n(p)):s(p)}}function Z2(e,n,s){return a;function a(c){return Yn(c)?Io(e,r)(c):s(c)}function r(c){return Ix(e,o,s,"definitionTitle","definitionTitleMarker","definitionTitleString")(c)}function o(c){return jn(c)?Mn(e,l,"whitespace")(c):l(c)}function l(c){return c===null||en(c)?n(c):s(c)}}const eM={name:"hardBreakEscape",tokenize:tM};function tM(e,n,s){return a;function a(o){return e.enter("hardBreakEscape"),e.consume(o),r}function r(o){return en(o)?(e.exit("hardBreakEscape"),n(o)):s(o)}}const nM={name:"headingAtx",resolve:sM,tokenize:iM};function sM(e,n){let s=e.length-2,a=3,r,o;return e[a][1].type==="whitespace"&&(a+=2),s-2>a&&e[s][1].type==="whitespace"&&(s-=2),e[s][1].type==="atxHeadingSequence"&&(a===s-1||s-4>a&&e[s-2][1].type==="whitespace")&&(s-=a+1===s?2:4),s>a&&(r={type:"atxHeadingText",start:e[a][1].start,end:e[s][1].end},o={type:"chunkText",start:e[a][1].start,end:e[s][1].end,contentType:"text"},Xs(e,a,s-a+1,[["enter",r,n],["enter",o,n],["exit",o,n],["exit",r,n]])),e}function iM(e,n,s){let a=0;return r;function r(h){return e.enter("atxHeading"),o(h)}function o(h){return e.enter("atxHeadingSequence"),l(h)}function l(h){return h===35&&a++<6?(e.consume(h),l):h===null||Yn(h)?(e.exit("atxHeadingSequence"),c(h)):s(h)}function c(h){return h===35?(e.enter("atxHeadingSequence"),d(h)):h===null||en(h)?(e.exit("atxHeading"),n(h)):jn(h)?Mn(e,c,"whitespace")(h):(e.enter("atxHeadingText"),u(h))}function d(h){return h===35?(e.consume(h),d):(e.exit("atxHeadingSequence"),c(h))}function u(h){return h===null||h===35||Yn(h)?(e.exit("atxHeadingText"),c(h)):(e.consume(h),u)}}const aM=["address","article","aside","base","basefont","blockquote","body","caption","center","col","colgroup","dd","details","dialog","dir","div","dl","dt","fieldset","figcaption","figure","footer","form","frame","frameset","h1","h2","h3","h4","h5","h6","head","header","hr","html","iframe","legend","li","link","main","menu","menuitem","nav","noframes","ol","optgroup","option","p","param","search","section","summary","table","tbody","td","tfoot","th","thead","title","tr","track","ul"],vp=["pre","script","style","textarea"],rM={concrete:!0,name:"htmlFlow",resolveTo:cM,tokenize:dM},oM={partial:!0,tokenize:mM},lM={partial:!0,tokenize:uM};function cM(e){let n=e.length;for(;n--&&!(e[n][0]==="enter"&&e[n][1].type==="htmlFlow"););return n>1&&e[n-2][1].type==="linePrefix"&&(e[n][1].start=e[n-2][1].start,e[n+1][1].start=e[n-2][1].start,e.splice(n-2,2)),e}function dM(e,n,s){const a=this;let r,o,l,c,d;return u;function u(N){return h(N)}function h(N){return e.enter("htmlFlow"),e.enter("htmlFlowData"),e.consume(N),m}function m(N){return N===33?(e.consume(N),f):N===47?(e.consume(N),o=!0,w):N===63?(e.consume(N),r=3,a.interrupt?n:M):Fs(N)?(e.consume(N),l=String.fromCharCode(N),v):s(N)}function f(N){return N===45?(e.consume(N),r=2,p):N===91?(e.consume(N),r=5,c=0,g):Fs(N)?(e.consume(N),r=4,a.interrupt?n:M):s(N)}function p(N){return N===45?(e.consume(N),a.interrupt?n:M):s(N)}function g(N){const W="CDATA[";return N===W.charCodeAt(c++)?(e.consume(N),c===W.length?a.interrupt?n:G:g):s(N)}function w(N){return Fs(N)?(e.consume(N),l=String.fromCharCode(N),v):s(N)}function v(N){if(N===null||N===47||N===62||Yn(N)){const W=N===47,de=l.toLowerCase();return!W&&!o&&vp.includes(de)?(r=1,a.interrupt?n(N):G(N)):aM.includes(l.toLowerCase())?(r=6,W?(e.consume(N),b):a.interrupt?n(N):G(N)):(r=7,a.interrupt&&!a.parser.lazy[a.now().line]?s(N):o?y(N):j(N))}return N===45||Ts(N)?(e.consume(N),l+=String.fromCharCode(N),v):s(N)}function b(N){return N===62?(e.consume(N),a.interrupt?n:G):s(N)}function y(N){return jn(N)?(e.consume(N),y):E(N)}function j(N){return N===47?(e.consume(N),E):N===58||N===95||Fs(N)?(e.consume(N),S):jn(N)?(e.consume(N),j):E(N)}function S(N){return N===45||N===46||N===58||N===95||Ts(N)?(e.consume(N),S):C(N)}function C(N){return N===61?(e.consume(N),x):jn(N)?(e.consume(N),C):j(N)}function x(N){return N===null||N===60||N===61||N===62||N===96?s(N):N===34||N===39?(e.consume(N),d=N,k):jn(N)?(e.consume(N),x):R(N)}function k(N){return N===d?(e.consume(N),d=null,O):N===null||en(N)?s(N):(e.consume(N),k)}function R(N){return N===null||N===34||N===39||N===47||N===60||N===61||N===62||N===96||Yn(N)?C(N):(e.consume(N),R)}function O(N){return N===47||N===62||jn(N)?j(N):s(N)}function E(N){return N===62?(e.consume(N),_):s(N)}function _(N){return N===null||en(N)?G(N):jn(N)?(e.consume(N),_):s(N)}function G(N){return N===45&&r===2?(e.consume(N),q):N===60&&r===1?(e.consume(N),Y):N===62&&r===4?(e.consume(N),$):N===63&&r===3?(e.consume(N),M):N===93&&r===5?(e.consume(N),L):en(N)&&(r===6||r===7)?(e.exit("htmlFlowData"),e.check(oM,D,H)(N)):N===null||en(N)?(e.exit("htmlFlowData"),H(N)):(e.consume(N),G)}function H(N){return e.check(lM,A,D)(N)}function A(N){return e.enter("lineEnding"),e.consume(N),e.exit("lineEnding"),P}function P(N){return N===null||en(N)?H(N):(e.enter("htmlFlowData"),G(N))}function q(N){return N===45?(e.consume(N),M):G(N)}function Y(N){return N===47?(e.consume(N),l="",ge):G(N)}function ge(N){if(N===62){const W=l.toLowerCase();return vp.includes(W)?(e.consume(N),$):G(N)}return Fs(N)&&l.length<8?(e.consume(N),l+=String.fromCharCode(N),ge):G(N)}function L(N){return N===93?(e.consume(N),M):G(N)}function M(N){return N===62?(e.consume(N),$):N===45&&r===2?(e.consume(N),M):G(N)}function $(N){return N===null||en(N)?(e.exit("htmlFlowData"),D(N)):(e.consume(N),$)}function D(N){return e.exit("htmlFlow"),n(N)}}function uM(e,n,s){const a=this;return r;function r(l){return en(l)?(e.enter("lineEnding"),e.consume(l),e.exit("lineEnding"),o):s(l)}function o(l){return a.parser.lazy[a.now().line]?s(l):n(l)}}function mM(e,n,s){return a;function a(r){return e.enter("lineEnding"),e.consume(r),e.exit("lineEnding"),e.attempt(tl,n,s)}}const hM={name:"htmlText",tokenize:pM};function pM(e,n,s){const a=this;let r,o,l;return c;function c(M){return e.enter("htmlText"),e.enter("htmlTextData"),e.consume(M),d}function d(M){return M===33?(e.consume(M),u):M===47?(e.consume(M),C):M===63?(e.consume(M),j):Fs(M)?(e.consume(M),R):s(M)}function u(M){return M===45?(e.consume(M),h):M===91?(e.consume(M),o=0,g):Fs(M)?(e.consume(M),y):s(M)}function h(M){return M===45?(e.consume(M),p):s(M)}function m(M){return M===null?s(M):M===45?(e.consume(M),f):en(M)?(l=m,Y(M)):(e.consume(M),m)}function f(M){return M===45?(e.consume(M),p):m(M)}function p(M){return M===62?q(M):M===45?f(M):m(M)}function g(M){const $="CDATA[";return M===$.charCodeAt(o++)?(e.consume(M),o===$.length?w:g):s(M)}function w(M){return M===null?s(M):M===93?(e.consume(M),v):en(M)?(l=w,Y(M)):(e.consume(M),w)}function v(M){return M===93?(e.consume(M),b):w(M)}function b(M){return M===62?q(M):M===93?(e.consume(M),b):w(M)}function y(M){return M===null||M===62?q(M):en(M)?(l=y,Y(M)):(e.consume(M),y)}function j(M){return M===null?s(M):M===63?(e.consume(M),S):en(M)?(l=j,Y(M)):(e.consume(M),j)}function S(M){return M===62?q(M):j(M)}function C(M){return Fs(M)?(e.consume(M),x):s(M)}function x(M){return M===45||Ts(M)?(e.consume(M),x):k(M)}function k(M){return en(M)?(l=k,Y(M)):jn(M)?(e.consume(M),k):q(M)}function R(M){return M===45||Ts(M)?(e.consume(M),R):M===47||M===62||Yn(M)?O(M):s(M)}function O(M){return M===47?(e.consume(M),q):M===58||M===95||Fs(M)?(e.consume(M),E):en(M)?(l=O,Y(M)):jn(M)?(e.consume(M),O):q(M)}function E(M){return M===45||M===46||M===58||M===95||Ts(M)?(e.consume(M),E):_(M)}function _(M){return M===61?(e.consume(M),G):en(M)?(l=_,Y(M)):jn(M)?(e.consume(M),_):O(M)}function G(M){return M===null||M===60||M===61||M===62||M===96?s(M):M===34||M===39?(e.consume(M),r=M,H):en(M)?(l=G,Y(M)):jn(M)?(e.consume(M),G):(e.consume(M),A)}function H(M){return M===r?(e.consume(M),r=void 0,P):M===null?s(M):en(M)?(l=H,Y(M)):(e.consume(M),H)}function A(M){return M===null||M===34||M===39||M===60||M===61||M===96?s(M):M===47||M===62||Yn(M)?O(M):(e.consume(M),A)}function P(M){return M===47||M===62||Yn(M)?O(M):s(M)}function q(M){return M===62?(e.consume(M),e.exit("htmlTextData"),e.exit("htmlText"),n):s(M)}function Y(M){return e.exit("htmlTextData"),e.enter("lineEnding"),e.consume(M),e.exit("lineEnding"),ge}function ge(M){return jn(M)?Mn(e,L,"linePrefix",a.parser.constructs.disable.null.includes("codeIndented")?void 0:4)(M):L(M)}function L(M){return e.enter("htmlTextData"),l(M)}}const fm={name:"labelEnd",resolveAll:xM,resolveTo:vM,tokenize:yM},fM={tokenize:wM},gM={tokenize:kM},bM={tokenize:jM};function xM(e){let n=-1;const s=[];for(;++n<e.length;){const a=e[n][1];if(s.push(e[n]),a.type==="labelImage"||a.type==="labelLink"||a.type==="labelEnd"){const r=a.type==="labelImage"?4:2;a.type="data",n+=r}}return e.length!==s.length&&Xs(e,0,e.length,s),e}function vM(e,n){let s=e.length,a=0,r,o,l,c;for(;s--;)if(r=e[s][1],o){if(r.type==="link"||r.type==="labelLink"&&r._inactive)break;e[s][0]==="enter"&&r.type==="labelLink"&&(r._inactive=!0)}else if(l){if(e[s][0]==="enter"&&(r.type==="labelImage"||r.type==="labelLink")&&!r._balanced&&(o=s,r.type!=="labelLink")){a=2;break}}else r.type==="labelEnd"&&(l=s);const d={type:e[o][1].type==="labelLink"?"link":"image",start:{...e[o][1].start},end:{...e[e.length-1][1].end}},u={type:"label",start:{...e[o][1].start},end:{...e[l][1].end}},h={type:"labelText",start:{...e[o+a+2][1].end},end:{...e[l-2][1].start}};return c=[["enter",d,n],["enter",u,n]],c=ci(c,e.slice(o+1,o+a+3)),c=ci(c,[["enter",h,n]]),c=ci(c,Ac(n.parser.constructs.insideSpan.null,e.slice(o+a+4,l-3),n)),c=ci(c,[["exit",h,n],e[l-2],e[l-1],["exit",u,n]]),c=ci(c,e.slice(l+1)),c=ci(c,[["exit",d,n]]),Xs(e,o,e.length,c),e}function yM(e,n,s){const a=this;let r=a.events.length,o,l;for(;r--;)if((a.events[r][1].type==="labelImage"||a.events[r][1].type==="labelLink")&&!a.events[r][1]._balanced){o=a.events[r][1];break}return c;function c(f){return o?o._inactive?m(f):(l=a.parser.defined.includes(ji(a.sliceSerialize({start:o.end,end:a.now()}))),e.enter("labelEnd"),e.enter("labelMarker"),e.consume(f),e.exit("labelMarker"),e.exit("labelEnd"),d):s(f)}function d(f){return f===40?e.attempt(fM,h,l?h:m)(f):f===91?e.attempt(gM,h,l?u:m)(f):l?h(f):m(f)}function u(f){return e.attempt(bM,h,m)(f)}function h(f){return n(f)}function m(f){return o._balanced=!0,s(f)}}function wM(e,n,s){return a;function a(m){return e.enter("resource"),e.enter("resourceMarker"),e.consume(m),e.exit("resourceMarker"),r}function r(m){return Yn(m)?Io(e,o)(m):o(m)}function o(m){return m===41?h(m):Ax(e,l,c,"resourceDestination","resourceDestinationLiteral","resourceDestinationLiteralMarker","resourceDestinationRaw","resourceDestinationString",32)(m)}function l(m){return Yn(m)?Io(e,d)(m):h(m)}function c(m){return s(m)}function d(m){return m===34||m===39||m===40?Ix(e,u,s,"resourceTitle","resourceTitleMarker","resourceTitleString")(m):h(m)}function u(m){return Yn(m)?Io(e,h)(m):h(m)}function h(m){return m===41?(e.enter("resourceMarker"),e.consume(m),e.exit("resourceMarker"),e.exit("resource"),n):s(m)}}function kM(e,n,s){const a=this;return r;function r(c){return Rx.call(a,e,o,l,"reference","referenceMarker","referenceString")(c)}function o(c){return a.parser.defined.includes(ji(a.sliceSerialize(a.events[a.events.length-1][1]).slice(1,-1)))?n(c):s(c)}function l(c){return s(c)}}function jM(e,n,s){return a;function a(o){return e.enter("reference"),e.enter("referenceMarker"),e.consume(o),e.exit("referenceMarker"),r}function r(o){return o===93?(e.enter("referenceMarker"),e.consume(o),e.exit("referenceMarker"),e.exit("reference"),n):s(o)}}const NM={name:"labelStartImage",resolveAll:fm.resolveAll,tokenize:SM};function SM(e,n,s){const a=this;return r;function r(c){return e.enter("labelImage"),e.enter("labelImageMarker"),e.consume(c),e.exit("labelImageMarker"),o}function o(c){return c===91?(e.enter("labelMarker"),e.consume(c),e.exit("labelMarker"),e.exit("labelImage"),l):s(c)}function l(c){return c===94&&"_hiddenFootnoteSupport"in a.parser.constructs?s(c):n(c)}}const CM={name:"labelStartLink",resolveAll:fm.resolveAll,tokenize:EM};function EM(e,n,s){const a=this;return r;function r(l){return e.enter("labelLink"),e.enter("labelMarker"),e.consume(l),e.exit("labelMarker"),e.exit("labelLink"),o}function o(l){return l===94&&"_hiddenFootnoteSupport"in a.parser.constructs?s(l):n(l)}}const hd={name:"lineEnding",tokenize:_M};function _M(e,n){return s;function s(a){return e.enter("lineEnding"),e.consume(a),e.exit("lineEnding"),Mn(e,n,"linePrefix")}}const ql={name:"thematicBreak",tokenize:MM};function MM(e,n,s){let a=0,r;return o;function o(u){return e.enter("thematicBreak"),l(u)}function l(u){return r=u,c(u)}function c(u){return u===r?(e.enter("thematicBreakSequence"),d(u)):a>=3&&(u===null||en(u))?(e.exit("thematicBreak"),n(u)):s(u)}function d(u){return u===r?(e.consume(u),a++,d):(e.exit("thematicBreakSequence"),jn(u)?Mn(e,c,"whitespace")(u):c(u))}}const qs={continuation:{tokenize:TM},exit:$M,name:"list",tokenize:IM},AM={partial:!0,tokenize:DM},RM={partial:!0,tokenize:PM};function IM(e,n,s){const a=this,r=a.events[a.events.length-1];let o=r&&r[1].type==="linePrefix"?r[2].sliceSerialize(r[1],!0).length:0,l=0;return c;function c(p){const g=a.containerState.type||(p===42||p===43||p===45?"listUnordered":"listOrdered");if(g==="listUnordered"?!a.containerState.marker||p===a.containerState.marker:Nu(p)){if(a.containerState.type||(a.containerState.type=g,e.enter(g,{_container:!0})),g==="listUnordered")return e.enter("listItemPrefix"),p===42||p===45?e.check(ql,s,u)(p):u(p);if(!a.interrupt||p===49)return e.enter("listItemPrefix"),e.enter("listItemValue"),d(p)}return s(p)}function d(p){return Nu(p)&&++l<10?(e.consume(p),d):(!a.interrupt||l<2)&&(a.containerState.marker?p===a.containerState.marker:p===41||p===46)?(e.exit("listItemValue"),u(p)):s(p)}function u(p){return e.enter("listItemMarker"),e.consume(p),e.exit("listItemMarker"),a.containerState.marker=a.containerState.marker||p,e.check(tl,a.interrupt?s:h,e.attempt(AM,f,m))}function h(p){return a.containerState.initialBlankLine=!0,o++,f(p)}function m(p){return jn(p)?(e.enter("listItemPrefixWhitespace"),e.consume(p),e.exit("listItemPrefixWhitespace"),f):s(p)}function f(p){return a.containerState.size=o+a.sliceSerialize(e.exit("listItemPrefix"),!0).length,n(p)}}function TM(e,n,s){const a=this;return a.containerState._closeFlow=void 0,e.check(tl,r,o);function r(c){return a.containerState.furtherBlankLines=a.containerState.furtherBlankLines||a.containerState.initialBlankLine,Mn(e,n,"listItemIndent",a.containerState.size+1)(c)}function o(c){return a.containerState.furtherBlankLines||!jn(c)?(a.containerState.furtherBlankLines=void 0,a.containerState.initialBlankLine=void 0,l(c)):(a.containerState.furtherBlankLines=void 0,a.containerState.initialBlankLine=void 0,e.attempt(RM,n,l)(c))}function l(c){return a.containerState._closeFlow=!0,a.interrupt=void 0,Mn(e,e.attempt(qs,n,s),"linePrefix",a.parser.constructs.disable.null.includes("codeIndented")?void 0:4)(c)}}function PM(e,n,s){const a=this;return Mn(e,r,"listItemIndent",a.containerState.size+1);function r(o){const l=a.events[a.events.length-1];return l&&l[1].type==="listItemIndent"&&l[2].sliceSerialize(l[1],!0).length===a.containerState.size?n(o):s(o)}}function $M(e){e.exit(this.containerState.type)}function DM(e,n,s){const a=this;return Mn(e,r,"listItemPrefixWhitespace",a.parser.constructs.disable.null.includes("codeIndented")?void 0:5);function r(o){const l=a.events[a.events.length-1];return!jn(o)&&l&&l[1].type==="listItemPrefixWhitespace"?n(o):s(o)}}const yp={name:"setextUnderline",resolveTo:LM,tokenize:OM};function LM(e,n){let s=e.length,a,r,o;for(;s--;)if(e[s][0]==="enter"){if(e[s][1].type==="content"){a=s;break}e[s][1].type==="paragraph"&&(r=s)}else e[s][1].type==="content"&&e.splice(s,1),!o&&e[s][1].type==="definition"&&(o=s);const l={type:"setextHeading",start:{...e[a][1].start},end:{...e[e.length-1][1].end}};return e[r][1].type="setextHeadingText",o?(e.splice(r,0,["enter",l,n]),e.splice(o+1,0,["exit",e[a][1],n]),e[a][1].end={...e[o][1].end}):e[a][1]=l,e.push(["exit",l,n]),e}function OM(e,n,s){const a=this;let r;return o;function o(u){let h=a.events.length,m;for(;h--;)if(a.events[h][1].type!=="lineEnding"&&a.events[h][1].type!=="linePrefix"&&a.events[h][1].type!=="content"){m=a.events[h][1].type==="paragraph";break}return!a.parser.lazy[a.now().line]&&(a.interrupt||m)?(e.enter("setextHeadingLine"),r=u,l(u)):s(u)}function l(u){return e.enter("setextHeadingLineSequence"),c(u)}function c(u){return u===r?(e.consume(u),c):(e.exit("setextHeadingLineSequence"),jn(u)?Mn(e,d,"lineSuffix")(u):d(u))}function d(u){return u===null||en(u)?(e.exit("setextHeadingLine"),n(u)):s(u)}}const FM={tokenize:zM};function zM(e){const n=this,s=e.attempt(tl,a,e.attempt(this.parser.constructs.flowInitial,r,Mn(e,e.attempt(this.parser.constructs.flow,r,e.attempt(V2,r)),"linePrefix")));return s;function a(o){if(o===null){e.consume(o);return}return e.enter("lineEndingBlank"),e.consume(o),e.exit("lineEndingBlank"),n.currentConstruct=void 0,s}function r(o){if(o===null){e.consume(o);return}return e.enter("lineEnding"),e.consume(o),e.exit("lineEnding"),n.currentConstruct=void 0,s}}const BM={resolveAll:Px()},UM=Tx("string"),HM=Tx("text");function Tx(e){return{resolveAll:Px(e==="text"?qM:void 0),tokenize:n};function n(s){const a=this,r=this.parser.constructs[e],o=s.attempt(r,l,c);return l;function l(h){return u(h)?o(h):c(h)}function c(h){if(h===null){s.consume(h);return}return s.enter("data"),s.consume(h),d}function d(h){return u(h)?(s.exit("data"),o(h)):(s.consume(h),d)}function u(h){if(h===null)return!0;const m=r[h];let f=-1;if(m)for(;++f<m.length;){const p=m[f];if(!p.previous||p.previous.call(a,a.previous))return!0}return!1}}}function Px(e){return n;function n(s,a){let r=-1,o;for(;++r<=s.length;)o===void 0?s[r]&&s[r][1].type==="data"&&(o=r,r++):(!s[r]||s[r][1].type!=="data")&&(r!==o+2&&(s[o][1].end=s[r-1][1].end,s.splice(o+2,r-o-2),r=o+2),o=void 0);return e?e(s,a):s}}function qM(e,n){let s=0;for(;++s<=e.length;)if((s===e.length||e[s][1].type==="lineEnding")&&e[s-1][1].type==="data"){const a=e[s-1][1],r=n.sliceStream(a);let o=r.length,l=-1,c=0,d;for(;o--;){const u=r[o];if(typeof u=="string"){for(l=u.length;u.charCodeAt(l-1)===32;)c++,l--;if(l)break;l=-1}else if(u===-2)d=!0,c++;else if(u!==-1){o++;break}}if(n._contentTypeTextTrailing&&s===e.length&&(c=0),c){const u={type:s===e.length||d||c<2?"lineSuffix":"hardBreakTrailing",start:{_bufferIndex:o?l:a.start._bufferIndex+l,_index:a.start._index+o,line:a.end.line,column:a.end.column-c,offset:a.end.offset-c},end:{...a.end}};a.end={...u.start},a.start.offset===a.end.offset?Object.assign(a,u):(e.splice(s,0,["enter",u,n],["exit",u,n]),s+=2)}s++}return e}const VM={42:qs,43:qs,45:qs,48:qs,49:qs,50:qs,51:qs,52:qs,53:qs,54:qs,55:qs,56:qs,57:qs,62:Cx},WM={91:Y2},GM={[-2]:md,[-1]:md,32:md},KM={35:nM,42:ql,45:[yp,ql],60:rM,61:yp,95:ql,96:xp,126:xp},JM={38:_x,92:Ex},YM={[-5]:hd,[-4]:hd,[-3]:hd,33:NM,38:_x,42:Su,60:[C2,hM],91:CM,92:[eM,Ex],93:fm,95:Su,96:F2},QM={null:[Su,BM]},XM={null:[42,95]},ZM={null:[]},eA=Object.freeze(Object.defineProperty({__proto__:null,attentionMarkers:XM,contentInitial:WM,disable:ZM,document:VM,flow:KM,flowInitial:GM,insideSpan:QM,string:JM,text:YM},Symbol.toStringTag,{value:"Module"}));function tA(e,n,s){let a={_bufferIndex:-1,_index:0,line:s&&s.line||1,column:s&&s.column||1,offset:s&&s.offset||0};const r={},o=[];let l=[],c=[];const d={attempt:k(C),check:k(x),consume:y,enter:j,exit:S,interrupt:k(x,{interrupt:!0})},u={code:null,containerState:{},defineSkip:w,events:[],now:g,parser:e,previous:null,sliceSerialize:f,sliceStream:p,write:m};let h=n.tokenize.call(u,d);return n.resolveAll&&o.push(n),u;function m(_){return l=ci(l,_),v(),l[l.length-1]!==null?[]:(R(n,0),u.events=Ac(o,u.events,u),u.events)}function f(_,G){return sA(p(_),G)}function p(_){return nA(l,_)}function g(){const{_bufferIndex:_,_index:G,line:H,column:A,offset:P}=a;return{_bufferIndex:_,_index:G,line:H,column:A,offset:P}}function w(_){r[_.line]=_.column,E()}function v(){let _;for(;a._index<l.length;){const G=l[a._index];if(typeof G=="string")for(_=a._index,a._bufferIndex<0&&(a._bufferIndex=0);a._index===_&&a._bufferIndex<G.length;)b(G.charCodeAt(a._bufferIndex));else b(G)}}function b(_){h=h(_)}function y(_){en(_)?(a.line++,a.column=1,a.offset+=_===-3?2:1,E()):_!==-1&&(a.column++,a.offset++),a._bufferIndex<0?a._index++:(a._bufferIndex++,a._bufferIndex===l[a._index].length&&(a._bufferIndex=-1,a._index++)),u.previous=_}function j(_,G){const H=G||{};return H.type=_,H.start=g(),u.events.push(["enter",H,u]),c.push(H),H}function S(_){const G=c.pop();return G.end=g(),u.events.push(["exit",G,u]),G}function C(_,G){R(_,G.from)}function x(_,G){G.restore()}function k(_,G){return H;function H(A,P,q){let Y,ge,L,M;return Array.isArray(A)?D(A):"tokenize"in A?D([A]):$(A);function $(me){return Ne;function Ne(ve){const Me=ve!==null&&me[ve],ie=ve!==null&&me.null,ye=[...Array.isArray(Me)?Me:Me?[Me]:[],...Array.isArray(ie)?ie:ie?[ie]:[]];return D(ye)(ve)}}function D(me){return Y=me,ge=0,me.length===0?q:N(me[ge])}function N(me){return Ne;function Ne(ve){return M=O(),L=me,me.partial||(u.currentConstruct=me),me.name&&u.parser.constructs.disable.null.includes(me.name)?de():me.tokenize.call(G?Object.assign(Object.create(u),G):u,d,W,de)(ve)}}function W(me){return _(L,M),P}function de(me){return M.restore(),++ge<Y.length?N(Y[ge]):q}}}function R(_,G){_.resolveAll&&!o.includes(_)&&o.push(_),_.resolve&&Xs(u.events,G,u.events.length-G,_.resolve(u.events.slice(G),u)),_.resolveTo&&(u.events=_.resolveTo(u.events,u))}function O(){const _=g(),G=u.previous,H=u.currentConstruct,A=u.events.length,P=Array.from(c);return{from:A,restore:q};function q(){a=_,u.previous=G,u.currentConstruct=H,u.events.length=A,c=P,E()}}function E(){a.line in r&&a.column<2&&(a.column=r[a.line],a.offset+=r[a.line]-1)}}function nA(e,n){const s=n.start._index,a=n.start._bufferIndex,r=n.end._index,o=n.end._bufferIndex;let l;if(s===r)l=[e[s].slice(a,o)];else{if(l=e.slice(s,r),a>-1){const c=l[0];typeof c=="string"?l[0]=c.slice(a):l.shift()}o>0&&l.push(e[r].slice(0,o))}return l}function sA(e,n){let s=-1;const a=[];let r;for(;++s<e.length;){const o=e[s];let l;if(typeof o=="string")l=o;else switch(o){case-5:{l="\r";break}case-4:{l=`
655
- `;break}case-3:{l=`\r
656
- `;break}case-2:{l=n?" ":" ";break}case-1:{if(!n&&r)continue;l=" ";break}default:l=String.fromCharCode(o)}r=o===-2,a.push(l)}return a.join("")}function iA(e){const a={constructs:Nx([eA,...(e||{}).extensions||[]]),content:r(v2),defined:[],document:r(w2),flow:r(FM),lazy:{},string:r(UM),text:r(HM)};return a;function r(o){return l;function l(c){return tA(a,o,c)}}}function aA(e){for(;!Mx(e););return e}const wp=/[\0\t\n\r]/g;function rA(){let e=1,n="",s=!0,a;return r;function r(o,l,c){const d=[];let u,h,m,f,p;for(o=n+(typeof o=="string"?o.toString():new TextDecoder(l||void 0).decode(o)),m=0,n="",s&&(o.charCodeAt(0)===65279&&m++,s=void 0);m<o.length;){if(wp.lastIndex=m,u=wp.exec(o),f=u&&u.index!==void 0?u.index:o.length,p=o.charCodeAt(f),!u){n=o.slice(m);break}if(p===10&&m===f&&a)d.push(-3),a=void 0;else switch(a&&(d.push(-5),a=void 0),m<f&&(d.push(o.slice(m,f)),e+=f-m),p){case 0:{d.push(65533),e++;break}case 9:{for(h=Math.ceil(e/4)*4,d.push(-2);e++<h;)d.push(-1);break}case 10:{d.push(-4),e=1;break}default:a=!0,e=1}m=f+1}return c&&(a&&d.push(-5),n&&d.push(n),d.push(null)),d}}const oA=/\\([!-/:-@[-`{-~])|&(#(?:\d{1,7}|x[\da-f]{1,6})|[\da-z]{1,31});/gi;function lA(e){return e.replace(oA,cA)}function cA(e,n,s){if(n)return n;if(s.charCodeAt(0)===35){const r=s.charCodeAt(1),o=r===120||r===88;return Sx(s.slice(o?2:1),o?16:10)}return pm(s)||e}const $x={}.hasOwnProperty;function dA(e,n,s){return n&&typeof n=="object"&&(s=n,n=void 0),uA(s)(aA(iA(s).document().write(rA()(e,n,!0))))}function uA(e){const n={transforms:[],canContainEols:["emphasis","fragment","heading","paragraph","strong"],enter:{autolink:o(be),autolinkProtocol:O,autolinkEmail:O,atxHeading:o(F),blockQuote:o(ie),characterEscape:O,characterReference:O,codeFenced:o(ye),codeFencedFenceInfo:l,codeFencedFenceMeta:l,codeIndented:o(ye,l),codeText:o(Z,l),codeTextData:O,data:O,codeFlowValue:O,definition:o(fe),definitionDestinationString:l,definitionLabelString:l,definitionTitleString:l,emphasis:o(Q),hardBreakEscape:o(X),hardBreakTrailing:o(X),htmlFlow:o(re,l),htmlFlowData:O,htmlText:o(re,l),htmlTextData:O,image:o(U),label:l,link:o(be),listItem:o(se),listItemValue:f,listOrdered:o(Ue,m),listUnordered:o(Ue),paragraph:o(Ve),reference:N,referenceString:l,resourceDestinationString:l,resourceTitleString:l,setextHeading:o(F),strong:o(Le),thematicBreak:o(Ke)},exit:{atxHeading:d(),atxHeadingSequence:C,autolink:d(),autolinkEmail:Me,autolinkProtocol:ve,blockQuote:d(),characterEscapeValue:E,characterReferenceMarkerHexadecimal:de,characterReferenceMarkerNumeric:de,characterReferenceValue:me,characterReference:Ne,codeFenced:d(v),codeFencedFence:w,codeFencedFenceInfo:p,codeFencedFenceMeta:g,codeFlowValue:E,codeIndented:d(b),codeText:d(P),codeTextData:E,data:E,definition:d(),definitionDestinationString:S,definitionLabelString:y,definitionTitleString:j,emphasis:d(),hardBreakEscape:d(G),hardBreakTrailing:d(G),htmlFlow:d(H),htmlFlowData:E,htmlText:d(A),htmlTextData:E,image:d(Y),label:L,labelText:ge,lineEnding:_,link:d(q),listItem:d(),listOrdered:d(),listUnordered:d(),paragraph:d(),referenceString:W,resourceDestinationString:M,resourceTitleString:$,resource:D,setextHeading:d(R),setextHeadingLineSequence:k,setextHeadingText:x,strong:d(),thematicBreak:d()}};Dx(n,(e||{}).mdastExtensions||[]);const s={};return a;function a(oe){let Te={type:"root",children:[]};const Fe={stack:[Te],tokenStack:[],config:n,enter:c,exit:u,buffer:l,resume:h,data:s},mt=[];let We=-1;for(;++We<oe.length;)if(oe[We][1].type==="listOrdered"||oe[We][1].type==="listUnordered")if(oe[We][0]==="enter")mt.push(We);else{const he=mt.pop();We=r(oe,he,We)}for(We=-1;++We<oe.length;){const he=n[oe[We][0]];$x.call(he,oe[We][1].type)&&he[oe[We][1].type].call(Object.assign({sliceSerialize:oe[We][2].sliceSerialize},Fe),oe[We][1])}if(Fe.tokenStack.length>0){const he=Fe.tokenStack[Fe.tokenStack.length-1];(he[1]||kp).call(Fe,void 0,he[0])}for(Te.position={start:ca(oe.length>0?oe[0][1].start:{line:1,column:1,offset:0}),end:ca(oe.length>0?oe[oe.length-2][1].end:{line:1,column:1,offset:0})},We=-1;++We<n.transforms.length;)Te=n.transforms[We](Te)||Te;return Te}function r(oe,Te,Fe){let mt=Te-1,We=-1,he=!1,pe,De,ut,ht;for(;++mt<=Fe;){const et=oe[mt];switch(et[1].type){case"listUnordered":case"listOrdered":case"blockQuote":{et[0]==="enter"?We++:We--,ht=void 0;break}case"lineEndingBlank":{et[0]==="enter"&&(pe&&!ht&&!We&&!ut&&(ut=mt),ht=void 0);break}case"linePrefix":case"listItemValue":case"listItemMarker":case"listItemPrefix":case"listItemPrefixWhitespace":break;default:ht=void 0}if(!We&&et[0]==="enter"&&et[1].type==="listItemPrefix"||We===-1&&et[0]==="exit"&&(et[1].type==="listUnordered"||et[1].type==="listOrdered")){if(pe){let vt=mt;for(De=void 0;vt--;){const Oe=oe[vt];if(Oe[1].type==="lineEnding"||Oe[1].type==="lineEndingBlank"){if(Oe[0]==="exit")continue;De&&(oe[De][1].type="lineEndingBlank",he=!0),Oe[1].type="lineEnding",De=vt}else if(!(Oe[1].type==="linePrefix"||Oe[1].type==="blockQuotePrefix"||Oe[1].type==="blockQuotePrefixWhitespace"||Oe[1].type==="blockQuoteMarker"||Oe[1].type==="listItemIndent"))break}ut&&(!De||ut<De)&&(pe._spread=!0),pe.end=Object.assign({},De?oe[De][1].start:et[1].end),oe.splice(De||mt,0,["exit",pe,et[2]]),mt++,Fe++}if(et[1].type==="listItemPrefix"){const vt={type:"listItem",_spread:!1,start:Object.assign({},et[1].start),end:void 0};pe=vt,oe.splice(mt,0,["enter",vt,et[2]]),mt++,Fe++,ut=void 0,ht=!0}}}return oe[Te][1]._spread=he,Fe}function o(oe,Te){return Fe;function Fe(mt){c.call(this,oe(mt),mt),Te&&Te.call(this,mt)}}function l(){this.stack.push({type:"fragment",children:[]})}function c(oe,Te,Fe){this.stack[this.stack.length-1].children.push(oe),this.stack.push(oe),this.tokenStack.push([Te,Fe||void 0]),oe.position={start:ca(Te.start),end:void 0}}function d(oe){return Te;function Te(Fe){oe&&oe.call(this,Fe),u.call(this,Fe)}}function u(oe,Te){const Fe=this.stack.pop(),mt=this.tokenStack.pop();if(mt)mt[0].type!==oe.type&&(Te?Te.call(this,oe,mt[0]):(mt[1]||kp).call(this,oe,mt[0]));else throw new Error("Cannot close `"+oe.type+"` ("+Ro({start:oe.start,end:oe.end})+"): it’s not open");Fe.position.end=ca(oe.end)}function h(){return hm(this.stack.pop())}function m(){this.data.expectingFirstListItemValue=!0}function f(oe){if(this.data.expectingFirstListItemValue){const Te=this.stack[this.stack.length-2];Te.start=Number.parseInt(this.sliceSerialize(oe),10),this.data.expectingFirstListItemValue=void 0}}function p(){const oe=this.resume(),Te=this.stack[this.stack.length-1];Te.lang=oe}function g(){const oe=this.resume(),Te=this.stack[this.stack.length-1];Te.meta=oe}function w(){this.data.flowCodeInside||(this.buffer(),this.data.flowCodeInside=!0)}function v(){const oe=this.resume(),Te=this.stack[this.stack.length-1];Te.value=oe.replace(/^(\r?\n|\r)|(\r?\n|\r)$/g,""),this.data.flowCodeInside=void 0}function b(){const oe=this.resume(),Te=this.stack[this.stack.length-1];Te.value=oe.replace(/(\r?\n|\r)$/g,"")}function y(oe){const Te=this.resume(),Fe=this.stack[this.stack.length-1];Fe.label=Te,Fe.identifier=ji(this.sliceSerialize(oe)).toLowerCase()}function j(){const oe=this.resume(),Te=this.stack[this.stack.length-1];Te.title=oe}function S(){const oe=this.resume(),Te=this.stack[this.stack.length-1];Te.url=oe}function C(oe){const Te=this.stack[this.stack.length-1];if(!Te.depth){const Fe=this.sliceSerialize(oe).length;Te.depth=Fe}}function x(){this.data.setextHeadingSlurpLineEnding=!0}function k(oe){const Te=this.stack[this.stack.length-1];Te.depth=this.sliceSerialize(oe).codePointAt(0)===61?1:2}function R(){this.data.setextHeadingSlurpLineEnding=void 0}function O(oe){const Fe=this.stack[this.stack.length-1].children;let mt=Fe[Fe.length-1];(!mt||mt.type!=="text")&&(mt=ct(),mt.position={start:ca(oe.start),end:void 0},Fe.push(mt)),this.stack.push(mt)}function E(oe){const Te=this.stack.pop();Te.value+=this.sliceSerialize(oe),Te.position.end=ca(oe.end)}function _(oe){const Te=this.stack[this.stack.length-1];if(this.data.atHardBreak){const Fe=Te.children[Te.children.length-1];Fe.position.end=ca(oe.end),this.data.atHardBreak=void 0;return}!this.data.setextHeadingSlurpLineEnding&&n.canContainEols.includes(Te.type)&&(O.call(this,oe),E.call(this,oe))}function G(){this.data.atHardBreak=!0}function H(){const oe=this.resume(),Te=this.stack[this.stack.length-1];Te.value=oe}function A(){const oe=this.resume(),Te=this.stack[this.stack.length-1];Te.value=oe}function P(){const oe=this.resume(),Te=this.stack[this.stack.length-1];Te.value=oe}function q(){const oe=this.stack[this.stack.length-1];if(this.data.inReference){const Te=this.data.referenceType||"shortcut";oe.type+="Reference",oe.referenceType=Te,delete oe.url,delete oe.title}else delete oe.identifier,delete oe.label;this.data.referenceType=void 0}function Y(){const oe=this.stack[this.stack.length-1];if(this.data.inReference){const Te=this.data.referenceType||"shortcut";oe.type+="Reference",oe.referenceType=Te,delete oe.url,delete oe.title}else delete oe.identifier,delete oe.label;this.data.referenceType=void 0}function ge(oe){const Te=this.sliceSerialize(oe),Fe=this.stack[this.stack.length-2];Fe.label=lA(Te),Fe.identifier=ji(Te).toLowerCase()}function L(){const oe=this.stack[this.stack.length-1],Te=this.resume(),Fe=this.stack[this.stack.length-1];if(this.data.inReference=!0,Fe.type==="link"){const mt=oe.children;Fe.children=mt}else Fe.alt=Te}function M(){const oe=this.resume(),Te=this.stack[this.stack.length-1];Te.url=oe}function $(){const oe=this.resume(),Te=this.stack[this.stack.length-1];Te.title=oe}function D(){this.data.inReference=void 0}function N(){this.data.referenceType="collapsed"}function W(oe){const Te=this.resume(),Fe=this.stack[this.stack.length-1];Fe.label=Te,Fe.identifier=ji(this.sliceSerialize(oe)).toLowerCase(),this.data.referenceType="full"}function de(oe){this.data.characterReferenceType=oe.type}function me(oe){const Te=this.sliceSerialize(oe),Fe=this.data.characterReferenceType;let mt;Fe?(mt=Sx(Te,Fe==="characterReferenceMarkerNumeric"?10:16),this.data.characterReferenceType=void 0):mt=pm(Te);const We=this.stack[this.stack.length-1];We.value+=mt}function Ne(oe){const Te=this.stack.pop();Te.position.end=ca(oe.end)}function ve(oe){E.call(this,oe);const Te=this.stack[this.stack.length-1];Te.url=this.sliceSerialize(oe)}function Me(oe){E.call(this,oe);const Te=this.stack[this.stack.length-1];Te.url="mailto:"+this.sliceSerialize(oe)}function ie(){return{type:"blockquote",children:[]}}function ye(){return{type:"code",lang:null,meta:null,value:""}}function Z(){return{type:"inlineCode",value:""}}function fe(){return{type:"definition",identifier:"",label:null,title:null,url:""}}function Q(){return{type:"emphasis",children:[]}}function F(){return{type:"heading",depth:0,children:[]}}function X(){return{type:"break"}}function re(){return{type:"html",value:""}}function U(){return{type:"image",title:null,url:"",alt:null}}function be(){return{type:"link",title:null,url:"",children:[]}}function Ue(oe){return{type:"list",ordered:oe.type==="listOrdered",start:null,spread:oe._spread,children:[]}}function se(oe){return{type:"listItem",spread:oe._spread,checked:null,children:[]}}function Ve(){return{type:"paragraph",children:[]}}function Le(){return{type:"strong",children:[]}}function ct(){return{type:"text",value:""}}function Ke(){return{type:"thematicBreak"}}}function ca(e){return{line:e.line,column:e.column,offset:e.offset}}function Dx(e,n){let s=-1;for(;++s<n.length;){const a=n[s];Array.isArray(a)?Dx(e,a):mA(e,a)}}function mA(e,n){let s;for(s in n)if($x.call(n,s))switch(s){case"canContainEols":{const a=n[s];a&&e[s].push(...a);break}case"transforms":{const a=n[s];a&&e[s].push(...a);break}case"enter":case"exit":{const a=n[s];a&&Object.assign(e[s],a);break}}}function kp(e,n){throw e?new Error("Cannot close `"+e.type+"` ("+Ro({start:e.start,end:e.end})+"): a different token (`"+n.type+"`, "+Ro({start:n.start,end:n.end})+") is open"):new Error("Cannot close document, a token (`"+n.type+"`, "+Ro({start:n.start,end:n.end})+") is still open")}function hA(e){const n=this;n.parser=s;function s(a){return dA(a,{...n.data("settings"),...e,extensions:n.data("micromarkExtensions")||[],mdastExtensions:n.data("fromMarkdownExtensions")||[]})}}function pA(e,n){const s={type:"element",tagName:"blockquote",properties:{},children:e.wrap(e.all(n),!0)};return e.patch(n,s),e.applyData(n,s)}function fA(e,n){const s={type:"element",tagName:"br",properties:{},children:[]};return e.patch(n,s),[e.applyData(n,s),{type:"text",value:`
657
- `}]}function gA(e,n){const s=n.value?n.value+`
658
- `:"",a={},r=n.lang?n.lang.split(/\s+/):[];r.length>0&&(a.className=["language-"+r[0]]);let o={type:"element",tagName:"code",properties:a,children:[{type:"text",value:s}]};return n.meta&&(o.data={meta:n.meta}),e.patch(n,o),o=e.applyData(n,o),o={type:"element",tagName:"pre",properties:{},children:[o]},e.patch(n,o),o}function bA(e,n){const s={type:"element",tagName:"del",properties:{},children:e.all(n)};return e.patch(n,s),e.applyData(n,s)}function xA(e,n){const s={type:"element",tagName:"em",properties:{},children:e.all(n)};return e.patch(n,s),e.applyData(n,s)}function vA(e,n){const s=typeof e.options.clobberPrefix=="string"?e.options.clobberPrefix:"user-content-",a=String(n.identifier).toUpperCase(),r=Wr(a.toLowerCase()),o=e.footnoteOrder.indexOf(a);let l,c=e.footnoteCounts.get(a);c===void 0?(c=0,e.footnoteOrder.push(a),l=e.footnoteOrder.length):l=o+1,c+=1,e.footnoteCounts.set(a,c);const d={type:"element",tagName:"a",properties:{href:"#"+s+"fn-"+r,id:s+"fnref-"+r+(c>1?"-"+c:""),dataFootnoteRef:!0,ariaDescribedBy:["footnote-label"]},children:[{type:"text",value:String(l)}]};e.patch(n,d);const u={type:"element",tagName:"sup",properties:{},children:[d]};return e.patch(n,u),e.applyData(n,u)}function yA(e,n){const s={type:"element",tagName:"h"+n.depth,properties:{},children:e.all(n)};return e.patch(n,s),e.applyData(n,s)}function wA(e,n){if(e.options.allowDangerousHtml){const s={type:"raw",value:n.value};return e.patch(n,s),e.applyData(n,s)}}function Lx(e,n){const s=n.referenceType;let a="]";if(s==="collapsed"?a+="[]":s==="full"&&(a+="["+(n.label||n.identifier)+"]"),n.type==="imageReference")return[{type:"text",value:"!["+n.alt+a}];const r=e.all(n),o=r[0];o&&o.type==="text"?o.value="["+o.value:r.unshift({type:"text",value:"["});const l=r[r.length-1];return l&&l.type==="text"?l.value+=a:r.push({type:"text",value:a}),r}function kA(e,n){const s=String(n.identifier).toUpperCase(),a=e.definitionById.get(s);if(!a)return Lx(e,n);const r={src:Wr(a.url||""),alt:n.alt};a.title!==null&&a.title!==void 0&&(r.title=a.title);const o={type:"element",tagName:"img",properties:r,children:[]};return e.patch(n,o),e.applyData(n,o)}function jA(e,n){const s={src:Wr(n.url)};n.alt!==null&&n.alt!==void 0&&(s.alt=n.alt),n.title!==null&&n.title!==void 0&&(s.title=n.title);const a={type:"element",tagName:"img",properties:s,children:[]};return e.patch(n,a),e.applyData(n,a)}function NA(e,n){const s={type:"text",value:n.value.replace(/\r?\n|\r/g," ")};e.patch(n,s);const a={type:"element",tagName:"code",properties:{},children:[s]};return e.patch(n,a),e.applyData(n,a)}function SA(e,n){const s=String(n.identifier).toUpperCase(),a=e.definitionById.get(s);if(!a)return Lx(e,n);const r={href:Wr(a.url||"")};a.title!==null&&a.title!==void 0&&(r.title=a.title);const o={type:"element",tagName:"a",properties:r,children:e.all(n)};return e.patch(n,o),e.applyData(n,o)}function CA(e,n){const s={href:Wr(n.url)};n.title!==null&&n.title!==void 0&&(s.title=n.title);const a={type:"element",tagName:"a",properties:s,children:e.all(n)};return e.patch(n,a),e.applyData(n,a)}function EA(e,n,s){const a=e.all(n),r=s?_A(s):Ox(n),o={},l=[];if(typeof n.checked=="boolean"){const h=a[0];let m;h&&h.type==="element"&&h.tagName==="p"?m=h:(m={type:"element",tagName:"p",properties:{},children:[]},a.unshift(m)),m.children.length>0&&m.children.unshift({type:"text",value:" "}),m.children.unshift({type:"element",tagName:"input",properties:{type:"checkbox",checked:n.checked,disabled:!0},children:[]}),o.className=["task-list-item"]}let c=-1;for(;++c<a.length;){const h=a[c];(r||c!==0||h.type!=="element"||h.tagName!=="p")&&l.push({type:"text",value:`
659
- `}),h.type==="element"&&h.tagName==="p"&&!r?l.push(...h.children):l.push(h)}const d=a[a.length-1];d&&(r||d.type!=="element"||d.tagName!=="p")&&l.push({type:"text",value:`
660
- `});const u={type:"element",tagName:"li",properties:o,children:l};return e.patch(n,u),e.applyData(n,u)}function _A(e){let n=!1;if(e.type==="list"){n=e.spread||!1;const s=e.children;let a=-1;for(;!n&&++a<s.length;)n=Ox(s[a])}return n}function Ox(e){const n=e.spread;return n??e.children.length>1}function MA(e,n){const s={},a=e.all(n);let r=-1;for(typeof n.start=="number"&&n.start!==1&&(s.start=n.start);++r<a.length;){const l=a[r];if(l.type==="element"&&l.tagName==="li"&&l.properties&&Array.isArray(l.properties.className)&&l.properties.className.includes("task-list-item")){s.className=["contains-task-list"];break}}const o={type:"element",tagName:n.ordered?"ol":"ul",properties:s,children:e.wrap(a,!0)};return e.patch(n,o),e.applyData(n,o)}function AA(e,n){const s={type:"element",tagName:"p",properties:{},children:e.all(n)};return e.patch(n,s),e.applyData(n,s)}function RA(e,n){const s={type:"root",children:e.wrap(e.all(n))};return e.patch(n,s),e.applyData(n,s)}function IA(e,n){const s={type:"element",tagName:"strong",properties:{},children:e.all(n)};return e.patch(n,s),e.applyData(n,s)}function TA(e,n){const s=e.all(n),a=s.shift(),r=[];if(a){const l={type:"element",tagName:"thead",properties:{},children:e.wrap([a],!0)};e.patch(n.children[0],l),r.push(l)}if(s.length>0){const l={type:"element",tagName:"tbody",properties:{},children:e.wrap(s,!0)},c=cm(n.children[1]),d=bx(n.children[n.children.length-1]);c&&d&&(l.position={start:c,end:d}),r.push(l)}const o={type:"element",tagName:"table",properties:{},children:e.wrap(r,!0)};return e.patch(n,o),e.applyData(n,o)}function PA(e,n,s){const a=s?s.children:void 0,o=(a?a.indexOf(n):1)===0?"th":"td",l=s&&s.type==="table"?s.align:void 0,c=l?l.length:n.children.length;let d=-1;const u=[];for(;++d<c;){const m=n.children[d],f={},p=l?l[d]:void 0;p&&(f.align=p);let g={type:"element",tagName:o,properties:f,children:[]};m&&(g.children=e.all(m),e.patch(m,g),g=e.applyData(m,g)),u.push(g)}const h={type:"element",tagName:"tr",properties:{},children:e.wrap(u,!0)};return e.patch(n,h),e.applyData(n,h)}function $A(e,n){const s={type:"element",tagName:"td",properties:{},children:e.all(n)};return e.patch(n,s),e.applyData(n,s)}const jp=9,Np=32;function DA(e){const n=String(e),s=/\r?\n|\r/g;let a=s.exec(n),r=0;const o=[];for(;a;)o.push(Sp(n.slice(r,a.index),r>0,!0),a[0]),r=a.index+a[0].length,a=s.exec(n);return o.push(Sp(n.slice(r),r>0,!1)),o.join("")}function Sp(e,n,s){let a=0,r=e.length;if(n){let o=e.codePointAt(a);for(;o===jp||o===Np;)a++,o=e.codePointAt(a)}if(s){let o=e.codePointAt(r-1);for(;o===jp||o===Np;)r--,o=e.codePointAt(r-1)}return r>a?e.slice(a,r):""}function LA(e,n){const s={type:"text",value:DA(String(n.value))};return e.patch(n,s),e.applyData(n,s)}function OA(e,n){const s={type:"element",tagName:"hr",properties:{},children:[]};return e.patch(n,s),e.applyData(n,s)}const FA={blockquote:pA,break:fA,code:gA,delete:bA,emphasis:xA,footnoteReference:vA,heading:yA,html:wA,imageReference:kA,image:jA,inlineCode:NA,linkReference:SA,link:CA,listItem:EA,list:MA,paragraph:AA,root:RA,strong:IA,table:TA,tableCell:$A,tableRow:PA,text:LA,thematicBreak:OA,toml:hl,yaml:hl,definition:hl,footnoteDefinition:hl};function hl(){}const Fx=-1,Rc=0,To=1,ic=2,gm=3,bm=4,xm=5,vm=6,zx=7,Bx=8,Cp=typeof self=="object"?self:globalThis,zA=(e,n)=>{const s=(r,o)=>(e.set(o,r),r),a=r=>{if(e.has(r))return e.get(r);const[o,l]=n[r];switch(o){case Rc:case Fx:return s(l,r);case To:{const c=s([],r);for(const d of l)c.push(a(d));return c}case ic:{const c=s({},r);for(const[d,u]of l)c[a(d)]=a(u);return c}case gm:return s(new Date(l),r);case bm:{const{source:c,flags:d}=l;return s(new RegExp(c,d),r)}case xm:{const c=s(new Map,r);for(const[d,u]of l)c.set(a(d),a(u));return c}case vm:{const c=s(new Set,r);for(const d of l)c.add(a(d));return c}case zx:{const{name:c,message:d}=l;return s(new Cp[c](d),r)}case Bx:return s(BigInt(l),r);case"BigInt":return s(Object(BigInt(l)),r);case"ArrayBuffer":return s(new Uint8Array(l).buffer,l);case"DataView":{const{buffer:c}=new Uint8Array(l);return s(new DataView(c),l)}}return s(new Cp[o](l),r)};return a},Ep=e=>zA(new Map,e)(0),mr="",{toString:BA}={},{keys:UA}=Object,oo=e=>{const n=typeof e;if(n!=="object"||!e)return[Rc,n];const s=BA.call(e).slice(8,-1);switch(s){case"Array":return[To,mr];case"Object":return[ic,mr];case"Date":return[gm,mr];case"RegExp":return[bm,mr];case"Map":return[xm,mr];case"Set":return[vm,mr];case"DataView":return[To,s]}return s.includes("Array")?[To,s]:s.includes("Error")?[zx,s]:[ic,s]},pl=([e,n])=>e===Rc&&(n==="function"||n==="symbol"),HA=(e,n,s,a)=>{const r=(l,c)=>{const d=a.push(l)-1;return s.set(c,d),d},o=l=>{if(s.has(l))return s.get(l);let[c,d]=oo(l);switch(c){case Rc:{let h=l;switch(d){case"bigint":c=Bx,h=l.toString();break;case"function":case"symbol":if(e)throw new TypeError("unable to serialize "+d);h=null;break;case"undefined":return r([Fx],l)}return r([c,h],l)}case To:{if(d){let f=l;return d==="DataView"?f=new Uint8Array(l.buffer):d==="ArrayBuffer"&&(f=new Uint8Array(l)),r([d,[...f]],l)}const h=[],m=r([c,h],l);for(const f of l)h.push(o(f));return m}case ic:{if(d)switch(d){case"BigInt":return r([d,l.toString()],l);case"Boolean":case"Number":case"String":return r([d,l.valueOf()],l)}if(n&&"toJSON"in l)return o(l.toJSON());const h=[],m=r([c,h],l);for(const f of UA(l))(e||!pl(oo(l[f])))&&h.push([o(f),o(l[f])]);return m}case gm:return r([c,l.toISOString()],l);case bm:{const{source:h,flags:m}=l;return r([c,{source:h,flags:m}],l)}case xm:{const h=[],m=r([c,h],l);for(const[f,p]of l)(e||!(pl(oo(f))||pl(oo(p))))&&h.push([o(f),o(p)]);return m}case vm:{const h=[],m=r([c,h],l);for(const f of l)(e||!pl(oo(f)))&&h.push(o(f));return m}}const{message:u}=l;return r([c,{name:d,message:u}],l)};return o},_p=(e,{json:n,lossy:s}={})=>{const a=[];return HA(!(n||s),!!n,new Map,a)(e),a},ac=typeof structuredClone=="function"?(e,n)=>n&&("json"in n||"lossy"in n)?Ep(_p(e,n)):structuredClone(e):(e,n)=>Ep(_p(e,n));function qA(e,n){const s=[{type:"text",value:"↩"}];return n>1&&s.push({type:"element",tagName:"sup",properties:{},children:[{type:"text",value:String(n)}]}),s}function VA(e,n){return"Back to reference "+(e+1)+(n>1?"-"+n:"")}function WA(e){const n=typeof e.options.clobberPrefix=="string"?e.options.clobberPrefix:"user-content-",s=e.options.footnoteBackContent||qA,a=e.options.footnoteBackLabel||VA,r=e.options.footnoteLabel||"Footnotes",o=e.options.footnoteLabelTagName||"h2",l=e.options.footnoteLabelProperties||{className:["sr-only"]},c=[];let d=-1;for(;++d<e.footnoteOrder.length;){const u=e.footnoteById.get(e.footnoteOrder[d]);if(!u)continue;const h=e.all(u),m=String(u.identifier).toUpperCase(),f=Wr(m.toLowerCase());let p=0;const g=[],w=e.footnoteCounts.get(m);for(;w!==void 0&&++p<=w;){g.length>0&&g.push({type:"text",value:" "});let y=typeof s=="string"?s:s(d,p);typeof y=="string"&&(y={type:"text",value:y}),g.push({type:"element",tagName:"a",properties:{href:"#"+n+"fnref-"+f+(p>1?"-"+p:""),dataFootnoteBackref:"",ariaLabel:typeof a=="string"?a:a(d,p),className:["data-footnote-backref"]},children:Array.isArray(y)?y:[y]})}const v=h[h.length-1];if(v&&v.type==="element"&&v.tagName==="p"){const y=v.children[v.children.length-1];y&&y.type==="text"?y.value+=" ":v.children.push({type:"text",value:" "}),v.children.push(...g)}else h.push(...g);const b={type:"element",tagName:"li",properties:{id:n+"fn-"+f},children:e.wrap(h,!0)};e.patch(u,b),c.push(b)}if(c.length!==0)return{type:"element",tagName:"section",properties:{dataFootnotes:!0,className:["footnotes"]},children:[{type:"element",tagName:o,properties:{...ac(l),id:"footnote-label"},children:[{type:"text",value:r}]},{type:"text",value:`
661
- `},{type:"element",tagName:"ol",properties:{},children:e.wrap(c,!0)},{type:"text",value:`
662
- `}]}}const Ic=(function(e){if(e==null)return YA;if(typeof e=="function")return Tc(e);if(typeof e=="object")return Array.isArray(e)?GA(e):KA(e);if(typeof e=="string")return JA(e);throw new Error("Expected function, string, or object as test")});function GA(e){const n=[];let s=-1;for(;++s<e.length;)n[s]=Ic(e[s]);return Tc(a);function a(...r){let o=-1;for(;++o<n.length;)if(n[o].apply(this,r))return!0;return!1}}function KA(e){const n=e;return Tc(s);function s(a){const r=a;let o;for(o in e)if(r[o]!==n[o])return!1;return!0}}function JA(e){return Tc(n);function n(s){return s&&s.type===e}}function Tc(e){return n;function n(s,a,r){return!!(QA(s)&&e.call(this,s,typeof a=="number"?a:void 0,r||void 0))}}function YA(){return!0}function QA(e){return e!==null&&typeof e=="object"&&"type"in e}const Ux=[],XA=!0,Cu=!1,ZA="skip";function Hx(e,n,s,a){let r;typeof n=="function"&&typeof s!="function"?(a=s,s=n):r=n;const o=Ic(r),l=a?-1:1;c(e,void 0,[])();function c(d,u,h){const m=d&&typeof d=="object"?d:{};if(typeof m.type=="string"){const p=typeof m.tagName=="string"?m.tagName:typeof m.name=="string"?m.name:void 0;Object.defineProperty(f,"name",{value:"node ("+(d.type+(p?"<"+p+">":""))+")"})}return f;function f(){let p=Ux,g,w,v;if((!n||o(d,u,h[h.length-1]||void 0))&&(p=eR(s(d,h)),p[0]===Cu))return p;if("children"in d&&d.children){const b=d;if(b.children&&p[0]!==ZA)for(w=(a?b.children.length:-1)+l,v=h.concat(b);w>-1&&w<b.children.length;){const y=b.children[w];if(g=c(y,w,v)(),g[0]===Cu)return g;w=typeof g[1]=="number"?g[1]:w+l}}return p}}}function eR(e){return Array.isArray(e)?e:typeof e=="number"?[XA,e]:e==null?Ux:[e]}function ym(e,n,s,a){let r,o,l;typeof n=="function"&&typeof s!="function"?(o=void 0,l=n,r=s):(o=n,l=s,r=a),Hx(e,o,c,r);function c(d,u){const h=u[u.length-1],m=h?h.children.indexOf(d):void 0;return l(d,m,h)}}const Eu={}.hasOwnProperty,tR={};function nR(e,n){const s=n||tR,a=new Map,r=new Map,o=new Map,l={...FA,...s.handlers},c={all:u,applyData:iR,definitionById:a,footnoteById:r,footnoteCounts:o,footnoteOrder:[],handlers:l,one:d,options:s,patch:sR,wrap:rR};return ym(e,function(h){if(h.type==="definition"||h.type==="footnoteDefinition"){const m=h.type==="definition"?a:r,f=String(h.identifier).toUpperCase();m.has(f)||m.set(f,h)}}),c;function d(h,m){const f=h.type,p=c.handlers[f];if(Eu.call(c.handlers,f)&&p)return p(c,h,m);if(c.options.passThrough&&c.options.passThrough.includes(f)){if("children"in h){const{children:w,...v}=h,b=ac(v);return b.children=c.all(h),b}return ac(h)}return(c.options.unknownHandler||aR)(c,h,m)}function u(h){const m=[];if("children"in h){const f=h.children;let p=-1;for(;++p<f.length;){const g=c.one(f[p],h);if(g){if(p&&f[p-1].type==="break"&&(!Array.isArray(g)&&g.type==="text"&&(g.value=Mp(g.value)),!Array.isArray(g)&&g.type==="element")){const w=g.children[0];w&&w.type==="text"&&(w.value=Mp(w.value))}Array.isArray(g)?m.push(...g):m.push(g)}}}return m}}function sR(e,n){e.position&&(n.position=V_(e))}function iR(e,n){let s=n;if(e&&e.data){const a=e.data.hName,r=e.data.hChildren,o=e.data.hProperties;if(typeof a=="string")if(s.type==="element")s.tagName=a;else{const l="children"in s?s.children:[s];s={type:"element",tagName:a,properties:{},children:l}}s.type==="element"&&o&&Object.assign(s.properties,ac(o)),"children"in s&&s.children&&r!==null&&r!==void 0&&(s.children=r)}return s}function aR(e,n){const s=n.data||{},a="value"in n&&!(Eu.call(s,"hProperties")||Eu.call(s,"hChildren"))?{type:"text",value:n.value}:{type:"element",tagName:"div",properties:{},children:e.all(n)};return e.patch(n,a),e.applyData(n,a)}function rR(e,n){const s=[];let a=-1;for(n&&s.push({type:"text",value:`
663
- `});++a<e.length;)a&&s.push({type:"text",value:`
664
- `}),s.push(e[a]);return n&&e.length>0&&s.push({type:"text",value:`
665
- `}),s}function Mp(e){let n=0,s=e.charCodeAt(n);for(;s===9||s===32;)n++,s=e.charCodeAt(n);return e.slice(n)}function Ap(e,n){const s=nR(e,n),a=s.one(e,void 0),r=WA(s),o=Array.isArray(a)?{type:"root",children:a}:a||{type:"root",children:[]};return r&&o.children.push({type:"text",value:`
666
- `},r),o}function oR(e,n){return e&&"run"in e?async function(s,a){const r=Ap(s,{file:a,...n});await e.run(r,a)}:function(s,a){return Ap(s,{file:a,...e||n})}}function Rp(e){if(e)throw e}var pd,Ip;function lR(){if(Ip)return pd;Ip=1;var e=Object.prototype.hasOwnProperty,n=Object.prototype.toString,s=Object.defineProperty,a=Object.getOwnPropertyDescriptor,r=function(u){return typeof Array.isArray=="function"?Array.isArray(u):n.call(u)==="[object Array]"},o=function(u){if(!u||n.call(u)!=="[object Object]")return!1;var h=e.call(u,"constructor"),m=u.constructor&&u.constructor.prototype&&e.call(u.constructor.prototype,"isPrototypeOf");if(u.constructor&&!h&&!m)return!1;var f;for(f in u);return typeof f>"u"||e.call(u,f)},l=function(u,h){s&&h.name==="__proto__"?s(u,h.name,{enumerable:!0,configurable:!0,value:h.newValue,writable:!0}):u[h.name]=h.newValue},c=function(u,h){if(h==="__proto__")if(e.call(u,h)){if(a)return a(u,h).value}else return;return u[h]};return pd=function d(){var u,h,m,f,p,g,w=arguments[0],v=1,b=arguments.length,y=!1;for(typeof w=="boolean"&&(y=w,w=arguments[1]||{},v=2),(w==null||typeof w!="object"&&typeof w!="function")&&(w={});v<b;++v)if(u=arguments[v],u!=null)for(h in u)m=c(w,h),f=c(u,h),w!==f&&(y&&f&&(o(f)||(p=r(f)))?(p?(p=!1,g=m&&r(m)?m:[]):g=m&&o(m)?m:{},l(w,{name:h,newValue:d(y,g,f)})):typeof f<"u"&&l(w,{name:h,newValue:f}));return w},pd}var cR=lR();const fd=sb(cR);function _u(e){if(typeof e!="object"||e===null)return!1;const n=Object.getPrototypeOf(e);return(n===null||n===Object.prototype||Object.getPrototypeOf(n)===null)&&!(Symbol.toStringTag in e)&&!(Symbol.iterator in e)}function dR(){const e=[],n={run:s,use:a};return n;function s(...r){let o=-1;const l=r.pop();if(typeof l!="function")throw new TypeError("Expected function as last argument, not "+l);c(null,...r);function c(d,...u){const h=e[++o];let m=-1;if(d){l(d);return}for(;++m<r.length;)(u[m]===null||u[m]===void 0)&&(u[m]=r[m]);r=u,h?uR(h,c)(...u):l(null,...u)}}function a(r){if(typeof r!="function")throw new TypeError("Expected `middelware` to be a function, not "+r);return e.push(r),n}}function uR(e,n){let s;return a;function a(...l){const c=e.length>l.length;let d;c&&l.push(r);try{d=e.apply(this,l)}catch(u){const h=u;if(c&&s)throw h;return r(h)}c||(d&&d.then&&typeof d.then=="function"?d.then(o,r):d instanceof Error?r(d):o(d))}function r(l,...c){s||(s=!0,n(l,...c))}function o(l){r(null,l)}}const Ti={basename:mR,dirname:hR,extname:pR,join:fR,sep:"/"};function mR(e,n){if(n!==void 0&&typeof n!="string")throw new TypeError('"ext" argument must be a string');nl(e);let s=0,a=-1,r=e.length,o;if(n===void 0||n.length===0||n.length>e.length){for(;r--;)if(e.codePointAt(r)===47){if(o){s=r+1;break}}else a<0&&(o=!0,a=r+1);return a<0?"":e.slice(s,a)}if(n===e)return"";let l=-1,c=n.length-1;for(;r--;)if(e.codePointAt(r)===47){if(o){s=r+1;break}}else l<0&&(o=!0,l=r+1),c>-1&&(e.codePointAt(r)===n.codePointAt(c--)?c<0&&(a=r):(c=-1,a=l));return s===a?a=l:a<0&&(a=e.length),e.slice(s,a)}function hR(e){if(nl(e),e.length===0)return".";let n=-1,s=e.length,a;for(;--s;)if(e.codePointAt(s)===47){if(a){n=s;break}}else a||(a=!0);return n<0?e.codePointAt(0)===47?"/":".":n===1&&e.codePointAt(0)===47?"//":e.slice(0,n)}function pR(e){nl(e);let n=e.length,s=-1,a=0,r=-1,o=0,l;for(;n--;){const c=e.codePointAt(n);if(c===47){if(l){a=n+1;break}continue}s<0&&(l=!0,s=n+1),c===46?r<0?r=n:o!==1&&(o=1):r>-1&&(o=-1)}return r<0||s<0||o===0||o===1&&r===s-1&&r===a+1?"":e.slice(r,s)}function fR(...e){let n=-1,s;for(;++n<e.length;)nl(e[n]),e[n]&&(s=s===void 0?e[n]:s+"/"+e[n]);return s===void 0?".":gR(s)}function gR(e){nl(e);const n=e.codePointAt(0)===47;let s=bR(e,!n);return s.length===0&&!n&&(s="."),s.length>0&&e.codePointAt(e.length-1)===47&&(s+="/"),n?"/"+s:s}function bR(e,n){let s="",a=0,r=-1,o=0,l=-1,c,d;for(;++l<=e.length;){if(l<e.length)c=e.codePointAt(l);else{if(c===47)break;c=47}if(c===47){if(!(r===l-1||o===1))if(r!==l-1&&o===2){if(s.length<2||a!==2||s.codePointAt(s.length-1)!==46||s.codePointAt(s.length-2)!==46){if(s.length>2){if(d=s.lastIndexOf("/"),d!==s.length-1){d<0?(s="",a=0):(s=s.slice(0,d),a=s.length-1-s.lastIndexOf("/")),r=l,o=0;continue}}else if(s.length>0){s="",a=0,r=l,o=0;continue}}n&&(s=s.length>0?s+"/..":"..",a=2)}else s.length>0?s+="/"+e.slice(r+1,l):s=e.slice(r+1,l),a=l-r-1;r=l,o=0}else c===46&&o>-1?o++:o=-1}return s}function nl(e){if(typeof e!="string")throw new TypeError("Path must be a string. Received "+JSON.stringify(e))}const xR={cwd:vR};function vR(){return"/"}function Mu(e){return!!(e!==null&&typeof e=="object"&&"href"in e&&e.href&&"protocol"in e&&e.protocol&&e.auth===void 0)}function yR(e){if(typeof e=="string")e=new URL(e);else if(!Mu(e)){const n=new TypeError('The "path" argument must be of type string or an instance of URL. Received `'+e+"`");throw n.code="ERR_INVALID_ARG_TYPE",n}if(e.protocol!=="file:"){const n=new TypeError("The URL must be of scheme file");throw n.code="ERR_INVALID_URL_SCHEME",n}return wR(e)}function wR(e){if(e.hostname!==""){const a=new TypeError('File URL host must be "localhost" or empty on darwin');throw a.code="ERR_INVALID_FILE_URL_HOST",a}const n=e.pathname;let s=-1;for(;++s<n.length;)if(n.codePointAt(s)===37&&n.codePointAt(s+1)===50){const a=n.codePointAt(s+2);if(a===70||a===102){const r=new TypeError("File URL path must not include encoded / characters");throw r.code="ERR_INVALID_FILE_URL_PATH",r}}return decodeURIComponent(n)}const gd=["history","path","basename","stem","extname","dirname"];class qx{constructor(n){let s;n?Mu(n)?s={path:n}:typeof n=="string"||kR(n)?s={value:n}:s=n:s={},this.cwd="cwd"in s?"":xR.cwd(),this.data={},this.history=[],this.messages=[],this.value,this.map,this.result,this.stored;let a=-1;for(;++a<gd.length;){const o=gd[a];o in s&&s[o]!==void 0&&s[o]!==null&&(this[o]=o==="history"?[...s[o]]:s[o])}let r;for(r in s)gd.includes(r)||(this[r]=s[r])}get basename(){return typeof this.path=="string"?Ti.basename(this.path):void 0}set basename(n){xd(n,"basename"),bd(n,"basename"),this.path=Ti.join(this.dirname||"",n)}get dirname(){return typeof this.path=="string"?Ti.dirname(this.path):void 0}set dirname(n){Tp(this.basename,"dirname"),this.path=Ti.join(n||"",this.basename)}get extname(){return typeof this.path=="string"?Ti.extname(this.path):void 0}set extname(n){if(bd(n,"extname"),Tp(this.dirname,"extname"),n){if(n.codePointAt(0)!==46)throw new Error("`extname` must start with `.`");if(n.includes(".",1))throw new Error("`extname` cannot contain multiple dots")}this.path=Ti.join(this.dirname,this.stem+(n||""))}get path(){return this.history[this.history.length-1]}set path(n){Mu(n)&&(n=yR(n)),xd(n,"path"),this.path!==n&&this.history.push(n)}get stem(){return typeof this.path=="string"?Ti.basename(this.path,this.extname):void 0}set stem(n){xd(n,"stem"),bd(n,"stem"),this.path=Ti.join(this.dirname||"",n+(this.extname||""))}fail(n,s,a){const r=this.message(n,s,a);throw r.fatal=!0,r}info(n,s,a){const r=this.message(n,s,a);return r.fatal=void 0,r}message(n,s,a){const r=new Ps(n,s,a);return this.path&&(r.name=this.path+":"+r.name,r.file=this.path),r.fatal=!1,this.messages.push(r),r}toString(n){return this.value===void 0?"":typeof this.value=="string"?this.value:new TextDecoder(n||void 0).decode(this.value)}}function bd(e,n){if(e&&e.includes(Ti.sep))throw new Error("`"+n+"` cannot be a path: did not expect `"+Ti.sep+"`")}function xd(e,n){if(!e)throw new Error("`"+n+"` cannot be empty")}function Tp(e,n){if(!e)throw new Error("Setting `"+n+"` requires `path` to be set too")}function kR(e){return!!(e&&typeof e=="object"&&"byteLength"in e&&"byteOffset"in e)}const jR=(function(e){const a=this.constructor.prototype,r=a[e],o=function(){return r.apply(o,arguments)};return Object.setPrototypeOf(o,a),o}),NR={}.hasOwnProperty;class wm extends jR{constructor(){super("copy"),this.Compiler=void 0,this.Parser=void 0,this.attachers=[],this.compiler=void 0,this.freezeIndex=-1,this.frozen=void 0,this.namespace={},this.parser=void 0,this.transformers=dR()}copy(){const n=new wm;let s=-1;for(;++s<this.attachers.length;){const a=this.attachers[s];n.use(...a)}return n.data(fd(!0,{},this.namespace)),n}data(n,s){return typeof n=="string"?arguments.length===2?(wd("data",this.frozen),this.namespace[n]=s,this):NR.call(this.namespace,n)&&this.namespace[n]||void 0:n?(wd("data",this.frozen),this.namespace=n,this):this.namespace}freeze(){if(this.frozen)return this;const n=this;for(;++this.freezeIndex<this.attachers.length;){const[s,...a]=this.attachers[this.freezeIndex];if(a[0]===!1)continue;a[0]===!0&&(a[0]=void 0);const r=s.call(n,...a);typeof r=="function"&&this.transformers.use(r)}return this.frozen=!0,this.freezeIndex=Number.POSITIVE_INFINITY,this}parse(n){this.freeze();const s=fl(n),a=this.parser||this.Parser;return vd("parse",a),a(String(s),s)}process(n,s){const a=this;return this.freeze(),vd("process",this.parser||this.Parser),yd("process",this.compiler||this.Compiler),s?r(void 0,s):new Promise(r);function r(o,l){const c=fl(n),d=a.parse(c);a.run(d,c,function(h,m,f){if(h||!m||!f)return u(h);const p=m,g=a.stringify(p,f);ER(g)?f.value=g:f.result=g,u(h,f)});function u(h,m){h||!m?l(h):o?o(m):s(void 0,m)}}}processSync(n){let s=!1,a;return this.freeze(),vd("processSync",this.parser||this.Parser),yd("processSync",this.compiler||this.Compiler),this.process(n,r),$p("processSync","process",s),a;function r(o,l){s=!0,Rp(o),a=l}}run(n,s,a){Pp(n),this.freeze();const r=this.transformers;return!a&&typeof s=="function"&&(a=s,s=void 0),a?o(void 0,a):new Promise(o);function o(l,c){const d=fl(s);r.run(n,d,u);function u(h,m,f){const p=m||n;h?c(h):l?l(p):a(void 0,p,f)}}}runSync(n,s){let a=!1,r;return this.run(n,s,o),$p("runSync","run",a),r;function o(l,c){Rp(l),r=c,a=!0}}stringify(n,s){this.freeze();const a=fl(s),r=this.compiler||this.Compiler;return yd("stringify",r),Pp(n),r(n,a)}use(n,...s){const a=this.attachers,r=this.namespace;if(wd("use",this.frozen),n!=null)if(typeof n=="function")d(n,s);else if(typeof n=="object")Array.isArray(n)?c(n):l(n);else throw new TypeError("Expected usable value, not `"+n+"`");return this;function o(u){if(typeof u=="function")d(u,[]);else if(typeof u=="object")if(Array.isArray(u)){const[h,...m]=u;d(h,m)}else l(u);else throw new TypeError("Expected usable value, not `"+u+"`")}function l(u){if(!("plugins"in u)&&!("settings"in u))throw new Error("Expected usable value but received an empty preset, which is probably a mistake: presets typically come with `plugins` and sometimes with `settings`, but this has neither");c(u.plugins),u.settings&&(r.settings=fd(!0,r.settings,u.settings))}function c(u){let h=-1;if(u!=null)if(Array.isArray(u))for(;++h<u.length;){const m=u[h];o(m)}else throw new TypeError("Expected a list of plugins, not `"+u+"`")}function d(u,h){let m=-1,f=-1;for(;++m<a.length;)if(a[m][0]===u){f=m;break}if(f===-1)a.push([u,...h]);else if(h.length>0){let[p,...g]=h;const w=a[f][1];_u(w)&&_u(p)&&(p=fd(!0,w,p)),a[f]=[u,p,...g]}}}}const SR=new wm().freeze();function vd(e,n){if(typeof n!="function")throw new TypeError("Cannot `"+e+"` without `parser`")}function yd(e,n){if(typeof n!="function")throw new TypeError("Cannot `"+e+"` without `compiler`")}function wd(e,n){if(n)throw new Error("Cannot call `"+e+"` on a frozen processor.\nCreate a new processor first, by calling it: use `processor()` instead of `processor`.")}function Pp(e){if(!_u(e)||typeof e.type!="string")throw new TypeError("Expected node, got `"+e+"`")}function $p(e,n,s){if(!s)throw new Error("`"+e+"` finished async. Use `"+n+"` instead")}function fl(e){return CR(e)?e:new qx(e)}function CR(e){return!!(e&&typeof e=="object"&&"message"in e&&"messages"in e)}function ER(e){return typeof e=="string"||_R(e)}function _R(e){return!!(e&&typeof e=="object"&&"byteLength"in e&&"byteOffset"in e)}const MR="https://github.com/remarkjs/react-markdown/blob/main/changelog.md",Dp=[],Lp={allowDangerousHtml:!0},AR=/^(https?|ircs?|mailto|xmpp)$/i,RR=[{from:"astPlugins",id:"remove-buggy-html-in-markdown-parser"},{from:"allowDangerousHtml",id:"remove-buggy-html-in-markdown-parser"},{from:"allowNode",id:"replace-allownode-allowedtypes-and-disallowedtypes",to:"allowElement"},{from:"allowedTypes",id:"replace-allownode-allowedtypes-and-disallowedtypes",to:"allowedElements"},{from:"className",id:"remove-classname"},{from:"disallowedTypes",id:"replace-allownode-allowedtypes-and-disallowedtypes",to:"disallowedElements"},{from:"escapeHtml",id:"remove-buggy-html-in-markdown-parser"},{from:"includeElementIndex",id:"#remove-includeelementindex"},{from:"includeNodeIndex",id:"change-includenodeindex-to-includeelementindex"},{from:"linkTarget",id:"remove-linktarget"},{from:"plugins",id:"change-plugins-to-remarkplugins",to:"remarkPlugins"},{from:"rawSourcePos",id:"#remove-rawsourcepos"},{from:"renderers",id:"change-renderers-to-components",to:"components"},{from:"source",id:"change-source-to-children",to:"children"},{from:"sourcePos",id:"#remove-sourcepos"},{from:"transformImageUri",id:"#add-urltransform",to:"urlTransform"},{from:"transformLinkUri",id:"#add-urltransform",to:"urlTransform"}];function hi(e){const n=IR(e),s=TR(e);return PR(n.runSync(n.parse(s),s),e)}function IR(e){const n=e.rehypePlugins||Dp,s=e.remarkPlugins||Dp,a=e.remarkRehypeOptions?{...e.remarkRehypeOptions,...Lp}:Lp;return SR().use(hA).use(s).use(oR,a).use(n)}function TR(e){const n=e.children||"",s=new qx;return typeof n=="string"&&(s.value=n),s}function PR(e,n){const s=n.allowedElements,a=n.allowElement,r=n.components,o=n.disallowedElements,l=n.skipHtml,c=n.unwrapDisallowed,d=n.urlTransform||$R;for(const h of RR)Object.hasOwn(n,h.from)&&(""+h.from+(h.to?"use `"+h.to+"` instead":"remove it")+MR+h.id,void 0);return ym(e,u),Y_(e,{Fragment:t.Fragment,components:r,ignoreInvalidStyle:!0,jsx:t.jsx,jsxs:t.jsxs,passKeys:!0,passNode:!0});function u(h,m,f){if(h.type==="raw"&&f&&typeof m=="number")return l?f.children.splice(m,1):f.children[m]={type:"text",value:h.value},m;if(h.type==="element"){let p;for(p in ud)if(Object.hasOwn(ud,p)&&Object.hasOwn(h.properties,p)){const g=h.properties[p],w=ud[p];(w===null||w.includes(h.tagName))&&(h.properties[p]=d(String(g||""),p,h))}}if(h.type==="element"){let p=s?!s.includes(h.tagName):o?o.includes(h.tagName):!1;if(!p&&a&&typeof m=="number"&&(p=!a(h,m,f)),p&&f&&typeof m=="number")return c&&h.children?f.children.splice(m,1,...h.children):f.children.splice(m,1),m}}}function $R(e){const n=e.indexOf(":"),s=e.indexOf("?"),a=e.indexOf("#"),r=e.indexOf("/");return n===-1||r!==-1&&n>r||s!==-1&&n>s||a!==-1&&n>a||AR.test(e.slice(0,n))?e:""}function Op(e,n){const s=String(e);if(typeof n!="string")throw new TypeError("Expected character");let a=0,r=s.indexOf(n);for(;r!==-1;)a++,r=s.indexOf(n,r+n.length);return a}function DR(e){if(typeof e!="string")throw new TypeError("Expected a string");return e.replace(/[|\\{}()[\]^$+*?.]/g,"\\$&").replace(/-/g,"\\x2d")}function LR(e,n,s){const r=Ic((s||{}).ignore||[]),o=OR(n);let l=-1;for(;++l<o.length;)Hx(e,"text",c);function c(u,h){let m=-1,f;for(;++m<h.length;){const p=h[m],g=f?f.children:void 0;if(r(p,g?g.indexOf(p):void 0,f))return;f=p}if(f)return d(u,h)}function d(u,h){const m=h[h.length-1],f=o[l][0],p=o[l][1];let g=0;const v=m.children.indexOf(u);let b=!1,y=[];f.lastIndex=0;let j=f.exec(u.value);for(;j;){const S=j.index,C={index:j.index,input:j.input,stack:[...h,u]};let x=p(...j,C);if(typeof x=="string"&&(x=x.length>0?{type:"text",value:x}:void 0),x===!1?f.lastIndex=S+1:(g!==S&&y.push({type:"text",value:u.value.slice(g,S)}),Array.isArray(x)?y.push(...x):x&&y.push(x),g=S+j[0].length,b=!0),!f.global)break;j=f.exec(u.value)}return b?(g<u.value.length&&y.push({type:"text",value:u.value.slice(g)}),m.children.splice(v,1,...y)):y=[u],v+y.length}}function OR(e){const n=[];if(!Array.isArray(e))throw new TypeError("Expected find and replace tuple or list of tuples");const s=!e[0]||Array.isArray(e[0])?e:[e];let a=-1;for(;++a<s.length;){const r=s[a];n.push([FR(r[0]),zR(r[1])])}return n}function FR(e){return typeof e=="string"?new RegExp(DR(e),"g"):e}function zR(e){return typeof e=="function"?e:function(){return e}}const kd="phrasing",jd=["autolink","link","image","label"];function BR(){return{transforms:[KR],enter:{literalAutolink:HR,literalAutolinkEmail:Nd,literalAutolinkHttp:Nd,literalAutolinkWww:Nd},exit:{literalAutolink:GR,literalAutolinkEmail:WR,literalAutolinkHttp:qR,literalAutolinkWww:VR}}}function UR(){return{unsafe:[{character:"@",before:"[+\\-.\\w]",after:"[\\-.\\w]",inConstruct:kd,notInConstruct:jd},{character:".",before:"[Ww]",after:"[\\-.\\w]",inConstruct:kd,notInConstruct:jd},{character:":",before:"[ps]",after:"\\/",inConstruct:kd,notInConstruct:jd}]}}function HR(e){this.enter({type:"link",title:null,url:"",children:[]},e)}function Nd(e){this.config.enter.autolinkProtocol.call(this,e)}function qR(e){this.config.exit.autolinkProtocol.call(this,e)}function VR(e){this.config.exit.data.call(this,e);const n=this.stack[this.stack.length-1];n.type,n.url="http://"+this.sliceSerialize(e)}function WR(e){this.config.exit.autolinkEmail.call(this,e)}function GR(e){this.exit(e)}function KR(e){LR(e,[[/(https?:\/\/|www(?=\.))([-.\w]+)([^ \t\r\n]*)/gi,JR],[/(?<=^|\s|\p{P}|\p{S})([-.\w+]+)@([-\w]+(?:\.[-\w]+)+)/gu,YR]],{ignore:["link","linkReference"]})}function JR(e,n,s,a,r){let o="";if(!Vx(r)||(/^w/i.test(n)&&(s=n+s,n="",o="http://"),!QR(s)))return!1;const l=XR(s+a);if(!l[0])return!1;const c={type:"link",title:null,url:o+n+l[0],children:[{type:"text",value:n+l[0]}]};return l[1]?[c,{type:"text",value:l[1]}]:c}function YR(e,n,s,a){return!Vx(a,!0)||/[-\d_]$/.test(s)?!1:{type:"link",title:null,url:"mailto:"+n+"@"+s,children:[{type:"text",value:n+"@"+s}]}}function QR(e){const n=e.split(".");return!(n.length<2||n[n.length-1]&&(/_/.test(n[n.length-1])||!/[a-zA-Z\d]/.test(n[n.length-1]))||n[n.length-2]&&(/_/.test(n[n.length-2])||!/[a-zA-Z\d]/.test(n[n.length-2])))}function XR(e){const n=/[!"&'),.:;<>?\]}]+$/.exec(e);if(!n)return[e,void 0];e=e.slice(0,n.index);let s=n[0],a=s.indexOf(")");const r=Op(e,"(");let o=Op(e,")");for(;a!==-1&&r>o;)e+=s.slice(0,a+1),s=s.slice(a+1),a=s.indexOf(")"),o++;return[e,s]}function Vx(e,n){const s=e.input.charCodeAt(e.index-1);return(e.index===0||Va(s)||Mc(s))&&(!n||s!==47)}Wx.peek=oI;function ZR(){this.buffer()}function eI(e){this.enter({type:"footnoteReference",identifier:"",label:""},e)}function tI(){this.buffer()}function nI(e){this.enter({type:"footnoteDefinition",identifier:"",label:"",children:[]},e)}function sI(e){const n=this.resume(),s=this.stack[this.stack.length-1];s.type,s.identifier=ji(this.sliceSerialize(e)).toLowerCase(),s.label=n}function iI(e){this.exit(e)}function aI(e){const n=this.resume(),s=this.stack[this.stack.length-1];s.type,s.identifier=ji(this.sliceSerialize(e)).toLowerCase(),s.label=n}function rI(e){this.exit(e)}function oI(){return"["}function Wx(e,n,s,a){const r=s.createTracker(a);let o=r.move("[^");const l=s.enter("footnoteReference"),c=s.enter("reference");return o+=r.move(s.safe(s.associationId(e),{after:"]",before:o})),c(),l(),o+=r.move("]"),o}function lI(){return{enter:{gfmFootnoteCallString:ZR,gfmFootnoteCall:eI,gfmFootnoteDefinitionLabelString:tI,gfmFootnoteDefinition:nI},exit:{gfmFootnoteCallString:sI,gfmFootnoteCall:iI,gfmFootnoteDefinitionLabelString:aI,gfmFootnoteDefinition:rI}}}function cI(e){let n=!1;return e&&e.firstLineBlank&&(n=!0),{handlers:{footnoteDefinition:s,footnoteReference:Wx},unsafe:[{character:"[",inConstruct:["label","phrasing","reference"]}]};function s(a,r,o,l){const c=o.createTracker(l);let d=c.move("[^");const u=o.enter("footnoteDefinition"),h=o.enter("label");return d+=c.move(o.safe(o.associationId(a),{before:d,after:"]"})),h(),d+=c.move("]:"),a.children&&a.children.length>0&&(c.shift(4),d+=c.move((n?`
667
- `:" ")+o.indentLines(o.containerFlow(a,c.current()),n?Gx:dI))),u(),d}}function dI(e,n,s){return n===0?e:Gx(e,n,s)}function Gx(e,n,s){return(s?"":" ")+e}const uI=["autolink","destinationLiteral","destinationRaw","reference","titleQuote","titleApostrophe"];Kx.peek=gI;function mI(){return{canContainEols:["delete"],enter:{strikethrough:pI},exit:{strikethrough:fI}}}function hI(){return{unsafe:[{character:"~",inConstruct:"phrasing",notInConstruct:uI}],handlers:{delete:Kx}}}function pI(e){this.enter({type:"delete",children:[]},e)}function fI(e){this.exit(e)}function Kx(e,n,s,a){const r=s.createTracker(a),o=s.enter("strikethrough");let l=r.move("~~");return l+=s.containerPhrasing(e,{...r.current(),before:l,after:"~"}),l+=r.move("~~"),o(),l}function gI(){return"~"}function bI(e){return e.length}function xI(e,n){const s=n||{},a=(s.align||[]).concat(),r=s.stringLength||bI,o=[],l=[],c=[],d=[];let u=0,h=-1;for(;++h<e.length;){const w=[],v=[];let b=-1;for(e[h].length>u&&(u=e[h].length);++b<e[h].length;){const y=vI(e[h][b]);if(s.alignDelimiters!==!1){const j=r(y);v[b]=j,(d[b]===void 0||j>d[b])&&(d[b]=j)}w.push(y)}l[h]=w,c[h]=v}let m=-1;if(typeof a=="object"&&"length"in a)for(;++m<u;)o[m]=Fp(a[m]);else{const w=Fp(a);for(;++m<u;)o[m]=w}m=-1;const f=[],p=[];for(;++m<u;){const w=o[m];let v="",b="";w===99?(v=":",b=":"):w===108?v=":":w===114&&(b=":");let y=s.alignDelimiters===!1?1:Math.max(1,d[m]-v.length-b.length);const j=v+"-".repeat(y)+b;s.alignDelimiters!==!1&&(y=v.length+y+b.length,y>d[m]&&(d[m]=y),p[m]=y),f[m]=j}l.splice(1,0,f),c.splice(1,0,p),h=-1;const g=[];for(;++h<l.length;){const w=l[h],v=c[h];m=-1;const b=[];for(;++m<u;){const y=w[m]||"";let j="",S="";if(s.alignDelimiters!==!1){const C=d[m]-(v[m]||0),x=o[m];x===114?j=" ".repeat(C):x===99?C%2?(j=" ".repeat(C/2+.5),S=" ".repeat(C/2-.5)):(j=" ".repeat(C/2),S=j):S=" ".repeat(C)}s.delimiterStart!==!1&&!m&&b.push("|"),s.padding!==!1&&!(s.alignDelimiters===!1&&y==="")&&(s.delimiterStart!==!1||m)&&b.push(" "),s.alignDelimiters!==!1&&b.push(j),b.push(y),s.alignDelimiters!==!1&&b.push(S),s.padding!==!1&&b.push(" "),(s.delimiterEnd!==!1||m!==u-1)&&b.push("|")}g.push(s.delimiterEnd===!1?b.join("").replace(/ +$/,""):b.join(""))}return g.join(`
668
- `)}function vI(e){return e==null?"":String(e)}function Fp(e){const n=typeof e=="string"?e.codePointAt(0):0;return n===67||n===99?99:n===76||n===108?108:n===82||n===114?114:0}function yI(e,n,s,a){const r=s.enter("blockquote"),o=s.createTracker(a);o.move("> "),o.shift(2);const l=s.indentLines(s.containerFlow(e,o.current()),wI);return r(),l}function wI(e,n,s){return">"+(s?"":" ")+e}function kI(e,n){return zp(e,n.inConstruct,!0)&&!zp(e,n.notInConstruct,!1)}function zp(e,n,s){if(typeof n=="string"&&(n=[n]),!n||n.length===0)return s;let a=-1;for(;++a<n.length;)if(e.includes(n[a]))return!0;return!1}function Bp(e,n,s,a){let r=-1;for(;++r<s.unsafe.length;)if(s.unsafe[r].character===`
669
- `&&kI(s.stack,s.unsafe[r]))return/[ \t]/.test(a.before)?"":" ";return`\\
670
- `}function jI(e,n){const s=String(e);let a=s.indexOf(n),r=a,o=0,l=0;if(typeof n!="string")throw new TypeError("Expected substring");for(;a!==-1;)a===r?++o>l&&(l=o):o=1,r=a+n.length,a=s.indexOf(n,r);return l}function NI(e,n){return!!(n.options.fences===!1&&e.value&&!e.lang&&/[^ \r\n]/.test(e.value)&&!/^[\t ]*(?:[\r\n]|$)|(?:^|[\r\n])[\t ]*$/.test(e.value))}function SI(e){const n=e.options.fence||"`";if(n!=="`"&&n!=="~")throw new Error("Cannot serialize code with `"+n+"` for `options.fence`, expected `` ` `` or `~`");return n}function CI(e,n,s,a){const r=SI(s),o=e.value||"",l=r==="`"?"GraveAccent":"Tilde";if(NI(e,s)){const m=s.enter("codeIndented"),f=s.indentLines(o,EI);return m(),f}const c=s.createTracker(a),d=r.repeat(Math.max(jI(o,r)+1,3)),u=s.enter("codeFenced");let h=c.move(d);if(e.lang){const m=s.enter(`codeFencedLang${l}`);h+=c.move(s.safe(e.lang,{before:h,after:" ",encode:["`"],...c.current()})),m()}if(e.lang&&e.meta){const m=s.enter(`codeFencedMeta${l}`);h+=c.move(" "),h+=c.move(s.safe(e.meta,{before:h,after:`
671
- `,encode:["`"],...c.current()})),m()}return h+=c.move(`
672
- `),o&&(h+=c.move(o+`
673
- `)),h+=c.move(d),u(),h}function EI(e,n,s){return(s?"":" ")+e}function km(e){const n=e.options.quote||'"';if(n!=='"'&&n!=="'")throw new Error("Cannot serialize title with `"+n+"` for `options.quote`, expected `\"`, or `'`");return n}function _I(e,n,s,a){const r=km(s),o=r==='"'?"Quote":"Apostrophe",l=s.enter("definition");let c=s.enter("label");const d=s.createTracker(a);let u=d.move("[");return u+=d.move(s.safe(s.associationId(e),{before:u,after:"]",...d.current()})),u+=d.move("]: "),c(),!e.url||/[\0- \u007F]/.test(e.url)?(c=s.enter("destinationLiteral"),u+=d.move("<"),u+=d.move(s.safe(e.url,{before:u,after:">",...d.current()})),u+=d.move(">")):(c=s.enter("destinationRaw"),u+=d.move(s.safe(e.url,{before:u,after:e.title?" ":`
674
- `,...d.current()}))),c(),e.title&&(c=s.enter(`title${o}`),u+=d.move(" "+r),u+=d.move(s.safe(e.title,{before:u,after:r,...d.current()})),u+=d.move(r),c()),l(),u}function MI(e){const n=e.options.emphasis||"*";if(n!=="*"&&n!=="_")throw new Error("Cannot serialize emphasis with `"+n+"` for `options.emphasis`, expected `*`, or `_`");return n}function zo(e){return"&#x"+e.toString(16).toUpperCase()+";"}function rc(e,n,s){const a=Rr(e),r=Rr(n);return a===void 0?r===void 0?s==="_"?{inside:!0,outside:!0}:{inside:!1,outside:!1}:r===1?{inside:!0,outside:!0}:{inside:!1,outside:!0}:a===1?r===void 0?{inside:!1,outside:!1}:r===1?{inside:!0,outside:!0}:{inside:!1,outside:!1}:r===void 0?{inside:!1,outside:!1}:r===1?{inside:!0,outside:!1}:{inside:!1,outside:!1}}Jx.peek=AI;function Jx(e,n,s,a){const r=MI(s),o=s.enter("emphasis"),l=s.createTracker(a),c=l.move(r);let d=l.move(s.containerPhrasing(e,{after:r,before:c,...l.current()}));const u=d.charCodeAt(0),h=rc(a.before.charCodeAt(a.before.length-1),u,r);h.inside&&(d=zo(u)+d.slice(1));const m=d.charCodeAt(d.length-1),f=rc(a.after.charCodeAt(0),m,r);f.inside&&(d=d.slice(0,-1)+zo(m));const p=l.move(r);return o(),s.attentionEncodeSurroundingInfo={after:f.outside,before:h.outside},c+d+p}function AI(e,n,s){return s.options.emphasis||"*"}function RI(e,n){let s=!1;return ym(e,function(a){if("value"in a&&/\r?\n|\r/.test(a.value)||a.type==="break")return s=!0,Cu}),!!((!e.depth||e.depth<3)&&hm(e)&&(n.options.setext||s))}function II(e,n,s,a){const r=Math.max(Math.min(6,e.depth||1),1),o=s.createTracker(a);if(RI(e,s)){const h=s.enter("headingSetext"),m=s.enter("phrasing"),f=s.containerPhrasing(e,{...o.current(),before:`
675
- `,after:`
676
- `});return m(),h(),f+`
677
- `+(r===1?"=":"-").repeat(f.length-(Math.max(f.lastIndexOf("\r"),f.lastIndexOf(`
678
- `))+1))}const l="#".repeat(r),c=s.enter("headingAtx"),d=s.enter("phrasing");o.move(l+" ");let u=s.containerPhrasing(e,{before:"# ",after:`
679
- `,...o.current()});return/^[\t ]/.test(u)&&(u=zo(u.charCodeAt(0))+u.slice(1)),u=u?l+" "+u:l,s.options.closeAtx&&(u+=" "+l),d(),c(),u}Yx.peek=TI;function Yx(e){return e.value||""}function TI(){return"<"}Qx.peek=PI;function Qx(e,n,s,a){const r=km(s),o=r==='"'?"Quote":"Apostrophe",l=s.enter("image");let c=s.enter("label");const d=s.createTracker(a);let u=d.move("![");return u+=d.move(s.safe(e.alt,{before:u,after:"]",...d.current()})),u+=d.move("]("),c(),!e.url&&e.title||/[\0- \u007F]/.test(e.url)?(c=s.enter("destinationLiteral"),u+=d.move("<"),u+=d.move(s.safe(e.url,{before:u,after:">",...d.current()})),u+=d.move(">")):(c=s.enter("destinationRaw"),u+=d.move(s.safe(e.url,{before:u,after:e.title?" ":")",...d.current()}))),c(),e.title&&(c=s.enter(`title${o}`),u+=d.move(" "+r),u+=d.move(s.safe(e.title,{before:u,after:r,...d.current()})),u+=d.move(r),c()),u+=d.move(")"),l(),u}function PI(){return"!"}Xx.peek=$I;function Xx(e,n,s,a){const r=e.referenceType,o=s.enter("imageReference");let l=s.enter("label");const c=s.createTracker(a);let d=c.move("![");const u=s.safe(e.alt,{before:d,after:"]",...c.current()});d+=c.move(u+"]["),l();const h=s.stack;s.stack=[],l=s.enter("reference");const m=s.safe(s.associationId(e),{before:d,after:"]",...c.current()});return l(),s.stack=h,o(),r==="full"||!u||u!==m?d+=c.move(m+"]"):r==="shortcut"?d=d.slice(0,-1):d+=c.move("]"),d}function $I(){return"!"}Zx.peek=DI;function Zx(e,n,s){let a=e.value||"",r="`",o=-1;for(;new RegExp("(^|[^`])"+r+"([^`]|$)").test(a);)r+="`";for(/[^ \r\n]/.test(a)&&(/^[ \r\n]/.test(a)&&/[ \r\n]$/.test(a)||/^`|`$/.test(a))&&(a=" "+a+" ");++o<s.unsafe.length;){const l=s.unsafe[o],c=s.compilePattern(l);let d;if(l.atBreak)for(;d=c.exec(a);){let u=d.index;a.charCodeAt(u)===10&&a.charCodeAt(u-1)===13&&u--,a=a.slice(0,u)+" "+a.slice(d.index+1)}}return r+a+r}function DI(){return"`"}function ev(e,n){const s=hm(e);return!!(!n.options.resourceLink&&e.url&&!e.title&&e.children&&e.children.length===1&&e.children[0].type==="text"&&(s===e.url||"mailto:"+s===e.url)&&/^[a-z][a-z+.-]+:/i.test(e.url)&&!/[\0- <>\u007F]/.test(e.url))}tv.peek=LI;function tv(e,n,s,a){const r=km(s),o=r==='"'?"Quote":"Apostrophe",l=s.createTracker(a);let c,d;if(ev(e,s)){const h=s.stack;s.stack=[],c=s.enter("autolink");let m=l.move("<");return m+=l.move(s.containerPhrasing(e,{before:m,after:">",...l.current()})),m+=l.move(">"),c(),s.stack=h,m}c=s.enter("link"),d=s.enter("label");let u=l.move("[");return u+=l.move(s.containerPhrasing(e,{before:u,after:"](",...l.current()})),u+=l.move("]("),d(),!e.url&&e.title||/[\0- \u007F]/.test(e.url)?(d=s.enter("destinationLiteral"),u+=l.move("<"),u+=l.move(s.safe(e.url,{before:u,after:">",...l.current()})),u+=l.move(">")):(d=s.enter("destinationRaw"),u+=l.move(s.safe(e.url,{before:u,after:e.title?" ":")",...l.current()}))),d(),e.title&&(d=s.enter(`title${o}`),u+=l.move(" "+r),u+=l.move(s.safe(e.title,{before:u,after:r,...l.current()})),u+=l.move(r),d()),u+=l.move(")"),c(),u}function LI(e,n,s){return ev(e,s)?"<":"["}nv.peek=OI;function nv(e,n,s,a){const r=e.referenceType,o=s.enter("linkReference");let l=s.enter("label");const c=s.createTracker(a);let d=c.move("[");const u=s.containerPhrasing(e,{before:d,after:"]",...c.current()});d+=c.move(u+"]["),l();const h=s.stack;s.stack=[],l=s.enter("reference");const m=s.safe(s.associationId(e),{before:d,after:"]",...c.current()});return l(),s.stack=h,o(),r==="full"||!u||u!==m?d+=c.move(m+"]"):r==="shortcut"?d=d.slice(0,-1):d+=c.move("]"),d}function OI(){return"["}function jm(e){const n=e.options.bullet||"*";if(n!=="*"&&n!=="+"&&n!=="-")throw new Error("Cannot serialize items with `"+n+"` for `options.bullet`, expected `*`, `+`, or `-`");return n}function FI(e){const n=jm(e),s=e.options.bulletOther;if(!s)return n==="*"?"-":"*";if(s!=="*"&&s!=="+"&&s!=="-")throw new Error("Cannot serialize items with `"+s+"` for `options.bulletOther`, expected `*`, `+`, or `-`");if(s===n)throw new Error("Expected `bullet` (`"+n+"`) and `bulletOther` (`"+s+"`) to be different");return s}function zI(e){const n=e.options.bulletOrdered||".";if(n!=="."&&n!==")")throw new Error("Cannot serialize items with `"+n+"` for `options.bulletOrdered`, expected `.` or `)`");return n}function sv(e){const n=e.options.rule||"*";if(n!=="*"&&n!=="-"&&n!=="_")throw new Error("Cannot serialize rules with `"+n+"` for `options.rule`, expected `*`, `-`, or `_`");return n}function BI(e,n,s,a){const r=s.enter("list"),o=s.bulletCurrent;let l=e.ordered?zI(s):jm(s);const c=e.ordered?l==="."?")":".":FI(s);let d=n&&s.bulletLastUsed?l===s.bulletLastUsed:!1;if(!e.ordered){const h=e.children?e.children[0]:void 0;if((l==="*"||l==="-")&&h&&(!h.children||!h.children[0])&&s.stack[s.stack.length-1]==="list"&&s.stack[s.stack.length-2]==="listItem"&&s.stack[s.stack.length-3]==="list"&&s.stack[s.stack.length-4]==="listItem"&&s.indexStack[s.indexStack.length-1]===0&&s.indexStack[s.indexStack.length-2]===0&&s.indexStack[s.indexStack.length-3]===0&&(d=!0),sv(s)===l&&h){let m=-1;for(;++m<e.children.length;){const f=e.children[m];if(f&&f.type==="listItem"&&f.children&&f.children[0]&&f.children[0].type==="thematicBreak"){d=!0;break}}}}d&&(l=c),s.bulletCurrent=l;const u=s.containerFlow(e,a);return s.bulletLastUsed=l,s.bulletCurrent=o,r(),u}function UI(e){const n=e.options.listItemIndent||"one";if(n!=="tab"&&n!=="one"&&n!=="mixed")throw new Error("Cannot serialize items with `"+n+"` for `options.listItemIndent`, expected `tab`, `one`, or `mixed`");return n}function HI(e,n,s,a){const r=UI(s);let o=s.bulletCurrent||jm(s);n&&n.type==="list"&&n.ordered&&(o=(typeof n.start=="number"&&n.start>-1?n.start:1)+(s.options.incrementListMarker===!1?0:n.children.indexOf(e))+o);let l=o.length+1;(r==="tab"||r==="mixed"&&(n&&n.type==="list"&&n.spread||e.spread))&&(l=Math.ceil(l/4)*4);const c=s.createTracker(a);c.move(o+" ".repeat(l-o.length)),c.shift(l);const d=s.enter("listItem"),u=s.indentLines(s.containerFlow(e,c.current()),h);return d(),u;function h(m,f,p){return f?(p?"":" ".repeat(l))+m:(p?o:o+" ".repeat(l-o.length))+m}}function qI(e,n,s,a){const r=s.enter("paragraph"),o=s.enter("phrasing"),l=s.containerPhrasing(e,a);return o(),r(),l}const VI=Ic(["break","delete","emphasis","footnote","footnoteReference","image","imageReference","inlineCode","inlineMath","link","linkReference","mdxJsxTextElement","mdxTextExpression","strong","text","textDirective"]);function WI(e,n,s,a){return(e.children.some(function(l){return VI(l)})?s.containerPhrasing:s.containerFlow).call(s,e,a)}function GI(e){const n=e.options.strong||"*";if(n!=="*"&&n!=="_")throw new Error("Cannot serialize strong with `"+n+"` for `options.strong`, expected `*`, or `_`");return n}iv.peek=KI;function iv(e,n,s,a){const r=GI(s),o=s.enter("strong"),l=s.createTracker(a),c=l.move(r+r);let d=l.move(s.containerPhrasing(e,{after:r,before:c,...l.current()}));const u=d.charCodeAt(0),h=rc(a.before.charCodeAt(a.before.length-1),u,r);h.inside&&(d=zo(u)+d.slice(1));const m=d.charCodeAt(d.length-1),f=rc(a.after.charCodeAt(0),m,r);f.inside&&(d=d.slice(0,-1)+zo(m));const p=l.move(r+r);return o(),s.attentionEncodeSurroundingInfo={after:f.outside,before:h.outside},c+d+p}function KI(e,n,s){return s.options.strong||"*"}function JI(e,n,s,a){return s.safe(e.value,a)}function YI(e){const n=e.options.ruleRepetition||3;if(n<3)throw new Error("Cannot serialize rules with repetition `"+n+"` for `options.ruleRepetition`, expected `3` or more");return n}function QI(e,n,s){const a=(sv(s)+(s.options.ruleSpaces?" ":"")).repeat(YI(s));return s.options.ruleSpaces?a.slice(0,-1):a}const av={blockquote:yI,break:Bp,code:CI,definition:_I,emphasis:Jx,hardBreak:Bp,heading:II,html:Yx,image:Qx,imageReference:Xx,inlineCode:Zx,link:tv,linkReference:nv,list:BI,listItem:HI,paragraph:qI,root:WI,strong:iv,text:JI,thematicBreak:QI};function XI(){return{enter:{table:ZI,tableData:Up,tableHeader:Up,tableRow:tT},exit:{codeText:nT,table:eT,tableData:Sd,tableHeader:Sd,tableRow:Sd}}}function ZI(e){const n=e._align;this.enter({type:"table",align:n.map(function(s){return s==="none"?null:s}),children:[]},e),this.data.inTable=!0}function eT(e){this.exit(e),this.data.inTable=void 0}function tT(e){this.enter({type:"tableRow",children:[]},e)}function Sd(e){this.exit(e)}function Up(e){this.enter({type:"tableCell",children:[]},e)}function nT(e){let n=this.resume();this.data.inTable&&(n=n.replace(/\\([\\|])/g,sT));const s=this.stack[this.stack.length-1];s.type,s.value=n,this.exit(e)}function sT(e,n){return n==="|"?n:e}function iT(e){const n=e||{},s=n.tableCellPadding,a=n.tablePipeAlign,r=n.stringLength,o=s?" ":"|";return{unsafe:[{character:"\r",inConstruct:"tableCell"},{character:`
680
- `,inConstruct:"tableCell"},{atBreak:!0,character:"|",after:"[ :-]"},{character:"|",inConstruct:"tableCell"},{atBreak:!0,character:":",after:"-"},{atBreak:!0,character:"-",after:"[:|-]"}],handlers:{inlineCode:f,table:l,tableCell:d,tableRow:c}};function l(p,g,w,v){return u(h(p,w,v),p.align)}function c(p,g,w,v){const b=m(p,w,v),y=u([b]);return y.slice(0,y.indexOf(`
681
- `))}function d(p,g,w,v){const b=w.enter("tableCell"),y=w.enter("phrasing"),j=w.containerPhrasing(p,{...v,before:o,after:o});return y(),b(),j}function u(p,g){return xI(p,{align:g,alignDelimiters:a,padding:s,stringLength:r})}function h(p,g,w){const v=p.children;let b=-1;const y=[],j=g.enter("table");for(;++b<v.length;)y[b]=m(v[b],g,w);return j(),y}function m(p,g,w){const v=p.children;let b=-1;const y=[],j=g.enter("tableRow");for(;++b<v.length;)y[b]=d(v[b],p,g,w);return j(),y}function f(p,g,w){let v=av.inlineCode(p,g,w);return w.stack.includes("tableCell")&&(v=v.replace(/\|/g,"\\$&")),v}}function aT(){return{exit:{taskListCheckValueChecked:Hp,taskListCheckValueUnchecked:Hp,paragraph:oT}}}function rT(){return{unsafe:[{atBreak:!0,character:"-",after:"[:|-]"}],handlers:{listItem:lT}}}function Hp(e){const n=this.stack[this.stack.length-2];n.type,n.checked=e.type==="taskListCheckValueChecked"}function oT(e){const n=this.stack[this.stack.length-2];if(n&&n.type==="listItem"&&typeof n.checked=="boolean"){const s=this.stack[this.stack.length-1];s.type;const a=s.children[0];if(a&&a.type==="text"){const r=n.children;let o=-1,l;for(;++o<r.length;){const c=r[o];if(c.type==="paragraph"){l=c;break}}l===s&&(a.value=a.value.slice(1),a.value.length===0?s.children.shift():s.position&&a.position&&typeof a.position.start.offset=="number"&&(a.position.start.column++,a.position.start.offset++,s.position.start=Object.assign({},a.position.start)))}}this.exit(e)}function lT(e,n,s,a){const r=e.children[0],o=typeof e.checked=="boolean"&&r&&r.type==="paragraph",l="["+(e.checked?"x":" ")+"] ",c=s.createTracker(a);o&&c.move(l);let d=av.listItem(e,n,s,{...a,...c.current()});return o&&(d=d.replace(/^(?:[*+-]|\d+\.)([\r\n]| {1,3})/,u)),d;function u(h){return h+l}}function cT(){return[BR(),lI(),mI(),XI(),aT()]}function dT(e){return{extensions:[UR(),cI(e),hI(),iT(e),rT()]}}const uT={tokenize:bT,partial:!0},rv={tokenize:xT,partial:!0},ov={tokenize:vT,partial:!0},lv={tokenize:yT,partial:!0},mT={tokenize:wT,partial:!0},cv={name:"wwwAutolink",tokenize:fT,previous:uv},dv={name:"protocolAutolink",tokenize:gT,previous:mv},Zi={name:"emailAutolink",tokenize:pT,previous:hv},Fi={};function hT(){return{text:Fi}}let Pa=48;for(;Pa<123;)Fi[Pa]=Zi,Pa++,Pa===58?Pa=65:Pa===91&&(Pa=97);Fi[43]=Zi;Fi[45]=Zi;Fi[46]=Zi;Fi[95]=Zi;Fi[72]=[Zi,dv];Fi[104]=[Zi,dv];Fi[87]=[Zi,cv];Fi[119]=[Zi,cv];function pT(e,n,s){const a=this;let r,o;return l;function l(m){return!Au(m)||!hv.call(a,a.previous)||Nm(a.events)?s(m):(e.enter("literalAutolink"),e.enter("literalAutolinkEmail"),c(m))}function c(m){return Au(m)?(e.consume(m),c):m===64?(e.consume(m),d):s(m)}function d(m){return m===46?e.check(mT,h,u)(m):m===45||m===95||Ts(m)?(o=!0,e.consume(m),d):h(m)}function u(m){return e.consume(m),r=!0,d}function h(m){return o&&r&&Fs(a.previous)?(e.exit("literalAutolinkEmail"),e.exit("literalAutolink"),n(m)):s(m)}}function fT(e,n,s){const a=this;return r;function r(l){return l!==87&&l!==119||!uv.call(a,a.previous)||Nm(a.events)?s(l):(e.enter("literalAutolink"),e.enter("literalAutolinkWww"),e.check(uT,e.attempt(rv,e.attempt(ov,o),s),s)(l))}function o(l){return e.exit("literalAutolinkWww"),e.exit("literalAutolink"),n(l)}}function gT(e,n,s){const a=this;let r="",o=!1;return l;function l(m){return(m===72||m===104)&&mv.call(a,a.previous)&&!Nm(a.events)?(e.enter("literalAutolink"),e.enter("literalAutolinkHttp"),r+=String.fromCodePoint(m),e.consume(m),c):s(m)}function c(m){if(Fs(m)&&r.length<5)return r+=String.fromCodePoint(m),e.consume(m),c;if(m===58){const f=r.toLowerCase();if(f==="http"||f==="https")return e.consume(m),d}return s(m)}function d(m){return m===47?(e.consume(m),o?u:(o=!0,d)):s(m)}function u(m){return m===null||sc(m)||Yn(m)||Va(m)||Mc(m)?s(m):e.attempt(rv,e.attempt(ov,h),s)(m)}function h(m){return e.exit("literalAutolinkHttp"),e.exit("literalAutolink"),n(m)}}function bT(e,n,s){let a=0;return r;function r(l){return(l===87||l===119)&&a<3?(a++,e.consume(l),r):l===46&&a===3?(e.consume(l),o):s(l)}function o(l){return l===null?s(l):n(l)}}function xT(e,n,s){let a,r,o;return l;function l(u){return u===46||u===95?e.check(lv,d,c)(u):u===null||Yn(u)||Va(u)||u!==45&&Mc(u)?d(u):(o=!0,e.consume(u),l)}function c(u){return u===95?a=!0:(r=a,a=void 0),e.consume(u),l}function d(u){return r||a||!o?s(u):n(u)}}function vT(e,n){let s=0,a=0;return r;function r(l){return l===40?(s++,e.consume(l),r):l===41&&a<s?o(l):l===33||l===34||l===38||l===39||l===41||l===42||l===44||l===46||l===58||l===59||l===60||l===63||l===93||l===95||l===126?e.check(lv,n,o)(l):l===null||Yn(l)||Va(l)?n(l):(e.consume(l),r)}function o(l){return l===41&&a++,e.consume(l),r}}function yT(e,n,s){return a;function a(c){return c===33||c===34||c===39||c===41||c===42||c===44||c===46||c===58||c===59||c===63||c===95||c===126?(e.consume(c),a):c===38?(e.consume(c),o):c===93?(e.consume(c),r):c===60||c===null||Yn(c)||Va(c)?n(c):s(c)}function r(c){return c===null||c===40||c===91||Yn(c)||Va(c)?n(c):a(c)}function o(c){return Fs(c)?l(c):s(c)}function l(c){return c===59?(e.consume(c),a):Fs(c)?(e.consume(c),l):s(c)}}function wT(e,n,s){return a;function a(o){return e.consume(o),r}function r(o){return Ts(o)?s(o):n(o)}}function uv(e){return e===null||e===40||e===42||e===95||e===91||e===93||e===126||Yn(e)}function mv(e){return!Fs(e)}function hv(e){return!(e===47||Au(e))}function Au(e){return e===43||e===45||e===46||e===95||Ts(e)}function Nm(e){let n=e.length,s=!1;for(;n--;){const a=e[n][1];if((a.type==="labelLink"||a.type==="labelImage")&&!a._balanced){s=!0;break}if(a._gfmAutolinkLiteralWalkedInto){s=!1;break}}return e.length>0&&!s&&(e[e.length-1][1]._gfmAutolinkLiteralWalkedInto=!0),s}const kT={tokenize:AT,partial:!0};function jT(){return{document:{91:{name:"gfmFootnoteDefinition",tokenize:ET,continuation:{tokenize:_T},exit:MT}},text:{91:{name:"gfmFootnoteCall",tokenize:CT},93:{name:"gfmPotentialFootnoteCall",add:"after",tokenize:NT,resolveTo:ST}}}}function NT(e,n,s){const a=this;let r=a.events.length;const o=a.parser.gfmFootnotes||(a.parser.gfmFootnotes=[]);let l;for(;r--;){const d=a.events[r][1];if(d.type==="labelImage"){l=d;break}if(d.type==="gfmFootnoteCall"||d.type==="labelLink"||d.type==="label"||d.type==="image"||d.type==="link")break}return c;function c(d){if(!l||!l._balanced)return s(d);const u=ji(a.sliceSerialize({start:l.end,end:a.now()}));return u.codePointAt(0)!==94||!o.includes(u.slice(1))?s(d):(e.enter("gfmFootnoteCallLabelMarker"),e.consume(d),e.exit("gfmFootnoteCallLabelMarker"),n(d))}}function ST(e,n){let s=e.length;for(;s--;)if(e[s][1].type==="labelImage"&&e[s][0]==="enter"){e[s][1];break}e[s+1][1].type="data",e[s+3][1].type="gfmFootnoteCallLabelMarker";const a={type:"gfmFootnoteCall",start:Object.assign({},e[s+3][1].start),end:Object.assign({},e[e.length-1][1].end)},r={type:"gfmFootnoteCallMarker",start:Object.assign({},e[s+3][1].end),end:Object.assign({},e[s+3][1].end)};r.end.column++,r.end.offset++,r.end._bufferIndex++;const o={type:"gfmFootnoteCallString",start:Object.assign({},r.end),end:Object.assign({},e[e.length-1][1].start)},l={type:"chunkString",contentType:"string",start:Object.assign({},o.start),end:Object.assign({},o.end)},c=[e[s+1],e[s+2],["enter",a,n],e[s+3],e[s+4],["enter",r,n],["exit",r,n],["enter",o,n],["enter",l,n],["exit",l,n],["exit",o,n],e[e.length-2],e[e.length-1],["exit",a,n]];return e.splice(s,e.length-s+1,...c),e}function CT(e,n,s){const a=this,r=a.parser.gfmFootnotes||(a.parser.gfmFootnotes=[]);let o=0,l;return c;function c(m){return e.enter("gfmFootnoteCall"),e.enter("gfmFootnoteCallLabelMarker"),e.consume(m),e.exit("gfmFootnoteCallLabelMarker"),d}function d(m){return m!==94?s(m):(e.enter("gfmFootnoteCallMarker"),e.consume(m),e.exit("gfmFootnoteCallMarker"),e.enter("gfmFootnoteCallString"),e.enter("chunkString").contentType="string",u)}function u(m){if(o>999||m===93&&!l||m===null||m===91||Yn(m))return s(m);if(m===93){e.exit("chunkString");const f=e.exit("gfmFootnoteCallString");return r.includes(ji(a.sliceSerialize(f)))?(e.enter("gfmFootnoteCallLabelMarker"),e.consume(m),e.exit("gfmFootnoteCallLabelMarker"),e.exit("gfmFootnoteCall"),n):s(m)}return Yn(m)||(l=!0),o++,e.consume(m),m===92?h:u}function h(m){return m===91||m===92||m===93?(e.consume(m),o++,u):u(m)}}function ET(e,n,s){const a=this,r=a.parser.gfmFootnotes||(a.parser.gfmFootnotes=[]);let o,l=0,c;return d;function d(g){return e.enter("gfmFootnoteDefinition")._container=!0,e.enter("gfmFootnoteDefinitionLabel"),e.enter("gfmFootnoteDefinitionLabelMarker"),e.consume(g),e.exit("gfmFootnoteDefinitionLabelMarker"),u}function u(g){return g===94?(e.enter("gfmFootnoteDefinitionMarker"),e.consume(g),e.exit("gfmFootnoteDefinitionMarker"),e.enter("gfmFootnoteDefinitionLabelString"),e.enter("chunkString").contentType="string",h):s(g)}function h(g){if(l>999||g===93&&!c||g===null||g===91||Yn(g))return s(g);if(g===93){e.exit("chunkString");const w=e.exit("gfmFootnoteDefinitionLabelString");return o=ji(a.sliceSerialize(w)),e.enter("gfmFootnoteDefinitionLabelMarker"),e.consume(g),e.exit("gfmFootnoteDefinitionLabelMarker"),e.exit("gfmFootnoteDefinitionLabel"),f}return Yn(g)||(c=!0),l++,e.consume(g),g===92?m:h}function m(g){return g===91||g===92||g===93?(e.consume(g),l++,h):h(g)}function f(g){return g===58?(e.enter("definitionMarker"),e.consume(g),e.exit("definitionMarker"),r.includes(o)||r.push(o),Mn(e,p,"gfmFootnoteDefinitionWhitespace")):s(g)}function p(g){return n(g)}}function _T(e,n,s){return e.check(tl,n,e.attempt(kT,n,s))}function MT(e){e.exit("gfmFootnoteDefinition")}function AT(e,n,s){const a=this;return Mn(e,r,"gfmFootnoteDefinitionIndent",5);function r(o){const l=a.events[a.events.length-1];return l&&l[1].type==="gfmFootnoteDefinitionIndent"&&l[2].sliceSerialize(l[1],!0).length===4?n(o):s(o)}}function RT(e){let s=(e||{}).singleTilde;const a={name:"strikethrough",tokenize:o,resolveAll:r};return s==null&&(s=!0),{text:{126:a},insideSpan:{null:[a]},attentionMarkers:{null:[126]}};function r(l,c){let d=-1;for(;++d<l.length;)if(l[d][0]==="enter"&&l[d][1].type==="strikethroughSequenceTemporary"&&l[d][1]._close){let u=d;for(;u--;)if(l[u][0]==="exit"&&l[u][1].type==="strikethroughSequenceTemporary"&&l[u][1]._open&&l[d][1].end.offset-l[d][1].start.offset===l[u][1].end.offset-l[u][1].start.offset){l[d][1].type="strikethroughSequence",l[u][1].type="strikethroughSequence";const h={type:"strikethrough",start:Object.assign({},l[u][1].start),end:Object.assign({},l[d][1].end)},m={type:"strikethroughText",start:Object.assign({},l[u][1].end),end:Object.assign({},l[d][1].start)},f=[["enter",h,c],["enter",l[u][1],c],["exit",l[u][1],c],["enter",m,c]],p=c.parser.constructs.insideSpan.null;p&&Xs(f,f.length,0,Ac(p,l.slice(u+1,d),c)),Xs(f,f.length,0,[["exit",m,c],["enter",l[d][1],c],["exit",l[d][1],c],["exit",h,c]]),Xs(l,u-1,d-u+3,f),d=u+f.length-2;break}}for(d=-1;++d<l.length;)l[d][1].type==="strikethroughSequenceTemporary"&&(l[d][1].type="data");return l}function o(l,c,d){const u=this.previous,h=this.events;let m=0;return f;function f(g){return u===126&&h[h.length-1][1].type!=="characterEscape"?d(g):(l.enter("strikethroughSequenceTemporary"),p(g))}function p(g){const w=Rr(u);if(g===126)return m>1?d(g):(l.consume(g),m++,p);if(m<2&&!s)return d(g);const v=l.exit("strikethroughSequenceTemporary"),b=Rr(g);return v._open=!b||b===2&&!!w,v._close=!w||w===2&&!!b,c(g)}}}class IT{constructor(){this.map=[]}add(n,s,a){TT(this,n,s,a)}consume(n){if(this.map.sort(function(o,l){return o[0]-l[0]}),this.map.length===0)return;let s=this.map.length;const a=[];for(;s>0;)s-=1,a.push(n.slice(this.map[s][0]+this.map[s][1]),this.map[s][2]),n.length=this.map[s][0];a.push(n.slice()),n.length=0;let r=a.pop();for(;r;){for(const o of r)n.push(o);r=a.pop()}this.map.length=0}}function TT(e,n,s,a){let r=0;if(!(s===0&&a.length===0)){for(;r<e.map.length;){if(e.map[r][0]===n){e.map[r][1]+=s,e.map[r][2].push(...a);return}r+=1}e.map.push([n,s,a])}}function PT(e,n){let s=!1;const a=[];for(;n<e.length;){const r=e[n];if(s){if(r[0]==="enter")r[1].type==="tableContent"&&a.push(e[n+1][1].type==="tableDelimiterMarker"?"left":"none");else if(r[1].type==="tableContent"){if(e[n-1][1].type==="tableDelimiterMarker"){const o=a.length-1;a[o]=a[o]==="left"?"center":"right"}}else if(r[1].type==="tableDelimiterRow")break}else r[0]==="enter"&&r[1].type==="tableDelimiterRow"&&(s=!0);n+=1}return a}function $T(){return{flow:{null:{name:"table",tokenize:DT,resolveAll:LT}}}}function DT(e,n,s){const a=this;let r=0,o=0,l;return c;function c(E){let _=a.events.length-1;for(;_>-1;){const A=a.events[_][1].type;if(A==="lineEnding"||A==="linePrefix")_--;else break}const G=_>-1?a.events[_][1].type:null,H=G==="tableHead"||G==="tableRow"?x:d;return H===x&&a.parser.lazy[a.now().line]?s(E):H(E)}function d(E){return e.enter("tableHead"),e.enter("tableRow"),u(E)}function u(E){return E===124||(l=!0,o+=1),h(E)}function h(E){return E===null?s(E):en(E)?o>1?(o=0,a.interrupt=!0,e.exit("tableRow"),e.enter("lineEnding"),e.consume(E),e.exit("lineEnding"),p):s(E):jn(E)?Mn(e,h,"whitespace")(E):(o+=1,l&&(l=!1,r+=1),E===124?(e.enter("tableCellDivider"),e.consume(E),e.exit("tableCellDivider"),l=!0,h):(e.enter("data"),m(E)))}function m(E){return E===null||E===124||Yn(E)?(e.exit("data"),h(E)):(e.consume(E),E===92?f:m)}function f(E){return E===92||E===124?(e.consume(E),m):m(E)}function p(E){return a.interrupt=!1,a.parser.lazy[a.now().line]?s(E):(e.enter("tableDelimiterRow"),l=!1,jn(E)?Mn(e,g,"linePrefix",a.parser.constructs.disable.null.includes("codeIndented")?void 0:4)(E):g(E))}function g(E){return E===45||E===58?v(E):E===124?(l=!0,e.enter("tableCellDivider"),e.consume(E),e.exit("tableCellDivider"),w):C(E)}function w(E){return jn(E)?Mn(e,v,"whitespace")(E):v(E)}function v(E){return E===58?(o+=1,l=!0,e.enter("tableDelimiterMarker"),e.consume(E),e.exit("tableDelimiterMarker"),b):E===45?(o+=1,b(E)):E===null||en(E)?S(E):C(E)}function b(E){return E===45?(e.enter("tableDelimiterFiller"),y(E)):C(E)}function y(E){return E===45?(e.consume(E),y):E===58?(l=!0,e.exit("tableDelimiterFiller"),e.enter("tableDelimiterMarker"),e.consume(E),e.exit("tableDelimiterMarker"),j):(e.exit("tableDelimiterFiller"),j(E))}function j(E){return jn(E)?Mn(e,S,"whitespace")(E):S(E)}function S(E){return E===124?g(E):E===null||en(E)?!l||r!==o?C(E):(e.exit("tableDelimiterRow"),e.exit("tableHead"),n(E)):C(E)}function C(E){return s(E)}function x(E){return e.enter("tableRow"),k(E)}function k(E){return E===124?(e.enter("tableCellDivider"),e.consume(E),e.exit("tableCellDivider"),k):E===null||en(E)?(e.exit("tableRow"),n(E)):jn(E)?Mn(e,k,"whitespace")(E):(e.enter("data"),R(E))}function R(E){return E===null||E===124||Yn(E)?(e.exit("data"),k(E)):(e.consume(E),E===92?O:R)}function O(E){return E===92||E===124?(e.consume(E),R):R(E)}}function LT(e,n){let s=-1,a=!0,r=0,o=[0,0,0,0],l=[0,0,0,0],c=!1,d=0,u,h,m;const f=new IT;for(;++s<e.length;){const p=e[s],g=p[1];p[0]==="enter"?g.type==="tableHead"?(c=!1,d!==0&&(qp(f,n,d,u,h),h=void 0,d=0),u={type:"table",start:Object.assign({},g.start),end:Object.assign({},g.end)},f.add(s,0,[["enter",u,n]])):g.type==="tableRow"||g.type==="tableDelimiterRow"?(a=!0,m=void 0,o=[0,0,0,0],l=[0,s+1,0,0],c&&(c=!1,h={type:"tableBody",start:Object.assign({},g.start),end:Object.assign({},g.end)},f.add(s,0,[["enter",h,n]])),r=g.type==="tableDelimiterRow"?2:h?3:1):r&&(g.type==="data"||g.type==="tableDelimiterMarker"||g.type==="tableDelimiterFiller")?(a=!1,l[2]===0&&(o[1]!==0&&(l[0]=l[1],m=gl(f,n,o,r,void 0,m),o=[0,0,0,0]),l[2]=s)):g.type==="tableCellDivider"&&(a?a=!1:(o[1]!==0&&(l[0]=l[1],m=gl(f,n,o,r,void 0,m)),o=l,l=[o[1],s,0,0])):g.type==="tableHead"?(c=!0,d=s):g.type==="tableRow"||g.type==="tableDelimiterRow"?(d=s,o[1]!==0?(l[0]=l[1],m=gl(f,n,o,r,s,m)):l[1]!==0&&(m=gl(f,n,l,r,s,m)),r=0):r&&(g.type==="data"||g.type==="tableDelimiterMarker"||g.type==="tableDelimiterFiller")&&(l[3]=s)}for(d!==0&&qp(f,n,d,u,h),f.consume(n.events),s=-1;++s<n.events.length;){const p=n.events[s];p[0]==="enter"&&p[1].type==="table"&&(p[1]._align=PT(n.events,s))}return e}function gl(e,n,s,a,r,o){const l=a===1?"tableHeader":a===2?"tableDelimiter":"tableData",c="tableContent";s[0]!==0&&(o.end=Object.assign({},vr(n.events,s[0])),e.add(s[0],0,[["exit",o,n]]));const d=vr(n.events,s[1]);if(o={type:l,start:Object.assign({},d),end:Object.assign({},d)},e.add(s[1],0,[["enter",o,n]]),s[2]!==0){const u=vr(n.events,s[2]),h=vr(n.events,s[3]),m={type:c,start:Object.assign({},u),end:Object.assign({},h)};if(e.add(s[2],0,[["enter",m,n]]),a!==2){const f=n.events[s[2]],p=n.events[s[3]];if(f[1].end=Object.assign({},p[1].end),f[1].type="chunkText",f[1].contentType="text",s[3]>s[2]+1){const g=s[2]+1,w=s[3]-s[2]-1;e.add(g,w,[])}}e.add(s[3]+1,0,[["exit",m,n]])}return r!==void 0&&(o.end=Object.assign({},vr(n.events,r)),e.add(r,0,[["exit",o,n]]),o=void 0),o}function qp(e,n,s,a,r){const o=[],l=vr(n.events,s);r&&(r.end=Object.assign({},l),o.push(["exit",r,n])),a.end=Object.assign({},l),o.push(["exit",a,n]),e.add(s+1,0,o)}function vr(e,n){const s=e[n],a=s[0]==="enter"?"start":"end";return s[1][a]}const OT={name:"tasklistCheck",tokenize:zT};function FT(){return{text:{91:OT}}}function zT(e,n,s){const a=this;return r;function r(d){return a.previous!==null||!a._gfmTasklistFirstContentOfListItem?s(d):(e.enter("taskListCheck"),e.enter("taskListCheckMarker"),e.consume(d),e.exit("taskListCheckMarker"),o)}function o(d){return Yn(d)?(e.enter("taskListCheckValueUnchecked"),e.consume(d),e.exit("taskListCheckValueUnchecked"),l):d===88||d===120?(e.enter("taskListCheckValueChecked"),e.consume(d),e.exit("taskListCheckValueChecked"),l):s(d)}function l(d){return d===93?(e.enter("taskListCheckMarker"),e.consume(d),e.exit("taskListCheckMarker"),e.exit("taskListCheck"),c):s(d)}function c(d){return en(d)?n(d):jn(d)?e.check({tokenize:BT},n,s)(d):s(d)}}function BT(e,n,s){return Mn(e,a,"whitespace");function a(r){return r===null?s(r):n(r)}}function UT(e){return Nx([hT(),jT(),RT(e),$T(),FT()])}const HT={};function pi(e){const n=this,s=e||HT,a=n.data(),r=a.micromarkExtensions||(a.micromarkExtensions=[]),o=a.fromMarkdownExtensions||(a.fromMarkdownExtensions=[]),l=a.toMarkdownExtensions||(a.toMarkdownExtensions=[]);r.push(UT(s)),o.push(cT()),l.push(dT(s))}const qT=45e3,VT=3e3,WT=2e3,GT=1500,Vp="fusion:sse-client-id";let hr=null;const fa=new Map;function Wp(){const e=typeof globalThis<"u"?globalThis.crypto:void 0;return e&&typeof e.randomUUID=="function"?e.randomUUID():`${Date.now().toString(36)}-${Math.random().toString(36).slice(2)}`}function pv(){if(!(typeof window>"u")){if(hr)return hr;try{const e=window.sessionStorage.getItem(Vp);if(e)return hr=e,e;const n=Wp();return window.sessionStorage.setItem(Vp,n),hr=n,n}catch{return hr=Wp(),hr}}}function fv(e){if(!(typeof window>"u"))try{return{parsed:new URL(e,window.location.origin),preserveRelativePath:e.startsWith("/")}}catch{return}}function gv(e){return e.origin===window.location.origin&&e.pathname==="/api/events"}function KT(e){const n=pv();if(!n)return e;const s=fv(e);return!s||!gv(s.parsed)?e:(s.parsed.searchParams.set("clientId",n),s.preserveRelativePath?`${s.parsed.pathname}${s.parsed.search}${s.parsed.hash}`:s.parsed.toString())}function Sm(e,n){const s=pv();if(!s)return;const a=fv(e);if(!a||!gv(a.parsed))return;const r=new URL(`/api/events/${n}`,window.location.origin);r.searchParams.set("clientId",s);const o=a.parsed.searchParams.get("projectId");return o&&r.searchParams.set("projectId",o),Li(`${r.pathname}${r.search}${r.hash}`)}function JT(e){if(typeof window>"u")return;const n=Sm(e.url,"disconnect");if(!n)return;const s=window.navigator?.sendBeacon?.bind(window.navigator);s&&s(n)||typeof window.fetch=="function"&&window.fetch(n,{method:"POST",keepalive:!0}).catch(()=>{})}function Pc(e){e.keepaliveTimer&&(clearInterval(e.keepaliveTimer),e.keepaliveTimer=null)}function Gp(e){if(typeof window>"u"||typeof window.fetch!="function")return;const n=Sm(e.url,"keepalive");if(!n)return;const s=typeof AbortController<"u"?new AbortController:null,a=s?window.setTimeout(()=>s.abort(),GT):null;window.fetch(n,{method:"POST",cache:"no-store",signal:s?.signal}).catch(()=>{}).finally(()=>{a!==null&&window.clearTimeout(a)})}function YT(e){Pc(e),Sm(e.url,"keepalive")&&(Gp(e),e.keepaliveTimer=window.setInterval(()=>{Gp(e)},WT))}if(typeof window<"u"){const e=()=>{for(const s of Array.from(fa.values()))if(!s.closed){if(Pc(s),JT(s),s.es){try{s.es.close()}catch{}s.es=null}s.closed=!0}},n=s=>{if(s.persisted)for(const a of Array.from(fa.values()))a.subscribers.size!==0&&(a.closed=!1,Cm(a))};window.addEventListener("pagehide",e),window.addEventListener("beforeunload",e),window.addEventListener("pageshow",n)}function jo(e){e.heartbeatTimer&&clearTimeout(e.heartbeatTimer),e.heartbeatTimer=setTimeout(()=>{bv(e)},qT)}function bv(e){if(e.heartbeatTimer&&(clearTimeout(e.heartbeatTimer),e.heartbeatTimer=null),e.es&&(e.es.close(),e.es=null),Pc(e),e.nativeListeners.clear(),e.closed||e.subscribers.size===0||e.reconnectTimer)return;const n=fa.get(e.url);if(!(!n||n!==e)){for(const s of e.subscribers)s.onReconnect?.();e.reconnectTimer=setTimeout(()=>{if(e.reconnectTimer=null,e.closed)return;const s=fa.get(e.url);s&&s===e&&e.subscribers.size>0&&Cm(e)},VT)}}function Cm(e){if(e.es||e.closed)return;e.reconnectTimer&&(clearTimeout(e.reconnectTimer),e.reconnectTimer=null);const n=new EventSource(Li(KT(e.url)));e.es=n,YT(e),n.addEventListener("open",()=>{jo(e);const s=e.hasOpenedOnce;e.hasOpenedOnce=!0;for(const a of e.subscribers)a.onOpen?.(),s&&a.onReconnect?.()}),n.addEventListener("error",s=>{for(const a of e.subscribers)a.onError?.(s);bv(e)}),n.addEventListener("message",()=>jo(e)),n.addEventListener("heartbeat",()=>jo(e)),xv(e),jo(e)}function xv(e){if(!e.es)return;const n=new Set;for(const s of e.subscribers)for(const a of s.events.keys())n.add(a);for(const s of n){if(e.nativeListeners.has(s))continue;const a=r=>{jo(e);const o=r;for(const l of e.subscribers){const c=l.events.get(s);if(c)for(const d of c)d(o)}};e.nativeListeners.set(s,a),e.es.addEventListener(s,a)}}function QT(e){e.closed=!0,e.heartbeatTimer&&clearTimeout(e.heartbeatTimer),Pc(e),e.reconnectTimer&&clearTimeout(e.reconnectTimer),e.es&&e.es.close(),e.es=null,e.nativeListeners.clear(),fa.delete(e.url)}function fi(e,n={}){let s=fa.get(e);s||(s={url:e,es:null,subscribers:new Set,nativeListeners:new Map,heartbeatTimer:null,keepaliveTimer:null,reconnectTimer:null,hasOpenedOnce:!1,closed:!1},fa.set(e,s));const a={events:new Map,onOpen:n.onOpen,onReconnect:n.onReconnect,onError:n.onError};if(n.events)for(const[l,c]of Object.entries(n.events)){let d=a.events.get(l);d||(d=new Set,a.events.set(l,d)),d.add(c)}s.subscribers.add(a);const r=!!s.es&&s.hasOpenedOnce;Cm(s),xv(s),r&&queueMicrotask(()=>{s.subscribers.has(a)&&a.onOpen?.()});let o=!0;return()=>{if(!o)return;o=!1;const l=fa.get(e);l&&(l.subscribers.delete(a),l.subscribers.size===0&&QT(l))}}const Kp=100;function vv(e,n,s){const[a,r]=i.useState([]),[o,l]=i.useState(!1),[c,d]=i.useState(!1),[u,h]=i.useState(null),[m,f]=i.useState(!1),p=i.useRef(null),g=i.useRef(!1),w=i.useRef(0),v=i.useRef(e),b=i.useRef(s),y=i.useRef(n),j=i.useRef(0);(v.current!==e||b.current!==s||y.current!==n)&&(v.current=e,b.current=s,y.current=n,w.current++,g.current=!0,r([]),l(!1),d(!1),h(null),f(!1),p.current&&(p.current(),p.current=null)),i.useEffect(()=>{if(!e||!n){p.current&&(p.current(),p.current=null);return}const k=w.current,R=++j.current;g.current=!1;const O=e,E=s;async function _(){if(!O)return;l(!0),f(!1);try{const H=await Jm(O,E,{limit:Kp});if(g.current||w.current!==k||j.current!==R)return;r(H.entries),d(H.hasMore),h(H.total)}catch{if(g.current||w.current!==k||j.current!==R)return;r([]),d(!1),h(null)}finally{!g.current&&w.current===k&&j.current===R&&l(!1)}const G=E?`?projectId=${encodeURIComponent(E)}`:"";p.current=fi(`/api/tasks/${O}/logs/stream${G}`,{events:{"agent:log":H=>{if(!(g.current||w.current!==k))try{const A=JSON.parse(H.data);r(P=>[...P,A]),h(P=>P!==null?P+1:null)}catch{}}}})}return _(),()=>{g.current=!0,p.current&&(p.current(),p.current=null)}},[e,n,s]);const C=i.useCallback(async()=>{if(!e||m)return;const k=w.current,R=a.length,O=e;f(!0);try{const E=await Jm(O,s,{limit:Kp,offset:R});if(g.current||w.current!==k)return;r(_=>[...E.entries,..._]),d(E.hasMore),h(E.total)}catch{}finally{f(!1)}},[e,s,a.length,m]),x=i.useCallback(()=>r([]),[]);return{entries:a,loading:o,clear:x,loadMore:C,hasMore:c,total:u,loadingMore:m}}const yv=i.createContext(null);function XT({openFile:e,children:n}){return t.jsx(yv.Provider,{value:{openFile:e},children:n})}function ZT(){return i.useContext(yv)}const eP=/(?<![\w@-])((?:[A-Za-z0-9_./@-]+\/)+[A-Za-z0-9_./@-]+\.[A-Za-z0-9]{1,8}(?::\d+(?::\d+)?)?|(?:Dockerfile|Makefile|AGENTS\.md|README\.md|README)(?::\d+(?::\d+)?)?)(?![\w-])/g,tP=["http://","https://","mailto:","git@","ftp://"],nP=new Set(["Dockerfile","Makefile","AGENTS.md","README.md","README"]);function wv(e){const n=/^(.*?)(?::(\d+)(?::(\d+))?)?$/.exec(e);return n?{path:n[1]??e,line:n[2]?Number.parseInt(n[2],10):void 0,col:n[3]?Number.parseInt(n[3],10):void 0}:{path:e}}function sP(e){return/^v?\d+(?:\.\d+)+$/.test(e)}function iP(e){return e.includes("/")||nP.has(e)}function aP(e,n,s){const a=e.slice(Math.max(0,n-16),n).toLowerCase();if(s.startsWith("//")||tP.some(o=>a.endsWith(o)))return!0;const{path:r}=wv(s);return!!(sP(r)||!iP(r))}function rP({path:e,line:n,col:s,children:a}){const r=ZT();return r?t.jsx("button",{type:"button",className:"file-path-link",onClick:()=>r.openFile(e,{line:n,col:s}),children:a??e}):t.jsx("span",{children:a??e})}function ks(e,n){if(!e)return[e];const s=[];let a=0,r=0;for(const o of e.matchAll(eP)){const l=o[0],c=o.index??0,d=c+l.length;if(aP(e,c,l))continue;c>a&&s.push(e.slice(a,c));const{path:u,line:h,col:m}=wv(l);s.push(t.jsx(rP,{path:u,line:h,col:m,children:l},`file-path-${c}-${r}`)),a=d,r+=1}return a===0?[e]:(a<e.length&&s.push(e.slice(a)),s)}function Ws(e){if(typeof e=="string"){const n=ks(e);return n.length===1?n[0]:t.jsx(t.Fragment,{children:n})}return Array.isArray(e)?ga.Children.map(e,n=>Ws(n)):!i.isValidElement(e)||typeof e.type=="string"&&["button","code","pre"].includes(e.type)||e.props.children===void 0?e:i.cloneElement(e,void 0,ga.Children.map(e.props.children,n=>Ws(n)))}const Jp="fn-agent-log-markdown",Yp="fn-agent-log-tool-output";function Qp(e,n){if(typeof window>"u")return n;try{const s=window.localStorage.getItem(e);return s===null?n:s==="true"}catch{return n}}function Xp(e,n){if(!(typeof window>"u"))try{window.localStorage.setItem(e,n?"true":"false")}catch{}}function oP(e){const n=new Date(e),a=new Date().getTime()-n.getTime(),r=Math.floor(a/6e4),o=Math.floor(r/60),l=Math.floor(o/24);return r<1?"just now":r<60?`${r}m ago`:o<24?`${o}h ago`:l<7?`${l}d ago`:n.toLocaleDateString()}const Zp={p:({children:e,...n})=>t.jsx("p",{...n,children:Ws(e)}),li:({children:e,...n})=>t.jsx("li",{...n,children:Ws(e)}),code:({children:e,...n})=>{const s=typeof e=="string"?e:ga.Children.toArray(e).join(""),a=ks(s);return a.length===1&&typeof a[0]=="string"?t.jsx("code",{...n,children:e}):t.jsx("code",{...n,children:a})},pre:({children:e,...n})=>t.jsx("pre",{...n,style:{overflowX:"auto",maxWidth:"100%",whiteSpace:"pre-wrap",wordBreak:"break-word"},children:e}),table:({children:e,...n})=>t.jsx("table",{...n,style:{display:"block",overflowX:"auto",maxWidth:"100%"},children:e})},kv=50,lP={triage:"Plan"};function ef(e){return e.scrollHeight-(e.scrollTop+e.clientHeight)<=kv}function Ru(e){return[e.taskId,e.timestamp,e.agent??"",e.type,e.text,e.detail??""].join("|")}function cP(e){const n=new Map;return e.map(s=>{const a=Ru(s),r=n.get(a)??0;return n.set(a,r+1),`${a}|${r}`})}function jv(e){return e==="tool"||e==="tool_result"||e==="tool_error"}function Cd({detail:e}){const[n,s]=i.useState(!1),a=i.useId(),r=e.split(`
682
- `).length,o=n?"Hide output":`Show output${r>1?` (${r} lines)`:""}`;return t.jsxs("div",{className:"agent-log-tool-detail-wrapper",children:[t.jsxs("button",{type:"button",className:"agent-log-tool-detail-toggle",onClick:()=>s(l=>!l),"aria-expanded":n,"aria-controls":a,"data-testid":"tool-detail-toggle",children:[n?t.jsx(vn,{size:14}):t.jsx(Wn,{size:14}),t.jsx("span",{children:o})]}),t.jsx("div",{id:a,className:n?"agent-log-tool-detail-content":"agent-log-tool-detail-content agent-log-tool-detail-content--collapsed","data-testid":"tool-detail-content",children:t.jsx("pre",{className:"agent-log-tool-detail",children:ks(e)})})]})}function dP(e,n){return e.agent?jv(e.type)?!0:!n||n.agent!==e.agent||n.type!==e.type:!1}function uP(e,n){const s=[];for(let a=0;a<e.length;a+=1){const{entry:r,hiddenToolBoundaryId:o}=e[a],l=n[a]??`${Ru(r)}|fallback`,c=a>0?e[a-1]:void 0,d=c?.entry,u=dP(r,d)||c!==void 0&&c.hiddenToolBoundaryId!==o;if(r.type==="text"||r.type==="thinking"){const h=[r];let m=a+1;for(;m<e.length;){const p=e[m],g=p.entry;if(g.type!==r.type||g.agent!==r.agent||p.hiddenToolBoundaryId!==o)break;h.push(g),m+=1}const f=n[m-1]??`${Ru(e[m-1].entry)}|fallback`;s.push({kind:r.type,entries:h,key:`${l}->${f}`,showBadge:u}),a=m-1;continue}s.push({kind:"single",entry:r,key:l,showBadge:u})}return s}function mP({entries:e,loading:n,executorModel:s,validatorModel:a,planningModel:r,hasMore:o=!1,onLoadMore:l,loadingMore:c=!1,totalCount:d=null}){const u=i.useRef(null),h=i.useRef(0),m=i.useRef(0),f=i.useRef(null),p=i.useRef(null),[g,w]=i.useState(()=>Qp(Jp,!0)),[v,b]=i.useState(()=>Qp(Yp,!0)),[y,j]=i.useState(!1),[S,C]=i.useState(!1),[x,k]=i.useState(!0);i.useEffect(()=>{Xp(Jp,g)},[g]),i.useEffect(()=>{Xp(Yp,v)},[v]);const R=i.useMemo(()=>{if(v)return e.map($=>({entry:$,hiddenToolBoundaryId:0}));const L=[];let M=0;for(const $ of e){if(jv($.type)){M+=1;continue}L.push({entry:$,hiddenToolBoundaryId:M})}return L},[e,v]),O=i.useMemo(()=>R.map(L=>L.entry),[R]),E=i.useMemo(()=>cP(O),[O]),_=i.useMemo(()=>uP(R,E),[R,E]);i.useLayoutEffect(()=>{const L=u.current;if(!L)return;const M=e.length,$=h.current,D=m.current||L.scrollHeight,N=E[0]??null,W=E[E.length-1]??null,de=f.current!==N,me=p.current!==W;if(M>$)if($===0)L.scrollTop=L.scrollHeight;else{const Ne=D-(L.scrollTop+L.clientHeight)<=kv,ve=me&&!de,Me=de&&!me;if(ve&&Ne&&(L.scrollTop=L.scrollHeight),Me){const ie=L.scrollHeight-D;ie>0&&(L.scrollTop+=ie)}}h.current=M,m.current=L.scrollHeight,f.current=N,p.current=W,k(ef(L))},[e,E]);const G=i.useCallback(()=>{const L=u.current;L&&k(ef(L))},[]),H=i.useCallback(()=>{const L=u.current;L&&(L.scrollTop=L.scrollHeight,k(!0))},[]),A=i.useCallback(L=>{L.key==="Escape"&&y&&j(!1)},[y]);i.useEffect(()=>{if(y)return document.addEventListener("keydown",A),()=>{document.removeEventListener("keydown",A)}},[y,A]);const P=s?.provider&&s?.modelId,q=a?.provider&&a?.modelId,Y=r?.provider&&r?.modelId,ge=i.useMemo(()=>{const L=[];return P&&L.push({role:"Executor",provider:s.provider,modelId:s.modelId}),q&&L.push({role:"Reviewer",provider:a.provider,modelId:a.modelId}),Y&&L.push({role:"Planning",provider:r.provider,modelId:r.modelId}),L},[P,s,q,a,Y,r]);return n&&e.length===0?t.jsx("div",{className:"agent-log-viewer","data-testid":"agent-log-viewer",children:t.jsx("div",{className:"agent-log-loading",children:"Loading agent logs…"})}):e.length===0?t.jsx("div",{className:"agent-log-viewer","data-testid":"agent-log-viewer",children:t.jsx("div",{className:"agent-log-empty",children:"No agent output yet."})}):t.jsxs("div",{className:`agent-log-viewer agent-log-viewer--streaming${y?" agent-log-viewer--fullscreen":""}`,"data-testid":"agent-log-viewer",children:[t.jsxs("div",{className:"agent-log-model-header","data-testid":"agent-log-model-header",children:[t.jsxs("div",{className:"agent-log-model-icons",children:[ge.map(L=>t.jsx(On,{provider:L.provider,size:"sm"},`${L.role}-${L.provider}-${L.modelId??"default"}`)),t.jsx("button",{className:"agent-log-model-expand-btn",onClick:()=>C(L=>!L),"aria-label":S?"Collapse model details":"Expand model details","aria-expanded":S,"aria-controls":"agent-log-model-details","data-testid":"agent-log-model-expand",children:S?t.jsx(vn,{size:14}):t.jsx(Wn,{size:14})})]}),t.jsxs("div",{className:"agent-log-model-header-toggle",children:[t.jsx("button",{className:"agent-log-mode-toggle",onClick:()=>w(L=>!L),"aria-label":g?"Switch to plain text mode":"Switch to markdown mode","aria-pressed":g,"data-testid":"agent-log-mode-toggle",title:g?"Show raw text":"Show formatted markdown",children:g?"Markdown":"Plain"}),t.jsx("button",{className:"agent-log-mode-toggle",onClick:()=>b(L=>!L),"aria-label":v?"Hide tool output":"Show tool output","aria-pressed":v,"data-testid":"agent-log-tool-output-toggle",title:v?"Hide tool calls and results":"Show tool calls and results",children:v?"Tools: On":"Tools: Off"}),t.jsx("button",{className:"agent-log-mode-toggle",onClick:()=>j(L=>!L),"aria-label":y?"Exit full screen":"Expand agent log to full screen","data-testid":"agent-log-fullscreen-toggle",title:y?"Exit full screen":"Expand agent log to full screen",children:y?t.jsx(Vo,{size:14}):t.jsx(jc,{size:14})})]}),S&&t.jsxs("div",{id:"agent-log-model-details",className:"agent-log-model-details",children:[t.jsxs("div",{className:"agent-log-model-group",children:[t.jsx("span",{className:"agent-log-model-label",children:"Executor:"}),P?t.jsxs("span",{className:"agent-log-model-value",children:[t.jsx(On,{provider:s.provider,size:"sm"}),t.jsxs("span",{children:[s.provider,"/",s.modelId]})]}):t.jsx("span",{className:"model-badge-default",children:"Using default"})]}),t.jsxs("div",{className:"agent-log-model-group",children:[t.jsx("span",{className:"agent-log-model-label",children:"Reviewer:"}),q?t.jsxs("span",{className:"agent-log-model-value",children:[t.jsx(On,{provider:a.provider,size:"sm"}),t.jsxs("span",{children:[a.provider,"/",a.modelId]})]}):t.jsx("span",{className:"model-badge-default",children:"Using default"})]}),t.jsxs("div",{className:"agent-log-model-group",children:[t.jsx("span",{className:"agent-log-model-label",children:"Planning:"}),Y?t.jsxs("span",{className:"agent-log-model-value",children:[t.jsx(On,{provider:r.provider,size:"sm"}),t.jsxs("span",{children:[r.provider,"/",r.modelId]})]}):t.jsx("span",{className:"model-badge-default",children:"Using default"})]})]})]}),t.jsxs("div",{ref:u,className:"agent-log-viewer-scroll",onScroll:G,children:[d!==null&&t.jsxs("div",{className:"agent-log-summary","data-testid":"agent-log-summary",children:["Showing ",O.length," of ",d," entries",!v&&e.length!==O.length?` (${e.length-O.length} tool entries hidden)`:""]}),o&&l&&t.jsx("div",{className:"agent-log-load-more","data-testid":"agent-log-load-more",children:t.jsx("button",{className:"agent-log-mode-toggle",onClick:l,disabled:c,"data-testid":"agent-log-load-more-button",children:c?t.jsxs(t.Fragment,{children:[t.jsx(St,{size:14,className:"animate-spin"}),"Loading…"]}):"Load More"})}),_.map(L=>{const M=L.kind==="single"?L.entry:L.entries[0],$=L.showBadge?t.jsx("span",{className:"agent-log-timestamp","data-testid":"agent-log-timestamp",children:oP(M.timestamp)}):null,D=L.showBadge?t.jsxs("span",{className:"agent-log-badge-row",children:[t.jsxs("span",{className:"agent-log-agent-badge",children:["[",lP[M.agent]??M.agent,"]"]}),$]}):null;if(L.kind==="single"){const{entry:W}=L;if(W.type==="tool")return t.jsxs("div",{className:"agent-log-tool",children:[D,t.jsxs("div",{className:"agent-log-tool-title",children:["⚡ ",W.text]}),W.detail?t.jsx(Cd,{detail:W.detail,type:"tool"}):null]},L.key);if(W.type==="tool_result")return t.jsxs("div",{className:"agent-log-tool-result",children:[D,t.jsxs("div",{className:"agent-log-tool-title",children:["✓ ",W.text]}),W.detail?t.jsx(Cd,{detail:W.detail,type:"tool_result"}):null]},L.key);if(W.type==="tool_error")return t.jsxs("div",{className:"agent-log-tool-error",children:[D,t.jsxs("div",{className:"agent-log-tool-title",children:["✗ ",W.text]}),W.detail?t.jsx(Cd,{detail:W.detail,type:"tool_error"}):null]},L.key)}const N=L.kind==="single"?M.text:L.entries.map(W=>W.text).join("");return L.kind==="thinking"?t.jsxs("div",{className:"agent-log-thinking",children:[D,g?t.jsx("div",{className:"markdown-body",children:t.jsx(hi,{remarkPlugins:[pi],components:Zp,children:N})}):t.jsx("pre",{className:"agent-log-plain-block",children:ks(N)})]},L.key):t.jsxs("div",{className:"agent-log-text",children:[D,g?t.jsx("div",{className:"markdown-body",children:t.jsx(hi,{remarkPlugins:[pi],components:Zp,children:N})}):t.jsx("pre",{className:"agent-log-plain-block",children:ks(N)})]},L.key)}),!x&&t.jsxs("button",{type:"button",className:"agent-log-return-to-live",onClick:H,"data-testid":"agent-log-return-to-live",children:[t.jsx(vn,{size:12}),t.jsx("span",{children:"Live"})]})]})]})}function Ir(e){return e??void 0}function bl(e){return{provider:Ir(e.modelProvider),modelId:Ir(e.modelId)}}function xl(e){return{provider:Ir(e.validatorModelProvider),modelId:Ir(e.validatorModelId)}}function vl(e){return{provider:Ir(e.planningModelProvider),modelId:Ir(e.planningModelId)}}function hP(e,n){return xb(e,n)}function pP(e,n){return vb(e,n)}function fP(e,n){return yb(e,n)}function Ed(e){if(!e)return{provider:void 0,modelId:void 0};const n=e.indexOf("/");return{provider:e.slice(0,n),modelId:e.slice(n+1)}}function _d(e){return e.provider&&e.modelId?`${e.provider}/${e.modelId}`:""}function Md(e,n){return e.provider===n.provider&&e.modelId===n.modelId}function gP(e,n){const a={executor:"Executor",validator:"Reviewer",planning:"Planning"}[e]||e;return!n.provider||!n.modelId?`${a} model set to default`:`${a} model set to ${n.provider}/${n.modelId}`}function bP({task:e,addToast:n,onTaskUpdated:s,settings:a}){const[r,o]=i.useState([]),[l,c]=i.useState([]),[d,u]=i.useState([]),[h,m]=i.useState(!1),[f,p]=i.useState(null),[g,w]=i.useState(()=>bl(e)),[v,b]=i.useState(()=>bl(e)),[y,j]=i.useState(()=>xl(e)),[S,C]=i.useState(()=>xl(e)),[x,k]=i.useState(()=>vl(e)),[R,O]=i.useState(()=>vl(e)),[E,_]=i.useState(()=>e.thinkingLevel??null),[G,H]=i.useState(()=>e.thinkingLevel??null),[A,P]=i.useState(null),q=i.useRef(e.id);i.useEffect(()=>{m(!0),p(null),Bs().then(Q=>{o(Q.models),c(Q.favoriteProviders),u(Q.favoriteModels)}).catch(Q=>{p(Q.message||"Failed to load models")}).finally(()=>{m(!1)})},[]);const Y=i.useCallback(async Q=>{const F=l,re=F.includes(Q)?F.filter(U=>U!==Q):[Q,...F];c(re);try{await Fn({favoriteProviders:re,favoriteModels:d})}catch{c(F),n("Failed to update favorites","error")}},[l,d,n]),ge=i.useCallback(async Q=>{const F=d,re=F.includes(Q)?F.filter(U=>U!==Q):[Q,...F];u(re);try{await Fn({favoriteProviders:l,favoriteModels:re})}catch{u(F),n("Failed to update model favorites","error")}},[d,l,n]);i.useEffect(()=>{q.current=e.id;const Q=bl(e),F=xl(e),X=vl(e);w(Q),b(Q),j(F),C(F),k(X),O(X);const re=e.thinkingLevel??null;_(re),H(re),P(null)},[e.id,e.modelProvider,e.modelId,e.validatorModelProvider,e.validatorModelId,e.planningModelProvider,e.planningModelId,e.thinkingLevel]);const L=i.useMemo(()=>_d(g),[g]),M=i.useMemo(()=>_d(y),[y]),$=i.useMemo(()=>_d(x),[x]),D=i.useMemo(()=>hP(e,a),[e,a]),N=i.useMemo(()=>pP(e,a),[e,a]),W=i.useMemo(()=>fP(e,a),[e,a]),de=A!==null,me=i.useCallback(async(Q,F)=>{const X=e.id,re=v,U=S,be=R;P(Q);try{const Ue=s?Q==="executor"?{modelProvider:F.provider??null,modelId:F.modelId??null}:Q==="validator"?{validatorModelProvider:F.provider??null,validatorModelId:F.modelId??null}:{planningModelProvider:F.provider??null,planningModelId:F.modelId??null}:{modelProvider:(Q==="executor"?F:v).provider??null,modelId:(Q==="executor"?F:v).modelId??null,validatorModelProvider:(Q==="validator"?F:S).provider??null,validatorModelId:(Q==="validator"?F:S).modelId??null,planningModelProvider:(Q==="planning"?F:R).provider??null,planningModelId:(Q==="planning"?F:R).modelId??null},se=await Ls(X,Ue);if(q.current!==X)return;const Ve=bl(se),Le=xl(se),ct=vl(se);b(Ve),w(Ve),C(Le),j(Le),O(ct),k(ct),s?.(se),n(gP(Q,{executor:Ve,validator:Le,planning:ct}[Q]),"success")}catch(Ue){if(q.current!==X)return;Q==="executor"?w(re):Q==="validator"?j(U):k(be),n(Ie(Ue)||"Failed to save model settings","error")}finally{q.current===X&&P(null)}},[e.id,v,S,R,n,s]),Ne=i.useCallback(Q=>{const F=Ed(Q);w(F),!Md(F,v)&&me("executor",F)},[v,me]),ve=i.useCallback(Q=>{const F=Ed(Q);j(F),!Md(F,S)&&me("validator",F)},[S,me]),Me=i.useCallback(Q=>{const F=Ed(Q);k(F),!Md(F,R)&&me("planning",F)},[R,me]),ie=i.useCallback(async Q=>{const F=e.id,X=G,re=Q===""?null:Q;_(re),P("thinking");try{const U=await Ls(F,{thinkingLevel:re});if(q.current!==F)return;const be=U.thinkingLevel??null;H(be),_(be),s?.(U);const Ue=a?.defaultThinkingLevel??"off";n(be===null?`Thinking level set to default (${Ue})`:`Thinking level set to ${be}`,"success")}catch(U){if(q.current!==F)return;_(X),n(Ie(U)||"Failed to save thinking level","error")}finally{q.current===F&&P(null)}},[e.id,G,a,n,s]),ye=!v.provider&&!v.modelId,Z=!S.provider&&!S.modelId,fe=!R.provider&&!R.modelId;return t.jsxs("div",{className:"model-selector-tab",children:[t.jsx("h4",{children:"Model Configuration"}),t.jsx("p",{className:"model-selector-intro",children:"Override the AI models used for this task. When not specified, project or global defaults are used."}),h?t.jsx("div",{className:"model-selector-loading",children:"Loading available models…"}):f?t.jsxs("div",{className:"model-selector-error",children:["Error loading models: ",f,t.jsx("button",{className:"btn btn-sm",onClick:()=>{m(!0),p(null),Bs().then(Q=>{o(Q.models),c(Q.favoriteProviders),u(Q.favoriteModels)}).catch(Q=>p(Q.message)).finally(()=>m(!1))},style:{marginLeft:"8px"},children:"Retry"})]}):r.length===0?t.jsx("div",{className:"model-selector-empty",children:"No models available. Configure authentication in Settings to enable model selection."}):t.jsxs(t.Fragment,{children:[t.jsxs("div",{className:"form-group",children:[t.jsx("label",{htmlFor:"executorModel",children:"Executor Model"}),t.jsx("div",{className:"model-selector-current",children:ye?t.jsxs("span",{className:"model-badge model-badge-default",children:["Using default",D.provider&&D.modelId?` (${D.provider}/${D.modelId})`:""]}):t.jsxs("span",{className:"model-badge model-badge-custom",children:[v.provider&&t.jsx(On,{provider:v.provider,size:"sm"}),v.provider,"/",v.modelId]})}),t.jsx(Ns,{id:"executorModel",label:"Executor Model",value:L,onChange:Ne,models:r,disabled:de,placeholder:"Select executor model…",favoriteProviders:l,onToggleFavorite:Y,favoriteModels:d,onToggleModelFavorite:ge}),t.jsx("small",{children:"The AI model used to implement this task."})]}),t.jsxs("div",{className:"form-group",children:[t.jsx("label",{htmlFor:"validatorModel",children:"Reviewer Model"}),t.jsx("div",{className:"model-selector-current",children:Z?t.jsxs("span",{className:"model-badge model-badge-default",children:["Using default",N.provider&&N.modelId?` (${N.provider}/${N.modelId})`:""]}):t.jsxs("span",{className:"model-badge model-badge-custom",children:[S.provider&&t.jsx(On,{provider:S.provider,size:"sm"}),S.provider,"/",S.modelId]})}),t.jsx(Ns,{id:"validatorModel",label:"Reviewer Model",value:M,onChange:ve,models:r,disabled:de,placeholder:"Select reviewer model…",favoriteProviders:l,onToggleFavorite:Y,favoriteModels:d,onToggleModelFavorite:ge}),t.jsx("small",{children:"The AI model used to review code and plans for this task."})]}),t.jsxs("div",{className:"form-group",children:[t.jsx("label",{htmlFor:"planningModel",children:"Planning Model"}),t.jsx("div",{className:"model-selector-current",children:fe?t.jsxs("span",{className:"model-badge model-badge-default",children:["Using default",W.provider&&W.modelId?` (${W.provider}/${W.modelId})`:""]}):t.jsxs("span",{className:"model-badge model-badge-custom",children:[R.provider&&t.jsx(On,{provider:R.provider,size:"sm"}),R.provider,"/",R.modelId]})}),t.jsx(Ns,{id:"planningModel",label:"Planning Model",value:$,onChange:Me,models:r,disabled:de,placeholder:"Select planning model…",favoriteProviders:l,onToggleFavorite:Y,favoriteModels:d,onToggleModelFavorite:ge}),t.jsx("small",{children:"The AI model used for task specification (triage phase)."})]}),t.jsxs("div",{className:"form-group",children:[t.jsx("label",{htmlFor:"thinkingLevel",children:"Thinking Level"}),t.jsx("div",{className:"model-selector-current",children:G===null?t.jsxs("span",{className:"model-badge model-badge-default",children:["Using default (",a?.defaultThinkingLevel??"off",")"]}):t.jsx("span",{className:"model-badge model-badge-custom",children:G})}),t.jsxs("select",{id:"thinkingLevel",value:E??"",onChange:Q=>ie(Q.target.value),disabled:de,className:"thinking-level-select",children:[t.jsxs("option",{value:"",children:["Default (",a?.defaultThinkingLevel??"off",")"]}),t.jsx("option",{value:"off",children:"Off"}),t.jsx("option",{value:"minimal",children:"Minimal"}),t.jsx("option",{value:"low",children:"Low"}),t.jsx("option",{value:"medium",children:"Medium"}),t.jsx("option",{value:"high",children:"High"})]}),t.jsx("small",{children:"Controls the reasoning effort for the AI agent. Higher levels use more tokens."})]}),t.jsx("div",{className:"model-selector-status",children:ye&&Z&&fe&&G===null?"Using project or global default models.":"Model settings are up to date."})]})]})}const xP={open:t.jsx(bc,{size:16}),closed:t.jsx(qo,{size:16}),merged:t.jsx(mb,{size:16})};function vP({taskId:e,projectId:n,prInfo:s,automationStatus:a,autoMerge:r=!1,isManualPrFlow:o=!1,prAuthAvailable:l,onPrCreated:c,onPrUpdated:d,addToast:u}){const[h,m]=i.useState(!1),[f,p]=i.useState(""),[g,w]=i.useState(""),[v,b]=i.useState(!1),[y,j]=i.useState(!1),[S,C]=i.useState(null),x=i.useCallback(async()=>{if(f.trim()){b(!0);try{const E=await mS(e,{title:f.trim(),body:g.trim()||void 0},n);c(E),m(!1),p(""),w(""),u(`Created PR #${E.number}`,"success")}catch(E){u(Ie(E)||"Failed to create PR","error")}finally{b(!1)}}},[e,f,g,n,c,u]),k=i.useCallback(async()=>{if(s){j(!0);try{const E=await hS(e,n);C(E),d(E.prInfo),u("PR status refreshed","success")}catch(E){u(Ie(E)||"Failed to refresh PR","error")}finally{j(!1)}}},[e,s,n,d,u]);if(!s)return a==="creating-pr"?t.jsxs("div",{className:"pr-section",children:[t.jsxs("h4",{children:[t.jsx(Qs,{size:16,className:"pr-section-icon"}),"Pull Request"]}),t.jsx("div",{className:"pr-hint pr-hint--muted",children:"fn is creating a pull request automatically for this task."})]}):r?t.jsxs("div",{className:"pr-section",children:[t.jsxs("h4",{children:[t.jsx(Qs,{size:16,className:"pr-section-icon"}),"Pull Request"]}),t.jsx("div",{className:"pr-hint pr-hint--muted",children:"Auto-merge will handle this task automatically."})]}):h?t.jsxs("div",{className:"pr-section",children:[t.jsxs("h4",{children:[t.jsx(Qs,{size:16,className:"pr-section-icon"}),"Create Pull Request"]}),t.jsxs("div",{className:"pr-form",children:[t.jsx("input",{type:"text",placeholder:"PR title",value:f,onChange:E=>p(E.target.value),disabled:v,className:"pr-input"}),t.jsx("textarea",{placeholder:"PR description (optional)",value:g,onChange:E=>w(E.target.value),disabled:v,className:"pr-textarea",rows:3}),t.jsxs("div",{className:"pr-actions",children:[t.jsx("button",{className:"btn btn-sm",onClick:()=>m(!1),disabled:v,children:"Cancel"}),t.jsx("button",{className:"btn btn-primary btn-sm",onClick:x,disabled:!f.trim()||v,children:v?"Creating…":"Create PR"})]})]})]}):t.jsxs("div",{className:"pr-section",children:[t.jsxs("h4",{children:[t.jsx(Qs,{size:16,className:"pr-section-icon"}),"Pull Request"]}),t.jsxs("button",{className:"btn btn-primary btn-sm",onClick:()=>m(!0),disabled:!l,title:l?"Create a PR for this task":"PR auth unavailable — run 'gh auth login'",children:[t.jsx(Tn,{size:14,className:"pr-section-icon--sm"}),"Create PR"]}),o&&t.jsx("div",{className:"pr-hint pr-hint--subtle",children:"Use the footer action to run PR-first completion for this task."}),!l&&t.jsxs("div",{className:"pr-hint pr-hint--subtle",children:["Run ",t.jsx("code",{children:"gh auth login"})," to enable PR creation."]})]});const R=xP[s.status]??t.jsx(bc,{size:16}),O=S?.blockingReasons??[];return t.jsxs("div",{className:"pr-section",children:[t.jsxs("h4",{children:[t.jsx(Qs,{size:16,className:"pr-section-icon"}),"Pull Request"]}),t.jsxs("div",{className:`pr-card pr-card--status-${s.status}`,children:[t.jsxs("div",{className:"pr-header",children:[t.jsx("span",{className:"pr-status-icon",children:R}),t.jsx("span",{className:`pr-status-badge pr-status-badge--${s.status}`,children:s.status}),t.jsxs("span",{className:"pr-number",children:["#",s.number]}),t.jsx("div",{className:"pr-spacer"}),t.jsx("button",{className:"btn btn-sm pr-refresh-btn",onClick:k,disabled:y,title:"Refresh PR status",children:t.jsx(us,{size:14,style:{verticalAlign:"middle",opacity:y?.5:1}})})]}),t.jsx("div",{className:"pr-title",children:s.title}),t.jsxs("div",{className:"pr-meta",children:[t.jsx("span",{children:s.headBranch}),t.jsx("span",{className:"pr-meta-arrow",children:"→"}),t.jsx("span",{children:s.baseBranch})]}),a==="merging-pr"&&t.jsx("div",{className:"pr-hint pr-hint--info",children:"fn is merging this pull request automatically."}),a==="awaiting-pr-checks"&&t.jsx("div",{className:"pr-hint pr-hint--info",children:O.length>0?`Waiting for: ${O.join("; ")}`:"Waiting for required checks or review feedback before auto-merge."}),s.status==="merged"&&t.jsx("div",{className:"pr-hint pr-hint--info",children:"This PR is merged. fn will finish local cleanup and move the task to Done."}),t.jsxs("div",{className:"pr-footer",children:[s.commentCount>0&&t.jsxs("span",{className:"pr-comments",children:[t.jsx(Ki,{size:14}),s.commentCount]}),t.jsxs("a",{href:s.url,target:"_blank",rel:"noopener noreferrer",className:"pr-link",children:[t.jsx(cb,{size:14}),"View on GitHub"]})]})]})]})}const tf=2e3;function yP(e){const n=e.updatedAt||e.createdAt,s=new Date(n).toLocaleString();return e.updatedAt?`${s} (edited)`:s}function wP(e){return e==="agent"||e==="system"}function kP({task:e,onTaskUpdated:n,addToast:s,currentAuthor:a="user",projectId:r}){const[o,l]=i.useState(""),[c,d]=i.useState(null),[u,h]=i.useState(""),[m,f]=i.useState(!1),[p,g]=i.useState(null),w=i.useMemo(()=>[...e.comments||[]].sort((k,R)=>new Date(R.createdAt).getTime()-new Date(k.createdAt).getTime()),[e.comments]),v=o.length>tf;async function b(){const k=o.trim();if(k){f(!0);try{const R=await IN(e.id,k,r);l(""),n?.(R),s("Comment added","success")}catch(R){s(Ie(R)||"Failed to add comment","error")}finally{f(!1)}}}async function y(k){const R=u.trim();if(R){f(!0);try{const O=await EN(e.id,k,R,r);d(null),h(""),n?.(O),s("Comment updated","success")}catch(O){s(Ie(O)||"Failed to update comment","error")}finally{f(!1)}}}async function j(k){g(k);try{const R=await _N(e.id,k,r);n?.(R),s("Comment deleted","success")}catch(R){s(Ie(R)||"Failed to delete comment","error")}finally{g(null)}}function S(k){k.key==="Enter"&&(k.ctrlKey||k.metaKey)&&(k.preventDefault(),b())}return t.jsxs("div",{className:"detail-section",children:[t.jsx("h4",{children:"Comments"}),w.length===0?t.jsx("div",{className:"detail-log-empty",children:"No comments yet."}):t.jsx("div",{className:"detail-activity-list",children:w.map(k=>{const R=k.author===a,O=c===k.id,E=wP(k.author);return t.jsxs("div",{className:"detail-log-entry",children:[t.jsxs("div",{className:"detail-log-header comments-header-row",children:[t.jsxs("div",{className:"comments-author-row",children:[E?t.jsx("span",{className:"ai-guidance-badge","data-testid":"ai-guidance-badge",children:"AI Guidance"}):t.jsx("strong",{children:k.author}),t.jsx("span",{className:"detail-log-timestamp",children:yP(k)})]}),R&&!O?t.jsxs("div",{className:"comments-actions-row",children:[t.jsx("button",{className:"btn btn-sm",onClick:()=>{d(k.id),h(k.text)},children:"Edit"}),t.jsx("button",{className:"btn btn-danger btn-sm",onClick:()=>void j(k.id),disabled:p===k.id,children:p===k.id?"Deleting…":"Delete"})]}):null]}),O?t.jsxs("div",{className:"comments-edit-form",children:[t.jsx("textarea",{value:u,onChange:_=>h(_.target.value),rows:3,className:"comments-textarea"}),t.jsxs("div",{className:"comments-edit-actions",children:[t.jsx("button",{className:"btn btn-sm",onClick:()=>{d(null),h("")},disabled:m,children:"Cancel"}),t.jsx("button",{className:"btn btn-primary btn-sm",onClick:()=>void y(k.id),disabled:m||!u.trim(),children:"Save"})]})]}):t.jsx("div",{className:"detail-log-outcome comments-outcome-text",children:k.text})]},k.id)})}),t.jsxs("div",{className:"comments-compose-form",children:[t.jsx("textarea",{value:o,onChange:k=>l(k.target.value),onKeyDown:S,rows:3,placeholder:"Add a comment",className:"comments-textarea"}),t.jsxs("div",{className:"comments-footer-row",children:[t.jsxs("span",{className:`comments-char-count${v?" comments-char-count--over":""}`,children:[o.length," / ",tf]}),t.jsx("button",{className:"btn btn-primary btn-sm",onClick:()=>void b(),disabled:m||!o.trim()||v,children:m?"Posting…":"Add Comment"})]})]})]})}const nf="Failed to load review data.",jP="No reviewer feedback yet — this task has not produced reviewer-agent feedback in direct mode.",sf="fn-task-review-markdown";function NP(e,n){if(typeof window>"u")return n;try{const s=window.localStorage.getItem(e);return s===null?n:s==="true"}catch{return n}}function SP(e,n){if(!(typeof window>"u"))try{window.localStorage.setItem(e,n?"true":"false")}catch{}}const CP={p:({children:e,...n})=>t.jsx("p",{...n,children:Ws(e)}),li:({children:e,...n})=>t.jsx("li",{...n,children:Ws(e)}),code:({children:e,...n})=>t.jsx("code",{...n,children:Ws(e)}),pre:({children:e,...n})=>t.jsx("pre",{...n,style:{overflowX:"auto",maxWidth:"100%",whiteSpace:"pre-wrap",wordBreak:"break-word"},children:Ws(e)}),table:({children:e,...n})=>t.jsx("table",{...n,style:{display:"block",overflowX:"auto",maxWidth:"100%"},children:e})};function lo(e){return e?new Date(e).toLocaleString():"Never"}function EP(e){return e==="manual"?"Manual":e==="auto"?"Background":"Initial load"}function _P(e){const n=new Map(e.addressing.map(o=>[o.itemId,o])),s=e.items.map(o=>{const l=n.get(o.id);return{id:o.id,summary:o.summary??o.body.slice(0,120),body:o.body,path:o.path,createdAt:o.createdAt,status:l?.status??"queued",addressing:l,item:o}}),a=new Set(s.map(o=>o.id)),r=e.addressing.filter(o=>!a.has(o.itemId)&&o.snapshot).map(o=>({id:o.itemId,summary:o.snapshot?.summary??o.itemId,body:o.snapshot?.body??o.snapshot?.summary??o.itemId,path:o.snapshot?.filePath,createdAt:o.selectedAt,status:o.status,addressing:o}));return[...s,...r]}function MP({task:e,projectId:n,onTaskUpdated:s,addToast:a}){const[r,o]=i.useState([]),[l,c]=i.useState(!1),[d,u]=i.useState(!1),[h,m]=i.useState(!0),[f,p]=i.useState(null),[g,w]=i.useState(null),[v,b]=i.useState(e.reviewState??null),[y,j]=i.useState(()=>NP(sf,!0)),S=r.length>0&&!d,C=v?.source==="pull-request",x=i.useMemo(()=>v?_P(v):[],[v]);i.useEffect(()=>{SP(sf,y)},[y]),i.useEffect(()=>{let A=!1;return m(!0),p(null),I1(e.id,n).then(P=>{A||(b(P.reviewState),w(P.emptyMessage??null))}).catch(()=>{A||p(nf)}).finally(()=>{A||m(!1)}),()=>{A=!0}},[e.id,n]);const k=i.useMemo(()=>v?v.source==="pull-request"?`${v.summary?.reviewDecision??"REVIEW_REQUIRED"} · ${x.length} review item(s)`:`${v.summary?.summary??"reviewer-agent"} · ${x.length} review item(s)`:"No review feedback captured yet.",[v,x.length]),R=v?v.source==="pull-request"?v.summary?.reviewDecision:v.summary?.verdict:void 0,O=l?"refreshing":v?.refreshStatus??"ready",E=O==="error"?"status-dot status-dot--error":O==="refreshing"?"status-dot status-dot--pending":"status-dot status-dot--online",_=A=>o(P=>P.includes(A)?P.filter(q=>q!==A):[...P,A]),G=async()=>{try{p(null),c(!0);const A=await T1(e.id,n);if(b(A.reviewState),s?.({...e,reviewState:A.reviewState,prInfo:A.prInfo??e.prInfo}),A.reviewState.refreshStatus==="error"){const P=A.reviewState.refreshError??"Failed to refresh review data.";p(P),a(P,"error");return}a("Review refreshed","success")}catch(A){const P=A instanceof Error?A.message:nf;p(P),a(P,"error")}finally{c(!1)}},H=async()=>{try{if(!v)return;p(null),u(!0);const A=x.filter(q=>r.includes(q.id)).map(q=>{if(!q.item)return{id:q.id,source:v.source==="pull-request"?"pr-review":"reviewer-agent",threadId:q.addressing?.snapshot?.threadId,filePath:q.addressing?.snapshot?.filePath,lineNumber:q.addressing?.snapshot?.lineNumber,author:q.addressing?.snapshot?.authorLogin,summary:q.summary,body:q.body,url:q.addressing?.snapshot?.url};const Y=q.item;return{id:q.item.id,source:v.source==="pull-request"?"pr-review":"reviewer-agent",threadId:typeof Y.threadId=="string"?Y.threadId:void 0,filePath:q.item.path,lineNumber:typeof Y.line=="number"?Y.line:void 0,author:q.item.author?.login,summary:q.item.summary??q.item.body.slice(0,120),body:q.item.body,url:typeof Y.url=="string"?Y.url:void 0}}),P=await P1(e.id,A,n);b(P.reviewState),s?.({...P.task,reviewState:P.reviewState}),o([]),a("Same-task AI revision started from selected review feedback","success")}catch(A){const P=A instanceof Error?A.message:"Failed to queue revision";p(P),a(P,"error")}finally{u(!1)}};return t.jsxs("div",{className:"task-review-tab",children:[t.jsxs("div",{className:"task-review-tab__header",children:[t.jsxs("div",{className:"task-review-tab__summary-wrap",children:[t.jsx("p",{className:"task-review-tab__summary",children:k}),R?t.jsx("span",{className:`task-review-tab__decision task-review-tab__decision--${R}`,children:R}):null]}),t.jsxs("div",{className:"task-review-tab__actions",children:[t.jsx("button",{className:"btn btn-sm",onClick:()=>j(A=>!A),"aria-pressed":y,"data-testid":"task-review-markdown-toggle",title:y?"Show raw text":"Show formatted markdown",children:y?"Markdown":"Plain"}),t.jsx("button",{className:"btn btn-sm",onClick:G,disabled:l||h,children:l?"Refreshing…":"Refresh"}),t.jsx("button",{className:"btn btn-primary btn-sm",disabled:!S,onClick:H,children:d?"Queueing…":"Request revision"})]})]}),t.jsxs("div",{className:"task-review-tab__meta task-review-tab__refresh-meta","aria-live":"polite",children:[t.jsx("span",{className:E,"aria-hidden":"true"}),t.jsxs("span",{children:[O==="error"?"Refresh failed":O==="refreshing"?"Refreshing":"Up to date"," · Last refreshed: ",lo(v?.lastRefreshedAt)," · ",EP(v?.refreshSource)]})]}),h?t.jsx("div",{className:"task-review-tab__meta",children:"Loading review data…"}):null,!h&&f?t.jsx("div",{className:"task-review-tab__error",children:f}):null,!h&&!f&&!C&&x.length===0?t.jsx("div",{className:"task-review-tab__empty",children:g??jP}):null,!h&&!f&&x.length>0?t.jsx("ul",{className:"task-review-tab__list",children:x.map(A=>{const P=`task-review-item-checkbox-${A.id}`;return t.jsx("li",{className:"task-review-tab__item card",children:t.jsxs("div",{className:"task-review-tab__item-inner",children:[t.jsx("label",{htmlFor:P,className:"task-review-tab__direct-item task-review-tab__direct-item--selectable",children:t.jsxs("div",{className:"task-review-tab__summary-wrap",children:[t.jsx("input",{id:P,type:"checkbox",checked:r.includes(A.id),onChange:()=>_(A.id)}),t.jsxs("span",{className:"task-review-tab__item-summary",children:[A.path?`${A.path}: `:"",A.summary]}),t.jsx("span",{className:`task-review-tab__status task-review-tab__status--${A.status}`,children:A.status})]})}),t.jsx("div",{className:"task-review-tab__meta",children:lo(A.createdAt)}),A.addressing?t.jsxs("div",{className:"task-review-tab__meta",children:["Selected: ",lo(A.addressing.selectedAt),A.addressing.startedAt?` · Started: ${lo(A.addressing.startedAt)}`:"",A.addressing.completedAt?` · Completed: ${lo(A.addressing.completedAt)}`:"",A.addressing.error?` · Error: ${A.addressing.error}`:""]}):null,y?t.jsx("div",{className:"task-review-tab__body markdown-body",children:t.jsx(hi,{remarkPlugins:[pi],components:CP,children:A.body})}):t.jsx("pre",{className:"task-review-tab__body",children:ks(A.body)})]})},A.id)})}):null,C&&!h&&!f&&x.length===0?t.jsx("div",{className:"task-review-tab__empty",children:"No review items yet."}):null]})}function AP(e){return e?e.slice(0,7):"Unknown"}function RP({task:e}){if(e.column!=="done"||!e.mergeDetails)return null;const n=e.mergeDetails;return t.jsxs("div",{className:"detail-section",children:[t.jsx("h4",{children:"Merge Details"}),t.jsxs("div",{className:"pr-card merge-details-card",children:[t.jsx("div",{className:"detail-log-entry",children:t.jsxs("div",{className:"detail-log-header",children:[t.jsx("span",{className:"detail-log-action",children:"Status"}),t.jsx("span",{className:"detail-log-outcome",children:n.mergeConfirmed===!1?"Recorded without local merge confirmation":"Merged successfully"})]})}),t.jsx("div",{className:"detail-log-entry",children:t.jsxs("div",{className:"detail-log-header",children:[t.jsx("span",{className:"detail-log-action",children:"Commit"}),t.jsx("span",{className:"detail-log-outcome",children:AP(n.commitSha)})]})}),t.jsx("div",{className:"detail-log-entry",children:t.jsxs("div",{className:"detail-log-header",children:[t.jsx("span",{className:"detail-log-action",children:"Files changed"}),t.jsx("span",{className:"detail-log-outcome",children:n.filesChanged??0})]})}),t.jsx("div",{className:"detail-log-entry",children:t.jsxs("div",{className:"detail-log-header",children:[t.jsx("span",{className:"detail-log-action",children:"Insertions / Deletions"}),t.jsxs("span",{className:"detail-log-outcome",children:["+",n.insertions??0," / -",n.deletions??0]})]})}),n.mergedAt?t.jsx("div",{className:"detail-log-entry",children:t.jsxs("div",{className:"detail-log-header",children:[t.jsx("span",{className:"detail-log-action",children:"Merged at"}),t.jsx("span",{className:"detail-log-outcome",children:new Date(n.mergedAt).toLocaleString()})]})}):null,n.prNumber?t.jsx("div",{className:"detail-log-entry",children:t.jsxs("div",{className:"detail-log-header",children:[t.jsx("span",{className:"detail-log-action",children:"PR"}),e.prInfo?.url?t.jsxs("a",{className:"detail-source-link detail-log-outcome",href:e.prInfo.url,target:"_blank",rel:"noopener noreferrer",children:["#",n.prNumber]}):t.jsxs("span",{className:"detail-log-outcome",children:["#",n.prNumber]})]})}):null,n.mergeCommitMessage?t.jsxs("div",{className:"detail-log-entry",children:[t.jsx("div",{className:"detail-log-header",children:t.jsx("span",{className:"detail-log-action",children:"Message"})}),t.jsx("div",{className:"detail-log-outcome",children:n.mergeCommitMessage})]}):null]})]})}function Nv(e){return e.split(`
683
- `).map((s,a)=>{let r="";return s.startsWith("+")&&!s.startsWith("+++")?r="diff-add":s.startsWith("-")&&!s.startsWith("---")?r="diff-del":s.startsWith("@@")&&(r="diff-hunk"),r?t.jsx("span",{className:r,children:`${s}
684
- `},a):t.jsx(ga.Fragment,{children:`${s}
685
- `},a)})}function IP(e){switch(e){case"added":return"A";case"deleted":return"D";case"modified":return"M";default:return"?"}}function TP({isOpen:e,taskId:n,files:s,stats:a,mergeDetails:r,column:o,onClose:l,onRefresh:c}){const[d,u]=i.useState(null),[h,m]=i.useState(!0),f=i.useRef(null);Oi(f,e,"fusion:changes-diff-modal-size");const p=Xi(l);i.useEffect(()=>{s.length>0&&d===null&&u(0)},[s,d]);const g=i.useCallback(()=>{u(y=>y!==null&&y>0?y-1:y)},[]),w=i.useCallback(()=>{u(y=>y!==null&&y<s.length-1?y+1:y)},[]);if(i.useEffect(()=>{if(!e)return;const y=j=>{if(j.key==="Escape"){l();return}j.key==="ArrowUp"&&(j.metaKey||j.ctrlKey)&&(j.preventDefault(),g()),j.key==="ArrowDown"&&(j.metaKey||j.ctrlKey)&&(j.preventDefault(),w())};return document.addEventListener("keydown",y),()=>document.removeEventListener("keydown",y)},[e,l,g,w]),!e)return null;const v=d!==null?s[d]:null,b=o==="done";return t.jsx("div",{className:"modal-overlay open",...p,role:"dialog","aria-modal":"true",children:t.jsxs("div",{className:"modal changes-diff-modal",ref:f,children:[t.jsxs("div",{className:"modal-header changes-diff-modal-header",children:[t.jsxs("div",{className:"changes-diff-header-title",children:[t.jsx(ki,{size:18}),t.jsxs("span",{children:["Changes — ",n]}),t.jsxs("span",{className:"changes-stat-summary",children:[t.jsxs("span",{className:"diff-add",children:["+",a.additions]})," ",t.jsxs("span",{className:"diff-del",children:["-",a.deletions]})]})]}),t.jsxs("div",{className:"changes-diff-header-actions",children:[s.length>0&&t.jsxs("div",{className:"changes-nav",children:[t.jsx("button",{className:"btn btn-sm btn-icon",onClick:g,disabled:d===null||d<=0,title:"Previous file (Ctrl+↑)","aria-label":"Previous file",children:t.jsx(gc,{})}),t.jsx("span",{className:"changes-nav-indicator","aria-live":"polite",children:d!==null?`${d+1}/${s.length}`:`—/${s.length}`}),t.jsx("button",{className:"btn btn-sm btn-icon",onClick:w,disabled:d===null||d>=s.length-1,title:"Next file (Ctrl+↓)","aria-label":"Next file",children:t.jsx(Wn,{})})]}),t.jsx("button",{className:`btn btn-sm ${h?"btn-primary":""}`,onClick:()=>m(y=>!y),title:h?"Disable word wrap":"Enable word wrap","aria-label":"Toggle word wrap",children:t.jsx(Kl,{size:14})}),c&&t.jsxs("button",{className:"btn btn-sm",onClick:c,children:[t.jsx(us,{size:14}),"Refresh"]}),t.jsx("button",{className:"modal-close",onClick:l,"aria-label":"Close",children:t.jsx(bn,{size:20})})]})]}),t.jsxs("div",{className:"changes-diff-body",children:[t.jsxs("div",{className:"changes-diff-sidebar",children:[b&&r&&t.jsxs("div",{className:"commit-diff-meta",children:[r.commitSha&&t.jsxs("div",{className:"commit-diff-sha",children:[t.jsx(Sr,{size:14}),t.jsx("code",{children:r.commitSha.slice(0,7)})]}),r.mergeCommitMessage&&t.jsx("div",{className:"commit-diff-message",children:r.mergeCommitMessage}),r.mergedAt&&t.jsxs("div",{className:"commit-diff-timestamp",children:["Merged ",new Date(r.mergedAt).toLocaleString()]})]}),t.jsx("div",{className:"changes-diff-file-list",children:s.map((y,j)=>t.jsxs("button",{className:`changes-diff-file-item ${d===j?"selected":""}`,onClick:()=>u(j),title:y.path,children:[t.jsx("span",{className:`changes-file-status changes-file-status--${y.status}`,children:IP(y.status)}),t.jsx("span",{className:"changes-diff-file-path",title:y.path,children:t.jsx("bdo",{dir:"ltr",children:y.path})}),t.jsxs("span",{className:"changes-diff-file-stat",children:["+",y.additions," -",y.deletions]})]},y.path))})]}),t.jsx("div",{className:"changes-diff-content",children:v?t.jsxs(t.Fragment,{children:[t.jsxs("div",{className:"changes-diff-file-header-bar",children:[t.jsx("span",{className:"changes-diff-file-header-name",children:v.path}),t.jsxs("span",{className:"changes-diff-file-header-stats",children:["+",v.additions," -",v.deletions]})]}),v.patch?t.jsx("div",{className:"changes-diff-viewer",children:t.jsx("pre",{className:`changes-diff-patch ${h?"changes-diff-patch--wrap":"changes-diff-patch--nowrap"}`,children:t.jsx("code",{children:Nv(v.patch)})})}):t.jsx("div",{className:"changes-diff-empty",children:"No diff available for this file."})]}):t.jsxs("div",{className:"changes-diff-empty",children:[t.jsx(ki,{size:48,opacity:.3}),t.jsx("p",{children:"Select a file to view its diff"})]})})]})]})})}function Sv(e){switch(e){case"added":return"A";case"deleted":return"D";case"modified":return"M";default:return"?"}}function Ad(e,n,s){return t.jsxs("div",{className:"detail-section task-changes-tab",children:[n&&s&&t.jsxs("div",{className:"commit-diff-meta",children:[s.commitSha&&t.jsxs("div",{className:"commit-diff-sha",children:[t.jsx(Sr,{size:14}),t.jsx("code",{children:s.commitSha.slice(0,7)})]}),s.mergedAt&&t.jsxs("div",{className:"commit-diff-timestamp",children:["Merged ",new Date(s.mergedAt).toLocaleString()]})]}),t.jsxs("div",{className:"task-changes-state task-changes-state--empty",children:[t.jsx(ki,{size:24}),t.jsxs("p",{children:[e.length," file",e.length===1?"":"s"," modified during execution."]}),t.jsx("span",{className:"task-changes-state-hint",children:n?"The recorded merge commit has no diff (likely collapsed into a squash on main). Showing file paths only — patches unavailable.":"The live worktree diff is empty. Showing the last file paths captured during execution — patches unavailable."})]}),t.jsx("div",{className:"changes-file-list task-changes-file-list--compact",children:e.map(a=>t.jsx("div",{className:"changes-file-item",children:t.jsxs("div",{className:"changes-file-header changes-file-header--static",children:[t.jsx("span",{className:"changes-file-status changes-file-status--unknown",title:"status unknown",children:Sv("unknown")}),t.jsx("span",{className:"changes-file-path",title:a,children:t.jsx("bdo",{dir:"ltr",children:a})})]})},a))})]})}function PP({taskId:e,worktree:n,projectId:s,column:a,mergeDetails:r,modifiedFiles:o}){const[l,c]=i.useState([]),[d,u]=i.useState({filesChanged:0,additions:0,deletions:0}),[h,m]=i.useState(!0),[f,p]=i.useState(null),[g,w]=i.useState([]),[v,b]=i.useState(null),[y,j]=i.useState(new Set),[S,C]=i.useState(null),[x,k]=i.useState(!0),[R,O]=i.useState(!1),E=a==="done",_=E&&!!r?.commitSha,G=a==="in-progress"||a==="in-review"||_,H=i.useCallback(async()=>{if(!G&&!E){m(!1);return}try{m(!0),p(null);const L=await Q1(e,s);if(b(L.lineageId),w(L.associations),!G){c([]),u({filesChanged:0,additions:0,deletions:0});return}const M=await $b(e,void 0,s),$=M.files.map(D=>({path:D.path,status:D.status,additions:D.additions,deletions:D.deletions,patch:D.patch}));c($),u(M.stats),$.length>0&&(j(new Set([$[0].path])),C(0))}catch(L){p(Ie(L)||"Failed to load task changes")}finally{m(!1)}},[e,s,G,E]);i.useEffect(()=>{H()},[H]);const A=L=>{j(M=>{const $=new Set(M);if($.has(L))$.delete(L);else{$.add(L);const D=l.findIndex(N=>N.path===L);D!==-1&&C(D)}return $})},P=L=>{if(L<0||L>=l.length)return;const M=l[L].path;j(new Set([M])),C(L)},q=S!==null&&S>0,Y=S!==null&&S<l.length-1;if(h)return t.jsx("div",{className:"detail-section",children:t.jsxs("div",{className:"task-changes-state task-changes-state--loading",children:[t.jsx("div",{className:"loading-spinner"}),t.jsx("span",{children:"Loading changes..."})]})});if(f)return t.jsx("div",{className:"detail-section",children:t.jsxs("div",{className:"task-changes-state task-changes-state--error",children:[t.jsx(zs,{size:16}),t.jsxs("span",{children:["Error loading changes: ",f]})]})});if(!E&&!n)return o&&o.length>0?Ad(o,!1):t.jsx("div",{className:"detail-section",children:t.jsxs("div",{className:"task-changes-state task-changes-state--empty",children:[t.jsx(ki,{size:24}),t.jsx("p",{children:"No worktree available for this task."}),t.jsx("span",{className:"task-changes-state-hint",children:"Changes will be shown once the task is in progress."})]})});if(E&&!_){if(o&&o.length>0)return Ad(o,!0,r);const L=r?.filesChanged,M=r?.insertions,$=r?.deletions,D=L!=null||M!=null||$!=null;return t.jsx("div",{className:"detail-section",children:t.jsxs("div",{className:"task-changes-state task-changes-state--empty",children:[t.jsx(ki,{size:24}),t.jsx("p",{children:"Detailed file changes unavailable."}),t.jsx("span",{className:"task-changes-state-hint",children:D?`Merge summary: ${L??0} file${(L??0)===1?"":"s"} changed, +${M??0} additions, -${$??0} deletions.`:"No merge commit was recorded for this task."})]})})}const ge=()=>t.jsxs("section",{className:"task-lineage-associations","aria-label":"Task commit associations",children:[t.jsxs("div",{className:"task-lineage-associations-header",children:[t.jsxs("h4",{children:[t.jsx(Sr,{size:16}),"Lineage commit associations"]}),v&&t.jsx("code",{className:"task-lineage-id",children:v})]}),g.length===0?t.jsx("p",{className:"task-lineage-associations-empty",children:"No associated commits recorded yet."}):t.jsx("div",{className:"task-lineage-associations-list",children:g.map(L=>{const M=L.matchedBy.replace(/-/g," ");return t.jsxs("article",{className:`task-lineage-association task-lineage-association--${L.confidence}`,children:[t.jsxs("div",{className:"task-lineage-association-main",children:[t.jsx("code",{className:"task-lineage-sha",children:L.commitSha.slice(0,7)}),t.jsx("span",{className:"task-lineage-subject",children:L.commitSubject})]}),t.jsxs("div",{className:"task-lineage-association-meta",children:[t.jsx("span",{children:new Date(L.authoredAt).toLocaleString()}),t.jsxs("span",{children:["Confidence: ",L.confidence]}),t.jsxs("span",{children:["Match: ",M]}),t.jsxs("span",{children:["Task snapshot: ",L.taskIdSnapshot]})]}),L.note&&t.jsx("p",{className:"task-lineage-note",children:L.note})]},`${L.commitSha}-${L.matchedBy}`)})})]});return l.length===0?o&&o.length>0?Ad(o,E,r):t.jsxs("div",{className:"detail-section task-changes-tab",children:[ge(),t.jsxs("div",{className:"task-changes-state task-changes-state--empty",children:[t.jsx(ki,{size:24}),t.jsx("p",{children:"No files modified."}),t.jsx("span",{className:"task-changes-state-hint",children:E?"No file changes were recorded in the merge commit.":"The agent did not modify any files during execution."})]})]}):t.jsxs("div",{className:"detail-section task-changes-tab",children:[ge(),E&&r&&t.jsxs("div",{className:"commit-diff-meta",children:[r.commitSha&&t.jsxs("div",{className:"commit-diff-sha",children:[t.jsx(Sr,{size:14}),t.jsx("code",{children:r.commitSha.slice(0,7)})]}),r.mergeCommitMessage&&t.jsx("div",{className:"commit-diff-message",children:r.mergeCommitMessage}),r.mergedAt&&t.jsxs("div",{className:"commit-diff-timestamp",children:["Merged ",new Date(r.mergedAt).toLocaleString()]})]}),t.jsxs("div",{className:"changes-header",children:[t.jsxs("div",{className:"task-changes-header-title",children:[t.jsxs("h4",{children:[t.jsx(ki,{size:16}),"Files Changed (",d.filesChanged,")"]}),t.jsxs("span",{className:"task-changes-stats changes-stat-summary",children:[t.jsxs("span",{className:"diff-add",children:["+",d.additions]})," ",t.jsxs("span",{className:"diff-del",children:["-",d.deletions]})]})]}),t.jsxs("div",{className:"changes-header-actions-wrapper",children:[t.jsxs("div",{className:"changes-header-actions",children:[l.length>0&&t.jsxs("div",{className:"changes-nav",children:[t.jsx("button",{className:"btn btn-sm btn-icon",onClick:()=>q&&P(S-1),disabled:!q,title:"Previous file","aria-label":"Previous file",children:t.jsx(gc,{})}),t.jsx("span",{className:"changes-nav-indicator","aria-live":"polite",children:S!==null?`${S+1}/${l.length}`:`—/${l.length}`}),t.jsx("button",{className:"btn btn-sm btn-icon",onClick:()=>Y&&P(S+1),disabled:!Y,title:"Next file","aria-label":"Next file",children:t.jsx(Wn,{})})]}),t.jsx("button",{className:`btn btn-sm ${x?"btn-primary":""}`,onClick:()=>k(L=>!L),title:x?"Disable word wrap":"Enable word wrap","aria-label":"Toggle word wrap",children:t.jsx(Kl,{size:14})})]}),t.jsxs("div",{className:"changes-header-actions-secondary",children:[t.jsx("button",{className:"btn btn-sm",onClick:H,disabled:h,children:"Refresh"}),t.jsx("button",{className:"btn btn-sm btn-icon",onClick:()=>O(!0),title:"Expand to full-screen diff view","aria-label":"Expand diff view",children:t.jsx(jc,{})})]})]})]}),t.jsx("div",{className:"changes-file-list task-changes-file-list--compact",children:l.map(L=>{const M=y.has(L.path);return t.jsxs("div",{className:`changes-file-item ${M?"expanded":""}`,children:[t.jsxs("button",{className:"changes-file-header",onClick:()=>A(L.path),children:[t.jsx("span",{className:"changes-file-toggle",children:M?t.jsx(vn,{size:14}):t.jsx(Wn,{size:14})}),t.jsx("span",{className:`changes-file-status changes-file-status--${L.status}`,title:L.status,children:Sv(L.status)}),t.jsx("span",{className:"changes-file-path",title:L.path,children:t.jsx("bdo",{dir:"ltr",children:L.path})}),t.jsxs("span",{className:"changes-file-stat",title:`+${L.additions} -${L.deletions}`,children:["+",L.additions," -",L.deletions]})]}),M&&L.patch&&t.jsx("div",{className:"changes-file-content",children:t.jsx("pre",{className:`changes-diff-patch ${x?"changes-diff-patch--wrap":"changes-diff-patch--nowrap"}`,children:t.jsx("code",{children:Nv(L.patch)})})})]},L.path)})}),t.jsx(TP,{isOpen:R,taskId:e,files:l,stats:d,mergeDetails:r,column:a,onClose:()=>O(!1),onRefresh:H})]})}function af(e){return{executorValue:e?.executorProvider&&e?.executorModelId?`${e.executorProvider}/${e.executorModelId}`:"",validatorValue:e?.validatorProvider&&e?.validatorModelId?`${e.validatorProvider}/${e.validatorModelId}`:""}}function $P(e){return e.trim().toLowerCase().replace(/[^a-z0-9_-]+/g,"-").replace(/-+/g,"-").replace(/^[-_]+|[-_]+$/g,"").slice(0,32)||"preset"}function X8(e,n){const s=$P(e),a=new Set(n.map(c=>c.id));if(!a.has(s))return s;const r=30;let o=s,l=1;for(;a.has(o)&&l<100;){const c=`-${l}`;o=`${s.slice(0,r-c.length)}${c}`,l++}return o}function rf(e){const n=e?.trim()??"";return Sc.test(n)?n:""}function Cv(e,n){const s=rf(e?.githubTrackingDefaultRepo);return s||rf(n?.githubTrackingDefaultRepo)}function DP(e){return e==="online"?"Online":e==="connecting"?"Connecting":e==="error"?"Error":"Offline"}const of=["image/png","image/jpeg","image/gif","image/webp"];function LP(e,n,s){const a=e==="post-merge"?"phase-badge--post-merge":"phase-badge--pre-merge";return t.jsx("span",{className:`phase-badge ${a}`,"data-testid":`${s}-${n}`,children:e==="post-merge"?"Post-merge":"Pre-merge"})}function Ev({mode:e,description:n,onDescriptionChange:s,title:a,onTitleChange:r,dependencies:o,onDependenciesChange:l,branch:c,onBranchChange:d,baseBranch:u,onBaseBranchChange:h,nodeId:m,onNodeIdChange:f,nodeOptions:p,nodeOverrideDisabled:g=!1,nodeOverrideDisabledReason:w,priority:v,onPriorityChange:b,executorModel:y,onExecutorModelChange:j,validatorModel:S,onValidatorModelChange:C,planningModel:x,onPlanningModelChange:k,thinkingLevel:R,onThinkingLevelChange:O,presetMode:E,onPresetModeChange:_,selectedPresetId:G,onSelectedPresetIdChange:H,selectedWorkflowSteps:A,onWorkflowStepsChange:P,onDefaultOnApplied:q,pendingImages:Y,onImagesChange:ge,tasks:L,projectId:M,disabled:$=!1,addToast:D,isActive:N=!0,onAutoSaveDescription:W,onPlanningMode:de,onSubtaskBreakdown:me,onClose:Ne,renderBelowPrimary:ve,renderBelowModelConfiguration:Me,hideDependencies:ie,autoExpandMoreOptionsOnSelection:ye=!0,reviewLevel:Z,onReviewLevelChange:fe,executionMode:Q,onExecutionModeChange:F,githubTrackingEnabled:X,onGithubTrackingEnabledChange:re,githubRepoOverride:U,onGithubRepoOverrideChange:be}){const Ue=(ie?!1:o.length>0)||Y.length>0||A.length>0||E!=="default"||(v??_s)!==_s||y!==""||S!==""||(x||"")!==""||(R||"")!==""||Z!==void 0||Q==="fast"||(c||"")!==""||(u||"")!==""||(m||"")!==""||X===!0||(U||"")!=="",[se,Ve]=i.useState(!1),[Le,ct]=i.useState(ye?Ue:!1),[Ke,oe]=i.useState(""),[Te,Fe]=i.useState([]),[mt,We]=i.useState([]),[he,pe]=i.useState([]),[De,ut]=i.useState(!1),[ht,et]=i.useState(null),[vt,Oe]=i.useState(null),[tt,ft]=i.useState([]),[Mt,yt]=i.useState("idle"),[Ge,K]=i.useState(!1),[ue,ot]=i.useState(!1),[xe,dt]=i.useState(!1),Je=i.useRef(null),ke=i.useRef(null),nt=i.useRef(null),bt=i.useRef(null),kt=i.useRef(null),wt=i.useRef(null),At=i.useRef(null),Ft=i.useRef(!1),ln=i.useRef(Ue),Vt=i.useRef(n.trim()),hn=i.useRef(n.trim());i.useEffect(()=>{N&&(ut(!0),Bs().then(ae=>{Fe(ae.models),We(ae.favoriteProviders),pe(ae.favoriteModels)}).catch(()=>{}).finally(()=>ut(!1)),Cc(M).then(ae=>et(ae)).catch(()=>et(null)),Jo(M).then(ae=>ft(ae.filter(le=>le.enabled))).catch(()=>ft([])),Qi().then(ae=>Oe(ae)).catch(()=>Oe(null)))},[N,M]);const un=ht?.modelPresets||[],pn=un.find(ae=>ae.id===G),an=Cv(ht,vt),Wt=(U||"").trim(),gn=Wt.length>0&&!Sc.test(Wt),cn=(ie?!1:o.length>0)||Y.length>0||A.length>0||E!=="default"||(v??_s)!==_s||y!==""||S!==""||(x||"")!==""||(R||"")!==""||Z!==void 0||Q==="fast"||(c||"")!==""||(u||"")!==""||(m||"")!==""||X===!0||(U||"")!=="";i.useEffect(()=>{if(e!=="create"||!N||!ht?.autoSelectModelPreset)return;const ae=(ht.defaultPresetBySize,void 0);if(ae){const le=af(ae);H(ae.id),_("preset"),j(le.executorValue),C(le.validatorValue)}},[N,ht,un,e]);const tn=i.useRef(!1),Yt=i.useRef(!1);i.useEffect(()=>{if(e!=="create"||!N||tn.current||tt.length===0)return;const ae=tt.filter(Qe=>Qe.defaultOn);if(ae.length===0)return;tn.current=!0;const le=ae.map(Qe=>Qe.id);P(le),q?.(le)},[e,N,tt]),i.useEffect(()=>{N||(tn.current=!1)},[N]),i.useEffect(()=>{e!=="create"||!N||re&&(Yt.current||ht&&(re(ht.githubTrackingEnabledByDefault??!1),Yt.current=!0))},[e,N,ht,re]),i.useEffect(()=>{N||(Yt.current=!1)},[N]),i.useEffect(()=>{if(!ye){ln.current=cn;return}cn&&!ln.current&&ct(!0),ln.current=cn},[cn,ye]),i.useEffect(()=>{Le||(Ve(!1),oe(""))},[Le]),i.useEffect(()=>{e!=="edit"||!N||bt.current&&(bt.current.focus(),bt.current.select())},[e,N]),i.useEffect(()=>{if(!se)return;const ae=le=>{ke.current&&!ke.current.contains(le.target)&&Ve(!1)};return document.addEventListener("mousedown",ae),()=>document.removeEventListener("mousedown",ae)},[se]),i.useEffect(()=>{(e!=="edit"||$)&&dt(!1)},[e,$]),i.useEffect(()=>{if(e!=="edit"){yt("idle");return}const ae=n.trim();Vt.current=ae,hn.current=ae,yt("idle")},[e]),i.useEffect(()=>{if(e!=="edit"||!W||!N)return;const ae=n.trim(),le=Vt.current;if(ae===le||ae===hn.current){wt.current&&(clearTimeout(wt.current),wt.current=null),Ft.current||yt("idle");return}return wt.current&&clearTimeout(wt.current),wt.current=setTimeout(async()=>{if(!Ft.current){Ft.current=!0,yt("saving");try{await W(ae),hn.current=ae,yt("saved"),At.current&&clearTimeout(At.current),At.current=setTimeout(()=>{yt("idle"),At.current=null},2e3)}catch{yt("idle")}finally{Ft.current=!1,wt.current=null}}},1500),()=>{wt.current&&(clearTimeout(wt.current),wt.current=null)}},[e,n,W,N]),i.useEffect(()=>()=>{wt.current&&clearTimeout(wt.current),At.current&&clearTimeout(At.current)},[]),i.useEffect(()=>{if(!Ge)return;const ae=le=>{Je.current&&!Je.current.contains(le.target)&&K(!1)};return document.addEventListener("mousedown",ae),()=>document.removeEventListener("mousedown",ae)},[Ge]);const Qt=i.useCallback(ae=>{const le=ae.clipboardData?.items;if(le)for(let Qe=0;Qe<le.length;Qe++){const xt=le[Qe];if(xt.type.startsWith("image/")){const zt=xt.getAsFile();if(zt&&of.includes(zt.type)){ae.preventDefault(),ge([...Y,{file:zt,previewUrl:URL.createObjectURL(zt)}]);return}}}},[Y,ge]),Kt=i.useCallback(ae=>{ae.preventDefault();const le=ae.dataTransfer.files;for(let Qe=0;Qe<le.length;Qe++){const xt=le[Qe];if(of.includes(xt.type)){ge([...Y,{file:xt,previewUrl:URL.createObjectURL(xt)}]);return}}},[Y,ge]),Jt=i.useCallback(ae=>{const le=Y[ae];le&&URL.revokeObjectURL(le.previewUrl),ge(Y.filter((Qe,xt)=>xt!==ae))},[Y,ge]),rn=i.useCallback(ae=>{l(o.includes(ae)?o.filter(le=>le!==ae):[...o,ae])},[o,l]),qt=(ae,le)=>ae.length>le?ae.slice(0,le)+"…":ae,we=i.useCallback(ae=>{s(ae.target.value);const le=ae.target;le.style.height="auto",le.style.height=le.scrollHeight+"px"},[s]),ze=i.useCallback(()=>{dt(ae=>!ae)},[]),rt=i.useCallback(ae=>{!xe||ae.key!=="Escape"||(ae.preventDefault(),ae.stopPropagation(),dt(!1))},[xe]),He=i.useCallback(async ae=>{const le=n.trim();if(!(!le||ue)){ot(!0);try{const Qe=await Ab(le,ae,M);s(Qe),K(!1),D("Description refined with AI","success"),nt.current&&(nt.current.style.height="auto",nt.current.style.height=nt.current.scrollHeight+"px")}catch(Qe){const xt=Rb(Qe);D(xt,"error")}finally{ot(!1)}}},[n,ue,D,s,M]),Ae=i.useCallback(async ae=>{const le=mt,xt=le.includes(ae)?le.filter(zt=>zt!==ae):[ae,...le];We(xt);try{await Fn({favoriteProviders:xt,favoriteModels:he})}catch{We(le)}},[mt,he]),pt=i.useCallback(async ae=>{const le=he,xt=le.includes(ae)?le.filter(zt=>zt!==ae):[ae,...le];pe(xt);try{await Fn({favoriteProviders:mt,favoriteModels:xt})}catch{pe(le)}},[he,mt]),Ct=i.useCallback(ae=>{if(ae<=0)return;const le=[...A];[le[ae-1],le[ae]]=[le[ae],le[ae-1]],P(le)},[A,P]),Tt=i.useCallback(ae=>{if(ae>=A.length-1)return;const le=[...A];[le[ae],le[ae+1]]=[le[ae+1],le[ae]],P(le)},[A,P]),Gt=i.useCallback(ae=>{P(A.filter(le=>le!==ae))},[A,P]),nn=new Map;for(const ae of tt)nn.set(ae.id,{name:ae.name,description:ae.description});const Ht=L.filter(ae=>!o.includes(ae.id)).sort((ae,le)=>{const Qe=le.createdAt.localeCompare(ae.createdAt);if(Qe!==0)return Qe;const xt=parseInt(ae.id.slice(ae.id.lastIndexOf("-")+1),10)||0;return(parseInt(le.id.slice(le.id.lastIndexOf("-")+1),10)||0)-xt}),on=Ke?Ht.filter(ae=>ae.id.toLowerCase().includes(Ke.toLowerCase())||ae.title&&ae.title.toLowerCase().includes(Ke.toLowerCase())||ae.description&&ae.description.toLowerCase().includes(Ke.toLowerCase())):Ht;return t.jsxs("div",{className:"task-form",onDrop:Kt,onDragOver:ae=>ae.preventDefault(),onPaste:Qt,children:[t.jsxs("div",{className:"task-form-primary-section",children:[e==="edit"&&r&&t.jsxs("div",{className:"form-group",children:[t.jsx("label",{htmlFor:"task-form-title",children:"Title"}),t.jsx("input",{ref:bt,autoFocus:!0,id:"task-form-title",type:"text",className:"modal-edit-input",placeholder:"Task title",value:a||"",onChange:ae=>r(ae.target.value),disabled:$})]}),t.jsxs("div",{className:"form-group",children:[t.jsxs("label",{htmlFor:"task-form-description",className:"description-label-row",children:[t.jsx("span",{children:"Description"}),t.jsx("span",{className:`description-auto-save-status${Mt==="idle"?"":" is-visible"}`,"aria-live":"polite",children:Mt==="saving"?"Saving...":Mt==="saved"?"Saved":""})]}),t.jsxs("div",{className:`description-with-refine${xe?" description--fullscreen":""}`,ref:Je,onKeyDown:rt,children:[xe&&t.jsxs("div",{className:"description-fullscreen-header",children:[t.jsx("span",{children:"Editing Description"}),t.jsx("button",{type:"button",className:"btn btn-sm description-expand-btn",onClick:ze,"aria-label":"Collapse description",title:"Collapse description",children:t.jsx(Vo,{size:14})})]}),t.jsx("textarea",{ref:nt,autoFocus:e==="create",id:"task-form-description",value:n,onChange:we,placeholder:"What needs to be done?",rows:e==="edit"?8:5,disabled:$||ue}),(()=>{const ae=!!n.trim()&&!$;return t.jsxs(t.Fragment,{children:[!xe&&t.jsx("button",{type:"button",className:`btn btn-sm description-expand-btn${ae?" description-expand-btn--offset":" description-expand-btn--flush"}`,onClick:ze,"aria-label":"Expand description",title:"Expand description",children:t.jsx(jc,{size:14})}),ae&&t.jsxs("button",{type:"button",className:`btn btn-sm refine-button ${ue?"refine-button--loading":""}`,onClick:()=>K(le=>!le),disabled:ue,"data-testid":"refine-button",title:"Refine description with AI",children:[t.jsx(cs,{size:12,style:{verticalAlign:"middle"}}),ue?"Refining...":"Refine"]})]})})(),Ge&&t.jsxs("div",{className:"refine-menu refine-menu--modal",onMouseDown:ae=>ae.preventDefault(),children:[t.jsxs("div",{className:"refine-menu-item",onClick:()=>He("clarify"),"data-testid":"refine-clarify",children:[t.jsx("div",{className:"refine-menu-item-title",children:"Clarify"}),t.jsx("div",{className:"refine-menu-item-desc",children:"Make the description clearer and more specific"})]}),t.jsxs("div",{className:"refine-menu-item",onClick:()=>He("add-details"),"data-testid":"refine-add-details",children:[t.jsx("div",{className:"refine-menu-item-title",children:"Add details"}),t.jsx("div",{className:"refine-menu-item-desc",children:"Add implementation details and context"})]}),t.jsxs("div",{className:"refine-menu-item",onClick:()=>He("expand"),"data-testid":"refine-expand",children:[t.jsx("div",{className:"refine-menu-item-title",children:"Expand"}),t.jsx("div",{className:"refine-menu-item-desc",children:"Expand into a more comprehensive description"})]}),t.jsxs("div",{className:"refine-menu-item",onClick:()=>He("simplify"),"data-testid":"refine-simplify",children:[t.jsx("div",{className:"refine-menu-item-title",children:"Simplify"}),t.jsx("div",{className:"refine-menu-item-desc",children:"Simplify and make more concise"})]})]})]})]}),e==="create"&&(de||me)&&t.jsxs("div",{className:"task-form-description-actions","data-testid":"task-form-description-actions",children:[de&&t.jsx("button",{type:"button",className:"btn btn-sm",onClick:()=>{const ae=n.trim();if(!ae){D("Enter a description first","error");return}Ne?.(),de(ae)},disabled:$||!n.trim(),"data-testid":"task-form-plan-button",children:"Plan"}),me&&t.jsx("button",{type:"button",className:"btn btn-sm",onClick:()=>{const ae=n.trim();if(!ae){D("Enter a description first","error");return}Ne?.(),me(ae)},disabled:$||!n.trim(),"data-testid":"task-form-subtask-button",children:"Subtask"})]})]}),ve,t.jsxs("button",{type:"button",className:"task-form-more-options-toggle",onClick:()=>ct(ae=>!ae),"aria-expanded":Le,"aria-controls":"task-form-more-options",disabled:$,"data-testid":"task-form-more-options-toggle",children:[t.jsx("span",{children:"More options"}),Le?t.jsx(mi,{size:14}):t.jsx(vn,{size:14})]}),t.jsxs("div",{id:"task-form-more-options",className:`task-form-more-options${Le?"":" collapsed"}`,"aria-hidden":!Le,hidden:!Le,"data-testid":"task-form-more-options",children:[t.jsxs("div",{className:"form-group",children:[t.jsx("label",{children:"Attachments"}),Y.length>0&&t.jsx("div",{className:"inline-create-previews",children:Y.map((ae,le)=>t.jsxs("div",{className:"inline-create-preview",children:[t.jsx("img",{src:ae.previewUrl,alt:ae.file.name}),t.jsx("button",{type:"button",className:"inline-create-preview-remove",onClick:()=>Jt(le),disabled:$,title:"Remove image",children:"×"})]},ae.previewUrl))}),t.jsx("input",{ref:kt,type:"file",accept:"image/*",onChange:ae=>{const le=ae.target.files?.[0];le&&(ge([...Y,{file:le,previewUrl:URL.createObjectURL(le)}]),ae.target.value="")},style:{display:"none"}}),t.jsx("button",{type:"button",className:"btn btn-sm",onClick:()=>kt.current?.click(),disabled:$,children:"Attach Screenshot"}),t.jsx("small",{children:"You can also paste images or drag & drop"})]}),f&&t.jsxs("div",{className:"form-group",children:[t.jsx("label",{htmlFor:"task-node-select",children:"Execution Node Override"}),t.jsxs("select",{id:"task-node-select",className:"select",value:m??"",onChange:ae=>f(ae.target.value||void 0),disabled:$||g,children:[t.jsx("option",{value:"",children:"Use project default / local"}),(p??[]).map(ae=>t.jsxs("option",{value:ae.id,children:[ae.name," (",DP(ae.status),")"]},ae.id))]}),(()=>{const ae=(p??[]).find(le=>le.id===m);return ae?t.jsx("div",{className:"task-form-node-status",children:t.jsx(Ua,{status:ae.status,showLabel:!0})}):null})(),t.jsx("small",{children:w??"Task override takes priority over project default node routing."})]}),!ie&&t.jsx(t.Fragment,{children:t.jsxs("div",{className:"form-group",children:[t.jsx("label",{children:"Dependencies"}),t.jsxs("div",{className:"dep-trigger-wrap",ref:ke,children:[t.jsx("button",{type:"button",className:"btn btn-sm dep-trigger",onClick:()=>Ve(ae=>!ae),disabled:$,children:o.length>0?`${o.length} selected`:"Add dependencies"}),se&&t.jsxs("div",{className:"dep-dropdown",children:[t.jsx("input",{className:"dep-dropdown-search",placeholder:"Search tasks…",autoFocus:!0,value:Ke,onChange:ae=>oe(ae.target.value),onClick:ae=>ae.stopPropagation()}),on.length===0?t.jsx("div",{className:"dep-dropdown-empty",children:"No available tasks"}):on.map(ae=>t.jsxs("div",{className:`dep-dropdown-item${o.includes(ae.id)?" selected":""}`,onClick:()=>rn(ae.id),onMouseDown:le=>le.preventDefault(),children:[t.jsx("span",{className:"dep-dropdown-id",children:ae.id}),t.jsx("span",{className:"dep-dropdown-title",children:qt(ae.title||ae.description||ae.id,30)})]},ae.id))]})]}),o.length>0&&t.jsx("div",{className:"selected-deps",children:o.map(ae=>t.jsxs("span",{className:"dep-chip",children:[ae,t.jsx("button",{type:"button",className:"dep-chip-remove",onClick:()=>rn(ae),disabled:$,children:"×"})]},ae))})]})}),(d||h)&&t.jsxs("div",{className:"form-group",children:[t.jsx("label",{children:"Branch Settings"}),d&&t.jsxs(t.Fragment,{children:[t.jsx("label",{htmlFor:"task-working-branch",className:"model-select-label",children:"Working branch"}),t.jsx("input",{id:"task-working-branch",className:"input",value:c||"",onChange:ae=>d(ae.target.value),placeholder:"e.g. feature/my-task",disabled:$})]}),h&&t.jsxs(t.Fragment,{children:[t.jsx("label",{htmlFor:"task-base-branch",className:"model-select-label",children:"Merge target / base branch"}),t.jsx("input",{id:"task-base-branch",className:"input",value:u||"",onChange:ae=>h(ae.target.value),placeholder:"e.g. main",disabled:$})]})]}),t.jsxs("div",{className:"form-group",children:[t.jsx("label",{children:"Model Configuration"}),b&&t.jsxs("div",{className:"model-select-row",children:[t.jsx("label",{htmlFor:"task-priority",className:"model-select-label",children:"Priority"}),t.jsx("select",{id:"task-priority","data-testid":"task-priority-select",value:v??_s,onChange:ae=>b(ae.target.value),disabled:$,children:wa.map(ae=>t.jsx("option",{value:ae,children:ae[0].toUpperCase()+ae.slice(1)},ae))})]}),F&&Q!==void 0&&t.jsxs("div",{className:"model-select-row",children:[t.jsx("label",{htmlFor:"task-execution-mode",className:"model-select-label",children:"Execution mode"}),t.jsxs("select",{id:"task-execution-mode","data-testid":"task-form-execution-mode-select",value:Q,onChange:ae=>F(ae.target.value),disabled:$,children:[t.jsx("option",{value:"standard",children:"Standard"}),t.jsx("option",{value:"fast",children:"Fast"})]})]}),De?t.jsx("div",{className:"model-selector-loading",children:"Loading models…"}):Te.length===0?t.jsx("small",{children:"No models available. Configure authentication in Settings."}):t.jsxs(t.Fragment,{children:[t.jsxs("div",{className:"model-select-row",children:[t.jsx("label",{htmlFor:"model-preset",className:"model-select-label",children:"Preset"}),t.jsxs("select",{id:"model-preset",value:E==="preset"?G:E,onChange:ae=>{const le=ae.target.value;if(le==="default"){_("default"),H(""),j(""),C("");return}if(le==="custom"){_("custom"),H("");return}const Qe=un.find(zt=>zt.id===le),xt=af(Qe);_("preset"),H(le),j(xt.executorValue),C(xt.validatorValue)},disabled:$,children:[t.jsx("option",{value:"default",children:"Use default"}),un.length>0?t.jsx("option",{disabled:!0,children:"──────────"}):null,un.map(ae=>t.jsx("option",{value:ae.id,children:ae.name},ae.id)),t.jsx("option",{value:"custom",children:"Custom"})]})]}),E==="preset"&&pn?t.jsxs("small",{children:["Using preset: ",pn.name]}):null,E==="preset"?t.jsx("button",{type:"button",className:"btn btn-sm",onClick:()=>_("custom"),disabled:$,children:"Override"}):null,t.jsxs("div",{className:"model-select-row",children:[t.jsx("label",{htmlFor:"executor-model",className:"model-select-label",children:"Executor"}),t.jsx(Ns,{id:"executor-model",label:"Executor Model",value:y,onChange:ae=>{_("custom"),H(""),j(ae)},models:Te,disabled:$||E==="preset",favoriteProviders:mt,onToggleFavorite:Ae,favoriteModels:he,onToggleModelFavorite:pt})]}),t.jsxs("div",{className:"model-select-row",children:[t.jsx("label",{htmlFor:"validator-model",className:"model-select-label",children:"Reviewer"}),t.jsx(Ns,{id:"validator-model",label:"Reviewer Model",value:S,onChange:ae=>{_("custom"),H(""),C(ae)},models:Te,disabled:$||E==="preset",favoriteProviders:mt,onToggleFavorite:Ae,favoriteModels:he,onToggleModelFavorite:pt})]}),k&&t.jsxs("div",{className:"model-select-row",children:[t.jsx("label",{htmlFor:"planning-model",className:"model-select-label",children:"Planning"}),t.jsx(Ns,{id:"planning-model",label:"Planning Model",value:x||"",onChange:ae=>{_("custom"),H(""),k(ae)},models:Te,disabled:$||E==="preset",favoriteProviders:mt,onToggleFavorite:Ae,favoriteModels:he,onToggleModelFavorite:pt})]}),O&&t.jsxs("div",{className:"model-select-row",children:[t.jsx("label",{htmlFor:"thinking-level",className:"model-select-label",children:"Thinking"}),t.jsxs("select",{id:"thinking-level",value:R||"",onChange:ae=>O(ae.target.value),disabled:$||E==="preset",children:[t.jsxs("option",{value:"",children:["Default (",ht?.defaultThinkingLevel??"off",")"]}),t.jsx("option",{value:"off",children:"Off"}),t.jsx("option",{value:"minimal",children:"Minimal"}),t.jsx("option",{value:"low",children:"Low"}),t.jsx("option",{value:"medium",children:"Medium"}),t.jsx("option",{value:"high",children:"High"})]})]}),fe&&t.jsxs("div",{className:"model-select-row",children:[t.jsx("label",{htmlFor:"review-level",className:"model-select-label",children:"Review"}),t.jsxs("select",{id:"review-level",value:Z??"",onChange:ae=>fe(ae.target.value===""?void 0:parseInt(ae.target.value,10)),disabled:$,children:[t.jsx("option",{value:"",children:"Default (Auto — triage decides)"}),t.jsx("option",{value:"0",children:"0 — None"}),t.jsx("option",{value:"1",children:"1 — Plan Only"}),t.jsx("option",{value:"2",children:"2 — Plan and Code"}),t.jsx("option",{value:"3",children:"3 — Full"})]})]})]})]}),Me,t.jsxs("div",{className:"form-group","data-testid":"workflow-steps-section",children:[t.jsx("label",{children:"Workflow Steps"}),t.jsxs("div",{className:"workflow-steps-section",children:[t.jsx("small",{className:"workflow-steps-description",children:"Select steps to run after task implementation completes"}),t.jsx("div",{className:"workflow-steps-list",children:tt.length>0&&tt.map(ae=>t.jsxs("label",{className:"checkbox-label workflow-step-item","data-testid":`workflow-step-checkbox-${ae.id}`,children:[t.jsx("input",{type:"checkbox",checked:A.includes(ae.id),onChange:le=>{P(le.target.checked?[...A,ae.id]:A.filter(Qe=>Qe!==ae.id))},disabled:$}),t.jsxs("div",{children:[t.jsxs("span",{className:"workflow-step-name",children:[ae.name,LP(ae.phase||"pre-merge",ae.id,"workflow-step-phase")]}),t.jsx("div",{className:"workflow-step-description",children:ae.description})]})]},ae.id))})]}),A.length>1&&t.jsxs("div",{className:"workflow-step-order","data-testid":"workflow-step-order",children:[t.jsx("small",{className:"workflow-step-order-label",children:"Execution order:"}),A.map((ae,le)=>{const Qe=nn.get(ae);return t.jsxs("div",{className:"workflow-step-order-item","data-testid":`workflow-step-order-item-${ae}`,children:[t.jsx("span",{className:"workflow-step-order-number",children:le+1}),t.jsx("span",{className:"workflow-step-order-name",children:Qe?.name||ae}),t.jsxs("div",{className:"workflow-step-order-actions",children:[t.jsx("button",{type:"button",className:"btn btn-icon btn-sm",onClick:()=>Ct(le),disabled:$||le===0,"data-testid":`workflow-step-move-up-${ae}`,title:"Move up",children:t.jsx(mi,{})}),t.jsx("button",{type:"button",className:"btn btn-icon btn-sm",onClick:()=>Tt(le),disabled:$||le===A.length-1,"data-testid":`workflow-step-move-down-${ae}`,title:"Move down",children:t.jsx(vn,{})}),t.jsx("button",{type:"button",className:"btn btn-icon btn-sm",onClick:()=>Gt(ae),disabled:$,"data-testid":`workflow-step-remove-${ae}`,title:"Remove",children:t.jsx(bn,{})})]})]},ae)})]})]}),(re||be)&&t.jsxs("div",{className:"form-group","data-testid":"task-form-github-tracking",children:[t.jsx("label",{children:"GitHub Tracking"}),re&&t.jsxs("label",{className:"checkbox-label",htmlFor:"task-github-tracking-enabled",children:[t.jsx("input",{id:"task-github-tracking-enabled",type:"checkbox",checked:X===!0,onChange:ae=>{Yt.current=!0,re(ae.target.checked)},disabled:$}),"Enable GitHub issue tracking for this task"]}),be&&t.jsxs(t.Fragment,{children:[t.jsx("label",{htmlFor:"task-github-repo-override",className:"model-select-label",children:"Repository (owner/repo)"}),t.jsx("input",{id:"task-github-repo-override",className:"input",value:U||"",onChange:ae=>be(ae.target.value),placeholder:an||"owner/repo",disabled:$}),gn?t.jsx("div",{className:"form-error",children:"Repository must be in owner/repo format."}):null]})]})]})]})}const lf={p:({children:e,...n})=>t.jsx("p",{...n,children:Ws(e)}),li:({children:e,...n})=>t.jsx("li",{...n,children:Ws(e)}),code:({children:e,...n})=>t.jsx("code",{...n,children:Ws(e)}),pre:({children:e,className:n,...s})=>t.jsx("pre",{...s,className:["workflow-markdown-pre",n].filter(Boolean).join(" "),children:Ws(e)}),table:({children:e,className:n,...s})=>t.jsx("table",{...s,className:["workflow-markdown-table",n].filter(Boolean).join(" "),children:e})};function OP(e){switch(e){case"passed":return"Passed";case"failed":return"Failed";case"skipped":return"Skipped";case"pending":return"Running…";default:return e}}function FP(e,n){if(!e||!n)return null;const s=new Date(e).getTime(),r=new Date(n).getTime()-s;if(r<1e3)return`${r}ms`;const o=Math.round(r/1e3);if(o<60)return`${o}s`;const l=Math.floor(o/60),c=o%60;return`${l}m ${c}s`}function zP(e){return e?new Date(e).toLocaleString():null}function BP(e){const n=e.split(`
686
- `);return n.length<=1?e:`${n.length} lines`}function yl(e,n,s){const a=e==="post-merge"?"phase-badge--post-merge":"phase-badge--pre-merge";return t.jsx("span",{className:`phase-badge ${a}`,"data-testid":`${s}-${n}`,children:e==="post-merge"?"Post-merge":"Pre-merge"})}function UP({entries:e,startedAt:n,stepId:s}){const a=i.useRef(null),r=new Date(n).getTime(),o=e.filter(l=>new Date(l.timestamp).getTime()>=r);return i.useEffect(()=>{const l=a.current;l&&(l.scrollTop=l.scrollHeight)},[o.length]),o.length===0?t.jsx("div",{className:"workflow-live-log","data-testid":`workflow-live-log-${s}`,children:t.jsx("div",{className:"workflow-live-log-empty",children:"Waiting for agent output…"})}):t.jsx("div",{ref:a,className:"workflow-live-log","data-testid":`workflow-live-log-${s}`,children:o.map((l,c)=>l.type==="tool"?t.jsxs("div",{className:"workflow-live-log-tool",children:["⚡ ",ks(l.text),l.detail&&t.jsxs("span",{className:"workflow-live-log-detail",children:[" — ",ks(l.detail)]})]},c):l.type==="tool_result"?t.jsxs("div",{className:"workflow-live-log-tool-result",children:["✓ ",ks(l.text),l.detail&&t.jsxs("span",{className:"workflow-live-log-detail",children:[" — ",ks(l.detail)]})]},c):l.type==="tool_error"?t.jsxs("div",{className:"workflow-live-log-tool-error",children:["✗ ",ks(l.text),l.detail&&t.jsxs("span",{className:"workflow-live-log-detail",children:[" — ",ks(l.detail)]})]},c):l.type==="thinking"?t.jsx("div",{className:"workflow-live-log-thinking",children:ks(l.text)},c):t.jsx("span",{className:"workflow-live-log-text",children:ks(l.text)},c))})}function HP({taskId:e,results:n,loading:s,enabledWorkflowSteps:a,canEdit:r,projectId:o,isTaskInProgress:l,onWorkflowStepsChange:c}){const[d,u]=i.useState({}),[h,m]=i.useState({}),[f,p]=i.useState(null),[g,w]=i.useState([]),[v,b]=i.useState(!1),y=n.some(N=>N.status==="pending"),{entries:j}=vv(e,!!l&&y,o);i.useEffect(()=>{let N=!1;return Jo(o).then(W=>{N||w(W.filter(de=>de.enabled))}).catch(()=>{N||w([])}),()=>{N=!0}},[o]);const S=a??[],C=i.useMemo(()=>g.map(N=>({id:N.id,name:N.name,description:N.description,phase:N.phase||"pre-merge"})),[g]),x=i.useMemo(()=>new Map(C.map(N=>[N.id,N])),[C]),k=N=>{u(W=>({...W,[N]:!W[N]}))},R=N=>{m(W=>{const de=W[N]??"markdown";return{...W,[N]:de==="markdown"?"plain":"markdown"}})},O=N=>{p(N)},E=()=>{p(null)};i.useEffect(()=>{if(!f)return;const N=W=>{W.key==="Escape"&&E()};return document.addEventListener("keydown",N),()=>{document.removeEventListener("keydown",N)}},[f]);const _=i.useCallback((N,W)=>{if(c){if(W){if(S.includes(N)){c(S);return}c([...S,N]);return}c(S.filter(de=>de!==N))}},[c,S]),G=i.useCallback(N=>{if(!c||N<=0)return;const W=[...S];[W[N-1],W[N]]=[W[N],W[N-1]],c(W)},[c,S]),H=i.useCallback(N=>{if(!c||N>=S.length-1)return;const W=[...S];[W[N],W[N+1]]=[W[N+1],W[N]],c(W)},[c,S]),A=i.useCallback(N=>{c&&c(S.filter(W=>W!==N))},[c,S]),P=n.length>0,q=S.length>0;i.useEffect(()=>{r||b(!1)},[r]);const Y=i.useMemo(()=>S.map(N=>{const W=x.get(N);return{id:N,name:W?.name||N,description:W?.description||"Step definition not found.",phase:W?.phase||"pre-merge"}}),[S,x]),ge=()=>!r||!v||s?null:t.jsxs("div",{className:"workflow-results-editor","data-testid":"workflow-steps-editor",children:[t.jsxs("div",{className:"workflow-steps-section",children:[t.jsx("small",{className:"workflow-steps-description",children:"Select steps to run after task implementation completes"}),t.jsx("div",{className:"workflow-steps-list",children:C.map(N=>t.jsxs("label",{className:"checkbox-label workflow-step-item","data-testid":`workflow-step-checkbox-${N.id}`,children:[t.jsx("input",{type:"checkbox",checked:S.includes(N.id),onChange:W=>_(N.id,W.target.checked)}),t.jsxs("div",{children:[t.jsxs("span",{className:"workflow-step-name",children:[N.name,yl(N.phase,N.id,"workflow-step-phase")]}),t.jsx("div",{className:"workflow-step-description",children:N.description})]})]},N.id))})]}),S.length>1&&t.jsxs("div",{className:"workflow-step-order","data-testid":"workflow-step-order",children:[t.jsx("small",{className:"workflow-step-order-label",children:"Execution order:"}),S.map((N,W)=>{const de=x.get(N);return t.jsxs("div",{className:"workflow-step-order-item","data-testid":`workflow-step-order-item-${N}`,children:[t.jsx("span",{className:"workflow-step-order-number",children:W+1}),t.jsx("span",{className:"workflow-step-order-name",children:de?.name||N}),t.jsxs("div",{className:"workflow-step-order-actions",children:[t.jsx("button",{type:"button",className:"btn btn-icon btn-sm",onClick:()=>G(W),disabled:W===0,"data-testid":`workflow-step-move-up-${N}`,title:"Move up",children:t.jsx(mi,{})}),t.jsx("button",{type:"button",className:"btn btn-icon btn-sm",onClick:()=>H(W),disabled:W===S.length-1,"data-testid":`workflow-step-move-down-${N}`,title:"Move down",children:t.jsx(vn,{})}),t.jsx("button",{type:"button",className:"btn btn-icon btn-sm",onClick:()=>A(N),"data-testid":`workflow-step-remove-${N}`,title:"Remove",children:t.jsx(bn,{})})]})]},N)})]})]}),L=()=>{if(s)return t.jsxs("div",{className:"workflow-results-loading","data-testid":"workflow-results-loading",children:[t.jsx("div",{className:"workflow-results-spinner"}),t.jsx("span",{children:"Loading workflow results…"})]});if(!P)return t.jsxs("div",{className:"workflow-results-empty","data-testid":"workflow-results-empty",children:[t.jsx("p",{children:"No workflow steps configured for this task."}),t.jsx("p",{className:"workflow-results-empty-hint",children:"Pre-merge steps run after implementation, before merge. Post-merge steps run after merge succeeds."})]});const N=n.filter(ve=>ve.status==="passed").length,W=n.filter(ve=>ve.status==="failed").length,de=n.filter(ve=>ve.status==="skipped").length,me=n.filter(ve=>ve.status==="pending").length,Ne=[`${n.length} step${n.length!==1?"s":""}`];return N>0&&Ne.push(`${N} passed`),W>0&&Ne.push(`${W} failed`),de>0&&Ne.push(`${de} skipped`),me>0&&Ne.push(`${me} running`),t.jsxs("div",{className:"workflow-results-list","data-testid":"workflow-results-list",children:[t.jsx("div",{className:"workflow-results-summary-bar","data-testid":"workflow-results-summary",children:Ne.join(" · ")}),n.map((ve,Me)=>{const ie=ve.phase||"pre-merge",ye=d[ve.workflowStepId]??!1;return t.jsxs("div",{className:`workflow-result-item workflow-result-item--${ve.status}`,"data-testid":`workflow-result-item-${ve.workflowStepId}`,children:[t.jsxs("div",{className:"workflow-result-header",children:[t.jsxs("div",{className:"workflow-result-name",children:[ve.workflowStepName,yl(ie,ve.workflowStepId,"workflow-result-phase")]}),t.jsx("span",{className:`workflow-result-badge workflow-result-badge--${ve.status}`,"data-testid":`workflow-result-badge-${ve.workflowStepId}`,children:OP(ve.status)})]}),t.jsxs("div",{className:"workflow-result-meta",children:[ve.startedAt&&t.jsxs("span",{className:"workflow-result-timestamp",children:["Started: ",zP(ve.startedAt)]}),ve.completedAt&&t.jsx("span",{className:"workflow-result-duration",children:FP(ve.startedAt,ve.completedAt)})]}),ve.status==="pending"&&ve.startedAt?t.jsx(UP,{entries:j,startedAt:ve.startedAt,stepId:ve.workflowStepId}):ve.output?t.jsxs("div",{className:"workflow-result-output-section",children:[t.jsxs("div",{className:"workflow-result-output-header",children:[t.jsx("span",{className:"workflow-result-output-label",children:"Output:"}),t.jsx("button",{type:"button",className:"btn btn-sm workflow-result-toggle",onClick:()=>k(ve.workflowStepId),"data-testid":`workflow-result-toggle-${ve.workflowStepId}`,children:ye?"Hide output":"Show output"}),!ye&&t.jsx("span",{className:"workflow-result-output-preview","data-testid":`workflow-result-preview-${ve.workflowStepId}`,children:BP(ve.output)}),ye&&t.jsxs(t.Fragment,{children:[t.jsx("button",{type:"button",className:"btn btn-sm workflow-result-mode-toggle",onClick:()=>R(ve.workflowStepId),"data-testid":`workflow-result-mode-toggle-${ve.workflowStepId}`,title:(h[ve.workflowStepId]??"markdown")==="markdown"?"Switch to plain text":"Switch to markdown",children:(h[ve.workflowStepId]??"markdown")==="markdown"?"Markdown":"Plain"}),t.jsx("button",{type:"button",className:"btn btn-icon btn-sm workflow-result-expand-toggle",onClick:()=>O(ve.workflowStepId),"data-testid":`workflow-result-expand-${ve.workflowStepId}`,title:"Expand output",children:t.jsx(jc,{size:12})})]})]}),ye&&t.jsx("div",{className:`workflow-result-output${(h[ve.workflowStepId]??"markdown")==="markdown"?" workflow-result-output--markdown":""}`,"data-testid":`workflow-result-output-${ve.workflowStepId}`,children:(h[ve.workflowStepId]??"markdown")==="markdown"?t.jsx("div",{className:"markdown-body",children:t.jsx(hi,{remarkPlugins:[pi],components:lf,children:ve.output})}):t.jsx("pre",{className:"workflow-result-output-text",children:ks(ve.output??"")})})]}):null]},`${ve.workflowStepId}-${Me}`)})]})},M=r?t.jsx("button",{type:"button",className:"btn btn-sm workflow-results-edit-toggle",onClick:()=>b(N=>!N),"data-testid":"workflow-steps-edit-toggle","aria-label":v?"Done editing workflow steps":"Edit workflow steps",title:v?"Done":"Edit",children:v?t.jsxs(t.Fragment,{children:[t.jsx(gs,{size:14}),"Done"]}):t.jsxs(t.Fragment,{children:[t.jsx(Os,{size:14}),"Edit"]})}):null,$=!s&&!P&&q,D=r&&P;return t.jsxs("div",{className:"workflow-results-tab","data-task-id":e,children:[$?t.jsxs("div",{className:"workflow-configured-steps","data-testid":"workflow-configured-steps",children:[t.jsxs("div",{className:"workflow-configured-header","data-testid":"workflow-configured-header",children:[t.jsxs("div",{className:"workflow-configured-title-row",children:[t.jsx("h4",{children:"Configured Workflow Steps"}),t.jsxs("span",{className:"workflow-configured-count","data-testid":"workflow-configured-count",children:[Y.length," step",Y.length===1?"":"s"]})]}),M]}),t.jsx("div",{className:"workflow-configured-list","data-testid":"workflow-configured-list",children:Y.map(N=>t.jsxs("div",{className:"workflow-configured-item","data-testid":`workflow-configured-step-${N.id}`,children:[t.jsxs("div",{className:"workflow-configured-name",children:[t.jsx("span",{className:"workflow-configured-name-text",children:N.name}),yl(N.phase,N.id,"workflow-configured-phase")]}),t.jsx("p",{className:"workflow-configured-description",children:N.description})]},N.id))}),t.jsx("p",{className:"workflow-results-empty-hint",children:"Pre-merge steps run after implementation, before merge. Post-merge steps run after merge succeeds."}),ge()]}):t.jsxs(t.Fragment,{children:[D&&t.jsxs("div",{className:"workflow-results-edit-header","data-testid":"workflow-results-edit-header",children:[t.jsx("h4",{children:"Workflow Steps"}),M]}),L(),ge()]}),f&&(()=>{const N=n.find(me=>me.workflowStepId===f);if(!N)return null;const W=h[N.workflowStepId]??"markdown",de=N.phase||"pre-merge";return t.jsx("div",{className:"workflow-output-modal-overlay",onClick:me=>{me.target===me.currentTarget&&E()},"data-testid":"workflow-output-modal",children:t.jsxs("div",{className:"workflow-output-modal",role:"dialog","aria-modal":"true",children:[t.jsxs("div",{className:"workflow-output-modal-header",children:[t.jsxs("div",{className:"workflow-output-modal-title",children:[t.jsx("span",{className:"workflow-output-modal-name",children:N.workflowStepName}),yl(de,N.workflowStepId,"workflow-output-modal-phase")]}),t.jsxs("div",{className:"workflow-output-modal-controls",children:[t.jsx("button",{type:"button",className:"btn btn-sm workflow-result-mode-toggle",onClick:()=>R(N.workflowStepId),"data-testid":"workflow-output-modal-mode-toggle",title:W==="markdown"?"Switch to plain text":"Switch to markdown",children:W==="markdown"?"Markdown":"Plain"}),t.jsx("button",{type:"button",className:"btn btn-icon btn-sm workflow-output-modal-close",onClick:E,"data-testid":"workflow-output-modal-close","aria-label":"Close",children:t.jsx(bn,{size:16})})]})]}),t.jsx("div",{className:"workflow-output-modal-body",children:t.jsx("div",{className:`workflow-result-output workflow-result-output--expanded${W==="markdown"?" workflow-result-output--markdown":""}`,"data-testid":"workflow-output-modal-content",children:W==="markdown"?t.jsx("div",{className:"markdown-body",children:t.jsx(hi,{remarkPlugins:[pi],components:lf,children:N.output})}):t.jsx("pre",{className:"workflow-result-output-text",children:ks(N.output??"")})})})]})})})()]})}function qP(e){return e==="block"?"Block execution":e==="fallback-local"?"Fall back to local":"Not configured"}const VP=new Set(["planning","researching","executing","finalizing","merging","merging-fix"]);function WP(e){return e!==void 0&&e!=="online"}function GP({task:e,settings:n,addToast:s,onTaskUpdated:a}){const[r,o]=i.useState([]),[l,c]=i.useState(!1),[d,u]=i.useState(null),[h,m]=i.useState(e.nodeId??""),[f,p]=i.useState(!1),g=i.useRef(e.id);i.useEffect(()=>{g.current=e.id,m(e.nodeId??""),p(!1)},[e.id,e.nodeId]),i.useEffect(()=>{c(!0),u(null),ec().then(E=>{o(E)}).catch(E=>{u(Ie(E)||"Failed to load nodes")}).finally(()=>{c(!1)})},[]);const w=i.useMemo(()=>new Map(r.map(E=>[E.id,E])),[r]),v=i.useMemo(()=>[...r].sort((E,_)=>E.name.localeCompare(_.name)),[r]),b=n,y=e.nodeId??b?.defaultNodeId??null,j=e.nodeId?"Per-task override":b?.defaultNodeId?"Project default":"No routing",S=y?w.get(y):void 0,C=S?`${S.name} (${S.type})`:y?`${y} (node unavailable or unknown)`:"Local (no routing configured)",x=e.column==="in-progress"||VP.has(e.status),k=x||f||l,R=i.useCallback(async E=>{if(E===h)return;const _=e.id,G=h;m(E),p(!0);try{const H=await Ls(_,{nodeId:E||null});if(g.current!==_)return;m(H.nodeId??""),a?.(H),s(E?"Node override updated":"Node override cleared","success")}catch(H){if(g.current!==_)return;m(G),s(Ie(H)||"Failed to update node override","error")}finally{g.current===_&&p(!1)}},[s,a,h,e.id]),O=i.useCallback(()=>{R("")},[R]);return t.jsxs("div",{className:"routing-tab",children:[t.jsx("h4",{children:"Task Routing"}),t.jsx("p",{className:"routing-tab__intro",children:"View the effective execution node and control per-task node override."}),t.jsxs("section",{className:"routing-tab__section",children:[t.jsx("h5",{children:"Routing Summary"}),t.jsxs("div",{className:"routing-summary-grid",role:"list",children:[t.jsxs("div",{className:"routing-summary-row",role:"listitem",children:[t.jsx("span",{className:"routing-summary-label",children:"Effective node"}),t.jsxs("span",{className:"routing-summary-value",children:[S?t.jsx(Ua,{status:S.status,compact:!0}):null,C,WP(S?.status)?t.jsx("span",{className:"routing-summary-warning",children:"Unhealthy"}):null]})]}),t.jsxs("div",{className:"routing-summary-row",role:"listitem",children:[t.jsx("span",{className:"routing-summary-label",children:"Routing source"}),t.jsx("span",{className:"routing-summary-value",children:j})]}),t.jsxs("div",{className:"routing-summary-row",role:"listitem",children:[t.jsx("span",{className:"routing-summary-label",children:"Unavailable-node policy"}),t.jsx("span",{className:"routing-summary-value",children:qP(b?.unavailableNodePolicy)})]})]}),x&&y?t.jsx("div",{className:"routing-tab__info-banner",children:"Routing is locked while this task is active. Node override cannot be changed until the task is no longer active."}):null]}),t.jsxs("section",{className:"routing-tab__section",children:[t.jsx("h5",{children:"Node Override"}),x?t.jsx("div",{className:"routing-tab__warning-banner",children:"Node override cannot be changed while the task is active."}):null,t.jsx("label",{className:"routing-tab__selector-label",htmlFor:`routing-node-${e.id}`,children:"Select execution node"}),t.jsxs("select",{id:`routing-node-${e.id}`,className:"select routing-tab__selector",value:h,disabled:k,onChange:E=>{R(E.target.value)},children:[t.jsx("option",{value:"",children:"Use project default"}),v.map(E=>t.jsxs("option",{value:E.id,title:`Status: ${E.status}`,children:[E.name," (",E.type,") — ",E.status]},E.id))]}),d?t.jsx("div",{className:"routing-tab__error",children:d}):null,e.nodeId?t.jsxs("div",{className:"routing-tab__override-row",children:[t.jsxs("span",{className:"routing-tab__override-text",children:["Override set to: ",w.get(e.nodeId)?.name??e.nodeId]}),t.jsx("button",{type:"button",className:"btn btn-sm",disabled:x||f,onClick:O,children:"Clear override"})]}):null]})]})}const KP=/^[a-zA-Z0-9_-]{1,64}$/,JP=200;function cf(e){return e?new Date(e).toLocaleString():""}function YP(e,n=JP){return e.length<=n?e:e.substring(0,n)+"…"}function QP({taskId:e,addToast:n,onTaskUpdated:s,projectId:a,canEdit:r=!1}){const[o,l]=i.useState([]),[c,d]=i.useState(!0),[u,h]=i.useState(null),[m,f]=i.useState(""),[p,g]=i.useState(null),[w,v]=i.useState(""),[b,y]=i.useState(null),[j,S]=i.useState([]),[C,x]=i.useState(!1),[k,R]=i.useState(!1),[O,E]=i.useState(""),[_,G]=i.useState(""),[H,A]=i.useState(!1),[P,q]=i.useState(null),[Y,ge]=i.useState(null),[L,M]=i.useState(!1),$=i.useCallback(async()=>{try{const ie=await MN(e,a);l(ie)}catch(ie){n(Ie(ie)||"Failed to load documents","error")}finally{d(!1)}},[e,a,n]);i.useEffect(()=>{$()},[$]);async function D(ie){u===ie.key?(h(null),f(""),g(null),v(""),y(null),S([]),M(!1)):(h(ie.key),f(ie.content),g(null),v(""),y(null),S([]),M(!1))}async function N(ie){if(b===ie)y(null),S([]);else{y(ie),x(!0);try{const ye=await AN(e,ie,a);S(ye)}catch(ye){n(Ie(ye)||"Failed to load revisions","error")}finally{x(!1)}}}function W(){u&&(g(u),v(m))}function de(){g(null),v("")}async function me(){if(!(!p||!w.trim())){A(!0);try{await Ym(e,p,w,{},a),g(null),v(""),await $();const ie=o.find(ye=>ye.key===p);ie&&f(ie.content),n("Document saved","success")}catch(ie){n(Ie(ie)||"Failed to save document","error")}finally{A(!1)}}}async function Ne(){const ie=O.trim(),ye=_.trim();if(!ie){n("Document key is required","error");return}if(!KP.test(ie)){n("Invalid key format. Use 1-64 alphanumeric characters, hyphens, or underscores.","error");return}if(!ye){n("Content is required","error");return}A(!0);try{await Ym(e,ie,ye,{},a),R(!1),E(""),G(""),await $(),n("Document created","success")}catch(Z){n(Ie(Z)||"Failed to create document","error")}finally{A(!1)}}async function ve(ie){q(ie);try{await RN(e,ie,a),ge(null),q(null),u===ie&&(h(null),f("")),b===ie&&(y(null),S([])),await $(),n("Document deleted","success")}catch(ye){n(Ie(ye)||"Failed to delete document","error")}finally{q(null)}}function Me(ie){f(ie.content),g(null),v("")}return c?t.jsxs("div",{className:"detail-section",children:[t.jsx("h4",{children:"Documents"}),t.jsx("div",{className:"detail-log-empty",children:"Loading documents…"})]}):t.jsxs("div",{className:"detail-section",children:[t.jsx("h4",{children:"Documents"}),k&&t.jsxs("div",{className:"task-document-create-form",children:[t.jsx("h5",{children:"New Document"}),t.jsxs("div",{className:"form-group",children:[t.jsx("label",{htmlFor:"doc-key",children:"Key"}),t.jsx("input",{id:"doc-key",type:"text",className:"task-document-key-input",value:O,onChange:ie=>E(ie.target.value),placeholder:"e.g., plan, notes, research",disabled:H}),t.jsx("span",{className:"form-hint",children:"Alphanumeric, hyphens, underscores (1-64 chars)"})]}),t.jsxs("div",{className:"form-group",children:[t.jsx("label",{htmlFor:"doc-content",children:"Content"}),t.jsx("textarea",{id:"doc-content",value:_,onChange:ie=>G(ie.target.value),rows:6,placeholder:"Enter document content…",disabled:H})]}),t.jsxs("div",{className:"form-actions",children:[t.jsx("button",{className:"btn btn-sm",onClick:()=>{R(!1),E(""),G("")},disabled:H,children:"Cancel"}),t.jsx("button",{className:"btn btn-primary btn-sm",onClick:()=>void Ne(),disabled:H||!O.trim()||!_.trim(),children:H?"Creating…":"Create"})]})]}),o.length===0&&!k?t.jsx("div",{className:"detail-log-empty",children:"No documents yet."}):t.jsx("div",{className:"task-documents-list",children:o.map(ie=>t.jsxs("div",{className:"task-document-card",children:[t.jsxs("div",{className:"task-document-card-header",children:[t.jsxs("div",{className:"task-document-card-title",children:[t.jsx(xa,{size:14}),t.jsx("span",{className:"task-document-key",children:ie.key}),t.jsxs("span",{className:"task-document-revision-badge",children:["v",ie.revision]})]}),t.jsxs("div",{className:"task-document-meta",children:[t.jsx("span",{className:"task-document-author",children:ie.author}),t.jsx("span",{className:"task-document-timestamp",children:cf(ie.updatedAt||ie.createdAt)})]})]}),u===ie.key&&p!==ie.key&&t.jsxs(t.Fragment,{children:[t.jsx("div",{className:"task-document-content-header",children:t.jsx("button",{className:"btn btn-sm document-mode-toggle",onClick:()=>M(ye=>!ye),"aria-label":L?"Switch to plain text":"Switch to markdown","aria-pressed":L,title:L?"Switch to plain text":"Switch to markdown",children:L?"Markdown":"Plain"})}),t.jsx("div",{className:"task-document-content",children:L?t.jsx("div",{className:"task-document-content-markdown",children:t.jsx("div",{className:"markdown-body",children:t.jsx(hi,{remarkPlugins:[pi],children:m})})}):t.jsx("pre",{className:"task-document-content-text",children:m})}),b===ie.key&&t.jsxs("div",{className:"task-document-revisions",children:[t.jsx("h5",{children:"Revision History"}),C?t.jsx("div",{className:"detail-log-empty",children:"Loading…"}):j.length<=1?t.jsx("div",{className:"detail-log-empty",children:"No previous revisions."}):t.jsx("div",{className:"task-document-revision-list",children:j.filter(ye=>ye.revision<ie.revision).sort((ye,Z)=>Z.revision-ye.revision).map(ye=>t.jsxs("div",{className:"task-document-revision-item",onClick:()=>Me(ye),children:[t.jsxs("div",{className:"revision-header",children:[t.jsxs("span",{className:"revision-badge",children:["v",ye.revision]}),t.jsx("span",{className:"revision-author",children:ye.author}),t.jsx("span",{className:"revision-timestamp",children:cf(ye.createdAt)})]}),t.jsx("div",{className:"revision-preview",children:YP(ye.content,100)})]},ye.id))})]})]}),p===ie.key&&t.jsxs("div",{className:"task-document-edit-form",children:[t.jsx("textarea",{value:w,onChange:ye=>v(ye.target.value),rows:10,disabled:H}),t.jsxs("div",{className:"form-actions",children:[t.jsx("button",{className:"btn btn-sm",onClick:de,disabled:H,children:"Cancel"}),t.jsx("button",{className:"btn btn-primary btn-sm",onClick:()=>void me(),disabled:H||!w.trim(),children:H?"Saving…":"Save"})]})]}),t.jsxs("div",{className:"task-document-actions",children:[t.jsx("button",{className:"btn btn-sm",onClick:()=>void D(ie),children:u===ie.key?t.jsxs(t.Fragment,{children:[t.jsx(mi,{size:14})," Collapse"]}):t.jsxs(t.Fragment,{children:[t.jsx(vn,{size:14})," Expand"]})}),u===ie.key&&t.jsxs(t.Fragment,{children:[t.jsxs("button",{className:"btn btn-sm",onClick:()=>void N(ie.key),children:[t.jsx(Oa,{size:14})," History"]}),r&&p!==ie.key&&t.jsx("button",{className:"btn btn-sm",onClick:W,children:"Edit"}),r&&(Y===ie.key?t.jsxs("div",{className:"confirm-delete-actions",children:[t.jsx("span",{children:"Delete?"}),t.jsx("button",{className:"btn btn-danger btn-sm",onClick:()=>void ve(ie.key),disabled:P===ie.key,children:P===ie.key?"…":"Yes"}),t.jsx("button",{className:"btn btn-sm",onClick:()=>ge(null),disabled:P===ie.key,children:"No"})]}):t.jsx("button",{className:"btn btn-danger btn-sm",onClick:()=>ge(ie.key),children:t.jsx(In,{size:14})}))]})]})]},ie.key))}),r&&!k&&t.jsxs("button",{className:"btn btn-sm task-document-new-btn",onClick:()=>R(!0),children:[t.jsx(Tn,{size:14})," New Document"]})]})}function wl(e){return e.toLocaleString()}function Rd(e){const n=new Date(e);return Number.isNaN(n.getTime())?e:n.toLocaleString()}function co(e){if(e<1e3)return`${Math.round(e)} ms`;const n=e/1e3;if(n<60)return`${n.toFixed(1)} s`;const s=Math.floor(n/60),a=Math.round(n%60);return`${s}m ${a}s`}function XP(e){const n=Date.now(),s=e.map(o=>{if(!o.startedAt)return null;const l=new Date(o.startedAt).getTime();if(Number.isNaN(l))return null;let c;if(o.completedAt){const d=new Date(o.completedAt).getTime();if(Number.isNaN(d)||d<l)return null;c=d}else c=Math.max(l,n);return{name:o.workflowStepName||o.workflowStepId,durationMs:c-l}}).filter(o=>o!==null),a=sx(e,n)??0,r=s.reduce((o,l)=>!o||l.durationMs>o.durationMs?l:o,void 0);return{timedStepCount:s.length,totalDurationMs:a,longestStep:r}}function ZP({tokenUsage:e,loading:n,task:s}){const a=Date.now(),r=tx(s?.log??[]),o=r.filter(g=>typeof g.durationMs=="number"),l=o.reduce((g,w)=>g+(w.durationMs??0),0),c=nx(s?.log)??0,d=typeof s?.timedExecutionMs=="number"?s.timedExecutionMs:Math.max(l,c),u=o.reduce((g,w)=>!g||(w.durationMs??0)>(g.durationMs??0)?w:g,void 0),h=XP(s?.workflowStepResults??[]),f=ix(s?.executionStartedAt,s?.executionCompletedAt,a)??(typeof s?.timedExecutionMs=="number"?s.timedExecutionMs:d+h.totalDurationMs),p=s?.steps?.length??0;return t.jsxs("section",{className:"task-token-stats-panel","aria-label":"Task execution statistics",children:[t.jsx("h4",{children:"Execution & Token Stats"}),t.jsxs("div",{className:"task-token-stats-panel__section",children:[t.jsx("h5",{children:"Execution Timing"}),t.jsxs("div",{className:"task-token-stats-panel__grid",role:"list","aria-label":"Execution timing metrics",children:[t.jsxs("div",{className:"task-token-stats-panel__metric",role:"listitem",children:[t.jsx("span",{className:"task-token-stats-panel__label",children:"Timing events"}),t.jsx("span",{className:"task-token-stats-panel__value",children:r.length.toLocaleString()})]}),t.jsxs("div",{className:"task-token-stats-panel__metric",role:"listitem",children:[t.jsx("span",{className:"task-token-stats-panel__label",children:"Timed duration"}),t.jsx("span",{className:"task-token-stats-panel__value",children:co(d)})]}),t.jsxs("div",{className:"task-token-stats-panel__metric",role:"listitem",children:[t.jsx("span",{className:"task-token-stats-panel__label",children:"Workflow timed steps"}),t.jsx("span",{className:"task-token-stats-panel__value",children:h.timedStepCount.toLocaleString()})]}),t.jsxs("div",{className:"task-token-stats-panel__metric",role:"listitem",children:[t.jsx("span",{className:"task-token-stats-panel__label",children:"Workflow runtime"}),t.jsx("span",{className:"task-token-stats-panel__value",children:co(h.totalDurationMs)})]}),t.jsxs("div",{className:"task-token-stats-panel__metric",role:"listitem",children:[t.jsx("span",{className:"task-token-stats-panel__label",children:"Total execution time"}),t.jsx("span",{className:"task-token-stats-panel__value",children:co(f)})]})]}),t.jsxs("dl",{className:"task-token-stats-panel__timestamps",children:[t.jsxs("div",{className:"task-token-stats-panel__timestamp-row",children:[t.jsx("dt",{children:"Longest timing event"}),t.jsx("dd",{children:u?.durationMs?`${u.summary} (${co(u.durationMs)})`:"No timed events recorded yet."})]}),t.jsxs("div",{className:"task-token-stats-panel__timestamp-row",children:[t.jsx("dt",{children:"Longest workflow step"}),t.jsx("dd",{children:h.longestStep?`${h.longestStep.name} (${co(h.longestStep.durationMs)})`:"No completed workflow step timings yet."})]})]})]}),t.jsxs("div",{className:"task-token-stats-panel__section",children:[t.jsx("h5",{children:"Execution Details"}),t.jsxs("dl",{className:"task-token-stats-panel__details",children:[t.jsxs("div",{className:"task-token-stats-panel__detail-row",children:[t.jsx("dt",{children:"Execution mode"}),t.jsx("dd",{children:s?.executionMode==="fast"?"Fast":"Standard"})]}),t.jsxs("div",{className:"task-token-stats-panel__detail-row",children:[t.jsx("dt",{children:"Runtime status"}),t.jsx("dd",{children:s?.status??"Not set"})]}),t.jsxs("div",{className:"task-token-stats-panel__detail-row",children:[t.jsx("dt",{children:"Paused"}),t.jsx("dd",{children:s?.paused?"Yes":"No"})]}),t.jsxs("div",{className:"task-token-stats-panel__detail-row",children:[t.jsx("dt",{children:"Step progress"}),t.jsx("dd",{children:p>0?`${Math.min((s?.currentStep??0)+1,p)} / ${p}`:"No steps"})]}),t.jsxs("div",{className:"task-token-stats-panel__detail-row",children:[t.jsx("dt",{children:"Retries (recovery / workflow / merge / task_done)"}),t.jsx("dd",{children:`${s?.recoveryRetryCount??0} / ${s?.workflowStepRetries??0} / ${s?.mergeRetries??0} / ${s?.taskDoneRetryCount??0}`})]}),t.jsxs("div",{className:"task-token-stats-panel__detail-row",children:[t.jsx("dt",{children:"Recovery state"}),t.jsx("dd",{children:s?.nextRecoveryAt?`Next recovery at ${Rd(s.nextRecoveryAt)}`:"No scheduled recovery"})]}),t.jsxs("div",{className:"task-token-stats-panel__detail-row",children:[t.jsx("dt",{children:"Self-heal counters"}),t.jsx("dd",{children:`stuck kills: ${s?.stuckKillCount??0}, post-review fixes: ${s?.postReviewFixCount??0}`})]}),t.jsxs("div",{className:"task-token-stats-panel__detail-row",children:[t.jsx("dt",{children:"Runtime links"}),t.jsx("dd",{children:[s?.assignedAgentId?`agent ${s.assignedAgentId}`:null,s?.checkedOutBy?`checkout ${s.checkedOutBy}`:null,s?.blockedBy?`blocked by ${s.blockedBy}`:null,s?.sessionFile?"has session":null].filter(Boolean).join(", ")||"No runtime links"})]})]})]}),t.jsxs("div",{className:"task-token-stats-panel__section",children:[t.jsx("h5",{children:"Token Usage"}),!e&&n?t.jsx("div",{className:"task-token-stats-panel__loading",role:"status","aria-live":"polite",children:"Loading token statistics…"}):e?t.jsxs(t.Fragment,{children:[t.jsxs("div",{className:"task-token-stats-panel__grid",role:"list","aria-label":"Task token totals",children:[t.jsxs("div",{className:"task-token-stats-panel__metric",role:"listitem",children:[t.jsx("span",{className:"task-token-stats-panel__label",children:"Input"}),t.jsx("span",{className:"task-token-stats-panel__value",children:wl(e.inputTokens)})]}),t.jsxs("div",{className:"task-token-stats-panel__metric",role:"listitem",children:[t.jsx("span",{className:"task-token-stats-panel__label",children:"Output"}),t.jsx("span",{className:"task-token-stats-panel__value",children:wl(e.outputTokens)})]}),t.jsxs("div",{className:"task-token-stats-panel__metric",role:"listitem",children:[t.jsx("span",{className:"task-token-stats-panel__label",children:"Cached"}),t.jsx("span",{className:"task-token-stats-panel__value",children:wl(e.cachedTokens)})]}),t.jsxs("div",{className:"task-token-stats-panel__metric",role:"listitem",children:[t.jsx("span",{className:"task-token-stats-panel__label",children:"Total"}),t.jsx("span",{className:"task-token-stats-panel__value",children:wl(e.totalTokens)})]})]}),t.jsxs("dl",{className:"task-token-stats-panel__timestamps",children:[t.jsxs("div",{className:"task-token-stats-panel__timestamp-row",children:[t.jsx("dt",{children:"First used"}),t.jsx("dd",{children:t.jsx("time",{dateTime:e.firstUsedAt,children:Rd(e.firstUsedAt)})})]}),t.jsxs("div",{className:"task-token-stats-panel__timestamp-row",children:[t.jsx("dt",{children:"Last used"}),t.jsx("dd",{children:t.jsx("time",{dateTime:e.lastUsedAt,children:Rd(e.lastUsedAt)})})]})]})]}):t.jsx("div",{className:"task-token-stats-panel__empty",role:"status",children:"No token usage recorded for this task yet."})]})]})}const _v=/^In-review stall surfaced \[([^\]]+)\]/;function e$(e,n){if(!e.log?.length)return;const s=[...e.log].reverse();for(const[a,r]of s.entries()){const o=r.action.match(_v);if(!(!o||o[1]!==n))return{entry:r,reversedIndex:a,code:n}}}const Em=new Set(["planning","researching","executing","finalizing","merging","merging-fix"]),df={p:({children:e,...n})=>t.jsx("p",{...n,children:Ws(e)}),li:({children:e,...n})=>t.jsx("li",{...n,children:Ws(e)}),code:({children:e,...n})=>{const s=typeof e=="string"?e:ga.Children.toArray(e).join(""),a=ks(s);return a.length===1&&typeof a[0]=="string"?t.jsx("code",{...n,children:e}):t.jsx("code",{...n,children:a})}};function t$(e){let n=null;for(const s of e){if(s.agent!=="executor"||s.type!=="text")continue;const a=s.text.match(/^Executor using model: (.+?)\/(.+)$/);a&&(n={provider:a[1],modelId:a[2]})}return n}function n$(e){let n=null;for(const s of e){if(s.agent!=="reviewer"||s.type!=="text")continue;const a=s.text.match(/^Reviewer using model: (.+?)\/(.+)$/);a&&(n={provider:a[1],modelId:a[2]})}return n}function uf(e){return(e.title??"").trim().length>0?!0:!!(e.description??"").split(/\r?\n/).map(s=>s.trim()).find(s=>s.length>0)}function Mv(e){const n=e?.runtimeConfig??void 0,s=typeof n?.model=="string"?n.model.trim():"";if(s){const o=s.indexOf("/");if(o>0&&o<s.length-1)return{provider:s.slice(0,o),modelId:s.slice(o+1)}}const a=typeof n?.modelProvider=="string"?n.modelProvider.trim():"",r=typeof n?.modelId=="string"?n.modelId.trim():"";return{provider:a||void 0,modelId:r||void 0}}function s$(e,n,s,a){const r=t$(n);if(r)return r;if(Em.has(e.status??"")||e.column==="in-progress"){const o=Mv(s);if(o.provider&&o.modelId)return o}return xb(e,a)}function i$(e,n,s,a){const r=n$(n);if(r)return r;if(Em.has(e.status??"")||e.column==="in-progress"){const o=Mv(s);if(o.provider&&o.modelId)return o}return vb(e,a)}function a$(e){let n=null;for(const s of e){if(s.agent!=="triage"||s.type!=="text")continue;const a=s.text.match(/^Triage using model: (.+?)\/(.+)$/);a&&(n={provider:a[1],modelId:a[2]})}return n}function r$(e,n,s){if(e.planningModelProvider&&e.planningModelId)return{provider:e.planningModelProvider,modelId:e.planningModelId};const a=a$(n);return a||yb(e,s)}function o$(e){switch(e){case"done":return"var(--color-success)";case"in-progress":return"var(--in-progress)";case"skipped":return"var(--text-dim)";case"pending":default:return"var(--border)"}}function kl(e){const n=new Date(e),a=new Date().getTime()-n.getTime(),r=Math.floor(a/6e4),o=Math.floor(r/60),l=Math.floor(o/24);return r<1?"just now":r<60?`${r}m ago`:o<24?`${o}h ago`:l<7?`${l}d ago`:n.toLocaleDateString(void 0,{month:"short",day:"numeric"})}function l$(e){return e<1024?`${e} B`:e<1024*1024?`${(e/1024).toFixed(1)} KB`:`${(e/(1024*1024)).toFixed(1)} MB`}function Id(e,n){return e.length>n?e.slice(0,n)+"…":e}function mf(e=[],n=[]){return e.length===n.length&&e.every((s,a)=>s===n[a])}function Td(e){const n=e.indexOf("/");return!e||n===-1?null:{provider:e.slice(0,n),modelId:e.slice(n+1)}}function Pd(e){return e.trim()}function c$(e){const n=e.trim();return n.length>0?n:void 0}function Hi(e){return typeof e=="string"&&wa.includes(e)?e:_s}function qi(e){return e==="fast"?"fast":"standard"}function d$(e){const n=e?.issueUrl;return typeof n=="string"&&n.length>0?n:void 0}function u$(e){const n=e.match(/^https:\/\/github\.com\/([^/]+)\/([^/]+)\/(issues|pull)\/(\d+)(?:$|[/?#])/);if(!n)return null;const[,s,a,,r]=n;return{label:`${s}/${a}#${r}`,href:e}}function m$(e){const n=e?.findingLabel;if(typeof n=="string"&&n.length>0)return n;const s=e?.runId;return typeof s=="string"&&s.length>0?s:void 0}const h$=i.lazy(()=>Sn(()=>import("./AgentDetailView-CWyOv8HJ.js"),__vite__mapDeps([0,1,2,3,4,5,6,7])).then(e=>({default:e.AgentDetailView})));function p$(e,n={}){switch(e.sourceType){case"dashboard_ui":return{label:"Dashboard"};case"quick_chat":return{label:"Quick Chat"};case"chat_session":return{label:"Chat Session"};case"agent_heartbeat":return{label:n.sourceAgentName??e.sourceAgentId??"agent",sourceAgentId:e.sourceAgentId};case"automation":return{label:"Automation"};case"cron":return{label:"Scheduled Task"};case"workflow_step":return{label:"Workflow Step"};case"github_import":{const s=d$(e.sourceMetadata),a=s?u$(s):null;return{label:"GitHub Import",contextInfo:s?a?.label??"Open issue":void 0,contextHref:s,contextInfoFull:s}}case"research":{const s=m$(e.sourceMetadata);return{label:"Research",contextInfo:s,contextInfoFull:s}}case"task_refine":return{label:"Refinement",parentTaskId:e.sourceParentTaskId};case"task_duplicate":return{label:"Duplicate",parentTaskId:e.sourceParentTaskId};case"cli":return{label:"CLI"};case"api":return{label:"API"};case"recovery":return{label:"Recovery"};case"unknown":default:return null}}const $d=200,f$=new Set(["triage","todo"]),g$=new Set(["triage","todo","in-progress","in-review"]);function Av({task:e,projectId:n,tasks:s=[],onOpenDetail:a,onMoveTask:r,onDeleteTask:o,onMergeTask:l,onRetryTask:c,onResetTask:d,onDuplicateTask:u,onTaskUpdated:h,addToast:m,prAuthAvailable:f,initialTab:p="definition",mobileHeaderMode:g="close",embedded:w=!1,onRequestClose:v}){const[b,y]=i.useState(p),[j,S]=i.useState(()=>"prompt"in e?e:null),[C,x]=i.useState(()=>!("prompt"in e));i.useEffect(()=>{if("prompt"in e){S(e),x(!1);return}let J=!1;return x(!0),S(null),Ba(e.id,n).then(Re=>{J||(S(Re),x(!1))}).catch(()=>{J||x(!1)}),()=>{J=!0}},[e.id,n]);const k=j?{...j,...e,prompt:j.prompt,log:j.log,githubTracking:e.githubTracking??j.githubTracking}:{...e,prompt:""},R=e.status==="failed"||e.status==="stuck-killed"||e.status==="planning"||e.status==="needs-replan"||(e.stuckKillCount??0)>0||(e.recoveryRetryCount??0)>0||!!e.nextRecoveryAt,[O,E]=i.useState(null),[_,G]=i.useState(null),H=p$(k,{sourceAgentName:O?.name});i.useEffect(()=>{y(p)},[p]),i.useEffect(()=>{L(!1)},[e.id]);const[A,P]=i.useState("activity"),[q,Y]=i.useState(null),[ge,L]=i.useState(!1),[M,$]=i.useState(e.attachments||[]),[D,N]=i.useState(!1),[W,de]=i.useState(e.dependencies||[]),[me,Ne]=i.useState(!1),[ve,Me]=i.useState(""),[ie,ye]=i.useState(null),[Z,fe]=i.useState([]),[Q,F]=i.useState(!1),[X,re]=i.useState(!1),[U,be]=i.useState(!1),[Ue,se]=i.useState(!1),[Ve,Le]=i.useState(!1),[ct,Ke]=i.useState(k.prompt||""),[oe,Te]=i.useState(""),[Fe,mt]=i.useState(!1);i.useEffect(()=>{if(b!=="logs"||A!=="activity"){Y(null);return}if(!q)return;const J=es.current?.querySelector('[data-stall-highlight="true"]');J&&typeof J.scrollIntoView=="function"&&J.scrollIntoView({block:"nearest",behavior:"smooth"})},[b,A,q]);const[We,he]=i.useState(""),[pe,De]=i.useState(!1),[ut,ht]=i.useState(!1),[et,vt]=i.useState(e.title||""),[Oe,tt]=i.useState(e.description||""),[ft,Mt]=i.useState(e.dependencies||[]),[yt,Ge]=i.useState(e.branch??""),[K,ue]=i.useState(e.baseBranch??""),[ot,xe]=i.useState(""),[dt,Je]=i.useState(""),[ke,nt]=i.useState(""),[bt,kt]=i.useState(""),[wt,At]=i.useState("default"),[Ft,ln]=i.useState(void 0),[Vt,hn]=i.useState(_s),[un,pn]=i.useState(e.nodeId),[an,Wt]=i.useState(qi(e.executionMode)),[gn,cn]=i.useState(""),[tn,Yt]=i.useState(e.enabledWorkflowSteps||[]),[Qt,Kt]=i.useState(e.sourceIssue?.provider??""),[Jt,rn]=i.useState(e.sourceIssue?.repository??""),[qt,we]=i.useState(e.sourceIssue?.externalIssueId??""),[ze,rt]=i.useState(e.sourceIssue?.url??""),[He,Ae]=i.useState([]),[pt,Ct]=i.useState(!1),[Tt,Gt]=i.useState(Hi(e.priority)),[nn,Ht]=i.useState(!1),[on,ae]=i.useState(qi(e.executionMode)),[le,Qe]=i.useState(!1),xt=i.useRef(!1),[zt,sn]=i.useState(!1),[xn,$n]=i.useState(!1),[wn,zn]=i.useState(!1),[ce,ee]=i.useState(!1),[Se,qe]=i.useState(e.githubTracking?.repoOverride??""),[z,_e]=i.useState(null),[Rt,Ot]=i.useState(null),[Lt,fn]=i.useState(!1),kn=i.useRef(null),es=i.useRef(null),ms=i.useRef(null),Gn=i.useRef(null),{getSlotsForId:hs}=Ub(n),Bt=hs("task-detail-tab").map((J,Re)=>({entry:J,tabId:`plugin-${J.pluginId}-${Re}`})),Bn=typeof b=="string"&&b.startsWith("plugin-")?Bt.find(J=>J.tabId===b)??null:null;i.useEffect(()=>(xt.current=!0,()=>{xt.current=!1}),[]);const[En,bs]=i.useState(void 0),[$s,ss]=i.useState(null),[Un,Kn]=i.useState([]),[Ms,xs]=i.useState(!1),[As,vs]=i.useState(e.enabledWorkflowSteps||[]),te=e.column==="in-progress"||Em.has(e.status);i.useEffect(()=>{vt(e.title||""),tt(e.description||""),Ge(e.branch??""),ue(e.baseBranch??""),Kt(e.sourceIssue?.provider??""),rn(e.sourceIssue?.repository??""),we(e.sourceIssue?.externalIssueId??""),rt(e.sourceIssue?.url??""),Wt(qi(e.executionMode)),zn(!1),ee(!1),qe(k.githubTracking?.repoOverride??""),_e(null),Ot(null),ht(!1)},[e.id,e.title,e.description,e.branch,e.baseBranch,e.sourceIssue,e.executionMode,k.githubTracking]),i.useEffect(()=>{vs(e.enabledWorkflowSteps||[])},[e.id,e.enabledWorkflowSteps]),i.useEffect(()=>{Gt(Hi(e.priority))},[e.id,e.priority]),i.useEffect(()=>{ae(qi(e.executionMode))},[e.id,e.executionMode]),i.useEffect(()=>{z!==null&&k.githubTracking?.enabled===!0===z&&_e(null)},[z,k.githubTracking?.enabled]),i.useEffect(()=>{let J=!1;return Cc(n).then(Re=>{J||bs(Re)}).catch(()=>{}),Qi().then(Re=>{J||ss(Re)}).catch(()=>{J||ss(null)}),()=>{J=!0}},[n]),i.useEffect(()=>{if(b!=="workflow")return;let J=!1;return xs(!0),f1(e.id,n).then(Re=>{J||Kn(Re)}).catch(Re=>{J||m(`Failed to load workflow results: ${Ie(Re)}`,"error")}).finally(()=>{J||xs(!1)}),()=>{J=!0}},[b,e.id,n,m]),i.useEffect(()=>{if(b!=="workflow")return;const J=n?`?projectId=${encodeURIComponent(n)}`:"",Re=Nt=>{try{const Ut=JSON.parse(Nt.data);Ut.id===e.id&&Array.isArray(Ut.workflowStepResults)&&Kn(Ut.workflowStepResults)}catch{}};return fi(`/api/events${J}`,{events:{"task:updated":Re}})},[b,e.id,n]),i.useEffect(()=>{me||Me("")},[me]),i.useEffect(()=>{if(!e.assignedAgentId){ye(null);return}const J=Z.find(Nt=>Nt.id===e.assignedAgentId);if(J){ye(J);return}let Re=!1;return gu(e.assignedAgentId,n).then(Nt=>{Re||ye(Nt)}).catch(()=>{Re||ye(null)}),()=>{Re=!0}},[e.assignedAgentId,n,Z]),i.useEffect(()=>{if(!e.sourceAgentId){E(null);return}const J=Z.find(Nt=>Nt.id===e.sourceAgentId);if(J){E(J);return}let Re=!1;return Promise.resolve(gu(e.sourceAgentId,n)).then(Nt=>{Re||E(Nt??null)}).catch(()=>{Re||E(null)}),()=>{Re=!0}},[e.sourceAgentId,n,Z]),i.useEffect(()=>{F(!1)},[e.id]),i.useEffect(()=>{if(!(zt||xn))return;const Re=Nt=>{const Ut=Nt.target,Rn=kn.current?.contains(Ut),Mi=Gn.current?.contains(Ut);!Rn&&zt&&sn(!1),!Mi&&xn&&$n(!1)};return document.addEventListener("mousedown",Re),()=>document.removeEventListener("mousedown",Re)},[zt,xn]),i.useEffect(()=>{if(!(zt||xn))return;const Re=Nt=>{Nt.key==="Escape"&&(Nt.stopPropagation(),zt&&sn(!1),xn&&$n(!1))};return document.addEventListener("keydown",Re),()=>document.removeEventListener("keydown",Re)},[zt,xn]),i.useEffect(()=>{Le(!1),Ke(k.prompt||""),Te("")},[e.id,k.prompt]);const Ee=f$.has(e.column)&&!pt,T=g$.has(e.column)&&!pt,je=z??k.githubTracking?.enabled===!0,Pe=k.githubTracking?.issue,st=C&&typeof e.githubTracking>"u",gt=uf(e),Et=T&&!Pe&&!st&&(!je||Lt&&k.githubTracking?.enabled!==!0),Pt=T||je||!!Pe,dn=st?"Loading":Pe?"Linked":je?"Enabled":"Disabled",Nn=!Pe&&(Lt||st),Hn=Cv(En??null,$s),ne=Se.trim(),Be=i.useCallback(async()=>{if(!T||Lt)return;const J=!je;_e(J),fn(!0);try{const Re=await Ls(e.id,{githubTracking:{enabled:J}},n);h?.(Re)}catch(Re){_e(k.githubTracking?.enabled===!0),m(`Failed to update ${e.id}: ${Ie(Re)}`,"error")}finally{xt.current&&fn(!1)}},[m,T,je,Lt,h,n,k.githubTracking?.enabled,e.id]),Xe=i.useCallback(async()=>{if(!(!T||Lt)){if(ne.length>0&&!Sc.test(ne)){Ot("Repository override must be in owner/repo format");return}Ot(null),fn(!0);try{const J=await Ls(e.id,{githubTracking:{repoOverride:ne.length>0?ne:null}},n);h?.(J)}catch(J){m(`Failed to update ${e.id}: ${Ie(J)}`,"error")}finally{xt.current&&fn(!1)}}},[m,T,ne,Lt,h,n,e.id]),Dt=i.useCallback(async()=>{if(!(!je||Pe||Lt)){if(!uf(e)){m("Add a title before creating a tracking issue","info");return}fn(!0);try{const J=await Ls(e.id,{githubTracking:{enabled:!0}},n);h?.(J),m("Requested GitHub tracking issue creation","info")}catch(J){m(`Failed to update ${e.id}: ${Ie(J)}`,"error")}finally{xt.current&&fn(!1)}}},[m,Pe,je,Lt,h,n,e]),Xt=i.useCallback(()=>{if(!Ee)return;ht(!0),vt(e.title||""),tt(e.description||""),Mt(e.dependencies||[]),Ge(e.branch??""),ue(e.baseBranch??"");const J=e.modelProvider&&e.modelId?`${e.modelProvider}/${e.modelId}`:"",Re=e.validatorModelProvider&&e.validatorModelId?`${e.validatorModelProvider}/${e.validatorModelId}`:"",Nt=e.planningModelProvider&&e.planningModelId?`${e.planningModelProvider}/${e.planningModelId}`:"";xe(J),Je(Re),nt(Nt),kt(e.thinkingLevel??""),pn(e.nodeId),At(J||Re||Nt?"custom":"default"),cn(""),Yt(e.enabledWorkflowSteps||[]),Wt(qi(e.executionMode)),Kt(e.sourceIssue?.provider??""),rn(e.sourceIssue?.repository??""),we(e.sourceIssue?.externalIssueId??""),rt(e.sourceIssue?.url??""),Ae([]),ln(e.reviewLevel),hn(Hi(e.priority))},[Ee,e]),mn=i.useCallback(()=>{ht(!1),vt(e.title||""),tt(e.description||""),Mt(e.dependencies||[]),Ge(e.branch??""),ue(e.baseBranch??""),pn(e.nodeId),Kt(e.sourceIssue?.provider??""),rn(e.sourceIssue?.repository??""),we(e.sourceIssue?.externalIssueId??""),rt(e.sourceIssue?.url??""),hn(Hi(e.priority)),Wt(qi(e.executionMode)),He.forEach(J=>URL.revokeObjectURL(J.previewUrl)),Ae([])},[e.title,e.description,e.dependencies,e.nodeId,e.priority,e.executionMode,He]),[qn,Dn]=i.useState("idle"),ts=i.useRef(null),Vn=i.useRef(0),os=i.useCallback(J=>{const Re={},Nt=et.trim(),Ut=Oe.trim();Nt&&Nt!==(e.title??"")&&(Re.title=Nt),J&&Ut&&Ut!==(e.description??"")&&(Re.description=Ut),mf(ft,e.dependencies??[])||(Re.dependencies=ft),mf(tn,e.enabledWorkflowSteps??[])||(Re.enabledWorkflowSteps=tn);const Rn=yt.trim()||null,Mi=e.branch??null;Rn!==Mi&&(Re.branch=Rn);const Lc=K.trim()||null,Oc=e.baseBranch??null;Lc!==Oc&&(Re.baseBranch=Lc);const Tm=Td(ot),_y=e.modelProvider&&e.modelId?`${e.modelProvider}/${e.modelId}`:"";ot!==_y&&(Re.modelProvider=Tm?.provider??null,Re.modelId=Tm?.modelId??null);const Pm=Td(dt),My=e.validatorModelProvider&&e.validatorModelId?`${e.validatorModelProvider}/${e.validatorModelId}`:"";dt!==My&&(Re.validatorModelProvider=Pm?.provider??null,Re.validatorModelId=Pm?.modelId??null);const $m=Td(ke),Ay=e.planningModelProvider&&e.planningModelId?`${e.planningModelProvider}/${e.planningModelId}`:"";ke!==Ay&&(Re.planningModelProvider=$m?.provider??null,Re.planningModelId=$m?.modelId??null);const Ry=e.thinkingLevel??"";bt!==Ry&&(Re.thinkingLevel=bt!==""?bt:null),(e.nodeId??void 0)!==un&&(Re.nodeId=un??null),Ft!==e.reviewLevel&&(Re.reviewLevel=Ft),Vt!==Hi(e.priority)&&(Re.priority=Vt),an!==qi(e.executionMode)&&(Re.executionMode=an==="fast"?"fast":null);const Fc=Pd(Qt),zc=Pd(Jt),il=Pd(qt),Bc=c$(ze);if(Fc.length===0&&zc.length===0&&il.length===0&&!Bc)e.sourceIssue&&(Re.sourceIssue=null);else{if(!Fc||!zc||!il)return{updates:null,error:"Source issue provider, repository, and issue identifier are required"};const Iy=Number.parseInt(il,10),Uc=e.sourceIssue?.issueNumber??Iy;if(!Number.isFinite(Uc)||Uc<=0)return{updates:null,error:"Source issue identifier must be numeric for new metadata"};const lr={provider:Fc,repository:zc,externalIssueId:il,issueNumber:Uc,...Bc?{url:Bc}:{}},cr=e.sourceIssue;(!cr||cr.provider!==lr.provider||cr.repository!==lr.repository||cr.externalIssueId!==lr.externalIssueId||cr.issueNumber!==lr.issueNumber||(cr.url??void 0)!==lr.url)&&(Re.sourceIssue=lr)}return{updates:Re,error:null}},[K,yt,ft,Oe,an,ot,un,ke,Vt,Ft,tn,qt,Qt,Jt,ze,bt,et,dt,e]),ns=i.useCallback(async J=>{const{updates:Re,error:Nt}=os(J);if(!Re)return Dn("error"),Nt&&m(`Failed to update ${e.id}: ${Nt}`,"error"),!1;if(Object.keys(Re).length===0)return!0;const Ut=++Vn.current;Ct(!0),Dn("saving");try{const Rn=await Ls(e.id,Re,n);return Ut!==Vn.current?void 0:(h?.(Rn),Dn("saved"),!0)}catch(Rn){return Ut===Vn.current&&(Dn("error"),m(`Failed to update ${e.id}: ${Ie(Rn)}`,"error")),!1}finally{xt.current&&Ut===Vn.current&&Ct(!1)}},[m,os,h,n,e.id]),ja=i.useCallback(async J=>{await ns(!0)},[ns]),Na=i.useCallback(async()=>{await ns(!0)&&(m(`Updated ${e.id}`,"success"),xt.current&&ht(!1))},[m,ns,e.id]);i.useEffect(()=>{if(ut)return ts.current&&clearTimeout(ts.current),ts.current=setTimeout(()=>{ns(!1)},700),()=>{ts.current&&(clearTimeout(ts.current),ts.current=null)}},[ut,et,ft,yt,K,ot,dt,ke,bt,un,Ft,Vt,an,tn,Qt,Jt,qt,ze,ns]);const zi=i.useCallback(async J=>{const Re=Hi(J),Nt=Hi(e.priority);if(Re===Nt){Gt(Nt);return}const Ut=Tt;Gt(Re),Ht(!0);try{const Rn=await Ls(e.id,{priority:Re},n);Gt(Hi(Rn.priority)),h?.(Rn),m(`Priority updated to ${Hi(Rn.priority)}`,"success")}catch(Rn){Gt(Ut),m(`Failed to update ${e.id}: ${Ie(Rn)}`,"error")}finally{xt.current&&Ht(!1)}},[e.id,e.priority,n,Tt,h,m]),Kr=i.useCallback(async()=>{const Re=qi(e.executionMode)==="fast"?"standard":"fast",Nt=on;ae(Re),Qe(!0);try{const Ut=await Ls(e.id,{executionMode:Re==="fast"?"fast":null},n),Rn=qi(Ut.executionMode);ae(Rn),h?.(Ut),m(`Execution mode updated to ${Rn}`,"success")}catch(Ut){ae(Nt),m(`Failed to update ${e.id}: ${Ie(Ut)}`,"error")}finally{xt.current&&Qe(!1)}},[e.id,e.executionMode,n,on,h,m]),Us=i.useCallback(J=>{ut&&(J.key==="Escape"?(J.preventDefault(),mn()):J.key==="Enter"&&(J.ctrlKey||J.metaKey)&&(J.preventDefault(),Na()))},[ut,mn,Na]);i.useEffect(()=>{if(ut)return document.addEventListener("keydown",Us),()=>document.removeEventListener("keydown",Us)},[ut,Us]);const Bi=i.useRef(null),{nodes:Qa}=_c(),{confirm:ls}=ti(),Jr=i.useCallback(async()=>{if(!(!Ee||!Pe||Lt||!await ls({title:"Unlink GitHub issue?",message:"This stops Fusion from syncing with the linked GitHub issue. The issue itself will not be modified.",confirmLabel:"Unlink",danger:!0}))){fn(!0);try{const Re=await Ls(e.id,{githubTracking:{issue:null}},n);h?.(Re),m("GitHub issue unlinked","success")}catch(Re){m(`Failed to update ${e.id}: ${Ie(Re)}`,"error")}finally{xt.current&&fn(!1)}}},[m,Ee,ls,Pe,Lt,h,n,e.id]),{entries:ta,loading:Js,loadMore:gi,hasMore:na,total:Sa,loadingMore:bi}=vv(e.id,b==="logs"&&A==="agent-log",n),_n=i.useCallback(()=>{v?.()},[v]);i.useEffect(()=>{if(w)return;const J=Re=>{Re.key==="Escape"&&!ut&&_n()};return document.addEventListener("keydown",J),()=>document.removeEventListener("keydown",J)},[w,_n,ut]);const Ca=i.useCallback(async J=>{try{const Re=e.steps.some(Rn=>Rn.status!=="pending"),Nt=(J==="todo"||J==="triage")&&Re;let Ut;if(Nt){if(await ls({title:"Preserve Progress?",message:"This task has completed steps. Keep progress before moving?",confirmLabel:"Keep Progress",cancelLabel:"Reset Progress"}))Ut={preserveProgress:!0};else if(!await ls({title:"Reset Progress?",message:"Reset all step progress before moving this task?",confirmLabel:"Reset Progress",cancelLabel:"Cancel Move",danger:!0}))return}await r(e.id,J,Ut),_n(),m(`Moved to ${ds[J]}`,"success")}catch(Re){m(Ie(Re),"error")}},[e.id,e.steps,r,_n,m,ls]),sa=i.useCallback(async()=>{if(!await ls({title:"Delete Task",message:`Delete ${e.id}?`,danger:!0}))return;const Re=e.githubTracking?.enabled===!0?e.githubTracking.issue:void 0;let Nt;if(Re?.owner&&Re.repo&&Re.number){const Ut=`${Re.owner}/${Re.repo}#${Re.number}`;await ls({title:"Linked GitHub Issue",message:`Choose what to do with ${Ut} when deleting ${e.id}.
687
-
688
- Close the issue?`,confirmLabel:"Close Issue",cancelLabel:"More Options"})?Nt="close":Nt=await ls({title:"Delete Linked GitHub Issue",message:`Delete ${Ut} on GitHub, or leave it unchanged?`,confirmLabel:"Delete Issue",cancelLabel:"Leave Unchanged",danger:!0})?"delete":"leave"}try{Nt?await o(e.id,{githubIssueAction:Nt}):await o(e.id),_n();const Ut=Re?.owner&&Re.repo&&Re.number&&Nt?` and ${Nt==="close"?"closed":Nt==="delete"?"deleted":"left"} issue ${Re.owner}/${Re.repo}#${Re.number}`:"";m(`Deleted ${e.id}${Ut}`,"info")}catch(Ut){const Rn=im(Ut);if(!Rn||Rn.dependentIds.length===0){m(Ie(Ut),"error");return}const Mi=Rn.dependentIds.join(", ");if(!await ls({title:"Force Delete Task",message:`${e.id} is a dependency of ${Mi}.
689
-
690
- Delete anyway by removing these dependency references first?`,danger:!0}))return;try{await o(e.id,{removeDependencyReferences:!0,githubIssueAction:Nt}),_n(),m(`Deleted ${e.id} after removing dependency references`,"info")}catch(Oc){m(Ie(Oc),"error")}}},[e.githubTracking?.enabled,e.githubTracking?.issue,e.id,o,_n,m,ls]),ia=i.useCallback(async()=>{await ls({title:"Merge Task",message:`Merge ${e.id} into the current branch?`})&&(_n(),m(`Merging ${e.id}...`,"info"),l(e.id).then(Re=>{const Nt=Re.merged?`Merged ${e.id} (branch: ${Re.branch})`:`Closed ${e.id} (${Re.error||"no branch to merge"})`;m(Nt,"success")}).catch(Re=>{m(Ie(Re),"error")}))},[e.id,l,_n,m,ls]),Xa=i.useCallback(()=>{c&&(_n(),c(e.id).then(()=>{m(`Retried ${e.id}`,"success")}).catch(J=>{m(Ie(J),"error")}))},[e.id,c,_n,m]),Ui=i.useCallback(()=>{d&&window.confirm(`This will erase all progress for ${e.id} and start the task from scratch. Continue?`)&&(_n(),d(e.id).then(()=>{m(`Reset ${e.id} — fresh run will be allocated`,"success")}).catch(J=>{m(Ie(J),"error")}))},[e.id,d,_n,m]),aa=i.useCallback(async()=>{if(!(!u||!await ls({title:"Duplicate Task",message:`Duplicate ${e.id}? This will create a new task in Triage with the same description and prompt.`})))try{const Re=await u(e.id);_n(),m(`Duplicated ${e.id} → ${Re.id}`,"success")}catch(Re){m(Ie(Re),"error")}},[e.id,u,_n,m,ls]),ra=i.useCallback(async()=>{try{e.paused?(await Cb(e.id,n),m(`Unpaused ${e.id}`,"success")):(await Sb(e.id,n),m(`Paused ${e.id}`,"success")),_n()}catch(J){m(Ie(J),"error")}},[e.id,e.paused,_n,m]),xi=i.useCallback(async()=>{try{await kN(e.id,n),m(`Plan approved — ${e.id} moved to Todo`,"success"),_n()}catch(J){m(Ie(J),"error")}},[e.id,_n,m]),Za=i.useCallback(async()=>{if(await ls({title:"Reject Plan",message:"Reject this plan? The specification will be discarded and regenerated.",danger:!0}))try{await jN(e.id,n),m(`Plan rejected — ${e.id} returned to Planning for replanning`,"info"),_n()}catch(Re){m(Ie(Re),"error")}},[e.id,_n,m,ls]),Ea=i.useCallback(async()=>{if(await ls({title:"Rebuild Plan",message:"Rebuild the plan for this task? The task will move to planning for replanning."}))try{await PN(e.id,n),_n(),m(`Replanning ${e.id}...`,"info")}catch(Re){m(Ie(Re),"error")}},[e.id,n,_n,m,ls]),_a=i.useCallback(()=>{mt(!0),he("")},[]),Hs=i.useCallback(()=>{sn(!1),$n(!1)},[]),Ci=i.useCallback(J=>{Hs(),Ca(J)},[Hs]),ni=i.useCallback(J=>{Hs(),J()},[Hs]),er=i.useCallback(()=>{Hs(),ia()},[Hs,ia]),Ei=i.useCallback(()=>{mt(!1),he(""),De(!1)},[]),Ma=i.useCallback(async()=>{if(!We.trim()){m("Please enter feedback describing what needs refinement","error");return}if(We.length>2e3){m("Feedback must be 2000 characters or less","error");return}De(!0);try{const J=await $N(e.id,We.trim(),n);m(`Refinement task created: ${J.id}`,"success"),_n()}catch(J){m(Ie(J),"error")}finally{De(!1)}},[e.id,We,m,_n]),si=i.useCallback(async J=>{N(!0);try{const Re=await Ec(e.id,J,n);$(Nt=>[...Nt,Re]),m("Screenshot attached","success")}catch(Re){m(Ie(Re),"error")}finally{N(!1)}},[e.id,m]),tr=i.useCallback(async J=>{const Re=J.target.files?.[0];Re&&(await si(Re),Bi.current&&(Bi.current.value=""))},[si]);i.useEffect(()=>{const J=Re=>{const Nt=Re.clipboardData?.items;if(Nt)for(let Ut=0;Ut<Nt.length;Ut++){const Rn=Nt[Ut];if(Rn.type.startsWith("image/")){const Mi=Rn.getAsFile();if(Mi){Re.preventDefault(),si(Mi);return}}}};return document.addEventListener("paste",J),()=>document.removeEventListener("paste",J)},[si]);const Yr=i.useCallback(J=>{J.preventDefault()},[]),nr=i.useCallback(J=>{J.preventDefault();const Re=J.dataTransfer.files;for(let Nt=0;Nt<Re.length;Nt++){const Ut=Re[Nt];if(Ut.type.startsWith("image/")){si(Ut);return}}},[si]),oa=i.useCallback(async J=>{try{await CN(e.id,J,n),$(Re=>Re.filter(Nt=>Nt.filename!==J)),m("Attachment deleted","info")}catch(Re){m(Ie(Re),"error")}},[e.id,m]),sr=i.useCallback(async J=>{const Re=As;vs(J);try{const Nt=await Ls(e.id,{enabledWorkflowSteps:J},n);m("Workflow steps updated","success"),h?.(Nt)}catch(Nt){vs(Re),m(`Failed to update workflow steps: ${Ie(Nt)}`,"error")}},[e.id,n,As,h,m]),Qr=i.useCallback(async()=>{re(!0);try{const J=await Hr(void 0,n);fe(J),F(!0)}catch(J){m(`Failed to load agents: ${Ie(J)}`,"error"),F(!1)}finally{re(!1)}},[n,m]),Xr=i.useCallback(async J=>{try{const Re=await lh(e.id,J,n),Nt=Z.find(Ut=>Ut.id===J)??null;ye(Nt||(Ut=>Ut?.id===J?Ut:null)),F(!1),h?.(Re),m("Assigned agent updated","success")}catch(Re){m(`Failed to assign agent: ${Ie(Re)}`,"error")}},[e.id,n,Z,h,m]),ir=i.useCallback(async()=>{try{const J=await lh(e.id,null,n);ye(null),F(!1),h?.(J),m("Agent unassigned","success")}catch(J){m(`Failed to unassign agent: ${Ie(J)}`,"error")}},[e.id,n,h,m]),ar=i.useCallback(async J=>{const Re=[...W,J];de(Re);try{await Ls(e.id,{dependencies:Re},n)}catch(Nt){de(W),m(Ie(Nt),"error")}},[e.id,W,m]),rr=i.useCallback(async(J,Re)=>{J.stopPropagation();const Nt=W.filter(Ut=>Ut!==Re);de(Nt);try{await Ls(e.id,{dependencies:Nt},n)}catch(Ut){de(W),m(Ie(Ut),"error")}},[e.id,W,m]),vi=i.useCallback(async J=>{try{const Re=await Ba(J,n);a(Re)}catch{m(`Failed to load dependency ${J}`,"error")}},[a,m]),_i=i.useCallback(async J=>{be(!0);try{await Ls(k.id,{prompt:J},n),m("Spec updated","success"),j&&(j.prompt=J)}catch(Re){throw m(Ie(Re),"error"),Re}finally{be(!1)}},[k,j,m]),Aa=i.useCallback(async J=>{se(!0);try{await TN(e.id,J,n),m("AI revision requested. Task moved to planning.","success"),_n()}catch(Re){const Nt=Ie(Re);Nt.includes("done")||Nt.includes("archived")?m("Cannot request revision: Task must be in 'triage', 'todo', 'in-progress', or 'in-review' column.","error"):m(Nt,"error")}finally{se(!1)}},[e.id,m,_n]),or=i.useCallback(()=>{Le(!0),Ke(k.prompt||""),Te("")},[k.prompt]),B=i.useCallback(()=>{Le(!1),Ke(k.prompt||""),Te("")},[k.prompt]),$e=i.useCallback(async()=>{if(ct===(k.prompt||"")){B();return}Le(!1);try{await _i(ct)}catch(J){throw Le(!0),J}},[ct,k.prompt,_i,B]),Ye=i.useCallback(async()=>{oe.trim()&&await Aa(oe.trim())},[oe,Aa]),jt=i.useCallback(J=>{J.key==="Escape"?(J.preventDefault(),B()):J.key==="Enter"&&(J.ctrlKey||J.metaKey)&&(J.preventDefault(),$e())},[B,$e]),Ce=s.filter(J=>J.id!==e.id&&!W.includes(J.id)).sort((J,Re)=>{const Nt=Re.createdAt.localeCompare(J.createdAt);if(Nt!==0)return Nt;const Ut=parseInt(J.id.slice(J.id.lastIndexOf("-")+1),10)||0;return(parseInt(Re.id.slice(Re.id.lastIndexOf("-")+1),10)||0)-Ut}),It=i.useMemo(()=>rm(s),[s]).get(e.id),Ze=i.useMemo(()=>{if(!It)return[];const J=new Set(It.staleBlockedByDependentIds);return It.dependentIds.map(Re=>{const Nt=s.find(Ut=>Ut.id===Re);return{id:Re,label:Nt?.title||Nt?.description||Re,stale:J.has(Re)}})},[It,s]),it=ie?.name??e.assignedAgentId??null,$t=i.useMemo(()=>{const J=[];return k.modelProvider&&J.push(k.modelProvider),k.validatorModelProvider&&!J.includes(k.validatorModelProvider)&&J.push(k.validatorModelProvider),k.planningModelProvider&&!J.includes(k.planningModelProvider)&&J.push(k.planningModelProvider),J},[k.modelProvider,k.validatorModelProvider,k.planningModelProvider]),Pn=hu[e.column]||[],ii=["todo","in-progress"],ai=e.column==="in-review"?ii:Pn,An=ai[0],Jn=ai.slice(1),Zt=Jn.length>0,ps=i.useCallback(()=>{sn(!1),ms.current?.focus()},[]),Ds=i.useCallback(J=>{if(!Zt){An&&Ci(An);return}const Re=J.currentTarget.querySelector(".detail-move-btn__arrow");if(!!(J.target instanceof Element&&J.target.closest(".detail-move-btn__arrow")||Re&&J.clientX>0&&J.clientX>=Re.getBoundingClientRect().left)){sn(Ut=>!Ut),$n(!1);return}An&&Ci(An)},[Zt,An,Ci]),ri=i.useCallback(J=>{!Zt||!(J.key==="ArrowDown"||J.altKey&&J.key==="ArrowDown")||(J.preventDefault(),sn(!0),$n(!1))},[Zt]),la=i.useCallback(J=>{J.key==="Escape"&&(J.preventDefault(),J.stopPropagation(),ps())},[ps]);i.useEffect(()=>{if(!zt)return;kn.current?.querySelector(".detail-move-menu-item")?.focus()},[zt]);const Zr={"creating-pr":"Creating PR…","awaiting-pr-checks":"Awaiting PR checks","merging-pr":"Merging PR…","merging-fix":"Merging fixes…"},Dc=e.status?Zr[e.status]:void 0,Cy=En?.mergeStrategy??"direct",Ey=En?.autoMerge??!1,Im=Cy==="pull-request"&&!Ey;let sl="Merge & Close";return Im&&!Dc&&(e.prInfo?e.prInfo.status==="open"?sl="Check PR Status":e.prInfo.status==="merged"&&(sl="Finish & Close"):sl="Start PR Review"),t.jsxs("div",{className:w?"task-detail-content task-detail-content--embedded":"task-detail-content",onDragOver:Yr,onDrop:nr,children:[t.jsxs("div",{className:"modal-header",children:[t.jsxs("div",{className:"detail-title-row",children:[t.jsx("span",{className:"detail-id",children:e.id}),t.jsx("span",{className:`detail-column-badge badge-${e.column}`,children:ds[e.column]})]}),t.jsxs("div",{className:"modal-header-actions",children:[!ut&&Ee&&t.jsx("button",{className:"modal-edit-btn",onClick:Xt,title:"Edit task","aria-label":"Edit task",children:t.jsx(Os,{size:14})}),!w&&g==="back"&&t.jsxs("button",{className:"modal-close task-detail-mobile-back",onClick:_n,"aria-label":"Back to task list",type:"button",children:[t.jsx(Ka,{"aria-hidden":"true"}),t.jsx("span",{children:"Back"})]}),!w&&g!=="back"&&t.jsx("button",{className:"modal-close",onClick:_n,"aria-label":"Close",type:"button",children:"×"})]})]}),t.jsxs("div",{className:`detail-body${b==="logs"&&A==="agent-log"&&!ut?" detail-body--agent-log":""}`,children:[ut?t.jsx("div",{className:"modal-edit-form",children:t.jsx(Ev,{mode:"edit",title:et,onTitleChange:vt,description:Oe,onDescriptionChange:tt,dependencies:ft,onDependenciesChange:Mt,branch:yt,onBranchChange:Ge,baseBranch:K,onBaseBranchChange:ue,executorModel:ot,onExecutorModelChange:xe,validatorModel:dt,onValidatorModelChange:Je,planningModel:ke,onPlanningModelChange:nt,thinkingLevel:bt,onThinkingLevelChange:kt,presetMode:wt,onPresetModeChange:At,selectedPresetId:gn,onSelectedPresetIdChange:cn,selectedWorkflowSteps:tn,onWorkflowStepsChange:Yt,pendingImages:He,onImagesChange:Ae,tasks:s.filter(J=>J.id!==e.id),projectId:n,disabled:pt,addToast:m,isActive:ut,onAutoSaveDescription:ja,reviewLevel:Ft,onReviewLevelChange:ln,priority:Vt,onPriorityChange:hn,nodeId:un,onNodeIdChange:pn,nodeOptions:Qa,nodeOverrideDisabled:te,nodeOverrideDisabledReason:te?"Execution node override is locked while a task is active/in progress.":void 0,executionMode:an,onExecutionModeChange:Wt,renderBelowModelConfiguration:t.jsxs("div",{className:"form-group detail-source-edit-group",children:[t.jsx("label",{children:"Source Issue"}),t.jsxs("div",{className:"detail-source-edit-grid",children:[t.jsx("input",{type:"text",className:"modal-edit-input",placeholder:"Provider (e.g. github)",value:Qt,onChange:J=>Kt(J.target.value),disabled:pt,"data-testid":"task-source-provider-input"}),t.jsx("input",{type:"text",className:"modal-edit-input",placeholder:"Repository (e.g. owner/repo)",value:Jt,onChange:J=>rn(J.target.value),disabled:pt,"data-testid":"task-source-repository-input"}),t.jsx("input",{type:"text",className:"modal-edit-input",placeholder:"Issue identifier",value:qt,onChange:J=>we(J.target.value),disabled:pt,"data-testid":"task-source-external-id-input"}),t.jsx("input",{type:"url",className:"modal-edit-input",placeholder:"Issue URL",value:ze,onChange:J=>rt(J.target.value),disabled:pt,"data-testid":"task-source-url-input"})]}),t.jsx("small",{children:"Leave all fields empty to clear source issue metadata."})]})})}):t.jsxs(t.Fragment,{children:[(()=>{const J=e.title||e.description||e.id,Re=!ge&&J.length>$d;return t.jsxs(t.Fragment,{children:[t.jsx("h2",{className:"detail-title",children:Re?J.slice(0,$d)+"…":J}),J.length>$d&&t.jsx("button",{className:"detail-description-toggle",onClick:()=>L(!ge),children:ge?"Show less":"Show more"})]})})(),t.jsxs("div",{className:"detail-meta",children:[t.jsxs("div",{className:"detail-meta-inline-controls","data-testid":"detail-meta-inline-controls",children:[t.jsxs("label",{className:`card-priority-badge card-priority-badge--${Tt} detail-priority-chip ${nn?"detail-priority-chip--saving":""}`,children:[t.jsx("span",{children:"Priority:"}),t.jsx("select",{className:"detail-priority-select",value:Tt,onChange:J=>{zi(J.target.value)},disabled:nn,"aria-label":"Task priority",children:wa.map(J=>t.jsx("option",{value:J,children:J},J))})]}),t.jsxs("button",{type:"button",className:`btn btn-sm detail-execution-mode-toggle ${on==="fast"?"detail-execution-mode-toggle--fast":""} ${le?"detail-execution-mode-toggle--saving":""}`,onClick:()=>{Kr()},disabled:le,"aria-label":`Execution mode: ${on}`,"aria-pressed":on==="fast",children:[t.jsx(as,{"aria-hidden":"true"}),t.jsx("span",{children:on==="fast"?"Fast":"Standard"})]})]}),H&&t.jsxs("div",{className:"detail-provenance",children:[t.jsx(Is,{"aria-hidden":"true"}),t.jsxs("span",{children:[k.sourceType==="agent_heartbeat"?t.jsxs(t.Fragment,{children:["Created by"," ",H.sourceAgentId?t.jsx("button",{type:"button",className:"detail-provenance-link",onClick:()=>G(H.sourceAgentId),children:H.label}):H.label]}):t.jsxs(t.Fragment,{children:["Created via ",H.label]}),H.parentTaskId&&t.jsxs(t.Fragment,{children:[" ","of"," ",t.jsx("button",{type:"button",className:"detail-provenance-link",onClick:()=>vi(H.parentTaskId),children:H.parentTaskId})]}),H.contextInfo?t.jsxs(t.Fragment,{children:[" (",H.contextHref?t.jsx("a",{className:"detail-provenance-link detail-provenance-context",href:H.contextHref,target:"_blank",rel:"noopener noreferrer",title:H.contextInfoFull,children:H.contextInfo}):t.jsx("span",{className:"detail-provenance-context",title:H.contextInfoFull,children:H.contextInfo}),")"]}):""]})]}),(e.prInfo?.number||e.mergeDetails?.prNumber)&&t.jsxs("div",{className:"detail-provenance detail-pr-link-row",children:[t.jsx(Is,{"aria-hidden":"true"}),t.jsxs("span",{children:["PR"," ",e.prInfo?.url?t.jsxs("a",{className:"detail-provenance-link",href:e.prInfo.url,target:"_blank",rel:"noopener noreferrer",children:["#",e.prInfo.number]}):t.jsxs("span",{children:["#",e.prInfo?.number??e.mergeDetails?.prNumber]})]})]}),t.jsxs("div",{className:"detail-timestamps","aria-label":"Task timestamps",children:[t.jsxs("span",{className:"detail-timestamp-item",children:[t.jsx("span",{className:"detail-timestamp-label",children:"Created"})," ",t.jsx("time",{dateTime:e.createdAt,title:new Date(e.createdAt).toLocaleString(),children:kl(e.createdAt)})]}),t.jsx("span",{className:"detail-timestamp-separator","aria-hidden":"true",children:"·"}),t.jsxs("span",{className:"detail-timestamp-item",children:[t.jsx("span",{className:"detail-timestamp-label",children:"Updated"})," ",t.jsx("time",{dateTime:e.updatedAt,title:new Date(e.updatedAt).toLocaleString(),children:kl(e.updatedAt)})]})]})]})]}),e.status==="failed"&&e.error&&t.jsxs("div",{className:"detail-error-alert",children:[t.jsx("span",{className:"detail-error-icon",children:"⚠"}),t.jsxs("div",{className:"detail-error-content",children:[t.jsx("div",{className:"detail-error-title",children:"Task Failed"}),t.jsx("div",{className:"detail-error-message",children:e.error})]})]}),!ut&&t.jsxs(t.Fragment,{children:[t.jsxs("div",{className:"detail-tabs",children:[t.jsx("button",{className:`detail-tab${b==="definition"?" detail-tab-active":""}`,onClick:()=>y("definition"),children:"Definition"}),t.jsx("button",{className:`detail-tab${b==="logs"?" detail-tab-active":""}`,onClick:()=>y("logs"),children:"Logs"}),(e.column==="in-progress"||e.column==="in-review"||e.column==="done")&&t.jsx("button",{className:`detail-tab${b==="changes"?" detail-tab-active":""}`,onClick:()=>y("changes"),children:"Changes"}),t.jsx("button",{className:`detail-tab${b==="review"?" detail-tab-active":""}`,onClick:()=>y("review"),children:"Review"}),t.jsx("button",{className:`detail-tab${b==="comments"?" detail-tab-active":""}`,onClick:()=>y("comments"),children:"Comments"}),t.jsx("button",{className:`detail-tab${b==="documents"?" detail-tab-active":""}`,onClick:()=>y("documents"),children:"Documents"}),t.jsx("button",{className:`detail-tab${b==="model"?" detail-tab-active":""}`,onClick:()=>y("model"),children:"Model"}),t.jsx("button",{className:`detail-tab${b==="workflow"?" detail-tab-active":""}`,onClick:()=>y("workflow"),children:"Workflow"}),t.jsx("button",{className:`detail-tab${b==="stats"?" detail-tab-active":""}`,onClick:()=>y("stats"),children:"Stats"}),t.jsx("button",{className:`detail-tab${b==="routing"?" detail-tab-active":""}`,onClick:()=>y("routing"),children:"Routing"}),Bt.map(({entry:J,tabId:Re})=>t.jsx("button",{className:`detail-tab${b===Re?" detail-tab-active":""}`,onClick:()=>y(Re),children:J.slot.label},`plugin-tab-${J.pluginId}-${Re}`))]}),b==="workflow"?t.jsx("div",{className:"detail-section",children:t.jsx(HP,{taskId:e.id,results:Un,loading:Ms,enabledWorkflowSteps:As,canEdit:Ee,projectId:n,isTaskInProgress:e.column==="in-progress"&&e.status!=="paused",onWorkflowStepsChange:sr})}):b==="model"?t.jsx("div",{className:"detail-section",children:t.jsx(bP,{task:e,addToast:m,onTaskUpdated:h,settings:En})}):b==="logs"?t.jsxs("div",{className:`detail-section${A==="agent-log"?" detail-section--agent-log":""}`,children:[t.jsxs("div",{className:"log-subview-toggle",children:[t.jsx("button",{className:`log-subview-btn${A==="activity"?" log-subview-btn-active":""}`,onClick:()=>P("activity"),children:"Activity"}),t.jsx("button",{className:`log-subview-btn${A==="agent-log"?" log-subview-btn-active":""}`,onClick:()=>P("agent-log"),children:"Agent Log"})]}),A==="agent-log"?t.jsx(mP,{entries:ta,loading:Js,executorModel:s$(e,ta,ie,En),validatorModel:i$(e,ta,ie,En),planningModel:r$(e,ta,En),hasMore:na,onLoadMore:gi,loadingMore:bi,totalCount:Sa}):t.jsxs("div",{className:"detail-activity",children:[t.jsx("h4",{children:"Activity"}),k.activityLogTruncatedCount?t.jsxs("div",{className:"detail-log-truncated",children:["Showing the most recent ",k.log.length," activity entries."]}):null,k.log&&k.log.length>0?t.jsx("div",{className:"detail-activity-list",ref:es,children:(()=>{let J=!1;return[...k.log].reverse().map((Re,Nt)=>{const Ut=Re.action.match(_v),Rn=!J&&q!=null&&Ut?.[1]===q;return Rn&&(J=!0),t.jsxs("div",{className:`detail-log-entry${Rn?" detail-log-entry--stall-highlight":""}`,"data-stall-highlight":Rn?"true":void 0,children:[t.jsxs("div",{className:"detail-log-header",children:[t.jsx("span",{className:"detail-log-timestamp",children:kl(Re.timestamp)}),t.jsx("span",{className:"detail-log-action",children:Re.action})]}),Re.outcome&&t.jsx("div",{className:"detail-log-outcome",children:Re.outcome})]},Nt)})})()}):t.jsx("div",{className:"detail-log-empty",children:"(no activity)"})]})]}):b==="changes"?t.jsx(PP,{taskId:e.id,worktree:e.worktree,projectId:n,column:e.column,mergeDetails:e.mergeDetails,modifiedFiles:e.modifiedFiles}):b==="review"?t.jsx(MP,{task:e,addToast:m,projectId:n,onTaskUpdated:h}):b==="comments"?t.jsx(kP,{task:e,addToast:m,projectId:n,onTaskUpdated:h}):b==="documents"?t.jsx(QP,{taskId:e.id,addToast:m,projectId:n,onTaskUpdated:h,canEdit:Ee}):Bn?t.jsx("div",{className:"detail-section",children:t.jsx(pa,{slotId:"task-detail-tab",projectId:n,pluginIds:[Bn.entry.pluginId]})}):b==="stats"?t.jsx("div",{className:"detail-section",children:t.jsx(ZP,{tokenUsage:k.tokenUsage,loading:C,task:k})}):b==="routing"?t.jsx("div",{className:"detail-section",children:t.jsx(GP,{task:e,settings:En,addToast:m,onTaskUpdated:h})}):t.jsxs(t.Fragment,{children:[e.column==="done"&&e.summary&&t.jsxs("div",{className:"detail-section detail-summary",children:[t.jsx("h4",{children:"Summary"}),t.jsx("div",{className:"markdown-body",children:t.jsx(hi,{remarkPlugins:[pi],components:df,children:e.summary})})]}),t.jsx(RP,{task:e}),e.sourceIssue&&t.jsxs("div",{className:"detail-section detail-source-section",children:[t.jsxs("div",{className:"detail-source-header",children:[t.jsxs("div",{className:"detail-source-summary",children:[t.jsx("span",{className:"detail-source-label",children:"Source issue"}),e.sourceIssue.provider.toLowerCase()==="github"&&t.jsxs("span",{className:"detail-source-provider-badge","aria-label":"GitHub source issue",children:[t.jsx(Is,{"aria-hidden":"true"}),t.jsx("span",{children:"GitHub"})]}),e.sourceIssue.url?t.jsx("a",{className:"detail-source-link detail-source-link--summary detail-source-number",href:e.sourceIssue.url,target:"_blank",rel:"noopener noreferrer",children:`(#${e.sourceIssue.issueNumber})`}):t.jsx("span",{className:"detail-source-number",children:`(#${e.sourceIssue.issueNumber})`})]}),t.jsx("button",{type:"button",className:"detail-source-toggle","aria-expanded":wn,"aria-label":wn?"Collapse source issue details":"Expand source issue details",onClick:()=>zn(J=>!J),children:t.jsx(Wn,{size:16,className:wn?"detail-source-chevron--expanded":void 0})})]}),wn&&t.jsxs("dl",{className:"detail-source-grid",children:[t.jsxs("div",{children:[t.jsx("dt",{children:"Provider"}),t.jsx("dd",{children:e.sourceIssue.provider})]}),t.jsxs("div",{children:[t.jsx("dt",{children:"Repository"}),t.jsx("dd",{children:e.sourceIssue.repository})]}),t.jsxs("div",{children:[t.jsx("dt",{children:"Issue Identifier"}),t.jsx("dd",{children:e.sourceIssue.externalIssueId})]}),t.jsxs("div",{children:[t.jsx("dt",{children:"URL"}),t.jsx("dd",{children:e.sourceIssue.url?t.jsx("a",{className:"detail-source-link",href:e.sourceIssue.url,target:"_blank",rel:"noopener noreferrer",children:e.sourceIssue.url}):t.jsx("span",{className:"detail-source-empty",children:"(none)"})})]})]})]}),Pt&&t.jsxs("div",{className:"detail-section detail-github-tracking-section",children:[t.jsxs("div",{className:"detail-source-header",children:[t.jsxs("div",{className:"detail-source-summary",children:[t.jsx("span",{className:"detail-source-label",children:"GitHub tracking"}),t.jsxs("span",{className:"detail-source-provider-badge","aria-label":"GitHub tracking status",children:[t.jsx(Is,{"aria-hidden":"true"}),t.jsx("span",{children:dn})]}),!Pe&&t.jsx("span",{className:"detail-source-empty",children:st?"Checking tracking status":je?"Issue not yet created":"Tracking is currently disabled"})]}),Et&&t.jsx("button",{type:"button",className:"btn btn-sm btn-primary detail-github-tracking-enable","aria-label":"Enable GitHub tracking",disabled:Lt,onClick:()=>void Be(),children:"Enable"}),Nn&&t.jsxs("span",{className:"detail-github-tracking-spinner",role:"status","aria-live":"polite","aria-label":Lt?"Enabling GitHub tracking":"Loading GitHub tracking status",children:[t.jsx(St,{size:16,className:"spin","aria-hidden":"true"}),t.jsx("span",{className:"visually-hidden",children:Lt?"Enabling GitHub tracking…":"Loading GitHub tracking status…"})]}),t.jsx("button",{type:"button",className:"detail-source-toggle","aria-expanded":ce,"aria-label":ce?"Collapse GitHub tracking details":"Expand GitHub tracking details",onClick:()=>ee(J=>!J),children:t.jsx(Wn,{size:16,className:ce?"detail-source-chevron--expanded":void 0})})]}),ce&&t.jsxs("div",{className:"detail-github-tracking-content",children:[Pe&&t.jsxs("dl",{className:"detail-source-grid detail-github-tracking-grid",children:[t.jsxs("div",{children:[t.jsx("dt",{children:"Issue"}),t.jsx("dd",{children:Pe.url?t.jsx("a",{className:"detail-source-link",href:Pe.url,target:"_blank",rel:"noopener noreferrer",children:`${Pe.owner}/${Pe.repo}#${Pe.number}`}):t.jsx("span",{children:`${Pe.owner}/${Pe.repo}#${Pe.number}`})})]}),t.jsxs("div",{children:[t.jsx("dt",{children:"State"}),t.jsx("dd",{children:t.jsx("span",{className:`detail-github-issue-state ${e.issueInfo?.state==="closed"?"detail-github-issue-state--closed":"detail-github-issue-state--open"}`,children:e.issueInfo?.state??"open"})})]})]}),t.jsxs("div",{className:"detail-github-tracking-controls",children:[!Pe&&je&&t.jsxs(t.Fragment,{children:[t.jsx("button",{className:"btn btn-sm touch-target",onClick:()=>void Dt(),disabled:Lt||!gt,title:gt?void 0:"Add a title or description so a tracking issue can be created.",children:"Create tracking issue"}),!gt&&t.jsx("small",{className:"detail-github-tracking-helper",children:"Tracking issue will be created once this task has a title or description to summarize."})]}),T&&t.jsxs(t.Fragment,{children:[t.jsxs("label",{className:"checkbox-label",htmlFor:"detail-github-tracking-toggle",children:[t.jsx("input",{id:"detail-github-tracking-toggle",type:"checkbox",checked:je,disabled:Lt,onChange:()=>void Be()}),"Enable GitHub tracking"]}),t.jsxs("div",{className:"detail-github-tracking-repo-row",children:[t.jsx("input",{className:"input",value:Se,onChange:J=>{qe(J.target.value),Ot(null)},placeholder:Hn||"owner/repo"}),t.jsx("button",{className:"btn btn-sm",onClick:()=>void Xe(),disabled:Lt,children:"Save"})]}),Rt&&t.jsx("small",{className:"detail-github-tracking-error",children:Rt}),Pe&&t.jsx("button",{className:"btn btn-sm touch-target",onClick:()=>void Jr(),disabled:Lt,children:"Unlink GitHub issue"})]})]})]})]}),t.jsx("div",{className:"detail-section detail-agent-section",children:t.jsxs("div",{className:"detail-meta-row",children:[t.jsxs("div",{className:"detail-meta-left",children:[$t.length>0&&t.jsx("span",{className:"detail-provider-icons","data-testid":"detail-provider-icons",children:$t.map(J=>t.jsx(On,{provider:J,size:"sm"},J))}),t.jsxs("span",{className:"detail-meta-label",children:[t.jsx(Xn,{size:14,className:"detail-meta-label-icon"}),"Agent"]})]}),t.jsxs("div",{className:"detail-agent-actions",children:[it?t.jsxs("span",{className:"detail-agent-chip",children:[t.jsx(Xn,{size:14}),it,t.jsx("button",{className:"detail-agent-clear",onClick:()=>void ir(),title:"Unassign agent",children:t.jsx(bn,{size:12})})]}):t.jsx("button",{className:"btn btn-sm",onClick:()=>{Q?F(!1):Qr()},children:"Assign Agent"}),Q&&t.jsxs("div",{className:"agent-picker-dropdown",children:[X&&t.jsx("div",{className:"agent-picker-loading",children:"Loading agents..."}),!X&&Z.map(J=>t.jsxs("button",{className:`agent-picker-item${e.assignedAgentId===J.id?" selected":""}`,onClick:()=>void Xr(J.id),children:[t.jsx(Xn,{size:14}),t.jsx("span",{className:"agent-picker-name",children:J.name}),t.jsx("span",{className:"agent-picker-role",children:J.role})]},J.id)),!X&&Z.length===0&&t.jsx("div",{className:"agent-picker-empty",children:"No agents available"})]})]})]})}),t.jsxs("div",{className:"detail-section detail-step-progress",children:[t.jsx("h4",{children:"Progress"}),k.steps&&k.steps.length>0?t.jsxs("div",{className:"step-progress-wrapper",children:[t.jsx("div",{className:"step-progress-bar",children:k.steps.map((J,Re)=>t.jsx("div",{className:`step-progress-segment step-progress-segment--${J.status}`,"data-tooltip":`${J.name} (${J.status})`,style:{backgroundColor:o$(J.status)}},Re))}),t.jsxs("span",{className:"step-progress-label",children:[k.steps.filter(J=>J.status==="done").length,"/",k.steps.length," step",k.steps.length===1?"":"s"]})]}):t.jsx("div",{className:"step-progress-empty",children:"(no steps defined)"})]}),t.jsxs("div",{className:"detail-section",children:[!Ve&&t.jsx("div",{className:"detail-spec-edit-trigger",children:t.jsx("button",{className:"btn btn-sm",onClick:or,children:"Edit"})}),Ve?t.jsxs("div",{className:"spec-editor-edit-mode",children:[t.jsx("textarea",{className:"spec-editor-textarea",value:ct,onChange:J=>Ke(J.target.value),onKeyDown:jt,disabled:U,placeholder:"Enter task specification in Markdown...",rows:12}),t.jsxs("div",{className:"spec-editor-actions-row",children:[t.jsx("button",{className:"btn btn-sm",onClick:B,disabled:U,children:"Cancel"}),t.jsx("button",{className:"btn btn-primary btn-sm",onClick:()=>void $e(),disabled:ct===(k.prompt||"")||U,children:U?"Saving…":"Save"})]}),t.jsxs("div",{className:"spec-editor-hint",children:[t.jsx("kbd",{children:"Ctrl"}),"+",t.jsx("kbd",{children:"Enter"})," to save · ",t.jsx("kbd",{children:"Escape"})," to cancel"]}),t.jsxs("div",{className:"spec-editor-revision",children:[t.jsx("h4",{children:"Ask AI to Revise"}),t.jsx("p",{className:"spec-editor-revision-help",children:"Provide feedback for the AI to improve this specification. The task will move to planning for replanning."}),t.jsx("textarea",{className:"spec-editor-feedback",value:oe,onChange:J=>Te(J.target.value),placeholder:"e.g., 'Add more details about error handling', 'Split this into smaller steps', 'Include tests for the API endpoints'...",disabled:Ue,rows:4,maxLength:2e3}),t.jsxs("div",{className:"spec-editor-revision-actions",children:[t.jsxs("span",{className:"spec-editor-char-count",children:[oe.length,"/2000"]}),t.jsx("button",{className:"btn btn-primary btn-sm",onClick:()=>void Ye(),disabled:!oe.trim()||Ue,children:Ue?"Requesting…":"Request AI Revision"})]})]})]}):C?t.jsx("div",{className:"spec-loading",children:"Loading specification…"}):k.prompt?t.jsx("div",{className:"markdown-body",children:t.jsx(hi,{remarkPlugins:[pi],components:df,children:k.prompt.replace(/^#\s+[^\n]*\n+/,"")})}):t.jsx("div",{className:"detail-prompt",children:"(no prompt)"})]}),t.jsxs("div",{className:"detail-section",children:[t.jsx("h4",{children:"Attachments"}),M.length>0?t.jsx("div",{className:"detail-attachments-grid",children:M.map(J=>{const Re=Li(`/api/tasks/${e.id}/attachments/${J.filename}`);return t.jsxs("div",{className:"detail-attachment-card",children:[t.jsx("a",{className:"detail-attachment-link",href:Re,target:"_blank",rel:"noopener noreferrer",children:t.jsx("img",{src:Re,alt:J.originalName,className:"detail-attachment-image"})}),t.jsxs("div",{className:"detail-attachment-meta",children:[J.originalName," (",l$(J.size),")"]}),t.jsx("button",{className:"detail-attachment-delete",onClick:()=>oa(J.filename),title:"Delete attachment",children:"×"})]},J.filename)})}):t.jsx("div",{className:"detail-empty-inline",children:"(no attachments)"}),t.jsx("input",{className:"detail-hidden-file-input",ref:Bi,type:"file",accept:"image/*",onChange:tr}),t.jsx("button",{className:"btn btn-sm",onClick:()=>Bi.current?.click(),disabled:D,children:D?"Uploading…":"Attach Screenshot"})]}),t.jsxs("div",{className:"detail-deps",children:[t.jsx("h4",{children:"Dependencies"}),W.length>0?t.jsx("ul",{className:"detail-dep-list",children:W.map(J=>{const Re=s.find(Ut=>Ut.id===J),Nt=Re?.title||Re?.description||J;return t.jsxs("li",{className:"detail-dep-item",children:[t.jsxs("span",{className:"detail-dep-link",onClick:()=>vi(J),onKeyDown:Ut=>{(Ut.key==="Enter"||Ut.key===" ")&&(Ut.preventDefault(),vi(J))},role:"link",tabIndex:0,title:`Click to view ${J}`,children:[t.jsx("span",{className:"detail-dep-id",children:J}),t.jsx("span",{className:"detail-dep-label",children:Id(Nt,40)})]}),t.jsx("button",{className:"dep-remove-btn",onClick:Ut=>rr(Ut,J),title:`Remove dependency ${J}`,children:"×"})]},J)})}):t.jsx("div",{className:"detail-empty-inline",children:"(no dependencies)"}),t.jsxs("div",{className:"dep-trigger-wrap",children:[t.jsx("button",{type:"button",className:"btn btn-sm dep-trigger",onClick:()=>{me&&Me(""),Ne(J=>!J)},children:"Add Dependency"}),me&&(()=>{const J=ve.toLowerCase(),Re=J?Ce.filter(Nt=>Nt.id.toLowerCase().includes(J)||Nt.title&&Nt.title.toLowerCase().includes(J)||Nt.description&&Nt.description.toLowerCase().includes(J)):Ce;return t.jsxs("div",{className:"dep-dropdown",children:[t.jsx("input",{className:"dep-dropdown-search",placeholder:"Search tasks…",autoFocus:!0,value:ve,onChange:Nt=>Me(Nt.target.value),onClick:Nt=>Nt.stopPropagation()}),Re.length===0?t.jsx("div",{className:"dep-dropdown-empty",children:"No available tasks"}):Re.map(Nt=>t.jsxs("div",{className:"dep-dropdown-item",onClick:()=>{ar(Nt.id),Ne(!1)},children:[t.jsx("span",{className:"dep-dropdown-id",children:Nt.id}),t.jsx("span",{className:"dep-dropdown-title",children:Id(Nt.title||Nt.description||Nt.id,30)})]},Nt.id))]})})()]})]}),t.jsxs("div",{className:"detail-deps detail-blocking",children:[t.jsx("h4",{children:"Blocking"}),Ze.length>0?t.jsx("ul",{className:"detail-dep-list",children:Ze.map(J=>t.jsxs("li",{className:"detail-dep-item",children:[t.jsxs("span",{className:"detail-dep-link",onClick:()=>vi(J.id),onKeyDown:Re=>{(Re.key==="Enter"||Re.key===" ")&&(Re.preventDefault(),vi(J.id))},role:"link",tabIndex:0,title:`Click to view ${J.id}`,children:[t.jsx("span",{className:"detail-dep-id",children:J.id}),t.jsx("span",{className:"detail-dep-label",children:Id(J.label,40)})]}),J.stale&&t.jsx("span",{className:"detail-blocking-item--stale",title:"Stale blockedBy edge: self-healing clearStaleBlockedBy should clear this automatically",children:"(stale)"})]},J.id))}):t.jsx("div",{className:"detail-empty-inline",children:"(no downstream tasks blocked)"})]}),e.column==="in-review"&&t.jsxs(t.Fragment,{children:[Zb(k)&&k.inReviewStall&&(()=>{const J=Xb(k.inReviewStall),Re=e$(k,k.inReviewStall.code);return t.jsxs("div",{className:`detail-section detail-in-review-stall detail-in-review-stall--${J.code}`,"data-stall-code":J.code,children:[t.jsxs("div",{className:"detail-in-review-stall-header",children:[t.jsx("span",{className:"card-status-badge card-status-badge--in-review in-review-stall",children:J.badgeLabel}),t.jsx("span",{className:"detail-in-review-stall-headline",children:J.headline})]}),t.jsx("div",{className:"detail-in-review-stall-reason",children:k.inReviewStall.reason}),t.jsx("div",{className:"detail-in-review-stall-description",children:J.description}),t.jsx("div",{className:"detail-in-review-stall-action",children:J.suggestedAction}),t.jsxs("div",{className:"detail-in-review-stall-meta",children:[t.jsxs("span",{children:["Observed ",kl(k.inReviewStall.observedAt)]}),Re?t.jsx("button",{type:"button",className:"btn btn-sm detail-in-review-stall-jump",onClick:()=>{y("logs"),P("activity"),Y(k.inReviewStall?.code??null)},children:"View activity log"}):t.jsx("span",{className:"detail-in-review-stall-no-log",title:"No 'In-review stall surfaced' entry on this task yet — self-healing may not have logged one within its rate-limit window.",children:"No log entry yet"})]})]})})(),t.jsx("div",{className:"detail-section detail-pr-section",children:t.jsx(vP,{taskId:e.id,projectId:n,prInfo:e.prInfo,automationStatus:e.status??null,autoMerge:En?.autoMerge??!1,isManualPrFlow:Im,prAuthAvailable:f??!1,onPrCreated:J=>{e.prInfo=J},onPrUpdated:J=>{e.prInfo=J},addToast:m})})]})]})]})]}),t.jsx("div",{className:"modal-actions",children:ut?t.jsxs(t.Fragment,{children:[t.jsx("span",{className:"modal-edit-hint",children:qn==="saving"?"Autosaving…":qn==="saved"?"Saved":qn==="error"?"Save failed":"Changes autosave as you edit"}),t.jsx("div",{className:"modal-actions-spacer"}),t.jsx("button",{className:"btn btn-sm",onClick:mn,disabled:pt,children:"Cancel"}),t.jsx("button",{className:"btn btn-primary btn-sm",onClick:()=>void Na(),disabled:pt,children:pt?"Saving…":"Save"})]}):t.jsxs(t.Fragment,{children:[e.column==="triage"&&e.status==="awaiting-approval"&&k.prompt&&t.jsxs(t.Fragment,{children:[t.jsx("button",{className:"btn btn-primary btn-sm",onClick:xi,children:"Approve Plan"}),t.jsx("button",{className:"btn btn-danger btn-sm",onClick:Za,children:"Reject Plan"})]}),e.column==="triage"&&e.status!=="awaiting-approval"&&!R&&t.jsx("button",{className:"btn btn-sm btn-danger",onClick:sa,"aria-label":"Delete task",title:"Delete task",children:"Delete"}),(e.column!=="triage"||e.status==="awaiting-approval"||R||e.paused)&&t.jsxs("div",{className:"detail-actions-dropdown",ref:Gn,children:[t.jsxs("button",{className:"btn btn-sm",onClick:()=>{$n(J=>!J),sn(!1)},"aria-haspopup":"menu","aria-expanded":xn,children:["Actions",t.jsx(vn,{size:12})]}),xn&&t.jsxs("div",{className:"detail-actions-menu",role:"menu",children:[t.jsx("button",{className:"detail-actions-menu-item detail-actions-menu-item-danger",role:"menuitem",onClick:()=>ni(sa),children:"Delete"}),u&&t.jsx("button",{className:"detail-actions-menu-item",role:"menuitem",onClick:()=>ni(aa),children:"Duplicate"}),(e.column==="done"||e.column==="in-review")&&t.jsx("button",{className:"detail-actions-menu-item",role:"menuitem",onClick:()=>ni(_a),children:"Refine"}),t.jsx("button",{className:"detail-actions-menu-item",role:"menuitem",onClick:()=>ni(Ea),children:"Respecify"}),R&&c&&t.jsx("button",{className:"detail-actions-menu-item",role:"menuitem",onClick:()=>ni(Xa),children:"Retry"}),d&&e.column!=="done"&&e.column!=="archived"&&t.jsx("button",{className:"detail-actions-menu-item detail-actions-menu-item-danger",role:"menuitem",onClick:()=>ni(Ui),children:"Reset"}),e.column!=="done"&&!e.assignedAgentId&&t.jsx("button",{className:"detail-actions-menu-item",role:"menuitem",onClick:()=>ni(ra),children:e.paused?"Unpause":"Pause"}),e.column!=="done"&&e.paused&&e.pausedByAgentId&&t.jsx("span",{className:"detail-actions-menu-item detail-actions-menu-note",role:"note",children:"Paused by agent"})]})]}),t.jsx("div",{className:"modal-actions-spacer"}),t.jsx("div",{className:"detail-move-dropdown",ref:kn,children:e.column==="in-review"?t.jsxs("div",{className:"detail-move-actions-in-review",children:[t.jsxs("div",{children:[t.jsxs("button",{ref:ms,className:"btn btn-primary btn-sm detail-move-btn",onClick:Ds,onKeyDown:ri,disabled:!An,"aria-label":An?`Move to ${ds[An]}`:void 0,"aria-haspopup":Zt?"menu":void 0,"aria-expanded":Zt?zt:void 0,children:[t.jsxs("span",{className:"detail-move-btn__label",children:["Move to ",An?ds[An]:""]}),Zt&&t.jsx("span",{className:"detail-move-btn__arrow","aria-hidden":"true",children:t.jsx(vn,{size:12})})]}),zt&&Zt&&t.jsx("div",{className:"detail-move-menu",role:"menu",onKeyDown:la,children:Jn.map(J=>t.jsx("button",{className:"detail-move-menu-item",role:"menuitem",onClick:()=>Ci(J),onKeyDown:la,children:J==="in-progress"?"Back to In Progress":`Move to ${ds[J]}`},J))})]}),Dc?t.jsx("button",{className:"btn btn-primary btn-sm",disabled:!0,children:Dc}):t.jsx("button",{className:"btn btn-primary btn-sm",onClick:er,children:sl})]}):t.jsxs("div",{children:[t.jsxs("button",{ref:ms,className:"btn btn-primary btn-sm detail-move-btn",onClick:Ds,onKeyDown:ri,disabled:!An,"aria-label":An?`Move to ${ds[An]}`:void 0,"aria-haspopup":Zt?"menu":void 0,"aria-expanded":Zt?zt:void 0,children:[t.jsxs("span",{className:"detail-move-btn__label",children:["Move to ",An?ds[An]:""]}),Zt&&t.jsx("span",{className:"detail-move-btn__arrow","aria-hidden":"true",children:t.jsx(vn,{size:12})})]}),zt&&Zt&&t.jsx("div",{className:"detail-move-menu",role:"menu",onKeyDown:la,children:Jn.map(J=>t.jsxs("button",{className:"detail-move-menu-item",role:"menuitem",onClick:()=>Ci(J),onKeyDown:la,children:["Move to ",ds[J]]},J))})]})})]})}),Fe&&t.jsx("div",{className:"modal-overlay open detail-refine-overlay",onClick:Ei,role:"dialog","aria-modal":"true",children:t.jsxs("div",{className:"modal detail-refine-modal",onClick:J=>J.stopPropagation(),children:[t.jsxs("div",{className:"modal-header",children:[t.jsx("h3",{className:"detail-refine-title",children:"Refine"}),t.jsx("button",{className:"modal-close",onClick:Ei,"aria-label":"Close",children:"×"})]}),t.jsxs("div",{className:"detail-body",children:[t.jsx("p",{className:"detail-refine-help",children:"Describe what needs to be refined or improved..."}),t.jsx("textarea",{className:"detail-refine-textarea",value:We,onChange:J=>he(J.target.value),placeholder:"Enter your feedback here...",rows:6,maxLength:2e3,autoFocus:!0}),t.jsxs("div",{className:"detail-refine-input-group",children:[t.jsxs("div",{className:"detail-refine-char-count",children:[We.length,"/2000 characters"]}),t.jsx("button",{className:"btn btn-primary btn-sm",onClick:Ma,disabled:!We.trim()||pe,children:pe?"Creating...":"Create Refinement Task"})]})]}),t.jsx("div",{className:"modal-actions",children:t.jsx("button",{className:"btn btn-sm",onClick:Ei,disabled:pe,children:"Cancel"})})]})}),_&&t.jsx(i.Suspense,{fallback:null,children:t.jsx(h$,{agentId:_,projectId:n,onClose:()=>G(null),addToast:m})})]})}function b$({onClose:e,...n}){const s=i.useRef(null);Oi(s,!0,"task-detail-modal-size"),Si(!0);const a=Xi(e);return t.jsx("div",{className:"modal-overlay open",...a,role:"dialog","aria-modal":"true",children:t.jsx("div",{className:"modal modal-lg task-detail-modal",ref:s,children:t.jsx(Av,{...n,onRequestClose:e})})})}const jl={triage:"var(--triage)",todo:"var(--todo)","in-progress":"var(--in-progress)","in-review":"var(--in-review)",done:"var(--done)",archived:"var(--text-dim)"},hf=new Set(["planning","researching","executing","finalizing","merging","merging-fix"]);function pf(e){return e==="merging-fix"?"Merging fixes…":e}const Rv=["title","status","column","dependencies","progress"],x$=["title","status","column"];function v$(e){return e==="online"?"Online":e==="connecting"?"Connecting":e==="error"?"Error":"Offline"}function y$(e){return e==="online"?"●":e==="connecting"?"◐":e==="error"?"✕":"○"}function ff(e){try{const n=Ln("kb-dashboard-list-columns",e);if(n){const a=JSON.parse(n).filter(r=>Rv.includes(r));if(a.length>0)return new Set(a)}}catch{}return new Set(x$)}function gf(e){try{const n=Ln("kb-dashboard-hide-done",e);if(n!==null)return n==="true"}catch{}return!1}function bf(e){try{const n=Ln("kb-dashboard-list-collapsed",e);if(n){const a=JSON.parse(n).filter(r=>ha.includes(r));if(a.length>0)return new Set(a)}}catch{}return new Set}function xf(e){try{const n=Ln("kb-dashboard-selected-tasks",e);if(n){const s=JSON.parse(n);return new Set(s)}}catch{}return new Set}function vf(e){try{const n=Ln("kb-dashboard-list-selected-task",e);if(typeof n=="string"&&n.trim().length>0)return n}catch{}return null}function yf(e){try{const s=Ln("kb-dashboard-list-sidebar-width",e);if(!s)return 400;const a=Number(s);if(Number.isFinite(a)&&a>0)return a}catch{}return 400}const oc=280,Iu=.65,Nl=16;function Tu(e){return Math.max(oc,e*Iu)}function Sl(e,n){const s=Tu(n);return Math.min(Math.max(e,oc),s)}function w$(e){return e.status==="executing"||e.column==="in-progress"}function wf(e){const n=ex(e);return n.total===0||!w$(e)?{label:"-",percent:0,hasProgress:!1}:{label:`${n.completed}/${n.total}`,percent:n.completed/n.total*100,hasProgress:!0}}function k$({tasks:e,onMoveTask:n,onRetryTask:s,onDeleteTask:a,onPauseTask:r,onUnpauseTask:o,onArchiveTask:l,onMergeTask:c,onResetTask:d,onDuplicateTask:u,onOpenDetail:h,addToast:m,globalPaused:f,onNewTask:p,onQuickCreate:g,availableModels:w,favoriteProviders:v=[],favoriteModels:b=[],onToggleFavorite:y,onToggleModelFavorite:j,onPlanningMode:S,onSubtaskBreakdown:C,onTasksUpdated:x,projectId:k,projectName:R,taskStuckTimeoutMs:O,searchQuery:E="",lastFetchTimeMs:_,prAuthAvailable:G}){const[H,A]=i.useState(null),[P,q]=i.useState("asc"),[Y,ge]=i.useState(null),[L,M]=i.useState(null),[$,D]=i.useState(null),W=ei()==="mobile",{confirm:de}=ti(),[me,Ne]=i.useState(()=>ff(k)),[ve,Me]=i.useState(()=>gf(k)),[ie,ye]=i.useState(()=>bf(k));i.useEffect(()=>{typeof window<"u"&&rs("kb-dashboard-list-columns",JSON.stringify([...me]),k)},[k,me]),i.useEffect(()=>{typeof window<"u"&&rs("kb-dashboard-hide-done",ve.toString(),k)},[ve,k]),i.useEffect(()=>{typeof window<"u"&&rs("kb-dashboard-list-collapsed",JSON.stringify([...ie]),k)},[ie,k]);const[Z,fe]=i.useState(!1),[Q,F]=i.useState(!1),[X,re]=i.useState(()=>xf(k)),[U,be]=i.useState(()=>vf(k)),[Ue,se]=i.useState(null),[Ve,Le]=i.useState(()=>yf(k)),ct=i.useRef(null),Ke=i.useRef(null);i.useEffect(()=>{Ne(ff(k)),Me(gf(k)),ye(bf(k)),re(xf(k));const we=vf(k);be(we),se(we?e.find(ze=>ze.id===we)??null:null),Le(yf(k))},[k,e]),i.useEffect(()=>{typeof window<"u"&&rs("kb-dashboard-selected-tasks",JSON.stringify([...X]),k)},[k,X]),i.useEffect(()=>{if(!(typeof window>"u")){if(U){rs("kb-dashboard-list-selected-task",U,k);return}qa("kb-dashboard-list-selected-task",k)}},[k,U]),i.useEffect(()=>{if(!U){se(null);return}const we=e.find(ze=>ze.id===U);we&&se(ze=>!ze||ze.id!==U?we:{...ze,...we})},[U,e]),i.useEffect(()=>{if(W||typeof ResizeObserver>"u")return;const we=ct.current;if(!we)return;const ze=()=>{const He=Sl(Ve,we.clientWidth);He!==Ve&&Le(He)};ze();const rt=new ResizeObserver(ze);return rt.observe(we),()=>rt.disconnect()},[W,Ve]),i.useEffect(()=>{if(W||typeof ResizeObserver>"u")return;const we=Ke.current,ze=ct.current;if(!we||!ze)return;let rt=null,He=we.offsetWidth;const Ae=new ResizeObserver(()=>{const pt=Sl(we.offsetWidth,ze.clientWidth);pt!==He&&(He=pt,rt&&clearTimeout(rt),rt=setTimeout(()=>{try{rs("kb-dashboard-list-sidebar-width",String(pt),k)}catch{}},200))});return Ae.observe(we),()=>{Ae.disconnect(),rt&&clearTimeout(rt)}},[W,k]);const oe=i.useCallback(()=>{F(we=>(we&&re(new Set),!we))},[]),Te=i.useCallback(we=>{re(ze=>{const rt=new Set(ze);return rt.has(we)?rt.delete(we):rt.add(we),rt})},[]),Fe=i.useCallback(()=>{re(new Set)},[]),mt=i.useCallback(we=>{Ne(ze=>{const rt=new Set(ze);return rt.has(we)?rt.size>1&&rt.delete(we):rt.add(we),rt})},[]),We={title:"Title",status:"Status",column:"Column",dependencies:"Dependencies",progress:"Progress"},he=i.useCallback(we=>{if(H===we){q(ze=>ze==="asc"?"desc":"asc");return}A(we),q("asc")},[H]),pe=i.useCallback(we=>{D(ze=>ze===we?null:we)},[]),De=i.useCallback(we=>{ye(ze=>{const rt=new Set(ze);return rt.has(we)?rt.delete(we):rt.add(we),rt})},[]),ut=i.useCallback(()=>{D(null)},[]),ht=i.useMemo(()=>{let we=E?e.filter(He=>He.id.toLowerCase().includes(E.toLowerCase())||He.title&&He.title.toLowerCase().includes(E.toLowerCase())||He.description.toLowerCase().includes(E.toLowerCase())):[...e];ve&&!$&&(we=we.filter(He=>He.column!=="done"&&He.column!=="archived"));const ze=$?we.filter(He=>He.column===$):we,rt={triage:[],todo:[],"in-progress":[],"in-review":[],done:[],archived:[]};ze.forEach(He=>{const Ae=Ku(He.column)?He.column:Yl;rt[Ae].push(He)});for(const He of ha){if(!H){rt[He]=Kb(rt[He],He);continue}rt[He]=[...rt[He]].sort((Ae,pt)=>{let Ct=0;switch(H){case"title":Ct=(Ae.title||Ae.description).localeCompare(pt.title||pt.description);break;case"status":Ct=(Ae.status||"").localeCompare(pt.status||"");break;case"column":Ct=Ae.column.localeCompare(pt.column);break}return P==="asc"?Ct:-Ct})}return rt},[e,E,H,P,ve,$]),et=i.useMemo(()=>Object.values(ht).reduce((we,ze)=>we+ze.length,0),[ht]),vt=i.useMemo(()=>e.filter(we=>we.column==="done"||we.column==="archived").length,[e]),Oe=i.useMemo(()=>ve?vt:0,[ve,vt]),tt=i.useCallback(()=>{const we=Object.values(ht).flat().filter(ze=>ze.column!=="archived").map(ze=>ze.id);re(ze=>{if(we.every(He=>ze.has(He))){const He=new Set(ze);return we.forEach(Ae=>He.delete(Ae)),He}else return new Set([...ze,...we])})},[ht]),ft=i.useMemo(()=>{const we=Object.values(ht).flat().filter(ze=>ze.column!=="archived");return we.length===0?!1:we.every(ze=>X.has(ze.id))},[ht,X]),Mt=i.useMemo(()=>{const we=Object.values(ht).flat().filter(rt=>rt.column!=="archived");if(we.length===0)return!1;const ze=we.filter(rt=>X.has(rt.id)).length;return ze>0&&ze<we.length},[ht,X]),[yt,Ge]=i.useState("__no_change__"),[K,ue]=i.useState("__no_change__"),[ot,xe]=i.useState("__no_change__"),[dt,Je]=i.useState([]),[ke,nt]=i.useState(!1),bt=i.useMemo(()=>ot&&ot!=="__no_change__"?dt.find(we=>we.id===ot):void 0,[dt,ot]),[kt,wt]=i.useState(!1);i.useEffect(()=>{if(X.size===0)return;let we=!1;return(async()=>{nt(!0);try{const rt=await ec();we||Je(rt)}catch(rt){console.error("Failed to fetch nodes for bulk edit",rt),we||Je([])}finally{we||nt(!1)}})(),()=>{we=!0}},[X.size]);const At=i.useCallback(async()=>{if(X.size===0)return;const we=Array.from(X).map(Tt=>e.find(Gt=>Gt.id===Tt)).filter(Tt=>!!Tt),ze=we.filter(Tt=>Tt.column==="archived"),rt=we.filter(Tt=>Tt.column!=="archived");if(rt.length===0){m("No selected tasks can be deleted (archived tasks are excluded)","error");return}if(!await de({title:"Delete Selected Tasks",message:`Delete ${rt.length} selected task${rt.length===1?"":"s"}?`,confirmLabel:"Delete",cancelLabel:"Cancel",danger:!0}))return;wt(!0);const Ae=[],pt=[],Ct=ze.map(Tt=>Tt.id);try{for(const Tt of rt)try{await a(Tt.id),Ae.push(Tt.id)}catch(Gt){const nn=im(Gt);if(!nn){pt.push(Tt.id);continue}if(!await de({title:"Force Delete Task",message:`Task ${Tt.id} has dependents: ${nn.dependentIds.join(", ")}. Remove dependency references and force delete?`,confirmLabel:"Force Delete",cancelLabel:"Skip",danger:!0})){pt.push(Tt.id);continue}try{await a(Tt.id,{removeDependencyReferences:!0}),Ae.push(Tt.id)}catch{pt.push(Tt.id)}}}finally{wt(!1)}Ae.length>0&&re(Tt=>{const Gt=new Set(Tt);for(const nn of Ae)Gt.delete(nn);return Gt}),m(`Deleted ${Ae.length} task${Ae.length===1?"":"s"} · ${Ct.length} archived skipped · ${pt.length} failed`,pt.length>0?"error":"success")},[m,de,a,X,e]),Ft=i.useCallback(async()=>{if(X.size===0)return;if(!r){m("Pause action is unavailable","error");return}const we=Array.from(X).map(pt=>e.find(Ct=>Ct.id===pt)).filter(pt=>!!pt),ze=we.filter(pt=>pt.column!=="archived"&&pt.paused!==!0),rt=we.length-ze.length;if(ze.length===0){m("No selected tasks can be paused","error");return}wt(!0);const He=[],Ae=[];try{for(const pt of ze)try{await r(pt.id),He.push(pt.id)}catch{Ae.push(pt.id)}}finally{wt(!1)}He.length>0&&re(pt=>{const Ct=new Set(pt);for(const Tt of He)Ct.delete(Tt);return Ct}),m(`Paused ${He.length} · ${rt} skipped · ${Ae.length} failed`,Ae.length>0?"error":"success")},[m,r,X,e]),ln=i.useCallback(async()=>{if(X.size===0)return;if(!o){m("Unpause action is unavailable","error");return}const we=Array.from(X).map(pt=>e.find(Ct=>Ct.id===pt)).filter(pt=>!!pt),ze=we.filter(pt=>pt.column!=="archived"&&pt.paused===!0),rt=we.length-ze.length;if(ze.length===0){m("No selected tasks can be unpaused","error");return}wt(!0);const He=[],Ae=[];try{for(const pt of ze)try{await o(pt.id),He.push(pt.id)}catch{Ae.push(pt.id)}}finally{wt(!1)}He.length>0&&re(pt=>{const Ct=new Set(pt);for(const Tt of He)Ct.delete(Tt);return Ct}),m(`Unpaused ${He.length} · ${rt} skipped · ${Ae.length} failed`,Ae.length>0?"error":"success")},[m,o,X,e]),Vt=i.useCallback(async()=>{if(X.size===0)return;if(!l){m("Archive action is unavailable","error");return}const we=Array.from(X).map(Ct=>e.find(Tt=>Tt.id===Ct)).filter(Ct=>!!Ct),ze=we.filter(Ct=>Ct.column==="done"),rt=we.length-ze.length;if(ze.length===0){m("No selected tasks can be archived (only done tasks)","error");return}if(!await de({title:"Archive Selected Tasks",message:`Archive ${ze.length} selected task${ze.length===1?"":"s"}?`,confirmLabel:"Archive",cancelLabel:"Cancel",danger:!1}))return;wt(!0);const Ae=[],pt=[];try{for(const Ct of ze)try{await l(Ct.id),Ae.push(Ct.id)}catch{pt.push(Ct.id)}}finally{wt(!1)}Ae.length>0&&re(Ct=>{const Tt=new Set(Ct);for(const Gt of Ae)Tt.delete(Gt);return Tt}),m(`Archived ${Ae.length} · ${rt} skipped · ${pt.length} failed`,pt.length>0?"error":"success")},[m,de,l,X,e]),hn=i.useCallback(async()=>{if(X.size===0)return;const we=Array.from(X).filter(rt=>{const He=e.find(Ae=>Ae.id===rt);return He&&He.column!=="archived"});if(we.length===0){m("No valid tasks to update (archived tasks cannot be modified)","error");return}const ze={taskIds:we};if(yt!=="__no_change__")if(yt==="")ze.modelProvider=null,ze.modelId=null;else{const rt=yt.indexOf("/");rt!==-1&&(ze.modelProvider=yt.slice(0,rt),ze.modelId=yt.slice(rt+1))}if(K!=="__no_change__")if(K==="")ze.validatorModelProvider=null,ze.validatorModelId=null;else{const rt=K.indexOf("/");rt!==-1&&(ze.validatorModelProvider=K.slice(0,rt),ze.validatorModelId=K.slice(rt+1))}if(ot!=="__no_change__"&&(ot===""?ze.nodeId=null:ze.nodeId=ot),Object.keys(ze).length===1){m("No changes to apply","info");return}wt(!0);try{const rt=await mN(ze.taskIds,ze.modelProvider,ze.modelId,ze.validatorModelProvider,ze.validatorModelId,void 0,void 0,ze.nodeId,k);x&&x(rt.updated),m(`Updated ${we.length} task${we.length===1?"":"s"}`,"success"),Fe(),Ge("__no_change__"),ue("__no_change__"),xe("__no_change__")}catch(rt){m(Ie(rt)||"Failed to update models","error")}finally{wt(!1)}},[X,e,yt,K,ot,k,m,Fe,x]),un=i.useCallback(we=>{if(W){h(we,{origin:"list-mobile"});return}be(we.id),se(we)},[W,h]),pn=i.useRef(null),an=i.useRef(null);i.useEffect(()=>()=>{pn.current&&clearTimeout(pn.current)},[]);const Wt=i.useCallback(we=>{if(be(we.id),se(we),"prompt"in we){an.current=null,pn.current&&(clearTimeout(pn.current),pn.current=null);return}an.current=we.id,pn.current&&clearTimeout(pn.current),pn.current=setTimeout(()=>{pn.current=null,an.current===we.id&&Ba(we.id,k).then(rt=>{an.current===rt.id&&se(He=>!He||He.id!==rt.id?He:{...He,...rt})}).catch(()=>{})},200)},[k]),gn=i.useCallback((we,ze)=>{if(ze.paused){we.preventDefault();return}we.dataTransfer.setData("text/plain",ze.id),we.dataTransfer.effectAllowed="move",ge(ze.id)},[]),cn=i.useCallback(()=>{ge(null),M(null)},[]),tn=i.useCallback(we=>{if(W)return;we.preventDefault();const ze=ct.current;if(!ze)return;const rt=ze.getBoundingClientRect(),He=pt=>{const Ct=pt.clientX-rt.left;Le(Sl(Ct,rt.width))},Ae=()=>{window.removeEventListener("mousemove",He),window.removeEventListener("mouseup",Ae)};window.addEventListener("mousemove",He),window.addEventListener("mouseup",Ae)},[W]),Yt=i.useCallback(we=>{if(W)return;const ze=ct.current?.clientWidth??0,rt=Ve/Iu+Nl,He=Math.max(ze,rt),Ae=Tu(He);if(we.key==="ArrowLeft"||we.key==="ArrowRight"){we.preventDefault();const pt=we.key==="ArrowLeft"?-Nl:Nl;Le(Ct=>Sl(Ct+pt,He));return}if(we.key==="Home"){we.preventDefault(),Le(oc);return}we.key==="End"&&(we.preventDefault(),Le(Ae))},[W,Ve]),Qt=i.useCallback((we,ze)=>{we.preventDefault(),we.dataTransfer.dropEffect="move",M(ze)},[]),Kt=i.useCallback(()=>{M(null)},[]),Jt=i.useCallback(async(we,ze)=>{we.preventDefault(),M(null);const rt=we.dataTransfer.getData("text/plain");if(rt){if(ze==="archived"){m("Tasks can only be archived via the archive button","error");return}try{const Ae=e.find(Tt=>Tt.id===rt)?.steps.some(Tt=>Tt.status!=="pending")??!1,pt=(ze==="todo"||ze==="triage")&&Ae;let Ct;if(pt){if(await de({title:"Preserve Progress?",message:"This task has completed steps. Keep progress before moving?",confirmLabel:"Keep Progress",cancelLabel:"Reset Progress"}))Ct={preserveProgress:!0};else if(!await de({title:"Reset Progress?",message:"Reset all step progress before moving this task?",confirmLabel:"Reset Progress",cancelLabel:"Cancel Move",danger:!0}))return}await n(rt,ze,Ct)}catch(He){m(Ie(He),"error")}}},[n,m,e,de]),rn=we=>!H||H!==we?t.jsx(ab,{size:14,className:"sort-icon"}):P==="asc"?t.jsx(La,{size:14,className:"sort-icon active"}):t.jsx(Uo,{size:14,className:"sort-icon active"}),qt=we=>t.jsxs("div",{id:we,className:"list-view-options-panel",children:[t.jsx("div",{className:"list-view-options-columns",children:Rv.map(ze=>{const rt=me.has(ze),He=rt&&me.size===1;return t.jsxs("label",{className:`list-column-dropdown-item${He?" disabled":""}`,title:He?"At least one column must be visible":"",children:[t.jsx("input",{type:"checkbox",checked:rt,onChange:()=>mt(ze),disabled:He}),t.jsx("span",{children:We[ze]})]},ze)})}),t.jsxs("button",{className:"btn btn-sm list-hide-done-toggle",onClick:()=>Me(ze=>!ze),"aria-pressed":ve,title:ve?"Show done tasks":"Hide done tasks",children:[ve?t.jsx(zr,{size:14}):t.jsx(qu,{size:14}),ve?"Show Done":"Hide Done"]}),t.jsx("div",{className:"list-drop-zones list-drop-zones--sidebar",children:ha.map(ze=>{const rt=e.filter(Ct=>Ct.column===ze).length,He=ze==="done"||ze==="archived",Ae=ve&&He?0:rt,pt=ve&&He&&rt>0;return t.jsxs("div",{className:`list-drop-zone${L===ze?" drag-over":""}${$===ze?" active":""}`,onClick:()=>pe(ze),onDragOver:Ct=>Qt(Ct,ze),onDragLeave:Kt,onDrop:Ct=>Jt(Ct,ze),"data-column":ze,children:[t.jsx("span",{className:`list-section-dot dot-${ze}`}),t.jsx("span",{className:"drop-zone-label",children:ds[ze]}),t.jsx("span",{className:"drop-zone-count",children:pt?`${Ae} of ${rt}`:rt})]},ze)})})]});return t.jsxs("div",{className:"list-view",children:[W&&t.jsxs(t.Fragment,{children:[t.jsxs("div",{className:"list-toolbar",children:[t.jsx("button",{className:"btn btn-sm",onClick:oe,"aria-pressed":Q,children:Q?"Done Editing":"Bulk Edit"}),t.jsxs("button",{className:"btn btn-sm list-view-options-toggle",onClick:()=>fe(we=>!we),"aria-expanded":Z,"aria-controls":"list-view-options-panel-mobile",children:[t.jsx(Om,{size:14}),"View options"]}),p?t.jsx("button",{className:"btn btn-task-create btn-sm list-new-task-action",onClick:p,children:"+ New Task"}):null,t.jsx("div",{className:"list-stats",children:$?`${et} of ${e.length} tasks in ${ds[$]}`:`${et} of ${e.length} tasks`})]}),Z?t.jsx("div",{className:"list-toolbar-mobile-options",children:qt("list-view-options-panel-mobile")}):null]}),t.jsx("div",{className:"list-table-container",children:t.jsxs("div",{className:W?"":"list-split-layout","data-testid":W?void 0:"list-split-layout",ref:ct,children:[t.jsxs("div",{className:W?"":"list-split-sidebar","data-testid":W?void 0:"list-split-sidebar",ref:Ke,style:W?void 0:{width:`${Ve}px`},children:[!W&&t.jsxs("aside",{className:"list-sidebar-controls","aria-label":"List controls",children:[t.jsxs("div",{className:"list-sidebar-controls__header",children:[t.jsxs("p",{className:"list-stats",children:[$?`${et} of ${e.length} tasks in ${ds[$]}`:`${et} of ${e.length} tasks`,Oe>0&&!$&&t.jsxs("span",{className:"list-stats-hidden",children:[" (",Oe," hidden)"]})]}),t.jsxs("div",{className:"list-sidebar-controls__actions",children:[t.jsx("button",{className:"btn btn-sm",onClick:oe,"aria-pressed":Q,children:Q?"Done Editing":"Bulk Edit"}),p?t.jsx("button",{className:"btn btn-task-create btn-sm list-new-task-action",onClick:p,children:"+ New Task"}):null]}),t.jsxs("div",{className:"list-sidebar-summary-chips",children:[$?t.jsx("button",{className:"btn btn-sm",onClick:ut,"aria-label":"Clear column filter",children:`Filter: ${ds[$]}`}):null,ve?t.jsx("span",{className:"list-sidebar-chip",children:"Done hidden"}):null,Q?t.jsx("span",{className:"list-sidebar-chip",children:"Bulk edit"}):null,Q&&X.size>0?t.jsx("button",{className:"btn btn-sm",onClick:Fe,children:`${X.size} selected`}):null]})]}),t.jsxs("button",{className:"btn btn-sm list-view-options-toggle",onClick:()=>fe(we=>!we),"aria-expanded":Z,"aria-controls":"list-view-options-panel",children:[t.jsx(Om,{size:14}),"View options"]}),Z&&qt("list-view-options-panel"),Q&&X.size>0?t.jsxs(t.Fragment,{children:[t.jsxs("div",{className:"bulk-edit-toolbar",children:[t.jsxs("button",{className:"btn btn-sm",onClick:Ft,disabled:kt,title:"Pause all selected tasks that are not already paused",children:[t.jsx(di,{size:14}),"Pause selected"]}),t.jsxs("button",{className:"btn btn-sm",onClick:ln,disabled:kt,title:"Unpause selected tasks that are currently paused",children:[t.jsx(is,{size:14}),"Unpause selected"]}),t.jsxs("button",{className:"btn btn-sm",onClick:Vt,disabled:kt,title:"Archive selected tasks that are in Done",children:[t.jsx(Fr,{size:14}),"Archive selected"]}),t.jsxs("button",{className:"btn btn-danger btn-sm",onClick:At,disabled:kt,title:"Delete selected tasks",children:[t.jsx(In,{size:14}),"Delete selected"]})]}),w&&w.length>0?t.jsxs("div",{className:"bulk-edit-toolbar",children:[t.jsx("span",{className:"bulk-edit-label",children:"Bulk Edit Models & Node:"}),t.jsx("div",{className:"bulk-edit-dropdown",children:t.jsx(Ns,{models:w,value:yt,onChange:Ge,label:"Executor Model",noChangeValue:"__no_change__",noChangeLabel:"No change",favoriteProviders:v,onToggleFavorite:y,favoriteModels:b,onToggleModelFavorite:j})}),t.jsx("div",{className:"bulk-edit-dropdown",children:t.jsx(Ns,{models:w,value:K,onChange:ue,label:"Reviewer Model",noChangeValue:"__no_change__",noChangeLabel:"No change",favoriteProviders:v,onToggleFavorite:y,favoriteModels:b,onToggleModelFavorite:j})}),t.jsxs("div",{className:"bulk-edit-dropdown bulk-edit-node-wrap",children:[t.jsxs("select",{className:"select bulk-node-select",value:ot,onChange:we=>xe(we.target.value),"aria-label":"Node Override",disabled:ke,children:[t.jsx("option",{value:"__no_change__",children:"No change"}),t.jsx("option",{value:"",children:"Use project default"}),dt.map(we=>t.jsx("option",{value:we.id,children:`${y$(we.status)} ${we.name||we.id} (${v$(we.status)})`},we.id))]}),bt?t.jsx(Ua,{status:bt.status,showLabel:!0}):null]}),t.jsx("button",{className:"btn btn-primary btn-sm bulk-edit-apply-btn",onClick:hn,disabled:kt||yt==="__no_change__"&&K==="__no_change__"&&ot==="__no_change__",children:kt?"Applying...":"Apply"})]}):null]}):null]}),t.jsx("div",{className:"list-quick-entry-above-table",children:t.jsx(lx,{onCreate:g??(async()=>m("Task creation not available","error")),addToast:m,tasks:e,availableModels:w,onPlanningMode:S,onSubtaskBreakdown:C,projectId:k,autoExpand:!1,favoriteProviders:v,favoriteModels:b,onToggleFavorite:y,onToggleModelFavorite:j})}),et===0?t.jsx("div",{className:"list-empty",children:E?"No tasks match your filter":"No tasks yet"}):W?t.jsx("div",{className:"list-cards",children:ha.map(we=>{if($&&we!==$||ve&&(we==="done"||we==="archived")&&!$)return null;const ze=ht[we],rt=ze.length===0;if(E&&rt)return null;const He=ie.has(we);return t.jsxs(i.Fragment,{children:[t.jsxs("div",{className:`list-card-section-header${He?" list-section-header--collapsed":""}`,onClick:()=>De(we),"aria-expanded":!He,role:"button",tabIndex:0,onKeyDown:Ae=>{(Ae.key==="Enter"||Ae.key===" ")&&(Ae.preventDefault(),De(we))},children:[t.jsx(Wn,{size:14,className:`list-section-chevron${He?"":" list-section-chevron--expanded"}`}),t.jsx("span",{className:`list-section-dot dot-${we}`}),t.jsx("span",{className:"list-section-title",children:ds[we]}),t.jsx("span",{className:"list-section-count",children:ze.length})]}),!He&&t.jsx(t.Fragment,{children:rt?t.jsx("div",{className:"list-empty-cell list-card-empty",children:"No tasks"}):ze.map(Ae=>{const pt=Ae.status==="failed",Ct=Ae.paused===!0,Tt=nc(Ae,O,_),Gt=!f&&!pt&&!Ct&&!Tt&&(Ae.column==="in-progress"||hf.has(Ae.status)),nn=typeof Ae.status=="string"&&Ae.status.trim().length>0,Ht=!!(Ae.dependencies&&Ae.dependencies.length>0),on=wf(Ae),ae=on.hasProgress,le=Q;return t.jsxs("div",{className:`list-card${Gt?" agent-active":""}${le?" list-card--selectable":""}`,onClick:()=>un(Ae),"data-id":Ae.id,children:[le&&t.jsx("label",{className:"list-card-checkbox",onClick:Qe=>Qe.stopPropagation(),children:t.jsx("input",{type:"checkbox",checked:X.has(Ae.id),onChange:Qe=>{Qe.stopPropagation(),Te(Ae.id)},onClick:Qe=>Qe.stopPropagation(),disabled:Ae.column==="archived","aria-label":`Select ${Ae.id}`})}),t.jsxs("div",{className:"list-card-row",children:[t.jsx("span",{className:"list-card-id",children:Ae.id}),Ae.executionMode==="fast"&&t.jsxs("span",{className:"list-execution-mode-badge list-execution-mode-badge--fast",title:"Fast mode","aria-label":"Fast mode",children:[t.jsx(as,{"aria-hidden":"true"}),t.jsx("span",{className:"visually-hidden",children:"Fast mode"})]}),t.jsx("span",{className:"list-card-spacer"}),Ct&&Ae.pausedByAgentId?t.jsx("span",{className:"list-status-badge paused",children:"paused by agent"}):Tt?t.jsx("span",{className:"list-status-badge stuck",children:"Stuck"}):nn?t.jsx("span",{className:`list-status-badge list-status-badge--${Ae.column}${pt?" failed":""}${Gt?" pulsing":""}`,children:pf(Ae.status??"")}):null]}),t.jsx("div",{className:"list-card-row",children:t.jsx("div",{className:"list-card-title",children:Ae.title||Ae.description})}),(Ht||ae)&&t.jsxs("div",{className:"list-card-row list-card-meta",children:[Ht&&t.jsxs("span",{className:"list-dep-badge",title:Ae.dependencies.join(", "),children:[t.jsx(Cr,{size:12})," ",Ae.dependencies.length]}),ae&&t.jsxs("div",{className:"list-progress",children:[t.jsx("div",{className:"list-progress-bar",children:t.jsx("div",{className:"list-progress-fill",style:{width:`${on.percent}%`,backgroundColor:jl[Ae.column]}})}),t.jsx("span",{className:"list-progress-label",children:on.label})]})]})]},Ae.id)})})]},we)})}):t.jsxs("table",{className:"list-table",children:[t.jsx("thead",{children:t.jsxs("tr",{children:[Q&&t.jsx("th",{className:"list-header-cell list-header-checkbox",children:t.jsx("input",{type:"checkbox",checked:ft,ref:we=>{we&&(we.indeterminate=Mt)},onChange:tt,"aria-label":"Select all visible tasks"})}),me.has("title")&&t.jsxs("th",{className:"list-header-cell",onClick:()=>he("title"),children:["Title ",rn("title")]}),me.has("status")&&t.jsxs("th",{className:"list-header-cell",onClick:()=>he("status"),children:["Status ",rn("status")]}),me.has("column")&&t.jsxs("th",{className:"list-header-cell",onClick:()=>he("column"),children:["Column ",rn("column")]}),me.has("dependencies")&&t.jsx("th",{className:"list-header-cell",children:"Dependencies"}),me.has("progress")&&t.jsx("th",{className:"list-header-cell",children:"Progress"})]})}),t.jsx("tbody",{children:ha.map(we=>{if($&&we!==$||ve&&(we==="done"||we==="archived")&&!$)return null;const ze=ht[we],rt=ze.length===0;if(E&&rt)return null;const He=ie.has(we);return t.jsxs(i.Fragment,{children:[t.jsx("tr",{className:`list-section-header${He?" list-section-header--collapsed":""}`,onClick:()=>De(we),"aria-expanded":!He,children:t.jsxs("th",{colSpan:me.size+(Q?1:0),className:"list-section-cell",children:[t.jsx(Wn,{size:14,className:`list-section-chevron${He?"":" list-section-chevron--expanded"}`}),t.jsx("span",{className:`list-section-dot dot-${we}`}),t.jsx("span",{className:"list-section-title",children:ds[we]}),t.jsx("span",{className:"list-section-count",children:ze.length})]})}),!He&&t.jsx(t.Fragment,{children:rt?t.jsx("tr",{className:"list-section-empty",children:t.jsx("td",{colSpan:me.size+(Q?1:0),className:"list-empty-cell",children:"No tasks"})}):ze.map(Ae=>{const pt=Ae.status==="failed",Ct=Ae.paused===!0,Tt=nc(Ae,O,_),Gt=!f&&!pt&&!Ct&&!Tt&&(Ae.column==="in-progress"||hf.has(Ae.status)),nn=Y===Ae.id;return t.jsxs("tr",{className:`list-row${pt?" failed":""}${Ct?" paused":""}${Tt?" stuck":""}${Gt?" agent-active":""}${nn?" dragging":""}${U===Ae.id?" list-row--selected":""}`,onClick:()=>un(Ae),draggable:!Ct,onDragStart:Ht=>gn(Ht,Ae),onDragEnd:cn,"data-id":Ae.id,children:[Q&&t.jsx("td",{className:"list-cell list-cell-checkbox",children:t.jsx("input",{type:"checkbox",checked:X.has(Ae.id),onChange:Ht=>{Ht.stopPropagation(),Te(Ae.id)},onClick:Ht=>Ht.stopPropagation(),disabled:Ae.column==="archived","aria-label":`Select ${Ae.id}`})}),me.has("title")&&t.jsx("td",{className:"list-cell list-cell-title",children:t.jsxs("div",{className:"list-title-content",children:[t.jsx("span",{className:"list-title-id",children:Ae.id}),t.jsxs("div",{className:"list-title-row",children:[Ae.executionMode==="fast"&&t.jsxs("span",{className:"list-execution-mode-badge list-execution-mode-badge--fast",title:"Fast mode","aria-label":"Fast mode",children:[t.jsx(as,{"aria-hidden":"true"}),t.jsx("span",{className:"visually-hidden",children:"Fast mode"})]}),t.jsx("span",{className:"list-title-text",children:Ae.title||Ae.description})]})]})}),me.has("status")&&t.jsx("td",{className:"list-cell",children:Ct&&Ae.pausedByAgentId?t.jsx("span",{className:"list-status-badge paused",children:"paused by agent"}):Tt?t.jsx("span",{className:"list-status-badge stuck",children:"Stuck"}):Ae.status?t.jsx("span",{className:`list-status-badge list-status-badge--${Ae.column}${pt?" failed":""}${Gt?" pulsing":""}`,children:pf(Ae.status??"")}):t.jsx("span",{className:"list-status-badge",children:"-"})}),me.has("column")&&t.jsx("td",{className:"list-cell",children:t.jsx("span",{className:"list-column-badge",style:{background:`color-mix(in srgb, ${jl[Ae.column]} 12%, transparent)`,color:jl[Ae.column]},children:ds[Ae.column]})}),me.has("dependencies")&&t.jsx("td",{className:"list-cell list-cell-deps",children:Ae.dependencies&&Ae.dependencies.length>0?t.jsxs("span",{className:"list-dep-badge",title:Ae.dependencies.join(", "),children:[t.jsx(Cr,{size:12})," ",Ae.dependencies.length]}):"-"}),me.has("progress")&&t.jsx("td",{className:"list-cell list-cell-progress",children:(()=>{const Ht=wf(Ae);return Ht.hasProgress?t.jsxs("div",{className:"list-progress",children:[t.jsx("div",{className:"list-progress-bar",children:t.jsx("div",{className:"list-progress-fill",style:{width:`${Ht.percent}%`,backgroundColor:jl[Ae.column]}})}),t.jsx("span",{className:"list-progress-label",children:Ht.label})]}):"-"})()})]},Ae.id)})})]},we)})})]})]}),!W&&t.jsxs(t.Fragment,{children:[t.jsx("div",{className:"list-split-resize-handle","data-testid":"list-split-resize-handle",onMouseDown:tn,onKeyDown:Yt,role:"separator",tabIndex:0,"aria-orientation":"vertical","aria-label":"Resize task list sidebar","aria-valuemin":oc,"aria-valuemax":Math.round(Tu(ct.current?.clientWidth??Ve/Iu+Nl)),"aria-valuenow":Math.round(Ve)}),t.jsx("div",{className:"list-split-detail","data-testid":"list-split-detail",children:Ue?t.jsx("div",{className:"list-split-detail-content","data-testid":"list-split-detail-content",children:t.jsx(Av,{task:Ue,projectId:k,tasks:e,embedded:!0,onOpenDetail:Wt,onMoveTask:n,onDeleteTask:a,onMergeTask:c,onRetryTask:s,onResetTask:d,onDuplicateTask:u,onTaskUpdated:we=>{se(ze=>!ze||ze.id!==we.id?ze:{...ze,...we})},addToast:m,prAuthAvailable:G})}):t.jsx("div",{className:"list-split-detail-empty",children:t.jsx("p",{children:"Select a task to view details"})})})]})]})})]})}const j$={active:{label:"Active",color:"var(--color-success)",icon:is},paused:{label:"Paused",color:"var(--color-warning)",icon:di},errored:{label:"Error",color:"var(--color-error)",icon:zs},initializing:{label:"Initializing",color:"var(--color-warning)",icon:St}};function N$(e){if(!e)return"Never";const n=new Date(e),a=new Date().getTime()-n.getTime(),r=Math.floor(a/6e4),o=Math.floor(a/36e5),l=Math.floor(a/864e5);return r<1?"Just now":r<60?`${r}m ago`:o<24?`${o}h ago`:l<7?`${l}d ago`:n.toLocaleDateString()}function kf(e,n=40){if(e.length<=n)return e;const s=e.slice(0,Math.floor(n/2)-2),a=e.slice(-Math.floor(n/2)+2);return`${s}...${a}`}function S$(e,n){if(e.project.id!==n.project.id||e.project.status!==n.project.status||e.project.name!==n.project.name||e.project.path!==n.project.path||e.project.lastActivityAt!==n.project.lastActivityAt||e.isLoading!==n.isLoading)return!1;const s=e.health,a=n.health;if(!s&&!a)return!0;if(!s||!a||s.activeTaskCount!==a.activeTaskCount||s.inFlightAgentCount!==a.inFlightAgentCount||s.totalTasksCompleted!==a.totalTasksCompleted||s.totalTasksFailed!==a.totalTasksFailed||s.status!==a.status)return!1;const r=e.availabilityMappings??[],o=n.availabilityMappings??[];return r.length!==o.length?!1:r.every((l,c)=>{const d=o[c];return!!d&&l.nodeId===d.nodeId&&l.path===d.path&&l.displayName===d.displayName&&l.available===d.available})}function C$({project:e,health:n,onSelect:s,onPause:a,onResume:r,onRemove:o,availabilityMappings:l=[],isLoading:c=!1}){const[d,u]=i.useState(!1),h=j$[e.status],m=h.icon,f=i.useCallback(()=>{s(e)},[s,e]),p=i.useCallback(j=>{j.stopPropagation(),a(e)},[a,e]),g=i.useCallback(j=>{j.stopPropagation(),r(e)},[r,e]),w=i.useCallback(j=>{if(j.stopPropagation(),!d){u(!0);return}o(e),u(!1)},[d,o,e]),v=e.status==="paused",b=e.status==="errored",y=e.status==="initializing";return t.jsxs("div",{className:`project-card ${c?"project-card-loading":""} ${b?"project-card-errored":""}`,onClick:f,"data-project-id":e.id,role:"button",tabIndex:0,onKeyDown:j=>{(j.key==="Enter"||j.key===" ")&&(j.preventDefault(),f())},children:[t.jsxs("div",{className:"project-card-header",children:[t.jsx("div",{className:"project-card-icon",children:t.jsx(ws,{size:20})}),t.jsxs("div",{className:"project-card-title-section",children:[t.jsx("h3",{className:"project-card-name",title:e.name,children:e.name}),l.length>0&&t.jsxs("div",{className:"project-card-availability","aria-label":"Project node availability",children:[l.slice(0,3).map(j=>t.jsxs("div",{className:"project-card-availability__row",title:`${j.displayName} → ${j.path}`,children:[t.jsx("span",{className:"project-card-availability__node",children:j.displayName}),t.jsx("span",{className:"project-card-availability__arrow",children:"→"}),t.jsx("code",{className:"project-card-availability__path",children:kf(j.path,28)})]},`${j.nodeId}-${j.path}`)),l.length>3&&t.jsxs("span",{className:"project-card-availability__more",children:["+",l.length-3," more"]})]}),t.jsx("span",{className:"project-card-path",title:e.path,children:kf(e.path)})]}),t.jsxs("div",{className:"project-card-status-badge",style:{color:h.color,borderColor:h.color},children:[t.jsx(m,{size:12,className:y?"animate-spin":""}),t.jsx("span",{children:h.label})]})]}),t.jsxs("div",{className:"project-card-health",children:[n&&t.jsxs(t.Fragment,{children:[t.jsxs("div",{className:"project-card-metric",children:[t.jsx("span",{className:"project-card-metric-value",children:n.activeTaskCount}),t.jsx("span",{className:"project-card-metric-label",children:"Active Tasks"})]}),t.jsxs("div",{className:"project-card-metric",children:[t.jsx("span",{className:"project-card-metric-value",children:n.inFlightAgentCount}),t.jsx("span",{className:"project-card-metric-label",children:"Agents"})]}),t.jsxs("div",{className:"project-card-metric",children:[t.jsx("span",{className:"project-card-metric-value",children:n.totalTasksCompleted}),t.jsx("span",{className:"project-card-metric-label",children:"Completed"})]})]}),!n&&t.jsx("div",{className:"project-card-metric project-card-metric-empty",children:t.jsx("span",{className:"project-card-metric-label",children:"No health data available"})})]}),t.jsxs("div",{className:"project-card-footer",children:[t.jsxs("div",{className:"project-card-activity",children:[t.jsx("span",{className:"project-card-activity-label",children:"Last activity:"}),t.jsx("span",{className:"project-card-activity-time",children:N$(e.lastActivityAt||n?.lastActivityAt)})]}),t.jsxs("div",{className:"project-card-actions",children:[v?t.jsxs("button",{className:"project-card-action project-card-action-resume",onClick:g,disabled:c,title:"Resume project","aria-label":"Resume project",children:[t.jsx(is,{size:14}),t.jsx("span",{children:"Resume"})]}):t.jsxs("button",{className:"project-card-action project-card-action-pause",onClick:p,disabled:c||y,title:y?"Cannot pause while initializing":"Pause project","aria-label":"Pause project",children:[t.jsx(di,{size:14}),t.jsx("span",{children:"Pause"})]}),t.jsxs("button",{className:"project-card-action project-card-action-open",onClick:f,disabled:c,title:"Open project","aria-label":"Open project",children:[t.jsx(Ho,{size:14}),t.jsx("span",{children:"Open"})]}),t.jsxs("button",{className:`project-card-action project-card-action-remove ${d?"is-armed":""}`,onClick:w,disabled:c,title:d?"Confirm remove":"Remove project","aria-label":d?"Confirm remove project":"Remove project",children:[t.jsx(In,{size:14}),t.jsx("span",{children:d?"Confirm":""})]})]})]})]})}const E$=i.memo(C$,S$);function jf(e){return typeof e=="string"&&e.trim().length>0}function No(e){return(e.nodeMappings??[]).filter(s=>jf(s.nodeId)&&jf(s.path)).map(s=>({nodeId:s.nodeId,nodeName:s.nodeName,path:s.path,available:s.available!==!1}))}function _$(e,n){return No(e).filter(s=>s.nodeId===n.id&&s.available)}function M$(e,n){return _$(e,n).length>0}function A$(e,n){return e.filter(s=>M$(s,n))}function Z8(e,n){return A$(e,n).length}function Nf(e,n,s,a){const r=s.find(o=>o.id===e);return r?.name?r.name:n?.nodeName?n.nodeName:a._sourceNodeName?a._sourceNodeName:e}function R$(){return t.jsxs("div",{className:"project-overview project-overview--loading",children:[t.jsx("div",{className:"project-overview__header-skeleton",children:t.jsxs("div",{className:"project-overview__stats-row",children:[t.jsxs("div",{className:"project-overview__stat-skeleton",children:[t.jsx("div",{className:"project-skeleton project-skeleton--icon",children:t.jsx(ws,{size:20,className:"project-skeleton-icon"})}),t.jsx("div",{className:"project-skeleton project-skeleton--value"}),t.jsx("div",{className:"project-skeleton project-skeleton--label"})]}),t.jsxs("div",{className:"project-overview__stat-skeleton",children:[t.jsx("div",{className:"project-skeleton project-skeleton--icon",children:t.jsx(Vs,{size:20,className:"project-skeleton-icon"})}),t.jsx("div",{className:"project-skeleton project-skeleton--value"}),t.jsx("div",{className:"project-skeleton project-skeleton--label"})]}),t.jsxs("div",{className:"project-overview__stat-skeleton",children:[t.jsx("div",{className:"project-skeleton project-skeleton--icon",children:t.jsx(Zn,{size:20,className:"project-skeleton-icon"})}),t.jsx("div",{className:"project-skeleton project-skeleton--value"}),t.jsx("div",{className:"project-skeleton project-skeleton--label"})]}),t.jsxs("div",{className:"project-overview__stat-skeleton",children:[t.jsx("div",{className:"project-skeleton project-skeleton--icon",children:t.jsx(zs,{size:20,className:"project-skeleton-icon"})}),t.jsx("div",{className:"project-skeleton project-skeleton--value"}),t.jsx("div",{className:"project-skeleton project-skeleton--label"})]})]})}),t.jsxs("div",{className:"project-overview__filters-skeleton",children:[t.jsx("div",{className:"project-skeleton project-skeleton--tab"}),t.jsx("div",{className:"project-skeleton project-skeleton--tab"}),t.jsx("div",{className:"project-skeleton project-skeleton--tab"}),t.jsx("div",{className:"project-skeleton project-skeleton--tab"})]}),t.jsx("div",{className:"project-grid project-grid--skeleton",children:Array.from({length:6}).map((e,n)=>t.jsxs("div",{className:"project-card project-card--skeleton",children:[t.jsxs("div",{className:"project-card-skeleton__header",children:[t.jsx("div",{className:"project-skeleton project-skeleton--icon-circle"}),t.jsxs("div",{className:"project-skeleton__text-group",children:[t.jsx("div",{className:"project-skeleton project-skeleton--title"}),t.jsx("div",{className:"project-skeleton project-skeleton--path"})]}),t.jsx("div",{className:"project-skeleton project-skeleton--badge"})]}),t.jsxs("div",{className:"project-card-skeleton__health",children:[t.jsx("div",{className:"project-skeleton project-skeleton--metric"}),t.jsx("div",{className:"project-skeleton project-skeleton--metric"}),t.jsx("div",{className:"project-skeleton project-skeleton--metric"})]}),t.jsxs("div",{className:"project-card-skeleton__footer",children:[t.jsx("div",{className:"project-skeleton project-skeleton--activity"}),t.jsx("div",{className:"project-skeleton project-skeleton--actions"})]})]},n))})]})}const I$=1e4,Sf=5;function T$(e){const[n,s]=i.useState({}),[a,r]=i.useState(!0),[o,l]=i.useState(null),c=i.useRef(null),d=i.useRef(null),u=i.useRef(!1),h=i.useCallback(async()=>{if(e.length===0){s({}),u.current||(u.current=!0),r(!1);return}d.current&&d.current.abort(),d.current=new AbortController,!u.current&&r(!0),l(null);try{const p={};for(let g=0;g<e.length;g+=Sf){const w=e.slice(g,g+Sf),v=await Promise.allSettled(w.map(async b=>{try{return await uh(b)}catch{return null}}));if(w.forEach((b,y)=>{const j=v[y];p[b]=j.status==="fulfilled"?j.value:null}),d.current?.signal.aborted)return}s(p),u.current=!0}catch(p){if(p instanceof Error&&p.name==="AbortError")return;l(p instanceof Error?p.message:"Failed to fetch health data"),u.current=!0}finally{r(!1)}},[e]),m=i.useCallback(async f=>{try{const p=await uh(f);s(g=>({...g,[f]:p}))}catch(p){console.error(`Failed to fetch health for project ${f}:`,p)}},[]);return i.useEffect(()=>(u.current=!1,h(),()=>{d.current&&d.current.abort()}),[h]),i.useEffect(()=>{if(e.length!==0)return c.current&&clearInterval(c.current),c.current=setInterval(()=>{h()},I$),()=>{c.current&&(clearInterval(c.current),c.current=null)}},[h,e.length]),{healthMap:n,loading:a,error:o,refresh:h,refreshProject:m}}function P$({projects:e,loading:n=!1,onSelectProject:s,onAddProject:a,onPauseProject:r,onResumeProject:o,onRemoveProject:l,nodes:c=[]}){const[d,u]=i.useState("all"),[h,m]=i.useState(null),[f,p]=i.useState("activity"),[g,w]=i.useState("desc");i.useEffect(()=>{if(typeof window>"u")return;const H=localStorage.getItem("kb-dashboard-recent-projects");if(H)try{const A=JSON.parse(H);b(A)}catch{}},[]);const[v,b]=i.useState([]),y=i.useMemo(()=>e.map(H=>H.id),[e]),{healthMap:j,loading:S}=T$(y),C=i.useMemo(()=>e.map(H=>({project:H,health:j[H.id]||null})),[e,j]),x=i.useMemo(()=>{let H=[...C];return d!=="all"&&(H=H.filter(({project:A})=>A.status===d)),h!==null&&(H=H.filter(({project:A})=>No(A).some(P=>P.available&&P.nodeId===h))),H},[C,d,h]),k=i.useMemo(()=>{const H=[...x];return H.sort((A,P)=>{let q=0;switch(f){case"name":q=A.project.name.localeCompare(P.project.name);break;case"activity":{const Y=A.project.lastActivityAt||A.health?.lastActivityAt||A.project.updatedAt,ge=P.project.lastActivityAt||P.health?.lastActivityAt||P.project.updatedAt;q=new Date(ge).getTime()-new Date(Y).getTime();break}case"status":{const Y={errored:0,initializing:1,paused:2,active:3};q=Y[A.project.status]-Y[P.project.status];break}}return g==="asc"?q:-q}),H},[x,f,g]),R=i.useMemo(()=>{const H=e.length,A=e.filter($=>$.status==="active").length,P=e.filter($=>$.status==="errored").length,q=new Set;e.forEach($=>{No($).forEach(D=>{D.available&&q.add(D.nodeId)})});const Y=q.size;let ge=0,L=0,M=0;return Object.values(j).forEach($=>{$&&(ge+=$.activeTaskCount,L+=$.totalTasksCompleted,M+=$.inFlightAgentCount)}),{totalProjects:H,activeProjects:A,erroredProjects:P,totalNodes:Y,totalActiveTasks:ge,totalCompletedTasks:L,totalInFlightAgents:M}},[e,j]),O=i.useMemo(()=>({all:e.length,active:e.filter(H=>H.status==="active").length,paused:e.filter(H=>H.status==="paused").length,errored:e.filter(H=>H.status==="errored").length}),[e]),E=i.useMemo(()=>{const H=new Map;return e.forEach(A=>{No(A).filter(P=>P.available).forEach(P=>{const q=P.nodeId,Y=H.get(q),ge=Nf(q,P,c,A);Y?Y.count+=1:H.set(q,{name:ge,count:1})})}),Array.from(H.entries()).map(([A,{name:P,count:q}])=>({nodeId:A,name:P,count:q}))},[e,c]),_=i.useCallback(H=>{const A=[H.id,...v.filter(P=>P!==H.id)].slice(0,3);b(A),typeof window<"u"&&localStorage.setItem("kb-dashboard-recent-projects",JSON.stringify(A)),s(H)},[s,v]);return n||S&&e.length>0&&Object.keys(j).length===0?t.jsx(R$,{}):e.length===0?t.jsx("div",{className:"project-overview project-overview--empty",children:t.jsxs("div",{className:"project-empty-state",children:[t.jsx("div",{className:"project-empty-state__icon",children:t.jsx(ma,{size:48})}),t.jsx("h2",{className:"project-empty-state__title",children:"No Projects Found"}),t.jsx("p",{className:"project-empty-state__description",children:"Get started by adding your first project. Projects allow you to organize and track tasks across multiple repositories."}),t.jsxs("button",{className:"btn btn-primary project-empty-state__cta",onClick:a,children:[t.jsx(Tn,{size:16}),"Add Your First Project"]})]})}):t.jsxs("div",{className:"project-overview",children:[t.jsxs("div",{className:"project-overview__header",children:[t.jsxs("h2",{className:"project-overview__title",children:[t.jsx(va,{size:20}),"Projects"]}),t.jsxs("div",{className:"project-overview__stats",children:[t.jsxs("div",{className:"project-stat",children:[t.jsx("div",{className:"project-stat__icon",children:t.jsx(ws,{size:16})}),t.jsxs("div",{className:"project-stat__content",children:[t.jsx("span",{className:"project-stat__value",children:R.totalProjects}),t.jsx("span",{className:"project-stat__label",children:"Total"})]})]}),t.jsxs("div",{className:"project-stat project-stat--active",children:[t.jsx("div",{className:"project-stat__icon",children:t.jsx(Vs,{size:16})}),t.jsxs("div",{className:"project-stat__content",children:[t.jsx("span",{className:"project-stat__value",children:R.totalActiveTasks}),t.jsx("span",{className:"project-stat__label",children:"Active Tasks"})]})]}),t.jsxs("div",{className:"project-stat project-stat--completed",children:[t.jsx("div",{className:"project-stat__icon",children:t.jsx(Zn,{size:16})}),t.jsxs("div",{className:"project-stat__content",children:[t.jsx("span",{className:"project-stat__value",children:R.totalCompletedTasks}),t.jsx("span",{className:"project-stat__label",children:"Completed"})]})]}),R.erroredProjects>0&&t.jsxs("div",{className:"project-stat project-stat--error",children:[t.jsx("div",{className:"project-stat__icon",children:t.jsx(zs,{size:16})}),t.jsxs("div",{className:"project-stat__content",children:[t.jsx("span",{className:"project-stat__value",children:R.erroredProjects}),t.jsx("span",{className:"project-stat__label",children:"Errored"})]})]}),R.totalNodes>1&&t.jsxs("div",{className:"project-stat project-stat--nodes",children:[t.jsx("div",{className:"project-stat__icon",children:t.jsx($o,{size:16})}),t.jsxs("div",{className:"project-stat__content",children:[t.jsx("span",{className:"project-stat__value",children:R.totalNodes}),t.jsx("span",{className:"project-stat__label",children:"Nodes"})]})]})]}),t.jsxs("button",{className:"btn btn-primary project-overview__add-btn",onClick:a,children:[t.jsx(Tn,{size:16}),"Add Project"]})]}),t.jsxs("div",{className:"project-overview__filters",children:[t.jsxs("div",{className:"project-filter-tabs",children:[t.jsxs("button",{className:`project-filter-tab ${d==="all"?"active":""}`,onClick:()=>u("all"),children:["All",t.jsx("span",{className:"project-filter-count",children:O.all})]}),t.jsxs("button",{className:`project-filter-tab ${d==="active"?"active":""}`,onClick:()=>u("active"),children:["Active",t.jsx("span",{className:"project-filter-count",children:O.active})]}),t.jsxs("button",{className:`project-filter-tab ${d==="paused"?"active":""}`,onClick:()=>u("paused"),children:["Paused",t.jsx("span",{className:"project-filter-count",children:O.paused})]}),t.jsxs("button",{className:`project-filter-tab ${d==="errored"?"active":""} ${O.errored>0?"has-errors":""}`,onClick:()=>u("errored"),children:["Errored",t.jsx("span",{className:"project-filter-count",children:O.errored})]})]}),E.length>1&&t.jsxs("div",{className:"project-node-filter",children:[t.jsx($o,{size:14}),t.jsxs("select",{value:h??"",onChange:H=>{m(H.target.value||null)},className:"project-node-filter-select","aria-label":"Filter by node",children:[t.jsx("option",{value:"",children:"All Nodes"}),E.map(({nodeId:H,name:A,count:P})=>t.jsxs("option",{value:H??"",children:[A," (",P,")"]},H??"local"))]})]}),t.jsxs("div",{className:"project-sort",children:[t.jsx(Gl,{size:14}),t.jsxs("select",{value:`${f}-${g}`,onChange:H=>{const[A,P]=H.target.value.split("-");p(A),w(P)},className:"project-sort-select","aria-label":"Sort projects",children:[t.jsx("option",{value:"activity-desc",children:"Last Activity (Newest)"}),t.jsx("option",{value:"activity-asc",children:"Last Activity (Oldest)"}),t.jsx("option",{value:"name-asc",children:"Name (A-Z)"}),t.jsx("option",{value:"name-desc",children:"Name (Z-A)"}),t.jsx("option",{value:"status-asc",children:"Status (Error → Active)"}),t.jsx("option",{value:"status-desc",children:"Status (Active → Error)"})]}),t.jsx(ab,{size:14})]})]}),t.jsx("div",{className:"project-grid",children:k.map(({project:H,health:A})=>{const P=No(H).filter(q=>q.available).map(q=>({...q,displayName:Nf(q.nodeId,q,c,H)}));return t.jsx(E$,{project:H,health:A,availabilityMappings:P,onSelect:_,onPause:r,onResume:o,onRemove:l},H.id)})}),k.length===0&&t.jsxs("div",{className:"project-overview__no-results",children:[t.jsx(Gl,{size:32}),t.jsx("p",{children:"No projects match the current filter"}),t.jsx("button",{className:"btn btn-secondary",onClick:()=>u("all"),children:"Show All Projects"})]})]})}const Iv=i.createContext(null);function $$({value:e,children:n}){return i.createElement(Iv.Provider,{value:e},n)}function Tv(){const e=i.useContext(Iv);if(!e)throw new Error("useNavigationHistoryContext must be used within a NavigationHistoryProvider");return e}function D$(e){const{enabled:n}=e,s=i.useRef([]),a=i.useRef(!1),r=i.useRef(n);r.current=n;const o=i.useCallback(c=>{if(!r.current||a.current)return;const d=s.current[s.current.length-1];if(d){const m=d.type==="modal"?d.close:d.revert,f=c.type==="modal"?c.close:c.revert;if(m===f)return}s.current.push(c);const u=s.current.length,h=typeof window<"u"&&window.history.state?window.history.state:{};window.history.pushState({...h,navIndex:u},"")},[]),l=i.useCallback(c=>{if(!r.current||s.current.length===0)return;s.current[s.current.length-1]=c;const d=s.current.length,u=typeof window<"u"&&window.history.state?window.history.state:{};window.history.replaceState({...u,navIndex:d},"")},[]);return i.useEffect(()=>{if(typeof window>"u")return;const c=d=>{if(!r.current)return;const u=d.state?.navIndex??0,h=s.current.length;if(u>=h)return;const m=h-u;if(!(m<=0)){a.current=!0;try{for(let f=0;f<m;f++){const p=s.current.pop();p&&(p.type==="modal"?p.close():p.revert())}}finally{a.current=!1}}};return window.addEventListener("popstate",c),()=>{window.removeEventListener("popstate",c)}},[]),{pushNav:o,replaceCurrent:l}}const _m="kb-planning-last-description",Mm="kb-subtask-last-description",Am="kb-mission-last-goal";function L$(e,n){rs(_m,e,n)}function O$(e){return Ln(_m,e)||""}function pr(e){qa(_m,e)}function F$(e,n){rs(Mm,e,n)}function z$(e){return Ln(Mm,e)||""}function Dd(e){qa(Mm,e)}function B$(e,n){rs(Am,e,n)}function U$(e){return Ln(Am,e)||""}function da(e){qa(Am,e)}function H$(e){const{question:n,response:s}=e;if(!n)return s;if(s&&typeof s=="object"&&!Array.isArray(s)){const a=s;if(n.id in a)return a[n.id]}return s}function q$(e,n){switch(e.type){case"text":return typeof n=="string"?n:n==null?"":String(n);case"single_select":return typeof n=="string"?e.options?.find(a=>a.id===n)?.label??n:n==null?"":String(n);case"multi_select":return Array.isArray(n)?n.map(s=>typeof s!="string"?String(s):e.options?.find(r=>r.id===s)?.label??s).join(", "):n==null?"":String(n);case"confirm":return n===!0?"Yes":n===!1?"No":n==null?"":String(n);default:return n==null?"":JSON.stringify(n)}}function V$(e){let n=0;const s=[];for(const a of e){if(a.question){n+=1,s.push({...a,questionNumber:n});continue}a.thinkingOutput&&s.push({...a,questionNumber:null})}return s}function ui({entries:e,defaultShowThinking:n=!1}){const[s,a]=i.useState({}),r=V$(e);return r.length===0?null:t.jsx("div",{className:"conversation-history","data-testid":"conversation-history",children:r.map((o,l)=>{const c=!!o.question,d=!!o.thinkingOutput,u=s[l]??n,h=c?H$(o):void 0,m=o.question&&h!==void 0?q$(o.question,h):"",f=o.response&&typeof o.response=="object"&&!Array.isArray(o.response)?o.response:void 0,p=typeof f?._comment=="string"?f._comment.trim():"";return t.jsxs("div",{className:"conversation-entry",children:[c?t.jsxs("div",{className:"conversation-entry-question",children:[t.jsxs("span",{className:"conversation-entry-question-label",children:["Q",o.questionNumber]}),t.jsx("p",{children:o.question?.question})]}):t.jsx("div",{className:"conversation-entry-question",children:t.jsx("span",{className:"conversation-entry-question-label",children:"AI Reasoning"})}),c&&t.jsxs("div",{className:"conversation-entry-response",children:[t.jsx("strong",{children:"Your response"}),t.jsx("p",{children:m||"—"}),p&&t.jsxs("p",{className:"conversation-comment",children:["💬 ",p]})]}),d&&t.jsxs("div",{className:"conversation-entry-thinking",children:[t.jsxs("button",{type:"button",className:"conversation-thinking-toggle",onClick:()=>{a(g=>({...g,[l]:!u}))},"aria-expanded":u,children:[t.jsx("span",{"aria-hidden":"true",children:u?"▾":"▸"}),u?`Hide ${c?"AI thinking":"AI reasoning"}`:`Show ${c?"AI thinking":"AI reasoning"}`]}),u&&t.jsx("pre",{children:o.thinkingOutput})]})]},`${o.question?.id??"thinking"}-${l}`)})})}const Cf="fusion-tab-id";function W$(){const e=globalThis.crypto;return e&&typeof e.randomUUID=="function"?e.randomUUID():`tab-${Date.now()}-${Math.random().toString(36).slice(2,10)}`}function Ya(){if(typeof window>"u")return"server-tab";const e=window.sessionStorage.getItem(Cf);if(e)return e;const n=W$();return window.sessionStorage.setItem(Cf,n),n}function $c(e){const n=i.useMemo(()=>Ya(),[]),[s,a]=i.useState(!1),[r,o]=i.useState(null),[l,c]=i.useState(!1);i.useEffect(()=>{if(!e){a(!1),o(null),c(!1);return}let u=!0;return c(!0),Promise.resolve(Y0(e,n)).then(h=>{if(u){if(h.acquired){a(!1),o(null);return}a(!0),o(h.currentHolder)}}).catch(()=>{u&&(a(!1),o(null))}).finally(()=>{u&&c(!1)}),()=>{u=!1;try{const h=Q0(e,n);h&&typeof h.catch=="function"&&h.catch(()=>{})}catch{}}},[e,n]),i.useEffect(()=>{if(!e||typeof window>"u")return;const u=()=>{if(typeof navigator.sendBeacon!="function")return;const h=Li(`/api/ai-sessions/${encodeURIComponent(e)}/lock/beacon?tabId=${encodeURIComponent(n)}`);navigator.sendBeacon(h)};return window.addEventListener("beforeunload",u),()=>{window.removeEventListener("beforeunload",u)}},[e,n]),i.useEffect(()=>!e||typeof EventSource>"u"?void 0:fi("/api/events",{events:{"ai_session:updated":h=>{try{const m=JSON.parse(h.data);if(m.id!==e)return;const f=m.lockedByTab??null;o(f),a(!!(f&&f!==n))}catch{}}}}),[e,n]);const d=i.useCallback(async()=>{if(e){c(!0);try{await Promise.resolve(X0(e,n)),a(!1),o(null)}finally{c(!1)}}},[e,n]);return{isLockedByOther:s,currentHolder:r,takeControl:d,isLoading:l}}const G$="fusion:ai-session-sync",Ef="fusion:ai-session-sync",K$=3e4,J$=6e4;function Ri(){return Date.now()}function Y$(){const e=globalThis.crypto;return e&&typeof e.randomUUID=="function"?e.randomUUID():`tab-${Date.now()}-${Math.random().toString(36).slice(2,10)}`}function _f(e){if(!e||typeof e!="object")return null;const n=e;return typeof n.type!="string"||typeof n.timestamp!="number"||!Number.isFinite(n.timestamp)?null:e}class Q${tabId;listeners=new Set;sessionStates=new Map;ownershipBySession=new Map;heartbeatByTab=new Map;ownedSessions=new Map;snapshot;channel=null;usingStorageFallback=!1;cleanupStorageListener=null;cleanupBeforeUnload=null;heartbeatInterval=null;staleSweepInterval=null;constructor(){this.tabId=Y$(),this.snapshot={tabId:this.tabId,sessions:new Map,activeTabMap:new Map},this.isBrowser()&&(this.initializeTransport(),this.startHeartbeat(),this.startStaleSweep(),this.setupBeforeUnloadCleanup())}subscribe(n){return this.listeners.add(n),()=>{this.listeners.delete(n)}}getSnapshot(){return this.snapshot}requestSync(){this.publish({type:"sync:request",tabId:this.tabId,timestamp:Ri()})}broadcastUpdate(n){const s=n.timestamp??Ri();this.applySessionUpdate({sessionId:n.sessionId,status:n.status,needsInput:n.needsInput??n.status==="awaiting_input",owningTabId:n.owningTabId,type:n.type,title:n.title,projectId:n.projectId,updatedAt:n.updatedAt},s),this.publish({type:"session:updated",sessionId:n.sessionId,status:n.status,needsInput:n.needsInput,owningTabId:n.owningTabId,sessionType:n.type,title:n.title,projectId:n.projectId,updatedAt:n.updatedAt,timestamp:s})}broadcastCompleted(n){const s=n.status??"complete",a=n.timestamp??Ri();this.applySessionUpdate({sessionId:n.sessionId,status:s,needsInput:!1,owningTabId:null},a),this.ownershipBySession.delete(n.sessionId),this.ownedSessions.delete(n.sessionId),this.emit(),this.publish({type:"session:completed",sessionId:n.sessionId,status:s,timestamp:a})}broadcastLock(n,s){const a=Ri();this.applyTabOwnership(n,s,a),this.ownedSessions.set(n,s),this.publish({type:"tab:active",tabId:s,sessionId:n,timestamp:a})}broadcastUnlock(n,s){const a=Ri();this.releaseTabOwnership(n,s,a),this.ownedSessions.delete(n),this.publish({type:"tab:inactive",tabId:s,sessionId:n,timestamp:a})}broadcastHeartbeat(n){const s=Ri();this.updateHeartbeat(n,s),this.publish({type:"tab:heartbeat",tabId:n,timestamp:s})}destroy(){this.cleanupStorageListener?.(),this.cleanupStorageListener=null,this.cleanupBeforeUnload?.(),this.cleanupBeforeUnload=null,this.channel&&(this.channel.close(),this.channel=null),this.heartbeatInterval&&(clearInterval(this.heartbeatInterval),this.heartbeatInterval=null),this.staleSweepInterval&&(clearInterval(this.staleSweepInterval),this.staleSweepInterval=null)}reset(){this.sessionStates.clear(),this.ownershipBySession.clear(),this.heartbeatByTab.clear(),this.ownedSessions.clear(),this.snapshot={tabId:this.tabId,sessions:new Map,activeTabMap:new Map},this.emit()}isBrowser(){return typeof window<"u"}initializeTransport(){if(typeof BroadcastChannel<"u")try{this.channel=new BroadcastChannel(G$),this.channel.onmessage=s=>{const a=_f(s.data);a&&this.handleIncomingMessage(a)},this.usingStorageFallback=!1;return}catch{}this.usingStorageFallback=!0;const n=s=>{if(!(s.key!==Ef||!s.newValue))try{const a=JSON.parse(s.newValue),r=_f(a.message);r&&this.handleIncomingMessage(r)}catch{}};window.addEventListener("storage",n),this.cleanupStorageListener=()=>{window.removeEventListener("storage",n)}}startHeartbeat(){this.heartbeatInterval=setInterval(()=>{const n=Ri();this.updateHeartbeat(this.tabId,n),this.publish({type:"tab:heartbeat",tabId:this.tabId,timestamp:n})},K$)}startStaleSweep(){this.staleSweepInterval=setInterval(()=>{this.emit()},1e4)}setupBeforeUnloadCleanup(){const n=()=>{for(const[s,a]of this.ownedSessions.entries()){const r=Ri();this.publish({type:"tab:inactive",tabId:a,sessionId:s,timestamp:r})}};window.addEventListener("beforeunload",n),this.cleanupBeforeUnload=()=>{window.removeEventListener("beforeunload",n)}}publish(n){const s={...n,senderTabId:this.tabId};if(this.channel){this.channel.postMessage(s);return}if(this.usingStorageFallback)try{const a={id:`${s.type}-${s.timestamp}-${Math.random().toString(36).slice(2,8)}`,message:s};window.localStorage.setItem(Ef,JSON.stringify(a))}catch{}}handleIncomingMessage(n){switch(n.type){case"session:updated":{this.applySessionUpdate({sessionId:n.sessionId,status:n.status,needsInput:n.needsInput,owningTabId:n.owningTabId,type:n.sessionType,title:n.title,projectId:n.projectId,updatedAt:n.updatedAt},n.timestamp);return}case"session:completed":{this.applySessionUpdate({sessionId:n.sessionId,status:n.status??"complete",needsInput:!1,owningTabId:null},n.timestamp),this.ownershipBySession.delete(n.sessionId),this.emit();return}case"tab:active":{this.applyTabOwnership(n.sessionId,n.tabId,n.timestamp);return}case"tab:inactive":{this.releaseTabOwnership(n.sessionId,n.tabId,n.timestamp);return}case"tab:heartbeat":{this.updateHeartbeat(n.tabId,n.timestamp);return}case"sync:request":{if(n.tabId===this.tabId)return;const s=[...this.sessionStates.values()].map(o=>{const l=this.ownershipBySession.get(o.sessionId);return{...o,owningTabId:l?.tabId??o.owningTabId??null}}),a=[...this.ownershipBySession.entries()].map(([o,l])=>({sessionId:o,tabId:l.tabId,timestamp:l.timestamp})),r=[...this.heartbeatByTab.entries()].map(([o,l])=>({tabId:o,timestamp:l}));this.publish({type:"sync:response",tabId:n.tabId,sessions:s,locks:a,heartbeats:r,timestamp:Ri()});return}case"sync:response":{if(n.tabId!==this.tabId)return;for(const s of n.sessions)this.applySessionUpdate({sessionId:s.sessionId,status:s.status,needsInput:s.needsInput,owningTabId:s.owningTabId,type:s.type,title:s.title,projectId:s.projectId,updatedAt:s.updatedAt},s.lastEventTimestamp,!1);for(const s of n.locks??[])this.applyTabOwnership(s.sessionId,s.tabId,s.timestamp,!1);for(const s of n.heartbeats??[])this.updateHeartbeat(s.tabId,s.timestamp,!1);this.emit();return}default:return}}applySessionUpdate(n,s,a=!0){const r=this.sessionStates.get(n.sessionId);if(r&&s<r.lastEventTimestamp)return;const o=this.ownershipBySession.get(n.sessionId),l={sessionId:n.sessionId,status:n.status,needsInput:n.needsInput??n.status==="awaiting_input",lastEventTimestamp:s,owningTabId:n.owningTabId??o?.tabId??r?.owningTabId??null,type:n.type??r?.type,title:n.title??r?.title,projectId:n.projectId??r?.projectId,updatedAt:n.updatedAt??new Date(s).toISOString()};this.sessionStates.set(n.sessionId,l),n.owningTabId!==void 0&&(n.owningTabId?this.applyTabOwnership(n.sessionId,n.owningTabId,s,!1):this.ownershipBySession.delete(n.sessionId)),a&&this.emit()}applyTabOwnership(n,s,a,r=!0){const o=this.ownershipBySession.get(n);if(o&&a<o.timestamp)return;this.ownershipBySession.set(n,{tabId:s,timestamp:a}),this.updateHeartbeat(s,a,!1);const l=this.sessionStates.get(n);l&&a>=l.lastEventTimestamp&&this.sessionStates.set(n,{...l,owningTabId:s,lastEventTimestamp:a}),r&&this.emit()}releaseTabOwnership(n,s,a,r=!0){const o=this.ownershipBySession.get(n);if(!o||o.tabId!==s||a<o.timestamp)return;this.ownershipBySession.delete(n);const l=this.sessionStates.get(n);l&&a>=l.lastEventTimestamp&&this.sessionStates.set(n,{...l,owningTabId:null,lastEventTimestamp:a}),r&&this.emit()}updateHeartbeat(n,s,a=!0){const r=this.heartbeatByTab.get(n);r!==void 0&&s<r||(this.heartbeatByTab.set(n,s),a&&this.emit())}emit(){const n=Ri(),s=new Map;for(const[r,o]of this.sessionStates.entries()){const l=this.ownershipBySession.get(r);s.set(r,{...o,owningTabId:l?.tabId??o.owningTabId??null})}const a=new Map;for(const[r,o]of this.ownershipBySession.entries()){const l=this.heartbeatByTab.get(o.tabId)??o.timestamp,c=n-l>J$;a.set(r,{sessionId:r,tabId:o.tabId,lastHeartbeatTimestamp:l,lastLockTimestamp:o.timestamp,stale:c})}this.snapshot={tabId:this.tabId,sessions:s,activeTabMap:a};for(const r of this.listeners)r()}}const Ii=new Q$;function Gr(){const e=i.useSyncExternalStore(c=>Ii.subscribe(c),()=>Ii.getSnapshot(),()=>Ii.getSnapshot());i.useEffect(()=>{Ii.requestSync()},[]);const n=i.useCallback(c=>{Ii.broadcastUpdate(c)},[]),s=i.useCallback(c=>{Ii.broadcastCompleted(c)},[]),a=i.useCallback((c,d)=>{Ii.broadcastLock(c,d)},[]),r=i.useCallback((c,d)=>{Ii.broadcastUnlock(c,d)},[]),o=i.useCallback(c=>{Ii.broadcastHeartbeat(c)},[]),l=i.useCallback(()=>{Ii.requestSync()},[]);return{tabId:e.tabId,sessions:e.sessions,activeTabMap:e.activeTabMap,broadcastUpdate:n,broadcastCompleted:s,broadcastLock:a,broadcastUnlock:r,broadcastHeartbeat:o,requestSync:l}}function X$(e,n){return e&&n?`${e}/${n}`:""}function Z$(e){if(!e)return{provider:void 0,modelId:void 0};const n=e.indexOf("/");return n===-1?{provider:void 0,modelId:void 0}:{provider:e.slice(0,n),modelId:e.slice(n+1)}}const e4=["Build a real-time collaborative document editor","Create a customer onboarding flow with email verification","Add a reporting dashboard with charts and CSV export","Implement a plugin system with marketplace"];function t4({isOpen:e,onClose:n,onMissionCreated:s,projectId:a,initialGoal:r,resumeSessionId:o}){Si(e);const[l,c]=i.useState(""),[d,u]=i.useState({type:"initial"}),[h,m]=i.useState(null),[f,p]=i.useState([]),[g,w]=i.useState([]),[v,b]=i.useState(null),[y,j]=i.useState(!1),S=i.useRef(!1),[C,x]=i.useState(""),[k,R]=i.useState(!0),[O,E]=i.useState(!1),[_,G]=i.useState(!1),[H,A]=i.useState(!1),P=i.useRef(null),q=i.useRef(null),Y=i.useRef(null),ge=i.useRef(null),[L,M]=i.useState(o??null),$=i.useMemo(()=>Ya(),[]),{isLockedByOther:D,takeControl:N,isLoading:W}=$c(e?L:null),{activeTabMap:de,broadcastUpdate:me,broadcastCompleted:Ne,broadcastLock:ve,broadcastUnlock:Me,broadcastHeartbeat:ie}=Gr(),{confirm:ye}=ti(),[Z,fe]=i.useState(void 0),[Q,F]=i.useState(void 0),[X,re]=i.useState([]),[U,be]=i.useState(!0),[Ue,se]=i.useState(null),[Ve,Le]=i.useState([]),[ct,Ke]=i.useState([]),oe=X$(Z,Q);i.useEffect(()=>{(async()=>{try{be(!0);const K=await Bs();re(K.models),Le(K.favoriteProviders),Ke(K.favoriteModels)}catch(K){se(Ie(K)||"Failed to load models")}finally{be(!1)}})()},[]);const Te=i.useCallback(Ge=>{Le(K=>{const ue=K,xe=ue.includes(Ge)?ue.filter(dt=>dt!==Ge):[Ge,...ue];return Fn({favoriteProviders:xe,favoriteModels:ct}).catch(()=>{Le(ue)}),xe})},[ct]),Fe=i.useCallback(Ge=>{Ke(K=>{const ue=K,xe=ue.includes(Ge)?ue.filter(dt=>dt!==Ge):[Ge,...ue];return Fn({favoriteProviders:Ve,favoriteModels:xe}).catch(()=>{Ke(ue)}),xe})},[Ve]),mt=i.useCallback((Ge,K)=>{if(!Ge||!K)return"Using default";const ue=X.find(ot=>ot.provider===Ge&&ot.id===K);return ue?`${ue.provider}/${ue.id}`:`${Ge}/${K}`},[X]),We=i.useCallback(Ge=>{q.current?.close();const K=D0(Ge,a,{onThinking:ue=>{x(ot=>ot+ue),me({sessionId:Ge,status:"generating",needsInput:!1,owningTabId:$,type:"mission_interview",title:l.trim()||void 0,projectId:a??null})},onQuestion:ue=>{E(!1),G(!1),da(a),u({type:"question",sessionId:Ge,question:ue}),x(""),j(!0),me({sessionId:Ge,status:"awaiting_input",needsInput:!0,owningTabId:$,type:"mission_interview",title:l.trim()||void 0,projectId:a??null})},onSummary:ue=>{E(!1),G(!1),da(a),u({type:"summary",sessionId:Ge,summary:ue}),b(ue),x(""),j(!0),me({sessionId:Ge,status:"complete",needsInput:!1,owningTabId:$,type:"mission_interview",title:l.trim()||void 0,projectId:a??null})},onError:ue=>{const ot=ue||"Session failed while contacting the AI.";E(!1),G(!1),m(null),u({type:"error",sessionId:Ge,errorMessage:ot}),x(""),j(!0),Y.current=Ge,me({sessionId:Ge,status:"error",needsInput:!1,owningTabId:$,type:"mission_interview",title:l.trim()||void 0,projectId:a??null}),Ne({sessionId:Ge,status:"error"})},onComplete:()=>{E(!1),G(!1),Y.current=null,Ne({sessionId:Ge,status:"complete"})},onConnectionStateChange:ue=>{E(ue==="reconnecting")}});q.current=K},[Ne,me,l,a,$]),he=i.useCallback(async Ge=>{const K=Ge??l;if(K.trim()){m(null),x(""),p([]),w([]),E(!1),u({type:"loading"});try{const{sessionId:ue}=await A0(K.trim(),a,Z&&Q?{modelProvider:Z,modelId:Q}:void 0);Y.current=ue,M(ue),da(a),We(ue),p([])}catch(ue){E(!1),m(Ie(ue)||"Failed to start interview session"),u({type:"initial"}),Y.current=null,M(null)}}},[We,l,Z,Q,a]);i.useEffect(()=>{e&&d.type==="initial"&&P.current?.focus()},[e,d.type]),i.useEffect(()=>{if(e&&!r&&!o&&!S.current&&d.type==="initial"){const Ge=U$(a);Ge&&c(Ge)}},[e]),i.useEffect(()=>{if(e&&r&&!S.current&&d.type==="initial"){c(r);const Ge=setTimeout(()=>{S.current=!0,he(r)},0);return()=>clearTimeout(Ge)}},[e,r,d.type,he]),i.useEffect(()=>{e||(S.current=!1,E(!1),G(!1),M(null))},[e]),i.useEffect(()=>{if(!e||!o||d.type!=="initial")return;let Ge=!1;return $i(o).then(K=>{if(Ge||!K)return;const ue=Ar(K.conversationHistory);if(w(ue),M(K.id),p(ue.map(ot=>ot.response).filter(ot=>!!(ot&&typeof ot=="object"&&!Array.isArray(ot)))),K.status==="awaiting_input"&&K.currentQuestion)try{da(a);const ot=JSON.parse(K.currentQuestion);Y.current=K.id,j(!0),u({type:"question",sessionId:K.id,question:ot})}catch{m("Failed to restore session question.")}else if(K.status==="complete"&&K.result)try{da(a);const ot=JSON.parse(K.result);Y.current=K.id,j(!0),b(ot),u({type:"summary",sessionId:K.id,summary:ot})}catch{m("Failed to restore session result.")}else K.status==="generating"?(Y.current=K.id,j(!0),K.thinkingOutput&&x(K.thinkingOutput),u({type:"loading"}),We(K.id)):K.status==="error"&&(Y.current=K.id,j(!0),m(null),u({type:"error",sessionId:K.id,errorMessage:K.error??"The session encountered an error."}))}).catch(()=>{Ge||m("Failed to resume session.")}),()=>{Ge=!0}},[We,e,o,d.type,a]),i.useEffect(()=>{if(!e){ge.current&&(Me(ge.current,$),ge.current=null);return}if(L&&ge.current!==L){ge.current&&Me(ge.current,$),ve(L,$),ge.current=L;return}!L&&ge.current&&(Me(ge.current,$),ge.current=null)},[ve,Me,e,L,$]),i.useEffect(()=>{if(!e||!L||ge.current!==L)return;ie($);const Ge=setInterval(()=>{ie($)},3e4);return()=>{clearInterval(Ge)}},[ie,e,L,$]),i.useEffect(()=>()=>{q.current?.close(),q.current=null,ge.current&&(Me(ge.current,$),ge.current=null)},[Me,$]),i.useEffect(()=>{if(!e)return;const Ge=K=>{(d.type==="question"||d.type==="summary")&&(K.preventDefault(),K.returnValue=""),q.current?.close()};return window.addEventListener("beforeunload",Ge),()=>window.removeEventListener("beforeunload",Ge)},[e,d]);const pe=i.useCallback(()=>{q.current?.close(),q.current=null,n()},[n]),De=i.useCallback(async()=>{if(l&&B$(l,a),!(y&&!await ye({title:"Close Interview",message:"Are you sure you want to close? Your interview progress will be lost.",danger:!0}))){if(q.current?.close(),q.current=null,d.type==="question"||d.type==="summary"||d.type==="error")try{await Lb(d.sessionId,a,$)}catch{}c(""),u({type:"initial"}),m(null),p([]),w([]),b(null),x(""),E(!1),G(!1),j(!1),A(!1),fe(void 0),F(void 0),Y.current=null,M(null),n()}},[l,y,d,n,a,$,ye]);i.useEffect(()=>{if(!e)return;const Ge=K=>{K.key==="Escape"&&De()};return document.addEventListener("keydown",Ge),()=>document.removeEventListener("keydown",Ge)},[e,De]);const ut=i.useCallback(async Ge=>{if(d.type!=="question")return;const{sessionId:K}=d;m(null),p(ue=>[...ue,Ge]),w(ue=>[...ue,{question:d.question,response:Ge}]),u({type:"loading"}),x("");try{We(K),await R0(K,Ge,a,$),j(!0)}catch(ue){q.current?.close(),q.current=null,m(Ie(ue)||"Failed to submit response"),u({type:"question",sessionId:K,question:d.question})}},[d,a,$,We]),ht=i.useCallback(async()=>{if(d.type!=="error")return;const Ge=d.sessionId;m(null),G(!0),x(""),u({type:"loading"}),We(Ge);try{Y.current=Ge,M(Ge),await I0(Ge,a,$)}catch(K){let ue=K;if((Ie(K)||"").includes("not in an error state"))try{const xe=await $i(Ge);if(!xe)throw new Error("Failed to refresh interview session.");const dt=Ar(xe.conversationHistory);if(w(dt),p(dt.map(Je=>Je.response).filter(Je=>!!(Je&&typeof Je=="object"&&!Array.isArray(Je)))),Y.current=xe.id,M(xe.id),j(!0),xe.status==="generating")x(xe.thinkingOutput??""),u({type:"loading"}),q.current?.isConnected()||We(xe.id);else if(xe.status==="awaiting_input"){if(!xe.currentQuestion)throw new Error("Interview session is awaiting input but has no current question.");da(a);const Je=JSON.parse(xe.currentQuestion);u({type:"question",sessionId:xe.id,question:Je}),q.current?.isConnected()||We(xe.id)}else if(xe.status==="complete"){if(!xe.result)throw new Error("Interview session is complete but has no result.");da(a);const Je=JSON.parse(xe.result);b(Je),u({type:"summary",sessionId:xe.id,summary:Je})}else xe.status==="error"&&u({type:"error",sessionId:xe.id,errorMessage:xe.error??"Retry failed. Please try again."});E(!1);return}catch(xe){ue=xe}q.current?.close(),q.current=null,u({type:"error",sessionId:Ge,errorMessage:Ie(ue)||"Retry failed. Please try again."}),E(!1)}finally{G(!1)}},[We,a,$,d]),et=i.useCallback(async()=>{if(d.type==="summary"){m(null),A(!0);try{const Ge=await $0(d.sessionId,v||void 0,a);s(Ge),da(a),q.current?.close(),q.current=null,c(""),u({type:"initial"}),m(null),p([]),w([]),b(null),x(""),E(!1),G(!1),j(!1),A(!1),Y.current=null,M(null),n()}catch(Ge){m(Ie(Ge)||"Failed to create mission"),A(!1)}}},[d,v,s,n,a]),vt=()=>d.type==="question"?Math.min(f.length+1,6):6,Oe=d.type==="loading"||d.type==="question"||d.type==="summary"||d.type==="error",tt=L?de.get(L):null,ft=tt&&tt.tabId!==$,Mt=!!(ft&&!tt.stale),yt=D&&(!ft||tt.stale);return e?t.jsx("div",{className:"modal-overlay open",onClick:Ge=>Ge.target===Ge.currentTarget&&De(),role:"dialog","aria-modal":"true",children:t.jsxs("div",{className:"modal modal-lg planning-modal",children:[t.jsxs("div",{className:"modal-header",children:[t.jsxs("div",{className:"detail-title-row",children:[t.jsx(js,{size:20,className:"icon-triage"}),t.jsx("h3",{children:"Plan Mission with AI"})]}),t.jsxs("div",{className:"modal-header-actions",children:[Oe&&t.jsx("button",{className:"modal-send-to-background",onClick:pe,title:"Send to background","aria-label":"Send to background",children:t.jsx(Vo,{size:16})}),t.jsx("button",{className:"modal-close",onClick:De,"aria-label":"Close",children:t.jsx(bn,{size:20})})]})]}),t.jsxs("div",{className:"planning-modal-body",children:[h&&t.jsx("div",{className:"form-error planning-error",children:h}),O&&t.jsx("div",{className:"form-hint text-muted",children:"Reconnecting…"}),Mt&&t.jsx("div",{className:"form-hint text-muted","data-testid":"session-active-another-tab-banner",children:"Session is active in another tab."}),d.type==="initial"&&t.jsxs("div",{className:"planning-initial",children:[t.jsxs("div",{className:"planning-view-scroll",children:[t.jsxs("div",{className:"planning-intro",children:[t.jsx(cs,{size:32,className:"icon-triage-lg"}),t.jsx("h4",{children:"Transform your vision into a structured mission"}),t.jsx("p",{className:"text-muted",children:"Describe what you want to build. The AI will interview you to understand scope, constraints, and requirements, then produce a structured plan with milestones, slices, and features."})]}),t.jsxs("div",{className:"form-group",children:[t.jsx("label",{htmlFor:"mission-goal",children:"What do you want to build?"}),t.jsx("textarea",{ref:P,id:"mission-goal",rows:4,className:"planning-textarea",placeholder:"e.g., Build a real-time collaborative document editor with presence, comments, and version history...",value:l,onChange:Ge=>c(Ge.target.value),onKeyDown:Ge=>{Ge.key==="Enter"&&!Ge.shiftKey&&l.trim()&&(Ge.preventDefault(),he())}})]}),t.jsxs("div",{className:"planning-examples",children:[t.jsx("span",{className:"planning-examples-label",children:"Try an example:"}),t.jsx("div",{className:"planning-example-chips",children:e4.map((Ge,K)=>t.jsx("button",{className:"planning-example-chip",onClick:()=>c(Ge),children:Ge.length>45?Ge.slice(0,45)+"...":Ge},K))})]}),t.jsxs("div",{className:"planning-model-select-group",children:[t.jsxs("label",{htmlFor:"mission-interview-modal-model",className:"form-label",children:["Planning Model",U&&t.jsx("span",{className:"text-muted text-muted-sm",children:"Loading models…"})]}),t.jsx(Ns,{id:"mission-interview-modal-model",label:"Planning Model",value:oe,onChange:Ge=>{const{provider:K,modelId:ue}=Z$(Ge);fe(K),F(ue)},models:X,disabled:U,favoriteProviders:Ve,onToggleFavorite:Te,favoriteModels:ct,onToggleModelFavorite:Fe}),Ue&&t.jsxs("div",{className:"form-hint form-hint-error",children:[Ue," ",t.jsx("button",{type:"button",className:"text-link-btn",onClick:()=>{(async()=>{try{be(!0);const Ge=await Bs();re(Ge.models),Le(Ge.favoriteProviders),Ke(Ge.favoriteModels),se(null)}catch(Ge){se(Ie(Ge)||"Failed to load models")}finally{be(!1)}})()},children:"Retry"})]}),t.jsx("div",{className:"model-selector-current model-selector-current--spaced",children:t.jsx("span",{className:`model-badge ${Z&&Q?"model-badge-custom":"model-badge-default"}`,children:mt(Z,Q)})})]})]}),t.jsx("div",{className:"planning-view-footer",children:t.jsxs("button",{className:"btn btn-primary planning-start-btn",onClick:()=>he(),disabled:!l.trim(),children:[t.jsx(js,{size:16,className:"icon-mr-8"}),"Start Interview"]})})]}),d.type==="loading"&&t.jsxs("div",{className:"planning-loading",children:[t.jsx(St,{size:40,className:"spin icon-todo"}),t.jsx("p",{children:C?"AI is thinking...":"Preparing next question..."}),t.jsxs("div",{className:"planning-thinking-container",children:[t.jsx("button",{className:"planning-thinking-toggle",onClick:()=>R(!k),type:"button",children:k?"Hide thinking":"Show thinking"}),k&&C&&t.jsx("div",{className:"planning-thinking-output",children:t.jsx("pre",{children:C})})]})]}),d.type==="error"&&t.jsx("div",{className:"planning-summary",children:t.jsxs("div",{className:"planning-view-scroll planning-summary-scroll",children:[g.length>0&&t.jsxs(t.Fragment,{children:[t.jsx(ui,{entries:g}),t.jsx("div",{className:"conversation-separator"})]}),t.jsxs("div",{className:"ai-error-panel",role:"alert",children:[t.jsx("div",{className:"ai-error-icon",children:"⚠️"}),t.jsx("div",{className:"ai-error-message",children:d.errorMessage}),t.jsxs("div",{className:"ai-error-actions",children:[t.jsxs("button",{className:"btn btn-primary",onClick:()=>void ht(),disabled:_,children:[_?t.jsx(St,{size:14,className:"spin"}):t.jsx(us,{size:14}),t.jsx("span",{className:"icon-ml-6",children:_?"Retrying...":"Retry"})]}),t.jsx("button",{className:"btn",onClick:De,disabled:_,children:"Cancel"})]})]})]})}),d.type==="question"&&t.jsx(n4,{question:d.question,progress:vt(),historyEntries:g,onSubmit:ut}),d.type==="summary"&&v&&t.jsx(s4,{summary:v,historyEntries:g,onSummaryChange:b,onApprove:et,onStartOver:()=>{u({type:"initial"}),j(!1),b(null),p([]),w([]),M(null),q.current?.close(),q.current=null},isCreating:H}),D&&t.jsx("div",{className:"session-lock-overlay","data-testid":"session-lock-overlay",children:t.jsxs("div",{className:"session-lock-banner",children:[t.jsx(kc,{size:16}),t.jsx("span",{children:yt?"This session is active in another tab":"This session is active in another tab (live heartbeat)"}),yt&&t.jsx("button",{type:"button",onClick:()=>{N()},disabled:W,className:"btn btn-primary session-lock-take-control",children:W?"Taking control...":"Take Control"})]})})]})]})}):null}function n4({question:e,progress:n,historyEntries:s,onSubmit:a}){const[r,o]=i.useState({}),[l,c]=i.useState(""),[d,u]=i.useState(""),h=i.useCallback(()=>{let f;e.type==="text"?f={[e.id]:l}:e.type==="confirm"?f={[e.id]:r[e.id]===!0}:f=r;const p=d.trim();p.length>0&&(f={...f,_comment:p}),a(f)},[d,e,r,l,a]);i.useEffect(()=>{o({}),c(""),u("")},[e.id]);const m=()=>{switch(e.type){case"text":return l.trim().length>0;case"single_select":return r[e.id]!==void 0;case"multi_select":return Array.isArray(r[e.id])&&r[e.id].length>0;case"confirm":return r[e.id]!==void 0;default:return!0}};return t.jsxs("div",{className:"planning-question-form",children:[t.jsxs("div",{className:"planning-view-scroll planning-question-scroll",children:[s.length>0&&t.jsxs(t.Fragment,{children:[t.jsx(ui,{entries:s}),t.jsx("div",{className:"conversation-separator"})]}),t.jsxs("div",{className:"planning-question-panel",children:[t.jsxs("div",{className:"planning-progress",children:[t.jsx("div",{className:"planning-progress-bar",children:[1,2,3,4,5,6].map(f=>t.jsx("div",{className:`planning-progress-step ${f<=n?"active":""}`},f))}),t.jsxs("span",{className:"planning-progress-text",children:["Question ",n," of ~6"]})]}),t.jsxs("div",{className:"planning-question-content",children:[t.jsx("h4",{className:"planning-question-text",children:e.question}),e.description&&t.jsx("p",{className:"planning-question-desc",children:e.description}),t.jsxs("div",{className:"planning-options",children:[e.type==="text"&&t.jsx("textarea",{className:"planning-textarea",rows:4,placeholder:"Type your answer here...",value:l,onChange:f=>c(f.target.value),onKeyDown:f=>{f.key==="Enter"&&!f.shiftKey&&l.trim()&&(f.preventDefault(),h())}}),e.type==="single_select"&&e.options&&t.jsx("div",{className:"planning-radio-group",role:"radiogroup",children:e.options.map(f=>t.jsxs("label",{className:"planning-option planning-option--radio",children:[t.jsx("input",{type:"radio",name:e.id,value:f.id,checked:r[e.id]===f.id,onChange:()=>o({[e.id]:f.id})}),t.jsxs("div",{className:"planning-option-content",children:[t.jsx("span",{className:"planning-option-label",children:f.label}),f.description&&t.jsx("span",{className:"planning-option-desc",children:f.description})]})]},f.id))}),e.type==="multi_select"&&e.options&&t.jsx("div",{className:"planning-checkbox-group",children:e.options.map(f=>{const p=r[e.id]||[];return t.jsxs("label",{className:"planning-option planning-option--checkbox",children:[t.jsx("input",{type:"checkbox",value:f.id,checked:p.includes(f.id),onChange:g=>{const w=g.target.checked?[...p,f.id]:p.filter(v=>v!==f.id);o({[e.id]:w})}}),t.jsxs("div",{className:"planning-option-content",children:[t.jsx("span",{className:"planning-option-label",children:f.label}),f.description&&t.jsx("span",{className:"planning-option-desc",children:f.description})]})]},f.id)})}),e.type==="confirm"&&t.jsxs("div",{className:"planning-confirm-group",children:[t.jsxs("button",{className:`planning-confirm-btn ${r[e.id]===!0?"selected":""}`,onClick:()=>o({[e.id]:!0}),children:[t.jsx(Zn,{size:18}),"Yes"]}),t.jsxs("button",{className:`planning-confirm-btn ${r[e.id]===!1?"selected":""}`,onClick:()=>o({[e.id]:!1}),children:[t.jsx(bn,{size:18}),"No"]})]})]}),e.type!=="text"&&t.jsxs("div",{className:"planning-comment-section",children:[t.jsx("label",{className:"planning-comment-label",htmlFor:`planning-comment-${e.id}`,children:"Additional comments (optional)"}),t.jsx("textarea",{id:`planning-comment-${e.id}`,className:"planning-textarea",rows:2,placeholder:"Add any extra context or direction...",value:d,onChange:f=>u(f.target.value)})]})]})]})]}),t.jsx("div",{className:"planning-actions",children:t.jsxs("button",{className:"btn btn-primary planning-actions-primary",onClick:h,disabled:!m(),children:["Continue",t.jsx(Ho,{size:16,className:"icon-ml-4"})]})})]})}function s4({summary:e,historyEntries:n,onSummaryChange:s,onApprove:a,onStartOver:r,isCreating:o}){const[l,c]=i.useState(()=>new Set(e.milestones.map((S,C)=>C))),[d,u]=i.useState(()=>{const S=new Set;return e.milestones.forEach((C,x)=>{C.slices.forEach((k,R)=>S.add(`${x}-${R}`))}),S}),h=S=>{c(C=>{const x=new Set(C);return x.has(S)?x.delete(S):x.add(S),x})},m=S=>{u(C=>{const x=new Set(C);return x.has(S)?x.delete(S):x.add(S),x})},f=(S,C)=>{const x=[...e.milestones];x[S]={...x[S],...C},s({...e,milestones:x})},p=(S,C,x)=>{const k=[...e.milestones],R=[...k[S].slices];R[C]={...R[C],...x},k[S]={...k[S],slices:R},s({...e,milestones:k})},g=(S,C,x,k)=>{const R=[...e.milestones],O=[...R[S].slices],E=[...O[C].features];E[x]={...E[x],...k},O[C]={...O[C],features:E},R[S]={...R[S],slices:O},s({...e,milestones:R})},w=S=>{const C=e.milestones.filter((x,k)=>k!==S);s({...e,milestones:C})},v=(S,C)=>{const x=[...e.milestones];x[S]={...x[S],slices:x[S].slices.filter((k,R)=>R!==C)},s({...e,milestones:x})},b=(S,C,x)=>{const k=[...e.milestones],R=[...k[S].slices];R[C]={...R[C],features:R[C].features.filter((O,E)=>E!==x)},k[S]={...k[S],slices:R},s({...e,milestones:k})},y=(S,C)=>{const x=[...e.milestones],k=[...x[S].slices];k[C]={...k[C],features:[...k[C].features,{title:"New feature",description:""}]},x[S]={...x[S],slices:k},s({...e,milestones:x})},j=e.milestones.reduce((S,C)=>S+C.slices.reduce((x,k)=>x+k.features.length,0),0);return t.jsxs("div",{className:"planning-summary",children:[t.jsxs("div",{className:"planning-view-scroll planning-summary-scroll",children:[n.length>0&&t.jsxs(t.Fragment,{children:[t.jsx(ui,{entries:n}),t.jsx("div",{className:"conversation-separator"})]}),t.jsxs("div",{className:"planning-summary-header",children:[t.jsx(Zn,{size:24,className:"icon-success"}),t.jsx("h4",{children:"Mission Plan Ready"}),t.jsxs("p",{className:"text-muted",children:[e.milestones.length," milestones, ",j," features. Review and edit before approving."]})]}),t.jsxs("div",{className:"planning-summary-form",children:[t.jsxs("div",{className:"form-group",children:[t.jsx("label",{children:"Mission Title"}),t.jsx("input",{type:"text",className:"form-input",value:e.missionTitle||"",onChange:S=>s({...e,missionTitle:S.target.value})})]}),t.jsxs("div",{className:"form-group",children:[t.jsx("label",{children:"Mission Description"}),t.jsx("textarea",{className:"planning-textarea",rows:3,value:e.missionDescription||"",onChange:S=>s({...e,missionDescription:S.target.value})})]}),t.jsxs("div",{className:"form-group",children:[t.jsx("label",{children:"Roadmap"}),t.jsx("div",{className:"roadmap-list",children:e.milestones.map((S,C)=>t.jsxs("div",{className:"roadmap-card",children:[t.jsxs("div",{className:"roadmap-card-header",onClick:()=>h(C),children:[l.has(C)?t.jsx(vn,{size:16,className:"icon-text-secondary"}):t.jsx(Wn,{size:16,className:"icon-text-secondary"}),t.jsx(Fa,{size:16,className:"icon-milestone"}),t.jsx("input",{type:"text",className:"form-input roadmap-input-title",value:S.title,onChange:x=>f(C,{title:x.target.value}),onClick:x=>x.stopPropagation()}),e.milestones.length>1&&t.jsx("button",{className:"btn-icon roadmap-shrink",onClick:x=>{x.stopPropagation(),w(C)},title:"Remove milestone",children:t.jsx(In,{size:14,className:"icon-text-secondary"})})]}),l.has(C)&&t.jsxs("div",{className:"roadmap-card-body",children:[t.jsx("textarea",{className:"planning-textarea roadmap-textarea-md",rows:2,placeholder:"Milestone description...",value:S.description||"",onChange:x=>f(C,{description:x.target.value})}),t.jsxs("div",{className:"roadmap-field-group",children:[t.jsx("label",{className:"roadmap-field-label",children:"Verification Criteria"}),t.jsx("textarea",{className:"planning-textarea roadmap-textarea-sm",rows:2,placeholder:"How to confirm this milestone is complete...",value:S.verification||"",onChange:x=>f(C,{verification:x.target.value})})]}),S.slices.map((x,k)=>{const R=`${C}-${k}`;return t.jsxs("div",{className:"roadmap-slice-card",children:[t.jsxs("div",{className:"roadmap-slice-header",onClick:()=>m(R),children:[d.has(R)?t.jsx(vn,{size:14,className:"icon-text-secondary"}):t.jsx(Wn,{size:14,className:"icon-text-secondary"}),t.jsx(du,{size:14,className:"icon-slice"}),t.jsx("input",{type:"text",className:"form-input roadmap-input-subtitle",value:x.title,onChange:O=>p(C,k,{title:O.target.value}),onClick:O=>O.stopPropagation()}),S.slices.length>1&&t.jsx("button",{className:"btn-icon roadmap-shrink",onClick:O=>{O.stopPropagation(),v(C,k)},title:"Remove slice",children:t.jsx(In,{size:12,className:"icon-text-secondary"})})]}),d.has(R)&&t.jsxs("div",{className:"roadmap-slice-body",children:[t.jsxs("div",{className:"roadmap-slice-field-group",children:[t.jsx("label",{className:"roadmap-field-label",children:"Slice Verification"}),t.jsx("textarea",{className:"planning-textarea roadmap-textarea-xs",rows:1,placeholder:"How to confirm this slice is done...",value:x.verification||"",onChange:O=>p(C,k,{verification:O.target.value})})]}),x.features.map((O,E)=>t.jsxs("div",{className:"roadmap-feature-row",children:[t.jsx(iu,{size:12,className:"icon-feature"}),t.jsxs("div",{className:"roadmap-feature-content",children:[t.jsx("input",{type:"text",className:"form-input roadmap-input-feature",value:O.title,onChange:_=>g(C,k,E,{title:_.target.value})}),O.description&&t.jsx("p",{className:"roadmap-feature-text",children:O.description}),O.acceptanceCriteria&&t.jsxs("p",{className:"roadmap-feature-text--italic",children:["AC: ",O.acceptanceCriteria]})]}),t.jsx("button",{className:"btn-icon roadmap-shrink",onClick:()=>b(C,k,E),title:"Remove feature",children:t.jsx(In,{size:12,className:"icon-text-secondary"})})]},E)),t.jsxs("button",{className:"btn roadmap-add-feature-btn",onClick:()=>y(C,k),children:[t.jsx(Tn,{size:12}),"Add Feature"]})]})]},k)})]})]},C))})]})]})]}),t.jsxs("div",{className:"planning-actions planning-summary-actions",children:[t.jsxs("button",{className:"btn",onClick:r,disabled:o,children:[t.jsx(Ka,{size:16,className:"icon-mr-4"}),"Start Over"]}),t.jsx("button",{className:"btn btn-primary",onClick:a,disabled:o||e.milestones.length===0,children:o?t.jsxs(t.Fragment,{children:[t.jsx(St,{size:16,className:"spin icon-mr-8"}),"Creating Mission..."]}):t.jsxs(t.Fragment,{children:[t.jsx(Zn,{size:16,className:"icon-mr-8"}),"Approve Plan"]})})]})]})}const i4=30,a4=16,r4=16;function o4(){if(typeof window>"u")return!1;const e="ontouchstart"in window||navigator.maxTouchPoints>0,n=window.innerWidth<=768;return e&&n}let Vl=null;function Pv(){return Vl===null&&(Vl=window.visualViewport?.height??window.innerHeight),Vl}function l4(e){const n=Pv();e>n&&(Vl=e)}function c4(e){return e?e instanceof HTMLTextAreaElement?!0:e instanceof HTMLInputElement?!new Set(["checkbox","radio","button","submit","reset","file","range","color","hidden"]).has(e.type):e instanceof HTMLElement&&e.isContentEditable:!1}function Mf(){if(typeof window>"u"||!window.visualViewport)return{overlap:0,open:!1,vvHeight:null,vvOffsetTop:0};const e=window.visualViewport,n=c4(document.activeElement),s=e.offsetTop;n||l4(e.height);const a=Math.max(0,window.innerHeight-e.offsetTop-e.height);if(a>0&&n)return{overlap:a,open:!0,vvHeight:e.height,vvOffsetTop:s};const r=Pv(),o=Math.max(0,r-e.offsetTop-e.height);if(o>=i4&&n)return{overlap:o,open:!0,vvHeight:e.height,vvOffsetTop:s};if(o>=a4&&n)return{overlap:o,open:!0,vvHeight:e.height,vvOffsetTop:s};const l=Math.max(0,r-e.height);return n&&l>=r4?{overlap:0,open:!0,vvHeight:e.height,vvOffsetTop:s}:{overlap:0,open:!1,vvHeight:null,vvOffsetTop:0}}function ea({enabled:e=!0}={}){const[n,s]=i.useState(0),[a,r]=i.useState(null),[o,l]=i.useState(0),[c,d]=i.useState(!1);return i.useEffect(()=>{if(!e||!o4()){s(0),r(null),l(0),d(!1);return}const u=window.visualViewport;if(!u){s(0),r(null),l(0),d(!1);return}const h=()=>{const x=Mf();s(x.overlap),r(x.vvHeight),l(x.vvOffsetTop),d(x.open)},m=()=>{const x=Mf();s(x.overlap),r(x.vvHeight),d(x.open)},f=[],p=x=>{if(typeof window>"u")return;const k=window.setTimeout(()=>{typeof window>"u"||h()},x);f.push(k)};let g=null,w=0,v=-1,b=0;const y=()=>{g!==null&&typeof window<"u"&&(window.cancelAnimationFrame(g),g=null)},j=()=>{if(typeof window>"u")return;h();const x=window.visualViewport?.offsetTop??0;if(x===v?b+=1:(b=0,v=x),b>=2||performance.now()>w){g=null;return}g=window.requestAnimationFrame(j)},S=()=>{typeof window>"u"||(y(),w=performance.now()+1500,v=-1,b=0,g=window.requestAnimationFrame(j))},C=()=>{h(),p(50),p(200),p(500),p(1e3),p(1500),S()};return C(),u.addEventListener("resize",h),u.addEventListener("scroll",m),document.addEventListener("focusin",C),document.addEventListener("focusout",h),document.addEventListener("visibilitychange",C),window.addEventListener("pageshow",C),()=>{u.removeEventListener("resize",h),u.removeEventListener("scroll",m),document.removeEventListener("focusin",C),document.removeEventListener("focusout",h),document.removeEventListener("visibilitychange",C),window.removeEventListener("pageshow",C);for(const x of f)clearTimeout(x);y(),s(0),r(null),l(0),d(!1)}},[e]),{keyboardOverlap:n,viewportHeight:a,viewportOffsetTop:o,keyboardOpen:c}}function d4({isOpen:e,onClose:n,onApplied:s,targetType:a,targetId:r,targetTitle:o,missionContext:l,projectId:c,resumeSessionId:d}){const u=ei();Si(e);const{keyboardOverlap:h,viewportHeight:m,viewportOffsetTop:f,keyboardOpen:p}=ea({enabled:u==="mobile"}),g=p?{"--keyboard-overlap":`${h}px`,"--vv-offset-top":`${f}px`,...m!==null?{"--vv-height":`${m}px`}:{}}:{},[w,v]=i.useState({type:"initial"}),[b,y]=i.useState(null),[j,S]=i.useState([]),[C,x]=i.useState([]),[k,R]=i.useState(null),[O,E]=i.useState(""),[_,G]=i.useState(!0),[H,A]=i.useState(!1),[P,q]=i.useState(!1),Y=i.useRef(null),ge=i.useRef(null),L=i.useRef(null),M=i.useRef(null),[$,D]=i.useState(null),N=i.useMemo(()=>Ya(),[]);$c(e?$:null);const{activeTabMap:W,broadcastUpdate:de,broadcastCompleted:me,broadcastLock:Ne,broadcastUnlock:ve,broadcastHeartbeat:Me}=Gr(),ie=a==="milestone"?L0:U0,ye=a==="milestone"?O0:H0,Z=a==="milestone"?F0:q0,fe=a==="milestone"?z0:V0,Q=a==="milestone"?B0:W0,F=a==="milestone"?"Milestone":"Slice",X=a==="milestone"?"milestone_interview":"slice_interview",re=i.useCallback(We=>{ge.current?.close();const he=Z(We,c,{onThinking:pe=>{E(De=>De+pe),de({sessionId:We,status:"generating",needsInput:!1,owningTabId:N,type:X,title:o,projectId:c??null})},onQuestion:pe=>{A(!1),U(),v({type:"question",sessionId:We,question:pe}),E(""),de({sessionId:We,status:"awaiting_input",needsInput:!0,owningTabId:N,type:X,title:o,projectId:c??null})},onSummary:pe=>{A(!1),U(),v({type:"summary",sessionId:We,summary:pe}),R(pe),E(""),de({sessionId:We,status:"complete",needsInput:!1,owningTabId:N,type:X,title:o,projectId:c??null})},onError:pe=>{const De=pe||"Session failed while contacting the AI.";A(!1),y(null),v({type:"error",sessionId:We,errorMessage:De}),E(""),L.current=We,de({sessionId:We,status:"error",needsInput:!1,owningTabId:N,type:X,title:o,projectId:c??null}),me({sessionId:We,status:"error"})},onComplete:()=>{A(!1),L.current=null,me({sessionId:We,status:"complete"})},onConnectionStateChange:pe=>{A(pe==="reconnecting")}});ge.current=he},[me,de,Z,X,c,N,o]),U=()=>{R(null),S([]),x([]),E("")},be=i.useCallback(async()=>{y(null),U(),A(!1),v({type:"loading"});try{const{sessionId:We}=await ie(r,c);L.current=We,D(We),re(We)}catch(We){A(!1),y(Ie(We)||`Failed to start ${F.toLowerCase()} interview`),v({type:"initial"}),L.current=null,D(null)}},[re,c,ie,r,F]),Ue=i.useCallback(async()=>{y(null),q(!0);try{await Q(r,c),s(),v({type:"applied"})}catch(We){y(Ie(We)||`Failed to skip ${F.toLowerCase()} interview`),q(!1)}},[s,c,Q,r,F]);i.useEffect(()=>{e&&w.type==="initial"&&Y.current?.focus()},[e,w.type]),i.useEffect(()=>{if(!e||!d||w.type!=="initial")return;let We=!1;return $i(d).then(he=>{if(We||!he)return;const pe=Ar(he.conversationHistory);if(x(pe),D(he.id),S(pe.map(De=>De.response).filter(De=>!!(De&&typeof De=="object"&&!Array.isArray(De)))),he.status==="awaiting_input"&&he.currentQuestion)try{const De=JSON.parse(he.currentQuestion);L.current=he.id,v({type:"question",sessionId:he.id,question:De})}catch{y("Failed to restore session question.")}else if(he.status==="complete"&&he.result)try{const De=JSON.parse(he.result);L.current=he.id,R(De),v({type:"summary",sessionId:he.id,summary:De})}catch{y("Failed to restore session result.")}else he.status==="generating"?(L.current=he.id,he.thinkingOutput&&E(he.thinkingOutput),v({type:"loading"}),re(he.id)):he.status==="error"&&(L.current=he.id,y(null),v({type:"error",sessionId:he.id,errorMessage:he.error??"The session encountered an error."}))}).catch(()=>{We||y("Failed to resume session.")}),()=>{We=!0}},[re,e,d,w.type]),i.useEffect(()=>{e||(A(!1),D(null))},[e]),i.useEffect(()=>{if(!(!e||!$)){if(M.current!==$){M.current&&ve(M.current,N),Ne($,N),M.current=$;return}!$&&M.current&&(ve(M.current,N),M.current=null)}},[Ne,ve,e,$,N]),i.useEffect(()=>{if(!e||!$||M.current!==$)return;Me(N);const We=setInterval(()=>{Me(N)},3e4);return()=>{clearInterval(We)}},[Me,e,$,N]),i.useEffect(()=>()=>{ge.current?.close(),ge.current=null,M.current&&(ve(M.current,N),M.current=null)},[ve,N]);const se=i.useCallback(()=>{ge.current?.close(),ge.current=null,n()},[n]),Ve=i.useCallback(async()=>{ge.current?.close(),ge.current=null,U(),v({type:"initial"}),y(null),L.current=null,D(null),n()},[n]),Le=i.useCallback(async We=>{if(w.type!=="question")return;const{sessionId:he}=w;y(null),S(pe=>[...pe,We]),x(pe=>[...pe,{question:w.question,response:We}]),v({type:"loading"}),E("");try{re(he),await ye(he,We,c,N)}catch(pe){ge.current?.close(),ge.current=null,y(Ie(pe)||"Failed to submit response"),v({type:"question",sessionId:he,question:w.question})}},[re,c,ye,N,w]),ct=i.useCallback(async()=>{if(w.type==="summary"){y(null),q(!0);try{await fe(w.sessionId,k||void 0,c),s(),v({type:"applied"})}catch(We){y(Ie(We)||"Failed to apply interview results"),q(!1)}}},[fe,k,s,c,w]),Ke=()=>w.type==="question"?Math.min(j.length+1,6):6,oe=w.type==="loading"||w.type==="question"||w.type==="summary"||w.type==="error",Te=$?W.get($):null,mt=!!(Te&&Te.tabId!==N&&!Te.stale);return e?t.jsx("div",{className:"modal-overlay open",onClick:We=>We.target===We.currentTarget&&Ve(),role:"dialog","aria-modal":"true","data-testid":"milestone-slice-interview-modal",children:t.jsxs("div",{className:"modal modal-lg planning-modal",style:g,children:[t.jsxs("div",{className:"modal-header",children:[t.jsxs("div",{className:"detail-title-row",children:[t.jsx(cs,{size:20,className:"icon-triage"}),t.jsxs("h3",{children:["Plan ",F,": ",o]})]}),t.jsxs("div",{className:"modal-header-actions",children:[oe&&t.jsx("button",{className:"modal-send-to-background",onClick:se,title:"Send to background","aria-label":"Send to background",children:t.jsx(Vo,{size:16})}),t.jsx("button",{className:"modal-close",onClick:Ve,"aria-label":"Close",children:t.jsx(bn,{size:20})})]})]}),t.jsxs("div",{className:"planning-modal-body",children:[b&&t.jsx("div",{className:"form-error planning-error",children:b}),H&&t.jsx("div",{className:"form-hint text-muted",children:"Reconnecting…"}),mt&&t.jsx("div",{className:"form-hint text-muted","data-testid":"session-active-another-tab-banner",children:"Session is active in another tab."}),w.type==="initial"&&t.jsxs("div",{className:"planning-initial",children:[t.jsx("div",{className:"planning-view-scroll",children:t.jsxs("div",{className:"planning-intro",children:[t.jsx(cs,{size:32,className:"icon-triage-lg"}),t.jsxs("h4",{children:["Refine ",F," scope with AI"]}),t.jsxs("p",{className:"text-muted",children:["The AI will interview you to refine the ",a,"'s scope, acceptance criteria, and verification methods. Each ",a," can have its own refined plan or inherit context from the mission level."]}),l&&t.jsxs("div",{className:"planning-context-info",children:[t.jsx("span",{className:"planning-context-label",children:"Mission context:"}),t.jsx("span",{className:"planning-context-text",children:l})]})]})}),t.jsxs("div",{className:"planning-view-footer",children:[t.jsxs("button",{className:"btn btn-primary planning-start-btn",onClick:()=>void be(),children:[t.jsx(cs,{size:16,className:"icon-mr-8"}),"Start Interview"]}),t.jsxs("button",{className:"btn planning-use-context-btn",onClick:()=>void Ue(),disabled:P,children:[P?t.jsx(St,{size:16,className:"spin"}):null,"Use Mission Context"]}),t.jsx("button",{className:"btn",onClick:Ve,children:"Cancel"})]})]}),w.type==="loading"&&t.jsxs("div",{className:"planning-loading",children:[t.jsx(St,{size:40,className:"spin icon-todo"}),t.jsx("p",{children:O?"AI is thinking...":"Preparing next question..."}),t.jsxs("div",{className:"planning-thinking-container",children:[t.jsx("button",{className:"planning-thinking-toggle",onClick:()=>G(!_),type:"button",children:_?"Hide thinking":"Show thinking"}),_&&O&&t.jsx("div",{className:"planning-thinking-output",children:t.jsx("pre",{children:O})})]})]}),w.type==="error"&&t.jsx("div",{className:"planning-summary",children:t.jsxs("div",{className:"planning-view-scroll planning-summary-scroll",children:[C.length>0&&t.jsxs(t.Fragment,{children:[t.jsx(ui,{entries:C}),t.jsx("div",{className:"conversation-separator"})]}),t.jsxs("div",{className:"ai-error-panel",role:"alert",children:[t.jsx("div",{className:"ai-error-icon",children:"⚠️"}),t.jsx("div",{className:"ai-error-message",children:w.errorMessage}),t.jsx("div",{className:"ai-error-actions",children:t.jsx("button",{className:"btn",onClick:Ve,children:"Cancel"})})]})]})}),w.type==="question"&&t.jsx(u4,{question:w.question,progress:Ke(),historyEntries:C,onSubmit:Le}),w.type==="summary"&&k&&t.jsx(m4,{summary:k,historyEntries:C,onSummaryChange:R,onApply:ct,onCancel:Ve,isApplying:P}),w.type==="applied"&&t.jsxs("div",{className:"planning-summary planning-applied",children:[t.jsx("div",{className:"planning-view-scroll",children:t.jsxs("div",{className:"planning-applied-content",children:[t.jsx(Zn,{size:48,className:"icon-success"}),t.jsxs("h4",{children:[F," Updated"]}),t.jsxs("p",{className:"text-muted",children:["The ",a,"'s scope and verification have been ",w.type==="applied"?"applied":"updated","."]})]})}),t.jsx("div",{className:"planning-view-footer",children:t.jsx("button",{className:"btn btn-primary",onClick:s,children:"Done"})})]})]})]})}):null}function u4({question:e,progress:n,historyEntries:s,onSubmit:a}){const[r,o]=i.useState({}),[l,c]=i.useState(""),[d,u]=i.useState(""),h=i.useCallback(()=>{let f;e.type==="text"?f={[e.id]:l}:e.type==="confirm"?f={[e.id]:r[e.id]===!0}:f=r;const p=d.trim();p.length>0&&(f={...f,_comment:p}),a(f)},[d,e,r,l,a]);i.useEffect(()=>{o({}),c(""),u("")},[e.id]);const m=()=>{switch(e.type){case"text":return l.trim().length>0;case"single_select":return r[e.id]!==void 0;case"multi_select":return Array.isArray(r[e.id])&&r[e.id].length>0;case"confirm":return r[e.id]!==void 0;default:return!0}};return t.jsxs("div",{className:"planning-question-form",children:[t.jsxs("div",{className:"planning-view-scroll planning-question-scroll",children:[s.length>0&&t.jsxs(t.Fragment,{children:[t.jsx(ui,{entries:s}),t.jsx("div",{className:"conversation-separator"})]}),t.jsxs("div",{className:"planning-question-panel",children:[t.jsxs("div",{className:"planning-progress",children:[t.jsx("div",{className:"planning-progress-bar",children:[1,2,3,4,5,6].map(f=>t.jsx("div",{className:`planning-progress-step ${f<=n?"active":""}`},f))}),t.jsxs("span",{className:"planning-progress-text",children:["Question ",n," of ~6"]})]}),t.jsxs("div",{className:"planning-question-content",children:[t.jsx("h4",{className:"planning-question-text",children:e.question}),e.description&&t.jsx("p",{className:"planning-question-desc",children:e.description}),t.jsxs("div",{className:"planning-options",children:[e.type==="text"&&t.jsx("textarea",{className:"planning-textarea",rows:4,placeholder:"Type your answer here...",value:l,onChange:f=>c(f.target.value),onKeyDown:f=>{f.key==="Enter"&&!f.shiftKey&&l.trim()&&(f.preventDefault(),h())}}),e.type==="single_select"&&e.options&&t.jsx("div",{className:"planning-radio-group",role:"radiogroup",children:e.options.map(f=>t.jsxs("label",{className:"planning-option planning-option--radio",children:[t.jsx("input",{type:"radio",name:e.id,value:f.id,checked:r[e.id]===f.id,onChange:()=>o({[e.id]:f.id})}),t.jsxs("div",{className:"planning-option-content",children:[t.jsx("span",{className:"planning-option-label",children:f.label}),f.description&&t.jsx("span",{className:"planning-option-desc",children:f.description})]})]},f.id))}),e.type==="multi_select"&&e.options&&t.jsx("div",{className:"planning-checkbox-group",children:e.options.map(f=>{const p=r[e.id]||[];return t.jsxs("label",{className:"planning-option planning-option--checkbox",children:[t.jsx("input",{type:"checkbox",value:f.id,checked:p.includes(f.id),onChange:g=>{const w=g.target.checked?[...p,f.id]:p.filter(v=>v!==f.id);o({[e.id]:w})}}),t.jsxs("div",{className:"planning-option-content",children:[t.jsx("span",{className:"planning-option-label",children:f.label}),f.description&&t.jsx("span",{className:"planning-option-desc",children:f.description})]})]},f.id)})}),e.type==="confirm"&&t.jsxs("div",{className:"planning-confirm-group",children:[t.jsxs("button",{className:`planning-confirm-btn ${r[e.id]===!0?"selected":""}`,onClick:()=>o({[e.id]:!0}),children:[t.jsx(Zn,{size:18}),"Yes"]}),t.jsxs("button",{className:`planning-confirm-btn ${r[e.id]===!1?"selected":""}`,onClick:()=>o({[e.id]:!1}),children:[t.jsx(bn,{size:18}),"No"]})]})]}),e.type!=="text"&&t.jsxs("div",{className:"planning-comment-section",children:[t.jsx("label",{className:"planning-comment-label",htmlFor:`planning-comment-${e.id}`,children:"Additional comments (optional)"}),t.jsx("textarea",{id:`planning-comment-${e.id}`,className:"planning-textarea",rows:2,placeholder:"Add any extra context or direction...",value:d,onChange:f=>u(f.target.value)})]})]})]})]}),t.jsx("div",{className:"planning-actions",children:t.jsxs("button",{className:"btn btn-primary planning-actions-primary",onClick:h,disabled:!m(),children:["Continue",t.jsx(Ho,{size:16,className:"icon-ml-4"})]})})]})}function m4({summary:e,historyEntries:n,onSummaryChange:s,onApply:a,onCancel:r,isApplying:o}){const[l,c]=i.useState(e),[d,u]=i.useState(!0),h=(m,f)=>{const p={...l,[m]:f};c(p),s(p)};return t.jsxs("div",{className:"planning-summary",children:[t.jsxs("div",{className:"planning-view-scroll planning-summary-scroll",children:[n.length>0&&t.jsxs(t.Fragment,{children:[t.jsx(ui,{entries:n}),t.jsx("div",{className:"conversation-separator"})]}),t.jsxs("div",{className:"planning-summary-panel",children:[t.jsx("div",{className:"planning-summary-header",children:t.jsxs("button",{className:"planning-summary-toggle",onClick:()=>u(!d),"aria-expanded":d,children:[d?t.jsx(vn,{size:16}):t.jsx(Wn,{size:16}),t.jsx("span",{children:"Refined Scope"})]})}),d&&t.jsxs("div",{className:"planning-summary-content",children:[l.description&&t.jsxs("div",{className:"planning-summary-field",children:[t.jsx("label",{children:"Description"}),t.jsx("textarea",{rows:3,value:l.description,onChange:m=>h("description",m.target.value)})]}),l.planningNotes&&t.jsxs("div",{className:"planning-summary-field",children:[t.jsx("label",{children:"Planning Notes"}),t.jsx("textarea",{rows:3,value:l.planningNotes,onChange:m=>h("planningNotes",m.target.value)})]}),l.verification&&t.jsxs("div",{className:"planning-summary-field",children:[t.jsx("label",{children:"Verification Criteria"}),t.jsx("textarea",{rows:2,value:l.verification,onChange:m=>h("verification",m.target.value)})]}),!l.description&&!l.planningNotes&&!l.verification&&t.jsx("p",{className:"text-muted planning-summary-empty",children:"No additional details were generated for this item."})]})]})]}),t.jsxs("div",{className:"planning-view-footer",children:[t.jsxs("button",{className:"btn btn-primary planning-actions-primary",onClick:a,disabled:o,children:[o?t.jsx(St,{size:16,className:"spin"}):null,"Apply"]}),t.jsx("button",{className:"btn",onClick:r,disabled:o,children:"Cancel"})]})]})}const Af=300,Cl=220,El=560,Rf="fusion:mission-sidebar-width",uo={planning:{bg:"var(--mission-planning-bg)",text:"var(--mission-planning-text)"},active:{bg:"var(--mission-active-bg)",text:"var(--mission-active-text)"},blocked:{bg:"var(--mission-blocked-bg)",text:"var(--mission-blocked-text)"},complete:{bg:"var(--mission-complete-bg)",text:"var(--mission-complete-text)"},archived:{bg:"var(--mission-archived-bg)",text:"var(--mission-archived-text)"}},If={planning:{bg:"var(--mission-planning-bg)",text:"var(--mission-planning-text)"},active:{bg:"var(--mission-active-bg)",text:"var(--mission-active-text)"},blocked:{bg:"var(--mission-blocked-bg)",text:"var(--mission-blocked-text)"},complete:{bg:"var(--mission-complete-bg)",text:"var(--mission-complete-text)"}},Tf={pending:{bg:"var(--slice-pending-bg)",text:"var(--slice-pending-text)"},active:{bg:"var(--slice-active-bg)",text:"var(--slice-active-text)"},complete:{bg:"var(--slice-complete-bg)",text:"var(--slice-complete-text)"}},_l={defined:{bg:"var(--feature-defined-bg)",text:"var(--feature-defined-text)"},triaged:{bg:"var(--feature-triaged-bg)",text:"var(--feature-triaged-text)"},"in-progress":{bg:"var(--feature-in-progress-bg)",text:"var(--feature-in-progress-text)"},done:{bg:"var(--feature-done-bg)",text:"var(--feature-done-text)"},blocked:{bg:"var(--mission-blocked-bg)",text:"var(--mission-blocked-text)"}},Ml={inactive:{bg:"var(--autopilot-inactive-bg)",text:"var(--autopilot-inactive-text)"},watching:{bg:"var(--autopilot-watching-bg)",text:"var(--autopilot-watching-text)"},activating:{bg:"var(--autopilot-activating-bg)",text:"var(--autopilot-activating-text)"},completing:{bg:"var(--autopilot-completing-bg)",text:"var(--autopilot-completing-text)"}},Al={pending:{bg:"var(--assertion-pending-bg)",text:"var(--assertion-pending-text)"},passed:{bg:"var(--assertion-passed-bg)",text:"var(--assertion-passed-text)"},failed:{bg:"var(--assertion-failed-bg)",text:"var(--assertion-failed-text)"},blocked:{bg:"var(--assertion-blocked-bg)",text:"var(--assertion-blocked-text)"}},Pf={not_started:{bg:"var(--assertion-pending-bg)",text:"var(--assertion-pending-text)"},needs_coverage:{bg:"var(--loop-needs-fix-bg)",text:"var(--loop-needs-fix-text)"},ready:{bg:"var(--loop-validating-bg)",text:"var(--loop-validating-text)"},passed:{bg:"var(--loop-passed-bg)",text:"var(--loop-passed-text)"},failed:{bg:"var(--loop-blocked-bg)",text:"var(--loop-blocked-text)"},blocked:{bg:"var(--loop-blocked-bg)",text:"var(--loop-blocked-text)"}},h4=3,p4=new Set(["generating","awaiting_input","error"]);function f4(e){switch(e){case"generating":return"Generating plan";case"awaiting_input":return"Awaiting input";case"error":return"Needs retry";default:return e}}function g4(e){switch(e){case"error":return"Retry interview";case"generating":return"Generating plan";default:return"Resume interview"}}function b4(e){return e==="completed"?"planned":e==="needs_update"?"needs_update":"not_started"}function $f({state:e}){const n=e==="planned"?"mission-plan-state-indicator--planned":e==="needs_update"?"mission-plan-state-indicator--needs-update":"mission-plan-state-indicator--not-started",s=e==="planned"?"Planned":e==="needs_update"?"Needs update":"Not planned";return t.jsx("span",{className:`mission-plan-state-indicator ${n}`,title:s,"aria-label":s})}function Df(e){return e?e.replace(/_/g," ").replace(/^\w/,n=>n.toUpperCase()):"Not started"}const Lf={title:"",description:"",status:"planning",autopilotEnabled:!1},Ld={title:"",description:"",status:"planning",dependencies:[]},Od={title:"",description:"",status:"pending"},Fd={title:"",description:"",acceptanceCriteria:"",status:"defined"},x4=3600*1e3;function lc(e){if(!e)return"—";const n=new Date(e).getTime();if(Number.isNaN(n))return"—";const s=Date.now()-n;if(s<0)return"just now";const a=Math.floor(s/(60*1e3));if(a<1)return"just now";if(a<60)return`${a}m ago`;const r=Math.floor(a/60);return r<24?`${r}h ago`:`${Math.floor(r/24)}d ago`}function v4(e){if(!e)return"healthy";const n=typeof e.lastErrorAt=="string"&&Date.now()-new Date(e.lastErrorAt).getTime()<=x4,s=e.totalTasks>0&&e.tasksFailed>e.totalTasks*.3;return n||s?"error":e.tasksFailed>0?"warning":e.tasksFailed===0&&e.tasksInFlight<=e.totalTasks?"healthy":"warning"}function y4(e){if(!e||typeof e!="object")return!1;const n=e;return typeof n.missionId=="string"&&typeof n.tasksCompleted=="number"&&typeof n.tasksFailed=="number"&&typeof n.tasksInFlight=="number"&&typeof n.totalTasks=="number"&&typeof n.estimatedCompletionPercent=="number"}function w4(e){if(!e||typeof e!="object")return!1;const n=e;return typeof n.id=="string"&&typeof n.missionId=="string"&&typeof n.eventType=="string"&&typeof n.description=="string"&&typeof n.timestamp=="string"}function zd(e){if(!e||typeof e!="object")return!1;const n=e;return typeof n.rollup?.milestoneId=="string"&&typeof n.rollup?.state=="string"&&Array.isArray(n.validationTelemetry?.validationRounds)&&typeof n.validationTelemetry?.totalRuns=="number"&&n.validationContract!==void 0&&Array.isArray(n.fixFeatures)}const $v=["feature_triaged","feature_completed"],Dv=["slice_activated","slice_completed","milestone_completed"],Lv=["mission_started","mission_paused","mission_resumed","mission_completed"],Ov=["autopilot_enabled","autopilot_disabled","autopilot_state_changed","autopilot_retry","autopilot_stale"];function Of(e,n){switch(n){case"errors":return e==="error"||e==="warning";case"state_changes":return Lv.includes(e);case"tasks":return $v.includes(e);case"slices":return Dv.includes(e);case"autopilot":return Ov.includes(e);default:return!0}}function k4(e){return e==="error"||e==="warning"?"mission-event__type--error":Lv.includes(e)?"mission-event__type--state":$v.includes(e)?"mission-event__type--task":Dv.includes(e)?"mission-event__type--slice":Ov.includes(e)?"mission-event__type--autopilot":"mission-event__type--default"}function j4(e){return e.replace(/_/g," ")}function N4(e,n){return n?e==="watching"?`Watching since ${lc(n)}`:`Last activation ${lc(n)}`:null}function S4({isOpen:e,isInline:n=!1,onClose:s,addToast:a,projectId:r,onSelectTask:o,availableTasks:l=[],resumeSessionId:c,targetMissionId:d,milestoneSliceResumeSessionId:u,onMilestoneSliceResumeFetchError:h}){const m=n||e,[f,p]=i.useState([]),[g,w]=i.useState(null),[v,b]=i.useState(!0),[y,j]=i.useState(!1),S=ei()==="mobile",{pushNav:C}=Tv(),[x,k]=i.useState(()=>{if(typeof window>"u")return Af;const B=window.localStorage.getItem(Rf),$e=B?Number(B):NaN;return Number.isFinite($e)?Math.max(Cl,Math.min(El,$e)):Af}),R=i.useCallback(B=>{try{window.localStorage.setItem(Rf,String(B))}catch{}},[]),O=i.useCallback(B=>{if(S)return;B.preventDefault(),B.stopPropagation();const $e=B.currentTarget;typeof $e.setPointerCapture=="function"&&$e.setPointerCapture(B.pointerId);const Ye=B.clientX,jt=x;let Ce=jt;document.body.style.userSelect="none";const at=Ze=>{const it=Ze.clientX-Ye,$t=Math.max(Cl,Math.min(El,jt+it));Ce=$t,k($t)},It=Ze=>{typeof $e.releasePointerCapture=="function"&&$e.releasePointerCapture(Ze.pointerId),document.body.style.userSelect="",document.removeEventListener("pointermove",at),document.removeEventListener("pointerup",It),R(Ce)};document.addEventListener("pointermove",at),document.addEventListener("pointerup",It)},[S,R,x]),E=i.useCallback(B=>{if(S||B.key!=="ArrowLeft"&&B.key!=="ArrowRight")return;B.preventDefault();const $e=B.shiftKey?50:10,Ye=B.key==="ArrowLeft"?-$e:$e,jt=Math.max(Cl,Math.min(El,x+Ye));k(jt),R(jt)},[S,R,x]),[_,G]=i.useState(!1),[H,A]=i.useState(null),[P,q]=i.useState(Lf),[Y,ge]=i.useState(!1),[L,M]=i.useState(new Set),[$,D]=i.useState(new Set),[N,W]=i.useState(null),[de,me]=i.useState(Ld),[Ne,ve]=i.useState(!1),[Me,ie]=i.useState(null),[ye,Z]=i.useState(Od),[fe,Q]=i.useState(!1),[F,X]=i.useState(null),[re,U]=i.useState(null),[be,Ue]=i.useState(Fd),[se,Ve]=i.useState(!1),[Le,ct]=i.useState(null),[Ke,oe]=i.useState(null),[Te,Fe]=i.useState(""),[mt,We]=i.useState(!1),[he,pe]=i.useState([]),[De,ut]=i.useState([]),[ht,et]=i.useState(void 0),vt=i.useRef(null),Oe=ht??(c&&vt.current===c?void 0:c),[tt,ft]=i.useState(null),[Mt,yt]=i.useState(null),[Ge,K]=i.useState(null);i.useEffect(()=>{m&&Oe&&We(!0)},[m,Oe]),i.useEffect(()=>{c&&vt.current!==c&&(vt.current=null)},[c]),i.useEffect(()=>{if(!m)return;let B=!1;return Xu(r).then($e=>{if(B)return;const Ye=$e.filter(jt=>jt.type!=="mission_interview"||!p4.has(jt.status)?!1:r?jt.projectId===r:jt.projectId==null);pe(Ye)}).catch($e=>{console.warn("[MissionManager] Failed to fetch pending interview sessions:",$e)}),()=>{B=!0}},[m,r,Oe]),i.useEffect(()=>{if(!m)return;let B=!1;return T0(r).then($e=>{B||ut($e)}).catch($e=>{console.warn("[MissionManager] Failed to fetch mission interview drafts:",$e)}),()=>{B=!0}},[m,r,Oe]),i.useEffect(()=>{if(!m||!u)return;let B=!1;return $i(u).then($e=>{if(!(B||!$e))try{const Ye=JSON.parse($e.inputPayload||"{}");Ye.targetId&&Ye.targetType&&ft({type:Ye.targetType,id:Ye.targetId,title:Ye.targetTitle||$e.title,resumeSessionId:u})}catch{ft({type:"milestone",id:"",title:$e.title,resumeSessionId:u})}}).catch($e=>{B||(console.warn("[MissionManager] Failed to fetch session for milestone/slice resume:",$e),h?.())}),()=>{B=!0}},[m,u,h]);const[ue,ot]=i.useState(null),[xe,dt]=i.useState(new Map),[Je,ke]=i.useState(null),[nt,bt]=i.useState({title:"",assertion:"",status:"pending"}),[kt,wt]=i.useState(!1),[At,Ft]=i.useState(null),[ln,Vt]=i.useState(new Map),[hn,un]=i.useState(new Set),[pn,an]=i.useState(new Set),[Wt,gn]=i.useState(null),[cn,tn]=i.useState(new Map),[Yt,Qt]=i.useState(null),[Kt,Jt]=i.useState(null),[rn,qt]=i.useState(!0),[we,ze]=i.useState(new Set),[rt,He]=i.useState(new Map),[Ae,pt]=i.useState(null),[Ct,Tt]=i.useState(new Map),[Gt,nn]=i.useState(null),[Ht,on]=i.useState(new Map),[ae,le]=i.useState(new Map),[Qe,xt]=i.useState("structure"),[zt,sn]=i.useState([]),xn=i.useRef([]),$n=i.useRef([]),wn=i.useRef(null),zn=i.useRef(null),ce=i.useRef("structure"),ee=i.useRef("all"),[Se,qe]=i.useState(!1),[z,_e]=i.useState(0),[Rt,Ot]=i.useState("all"),[Lt,fn]=i.useState(new Set),kn=i.useRef(null),es=i.useRef(null);$n.current=f,wn.current=g,zn.current=Yt,ce.current=Qe,ee.current=Rt;const ms=i.useCallback((B="auto")=>{const $e=es.current;if($e&&typeof $e.scrollIntoView=="function"){$e.scrollIntoView({block:"end",behavior:B});return}const Ye=kn.current;Ye&&(Ye.scrollTop=Ye.scrollHeight)},[]),Gn=i.useCallback(()=>{const B=kn.current;return B?B.scrollHeight-B.scrollTop-B.clientHeight<=100:!0},[]),hs=i.useCallback(async B=>{if(B.length===0){le(new Map);return}const $e=await s0(r);le(Ye=>{const jt=new Map(Ye);for(const[Ce,at]of Object.entries($e))y4(at)&&jt.set(Ce,at);return jt})},[r]),Cn=i.useCallback(async()=>{try{b(!0);const B=await X1(r);p(B),hs(B)}catch(B){a(Ie(B)||"Failed to load missions","error")}finally{b(!1)}},[a,r,hs]),Bt=i.useCallback(async B=>{try{j(!0);const $e=await Db(B,r);if(!$e||!Array.isArray($e.milestones)){j(!1);return}if(w($e),$e.milestones.length>0){const Ye=$e.milestones[0].id;Qt(Ye),qt(!0),M(new Set([Ye])),Gc(Ye,r).then(jt=>{dt(Ce=>{const at=new Map(Ce);return at.set(Ye,jt),at})}).catch(()=>{}),Kc(Ye,r).then(jt=>{tn(Ce=>{const at=new Map(Ce);return at.set(Ye,jt),at})}).catch(()=>{}),$e.milestones[0].slices.length>0&&D(new Set([$e.milestones[0].slices[0].id]))}else Qt(null),Jt(null)}catch($e){a(Ie($e)||"Failed to load mission details","error")}finally{j(!1)}},[a,r]);i.useEffect(()=>{if(!m||!Yt){Jt(null);return}let B=!1;return Jt(null),hh(Yt,r).then($e=>{if(!B){if(!zd($e)){Jt(null);return}Jt($e),tn(Ye=>{const jt=new Map(Ye);return jt.set(Yt,$e.rollup),jt})}}).catch(()=>{B||Jt(null)}),()=>{B=!0}},[m,Yt,r]),i.useEffect(()=>{qt(!0)},[Yt]);const Bn=i.useCallback(B=>{!B||B!==zn.current||hh(B,r).then($e=>{zn.current!==B||!zd($e)||(Jt($e),tn(Ye=>{const jt=new Map(Ye);return jt.set(B,$e.rollup),jt}))}).catch(()=>{})},[r]),En=i.useCallback(async(B,$e)=>{const Ye=$e?.append??!1,jt=Ye?xn.current.length:0;Ye||(qe(!0),fn(new Set));try{const Ce=await n0(B,{limit:50,offset:jt,eventType:void 0},r),at=Ce.events.filter(It=>Of(It.eventType,Rt));sn(It=>{if(!Ye)return xn.current=at,at;const Ze=new Set(It.map($t=>$t.id)),it=[...It];for(const $t of at)Ze.has($t.id)||it.push($t);return xn.current=it,it}),_e(Ce.total),Ye||requestAnimationFrame(()=>{ms("auto")})}catch(Ce){a(Ie(Ce)||"Failed to load mission activity","error")}finally{Ye||qe(!1)}},[a,Rt,r,ms]);i.useEffect(()=>{xn.current=zt},[zt]),i.useEffect(()=>{m&&(Cn(),w(null),Qt(null),Jt(null),sn([]),_e(0),xt("structure"),Ot("all"),fn(new Set))},[m,Cn]);const bs=i.useRef(null);i.useEffect(()=>{m&&d&&bs.current!==d&&f.length>0&&(bs.current=d,Bt(d))},[m,d,f,Bt]),i.useEffect(()=>{m||(bs.current=null)},[m]);const $s=i.useRef(!1);i.useEffect(()=>{!m||!n||S||v||$s.current||g||d||f.length!==0&&($s.current=!0,Bt(f[0].id))},[m,n,S,v,f,g,d,Bt]),i.useEffect(()=>{m||($s.current=!1)},[m]),i.useEffect(()=>{!m||!g||Qe!=="activity"||En(g.id)},[Qe,m,En,g,Rt]),i.useEffect(()=>{if(!m||typeof EventSource>"u")return;const B=new URLSearchParams;r&&B.set("projectId",r);const $e=`/api/events${B.size>0?`?${B.toString()}`:""}`,Ye=()=>{hs($n.current)},jt=An=>{Ye();const Jn=An;if(Jn.data)try{const Zt=JSON.parse(Jn.data);Zt?.id&&p(ps=>ps.map(Ds=>Ds.id===Zt.id?{...Ds,...Zt}:Ds))}catch{}wn.current&&Bt(wn.current.id)},Ce=An=>{Ye(),wn.current&&Bt(wn.current.id)},at=()=>{Ye(),wn.current&&Bt(wn.current.id)},It=An=>{Ye(),wn.current&&Bt(wn.current.id)},Ze=An=>{const Jn=An;if(Jn.data)try{const Zt=JSON.parse(Jn.data);Zt&&Zt.featureId&&(Js(Zt.featureId),gi(Zt.featureId),Zt.milestoneId&&Bn(Zt.milestoneId))}catch{}},it=An=>{const Jn=An;if(Jn.data)try{const Zt=JSON.parse(Jn.data);Zt&&Zt.featureId&&(Js(Zt.featureId),gi(Zt.featureId),Zt.milestoneId&&Bn(Zt.milestoneId),wn.current&&Bt(wn.current.id))}catch{}},$t=An=>{const Jn=An;if(Jn.data)try{const Zt=JSON.parse(Jn.data);Zt&&Zt.milestoneId&&(ns(Zt.milestoneId),Bn(Zt.milestoneId))}catch{}},Pn=An=>{const Jn=An;if(Jn.data)try{const Zt=JSON.parse(Jn.data);Zt&&Zt.milestoneId&&(os(Zt.milestoneId),ns(Zt.milestoneId),Bn(Zt.milestoneId))}catch{}};return fi($e,{events:{"mission:updated":jt,"slice:updated":Ce,"feature:updated":at,"milestone:updated":It,"mission:event":An=>{Ye();const Jn=wn.current;if(!Jn||ce.current!=="activity")return;const Zt=Gn(),ps=An;if(ps.data)try{const Ds=JSON.parse(ps.data);if(!w4(Ds)||Ds.missionId!==Jn.id||!Of(Ds.eventType,ee.current))return;sn(ri=>{const la=ri.filter(Zr=>Zr.id!==Ds.id);return[Ds,...la].slice(0,100)}),_e(ri=>ri+1),Zt&&requestAnimationFrame(()=>{const ri=kn.current;ri&&(ri.scrollTop=0)})}catch{}},"validator-run:started":Ze,"validator-run:completed":it,"milestone:validation:updated":$t,"assertion:created":Pn,"assertion:updated":Pn,"assertion:deleted":Pn,"assertion:linked":Pn,"assertion:unlinked":Pn,"fix-feature:created":An=>{const Jn=An;if(Jn.data)try{const Zt=JSON.parse(Jn.data);if(Zt&&Zt.sourceFeatureId){Js(Zt.sourceFeatureId);const ps=Zt?.feature?.sliceId,Ds=wn.current;if(ps&&Ds){const ri=Ds.milestones.find(la=>la.slices.some(Zr=>Zr.id===ps));ri&&Bn(ri.id)}wn.current&&Bt(wn.current.id)}}catch{}}}})},[m,Gn,Bt,hs,r,Bn]);const ss=i.useCallback(B=>{A(B.id),G(!1),q({title:B.title,description:B.description||"",status:B.status,autopilotEnabled:B.autopilotEnabled??!1})},[]),Un=i.useCallback(()=>{A(null),G(!1),q(Lf)},[]),Kn=i.useCallback(async()=>{if(!P.title.trim()){a("Mission title is required","error");return}try{if(ge(!0),_)await Z1({title:P.title.trim(),description:P.description.trim()||void 0,autopilotEnabled:P.autopilotEnabled},r),a("Mission created","success");else if(H){const B={title:P.title.trim(),description:P.description.trim()||void 0,status:P.status,autopilotEnabled:P.autopilotEnabled};P.autopilotEnabled&&(B.autoAdvance=!0),await e0(H,B,r),a("Mission updated","success"),g?.id===H&&await Bt(H)}await Cn(),Un()}catch(B){a(Ie(B)||"Failed to save mission","error")}finally{ge(!1)}},[P,_,H,a,Cn,Bt,g,Un,r]),Ms=i.useCallback(async B=>{try{await t0(B,r),a("Mission deleted","success"),g?.id===B&&w(null),await Cn(),ot(null)}catch($e){a(Ie($e)||"Failed to delete mission","error")}},[a,Cn,g,r]),xs=i.useCallback(()=>{ve(!0),W(null),me(Ld)},[]),As=i.useCallback(B=>{W(B.id),ve(!1),me({title:B.title,description:B.description||"",status:B.status,dependencies:B.dependencies})},[]),vs=i.useCallback(()=>{W(null),ve(!1),me(Ld)},[]),te=i.useCallback(async()=>{if(!de.title.trim()){a("Milestone title is required","error");return}try{ge(!0),Ne&&g?(await i0(g.id,{title:de.title.trim(),description:de.description.trim()||void 0,dependencies:de.dependencies},r),a("Milestone created","success")):N&&(await a0(N,{title:de.title.trim(),description:de.description.trim()||void 0,status:de.status,dependencies:de.dependencies},r),a("Milestone updated","success")),await Bt(g.id),vs()}catch(B){a(Ie(B)||"Failed to save milestone","error")}finally{ge(!1)}},[de,Ne,N,g,a,Bt,vs,P.title,r]),Ee=i.useCallback(async B=>{try{await r0(B,r),a("Milestone deleted","success"),await Bt(g.id),ot(null)}catch($e){a(Ie($e)||"Failed to delete milestone","error")}},[a,Bt,g,r]),T=i.useCallback(B=>{Qt(B),qt(!0),M($e=>{const Ye=new Set($e);return!Ye.has(B)?(Ye.add(B),Gc(B,r).then(Ce=>{dt(at=>{const It=new Map(at);return It.set(B,Ce),It})}).catch(()=>{}),Kc(B,r).then(Ce=>{tn(at=>{const It=new Map(at);return It.set(B,Ce),It})}).catch(()=>{})):Ye.delete(B),Ye})},[r]),je=i.useCallback(B=>{X(B),Q(!0),ie(null),Z(Od)},[]),Pe=i.useCallback(B=>{ie(B.id),Q(!1),Z({title:B.title,description:B.description||"",status:B.status})},[]),st=i.useCallback(()=>{ie(null),Q(!1),X(null),Z(Od)},[]),gt=i.useCallback(async()=>{if(!ye.title.trim()){a("Slice title is required","error");return}try{ge(!0),fe&&F?(await o0(F,{title:ye.title.trim(),description:ye.description.trim()||void 0},r),a("Slice created","success")):Me&&(await l0(Me,{title:ye.title.trim(),description:ye.description.trim()||void 0,status:ye.status},r),a("Slice updated","success")),await Bt(g.id),st()}catch(B){a(Ie(B)||"Failed to save slice","error")}finally{ge(!1)}},[ye,fe,Me,F,g,a,Bt,st,r]),Et=i.useCallback(async B=>{try{await c0(B,r),a("Slice deleted","success"),await Bt(g.id),ot(null)}catch($e){a(Ie($e)||"Failed to delete slice","error")}},[a,Bt,g,r]),Pt=i.useCallback(async B=>{try{await d0(B,r),a("Slice activated","success"),await Bt(g.id)}catch($e){a(Ie($e)||"Failed to activate slice","error")}},[a,Bt,g,r]),dn=i.useCallback(B=>{D($e=>{const Ye=new Set($e);return Ye.has(B)?Ye.delete(B):Ye.add(B),Ye})},[]),Nn=i.useCallback(B=>{ct(B),Ve(!0),U(null),Ue(Fd)},[]),Hn=i.useCallback(B=>{U(B.id),Ve(!1),Ue({title:B.title,description:B.description||"",acceptanceCriteria:B.acceptanceCriteria||"",status:B.status})},[]),ne=i.useCallback(()=>{U(null),Ve(!1),ct(null),Ue(Fd)},[]),Be=i.useCallback(async()=>{if(!be.title.trim()){a("Feature title is required","error");return}try{ge(!0),se&&Le?(await u0(Le,{title:be.title.trim(),description:be.description.trim()||void 0,acceptanceCriteria:be.acceptanceCriteria.trim()||void 0},r),a("Feature created","success")):re&&(await m0(re,{title:be.title.trim(),description:be.description.trim()||void 0,acceptanceCriteria:be.acceptanceCriteria.trim()||void 0,status:be.status},r),a("Feature updated","success")),await Bt(g.id),ne()}catch(B){a(Ie(B)||"Failed to save feature","error")}finally{ge(!1)}},[be,se,re,Le,g,a,Bt,ne,r]),Xe=i.useCallback(async B=>{try{await h0(B,r),a("Feature deleted","success"),await Bt(g.id),ot(null)}catch($e){a(Ie($e)||"Failed to delete feature","error")}},[a,Bt,g,r]),Dt=i.useCallback(async()=>{if(!Ke||!Te.trim()){a("Task ID is required","error");return}try{await p0(Ke,Te.trim(),r),a("Feature linked to task","success"),await Bt(g.id),oe(null),Fe("")}catch(B){a(Ie(B)||"Failed to link feature to task","error")}},[Ke,Te,a,Bt,g,r]),Xt=i.useCallback(async B=>{try{await f0(B,r),a("Feature unlinked from task","success"),await Bt(g.id)}catch($e){a(Ie($e)||"Failed to unlink feature","error")}},[a,Bt,g,r]),mn=i.useCallback(async B=>{try{ge(!0),await g0(B,void 0,void 0,r),a("Feature triaged — task created","success"),await Bt(g.id)}catch($e){a(Ie($e)||"Failed to triage feature","error")}finally{ge(!1)}},[a,Bt,g,r]),qn=i.useCallback(async B=>{K(B);try{const $e=await G0(B,r);yt({featureId:B,enrichedDescription:$e.description})}catch{await mn(B)}finally{K(null)}},[mn,r]),Dn=i.useCallback(async()=>{Mt&&(yt(null),await mn(Mt.featureId))},[mn,Mt]),ts=i.useCallback(()=>{yt(null)},[]),Vn=i.useCallback(async B=>{try{ge(!0);const $e=await b0(B,r);a(`Triaged ${$e.count} feature${$e.count!==1?"s":""}`,"success"),await Bt(g.id)}catch($e){a(Ie($e)||"Failed to triage slice features","error")}finally{ge(!1)}},[a,Bt,g,r]),os=i.useCallback(async B=>{try{const $e=await Gc(B,r);dt(Ye=>{const jt=new Map(Ye);return jt.set(B,$e),jt})}catch{}},[r]),ns=i.useCallback(async B=>{try{const $e=await Kc(B,r);tn(Ye=>{const jt=new Map(Ye);return jt.set(B,$e),jt})}catch{}},[r]),ja=i.useCallback(async B=>{if(!nt.title.trim()||!nt.assertion.trim()){a("Title and assertion text are required","error");return}try{ge(!0),await x0(B,{title:nt.title.trim(),assertion:nt.assertion.trim(),status:nt.status},r),a("Assertion created","success"),await os(B),await ns(B),wt(!1),bt({title:"",assertion:"",status:"pending"})}catch($e){a(Ie($e)||"Failed to create assertion","error")}finally{ge(!1)}},[nt,a,os,ns,r]),Na=i.useCallback(B=>{ke(B.id),bt({title:B.title,assertion:B.assertion,status:B.status})},[]),zi=i.useCallback(()=>{ke(null),wt(!1),bt({title:"",assertion:"",status:"pending"})},[]),Kr=i.useCallback(async(B,$e)=>{if(!nt.title.trim()||!nt.assertion.trim()){a("Title and assertion text are required","error");return}try{ge(!0),await v0(B,{title:nt.title.trim(),assertion:nt.assertion.trim(),status:nt.status},r),a("Assertion updated","success"),await os($e),await ns($e),zi()}catch(Ye){a(Ie(Ye)||"Failed to update assertion","error")}finally{ge(!1)}},[nt,a,os,ns,zi,r]),Us=i.useCallback(async B=>{try{const $e=await k0(B,r);Vt(Ye=>{const jt=new Map(Ye);return jt.set(B,$e),jt})}catch{}},[r]),Bi=i.useCallback(async B=>{const $e=At!==B;Ft(Ye=>Ye===B?null:B),$e&&await Us(B)},[At,Us]),Qa=i.useCallback(B=>{Ft(B),Us(B),requestAnimationFrame(()=>{const $e=document.querySelector(`[data-mission-assertion-id="${B}"]`);$e instanceof HTMLElement&&typeof $e.scrollIntoView=="function"&&$e.scrollIntoView({behavior:"smooth",block:"center"})})},[Us]),ls=i.useCallback(async(B,$e)=>{try{un(Ye=>new Set(Ye).add($e)),await y0(B,$e,r),a("Feature linked to assertion","success"),await Us($e),gn(null)}catch(Ye){a(Ie(Ye)||"Failed to link feature","error")}finally{un(Ye=>{const jt=new Set(Ye);return jt.delete($e),jt})}},[a,Us,r]),Jr=i.useCallback(async(B,$e)=>{const Ye=`${B}-${$e}`;try{an(jt=>new Set(jt).add(Ye)),await w0(B,$e,r),a("Feature unlinked from assertion","success"),await Us($e)}catch(jt){a(Ie(jt)||"Failed to unlink feature","error")}finally{an(jt=>{const Ce=new Set(jt);return Ce.delete(Ye),Ce})}},[a,Us,r]),ta=i.useCallback(async B=>{try{ze(Ye=>new Set(Ye).add(B)),await j0(B,r),a("Validation triggered","success");const $e=await ph(B,r);He(Ye=>{const jt=new Map(Ye);return jt.set(B,$e),jt})}catch($e){a(Ie($e)||"Failed to trigger validation","error")}finally{ze($e=>{const Ye=new Set($e);return Ye.delete(B),Ye})}},[a,r]),Js=i.useCallback(async B=>{try{const $e=await ph(B,r);He(Ye=>{const jt=new Map(Ye);return jt.set(B,$e),jt})}catch{}},[r]),gi=i.useCallback(async B=>{try{const $e=await N0(B,{limit:10},r);Tt(Ye=>{const jt=new Map(Ye);return jt.set(B,$e),jt})}catch{}},[r]),na=i.useCallback(B=>{const $e=wn.current;if($e){for(const Ye of $e.milestones)for(const jt of Ye.slices)if(jt.features.find(at=>at.id===B)){M(at=>{const It=new Set(at);return It.add(Ye.id),It}),D(at=>{const It=new Set(at);return It.add(jt.id),It}),pt(B),Qt(Ye.id),Js(B),gi(B),requestAnimationFrame(()=>{const at=document.querySelector(`[data-mission-feature-id="${B}"]`);at instanceof HTMLElement&&typeof at.scrollIntoView=="function"&&at.scrollIntoView({behavior:"smooth",block:"center"})});return}}},[Js,gi]),Sa=i.useCallback(async B=>{try{const $e=await S0(B,r);on(Ye=>{const jt=new Map(Ye);return jt.set(B,$e),jt})}catch{}},[r]),bi=i.useCallback(async B=>{Ae===B?pt(null):(pt(B),await Js(B),await gi(B))},[Ae,Js,gi]),_n=i.useCallback(async B=>{Gt===B?nn(null):(nn(B),await Sa(B))},[Gt,Sa]),Ca=i.useCallback(async B=>{try{await C0(B,r),a("Mission resumed","success"),await Bt(B),Cn()}catch($e){a(Ie($e)||"Failed to resume mission","error")}},[a,Bt,Cn,r]),sa=i.useCallback(async B=>{try{const Ye=(await E0(B,r)).pausedTaskIds?.length??0;a(`Mission stopped (${Ye} task${Ye!==1?"s":""} paused)`,"success"),await Bt(B),Cn()}catch($e){a(Ie($e)||"Failed to stop mission","error")}},[a,Bt,Cn,r]),ia=i.useCallback(async B=>{try{await _0(B,r),a("Mission started — first slice activated","success"),await Bt(B),Cn()}catch($e){a(Ie($e)||"Failed to start mission","error")}},[a,Bt,Cn,r]),Xa=i.useCallback(async(B,$e)=>{try{await M0(B,{enabled:$e},r),a($e?"Autopilot enabled":"Autopilot disabled","success"),await Bt(B),Cn()}catch(Ye){a(Ie(Ye)||"Failed to update autopilot","error")}},[a,Bt,Cn,r]),Ui=i.useCallback(B=>{xt("structure"),Qt(null),Jt(null),sn([]),_e(0),Ot("all"),fn(new Set),Bt(B.id)},[Bt]),aa=i.useCallback(()=>{w(null),Qt(null),Jt(null),xt("structure"),sn([]),_e(0),Ot("all"),fn(new Set),Cn()},[Cn]),ra=zt.length<z,xi=g?.autopilotState??"inactive",Za=xi==="watching"||xi==="activating",Ea=N4(xi,g?.lastAutopilotActivityAt),_a=i.useRef(g?.id??null);i.useEffect(()=>{const B=_a.current,$e=g?.id??null;_a.current=$e,!(!m||!S||!$e||B===$e)&&C({type:"view",revert:aa})},[aa,m,S,C,g?.id]);const Hs=i.useMemo(()=>!Kt||!Yt||!zd(Kt)?null:Kt.rollup.milestoneId===Yt?Kt:null,[Yt,Kt]),Ci=i.useMemo(()=>{const B=new Map;for(const $e of Hs?.validationTelemetry.validationRounds??[]){const Ye=B.get($e.featureId);(!Ye||$e.startedAt>Ye.startedAt)&&B.set($e.featureId,$e)}return B},[Hs]),ni=i.useCallback(()=>{!g||Se||!ra||En(g.id,{append:!0})},[Se,ra,En,g]),er=i.useCallback(B=>{fn($e=>{const Ye=new Set($e);return Ye.has(B)?Ye.delete(B):Ye.add(B),Ye})},[]),Ei=i.useCallback(B=>{B.key==="Enter"&&!B.shiftKey&&(B.preventDefault(),Kn())},[Kn]),Ma=i.useCallback(B=>{B.key==="Enter"&&!B.shiftKey&&(B.preventDefault(),te())},[te]),si=i.useCallback(B=>{B.key==="Enter"&&!B.shiftKey&&(B.preventDefault(),gt())},[gt]),tr=i.useCallback(B=>{B.key==="Enter"&&!B.shiftKey&&(B.preventDefault(),Be())},[Be]),Yr=i.useRef(null);if(i.useEffect(()=>{if(!m)return;const B=$e=>{$e.key==="Escape"&&s()};return document.addEventListener("keydown",B),()=>document.removeEventListener("keydown",B)},[m,s]),!m)return null;const nr=()=>g?t.jsxs("div",{className:"mission-detail",children:[t.jsxs("div",{className:"mission-detail__header",children:[t.jsxs("div",{className:"mission-detail__title-row",children:[t.jsxs("div",{className:"mission-detail__title-text",children:[Za&&t.jsx("span",{className:"mission-detail__autopilot-dot",title:"Autopilot watching"}),t.jsx("h3",{className:"mission-detail__title",children:g.title})]}),t.jsx("span",{className:"mission-status-badge",style:{backgroundColor:(uo[g.status]||uo.planning).bg,color:(uo[g.status]||uo.planning).text},children:g.status})]}),g.description&&t.jsx("p",{className:"mission-detail__description",children:g.description}),t.jsx("div",{className:"mission-detail__meta",children:t.jsxs("span",{className:"mission-detail__meta-info",children:[g.milestones.length," milestones"]})}),t.jsxs("div",{className:"mission-detail__autopilot",children:[t.jsxs("div",{className:"mission-detail__autopilot-toggle",children:[t.jsxs("label",{className:"mission-toggle","data-testid":"mission-autopilot-toggle",children:[t.jsx("input",{type:"checkbox",checked:g.autopilotEnabled??!1,onChange:B=>Xa(g.id,B.target.checked),"aria-label":"Autopilot"}),t.jsx("span",{className:"mission-toggle__track","aria-hidden":"true",children:t.jsx("span",{className:"mission-toggle__thumb"})}),t.jsxs("span",{className:"mission-toggle__label",children:[t.jsx(as,{size:14,className:"mission-detail__autopilot-icon"}),"Autopilot"]})]}),t.jsxs("span",{className:"mission-status-badge mission-status-badge--sm",style:{backgroundColor:(Ml[xi]||Ml.inactive).bg,color:(Ml[xi]||Ml.inactive).text},"data-testid":"autopilot-state-badge",children:[Za&&t.jsx("span",{className:"mission-detail__autopilot-pulse"}),xi]})]}),Ea&&t.jsx("span",{className:"mission-detail__autopilot-activity mission-relative-time",children:Ea})]}),t.jsxs("div",{className:"mission-detail__actions",children:[g.status==="active"&&t.jsx("button",{className:"mission-icon-btn mission-icon-btn--danger",onClick:()=>sa(g.id),title:"Stop mission","aria-label":"Stop mission",children:t.jsx(Pi,{size:14})}),g.status==="blocked"&&t.jsx("button",{className:"mission-icon-btn mission-icon-btn--success",onClick:()=>Ca(g.id),title:"Resume mission","aria-label":"Resume mission",children:t.jsx(is,{size:14})}),g.status==="planning"&&t.jsx("button",{className:"mission-icon-btn mission-icon-btn--success",onClick:()=>ia(g.id),title:"Start mission","aria-label":"Start mission",children:t.jsx(is,{size:14})}),t.jsx("button",{className:"mission-icon-btn",onClick:()=>ss(g),title:"Edit mission","aria-label":"Edit mission",children:t.jsx(Os,{size:14})}),t.jsx("button",{className:"mission-icon-btn mission-icon-btn--danger",onClick:()=>ot({type:"mission",id:g.id}),title:"Delete mission","aria-label":"Delete mission",children:t.jsx(In,{size:14})})]})]}),H===g.id&&t.jsxs("div",{className:"mission-form-card",children:[t.jsx("input",{type:"text",placeholder:"Mission title",value:P.title,onChange:B=>q({...P,title:B.target.value}),onKeyDown:Ei,autoFocus:!0}),t.jsx("textarea",{placeholder:"Description (optional)",value:P.description,onChange:B=>q({...P,description:B.target.value}),rows:2}),t.jsxs("div",{className:"mission-form-card__row",children:[t.jsxs("select",{value:P.status,onChange:B=>q({...P,status:B.target.value}),children:[t.jsx("option",{value:"planning",children:"Planning"}),t.jsx("option",{value:"active",children:"Active"}),t.jsx("option",{value:"blocked",children:"Blocked"}),t.jsx("option",{value:"complete",children:"Complete"}),t.jsx("option",{value:"archived",children:"Archived"})]}),t.jsxs("label",{className:"mission-checkbox",children:[t.jsx("input",{type:"checkbox",checked:P.autopilotEnabled,onChange:B=>q({...P,autopilotEnabled:B.target.checked})}),t.jsx(as,{size:12})," Autopilot"]})]}),t.jsxs("div",{className:"mission-form-card__actions",children:[t.jsxs("button",{className:"mission-btn mission-btn--primary",onClick:Kn,disabled:Y,children:[Y?t.jsx(St,{size:14,className:"spinner"}):t.jsx(gs,{size:14}),"Update"]}),t.jsx("button",{className:"mission-btn mission-btn--ghost",onClick:Un,children:"Cancel"})]})]}),t.jsxs("div",{className:"mission-detail__tabs",role:"tablist","aria-label":"Mission detail tabs",children:[t.jsx("button",{className:`mission-btn ${Qe==="structure"?"mission-btn--primary":"mission-btn--ghost"} mission-btn--sm mission-detail__tab`,onClick:()=>xt("structure"),role:"tab","aria-selected":Qe==="structure","data-testid":"mission-tab-structure",children:"Structure"}),t.jsxs("button",{className:`mission-btn ${Qe==="activity"?"mission-btn--primary":"mission-btn--ghost"} mission-btn--sm mission-detail__tab`,onClick:()=>xt("activity"),role:"tab","aria-selected":Qe==="activity","data-testid":"mission-tab-activity",children:["Activity (",z,")"]})]}),Qe==="structure"?t.jsxs("div",{className:"mission-detail__milestones",children:[g.milestones.map(B=>{const $e=Hs?.rollup.milestoneId===B.id?Hs:null,Ye=$e?.rollup??cn.get(B.id),jt=$e?.validationTelemetry.validationRounds??[],Ce=$e?.fixFeatures??[],at=Pf[Ye?.state??"not_started"]??Pf.not_started,It=Ye&&(Ye.state==="blocked"||Ye.state==="failed")?$e?.validationTelemetry.validationRounds.find(Ze=>Ze.blockedReason)?.blockedReason:void 0;return t.jsxs("div",{className:"mission-milestone",children:[t.jsxs("div",{className:"mission-milestone__header",onClick:()=>T(B.id),children:[t.jsx("button",{className:"mission-milestone__expand",children:L.has(B.id)?t.jsx(vn,{size:16}):t.jsx(Wn,{size:16})}),t.jsx(Fa,{size:16,className:"mission-milestone__icon"}),t.jsx("span",{className:"mission-milestone__title",children:B.title}),t.jsx("span",{className:"mission-status-badge mission-status-badge--sm",style:{backgroundColor:If[B.status].bg,color:If[B.status].text},children:B.status}),t.jsxs("span",{className:"mission-milestone__count",children:[B.slices.length," slices"]}),t.jsx($f,{state:b4(B.interviewState)}),Ye&&t.jsxs(t.Fragment,{children:[t.jsx("span",{className:"mission-status-badge mission-status-badge--sm",style:{backgroundColor:at.bg,color:at.text},title:"Validation state",children:Df(Ye.state)}),Ye.totalAssertions>0&&t.jsx("div",{className:"mission-milestone__coverage-bar",title:`${Ye.passedAssertions??0} of ${Ye.totalAssertions} assertions passing`,children:t.jsx("div",{className:"mission-milestone__coverage-bar-fill",style:{width:`${(Ye.passedAssertions??0)/Ye.totalAssertions*100}%`,backgroundColor:(Ye.passedAssertions??0)===Ye.totalAssertions?"var(--color-success)":"var(--color-warning)"}})})]}),B.status!=="complete"&&t.jsx("button",{className:"mission-icon-btn",onClick:()=>ft({type:"milestone",id:B.id,title:B.title}),title:"Plan milestone","aria-label":"Plan milestone",children:t.jsx(xa,{size:14})}),t.jsxs("div",{className:"mission-milestone__actions",onClick:Ze=>Ze.stopPropagation(),children:[t.jsx("button",{className:"mission-icon-btn",onClick:()=>je(B.id),title:"Add slice",children:t.jsx(Tn,{size:14})}),t.jsx("button",{className:"mission-icon-btn",onClick:()=>As(B),title:"Edit milestone",children:t.jsx(Os,{size:14})}),t.jsx("button",{className:"mission-icon-btn mission-icon-btn--danger",onClick:()=>ot({type:"milestone",id:B.id}),title:"Delete milestone",children:t.jsx(In,{size:14})})]})]}),L.has(B.id)&&t.jsxs("div",{className:"mission-milestone__body",children:[(Ne||N===B.id)&&t.jsxs("div",{className:"mission-form-card",children:[t.jsx("input",{type:"text",placeholder:"Milestone title",value:de.title,onChange:Ze=>me({...de,title:Ze.target.value}),onKeyDown:Ma,autoFocus:!0}),t.jsx("textarea",{placeholder:"Description (optional)",value:de.description,onChange:Ze=>me({...de,description:Ze.target.value}),rows:2}),t.jsxs("div",{className:"mission-form-card__actions",children:[t.jsxs("button",{className:"mission-btn mission-btn--primary",onClick:te,disabled:Y,children:[Y?t.jsx(St,{size:14,className:"spinner"}):t.jsx(gs,{size:14}),N?"Update":"Create"]}),t.jsx("button",{className:"mission-btn mission-btn--ghost",onClick:vs,children:"Cancel"})]})]}),$e&&t.jsxs("div",{className:"mission-validation-telemetry",children:[t.jsxs("div",{className:"mission-validation-telemetry__header",children:[t.jsx("span",{className:"mission-validation-telemetry__title",children:"Validation Telemetry"}),t.jsxs("span",{className:"mission-validation-telemetry__meta",children:[$e.validationTelemetry.totalRuns," rounds",$e.validationTelemetry.lastValidatorStatus?` · Last ${$e.validationTelemetry.lastValidatorStatus}`:""]})]}),It&&t.jsxs("div",{className:"mission-blocked-reason",children:[t.jsx("strong",{children:"Blocked reason:"})," ",It]}),jt.length>0&&t.jsxs("div",{className:"mission-validation-rounds",children:[t.jsxs("button",{className:"mission-btn mission-btn--ghost mission-btn--sm mission-validation-rounds__toggle",onClick:()=>qt(Ze=>!Ze),title:rn?"Hide validation rounds":"Show validation rounds",children:[rn?t.jsx(vn,{size:12}):t.jsx(Wn,{size:12}),"Validation rounds (",jt.length,")"]}),rn&&t.jsx("div",{className:"mission-validation-rounds__list",children:jt.map(Ze=>t.jsxs("div",{className:"mission-validation-round",children:[t.jsxs("div",{className:"mission-validation-round__header",children:[t.jsx("span",{className:`mission-status-badge mission-status-badge--sm mission-validation-round__status mission-validation-round__status--${Ze.validatorStatus}`,children:Ze.validatorStatus}),t.jsx("span",{className:"mission-validation-round__feature",children:Ze.featureTitle}),t.jsxs("span",{className:"mission-validation-round__attempts",children:["impl #",Ze.implementationAttempt," · reviewer #",Ze.validatorAttempt]})]}),t.jsxs("div",{className:"mission-validation-round__links",children:[t.jsx("span",{className:"mission-validation-round__label",children:"Failed assertions:"}),Ze.failedAssertionIds.length>0?t.jsx("div",{className:"mission-validation-round__chip-list",children:Ze.failedAssertionIds.map(it=>t.jsx("button",{className:"mission-validation-round__link-chip",onClick:()=>Qa(it),title:`Jump to assertion ${it}`,children:it},`${Ze.roundId}-${it}`))}):t.jsx("span",{className:"mission-validation-round__empty",children:"None"})]}),t.jsxs("div",{className:"mission-validation-round__links",children:[t.jsx("span",{className:"mission-validation-round__label",children:"Generated fix features:"}),Ze.generatedFixFeatureIds.length>0?t.jsx("div",{className:"mission-validation-round__chip-list",children:Ze.generatedFixFeatureIds.map(it=>t.jsx("button",{className:"mission-validation-round__link-chip",onClick:()=>na(it),title:`Jump to fix feature ${it}`,children:it},`${Ze.roundId}-${it}`))}):t.jsx("span",{className:"mission-validation-round__empty",children:"None"})]}),Ze.blockedReason&&t.jsx("div",{className:"mission-validation-round__blocked-reason",children:Ze.blockedReason})]},Ze.roundId))})]}),Ce.length>0&&t.jsxs("div",{className:"mission-fix-features",children:[t.jsx("div",{className:"mission-fix-features__title",children:"Generated Fix Features"}),t.jsx("div",{className:"mission-fix-features__list",children:Ce.map(Ze=>t.jsxs("div",{className:"mission-fix-feature",children:[t.jsxs("div",{className:"mission-fix-feature__header",children:[t.jsx("button",{className:"mission-fix-feature__title",onClick:()=>na(Ze.id),title:`Jump to feature ${Ze.id}`,children:Ze.title}),t.jsx("span",{className:"mission-status-badge mission-status-badge--sm",style:{backgroundColor:_l[Ze.status].bg,color:_l[Ze.status].text},children:Ze.status}),Ze.loopState&&t.jsx("span",{className:`mission-loop-state mission-loop-state--${Ze.loopState}`,children:Ze.loopState})]}),t.jsxs("div",{className:"mission-fix-feature__meta",children:[t.jsx("span",{children:"Source:"}),t.jsx("button",{className:"mission-validation-round__link-chip",onClick:()=>na(Ze.sourceFeatureId),title:`Jump to source feature ${Ze.sourceFeatureId}`,children:Ze.sourceFeatureId}),t.jsx("span",{children:"Run:"}),t.jsx("span",{className:"mission-fix-feature__run",children:Ze.runId})]}),Ze.failedAssertionIds.length>0&&t.jsxs("div",{className:"mission-fix-feature__assertions",children:[t.jsx("span",{className:"mission-validation-round__label",children:"Failed assertions:"}),t.jsx("div",{className:"mission-validation-round__chip-list",children:Ze.failedAssertionIds.map(it=>t.jsx("button",{className:"mission-validation-round__link-chip",onClick:()=>Qa(it),title:`Jump to assertion ${it}`,children:it},`${Ze.id}-${it}`))})]})]},Ze.id))})]})]}),t.jsxs("div",{className:"mission-slices",children:[B.slices.map(Ze=>t.jsxs("div",{className:"mission-slice",children:[t.jsxs("div",{className:"mission-slice__header",onClick:()=>dn(Ze.id),children:[t.jsx("button",{className:"mission-slice__expand",children:$.has(Ze.id)?t.jsx(vn,{size:16}):t.jsx(Wn,{size:16})}),t.jsx(du,{size:16,className:"mission-slice__icon"}),t.jsx("span",{className:"mission-slice__title",children:Ze.title}),t.jsx("span",{className:"mission-status-badge mission-status-badge--sm",style:{backgroundColor:Tf[Ze.status].bg,color:Tf[Ze.status].text},children:Ze.status}),t.jsxs("span",{className:"mission-slice__count",children:[Ze.features?.length||0," features"]}),t.jsx($f,{state:Ze.planState??"not_started"}),Ze.status!=="complete"&&t.jsx("button",{className:"mission-icon-btn",onClick:()=>ft({type:"slice",id:Ze.id,title:Ze.title}),title:"Plan slice","aria-label":"Plan slice",children:t.jsx(xa,{size:14})}),t.jsxs("div",{className:"mission-slice__actions",onClick:it=>it.stopPropagation(),children:[Ze.status==="pending"&&t.jsx("button",{className:"mission-icon-btn mission-icon-btn--success",onClick:()=>Pt(Ze.id),title:"Activate slice",children:t.jsx(is,{size:14})}),Ze.status==="active"&&Ze.features?.some(it=>it.status==="defined")&&t.jsx("button",{className:"mission-icon-btn",onClick:()=>Vn(Ze.id),title:"Triage all features",disabled:Y,children:Y?t.jsx(St,{size:14,className:"spinner"}):t.jsx(as,{size:14})}),t.jsx("button",{className:"mission-icon-btn",onClick:()=>Nn(Ze.id),title:"Add feature",children:t.jsx(Tn,{size:14})}),t.jsx("button",{className:"mission-icon-btn",onClick:()=>Pe(Ze),title:"Edit slice",children:t.jsx(Os,{size:14})}),t.jsx("button",{className:"mission-icon-btn mission-icon-btn--danger",onClick:()=>ot({type:"slice",id:Ze.id}),title:"Delete slice",children:t.jsx(In,{size:14})})]})]}),$.has(Ze.id)&&t.jsxs("div",{className:"mission-slice__body",children:[fe&&F===B.id&&!Me&&t.jsxs("div",{className:"mission-form-card",children:[t.jsx("input",{type:"text",placeholder:"Slice title",value:ye.title,onChange:it=>Z({...ye,title:it.target.value}),onKeyDown:si,autoFocus:!0}),t.jsx("textarea",{placeholder:"Description (optional)",value:ye.description,onChange:it=>Z({...ye,description:it.target.value}),rows:2}),t.jsxs("div",{className:"mission-form-card__actions",children:[t.jsxs("button",{className:"mission-btn mission-btn--primary",onClick:gt,disabled:Y,children:[Y?t.jsx(St,{size:14,className:"spinner"}):t.jsx(gs,{size:14}),"Create"]}),t.jsx("button",{className:"mission-btn mission-btn--ghost",onClick:st,children:"Cancel"})]})]}),Me===Ze.id&&t.jsxs("div",{className:"mission-form-card",children:[t.jsx("input",{type:"text",placeholder:"Slice title",value:ye.title,onChange:it=>Z({...ye,title:it.target.value}),onKeyDown:si,autoFocus:!0}),t.jsx("textarea",{placeholder:"Description (optional)",value:ye.description,onChange:it=>Z({...ye,description:it.target.value}),rows:2}),t.jsxs("select",{value:ye.status,onChange:it=>Z({...ye,status:it.target.value}),children:[t.jsx("option",{value:"pending",children:"Pending"}),t.jsx("option",{value:"active",children:"Active"}),t.jsx("option",{value:"complete",children:"Complete"})]}),t.jsxs("div",{className:"mission-form-card__actions",children:[t.jsxs("button",{className:"mission-btn mission-btn--primary",onClick:gt,disabled:Y,children:[Y?t.jsx(St,{size:14,className:"spinner"}):t.jsx(gs,{size:14}),"Update"]}),t.jsx("button",{className:"mission-btn mission-btn--ghost",onClick:st,children:"Cancel"})]})]}),t.jsxs("div",{className:"mission-features",children:[Ze.features?.map(it=>t.jsxs("div",{className:"mission-feature","data-mission-feature-id":it.id,children:[t.jsxs("div",{className:"mission-feature__header",children:[t.jsx("button",{className:"mission-feature__expand",onClick:()=>bi(it.id),title:Ae===it.id?"Collapse details":"Expand to show run history",children:Ae===it.id?t.jsx(vn,{size:14}):t.jsx(Wn,{size:14})}),t.jsx(iu,{size:14,className:"mission-feature__icon"}),t.jsx("span",{className:"mission-feature__title",children:it.title}),t.jsx("span",{className:"mission-status-badge mission-status-badge--sm",style:{backgroundColor:_l[it.status].bg,color:_l[it.status].text},children:it.status}),it.loopState&&it.loopState!=="idle"&&t.jsxs("span",{className:`mission-loop-state mission-loop-state--${it.loopState}`,title:`Loop state: ${it.loopState}`,children:[it.loopState==="implementing"&&"⏳",it.loopState==="validating"&&"🔄",it.loopState==="needs_fix"&&"🔧",it.loopState==="passed"&&"✅",it.loopState==="blocked"&&"🚫"]}),it.generatedFromFeatureId&&t.jsx("button",{className:"mission-feature__lineage",onClick:()=>na(it.generatedFromFeatureId),title:`Generated from feature: ${it.generatedFromFeatureId}`,children:"🔗 Fix"}),(it.loopState==="validating"||it.loopState==="needs_fix")&&(()=>{const $t=rt.get(it.id),Pn=Ci.get(it.id),ii=$t?.implementationAttemptCount??Pn?.implementationAttempt??it.implementationAttemptCount??0,ai=$t?.retryBudgetRemaining??Math.max(0,h4-ii);return t.jsxs("span",{className:"mission-feature__retry-budget",title:"Implementation attempts and remaining retry budget",children:["Attempt ",ii," · ",ai," ",ai===1?"retry":"retries"," left"]})})(),it.loopState==="implementing"&&t.jsx("button",{className:"mission-icon-btn mission-icon-btn--validate",onClick:()=>ta(it.id),title:"Validate feature",disabled:we.has(it.id),children:we.has(it.id)?t.jsx(St,{size:14,className:"spinner"}):t.jsx(cs,{size:14})}),it.taskId&&t.jsx("span",{className:"mission-feature__task-link",onClick:()=>o?.(it.taskId),title:"Click to view task",children:it.taskId}),t.jsxs("div",{className:"mission-feature__actions",children:[it.status==="defined"&&!it.taskId&&t.jsx("button",{className:"mission-icon-btn",onClick:()=>qn(it.id),title:"Triage — create task",disabled:Y||Ge===it.id,children:Ge===it.id?t.jsx(St,{size:14,className:"spinner"}):t.jsx(as,{size:14})}),it.taskId?t.jsx("button",{className:"mission-icon-btn",onClick:()=>Xt(it.id),title:"Unlink task",children:t.jsx(Um,{size:14})}):it.status!=="defined"?t.jsx("button",{className:"mission-icon-btn",onClick:()=>oe(it.id),title:"Link to task",children:t.jsx(Cr,{size:14})}):null,t.jsx("button",{className:"mission-icon-btn",onClick:()=>Hn(it),title:"Edit feature",children:t.jsx(Os,{size:14})}),t.jsx("button",{className:"mission-icon-btn mission-icon-btn--danger",onClick:()=>ot({type:"feature",id:it.id}),title:"Delete feature",children:t.jsx(In,{size:14})})]})]}),it.description&&t.jsx("p",{className:"mission-feature__description",children:it.description}),it.acceptanceCriteria&&t.jsxs("p",{className:"mission-feature__criteria",children:[t.jsx("strong",{children:"Acceptance:"})," ",it.acceptanceCriteria]}),Mt?.featureId===it.id&&t.jsxs("div",{className:"mission-triage-preview",children:[t.jsx("div",{className:"mission-triage-preview__header",children:"Enriched Description Preview"}),t.jsx("div",{className:"mission-triage-preview__content",children:Mt.enrichedDescription}),t.jsxs("div",{className:"mission-triage-preview__actions",children:[t.jsxs("button",{className:"btn btn-primary",onClick:Dn,disabled:Y,children:[Y?t.jsx(St,{size:14,className:"spinner"}):null,"Create Task"]}),t.jsx("button",{className:"btn",onClick:ts,disabled:Y,children:"Cancel"})]})]}),re===it.id&&t.jsxs("div",{className:"mission-form-card",children:[t.jsx("input",{type:"text",placeholder:"Feature title",value:be.title,onChange:$t=>Ue({...be,title:$t.target.value}),onKeyDown:tr,autoFocus:!0}),t.jsx("textarea",{placeholder:"Description (optional)",value:be.description,onChange:$t=>Ue({...be,description:$t.target.value}),rows:2}),t.jsx("textarea",{placeholder:"Acceptance criteria (optional)",value:be.acceptanceCriteria,onChange:$t=>Ue({...be,acceptanceCriteria:$t.target.value}),rows:2}),t.jsxs("select",{value:be.status,onChange:$t=>Ue({...be,status:$t.target.value}),children:[t.jsx("option",{value:"defined",children:"Defined"}),t.jsx("option",{value:"triaged",children:"Triaged"}),t.jsx("option",{value:"in-progress",children:"In Progress"}),t.jsx("option",{value:"done",children:"Done"})]}),t.jsxs("div",{className:"mission-form-card__actions",children:[t.jsxs("button",{className:"mission-btn mission-btn--primary",onClick:Be,disabled:Y,children:[Y?t.jsx(St,{size:14,className:"spinner"}):t.jsx(gs,{size:14}),"Update"]}),t.jsx("button",{className:"mission-btn mission-btn--ghost",onClick:ne,children:"Cancel"})]})]}),Ae===it.id&&t.jsxs("div",{className:"mission-feature__run-history",children:[t.jsx("div",{className:"mission-feature__run-history-header",children:t.jsx("span",{className:"mission-feature__run-history-title",children:"Validation Runs"})}),(Ct.get(it.id)??[]).map($t=>t.jsxs("div",{className:"mission-run",children:[t.jsxs("div",{className:"mission-run__header",onClick:()=>_n($t.id),children:[t.jsx("span",{className:`mission-status-badge mission-status-badge--sm mission-run__status mission-run__status--${$t.status}`,title:$t.status,children:$t.status}),t.jsx("span",{className:"mission-run__time",children:new Date($t.startedAt).toLocaleString()}),$t.completedAt&&t.jsxs("span",{className:"mission-run__duration",children:[Math.round((new Date($t.completedAt).getTime()-new Date($t.startedAt).getTime())/1e3),"s"]}),$t.triggerType&&t.jsx("span",{className:"mission-run__trigger",children:$t.triggerType}),t.jsx("button",{className:"mission-icon-btn",title:Gt===$t.id?"Hide details":"Show details",children:Gt===$t.id?t.jsx(vn,{size:12}):t.jsx(Wn,{size:12})})]}),Gt===$t.id&&Ht.get($t.id)&&t.jsxs("div",{className:"mission-run__details",children:[$t.summary&&t.jsx("p",{className:"mission-run__summary",children:$t.summary}),$t.blockedReason&&t.jsxs("p",{className:"mission-run__blocked-reason",children:[t.jsx("strong",{children:"Blocked:"})," ",$t.blockedReason]}),Ht.get($t.id)?.failures&&Ht.get($t.id).failures.length>0&&t.jsxs("div",{className:"mission-run__failures",children:[t.jsx("span",{className:"mission-run__failures-title",children:"Failed Assertions:"}),Ht.get($t.id).failures.map(Pn=>t.jsxs("div",{className:"mission-run__failure",children:[t.jsx("span",{className:"mission-run__failure-message",children:Pn.message}),Pn.expected&&t.jsxs("span",{className:"mission-run__failure-expected",children:["Expected: ",Pn.expected]}),Pn.actual&&t.jsxs("span",{className:"mission-run__failure-actual",children:["Actual: ",Pn.actual]})]},Pn.id))]}),(!Ht.get($t.id)?.failures||Ht.get($t.id).failures.length===0)&&t.jsx("p",{className:"mission-run__no-failures",children:"No assertion failures"})]})]},$t.id)),(!Ct.get(it.id)||Ct.get(it.id).length===0)&&t.jsx("div",{className:"mission-run-history__empty",children:"No validation runs yet."})]})]},it.id)),se&&Le===Ze.id&&t.jsxs("div",{className:"mission-form-card",children:[t.jsx("input",{type:"text",placeholder:"Feature title",value:be.title,onChange:it=>Ue({...be,title:it.target.value}),onKeyDown:tr,autoFocus:!0}),t.jsx("textarea",{placeholder:"Description (optional)",value:be.description,onChange:it=>Ue({...be,description:it.target.value}),rows:2}),t.jsx("textarea",{placeholder:"Acceptance criteria (optional)",value:be.acceptanceCriteria,onChange:it=>Ue({...be,acceptanceCriteria:it.target.value}),rows:2}),t.jsxs("div",{className:"mission-form-card__actions",children:[t.jsxs("button",{className:"mission-btn mission-btn--primary",onClick:Be,disabled:Y,children:[Y?t.jsx(St,{size:14,className:"spinner"}):t.jsx(gs,{size:14}),"Create"]}),t.jsx("button",{className:"mission-btn mission-btn--ghost",onClick:ne,children:"Cancel"})]})]}),!se&&(!Ze.features||Ze.features.length===0)&&t.jsxs("div",{className:"mission-manager__empty mission-features__empty",children:[t.jsx(iu,{size:16}),t.jsx("span",{children:"No fix features generated."})]})]})]})]},Ze.id)),B.slices.length===0&&!fe&&t.jsxs("div",{className:"mission-manager__empty",children:[t.jsx(du,{size:16}),t.jsx("span",{children:"No slices yet"})]}),t.jsxs("div",{className:"mission-assertions",children:[t.jsxs("div",{className:"mission-assertions__header",children:[t.jsx("span",{className:"mission-assertions__title",children:"Assertions"}),Ye&&t.jsx("span",{className:"mission-status-badge mission-status-badge--sm",style:{backgroundColor:at.bg,color:at.text},children:Df(Ye.state)}),Ye&&Ye.totalAssertions>0&&t.jsx("div",{className:"mission-assertions__coverage-bar",title:`${Ye.passedAssertions??0} of ${Ye.totalAssertions} assertions passing`,children:t.jsx("div",{className:"mission-assertions__coverage-bar-fill",style:{width:`${(Ye.passedAssertions??0)/Ye.totalAssertions*100}%`,backgroundColor:(Ye.passedAssertions??0)===Ye.totalAssertions?"var(--color-success)":"var(--color-warning)"}})}),t.jsx("button",{className:"mission-icon-btn",onClick:()=>{wt(!0),ke(null),bt({title:"",assertion:"",status:"pending"})},title:"Add assertion",children:t.jsx(Tn,{size:14})})]}),kt&&t.jsxs("div",{className:"mission-form-card",children:[t.jsx("input",{type:"text",placeholder:"Assertion title",value:nt.title,onChange:Ze=>bt({...nt,title:Ze.target.value}),autoFocus:!0}),t.jsx("textarea",{placeholder:"Assertion text (what should be true when complete)",value:nt.assertion,onChange:Ze=>bt({...nt,assertion:Ze.target.value}),rows:2}),t.jsxs("select",{value:nt.status,onChange:Ze=>bt({...nt,status:Ze.target.value}),children:[t.jsx("option",{value:"pending",children:"Pending"}),t.jsx("option",{value:"passed",children:"Passed"}),t.jsx("option",{value:"failed",children:"Failed"}),t.jsx("option",{value:"blocked",children:"Blocked"})]}),t.jsxs("div",{className:"mission-form-card__actions",children:[t.jsxs("button",{className:"mission-btn mission-btn--primary",onClick:()=>ja(B.id),disabled:Y,children:[Y?t.jsx(St,{size:14,className:"spinner"}):t.jsx(gs,{size:14}),"Create"]}),t.jsx("button",{className:"mission-btn mission-btn--ghost",onClick:zi,children:"Cancel"})]})]}),t.jsxs("div",{className:"mission-assertions__list",children:[(Array.isArray(xe.get(B.id))?xe.get(B.id):[]).map(Ze=>t.jsxs("div",{className:"mission-assertion","data-mission-assertion-id":Ze.id,children:[t.jsx("div",{className:"mission-assertion__header",children:Je===Ze.id?t.jsxs("div",{className:"mission-form-card",children:[t.jsx("input",{type:"text",placeholder:"Assertion title",value:nt.title,onChange:it=>bt({...nt,title:it.target.value}),autoFocus:!0}),t.jsx("textarea",{placeholder:"Assertion text",value:nt.assertion,onChange:it=>bt({...nt,assertion:it.target.value}),rows:2}),t.jsxs("select",{value:nt.status,onChange:it=>bt({...nt,status:it.target.value}),children:[t.jsx("option",{value:"pending",children:"Pending"}),t.jsx("option",{value:"passed",children:"Passed"}),t.jsx("option",{value:"failed",children:"Failed"}),t.jsx("option",{value:"blocked",children:"Blocked"})]}),t.jsxs("div",{className:"mission-form-card__actions",children:[t.jsxs("button",{className:"mission-btn mission-btn--primary",onClick:()=>Kr(Ze.id,B.id),disabled:Y,children:[Y?t.jsx(St,{size:14,className:"spinner"}):t.jsx(gs,{size:14}),"Save"]}),t.jsx("button",{className:"mission-btn mission-btn--ghost",onClick:zi,children:"Cancel"})]})]}):t.jsxs(t.Fragment,{children:[t.jsx("span",{className:"mission-status-badge mission-status-badge--sm",style:{backgroundColor:(Al[Ze.status]??Al.pending).bg,color:(Al[Ze.status]??Al.pending).text},children:Ze.status}),t.jsx("span",{className:"mission-assertion__title",children:Ze.title}),(()=>{const $t=ln.get(Ze.id)?.length??0;return $t>0?t.jsxs("span",{className:"mission-assertion__linked-count",title:`${$t} linked feature${$t!==1?"s":""}`,children:["(",$t," linked)"]}):null})(),t.jsx("button",{className:"mission-icon-btn",onClick:()=>Bi(Ze.id),title:"Toggle details",children:At===Ze.id?t.jsx(vn,{size:14}):t.jsx(Wn,{size:14})}),t.jsx("button",{className:"mission-icon-btn",onClick:()=>Na(Ze),title:"Edit assertion",children:t.jsx(Os,{size:14})}),t.jsx("button",{className:"mission-icon-btn mission-icon-btn--danger",onClick:()=>ot({type:"assertion",id:Ze.id}),title:"Delete assertion",children:t.jsx(In,{size:14})})]})}),At===Ze.id&&t.jsxs("div",{className:"mission-assertion__body",children:[t.jsx("p",{className:"mission-assertion__text",children:Ze.assertion}),t.jsxs("div",{className:"mission-assertion__linked-features",children:[t.jsxs("div",{className:"mission-assertion__linked-features-header",children:[t.jsx("span",{className:"mission-assertion__linked-features-label",children:"Linked Features"}),t.jsxs("button",{className:"mission-btn mission-btn--ghost mission-btn--sm",onClick:async()=>{At!==Ze.id&&await Bi(Ze.id),gn(Wt===Ze.id?null:Ze.id)},title:"Link a feature",children:[t.jsx(Cr,{size:12}),"Link Feature"]})]}),Wt===Ze.id&&t.jsx("div",{className:"mission-assertion__feature-picker",children:t.jsx("div",{className:"mission-assertion__feature-picker-dropdown",children:(()=>{const it=new Set((ln.get(Ze.id)??[]).map(Pn=>Pn.id)),$t=[];return g?.milestones.forEach(Pn=>Pn.slices.forEach(ii=>$t.push(...ii.features.filter(ai=>!it.has(ai.id))))),$t.length===0?t.jsx("span",{className:"mission-assertion__feature-picker-empty",children:"All features already linked"}):$t.map(Pn=>t.jsxs("button",{className:"mission-assertion__feature-picker-item",onClick:()=>ls(Pn.id,Ze.id),disabled:hn.has(Ze.id),children:[t.jsx("span",{className:"mission-assertion__feature-picker-title",children:Pn.title}),hn.has(Ze.id)&&t.jsx(St,{size:12,className:"spinner"})]},Pn.id))})()})}),(()=>{const it=ln.get(Ze.id)??[];return it.length===0?t.jsx("span",{className:"mission-assertion__linked-empty",children:"No features linked yet"}):it.map($t=>{const Pn=`${$t.id}-${Ze.id}`,ii=pn.has(Pn);return t.jsxs("div",{className:"mission-assertion__linked-feature",children:[t.jsx("span",{className:"mission-assertion__linked-feature-title",children:$t.title}),t.jsx("button",{className:"mission-icon-btn mission-icon-btn--danger",onClick:()=>Jr($t.id,Ze.id),disabled:ii,title:"Unlink feature",children:ii?t.jsx(St,{size:12,className:"spinner"}):t.jsx(Um,{size:12})})]},$t.id)})})()]})]})]},Ze.id)),(!xe.get(B.id)||xe.get(B.id)?.length===0)&&!kt&&t.jsx("div",{className:"mission-manager__empty mission-assertions__empty",children:t.jsx("span",{children:"No assertions defined. Add one to define completion criteria."})})]})]})]})]})]},B.id)}),g&&!Ne&&N===null&&t.jsxs("button",{className:"mission-add-btn",onClick:xs,children:[t.jsx(Tn,{size:16}),"Add Milestone"]}),Ne&&N===null&&t.jsxs("div",{className:"mission-form-card",children:[t.jsx("input",{type:"text",placeholder:"Milestone title",value:de.title,onChange:B=>me({...de,title:B.target.value}),onKeyDown:Ma,autoFocus:!0}),t.jsx("textarea",{placeholder:"Description (optional)",value:de.description,onChange:B=>me({...de,description:B.target.value}),rows:2}),t.jsxs("div",{className:"mission-form-card__actions",children:[t.jsxs("button",{className:"mission-btn mission-btn--primary",onClick:te,disabled:Y,children:[Y?t.jsx(St,{size:14,className:"spinner"}):t.jsx(gs,{size:14}),"Create"]}),t.jsx("button",{className:"mission-btn mission-btn--ghost",onClick:vs,children:"Cancel"})]})]}),g.milestones.length===0&&!Ne&&t.jsxs("div",{className:"mission-manager__empty",children:[t.jsx(Fa,{size:24}),t.jsx("span",{children:"No milestones yet. Add one to get started."})]})]}):t.jsxs("div",{className:"mission-detail__activity","data-testid":"mission-activity-tab",children:[t.jsxs("div",{className:"mission-detail__activity-controls",children:[t.jsxs("label",{className:"mission-detail__activity-filter",children:[t.jsx("span",{children:"Filter"}),t.jsxs("select",{value:Rt,onChange:B=>Ot(B.target.value),"data-testid":"mission-activity-filter",children:[t.jsx("option",{value:"all",children:"All events"}),t.jsx("option",{value:"errors",children:"Errors & warnings"}),t.jsx("option",{value:"state_changes",children:"State changes"}),t.jsx("option",{value:"tasks",children:"Task events"}),t.jsx("option",{value:"slices",children:"Slice & milestone events"}),t.jsx("option",{value:"autopilot",children:"Autopilot events"})]})]}),t.jsxs("span",{className:"mission-detail__activity-count",children:[zt.length," of ",z]})]}),!Se&&ra&&t.jsx("div",{className:"mission-detail__activity-load-more mission-detail__activity-load-more--top",children:t.jsx("button",{className:"mission-btn mission-btn--ghost",onClick:ni,"data-testid":"mission-activity-load-more",children:"Load more"})}),Se?t.jsxs("div",{className:"mission-manager__loading mission-detail__activity-loading",children:[t.jsx(St,{size:18,className:"spinner"}),t.jsx("span",{children:"Loading mission activity..."})]}):zt.length===0?t.jsxs("div",{className:"mission-manager__empty",children:[t.jsx(Vs,{size:18}),t.jsx("span",{children:"No events yet."})]}):t.jsxs("div",{ref:kn,className:"mission-events","data-testid":"mission-activity-events",children:[zt.map(B=>{const $e=!!(B.metadata&&Object.keys(B.metadata).length>0),Ye=Lt.has(B.id);return t.jsxs("div",{className:"mission-event",children:[t.jsxs("div",{className:"mission-event__header",children:[t.jsx("span",{className:`mission-event__type ${k4(B.eventType)}`,children:j4(B.eventType)}),t.jsx("span",{className:"mission-event__time",children:lc(B.timestamp)})]}),t.jsx("p",{className:"mission-event__description",children:B.description}),t.jsx("span",{className:"mission-event__timestamp",children:new Date(B.timestamp).toLocaleString()}),$e&&t.jsxs("div",{className:"mission-event__metadata",children:[t.jsxs("button",{className:"mission-btn mission-btn--ghost mission-btn--sm",onClick:()=>er(B.id),"data-testid":`mission-event-metadata-${B.id}`,children:[Ye?"Hide":"Show"," metadata"]}),Ye&&t.jsx("pre",{className:"mission-event__metadata-content",children:JSON.stringify(B.metadata,null,2)})]})]},B.id)}),t.jsx("div",{ref:es})]})]})]}):null,oa=B=>{et(B),We(!0)},sr=()=>{vt.current=Oe??null,et(void 0),We(!1)},Qr=async B=>{try{await P0(B,r),ut($e=>$e.filter(Ye=>Ye.id!==B))}catch($e){if($e instanceof Xl&&$e.status===409){a("Draft is open in another tab","error");return}if($e instanceof Xl&&$e.status===404){ut(Ye=>Ye.filter(jt=>jt.id!==B));return}a(Ie($e)||"Failed to discard draft","error");return}finally{ot(null)}},Xr=()=>De.map(B=>{const $e=B.status==="error",Ye=B.status==="generating",jt=g4(B.status);return t.jsxs("div",{className:"mission-list__item mission-list__item--interview",role:"button",tabIndex:0,"aria-label":`Resume interview ${B.title||"Mission interview"}`,onClick:()=>oa(B.id),onKeyDown:Ce=>{if(Ce.currentTarget===Ce.target){if(Ce.key==="Enter"){oa(B.id);return}Ce.key===" "&&(Ce.preventDefault(),oa(B.id))}},children:[t.jsxs("div",{className:"mission-list__item-content",children:[t.jsxs("div",{className:"mission-list__item-header",children:[t.jsx(cs,{size:16,className:"mission-list__item-icon"}),t.jsx("span",{className:"mission-list__item-title",children:B.title||"Mission interview"})]}),t.jsx("div",{className:"mission-list__item-tags",children:t.jsx("span",{className:`mission-status-badge mission-status-badge--sm mission-interview-status mission-interview-status--${B.status}`,children:f4(B.status)})}),t.jsx("p",{className:"mission-list__item-description",children:Ye?"Generating mission hierarchy from interview context.":$e?"Interview hit an error. Retry from this list item.":"Interview is waiting for your next response."})]}),t.jsxs("div",{className:"mission-list__item-actions mission-list__resume-actions",onClick:Ce=>Ce.stopPropagation(),children:[t.jsxs("button",{className:"mission-btn mission-btn--ghost mission-btn--sm",onClick:()=>oa(B.id),title:jt,"aria-label":jt,disabled:Ye,children:[Ye?t.jsx(St,{size:14,className:"spinner"}):$e?t.jsx(us,{size:14}):t.jsx(cs,{size:14}),t.jsx("span",{children:Ye?"Generating…":$e?"Retry":"Resume"})]}),t.jsxs("button",{className:"mission-btn mission-btn--danger mission-btn--sm",onClick:()=>ot({type:"interview_draft",id:B.id}),title:"Discard draft","aria-label":"Discard draft",children:[t.jsx(In,{size:14}),t.jsx("span",{children:"Discard"})]})]})]},B.id)}),ir=(B,$e)=>B.map(Ye=>{const jt=Ye,Ce=g?.id===jt.id,at=uo[jt.status]||{bg:"",text:""},It=jt.summary,Ze=ae.get(jt.id),it=v4(Ze),$t=!!(It&&(It.totalMilestones>0||It.totalFeatures>0)),Pn=Ze?.totalTasks??0,ii=Ze?.tasksCompleted??0,ai=Ze?.tasksFailed??0,An=Ze?.estimatedCompletionPercent??It?.progressPercent??0,Jn=$t||Pn>0||ai>0||!!Ze?.lastActivityAt,Zt=$e?.interviewStyle===!0;return t.jsxs("div",{className:`mission-list__item ${Ce?"mission-list__item--selected":""} ${Zt?"mission-list__item--interview":""}`,role:"button",tabIndex:0,"aria-label":`Open mission ${jt.title}`,"aria-pressed":Ce,onClick:()=>Ui(Ye),onKeyDown:ps=>{if(ps.currentTarget===ps.target){if(ps.key==="Enter"){Ui(Ye);return}ps.key===" "&&(ps.preventDefault(),Ui(Ye))}},children:[t.jsxs("div",{className:"mission-list__item-content",children:[t.jsxs("div",{className:"mission-list__item-header",children:[t.jsx(js,{size:16,className:"mission-list__item-icon"}),t.jsx("span",{className:"mission-list__item-title",children:jt.title})]}),t.jsxs("div",{className:"mission-list__item-tags",children:[Ye.autopilotEnabled&&t.jsx("span",{title:"Autopilot enabled",children:t.jsx(as,{size:12,className:"mission-list__item-autopilot-icon"})}),t.jsx("span",{className:`mission-health-badge mission-health-badge--${it}`,"data-testid":`mission-health-badge-${jt.id}`,"aria-label":`Mission health: ${it}`}),t.jsx("span",{className:"mission-status-badge mission-status-badge--sm",style:{backgroundColor:at.bg,color:at.text},children:jt.status}),Zt&&t.jsx("span",{className:"mission-status-badge mission-status-badge--sm mission-interview-status mission-interview-status--awaiting_input",children:"Interview in progress"})]}),Zt?t.jsx("p",{className:"mission-list__item-description",children:"Mission interview is still in progress. Open this mission to continue planning."}):jt.description?t.jsx("p",{className:"mission-list__item-description",children:jt.description}):null,Jn&&t.jsxs("div",{className:"mission-list__item-summary",children:[$t&&t.jsxs(t.Fragment,{children:[t.jsxs("span",{className:"mission-list__item-stat",children:[It.completedMilestones,"/",It.totalMilestones," milestones"]}),t.jsxs("span",{className:"mission-list__item-stat",children:[It.completedFeatures,"/",It.totalFeatures," features"]})]}),t.jsxs("span",{className:"mission-list__item-stat","data-testid":`mission-task-stats-${jt.id}`,children:[ii,"/",Pn," tasks"]}),ai>0&&t.jsxs("button",{className:"mission-list__item-failed",onClick:ps=>{ps.stopPropagation(),Ui(Ye)},"data-testid":`mission-failed-${jt.id}`,title:"View mission failures",children:[ai," failed"]}),t.jsx("div",{className:`mission-list__item-progress mission-list__item-progress--${it}`,children:t.jsx("div",{className:"mission-list__item-progress-bar",style:{width:`${An}%`}})})]}),Jn&&t.jsx("div",{className:"mission-list__item-activity",children:t.jsxs("span",{className:"mission-relative-time","data-testid":`mission-last-activity-${jt.id}`,children:["Activity ",lc(Ze?.lastActivityAt)]})})]}),t.jsxs("div",{className:"mission-list__item-actions",onClick:ps=>ps.stopPropagation(),children:[jt.status==="active"&&t.jsx("button",{className:"mission-icon-btn mission-icon-btn--danger",onClick:()=>sa(jt.id),title:"Stop mission",children:t.jsx(Pi,{size:14})}),jt.status==="blocked"&&t.jsx("button",{className:"mission-icon-btn mission-icon-btn--success",onClick:()=>Ca(jt.id),title:"Resume mission",children:t.jsx(is,{size:14})}),jt.status==="planning"&&t.jsx("button",{className:"mission-icon-btn mission-icon-btn--success",onClick:()=>ia(jt.id),title:"Start mission",children:t.jsx(is,{size:14})}),t.jsx("button",{className:"mission-icon-btn",onClick:()=>ss(Ye),title:"Edit mission",children:t.jsx(Os,{size:14})}),t.jsx("button",{className:"mission-icon-btn mission-icon-btn--danger",onClick:()=>ot({type:"mission",id:jt.id}),title:"Delete mission",children:t.jsx(In,{size:14})})]})]},jt.id)}),ar=({hideBottomButtons:B=!1}={})=>{const $e=f.filter(at=>at.interviewState==="in_progress"),Ye=f.filter(at=>at.interviewState!=="in_progress"),jt=S&&f.length>0&&!_,Ce=!B&&!jt;return t.jsxs("div",{className:"mission-list",children:[_&&t.jsxs("div",{className:"mission-form-card",children:[t.jsx("input",{type:"text",placeholder:"Mission title",value:P.title,onChange:at=>q({...P,title:at.target.value}),onKeyDown:Ei,autoFocus:!0}),t.jsx("textarea",{placeholder:"Description (optional)",value:P.description,onChange:at=>q({...P,description:at.target.value}),rows:2}),t.jsxs("div",{className:"mission-form-card__actions",children:[t.jsxs("button",{className:"mission-btn mission-btn--primary",onClick:Kn,disabled:Y,children:[Y?t.jsx(St,{size:14,className:"spinner"}):t.jsx(gs,{size:14}),"Create"]}),t.jsx("button",{className:"mission-btn mission-btn--ghost",onClick:Un,children:"Cancel"})]})]}),jt&&t.jsx("div",{className:"mission-list__top-action",children:t.jsxs("button",{className:"btn btn-sm btn-task-create mission-list__primary-cta",onClick:()=>We(!0),children:[t.jsx(cs,{size:14}),"Plan New Mission"]})}),De.length>0&&t.jsxs("div",{className:"mission-list__drafts-group",children:[t.jsxs("div",{className:"mission-list__drafts-header",children:[t.jsx(cs,{size:16,className:"mission-list__item-icon"}),t.jsx("span",{children:"Drafts"}),t.jsxs("span",{children:["(",De.length,")"]})]}),Xr()]}),ir($e,{interviewStyle:!0}),ir(Ye),H&&t.jsxs("div",{className:"mission-form-card",children:[t.jsx("input",{type:"text",placeholder:"Mission title",value:P.title,onChange:at=>q({...P,title:at.target.value}),onKeyDown:Ei,autoFocus:!0}),t.jsx("textarea",{placeholder:"Description (optional)",value:P.description,onChange:at=>q({...P,description:at.target.value}),rows:2}),t.jsxs("div",{className:"mission-form-card__row",children:[t.jsxs("select",{value:P.status,onChange:at=>q({...P,status:at.target.value}),children:[t.jsx("option",{value:"planning",children:"Planning"}),t.jsx("option",{value:"active",children:"Active"}),t.jsx("option",{value:"blocked",children:"Blocked"}),t.jsx("option",{value:"complete",children:"Complete"}),t.jsx("option",{value:"archived",children:"Archived"})]}),t.jsxs("label",{className:"mission-checkbox",children:[t.jsx("input",{type:"checkbox",checked:P.autopilotEnabled,onChange:at=>q({...P,autopilotEnabled:at.target.checked})}),t.jsx(as,{size:12})," Autopilot"]})]}),t.jsxs("div",{className:"mission-form-card__actions",children:[t.jsxs("button",{className:"mission-btn mission-btn--primary",onClick:Kn,disabled:Y,children:[Y?t.jsx(St,{size:14,className:"spinner"}):t.jsx(gs,{size:14}),"Update"]}),t.jsx("button",{className:"mission-btn mission-btn--ghost",onClick:Un,children:"Cancel"})]})]}),f.length===0&&De.length===0&&$e.length===0&&!_&&t.jsxs("div",{className:"mission-manager__empty mission-manager__empty--large mission-manager__empty--mission",children:[t.jsx(js,{size:32}),t.jsx("h3",{className:"mission-manager__empty-title",children:"No missions yet"}),t.jsx("p",{className:"mission-manager__empty-body",children:"Missions are large initiatives that bundle milestones, slices, and features into a single plan. Plan a mission to break down a goal end-to-end and let agents work through it autopilot-style."}),t.jsxs("button",{className:"btn btn-sm btn-primary mission-manager__empty-cta",onClick:()=>We(!0),children:[t.jsx(cs,{size:14}),"Plan New Mission"]})]}),!_&&t.jsx("div",{className:"mission-list__footer",children:Ce&&t.jsx("div",{className:"mission-list__footer-actions",children:t.jsxs("button",{className:"mission-add-btn",onClick:()=>We(!0),children:[t.jsx(cs,{size:16}),"Plan New Mission"]})})})]})},rr=()=>{const B=ue?.type==="interview_draft";return t.jsx("div",{className:"mission-confirm-panel mission-confirm-panel--danger",children:t.jsxs("div",{className:"mission-confirm-panel__content",children:[t.jsx("p",{children:B?"Discard this interview draft? This removes the saved draft and cannot be undone.":`Delete this ${ue?.type}? This cannot be undone.`}),t.jsxs("div",{className:"mission-confirm-panel__actions",children:[t.jsx("button",{className:"mission-btn mission-btn--danger",onClick:async()=>{ue&&(ue.type==="mission"?await Ms(ue.id):ue.type==="milestone"?await Ee(ue.id):ue.type==="slice"?await Et(ue.id):ue.type==="feature"?await Xe(ue.id):ue.type==="interview_draft"&&await Qr(ue.id))},children:B?"Discard":"Delete"}),t.jsx("button",{className:"mission-btn mission-btn--ghost",onClick:()=>ot(null),children:"Cancel"})]})]})})},vi=()=>t.jsx("div",{className:"mission-confirm-panel mission-confirm-panel--link",children:t.jsxs("div",{className:"mission-confirm-panel__content",children:[t.jsx("p",{children:"Link feature to task:"}),t.jsx("input",{type:"text",placeholder:"Task ID (e.g., FN-001)",value:Te,onChange:B=>Fe(B.target.value),autoFocus:!0}),l.length>0&&t.jsxs("div",{className:"mission-task-suggestions",children:[t.jsx("small",{children:"Or select:"}),t.jsx("div",{className:"mission-task-suggestions__list",children:l.slice(0,5).map(B=>t.jsxs("button",{className:"mission-task-suggestions__item",onClick:()=>Fe(B.id),children:[B.id,": ",B.title||"Untitled"]},B.id))})]}),t.jsxs("div",{className:"mission-confirm-panel__actions",children:[t.jsx("button",{className:"mission-btn mission-btn--primary",onClick:Dt,children:"Link"}),t.jsx("button",{className:"mission-btn mission-btn--ghost",onClick:()=>{oe(null),Fe("")},children:"Cancel"})]})]})}),_i=t.jsxs("div",{ref:Yr,className:`mission-manager mission-manager--desktop${n?" mission-manager--inline":""}`,role:n?void 0:"dialog","aria-modal":n?void 0:!0,"aria-label":n?void 0:"Mission Manager","data-testid":"mission-manager-dialog",children:[t.jsxs("div",{className:`mission-manager__header${n?" mission-manager__header--inline":""}`,children:[t.jsxs("div",{className:"mission-manager__header-title",children:[g&&t.jsx("button",{className:"mission-manager__back-btn",onClick:aa,title:"Back to missions","aria-label":"Back to missions list","data-testid":"mission-back-btn",children:t.jsx(gc,{size:18})}),t.jsx(js,{size:18,className:"mission-manager__header-icon"}),t.jsxs("h2",{className:"mission-manager__title","data-testid":"mission-header-title",children:[t.jsx("span",{className:"mission-manager__title-text mission-manager__title-text--desktop",children:"Missions"}),t.jsx("span",{className:"mission-manager__title-text mission-manager__title-text--mobile",children:g?g.title:"Missions"})]})]}),!n&&t.jsx("button",{className:"modal-close",onClick:s,title:"Close","aria-label":"Close Mission Manager","data-testid":"mission-close-btn",children:t.jsx(bn,{size:18})})]}),S?t.jsxs("div",{className:"mission-manager__body mission-manager__body--stacked",children:[v?t.jsxs("div",{className:"mission-manager__loading",children:[t.jsx(St,{size:24,className:"spinner"}),t.jsx("span",{children:"Loading missions..."})]}):y?t.jsxs("div",{className:"mission-manager__loading",children:[t.jsx(St,{size:24,className:"spinner"}),t.jsx("span",{children:"Loading mission details..."})]}):g?nr():ar(),ue&&rr(),Ke&&vi()]}):t.jsxs("div",{className:"mission-manager__split",children:[t.jsxs("aside",{className:"mission-manager__sidebar","data-testid":"mission-sidebar","aria-label":"Mission list",style:S?void 0:{width:`${x}px`},children:[t.jsx("div",{className:"mission-manager__sidebar-list",children:v?t.jsxs("div",{className:"mission-manager__loading",children:[t.jsx(St,{size:24,className:"spinner"}),t.jsx("span",{children:"Loading missions..."})]}):ar({hideBottomButtons:!0})}),t.jsx("div",{className:"mission-manager__sidebar-footer","data-testid":"mission-sidebar-footer",children:t.jsxs("button",{className:"btn btn-primary mission-manager__sidebar-cta",onClick:()=>We(!0),title:"Plan New Mission","aria-label":"Plan New Mission",children:[t.jsx(cs,{size:14}),"Plan New Mission"]})})]}),!S&&t.jsx("div",{className:"mission-manager__sidebar-resize-handle",role:"separator","aria-orientation":"vertical","aria-valuemin":Cl,"aria-valuemax":El,"aria-valuenow":x,"aria-label":"Resize mission sidebar",tabIndex:0,onPointerDown:O,onKeyDown:E}),t.jsxs("div",{className:"mission-manager__detail-pane",children:[y?t.jsxs("div",{className:"mission-manager__loading",children:[t.jsx(St,{size:24,className:"spinner"}),t.jsx("span",{children:"Loading mission details..."})]}):g?nr():t.jsxs("div",{className:"mission-manager__detail-pane-empty","data-testid":"mission-empty-detail",children:[t.jsx(js,{size:32}),t.jsx("span",{children:"Select a mission to view details"})]}),ue&&rr(),Ke&&vi()]})]})]}),Aa=t.jsx(t4,{isOpen:mt,onClose:sr,onMissionCreated:()=>{Cn(),a("Mission created from AI interview","success")},projectId:r,resumeSessionId:Oe}),or=tt?t.jsx(d4,{isOpen:!0,onClose:()=>ft(null),onApplied:()=>{ft(null),g&&Bt(g.id)},targetType:tt.type,targetId:tt.id,targetTitle:tt.title,missionContext:g?.title,projectId:r,resumeSessionId:tt.resumeSessionId}):null;return n?t.jsxs(t.Fragment,{children:[_i,Aa,or]}):t.jsxs(t.Fragment,{children:[t.jsx("div",{className:"mission-manager-overlay open",onClick:B=>B.target===B.currentTarget&&s(),"data-testid":"mission-manager-overlay",role:"dialog","aria-modal":"true",children:_i}),Aa,or]})}const C4={pre:({children:e,...n})=>t.jsx("pre",{...n,className:"mailbox-markdown-pre",children:e}),table:({children:e,...n})=>t.jsx("table",{...n,className:"mailbox-markdown-table",children:e}),a:({children:e,...n})=>t.jsx("a",{...n,target:"_blank",rel:"noopener noreferrer",children:e})},Ff=i.memo(function({content:n,className:s,testId:a}){const r=s?`mailbox-markdown ${s}`:"mailbox-markdown";return t.jsx("div",{className:r,"data-testid":a,children:t.jsx(hi,{remarkPlugins:[pi],components:C4,children:n})})}),Rl=2e3;function zf({recipient:e,replyContext:n,agents:s=[],projectId:a,onSend:r,onCancel:o,addToast:l,isLoadingAgents:c=!1}){const[d,u]=i.useState(e?.id??""),[h,m]=i.useState(e?.type??"agent"),[f,p]=i.useState(""),[g,w]=i.useState(!1),[v,b]=i.useState(!1),[y,j]=i.useState(null),S=i.useRef(null),C=i.useMemo(()=>s.find(H=>H.id===d),[s,d]),x=i.useMemo(()=>e?s.find(H=>H.id===e.id):void 0,[s,e]),k=h==="agent",R=k&&C?.runtimeConfig?.messageResponseMode==="immediate",O=k&&(g||R),E=d.trim()!==""&&f.trim().length>0&&f.length<=Rl,_=i.useCallback(async()=>{if(!(!E||v)){b(!0),j(null);try{const H=h==="agent"?"user-to-agent":"system",A=n?{replyTo:{messageId:n.messageId}}:void 0,P=O;await iC({toId:d.trim(),toType:h,content:f.trim(),type:H,...A?{metadata:A}:{},...P?{wakeImmediately:!0}:{}},a),r()}catch(H){const A=Ie(H)||"Failed to send message";j(A),l?.(A,"error")}finally{b(!1)}}},[E,v,d,h,f,O,n,a,r,l]),G=i.useCallback(H=>{u(H),m("agent")},[]);return i.useEffect(()=>{n&&S.current?.focus()},[n]),i.useEffect(()=>{if(!n||typeof window>"u"||window.visualViewport==null)return;const H=()=>{S.current?.scrollIntoView({block:"center",behavior:"auto"})};return window.visualViewport.addEventListener("resize",H),()=>{window.visualViewport?.removeEventListener("resize",H)}},[n]),t.jsxs("div",{className:"message-composer","data-testid":"message-composer",children:[t.jsxs("div",{className:"message-composer-header",children:[t.jsx("span",{children:n?"Reply":"New Message"}),t.jsx("button",{className:"btn-icon",onClick:o,"aria-label":"Cancel","data-testid":"message-composer-cancel",children:t.jsx(bn,{size:16})})]}),t.jsxs("div",{className:"message-composer-body",children:[!e&&t.jsxs("div",{className:"message-composer-field",children:[t.jsx("label",{className:"message-composer-label",htmlFor:"message-recipient",children:"To:"}),t.jsxs("select",{id:"message-recipient",className:"message-composer-select",value:d,onChange:H=>G(H.target.value),disabled:c||s.length===0,"data-testid":"message-composer-recipient",children:[t.jsx("option",{value:"",children:c?"Loading agents…":s.length===0?"No agents available":"Select agent…"}),s.map(H=>t.jsx("option",{value:H.id,children:H.name||H.id},H.id))]})]}),e&&t.jsxs("div",{className:"message-composer-field",children:[t.jsx("span",{className:"message-composer-label",children:"To:"}),t.jsxs("span",{className:"message-composer-recipient-fixed",children:[t.jsx(Xn,{size:14}),x?.name||e.id]})]}),n&&t.jsxs("div",{className:"message-composer-field","data-testid":"message-composer-reply-context",children:[t.jsx("span",{className:"message-composer-label",children:"Replying to:"}),t.jsx("span",{className:"message-composer-recipient-fixed",children:n.preview?.trim()?n.preview:`Message ${n.messageId}`})]}),t.jsxs("div",{className:"message-composer-field message-composer-field--content",children:[t.jsx("label",{className:"message-composer-label",htmlFor:"message-content",children:"Message:"}),t.jsx("textarea",{id:"message-content",ref:S,className:"message-composer-textarea",placeholder:"Type your message…",value:f,onChange:H=>p(H.target.value),maxLength:Rl,rows:4,"data-testid":"message-composer-content"}),t.jsx("div",{className:"message-composer-charcount","data-testid":"message-composer-charcount",children:t.jsxs("span",{className:f.length>Rl?"over-limit":"",children:[f.length,"/",Rl]})})]}),k&&t.jsx("div",{className:"message-composer-field message-composer-field--wake",children:t.jsxs("label",{className:"message-composer-wake-label",children:[t.jsx("input",{type:"checkbox",checked:O,disabled:R,onChange:H=>w(H.target.checked),"data-testid":"message-composer-wake"}),t.jsxs("span",{children:["Wake agent immediately",t.jsx("span",{className:"message-composer-wake-hint","data-testid":"message-composer-wake-hint",children:R?"(agent is already set to immediate response mode)":"(one-off override for this message only)"})]})]})}),y&&t.jsxs("div",{className:"message-composer-error","data-testid":"message-composer-error",children:[t.jsx(zs,{size:14}),t.jsx("span",{children:y})]})]}),t.jsxs("div",{className:"message-composer-footer",children:[t.jsx("button",{className:"btn btn-sm btn-secondary",onClick:o,"data-testid":"message-composer-cancel-btn",children:"Cancel"}),t.jsx("button",{className:"btn btn-sm btn-primary",onClick:_,disabled:!E||v,"data-testid":"message-composer-send",children:v?t.jsxs(t.Fragment,{children:[t.jsx(St,{size:14,className:"spin"}),t.jsx("span",{children:"Sending…"})]}):t.jsxs(t.Fragment,{children:[t.jsx(Da,{size:14}),t.jsx("span",{children:"Send"})]})})]})]})}const Es="__all_agents__",cc=280,Pu=.65,Bd=16,Bf=320;function $u(e){return Math.max(cc,e*Pu)}function Ud(e,n){const s=$u(n);return Math.min(Math.max(e,cc),s)}function Uf(e){try{const n=Ln("kb-dashboard-mailbox-sidebar-width",e);if(!n)return Bf;const s=Number(n);if(Number.isFinite(s)&&s>0)return s}catch{}return Bf}function Vi(e){const n=new Date(e),a=new Date().getTime()-n.getTime(),r=Math.floor(a/6e4),o=Math.floor(a/36e5),l=Math.floor(a/864e5);return r<1?"Just now":r<60?`${r}m ago`:o<24?`${o}h ago`:l<7?`${l}d ago`:n.toLocaleDateString(void 0,{month:"short",day:"numeric"})}function E4(e,n,s){if(n==="user")return e==="dashboard"?"You":`User: ${e}`;if(n==="agent"){const a=s?.get(e)?.trim();return a?a===e?`Agent: ${e}`:`Agent: ${a} (${e})`:`Agent: ${e}`}return"System"}function _4(e){switch(e){case"agent-to-agent":return"Agent ↔ Agent";case"agent-to-user":return"Agent → You";case"user-to-agent":return"You → Agent";case"system":return"System"}}function Hf(e,n=80){return e.length<=n?e:`${e.slice(0,n)}…`}function qf(){if(typeof window>"u")return null;const n=new URLSearchParams(window.location.search).get("mailbox-message");return n||(/^#message-(.+)$/.exec(window.location.hash)?.[1]??null)}function mo(e){return`mailbox-list-message-${e}`}function Hd(e){return`mailbox-detail-message-${e}`}function M4(e,n){const s=[...e];s.some(o=>o.id===n.id)||s.push(n);const a=new Set([n.id]);let r=!0;for(;r;){r=!1;for(const o of s){const l=o.metadata?.replyTo?.messageId;a.has(o.id)&&l&&!a.has(l)&&(a.add(l),r=!0),l&&a.has(l)&&!a.has(o.id)&&(a.add(o.id),r=!0)}}return s.filter(o=>a.has(o.id)).sort((o,l)=>new Date(o.createdAt).getTime()-new Date(l.createdAt).getTime())}function A4({projectId:e,addToast:n,onUnreadCountChange:s}){const[a,r]=i.useState("inbox"),[o,l]=i.useState(null),[c,d]=i.useState(null),[u,h]=i.useState(0),[m,f]=i.useState(!1),[p,g]=i.useState(null),[w,v]=i.useState([]),[b,y]=i.useState(!1),[j,S]=i.useState(null),[C,x]=i.useState(null),[k,R]=i.useState(Es),[O,E]=i.useState("inbox"),[_,G]=i.useState(null),[H,A]=i.useState(null),[P,q]=i.useState([]),[Y,ge]=i.useState("pending"),[L,M]=i.useState([]),[$,D]=i.useState(0),[N,W]=i.useState(null),[de,me]=i.useState(""),[Ne,ve]=i.useState(!1),Me=i.useMemo(()=>new Map(P.map(K=>[K.id,K.name??""])),[P]),ie=i.useCallback((K,ue)=>E4(K,ue,Me),[Me]),Z=ei()==="mobile",fe=!Z,[Q,F]=i.useState(()=>Uf(e)),X=i.useRef(null),{keyboardOverlap:re,viewportHeight:U,viewportOffsetTop:be,keyboardOpen:Ue}=ea({enabled:Z}),se=i.useMemo(()=>{if(Ue)return{"--keyboard-overlap":`${re}px`,"--vv-offset-top":`${be}px`,...U!=null?{"--vv-height":`${U}px`}:{}}},[Ue,re,U,be]);i.useEffect(()=>{F(Uf(e))},[e]),i.useEffect(()=>{if(!fe)return;const K=X.current?.clientWidth;K&&F(ue=>Ud(ue,K))},[fe]),i.useEffect(()=>{if(fe)try{rs("kb-dashboard-mailbox-sidebar-width",String(Q),e)}catch{}},[fe,e,Q]);const Ve=i.useCallback(K=>{if(!fe)return;K.preventDefault();const ue=X.current;if(!ue)return;const ot=ue.getBoundingClientRect(),xe=Je=>{const ke=Je.clientX-ot.left;F(Ud(ke,ot.width))},dt=()=>{window.removeEventListener("mousemove",xe),window.removeEventListener("mouseup",dt)};window.addEventListener("mousemove",xe),window.addEventListener("mouseup",dt)},[fe]),Le=i.useCallback(K=>{if(!fe)return;const ue=X.current?.clientWidth??0,ot=Q/Pu+Bd,xe=Math.max(ue,ot),dt=$u(xe);if(K.key==="ArrowLeft"||K.key==="ArrowRight"){K.preventDefault();const Je=K.key==="ArrowLeft"?-Bd:Bd;F(ke=>Ud(ke+Je,xe));return}if(K.key==="Home"){K.preventDefault(),F(cc);return}K.key==="End"&&(K.preventDefault(),F(dt))},[fe,Q]),ct=i.useCallback(async()=>{f(!0);try{const K=await nC({limit:50},e);l(K),h(K.unreadCount),s?.(K.unreadCount)}catch{}finally{f(!1)}},[e,s]),Ke=i.useCallback(async()=>{f(!0);try{const K=await sC({limit:50},e);d(K)}catch{}finally{f(!1)}},[e]),oe=i.useCallback(async K=>{f(!0);try{const ue=await cC(K,e);G(ue)}catch{}finally{f(!1)}},[e]),Te=i.useCallback(async()=>{f(!0);try{const K=await dC(e);A(K)}catch{}finally{f(!1)}},[e]),Fe=i.useCallback(async()=>{try{const K=await Hr(void 0,e);q(K)}catch{}},[e]),mt=i.useCallback(async()=>{try{const K=await Fb(e);h(K.unreadCount),s?.(K.unreadCount)}catch{}},[e,s]),We=i.useCallback(async K=>{f(!0);try{const ue=await cl({status:K==="pending"?"pending":void 0,limit:100},e);if(K==="pending")M(ue.requests);else{const[ot,xe,dt]=await Promise.all([cl({status:"approved",limit:100},e),cl({status:"denied",limit:100},e),cl({status:"completed",limit:100},e)]);M([...ot.requests,...xe.requests,...dt.requests].sort((Je,ke)=>ke.updatedAt.localeCompare(Je.updatedAt)))}D(ue.pendingCount)}catch{}finally{f(!1)}},[e]);i.useEffect(()=>{a==="inbox"?ct():a==="outbox"?Ke():a==="agents"?Fe():a==="approvals"&&We(Y)},[a,ct,Ke,Fe,We,Y]),i.useEffect(()=>{if(k===Es){Te();return}oe(k)},[k,oe,Te]),i.useEffect(()=>{mt()},[mt]),i.useEffect(()=>{Fe()},[Fe]),i.useEffect(()=>{if(typeof EventSource>"u")return;const K=e?`?projectId=${encodeURIComponent(e)}`:"",ue=()=>{mt(),a==="inbox"?ct():a==="outbox"?Ke():a==="approvals"&&We(Y),k===Es?Te():k&&oe(k)};return fi(`/api/events${K}`,{events:{"message:sent":ue,"message:received":ue,"message:read":ue,"message:deleted":ue,"approval:requested":ue,"approval:updated":ue,"approval:decided":ue}})},[e,a,k,mt,ct,Ke,oe,Te,We,Y]);const he=i.useCallback(async K=>{if(g(K),!K.read&&a==="inbox")try{const ue=await aC(K.id,e);ue&&l(xe=>xe&&{...xe,messages:xe.messages.map(dt=>dt.id===ue.id?ue:dt),unreadCount:Math.max(0,xe.unreadCount-1)});const ot=Math.max(0,u-1);h(ot),s?.(ot)}catch{}try{const ue=await lC(K.fromId,K.fromType,e);v(ue)}catch{v([K])}},[e,u,s,a]);i.useEffect(()=>{const K=qf();if(!K)return;const ue=[...o?.messages??[],...c?.messages??[],..._?.inbox??[],..._?.outbox??[],...H?.messages??[],...w].find(ot=>ot.id===K);ue&&he(ue)},[o,c,_,H,w,he]),i.useEffect(()=>{const K=qf();if(!K)return;const ue=document.getElementById(Hd(K));if(!ue)return;ue.scrollIntoView({behavior:"smooth",block:"center"}),ue.classList.add("mailbox-message-highlight");const ot=window.setTimeout(()=>{ue.classList.remove("mailbox-message-highlight")},2e3);return()=>{window.clearTimeout(ot)}},[p,w]);const pe=i.useCallback(()=>{g(null),v([])},[]),De=i.useCallback(async()=>{try{const K=await rC(e);h(0),s?.(0),l(ue=>ue&&{...ue,messages:ue.messages.map(ot=>({...ot,read:!0})),unreadCount:0}),n?.(`Marked ${K.markedAsRead} messages as read`,"success")}catch{n?.("Failed to mark messages as read","error")}},[e,n,s]),ut=i.useCallback(async K=>{try{await oC(K,e),g(null),v([]),a==="inbox"?ct():a==="outbox"?Ke():k===Es?Te():k&&oe(k),n?.("Message deleted","success")}catch{n?.("Failed to delete message","error")}},[e,a,k,ct,Ke,oe,Te,n]),ht=i.useCallback(K=>{S({id:K.fromId,type:K.fromType}),x({messageId:K.id,preview:Hf(K.content,120)}),y(!0)},[]),et=i.useCallback(()=>{y(!1),S(null),x(null),n?.("Message sent","success"),a==="outbox"?Ke():a==="agents"&&k===Es?Te():a==="agents"&&k&&oe(k),mt()},[a,Ke,k,oe,Te,n,mt]),vt=i.useCallback(()=>{S(a==="agents"&&k&&k!==Es?{id:k,type:"agent"}:null),x(null),y(!0)},[a,k]),Oe=i.useCallback(()=>{y(!1),S(null),x(null)},[]),tt=i.useCallback(async K=>{try{const ue=await fh(K.id,e);W(ue),me("")}catch{n?.("Failed to load approval request","error")}},[e,n]),ft=i.useCallback(async K=>{if(!(!N||Ne)){ve(K);try{await uC(N.id,{decision:K,comment:de||void 0},e),await We(Y);const ue=await fh(N.id,e);W(ue),me(""),n?.(`Request ${K==="approve"?"approved":"denied"}`,"success")}catch{n?.("Failed to submit decision","error")}finally{ve(!1)}}},[N,Ne,de,e,We,Y,n]),Mt=()=>{if(!p||b)return null;const K=M4(w,p);return t.jsxs("div",{className:"mailbox-message-detail","data-testid":"mailbox-message-detail",id:Hd(p.id),children:[t.jsxs("div",{className:"mailbox-message-detail-header",children:[Z&&t.jsx("button",{className:"btn btn-sm btn-secondary",onClick:pe,"data-testid":"mailbox-back-to-list",children:"← Back"}),t.jsxs("div",{className:"mailbox-message-detail-meta",children:[t.jsx("span",{className:"mailbox-message-type",children:_4(p.type)}),t.jsx("span",{className:"mailbox-message-time",children:Vi(p.createdAt)})]}),t.jsxs("div",{className:"mailbox-message-detail-actions",children:[p.fromType==="agent"&&t.jsxs("button",{className:"btn btn-sm btn-secondary",onClick:()=>ht(p),"data-testid":"mailbox-reply",children:[t.jsx(Ki,{size:14}),t.jsx("span",{children:"Reply"})]}),t.jsxs("button",{className:"btn btn-sm btn-secondary",onClick:()=>ut(p.id),"data-testid":"mailbox-delete",children:[t.jsx(In,{size:14}),t.jsx("span",{children:"Delete"})]})]})]}),t.jsxs("div",{className:"mailbox-message-participants",children:[t.jsxs("div",{className:"mailbox-participant",children:[t.jsx("span",{className:"mailbox-participant-label",children:"From:"}),t.jsxs("span",{className:"mailbox-participant-value",children:[p.fromType==="agent"?t.jsx(Xn,{size:14}):t.jsx(Ra,{size:14}),ie(p.fromId,p.fromType)]})]}),t.jsxs("div",{className:"mailbox-participant",children:[t.jsx("span",{className:"mailbox-participant-label",children:"To:"}),t.jsxs("span",{className:"mailbox-participant-value",children:[p.toType==="agent"?t.jsx(Xn,{size:14}):t.jsx(Ra,{size:14}),ie(p.toId,p.toType)]})]})]}),K.length>1&&t.jsxs("div",{className:"mailbox-conversation","data-testid":"mailbox-conversation",children:[t.jsx("div",{className:"mailbox-conversation-label",children:"Conversation"}),K.map(ue=>{const ot=ue.metadata?.replyTo?.messageId,xe=ot?K.find(dt=>dt.id===ot):void 0;return t.jsxs("div",{id:Hd(ue.id),className:`mailbox-conversation-msg ${ue.id===p.id?"current":""}`,children:[t.jsxs("div",{className:"mailbox-conversation-msg-header",children:[t.jsx("span",{children:ie(ue.fromId,ue.fromType)}),t.jsx("span",{className:"mailbox-message-time",children:Vi(ue.createdAt)})]}),ot&&t.jsxs("div",{className:"mailbox-reply-context-static","data-testid":`mailbox-reply-context-${ue.id}`,children:["↪ Replying to ",xe?Hf(xe.content,60):`message ${ot}`]}),t.jsx(Ff,{content:ue.content,className:"mailbox-conversation-msg-body"})]},ue.id)})]}),K.length<=1&&t.jsxs(t.Fragment,{children:[p.metadata?.replyTo?.messageId&&t.jsxs("div",{className:"mailbox-reply-context-static","data-testid":"mailbox-selected-reply-context",children:["↪ Replying to message ",p.metadata.replyTo.messageId]}),t.jsx(Ff,{content:p.content,className:"mailbox-message-body",testId:"mailbox-message-body"})]})]})},yt=()=>t.jsxs(t.Fragment,{children:[a==="inbox"&&t.jsxs("div",{className:"mailbox-list","data-testid":"mailbox-inbox-list",children:[m&&!o&&t.jsx(Il,{}),o&&o.messages.length===0&&t.jsxs("div",{className:"mailbox-empty","data-testid":"mailbox-inbox-empty",children:[t.jsx(ma,{size:32}),t.jsx("p",{children:"No messages in your inbox"})]}),o?.messages.map(K=>t.jsxs("div",{id:mo(K.id),className:`mailbox-item ${K.read?"":"unread"}`,onClick:()=>he(K),"data-testid":`mailbox-item-${K.id}`,children:[t.jsx("div",{className:"mailbox-item-avatar",children:K.fromType==="agent"?t.jsx(Xn,{size:16}):t.jsx(Ra,{size:16})}),t.jsxs("div",{className:"mailbox-item-content",children:[t.jsxs("div",{className:"mailbox-item-header",children:[t.jsx("span",{className:"mailbox-item-from",children:ie(K.fromId,K.fromType)}),t.jsx("span",{className:"mailbox-item-time",children:Vi(K.createdAt)})]}),t.jsxs("div",{className:"mailbox-item-preview",children:[K.content.slice(0,80),K.content.length>80?"…":""]})]}),!K.read&&t.jsx("div",{className:"mailbox-item-unread-dot","data-testid":`mailbox-unread-dot-${K.id}`})]},K.id))]}),a==="outbox"&&t.jsxs("div",{className:"mailbox-list","data-testid":"mailbox-outbox-list",children:[m&&!c&&t.jsx(Il,{}),c&&c.messages.length===0&&t.jsxs("div",{className:"mailbox-empty","data-testid":"mailbox-outbox-empty",children:[t.jsx(Da,{size:32}),t.jsx("p",{children:"No sent messages"})]}),c?.messages.map(K=>t.jsxs("div",{id:mo(K.id),className:"mailbox-item",onClick:()=>he(K),"data-testid":`mailbox-item-${K.id}`,children:[t.jsx("div",{className:"mailbox-item-avatar",children:K.toType==="agent"?t.jsx(Xn,{size:16}):t.jsx(Ra,{size:16})}),t.jsxs("div",{className:"mailbox-item-content",children:[t.jsxs("div",{className:"mailbox-item-header",children:[t.jsxs("span",{className:"mailbox-item-to",children:["To: ",ie(K.toId,K.toType)]}),t.jsx("span",{className:"mailbox-item-time",children:Vi(K.createdAt)})]}),t.jsxs("div",{className:"mailbox-item-preview",children:[K.content.slice(0,80),K.content.length>80?"…":""]})]})]},K.id))]}),a==="approvals"&&t.jsxs("div",{className:"mailbox-approvals","data-testid":"mailbox-approvals",children:[t.jsxs("div",{className:"mailbox-approval-filters","data-testid":"mailbox-approval-filters",children:[t.jsx("button",{className:`btn btn-sm btn-secondary mailbox-agent-subtab ${Y==="pending"?"active":""}`,onClick:()=>{ge("pending"),W(null)},"data-testid":"mailbox-approval-filter-pending",children:"Pending"}),t.jsx("button",{className:`btn btn-sm btn-secondary mailbox-agent-subtab ${Y==="history"?"active":""}`,onClick:()=>{ge("history"),W(null)},"data-testid":"mailbox-approval-filter-history",children:"History"})]}),t.jsxs("div",{className:"mailbox-list","data-testid":"mailbox-approval-list",children:[L.length===0&&!m&&t.jsxs("div",{className:"mailbox-empty","data-testid":"mailbox-approval-empty",children:[t.jsx(ma,{size:32}),t.jsx("p",{children:Y==="pending"?"No pending approvals":"No historical approvals"})]}),L.map(K=>t.jsxs("div",{className:"mailbox-item mailbox-approval-item",onClick:()=>void tt(K),"data-testid":`mailbox-approval-item-${K.id}`,children:[t.jsx("div",{className:`status-dot mailbox-approval-status-dot mailbox-approval-status-dot--${K.status}`}),t.jsxs("div",{className:"mailbox-item-content",children:[t.jsxs("div",{className:"mailbox-item-header",children:[t.jsxs("span",{className:"mailbox-item-from",children:[K.agentId," · ",K.actionCategory]}),t.jsx("span",{className:"mailbox-item-time",children:Vi(K.createdAt)})]}),t.jsx("div",{className:"mailbox-item-preview",children:K.actionSummary})]}),t.jsx("span",{className:`mailbox-approval-status mailbox-approval-status--${K.status}`,children:K.status})]},K.id))]})]}),a==="agents"&&t.jsx("div",{className:"mailbox-agents","data-testid":"mailbox-agents",children:P.length===0?t.jsxs("div",{className:"mailbox-empty",children:[t.jsx(Xn,{size:32}),t.jsx("p",{children:"No agents found"})]}):t.jsxs(t.Fragment,{children:[t.jsxs("div",{className:"mailbox-agents-header",children:[t.jsx("div",{className:"mailbox-agents-dropdown",children:t.jsxs("select",{className:"message-composer-select mailbox-agent-select",value:k,onChange:K=>{R(K.target.value),E("inbox")},"data-testid":"mailbox-agent-select",children:[t.jsx("option",{value:Es,children:"All agents"}),P.map(K=>t.jsx("option",{value:K.id,children:K.name||K.id},K.id))]})}),t.jsxs("button",{className:"btn btn-sm btn-secondary mailbox-compose-btn",onClick:vt,"data-testid":"mailbox-compose-btn",children:[t.jsx(Ki,{size:14}),t.jsx("span",{children:"Compose"})]})]}),k&&k!==Es&&t.jsxs("div",{className:"mailbox-agent-subtabs","data-testid":"mailbox-agent-subtabs",children:[t.jsxs("button",{className:`btn btn-sm btn-secondary mailbox-agent-subtab ${O==="inbox"?"active":""}`,onClick:()=>E("inbox"),"data-testid":"mailbox-agent-subtab-inbox",children:[t.jsx(ma,{size:12}),t.jsx("span",{children:"Inbox"}),_&&_.unreadCount>0&&t.jsx("span",{className:"mailbox-tab-badge",children:_.unreadCount})]}),t.jsxs("button",{className:`btn btn-sm btn-secondary mailbox-agent-subtab ${O==="outbox"?"active":""}`,onClick:()=>E("outbox"),"data-testid":"mailbox-agent-subtab-outbox",children:[t.jsx(Da,{size:12}),t.jsx("span",{children:"Outbox"})]})]}),t.jsxs("div",{className:"mailbox-agents-content",children:[k===Es&&m&&!H&&t.jsx(Il,{}),k===Es&&H&&H.messages.length===0&&t.jsxs("div",{className:"mailbox-empty",children:[t.jsx(ma,{size:32}),t.jsx("p",{children:"No agent-to-agent messages"})]}),k===Es&&H&&H.messages.map(K=>t.jsxs("div",{id:mo(K.id),className:`mailbox-item ${K.read?"":"unread"}`,onClick:()=>he(K),"data-testid":`mailbox-item-${K.id}`,children:[t.jsx("div",{className:"mailbox-item-avatar",children:K.fromType==="agent"?t.jsx(Xn,{size:16}):t.jsx(Ra,{size:16})}),t.jsxs("div",{className:"mailbox-item-content",children:[t.jsxs("div",{className:"mailbox-item-header",children:[t.jsx("span",{className:"mailbox-item-from",children:ie(K.fromId,K.fromType)}),t.jsx("span",{className:"mailbox-item-time",children:Vi(K.createdAt)})]}),t.jsxs("div",{className:"mailbox-item-participants","data-testid":`mailbox-item-participants-${K.id}`,children:[t.jsxs("span",{children:["From: ",ie(K.fromId,K.fromType)]}),t.jsxs("span",{children:["To: ",ie(K.toId,K.toType)]})]}),t.jsxs("div",{className:"mailbox-item-preview",children:[K.content.slice(0,80),K.content.length>80?"…":""]})]})]},K.id)),k&&k!==Es&&m&&!_&&t.jsx(Il,{}),k&&k!==Es&&_&&O==="inbox"&&_.inbox.length===0&&t.jsxs("div",{className:"mailbox-empty",children:[t.jsx(ma,{size:32}),t.jsx("p",{children:"No received messages for this agent"})]}),k&&k!==Es&&_&&O==="outbox"&&_.outbox.length===0&&t.jsxs("div",{className:"mailbox-empty",children:[t.jsx(Da,{size:32}),t.jsx("p",{children:"No sent messages for this agent"})]}),k&&k!==Es&&_&&O==="inbox"&&_.inbox.map(K=>t.jsxs("div",{id:mo(K.id),className:`mailbox-item ${K.read?"":"unread"}`,onClick:()=>he(K),"data-testid":`mailbox-item-${K.id}`,children:[t.jsx("div",{className:"mailbox-item-avatar",children:K.fromType==="agent"?t.jsx(Xn,{size:16}):t.jsx(Ra,{size:16})}),t.jsxs("div",{className:"mailbox-item-content",children:[t.jsxs("div",{className:"mailbox-item-header",children:[t.jsx("span",{className:"mailbox-item-from",children:ie(K.fromId,K.fromType)}),t.jsx("span",{className:"mailbox-item-time",children:Vi(K.createdAt)})]}),t.jsxs("div",{className:"mailbox-item-preview",children:[K.content.slice(0,80),K.content.length>80?"…":""]})]})]},K.id)),k&&k!==Es&&_&&O==="outbox"&&_.outbox.map(K=>t.jsxs("div",{id:mo(K.id),className:"mailbox-item",onClick:()=>he(K),"data-testid":`mailbox-item-${K.id}`,children:[t.jsx("div",{className:"mailbox-item-avatar",children:K.toType==="agent"?t.jsx(Xn,{size:16}):t.jsx(Ra,{size:16})}),t.jsxs("div",{className:"mailbox-item-content",children:[t.jsxs("div",{className:"mailbox-item-header",children:[t.jsxs("span",{className:"mailbox-item-to",children:["To: ",ie(K.toId,K.toType)]}),t.jsx("span",{className:"mailbox-item-time",children:Vi(K.createdAt)})]}),t.jsxs("div",{className:"mailbox-item-preview",children:[K.content.slice(0,80),K.content.length>80?"…":""]})]})]},K.id))]})]})})]}),Ge=()=>b?t.jsx(zf,{recipient:j,replyContext:C,agents:P,projectId:e,onSend:et,onCancel:Oe,addToast:n}):p?Mt():a==="approvals"&&N?t.jsxs("div",{className:"mailbox-message-detail mailbox-approval-detail","data-testid":"mailbox-approval-detail",children:[Z&&t.jsx("button",{className:"btn btn-sm btn-secondary",onClick:()=>W(null),"data-testid":"mailbox-approval-back-to-list",children:"← Back"}),t.jsx("div",{className:"mailbox-message-detail-header",children:t.jsxs("div",{className:"mailbox-message-detail-meta",children:[t.jsx("span",{className:"mailbox-message-type",children:N.actionCategory}),t.jsx("span",{className:"mailbox-message-time",children:N.status})]})}),t.jsxs("div",{className:"mailbox-message-body",children:[t.jsx("strong",{children:N.actionSummary}),t.jsxs("p",{children:["Requester: ",N.requester.actorName," (",N.agentId,")"]}),N.taskId&&t.jsxs("p",{children:["Task: ",N.taskId]}),t.jsxs("p",{children:["Requested: ",Vi(N.createdAt)]})]}),t.jsx("div",{className:"mailbox-conversation","data-testid":"mailbox-approval-history",children:N.history.map(K=>t.jsxs("div",{className:"mailbox-conversation-msg",children:[t.jsxs("div",{className:"mailbox-conversation-msg-header",children:[t.jsx("span",{children:K.eventType}),t.jsx("span",{children:K.actor.actorName})]}),K.note&&t.jsx("div",{className:"mailbox-item-preview",children:K.note})]},K.id))}),N.status==="pending"&&t.jsxs("div",{className:"mailbox-approval-decision","data-testid":"mailbox-approval-decision",children:[t.jsx("textarea",{className:"message-composer-textarea mailbox-approval-comment",value:de,onChange:K=>me(K.target.value),placeholder:"Optional comment","data-testid":"mailbox-approval-comment"}),t.jsxs("div",{className:"mailbox-header-actions",children:[t.jsx("button",{className:"btn btn-sm btn-secondary",onClick:()=>void ft("deny"),disabled:Ne!==!1,"data-testid":"mailbox-approval-deny",children:"Deny"}),t.jsx("button",{className:"btn btn-sm btn-primary",onClick:()=>void ft("approve"),disabled:Ne!==!1,"data-testid":"mailbox-approval-approve",children:"Approve"})]})]})]}):t.jsxs("div",{className:"mailbox-split-empty","data-testid":"mailbox-split-empty",children:[t.jsx(za,{size:24}),t.jsx("p",{children:"Select a message to read"})]});return t.jsxs("div",{className:"mailbox-view",style:se,"data-testid":"mailbox-view",children:[t.jsxs("div",{className:"mailbox-header",children:[t.jsxs("div",{className:"mailbox-title",children:[t.jsx(za,{size:18}),t.jsx("span",{children:"Mailbox"}),u>0&&t.jsx("span",{className:"mailbox-unread-badge","data-testid":"mailbox-unread-badge",children:u})]}),t.jsxs("div",{className:"mailbox-header-actions",children:[t.jsxs("button",{className:"btn btn-sm btn-primary",onClick:vt,title:"Compose message","data-testid":"mailbox-header-compose",children:[t.jsx(Ki,{size:14}),t.jsx("span",{children:"Compose"})]}),a==="inbox"&&u>0&&t.jsxs("button",{className:"btn btn-sm btn-secondary",onClick:De,title:"Mark all as read","data-testid":"mailbox-mark-all-read",children:[t.jsx(Lm,{size:14}),t.jsx("span",{children:"Mark all read"})]}),t.jsx("button",{className:"btn-icon",onClick:()=>{a==="inbox"?ct():a==="outbox"?Ke():a==="approvals"?We(Y):k===Es?Te():k&&oe(k)},disabled:m,title:"Refresh","data-testid":"mailbox-refresh",children:m?t.jsx(St,{size:14,className:"spin"}):t.jsx(us,{size:14})})]})]}),t.jsxs("div",{className:"mailbox-tabs","data-testid":"mailbox-tabs",children:[t.jsxs("button",{className:`btn btn-sm btn-secondary mailbox-tab ${a==="inbox"?"active":""}`,onClick:()=>{r("inbox"),g(null)},"data-testid":"mailbox-tab-inbox",children:[t.jsx(ma,{size:14}),t.jsx("span",{children:"Inbox"}),u>0&&t.jsx("span",{className:"mailbox-tab-badge",children:u})]}),t.jsxs("button",{className:`btn btn-sm btn-secondary mailbox-tab ${a==="outbox"?"active":""}`,onClick:()=>{r("outbox"),g(null)},"data-testid":"mailbox-tab-outbox",children:[t.jsx(Da,{size:14}),t.jsx("span",{children:"Outbox"})]}),t.jsxs("button",{className:`btn btn-sm btn-secondary mailbox-tab ${a==="agents"?"active":""}`,onClick:()=>{r("agents"),g(null),W(null)},"data-testid":"mailbox-tab-agents",children:[t.jsx(Xn,{size:14}),t.jsx("span",{children:"Agents"})]}),t.jsxs("button",{className:`btn btn-sm btn-secondary mailbox-tab ${a==="approvals"?"active":""}`,onClick:()=>{r("approvals"),g(null),W(null)},"data-testid":"mailbox-tab-approvals",children:[t.jsx(Lm,{size:14}),t.jsx("span",{children:"Approvals"}),$>0&&t.jsx("span",{className:"mailbox-tab-badge","data-testid":"mailbox-approvals-pending-badge",children:$})]})]}),t.jsx("div",{className:"mailbox-content","data-testid":"mailbox-content",children:fe?t.jsxs("div",{className:"mailbox-split-layout","data-testid":"mailbox-split-layout",ref:X,children:[t.jsx("div",{className:"mailbox-split-list-pane","data-testid":"mailbox-split-list-pane",style:{width:`${Q}px`},children:yt()}),t.jsx("div",{className:"mailbox-split-resize-handle","data-testid":"mailbox-split-resize-handle",role:"separator","aria-orientation":"vertical","aria-label":"Resize message list pane",tabIndex:0,"aria-valuemin":cc,"aria-valuemax":Math.round($u(X.current?.clientWidth??Q/Pu)),"aria-valuenow":Math.round(Q),onMouseDown:Ve,onKeyDown:Le}),t.jsx("div",{className:"mailbox-split-detail-pane","data-testid":"mailbox-split-detail-pane",children:Ge()})]}):t.jsxs(t.Fragment,{children:[Mt(),a==="approvals"&&N&&Ge(),b&&t.jsx(zf,{recipient:j,replyContext:C,agents:P,projectId:e,onSend:et,onCancel:Oe,addToast:n}),!p&&!N&&!b&&yt()]})})]})}function Il(){return t.jsx("div",{className:"mailbox-skeleton","data-testid":"mailbox-skeleton",children:Array.from({length:5}).map((e,n)=>t.jsxs("div",{className:"mailbox-skeleton-item",children:[t.jsx("div",{className:"mailbox-skeleton-avatar"}),t.jsxs("div",{className:"mailbox-skeleton-content",children:[t.jsx("div",{className:"mailbox-skeleton-line mailbox-skeleton-line--short"}),t.jsx("div",{className:"mailbox-skeleton-line mailbox-skeleton-line--long"})]})]},n))})}const R4=640;function I4({isOpen:e,onClose:n,onImport:s,tasks:a,projectId:r}){Si(e);const[o,l]=i.useState(""),[c,d]=i.useState(""),[u,h]=i.useState(""),[m,f]=i.useState(!1),[p,g]=i.useState("issues"),[w,v]=i.useState([]),[b,y]=i.useState(null),[j,S]=i.useState([]),[C,x]=i.useState(null),[k,R]=i.useState(null),[O,E]=i.useState(!1),[_,G]=i.useState([]),[H,A]=i.useState(!1),[P,q]=i.useState(""),Y=i.useRef(!1),ge=i.useRef(null);Oi(ge,e,"fusion:github-modal-size");const L=Xi(n),[M,$]=i.useState(!1),[D,N]=i.useState("list"),W=i.useRef(null),de=new Set;for(const he of a){const pe=he.description.match(/Source: (https:\/\/github\.com\/[^/]+\/[^/]+\/issues\/\d+)/);pe&&de.add(pe[1]);const De=he.description.match(/PR: (https:\/\/github\.com\/[^/]+\/[^/]+\/pull\/\d+)/);De&&de.add(De[1])}i.useEffect(()=>{if(e)return l(""),d(""),h(""),v([]),y(null),S([]),x(null),g("issues"),R(null),E(!1),G([]),A(!0),q(""),W.current=null,Y.current=!0,rS().then(he=>{if(Y.current)if(G(he),A(!1),he.length===1){const pe=he[0];l(pe.owner),d(pe.repo),q(pe.name)}else he.length>1&&(l(""),d(""),q(""))}).catch(()=>{Y.current&&A(!1)}),()=>{Y.current=!1}},[e]);const me=i.useCallback(he=>{if(q(he),he==="")l(""),d("");else{const pe=_.find(De=>De.name===he);pe&&(l(pe.owner),d(pe.repo))}},[_]),Ne=i.useCallback(async()=>{if(!o.trim()||!c.trim()){R("Repository must be selected");return}f(!0),R(null),v([]),y(null);try{const he=u.split(",").map(De=>De.trim()).filter(Boolean),pe=await nS(o.trim(),c.trim(),30,he.length>0?he:void 0);v(pe),pe.length===0&&R("No open issues found")}catch(he){R(Ie(he)||"Failed to fetch issues")}finally{f(!1)}},[o,c,u]),ve=i.useCallback(async()=>{if(!o.trim()||!c.trim()){R("Repository must be selected");return}f(!0),R(null),S([]),x(null);try{const he=await iS(o.trim(),c.trim(),30);S(he),he.length===0&&R("No open pull requests found")}catch(he){R(Ie(he)||"Failed to fetch pull requests")}finally{f(!1)}},[o,c]);i.useEffect(()=>{if(!e||!o.trim()||!c.trim()||m||O)return;const he={owner:o.trim(),repo:c.trim(),labels:u.trim(),tab:p};W.current?.owner===he.owner&&W.current?.repo===he.repo&&W.current?.labels===he.labels&&W.current?.tab===he.tab||(W.current=he,p==="issues"?Ne():ve())},[o,c,u,p,e,m,O,Ne,ve]),i.useEffect(()=>{if(!e)return;const he=pe=>{pe.key==="Escape"&&n()};return document.addEventListener("keydown",he),()=>document.removeEventListener("keydown",he)},[e,n]),i.useEffect(()=>{if(!e)return;const he=()=>{$(window.innerWidth<=R4)};return he(),window.addEventListener("resize",he),()=>window.removeEventListener("resize",he)},[e]);const Me=i.useCallback(he=>{y(he),M&&N("preview")},[M]),ie=i.useCallback(he=>{x(he),M&&N("preview")},[M]),ye=i.useCallback(()=>{N("list")},[]),Z=i.useCallback(async()=>{if(p==="issues"){if(b===null)return;E(!0),R(null);try{const he=await sS(o.trim(),c.trim(),b,r);s(he),y(null),M&&D==="preview"&&N("list")}catch(he){const pe=Ie(he);pe?.includes("already imported")?R(pe):R(pe||"Failed to import issue")}finally{E(!1)}}else{if(C===null)return;E(!0),R(null);try{const he=await aS(o.trim(),c.trim(),C,r);s(he),x(null),M&&D==="preview"&&N("list")}catch(he){const pe=Ie(he);pe?.includes("already imported")?R(pe):R(pe||"Failed to import pull request")}finally{E(!1)}}},[p,b,C,o,c,s,M,D]),fe=w.find(he=>he.number===b),Q=j.find(he=>he.number===C);if(!e)return null;const F=_.length>0,X=_.length===1,re=w.filter(he=>de.has(he.html_url)).length,U=j.filter(he=>de.has(he.html_url)).length,be=k==="No open issues found",Ue=k==="No open pull requests found",se=p==="issues"?be:Ue,Ve=!!k&&!be&&w.length===0&&!m,Le=!!k&&!Ue&&j.length===0&&!m,ct=p==="issues"?Ve:Le,Ke=m||w.length>0||be||Ve,oe=m||j.length>0||Ue||Le,Te=p==="issues"?Ke:oe,Fe=!!k&&w.length>0&&!be,mt=!!k&&j.length>0&&!Ue,We=p==="issues"?Fe:mt;return t.jsx("div",{className:"modal-overlay open",...L,role:"dialog","aria-modal":"true",children:t.jsxs("div",{className:"modal modal-lg github-import-modal",ref:ge,children:[t.jsxs("div",{className:"modal-header github-import-modal__header",children:[t.jsxs("div",{children:[t.jsx("h3",{children:"Import from GitHub"}),t.jsx("p",{className:"github-import-modal__subtitle",children:"Choose a detected remote, load open issues or pull requests, and import one into the board."})]}),t.jsx("button",{className:"modal-close",onClick:n,"aria-label":"Close import modal",children:"×"})]}),t.jsxs("div",{className:"modal-body github-import-modal__body",children:[t.jsxs("div",{className:"github-import-tabs",role:"tablist","aria-label":"Import type",children:[t.jsxs("button",{role:"tab","aria-selected":p==="issues","aria-controls":"github-import-list-pane",className:`github-import-tab ${p==="issues"?"active":""}`,onClick:()=>{g("issues"),x(null)},disabled:m||O,children:[t.jsx(bc,{size:16}),t.jsx("span",{children:"Issues"})]}),t.jsxs("button",{role:"tab","aria-selected":p==="pulls","aria-controls":"github-import-list-pane",className:`github-import-tab ${p==="pulls"?"active":""}`,onClick:()=>{g("pulls"),y(null)},disabled:m||O,children:[t.jsx(Qs,{size:16}),t.jsx("span",{children:"Pull Requests"})]})]}),t.jsxs("div",{className:"github-import-toolbar","data-testid":"github-import-toolbar",role:"toolbar","aria-label":"GitHub import controls",children:[t.jsx("div",{className:"github-import-toolbar__zone github-import-toolbar__zone--remote",children:H?t.jsxs("div",{className:"github-import-toolbar__loading",role:"status","aria-live":"polite",children:[t.jsx(St,{size:16,className:"spin"}),t.jsx("span",{children:"Detecting…"})]}):F?X?t.jsxs("div",{className:"github-import-remote-pill","data-testid":"github-import-single-remote",children:[t.jsx("span",{className:"github-import-remote-pill__name",children:_[0].name}),t.jsxs("span",{className:"github-import-remote-pill__repo",children:[_[0].owner,"/",_[0].repo]})]}):t.jsxs("div",{className:"github-import-remote-select",children:[t.jsx("label",{htmlFor:"gh-remote",className:"visually-hidden",children:"Repository"}),t.jsxs("select",{id:"gh-remote",value:P,onChange:he=>me(he.target.value),disabled:m||O,"aria-label":"Select Git remote",children:[t.jsx("option",{value:"",children:"Select remote…"}),_.map(he=>t.jsxs("option",{value:he.name,children:[he.name," (",he.owner,"/",he.repo,")"]},he.name))]})]}):t.jsx("span",{className:"github-import-toolbar__no-remote",children:"No remotes"})}),t.jsx("div",{className:"github-import-toolbar__zone github-import-toolbar__zone--filter",children:p==="issues"?t.jsxs(t.Fragment,{children:[t.jsx("label",{htmlFor:"gh-labels",className:"visually-hidden",children:"Filter by labels"}),t.jsx("input",{id:"gh-labels",type:"text",placeholder:"Filter: bug,enhancement…",value:u,onChange:he=>h(he.target.value),onKeyDown:he=>he.key==="Enter"&&Ne(),disabled:m||O||!F,"aria-label":"Filter issues by labels"})]}):t.jsxs("span",{className:"github-import-filter-hint",children:["Open pull requests from ",o||"selected remote"]})}),t.jsx("div",{className:"github-import-toolbar__zone github-import-toolbar__zone--action",children:t.jsxs("button",{id:"gh-load",className:"btn btn-primary github-import-load-button",onClick:p==="issues"?Ne:ve,disabled:m||O||!o.trim()||!c.trim(),"aria-label":m?`Loading ${p}`:`Load ${p} from repository`,title:m?"Loading…":`Load ${p}`,children:[m?t.jsx(St,{size:14,className:"spin"}):t.jsx(us,{size:14}),t.jsx("span",{children:m?"Loading…":"Load"})]})})]}),!H&&!F&&t.jsxs("div",{className:"github-import-state github-import-state--warning",role:"alert",children:[t.jsxs("div",{children:[t.jsx("strong",{children:"No GitHub remotes detected"}),t.jsx("span",{children:"Add a GitHub remote to this repository, then reopen the modal."})]}),t.jsx("code",{className:"github-import-command",children:"git remote add origin https://github.com/owner/repo.git"})]}),We&&t.jsx("div",{className:"form-error github-import-banner",role:"alert",children:k}),t.jsxs("div",{className:"github-import-workspace",children:[t.jsxs("section",{className:`github-import-list-pane ${M?"mobile":""} ${D==="list"?"active":""}`,"data-testid":"github-import-list-pane","aria-labelledby":"github-import-results-heading",children:[t.jsxs("div",{className:"github-import-pane-header",children:[t.jsx("h4",{id:"github-import-results-heading",children:p==="issues"?"Issues":"Pull Requests"}),p==="issues"&&w.length>0&&t.jsxs("div",{className:"github-import-results-meta","aria-live":"polite",children:[t.jsxs("span",{children:[w.length," issue",w.length===1?"":"s"]}),t.jsxs("span",{children:[re," imported"]})]}),p==="pulls"&&j.length>0&&t.jsxs("div",{className:"github-import-results-meta","aria-live":"polite",children:[t.jsxs("span",{children:[j.length," pull request",j.length===1?"":"s"]}),t.jsxs("span",{children:[U," imported"]})]})]}),t.jsxs("div",{className:"github-import-pane-content",children:[!Te&&t.jsx("div",{className:"github-import-state github-import-state--idle","data-testid":"github-import-results-idle",children:t.jsxs("div",{children:[t.jsx("strong",{children:"Nothing loaded yet"}),t.jsx("span",{children:"Select a repository and click Load to start reviewing import candidates."})]})}),m&&t.jsxs("div",{className:"github-import-state github-import-state--loading",role:"status","aria-live":"polite",children:[t.jsx(St,{size:16,className:"spin"}),t.jsxs("div",{children:[t.jsxs("strong",{children:["Loading open ",p==="issues"?"issues":"pull requests","…"]}),t.jsx("span",{children:"Fetching the latest list from GitHub."})]})]}),ct&&t.jsx("div",{className:"github-import-state github-import-state--error",role:"alert",children:t.jsxs("div",{children:[t.jsxs("strong",{children:["Could not load ",p==="issues"?"issues":"pull requests"]}),t.jsx("span",{children:k})]})}),se&&t.jsx("div",{className:"github-import-state github-import-state--empty",role:"status",children:t.jsxs("div",{children:[t.jsxs("strong",{children:["No open ",p==="issues"?"issues":"pull requests"," found"]}),t.jsx("span",{children:p==="issues"?"Try a different label filter or choose another repository.":"Choose another repository."})]})}),p==="issues"&&w.length>0&&t.jsx("div",{className:"issues-list","aria-live":"polite",children:w.map(he=>{const pe=de.has(he.html_url);return t.jsxs("div",{className:`issue-item ${b===he.number?"selected":""} ${pe?"imported":""}`,onClick:()=>!pe&&Me(he.number),children:[t.jsx("input",{type:"radio",name:"issue",checked:b===he.number,onChange:()=>Me(he.number),disabled:pe,"aria-label":`Select issue #${he.number}`}),t.jsxs("div",{className:"issue-main",children:[t.jsxs("div",{className:"issue-heading-row",children:[t.jsxs("span",{className:"issue-number",children:["#",he.number]}),t.jsx("span",{className:"issue-title",children:he.title})]}),he.labels.length>0&&t.jsx("span",{className:"issue-labels",children:he.labels.map(De=>t.jsx("span",{className:"label-chip",children:De.name},De.name))})]}),pe&&t.jsx("span",{className:"imported-badge",children:"Imported"})]},he.number)})}),p==="pulls"&&j.length>0&&t.jsx("div",{className:"issues-list","aria-live":"polite",children:j.map(he=>{const pe=de.has(he.html_url);return t.jsxs("div",{className:`issue-item ${C===he.number?"selected":""} ${pe?"imported":""}`,onClick:()=>!pe&&ie(he.number),children:[t.jsx("input",{type:"radio",name:"pull",checked:C===he.number,onChange:()=>ie(he.number),disabled:pe,"aria-label":`Select pull request #${he.number}`}),t.jsxs("div",{className:"issue-main",children:[t.jsxs("div",{className:"issue-heading-row",children:[t.jsxs("span",{className:"issue-number",children:["#",he.number]}),t.jsx("span",{className:"issue-title",children:he.title})]}),t.jsxs("span",{className:"pull-branch-info",children:[he.headBranch," → ",he.baseBranch]})]}),pe&&t.jsx("span",{className:"imported-badge",children:"Imported"})]},he.number)})})]})]}),t.jsxs("section",{className:`github-import-preview-pane ${M?"mobile":""} ${D==="preview"?"active":""}`,"data-testid":"github-import-preview-pane","aria-labelledby":"github-import-preview-heading",children:[t.jsxs("div",{className:"github-import-pane-header",children:[M&&t.jsxs("button",{className:"github-import-back-button",onClick:ye,"data-testid":"github-import-back-button","aria-label":`Back to ${p==="issues"?"issues":"pull requests"} list`,children:[t.jsx(Ka,{size:16}),t.jsx("span",{children:"Back"})]}),t.jsx("h4",{id:"github-import-preview-heading",children:"Preview"})]}),t.jsxs("div",{className:"github-import-pane-content",children:[p==="issues"&&fe?t.jsxs("div",{className:"issue-preview","data-testid":"github-import-preview-card",children:[t.jsxs("div",{className:"preview-meta",children:["Issue #",fe.number]}),t.jsx("div",{className:"preview-title",children:fe.title}),t.jsx("div",{className:"preview-body",children:fe.body?fe.body.slice(0,200)+(fe.body.length>200?"…":""):"(no description)"})]}):p==="issues"?t.jsx("div",{className:"github-import-state github-import-state--idle","data-testid":"github-import-preview-empty",children:t.jsxs("div",{children:[t.jsx("strong",{children:"No issue selected"}),t.jsx("span",{children:"Choose an issue from the list to inspect its title and description."})]})}):null,p==="pulls"&&Q?t.jsxs("div",{className:"issue-preview","data-testid":"github-import-preview-card",children:[t.jsxs("div",{className:"preview-meta",children:["Pull Request #",Q.number]}),t.jsx("div",{className:"preview-title",children:Q.title}),t.jsxs("div",{className:"preview-branch",children:[t.jsx("strong",{children:"Branch:"})," ",Q.headBranch," → ",Q.baseBranch]}),t.jsx("div",{className:"preview-body",children:Q.body?Q.body.slice(0,200)+(Q.body.length>200?"…":""):"(no description)"})]}):p==="pulls"?t.jsx("div",{className:"github-import-state github-import-state--idle","data-testid":"github-import-preview-empty",children:t.jsxs("div",{children:[t.jsx("strong",{children:"No pull request selected"}),t.jsx("span",{children:"Choose a pull request from the list to inspect its details."})]})}):null]})]})]})]}),t.jsxs("div",{className:"modal-actions github-import-modal__actions",children:[t.jsx("button",{className:"btn",onClick:n,disabled:O,children:"Cancel"}),t.jsx("button",{className:"btn btn-primary",onClick:Z,disabled:(p==="issues"?b===null:C===null)||O,children:O?t.jsx(St,{size:14,className:"spin"}):"Import"})]})]})})}function li({summary:e,children:n,className:s="",onToggle:a,defaultOpen:r=!1}){const[o,l]=i.useState(r);return t.jsxs("div",{className:`onboarding-disclosure ${s}`.trim(),children:[t.jsxs("button",{className:"onboarding-disclosure-trigger",onClick:()=>{const c=!o;l(c),a?.(c)},"aria-expanded":o,type:"button",children:[t.jsx(Wn,{size:14,className:"onboarding-disclosure-chevron","aria-hidden":"true"}),t.jsx("span",{children:e})]}),o?t.jsx("div",{className:"onboarding-disclosure-content",children:n}):null]})}const T4=["Build a user authentication system with login and signup","Add dark mode support to the dashboard","Create an API endpoint for exporting tasks as CSV","Refactor the task card component for better performance"];function Wa(e){return e&&wa.includes(e)?e:_s}function qd(e){return{...e,priority:Wa(e.priority)}}function P4(e,n){return e.length===n.length&&e.every((s,a)=>s===n[a])}function $4(e,n){const s=new Map(e.map(a=>[a.id,a]));return n.map(a=>{const r=s.get(a.id),o=Wa(a.priority),l={id:a.id};return(!r||a.title!==r.title)&&(l.title=a.title),(!r||a.description!==r.description)&&(l.description=a.description),(!r||a.suggestedSize!==r.suggestedSize)&&(l.suggestedSize=a.suggestedSize),(!r||o!==Wa(r.priority))&&(l.priority=o),(!r||!P4(a.dependsOn,r.dependsOn))&&(l.dependsOn=a.dependsOn),l})}function D4(e,n){return e&&n?`${e}/${n}`:""}function L4(e){if(!e)return{provider:void 0,modelId:void 0};const n=e.indexOf("/");return n===-1?{provider:void 0,modelId:void 0}:{provider:e.slice(0,n),modelId:e.slice(n+1)}}function O4({isOpen:e,onClose:n,onTaskCreated:s,onTasksCreated:a,tasks:r,initialPlan:o,projectId:l,resumeSessionId:c}){const[d,u]=i.useState(""),[h,m]=i.useState({type:"initial"}),[f,p]=i.useState(null),[g,w]=i.useState([]),[v,b]=i.useState([]),[y,j]=i.useState(null),S=i.useRef(!1),C=i.useRef(!1),[x,k]=i.useState(""),[R,O]=i.useState(!0),[E,_]=i.useState(!1),[G,H]=i.useState(!1),[A,P]=i.useState(null),[q,Y]=i.useState(0),ge=i.useRef(null),L=i.useRef(null),M=i.useRef(null),$=i.useRef(null),D=i.useRef(null),N=i.useRef(null),W=i.useRef(null),[de,me]=i.useState(c??null),Ne=i.useMemo(()=>Ya(),[]),{isLockedByOther:ve,takeControl:Me,isLoading:ie}=$c(e?de:null),{activeTabMap:ye,broadcastUpdate:Z,broadcastCompleted:fe,broadcastLock:Q,broadcastUnlock:F,broadcastHeartbeat:X}=Gr(),[re,U]=i.useState(void 0),[be,Ue]=i.useState(void 0),[se,Ve]=i.useState("medium"),[Le,ct]=i.useState(""),[Ke,oe]=i.useState([]),[Te,Fe]=i.useState(!1),[mt,We]=i.useState(null),[he,pe]=i.useState([]),[De,ut]=i.useState([]),[ht,et]=i.useState({}),vt=i.useRef(null),[Oe,tt]=i.useState([]),[ft,Mt]=i.useState(!1),[yt,Ge]=i.useState(c??null),[K,ue]=i.useState(!!c),[ot,xe]=i.useState(null),[dt,Je]=i.useState(!1),ke=i.useRef(!1),nt=i.useRef(null),bt=i.useRef(""),kt=i.useRef(null),wt=i.useRef(null);Oi(L,e,"fusion:planning-modal-size");const At=ei(),Ft=At==="mobile",{pushNav:ln}=Tv(),{keyboardOverlap:Vt,viewportHeight:hn,viewportOffsetTop:un,keyboardOpen:pn}=ea({enabled:At==="mobile"});Si(At==="mobile"&&e),i.useEffect(()=>{const ce=L.current;ce&&(pn?(ce.style.setProperty("--keyboard-overlap",`${Vt}px`),ce.style.setProperty("--vv-offset-top",`${un}px`),hn!==null?ce.style.setProperty("--vv-height",`${hn}px`):ce.style.removeProperty("--vv-height")):(ce.style.removeProperty("--keyboard-overlap"),ce.style.removeProperty("--vv-offset-top"),ce.style.removeProperty("--vv-height")))},[pn,Vt,un,hn]),i.useEffect(()=>{bt.current=x},[x]),i.useEffect(()=>{const ce=nt.current;if(!ce)return;ce.scrollHeight-ce.scrollTop-ce.clientHeight<32&&(ce.scrollTop=ce.scrollHeight)},[x]),i.useEffect(()=>{if(h.type!=="loading"){P(null),Y(0);return}const ce=Date.now();P(ce),Y(0);const ee=setInterval(()=>{Y(Math.max(0,Math.floor((Date.now()-ce)/1e3)))},1e3);return()=>clearInterval(ee)},[h.type]),i.useEffect(()=>{if(h.type!=="loading")return;const ce=$.current;if(!ce)return;let ee=!1;const qe=setInterval(async()=>{try{const z=await $i(ce);if(ee||!z||$.current!==ce)return;if(z.status==="awaiting_input"&&z.currentQuestion){const _e=JSON.parse(z.currentQuestion);m({type:"question",session:{sessionId:ce,currentQuestion:_e,summary:null}}),k("")}else if(z.status==="complete"&&z.result){const _e=qd(JSON.parse(z.result));m({type:"summary",session:{sessionId:ce,currentQuestion:null,summary:_e},summary:_e}),j(_e),k("")}}catch{}},8e3);return()=>{ee=!0,clearInterval(qe)}},[h.type]);const an=i.useCallback(()=>{u(""),m({type:"initial"}),p(null),w([]),b([]),j(null),k(""),_(!1),H(!1),U(void 0),Ue(void 0),Ve("medium"),ct(""),$.current=null,me(null)},[]),Wt=D4(re,be),gn=i.useCallback((ce,ee)=>{if(!ce||!ee)return ht.provider&&ht.modelId?`${ht.provider}/${ht.modelId}`:"Using default";const Se=Ke.find(qe=>qe.provider===ce&&qe.id===ee);return Se?`${Se.provider}/${Se.id}`:`${ce}/${ee}`},[Ke,ht.modelId,ht.provider]),cn=i.useCallback(async()=>{Fe(!0),We(null);try{const ce=await Bs();oe(ce.models),pe(ce.favoriteProviders),ut(ce.favoriteModels),et({provider:ce.resolvedPlanningProvider,modelId:ce.resolvedPlanningModelId})}catch(ce){We(Ie(ce)||"Failed to load models")}finally{Fe(!1)}},[]),tn=i.useCallback(ce=>{pe(ee=>{const Se=ee,z=Se.includes(ce)?Se.filter(_e=>_e!==ce):[ce,...Se];return Fn({favoriteProviders:z,favoriteModels:De}).catch(()=>{pe(Se)}),z})},[De]),Yt=i.useCallback(ce=>{ut(ee=>{const Se=ee,z=Se.includes(ce)?Se.filter(_e=>_e!==ce):[ce,...Se];return Fn({favoriteProviders:he,favoriteModels:z}).catch(()=>{ut(Se)}),z})},[he]),Qt=i.useCallback(ce=>{M.current?.close();const ee=()=>$.current!==ce,Se=o1(ce,l,{onThinking:qe=>{ee()||(k(z=>z+qe),Z({sessionId:ce,status:"generating",needsInput:!1,owningTabId:Ne,type:"planning",title:d.trim()||void 0,projectId:l??null}))},onQuestion:qe=>{if(ee())return;_(!1),H(!1),pr(l);const z=bt.current.trim();z&&b(_e=>_e[_e.length-1]?.thinkingOutput===z?_e:[..._e,{thinkingOutput:z}]),m({type:"question",session:{sessionId:ce,currentQuestion:qe,summary:null}}),k(""),Z({sessionId:ce,status:"awaiting_input",needsInput:!0,owningTabId:Ne,type:"planning",title:d.trim()||void 0,projectId:l??null})},onSummary:qe=>{if(ee())return;_(!1),H(!1),pr(l);const z=bt.current.trim();z&&b(_e=>_e[_e.length-1]?.thinkingOutput===z?_e:[..._e,{thinkingOutput:z}]),m({type:"summary",session:{sessionId:ce,currentQuestion:null,summary:qe},summary:qe}),j(qe),k(""),Z({sessionId:ce,status:"complete",needsInput:!1,owningTabId:Ne,type:"planning",title:d.trim()||void 0,projectId:l??null})},onError:qe=>{const z=qe||"Session failed while contacting the AI.";_(!0),(async()=>{try{const _e=await $i(ce);if(_e&&(_e.status==="generating"||_e.status==="awaiting_input")){Qt(ce);return}}catch{}_(!1),H(!1),p(null),m(_e=>_e.type==="question"||_e.type==="summary"||_e.type==="error"?{type:"error",session:_e.session,errorMessage:z}:{type:"error",session:{sessionId:ce,currentQuestion:null,summary:null},errorMessage:z}),k(""),$.current=ce,Z({sessionId:ce,status:"error",needsInput:!1,owningTabId:Ne,type:"planning",title:d.trim()||void 0,projectId:l??null}),fe({sessionId:ce,status:"error"})})()},onComplete:()=>{_(!1),H(!1),$.current=null,fe({sessionId:ce,status:"complete"})},onConnectionStateChange:qe=>{_(qe==="reconnecting")}});M.current=Se},[fe,Z,d,l,Ne]),Kt=i.useCallback(async ce=>{const ee=ce??d;if(ee.trim()){p(null),k(""),b([]),w([]),_(!1),m({type:"loading"});try{const Se=re&&be?{planningModelProvider:re,planningModelId:be}:void 0,qe=Le.trim()?Number.parseInt(Le,10):void 0,z=D.current,{sessionId:_e}=await HS(ee.trim(),l,Se,{planningDepth:se,customQuestionCount:Number.isInteger(qe)?qe:void 0},z??void 0);D.current=null,$.current=_e,me(_e),Ge(_e),Qt(_e),w([])}catch(Se){_(!1),p(Ie(Se)||"Failed to start planning session"),m({type:"initial"}),$.current=null,me(null)}}},[Qt,Le,d,se,be,re,l]);i.useEffect(()=>{e&&h.type==="initial"&&ge.current?.focus()},[e,h.type]),i.useEffect(()=>{e&&cn()},[e,cn]),i.useEffect(()=>{if(e&&o&&!S.current&&h.type==="initial"){u(o);const ce=setTimeout(()=>{S.current=!0,Kt(o)},0);return()=>clearTimeout(ce)}else if(e&&!o&&!S.current&&!C.current&&h.type==="initial"){C.current=!0;const ce=O$(l);ce&&u(ce)}},[e,o,h.type,Kt,l]);const Jt=i.useCallback(async ce=>{M.current?.close(),M.current=null,p(null),k(""),w([]),b([]),j(null),H(!1),m({type:"loading"});try{const ee=await $i(ce);if(!ee){Ge(null),ue(!1),m({type:"initial"});return}$.current=ce,me(ce);const Se=Ar(ee.conversationHistory);if(b(Se),w(Se.map(qe=>qe.response).filter(qe=>!!(qe&&typeof qe=="object"&&!Array.isArray(qe)))),ee.status==="draft"){let qe="",z,_e;try{const Rt=ee.inputPayload?JSON.parse(ee.inputPayload):null;Rt&&typeof Rt.initialPlan=="string"&&(qe=Rt.initialPlan),Rt&&typeof Rt.modelProvider=="string"&&typeof Rt.modelId=="string"&&(z=Rt.modelProvider,_e=Rt.modelId)}catch{}u(qe),U(z),Ue(_e),D.current=ce,wt.current=qe?{sessionId:ce,initialPlan:qe.trim(),modelProvider:z,modelId:_e}:null,m({type:"initial"})}else if(ee.status==="awaiting_input"&&ee.currentQuestion){pr(l);const qe=JSON.parse(ee.currentQuestion);if(m({type:"question",session:{sessionId:ce,currentQuestion:qe,summary:null}}),ee.thinkingOutput){const z=ee.thinkingOutput.trim();z&&b(_e=>_e[_e.length-1]?.thinkingOutput===z?_e:[..._e,{thinkingOutput:z}])}Qt(ce)}else if(ee.status==="complete"&&ee.result){pr(l);const qe=qd(JSON.parse(ee.result));m({type:"summary",session:{sessionId:ce,currentQuestion:null,summary:qe},summary:qe}),j(qe)}else ee.status==="generating"?(m({type:"loading"}),ee.thinkingOutput&&k(ee.thinkingOutput),Qt(ce)):ee.status==="error"&&m({type:"error",session:{sessionId:ce,currentQuestion:null,summary:null},errorMessage:ee.error||"Session failed"})}catch{p("Failed to load session"),m({type:"initial"})}},[Qt,l]);i.useEffect(()=>{!e||!c||$.current!==c&&W.current!==c&&(Ge(c),ue(!0),Jt(c))},[e,c]),i.useEffect(()=>{e&&yt&&(c&&c===yt||Jt(yt))},[e]);const rn=i.useCallback(async()=>{Mt(!0);try{const ee=(await Xu(l,{includeCompleted:!0,includeArchived:dt})).filter(Se=>Se.type==="planning").sort((Se,qe)=>Date.parse(qe.updatedAt)-Date.parse(Se.updatedAt));tt(ee)}catch{}finally{Mt(!1)}},[l,dt]);i.useEffect(()=>{e&&rn()},[e,rn]);const qt=i.useRef(!1);i.useEffect(()=>{const ce=qt.current&&!ft;qt.current=ft,ce&&At==="mobile"&&(K||c||yt||Oe.length>0||ue(!0))},[At,K,c,yt,ft,Oe.length]),i.useEffect(()=>{if(!e)return;const ce=l?`?projectId=${encodeURIComponent(l)}`:"",ee=qe=>{try{const z=JSON.parse(qe.data);if(z.type!=="planning")return;tt(_e=>{const Rt=_e.findIndex(Lt=>Lt.id===z.id);return(Rt>=0?[..._e.slice(0,Rt),z,..._e.slice(Rt+1)]:[z,..._e]).sort((Lt,fn)=>Date.parse(fn.updatedAt)-Date.parse(Lt.updatedAt))})}catch{}},Se=qe=>{try{const z=JSON.parse(qe.data);tt(_e=>_e.filter(Rt=>Rt.id!==z))}catch{}};return fi(`/api/events${ce}`,{events:{"ai_session:updated":ee,"ai_session:deleted":Se},onReconnect:()=>{rn()}})},[e,l,rn]);const we=i.useCallback(ce=>{if(yt===ce){ue(!0);return}Ge(ce),ue(!0),Jt(ce)},[Jt,yt]),ze=i.useCallback(()=>{M.current?.close(),M.current=null,D.current=null,N.current&&(clearTimeout(N.current),N.current=null),c&&(W.current=c),an(),Ge(null),ue(!0)},[an,c]),rt=i.useCallback(()=>{ue(!1)},[]),He=i.useRef(!1);i.useEffect(()=>{e||(He.current=!1)},[e]),i.useEffect(()=>{const ce=He.current;if(Ft){if(!K){He.current=!1;return}ce||ln({type:"view",revert:rt}),He.current=!0}},[rt,Ft,K,ln]);const Ae=i.useCallback(async(ce,ee)=>{const Se=ee.trim();if(!(!Se||wt.current?.sessionId===ce&&wt.current.initialPlan===Se&&wt.current.modelProvider===re&&wt.current.modelId===be))try{await eC(ce,{initialPlan:Se,modelProvider:re&&be?re:void 0,modelId:re&&be?be:void 0},l),wt.current={sessionId:ce,initialPlan:Se,modelProvider:re,modelId:be}}catch{}},[be,re,l]);i.useEffect(()=>{if(kt.current&&(clearTimeout(kt.current),kt.current=null),!(!e||h.type!=="initial"||!yt))return kt.current=setTimeout(()=>{Ae(yt,d)},500),()=>{kt.current&&(clearTimeout(kt.current),kt.current=null)}},[d,e,yt,Ae,h.type]),i.useEffect(()=>{wt.current=null},[yt]),i.useEffect(()=>()=>{kt.current&&(clearTimeout(kt.current),kt.current=null)},[]);const pt=i.useCallback(async ce=>{const ee=qe=>qe==="generating"||qe==="awaiting_input",Se=Oe.find(qe=>qe.id===ce);if(Se&&ee(Se.status))try{await Mb(ce,l,Ne)}catch{}try{await Ob(ce)}catch{}fe({sessionId:ce,status:"complete",timestamp:Date.now()}),tt(qe=>qe.filter(z=>z.id!==ce)),yt===ce&&(M.current?.close(),M.current=null,an(),Ge(null),ue(!1)),xe(null)},[fe,Oe,l,an,yt,Ne]),Ct=i.useCallback(async ce=>{const Se=Oe.find(qe=>qe.id===ce)?.archived===!0;try{Se?await J0(ce):await K0(ce)}catch{return}tt(qe=>!Se&&!dt?qe.filter(z=>z.id!==ce):qe.map(z=>z.id===ce?{...z,archived:!Se}:z)),!Se&&yt===ce&&!dt&&(M.current?.close(),M.current=null,an(),Ge(null),ue(!1))},[Oe,an,yt,ue,dt]);i.useEffect(()=>{e||(S.current=!1,C.current=!1,_(!1),H(!1),me(null))},[e]),i.useEffect(()=>{if(!e){vt.current&&(F(vt.current,Ne),vt.current=null);return}if(de&&vt.current!==de){vt.current&&F(vt.current,Ne),Q(de,Ne),vt.current=de;return}!de&&vt.current&&(F(vt.current,Ne),vt.current=null)},[Q,F,e,de,Ne]),i.useEffect(()=>{if(!e||!de||vt.current!==de)return;X(Ne);const ce=setInterval(()=>{X(Ne)},3e4);return()=>{clearInterval(ce)}},[X,e,de,Ne]),i.useEffect(()=>()=>{N.current&&(clearTimeout(N.current),N.current=null),M.current?.close(),M.current=null,vt.current&&(F(vt.current,Ne),vt.current=null)},[F,Ne]),i.useEffect(()=>{if(!e)return;const ce=()=>{M.current?.close(),M.current=null};return window.addEventListener("beforeunload",ce),()=>window.removeEventListener("beforeunload",ce)},[e]);const Tt=i.useCallback((ce,ee)=>{kt.current&&(clearTimeout(kt.current),kt.current=null),(async()=>{try{await Ae(ce,ee),await tC(ce,l)}catch{}})()},[l,Ae]),Gt=i.useCallback(()=>{if(At!=="mobile")return;const ce=document.activeElement;ce instanceof HTMLElement&&ce.blur(),window.scrollTo(0,0),requestAnimationFrame(()=>{window.scrollTo(0,0)})},[At]),nn=i.useCallback(()=>{d&&h.type==="initial"&&L$(d,l);const ce=D.current;ce&&d.trim()&&Tt(ce,d),D.current=null,N.current&&(clearTimeout(N.current),N.current=null),M.current?.close(),M.current=null,_(!1),H(!1),Gt(),n()},[Tt,d,n,l,Gt,h.type]);i.useEffect(()=>{if(!e)return;const ce=ee=>{ee.key==="Escape"&&nn()};return document.addEventListener("keydown",ce),()=>document.removeEventListener("keydown",ce)},[e,nn]);const Ht=i.useCallback(async ce=>{if(h.type!=="question")return;const{session:ee}=h,Se=ee.sessionId,qe=ee.currentQuestion;if(!qe){p("No active question in session");return}p(null),w(z=>[...z,ce]),b(z=>{const _e=bt.current.trim();let Rt=z;return _e&&Rt[Rt.length-1]?.thinkingOutput!==_e&&(Rt=[...Rt,{thinkingOutput:_e}]),[...Rt,{question:qe,response:ce}]}),m({type:"loading"}),k("");try{await th(Se,ce,l,Ne)}catch(z){p(Ie(z)||"Failed to submit response"),m({type:"question",session:ee})}},[l,Ne,h]),on=i.useCallback(async()=>{if(h.type!=="summary")return;const{session:ce,summary:ee}=h,Se=ce.sessionId;$.current=Se,me(Se),p(null),H(!1),k(""),m({type:"loading"}),Qt(Se);try{await th(Se,{refine:!0},l,Ne)}catch(qe){M.current?.close(),M.current=null,p(Ie(qe)||"Failed to refine plan"),m({type:"summary",session:ce,summary:y??ee})}},[Qt,y,l,Ne,h]),ae=i.useCallback(async()=>{const ce=$.current;if(ce){try{await WS(ce,l,Ne)}catch{}M.current?.close(),M.current=null,_(!1),H(!1),m({type:"error",session:{sessionId:ce,currentQuestion:null,summary:null},errorMessage:"Generation stopped by user. You can retry or start a new session."}),k("")}},[l,Ne]),le=i.useCallback(async()=>{if(h.type!=="error")return;const ce=h.session;p(null),H(!0),k(""),m({type:"loading"}),Qt(ce.sessionId);try{$.current=ce.sessionId,me(ce.sessionId),await VS(ce.sessionId,l,Ne)}catch(ee){let Se=ee;if((Ie(ee)||"").includes("not in an error state"))try{const z=await $i(ce.sessionId);if(!z)throw new Error("Failed to refresh planning session.");if($.current=z.id,me(z.id),z.status==="generating")k(z.thinkingOutput??""),m({type:"loading"});else if(z.status==="awaiting_input"){if(!z.currentQuestion)throw new Error("Planning session is awaiting input but has no current question.");const _e=JSON.parse(z.currentQuestion);if(pr(l),m({type:"question",session:{sessionId:z.id,currentQuestion:_e,summary:null}}),z.thinkingOutput){const Rt=z.thinkingOutput.trim();Rt&&b(Ot=>Ot[Ot.length-1]?.thinkingOutput===Rt?Ot:[...Ot,{thinkingOutput:Rt}])}M.current?.isConnected()||Qt(z.id)}else if(z.status==="complete"){if(!z.result)throw new Error("Planning session is complete but has no result.");const _e=qd(JSON.parse(z.result));pr(l),m({type:"summary",session:{sessionId:z.id,currentQuestion:null,summary:_e},summary:_e}),j(_e)}else z.status==="error"&&m({type:"error",session:{sessionId:z.id,currentQuestion:null,summary:null},errorMessage:z.error||"Retry failed. Please try again."});_(!1);return}catch(z){Se=z}M.current?.close(),M.current=null,m({type:"error",session:ce,errorMessage:Ie(Se)||"Retry failed. Please try again."}),_(!1)}finally{H(!1)}},[Qt,l,Ne,h]),Qe=i.useCallback(async()=>{if(h.type==="summary"){p(null),m({type:"loading"});try{const ce=h.session.sessionId,ee=await GS(ce,y??void 0,l);s(ee),Ge(null),tt(Se=>Se.filter(qe=>qe.id!==ce)),fe({sessionId:ce,status:"complete",timestamp:Date.now()}),nn()}catch(ce){p(Ie(ce)||"Failed to create task"),m({type:"summary",session:h.session,summary:h.summary})}}},[fe,y,h,l,s,nn]),xt=i.useCallback(async()=>{if(h.type==="summary"){p(null),m({type:"loading"});try{const ce=await KS(h.session.sessionId,y??void 0,l),ee=ce.subtasks.map(Se=>({...Se,priority:Wa(Se.priority),dependsOn:[...Se.dependsOn]}));me(ce.sessionId),m({type:"breakdown",sessionId:ce.sessionId,originalSubtasks:ee.map(Se=>({...Se,dependsOn:[...Se.dependsOn]})),subtasks:ee.map(Se=>({...Se,dependsOn:[...Se.dependsOn]})),dirty:!1})}catch(ce){p(Ie(ce)||"Failed to start breakdown"),m({type:"summary",session:h.session,summary:h.summary})}}},[y,h,l]),zt=i.useCallback(async()=>{if(h.type==="breakdown"){p(null),m({type:"creating"});try{const ce=h.sessionId,ee=await JS(ce,$4(h.originalSubtasks,h.subtasks.map(Se=>({...Se,priority:Wa(Se.priority)}))),l);a(ee.tasks),tt(Se=>Se.filter(qe=>qe.id!==ce)),fe({sessionId:ce,status:"complete",timestamp:Date.now()}),u(""),m({type:"initial"}),p(null),w([]),b([]),j(null),k(""),U(void 0),Ue(void 0),Ve("medium"),ct(""),$.current=null,me(null),Ge(null),nn()}catch(ce){p(Ie(ce)||"Failed to create tasks"),m({type:"breakdown",sessionId:h.sessionId,originalSubtasks:h.originalSubtasks,subtasks:h.subtasks,dirty:h.dirty})}}},[fe,nn,h,a,l]),sn=i.useCallback(async()=>{if(h.type!=="question"||g.length===0)return;const ce=h.session.sessionId;p(null),m({type:"loading"});try{const ee=await qS(ce,l,Ne);w(ee.history.map(Se=>Se.response&&typeof Se.response=="object"&&!Array.isArray(Se.response)?Se.response:{[Se.question.id]:Se.response})),b(ee.history.map(Se=>({question:Se.question,response:Se.response&&typeof Se.response=="object"&&!Array.isArray(Se.response)?Se.response:{[Se.question.id]:Se.response},thinkingOutput:Se.thinkingOutput}))),k(""),m({type:"question",session:{...h.session,currentQuestion:ee.currentQuestion,summary:null}})}catch(ee){p(Ie(ee)||"Failed to go back to the previous question"),m({type:"question",session:h.session})}},[l,g.length,Ne,h]),xn=()=>h.type==="question"?Math.min(g.length+1,3):3,$n=de?ye.get(de):null,wn=$n&&$n.tabId!==Ne,zn=ve&&(!wn||$n.stale);return e?t.jsx("div",{className:"modal-overlay open",onMouseDown:ce=>{ke.current=ce.target===ce.currentTarget},onClick:ce=>{ce.target===ce.currentTarget&&ke.current&&nn(),ke.current=!1},role:"dialog","aria-modal":"true",children:t.jsxs("div",{className:"modal modal-lg planning-modal",ref:L,children:[t.jsxs("div",{className:"modal-header",children:[t.jsxs("div",{className:"detail-title-row",children:[K&&t.jsx("button",{className:"modal-back planning-mobile-back",onClick:rt,"aria-label":"Back to sessions",title:"Back to sessions",children:t.jsx(gc,{size:18})}),t.jsx(Di,{size:20,className:"icon-triage"}),t.jsx("h3",{children:"Planning Mode"})]}),t.jsx("div",{className:"modal-header-actions",children:t.jsx("button",{className:"modal-close",onClick:nn,"aria-label":"Close",children:t.jsx(bn,{size:20})})})]}),t.jsxs("div",{className:`planning-modal-body planning-modal-body--split ${K?"planning-modal-body--show-detail":"planning-modal-body--show-list"}`,children:[t.jsx(H4,{sessions:Oe,loading:ft,selectedSessionId:yt,pendingDeleteId:ot,showArchived:dt,onToggleShowArchived:()=>Je(ce=>!ce),onArchive:ce=>void Ct(ce),onSelectSession:we,onNewSession:ze,onRequestDelete:xe,onConfirmDelete:ce=>void pt(ce),onCancelDelete:()=>xe(null)}),t.jsxs("div",{className:"planning-detail",children:[f&&t.jsx("div",{className:"form-error planning-error",children:f}),E&&t.jsx("div",{className:"form-hint text-muted",children:"Reconnecting…"}),h.type==="initial"&&t.jsxs("div",{className:"planning-initial",children:[t.jsxs("div",{className:"planning-view-scroll",children:[t.jsxs("div",{className:"planning-intro",children:[t.jsx(cs,{size:32,className:"icon-triage-lg"}),t.jsx("h4",{children:"Transform your idea into a detailed task"}),t.jsx("p",{className:"text-muted",children:"Describe what you want to build in plain language. The AI will ask clarifying questions and help you structure a well-defined task."})]}),t.jsxs("div",{className:"form-group",children:[t.jsx("label",{htmlFor:"initial-plan",children:"What do you want to build?"}),t.jsx("textarea",{ref:ge,id:"initial-plan",rows:4,className:"planning-textarea",placeholder:"e.g., Build a user authentication system with login, signup, and password reset...",value:d,onChange:ce=>{const ee=ce.target.value;u(ee),!(D.current||ee.trim().length===0)&&(N.current&&clearTimeout(N.current),N.current=setTimeout(()=>{if(D.current)return;const Se=ee.trim();if(!Se)return;US(Se,l,re&&be?{planningModelProvider:re,planningModelId:be}:void 0).then(z=>{D.current=z.sessionId,tt(_e=>_e.some(Ot=>Ot.id===z.sessionId)?_e:[{id:z.sessionId,type:"planning",status:"draft",title:z.title,preview:Se.length>80?`${Se.slice(0,79).trimEnd()}…`:Se,projectId:l??null,lockedByTab:null,updatedAt:new Date().toISOString(),archived:!1},..._e].sort((Ot,Lt)=>Date.parse(Lt.updatedAt)-Date.parse(Ot.updatedAt))),Ge(z.sessionId)}).catch(()=>{})},300))},onKeyDown:ce=>{ce.key==="Enter"&&!ce.shiftKey&&d.trim()&&(ce.preventDefault(),Kt())},onBlur:()=>{const ce=D.current;ce&&d.trim()&&Tt(ce,d)}})]}),t.jsxs("div",{className:"planning-examples",children:[t.jsx("span",{className:"planning-examples-label",children:"Try an example:"}),t.jsx("div",{className:"planning-example-chips",children:T4.map((ce,ee)=>t.jsx("button",{className:"planning-example-chip",onClick:()=>u(ce),children:ce.length>40?ce.slice(0,40)+"...":ce},ee))})]}),t.jsx(li,{summary:"Advanced planning settings",className:"planning-advanced-disclosure",children:t.jsxs("div",{className:"planning-advanced-content",children:[t.jsxs("div",{className:"planning-advanced-section planning-model-select-group",children:[t.jsxs("label",{htmlFor:"planning-modal-model",className:"form-label",children:["Planning Model",Te&&t.jsx("span",{className:"text-muted text-muted-sm",children:"Loading models…"})]}),t.jsx("p",{className:"planning-advanced-blurb",children:"Selects which model runs the planning interview and writes the final draft."}),t.jsx(Ns,{id:"planning-modal-model",label:"Planning Model",value:Wt,onChange:ce=>{const{provider:ee,modelId:Se}=L4(ce);U(ee),Ue(Se)},models:Ke,disabled:Te,favoriteProviders:he,onToggleFavorite:tn,favoriteModels:De,onToggleModelFavorite:Yt}),mt&&t.jsxs("div",{className:"form-hint form-hint-error",children:[mt," ",t.jsx("button",{type:"button",className:"text-link-btn",onClick:()=>{cn()},children:"Retry"})]}),t.jsx("div",{className:"model-selector-current model-selector-current--spaced",children:t.jsx("span",{className:`model-badge ${re&&be?"model-badge-custom":"model-badge-default"}`,children:gn(re,be)})})]}),t.jsxs("div",{className:"planning-advanced-section planning-depth-selector",children:[t.jsx("p",{className:"planning-advanced-blurb",children:"Plan size sets default interview depth. Questions lets you override with an exact count."}),t.jsxs("div",{className:"planning-depth-controls-row",children:[t.jsx("div",{className:"planning-depth-chip-group",role:"group","aria-label":"Planning depth",children:[{value:"small",label:"Small"},{value:"medium",label:"Medium"},{value:"large",label:"Large"}].map(ce=>t.jsx("button",{type:"button",className:`planning-depth-chip btn ${se===ce.value?"btn-primary planning-depth-chip-active":""}`,onClick:()=>Ve(ce.value),"aria-pressed":se===ce.value,children:ce.label},ce.value))}),t.jsxs("label",{className:"planning-depth-question-count",htmlFor:"planning-depth-questions",children:[t.jsx("span",{children:"Questions"}),t.jsx("input",{id:"planning-depth-questions",className:"input planning-depth-question-input",type:"number",min:1,max:20,value:Le,onChange:ce=>ct(ce.target.value),placeholder:"Auto"})]})]})]})]})})]}),t.jsx("div",{className:"planning-view-footer",children:t.jsxs("button",{className:"btn btn-primary planning-start-btn",onClick:()=>Kt(),disabled:!d.trim(),children:[t.jsx(Di,{size:16,className:"icon-mr-8"}),"Start Planning"]})})]}),h.type==="loading"&&t.jsxs("div",{className:"planning-loading",children:[t.jsx(St,{size:40,className:"spin icon-todo"}),t.jsx("p",{children:x?"AI is thinking...":"Generating next question..."}),A&&t.jsxs("div",{className:"planning-elapsed",children:["Thinking… (",q,"s)"]}),t.jsxs("div",{className:"planning-thinking-container",children:[t.jsx("button",{className:"planning-thinking-toggle",onClick:()=>O(!R),type:"button",children:R?"Hide thinking":"Show thinking"}),t.jsx("div",{className:"planning-loading-actions",children:t.jsxs("button",{className:"btn planning-stop-btn",type:"button",onClick:()=>void ae(),children:[t.jsx(mw,{size:14}),t.jsx("span",{className:"icon-ml-6",children:"Stop"})]})}),R&&x&&t.jsx("div",{className:"planning-thinking-output",ref:nt,children:t.jsx("pre",{children:x})})]})]}),h.type==="error"&&t.jsx("div",{className:"planning-summary",children:t.jsxs("div",{className:"planning-view-scroll planning-summary-scroll",children:[v.length>0&&t.jsxs(t.Fragment,{children:[t.jsx(ui,{entries:v}),t.jsx("div",{className:"conversation-separator"})]}),t.jsxs("div",{className:"ai-error-panel",role:"alert",children:[t.jsx("div",{className:"ai-error-icon",children:"⚠️"}),t.jsx("div",{className:"ai-error-message",children:h.errorMessage}),t.jsxs("div",{className:"ai-error-actions",children:[t.jsxs("button",{className:"btn btn-primary",onClick:()=>void le(),disabled:G,children:[G?t.jsx(St,{size:14,className:"spin"}):t.jsx(us,{size:14}),t.jsx("span",{className:"icon-ml-6",children:G?"Retrying...":"Retry"})]}),t.jsx("button",{className:"btn",onClick:nn,disabled:G,children:"Dismiss"})]})]})]})}),h.type==="creating"&&t.jsxs("div",{className:"planning-loading",children:[t.jsx(St,{size:40,className:"spin icon-todo"}),t.jsx("p",{children:"Creating tasks..."})]}),h.type==="question"&&h.session.currentQuestion&&t.jsx("div",{className:"planning-question",children:t.jsx(F4,{question:h.session.currentQuestion,progress:xn(),historyEntries:v,onSubmit:Ht,onBack:g.length>0?sn:void 0})}),h.type==="summary"&&y&&t.jsx(z4,{summary:y,historyEntries:v,onSummaryChange:j,tasks:r,onCreateTask:Qe,onBreakIntoTasks:xt,onRefine:()=>{on()},isLoading:!1}),h.type==="breakdown"&&t.jsx(U4,{subtasks:h.subtasks,isLoading:!1,onUpdateSubtasks:ce=>m({...h,subtasks:ce,dirty:!0}),onCreateTasks:zt,onBack:()=>{const ee={sessionId:h.sessionId,currentQuestion:null,summary:y??null};y&&m({type:"summary",session:ee,summary:y})}})]}),ve&&t.jsx("div",{className:"session-lock-overlay","data-testid":"session-lock-overlay",children:t.jsxs("div",{className:"session-lock-banner",children:[t.jsx(kc,{size:16}),t.jsx("span",{children:zn?"This session is active in another tab":"This session is active in another tab (live heartbeat)"}),zn&&t.jsx("button",{type:"button",onClick:()=>{Me()},disabled:ie,className:"btn btn-primary session-lock-take-control",children:ie?"Taking control...":"Take Control"})]})})]})]})}):null}function F4({question:e,progress:n,historyEntries:s,onSubmit:a,onBack:r}){const[o,l]=i.useState({}),[c,d]=i.useState(""),[u,h]=i.useState(""),m=i.useCallback(()=>{let p;e.type==="text"?p={[e.id]:c}:e.type==="confirm"?p={[e.id]:o[e.id]===!0}:p=o;const g=u.trim();g.length>0&&(p={...p,_comment:g}),a(p)},[u,e,o,c,a]);i.useEffect(()=>{l({}),d(""),h("")},[e.id]);const f=()=>{switch(e.type){case"text":return c.trim().length>0;case"single_select":return o[e.id]!==void 0;case"multi_select":return Array.isArray(o[e.id])&&o[e.id].length>0;case"confirm":return o[e.id]!==void 0;default:return!0}};return t.jsxs("div",{className:"planning-question-form",children:[t.jsxs("div",{className:"planning-view-scroll planning-question-scroll",children:[s.length>0&&t.jsxs(t.Fragment,{children:[t.jsx(ui,{entries:s}),t.jsx("div",{className:"conversation-separator"})]}),t.jsxs("div",{className:"planning-question-panel",children:[t.jsxs("div",{className:"planning-progress",children:[t.jsx("div",{className:"planning-progress-bar",children:[1,2,3].map(p=>t.jsx("div",{className:`planning-progress-step ${p<=n?"active":""}`},p))}),t.jsxs("span",{className:"planning-progress-text",children:["Question ",n," of ~3"]})]}),t.jsxs("div",{className:"planning-question-content",children:[t.jsx("h4",{className:"planning-question-text",children:e.question}),e.description&&t.jsx("p",{className:"planning-question-desc",children:e.description}),t.jsxs("div",{className:"planning-options",children:[e.type==="text"&&t.jsx("textarea",{className:"planning-textarea",rows:4,placeholder:"Type your answer here...",value:c,onChange:p=>d(p.target.value),onKeyDown:p=>{p.key==="Enter"&&!p.shiftKey&&c.trim()&&(p.preventDefault(),m())}}),e.type==="single_select"&&e.options&&t.jsx("div",{className:"planning-radio-group",role:"radiogroup",children:e.options.map(p=>t.jsxs("label",{className:"planning-option planning-option--radio",children:[t.jsx("input",{type:"radio",name:e.id,value:p.id,checked:o[e.id]===p.id,onChange:()=>l({[e.id]:p.id})}),t.jsxs("div",{className:"planning-option-content",children:[t.jsx("span",{className:"planning-option-label",children:p.label}),p.description&&t.jsx("span",{className:"planning-option-desc",children:p.description})]})]},p.id))}),e.type==="multi_select"&&e.options&&t.jsx("div",{className:"planning-checkbox-group",children:e.options.map(p=>{const g=o[e.id]||[];return t.jsxs("label",{className:"planning-option planning-option--checkbox",children:[t.jsx("input",{type:"checkbox",value:p.id,checked:g.includes(p.id),onChange:w=>{const v=w.target.checked?[...g,p.id]:g.filter(b=>b!==p.id);l({[e.id]:v})}}),t.jsxs("div",{className:"planning-option-content",children:[t.jsx("span",{className:"planning-option-label",children:p.label}),p.description&&t.jsx("span",{className:"planning-option-desc",children:p.description})]})]},p.id)})}),e.type==="confirm"&&t.jsxs("div",{className:"planning-confirm-group",children:[t.jsxs("button",{className:`planning-confirm-btn ${o[e.id]===!0?"selected":""}`,onClick:()=>l({[e.id]:!0}),children:[t.jsx(Zn,{size:18}),"Yes"]}),t.jsxs("button",{className:`planning-confirm-btn ${o[e.id]===!1?"selected":""}`,onClick:()=>l({[e.id]:!1}),children:[t.jsx(bn,{size:18}),"No"]})]})]}),e.type!=="text"&&t.jsxs("div",{className:"planning-comment-section",children:[t.jsx("label",{className:"planning-comment-label",htmlFor:`planning-comment-${e.id}`,children:"Additional comments (optional)"}),t.jsx("textarea",{id:`planning-comment-${e.id}`,className:"planning-textarea",rows:2,placeholder:"Add any extra context or direction...",value:u,onChange:p=>h(p.target.value)})]})]})]})]}),t.jsxs("div",{className:"planning-actions",children:[r&&t.jsxs("button",{className:"btn",onClick:r,children:[t.jsx(Ka,{size:16,className:"icon-mr-4"}),"Back"]}),t.jsxs("button",{className:"btn btn-primary planning-actions-primary",onClick:m,disabled:!f(),children:["Continue",t.jsx(Ho,{size:16,className:"icon-ml-4"})]})]})]})}function z4({summary:e,historyEntries:n,onSummaryChange:s,tasks:a,onCreateTask:r,onBreakIntoTasks:o,onRefine:l,isLoading:c}){const[d,u]=i.useState(!1),[h,m]=i.useState(e.suggestedDependencies),f=Wa(e.priority),p=g=>{const w=h.includes(g)?h.filter(v=>v!==g):[...h,g];m(w),s({...e,suggestedDependencies:w})};return t.jsxs("div",{className:"planning-summary",children:[t.jsxs("div",{className:"planning-view-scroll planning-summary-scroll",children:[n.length>0&&t.jsxs(li,{summary:"Show user Q&A",className:"planning-summary-qa-disclosure",children:[t.jsx(ui,{entries:n}),t.jsx("div",{className:"conversation-separator"})]}),t.jsxs("div",{className:"planning-summary-header",children:[t.jsx(Zn,{size:24,className:"icon-success"}),t.jsx("h4",{children:"Planning Complete!"}),t.jsx("p",{className:"text-muted",children:"Review and refine your task before creating it."})]}),t.jsxs("div",{className:"planning-summary-form",children:[t.jsxs("div",{className:"form-group",children:[t.jsxs("label",{children:["Description",t.jsx("button",{type:"button",className:"planning-expand-btn",onClick:()=>u(!d),children:d?"Collapse":"Expand"})]}),t.jsx("textarea",{className:`planning-textarea ${d?"expanded":""}`,rows:d?10:4,value:e.description,onChange:g=>s({...e,description:g.target.value})})]}),t.jsxs("div",{className:"planning-summary-meta-row",children:[t.jsxs("div",{className:"form-group",children:[t.jsx("label",{htmlFor:"planning-summary-size",children:"Suggested Size"}),t.jsxs("select",{id:"planning-summary-size",className:"planning-size-select",value:e.suggestedSize,onChange:g=>s({...e,suggestedSize:g.target.value}),disabled:c,children:[t.jsx("option",{value:"S",children:"S (Small)"}),t.jsx("option",{value:"M",children:"M (Medium)"}),t.jsx("option",{value:"L",children:"L (Large)"})]})]}),t.jsxs("div",{className:"form-group",children:[t.jsx("label",{htmlFor:"planning-summary-priority",children:"Priority"}),t.jsx("select",{id:"planning-summary-priority",className:"planning-size-select",value:f,onChange:g=>s({...e,priority:g.target.value}),disabled:c,children:wa.map(g=>t.jsx("option",{value:g,children:g[0].toUpperCase()+g.slice(1)},g))})]})]}),a.length>0&&t.jsxs("div",{className:"form-group",children:[t.jsx("label",{children:"Suggested Dependencies"}),t.jsx("div",{className:"planning-deps-list",children:a.map(g=>t.jsxs("label",{className:`planning-dep-chip ${h.includes(g.id)?"selected":""}`,children:[t.jsx("input",{type:"checkbox",checked:h.includes(g.id),onChange:()=>p(g.id)}),t.jsx("span",{className:"planning-dep-id",children:g.id}),t.jsx("span",{className:"planning-dep-title",children:g.title||g.description.slice(0,30)})]},g.id))})]}),t.jsxs("div",{className:"form-group",children:[t.jsx("label",{children:"Key Deliverables"}),t.jsx("ul",{className:"planning-deliverables",children:e.keyDeliverables.map((g,w)=>t.jsx("li",{children:g},w))})]})]})]}),t.jsxs("div",{className:"planning-actions planning-summary-actions",children:[t.jsxs("button",{className:"btn",onClick:l,disabled:c,children:[t.jsx(Ka,{size:16,className:"icon-mr-4"}),"Refine Further"]}),t.jsxs("div",{className:"planning-summary-actions-right",children:[t.jsx("button",{className:"btn",onClick:r,disabled:c,children:c?t.jsxs(t.Fragment,{children:[t.jsx(St,{size:16,className:"spin icon-mr-8"}),"Creating..."]}):t.jsxs(t.Fragment,{children:[t.jsx(Zn,{size:16,className:"icon-mr-8"}),"Create Single Task"]})}),t.jsx("button",{className:"btn btn-primary",onClick:o,disabled:c,title:"Break the plan into multiple tasks with dependencies",children:c?t.jsxs(t.Fragment,{children:[t.jsx(St,{size:16,className:"spin icon-mr-8"}),"Breaking down..."]}):t.jsxs(t.Fragment,{children:[t.jsx(wc,{size:16,className:"icon-mr-8"}),"Break into Tasks"]})})]})]})]})}function Vf(e){const n=new Map(e.map(o=>[o.id,o.dependsOn])),s=new Set,a=new Set,r=o=>{if(s.has(o))return!0;if(a.has(o))return!1;s.add(o);for(const l of n.get(o)??[])if(n.has(l)&&r(l))return!0;return s.delete(o),a.add(o),!1};return e.some(o=>r(o.id))}function B4(e){return{id:`subtask-${e}`,title:"",description:"",suggestedSize:"M",priority:_s,dependsOn:[]}}function U4({subtasks:e,isLoading:n,onUpdateSubtasks:s,onCreateTasks:a,onBack:r}){const[o,l]=i.useState(null),[c,d]=i.useState(null),[u,h]=i.useState(null),m=i.useRef([]),f=i.useMemo(()=>e.length===0||e.some(x=>!x.title.trim())?!0:Vf(e),[e]),p=i.useCallback((x,k)=>{s(e.map(R=>R.id===x?{...R,...k}:R))},[e,s]),g=i.useCallback(()=>{s([...e,B4(e.length+1)])},[e,s]),w=i.useCallback(x=>{s(e.filter(k=>k.id!==x).map(k=>({...k,dependsOn:k.dependsOn.filter(R=>R!==x)})))},[e,s]),v=i.useCallback((x,k)=>{if(k<0||k>=e.length)return;const R=[...e],[O]=R.splice(x,1);R.splice(k,0,O),s(R)},[e,s]),b=i.useCallback(x=>k=>{l(x),k.dataTransfer.setData("text/plain",x),k.dataTransfer.effectAllowed="move"},[]),y=i.useCallback(()=>{l(null),d(null),h(null)},[]),j=i.useCallback(x=>k=>{if(k.preventDefault(),x===o)return;const R=k.currentTarget.getBoundingClientRect(),O=R.top+R.height/2,E=k.clientY<O?"before":"after";d(x),h(E)},[o]),S=i.useCallback(x=>k=>{k.preventDefault();const R=k.dataTransfer.getData("text/plain");if(!R||R===x){y();return}const O=e.findIndex(A=>A.id===R),E=e.findIndex(A=>A.id===x);if(O===-1||E===-1){y();return}const _=[...e],[G]=_.splice(O,1);let H=E;u==="after"&&O<E&&H--,u==="after"&&H++,_.splice(H,0,G),s(_),y()},[e,u,s,y]),C=i.useCallback(x=>{const k=x.currentTarget.getBoundingClientRect(),R=x.clientX,O=x.clientY;(R<k.left||R>k.right||O<k.top||O>k.bottom)&&(d(null),h(null))},[]);return t.jsxs("div",{className:"planning-summary",children:[t.jsxs("div",{className:"planning-view-scroll planning-summary-scroll",children:[t.jsxs("div",{className:"planning-summary-header",children:[t.jsx(wc,{size:24,className:"icon-triage"}),t.jsx("h4",{children:"Break into Tasks"}),t.jsx("p",{className:"text-muted",children:"Review and edit the subtasks generated from your plan. Adjust titles, descriptions, sizes, priorities, and dependencies before creating."})]}),t.jsxs("div",{className:"planning-summary-form",children:[e.map((x,k)=>{const R=o===x.id,O=c===x.id,E=["task-detail-section","subtask-item",R?"subtask-item-dragging":"",O?"subtask-item-drop-target":"",O&&u==="before"?"subtask-item-drop-before":"",O&&u==="after"?"subtask-item-drop-after":""].filter(Boolean).join(" ");return t.jsxs("div",{className:E,"data-testid":`subtask-item-${k}`,draggable:!n,onDragStart:b(x.id),onDragEnd:y,onDragOver:j(x.id),onDrop:S(x.id),onDragLeave:C,children:[t.jsxs("div",{className:"detail-title-row subtask-item-header subtask-item-header--between",children:[t.jsxs("div",{className:"subtask-drag-handle",title:"Drag to reorder",children:[t.jsx(yc,{size:16}),t.jsx("strong",{children:x.id})]}),t.jsxs("div",{className:"subtask-item-actions",children:[t.jsx("button",{type:"button",className:"btn btn-icon btn-sm",onClick:()=>v(k,k-1),disabled:n||k===0,title:"Move up","aria-label":"Move subtask up",children:t.jsx(La,{size:14})}),t.jsx("button",{type:"button",className:"btn btn-icon btn-sm",onClick:()=>v(k,k+1),disabled:n||k===e.length-1,title:"Move down","aria-label":"Move subtask down",children:t.jsx(Uo,{size:14})}),t.jsxs("button",{type:"button",className:"btn btn-sm",onClick:()=>w(x.id),disabled:n,children:[t.jsx(In,{size:14})," Remove"]})]})]}),t.jsxs("div",{className:"form-group",children:[t.jsx("label",{children:"Title"}),t.jsx("input",{ref:_=>{m.current[k]=_},value:x.title,onChange:_=>p(x.id,{title:_.target.value}),onKeyDown:_=>{_.key==="Enter"&&(_.preventDefault(),k<e.length-1&&m.current[k+1]?.focus())},disabled:n})]}),t.jsxs("div",{className:"form-group",children:[t.jsx("label",{children:"Description"}),t.jsx("textarea",{rows:3,value:x.description,onChange:_=>p(x.id,{description:_.target.value}),disabled:n})]}),t.jsxs("div",{className:"planning-summary-meta-row",children:[t.jsxs("div",{className:"form-group",children:[t.jsx("label",{htmlFor:`${x.id}-size`,children:"Size"}),t.jsxs("select",{id:`${x.id}-size`,className:"planning-size-select",value:x.suggestedSize,onChange:_=>p(x.id,{suggestedSize:_.target.value}),disabled:n,children:[t.jsx("option",{value:"S",children:"S"}),t.jsx("option",{value:"M",children:"M"}),t.jsx("option",{value:"L",children:"L"})]})]}),t.jsxs("div",{className:"form-group",children:[t.jsx("label",{htmlFor:`${x.id}-priority`,children:"Priority"}),t.jsx("select",{id:`${x.id}-priority`,className:"planning-size-select",value:Wa(x.priority),onChange:_=>p(x.id,{priority:_.target.value}),disabled:n,children:wa.map(_=>t.jsx("option",{value:_,children:_[0].toUpperCase()+_.slice(1)},_))})]})]}),t.jsxs("div",{className:"form-group",children:[t.jsx("label",{children:"Dependencies"}),t.jsxs("div",{className:"planning-deps-list",children:[e.slice(0,k).filter(_=>_.id!==x.id).map(_=>{const G=x.dependsOn.includes(_.id);return t.jsxs("label",{className:`planning-dep-chip ${G?"selected":""}`,children:[t.jsx("input",{type:"checkbox",checked:G,onChange:()=>{const H=G?x.dependsOn.filter(A=>A!==_.id):[...x.dependsOn,_.id];p(x.id,{dependsOn:H})},disabled:n}),t.jsx("span",{className:"planning-dep-id",children:_.id}),t.jsx("span",{className:"planning-dep-title",children:_.title||"Untitled"})]},_.id)}),k===0&&t.jsx("div",{className:"text-muted",children:"First subtask cannot have dependencies."}),k>0&&e.slice(0,k).filter(_=>_.id!==x.id).length===0&&t.jsx("div",{className:"text-muted",children:"No previous subtasks available."})]})]})]},x.id)}),t.jsxs("button",{type:"button",className:"btn",onClick:g,disabled:n,children:[t.jsx(Tn,{size:16,className:"icon-mr-6"})," Add subtask"]}),Vf(e)&&t.jsx("div",{className:"form-error planning-error",children:"Dependencies contain a cycle. Remove circular references before creating tasks."})]})]}),t.jsxs("div",{className:"planning-actions planning-summary-actions",children:[t.jsxs("button",{className:"btn",onClick:r,disabled:n,children:[t.jsx(Ka,{size:16,className:"icon-mr-4"}),"Back to Summary"]}),t.jsx("button",{className:"btn btn-primary",onClick:a,disabled:n||f,children:n?t.jsxs(t.Fragment,{children:[t.jsx(St,{size:16,className:"spin icon-mr-6"}),"Creating..."]}):t.jsx(t.Fragment,{children:"Create Tasks"})})]})]})}function H4({sessions:e,loading:n,selectedSessionId:s,pendingDeleteId:a,showArchived:r,onToggleShowArchived:o,onArchive:l,onSelectSession:c,onNewSession:d,onRequestDelete:u,onConfirmDelete:h,onCancelDelete:m}){return t.jsxs("aside",{className:"planning-sidebar","aria-label":"Planning sessions",children:[t.jsx("div",{className:"planning-sidebar-header",children:t.jsxs("button",{className:`planning-sidebar-new ${s===null?"active":""}`,onClick:d,type:"button",children:[t.jsx(_k,{size:16}),t.jsx("span",{children:"New session"})]})}),t.jsxs("div",{className:"planning-sidebar-list",children:[e.length===0&&!n&&t.jsx("div",{className:"planning-sidebar-empty text-muted",children:"No saved sessions yet. Start one on the right to see it here."}),e.map(f=>{const p=f.id===s,g=a===f.id,w=f.archived===!0,v=f.status==="complete"||f.status==="error";return t.jsxs("div",{className:`planning-sidebar-item ${p?"selected":""} ${g?"pending-delete":""} ${w?"archived":""}`,children:[t.jsxs("button",{type:"button",className:"planning-sidebar-item-button",onClick:()=>c(f.id),children:[t.jsx(q4,{status:f.status}),t.jsxs("span",{className:"planning-sidebar-item-body",children:[t.jsx("span",{className:"planning-sidebar-item-title",children:f.status==="draft"&&(!f.title||f.title==="New planning session")?f.preview??"New planning session":f.title||"Untitled session"}),t.jsxs("span",{className:"planning-sidebar-item-meta",children:[t.jsx(V4,{status:f.status}),t.jsx("span",{"aria-hidden":!0,children:" · "}),t.jsx("span",{children:W4(f.updatedAt)})]})]})]}),g?t.jsxs("div",{className:"planning-sidebar-confirm",children:[t.jsx("button",{type:"button",className:"btn btn-sm btn-danger",onClick:()=>h(f.id),children:"Delete"}),t.jsx("button",{type:"button",className:"btn btn-sm",onClick:m,children:"Cancel"})]}):t.jsxs("div",{className:"planning-sidebar-item-actions",children:[v&&t.jsx("button",{type:"button",className:"planning-sidebar-item-archive",onClick:b=>{b.stopPropagation(),l(f.id)},"aria-label":w?"Unarchive session":"Archive session",title:w?"Unarchive session":"Archive session",children:w?t.jsx(Uy,{size:14}):t.jsx(Fr,{size:14})}),t.jsx("button",{type:"button",className:"planning-sidebar-item-delete",onClick:b=>{b.stopPropagation(),u(f.id)},"aria-label":"Delete session",title:"Delete session",children:t.jsx(In,{size:14})})]})]},f.id)})]}),t.jsx("div",{className:"planning-sidebar-footer",children:t.jsx("a",{href:"#",className:"planning-sidebar-toggle-archived-link",onClick:f=>{f.preventDefault(),o()},"aria-pressed":r,children:r?"Hide archived":"Show archived"})})]})}function q4({status:e}){switch(e){case"generating":return t.jsx(St,{size:14,className:"spin planning-sidebar-status-icon planning-sidebar-status-generating"});case"awaiting_input":return t.jsx(au,{size:14,className:"planning-sidebar-status-icon planning-sidebar-status-awaiting"});case"complete":return t.jsx(Zn,{size:14,className:"planning-sidebar-status-icon planning-sidebar-status-complete"});case"error":return t.jsx(zs,{size:14,className:"planning-sidebar-status-icon planning-sidebar-status-error"});default:return t.jsx(Yi,{size:14,className:"planning-sidebar-status-icon"})}}function V4({status:e}){switch(e){case"generating":return t.jsx("span",{children:"Generating"});case"awaiting_input":return t.jsx("span",{children:"Needs input"});case"complete":return t.jsx("span",{children:"Complete"});case"error":return t.jsx("span",{children:"Error"});default:return t.jsx("span",{children:e})}}function W4(e){const n=Date.now()-Date.parse(e);if(!Number.isFinite(n)||n<0)return"";const s=Math.floor(n/1e3);if(s<60)return"just now";const a=Math.floor(s/60);if(a<60)return`${a}m ago`;const r=Math.floor(a/60);if(r<24)return`${r}h ago`;const o=Math.floor(r/24);if(o<7)return`${o}d ago`;const l=Math.floor(o/7);return l<4?`${l}w ago`:new Date(e).toLocaleDateString()}function G4(e){return{id:`subtask-${e}`,title:"",description:"",suggestedSize:"M",dependsOn:[]}}function Wf(e){const n=new Map(e.map(o=>[o.id,o.dependsOn])),s=new Set,a=new Set,r=o=>{if(s.has(o))return!0;if(a.has(o))return!1;s.add(o);for(const l of n.get(o)??[])if(n.has(l)&&r(l))return!0;return s.delete(o),a.add(o),!1};return e.some(o=>r(o.id))}function K4({isOpen:e,onClose:n,initialDescription:s,onTasksCreated:a,parentTaskId:r,projectId:o,resumeSessionId:l}){const c=ei();Si(e);const{keyboardOverlap:d,viewportHeight:u,viewportOffsetTop:h,keyboardOpen:m}=ea({enabled:c==="mobile"}),f=m?{"--keyboard-overlap":`${d}px`,"--vv-offset-top":`${h}px`,...u!==null?{"--vv-height":`${u}px`}:{}}:{},[p,g]=i.useState({type:"initial"}),[w,v]=i.useState([]),[b,y]=i.useState([]),[j,S]=i.useState(""),[C,x]=i.useState(!0),[k,R]=i.useState(!1),[O,E]=i.useState(!1),[_,G]=i.useState(s),[H,A]=i.useState(null),[P,q]=i.useState(!1),[Y,ge]=i.useState("project-default"),[L,M]=i.useState(""),[$,D]=i.useState(""),[N,W]=i.useState("shared"),[de,me]=i.useState(null),[Ne,ve]=i.useState(null),[Me,ie]=i.useState(null),ye=i.useRef(null),Z=i.useRef([]),fe=i.useRef(!1),Q=i.useRef(null),F=p.type==="generating"||p.type==="editing"||p.type==="creating"||p.type==="error"?p.sessionId:null,X=i.useMemo(()=>Ya(),[]),{isLockedByOther:re,takeControl:U,isLoading:be}=$c(e?F:null),{activeTabMap:Ue,broadcastUpdate:se,broadcastCompleted:Ve,broadcastLock:Le,broadcastUnlock:ct,broadcastHeartbeat:Ke}=Gr(),oe=i.useMemo(()=>w.length===0||w.some(ke=>!ke.title.trim())||(Y==="existing"||Y==="custom-new")&&!L.trim()?!0:Wf(w),[Y,L,w]),Te=p.type==="generating"||p.type==="editing"||p.type==="error",Fe=F?Ue.get(F):null,{confirm:mt}=ti(),We=Fe&&Fe.tabId!==X,he=!!(We&&!Fe.stale),pe=re&&(!We||Fe.stale),De=i.useCallback(()=>{_&&F$(_,o),ye.current?.close(),ye.current=null,g({type:"initial"}),v([]),y([]),S(""),x(!0),R(!1),E(!1),A(null),q(!1),ge("project-default"),M(""),D(""),W("shared"),fe.current=!1},[_,o]),ut=i.useCallback(()=>{ye.current?.close(),ye.current=null,n()},[n]),ht=i.useCallback(async()=>{if(!((P||p.type==="editing"||p.type==="creating")&&!await mt({title:"Discard Changes",message:"Close subtask breakdown? Unsaved changes will be lost.",danger:!0}))){if(F)try{await Ib(F,o,X)}catch{}De(),n()}},[P,n,De,F,X,p.type,o,mt]),et=i.useCallback(ke=>{ye.current?.close(),ye.current=N1(ke,o,{onThinking:nt=>{S(bt=>bt+nt),se({sessionId:ke,status:"generating",needsInput:!1,owningTabId:X,type:"subtask",title:_.trim()||void 0,projectId:o??null})},onSubtasks:nt=>{R(!1),E(!1),Dd(o),v(nt),g({type:"editing",sessionId:ke}),q(!1),se({sessionId:ke,status:"awaiting_input",needsInput:!0,owningTabId:X,type:"subtask",title:_.trim()||void 0,projectId:o??null})},onError:nt=>{const bt=nt||"Session failed while contacting the AI.";R(!1),E(!1),A(null),g({type:"error",sessionId:ke,errorMessage:bt}),se({sessionId:ke,status:"error",needsInput:!1,owningTabId:X,type:"subtask",title:_.trim()||void 0,projectId:o??null}),Ve({sessionId:ke,status:"error"})},onComplete:()=>{Ve({sessionId:ke,status:"complete"})},onConnectionStateChange:nt=>{R(nt==="reconnecting")}})},[Ve,se,_,o,X]),vt=i.useCallback(async()=>{if(_.trim()){A(null),y([]),S(""),R(!1);try{const{sessionId:ke}=await w1(_.trim(),o);g({type:"generating",sessionId:ke}),et(ke)}catch(ke){A(Ie(ke)||"Failed to start subtask breakdown"),g({type:"initial"})}}},[et,_,o]);i.useEffect(()=>{if(!e){De();return}if(e&&s&&!fe.current)G(s),fe.current=!0,vt();else if(e&&!s&&!fe.current){const ke=z$(o);ke&&G(ke)}},[e,s,vt,De]),i.useEffect(()=>{!e||!l||p.type!=="initial"||(async()=>{try{const ke=await $i(l);if(!ke)return;const nt=Ar(ke.conversationHistory);if(y(nt),ke.status==="generating"||ke.status==="awaiting_input")S(ke.thinkingOutput??""),g({type:"generating",sessionId:l}),et(l);else if(ke.status==="complete"&&ke.result){Dd(o);const bt=JSON.parse(ke.result);v(bt),g({type:"editing",sessionId:l})}else ke.status==="error"&&(A(null),g({type:"error",sessionId:l,errorMessage:ke.error??"Session encountered an error"}))}catch(ke){A(Ie(ke)||"Failed to resume session")}})()},[et,e,l,p.type,o]),i.useEffect(()=>{if(!e){Q.current&&(ct(Q.current,X),Q.current=null);return}if(F&&Q.current!==F){Q.current&&ct(Q.current,X),Le(F,X),Q.current=F;return}!F&&Q.current&&(ct(Q.current,X),Q.current=null)},[Le,ct,e,F,X]),i.useEffect(()=>{if(!e||!F||Q.current!==F)return;Ke(X);const ke=setInterval(()=>{Ke(X)},3e4);return()=>{clearInterval(ke)}},[Ke,e,F,X]),i.useEffect(()=>()=>{ye.current?.close(),Q.current&&(ct(Q.current,X),Q.current=null)},[ct,X]),i.useEffect(()=>{if(!e)return;const ke=nt=>{nt.key==="Escape"&&(nt.preventDefault(),ht())};return document.addEventListener("keydown",ke),()=>document.removeEventListener("keydown",ke)},[e,ht]);const Oe=i.useCallback((ke,nt)=>{v(bt=>bt.map(kt=>kt.id===ke?{...kt,...nt}:kt)),q(!0)},[]),tt=i.useCallback(()=>{v(ke=>[...ke,G4(ke.length+1)]),q(!0)},[]),ft=i.useCallback(ke=>{v(nt=>nt.filter(bt=>bt.id!==ke).map(bt=>({...bt,dependsOn:bt.dependsOn.filter(kt=>kt!==ke)}))),q(!0)},[]),Mt=i.useCallback(ke=>nt=>{me(ke),nt.dataTransfer.setData("text/plain",ke),nt.dataTransfer.effectAllowed="move"},[]),yt=i.useCallback(()=>{me(null),ve(null),ie(null)},[]),Ge=i.useCallback(ke=>nt=>{if(nt.preventDefault(),ke===de)return;const bt=nt.currentTarget.getBoundingClientRect(),kt=bt.top+bt.height/2,wt=nt.clientY<kt?"before":"after";ve(ke),ie(wt)},[de]),K=i.useCallback(ke=>nt=>{nt.preventDefault();const bt=nt.dataTransfer.getData("text/plain");if(!bt||bt===ke){me(null),ve(null),ie(null);return}v(kt=>{const wt=kt.findIndex(hn=>hn.id===bt),At=kt.findIndex(hn=>hn.id===ke);if(wt===-1||At===-1)return kt;const Ft=[...kt],[ln]=Ft.splice(wt,1);let Vt=At;return Me==="after"&&wt<At&&Vt--,Me==="after"&&Vt++,Ft.splice(Vt,0,ln),Ft}),q(!0),me(null),ve(null),ie(null)},[Me]),ue=i.useCallback(ke=>{const nt=ke.currentTarget.getBoundingClientRect(),bt=ke.clientX,kt=ke.clientY;(bt<nt.left||bt>nt.right||kt<nt.top||kt>nt.bottom)&&(ve(null),ie(null))},[]),ot=i.useCallback((ke,nt)=>{nt<0||nt>=w.length||(v(bt=>{const kt=[...bt],[wt]=kt.splice(ke,1);return kt.splice(nt,0,wt),kt}),q(!0))},[w.length]),xe=i.useCallback(ke=>{Z.current[ke+1]?.focus()},[]),dt=i.useCallback(async()=>{if(!(!F||oe)){A(null),g({type:"creating",sessionId:F});try{const ke=await S1(F,w,r,o,{branchSelection:{mode:Y,...Y==="existing"||Y==="custom-new"?{branchName:L}:{},...$.trim()?{baseBranch:$.trim()}:{}},branchAssignment:{mode:N}});a(ke.tasks),De(),n()}catch(ke){A(Ie(ke)||"Failed to create tasks"),g({type:"editing",sessionId:F})}}},[$,N,Y,L,oe,n,a,r,o,De,F,w]),Je=i.useCallback(async()=>{if(p.type!=="error")return;const ke=p.sessionId;A(null),E(!0),S(""),g({type:"generating",sessionId:ke}),et(ke);try{await k1(ke,o,X)}catch(nt){let bt=nt;if((Ie(nt)||"").includes("not in an error state"))try{const wt=await $i(ke);if(!wt)throw new Error("Failed to refresh subtask session.");if(y(Ar(wt.conversationHistory)),wt.status==="generating"||wt.status==="awaiting_input")S(wt.thinkingOutput??""),g({type:"generating",sessionId:wt.id}),ye.current?.isConnected()||et(wt.id);else if(wt.status==="complete"){if(!wt.result)throw new Error("Subtask session is complete but has no result.");Dd(o);const At=JSON.parse(wt.result);v(At),g({type:"editing",sessionId:wt.id}),q(!1)}else wt.status==="error"&&g({type:"error",sessionId:wt.id,errorMessage:wt.error??"Retry failed. Please try again."});R(!1);return}catch(wt){bt=wt}ye.current?.close(),ye.current=null,g({type:"error",sessionId:ke,errorMessage:Ie(bt)||"Retry failed. Please try again."}),R(!1)}finally{E(!1)}},[et,o,X,p]);return e?t.jsx("div",{className:"modal-overlay open",onClick:ke=>ke.target===ke.currentTarget&&void ht(),role:"dialog","aria-modal":"true",children:t.jsxs("div",{className:"modal modal-lg planning-modal",style:f,children:[t.jsxs("div",{className:"modal-header",children:[t.jsxs("div",{className:"detail-title-row",children:[t.jsx(wc,{size:20,className:"icon-triage"}),t.jsx("h3",{children:"Subtask Breakdown"})]}),t.jsxs("div",{className:"modal-header-actions",children:[Te&&t.jsx("button",{className:"modal-send-to-background",onClick:ut,title:"Send to background","aria-label":"Send to background",children:t.jsx(Vo,{size:16})}),t.jsx("button",{className:"modal-close",onClick:()=>void ht(),"aria-label":"Close",children:t.jsx(bn,{size:20})})]})]}),t.jsxs("div",{className:"planning-modal-body",children:[H&&t.jsx("div",{className:"form-error planning-error",children:H}),k&&t.jsx("div",{className:"form-hint text-muted",children:"Reconnecting…"}),he&&t.jsx("div",{className:"form-hint text-muted","data-testid":"session-active-another-tab-banner",children:"Session is active in another tab."}),p.type==="initial"&&t.jsx("div",{className:"planning-initial",children:t.jsxs("div",{className:"planning-view-scroll",children:[t.jsx("p",{className:"text-muted",children:"Preparing to break this task into subtasks."}),t.jsx("pre",{className:"planning-thinking-output",children:_})]})}),p.type==="generating"&&t.jsxs("div",{className:"planning-loading",children:[b.length>0&&t.jsxs(t.Fragment,{children:[t.jsx(ui,{entries:b,defaultShowThinking:!0}),t.jsx("div",{className:"conversation-separator"})]}),t.jsx(St,{size:40,className:"spin icon-todo"}),t.jsx("p",{children:"AI is generating subtasks..."}),t.jsxs("div",{className:"planning-thinking-container",children:[t.jsx("button",{className:"planning-thinking-toggle",onClick:()=>x(!C),type:"button",children:C?"Hide thinking":"Show thinking"}),C&&j&&t.jsx("div",{className:"planning-thinking-output",children:t.jsx("pre",{children:j})})]})]}),p.type==="error"&&t.jsx("div",{className:"planning-summary",children:t.jsxs("div",{className:"planning-view-scroll planning-summary-scroll",children:[b.length>0&&t.jsxs(t.Fragment,{children:[t.jsx(ui,{entries:b,defaultShowThinking:!0}),t.jsx("div",{className:"conversation-separator"})]}),t.jsxs("div",{className:"ai-error-panel",role:"alert",children:[t.jsx("div",{className:"ai-error-icon",children:"⚠️"}),t.jsx("div",{className:"ai-error-message",children:p.errorMessage}),t.jsxs("div",{className:"ai-error-actions",children:[t.jsxs("button",{className:"btn btn-primary",onClick:()=>void Je(),disabled:O,children:[O?t.jsx(St,{size:14,className:"spin"}):t.jsx(us,{size:14}),t.jsx("span",{className:"icon-ml-6",children:O?"Retrying...":"Retry"})]}),t.jsx("button",{className:"btn",onClick:()=>void ht(),disabled:O,children:"Cancel"})]})]})]})}),(p.type==="editing"||p.type==="creating")&&t.jsxs("div",{className:"planning-summary",children:[t.jsxs("div",{className:"planning-view-scroll planning-summary-scroll",children:[b.length>0&&t.jsxs(t.Fragment,{children:[t.jsx(ui,{entries:b}),t.jsx("div",{className:"conversation-separator"})]}),t.jsxs("div",{className:"planning-summary-header",children:[t.jsx(Zn,{size:24,className:"icon-success"}),t.jsx("h4",{children:"Review your subtasks"}),t.jsx("p",{className:"text-muted",children:"Edit titles, descriptions, sizes, and dependencies before creating all tasks at once."})]}),t.jsxs("div",{className:"planning-summary-form",children:[t.jsxs("div",{className:"task-detail-section",children:[t.jsxs("div",{className:"form-group",children:[t.jsx("label",{children:"Branch strategy"}),t.jsxs("select",{value:Y,onChange:ke=>ge(ke.target.value),disabled:p.type==="creating",children:[t.jsx("option",{value:"project-default",children:"Use project/default branch"}),t.jsx("option",{value:"auto-new",children:"Create auto-named branch per task"}),t.jsx("option",{value:"existing",children:"Use existing branch"}),t.jsx("option",{value:"custom-new",children:"Create custom new branch"})]})]}),(Y==="existing"||Y==="custom-new")&&t.jsxs("div",{className:"form-group",children:[t.jsx("label",{children:"Branch name"}),t.jsx("input",{value:L,onChange:ke=>M(ke.target.value),disabled:p.type==="creating"})]}),t.jsxs("div",{className:"form-group",children:[t.jsx("label",{children:"Merge target / base branch (optional)"}),t.jsx("input",{value:$,onChange:ke=>D(ke.target.value),disabled:p.type==="creating",placeholder:"main"})]}),t.jsxs("div",{className:"form-group",children:[t.jsx("label",{children:"Planning branch mode"}),t.jsxs("select",{value:N,onChange:ke=>W(ke.target.value),disabled:p.type==="creating",children:[t.jsx("option",{value:"shared",children:"Shared branch for all subtasks"}),t.jsx("option",{value:"per-task-derived",children:"Per-task branch derived from planning branch"})]})]})]}),w.map((ke,nt)=>{const bt=de===ke.id,kt=Ne===ke.id,wt=["task-detail-section","subtask-item",bt?"subtask-item-dragging":"",kt?"subtask-item-drop-target":"",kt&&Me==="before"?"subtask-item-drop-before":"",kt&&Me==="after"?"subtask-item-drop-after":""].filter(Boolean).join(" ");return t.jsxs("div",{className:wt,"data-testid":`subtask-item-${nt}`,draggable:p.type!=="creating",onDragStart:Mt(ke.id),onDragEnd:yt,onDragOver:Ge(ke.id),onDrop:K(ke.id),onDragLeave:ue,children:[t.jsxs("div",{className:"detail-title-row subtask-item-header subtask-item-header--between",children:[t.jsxs("div",{className:"subtask-drag-handle",title:"Drag to reorder",children:[t.jsx(yc,{size:16}),t.jsx("strong",{children:ke.id})]}),t.jsxs("div",{className:"subtask-item-actions",children:[t.jsx("button",{type:"button",className:"btn btn-icon btn-sm",onClick:()=>ot(nt,nt-1),disabled:p.type==="creating"||nt===0,title:"Move up","aria-label":"Move subtask up",children:t.jsx(La,{})}),t.jsx("button",{type:"button",className:"btn btn-icon btn-sm",onClick:()=>ot(nt,nt+1),disabled:p.type==="creating"||nt===w.length-1,title:"Move down","aria-label":"Move subtask down",children:t.jsx(Uo,{})}),t.jsxs("button",{type:"button",className:"btn btn-sm",onClick:()=>ft(ke.id),disabled:p.type==="creating",children:[t.jsx(In,{size:14})," Remove"]})]})]}),t.jsxs("div",{className:"form-group",children:[t.jsx("label",{children:"Title"}),t.jsx("input",{ref:At=>{Z.current[nt]=At},value:ke.title,onChange:At=>Oe(ke.id,{title:At.target.value}),onKeyDown:At=>{At.key==="Enter"&&(At.preventDefault(),xe(nt))},disabled:p.type==="creating"})]}),t.jsxs("div",{className:"form-group",children:[t.jsx("label",{children:"Description"}),t.jsx("textarea",{rows:8,value:ke.description,onChange:At=>Oe(ke.id,{description:At.target.value}),disabled:p.type==="creating"})]}),t.jsxs("div",{className:"form-group",children:[t.jsx("label",{children:"Size"}),t.jsxs("select",{className:"planning-size-select",value:ke.suggestedSize,onChange:At=>Oe(ke.id,{suggestedSize:At.target.value}),disabled:p.type==="creating",children:[t.jsx("option",{value:"S",children:"S"}),t.jsx("option",{value:"M",children:"M"}),t.jsx("option",{value:"L",children:"L"})]})]}),t.jsxs("div",{className:"form-group",children:[t.jsx("label",{children:"Dependencies"}),t.jsxs("div",{className:"planning-deps-list",children:[w.slice(0,nt).filter(At=>At.id!==ke.id).map(At=>{const Ft=ke.dependsOn.includes(At.id);return t.jsxs("label",{className:`planning-dep-chip ${Ft?"selected":""}`,children:[t.jsx("input",{type:"checkbox",checked:Ft,onChange:()=>{const ln=Ft?ke.dependsOn.filter(Vt=>Vt!==At.id):[...ke.dependsOn,At.id];Oe(ke.id,{dependsOn:ln})},disabled:p.type==="creating"}),t.jsx("span",{className:"planning-dep-id",children:At.id}),t.jsx("span",{className:"planning-dep-title",children:At.title||"Untitled"})]},At.id)}),nt===0&&t.jsx("div",{className:"text-muted",children:"First subtask cannot have dependencies."}),nt>0&&w.slice(0,nt).filter(At=>At.id!==ke.id).length===0&&t.jsx("div",{className:"text-muted",children:"No previous subtasks available."})]})]})]},ke.id)}),t.jsxs("button",{type:"button",className:"btn",onClick:tt,disabled:p.type==="creating",children:[t.jsx(Tn,{size:16,className:"icon-mr-6"})," Add subtask"]}),Wf(w)&&t.jsx("div",{className:"form-error planning-error",children:"Dependencies contain a cycle. Remove circular references before creating tasks."})]})]}),t.jsxs("div",{className:"planning-actions planning-summary-actions",children:[t.jsx("button",{className:"btn",onClick:()=>void ht(),disabled:p.type==="creating",children:"Cancel"}),t.jsx("button",{className:"btn btn-primary",onClick:()=>void dt(),disabled:p.type==="creating"||oe,children:p.type==="creating"?t.jsxs(t.Fragment,{children:[t.jsx(St,{size:16,className:"spin icon-mr-6"}),"Creating..."]}):t.jsx(t.Fragment,{children:"Create Tasks"})})]})]}),re&&t.jsx("div",{className:"session-lock-overlay","data-testid":"session-lock-overlay",children:t.jsxs("div",{className:"session-lock-banner",children:[t.jsx(kc,{size:16}),t.jsx("span",{children:pe?"This session is active in another tab":"This session is active in another tab (live heartbeat)"}),pe&&t.jsx("button",{type:"button",onClick:()=>{U()},disabled:be,className:"btn btn-primary session-lock-take-control",children:be?"Taking control...":"Take Control"})]})})]})]})}):null}const J4=5,Y4=1e3,Q4=45e3;function Tl(){return{scrollback:null,connected:null,data:[]}}function X4(e,n){const[s,a]=i.useState("disconnected"),r=i.useRef(0),o=i.useRef(e),l=i.useRef(n),c=o.current!==e||l.current!==n;c&&(o.current=e,l.current=n,r.current++);const d=i.useRef(null),u=i.useRef(0),h=i.useRef(null),m=i.useRef(null),f=i.useRef(!1),p=i.useRef(new Set),g=i.useRef(new Set),w=i.useRef(new Set),v=i.useRef(new Set),b=i.useRef(new Set),y=i.useRef(Tl()),j=i.useCallback(A=>{p.current.add(A);const P=y.current;return P.data.length>0&&(P.data.forEach(q=>A(q)),P.data=[]),()=>p.current.delete(A)},[]),S=i.useCallback(A=>(g.current.add(A),()=>g.current.delete(A)),[]),C=i.useCallback(A=>{w.current.add(A);const P=y.current;return P.connected&&(A(P.connected),P.connected=null),()=>w.current.delete(A)},[]),x=i.useCallback(A=>{v.current.add(A);const P=y.current;return P.scrollback&&(A(P.scrollback),P.scrollback=null),()=>v.current.delete(A)},[]),k=i.useCallback(A=>(b.current.add(A),()=>b.current.delete(A)),[]),R=i.useCallback(A=>{const P=d.current;P?.readyState===WebSocket.OPEN&&P.send(JSON.stringify({type:"input",data:A}))},[]),O=i.useCallback((A,P)=>{const q=d.current;q?.readyState===WebSocket.OPEN&&q.send(JSON.stringify({type:"resize",cols:A,rows:P}))},[]),E=i.useCallback(()=>{h.current&&(clearTimeout(h.current),h.current=null),m.current&&(clearInterval(m.current),m.current=null),d.current&&(d.current.onopen=null,d.current.onmessage=null,d.current.onclose=null,d.current.onerror=null,d.current.close(),d.current=null),y.current=Tl()},[]),_=i.useCallback(()=>{h.current&&(clearTimeout(h.current),h.current=null),m.current&&(clearInterval(m.current),m.current=null),d.current&&(f.current=!0,d.current.onopen=null,d.current.onmessage=null,d.current.onclose=null,d.current.onerror=null,d.current.close(),d.current=null),y.current=Tl()},[]),G=i.useCallback(()=>{if(!e){a("disconnected");return}if(d.current?.readyState===WebSocket.OPEN)return;d.current&&(f.current=!0,d.current.onopen=null,d.current.onmessage=null,d.current.onclose=null,d.current.onerror=null,d.current.close(),d.current=null),f.current=!1,a("connecting");const A=r.current;let q=`${window.location.protocol==="https:"?"wss:":"ws:"}//${window.location.host}/api/terminal/ws?sessionId=${encodeURIComponent(e)}`;n&&(q+=`&projectId=${encodeURIComponent(n)}`);const Y=new WebSocket(Li(q));d.current=Y,Y.onopen=()=>{if(r.current!==A){Y.close();return}y.current=Tl(),a("connected"),u.current=0,m.current&&clearInterval(m.current),m.current=setInterval(()=>{r.current===A&&Y.readyState===WebSocket.OPEN&&Y.send(JSON.stringify({type:"ping"}))},Q4)},Y.onmessage=ge=>{if(r.current===A)try{const L=JSON.parse(ge.data),M=y.current;switch(L.type){case"data":L.data&&(p.current.size===0&&M.data.push(L.data),p.current.forEach($=>$(L.data)));break;case"scrollback":L.data&&(M.scrollback=L.data,v.current.forEach($=>$(L.data)));break;case"connected":L.shell&&L.cwd&&(M.connected={shell:L.shell,cwd:L.cwd},w.current.forEach($=>$({shell:L.shell,cwd:L.cwd})));break;case"exit":L.exitCode!==void 0&&g.current.forEach($=>$(L.exitCode));break;case"ping":Y.readyState===WebSocket.OPEN&&Y.send(JSON.stringify({type:"pong"}));break;case"pong":break}}catch{}},Y.onclose=ge=>{if(r.current!==A)return;if(d.current=null,m.current&&(clearInterval(m.current),m.current=null),f.current){a("disconnected");return}if(ge.code===4e3||ge.code===4004){a("disconnected"),ge.code===4004&&b.current.forEach($=>$());return}if(u.current++,u.current>J4){a("disconnected");return}const L=Y4*Math.pow(2,u.current-1);a("reconnecting");const M=r.current;h.current=setTimeout(()=>{r.current===M&&(f.current||G())},Math.min(L,16e3))},Y.onerror=()=>{}},[e,n]),H=i.useCallback(()=>{u.current=0,_(),G()},[_,G]);return i.useEffect(()=>(c&&(E(),u.current=0,a("disconnected")),e?G():a("disconnected"),_),[e,n,c,G,_,E]),{connectionStatus:s,sendInput:R,resize:O,onData:j,onExit:S,onConnect:C,onScrollback:x,reconnect:H,onSessionInvalid:k}}const Fv="kb-terminal-tabs",Z4=15e3,eD=15e3;function Gf(){return`tab-${Date.now()}-${Math.random().toString(36).substring(2,9)}`}function Kf(e){if(typeof window>"u")return[];try{const n=Ln(Fv,e);if(n)return JSON.parse(n)}catch{}return[]}function Vd(e){const n=e instanceof Error?e.message:typeof e=="string"?e:"";return n.includes("Failed to parse URL")||n.includes("Invalid URL")}function Jf(e,n,s){let a;const r=new Promise((o,l)=>{a=setTimeout(()=>l(new Error(`${s} timed out after ${n}ms`)),n)});return Promise.race([e,r]).finally(()=>clearTimeout(a))}function tD(e){const[n,s]=i.useState(()=>Kf(e)),[a,r]=i.useState(!1),[o,l]=i.useState(!0),[c,d]=i.useState(null),[u,h]=i.useState(0),m=i.useRef(0);i.useEffect(()=>{m.current+=1,s(Kf(e)),r(!1),l(!0),d(null)},[e]),i.useEffect(()=>{try{rs(Fv,JSON.stringify(n),e)}catch{}},[e,n]),i.useEffect(()=>{let C=!1;const x=m.current;return(async()=>{if(!C)try{const R=await Jf(pS(e),Z4,"listTerminalSessions");if(C||x!==m.current)return;const O=new Set(R.map(E=>E.id));l(!0),s(E=>{if(C||x!==m.current)return E;const G=E.map(P=>({...P,_verified:O.has(P.sessionId)})).filter(P=>P._verified);if(G.length===0)return[];const H=G.map(({_verified:P,...q})=>q);return H.find(P=>P.isActive)?H:H.map((P,q)=>({...P,isActive:q===0}))}),r(!0)}catch(R){if(C||x!==m.current)return;const O=Vd(R);O||console.warn("Failed to validate terminal sessions with server:",R),l(!O),r(!0)}})(),()=>{C=!0}},[e]),i.useEffect(()=>{if(n.length===0&&a&&o){const C=m.current,x=setTimeout(()=>{Jf(rl(void 0,void 0,void 0,e),eD,"createTerminalSession").then(k=>{if(C!==m.current)return;const R={id:Gf(),sessionId:k.sessionId,title:`Terminal ${n.length+1}`,isActive:!0,createdAt:Date.now()};s(O=>O.length>0?O:[...O.map(_=>({..._,isActive:!1})),R]),d(null)}).catch(k=>{if(C!==m.current)return;Vd(k)||console.error(k);const R=k instanceof Error?k.message:typeof k=="string"?k:"Failed to create terminal session";d(R)})},0);return()=>clearTimeout(x)}},[a,o,n.length,u]);const f=i.useCallback(async()=>{const C=await rl(void 0,void 0,void 0,e),x={id:Gf(),sessionId:C.sessionId,title:`Terminal ${n.length+1}`,isActive:!0,createdAt:Date.now()};return s(k=>[...k.map(O=>({...O,isActive:!1})),x]),x},[n.length]),p=i.useCallback(async()=>f(),[f]),g=i.useCallback(C=>{s(x=>{const k=x.find(_=>_.id===C);if(!k)return x;Qm(k.sessionId,e).catch(_=>{console.warn(`Failed to kill terminal session ${k.sessionId}:`,_)});const R=x.findIndex(_=>_.id===C),O=k.isActive,E=x.filter(_=>_.id!==C);if(E.length===0)return[];if(O){const _=Math.min(R,E.length-1);return E.map((G,H)=>({...G,isActive:H===_}))}return E})},[]),w=i.useCallback(C=>{s(x=>{let k=!1;const R=x.map(O=>O.id===C?(k=!0,{...O,isActive:!0}):{...O,isActive:!1});return k?R:x})},[]),v=i.useCallback((C,x)=>{s(k=>k.map(R=>R.id===C?{...R,title:x}:R))},[]),b=i.useCallback(async()=>{s(k=>{const R=k.find(O=>O.isActive);return R&&Qm(R.sessionId,e).catch(O=>{console.warn(`Failed to kill old session ${R.sessionId}:`,O)}),k});const C=n.find(k=>k.isActive);if(!C)return;const x=await rl(void 0,void 0,void 0,e);s(k=>k.map(R=>R.id===C.id?{...R,sessionId:x.sessionId}:R))},[n]),y=i.useCallback(async()=>{const C=n.find(x=>x.isActive);if(C)try{const x=await rl(void 0,void 0,void 0,e);s(k=>k.map(R=>R.id===C.id?{...R,sessionId:x.sessionId}:R)),d(null)}catch(x){Vd(x)||console.error(x);const k=x instanceof Error?x.message:typeof x=="string"?x:"Failed to create terminal session";d(k)}},[n]),j=n.find(C=>C.isActive)??null,S=i.useCallback(()=>{d(null),m.current+=1,h(C=>C+1)},[]);return{tabs:n,activeTab:j,isReady:a,bootstrapError:c,createTab:p,closeTab:g,setActiveTab:w,updateTabTitle:v,restartActiveTab:b,retryBootstrap:S,replaceActiveTabSession:y}}const nD=1e4,sD=[500,1500,3e3],zv="kb-terminal-font-size",So=14,iD=8,aD=32,rD='"Fusion Terminal Nerd Font Symbols", "MesloLGS NF", "MesloLGM Nerd Font", "JetBrainsMono Nerd Font", "FiraCode Nerd Font", "Hack Nerd Font", ui-monospace, SFMono-Regular, "SF Mono", Menlo, Consolas, monospace';function oD(e){if(!e)return"";const n=e.slice(0,1).toUpperCase();return n==="["?"\x1B":n>="A"&&n<="Z"?String.fromCharCode(n.charCodeAt(0)-64):e}function lD(e){return`\x1B${e}`}const cD=[{label:"C",key:"c",description:"SigInt"},{label:"D",key:"d",description:"EOF"},{label:"Z",key:"z",description:"Suspend"},{label:"L",key:"l",description:"Clear"},{label:"R",key:"r",description:"Reverse search"},{label:"A",key:"a",description:"Home"},{label:"E",key:"e",description:"End"},{label:"U",key:"u",description:"Kill line"},{label:"K",key:"k",description:"Kill to EOL"},{label:"W",key:"w",description:"Del word"},{label:".",key:".",description:"Last argument"}];function Co(e){return Math.min(aD,Math.max(iD,e))}function dD(){if(typeof window>"u")return So;try{const e=window.localStorage.getItem(zv);if(!e)return So;const n=Number.parseInt(e,10);return Number.isFinite(n)?Co(n):So}catch{return So}}function uD(e){const n=typeof e=="string"?e:e instanceof Error?e.message:String(e);return n.includes("MIME type")||n.includes("Failed to fetch dynamically imported module")}function mD(e){return new Promise(n=>setTimeout(n,e))}async function hD(e,n=sD){let s;for(let a=0;a<=n.length;a+=1)try{return await e()}catch(r){if(!uD(r))throw r;s===void 0&&(s=r);const o=n[a];if(o===void 0)throw s??r;const l=r instanceof Error?r.message:String(r);console.warn(`[TerminalModal] Dynamic xterm import failed (attempt ${a+1}/${n.length+1}). Retrying in ${o}ms...`,l),await mD(o)}throw s??new Error("Dynamic import failed")}function Yf(){if(typeof window>"u")return!1;const e="ontouchstart"in window||navigator.maxTouchPoints>0,n=window.innerWidth<=768;return e&&n}function pD(){if(typeof window>"u"||!window.visualViewport)return 0;const e=window.visualViewport,n=Math.max(0,window.innerHeight-e.offsetTop-e.height);if(n>0)return n;const a=fD()-e.offsetTop-e.height;return a>=30&&a>80?a:0}let Wd=null;function fD(){return Wd===null&&(Wd=window.innerHeight),Wd}function gD({isOpen:e,onClose:n,initialCommand:s,projectId:a}){const[r,o]=i.useState(null),[l,c]=i.useState(null),[d,u]=i.useState(!1),[h,m]=i.useState(null),[f,p]=i.useState(0),[g,w]=i.useState(0),[v,b]=i.useState(null),[y,j]=i.useState(()=>dD()),[S,C]=i.useState(!1),[x,k]=i.useState(null),R=i.useRef(null),O=i.useRef(null),E=i.useRef(!1);Oi(O,e,"fusion:terminal-modal-size");const _=i.useRef(null),G=i.useRef(null),H=i.useRef(!1),A=i.useRef(!1),P=i.useRef(null),q=i.useRef(()=>{}),Y=i.useRef(null),ge=i.useRef(0),L=i.useRef(y),M=i.useRef(null),$=i.useRef(a);ge.current=g,L.current=y;const D=i.useCallback(Oe=>{if(Oe&&A.current!==Oe)return;const tt=G.current,ft=_.current,Mt=P.current;if(!(!tt||!ft)&&!(Oe&&A.current!==Oe))try{tt.fit(),Mt&&Mt(ft.cols,ft.rows)}catch{}},[]);i.useEffect(()=>{e&&p(Oe=>Oe+1)},[e]),i.useEffect(()=>{if(!e||!Yf())return;const Oe=window.visualViewport;if(!Oe)return;const tt=()=>{const ft=pD();w(ft),b(Oe.height),ft>0&&O.current?.scrollIntoView&&O.current.scrollIntoView({block:"end",behavior:"smooth"}),M.current!==null&&(cancelAnimationFrame(M.current),M.current=null);const Mt=typeof A.current=="string"?A.current:void 0;M.current=requestAnimationFrame(()=>{M.current=null,D(Mt)})};return tt(),Oe.addEventListener("resize",tt),Oe.addEventListener("scroll",tt),()=>{Oe.removeEventListener("resize",tt),Oe.removeEventListener("scroll",tt),M.current!==null&&(cancelAnimationFrame(M.current),M.current=null),w(0),b(null)}},[D,e]),i.useEffect(()=>{if(!e)return;const Oe=O.current;if(!Oe||typeof ResizeObserver>"u")return;let tt=null;const ft=new ResizeObserver(()=>{tt!==null&&cancelAnimationFrame(tt),tt=requestAnimationFrame(()=>{tt=null;const Mt=typeof A.current=="string"?A.current:void 0;D(Mt)})});return ft.observe(Oe),()=>{ft.disconnect(),tt!==null&&cancelAnimationFrame(tt)}},[D,e]);const{tabs:N,activeTab:W,isReady:de,bootstrapError:me,createTab:Ne,closeTab:ve,setActiveTab:Me,updateTabTitle:ie,restartActiveTab:ye,retryBootstrap:Z,replaceActiveTabSession:fe}=tD(a),{connectionStatus:Q,sendInput:F,resize:X,onData:re,onConnect:U,onExit:be,onScrollback:Ue,reconnect:se,onSessionInvalid:Ve}=X4(W?.sessionId??null,a);P.current=X,q.current=F,i.useEffect(()=>{if(!(typeof window>"u"))try{window.localStorage.setItem(zv,String(y))}catch{}},[y]);const Le=i.useCallback(()=>{const Oe=_.current;if(Oe)try{G.current?.fit(),X(Oe.cols,Oe.rows)}catch{}},[X]);i.useEffect(()=>{if(!e||!de)return;const Oe=W?.sessionId;if(!Oe)return;const tt=$.current!==a;if(tt&&($.current=a),A.current===Oe&&_.current&&!tt)return;_.current&&(A.current!==Oe||tt)&&(_.current.dispose(),_.current=null,G.current=null,A.current=!1,Y.current&&(window.removeEventListener("resize",Y.current),Y.current=null),u(!1),m(null));let ft=!0,Mt;return(async()=>{const Ge=hD(()=>Promise.all([Sn(()=>import("./vendor-xterm-DzcZoU0P.js").then(xe=>xe.x),__vite__mapDeps([5,1,6])),Sn(()=>import("./addon-fit-C7jRorKK.js").then(xe=>xe.a),__vite__mapDeps([8,1])),Sn(()=>import("./addon-web-links-CkJwd4cQ.js").then(xe=>xe.a),__vite__mapDeps([9,1]))])),K=new Promise((xe,dt)=>{Mt=setTimeout(()=>{dt(new Error("xterm initialization timed out"))},nD)});let ue,ot;try{const[{Terminal:xe},{FitAddon:dt},{WebLinksAddon:Je}]=await Promise.race([Ge,K]);if(!ft||!R.current||_.current)return;ue=new xe({cursorBlink:!0,cursorStyle:"block",fontSize:L.current,fontFamily:rD,theme:{background:"#1e1e1e",foreground:"#d4d4d4",cursor:"#d4d4d4",selectionBackground:"#264f78",black:"#1e1e1e",red:"#f48771",green:"#4ec9b0",yellow:"#dcdcaa",blue:"#569cd6",magenta:"#c586c0",cyan:"#9cdcfe",white:"#d4d4d4"},allowProposedApi:!0,scrollback:5e3}),ot=new dt,ue.loadAddon(ot);const ke=new Je;if(ue.loadAddon(ke),!Yf())try{const{WebglAddon:kt}=await Sn(async()=>{const{WebglAddon:At}=await import("./addon-webgl-BjvOw43o.js").then(Ft=>Ft.a);return{WebglAddon:At}},__vite__mapDeps([10,1])),wt=new kt;wt.onContextLoss(()=>{wt.dispose()}),ue.loadAddon(wt)}catch{}ue.open(R.current),Mt&&clearTimeout(Mt);const nt=R.current?.querySelector(".xterm-helper-textarea");if(nt&&nt.focus(),R.current)try{R.current.dispatchEvent(new MouseEvent("click",{bubbles:!0,cancelable:!0}))}catch{}setTimeout(()=>{ot.fit();const kt=R.current?.querySelector(".xterm-helper-textarea");kt&&kt.focus()},50),_.current=ue,G.current=ot,A.current=Oe,ge.current>0&&(M.current!==null&&(cancelAnimationFrame(M.current),M.current=null),M.current=requestAnimationFrame(()=>{M.current=null,D(Oe)})),ue.onData(kt=>{A.current===Oe&&q.current(kt)});const bt=()=>{if(A.current===Oe&&G.current&&_.current)try{G.current.fit();const{cols:kt,rows:wt}=_.current;P.current?.(kt,wt)}catch{}};window.addEventListener("resize",bt),Y.current&&window.removeEventListener("resize",Y.current),Y.current=bt,u(!0),m(null)}catch(xe){if(Mt&&clearTimeout(Mt),!ft)return;const dt=xe instanceof Error?xe.message:"xterm initialization failed";m(dt)}})(),()=>{ft=!1,Mt&&clearTimeout(Mt)}},[D,e,de,W?.sessionId,a]),i.useEffect(()=>{e||(_.current&&(_.current.dispose(),_.current=null),G.current=null,A.current=!1,Y.current&&(window.removeEventListener("resize",Y.current),Y.current=null),u(!1),m(null),H.current=!1,o(null),c(null),C(!1),k(null))},[e]),i.useEffect(()=>{if(!d||!_.current||!W)return;const Oe=W.sessionId,tt=K=>{A.current===Oe&&_.current?.write(K)},ft=re(K=>{tt(K)}),Mt=Ue(K=>{tt(K)}),yt=U(K=>{ie(W.id,tm(K.shell)||K.shell)}),Ge=be(K=>{A.current===Oe&&(c(K),_.current?.write(`\r
691
- \x1B[33m[Process exited with code ${K}]\x1B[0m\r
692
- `))});return()=>{ft(),Mt(),yt(),Ge()}},[d,W?.sessionId,W?.id,W,Q,re,Ue,U,be,ie]),i.useEffect(()=>{Q==="connected"&&s&&H.current!==s&&W&&(H.current=s,setTimeout(()=>{F(s+`
693
- `)},500))},[Q,s,F,W,f]),i.useEffect(()=>{if(!d||!_.current)return;_.current.options.fontSize=y,M.current!==null&&(cancelAnimationFrame(M.current),M.current=null);const Oe=requestAnimationFrame(()=>{M.current=null,Le()});return M.current=Oe,()=>{M.current===Oe&&(cancelAnimationFrame(Oe),M.current=null)}},[y,d,Le]),i.useEffect(()=>{if(!e)return;const Oe=tt=>{if(!(!tt.ctrlKey&&!tt.metaKey)){if(tt.code==="Equal"||tt.code==="NumpadAdd"){tt.preventDefault(),j(ft=>Co(ft+1));return}if(tt.code==="Minus"||tt.code==="NumpadSubtract"){tt.preventDefault(),j(ft=>Co(ft-1));return}if(tt.code==="Digit0"||tt.code==="Numpad0"){tt.preventDefault(),j(So);return}}};return window.addEventListener("keydown",Oe),()=>window.removeEventListener("keydown",Oe)},[e,Le]),i.useEffect(()=>{if(!e)return;const Oe=tt=>{tt.key==="Escape"&&n()};return document.addEventListener("keydown",Oe),()=>document.removeEventListener("keydown",Oe)},[e,n]),i.useEffect(()=>{Q==="connected"&&_.current&&setTimeout(()=>{if(!_.current||!R.current)return;const Oe=R.current.querySelector(".xterm-helper-textarea");Oe&&Oe.focus();try{R.current.dispatchEvent(new MouseEvent("click",{bubbles:!0,cancelable:!0}))}catch{}},100)},[Q]);const ct=i.useCallback(()=>{if(!R.current||typeof window<"u"&&typeof window.matchMedia=="function"&&window.matchMedia("(hover: none) and (pointer: coarse)")?.matches===!0)return;_.current?.focus();const tt=R.current.querySelector(".xterm-helper-textarea");if(!tt)return;tt.autocapitalize="off",tt.autocomplete="off",tt.autocorrect="off",tt.spellcheck=!1,tt.setAttribute("inputmode","text");try{tt.focus({preventScroll:!0})}catch{tt.focus()}const ft=tt.value.length;tt.setSelectionRange(ft,ft)},[]);i.useEffect(()=>Ve(()=>{_.current?.clear(),c(null),H.current=!1,_.current&&(_.current.dispose(),_.current=null),G.current=null,A.current=!1,Y.current&&(window.removeEventListener("resize",Y.current),Y.current=null),u(!1),m(null),fe().catch(tt=>{console.error("Failed to replace invalid terminal session:",tt)})}),[Ve,fe]);const Ke=i.useCallback(Oe=>{Oe.target===Oe.currentTarget&&(E.current=!0)},[]),oe=i.useCallback(Oe=>{E.current&&Oe.target===Oe.currentTarget&&n(),E.current=!1},[n]),Te=i.useCallback(()=>{_.current?.clear()},[]),Fe=i.useCallback(async()=>{_.current?.clear(),c(null),H.current=!1;try{await ye()}catch(Oe){o(Ie(Oe)||"Failed to restart terminal session")}},[ye]),mt=i.useCallback(()=>{_.current&&(_.current.dispose(),_.current=null),G.current=null,A.current=!1,Y.current&&(window.removeEventListener("resize",Y.current),Y.current=null),m(null),u(!1)},[]),We=i.useCallback(()=>{window.location.reload()},[]),he=i.useCallback(()=>{j(Oe=>Co(Oe+1))},[]),pe=i.useCallback(()=>{j(Oe=>Co(Oe-1))},[]),De=i.useCallback(Oe=>{k(tt=>tt===Oe?null:Oe)},[]),ut=i.useCallback(Oe=>{if(x==="ctrl"){F(oD(Oe)),k(null);return}if(x==="alt"){F(lD(Oe)),k(null);return}F(Oe)},[F,x]),ht=i.useCallback(Oe=>{F(Oe),k(null)},[F]);if(!e)return null;const et=()=>{switch(Q){case"connected":return t.jsx("span",{className:"terminal-status connected",title:"Connected"});case"connecting":case"reconnecting":return t.jsx("span",{className:"terminal-status connecting",title:"Connecting..."});case"disconnected":return t.jsx("span",{className:"terminal-status disconnected",title:"Disconnected"});default:return null}},vt=!de||!W&&!me;return t.jsx("div",{className:"modal-overlay open",onMouseDown:Ke,onMouseUp:oe,role:"dialog","aria-modal":"true","data-testid":"terminal-modal-overlay",style:g>0?{"--overlay-padding-top":"0px"}:void 0,children:t.jsxs("div",{ref:O,className:"modal terminal-modal","data-testid":"terminal-modal",style:g>0?{"--keyboard-overlap":`${g}px`,"--vv-height":v?`${v}px`:void 0}:void 0,children:[t.jsxs("div",{className:"terminal-header",children:[t.jsxs("div",{className:"terminal-tabs","data-testid":"terminal-tabs",children:[N.map(Oe=>t.jsxs("div",{className:`terminal-tab ${Oe.isActive?"terminal-tab--active":""}`,onClick:()=>Me(Oe.id),title:Oe.title,role:"tab","aria-selected":Oe.isActive,children:[t.jsx("span",{className:"terminal-tab-label",children:Oe.title}),N.length>1&&t.jsx("button",{className:"terminal-tab-close",onClick:tt=>{tt.stopPropagation(),ve(Oe.id)},title:"Close tab",children:"×"})]},Oe.id)),t.jsx("button",{className:"terminal-tab terminal-tab--new",onClick:Ne,title:"New terminal",children:"+"})]}),t.jsxs("div",{className:"terminal-title","data-testid":"terminal-title",children:[t.jsx(Ji,{size:16}),et()]}),t.jsxs("div",{className:"terminal-actions","data-testid":"terminal-actions",children:[Q==="disconnected"&&W&&t.jsxs("button",{className:"terminal-reconnect-btn",onClick:se,title:"Reconnect","data-testid":"terminal-reconnect-btn",children:[t.jsx(us,{size:14}),t.jsx("span",{className:"terminal-action-label",children:"Reconnect"})]}),l!==null&&t.jsxs("button",{className:"terminal-restart-btn",onClick:Fe,title:"New Session","data-testid":"terminal-restart-btn",children:[t.jsx(us,{size:14}),t.jsx("span",{className:"terminal-action-label",children:"New Session"})]}),t.jsxs("button",{className:"terminal-clear-btn",onClick:Te,"data-testid":"terminal-clear-btn",title:"Clear terminal",children:[t.jsx(In,{size:14}),t.jsx("span",{className:"terminal-action-label",children:"Clear"})]}),t.jsxs("button",{className:"terminal-clear-btn terminal-clear-btn--shortcut",onClick:()=>C(Oe=>!Oe),"data-testid":"terminal-shortcut-toggle",title:"Shortcuts","aria-pressed":S,children:[t.jsx(ck,{size:14}),t.jsx("span",{className:"terminal-action-label",children:"Shortcuts"})]}),t.jsx("button",{className:"terminal-close",onClick:n,"data-testid":"terminal-close-btn",title:"Close terminal",children:t.jsx(bn,{size:20})})]})]}),r&&t.jsx("div",{className:"terminal-error","data-testid":"terminal-error",children:r}),t.jsxs("div",{className:"terminal-container","data-testid":"terminal-container",children:[vt&&!me&&t.jsxs("div",{className:"terminal-loading","data-testid":"terminal-loading",children:[t.jsx("div",{className:"terminal-spinner"}),t.jsx("span",{children:"Starting terminal..."})]}),me&&!W&&t.jsx("div",{className:"terminal-loading","data-testid":"terminal-bootstrap-error",children:t.jsxs("div",{className:"terminal-error-content",children:[t.jsxs("span",{children:["Failed to start terminal: ",me]}),t.jsxs("div",{className:"terminal-error-actions",children:[t.jsxs("button",{className:"terminal-retry-btn",onClick:Z,"data-testid":"terminal-retry-btn",children:[t.jsx(us,{size:14}),"Retry"]}),t.jsxs("button",{className:"terminal-retry-btn",onClick:We,"data-testid":"terminal-bootstrap-refresh-btn",children:[t.jsx(us,{size:14}),"Refresh page"]})]})]})}),h&&W&&t.jsx("div",{className:"terminal-loading","data-testid":"terminal-xterm-init-error",children:t.jsxs("div",{className:"terminal-error-content",children:[t.jsxs("span",{children:["Terminal UI failed to initialize: ",h]}),t.jsxs("div",{className:"terminal-error-actions",children:[t.jsxs("button",{className:"terminal-retry-btn",onClick:mt,"data-testid":"terminal-reinit-btn",children:[t.jsx(us,{size:14}),"Reinitialize"]}),t.jsxs("button",{className:"terminal-retry-btn",onClick:We,"data-testid":"terminal-xterm-refresh-btn",children:[t.jsx(us,{size:14}),"Refresh page"]})]})]})}),t.jsx("div",{ref:R,className:"terminal-xterm","data-testid":"terminal-xterm",onPointerDown:ct,onTouchStart:ct},W?.sessionId)]}),S&&t.jsxs("div",{className:"terminal-shortcut-panel","data-testid":"terminal-shortcut-panel",children:[t.jsxs("div",{className:"terminal-shortcut-modifier-row",children:[t.jsx("button",{type:"button",className:`terminal-shortcut-btn terminal-shortcut-btn--modifier ${x==="ctrl"?"is-active":""}`,"data-testid":"terminal-modifier-ctrl",onClick:()=>De("ctrl"),"aria-pressed":x==="ctrl",children:"Ctrl"}),t.jsx("button",{type:"button",className:`terminal-shortcut-btn terminal-shortcut-btn--modifier ${x==="alt"?"is-active":""}`,"data-testid":"terminal-modifier-alt",onClick:()=>De("alt"),"aria-pressed":x==="alt",children:"Alt"}),t.jsx("button",{type:"button",className:"terminal-shortcut-btn",onClick:()=>ht("\x1B"),children:"ESC"}),t.jsx("button",{type:"button",className:"terminal-shortcut-btn",onClick:()=>ht(" "),children:"Tab"})]}),cD.map(Oe=>t.jsx("button",{type:"button",className:"terminal-shortcut-btn",onClick:()=>ut(Oe.key),title:Oe.description,children:Oe.label},Oe.label))]}),t.jsxs("div",{className:"terminal-status-bar","data-testid":"terminal-status-bar",children:[t.jsxs("span",{className:`terminal-connection-status ${Q}`,children:[Q==="connected"&&"Connected",Q==="connecting"&&"Connecting...",Q==="reconnecting"&&"Reconnecting...",Q==="disconnected"&&"Disconnected"]}),l!==null&&t.jsxs("span",{className:"terminal-exit-code","data-testid":"terminal-exit-code",children:["Exit: ",l]}),t.jsxs("span",{className:"terminal-font-size-controls",children:[t.jsx("button",{type:"button",className:"terminal-font-size-btn",onClick:pe,"data-testid":"terminal-font-size-decrease","aria-label":"Decrease terminal font size",children:t.jsx(Ik,{size:14})}),t.jsxs("span",{className:"terminal-font-size-value","data-testid":"terminal-font-size-value",children:[y,"px"]}),t.jsx("button",{type:"button",className:"terminal-font-size-btn",onClick:he,"data-testid":"terminal-font-size-increase","aria-label":"Increase terminal font size",children:t.jsx(Tn,{size:14})})]}),t.jsx("span",{className:"terminal-shortcuts",children:"Ctrl++/- zoom • ⌨ Shortcuts panel • Esc close"})]})]})})}const ho={name:"",command:""};function Qf(e){return/^[a-zA-Z0-9_-]+$/.test(e)}function bD(e,n=60){return e.length<=n?e:e.slice(0,n-3)+"..."}function xD({isOpen:e,onClose:n,addToast:s,projectId:a,onRunScript:r}){Si(e);const[o,l]=i.useState({}),[c,d]=i.useState(!0),[u,h]=i.useState(!1),[m,f]=i.useState(null),[p,g]=i.useState(ho),[w,v]=i.useState(!1),[b,y]=i.useState(null),[j,S]=i.useState(null),C=Xi(n),x=i.useCallback(async()=>{try{d(!0);const q=await Lo(a);l(q)}catch(q){s(Ie(q)||"Failed to load scripts","error")}finally{d(!1)}},[s,a]);i.useEffect(()=>{e&&x()},[e,x]);const k=i.useCallback(()=>{h(!0),f(null),g(ho),S(null)},[]),R=i.useCallback((q,Y)=>{f(q),h(!1),g({name:q,command:Y}),S(null)},[]),O=i.useCallback(()=>{f(null),h(!1),g(ho),S(null)},[]),E=i.useCallback(q=>{g(Y=>({...Y,name:q})),q&&!Qf(q)?S("Name must contain only letters, numbers, hyphens, and underscores (no spaces)"):S(null)},[]),_=i.useCallback(async()=>{const q=p.name.trim(),Y=p.command.trim();if(!q){s("Script name is required","error");return}if(!Qf(q)){s("Script name must contain only letters, numbers, hyphens, and underscores (no spaces)","error");return}if(!Y){s("Script command is required","error");return}v(!0);try{await v1(q,Y,a),s(m?"Script updated":"Script created","success"),f(null),h(!1),g(ho),S(null),await x()}catch(ge){const L=Ie(ge);L?.includes("already exists")?s("A script with this name already exists","error"):s(L||"Failed to save script","error")}finally{v(!1)}},[p,m,s,x,a]),G=i.useCallback(async q=>{try{await y1(q,a),s("Script deleted","success"),y(null),m===q&&(f(null),g(ho)),await x()}catch(Y){s(Ie(Y)||"Failed to delete script","error")}},[m,s,x,a]),H=i.useCallback((q,Y)=>{r&&r(q,Y)},[r]);if(!e)return null;const A=u||m!==null,P=Object.entries(o).map(([q,Y])=>({name:q,command:Y}));return t.jsx("div",{className:"modal-overlay open",...C,"data-testid":"scripts-modal",children:t.jsxs("div",{className:"modal scripts-modal",role:"dialog","aria-modal":"true","aria-label":"Scripts",children:[t.jsxs("div",{className:"modal-header",children:[t.jsxs("h2",{children:[t.jsx(Ji,{size:18,style:{marginRight:"8px",verticalAlign:"middle"}}),"Scripts"]}),t.jsx("button",{className:"modal-close",onClick:n,"aria-label":"Close",children:"×"})]}),t.jsx("div",{className:"modal-body scripts-modal-body",children:c?t.jsxs("div",{style:{textAlign:"center",padding:"32px",color:"var(--text-muted)"},children:[t.jsx(St,{size:24,className:"spin",style:{margin:"0 auto 8px",display:"block"}}),"Loading scripts..."]}):A?t.jsxs("div",{className:"scripts-modal-form",style:{display:"flex",flexDirection:"column",gap:"16px"},children:[t.jsxs("div",{children:[t.jsx("label",{htmlFor:"script-name",style:{display:"block",marginBottom:"4px",fontSize:"13px",fontWeight:500,color:"var(--text)"},children:"Script Name"}),t.jsx("input",{id:"script-name",type:"text",className:"input",value:p.name,onChange:q=>E(q.target.value),placeholder:"e.g., build, test, lint",disabled:w||m!==null,"data-testid":"script-name-input",style:{width:"100%",borderColor:j?"var(--color-error)":void 0}}),j&&t.jsx("div",{style:{fontSize:"12px",color:"var(--color-error)",marginTop:"4px"},"data-testid":"script-name-error",children:j}),t.jsx("div",{style:{fontSize:"11px",color:"var(--text-muted)",marginTop:"4px"},children:"Letters, numbers, hyphens, and underscores only"})]}),t.jsxs("div",{children:[t.jsx("label",{htmlFor:"script-command",style:{display:"block",marginBottom:"4px",fontSize:"13px",fontWeight:500,color:"var(--text)"},children:"Command"}),t.jsx("textarea",{id:"script-command",className:"input",value:p.command,onChange:q=>g(Y=>({...Y,command:q.target.value})),placeholder:"e.g., npm run build",rows:3,disabled:w,"data-testid":"script-command-input",style:{width:"100%",resize:"vertical",fontFamily:"monospace"}})]}),t.jsxs("div",{className:"scripts-modal-form-actions",style:{display:"flex",gap:"8px",justifyContent:"flex-end"},children:[t.jsx("button",{className:"btn btn-secondary",onClick:O,disabled:w,"data-testid":"script-cancel-btn",children:"Cancel"}),t.jsx("button",{className:"btn btn-primary",onClick:_,disabled:w||!!j,"data-testid":"script-save-btn",children:w?t.jsxs(t.Fragment,{children:[t.jsx(St,{size:14,className:"spin",style:{marginRight:"6px"}}),"Saving..."]}):m?"Update":"Create"})]})]}):t.jsxs(t.Fragment,{children:[t.jsxs("div",{className:"scripts-modal-list-header",style:{display:"flex",justifyContent:"space-between",alignItems:"center",marginBottom:"16px"},children:[t.jsx("div",{style:{fontSize:"13px",color:"var(--text-muted)"},children:P.length===0?"No scripts defined":`${P.length} script${P.length===1?"":"s"}`}),t.jsxs("button",{className:"btn btn-primary",onClick:k,"data-testid":"add-script-btn",style:{display:"flex",alignItems:"center",gap:"6px"},children:[t.jsx(Tn,{size:14}),"Add Script"]})]}),P.length===0?t.jsxs("div",{style:{textAlign:"center",padding:"32px",color:"var(--text-muted)",fontSize:"14px",border:"1px dashed var(--border)",borderRadius:"8px"},"data-testid":"empty-state",children:[t.jsx(Ji,{size:32,style:{margin:"0 auto 12px",opacity:.5}}),t.jsx("div",{children:"No scripts defined yet."}),t.jsx("div",{style:{marginTop:"4px",fontSize:"12px"},children:"Add scripts to quickly run common commands from the dashboard."})]}):t.jsx("div",{className:"scripts-modal-list",style:{display:"flex",flexDirection:"column",gap:"8px"},children:P.map(q=>t.jsx("div",{className:"script-card","data-testid":`script-${q.name}`,style:{padding:"12px 16px",border:"1px solid var(--border)",borderRadius:"8px",background:"var(--card)"},children:t.jsxs("div",{className:"script-card-header",style:{display:"flex",justifyContent:"space-between",alignItems:"flex-start"},children:[t.jsxs("div",{style:{flex:1,minWidth:0},children:[t.jsx("div",{style:{display:"flex",alignItems:"center",gap:"8px",marginBottom:"4px"},children:t.jsx("span",{style:{fontWeight:600,fontSize:"14px",fontFamily:"monospace"},children:q.name})}),t.jsx("div",{style:{fontSize:"12px",color:"var(--text-muted)",fontFamily:"monospace",overflow:"hidden",textOverflow:"ellipsis",whiteSpace:"nowrap"},title:q.command,children:bD(q.command)})]}),t.jsxs("div",{className:"script-card-actions",style:{display:"flex",gap:"4px",marginLeft:"8px",flexShrink:0},children:[t.jsxs("button",{className:"btn btn-secondary",onClick:()=>H(q.name,q.command),title:"Run script","aria-label":`Run ${q.name}`,"data-testid":`run-script-${q.name}`,style:{display:"flex",alignItems:"center",gap:"4px",padding:"4px 10px",fontSize:"12px"},children:[t.jsx(is,{size:12}),"Run"]}),t.jsx("button",{className:"btn-icon",onClick:()=>R(q.name,q.command),title:"Edit","aria-label":`Edit ${q.name}`,"data-testid":`edit-script-${q.name}`,children:t.jsx(Tn,{size:14,style:{transform:"rotate(45deg)"}})}),b===q.name?t.jsxs("div",{className:"script-delete-confirm",style:{display:"flex",gap:"4px",alignItems:"center"},children:[t.jsx("button",{className:"btn-icon",onClick:()=>G(q.name),title:"Confirm delete","aria-label":`Confirm delete ${q.name}`,"data-testid":`confirm-delete-script-${q.name}`,style:{color:"var(--color-error)"},children:t.jsx(In,{size:14})}),t.jsx("button",{className:"btn-icon",onClick:()=>y(null),title:"Cancel delete","aria-label":"Cancel delete","data-testid":`cancel-delete-script-${q.name}`,children:t.jsx(bn,{size:14})})]}):t.jsx("button",{className:"btn-icon",onClick:()=>y(q.name),title:"Delete","aria-label":`Delete ${q.name}`,"data-testid":`delete-script-${q.name}`,children:t.jsx(In,{size:14})})]})]})},q.name))})]})})]})})}function vD(e,n,s){const[a,r]=i.useState([]),[o,l]=i.useState("."),[c,d]=i.useState(!1),[u,h]=i.useState(null),[m,f]=i.useState(0),p=i.useCallback(()=>{f(w=>w+1)},[]),g=i.useCallback(w=>{l(w),h(null)},[]);return i.useEffect(()=>{l("."),h(null),r([])},[e]),i.useEffect(()=>{if(!n||!e)return;let w=!1;async function v(){d(!0),h(null);try{const b=await TS(e,o==="."?void 0:o,s);w||r(b.entries)}catch(b){w||(h(Ie(b)||"Failed to load files"),r([]))}finally{w||d(!1)}}return v(),()=>{w=!0}},[e,o,n,m,s]),{entries:a,currentPath:o,setPath:g,loading:c,error:u,refresh:p}}function yD(e,n,s,a){const[r,o]=i.useState(""),[l,c]=i.useState(""),[d,u]=i.useState(null),[h,m]=i.useState(!1),[f,p]=i.useState(!1),[g,w]=i.useState(null),v=i.useCallback(j=>{o(j),w(null)},[]);i.useEffect(()=>{if(!e||!n){o(""),c(""),u(null),w(null);return}let j=!1;async function S(){m(!0),w(null);try{const C=await PS(e,n,a);j||(o(C.content),c(C.content),u(C.mtime))}catch(C){j||(w(Ie(C)||"Failed to load file"),o(""),c(""),u(null))}finally{j||m(!1)}}return S(),()=>{j=!0}},[e,n,s,a]);const b=r!==l,y=i.useCallback(async()=>{if(!(!e||!n||!b)){p(!0),w(null);try{const j=await $S(e,n,r,a);c(r),u(j.mtime)}catch(j){throw w(Ie(j)||"Failed to save file"),j}finally{p(!1)}}},[e,n,r,b,a]);return{content:r,setContent:v,originalContent:l,loading:h,saving:f,error:g,save:y,hasChanges:b,mtime:d}}const wD=1e4;function kD(e){const s=e.replace(/[\\/]+$/,"").split(/[\\/]/).filter(Boolean);return s[s.length-1]||e||"Project Root"}function jD(e){return{id:e.id,label:e.id,title:e.title,worktree:e.worktree,kind:"task"}}function ND(e){const[n,s]=i.useState("Project Root"),[a,r]=i.useState([]),[o,l]=i.useState(!0),[c,d]=i.useState(null);return i.useEffect(()=>{let u=!1;async function h(){try{const f=await IS(e);if(u)return;s(kD(f.project)),r(f.tasks.map(jD)),d(null)}catch(f){u||d(Ie(f)||"Failed to load workspaces")}finally{u||l(!1)}}h();const m=window.setInterval(()=>{h()},wD);return()=>{u=!0,window.clearInterval(m)}},[e]),{projectName:n,workspaces:a,loading:o,error:c}}function SD(e){return e===void 0?"":e<1024?`${e} B`:e<1024*1024?`${(e/1024).toFixed(1)} KB`:`${(e/(1024*1024)).toFixed(1)} MB`}function CD(e){return e?new Date(e).toLocaleDateString():""}function Xf(e,n){return JC(e,n)}const po={visible:!1,x:0,y:0,entry:null,entryFullPath:""},Gd={type:null,entry:null,entryFullPath:""},ED=200,_D=500,Zf=10;function MD({x:e,y:n,entry:s,onAction:a,onClose:r}){const o=i.useRef(null),[l,c]=i.useState({x:e,y:n});i.useEffect(()=>{const h=o.current;if(!h)return;const m=h.getBoundingClientRect(),f=window.visualViewport,p=f?.width&&f.width>0?f.width:window.innerWidth,g=f?.height&&f.height>0?f.height:window.innerHeight,w=f?.offsetLeft??0,v=f?.offsetTop??0,b=8;let y=e-w,j=n-v;y+m.width>p-b&&(y=p-b-m.width),j+m.height>g-b&&(j=g-b-m.height),y<b&&(y=b),j<b&&(j=b),c({x:y+w,y:j+v})},[e,n]),i.useEffect(()=>{const h=m=>{m.key==="Escape"&&r()};return document.addEventListener("keydown",h),()=>document.removeEventListener("keydown",h)},[r]);const d=s.type==="directory",u=[{id:"copy",label:"Copy",icon:ba,disabled:!1},{id:"move",label:"Move",icon:$k,disabled:!1},{id:"rename",label:"Rename",icon:Os,disabled:!1},...d?[{id:"download-zip",label:"Download as ZIP",icon:Fr,disabled:!1}]:[{id:"download",label:"Download",icon:kw,disabled:!1}],{id:"divider",label:"",icon:ba,disabled:!0},{id:"delete",label:"Delete",icon:In,disabled:!1}];return t.jsx("div",{className:"context-menu-overlay",onClick:r,children:t.jsx("div",{ref:o,className:"file-browser-context-menu",role:"menu","aria-label":"File operations",style:{left:l.x,top:l.y},onClick:h=>h.stopPropagation(),children:u.map(h=>h.id==="divider"?t.jsx("div",{className:"file-browser-context-menu__divider",role:"separator"},"divider"):t.jsxs("button",{role:"menuitem",className:`file-browser-context-menu__item ${h.disabled?"file-browser-context-menu__disabled":""} ${h.id==="delete"?"file-browser-context-menu__item--danger":""}`,disabled:h.disabled,onClick:()=>a(h.id),children:[t.jsx(h.icon,{size:14,className:"file-browser-context-menu__item-icon"}),t.jsx("span",{children:h.label})]},h.id))})})}function AD({type:e,entry:n,entryFullPath:s,onConfirm:a,onCancel:r,loading:o,error:l}){const c=i.useRef(null),d=e==="rename"?n.name:"",[u,h]=i.useState(d);i.useEffect(()=>{setTimeout(()=>c.current?.focus(),50)},[]),i.useEffect(()=>{if(e==="rename"&&c.current){const g=n.name.lastIndexOf(".");g>0?c.current.setSelectionRange(0,g):c.current.select()}},[e,n.name]);const m=g=>{g.key==="Enter"&&u.trim()&&a(u.trim()),g.key==="Escape"&&r()};if(e==="delete")return t.jsx("div",{className:"context-menu-overlay",onClick:r,children:t.jsxs("div",{className:"file-browser-dialog",onClick:g=>g.stopPropagation(),children:[t.jsxs("div",{className:"file-browser-dialog-title",children:["Delete ",n.type==="directory"?"Folder":"File"]}),t.jsxs("div",{className:"file-browser-dialog-message",children:["Are you sure you want to delete ",t.jsx("strong",{children:n.name}),"?",n.type==="directory"&&" This will delete all contents recursively."]}),l&&t.jsx("div",{className:"file-browser-dialog-error",children:l}),t.jsxs("div",{className:"file-browser-dialog-actions",children:[t.jsx("button",{className:"btn btn-sm",onClick:r,disabled:o,children:"Cancel"}),t.jsx("button",{className:"btn btn-danger btn-sm",onClick:()=>a(""),disabled:o,children:o?"Deleting...":"Delete"})]})]})});const p={copy:{title:"Copy",placeholder:"Destination path",confirm:"Copy"},move:{title:"Move",placeholder:"Destination path",confirm:"Move"},rename:{title:"Rename",placeholder:"New name",confirm:"Rename"}}[e];return t.jsx("div",{className:"context-menu-overlay",onClick:r,children:t.jsxs("div",{className:"file-browser-dialog",onClick:g=>g.stopPropagation(),children:[t.jsx("div",{className:"file-browser-dialog-title",children:p.title}),t.jsx("div",{className:"file-browser-dialog-info",children:e==="rename"?n.name:s}),t.jsx("input",{ref:c,className:"file-browser-dialog-input",type:"text",value:u,onChange:g=>h(g.target.value),placeholder:p.placeholder,onKeyDown:m,disabled:o}),l&&t.jsx("div",{className:"file-browser-dialog-error",children:l}),t.jsxs("div",{className:"file-browser-dialog-actions",children:[t.jsx("button",{className:"btn btn-sm",onClick:r,disabled:o,children:"Cancel"}),t.jsx("button",{className:"btn btn-primary btn-sm",onClick:()=>a(u.trim()),disabled:o||!u.trim(),children:o?`${p.confirm}ing...`:p.confirm})]})]})})}function RD({entries:e,currentPath:n,onSelectFile:s,onNavigate:a,loading:r,error:o,onRetry:l,workspace:c,onRefresh:d,projectId:u}){const[h,m]=i.useState(po),[f,p]=i.useState(Gd),[g,w]=i.useState(!1),[v,b]=i.useState(null),[y,j]=i.useState(!1),[S,C]=i.useState(null),x=i.useRef(null),k=i.useRef(null),R=i.useRef(null),O=i.useRef(!1),E=i.useCallback(()=>{x.current!==null&&(window.clearTimeout(x.current),x.current=null),k.current!==null&&(window.clearTimeout(k.current),k.current=null)},[]),_=i.useCallback(()=>{E(),R.current=null,j(!1),C(null)},[E]);i.useEffect(()=>()=>{E()},[E]);const G=i.useCallback(($,D,N,W)=>{m({visible:!0,x:$,y:D,entry:N,entryFullPath:W})},[]),H=i.useCallback(($,D,N)=>{if($.touches.length!==1)return;const W=$.touches[0];W&&(_(),R.current={x:W.clientX,y:W.clientY},k.current=window.setTimeout(()=>{j(!0),C(N)},ED),x.current=window.setTimeout(()=>{const de=R.current;de&&(O.current=!0,j(!1),C(null),E(),G(de.x,de.y,D,N))},_D))},[_,E,G]),A=i.useCallback($=>{const D=R.current,N=$.touches[0];!D||!N||(Math.abs(N.clientX-D.x)>Zf||Math.abs(N.clientY-D.y)>Zf)&&_()},[_]),P=i.useCallback(()=>{_()},[_]);i.useEffect(()=>{if(!h.visible)return;const $=document.querySelector(".file-browser-list"),D=()=>{O.current=!1,_(),m(po)};return $?.addEventListener("scroll",D),()=>$?.removeEventListener("scroll",D)},[_,h.visible]),i.useEffect(()=>{if(!h.visible)return;const $=D=>{D.key==="Escape"&&(O.current=!1,m(po))};return document.addEventListener("keydown",$),()=>document.removeEventListener("keydown",$)},[h.visible]);const q=i.useCallback(($,D)=>{$.preventDefault(),$.stopPropagation(),_(),O.current=!1,G($.clientX,$.clientY,D,Xf(n,D.name))},[_,n,G]),Y=i.useCallback($=>{if(!h.entry)return;O.current=!1;const D=h.entry,N=h.entryFullPath;if(m(po),$==="download"){if(!c)return;const W=_b(c,N,u);window.open(Li(W),"_blank");return}if($==="download-zip"){if(!c)return;const W=BS(c,N,u);window.open(Li(W),"_blank");return}p({type:$,entry:D,entryFullPath:N}),b(null)},[h,c,u]),ge=i.useCallback(async $=>{if(!(!f.type||!f.entry||!c)){w(!0),b(null);try{switch(f.type){case"copy":await LS(c,f.entryFullPath,$,u);break;case"move":await OS(c,f.entryFullPath,$,u);break;case"rename":await zS(c,f.entryFullPath,$,u);break;case"delete":await FS(c,f.entryFullPath,u);break}p(Gd),d?.()}catch(D){b(Ie(D)||"Operation failed")}finally{w(!1)}}},[f,c,d,u]),L=i.useCallback(()=>{p(Gd),b(null)},[]),M=i.useCallback(($,D)=>{if(O.current){O.current=!1;return}h.visible||($.type==="directory"?a(D):s(D))},[h.visible,a,s]);return r?t.jsxs("div",{className:"file-browser-loading",children:[t.jsx(St,{className:"spin",size:24}),t.jsx("span",{children:"Loading files..."})]}):o?t.jsxs("div",{className:"file-browser-error",children:[t.jsxs("p",{children:["Error: ",o]}),l&&t.jsx("button",{className:"btn btn-sm",onClick:l,children:"Retry"})]}):t.jsxs("div",{className:"file-browser",children:[t.jsxs("div",{className:"file-browser-header",children:[n!=="."&&t.jsxs("button",{className:"file-browser-up",onClick:()=>{a(YC(n))},children:[t.jsx(Wn,{size:16,style:{transform:"rotate(-90deg)"}}),"Up one level"]}),t.jsx("span",{className:"file-browser-path",children:n==="."?"Root":qr(n)})]}),t.jsx("div",{className:"file-browser-list",children:e.length===0?t.jsx("div",{className:"file-browser-empty",children:"(empty directory)"}):e.map($=>{const D=Xf(n,$.name),N=y&&S===D;return t.jsxs("div",{className:`file-node file-node--${$.type} ${N?"file-node--long-pressing":""}`,onClick:()=>M($,D),onContextMenu:W=>q(W,$),onTouchStart:W=>H(W,$,D),onTouchMove:A,onTouchEnd:P,onTouchCancel:P,children:[t.jsx("div",{className:"file-node-icon",children:$.type==="directory"?t.jsx(ws,{size:16}):t.jsx(ub,{size:16})}),t.jsx("div",{className:"file-node-name",children:$.name}),$.type==="file"&&$.size!==void 0&&t.jsx("div",{className:"file-node-size",children:SD($.size)}),$.mtime&&t.jsx("div",{className:"file-node-time",children:CD($.mtime)})]},$.name)})}),h.visible&&h.entry&&t.jsx(MD,{x:h.x,y:h.y,entry:h.entry,onAction:Y,onClose:()=>{O.current=!1,m(po)}}),f.type&&f.entry&&t.jsx(AD,{type:f.type,entry:f.entry,entryFullPath:f.entryFullPath,onConfirm:ge,onCancel:L,loading:g,error:v})]})}function ID(e){if(!e)return!1;const n=e.toLowerCase();return n.endsWith(".md")||n.endsWith(".markdown")||n.endsWith(".mdx")}function TD({content:e,onChange:n,readOnly:s,filePath:a,showLineNumbers:r=!1,onToggleLineNumbers:o,canToggleLineNumbers:l=!0}){const[c,d]=i.useState(!1),[u,h]=i.useState(!0),[m,f]=i.useState(!1),p=i.useRef(null),g=ID(a),w=i.useId(),v=g&&(s?!0:c),b=r&&!s&&!v,y=!!o&&l&&!s&&!v,j=y||!s,S=i.useMemo(()=>b?e.split(`
694
- `).length:0,[e,b]),C=i.useCallback(()=>{d(!1)},[]),x=i.useCallback(()=>{d(!0)},[]),k=i.useCallback(()=>{h(E=>!E)},[]),R=i.useCallback(()=>{f(E=>!E)},[]),O=i.useCallback(E=>{p.current&&(p.current.scrollTop=E.currentTarget.scrollTop)},[]);return t.jsxs("div",{className:"file-editor-container",children:[g?t.jsxs("div",{className:"file-editor-toolbar",children:[t.jsxs("div",{className:"file-editor-mode-toggle",children:[!s&&t.jsxs("button",{className:`btn btn-sm ${v?"":"btn-primary"}`,onClick:C,disabled:!v,"aria-label":"Edit mode",children:[t.jsx(db,{size:14}),"Edit"]}),t.jsxs("button",{className:`btn btn-sm ${v?"btn-primary":""}`,onClick:x,disabled:v,"aria-label":"Preview mode",children:[t.jsx(zr,{size:14}),"Preview"]})]}),!s&&t.jsx("div",{className:"file-editor-toolbar-actions",children:j&&t.jsxs(t.Fragment,{children:[t.jsx("button",{className:"btn btn-sm btn-icon",onClick:R,"aria-label":"Toggle editor options",title:"Toggle editor options","aria-expanded":m,"aria-controls":w,children:m?t.jsx(mi,{size:14}):t.jsx(vn,{size:14})}),t.jsxs("div",{className:"file-editor-toolbar-collapsible",id:w,hidden:!m,children:[y&&t.jsxs("button",{className:`btn btn-sm file-editor-line-numbers-button ${r?"btn-primary":""}`,onClick:o,"aria-label":"Toggle line numbers","aria-pressed":r,title:"Toggle line numbers",children:[t.jsx(zm,{size:14}),t.jsx("span",{children:"Line #"})]}),t.jsx("button",{className:`btn btn-sm ${u?"btn-primary":""}`,onClick:k,"aria-label":"Toggle word wrap",title:"Toggle word wrap",children:t.jsx(Kl,{size:14})})]})]})})]}):!s&&t.jsxs("div",{className:"file-editor-toolbar",children:[t.jsx("div",{className:"file-editor-mode-toggle"}),t.jsx("div",{className:"file-editor-toolbar-actions",children:j&&t.jsxs(t.Fragment,{children:[t.jsx("button",{className:"btn btn-sm btn-icon",onClick:R,"aria-label":"Toggle editor options",title:"Toggle editor options","aria-expanded":m,"aria-controls":w,children:m?t.jsx(mi,{size:14}):t.jsx(vn,{size:14})}),t.jsxs("div",{className:"file-editor-toolbar-collapsible",id:w,hidden:!m,children:[y&&t.jsxs("button",{className:`btn btn-sm file-editor-line-numbers-button ${r?"btn-primary":""}`,onClick:o,"aria-label":"Toggle line numbers","aria-pressed":r,title:"Toggle line numbers",children:[t.jsx(zm,{size:14}),t.jsx("span",{children:"Line #"})]}),t.jsx("button",{className:`btn btn-sm ${u?"btn-primary":""}`,onClick:k,"aria-label":"Toggle word wrap",title:"Toggle word wrap",children:t.jsx(Kl,{size:14})})]})]})})]}),v?t.jsx("div",{className:"file-editor-preview markdown-body",children:t.jsx(hi,{remarkPlugins:[pi],children:e})}):t.jsxs("div",{className:`file-editor-textarea-shell ${b?"file-editor-textarea-shell--line-numbers":""}`,children:[b&&t.jsx("div",{className:"file-editor-line-numbers",ref:p,"aria-hidden":"true",children:Array.from({length:S},(E,_)=>t.jsx("div",{className:"file-editor-line-number",children:_+1},`line-${_+1}`))}),t.jsx("textarea",{className:`file-editor-textarea ${u?"file-editor-textarea--wrap":""}`,value:e,onChange:E=>n(E.target.value),onScroll:O,readOnly:s,spellCheck:!1,"aria-label":a?`Editor for ${a}`:"File editor"})]})]})}function PD(e,n=44){if(e)return e.length<=n?e:`${e.slice(0,n-1)}…`}function $D({currentWorkspace:e,projectName:n,workspaces:s,onSelect:a}){const[r,o]=i.useState(!1),l=i.useMemo(()=>e==="project"?n||"Project Root":s.find(d=>d.id===e)?.label??e,[e,n,s]);return t.jsxs("div",{className:"workspace-selector",children:[t.jsxs("button",{type:"button",className:"workspace-selector-trigger",onClick:()=>o(c=>!c),"aria-haspopup":"listbox","aria-expanded":r,children:[e==="project"?t.jsx(Fm,{size:14}):t.jsx(lu,{size:14}),t.jsx("span",{className:"workspace-selector-trigger-label",children:l}),t.jsx(vn,{size:14,className:`workspace-selector-trigger-icon${r?" open":""}`})]}),r&&t.jsxs("div",{className:"workspace-selector-menu",role:"listbox","aria-label":"Select workspace",children:[t.jsxs("button",{type:"button",className:`workspace-selector-option${e==="project"?" active":""}`,onClick:()=>{a("project"),o(!1)},children:[t.jsxs("div",{className:"workspace-selector-option-main",children:[t.jsx(Fm,{size:14}),t.jsx("span",{children:"Project Root"})]}),t.jsx("span",{className:"workspace-selector-option-meta",children:n})]}),s.length>0&&t.jsxs("div",{className:"workspace-selector-group",children:[t.jsx("div",{className:"workspace-selector-group-label",children:"Task Worktrees"}),s.map(c=>t.jsxs("button",{type:"button",className:`workspace-selector-option${e===c.id?" active":""}`,onClick:()=>{a(c.id),o(!1)},children:[t.jsxs("div",{className:"workspace-selector-option-main",children:[t.jsx(lu,{size:14}),t.jsx("span",{children:c.id})]}),c.title&&t.jsx("span",{className:"workspace-selector-option-meta",title:c.title,children:PD(c.title)})]},c.id))]})]})]})}const DD=768,LD=280,Pl=180,$l=500,eg="fusion:file-browser-sidebar-width",tg="kb-files-line-numbers",Bv=new Set([".png",".jpg",".jpeg",".gif",".webp",".ico",".bmp",".svgz"]),OD=new Set([...Bv,".exe",".dll",".so",".dylib",".zip",".tar",".gz",".bz2",".xz",".7z",".rar",".pdf",".doc",".docx",".xls",".xlsx",".ppt",".pptx",".mp3",".mp4",".avi",".mov",".webm",".mkv",".flv",".woff",".woff2",".ttf",".otf",".eot",".wasm",".bin"]);function Dl(e){const n=e.slice(e.lastIndexOf(".")).toLowerCase();return OD.has(n)}function FD(e){const n=e.slice(e.lastIndexOf(".")).toLowerCase();return Bv.has(n)}function zD(e){const n=e.replace(/\\/g,"/").replace(/^\.\//,"").replace(/\/$/,""),s=n.lastIndexOf("/");return s>0?n.slice(0,s):"."}function BD({initialWorkspace:e="project",initialFile:n=null,onClose:s,onWorkspaceChange:a,projectId:r}){const{projectName:o,workspaces:l}=ND(r),c=i.useRef(null);Oi(c,!0,"fusion:files-modal-size");const d=Xi(s),[u,h]=i.useState(e),[m,f]=i.useState(null),[p,g]=i.useState(!1),[w,v]=i.useState("list"),[b,y]=i.useState(LD),[j,S]=i.useState(!1),{entries:C,currentPath:x,setPath:k,loading:R,error:O,refresh:E}=vD(u,!0,r),{content:_,setContent:G,originalContent:H,loading:A,saving:P,error:q,save:Y,hasChanges:ge,mtime:L}=yD(u,m,!0,r);i.useEffect(()=>{h(e)},[e]),i.useEffect(()=>{const Z=()=>{g(window.innerWidth<=DD)};return Z(),window.addEventListener("resize",Z),()=>window.removeEventListener("resize",Z)},[]),i.useEffect(()=>{m||v("list")},[m]),i.useEffect(()=>{if(!n){f(null);return}f(n),k(zD(n)),p&&v("editor")},[n,p,k]),i.useEffect(()=>{try{const Z=localStorage.getItem(eg);if(!Z)return;const fe=Number.parseInt(Z,10);if(!Number.isNaN(fe)){const Q=Math.max(Pl,Math.min($l,fe));y(Q)}}catch{}},[]),i.useEffect(()=>{const Z=Ln(tg,r);S(Z==="true")},[r]),i.useEffect(()=>{const Z=fe=>{fe.key==="Escape"&&s(),(fe.metaKey||fe.ctrlKey)&&fe.key==="s"&&(fe.preventDefault(),ge&&!P&&Y())};return document.addEventListener("keydown",Z),()=>document.removeEventListener("keydown",Z)},[s,ge,P,Y]);const M=i.useCallback(Z=>{f(Z),p&&v("editor")},[p]),$=i.useCallback(()=>{v("list")},[]),D=i.useCallback(()=>{G(H)},[H,G]),N=i.useCallback(Z=>{h(Z),f(null),v("list"),a?.(Z)},[a]),W=i.useCallback(Z=>{try{localStorage.setItem(eg,String(Z))}catch{}},[]),de=i.useCallback(Z=>{if(p)return;Z.preventDefault(),Z.stopPropagation();const fe=Z.currentTarget;typeof fe.setPointerCapture=="function"&&fe.setPointerCapture(Z.pointerId);const Q=Z.clientX,F=b;let X=F;document.body.style.userSelect="none";const re=be=>{const Ue=be.clientX-Q,se=Math.max(Pl,Math.min($l,F+Ue));X=se,y(se)},U=be=>{typeof fe.releasePointerCapture=="function"&&fe.releasePointerCapture(be.pointerId),document.body.style.userSelect="",document.removeEventListener("pointermove",re),document.removeEventListener("pointerup",U),W(X)};document.addEventListener("pointermove",re),document.addEventListener("pointerup",U)},[p,W,b]),me=i.useCallback(Z=>{if(p)return;const fe=20;if(Z.key!=="ArrowLeft"&&Z.key!=="ArrowRight")return;Z.preventDefault();const Q=Z.key==="ArrowLeft"?-fe:fe,F=Math.max(Pl,Math.min($l,b+Q));y(F),W(F)},[p,W,b]),Ne=i.useCallback(()=>{S(Z=>{const fe=!Z;return rs(tg,String(fe),r),fe})},[r]),Me=`Files — ${i.useMemo(()=>u==="project"?"Project":l.find(Z=>Z.id===u)?.id??u,[u,l])}`,ie=i.useMemo(()=>!m||!FD(m)?null:_b(u,m,r),[m,u,r]),ye=Z=>{const fe=new Blob([Z]).size;return fe<1024?`${fe} B`:`${(fe/1024).toFixed(1)} KB`};return t.jsx("div",{className:"modal-overlay open",...d,role:"dialog","aria-modal":"true",children:t.jsxs("div",{className:"modal file-browser-modal",ref:c,children:[t.jsxs("div",{className:"modal-header file-browser-modal-header",children:[t.jsxs("div",{className:"file-browser-header-title",children:[t.jsx(ws,{size:18}),t.jsx("span",{children:Me}),m&&t.jsx("span",{className:"file-browser-header-path",children:m})]}),t.jsxs("div",{className:"file-browser-header-actions",children:[t.jsx($D,{currentWorkspace:u,projectName:o,workspaces:l,onSelect:N}),t.jsx("button",{className:"modal-close",onClick:s,"aria-label":"Close",children:t.jsx(bn,{size:20})})]})]}),t.jsxs("div",{className:"file-browser-body",children:[t.jsx("div",{className:`file-browser-sidebar ${p?"mobile":""} ${w==="list"?"active":""}`,style:p?void 0:{width:`${b}px`},children:t.jsx(RD,{entries:C,currentPath:x,onSelectFile:M,onNavigate:k,loading:R,error:O,onRetry:E,workspace:u,onRefresh:E,projectId:r})}),!p&&t.jsx("div",{className:"file-browser-resize-handle",role:"separator","aria-orientation":"vertical","aria-valuemin":Pl,"aria-valuemax":$l,"aria-valuenow":b,"aria-label":"Resize sidebar",tabIndex:0,onPointerDown:de,onKeyDown:me}),t.jsx("div",{className:`file-browser-content ${p?"mobile":""} ${w==="editor"?"active":""}`,children:m?t.jsxs(t.Fragment,{children:[t.jsxs("div",{className:"file-browser-toolbar",children:[t.jsxs("div",{className:"file-browser-file-info",children:[p&&w==="editor"&&t.jsxs("button",{className:"file-browser-back-button",onClick:$,"aria-label":"Back to file list",children:[t.jsx(Ka,{size:16}),t.jsx("span",{children:"Back"})]}),m,Dl(m)&&t.jsxs("span",{className:"file-browser-binary-indicator",children:[t.jsx(zw,{size:12}),"Binary file — read only"]}),L&&t.jsxs("span",{className:"file-browser-mtime",children:["Modified: ",new Date(L).toLocaleString()]}),A&&t.jsx("span",{className:"file-browser-loading",children:"Loading..."})]}),t.jsx("div",{className:"file-browser-actions",children:!ie&&ge&&t.jsxs(t.Fragment,{children:[t.jsxs("button",{className:"btn btn-sm",onClick:D,disabled:P,children:[t.jsx(Yk,{size:14}),"Discard"]}),t.jsxs("button",{className:"btn btn-primary btn-sm",onClick:()=>void Y(),disabled:P,children:[t.jsx(gb,{size:14}),P?"Saving...":"Save"]})]})})]}),q&&!ie&&t.jsx("div",{className:"file-browser-error-banner",children:q}),ie?t.jsx("div",{className:"file-browser-image-preview",children:t.jsx("img",{src:ie,alt:m??"",className:"file-browser-image"})}):t.jsx("div",{className:"file-editor-wrapper",children:t.jsx(TD,{content:_,onChange:G,filePath:m,readOnly:Dl(m),showLineNumbers:j&&!Dl(m),onToggleLineNumbers:Ne,canToggleLineNumbers:!Dl(m)})}),!ie&&t.jsxs("div",{className:"file-browser-footer",children:[t.jsx("span",{children:ye(_)}),ge&&t.jsx("span",{className:"file-browser-unsaved",children:"Unsaved changes"})]})]}):t.jsxs("div",{className:"file-browser-placeholder",children:[t.jsx(ws,{size:48,opacity:.3}),t.jsx("p",{children:"Select a file to edit"})]})})]})]})})}const UD=i.lazy(()=>Sn(()=>import("./TodoView-rSn0aPsb.js"),__vite__mapDeps([11,1,5,6,12])).then(e=>({default:e.TodoView})));function HD({onClose:e,projectId:n,addToast:s,onPlanningMode:a}){const r=Xi(e),l=ei()==="mobile",{keyboardOverlap:c,viewportHeight:d,viewportOffsetTop:u,keyboardOpen:h}=ea({enabled:l});Si(l);const m=h?{"--keyboard-overlap":`${c}px`,"--vv-offset-top":`${u}px`,...d!==null?{"--vv-height":`${d}px`}:{}}:{};return i.useEffect(()=>{const f=p=>{p.key==="Escape"&&e()};return document.addEventListener("keydown",f),()=>document.removeEventListener("keydown",f)},[e]),t.jsx("div",{className:"modal-overlay open",...r,role:"dialog","aria-modal":"true",children:t.jsxs("div",{className:"modal todo-modal",style:m,children:[t.jsxs("div",{className:"modal-header todo-modal-header",children:[t.jsxs("div",{className:"todo-modal-header-title",children:[t.jsx(fk,{size:18}),t.jsxs("div",{children:[t.jsx("h2",{children:"Todos"}),t.jsx("p",{children:"Manage reusable todo lists for your project."})]})]}),t.jsx("button",{className:"modal-close",onClick:e,"aria-label":"Close",children:t.jsx(bn,{size:20})})]}),t.jsx("div",{className:"todo-modal-body",children:t.jsx(i.Suspense,{fallback:null,children:t.jsx(UD,{projectId:n,addToast:s,onPlanningMode:a,onClose:e,mobileKeyboardActive:l&&h})})})]})})}function qD(e={}){const{pollInterval:n=3e4,autoRefresh:s=!0}=e,[a,r]=i.useState({providers:[],loading:!0,error:null,lastUpdated:null}),o=i.useRef(null),l=i.useRef(null),c=i.useCallback(async(u=!1)=>{l.current&&l.current.abort(),l.current=new AbortController,u&&r(h=>({...h,loading:!0,error:null}));try{const{providers:h}=await DN();r({providers:h,loading:!1,error:null,lastUpdated:new Date})}catch(h){if(h instanceof Error&&h.name==="AbortError")return;r(m=>({...m,loading:!1,error:Ie(h)||"Failed to fetch usage data"}))}},[]);i.useEffect(()=>{c()},[c]),i.useEffect(()=>{if(s)return o.current=setInterval(()=>{c(!1)},n),()=>{o.current&&(clearInterval(o.current),o.current=null)}},[s,n,c]),i.useEffect(()=>()=>{l.current&&l.current.abort(),o.current&&clearInterval(o.current)},[]);const d=i.useCallback(()=>c(!0),[c]);return{providers:a.providers,loading:a.loading,error:a.error,lastUpdated:a.lastUpdated,refresh:d}}function VD(e){const n=new Date(e),s=new Date,a=n.toLocaleTimeString(void 0,{hour:"numeric",minute:"2-digit",hour12:!0});if(n.toDateString()===s.toDateString())return a;const o=new Date(s.getFullYear(),s.getMonth(),s.getDate()),l=new Date(n.getFullYear(),n.getMonth(),n.getDate()),c=Math.round((l.getTime()-o.getTime())/(1440*60*1e3));return c>=1&&c<=7?`${n.toLocaleDateString(void 0,{weekday:"short"})} ${a}`:`${n.toLocaleDateString(void 0,{month:"short",day:"numeric"})}, ${a}`}function WD(e){return e>90?"usage-progress-fill--high":e>70?"usage-progress-fill--medium":"usage-progress-fill--low"}const Uv="kb-usage-hidden-windows",Hv="kb-usage-modal-size",qv="kb-usage-provider-order";function ng(e){const n=Ln(Hv,e);if(!n)return null;try{const s=JSON.parse(n);if(s&&typeof s.width=="number"&&typeof s.height=="number"&&s.width>0&&s.height>0)return{width:s.width,height:s.height}}catch{}return null}function sg(e){const n=Ln(Uv,e);if(!n)return{};try{const s=JSON.parse(n);return!s||typeof s!="object"?{}:Object.entries(s).reduce((a,[r,o])=>{if(Array.isArray(o)){const l=o.filter(c=>typeof c=="string");l.length>0&&(a[r]=l)}return a},{})}catch{return{}}}function GD(e,n){rs(Uv,JSON.stringify(e),n)}function ig(e){const n=Ln(qv,e);if(!n)return[];try{const s=JSON.parse(n);return Array.isArray(s)?s.filter(a=>typeof a=="string"):[]}catch{return[]}}function ag(e,n){rs(qv,JSON.stringify(e),n)}function Vv(e,n,s){return s[e]?.includes(n)??!1}function KD({window:e,viewMode:n,isHidden:s,onToggleHidden:a}){const r=WD(e.percentUsed),o=n==="remaining",l=Math.round(o?e.percentLeft:e.percentUsed),c=o?`${Math.round(e.percentLeft)}% remaining`:`${Math.round(e.percentUsed)}% used`,d=o?`${Math.round(e.percentUsed)}% used`:`${Math.round(e.percentLeft)}% left`;let u=e.resetText;if(!u&&e.resetAt){const v=new Date(e.resetAt).getTime()-Date.now();if(v>0){const b=Math.floor(v/36e5),y=Math.floor(b/24),j=b%24;y>0&&j>0?u=`resets in ${y}d ${j}h`:y>0?u=`resets in ${y}d`:b>0?u=`resets in ${b}h`:u=`resets in ${Math.floor(v/6e4)}m`}}const h=e.pace,m=h!==void 0;let f=0;m&&(f=o?100-h.percentElapsed:h.percentElapsed);const p=h?.status==="ahead",g=h?.status==="behind",w=h?.status==="on-track";return t.jsxs("div",{className:`usage-window ${s?"usage-window--hidden":""}`,children:[t.jsxs("div",{className:"usage-window-header",children:[t.jsx("span",{className:"usage-window-label",children:e.label}),t.jsxs("div",{className:"usage-window-header-controls",children:[!s&&t.jsx("span",{className:"usage-window-percentage",children:c}),!s&&t.jsx("button",{className:"btn-icon usage-window-hide-btn",onClick:a,"aria-label":`Hide ${e.label}`,"data-testid":"usage-window-hide-btn",children:t.jsx(zr,{size:14})})]})]}),t.jsxs("div",{className:"usage-progress-wrapper",children:[t.jsx("div",{className:"usage-progress-bar",children:t.jsx("div",{className:`usage-progress-fill ${r}`,style:{width:`${l}%`},role:"progressbar","aria-valuenow":l,"aria-valuemin":0,"aria-valuemax":100,"aria-label":`${e.label}: ${c}`})}),m&&t.jsx("div",{className:"usage-pace-marker",style:{left:`${f}%`},"aria-hidden":"true","data-testid":"pace-marker"})]}),t.jsxs("div",{className:"usage-window-footer",children:[t.jsx("span",{className:"usage-window-left",children:d}),t.jsxs("span",{className:"usage-window-reset-group",children:[u&&t.jsx("span",{className:"usage-window-reset",children:u}),e.resetAt&&t.jsx("span",{className:"usage-window-reset-at",children:VD(e.resetAt)})]})]}),m&&t.jsxs("div",{className:"usage-pace-row","data-testid":"pace-row",children:[p&&t.jsxs(t.Fragment,{children:[t.jsx(Br,{size:14,className:"pace-icon pace-ahead"}),t.jsx("span",{className:"pace-text pace-ahead",children:h.message})]}),g&&t.jsxs(t.Fragment,{children:[t.jsx(xj,{size:14,className:"pace-icon pace-behind"}),t.jsx("span",{className:"pace-text pace-behind",children:h.message})]}),w&&t.jsxs(t.Fragment,{children:[t.jsx(Zn,{size:14,className:"pace-icon pace-ontrack"}),t.jsx("span",{className:"pace-text pace-ontrack",children:h.message})]})]})]})}function JD(e){const n=e.toLowerCase();return n.includes("claude")||n.includes("anthropic")?"anthropic":n.includes("codex")||n.includes("openai")||n.includes("gpt")?"openai":n.includes("gemini")||n.includes("google")||n.includes("antigravity")?"google":n.includes("ollama")?"ollama":n.includes("minimax")?"minimax":n.includes("zai")||n.includes("zhipu")?"zai":n.includes("kimi")||n.includes("moonshot")?"kimi":n.includes("bedrock")||n.includes("amazon")?"bedrock":n.includes("xai")||n.includes("grok")?"xai":n.includes("opencode")?"opencode":n.includes("copilot")||n==="github copilot"?"github-copilot":e}function YD({provider:e,viewMode:n,hiddenWindows:s,onToggleWindow:a,onShowAllHidden:r,isDragging:o,isDragOver:l,dragOverPosition:c,onDragStart:d,onDragOver:u,onDragLeave:h,onDrop:m,onDragEnd:f,isTouchReorderMode:p,canMoveUp:g,canMoveDown:w,onMoveUp:v,onMoveDown:b}){const y=s[e.name]?.length??0,j=()=>{switch(e.status){case"ok":return null;case"error":return t.jsx("span",{className:"usage-status-badge usage-status-badge--error",children:"Error"});case"no-auth":default:return t.jsx("span",{className:"usage-status-badge usage-status-badge--not-configured",children:"Not configured"})}};return t.jsxs("div",{className:`usage-provider${o?" usage-provider--dragging":""}${l&&c==="before"?" usage-provider--drag-over-before":""}${l&&c==="after"?" usage-provider--drag-over-after":""}`,"data-provider":e.name,"data-status":e.status,draggable:!p,onDragStart:p?void 0:d,onDragOver:p?void 0:u,onDragLeave:p?void 0:h,onDrop:p?void 0:m,onDragEnd:p?void 0:f,children:[t.jsxs("div",{className:"usage-provider-header",children:[t.jsxs("div",{className:"usage-provider-info",children:[t.jsx(On,{provider:JD(e.name),size:"md"}),t.jsx("span",{className:"usage-provider-name",children:e.name}),y>0&&t.jsxs("button",{className:"btn btn-sm usage-show-hidden-btn",onClick:()=>r(e.name),"data-testid":"usage-show-hidden-btn",children:["Show hidden (",y,")"]})]}),t.jsxs("div",{className:"usage-provider-actions",children:[p&&t.jsxs("div",{className:"usage-provider-reorder-controls",role:"group","aria-label":`Reorder ${e.name}`,children:[t.jsx("button",{className:"btn-icon usage-provider-reorder-btn",type:"button",onClick:v,disabled:!g,"aria-label":`Move ${e.name} up`,children:t.jsx(mi,{size:14})}),t.jsx("button",{className:"btn-icon usage-provider-reorder-btn",type:"button",onClick:b,disabled:!w,"aria-label":`Move ${e.name} down`,children:t.jsx(vn,{size:14})})]}),j(),t.jsx("div",{className:"usage-provider-drag-handle","aria-hidden":"true",children:t.jsx(yc,{size:16})})]})]}),e.error&&t.jsx("div",{className:"usage-provider-error",children:e.error}),e.plan&&t.jsx("div",{className:"usage-provider-meta",children:t.jsx("span",{className:"usage-provider-plan",children:e.plan})}),e.windows.length>0?t.jsx("div",{className:"usage-provider-windows",children:e.windows.map((S,C)=>{const x=Vv(e.name,S.label,s);return t.jsx(KD,{window:S,viewMode:n,isHidden:x,onToggleHidden:()=>a(e.name,S.label)},`${e.name}-${S.label}-${C}`)})}):e.status==="ok"?t.jsx("div",{className:"usage-provider-empty",children:"No usage data available"}):null]})}function QD(){return t.jsx("div",{className:"usage-skeleton",children:[1,2,3].map(e=>t.jsxs("div",{className:"usage-skeleton-provider",children:[t.jsxs("div",{className:"usage-skeleton-header",children:[t.jsx("div",{className:"usage-skeleton-icon"}),t.jsx("div",{className:"usage-skeleton-name"}),t.jsx("div",{className:"usage-skeleton-badge"})]}),t.jsx("div",{className:"usage-skeleton-bar"}),t.jsx("div",{className:"usage-skeleton-text"})]},e))})}function XD({isOpen:e,onClose:n,projectId:s,anchorRect:a}){const{providers:r,loading:o,error:l,lastUpdated:c,refresh:d}=qD({autoRefresh:e}),[u,h]=i.useState(!1),[m,f]=i.useState(()=>typeof window<"u"?window.innerWidth>=769:!1),[p,g]=i.useState(()=>typeof window>"u"?!1:window.matchMedia?.("(pointer: coarse)").matches??!1),[w,v]=i.useState("used"),[b,y]=i.useState(()=>sg(s)),[j,S]=i.useState(()=>ig(s)),[C,x]=i.useState(null),[k,R]=i.useState(null),[O,E]=i.useState(null),_=i.useRef(null),G=i.useRef(null),H=i.useRef(e),A=i.useRef(!1),[P,q]=i.useState(()=>ng(s));i.useEffect(()=>{q(ng(s))},[s]),i.useEffect(()=>{if(!e||!m)return;const U=G.current;if(!U||typeof ResizeObserver>"u")return;let be=null;const Ue=new ResizeObserver(se=>{const Ve=se[0];if(!Ve)return;const{width:Le,height:ct}=Ve.contentRect;Le<=0||ct<=0||(be&&clearTimeout(be),be=setTimeout(()=>{rs(Hv,JSON.stringify({width:Math.round(Le),height:Math.round(ct)}),s)},250))});return Ue.observe(U),()=>{be&&clearTimeout(be),Ue.disconnect()}},[e,m,s]),i.useEffect(()=>{e||(A.current=!1)},[e]),i.useEffect(()=>{r.length>0&&(A.current=!0)},[r.length]),i.useEffect(()=>{if(typeof window>"u")return;const U=window.matchMedia?.("(pointer: coarse)"),be=()=>{f(window.innerWidth>=769),g(U?.matches??!1)};return be(),window.addEventListener("resize",be),U?.addEventListener?.("change",be),()=>{window.removeEventListener("resize",be),U?.removeEventListener?.("change",be)}},[]),i.useEffect(()=>{!H.current&&e&&(!c||Date.now()-c.getTime()>5e3)&&d(),H.current=e},[e,c,d]),i.useEffect(()=>{const U=Ln("kb-usage-view-mode",s);if(U==="used"||U==="remaining"){v(U);return}v("used")},[s]);const Y=i.useCallback(U=>{v(U),rs("kb-usage-view-mode",U,s)},[s]);i.useEffect(()=>{y(sg(s)),S(ig(s))},[s]),i.useEffect(()=>{GD(b,s)},[b,s]);const ge=i.useCallback((U,be)=>{y(Ue=>{if(Vv(U,be,Ue)){const se=(Ue[U]??[]).filter(Ve=>Ve!==be);if(se.length===0){const{[U]:Ve,...Le}=Ue;return Le}return{...Ue,[U]:se}}return{...Ue,[U]:[...Ue[U]??[],be]}})},[]),L=i.useCallback(U=>{y(be=>{if(!be[U])return be;const{[U]:Ue,...se}=be;return se})},[]),M=i.useCallback(U=>{if(j.length===0)return U;const be=new Map(U.map(se=>[se.name,se])),Ue=[];for(const se of j){const Ve=be.get(se);Ve&&(Ue.push(Ve),be.delete(se))}return[...Ue,...be.values()]},[j]),$=i.useCallback((U,be)=>{U.dataTransfer.effectAllowed="move",U.dataTransfer.setData("text/plain",be),x(be)},[]),D=i.useCallback((U,be)=>{if(!C||C===be)return;U.preventDefault(),U.dataTransfer.dropEffect="move";const{top:Ue,height:se}=U.currentTarget.getBoundingClientRect(),Ve=Ue+se/2,Le=U.clientY<Ve?"before":"after";R(be),E(Le)},[C]),N=i.useCallback((U,be)=>{U.preventDefault();const Ue=C??U.dataTransfer.getData("text/plain");if(!Ue||Ue===be){R(null),E(null);return}const Ve=M(r).map(Ke=>Ke.name).filter(Ke=>Ke!==Ue),Le=Ve.indexOf(be);if(Le<0){R(null),E(null);return}const ct=O==="after"?Le+1:Le;Ve.splice(ct,0,Ue),ag(Ve,s),S(Ve),R(null),E(null)},[C,O,s,r,M]),W=i.useCallback(()=>{x(null),R(null),E(null)},[]),de=i.useCallback((U,be)=>{const Ue=M(r).map(Ke=>Ke.name),se=Ue.indexOf(U),Ve=se+be;if(se<0||Ve<0||Ve>=Ue.length)return;const Le=[...Ue],[ct]=Le.splice(se,1);Le.splice(Ve,0,ct),ag(Le,s),S(Le)},[s,r,M]),me=i.useCallback(async()=>{h(!0),await d(),h(!1)},[d]);i.useEffect(()=>{if(!e)return;const U=be=>{be.key==="Escape"&&n()};return document.addEventListener("keydown",U),()=>document.removeEventListener("keydown",U)},[e,n]);const Ne=i.useCallback(U=>{U.target===U.currentTarget&&n()},[n]);if(!e)return null;const ve=!!(a&&m),Me=8,ie=12,Z=P?.width??420,fe=ve?Math.min((a?.bottom??0)+Me,window.innerHeight-ie):void 0,Q=ve?Math.max(8,(a?.right??0)-Z):void 0,F=m&&P?{width:P.width,height:P.height}:{},X=M(r),re=t.jsxs("div",{ref:G,className:`usage-modal${ve?" usage-modal--popover":" modal"}`,"data-testid":"usage-modal",style:ve?{position:"fixed",top:fe,left:Q,...F}:F,children:[t.jsxs("div",{className:"modal-header",children:[t.jsxs("div",{className:"usage-header",children:[t.jsx(Vs,{size:18,className:"usage-header-icon"}),t.jsx("h3",{children:"Usage"})]}),t.jsxs("div",{className:"usage-header-actions",children:[t.jsxs("div",{className:"usage-view-toggle",role:"group","aria-label":"Usage view mode",children:[t.jsx("button",{className:`usage-view-toggle-btn ${w==="used"?"active":""}`,onClick:()=>Y("used"),"aria-pressed":w==="used","data-testid":"usage-view-toggle-used",children:"Used"}),t.jsx("button",{className:`usage-view-toggle-btn ${w==="remaining"?"active":""}`,onClick:()=>Y("remaining"),"aria-pressed":w==="remaining","data-testid":"usage-view-toggle-remaining",children:"Remaining"})]}),t.jsx("button",{className:"modal-close",onClick:n,"aria-label":"Close usage modal","data-testid":"usage-modal-close",children:t.jsx(bn,{size:20})})]})]}),t.jsx("div",{className:"usage-content",ref:_,children:(o||!A.current&&!l)&&r.length===0?t.jsx(QD,{}):l&&r.length===0?t.jsxs("div",{className:"usage-error",children:[t.jsx("p",{children:"Failed to load usage data"}),t.jsx("p",{className:"usage-error-message",children:l}),t.jsx("button",{className:"btn btn-sm",onClick:me,children:"Retry"})]}):r.length===0?t.jsxs("div",{className:"usage-empty",children:[t.jsx("p",{children:"No AI providers configured"}),t.jsx("p",{className:"usage-empty-hint",children:"Configure authentication in Settings to see usage data."})]}):t.jsx("div",{className:"usage-providers",children:X.map((U,be)=>t.jsx(YD,{provider:U,viewMode:w,hiddenWindows:b,onToggleWindow:ge,onShowAllHidden:L,isDragging:C===U.name,isDragOver:k===U.name,dragOverPosition:k===U.name?O:null,onDragStart:Ue=>$(Ue,U.name),onDragOver:Ue=>D(Ue,U.name),onDragLeave:()=>{k===U.name&&(R(null),E(null))},onDrop:Ue=>N(Ue,U.name),onDragEnd:W,isTouchReorderMode:p,canMoveUp:be>0,canMoveDown:be<X.length-1,onMoveUp:()=>de(U.name,-1),onMoveDown:()=>de(U.name,1)},U.name))})}),t.jsxs("div",{className:"modal-actions usage-actions",children:[t.jsx("div",{className:"modal-actions-left usage-actions-left",children:t.jsx("div",{className:"usage-last-updated",children:c&&t.jsxs("span",{children:["Last updated: ",c.toLocaleTimeString()]})})}),t.jsxs("div",{className:"modal-actions-right usage-actions-right",children:[t.jsxs("button",{className:"btn btn-sm",onClick:me,disabled:o||u,"data-testid":"usage-refresh-btn",children:[t.jsx(us,{size:14,className:u?"spin":"",style:{marginRight:6}}),"Refresh"]}),t.jsx("button",{className:"btn btn-primary btn-sm",onClick:n,children:"Close"})]})]})]});return ve?t.jsxs(t.Fragment,{children:[t.jsx("div",{className:"usage-popover-backdrop",onClick:n,"data-testid":"usage-modal-overlay"}),re]}):t.jsx("div",{className:"modal-overlay open",onClick:Ne,"data-testid":"usage-modal-overlay",children:re})}function Wv(e){if(e<1e3)return`${e}ms`;const n=Math.floor(e/1e3);if(n<60)return`${n}s`;const s=Math.floor(n/60),a=n%60;if(s<60)return a>0?`${s}m ${a}s`:`${s}m`;const r=Math.floor(s/60),o=s%60;return o>0?`${r}h ${o}m`:`${r}h`}function dc(e){const n=Date.now(),s=new Date(e).getTime(),a=n-s;if(a<0){const r=Math.abs(a);return r<6e4?"in a moment":r<36e5?`in ${Math.floor(r/6e4)}m`:r<864e5?`in ${Math.floor(r/36e5)}h`:`in ${Math.floor(r/864e5)}d`}return a<6e4?"just now":a<36e5?`${Math.floor(a/6e4)}m ago`:a<864e5?`${Math.floor(a/36e5)}h ago`:`${Math.floor(a/864e5)}d ago`}const ZD={cron:"var(--color-blue, #3b82f6)",webhook:"var(--color-purple, #a855f7)",api:"var(--color-green, #22c55e)",manual:"var(--color-gray, #6b7280)"},Gv={cron:"Cron",webhook:"Webhook",api:"API",manual:"Manual"},eL={cron:rb,webhook:bb,api:ob,manual:as},tL={parallel:"Concurrent",queue:"Queued",reject:"Exclusive"},nL={run:"Catch up",skip:"Skip missed",run_one:"Catch up (latest)"};function sL({result:e}){const n=e.completedAt&&e.startedAt?new Date(e.completedAt).getTime()-new Date(e.startedAt).getTime():0;return t.jsxs("span",{className:`schedule-run-badge ${e.success?"success":"failure"}`,children:[e.success?t.jsx(Zn,{size:12}):t.jsx(qo,{size:12}),t.jsx("span",{children:e.success?"Success":"Failed"}),n>0&&t.jsx("span",{className:"schedule-run-duration",children:Wv(n)})]})}function iL({result:e,index:n}){const[s,a]=i.useState(!1),r=e.completedAt&&e.startedAt?new Date(e.completedAt).getTime()-new Date(e.startedAt).getTime():0;return t.jsxs("div",{className:"schedule-history-item",children:[t.jsxs("button",{className:"schedule-history-header",onClick:()=>a(!s),"aria-expanded":s,"aria-label":`Run #${n+1}: ${e.success?"succeeded":"failed"} ${dc(e.startedAt)}`,children:[t.jsx("span",{className:`schedule-history-status ${e.success?"success":"failure"}`,children:e.success?t.jsx(Zn,{size:12}):t.jsx(qo,{size:12})}),t.jsx("span",{className:"schedule-history-time",children:dc(e.startedAt)}),e.triggerType&&t.jsx("span",{className:"routine-history-trigger-type",children:Gv[e.triggerType]}),t.jsx("span",{className:"schedule-history-duration",children:Wv(r)}),s?t.jsx(mi,{size:12}):t.jsx(vn,{size:12})]}),s&&t.jsxs("div",{className:"schedule-history-detail",children:[e.output&&t.jsx("pre",{className:"schedule-history-output",children:e.output}),e.error&&t.jsx("div",{className:"schedule-history-error",children:e.error})]})]})}function aL({routine:e,onEdit:n,onDelete:s,onRun:a,onToggle:r,running:o,lastRunOutput:l}){const[c,d]=i.useState(!1),{confirm:u}=ti(),h=i.useCallback(async()=>{await u({title:"Delete Routine",message:`Delete routine "${e.name}"? This cannot be undone.`,danger:!0})&&s(e)},[e,s,u]),m=ZD[e.trigger.type],f=eL[e.trigger.type],p=e.trigger.type==="cron"?("cronExpression"in e.trigger?e.trigger.cronExpression:void 0)||e.cronExpression||"":e.cronExpression||"";return t.jsxs("div",{className:`routine-card${e.enabled?"":" disabled"}${o?" running":""}`,children:[t.jsxs("div",{className:"routine-card-header",children:[t.jsxs("div",{className:"routine-card-info",children:[t.jsxs("div",{className:"routine-card-name-row",children:[t.jsx("span",{className:"routine-card-name",children:e.name}),t.jsxs("span",{className:"routine-trigger-badge",style:{borderColor:m,color:m},children:[t.jsx(f,{size:10}),Gv[e.trigger.type]]}),e.scope&&t.jsxs("span",{className:`routine-scope-badge${e.scope==="global"?" global":" project"}`,title:`${e.scope==="global"?"Global":"Project"}-scoped routine`,children:[e.scope==="global"?t.jsx(xc,{size:10}):t.jsx(ws,{size:10}),e.scope]})]}),e.description&&t.jsx("p",{className:"routine-card-description",children:e.description})]}),t.jsxs("div",{className:"routine-card-actions",children:[t.jsx("button",{className:"btn-icon",onClick:()=>a(e),disabled:o,title:o?"Running…":"Run now","aria-label":o?"Running…":`Run ${e.name} now`,children:o?t.jsx(St,{className:"spinner"}):t.jsx(is,{})}),t.jsx("button",{className:"btn-icon",onClick:()=>r(e),title:e.enabled?"Disable":"Enable","aria-label":e.enabled?`Disable ${e.name}`:`Enable ${e.name}`,"aria-pressed":e.enabled,children:e.enabled?t.jsx(di,{}):t.jsx(is,{})}),t.jsx("button",{className:"btn-icon",onClick:()=>n(e),title:"Edit","aria-label":`Edit ${e.name}`,children:t.jsx(Os,{})}),t.jsx("button",{className:"btn-icon",onClick:h,title:"Delete","aria-label":`Delete ${e.name}`,children:t.jsx(In,{})})]})]}),t.jsxs("div",{className:"routine-card-meta",children:[e.steps&&e.steps.length>0?t.jsxs("div",{className:"routine-meta-item",children:[t.jsx(Fa,{size:12}),t.jsxs("span",{className:"routine-policy-badge",children:[e.steps.length," step",e.steps.length===1?"":"s"]})]}):e.command?t.jsx("div",{className:"routine-meta-item routine-meta-command-preview",title:e.command,children:t.jsx("code",{className:"routine-cron",children:e.command})}):null,e.trigger.type==="cron"&&p&&t.jsxs("div",{className:"routine-meta-item",children:[t.jsx(Yi,{size:12}),t.jsx("code",{className:"routine-cron",children:p})]}),t.jsx("div",{className:"routine-meta-item",children:t.jsx("span",{className:"routine-policy-badge",title:`Execution policy: ${e.executionPolicy}`,children:tL[e.executionPolicy]})}),t.jsx("div",{className:"routine-meta-item",children:t.jsx("span",{className:"routine-policy-badge",title:`Catch-up policy: ${e.catchUpPolicy}`,children:nL[e.catchUpPolicy]})}),e.nextRunAt&&e.enabled&&t.jsxs("div",{className:"routine-meta-item",children:[t.jsx("span",{className:"routine-meta-label",children:"Next:"}),t.jsx("span",{title:e.nextRunAt,children:dc(e.nextRunAt)})]}),e.lastRunAt&&t.jsxs("div",{className:"routine-meta-item",children:[t.jsx("span",{className:"routine-meta-label",children:"Last:"}),t.jsx("span",{title:e.lastRunAt,children:dc(e.lastRunAt)})]}),e.lastRunResult&&t.jsx(sL,{result:e.lastRunResult}),t.jsxs("div",{className:"routine-meta-item",children:[t.jsx("span",{className:"routine-meta-label",children:"Runs:"}),t.jsx("span",{children:e.runCount})]})]}),l&&t.jsxs("div",{className:`routine-run-output ${l.success?"success":"failure"}`,children:[l.output&&t.jsx("pre",{className:"routine-run-output-text",children:l.output}),l.error&&t.jsx("div",{className:"routine-run-output-error",children:l.error})]}),e.runHistory.length>0&&t.jsxs("div",{className:"routine-card-history",children:[t.jsxs("button",{className:"schedule-history-toggle",onClick:()=>d(g=>!g),"aria-expanded":c,children:[c?t.jsx(mi,{size:12}):t.jsx(vn,{size:12}),t.jsxs("span",{children:["Run History (",e.runHistory.length,")"]})]}),c&&t.jsxs("div",{className:"schedule-history-list",children:[e.runHistory.slice(0,10).map((g,w)=>t.jsx(iL,{result:g,index:w},`${g.startedAt}-${w}`)),e.runHistory.length>10&&t.jsxs("div",{className:"schedule-history-more",children:["…and ",e.runHistory.length-10," more"]})]})]})]})}function rL({type:e,size:n=12}){return e==="command"?t.jsxs("span",{className:"step-type-badge step-type-command",title:"Command step",children:[t.jsx(Ji,{size:n}),t.jsx("span",{children:"Command"})]}):e==="create-task"?t.jsxs("span",{className:"step-type-badge step-type-create-task",title:"Create Task step",children:[t.jsx(xk,{size:n}),t.jsx("span",{children:"Create Task"})]}):t.jsxs("span",{className:"step-type-badge step-type-ai-prompt",title:"AI Prompt step",children:[t.jsx(cs,{size:n}),t.jsx("span",{children:"AI Prompt"})]})}function Kd(){return typeof crypto<"u"&&typeof crypto.randomUUID=="function"?crypto.randomUUID():`step-${Date.now()}-${Math.random().toString(36).slice(2,11)}`}function oL(e){return e==="command"?{id:Kd(),type:e,name:"New Command Step",command:"",continueOnFailure:!1}:e==="ai-prompt"?{id:Kd(),type:e,name:"New AI Prompt Step",prompt:"",continueOnFailure:!1}:{id:Kd(),type:e,name:"New Create Task Step",taskDescription:"",taskColumn:"triage",continueOnFailure:!1}}function lL({step:e,onSave:n,onCancel:s}){const[a,r]=i.useState(e.name),[o,l]=i.useState(e.type),[c,d]=i.useState(e.command??""),[u,h]=i.useState(e.prompt??""),[m,f]=i.useState(e.modelProvider??""),[p,g]=i.useState(e.modelId??""),[w,v]=i.useState(e.taskTitle??""),[b,y]=i.useState(e.taskDescription??""),[j,S]=i.useState(e.taskColumn??"triage"),[C,x]=i.useState(e.timeoutMs),[k,R]=i.useState(e.continueOnFailure??!1),[O,E]=i.useState({}),[_,G]=i.useState([]),[H,A]=i.useState(!1),[P,q]=i.useState(null);i.useEffect(()=>{let $=!1;return A(!0),q(null),Bs().then(D=>{$||G(D.models)}).catch(D=>{$||q(D instanceof Error?D.message:"Failed to load models")}).finally(()=>{$||A(!1)}),()=>{$=!0}},[]);const Y=i.useCallback(()=>{const $={};return a.trim()||($.name="Step name is required"),o==="command"&&!c.trim()&&($.command="Command is required"),o==="ai-prompt"&&!u.trim()&&($.prompt="Prompt is required"),o==="create-task"&&!b.trim()&&($.taskDescription="Task description is required"),(o==="ai-prompt"||o==="create-task")&&(m||p)&&(!m||!p)&&($.modelProvider="Both model provider and model ID must be set together"),C!==void 0&&C<1e3&&($.timeoutMs="Timeout must be at least 1 second (1000ms)"),E($),Object.keys($).length===0},[a,o,c,u,b,m,p,C]),ge=m&&p?`${m}/${p}`:"",L=i.useCallback($=>{if(!$)f(""),g("");else{const D=$.indexOf("/");D!==-1&&(f($.slice(0,D)),g($.slice(D+1)))}},[]),M=i.useCallback(()=>{if(!Y())return;const $={...e,name:a.trim(),type:o,command:o==="command"?c.trim():void 0,prompt:o==="ai-prompt"?u.trim():void 0,taskTitle:o==="create-task"&&w.trim()?w.trim():void 0,taskDescription:o==="create-task"&&b.trim()?b.trim():void 0,taskColumn:o==="create-task"?j:void 0,modelProvider:(o==="ai-prompt"||o==="create-task")&&m.trim()?m.trim():void 0,modelId:(o==="ai-prompt"||o==="create-task")&&p.trim()?p.trim():void 0,timeoutMs:C||void 0,continueOnFailure:k};o!=="ai-prompt"&&delete $.prompt,o!=="create-task"&&(delete $.taskTitle,delete $.taskDescription,delete $.taskColumn),n($)},[Y,n,e,a,o,c,u,w,b,j,m,p,C,k]);return t.jsxs("div",{className:"step-editor",children:[t.jsxs("div",{className:"form-group",children:[t.jsx("label",{htmlFor:`step-name-${e.id}`,children:"Step Name"}),t.jsx("input",{id:`step-name-${e.id}`,type:"text",placeholder:"e.g. Run tests",value:a,onChange:$=>r($.target.value),"aria-invalid":!!O.name}),O.name&&t.jsx("small",{className:"field-error",children:O.name})]}),t.jsxs("div",{className:"form-group",children:[t.jsx("label",{htmlFor:`step-type-${e.id}`,children:"Step Type"}),t.jsxs("select",{id:`step-type-${e.id}`,value:o,onChange:$=>l($.target.value),children:[t.jsx("option",{value:"command",children:"Command"}),t.jsx("option",{value:"ai-prompt",children:"AI Prompt"}),t.jsx("option",{value:"create-task",children:"Create Task"})]})]}),o==="command"&&t.jsxs("div",{className:"form-group",children:[t.jsx("label",{htmlFor:`step-command-${e.id}`,children:"Command"}),t.jsx("textarea",{id:`step-command-${e.id}`,placeholder:"e.g. npm test",value:c,onChange:$=>d($.target.value),rows:2,"aria-invalid":!!O.command}),O.command&&t.jsx("small",{className:"field-error",children:O.command})]}),o==="ai-prompt"&&t.jsxs(t.Fragment,{children:[t.jsxs("div",{className:"form-group",children:[t.jsx("label",{htmlFor:`step-prompt-${e.id}`,children:"Prompt"}),t.jsx("textarea",{id:`step-prompt-${e.id}`,placeholder:"e.g. Summarize the test results and highlight any failures",value:u,onChange:$=>h($.target.value),rows:3,"aria-invalid":!!O.prompt}),O.prompt&&t.jsx("small",{className:"field-error",children:O.prompt})]}),t.jsxs("div",{className:"form-group",children:[t.jsx("label",{htmlFor:`step-model-${e.id}`,children:"Model (optional)"}),t.jsx(Ns,{id:`step-model-${e.id}`,label:"Model",models:_,value:ge,onChange:L,placeholder:"Use default",disabled:H}),P&&t.jsx("small",{className:"field-error",children:P}),t.jsx("small",{children:"AI model for this step. Uses default if not selected."})]})]}),o==="create-task"&&t.jsxs(t.Fragment,{children:[t.jsxs("div",{className:"form-group",children:[t.jsx("label",{htmlFor:`step-task-title-${e.id}`,children:"Task Title (optional)"}),t.jsx("input",{id:`step-task-title-${e.id}`,type:"text",placeholder:"e.g. Review weekly dependencies",value:w,onChange:$=>v($.target.value)}),t.jsx("small",{children:"Leave blank to auto-summarize from description"})]}),t.jsxs("div",{className:"form-group",children:[t.jsx("label",{htmlFor:`step-task-description-${e.id}`,children:"Task Description *"}),t.jsx("textarea",{id:`step-task-description-${e.id}`,placeholder:"e.g. Check all npm dependencies for security vulnerabilities and update outdated packages",value:b,onChange:$=>y($.target.value),rows:4,"aria-invalid":!!O.taskDescription}),O.taskDescription&&t.jsx("small",{className:"field-error",children:O.taskDescription})]}),t.jsxs("div",{className:"form-group",children:[t.jsx("label",{htmlFor:`step-task-column-${e.id}`,children:"Target Column"}),t.jsxs("select",{id:`step-task-column-${e.id}`,value:j,onChange:$=>S($.target.value),children:[t.jsx("option",{value:"triage",children:"Triage"}),t.jsx("option",{value:"todo",children:"To Do"})]}),t.jsx("small",{children:"Column where the new task will be created"})]}),t.jsxs("div",{className:"form-group",children:[t.jsx("label",{htmlFor:`step-task-model-${e.id}`,children:"Executor Model (optional)"}),t.jsx(Ns,{id:`step-task-model-${e.id}`,label:"Model",models:_,value:ge,onChange:L,placeholder:"Use default",disabled:H}),P&&t.jsx("small",{className:"field-error",children:P}),O.modelProvider&&t.jsx("small",{className:"field-error",children:O.modelProvider}),t.jsx("small",{children:"AI model for executing the created task. Uses default if not selected."})]})]}),t.jsxs("div",{className:"form-group",children:[t.jsx("label",{htmlFor:`step-timeout-${e.id}`,children:"Timeout (ms, optional)"}),t.jsx("input",{id:`step-timeout-${e.id}`,type:"number",min:1e3,step:1e3,placeholder:"Override schedule timeout",value:C??"",onChange:$=>x($.target.value?Number($.target.value):void 0),"aria-invalid":!!O.timeoutMs}),O.timeoutMs&&t.jsx("small",{className:"field-error",children:O.timeoutMs})]}),t.jsxs("div",{className:"form-group",children:[t.jsxs("label",{htmlFor:`step-continue-${e.id}`,className:"checkbox-label",children:[t.jsx("input",{id:`step-continue-${e.id}`,type:"checkbox",checked:k,onChange:$=>R($.target.checked)}),"Continue on failure"]}),t.jsx("small",{children:"If checked, the next step will run even if this one fails"})]}),t.jsxs("div",{className:"step-editor-actions",children:[t.jsx("button",{type:"button",className:"btn btn-sm",onClick:s,children:"Cancel"}),t.jsx("button",{type:"button",className:"btn btn-primary btn-sm",onClick:M,children:"Save Step"})]})]})}function cL({steps:e,onChange:n,onEditingChange:s}){const[a,r]=i.useState(null);i.useEffect(()=>{s?.(a!==null)},[a,s]);const o=i.useCallback(u=>{const h=oL(u);n([...e,h]),r(h.id)},[e,n]),l=i.useCallback(u=>{n(e.filter(h=>h.id!==u)),a===u&&r(null)},[e,n,a]),c=i.useCallback((u,h)=>{const m=e.findIndex(g=>g.id===u);if(m<0)return;const f=h==="up"?m-1:m+1;if(f<0||f>=e.length)return;const p=[...e];[p[m],p[f]]=[p[f],p[m]],n(p)},[e,n]),d=i.useCallback(u=>{n(e.map(h=>h.id===u.id?u:h)),r(null)},[e,n]);return t.jsxs("div",{className:"steps-editor",children:[t.jsx("div",{className:"steps-editor-header",children:t.jsxs("span",{className:"steps-editor-title",children:["Steps (",e.length,")"]})}),e.length===0&&t.jsx("div",{className:"steps-empty-state",children:t.jsx("p",{children:"No steps added yet. Add a command or AI prompt step to get started."})}),t.jsx("div",{className:"steps-list",children:e.map((u,h)=>t.jsx("div",{className:"step-card",children:a===u.id?t.jsx(lL,{step:u,onSave:d,onCancel:()=>r(null)}):t.jsxs("div",{className:"step-card-row",children:[t.jsx("div",{className:"step-card-drag",children:t.jsx(yc,{size:14})}),t.jsx("span",{className:"step-card-index",children:h+1}),t.jsx(rL,{type:u.type}),t.jsx("span",{className:"step-card-name",children:u.name}),u.continueOnFailure&&t.jsx("span",{className:"step-card-flag",title:"Continues on failure",children:"⚡"}),t.jsxs("div",{className:"step-card-actions",children:[t.jsx("button",{type:"button",className:"btn-icon",onClick:()=>c(u.id,"up"),disabled:h===0,title:"Move up","aria-label":`Move ${u.name} up`,children:t.jsx(mi,{})}),t.jsx("button",{type:"button",className:"btn-icon",onClick:()=>c(u.id,"down"),disabled:h===e.length-1,title:"Move down","aria-label":`Move ${u.name} down`,children:t.jsx(vn,{})}),t.jsx("button",{type:"button",className:"btn-icon",onClick:()=>r(u.id),title:"Edit","aria-label":`Edit ${u.name}`,children:t.jsx(Os,{})}),t.jsx("button",{type:"button",className:"btn-icon",onClick:()=>l(u.id),title:"Delete","aria-label":`Delete ${u.name}`,children:t.jsx(In,{})})]})]})},u.id))}),t.jsxs("div",{className:"steps-add-buttons",children:[t.jsxs("button",{type:"button",className:"btn btn-sm",onClick:()=>o("command"),children:[t.jsx(Tn,{size:14}),"Add Command Step"]}),t.jsxs("button",{type:"button",className:"btn btn-sm",onClick:()=>o("ai-prompt"),children:[t.jsx(Tn,{size:14}),"Add AI Prompt Step"]}),t.jsxs("button",{type:"button",className:"btn btn-sm",onClick:()=>o("create-task"),children:[t.jsx(Tn,{size:14}),"Add Create Task Step"]})]})]})}const Kv={hourly:"0 * * * *",daily:"0 0 * * *",weekly:"0 0 * * 1",monthly:"0 0 1 * *"},dL={hourly:"Every hour",daily:"Every day (midnight)",weekly:"Every week (Monday)",monthly:"Every month (1st)",custom:"Custom cron expression"};function uL(e){const n=e.trim();for(const[s,a]of Object.entries(Kv))if(a===n)return s;return"custom"}function mL(e){const n=e.trim().split(/\s+/);return n.length!==5?!1:n.every(s=>/^[\d*,/-]+$/.test(s))}function hL(e,n,s,a,r){switch(e){case"cron":return{type:"cron",cronExpression:n};case"webhook":return{type:"webhook",webhookPath:s||"/trigger/"+Math.random().toString(36).slice(2,10),secret:a||void 0};case"api":return{type:"api",endpoint:r||"/api/routine/"+Math.random().toString(36).slice(2,10)};case"manual":return{type:"manual"}}}function pL(e){const n=e.trigger;switch(n.type){case"cron":return{triggerType:"cron",cronExpression:n.cronExpression,webhookPath:"",webhookSecret:"",endpoint:""};case"webhook":return{triggerType:"webhook",cronExpression:"",webhookPath:n.webhookPath,webhookSecret:n.secret||"",endpoint:""};case"api":return{triggerType:"api",cronExpression:"",webhookPath:"",webhookSecret:"",endpoint:n.endpoint};case"manual":return{triggerType:"manual",cronExpression:"",webhookPath:"",webhookSecret:"",endpoint:""}}}const fL=[{value:"parallel",label:"Allow concurrent runs"},{value:"queue",label:"Queue after current (one at a time)"},{value:"reject",label:"Reject new runs while running"}],gL=[{value:"skip",label:"Skip missed runs"},{value:"run_one",label:"Run the most recent missed run"},{value:"run",label:"Run all missed runs"}];function rg(){return typeof crypto<"u"&&typeof crypto.randomUUID=="function"?crypto.randomUUID():`step-${Date.now()}-${Math.random().toString(36).slice(2,11)}`}function og({routine:e,onSubmit:n,onCancel:s,scope:a,projectId:r,onScopeChange:o}){const l=!!e,c=e?pL(e):{triggerType:"cron",cronExpression:"0 * * * *",webhookPath:"",webhookSecret:"",endpoint:""},[d,u]=i.useState(e?.name??""),[h,m]=i.useState(e?.description??""),[f,p]=i.useState(c.triggerType),[g,w]=i.useState(c.cronExpression),[v,b]=i.useState(()=>c.triggerType!=="cron"?"custom":uL(c.cronExpression)),[y,j]=i.useState(c.webhookPath),[S,C]=i.useState(c.webhookSecret),[x,k]=i.useState(c.endpoint),[R,O]=i.useState(e?.executionPolicy??"queue"),[E,_]=i.useState(e?.catchUpPolicy??"run_one"),[G,H]=i.useState(e?.enabled??!0),A=e?.steps&&e.steps.length===1&&e.steps[0].type==="ai-prompt"&&!e.command,P=e?.steps&&e.steps.length===1&&e.steps[0].type==="create-task"&&!e.command,[q,Y]=i.useState(e?.steps&&e.steps.length>0&&!A&&!P?"advanced":"simple"),[ge,L]=i.useState(()=>A?"ai-prompt":P?"create-task":"command"),[M,$]=i.useState(e?.command??""),[D,N]=i.useState(e?.steps??[]),[W,de]=i.useState(!1),[me,Ne]=i.useState(e?.timeoutMs??3e5),[ve,Me]=i.useState(A?e.steps?.[0]?.prompt??"":""),[ie,ye]=i.useState(P?e.steps?.[0]?.taskTitle??"":""),[Z,fe]=i.useState(P?e.steps?.[0]?.taskDescription??"":""),[Q,F]=i.useState(P?e.steps?.[0]?.taskColumn??"triage":"triage"),[X,re]=i.useState(A||P?e.steps?.[0]?.modelProvider??"":""),[U,be]=i.useState(A||P?e.steps?.[0]?.modelId??"":""),[Ue,se]=i.useState([]),[Ve,Le]=i.useState(!1),[ct,Ke]=i.useState(null),[oe,Te]=i.useState(a??"global"),[Fe,mt]=i.useState({}),[We,he]=i.useState(!1),pe=i.useRef(!0);i.useEffect(()=>()=>{pe.current=!1},[]),i.useEffect(()=>{a&&Te(a)},[a]),i.useEffect(()=>{let xe=!1;return Le(!0),Ke(null),Bs().then(dt=>{xe||se(dt.models)}).catch(dt=>{xe||Ke(dt instanceof Error?dt.message:"Failed to load models")}).finally(()=>{xe||Le(!1)}),()=>{xe=!0}},[]);const De=X&&U?`${X}/${U}`:"",ut=i.useCallback(xe=>{if(!xe){re(""),be("");return}const dt=xe.indexOf("/");dt!==-1&&(re(xe.slice(0,dt)),be(xe.slice(dt+1)))},[]),ht=i.useCallback(()=>{const xe={};if(d.trim()||(xe.name="Name is required"),oe==="project"&&!r&&(xe.scope="Project-specific entries require an active project."),f==="cron"&&v==="custom"&&(g.trim()?mL(g)||(xe.cronExpression="Invalid cron format — expected 5 fields (e.g. '0 */6 * * *')"):xe.cronExpression="Cron expression is required"),f==="webhook"&&!y.trim()&&(xe.webhookPath="Webhook path is required"),f==="api"&&!x.trim()&&(xe.endpoint="API endpoint is required"),q==="simple")ge==="command"&&!M.trim()&&(xe.command="Command is required"),ge==="ai-prompt"&&!ve.trim()&&(xe.prompt="Prompt is required"),ge==="create-task"&&!Z.trim()&&(xe.taskDescription="Task description is required"),(X.trim()&&!U.trim()||!X.trim()&&U.trim())&&(xe.model="Both model provider and model ID must be set, or both must be empty");else{D.length===0&&(xe.steps="At least one step is required"),W&&(xe.stepsEditing="Please save or cancel all step edits before saving the routine");const dt=[];D.forEach((Je,ke)=>{Je.name?.trim()||dt.push(`Step ${ke+1}: Name is required`),Je.type==="command"&&!Je.command?.trim()&&dt.push(`Step ${ke+1}: Command is required`),Je.type==="ai-prompt"&&!Je.prompt?.trim()&&dt.push(`Step ${ke+1}: Prompt is required`),Je.type==="create-task"&&!Je.taskDescription?.trim()&&dt.push(`Step ${ke+1}: Task description is required`)}),dt.length>0&&(xe.steps=dt.join("; "))}return me<1e3&&(xe.timeoutMs="Timeout must be at least 1 second (1000ms)"),mt(xe),Object.keys(xe).length===0},[d,f,g,v,y,x,oe,r,q,ge,M,ve,Z,X,U,D,W,me]),et=i.useCallback(async xe=>{if(xe.preventDefault(),!!ht()){he(!0);try{let dt=e?.scope??oe??(r?"project":"global");dt==="project"&&!r&&(dt="global");const Je=hL(f,g,y,S,x);let ke,nt;q==="simple"?ge==="command"?ke=M.trim()||void 0:ge==="ai-prompt"?nt=[{id:rg(),type:"ai-prompt",name:d.trim(),prompt:ve.trim(),modelProvider:X.trim()||void 0,modelId:U.trim()||void 0}]:nt=[{id:rg(),type:"create-task",name:d.trim(),taskTitle:ie.trim()||void 0,taskDescription:Z.trim(),taskColumn:Q,modelProvider:X.trim()||void 0,modelId:U.trim()||void 0}]:nt=D;const bt={name:d.trim(),agentId:e?.agentId??"",description:h.trim()||void 0,trigger:Je,command:ke,steps:nt,timeoutMs:me,executionPolicy:R,catchUpPolicy:E,enabled:G,scope:dt};await n(bt)}finally{pe.current&&he(!1)}}},[ht,n,d,h,f,g,y,S,x,q,ge,M,ve,X,U,ie,Z,Q,D,me,R,E,G,oe,r,e?.scope,e?.agentId]),vt="routine-name-error",Oe="routine-cron-error",tt="routine-webhook-error",ft="routine-endpoint-error",Mt="routine-command-error",yt="routine-prompt-error",Ge="routine-task-description-error",K="routine-model-error",ue="routine-timeout-error",ot=i.useCallback(xe=>{b(xe),xe!=="custom"&&w(Kv[xe])},[]);return t.jsxs("form",{className:"routine-form",onSubmit:et,noValidate:!0,children:[t.jsx("h4",{className:"settings-section-heading",children:l?"Edit Routine":"New Routine"}),t.jsxs("div",{className:"form-group",children:[t.jsx("label",{htmlFor:"routine-name",children:"Name"}),t.jsx("input",{id:"routine-name",type:"text",placeholder:"e.g. Daily standup reminder",value:d,onChange:xe=>u(xe.target.value),"aria-invalid":!!Fe.name,"aria-describedby":Fe.name?vt:void 0}),Fe.name&&t.jsx("small",{id:vt,className:"field-error",children:Fe.name})]}),t.jsxs("div",{className:"form-group",children:[t.jsx("label",{htmlFor:"routine-description",children:"Description (optional)"}),t.jsx("textarea",{id:"routine-description",placeholder:"What does this routine do?",value:h,onChange:xe=>m(xe.target.value),rows:2})]}),t.jsxs("div",{className:"form-group",children:[t.jsx("label",{children:"Scope"}),t.jsxs("div",{className:"routine-scope-toggle",role:"radiogroup","aria-label":"Routine scope",children:[t.jsxs("button",{type:"button",className:`routine-scope-btn${oe==="global"?" active":""}`,onClick:()=>{Te("global"),o?.("global")},role:"radio","aria-checked":oe==="global"?"true":"false",disabled:!!e?.scope,title:e?.scope?`Scope is locked to ${e.scope} for existing routines`:"Global scope",children:[t.jsx(xc,{size:12}),"Global"]}),t.jsxs("button",{type:"button",className:`routine-scope-btn${oe==="project"?" active":""}`,onClick:()=>{Te("project"),o?.("project")},role:"radio","aria-checked":oe==="project"?"true":"false",disabled:!!e?.scope||!r,title:e?.scope?`Scope is locked to ${e.scope} for existing routines`:r?"Project scope":"Select a project to enable project scope",children:[t.jsx(ws,{size:12}),"Project"]})]}),t.jsx("small",{children:!r&&!e?.scope?"No active project. Routines will be created at global scope.":oe==="project"&&r?"This routine will be scoped to the current project.":"This routine will be created at global scope."}),Fe.scope&&t.jsx("small",{className:"field-error",children:Fe.scope})]}),t.jsxs("div",{className:"form-group",children:[t.jsx("label",{children:"Trigger Type"}),t.jsxs("div",{className:"routine-trigger-type-selector",role:"radiogroup","aria-label":"Trigger type",children:[t.jsxs("button",{type:"button",className:`routine-trigger-btn${f==="cron"?" active":""}`,onClick:()=>p("cron"),role:"radio","aria-checked":f==="cron",children:[t.jsx(rb,{size:14}),"Cron"]}),t.jsxs("button",{type:"button",className:`routine-trigger-btn${f==="webhook"?" active":""}`,onClick:()=>p("webhook"),role:"radio","aria-checked":f==="webhook",children:[t.jsx(bb,{size:14}),"Webhook"]}),t.jsxs("button",{type:"button",className:`routine-trigger-btn${f==="api"?" active":""}`,onClick:()=>p("api"),role:"radio","aria-checked":f==="api",children:[t.jsx(ob,{size:14}),"API"]}),t.jsxs("button",{type:"button",className:`routine-trigger-btn${f==="manual"?" active":""}`,onClick:()=>p("manual"),role:"radio","aria-checked":f==="manual",children:[t.jsx(as,{size:14}),"Manual"]})]})]}),f==="cron"&&t.jsxs("div",{className:"form-group",children:[t.jsx("label",{htmlFor:"routine-frequency",children:"Frequency"}),t.jsx("select",{id:"routine-frequency",value:v,onChange:xe=>ot(xe.target.value),children:Object.entries(dL).map(([xe,dt])=>t.jsx("option",{value:xe,children:dt},xe))}),t.jsx("label",{htmlFor:"routine-cron",children:"Cron Expression"}),t.jsx("input",{id:"routine-cron",type:"text",placeholder:"* * * * *",value:g,onChange:xe=>w(xe.target.value),disabled:v!=="custom","aria-invalid":!!Fe.cronExpression,"aria-describedby":Fe.cronExpression?Oe:void 0}),Fe.cronExpression?t.jsx("small",{id:Oe,className:"field-error",children:Fe.cronExpression}):t.jsx("small",{children:v==="custom"?t.jsxs(t.Fragment,{children:["min hour day month weekday — ",t.jsx("a",{href:"https://crontab.guru",target:"_blank",rel:"noopener noreferrer",children:"crontab.guru"})]}):`Auto-filled from preset: ${g}`})]}),f==="webhook"&&t.jsxs(t.Fragment,{children:[t.jsxs("div",{className:"form-group",children:[t.jsx("label",{htmlFor:"routine-webhook-path",children:"Webhook Path"}),t.jsx("input",{id:"routine-webhook-path",type:"text",placeholder:"/trigger/my-routine",value:y,onChange:xe=>j(xe.target.value),"aria-invalid":!!Fe.webhookPath,"aria-describedby":Fe.webhookPath?tt:void 0}),Fe.webhookPath?t.jsx("small",{id:tt,className:"field-error",children:Fe.webhookPath}):t.jsx("small",{children:"URL path for the webhook endpoint"})]}),t.jsxs("div",{className:"form-group",children:[t.jsx("label",{htmlFor:"routine-webhook-secret",children:"Webhook Secret (optional)"}),t.jsx("input",{id:"routine-webhook-secret",type:"password",placeholder:"Optional — leave empty for unauthenticated webhooks",value:S,onChange:xe=>C(xe.target.value)}),t.jsx("small",{children:"HMAC secret for signature verification. Leave empty for unauthenticated webhooks."})]})]}),f==="api"&&t.jsxs("div",{className:"form-group",children:[t.jsx("label",{htmlFor:"routine-endpoint",children:"API Endpoint"}),t.jsx("input",{id:"routine-endpoint",type:"text",placeholder:"/api/routine/my-routine",value:x,onChange:xe=>k(xe.target.value),"aria-invalid":!!Fe.endpoint,"aria-describedby":Fe.endpoint?ft:void 0}),Fe.endpoint?t.jsx("small",{id:ft,className:"field-error",children:Fe.endpoint}):t.jsx("small",{children:"API endpoint path that triggers this routine"})]}),f==="manual"&&t.jsx("div",{className:"form-group",children:t.jsx("small",{className:"routine-trigger-info",children:"This routine will be triggered manually via the dashboard or API."})}),t.jsxs("div",{className:"form-group",children:[t.jsx("label",{children:"Action Mode"}),t.jsxs("div",{className:"schedule-mode-toggle",role:"radiogroup","aria-label":"Action mode",children:[t.jsx("button",{type:"button",className:`schedule-mode-btn${q==="simple"?" active":""}`,onClick:()=>Y("simple"),role:"radio","aria-checked":q==="simple",children:"Simple"}),t.jsx("button",{type:"button",className:`schedule-mode-btn${q==="advanced"?" active":""}`,onClick:()=>Y("advanced"),role:"radio","aria-checked":q==="advanced",children:"Multi-Step"})]}),t.jsx("small",{children:q==="simple"?"Run one command, prompt, or task creation action":"Run multiple actions sequentially"})]}),q==="simple"?t.jsxs(t.Fragment,{children:[t.jsxs("div",{className:"form-group",children:[t.jsx("label",{children:"Action Type"}),t.jsxs("div",{className:"schedule-mode-toggle",role:"radiogroup","aria-label":"Action type",children:[t.jsx("button",{type:"button",className:`schedule-mode-btn${ge==="command"?" active":""}`,onClick:()=>L("command"),role:"radio","aria-checked":ge==="command",children:"Command"}),t.jsx("button",{type:"button",className:`schedule-mode-btn${ge==="ai-prompt"?" active":""}`,onClick:()=>L("ai-prompt"),role:"radio","aria-checked":ge==="ai-prompt",children:"AI Prompt"}),t.jsx("button",{type:"button",className:`schedule-mode-btn${ge==="create-task"?" active":""}`,onClick:()=>L("create-task"),role:"radio","aria-checked":ge==="create-task",children:"Create Task"})]})]}),ge==="command"?t.jsxs("div",{className:"form-group",children:[t.jsx("label",{htmlFor:"routine-command",children:"Command"}),t.jsx("input",{id:"routine-command",type:"text",placeholder:"e.g. npx runfusion.ai backup --create",value:M,onChange:xe=>$(xe.target.value),"aria-invalid":!!Fe.command,"aria-describedby":Fe.command?Mt:void 0}),Fe.command?t.jsx("small",{id:Mt,className:"field-error",children:Fe.command}):t.jsx("small",{children:"Shell command to execute."})]}):ge==="ai-prompt"?t.jsxs(t.Fragment,{children:[t.jsxs("div",{className:"form-group",children:[t.jsx("label",{htmlFor:"routine-prompt",children:"Prompt"}),t.jsx("textarea",{id:"routine-prompt",placeholder:"e.g. Summarize recent activity and create action items",value:ve,onChange:xe=>Me(xe.target.value),rows:3,"aria-invalid":!!Fe.prompt,"aria-describedby":Fe.prompt?yt:void 0}),Fe.prompt?t.jsx("small",{id:yt,className:"field-error",children:Fe.prompt}):t.jsx("small",{children:"AI prompt to execute."})]}),t.jsxs("div",{className:"form-group",children:[t.jsx("label",{htmlFor:"routine-model",children:"Model (optional)"}),t.jsx(Ns,{id:"routine-model",label:"Model",models:Ue,value:De,onChange:ut,placeholder:"Use default",disabled:Ve}),ct&&t.jsx("small",{className:"field-error",children:ct}),Fe.model&&t.jsx("small",{id:K,className:"field-error",children:Fe.model})]})]}):t.jsxs(t.Fragment,{children:[t.jsxs("div",{className:"form-group",children:[t.jsx("label",{htmlFor:"routine-task-title",children:"Task Title (optional)"}),t.jsx("input",{id:"routine-task-title",type:"text",placeholder:"e.g. Review weekly dependencies",value:ie,onChange:xe=>ye(xe.target.value)})]}),t.jsxs("div",{className:"form-group",children:[t.jsx("label",{htmlFor:"routine-task-description",children:"Task Description"}),t.jsx("textarea",{id:"routine-task-description",placeholder:"e.g. Check npm dependencies for security vulnerabilities",value:Z,onChange:xe=>fe(xe.target.value),rows:4,"aria-invalid":!!Fe.taskDescription,"aria-describedby":Fe.taskDescription?Ge:void 0}),Fe.taskDescription?t.jsx("small",{id:Ge,className:"field-error",children:Fe.taskDescription}):t.jsx("small",{children:"Describes the task that will be created."})]}),t.jsxs("div",{className:"form-group",children:[t.jsx("label",{htmlFor:"routine-task-column",children:"Target Column"}),t.jsxs("select",{id:"routine-task-column",value:Q,onChange:xe=>F(xe.target.value),children:[t.jsx("option",{value:"triage",children:"Triage"}),t.jsx("option",{value:"todo",children:"To Do"})]})]}),t.jsxs("div",{className:"form-group",children:[t.jsx("label",{htmlFor:"routine-task-model",children:"Executor Model (optional)"}),t.jsx(Ns,{id:"routine-task-model",label:"Executor Model",models:Ue,value:De,onChange:ut,placeholder:"Use default",disabled:Ve}),ct&&t.jsx("small",{className:"field-error",children:ct}),Fe.model&&t.jsx("small",{id:K,className:"field-error",children:Fe.model})]})]})]}):t.jsxs(t.Fragment,{children:[t.jsx(cL,{steps:D,onChange:N,onEditingChange:de}),Fe.steps&&t.jsx("small",{className:"field-error",children:Fe.steps}),Fe.stepsEditing&&t.jsx("small",{className:"field-error",children:Fe.stepsEditing})]}),t.jsxs("div",{className:"form-group",children:[t.jsx("label",{htmlFor:"routine-timeout",children:"Timeout (ms)"}),t.jsx("input",{id:"routine-timeout",type:"number",min:1e3,step:1e3,value:me,onChange:xe=>Ne(Number(xe.target.value)),"aria-invalid":!!Fe.timeoutMs,"aria-describedby":Fe.timeoutMs?ue:void 0}),Fe.timeoutMs?t.jsx("small",{id:ue,className:"field-error",children:Fe.timeoutMs}):t.jsx("small",{children:"Maximum execution time in milliseconds."})]}),t.jsxs("div",{className:"form-group",children:[t.jsx("label",{htmlFor:"routine-execution-policy",children:"Execution Policy"}),t.jsx("select",{id:"routine-execution-policy",value:R,onChange:xe=>O(xe.target.value),children:fL.map(xe=>t.jsx("option",{value:xe.value,children:xe.label},xe.value))}),t.jsx("small",{children:"How to handle concurrent executions of this routine"})]}),t.jsxs("div",{className:"form-group",children:[t.jsx("label",{htmlFor:"routine-catchup-policy",children:"Catch-up Policy"}),t.jsx("select",{id:"routine-catchup-policy",value:E,onChange:xe=>_(xe.target.value),children:gL.map(xe=>t.jsx("option",{value:xe.value,children:xe.label},xe.value))}),t.jsx("small",{children:"What to do when a scheduled run is missed"})]}),t.jsxs("div",{className:"form-group",children:[t.jsxs("label",{htmlFor:"routine-enabled",className:"checkbox-label",children:[t.jsx("input",{id:"routine-enabled",type:"checkbox",checked:G,onChange:xe=>H(xe.target.checked)}),"Enabled"]}),t.jsx("small",{children:"When disabled, the routine will not run automatically"})]}),t.jsxs("div",{className:"modal-actions",children:[t.jsx("button",{type:"button",className:"btn btn-sm",onClick:s,disabled:We,children:"Cancel"}),t.jsx("button",{type:"submit",className:"btn btn-primary btn-sm",disabled:We,children:We?"Saving…":l?"Save Changes":"Create Routine"})]})]})}const bL=3e4;function xL({onClose:e,addToast:n,projectId:s}){const[a,r]=i.useState(()=>s?"project":"global"),[o,l]=i.useState([]),[c,d]=i.useState("list"),[u,h]=i.useState(),[m,f]=i.useState(null),[p,g]=i.useState({}),w=i.useRef(null);Oi(w,!0,"fusion:automation-modal-size");const v=i.useMemo(()=>({scope:a,projectId:a==="project"?s:void 0}),[a,s]),b=i.useCallback(async()=>{try{const A=await l1(v);l(A),g(P=>{const q={...P};for(const Y of A){const ge=q[Y.id];if(!ge||!Y.lastRunResult)continue;const L=Y.lastRunResult;L.success===ge.success&&(L.output||"")===ge.output&&(L.error||"")===(ge.error||"")&&delete q[Y.id]}return q})}catch(A){n(Ie(A)||"Failed to load routines","error")}},[n,v]);i.useEffect(()=>{b()},[b]),i.useEffect(()=>{const A=setInterval(()=>{b()},bL);return()=>clearInterval(A)},[b]),i.useEffect(()=>{const A=P=>{P.key==="Escape"&&(c!=="list"?(d("list"),h(void 0)):e())};return document.addEventListener("keydown",A),()=>document.removeEventListener("keydown",A)},[e,c]);const y=Xi(e),j=i.useCallback(async A=>{try{await c1(A,v),n("Routine created","success"),d("list"),await b()}catch(P){n(Ie(P)||"Failed to create routine","error")}},[n,b,v]),S=i.useCallback(A=>{h(A),d("edit")},[]),C=i.useCallback(async A=>{if(u)try{await ih(u.id,A,v),n("Routine updated","success"),d("list"),h(void 0),await b()}catch(P){n(Ie(P)||"Failed to update routine","error")}},[u,n,b,v]),x=i.useCallback(async A=>{try{await d1(A.id,v),n(`Deleted "${A.name}"`,"success"),await b()}catch(P){n(Ie(P)||"Failed to delete routine","error")}},[n,b,v]),k=i.useCallback(async A=>{f(A.id);try{const{result:P}=await u1(A.id,v);g(q=>({...q,[A.id]:{output:P.output||"",error:P.error,success:P.success}})),P.success?n(`"${A.name}" completed successfully`,"success"):n(`"${A.name}" failed: ${P.error||"Unknown error"}`,"error"),await b()}catch(P){n(Ie(P)||"Failed to run routine","error")}finally{f(null)}},[n,b,v]),R=i.useCallback(async A=>{try{await ih(A.id,{enabled:!A.enabled},v),n(`"${A.name}" ${A.enabled?"disabled":"enabled"}`,"success"),await b()}catch(P){n(Ie(P)||"Failed to toggle routine","error")}},[n,b,v]),O=i.useCallback(()=>{d("list"),h(void 0)},[]);i.useEffect(()=>{c!=="list"&&g({})},[c]);const E=i.useCallback(A=>{r(A),d("list"),h(void 0),g({})},[]),_=()=>c==="create"?t.jsx(og,{onSubmit:j,onCancel:O,scope:a,projectId:s}):c==="edit"&&u?t.jsx(og,{routine:u,onSubmit:C,onCancel:O,scope:a,projectId:s}):o.length===0?t.jsxs("div",{className:"routine-empty-state",children:[t.jsx(as,{size:48,strokeWidth:1}),t.jsx("h4",{children:"No automations yet"}),t.jsx("p",{children:"Create an automation with a schedule, webhook, API, or manual trigger."}),t.jsxs("button",{className:"btn btn-primary btn-sm",onClick:()=>d("create"),children:[t.jsx(Tn,{size:14}),"Create your first automation"]})]}):t.jsx("div",{className:"routine-list",children:o.map(A=>t.jsx(aL,{routine:A,onEdit:S,onDelete:x,onRun:k,onToggle:R,running:m===A.id,lastRunOutput:p[A.id]??null},A.id))}),G=()=>_(),H=c==="list"&&o.length>0;return t.jsx("div",{className:"modal-overlay open",...y,children:t.jsxs("div",{ref:w,className:"modal modal-lg automation-modal",role:"dialog","aria-modal":"true","aria-labelledby":"schedules-modal-title",children:[t.jsxs("div",{className:"modal-header",children:[t.jsxs("div",{className:"detail-title-row",children:[t.jsx(as,{size:20,className:"icon-triage"}),t.jsx("h3",{id:"schedules-modal-title",children:"Automations"})]}),t.jsx("button",{className:"modal-close",onClick:e,"aria-label":"Close",children:t.jsx(bn,{size:20})})]}),t.jsxs("div",{className:"scheduling-toolbar","aria-live":"polite",children:[t.jsxs("div",{className:"scheduling-toolbar-left",role:"group","aria-label":"Scheduling scope",children:[t.jsxs("div",{className:"scheduling-scope-selector",children:[t.jsxs("button",{type:"button",className:`scope-btn${a==="global"?" active":""}`,onClick:()=>E("global"),"aria-pressed":a==="global",title:"Global (user-level) automations",children:[t.jsx(xc,{size:14}),"Global"]}),t.jsxs("button",{type:"button",className:`scope-btn${a==="project"?" active":""}`,onClick:()=>E("project"),"aria-pressed":a==="project",title:"Project-scoped automations",children:[t.jsx(ws,{size:14}),"Project"]})]}),t.jsxs("span",{className:"scheduling-count",children:[t.jsx(as,{size:14}),o.length," automation",o.length===1?"":"s"]})]}),t.jsx("div",{className:"scheduling-toolbar-right",children:H&&t.jsxs("button",{className:"btn btn-primary btn-sm",onClick:()=>d("create"),"aria-label":"Create new automation",children:[t.jsx(Tn,{size:14}),"New Automation"]})})]}),t.jsx("div",{className:"schedule-modal-content",id:"scheduled-tasks-content",children:G()})]})})}const vL=3e4,Du=new Map,Jd=new Map;function lg(e){return e??"default"}function cg(e){const n=Du.get(e);return n?Date.now()>=n.expiresAt?(Du.delete(e),null):n:null}function yL(e,n){const s=e.some(r=>r.id!=="github"&&r.authenticated),a=e.some(r=>r.id==="github"&&r.authenticated)||(n?.authenticated??!1);return{hasAiProvider:s,hasGithub:a}}async function wL(e){const n=Jd.get(e);if(n)return n;const s=Do().then(({providers:a,ghCli:r})=>{const l={...yL(a,r),ghCli:r,expiresAt:Date.now()+vL};return Du.set(e,l),l}).finally(()=>{Jd.delete(e)});return Jd.set(e,s),s}function Jv(e){const n=lg(e),s=cg(n),[a,r]=i.useState(s?.hasAiProvider??!1),[o,l]=i.useState(s?.hasGithub??!1),[,c]=i.useState(s?.ghCli),[d,u]=i.useState(s==null),h=i.useRef(!!s);return i.useEffect(()=>{let m=!1;const f=lg(e),p=cg(f);if(p)return r(p.hasAiProvider),l(p.hasGithub),c(p.ghCli),u(!1),h.current=!0,()=>{m=!0};h.current=!1;async function g(){!h.current&&u(!0);try{const v=await wL(f);if(m)return;r(v.hasAiProvider),l(v.hasGithub),c(v.ghCli)}catch{}finally{m||(h.current=!0,u(!1))}}return g(),()=>{m=!0}},[e]),i.useMemo(()=>({hasAiProvider:a,hasGithub:o,loading:d,hasWarnings:!a||!o}),[a,o,d])}function Yv({hasAiProvider:e,hasGithub:n,compact:s=!1,onDismiss:a}){if(e&&n)return null;const r=a?t.jsx("button",{type:"button",className:"setup-warning-banner__dismiss touch-target","aria-label":"Dismiss setup warning",onClick:a,children:t.jsx(bn,{size:16,"aria-hidden":"true"})}):null;if(s)return t.jsxs("div",{className:`setup-warning-banner setup-warning-banner--compact${a?" setup-warning-banner--dismissible":""}`,role:"status","aria-live":"polite",children:[t.jsx("p",{className:"setup-warning-banner__compact-text",children:"⚠ Setup incomplete — AI and/or GitHub features will be limited."}),r]});const o=[];return e||o.push({key:"ai",title:"No AI provider connected",description:"AI agents won't be able to work on tasks until you connect a provider. Set one up in Settings → AI Setup."}),n||o.push({key:"github",title:"GitHub not connected",description:"You won't be able to import issues from GitHub, but you can still create tasks manually."}),t.jsxs("div",{className:`setup-warning-banner${a?" setup-warning-banner--dismissible":""}`,role:"status","aria-live":"polite",children:[r,o.map(l=>t.jsxs("div",{className:"setup-warning-banner__item",children:[t.jsx("strong",{className:"setup-warning-banner__title",children:l.title}),t.jsx("p",{className:"setup-warning-banner__description",children:l.description})]},l.key))]})}function kL({isOpen:e,onClose:n,projectId:s,tasks:a,onCreateTask:r,addToast:o}){const{confirm:l}=ti(),c=ei();Si(e);const{keyboardOverlap:d,viewportHeight:u,viewportOffsetTop:h,keyboardOpen:m}=ea({enabled:c==="mobile"}),f=m?{"--keyboard-overlap":`${d}px`,"--vv-offset-top":`${h}px`,...u!==null?{"--vv-height":`${u}px`}:{}}:{},[p,g]=i.useState(""),[w,v]=i.useState([]),[b,y]=i.useState(""),[j,S]=i.useState(""),[C,x]=i.useState([]),[k,R]=i.useState(!1),[O,E]=i.useState(""),[_,G]=i.useState(""),[H,A]=i.useState(""),[P,q]=i.useState(""),[Y,ge]=i.useState(""),[L,M]=i.useState("default"),[$,D]=i.useState(!1),[N,W]=i.useState([]),[de,me]=i.useState(!1),[Ne,ve]=i.useState(void 0),[Me,ie]=i.useState(_s),[ye,Z]=i.useState(void 0),[fe,Q]=i.useState(!1),[F,X]=i.useState(""),[re,U]=i.useState(null),[be,Ue]=i.useState([]),[se,Ve]=i.useState(!1),[Le,ct]=i.useState(!1),Ke=i.useRef(null),[oe,Te]=i.useState(!1),[Fe,mt]=i.useState(""),We=i.useRef(null),{hasAiProvider:he,hasGithub:pe,loading:De}=Jv(s),{nodes:ut}=_c(),ht=i.useCallback(Je=>{me(!0),W(Je)},[]),et=i.useCallback(()=>{me(!1)},[]),vt=i.useCallback(async()=>{if(be.length>0){Ve(!0);return}ct(!0);try{const Je=await Hr(void 0,s);Ue(Je),Ve(!0)}catch(Je){const ke=Ie(Je);o(ke?`Failed to load agents: ${ke}`:"Failed to load agents","error"),Ve(!1)}finally{ct(!1)}},[be.length,s,o]);i.useEffect(()=>{if(!se)return;const Je=ke=>{Ke.current&&!Ke.current.contains(ke.target)&&Ve(!1)};return document.addEventListener("mousedown",Je),()=>document.removeEventListener("mousedown",Je)},[se]),i.useEffect(()=>{if(!oe)return;const Je=ke=>{We.current&&!We.current.contains(ke.target)&&(Te(!1),mt(""))};return document.addEventListener("mousedown",Je),()=>document.removeEventListener("mousedown",Je)},[oe]);const Oe=a.filter(Je=>!w.includes(Je.id)).sort((Je,ke)=>{const nt=ke.createdAt.localeCompare(Je.createdAt);if(nt!==0)return nt;const bt=parseInt(Je.id.slice(Je.id.lastIndexOf("-")+1),10)||0;return(parseInt(ke.id.slice(ke.id.lastIndexOf("-")+1),10)||0)-bt}),tt=Fe?Oe.filter(Je=>Je.id.toLowerCase().includes(Fe.toLowerCase())||Je.title&&Je.title.toLowerCase().includes(Fe.toLowerCase())||Je.description&&Je.description.toLowerCase().includes(Fe.toLowerCase())):Oe,ft=(Je,ke)=>Je.length>ke?Je.slice(0,ke)+"…":Je,Mt=F.trim(),yt=Mt.length>0&&!Sc.test(Mt);i.useEffect(()=>{const Je=p.trim()!==""||w.length>0||C.length>0||O!==""||_!==""||H!==""||P!==""||N.length>0||re!==null||Ne!==void 0||Me!==_s||ye!==void 0||b!==""||j!==""||fe||Mt!=="";D(Je)},[p,w,C,O,_,H,P,N,re,Ne,Me,ye,b,j,fe,Mt]);const Ge=i.useCallback(async()=>{$&&!await l({title:"Discard Changes",message:"You have unsaved changes. Discard them?",danger:!0})||(C.forEach(Je=>URL.revokeObjectURL(Je.previewUrl)),x([]),g(""),v([]),E(""),G(""),A(""),q(""),ge(""),M("default"),W([]),me(!1),U(null),Ve(!1),ve(void 0),ie(_s),Z(void 0),y(""),S(""),D(!1),Q(!1),X(""),n())},[$,n,C,l]),K=i.useCallback(async()=>{const Je=p.trim();if(!(!Je||k||yt)){R(!0);try{const ke=O.indexOf("/"),nt=_.indexOf("/"),bt=H.indexOf("/"),kt=await r({title:void 0,description:Je,column:"triage",dependencies:w.length?w:void 0,enabledWorkflowSteps:de?N.length>0?N:[]:void 0,...re?{assignedAgentId:re}:{},modelPresetId:L==="preset"&&Y||void 0,modelProvider:O&&ke!==-1?O.slice(0,ke):void 0,modelId:O&&ke!==-1?O.slice(ke+1):void 0,validatorModelProvider:_&&nt!==-1?_.slice(0,nt):void 0,validatorModelId:_&&nt!==-1?_.slice(nt+1):void 0,planningModelProvider:H&&bt!==-1?H.slice(0,bt):void 0,planningModelId:H&&bt!==-1?H.slice(bt+1):void 0,thinkingLevel:P!==""?P:void 0,reviewLevel:Ne,priority:Me,nodeId:ye,branch:b.trim()===""?void 0:b.trim(),baseBranch:j.trim()===""?void 0:j.trim(),...fe||Mt!==""?{githubTracking:{enabled:fe,...Mt!==""?{repoOverride:Mt}:{}}}:{}});if(C.length>0){const wt=[];for(const At of C)try{await Ec(kt.id,At.file,s)}catch{wt.push(At.file.name)}wt.length>0&&o(`Failed to upload: ${wt.join(", ")}`,"error")}C.forEach(wt=>URL.revokeObjectURL(wt.previewUrl)),x([]),g(""),v([]),E(""),G(""),A(""),q(""),ge(""),M("default"),W([]),me(!1),U(null),Ve(!1),ve(void 0),ie(_s),Z(void 0),y(""),S(""),o(`Created ${kt.id}`,"success"),n()}catch(ke){o(Ie(ke)||"Failed to create task","error")}finally{R(!1)}}},[p,w,C,O,_,H,P,k,r,o,n,s,L,Y,N,de,re,Ne,Me,ye,b,j]),ue=i.useCallback(Je=>{Je.key==="Escape"&&(Je.preventDefault(),Ge())},[Ge]),xe=(re?be.find(Je=>Je.id===re):void 0)?.name??re,dt=t.jsxs("div",{className:"new-task-quick-fields",children:[t.jsxs("div",{className:"form-group",children:[t.jsx("label",{children:"Dependencies"}),t.jsxs("div",{className:"dep-trigger-wrap",ref:We,children:[t.jsx("button",{type:"button",className:"btn btn-sm dep-trigger",onClick:()=>Te(Je=>!Je),disabled:k,"data-testid":"dep-trigger",children:w.length>0?`${w.length} selected`:"Add dependencies"}),oe&&t.jsxs("div",{className:"dep-dropdown",children:[t.jsx("input",{className:"dep-dropdown-search",placeholder:"Search tasks…",autoFocus:!0,value:Fe,onChange:Je=>mt(Je.target.value),onClick:Je=>Je.stopPropagation()}),tt.length===0?t.jsx("div",{className:"dep-dropdown-empty",children:"No available tasks"}):tt.map(Je=>t.jsxs("div",{className:`dep-dropdown-item${w.includes(Je.id)?" selected":""}`,onClick:()=>{v(w.includes(Je.id)?w.filter(ke=>ke!==Je.id):[...w,Je.id]),Te(!1),mt("")},onMouseDown:ke=>ke.preventDefault(),children:[t.jsx("span",{className:"dep-dropdown-id",children:Je.id}),t.jsx("span",{className:"dep-dropdown-title",children:ft(Je.title||Je.description||Je.id,30)})]},Je.id))]})]}),w.length>0&&t.jsx("div",{className:"selected-deps",children:w.map(Je=>t.jsxs("span",{className:"dep-chip",children:[Je,t.jsx("button",{type:"button",className:"dep-chip-remove",onClick:()=>v(w.filter(ke=>ke!==Je)),disabled:k,children:"×"})]},Je))})]}),t.jsxs("div",{className:"form-group",children:[t.jsx("label",{children:"Assign Agent"}),t.jsxs("div",{className:"agent-trigger-wrap",ref:Ke,children:[t.jsxs("button",{type:"button",className:"btn btn-sm dep-trigger",onClick:()=>{se?Ve(!1):vt()},disabled:k,"data-testid":"new-task-agent-button",children:[t.jsx(Xn,{size:12,style:{verticalAlign:"middle"}}),xe?` ${xe}`:" Assign agent"]}),se&&t.jsxs("div",{className:"dep-dropdown agent-picker-dropdown",onMouseDown:Je=>Je.preventDefault(),children:[t.jsx("div",{className:"dep-dropdown-search-header",children:"Select agent"}),Le&&t.jsx("div",{className:"dep-dropdown-empty",children:"Loading agents..."}),!Le&&be.map(Je=>t.jsxs("div",{className:`dep-dropdown-item${re===Je.id?" selected":""}`,onMouseDown:ke=>ke.preventDefault(),onClick:()=>{U(Je.id===re?null:Je.id),Ve(!1)},"data-testid":`agent-option-${Je.id}`,children:[t.jsx(Xn,{size:12,style:{marginRight:6}}),t.jsx("span",{className:"dep-dropdown-id",children:Je.role}),t.jsx("span",{className:"dep-dropdown-title",children:Je.name})]},Je.id)),!Le&&be.length===0&&t.jsx("div",{className:"dep-dropdown-empty",children:"No agents available"}),re&&t.jsx("div",{className:"dep-dropdown-item",onMouseDown:Je=>Je.preventDefault(),onClick:()=>{U(null),Ve(!1)},children:t.jsx("span",{className:"dep-dropdown-title",children:"Clear selection"})})]})]})]})]});return e?t.jsx("div",{className:"modal-overlay open",onClick:Ge,onKeyDown:ue,role:"dialog","aria-modal":"true",children:t.jsxs("div",{className:"modal modal-lg new-task-modal",onClick:Je=>Je.stopPropagation(),style:f,children:[t.jsxs("div",{className:"modal-header",children:[t.jsx("h3",{children:"New Task"}),t.jsx("button",{className:"modal-close",onClick:Ge,disabled:k,"aria-label":"Close",children:"×"})]}),t.jsxs("div",{className:"modal-body",children:[!De&&t.jsx(Yv,{hasAiProvider:he,hasGithub:pe}),t.jsx(Ev,{mode:"create",description:p,onDescriptionChange:g,dependencies:w,onDependenciesChange:v,executorModel:O,onExecutorModelChange:E,validatorModel:_,onValidatorModelChange:G,presetMode:L,onPresetModeChange:M,selectedPresetId:Y,onSelectedPresetIdChange:ge,selectedWorkflowSteps:N,onWorkflowStepsChange:ht,onDefaultOnApplied:et,pendingImages:C,onImagesChange:x,tasks:a,projectId:s,disabled:k,addToast:o,isActive:e,onClose:Ge,planningModel:H,onPlanningModelChange:A,thinkingLevel:P,onThinkingLevelChange:q,reviewLevel:Ne,onReviewLevelChange:ve,priority:Me,onPriorityChange:ie,branch:b,onBranchChange:y,baseBranch:j,onBaseBranchChange:S,nodeId:ye,onNodeIdChange:Z,nodeOptions:ut,githubTrackingEnabled:fe,onGithubTrackingEnabledChange:Q,githubRepoOverride:F,onGithubRepoOverrideChange:X,renderBelowPrimary:dt,hideDependencies:!0,autoExpandMoreOptionsOnSelection:!1})]}),t.jsxs("div",{className:"modal-actions",children:[t.jsx("button",{className:"btn btn-sm",onClick:Ge,disabled:k,children:"Cancel"}),t.jsx("button",{className:"btn btn-primary btn-sm",onClick:K,disabled:!p.trim()||k||yt,children:k?"Creating...":"Create Task"})]})]})}):null}function wi(e){if(!Number.isFinite(e)||e<0)return"—";const n=e/(1024*1024);return n<1024?`${n.toFixed(0)} MB`:`${(n/1024).toFixed(2)} GB`}function dg(e,n){return!Number.isFinite(e)||!Number.isFinite(n)||n<=0?"—":`${(e/n*100).toFixed(1)}%`}function jL(e,n){if(n<=0)return"normal";const s=e/n;return s>=.85?"critical":s>=.65?"warning":"normal"}function NL(e,n){if(n<=0)return"normal";const s=e/n;return s>=.5?"critical":s>=.25?"warning":"normal"}function SL(e,n){if(n<=0)return"normal";const s=e/n;return s>=.9?"critical":s>=.75?"warning":"normal"}function CL(e,n){if(e===null||!Number.isFinite(e)||e<0)return"normal";const s=n>0?e/n:e;return s>=80?"critical":s>=50?"warning":"normal"}function Ll(e){return e==="critical"?"system-stats-modal__value--critical":e==="warning"?"system-stats-modal__value--warning":""}function EL(e){if(!e)return"Not yet";const n=new Date(e);return Number.isNaN(n.getTime())?"Not yet":n.toLocaleString()}function _L({isOpen:e,onClose:n,projectId:s}){const[a,r]=i.useState(null),[o,l]=i.useState(!1),[c,d]=i.useState(null),[u,h]=i.useState(!0),[m,f]=i.useState(90),[p,g]=i.useState(!1),[w,v]=i.useState(!1),[b,y]=i.useState(null),[j,S]=i.useState(null),[C,x]=i.useState(null),k=i.useCallback(async ie=>{l(!0);try{const ye=await W1(s);r(ye),d(null),x(Date.now()),ie?.preserveKillResult||y(null)}catch(ye){d(ye instanceof Error?ye.message:"Failed to load system stats")}finally{l(!1)}},[s]);i.useEffect(()=>{if(!e)return;k();const ie=window.setInterval(()=>{k()},5e3);return()=>{window.clearInterval(ie)}},[e,k]),i.useEffect(()=>{if(!e)return;(async()=>{try{const ye=await Qi();h(ye.vitestAutoKillEnabled??!0),f(ye.vitestKillThresholdPct??90),S(null)}catch(ye){S(ye instanceof Error?ye.message:"Failed to load vitest settings")}})()},[e]),i.useEffect(()=>{if(!e)return;const ie=ye=>{ye.key==="Escape"&&n()};return document.addEventListener("keydown",ie),()=>document.removeEventListener("keydown",ie)},[e,n]);const R=i.useMemo(()=>{if(!a)return[];const ie=a.systemStats,ye=Ll(jL(ie.heapUsed,ie.heapLimit)),Z=Ll(NL(ie.rss,ie.systemTotalMem));return[{label:"RSS",value:wi(ie.rss),detail:dg(ie.rss,ie.systemTotalMem),className:Z},{label:"Heap Used",value:wi(ie.heapUsed),detail:`of ${wi(ie.heapTotal)}`,className:ye},{label:"Heap Limit",value:wi(ie.heapLimit),detail:"V8 limit"},{label:"External",value:wi(ie.external)},{label:"Array Buffers",value:wi(ie.arrayBuffers)}]},[a]),O=i.useCallback(async ie=>{h(ie);try{await Fn({vitestAutoKillEnabled:ie}),S(null)}catch(ye){S(ye instanceof Error?ye.message:"Failed to save vitest settings")}},[]),E=i.useCallback(async ie=>{const ye=Math.min(99,Math.max(50,Number.isFinite(ie)?Math.round(ie):90));f(ye);try{await Fn({vitestKillThresholdPct:ye}),S(null)}catch(Z){S(Z instanceof Error?Z.message:"Failed to save vitest settings")}},[]),_=i.useCallback(async()=>{if(!p){if(!w){v(!0);return}g(!0);try{const ie=await G1(s);y(ie),v(!1),await k({preserveKillResult:!0})}catch(ie){d(ie instanceof Error?ie.message:"Failed to kill vitest processes")}finally{g(!1)}}},[w,p,k,s]);if(!e)return null;const G=a?.systemStats,H=o&&!!a,A=C?`Updated ${new Date(C).toLocaleTimeString([],{hour:"2-digit",minute:"2-digit",second:"2-digit"})}`:"Waiting for first update",P=a?.taskStats,q=G?G.systemTotalMem-G.systemFreeMem:0,Y=G?SL(q,G.systemTotalMem):"normal",ge=G?Ll(Y):"",L=G&&Number.isFinite(G.systemTotalMem)&&G.systemTotalMem>0?Math.max(0,Math.min(100,q/G.systemTotalMem*100)):0,M=G?`System memory used: ${L.toFixed(1)}% (${wi(q)} of ${wi(G.systemTotalMem)})`:"System memory usage unavailable",$=a?.vitestProcessCount,D=CL(G?.cpuPercent??null,G?.cpuCount??0),N=Ll(D),W=G?.cpuPercent??null,de=W===null?0:Math.max(0,Math.min(100,W)),me=W===null?"Sampling…":`${W.toFixed(1)}%`,Ne=W===null?"App CPU usage unavailable: waiting for another sample":`App CPU usage: ${W.toFixed(1)}%`,ve=b?b.killed>0?"system-stats-modal__kill-result system-stats-modal__kill-result--success":"system-stats-modal__kill-result system-stats-modal__kill-result--error":"",Me=EL(a?.vitestLastAutoKillAt);return t.jsx("div",{className:"modal-overlay open",role:"dialog","aria-modal":"true","aria-labelledby":"system-stats-modal-title",onClick:ie=>{ie.target===ie.currentTarget&&n()},"data-testid":"system-stats-modal-overlay",children:t.jsxs("div",{className:"modal modal-lg system-stats-modal","data-testid":"system-stats-modal",children:[t.jsxs("div",{className:"modal-header system-stats-modal__header",children:[t.jsxs("h2",{id:"system-stats-modal-title",className:"system-stats-modal__title",children:[t.jsx(Er,{}),t.jsx("span",{children:"System Stats"})]}),t.jsxs("div",{className:"system-stats-modal__header-actions",children:[t.jsxs("span",{className:"system-stats-modal__auto-refresh","aria-live":"polite",children:[t.jsx("span",{children:"Auto-refresh · 5s"}),t.jsx("span",{className:"system-stats-modal__auto-refresh-time",children:A})]}),t.jsx("button",{type:"button",className:"btn-icon",onClick:()=>void k(),title:"Refresh","aria-label":"Refresh system stats",children:t.jsx(us,{size:16,className:H?"system-stats-modal__refresh--spinning":void 0})}),t.jsx("button",{type:"button",className:"modal-close",onClick:n,"aria-label":"Close",children:t.jsx(bn,{})})]})]}),o&&!a&&t.jsx("div",{className:"system-stats-modal__state",children:"Loading system stats…"}),c&&!a&&t.jsx("div",{className:"system-stats-modal__state system-stats-modal__state--error",role:"alert",children:c}),a&&t.jsxs("div",{className:"system-stats-modal__content",children:[t.jsxs("section",{className:"system-stats-modal__section","aria-label":"Process stats",children:[t.jsx("h3",{className:"system-stats-modal__section-title",children:"Process"}),t.jsx("dl",{className:"system-stats-modal__grid",children:R.map(ie=>t.jsxs("div",{className:"system-stats-modal__row",children:[t.jsx("dt",{children:ie.label}),t.jsxs("dd",{children:[t.jsx("span",{className:`system-stats-modal__value ${ie.className}`.trim(),children:ie.value}),ie.detail?t.jsx("span",{className:"system-stats-modal__detail",children:ie.detail}):null]})]},ie.label))})]}),t.jsxs("section",{className:"system-stats-modal__section","aria-label":"CPU and load stats",children:[t.jsx("h3",{className:"system-stats-modal__section-title",children:"CPU & Load"}),t.jsxs("dl",{className:"system-stats-modal__grid",children:[t.jsxs("div",{className:"system-stats-modal__row system-stats-modal__row--cpu-used",children:[t.jsx("dt",{children:"App CPU"}),t.jsxs("dd",{children:[t.jsx("span",{className:`system-stats-modal__value ${N}`.trim(),children:me}),t.jsx("span",{className:"system-stats-modal__detail",children:W===null?"First sample pending":"process usage"})]}),t.jsx("div",{className:"system-stats-modal__memory-progress-wrapper",children:t.jsx("div",{className:`system-stats-modal__memory-progress-track system-stats-modal__memory-progress-track--${D}`,role:"progressbar","aria-valuenow":Math.round(de),"aria-valuemin":0,"aria-valuemax":100,"aria-label":Ne,children:t.jsx("div",{className:`system-stats-modal__memory-progress-fill system-stats-modal__memory-progress-fill--${D}`,style:{width:`${de}%`}})})})]}),t.jsxs("div",{className:"system-stats-modal__row",children:[t.jsx("dt",{children:"Load Avg"}),t.jsx("dd",{children:G?.loadAvg.map(ie=>ie.toFixed(2)).join(" ")??"—"})]}),t.jsxs("div",{className:"system-stats-modal__row",children:[t.jsx("dt",{children:"Cores"}),t.jsx("dd",{children:G?.cpuCount??"—"})]}),t.jsxs("div",{className:"system-stats-modal__row",children:[t.jsx("dt",{children:"Platform"}),t.jsx("dd",{children:G?.platform??"—"})]}),t.jsxs("div",{className:"system-stats-modal__row",children:[t.jsx("dt",{children:"Node"}),t.jsx("dd",{children:G?.nodeVersion??"—"})]}),t.jsxs("div",{className:"system-stats-modal__row",children:[t.jsx("dt",{children:"PID"}),t.jsx("dd",{children:G?.pid??"—"})]})]})]}),t.jsxs("section",{className:"system-stats-modal__section","aria-label":"System memory stats",children:[t.jsx("h3",{className:"system-stats-modal__section-title",children:"System"}),t.jsxs("dl",{className:"system-stats-modal__grid",children:[t.jsxs("div",{className:"system-stats-modal__row system-stats-modal__row--memory-used",children:[t.jsx("dt",{children:"Memory Used"}),t.jsxs("dd",{children:[t.jsx("span",{className:`system-stats-modal__value ${ge}`.trim(),children:G?wi(q):"—"}),t.jsx("span",{className:"system-stats-modal__detail",children:G?`${dg(q,G.systemTotalMem)} of ${wi(G.systemTotalMem)}`:""})]}),t.jsx("div",{className:"system-stats-modal__memory-progress-wrapper",children:t.jsx("div",{className:`system-stats-modal__memory-progress-track system-stats-modal__memory-progress-track--${Y}`,role:"progressbar","aria-valuenow":Math.round(L),"aria-valuemin":0,"aria-valuemax":100,"aria-label":M,children:t.jsx("div",{className:`system-stats-modal__memory-progress-fill system-stats-modal__memory-progress-fill--${Y}`,style:{width:`${L}%`}})})})]}),t.jsxs("div",{className:"system-stats-modal__row",children:[t.jsx("dt",{children:"Memory Free"}),t.jsx("dd",{children:G?wi(G.systemFreeMem):"—"})]})]})]}),t.jsxs("section",{className:"system-stats-modal__section","aria-label":"Task stats",children:[t.jsx("h3",{className:"system-stats-modal__section-title",children:"Tasks"}),t.jsxs("dl",{className:"system-stats-modal__grid",children:[t.jsxs("div",{className:"system-stats-modal__row",children:[t.jsx("dt",{children:"Total"}),t.jsx("dd",{children:P?.total??0})]}),Object.entries(P?.byColumn??{}).map(([ie,ye])=>t.jsxs("div",{className:"system-stats-modal__row",children:[t.jsx("dt",{children:ie}),t.jsx("dd",{children:ye})]},ie))]})]}),t.jsxs("section",{className:"system-stats-modal__section","aria-label":"Agent stats",children:[t.jsx("h3",{className:"system-stats-modal__section-title",children:"Agents"}),t.jsxs("dl",{className:"system-stats-modal__grid",children:[t.jsxs("div",{className:"system-stats-modal__row",children:[t.jsx("dt",{children:"idle"}),t.jsx("dd",{children:P?.agents.idle??0})]}),t.jsxs("div",{className:"system-stats-modal__row",children:[t.jsx("dt",{children:"active"}),t.jsx("dd",{children:P?.agents.active??0})]}),t.jsxs("div",{className:"system-stats-modal__row",children:[t.jsx("dt",{children:"running"}),t.jsx("dd",{children:P?.agents.running??0})]}),t.jsxs("div",{className:"system-stats-modal__row",children:[t.jsx("dt",{children:"error"}),t.jsx("dd",{children:P?.agents.error??0})]})]})]}),t.jsxs("section",{className:"system-stats-modal__section","aria-label":"Vitest controls",children:[t.jsxs("h3",{className:"system-stats-modal__section-title system-stats-modal__section-title--with-icon",children:[t.jsx(aj,{}),t.jsx("span",{children:"Vitest Controls"})]}),t.jsx("dl",{className:"system-stats-modal__grid system-stats-modal__vitest-controls",children:t.jsxs("div",{className:"system-stats-modal__row",children:[t.jsx("dt",{children:"Vitest Processes"}),t.jsx("dd",{children:$??"—"})]})}),t.jsxs("div",{className:"system-stats-modal__vitest-controls",children:[t.jsx("div",{className:"system-stats-modal__kill-row",children:t.jsxs("button",{type:"button",className:"btn btn-danger",onClick:()=>void _(),disabled:p||$===0,children:[t.jsx(cj,{}),t.jsx("span",{children:w?"Confirm Kill?":"Kill Vitest Processes"})]})}),t.jsxs("label",{className:"system-stats-modal__toggle-row",children:[t.jsx("input",{type:"checkbox",checked:u,onChange:ie=>{O(ie.target.checked)}}),t.jsx("span",{children:"Auto-kill vitest on memory pressure"})]}),t.jsxs("div",{className:"system-stats-modal__threshold-row",children:[t.jsx("label",{htmlFor:"vitest-threshold-number",children:"Kill threshold (%)"}),t.jsxs("div",{className:"system-stats-modal__threshold-controls",children:[t.jsx("input",{id:"vitest-threshold-range",type:"range",min:50,max:99,value:m,"aria-label":"Kill threshold slider (%)",onChange:ie=>{const ye=Number.parseInt(ie.target.value,10);E(Number.isNaN(ye)?90:ye)}}),t.jsx("input",{id:"vitest-threshold-number",type:"number",className:"input",min:50,max:99,value:m,"aria-label":"Kill threshold (%)",onChange:ie=>{const ye=Number.parseInt(ie.target.value,10);E(Number.isNaN(ye)?90:ye)},onBlur:()=>{E(m)}})]})]}),b&&t.jsxs("p",{className:ve,children:["Killed ",b.killed," processes"]}),t.jsxs("p",{className:"system-stats-modal__last-kill",children:["Last auto-kill: ",Me]}),j&&t.jsx("p",{className:"system-stats-modal__kill-result system-stats-modal__kill-result--error",children:j})]})]})]}),c&&a&&t.jsxs("div",{className:"system-stats-modal__footer-error",children:["Latest refresh failed: ",c]})]})})}const ML=5e3;function AL(e={}){const{projectId:n,type:s,limit:a=50,autoRefresh:r=!0,useCentralFeed:o=!1}=e,[l,c]=i.useState([]),[d,u]=i.useState(!1),[h,m]=i.useState(null),[f,p]=i.useState(!1),g=i.useRef(null),w=i.useRef(void 0),v=i.useCallback(async()=>{try{u(!0),m(null);let j;o?j=await mh({limit:a,projectId:n,type:s}):j=(await ah({limit:a,type:s,projectId:n})).map(C=>({...C,projectId:n??"",projectName:""})),c(j),p(j.length===a),j.length>0&&(w.current=j[j.length-1].timestamp)}catch(j){m(j instanceof Error?j.message:"Failed to load activity log")}finally{u(!1)}},[a,n,s,o]),b=i.useCallback(async()=>{if(w.current)try{u(!0);let j;o?j=await mh({limit:a,projectId:n,type:s,since:w.current}):j=(await ah({limit:a,type:s,since:w.current,projectId:n})).map(C=>({...C,projectId:n??"",projectName:""})),c(S=>[...S,...j]),p(j.length===a),j.length>0&&(w.current=j[j.length-1].timestamp)}catch(j){m(j instanceof Error?j.message:"Failed to load more entries")}finally{u(!1)}},[a,n,s,o]),y=i.useCallback(()=>{c([]),p(!1),w.current=void 0},[]);return i.useEffect(()=>{v()},[v]),i.useEffect(()=>{if(r)return g.current=setInterval(()=>{v()},ML),()=>{g.current&&(clearInterval(g.current),g.current=null)}},[r,v]),{entries:l,loading:d,error:h,refresh:v,clear:y,hasMore:f,loadMore:b}}const Yd={"task:created":"Task Created","task:moved":"Task Moved","task:updated":"Task Updated","task:deleted":"Task Deleted","task:merged":"Task Merged","task:failed":"Task Failed","settings:updated":"Settings Updated"},RL={"task:created":t.jsx(Tn,{size:14,className:"activity-icon created"}),"task:moved":t.jsx(Ho,{size:14,className:"activity-icon moved"}),"task:updated":t.jsx(us,{size:14,className:"activity-icon updated"}),"task:deleted":t.jsx(bn,{size:14,className:"activity-icon deleted"}),"task:merged":t.jsx(Zn,{size:14,className:"activity-icon merged"}),"task:failed":t.jsx(qo,{size:14,className:"activity-icon failed"}),"settings:updated":t.jsx(_o,{size:14,className:"activity-icon settings"})};function IL(e){const n=new Date(e),a=new Date().getTime()-n.getTime(),r=Math.floor(a/6e4),o=Math.floor(a/36e5),l=Math.floor(a/864e5);return r<1?"Just now":r<60?`${r}m ago`:o<24?`${o}h ago`:l<7?`${l}d ago`:n.toLocaleDateString(void 0,{month:"short",day:"numeric"})}function TL({isOpen:e,onClose:n,tasks:s,onOpenTaskDetail:a,projectId:r,projects:o=[],onProjectFilterChange:l,currentProject:c}){const[d,u]=i.useState("all"),[h,m]=i.useState(r||"all"),[f,p]=i.useState(!1);i.useEffect(()=>{m(r||"all")},[r]);const g=d==="all"?void 0:d,w=h==="all"?void 0:h,v=!c&&o.length>0,{entries:b,loading:y,error:j,refresh:S,hasMore:C}=AL({projectId:w,type:g,limit:100,autoRefresh:e,useCentralFeed:v}),x=b.map(_=>({id:_.id,timestamp:_.timestamp,type:_.type,taskId:_.taskId,taskTitle:_.taskTitle,details:_.details,metadata:_.metadata,projectId:_.projectId,projectName:_.projectName})),k=async()=>{try{await m1(),S(),p(!1)}catch{p(!1)}},R=_=>{a&&a(_)},O=_=>{m(_),l?.(_==="all"?void 0:_)};i.useEffect(()=>{if(!e)return;const _=G=>{G.key==="Escape"&&(f?p(!1):n())};return document.addEventListener("keydown",_),()=>document.removeEventListener("keydown",_)},[e,n,f]);const E=d!=="all"||h!=="all";return e?t.jsx("div",{className:"modal-overlay open",onClick:_=>{_.target===_.currentTarget&&n()},role:"dialog","aria-modal":"true","data-testid":"activity-log-modal-overlay",children:t.jsxs("div",{className:"modal modal-lg activity-log-modal","data-testid":"activity-log-modal",children:[t.jsxs("div",{className:"modal-header activity-log-header",children:[t.jsxs("div",{className:"activity-log-title",children:[t.jsx(Oa,{size:18}),t.jsx("span",{children:"Activity Log"})]}),t.jsxs("div",{className:"activity-log-actions",children:[o.length>0&&t.jsxs("div",{className:"activity-log-filter activity-log-filter--project",children:[t.jsx(ws,{size:14}),t.jsxs("select",{value:h,onChange:_=>O(_.target.value),className:"activity-log-filter-select","data-testid":"activity-project-filter",children:[t.jsx("option",{value:"all",children:"All Projects"}),o.map(_=>t.jsx("option",{value:_.id,children:_.name},_.id))]})]}),t.jsxs("div",{className:"activity-log-filter",children:[t.jsx(Gl,{size:14}),t.jsxs("select",{value:d,onChange:_=>u(_.target.value),className:"activity-log-filter-select","data-testid":"activity-filter",children:[t.jsx("option",{value:"all",children:"All Events"}),Object.entries(Yd).map(([_,G])=>t.jsx("option",{value:_,children:G},_))]})]}),t.jsx("button",{className:"activity-log-refresh",onClick:()=>S(),title:"Refresh","data-testid":"activity-refresh",children:y?t.jsx(St,{size:14,className:"spin"}):t.jsx(us,{size:14})}),x.length>0&&t.jsx("button",{className:"activity-log-clear",onClick:()=>p(!0),title:"Clear Log","data-testid":"activity-clear",children:t.jsx(In,{size:14})})]}),t.jsx("button",{className:"modal-close",onClick:n,"aria-label":"Close",title:"Close","data-testid":"activity-close",children:"×"})]}),E&&t.jsxs("div",{className:"activity-log-active-filters",children:[t.jsx("span",{className:"activity-log-filter-label",children:"Active filters:"}),h!=="all"&&t.jsxs("span",{className:"activity-log-filter-badge",children:["Project: ",o.find(_=>_.id===h)?.name||h]}),d!=="all"&&t.jsxs("span",{className:"activity-log-filter-badge",children:["Type: ",Yd[d]]}),t.jsx("button",{className:"activity-log-clear-filters",onClick:()=>{u("all"),m("all"),l?.(void 0)},children:"Clear all"})]}),t.jsxs("div",{className:"activity-log-content","data-testid":"activity-log-content",children:[j&&t.jsxs("div",{className:"activity-log-error","data-testid":"activity-error",children:[t.jsx(zs,{size:16}),t.jsx("span",{children:j})]}),x.length===0&&!y&&!j&&t.jsxs("div",{className:"activity-log-empty","data-testid":"activity-empty",children:[t.jsx(Oa,{size:48,className:"activity-log-empty-icon"}),t.jsx("p",{children:E?"No activity matches the current filters":"No activity recorded yet"}),E&&t.jsx("button",{className:"btn btn-secondary",onClick:()=>{u("all"),m("all"),l?.(void 0)},children:"Clear Filters"})]}),t.jsx("div",{className:"activity-log-list",children:x.map(_=>t.jsxs("div",{className:"activity-log-entry","data-testid":"activity-entry",children:[t.jsx("div",{className:"activity-log-entry-icon",children:RL[_.type]}),t.jsxs("div",{className:"activity-log-entry-content",children:[t.jsxs("div",{className:"activity-log-entry-header",children:[t.jsx("span",{className:"activity-log-entry-type",children:Yd[_.type]}),t.jsx("span",{className:"activity-log-entry-time",children:IL(_.timestamp)})]}),t.jsxs("div",{className:"activity-log-entry-details",children:[_.taskId&&t.jsx("button",{className:"activity-log-task-link",onClick:()=>R(_.taskId),"data-testid":"activity-task-link",children:_.taskId}),_.taskTitle&&t.jsx("span",{className:"activity-log-task-title",children:_.taskTitle}),t.jsx("span",{className:"activity-log-entry-text",children:ks(_.details??"")})]}),_.metadata&&Object.keys(_.metadata).length>0&&t.jsxs("div",{className:"activity-log-entry-metadata",children:[typeof _.metadata.from=="string"&&typeof _.metadata.to=="string"&&t.jsxs("span",{className:"activity-log-metadata-item",children:[_.metadata.from," → ",_.metadata.to]}),typeof _.metadata.merged=="boolean"&&t.jsx("span",{className:`activity-log-metadata-item ${_.metadata.merged?"success":"error"}`,children:_.metadata.merged?"Merged":"Not merged"})]})]})]},_.id))}),C&&!y&&t.jsx("button",{className:"activity-log-load-more",onClick:S,"data-testid":"activity-load-more",children:"Load More"}),y&&x.length>0&&t.jsx("div",{className:"activity-log-loading",children:t.jsx(St,{size:20,className:"spin"})})]}),f&&t.jsx("div",{className:"activity-log-confirm-overlay",children:t.jsxs("div",{className:"activity-log-confirm-dialog",children:[t.jsx("h3",{children:"Clear Activity Log?"}),t.jsx("p",{children:"This will permanently delete all activity log entries. This action cannot be undone."}),t.jsxs("div",{className:"activity-log-confirm-actions",children:[t.jsx("button",{className:"activity-log-confirm-cancel",onClick:()=>p(!1),children:"Cancel"}),t.jsx("button",{className:"activity-log-confirm-clear",onClick:k,children:"Clear Log"})]})]})})]})}):null}const fo=[{id:"status",label:"Status",icon:fb},{id:"changes",label:"Changes",icon:ou},{id:"commits",label:"Commits",icon:Sr},{id:"branches",label:"Branches",icon:Is},{id:"worktrees",label:"Worktrees",icon:nk},{id:"stashes",label:"Stashes",icon:Fr},{id:"remotes",label:"Remotes",icon:mb}];function ug({status:e}){switch(e){case"added":case"untracked":return t.jsx($w,{size:14,className:"gm-file-icon gm-file-added"});case"modified":return t.jsx(db,{size:14,className:"gm-file-icon gm-file-modified"});case"deleted":return t.jsx(Iw,{size:14,className:"gm-file-icon gm-file-deleted"});case"renamed":case"copied":return t.jsx(xa,{size:14,className:"gm-file-icon gm-file-renamed"});default:return t.jsx(Lw,{size:14,className:"gm-file-icon"})}}function mg({status:e}){const n=e==="untracked"?"U":e==="added"?"A":e==="modified"?"M":e==="deleted"?"D":e==="renamed"?"R":e==="copied"?"C":"?";return t.jsx("span",{className:`gm-file-badge gm-file-badge-${e}`,children:n})}function PL(e){return i.useCallback(async(n,s)=>{try{await navigator.clipboard.writeText(n),e(`Copied ${s||"to clipboard"}`,"success")}catch{e("Failed to copy","error")}},[e])}function Tr(e){if(!e)return"—";const n=new Date(e);if(isNaN(n.getTime()))return"—";const a=new Date().getTime()-n.getTime(),r=Math.floor(a/6e4);if(r<1)return"just now";if(r<60)return`${r}m ago`;const o=Math.floor(r/60);if(o<24)return`${o}h ago`;const l=Math.floor(o/24);return l<30?`${l}d ago`:n.toLocaleDateString()}function $L({isOpen:e,onClose:n,tasks:s,addToast:a,projectId:r}){const o=ti(),l=ei();Si(e);const{keyboardOverlap:c,viewportHeight:d,viewportOffsetTop:u,keyboardOpen:h}=ea({enabled:l==="mobile"}),m=h?{"--keyboard-overlap":`${c}px`,"--vv-offset-top":`${u}px`,...d!==null?{"--vv-height":`${d}px`}:{}}:{},f=i.useCallback(()=>{if(l==="mobile"){const le=document.activeElement;le instanceof HTMLElement&&le.blur(),window.scrollTo(0,0),requestAnimationFrame(()=>{window.scrollTo(0,0)})}n()},[n,l]),[p,g]=i.useState("status"),[w,v]=i.useState(!1),[b,y]=i.useState(null),j=i.useRef(null);Oi(j,e,"fusion:git-modal-size");const S=Xi(f),C=PL(a),[x,k]=i.useState(null),[R,O]=i.useState([]),[E,_]=i.useState(new Set),[G,H]=i.useState(""),[A,P]=i.useState(!1),[q,Y]=i.useState(null),[ge,L]=i.useState(!1),[M,$]=i.useState(null),[D,N]=i.useState(null),W=i.useRef(0),[de,me]=i.useState([]),[Ne,ve]=i.useState(null),[Me,ie]=i.useState(null),[ye,Z]=i.useState(!1),[fe,Q]=i.useState(20),[F,X]=i.useState(""),[re,U]=i.useState([]),[be,Ue]=i.useState(""),[se,Ve]=i.useState(""),[Le,ct]=i.useState(""),[Ke,oe]=i.useState(null),[Te,Fe]=i.useState([]),[mt,We]=i.useState(!1),[he,pe]=i.useState(null),[De,ut]=i.useState(null),[ht,et]=i.useState(!1),[vt,Oe]=i.useState([]),[tt,ft]=i.useState([]),[Mt,yt]=i.useState(""),[Ge,K]=i.useState(null),[ue,ot]=i.useState(null),[xe,dt]=i.useState(null),[Je,ke]=i.useState(!1),[nt,bt]=i.useState(null),kt=i.useRef(0),[wt,At]=i.useState(null),[Ft,ln]=i.useState(null),Vt=i.useCallback(async()=>{if(e){v(!0),y(null);try{switch(p){case"status":{const le=await yi(r);k(le);break}case"changes":{const[le,Qe]=await Promise.all([yi(r),dr(r)]);k(le),O(Qe),_(new Set),N(null),Y(null),$(null);break}case"commits":{const le=await fS(fe,r);me(le);break}case"branches":{const[le,Qe]=await Promise.all([eo(r),yi(r)]);U(le),k(Qe);break}case"worktrees":{const le=await vS(r);Oe(le);break}case"stashes":{const le=await ol(r);ft(le),ot(null),dt(null),bt(null),kt.current+=1;break}case"remotes":{const le=await yi(r);k(le);break}}}catch(le){y(Ie(le)||"Failed to fetch git data"),a(Ie(le)||"Failed to fetch git data","error")}finally{v(!1)}}},[p,e,fe,a,r]);i.useEffect(()=>{e&&Vt()},[Vt,e]),i.useEffect(()=>{if(!e)return;const le=Qe=>{if(Qe.key==="Escape"){f();return}if((Qe.key==="ArrowUp"||Qe.key==="ArrowDown")&&Qe.altKey){Qe.preventDefault();const xt=fo.findIndex(zt=>zt.id===p);Qe.key==="ArrowUp"&&xt>0?g(fo[xt-1].id):Qe.key==="ArrowDown"&&xt<fo.length-1&&g(fo[xt+1].id)}};return document.addEventListener("keydown",le),()=>document.removeEventListener("keydown",le)},[e,f,p]);const hn=i.useCallback(async le=>{try{await Zm(le,r),a(`Staged ${le.length} file(s)`,"success");const Qe=await dr(r);O(Qe),_(new Set),N(null),Y(null),$(null)}catch(Qe){a(Ie(Qe)||"Failed to stage files","error")}},[a,r]),un=i.useCallback(async le=>{try{await AS(le,r),a(`Unstaged ${le.length} file(s)`,"success");const Qe=await dr(r);O(Qe),_(new Set),N(null),Y(null),$(null)}catch(Qe){a(Ie(Qe)||"Failed to unstage files","error")}},[a,r]),pn=i.useCallback(async le=>{if(await o.confirm({title:"Discard Changes",message:`Discard changes to ${le.length} file(s)? This cannot be undone.`,danger:!0}))try{await RS(le,r),a(`Discarded changes to ${le.length} file(s)`,"success");const[xt,zt]=await Promise.all([dr(r),yi(r)]);O(xt),k(zt),_(new Set),N(null),Y(null),$(null)}catch(xt){a(Ie(xt)||"Failed to discard changes","error")}},[a,r,o]),an=i.useCallback(async le=>{if(le.preventDefault(),!!G.trim()){P(!0);try{const Qe=await eh(G.trim(),r);a(`Committed: ${Qe.hash}`,"success"),H("");const[xt,zt]=await Promise.all([dr(r),yi(r)]);O(xt),k(zt),N(null),Y(null),$(null)}catch(Qe){a(Ie(Qe)||"Failed to commit","error")}finally{P(!1)}}},[G,a,r]),Wt=i.useCallback(async()=>{if(G.trim()){P(!0);try{const le=R.filter(sn=>!sn.staged).map(sn=>sn.file);le.length>0&&await Zm(le,r);const Qe=await eh(G.trim(),r);a(`Committed: ${Qe.hash}`,"success"),H("");const[xt,zt]=await Promise.all([dr(r),yi(r)]);O(xt),k(zt),N(null),Y(null),$(null)}catch(le){a(Ie(le)||"Failed to commit","error")}finally{P(!1)}}},[G,R,a,r]),gn=i.useCallback(async(le,Qe)=>{N({file:le,staged:Qe}),L(!0),$(null);const xt=W.current+1;W.current=xt;try{const zt=await MS(le,Qe,r);if(W.current!==xt)return;Y(zt)}catch(zt){if(W.current!==xt)return;const sn=Ie(zt)||"Failed to load file diff";Y(null),$(sn),a(sn,"error")}finally{W.current===xt&&L(!1)}},[a,r]),cn=i.useCallback(le=>{_(Qe=>{const xt=new Set(Qe);return xt.has(le)?xt.delete(le):xt.add(le),xt})},[]),tn=i.useCallback(async le=>{if(Ne===le){ve(null),ie(null);return}ve(le),Z(!0);try{const Qe=await Zl(le,r);ie(Qe)}catch(Qe){a(Ie(Qe)||"Failed to load diff","error"),ie(null)}finally{Z(!1)}},[Ne,a,r]),Yt=i.useCallback(()=>{Q(le=>Math.min(le+20,100))},[]),Qt=i.useMemo(()=>{if(!F.trim())return de;const le=F.toLowerCase();return de.filter(Qe=>Qe.message.toLowerCase().includes(le)||Qe.author.toLowerCase().includes(le)||Qe.shortHash.toLowerCase().includes(le))},[de,F]),Kt=i.useCallback(async le=>{if(le.preventDefault(),!!be.trim()){v(!0);try{await yS(be.trim(),se.trim()||void 0,r),a(`Created branch ${be}`,"success"),Ue(""),Ve("");const Qe=await eo(r);U(Qe)}catch(Qe){a(Ie(Qe)||"Failed to create branch","error")}finally{v(!1)}}},[be,se,a,r]),Jt=i.useCallback(async le=>{v(!0);try{await wS(le,r),a(`Switched to ${le}`,"success");const[Qe,xt]=await Promise.all([yi(r),eo(r)]);k(Qe),U(xt)}catch(Qe){a(Ie(Qe)||"Failed to checkout branch","error")}finally{v(!1)}},[a,r]),rn=i.useCallback(async le=>{if(await o.confirm({title:"Delete Branch",message:`Delete branch "${le}"?`,danger:!0})){v(!0);try{await Xm(le,void 0,r),a(`Deleted branch ${le}`,"success");const xt=await eo(r);U(xt)}catch(xt){if(Ie(xt).includes("not fully merged")){if(await o.confirm({title:"Force Delete Branch",message:"Branch has unmerged commits. Force delete?",danger:!0}))try{await Xm(le,!0,r),a(`Force deleted branch ${le}`,"success");const sn=await eo(r);U(sn)}catch(sn){a(Ie(sn)||"Failed to delete branch","error")}}else a(Ie(xt)||"Failed to delete branch","error")}finally{v(!1)}}},[a,r,o]),qt=i.useMemo(()=>{if(!Le.trim())return re;const le=Le.toLowerCase();return re.filter(Qe=>Qe.name.toLowerCase().includes(le))},[re,Le]),we=i.useCallback(async le=>{if(Ke===le){oe(null),Fe([]),pe(null),ut(null);return}oe(le),Fe([]),pe(null),ut(null),We(!0);try{const Qe=await xS(le,10,r);Fe(Qe)}catch{Fe([])}finally{We(!1)}},[Ke,r]),ze=i.useCallback(async le=>{if(he===le){pe(null),ut(null);return}pe(le),ut(null),et(!0);try{const Qe=await Zl(le,r);ut(Qe)}catch{ut(null)}finally{et(!1)}},[he,r]),rt=i.useCallback(()=>{oe(null),Fe([]),pe(null),ut(null)},[]),He=i.useCallback(()=>{kt.current+=1,ot(null),dt(null),bt(null),ke(!1)},[]),Ae=i.useCallback(async le=>{le.preventDefault(),K("create"),He();try{await SS(Mt.trim()||void 0,r),a("Changes stashed","success"),yt("");const Qe=await ol(r);ft(Qe)}catch(Qe){a(Ie(Qe)||"Failed to stash changes","error")}finally{K(null)}},[Mt,a,r,He]),pt=i.useCallback(async(le,Qe=!1)=>{K(`apply-${le}`),He();try{await CS(le,Qe,r),a(Qe?"Stash popped":"Stash applied","success");const xt=await ol(r);ft(xt)}catch(xt){a(Ie(xt)||"Failed to apply stash","error")}finally{K(null)}},[a,r,He]),Ct=i.useCallback(async le=>{if(await o.confirm({title:"Drop Stash",message:`Drop stash@{${le}}? This cannot be undone.`,danger:!0})){K(`drop-${le}`),He();try{await ES(le,r),a("Stash dropped","success");const xt=await ol(r);ft(xt)}catch(xt){a(Ie(xt)||"Failed to drop stash","error")}finally{K(null)}}},[a,r,o,He]),Tt=i.useCallback(async le=>{if(ue===le){He();return}const Qe=kt.current+1;kt.current=Qe,ot(le),dt(null),bt(null),ke(!0);try{const xt=await _S(le,r);if(kt.current!==Qe)return;dt(xt)}catch(xt){if(kt.current!==Qe)return;dt(null),bt(Ie(xt)||"Failed to load stash diff")}finally{kt.current===Qe&&ke(!1)}},[ue,r,He]),Gt=i.useCallback(async()=>{At("fetch");try{const le=await kS(void 0,r);ln(le),a(le.message||"Fetch completed",le.fetched?"success":"info");const Qe=await yi(r);k(Qe)}catch(le){a(Ie(le)||"Fetch failed","error")}finally{At(null)}},[a,r]),nn=i.useCallback(async le=>{At("pull");try{const Qe=await jS(le,r);if(ln(Qe),Qe.conflict)a("Merge conflict detected. Resolve manually.","error");else{const zt=le?.rebase?"Pull --rebase completed":"Pull completed";a(Qe.message||zt,"success")}const xt=await yi(r);k(xt)}catch(Qe){a(Ie(Qe)||"Pull failed","error")}finally{At(null)}},[a,r]),Ht=i.useCallback(async()=>{At("push");try{const le=await NS(r);ln(le),a(le.message||"Push completed","success");const Qe=await yi(r);k(Qe)}catch(le){a(Ie(le)||"Push failed","error")}finally{At(null)}},[a,r]),on=i.useMemo(()=>R.filter(le=>le.staged),[R]),ae=i.useMemo(()=>R.filter(le=>!le.staged),[R]);return e?t.jsx("div",{className:"modal-overlay open git-manager-modal-overlay",...S,role:"dialog","aria-modal":"true",children:t.jsxs("div",{className:"modal gm-modal",ref:j,style:m,children:[t.jsxs("div",{className:"modal-header",children:[t.jsxs("h3",{children:[t.jsx(lu,{size:18,style:{marginRight:8,verticalAlign:"middle"}}),"Git Manager"]}),t.jsxs("div",{className:"gm-header-actions",children:[t.jsx("button",{className:"btn btn-sm",onClick:Vt,disabled:w,title:"Refresh",children:t.jsx(us,{size:14,className:w?"spin":""})}),t.jsx("button",{className:"modal-close",onClick:f,"aria-label":"Close",children:t.jsx(bn,{size:18})})]})]}),t.jsxs("div",{className:"gm-layout",children:[t.jsx("nav",{className:"gm-sidebar",role:"tablist","aria-label":"Git Manager Sections",children:fo.map(le=>{const Qe=le.icon;return t.jsxs("button",{role:"tab","aria-selected":p===le.id,className:`gm-nav-item${p===le.id?" active":""}`,onClick:()=>g(le.id),children:[t.jsx(Qe,{size:16}),t.jsx("span",{className:"gm-nav-label",children:le.label})]},le.id)})}),t.jsxs("div",{className:"gm-content",role:"tabpanel",children:[w&&t.jsxs("div",{className:"gm-loading",children:[t.jsx(St,{size:24,className:"spin"}),t.jsx("span",{children:"Loading..."})]}),b&&!w&&t.jsxs("div",{className:"gm-error",children:[t.jsx(zs,{size:18}),t.jsx("span",{children:b}),t.jsx("button",{className:"btn btn-sm",onClick:Vt,children:"Retry"})]}),p==="status"&&!w&&x&&t.jsx(DL,{status:x,copyToClipboard:C}),p==="changes"&&!w&&t.jsx(LL,{status:x,stagedFiles:on,unstagedFiles:ae,selectedFiles:E,toggleFileSelection:cn,onStageFiles:hn,onUnstageFiles:un,onDiscardChanges:pn,onSelectDiffFile:gn,selectedDiffTarget:D,changeDiff:q,loadingChangeDiff:ge,changeDiffError:M,commitMessage:G,setCommitMessage:H,onCommit:an,onStageAllAndCommit:Wt,committing:A}),p==="commits"&&!w&&t.jsx(OL,{commits:Qt,commitSearch:F,setCommitSearch:X,selectedCommit:Ne,commitDiff:Me,loadingDiff:ye,onCommitClick:tn,onLoadMore:Yt,canLoadMore:de.length>=fe&&fe<100,copyToClipboard:C}),p==="branches"&&!w&&t.jsx(FL,{branches:qt,branchSearch:Le,setBranchSearch:ct,newBranchName:be,setNewBranchName:Ue,branchBase:se,setBranchBase:Ve,onCreateBranch:Kt,onCheckoutBranch:Jt,onDeleteBranch:rn,loading:w,allBranches:re,selectedBranch:Ke,branchCommits:Te,loadingBranchCommits:mt,expandedBranchCommit:he,branchCommitDiff:De,loadingBranchCommitDiff:ht,onSelectBranch:we,onBranchCommitClick:ze,onCloseBranchDetails:rt}),p==="worktrees"&&!w&&t.jsx(zL,{worktrees:vt}),p==="stashes"&&!w&&t.jsx(BL,{stashes:tt,stashMessage:Mt,setStashMessage:yt,onCreateStash:Ae,onApplyStash:pt,onDropStash:Ct,onToggleStashDiff:Tt,stashLoading:Ge,expandedStashIndex:ue,stashDiff:xe,loadingStashDiff:Je,stashDiffError:nt}),p==="remotes"&&!w&&t.jsx(UL,{status:x,remoteLoading:wt,lastRemoteResult:Ft,onFetch:Gt,onPull:nn,onPush:Ht,addToast:a,projectId:r,copyToClipboard:C})]})]})]})}):null}function DL({status:e,copyToClipboard:n}){return t.jsxs("div",{className:"gm-panel","data-testid":"status-panel",children:[t.jsx("div",{className:"gm-panel-header",children:t.jsx("h4",{children:"Repository Status"})}),t.jsxs("div",{className:"gm-status-grid",children:[t.jsxs("div",{className:"gm-status-card",children:[t.jsx("span",{className:"gm-status-label",children:"Branch"}),t.jsxs("span",{className:"gm-status-value",children:[t.jsx(Is,{size:14}),t.jsx("span",{children:e.branch})]})]}),t.jsxs("div",{className:"gm-status-card",children:[t.jsx("span",{className:"gm-status-label",children:"Commit"}),t.jsxs("span",{className:"gm-status-value",children:[t.jsx("code",{className:"gm-hash",children:e.commit}),t.jsx("button",{className:"gm-icon-btn",onClick:()=>n(e.commit,"commit hash"),title:"Copy commit hash",children:t.jsx(ba,{size:12})})]})]}),t.jsxs("div",{className:"gm-status-card",children:[t.jsx("span",{className:"gm-status-label",children:"Working Tree"}),t.jsx("span",{className:`gm-status-badge ${e.isDirty?"dirty":"clean"}`,children:e.isDirty?t.jsxs(t.Fragment,{children:[t.jsx(zs,{size:12}),"Modified"]}):t.jsxs(t.Fragment,{children:[t.jsx(Zn,{size:12}),"Clean"]})})]}),t.jsxs("div",{className:"gm-status-card",children:[t.jsx("span",{className:"gm-status-label",children:"Remote Sync"}),t.jsxs("span",{className:"gm-status-value",children:[e.ahead>0&&t.jsxs("span",{className:"gm-ahead",title:`${e.ahead} commit(s) ahead`,children:[t.jsx(La,{size:12}),e.ahead]}),e.behind>0&&t.jsxs("span",{className:"gm-behind",title:`${e.behind} commit(s) behind`,children:[t.jsx(Uo,{size:12}),e.behind]}),e.ahead===0&&e.behind===0&&t.jsxs("span",{className:"gm-in-sync",children:[t.jsx(Zn,{size:12}),"Up to date"]})]})]})]})]})}function LL({status:e,stagedFiles:n,unstagedFiles:s,selectedFiles:a,toggleFileSelection:r,onStageFiles:o,onUnstageFiles:l,onDiscardChanges:c,onSelectDiffFile:d,selectedDiffTarget:u,changeDiff:h,loadingChangeDiff:m,changeDiffError:f,commitMessage:p,setCommitMessage:g,onCommit:w,onStageAllAndCommit:v,committing:b}){const y=s.filter(S=>a.has(`unstaged:${S.file}`)),j=n.filter(S=>a.has(`staged:${S.file}`));return t.jsxs("div",{className:"gm-panel","data-testid":"changes-panel",children:[e&&t.jsxs("div",{className:"gm-changes-header",children:[t.jsxs("span",{className:"gm-branch-indicator",children:[t.jsx(Is,{size:14}),e.branch]}),e.isDirty&&t.jsx("span",{className:"gm-dirty-badge",children:"Modified"})]}),t.jsxs("div",{className:"gm-changes-split",children:[t.jsxs("div",{className:"gm-changes-lists",children:[t.jsxs("div",{className:"gm-file-section",children:[t.jsxs("div",{className:"gm-file-section-header",children:[t.jsxs("h5",{children:["Unstaged Changes (",s.length,")"]}),t.jsxs("div",{className:"gm-file-section-actions",children:[y.length>0&&t.jsxs(t.Fragment,{children:[t.jsxs("button",{className:"btn btn-sm btn-primary",onClick:()=>o(y.map(S=>S.file)),title:"Stage selected",children:[t.jsx(Tn,{size:12})," Stage (",y.length,")"]}),t.jsx("button",{className:"btn btn-sm btn-danger",onClick:()=>c(y.map(S=>S.file)),title:"Discard selected",children:t.jsx(qo,{size:12})})]}),s.length>0&&t.jsx("button",{className:"btn btn-sm",onClick:()=>o(s.map(S=>S.file)),title:"Stage all",children:"Stage All"})]})]}),t.jsx("div",{className:"gm-file-list gm-file-list-unstaged","data-testid":"gm-file-list-unstaged",children:s.length===0?t.jsx("div",{className:"gm-empty",children:"No unstaged changes"}):s.map(S=>{const C=u?.file===S.file&&u.staged===!1;return t.jsxs("div",{className:`gm-file-item${C?" active":""}`,onClick:()=>d(S.file,!1),role:"button",tabIndex:0,onKeyDown:x=>{(x.key==="Enter"||x.key===" ")&&(x.preventDefault(),d(S.file,!1))},children:[t.jsx("label",{className:"gm-file-checkbox",onClick:x=>x.stopPropagation(),children:t.jsx("input",{type:"checkbox",checked:a.has(`unstaged:${S.file}`),onChange:()=>r(`unstaged:${S.file}`)})}),t.jsx(ug,{status:S.status}),t.jsx("span",{className:"gm-file-name",title:S.file,children:t.jsx("bdo",{dir:"ltr",children:S.file})}),t.jsx(mg,{status:S.status}),t.jsx("button",{className:"gm-icon-btn",onClick:x=>{x.stopPropagation(),o([S.file])},title:"Stage file",children:t.jsx(Tn,{size:12})})]},`unstaged:${S.file}`)})})]}),t.jsxs("div",{className:"gm-file-section",children:[t.jsxs("div",{className:"gm-file-section-header",children:[t.jsxs("h5",{children:["Staged Changes (",n.length,")"]}),t.jsxs("div",{className:"gm-file-section-actions",children:[j.length>0&&t.jsxs("button",{className:"btn btn-sm",onClick:()=>l(j.map(S=>S.file)),title:"Unstage selected",children:["Unstage (",j.length,")"]}),n.length>0&&t.jsx("button",{className:"btn btn-sm",onClick:()=>l(n.map(S=>S.file)),title:"Unstage all",children:"Unstage All"})]})]}),t.jsx("div",{className:"gm-file-list gm-file-list-staged","data-testid":"gm-file-list-staged",children:n.length===0?t.jsx("div",{className:"gm-empty",children:"No staged changes"}):n.map(S=>{const C=u?.file===S.file&&u.staged===!0;return t.jsxs("div",{className:`gm-file-item staged${C?" active":""}`,onClick:()=>d(S.file,!0),role:"button",tabIndex:0,onKeyDown:x=>{(x.key==="Enter"||x.key===" ")&&(x.preventDefault(),d(S.file,!0))},children:[t.jsx("label",{className:"gm-file-checkbox",onClick:x=>x.stopPropagation(),children:t.jsx("input",{type:"checkbox",checked:a.has(`staged:${S.file}`),onChange:()=>r(`staged:${S.file}`)})}),t.jsx(ug,{status:S.status}),t.jsx("span",{className:"gm-file-name",title:S.file,children:t.jsx("bdo",{dir:"ltr",children:S.file})}),t.jsx(mg,{status:S.status}),t.jsx("button",{className:"gm-icon-btn",onClick:x=>{x.stopPropagation(),l([S.file])},title:"Unstage file",children:t.jsx(bn,{size:12})})]},`staged:${S.file}`)})})]})]}),t.jsx("div",{className:"gm-changes-diff",children:u||m||h||f?t.jsxs("div",{className:"gm-diff-section",children:[u&&t.jsxs("div",{className:"gm-diff-target",children:[t.jsx(ou,{size:14}),t.jsxs("span",{children:[u.staged?"Staged":"Unstaged"," diff: "]}),t.jsx("code",{children:u.file})]}),m&&t.jsxs("div",{className:"gm-diff-loading",children:[t.jsx(St,{size:16,className:"spin"}),"Loading diff..."]}),f&&!m&&t.jsx("div",{className:"gm-diff-error",children:f}),h&&!m&&t.jsxs("div",{className:"gm-diff-viewer",children:[h.stat&&t.jsx("pre",{className:"gm-diff-stat",children:h.stat}),t.jsx("pre",{className:"gm-diff-patch",children:h.patch})]})]}):t.jsxs("div",{className:"gm-diff-empty",children:[t.jsx(ou,{size:20}),t.jsx("span",{children:"Select a file to view its diff"})]})})]}),t.jsxs("form",{className:"gm-commit-form",onSubmit:w,children:[t.jsx("textarea",{className:"gm-commit-input",placeholder:"Commit message...",value:p,onChange:S=>g(S.target.value),rows:3,disabled:b}),t.jsxs("div",{className:"gm-commit-actions",children:[t.jsxs("button",{type:"submit",className:"btn btn-sm btn-primary",disabled:b||!p.trim()||n.length===0,title:n.length===0?"No staged changes to commit":"Commit staged changes",children:[b?t.jsx(St,{size:14,className:"spin"}):t.jsx(Da,{size:14}),"Commit"]}),s.length>0&&t.jsx("button",{type:"button",className:"btn btn-sm",onClick:v,disabled:b||!p.trim(),title:"Stage all and commit",children:"Stage All & Commit"})]})]})]})}function OL({commits:e,commitSearch:n,setCommitSearch:s,selectedCommit:a,commitDiff:r,loadingDiff:o,onCommitClick:l,onLoadMore:c,canLoadMore:d,copyToClipboard:u}){return t.jsxs("div",{className:"gm-panel","data-testid":"commits-panel",children:[t.jsxs("div",{className:"gm-panel-header",children:[t.jsx("h4",{children:"Commits"}),t.jsxs("div",{className:"gm-search-box",children:[t.jsx(Gi,{size:14}),t.jsx("input",{type:"text",placeholder:"Search commits...",value:n,onChange:h=>s(h.target.value)})]})]}),t.jsx("div",{className:"gm-commits-list",children:e.length===0?t.jsx("div",{className:"gm-empty",children:n?"No matching commits":"No commits found"}):e.map((h,m)=>t.jsxs("div",{className:"gm-commit-item",children:[t.jsxs("div",{className:"gm-commit-graph",children:[t.jsx("div",{className:"gm-commit-dot"}),m<e.length-1&&t.jsx("div",{className:"gm-commit-line"})]}),t.jsxs("div",{className:"gm-commit-body",children:[t.jsxs("button",{className:"gm-commit-header",onClick:()=>l(h.hash),children:[t.jsxs("div",{className:"gm-commit-top-row",children:[t.jsx("code",{className:"gm-hash",children:h.shortHash}),t.jsx("span",{className:"gm-commit-message",title:h.message,children:h.message})]}),t.jsxs("div",{className:"gm-commit-meta",children:[t.jsx("span",{children:h.author}),t.jsx("span",{children:"•"}),t.jsx("span",{children:Tr(h.date)}),h.parents.length>1&&t.jsx("span",{className:"gm-merge-badge",children:"merge"})]})]}),t.jsx("div",{className:"gm-commit-actions-row",children:t.jsx("button",{className:"gm-icon-btn",onClick:()=>u(h.hash,"commit hash"),title:"Copy full hash",children:t.jsx(ba,{size:12})})}),a===h.hash&&t.jsx("div",{className:"gm-commit-diff",children:o?t.jsxs("div",{className:"gm-diff-loading",children:[t.jsx(St,{size:16,className:"spin"}),"Loading diff..."]}):r?t.jsxs(t.Fragment,{children:[h.body&&t.jsx("div",{className:"gm-commit-message-full",children:h.body}),r.stat&&t.jsx("pre",{className:"gm-diff-stat",children:r.stat}),t.jsx("pre",{className:"gm-diff-patch",children:r.patch})]}):t.jsx("div",{className:"gm-diff-error",children:"Failed to load diff"})})]})]},h.hash))}),d&&t.jsx("button",{className:"gm-load-more",onClick:c,children:"Load more commits"})]})}function FL({branches:e,branchSearch:n,setBranchSearch:s,newBranchName:a,setNewBranchName:r,branchBase:o,setBranchBase:l,onCreateBranch:c,onCheckoutBranch:d,onDeleteBranch:u,loading:h,allBranches:m,selectedBranch:f,branchCommits:p,loadingBranchCommits:g,expandedBranchCommit:w,branchCommitDiff:v,loadingBranchCommitDiff:b,onSelectBranch:y,onBranchCommitClick:j,onCloseBranchDetails:S}){return t.jsxs("div",{className:"gm-panel","data-testid":"branches-panel",children:[t.jsxs("div",{className:"gm-panel-header",children:[t.jsx("h4",{children:"Branches"}),t.jsxs("div",{className:"gm-search-box",children:[t.jsx(Gi,{size:14}),t.jsx("input",{type:"text",placeholder:"Filter branches...",value:n,onChange:C=>s(C.target.value)})]})]}),t.jsxs("form",{className:"gm-create-form",onSubmit:c,children:[t.jsx("input",{type:"text",placeholder:"New branch name",value:a,onChange:C=>r(C.target.value),disabled:h}),t.jsxs("select",{value:o,onChange:C=>l(C.target.value),disabled:h,className:"gm-branch-select",children:[t.jsx("option",{value:"",children:"Base: HEAD"}),m.map(C=>t.jsx("option",{value:C.name,children:C.name},C.name))]}),t.jsxs("button",{type:"submit",className:"btn btn-primary btn-sm",disabled:h||!a.trim(),children:[t.jsx(Tn,{size:14}),"Create"]})]}),t.jsx("div",{className:"gm-branches-list",children:e.length===0?t.jsx("div",{className:"gm-empty",children:n?"No matching branches":"No branches found"}):e.map(C=>t.jsxs("div",{children:[t.jsxs("div",{className:`gm-branch-item${C.isCurrent?" current":""}${f===C.name?" selected":""}`,onClick:()=>y(C.name),children:[t.jsxs("div",{className:"gm-branch-info",children:[t.jsxs("span",{className:"gm-branch-name",children:[C.isCurrent&&t.jsx(gs,{size:14,className:"gm-current-icon"}),C.name]}),C.remote&&t.jsxs("span",{className:"gm-branch-remote",children:["→ ",C.remote]}),C.lastCommitDate&&t.jsx("span",{className:"gm-branch-date",children:Tr(C.lastCommitDate)})]}),t.jsx("div",{className:"gm-branch-actions",children:!C.isCurrent&&t.jsxs(t.Fragment,{children:[t.jsx("button",{className:"btn btn-sm",onClick:x=>{x.stopPropagation(),d(C.name)},disabled:h,title:"Checkout",children:t.jsx(Is,{size:14})}),t.jsx("button",{className:"btn btn-sm btn-danger",onClick:x=>{x.stopPropagation(),u(C.name)},disabled:h,title:"Delete",children:t.jsx(In,{size:14})})]})})]}),f===C.name&&t.jsxs("div",{className:"gm-branch-details",children:[t.jsxs("div",{className:"gm-branch-details-header",children:[t.jsxs("span",{className:"gm-branch-details-title",children:[t.jsx(Sr,{size:14}),"Commits on ",C.name]}),t.jsx("button",{className:"gm-icon-btn",onClick:S,title:"Close","data-testid":"close-branch-details",children:t.jsx(bn,{size:14})})]}),g?t.jsxs("div",{className:"gm-branch-details-loading",children:[t.jsx(St,{size:16,className:"spin"}),"Loading commits..."]}):p.length===0?t.jsx("div",{className:"gm-empty",children:"No commits found"}):t.jsx("div",{className:"gm-branch-commits-list",children:p.map(x=>t.jsxs("div",{className:"gm-branch-commit",children:[t.jsxs("button",{className:"gm-branch-commit-row",onClick:()=>j(x.hash),"data-testid":`branch-commit-${x.shortHash}`,children:[t.jsx("span",{className:"gm-commit-hash",children:x.shortHash}),t.jsx("span",{className:"gm-commit-message",title:x.message,children:x.message}),t.jsxs("div",{className:"gm-commit-meta",children:[t.jsx("span",{children:x.author}),t.jsx("span",{children:"•"}),t.jsx("span",{children:Tr(x.date)}),x.parents.length>1&&t.jsx("span",{className:"gm-merge-badge",children:"merge"})]})]}),w===x.hash&&t.jsx("div",{className:"gm-commit-diff",children:b?t.jsxs("div",{className:"gm-diff-loading",children:[t.jsx(St,{size:16,className:"spin"}),"Loading diff..."]}):v?t.jsxs(t.Fragment,{children:[(x.body||x.message)&&t.jsx("div",{className:"gm-commit-message-full",children:x.body||x.message}),v.stat&&t.jsx("pre",{className:"gm-diff-stat",children:v.stat}),t.jsx("pre",{className:"gm-diff-patch",children:v.patch})]}):t.jsx("div",{className:"gm-diff-error",children:"Failed to load diff"})})]},x.hash))})]})]},C.name))})]})}function zL({worktrees:e}){return t.jsxs("div",{className:"gm-panel","data-testid":"worktrees-panel",children:[t.jsxs("div",{className:"gm-panel-header",children:[t.jsx("h4",{children:"Worktrees"}),t.jsxs("div",{className:"gm-worktree-stats",children:[t.jsxs("span",{children:[e.length," total"]}),t.jsx("span",{className:"gm-stat-separator",children:"•"}),t.jsxs("span",{children:[e.filter(n=>n.taskId).length," in use"]})]})]}),t.jsx("div",{className:"gm-worktrees-list",children:e.map(n=>t.jsx("div",{className:`gm-worktree-item${n.isMain?" main":""}`,children:t.jsxs("div",{className:"gm-worktree-info",children:[t.jsxs("div",{className:"gm-worktree-path-row",children:[n.isMain&&t.jsx("span",{className:"gm-badge main",children:"main"}),n.isBare&&t.jsx("span",{className:"gm-badge bare",children:"bare"}),t.jsx("span",{className:"gm-worktree-path",title:n.path,children:tm(n.path)||n.path})]}),t.jsxs("div",{className:"gm-worktree-detail",children:[n.branch&&t.jsxs("span",{className:"gm-worktree-branch",children:[t.jsx(Is,{size:12}),n.branch]}),n.taskId&&t.jsx("span",{className:"gm-worktree-task",children:n.taskId})]})]})},n.path))})]})}function BL({stashes:e,stashMessage:n,setStashMessage:s,onCreateStash:a,onApplyStash:r,onDropStash:o,onToggleStashDiff:l,stashLoading:c,expandedStashIndex:d,stashDiff:u,loadingStashDiff:h,stashDiffError:m}){return t.jsxs("div",{className:"gm-panel","data-testid":"stashes-panel",children:[t.jsx("div",{className:"gm-panel-header",children:t.jsx("h4",{children:"Stashes"})}),t.jsxs("form",{className:"gm-create-form",onSubmit:a,children:[t.jsx("input",{type:"text",placeholder:"Stash message (optional)",value:n,onChange:f=>s(f.target.value),disabled:c!==null}),t.jsxs("button",{type:"submit",className:"btn btn-primary btn-sm",disabled:c!==null,children:[c==="create"?t.jsx(St,{size:14,className:"spin"}):t.jsx(Fr,{size:14}),"Stash"]})]}),t.jsx("div",{className:"gm-stash-list",children:e.length===0?t.jsx("div",{className:"gm-empty",children:"No stashes"}):e.map(f=>t.jsxs("div",{className:"gm-stash-item",children:[t.jsxs("div",{className:"gm-stash-header",children:[t.jsxs("div",{className:"gm-stash-info",children:[t.jsxs("span",{className:"gm-stash-ref",children:["stash@",`{${f.index}}`]}),t.jsx("span",{className:"gm-stash-message",children:f.message}),t.jsxs("div",{className:"gm-stash-meta",children:[f.branch&&t.jsxs("span",{className:"gm-stash-branch",children:[t.jsx(Is,{size:12}),f.branch]}),t.jsx("span",{children:Tr(f.date)})]})]}),t.jsxs("div",{className:"gm-stash-actions",children:[t.jsx("button",{className:"btn btn-sm",onClick:()=>l(f.index),disabled:c!==null,children:d===f.index?"Hide":"View"}),t.jsx("button",{className:"btn btn-sm btn-primary",onClick:()=>r(f.index,!1),disabled:c!==null,title:"Apply stash (keep)",children:c===`apply-${f.index}`?t.jsx(St,{size:14,className:"spin"}):"Apply"}),t.jsx("button",{className:"btn btn-sm",onClick:()=>r(f.index,!0),disabled:c!==null,title:"Pop stash (apply and drop)",children:"Pop"}),t.jsx("button",{className:"btn btn-sm btn-danger",onClick:()=>o(f.index),disabled:c!==null,title:"Drop stash",children:c===`drop-${f.index}`?t.jsx(St,{size:14,className:"spin"}):t.jsx(In,{size:14})})]})]}),d===f.index&&t.jsx("div",{className:"gm-stash-diff",children:h?t.jsxs("div",{className:"gm-diff-loading",children:[t.jsx(St,{size:14,className:"spin"}),"Loading stash diff…"]}):m?t.jsx("div",{className:"gm-diff-error",children:m}):u?t.jsxs("div",{className:"gm-diff-viewer",children:[u.stat&&t.jsx("pre",{className:"gm-diff-stat",children:u.stat}),t.jsx("pre",{className:"gm-diff-patch",children:u.patch})]}):null})]},f.index))})]})}function UL({status:e,remoteLoading:n,lastRemoteResult:s,onFetch:a,onPull:r,onPush:o,addToast:l,projectId:c,copyToClipboard:d}){const u=pe=>{try{return new URL(pe).hostname}catch{return pe.replace(/^git@/,"").split(":")[0]||pe}},[h,m]=i.useState([]),[f,p]=i.useState(!1),[g,w]=i.useState(null),[v,b]=i.useState(""),[y,j]=i.useState(""),[S,C]=i.useState(null),[x,k]=i.useState(""),[R,O]=i.useState(""),[E,_]=i.useState(!1),[G,H]=i.useState(!1),A=i.useRef(null),[P,q]=i.useState([]),[Y,ge]=i.useState(!1),[L,M]=i.useState(null),[$,D]=i.useState([]),[N,W]=i.useState(!1),[de,me]=i.useState(null),Ne=i.useRef(0),ve=h.find(pe=>pe.name===L);i.useEffect(()=>{(n!==null||f)&&H(!1)},[n,f]),i.useEffect(()=>{if(!G)return;const pe=ut=>{A.current?.contains(ut.target)||H(!1)},De=ut=>{ut.key==="Escape"&&H(!1)};return document.addEventListener("mousedown",pe),document.addEventListener("keydown",De),()=>{document.removeEventListener("mousedown",pe),document.removeEventListener("keydown",De)}},[G]);const[Me,ie]=i.useState(null),[ye,Z]=i.useState(null),[fe,Q]=i.useState(!1),[F,X]=i.useState(null),[re,U]=i.useState(null),[be,Ue]=i.useState(!1);i.useEffect(()=>{se()},[]),i.useEffect(()=>{e&&e.ahead>0?Ve():e&&e.ahead===0&&q([])},[e?.ahead]),i.useEffect(()=>{h.length>0&&!L&&M(h[0].name)},[h]),i.useEffect(()=>{L?Le(L):(D([]),me(null))},[L]),i.useEffect(()=>{!L||!s||Le(L)},[L,s]),i.useEffect(()=>{L&&!h.find(pe=>pe.name===L)&&M(h.length>0?h[0].name:null)},[h,L]);const se=async()=>{p(!0);try{const pe=await oS(c);m(pe)}catch(pe){l(Ie(pe)||"Failed to load remotes","error")}finally{p(!1)}},Ve=async()=>{ge(!0);try{const pe=await gS(c);q(pe)}catch{q([])}finally{ge(!1)}},Le=async pe=>{const De=Ne.current+1;Ne.current=De,W(!0),me(null);try{const ut=await bS(pe,void 0,10,c);if(Ne.current!==De)return;D(ut)}catch(ut){if(Ne.current!==De)return;me(Ie(ut)||"Failed to load remote commits"),D([])}finally{Ne.current===De&&W(!1)}},ct=ti(),Ke=async pe=>{if(pe.preventDefault(),!(!v.trim()||!y.trim())){w("add");try{await lS(v.trim(),y.trim(),c),l(`Remote '${v}' added successfully`,"success"),b(""),j(""),_(!1),await se()}catch(De){l(Ie(De)||"Failed to add remote","error")}finally{w(null)}}},oe=async pe=>{if(await ct.confirm({title:"Remove Remote",message:`Are you sure you want to remove remote '${pe}'?`,danger:!0})){w(`remove-${pe}`);try{await cS(pe,c),l(`Remote '${pe}' removed`,"success"),await se()}catch(ut){l(Ie(ut)||"Failed to remove remote","error")}finally{w(null)}}},Te=async pe=>{if(R.trim()){w(`rename-${pe}`);try{await dS(pe,R.trim(),c),l(`Remote renamed to '${R.trim()}'`,"success"),C(null),O(""),await se()}catch(De){l(Ie(De)||"Failed to rename remote","error")}finally{w(null)}}},Fe=async pe=>{if(x.trim()){w(`url-${pe}`);try{await uS(pe,x.trim(),c),l("Remote URL updated","success"),C(null),k(""),await se()}catch(De){l(Ie(De)||"Failed to update remote URL","error")}finally{w(null)}}},mt=i.useCallback(async(pe,De)=>{if(De==="ahead"){if(Me===pe){ie(null),Z(null);return}ie(pe),Z(null),Q(!0);try{const ut=await Zl(pe);Z(ut)}catch{Z(null)}finally{Q(!1)}}else{if(F===pe){X(null),U(null);return}X(pe),U(null),Ue(!0);try{const ut=await Zl(pe);U(ut)}catch{U(null)}finally{Ue(!1)}}},[Me,F]),We=pe=>{C(`url-${pe.name}`),k(pe.pushUrl||pe.fetchUrl)},he=pe=>{C(`name-${pe.name}`),O(pe.name)};return t.jsx("div",{className:"gm-panel gm-remotes-panel","data-testid":"remotes-panel",children:t.jsxs("div",{className:"gm-remotes-layout",children:[t.jsxs("div",{className:"gm-remote-selector","data-testid":"remote-selector",children:[t.jsxs("div",{className:"gm-remote-selector-header",children:[t.jsx("span",{className:"gm-remote-selector-title",children:"Remotes"}),t.jsx("button",{className:"btn btn-sm",onClick:()=>_(!E),disabled:g!==null,title:E?"Cancel":"Add Remote",children:E?t.jsx(bn,{size:14}):t.jsx(Tn,{size:14})})]}),E&&t.jsxs("form",{className:"gm-remote-form",onSubmit:Ke,children:[t.jsx("input",{type:"text",placeholder:"Remote name",value:v,onChange:pe=>b(pe.target.value),disabled:g==="add",className:"input gm-input"}),t.jsx("input",{type:"text",placeholder:"Repository URL",value:y,onChange:pe=>j(pe.target.value),disabled:g==="add",className:"input gm-input gm-input-url"}),t.jsxs("button",{type:"submit",className:"btn btn-sm btn-primary",disabled:!v.trim()||!y.trim()||g==="add",children:[g==="add"?t.jsx(St,{size:12,className:"spin"}):t.jsx(Tn,{size:12}),"Add"]})]}),f?t.jsxs("div",{className:"gm-loading",children:[t.jsx(St,{size:16,className:"spin"}),"Loading..."]}):h.length===0?t.jsx("div",{className:"gm-empty",children:"No remotes"}):h.map(pe=>t.jsxs("div",{className:`gm-remote-selector-item${L===pe.name?" selected":""}`,onClick:()=>M(pe.name),role:"button",tabIndex:0,onKeyDown:De=>{(De.key==="Enter"||De.key===" ")&&(De.preventDefault(),M(pe.name))},children:[t.jsxs("div",{className:"gm-remote-selector-info",children:[t.jsxs("span",{className:"gm-remote-selector-name",children:[t.jsx("span",{className:"gm-remote-selector-name-text",children:pe.name}),pe.name==="origin"&&t.jsx("span",{className:"gm-remote-default-badge",children:"default"})]}),t.jsx("span",{className:"gm-remote-selector-host",title:pe.fetchUrl,children:u(pe.fetchUrl)})]}),t.jsx("button",{className:"btn btn-icon btn-sm gm-remote-remove-btn",onClick:De=>{De.stopPropagation(),oe(pe.name)},disabled:g!==null,title:"Remove remote",children:t.jsx(In,{size:14})})]},pe.name))]}),t.jsxs("div",{className:"gm-remote-detail","data-testid":"remote-detail-panel",children:[L&&ve?t.jsxs(t.Fragment,{children:[t.jsxs("div",{className:"gm-remote-sync-card","data-testid":"remote-sync-card",children:[t.jsxs("div",{className:"gm-remote-sync-card-header",children:[t.jsx("span",{className:"gm-remote-sync-card-title",children:L}),e&&(e.ahead>0||e.behind>0)&&t.jsxs("div",{className:"gm-remote-status",children:[e.ahead>0&&t.jsxs("div",{className:"gm-remote-indicator ahead",children:[t.jsx("span",{className:"status-dot status-dot--online","aria-hidden":"true"}),t.jsx(La,{size:14}),e.ahead," to push"]}),e.behind>0&&t.jsxs("div",{className:"gm-remote-indicator behind",children:[t.jsx("span",{className:"status-dot status-dot--pending","aria-hidden":"true"}),t.jsx(Uo,{size:14}),e.behind," to pull"]})]})]}),t.jsxs("div",{className:"gm-remote-actions",children:[t.jsxs("button",{className:"btn btn-primary",onClick:a,disabled:n!==null||f,children:[n==="fetch"?t.jsx(St,{size:14,className:"spin"}):t.jsx(us,{size:14}),"Fetch"]}),t.jsxs("div",{className:"gm-pull-split",ref:A,children:[t.jsxs("button",{className:"btn btn-primary gm-pull-split-main",onClick:()=>{H(!1),r({rebase:!1})},disabled:n!==null||f,children:[n==="pull"?t.jsx(St,{size:14,className:"spin"}):t.jsx(Qs,{size:14}),"Pull"]}),t.jsx("button",{className:"btn btn-primary btn-icon gm-pull-split-toggle",onClick:()=>H(pe=>!pe),disabled:n!==null||f,"aria-label":"Pull options","aria-haspopup":"menu","aria-expanded":G,children:t.jsx(vn,{size:14})}),G?t.jsxs("div",{className:"gm-pull-menu",role:"menu","aria-label":"Pull options menu",children:[t.jsx("button",{className:"gm-pull-menu-item",role:"menuitem",onClick:()=>{H(!1),r({rebase:!1})},children:"Pull"}),t.jsx("button",{className:"gm-pull-menu-item",role:"menuitem",onClick:()=>{H(!1),r({rebase:!0})},children:"Pull --rebase"})]}):null]}),t.jsxs("button",{className:"btn btn-primary",onClick:o,disabled:n!==null||f,children:[n==="push"?t.jsx(St,{size:14,className:"spin"}):t.jsx(La,{size:14}),"Push"]})]})]}),t.jsxs("div",{className:"gm-remote-detail-card","data-testid":"remote-detail-card",children:[t.jsxs("div",{className:"gm-remote-detail-urls",children:[t.jsxs("div",{className:"gm-remote-detail-url-row",children:[t.jsx("span",{className:"gm-url-label",children:"Fetch:"}),S===`url-${L}`?t.jsxs("div",{className:"gm-remote-edit",children:[t.jsx("input",{type:"text",value:x,onChange:pe=>k(pe.target.value),className:"input gm-input",autoFocus:!0}),t.jsx("button",{className:"btn btn-sm btn-primary",onClick:()=>Fe(L),disabled:g===`url-${L}`,children:g===`url-${L}`?t.jsx(St,{size:12,className:"spin"}):t.jsx(gs,{size:12})}),t.jsx("button",{className:"btn btn-sm",onClick:()=>{C(null),k("")},title:"Cancel",children:t.jsx(bn,{size:12})})]}):t.jsxs(t.Fragment,{children:[t.jsx("span",{className:"gm-url-value",title:ve.fetchUrl,children:t.jsx("bdo",{dir:"ltr",children:ve.fetchUrl})}),t.jsxs("div",{className:"gm-remote-inline-actions",children:[t.jsx("button",{className:"btn btn-icon btn-sm",onClick:()=>d(ve.fetchUrl,"fetch URL"),title:"Copy fetch URL",children:t.jsx(ba,{size:14})}),t.jsx("button",{className:"btn btn-icon btn-sm",onClick:()=>We(ve),disabled:g!==null,title:"Edit remote URL",children:t.jsx(Os,{size:14})})]})]})]}),ve.pushUrl&&ve.pushUrl!==ve.fetchUrl&&t.jsxs("div",{className:"gm-remote-detail-url-row",children:[t.jsx("span",{className:"gm-url-label",children:"Push:"}),t.jsx("span",{className:"gm-url-value",title:ve.pushUrl,children:t.jsx("bdo",{dir:"ltr",children:ve.pushUrl})}),t.jsx("div",{className:"gm-remote-inline-actions",children:t.jsx("button",{className:"btn btn-icon btn-sm",onClick:()=>d(ve.pushUrl,"push URL"),title:"Copy push URL",children:t.jsx(ba,{size:14})})})]})]}),t.jsx("div",{className:"gm-remote-detail-name-row",children:S===`name-${L}`?t.jsxs("div",{className:"gm-remote-edit",children:[t.jsx("input",{type:"text",value:R,onChange:pe=>O(pe.target.value),className:"input gm-input",autoFocus:!0}),t.jsx("button",{className:"btn btn-sm btn-primary",onClick:()=>Te(L),disabled:g===`rename-${L}`,children:g===`rename-${L}`?t.jsx(St,{size:12,className:"spin"}):t.jsx(gs,{size:12})}),t.jsx("button",{className:"btn btn-sm",onClick:()=>{C(null),O("")},title:"Cancel",children:t.jsx(bn,{size:12})})]}):t.jsx("button",{className:"btn btn-icon btn-sm",onClick:()=>he(ve),disabled:g!==null,title:"Edit remote name",children:t.jsx(Os,{size:14})})})]}),e&&e.ahead>0&&t.jsxs("div",{className:"gm-remote-section","data-testid":"commits-to-push",children:[t.jsx("div",{className:"gm-section-subheader",children:t.jsxs("h5",{children:[t.jsx(La,{size:14}),"Commits to Push (",e.ahead,")"]})}),Y?t.jsxs("div",{className:"gm-loading",children:[t.jsx(St,{size:14,className:"spin"}),"Loading..."]}):P.length>0?t.jsx("div",{className:"gm-ahead-commits-list","data-testid":"ahead-commits-list",children:P.map(pe=>t.jsxs("div",{className:"gm-commit-item-compact-wrapper",children:[t.jsxs("div",{className:"gm-commit-item-compact gm-commit-clickable",onClick:()=>mt(pe.hash,"ahead"),role:"button",tabIndex:0,onKeyDown:De=>{(De.key==="Enter"||De.key===" ")&&(De.preventDefault(),mt(pe.hash,"ahead"))},title:"Click to view diff",children:[t.jsx("div",{className:"gm-commit-compact-hash",children:t.jsx("code",{className:"gm-hash",children:pe.shortHash})}),t.jsxs("div",{className:"gm-commit-compact-info",children:[t.jsx("span",{className:"gm-commit-message",title:pe.message,children:pe.message}),t.jsxs("span",{className:"gm-commit-meta",children:[t.jsx("span",{children:pe.author}),t.jsx("span",{children:"•"}),t.jsx("span",{children:Tr(pe.date)})]})]}),t.jsx("span",{className:"gm-commit-expand-icon",children:Me===pe.hash?t.jsx(vn,{size:14}):t.jsx(Wn,{size:14})})]}),Me===pe.hash&&t.jsx("div",{className:"gm-commit-diff gm-commit-diff-compact",children:fe?t.jsxs("div",{className:"gm-diff-loading",children:[t.jsx(St,{size:16,className:"spin"}),"Loading diff..."]}):ye?t.jsxs(t.Fragment,{children:[(pe.body||pe.message)&&t.jsx("div",{className:"gm-commit-message-full",children:pe.body||pe.message}),ye.stat&&t.jsx("pre",{className:"gm-diff-stat",children:ye.stat}),t.jsx("pre",{className:"gm-diff-patch",children:ye.patch})]}):t.jsx("div",{className:"gm-diff-error",children:"Failed to load diff"})})]},pe.hash))}):t.jsx("div",{className:"gm-empty",children:"No ahead commits found (may need to fetch first)"})]}),t.jsxs("div",{className:"gm-remote-section","data-testid":"remote-commits-section",children:[t.jsx("div",{className:"gm-section-subheader",children:t.jsxs("h5",{children:[t.jsx(fb,{size:14}),"Recent commits on ",L]})}),N?t.jsxs("div",{className:"gm-loading",children:[t.jsx(St,{size:14,className:"spin"}),"Loading commits..."]}):de?t.jsxs("div",{className:"gm-error",children:[t.jsx(zs,{size:14}),de]}):$.length===0?t.jsxs("div",{className:"gm-empty",children:["No commits found on ",L,". Try fetching first."]}):t.jsx("div",{className:"gm-remote-commits-list","data-testid":"remote-commits-list",children:$.map(pe=>t.jsxs("div",{className:"gm-commit-item-compact-wrapper",children:[t.jsxs("div",{className:"gm-commit-item-compact gm-commit-clickable",onClick:()=>mt(pe.hash,"remote"),role:"button",tabIndex:0,onKeyDown:De=>{(De.key==="Enter"||De.key===" ")&&(De.preventDefault(),mt(pe.hash,"remote"))},title:"Click to view diff",children:[t.jsx("div",{className:"gm-commit-compact-hash",children:t.jsx("code",{className:"gm-hash",children:pe.shortHash})}),t.jsxs("div",{className:"gm-commit-compact-info",children:[t.jsx("span",{className:"gm-commit-message",title:pe.message,children:pe.message}),t.jsxs("span",{className:"gm-commit-meta",children:[t.jsx("span",{children:pe.author}),t.jsx("span",{children:"•"}),t.jsx("span",{children:Tr(pe.date)})]})]}),t.jsx("span",{className:"gm-commit-expand-icon",children:F===pe.hash?t.jsx(vn,{size:14}):t.jsx(Wn,{size:14})})]}),F===pe.hash&&t.jsx("div",{className:"gm-commit-diff gm-commit-diff-compact",children:be?t.jsxs("div",{className:"gm-diff-loading",children:[t.jsx(St,{size:16,className:"spin"}),"Loading diff..."]}):re?t.jsxs(t.Fragment,{children:[(pe.body||pe.message)&&t.jsx("div",{className:"gm-commit-message-full",children:pe.body||pe.message}),re.stat&&t.jsx("pre",{className:"gm-diff-stat",children:re.stat}),t.jsx("pre",{className:"gm-diff-patch",children:re.patch})]}):t.jsx("div",{className:"gm-diff-error",children:"Failed to load diff"})})]},pe.hash))})]})]}):t.jsx("div",{className:"gm-empty",children:"Select a remote to view details"}),s&&t.jsx("div",{className:"gm-remote-result",children:s.message})]})]})})}const fr={name:"",description:"",mode:"prompt",phase:"pre-merge",prompt:"",scriptName:"",enabled:!0,defaultOn:!1,modelProvider:"",modelId:""};function HL(e,n){return e&&n?`${e}/${n}`:""}function qL(e){if(!e)return{provider:"",modelId:""};const n=e.indexOf("/");return n===-1?{provider:"",modelId:""}:{provider:e.slice(0,n),modelId:e.slice(n+1)}}function hg(e){switch(e){case"file-text":return xa;case"check-circle":return Zn;case"shield":return oj;case"zap":return as;case"eye":return zr;case"globe":return xc;case"layout-grid":return va;case"puzzle":return Vk;default:return Zn}}function pg(e){switch(e.toLowerCase()){case"quality":return"wfm-badge-category wfm-badge-category-quality";case"security":return"wfm-badge-category wfm-badge-category-security";default:return"wfm-badge-category"}}function VL({isOpen:e,onClose:n,addToast:s,projectId:a}){const[r,o]=i.useState([]),[l,c]=i.useState([]),[d,u]=i.useState({}),[h,m]=i.useState(!0),[f,p]=i.useState(!0),[g,w]=i.useState("my-steps"),[v,b]=i.useState(null),[y,j]=i.useState(!1),[S,C]=i.useState(!1),[x,k]=i.useState(fr),[R,O]=i.useState(!1),[E,_]=i.useState(!1),[G,H]=i.useState(null),[A,P]=i.useState(null),[q,Y]=i.useState({}),[ge,L]=i.useState([]),M=i.useRef(null);Oi(M,e,"fusion:workflow-steps-modal-size");const $=i.useCallback(async()=>{try{m(!0);const F=await Jo(a);o(F)}catch(F){s(Ie(F)||"Failed to load workflow steps","error")}finally{m(!1)}},[s,a]),D=i.useCallback(async()=>{try{const F=await Lo(a);Y(F||{})}catch{}},[a]),N=i.useCallback(async()=>{try{const F=await Bs();L(F.models||[])}catch{}},[]),W=i.useCallback(async()=>{try{p(!0);const[F,X]=await Promise.all([g1(),b1()]);c(F.templates);const re=Object.fromEntries(X.templates.map(({pluginId:U,template:be})=>[be.id,U]));u(re)}catch(F){s(Ie(F)||"Failed to load templates","error")}finally{p(!1)}},[s]);i.useEffect(()=>{e&&($(),W(),D(),N())},[e,$,W,D,N]);const de=i.useCallback(()=>{C(!0),j(!1),b(null),k(fr)},[]),me=i.useCallback(()=>{C(!1),j(!0),b(null),k(fr)},[]),Ne=i.useCallback(F=>{b(F.id),j(!1),k({name:F.name,description:F.description,mode:F.mode||"prompt",phase:F.phase||"pre-merge",prompt:F.prompt,scriptName:F.scriptName||"",enabled:F.enabled,defaultOn:F.defaultOn||!1,modelProvider:F.modelProvider||"",modelId:F.modelId||""})},[]),ve=i.useCallback(()=>{b(null),j(!1),C(!1),k(fr)},[]),Me=i.useCallback(async()=>{if(!x.name.trim()||!x.description.trim()){s("Name and description are required","error");return}O(!0);try{const F=x.mode==="prompt"&&x.modelProvider&&x.modelId?{modelProvider:x.modelProvider,modelId:x.modelId}:x.mode==="prompt"?{modelProvider:void 0,modelId:void 0}:{};if(y){const X={name:x.name.trim(),description:x.description.trim(),mode:x.mode,phase:x.phase,prompt:x.mode==="prompt"&&x.prompt.trim()||void 0,scriptName:x.mode==="script"?x.scriptName.trim():void 0,enabled:x.enabled,defaultOn:x.defaultOn||void 0,...F};await rh(X,a),s("Workflow step created","success")}else v&&(await h1(v,{name:x.name.trim(),description:x.description.trim(),mode:x.mode,phase:x.phase,prompt:x.mode==="prompt"?x.prompt:"",scriptName:x.mode==="script"?x.scriptName.trim():void 0,enabled:x.enabled,defaultOn:x.defaultOn,...F},a),s("Workflow step updated","success"));j(!1),b(null),k(fr),await $()}catch(F){s(Ie(F)||"Failed to save workflow step","error")}finally{O(!1)}},[x,y,v,s,$]),ie=i.useCallback(async F=>{try{await p1(F,a),s("Workflow step deleted","success"),H(null),v===F&&(b(null),k(fr)),await $()}catch(X){s(Ie(X)||"Failed to delete workflow step","error")}},[v,s,$]),ye=i.useCallback(async()=>{if(!(!v&&!y)&&x.mode==="prompt"){if(y){if(!x.name.trim()||!x.description.trim()){s("Name and description are required before refining","error");return}O(!0);try{const F=x.modelProvider&&x.modelId?{modelProvider:x.modelProvider,modelId:x.modelId}:{},X={name:x.name.trim(),description:x.description.trim(),mode:"prompt",prompt:x.prompt.trim()||void 0,enabled:x.enabled,defaultOn:x.defaultOn||void 0,...F},re=await rh(X,a);j(!1),b(re.id),_(!0);const U=await oh(re.id,a);k(be=>({...be,prompt:U.prompt})),s("Prompt refined with AI","success"),await $()}catch(F){s(Ie(F)||"Failed to refine prompt","error")}finally{O(!1),_(!1)}return}if(v){_(!0);try{const F=await oh(v,a);k(X=>({...X,prompt:F.prompt})),s("Prompt refined with AI","success"),await $()}catch(F){s(Ie(F)||"Failed to refine prompt","error")}finally{_(!1)}}}},[v,y,x,s,$]),Z=i.useCallback(async F=>{P(F.id);try{await x1(F.id,a),s(`Added ${F.name} workflow step`,"success"),await $(),w("my-steps"),C(!1)}catch(X){const re=Ie(X);re?.includes("already exists")?s(`A workflow step named '${F.name}' already exists`,"error"):s(re||"Failed to add workflow step from template","error")}finally{P(null)}},[s,$]),fe=Xi(n);if(!e)return null;const Q=y||v!==null;return t.jsx("div",{className:"modal-overlay open",...fe,"data-testid":"workflow-step-manager",children:t.jsxs("div",{ref:M,className:"modal workflow-step-manager-modal",role:"dialog","aria-modal":"true","aria-label":"Workflow Steps",children:[t.jsxs("div",{className:"modal-header",children:[t.jsx("h2",{children:"Workflow Steps"}),t.jsx("button",{className:"modal-close",onClick:n,"aria-label":"Close",children:"×"})]}),t.jsx("div",{className:"wfm-body",children:h?t.jsx("div",{className:"wfm-loading",children:"Loading..."}):t.jsxs(t.Fragment,{children:[!Q&&t.jsxs("div",{className:"wfm-tab-row",children:[t.jsxs("button",{className:`btn ${g==="my-steps"?"btn-primary":"btn-secondary"} wfm-tab-btn`,onClick:()=>w("my-steps"),"data-testid":"tab-my-steps",children:[t.jsx(Yy,{size:14}),"My Workflow Steps (",r.length,")"]}),t.jsxs("button",{className:`btn ${g==="templates"?"btn-primary":"btn-secondary"} wfm-tab-btn`,onClick:()=>w("templates"),"data-testid":"tab-templates",children:[t.jsx(va,{size:14}),"Templates (",l.length,")"]})]}),g==="my-steps"&&!Q&&!S&&t.jsxs(t.Fragment,{children:[r.length===0&&t.jsx("div",{className:"wfm-empty","data-testid":"empty-state",children:"No workflow steps defined. Create one to get started, or add one from the Templates tab."}),r.length>0&&t.jsx("div",{className:"wfm-step-list",children:r.map(F=>t.jsx("div",{className:"wfm-step-card","data-testid":`workflow-step-${F.id}`,children:t.jsxs("div",{className:"wfm-step-card-top",children:[t.jsxs("div",{className:"wfm-step-card-info",children:[t.jsxs("div",{className:"wfm-step-card-title-row",children:[t.jsx("span",{className:"wfm-step-card-name",children:F.name}),t.jsx("span",{className:`wfm-badge ${F.enabled?"wfm-badge-enabled":"wfm-badge-disabled"}`,children:F.enabled?"Enabled":"Disabled"}),t.jsx("span",{className:`wfm-badge ${(F.mode||"prompt")==="script"?"wfm-badge-script":"wfm-badge-prompt"}`,children:(F.mode||"prompt")==="script"?"Script":"AI Prompt"}),t.jsx("span",{className:`wfm-badge ${(F.phase||"pre-merge")==="post-merge"?"wfm-badge-post-merge":"wfm-badge-pre-merge"}`,children:(F.phase||"pre-merge")==="post-merge"?"Post-merge":"Pre-merge"}),F.defaultOn&&t.jsx("span",{className:"wfm-badge wfm-badge-default-on",children:"Default on"})]}),t.jsx("div",{className:"wfm-step-card-desc",children:F.description})]}),t.jsxs("div",{className:"wfm-step-card-actions",children:[t.jsx("button",{className:"btn-icon",onClick:()=>Ne(F),title:"Edit","aria-label":`Edit ${F.name}`,children:t.jsx(Os,{size:14})}),G===F.id?t.jsxs("div",{className:"wfm-delete-confirm",children:[t.jsx("button",{className:"btn-icon wfm-delete-confirm-btn",onClick:()=>ie(F.id),title:"Confirm delete","aria-label":`Confirm delete ${F.name}`,children:t.jsx(gs,{size:14})}),t.jsx("button",{className:"btn-icon",onClick:()=>H(null),title:"Cancel delete","aria-label":"Cancel delete",children:t.jsx(bn,{size:14})})]}):t.jsx("button",{className:"btn-icon",onClick:()=>H(F.id),title:"Delete","aria-label":`Delete ${F.name}`,children:t.jsx(In,{size:14})})]})]})},F.id))})]}),g==="templates"&&!Q&&!S&&t.jsx(t.Fragment,{children:f?t.jsxs("div",{className:"wfm-loading",children:[t.jsx(St,{size:24,className:"spin wfm-spinner"}),"Loading templates..."]}):l.length===0?t.jsx("div",{className:"wfm-empty","data-testid":"no-templates-state",children:"No templates available."}):t.jsx("div",{className:"wfm-template-list",children:l.map(F=>{const X=hg(F.icon),re=pg(F.category),U=A===F.id;return t.jsx("div",{className:"wfm-template-card","data-testid":`template-${F.id}`,children:t.jsxs("div",{className:"wfm-template-inner",children:[t.jsx("div",{className:"wfm-template-icon",children:t.jsx(X,{size:20})}),t.jsxs("div",{className:"wfm-template-content",children:[t.jsxs("div",{className:"wfm-template-title-row",children:[t.jsx("span",{className:"wfm-template-name",children:F.name}),t.jsx("span",{className:re,children:F.category}),d[F.id]&&t.jsx("span",{className:"wfm-badge-category wfm-badge-category-plugin",children:d[F.id]})]}),t.jsx("div",{className:"wfm-template-desc",children:F.description}),t.jsx("button",{className:"btn btn-primary wfm-template-add-btn",onClick:()=>Z(F),disabled:U,"data-testid":`add-template-${F.id}`,children:U?t.jsxs(t.Fragment,{children:[t.jsx(St,{size:12,className:"spin"}),"Adding..."]}):t.jsxs(t.Fragment,{children:[t.jsx(Tn,{size:12}),"Add"]})})]})]})},F.id)})})}),S&&!Q&&t.jsxs("div",{className:"wfm-create-chooser","data-testid":"workflow-step-create-chooser",children:[t.jsx("h3",{className:"wfm-form-title",children:"How would you like to create this workflow step?"}),t.jsx("p",{className:"wfm-create-chooser-hint",children:"Start from a built-in template or create a fully custom workflow step."}),t.jsxs("button",{className:"btn wfm-create-custom-btn",onClick:me,"data-testid":"create-custom-step",children:[t.jsx(Tn,{size:14}),"Custom workflow step"]}),f?t.jsxs("div",{className:"wfm-loading","data-testid":"create-chooser-template-loading",children:[t.jsx(St,{size:24,className:"spin wfm-spinner"}),"Loading built-in templates..."]}):l.length===0?t.jsx("div",{className:"wfm-empty","data-testid":"create-chooser-no-templates",children:"No built-in templates are available right now. You can still create a custom step."}):t.jsx("div",{className:"wfm-template-list","data-testid":"create-chooser-templates",children:l.map(F=>{const X=hg(F.icon),re=pg(F.category),U=A===F.id;return t.jsx("div",{className:"wfm-template-card","data-testid":`chooser-template-${F.id}`,children:t.jsxs("div",{className:"wfm-template-inner",children:[t.jsx("div",{className:"wfm-template-icon",children:t.jsx(X,{size:20})}),t.jsxs("div",{className:"wfm-template-content",children:[t.jsxs("div",{className:"wfm-template-title-row",children:[t.jsx("span",{className:"wfm-template-name",children:F.name}),t.jsx("span",{className:re,children:F.category}),d[F.id]&&t.jsx("span",{className:"wfm-badge-category wfm-badge-category-plugin",children:d[F.id]})]}),t.jsx("div",{className:"wfm-template-desc",children:F.description}),t.jsx("button",{className:"btn btn-primary wfm-template-add-btn",onClick:()=>Z(F),disabled:U,"data-testid":`chooser-add-template-${F.id}`,children:U?t.jsxs(t.Fragment,{children:[t.jsx(St,{size:12,className:"spin"}),"Adding..."]}):t.jsxs(t.Fragment,{children:[t.jsx(Tn,{size:12}),"Add template"]})})]})]})},F.id)})})]}),Q&&t.jsxs("div",{className:"wfm-form","data-testid":"workflow-step-form",children:[t.jsx("h3",{className:"wfm-form-title",children:y?"New Workflow Step":"Edit Workflow Step"}),t.jsxs("div",{className:"wfm-form-fields",children:[t.jsxs("div",{className:"wfm-field",children:[t.jsx("label",{children:"Name"}),t.jsx("input",{type:"text",value:x.name,onChange:F=>k(X=>({...X,name:F.target.value})),placeholder:"e.g. Documentation Review","data-testid":"workflow-step-name"})]}),t.jsxs("div",{className:"wfm-field",children:[t.jsx("label",{children:"Description"}),t.jsx("textarea",{value:x.description,onChange:F=>k(X=>({...X,description:F.target.value})),placeholder:"Brief description of what this step does",rows:2,"data-testid":"workflow-step-description"})]}),t.jsxs("div",{className:"wfm-field",children:[t.jsx("label",{children:"Execution Mode"}),t.jsxs("div",{className:"wfm-mode-selector","data-testid":"workflow-step-mode-selector",children:[t.jsxs("button",{className:`btn ${x.mode==="prompt"?"btn-primary":"btn-secondary"} wfm-mode-btn`,onClick:()=>k(F=>({...F,mode:"prompt",scriptName:""})),"data-testid":"mode-prompt",children:[t.jsx(Ki,{size:14}),"AI Prompt"]}),t.jsxs("button",{className:`btn ${x.mode==="script"?"btn-primary":"btn-secondary"} wfm-mode-btn`,onClick:()=>k(F=>({...F,mode:"script",prompt:"",modelProvider:"",modelId:""})),"data-testid":"mode-script",children:[t.jsx(Ji,{size:14}),"Run Script"]})]})]}),t.jsxs("div",{className:"wfm-field",children:[t.jsx("label",{children:"Execution Phase"}),t.jsxs("div",{className:"wfm-mode-selector","data-testid":"workflow-step-phase-selector",children:[t.jsx("button",{className:`btn ${x.phase==="pre-merge"?"btn-primary":"btn-secondary"} wfm-mode-btn`,onClick:()=>k(F=>({...F,phase:"pre-merge"})),"data-testid":"phase-pre-merge",children:"Pre-merge"}),t.jsx("button",{className:`btn ${x.phase==="post-merge"?"btn-primary":"btn-secondary"} wfm-mode-btn`,onClick:()=>k(F=>({...F,phase:"post-merge"})),"data-testid":"phase-post-merge",children:"Post-merge"})]}),t.jsx("div",{className:"wfm-field-hint",children:x.phase==="pre-merge"?"Runs before merge — can block merge on failure":"Runs after merge success — failures are logged but do not block"})]}),x.mode==="prompt"&&t.jsxs("div",{className:"wfm-field",children:[t.jsxs("div",{className:"wfm-prompt-header",children:[t.jsx("label",{children:"Agent Prompt"}),t.jsxs("button",{className:"btn-icon wfm-refine-btn",onClick:ye,disabled:!x.description.trim()||E,title:"Refine with AI","aria-label":"Refine prompt with AI","data-testid":"refine-btn",children:[E?t.jsx(St,{size:12,className:"spin"}):t.jsx(cs,{size:12}),t.jsx("span",{children:"Refine with AI"})]})]}),t.jsx("textarea",{value:x.prompt,onChange:F=>k(X=>({...X,prompt:F.target.value})),placeholder:"Leave empty to use AI refinement",rows:6,className:"wfm-prompt-textarea","data-testid":"workflow-step-prompt"})]}),x.mode==="prompt"&&t.jsxs("div",{className:"wfm-field","data-testid":"workflow-step-model-field",children:[t.jsxs("div",{className:"wfm-model-header",children:[t.jsx("label",{children:"Model Override"}),x.modelProvider&&x.modelId&&t.jsxs("button",{type:"button",className:"btn-icon wfm-model-clear-btn",onClick:()=>k(F=>({...F,modelProvider:"",modelId:""})),title:"Clear model override (use global default)","data-testid":"clear-model-override",children:[t.jsx(bn,{size:12}),t.jsx("span",{children:"Use default"})]})]}),t.jsx("span",{className:"wfm-model-hint",children:x.modelProvider&&x.modelId?`Using ${x.modelProvider}/${x.modelId}`:"Using global default model"}),t.jsx("div",{"data-testid":"workflow-step-model-select",children:t.jsx(Ns,{models:ge,value:HL(x.modelProvider,x.modelId),onChange:F=>{const X=qL(F);k(re=>({...re,modelProvider:X.provider,modelId:X.modelId}))},placeholder:"Select a model override…",label:"Model override for this workflow step"})})]}),x.mode==="script"&&t.jsxs("div",{className:"wfm-field",children:[t.jsx("label",{children:"Script"}),Object.keys(q).length===0?t.jsx("div",{className:"wfm-no-scripts","data-testid":"no-scripts-message",children:"No scripts configured. Add scripts in Settings → Scripts first."}):t.jsxs("select",{value:x.scriptName,onChange:F=>k(X=>({...X,scriptName:F.target.value})),"data-testid":"workflow-step-script-select",children:[t.jsx("option",{value:"",children:"Select a script…"}),Object.entries(q).map(([F,X])=>t.jsxs("option",{value:F,children:[F," (",X,")"]},F))]})]}),t.jsxs("label",{className:"wfm-checkbox-label",children:[t.jsx("input",{type:"checkbox",checked:x.enabled,onChange:F=>k(X=>({...X,enabled:F.target.checked})),"data-testid":"workflow-step-enabled"}),"Enabled (available for selection on new tasks)"]}),t.jsxs("label",{className:"wfm-checkbox-label",children:[t.jsx("input",{type:"checkbox",checked:x.defaultOn,onChange:F=>k(X=>({...X,defaultOn:F.target.checked})),"data-testid":"workflow-step-default-on"}),"Default on for new tasks"]}),t.jsxs("div",{className:"wfm-form-actions",children:[t.jsx("button",{className:"btn btn-secondary",onClick:ve,disabled:R,children:"Cancel"}),t.jsx("button",{className:"btn btn-primary",onClick:Me,disabled:R||!x.name.trim()||!x.description.trim()||x.mode==="script"&&!x.scriptName.trim(),"data-testid":"save-workflow-step",children:R?"Saving...":y?"Create":"Save"})]})]})]})]})}),!Q&&!S&&t.jsx("div",{className:"wfm-footer",children:t.jsxs("button",{className:"btn btn-primary wfm-footer-add-btn",onClick:de,"data-testid":"add-workflow-step",children:[t.jsx(Tn,{size:14}),"Add Workflow Step"]})})]})})}const WL=36e5,GL=3e5,Qd=[{value:3e5,label:"5m"},{value:9e5,label:"15m"},{value:18e5,label:"30m"},{value:36e5,label:"1h"},{value:108e5,label:"3h"},{value:216e5,label:"6h"},{value:432e5,label:"12h"},{value:864e5,label:"24h"},{value:1728e5,label:"48h"},{value:2592e5,label:"72h"},{value:6048e5,label:"1w"}];function KL(e){return e<1e3?`${e}ms`:e<6e4?`${Math.round(e/1e3)}s`:e<36e5?`${Math.round(e/6e4)}m`:e<864e5?`${Math.round(e/36e5)}h`:e<6048e5?`${Math.round(e/864e5)}d`:`${Math.round(e/6048e5)}w`}function JL(e){return typeof e!="number"||!Number.isFinite(e)?WL:Math.max(GL,Math.round(e))}function eB(e){if(Qd.some(s=>s.value===e))return[...Qd];const n={value:e,label:`${KL(e)} (custom)`};return[...Qd,n].sort((s,a)=>s.value-a.value)}const YL=4,QL=5*6e4;function XL(e){const n=JL(e?.heartbeatIntervalMs);return Math.max(n*YL,QL)}function fg(e){const n=Math.floor(e/6e4);if(n<1)return"<1m";const s=Math.floor(n/60),a=n%60;return s>0&&a>0?`${s}h ${a}m`:s>0?`${s}h`:`${a}m`}function ZL(e){const n=e.metadata;return n&&(n.agentKind==="task-worker"||n.taskWorker===!0||n.managedBy==="task-executor")?!0:!!(e.role==="executor"&&e.name?.startsWith("executor-")&&e.taskId)}function eO(e){const s=e.metadata?.heartbeatTimerRepair;if(!s||typeof s!="object")return{};const a=s;return{repairedAt:typeof a.repairedAt=="string"?a.repairedAt:void 0,staleAtRepair:typeof a.staleAtRepair=="boolean"?a.staleAtRepair:void 0,staleRepairReason:typeof a.staleRepairReason=="string"?a.staleRepairReason:void 0}}function tO(e){const{state:n,lastHeartbeatAt:s,lastError:a,pauseReason:r,runtimeConfig:o}=e,l=ZL(e),c=l||o?.enabled!==!1;if(n==="error")return{label:a??"Error",icon:t.jsx(Vs,{size:14}),color:"var(--state-error-text)",stateDerived:!a};if(n==="paused")return{label:r?`Paused: ${r}`:"Paused",icon:t.jsx(di,{size:14}),color:"var(--state-paused-text)",stateDerived:!r};if(n==="running"||l&&n==="active")return{label:"Running",icon:t.jsx(Vs,{size:14}),color:"var(--state-active-text)",stateDerived:!0};if(!c)return{label:"Heartbeat Disabled",icon:t.jsx(di,{size:14}),color:"var(--state-paused-text)",stateDerived:!1};if(!s)return{label:n==="active"?"Starting...":"Idle",icon:t.jsx(Xn,{size:14}),color:"var(--text-muted)",stateDerived:!1};const d=eO(e);if(d.staleAtRepair&&d.repairedAt){const f=Date.parse(d.repairedAt),p=Date.parse(s);if(Number.isFinite(f)&&Number.isFinite(p)&&p<f)return{label:"Unresponsive",icon:t.jsx(Vs,{size:14}),color:"var(--state-error-text)",stateDerived:!1,reason:d.staleRepairReason??"Heartbeat scheduler repaired a missing timer; waiting for recovery heartbeat"}}const u=new Date(s).getTime(),h=Date.now()-u,m=XL(o);if(h>m){const f=`No heartbeat for ${fg(h)} (threshold: ${fg(m)})`;return{label:"Unresponsive",icon:t.jsx(Vs,{size:14}),color:"var(--state-error-text)",stateDerived:!1,reason:f}}return{label:"Healthy",icon:t.jsx(ik,{size:14}),color:"var(--state-active-text)",stateDerived:!1}}function uc({agent:e,size:n=36,className:s}){const[a,r]=i.useState(!1);i.useEffect(()=>{r(!1)},[e.imageUrl]);const o=i.useMemo(()=>{if(!e.imageUrl)return;const l=encodeURIComponent(e.updatedAt??""),c=e.imageUrl.includes("?")?"&":"?";return`${e.imageUrl}${c}t=${l}`},[e.imageUrl,e.updatedAt]);return t.jsx("span",{className:`agent-avatar${s?` ${s}`:""}`,style:{width:`${n}px`,height:`${n}px`},"aria-label":`${e.name} avatar`,children:o&&!a?t.jsx("img",{src:o,alt:`${e.name} avatar`,onError:()=>r(!0)}):e.icon?.trim()?t.jsx("span",{className:"agent-avatar-emoji",style:{fontSize:`calc(${n}px * 0.58)`},"aria-hidden":"true",children:e.icon}):t.jsx(Xn,{size:Math.max(14,Math.round(n*.55)),"aria-hidden":"true"})})}const nO="https://github.com/Runfusion/Fusion/issues/new";function sO(e,n){const s=`[Agent Error] ${n.surface}${n.agentName?` - ${n.agentName}`:""}`,a=["## Agent Error Report","",`- Surface: ${n.surface}`,`- Agent ID: ${n.agentId??"unknown"}`,`- Agent Name: ${n.agentName??"unknown"}`,`- Agent State: ${n.agentState??"unknown"}`,`- Run ID: ${n.runId??"n/a"}`,`- Task ID: ${n.taskId??"n/a"}`,`- Timestamp: ${n.timestamp??new Date().toISOString()}`,"","## Error","```text",e,"```"],r=new URLSearchParams({title:s,body:a.join(`
695
- `)});return`${nO}?${r.toString()}`}function iO({open:e,onClose:n,errorText:s,issueContext:a}){const[r,o]=i.useState(!1),l=i.useMemo(()=>sO(s,a),[s,a]);return e?t.jsx("div",{className:"modal-overlay open",onClick:c=>c.target===c.currentTarget&&n(),role:"dialog","aria-modal":"true","aria-label":"Agent error details",children:t.jsxs("div",{className:"modal agent-error-modal",children:[t.jsxs("div",{className:"modal-header",children:[t.jsxs("h2",{className:"modal-title",children:[t.jsx(zs,{size:16}),"Agent Error Details"]}),t.jsx("button",{className:"modal-close",onClick:n,"aria-label":"Close",children:"×"})]}),t.jsx("div",{className:"agent-error-modal__content",children:t.jsx("pre",{className:"agent-error-modal__error",children:s})}),t.jsxs("div",{className:"modal-actions",children:[t.jsxs("button",{type:"button",className:"btn btn-sm",onClick:()=>{navigator.clipboard.writeText(s).then(()=>{o(!0),setTimeout(()=>o(!1),1500)})},"aria-label":r?"Copied error to clipboard":"Copy error to clipboard",children:[r?t.jsx(gs,{size:14}):t.jsx(ba,{size:14}),r?"Copied":"Copy"]}),t.jsxs("a",{className:"btn btn-sm btn-warning",href:l,target:"_blank",rel:"noreferrer",onClick:c=>{c.preventDefault(),window.open(l,"_blank","noopener,noreferrer")},children:[t.jsx(cb,{size:14}),"Report on GitHub"]})]})]})}):null}function aO({errorText:e,issueContext:n,summaryPrefix:s="Error"}){const[a,r]=i.useState(!1);return t.jsxs(t.Fragment,{children:[t.jsxs("button",{type:"button",className:"agent-error-indicator",onClick:()=>r(!0),"aria-label":"Open error details",children:[t.jsx(zs,{size:14}),t.jsx("span",{className:"agent-error-indicator__label",children:s})]}),t.jsx(iO,{open:a,onClose:()=>r(!1),errorText:e,issueContext:n})]})}const Ol=[{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:"✦"}];function rO({isOpen:e,onClose:n,addToast:s,projectId:a}){const[r,o]=i.useState([]),[l,c]=i.useState(!1),[d,u]=i.useState(!1),[h,m]=i.useState(""),[f,p]=i.useState("custom"),[g,w]=i.useState("all"),[v,b]=i.useState(()=>{if(typeof window>"u")return"list";const D=Ln("fn-agent-view",a);return D==="board"||D==="list"?D:"list"});i.useEffect(()=>{const D=Ln("fn-agent-view",a);if(D==="board"||D==="list"){b(D);return}b("list")},[a]),i.useEffect(()=>{rs("fn-agent-view",v,a)},[a,v]);const[y,j]=i.useState(null),S=i.useRef(null),[C,x]=i.useState(new Set),[k,R]=i.useState(new Map),{confirm:O}=ti(),E=i.useMemo(()=>k.size===0?r:r.map(D=>{const N=k.get(D.id);return N?{...D,state:N}:D}),[r,k]),_=i.useMemo(()=>g!=="all"?E:[...E].sort((D,N)=>{const W=D.state==="paused"?1:0,de=N.state==="paused"?1:0;return W!==de?W-de:(N.updatedAt??"").localeCompare(D.updatedAt??"")}),[E,g]),G=i.useCallback(async()=>{c(!0);try{const N=await Hr(g!=="all"?{state:g}:void 0,a);o(N)}catch(D){s(`Failed to load agents: ${Ie(D)}`,"error")}finally{c(!1)}},[g,s,a]);i.useEffect(()=>{e&&G()},[e,G]),i.useEffect(()=>{if(!e)return;const D=setInterval(()=>{G()},3e4);return()=>{clearInterval(D)}},[e,G]);const H=async()=>{if(h.trim())try{await E1({name:h.trim(),role:f},a),s(`Agent "${h}" created`,"success"),m(""),u(!1),G()}catch(D){s(`Failed to create agent: ${Ie(D)}`,"error")}},A=async(D,N)=>{if(!C.has(D)){x(W=>new Set(W).add(D)),R(W=>{const de=new Map(W);return de.set(D,N),de});try{await M1(D,N,a),s(`Agent state updated to ${N}`,"success"),await G(),R(W=>{const de=new Map(W);return de.delete(D),de})}catch(W){R(de=>{const me=new Map(de);return me.delete(D),me}),s(`Failed to update state: ${Ie(W)}`,"error")}finally{x(W=>{const de=new Set(W);return de.delete(D),de})}}},P=async(D,N)=>{if(await O({title:"Delete Agent",message:`Delete agent "${N}"? This cannot be undone.`,danger:!0}))try{await A1(D,a),s(`Agent "${N}" deleted`,"success"),G()}catch(de){s(`Failed to delete agent: ${Ie(de)}`,"error")}},q=async(D,N)=>{const W=r.find(de=>de.id===D);if(W){if(W.role===N){j(null);return}try{await _1(D,{role:N},a),s(`Agent role updated to ${Ol.find(de=>de.value===N)?.label??N}`,"success"),j(null),G()}catch(de){s(`Failed to update role: ${Ie(de)}`,"error")}}},Y=(D,N)=>{D.key==="Escape"&&j(null)},ge=D=>Ol.find(N=>N.value===D)?.label??D,L=D=>tO(D),M=D=>D.color==="var(--state-active-text)"?"active":D.color==="var(--state-paused-text)"?"paused":D.color==="var(--state-error-text)"?"error":"muted",$=(D,N)=>D.state==="error"?{title:void 0,label:"Error"}:{title:N.reason??N.label,label:N.stateDerived?null:N.label};return e?t.jsx("div",{className:"modal-overlay open",onClick:D=>D.target===D.currentTarget&&n(),role:"dialog","aria-modal":"true",children:t.jsxs("div",{className:"modal modal--wide agent-list-modal",children:[t.jsxs("div",{className:"modal-header",children:[t.jsxs("h2",{className:"modal-title",children:[t.jsx(Xn,{size:20}),"Agents"]}),t.jsxs("div",{className:"modal-actions",children:[t.jsxs("div",{className:"view-toggle",children:[t.jsx("button",{className:`view-toggle-btn${v==="board"?" active":""}`,onClick:()=>b("board"),title:"Board view","aria-label":"Board view","aria-pressed":v==="board",children:t.jsx(va,{size:16})}),t.jsx("button",{className:`view-toggle-btn${v==="list"?" active":""}`,onClick:()=>b("list"),title:"List view","aria-label":"List view","aria-pressed":v==="list",children:t.jsx(cu,{size:16})})]}),t.jsx("button",{className:"btn-icon",onClick:()=>void G(),title:"Refresh",disabled:l,children:t.jsx(us,{size:16,className:l?"spin":""})}),t.jsx("button",{className:"modal-close",onClick:n,"aria-label":"Close",children:"×"})]})]}),t.jsxs("div",{className:"modal-content agent-modal-content",children:[t.jsxs("div",{className:"agent-controls",children:[t.jsxs("div",{className:"agent-state-filter",children:[t.jsx(Gl,{size:14}),t.jsxs("select",{className:"agent-state-filter-select",value:g,onChange:D=>w(D.target.value),"aria-label":"Filter agents by state",children:[t.jsx("option",{value:"all",children:"All States"}),t.jsx("option",{value:"idle",children:"Idle"}),t.jsx("option",{value:"active",children:"Active"}),t.jsx("option",{value:"running",children:"Running"}),t.jsx("option",{value:"paused",children:"Paused"}),t.jsx("option",{value:"error",children:"Error"})]})]}),t.jsxs("button",{className:"btn btn-task-create btn-sm",onClick:()=>u(!d),children:[t.jsx(Tn,{size:16}),d?"Cancel":"New Agent"]})]}),d&&t.jsxs("div",{className:"agent-create-form",children:[t.jsx("input",{type:"text",placeholder:"Agent name...",value:h,onChange:D=>m(D.target.value),onKeyDown:D=>D.key==="Enter"&&H(),className:"input",autoFocus:!0}),t.jsx("select",{className:"select",value:f,onChange:D=>p(D.target.value),children:Ol.map(D=>t.jsxs("option",{value:D.value,children:[D.icon," ",D.label]},D.value))}),t.jsx("button",{className:"btn btn-task-create btn-sm",onClick:()=>void H(),children:"Create"})]}),t.jsx("div",{className:v==="board"?"agent-board":"agent-list",children:_.length===0?t.jsxs("div",{className:"agent-empty",children:[t.jsx(Xn,{size:48,opacity:.3}),t.jsx("p",{children:"No agents found"}),t.jsx("p",{className:"text-secondary",children:"Create an agent to get started"})]}):v==="board"?_.map(D=>{const N=L(D),W=$(D,N),de=M(N);return t.jsxs("div",{className:"agent-board-card","data-state":D.state,children:[t.jsxs("div",{className:"agent-board-header",children:[t.jsx("span",{className:"agent-board-icon",children:t.jsx(uc,{agent:D,size:20})}),t.jsx("span",{className:"agent-board-badge","data-state":D.state,children:D.state}),t.jsx("span",{className:"agent-board-health","data-health":de,title:W.title,children:N.icon})]}),t.jsx("div",{className:"agent-board-name",title:D.name,children:D.name}),t.jsx("div",{className:"agent-board-id",children:D.id}),t.jsxs("div",{className:"agent-board-actions",children:[D.state==="idle"&&t.jsxs(t.Fragment,{children:[t.jsx("button",{className:"btn btn--sm",onClick:()=>void A(D.id,"active"),disabled:C.has(D.id),title:"Activate",children:t.jsx(is,{size:14})}),t.jsx("button",{className:"btn btn--sm btn--danger",onClick:()=>void P(D.id,D.name),title:"Delete",children:t.jsx(In,{size:14})})]}),D.state==="active"&&t.jsxs(t.Fragment,{children:[t.jsx("button",{className:"btn btn--sm",onClick:()=>void A(D.id,"paused"),disabled:C.has(D.id),title:"Pause",children:t.jsx(di,{size:14})}),t.jsx("button",{className:"btn btn--sm btn--danger",onClick:()=>void A(D.id,"paused"),disabled:C.has(D.id),title:"Stop",children:t.jsx(Pi,{size:14})})]}),D.state==="paused"&&t.jsxs(t.Fragment,{children:[t.jsx("button",{className:"btn btn--sm",onClick:()=>void A(D.id,"active"),disabled:C.has(D.id),title:"Resume",children:t.jsx(is,{size:14})}),t.jsx("button",{className:"btn btn--sm btn--danger",onClick:()=>void P(D.id,D.name),title:"Delete",children:t.jsx(In,{size:14})})]}),D.state==="running"&&t.jsxs(t.Fragment,{children:[t.jsx("button",{className:"btn btn--sm",onClick:()=>void A(D.id,"paused"),disabled:C.has(D.id),title:"Pause",children:t.jsx(di,{size:14})}),t.jsx("button",{className:"btn btn--sm btn--danger",onClick:()=>void A(D.id,"paused"),disabled:C.has(D.id),title:"Stop",children:t.jsx(Pi,{size:14})})]}),D.state==="error"&&t.jsxs(t.Fragment,{children:[t.jsx("button",{className:"btn btn--sm",onClick:()=>void A(D.id,"active"),disabled:C.has(D.id),title:"Retry",children:t.jsx(is,{size:14})}),t.jsx("button",{className:"btn btn--sm btn--danger",onClick:()=>void A(D.id,"paused"),disabled:C.has(D.id),title:"Stop",children:t.jsx(Pi,{size:14})})]})]})]},D.id)}):_.map(D=>{const N=L(D),W=$(D,N),de=M(N);return t.jsxs("div",{className:"agent-card","data-state":D.state,children:[t.jsxs("div",{className:"agent-card-header",children:[t.jsxs("div",{className:"agent-info",children:[y===D.id?t.jsx("select",{ref:S,className:"select agent-role-select",value:D.role,onChange:me=>void q(D.id,me.target.value),onKeyDown:me=>Y(me,D.id),onBlur:()=>j(null),autoFocus:!0,children:Ol.map(me=>t.jsxs("option",{value:me.value,children:[me.icon," ",me.label]},me.value))}):t.jsx("span",{className:"agent-icon agent-icon--clickable",onClick:()=>j(D.id),title:"Click to change role",role:"button",tabIndex:0,onKeyDown:me=>{(me.key==="Enter"||me.key===" ")&&j(D.id)},children:t.jsx(uc,{agent:D,size:20})}),t.jsxs("div",{className:"agent-meta",children:[t.jsx("span",{className:"agent-name",children:D.name}),t.jsx("span",{className:"agent-id text-secondary",children:D.id})]})]}),t.jsxs("div",{className:"agent-badges",children:[t.jsx("span",{className:"badge agent-list-state-badge","data-state":D.state,children:D.state}),t.jsxs("span",{className:"badge agent-list-health-badge","data-health":de,title:W.title,children:[N.icon,W.label?` ${W.label}`:""]}),t.jsx("span",{className:"badge text-secondary",children:ge(D.role)})]})]}),t.jsxs("div",{className:"agent-card-body",children:[D.state==="error"&&D.lastError?t.jsx(aO,{errorText:D.lastError,issueContext:{surface:"AgentListModal list",agentId:D.id,agentName:D.name,agentState:D.state,taskId:D.taskId}}):null,D.taskId&&t.jsxs("div",{className:"agent-task",children:[t.jsx("span",{className:"text-secondary",children:"Working on:"}),t.jsx("span",{className:"badge",children:D.taskId})]}),D.lastHeartbeatAt&&t.jsxs("div",{className:"agent-heartbeat",children:[t.jsx("span",{className:"text-secondary",children:"Last heartbeat:"}),t.jsx("span",{children:new Date(D.lastHeartbeatAt).toLocaleString()})]})]}),t.jsxs("div",{className:"agent-card-actions",children:[D.state==="idle"&&t.jsxs(t.Fragment,{children:[t.jsxs("button",{className:"btn btn--sm",onClick:()=>void A(D.id,"active"),disabled:C.has(D.id),title:"Activate",children:[t.jsx(is,{size:14})," Start"]}),t.jsxs("button",{className:"btn btn--sm btn--danger",onClick:()=>void P(D.id,D.name),title:"Delete",children:[t.jsx(In,{size:14})," Delete"]})]}),D.state==="active"&&t.jsxs(t.Fragment,{children:[t.jsxs("button",{className:"btn btn--sm",onClick:()=>void A(D.id,"paused"),disabled:C.has(D.id),title:"Pause",children:[t.jsx(di,{size:14})," Pause"]}),t.jsxs("button",{className:"btn btn--sm btn--danger",onClick:()=>void A(D.id,"paused"),disabled:C.has(D.id),title:"Stop",children:[t.jsx(Pi,{size:14})," Stop"]})]}),D.state==="paused"&&t.jsxs(t.Fragment,{children:[t.jsxs("button",{className:"btn btn--sm",onClick:()=>void A(D.id,"active"),disabled:C.has(D.id),title:"Resume",children:[t.jsx(is,{size:14})," Resume"]}),t.jsxs("button",{className:"btn btn--sm btn--danger",onClick:()=>void P(D.id,D.name),title:"Delete",children:[t.jsx(In,{size:14})," Delete"]})]}),D.state==="running"&&t.jsxs(t.Fragment,{children:[t.jsxs("button",{className:"btn btn--sm",onClick:()=>void A(D.id,"paused"),disabled:C.has(D.id),title:"Pause",children:[t.jsx(di,{size:14})," Pause"]}),t.jsxs("button",{className:"btn btn--sm btn--danger",onClick:()=>void A(D.id,"paused"),disabled:C.has(D.id),title:"Stop",children:[t.jsx(Pi,{size:14})," Stop"]})]}),D.state==="error"&&t.jsxs(t.Fragment,{children:[t.jsxs("button",{className:"btn btn--sm",onClick:()=>void A(D.id,"active"),disabled:C.has(D.id),title:"Retry",children:[t.jsx(is,{size:14})," Retry"]}),t.jsxs("button",{className:"btn btn--sm btn--danger",onClick:()=>void A(D.id,"paused"),disabled:C.has(D.id),title:"Stop",children:[t.jsx(Pi,{size:14})," Stop"]})]})]})]},D.id)})})]})]})}):null}function oO({authenticated:e,onToggled:n,compact:s=!1}){const[a,r]=i.useState(null),[o,l]=i.useState(null),[c,d]=i.useState(null),u=i.useRef(!0);i.useEffect(()=>(u.current=!0,()=>{u.current=!1}),[]);const h=i.useCallback(async()=>{try{const b=await LN();return u.current&&r(b),b}catch(b){return u.current&&d({kind:"error",message:b instanceof Error?b.message:String(b)}),null}},[]);i.useEffect(()=>{h()},[h]);const m=i.useCallback(async()=>{l("testing"),d(null),await h(),u.current&&l(null)},[h]),f=i.useCallback(async b=>{l(b?"enabling":"disabling"),d(null);try{const y=await HN(b);u.current&&d({kind:y.enabled?"enabled":"disabled",restartRequired:y.restartRequired}),n?.(y.enabled),await h()}catch(y){u.current&&d({kind:"error",message:y instanceof Error?y.message:String(y)})}finally{u.current&&l(null)}},[n,h]),p=a?.binary.available??!1,g=a?.enabled??e,w=t.jsxs("span",{className:"onboarding-provider-card__description",children:["Route AI calls through your locally-installed ",t.jsx("code",{children:"claude"})," CLI. Uses your existing Claude subscription / quota instead of an API key."]}),v=t.jsxs(t.Fragment,{children:[t.jsx("button",{type:"button",className:"btn btn-sm",onClick:m,disabled:o!==null,children:o==="testing"?t.jsxs(t.Fragment,{children:[t.jsx(St,{size:12,className:"animate-spin"}),"Testing…"]}):"Test"}),g?t.jsx("button",{type:"button",className:"btn btn-sm",onClick:()=>void f(!1),disabled:o!==null,children:o==="disabling"?"Disabling…":"Disable"}):t.jsx("button",{type:"button",className:"btn btn-primary btn-sm",onClick:()=>void f(!0),disabled:o!==null||!p,title:p?void 0:"`claude` binary not detected on PATH — install Claude CLI first.",children:o==="enabling"?"Enabling…":"Enable"})]});return s?t.jsxs("div",{className:`auth-provider-card auth-provider-card--cli${e?" auth-provider-card--authenticated":""}`,"data-testid":"claude-cli-provider-card",children:[t.jsxs("div",{className:"auth-provider-header",children:[t.jsxs("div",{className:"auth-provider-info",children:[t.jsx(On,{provider:"claude-cli",size:"sm"}),t.jsx("strong",{children:"Anthropic — via Claude CLI"}),t.jsx(lO,{status:a,authenticated:e})]}),t.jsx("div",{className:"auth-provider-cli-actions",children:v})]}),t.jsxs("details",{className:"auth-provider-cli-details",children:[t.jsx("summary",{children:"Details"}),t.jsxs("div",{className:"auth-provider-cli-details-body",children:[w,t.jsx(gg,{status:a,authenticated:e}),c&&t.jsx(bg,{action:c})]})]})]}):t.jsxs("div",{className:`onboarding-provider-card${e?" onboarding-provider-card--connected":""}`,"data-testid":"claude-cli-provider-card",children:[t.jsx("div",{className:"onboarding-provider-card__icon",children:t.jsx(On,{provider:"claude-cli",size:"md"})}),t.jsxs("div",{className:"onboarding-provider-card__body",children:[t.jsx("strong",{className:"onboarding-provider-card__name",children:"Anthropic — via Claude CLI"}),w,t.jsx(gg,{status:a,authenticated:e})]}),t.jsx("div",{className:"onboarding-provider-card__actions",children:v}),c&&t.jsx(bg,{action:c})]})}function lO({status:e,authenticated:n}){const s=e?.enabled??n,a=e?.binary.available??!1;return s?t.jsx("span",{className:"auth-status-badge authenticated",children:"✓ Active"}):!a&&e?t.jsx("span",{className:"auth-status-badge not-authenticated",children:"✗ Not installed"}):t.jsx("span",{className:"auth-status-badge not-authenticated",children:"✗ Not connected"})}function gg({status:e,authenticated:n}){if(!e)return t.jsxs("small",{className:"settings-muted",children:[t.jsx(St,{size:10,className:"animate-spin"})," Probing local CLI…"]});const{binary:s,enabled:a,extension:r,ready:o}=e;return s.available?a?r&&r.status!=="ok"?t.jsxs("small",{className:"onboarding-provider-card__status onboarding-provider-card__status--warning",children:["⚠ Extension load failed: ",r.reason??r.status]}):o||n?t.jsxs("small",{className:"onboarding-provider-card__status onboarding-provider-card__status--connected",children:["✓ Connected",s.version?` — ${s.version}`:""]}):t.jsx("small",{className:"settings-muted",children:"Enabled. Validating…"}):t.jsxs("small",{className:"settings-muted",children:[t.jsx("code",{children:"claude"})," ",s.version?`(${s.version})`:""," detected",s.binaryPath?` at ${s.binaryPath}`:"",". Click Enable to route AI calls through it."]}):t.jsxs("small",{className:"onboarding-provider-card__status onboarding-provider-card__status--error",children:["✗ ",s.reason??"`claude` not found on PATH"]})}function bg({action:e}){if(e.kind==="error")return t.jsx("p",{className:"onboarding-helper-text onboarding-helper-text--error",children:e.message});const n=e.kind==="enabled"?"Enabled":"Disabled";return t.jsxs("p",{className:"onboarding-helper-text",children:[n,"."," ",e.kind==="enabled"?"Claude-CLI-routed models are now visible in the model picker.":"Claude-CLI-routed models are hidden from the model picker."]})}function cO({authenticated:e,compact:n=!1,onToggled:s}){const[a,r]=i.useState(null),[o,l]=i.useState(null),c=i.useRef(!0);i.useEffect(()=>(c.current=!0,()=>{c.current=!1}),[]);const d=i.useCallback(async()=>{try{const g=await BN();return c.current&&r(g),g}catch{return null}},[]);i.useEffect(()=>{d()},[d]);const u=i.useCallback(async g=>{l(g?"enabling":"disabling");try{const w=await VN(g);s?.(w.enabled),await d()}finally{c.current&&l(null)}},[s,d]),h=a?.enabled??e,m=a?.binary.available??!1,f=t.jsxs(t.Fragment,{children:[t.jsx("button",{type:"button",className:"btn btn-sm",onClick:()=>{l("testing"),d().finally(()=>{c.current&&l(null)})},disabled:o!==null,children:o==="testing"?t.jsxs(t.Fragment,{children:[t.jsx(St,{size:12,className:"animate-spin"})," Testing…"]}):"Test"}),h?t.jsx("button",{type:"button",className:"btn btn-sm",onClick:()=>void u(!1),disabled:o!==null,children:o==="disabling"?"Disabling…":"Disable"}):t.jsx("button",{type:"button",className:"btn btn-primary btn-sm",onClick:()=>void u(!0),disabled:o!==null||!m,children:o==="enabling"?"Enabling…":"Enable"})]}),p=a?a.binary.available?h?`Connected${a.binary.version?` — ${a.binary.version}`:""}`:"Detected. Click Enable to route calls through Cursor CLI.":a.binary.reason??"`cursor-agent` not found on PATH":"Probing local CLI…";return n?t.jsxs("div",{className:`cursor-cli-provider-card auth-provider-card auth-provider-card--cli${e?" auth-provider-card--authenticated":""}`,"data-testid":"cursor-cli-provider-card",children:[t.jsxs("div",{className:"auth-provider-header",children:[t.jsxs("div",{className:"auth-provider-info",children:[t.jsx(On,{provider:"cursor-cli",size:"sm"}),t.jsx("strong",{children:"Cursor — via Cursor CLI"}),t.jsx("span",{className:`auth-status-badge ${h?"authenticated":"not-authenticated"}`,children:h?"✓ Active":"✗ Not connected"})]}),t.jsx("div",{className:"auth-provider-cli-actions",children:f})]}),t.jsx("small",{className:"settings-muted",children:p})]}):t.jsxs("div",{className:`cursor-cli-provider-card onboarding-provider-card${e?" onboarding-provider-card--connected":""}`,"data-testid":"cursor-cli-provider-card",children:[t.jsx("div",{className:"onboarding-provider-card__icon",children:t.jsx(On,{provider:"cursor-cli",size:"md"})}),t.jsxs("div",{className:"onboarding-provider-card__body",children:[t.jsx("strong",{className:"onboarding-provider-card__name",children:"Cursor — via Cursor CLI"}),t.jsx("span",{className:"onboarding-provider-card__description",children:"Route AI calls through your local Cursor agent runtime."}),t.jsx("small",{className:"settings-muted",children:p})]}),t.jsx("div",{className:"onboarding-provider-card__actions",children:f})]})}function dO({authenticated:e,onToggled:n,compact:s=!1}){const[a,r]=i.useState(null),[o,l]=i.useState(null),c=i.useRef(!0);i.useEffect(()=>(c.current=!0,()=>{c.current=!1}),[]);const d=i.useCallback(async()=>{const w=await UN();return c.current&&r(w),w},[]);i.useEffect(()=>{d()},[d]);const u=i.useCallback(async w=>{l(w?"enabling":"disabling");try{const v=await WN(w);n?.(v.enabled),await d()}finally{c.current&&l(null)}},[n,d]),h=i.useCallback(async()=>{l("testing");try{await d()}finally{c.current&&l(null)}},[d]),m=a?.enabled??e,f=a?.server.available??!1,p=a?a.server.available?`Server reachable at ${a.server.url}`:`Server unavailable: ${a.server.reason??"not reachable"}`:"Probing llama.cpp server…",g=t.jsxs("div",{className:"auth-provider-cli-actions",children:[t.jsx("button",{type:"button",className:"btn btn-sm",onClick:()=>void h(),disabled:o!==null,children:o==="testing"?t.jsxs(t.Fragment,{children:[t.jsx(St,{size:12,className:"animate-spin"}),"Testing…"]}):"Test"}),m?t.jsx("button",{type:"button",className:"btn btn-sm",onClick:()=>void u(!1),disabled:o!==null,children:o==="disabling"?"Disabling…":"Disable"}):t.jsx("button",{type:"button",className:"btn btn-primary btn-sm",onClick:()=>void u(!0),disabled:o!==null||!f,children:o==="enabling"?"Enabling…":"Enable"})]});return s?t.jsxs("div",{className:`auth-provider-card auth-provider-card--cli llama-cpp-provider-card llama-cpp-provider-card--compact${m?" auth-provider-card--authenticated":""}`,"data-testid":"llama-cpp-provider-card",children:[t.jsxs("div",{className:"auth-provider-header",children:[t.jsxs("div",{className:"auth-provider-info",children:[t.jsx(On,{provider:"llama-cpp",size:"sm"}),t.jsx("strong",{children:"llama.cpp — via HTTP server"})]}),g]}),t.jsx("small",{className:`auth-hint llama-cpp-status${a?.ready?" llama-cpp-status--ok":""}`,children:p})]}):t.jsxs("div",{className:"onboarding-provider-card llama-cpp-provider-card llama-cpp-provider-card--full","data-testid":"llama-cpp-provider-card",children:[t.jsxs("div",{className:"auth-provider-info",children:[t.jsx(On,{provider:"llama-cpp",size:"md"}),t.jsx("strong",{children:"llama.cpp — via HTTP server"})]}),t.jsx("small",{className:`llama-cpp-status${a?.ready?" llama-cpp-status--ok":""}`,children:p}),g]})}function uO(e){const n="([A-Z0-9]{2,}(?:-[A-Z0-9]{2,})+|[A-Z0-9]{6,9})",s=new RegExp(`\\b(?:device\\s+code|your\\s+code|code)\\s*(?:is|:)?\\s*${n}\\b`,"i"),a=new RegExp(`\\b(?:enter|use)\\s+${n}\\b`,"i"),r=/\b([A-Z0-9]{2,}(?:-[A-Z0-9]{2,})+)\b/,o=e.match(s);if(o?.[1])return o[1];const l=e.match(a);if(l?.[1])return l[1];const c=e.match(r);return c?.[1]?c[1]:null}function Xd({instructions:e,"data-testid":n}){const[s,a]=i.useState(!1),r=uO(e),o=i.useRef(null),l=i.useCallback(()=>{a(!0),setTimeout(()=>a(!1),2e3)},[]),c=i.useCallback(async()=>{const d=r??e;try{await navigator.clipboard.writeText(d),l()}catch{}},[r,e,l]);return i.useEffect(()=>{const d=o.current===null&&r!==null;if(o.current=r,!d)return;(async()=>{try{await navigator.clipboard.writeText(r),l()}catch{}})()},[r,l]),t.jsx("p",{className:"auth-login-instructions","data-testid":n,children:r?t.jsx(t.Fragment,{children:e.split(r).map((d,u,h)=>t.jsxs("span",{children:[d,u<h.length-1&&t.jsxs("span",{className:"device-code-wrapper",children:[t.jsx("code",{className:"device-code",children:r}),t.jsx("button",{className:"device-code-copy-btn",onClick:c,title:s?"Copied!":"Copy code","aria-label":s?"Copied to clipboard":"Copy device code",type:"button",children:s?t.jsx(gs,{size:12}):t.jsx(ba,{size:12})})]})]},u))}):e})}function mO({value:e,onChange:n,onSubmit:s,prompt:a,placeholder:r,helpText:o,disabled:l=!1,submitLabel:c="Submit code","data-testid":d}){const u=i.useRef(null),h=i.useRef(null),[m,f]=i.useState(!1),p=i.useCallback(()=>{if(typeof window>"u"||typeof window.matchMedia!="function")return!1;const v=window.matchMedia("(max-width: 768px)").matches,b=window.matchMedia("(pointer: coarse)").matches;return v||b},[]),g=i.useCallback(()=>typeof window>"u"||typeof window.matchMedia!="function"||window.matchMedia("(prefers-reduced-motion: reduce)").matches?"auto":"smooth",[]),w=i.useCallback(()=>{if(!p())return;const v=h.current??u.current;if(!v||typeof v.scrollIntoView!="function")return;const b=g();requestAnimationFrame(()=>{v.scrollIntoView({block:"center",behavior:b,inline:"nearest"}),window.setTimeout(()=>{v.scrollIntoView({block:"center",behavior:b,inline:"nearest"})},120)})},[g,p]);return i.useEffect(()=>{if(!m||!p())return;w();const v=window.visualViewport;if(!v)return;const b=()=>{document.activeElement===h.current&&w()};return v.addEventListener("resize",b),v.addEventListener("scroll",b),()=>{v.removeEventListener("resize",b),v.removeEventListener("scroll",b)}},[m,w,p]),t.jsxs("div",{ref:u,className:"oauth-manual-code","data-testid":d,children:[t.jsx("p",{className:"oauth-manual-code__prompt",children:a}),t.jsx("textarea",{ref:h,className:"form-input oauth-manual-code__input",value:e,onChange:v=>n(v.target.value),onFocus:()=>{f(!0),w()},onBlur:()=>f(!1),placeholder:r,rows:3,spellCheck:!1,disabled:l}),t.jsx("div",{className:"oauth-manual-code__actions",children:t.jsx("button",{type:"button",className:"btn btn-sm",onClick:s,disabled:l,children:c})}),o&&t.jsx("p",{className:"oauth-manual-code__help",children:o})]})}const hO=new Set(["anthropic","claude-cli","pi-claude-cli","openai","openai-codex","google","gemini","google-antigravity","antigravity","google-vertex","vertex","google-cloud-code","cloud-code","google-gemini-cli","google-generative-ai","ollama","github","github-copilot","openrouter","minimax","minimax-cn","zai","kimi","moonshot","kimi-coding","bedrock","amazon-bedrock","xai","grok","opencode","opencode-go","qwen","qwen-ai","qwen-coder","alibaba","tongyi","lmstudio","lm-studio","huggingface","hugging-face","hf","mistral","mistral-ai","azure","azure-openai","azure-openai-responses","fireworks","fireworks-ai","fireworksai","cerebras","groq","vercel","vercel-ai-gateway","hermes","hermes-agent","hermesagent","openclaw","open-claw","paperclip","paperclipai","paperclip-ai"]),pO=/^[a-z][a-z0-9-]*$/,xg=["openai-completions","openai-responses","anthropic-messages","google-generative-ai"];function vg(){return{id:"",name:"",reasoning:!1}}function fO({initialConfig:e,onSave:n,onCancel:s,saving:a=!1,error:r}){const o=!!e,[l,c]=i.useState(e?.id??""),[d,u]=i.useState(e?.name??""),[h,m]=i.useState(e?.baseUrl??""),[f,p]=i.useState(e?.api??"openai-completions"),[g,w]=i.useState(e?.apiKey??""),[v,b]=i.useState(e?.models?.length?e.models:[vg()]),[y,j]=i.useState(null),S=v.length>1,C=i.useMemo(()=>y??r??null,[y,r]);function x(E,_){b(G=>G.map((H,A)=>A===E?{...H,..._}:H))}function k(E){b(_=>_.length<=1?_:_.filter((G,H)=>H!==E))}function R(){if(!l.trim())return"Provider ID is required.";if(!pO.test(l.trim()))return"Provider ID must be kebab-case.";if(!o&&hO.has(l.trim()))return"Provider ID conflicts with a built-in provider.";if(!h.trim())return"Base URL is required.";try{const E=new URL(h.trim());if(E.protocol!=="http:"&&E.protocol!=="https:")return"Base URL must use http or https."}catch{return"Base URL must be a valid URL."}return xg.includes(f)?v.length===0?"At least one model is required.":v.some(E=>!E.id?.trim())?"Each model must have a model ID.":null:"API type is required."}async function O(E){E.preventDefault();const _=R();j(_),!_&&await n({id:l.trim(),name:d.trim()||void 0,baseUrl:h.trim(),api:f,apiKey:g.trim()||void 0,models:v.map(G=>({id:G.id.trim(),name:G.name?.trim()||void 0,reasoning:!!G.reasoning,contextWindow:G.contextWindow,maxTokens:G.maxTokens}))})}return t.jsxs("form",{onSubmit:O,className:"custom-provider-form","aria-label":"custom-provider-form",children:[t.jsxs("div",{className:"form-group custom-provider-form__group",children:[t.jsx("label",{htmlFor:"custom-provider-id",children:"Provider ID"}),t.jsx("input",{id:"custom-provider-id",className:"input",value:l,onChange:E=>c(E.target.value),disabled:o||a})]}),t.jsxs("div",{className:"form-group custom-provider-form__group",children:[t.jsx("label",{htmlFor:"custom-provider-name",children:"Display Name"}),t.jsx("input",{id:"custom-provider-name",className:"input",value:d,onChange:E=>u(E.target.value),disabled:a})]}),t.jsxs("div",{className:"form-group custom-provider-form__group",children:[t.jsx("label",{htmlFor:"custom-provider-base-url",children:"Base URL"}),t.jsx("input",{id:"custom-provider-base-url",className:"input",value:h,onChange:E=>m(E.target.value),disabled:a})]}),t.jsxs("div",{className:"form-group custom-provider-form__group",children:[t.jsx("label",{htmlFor:"custom-provider-api",children:"API Type"}),t.jsx("select",{id:"custom-provider-api",className:"select",value:f,onChange:E=>p(E.target.value),disabled:a,children:xg.map(E=>t.jsx("option",{value:E,children:E},E))})]}),t.jsxs("div",{className:"form-group custom-provider-form__group",children:[t.jsx("label",{htmlFor:"custom-provider-api-key",children:"API Key"}),t.jsx("input",{id:"custom-provider-api-key",className:"input",placeholder:"sk-..., MY_API_KEY, or !command",value:g,onChange:E=>w(E.target.value),disabled:a})]}),t.jsxs("div",{className:"form-group custom-provider-form__group",children:[t.jsx("label",{children:"Models"}),t.jsx("div",{className:"custom-provider-form__models",children:v.map((E,_)=>t.jsxs("div",{className:"custom-provider-form__model-row",children:[t.jsx("input",{className:"input","aria-label":`Model ID ${_+1}`,placeholder:"Model ID",value:E.id,onChange:G=>x(_,{id:G.target.value}),disabled:a}),t.jsx("input",{className:"input","aria-label":`Model name ${_+1}`,placeholder:"Display name",value:E.name??"",onChange:G=>x(_,{name:G.target.value}),disabled:a}),t.jsxs("label",{className:"checkbox-label custom-provider-form__toggle",children:[t.jsx("input",{type:"checkbox",checked:!!E.reasoning,onChange:G=>x(_,{reasoning:G.target.checked}),disabled:a}),"Reasoning"]}),t.jsx("input",{className:"input","aria-label":`Context window ${_+1}`,placeholder:"Context window",type:"number",value:E.contextWindow??"",onChange:G=>x(_,{contextWindow:G.target.value?Number(G.target.value):void 0}),disabled:a}),t.jsx("input",{className:"input","aria-label":`Max tokens ${_+1}`,placeholder:"Max tokens",type:"number",value:E.maxTokens??"",onChange:G=>x(_,{maxTokens:G.target.value?Number(G.target.value):void 0}),disabled:a}),t.jsx("button",{type:"button",className:"btn btn-icon btn-sm",onClick:()=>k(_),disabled:a||!S,"aria-label":`Remove model ${_+1}`,children:"×"})]},`${_}-model`))}),t.jsx("button",{type:"button",className:"btn btn-sm",onClick:()=>b(E=>[...E,vg()]),disabled:a,children:"+ Add model"})]}),C?t.jsx("div",{className:"form-error",children:C}):null,t.jsxs("div",{className:"custom-provider-form__actions",children:[s?t.jsx("button",{type:"button",className:"btn",onClick:s,disabled:a,children:"Cancel"}):null,t.jsx("button",{type:"submit",className:"btn btn-primary",disabled:a,children:a?"Saving...":"Save Provider"})]})]})}const gO=new Set(["google-antigravity","antigravity","google-gemini-cli"]);function bO(e){return!gO.has(e)}function yg(e){return e.filter(n=>bO(n.id))}const Qv={host:"web",activeProfileId:null,profiles:[]},Xv=i.createContext({shellApi:null,state:Qv,ready:!0,openConnectionManagerSignal:0});function xO({children:e}){const n=i.useMemo(()=>typeof window<"u"?window.fusionShell??null:null,[]),[s,a]=i.useState(Qv),[r,o]=i.useState(!n),[l,c]=i.useState(0);return i.useEffect(()=>{if(!n)return;let d=!1;n.getState().then(m=>{d||(a(m),o(!0))});const u=n.subscribe(m=>{a(m)}),h=()=>{c(m=>m+1)};return window.addEventListener("shell:open-connection-manager",h),()=>{d=!0,u(),window.removeEventListener("shell:open-connection-manager",h)}},[n]),t.jsx(Xv.Provider,{value:{shellApi:n,state:s,ready:r,openConnectionManagerSignal:l},children:e})}function vO(){return i.useContext(Xv)}const yO={host:"web",activeProfileId:null,profiles:[]};function wO(e){if(!e)return yO;const n=Array.isArray(e.profiles)?e.profiles.filter(a=>!!(a&&a.id&&a.serverUrl)):[],s=e.activeProfileId&&n.some(a=>a.id===e.activeProfileId)?e.activeProfileId:null;return{...e,activeProfileId:s,profiles:n}}function Rm(e){return new Error(`${e} is only available in native shell mode`)}async function kO(e,n){if(!e)throw Rm("Saving connection profiles");return e.saveProfile(n)}async function jO(e,n){if(!e)throw Rm("Deleting connection profiles");await e.deleteProfile(n)}async function NO(e,n){if(!e)throw Rm("Switching connection profiles");return e.setActiveProfile(n)}function Zv(){const e=vO(),n=i.useMemo(()=>wO(e.state),[e.state]),s=i.useCallback(o=>kO(e.shellApi,o),[e.shellApi]),a=i.useCallback(o=>jO(e.shellApi,o),[e.shellApi]),r=i.useCallback(o=>NO(e.shellApi,o),[e.shellApi]);return{...e,state:n,saveProfile:s,removeProfile:a,setActiveProfile:r}}const Ga="fusion_model_onboarding_state",Pr=[],$r=[],mc=!1,hc=!1,Dr={},SO=void 0,ua=["ai-setup","github","project-setup","first-task"],CO={"ai-setup":"AI Setup",github:"GitHub","project-setup":"Project","first-task":"First Task",complete:"Complete"};function Zs(){if(typeof window>"u")return null;try{const e=localStorage.getItem(Ga);if(!e)return null;const n=JSON.parse(e);return n&&typeof n=="object"&&"currentStep"in n&&typeof n.currentStep=="string"?EO(n):null}catch{return null}}function EO(e){const n=e.postOnboardingDismissedAt??SO;return{...e,completedSteps:e.completedSteps??Pr,skippedSteps:e.skippedSteps??$r,dismissed:e.dismissed??mc,completed:e.completed??hc,stepData:e.stepData??Dr,...n?{postOnboardingDismissedAt:n}:{}}}function Fl(e,n){if(!(typeof window>"u")){if(!n){const s={currentStep:e,updatedAt:new Date().toISOString(),completedSteps:Pr,skippedSteps:$r,dismissed:mc,completed:hc,stepData:Dr};try{localStorage.setItem(Ga,JSON.stringify(s))}catch{}return}try{const s=Zs(),a=new Date().toISOString(),r=n.completed??hc;let o=n.dismissed??mc;r&&(o=!1);const l=n.completedSteps??s?.completedSteps??Pr,c=n.skippedSteps??s?.skippedSteps??$r,d={...s?.stepData??Dr};if(n.stepData)for(const[h,m]of Object.entries(n.stepData))m!==void 0&&(d[h]={...d[h]??{},...m});const u={currentStep:e,updatedAt:a,completedSteps:l,skippedSteps:c,dismissed:o,completed:r,stepData:d};localStorage.setItem(Ga,JSON.stringify(u))}catch{}}}function _O(e){if(!(typeof window>"u"))try{const n=Zs(),s=new Date().toISOString();if(!n){const o={currentStep:e,updatedAt:s,completedSteps:Pr,skippedSteps:[e],dismissed:mc,completed:hc,stepData:Dr};localStorage.setItem(Ga,JSON.stringify(o));return}const a=n.skippedSteps.includes(e)?n.skippedSteps:[...n.skippedSteps,e],r={...n,skippedSteps:a,completedSteps:n.completedSteps.filter(o=>o!==e),updatedAt:s};localStorage.setItem(Ga,JSON.stringify(r))}catch{}}function wg(){if(!(typeof window>"u"))try{const e=Zs(),n=new Date().toISOString(),s=e?{...e,completedAt:n,completed:!0,dismissed:!1,updatedAt:n}:{currentStep:"complete",updatedAt:n,completedAt:n,completedSteps:Pr,skippedSteps:$r,dismissed:!1,completed:!0,stepData:Dr};localStorage.setItem(Ga,JSON.stringify(s))}catch{}}function Lr(){const e=Zs();return e?e.completed===!0?!0:typeof e.completedAt=="string"&&e.completedAt.length>0:!1}function MO(){if(!(typeof window>"u"))try{const e=Zs(),n=new Date().toISOString(),s=e?{...e,updatedAt:n,postOnboardingDismissedAt:n}:{currentStep:"complete",updatedAt:n,completedSteps:Pr,skippedSteps:$r,dismissed:!1,completed:!1,stepData:Dr,postOnboardingDismissedAt:n};localStorage.setItem(Ga,JSON.stringify(s))}catch{}}function ey(){const e=Zs();return e?typeof e.postOnboardingDismissedAt=="string"&&e.postOnboardingDismissedAt.length>0:!1}function AO(){const e=Zs();return!e||Lr()?!1:e.currentStep!=="complete"}function RO(){const e=Zs();if(!e||Lr()||e.currentStep==="complete")return null;const n=e.currentStep,s=CO[n]??PO(e.currentStep);return{currentStep:e.currentStep,label:s,completedSteps:e.completedSteps}}function IO(){const e=Zs();return e?e.skippedSteps:$r}function TO(e){const n=Zs();return!n||!n.stepData?null:n.stepData[e]??null}function PO(e){return e.replace(/[-_]/g," ").replace(/\b\w/g,n=>n.toUpperCase())}const ty="fusion_onboarding_events",kg="fusion_onboarding_session_id",$O=200,DO=50;function oi(e,n={}){if(!(typeof window>"u"))try{const s=OO(),a=BO(n.step),r={type:e,timestamp:new Date().toISOString(),...a?{step:a}:{},metadata:n,sessionId:LO()},o=zO([...s,r]);FO(o)}catch{}}function LO(){if(typeof window>"u")return"server-session";try{const e=sessionStorage.getItem(kg);if(e)return e;const n=jg();return sessionStorage.setItem(kg,n),n}catch{return jg()}}function jg(){return typeof crypto<"u"&&typeof crypto.randomUUID=="function"?crypto.randomUUID():`onboarding-${Date.now().toString(36)}-${Math.random().toString(36).slice(2,12)}`}function OO(){try{const e=localStorage.getItem(ty);if(!e)return[];const n=JSON.parse(e);return Array.isArray(n)?n.filter(UO):[]}catch{return[]}}function FO(e){try{localStorage.setItem(ty,JSON.stringify(e))}catch{}}function zO(e){const n=[...e];for(;n.length>$O;)n.splice(0,DO);return n}function BO(e){if(e==="ai-setup"||e==="github"||e==="first-task"||e==="complete")return e}function UO(e){if(!e||typeof e!="object")return!1;const n=e;return typeof n.type=="string"&&typeof n.timestamp=="string"&&typeof n.sessionId=="string"&&!!n.metadata&&typeof n.metadata=="object"}const HO=e=>({id:e.id,name:e.name,baseUrl:e.baseUrl,api:"api"in e?e.api:e.apiType==="anthropic-compatible"?"anthropic-messages":"openai-responses",apiKey:e.apiKey,models:e.models?.map(n=>({id:n.id,name:n.name}))??[]}),qO={anthropic:{description:"Claude models — strong at reasoning, analysis, and code"},openai:{description:"GPT models — versatile for a wide range of tasks",apiKeyInfo:{fieldLabel:"OpenAI API Key",setupInstructions:"Create an API key from your OpenAI dashboard under API keys.",dashboardUrl:"https://platform.openai.com/api-keys",inputPlaceholder:"sk-...",usageDescription:"Used for GPT models in task execution and planning"}},"openai-codex":{description:"Codex models by OpenAI — optimized for coding tasks"},google:{description:"Gemini models — multimodal with strong reasoning"},gemini:{description:"Gemini models — multimodal with strong reasoning"},ollama:{description:"Run open-source models locally on your machine",apiKeyInfo:{fieldLabel:"Ollama Endpoint",setupInstructions:"Enter your Ollama endpoint URL (for example http://localhost:11434).",inputPlaceholder:"http://localhost:11434",usageDescription:"Connects to your local Ollama instance"}},minimax:{description:"MiniMax models — cost-effective for high-volume usage",apiKeyInfo:{fieldLabel:"MiniMax API Key",setupInstructions:"Generate an API key from the MiniMax platform developer console.",dashboardUrl:"https://platform.minimaxi.com/",inputPlaceholder:"Enter your MiniMax API key",usageDescription:"Used for MiniMax models in task execution"}},zai:{description:"GLM models by Zhipu AI — strong multilingual support",apiKeyInfo:{fieldLabel:"Zhipu AI API Key",setupInstructions:"Create an API key in the Zhipu AI open platform account settings.",dashboardUrl:"https://open.bigmodel.cn/",inputPlaceholder:"Enter your Zhipu AI API key",usageDescription:"Used for GLM models in task execution"}},kimi:{description:"Kimi by Moonshot AI — long-context capabilities"},moonshot:{description:"Kimi by Moonshot AI — long-context capabilities"},"kimi-coding":{description:"Kimi by Moonshot AI — long-context capabilities",apiKeyInfo:{fieldLabel:"Kimi API Key",setupInstructions:"Create your API key in the Moonshot platform account settings.",dashboardUrl:"https://platform.moonshot.cn/",inputPlaceholder:"Enter your Kimi API key",usageDescription:"Used for Kimi/Moonshot AI models in task execution and planning"}},openrouter:{description:"OpenRouter — route requests across multiple AI providers",apiKeyInfo:{fieldLabel:"OpenRouter API Key",setupInstructions:"Create an API key from your OpenRouter account key management page.",dashboardUrl:"https://openrouter.ai/keys",inputPlaceholder:"sk-or-v1-...",usageDescription:"Routes to multiple AI model providers through a single key"}}},ny={anthropic:{pattern:/^sk-ant-/,hint:"Starts with sk-ant-",example:"sk-ant-api03-..."},openai:{pattern:/^sk-/,hint:"Starts with sk-",example:"sk-..."},"openai-codex":{pattern:/^sk-/,hint:"Starts with sk-",example:"sk-..."},openrouter:{pattern:/^sk-or-/,hint:"Starts with sk-or-",example:"sk-or-v1-..."},google:{pattern:/^AIza/,hint:"Starts with AIza",example:"AIza..."},gemini:{pattern:/^AIza/,hint:"Starts with AIza",example:"AIza..."},minimax:{pattern:/^.{8,}$/,hint:"At least 8 characters",example:"..."},ollama:{pattern:/^.+$/,hint:"Any non-empty value",example:"ollama"},zai:{pattern:/^.{8,}$/,hint:"At least 8 characters",example:"..."},kimi:{pattern:/^.{8,}$/,hint:"At least 8 characters",example:"..."},"kimi-coding":{pattern:/^.{8,}$/,hint:"At least 8 characters",example:"..."},moonshot:{pattern:/^.{8,}$/,hint:"At least 8 characters",example:"..."}},VO={pattern:/^.{8,}$/,hint:"At least 8 characters",example:"..."},Ng={anthropic:"Anthropic",openai:"OpenAI","openai-codex":"OpenAI Codex",openrouter:"OpenRouter",google:"Google",gemini:"Gemini",minimax:"MiniMax",ollama:"Ollama",zai:"Zhipu AI",kimi:"Kimi","kimi-coding":"Kimi Coding",moonshot:"Moonshot"},WO=e=>`After you sign in with ${e}, the browser will try to redirect to a localhost address that this dashboard can't reach. The redirect tab will look like it failed. Before that happens, copy the full URL from the browser address bar — you'll paste it back here to finish login. Continue?`;function Lu(e){if(Ng[e])return Ng[e];const n=e.trim();return n?n.split(/[-_\s]+/).filter(Boolean).map(s=>s.charAt(0).toUpperCase()+s.slice(1)).join(" "):"This provider"}const Zd=["anthropic","openai","google","gemini","ollama"],GO=["anthropic","claude-cli","droid-cli","cursor-cli","llama-cpp","openai-codex","gemini","minimax","kimi","zai"],KO={anthropic:"anthropic","claude-cli":"claude-cli","droid-cli":"droid-cli","llama-cpp":"llama-cpp","openai-codex":"openai-codex",google:"gemini",gemini:"gemini",minimax:"minimax",kimi:"kimi",moonshot:"kimi","kimi-coding":"kimi",zai:"zai"},JO={gemini:["google","gemini"],kimi:["kimi","moonshot","kimi-coding"]};function Ou(e){return KO[e]??e}function Sg(e){const n=Ou(e),s=GO.indexOf(n);return s===-1?Number.POSITIVE_INFINITY:s}function Cg(e,n){if(e.authenticated!==n.authenticated)return e.authenticated?-1:1;const s=Sg(e.id),a=Sg(n.id);if(s!==a)return s-a;const r=Ou(e.id),o=Ou(n.id);if(r!==o)return r.localeCompare(o);const l=JO[r];if(l){const d=l.indexOf(e.id),u=l.indexOf(n.id);if(d!==u)return(d===-1?Number.POSITIVE_INFINITY:d)-(u===-1?Number.POSITIVE_INFINITY:u)}const c=e.name.localeCompare(n.name);return c!==0?c:e.id.localeCompare(n.id)}function YO(e,n){const s=n.trim();if(!s)return"API key is required";const a=ny[e]??VO;return a.pattern.test(s)?null:`${Lu(e)} keys should follow this format: ${a.hint} (e.g. ${a.example})`}const sy={fieldLabel:"API Key",setupInstructions:"Enter your API key for this provider.",inputPlaceholder:"Enter API key",usageDescription:"Used by Fusion to authenticate requests to this provider"},QO={description:"AI provider — connect to start using AI models",apiKeyInfo:sy};function Fu(e){return qO[e]??QO}function XO(e){return Fu(e.id).apiKeyInfo??sy}function ZO({items:e}){return e.some(s=>s.status!=="connected")?t.jsxs("div",{className:"onboarding-readiness-summary","data-testid":"readiness-summary",role:"status",children:[t.jsx("p",{className:"onboarding-readiness-header",children:"Setup Summary"}),e.map(s=>{const a=s.status==="connected"?"✓":s.status==="missing"?"⚠":"○";return t.jsxs("div",{className:`onboarding-readiness-item onboarding-readiness-item--${s.status}`,"data-status":s.status,children:[t.jsx("span",{className:"onboarding-readiness-icon","aria-hidden":"true",children:a}),t.jsxs("span",{className:"onboarding-readiness-content",children:[t.jsx("span",{className:"onboarding-readiness-label",children:s.label}),s.detail&&t.jsx("span",{className:"onboarding-readiness-detail",children:s.detail})]})]},s.label)})]}):t.jsx("div",{className:"onboarding-readiness-summary","data-testid":"readiness-summary",role:"status",children:t.jsx("p",{className:"onboarding-readiness-all-connected",children:"✓ All integrations connected"})})}function eF({provider:e,apiKeyInfo:n,inputValue:s,isSaving:a,error:r,success:o,isConnected:l,onInputChange:c,onSave:d,onClear:u}){const h=`onboarding-apikey-input-${e.id}`,m=a||!s.trim(),f=ny[e.id],p=`input onboarding-apikey-input${r?" onboarding-apikey-input--error":""}${o?" onboarding-apikey-input--success":""}`,g=t.jsxs(t.Fragment,{children:[f&&t.jsxs("small",{className:"onboarding-apikey-hint",children:["Format: ",f.hint]}),t.jsx("p",{className:"onboarding-apikey-instructions",children:n.setupInstructions}),n.dashboardUrl&&t.jsx("a",{href:n.dashboardUrl,target:"_blank",rel:"noreferrer",className:"onboarding-apikey-dashboard-link",children:"Get your API key →"}),t.jsx("p",{className:"onboarding-apikey-usage",children:n.usageDescription})]});return l?t.jsxs("div",{className:"onboarding-apikey-form","data-testid":`onboarding-apikey-form-${e.id}`,children:[t.jsxs("div",{className:"onboarding-apikey-connected-header",children:[t.jsx("strong",{className:"onboarding-provider-card__name",children:n.fieldLabel}),t.jsx("span",{className:"auth-status-badge connected",children:"✓ API key saved"})]}),t.jsx("button",{className:"btn btn-sm",onClick:()=>u(e.id),disabled:a,children:a?"Removing…":"Remove Key"}),t.jsx(li,{summary:"Advanced setup details",children:g}),r&&t.jsx("small",{className:"field-error",children:r})]}):t.jsxs("div",{className:"onboarding-apikey-form","data-testid":`onboarding-apikey-form-${e.id}`,children:[t.jsx("label",{htmlFor:h,className:"onboarding-apikey-field-label",children:n.fieldLabel}),t.jsxs("div",{className:"onboarding-apikey-input-row",children:[t.jsx("input",{id:h,type:"password",className:p,placeholder:n.inputPlaceholder??"Enter API key",value:s,onChange:w=>c(e.id,w.target.value),onKeyDown:w=>{w.key==="Enter"&&d(e.id,s)},"data-testid":h}),t.jsx("button",{className:"btn btn-primary btn-sm",onClick:()=>d(e.id,s),disabled:m,"data-testid":`onboarding-apikey-save-${e.id}`,children:a?"Saving…":"Save"})]}),r&&t.jsx("small",{className:"field-error",children:r}),o&&!r&&t.jsx("small",{className:"onboarding-apikey-success","data-testid":`onboarding-apikey-success-${e.id}`,children:o}),t.jsx(li,{summary:"Advanced setup details",children:g})]})}const tF=150;function nF({onComplete:e,addToast:n,projectId:s,onOpenSetupWizard:a,onOpenNewTask:r,onOpenGitHubImport:o,firstCreatedTask:l,onViewTask:c}){const{confirm:d}=ti(),u=Zs(),h=u?.currentStep,m=h==="complete"?"ai-setup":ua.includes(h)?h:"ai-setup",f=u?.completedSteps??[],p=u?.skippedSteps??IO(),[g,w]=i.useState(!0),[v,b]=i.useState(m),[y,j]=i.useState(f),[S,C]=i.useState(p),[x,k]=i.useState(!1),[R,O]=i.useState(""),[E,_]=i.useState(!1),[G,H]=i.useState(null),[A,P]=i.useState(null),[q,Y]=i.useState([]),[ge,L]=i.useState(void 0),[M,$]=i.useState(!0),[D,N]=i.useState(null),[W,de]=i.useState({}),[me,Ne]=i.useState({}),[ve,Me]=i.useState({}),[ie,ye]=i.useState(null),[Z,fe]=i.useState([]),[Q,F]=i.useState(""),[X,re]=i.useState(!1),[U,be]=i.useState({}),[Ue,se]=i.useState({}),[Ve,Le]=i.useState({}),[ct,Ke]=i.useState([]),[oe,Te]=i.useState(!1),[Fe,mt]=i.useState(!1),[We,he]=i.useState(),[pe,De]=i.useState("Remote Server"),[ut,ht]=i.useState(""),[et,vt]=i.useState(""),[Oe,tt]=i.useState(!1),[ft,Mt]=i.useState(null),yt=i.useRef({}),Ge=i.useRef(null),K=i.useRef(null),ue=i.useRef(null),[ot,xe]=i.useState({}),[dt,Je]=i.useState(()=>Zs()?.stepData?.github?.skipped===!0),ke=i.useRef(0),nt=i.useRef(l),{shellApi:bt,state:kt}=Zv(),wt=i.useRef(!1),At=u?.currentStep,Ft=!!u&&u.currentStep!=="complete";Oi(K,g,"fusion:model-onboarding-modal-size"),i.useEffect(()=>{const T=Ge.current;T&&(T.scrollTop=0)},[v]);const[ln,Vt]=i.useState(()=>Zs()?.stepData?.["ai-setup"]?.skippedProviders??{}),hn=[{key:"ai-setup",label:"AI Setup"},{key:"github",label:"GitHub"},{key:"project-setup",label:"Project"},{key:"first-task",label:"First Task"}],un=hn.findIndex(T=>T.key===v),pn=v==="complete"?hn.length:un;i.useEffect(()=>{v!=="complete"&&Fl(v,{completedSteps:y,skippedSteps:S})},[v,y,S]),i.useEffect(()=>{wt.current||(wt.current=!0,oi("onboarding:wizard-opened",{source:Ft?"resume":"initial",resumedFromStep:At}))},[Ft,At]),i.useEffect(()=>{const T=nt.current!=null,je=l!=null;!T&&je&&k(!0),je||k(!1),nt.current=l},[l]);const an=i.useRef(m);i.useEffect(()=>{if(an.current==="ai-setup"&&v!=="ai-setup"&&!q.some(je=>je.id!=="github"&&je.authenticated)){const je={};for(const Pe of q)Pe.id!=="github"&&!Pe.authenticated&&!ln[Pe.id]&&(je[Pe.id]=!0);if(Object.keys(je).length>0){const Pe={...ln,...je};Vt(Pe),Fl(v,{stepData:{"ai-setup":{skippedProviders:Pe}}})}}an.current=v},[v,q,ln]);const Wt=i.useCallback(async()=>{try{const{providers:T,ghCli:je}=await Do(),Pe=yg(T);Y(Pe),L(je),de(st=>{const gt={};for(const[Et,Pt]of Object.entries(st)){const dn=Pe.find(Nn=>Nn.id===Et);dn&&!dn.authenticated&&dn.loginInProgress&&(gt[Et]=Pt)}return Object.keys(gt).length===Object.keys(st).length?st:gt}),xe(st=>{let gt=!1;const Et={...st};for(const[Pt,dn]of Object.entries(st)){if(dn!=="pending")continue;Pe.find(Hn=>Hn.id===Pt)?.loginInProgress||(delete Et[Pt],gt=!0)}return gt?Et:st}),Vt(st=>{const gt={...st};for(const Et of Pe)Et.authenticated&&gt[Et.id]&&delete gt[Et.id];return Object.keys(gt).length===Object.keys(st).length?st:gt})}catch{}},[]),gn=i.useCallback(async()=>{try{const T=await GN();Ke((T.providers??[]).map(HO))}catch{}},[]),cn=i.useCallback(async T=>{mt(!0),he(void 0);try{await JN(T),await gn(),await Bs().then(je=>fe(je.models??[])),Te(!1)}catch(je){he(Ie(je)||"Failed to create custom provider")}finally{mt(!1)}},[gn]),tn=i.useRef(!1);i.useEffect(()=>{v==="ai-setup"&&gn(),tn.current&&Wt(),tn.current=v!=="ai-setup"},[v,Wt,gn]),i.useEffect(()=>{if(!q.some(Pe=>Pe.loginInProgress))return;const je=setInterval(()=>{Wt()},2e3);return()=>clearInterval(je)},[q,Wt]);const Yt=q.find(T=>T.id==="github"),Qt=!!Yt,Kt=Yt?.authenticated??!1,Jt=Yt?.loginInProgress??!1,rn=ge?.authenticated??!1,qt=Kt||rn,we=!Kt&&rn,ze=i.useCallback(T=>{if(T.authenticated)return"connected";const je=ot?.[T.id];return je==="timeout"||je==="failed"?"retry":ln[T.id]?"skipped":"not-connected"},[ot,ln]);function rt({status:T}){const je={connected:{text:"✓ Connected",className:"auth-status-badge connected"},"not-connected":{text:"Not connected",className:"auth-status-badge not-connected"},skipped:{text:"Skipped",className:"auth-status-badge skipped"},retry:{text:"Retry",className:"auth-status-badge retry"}},{text:Pe,className:st}=je[T];return t.jsx("span",{"data-testid":"provider-status-badge",className:st,"data-status":T,children:Pe})}const He=i.useCallback(()=>{if(qt)return"connected";const T=ot.github;return T==="pending"?"pending":T==="failed"||T==="timeout"?"failed":dt?"skipped":"not-connected"},[qt,ot,dt]);function Ae({status:T}){const je={connected:{text:"✓ Connected",className:"auth-status-badge connected"},pending:{text:"⏳ Connecting…",className:"auth-status-badge pending"},failed:{text:"✗ Connection failed",className:"auth-status-badge retry"},skipped:{text:"Skipped",className:"auth-status-badge skipped"},"not-connected":{text:"Not connected",className:"auth-status-badge not-connected"}},{text:Pe,className:st}=je[T];return t.jsx("span",{"data-testid":"github-status-badge",className:st,"data-status":T,children:Pe})}const pt=i.useCallback(async()=>{try{const T=await Bs();fe(T.models)}catch{}},[]),Ct=i.useCallback(async()=>{try{const T=await Qi();if(T.defaultProvider&&T.defaultModelId){const je=`${T.defaultProvider}/${T.defaultModelId}`;F(je)}}catch{}},[]);i.useEffect(()=>{Promise.all([Wt(),pt(),Ct()]).finally(()=>$(!1))},[Wt,pt,Ct]),i.useEffect(()=>{const T=TO("ai-setup");if(T?.loginOutcomes){const je=T.loginOutcomes,Pe={};for(const[st,gt]of Object.entries(je))gt!=="pending"&&(Pe[st]=gt);Object.keys(Pe).length>0&&xe(Pe)}},[]);const Tt=i.useCallback((T,je)=>{Fl(v,{completedSteps:y,stepData:{"ai-setup":{loginOutcomes:{[T]:je}}}})},[v,y]);i.useEffect(()=>{const T=Object.entries(ot).filter(([je,Pe])=>Pe!=="pending");for(const[je,Pe]of T)Tt(je,Pe)},[ot,Tt]),i.useEffect(()=>()=>{ue.current&&clearInterval(ue.current),Object.values(yt.current).forEach(clearTimeout),yt.current={}},[]);const Gt=i.useCallback(T=>{Je(T),Fl(v,{completedSteps:y,stepData:{github:{skipped:T}}})},[v,y]),nn=i.useCallback(T=>T==="complete"?-1:ua.indexOf(T),[]),Ht=i.useCallback(()=>{j(je=>[...new Set([...je,v])]),C(je=>je.filter(Pe=>Pe!==v)),oi("onboarding:step-completed",{step:v}),v==="github"&&!Kt&&Gt(!1);const T=nn(v);T>=0&&T<ua.length-1&&b(ua[T+1])},[v,Kt,Gt,nn]),on=i.useCallback(()=>{C(je=>[...new Set([...je,v])]),_O(v),oi("onboarding:step-skipped",{step:v}),v==="github"&&!Kt&&Gt(!0);const T=nn(v);T>=0&&T<ua.length-1&&b(ua[T+1])},[v,Kt,Gt,nn]),ae=i.useCallback(()=>{const T=v;j(Pe=>Pe.filter(st=>st!==T)),C(Pe=>Pe.filter(st=>st!==T)),T==="github"&&!Kt&&Gt(!1);const je=nn(v);je>0&&b(ua[je-1])},[v,Kt,Gt,nn]),le=i.useCallback(()=>{on()},[on]),Qe=i.useCallback(async T=>{const je=q.find(st=>st.id===T);if(je?.requiresManualCode===!0&&!await d({title:"Heads up — manual paste-back required",message:WO(je.name),confirmLabel:"Continue to login",cancelLabel:"Cancel"}))return;xe(st=>{const gt=st[T];if(gt&&gt!=="pending"){const{[T]:Et,...Pt}=st;return Pt}return st});const Pe=()=>{de(st=>{if(!(T in st))return st;const gt={...st};return delete gt[T],gt}),Ne(st=>{if(!(T in st))return st;const gt={...st};return delete gt[T],gt}),Me(st=>{if(!(T in st))return st;const gt={...st};return delete gt[T],gt})};Pe(),xe(st=>({...st,[T]:"pending"})),N(T),ke.current=0;try{const{url:st,instructions:gt,manualCode:Et}=await YN(T);gt?.trim()&&de(Pt=>({...Pt,[T]:gt})),Et&&Ne(Pt=>({...Pt,[T]:Et})),window.open(Li(st),"_blank"),ue.current=setInterval(async()=>{if(ke.current++,ke.current>=tF){ue.current&&(clearInterval(ue.current),ue.current=null),N(null),Y(Pt=>Pt.map(dn=>dn.id===T?{...dn,loginInProgress:!1}:dn)),xe(Pt=>({...Pt,[T]:"timeout"})),Pe(),n("Login timed out. Please try again.","warning");return}try{const{providers:Pt,ghCli:dn}=await Do(),Nn=yg(Pt);Y(Nn),L(dn);const Hn=Nn.find(ne=>ne.id===T);if(Hn?.authenticated){ue.current&&(clearInterval(ue.current),ue.current=null),N(null),xe(ne=>({...ne,[T]:"success"})),Pe(),T==="github"&&Gt(!1),n("Login successful","success");return}Hn?.loginInProgress||(ue.current&&(clearInterval(ue.current),ue.current=null),N(null),xe(ne=>({...ne,[T]:"failed"})),Pe(),n("Login did not complete. Please try again.","error"))}catch{}},2e3)}catch(st){st instanceof Error&&st.message.includes("already in progress")||st&&typeof st=="object"&&"status"in st&&st.status===409?(n("Login already in progress. Cancel it to retry.","warning"),xe(Et=>({...Et,[T]:"pending"})),Wt()):(n(st instanceof Error?st.message:"Login failed","error"),xe(Et=>({...Et,[T]:"failed"}))),N(null),Pe()}},[n,q,d,Wt,Gt]),xt=i.useCallback(async T=>{const je=ve[T]?.trim();if(!je){n("Paste the full redirect URL or authorization code first.","warning");return}ye(T);try{(await QN(T,je)).submitted?(Me(st=>{if(!(T in st))return st;const gt={...st};return delete gt[T],gt}),n("Authorization code received. Finishing login…","success")):n("That authorization code was already submitted. Waiting for login…","warning")}catch(Pe){n(Ie(Pe)||"Failed to submit authorization code","error")}finally{ye(null)}},[n,ve]),zt=i.useCallback(async T=>{ue.current&&(clearInterval(ue.current),ue.current=null),N(T),ke.current=0,Y(je=>je.map(Pe=>Pe.id===T?{...Pe,loginInProgress:!1}:Pe)),xe(je=>({...je,[T]:"cancelled"}));try{await ZN(T),await Wt().catch(()=>{}),n("Login cancelled","success")}catch(je){n(Ie(je)||"Failed to cancel login","error")}finally{N(null),de(je=>{if(!(T in je))return je;const Pe={...je};return delete Pe[T],Pe}),Ne(je=>{if(!(T in je))return je;const Pe={...je};return delete Pe[T],Pe}),Me(je=>{if(!(T in je))return je;const Pe={...je};return delete Pe[T],Pe}),ye(je=>je===T?null:je)}},[n,Wt]),sn=i.useCallback((T,je)=>{be(st=>({...st,[T]:je}));const Pe=yt.current[T];Pe&&(clearTimeout(Pe),delete yt.current[T]),se(st=>{if(!st[T])return st;const gt={...st};return delete gt[T],gt}),Le(st=>{if(!st[T])return st;const gt={...st};return delete gt[T],gt})},[]),xn=i.useCallback(()=>{const T=Ge.current;if(!T)return;const je=typeof window<"u"&&typeof window.matchMedia=="function"&&window.matchMedia("(prefers-reduced-motion: reduce)").matches;try{if(typeof T.scrollTo=="function"){T.scrollTo({top:0,behavior:je?"auto":"smooth"});return}}catch{}T.scrollTop=0},[]),$n=i.useCallback(async(T,je)=>{const Pe=(je??U[T]??"").trim(),st=YO(T,Pe);if(st){se(Et=>({...Et,[T]:st}));return}const gt=yt.current[T];gt&&(clearTimeout(gt),delete yt.current[T]),N(T),se(Et=>{const Pt={...Et};return delete Pt[T],Pt}),Le(Et=>{if(!Et[T])return Et;const Pt={...Et};return delete Pt[T],Pt});try{await eS(T,Pe),await Wt(),xn(),be(Et=>{const Pt={...Et};return delete Pt[T],Pt}),se(Et=>{if(!Et[T])return Et;const Pt={...Et};return delete Pt[T],Pt}),Le(Et=>({...Et,[T]:"✓ Key saved"})),yt.current[T]=setTimeout(()=>{Le(Et=>{if(!Et[T])return Et;const Pt={...Et};return delete Pt[T],Pt}),delete yt.current[T]},3e3),n("API key saved","success")}catch(Et){const Pt=Et instanceof TypeError&&Et.message.includes("Failed to fetch")?"Could not reach the server. Check your connection and try again.":Et instanceof Error?Et.message:"Failed to save API key";se(dn=>({...dn,[T]:Pt})),Le(dn=>{if(!dn[T])return dn;const Nn={...dn};return delete Nn[T],Nn}),n(Pt,"error")}finally{N(null)}},[U,n,Wt,xn]),wn=i.useCallback(async T=>{N(T);try{await tS(T),await Wt(),n("API key removed","success")}catch(je){n(je instanceof Error?je.message:"Failed to clear API key","error")}finally{N(null)}},[n,Wt]),zn=i.useCallback(async T=>{N(T);try{await XN(T),await Wt(),n("Logged out","success")}catch(je){n(je instanceof Error?je.message:"Logout failed","error")}finally{N(null)}},[n,Wt]),ce=i.useCallback(T=>{F(T)},[]),ee=i.useCallback(async()=>{try{const T={modelOnboardingComplete:!0};if(Q){const je=Q.indexOf("/"),Pe=je!==-1?Q.slice(0,je):void 0,st=je!==-1?Q.slice(je+1):Q,gt=Z.find(Et=>Et.id===st);gt?(T.defaultProvider=gt.provider,T.defaultModelId=gt.id):Pe&&st&&(T.defaultProvider=Pe,T.defaultModelId=st)}await Fn(T),wg()}catch{}},[Q,Z,Fn,wg]),Se=i.useCallback(async()=>{const T=[...new Set([...y,"first-task"])];re(!0);try{await ee(),oi("onboarding:completed",{completedSteps:T,skippedSteps:S}),j(T),C(je=>je.filter(Pe=>Pe!=="first-task")),b("complete")}finally{re(!1)}},[ee,y,S]),qe=i.useCallback(async()=>{if(!s)return;const T=R.trim();if(!T){H("Please enter a task description.");return}H(null),_(!0);let je=!1;try{const Pe=await Nb({description:T,source:{sourceType:"dashboard_ui"}},s);P(Pe),k(!0),oi("onboarding:first-task-created",{taskId:Pe?.id}),n("Task created","success"),je=!0}catch(Pe){const st=Pe instanceof Error?Pe.message:"Something went wrong creating your task. Please try again.";H(st),n(st,"error")}finally{_(!1)}je&&ee()},[s,R,n,ee]),z=i.useCallback(async()=>{re(!0);try{await ee()}finally{re(!1)}oi("onboarding:open-new-task",{}),r?.()},[ee,r]),_e=i.useCallback(async()=>{if(qt){re(!0);try{await ee()}finally{re(!1)}w(!1),e(),oi("onboarding:open-github-import",{}),o?.()}},[ee,qt,e,o]),Rt=i.useCallback(async()=>{oi("onboarding:dismissed",{currentStep:v,completedSteps:y,skippedSteps:S}),re(!0);try{await Fn({modelOnboardingComplete:!0})}catch{}w(!1),e()},[v,y,S,e]),Ot=i.useCallback(()=>{oi("onboarding:finished",{}),w(!1),e()},[e]),Lt=i.useCallback(()=>{const T=l??A;T&&(ee(),c?.(T),e())},[l,A,ee,c,e]),fn=i.useCallback(()=>{ee(),e()},[ee,e]),kn=He(),es=q.filter(T=>T.id!=="github"),ms=kt.host!=="web"&&!kt.activeProfileId,Gn=[...es].sort(Cg),hs=Gn.some(T=>!T.type||T.type==="oauth"),Cn=Gn.some(T=>T.type==="api_key"),Bt=es.filter(T=>T.authenticated),Bn=Bt.length>0,En=!!s,bs=v==="github"&&!Bn,$s=i.useCallback(async()=>{if(bt){Mt(null),tt(!0);try{const T=await bt.saveProfile({name:pe,serverUrl:ut,authToken:et.trim()?et:null});try{await bt.setActiveProfile(T.id)}catch(je){Mt(Ie(je)||"Saved profile but failed to activate it");return}ht(""),vt(""),n("Remote server profile saved","success")}catch(T){Mt(Ie(T)||"Failed to save shell connection")}finally{tt(!1)}}},[bt,pe,ut,et,n]);if(!g)return null;const ss=(()=>{if(!Q)return"";const T=Q.indexOf("/"),je=T===-1?void 0:Q.slice(0,T),Pe=T===-1?Q:Q.slice(T+1),st=Z.find(gt=>gt.id===Pe&&(!je||gt.provider===je));return st?.name?st.name:je?`${Lu(je)} ${Pe}`:Q})(),Un=[];if(En?Un.push({label:"Project",status:"connected",detail:"Project selected — task creation and imports are available"}):Un.push({label:"Project",status:"missing",detail:"Register a project to enable task creation and imports"}),Bn){const T=Lu(Bt[0]?.id??"");Un.push({label:"AI Provider",status:"connected",detail:`${T} connected — AI agents can work on tasks`})}else es.length>0&&es.some(T=>ln[T.id])?Un.push({label:"AI Provider",status:"skipped",detail:"AI agents won't be available until you connect a provider"}):Un.push({label:"AI Provider",status:"missing",detail:"Connect a provider in Settings → AI Setup"});qt?Un.push({label:"GitHub",status:"connected",detail:we?"Connected via GitHub CLI — imports and PR tracking are available":"Issues and PRs can be imported"}):!Qt||dt?Un.push({label:"GitHub",status:"skipped",detail:"You can connect anytime from Settings"}):Un.push({label:"GitHub",status:"missing",detail:"Connect to import issues as tasks"}),ss&&Un.push({label:"Default Model",status:"connected",detail:ss});const Kn=l??A,Ms=Kn?.description?.split(`
696
- `)[0]?.trim()||Kn?.title||"",xs=new Set(Zd),As=Gn.filter(T=>xs.has(T.id)).sort((T,je)=>{const Pe=Zd.indexOf(T.id),st=Zd.indexOf(je.id);return Pe!==st?Pe-st:Cg(T,je)}),vs=Gn.filter(T=>T.authenticated&&!xs.has(T.id)),te=Gn.filter(T=>!T.authenticated&&!xs.has(T.id)),Ee=T=>{const je=ot[T.id]==="timeout"||ot[T.id]==="failed"||ot[T.id]==="cancelled",Pe=T.loginInProgress&&!je;if(T.id==="llama-cpp"&&T.type==="cli")return t.jsx(dO,{authenticated:T.authenticated,onToggled:()=>{Wt()}},T.id);if(T.id==="claude-cli"&&T.type==="cli")return t.jsx(oO,{authenticated:T.authenticated,onToggled:()=>{Wt()}},T.id);if(T.id==="cursor-cli"&&T.type==="cli")return t.jsx(cO,{authenticated:T.authenticated,onToggled:()=>{Wt()}},T.id);if(T.type==="api_key"){const st=Fu(T.id),gt=XO(T);return t.jsxs("div",{"data-testid":`onboarding-provider-card-${T.id}`,className:`onboarding-provider-card${T.authenticated?" onboarding-provider-card--connected":""}`,children:[t.jsx("div",{className:"onboarding-provider-card__icon","data-testid":`onboarding-provider-icon-${T.id}`,"aria-hidden":"true",children:t.jsx(On,{provider:T.id,size:"md"})}),t.jsxs("div",{className:"onboarding-provider-card__body",children:[t.jsxs("strong",{className:"onboarding-provider-card__name",children:[t.jsx(hb,{size:14,className:"onboarding-provider-key-icon"}),T.name]}),t.jsx("span",{className:"onboarding-provider-card__description",children:st.description}),t.jsx(rt,{status:ze(T)}),T.authenticated&&T.keyHint&&t.jsxs("span",{className:"auth-key-hint",children:["Key: ",T.keyHint]})]}),t.jsx("div",{className:"onboarding-provider-card__actions onboarding-provider-card__actions--api-key",children:t.jsx(eF,{provider:T,apiKeyInfo:gt,inputValue:U[T.id]??"",isSaving:D===T.id,error:Ue[T.id],success:Ve[T.id],isConnected:T.authenticated,onInputChange:sn,onSave:$n,onClear:wn})})]},T.id)}return t.jsxs("div",{"data-testid":`onboarding-provider-card-${T.id}`,className:`onboarding-provider-card${T.authenticated?" onboarding-provider-card--connected":""}`,children:[t.jsx("div",{className:"onboarding-provider-card__icon","data-testid":`onboarding-provider-icon-${T.id}`,"aria-hidden":"true",children:t.jsx(On,{provider:T.id,size:"md"})}),t.jsxs("div",{className:"onboarding-provider-card__body",children:[t.jsx("strong",{className:"onboarding-provider-card__name",children:T.name}),t.jsx("span",{className:"onboarding-provider-card__description",children:Fu(T.id).description}),t.jsx(rt,{status:ze(T)})]}),t.jsx("div",{className:"onboarding-provider-card__actions",children:D===T.id?T.authenticated?t.jsx("button",{className:"btn btn-sm",disabled:!0,children:"Logging out…"}):t.jsxs(t.Fragment,{children:[t.jsx("button",{className:"btn btn-sm",disabled:!0,children:"Waiting for login…"}),t.jsx("button",{className:"btn btn-sm",onClick:()=>void zt(T.id),children:"Cancel"})]}):Pe?t.jsxs(t.Fragment,{children:[t.jsx("button",{className:"btn btn-sm",disabled:!0,children:"Waiting for login…"}),t.jsx("button",{className:"btn btn-sm",onClick:()=>void zt(T.id),children:"Cancel"})]}):T.authenticated?t.jsx("button",{className:"btn btn-sm",onClick:()=>zn(T.id),children:"Logout"}):t.jsx("button",{className:"btn btn-primary btn-sm",onClick:()=>Qe(T.id),children:"Login"})}),(D===T.id||Pe)&&W[T.id]&&t.jsx(Xd,{instructions:W[T.id],"data-testid":`onboarding-login-instructions-${T.id}`}),(D===T.id||Pe)&&me[T.id]&&t.jsx(mO,{value:ve[T.id]??"",onChange:st=>Me(gt=>({...gt,[T.id]:st})),onSubmit:()=>void xt(T.id),prompt:me[T.id].prompt,placeholder:me[T.id].placeholder,helpText:me[T.id].helpText,disabled:ie===T.id,submitLabel:ie===T.id?"Submitting…":"Submit code","data-testid":`onboarding-manual-code-${T.id}`}),ot[T.id]==="timeout"&&D!==T.id&&t.jsx("p",{className:"onboarding-helper-text onboarding-inline-feedback",children:"Login timed out. Please try again."}),ot[T.id]==="failed"&&D!==T.id&&t.jsx("p",{className:"field-error onboarding-inline-feedback",children:"Login failed. Please try again."})]},T.id)};return t.jsx("div",{className:"modal-overlay open",role:"dialog","aria-modal":"true","aria-labelledby":"onboarding-title",children:t.jsxs("div",{className:"modal model-onboarding-modal",ref:K,children:[t.jsxs("div",{className:"model-onboarding-header",children:[t.jsxs("h2",{id:"onboarding-title",className:"model-onboarding-title",children:[v==="ai-setup"&&t.jsxs(t.Fragment,{children:[t.jsx(as,{size:24})," Set Up AI ",t.jsx("span",{className:"onboarding-optional-badge",children:"Optional"})]}),v==="github"&&t.jsxs(t.Fragment,{children:[t.jsx(Qs,{size:24})," Connect GitHub ",t.jsx("span",{className:"onboarding-optional-badge",children:"Optional"})]}),v==="project-setup"&&t.jsxs(t.Fragment,{children:[t.jsx(Bm,{size:24})," Set Up Your Project"]}),v==="first-task"&&t.jsxs(t.Fragment,{children:[t.jsx(Bm,{size:24})," Create Your First Task"]}),v==="complete"&&t.jsxs(t.Fragment,{children:[t.jsx(Zn,{size:24})," All Set!"]})]}),v!=="complete"&&t.jsx("button",{className:"modal-close",onClick:Rt,"aria-label":"Skip onboarding",title:"Skip for now",children:t.jsx(bn,{size:20})})]}),t.jsx("div",{className:"model-onboarding-steps",children:hn.map((T,je)=>{const Pe=pn>je,st=y.includes(T.key)&&Pe,gt=S.includes(T.key)&&!y.includes(T.key)&&Pe,Et=st||gt;return t.jsxs("div",{className:"onboarding-step-wrapper",children:[je>0&&t.jsx("div",{className:`model-onboarding-step-connector ${je<=pn?"done":""}`}),Et?t.jsxs("button",{className:`model-onboarding-step-indicator ${v===T.key?"active":""} ${st?"done":""} ${gt?"skipped":""}`,onClick:()=>b(T.key),"aria-label":`Go back to ${T.label}`,title:`Review ${T.label}`,children:[t.jsx("span",{className:"step-number",children:st?t.jsx(Zn,{size:14}):gt?t.jsx("span",{className:"onboarding-step-skip-mark",children:"–"}):je+1}),t.jsx("span",{className:"step-label",children:T.label})]}):t.jsxs("div",{className:`model-onboarding-step-indicator ${v===T.key?"active":""} ${st?"done":""} ${gt?"skipped":""}`,children:[t.jsx("span",{className:"step-number",children:st?t.jsx(Zn,{size:14}):gt?t.jsx("span",{className:"onboarding-step-skip-mark",children:"–"}):je+1}),t.jsx("span",{className:"step-label",children:T.label})]})]},T.key)})}),t.jsxs("div",{className:"model-onboarding-content",ref:Ge,children:[v==="ai-setup"&&t.jsxs("div",{className:"model-onboarding-ai-setup",children:[t.jsx("p",{className:"model-onboarding-description",children:"Fusion uses AI models to plan, write, and review code for you. Connect an AI provider below to get started — you can use a hosted service or enter an API key."}),t.jsx("p",{className:"onboarding-helper-text model-onboarding-primary-helper",children:"You only need one provider to get started."}),t.jsx("p",{className:"onboarding-helper-text",children:"Research runs require provider credentials and an enabled Research View. After onboarding, verify these in Settings → Authentication and Settings → Experimental Features."}),ms&&t.jsxs("div",{className:"card",children:[t.jsx("h3",{className:"onboarding-section-title",children:"Connect remote Fusion server"}),t.jsx("p",{className:"onboarding-helper-text",children:"Your native shell needs an active remote profile before dashboard handoff can complete."}),t.jsx("label",{htmlFor:"onboarding-shell-profile-name",className:"onboarding-apikey-field-label",children:"Profile name"}),t.jsx("input",{id:"onboarding-shell-profile-name",className:"input",value:pe,onChange:T=>De(T.target.value)}),t.jsx("label",{htmlFor:"onboarding-shell-server-url",className:"onboarding-apikey-field-label",children:"Server URL"}),t.jsx("input",{id:"onboarding-shell-server-url",className:"input",placeholder:"https://your-fusion-host",value:ut,onChange:T=>ht(T.target.value)}),t.jsx("label",{htmlFor:"onboarding-shell-token",className:"onboarding-apikey-field-label",children:"Auth token (optional)"}),t.jsx("input",{id:"onboarding-shell-token",className:"input",type:"password",value:et,onChange:T=>vt(T.target.value)}),ft&&t.jsx("small",{className:"field-error",children:ft}),t.jsxs("div",{className:"onboarding-apikey-input-row",children:[t.jsx("button",{type:"button",className:"btn btn-sm",onClick:()=>void bt?.openConnectionManager(),children:"Open manager"}),t.jsx("button",{type:"button",className:"btn btn-primary btn-sm",onClick:()=>void $s(),disabled:!ut.trim()||Oe,children:Oe?"Saving…":"Save remote server"})]})]}),!M&&q.length>0&&(()=>{const T=q.filter(Et=>Et.id!=="github"&&Et.authenticated).length,je=q.filter(Et=>Et.id!=="github").length,Pe=Object.keys(ln).filter(Et=>!q.find(Pt=>Pt.id===Et)?.authenticated).length;if(je===0)return null;let st="onboarding-provider-summary",gt="";return T>0?(st+=" onboarding-provider-summary--connected",gt=`✓ ${T} of ${je} provider${je!==1?"s":""} connected`):Pe>0?(st+=" onboarding-provider-summary--skipped",gt=`${Pe} provider${Pe!==1?"s":""} skipped`):(st+=" onboarding-provider-summary--none",gt="No providers connected yet"),t.jsx("div",{className:st,"data-testid":"provider-summary",children:gt})})(),t.jsx(pa,{slotId:"onboarding-recommendation-card",projectId:s}),t.jsx(li,{summary:"What are AI providers?",children:t.jsx("p",{className:"onboarding-helper-text",children:"AI providers like OpenAI and Anthropic power the AI capabilities in Fusion. Connecting a provider lets Fusion's agents use AI models to help with your tasks."})}),q.length>0&&!q.some(T=>T.authenticated)&&t.jsx("p",{className:"onboarding-helper-text",children:"Skip this step if you'd like — you can always add providers later from Settings."}),M?t.jsxs("div",{className:"model-onboarding-loading",children:[t.jsx(St,{size:24,className:"animate-spin"}),t.jsx("span",{children:"Loading providers…"})]}):q.length===0?t.jsx("div",{className:"model-onboarding-empty",children:"No AI providers are configured. Please check your Fusion configuration."}):t.jsxs(t.Fragment,{children:[t.jsx(pa,{slotId:"onboarding-provider-card",projectId:s,renderPlaceholder:!1,actions:{refreshAuthProviders:()=>{Wt()}}}),t.jsxs("section",{className:"onboarding-provider-section","data-testid":"onboarding-quick-start-providers",children:[t.jsx("h3",{className:"onboarding-section-title",children:"Quick start providers"}),As.length>0?t.jsx("div",{className:"model-onboarding-providers",children:As.map(T=>Ee(T))}):t.jsx("p",{className:"onboarding-helper-text",children:"No quick-start providers are available in this environment."})]}),vs.length>0&&t.jsxs("section",{className:"onboarding-provider-section","data-testid":"onboarding-connected-providers",children:[t.jsx("h3",{className:"onboarding-section-title",children:"Connected providers"}),t.jsx("div",{className:"model-onboarding-providers",children:vs.map(T=>Ee(T))})]}),t.jsxs("div",{className:"onboarding-model-section",children:[t.jsx("h3",{className:"onboarding-section-title",children:"Default Model (Optional)"}),t.jsx("p",{className:"model-onboarding-description",children:"Pick a default model for AI tasks, or leave this blank to choose later. Models vary in speed, capability, and cost."}),t.jsx(li,{summary:"How do I choose a model?",children:t.jsx("p",{className:"onboarding-helper-text",children:"Models vary in speed, capability, and cost. A good default is usually the latest model from your connected provider. You can always change this later in Settings."})}),Z.length===0?t.jsx("div",{className:"model-onboarding-empty",children:"No models available yet. Connect a provider above to see model options."}):t.jsx("div",{className:"onboarding-model-selector",children:t.jsx(Ns,{models:Z,value:Q,onChange:ce,placeholder:"Select a default model…",label:"Default model"})}),Q&&t.jsx("div",{className:"onboarding-model-preview",children:t.jsxs("small",{className:"settings-muted",children:["Selected:"," ",Z.find(T=>T.id===Q)?.name??Q]})})]}),t.jsx(li,{summary:"Advanced provider settings",className:"onboarding-provider-advanced",children:t.jsxs("div",{"data-testid":"onboarding-advanced-provider-settings",children:[te.length>0?t.jsx("div",{className:"model-onboarding-providers",children:te.map(T=>Ee(T))}):t.jsx("p",{className:"onboarding-helper-text",children:"All currently available providers are already shown above."}),ct.length>0?t.jsx("div",{className:"onboarding-custom-provider-list",children:ct.map(T=>t.jsxs("div",{className:"onboarding-custom-provider-item",children:[t.jsx(On,{provider:T.id,size:"sm"}),t.jsx("span",{children:T.name||T.id})]},T.id))}):null,oe?t.jsx(fO,{onSave:cn,onCancel:()=>{Te(!1),he(void 0)},saving:Fe,error:We}):t.jsx("button",{type:"button",className:"btn btn-sm",onClick:()=>Te(!0),children:"Add custom provider"})]})}),hs&&t.jsx(li,{summary:"How does login work?",children:t.jsx("p",{className:"onboarding-helper-text",children:"Clicking Login opens the provider's website in a new tab where you sign in. Once you authorize Fusion, this page will automatically detect the connection. Your credentials are never stored in Fusion."})}),Cn&&t.jsx(li,{summary:"What is an API key?",children:t.jsx("p",{className:"onboarding-helper-text",children:"An API key is a secret token that authenticates Fusion with the provider. You can find your key in the provider's dashboard under API settings. Keys are stored securely on your machine."})}),t.jsx(pa,{slotId:"onboarding-setup-help",projectId:s})]})]}),v==="github"&&t.jsxs("div",{className:"model-onboarding-github",children:[qt?t.jsx("p",{className:"model-onboarding-description",children:we?"GitHub CLI is already authenticated — issue imports and pull request tracking work right now. You're all set; no further action needed.":"GitHub is connected — issue imports and pull request tracking are available. You're all set; no further action needed."}):t.jsx("p",{className:"model-onboarding-description",children:"Connecting GitHub unlocks issue imports and pull request tracking. You can skip this — task creation works without it."}),!qt&&t.jsx("div",{className:"onboarding-feature-list",children:t.jsxs("ul",{children:[t.jsx("li",{className:"onboarding-feature-list-heading",children:t.jsx("strong",{children:"Without GitHub (available now):"})}),t.jsx("li",{className:"onboarding-helper-text",children:"Create tasks manually"}),t.jsx("li",{className:"onboarding-helper-text",children:"Describe work for AI agents"}),t.jsx("li",{className:"onboarding-helper-text",children:"Track progress on the board"}),t.jsx("li",{className:"onboarding-feature-list-heading",children:t.jsx("strong",{children:"With GitHub (after connecting):"})}),t.jsx("li",{className:"onboarding-helper-text onboarding-feature-list-item--with-github",children:"Import issues as tasks"}),t.jsx("li",{className:"onboarding-helper-text onboarding-feature-list-item--with-github",children:"Sync pull request status"}),t.jsx("li",{className:"onboarding-helper-text onboarding-feature-list-item--with-github",children:"Link code changes to tasks"})]})}),bs&&t.jsxs("div",{className:"onboarding-skip-banner",role:"status",children:[t.jsx("strong",{children:"No AI provider connected"}),t.jsx("p",{children:"AI features like task planning and code generation won't be available until you connect one. You can set this up later in Settings."})]}),t.jsx(li,{summary:"What does GitHub integration do?",children:t.jsx("p",{className:"onboarding-helper-text",children:"Without GitHub, you can still create and manage tasks manually. GitHub integration adds the ability to import issues as tasks, track pull request status alongside your work, and automatically link commits to tasks. Connect anytime from Settings → Authentication."})}),Qt?t.jsxs(t.Fragment,{children:[t.jsxs("div",{className:"onboarding-provider-row",children:[t.jsxs("div",{className:"onboarding-provider-info",children:[t.jsxs("strong",{children:[t.jsx(Qs,{size:16,className:"onboarding-provider-title-icon"}),"GitHub"]}),t.jsx("span",{"data-testid":"onboarding-auth-status-github",children:t.jsx(Ae,{status:kn})})]}),Kt&&(D==="github"?t.jsx("button",{className:"btn btn-sm",disabled:!0,children:"Logging out…"}):t.jsx("button",{className:"btn btn-sm",onClick:()=>zn("github"),children:"Disconnect"}))]}),(kn==="not-connected"||kn==="pending")&&t.jsxs("div",{className:"onboarding-github-connect-cta","data-testid":"onboarding-github-connect-cta",children:[D==="github"||Jt?t.jsxs("div",{className:"onboarding-github-connect-actions",children:[t.jsx("button",{className:"btn btn-sm",disabled:!0,children:"Waiting for login…"}),t.jsx("button",{className:"btn btn-sm",onClick:()=>void zt("github"),children:"Cancel"})]}):t.jsxs("button",{className:"btn btn-primary btn-sm",onClick:()=>Qe("github"),children:[t.jsx(Qs,{size:16}),"Connect"]}),(D==="github"||Jt)&&W.github&&t.jsx(Xd,{instructions:W.github,"data-testid":"onboarding-login-instructions-github"})]}),kn==="connected"&&t.jsx("div",{className:"onboarding-github-feedback onboarding-github-feedback--success",children:we?"GitHub CLI is authenticated. Imports and pull request tracking are available. Connect OAuth in Settings → Authentication if you want dashboard-managed sign-in controls.":"GitHub OAuth is connected. You can import issues and track pull requests."}),kn==="failed"&&t.jsxs("div",{className:"onboarding-github-feedback onboarding-github-feedback--error",children:[t.jsx("p",{children:"Connection failed or timed out."}),t.jsxs("div",{className:"onboarding-github-feedback-actions",children:[t.jsx("button",{className:"btn btn-sm",onClick:()=>Qe("github"),children:"Retry"}),t.jsx("button",{className:"onboarding-skip-step-link",onClick:le,children:"Skip for now"})]})]}),kn==="pending"&&t.jsx("div",{className:"onboarding-github-feedback onboarding-github-feedback--info",children:"Waiting for GitHub authorization…"}),kn==="skipped"&&t.jsxs("div",{className:"onboarding-github-feedback onboarding-github-feedback--info",children:[t.jsx("p",{children:"GitHub was skipped. You can connect anytime from Settings → Authentication."}),t.jsx("div",{className:"onboarding-github-feedback-actions",children:t.jsx("button",{className:"btn btn-sm",onClick:()=>Qe("github"),children:"Connect anyway"})})]}),kn==="not-connected"&&t.jsx("p",{className:"onboarding-helper-text",children:"No worries if you're not ready — connect GitHub anytime from Settings → Authentication."})]}):t.jsxs("div",{className:"model-onboarding-github-optional",children:[t.jsx("div",{className:"optional-icon optional-icon--github","aria-hidden":"true",children:t.jsx(On,{provider:"github",size:"lg"})}),we?t.jsx("p",{children:"GitHub CLI is already authenticated, so imports and PR tracking work now. OAuth from the dashboard is optional and only controls dashboard-managed connect/disconnect."}):t.jsx("p",{children:"GitHub OAuth isn't connected yet. You can set it up in Settings → Authentication, or continue now and connect later."}),t.jsxs("div",{className:"model-onboarding-github-optional__actions",children:[t.jsx("button",{className:"btn btn-primary btn-sm",onClick:()=>b("project-setup"),children:we?"Continue with gh CLI auth →":"Continue without GitHub →"}),we&&(D==="github"||Jt?t.jsxs("button",{className:"btn btn-sm",disabled:!0,children:[t.jsx(St,{size:14,className:"onboarding-spinner"}),"Waiting for OAuth login…"]}):t.jsxs("button",{className:"btn btn-sm",onClick:()=>Qe("github"),children:[t.jsx(On,{provider:"github",size:"sm"}),"Connect OAuth (optional)"]}))]}),we&&(D==="github"||Jt)&&W.github&&t.jsx(Xd,{instructions:W.github,"data-testid":"onboarding-login-instructions-github"})]})]}),v==="project-setup"&&t.jsxs("div",{className:"model-onboarding-project-setup",children:[t.jsx("p",{className:"model-onboarding-description",children:"Choose your first project before creating or importing tasks. You can register an existing local directory or clone a GitHub repository URL through the setup wizard."}),En?t.jsx("div",{className:"onboarding-project-ready","data-testid":"onboarding-project-ready",role:"status",children:t.jsx("p",{children:"Project selected — task creation and imports are available."})}):t.jsxs("div",{className:"onboarding-project-prerequisite","data-testid":"onboarding-project-prerequisite",children:[t.jsx("p",{className:"onboarding-helper-text",children:"A project is required before first-task actions are available."}),t.jsx("button",{type:"button",className:"btn btn-primary",onClick:a,"data-testid":"onboarding-open-setup-wizard",children:"Set Up Project"}),t.jsx("p",{className:"onboarding-helper-text",children:"In the setup wizard, pick an existing directory or paste a GitHub clone URL."})]}),t.jsx(li,{summary:"What does project setup do?",children:t.jsx("p",{className:"onboarding-helper-text",children:"Project setup registers a workspace so Fusion knows where to read files, run commands, and track task changes."})})]}),v==="first-task"&&t.jsxs("div",{className:"model-onboarding-first-task",children:[t.jsx("p",{className:"model-onboarding-description",children:"Create your first task to start the board and launch AI execution."}),x&&Kn?t.jsxs("div",{className:"onboarding-task-created",children:[t.jsx(Zn,{size:56,className:"success-icon"}),t.jsx("h3",{className:"onboarding-task-created__title",children:"Your first task is ready!"}),t.jsx("div",{className:"onboarding-task-created__task-id",children:Kn.id}),Ms&&t.jsx("p",{className:"onboarding-task-created__description",children:Ms}),t.jsx("p",{className:"onboarding-task-created__hint",children:"Your task has been created and will appear on the board."}),t.jsxs("div",{className:"onboarding-task-created__actions",children:[t.jsx("button",{type:"button",className:"btn btn-primary",onClick:Lt,children:"View Task"}),t.jsx("button",{type:"button",className:"btn",onClick:fn,children:"Go to Dashboard"})]})]}):t.jsxs(t.Fragment,{children:[En?t.jsxs(t.Fragment,{children:[t.jsxs("div",{className:"onboarding-first-task-form",children:[t.jsx("label",{className:"onboarding-first-task-form__label",htmlFor:"onboarding-first-task-input",children:"Describe your first task"}),t.jsx("textarea",{id:"onboarding-first-task-input",className:"input onboarding-first-task-form__input","data-testid":"onboarding-first-task-input",value:R,onChange:T=>{O(T.target.value),H(null)},placeholder:"Example: Build a login page with email and password",rows:4}),t.jsx("div",{className:"onboarding-first-task-form__actions",children:t.jsx("button",{type:"button",className:"btn btn-primary",onClick:qe,disabled:E,"data-testid":"onboarding-first-task-submit",children:E?t.jsxs(t.Fragment,{children:[t.jsx(St,{size:16,className:"animate-spin"}),t.jsx("span",{children:"Creating task…"})]}):"Create First Task"})})]}),G&&t.jsxs("div",{className:"onboarding-task-error",role:"alert","data-testid":"onboarding-task-error",children:[t.jsx("p",{className:"field-error",children:G}),t.jsx("p",{className:"onboarding-helper-text",children:"Your text has been preserved — fix the issue and try again."})]})]}):t.jsxs("div",{className:"onboarding-project-prerequisite","data-testid":"onboarding-project-prerequisite",children:[t.jsx("p",{className:"onboarding-helper-text",children:"A project must be selected before you can create tasks or import from GitHub."}),t.jsx("button",{type:"button",className:"btn btn-primary",onClick:a,"data-testid":"onboarding-open-setup-wizard",children:"Set Up Project"})]}),t.jsx(ZO,{items:Un}),En&&t.jsxs(t.Fragment,{children:[t.jsx(li,{summary:"What happens when I create a task?",children:t.jsx("p",{className:"onboarding-helper-text",children:"A task describes something you want done. Fusion's AI agents will read your description and work on implementing it. You can track progress on the board and review the results."})}),t.jsxs("div",{className:"onboarding-cta-options",children:[t.jsxs("button",{className:"onboarding-cta-card primary",onClick:z,disabled:X,children:[t.jsx("div",{className:"cta-icon",children:t.jsx(Tn,{size:24})}),t.jsxs("div",{className:"cta-content",children:[t.jsx("strong",{children:"Create a New Task"}),t.jsx("span",{children:"Describe what you need built and AI will work on it"})]})]}),t.jsxs("button",{className:`onboarding-cta-card${qt?"":" onboarding-cta-card--disabled"}`,"data-testid":"cta-github-import",onClick:_e,disabled:X||!qt,children:[t.jsx("div",{className:"cta-icon",children:t.jsx(Qs,{size:24})}),t.jsxs("div",{className:"cta-content",children:[t.jsx("strong",{children:"Import from GitHub"}),t.jsx("span",{children:"Turn GitHub issues into tasks you can track here"}),!qt&&t.jsx("small",{className:"onboarding-cta-note",children:"Requires GitHub connection"})]})]})]}),t.jsxs("p",{className:"onboarding-skip-note",children:["You can create tasks anytime from the board, or use"," ",t.jsx("code",{children:"fn task create"})," in the terminal."]})]})]})]}),v==="complete"&&t.jsxs("div",{className:"model-onboarding-complete",children:[t.jsx(Zn,{size:48,className:"success-icon"}),t.jsx("p",{children:"Setup complete! Head to the board to create your first task, or explore the dashboard to see what's available."})]})]}),t.jsxs("div",{className:"model-onboarding-footer",children:[v==="ai-setup"&&t.jsxs(t.Fragment,{children:[t.jsx("button",{className:"btn btn-sm",onClick:Rt,disabled:X,children:"Skip for now"}),t.jsx("button",{className:"onboarding-skip-step-link",onClick:on,children:"Skip setup →"}),t.jsx("button",{className:"btn btn-primary",onClick:Ht,children:"Next →"})]}),v==="github"&&t.jsxs(t.Fragment,{children:[t.jsx("button",{className:"btn btn-sm",onClick:ae,children:"← Back"}),t.jsx("button",{className:"onboarding-skip-step-link",onClick:on,children:"Skip GitHub →"}),t.jsx("button",{className:"btn btn-primary",onClick:Ht,children:"Next →"})]}),v==="project-setup"&&t.jsxs(t.Fragment,{children:[t.jsx("button",{className:"btn btn-sm",onClick:ae,children:"← Back"}),t.jsx("button",{className:"btn btn-primary",onClick:Ht,disabled:!En,children:"Next →"})]}),v==="first-task"&&!x&&t.jsxs(t.Fragment,{children:[t.jsx("button",{className:"btn btn-sm",onClick:ae,children:"← Back"}),t.jsx("button",{className:"btn btn-primary",onClick:Se,disabled:X,children:X?t.jsxs(t.Fragment,{children:[t.jsx(St,{size:16,className:"animate-spin"}),t.jsx("span",{children:"Saving…"})]}):"Finish Setup"})]}),v==="complete"&&t.jsxs("button",{className:"btn btn-primary",onClick:Ot,children:[t.jsx(Zn,{size:16}),t.jsx("span",{children:"Get Started"})]})]})]})})}function iy({toasts:e}){return t.jsx("div",{className:"toast-container",id:"toasts",children:e.map(n=>t.jsx("div",{className:`toast toast-${n.type}`,children:n.message},n.id))})}const sF=i.lazy(()=>Sn(()=>import("./SetupWizardModal-_IK6hTA7.js"),__vite__mapDeps([13,1,14,15,16,17,5,6,18])).then(e=>({default:e.SetupWizardModal}))),iF=i.lazy(()=>Sn(()=>import("./SettingsModal-CYetgxZj.js"),__vite__mapDeps([19,1,20,21,22,2,5,6,23])).then(e=>({default:e.SettingsModal})));function aF(){(typeof window<"u"&&window.requestIdleCallback||(n=>globalThis.setTimeout(n,200)))(()=>{Sn(()=>import("./SettingsModal-CYetgxZj.js"),__vite__mapDeps([19,1,20,21,22,2,5,6,23]))},{timeout:1500})}function rF({projectId:e,tasks:n,projects:s,currentProject:a,addToast:r,toasts:o,removeToast:l,modalManager:c,projectActions:d,taskHandlers:u,taskOperations:h,deepLink:m,settings:f,onSettingsClose:p,onReopenOnboarding:g}){const[w,v]=i.useState(null),b=c.detailTask?(()=>{const k=n.find(R=>R.id===c.detailTask?.id);return k?"prompt"in c.detailTask?{...c.detailTask,...k,prompt:c.detailTask.prompt,log:c.detailTask.log}:k:c.detailTask})():null,y=p??c.closeSettings,j=i.useCallback(()=>{c.openNewTask()},[c]),S=i.useCallback(()=>{c.openGitHubImport()},[c]),C=i.useCallback(k=>{v(null),c.closeModelOnboarding(),c.openDetailTask(k)},[c]),x=i.useCallback(async k=>{const R=await u.handleModalCreate(k);return c.modelOnboardingOpen&&v(R),R},[u.handleModalCreate,c.modelOnboardingOpen]);return i.useEffect(()=>{!c.modelOnboardingOpen&&w&&v(null)},[c.modelOnboardingOpen,w]),i.useEffect(()=>{aF()},[]),t.jsxs(t.Fragment,{children:[b&&t.jsx(Ia,{children:t.jsx(b$,{task:b,projectId:e,tasks:n,onClose:m.handleDetailClose,onOpenDetail:c.openDetailTask,mobileHeaderMode:c.detailTaskOrigin==="list-mobile"?"back":"close",onMoveTask:h.moveTask,onDeleteTask:h.deleteTask,onMergeTask:h.mergeTask,onRetryTask:h.retryTask,onResetTask:h.resetTask,onDuplicateTask:h.duplicateTask,onTaskUpdated:c.updateDetailTask,addToast:r,prAuthAvailable:f.prAuthAvailable,initialTab:c.detailTaskInitialTab})}),c.settingsOpen&&t.jsx(Ia,{children:t.jsx(i.Suspense,{fallback:null,children:t.jsx(iF,{onClose:y,addToast:r,initialSection:c.settingsInitialSection,projectId:e,themeMode:f.themeMode,colorTheme:f.colorTheme,onThemeModeChange:f.setThemeMode,onColorThemeChange:f.setColorTheme,dashboardFontScalePct:f.dashboardFontScalePct,onDashboardFontScaleChange:f.setDashboardFontScalePct,onReopenOnboarding:g})})}),t.jsx(I4,{isOpen:c.githubImportOpen,onClose:c.closeGitHubImport,onImport:u.handleGitHubImport,tasks:n,projectId:e}),t.jsx(Ia,{children:t.jsx(O4,{isOpen:c.isPlanningOpen,onClose:c.closePlanning,onTaskCreated:u.handlePlanningTaskCreated,onTasksCreated:u.handlePlanningTasksCreated,tasks:n,initialPlan:c.planningInitialPlan??void 0,projectId:e,resumeSessionId:c.planningResumeSessionId})}),t.jsx(Ia,{children:t.jsx(K4,{isOpen:c.isSubtaskOpen,onClose:c.closeSubtask,initialDescription:c.subtaskInitialDescription??"",onTasksCreated:u.handleSubtaskTasksCreated,projectId:e,resumeSessionId:c.subtaskResumeSessionId})}),t.jsx(gD,{isOpen:c.terminalOpen,onClose:c.closeTerminal,initialCommand:c.terminalInitialCommand,projectId:e}),t.jsx(xD,{isOpen:c.scriptsOpen,onClose:c.closeScripts,addToast:r,onRunScript:c.runScript,projectId:e}),c.filesOpen&&t.jsx(BD,{initialWorkspace:c.fileBrowserWorkspace,initialFile:c.fileBrowserInitialFile,isOpen:!0,onClose:c.closeFiles,onWorkspaceChange:c.setFileWorkspace,projectId:e}),c.todosOpen&&t.jsx(HD,{isOpen:!0,onClose:c.closeTodos,addToast:r,projectId:e,onPlanningMode:c.openPlanningWithInitialPlan}),t.jsx(XD,{isOpen:c.usageOpen,onClose:c.closeUsage,projectId:e,anchorRect:c.usageAnchorRect}),t.jsx(_L,{isOpen:c.systemStatsOpen,onClose:c.closeSystemStats,projectId:e}),c.schedulesOpen&&t.jsx(xL,{onClose:c.closeSchedules,addToast:r,projectId:e}),t.jsx(Ia,{children:t.jsx(kL,{isOpen:c.newTaskModalOpen,onClose:c.closeNewTask,tasks:n,onCreateTask:x,addToast:r,projectId:e})}),t.jsx(TL,{isOpen:c.activityLogOpen,onClose:c.closeActivityLog,tasks:n,projectId:e,projects:s,currentProject:a,onOpenTaskDetail:k=>{const R=n.find(O=>O.id===k);R&&c.openDetailTask(R)}}),t.jsx(Ia,{children:t.jsx($L,{isOpen:c.gitManagerOpen,onClose:c.closeGitManager,tasks:n,addToast:r,projectId:e})}),t.jsx(Ia,{children:t.jsx(VL,{isOpen:c.workflowStepsOpen,onClose:c.closeWorkflowSteps,addToast:r,projectId:e})}),t.jsx(rO,{isOpen:c.agentsOpen,onClose:c.closeAgents,addToast:r,projectId:e}),c.setupWizardOpen&&t.jsx(i.Suspense,{fallback:null,children:t.jsx(sF,{onProjectRegistered:d.handleSetupComplete,onClose:c.closeSetupWizard})}),c.modelOnboardingOpen&&t.jsx(nF,{onComplete:d.handleModelOnboardingComplete,addToast:r,projectId:e??"",onOpenSetupWizard:d.handleAddProject,onOpenNewTask:j,onOpenGitHubImport:S,firstCreatedTask:w,onViewTask:C}),t.jsx(iy,{toasts:o,onRemove:l})]})}function oF({errorMessage:e,isRetrying:n,onRetry:s,onManageConnection:a}){return t.jsxs("div",{className:"project-overview-empty",role:"alert","aria-live":"polite",children:[t.jsx("h2",{children:"Can't reach the Fusion backend"}),t.jsx("p",{className:"settings-muted",children:"Fusion couldn't load your projects right now. Please make sure the backend is running and try again."}),t.jsxs("p",{className:"settings-muted",children:["Error: ",e]}),t.jsxs("div",{className:"modal-actions",children:[t.jsx("button",{type:"button",className:"btn btn-primary",onClick:s,disabled:n,children:n?"Retrying…":"Retry Connection"}),a&&t.jsx("button",{type:"button",className:"btn",onClick:a,children:"Manage Connection"})]})]})}const zu=[{id:"projects",label:"Loading projects"},{id:"project",label:"Selecting project"},{id:"tasks",label:"Fetching tasks"}];function lF(e,n){if(n==="ready")return"done";const s=zu.findIndex(r=>r.id===n),a=zu.findIndex(r=>r.id===e);return a<s?"done":a===s?"active":"pending"}function cF({stage:e}){const[n]=i.useState(()=>Ej());return t.jsx("div",{className:"dashboard-loader",role:"status","aria-live":"polite","aria-label":n?"Updating Fusion dashboard":"Loading Fusion dashboard","data-stage":e,"data-version-update":n?"true":void 0,children:t.jsxs("div",{className:"dashboard-loader__content",children:[t.jsx("h1",{className:"dashboard-loader__logo",children:"Fusion"}),n?t.jsx("p",{className:"dashboard-loader__message dashboard-loader__message--update",children:"Updating to a new frontend version..."}):t.jsx("p",{className:"dashboard-loader__message",children:"Initializing dashboard..."}),t.jsx("ol",{className:"dashboard-loader__steps","aria-label":"Dashboard loading progress",children:zu.map(s=>{const a=lF(s.id,e);return t.jsxs("li",{className:`dashboard-loader__step dashboard-loader__step--${a}`,"data-testid":`dashboard-loader-step-${s.id}`,children:[t.jsx("span",{className:"dashboard-loader__step-icon","aria-hidden":"true",children:a==="done"?"✓":a==="active"?t.jsx(St,{className:"dashboard-loader__spinner animate-spin",size:14}):"•"}),t.jsx("span",{className:"dashboard-loader__step-label",children:s.label})]},s.id)})})]})})}const dF=5e3;function uF(e,n,s){return e||n&&s===0?"idle":n&&s>0?"paused":s>0?"running":"idle"}function mF(e,n,s){let a=0,r=0,o=0,l=0,c=0;for(const d of e){switch(d.column){case"in-progress":a++,nc(d,n,s)&&o++;break;case"todo":l++;break;case"in-review":c++;break}d.blockedBy&&d.blockedBy.length>0&&r++}return{runningTaskCount:a,blockedTaskCount:r,stuckTaskCount:o,queuedTaskCount:l,inReviewCount:c}}function hF(e,n,s,a){const[r,o]=i.useState({globalPause:!1,enginePaused:!1,maxConcurrent:2}),[l,c]=i.useState(!0),[d,u]=i.useState(null),h=i.useRef(null),m=i.useRef(null),f=i.useCallback(async()=>{m.current&&m.current.abort(),m.current=new AbortController;try{c(!0),u(null);const v=await V1(n);o(v)}catch(v){if(v instanceof Error&&v.name==="AbortError")return;u(v instanceof Error?v.message:"Failed to fetch executor stats")}finally{c(!1)}},[n]);i.useEffect(()=>(f(),()=>{m.current&&m.current.abort()}),[f]),i.useEffect(()=>(h.current&&clearInterval(h.current),h.current=setInterval(()=>{f()},dF),()=>{h.current&&(clearInterval(h.current),h.current=null)}),[f]);const p=mF(e,s,a),g=uF(r.globalPause,r.enginePaused,p.runningTaskCount);return{stats:{...p,executorState:g,maxConcurrent:r.maxConcurrent,lastActivityAt:r.lastActivityAt},loading:l,error:d,refresh:f}}const pF={planning:Di,subtask:Fa,mission_interview:js,milestone_interview:js,slice_interview:js},fF={planning:"Planning",subtask:"Subtask Breakdown",mission_interview:"Mission Interview",milestone_interview:"Milestone Interview",slice_interview:"Slice Interview"};function gF({sessions:e,generating:n,needsInput:s,onOpenSession:a,onDismissSession:r}){const{confirm:o}=ti(),[l,c]=i.useState(!1),[d,u]=i.useState(new Set),h=i.useRef(null),m=i.useRef(new Map),f=i.useRef(null),{activeTabMap:p}=Gr(),g=i.useMemo(()=>Ya(),[]);if(i.useEffect(()=>{if(!l)return;const b=y=>{h.current&&!h.current.contains(y.target)&&c(!1)};return document.addEventListener("mousedown",b),()=>document.removeEventListener("mousedown",b)},[l]),i.useEffect(()=>{const b=new Set,y=new Map;for(const j of e){const S=p.get(j.id),C=[j.status,j.updatedAt,S?.tabId??j.lockedByTab??"",S?.stale?"stale":"fresh"].join("|"),x=m.current.get(j.id);x&&x!==C&&b.add(j.id),y.set(j.id,C)}if(m.current=y,b.size!==0)return u(b),f.current&&clearTimeout(f.current),f.current=setTimeout(()=>{u(new Set),f.current=null},500),()=>{f.current&&(clearTimeout(f.current),f.current=null)}},[p,e]),e.length===0)return null;const w=e.length,v=s>0;return t.jsxs("div",{ref:h,className:"background-tasks-indicator",children:[t.jsxs("button",{className:`background-tasks-indicator__pill${v?" background-tasks-indicator__pill--attention":""}`,onClick:()=>c(b=>!b),title:`${w} background AI task${w!==1?"s":""}${s>0?` (${s} need${s!==1?"":"s"} input)`:""}`,children:[n>0&&t.jsx(St,{size:12,style:{animation:"spin 1s linear infinite"}}),s>0&&n===0&&t.jsx(au,{size:12}),t.jsxs("span",{children:["AI ",w]})]}),l&&t.jsxs("div",{className:"background-tasks-indicator__popover",children:[t.jsx("div",{className:"background-tasks-indicator__popover-header",children:"Background Tasks"}),t.jsx("div",{className:"background-tasks-indicator__popover-list",children:e.map(b=>{const y=pF[b.type],j=b.status==="generating",S=b.status==="awaiting_input",C=b.status==="error",x=p.get(b.id),k=x?.tabId??b.lockedByTab??null,R=!!(k&&k!==g&&!x?.stale),O=d.has(b.id);return t.jsxs("div",{className:`background-tasks-indicator__item${O?" background-tasks-indicator__item--updated":""}`,style:{transition:"background-color 220ms ease, transform 220ms ease",backgroundColor:O?"var(--color-accent-soft, rgba(59, 130, 246, 0.14))":void 0,transform:O?"translateY(-1px)":void 0},onClick:async()=>{R&&!await o({title:"Open Active Session",message:"This session is active in another tab. Open anyway?"})||(a(b),c(!1))},children:[C?t.jsx(zs,{size:14,className:"background-tasks-indicator__session-icon",style:{color:"var(--color-error)"}}):t.jsx(y,{size:14,className:"background-tasks-indicator__session-icon"}),t.jsxs("div",{className:"background-tasks-indicator__session-content",children:[t.jsx("div",{className:"background-tasks-indicator__session-title",children:b.title}),t.jsxs("div",{className:"background-tasks-indicator__session-meta",children:[C?"Failed":fF[b.type],j&&" — generating...",S&&!R&&" — needs input",S&&R&&" — active in another tab"]})]}),j&&t.jsx(St,{size:14,className:"background-tasks-indicator__session-icon",style:{animation:"spin 1s linear infinite",color:"var(--color-success)"}}),S&&!R&&t.jsx(au,{size:14,className:"background-tasks-indicator__session-icon",style:{color:"var(--triage)"}}),S&&R&&t.jsx(kc,{size:14,className:"background-tasks-indicator__session-icon",style:{color:"var(--text-muted)"}}),t.jsx("button",{className:"background-tasks-indicator__item-dismiss",onClick:E=>{E.stopPropagation(),r(b.id)},title:"Dismiss",children:t.jsx(bn,{size:12})})]},b.id)})})]})]})}function bF(e){if(!e)return"no activity";const n=Date.now(),s=new Date(e).getTime(),a=n-s,r=Math.floor(a/1e3),o=Math.floor(r/60),l=Math.floor(o/60),c=Math.floor(l/24);return c>0?`${c}d ago`:l>0?`${l}h ago`:o>0?`${o}m ago`:r>10?`${r}s ago`:"just now"}function xF(e){switch(e){case"running":return{label:"Running",color:"var(--color-success)",icon:is};case"paused":return{label:"Paused",color:"var(--triage)",icon:di};case"idle":default:return{label:"Idle",color:"var(--text-muted)",icon:as}}}function vF({tasks:e,projectId:n,taskStuckTimeoutMs:s,staleHighFanoutBlockerAgeThresholdMs:a,backgroundSessions:r,backgroundGenerating:o,backgroundNeedsInput:l,onOpenBackgroundSession:c,onDismissBackgroundSession:d,lastFetchTimeMs:u,currentProjectPath:h,onOpenProjectDirectory:m,keyboardOpen:f}){if(f)return null;const{stats:p,loading:g,error:w}=hF(e,n,s,u),[v,b]=i.useState(!1),y=i.useMemo(()=>xF(p.executorState),[p.executorState]),j=i.useMemo(()=>bF(p.lastActivityAt),[p.lastActivityAt]),S=i.useMemo(()=>{const x=rm(e,{staleHighFanoutAgeThresholdMs:a??kb});return Array.from(x.values()).map(R=>R.escalation).filter(R=>!!R).sort((R,O)=>O.activeTodoCount!==R.activeTodoCount?O.activeTodoCount-R.activeTodoCount:O.totalActiveCount!==R.totalActiveCount?O.totalActiveCount-R.totalActiveCount:O.blockingAgeMs!==R.blockingAgeMs?O.blockingAgeMs-R.blockingAgeMs:R.blockerId.localeCompare(O.blockerId,"en",{numeric:!0,sensitivity:"base"}))[0]??null},[e,a]),C=y.icon;return w?t.jsx("div",{className:"executor-status-bar executor-status-bar--error",role:"status","aria-label":"Executor status",children:t.jsxs("span",{className:"executor-status-bar__error",children:[t.jsx(Br,{size:14}),w]})}):g&&p.runningTaskCount===0?t.jsx("div",{className:"executor-status-bar executor-status-bar--loading",role:"status","aria-label":"Executor status",children:t.jsx("span",{className:"executor-status-bar__loading-text",children:"Loading..."})}):t.jsxs("div",{className:`executor-status-bar ${p.executorState==="running"?"executor-status-bar--running":""}`,role:"status","aria-label":"Executor status",children:[r&&r.length>0&&c&&d&&t.jsxs(t.Fragment,{children:[t.jsx(gF,{sessions:r,generating:o??0,needsInput:l??0,onOpenSession:c,onDismissSession:d}),t.jsx("span",{className:"executor-status-bar__divider","aria-hidden":"true"})]}),t.jsxs("div",{className:"executor-status-bar__segment",children:[t.jsx("span",{className:"executor-status-bar__indicator executor-status-bar__indicator--queued","aria-hidden":"true"}),t.jsx("span",{className:"executor-status-bar__label",children:"Queued"}),t.jsx("span",{className:"executor-status-bar__count",children:p.queuedTaskCount})]}),t.jsx("span",{className:"executor-status-bar__divider","aria-hidden":"true"}),t.jsxs("div",{className:"executor-status-bar__segment",children:[t.jsx("span",{className:`executor-status-bar__indicator executor-status-bar__indicator--running ${p.runningTaskCount>0?"executor-status-bar__indicator--active":""}`,"aria-hidden":"true"}),t.jsx("span",{className:"executor-status-bar__label",children:"Running"}),t.jsx("span",{className:"executor-status-bar__count",children:p.runningTaskCount}),t.jsx("span",{className:"executor-status-bar__separator","aria-hidden":"true",children:"/"}),t.jsx("span",{className:"executor-status-bar__max",children:p.maxConcurrent})]}),t.jsx("span",{className:"executor-status-bar__divider","aria-hidden":"true"}),p.stuckTaskCount>0&&t.jsxs(t.Fragment,{children:[t.jsxs("div",{className:"executor-status-bar__segment executor-status-bar__segment--stuck",children:[t.jsx("span",{className:"executor-status-bar__indicator executor-status-bar__indicator--stuck executor-status-bar__indicator--active","aria-hidden":"true"}),t.jsx("span",{className:"executor-status-bar__label",children:"Stuck"}),t.jsx("span",{className:"executor-status-bar__count executor-status-bar__count--error",children:p.stuckTaskCount})]}),t.jsx("span",{className:"executor-status-bar__divider","aria-hidden":"true"})]}),t.jsxs("div",{className:"executor-status-bar__segment",children:[t.jsx("span",{className:`executor-status-bar__indicator executor-status-bar__indicator--blocked ${p.blockedTaskCount>0?"executor-status-bar__indicator--active":""}`,"aria-hidden":"true"}),t.jsx("span",{className:"executor-status-bar__label",children:"Blocked"}),t.jsx("span",{className:`executor-status-bar__count ${p.blockedTaskCount>0?"executor-status-bar__count--warning":""}`,children:p.blockedTaskCount})]}),t.jsx("span",{className:"executor-status-bar__divider","aria-hidden":"true"}),t.jsxs("div",{className:"executor-status-bar__segment",children:[t.jsx("span",{className:"executor-status-bar__indicator executor-status-bar__indicator--review","aria-hidden":"true"}),t.jsx("span",{className:"executor-status-bar__label",children:"In Review"}),t.jsx("span",{className:"executor-status-bar__count",children:p.inReviewCount})]}),S&&t.jsxs(t.Fragment,{children:[t.jsx("span",{className:"executor-status-bar__divider","aria-hidden":"true"}),t.jsxs("div",{className:"executor-status-bar__segment executor-status-bar__segment--fanout",children:[t.jsx("span",{className:"executor-status-bar__indicator executor-status-bar__indicator--fanout executor-status-bar__indicator--active","aria-hidden":"true"}),t.jsx("span",{className:"executor-status-bar__label",children:"Escalated"}),t.jsxs("span",{className:"executor-status-bar__fanout-summary",title:`Escalated blocker ${S.blockerId}: ${S.activeTodoCount} todo waiting (threshold ${Ju}), ${S.totalActiveCount} active total`,children:[S.blockerId," · ",S.activeTodoCount," todo"]})]})]}),h&&m&&t.jsxs(t.Fragment,{children:[t.jsx("span",{className:"executor-status-bar__divider","aria-hidden":"true"}),t.jsxs("div",{className:"executor-status-bar__segment executor-status-bar__segment--project-directory",children:[t.jsx("button",{className:`executor-status-bar__folder-toggle${v?" executor-status-bar__folder-toggle--active":""}`,onClick:()=>b(x=>!x),"aria-label":v?"Hide project directory":"Show project directory","aria-expanded":v,"data-testid":"executor-project-path-toggle",title:v?"Hide project directory":"Show project directory",children:t.jsx(ws,{size:12,"aria-hidden":"true"})}),v&&t.jsx("button",{className:"executor-status-bar__project-path",onClick:m,title:h,"data-testid":"executor-project-path-link",children:h})]})]}),t.jsx("div",{className:"executor-status-bar__spacer"}),t.jsxs("div",{className:"executor-status-bar__segment executor-status-bar__segment--time",children:[t.jsx(Yi,{size:12,className:"executor-status-bar__icon","aria-hidden":"true"}),t.jsx("span",{className:"executor-status-bar__time",children:j})]}),t.jsx("span",{className:"executor-status-bar__divider","aria-hidden":"true"}),t.jsxs("div",{className:"executor-status-bar__segment",children:[t.jsx(C,{size:12,style:{color:y.color},"aria-hidden":"true"}),t.jsx("span",{className:"executor-status-bar__state",style:{color:y.color},children:y.label})]})]})}const yF={planning:Di,subtask:Fa,mission_interview:js,milestone_interview:js,slice_interview:js},wF={planning:"Planning",subtask:"Subtask Breakdown",mission_interview:"Mission Interview",milestone_interview:"Milestone Interview",slice_interview:"Slice Interview"},ay="fusion:session-banner-dismissed";function Eo(e){if(!e)return 0;const n=Date.parse(e);return Number.isFinite(n)?n:0}function kF(){if(typeof window>"u")return new Map;try{const e=window.localStorage.getItem(ay);if(!e)return new Map;const n=JSON.parse(e),s=new Map;for(const[a,r]of Object.entries(n)){const o=typeof r=="number"?r:Eo(r);s.set(a,o)}return s}catch{return new Map}}function jF(e){if(!(typeof window>"u"))try{const n={};for(const[s,a]of e)n[s]=a;window.localStorage.setItem(ay,JSON.stringify(n))}catch{}}const Wi=kF();function NF({sessions:e,onResumeSession:n,onDismissSession:s,onDismissAll:a}){const[r,o]=i.useState(0),l=()=>{jF(Wi),o(g=>g+1)};i.useEffect(()=>{if(Wi.size===0)return;const g=new Map(e.map(v=>[v.id,v]));let w=!1;for(const[v,b]of Wi){const y=g.get(v);if(!y)continue;if(!(y.status==="awaiting_input"||y.status==="error")){Wi.delete(v),w=!0;continue}Eo(y.updatedAt)>b&&(Wi.delete(v),w=!0)}w&&l()},[e]);const c=i.useMemo(()=>e.filter(g=>{if(g.status!=="awaiting_input"&&g.status!=="error")return!1;const w=Wi.get(g.id);return w===void 0?!0:Eo(g.updatedAt)>w}),[e,r]);if(c.length===0)return null;const d=c.filter(g=>g.status==="awaiting_input").length,u=c.filter(g=>g.status==="error").length;let h="";d>0&&u>0?h=`${d} AI session${d===1?"":"s"} need${d===1?"s":""} your input, ${u} failed`:d>0?h=`${d} AI session${d===1?"":"s"} need${d===1?"s":""} your input`:u>0&&(h=`${u} AI session${u===1?"":"s"} failed`);const m=g=>{Wi.set(g.id,Math.max(Eo(g.updatedAt),Date.now())),l()},f=g=>{Wi.delete(g.id),l(),n(g)},p=()=>{const g=Date.now();for(const w of c)Wi.set(w.id,Math.max(Eo(w.updatedAt),g));l(),a()};return t.jsxs("section",{className:"session-notification-banner",role:"region","aria-live":"polite","aria-label":"AI sessions needing input or failed",children:[t.jsxs("div",{className:"session-notification-banner__header",children:[t.jsxs("div",{className:"session-notification-banner__headline",children:[t.jsx(zs,{size:16,"aria-hidden":"true"}),t.jsx("span",{children:h})]}),t.jsxs("button",{className:"session-notification-banner__dismiss-all",onClick:p,children:[t.jsx(bn,{size:14,"aria-hidden":"true"}),t.jsx("span",{children:"Dismiss all"})]})]}),t.jsx("div",{className:"session-notification-banner__list",children:c.map(g=>{const w=yF[g.type],v=g.status==="error";return t.jsxs("article",{className:`session-notification-banner__item${v?" session-notification-banner__item--error":""}`,"data-session-type":g.type,"data-session-status":g.status,children:[t.jsxs("div",{className:"session-notification-banner__item-main",children:[v?t.jsx(zs,{size:16,className:"session-notification-banner__type-icon session-notification-banner__type-icon--error","aria-hidden":"true"}):t.jsx(w,{size:16,className:"session-notification-banner__type-icon","aria-hidden":"true"}),t.jsxs("div",{className:"session-notification-banner__text",children:[t.jsx("p",{className:"session-notification-banner__title",title:g.title,children:g.title}),t.jsx("p",{className:"session-notification-banner__meta",children:v?"Failed":wF[g.type]})]})]}),t.jsxs("div",{className:"session-notification-banner__actions",children:[t.jsx("button",{className:"session-notification-banner__resume",onClick:()=>f(g),children:v?"Retry":"Resume"}),t.jsx("button",{className:"session-notification-banner__dismiss",onClick:()=>{m(g),s(g.id)},"aria-label":`Dismiss ${g.title}`,children:t.jsx(bn,{size:14,"aria-hidden":"true"})})]})]},g.id)})})]})}const ry="fusion:cli-binary-banner-dismissed";function SF(){if(typeof window>"u")return!1;try{return window.localStorage.getItem(ry)==="1"}catch{return!1}}function CF(){if(!(typeof window>"u"))try{window.localStorage.setItem(ry,"1")}catch{}}function EF({onOpenSettings:e}){const[n,s]=i.useState(null),[a,r]=i.useState(()=>SF()),[o,l]=i.useState(!1),[c,d]=i.useState(null);i.useEffect(()=>{if(a)return;let y=!1;return ON().then(j=>{y||s(j)}).catch(()=>{}),()=>{y=!0}},[a]);const u=i.useCallback(async()=>{l(!0),d(null);try{const y=await FN();s({binary:y.binary,expectedVersion:y.expectedVersion,state:y.state,install:y.install}),y.installResult.success||d(y.installResult.permissionsHint||y.installResult.stderr||`Install failed (exit ${y.installResult.exitCode??"n/a"})`)}catch(y){d(y instanceof Error?y.message:String(y))}finally{l(!1)}},[]),h=i.useCallback(()=>{CF(),r(!0)},[]);if(a||!n||n.state==="installed"||n.state==="skipped")return null;const m=n.state==="version-mismatch",f=n.binary.version,p=n.expectedVersion,g=m?"Update the Fusion CLI":"Install the Fusion CLI",w=m?t.jsxs(t.Fragment,{children:["Your installed ",t.jsx("code",{children:"fn"}),"/",t.jsx("code",{children:"fusion"})," CLI is"," ",t.jsxs("strong",{children:["v",f??"unknown"]})," but this dashboard expects"," ",t.jsxs("strong",{children:["v",p]}),". Update to stay in sync."]}):t.jsxs(t.Fragment,{children:["Get the ",t.jsx("code",{children:"fn"})," and ",t.jsx("code",{children:"fusion"})," commands on your terminal so you can drive Fusion from anywhere. One click below or copy the command into your shell."]}),v=m?"Update with npm":"Install with npm",b=m?"Updating…":"Installing…";return t.jsxs("div",{className:"cli-binary-banner",role:"status",children:[t.jsxs("div",{className:"cli-binary-banner__body",children:[t.jsx("div",{className:"cli-binary-banner__title",children:g}),t.jsx("div",{className:"cli-binary-banner__text",children:w}),t.jsxs("div",{className:"cli-binary-banner__actions",children:[t.jsx("button",{type:"button",className:"cli-binary-banner__primary",onClick:()=>void u(),disabled:o,children:o?b:v}),t.jsx("button",{type:"button",className:"cli-binary-banner__secondary",onClick:e,children:"Open Settings"})]}),c&&t.jsx("div",{className:"cli-binary-banner__error",children:c})]}),t.jsx("button",{type:"button",className:"cli-binary-banner__dismiss","aria-label":"Dismiss",onClick:h,children:t.jsx(bn,{size:16})})]})}function _F({signal:e,onDismiss:n}){return!e||!e.atRisk?null:t.jsxs("div",{className:`capacity-risk-banner${n?" capacity-risk-banner--dismissible":""}`,role:"status","aria-live":"polite",children:[t.jsxs("div",{className:"capacity-risk-banner__content",children:[t.jsx("strong",{children:"Capacity risk:"})," Todo ",e.todoCount," (threshold ",e.threshold,") · In Progress ",e.inProgressCount," · In Review ",e.inReviewCount," · Idle agents ",e.idleNonEphemeralAgentCount]}),n?t.jsx("button",{type:"button",className:"capacity-risk-banner__dismiss touch-target","aria-label":"Dismiss capacity warning",onClick:n,children:t.jsx(bn,{"aria-hidden":"true"})}):null]})}const MF={duplicate_active_id:"Duplicate active task ID",id_in_active_and_archived:"Task ID present in active and archived storage",next_sequence_at_or_below_used:"Allocator next sequence overlaps an existing task ID",task_row_outside_known_prefix:"Task row uses a prefix outside allocator state"};function AF(e){return e.length<=5?e.join(", "):`${e.slice(0,5).join(", ")} +${e.length-5} more`}function RF({report:e,recommendedAction:n,onRefresh:s}){const[a,r]=i.useState(!1),[o,l]=i.useState(null);if(e.status!=="anomaly")return null;const c=async()=>{r(!0),l(null);try{const d=await dN();s?.(d.taskIdIntegrity,d.taskIdIntegrity.recommendedAction)}catch(d){l(d instanceof Error?d.message:"Failed to refresh integrity status.")}finally{r(!1)}};return t.jsxs("section",{className:"task-id-integrity-banner",role:"alert","aria-live":"assertive",children:[t.jsxs("div",{className:"task-id-integrity-banner__header",children:[t.jsxs("div",{className:"task-id-integrity-banner__headline-wrap",children:[t.jsx("span",{className:"status-dot status-dot--error","aria-hidden":"true"}),t.jsx(Br,{"aria-hidden":"true"}),t.jsx("h2",{className:"task-id-integrity-banner__headline",children:"Task ID integrity anomaly detected"})]}),t.jsxs("button",{type:"button",className:"btn btn-sm task-id-integrity-banner__refresh",onClick:()=>{c()},disabled:a,children:[t.jsx(us,{className:a?"task-id-integrity-banner__refresh-icon task-id-integrity-banner__refresh-icon--spinning":"task-id-integrity-banner__refresh-icon","aria-hidden":"true"}),a?"Re-checking…":"Re-check"]})]}),t.jsx("p",{className:"task-id-integrity-banner__body",children:"Fusion found allocator state that can cause task IDs to be reused or overwrite live task records."}),t.jsx("ul",{className:"task-id-integrity-banner__list",children:e.anomalies.map(d=>t.jsxs("li",{className:"task-id-integrity-banner__item",children:[t.jsx("strong",{className:"task-id-integrity-banner__item-title",children:MF[d.kind]}),t.jsx("span",{className:"task-id-integrity-banner__item-detail",children:d.details}),t.jsx("code",{className:"task-id-integrity-banner__ids",children:AF(d.affectedIds)})]},`${d.kind}:${d.prefix}:${d.affectedIds.join(",")}`))}),t.jsx("p",{className:"task-id-integrity-banner__footer",children:n}),o?t.jsx("p",{className:"task-id-integrity-banner__error",children:o}):null]})}function IF({latestVersion:e,currentVersion:n,onDismiss:s}){return t.jsxs("div",{className:"update-available-banner",role:"status","aria-live":"polite",children:[t.jsxs("p",{className:"update-available-banner__text",children:["Update available: v",e," (current: v",n,"). Run ",t.jsx("code",{children:"fn update"})," for an installed CLI, or pull this source checkout."," ",t.jsx("a",{className:"update-available-banner__link",href:"https://github.com/Runfusion/Fusion/blob/main/CHANGELOG.md",target:"_blank",rel:"noreferrer",children:"Release notes"})," ","·"," ",t.jsx("a",{className:"update-available-banner__link",href:"https://runfusion.ai",target:"_blank",rel:"noreferrer",children:"Learn more"})]}),t.jsx("button",{type:"button",className:"update-available-banner__dismiss touch-target","aria-label":"Dismiss update notice",onClick:s,children:t.jsx(bn,{size:16,"aria-hidden":"true"})})]})}function TF({pendingCount:e,onOpenMailbox:n,onDismiss:s}){const a=e===1?"request":"requests";return t.jsx("section",{className:"approval-notification-banner",role:"region","aria-live":"polite","aria-label":"Approval requests",children:t.jsxs("div",{className:"approval-notification-banner__content",children:[t.jsxs("div",{className:"approval-notification-banner__headline",children:[t.jsx("span",{className:"status-dot","aria-hidden":"true"}),t.jsx(Br,{"aria-hidden":"true"}),t.jsxs("span",{children:[e," approval ",a," need your attention"]})]}),t.jsxs("div",{className:"approval-notification-banner__actions",children:[t.jsxs("button",{type:"button",className:"btn btn-sm",onClick:n,children:[t.jsx(ma,{"aria-hidden":"true"}),t.jsx("span",{children:"Open Mailbox"})]}),t.jsx("button",{type:"button",className:"btn-icon approval-notification-banner__dismiss",onClick:s,"aria-label":"Dismiss approval notification banner",children:t.jsx(bn,{"aria-hidden":"true"})})]})]})})}function PF({onResume:e}){const n=RO();if(!n)return null;const s=n.completedSteps.length,a=ua.length,r=s>0?`${s} of ${a} step${s!==1?"s":""} complete — You're on the `:"You're on the ";return t.jsxs("section",{className:"onboarding-resume-card",role:"region","aria-label":"Resume onboarding",children:[t.jsxs("div",{className:"onboarding-resume-card__main",children:[t.jsx("div",{className:"onboarding-resume-card__icon","aria-hidden":"true",children:t.jsx(cs,{size:20})}),t.jsxs("div",{className:"onboarding-resume-card__content",children:[t.jsx("h2",{className:"onboarding-resume-card__title",children:"Continue Setup"}),t.jsxs("p",{className:"onboarding-resume-card__description",children:[r,t.jsx("strong",{children:n.label})," step. Continue where you left off to complete your dashboard setup."]})]})]}),t.jsx("div",{className:"onboarding-resume-card__actions",children:t.jsxs("button",{className:"onboarding-resume-card__resume-btn btn btn-primary btn-sm",onClick:()=>{oi("onboarding:resumed",{source:"resume-card",resumedFromStep:n.currentStep}),e()},children:[t.jsx(is,{size:14,"aria-hidden":"true"}),t.jsx("span",{children:"Continue onboarding"})]})})]})}function $F({onOpenSettings:e,onOpenModelOnboarding:n}){const s=Lr(),a=ey(),[r,o]=i.useState(!0),[l,c]=i.useState(!1),[d,u]=i.useState(!1),[h,m]=i.useState({needsAiProvider:!1,needsDefaultModel:!1,needsGitHub:!1});i.useEffect(()=>{if(!s||a){o(!1);return}let b=!1;return(async()=>{try{o(!0),c(!1);const[j,S]=await Promise.all([Do(),Qi()]);if(b)return;const C=j.providers??[],x=C.find(_=>_.id==="github"),R=!C.some(_=>_.id!=="github"&&_.authenticated),O=!S.defaultProvider&&!S.defaultModelId,E=x?!x.authenticated:!1;m({needsAiProvider:R,needsDefaultModel:O,needsGitHub:E})}catch{b||c(!0)}finally{b||o(!1)}})(),()=>{b=!0}},[s,a]);const f=i.useCallback(()=>{MO(),u(!0)},[]),p=i.useCallback(()=>{n()},[n]),g=i.useCallback(()=>{e("global-models")},[e]),w=i.useCallback(()=>{e("authentication")},[e]),v=i.useMemo(()=>{const b=[];return h.needsAiProvider&&b.push({id:"ai-provider",title:"Connect AI Provider",description:"Connect an AI provider to enable AI agents for task planning and code generation",actionLabel:"Set Up AI",onAction:p,icon:as}),h.needsDefaultModel&&b.push({id:"default-model",title:"Select Default Model",description:"Choose a default AI model for task execution",actionLabel:"Choose Model",onAction:g,icon:hb}),h.needsGitHub&&b.push({id:"github",title:"Connect GitHub",description:"Connect GitHub to import issues and track pull requests",actionLabel:"Connect GitHub",onAction:w,icon:Qs}),b},[h.needsAiProvider,h.needsDefaultModel,h.needsGitHub,w,g,p]);return!s||a||d||r||l||v.length===0?null:t.jsxs("section",{className:"post-onboarding-recommendations",role:"region","aria-label":"Setup recommendations",children:[t.jsxs("div",{className:"post-onboarding-recommendations__main",children:[t.jsx("div",{className:"post-onboarding-recommendations__icon","aria-hidden":"true",children:t.jsx(Di,{size:18,"aria-hidden":!0})}),t.jsxs("div",{className:"post-onboarding-recommendations__content",children:[t.jsx("h2",{className:"post-onboarding-recommendations__title",children:"Recommended Next Steps"}),t.jsx("p",{className:"post-onboarding-recommendations__description",children:"Complete these setup items to get the most out of Fusion."}),t.jsx("ul",{className:"post-onboarding-recommendations__list",children:v.map(b=>{const y=b.icon;return t.jsxs("li",{className:"post-onboarding-recommendations__item",children:[t.jsx("span",{className:"post-onboarding-recommendations__item-icon","aria-hidden":"true",children:t.jsx(y,{size:14,"aria-hidden":!0})}),t.jsxs("span",{className:"post-onboarding-recommendations__item-text",children:[t.jsx("strong",{children:b.title}),t.jsx("span",{children:b.description})]}),t.jsx("button",{type:"button",className:"btn btn-sm btn-primary",onClick:b.onAction,children:b.actionLabel})]},b.id)})}),t.jsx(pa,{slotId:"post-onboarding-recommendation",renderPlaceholder:!1,actions:{openSettingsSection:e,openModelOnboarding:n}})]})]}),t.jsx("button",{type:"button",className:"post-onboarding-recommendations__dismiss",onClick:f,"aria-label":"Dismiss recommendations",children:t.jsx(bn,{size:16,"aria-hidden":!0})})]})}function DF({size:e=20}){return t.jsx("svg",{width:e,height:e,viewBox:"0 0 24 24",fill:"currentColor","aria-hidden":"true",children:t.jsx("path",{d:"M12 2C6.477 2 2 6.484 2 12.017c0 4.425 2.865 8.18 6.839 9.504.5.092.682-.217.682-.483 0-.237-.008-.868-.013-1.703-2.782.605-3.369-1.343-3.369-1.343-.454-1.158-1.11-1.466-1.11-1.466-.908-.62.069-.608.069-.608 1.003.07 1.531 1.032 1.531 1.032.892 1.53 2.341 1.088 2.91.832.092-.647.35-1.088.636-1.338-2.22-.253-4.555-1.113-4.555-4.951 0-1.093.39-1.988 1.029-2.688-.103-.253-.446-1.272.098-2.65 0 0 .84-.27 2.75 1.026A9.564 9.564 0 0112 6.844c.85.004 1.705.115 2.504.337 1.909-1.296 2.747-1.027 2.747-1.027.546 1.379.203 2.398.1 2.651.64.7 1.028 1.595 1.028 2.688 0 3.848-2.339 4.695-4.566 4.942.359.309.678.92.678 1.855 0 1.338-.012 2.419-.012 2.747 0 .268.18.58.688.482A10.019 10.019 0 0022 12.017C22 6.484 17.522 2 12 2z"})})}function go(e){return e>99?"99+":String(e)}function LF({view:e,onChangeView:n,footerVisible:s,modalOpen:a=!1,keyboardOpen:r=!1,onOpenSettings:o,onOpenActivityLog:l,onOpenSystemStats:c,onOpenMailbox:d,mailboxUnreadCount:u=0,mailboxPendingApprovalCount:h=0,chatHasUnreadResponse:m=!1,stashOrphanCount:f=0,onOpenGitManager:p,onOpenWorkflowSteps:g,onOpenSchedules:w,onOpenScripts:v,onToggleTerminal:b,onOpenFiles:y,onOpenTodos:j,todosOpen:S=!1,onOpenGitHubImport:C,onOpenPlanning:x,onResumePlanning:k,activePlanningSessionCount:R=0,onOpenUsage:O,onRunScript:E,projectId:_,onViewAllProjects:G,showSkillsTab:H,experimentalFeatures:A,onOpenNodes:P,pluginDashboardViews:q=[],shellConnectionControl:Y}){const ge=ei(),[L,M]=i.useState(!1),[$,D]=i.useState(!1),[N,W]=i.useState({}),[de,me]=i.useState(!1),Ne=i.useMemo(()=>Object.entries(N).sort(([se],[Ve])=>se.localeCompare(Ve)),[N]);i.useEffect(()=>{if(!$)return;let se=!1;return me(!0),Lo(_).then(Ve=>{se||W(Ve)}).catch(()=>{se||W({})}).finally(()=>{se||me(!1)}),()=>{se=!0}},[$,_]);const ve=i.useCallback(()=>M(!1),[]),Me=i.useCallback(se=>{ve(),se?.()},[ve]);if(i.useEffect(()=>{if(!L)return;const se=Ve=>{Ve.key==="Escape"&&M(!1)};return document.addEventListener("keydown",se),()=>document.removeEventListener("keydown",se)},[L]),ge!=="mobile"||a||r)return null;const ie=R>0&&k?k:x,ye=!!H,Z=!!A?.todoView,fe=ye,Q=ye&&!fe,re=q.filter(se=>se.view.placement==="primary").sort((se,Ve)=>(se.view.order??Number.MAX_SAFE_INTEGER)-(Ve.view.order??Number.MAX_SAFE_INTEGER)).slice(0,1),U=new Set(re.map(se=>`${se.pluginId}:${se.view.viewId}`)),be=q.filter(se=>!U.has(`${se.pluginId}:${se.view.viewId}`)).sort((se,Ve)=>(se.view.order??Number.MAX_SAFE_INTEGER)-(Ve.view.order??Number.MAX_SAFE_INTEGER)),Ue=e==="documents"||!!A?.evalsView&&e==="evals"||e==="research"||e==="insights"||e==="memory"||e==="devserver"||e==="dev-server"||S&&Z||e==="skills"&&!fe||e==="graph"||e==="stash-recovery"||kr(e)&&!re.some(se=>Mo(se.pluginId,se.view.viewId)===e);return t.jsxs(t.Fragment,{children:[t.jsxs("nav",{className:`mobile-nav-bar${s?" mobile-nav-bar--with-footer":""}`,role:"tablist","aria-label":"Primary navigation",children:[t.jsxs("button",{type:"button",className:`mobile-nav-tab${e==="board"||e==="list"?" mobile-nav-tab--active":""}`,"data-testid":"mobile-nav-tab-tasks",role:"tab","aria-selected":e==="board"||e==="list",onClick:()=>{n(e==="board"||e==="list"?e:"board")},children:[t.jsx(va,{}),t.jsx("span",{className:"mobile-nav-tab-label",children:"Tasks"})]}),t.jsxs("button",{type:"button",className:`mobile-nav-tab${e==="agents"?" mobile-nav-tab--active":""}`,"data-testid":"mobile-nav-tab-agents",role:"tab","aria-selected":e==="agents",onClick:()=>n("agents"),children:[t.jsx(Xn,{}),t.jsx("span",{className:"mobile-nav-tab-label",children:"Agents"})]}),t.jsxs("button",{type:"button",className:`mobile-nav-tab${e==="missions"?" mobile-nav-tab--active":""}`,"data-testid":"mobile-nav-tab-missions",role:"tab","aria-selected":e==="missions",onClick:()=>n("missions"),children:[t.jsx(js,{}),t.jsx("span",{className:"mobile-nav-tab-label",children:"Missions"})]}),t.jsxs("button",{type:"button",className:`mobile-nav-tab${e==="chat"?" mobile-nav-tab--active":""}`,"data-testid":"mobile-nav-tab-chat",role:"tab","aria-selected":e==="chat",onClick:()=>n("chat"),children:[t.jsxs("span",{className:"mobile-nav-tab-icon-wrapper",children:[t.jsx(Ki,{}),m&&e!=="chat"&&t.jsx("span",{className:"status-dot status-dot--pending mobile-nav-chat-unread-dot","aria-label":"Unread chat response"})]}),t.jsx("span",{className:"mobile-nav-tab-label",children:"Chat"})]}),t.jsxs("button",{type:"button",className:`mobile-nav-tab${e==="mailbox"?" mobile-nav-tab--active":""}`,"data-testid":"mobile-nav-tab-mailbox",role:"tab","aria-selected":e==="mailbox",onClick:()=>n("mailbox"),children:[t.jsxs("span",{className:"mobile-nav-tab-icon-wrapper",children:[t.jsx(za,{}),h>0&&e!=="mailbox"&&t.jsx("span",{className:"status-dot status-dot--pending mobile-nav-chat-unread-dot","aria-label":"Pending approvals"})]}),t.jsx("span",{className:"mobile-nav-tab-label",children:"Mailbox"}),u>0&&t.jsx("span",{className:"mobile-nav-tab-badge",children:go(u)})]}),fe&&t.jsxs("button",{type:"button",className:`mobile-nav-tab${e==="skills"?" mobile-nav-tab--active":""}`,"data-testid":"mobile-nav-tab-skills",role:"tab","aria-selected":e==="skills",onClick:()=>n("skills"),children:[t.jsx(as,{}),t.jsx("span",{className:"mobile-nav-tab-label",children:"Skills"})]}),re.map(se=>{const Ve=Mo(se.pluginId,se.view.viewId),Le=tc(se.view.icon);return t.jsxs("button",{type:"button",className:`mobile-nav-tab${e===Ve||e==="graph"&&se.pluginId==="fusion-plugin-dependency-graph"&&se.view.viewId==="graph"?" mobile-nav-tab--active":""}`,"data-testid":`mobile-nav-tab-plugin-${se.pluginId}-${se.view.viewId}`,role:"tab","aria-selected":e===Ve||e==="graph"&&se.pluginId==="fusion-plugin-dependency-graph"&&se.view.viewId==="graph",onClick:()=>n(se.pluginId==="fusion-plugin-dependency-graph"&&se.view.viewId==="graph"?"graph":Ve),children:[t.jsx(Le,{}),t.jsx("span",{className:"mobile-nav-tab-label",children:se.view.label})]},`${se.pluginId}:${se.view.viewId}`)}),t.jsxs("button",{type:"button",className:`mobile-nav-tab${Ue?" mobile-nav-tab--active":""}`,"data-testid":"mobile-nav-tab-more",role:"tab","aria-selected":!1,onClick:()=>M(se=>!se),children:[t.jsx(ru,{}),t.jsx("span",{className:"mobile-nav-tab-label",children:"More"})]})]}),L&&t.jsxs(t.Fragment,{children:[t.jsx("div",{className:"mobile-more-sheet-backdrop",onClick:ve}),t.jsxs("div",{className:"mobile-more-sheet",children:[t.jsx("div",{className:"mobile-more-sheet-handle"}),t.jsx("div",{className:"mobile-more-sheet-title",children:"Navigate"}),Y?t.jsx("div",{className:"mobile-more-shell-connection","data-testid":"mobile-more-shell-connection",children:Y}):null,t.jsxs("button",{type:"button",className:"mobile-more-item","data-testid":"mobile-more-item-mailbox",onClick:()=>Me(d),children:[t.jsx(za,{}),t.jsx("span",{children:"Mailbox"}),u>0&&t.jsx("span",{className:"mobile-more-item-badge mobile-more-item-badge--unread",children:go(u)}),h>0&&t.jsx("span",{className:"mobile-more-item-badge",children:go(h)})]}),t.jsxs("button",{type:"button",className:"mobile-more-item","data-testid":"mobile-more-item-activity",onClick:()=>Me(l),children:[t.jsx(Vs,{}),t.jsx("span",{children:"Activity Log"})]}),t.jsxs("button",{type:"button",className:"mobile-more-item","data-testid":"mobile-more-item-system-stats",onClick:()=>Me(c),children:[t.jsx(Er,{}),t.jsx("span",{children:"System Stats"})]}),t.jsxs("button",{type:"button",className:"mobile-more-item","data-testid":"mobile-more-item-git",onClick:()=>Me(p),children:[t.jsx(Is,{}),t.jsx("span",{children:"Git Manager"})]}),t.jsxs("div",{className:"mobile-more-split-row",children:[t.jsxs("button",{type:"button",className:"mobile-more-item mobile-more-split-primary","data-testid":"mobile-more-item-terminal",onClick:()=>Me(b),children:[t.jsx(Ji,{}),t.jsx("span",{children:"Terminal"})]}),t.jsx("button",{type:"button",className:"mobile-more-split-toggle","data-testid":"mobile-more-terminal-split-toggle",onClick:()=>D(se=>!se),"aria-expanded":$,"aria-haspopup":"menu","aria-label":"Show scripts",children:t.jsx(Wn,{size:14,className:`mobile-more-chevron${$?" mobile-more-chevron--open":""}`})})]}),$&&t.jsx("div",{className:"mobile-more-submenu",role:"menu","aria-label":"Scripts submenu",children:de?t.jsxs("div",{className:"mobile-more-submenu-loading","data-testid":"mobile-more-scripts-loading",children:[t.jsx(St,{className:"animate-spin"}),t.jsx("span",{children:"Loading scripts…"})]}):Ne.length>0?t.jsxs(t.Fragment,{children:[Ne.map(([se,Ve])=>t.jsxs("button",{type:"button",className:"mobile-more-item mobile-more-subitem","data-testid":`mobile-more-script-item-${se}`,onClick:()=>{E&&E(se,Ve),ve(),D(!1)},children:[t.jsx(is,{}),t.jsx("span",{children:se})]},se)),v&&t.jsxs("button",{type:"button",className:"mobile-more-item mobile-more-subitem mobile-more-subitem--manage","data-testid":"mobile-more-scripts-manage",onClick:()=>{ve(),D(!1),v()},children:[t.jsx(ki,{}),t.jsx("span",{children:"Manage Scripts…"})]})]}):v&&t.jsxs("button",{type:"button",className:"mobile-more-item mobile-more-subitem","data-testid":"mobile-more-scripts-manage",onClick:()=>{ve(),D(!1),v()},children:[t.jsx(ki,{}),t.jsx("span",{children:"No scripts — add one…"})]})}),t.jsxs("button",{type:"button",className:"mobile-more-item","data-testid":"mobile-more-item-files",onClick:()=>Me(y),children:[t.jsx(ws,{}),t.jsx("span",{children:"Files"})]}),t.jsxs("button",{type:"button",className:"mobile-more-item","data-testid":"mobile-more-item-planning",onClick:()=>Me(ie),children:[t.jsx(Di,{}),t.jsx("span",{children:"Planning"}),R>0&&t.jsx("span",{className:"mobile-more-item-badge",children:go(R)})]}),t.jsxs("button",{type:"button",className:"mobile-more-item","data-testid":"mobile-more-item-workflow",onClick:()=>Me(g),children:[t.jsx(Jl,{}),t.jsx("span",{children:"Workflow Steps"})]}),t.jsxs("button",{type:"button",className:"mobile-more-item","data-testid":"mobile-more-item-schedules",onClick:()=>Me(w),children:[t.jsx(Yi,{}),t.jsx("span",{children:"Automation"})]}),t.jsxs("button",{type:"button",className:"mobile-more-item","data-testid":"mobile-more-item-github",onClick:()=>Me(C),children:[t.jsx(DF,{}),t.jsx("span",{children:"Import from GitHub"})]}),t.jsxs("button",{type:"button",className:"mobile-more-item","data-testid":"mobile-more-item-usage",onClick:()=>Me(O),children:[t.jsx(Vs,{}),t.jsx("span",{children:"Usage"})]}),t.jsxs("button",{type:"button",className:"mobile-more-item","data-testid":"mobile-more-item-projects",onClick:()=>Me(G),children:[t.jsx(vc,{}),t.jsx("span",{children:"Projects"})]}),t.jsxs("button",{type:"button",className:"mobile-more-item","data-testid":"mobile-more-item-documents",onClick:()=>Me(()=>n("documents")),children:[t.jsx(xa,{}),t.jsx("span",{children:"Documents"})]}),A?.evalsView&&t.jsxs("button",{type:"button",className:"mobile-more-item","data-testid":"mobile-more-item-evals",onClick:()=>Me(()=>n("evals")),children:[t.jsx(js,{}),t.jsx("span",{children:"Evals"})]}),Q&&t.jsxs("button",{type:"button",className:"mobile-more-item","data-testid":"mobile-more-item-skills",onClick:()=>Me(()=>n("skills")),children:[t.jsx(as,{}),t.jsx("span",{children:"Skills"})]}),t.jsxs("button",{type:"button",className:"mobile-more-item","data-testid":"mobile-more-item-stash-recovery",onClick:()=>Me(()=>n("stash-recovery")),children:[t.jsx(Oa,{}),t.jsx("span",{children:"Stash Recovery"}),f>0?t.jsx("span",{className:"mobile-more-item-badge",children:go(f)}):null]}),A?.researchView&&t.jsxs("button",{type:"button",className:"mobile-more-item","data-testid":"mobile-more-item-research",onClick:()=>Me(()=>n("research")),children:[t.jsx(Gi,{}),t.jsx("span",{children:"Research"})]}),A?.insights&&t.jsxs("button",{type:"button",className:"mobile-more-item","data-testid":"mobile-more-item-insights",onClick:()=>Me(()=>n("insights")),children:[t.jsx(cs,{}),t.jsx("span",{children:"Insights"})]}),A?.memoryView&&t.jsxs("button",{type:"button",className:"mobile-more-item","data-testid":"mobile-more-item-memory",onClick:()=>Me(()=>n("memory")),children:[t.jsx(Po,{}),t.jsx("span",{children:"Memory"})]}),A?.devServerView&&t.jsxs("button",{type:"button",className:"mobile-more-item","data-testid":"mobile-more-item-dev-server",onClick:()=>{Me(()=>n("dev-server"))},children:[t.jsx(Er,{}),t.jsx("span",{children:"Dev Server"})]}),A?.nodesView&&P&&t.jsxs("button",{type:"button",className:"mobile-more-item","data-testid":"mobile-more-item-nodes",onClick:()=>Me(P),children:[t.jsx(Lk,{}),t.jsx("span",{children:"Nodes"})]}),Z&&t.jsxs("button",{type:"button",className:"mobile-more-item","data-testid":"mobile-more-item-todos",onClick:()=>Me(()=>j?.()),children:[t.jsx(Vu,{}),t.jsx("span",{children:"Todos"})]}),be.map(se=>{const Ve=Mo(se.pluginId,se.view.viewId),Le=tc(se.view.icon);return t.jsxs("button",{type:"button",className:"mobile-more-item","data-testid":`mobile-more-item-plugin-${se.pluginId}-${se.view.viewId}`,onClick:()=>Me(()=>n(se.pluginId==="fusion-plugin-dependency-graph"&&se.view.viewId==="graph"?"graph":Ve)),children:[t.jsx(Le,{}),t.jsx("span",{children:se.view.label})]},`${se.pluginId}:${se.view.viewId}`)}),t.jsx("div",{className:"mobile-more-separator"}),t.jsxs("button",{type:"button",className:"mobile-more-item","data-testid":"mobile-more-item-settings",onClick:()=>Me(o),children:[t.jsx(_o,{}),t.jsx("span",{children:"Settings"})]})]})]})]})}function Eg(e){return e.trim().toLowerCase().replace(/[\s-]+/g,"_").replace(/_+/g,"_")}function oy(e,n){const s=n.trim();if(!s)return!0;const a=Eg(s);return Eg(e).includes(a)||e.toLowerCase().includes(s.toLowerCase())}function OF({agents:e,filter:n,highlightedIndex:s,visible:a,onSelect:r,position:o="below",roomMemberIds:l,roomName:c}){const d=i.useMemo(()=>e.filter(g=>oy(g.name,n)),[e,n]),u=!!l,h=u&&n.trim().length>0,m=i.useMemo(()=>u?d.filter(g=>l?.has(g.id)):d,[d,l,u]),f=i.useMemo(()=>u?d.filter(g=>!l?.has(g.id)):[],[d,l,u]),p=h?[...m,...f]:m;return a?t.jsx("div",{className:`agent-mention-popup agent-mention-popup--${o}`,"data-testid":"agent-mention-popup",role:"listbox","aria-label":"Agent mention suggestions",children:p.length===0?t.jsx("div",{className:"agent-mention-empty",children:"No agents found"}):t.jsxs(t.Fragment,{children:[u&&t.jsx("div",{className:"agent-mention-section-header","data-testid":"agent-mention-members-header",children:c?`Members of #${c}`:"Room members"}),m.map((g,w)=>t.jsxs("button",{type:"button",className:`agent-mention-item${w===s?" agent-mention-item--highlighted":""}`,"data-testid":`agent-mention-item-${g.id}`,onMouseDown:v=>v.preventDefault(),onClick:()=>r(g),role:"option","aria-selected":w===s,children:[t.jsx(uc,{agent:g,size:20}),u&&t.jsx("span",{className:"status-dot agent-mention-member-dot","aria-label":"Room member"}),t.jsx("span",{className:"agent-mention-name",children:g.name}),t.jsx("span",{className:"agent-mention-role",children:g.role})]},g.id)),u&&!h&&f.length>0&&t.jsx("div",{className:"agent-mention-hint","data-testid":"agent-mention-other-hint",children:"Type to search other agents"}),u&&h&&f.length>0&&t.jsxs(t.Fragment,{children:[t.jsx("div",{className:"agent-mention-section-header","data-testid":"agent-mention-others-header",children:"Other agents"}),f.map((g,w)=>{const v=m.length+w;return t.jsxs("button",{type:"button",className:`agent-mention-item${v===s?" agent-mention-item--highlighted":""}`,"data-testid":`agent-mention-item-${g.id}`,onMouseDown:b=>b.preventDefault(),onClick:()=>r(g),role:"option","aria-selected":v===s,children:[t.jsx(uc,{agent:g,size:20}),t.jsx("span",{className:"agent-mention-name",children:g.name}),t.jsx("span",{className:"agent-mention-role",children:g.role})]},g.id)})]})]})}):null}function _g(e){const{sessionId:n,tempUserMessageId:s,setStreamingText:a,setStreamingThinking:r,setStreamingToolCalls:o,cancelStreamingFlushesRef:l,addToast:c,onDone:d,onError:u,onFallbackSession:h}=e;let m="",f="",p=[],g,w=null,v=null;const b=()=>{w=null,a(m)},y=()=>{v=null,r(f)},j=()=>{w!==null&&(cancelAnimationFrame(w),w=null),v!==null&&(cancelAnimationFrame(v),v=null)};return l.current=j,{handlers:{onThinking:C=>{f+=C,v===null&&(v=requestAnimationFrame(y))},onText:C=>{m+=C,w===null&&(w=requestAnimationFrame(b))},onToolStart:C=>{p=[...p,{toolName:C.toolName,args:C.args,isError:!1,status:"running"}],o(p)},onToolEnd:C=>{const x=[...p];for(let k=x.length-1;k>=0;k--){const R=x[k];if(R?.toolName===C.toolName&&R.status==="running"){x[k]={...R,status:"completed",isError:C.isError,result:C.result},p=x,o(x);return}}p=[...x,{toolName:C.toolName,isError:C.isError,result:C.result,status:"completed"}],o(p)},onFallback:C=>{g=C,h?.(C,n),c?.(`Primary model unavailable. Switched to fallback ${C.fallbackModel}.`,"warning")},onDone:C=>{j(),d({messageId:C.messageId,message:C.message,accumulated:{text:m,thinking:f,toolCalls:p,fallbackInfo:g}})},onError:C=>{j(),u(C,s)}},cancelFlushes:j}}let Mg=null,Ag=null;const FF=["load failed","failed to fetch","networkerror when attempting to fetch resource.","connection aborted","connection closed unexpectedly","network error"];function zF(e){const n=e.trim().toLowerCase();return n?FF.some(s=>n.includes(s)):!1}function BF(){const e=i.useRef(Mg),n=i.useRef(Ag),s=i.useRef(new Set);i.useEffect(()=>{if(typeof document>"u")return;let l=document.visibilityState;const c=()=>{const d=Date.now(),u=document.visibilityState;if(u==="hidden"&&(e.current=d,Mg=d),u==="visible"&&(n.current=d,Ag=d,l==="hidden"))for(const h of s.current)h();l=u};return c(),document.addEventListener("visibilitychange",c),()=>document.removeEventListener("visibilitychange",c)},[]);const a=i.useCallback(()=>typeof document<"u"&&document.visibilityState==="hidden",[]),r=i.useCallback((l=5e3)=>{const c=e.current;if(c===null)return!1;const d=Date.now();if(a())return d-c<=l;const u=n.current;return u===null||u<c?!1:d-u<=l},[a]),o=i.useCallback(l=>(s.current.add(l),()=>{s.current.delete(l)}),[]);return i.useMemo(()=>({isHiddenNow:a,wasRecentlyHidden:r,onBecameVisible:o}),[a,o,r])}const wr="__fn_agent__";function ly(e,n){const s=typeof e=="string"?e.trim():"",a=typeof n=="string"?n.trim():"";return!s||!a?{}:{modelProvider:s,modelId:a}}function zl(e,n,s){const a=typeof e=="string"?e.trim():"",r=ly(n,s),o=a||(r.modelProvider&&r.modelId?wr:"");return o?{agentId:o,...r}:null}function Bl(e,n,s){const a=ly(n,s),r=a.modelProvider??"",o=a.modelId??"";return`${e}::${r}/${o}`}function Rg(e){const n=typeof e=="string"?e.trim():"",s=n.indexOf("/");return!n||s<=0||s>=n.length-1?{}:{modelProvider:n.slice(0,s),modelId:n.slice(s+1)}}function UF(e){const n=e?.toolCalls;if(!Array.isArray(n))return;const s=n.map(a=>{if(!a||typeof a!="object")return null;const r=a,o=typeof r.toolName=="string"?r.toolName:"";if(!o)return null;const l=r.args;return{toolName:o,...l&&typeof l=="object"?{args:l}:{},isError:!!r.isError,result:r.result,status:"completed"}}).filter(a=>a!==null);return s.length>0?s:void 0}function HF(e){const n=e?.fallback;if(!n||typeof n!="object")return;const s=n,a=typeof s.primaryModel=="string"?s.primaryModel:"",r=typeof s.fallbackModel=="string"?s.fallbackModel:"",o=s.triggerPoint;if(!(!a||!r||o!=="session-creation"&&o!=="prompt-time"))return{primaryModel:a,fallbackModel:r,triggerPoint:o}}function gr(e){return{id:e.id,sessionId:e.sessionId,role:e.role,content:e.content,thinkingOutput:e.thinkingOutput,toolCalls:UF(e.metadata),fallbackInfo:HF(e.metadata),createdAt:e.createdAt}}function qF(e,n){const[s,a]=i.useState(null),[r,o]=i.useState([]),[l,c]=i.useState(!1),[d,u]=i.useState([]),[h,m]=i.useState(!1),[f,p]=i.useState(!1),[g,w]=i.useState(""),[v,b]=i.useState(""),[y,j]=i.useState([]),[S,C]=i.useState(""),x=i.useRef(null),k=i.useRef(!1),R=i.useRef(null),O=i.useRef(""),E=i.useRef(f);E.current=f;const _=i.useRef(null),G=i.useRef(""),H=i.useRef(null),A=i.useRef(s);A.current=s;const P=i.useRef(0),q=3,Y=i.useRef(!1);i.useEffect(()=>{O.current=S},[S]);const ge=i.useCallback(async()=>{c(!0);try{const X=await gh(e);o(X.sessions)}catch(X){console.error("[useQuickChat] Failed to refresh sessions:",X)}finally{c(!1)}},[e]),L=i.useCallback(async X=>{const re={agentId:X.agentId};return X.modelProvider&&X.modelId&&(re.modelProvider=X.modelProvider,re.modelId=X.modelId),(await gC(re,e)).session},[e]),M=i.useCallback(()=>{O.current="",C("")},[]),$=i.useCallback(()=>{const X=O.current.trim();X&&(O.current="",C(""),Z.current(X))},[]),D=i.useCallback((X,re,U)=>{if(x.current||!X)return!0;k.current=!1,re&&(w(re.streamingText),b(re.streamingThinking),j(re.toolCalls)),p(!0);const{handlers:be}=_g({sessionId:X,tempUserMessageId:"",setStreamingText:w,setStreamingThinking:b,setStreamingToolCalls:j,cancelStreamingFlushesRef:R,addToast:U?.silent?void 0:n,onFallbackSession:(Ue,se)=>{const Ve=Rg(Ue.fallbackModel);o(Le=>Le.map(ct=>ct.id===se?{...ct,...Ve}:ct)),a(Le=>Le&&Le.id===se?{...Le,...Ve}:Le)},onDone:()=>{w(""),b(""),j([]),p(!1),E.current=!1,x.current=null,to(X,{limit:50},e).then(Ue=>{u(Ue.messages.map(gr))}).catch(()=>{}),$()},onError:Ue=>{w(""),b(""),j([]),p(!1),E.current=!1,x.current=null;const se=typeof Ue=="string"&&Ue.trim()?Ue:"Failed to get response";U?.silent||n?.(se,"error"),to(X,{limit:50},e).then(Ve=>{u(Ve.messages.map(gr))}).catch(()=>{}),$()}});return x.current=yC(X,be,e,{...typeof re?.replayFromEventId=="number"?{lastEventId:re.replayFromEventId}:{}}),!0},[n,e,$]),N=i.useCallback(async(X,re,U)=>{const be=zl(X,re,U);if(!be)return;const Ue=Bl(be.agentId,be.modelProvider,be.modelId);c(!0);try{const{session:se}=await fC({agentId:be.agentId,modelProvider:be.modelProvider,modelId:be.modelId},e);if(se)a(se),G.current=Ue,se.isGenerating&&D(se.id,se.inFlightGeneration);else{const Ve=await L(be);a(Ve),G.current=Ue}P.current=0}catch(se){console.error("[useQuickChat] Failed to initialize session:",se),P.current+=1,P.current<=q&&n?.("Failed to initialize chat","error")}finally{c(!1)}},[D,e,n,L]),W=i.useCallback(async()=>{if(s){m(!0);try{const X=await to(s.id,{limit:50},e);u(X.messages.map(gr))}catch(X){console.error("[useQuickChat] Failed to load messages:",X)}finally{m(!1)}}},[s,e]);i.useEffect(()=>{s?W():u([])},[s,W]),i.useEffect(()=>{if(!s?.isGenerating||(x.current||D(s.id,s.inFlightGeneration),!E.current||x.current||!s))return;const X=setInterval(async()=>{if(!E.current||x.current||!s){clearInterval(X);return}try{if(!(await Jc(s.id,e)).session.isGenerating){clearInterval(X);const U=await to(s.id,{limit:50},e);u(U.messages.map(gr)),w(""),b(""),j([]),p(!1),E.current=!1,$()}}catch{}},3e3);return()=>clearInterval(X)},[s,D,e,$]);const de=i.useCallback(async()=>{if(s){m(!0);try{const X=await to(s.id,{limit:50},e);u(X.messages.map(gr))}catch(X){console.error("[useQuickChat] Failed to reload messages:",X)}finally{m(!1)}}},[s,e]),me=i.useCallback(()=>{R.current?.(),R.current=null,O.current="",C(""),w(""),b(""),j([]),p(!1)},[]),Ne=i.useCallback(async(X,re,U)=>{const be=zl(X,re,U);if(!be)return;const Ue=Bl(be.agentId,be.modelProvider,be.modelId);H.current=be;const se=Ue===G.current&&A.current;if(se||(x.current&&(x.current.close(),x.current=null),me()),se){await de();return}a(null),u([]),G.current=Ue,await N(be.agentId,be.modelProvider,be.modelId)},[N,de,me]),ve=i.useCallback(async X=>{const re=zl(X.agentId,X.modelProvider??void 0,X.modelId??void 0);re&&(H.current=re,G.current=Bl(re.agentId,re.modelProvider,re.modelId),x.current&&(x.current.close(),x.current=null),me(),a(X),X.isGenerating&&D(X.id,X.inFlightGeneration))},[D,me]),Me=i.useCallback(async(X,re)=>{await Ne(wr,X,re)},[Ne]),ie=i.useCallback(async(X,re,U)=>{const Ue=zl(X??"",re,U)??H.current;if(!Ue)return;H.current=Ue;const se=Bl(Ue.agentId,Ue.modelProvider,Ue.modelId);Y.current=!0,P.current=0,x.current&&(x.current.close(),x.current=null),me(),u([]),a(null),c(!0);try{const Ve=await L(Ue);a(Ve),G.current=se;const Le=await gh(e);o(Le.sessions)}catch(Ve){console.error("[useQuickChat] Failed to start a fresh session:",Ve),n?.("Failed to start a new chat","error")}finally{Y.current=!1,c(!1)}},[n,L,e,me]),ye=i.useCallback(()=>{s&&(k.current=!0,R.current?.(),R.current=null,x.current?.close(),x.current=null,bC(s.id,e).catch(()=>{}),p(!1),w(""),b(""),j([]))},[s,e]),Z=i.useRef(()=>Promise.resolve()),fe=BF(),Q=i.useCallback(async X=>{try{await ge();const U=(await Jc(X,e)).session;A.current?.id===X&&a(be=>!be||be.id!==X?be:{...be,...U}),U.isGenerating?(w(""),b(""),j([]),p(!0),E.current=!0,D(X,U.inFlightGeneration,{silent:!0})):(w(""),b(""),j([]),p(!1),E.current=!1,await de())}catch{}},[D,e,ge,de]),F=i.useCallback((X,re)=>{if(!s||!X.trim()&&(!re||re.length===0))return Promise.resolve();if(E.current)return re&&re.length>0?Promise.reject(new Error("Cannot send attachments while a response is streaming")):(O.current=X,C(X),Promise.resolve());const U=new Promise((be,Ue)=>{_.current={resolve:be,reject:Ue},k.current=!1,x.current&&(x.current.close(),x.current=null);const se=`temp-${Date.now()}`,Ve={id:se,sessionId:s.id,role:"user",content:X,createdAt:new Date().toISOString()};u(ct=>[...ct,Ve]),w(""),b(""),j([]),p(!0);const{handlers:Le}=_g({sessionId:s.id,tempUserMessageId:se,setStreamingText:w,setStreamingThinking:b,setStreamingToolCalls:j,cancelStreamingFlushesRef:R,addToast:n,onFallbackSession:(ct,Ke)=>{const oe=Rg(ct.fallbackModel);o(Te=>Te.map(Fe=>Fe.id===Ke?{...Fe,...oe}:Fe)),a(Te=>Te&&Te.id===Ke?{...Te,...oe}:Te)},onDone:({messageId:ct,message:Ke,accumulated:oe})=>{const Te=Ke?gr(Ke):{id:ct||`msg-${Date.now()}`,sessionId:s.id,role:"assistant",content:oe.text,thinkingOutput:oe.thinking||void 0,toolCalls:oe.toolCalls.length>0?oe.toolCalls:void 0,fallbackInfo:oe.fallbackInfo,createdAt:new Date().toISOString()};u(Fe=>[...Fe,Te]),w(""),b(""),j([]),p(!1),E.current=!1,x.current=null,_.current?.resolve(),_.current=null,$()},onError:ct=>{w(""),b(""),j([]),p(!1),E.current=!1,x.current=null,console.error("[useQuickChat] Stream error:",ct);const Ke=typeof ct=="string"&&ct.trim()?ct:"Failed to get response",oe=zF(Ke);oe?(console.info("[useQuickChat] Suppressed tab-suspension stream error:",ct),s?.id&&(w(""),b(""),j([]),p(!0),E.current=!0,Q(s.id)),_.current?.resolve()):(n?.(Ke,"error"),_.current?.reject(new Error(Ke))),_.current=null,k.current||$(),oe||de()}});x.current=vC(s.id,X,Le,re,e)});return U.catch(()=>{}),U},[s,e,n,de,Q,$]);return Z.current=F,i.useEffect(()=>fe.onBecameVisible(()=>{if(Y.current)return;const re=A.current;!re||x.current||Promise.resolve(Jc(re.id,e)).then(U=>{if(!(x.current||A.current?.id!==re.id)){if(U.session.isGenerating){w(""),b(""),j([]),p(!0),E.current=!0,D(re.id,U.session.inFlightGeneration,{silent:!0});return}E.current&&(w(""),b(""),j([]),p(!1),E.current=!1,$(),de())}}).catch(()=>{})}),[D,e,de,fe,$]),i.useEffect(()=>()=>{x.current&&(x.current.close(),x.current=null)},[]),i.useMemo(()=>({activeSession:s,sessions:r,sessionsLoading:l,messages:d,messagesLoading:h,isStreaming:f,streamingText:g,streamingThinking:v,streamingToolCalls:y,pendingMessage:S,sendMessage:F,stopStreaming:ye,clearPendingMessage:M,switchSession:Ne,selectSession:ve,startModelChat:Me,startFreshSession:ie,refreshSessions:ge,loadMessages:W,reloadMessages:de,skipNextSessionInitRef:Y}),[s,r,l,d,h,f,g,v,y,S,F,ye,M,Ne,ve,Me,ie,ge,W,de])}function cy(e,n){const[s,a]=i.useState([]),[r,o]=i.useState(null),[l,c]=i.useState(!1),d=i.useCallback(async p=>{c(!0);try{const g=n?.filterState,w=g&&g!=="all"?{state:g}:void 0,v=n?.showSystemAgents??!1,b=await Hr({...w,...p,includeEphemeral:p?.includeEphemeral??v},e),y=Array.from(new Map(b.map(j=>[j.id,j])).values());a(y)}catch(g){console.error("Failed to load agents:",g)}finally{c(!1)}},[e,n?.filterState,n?.showSystemAgents]),u=i.useCallback(async()=>{try{const p=await R1(e);o(p)}catch(p){console.error("Failed to load agent stats:",p)}},[e]);i.useEffect(()=>{d(),u()},[d,u]),i.useEffect(()=>{const p=e?`?projectId=${encodeURIComponent(e)}`:"",g=()=>{d(),u()};return fi(`/api/events${p}`,{events:{"agent:created":g,"agent:updated":g,"agent:deleted":g,"agent:stateChanged":g,"approval:requested":g,"approval:updated":g,"approval:decided":g}})},[e,d,u]);const h=i.useCallback(async()=>{await Promise.all([d(),u()])},[d,u]),m=n?.showSystemAgents??!1,f=s.filter(p=>p.state!=="active"&&p.state!=="running"?!1:m||!Jj(p));return{agents:s,activeAgents:f,stats:r,isLoading:l,loadAgents:d,loadStats:u,refreshAgents:h}}function VF({visible:e,position:n,files:s,selectedIndex:a,onSelect:r,loading:o}){return e?t.jsxs("div",{className:"file-mention-popup",style:{top:n.top,left:n.left},"data-testid":"file-mention-popup",onMouseDown:l=>{l.preventDefault()},children:[o&&t.jsx("div",{className:"file-mention-popup-loading","data-testid":"file-mention-loading",children:t.jsx("span",{className:"spinner"})}),!o&&s.length===0&&t.jsx("div",{className:"file-mention-popup-empty","data-testid":"file-mention-empty",children:"No files found"}),!o&&s.length>0&&t.jsx("ul",{className:"file-mention-popup-list",role:"listbox",children:s.map((l,c)=>{const d=KC(l.path),u=l.name;return t.jsxs("li",{className:`file-mention-popup-item${c===a?" file-mention-popup-item--selected":""}`,onClick:()=>r(l),onMouseEnter:()=>{},role:"option","aria-selected":c===a,"data-testid":`file-mention-item-${c}`,children:[t.jsx("span",{className:"file-mention-popup-icon",children:t.jsx(ub,{size:14})}),t.jsxs("div",{className:"file-mention-popup-info",children:[t.jsx("span",{className:"file-mention-popup-item-name",children:u}),d&&t.jsx("span",{className:"file-mention-popup-item-path",children:d})]})]},l.path)})})]}):null}const WF=200;function GF(e={}){const{projectId:n,workspace:s="project"}=e,[a,r]=i.useState(!1),[o,l]=i.useState(""),[c,d]=i.useState(-1),[u,h]=i.useState([]),[m,f]=i.useState(!1),[p,g]=i.useState(0),w=i.useRef(null),v=i.useRef(null);i.useEffect(()=>()=>{w.current&&clearTimeout(w.current),v.current?.abort()},[]);const b=i.useCallback((x,k)=>{if(k<0||k>x.length){r(!1);return}const R=O=>/[a-zA-Z0-9/_.-]/.test(O);for(let O=k-1;O>=0;O--){if(x[O]==="#")if(O===0){const E=x.slice(O+1,k);d(O),l(E),g(0),r(!0);return}else{const E=x[O-1];if(/[\s,.;:!?'"()[\]{}]/.test(E)){const _=x.slice(O+1,k);d(O),l(_),g(0),r(!0);return}r(!1);return}if(!R(x[O])){r(!1);return}}r(!1)},[]),y=i.useCallback(()=>{r(!1),l(""),d(-1),h([]),g(0),f(!1)},[]),j=i.useCallback(async x=>{if(!x.trim()){h([]),f(!1);return}v.current?.abort(),v.current=new AbortController;try{f(!0);const k=await DS(x,s,n);h(k.files),g(0)}catch(k){k.name!=="AbortError"&&h([])}finally{f(!1)}},[s,n]);i.useEffect(()=>{if(a)return w.current&&clearTimeout(w.current),w.current=setTimeout(()=>{j(o)},WF),()=>{w.current&&clearTimeout(w.current)}},[o,a,j]);const S=i.useCallback((x,k)=>{if(!a||c<0)return k;const R=k.slice(0,c),O=k.slice(c+1),E=O.match(/[\s]|$/),_=E?E.index:O.length,G=O.slice(_);return`${R}#${x.path}${G}`},[a,c]),C=i.useCallback((x,k)=>{if(!a||u.length===0)return!1;switch(x.key){case"ArrowDown":return x.preventDefault(),g(R=>Math.min(R+1,u.length-1)),!0;case"ArrowUp":return x.preventDefault(),g(R=>Math.max(R-1,0)),!0;case"Enter":case"Tab":return u[p]?(x.preventDefault(),!0):!1;case"Escape":return x.preventDefault(),y(),!0;default:return!1}},[a,u,p,y]);return{mentionActive:a,files:u,loading:m,mentionQuery:o,selectedIndex:p,setSelectedIndex:g,detectMention:b,selectFile:S,dismissMention:y,handleKeyDown:C}}function KF(e){return`${e.name?.trim()||e.id} (${e.role})`}function bo(e){const n=e.trim(),s=n.indexOf("/");return!n||s<=0||s>=n.length-1?null:{modelProvider:n.slice(0,s),modelId:n.slice(s+1)}}function JF(e,n){return n?e?.name?.trim()?e.name.trim():n.modelId.replace(/[-_]/g," ").replace(/\s+/g," ").replace(/^\w/,s=>s.toUpperCase()).trim():null}function Wl(e,n){return e.length<=n?e:`${e.slice(0,n)}…`}function YF(e){if(!e)return null;const n=Object.entries(e);return n.length===0?null:n.map(([s,a])=>{const r=typeof a=="string"?a:(()=>{try{return JSON.stringify(a)}catch{return String(a)}})();return`${s}=${Wl(r,50)}`}).join(", ")}function QF(e){if(e===void 0)return null;if(typeof e=="string")return Wl(e,200);try{return Wl(JSON.stringify(e),200)}catch{return Wl(String(e),200)}}function dy(e,n=!1){if(!e||e.length===0)return null;const s=(f,p)=>{const g=f.status==="running",w=f.status==="completed"&&f.isError,v=YF(f.args),b=QF(f.result),y=g?v:b?`result: ${b}`:v?`args: ${v}`:null,j=n?null:y,S=g?"running":w?"error":"completed";return t.jsxs("details",{className:`chat-tool-call${g?" chat-tool-call--running":""}${w?" 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:f.toolName,children:f.toolName}),j&&t.jsx("span",{className:"chat-tool-call-preview",title:j,children:j}),t.jsx("span",{className:"chat-tool-call-status-text",children:S})]}),t.jsxs("div",{className:"chat-tool-call-content",children:[v&&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:v})]}),b&&t.jsxs("div",{className:`chat-tool-call-row${w?" 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:b})]})]})]},`${f.toolName}-${p}`)},a=`chat-tool-calls${n?" chat-tool-calls--compact":""}`;if(e.length===1)return t.jsxs("div",{className:a,"data-testid":"chat-tool-calls",children:[t.jsxs("div",{className:"chat-tool-calls-header",children:[t.jsx(Hm,{size:12,"aria-hidden":"true"}),t.jsx("span",{children:"Tool calls"})]}),s(e[0],0)]});const r=e.filter(f=>f.status==="running").length,o=e.filter(f=>f.status==="completed"&&f.isError).length,l=r>0,c=Array.from(new Set(e.map(f=>f.toolName))),d=c.slice(0,5),u=Math.max(0,c.length-d.length),h=u>0?`${d.join(", ")}, +${u} more`:d.join(", "),m=l?`(${r} running)`:o>0?`(${o} ${o===1?"error":"errors"})`:null;return t.jsx("div",{className:a,"data-testid":"chat-tool-calls",children:t.jsxs("details",{className:`chat-tool-calls-group${n?" chat-tool-calls-group--compact":""}`,"data-testid":"chat-tool-calls-group",open:l,children:[t.jsxs("summary",{className:"chat-tool-calls-group-summary",children:[t.jsx(Hm,{size:12,"aria-hidden":"true"}),t.jsxs("span",{className:"chat-tool-calls-count",children:[e.length," tool calls"]}),t.jsx("span",{className:"chat-tool-calls-names",title:h,children:h}),m&&t.jsx("span",{className:"chat-tool-calls-group-status",children:m})]}),e.map((f,p)=>s(f,p))]})})}const uy={pre:({children:e,...n})=>t.jsx("pre",{...n,className:"quick-chat-markdown-pre",children:e}),table:({children:e,...n})=>t.jsx("table",{...n,className:"quick-chat-markdown-table",children:e})};function Ig(e){const n=/(^|[\s])\/([^\s]*)$/.exec(e);if(!n)return null;const s=n[1]??"",a=n[2]??"",r=n.index+s.length;return{filter:a,start:r,end:e.length}}function XF(e,n){const s=e.slice(0,n),a=/(^|[\s])@([\w-]*)$/.exec(s);if(!a)return null;const r=a[2]??"",o=s.length-r.length-1;return{filter:r,start:o,end:n}}const Ul={width:320,height:400},ZF=new Set(["image/png","image/jpeg","image/gif","image/webp","text/plain","application/json","text/yaml","text/x-log","text/csv","application/xml","text/markdown"]),ez=[".png",".jpg",".jpeg",".gif",".webp",".txt",".json",".yaml",".yml",".log",".csv",".xml",".md"];function tz(e){return e.type.startsWith("image/")}function nz(e){if(ZF.has(e.type))return!0;const n=e.name.toLowerCase();return ez.some(s=>n.endsWith(s))}const br={width:280,height:260},Rs=768,xr=8;function sz(e,n){const s=i.useCallback(()=>{if(typeof window>"u")return 0;const S=getComputedStyle(document.documentElement).getPropertyValue("--executor-footer-height").trim();return S&&parseFloat(S)||0},[]),a=i.useCallback(()=>typeof window<"u"&&window.innerWidth<=768?{x:4,y:4+s()}:{x:24,y:24+s()},[s]),[r,o]=i.useState(()=>{if(typeof window>"u")return a();const S=`fusion-quick-chat-position-${e||"default"}`;try{const C=localStorage.getItem(S);if(C){const x=JSON.parse(C);if(typeof x.x=="number"&&typeof x.y=="number"&&!isNaN(x.x)&&!isNaN(x.y))return x}}catch{}return a()}),[l,c]=i.useState(!1),d=i.useRef(null),u=i.useRef(r),h=i.useRef(null),m=i.useRef(null),f=n??i.useRef(!1);i.useEffect(()=>{u.current=r},[r]);const p=i.useCallback(S=>{if(typeof window>"u")return S;const C=48,x=window.innerWidth<=768?4:8,k=window.innerWidth<=768?44:0,R=window.innerWidth>768?s():0,O=window.innerWidth-C-x,E=window.innerHeight-C-x-k-R;return{x:Math.max(x,Math.min(O,S.x)),y:Math.max(x,Math.min(E,S.y))}},[s]),g=i.useCallback(S=>{if(typeof window>"u")return;const C=`fusion-quick-chat-position-${e||"default"}`;try{localStorage.setItem(C,JSON.stringify(S))}catch{}},[e]),w=i.useCallback(()=>{if(!d.current)return;const S=m.current,C=h.current;S&&C!==null&&typeof S.releasePointerCapture=="function"&&S.releasePointerCapture(C),d.current=null,h.current=null,m.current=null,c(!1),document.body.style.userSelect="",f.current&&g(u.current),document.removeEventListener("pointermove",v),document.removeEventListener("pointerup",b),document.removeEventListener("pointercancel",y)},[g]),v=i.useCallback(S=>{if(!d.current||h.current!==null&&S.pointerId!==h.current)return;const C=S.clientX-d.current.pointerX,x=S.clientY-d.current.pointerY;if((Math.abs(C)>=5||Math.abs(x)>=5)&&(f.current=!0),!f.current)return;const k=d.current.x-C,R=d.current.y-x,O=p({x:k,y:R});u.current=O,o(O)},[p]),b=i.useCallback(S=>{h.current!==null&&S.pointerId!==h.current||w()},[w]),y=i.useCallback(S=>{h.current!==null&&S.pointerId!==h.current||w()},[w]),j=i.useCallback(S=>{if(S.button!==0&&S.pointerType==="mouse")return;const C=S.currentTarget;S.preventDefault(),typeof C.setPointerCapture=="function"&&C.setPointerCapture(S.pointerId);const x=u.current;d.current={x:x.x,y:x.y,pointerX:S.clientX,pointerY:S.clientY},h.current=S.pointerId,m.current=C,f.current=!1,c(!0),document.body.style.userSelect="none",document.addEventListener("pointermove",v,{passive:!0}),document.addEventListener("pointerup",b),document.addEventListener("pointercancel",y)},[y,v,b]);return i.useEffect(()=>()=>{document.removeEventListener("pointermove",v),document.removeEventListener("pointerup",b),document.removeEventListener("pointercancel",y),document.body.style.userSelect=""},[y,v,b]),{position:r,isDragging:l,handlePointerDown:j}}function iz(e,n,s){const a=`fusion:quick-chat-size-${e||"default"}`,r=i.useCallback(()=>typeof window<"u"&&window.innerWidth>Rs,[]),o=i.useCallback((f,p,g)=>{if(typeof window>"u")return f;const w=Math.max(br.width,window.innerWidth-p-xr),v=Math.max(br.height,window.innerHeight-g-xr);return{width:Math.max(br.width,Math.min(w,f.width)),height:Math.max(br.height,Math.min(v,f.height))}},[]),l=i.useCallback(()=>{if(typeof window>"u"||window.innerWidth<=Rs)return Ul;try{const f=localStorage.getItem(a);if(!f)return Ul;const p=JSON.parse(f);return typeof p.width!="number"||typeof p.height!="number"?Ul:{width:p.width,height:p.height}}catch{return Ul}},[a]),[c,d]=i.useState(l),[u,h]=i.useState({right:0,bottom:0});i.useEffect(()=>{if(!r())return;const f={right:n+u.right,bottom:s+u.bottom};d(p=>o(p,f.right,f.bottom))},[o,r,n,s,u]),i.useEffect(()=>{if(r())try{localStorage.setItem(a,JSON.stringify(c))}catch{}},[r,c,a]);const m=i.useCallback(f=>{if(!r())return;const p=f.currentTarget.dataset.resizeDirection;if(!p)return;f.preventDefault(),f.stopPropagation();const g=f.currentTarget;typeof g.setPointerCapture=="function"&&g.setPointerCapture(f.pointerId);const w={pointerX:f.clientX,pointerY:f.clientY,width:c.width,height:c.height,anchorRight:u.right,anchorBottom:u.bottom};document.body.style.userSelect="none";const v=y=>{const j=y.clientX-w.pointerX,S=y.clientY-w.pointerY;let C=w.width,x=w.height,k=w.anchorRight,R=w.anchorBottom;if(p.includes("w")&&(C=w.width-j),p.includes("e")){const A=j;C=w.width+A,k=w.anchorRight-A}if(p.includes("n")&&(x=w.height-S),p.includes("s")){const A=S;x=w.height+A,R=w.anchorBottom-A}const O=n+k,E=s+R,_=o({width:C,height:x},O,E),G=Math.max(xr-n,Math.min(window.innerWidth-n-br.width-xr,k)),H=Math.max(xr-s,Math.min(window.innerHeight-s-br.height-xr,R));d(_),h({right:G,bottom:H})},b=y=>{typeof g.releasePointerCapture=="function"&&g.releasePointerCapture(y.pointerId),document.body.style.userSelect="",document.removeEventListener("pointermove",v),document.removeEventListener("pointerup",b);try{localStorage.setItem(a,JSON.stringify({width:c.width,height:c.height}))}catch{}};document.addEventListener("pointermove",v),document.addEventListener("pointerup",b)},[u.bottom,u.right,o,s,n,r,c.height,c.width,a]);return{panelSize:c,anchorOffset:u,handleResizeStart:m}}const Tg=i.memo(function({message:n,forcePlain:s,mentionAgentsByName:a,roomContext:r,onToggleRender:o}){const l=n.role==="user",c=i.useMemo(()=>{if(!l)return null;const u=n.content,h=/@([\w-]+)/g,m=[];let f=0,p=h.exec(u);for(;p;){const[g,w=""]=p,v=p.index;v>f&&m.push(u.slice(f,v));const b=w.replace(/_/g," ").toLowerCase(),y=a.get(b);if(y){const j=!!(r&&!r.memberIds.has(y.id)),S=j?`Not a member of ${r?.roomName}`:void 0;m.push(t.jsxs("span",{className:`chat-mention-chip${j?" chat-mention-chip--non-member":""}`,title:S,"aria-label":S,children:["@",y.name.replace(/\s+/g,"_")]},`${y.id}-${v}`))}else m.push(g);f=v+g.length,p=h.exec(u)}return f<u.length&&m.push(u.slice(f)),m.length===0?u:m},[l,n.content,a,r]),d=i.useMemo(()=>l?null:s?t.jsx("div",{className:"quick-chat-message-content quick-chat-message-content--plain",children:n.content}):t.jsx("div",{className:"quick-chat-message-content quick-chat-message-content--markdown",children:t.jsx(hi,{remarkPlugins:[pi],components:uy,children:n.content})}),[l,s,n.content]);return t.jsxs("div",{className:`quick-chat-panel-message ${l?"quick-chat-panel-message--sent":"quick-chat-panel-message--received"}`,"data-testid":`quick-chat-message-${n.id}`,children:[l?t.jsx("p",{children:c}):t.jsxs(t.Fragment,{children:[d,t.jsx("button",{type:"button",className:`quick-chat-message-render-toggle${s?" quick-chat-message-render-toggle--plain":""}`,"data-testid":"quick-chat-message-render-toggle","aria-label":s?"Show rendered markdown":"Show plain text",onClick:()=>o(n.id),children:s?t.jsx(qu,{size:14}):t.jsx(zr,{size:14})})]}),dy(n.toolCalls,!0)]})});function az({projectId:e,addToast:n,showFAB:s=!0,open:a,onOpenChange:r,favoriteProviders:o=[],favoriteModels:l=[],onToggleFavorite:c,onToggleModelFavorite:d,roomContext:u=null}){const{agents:h}=cy(e),[m,f]=i.useState(!1),p=a!==void 0,g=p?a:m,w=p?ne=>{r?.(typeof ne=="function"?ne(g):ne)}:f,{keyboardOpen:v}=ea({enabled:g}),b=ei(),y=b==="mobile",[j,S]=i.useState("agent"),[C,x]=i.useState(""),[k,R]=i.useState(!1),[O,E]=i.useState("model"),[_,G]=i.useState(""),[H,A]=i.useState(""),[P,q]=i.useState([]),[Y,ge]=i.useState(!1),[L,M]=i.useState(""),[$,D]=i.useState(""),[N,W]=i.useState(""),[de,me]=i.useState([]),[Ne,ve]=i.useState(!1),[Me,ie]=i.useState(!1),[ye,Z]=i.useState(""),[fe,Q]=i.useState(0),[F,X]=i.useState(""),[re,U]=i.useState(!1),[be,Ue]=i.useState(0),[se,Ve]=i.useState(-1),[Le,ct]=i.useState(()=>new Set),[Ke,oe]=i.useState(!1),[Te,Fe]=i.useState([]),[mt,We]=i.useState(!1),[he,pe]=i.useState(!1),[,De]=i.useState(!1),[ut,ht]=i.useState({top:0,left:0}),et=GF({projectId:e}),vt=i.useCallback(ne=>{if(!ne||!et.mentionActive)return;const Be=ne.getBoundingClientRect();ht({top:Be.top-260,left:Be.left+8})},[et.mentionActive]),Oe=i.useRef(!1),tt=i.useRef(!1),ft=i.useRef(!1),Mt=i.useRef(""),yt=i.useRef(!1),Ge=i.useRef(!1),K=i.useRef(C),ue=i.useRef(L),ot=i.useRef(0),xe=i.useRef(null),dt=i.useRef(null),Je=i.useRef(0),{position:ke,isDragging:nt,handlePointerDown:bt}=sz(e,Oe),kt=ke.y+60,{panelSize:wt,anchorOffset:At,handleResizeStart:Ft}=iz(e,ke.x,kt),ln=typeof window<"u"&&window.innerWidth>Rs,{activeSession:Vt,messages:hn,isStreaming:un,streamingText:pn,streamingThinking:an,streamingToolCalls:Wt,sessions:gn,sessionsLoading:cn,messagesLoading:tn,sendMessage:Yt,stopStreaming:Qt,pendingMessage:Kt,clearPendingMessage:Jt,switchSession:rn,selectSession:qt,startModelChat:we,startFreshSession:ze,refreshSessions:rt,skipNextSessionInitRef:He}=qF(e,n),Ae=i.useRef(null),pt=i.useRef(null),Ct=i.useRef(null),Tt=i.useRef(null),Gt=i.useRef(null),nn=i.useRef([]),Ht=i.useRef(!1),on=i.useRef(!1),ae=i.useRef(!1),le=i.useRef(null),Qe=i.useRef(!1),xt=i.useRef(!1),zt=i.useRef({isOpen:!1,sessionId:null});i.useEffect(()=>{if(!g||typeof window>"u"||typeof document>"u"||window.innerWidth>Rs)return;const ne=window.scrollY,Be=document.documentElement,Xe=document.body,Dt={htmlOverflow:Be.style.overflow,bodyOverflow:Xe.style.overflow};return window.scrollTo(0,0),Be.style.overflow="hidden",Xe.style.overflow="hidden",()=>{Be.style.overflow=Dt.htmlOverflow,Xe.style.overflow=Dt.bodyOverflow,window.scrollTo(0,ne)}},[g]),i.useLayoutEffect(()=>{if(!g||typeof window>"u"||!window.visualViewport)return;const ne=Ae.current;if(!ne)return;const Be=window.visualViewport,Xe=()=>{Qe.current||(ne.style.setProperty("--vv-height",`${Be.height}px`),ne.style.setProperty("--vv-offset-top",`${Be.offsetTop||0}px`))};return Xe(),Be.addEventListener("resize",Xe),Be.addEventListener("scroll",Xe),()=>{Be.removeEventListener("resize",Xe),Be.removeEventListener("scroll",Xe)}},[g]);const sn=L||$,xn=i.useMemo(()=>bo(sn),[sn]),$n=i.useMemo(()=>j==="model"&&Vt?.modelProvider&&Vt?.modelId?`${Vt.modelProvider}/${Vt.modelId}`:sn,[Vt?.modelId,Vt?.modelProvider,j,sn]),wn=i.useMemo(()=>bo($n),[$n]),zn=i.useMemo(()=>P.find(ne=>`${ne.provider}/${ne.id}`===$n)??null,[$n,P]),ce=i.useMemo(()=>JF(zn,wn),[zn,wn]),ee=i.useMemo(()=>j==="model"?xn?`${wr}::${xn.modelProvider}/${xn.modelId}`:"":C?`${C}::`:"",[j,C,xn]),qe=!(j==="agent"?!!C:!!xn)||!Vt,z=i.useMemo(()=>!!C&&gn.some(ne=>!ne.modelProvider&&!ne.modelId&&ne.agentId===C),[C,gn]);i.useEffect(()=>{K.current=C},[C]),i.useEffect(()=>{ue.current=L},[L]),i.useEffect(()=>{if(h.length===0){x(""),S("model");return}if(yt.current&&z)return;h.some(Be=>Be.id===C)||x(h[0]?.id??"")},[h,z,C]),i.useEffect(()=>{!g||tt.current||(tt.current=!0,ft.current=!1,ge(!0),Bs().then(ne=>{const Be=ne.models??[];if(q(Be),ue.current||Be.length===0)return;const Xe=ne.defaultProvider,Dt=ne.defaultModelId;if(Xe&&Dt){const mn=`${Xe}/${Dt}`;if(Be.some(Dn=>`${Dn.provider}/${Dn.id}`===mn)){D(mn),ue.current||M(mn),yt.current||S("model");return}}D("");const Xt=Be[0];Xt&&!ue.current&&M(`${Xt.provider}/${Xt.id}`)}).catch(ne=>{console.error("[QuickChatFAB] Failed to load models:",ne),q([]),D("")}).finally(()=>{ft.current=!0,ge(!1)}))},[g,h.length,L]),i.useEffect(()=>{!g||!e||(ve(!0),pC(e).then(ne=>{me(ne)}).catch(()=>{me([])}).finally(()=>{ve(!1)}))},[g,e]),i.useEffect(()=>{g&&rt()},[g,rt]),i.useEffect(()=>{if(!g||cn||yt.current||gn.length===0)return;const ne=gn.filter(Dt=>Dt.status!=="archived"),Be=Dt=>{if(!Dt)return 0;const Xt=Date.parse(Dt);return Number.isFinite(Xt)?Xt:0},Xe=[...ne].sort((Dt,Xt)=>{const mn=Math.max(Be(Dt.lastMessageAt),Be(Dt.updatedAt));return Math.max(Be(Xt.lastMessageAt),Be(Xt.updatedAt))-mn})[0];Xe?(Xe.modelProvider&&Xe.modelId?(S("model"),M(`${Xe.modelProvider}/${Xe.modelId}`)):(S("agent"),x(Xe.agentId)),Ge.current=!0,qt(Xe)):Ge.current=!1,yt.current=!0},[g,qt,gn,cn]),i.useEffect(()=>{if(!g){Mt.current="";return}if(!yt.current&&gn.length===0&&tt.current&&!ft.current)return;if(!ee){Mt.current="";return}if(He.current){Mt.current=ee;return}const Be=ee===Mt.current&&!Vt&&!cn;if(Ge.current){Ge.current=!1,Mt.current=ee;return}if(!(ee===Mt.current&&!Be)){if(Mt.current=ee,j==="model"&&xn){we(xn.modelProvider,xn.modelId);return}j==="agent"&&C&&rn(C)}},[g,j,xn,C,ee,Vt,cn,we,rn,He]),i.useEffect(()=>{g||(U(!1),X(""),Ve(-1),ie(!1),Z(""),Q(0),nn.current.forEach(ne=>{ne.previewUrl&&URL.revokeObjectURL(ne.previewUrl)}),Fe([]))},[g]),i.useEffect(()=>{nn.current=Te},[Te]),i.useEffect(()=>{if(!g){Ht.current=!1;return}typeof window>"u"||(Ht.current=window.innerWidth<=Rs)},[g]),i.useEffect(()=>{if(!g||qe||!Ht.current)return;const ne=Tt.current;if(!ne)return;const Be=document.activeElement,Xe=Be?Ae.current?.contains(Be):!1,Dt=Be===document.body,Xt=Be===le.current;if(!Xe&&!Dt&&!Xt){Ht.current=!1;return}if(Xt){ne.focus({preventScroll:!0}),Ht.current=!1;return}const mn=requestAnimationFrame(()=>{ne.focus(),Ht.current=!1});return()=>cancelAnimationFrame(mn)},[g,qe]),i.useEffect(()=>()=>{nn.current.forEach(ne=>{ne.previewUrl&&URL.revokeObjectURL(ne.previewUrl)})},[]);const _e=i.useCallback(()=>{R(!0),E("model"),G(h[0]?.id??""),A(L||$||"")},[h,$,L]),Rt=i.useMemo(()=>h.find(ne=>ne.id===C)??null,[h,C]),Ot=i.useMemo(()=>{const ne=ye.trim().toLowerCase();return(ne?de.filter(Xe=>Xe.name.toLowerCase().includes(ne)):de).slice(0,10)},[de,ye]),Lt=i.useMemo(()=>{const ne=h.filter(Dt=>oy(Dt.name,F));if(!u)return ne;const Be=ne.filter(Dt=>u.memberIds.has(Dt.id));if(F.trim().length===0)return Be;const Xe=ne.filter(Dt=>!u.memberIds.has(Dt.id));return[...Be,...Xe]},[h,F,u]),fn=i.useMemo(()=>{const ne=new Map;for(const Be of h)ne.set(Be.name.toLowerCase(),Be);return ne},[h]);i.useEffect(()=>{Q(0)},[Ot]),i.useEffect(()=>{Ue(0)},[F,re]),i.useEffect(()=>()=>{xe.current!==null&&(window.clearTimeout(xe.current),xe.current=null),dt.current!==null&&(window.clearTimeout(dt.current),dt.current=null)},[]),i.useEffect(()=>{if(!g)return;const ne=Xe=>{const Dt=Xe.target;Ae.current?.contains(Dt)||pt.current?.contains(Dt)||Dt.closest(".model-combobox-dropdown--portal")||w(!1)},Be=Xe=>{Xe.key==="Escape"&&w(!1)};return document.addEventListener("mousedown",ne),document.addEventListener("keydown",Be),()=>{document.removeEventListener("mousedown",ne),document.removeEventListener("keydown",Be)}},[g,w]);const kn=i.useCallback(()=>{const ne=Ct.current;if(!ne)return;const Xe=ne.scrollTop+ne.clientHeight>=ne.scrollHeight-50;pe(!Xe),xt.current=!Xe},[]),es=i.useCallback(ne=>{if(!ne.isConnected)return;let Be=0,Xe=0,Dt=-1;const Xt=6,mn=()=>{if(ne.isConnected){if(ne.scrollTop=ne.scrollHeight,ne.scrollHeight===Dt?Xe+=1:(Xe=0,Dt=ne.scrollHeight),Be+=1,Be>=Xt||Xe>=2){pe(!1),xt.current=!1;return}window.requestAnimationFrame(mn)}};mn()},[]),ms=i.useCallback(()=>{const ne=Ct.current;ne&&es(ne)},[es]);i.useLayoutEffect(()=>{const ne=Vt?.id??null,Be=zt.current;if(zt.current={isOpen:g,sessionId:ne},!g||!ne)return;const Xe=!Be.isOpen&&g,Dt=Be.isOpen&&Be.sessionId!==ne;if(!Xe&&!Dt)return;const Xt=Ct.current;Xt&&es(Xt)},[g,Vt?.id,es]),i.useEffect(()=>{if(!y||!g||!Vt)return;const ne=()=>{const Xe=Ct.current;Xe&&es(Xe)},Be=()=>{document.visibilityState==="visible"&&ne()};return document.addEventListener("visibilitychange",Be),window.addEventListener("pageshow",ne),()=>{document.removeEventListener("visibilitychange",Be),window.removeEventListener("pageshow",ne)}},[y,g,Vt,es]),i.useEffect(()=>{g&&(xt.current||ms())},[hn,pn,an,un,g,ms]);const Gn=i.useMemo(()=>{const ne=new Map(h.map(Xe=>[Xe.id,Xe.name?.trim()||Xe.id])),Be=new Map(P.map(Xe=>[`${Xe.provider}/${Xe.id}`,Xe.name?.trim()||""]));return gn.map((Xe,Dt)=>{const Xt=Xe.title?.trim()||`Session ${Dt+1}`;let mn=null;if(Xe.agentId&&Xe.agentId!==wr)mn=ne.get(Xe.agentId)||Xe.agentId;else if(Xe.modelProvider&&Xe.modelId){const qn=`${Xe.modelProvider}/${Xe.modelId}`,Dn=Be.get(qn);mn=Dn?`${Dn} [${qn}]`:qn}return{id:Xe.id,label:mn?`${Xt} — ${mn}`:Xt}})},[h,P,gn]),hs=i.useMemo(()=>j==="agent"?Rt?`Message ${Rt.name||Rt.id}`:"Select an agent to start chatting":ce?`Message ${ce}`:"Select a model to start chatting",[j,Rt,ce]),Cn=i.useCallback(ne=>{const Be=gn.find(Xe=>Xe.id===ne);Be&&(yt.current=!0,Be.modelProvider&&Be.modelId?(S("model"),M(`${Be.modelProvider}/${Be.modelId}`)):(S("agent"),x(Be.agentId)),qt(Be))},[qt,gn]),Bt=i.useCallback(async()=>{if(!cn){if(yt.current=!0,O==="agent"){if(!_)return;S("agent"),x(_),await ze(_)}else{const ne=bo(H||L||$);if(!ne)return;S("model"),M(`${ne.modelProvider}/${ne.modelId}`),await ze(wr,ne.modelProvider,ne.modelId)}await rt(),R(!1),E("model")}},[$,_,O,H,rt,L,cn,ze]),Bn=Kt.length>50?`${Kt.slice(0,50)}…`:Kt,En=i.useCallback(ne=>{if(!ne||ne.length===0)return;const Be=[];for(let Xe=0;Xe<ne.length;Xe+=1){const Dt=ne[Xe];nz(Dt)&&Be.push({file:Dt,previewUrl:tz(Dt)?URL.createObjectURL(Dt):""})}Be.length>0&&Fe(Xe=>[...Xe,...Be])},[]),bs=i.useCallback(ne=>{Fe(Be=>{const Xe=Be[ne];return Xe?.previewUrl&&URL.revokeObjectURL(Xe.previewUrl),Be.filter((Dt,Xt)=>Xt!==ne)})},[]),$s=i.useCallback(ne=>{En(ne.clipboardData?.files)},[En]),ss=i.useCallback(()=>{if(typeof window>"u"||window.innerWidth>Rs)return;const ne=Tt.current;!ne||ne.disabled||ne.focus({preventScroll:!0})},[]),Un=i.useCallback(()=>{typeof window>"u"||window.innerWidth>Rs||(ae.current=!0)},[]),Kn=i.useCallback(async()=>{const ne=N.trim(),Be=nn.current;if(!(!ne&&Be.length===0)&&!qe){if(W(""),U(!1),X(""),Ve(-1),ne==="/help"){oe(!0),ss(),ae.current=!1;return}if(ne==="/clear"||ne==="/new"){Qt(),Jt(),Be.forEach(Xe=>{Xe.previewUrl&&URL.revokeObjectURL(Xe.previewUrl)}),Fe(Xe=>Xe.filter(Dt=>!Be.includes(Dt)));try{if(j==="model"){const Xe=bo(sn);if(!Xe)return;await ze(wr,Xe.modelProvider,Xe.modelId)}else C&&await ze(C)}catch{n("Failed to clear conversation","error")}finally{ss(),ae.current=!1}return}try{oe(!1),await Yt(ne,Be.map(Xe=>Xe.file)),Be.forEach(Xe=>{Xe.previewUrl&&URL.revokeObjectURL(Xe.previewUrl)}),Fe(Xe=>Xe.filter(Dt=>!Be.includes(Dt)))}catch{}finally{ss(),ae.current=!1}}},[n,j,Jt,ss,qe,N,sn,C,Yt,ze,Qt]),Ms=i.useCallback(ne=>{ne.preventDefault(),Je.current+=1,We(!0)},[]),xs=i.useCallback(ne=>{ne.preventDefault(),ne.dataTransfer.dropEffect="copy",We(!0)},[]),As=i.useCallback(ne=>{ne.preventDefault(),Je.current=Math.max(0,Je.current-1),Je.current===0&&We(!1)},[]),vs=i.useCallback(ne=>{ne.preventDefault(),Je.current=0,We(!1),En(ne.dataTransfer?.files)},[En]),te=i.useCallback((ne,Be)=>{const Xe=XF(ne,Be);if(Xe){U(!0),X(Xe.filter),Ve(Xe.start);return}U(!1),X(""),Ve(-1)},[]),Ee=i.useCallback(ne=>{W(Be=>{const Xe=Ig(Be);if(!Xe)return Be;const Dt=`/skill:${ne.name} `,Xt=Be.slice(0,Xe.start)+Dt+Be.slice(Xe.end);return window.requestAnimationFrame(()=>{Tt.current&&Tt.current.focus()}),Xt}),ie(!1),Z(""),Q(0)},[]),T=i.useCallback(ne=>{const Be=Tt.current;if(!Be||se<0)return;const Xe=Be.selectionStart??ot.current,Dt=Be.selectionEnd??Xe,Xt=Math.max(Xe,Dt),mn=Math.min(se,Xt),Dn=`${`@${ne.name.replace(/\s+/g,"_")}`} `,ts=N.slice(0,mn)+Dn+N.slice(Xt),Vn=mn+Dn.length;W(ts),U(!1),X(""),Ue(0),Ve(-1),window.requestAnimationFrame(()=>{Tt.current&&(Tt.current.focus(),Tt.current.setSelectionRange(Vn,Vn))})},[se,N]),je=i.useCallback(ne=>{const Be=ne.target.value,Xe=ne.target.selectionStart??Be.length;ot.current=Xe,W(Be),Ke&&Be.trim().length>0&&oe(!1),te(Be,Xe);const Dt=Ig(Be);Dt?(ie(!0),Z(Dt.filter)):(ie(!1),Z("")),et.detectMention(Be,Xe),De(et.mentionActive),et.mentionActive&&vt(ne.target)},[Ke,te,et,vt]),Pe=i.useCallback(()=>{if(ae.current){window.requestAnimationFrame(()=>{ss()});return}typeof window<"u"&&window.innerWidth<=Rs&&Ae.current&&(Qe.current=!0,Ae.current.style.removeProperty("--vv-height"),Ae.current.style.removeProperty("--vv-offset-top"),window.setTimeout(()=>{Qe.current=!1},450)),xe.current!==null&&window.clearTimeout(xe.current),xe.current=window.setTimeout(()=>{U(!1),X(""),Ve(-1),De(!1),et.dismissMention(),xe.current=null},120),dt.current!==null&&window.clearTimeout(dt.current),dt.current=window.setTimeout(()=>{ie(!1),dt.current=null},120)},[et,ss]),st=i.useCallback(()=>{Qe.current=!1,xe.current!==null&&(window.clearTimeout(xe.current),xe.current=null),dt.current!==null&&(window.clearTimeout(dt.current),dt.current=null)},[]),gt=i.useCallback(ne=>{const Be=ne.currentTarget,Xe=Be.selectionStart??Be.value.length;ot.current=Xe,te(Be.value,Xe),et.detectMention(Be.value,Xe),De(et.mentionActive),et.mentionActive&&vt(Be)},[te,et,vt]),Et=i.useCallback(ne=>{ne.key!=="Escape"&&gt(ne)},[gt]),Pt=i.useCallback(ne=>{ct(Be=>{const Xe=new Set(Be);return Xe.has(ne)?Xe.delete(ne):Xe.add(ne),Xe})},[]),dn=i.useCallback((ne,Be=!1)=>Be?t.jsx("div",{className:"quick-chat-message-content quick-chat-message-content--plain",children:ne}):t.jsx("div",{className:"quick-chat-message-content quick-chat-message-content--markdown",children:t.jsx(hi,{remarkPlugins:[pi],components:uy,children:ne})}),[]),Nn=i.useCallback(ne=>{if(ot.current=ne.currentTarget.selectionStart??ot.current,et.mentionActive&&et.files.length>0){if(et.handleKeyDown(ne,N),ne.key==="Enter"||ne.key==="Tab"){const Be=et.files[et.selectedIndex];if(Be){const Xe=et.selectFile(Be,N);W(Xe),et.dismissMention(),De(!1)}}return}if(re&&ne.key==="ArrowDown"){ne.preventDefault(),Lt.length>0&&Ue(Be=>(Be+1)%Lt.length);return}if(re&&ne.key==="ArrowUp"){ne.preventDefault(),Lt.length>0&&Ue(Be=>Be===0?Lt.length-1:Be-1);return}if(re&&ne.key==="Enter"){ne.preventDefault();const Be=Lt[be]??Lt[0];Be&&T(Be);return}if(re&&ne.key==="Escape"){ne.preventDefault(),ne.stopPropagation(),U(!1),X(""),Ve(-1);return}if(Me&&Ot.length>0&&ne.key==="ArrowDown"){ne.preventDefault(),Q(Be=>(Be+1)%Ot.length);return}if(Me&&Ot.length>0&&ne.key==="ArrowUp"){ne.preventDefault(),Q(Be=>Be===0?Ot.length-1:Be-1);return}if(Me&&(ne.key==="Enter"||ne.key==="Tab")){ne.preventDefault();const Be=Ot[fe]??Ot[0];Be&&Ee(Be);return}if(Me&&ne.key==="Escape"){ne.preventDefault(),ie(!1),Z("");return}ne.key!=="Enter"||ne.shiftKey||(ne.preventDefault(),Kn())},[re,Lt,be,T,Kn,et,N,Me,Ot,fe,Ee]),Hn=i.useCallback(()=>{if(Oe.current){Oe.current=!1;return}if(g){w(!1);return}typeof window<"u"&&window.innerWidth<=Rs&&le.current?.focus({preventScroll:!0}),w(!0)},[g,w]);return t.jsxs(t.Fragment,{children:[t.jsx("input",{ref:le,type:"text",className:"quick-chat-stealth-input","aria-hidden":"true",tabIndex:-1}),s&&t.jsx("button",{ref:pt,type:"button",className:"quick-chat-fab","aria-label":"Open quick chat","data-testid":"quick-chat-fab","data-dragging":nt?"true":"false",style:{right:ke.x,bottom:ke.y},onPointerDown:bt,onClick:Hn,children:t.jsx(Ki,{size:24})}),g&&t.jsxs("div",{className:`quick-chat-panel${y&&v?" quick-chat-panel--keyboard-open":""}`,ref:Ae,"data-testid":"quick-chat-panel",style:{...ln?{right:ke.x+At.right,bottom:kt+At.bottom,width:wt.width,height:wt.height}:{}},children:[ln&&t.jsxs(t.Fragment,{children:[t.jsx("div",{className:"quick-chat-resize-handle","data-resize-direction":"n","data-testid":"quick-chat-resize-n",onPointerDown:Ft,role:"separator","aria-orientation":"horizontal","aria-label":"Resize panel from top"}),t.jsx("div",{className:"quick-chat-resize-handle","data-resize-direction":"s","data-testid":"quick-chat-resize-s",onPointerDown:Ft,role:"separator","aria-orientation":"horizontal","aria-label":"Resize panel from bottom"}),t.jsx("div",{className:"quick-chat-resize-handle","data-resize-direction":"e","data-testid":"quick-chat-resize-e",onPointerDown:Ft,role:"separator","aria-orientation":"vertical","aria-label":"Resize panel from right"}),t.jsx("div",{className:"quick-chat-resize-handle","data-resize-direction":"w","data-testid":"quick-chat-resize-w",onPointerDown:Ft,role:"separator","aria-orientation":"vertical","aria-label":"Resize panel from left"}),t.jsx("div",{className:"quick-chat-resize-handle","data-resize-direction":"nw","data-testid":"quick-chat-resize-nw",onPointerDown:Ft,role:"separator","aria-label":"Resize panel from top-left corner"}),t.jsx("div",{className:"quick-chat-resize-handle","data-resize-direction":"ne","data-testid":"quick-chat-resize-ne",onPointerDown:Ft,role:"separator","aria-label":"Resize panel from top-right corner"}),t.jsx("div",{className:"quick-chat-resize-handle","data-resize-direction":"sw","data-testid":"quick-chat-resize-sw",onPointerDown:Ft,role:"separator","aria-label":"Resize panel from bottom-left corner"}),t.jsx("div",{className:"quick-chat-resize-handle","data-resize-direction":"se","data-testid":"quick-chat-resize-se",onPointerDown:Ft,role:"separator","aria-label":"Resize panel from bottom-right corner"})]}),t.jsxs("div",{className:"quick-chat-panel-header",children:[t.jsxs("div",{className:"quick-chat-panel-title-wrap",children:[t.jsx("h3",{children:"Quick Chat"}),j==="model"&&ce&&(()=>{const ne=zn?.provider??wn?.modelProvider??"";return b==="mobile"&&ce.length>12&&ne?t.jsx("span",{className:"quick-chat-model-tag quick-chat-model-tag--icon","data-testid":"quick-chat-model-tag",title:ce,"aria-label":ce,children:t.jsx(On,{provider:ne,size:"sm"})}):t.jsx("span",{className:"quick-chat-model-tag","data-testid":"quick-chat-model-tag",title:ce,children:ce})})()]}),t.jsxs("div",{className:"quick-chat-panel-header-actions",children:[t.jsx("button",{type:"button",className:"btn-icon quick-chat-new-chat-btn","data-testid":"quick-chat-new-thread","aria-label":"Start a new chat",onClick:_e,disabled:cn,children:t.jsx(Tn,{size:16})}),t.jsx("button",{type:"button",className:"btn-icon","aria-label":"Close quick chat","data-testid":"quick-chat-close",onClick:()=>w(!1),children:t.jsx(bn,{size:16})})]})]}),t.jsxs("div",{className:"quick-chat-panel-agent-select","data-testid":"quick-chat-session-select",children:[t.jsx("label",{htmlFor:"quick-chat-session-select",className:"visually-hidden",children:"Select session"}),t.jsxs("select",{id:"quick-chat-session-select",value:Vt?.id??"",onChange:ne=>Cn(ne.target.value),"data-testid":"quick-chat-session-dropdown",children:[t.jsx("option",{value:"",disabled:!0,children:cn?"Loading sessions…":"Select a session"}),Gn.map(ne=>t.jsx("option",{value:ne.id,children:ne.label},ne.id))]})]}),k&&t.jsxs("div",{className:"quick-chat-new-session-chooser","data-testid":"quick-chat-new-session-chooser",children:[t.jsxs("div",{className:"quick-chat-inline-mode-toggle","data-testid":"quick-chat-inline-mode-toggle",children:[t.jsx("button",{type:"button",className:`quick-chat-mode-btn${O==="model"?" quick-chat-mode-btn--active":""}`,"data-testid":"quick-chat-inline-mode-model",onClick:()=>E("model"),children:"Model"}),t.jsx("button",{type:"button",className:`quick-chat-mode-btn${O==="agent"?" quick-chat-mode-btn--active":""}`,"data-testid":"quick-chat-inline-mode-agent",onClick:()=>E("agent"),children:"Agent"})]}),O==="agent"?t.jsxs("div",{className:"quick-chat-panel-agent-select",children:[t.jsx("label",{htmlFor:"quick-chat-new-agent-select",className:"visually-hidden",children:"Select agent for new chat"}),t.jsx("select",{id:"quick-chat-new-agent-select",value:_,onChange:ne=>G(ne.target.value),"data-testid":"quick-chat-new-agent-select",children:h.map(ne=>t.jsx("option",{value:ne.id,children:KF(ne)},ne.id))})]}):t.jsx("div",{className:"quick-chat-panel-agent-select","data-testid":"quick-chat-new-model-select",children:t.jsx(Ns,{id:"quick-chat-new-model-select",models:P,value:H,onChange:A,label:"Select model override",placeholder:Y?"Loading models…":"Select a model",disabled:Y||P.length===0,favoriteProviders:o,favoriteModels:l,onToggleFavorite:c,onToggleModelFavorite:d})}),t.jsxs("div",{className:"quick-chat-new-session-actions",children:[t.jsx("button",{type:"button",className:"btn","data-testid":"quick-chat-new-session-cancel",onClick:()=>{R(!1),E("model")},children:"Cancel"}),t.jsx("button",{type:"button",className:"btn btn-primary","data-testid":"quick-chat-new-session-submit",onClick:()=>void Bt(),disabled:cn||(O==="agent"?!_:!bo(H||L||$)),children:"Create"})]})]}),t.jsx("div",{className:"quick-chat-panel-messages",ref:Ct,"data-testid":"quick-chat-messages",onScroll:kn,children:cn?t.jsx("div",{className:"quick-chat-panel-empty",children:"Loading conversation…"}):un?t.jsxs(t.Fragment,{children:[hn.map(ne=>t.jsx(Tg,{message:ne,forcePlain:ne.role!=="user"&&Le.has(ne.id),mentionAgentsByName:fn,roomContext:u,onToggleRender:Pt},ne.id)),Ke&&t.jsx("div",{className:"quick-chat-panel-message quick-chat-panel-message--received","data-testid":"quick-chat-help-message",children:dn("Available commands:\n- `/new` or `/clear` — Clear conversation and start fresh\n- `/skill:{name}` — Use a specific skill\n- `/help` — Show this help")}),t.jsxs("div",{className:"quick-chat-panel-message quick-chat-panel-message--received quick-chat-panel-message--streaming","data-testid":"quick-chat-streaming-message",children:[pn?t.jsxs(t.Fragment,{children:[t.jsx("div",{"data-testid":"quick-chat-streaming-text",children:dn(pn,Le.has("__streaming__"))}),t.jsx("button",{type:"button",className:`quick-chat-message-render-toggle${Le.has("__streaming__")?" quick-chat-message-render-toggle--plain":""}`,"data-testid":"quick-chat-message-render-toggle","aria-label":Le.has("__streaming__")?"Show rendered markdown":"Show plain text",onClick:()=>Pt("__streaming__"),children:Le.has("__streaming__")?t.jsx(qu,{size:14}):t.jsx(zr,{size:14})})]}):t.jsx("p",{className:"quick-chat-panel-waiting","data-testid":"quick-chat-waiting",children:an?"Thinking…":"Connecting…"}),dy(Wt,!0),an&&t.jsxs("details",{className:"chat-message-thinking","data-testid":"quick-chat-streaming-thinking",children:[t.jsx("summary",{children:"Thinking"}),t.jsx("pre",{className:"chat-message-thinking-content",children:an})]})]})]}):tn?t.jsx("div",{className:"quick-chat-panel-empty",children:"Loading conversation…"}):hn.length===0&&!pn&&!an&&!un&&!Ke?t.jsx("div",{className:"quick-chat-panel-empty",children:"No messages yet. Start the conversation!"}):t.jsxs(t.Fragment,{children:[hn.map(ne=>t.jsx(Tg,{message:ne,forcePlain:ne.role!=="user"&&Le.has(ne.id),mentionAgentsByName:fn,roomContext:u,onToggleRender:Pt},ne.id)),Ke&&t.jsx("div",{className:"quick-chat-panel-message quick-chat-panel-message--received","data-testid":"quick-chat-help-message",children:dn("Available commands:\n- `/new` or `/clear` — Clear conversation and start fresh\n- `/skill:{name}` — Use a specific skill\n- `/help` — Show this help")})]})}),he&&t.jsxs("button",{type:"button",className:"btn btn-sm quick-chat-jump-to-latest","data-testid":"quick-chat-jump-to-latest",onClick:ms,children:[t.jsx(vn,{size:14}),"Latest"]}),Te.length>0&&t.jsx("div",{className:"quick-chat-attachment-previews","data-testid":"quick-chat-attachment-previews",children:Te.map((ne,Be)=>t.jsxs("div",{className:"quick-chat-attachment-preview","data-testid":`quick-chat-attachment-preview-${Be}`,children:[ne.previewUrl?t.jsx("img",{src:ne.previewUrl,alt:ne.file.name}):t.jsx("span",{className:"quick-chat-attachment-preview-name",children:ne.file.name}),t.jsx("button",{type:"button",className:"quick-chat-attachment-remove","data-testid":`quick-chat-attachment-remove-${Be}`,"aria-label":`Remove ${ne.file.name}`,onClick:()=>bs(Be),children:"×"})]},`${ne.file.name}-${Be}`))}),t.jsx("div",{className:"quick-chat-panel-input",children:t.jsxs("div",{className:`quick-chat-input-wrapper${mt?" quick-chat-input-wrapper--dragover":""}`,onDragEnter:Ms,onDragOver:xs,onDragLeave:As,onDrop:vs,children:[t.jsx("input",{ref:Gt,type:"file",accept:"image/*,.txt,.json,.yaml,.yml,.log,.csv,.xml,.md",multiple:!0,tabIndex:-1,"aria-hidden":"true",className:"quick-chat-attachment-input",onChange:ne=>{En(ne.target.files),ne.target.value=""}}),t.jsxs("div",{className:"quick-chat-input-row","data-testid":"quick-chat-input-row",children:[t.jsx("button",{type:"button",className:"btn-icon quick-chat-attach-btn","data-testid":"quick-chat-attach-btn","aria-label":"Attach files",onClick:()=>Gt.current?.click(),children:t.jsx(pb,{size:16})}),t.jsx("input",{ref:Tt,type:"text",value:N,onChange:je,onKeyDown:Nn,onKeyUp:Et,onClick:gt,onBlur:Pe,onFocus:st,onPaste:$s,onTouchStart:ne=>{typeof window>"u"||window.innerWidth>Rs||document.activeElement!==ne.currentTarget&&(ne.preventDefault(),ne.currentTarget.focus({preventScroll:!0}))},placeholder:hs,disabled:qe,"data-testid":"quick-chat-input"}),un?t.jsx("button",{type:"button",className:"chat-input-stop quick-chat-send-btn",onPointerDown:ne=>{typeof window>"u"||window.innerWidth>Rs||(ne.preventDefault(),ne.pointerType&&ne.pointerType!=="mouse"&&(on.current=!0,Qt()))},onTouchStart:ne=>{typeof window>"u"||window.innerWidth>Rs||(ne.preventDefault(),on.current=!0,Qt())},onMouseDown:ne=>{typeof window>"u"||window.innerWidth>Rs||ne.preventDefault()},onClick:()=>{if(on.current){on.current=!1;return}Qt()},"aria-label":"Stop generation","data-testid":"quick-chat-stop",children:t.jsx(Pi,{size:14})}):t.jsx("button",{type:"button",className:"quick-chat-send-btn",onPointerDown:ne=>{typeof window>"u"||window.innerWidth>Rs||(ne.preventDefault(),ne.pointerType&&ne.pointerType!=="mouse"&&(on.current=!0,Un(),ss(),Kn()))},onTouchStart:ne=>{typeof window>"u"||window.innerWidth>Rs||(ne.preventDefault(),on.current=!0,Un(),ss(),Kn())},onMouseDown:ne=>{typeof window>"u"||window.innerWidth>Rs||ne.preventDefault()},onClick:()=>{if(on.current){on.current=!1;return}Kn()},disabled:qe||N.trim().length===0&&Te.length===0,"data-testid":"quick-chat-send",children:t.jsx(Da,{size:16})})]}),t.jsx(OF,{agents:h,filter:F,highlightedIndex:be,visible:re,onSelect:T,position:"above",roomMemberIds:u?.memberIds,roomName:u?.roomName}),t.jsx(VF,{visible:et.mentionActive&&!re,position:ut,files:et.files,selectedIndex:et.selectedIndex,onSelect:ne=>{const Be=et.selectFile(ne,N);W(Be),et.dismissMention(),De(!1),Tt.current?.focus()},loading:et.loading}),Me&&t.jsx("div",{className:"chat-skill-menu","data-testid":"quick-chat-skill-menu",role:"listbox","aria-label":"Skill suggestions",children:Ne?t.jsx("div",{className:"chat-skill-menu-empty",children:"Loading skills…"}):Ot.length===0?t.jsx("div",{className:"chat-skill-menu-empty",children:ye?"No skills found":"No skills available"}):Ot.map((ne,Be)=>t.jsxs("button",{type:"button",role:"option","aria-selected":Be===fe,className:`chat-skill-menu-item${Be===fe?" chat-skill-menu-item--highlighted":""}`,onMouseDown:Xe=>Xe.preventDefault(),onMouseEnter:()=>Q(Be),onClick:()=>Ee(ne),children:[t.jsx("span",{className:"chat-skill-menu-item-name",children:ne.name}),t.jsx("span",{className:"chat-skill-menu-item-description",title:ne.relativePath,children:ne.relativePath})]},ne.id))}),Kt&&t.jsxs("div",{className:"chat-pending-message","data-testid":"chat-pending-indicator",children:[t.jsx("span",{children:`Queued: ${Bn}`}),t.jsx("button",{type:"button",className:"chat-pending-message-dismiss","aria-label":"Dismiss queued message","data-testid":"chat-pending-dismiss",onClick:Jt,children:"×"})]})]})})]})]})}function xo(e){if(!e)return 0;const n=Date.parse(e);return Number.isFinite(n)?n:0}function Pg(e){return e.status==="generating"||e.status==="awaiting_input"}function vo(e){return e==="complete"||e==="error"}function rz(e){const[n,s]=i.useState([]),a=i.useRef(new Map),r=i.useRef(new Map),{sessions:o,broadcastUpdate:l,broadcastCompleted:c,requestSync:d}=Gr(),u=i.useCallback(()=>{Xu(e).then(p=>{const g=p.filter(v=>{const b=xo(v.updatedAt),y=r.current.get(v.id);return y===void 0?!0:b<=y?!1:(r.current.delete(v.id),!0)}),w=new Map;for(const v of g)w.set(v.id,xo(v.updatedAt));a.current=w,s(g)}).catch(p=>{console.warn("[useBackgroundSessions] Failed to fetch AI sessions:",p)})},[e]);i.useEffect(()=>{d(),u()},[u,d]),i.useEffect(()=>{s(p=>{if(o.size===0)return p;let g=!1;const w=new Map(p.map(v=>[v.id,v]));for(const v of o.values()){if(e&&v.projectId&&v.projectId!==e)continue;const b=v.lastEventTimestamp,y=a.current.get(v.sessionId)??0;if(b<y)continue;const j=r.current.get(v.sessionId);if(j!==void 0&&b<=j)continue;if(j!==void 0&&b>j&&!vo(v.status)&&r.current.delete(v.sessionId),vo(v.status)){w.delete(v.sessionId)&&(g=!0),a.current.set(v.sessionId,b);continue}const S=w.get(v.sessionId),C=v.type??S?.type,x=v.title??S?.title;if(!S&&(!C||!x))continue;const k={id:v.sessionId,type:C??"planning",status:v.status,title:x??"AI Session",projectId:v.projectId??S?.projectId??e??null,lockedByTab:v.owningTabId??S?.lockedByTab??null,updatedAt:v.updatedAt??S?.updatedAt??new Date(b).toISOString()},R=w.get(v.sessionId);(!R||R.status!==k.status||R.title!==k.title||R.type!==k.type||R.projectId!==k.projectId||R.lockedByTab!==k.lockedByTab||R.updatedAt!==k.updatedAt)&&(w.set(v.sessionId,k),a.current.set(v.sessionId,b),g=!0)}return g?[...w.values()].sort((v,b)=>xo(b.updatedAt)-xo(v.updatedAt)):p})},[e,o]),i.useEffect(()=>{const p=e?`?projectId=${encodeURIComponent(e)}`:"",g=v=>{try{const b=JSON.parse(v.data),y=xo(b.updatedAt)||Date.now();s(j=>{const S=a.current.get(b.id)??0;if(y<S)return j;const C=r.current.get(b.id);if(C!==void 0&&y<=C)return j;if(C!==void 0&&y>C&&!vo(b.status)&&r.current.delete(b.id),a.current.set(b.id,y),vo(b.status))return j.filter(k=>k.id!==b.id);const x=j.findIndex(k=>k.id===b.id);if(x>=0){const k=[...j];return k[x]=b,k}return Pg(b)?[b,...j]:j}),l({sessionId:b.id,status:b.status,needsInput:b.status==="awaiting_input",type:b.type,title:b.title,projectId:b.projectId,owningTabId:b.lockedByTab,updatedAt:b.updatedAt,timestamp:y}),vo(b.status)&&c({sessionId:b.id,status:b.status,timestamp:y})}catch{}},w=v=>{try{const b=JSON.parse(v.data),y=Date.now();r.current.set(b,y),a.current.set(b,Math.max(a.current.get(b)??0,y)),c({sessionId:b,status:"complete",timestamp:y}),s(j=>j.filter(S=>S.id!==b))}catch{}};return fi(`/api/events${p}`,{events:{"ai_session:updated":g,"ai_session:deleted":w},onReconnect:()=>{u()}})},[c,l,e,u]);const h=i.useCallback(async p=>{const w=n.find(j=>j.id===p)?.type,v=Ya();let b=!1;if(w==="planning")try{await Mb(p,e,v)}catch(j){b=!0,j instanceof Error&&j.message.includes("locked")&&console.warn(`[useBackgroundSessions] Forcing dismiss of planning session ${p} despite lock by another tab`)}else if(w==="subtask")try{await Ib(p,e,v)}catch(j){b=!0,j instanceof Error&&j.message.includes("locked")&&console.warn(`[useBackgroundSessions] Forcing dismiss of subtask session ${p} despite lock by another tab`)}else if(w==="mission_interview")try{await Lb(p,e,v)}catch(j){b=!0,j instanceof Error&&j.message.includes("locked")&&console.warn(`[useBackgroundSessions] Forcing dismiss of mission interview session ${p} despite lock by another tab`)}b&&console.warn(`[useBackgroundSessions] Cancellation failed for session ${p}, attempting delete anyway`);const y=Date.now();r.current.set(p,y),a.current.set(p,Math.max(a.current.get(p)??0,y)),c({sessionId:p,status:"complete",timestamp:y});try{await Ob(p)}catch{}s(j=>j.filter(S=>S.id!==p))},[c,e,n]),m=i.useMemo(()=>n.filter(p=>Pg(p)),[n]),f=i.useMemo(()=>m.filter(p=>p.type==="planning"),[m]);return{sessions:m,generating:m.filter(p=>p.status==="generating").length,needsInput:m.filter(p=>p.status==="awaiting_input").length,planningSessions:f,dismissSession:h,refresh:u}}const pc="fusion:hide-session-banners",Bu="fusion:session-banner-pref-changed";function oz(){if(typeof window>"u")return!1;try{return window.localStorage.getItem(pc)==="1"}catch{return!1}}function lz(e){if(typeof window>"u")return()=>{};const n=a=>{a.key===pc&&e()},s=()=>e();return window.addEventListener("storage",n),window.addEventListener(Bu,s),()=>{window.removeEventListener("storage",n),window.removeEventListener(Bu,s)}}function tB(e){if(!(typeof window>"u"))try{e?window.localStorage.setItem(pc,"1"):window.localStorage.removeItem(pc),window.dispatchEvent(new Event(Bu))}catch{}}function cz(){return i.useSyncExternalStore(lz,oz,()=>!1)}function ys(e){return{...e,column:wb(e.column),dependencies:Array.isArray(e.dependencies)?e.dependencies:[],steps:Array.isArray(e.steps)?e.steps:[],log:Array.isArray(e.log)?e.log:[]}}function $g(e,n){return!e&&!n?0:e?n?e.localeCompare(n):1:-1}function dz(e,n){return{...n,columnMovedAt:e.columnMovedAt??n.columnMovedAt,executionStartedAt:e.executionStartedAt??n.executionStartedAt,executionCompletedAt:e.executionCompletedAt??n.executionCompletedAt,worktree:n.worktree??e.worktree,modifiedFiles:n.modifiedFiles??e.modifiedFiles,timedExecutionMs:n.timedExecutionMs??e.timedExecutionMs,workflowStepResults:n.workflowStepResults??e.workflowStepResults,tokenUsage:n.tokenUsage??e.tokenUsage,mergeDetails:n.mergeDetails??e.mergeDetails}}function eu(e,n){if($g(n.updatedAt,e.updatedAt)<0)return e;if(e.column===n.column)return dz(e,n);const a=$g(e.columnMovedAt,n.columnMovedAt);return e.columnMovedAt&&!n.columnMovedAt?{...n,column:e.column,columnMovedAt:e.columnMovedAt}:a>=0?{...n,column:e.column,columnMovedAt:e.columnMovedAt}:n}function uz(e){const n=e?.projectId,s=e?.searchQuery,a=e?.sseEnabled??!0,[r,o]=i.useState([]),[l,c]=i.useState(!1),d=i.useRef(l);d.current=l;const u=i.useRef(r),h=i.useRef(0),m=i.useRef(0),f=i.useRef(s),p=i.useRef(null),g=i.useRef(void 0),w=i.useRef(0),v=i.useRef(n);u.current=r,f.current=s,v.current!==n&&(v.current=n,w.current++);const b=1e3,y=i.useCallback(async L=>{const M=++h.current,$=n,D=L?.searchQueryOverride??f.current,N=L?.includeArchivedOverride??d.current;try{const W=await uN(void 0,void 0,$,D,N);if(h.current!==M||n!==$)return;o(W.map(ys)),g.current=Date.now()}catch{if(h.current!==M||n!==$)return;if(L?.clearOnError){o([]);return}o(W=>W)}},[n]);p.current=y;const j=i.useCallback(async()=>{d.current||(c(!0),d.current=!0,await p.current({includeArchivedOverride:!0}))},[]),S=i.useRef(s);i.useEffect(()=>{if(s===void 0&&S.current===void 0)return;S.current=s;const L=setTimeout(()=>{y({searchQueryOverride:s})},300);return()=>clearTimeout(L)},[s]),i.useEffect(()=>{y({clearOnError:!0});const L=()=>{if(document.visibilityState!=="visible")return;const M=Date.now();M-m.current<b||(m.current=M,y())};return document.addEventListener("visibilitychange",L),()=>{document.removeEventListener("visibilitychange",L)}},[y]),i.useEffect(()=>{if(a===!1)return;const L=w.current,M=n?`?projectId=${encodeURIComponent(n)}`:"",$=()=>w.current!==L;let D=!0;const N=Me=>{if($())return;const ie=ys(JSON.parse(Me.data));if(f.current){p.current({searchQueryOverride:f.current});return}o(ye=>{const Z=ye.findIndex(X=>X.id===ie.id);if(Z===-1)return[...ye,ie];const fe=ye[Z],Q=eu(fe,ie);if(Q===fe)return ye;const F=[...ye];return F[Z]=Q,F}),g.current=Date.now()},W=Me=>{if($())return;if(f.current){p.current({searchQueryOverride:f.current});return}const{task:ie,to:ye}=JSON.parse(Me.data),Z=ys(ie),fe={...Z,column:wb(ye,Z.column)};o(Q=>{const F=Q.findIndex(re=>re.id===fe.id);if(F===-1)return[...Q,fe];const X=[...Q];return X[F]=fe,X}),g.current=Date.now()},de=Me=>{if($())return;if(f.current){p.current({searchQueryOverride:f.current});return}const ie=ys(JSON.parse(Me.data));o(ye=>{const Z=ye.findIndex(X=>X.id===ie.id);if(Z===-1)return[...ye,ie];const fe=ye[Z],Q=eu(fe,ie);if(Q===fe)return ye;const F=[...ye];return F[Z]=Q,F}),g.current=Date.now()},me=Me=>{if($())return;if(f.current){p.current({searchQueryOverride:f.current});return}const ie=ys(JSON.parse(Me.data));o(ye=>ye.filter(Z=>Z.id!==ie.id))},Ne=Me=>{if($())return;if(f.current){p.current({searchQueryOverride:f.current});return}const{task:ie}=JSON.parse(Me.data),Z={...ys(ie),column:"done"};o(fe=>{const Q=fe.findIndex(X=>X.id===Z.id);if(Q===-1)return[...fe,Z];const F=[...fe];return F[Q]=Z,F})},ve=fi(`/api/events${M}`,{events:{"task:created":N,"task:moved":W,"task:updated":de,"task:deleted":me,"task:merged":Ne},onReconnect:()=>{D&&($()||p.current())}});return()=>{D=!1,ve()}},[n,a]);const C=i.useCallback(async L=>{const M=ys(await Nb(L,n));return o($=>$.some(D=>D.id===M.id)?$:[...$,M]),M},[n]),x=i.useCallback(async(L,M,$)=>ys(await hN(L,M,n,$)),[n]),k=i.useCallback(async L=>ys(await Sb(L,n)),[n]),R=i.useCallback(async L=>ys(await Cb(L,n)),[n]),O=i.useCallback(async(L,M)=>ys(await pN(L,n,M)),[n]),E=i.useCallback(async L=>fN(L,n),[n]),_=i.useCallback(async L=>ys(await gN(L,n)),[n]),G=i.useCallback(async L=>ys(await bN(L,n)),[n]),H=i.useCallback(async L=>{const M=ys(await xN(L,n));return o($=>$.some(D=>D.id===M.id)?$:[...$,M]),M},[n]),A=i.useCallback(async(L,M)=>{const $=u.current.find(N=>N.id===L),D=$?{...$,...M,updatedAt:new Date().toISOString()}:void 0;D&&o(N=>N.map(W=>W.id===L?D:W));try{const N=ys(await Ls(L,M,n));return o(W=>W.map(de=>de.id===L?N:de)),N}catch(N){throw $&&o(W=>W.map(de=>de.id===L?$:de)),N}},[n]),P=i.useCallback(async L=>{const M=ys(await vN(L,n));return o($=>$.map(D=>D.id===L?M:D)),M},[n]),q=i.useCallback(async L=>{const M=ys(await yN(L,n));return o($=>$.map(D=>D.id===L?M:D)),M},[n]),Y=i.useCallback(async()=>{const M=(await wN(n)).map(ys);return o($=>$.map(D=>M.find(W=>W.id===D.id)||D)),M},[n]),ge=i.useCallback(L=>{if(L.length===0)return;if(f.current){p.current({searchQueryOverride:f.current});return}const M=L.map(ys);o($=>{let D=$;for(const N of M){const W=D.findIndex(Ne=>Ne.id===N.id);if(W===-1){D===$&&(D=[...$]),D.push(N);continue}const de=D[W],me=eu(de,N);me!==de&&(D===$&&(D=[...$]),D[W]=me)}return D}),g.current=Date.now()},[]);return{tasks:r,createTask:C,moveTask:x,pauseTask:k,unpauseTask:R,deleteTask:O,mergeTask:E,retryTask:_,resetTask:G,duplicateTask:H,updateTask:A,archiveTask:P,unarchiveTask:q,archiveAllDone:Y,loadArchivedTasks:j,includeArchived:l,ingestCreatedTasks:ge,lastFetchTimeMs:g.current}}const mz=5e3,hz=1e3;function pz(e){const s=($1(e)?e.nodeMappings??e.projectNodeMappings??e.pathMappings??[]:[]).filter(a=>!!a?.nodeId&&!!a?.path).map(a=>({nodeId:a.nodeId,nodeName:a.nodeName,path:a.path,available:a.available!==!1}));return s.length>0?s:e.nodeId&&e.path?[{nodeId:e.nodeId,nodeName:e._sourceNodeName,path:e.path,available:!0}]:[]}function Dg(e){return e.map(n=>({...n,nodeMappings:pz(n)}))}function fz(){const[e,n]=i.useState([]),[s,a]=i.useState(!0),[r,o]=i.useState(null),l=i.useRef(null),c=i.useRef(0),d=i.useCallback(async()=>{try{o(null);const f=await ch();n(Dg(f))}catch(f){o(f instanceof Error?f.message:"Failed to fetch projects")}},[]);i.useEffect(()=>{let f=!1;async function p(){a(!0);const w=performance.now();try{const v=await ch(),b=Dg(v),y=Math.round(performance.now()-w);console.log(`[useProjects] initial fetchProjectsAcrossNodes took ${y}ms (${b.length} projects)`),f||(n(b),o(null))}catch(v){const b=Math.round(performance.now()-w);console.warn(`[useProjects] initial fetch failed after ${b}ms: ${v instanceof Error?v.message:String(v)}`),f||o(v instanceof Error?v.message:"Failed to fetch projects")}finally{f||a(!1)}}p();const g=()=>{if(document.visibilityState!=="visible")return;const w=Date.now();w-c.current<hz||(c.current=w,d())};return document.addEventListener("visibilitychange",g),()=>{f=!0,document.removeEventListener("visibilitychange",g)}},[d]),i.useEffect(()=>{if(!s)return l.current=setInterval(()=>{d()},mz),()=>{l.current&&(clearInterval(l.current),l.current=null)}},[s,d]);const u=i.useCallback(async f=>{const p=await H1(f);return n(g=>[...g,p]),p},[]),h=i.useCallback(async(f,p)=>{const g=await Y1(f,p);return n(w=>w.map(v=>v.id===f?g:v)),g},[]),m=i.useCallback(async f=>{await Pb(f),n(p=>p.filter(g=>g.id!==f))},[]);return{projects:e,loading:s,error:r,refresh:d,register:u,update:h,unregister:m}}const gz="kb-dashboard-current-project";function bz(e){return e??"local"}function xz(e,n={}){const{nodeId:s=null}=n,[a,r]=i.useState(null),[o,l]=i.useState(!0),c=i.useRef(!1),d=i.useRef(!1),u=i.useRef(null),h=bz(s);i.useEffect(()=>{let p=!1;async function g(){try{const w=await Qi();if(p)return;u.current=w.dashboardCurrentProjectIdByNode??{};const v=u.current[h];if(v){const b=e.find(y=>y.id===v);b&&(r(b),c.current=!0)}if(!v)try{const b=localStorage.getItem(gz);if(b){const y=JSON.parse(b);y?.id&&e.some(S=>S.id===y.id)&&(r(y),c.current=!0,u.current={...u.current,[h]:y.id},await Fn({dashboardCurrentProjectIdByNode:u.current}).catch(()=>{}))}}catch{}}catch{}finally{p||l(!1)}}return g(),()=>{p=!0}},[h,e]),i.useEffect(()=>{if(!o){if(a){if(!e.some(w=>w.id===a.id)&&e.length>0){const w=e.find(v=>v.status==="active");r(w||e[0]||null);return}const g={...u.current,[h]:a.id};u.current=g,Fn({dashboardCurrentProjectIdByNode:g}).catch(()=>{})}else if(e.length>0&&!d.current){const p=e.find(g=>g.status==="active");p&&r(p)}}},[a,e,o,h]);const m=i.useCallback(p=>{if(d.current=!1,r(p),p){const g={...u.current,[h]:p.id};u.current=g,Fn({dashboardCurrentProjectIdByNode:g}).catch(()=>{})}},[h]),f=i.useCallback(()=>{d.current=!0,r(null);const p={...u.current};delete p[h],u.current=p,Fn({dashboardCurrentProjectIdByNode:p}).catch(()=>{})},[h]);return{currentProject:a,setCurrentProject:m,clearCurrentProject:f,loading:o}}const my=i.createContext(null);function vz({children:e}){const[n,s]=i.useState([]),a=i.useRef(0),r=i.useRef(new Map),o=i.useCallback(c=>{const d=r.current.get(c);d!==void 0&&(clearTimeout(d),r.current.delete(c)),s(u=>u.filter(h=>h.id!==c))},[]),l=i.useCallback((c,d="info")=>{const u=a.current++;s(m=>[...m,{id:u,message:c,type:d}]);const h=setTimeout(()=>o(u),4e3);r.current.set(u,h)},[o]);return i.useEffect(()=>()=>{r.current.forEach(c=>clearTimeout(c)),r.current.clear()},[]),ga.createElement(my.Provider,{value:{toasts:n,addToast:l,removeToast:o}},e)}function yz(){const e=i.useContext(my);if(!e)throw new Error("useToast must be used within ToastProvider");return e}const hy="kb-dashboard-theme-mode",py="kb-dashboard-color-theme",fy="kb-dashboard-font-scale-pct",Uu=100,wz=85,kz=125,gy=[...Gj],Hu="theme-data",yo="theme-data.css";function jz(){const e=document.baseURI||(typeof document.location<"u"?document.location.href:"");return e?e.startsWith("http://")||e.startsWith("https://")?new URL(`/${yo}`,e).toString():e.startsWith("file://")?e.endsWith("/")?e.slice(0,-1)+`/${yo}`:e.replace(/\/[^/]+$/,`/${yo}`):`/${yo}`:`/${yo}`}const Gs=typeof window<"u",Nz=Gs?i.useLayoutEffect:i.useEffect;function by(e){return e==="dark"||e==="light"||e==="system"}function Lg(){if(!Gs)return"dark";try{const e=localStorage.getItem(hy);if(by(e))return e}catch{}return"dark"}function Og(){if(!Gs)return"default";try{const e=localStorage.getItem(py);if(e&&gy.includes(e))return e}catch{}return"default"}function Fg(e){if(Gs)try{localStorage.setItem(hy,e)}catch{}}function zg(e){if(Gs)try{localStorage.setItem(py,e)}catch{}}function Bo(e){return typeof e!="number"||!Number.isFinite(e)?Uu:Math.min(kz,Math.max(wz,Math.round(e)))}function Bg(){if(!Gs)return Uu;try{const e=Number(localStorage.getItem(fy));return Bo(e)}catch{return Uu}}function Ug(e){if(Gs)try{localStorage.setItem(fy,String(Bo(e)))}catch{}}function Sz(e,n){return e==="system"?n?"dark":"light":e}function Cz(e,n,s,a){if(!Gs)return;const r=Sz(e,a);document.documentElement.setAttribute("data-theme",r),document.documentElement.setAttribute("data-color-theme",n),document.documentElement.style.fontSize=`${Bo(s)}%`}function Hg(){if(!Gs)return;const e=jz(),n=document.getElementById(Hu);if(n){n.href!==e&&(n.href=e),n.parentNode===document.head&&document.head.lastChild!==n&&document.head.appendChild(n);return}const s=document.createElement("link");s.rel="stylesheet",s.href=e,s.id=Hu,document.head.appendChild(s)}function qg(){if(!Gs)return;const e=document.getElementById(Hu);e&&e.remove()}function Ez(){const[e,n]=i.useState(()=>Lg()),[s,a]=i.useState(()=>Og()),[r,o]=i.useState(()=>Bg()),[l,c]=i.useState(!0),[d,u]=i.useState(()=>Gs?window.matchMedia("(prefers-color-scheme: dark)").matches:!0),h=i.useRef(e),m=i.useRef(s),f=i.useRef(r),p=i.useRef(!1),g=i.useRef(!1),w=i.useRef(!1);i.useEffect(()=>{h.current=e},[e]),i.useEffect(()=>{m.current=s},[s]),i.useEffect(()=>{f.current=r},[r]),i.useEffect(()=>{if(!Gs||!l)return;let j=!1;return Qi().then(S=>{if(!j&&(by(S.themeMode)&&!p.current&&(h.current!==S.themeMode&&(h.current=S.themeMode,n(S.themeMode)),Lg()!==S.themeMode&&Fg(S.themeMode)),S.colorTheme&&gy.includes(S.colorTheme)&&!g.current&&(m.current!==S.colorTheme&&(m.current=S.colorTheme,a(S.colorTheme)),Og()!==S.colorTheme&&zg(S.colorTheme)),!w.current)){const C=Bo(S.dashboardFontScalePct);f.current!==C&&(f.current=C,o(C)),Bg()!==C&&Ug(C)}}).catch(S=>{console.warn("[useTheme] Failed to hydrate theme from global settings",S)}).finally(()=>{j||c(!1)}),()=>{j=!0}},[l]),i.useEffect(()=>{if(!Gs)return;const j=window.matchMedia("(prefers-color-scheme: dark)"),S=C=>{u(C.matches)};return j.addEventListener("change",S),()=>j.removeEventListener("change",S)},[]),Nz(()=>{Cz(e,s,r,d)},[e,s,r,d]),i.useEffect(()=>{!Gs||l||(s!=="default"?Hg():qg())},[s,l]);const v=i.useCallback(j=>{p.current=!0,h.current=j,n(j),Fg(j),Fn({themeMode:j}).catch(S=>{console.warn("[useTheme] Failed to persist themeMode to global settings",S)})},[]),b=i.useCallback(j=>{g.current=!0,m.current=j,a(j),zg(j),j!=="default"?Hg():qg(),Fn({colorTheme:j}).catch(S=>{console.warn("[useTheme] Failed to persist colorTheme to global settings",S)})},[]),y=i.useCallback(j=>{const S=Bo(j);w.current=!0,f.current=S,o(S),Ug(S),Fn({dashboardFontScalePct:S}).catch(C=>{console.warn("[useTheme] Failed to persist dashboardFontScalePct to global settings",C)})},[]);return{themeMode:e,colorTheme:s,dashboardFontScalePct:r,setThemeMode:v,setColorTheme:b,setDashboardFontScalePct:y,isSystemDark:d}}function _z(e){const{planningSessions:n}=e,[s,a]=i.useState(!1),[r,o]=i.useState(!1),[l,c]=i.useState(null),[d,u]=i.useState(void 0),[h,m]=i.useState(!1),[f,p]=i.useState(null),[g,w]=i.useState(void 0),[v,b]=i.useState(null),[y,j]=i.useState("definition"),[S,C]=i.useState(null),[x,k]=i.useState(!1),[R,O]=i.useState(void 0),[E,_]=i.useState(!1),[G,H]=i.useState(!1),[A,P]=i.useState(!1),[q,Y]=i.useState(null),[ge,L]=i.useState(!1),[M,$]=i.useState(!1),[D,N]=i.useState(void 0),[W,de]=i.useState(!1),[me,Ne]=i.useState(!1),[ve,Me]=i.useState("project"),[ie,ye]=i.useState(null),[Z,fe]=i.useState(!1),[Q,F]=i.useState(!1),[X,re]=i.useState(!1),[U,be]=i.useState(!1),[Ue,se]=i.useState(!1),[Ve,Le]=i.useState(!1),[ct,Ke]=i.useState(!1),oe=!!(v||x||s||r||h||M||W||me||Z||Q||X||Ue||U||A||ge||E||G||Ve||ct),Te=i.useCallback(()=>a(!0),[]),Fe=i.useCallback(()=>a(!1),[]),mt=i.useCallback(()=>o(!0),[]),We=i.useCallback(He=>{c(He),o(!0)},[]),he=i.useCallback(()=>{const He=n[0];He&&(u(He.id),o(!0))},[n]),pe=i.useCallback(He=>{u(He),o(!0)},[]),De=i.useCallback(()=>{o(!1),c(null),u(void 0)},[]),ut=i.useCallback(He=>{p(He),m(!0)},[]),ht=i.useCallback(He=>{w(He),m(!0)},[]),et=i.useCallback(()=>{m(!1),p(null),w(void 0)},[]),vt=i.useCallback((He,Ae="definition",pt)=>{b(He),j(Ae),C(pt?.origin??null)},[]),Oe=i.useCallback(He=>{b(He),j("changes"),C(null)},[]),tt=i.useCallback(He=>{b(Ae=>Ae&&{...Ae,...He})},[]),ft=i.useCallback(()=>{b(null),C(null)},[]),Mt=i.useCallback(He=>{O(He),k(!0)},[]),yt=i.useCallback(()=>{k(!1),O(void 0)},[]),Ge=i.useCallback(()=>_(!0),[]),K=i.useCallback(()=>_(!1),[]),ue=i.useCallback(()=>H(!0),[]),ot=i.useCallback(()=>H(!1),[]),xe=i.useCallback(He=>{Y(He??null),P(!0)},[]),dt=i.useCallback(()=>{P(!1),Y(null)},[]),Je=i.useCallback(()=>L(!0),[]),ke=i.useCallback(()=>L(!1),[]),nt=i.useCallback(()=>{$(He=>!He)},[]),bt=i.useCallback(()=>{$(!1),N(void 0)},[]),kt=i.useCallback((He,Ae)=>{He&&Me(He),ye(Ae??null),de(!0)},[]),wt=i.useCallback(()=>{de(!1),ye(null)},[]),At=i.useCallback(()=>Ne(!0),[]),Ft=i.useCallback(()=>Ne(!1),[]),ln=i.useCallback(He=>{Me(He)},[]),Vt=i.useCallback(()=>fe(!0),[]),hn=i.useCallback(()=>fe(!1),[]),un=i.useCallback(()=>F(!0),[]),pn=i.useCallback(()=>F(!1),[]),an=i.useCallback(()=>re(!0),[]),Wt=i.useCallback(()=>re(!1),[]),gn=i.useCallback(()=>be(!0),[]),cn=i.useCallback(()=>be(!1),[]),tn=i.useCallback(()=>se(!0),[]),Yt=i.useCallback(()=>se(!1),[]),Qt=i.useCallback(async(He,Ae)=>{se(!1),N(Ae),$(!0)},[]),Kt=i.useCallback(()=>Le(!0),[]),Jt=i.useCallback(()=>Le(!1),[]),rn=i.useCallback(()=>Ke(!0),[]),qt=i.useCallback(()=>Ke(!1),[]),we=i.useCallback((He,Ae)=>{Ae(`Created ${He.id} from planning mode`,"success"),o(!1),c(null)},[]),ze=i.useCallback((He,Ae)=>{const pt=He.map(Ct=>Ct.id).join(", ");Ae(`Created ${pt} from planning mode`,"success"),o(!1),c(null)},[]),rt=i.useCallback((He,Ae)=>{const pt=He.map(Ct=>Ct.id).join(", ");Ae(`Created ${pt} from subtask breakdown`,"success"),m(!1),p(null)},[]);return{newTaskModalOpen:s,isPlanningOpen:r,planningInitialPlan:l,planningResumeSessionId:d,isSubtaskOpen:h,subtaskInitialDescription:f,subtaskResumeSessionId:g,detailTask:v,detailTaskInitialTab:y,detailTaskOrigin:S,settingsOpen:x,settingsInitialSection:R,schedulesOpen:E,githubImportOpen:G,usageOpen:A,usageAnchorRect:q,systemStatsOpen:ge,terminalOpen:M,terminalInitialCommand:D,filesOpen:W,todosOpen:me,fileBrowserWorkspace:ve,fileBrowserInitialFile:ie,activityLogOpen:Z,gitManagerOpen:Q,workflowStepsOpen:X,agentsOpen:U,scriptsOpen:Ue,setupWizardOpen:Ve,modelOnboardingOpen:ct,anyModalOpen:oe,openNewTask:Te,closeNewTask:Fe,openPlanning:mt,openPlanningWithInitialPlan:We,resumePlanning:he,openPlanningWithSession:pe,closePlanning:De,openSubtaskBreakdown:ut,openSubtaskWithSession:ht,closeSubtask:et,openDetailTask:vt,openDetailWithChangesTab:Oe,updateDetailTask:tt,closeDetailTask:ft,openSettings:Mt,closeSettings:yt,openSchedules:Ge,closeSchedules:K,openGitHubImport:ue,closeGitHubImport:ot,openUsage:xe,closeUsage:dt,openSystemStats:Je,closeSystemStats:ke,toggleTerminal:nt,closeTerminal:bt,openFiles:kt,closeFiles:wt,openTodos:At,closeTodos:Ft,setFileWorkspace:ln,openActivityLog:Vt,closeActivityLog:hn,openGitManager:un,closeGitManager:pn,openWorkflowSteps:an,closeWorkflowSteps:Wt,openAgents:gn,closeAgents:cn,openScripts:tn,closeScripts:Yt,runScript:Qt,openSetupWizard:Kt,closeSetupWizard:Jt,openModelOnboarding:rn,closeModelOnboarding:qt,onPlanningTaskCreated:we,onPlanningTasksCreated:ze,onSubtaskTasksCreated:rt}}function Mz(e){const[n,s]=i.useState(2),[a,r]=i.useState("."),[o,l]=i.useState(!0),[c,d]=i.useState(!1),[u,h]=i.useState(!1),[m,f]=i.useState(void 0),[p,g]=i.useState(7200*1e3),[w,v]=i.useState(!1),[b,y]=i.useState(20),[j,S]=i.useState(!1),[C,x]=i.useState(!1),[k,R]=i.useState(!1),[O,E]=i.useState({}),[_,G]=i.useState(!1),[H,A]=i.useState(!1),[P,q]=i.useState(!1),[Y,ge]=i.useState(!1),[L,M]=i.useState(!0),$=i.useCallback(async()=>{const[Ne,ve]=await Promise.allSettled([NN(e),Cc(e)]);if(Ne.status==="fulfilled"&&(s(Ne.value.maxConcurrent),r(Ne.value.rootDir)),ve.status==="fulfilled"){const Me=ve.value;l(!!Me.autoMerge),d(!!Me.globalPause),h(!!Me.enginePaused),x(!!Me.prAuthAvailable),f(Me.taskStuckTimeoutMs),g(Me.staleHighFanoutBlockerAgeThresholdMs??7200*1e3),S(Me.showQuickChatFAB===!0),v(Me.capacityRiskBannerEnabled===!0),y(Me.capacityRiskTodoThreshold??20),E(Me.experimentalFeatures??{});const ie=Me.experimentalFeatures??{};G(ie.insights===!0),A(ie.memoryView===!0),q(ie.devServerView===!0||ie.devServer===!0),ge(ie.todoView===!0);const ye=Me.autoReloadOnVersionChange!==!1;M(ye),qc(ye)}R(!0)},[e]);i.useEffect(()=>{R(!1),E({}),G(!1),A(!1),q(!1),ge(!1),$()},[$]);const D=i.useCallback(async()=>{const Ne=!o;l(Ne);try{await al({autoMerge:Ne},e)}catch{l(!Ne)}},[o,e]),N=i.useCallback(async()=>{const Ne=!c;d(Ne);try{await al({globalPause:Ne,globalPauseReason:Ne?"manual":void 0},e)}catch{d(!Ne)}},[c,e]),W=i.useCallback(async()=>{const Ne=!u;h(Ne);try{await al({enginePaused:Ne},e)}catch{h(!Ne)}},[u,e]),de=i.useCallback(async()=>{const Ne=!j;S(Ne);try{await al({showQuickChatFAB:Ne},e)}catch{S(!Ne)}},[j,e]),me=i.useCallback(async()=>{const Ne=!L;M(Ne),qc(Ne);try{await Fn({autoReloadOnVersionChange:Ne})}catch{M(!Ne),qc(!Ne)}},[L]);return{maxConcurrent:n,rootDir:a,autoMerge:o,globalPaused:c,enginePaused:u,taskStuckTimeoutMs:m,staleHighFanoutBlockerAgeThresholdMs:p,capacityRiskBannerEnabled:w,capacityRiskTodoThreshold:b,showQuickChatFAB:j,prAuthAvailable:C,settingsLoaded:k,experimentalFeatures:O,insightsEnabled:_,memoryEnabled:H,devServerEnabled:P,todosEnabled:Y,autoReloadOnVersionChange:L,toggleAutoMerge:D,toggleGlobalPause:N,toggleEnginePause:W,toggleShowQuickChatFAB:de,toggleAutoReloadOnVersionChange:me,refresh:$}}function Az(e){const{projectId:n,projects:s,projectsLoading:a,currentProject:r,setCurrentProject:o,addToast:l,openTaskDetail:c,closeTaskDetail:d}=e,u=i.useRef(!1),h=i.useRef(!1),m=i.useRef(null);return i.useEffect(()=>{if(!h.current){const b=window.location.pathname.match(/^\/tasks\/([A-Z]+-\d+)\/?$/);if(b){const y=b[1];if(/^[A-Z]+-\d+$/.test(y)){const j=new URLSearchParams(window.location.search);j.set("task",y);const S=j.toString(),C=window.history.state??{};window.history.replaceState(C,"",S?`/?${S}`:"/"),h.current=!0}}}const p=new URLSearchParams(window.location.search),g=p.get("project"),w=p.get("task");if(!w||a)return;if(g){const b=s.find(y=>y.id===g);if(!b){l(`Project '${g}' not found`,"error");return}r?.id!==b.id&&o(b)}if(u.current)return;u.current=!0,Ba(w,g??n).then(b=>{c(b),m.current=w}).catch(()=>{l(`Task ${w} not found`,"error")})},[n,s,a,r,o,l,c]),{handleDetailClose:i.useCallback(()=>{if(m.current){const p=new URLSearchParams(window.location.search);p.delete("task");const g=p.toString(),w=window.history.state??{};window.history.replaceState(w,"",g?`${window.location.pathname}?${g}`:window.location.pathname),m.current=null}d()},[d])}}function Rz(){const[e,n]=i.useState([]),[s,a]=i.useState([]),[r,o]=i.useState([]),l=i.useRef(s),c=i.useRef(r);i.useEffect(()=>{Bs().then(h=>{n(h.models),l.current=h.favoriteProviders,c.current=h.favoriteModels,a(h.favoriteProviders),o(h.favoriteModels)}).catch(()=>{})},[]),i.useEffect(()=>{l.current=s},[s]),i.useEffect(()=>{c.current=r},[r]);const d=i.useCallback(async h=>{const m=l.current,p=m.includes(h)?m.filter(g=>g!==h):[h,...m];l.current=p,a(()=>p);try{await Fn({favoriteProviders:p,favoriteModels:c.current})}catch(g){throw l.current=m,a(()=>m),g}},[]),u=i.useCallback(async h=>{const m=c.current,p=m.includes(h)?m.filter(g=>g!==h):[h,...m];c.current=p,o(()=>p);try{await Fn({favoriteProviders:l.current,favoriteModels:p})}catch(g){throw c.current=m,o(()=>m),g}},[]);return{availableModels:e,favoriteProviders:s,favoriteModels:r,toggleFavoriteProvider:d,toggleFavoriteModel:u}}function Iz({projectId:e,setupWizardOpen:n,openModelOnboarding:s,openSettings:a}){const r=i.useRef(!1),o=i.useRef(n);o.current=n,i.useEffect(()=>{if(n||!e||r.current)return;r.current=!0;let l=!1,c=!1;Do().then(({providers:d})=>{const u=d.some(m=>m.authenticated);if(d.length>0&&!u||d.length>0&&u)return Qi().then(m=>{const f=!!(m.defaultProvider&&m.defaultModelId);(m.modelOnboardingComplete===!1||m.modelOnboardingComplete===void 0)&&(!u||!f)&&!Lr()?l=!0:!u&&!Lr()&&(c=!0)})}).then(()=>{if(o.current){r.current=!1;return}l?(oi("onboarding:auto-triggered",{trigger:"first-run"}),s()):c&&(oi("onboarding:auto-triggered",{trigger:"missing-provider"}),a("authentication"))}).catch(()=>{})},[e,n,s,a])}const Vg="kb-update-banner-dismissed";function Tz(){const[e,n]=i.useState(!0),[s,a]=i.useState(!1),[r,o]=i.useState(null),[l,c]=i.useState(null),[d,u]=i.useState(!1);i.useEffect(()=>{const m=sessionStorage.getItem(Vg)==="true";u(m);let f=!1;return SN().then(p=>{f||p.disabled||(a(p.updateAvailable===!0),o(typeof p.latestVersion=="string"?p.latestVersion:null),c(typeof p.currentVersion=="string"?p.currentVersion:null))}).catch(()=>{}).finally(()=>{f||n(!1)}),()=>{f=!0}},[]);const h=i.useCallback(()=>{u(!0),sessionStorage.setItem(Vg,"true")},[]);return{updateAvailable:s,latestVersion:r,currentVersion:l,loading:e,dismissed:d,dismiss:h}}const Pz=["board","list","graph","agents","missions","chat","documents","research","evals","skills","mailbox","insights","memory","devserver","dev-server","stash-recovery"];function $z(e){return e!==null&&Pz.includes(e)}function tu(e){return e!==null&&($z(e)||kr(e))}const Dz=Zo("fusion-plugin-roadmap","roadmaps");function Wg(e){return e==="devserver"?"dev-server":e}function Gg(e){return e!=="roadmaps"?"board":Wb("fusion-plugin-roadmap","roadmaps")?Dz:"board"}function Lz(e){const{projectsLoading:n,projectsError:s,currentProjectLoading:a,currentProject:r,projectsLength:o,setupWizardOpen:l,openSetupWizard:c,themeMode:d,setThemeMode:u}=e,[h,m]=i.useState(()=>{if(typeof window<"u"){const b=window.localStorage.getItem("kb-dashboard-view-mode");if(b==="overview"||b==="project")return b}return"overview"}),[f,p]=i.useState(()=>{const b=Ln("kb-dashboard-task-view");return b==="roadmaps"?Gg(b):tu(b)?b:"board"}),g=i.useRef(!1);i.useEffect(()=>{window.localStorage.setItem("kb-dashboard-view-mode",h)},[h]),i.useEffect(()=>{const b=Ln("kb-dashboard-task-view",r?.id);if(b==="roadmaps")p(Gg(b));else if(tu(b)){const y=!g.current&&b==="devserver";p(y?"devserver":Wg(b))}else p("board");r?.id&&(g.current=!0)},[r?.id]),i.useEffect(()=>{rs("kb-dashboard-task-view",f,r?.id)},[r?.id,f]),i.useEffect(()=>{if(typeof window>"u")return;const b=new URLSearchParams(window.location.search).get("view");b&&tu(b)&&p(Wg(b))},[]),i.useEffect(()=>{n||a||r&&h==="overview"&&m("project")},[n,a,r,h]),i.useEffect(()=>{if(n||a||l||s||o>0||r)return;const b=window.setTimeout(()=>{c()},500);return()=>window.clearTimeout(b)},[n,s,o,a,r,l,c]);const w=i.useCallback(b=>{p(b)},[]),v=i.useCallback(()=>{const b=["dark","light","system"],y=b.indexOf(d),j=b[(y+1)%b.length];u(j)},[d,u]);return{viewMode:h,setViewMode:m,taskView:f,setTaskView:p,handleChangeTaskView:w,handleToggleTheme:v}}const nu=new Map,Oz=6e4;function Fz(e){const[n,s]=i.useState([]),[a,r]=i.useState(!0),[o,l]=i.useState(null),[c,d]=i.useState(0),u=i.useRef(!1),h=i.useCallback(()=>{const m=e??"default";nu.delete(m),d(f=>f+1)},[e]);return i.useEffect(()=>{const m=e??"default";let f=!1;async function p(){const g=nu.get(m);if(g&&Date.now()<g.expiresAt){if(f)return;s(g.views),r(!1);return}u.current||r(!0),l(null);try{const w=await hC(e);if(f)return;nu.set(m,{views:w,expiresAt:Date.now()+Oz}),s(w)}catch(w){if(f)return;l(w instanceof Error?w.message:"Failed to fetch plugin dashboard views")}finally{f||(r(!1),u.current=!0)}}return p(),()=>{f=!0}},[e,c]),i.useMemo(()=>({views:n,loading:a,error:o,refetch:h}),[n,a,o,h])}function zz({taskView:e,context:n}){return t.jsx(XC,{viewId:e,context:n})}let Kg=!1;function Or(e,n){return function(){return i.createElement("span",null,`Bundled plugin view unavailable: ${e}#${n}`)}}async function Bz(){const e="@fusion-plugin-examples/dependency-graph/dashboard-view",n="DependencyGraphDashboardView",a=(await Sn(()=>import("./dashboard-view-C_G8JVU7.js"),__vite__mapDeps([24,1,25,5,6,26])))[n];return a?{default:a}:(console.warn(`[plugin-views] Missing export ${n} from ${e}`),{default:Or(e,n)})}async function Uz(){const e="@fusion-plugin-examples/roadmap/dashboard-view",n="RoadmapDashboardView",a=(await Sn(()=>import("./dashboard-view-BWGH_fAq.js"),__vite__mapDeps([27,1,25,28])))[n];return a?{default:a}:(console.warn(`[plugin-views] Missing export ${n} from ${e}`),{default:Or(e,n)})}async function Hz(){const e="@fusion-plugin-examples/cli-printing-press/dashboard-view",n="CliPrintingPressWizardView";try{const a=(await import(e))[n];return a?{default:a}:(console.warn(`[plugin-views] Missing export ${n} from ${e}`),{default:Or(e,n)})}catch{return{default:Or(e,n)}}}async function qz(){const e="@fusion-plugin-examples/cli-printing-press/manage-view",n="CliPrintingPressManageView";try{const a=(await import(e))[n];return a?{default:a}:(console.warn(`[plugin-views] Missing export ${n} from ${e}`),{default:Or(e,n)})}catch{return{default:Or(e,n)}}}function xy(){Kg||(Kg=!0,dl("fusion-plugin-dependency-graph","graph",i.lazy(Bz)),dl("fusion-plugin-roadmap","roadmaps",i.lazy(Uz)),dl("fusion-plugin-cli-printing-press","wizard",i.lazy(Hz)),dl("fusion-plugin-cli-printing-press","manage",i.lazy(qz)))}function Vz(e){const{setCurrentProject:n,clearCurrentProject:s,setViewMode:a,currentProject:r,refreshProjects:o,toggleFavoriteProvider:l,toggleFavoriteModel:c,addToast:d,openSettings:u,openSetupWizard:h,closeSetupWizard:m,closeModelOnboarding:f}=e,p=i.useCallback(R=>{n(R),a("project")},[n,a]),g=i.useCallback(()=>{s(),a("overview")},[s,a]),w=i.useCallback(()=>{u()},[u]),v=i.useCallback(()=>{h()},[h]),b=i.useCallback(R=>{m(),n(R),a("project"),d(`Project ${R.name} registered successfully`,"success"),o()},[m,n,a,d,o]),y=i.useCallback(()=>{f()},[f]),j=i.useCallback(async R=>{try{await K1(R.id),d(`Project ${R.name} paused`,"success"),await o()}catch{d(`Failed to pause project ${R.name}`,"error")}},[d,o]),S=i.useCallback(async R=>{try{await J1(R.id),d(`Project ${R.name} resumed`,"success"),await o()}catch{d(`Failed to resume project ${R.name}`,"error")}},[d,o]),C=i.useCallback(async R=>{try{await Pb(R.id),d(`Project ${R.name} removed`,"success"),r?.id===R.id&&(s(),a("overview")),await o()}catch{d(`Failed to remove project ${R.name}`,"error")}},[r,s,a,d,o]),x=i.useCallback(async R=>{try{await l(R)}catch{d("Failed to update favorites","error")}},[l,d]),k=i.useCallback(async R=>{try{await c(R)}catch{d("Failed to update model favorites","error")}},[c,d]);return{handleSelectProject:p,handleViewAllProjects:g,handleOpenSettings:w,handleAddProject:v,handleSetupComplete:b,handleModelOnboardingComplete:y,handlePauseProject:j,handleResumeProject:S,handleRemoveProject:C,handleToggleFavorite:x,handleToggleModelFavorite:k}}function Wz(e){const{createTask:n,ingestCreatedTasks:s,onPlanningTaskCreated:a,onPlanningTasksCreated:r,onSubtaskTasksCreated:o,addToast:l}=e,c=i.useCallback(async p=>n({...p,column:"triage",source:{sourceType:"dashboard_ui"}}),[n]),d=i.useCallback(async p=>await n({...p,column:"triage",source:{sourceType:"dashboard_ui"}}),[n]),u=i.useCallback(p=>{s([p]),a(p,l)},[l,s,a]),h=i.useCallback(p=>{s(p),r(p,l)},[l,s,r]),m=i.useCallback(p=>{s(p),o(p,l)},[l,s,o]),f=i.useCallback(p=>{l(`Imported ${p.id} from GitHub`,"success")},[l]);return{handleBoardQuickCreate:c,handleModalCreate:d,handlePlanningTaskCreated:u,handlePlanningTasksCreated:h,handleSubtaskTasksCreated:m,handleGitHubImport:f}}function Gz(e,n){const{projectId:s,searchQuery:a}=n??{},[r,o]=i.useState([]),[l,c]=i.useState([]),[d,u]=i.useState(null),[h,m]=i.useState(!1),[f,p]=i.useState(null),g=i.useRef(null),w=i.useCallback(async()=>{if(!e){o([]),c([]),u(null),m(!1),p(null);return}g.current?.abort();const b=new AbortController;g.current=b,m(!0),p(null);try{const y=[wC(e),kC(e)];s&&(y.push(jC(e,s,a)),y.push(NC(e,s)));const j=await Promise.allSettled(y);if(b.signal.aborted)return;const S=j[0],C=j[1];if(S.status==="rejected"){p(`Failed to fetch node health: ${S.reason}`),m(!1);return}if(u(S.value),C.status==="rejected"){p(`Failed to fetch projects: ${C.reason}`),m(!1);return}if(o(C.value),s&&j[2]){const x=j[2];if(x.status==="rejected"){p(`Failed to fetch tasks: ${x.reason}`),m(!1);return}x.status==="fulfilled"&&c(x.value)}m(!1)}catch(y){b.signal.aborted||(p(y instanceof Error?y.message:"Unknown error"),m(!1))}},[e,s,a]);i.useEffect(()=>(w(),()=>{g.current?.abort()}),[w]);const v=i.useCallback(()=>{w()},[w]);return{projects:r,tasks:l,health:d,loading:h,error:f,refresh:v}}function Kz(e){const[n,s]=i.useState(!1),[a,r]=i.useState(null);return i.useEffect(()=>{if(!e){s(!1),r(null);return}const o=`/api/proxy/${encodeURIComponent(e)}/events`;return fi(o,{events:{"task:created":l=>{r({type:"task:created",data:l.data})},"task:moved":l=>{r({type:"task:moved",data:l.data})},"task:updated":l=>{r({type:"task:updated",data:l.data})},"task:deleted":l=>{r({type:"task:deleted",data:l.data})},"task:merged":l=>{r({type:"task:merged",data:l.data})}},onOpen:()=>s(!0),onError:()=>s(!1)})},[e]),{isConnected:n,lastEvent:a}}const Jz="fusion-dashboard-current-node",vy=i.createContext(null);function Yz({children:e}){const[n,s]=i.useState(null),[a,r]=i.useState(!0),o=i.useRef(!1),l=i.useRef(void 0);i.useEffect(()=>{let h=!1;async function m(){try{const f=await Qi();if(h)return;l.current=f.dashboardCurrentNodeId;const p=f.dashboardCurrentNodeId;if(p&&(o.current=!0),!p)try{const g=localStorage.getItem(Jz);if(g){const w=JSON.parse(g);w?.id&&w?.type==="remote"&&(l.current=w.id,await Fn({dashboardCurrentNodeId:w.id}).catch(()=>{}))}}catch{}}catch{}finally{h||r(!1)}}return m(),()=>{h=!0}},[]),i.useEffect(()=>{if(!a)if(n&&n.type==="remote"&&n.id){const h=n.id;l.current!==h&&(l.current=h,Fn({dashboardCurrentNodeId:h}).catch(()=>{}))}else n===null&&l.current!==void 0&&(l.current=void 0,Fn({dashboardCurrentNodeId:void 0}).catch(()=>{}))},[n,a]);const c=i.useCallback(h=>{s(h)},[]),d=i.useCallback(()=>{s(null),l.current=void 0,Fn({dashboardCurrentNodeId:void 0}).catch(()=>{})},[]),u={currentNode:n,currentNodeId:n?.id??null,isRemote:n!==null&&n.type==="remote",setCurrentNode:c,clearCurrentNode:d};return t.jsx(vy.Provider,{value:u,children:e})}function Qz(){const e=i.useContext(vy);if(e===null)throw new Error("useNodeContext must be used within a NodeProvider");return e}const Xz=["shellKind","shellMode","profileId","serverBaseUrl","serverLabel","shellCanOpenConnectionManager","hostKind","mode","connectionId","serverUrl","canOpenConnectionManager"],Zz=["__FUSION_SHELL_HOST_CONTEXT__","__fusionShellHostContext","__FUSION_SHELL_CONTEXT__"];let fc=null,Jg=!1;function e6(e){if(typeof e=="boolean")return e;if(typeof e=="string"){if(e==="1"||e==="true")return!0;if(e==="0"||e==="false")return!1}}function t6(e){if(!(typeof e!="string"||e.trim().length===0))try{const n=new URL(e);return n.protocol!=="http:"&&n.protocol!=="https:"?void 0:n.toString().replace(/\/$/,"")}catch{return}}function yy(e){if(e==="browser"||e==="desktop-shell"||e==="mobile-shell")return e;if(e==="desktop")return"desktop-shell";if(e==="mobile")return"mobile-shell"}function n6(e){return e==="local"||e==="remote"?e:void 0}function wy(e){const n=n6(e.mode),s=typeof e.connectionId=="string"&&e.connectionId.trim()?e.connectionId:void 0,a=t6(e.serverUrl),r=e6(e.canOpenConnectionManager);return{kind:e.kind,...n?{mode:n}:{},...s?{connectionId:s}:{},...a?{serverUrl:a}:{},...r!==void 0?{canOpenConnectionManager:r}:{}}}function s6(e){for(const n of Zz){const s=e[n];if(!s||typeof s!="object")continue;const a=s,r=yy(a.kind??a.shellKind??a.hostKind);if(r)return r==="browser"?{kind:r}:wy({kind:r,mode:a.mode??a.shellMode,connectionId:a.connectionId??a.profileId,serverUrl:a.serverUrl??a.serverBaseUrl,canOpenConnectionManager:a.canOpenConnectionManager??a.shellCanOpenConnectionManager})}return null}function i6(e){let n;try{n=new URL(e.location.href)}catch{return null}const s=n.searchParams,a=yy(s.get("hostKind")??s.get("kind")??s.get("shellKind"));return a?a==="browser"?{kind:a}:wy({kind:a,mode:s.get("mode")??s.get("shellMode"),connectionId:s.get("connectionId")??s.get("profileId"),serverUrl:s.get("serverUrl")??s.get("serverBaseUrl"),canOpenConnectionManager:s.get("canOpenConnectionManager")??s.get("shellCanOpenConnectionManager")}):null}function a6(e){try{const n=new URL(e.location.href);let s=!1;for(const r of Xz)n.searchParams.has(r)&&(n.searchParams.delete(r),s=!0);if(!s)return;const a=n.pathname+(n.search?n.search:"")+n.hash;e.history.replaceState(e.history.state,"",a)}catch{}}function r6(e=window){const n=s6(e);if(n)return n;const s=i6(e);return s||(typeof e.fusionAPI<"u"?{kind:"desktop-shell"}:{kind:"browser"})}function ky(e=window){return!Jg&&typeof window<"u"&&(fc=r6(e),a6(e),Jg=!0),fc??{kind:"browser"}}function o6(){return fc||(typeof window>"u"?{kind:"browser"}:ky(window))}const l6={kind:"browser"},jy=i.createContext({host:l6,isNativeShell:!1,kind:"browser"});function c6(e){const n=e.kind!=="browser";return{host:e,isNativeShell:n,kind:e.kind,...n?{mode:e.mode,connectionId:e.connectionId,serverUrl:e.serverUrl,canOpenConnectionManager:e.canOpenConnectionManager}:{}}}function d6({children:e}){const n=i.useMemo(()=>c6(o6()),[]);return t.jsx(jy.Provider,{value:n,children:e})}function u6(){return i.useContext(jy)}function m6(e,n){const s=new URL(e);return n&&s.searchParams.set("rt",n),s.toString()}function h6({open:e,shellApi:n,shellState:s,onComplete:a}){const[r,o]=i.useState(s.desktopMode??"remote"),[l,c]=i.useState("Remote Server"),[d,u]=i.useState(""),[h,m]=i.useState(""),[f,p]=i.useState(null),[g,w]=i.useState(!1),[v,b]=i.useState(!1),y=s.host==="desktop-shell";i.useEffect(()=>{y&&o(s.desktopMode??"remote")},[y,s.desktopMode]);const j=i.useMemo(()=>y&&r==="local"?!0:d.trim().length>0,[y,r,d]);return e?t.jsx("div",{className:"modal-overlay open",children:t.jsxs("div",{className:"modal native-shell-onboarding-modal",children:[t.jsx("div",{className:"modal-header",children:t.jsx("h2",{children:"Welcome to Fusion"})}),t.jsxs("div",{className:"native-shell-onboarding-body",children:[t.jsx("p",{children:"Fusion helps you plan, run, and review AI-assisted engineering work."}),y&&t.jsxs("div",{className:"native-shell-onboarding-mode-row",children:[t.jsx("button",{type:"button",className:`btn ${r==="local"?"btn-primary":""}`,onClick:()=>o("local"),children:"Local Fusion"}),t.jsx("button",{type:"button",className:`btn ${r==="remote"?"btn-primary":""}`,onClick:()=>o("remote"),children:"Remote Server"})]}),(!y||r==="remote")&&t.jsxs(t.Fragment,{children:[t.jsx("button",{type:"button",className:"btn",onClick:async()=>{p(null),w(!0);try{const S=await n.startQrScan();u(S.serverUrl),m(S.authToken??"")}catch(S){p(S.message)}finally{w(!1)}},disabled:g,children:g?"Scanning…":"Scan QR"}),t.jsx("label",{className:"native-shell-onboarding-label",htmlFor:"native-shell-onboarding-profile-name",children:"Profile name"}),t.jsx("input",{id:"native-shell-onboarding-profile-name",className:"input",value:l,onChange:S=>c(S.target.value)}),t.jsx("label",{className:"native-shell-onboarding-label",htmlFor:"native-shell-onboarding-server-url",children:"Server URL"}),t.jsx("input",{id:"native-shell-onboarding-server-url",className:"input",value:d,onChange:S=>u(S.target.value),placeholder:"https://your-fusion-host"}),t.jsx("label",{className:"native-shell-onboarding-label",htmlFor:"native-shell-onboarding-auth-token",children:"Auth token (optional)"}),t.jsx("input",{id:"native-shell-onboarding-auth-token",className:"input",type:"password",value:h,onChange:S=>m(S.target.value)})]}),f&&t.jsx("p",{className:"form-error",role:"alert",children:f})]}),t.jsx("div",{className:"modal-actions",children:t.jsx("button",{type:"button",className:"btn btn-primary",disabled:!j||v,onClick:async()=>{p(null),b(!0);try{if(y&&r==="local"){await n.setDesktopMode("local"),a();return}const S=await n.saveProfile({name:l.trim()||"Remote Server",serverUrl:d,authToken:h||null});if(y&&await n.setDesktopMode("remote"),await n.setActiveProfile(S.id),typeof window<"u"&&s.host!=="web"){window.location.href=m6(S.serverUrl,S.authToken??null);return}a()}catch(S){p(S.message)}finally{b(!1)}},children:v?"Saving…":"Continue"})})]})}):null}function p6({open:e,shellApi:n,shellState:s,onClose:a}){const r=i.useMemo(()=>s.profiles.find(x=>x.id===s.activeProfileId)??null,[s.activeProfileId,s.profiles]),[o,l]=i.useState(null),[c,d]=i.useState({}),[u,h]=i.useState(null),[m,f]=i.useState(null);if(!e)return null;const p=o==="__new__",g=p?null:s.profiles.find(x=>x.id===o)??r,w=c.name??g?.name??"",v=c.serverUrl??g?.serverUrl??"",b=c.authToken??g?.authToken??"",y=()=>{l(null),d({}),f(null)},j=async()=>{f(null);try{const x=new URL(v.trim());if(!/^https?:$/.test(x.protocol))throw new Error("Server URL must use http or https");const k=await n.saveProfile({id:p?void 0:o??g?.id,name:w||"Remote Server",serverUrl:v,authToken:b||null});await n.setActiveProfile(k.id),l(k.id),d({})}catch(x){f(x.message)}},S=async()=>{f(null);try{const x=await n.startQrScan();l("__new__"),d({name:"",serverUrl:x.serverUrl,authToken:x.authToken??""})}catch(x){f(x.message)}},C=async()=>{u&&(await n.deleteProfile(u.id),h(null),y())};return t.jsx("div",{className:"modal-overlay open",children:t.jsxs("div",{className:"modal native-shell-connection-manager",role:"dialog","aria-label":"Connection Manager",children:[t.jsxs("div",{className:"modal-header",children:[t.jsx("h2",{children:"Connection Manager"}),t.jsx("button",{type:"button",className:"modal-close",onClick:a,"aria-label":"Close",children:"×"})]}),s.host==="desktop-shell"&&t.jsxs("div",{className:"native-shell-connection-manager__mode-row",children:[t.jsx("button",{type:"button",className:`btn ${s.desktopMode==="local"?"btn-primary":""}`,onClick:()=>void n.setDesktopMode("local"),children:"Local"}),t.jsx("button",{type:"button",className:`btn ${s.desktopMode!=="local"?"btn-primary":""}`,onClick:()=>void n.setDesktopMode("remote"),children:"Remote"})]}),t.jsx("div",{className:"native-shell-connection-manager__profiles",children:s.profiles.length===0?t.jsxs("div",{className:"card native-shell-connection-manager__empty-state",children:[t.jsx("p",{className:"settings-muted",children:"No remote servers saved yet."}),t.jsxs("div",{className:"native-shell-connection-manager__profile-actions",children:[t.jsx("button",{type:"button",className:"btn btn-sm",onClick:()=>{l("__new__"),d({name:"",serverUrl:"",authToken:""}),f(null)},children:"Add server"}),s.host==="mobile-shell"&&t.jsx("button",{type:"button",className:"btn btn-sm",onClick:()=>void S(),children:"Scan QR"})]})]}):s.profiles.map(x=>t.jsxs("div",{className:"card native-shell-connection-manager__profile",children:[t.jsxs("div",{children:[t.jsx("strong",{children:x.name}),t.jsx("div",{className:"settings-muted",children:x.serverUrl}),x.id===s.activeProfileId&&t.jsx("span",{className:"native-shell-connection-manager__active-pill",children:"Active"})]}),t.jsxs("div",{className:"native-shell-connection-manager__profile-actions",children:[t.jsx("button",{type:"button",className:"btn btn-sm","aria-label":`Edit ${x.name}`,onClick:()=>{l(x.id),d(x)},children:"Edit"}),t.jsx("button",{type:"button",className:"btn btn-sm","aria-label":`Use ${x.name}`,onClick:()=>void n.setActiveProfile(x.id),children:"Use"}),t.jsx("button",{type:"button",className:"btn btn-sm btn-danger","aria-label":`Delete ${x.name}`,onClick:()=>h(x),children:"Delete"})]})]},x.id))}),t.jsxs("div",{className:"native-shell-connection-manager__mode-row",children:[t.jsx("button",{type:"button",className:"btn",onClick:()=>{l("__new__"),d({name:"",serverUrl:"",authToken:""}),f(null)},children:"Add connection"}),s.host==="mobile-shell"&&t.jsx("button",{type:"button",className:"btn",onClick:()=>void S(),children:"Scan QR"})]}),t.jsxs("div",{className:"form-group native-shell-connection-manager__editor",children:[t.jsx("label",{htmlFor:"native-shell-connection-manager-name",children:"Name"}),t.jsx("input",{id:"native-shell-connection-manager-name",className:"input",value:w,onChange:x=>d(k=>({...k,name:x.target.value}))}),t.jsx("label",{htmlFor:"native-shell-connection-manager-url",children:"Server URL"}),t.jsx("input",{id:"native-shell-connection-manager-url",className:"input",value:v,onChange:x=>d(k=>({...k,serverUrl:x.target.value}))}),t.jsx("label",{htmlFor:"native-shell-connection-manager-token",children:"Auth token (optional)"}),t.jsx("input",{id:"native-shell-connection-manager-token",className:"input",type:"password",value:b??"",onChange:x=>d(k=>({...k,authToken:x.target.value}))}),m&&t.jsx("p",{className:"form-error",role:"alert",children:m})]}),u&&t.jsxs("div",{className:"native-shell-connection-manager__delete-confirm",role:"alertdialog","aria-label":"Delete server confirmation",children:[t.jsxs("p",{children:["Delete ",t.jsx("strong",{children:u.name}),"? This removes the saved profile."]}),t.jsxs("div",{className:"native-shell-connection-manager__profile-actions",children:[t.jsx("button",{type:"button",className:"btn btn-sm",onClick:()=>h(null),children:"Cancel"}),t.jsx("button",{type:"button",className:"btn btn-sm btn-danger",onClick:()=>void C(),children:"Delete"})]})]}),t.jsxs("div",{className:"modal-actions",children:[t.jsx("button",{type:"button",className:"btn",onClick:a,children:"Close"}),t.jsx("button",{type:"button",className:"btn",onClick:y,children:"Cancel"}),t.jsx("button",{type:"button",className:"btn btn-primary",onClick:()=>void j(),disabled:!v.trim(),children:"Save"})]})]})})}function f6(e){if(e.hostKind==="desktop-shell"&&e.mode==="local")return{title:"Desktop local mode",actionLabel:"Switch server",dotClassName:"status-dot status-dot--online"};const n=e.profileLabel??e.profileId,s=e.serverOrigin,a=n&&s?`${n} · ${s}`:n??s;return e.mode==="remote"?{title:a??"Connection info unavailable",actionLabel:e.hostKind==="desktop-shell"?"Switch server":"Manage connections",dotClassName:a?"status-dot status-dot--online":"status-dot status-dot--pending"}:{title:a??"Connection info unavailable",actionLabel:"Manage connections",dotClassName:a?"status-dot status-dot--online":"status-dot status-dot--pending"}}function Yg({status:e,onError:n}){if(e.hostKind==="browser"||!e.available)return null;const s=f6(e),a=i.useCallback(async()=>{const r=await e.openConnectionManager();!r.ok&&r.reason==="failed"&&n?.(r.error??"Failed to open connection manager")},[n,e]);return t.jsxs("button",{type:"button",className:"btn shell-connection-status",onClick:()=>void a(),"data-testid":"shell-connection-status-button",children:[t.jsx("span",{className:s.dotClassName,"aria-hidden":"true"}),t.jsx("span",{className:"shell-connection-status__kind",children:e.hostKind==="desktop-shell"?"Desktop":"Mobile"}),t.jsx("span",{className:"shell-connection-status__summary",title:s.title,children:s.title}),t.jsx("span",{className:"shell-connection-status__action",children:s.actionLabel})]})}function g6(e){if(e)try{return new URL(e).origin}catch{return}}function b6(e,n){const s=e.profiles.find(a=>a.id===e.activeProfileId)??null;return s||(n.kind==="browser"||!n.connectionId?null:e.profiles.find(a=>a.id===n.connectionId)??null)}async function x6(e){if(!e?.getState)return null;try{return await e.getState()}catch{return null}}async function v6(e,n=window){const s=n.fusionAPI,a=n.fusionShell,r=await x6(a),o=r?b6(r,e):null,l=e.kind==="browser"?void 0:e.mode??r?.desktopMode,c=o?.id??(e.kind==="browser"?void 0:e.connectionId),d=o?.name,u=g6(o?.serverUrl??(e.kind==="browser"?void 0:e.serverUrl)),h=e.kind==="desktop-shell"&&typeof s?.openConnectionManager=="function",m=e.kind==="mobile-shell"&&typeof a?.openConnectionManager=="function",f=h||m;return{hostKind:e.kind,available:f,...l?{mode:l}:{},...c?{profileId:c}:{},...d?{profileLabel:d}:{},...u?{serverOrigin:u}:{},openConnectionManager:async()=>{try{return h?(await s.openConnectionManager?.(),{ok:!0}):m?(await a.openConnectionManager(),{ok:!0}):{ok:!1,reason:"unsupported"}}catch(p){return{ok:!1,reason:"failed",error:p instanceof Error?p.message:String(p)}}}}}function y6({open:e}){const[n,s]=i.useState(""),a=i.useRef(null);i.useEffect(()=>{e&&a.current?.focus()},[e]);const r=i.useCallback(()=>{const l=n.trim();l&&(Zj(l),window.location.reload())},[n]),o=i.useCallback(()=>{eN(),window.location.reload()},[]);return e?t.jsx("div",{className:"modal-overlay open auth-token-recovery-overlay",role:"presentation",onKeyDownCapture:l=>{l.key==="Escape"&&(l.preventDefault(),l.stopPropagation())},children:t.jsxs("div",{className:"modal modal-md",role:"dialog","aria-modal":"true","aria-labelledby":"auth-token-recovery-title","aria-describedby":"auth-token-recovery-description",children:[t.jsx("div",{className:"modal-header auth-token-recovery-header",children:t.jsx("h3",{id:"auth-token-recovery-title",children:"Authentication token required"})}),t.jsxs("div",{className:"auth-token-recovery-content",children:[t.jsx("p",{id:"auth-token-recovery-description",children:"This dashboard session can't authenticate with the daemon. Set a replacement token or clear the current token and retry."}),t.jsxs("div",{className:"auth-token-recovery-field",children:[t.jsx("label",{htmlFor:"auth-token-recovery-input",children:"Replacement token"}),t.jsx("input",{ref:a,id:"auth-token-recovery-input",className:"input",type:"password",value:n,onChange:l=>s(l.target.value),placeholder:"Paste token",autoComplete:"off",spellCheck:!1})]})]}),t.jsxs("div",{className:"modal-actions auth-token-recovery-actions",children:[t.jsx("button",{type:"button",className:"btn",onClick:o,children:"Clear token and retry"}),t.jsx("button",{type:"button",className:"btn btn-primary",onClick:r,disabled:n.trim().length===0,children:"Set token and reload"})]})]})}):null}const w6=200,k6=i.lazy(()=>Sn(()=>import("./AgentsView-DljrBNE1.js"),__vite__mapDeps([29,1,3,4,30,15,5,6,31])).then(e=>({default:e.AgentsView}))),j6=i.lazy(()=>Sn(()=>import("./DocumentsView-BhrdTTh3.js"),__vite__mapDeps([32,1,5,6,33])).then(e=>({default:e.DocumentsView}))),N6=i.lazy(()=>Sn(()=>import("./InsightsView-j7J_vUME.js"),__vite__mapDeps([34,1,22,5,6,35])).then(e=>({default:e.InsightsView}))),S6=i.lazy(()=>Sn(()=>import("./ResearchView-B5wYC1KE.js"),__vite__mapDeps([36,1,5,6,37])).then(e=>({default:e.ResearchView}))),C6=i.lazy(()=>Sn(()=>import("./EvalsView-DrFp2cLg.js"),__vite__mapDeps([38,1,5,6,39])).then(e=>({default:e.EvalsView}))),E6=i.lazy(()=>Sn(()=>import("./NodesView-Cr4CXr7b.js"),__vite__mapDeps([40,1,17,30,5,6,41])).then(e=>({default:e.NodesView}))),_6=i.lazy(()=>Sn(()=>import("./ChatView-BklDUi5_.js"),__vite__mapDeps([42,1,5,6,43])).then(e=>({default:e.ChatView}))),M6=i.lazy(()=>Sn(()=>import("./SkillsView-Dilmj1nh.js"),__vite__mapDeps([44,1,5,6,45])).then(e=>({default:e.SkillsView}))),A6=i.lazy(()=>Sn(()=>import("./MemoryView-QWiqVDuQ.js"),__vite__mapDeps([46,1,20,21,5,6,47])).then(e=>({default:e.MemoryView}))),R6=i.lazy(()=>Sn(()=>import("./DevServerView-BqcI1wXr.js"),__vite__mapDeps([48,1,5,6,49])).then(e=>({default:e.DevServerView})));i.lazy(()=>Sn(()=>import("./TodoView-rSn0aPsb.js"),__vite__mapDeps([11,1,5,6,12])).then(e=>({default:e.TodoView})));const I6=i.lazy(()=>Sn(()=>import("./StashRecoveryView-BtL9aAn3.js"),__vite__mapDeps([50,1,5,6,51])).then(e=>({default:e.StashRecoveryView})));function T6(){(typeof window<"u"&&window.requestIdleCallback||(n=>setTimeout(n,200)))(()=>{Sn(()=>import("./AgentsView-DljrBNE1.js"),__vite__mapDeps([29,1,3,4,30,15,5,6,31])),Sn(()=>import("./DocumentsView-BhrdTTh3.js"),__vite__mapDeps([32,1,5,6,33])),Sn(()=>import("./InsightsView-j7J_vUME.js"),__vite__mapDeps([34,1,22,5,6,35])),Sn(()=>import("./ResearchView-B5wYC1KE.js"),__vite__mapDeps([36,1,5,6,37])),Sn(()=>import("./EvalsView-DrFp2cLg.js"),__vite__mapDeps([38,1,5,6,39])),Sn(()=>import("./NodesView-Cr4CXr7b.js"),__vite__mapDeps([40,1,17,30,5,6,41])),Sn(()=>import("./ChatView-BklDUi5_.js"),__vite__mapDeps([42,1,5,6,43])),Sn(()=>import("./SkillsView-Dilmj1nh.js"),__vite__mapDeps([44,1,5,6,45])),Sn(()=>import("./MemoryView-QWiqVDuQ.js"),__vite__mapDeps([46,1,20,21,5,6,47])),Sn(()=>import("./DevServerView-BqcI1wXr.js"),__vite__mapDeps([48,1,5,6,49])),Sn(()=>import("./TodoView-rSn0aPsb.js"),__vite__mapDeps([11,1,5,6,12])),Sn(()=>import("./StashRecoveryView-BtL9aAn3.js"),__vite__mapDeps([50,1,5,6,51]))})}xy();const su="kb-setup-warning-dismissed",P6="kb-chat-active-session",Qg="kb-dashboard-working-branch-filter",Xg="kb-dashboard-base-branch-filter",Zg="__fusion:no-branch__",Ny="fusion:approval-banner-dismissed",Hl="kb-capacity-risk-banner-dismissed";function $6(e,n){return e==="awaiting-approval"&&n!=="awaiting-approval"}function eb(e){if(!e)return 0;const n=Date.parse(e);return Number.isFinite(n)?n:0}function D6(){if(typeof window>"u")return new Map;try{const e=window.localStorage.getItem(Ny);if(!e)return new Map;const n=JSON.parse(e),s=new Map;for(const[a,r]of Object.entries(n))typeof r=="number"&&Number.isFinite(r)&&s.set(a,r);return s}catch{return new Map}}function tb(e){if(!(typeof window>"u"))try{const n={};for(const[s,a]of e)n[s]=a;window.localStorage.setItem(Ny,JSON.stringify(n))}catch{}}function L6(e,n){const s=new URL(e);return n&&s.searchParams.set("rt",n),s.toString()}function O6(e,n,s){return!n||s||e.host==="web"?!1:e.host==="mobile-shell"?!e.activeProfileId:e.desktopMode==="local"?!1:!e.activeProfileId}function F6(){const{toasts:e,addToast:n,removeToast:s}=yz(),{shellApi:a,state:r,ready:o,openConnectionManagerSignal:l}=Zv(),c=u6();i.useEffect(()=>{T6()},[]);const{projects:d,loading:u,error:h,refresh:m}=fz(),{nodes:f}=_c(),{currentNode:p,currentNodeId:g,isRemote:w,setCurrentNode:v,clearCurrentNode:b}=Qz(),{currentProject:y,setCurrentProject:j,clearCurrentProject:S,loading:C}=xz(d,{nodeId:g}),{hasAiProvider:x,hasGithub:k,loading:R,hasWarnings:O}=Jv(y?.id),{updateAvailable:E,latestVersion:_,currentVersion:G,dismissed:H,dismiss:A}=Tz();i.useEffect(()=>{if(g&&!p&&f.length>0){const Ce=f.find(at=>at.id===g);if(Ce){v(Ce);return}}g&&f.length>0&&(f.some(at=>at.id===g)||b())},[g,p,f,v,b]);const[P,q]=i.useState(""),[Y,ge]=i.useState(""),[L,M]=i.useState("");i.useEffect(()=>{ge(Ln(Qg,y?.id)??""),M(Ln(Xg,y?.id)??"")},[y?.id]);const $=i.useCallback(Ce=>{ge(Ce),rs(Qg,Ce,y?.id)},[y?.id]),D=i.useCallback(Ce=>{M(Ce),rs(Xg,Ce,y?.id)},[y?.id]),N=Gz(g,{projectId:y?.id,searchQuery:P||void 0});Kz(g);const W=w&&N.projects.length>0?N.projects:d,{themeMode:de,colorTheme:me,dashboardFontScalePct:Ne,setThemeMode:ve,setColorTheme:Me,setDashboardFontScalePct:ie}=Ez(),{sessions:ye,generating:Z,needsInput:fe,planningSessions:Q,dismissSession:F}=rz(y?.id),X=ye.filter(Ce=>Ce.status==="awaiting_input"||Ce.status==="error"),re=cz(),U=_z({projectId:y?.id,planningSessions:Q}),Ue=ei()==="mobile",{pushNav:se,replaceCurrent:Ve}=D$({enabled:!0}),{viewMode:Le,setViewMode:ct,taskView:Ke,handleChangeTaskView:oe}=Lz({projectsLoading:u,projectsError:h,currentProjectLoading:C,currentProject:y,projectsLength:d.length,setupWizardOpen:U.setupWizardOpen,openSetupWizard:U.openSetupWizard,themeMode:de,setThemeMode:ve}),{views:Te}=Fz(y?.id),Fe=i.useMemo(()=>{const Ce=Te.find(at=>at.pluginId==="fusion-plugin-dependency-graph"&&at.view.viewId==="graph");return Ce?`plugin:${Ce.pluginId}:${Ce.view.viewId}`:Wb("fusion-plugin-dependency-graph","graph")?"plugin:fusion-plugin-dependency-graph:graph":null},[Te]),mt=i.useCallback(Ce=>{Ce==="missions"&&(Gt(void 0),Ht(void 0),ae(void 0));const at=Ke;oe(Ce),at!==Ce&&se({type:"view",revert:()=>oe(at)})},[oe,Ke,se]),We=Ke==="board"||Ke==="list",{tasks:he,createTask:pe,moveTask:De,pauseTask:ut,unpauseTask:ht,deleteTask:et,mergeTask:vt,retryTask:Oe,resetTask:tt,updateTask:ft,duplicateTask:Mt,archiveTask:yt,unarchiveTask:Ge,archiveAllDone:K,loadArchivedTasks:ue,ingestCreatedTasks:ot,lastFetchTimeMs:xe}=uz({...y?{projectId:y.id}:{},searchQuery:P||void 0,sseEnabled:We}),dt=w&&N.tasks.length>0?N.tasks:he,[Je,ke]=i.useState(!1),[nt,bt]=i.useState(0),kt=i.useRef(performance.now()),wt=i.useRef(!1),At=i.useRef(!1),Ft=i.useMemo(()=>u?"projects":C?"project":"tasks",[u,C]);i.useEffect(()=>{if(!u&&!wt.current){wt.current=!0;const Ce=`projects loaded at ${Math.round(performance.now()-kt.current)}ms from mount`;console.log(`[App] ${Ce}`)}if(!C&&!At.current){At.current=!0;const Ce=`current-project resolved at ${Math.round(performance.now()-kt.current)}ms from mount`;console.log(`[App] ${Ce}`)}},[u,C]),i.useEffect(()=>{if(Je||u||C)return;const Ce=performance.now(),at=window.setTimeout(()=>{const It=`dashboard ready at ${Math.round(performance.now()-kt.current)}ms from mount (settle delay=${Math.round(performance.now()-Ce)}ms)`;console.log(`[App] ${It}`),ke(!0)},w6);return()=>{window.clearTimeout(at)}},[Je,u,C]);const{keyboardOpen:ln}=ea({enabled:Ue}),Vt=Ue&&ln&&!U.anyModalOpen;Si(Vt);const[hn,un]=i.useState(0),[pn,an]=i.useState(0),[Wt,gn]=i.useState(!1),[cn,tn]=i.useState(0),[Yt,Qt]=i.useState(null),Kt=i.useRef(new Map),Jt=i.useRef(new Set),rn=i.useRef(D6()),qt=i.useCallback(()=>{Fb(y?.id).then(Ce=>{un(Ce.unreadCount),an(Ce.pendingApprovalCount??0)}).catch(Ce=>{console.warn("[App] Failed to fetch mailbox unread count:",Ce)})},[y?.id]);i.useEffect(()=>{const Ce=new Map,at=new Set;for(const It of he)Ce.set(It.id,It.status),It.status==="awaiting-approval"&&at.add(`task:${It.id}`);Kt.current=Ce,Jt.current=at},[he]),i.useEffect(()=>{qt();const Ce=new URLSearchParams;y?.id&&Ce.set("projectId",y.id);const at=Ce.size>0?`?${Ce.toString()}`:"",It=Ze=>{const it=rn.current.get(Ze.dedupeKey);it!==void 0&&Ze.updatedAtMs<=it||Qt(Ze)};return fi(`/api/events${at}`,{onReconnect:qt,events:{"message:sent":qt,"message:received":qt,"message:read":qt,"message:deleted":qt,"approval:requested":Ze=>{qt();try{const it=JSON.parse(Ze.data),$t=it.id?`approval:${it.id}`:it.taskId?`task:${it.taskId}`:void 0;if(!$t||Jt.current.has($t))return;Jt.current.add($t),It({dedupeKey:$t,updatedAtMs:eb(it.updatedAt??it.createdAt)})}catch{}},"approval:updated":qt,"approval:decided":qt,"task:updated":Ze=>{try{const it=JSON.parse(Ze.data);if(!it?.id)return;const $t=`task:${it.id}`,Pn=Kt.current.get(it.id);if(Kt.current.set(it.id,it.status),it.status!=="awaiting-approval"){Jt.current.delete($t),rn.current.delete($t),tb(rn.current);return}if(Jt.current.has($t))return;$6(it.status,Pn)&&(Jt.current.add($t),It({dedupeKey:$t,updatedAtMs:eb(it.updatedAt)}),qt())}catch{}}}})},[y?.id,qt]),i.useEffect(()=>{Ke==="chat"&&gn(!1)},[Ke]),i.useEffect(()=>{let Ce=!1;const at=async()=>{try{const Ze=await I("/stash-recovery/orphans");Ce||tn(Ze.count??0)}catch{Ce||tn(0)}};at();const It=window.setInterval(()=>void at(),3e4);return()=>{Ce=!0,window.clearInterval(It)}},[y?.id]),i.useEffect(()=>{const Ce=new URLSearchParams;y?.id&&Ce.set("projectId",y.id);const at=Ce.size>0?`?${Ce.toString()}`:"";return fi(`/api/events${at}`,{events:{"chat:message:added":It=>{try{const Ze=JSON.parse(It.data),it=Ln(P6,y?.id);if(!it||Ze.role!=="assistant"||Ke==="chat"||Ze.sessionId!==it||Ze.projectId&&y?.id&&Ze.projectId!==y.id)return;gn(!0)}catch{}}}})},[y?.id,Ke]);const we=i.useMemo(()=>Array.from(new Set(dt.map(Ce=>Ce.branch?.trim()).filter(Ce=>!!(Ce&&Ce.length>0)))).sort((Ce,at)=>Ce.localeCompare(at)),[dt]),ze=i.useMemo(()=>Array.from(new Set(dt.map(Ce=>Ce.baseBranch?.trim()).filter(Ce=>!!(Ce&&Ce.length>0)))).sort((Ce,at)=>Ce.localeCompare(at)),[dt]),rt=i.useMemo(()=>dt.filter(Ce=>{const at=Ce.branch?.trim()??"",It=Ce.baseBranch?.trim()??"";if(Y===Zg){if(at.length>0)return!1}else if(Y.length>0&&at!==Y)return!1;if(L===Zg){if(It.length>0)return!1}else if(L.length>0&&It!==L)return!1;return!0}),[dt,Y,L]),[He,Ae]=i.useState(!1),[pt,Ct]=i.useState(!1),[Tt,Gt]=i.useState(void 0),[nn,Ht]=i.useState(void 0),[on,ae]=i.useState(void 0),[le,Qe]=i.useState(!1),[xt,zt]=i.useState(!1),[sn,xn]=i.useState(null),[$n,wn]=i.useState(()=>Ln(su,y?.id)==="true"),[zn,ce]=i.useState(()=>Ln(Hl,y?.id)==="true");i.useEffect(()=>{wn(Ln(su,y?.id)==="true")},[y?.id]),i.useEffect(()=>{ce(Ln(Hl,y?.id)==="true")},[y?.id]),i.useEffect(()=>{let Ce=!1;return cN().then(at=>{Ce||xn(at)}).catch(()=>{Ce||xn(null)}),()=>{Ce=!0}},[]),i.useEffect(()=>{const Ce=()=>{zt(!0)};return window.addEventListener(pu,Ce),()=>{window.removeEventListener(pu,Ce)}},[]);const ee=i.useCallback(()=>{rs(su,"true",y?.id),wn(!0)},[y?.id]),Se=i.useCallback(()=>{rs(Hl,"true",y?.id),ce(!0)},[y?.id]),{maxConcurrent:qe,autoMerge:z,globalPaused:_e,enginePaused:Rt,taskStuckTimeoutMs:Ot,staleHighFanoutBlockerAgeThresholdMs:Lt,capacityRiskBannerEnabled:fn,capacityRiskTodoThreshold:kn,showQuickChatFAB:es,prAuthAvailable:ms,settingsLoaded:Gn,experimentalFeatures:hs,insightsEnabled:Cn,memoryEnabled:Bt,devServerEnabled:Bn,todosEnabled:En,toggleAutoMerge:bs,toggleGlobalPause:$s,toggleEnginePause:ss,refresh:Un}=Mz(y?.id),{stats:Kn}=cy(y?.id),Ms=i.useMemo(()=>dt.filter(Ce=>Ce.column==="in-progress").length,[dt]),xs=i.useMemo(()=>dt.filter(Ce=>Ce.column==="in-review").length,[dt]),As=i.useMemo(()=>Oj({todoCount:Kn?.todoTaskCount??0,inProgressCount:Ms,inReviewCount:xs,idleNonEphemeralAgentCount:Kn?.idleNonEphemeralCount??0,threshold:kn??Lj}),[Kn?.todoTaskCount,Kn?.idleNonEphemeralCount,Ms,xs,kn]),vs=i.useRef(fn),te=i.useRef(kn),Ee=i.useRef(y?.id);i.useEffect(()=>{if(Ee.current!==y?.id){Ee.current=y?.id,vs.current=fn,te.current=kn;return}const Ce=vs.current,at=te.current;(!Ce&&fn||at!==kn)&&(qa(Hl,y?.id),ce(!1)),Ee.current=y?.id,vs.current=fn,te.current=kn},[fn,kn,y?.id]);const T=hs.skillsView===!0,je=hs.nodesView===!0,Pe=hs.researchView===!0,st=hs.evalsView===!0,gt=hs.agentOnboarding===!0,Et=!0,Pt=i.useCallback(()=>{U.closeSettings(),bt(Ce=>Ce+1),Un()},[U,Un]);i.useEffect(()=>{if(Gn&&!kr(Ke)){if(Ke==="graph"&&!Fe){oe("board");return}Ke==="skills"&&!T&&oe("board"),Ke==="insights"&&!Cn&&oe("board"),Ke==="memory"&&!Bt&&oe("board"),(Ke==="devserver"||Ke==="dev-server")&&!Bn&&oe("board"),Ke==="research"&&!Pe&&oe("board"),Ke==="evals"&&!st&&oe("board")}},[Ke,Gn,T,Cn,oe,Et,Bt,Bn,Pe,st,Fe]),i.useEffect(()=>{He&&!je&&Ae(!1)},[He,je]);const{availableModels:dn,favoriteProviders:Nn,favoriteModels:Hn,toggleFavoriteProvider:ne,toggleFavoriteModel:Be}=Rz();Iz({projectId:y?.id,setupWizardOpen:U.setupWizardOpen,openModelOnboarding:U.openModelOnboarding,openSettings:U.openSettings});const{handleSelectProject:Xe,handleViewAllProjects:Dt,handleAddProject:Xt,handleSetupComplete:mn,handleModelOnboardingComplete:qn,handlePauseProject:Dn,handleResumeProject:ts,handleRemoveProject:Vn,handleToggleFavorite:os,handleToggleModelFavorite:ns}=Vz({setCurrentProject:j,clearCurrentProject:S,setViewMode:ct,currentProject:y,refreshProjects:m,toggleFavoriteProvider:ne,toggleFavoriteModel:Be,addToast:n,openSettings:U.openSettings,openSetupWizard:U.openSetupWizard,closeSetupWizard:U.closeSetupWizard,closeModelOnboarding:U.closeModelOnboarding}),{handleDetailClose:ja}=Az({projectId:y?.id,projects:d,projectsLoading:u,currentProject:y,setCurrentProject:j,addToast:n,openTaskDetail:U.openDetailTask,closeTaskDetail:U.closeDetailTask}),Na=i.useCallback(async({insightId:Ce,title:at,description:It})=>{await pe({title:at,description:It,column:"triage",source:{sourceType:"dashboard_ui",sourceMetadata:{origin:"insights",insightId:Ce}}})},[pe]),{handleBoardQuickCreate:zi,handleModalCreate:Kr,handlePlanningTaskCreated:Us,handlePlanningTasksCreated:Bi,handleSubtaskTasksCreated:Qa,handleGitHubImport:ls}=Wz({createTask:pe,ingestCreatedTasks:ot,onPlanningTaskCreated:U.onPlanningTaskCreated,onPlanningTasksCreated:U.onPlanningTasksCreated,onSubtaskTasksCreated:U.onSubtaskTasksCreated,addToast:n}),Jr=i.useCallback((Ce,at)=>{at==="changes"?U.openDetailWithChangesTab(Ce):U.openDetailTask(Ce,at),se({type:"modal",close:U.closeDetailTask})},[U,se]),ta=i.useCallback(async Ce=>{try{const at=await Ba(Ce,y?.id);U.openDetailTask(at,"logs"),se({type:"modal",close:U.closeDetailTask})}catch(at){n(`Failed to open task logs: ${at.message}`,"error")}},[U,y?.id,n,se]),[Js,gi]=i.useState([]);i.useEffect(()=>{let Ce=!1;return Jo(y?.id).then(at=>{Ce||gi(at)}).catch(()=>{Ce||gi([])}),()=>{Ce=!0}},[y?.id]);const na=i.useMemo(()=>new Map(Js.map(Ce=>[Ce.id,Ce.name])),[Js]);i.useCallback(()=>{je&&Ae(Ce=>!Ce)},[je]);const Sa=i.useCallback(()=>{je&&(He?Ae(!1):(Ae(!0),se({type:"view",revert:()=>Ae(!1)})))},[je,He,se]),bi=i.useCallback((Ce,at,It)=>{U.openDetailTask(Ce,at,It),se({type:"modal",close:U.closeDetailTask})},[U,se]),_n=i.useCallback(Ce=>{U.openSettings(Ce),se({type:"modal",close:Pt})},[U,se,Pt]),Ca=i.useCallback(()=>{U.openNewTask(),se({type:"modal",close:U.closeNewTask})},[U,se]),sa=i.useCallback(()=>{U.openPlanning(),se({type:"modal",close:U.closePlanning})},[U,se]),ia=i.useCallback(Ce=>{U.openPlanningWithInitialPlan(Ce),se({type:"modal",close:U.closePlanning})},[U,se]),Xa=i.useCallback(()=>{U.resumePlanning(),se({type:"modal",close:U.closePlanning})},[U,se]),Ui=i.useCallback(Ce=>{U.openSubtaskBreakdown(Ce),se({type:"modal",close:U.closeSubtask})},[U,se]),aa=i.useCallback(()=>{U.openGitHubImport(),se({type:"modal",close:U.closeGitHubImport})},[U,se]),ra=i.useCallback(()=>{U.terminalOpen?U.toggleTerminal():(U.toggleTerminal(),se({type:"modal",close:U.closeTerminal}))},[U,se]),xi=i.useCallback((Ce,at)=>{U.openFiles(Ce,at),se({type:"modal",close:U.closeFiles})},[U,se]),Za=i.useCallback((Ce,at)=>{U.openFiles(at?.workspace,Ce),se({type:"modal",close:U.closeFiles})},[U,se]),Ea=i.useCallback(()=>{U.openTodos(),se({type:"modal",close:U.closeTodos})},[U,se]),_a=i.useCallback(()=>{U.openActivityLog(),se({type:"modal",close:U.closeActivityLog})},[U,se]),Hs=i.useCallback(()=>{U.openGitManager(),se({type:"modal",close:U.closeGitManager})},[U,se]),Ci=i.useCallback(()=>{U.openSystemStats(),se({type:"modal",close:U.closeSystemStats})},[U,se]),ni=i.useCallback(()=>{U.openSchedules(),se({type:"modal",close:U.closeSchedules})},[U,se]),er=i.useCallback(()=>{U.openScripts(),se({type:"modal",close:U.closeScripts})},[U,se]),Ei=i.useCallback(()=>{U.openWorkflowSteps(),se({type:"modal",close:U.closeWorkflowSteps})},[U,se]),Ma=i.useCallback(Ce=>{U.openUsage(Ce),se({type:"modal",close:U.closeUsage})},[U,se]),si=i.useCallback(async(Ce,at)=>{await U.runScript(Ce,at),Ve({type:"modal",close:U.closeTerminal})},[U,Ve]),tr=i.useCallback(()=>{U.closeSettings(),U.openModelOnboarding(),Ve({type:"modal",close:U.closeModelOnboarding})},[U,Ve]),Yr=i.useCallback(()=>{U.setFileWorkspace("project"),U.openFiles()},[U]),nr=i.useCallback(async()=>{Ct(!0);try{await m()}finally{Ct(!1)}},[m]),oa=i.useCallback(Ce=>{Ht(Ce),Gt(void 0),oe("missions")},[oe]),sr=i.useCallback(Ce=>{Ce.type==="planning"?U.openPlanningWithSession(Ce.id):Ce.type==="subtask"?U.openSubtaskWithSession(Ce.id):Ce.type==="mission_interview"?(Ht(void 0),Gt(Ce.id),ae(void 0),oe("missions")):(Ce.type==="milestone_interview"||Ce.type==="slice_interview")&&(Gt(void 0),Ht(void 0),ae(Ce.id),oe("missions"))},[oe,U]),Qr=i.useCallback(()=>{},[]),Xr=i.useCallback(()=>{},[]),[ir,ar]=i.useState(!1),[rr,vi]=i.useState(!1),[_i,Aa]=i.useState(null),or=O6(r,o,ir);i.useEffect(()=>{!a||l===0||vi(!0)},[a,l]),i.useEffect(()=>{let Ce=!1;return v6(c.host).then(at=>{Ce||Aa(at)}),()=>{Ce=!0}},[c.host,r.activeProfileId,r.desktopMode,r.host,r.profiles]),i.useEffect(()=>{r.host==="desktop-shell"&&r.desktopMode==="local"&&(r.localServer?.status!=="ready"||!r.localServer.port||window.location.port!==String(r.localServer.port)&&(window.location.href=`http://localhost:${r.localServer.port}`))},[r]),i.useEffect(()=>{if(r.host!=="desktop-shell"||r.desktopMode!=="remote")return;const Ce=r.profiles.find(It=>It.id===r.activeProfileId);if(!Ce||typeof window>"u")return;const at=L6(Ce.serverUrl,Ce.authToken??null);window.location.href!==at&&(window.location.href=at)},[r]);const B=!u&&!C&&d.length===0&&!y&&!!h,$e=()=>{if(B)return t.jsx(oF,{errorMessage:h??"Failed to fetch projects",isRetrying:pt,onRetry:nr,onManageConnection:a?()=>{a.openConnectionManager()}:void 0});if(He)return t.jsx("div",{className:"nodes-management-overlay",children:t.jsx(Cs,{children:t.jsx(i.Suspense,{fallback:null,children:t.jsx(E6,{addToast:n,onClose:()=>Ae(!1)})})})});if(Le==="overview")return t.jsx(Cs,{children:t.jsx(P$,{projects:d,loading:u,onSelectProject:Xe,onAddProject:Xt,onPauseProject:Dn,onResumeProject:ts,onRemoveProject:Vn,nodes:f})});const Ce=Ke==="graph"?Fe:kr(Ke)?Ke:null;return Ce?t.jsx(Cs,{children:t.jsx(zz,{taskView:Ce,context:{projectId:y?.id,tasks:w&&N.tasks.length>0?N.tasks:he,workflowSteps:Js,openTaskDetail:(at,It)=>bi(at,It),renderTaskCard:at=>t.jsx(Oo,{task:at,projectId:y?.id,onOpenDetail:It=>bi(It),addToast:n,workflowStepNameLookup:na,disableDrag:!0}),addToast:n}})}):Ke==="skills"?!Gn||!T?null:t.jsx(Cs,{children:t.jsx(i.Suspense,{fallback:null,children:t.jsx(M6,{addToast:n,projectId:y?.id,onClose:()=>oe("board")})})}):Ke==="chat"?t.jsx(Cs,{children:t.jsx(i.Suspense,{fallback:null,children:t.jsx(_6,{addToast:n,projectId:y?.id,experimentalFeatures:hs})})}):Ke==="mailbox"?t.jsx(Cs,{children:t.jsx(A4,{projectId:y?.id,addToast:n,onUnreadCountChange:un})}):Ke==="missions"?t.jsx(Cs,{children:t.jsx(S4,{isInline:!0,isOpen:!0,onClose:()=>{Ht(void 0),Gt(void 0),ae(void 0),oe("board")},addToast:n,projectId:y?.id,onSelectTask:at=>{const It=he.find(Ze=>Ze.id===at);It&&bi(It)},availableTasks:he.map(at=>({id:at.id,title:at.title})),resumeSessionId:Tt,targetMissionId:nn,milestoneSliceResumeSessionId:on,onMilestoneSliceResumeFetchError:()=>ae(void 0)})}):Ke==="agents"&&Et?t.jsx(Cs,{children:t.jsx(i.Suspense,{fallback:null,children:t.jsx(k6,{addToast:n,projectId:y?.id,onOpenTaskLogs:ta,agentOnboardingEnabled:gt})})}):Ke==="documents"?t.jsx(Cs,{children:t.jsx(i.Suspense,{fallback:null,children:t.jsx(j6,{projectId:y?.id,addToast:n,onOpenDetail:bi})})}):Ke==="stash-recovery"?t.jsx(Cs,{children:t.jsx(i.Suspense,{fallback:null,children:t.jsx(I6,{})})}):Ke==="insights"?!Gn||!Cn?null:t.jsx(Cs,{children:t.jsx(i.Suspense,{fallback:null,children:t.jsx(N6,{projectId:y?.id,addToast:n,onClose:()=>oe("board"),onCreateTask:Na})})}):Ke==="research"?!Gn||!Pe?null:t.jsx(Cs,{children:t.jsx(i.Suspense,{fallback:null,children:t.jsx(S6,{projectId:y?.id,addToast:n,onOpenSettings:at=>U.openSettings(at),readinessVersion:nt})})}):Ke==="evals"?!Gn||!st?null:t.jsx(Cs,{children:t.jsx(i.Suspense,{fallback:null,children:t.jsx(C6,{projectId:y?.id,onOpenSettings:at=>U.openSettings(at),onOpenTaskDetail:at=>{Ba(at,y?.id).then(It=>bi(It)).catch(It=>n(It instanceof Error?It.message:"Failed to open task detail","error"))}})})}):Ke==="memory"?!Gn||!Bt?null:t.jsx(Cs,{children:t.jsx(i.Suspense,{fallback:null,children:t.jsx(A6,{addToast:n,projectId:y?.id})})}):Ke==="devserver"||Ke==="dev-server"?!Gn||!Bn?null:t.jsx(Cs,{children:t.jsx(i.Suspense,{fallback:null,children:t.jsx(R6,{addToast:n,projectId:y?.id})})}):Ke==="board"?t.jsxs(Cs,{children:[fn&&!zn?t.jsx(_F,{signal:As,onDismiss:Se}):null,t.jsx(x_,{tasks:rt,projectId:y?.id,maxConcurrent:qe,onMoveTask:De,onPauseTask:ut,onOpenDetail:bi,addToast:n,onQuickCreate:zi,onNewTask:Ca,onPlanningMode:ia,onSubtaskBreakdown:Ui,autoMerge:z,onToggleAutoMerge:bs,globalPaused:_e,onUpdateTask:ft,onRetryTask:Oe,onArchiveTask:yt,onUnarchiveTask:Ge,onDeleteTask:et,onArchiveAllDone:K,onLoadArchivedTasks:ue,searchQuery:P,availableModels:dn,onOpenDetailWithTab:Jr,favoriteProviders:Nn,favoriteModels:Hn,onToggleFavorite:os,onToggleModelFavorite:ns,taskStuckTimeoutMs:Ot,staleHighFanoutBlockerAgeThresholdMs:Lt,onOpenMission:oa,lastFetchTimeMs:xe})]}):t.jsx(Cs,{children:t.jsx(k$,{tasks:w&&N.tasks.length>0?N.tasks:he,projectId:y?.id,onMoveTask:De,onRetryTask:Oe,onDeleteTask:et,onPauseTask:ut,onUnpauseTask:ht,onArchiveTask:yt,onMergeTask:vt,onResetTask:tt,onDuplicateTask:Mt,onOpenDetail:(at,It)=>bi(at,void 0,It),addToast:n,globalPaused:_e,onNewTask:Ca,onQuickCreate:zi,onPlanningMode:ia,onSubtaskBreakdown:Ui,availableModels:dn,favoriteProviders:Nn,favoriteModels:Hn,onToggleFavorite:os,onToggleModelFavorite:ns,taskStuckTimeoutMs:Ot,searchQuery:P,lastFetchTimeMs:xe,prAuthAvailable:ms})})},Ye=!U.modelOnboardingOpen&&AO(),jt=!U.modelOnboardingOpen&&!Ye&&Lr()&&!ey();return t.jsx($$,{value:{pushNav:se,replaceCurrent:Ve},children:t.jsx(XT,{openFile:Za,children:Je?t.jsxs(t.Fragment,{children:[t.jsx(nE,{shellHost:c.host,onOpenSettings:_n,onOpenGitHubImport:aa,onOpenPlanning:sa,onResumePlanning:Xa,activePlanningSessionCount:Q.length,onOpenUsage:Ma,onOpenActivityLog:_a,onOpenSystemStats:Ci,onOpenMailbox:()=>mt("mailbox"),mailboxUnreadCount:hn,mailboxPendingApprovalCount:pn,chatHasUnreadResponse:Wt,stashOrphanCount:cn,onOpenSchedules:ni,onOpenGitManager:Hs,onOpenNodes:Sa,showNodesButton:je,onOpenWorkflowSteps:Ei,onOpenScripts:er,onRunScript:si,onToggleTerminal:ra,onOpenFiles:xi,filesOpen:U.filesOpen,onOpenTodos:Ea,todosOpen:U.todosOpen,todosEnabled:En,globalPaused:_e,enginePaused:Rt,onToggleGlobalPause:$s,onToggleEnginePause:ss,view:Ke,onChangeView:Le==="project"&&y?mt:void 0,showSkillsTab:T,showAgentsTab:Et,searchQuery:P,onSearchChange:q,branchFilter:Y,baseBranchFilter:L,branchOptions:we,baseBranchOptions:ze,onBranchFilterChange:$,onBaseBranchFilterChange:D,projects:W,currentProject:y,onSelectProject:Xe,onViewAllProjects:Dt,projectId:y?.id,mobileNavEnabled:Ue,availableNodes:f,currentNode:p,onSelectNode:Ce=>{Ce===null?b():v(Ce)},isRemote:w,experimentalFeatures:{insights:Cn,memoryView:Bt,devServer:Bn,devServerView:Bn,researchView:Pe,evalsView:st},pluginDashboardViews:Te,shellConnectionControl:!Ue&&_i?t.jsx(Yg,{status:_i,onError:Ce=>n(Ce,"error")}):void 0}),Le==="project"&&y&&!He&&Ke!=="missions"&&!U.isPlanningOpen&&!re&&t.jsx(NF,{sessions:X,onResumeSession:sr,onDismissSession:Qr,onDismissAll:Xr}),Le==="project"&&y&&t.jsx(EF,{onOpenSettings:()=>U.openSettings("general")}),Le==="project"&&y&&Ye&&t.jsx(PF,{onResume:U.openModelOnboarding}),Le==="project"&&y&&jt&&t.jsx($F,{onOpenModelOnboarding:U.openModelOnboarding,onOpenSettings:Ce=>U.openSettings(Ce)}),Le==="project"&&y&&E&&_&&G&&!H&&t.jsx(IF,{latestVersion:_,currentVersion:G,onDismiss:A}),Le==="project"&&y&&sn?.taskIdIntegrity?.status==="anomaly"&&sn.taskIdIntegrity.recommendedAction&&t.jsx(RF,{report:sn.taskIdIntegrity,recommendedAction:sn.taskIdIntegrity.recommendedAction,onRefresh:(Ce,at)=>{xn(It=>It?{...It,status:Ce.status==="anomaly"||!It.database.healthy?"degraded":"ok",taskIdIntegrity:{...Ce,recommendedAction:at}}:null)}}),Le==="project"&&y&&!R&&O&&!$n&&t.jsx(Yv,{hasAiProvider:x,hasGithub:k,onDismiss:ee}),Le==="project"&&y&&Yt&&t.jsx(TF,{pendingCount:Math.max(pn,1),onOpenMailbox:()=>mt("mailbox"),onDismiss:()=>{rn.current.set(Yt.dedupeKey,Math.max(Date.now(),Yt.updatedAtMs)),tb(rn.current),Qt(null)}}),t.jsx("div",{className:`project-content${Le==="project"&&y&&(!Ue||!Vt)?" project-content--with-footer":""}${Ue&&!Vt?" project-content--with-mobile-nav":""}`,children:$e()}),Le==="project"&&y&&!He&&t.jsx(vF,{tasks:w&&N.tasks.length>0?N.tasks:he,projectId:y.id,taskStuckTimeoutMs:Ot,staleHighFanoutBlockerAgeThresholdMs:Lt,backgroundSessions:ye,backgroundGenerating:Z,backgroundNeedsInput:fe,onOpenBackgroundSession:sr,onDismissBackgroundSession:F,lastFetchTimeMs:xe,currentProjectPath:y.path,onOpenProjectDirectory:Yr,keyboardOpen:Vt}),t.jsx(LF,{view:Ke,onChangeView:Le==="project"&&y?mt:()=>{},footerVisible:Le==="project"&&!!y,modalOpen:U.anyModalOpen,keyboardOpen:Vt,onOpenSettings:_n,onOpenActivityLog:_a,onOpenSystemStats:Ci,onOpenMailbox:()=>mt("mailbox"),onOpenNodes:Sa,mailboxUnreadCount:hn,mailboxPendingApprovalCount:pn,chatHasUnreadResponse:Wt,stashOrphanCount:cn,onOpenGitManager:Hs,onOpenWorkflowSteps:Ei,onOpenSchedules:ni,onOpenScripts:er,onToggleTerminal:ra,onOpenFiles:xi,onOpenTodos:Ea,todosOpen:U.todosOpen,onOpenGitHubImport:aa,onOpenPlanning:sa,onResumePlanning:Xa,activePlanningSessionCount:Q.length,onOpenUsage:()=>Ma(null),onViewAllProjects:Dt,onRunScript:si,projectId:y?.id,showSkillsTab:T,experimentalFeatures:{insights:Cn,memoryView:Bt,devServer:Bn,devServerView:Bn,todoView:En,researchView:Pe,evalsView:st,nodesView:je},pluginDashboardViews:Te,shellConnectionControl:Ue&&_i?t.jsx(Yg,{status:_i,onError:Ce=>n(Ce,"error")}):void 0}),Le==="project"&&y&&Ke!=="chat"&&Ke!=="mailbox"&&Ke!=="insights"&&Ke!=="evals"&&Ke!=="devserver"&&Ke!=="dev-server"&&Ke!=="graph"&&!kr(Ke)&&t.jsx(az,{projectId:y.id,addToast:n,showFAB:es,open:le,onOpenChange:Qe,favoriteProviders:Nn,favoriteModels:Hn,onToggleFavorite:os,onToggleModelFavorite:ns}),t.jsx(rF,{projectId:y?.id,tasks:he,projects:d,currentProject:y,addToast:n,toasts:e,removeToast:s,modalManager:U,projectActions:{handleAddProject:Xt,handleSetupComplete:mn,handleModelOnboardingComplete:qn},taskHandlers:{handleModalCreate:Kr,handlePlanningTaskCreated:Us,handlePlanningTasksCreated:Bi,handleSubtaskTasksCreated:Qa,handleGitHubImport:ls},taskOperations:{moveTask:De,deleteTask:et,mergeTask:vt,retryTask:Oe,resetTask:tt,duplicateTask:Mt},deepLink:{handleDetailClose:ja},settings:{prAuthAvailable:ms,themeMode:de,colorTheme:me,dashboardFontScalePct:Ne,setThemeMode:ve,setColorTheme:Me,setDashboardFontScalePct:ie},onSettingsClose:Pt,onReopenOnboarding:tr}),t.jsx(y6,{open:xt}),a&&t.jsxs(t.Fragment,{children:[t.jsx(h6,{open:or,shellApi:a,shellState:r,onComplete:()=>ar(!0)}),t.jsx(p6,{open:rr,shellApi:a,shellState:r,onClose:()=>vi(!1)})]})]}):t.jsxs(t.Fragment,{children:[t.jsx(cF,{stage:Ft}),t.jsx(iy,{toasts:e,onRemove:s})]})})})}function z6(){return t.jsx(vz,{children:t.jsx(d6,{children:t.jsx(xO,{children:t.jsx(Yz,{children:t.jsx(aE,{children:t.jsx(F6,{})})})})})})}function Sy(e){e.postMessage({type:"SKIP_WAITING"})}function nb(e){e.addEventListener("statechange",()=>{e.state==="installed"&&navigator.serviceWorker.controller&&Sy(e)})}function B6(){if(!("serviceWorker"in navigator))return;const e=!!navigator.serviceWorker.controller;let n=!1;navigator.serviceWorker.addEventListener("controllerchange",()=>{n||!e||(n=!0,Gu("service worker activated new version"))}),navigator.serviceWorker.register("/sw.js").then(s=>{console.log("SW registered:",s.scope),s.waiting&&navigator.serviceWorker.controller&&Sy(s.waiting),s.installing&&nb(s.installing),s.addEventListener("updatefound",()=>{const a=s.installing;a&&nb(a)})}).catch(s=>{console.log("SW registration failed:",s)})}oN();Tj();ky();xy();Ty.createRoot(document.getElementById("root")).render(t.jsx(i.StrictMode,{children:t.jsx(Pj,{children:t.jsx(z6,{})})}));B6();export{_1 as $,Vs as A,Xn as B,Zn as C,Jj as D,k5 as E,xa as F,xc as G,cu as H,Tn as I,Gl as J,eB as K,St as L,Vo as M,Lk as N,aO as O,On as P,Qd as Q,us as R,Gi as S,Br as T,is as U,di as V,In as W,bn as X,tO as Y,as as Z,Sn as _,vn as a,P5 as a$,GL as a0,KL as a1,M1 as a2,v5 as a3,A1 as a4,I3 as a5,T3 as a6,PS as a7,qu as a8,zr as a9,q8 as aA,H8 as aB,U8 as aC,z8 as aD,uN as aE,Do as aF,D8 as aG,O8 as aH,L8 as aI,J8 as aJ,G8 as aK,K8 as aL,Y8 as aM,L5 as aN,Z8 as aO,$o as aP,iu as aQ,oj as aR,Pi as aS,Xk as aT,kw as aU,ks as aV,A$ as aW,Os as aX,gb as aY,Yk as aZ,T5 as a_,Ka as aa,hi as ab,pi as ac,mi as ad,_8 as ae,T8 as af,I8 as ag,Xl as ah,P8 as ai,M8 as aj,$8 as ak,A8 as al,R8 as am,cs as an,Fr as ao,_o as ap,zs as aq,xj as ar,Di as as,cb as at,Yi as au,Uy as av,F8 as aw,B8 as ax,W8 as ay,V8 as az,Wn as b,n5 as b$,$5 as b0,D5 as b1,_c as b2,fz as b3,gh as b4,to as b5,_g as b6,yC as b7,qa as b8,gC as b9,ub as bA,Hm as bB,Ki as bC,x8 as bD,b8 as bE,v8 as bF,m3 as bG,u3 as bH,d3 as bI,h3 as bJ,k3 as bK,j3 as bL,v3 as bM,g3 as bN,b3 as bO,x3 as bP,f3 as bQ,p3 as bR,c3 as bS,y3 as bT,TD as bU,Z3 as bV,X3 as bW,a5 as bX,Q3 as bY,e5 as bZ,t5 as b_,y8 as ba,w8 as bb,bC as bc,BF as bd,Jc as be,vC as bf,zF as bg,S8 as bh,C8 as bi,k8 as bj,j8 as bk,N8 as bl,E8 as bm,Tv as bn,GF as bo,ea as bp,oy as bq,pC as br,gs as bs,ba as bt,gc as bu,OF as bv,Da as bw,pb as bx,VF as by,Ws as bz,lt as c,oS as c$,s5 as c0,i1 as c1,i5 as c2,Qu as c3,t1 as c4,n1 as c5,s1 as c6,e1 as c7,Y3 as c8,jc as c9,q3 as cA,B3 as cB,L3 as cC,U3 as cD,O3 as cE,H3 as cF,F3 as cG,z3 as cH,Yy as cI,GN as cJ,V3 as cK,KN as cL,W3 as cM,li as cN,Oi as cO,cz as cP,vD as cQ,N3 as cR,F5 as cS,cN as cT,Q6 as cU,yg as cV,M5 as cW,X6 as cX,e3 as cY,l3 as cZ,o3 as c_,aj as ca,Er as cb,U5 as cc,H5 as cd,q5 as ce,V5 as cf,W5 as cg,G5 as ch,K5 as ci,B5 as cj,Nb as ck,fk as cl,I as cm,nc as cn,Oo as co,_r as cp,H1 as cq,Zj as cr,eN as cs,ON as ct,FN as cu,c8 as cv,$3 as cw,P3 as cx,d8 as cy,D3 as cz,_5 as d,b5 as d$,YN as d0,Li as d1,QN as d2,ZN as d3,XN as d4,eS as d5,tS as d6,E3 as d7,A5 as d8,R5 as d9,J6 as dA,af as dB,Y6 as dC,K6 as dD,X8 as dE,w3 as dF,J5 as dG,Q5 as dH,e8 as dI,X5 as dJ,Y5 as dK,Z5 as dL,t8 as dM,gu as dN,Jm as dO,g5 as dP,x5 as dQ,cC as dR,Nw as dS,za as dT,Is as dU,ik as dV,n8 as dW,w5 as dX,qo as dY,mP as dZ,ma as d_,I5 as da,Xi as db,W6 as dc,G6 as dd,z5 as de,t3 as df,au as dg,ws as dh,RD as di,oO as dj,cO as dk,dO as dl,pa as dm,Xd as dn,mO as dp,s3 as dq,Z6 as dr,i3 as ds,n3 as dt,a3 as du,r3 as dv,Ua as dw,tB as dx,Vj as dy,Nc as dz,C5 as e,N5 as e0,j5 as e1,db as e2,p5 as e3,h5 as e4,o5 as e5,l5 as e6,WL as e7,Ra as e8,y5 as e9,_3 as eA,S3 as eB,C3 as eC,Vk as eD,A3 as eE,R3 as eF,M3 as eG,u5 as ea,d5 as eb,$S as ec,m5 as ed,f5 as ee,s8 as ef,aC as eg,c5 as eh,r5 as ei,ui as ej,J3 as ek,G3 as el,K3 as em,i8 as en,u8 as eo,du as ep,p8 as eq,f8 as er,h8 as es,o8 as et,r8 as eu,l8 as ev,a8 as ew,m8 as ex,O5 as ey,Q8 as ez,Ba as f,E5 as g,Bs as h,Hr as i,Fn as j,uc as k,g8 as l,Ns as m,E1 as n,S5 as o,ei as p,cy as q,JL as r,fi as s,Ln as t,Si as u,ti as v,rs as w,Cc as x,al as y,Ie as z};