@runfusion/fusion 0.25.0 → 0.26.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 (113) hide show
  1. package/README.md +6 -0
  2. package/dist/bin.js +47492 -45420
  3. package/dist/client/assets/{AgentDetailView-ZbHEbYRT.js → AgentDetailView-Cv-vgOj3.js} +3 -3
  4. package/dist/client/assets/{AgentsView-B3jYk8Kt.js → AgentsView-D6Zi5zfP.js} +4 -4
  5. package/dist/client/assets/ChatView-CAHjY9uO.js +1 -0
  6. package/dist/client/assets/{DevServerView-DyGDEiBP.js → DevServerView--_WBvIDQ.js} +1 -1
  7. package/dist/client/assets/{DirectoryPicker-D5UIeIl6.js → DirectoryPicker-xedtR-Rd.js} +1 -1
  8. package/dist/client/assets/{DocumentsView-DNHu1T8K.js → DocumentsView-Bg2oaZks.js} +1 -1
  9. package/dist/client/assets/{EvalsView-CpRobtDi.js → EvalsView-B3uOCXfr.js} +1 -1
  10. package/dist/client/assets/{ExperimentalAgentOnboardingModal-DOY_oZi7.js → ExperimentalAgentOnboardingModal-Bx6yXVS5.js} +1 -1
  11. package/dist/client/assets/{InsightsView-vp0RE8Mg.js → InsightsView-Q1zvtF4F.js} +1 -1
  12. package/dist/client/assets/{MemoryView-PSc5lGJt.js → MemoryView-xcN_eouf.js} +1 -1
  13. package/dist/client/assets/{NodesView-DMj6HGeC.js → NodesView-RxXg58_Q.js} +1 -1
  14. package/dist/client/assets/{PiExtensionsManager-DL_QcN56.js → PiExtensionsManager-Cc8aAZXg.js} +2 -2
  15. package/dist/client/assets/{PluginManager-BtYKm8IT.js → PluginManager-BEkyBajl.js} +1 -1
  16. package/dist/client/assets/{ResearchView-BzCcDAS4.css → ResearchView-BEI4ZSGs.css} +1 -1
  17. package/dist/client/assets/ResearchView-CERNf7sJ.js +1 -0
  18. package/dist/client/assets/{SettingsModal-CUCyaAyE.js → SettingsModal-B1r0yASu.js} +1 -1
  19. package/dist/client/assets/SettingsModal-BLsac7CJ.js +31 -0
  20. package/dist/client/assets/SettingsModal-Cis-4Lot.css +1 -0
  21. package/dist/client/assets/{SetupWizardModal-BKscasuh.js → SetupWizardModal-D1q548_L.js} +1 -1
  22. package/dist/client/assets/{SkillsView-BdELqTy7.js → SkillsView-ClLM6u6p.js} +1 -1
  23. package/dist/client/assets/StashRecoveryView-B_8WIQEo.css +1 -0
  24. package/dist/client/assets/StashRecoveryView-ze0pEZ5U.js +1 -0
  25. package/dist/client/assets/{TodoView-DFNGBDNV.js → TodoView-CTmIfy2M.js} +1 -1
  26. package/dist/client/assets/createLucideIcon-BazL2hk5.js +21 -0
  27. package/dist/client/assets/dashboard-view-4xAN3yO5.js +21 -0
  28. package/dist/client/assets/dashboard-view-BkTMSZYn.css +1 -0
  29. package/dist/client/assets/dashboard-view-CyWN-d02.js +63 -0
  30. package/dist/client/assets/dashboard-view-DdGlfuu-.css +1 -0
  31. package/dist/client/assets/{folder-open-k1xmUMyr.js → folder-open-BZuKESeq.js} +1 -1
  32. package/dist/client/assets/index-Bdw6llW6.js +692 -0
  33. package/dist/client/assets/index-CZGlyJuS.css +1 -0
  34. package/dist/client/assets/{star-ne32r3Y4.js → star-D75YKEq-.js} +1 -1
  35. package/dist/client/assets/{upload-MS-2Gx53.js → upload-BYYTgWFj.js} +1 -1
  36. package/dist/client/assets/{users-C519GSjH.js → users-RS90Aii3.js} +1 -1
  37. package/dist/client/index.html +2 -2
  38. package/dist/client/version.json +1 -1
  39. package/dist/droid-cli/package.json +1 -1
  40. package/dist/extension.js +4340 -3059
  41. package/dist/pi-claude-cli/package.json +1 -1
  42. package/dist/plugins/fusion-plugin-cli-printing-press/manifest.json +6 -0
  43. package/dist/plugins/fusion-plugin-cli-printing-press/package.json +26 -0
  44. package/dist/plugins/fusion-plugin-cli-printing-press/src/__tests__/manifest.test.ts +20 -0
  45. package/dist/plugins/fusion-plugin-cli-printing-press/src/index.ts +14 -0
  46. package/dist/plugins/fusion-plugin-cursor-runtime/package.json +1 -1
  47. package/dist/plugins/fusion-plugin-dependency-graph/package.json +1 -1
  48. package/dist/plugins/fusion-plugin-droid-runtime/package.json +1 -1
  49. package/dist/plugins/fusion-plugin-hermes-runtime/package.json +1 -1
  50. package/dist/plugins/fusion-plugin-openclaw-runtime/package.json +1 -1
  51. package/dist/plugins/fusion-plugin-paperclip-runtime/package.json +1 -1
  52. package/dist/plugins/fusion-plugin-reports/package.json +1 -1
  53. package/dist/plugins/fusion-plugin-roadmap/{src/dashboard/RoadmapsView.css → bundled.css} +13 -219
  54. package/dist/plugins/fusion-plugin-roadmap/bundled.js +29535 -0
  55. package/dist/plugins/fusion-plugin-roadmap/package.json +4 -41
  56. package/dist/plugins/fusion-plugin-whatsapp-chat/package.json +1 -1
  57. package/package.json +2 -3
  58. package/dist/client/assets/ChatView-DhPkiEGs.js +0 -1
  59. package/dist/client/assets/ResearchView-BhWqfdV0.js +0 -1
  60. package/dist/client/assets/SettingsModal-BAgB4_AR.js +0 -31
  61. package/dist/client/assets/SettingsModal-DzsLquBu.css +0 -1
  62. package/dist/client/assets/index-Qq2JOOWx.css +0 -1
  63. package/dist/client/assets/index-TFYXEVpn.js +0 -692
  64. package/dist/plugins/fusion-plugin-roadmap/src/__tests__/api-client.test.ts +0 -101
  65. package/dist/plugins/fusion-plugin-roadmap/src/__tests__/index.test.ts +0 -92
  66. package/dist/plugins/fusion-plugin-roadmap/src/__tests__/roadmap-routes.test.ts +0 -48
  67. package/dist/plugins/fusion-plugin-roadmap/src/__tests__/roadmap-suggestions.test.ts +0 -31
  68. package/dist/plugins/fusion-plugin-roadmap/src/dashboard/RoadmapsView.tsx +0 -2559
  69. package/dist/plugins/fusion-plugin-roadmap/src/dashboard/__tests__/RoadmapsView.test.tsx +0 -1144
  70. package/dist/plugins/fusion-plugin-roadmap/src/dashboard/__tests__/useRoadmaps.test.ts +0 -1756
  71. package/dist/plugins/fusion-plugin-roadmap/src/dashboard/api.ts +0 -70
  72. package/dist/plugins/fusion-plugin-roadmap/src/dashboard/test-setup.ts +0 -7
  73. package/dist/plugins/fusion-plugin-roadmap/src/dashboard/types.ts +0 -1
  74. package/dist/plugins/fusion-plugin-roadmap/src/dashboard/useConfirm.ts +0 -8
  75. package/dist/plugins/fusion-plugin-roadmap/src/dashboard/useRoadmaps.ts +0 -1188
  76. package/dist/plugins/fusion-plugin-roadmap/src/dashboard/useViewportMode.ts +0 -20
  77. package/dist/plugins/fusion-plugin-roadmap/src/dashboard-view.tsx +0 -6
  78. package/dist/plugins/fusion-plugin-roadmap/src/index.ts +0 -74
  79. package/dist/plugins/fusion-plugin-roadmap/src/roadmap-routes.ts +0 -1
  80. package/dist/plugins/fusion-plugin-roadmap/src/roadmap-schema.ts +0 -41
  81. package/dist/plugins/fusion-plugin-roadmap/src/roadmap-suggestions.d.ts +0 -15
  82. package/dist/plugins/fusion-plugin-roadmap/src/roadmap-suggestions.ts +0 -15
  83. package/dist/plugins/fusion-plugin-roadmap/src/roadmap-types.d.ts +0 -283
  84. package/dist/plugins/fusion-plugin-roadmap/src/roadmap-types.d.ts.map +0 -1
  85. package/dist/plugins/fusion-plugin-roadmap/src/roadmap-types.js +0 -21
  86. package/dist/plugins/fusion-plugin-roadmap/src/roadmap-types.js.map +0 -1
  87. package/dist/plugins/fusion-plugin-roadmap/src/roadmap-types.ts +0 -310
  88. package/dist/plugins/fusion-plugin-roadmap/src/routes/roadmap-routes.d.ts +0 -5
  89. package/dist/plugins/fusion-plugin-roadmap/src/routes/roadmap-routes.d.ts.map +0 -1
  90. package/dist/plugins/fusion-plugin-roadmap/src/routes/roadmap-routes.js +0 -361
  91. package/dist/plugins/fusion-plugin-roadmap/src/routes/roadmap-routes.js.map +0 -1
  92. package/dist/plugins/fusion-plugin-roadmap/src/routes/roadmap-routes.ts +0 -408
  93. package/dist/plugins/fusion-plugin-roadmap/src/routes/roadmap-suggestions.d.ts +0 -68
  94. package/dist/plugins/fusion-plugin-roadmap/src/routes/roadmap-suggestions.d.ts.map +0 -1
  95. package/dist/plugins/fusion-plugin-roadmap/src/routes/roadmap-suggestions.js +0 -300
  96. package/dist/plugins/fusion-plugin-roadmap/src/routes/roadmap-suggestions.js.map +0 -1
  97. package/dist/plugins/fusion-plugin-roadmap/src/routes/roadmap-suggestions.ts +0 -381
  98. package/dist/plugins/fusion-plugin-roadmap/src/server/index.d.ts +0 -3
  99. package/dist/plugins/fusion-plugin-roadmap/src/server/index.ts +0 -1
  100. package/dist/plugins/fusion-plugin-roadmap/src/store/__tests__/roadmap-handoff.test.ts +0 -445
  101. package/dist/plugins/fusion-plugin-roadmap/src/store/__tests__/roadmap-ordering.test.ts +0 -334
  102. package/dist/plugins/fusion-plugin-roadmap/src/store/__tests__/roadmap-store.test.ts +0 -1318
  103. package/dist/plugins/fusion-plugin-roadmap/src/store/roadmap-handoff.ts +0 -163
  104. package/dist/plugins/fusion-plugin-roadmap/src/store/roadmap-ordering.d.ts +0 -37
  105. package/dist/plugins/fusion-plugin-roadmap/src/store/roadmap-ordering.d.ts.map +0 -1
  106. package/dist/plugins/fusion-plugin-roadmap/src/store/roadmap-ordering.js +0 -188
  107. package/dist/plugins/fusion-plugin-roadmap/src/store/roadmap-ordering.js.map +0 -1
  108. package/dist/plugins/fusion-plugin-roadmap/src/store/roadmap-ordering.ts +0 -311
  109. package/dist/plugins/fusion-plugin-roadmap/src/store/roadmap-store.d.ts +0 -299
  110. package/dist/plugins/fusion-plugin-roadmap/src/store/roadmap-store.d.ts.map +0 -1
  111. package/dist/plugins/fusion-plugin-roadmap/src/store/roadmap-store.js +0 -765
  112. package/dist/plugins/fusion-plugin-roadmap/src/store/roadmap-store.js.map +0 -1
  113. package/dist/plugins/fusion-plugin-roadmap/src/store/roadmap-store.ts +0 -1001
@@ -1,692 +0,0 @@
1
- const __vite__mapDeps=(i,m=__vite__mapDeps,d=(m.f||(m.f=["assets/AgentDetailView-ZbHEbYRT.js","assets/vendor-react-K0fH_qHe.js","assets/star-ne32r3Y4.js","assets/ExperimentalAgentOnboardingModal-DOY_oZi7.js","assets/ExperimentalAgentOnboardingModal-B-APN_lM.css","assets/vendor-xterm-DzcZoU0P.js","assets/vendor-xterm-LZoznX6r.css","assets/AgentDetailView-BwJaLqZh.css","assets/addon-fit-C7jRorKK.js","assets/addon-web-links-CkJwd4cQ.js","assets/addon-webgl-BjvOw43o.js","assets/TodoView-DFNGBDNV.js","assets/TodoView-Cx9cVhq7.css","assets/SetupWizardModal-BKscasuh.js","assets/DirectoryPicker-D5UIeIl6.js","assets/folder-open-k1xmUMyr.js","assets/DirectoryPicker-DzKVmxOf.css","assets/projectDetection-G3XuxD2X.js","assets/SetupWizardModal-CGYGKurR.css","assets/SettingsModal-BAgB4_AR.js","assets/SettingsModal-CUCyaAyE.js","assets/SettingsModal-DzsLquBu.css","assets/users-C519GSjH.js","assets/SettingsModal-BNSrO1M9.css","assets/AgentsView-B3jYk8Kt.js","assets/upload-MS-2Gx53.js","assets/AgentsView-CV3vm7Qk.css","assets/DocumentsView-DNHu1T8K.js","assets/DocumentsView-gv4zG3aT.css","assets/InsightsView-vp0RE8Mg.js","assets/InsightsView-B0J4mhzV.css","assets/ResearchView-BhWqfdV0.js","assets/ResearchView-BzCcDAS4.css","assets/EvalsView-CpRobtDi.js","assets/EvalsView-CUNJ1TLc.css","assets/NodesView-DMj6HGeC.js","assets/NodesView-DT4pXowv.css","assets/ChatView-DhPkiEGs.js","assets/ChatView-DwJAd5G1.css","assets/SkillsView-BdELqTy7.js","assets/SkillsView-Cytf009Z.css","assets/MemoryView-PSc5lGJt.js","assets/MemoryView-zaXewZzi.css","assets/DevServerView-DyGDEiBP.js","assets/DevServerView-DlZpuAnj.css"])))=>i.map(i=>d[i]);
2
- import{r as i,j as t,R as kl,a as va,g as mg,c as Sv}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 hg=(...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 Cv=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 Ev=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 Yu=e=>{const n=Ev(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 uc={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 _v=e=>{for(const n in e)if(n.startsWith("aria-")||n==="role"||n==="title")return!0;return!1},Mv=i.createContext({}),Av=()=>i.useContext(Mv),Pv=i.forwardRef(({color:e,size:n,strokeWidth:s,absoluteStrokeWidth:a,className:r="",children:o,iconNode:l,...c},d)=>{const{size:u=24,strokeWidth:m=2,absoluteStrokeWidth:h=!1,color:f="currentColor",className:p=""}=Av()??{},g=a??h?Number(s??m)*24/Number(n??u):s??m;return i.createElement("svg",{ref:d,...uc,width:n??u??uc.width,height:n??u??uc.height,stroke:e??f,strokeWidth:g,className:hg("lucide",p,r),...!o&&!_v(c)&&{"aria-hidden":"true"},...c},[...l.map(([x,w])=>i.createElement(x,w)),...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 et=(e,n)=>{const s=i.forwardRef(({className:a,...r},o)=>i.createElement(Pv,{ref:o,iconNode:n,className:hg(`lucide-${Cv(Yu(e))}`,`lucide-${e}`,a),...r}));return s.displayName=Yu(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 Rv=[["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"}]],Ks=et("activity",Rv);/**
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 Iv=[["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"}]],Tv=et("archive-restore",Iv);/**
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 $v=[["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"}]],xo=et("archive",$v);/**
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 Dv=[["path",{d:"M12 5v14",key:"s699le"}],["path",{d:"m19 12-7 7-7-7",key:"1idqje"}]],vo=et("arrow-down",Dv);/**
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 Lv=[["path",{d:"m12 19-7-7 7-7",key:"1l729n"}],["path",{d:"M19 12H5",key:"x3x0zl"}]],Aa=et("arrow-left",Lv);/**
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 Ov=[["path",{d:"M5 12h14",key:"1ays0h"}],["path",{d:"m12 5 7 7-7 7",key:"xquz4c"}]],yo=et("arrow-right",Ov);/**
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 zv=[["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"}]],pg=et("arrow-up-down",zv);/**
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 Fv=[["path",{d:"m5 12 7-7 7 7",key:"hav0vg"}],["path",{d:"M12 19V5",key:"x0mq9r"}]],ka=et("arrow-up",Fv);/**
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 Uv=[["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"}]],Bv=et("book-open",Uv);/**
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 Hv=[["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"}]],$n=et("bot",Hv);/**
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 qv=[["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"}]],Sd=et("box",qv);/**
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 Vv=[["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"}]],oo=et("brain",Vv);/**
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 Wv=[["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"}]],fg=et("calendar",Wv);/**
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 Kv=[["path",{d:"M18 6 7 17l-5-5",key:"116fxf"}],["path",{d:"m22 10-7.5 7.5L13 16",key:"ke71qq"}]],Qu=et("check-check",Kv);/**
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 Gv=[["path",{d:"M20 6 9 17l-5-5",key:"1gmf2c"}]],hs=et("check",Gv);/**
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 Jv=[["path",{d:"m6 9 6 6 6-6",key:"qrunsl"}]],rn=et("chevron-down",Jv);/**
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 Yv=[["path",{d:"m15 18-6-6 6-6",key:"1wnfg3"}]],Vl=et("chevron-left",Yv);/**
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 Qv=[["path",{d:"m9 18 6-6-6-6",key:"mthhwq"}]],Mn=et("chevron-right",Qv);/**
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 Xv=[["path",{d:"m18 15-6-6-6 6",key:"153udz"}]],Ei=et("chevron-up",Xv);/**
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 Zv=[["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"}]],Ps=et("circle-alert",Zv);/**
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 ey=[["path",{d:"M21.801 10A10 10 0 1 1 17 3.335",key:"yps3ct"}],["path",{d:"m9 11 3 3L22 4",key:"1pflzl"}]],Dn=et("circle-check-big",ey);/**
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 ty=[["circle",{cx:"12",cy:"12",r:"10",key:"1mglay"}],["circle",{cx:"12",cy:"12",r:"1",key:"41hilf"}]],Wl=et("circle-dot",ty);/**
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 ny=[["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"}]],Cd=et("circle-question-mark",ny);/**
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 sy=[["circle",{cx:"12",cy:"12",r:"10",key:"1mglay"}],["rect",{x:"9",y:"9",width:"6",height:"6",rx:"1",key:"1ssd4o"}]],iy=et("circle-stop",sy);/**
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 ay=[["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"}]],wo=et("circle-x",ay);/**
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 ry=[["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"}]],oy=et("clipboard-list",ry);/**
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 ly=[["circle",{cx:"12",cy:"12",r:"10",key:"1mglay"}],["path",{d:"M12 6v6l4 2",key:"mmk7yg"}]],Hi=et("clock",ly);/**
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 cy=[["path",{d:"m16 18 6-6-6-6",key:"eg8j8"}],["path",{d:"m8 6-6 6 6 6",key:"ppft3o"}]],gg=et("code",cy);/**
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 dy=[["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"}]],Xu=et("columns-3",dy);/**
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 uy=[["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"}]],sa=et("copy",uy);/**
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 my=[["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"}]],bg=et("cpu",my);/**
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 hy=[["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"}]],py=et("download",hy);/**
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 fy=[["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"}]],gy=et("ellipsis-vertical",fy);/**
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 by=[["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"}]],Ed=et("ellipsis",by);/**
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 xy=[["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"}]],xg=et("external-link",xy);/**
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 vy=[["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"}]],mu=et("eye-off",vy);/**
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 yy=[["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"}]],kr=et("eye",yy);/**
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 wy=[["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"}]],hi=et("file-code",wy);/**
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 ky=[["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"}]],_d=et("file-diff",ky);/**
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 jy=[["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"}]],Ny=et("file-minus",jy);/**
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 Sy=[["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"}]],vg=et("file-pen",Sy);/**
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 Cy=[["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"}]],Ey=et("file-plus",Cy);/**
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 _y=[["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"}]],My=et("file-question-mark",_y);/**
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 Ay=[["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"}]],ia=et("file-text",Ay);/**
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 Py=[["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"}]],Ry=et("file-type",Py);/**
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 Iy=[["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"}]],yg=et("file",Iy);/**
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 Ty=[["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"}]],$y=et("flag",Ty);/**
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 Dy=[["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"}]],Md=et("folder-git-2",Dy);/**
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 Ly=[["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"}]],Zu=et("folder-root",Ly);/**
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 Oy=[["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"}]],bs=et("folder",Oy);/**
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 zy=[["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"}]],jl=et("funnel",zy);/**
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 Fy=[["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"}]],Us=et("git-branch",Fy);/**
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 Uy=[["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"}]],ko=et("git-commit-horizontal",Uy);/**
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 By=[["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"}]],wg=et("git-merge",By);/**
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 Hy=[["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"}]],Ws=et("git-pull-request",Hy);/**
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 qy=[["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"}]],Kl=et("globe",qy);/**
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 Vy=[["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"}]],Gl=et("grid-3x3",Vy);/**
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 Wy=[["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"}]],Jl=et("grip-vertical",Wy);/**
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 Ky=[["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"}]],Gy=et("hard-drive",Ky);/**
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 Jy=[["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"}]],Yy=et("heart",Jy);/**
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 Qy=[["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"}]],lo=et("history",Qy);/**
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 Xy=[["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"}]],ya=et("inbox",Xy);/**
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 Zy=[["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"}]],kg=et("key",Zy);/**
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 ew=[["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"}]],tw=et("keyboard",ew);/**
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 nw=[["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"}]],ja=et("layers",nw);/**
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 sw=[["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"}]],aa=et("layout-grid",sw);/**
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 iw=[["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"}]],_i=et("lightbulb",iw);/**
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 aw=[["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=et("link",aw);/**
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 rw=[["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"}]],ow=et("list-checks",rw);/**
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 lw=[["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"}]],cw=et("list-ordered",lw);/**
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 dw=[["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"}]],uw=et("list-plus",dw);/**
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 mw=[["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"}]],Yl=et("list-tree",mw);/**
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 hw=[["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"}]],Ad=et("list",hw);/**
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 pw=[["path",{d:"M21 12a9 9 0 1 1-6.219-8.56",key:"13zald"}]],bt=et("loader-circle",pw);/**
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 fw=[["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"}]],Ql=et("lock",fw);/**
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 gw=[["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"}]],Na=et("mail",gw);/**
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 bw=[["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"}]],xw=et("map",bw);/**
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 vw=[["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"}]],Xl=et("maximize-2",vw);/**
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 yw=[["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"}]],ww=et("message-square-plus",yw);/**
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 kw=[["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"}]],Ui=et("message-square",kw);/**
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 jw=[["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"}]],jo=et("minimize-2",jw);/**
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 Nw=[["path",{d:"M5 12h14",key:"1ays0h"}]],Sw=et("minus",Nw);/**
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 Cw=[["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"}]],dr=et("monitor",Cw);/**
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 Ew=[["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"}]],_w=et("move",Ew);/**
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 Mw=[["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"}]],Aw=et("network",Mw);/**
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 Pw=[["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"}]],Pd=et("package",Pw);/**
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 Rw=[["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"}]],jg=et("paperclip",Rw);/**
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 Iw=[["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"}]],pi=et("pause",Iw);/**
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 Tw=[["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"}]],Ds=et("pencil",Tw);/**
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 $w=[["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"}]],Yn=et("play",$w);/**
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 Dw=[["path",{d:"M5 12h14",key:"1ays0h"}],["path",{d:"M12 5v14",key:"s699le"}]],gn=et("plus",Dw);/**
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 Lw=[["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"}]],Ow=et("puzzle",Lw);/**
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 zw=[["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"}]],Ng=et("radio",zw);/**
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 Fw=[["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"}]],os=et("refresh-cw",Fw);/**
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 Uw=[["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"}]],em=et("rocket",Uw);/**
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 Bw=[["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"}]],Hw=et("rotate-ccw",Bw);/**
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 qw=[["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"}]],Vw=et("rotate-cw",qw);/**
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 Ww=[["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"}]],Sg=et("save",Ww);/**
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 Kw=[["path",{d:"m21 21-4.34-4.34",key:"14j7rj"}],["circle",{cx:"11",cy:"11",r:"8",key:"4ej97u"}]],Fi=et("search",Kw);/**
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 Gw=[["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"}]],wa=et("send",Gw);/**
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 Jw=[["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"}]],co=et("server",Jw);/**
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 Yw=[["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"}]],to=et("settings",Yw);/**
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 Qw=[["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"}]],Xw=et("shield-alert",Qw);/**
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 Zw=[["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"}]],ek=et("shield",Zw);/**
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 tk=[["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"}]],nk=et("skull",tk);/**
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 sk=[["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"}]],ps=et("sparkles",sk);/**
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 ik=[["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"}]],hu=et("square-check-big",ik);/**
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 ak=[["rect",{width:"18",height:"18",x:"3",y:"3",rx:"2",key:"afitv7"}]],Si=et("square",ak);/**
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 rk=[["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"}]],vs=et("target",rk);/**
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 ok=[["path",{d:"M12 19h8",key:"baeox8"}],["path",{d:"m4 17 6-6-6-6",key:"1yngyt"}]],Bi=et("terminal",ok);/**
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 lk=[["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"}]],Nl=et("text-wrap",lk);/**
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 ck=[["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"}]],vn=et("trash-2",ck);/**
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 dk=[["path",{d:"M16 7h6v6",key:"box55l"}],["path",{d:"m22 7-8.5 8.5-5-5L2 17",key:"1t1m79"}]],uk=et("trending-up",dk);/**
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 mk=[["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"}]],No=et("triangle-alert",mk);/**
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 hk=[["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"}]],tm=et("unlink",hk);/**
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 pk=[["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"}]],Ka=et("user",pk);/**
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 fk=[["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"}]],Cg=et("webhook",fk);/**
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 gk=[["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"}]],Sl=et("workflow",gk);/**
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 bk=[["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"}]],nm=et("wrench",bk);/**
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 xk=[["path",{d:"M18 6 6 18",key:"1bl5f8"}],["path",{d:"m6 6 12 12",key:"d8bk6v"}]],nn=et("x",xk);/**
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 vk=[["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"}]],Qn=et("zap",vk),Rd="fusion:version-reload",Id="fusion:version-update";let pu=!0;function mc(e){pu=e}function yk(){try{if(sessionStorage.getItem(Id))return sessionStorage.removeItem(Id),!0}catch{}return!1}function fu(e){if(sessionStorage.getItem(Rd)){console.warn("[versionCheck] reload already attempted, suppressing",e);return}if(sessionStorage.setItem(Rd,"1"),!pu){console.info("[versionCheck] auto-reload disabled by setting, skipping reload:",e);return}console.info("[versionCheck] reloading:",e),window.location.reload()}function wk(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 kk(e){return wk(e)?(fu(`chunk load error: ${e?.message??e}`),!0):!1}async function jk(){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 Nk(){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&&(pu=!1)}catch{}}const Sk=6e4;let sm=0,hc=!1;async function pc(){if(!(hc||document.visibilityState!=="visible")&&!(Date.now()-sm<Sk)){sm=Date.now(),hc=!0;try{const e=await jk();if(e&&e!=="e0d96712c-72a640a4"){try{sessionStorage.setItem(Id,"1")}catch{}fu(`build version changed: e0d96712c-72a640a4 -> ${e}`)}}finally{hc=!1}}}function Ck(){Nk(),window.setTimeout(()=>sessionStorage.removeItem(Rd),5e3),document.addEventListener("visibilitychange",()=>{pc()}),window.addEventListener("focus",()=>{pc()}),window.setTimeout(()=>void pc(),2e3)}class So 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),!kk(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(No,{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 _s({children:e,onError:n}){return t.jsx(So,{level:"page",onError:n,children:e})}function ga({children:e,onError:n}){return t.jsx(So,{level:"modal",onError:n,children:e})}function Ek({children:e,onError:n}){return t.jsx(So,{level:"root",onError:n,children:e})}const _k="modulepreload",Mk=function(e){return"/"+e},im={},xn=function(n,s,a){let r=Promise.resolve();if(s&&s.length>0){let l=function(u){return Promise.all(u.map(m=>Promise.resolve(m).then(h=>({status:"fulfilled",value:h}),h=>({status:"rejected",reason:h}))))};document.getElementsByTagName("link");const c=document.querySelector("meta[property=csp-nonce]"),d=c?.nonce||c?.getAttribute("nonce");r=l(s.map(u=>{if(u=Mk(u),u in im)return;im[u]=!0;const m=u.endsWith(".css"),h=m?'[rel="stylesheet"]':"";if(document.querySelector(`link[href="${u}"]${h}`))return;const f=document.createElement("link");if(f.rel=m?"stylesheet":_k,m||(f.as="script"),f.crossOrigin="",f.href=u,d&&f.setAttribute("nonce",d),document.head.appendChild(f),m)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)})},gu="fn.authToken",am="token",Ak="fn_token";let ir,rm=!1,Cl=!1;const Td="fn:auth-token-recovery-required";function Pk(){try{const e=window.localStorage.getItem(gu);return e&&e.length>0?e:void 0}catch{return}}function Eg(e){try{window.localStorage.setItem(gu,e)}catch{}}function Rk(){if(!(rm||typeof window>"u")){rm=!0;try{const e=new URL(window.location.href),n=e.searchParams.get(am);if(!n)return;Eg(n),e.searchParams.delete(am);const s=e.pathname+(e.search?e.search:"")+e.hash;return window.history.replaceState(window.history.state,"",s),n}catch{return}}}function ur(){if(ir!==void 0)return ir;const e=Rk();if(e)return ir=e,e;const n=Pk();if(n)return ir=n,n}function Ik(e){ir=e,Cl=!1,Eg(e)}function Tk(){ir=void 0,Cl=!1;try{window.localStorage.removeItem(gu)}catch{}}function om(e){return e==="ws:"?"http:":e==="wss:"?"https:":e}function $k(e){return e==="http:"||e==="https:"||e==="ws:"||e==="wss:"}function Dk(e){if(typeof window>"u")return!1;const n=new URL(window.location.origin);if(!$k(e.protocol))return!1;const s=e.hostname===n.hostname,a=e.port===n.port,r=om(e.protocol)===om(n.protocol);return s&&a&&r}function Lk(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 Mi(e){const n=ur();if(!n||typeof window>"u")return e;const s=Lk(e);return!s||!Dk(s.parsed)?e:(s.parsed.searchParams.set(Ak,n),s.preserveRelativePath?`${s.parsed.pathname}${s.parsed.search}${s.parsed.hash}`:s.parsed.toString())}function gi(e){const n=ur();if(!n)return e;const s=new Headers(e??{});return s.has("Authorization")||s.set("Authorization",`Bearer ${n}`),s}function Ok(e){if(!e||typeof e!="object")return!1;const n=e;return n.error==="Unauthorized"&&n.message==="Valid bearer token required"}function zk(){typeof window>"u"||Cl||(Cl=!0,window.dispatchEvent(new CustomEvent(Td)))}async function Fk(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();Ok(a)&&zk()}catch{}}function Uk(){if(typeof window>"u"||window.__fnAuthFetchInstalled)return;window.__fnAuthFetchInstalled=!0,ur();const e=window.fetch.bind(window);window.fetch=function(s,a){const r=ur(),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=>(Fk(d),d))}}class _g extends Error{status;details;constructor(n,s,a){super(n),this.name="ApiRequestError",this.status=s,this.details=a}}function Bk(e){const n=e.trim();return n.startsWith("<!DOCTYPE")||n.startsWith("<html")||n.startsWith("<HTML")}function ws(e){return`/api${e}`}async function T(e,n={}){const s=ws(e),a=ur(),r=(()=>{if(a){const f=new Headers(n.headers??{});return f.has("Content-Type")||f.set("Content-Type","application/json"),gi(f)}if(!n.headers)return{"Content-Type":"application/json"};const h=new Headers(n.headers);return h.has("Content-Type")||h.set("Content-Type","application/json"),Object.fromEntries(h.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")||Bk(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 h=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})${h?` Response: ${h}`:""}`)}let m;try{m=c?JSON.parse(c):null}catch{throw new Error(`API returned invalid JSON for ${s}. (${o.status} ${o.statusText})`)}if(!o.ok){const h=m;throw new _g(h?.error||`Request failed for ${s}: ${o.status} ${o.statusText}`,o.status,h?.details)}return m}function Qz(){return T("/health")}function Xz(){return T("/updates/check")}function Hk(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 T(`/tasks${l}`)}async function Sa(e,n){const a=ws(W(`/tasks/${e}`,n));for(let r=1;r<=2;r++){const o=await fetch(a,{headers:gi({"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 Mg(e,n,s){const{title:a,description:r,column:o,dependencies:l,breakIntoSubtasks:c,enabledWorkflowSteps:d,assignedAgentId:u,modelPresetId:m,modelProvider:h,modelId:f,validatorModelProvider:p,validatorModelId:g,planningModelProvider:x,planningModelId:w,thinkingLevel:b,summarize:y,reviewLevel:S,executionMode:k,priority:C,source:v,nodeId:j,branch:P,baseBranch:U}=e;return Mo(W("/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:m,modelProvider:h,modelId:f,validatorModelProvider:p,validatorModelId:g,planningModelProvider:x,planningModelId:w,thinkingLevel:b,summarize:y,reviewLevel:S,executionMode:k,priority:C,source:v,nodeId:j,branch:P,baseBranch:U})})}function mi(e,n,s){return T(W(`/tasks/${e}`,s),{method:"PATCH",body:JSON.stringify(n)})}function qk(e,n,s,a,r,o,l,c,d){return T(W("/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 Vk(e,n,s,a){return T(W(`/tasks/${e}/move`,s),{method:"POST",body:JSON.stringify({column:n,...typeof a=="object"&&a?.preserveProgress?{preserveProgress:!0}:{}})})}function Wk(e,n,s){const a=new URLSearchParams;s?.removeDependencyReferences&&a.set("removeDependencyReferences","true");const r=a.size>0?`?${a.toString()}`:"";return T(W(`/tasks/${e}${r}`,n),{method:"DELETE"})}function Kk(e,n){return T(W(`/tasks/${e}/merge`,n),{method:"POST"})}function Gk(e,n){return T(W(`/tasks/${e}/retry`,n),{method:"POST"})}function Jk(e,n){return T(W(`/tasks/${e}/reset`,n),{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify({confirm:!0})})}function Yk(e,n){return T(W(`/tasks/${e}/duplicate`,n),{method:"POST"})}function Ag(e,n){return T(W(`/tasks/${e}/pause`,n),{method:"POST"})}function Qk(e,n){return T(W(`/tasks/${e}/unpause`,n),{method:"POST"})}function Xk(e,n){return T(W(`/tasks/${e}/archive`,n),{method:"POST"})}function Zk(e,n){return T(W(`/tasks/${e}/unarchive`,n),{method:"POST"})}function ej(e){return T(W("/tasks/archive-all-done",e),{method:"POST"}).then(n=>n.archived)}function tj(e,n){return T(W(`/tasks/${e}/approve-plan`,n),{method:"POST"})}function nj(e,n){return T(W(`/tasks/${e}/reject-plan`,n),{method:"POST"})}function sj(e){return T(W("/config",e))}function Zl(e){return T(W("/settings",e))}function Do(e,n){return T(W("/settings",n),{method:"PUT",body:JSON.stringify(e)})}function ij(e){return T(W("/update-check",e))}function Zz(e){return T(W("/remote/settings",e))}function eF(e,n){return T(W("/remote/settings",n),{method:"PUT",body:JSON.stringify(e)})}function tF(e){return T(W("/remote/status",e))}function nF(e){return T(W("/remote/install-cloudflared",e),{method:"POST"})}function sF(e){return T(W("/remote/tunnel/start",e),{method:"POST"})}function iF(e){return T(W("/remote/tunnel/stop",e),{method:"POST"})}function aF(e){return T(W("/remote/tunnel/kill-external",e),{method:"POST"})}function rF(e){return T(W("/remote/token/persistent/regenerate",e),{method:"POST"})}function oF(e,n){return T(W("/remote/token/short-lived/generate",n),{method:"POST",body:JSON.stringify({ttlMs:e})})}function Pg(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 lF(e={}){const{projectId:n,tokenType:s="persistent",ttlMs:a}=e,r=Pg(null,s,a);return T(W(`/remote/url${r}`,n))}function cF(e="text",n={}){const{projectId:s,tokenType:a="persistent",ttlMs:r}=n,o=Pg(e,a,r);return T(W(`/remote/qr${o}`,s))}function dF(e){return T(W("/memory",e))}function uF(e,n){return T(W("/memory",n),{method:"PUT",body:JSON.stringify({content:e})})}function mF(e){return T(W("/memory/files",e))}function hF(e,n){const s=`path=${encodeURIComponent(e)}`;return T(W(`/memory/file?${s}`,n))}function pF(e,n,s){return T(W("/memory/file",s),{method:"PUT",body:JSON.stringify({path:e,content:n})})}function fF(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 T(W("/memory/compact",a),{method:"POST",body:JSON.stringify(s?{path:s}:{})})}function gF(e){return T(W("/memory/dream",e),{method:"POST"})}function bF(e){return T(W("/memory/insights",e))}function xF(e,n){return T(W("/memory/insights",n),{method:"PUT",body:JSON.stringify({content:e})})}function vF(e){return T(W("/memory/extract",e),{method:"POST"})}function yF(e){return T(W("/memory/audit",e))}function wF(e){return T(W("/memory/stats",e))}function kF(e){return T(W("/memory/backend",e))}function jF(e){return T(W("/memory/install-qmd",e),{method:"POST"})}function NF(e,n){return T(W("/memory/test",n),{method:"POST",body:JSON.stringify({query:e})})}function Pa(){return T("/settings/global")}function kn(e){return T("/settings/global",{method:"PUT",body:JSON.stringify(e)})}function SF(e){return T(W("/settings/scopes",e))}function CF(e){return T(W("/settings/pi-extensions",e))}function EF(e,n){return T(W("/settings/pi-extensions",n),{method:"PUT",body:JSON.stringify({disabledIds:e})})}function _F(e,n,s){return T(W("/settings/test-notification",s),{method:"POST",body:JSON.stringify({providerId:e,...n??{}})})}function MF(){return T("/pi-settings")}async function AF(e){return T("/pi-settings",{method:"PUT",body:JSON.stringify(e)})}async function PF(e){return T("/pi-settings/packages",{method:"POST",body:JSON.stringify({source:e})})}async function RF(e){return T(W("/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(ws(W(`/tasks/${e}/attachments`,s)),{method:"POST",headers:gi(),body:a}),o=await r.json();if(!r.ok)throw new Error(o.error||"Upload failed");return o}async function aj(e,n,s){return T(W(`/tasks/${e}/attachments/${n}`,s),{method:"DELETE"})}async function lm(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=W(`/tasks/${e}/logs${r}`,n),l=await fetch(ws(o),{headers:gi()});if(!l.ok){const m=await l.json().catch(()=>({error:"Failed to fetch agent logs"}));throw new Error(m.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 rj(e,n,s,a){return T(W(`/tasks/${e}/comments/${n}`,a),{method:"PATCH",body:JSON.stringify({text:s})})}function oj(e,n,s){return T(W(`/tasks/${e}/comments/${n}`,s),{method:"DELETE"})}function lj(e,n){return T(W(`/tasks/${e}/documents`,n))}function cj(e,n,s){return T(W(`/tasks/${e}/documents/${n}/revisions`,s))}async function IF(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 T(W(r,n))}function TF(e,n){const s=new URLSearchParams;n?.showHidden&&s.set("showHidden","1");const a=s.toString(),r=`/files/markdown-list${a?`?${a}`:""}`;return T(W(r,e))}function cm(e,n,s,a,r){return T(W(`/tasks/${e}/documents/${n}`,r),{method:"PUT",body:JSON.stringify({content:s,author:a?.author,metadata:a?.metadata})})}function dj(e,n,s){return T(W(`/tasks/${e}/documents/${n}`,s),{method:"DELETE"})}function uj(e,n,s){return T(W(`/tasks/${e}/steer`,s),{method:"POST",body:JSON.stringify({text:n})})}function mj(e,n,s){return T(W(`/tasks/${e}/spec/revise`,s),{method:"POST",body:JSON.stringify({feedback:n})})}function hj(e,n){return T(W(`/tasks/${e}/spec/rebuild`,n),{method:"POST"})}function pj(e,n,s){return T(W(`/tasks/${e}/refine`,s),{method:"POST",body:JSON.stringify({feedback:n})})}function Os(){return T("/models")}function fj(){return T("/usage")}function gj(){return T("/providers/claude-cli/status")}function bj(){return T("/system/fn-binary/status")}function xj(){return T("/system/fn-binary/install",{method:"POST"})}function vj(){return T("/providers/droid-cli/status")}function yj(){return T("/providers/cursor-cli/status")}function wj(){return T("/providers/llama-cpp/status")}async function $F(e){const n=e?.binaryPath?`?binaryPath=${encodeURIComponent(e.binaryPath)}`:"";return T(`/providers/hermes/status${n}`)}async function DF(e){const n=e?.binaryPath?`?binaryPath=${encodeURIComponent(e.binaryPath)}`:"";return(await T(`/providers/hermes/profiles${n}`)).profiles??[]}async function LF(e){const n=e?.binaryPath?`?binaryPath=${encodeURIComponent(e.binaryPath)}`:"";return T(`/providers/openclaw/status${n}`)}async function OF(e){const n=new URLSearchParams({apiUrl:e.apiUrl});return e.apiKey&&n.set("apiKey",e.apiKey),T(`/providers/paperclip/status?${n.toString()}`)}async function zF(e){const n=new URLSearchParams({apiUrl:e.apiUrl});return e.apiKey&&n.set("apiKey",e.apiKey),(await T(`/providers/paperclip/companies?${n.toString()}`)).companies??[]}async function FF(e){const n=new URLSearchParams({apiUrl:e.apiUrl,companyId:e.companyId});return e.apiKey&&n.set("apiKey",e.apiKey),(await T(`/providers/paperclip/agents?${n.toString()}`)).agents??[]}async function UF(e){return T("/providers/paperclip/cli-mint-key",{method:"POST",body:JSON.stringify(e)})}async function BF(e){const n=new URLSearchParams;e.cliBinaryPath&&n.set("cliBinaryPath",e.cliBinaryPath),e.cliConfigPath&&n.set("cliConfigPath",e.cliConfigPath);const s=n.toString();return T(`/providers/paperclip/cli-status${s?`?${s}`:""}`)}async function HF(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 T(`/providers/paperclip/cli-companies${s?`?${s}`:""}`)).companies??[]}async function qF(e){const n=new URLSearchParams({companyId:e.companyId});return e.cliBinaryPath&&n.set("cliBinaryPath",e.cliBinaryPath),e.cliConfigPath&&n.set("cliConfigPath",e.cliConfigPath),(await T(`/providers/paperclip/cli-agents?${n.toString()}`)).agents??[]}async function VF(e={}){const n=new URLSearchParams;e.cliConfigPath&&n.set("cliConfigPath",e.cliConfigPath);const s=n.toString();return T(`/providers/paperclip/cli-discovery${s?`?${s}`:""}`)}function kj(e){return T("/auth/claude-cli",{method:"POST",body:JSON.stringify({enabled:e})})}function jj(e){return T("/auth/droid-cli",{method:"POST",body:JSON.stringify({enabled:e})})}function Nj(e){return T("/auth/cursor-cli",{method:"POST",body:JSON.stringify({enabled:e})})}function Sj(e){return T("/auth/llama-cpp",{method:"POST",body:JSON.stringify({enabled:e})})}async function Cj(){const n=(await T("/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 Ej(e){return T("/custom-providers",{method:"POST",body:JSON.stringify(e)})}function WF(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 T(`/custom-providers/${encodeURIComponent(e)}`,{method:"PUT",body:JSON.stringify(a)})}function KF(e){return T(`/custom-providers/${encodeURIComponent(e)}`,{method:"DELETE"})}function _j(e){const n=e.api==="anthropic-messages"?"anthropic-compatible":"openai-compatible";return Ej({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 uo(){return T("/auth/status")}function Mj(e){return T("/auth/login",{method:"POST",body:JSON.stringify({provider:e,origin:window.location.origin})})}function Aj(e,n){return T("/auth/manual-code",{method:"POST",body:JSON.stringify({provider:e,code:n})})}function Pj(e){return T("/auth/logout",{method:"POST",body:JSON.stringify({provider:e})})}function Rj(e){return T("/auth/cancel",{method:"POST",body:JSON.stringify({provider:e})})}function Ij(e,n){return T("/auth/api-key",{method:"POST",body:JSON.stringify({provider:e,apiKey:n})})}function Tj(e){return T("/auth/api-key",{method:"DELETE",body:JSON.stringify({provider:e})})}function $j(e,n,s,a){return T("/github/issues/fetch",{method:"POST",body:JSON.stringify({owner:e,repo:n,limit:s,labels:a})})}function Dj(e,n,s,a){return T(W("/github/issues/import",a),{method:"POST",body:JSON.stringify({owner:e,repo:n,issueNumber:s})})}function Lj(e,n,s){return T("/github/pulls/fetch",{method:"POST",body:JSON.stringify({owner:e,repo:n,limit:s})})}function Oj(e,n,s,a){return T(W("/github/pulls/import",a),{method:"POST",body:JSON.stringify({owner:e,repo:n,prNumber:s})})}function zj(e){return T(W("/git/remotes",e))}function Fj(e){return T(W("/git/remotes/detailed",e))}function Uj(e,n,s){return T(W("/git/remotes",s),{method:"POST",body:JSON.stringify({name:e,url:n})})}function Bj(e,n){return T(W(`/git/remotes/${encodeURIComponent(e)}`,n),{method:"DELETE"})}function Hj(e,n,s){return T(W(`/git/remotes/${encodeURIComponent(e)}`,s),{method:"PATCH",body:JSON.stringify({newName:n})})}function qj(e,n,s){return T(W(`/git/remotes/${encodeURIComponent(e)}/url`,s),{method:"PUT",body:JSON.stringify({url:n})})}function Vj(e,n,s){return T(W(`/tasks/${e}/pr/create`,s),{method:"POST",body:JSON.stringify(n)})}function Wj(e,n){return T(W(`/tasks/${e}/pr/refresh`,n),{method:"POST"})}async function Kj(e,n){return(await T(W("/github/batch/status",n),{method:"POST",body:JSON.stringify({taskIds:e})})).results}function Lo(e,n,s,a){return T(W("/terminal/sessions",a),{method:"POST",body:JSON.stringify({cwd:e,cols:n,rows:s})})}function dm(e,n){return T(W(`/terminal/sessions/${encodeURIComponent(e)}`,n),{method:"DELETE"})}function Gj(e){return T(W("/terminal/sessions",e))}function di(e){return T(W("/git/status",e))}function Jj(e,n){const s=e?`?limit=${e}`:"";return T(W(`/git/commits${s}`,n))}function El(e,n){return T(W(`/git/commits/${e}/diff`,n))}function Yj(e){return T(W("/git/commits/ahead",e))}function Qj(e,n,s,a){const r=new URLSearchParams;r.set("limit",String(s));const o=r.size>0?`?${r.toString()}`:"";return T(W(`/git/remotes/${encodeURIComponent(e)}/commits${o}`,a))}function Ar(e){return T(W("/git/branches",e))}function Xj(e,n,s){const a=`?limit=${n}`;return T(W(`/git/branches/${encodeURIComponent(e)}/commits${a}`,s))}function Zj(e){return T(W("/git/worktrees",e))}function eN(e,n,s){return T(W("/git/branches",s),{method:"POST",body:JSON.stringify({name:e,base:n})})}function tN(e,n){return T(W(`/git/branches/${encodeURIComponent(e)}/checkout`,n),{method:"POST"})}function um(e,n,s){const a=n?"?force=true":"";return T(W(`/git/branches/${encodeURIComponent(e)}${a}`,s),{method:"DELETE"})}function nN(e,n){return T(W("/git/fetch",n),{method:"POST",body:JSON.stringify({remote:e})})}function sN(e,n){const s=typeof e=="string"?void 0:e;return T(W("/git/pull",typeof e=="string"?e:n),{method:"POST",body:JSON.stringify({rebase:s?.rebase??!1})})}function iN(e){return T(W("/git/push",e),{method:"POST"})}function Oo(e){return T(W("/git/stashes",e))}function aN(e,n){return T(W("/git/stashes",n),{method:"POST",body:JSON.stringify({message:e})})}function rN(e,n,s){return T(W(`/git/stashes/${e}/apply`,s),{method:"POST",body:JSON.stringify({drop:n})})}function oN(e,n){return T(W(`/git/stashes/${e}`,n),{method:"DELETE"})}function lN(e,n){return T(W(`/git/stashes/${e}/diff`,n))}function cN(e,n,s){const a=new URLSearchParams;return a.set("path",e),a.set("staged",String(n)),T(W(`/git/diff/file?${a.toString()}`,s))}function Ga(e){return T(W("/git/changes",e))}function mm(e,n){return T(W("/git/stage",n),{method:"POST",body:JSON.stringify({files:e})})}function dN(e,n){return T(W("/git/unstage",n),{method:"POST",body:JSON.stringify({files:e})})}function hm(e,n){return T(W("/git/commit",n),{method:"POST",body:JSON.stringify({message:e})})}function uN(e,n){return T(W("/git/discard",n),{method:"POST",body:JSON.stringify({files:e})})}function mN(e){return T(W("/workspaces",e))}function hN(e,n,s){const a=new URLSearchParams({workspace:e});return n&&a.set("path",n),s&&a.set("projectId",s),T(`/files?${a.toString()}`)}function pN(e,n,s){const a=new URLSearchParams({workspace:e});return s&&a.set("projectId",s),T(`/files/${encodeURIComponent(n)}?${a.toString()}`)}function fN(e,n,s,a){const r=new URLSearchParams({workspace:e});return a&&r.set("projectId",a),T(`/files/${encodeURIComponent(n)}?${r.toString()}`,{method:"POST",body:JSON.stringify({content:s})})}function gN(e,n,s){const a=new URLSearchParams({q:e});return n&&a.set("workspace",n),s&&a.set("projectId",s),T(`/files/search?${a.toString()}`)}function bN(e,n,s,a){const r=new URLSearchParams({workspace:e});return a&&r.set("projectId",a),T(`/files/${encodeURIComponent(n)}/copy?${r.toString()}`,{method:"POST",body:JSON.stringify({destination:s})})}function xN(e,n,s,a){const r=new URLSearchParams({workspace:e});return a&&r.set("projectId",a),T(`/files/${encodeURIComponent(n)}/move?${r.toString()}`,{method:"POST",body:JSON.stringify({destination:s})})}function vN(e,n,s){const a=new URLSearchParams({workspace:e});return s&&a.set("projectId",s),T(`/files/${encodeURIComponent(n)}/delete?${a.toString()}`,{method:"POST"})}function yN(e,n,s,a){const r=new URLSearchParams({workspace:e});return a&&r.set("projectId",a),T(`/files/${encodeURIComponent(n)}/rename?${r.toString()}`,{method:"POST",body:JSON.stringify({newName:s})})}function Rg(e,n,s){const a=new URLSearchParams({workspace:e});return s&&a.set("projectId",s),`/api/files/${encodeURIComponent(n)}/download?${a.toString()}`}function wN(e,n,s){const a=new URLSearchParams({workspace:e});return s&&a.set("projectId",s),`/api/files/${encodeURIComponent(n)}/download-zip?${a.toString()}`}function kN(e,n,s){return T(W("/planning/create-draft",n),{method:"POST",body:JSON.stringify({initialPlan:e,planningModelProvider:s?.planningModelProvider,planningModelId:s?.planningModelId})})}function jN(e,n,s,a,r){return T(W("/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 pm(e,n,s,a){return T(W("/planning/respond",s),{method:"POST",body:JSON.stringify({sessionId:e,responses:n,tabId:a})})}function NN(e,n,s){return T(W(`/planning/${encodeURIComponent(e)}/back`,n),{method:"POST",...s?{body:JSON.stringify({tabId:s})}:{}})}function SN(e,n,s){return T(W(`/planning/${encodeURIComponent(e)}/retry`,n),{method:"POST",...s?{body:JSON.stringify({tabId:s})}:{}})}function CN(e,n,s){return T(W(`/planning/${encodeURIComponent(e)}/stop`,n),{method:"POST",...s?{body:JSON.stringify({tabId:s})}:{}})}function Ig(e,n,s){return T(W("/planning/cancel",n),{method:"POST",body:JSON.stringify({sessionId:e,tabId:s})})}function GF(e,n,s,a){return T(W("/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 JF(e,n,s){return T(W("/agents/onboarding/respond",s),{method:"POST",body:JSON.stringify({sessionId:e,responses:n})})}function YF(e,n){return T(W("/agents/onboarding/cancel",n),{method:"POST",body:JSON.stringify({sessionId:e})})}function EN(e,n,s){return T(W("/planning/create-task",s),{method:"POST",body:JSON.stringify(n?{sessionId:e,summary:n}:{sessionId:e})})}function _N(e,n,s){return T(W("/planning/start-breakdown",s),{method:"POST",body:JSON.stringify(n?{sessionId:e,summary:n}:{sessionId:e})})}function MN(e,n,s){return T(W("/planning/create-tasks",s),{method:"POST",body:JSON.stringify({planningSessionId:e,subtasks:n})})}const $d=new Set;if(typeof window<"u"){const e=()=>{for(const n of Array.from($d))try{n.close()}catch{}};window.addEventListener("pagehide",e),window.addEventListener("beforeunload",e)}function AN(e,n){if(n===null||n<=0)return e;const s=e.includes("?")?"&":"?";return`${e}${s}lastEventId=${encodeURIComponent(String(n))}`}function jr(e,n,s={}){const a=s.maxReconnectAttempts??10;let r=null,o=!1,l=0,c=null,d=null,u=!1;const m=p=>{const g=p.lastEventId;if(!g)return!0;const x=Number.parseInt(g,10);return Number.isFinite(x)?d!==null&&x<=d?!1:(d=x,!0):!0},h=()=>{if(o)return;const p=AN(e,d),g=new EventSource(Mi(p));r=g,g.onopen=()=>{l=0,u=!1,s.onConnectionStateChange?.("connected"),n.onOpen?.()},g.onmessage=x=>{const w=x;m(w)&&n.onMessage?.(w)};for(const[x,w]of Object.entries(n.events??{}))g.addEventListener(x,b=>{const y=b;m(y)&&w(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 w=Math.min(1e3*2**(l-1),3e4);c=setTimeout(()=>{c=null,h()},w)}};h();const f={close:()=>{o=!0,c&&(clearTimeout(c),c=null),r?.close(),$d.delete(f)},isConnected:()=>!o&&r?.readyState===EventSource.OPEN};return $d.add(f),f}function fm(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 PN(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 RN(e){const s=(Array.isArray(e.lines)?e.lines:[]).map((a,r)=>PN(a,r+1));return{lines:s,totalLines:typeof e.totalLines=="number"&&Number.isFinite(e.totalLines)?e.totalLines:s.length}}function IN(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,m)=>({id:m+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 gm(e){return Array.isArray(e)?e.map(fm):(e.candidates??[]).map(fm)}async function TN(e){try{const n=await T(W("/dev-server/candidates",e));return gm(n)}catch(n){if(n instanceof Error&&/\/dev-server\/candidates/.test(n.message)){const s=await T(W("/dev-server/detect",e));return gm(s)}throw n}}function bu(e){return T(W("/dev-server/status",e)).then(mr)}async function QF(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 T(W(`/dev-server/logs/history${a}`,n));return RN(r)}catch(r){if(r instanceof Error&&/\/dev-server\/logs\/history/.test(r.message)){const o=await bu(n);return IN(o.logs,e)}throw r}}function $N(e,n){const s=e.cwd??e.packagePath??".",a=e.scriptName;return T(W("/dev-server/start",n),{method:"POST",body:JSON.stringify({command:e.command,scriptName:a,scriptId:a,cwd:s,packagePath:e.packagePath})}).then(mr)}function DN(e){return T(W("/dev-server/stop",e),{method:"POST"}).then(mr)}function LN(e){return T(W("/dev-server/restart",e),{method:"POST"}).then(mr)}async function ON(e,n){const s=typeof e=="string"?{url:e}:e;try{const a=await T(W("/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 T(W("/dev-server/preview-url",n),{method:"PUT",body:JSON.stringify(s)});return mr(r)}throw a}}function XF(e){return ws(W("/dev-server/logs/stream",e))}async function ZF(e){try{return(await T(W("/devserver",e))).sessions??[]}catch{try{const n=await bu(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 e3(e,n){try{return await T(W(`/devserver/${encodeURIComponent(e)}`,n))}catch{try{const s=await bu(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 t3(e,n){try{return await T(W(`/devserver/${encodeURIComponent(e)}/start`,n),{method:"POST"})}catch{const s=await $N({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 n3(e,n){try{return await T(W(`/devserver/${encodeURIComponent(e)}/stop`,n),{method:"POST"})}catch{const s=await DN(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 s3(e,n){try{return await T(W(`/devserver/${encodeURIComponent(e)}/restart`,n),{method:"POST"})}catch{const s=await LN(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 i3(e,n,s){try{const a=await T(W(`/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 ON({url:n},s);return{url:a.previewUrl??a.manualUrl??null,source:"manual"}}}async function a3(e){try{return(await T(W("/devserver/detect",e))).candidates??[]}catch{try{return(await TN(e)).map(s=>({name:s.name,command:s.command,cwd:s.cwd,scriptName:s.scriptName,packagePath:s.packagePath}))}catch{return[]}}}function r3(e,n){return ws(W(`/devserver/${encodeURIComponent(e)}/logs/stream`,n))}function Co(e,n,s=25e3){const a=setInterval(()=>{A1(e,n).catch(()=>{})},s);return{stop:()=>{clearInterval(a)}}}function zN(e,n){return ws(W(`/planning/${encodeURIComponent(e)}/stream`,n))}function FN(e,n){return ws(W(`/agents/onboarding/${encodeURIComponent(e)}/stream`,n))}function o3(e,n,s,a){const r=FN(e,n),o=jr(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 UN(e,n,s,a){const r=zN(e,n);let o=null,l=null;const c=()=>{o?.stop(),o=null},d=jr(r,{onOpen:()=>{c(),o=Co(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(m){console.error("[planning] Failed to parse question event:",m)}},summary:u=>{try{s.onSummary?.(JSON.parse(u.data))}catch(m){console.error("[planning] Failed to parse summary event:",m)}},error:u=>{try{const m=JSON.parse(u.data);s.onError?.(m.message||m)}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 Eo(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 BN(e){return T(Eo("/routines",e))}function HN(e,n){return T(Eo("/routines",n),{method:"POST",body:JSON.stringify(e)})}function bm(e,n,s){return T(Eo(`/routines/${e}`,s),{method:"PATCH",body:JSON.stringify(n)})}async function qN(e,n){await T(Eo(`/routines/${e}`,n),{method:"DELETE"})}function VN(e,n){return T(Eo(`/routines/${e}/trigger`,n),{method:"POST"})}function xm(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 T(`/activity${s}`)}function WN(e){const n=W("/activity",e);return T(n,{method:"DELETE"})}function _o(e){return T(W("/workflow-steps",e))}function vm(e,n){return T(W("/workflow-steps",n),{method:"POST",body:JSON.stringify(e)})}function KN(e,n,s){return T(W(`/workflow-steps/${e}`,s),{method:"PATCH",body:JSON.stringify(n)})}function GN(e,n){return T(W(`/workflow-steps/${e}`,n),{method:"DELETE"})}function ym(e,n){return T(W(`/workflow-steps/${e}/refine`,n),{method:"POST"})}function JN(e,n){return T(W(`/tasks/${encodeURIComponent(e)}/workflow-results`,n))}function YN(){return T("/workflow-step-templates")}function QN(){return T("/plugin-workflow-step-templates")}function XN(e,n){return T(W(`/workflow-step-templates/${encodeURIComponent(e)}/create`,n),{method:"POST"})}function mo(e){return T(W("/scripts",e))}function ZN(e,n,s){return T(W("/scripts",s),{method:"POST",body:JSON.stringify({name:e,command:n})})}function eS(e,n){return T(W(`/scripts/${encodeURIComponent(e)}`,n),{method:"DELETE"})}async function Tg(e,n,s){return(await T(W("/ai/refine-text",s),{method:"POST",body:JSON.stringify({text:e,type:n})})).refined}const zo={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 $g(e){if(!(e instanceof Error))return zo.NETWORK;const n=e.message.toLowerCase();return n.includes("rate limit")||n.includes("429")?zo.RATE_LIMIT:n.includes("invalid")&&n.includes("type")?zo.INVALID_TYPE:n.startsWith("text must")||n.includes("text is required")||n.includes("type is required")?e.message:zo.NETWORK}function tS(e,n){return T(W("/subtasks/start-streaming",n),{method:"POST",body:JSON.stringify({description:e})})}function nS(e,n,s){return T(W(`/subtasks/${encodeURIComponent(e)}/retry`,n),{method:"POST",...s?{body:JSON.stringify({tabId:s})}:{}})}function sS(e,n){return ws(W(`/subtasks/${encodeURIComponent(e)}/stream`,n))}function iS(e,n,s,a){let r=null,o=null;const l=()=>{r?.stop(),r=null},c=jr(sS(e,n),{onOpen:()=>{l(),r=Co(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),m=typeof u=="string"&&u.length>0?u:null;s.onError?.(m||"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 aS(e,n,s,a){return T(W("/subtasks/create-tasks",a),{method:"POST",body:JSON.stringify({sessionId:e,parentTaskId:s,subtasks:n.map(r=>({tempId:r.id,title:r.title,description:r.description,size:r.suggestedSize,dependsOn:r.dependsOn}))})})}function Dg(e,n,s){return T(W("/subtasks/cancel",n),{method:"POST",body:JSON.stringify({sessionId:e,tabId:s})})}function W(e,n){if(!n)return e;const s=e.includes("?")?"&":"?";return`${e}${s}projectId=${encodeURIComponent(n)}`}function rS(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 Mo(e,n){const{nodeId:s,localNodeId:a,...r}=n??{},o=rS(e,s,a);return T(o,r)}function Nr(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 T(`/agents${a}`)}function Dd(e,n){return T(W(`/agents/${encodeURIComponent(e)}`,n))}function oS(e,n){return T(W("/agents",n),{method:"POST",body:JSON.stringify(e)})}function lS(e,n,s){return T(W(`/agents/${encodeURIComponent(e)}`,s),{method:"PATCH",body:JSON.stringify(n)})}async function l3(e,n,s){const a=new FormData;a.append("file",n);const r=await fetch(ws(W(`/agents/${encodeURIComponent(e)}/avatar`,s)),{method:"POST",headers:gi(),body:a}),o=await r.json();if(!r.ok)throw new Error(o.error||"Avatar upload failed");return o}function c3(e,n){return T(W(`/agents/${encodeURIComponent(e)}/avatar`,n),{method:"DELETE"})}function d3(e,n){return T(W(`/agents/${encodeURIComponent(e)}/upgrade-heartbeat-procedure`,n),{method:"POST"})}function u3(e,n,s){return T(W(`/agents/${encodeURIComponent(e)}/instructions`,s),{method:"PATCH",body:JSON.stringify(n)})}function m3(e,n,s){return T(W(`/agents/${encodeURIComponent(e)}/soul`,s),{method:"PATCH",body:JSON.stringify({soul:n})})}function h3(e,n,s){return T(W(`/agents/${encodeURIComponent(e)}/memory`,s),{method:"PATCH",body:JSON.stringify({memory:n})})}function p3(e,n){return T(W(`/agents/${encodeURIComponent(e)}/memory/files`,n))}function f3(e,n,s){const a=`path=${encodeURIComponent(n)}`;return T(W(`/agents/${encodeURIComponent(e)}/memory/file?${a}`,s))}function g3(e,n,s,a){return T(W(`/agents/${encodeURIComponent(e)}/memory/file`,a),{method:"PUT",body:JSON.stringify({path:n,content:s})})}function cS(e,n,s){return T(W(`/agents/${encodeURIComponent(e)}/state`,s),{method:"POST",body:JSON.stringify({state:n})})}function dS(e,n){return T(W(`/agents/${encodeURIComponent(e)}`,n),{method:"DELETE"})}function b3(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 T(`/agents/${encodeURIComponent(e)}/runs${r}`)}function x3(e,n,s){return T(W(`/agents/${encodeURIComponent(e)}/runs/${encodeURIComponent(n)}`,s))}function v3(e,n,s){return T(W(`/agents/${encodeURIComponent(e)}/runs/${encodeURIComponent(n)}/logs`,s))}function y3(e,n,s){const a=s?.source??"manual",r=s?.triggerDetail??"Agent activated via dashboard";return T(W(`/agents/${encodeURIComponent(e)}/runs`,n),{method:"POST",body:JSON.stringify({source:a,triggerDetail:r})})}function w3(e,n){return T(W(`/agents/${encodeURIComponent(e)}/runs/stop`,n),{method:"POST"})}function uS(e){return T(W("/agents/stats",e))}function k3(e,n){return T(W(`/agents/${encodeURIComponent(e)}/chain-of-command`,n))}function j3(e,n){const s=new URLSearchParams;e&&s.set("projectId",e),n?.includeEphemeral&&s.set("includeEphemeral","true");const a=s.toString();return T(`/agents/org-tree${a?`?${a}`:""}`)}function N3(e,n){return T(W(`/agents/${encodeURIComponent(e)}/children`,n)).catch(s=>{if(s.message.includes("not found"))return[];throw s})}function wm(e,n,s){return T(W(`/tasks/${encodeURIComponent(e)}/assign`,s),{method:"PATCH",body:JSON.stringify({agentId:n})})}function Lg(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 mS(e,n){const s=await T(W(`/tasks/${encodeURIComponent(e)}/review`,n));return Lg(s)}async function hS(e,n){const s=await T(W(`/tasks/${encodeURIComponent(e)}/review/refresh`,n),{method:"POST"});return Lg(s)}function pS(e,n,s){return T(W(`/tasks/${encodeURIComponent(e)}/review/address`,s),{method:"POST",body:JSON.stringify({selectedItems:n,tab:"review"})})}function S3(e,n){return T(W(`/agents/${encodeURIComponent(e)}/tasks`,n))}function C3(){return T("/agents/companies")}function E3(e,n){return T(W("/agents/generate/start",n),{method:"POST",body:JSON.stringify({role:e})})}function _3(e,n){return T(W("/agents/generate/spec",n),{method:"POST",body:JSON.stringify({sessionId:e})})}function M3(e,n){return T(W(`/agents/generate/${encodeURIComponent(e)}`,n),{method:"DELETE"})}function A3(e){return T(W("/backups",e))}function P3(e){return T(W("/backups",e),{method:"POST"})}function R3(e,n){const s=W("/settings/export",n),a=`${s}${s.includes("?")?"&":"?"}scope=${encodeURIComponent(e)}`;return T(a)}function I3(e,n,s){return T(W("/settings/import",s),{method:"POST",body:JSON.stringify({data:e,scope:n?.scope??"both",merge:n?.merge??!0})})}function fS(e){return Array.isArray(e.nodeMappings)||Array.isArray(e.projectNodeMappings)||Array.isArray(e.pathMappings)}function km(){return T("/projects/across-nodes")}function _l(){return T("/nodes")}function T3(){return T("/docker/nodes")}function $3(e){return T(`/docker/nodes/${encodeURIComponent(e)}/container-status`)}function D3(e,n){const s=new URLSearchParams;typeof n?.tail=="number"&&s.set("tail",String(n.tail));const a=s.size>0?`?${s.toString()}`:"";return T(`/docker/nodes/${encodeURIComponent(e)}/logs${a}`)}function L3(e){return T("/docker-nodes",{method:"POST",body:JSON.stringify(e)})}function gS(e){return T("/nodes",{method:"POST",body:JSON.stringify(e)})}function bS(e){return T("/nodes/discover-projects",{method:"POST",body:JSON.stringify(e)})}function xS(e,n){return T(`/nodes/${encodeURIComponent(e)}`,{method:"PATCH",body:JSON.stringify(n)})}function vS(e){return T(`/nodes/${encodeURIComponent(e)}/docker-config`)}function yS(e,n){return T(`/nodes/${encodeURIComponent(e)}/docker-config`,{method:"PATCH",body:JSON.stringify(n)})}function wS(e){return T(`/nodes/${encodeURIComponent(e)}/docker-config/diff`)}function jm(e){return T(`/nodes/${encodeURIComponent(e)}`,{method:"DELETE"})}async function kS(e){const n=await T(`/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()}}function O3(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=ur();l&&o.set("fn_token",l);const c=o.toString(),d=`/browse-directory${c?`?${c}`:""}`;return T(d)}function jS(e){return T("/projects",{method:"POST",body:JSON.stringify(e)})}function Og(e){return T(`/projects/${encodeURIComponent(e)}`,{method:"DELETE"})}function NS(e,n,s){return T(`/projects/${encodeURIComponent(e)}/path-mappings/${encodeURIComponent(n)}`,{method:"PUT",body:JSON.stringify({path:s})})}function Nm(e){return T(`/projects/${encodeURIComponent(e)}/health`)}function SS(e){return T(W("/executor/stats",e))}function CS(e){return T(W("/system-stats",e))}function ES(e){return T(W("/kill-vitest",e),{method:"POST"})}function Sm(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 T(`/activity-feed${s}`)}function _S(e){return T(`/projects/${encodeURIComponent(e)}/pause`,{method:"POST"})}function MS(e){return T(`/projects/${encodeURIComponent(e)}/resume`,{method:"POST"})}function z3(){return T("/global-concurrency")}function F3(e){return T("/global-concurrency",{method:"PUT",body:JSON.stringify(e)})}function AS(e,n){return T(`/projects/${encodeURIComponent(e)}`,{method:"PATCH",body:JSON.stringify(n)})}function zg(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 T(`/tasks/${encodeURIComponent(e)}/diff${r}`)}function PS(e){return T(W("/missions",e))}function RS(e,n){return T(W("/missions",n),{method:"POST",body:JSON.stringify(e)})}function Fg(e,n){return T(W(`/missions/${encodeURIComponent(e)}`,n))}function IS(e,n,s){return T(W(`/missions/${encodeURIComponent(e)}`,s),{method:"PATCH",body:JSON.stringify(n)})}function TS(e,n){return T(W(`/missions/${encodeURIComponent(e)}`,n),{method:"DELETE"})}function $S(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 T(W(`/missions/${encodeURIComponent(e)}/events${r}`,s))}function DS(e){return T(W("/missions/health",e))}function LS(e,n,s){return T(W(`/missions/${encodeURIComponent(e)}/milestones`,s),{method:"POST",body:JSON.stringify(n)})}function OS(e,n,s){return T(W(`/missions/milestones/${encodeURIComponent(e)}`,s),{method:"PATCH",body:JSON.stringify(n)})}function zS(e,n){return T(W(`/missions/milestones/${encodeURIComponent(e)}`,n),{method:"DELETE"})}function FS(e,n,s){return T(W(`/missions/milestones/${encodeURIComponent(e)}/slices`,s),{method:"POST",body:JSON.stringify(n)})}function US(e,n,s){return T(W(`/missions/slices/${encodeURIComponent(e)}`,s),{method:"PATCH",body:JSON.stringify(n)})}function BS(e,n){return T(W(`/missions/slices/${encodeURIComponent(e)}`,n),{method:"DELETE"})}function HS(e,n){return T(W(`/missions/slices/${encodeURIComponent(e)}/activate`,n),{method:"POST"})}function qS(e,n,s){return T(W(`/missions/slices/${encodeURIComponent(e)}/features`,s),{method:"POST",body:JSON.stringify(n)})}function VS(e,n,s){return T(W(`/missions/features/${encodeURIComponent(e)}`,s),{method:"PATCH",body:JSON.stringify(n)})}function WS(e,n){return T(W(`/missions/features/${encodeURIComponent(e)}`,n),{method:"DELETE"})}function KS(e,n,s){return T(W(`/missions/features/${encodeURIComponent(e)}/link-task`,s),{method:"POST",body:JSON.stringify({taskId:n})})}function GS(e,n){return T(W(`/missions/features/${encodeURIComponent(e)}/unlink-task`,n),{method:"POST"})}function JS(e,n,s,a){return T(W(`/missions/features/${encodeURIComponent(e)}/triage`,a),{method:"POST",body:JSON.stringify({taskTitle:n,taskDescription:s})})}function YS(e,n){return T(W(`/missions/slices/${encodeURIComponent(e)}/triage-all`,n),{method:"POST"})}function fc(e,n){return T(W(`/missions/milestones/${encodeURIComponent(e)}/assertions`,n))}function QS(e,n,s){return T(W(`/missions/milestones/${encodeURIComponent(e)}/assertions`,s),{method:"POST",body:JSON.stringify(n)})}function XS(e,n,s){return T(W(`/missions/assertions/${encodeURIComponent(e)}`,s),{method:"PATCH",body:JSON.stringify(n)})}function ZS(e,n,s){return T(W(`/missions/features/${encodeURIComponent(e)}/assertions/${encodeURIComponent(n)}/link`,s),{method:"POST"})}function e1(e,n,s){return T(W(`/missions/features/${encodeURIComponent(e)}/assertions/${encodeURIComponent(n)}/unlink`,s),{method:"POST"})}function t1(e,n){return T(W(`/missions/assertions/${encodeURIComponent(e)}/features`,n))}function gc(e,n){return T(W(`/missions/milestones/${encodeURIComponent(e)}/validation`,n))}function Cm(e,n){return T(W(`/missions/milestones/${encodeURIComponent(e)}/validation-telemetry`,n))}function n1(e,n){return T(W(`/missions/features/${encodeURIComponent(e)}/validate`,n),{method:"POST"})}function Em(e,n){return T(W(`/missions/features/${encodeURIComponent(e)}/validation-loop`,n))}function s1(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 T(W(`/missions/features/${encodeURIComponent(e)}/validation-runs${r}`,s)).then(o=>o.runs)}function i1(e,n){return T(W(`/missions/validation-runs/${encodeURIComponent(e)}`,n))}function a1(e,n){return T(W(`/missions/${encodeURIComponent(e)}/resume`,n),{method:"POST"})}function r1(e,n){return T(W(`/missions/${encodeURIComponent(e)}/stop`,n),{method:"POST"})}function o1(e,n){return T(W(`/missions/${encodeURIComponent(e)}/start`,n),{method:"POST"})}function l1(e,n,s){return T(W(`/missions/${encodeURIComponent(e)}/autopilot`,s),{method:"PATCH",body:JSON.stringify(n)})}function c1(e,n,s){return T(W("/missions/interview/start",n),{method:"POST",body:JSON.stringify({missionTitle:e,modelProvider:s?.modelProvider,modelId:s?.modelId})})}function d1(e,n,s,a){return T(W("/missions/interview/respond",s),{method:"POST",body:JSON.stringify({sessionId:e,responses:n,tabId:a})})}function u1(e,n,s){return T(W(`/missions/interview/${encodeURIComponent(e)}/retry`,n),{method:"POST",...s?{body:JSON.stringify({tabId:s})}:{}})}function Ug(e,n,s){return T(W("/missions/interview/cancel",n),{method:"POST",body:JSON.stringify({sessionId:e,tabId:s})})}function m1(e,n,s){return T(W("/missions/interview/create-mission",s),{method:"POST",body:JSON.stringify({sessionId:e,summary:n})})}function h1(e,n,s,a){const r=ws(W(`/missions/interview/${encodeURIComponent(e)}/stream`,n));let o=null,l=null;const c=()=>{o?.stop(),o=null},d=jr(r,{onOpen:()=>{c(),o=Co(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(m){console.error("[mission-interview] Failed to parse question event:",m)}},summary:u=>{try{s.onSummary?.(JSON.parse(u.data))}catch(m){console.error("[mission-interview] Failed to parse summary event:",m)}},error:u=>{try{const m=JSON.parse(u.data);s.onError?.(m.message||m)}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 Ao(e,n,s){return W(`/missions/milestones/${encodeURIComponent(e)}/interview${n}`,s)}function Po(e,n,s){return W(`/missions/slices/${encodeURIComponent(e)}/interview${n}`,s)}function p1(e,n){return T(Ao(e,"/start",n),{method:"POST"})}function f1(e,n,s,a){return T(Ao(e,"/respond",s),{method:"POST",body:JSON.stringify({sessionId:e,responses:n,tabId:a})})}function g1(e,n,s,a){const r=ws(Ao(e,`/${encodeURIComponent(e)}/stream`,n));let o=null,l=null;const c=()=>{o?.stop(),o=null},d=jr(r,{onOpen:()=>{c(),o=Co(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(m){console.error("[milestone-interview] Failed to parse question event:",m)}},summary:u=>{try{s.onSummary?.(JSON.parse(u.data))}catch(m){console.error("[milestone-interview] Failed to parse summary event:",m)}},error:u=>{try{const m=JSON.parse(u.data);s.onError?.(m.message||m)}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 b1(e,n,s){return T(Ao(e,"/apply",s),{method:"POST",body:JSON.stringify({sessionId:e,summary:n})})}function x1(e,n){return T(Ao(e,"/skip",n),{method:"POST"})}function v1(e,n){return T(Po(e,"/start",n),{method:"POST"})}function y1(e,n,s,a){return T(Po(e,"/respond",s),{method:"POST",body:JSON.stringify({sessionId:e,responses:n,tabId:a})})}function w1(e,n,s,a){const r=ws(Po(e,`/${encodeURIComponent(e)}/stream`,n));let o=null,l=null;const c=()=>{o?.stop(),o=null},d=jr(r,{onOpen:()=>{c(),o=Co(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(m){console.error("[slice-interview] Failed to parse question event:",m)}},summary:u=>{try{s.onSummary?.(JSON.parse(u.data))}catch(m){console.error("[slice-interview] Failed to parse summary event:",m)}},error:u=>{try{const m=JSON.parse(u.data);s.onError?.(m.message||m)}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 k1(e,n,s){return T(Po(e,"/apply",s),{method:"POST",body:JSON.stringify({sessionId:e,summary:n})})}function j1(e,n){return T(Po(e,"/skip",n),{method:"POST"})}async function N1(e,n){try{return await T(W(`/missions/features/${encodeURIComponent(e)}/preview-description`,n),{method:"POST"})}catch{throw new Error("Preview endpoint not available")}}function U3(e){return T(W("/todos",e))}function B3(e,n){const s={title:e};return T(W("/todos",n),{method:"POST",body:JSON.stringify(s)})}function H3(e,n,s){const a={title:n};return T(W(`/todos/${encodeURIComponent(e)}`,s),{method:"PATCH",body:JSON.stringify(a)})}function q3(e,n){return T(W(`/todos/${encodeURIComponent(e)}`,n),{method:"DELETE"})}function V3(e,n,s){const a={text:n};return T(W(`/todos/${encodeURIComponent(e)}/items`,s),{method:"POST",body:JSON.stringify(a)})}function W3(e,n,s){const a=n;return T(W(`/todos/items/${encodeURIComponent(e)}`,s),{method:"PATCH",body:JSON.stringify(a)})}function K3(e,n){return T(W(`/todos/items/${encodeURIComponent(e)}`,n),{method:"DELETE"})}function G3(e,n,s){return T(W(`/todos/${encodeURIComponent(e)}/items/reorder`,s),{method:"POST",body:JSON.stringify({itemIds:n})})}function hr(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(ws(`/ai-sessions${a?`?${a}`:""}`),{headers:gi()});return r.ok?(await r.json()).sessions??[]:[]}async function S1(e){return T(`/ai-sessions/${encodeURIComponent(e)}/archive`,{method:"POST"})}async function C1(e){return T(`/ai-sessions/${encodeURIComponent(e)}/unarchive`,{method:"POST"})}async function Ci(e){const n=await fetch(ws(`/ai-sessions/${encodeURIComponent(e)}`),{headers:gi()});return n.ok?n.json():null}async function E1(e,n){const s=await T(`/ai-sessions/${encodeURIComponent(e)}/lock`,{method:"POST",body:JSON.stringify({tabId:n})});return{acquired:s.acquired,currentHolder:s.currentHolder??null}}function _1(e,n){return T(`/ai-sessions/${encodeURIComponent(e)}/lock`,{method:"DELETE",body:JSON.stringify({tabId:n})})}function M1(e,n){return T(`/ai-sessions/${encodeURIComponent(e)}/lock/force`,{method:"POST",body:JSON.stringify({tabId:n})})}async function Bg(e){await fetch(ws(`/ai-sessions/${encodeURIComponent(e)}`),{method:"DELETE",headers:gi()})}function A1(e,n){return T(W(`/ai-sessions/${encodeURIComponent(e)}/ping`,n),{method:"POST"})}function P1(e,n,s){return T(W(`/ai-sessions/${encodeURIComponent(e)}/draft`,s),{method:"PATCH",body:JSON.stringify(n)})}function R1(e,n){return T(W(`/planning/${encodeURIComponent(e)}/summarize-draft-title`,n),{method:"POST"})}function I1(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 T(`/messages/inbox${a}`)}function T1(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 T(`/messages/outbox${a}`)}function Hg(e){return T(W("/messages/unread-count",e))}function $1(e,n){return T(W("/messages",n),{method:"POST",body:JSON.stringify(e)})}function D1(e,n){return T(W(`/messages/${encodeURIComponent(e)}/read`,n),{method:"POST"})}function L1(e){return T(W("/messages/read-all",e),{method:"POST"})}function O1(e,n){return T(W(`/messages/${encodeURIComponent(e)}`,n),{method:"DELETE"})}function z1(e,n,s){const a=`/messages/conversation/${encodeURIComponent(n)}/${encodeURIComponent(e)}`;return T(W(a,s))}function F1(e,n){return T(W(`/agents/${encodeURIComponent(e)}/mailbox`,n))}function Fo(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 T(`/approvals${a}`)}function _m(e,n){return T(W(`/approvals/${encodeURIComponent(e)}`,n))}function U1(e,n,s){return T(W(`/approvals/${encodeURIComponent(e)}/decision`,s),{method:"POST",body:JSON.stringify(n)})}function J3(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 T(`/agents/${encodeURIComponent(e)}/reflections${r}`)}function Y3(e,n){return T(W(`/agents/${encodeURIComponent(e)}/reflections`,n),{method:"POST"})}function Q3(e,n,s){const a=new URLSearchParams;s&&a.set("projectId",s);const r=a.size>0?`?${a.toString()}`:"";return T(`/agents/${encodeURIComponent(e)}/performance${r}`)}function X3(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 T(`/agents/${encodeURIComponent(e)}/ratings${r}`)}function Z3(e,n,s){return T(W(`/agents/${encodeURIComponent(e)}/ratings`,s),{method:"POST",body:JSON.stringify(n)})}function e6(e,n){return T(W(`/agents/${encodeURIComponent(e)}/ratings/summary`,n))}function t6(e,n,s){return T(W(`/agents/${encodeURIComponent(e)}/ratings/${encodeURIComponent(n)}`,s),{method:"DELETE"})}function n6(e,n){return T(W(`/agents/${encodeURIComponent(e)}/budget`,n))}function s6(e,n){return T(W(`/agents/${encodeURIComponent(e)}/budget/reset`,n),{method:"POST"})}async function i6(e){return T(W("/plugins",e))}async function a6(e,n){return T(W("/plugins",n),{method:"POST",body:JSON.stringify({mode:"install",...e})})}async function r6(e,n){return T(W(`/plugins/${encodeURIComponent(e)}/enable`,n),{method:"POST"})}async function o6(e,n){return T(W(`/plugins/${encodeURIComponent(e)}/disable`,n),{method:"POST"})}async function l6(e,n){return T(W(`/plugins/${encodeURIComponent(e)}`,n),{method:"DELETE"})}async function c6(e,n){return T(W(`/plugins/${encodeURIComponent(e)}/settings`,n))}async function d6(e,n,s){return T(W(`/plugins/${encodeURIComponent(e)}/settings`,s),{method:"PUT",body:JSON.stringify({settings:n})})}async function u6(e,n){return T(W(`/plugins/${encodeURIComponent(e)}/setup-status`,n))}async function m6(e,n){return T(W(`/plugins/${encodeURIComponent(e)}/setup/install`,n),{method:"POST"})}async function h6(e,n){return T(W(`/plugins/${encodeURIComponent(e)}/reload`,n),{method:"POST"})}async function p6(e,n,s){return T(W(`/plugins/${encodeURIComponent(e)}`,s),{method:"PATCH",body:JSON.stringify(n)})}async function f6(e,n){return T(W(`/plugins/${encodeURIComponent(e)}/rescan`,n),{method:"POST"})}async function B1(e){return T(W("/plugins/ui-slots",e))}async function H1(e){return T(W("/plugins/dashboard-views",e))}async function g6(e){return T(W("/plugins/runtimes",e))}async function q1(e){return(await T(W("/skills/discovered",e))).skills}async function b6(e,n,s){return T(W("/skills/execution",s),{method:"PATCH",body:JSON.stringify({skillId:e,enabled:n})})}async function x6(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 T(W(`/skills/catalog${r}`,s))}async function v6(e,n){return(await T(W(`/skills/${encodeURIComponent(e)}/content`,n))).content}function Mm(e,n){const s=new URLSearchParams;e&&s.set("projectId",e);const a=s.toString();return T(`/chat/sessions${a?`?${a}`:""}`)}async function V1(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 T(`/chat/sessions?${o.toString()}`)).sessions[0]??null}}function W1(e,n){return T(W("/chat/sessions",n),{method:"POST",body:JSON.stringify(e)})}function K1(e,n){return T(W(`/chat/sessions/${encodeURIComponent(e)}`,n))}function y6(e,n,s){return T(W(`/chat/sessions/${encodeURIComponent(e)}`,s),{method:"PATCH",body:JSON.stringify(n)})}function w6(e,n){return T(W(`/chat/sessions/${encodeURIComponent(e)}`,n),{method:"DELETE"})}function Pr(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 T(W(`/chat/sessions/${encodeURIComponent(e)}/messages${r?`?${r}`:""}`,s))}function k6(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 T(`/chat/rooms${a?`?${a}`:""}`)}function j6(e,n){const s={...e,...n?{projectId:n}:{}};return T(W("/chat/rooms",n),{method:"POST",body:JSON.stringify(s)})}function N6(e,n){return T(W(`/chat/rooms/${encodeURIComponent(e)}`,n),{method:"DELETE"})}function S6(e,n){return T(W(`/chat/rooms/${encodeURIComponent(e)}/members`,n))}function C6(e,n,s){const a=new URLSearchParams;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 T(W(`/chat/rooms/${encodeURIComponent(e)}/messages${r?`?${r}`:""}`,s))}function E6(e,n,s){return T(W(`/chat/rooms/${encodeURIComponent(e)}/messages`,s),{method:"POST",body:JSON.stringify(n)})}function G1(e,n){return T(W(`/chat/sessions/${encodeURIComponent(e)}/cancel`,n),{method:"POST"})}function J1(e,n,s,a,r,o){const l=ws(W(`/chat/sessions/${encodeURIComponent(e)}/messages`,r)),c=new AbortController;let d=!1,u=!1,m=!1;const h=Math.max(1e3,6e4);let f=null;const p=()=>{f&&(clearTimeout(f),f=null)},g=()=>{m||(m=!0,p())},x=(w,b)=>{if(w)switch(g(),w){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;try{const y=JSON.parse(b);s.onError?.(y.message||y)}catch{s.onError?.(b||"Stream error")}break}};return(async()=>{try{const w=Array.isArray(a)&&a.length>0,b=w?(()=>{const E=new FormData;return E.append("content",n),a.forEach(R=>E.append("attachments",R)),E})():JSON.stringify({content:n}),y=await fetch(l,{method:"POST",headers:w?gi():gi({"Content-Type":"application/json"}),body:b,signal:c.signal});if(!y.ok){const E=await y.text();let R=`Request failed: ${y.status}`;try{R=JSON.parse(E).error||R}catch{}s.onError?.(R);return}if(!y.body){s.onError?.("No response body");return}s.onConnectionStateChange?.("connected"),f=setTimeout(()=>{u||d||m||(u=!0,s.onError?.("Timed out waiting for first response event"),c.abort())},h);const S=y.body.getReader(),k=new TextDecoder;let C="",v="",j=[];const P=(E,R=!1)=>{C+=E;const L=C.split(`
643
- `);C=L.pop()||"",R&&C.length>0&&(L.push(C),C="");for(const F of L){const M=F.endsWith("\r")?F.slice(0,-1):F;if(M.startsWith("event:"))v=M.slice(6).trim();else if(M.startsWith("data:")){const O=M.slice(5);j.push(O.startsWith(" ")?O.slice(1):O)}else if(M===""){const O=j.join(`
644
- `);x(v,O),v="",j=[]}}if(R&&v&&j.length>0){const F=j.join(`
645
- `);x(v,F),v="",j=[]}};for(;;){const{done:E,value:R}=await S.read();if(E){P(k.decode(),!0);break}P(k.decode(R,{stream:!0}))}const U=C.length>0||v.length>0||j.length>0;!u&&!d&&!U&&s.onError?.("Connection closed unexpectedly"),p()}catch(w){if(w instanceof DOMException&&w.name==="AbortError"){!d&&!u&&s.onError?.("Connection aborted"),p();return}if(d){p();return}p(),s.onError?.(w instanceof Error?w.message:"Connection error")}})(),{close:()=>{d=!0,p(),c.abort()},isConnected:()=>!d}}function Y1(e,n,s,a){const r=ws(W(`/chat/sessions/${encodeURIComponent(e)}/stream`,s)),o=new AbortController;let l=!1,c=!1;const d=(u,m)=>{if(u)switch(u){case"thinking":try{n.onThinking?.(JSON.parse(m))}catch{n.onThinking?.(m)}break;case"text":try{n.onText?.(JSON.parse(m))}catch{n.onText?.(m)}break;case"tool_start":try{n.onToolStart?.(JSON.parse(m))}catch{}break;case"tool_end":try{n.onToolEnd?.(JSON.parse(m))}catch{}break;case"fallback":try{n.onFallback?.(JSON.parse(m))}catch{}break;case"done":c=!0;try{const h=JSON.parse(m);n.onDone?.({messageId:typeof h.messageId=="string"?h.messageId:"",...h.message&&typeof h.message=="object"?{message:h.message}:{}})}catch{n.onDone?.({messageId:""})}break;case"error":c=!0;try{const h=JSON.parse(m);n.onError?.(h.message||h)}catch{n.onError?.(m||"Stream error")}break}};return(async()=>{try{const u=new Headers(gi());a?.lastEventId;const m=await fetch(r,{method:"GET",headers:u,signal:o.signal});if(!m.ok){const y=await m.text();let S=`Request failed: ${m.status}`;try{S=JSON.parse(y).error||S}catch{}n.onError?.(S);return}if(!m.body){n.onError?.("No response body");return}n.onConnectionStateChange?.("connected");const h=m.body.getReader(),f=new TextDecoder;let p="",g="",x=[];const w=(y,S=!1)=>{p+=y;const k=p.split(`
646
- `);p=k.pop()||"",S&&p.length>0&&(k.push(p),p="");for(const C of k){const v=C.endsWith("\r")?C.slice(0,-1):C;if(v.startsWith("event:"))g=v.slice(6).trim();else if(v.startsWith("data:")){const j=v.slice(5);x.push(j.startsWith(" ")?j.slice(1):j)}else if(v===""){const j=x.join(`
647
- `);d(g,j),g="",x=[]}}if(S&&g&&x.length>0){const C=x.join(`
648
- `);d(g,C),g="",x=[]}};for(;;){const{done:y,value:S}=await h.read();if(y){w(f.decode(),!0);break}w(f.decode(S,{stream:!0}))}const b=p.length>0||g.length>0||x.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 _6(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 T(W(`/insights${a}`,n))}function M6(e,n){return T(W(`/insights/${encodeURIComponent(e)}/dismiss`,n),{method:"POST"})}function A6(e,n){return T(W(`/insights/${encodeURIComponent(e)}/archive`,n),{method:"POST"})}function P6(e,n){return T(W(`/insights/${encodeURIComponent(e)}/unarchive`,n),{method:"POST"})}function R6(e="manual",n,s,a,r){const o={trigger:e,inputMetadata:n};return a&&(o.modelProvider=a),r&&(o.modelId=r),T(W("/insights/run",s),{method:"POST",body:JSON.stringify(o)})}function I6(e){return T(W("/insights/runs",e))}function T6(e,n){return T(W(`/insights/${encodeURIComponent(e)}/create-task`,n),{method:"POST"})}function $6(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 T(W(`/evals${a}`,n))}function D6(e,n){return T(W(`/evals/${encodeURIComponent(e)}`,n))}function L6(e){return T(W("/evals/runs",e))}function O6(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 T(W(`/research/runs${a}`,n))}function z6(e,n){return T(W("/research/runs",n),{method:"POST",body:JSON.stringify(e)})}function F6(e,n){return T(W(`/research/runs/${encodeURIComponent(e)}`,n))}function qg(e){if(e instanceof _g){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 U6(e,n){try{return await T(W(`/research/runs/${encodeURIComponent(e)}/cancel`,n),{method:"POST"})}catch(s){qg(s)}}async function B6(e,n){try{return await T(W(`/research/runs/${encodeURIComponent(e)}/retry`,n),{method:"POST"})}catch(s){qg(s)}}function H6(e,n,s){return T(W(`/research/runs/${encodeURIComponent(e)}/export?format=${encodeURIComponent(n)}`,s))}function q6(e,n,s){const a=n.findingId??"finding-1";return T(W(`/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 V6(e,n,s){const a=n.findingId??"finding-1";return T(W(`/research/runs/${encodeURIComponent(e)}/findings/${encodeURIComponent(a)}/tasks/${encodeURIComponent(n.taskId)}/enrich`,s),{method:"POST",body:JSON.stringify({attachExport:n.attachExport})})}async function Q1(e){return Mo("/health",{nodeId:e})}async function X1(e){return Mo("/projects",{nodeId:e})}async function Z1(e,n,s){const a=new URLSearchParams({projectId:n});return s&&s.trim()&&a.set("q",s.trim()),Mo(`/tasks?${a.toString()}`,{nodeId:e})}async function e0(e,n){return Mo(`/project-health?projectId=${encodeURIComponent(n)}`,{nodeId:e})}async function W6(e){return T(`/nodes/${encodeURIComponent(e)}/settings/push`,{method:"POST",body:JSON.stringify({})})}async function K6(e){return T(`/nodes/${encodeURIComponent(e)}/settings/pull`,{method:"POST",body:JSON.stringify({conflictResolution:"last-write-wins"})})}async function G6(e){return T(`/nodes/${encodeURIComponent(e)}/settings/sync-status`)}async function J6(e){return T(`/nodes/${encodeURIComponent(e)}/auth/sync`,{method:"POST",body:JSON.stringify({})})}async function t0(e,n){return Promise.all(n.map(({projectId:s,path:a})=>NS(s,e,a)))}function n0(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 s0({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}=n0(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 i0(e){return e.charAt(0).toUpperCase()+e.slice(1)}function Ca({status:e,showLabel:n=!1,className:s,compact:a=!1}){const r=i0(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 Am=new Map,a0=6e4;function Vg(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(m=>n.filter(h=>h.slot.slotId===m),[n]);return i.useEffect(()=>{const m=e??"default";let h=!1;async function f(){const p=Am.get(m);if(p&&Date.now()<p.expiresAt){if(h||d.current)return;s(p.slots),r(!1);return}!c.current&&r(!0),l(null);try{const x=await B1(e);if(h||d.current)return;Am.set(m,{slots:x,expiresAt:Date.now()+a0}),s(x),c.current=!0}catch(x){if(h||d.current)return;l(x instanceof Error?x.message:"Failed to fetch UI slots"),c.current=!0}finally{!h&&!d.current&&r(!1)}}return f(),()=>{h=!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 Pm({size:e,color:n,label:s="llama.cpp"}){return t.jsx(bg,{size:e,color:n,"aria-label":s,"data-testid":"llama-cpp-icon"})}const r0={sm:16,md:20,lg:24};function o0({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 Rm({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 wi({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 l0({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 Im({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 c0({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 bc({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 Tm({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 $m({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 Dm({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 xc({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 Lm({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 Rr({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 Om({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 vc({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 zm({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 yc({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 d0({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 u0({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 Fm({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 wc({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 m0({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 Um({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 kc({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 Bm({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 jc({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 Hm({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 h0({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 p0({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 f0={anthropic:{component:o0,color:"var(--provider-anthropic)"},"claude-cli":{component:Hm,color:"var(--provider-anthropic)",label:"Anthropic — via Claude CLI"},"pi-claude-cli":{component:Hm,color:"var(--provider-anthropic)",label:"Anthropic — via Claude CLI"},"droid-cli":{component:h0,color:"var(--provider-openai)",label:"Factory AI — via Droid CLI"},"cursor-cli":{component:p0,color:"var(--provider-cursor-cli)",label:"Cursor — via Cursor CLI"},"llama-cpp":{component:Pm,color:"var(--provider-ollama)",label:"llama.cpp"},"llama-server":{component:Pm,color:"var(--provider-ollama)",label:"llama.cpp"},openai:{component:Rm,color:"var(--provider-openai)"},"openai-codex":{component:Rm,color:"var(--provider-openai)",label:"OpenAI Codex"},google:{component:wi,color:"var(--provider-gemini)"},gemini:{component:wi,color:"var(--provider-gemini)"},"google-antigravity":{component:wi,color:"var(--provider-gemini)",label:"Google Gemini"},antigravity:{component:wi,color:"var(--provider-gemini)",label:"Google Gemini"},"google-vertex":{component:wi,color:"var(--provider-gemini)",label:"Google Vertex AI"},vertex:{component:wi,color:"var(--provider-gemini)",label:"Google Vertex AI"},"google-cloud-code":{component:wi,color:"var(--provider-gemini)",label:"Google Cloud Code"},"cloud-code":{component:wi,color:"var(--provider-gemini)",label:"Google Cloud Code"},"google-gemini-cli":{component:wi,color:"var(--provider-gemini)",label:"Google Gemini CLI"},"google-generative-ai":{component:wi,color:"var(--provider-gemini)",label:"Google Generative AI"},ollama:{component:l0,color:"var(--text)"},github:{component:Um,color:"var(--text)"},"github-copilot":{component:Um,color:"var(--text)",label:"GitHub Copilot"},openrouter:{component:m0,color:"var(--provider-openrouter)"},minimax:{component:Im,color:"var(--provider-minimax)"},"minimax-cn":{component:Im,color:"var(--provider-minimax)",label:"MiniMax (CN)"},zai:{component:c0,color:"var(--provider-zai)"},kimi:{component:bc,color:"var(--provider-kimi)"},moonshot:{component:bc,color:"var(--provider-kimi)"},"kimi-coding":{component:bc,color:"var(--provider-kimi)",label:"Kimi"},bedrock:{component:Tm,color:"var(--provider-bedrock)"},"amazon-bedrock":{component:Tm,color:"var(--provider-bedrock)",label:"Amazon Bedrock"},xai:{component:$m,color:"var(--text)"},grok:{component:$m,color:"var(--text)",label:"xAI"},opencode:{component:Dm,color:"var(--provider-opencode)"},"opencode-go":{component:Dm,color:"var(--provider-opencode)",label:"Opencode (Go)"},deepseek:{component:xc,color:"var(--provider-deepseek)",label:"DeepSeek"},"deepseek-ai":{component:xc,color:"var(--provider-deepseek)",label:"DeepSeek"},"deep-seek":{component:xc,color:"var(--provider-deepseek)",label:"DeepSeek"},cloudflare:{component:Lm,color:"var(--provider-cloudflare)",label:"Cloudflare"},cloudflared:{component:Lm,color:"var(--provider-cloudflare)",label:"Cloudflare"},qwen:{component:Rr,color:"var(--provider-qwen)"},"qwen-ai":{component:Rr,color:"var(--provider-qwen)",label:"Qwen"},"qwen-coder":{component:Rr,color:"var(--provider-qwen)",label:"Qwen Coder"},alibaba:{component:Rr,color:"var(--provider-qwen)",label:"Qwen"},tongyi:{component:Rr,color:"var(--provider-qwen)",label:"Qwen"},lmstudio:{component:Om,color:"var(--provider-lmstudio)",label:"LM Studio"},"lm-studio":{component:Om,color:"var(--provider-lmstudio)",label:"LM Studio"},huggingface:{component:vc,color:"var(--provider-huggingface)",label:"Hugging Face"},"hugging-face":{component:vc,color:"var(--provider-huggingface)",label:"Hugging Face"},hf:{component:vc,color:"var(--provider-huggingface)",label:"Hugging Face"},mistral:{component:zm,color:"var(--provider-mistral)",label:"Mistral AI"},"mistral-ai":{component:zm,color:"var(--provider-mistral)",label:"Mistral AI"},azure:{component:yc,color:"var(--provider-azure)"},"azure-openai":{component:yc,color:"var(--provider-azure)",label:"Azure OpenAI"},"azure-openai-responses":{component:yc,color:"var(--provider-azure)",label:"Azure OpenAI"},fireworks:{component:wc,color:"var(--provider-fireworks)",label:"Fireworks AI"},"fireworks-ai":{component:wc,color:"var(--provider-fireworks)",label:"Fireworks AI"},fireworksai:{component:wc,color:"var(--provider-fireworks)",label:"Fireworks AI"},cerebras:{component:d0,color:"var(--provider-cerebras)"},groq:{component:u0,color:"var(--provider-groq)"},vercel:{component:Fm,color:"var(--provider-vercel)"},"vercel-ai-gateway":{component:Fm,color:"var(--provider-vercel)",label:"Vercel AI Gateway"},hermes:{component:kc,color:"var(--provider-hermes)",label:"Hermes"},"hermes-agent":{component:kc,color:"var(--provider-hermes)",label:"Hermes"},hermesagent:{component:kc,color:"var(--provider-hermes)",label:"Hermes"},openclaw:{component:Bm,color:"var(--provider-openclaw)",label:"OpenClaw"},"open-claw":{component:Bm,color:"var(--provider-openclaw)",label:"OpenClaw"},paperclip:{component:jc,color:"var(--provider-paperclip)",label:"Paperclip"},paperclipai:{component:jc,color:"var(--provider-paperclip)",label:"Paperclip"},"paperclip-ai":{component:jc,color:"var(--provider-paperclip)",label:"Paperclip"}};function Sn({provider:e,size:n="sm"}){const s=e.toLowerCase(),a=f0[s],r=a?.component,o=a?.color??"var(--text-muted)",l=a?.label,c=r0[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(bg,{size:c})})}function Wg({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 m=i.useCallback(async()=>{try{const b=await vj();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(()=>{m()},[m]);const h=i.useCallback(async()=>{l("testing"),d(null),await m(),u.current&&l(null)},[m]),f=i.useCallback(async b=>{l(b?"enabling":"disabling"),d(null);try{const y=await jj(b);u.current&&d({kind:y.enabled?"enabled":"disabled",restartRequired:y.restartRequired}),n?.(y.enabled),await m()}catch(y){u.current&&d({kind:"error",message:y instanceof Error?y.message:String(y)})}finally{u.current&&l(null)}},[n,m]),p=a?.binary.available??!1,g=a?.enabled??e,x=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."]}),w=t.jsxs(t.Fragment,{children:[t.jsx("button",{type:"button",className:"btn btn-sm",onClick:h,disabled:o!==null,children:o==="testing"?t.jsxs(t.Fragment,{children:[t.jsx(bt,{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(Sn,{provider:"droid-cli",size:"sm"}),t.jsx("strong",{children:"Factory AI — via Droid CLI"}),t.jsx(g0,{status:a,authenticated:e})]}),t.jsx("div",{className:"auth-provider-cli-actions",children:w})]}),t.jsxs("details",{className:"auth-provider-cli-details",children:[t.jsx("summary",{children:"Details"}),t.jsxs("div",{className:"auth-provider-cli-details-body",children:[x,t.jsx(qm,{status:a,authenticated:e}),c&&t.jsx(Vm,{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(Sn,{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"}),x,t.jsx(qm,{status:a,authenticated:e})]}),t.jsx("div",{className:"onboarding-provider-card__actions",children:w}),c&&t.jsx(Vm,{action:c})]})}function g0({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 qm({status:e,authenticated:n}){if(!e)return t.jsxs("small",{className:"settings-muted",children:[t.jsx(bt,{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 Vm({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 Wm({actions:e}){return t.jsx(Wg,{compact:!0,authenticated:!1,onToggled:()=>{e?.refreshAuthProviders?.()}})}function b0({actions:e}){return t.jsx(Wg,{authenticated:!1,onToggled:()=>{e?.refreshAuthProviders?.()}})}function x0(){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 v0({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 y0=[{pluginId:"fusion-plugin-droid-runtime",slotId:"settings-provider-card",componentPath:"./components/settings-provider-card.js",component:Wm},{pluginId:"fusion-plugin-droid-runtime",slotId:"settings-integration-card",componentPath:"./components/settings-integration-card.js",component:Wm},{pluginId:"fusion-plugin-droid-runtime",slotId:"onboarding-provider-card",componentPath:"./components/onboarding-provider-card.js",component:b0},{pluginId:"fusion-plugin-droid-runtime",slotId:"onboarding-setup-help",componentPath:"./components/onboarding-setup-help.js",component:x0},{pluginId:"fusion-plugin-droid-runtime",slotId:"post-onboarding-recommendation",componentPath:"./components/post-onboarding-recommendation.js",component:v0}];function w0(e){return y0.find(s=>s.pluginId===e.pluginId&&s.slotId===e.slot.slotId&&s.componentPath===e.slot.componentPath)?.component??null}function k0({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 ta({slotId:e,projectId:n,pluginIds:s,renderPlaceholder:a=!0,actions:r}){const{getSlotsForId:o,loading:l,error:c}=Vg(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(So,{level:"page",children:t.jsx(t.Fragment,{children:d.map((u,m)=>{const h=`${u.pluginId}-${u.slot.slotId}-${m}`,f=w0(u);return f?t.jsx(f,{entry:u,actions:r},h):a?t.jsx(k0,{slotId:u.slot.slotId,pluginId:u.pluginId},h):null})})})}function j0(){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 Ys(){const[e,n]=i.useState(j0);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 Sr(e){return e.replace(/\\/g,"/")}function vu(e){return e.replace(/[\\/]+$/g,"")}function yu(e){const n=Sr(vu(e));return n?n.split("/").filter(Boolean):[]}function wu(e){const n=Sr(vu(e));if(!n)return e;const s=n.split("/").filter(Boolean);return s[s.length-1]||n}function Kg(e,n){const s=yu(e);return s.length===0?Sr(e):s.slice(-2).join("/")}function N0(e){const n=Sr(vu(e)),s=n.lastIndexOf("/");return s<0?"":n.slice(0,s+1)}function S0(e,n){return!e||e==="."?n:[...yu(e),n].join("/")}function C0(e){const n=yu(e);return n.length===0?".":(n.pop(),n.length===0?".":n.join("/"))}function Y6(e){const n=Sr(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 ku=new Map;function Ro(e,n){return`plugin:${e}:${n}`}function Gg(e){const n=/^plugin:([^:]+):(.+)$/u.exec(e);return n?{pluginId:n[1],viewId:n[2]}:null}function rr(e){return Gg(e)!==null}function Km(e,n,s){ku.set(Ro(e,n),s)}function E0(e,n){return ku.get(Ro(e,n))??null}function _0(e,n){return ku.has(Ro(e,n))}function Nc({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(No,{}),"Plugin view unavailable"]}),t.jsxs("p",{className:"plugin-dashboard-view-missing-description",children:["No host registration found for ",t.jsx("code",{children:e}),"."]})]})}function M0({viewId:e,context:n}){const s=Gg(e);if(!s)return t.jsx(Nc,{viewId:e});const a=E0(s.pluginId,s.viewId);return a?t.jsx(So,{fallback:t.jsx(Nc,{viewId:e}),children:t.jsx(i.Suspense,{fallback:null,children:t.jsx(a,{context:n})})}):t.jsx(Nc,{viewId:e})}const no=Ro,A0={activity:Ks,bot:$n,brain:oo,checksquare:hu,clock:Hi,filetext:ia,folder:bs,gitbranch:Us,grid3x3:Gl,layoutgrid:aa,mail:Na,map:xw,messagesquare:Ui,monitor:dr,search:Fi,sparkles:ps,target:vs,workflow:Sl,zap:Qn};function P0(e){return(e??"").trim().toLowerCase().replace(/[-_\s]/g,"")}function Ml(e){return A0[P0(e)]??Gl}const Uo="__fusion:no-branch__",Jg={active:{color:"var(--success)"},paused:{color:"var(--warning)"},errored:{color:"var(--color-error)"},initializing:{color:"var(--info)"}};function R0({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(rn,{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,m=Jg[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:m||"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:Kg(d.path)})]}),u&&t.jsx(hs,{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 Gm({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 I0({onOpenSettings:e,onOpenGitHubImport:n,onOpenPlanning:s,onResumePlanning:a,activePlanningSessionCount:r=0,onOpenUsage:o,onOpenActivityLog:l,onOpenSystemStats:c,onOpenMailbox:d,mailboxUnreadCount:u=0,mailboxPendingApprovalCount:m=0,chatHasUnreadResponse:h=!1,onOpenSchedules:f,onOpenGitManager:p,onOpenNodes:g,showNodesButton:x,onOpenWorkflowSteps:w,onOpenScripts:b,onRunScript:y,onToggleTerminal:S,onOpenFiles:k,filesOpen:C,onOpenTodos:v,todosOpen:j,todosEnabled:P,globalPaused:U,enginePaused:E,onToggleGlobalPause:R,onToggleEnginePause:L,view:F="board",onChangeView:M,showSkillsTab:O,showAgentsTab:q,searchQuery:te="",onSearchChange:Z,branchFilter:K="",baseBranchFilter:A="",branchOptions:I=[],baseBranchOptions:$=[],onBranchFilterChange:N,onBaseBranchFilterChange:G,projects:xe=[],currentProject:Se,onSelectProject:je,onViewAllProjects:se,projectId:Ve,shellHost:ee={kind:"browser"},mobileNavEnabled:ce,availableNodes:ne=[],currentNode:re,onSelectNode:J,isRemote:B=!1,experimentalFeatures:ye,pluginDashboardViews:Ce=[],shellConnectionControl:H}){const ke=Ys(),pe=ke==="mobile",Oe=pe||ke==="tablet",He=pe&&ce,[dt,Fe]=i.useState(!1),[fe,$e]=i.useState(!1),[De,ot]=i.useState(!1),[Be,we]=i.useState(!1),[Q,_e]=i.useState(!1),[lt,ht]=i.useState(!1),[mt,xt]=i.useState(!1),[Ie,Ue]=i.useState(!1),[pt,oe]=i.useState(!1),[le,ge]=i.useState(!1),[Ne,ue]=i.useState(!1),[qe,me]=i.useState({}),[tt,Ct]=i.useState(!1),[wt,$t]=i.useState(-1),[Vt,Mt]=i.useState(null),[Dt,Qt]=i.useState({}),[Kt,Bt]=i.useState(!1),on=i.useRef(null),fn=i.useRef(null),Jt=i.useRef(null),an=i.useRef(null),zt=i.useRef(null),en=i.useRef(null),Zt=i.useRef(!1),dn=i.useRef(null),ve=i.useRef(null),ze=i.useRef(null),We=i.useRef(null),Ze=i.useRef(null),Ye=i.useRef(null),It=i.useRef(null),St=i.useRef(null),Ht=i.useRef(!1),jt=i.useMemo(()=>ne.filter(ie=>ie.type==="remote"),[ne]),ae=jt.length>0,Le=i.useMemo(()=>Object.entries(qe).sort(([ie],[st])=>ie.localeCompare(st)),[qe]),At=Le.length>0,Lt=Le.length+(At?1:0),Ft=i.useMemo(()=>Object.entries(Dt).sort(([ie],[st])=>ie.localeCompare(st)),[Dt]),Me=i.useMemo(()=>!!(M||ye?.researchView||P||ye?.insights||O||ye?.memoryView||ye?.devServerView||!He||Ce.some(ie=>ie.view.placement!=="primary")),[M,ye,P,O,He,Ce]),ct=i.useCallback(()=>{const ie=window.visualViewport;return ie&&ie.width>0&&ie.height>0?{width:ie.width,height:ie.height,offsetTop:ie.offsetTop,offsetLeft:ie.offsetLeft}:{width:window.innerWidth,height:window.innerHeight,offsetTop:0,offsetLeft:0}},[]),gt=i.useCallback(()=>{const ie=It.current;if(!ie)return;const st=ie.getBoundingClientRect(),Gt=St.current,{width:Cn,height:fs,offsetTop:On,offsetLeft:jn}=ct(),zn=16,hn=16,Et=6,En=Gt?.offsetWidth||Math.max(st.width,260),yn=Math.min(En,Math.max(Cn-zn*2,160)),ls=Gt?.offsetHeight||280,cs=Math.min(ls,Math.max(fs-hn*2,160)),Hn=st.top-On,qn=st.bottom-On,wn=st.right-jn,Zn=fs-qn,_n=Hn,is=Zn<cs&&_n>Zn,Ns=Math.min(Math.max(wn-yn,zn),Cn-zn-yn)+jn,es=is?Math.max(hn+On,Hn-cs-Et+On):Math.min(qn+Et+On,fs+On-hn-cs);Mt({top:es,left:Ns,width:yn})},[ct]),_t=i.useCallback((ie,st)=>{y?.(ie,st),ue(!1),$t(-1)},[y]),Yt=i.useCallback(()=>{b?.(),ue(!1),$t(-1)},[b]),Xt=i.useCallback(ie=>{switch(ie.key){case"ArrowDown":ie.preventDefault(),Lt>0&&$t(st=>st<Lt-1?st+1:0);break;case"ArrowUp":ie.preventDefault(),Lt>0&&$t(st=>st>0?st-1:Lt-1);break;case"Enter":if(ie.preventDefault(),wt>=0)if(wt<Le.length){const[st,Gt]=Le[wt];_t(st,Gt)}else At&&wt===Le.length&&Yt();break;case"Home":ie.preventDefault(),Lt>0&&$t(0);break;case"End":ie.preventDefault(),Lt>0&&$t(Lt-1);break}},[Yt,_t,wt,Le,At,Lt]);i.useEffect(()=>{Zt.current=Q},[Q]),i.useEffect(()=>{Ht.current=Ne},[Ne]),i.useEffect(()=>{if(!Q||!Oe)return;let ie=!1;return Bt(!0),mo(Ve).then(st=>{ie||Qt(st)}).catch(()=>{ie||Qt({})}).finally(()=>{ie||Bt(!1)}),()=>{ie=!0}},[Q,Oe,Ve]),i.useEffect(()=>{if(!Ne||Oe)return;let ie=!1;return Ct(!0),mo(Ve).then(st=>{ie||me(st)}).catch(()=>{ie||me({})}).finally(()=>{ie||Ct(!1)}),()=>{ie=!0}},[Ne,Oe,Ve]),i.useEffect(()=>{if(!Ne)return;const ie=st=>{Ye.current&&!Ye.current.contains(st.target)&&ue(!1)};return document.addEventListener("mousedown",ie),()=>document.removeEventListener("mousedown",ie)},[Ne]),i.useEffect(()=>{if(!Ne)return;const ie=st=>{st.key==="Escape"&&(ue(!1),It.current?.focus())};return document.addEventListener("keydown",ie),()=>document.removeEventListener("keydown",ie)},[Ne]),i.useEffect(()=>{if(Ne){$t(-1);const ie=window.setTimeout(()=>St.current?.focus(),0);return()=>window.clearTimeout(ie)}Mt(null)},[Ne]),i.useEffect(()=>{if(!Ne)return;const ie=requestAnimationFrame(()=>{gt()});return()=>cancelAnimationFrame(ie)},[Ne,tt,Le.length,At,gt]),i.useEffect(()=>{if(!Ne)return;const ie=()=>gt();window.addEventListener("resize",ie),window.addEventListener("scroll",ie,!0);const st=window.visualViewport;return st&&(st.addEventListener("resize",ie),st.addEventListener("scroll",ie)),()=>{window.removeEventListener("resize",ie),window.removeEventListener("scroll",ie,!0),st&&(st.removeEventListener("resize",ie),st.removeEventListener("scroll",ie))}},[Ne,gt]),i.useEffect(()=>{Oe&&(ue(!1),$t(-1))},[Oe]);const Te=dt||te.length>0,Je=(fe||te.length>0)&&!De,Nt=(F==="board"||F==="list")&&!pe&&Z&&!De&&te.length===0,Ut=(F==="board"||F==="list")&&!pe&&Z,tn=F==="board";i.useEffect(()=>{te===""&&ot(!1)},[te]),i.useEffect(()=>{if(!Be)return;const ie=st=>{fn.current&&!fn.current.contains(st.target)&&on.current&&!on.current.contains(st.target)&&we(!1)};return document.addEventListener("mousedown",ie),()=>document.removeEventListener("mousedown",ie)},[Be]),i.useEffect(()=>{if(!pt)return;const ie=st=>{an.current&&!an.current.contains(st.target)&&Jt.current&&!Jt.current.contains(st.target)&&oe(!1)};return document.addEventListener("mousedown",ie),()=>document.removeEventListener("mousedown",ie)},[pt]),i.useEffect(()=>{if(!lt)return;const ie=st=>{dn.current&&!dn.current.contains(st.target)&&ht(!1)};return document.addEventListener("mousedown",ie),()=>document.removeEventListener("mousedown",ie)},[lt]),i.useEffect(()=>{const ie=st=>{if(st.key==="Escape"){if(Ue(!1),oe(!1),Zt.current){_e(!1);return}if(Ht.current){ue(!1),It.current?.focus();return}we(!1),Fe(!1),ht(!1),xt(!1)}};return document.addEventListener("keydown",ie),()=>document.removeEventListener("keydown",ie)},[]),i.useEffect(()=>{if(!mt)return;const ie=st=>{ve.current&&!ve.current.contains(st.target)&&xt(!1)};return document.addEventListener("mousedown",ie),()=>document.removeEventListener("mousedown",ie)},[mt]),i.useEffect(()=>{if(!le)return;const ie=st=>{Ze.current&&!Ze.current.contains(st.target)&&ge(!1)};return document.addEventListener("mousedown",ie),()=>document.removeEventListener("mousedown",ie)},[le]),i.useEffect(()=>{if(!le)return;const ie=st=>{st.key==="Escape"&&ge(!1)};return document.addEventListener("keydown",ie),()=>document.removeEventListener("keydown",ie)},[le]),i.useEffect(()=>{if(!Ie)return;const ie=st=>{ze.current&&!ze.current.contains(st.target)&&We.current&&!We.current.contains(st.target)&&Ue(!1)};return document.addEventListener("mousedown",ie),()=>document.removeEventListener("mousedown",ie)},[Ie]);const Xn=i.useCallback(()=>{Fe(ie=>!ie)},[]),be=i.useCallback(()=>{$e(!0),ot(!1)},[]),it=i.useCallback(()=>{$e(!1),ot(!0),Z&&Z("")},[Z]),rt=i.useCallback(()=>{we(ie=>!ie)},[]),at=i.useCallback(ie=>{ie&&ie(),we(!1),_e(!1)},[]),ut=i.useCallback(()=>{Fe(!1),Z&&Z("")},[Z]),vt=ee.kind==="desktop-shell";return t.jsxs("div",{className:"header-wrapper",children:[t.jsxs("header",{className:"header","data-shell-kind":ee.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"})]}),pe&&xe.length>=1&&je&&t.jsxs("div",{className:"mobile-project-switch",ref:ve,children:[t.jsx("button",{className:`mobile-project-switch-trigger${mt?" mobile-project-switch-trigger--open":""}`,onClick:()=>xt(ie=>!ie),title:"Switch project","aria-label":"Switch project","aria-expanded":mt,"aria-haspopup":"listbox","data-testid":"mobile-project-switch-trigger",children:t.jsx(rn,{size:14,className:`mobile-project-switch-chevron${mt?" mobile-project-switch-chevron--open":""}`})}),mt&&t.jsx("div",{className:"mobile-project-switch-dropdown",role:"listbox","aria-label":"Select project","data-testid":"mobile-project-switch-dropdown",children:xe.map(ie=>{const st=Se?.id===ie.id,Gt=Jg[ie.status]?.color;return t.jsxs("button",{className:`mobile-project-switch-item${st?" mobile-project-switch-item--current":""}`,onClick:()=>{je(ie),xt(!1)},role:"option","aria-selected":st,"data-testid":`mobile-project-switch-item-${ie.id}`,children:[t.jsx("span",{className:"mobile-project-switch-dot",style:{backgroundColor:Gt||"var(--text-muted)"}}),t.jsxs("div",{className:"mobile-project-switch-info",children:[t.jsx("span",{className:"mobile-project-switch-name",children:ie.name}),t.jsx("span",{className:"mobile-project-switch-path",children:Kg(ie.path)})]}),st&&t.jsx(hs,{size:14,className:"mobile-project-switch-check"})]},ie.id)})})]}),!Oe&&xe.length>=1&&se&&t.jsx(R0,{projects:xe,currentProject:Se??null,onViewAll:se,onSelectProject:je}),ae&&t.jsxs("div",{className:`header-node-selector${pe?" header-node-selector--mobile":""}`,ref:pe?void 0:dn,children:[t.jsx(s0,{node:re??null,showDetails:!pe}),!pe&&t.jsxs(t.Fragment,{children:[t.jsx("button",{className:`btn-icon node-selector-trigger${lt?" node-selector-trigger--open":""}`,onClick:()=>ht(ie=>!ie),title:"Switch node","aria-label":"Switch node","aria-expanded":lt,"aria-haspopup":"listbox","data-testid":"node-selector-trigger",children:t.jsx(Mn,{size:12,className:`node-selector-chevron${lt?" node-selector-chevron--open":""}`})}),lt&&t.jsxs("div",{className:"node-selector-dropdown",role:"listbox","aria-label":"Select node",children:[t.jsxs("button",{className:`node-selector-option${B?"":" node-selector-option--active"}`,onClick:()=>{J?.(null),ht(!1)},role:"option","aria-selected":!B,"data-testid":"node-option-local",children:[t.jsx(Ca,{status:"online",compact:!0}),t.jsx("span",{className:"node-selector-option-label",children:"Local"})]}),jt.map(ie=>t.jsxs("button",{className:`node-selector-option${re?.id===ie.id?" node-selector-option--active":""}`,onClick:()=>{J?.(ie),ht(!1)},role:"option","aria-selected":re?.id===ie.id,"data-testid":`node-option-${ie.id}`,children:[t.jsx(Ca,{status:ie.status,compact:!0}),t.jsx("span",{className:"node-selector-option-label",children:ie.name}),t.jsx("span",{className:"node-selector-option-status",children:ie.status})]},ie.id))]})]})]})]}),t.jsxs("div",{className:"header-actions",children:[H,He&&M&&(F==="board"||F==="list")&&t.jsxs("div",{className:"view-toggle","data-testid":"mobile-view-toggle",children:[t.jsx("button",{className:`view-toggle-btn${F==="board"?" active":""}`,onClick:()=>M("board"),title:"Board view","aria-label":"Board view","aria-pressed":F==="board","data-testid":"mobile-view-toggle-board",children:t.jsx(aa,{size:16})}),t.jsx("button",{className:`view-toggle-btn${F==="list"?" active":""}`,onClick:()=>M("list"),title:"List view","aria-label":"List view","aria-pressed":F==="list","data-testid":"mobile-view-toggle-list",children:t.jsx(Ad,{size:16})})]}),Z&&pe&&(He||F==="board"||F==="list")&&!Te&&t.jsx("button",{className:"btn-icon mobile-search-trigger",onClick:Xn,title:"Open search","aria-label":"Open search","aria-expanded":!1,"data-testid":"mobile-header-search-btn",children:t.jsx(Fi,{size:16})}),Nt&&t.jsx("button",{className:"btn-icon",onClick:be,title:"Open search","aria-label":"Open search","data-testid":"desktop-header-search-btn",children:t.jsx(Fi,{size:16})}),pe&&He&&o&&t.jsx("button",{className:"btn-icon",onClick:ie=>o(ie.currentTarget.getBoundingClientRect()),title:"View usage","data-testid":"mobile-header-usage-btn",children:t.jsx(Ks,{size:16})}),!He&&M&&t.jsxs("div",{className:"view-toggle",children:[t.jsx("button",{className:`view-toggle-btn${F==="board"?" active":""}`,onClick:()=>M("board"),title:"Board view","aria-label":"Board view","aria-pressed":F==="board",children:t.jsx(aa,{size:16})}),t.jsx("button",{className:`view-toggle-btn${F==="list"?" active":""}`,onClick:()=>M("list"),title:"List view","aria-label":"List view","aria-pressed":F==="list",children:t.jsx(Ad,{size:16})}),q&&t.jsx("button",{className:`view-toggle-btn${F==="agents"?" active":""}`,onClick:()=>M("agents"),title:"Agents view","aria-label":"Agents view","aria-pressed":F==="agents",children:t.jsx($n,{size:16})}),t.jsx("button",{className:`view-toggle-btn${F==="missions"?" active":""}`,onClick:()=>M("missions"),title:"Missions view","aria-label":"Missions view","aria-pressed":F==="missions",children:t.jsx(vs,{size:16})}),t.jsxs("button",{className:`view-toggle-btn${F==="chat"?" active":""}`,onClick:()=>M("chat"),title:"Chat view","aria-label":"Chat view","aria-pressed":F==="chat","data-testid":"header-chat-view-btn",children:[t.jsx(Ui,{size:16}),h&&F!=="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${F==="documents"?" active":""}`,onClick:()=>M("documents"),title:"Documents view","aria-label":"Documents view","aria-pressed":F==="documents",children:t.jsx(ia,{size:16})}),t.jsxs("button",{className:`view-toggle-btn${F==="mailbox"?" active":""}`,onClick:()=>M("mailbox"),title:"Mailbox view","aria-label":"Mailbox view","aria-pressed":F==="mailbox",children:[t.jsx(Na,{size:16}),m>0&&F!=="mailbox"&&t.jsx("span",{className:"status-dot status-dot--pending header-chat-unread-dot","aria-label":"Pending approvals"})]}),Ce.filter(ie=>ie.view.placement==="primary").sort((ie,st)=>(ie.view.order??Number.MAX_SAFE_INTEGER)-(st.view.order??Number.MAX_SAFE_INTEGER)).map(ie=>{const st=no(ie.pluginId,ie.view.viewId),Gt=Ml(ie.view.icon);return t.jsx("button",{className:`view-toggle-btn${F===st||F==="graph"&&ie.pluginId==="fusion-plugin-dependency-graph"&&ie.view.viewId==="graph"?" active":""}`,onClick:()=>M(ie.pluginId==="fusion-plugin-dependency-graph"&&ie.view.viewId==="graph"?"graph":st),title:`${ie.view.label} view`,"aria-label":`${ie.view.label} view`,"aria-pressed":F===st,"data-testid":`view-toggle-plugin-${ie.pluginId}-${ie.view.viewId}`,children:t.jsx(Gt,{size:16})},`${ie.pluginId}:${ie.view.viewId}`)}),Me&&t.jsxs(t.Fragment,{children:[t.jsx("button",{ref:We,className:`view-toggle-btn${["research","skills","insights","memory","dev-server","devserver","graph"].includes(F)||ye?.evalsView&&F==="evals"||P&&j||rr(F)?" active":""}`,onClick:()=>Ue(ie=>!ie),title:"More views","aria-label":"More views","aria-haspopup":"menu","aria-expanded":Ie,"data-testid":"view-toggle-overflow-trigger",children:t.jsx(rn,{size:12})}),Ie&&t.jsxs("div",{ref:ze,className:"view-toggle-overflow-menu",role:"menu","aria-label":"More views",children:[ye?.evalsView&&t.jsxs("button",{className:`view-toggle-overflow-item${F==="evals"?" active":""}`,onClick:()=>{M("evals"),Ue(!1)},role:"menuitem","data-testid":"view-overflow-evals",children:[t.jsx(vs,{size:14}),t.jsx("span",{children:"Evals"})]}),ye?.researchView&&t.jsxs("button",{className:`view-toggle-overflow-item${F==="research"?" active":""}`,onClick:()=>{M("research"),Ue(!1)},role:"menuitem","data-testid":"view-overflow-research",children:[t.jsx(Fi,{size:14}),t.jsx("span",{children:"Research"})]}),ye?.insights&&t.jsxs("button",{className:`view-toggle-overflow-item${F==="insights"?" active":""}`,onClick:()=>{M("insights"),Ue(!1)},role:"menuitem","data-testid":"view-overflow-insights",children:[t.jsx(ps,{size:14}),t.jsx("span",{children:"Insights"})]}),O&&t.jsxs("button",{className:`view-toggle-overflow-item${F==="skills"?" active":""}`,onClick:()=>{M("skills"),Ue(!1)},role:"menuitem","data-testid":"view-overflow-skills",children:[t.jsx(Qn,{size:14}),t.jsx("span",{children:"Skills"})]}),ye?.memoryView&&t.jsxs("button",{className:`view-toggle-overflow-item${F==="memory"?" active":""}`,onClick:()=>{M("memory"),Ue(!1)},role:"menuitem","data-testid":"view-toggle-memory",children:[t.jsx(oo,{size:14}),t.jsx("span",{children:"Memory"})]}),ye?.devServerView&&t.jsxs("button",{className:`view-toggle-overflow-item${F==="dev-server"||F==="devserver"?" active":""}`,onClick:()=>{M("devserver"),Ue(!1)},role:"menuitem","data-testid":"view-toggle-devserver",children:[t.jsx(dr,{size:14}),t.jsx("span",{children:"Dev Server"}),t.jsx("span",{className:"visually-hidden","data-testid":"view-toggle-dev-server"})]}),P&&v&&t.jsxs("button",{className:`view-toggle-overflow-item${j?" active":""}`,onClick:()=>{v(),Ue(!1)},role:"menuitem","data-testid":"view-overflow-todos",children:[t.jsx(hu,{size:14}),t.jsx("span",{children:"Todos"})]}),Ce.filter(ie=>ie.view.placement!=="primary").sort((ie,st)=>(ie.view.order??Number.MAX_SAFE_INTEGER)-(st.view.order??Number.MAX_SAFE_INTEGER)).map(ie=>{const st=no(ie.pluginId,ie.view.viewId),Gt=Ml(ie.view.icon);return t.jsxs("button",{className:`view-toggle-overflow-item${F===st||F==="graph"&&ie.pluginId==="fusion-plugin-dependency-graph"&&ie.view.viewId==="graph"?" active":""}`,onClick:()=>{M(ie.pluginId==="fusion-plugin-dependency-graph"&&ie.view.viewId==="graph"?"graph":st),Ue(!1)},role:"menuitem","data-testid":`view-overflow-plugin-${ie.pluginId}-${ie.view.viewId}`,children:[t.jsx(Gt,{size:14}),t.jsx("span",{children:ie.view.label})]},`${ie.pluginId}:${ie.view.viewId}`)})]})]})]}),!Oe&&o&&t.jsx("button",{className:"btn-icon",onClick:ie=>o(ie.currentTarget.getBoundingClientRect()),title:"View usage","data-testid":"desktop-header-usage-btn",children:t.jsx(Ks,{size:16})}),!Oe&&c&&t.jsx("button",{className:"btn-icon",onClick:c,title:"System Stats","data-testid":"desktop-header-system-stats-btn",children:t.jsx(dr,{size:16})}),!Oe&&l&&t.jsx("button",{className:"btn-icon",onClick:l,title:"View Activity Log",children:t.jsx(lo,{size:16})}),!Oe&&!vt&&t.jsx("button",{className:"btn-icon",onClick:n,title:"Import from GitHub",children:t.jsx(Gm,{size:16})}),!Oe&&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(_i,{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})]}),!Oe&&t.jsxs("div",{className:"terminal-split-btn",ref:Ye,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(Bi,{size:16})}),b&&y&&t.jsxs(t.Fragment,{children:[t.jsx("span",{className:"terminal-split-btn__divider"}),t.jsx("button",{ref:It,className:`btn-icon terminal-split-btn__chevron${Ne?" btn-icon--active":""}`,onClick:()=>ue(ie=>!ie),title:"Scripts","aria-haspopup":"listbox","aria-expanded":Ne,"aria-label":"Quick scripts","data-testid":"scripts-btn",children:t.jsx(rn,{size:12,className:`quick-scripts-dropdown__trigger-chevron${Ne?" rotate":""}`})}),Ne&&t.jsx("div",{ref:St,tabIndex:-1,className:"quick-scripts-dropdown__menu",role:"listbox","aria-label":"Scripts",onKeyDown:Xt,"data-testid":"quick-scripts-dropdown",style:Vt?{position:"fixed",top:`${Vt.top}px`,left:`${Vt.left}px`,width:`${Vt.width}px`,right:"auto"}:void 0,children:tt?t.jsxs("div",{className:"quick-scripts-dropdown__loading","data-testid":"quick-scripts-loading",children:[t.jsx(bt,{size:16,className:"animate-spin"}),t.jsx("span",{children:"Loading scripts..."})]}):Le.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(Bi,{size:16})}),t.jsx("p",{children:"No scripts configured"}),t.jsx("button",{className:"quick-scripts-dropdown__empty-action btn",onClick:Yt,children:"Add your first script"})]}):t.jsxs(t.Fragment,{children:[t.jsx("div",{className:"quick-scripts-dropdown__list",children:Le.map(([ie,st],Gt)=>t.jsxs("button",{className:`quick-scripts-dropdown__item ${wt===Gt?"highlighted":""}`,onClick:()=>_t(ie,st),role:"option","aria-selected":wt===Gt,"data-testid":`quick-script-item-${ie}`,children:[t.jsx(Yn,{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:ie}),t.jsx("span",{className:"quick-scripts-dropdown__item-command",title:st,children:st.length>50?`${st.slice(0,50)}...`:st})]})]},ie))}),t.jsx("div",{className:"quick-scripts-dropdown__footer",children:t.jsxs("button",{className:`quick-scripts-dropdown__manage ${At&&wt===Le.length?"highlighted":""}`,onClick:Yt,"data-testid":"quick-scripts-manage",children:[t.jsx(to,{size:14}),t.jsx("span",{children:"Manage Scripts..."})]})})]})})]})]}),!Oe&&k&&t.jsx("button",{className:`btn-icon${C?" btn-icon--active":""}`,onClick:k,title:"Browse files","data-testid":"files-toggle-btn",children:t.jsx(bs,{size:16})}),!Oe&&p&&t.jsx("button",{className:"btn-icon",onClick:p,title:"Git Manager","data-testid":"git-manager-btn",children:t.jsx(Us,{size:16})}),!Oe&&w&&t.jsx("button",{className:"btn-icon",onClick:w,title:"Workflow Steps","data-testid":"workflow-steps-btn",children:t.jsx(Sl,{size:16})}),!Oe&&t.jsxs("div",{style:{position:"relative"},children:[t.jsx("button",{ref:Jt,className:"btn-icon",onClick:()=>oe(ie=>!ie),title:"More actions","aria-label":"More actions","aria-expanded":pt,"aria-haspopup":"menu","data-testid":"desktop-overflow-trigger",children:t.jsx(Ed,{size:16})}),pt&&t.jsxs("div",{ref:an,className:"desktop-overflow-menu",role:"menu","aria-label":"More actions",children:[g&&x!==!1&&t.jsxs("button",{className:"view-toggle-overflow-item",onClick:()=>{g(),oe(!1)},role:"menuitem","data-testid":"desktop-overflow-nodes-btn",children:[t.jsx(co,{size:14}),t.jsx("span",{children:"Nodes"})]}),t.jsxs("button",{className:"view-toggle-overflow-item",onClick:()=>{at(f),oe(!1)},role:"menuitem","data-testid":"desktop-overflow-schedules-btn",children:[t.jsx(Hi,{size:14}),t.jsx("span",{children:"Automation"})]})]})]}),t.jsxs("div",{className:"engine-control-split-btn",ref:Ze,children:[t.jsx("button",{className:`btn-icon engine-control-split-btn__main${U?" btn-icon--stopped":""}`,onClick:R,title:U?"Start AI engine":"Stop AI engine","data-testid":"engine-control-main-btn",children:U?t.jsx(Yn,{size:16}):t.jsx(Si,{size:16})}),t.jsx("span",{className:"engine-control-split-btn__divider"}),t.jsx("button",{className:`btn-icon engine-control-split-btn__chevron${le?" btn-icon--active":""}`,onClick:()=>ge(ie=>!ie),title:"Engine options","aria-haspopup":"menu","aria-expanded":le,"data-testid":"engine-control-chevron-btn",children:t.jsx(rn,{size:12})}),le&&t.jsx("div",{className:"engine-control-split-btn__menu",role:"menu",children:t.jsxs("button",{className:`engine-control-split-btn__menu-item${E?" engine-control-split-btn__menu-item--active":""}`,onClick:()=>{L?.(),ge(!1)},role:"menuitem",title:E?"Resume scheduling":"Pause triage",disabled:!!U,"data-testid":"engine-control-pause-triage-btn",children:[E?t.jsx(Yn,{size:14}):t.jsx(pi,{size:14}),t.jsx("span",{children:E?"Resume scheduling":"Pause triage"})]})})]}),!Oe&&t.jsx("button",{className:"btn-icon",onClick:e,title:"Settings",children:t.jsx(to,{size:16})}),t.jsx(ta,{slotId:"header-action",projectId:Ve}),Oe&&!He&&t.jsx("button",{ref:on,className:"btn-icon compact-overflow-trigger",onClick:rt,title:"More header actions","aria-label":"More header actions","aria-expanded":Be,"aria-haspopup":"menu",children:t.jsx(Ed,{size:16})}),Oe&&!He&&Be&&t.jsxs("div",{ref:fn,className:"mobile-overflow-menu",role:"menu","aria-label":"Additional header actions",children:[xe.length>=1&&se&&t.jsxs("button",{className:"mobile-overflow-item",onClick:()=>at(se),role:"menuitem","data-testid":"overflow-project-selector-btn",children:[t.jsx(Gl,{size:16}),t.jsx("span",{children:"Projects"})]}),k&&t.jsxs("button",{className:"mobile-overflow-item",onClick:()=>at(k),role:"menuitem","data-testid":"overflow-files-btn",children:[t.jsx(bs,{size:16}),t.jsx("span",{children:"Browse Files"})]}),t.jsxs("button",{className:`mobile-overflow-item${r>0?" mobile-overflow-item--has-indicator":""}`,onClick:()=>at(r>0&&a?a:s),role:"menuitem","data-testid":"overflow-planning-btn",children:[t.jsxs("span",{className:"mobile-overflow-icon-wrapper",children:[t.jsx(_i,{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"})]}),p&&t.jsxs("button",{className:"mobile-overflow-item",onClick:()=>at(p),role:"menuitem","data-testid":"overflow-git-btn",children:[t.jsx(Us,{size:16}),t.jsx("span",{children:"Git Manager"})]}),g&&x!==!1&&t.jsxs("button",{className:"mobile-overflow-item",onClick:()=>at(g),role:"menuitem","data-testid":"overflow-nodes-btn",children:[t.jsx(co,{size:16}),t.jsx("span",{children:"Nodes"})]}),!vt&&t.jsxs("button",{className:"mobile-overflow-item",onClick:()=>at(n),role:"menuitem",children:[t.jsx(Gm,{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:()=>at(S),role:"menuitem","data-testid":"overflow-terminal-primary-btn",children:[t.jsx(Bi,{size:16}),t.jsx("span",{children:"Terminal"})]}),t.jsx("button",{className:"mobile-overflow-split-toggle",onClick:()=>_e(ie=>!ie),role:"menuitem","aria-expanded":Q,"aria-haspopup":"menu","aria-label":"Show scripts","data-testid":"overflow-terminal-submenu-toggle",children:t.jsx(Mn,{size:14,className:`mobile-overflow-chevron${Q?" mobile-overflow-chevron--open":""}`})})]}),Q&&t.jsx("div",{className:"mobile-overflow-submenu",role:"menu","aria-label":"Scripts submenu",children:Kt?t.jsxs("div",{className:"mobile-overflow-submenu-loading","data-testid":"overflow-scripts-loading",children:[t.jsx(bt,{size:14,className:"animate-spin"}),t.jsx("span",{children:"Loading scripts…"})]}):Ft.length>0?t.jsxs(t.Fragment,{children:[Ft.map(([ie,st])=>t.jsxs("button",{className:"mobile-overflow-item mobile-overflow-subitem",onClick:()=>{y&&y(ie,st),we(!1),_e(!1)},role:"menuitem","data-testid":`overflow-script-item-${ie}`,children:[t.jsx(Yn,{size:14}),t.jsx("span",{children:ie})]},ie)),b&&t.jsxs("button",{className:"mobile-overflow-item mobile-overflow-subitem mobile-overflow-subitem--manage",onClick:()=>at(b),role:"menuitem","data-testid":"overflow-scripts-manage",children:[t.jsx(hi,{size:14}),t.jsx("span",{children:"Manage Scripts…"})]})]}):b&&t.jsxs("button",{className:"mobile-overflow-item mobile-overflow-subitem",onClick:()=>at(b),role:"menuitem","data-testid":"overflow-scripts-manage",children:[t.jsx(hi,{size:14}),t.jsx("span",{children:"No scripts — add one…"})]})})]}),t.jsxs("button",{className:"mobile-overflow-item",onClick:()=>at(f),role:"menuitem","data-testid":"overflow-schedules-btn",children:[t.jsx(Hi,{size:16}),t.jsx("span",{children:"Automation"})]}),l&&t.jsxs("button",{className:"mobile-overflow-item",onClick:()=>at(l),role:"menuitem","data-testid":"overflow-activity-log-btn",children:[t.jsx(lo,{size:16}),t.jsx("span",{children:"View Activity Log"})]}),d&&t.jsxs("button",{className:"mobile-overflow-item",onClick:()=>at(d),role:"menuitem","data-testid":"overflow-mailbox-btn",children:[t.jsx(Na,{size:16}),t.jsxs("span",{children:["Mailbox",u>0?` (${u})`:""]}),m>0&&t.jsx("span",{className:"header-badge","data-testid":"overflow-mailbox-approval-badge",children:m})]}),o&&t.jsxs("button",{className:"mobile-overflow-item",onClick:ie=>at(()=>o(ie.currentTarget.getBoundingClientRect())),role:"menuitem","data-testid":"overflow-usage-btn",children:[t.jsx(Ks,{size:16}),t.jsx("span",{children:"View Usage"})]}),w&&t.jsxs("button",{className:"mobile-overflow-item",onClick:()=>at(w),role:"menuitem","data-testid":"overflow-workflow-steps-btn",children:[t.jsx(Sl,{size:16}),t.jsx("span",{children:"Workflow Steps"})]}),t.jsxs("button",{className:"mobile-overflow-item",onClick:()=>at(e),role:"menuitem",children:[t.jsx(to,{size:16}),t.jsx("span",{children:"Settings"})]})]})]})]}),Ut&&Je&&t.jsxs("div",{className:"header-floating-search",children:[t.jsxs("div",{className:"header-search",children:[t.jsx(Fi,{size:14,className:"header-search-icon"}),t.jsx("input",{autoFocus:!0,type:"text",placeholder:"Search tasks...",value:te,onChange:ie=>Z(ie.target.value),className:"header-search-input"}),t.jsx("button",{className:"header-search-clear",onClick:it,"aria-label":"Close search",children:t.jsx(nn,{size:14})})]}),tn&&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:K,onChange:ie=>N?.(ie.target.value),"data-testid":"working-branch-filter",children:[t.jsx("option",{value:"",children:"All working branches"}),t.jsx("option",{value:Uo,children:"No working branch"}),I.map(ie=>t.jsx("option",{value:ie,children:ie},ie))]})]}),t.jsxs("label",{className:"header-branch-filter-label",children:[t.jsx("span",{children:"Base branch"}),t.jsxs("select",{className:"header-branch-filter-select",value:A,onChange:ie=>G?.(ie.target.value),"data-testid":"target-branch-filter",children:[t.jsx("option",{value:"",children:"All base branches"}),t.jsx("option",{value:Uo,children:"No base branch"}),$.map(ie=>t.jsx("option",{value:ie,children:ie},ie))]})]})]})]}),Z&&pe&&Te&&t.jsxs("div",{className:"header-floating-search",children:[t.jsxs("div",{ref:zt,className:"header-search mobile-search-expanded",children:[t.jsx(Fi,{size:14,className:"header-search-icon"}),t.jsx("input",{ref:en,autoFocus:!0,type:"text",placeholder:"Search tasks...",value:te,onChange:ie=>Z(ie.target.value),className:"header-search-input"}),t.jsx("button",{className:"header-search-clear",onClick:ut,"aria-label":"Close search",children:t.jsx(nn,{size:14})})]}),tn&&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:K,onChange:ie=>N?.(ie.target.value),"data-testid":"working-branch-filter-mobile",children:[t.jsx("option",{value:"",children:"All working branches"}),t.jsx("option",{value:Uo,children:"No working branch"}),I.map(ie=>t.jsx("option",{value:ie,children:ie},ie))]})]}),t.jsxs("label",{className:"header-branch-filter-label",children:[t.jsx("span",{children:"Base branch"}),t.jsxs("select",{className:"header-branch-filter-select",value:A,onChange:ie=>G?.(ie.target.value),"data-testid":"target-branch-filter-mobile",children:[t.jsx("option",{value:"",children:"All base branches"}),t.jsx("option",{value:Uo,children:"No base branch"}),$.map(ie=>t.jsx("option",{value:ie,children:ie},ie))]})]})]})]})]})}const T0={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,ntfyEvents:["in-review","merged","failed","awaiting-approval","awaiting-user-review","planning-awaiting-input","message:agent-to-user","message:agent-to-agent","gridlock","fallback-used","memory-dreams-processed"],ntfyDashboardHost:void 0,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,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:"none",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:{}},$0={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",requirePrApproval:!1,pushAfterMerge:!1,pushRemote:"origin",unavailableNodePolicy:"block",defaultNodeId:void 0,worktreeInitCommand:void 0,testCommand:void 0,buildCommand:void 0,recycleWorktrees:!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,worktreeRebaseBeforeMerge:!0,worktreeRebaseRemote:"",worktreeRebaseLocalBase:!0,mergeConflictStrategy:"smart-prefer-main",workflowStepTimeoutMs:36e4,strictScopeEnforcement:!1,buildRetryCount:0,verificationFixRetries:3,buildTimeoutMs:3e5,requirePlanApproval:!1,specStalenessEnabled:!1,specStalenessMaxAgeMs:360*60*1e3,taskStuckTimeoutMs:void 0,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},D0=Object.freeze(Object.keys(T0)),L0=Object.freeze(Object.keys($0));function Q6(e){return D0.includes(e)}function X6(e){return L0.includes(e)}function Pe(e){if(e instanceof Error)return e.message;if(typeof e=="string")return e;try{return JSON.stringify(e)}catch{return String(e)}}function O0(e){return!!(e?.provider&&e?.modelId)}function ra(...e){for(const n of e)if(O0(n))return{provider:n.provider,modelId:n.modelId};return{}}function tc(e){return ra({provider:e?.defaultProviderOverride,modelId:e?.defaultModelIdOverride},{provider:e?.defaultProvider,modelId:e?.defaultModelId})}function z0(e){return ra({provider:e?.executionProvider,modelId:e?.executionModelId},{provider:e?.executionGlobalProvider,modelId:e?.executionGlobalModelId},tc(e))}function F0(e){return ra({provider:e?.planningProvider,modelId:e?.planningModelId},{provider:e?.planningGlobalProvider,modelId:e?.planningGlobalModelId},tc(e))}function U0(e){return ra({provider:e?.validatorProvider,modelId:e?.validatorModelId},{provider:e?.validatorGlobalProvider,modelId:e?.validatorGlobalModelId},tc(e))}function Z6(e){return ra({provider:e?.titleSummarizerProvider,modelId:e?.titleSummarizerModelId},{provider:e?.titleSummarizerGlobalProvider,modelId:e?.titleSummarizerGlobalModelId},{provider:e?.planningProvider,modelId:e?.planningModelId},tc(e))}function Yg(e,n){return ra({provider:e.modelProvider,modelId:e.modelId},z0(n))}function Qg(e,n){return ra({provider:e.validatorModelProvider,modelId:e.validatorModelId},U0(n))}function Xg(e,n){return ra({provider:e.planningModelProvider,modelId:e.planningModelId},F0(n))}const e5=["off","minimal","low","medium","high"],ea=["triage","todo","in-progress","in-review","done","archived"],Al="triage";function ju(e){return typeof e=="string"&&ea.includes(e)}function Zg(e,n=Al){return ju(e)?e:n}const oa=["low","normal","high","urgent"],js="normal",B0=["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"],ns={triage:"Planning",todo:"Todo","in-progress":"In Progress","in-review":"In Review",done:"Done",archived:"Archived"},H0={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"},Ld={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 q0(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)}function Jm(e){return e==="urgent"?3:e==="high"?2:e==="low"?0:1}function Ym(e,n){return Jm(n)-Jm(e)}function Sc(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 Qm(e){const n=e.columnMovedAt??e.updatedAt??e.createdAt,s=Date.parse(n);return Number.isFinite(s)?s:0}function Xm(e){return e==="merging"||e==="merging-pr"||e==="merging-fix"}function eb(e,n){return n==="todo"?[...e].sort((s,a)=>{const r=Ym(s.priority,a.priority);return r!==0?r:s.createdAt!==a.createdAt?s.createdAt.localeCompare(a.createdAt):Sc(s.id,a.id)}):[...e].sort((s,a)=>{if(n==="done"){const o=Qm(a)-Qm(s);return o!==0?o:Sc(s.id,a.id)}if(n==="in-review"){const o=Xm(s.status),l=Xm(a.status);if(o!==l)return o?-1:1}const r=Ym(s.priority,a.priority);return r!==0?r:Sc(s.id,a.id)})}function V0(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 W0({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 tb=i.createContext(null);function K0({children:e}){const[n,s]=i.useState([]),a=i.useRef([]),r=i.useCallback(u=>{s(m=>{const h=u(m);return a.current=h,h})},[]),o=i.useCallback(u=>new Promise(m=>{r(h=>[...h,{options:u,resolve:m}])}),[r]),l=i.useCallback(u=>{const m=a.current[0];m&&(m.resolve(u),r(h=>h.slice(1)))},[r]),c=n[0]??null,d=i.useMemo(()=>({confirm:o}),[o]);return kl.createElement(tb.Provider,{value:d},e,kl.createElement(W0,{isOpen:c!==null,options:c?.options??null,onConfirm:()=>l(!0),onCancel:()=>l(!1)}))}function ai(){const e=i.useContext(tb);return e||{confirm:async n=>!1}}function G0(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 nb({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(Ws,{size:12}),t.jsxs("span",{children:["#",e.number]})]}),n&&t.jsxs("a",{className:`card-github-badge ${G0(n.state,n.stateReason)}`,title:`Issue #${n.number}: ${n.title}`,href:n.url,target:"_blank",rel:"noopener noreferrer",children:[t.jsx(Wl,{size:12}),t.jsxs("span",{children:["#",n.number]})]})]})}function Bo(e,n){return`${e??"default"}:${n}`}class J0{ws=null;listeners=new Set;badgeUpdates=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;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=Bo(this.projectId,o);this.subscriptionsByTask.set(l,new Set([r]))}this.shouldReconnect=this.subscriptionsByTask.size>0,this.connect()}}subscribeTask(n,s){const a=Bo(this.projectId,s),r=this.subscriptionsByTask.get(a)??new Set,o=!r.has(n);r.add(n),this.subscriptionsByTask.set(a,r),this.shouldReconnect=this.subscriptionsByTask.size>0,this.connect(),o&&this.send({type:"subscribe",taskId:s,projectId:this.projectId})}unsubscribeTask(n,s){const a=Bo(this.projectId,s),r=this.subscriptionsByTask.get(a);r&&(r.delete(n),r.size===0&&(this.subscriptionsByTask.delete(a),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.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(Mi(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=Bo(this.projectId,l.taskId),d=this.badgeUpdates.get(c);this.badgeUpdates.set(c,{prInfo:Zm(l,"prInfo")?l.prInfo??null:d?.prInfo,issueInfo:Zm(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 ba=new J0;let Y0=0;function Zm(e,n){return Object.prototype.hasOwnProperty.call(e,n)}function sb(e){const n=i.useRef(null);n.current===null&&(n.current=`badge-hook-${Y0++}`);const s=i.useSyncExternalStore(o=>ba.subscribe(o),()=>ba.getSnapshot(),()=>ba.getSnapshot()),a=i.useCallback(o=>{ba.subscribeTask(n.current,o)},[]),r=i.useCallback(o=>{ba.unsubscribeTask(n.current,o)},[]);return i.useEffect(()=>{ba.setProjectId(e??null)},[e]),i.useEffect(()=>()=>{ba.cleanupHook(n.current)},[]),{badgeUpdates:s.badgeUpdates,isConnected:s.isConnected,subscribeToBadge:a,unsubscribeFromBadge:r}}function Pl(e,n,s,a){return e===void 0||!n?s:!a||n>=a?e??void 0:s}function Q0({taskId:e,prInfo:n,issueInfo:s,updatedAt:a,isInViewport:r,projectId:o}){const{badgeUpdates:l,subscribeToBadge:c,unsubscribeFromBadge:d}=sb(o),u=!!(n||s);i.useEffect(()=>{if(!u||!r){d(e);return}return c(e),()=>{d(e)}},[u,r,o,c,e,d]);const m=l.get(`${o??"default"}:${e}`),h=Pl(m?.prInfo,m?.timestamp,n,n?.lastCheckedAt??a),f=Pl(m?.issueInfo,m?.timestamp,s,s?.lastCheckedAt??a);return!h&&!f?null:t.jsx(nb,{prInfo:h,issueInfo:f})}const X0=i.memo(Q0);X0.displayName="TaskCardBadge";const Zs={data:new Map,pendingPromise:null,lastFetchTime:null},Z0=5e3;function xl(e,n){return n?`${n}::${e}`:e}function eC(e,n){const s=Zs.data.get(xl(e,n));if(!(!s||Date.now()-s.timestamp>Z0))return s}function tC(e){const[n,s]=i.useState(!1),a=i.useRef(null),r=i.useCallback(async c=>{let u=null;for(let m=0;m<3;m++)try{return await Kj(c,e)}catch(h){u=h instanceof Error?h:new Error(String(h));const f=Pe(h);if(f?.includes("429")||f?.toLowerCase().includes("rate limit")){const p=Math.min(1e3*Math.pow(2,m),3e4);await new Promise(g=>setTimeout(g,p));continue}break}if(u)throw u;return{}},[e]),o=i.useCallback(async c=>{if(c.length===0)return;const u=Date.now()-5e3;if(c.every(f=>{const p=Zs.data.get(xl(f,e));return p&&p.timestamp>u})&&Zs.lastFetchTime&&Zs.lastFetchTime>u)return;if(a.current&&(clearTimeout(a.current),a.current=null),Zs.pendingPromise){s(!0);try{await Zs.pendingPromise}finally{s(!1)}return}s(!0);const h=r(c);Zs.pendingPromise=h;try{const f=await h,p=Date.now();for(const[g,x]of Object.entries(f))Zs.data.set(xl(g,e),{result:x,timestamp:p});Zs.lastFetchTime=p}catch{}finally{Zs.pendingPromise=null,s(!1)}},[r,e]),l=i.useCallback(c=>Zs.data.get(xl(c,e)),[e]);return{fetchBatch:o,isLoading:n,lastFetchTime:Zs.lastFetchTime,getBatchData:l}}const Od=new Map,nC=3e4;function ib(e,n,s,a){return`${e}:${n??""}:${s??""}:${a??""}`}function sC(e,n,s,a){const r=ib(e,n,s,a),o=Od.get(r);return o?Date.now()>o.expiresAt?(Od.delete(r),null):o.stats:null}function iC(e,n,s,a,r){const o=ib(e,n,s,a);Od.set(o,{stats:r,expiresAt:Date.now()+nC})}function aC(e,n,s,a,r={}){const o=r.enabled??!0,l=r.worktree,c=r.stepVersion,d=r.pollIntervalMs,[u,m]=i.useState(null),[h,f]=i.useState(!1);return i.useEffect(()=>{if(!o){m(null),f(!1);return}const p=n==="done"&&!!s,g=(n==="in-progress"||n==="in-review")&&!!l;if(!e||!p&&!g){m(null),f(!1);return}const x=g?l:void 0,w=c!==void 0?String(c):void 0;let b=!1;async function y(k=!1){if(!k){const C=sC(e,a,x,w);if(C){b||(m(C),f(!1));return}}f(!0);try{const C=await zg(e,x,a);b||(m(C.stats),iC(e,a,x,w,C.stats))}catch{b||m(null)}finally{b||f(!1)}}y();let S;return d&&g&&(S=setInterval(()=>{y(!0)},d)),()=>{b=!0,S&&clearInterval(S)}},[e,n,s,a,o,l,c,d]),{stats:u,loading:h}}const rC=new Set(["failed","stuck-killed"]);function Rl(e,n,s){if(e.column!=="in-progress"||e.status&&rC.has(e.status)||!n||n<=0)return!1;const a=new Date(e.updatedAt).getTime();return(s??Date.now())-a>n}function oC(e){switch(e){case"passed":return"done";case"failed":return"failed";case"skipped":return"skipped";case"pending":default:return"pending"}}function lC(e){return e==="done"||e==="skipped"}function cC(e,n,s){const a=s?.get(e)?.trim();if(a)return a;const r=n?.workflowStepName?.trim();return r||e}function ab(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:cC(d,u,n),status:u?oC(u.status):"pending",source:"workflow",phase:u?.phase??"pre-merge"}}),o=[...s,...r],l=o.length,c=o.filter(d=>lC(d.status)).length;return{total:l,completed:c,items:o}}function dC(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 rb(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:dC(n)}})}function ob(e){if(!e||e.length===0)return null;let n=0,s=0;for(const a of rb(e))typeof a.durationMs=="number"&&(n+=a.durationMs,s+=1);return s>0?n:null}function Ea(e){if(!e)return null;const n=Date.parse(e);return Number.isFinite(n)?n:null}function lb(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=Ea(r.startedAt);if(o==null)continue;let l;if(r.completedAt){const c=Ea(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 cb(e,n,s){const a=Ea(e);if(a==null)return null;const r=Ea(n),o=r!=null&&r>=a?r:s;return Math.max(0,o-a)}const zd=new Map;async function uC(e,n){const s=zd.get(e);if(s)return s;try{const a=await Fg(e,n);return zd.set(e,a.title),a.title}catch{return e}}const eh=12;function mC(e){return e.length<=eh?e:e.slice(0,eh-3)+"..."}const Fd=new Map;async function hC(e,n){const s=Fd.get(e);if(s)return s;try{const a=await Dd(e,n);return Fd.set(e,a.name),a.name}catch{return e}}function pC(e){return typeof e=="string"&&oa.includes(e)?e:js}function fC(e,n){return e.length<=n?e:e.slice(0,n-3)+"..."}function db(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 gC(e){return e.sourceType==="agent_heartbeat"||e.sourceType==="automation"||!!db(e)}const bC=new Set(["triage","todo"]),th=new Set(["planning","researching","executing","finalizing","merging","merging-fix"]),nh=new Set(["merging","merging-pr","merging-fix"]),xC={triage:"var(--triage)",todo:"var(--todo)","in-progress":"var(--in-progress)","in-review":"var(--in-review)",done:"var(--done)",archived:"var(--text-muted)"},vC=new Set(["in-progress","in-review","done"]),yC=3e4;function wC(e){return e==="merging-fix"?"Merging fixes…":e}function kC(e){const n=Ea(e.columnMovedAt??e.updatedAt);if(n==null)return null;const s=Date.now();return n>s?null:n}function sh(e,n){const s=Ea(e.columnMovedAt??e.updatedAt);return s==null?null:Math.max(0,n-s)}function Gr(e,n){return cb(e.executionStartedAt,e.executionCompletedAt,n)}function jC(e){return e.column==="done"?kC(e):null}function ub(e,n){const s=Ea(e.updatedAt);return s==null?null:Math.max(0,n-s)}function NC(e,n){const s=Gr(e,n);if(s!=null)return s;const a=ub(e,n),r=Jr(e,n);return r!=null?r+(a??0):a}function Jr(e,n){if(typeof e.timedExecutionMs=="number")return e.timedExecutionMs;const s=ob(e.log),a=lb(e.workflowStepResults,n);return s==null&&a==null?null:(s??0)+(a??0)}function ih(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 ah(e){if(!e)return null;const n=e.trim();return n.length>0?n:null}function SC(e){const n=ah(e.branch),s=ah(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 rh(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 oh(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 CC(e,n){return e.length!==n.length?!1:e.every((s,a)=>s.name===n[a]?.name&&s.status===n[a]?.status)}function EC(e,n){return e.length!==n.length?!1:e.every((s,a)=>s===n[a])}function _C(e,n){return!e&&!n?!0:!e||!n||e.length!==n.length?!1:e.every((s,a)=>s===n[a])}function MC(e){const n=e?.issueUrl;return typeof n=="string"&&n.length>0?n:void 0}function AC(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}function PC(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 RC(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 IC(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 TC(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&&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&&RC(s.attachments,a.attachments)&&IC(s.comments,a.comments)&&EC(s.dependencies,a.dependencies)&&CC(s.steps,a.steps)&&_C(s.enabledWorkflowSteps,a.enabledWorkflowSteps)&&PC(s.workflowStepResults,a.workflowStepResults)&&oh(s.prInfo,a.prInfo)&&oh(s.issueInfo,a.issueInfo)}function $C({task:e,projectId:n,queued:s,onOpenDetail:a,addToast:r,globalPaused:o,onUpdateTask:l,onArchiveTask:c,onUnarchiveTask:d,onDeleteTask:u,onRetryTask:m,onOpenDetailWithTab:h,taskStuckTimeoutMs:f,onOpenMission:p,onMoveTask:g,lastFetchTimeMs:x,workflowStepNameLookup:w,disableDrag:b}){const[y,S]=i.useState(!1),[k,C]=i.useState(!1),[v,j]=i.useState(!1),[P,U]=i.useState(e.description||""),[E,R]=i.useState(!1),[L,F]=i.useState(e.column==="in-progress"||e.column==="triage"&&e.steps.some(Me=>Me.status==="done"||Me.status==="skipped")),[M,O]=i.useState(null),[q,te]=i.useState(null),[Z,K]=i.useState(!1),[A,I]=i.useState(!1),[$,N]=i.useState(()=>Date.now()),G=i.useRef(null),xe=i.useRef(!1),Se=i.useRef(null),je=i.useRef(null),[se,Ve]=i.useState(!1),{badgeUpdates:ee,subscribeToBadge:ce,unsubscribeFromBadge:ne}=sb(n),{confirm:re}=ai(),J=i.useRef(null),B=i.useRef(!1),ye=i.useCallback(Me=>Me instanceof Element?!!Me.closest("button, a, input, textarea, select, label, [role='button']"):!1,[]);i.useEffect(()=>{U(e.description||"")},[e.id,e.description]),i.useEffect(()=>{if(!Z)return;const Me=ct=>{je.current&&!je.current.contains(ct.target)&&K(!1)};return document.addEventListener("click",Me),()=>document.removeEventListener("click",Me)},[Z]),i.useEffect(()=>{if(!e.missionId){O(null);return}const Me=zd.get(e.missionId);if(Me){O(Me);return}let ct=!1;return uC(e.missionId,n).then(gt=>{ct||O(gt)}),()=>{ct=!0}},[e.missionId,n]),i.useEffect(()=>{if(!e.assignedAgentId){te(null);return}const Me=Fd.get(e.assignedAgentId);if(Me){te(Me);return}te(null);let ct=!1;return hC(e.assignedAgentId,n).then(gt=>{ct||te(gt)}),()=>{ct=!0}},[e.assignedAgentId,n]),i.useEffect(()=>{if(v&&G.current){const Me=G.current;Me.focus(),Me.style.height="auto",Me.style.height=Me.scrollHeight+"px"}},[v]),i.useEffect(()=>{if(typeof IntersectionObserver>"u"){Ve(!0);return}const Me=Se.current;if(!Me)return;const ct=new IntersectionObserver(([gt])=>{Ve(gt?.isIntersecting??!0)},{rootMargin:"200px"});return ct.observe(Me),()=>ct.disconnect()},[v,e.id]);const Ce=i.useCallback(Me=>{Me.dataTransfer.setData("text/plain",e.id),Me.dataTransfer.effectAllowed="move",S(!0)},[e.id]),H=i.useCallback(()=>{S(!1)},[]),ke=i.useCallback(Me=>Me.dataTransfer.types.includes("Files"),[]),pe=i.useCallback(Me=>{ke(Me)&&(Me.preventDefault(),Me.stopPropagation(),Me.dataTransfer.dropEffect="copy",C(!0))},[ke]),Ae=i.useCallback(Me=>{ke(Me)&&(Me.preventDefault(),Me.stopPropagation(),C(!1))},[ke]),Oe=i.useCallback(async Me=>{if(!ke(Me))return;Me.preventDefault(),Me.stopPropagation(),C(!1);const ct=Array.from(Me.dataTransfer.files);for(const gt of ct)try{await ec(e.id,gt,n),r(`Attached ${gt.name} to ${e.id}`,"success")}catch(_t){r(`Failed to attach ${gt.name}: ${Pe(_t)}`,"error")}},[e.id,ke,r]),He=i.useCallback(()=>{v||a(e)},[e,a,v]),dt=i.useCallback(Me=>{if(xe.current){xe.current=!1;return}ye(Me.target)||He()},[He,ye]),Fe=i.useCallback(Me=>{const ct=Me.touches[0];ct&&(J.current={x:ct.clientX,y:ct.clientY,time:Date.now()},B.current=!1)},[]),fe=i.useCallback(Me=>{if(!J.current)return;const ct=Me.touches[0];if(!ct)return;const gt=Math.abs(ct.clientX-J.current.x),_t=Math.abs(ct.clientY-J.current.y);(gt>lh||_t>lh)&&(B.current=!0)},[]),$e=i.useCallback(Me=>{if(ye(Me.target)||!J.current)return;const gt=Date.now()-J.current.time<DC,_t=!B.current;gt&&_t&&(xe.current=!0,He()),J.current=null,B.current=!1},[He,ye]),De=i.useCallback(async(Me,ct)=>{Me.stopPropagation();try{const gt=await Sa(ct,n);a(gt)}catch{r(`Failed to load dependency ${ct}`,"error")}},[a,r]),ot=e.status==="failed",Be=e.paused===!0,we=!!(e.paused&&e.pausedByAgentId),Q=pC(e.priority),_e=Q!==js,lt=Rl(e,f,x),ht=e.column==="triage"&&e.status==="awaiting-approval",mt=e.column==="archived",xt=!o&&!s&&!ot&&!Be&&!lt&&!ht&&(e.column==="in-progress"||th.has(e.status)),Ie=!b&&!s&&!Be&&!v&&!mt,Ue=bC.has(e.column)&&!xt&&!Be&&!s&&l,pt=!!(e.prInfo||e.issueInfo),oe=e.sourceType==="github_import",le=i.useMemo(()=>SC(e),[e.id,e.branch,e.baseBranch]),ge=!!(le.branch||le.baseBranch),Ne=MC(e.sourceMetadata),ue=gC(e),qe=db(e),me=qe?`Created by agent: ${qe}`:"Created by agent",tt=!!(e.assignedAgentId&&q===null),Ct=i.useMemo(()=>{const Me=[];return e.modelProvider&&Me.push(e.modelProvider),e.validatorModelProvider&&!Me.includes(e.validatorModelProvider)&&Me.push(e.validatorModelProvider),e.planningModelProvider&&!Me.includes(e.planningModelProvider)&&Me.push(e.planningModelProvider),Me},[e.modelProvider,e.validatorModelProvider,e.planningModelProvider]),wt=i.useMemo(()=>ab(e,w),[e.steps,e.enabledWorkflowSteps,e.workflowStepResults,w]),$t=wt.total>0&&(e.status==="executing"||e.column==="in-progress");i.useEffect(()=>{if(e.column!=="in-progress"&&e.column!=="in-review")return;const Me=e.status!=null&&nh.has(e.status);if(e.column==="in-progress"){const gt=Gr(e,Date.now()),_t=sh(e,Date.now()),Yt=Jr(e,Date.now());if(gt==null&&_t==null&&Yt==null)return}if(!Me&&e.column==="in-review"){const gt=Gr(e,Date.now()),_t=Jr(e,Date.now());if(gt==null&&_t==null)return}N(Date.now());const ct=window.setInterval(()=>{N(Date.now())},yC);return()=>window.clearInterval(ct)},[e.column,e.status,e.columnMovedAt,e.updatedAt,e.workflowStepResults,e.timedExecutionMs,e.executionStartedAt,e.executionCompletedAt]);const Vt=i.useMemo(()=>{if(!vC.has(e.column))return null;if(e.status!=null&&nh.has(e.status)){const Xt=NC(e,$);if(Xt!=null){const Te=rh(Xt);if(Te){const Je=ub(e,$),Nt=Je==null?null:ih(Je),Ut=Nt?`Execution time ${Te}. Merge phase ${Nt}`:`Execution time ${Te}. Merging`;return{label:Te,title:Ut,ariaLabel:Ut}}}}if(e.column==="in-progress"){const Xt=Gr(e,$)??sh(e,$)??Jr(e,$);if(Xt==null)return null;const Te=ih(Xt);return Te?{label:Te,title:`In progress ${Te}`,ariaLabel:`In progress ${Te}`}:null}const ct=Gr(e,$)??Jr(e,$);if(ct==null)return null;const gt=rh(ct);if(!gt)return null;const _t=jC(e);if(_t==null)return{label:gt,title:`Execution time ${gt}`,ariaLabel:`Execution time ${gt}`};const Yt=new Date(_t).toLocaleString();return{label:gt,title:`Execution time ${gt}. Completed ${Yt}`,ariaLabel:`Execution time ${gt}. Completed ${Yt}`}},[e.column,e.status,e.columnMovedAt,e.timedExecutionMs,e.updatedAt,e.workflowStepResults,e.log,e.executionStartedAt,e.executionCompletedAt,$]);i.useEffect(()=>{if(!pt||!se){ne(e.id);return}return ce(e.id),()=>{ne(e.id)}},[pt,se,ce,e.id,ne]);const Mt=ee.get(`${n??"default"}:${e.id}`),Dt=e.column==="in-progress"||e.column==="in-review",Qt=i.useMemo(()=>e.steps.map(Me=>`${Me.name}:${Me.status}`).join("|"),[e.steps]),{stats:Kt}=aC(e.id,e.column,e.mergeDetails?.commitSha,n,{enabled:se,worktree:e.worktree,stepVersion:Dt?Qt:void 0,pollIntervalMs:Dt?3e4:void 0}),Bt=i.useMemo(()=>eC(e.id,n),[e.id,n]),on=i.useMemo(()=>{const Me=Mt?.prInfo,ct=Mt?.timestamp,gt=Bt?.result?.prInfo,_t=Bt?.timestamp?new Date(Bt.timestamp).toISOString():void 0,Yt=e.prInfo,Xt=e.prInfo?.lastCheckedAt??e.updatedAt;let Te=Pl(Me,ct,Yt,Xt);const Je=ct&&ct>=Xt?ct:Xt;return gt&&_t&&(!Je||_t>Je)&&(Te=gt),Te},[Mt,Bt,e.prInfo,e.updatedAt]),fn=i.useMemo(()=>{const Me=Mt?.issueInfo,ct=Mt?.timestamp,gt=Bt?.result?.issueInfo,_t=Bt?.timestamp?new Date(Bt.timestamp).toISOString():void 0,Yt=e.issueInfo,Xt=e.issueInfo?.lastCheckedAt??e.updatedAt;let Te=Pl(Me,ct,Yt,Xt);const Je=ct&&ct>=Xt?ct:Xt;return gt&&_t&&(!Je||_t>Je)&&(Te=gt),Te},[Mt,Bt,e.issueInfo,e.updatedAt]),Jt=i.useCallback(Me=>{Me?.stopPropagation(),!(!Ue||E)&&(j(!0),U(e.description||""))},[Ue,E,e.description]),an=i.useCallback(()=>{j(!1),U(e.description||"")},[e.description]),zt=i.useCallback(()=>P!==(e.description||""),[P,e.description]),en=i.useCallback(async()=>{if(!(!l||E)){if(!zt()){an();return}R(!0);try{await l(e.id,{description:P.trim()||void 0}),r(`Updated ${e.id}`,"success"),j(!1)}catch(Me){r(`Failed to update ${e.id}: ${Pe(Me)}`,"error")}finally{R(!1)}}},[l,e.id,P,E,zt,an,r]),Zt=i.useCallback(Me=>{Me.key==="Enter"&&!Me.shiftKey?(Me.preventDefault(),en()):Me.key==="Escape"&&(Me.preventDefault(),an())},[en,an]),dn=i.useCallback(()=>{setTimeout(()=>{const Me=document.activeElement;Me===G.current||Me?.closest(".card-editing-content")||(zt()?en():an())},0)},[zt,en,an]),ve=i.useCallback(Me=>{Ue&&(Me.stopPropagation(),Jt(Me))},[Ue,Jt]),ze=i.useCallback(Me=>{Me.stopPropagation(),Jt(Me)},[Jt]),We=i.useCallback(Me=>{U(Me.target.value);const ct=Me.target;ct.style.height="auto",ct.style.height=ct.scrollHeight+"px"},[]),Ze=i.useCallback(Me=>{Me.stopPropagation(),c&&c(e.id).then(()=>{r(`Archived ${e.id}`,"success")}).catch(ct=>{r(`Failed to archive ${e.id}: ${Pe(ct)}`,"error")})},[r,c,e.id]),Ye=i.useCallback(Me=>{Me.stopPropagation(),d&&d(e.id).then(()=>{r(`Unarchived ${e.id}`,"success")}).catch(ct=>{r(`Failed to unarchive ${e.id}: ${Pe(ct)}`,"error")})},[r,d,e.id]),It=i.useCallback(async Me=>{if(Me.stopPropagation(),!(!u||!await re({title:"Delete Task",message:`Delete ${e.id}?`,danger:!0})))try{await u(e.id),r(`Deleted ${e.id}`,"success")}catch(gt){const _t=AC(gt);if(!_t||_t.dependentIds.length===0){r(`Failed to delete ${e.id}: ${Pe(gt)}`,"error");return}const Yt=_t.dependentIds.join(", ");if(!await re({title:"Force Delete Task",message:`${e.id} is a dependency of ${Yt}.
650
-
651
- Delete anyway by removing these dependency references first?`,danger:!0}))return;try{await u(e.id,{removeDependencyReferences:!0}),r(`Deleted ${e.id} after removing dependency references`,"success")}catch(Te){r(`Failed to delete ${e.id}: ${Pe(Te)}`,"error")}}},[r,re,u,e.id]),St=i.useCallback(Me=>{Me.stopPropagation(),h?.(e,"changes")},[e,h]),Ht=i.useCallback(Me=>{Me.stopPropagation(),F(ct=>!ct)},[]),jt=i.useCallback(Me=>{Me.stopPropagation(),e.missionId&&p&&p(e.missionId)},[e.missionId,p]),ae=i.useCallback(Me=>{Me.stopPropagation(),K(ct=>!ct)},[]),Le=i.useCallback(async(Me,ct)=>{if(Me.stopPropagation(),K(!1),!!g)try{const gt=e.steps.some(Xt=>Xt.status!=="pending"),_t=(ct==="todo"||ct==="triage")&&gt;let Yt;if(_t){if(await re({title:"Preserve Progress?",message:"This task has completed steps. Keep progress before moving?",confirmLabel:"Keep Progress",cancelLabel:"Reset Progress"}))Yt={preserveProgress:!0};else if(!await re({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,ct,Yt),r(`Moved ${e.id} to ${ns[ct]}`,"success")}catch(gt){r(`Failed to move ${e.id}: ${Pe(gt)}`,"error")}},[r,re,g,e.id,e.steps]),At=i.useCallback(async Me=>{if(Me.stopPropagation(),!(!m||A)){I(!0);try{await m(e.id)}catch(ct){r(`Failed to retry ${e.id}: ${Pe(ct)}`,"error")}finally{I(!1)}}},[r,A,m,e.id]),Lt=`card${y?" dragging":""}${s?" queued":""}${xt?" agent-active":""}${ot?" failed":""}${Be?" paused":""}${lt?" stuck":""}${ht?" awaiting-approval":""}${k?" file-drop-target":""}${v?" card-editing":""}${E?" card-saving":""}`,Ft=(()=>{if(e.column==="in-progress"){const Me=Kt?.filesChanged,ct=Me==null||Me===0?e.modifiedFiles?.length:void 0,gt=Me!=null&&Me>0?Me:ct;return gt==null||gt===0?null:t.jsxs("button",{type:"button",className:"card-session-files",onClick:St,disabled:!h,children:[t.jsx(bs,{size:12}),t.jsxs("span",{children:[gt," ",gt===1?"file":"files"," changed"]})]})}if(e.column==="in-review"){const Me=Kt?.filesChanged,ct=Me==null||Me===0?e.modifiedFiles?.length:void 0,gt=Me!=null&&Me>0?Me:ct;return gt==null||gt===0?null:t.jsxs("button",{type:"button",className:"card-session-files",onClick:St,disabled:!h,children:[t.jsx(bs,{size:12}),t.jsxs("span",{children:[gt," ",gt===1?"file":"files"," changed"]})]})}if(e.column==="done"){const Me=Kt?.filesChanged,ct=e.mergeDetails?.filesChanged,gt=Me??ct;if(gt!=null&&gt>0)return t.jsxs("button",{type:"button",className:"card-session-files",onClick:St,disabled:!h,children:[t.jsx(bs,{size:12}),t.jsxs("span",{children:[gt," ",gt===1?"file":"files"," changed"]})]});const _t=e.modifiedFiles?.length;if(_t!=null&&_t>0)return t.jsxs("button",{type:"button",className:"card-session-files",onClick:St,disabled:!h,children:[t.jsx(bs,{size:12}),t.jsxs("span",{children:[_t," ",_t===1?"file":"files"," changed"]})]})}return null})();return v?t.jsx("div",{ref:Se,className:Lt,"data-id":e.id,"data-column":e.column,onDoubleClick:ve,children:t.jsxs("div",{className:"card-editing-content",children:[t.jsx("textarea",{ref:G,className:"card-edit-desc-textarea",placeholder:"Task description",value:P,onChange:We,onKeyDown:Zt,onBlur:dn,disabled:E,rows:4}),E&&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:Se,className:Lt,"data-id":e.id,"data-column":e.column,draggable:Ie,onDragStart:Ie?Ce:void 0,onDragEnd:Ie?H:void 0,onDragOver:pe,onDragLeave:Ae,onDrop:Oe,onClick:dt,onTouchStart:Fe,onTouchMove:fe,onTouchEnd:$e,onDoubleClick:ve,children:[t.jsxs("div",{className:"card-header",children:[t.jsx("span",{className:"card-id",children:e.id}),Be&&t.jsx("span",{className:"card-status-badge paused",children:we?"paused by agent":"paused"}),!Be&&e.status&&e.status!=="queued"&&t.jsx("span",{className:`card-status-badge card-status-badge--${e.column}${ht?" awaiting-approval":""}${th.has(e.status)?" pulsing":""}${ot?" failed":""}${lt?" stuck":""}`,children:lt?"Stuck":ht?"Awaiting Approval":wC(e.status)}),lt&&(Be||!e.status||e.status==="queued")&&t.jsx("span",{className:"card-status-badge stuck",children:"Stuck"}),pt&&t.jsx(nb,{prInfo:on,issueInfo:fn}),ue&&t.jsxs("span",{className:"card-agent-created-badge",title:me,"aria-label":me,children:[t.jsx($n,{size:11,"aria-hidden":"true"}),t.jsx("span",{className:"visually-hidden",children:me}),t.jsx("span",{"aria-hidden":"true",children:"Agent"})]}),_e&&t.jsx("span",{className:`card-priority-badge card-priority-badge--${Q}`,children:Q}),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(Qn,{"aria-hidden":"true"}),t.jsx("span",{className:"visually-hidden",children:"Fast mode"})]}),e.missionId&&t.jsxs("span",{className:"card-mission-badge",onClick:jt,title:`Mission: ${M??e.missionId}`,role:p?"button":void 0,tabIndex:p?0:void 0,style:{overflow:"hidden",textOverflow:"ellipsis",whiteSpace:"nowrap"},children:[t.jsx(vs,{size:11}),mC(M??e.missionId)]}),t.jsxs("div",{className:"card-header-actions",children:[Ue&&t.jsx("button",{className:"card-edit-btn",onClick:ze,title:"Edit task","aria-label":"Edit task",children:t.jsx(Ds,{size:12})}),e.column==="triage"&&u&&t.jsx("button",{className:"card-delete-btn",onClick:It,title:"Delete task","aria-label":"Delete task",children:t.jsx(vn,{size:12})}),e.column==="done"&&c&&t.jsx("button",{className:"card-archive-btn",onClick:Ze,title:"Archive task","aria-label":"Archive task",children:"Archive"}),e.column==="archived"&&d&&t.jsx("button",{className:"card-unarchive-btn",onClick:Ye,title:"Unarchive task","aria-label":"Unarchive task",children:"Unarchive"}),e.column==="in-progress"&&g&&t.jsxs("div",{className:"card-send-back",ref:je,children:[t.jsxs("button",{className:"card-send-back-btn",onClick:ae,title:"Send back","aria-label":"Send back","aria-haspopup":"menu","aria-expanded":Z,children:["Send back",t.jsx(rn,{size:10})]}),Z&&t.jsx("div",{className:"card-send-back-menu",role:"menu",children:Ld["in-progress"].filter(Me=>Me!=="in-review").map(Me=>t.jsx("button",{className:"card-send-back-menu-item",role:"menuitem",onClick:ct=>Le(ct,Me),children:ns[Me]},Me))})]}),e.column==="in-review"&&g&&t.jsxs("div",{className:"card-send-back",ref:je,children:[t.jsxs("button",{className:"card-send-back-btn",onClick:ae,title:"Move task","aria-label":"Move task","aria-haspopup":"menu","aria-expanded":Z,children:["Move",t.jsx(rn,{size:10})]}),Z&&t.jsx("div",{className:"card-send-back-menu",role:"menu",children:Ld["in-review"].map(Me=>t.jsx("button",{className:"card-send-back-menu-item",role:"menuitem",onClick:ct=>Le(ct,Me),children:Me==="done"?"Done (no merge)":ns[Me]},Me))})]}),e.size&&t.jsx("span",{className:`card-size-badge size-${e.size.toLowerCase()}`,children:e.size})]})]}),ot&&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}),m&&t.jsxs("button",{type:"button",className:"btn btn-sm card-error-retry-btn",onClick:At,disabled:A,children:[t.jsx(Vw,{size:12}),A?"Retrying…":"Retry"]})]}),t.jsx("div",{className:"card-title",title:e.title||e.description||void 0,children:dh(e.title,ch)||dh(e.description,ch)||e.id}),ge&&t.jsxs("div",{className:"card-branch-row","aria-label":"Branch metadata",children:[le.branch&&t.jsxs("span",{className:"card-branch-chip",title:le.branch,children:[t.jsx("span",{className:"card-branch-label",children:"Branch"}),t.jsx("span",{className:"card-branch-value",children:le.branch})]}),le.baseBranch&&t.jsxs("span",{className:"card-branch-chip",title:le.baseBranch,children:[t.jsx("span",{className:"card-branch-label",children:"Base"}),t.jsx("span",{className:"card-branch-value",children:le.baseBranch})]})]}),$t&&(()=>{const Me=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:`${Me}%`,backgroundColor:xC[e.column]}})}),t.jsxs("span",{className:"card-progress-label",children:[wt.completed,"/",wt.total]})]}),t.jsxs("button",{type:"button",className:"card-steps-toggle",onClick:Ht,"aria-expanded":L,"aria-label":L?"Hide steps":"Show steps",children:[t.jsxs("span",{children:[wt.total," step",wt.total===1?"":"s"]}),t.jsx(rn,{size:14,className:`card-steps-toggle-icon${L?" expanded":""}`})]}),L&&t.jsx("div",{className:"card-steps-list",children:wt.items.map(ct=>{const gt=ct.source==="workflow"&&ct.status==="failed";return t.jsxs("div",{className:"card-step-item",children:[t.jsx("span",{className:`card-step-dot card-step-dot--${ct.status}${gt?" card-step-dot--workflow-failed":""}`,"aria-hidden":"true"}),t.jsx("span",{className:`card-step-name${ct.status==="done"?" completed":""}`,children:ct.name}),ct.source==="workflow"&&t.jsx("span",{className:`card-step-workflow-badge card-step-workflow-badge--${ct.phase}`,title:"Workflow check",children:"workflow"})]},ct.id)})})]})})(),(Ft||Vt||oe)&&t.jsxs("div",{className:"card-footer-row",children:[Ft,oe&&t.jsx("span",{className:"card-source-provenance",title:Ne?`Imported from GitHub: ${Ne}`:"Imported from GitHub","aria-label":"Imported from GitHub",children:t.jsx(Sn,{provider:"github",size:"sm"})}),Vt&&t.jsxs("span",{className:"card-time-indicator",title:Vt.title,"aria-label":Vt.ariaLabel,children:[t.jsx(Hi,{size:12}),t.jsx("span",{children:Vt.label})]})]}),(e.dependencies&&e.dependencies.length>0||s||e.status==="queued"||e.blockedBy)&&t.jsxs("div",{className:"card-meta",children:[e.dependencies&&e.dependencies.length>0&&t.jsx("div",{className:"card-dep-list",children:e.dependencies.map(Me=>t.jsxs("span",{className:"card-dep-badge clickable",onClick:ct=>void De(ct,Me),title:`Click to view ${Me}`,children:[t.jsx(cr,{size:12,style:{verticalAlign:"middle"}})," ",Me]},Me))}),e.blockedBy&&t.jsxs("span",{className:"card-scope-badge","data-tooltip":`Blocked by ${e.blockedBy} (file overlap)`,children:[t.jsx(ja,{size:12,style:{verticalAlign:"middle"}})," ",e.blockedBy]}),(s||e.status==="queued")&&e.column!=="in-progress"&&t.jsxs("span",{className:"queued-badge",children:[t.jsx(Hi,{size:12,style:{verticalAlign:"middle"}})," Queued"]})]}),(e.assignedAgentId||Ct.length>0)&&t.jsxs("div",{className:"card-agent-row",children:[Ct.length>0&&t.jsx("span",{className:"card-provider-icons","data-testid":"card-provider-icons",children:Ct.map(Me=>t.jsx(Sn,{provider:Me,size:"sm"},Me))}),e.assignedAgentId&&t.jsxs("span",{className:`card-agent-badge${tt?" card-agent-badge--loading":""}`,title:`Assigned to ${q??e.assignedAgentId}`,children:[t.jsx($n,{size:11}),t.jsx("span",{className:"card-agent-badge-text","aria-hidden":"true",children:fC(q??e.assignedAgentId,15)}),t.jsxs("span",{className:"visually-hidden",children:["Assigned to ",q??e.assignedAgentId]})]})]}),t.jsx(ta,{slotId:"task-card-badge",projectId:n})]})}const lh=10,DC=300,ch=140;function dh(e,n){return e?e.length>n?e.slice(0,n)+"…":e:""}const ho=i.memo($C,TC);ho.displayName="TaskCard";function LC({label:e,activeTasks:n,queuedTasks:s,projectId:a,onOpenDetail:r,addToast:o,globalPaused:l,onUpdateTask:c,onRetryTask:d,onOpenDetailWithTab:u,taskStuckTimeoutMs:m,onOpenMission:h,lastFetchTimeMs:f,workflowStepNameLookup:p}){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(oy,{size:14}):t.jsx(Us,{size:14})}),t.jsx("span",{className:"worktree-label",children:e})]}),n.map(g=>t.jsx(ho,{task:g,projectId:a,onOpenDetail:r,addToast:o,globalPaused:l,onUpdateTask:c,onRetryTask:d,onOpenDetailWithTab:u,taskStuckTimeoutMs:m,onOpenMission:h,lastFetchTimeMs:f,workflowStepNameLookup:p},g.id)),s.map(g=>t.jsx(ho,{task:g,projectId:a,queued:!0,onOpenDetail:r,addToast:o,globalPaused:l,onUpdateTask:c,onRetryTask:d,onOpenDetailWithTab:u,taskStuckTimeoutMs:m,onOpenMission:h,lastFetchTimeMs:f,workflowStepNameLookup:p},g.id))]})}const mb=i.memo(LC);mb.displayName="WorktreeGroup";function uh(e){return e.toLowerCase().replace(/[-_./]/g,"")}function OC(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 zC(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 m=e[c-1]===n[u-1]?0:1;d[u]=Math.min(l[u]+1,d[u-1]+1,l[u-1]+m),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 FC(e,n){const s=uh(e),a=uh(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&&OC(s,o)||s.length>=4&&zC(s,o,1))return!0;return!1}function UC(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=>FC(o,r))})}function ys({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:m,noChangeValue:h,noChangeLabel:f="No change"}){const[p,g]=i.useState(!1),[x,w]=i.useState(""),[b,y]=i.useState(0),[S,k]=i.useState(null),[C,v]=i.useState(null),j=i.useRef(null),P=i.useRef(null),U=i.useRef(null),E=i.useRef(null),R=i.useRef(null),L=i.useMemo(()=>UC(e,x),[e,x]),F=i.useMemo(()=>L.reduce((ne,re)=>((ne[re.provider]??=[]).push(re),ne),{}),[L]),M=i.useMemo(()=>{const ne=[];for(const re of u){const J=re.indexOf("/");if(J===-1)continue;const B=re.slice(0,J),ye=re.slice(J+1),Ce=L.find(H=>H.provider===B&&H.id===ye);Ce&&ne.push({model:Ce,fullId:re})}return ne},[u,L]),O=i.useMemo(()=>{const ne=Object.entries(F),re=new Set(c);return ne.sort(([J],[B])=>{const ye=re.has(J),Ce=re.has(B);if(ye&&!Ce)return-1;if(!ye&&Ce)return 1;if(ye&&Ce){const H=c.indexOf(J),ke=c.indexOf(B);if(H!==ke)return H-ke}return J.localeCompare(B)})},[F,c]),q=typeof h=="string"&&h.length>0,te=i.useMemo(()=>{if(!n||q&&n===h)return null;const ne=n.indexOf("/");return ne===-1?null:n.slice(0,ne)},[q,h,n]),Z=i.useMemo(()=>{const ne=[];return q&&ne.push({type:"no-change",value:h,label:f}),ne.push({type:"default",value:"",label:"Use default"}),ne},[q,f,h]),K=i.useMemo(()=>{const ne=[...Z];for(const{model:re,fullId:J}of M)ne.push({type:"favorite",value:J,label:re.name,provider:re.provider});return O.forEach(([re,J])=>{ne.push({type:"provider",value:`__group_${re}`,label:re,provider:re}),J.forEach(B=>{ne.push({type:"model",value:`${B.provider}/${B.id}`,label:B.name,provider:B.provider})})}),ne},[M,O,Z]),A=i.useMemo(()=>{if(q&&n===h)return f;if(!n)return"Use default";const ne=n.indexOf("/");if(ne===-1)return n;const re=n.slice(0,ne),J=n.slice(ne+1);return e.find(ye=>ye.provider===re&&ye.id===J)?.name||n},[q,f,h,n,e]),I=i.useMemo(()=>K.findIndex(ne=>ne.value===n),[K,n]),$=i.useCallback(()=>{const ne=window.visualViewport;return ne&&ne.height>0&&ne.width>0?{width:ne.width,height:ne.height,offsetTop:ne.offsetTop,offsetLeft:ne.offsetLeft}:{width:window.innerWidth,height:window.innerHeight,offsetTop:0,offsetLeft:0}},[]),N=i.useCallback(()=>{const{height:ne}=$(),re=typeof window.matchMedia=="function",J=re?window.matchMedia("(max-width: 640px)").matches:!1,B=re?window.matchMedia("(max-width: 768px)").matches:!1;return ne<=0?320:J?Math.min(ne*.6,360):B?Math.min(ne*.7,420):320},[$]),G=i.useCallback(()=>{const ne=P.current;if(!ne)return;const re=ne.getBoundingClientRect(),{width:J,height:B,offsetTop:ye,offsetLeft:Ce}=$(),H=16,ke=16,pe=4,Ae=N(),Oe=re.bottom-ye,He=re.top-ye,dt=re.left-Ce,Fe=B-Oe,fe=He,$e=Math.max(Fe-ke-pe,160),De=Math.max(fe-ke-pe,160),ot=Fe<Ae&&fe>Fe,Be=Math.max(Math.min(ot?De:$e,Ae),160),we=Math.min(re.width,J-H*2),Q=Math.min(Math.max(dt,H),J-H-we)+Ce,_e=ot?Math.max(ke+ye,He-Be-pe+ye):Math.min(Oe+pe+ye,B+ye-ke-Be);k({top:_e,left:Q,width:we,maxHeight:Be})},[$,N]);i.useEffect(()=>{v(document.body)},[]);const xe=i.useRef(!1);i.useEffect(()=>{if(!p){xe.current=!1;return}if(xe.current||K.length===0)return;const ne=K.findIndex((re,J)=>J>=(I>=0?I:0)&&re.type!=="provider");y(ne>=0?ne:0),xe.current=!0},[p,K,I]),i.useEffect(()=>{p&&xe.current&&(y(0),R.current&&(R.current.scrollTop=0))},[x,p]),i.useEffect(()=>{if(!p)return;G();const ne=requestAnimationFrame(()=>E.current?.focus());return()=>cancelAnimationFrame(ne)},[p,G]),i.useEffect(()=>{if(!p)return;const ne=()=>G();window.addEventListener("resize",ne),window.addEventListener("scroll",ne,!0);const re=window.visualViewport;return re&&(re.addEventListener("resize",ne),re.addEventListener("scroll",ne)),()=>{window.removeEventListener("resize",ne),window.removeEventListener("scroll",ne,!0),re&&(re.removeEventListener("resize",ne),re.removeEventListener("scroll",ne))}},[p,G]),i.useEffect(()=>{if(!p)return;const ne=re=>{const J=re.target,B=j.current?.contains(J),ye=U.current?.contains(J);!B&&!ye&&(g(!1),w(""))};return document.addEventListener("mousedown",ne),()=>document.removeEventListener("mousedown",ne)},[p]);const Se=i.useCallback(ne=>{switch(ne.key){case"ArrowDown":if(ne.preventDefault(),!p)g(!0);else{let re=b;for(let J=1;J<=K.length;J++){const B=(b+J)%K.length;if(K[B]?.type!=="provider"){re=B;break}}y(re)}break;case"ArrowUp":if(ne.preventDefault(),p){let re=b;for(let J=1;J<=K.length;J++){const B=(b-J+K.length)%K.length;if(K[B]?.type!=="provider"){re=B;break}}y(re)}break;case"Enter":if(ne.preventDefault(),p){const re=K[b];re&&re.type!=="provider"&&re.type!=="favorite"&&(s(re.value),g(!1),w(""))}else g(!0);break;case"Escape":ne.preventDefault(),g(!1),w("");break;case"Tab":p&&(g(!1),w(""));break}},[p,b,K,s]),je=i.useCallback(ne=>{s(ne),g(!1),w("")},[s]),se=i.useCallback(()=>{w(""),E.current?.focus()},[]),Ve=i.useCallback(()=>{r||g(ne=>!ne)},[r]);i.useEffect(()=>{if(p&&R.current){const ne=R.current.querySelector(`[data-index="${b}"]`);ne&&typeof ne.scrollIntoView=="function"&&ne.scrollIntoView({block:"nearest"})}},[b,p]);const ee=x.length>0,ce=p&&S?t.jsxs("div",{ref:U,className:"model-combobox-dropdown model-combobox-dropdown--portal",role:"listbox","data-testid":"model-combobox-portal",onKeyDown:Se,style:{top:`${S.top}px`,left:`${S.left}px`,width:`${S.width}px`,maxHeight:`${S.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:x,onChange:ne=>w(ne.target.value),onClick:ne=>ne.stopPropagation()}),ee&&t.jsx("button",{type:"button",className:"model-combobox-clear",onClick:se,"aria-label":"Clear filter",children:"×"})]}),t.jsxs("div",{className:"model-combobox-results-count",children:[L.length," model",L.length!==1?"s":""]}),t.jsxs("div",{ref:R,className:"model-combobox-list",children:[Z.map((ne,re)=>t.jsx("div",{"data-index":re,className:`model-combobox-option ${b===re?"model-combobox-option--highlighted":""} ${n===ne.value?"model-combobox-option--selected":""}`,onClick:()=>je(ne.value),onMouseEnter:()=>y(re),role:"option","aria-selected":n===ne.value,children:t.jsx("span",{className:"model-combobox-option-text model-combobox-option-text--default",children:ne.label})},`${ne.type}-${ne.value}`)),M.length>0&&t.jsxs(t.Fragment,{children:[t.jsx("div",{className:"model-combobox-divider"}),M.map(({model:ne,fullId:re},J)=>{const B=J+Z.length,ye=b===B,Ce=n===re;return t.jsxs("div",{"data-index":B,className:`model-combobox-option model-combobox-option--favorite ${ye?"model-combobox-option--highlighted":""} ${Ce?"model-combobox-option--selected":""}`,onClick:()=>je(re),onMouseEnter:()=>y(B),role:"option","aria-selected":Ce,children:[t.jsxs("span",{className:"model-combobox-option-main",children:[t.jsx("span",{className:"model-combobox-option-icon",children:t.jsx(Sn,{provider:ne.provider,size:"sm"})}),t.jsx("span",{className:"model-combobox-option-text",children:ne.name})]}),t.jsx("span",{className:"model-combobox-option-id",children:ne.id}),m&&t.jsx("button",{type:"button",className:"model-combobox-option-favorite model-combobox-option-favorite--active",onClick:H=>{H.stopPropagation(),m(re)},title:"Remove from favorites","aria-label":`Remove ${ne.name} from favorites`,children:"★"})]},re)}),t.jsx("div",{className:"model-combobox-divider"})]}),O.map(([ne,re])=>{const J=K.findIndex(Ce=>Ce.value===`__group_${ne}`),B=c.includes(ne),ye=re.filter(Ce=>{const H=`${Ce.provider}/${Ce.id}`;return!u.includes(H)});return ye.length===0?null:t.jsxs("div",{className:"model-combobox-group",children:[t.jsxs("div",{className:"model-combobox-optgroup","data-index":J,children:[t.jsx(Sn,{provider:ne,size:"sm"}),t.jsx("span",{className:"model-combobox-optgroup-text",children:ne}),d&&t.jsx("button",{type:"button",className:`model-combobox-optgroup-favorite ${B?"model-combobox-optgroup-favorite--active":""}`,onClick:Ce=>{Ce.stopPropagation(),d(ne)},title:B?"Remove from favorites":"Add to favorites","aria-label":B?`Remove ${ne} from favorites`:`Add ${ne} to favorites`,children:"★"})]}),ye.map(Ce=>{const H=`${Ce.provider}/${Ce.id}`,ke=K.findIndex(He=>He.value===H),pe=b===ke,Ae=n===H,Oe=u.includes(H);return t.jsxs("div",{"data-index":ke,className:`model-combobox-option ${pe?"model-combobox-option--highlighted":""} ${Ae?"model-combobox-option--selected":""}`,onClick:()=>je(H),onMouseEnter:()=>y(ke),role:"option","aria-selected":Ae,children:[t.jsx("span",{className:"model-combobox-option-text",children:Ce.name}),t.jsx("span",{className:"model-combobox-option-id",children:Ce.id}),m&&t.jsx("button",{type:"button",className:`model-combobox-option-favorite ${Oe?"model-combobox-option-favorite--active":""}`,onClick:He=>{He.stopPropagation(),m(H)},title:Oe?"Remove from favorites":"Add to favorites","aria-label":Oe?`Remove ${Ce.name} from favorites`:`Add ${Ce.name} to favorites`,children:Oe?"★":"☆"})]},H)})]},ne)}),L.length===0&&ee&&t.jsxs("div",{className:"model-combobox-no-results",children:["No models match '",x,"'"]})]})]}):null;return t.jsxs(t.Fragment,{children:[t.jsx("div",{ref:j,className:"model-combobox",onKeyDown:Se,children:t.jsxs("button",{ref:P,type:"button",id:o,className:"model-combobox-trigger",onClick:Ve,disabled:r,"aria-haspopup":"listbox","aria-expanded":p,"aria-label":l,children:[te&&t.jsx("span",{className:"model-combobox-trigger-icon",children:t.jsx(Sn,{provider:te,size:"sm"})}),t.jsx("span",{className:"model-combobox-trigger-text",children:A||a}),t.jsx("span",{className:"model-combobox-trigger-arrow",children:"▼"})]})}),C&&ce?va.createPortal(ce,C):null]})}function Nu(e,n){return typeof n!="string"||n.length===0?e:`kb:${n}:${e}`}function An(e,n){if(typeof window>"u")return null;const s=window.localStorage?.getItem;return typeof s!="function"?null:s.call(window.localStorage,Nu(e,n))}function ss(e,n,s){if(typeof window>"u")return;const a=window.localStorage?.setItem;typeof a=="function"&&a.call(window.localStorage,Nu(e,s),n)}function pr(e,n){if(typeof window>"u")return;const s=window.localStorage?.removeItem;typeof s=="function"&&s.call(window.localStorage,Nu(e,n))}const BC=1e4,HC=1e3;function nc(){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 _l();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 k=await _l();b||(n(k),o(null))}catch(k){b||o(k instanceof Error?k.message:"Failed to fetch nodes")}finally{b||a(!1)}}y();const S=()=>{if(document.visibilityState!=="visible")return;const k=Date.now();k-c.current<HC||(c.current=k,d())};return document.addEventListener("visibilitychange",S),()=>{b=!0,document.removeEventListener("visibilitychange",S)}},[d]),i.useEffect(()=>{if(!s)return l.current=setInterval(()=>{d()},BC),()=>{l.current&&(clearInterval(l.current),l.current=null)}},[s,d]);const u=i.useCallback(async b=>{const{projectMappings:y,...S}=b,k=await gS(S);if(y.length>0)try{await t0(k.id,y)}catch(C){const v=C instanceof Error?C.message:"Failed to persist project mappings";let j="";try{await jm(k.id)}catch(P){j=P instanceof Error?P.message:"Failed to unregister node after mapping failure"}throw await d(),j?new Error(`${v}. Cleanup also failed: ${j}`):new Error(v)}return await d(),k},[d]),m=i.useCallback(async(b,y)=>{const S=await xS(b,y);return n(k=>k.map(C=>C.id===b?S:C)),S},[]),h=i.useCallback(async b=>{await jm(b),n(y=>y.filter(S=>S.id!==b))},[]),f=i.useCallback(async b=>{const y=await kS(b);n(S=>S.map(k=>k.id===b?{...k,status:y.status,updatedAt:y.checkedAt}:k))},[]),p=i.useCallback(b=>vS(b),[]),g=i.useCallback(async(b,y)=>{const S=await yS(b,y);return n(k=>k.map(C=>C.id===b?{...C,dockerConfig:S}:C)),S},[]),x=i.useCallback(async b=>{const y=await wS(b);return"persistedVersion"in y?y:{persistedVersion:0,deployedVersion:null,needsRecreate:!1}},[]),w=i.useCallback(async b=>bS(b),[]);return{nodes:e,loading:s,error:r,refresh:d,register:u,update:m,unregister:h,healthCheck:f,fetchDockerConfig:p,patchDockerConfig:g,fetchDockerDiff:x,discoverRemoteProjects:w}}const Ir="kb-quick-entry-text",qC=["image/png","image/jpeg","image/gif","image/webp"];function VC(e){return e==="online"?"Online":e==="connecting"?"Connecting":e==="error"?"Error":"Offline"}function Cc(e,n){return e&&n?`${e}/${n}`:""}function Ec(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 hb({onCreate:e,addToast:n,tasks:s=[],availableModels:a,onPlanningMode:r,onSubtaskBreakdown:o,projectId:l,autoExpand:c=!0,favoriteProviders:d,favoriteModels:u,onToggleFavorite:m,onToggleModelFavorite:h}){const[f,p]=i.useState(()=>typeof window<"u"&&An(Ir,l)||""),[g,x]=i.useState(!1),[w,b]=i.useState(!1),[y,S]=i.useState(!1),k=i.useRef(null),C=i.useRef(null),v=i.useRef(!1),j=i.useRef(l),[P,U]=i.useState([]),E=i.useRef([]),[R,L]=i.useState([]),[F,M]=i.useState(!1),[O,q]=i.useState(""),[te,Z]=i.useState(null),[K,A]=i.useState([]),[I,$]=i.useState(void 0),[N,G]=i.useState(!1),[xe,Se]=i.useState(!1),[je,se]=i.useState(!1),[Ve,ee]=i.useState(!1),[ce,ne]=i.useState(!1),[re,J]=i.useState(null),[B,ye]=i.useState(void 0),[Ce,H]=i.useState(void 0),[ke,pe]=i.useState(void 0),[Ae,Oe]=i.useState(void 0),[He,dt]=i.useState(void 0),[Fe,fe]=i.useState(void 0),$e=i.useRef(null),De=i.useRef(null),ot=i.useRef(null),Be=i.useRef(null),we=i.useRef(null),Q=i.useRef(null),_e=i.useRef(null),lt=i.useRef(null),[ht,mt]=i.useState(null),[xt,Ie]=i.useState(null),[Ue,pt]=i.useState(null),[oe,le]=i.useState(null),ge=i.useRef(null),Ne=i.useRef(null),[ue,qe]=i.useState(null),[me]=i.useState(()=>typeof document<"u"?document.body:null),[tt,Ct]=i.useState(!1),[wt,$t]=i.useState(null),[Vt,Mt]=i.useState(a??[]),[Dt,Qt]=i.useState([]),[Kt,Bt]=i.useState([]),[on,fn]=i.useState(null),[Jt,an]=i.useState(void 0),[zt,en]=i.useState(!1),[Zt,dn]=i.useState(js),[ve,ze]=i.useState(void 0),{nodes:We}=nc(),[Ze,Ye]=i.useState(!1),[It,St]=i.useState(!1),Ht=i.useRef(null),jt=i.useRef(null),[ae,Le]=i.useState(null),At=d??Dt,Lt=u??Kt,Ft=!e;i.useEffect(()=>{if(a)Mt(a),Ct(!1),$t(null);else{let X=!1;return Ct(!0),$t(null),Os().then(_=>{X||(Mt(_.models),d||Qt(_.favoriteProviders),u||Bt(_.favoriteModels))}).catch(_=>{X||$t(Pe(_)||"Failed to load models")}).finally(()=>{X||Ct(!1)}),Zl(l).then(_=>{X||fn(_)}).catch(()=>{}),()=>{X=!0}}},[a,d,u,l]);const Me=Cc(B,Ce),ct=Cc(ke,Ae),gt=Cc(He,Fe),_t=!!(B&&Ce),Yt=!!(ke&&Ae),Xt=!!(He&&Fe),Te=Number(_t)+Number(Yt)+Number(Xt),Je=Jt?on?.modelPresets?.find(X=>X.id===Jt)?.name??"Models":Te>0?`${Te} model${Te===1?"":"s"}`:"Models",Nt=i.useCallback((X,_)=>{if(!X||!_)return"Using default";const de=Vt.find(D=>D.provider===X&&D.id===_);return de?`${de.provider}/${de.id}`:`${X}/${_}`},[Vt]);i.useEffect(()=>{p(An(Ir,l)||"")},[l]),i.useEffect(()=>{typeof window<"u"&&ss(Ir,f,l)},[f,l]),i.useEffect(()=>{j.current!==l&&(j.current=l,A([]),$(void 0),Z(null),G(!1),mt(null))},[l]),i.useEffect(()=>{typeof window<"u"&&localStorage.removeItem("kb-quick-entry-expanded")},[]),i.useEffect(()=>{E.current=P},[P]),i.useEffect(()=>()=>{E.current.forEach(X=>URL.revokeObjectURL(X.previewUrl))},[]);const Ut=i.useCallback(()=>{const X=k.current;if(!X)return;X.style.height="auto";const _=Math.min(X.scrollHeight,200);X.style.height=`${_}px`},[]);i.useEffect(()=>{w&&Ut()},[f,w,Ut]),i.useEffect(()=>{if(!g&&f===""&&k.current){const X=setTimeout(()=>{k.current?.focus()},0);return()=>clearTimeout(X)}},[g,f]),i.useEffect(()=>{F||q("")},[F]),i.useEffect(()=>{if(!Ze)return;const X=_=>{const de=_.target,D=Ht.current?.contains(de),Y=jt.current?.contains(de);!D&&!Y&&Ye(!1)};return document.addEventListener("mousedown",X),()=>document.removeEventListener("mousedown",X)},[Ze]),i.useEffect(()=>{if(!ce)return;const X=_=>{const de=_.target,D=$e.current?.contains(de),Y=De.current?.contains(de),Ee=de instanceof Element&&de.closest?.(".model-combobox-dropdown--portal")!=null;!D&&!Y&&!Ee&&(ne(!1),J(null))};return document.addEventListener("mousedown",X),()=>document.removeEventListener("mousedown",X)},[ce]),i.useEffect(()=>{if(!xe)return;const X=_=>{const de=_.target;we.current?.contains(de)||Q.current?.contains(de)||(Se(!1),Ie(null))};return document.addEventListener("mousedown",X),()=>document.removeEventListener("mousedown",X)},[xe]),i.useEffect(()=>{if(!N)return;const X=_=>{const de=_.target;ot.current?.contains(de)||Be.current?.contains(de)||(G(!1),mt(null))};return document.addEventListener("mousedown",X),()=>document.removeEventListener("mousedown",X)},[N]),i.useEffect(()=>{if(!je)return;const X=_=>{const de=_.target;_e.current?.contains(de)||lt.current?.contains(de)||(se(!1),pt(null))};return document.addEventListener("mousedown",X),()=>document.removeEventListener("mousedown",X)},[je]);const tn=i.useCallback(()=>{P.forEach(X=>URL.revokeObjectURL(X.previewUrl)),U([]),C.current&&(C.current.value=""),p(""),L([]),Z(null),G(!1),mt(null),Se(!1),Ie(null),se(!1),pt(null),ye(void 0),H(void 0),pe(void 0),Oe(void 0),dt(void 0),fe(void 0),an(void 0),en(!1),dn(js),ze(void 0),M(!1),ne(!1),le(null),J(null),Ye(!1),St(!1),b(!1),S(!1),v.current=!0,k.current&&(k.current.style.height="auto"),typeof window<"u"&&pr(Ir,l)},[P,l]),Xn=i.useCallback(X=>{if(!X||X.length===0)return;const _=[];for(let de=0;de<X.length;de++){const D=X[de];qC.includes(D.type)&&_.push({file:D,previewUrl:URL.createObjectURL(D)})}_.length>0&&U(de=>[...de,..._])},[]),be=i.useCallback(X=>{g||Xn(X.clipboardData?.files)},[Xn,g]),it=i.useCallback(X=>{U(_=>{const de=_[X];return de&&URL.revokeObjectURL(de.previewUrl),_.filter((D,Y)=>Y!==X)})},[]),rt=i.useCallback(async()=>{const X=f.trim();if(!X||g||!e)return;const _=f;x(!0),p("");try{const de=await e({description:X,column:"triage",dependencies:R.length?R:void 0,...te?{assignedAgentId:te}:{},modelPresetId:Jt,modelProvider:_t?B:void 0,modelId:_t?Ce:void 0,validatorModelProvider:Yt?ke:void 0,validatorModelId:Yt?Ae:void 0,planningModelProvider:Xt?He:void 0,planningModelId:Xt?Fe:void 0,...zt?{executionMode:"fast"}:{},priority:Zt,nodeId:ve});if(de&&P.length>0){const D=[];for(const Y of P)try{await ec(de.id,Y.file,l)}catch{D.push(Y.file.name)}D.length>0&&n(`Failed to upload: ${D.join(", ")}`,"error")}tn()}catch(de){p(_),n(Pe(de)||"Failed to create task","error")}finally{x(!1)}},[f,g,e,R,te,_t,B,Ce,Yt,ke,Ae,Xt,He,Fe,P,l,n,tn,zt,Zt,ve]),at=i.useCallback(X=>{if(X.key==="Enter"){if(X.shiftKey&&w)return;X.preventDefault(),rt()}else if(X.key==="Escape"){if(X.preventDefault(),re){J(null);return}if(ce){ne(!1),le(null);return}if(F){M(!1);return}if(Ze){Ye(!1);return}if(xe){Se(!1),Ie(null);return}if(je){se(!1),pt(null);return}if(N){G(!1),mt(null);return}f.trim()&&(p(""),k.current&&(k.current.style.height="auto"),typeof window<"u"&&pr(Ir,l)),b(!1),S(!1),k.current?.blur()}},[rt,f,w,F,N,xe,ce,re,Ze,je,l,S]),ut=i.useCallback(()=>{v.current&&(v.current=!1)},[]),vt=i.useCallback(()=>{c&&b(!0)},[c]),ie=i.useCallback(X=>{L(_=>_.includes(X)?_.filter(de=>de!==X):[..._,X])},[]),st=i.useCallback(()=>{const X=window.visualViewport;return X&&X.width>0&&X.height>0?{width:X.width,height:X.height,offsetTop:X.offsetTop,offsetLeft:X.offsetLeft}:{width:window.innerWidth,height:window.innerHeight,offsetTop:0,offsetLeft:0}},[]),Gt=i.useCallback(()=>{const X=$e.current;if(!X)return;const _=X.getBoundingClientRect(),{width:de,height:D,offsetTop:Y,offsetLeft:Ee}=st(),Ge=16,kt=16,Tt=4,Pt=de<=768,ln=Math.min(Pt?D*.6:D*.5,360),ts=Math.max(_.width*1.35,320),Rn=Pt?Math.min(de-Ge*2,360):ts,Fn=Math.min(Rn,Math.max(de-Ge*2,240)),Un=_.top-Y,gs=_.bottom-Y,Ln=_.left-Ee,Vn=D-gs,Wn=Un,Kn=Math.max(Vn-kt-Tt,160),Bn=Math.max(Wn-kt-Tt,160),Nn=Vn<ln&&Wn>Vn,Gn=Math.max(Math.min(Nn?Bn:Kn,ln),160),ds=Math.min(Math.max(Ln,Ge),de-Ge-Fn)+Ee,Ts=Nn?Math.max(kt+Y,Un-Gn-Tt+Y):Math.min(gs+Tt+Y,D+Y-kt-Gn);le({top:Ts,left:ds,width:Fn,maxHeight:Gn})},[st]),Cn=i.useCallback(()=>{const X=Ht.current?.querySelector(".refine-button");if(!X)return;const _=X.getBoundingClientRect(),{width:de,height:D,offsetTop:Y,offsetLeft:Ee}=st(),Ge=8,kt=12,Tt=4,Pt=Math.min(200,Math.max(D-kt*2,160)),ln=Math.min(200,de-Ge*2),ts=_.top-Y,Rn=_.bottom-Y,Fn=_.left-Ee,Un=D-Rn,gs=ts,Ln=Un<Pt&&gs>Un,Vn=Math.min(Math.max(Fn,Ge),de-Ge-ln)+Ee,Wn=Ln?Math.max(kt+Y,ts-Pt-Tt+Y):Math.min(Rn+Tt+Y,D+Y-kt-Pt);Le({top:Wn,left:Vn})},[st]),fs=i.useCallback(()=>{const X=ge.current;if(!X)return;const _=X.getBoundingClientRect(),{width:de,height:D,offsetTop:Y,offsetLeft:Ee}=st(),Ge=16,kt=16,Tt=4,Pt=de<=768,ln=Math.min(Pt?D*.6:D*.5,320),ts=Pt?Math.min(de-Ge*2,360):Math.max(_.width,280),Rn=Math.min(ts,Math.max(de-Ge*2,240)),Fn=_.top-Y,Un=_.bottom-Y,gs=_.left-Ee,Ln=D-Un,Vn=Fn,Wn=Math.max(Ln-kt-Tt,200),Kn=Math.max(Vn-kt-Tt,200),Bn=Ln<ln&&Vn>Ln,Nn=Math.max(Math.min(Bn?Kn:Wn,ln),200),Gn=Math.min(Math.max(gs,Ge),de-Ge-Rn)+Ee,ds=Bn?Math.max(kt+Y,Fn-Nn-Tt+Y):Math.min(Un+Tt+Y,D+Y-kt-Nn);qe({top:ds,left:Gn,width:Rn,maxHeight:Nn})},[st]),On=i.useCallback(()=>{const X=ot.current?.querySelector("button");if(!X)return;const _=X.getBoundingClientRect(),{width:de,height:D,offsetTop:Y,offsetLeft:Ee}=st(),Ge=16,kt=16,Tt=4,Pt=de<=768,ln=Math.min(Pt?D*.6:D*.5,320),ts=Pt?Math.min(de-Ge*2,280):Math.max(_.width,240),Rn=Math.min(ts,Math.max(de-Ge*2,200)),Fn=_.top-Y,Un=_.bottom-Y,gs=_.left-Ee,Ln=D-Un,Vn=Fn,Wn=Math.max(Ln-kt-Tt,160),Kn=Math.max(Vn-kt-Tt,160),Bn=Ln<ln&&Vn>Ln,Nn=Math.max(Math.min(Bn?Kn:Wn,ln),160),Gn=Math.min(Math.max(gs,Ge),de-Ge-Rn)+Ee,ds=Bn?Math.max(kt+Y,Fn-Nn-Tt+Y):Math.min(Un+Tt+Y,D+Y-kt-Nn);mt({top:ds,left:Gn,width:Rn,maxHeight:Nn})},[st]),jn=i.useCallback(()=>{const X=we.current?.querySelector("button");if(!X)return;const _=X.getBoundingClientRect(),{width:de,height:D,offsetTop:Y,offsetLeft:Ee}=st(),Ge=16,kt=16,Tt=4,Pt=de<=768,ln=Math.min(Pt?D*.6:D*.5,320),ts=Pt?Math.min(de-Ge*2,280):Math.max(_.width,240),Rn=Math.min(ts,Math.max(de-Ge*2,200)),Fn=_.top-Y,Un=_.bottom-Y,gs=_.left-Ee,Ln=D-Un,Vn=Fn,Wn=Math.max(Ln-kt-Tt,160),Kn=Math.max(Vn-kt-Tt,160),Bn=Ln<ln&&Vn>Ln,Nn=Math.max(Math.min(Bn?Kn:Wn,ln),160),Gn=Math.min(Math.max(gs,Ge),de-Ge-Rn)+Ee,ds=Bn?Math.max(kt+Y,Fn-Nn-Tt+Y):Math.min(Un+Tt+Y,D+Y-kt-Nn);Ie({top:ds,left:Gn,width:Rn,maxHeight:Nn})},[st]),zn=i.useCallback(()=>{const X=_e.current?.querySelector("button");if(!X)return;const _=X.getBoundingClientRect(),{width:de,height:D,offsetTop:Y,offsetLeft:Ee}=st(),Ge=16,kt=16,Tt=4,Pt=220,ln=Math.min(Math.max(_.width,200),Math.max(de-Ge*2,200)),ts=_.top-Y,Rn=_.bottom-Y,Fn=_.left-Ee,Un=D-Rn,gs=ts,Ln=Math.max(Un-kt-Tt,160),Vn=Math.max(gs-kt-Tt,160),Wn=Un<Pt&&gs>Un,Kn=Math.max(Math.min(Wn?Vn:Ln,Pt),160),Bn=Math.min(Math.max(Fn,Ge),de-Ge-ln)+Ee,Nn=Wn?Math.max(kt+Y,ts-Kn-Tt+Y):Math.min(Rn+Tt+Y,D+Y-kt-Kn);pt({top:Nn,left:Bn,width:ln,maxHeight:Kn})},[st]);i.useEffect(()=>{if(!ce)return;const X=()=>Gt();window.addEventListener("resize",X),window.addEventListener("scroll",X,!0);const _=window.visualViewport;return _&&(_.addEventListener("resize",X),_.addEventListener("scroll",X)),()=>{window.removeEventListener("resize",X),window.removeEventListener("scroll",X,!0),_&&(_.removeEventListener("resize",X),_.removeEventListener("scroll",X))}},[ce,Gt]),i.useEffect(()=>{if(!Ze)return;const X=()=>Cn();window.addEventListener("resize",X),window.addEventListener("scroll",X,!0);const _=window.visualViewport;return _&&(_.addEventListener("resize",X),_.addEventListener("scroll",X)),()=>{window.removeEventListener("resize",X),window.removeEventListener("scroll",X,!0),_&&(_.removeEventListener("resize",X),_.removeEventListener("scroll",X))}},[Ze,Cn]),i.useEffect(()=>{if(!F)return;const X=()=>fs();window.addEventListener("resize",X),window.addEventListener("scroll",X,!0);const _=window.visualViewport;return _&&(_.addEventListener("resize",X),_.addEventListener("scroll",X)),()=>{window.removeEventListener("resize",X),window.removeEventListener("scroll",X,!0),_&&(_.removeEventListener("resize",X),_.removeEventListener("scroll",X))}},[F,fs]),i.useEffect(()=>{if(!N)return;const X=()=>On();window.addEventListener("resize",X),window.addEventListener("scroll",X,!0);const _=window.visualViewport;return _&&(_.addEventListener("resize",X),_.addEventListener("scroll",X)),()=>{window.removeEventListener("resize",X),window.removeEventListener("scroll",X,!0),_&&(_.removeEventListener("resize",X),_.removeEventListener("scroll",X))}},[N,On]),i.useEffect(()=>{if(!xe)return;const X=()=>jn();window.addEventListener("resize",X),window.addEventListener("scroll",X,!0);const _=window.visualViewport;return _&&(_.addEventListener("resize",X),_.addEventListener("scroll",X)),()=>{window.removeEventListener("resize",X),window.removeEventListener("scroll",X,!0),_&&(_.removeEventListener("resize",X),_.removeEventListener("scroll",X))}},[xe,jn]),i.useEffect(()=>{if(!je)return;const X=()=>zn();window.addEventListener("resize",X),window.addEventListener("scroll",X,!0);const _=window.visualViewport;return _&&(_.addEventListener("resize",X),_.addEventListener("scroll",X)),()=>{window.removeEventListener("resize",X),window.removeEventListener("scroll",X,!0),_&&(_.removeEventListener("resize",X),_.removeEventListener("scroll",X))}},[je,zn]);const hn=i.useCallback(X=>{const _=Ec(X);dt(_.provider),fe(_.modelId)},[]),Et=i.useCallback(X=>{const _=Ec(X);ye(_.provider),H(_.modelId)},[]),En=i.useCallback(X=>{const _=Ec(X);pe(_.provider),Oe(_.modelId)},[]),yn=i.useCallback(async X=>{if(m){m(X);return}const _=Dt,D=_.includes(X)?_.filter(Y=>Y!==X):[X,..._];Qt(D);try{await kn({favoriteProviders:D,favoriteModels:Kt})}catch{Qt(_)}},[Dt,Kt,m]),ls=i.useCallback(async X=>{if(h){h(X);return}const _=Kt,D=_.includes(X)?_.filter(Y=>Y!==X):[X,..._];Bt(D);try{await kn({favoriteProviders:Dt,favoriteModels:D})}catch{Bt(_)}},[Kt,Dt,h]),cs=i.useCallback(()=>{const X=f.trim();if(!X){n("Enter a description first","error");return}r?.(X),tn()},[f,r,n,tn]),Hn=i.useCallback(()=>{const X=f.trim();if(!X){n("Enter a description first","error");return}o?.(X),tn()},[f,o,n,tn]),qn=i.useCallback(()=>{rt()},[rt]),wn=i.useCallback(async X=>{const _=f.trim();if(!(!_||It)){Ye(!1),St(!0);try{const de=await Tg(_,X,l);p(de),n("Description refined with AI","success"),k.current&&(k.current.style.height="auto",k.current.style.height=`${Math.min(k.current.scrollHeight,200)}px`)}catch(de){const D=$g(de);n(D,"error")}finally{St(!1)}}},[f,It,n,l]),Zn=(X,_)=>X.length>_?X.slice(0,_)+"…":X,_n=i.useCallback(async()=>{if(a){Mt(a),$t(null),Ct(!1);return}Ct(!0),$t(null);try{const X=await Os();Mt(X.models),d||Qt(X.favoriteProviders),u||Bt(X.favoriteModels)}catch(X){$t(Pe(X)||"Failed to load models")}finally{Ct(!1)}},[a,d,u]),is=i.useCallback(async()=>{if(K.length>0&&I===l){G(!0),On();return}ee(!0);try{const X=await Nr(void 0,l);A(X),$(l),G(!0),On()}catch(X){const _=Pe(X);n(_?`Failed to load agents: ${_}`:"Failed to load agents","error"),G(!1)}finally{ee(!1)}},[K.length,I,l,n,On]),es=(te?K.find(X=>X.id===te):void 0)?.name??te,ks=ve?We.find(X=>X.id===ve):void 0,Is=y,Ss=i.useCallback(()=>{S(X=>{const _=!X;return b(_),_})},[]);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:k,className:`quick-entry-input ${w?"quick-entry-input--expanded":""}`,placeholder:g?"Creating...":"Add a task...",value:f,onChange:X=>p(X.target.value),onKeyDown:at,onPaste:be,onFocus:vt,onBlur:ut,disabled:g||Ft,"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:Ss,"aria-expanded":y,"aria-controls":"quick-entry-controls","data-testid":"quick-entry-toggle",title:y?"Collapse":"Expand",children:y?t.jsx(Ei,{size:14}):t.jsx(rn,{size:14})})]})}),t.jsxs("div",{id:"quick-entry-controls",className:"quick-entry-controls",hidden:!Is,"aria-hidden":!Is,children:[Is&&!g&&t.jsxs("div",{className:"quick-entry-actions","data-testid":"quick-entry-actions",children:[t.jsxs("button",{type:"button",className:"btn btn-sm",onClick:cs,onMouseDown:X=>X.preventDefault(),disabled:!f.trim(),"data-testid":"plan-button",title:"Open planning mode with current description",children:[t.jsx(_i,{size:12,style:{verticalAlign:"middle",marginRight:4}}),"Plan"]}),t.jsxs("button",{type:"button",className:"btn btn-sm",onClick:Hn,onMouseDown:X=>X.preventDefault(),disabled:!f.trim(),"data-testid":"subtask-button",title:"Break down into AI-generated subtasks",children:[t.jsx(Yl,{size:12,style:{verticalAlign:"middle",marginRight:4}}),"Subtask"]}),t.jsxs("div",{className:"refine-trigger-wrap",ref:Ht,children:[t.jsxs("button",{type:"button",className:`btn btn-sm refine-button ${It?"refine-button--loading":""}`,onClick:()=>{Ye(X=>{const _=!X;return _?Cn():Le(null),_})},disabled:!f.trim()||It,"data-testid":"refine-button",title:"Refine description with AI",children:[t.jsx(ps,{size:12,style:{verticalAlign:"middle"}}),It?"Refining...":"Refine"]}),Ze&&me&&ae&&va.createPortal(t.jsxs("div",{ref:jt,className:"refine-menu refine-menu--portal",onMouseDown:X=>X.preventDefault(),style:{position:"fixed",top:`${ae.top}px`,left:`${ae.left}px`},children:[t.jsxs("div",{className:"refine-menu-item",onClick:()=>wn("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:()=>wn("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:()=>wn("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:()=>wn("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"})]})]}),me)]}),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:()=>{M(X=>{const _=!X;return _?(ne(!1),le(null),J(null),G(!1),mt(null),Se(!1),Ie(null),se(!1),pt(null),fs()):qe(null),_})},children:[t.jsx(cr,{size:12,style:{verticalAlign:"middle"}}),R.length>0?`${R.length} deps`:"Deps"]})}),F&&me&&ue&&(()=>{const X=O.toLowerCase(),_=(X?s.filter(de=>de.id.toLowerCase().includes(X)||de.title&&de.title.toLowerCase().includes(X)||de.description&&de.description.toLowerCase().includes(X)):[...s]).sort((de,D)=>{const Y=D.createdAt.localeCompare(de.createdAt);if(Y!==0)return Y;const Ee=parseInt(de.id.slice(de.id.lastIndexOf("-")+1),10)||0;return(parseInt(D.id.slice(D.id.lastIndexOf("-")+1),10)||0)-Ee});return va.createPortal(t.jsxs("div",{ref:Ne,className:"dep-dropdown dep-dropdown--portal",onMouseDown:de=>de.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:O,onChange:de=>q(de.target.value),onClick:de=>de.stopPropagation()}),_.length===0?t.jsx("div",{className:"dep-dropdown-empty",children:"No existing tasks"}):_.map(de=>t.jsxs("div",{className:`dep-dropdown-item${R.includes(de.id)?" selected":""}`,onMouseDown:D=>D.preventDefault(),onClick:()=>ie(de.id),children:[t.jsx("span",{className:"dep-dropdown-id",children:de.id}),t.jsx("span",{className:"dep-dropdown-title",children:Zn(de.title||de.description||de.id,60)})]},de.id))]}),me)})(),t.jsxs("button",{type:"button",className:"btn btn-sm","data-testid":"quick-entry-attach",onClick:()=>C.current?.click(),children:[t.jsx(jg,{size:12,style:{verticalAlign:"middle"}}),P.length>0?`Attach (${P.length})`:"Attach"]}),t.jsxs("button",{ref:$e,type:"button",className:"btn btn-sm","data-testid":"quick-entry-models",onClick:()=>{M(!1),G(!1),mt(null),Se(!1),Ie(null),se(!1),pt(null),J(null),ne(!0),Gt()},children:[t.jsx(oo,{size:12,style:{verticalAlign:"middle"}}),Je]}),t.jsx("div",{className:"node-trigger-wrap",ref:we,children:t.jsxs("button",{type:"button",className:"btn btn-sm dep-trigger","data-testid":"quick-entry-node-button",onClick:()=>{M(!1),G(!1),mt(null),ne(!1),le(null),J(null),se(!1),pt(null),Se(X=>{const _=!X;return _?jn():Ie(null),_})},children:[t.jsx(co,{size:12,style:{verticalAlign:"middle"}}),` ${ks?.name??"Node"}`,ks&&t.jsx("span",{className:"quick-entry-node-status",children:t.jsx(Ca,{status:ks.status,showLabel:!0})})]})}),xe&&me&&xt&&va.createPortal(t.jsxs("div",{ref:Q,className:"dep-dropdown node-picker-dropdown node-picker-dropdown--portal",onMouseDown:X=>X.preventDefault(),style:{position:"fixed",top:`${xt.top}px`,left:`${xt.left}px`,width:`${xt.width}px`,maxHeight:xt.maxHeight?`${xt.maxHeight}px`:void 0,overflowY:xt.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${ve==null?" selected":""}`,onMouseDown:X=>X.preventDefault(),onClick:()=>{ze(void 0),Se(!1),Ie(null)},children:t.jsx("span",{className:"node-picker-item-name",children:"Project default / local"})}),We.map(X=>t.jsxs("div",{className:`dep-dropdown-item node-picker-item${ve===X.id?" selected":""}`,onMouseDown:_=>_.preventDefault(),onClick:()=>{ze(X.id),Se(!1),Ie(null)},children:[t.jsx("span",{className:"quick-entry-node-status",children:t.jsx(Ca,{status:X.status})}),t.jsx("span",{className:"node-picker-item-name",children:X.name}),t.jsx("span",{className:"node-picker-item-status",children:VC(X.status)})]},X.id))]}),me),t.jsx("div",{className:"agent-trigger-wrap",ref:ot,children:t.jsxs("button",{type:"button",className:"btn btn-sm dep-trigger",onClick:()=>{N?(G(!1),mt(null)):(Se(!1),Ie(null),se(!1),pt(null),is())},"data-testid":"quick-entry-agent-button",children:[t.jsx($n,{size:12,style:{verticalAlign:"middle"}}),es?` ${es}`:" Agent"]})}),N&&me&&ht&&va.createPortal(t.jsxs("div",{ref:Be,className:"dep-dropdown agent-picker-dropdown agent-picker-dropdown--portal",onMouseDown:X=>X.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"}),Ve&&t.jsx("div",{className:"dep-dropdown-empty",children:"Loading agents..."}),!Ve&&K.map(X=>t.jsxs("div",{className:`dep-dropdown-item${te===X.id?" selected":""}`,onMouseDown:_=>_.preventDefault(),onClick:()=>{Z(X.id===te?null:X.id),G(!1),mt(null)},children:[t.jsx($n,{size:12,style:{marginRight:6}}),t.jsx("span",{className:"dep-dropdown-id",children:X.role}),t.jsx("span",{className:"dep-dropdown-title",children:X.name})]},X.id)),!Ve&&K.length===0&&t.jsx("div",{className:"dep-dropdown-empty",children:"No agents available"}),te&&t.jsx("div",{className:"dep-dropdown-item",onMouseDown:X=>X.preventDefault(),onClick:()=>{Z(null),G(!1),mt(null)},children:t.jsx("span",{className:"dep-dropdown-title",children:"Clear selection"})})]}),me),t.jsx("div",{className:"priority-trigger-wrap",ref:_e,children:t.jsxs("button",{type:"button",className:"btn btn-sm dep-trigger","data-testid":"quick-entry-priority-button",onClick:()=>{M(!1),G(!1),mt(null),Se(!1),Ie(null),ne(!1),le(null),J(null),se(X=>{const _=!X;return _?zn():pt(null),_})},children:[t.jsx($y,{size:12,style:{verticalAlign:"middle"}}),` ${Zt[0].toUpperCase()}${Zt.slice(1)}`]})}),je&&me&&Ue&&va.createPortal(t.jsxs("div",{ref:lt,className:"dep-dropdown priority-picker-dropdown priority-picker-dropdown--portal",onMouseDown:X=>X.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("div",{className:"dep-dropdown-search-header",children:"Select priority"}),oa.map(X=>{const _=`${X[0].toUpperCase()}${X.slice(1)}`;return t.jsx("div",{className:`dep-dropdown-item${Zt===X?" selected":""}`,"data-testid":`quick-entry-priority-option-${X}`,onMouseDown:de=>de.preventDefault(),onClick:()=>{dn(X),se(!1),pt(null)},children:t.jsx("span",{className:"dep-dropdown-title",children:_})},X)})]}),me),t.jsx("button",{type:"button",className:`btn btn-sm ${zt?"btn-primary":""}`,onClick:()=>en(X=>!X),onMouseDown:X=>X.preventDefault(),"aria-pressed":zt,"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:qn,onMouseDown:X=>X.preventDefault(),disabled:!f.trim()||g,"data-testid":"quick-entry-save",title:"Create task",children:[t.jsx(Sg,{size:12,style:{verticalAlign:"middle",marginRight:4}}),"Save"]})]}),P.length>0&&t.jsx("div",{className:"inline-create-previews",children:P.map((X,_)=>t.jsxs("div",{className:"inline-create-preview",children:[t.jsx("img",{src:X.previewUrl,alt:X.file.name}),t.jsx("button",{type:"button",className:"inline-create-preview-remove",onClick:()=>it(_),disabled:g,title:"Remove image","data-testid":`quick-entry-preview-remove-${_}`,children:"×"})]},X.previewUrl))}),ce&&me&&oe&&va.createPortal(t.jsx("div",{ref:De,className:"model-nested-menu model-nested-menu--portal",onMouseDown:X=>X.preventDefault(),"data-testid":"model-nested-menu",style:{position:"fixed",top:`${oe.top}px`,left:`${oe.left}px`,width:`${oe.width}px`,maxHeight:oe.maxHeight?`${oe.maxHeight}px`:void 0,overflowY:oe.maxHeight?"auto":void 0},children:re===null?t.jsxs("div",{className:"model-menu-items",children:[t.jsxs("button",{type:"button",className:`model-menu-item ${Xt?"model-menu-item--active":""}`,onClick:()=>J("plan"),"data-testid":"model-menu-plan",children:[t.jsxs("span",{className:"model-menu-item-label",children:[t.jsx(_i,{size:12,style:{verticalAlign:"middle",marginRight:6}}),"Plan"]}),t.jsx("span",{className:"model-menu-item-value",children:Xt?Nt(He,Fe):"Using default"}),t.jsx(Mn,{size:12,style:{marginLeft:"auto",color:"var(--text-dim)"}})]}),t.jsxs("button",{type:"button",className:`model-menu-item ${_t?"model-menu-item--active":""}`,onClick:()=>J("executor"),"data-testid":"model-menu-executor",children:[t.jsxs("span",{className:"model-menu-item-label",children:[t.jsx(ps,{size:12,style:{verticalAlign:"middle",marginRight:6}}),"Executor"]}),t.jsx("span",{className:"model-menu-item-value",children:_t?Nt(B,Ce):"Using default"}),t.jsx(Mn,{size:12,style:{marginLeft:"auto",color:"var(--text-dim)"}})]}),t.jsxs("button",{type:"button",className:`model-menu-item ${Yt?"model-menu-item--active":""}`,onClick:()=>J("validator"),"data-testid":"model-menu-validator",children:[t.jsxs("span",{className:"model-menu-item-label",children:[t.jsx(oo,{size:12,style:{verticalAlign:"middle",marginRight:6}}),"Reviewer"]}),t.jsx("span",{className:"model-menu-item-value",children:Yt?Nt(ke,Ae):"Using default"}),t.jsx(Mn,{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:()=>J(null),"data-testid":"model-submenu-back",children:[t.jsx(rn,{size:12,style:{transform:"rotate(90deg)",marginRight:4}}),"Back"]}),t.jsxs("div",{className:"model-submenu-header",children:[re==="plan"&&"Plan Model",re==="executor"&&"Executor Model",re==="validator"&&"Reviewer Model"]}),t.jsx(ys,{models:Vt,value:re==="plan"?gt:re==="executor"?Me:ct,onChange:re==="plan"?hn:re==="executor"?Et:En,placeholder:"Using default",disabled:tt,id:`model-${re}-select`,label:`${re} model`,favoriteProviders:At,onToggleFavorite:yn,favoriteModels:Lt,onToggleModelFavorite:ls}),wt&&t.jsxs("div",{className:"model-submenu-error",children:[t.jsx("span",{children:wt}),t.jsx("button",{type:"button",className:"btn btn-sm",onClick:_n,children:"Retry"})]})]})}),me)]}),t.jsx("input",{ref:C,type:"file",accept:"image/*",multiple:!0,style:{display:"none"},onChange:X=>{Xn(X.target.files),X.currentTarget.value=""},"data-testid":"quick-entry-file-input"}),t.jsx("div",{className:"quick-entry-hint",children:"Enter to create · Esc to cancel"})]})}function WC(e){return wu(e)||e}function KC(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 GC(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 x=g.worktree,w=o.get(x)||[];w.push(g),o.set(x,w)}const l=new Map(n.map(g=>[g.id,g])),d=n.filter(g=>g.column==="todo").filter(g=>!g.paused&&(g.dependencies||[]).every(x=>{const w=l.get(x);return w&&(w.column==="done"||w.column==="in-review"||w.column==="archived")})),m=KC(d).map(g=>l.get(g)).filter(g=>g!==void 0&&d.includes(g)),h=[],f=Array.from(o.keys());for(const g of f)h.push({label:WC(g),activeTasks:o.get(g),queuedTasks:[]});r.length>0&&h.push({label:"Unassigned",activeTasks:r,queuedTasks:[]});const p=m.slice(0,s);return p.length>0&&h.push({label:"Up Next",activeTasks:[],queuedTasks:p}),h}const mh=100,_c=50,hh=25;function JC({column:e,tasks:n,projectId:s,maxConcurrent:a,onMoveTask:r,onPauseTask:o,onOpenDetail:l,addToast:c,onQuickCreate:d,onNewTask:u,autoMerge:m,onToggleAutoMerge:h,globalPaused:f,onUpdateTask:p,onRetryTask:g,onArchiveTask:x,onUnarchiveTask:w,onDeleteTask:b,onArchiveAllDone:y,collapsed:S,onToggleCollapse:k,allTasks:C,availableModels:v,onPlanningMode:j,onSubtaskBreakdown:P,onOpenDetailWithTab:U,favoriteProviders:E,favoriteModels:R,onToggleFavorite:L,onToggleModelFavorite:F,isSearchActive:M,taskStuckTimeoutMs:O,onOpenMission:q,lastFetchTimeMs:te,workflowStepNameLookup:Z}){const[K,A]=i.useState(!1),[I,$]=i.useState(_c),[N,G]=i.useState(!1),[xe,Se]=i.useState(!1),[je,se]=i.useState(!1),[Ve,ee]=i.useState(!1),ce=i.useRef(null),ne=V0(n.length),{confirm:re}=ai();i.useEffect(()=>{if(!N)return;function Q(lt){ce.current?.contains(lt.target)||G(!1)}function _e(lt){lt.key==="Escape"&&G(!1)}return document.addEventListener("mousedown",Q),document.addEventListener("keydown",_e),()=>{document.removeEventListener("mousedown",Q),document.removeEventListener("keydown",_e)}},[N]);const J=e==="archived",B=J&&S,ye=!J&&!M&&e!=="in-progress"&&n.length>mh;i.useEffect(()=>{$(Q=>e==="in-progress"||J||n.length<=mh?_c:Math.min(Math.max(Q,_c),n.length))},[e,J,n.length]);const Ce=i.useCallback(Q=>{J||(Q.preventDefault(),Q.dataTransfer.dropEffect="move",A(!0))},[J]),H=i.useCallback(Q=>{Q.currentTarget.contains(Q.relatedTarget)||A(!1)},[]),ke=i.useCallback(async Q=>{Q.preventDefault(),A(!1);const _e=Q.dataTransfer.getData("text/plain");if(!_e)return;const lt=n.find(ht=>ht.id===_e);if(!(lt&&lt.column===e))try{const mt=(C?.find(Ue=>Ue.id===_e)??lt)?.steps.some(Ue=>Ue.status!=="pending")??!1,xt=(e==="todo"||e==="triage")&&mt;let Ie;if(xt){if(await re({title:"Preserve Progress?",message:"This task has completed steps. Keep progress before moving?",confirmLabel:"Keep Progress",cancelLabel:"Reset Progress"}))Ie={preserveProgress:!0};else if(!await re({title:"Reset Progress?",message:"Reset all step progress before moving this task?",confirmLabel:"Reset Progress",cancelLabel:"Cancel Move",danger:!0}))return}await r(_e,e,Ie)}catch(ht){c(Pe(ht),"error")}},[c,C,e,re,r,n]),pe=i.useMemo(()=>e!=="in-progress"?[]:GC(n,n,a),[e,n,a]),Ae=i.useMemo(()=>ye?n.slice(0,I):n,[ye,n,I]),Oe=Math.max(0,n.length-Ae.length),He=i.useCallback(()=>{$(Q=>Math.min(Q+hh,n.length))},[n.length]),dt=i.useCallback(async()=>{if(G(!1),!(n.length===0||!await re({title:"Replan All Tasks",message:`Move all ${n.length} todo task${n.length===1?"":"s"} back to planning to be replanned?`}))){Se(!0);try{const _e=await Promise.allSettled(n.map(mt=>r(mt.id,"triage"))),lt=_e.filter(mt=>mt.status==="rejected").length,ht=_e.length-lt;lt===0?c(`Moved ${ht} task${ht===1?"":"s"} to planning for replanning`,"success"):c(`Moved ${ht} of ${_e.length} tasks; ${lt} failed`,"error")}finally{Se(!1)}}},[n,r,c,re]),Fe=i.useMemo(()=>n.filter(Q=>!Q.paused&&!Q.assignedAgentId),[n]),fe=Fe.length,$e=e==="todo"||e==="in-progress"||e==="in-review",De=xe||je||Ve,ot=i.useCallback(async()=>{if(!(!o||(G(!1),fe===0)||!await re({title:"Stop All Tasks",message:`Stop all ${fe} ${ns[e].toLowerCase()} task${fe===1?"":"s"}?`,danger:!0}))){se(!0);try{const _e=await Promise.allSettled(Fe.map(mt=>o(mt.id))),lt=_e.filter(mt=>mt.status==="rejected").length,ht=_e.length-lt;lt===0?c(`Stopped ${ht} task${ht===1?"":"s"}`,"success"):c(`Stopped ${ht} of ${_e.length} tasks; ${lt} failed`,"error")}finally{se(!1)}}},[o,fe,e,Fe,c,re]),Be=i.useCallback(async()=>{if(G(!1),n.length===0||!await re({title:"Move All to Todo",message:`Move all ${n.length} ${ns[e].toLowerCase()} task${n.length===1?"":"s"} to Todo?`}))return;const _e=n.some(ht=>ht.steps.some(mt=>mt.status!=="pending"));let lt=!1;if(_e){if(await re({title:"Preserve Progress?",message:"Some tasks have completed steps. Keep progress before moving to Todo?",confirmLabel:"Keep Progress",cancelLabel:"Reset Progress"}))lt=!0;else if(!await re({title:"Reset Progress?",message:"Reset step progress for tasks before moving to Todo?",confirmLabel:"Reset Progress",cancelLabel:"Cancel Move",danger:!0}))return}ee(!0);try{const ht=await Promise.allSettled(n.map(Ie=>r(Ie.id,"todo",lt?{preserveProgress:!0}:void 0))),mt=ht.filter(Ie=>Ie.status==="rejected").length,xt=ht.length-mt;mt===0?c(`Moved ${xt} task${xt===1?"":"s"} to Todo`,"success"):c(`Moved ${xt} of ${ht.length} tasks to Todo; ${mt} failed`,"error")}finally{ee(!1)}},[n,e,r,c,re]),we=i.useCallback(async()=>{if(!(!y||n.length===0||!await re({title:"Archive All Done",message:`Archive all ${n.length} done tasks?`,danger:!0})))try{const _e=await y();c(`Archived ${_e.length} tasks`,"success")}catch(_e){c(Pe(_e)||"Failed to archive tasks","error")}},[y,n.length,c,re]);return t.jsxs("div",{className:`column${K?" drag-over":""}${J?" column-archived":""}${B?" column-collapsed":""}`,"data-column":e,onDragOver:Ce,onDragLeave:H,onDrop:ke,children:[t.jsxs("div",{className:"column-header",children:[t.jsx("div",{className:`column-dot dot-${e}`}),t.jsx("h2",{children:ns[e]}),t.jsx("span",{className:`column-count${ne?" count-flash":""}`,children:n.length}),e==="in-review"&&h&&t.jsxs("label",{className:"auto-merge-toggle",title:m?"Auto-merge enabled":"Auto-merge disabled",children:[t.jsx("input",{type:"checkbox",checked:!!m,onChange:h}),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:we,disabled:n.length===0,title:"Archive all done tasks","aria-label":"Archive all done tasks",children:t.jsx(xo,{})}),J&&k&&t.jsx("button",{className:"btn btn-icon btn-sm",onClick:k,title:S?"Expand archived tasks":"Collapse archived tasks","aria-label":S?"Expand archived tasks":"Collapse archived tasks",children:S?t.jsx(rn,{size:16}):t.jsx(Ei,{size:16})}),$e&&t.jsxs("div",{className:"column-menu",ref:ce,children:[t.jsx("button",{type:"button",className:"btn btn-icon btn-sm",onClick:()=>G(Q=>!Q),"aria-haspopup":"menu","aria-expanded":N,"aria-label":`${ns[e]} column actions`,title:"Column actions",disabled:De,children:t.jsx(gy,{})}),N&&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 dt(),disabled:n.length===0||xe,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 ot(),disabled:fe===0||je||!o,children:["Stop All",t.jsx("span",{className:"column-menu-item-hint",children:n.length===0?"No tasks in this column":fe===0?"No manually pausable tasks":`Pause ${fe} active unassigned task${fe===1?"":"s"}`})]}),t.jsxs("button",{type:"button",role:"menuitem",className:"column-menu-item",onClick:()=>void Be(),disabled:n.length===0||Ve,children:["Move All to Todo",t.jsxs("span",{className:"column-menu-item-hint",children:["Move ",n.length," task",n.length===1?"":"s"," to Todo"]})]})]})]})]})]}),!B&&t.jsx("p",{className:"column-desc",children:H0[e]}),!B&&t.jsxs("div",{className:"column-body",children:[e==="triage"&&d&&t.jsx(hb,{onCreate:d,addToast:c,tasks:C??[],availableModels:v,onPlanningMode:j,onSubtaskBreakdown:P,projectId:s,autoExpand:!1,favoriteProviders:E,favoriteModels:R,onToggleFavorite:L,onToggleModelFavorite:F}),e==="in-progress"?pe.length===0?t.jsx("div",{className:"empty-column",children:"No tasks"}):pe.map(Q=>t.jsx(mb,{label:Q.label,activeTasks:Q.activeTasks,queuedTasks:Q.queuedTasks,projectId:s,onOpenDetail:l,addToast:c,globalPaused:f,onUpdateTask:p,onRetryTask:g,onOpenDetailWithTab:U,taskStuckTimeoutMs:O,onOpenMission:q,lastFetchTimeMs:te,workflowStepNameLookup:Z},Q.label)):n.length===0?t.jsx("div",{className:"empty-column",children:"No tasks"}):t.jsxs(t.Fragment,{children:[Ae.map(Q=>t.jsx(ho,{task:Q,projectId:s,onOpenDetail:l,addToast:c,globalPaused:f,onUpdateTask:p,onRetryTask:g,onArchiveTask:x,onUnarchiveTask:w,onDeleteTask:b,onOpenDetailWithTab:U,taskStuckTimeoutMs:O,onOpenMission:q,onMoveTask:r,lastFetchTimeMs:te,workflowStepNameLookup:Z},Q.id)),ye&&Oe>0&&t.jsxs("button",{type:"button",className:"btn btn-secondary btn-sm",onClick:He,children:["Load ",Math.min(hh,Oe)," more (",Oe," remaining)"]})]}),t.jsx(ta,{slotId:"board-column-footer",projectId:s})]})]})}const pb=i.memo(JC);pb.displayName="Column";function YC(e,n){return e.length!==n.length?!1:e.every((s,a)=>s===n[a])}const ph=new Map;function QC(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 XC({tasks:e,projectId:n,maxConcurrent:s,onMoveTask:a,onPauseTask:r,onOpenDetail:o,addToast:l,onQuickCreate:c,onNewTask:d,autoMerge:u,onToggleAutoMerge:m,globalPaused:h,onUpdateTask:f,onRetryTask:p,onArchiveTask:g,onUnarchiveTask:x,onDeleteTask:w,onArchiveAllDone:b,onLoadArchivedTasks:y,searchQuery:S="",availableModels:k,onPlanningMode:C,onSubtaskBreakdown:v,onOpenDetailWithTab:j,favoriteProviders:P,favoriteModels:U,onToggleFavorite:E,onToggleModelFavorite:R,taskStuckTimeoutMs:L,onOpenMission:F,lastFetchTimeMs:M}){const[O,q]=i.useState(!0),te=i.useRef(!1),{fetchBatch:Z}=tC(n),K=i.useRef(null),[A,I]=i.useState(ph),$=S.trim()!=="",N=i.useRef({triage:[],todo:[],"in-progress":[],"in-review":[],done:[],archived:[]}),G=i.useCallback(()=>{q(je=>{const se=!je;return!se&&!te.current&&y&&(te.current=!0,y()),se})},[y]),xe=i.useMemo(()=>{const je={triage:[],todo:[],"in-progress":[],"in-review":[],done:[],archived:[]};for(const ee of e){const ce=ju(ee.column)?ee.column:Al;(je[ce]??je[Al]).push(ee)}const se=N.current,Ve={};for(const ee of ea){const ce=eb(je[ee],ee);Ve[ee]=YC(se[ee],ce)?se[ee]:ce}return N.current=Ve,Ve},[e]);i.useEffect(()=>{let je=!1;return _o(n).then(se=>{if(je)return;const Ve=new Map(se.map(ee=>[ee.id,ee.name]));I(ee=>QC(ee,Ve)?ee:Ve)}).catch(()=>{je||I(se=>se.size===0?se:ph)}),()=>{je=!0}},[n]);const Se=i.useMemo(()=>e.filter(je=>je.prInfo||je.issueInfo).map(je=>je.id),[e]);return i.useEffect(()=>{if(Se.length!==0)return K.current&&clearTimeout(K.current),K.current=setTimeout(()=>{const je=[];for(let se=0;se<Se.length;se+=50)je.push(Se.slice(se,se+50));je.forEach(se=>{Z(se)})},500),()=>{K.current&&clearTimeout(K.current)}},[Se,Z]),t.jsx(t.Fragment,{children:t.jsx("main",{className:"board",id:"board",children:ea.map(je=>t.jsx(pb,{column:je,tasks:xe[je],projectId:n,maxConcurrent:s,onMoveTask:a,onPauseTask:r,onOpenDetail:o,addToast:l,globalPaused:h,onUpdateTask:f,onRetryTask:p,onArchiveTask:g,onUnarchiveTask:x,onDeleteTask:w,allTasks:e,availableModels:k,onOpenDetailWithTab:j,favoriteProviders:P,favoriteModels:U,onToggleFavorite:E,onToggleModelFavorite:R,isSearchActive:$,taskStuckTimeoutMs:L,onOpenMission:F,lastFetchTimeMs:M,workflowStepNameLookup:A,...je==="triage"?{onQuickCreate:c,onNewTask:d,onPlanningMode:C,onSubtaskBreakdown:v}:{},...je==="in-review"?{autoMerge:u,onToggleAutoMerge:m}:{},...je==="done"?{onArchiveAllDone:b}:{},...je==="archived"?{collapsed:O,onToggleCollapse:G}:{}},je))})})}function Ai(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:m,height:h}=JSON.parse(u);typeof m=="number"&&m>0&&(a.style.width=`${m}px`),typeof h=="number"&&h>0&&(a.style.height=`${h}px`)}}catch{}if(typeof ResizeObserver>"u")return;let o=a.offsetWidth,l=a.offsetHeight,c=null;const d=new ResizeObserver(()=>{const u=a.offsetWidth,m=a.offsetHeight;u===o&&m===l||(o=u,l=m,c&&clearTimeout(c),c=setTimeout(()=>{try{localStorage.setItem(s,JSON.stringify({width:u,height:m}))}catch{}},200))});return d.observe(a),()=>{d.disconnect(),c&&clearTimeout(c)}},[e,n,s])}function ZC(){if(typeof window>"u")return!1;const e="ontouchstart"in window||navigator.maxTouchPoints>0,n=window.innerWidth<=768;return e&&n}let or=0,so=null;function eE(){if(typeof window>"u")return;if(or>0){or+=1;return}const e=document.documentElement,n=document.body;so={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=`-${so.scrollY}px`,n.style.left="0",n.style.right="0",n.style.width="100%",n.style.overflow="hidden",or=1}function tE(){if(typeof window>"u"||or===0||(or-=1,or>0||!so))return;const e=document.documentElement,n=document.body,{htmlOverflow:s,bodyPosition:a,bodyTop:r,bodyLeft:o,bodyRight:l,bodyWidth:c,bodyOverflow:d,scrollY:u}=so;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,so=null,window.scrollTo(0,0)}function vi(e){i.useEffect(()=>{if(!(!e||!ZC()))return eE(),()=>{tE()}},[e])}function qi(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 nE(e,n){const s={};return(e[e.length-1]===""?[...e,""]:e).join((s.padRight?" ":"")+","+(s.padLeft===!1?"":" ")).trim()}const sE=/^[$_\p{ID_Start}][$_\u{200C}\u{200D}\p{ID_Continue}]*$/u,iE=/^[$_\p{ID_Start}][-$_\u{200C}\u{200D}\p{ID_Continue}]*$/u,aE={};function fh(e,n){return(aE.jsx?iE:sE).test(e)}const rE=/[ \t\n\f\r]/g;function oE(e){return typeof e=="object"?e.type==="text"?gh(e.value):!1:gh(e)}function gh(e){return e.replace(rE,"")===""}class Io{constructor(n,s,a){this.normal=s,this.property=n,a&&(this.space=a)}}Io.prototype.normal={};Io.prototype.property={};Io.prototype.space=void 0;function fb(e,n){const s={},a={};for(const r of e)Object.assign(s,r.property),Object.assign(a,r.normal);return new Io(s,a,n)}function Ud(e){return e.toLowerCase()}class Bs{constructor(n,s){this.attribute=s,this.property=n}}Bs.prototype.attribute="";Bs.prototype.booleanish=!1;Bs.prototype.boolean=!1;Bs.prototype.commaOrSpaceSeparated=!1;Bs.prototype.commaSeparated=!1;Bs.prototype.defined=!1;Bs.prototype.mustUseProperty=!1;Bs.prototype.number=!1;Bs.prototype.overloadedBoolean=!1;Bs.prototype.property="";Bs.prototype.spaceSeparated=!1;Bs.prototype.space=void 0;let lE=0;const sn=Ra(),ms=Ra(),Bd=Ra(),yt=Ra(),Tn=Ra(),lr=Ra(),Vs=Ra();function Ra(){return 2**++lE}const Hd=Object.freeze(Object.defineProperty({__proto__:null,boolean:sn,booleanish:ms,commaOrSpaceSeparated:Vs,commaSeparated:lr,number:yt,overloadedBoolean:Bd,spaceSeparated:Tn},Symbol.toStringTag,{value:"Module"})),Mc=Object.keys(Hd);class Su extends Bs{constructor(n,s,a,r){let o=-1;if(super(n,s),bh(this,"space",r),typeof a=="number")for(;++o<Mc.length;){const l=Mc[o];bh(this,Mc[o],(a&Hd[l])===Hd[l])}}}Su.prototype.defined=!0;function bh(e,n,s){s&&(e[n]=s)}function Cr(e){const n={},s={};for(const[a,r]of Object.entries(e.properties)){const o=new Su(a,e.transform(e.attributes||{},a),r,e.space);e.mustUseProperty&&e.mustUseProperty.includes(a)&&(o.mustUseProperty=!0),n[a]=o,s[Ud(a)]=a,s[Ud(o.attribute)]=a}return new Io(n,s,e.space)}const gb=Cr({properties:{ariaActiveDescendant:null,ariaAtomic:ms,ariaAutoComplete:null,ariaBusy:ms,ariaChecked:ms,ariaColCount:yt,ariaColIndex:yt,ariaColSpan:yt,ariaControls:Tn,ariaCurrent:null,ariaDescribedBy:Tn,ariaDetails:null,ariaDisabled:ms,ariaDropEffect:Tn,ariaErrorMessage:null,ariaExpanded:ms,ariaFlowTo:Tn,ariaGrabbed:ms,ariaHasPopup:null,ariaHidden:ms,ariaInvalid:null,ariaKeyShortcuts:null,ariaLabel:null,ariaLabelledBy:Tn,ariaLevel:yt,ariaLive:null,ariaModal:ms,ariaMultiLine:ms,ariaMultiSelectable:ms,ariaOrientation:null,ariaOwns:Tn,ariaPlaceholder:null,ariaPosInSet:yt,ariaPressed:ms,ariaReadOnly:ms,ariaRelevant:null,ariaRequired:ms,ariaRoleDescription:Tn,ariaRowCount:yt,ariaRowIndex:yt,ariaRowSpan:yt,ariaSelected:ms,ariaSetSize:yt,ariaSort:null,ariaValueMax:yt,ariaValueMin:yt,ariaValueNow:yt,ariaValueText:null,role:null},transform(e,n){return n==="role"?n:"aria-"+n.slice(4).toLowerCase()}});function bb(e,n){return n in e?e[n]:n}function xb(e,n){return bb(e,n.toLowerCase())}const cE=Cr({attributes:{acceptcharset:"accept-charset",classname:"class",htmlfor:"for",httpequiv:"http-equiv"},mustUseProperty:["checked","multiple","muted","selected"],properties:{abbr:null,accept:lr,acceptCharset:Tn,accessKey:Tn,action:null,allow:null,allowFullScreen:sn,allowPaymentRequest:sn,allowUserMedia:sn,alt:null,as:null,async:sn,autoCapitalize:null,autoComplete:Tn,autoFocus:sn,autoPlay:sn,blocking:Tn,capture:null,charSet:null,checked:sn,cite:null,className:Tn,cols:yt,colSpan:null,content:null,contentEditable:ms,controls:sn,controlsList:Tn,coords:yt|lr,crossOrigin:null,data:null,dateTime:null,decoding:null,default:sn,defer:sn,dir:null,dirName:null,disabled:sn,download:Bd,draggable:ms,encType:null,enterKeyHint:null,fetchPriority:null,form:null,formAction:null,formEncType:null,formMethod:null,formNoValidate:sn,formTarget:null,headers:Tn,height:yt,hidden:Bd,high:yt,href:null,hrefLang:null,htmlFor:Tn,httpEquiv:Tn,id:null,imageSizes:null,imageSrcSet:null,inert:sn,inputMode:null,integrity:null,is:null,isMap:sn,itemId:null,itemProp:Tn,itemRef:Tn,itemScope:sn,itemType:Tn,kind:null,label:null,lang:null,language:null,list:null,loading:null,loop:sn,low:yt,manifest:null,max:null,maxLength:yt,media:null,method:null,min:null,minLength:yt,multiple:sn,muted:sn,name:null,nonce:null,noModule:sn,noValidate:sn,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:sn,optimum:yt,pattern:null,ping:Tn,placeholder:null,playsInline:sn,popover:null,popoverTarget:null,popoverTargetAction:null,poster:null,preload:null,readOnly:sn,referrerPolicy:null,rel:Tn,required:sn,reversed:sn,rows:yt,rowSpan:yt,sandbox:Tn,scope:null,scoped:sn,seamless:sn,selected:sn,shadowRootClonable:sn,shadowRootDelegatesFocus:sn,shadowRootMode:null,shape:null,size:yt,sizes:null,slot:null,span:yt,spellCheck:ms,src:null,srcDoc:null,srcLang:null,srcSet:null,start:yt,step:null,style:null,tabIndex:yt,target:null,title:null,translate:null,type:null,typeMustMatch:sn,useMap:null,value:ms,width:yt,wrap:null,writingSuggestions:null,align:null,aLink:null,archive:Tn,axis:null,background:null,bgColor:null,border:yt,borderColor:null,bottomMargin:yt,cellPadding:null,cellSpacing:null,char:null,charOff:null,classId:null,clear:null,code:null,codeBase:null,codeType:null,color:null,compact:sn,declare:sn,event:null,face:null,frame:null,frameBorder:null,hSpace:yt,leftMargin:yt,link:null,longDesc:null,lowSrc:null,marginHeight:yt,marginWidth:yt,noResize:sn,noHref:sn,noShade:sn,noWrap:sn,object:null,profile:null,prompt:null,rev:null,rightMargin:yt,rules:null,scheme:null,scrolling:ms,standby:null,summary:null,text:null,topMargin:yt,valueType:null,version:null,vAlign:null,vLink:null,vSpace:yt,allowTransparency:null,autoCorrect:null,autoSave:null,disablePictureInPicture:sn,disableRemotePlayback:sn,prefix:null,property:null,results:yt,security:null,unselectable:null},space:"html",transform:xb}),dE=Cr({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:Vs,accentHeight:yt,accumulate:null,additive:null,alignmentBaseline:null,alphabetic:yt,amplitude:yt,arabicForm:null,ascent:yt,attributeName:null,attributeType:null,azimuth:yt,bandwidth:null,baselineShift:null,baseFrequency:null,baseProfile:null,bbox:null,begin:null,bias:yt,by:null,calcMode:null,capHeight:yt,className:Tn,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:yt,diffuseConstant:yt,direction:null,display:null,dur:null,divisor:yt,dominantBaseline:null,download:sn,dx:null,dy:null,edgeMode:null,editable:null,elevation:yt,enableBackground:null,end:null,event:null,exponent:yt,externalResourcesRequired:null,fill:null,fillOpacity:yt,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:lr,g2:lr,glyphName:lr,glyphOrientationHorizontal:null,glyphOrientationVertical:null,glyphRef:null,gradientTransform:null,gradientUnits:null,handler:null,hanging:yt,hatchContentUnits:null,hatchUnits:null,height:null,href:null,hrefLang:null,horizAdvX:yt,horizOriginX:yt,horizOriginY:yt,id:null,ideographic:yt,imageRendering:null,initialVisibility:null,in:null,in2:null,intercept:yt,k:yt,k1:yt,k2:yt,k3:yt,k4:yt,kernelMatrix:Vs,kernelUnitLength:null,keyPoints:null,keySplines:null,keyTimes:null,kerning:null,lang:null,lengthAdjust:null,letterSpacing:null,lightingColor:null,limitingConeAngle:yt,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:yt,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:yt,overlineThickness:yt,paintOrder:null,panose1:null,path:null,pathLength:yt,patternContentUnits:null,patternTransform:null,patternUnits:null,phase:null,ping:Tn,pitch:null,playbackOrder:null,pointerEvents:null,points:null,pointsAtX:yt,pointsAtY:yt,pointsAtZ:yt,preserveAlpha:null,preserveAspectRatio:null,primitiveUnits:null,propagate:null,property:Vs,r:null,radius:null,referrerPolicy:null,refX:null,refY:null,rel:Vs,rev:Vs,renderingIntent:null,repeatCount:null,repeatDur:null,requiredExtensions:Vs,requiredFeatures:Vs,requiredFonts:Vs,requiredFormats:Vs,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:yt,specularExponent:yt,spreadMethod:null,spacing:null,startOffset:null,stdDeviation:null,stemh:null,stemv:null,stitchTiles:null,stopColor:null,stopOpacity:null,strikethroughPosition:yt,strikethroughThickness:yt,string:null,stroke:null,strokeDashArray:Vs,strokeDashOffset:null,strokeLineCap:null,strokeLineJoin:null,strokeMiterLimit:yt,strokeOpacity:yt,strokeWidth:null,style:null,surfaceScale:yt,syncBehavior:null,syncBehaviorDefault:null,syncMaster:null,syncTolerance:null,syncToleranceDefault:null,systemLanguage:Vs,tabIndex:yt,tableValues:null,target:null,targetX:yt,targetY:yt,textAnchor:null,textDecoration:null,textRendering:null,textLength:null,timelineBegin:null,title:null,transformBehavior:null,type:null,typeOf:Vs,to:null,transform:null,transformOrigin:null,u1:null,u2:null,underlinePosition:yt,underlineThickness:yt,unicode:null,unicodeBidi:null,unicodeRange:null,unitsPerEm:yt,values:null,vAlphabetic:yt,vMathematical:yt,vectorEffect:null,vHanging:yt,vIdeographic:yt,version:null,vertAdvY:yt,vertOriginX:yt,vertOriginY:yt,viewBox:null,viewTarget:null,visibility:null,width:null,widths:null,wordSpacing:null,writingMode:null,x:null,x1:null,x2:null,xChannelSelector:null,xHeight:yt,y:null,y1:null,y2:null,yChannelSelector:null,z:null,zoomAndPan:null},space:"svg",transform:bb}),vb=Cr({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()}}),yb=Cr({attributes:{xmlnsxlink:"xmlns:xlink"},properties:{xmlnsXLink:null,xmlns:null},space:"xmlns",transform:xb}),wb=Cr({properties:{xmlBase:null,xmlLang:null,xmlSpace:null},space:"xml",transform(e,n){return"xml:"+n.slice(3).toLowerCase()}}),uE={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"},mE=/[A-Z]/g,xh=/-[a-z]/g,hE=/^data[-\w.:]+$/i;function pE(e,n){const s=Ud(n);let a=n,r=Bs;if(s in e.normal)return e.property[e.normal[s]];if(s.length>4&&s.slice(0,4)==="data"&&hE.test(n)){if(n.charAt(4)==="-"){const o=n.slice(5).replace(xh,gE);a="data"+o.charAt(0).toUpperCase()+o.slice(1)}else{const o=n.slice(4);if(!xh.test(o)){let l=o.replace(mE,fE);l.charAt(0)!=="-"&&(l="-"+l),n="data"+l}}r=Su}return new r(a,n)}function fE(e){return"-"+e.toLowerCase()}function gE(e){return e.charAt(1).toUpperCase()}const bE=fb([gb,cE,vb,yb,wb],"html"),Cu=fb([gb,dE,vb,yb,wb],"svg");function xE(e){return e.join(" ").trim()}var Ja={},Ac,vh;function vE(){if(vh)return Ac;vh=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=`
652
- `,u="/",m="*",h="",f="comment",p="declaration";function g(w,b){if(typeof w!="string")throw new TypeError("First argument must be a string");if(!w)return[];b=b||{};var y=1,S=1;function k(M){var O=M.match(n);O&&(y+=O.length);var q=M.lastIndexOf(d);S=~q?M.length-q:S+M.length}function C(){var M={line:y,column:S};return function(O){return O.position=new v(M),U(),O}}function v(M){this.start=M,this.end={line:y,column:S},this.source=b.source}v.prototype.content=w;function j(M){var O=new Error(b.source+":"+y+":"+S+": "+M);if(O.reason=M,O.filename=b.source,O.line=y,O.column=S,O.source=w,!b.silent)throw O}function P(M){var O=M.exec(w);if(O){var q=O[0];return k(q),w=w.slice(q.length),O}}function U(){P(s)}function E(M){var O;for(M=M||[];O=R();)O!==!1&&M.push(O);return M}function R(){var M=C();if(!(u!=w.charAt(0)||m!=w.charAt(1))){for(var O=2;h!=w.charAt(O)&&(m!=w.charAt(O)||u!=w.charAt(O+1));)++O;if(O+=2,h===w.charAt(O-1))return j("End of comment missing");var q=w.slice(2,O-2);return S+=2,k(q),w=w.slice(O),S+=2,M({type:f,comment:q})}}function L(){var M=C(),O=P(a);if(O){if(R(),!P(r))return j("property missing ':'");var q=P(o),te=M({type:p,property:x(O[0].replace(e,h)),value:q?x(q[0].replace(e,h)):h});return P(l),te}}function F(){var M=[];E(M);for(var O;O=L();)O!==!1&&(M.push(O),E(M));return M}return U(),F()}function x(w){return w?w.replace(c,h):h}return Ac=g,Ac}var yh;function yE(){if(yh)return Ja;yh=1;var e=Ja&&Ja.__importDefault||function(a){return a&&a.__esModule?a:{default:a}};Object.defineProperty(Ja,"__esModule",{value:!0}),Ja.default=s;const n=e(vE());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:m}=d;c?r(u,m,d):m&&(o=o||{},o[u]=m)}),o}return Ja}var Tr={},wh;function wE(){if(wh)return Tr;wh=1,Object.defineProperty(Tr,"__esModule",{value:!0}),Tr.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,m){return m.toUpperCase()},c=function(u,m){return"".concat(m,"-")},d=function(u,m){return m===void 0&&(m={}),o(u)?u:(u=u.toLowerCase(),m.reactCompat?u=u.replace(r,c):u=u.replace(a,c),u.replace(n,l))};return Tr.camelCase=d,Tr}var $r,kh;function kE(){if(kh)return $r;kh=1;var e=$r&&$r.__importDefault||function(r){return r&&r.__esModule?r:{default:r}},n=e(yE()),s=wE();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,$r=a,$r}var jE=kE();const NE=mg(jE),kb=jb("end"),Eu=jb("start");function jb(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 SE(e){const n=Eu(e),s=kb(e);if(n&&s)return{start:n,end:s}}function io(e){return!e||typeof e!="object"?"":"position"in e||"type"in e?jh(e.position):"start"in e||"end"in e?jh(e):"line"in e||"column"in e?qd(e):""}function qd(e){return Nh(e&&e.line)+":"+Nh(e&&e.column)}function jh(e){return qd(e&&e.start)+"-"+qd(e&&e.end)}function Nh(e){return e&&typeof e=="number"?e:1}class Rs 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=io(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}}Rs.prototype.file="";Rs.prototype.name="";Rs.prototype.reason="";Rs.prototype.message="";Rs.prototype.stack="";Rs.prototype.column=void 0;Rs.prototype.line=void 0;Rs.prototype.ancestors=void 0;Rs.prototype.cause=void 0;Rs.prototype.fatal=void 0;Rs.prototype.place=void 0;Rs.prototype.ruleId=void 0;Rs.prototype.source=void 0;const _u={}.hasOwnProperty,CE=new Map,EE=/[A-Z]/g,_E=new Set(["table","tbody","thead","tfoot","tr"]),ME=new Set(["td","th"]),Nb="https://github.com/syntax-tree/hast-util-to-jsx-runtime";function AE(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=OE(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=LE(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"?Cu:bE,stylePropertyNameCase:n.stylePropertyNameCase||"dom",tableCellAlignToStyle:n.tableCellAlignToStyle!==!1},o=Sb(r,e,void 0);return o&&typeof o!="string"?o:r.create(e,r.Fragment,{children:o||void 0},void 0)}function Sb(e,n,s){if(n.type==="element")return PE(e,n,s);if(n.type==="mdxFlowExpression"||n.type==="mdxTextExpression")return RE(e,n);if(n.type==="mdxJsxFlowElement"||n.type==="mdxJsxTextElement")return TE(e,n,s);if(n.type==="mdxjsEsm")return IE(e,n);if(n.type==="root")return $E(e,n,s);if(n.type==="text")return DE(e,n)}function PE(e,n,s){const a=e.schema;let r=a;n.tagName.toLowerCase()==="svg"&&a.space==="html"&&(r=Cu,e.schema=r),e.ancestors.push(n);const o=Eb(e,n.tagName,!1),l=zE(e,n);let c=Au(e,n);return _E.has(n.tagName)&&(c=c.filter(function(d){return typeof d=="string"?!oE(d):!0})),Cb(e,l,o,n),Mu(l,c),e.ancestors.pop(),e.schema=a,e.create(n,o,l,s)}function RE(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)}po(e,n.position)}function IE(e,n){if(n.data&&n.data.estree&&e.evaluater)return e.evaluater.evaluateProgram(n.data.estree);po(e,n.position)}function TE(e,n,s){const a=e.schema;let r=a;n.name==="svg"&&a.space==="html"&&(r=Cu,e.schema=r),e.ancestors.push(n);const o=n.name===null?e.Fragment:Eb(e,n.name,!0),l=FE(e,n),c=Au(e,n);return Cb(e,l,o,n),Mu(l,c),e.ancestors.pop(),e.schema=a,e.create(n,o,l,s)}function $E(e,n,s){const a={};return Mu(a,Au(e,n)),e.create(n,e.Fragment,a,s)}function DE(e,n){return n.value}function Cb(e,n,s,a){typeof s!="string"&&s!==e.Fragment&&e.passNode&&(n.node=a)}function Mu(e,n){if(n.length>0){const s=n.length>1?n:n[0];s&&(e.children=s)}}function LE(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 OE(e,n){return s;function s(a,r,o,l){const c=Array.isArray(o.children),d=Eu(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 zE(e,n){const s={};let a,r;for(r in n.properties)if(r!=="children"&&_u.call(n.properties,r)){const o=UE(e,r,n.properties[r]);if(o){const[l,c]=o;e.tableCellAlignToStyle&&l==="align"&&typeof c=="string"&&ME.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 FE(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 po(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 po(e,n.position);else o=a.value===null?!0:a.value;s[r]=o}return s}function Au(e,n){const s=[];let a=-1;const r=e.passKeys?new Map:CE;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=Sb(e,o,l);c!==void 0&&s.push(c)}return s}function UE(e,n,s){const a=pE(e.schema,n);if(!(s==null||typeof s=="number"&&Number.isNaN(s))){if(Array.isArray(s)&&(s=a.commaSeparated?nE(s):xE(s)),a.property==="style"){let r=typeof s=="object"?s:BE(e,String(s));return e.stylePropertyNameCase==="css"&&(r=HE(r)),["style",r]}return[e.elementAttributeNameCase==="react"&&a.space?uE[a.property]||a.property:a.attribute,s]}}function BE(e,n){try{return NE(n,{reactCompat:!0})}catch(s){if(e.ignoreInvalidStyle)return{};const a=s,r=new Rs("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=Nb+"#cannot-parse-style-attribute",r}}function Eb(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=fh(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=fh(n)&&!/^[a-z]/.test(n)?{type:"Identifier",name:n}:{type:"Literal",value:n};if(a.type==="Literal"){const r=a.value;return _u.call(e.components,r)?e.components[r]:r}if(e.evaluater)return e.evaluater.evaluateExpression(a);po(e)}function po(e,n){const s=new Rs("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=Nb+"#cannot-handle-mdx-estrees-without-createevaluater",s}function HE(e){const n={};let s;for(s in e)_u.call(e,s)&&(n[qE(s)]=e[s]);return n}function qE(e){let n=e.replace(EE,VE);return n.slice(0,3)==="ms-"&&(n="-"+n),n}function VE(e){return"-"+e.toLowerCase()}const Pc={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"]},WE={};function Pu(e,n){const s=WE,a=typeof s.includeImageAlt=="boolean"?s.includeImageAlt:!0,r=typeof s.includeHtml=="boolean"?s.includeHtml:!0;return _b(e,a,r)}function _b(e,n,s){if(KE(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 Sh(e.children,n,s)}return Array.isArray(e)?Sh(e,n,s):""}function Sh(e,n,s){const a=[];let r=-1;for(;++r<e.length;)a[r]=_b(e[r],n,s);return a.join("")}function KE(e){return!!(e&&typeof e=="object")}const Ch=document.createElement("i");function Ru(e){const n="&"+e+";";Ch.innerHTML=n;const s=Ch.textContent;return s.charCodeAt(s.length-1)===59&&e!=="semi"||s===n?!1:s}function Gs(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 ni(e,n){return e.length>0?(Gs(e,e.length,0,n),e):n}const Eh={}.hasOwnProperty;function Mb(e){const n={};let s=-1;for(;++s<e.length;)GE(n,e[s]);return n}function GE(e,n){let s;for(s in n){const r=(Eh.call(e,s)?e[s]:void 0)||(e[s]={}),o=n[s];let l;if(o)for(l in o){Eh.call(r,l)||(r[l]=[]);const c=o[l];JE(r[l],Array.isArray(c)?c:c?[c]:[])}}}function JE(e,n){let s=-1;const a=[];for(;++s<n.length;)(n[s].add==="after"?e:a).push(n[s]);Gs(e,0,0,a)}function Ab(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 fi(e){return e.replace(/[\t\n\r ]+/g," ").replace(/^ | $/g,"").toLowerCase().toUpperCase()}const Ls=la(/[A-Za-z]/),As=la(/[\dA-Za-z]/),YE=la(/[#-'*+\--9=?A-Z^-~]/);function Il(e){return e!==null&&(e<32||e===127)}const Vd=la(/\d/),QE=la(/[\dA-Fa-f]/),XE=la(/[!-/:-@[-`{-~]/);function Wt(e){return e!==null&&e<-2}function Pn(e){return e!==null&&(e<0||e===32)}function mn(e){return e===-2||e===-1||e===32}const sc=la(/\p{P}|\p{S}/u),_a=la(/\s/);function la(e){return n;function n(s){return s!==null&&s>-1&&e.test(String.fromCharCode(s))}}function Er(e){const n=[];let s=-1,a=0,r=0;for(;++s<e.length;){const o=e.charCodeAt(s);let l="";if(o===37&&As(e.charCodeAt(s+1))&&As(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 pn(e,n,s,a){const r=a?a-1:Number.POSITIVE_INFINITY;let o=0;return l;function l(d){return mn(d)?(e.enter(s),c(d)):n(d)}function c(d){return mn(d)&&o++<r?(e.consume(d),c):(e.exit(s),n(d))}}const ZE={tokenize:e2};function e2(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"),pn(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 Wt(c)?(e.consume(c),e.exit("chunkText"),o):(e.consume(c),l)}}const t2={tokenize:n2},_h={tokenize:s2};function n2(e){const n=this,s=[];let a=0,r,o,l;return c;function c(S){if(a<s.length){const k=s[a];return n.containerState=k[1],e.attempt(k[0].continuation,d,u)(S)}return u(S)}function d(S){if(a++,n.containerState._closeFlow){n.containerState._closeFlow=void 0,r&&y();const k=n.events.length;let C=k,v;for(;C--;)if(n.events[C][0]==="exit"&&n.events[C][1].type==="chunkFlow"){v=n.events[C][1].end;break}b(a);let j=k;for(;j<n.events.length;)n.events[j][1].end={...v},j++;return Gs(n.events,C+1,0,n.events.slice(k)),n.events.length=j,u(S)}return c(S)}function u(S){if(a===s.length){if(!r)return f(S);if(r.currentConstruct&&r.currentConstruct.concrete)return g(S);n.interrupt=!!(r.currentConstruct&&!r._gfmTableDynamicInterruptHack)}return n.containerState={},e.check(_h,m,h)(S)}function m(S){return r&&y(),b(a),f(S)}function h(S){return n.parser.lazy[n.now().line]=a!==s.length,l=n.now().offset,g(S)}function f(S){return n.containerState={},e.attempt(_h,p,g)(S)}function p(S){return a++,s.push([n.currentConstruct,n.containerState]),f(S)}function g(S){if(S===null){r&&y(),b(0),e.consume(S);return}return r=r||n.parser.flow(n.now()),e.enter("chunkFlow",{_tokenizer:r,contentType:"flow",previous:o}),x(S)}function x(S){if(S===null){w(e.exit("chunkFlow"),!0),b(0),e.consume(S);return}return Wt(S)?(e.consume(S),w(e.exit("chunkFlow")),a=0,n.interrupt=void 0,c):(e.consume(S),x)}function w(S,k){const C=n.sliceStream(S);if(k&&C.push(null),S.previous=o,o&&(o.next=S),o=S,r.defineSkip(S.start),r.write(C),n.parser.lazy[S.start.line]){let v=r.events.length;for(;v--;)if(r.events[v][1].start.offset<l&&(!r.events[v][1].end||r.events[v][1].end.offset>l))return;const j=n.events.length;let P=j,U,E;for(;P--;)if(n.events[P][0]==="exit"&&n.events[P][1].type==="chunkFlow"){if(U){E=n.events[P][1].end;break}U=!0}for(b(a),v=j;v<n.events.length;)n.events[v][1].end={...E},v++;Gs(n.events,P+1,0,n.events.slice(j)),n.events.length=v}}function b(S){let k=s.length;for(;k-- >S;){const C=s[k];n.containerState=C[1],C[0].exit.call(n,e)}s.length=S}function y(){r.write([null]),o=void 0,r=void 0,n.containerState._closeFlow=void 0}}function s2(e,n,s){return pn(e,e.attempt(this.parser.constructs.document,n,s),"linePrefix",this.parser.constructs.disable.null.includes("codeIndented")?void 0:4)}function fr(e){if(e===null||Pn(e)||_a(e))return 1;if(sc(e))return 2}function ic(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 Wd={name:"attention",resolveAll:i2,tokenize:a2};function i2(e,n){let s=-1,a,r,o,l,c,d,u,m;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 h={...e[a][1].end},f={...e[s][1].start};Mh(h,-d),Mh(f,d),l={type:d>1?"strongSequence":"emphasisSequence",start:h,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=ni(u,[["enter",e[a][1],n],["exit",e[a][1],n]])),u=ni(u,[["enter",r,n],["enter",l,n],["exit",l,n],["enter",o,n]]),u=ni(u,ic(n.parser.constructs.insideSpan.null,e.slice(a+1,s),n)),u=ni(u,[["exit",o,n],["enter",c,n],["exit",c,n],["exit",r,n]]),e[s][1].end.offset-e[s][1].start.offset?(m=2,u=ni(u,[["enter",e[s][1],n],["exit",e[s][1],n]])):m=0,Gs(e,a-1,s-a+3,u),s=a+u.length-m-2;break}}for(s=-1;++s<e.length;)e[s][1].type==="attentionSequence"&&(e[s][1].type="data");return e}function a2(e,n){const s=this.parser.constructs.attentionMarkers.null,a=this.previous,r=fr(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"),m=fr(d),h=!m||m===2&&r||s.includes(d),f=!r||r===2&&m||s.includes(a);return u._open=!!(o===42?h:h&&(r||!f)),u._close=!!(o===42?f:f&&(m||!h)),n(d)}}function Mh(e,n){e.column+=n,e.offset+=n,e._bufferIndex+=n}const r2={name:"autolink",tokenize:o2};function o2(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 Ls(p)?(e.consume(p),l):p===64?s(p):u(p)}function l(p){return p===43||p===45||p===46||As(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||As(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||Il(p)?s(p):(e.consume(p),d)}function u(p){return p===64?(e.consume(p),m):YE(p)?(e.consume(p),u):s(p)}function m(p){return As(p)?h(p):s(p)}function h(p){return p===46?(e.consume(p),a=0,m):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||As(p))&&a++<63){const g=p===45?f:h;return e.consume(p),g}return s(p)}}const To={partial:!0,tokenize:l2};function l2(e,n,s){return a;function a(o){return mn(o)?pn(e,r,"linePrefix")(o):r(o)}function r(o){return o===null||Wt(o)?n(o):s(o)}}const Pb={continuation:{tokenize:d2},exit:u2,name:"blockQuote",tokenize:c2};function c2(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 mn(l)?(e.enter("blockQuotePrefixWhitespace"),e.consume(l),e.exit("blockQuotePrefixWhitespace"),e.exit("blockQuotePrefix"),n):(e.exit("blockQuotePrefix"),n(l))}}function d2(e,n,s){const a=this;return r;function r(l){return mn(l)?pn(e,o,"linePrefix",a.parser.constructs.disable.null.includes("codeIndented")?void 0:4)(l):o(l)}function o(l){return e.attempt(Pb,n,s)(l)}}function u2(e){e.exit("blockQuote")}const Rb={name:"characterEscape",tokenize:m2};function m2(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 XE(o)?(e.enter("characterEscapeValue"),e.consume(o),e.exit("characterEscapeValue"),e.exit("characterEscape"),n):s(o)}}const Ib={name:"characterReference",tokenize:h2};function h2(e,n,s){const a=this;let r=0,o,l;return c;function c(h){return e.enter("characterReference"),e.enter("characterReferenceMarker"),e.consume(h),e.exit("characterReferenceMarker"),d}function d(h){return h===35?(e.enter("characterReferenceMarkerNumeric"),e.consume(h),e.exit("characterReferenceMarkerNumeric"),u):(e.enter("characterReferenceValue"),o=31,l=As,m(h))}function u(h){return h===88||h===120?(e.enter("characterReferenceMarkerHexadecimal"),e.consume(h),e.exit("characterReferenceMarkerHexadecimal"),e.enter("characterReferenceValue"),o=6,l=QE,m):(e.enter("characterReferenceValue"),o=7,l=Vd,m(h))}function m(h){if(h===59&&r){const f=e.exit("characterReferenceValue");return l===As&&!Ru(a.sliceSerialize(f))?s(h):(e.enter("characterReferenceMarker"),e.consume(h),e.exit("characterReferenceMarker"),e.exit("characterReference"),n)}return l(h)&&r++<o?(e.consume(h),m):s(h)}}const Ah={partial:!0,tokenize:f2},Ph={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(v){return u(v)}function u(v){const j=a.events[a.events.length-1];return o=j&&j[1].type==="linePrefix"?j[2].sliceSerialize(j[1],!0).length:0,c=v,e.enter("codeFenced"),e.enter("codeFencedFence"),e.enter("codeFencedFenceSequence"),m(v)}function m(v){return v===c?(l++,e.consume(v),m):l<3?s(v):(e.exit("codeFencedFenceSequence"),mn(v)?pn(e,h,"whitespace")(v):h(v))}function h(v){return v===null||Wt(v)?(e.exit("codeFencedFence"),a.interrupt?n(v):e.check(Ah,x,k)(v)):(e.enter("codeFencedFenceInfo"),e.enter("chunkString",{contentType:"string"}),f(v))}function f(v){return v===null||Wt(v)?(e.exit("chunkString"),e.exit("codeFencedFenceInfo"),h(v)):mn(v)?(e.exit("chunkString"),e.exit("codeFencedFenceInfo"),pn(e,p,"whitespace")(v)):v===96&&v===c?s(v):(e.consume(v),f)}function p(v){return v===null||Wt(v)?h(v):(e.enter("codeFencedFenceMeta"),e.enter("chunkString",{contentType:"string"}),g(v))}function g(v){return v===null||Wt(v)?(e.exit("chunkString"),e.exit("codeFencedFenceMeta"),h(v)):v===96&&v===c?s(v):(e.consume(v),g)}function x(v){return e.attempt(r,k,w)(v)}function w(v){return e.enter("lineEnding"),e.consume(v),e.exit("lineEnding"),b}function b(v){return o>0&&mn(v)?pn(e,y,"linePrefix",o+1)(v):y(v)}function y(v){return v===null||Wt(v)?e.check(Ah,x,k)(v):(e.enter("codeFlowValue"),S(v))}function S(v){return v===null||Wt(v)?(e.exit("codeFlowValue"),y(v)):(e.consume(v),S)}function k(v){return e.exit("codeFenced"),n(v)}function C(v,j,P){let U=0;return E;function E(O){return v.enter("lineEnding"),v.consume(O),v.exit("lineEnding"),R}function R(O){return v.enter("codeFencedFence"),mn(O)?pn(v,L,"linePrefix",a.parser.constructs.disable.null.includes("codeIndented")?void 0:4)(O):L(O)}function L(O){return O===c?(v.enter("codeFencedFenceSequence"),F(O)):P(O)}function F(O){return O===c?(U++,v.consume(O),F):U>=l?(v.exit("codeFencedFenceSequence"),mn(O)?pn(v,M,"whitespace")(O):M(O)):P(O)}function M(O){return O===null||Wt(O)?(v.exit("codeFencedFence"),j(O)):P(O)}}}function f2(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 Rc={name:"codeIndented",tokenize:b2},g2={partial:!0,tokenize:x2};function b2(e,n,s){const a=this;return r;function r(u){return e.enter("codeIndented"),pn(e,o,"linePrefix",5)(u)}function o(u){const m=a.events[a.events.length-1];return m&&m[1].type==="linePrefix"&&m[2].sliceSerialize(m[1],!0).length>=4?l(u):s(u)}function l(u){return u===null?d(u):Wt(u)?e.attempt(g2,l,d)(u):(e.enter("codeFlowValue"),c(u))}function c(u){return u===null||Wt(u)?(e.exit("codeFlowValue"),l(u)):(e.consume(u),c)}function d(u){return e.exit("codeIndented"),n(u)}}function x2(e,n,s){const a=this;return r;function r(l){return a.parser.lazy[a.now().line]?s(l):Wt(l)?(e.enter("lineEnding"),e.consume(l),e.exit("lineEnding"),r):pn(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):Wt(l)?r(l):s(l)}}const v2={name:"codeText",previous:w2,resolve:y2,tokenize:k2};function y2(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 w2(e){return e!==96||this.events[this.events.length-1][1].type==="characterEscape"}function k2(e,n,s){let a=0,r,o;return l;function l(h){return e.enter("codeText"),e.enter("codeTextSequence"),c(h)}function c(h){return h===96?(e.consume(h),a++,c):(e.exit("codeTextSequence"),d(h))}function d(h){return h===null?s(h):h===32?(e.enter("space"),e.consume(h),e.exit("space"),d):h===96?(o=e.enter("codeTextSequence"),r=0,m(h)):Wt(h)?(e.enter("lineEnding"),e.consume(h),e.exit("lineEnding"),d):(e.enter("codeTextData"),u(h))}function u(h){return h===null||h===32||h===96||Wt(h)?(e.exit("codeTextData"),d(h)):(e.consume(h),u)}function m(h){return h===96?(e.consume(h),r++,m):r===a?(e.exit("codeTextSequence"),e.exit("codeText"),n(h)):(o.type="codeTextData",u(h))}}class j2{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&&Dr(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),Dr(this.left,n)}unshift(n){this.setCursor(0),this.right.push(n)}unshiftMany(n){this.setCursor(0),Dr(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);Dr(this.right,s.reverse())}else{const s=this.right.splice(this.left.length+this.right.length-n,Number.POSITIVE_INFINITY);Dr(this.left,s.reverse())}}}function Dr(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 Tb(e){const n={};let s=-1,a,r,o,l,c,d,u;const m=new j2(e);for(;++s<m.length;){for(;s in n;)s=n[s];if(a=m.get(s),s&&a[1].type==="chunkFlow"&&m.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,N2(m,s)),s=n[s],u=!0);else if(a[1]._container){for(o=s,r=void 0;o--;)if(l=m.get(o),l[1].type==="lineEnding"||l[1].type==="lineEndingBlank")l[0]==="enter"&&(r&&(m.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={...m.get(r)[1].start},c=m.slice(r,s),c.unshift(a),m.splice(r,s-r+1,c))}}return Gs(e,0,Number.POSITIVE_INFINITY,m.slice(0)),!u}function N2(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 m,h,f=-1,p=s,g=0,x=0;const w=[x];for(;p;){for(;e.get(++r)[1]!==p;);o.push(r),p._tokenizer||(m=a.sliceStream(p),p.next||m.push(null),h&&l.defineSkip(p.start),p._isInFirstContentOfListItem&&(l._gfmTasklistFirstContentOfListItem=!0),l.write(m),p._isInFirstContentOfListItem&&(l._gfmTasklistFirstContentOfListItem=void 0)),h=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&&(x=f+1,w.push(x),p._tokenizer=void 0,p.previous=void 0,p=p.next);for(l.events=[],p?(p._tokenizer=void 0,p.previous=void 0):w.pop(),f=w.length;f--;){const b=c.slice(w[f],w[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 S2={resolve:E2,tokenize:_2},C2={partial:!0,tokenize:M2};function E2(e){return Tb(e),e}function _2(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):Wt(c)?e.check(C2,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 M2(e,n,s){const a=this;return r;function r(l){return e.exit("chunkContent"),e.enter("lineEnding"),e.consume(l),e.exit("lineEnding"),pn(e,o,"linePrefix")}function o(l){if(l===null||Wt(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 $b(e,n,s,a,r,o,l,c,d){const u=d||Number.POSITIVE_INFINITY;let m=0;return h;function h(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||Il(b)?s(b):(e.enter(a),e.enter(l),e.enter(c),e.enter("chunkString",{contentType:"string"}),x(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||Wt(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 x(b){return!m&&(b===null||b===41||Pn(b))?(e.exit("chunkString"),e.exit(c),e.exit(l),e.exit(a),n(b)):m<u&&b===40?(e.consume(b),m++,x):b===41?(e.consume(b),m--,x):b===null||b===32||b===40||Il(b)?s(b):(e.consume(b),b===92?w:x)}function w(b){return b===40||b===41||b===92?(e.consume(b),x):x(b)}}function Db(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),m}function m(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):Wt(p)?(e.enter("lineEnding"),e.consume(p),e.exit("lineEnding"),m):(e.enter("chunkString",{contentType:"string"}),h(p))}function h(p){return p===null||p===91||p===93||Wt(p)||c++>999?(e.exit("chunkString"),m(p)):(e.consume(p),d||(d=!mn(p)),p===92?f:h)}function f(p){return p===91||p===92||p===93?(e.consume(p),c++,h):h(p)}}function Lb(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):Wt(f)?(e.enter("lineEnding"),e.consume(f),e.exit("lineEnding"),pn(e,u,"linePrefix")):(e.enter("chunkString",{contentType:"string"}),m(f))}function m(f){return f===l||f===null||Wt(f)?(e.exit("chunkString"),u(f)):(e.consume(f),f===92?h:m)}function h(f){return f===l||f===92?(e.consume(f),m):m(f)}}function ao(e,n){let s;return a;function a(r){return Wt(r)?(e.enter("lineEnding"),e.consume(r),e.exit("lineEnding"),s=!0,a):mn(r)?pn(e,a,s?"linePrefix":"lineSuffix")(r):n(r)}}const A2={name:"definition",tokenize:R2},P2={partial:!0,tokenize:I2};function R2(e,n,s){const a=this;let r;return o;function o(p){return e.enter("definition"),l(p)}function l(p){return Db.call(a,e,c,s,"definitionLabel","definitionLabelMarker","definitionLabelString")(p)}function c(p){return r=fi(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 Pn(p)?ao(e,u)(p):u(p)}function u(p){return $b(e,m,s,"definitionDestination","definitionDestinationLiteral","definitionDestinationLiteralMarker","definitionDestinationRaw","definitionDestinationString")(p)}function m(p){return e.attempt(P2,h,h)(p)}function h(p){return mn(p)?pn(e,f,"whitespace")(p):f(p)}function f(p){return p===null||Wt(p)?(e.exit("definition"),a.parser.defined.push(r),n(p)):s(p)}}function I2(e,n,s){return a;function a(c){return Pn(c)?ao(e,r)(c):s(c)}function r(c){return Lb(e,o,s,"definitionTitle","definitionTitleMarker","definitionTitleString")(c)}function o(c){return mn(c)?pn(e,l,"whitespace")(c):l(c)}function l(c){return c===null||Wt(c)?n(c):s(c)}}const T2={name:"hardBreakEscape",tokenize:$2};function $2(e,n,s){return a;function a(o){return e.enter("hardBreakEscape"),e.consume(o),r}function r(o){return Wt(o)?(e.exit("hardBreakEscape"),n(o)):s(o)}}const D2={name:"headingAtx",resolve:L2,tokenize:O2};function L2(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"},Gs(e,a,s-a+1,[["enter",r,n],["enter",o,n],["exit",o,n],["exit",r,n]])),e}function O2(e,n,s){let a=0;return r;function r(m){return e.enter("atxHeading"),o(m)}function o(m){return e.enter("atxHeadingSequence"),l(m)}function l(m){return m===35&&a++<6?(e.consume(m),l):m===null||Pn(m)?(e.exit("atxHeadingSequence"),c(m)):s(m)}function c(m){return m===35?(e.enter("atxHeadingSequence"),d(m)):m===null||Wt(m)?(e.exit("atxHeading"),n(m)):mn(m)?pn(e,c,"whitespace")(m):(e.enter("atxHeadingText"),u(m))}function d(m){return m===35?(e.consume(m),d):(e.exit("atxHeadingSequence"),c(m))}function u(m){return m===null||m===35||Pn(m)?(e.exit("atxHeadingText"),c(m)):(e.consume(m),u)}}const z2=["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"],Rh=["pre","script","style","textarea"],F2={concrete:!0,name:"htmlFlow",resolveTo:H2,tokenize:q2},U2={partial:!0,tokenize:W2},B2={partial:!0,tokenize:V2};function H2(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 q2(e,n,s){const a=this;let r,o,l,c,d;return u;function u(N){return m(N)}function m(N){return e.enter("htmlFlow"),e.enter("htmlFlowData"),e.consume(N),h}function h(N){return N===33?(e.consume(N),f):N===47?(e.consume(N),o=!0,x):N===63?(e.consume(N),r=3,a.interrupt?n:A):Ls(N)?(e.consume(N),l=String.fromCharCode(N),w):s(N)}function f(N){return N===45?(e.consume(N),r=2,p):N===91?(e.consume(N),r=5,c=0,g):Ls(N)?(e.consume(N),r=4,a.interrupt?n:A):s(N)}function p(N){return N===45?(e.consume(N),a.interrupt?n:A):s(N)}function g(N){const G="CDATA[";return N===G.charCodeAt(c++)?(e.consume(N),c===G.length?a.interrupt?n:L:g):s(N)}function x(N){return Ls(N)?(e.consume(N),l=String.fromCharCode(N),w):s(N)}function w(N){if(N===null||N===47||N===62||Pn(N)){const G=N===47,xe=l.toLowerCase();return!G&&!o&&Rh.includes(xe)?(r=1,a.interrupt?n(N):L(N)):z2.includes(l.toLowerCase())?(r=6,G?(e.consume(N),b):a.interrupt?n(N):L(N)):(r=7,a.interrupt&&!a.parser.lazy[a.now().line]?s(N):o?y(N):S(N))}return N===45||As(N)?(e.consume(N),l+=String.fromCharCode(N),w):s(N)}function b(N){return N===62?(e.consume(N),a.interrupt?n:L):s(N)}function y(N){return mn(N)?(e.consume(N),y):E(N)}function S(N){return N===47?(e.consume(N),E):N===58||N===95||Ls(N)?(e.consume(N),k):mn(N)?(e.consume(N),S):E(N)}function k(N){return N===45||N===46||N===58||N===95||As(N)?(e.consume(N),k):C(N)}function C(N){return N===61?(e.consume(N),v):mn(N)?(e.consume(N),C):S(N)}function v(N){return N===null||N===60||N===61||N===62||N===96?s(N):N===34||N===39?(e.consume(N),d=N,j):mn(N)?(e.consume(N),v):P(N)}function j(N){return N===d?(e.consume(N),d=null,U):N===null||Wt(N)?s(N):(e.consume(N),j)}function P(N){return N===null||N===34||N===39||N===47||N===60||N===61||N===62||N===96||Pn(N)?C(N):(e.consume(N),P)}function U(N){return N===47||N===62||mn(N)?S(N):s(N)}function E(N){return N===62?(e.consume(N),R):s(N)}function R(N){return N===null||Wt(N)?L(N):mn(N)?(e.consume(N),R):s(N)}function L(N){return N===45&&r===2?(e.consume(N),q):N===60&&r===1?(e.consume(N),te):N===62&&r===4?(e.consume(N),I):N===63&&r===3?(e.consume(N),A):N===93&&r===5?(e.consume(N),K):Wt(N)&&(r===6||r===7)?(e.exit("htmlFlowData"),e.check(U2,$,F)(N)):N===null||Wt(N)?(e.exit("htmlFlowData"),F(N)):(e.consume(N),L)}function F(N){return e.check(B2,M,$)(N)}function M(N){return e.enter("lineEnding"),e.consume(N),e.exit("lineEnding"),O}function O(N){return N===null||Wt(N)?F(N):(e.enter("htmlFlowData"),L(N))}function q(N){return N===45?(e.consume(N),A):L(N)}function te(N){return N===47?(e.consume(N),l="",Z):L(N)}function Z(N){if(N===62){const G=l.toLowerCase();return Rh.includes(G)?(e.consume(N),I):L(N)}return Ls(N)&&l.length<8?(e.consume(N),l+=String.fromCharCode(N),Z):L(N)}function K(N){return N===93?(e.consume(N),A):L(N)}function A(N){return N===62?(e.consume(N),I):N===45&&r===2?(e.consume(N),A):L(N)}function I(N){return N===null||Wt(N)?(e.exit("htmlFlowData"),$(N)):(e.consume(N),I)}function $(N){return e.exit("htmlFlow"),n(N)}}function V2(e,n,s){const a=this;return r;function r(l){return Wt(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 W2(e,n,s){return a;function a(r){return e.enter("lineEnding"),e.consume(r),e.exit("lineEnding"),e.attempt(To,n,s)}}const K2={name:"htmlText",tokenize:G2};function G2(e,n,s){const a=this;let r,o,l;return c;function c(A){return e.enter("htmlText"),e.enter("htmlTextData"),e.consume(A),d}function d(A){return A===33?(e.consume(A),u):A===47?(e.consume(A),C):A===63?(e.consume(A),S):Ls(A)?(e.consume(A),P):s(A)}function u(A){return A===45?(e.consume(A),m):A===91?(e.consume(A),o=0,g):Ls(A)?(e.consume(A),y):s(A)}function m(A){return A===45?(e.consume(A),p):s(A)}function h(A){return A===null?s(A):A===45?(e.consume(A),f):Wt(A)?(l=h,te(A)):(e.consume(A),h)}function f(A){return A===45?(e.consume(A),p):h(A)}function p(A){return A===62?q(A):A===45?f(A):h(A)}function g(A){const I="CDATA[";return A===I.charCodeAt(o++)?(e.consume(A),o===I.length?x:g):s(A)}function x(A){return A===null?s(A):A===93?(e.consume(A),w):Wt(A)?(l=x,te(A)):(e.consume(A),x)}function w(A){return A===93?(e.consume(A),b):x(A)}function b(A){return A===62?q(A):A===93?(e.consume(A),b):x(A)}function y(A){return A===null||A===62?q(A):Wt(A)?(l=y,te(A)):(e.consume(A),y)}function S(A){return A===null?s(A):A===63?(e.consume(A),k):Wt(A)?(l=S,te(A)):(e.consume(A),S)}function k(A){return A===62?q(A):S(A)}function C(A){return Ls(A)?(e.consume(A),v):s(A)}function v(A){return A===45||As(A)?(e.consume(A),v):j(A)}function j(A){return Wt(A)?(l=j,te(A)):mn(A)?(e.consume(A),j):q(A)}function P(A){return A===45||As(A)?(e.consume(A),P):A===47||A===62||Pn(A)?U(A):s(A)}function U(A){return A===47?(e.consume(A),q):A===58||A===95||Ls(A)?(e.consume(A),E):Wt(A)?(l=U,te(A)):mn(A)?(e.consume(A),U):q(A)}function E(A){return A===45||A===46||A===58||A===95||As(A)?(e.consume(A),E):R(A)}function R(A){return A===61?(e.consume(A),L):Wt(A)?(l=R,te(A)):mn(A)?(e.consume(A),R):U(A)}function L(A){return A===null||A===60||A===61||A===62||A===96?s(A):A===34||A===39?(e.consume(A),r=A,F):Wt(A)?(l=L,te(A)):mn(A)?(e.consume(A),L):(e.consume(A),M)}function F(A){return A===r?(e.consume(A),r=void 0,O):A===null?s(A):Wt(A)?(l=F,te(A)):(e.consume(A),F)}function M(A){return A===null||A===34||A===39||A===60||A===61||A===96?s(A):A===47||A===62||Pn(A)?U(A):(e.consume(A),M)}function O(A){return A===47||A===62||Pn(A)?U(A):s(A)}function q(A){return A===62?(e.consume(A),e.exit("htmlTextData"),e.exit("htmlText"),n):s(A)}function te(A){return e.exit("htmlTextData"),e.enter("lineEnding"),e.consume(A),e.exit("lineEnding"),Z}function Z(A){return mn(A)?pn(e,K,"linePrefix",a.parser.constructs.disable.null.includes("codeIndented")?void 0:4)(A):K(A)}function K(A){return e.enter("htmlTextData"),l(A)}}const Iu={name:"labelEnd",resolveAll:X2,resolveTo:Z2,tokenize:e_},J2={tokenize:t_},Y2={tokenize:n_},Q2={tokenize:s_};function X2(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&&Gs(e,0,e.length,s),e}function Z2(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}},m={type:"labelText",start:{...e[o+a+2][1].end},end:{...e[l-2][1].start}};return c=[["enter",d,n],["enter",u,n]],c=ni(c,e.slice(o+1,o+a+3)),c=ni(c,[["enter",m,n]]),c=ni(c,ic(n.parser.constructs.insideSpan.null,e.slice(o+a+4,l-3),n)),c=ni(c,[["exit",m,n],e[l-2],e[l-1],["exit",u,n]]),c=ni(c,e.slice(l+1)),c=ni(c,[["exit",d,n]]),Gs(e,o,e.length,c),e}function e_(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?h(f):(l=a.parser.defined.includes(fi(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(J2,m,l?m:h)(f):f===91?e.attempt(Y2,m,l?u:h)(f):l?m(f):h(f)}function u(f){return e.attempt(Q2,m,h)(f)}function m(f){return n(f)}function h(f){return o._balanced=!0,s(f)}}function t_(e,n,s){return a;function a(h){return e.enter("resource"),e.enter("resourceMarker"),e.consume(h),e.exit("resourceMarker"),r}function r(h){return Pn(h)?ao(e,o)(h):o(h)}function o(h){return h===41?m(h):$b(e,l,c,"resourceDestination","resourceDestinationLiteral","resourceDestinationLiteralMarker","resourceDestinationRaw","resourceDestinationString",32)(h)}function l(h){return Pn(h)?ao(e,d)(h):m(h)}function c(h){return s(h)}function d(h){return h===34||h===39||h===40?Lb(e,u,s,"resourceTitle","resourceTitleMarker","resourceTitleString")(h):m(h)}function u(h){return Pn(h)?ao(e,m)(h):m(h)}function m(h){return h===41?(e.enter("resourceMarker"),e.consume(h),e.exit("resourceMarker"),e.exit("resource"),n):s(h)}}function n_(e,n,s){const a=this;return r;function r(c){return Db.call(a,e,o,l,"reference","referenceMarker","referenceString")(c)}function o(c){return a.parser.defined.includes(fi(a.sliceSerialize(a.events[a.events.length-1][1]).slice(1,-1)))?n(c):s(c)}function l(c){return s(c)}}function s_(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 i_={name:"labelStartImage",resolveAll:Iu.resolveAll,tokenize:a_};function a_(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 r_={name:"labelStartLink",resolveAll:Iu.resolveAll,tokenize:o_};function o_(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 Ic={name:"lineEnding",tokenize:l_};function l_(e,n){return s;function s(a){return e.enter("lineEnding"),e.consume(a),e.exit("lineEnding"),pn(e,n,"linePrefix")}}const vl={name:"thematicBreak",tokenize:c_};function c_(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||Wt(u))?(e.exit("thematicBreak"),n(u)):s(u)}function d(u){return u===r?(e.consume(u),a++,d):(e.exit("thematicBreakSequence"),mn(u)?pn(e,c,"whitespace")(u):c(u))}}const zs={continuation:{tokenize:h_},exit:f_,name:"list",tokenize:m_},d_={partial:!0,tokenize:g_},u_={partial:!0,tokenize:p_};function m_(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:Vd(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(vl,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 Vd(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(To,a.interrupt?s:m,e.attempt(d_,f,h))}function m(p){return a.containerState.initialBlankLine=!0,o++,f(p)}function h(p){return mn(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 h_(e,n,s){const a=this;return a.containerState._closeFlow=void 0,e.check(To,r,o);function r(c){return a.containerState.furtherBlankLines=a.containerState.furtherBlankLines||a.containerState.initialBlankLine,pn(e,n,"listItemIndent",a.containerState.size+1)(c)}function o(c){return a.containerState.furtherBlankLines||!mn(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(u_,n,l)(c))}function l(c){return a.containerState._closeFlow=!0,a.interrupt=void 0,pn(e,e.attempt(zs,n,s),"linePrefix",a.parser.constructs.disable.null.includes("codeIndented")?void 0:4)(c)}}function p_(e,n,s){const a=this;return pn(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 f_(e){e.exit(this.containerState.type)}function g_(e,n,s){const a=this;return pn(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!mn(o)&&l&&l[1].type==="listItemPrefixWhitespace"?n(o):s(o)}}const Ih={name:"setextUnderline",resolveTo:b_,tokenize:x_};function b_(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 x_(e,n,s){const a=this;let r;return o;function o(u){let m=a.events.length,h;for(;m--;)if(a.events[m][1].type!=="lineEnding"&&a.events[m][1].type!=="linePrefix"&&a.events[m][1].type!=="content"){h=a.events[m][1].type==="paragraph";break}return!a.parser.lazy[a.now().line]&&(a.interrupt||h)?(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"),mn(u)?pn(e,d,"lineSuffix")(u):d(u))}function d(u){return u===null||Wt(u)?(e.exit("setextHeadingLine"),n(u)):s(u)}}const v_={tokenize:y_};function y_(e){const n=this,s=e.attempt(To,a,e.attempt(this.parser.constructs.flowInitial,r,pn(e,e.attempt(this.parser.constructs.flow,r,e.attempt(S2,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 w_={resolveAll:zb()},k_=Ob("string"),j_=Ob("text");function Ob(e){return{resolveAll:zb(e==="text"?N_: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(m){return u(m)?o(m):c(m)}function c(m){if(m===null){s.consume(m);return}return s.enter("data"),s.consume(m),d}function d(m){return u(m)?(s.exit("data"),o(m)):(s.consume(m),d)}function u(m){if(m===null)return!0;const h=r[m];let f=-1;if(h)for(;++f<h.length;){const p=h[f];if(!p.previous||p.previous.call(a,a.previous))return!0}return!1}}}function zb(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 N_(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 S_={42:zs,43:zs,45:zs,48:zs,49:zs,50:zs,51:zs,52:zs,53:zs,54:zs,55:zs,56:zs,57:zs,62:Pb},C_={91:A2},E_={[-2]:Rc,[-1]:Rc,32:Rc},__={35:D2,42:vl,45:[Ih,vl],60:F2,61:Ih,95:vl,96:Ph,126:Ph},M_={38:Ib,92:Rb},A_={[-5]:Ic,[-4]:Ic,[-3]:Ic,33:i_,38:Ib,42:Wd,60:[r2,K2],91:r_,92:[T2,Rb],93:Iu,95:Wd,96:v2},P_={null:[Wd,w_]},R_={null:[42,95]},I_={null:[]},T_=Object.freeze(Object.defineProperty({__proto__:null,attentionMarkers:R_,contentInitial:C_,disable:I_,document:S_,flow:__,flowInitial:E_,insideSpan:P_,string:M_,text:A_},Symbol.toStringTag,{value:"Module"}));function $_(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:j(C),check:j(v),consume:y,enter:S,exit:k,interrupt:j(v,{interrupt:!0})},u={code:null,containerState:{},defineSkip:x,events:[],now:g,parser:e,previous:null,sliceSerialize:f,sliceStream:p,write:h};let m=n.tokenize.call(u,d);return n.resolveAll&&o.push(n),u;function h(R){return l=ni(l,R),w(),l[l.length-1]!==null?[]:(P(n,0),u.events=ic(o,u.events,u),u.events)}function f(R,L){return L_(p(R),L)}function p(R){return D_(l,R)}function g(){const{_bufferIndex:R,_index:L,line:F,column:M,offset:O}=a;return{_bufferIndex:R,_index:L,line:F,column:M,offset:O}}function x(R){r[R.line]=R.column,E()}function w(){let R;for(;a._index<l.length;){const L=l[a._index];if(typeof L=="string")for(R=a._index,a._bufferIndex<0&&(a._bufferIndex=0);a._index===R&&a._bufferIndex<L.length;)b(L.charCodeAt(a._bufferIndex));else b(L)}}function b(R){m=m(R)}function y(R){Wt(R)?(a.line++,a.column=1,a.offset+=R===-3?2:1,E()):R!==-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=R}function S(R,L){const F=L||{};return F.type=R,F.start=g(),u.events.push(["enter",F,u]),c.push(F),F}function k(R){const L=c.pop();return L.end=g(),u.events.push(["exit",L,u]),L}function C(R,L){P(R,L.from)}function v(R,L){L.restore()}function j(R,L){return F;function F(M,O,q){let te,Z,K,A;return Array.isArray(M)?$(M):"tokenize"in M?$([M]):I(M);function I(Se){return je;function je(se){const Ve=se!==null&&Se[se],ee=se!==null&&Se.null,ce=[...Array.isArray(Ve)?Ve:Ve?[Ve]:[],...Array.isArray(ee)?ee:ee?[ee]:[]];return $(ce)(se)}}function $(Se){return te=Se,Z=0,Se.length===0?q:N(Se[Z])}function N(Se){return je;function je(se){return A=U(),K=Se,Se.partial||(u.currentConstruct=Se),Se.name&&u.parser.constructs.disable.null.includes(Se.name)?xe():Se.tokenize.call(L?Object.assign(Object.create(u),L):u,d,G,xe)(se)}}function G(Se){return R(K,A),O}function xe(Se){return A.restore(),++Z<te.length?N(te[Z]):q}}}function P(R,L){R.resolveAll&&!o.includes(R)&&o.push(R),R.resolve&&Gs(u.events,L,u.events.length-L,R.resolve(u.events.slice(L),u)),R.resolveTo&&(u.events=R.resolveTo(u.events,u))}function U(){const R=g(),L=u.previous,F=u.currentConstruct,M=u.events.length,O=Array.from(c);return{from:M,restore:q};function q(){a=R,u.previous=L,u.currentConstruct=F,u.events.length=M,c=O,E()}}function E(){a.line in r&&a.column<2&&(a.column=r[a.line],a.offset+=r[a.line]-1)}}function D_(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 L_(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=`
653
- `;break}case-3:{l=`\r
654
- `;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 O_(e){const a={constructs:Mb([T_,...(e||{}).extensions||[]]),content:r(ZE),defined:[],document:r(t2),flow:r(v_),lazy:{},string:r(k_),text:r(j_)};return a;function r(o){return l;function l(c){return $_(a,o,c)}}}function z_(e){for(;!Tb(e););return e}const Th=/[\0\t\n\r]/g;function F_(){let e=1,n="",s=!0,a;return r;function r(o,l,c){const d=[];let u,m,h,f,p;for(o=n+(typeof o=="string"?o.toString():new TextDecoder(l||void 0).decode(o)),h=0,n="",s&&(o.charCodeAt(0)===65279&&h++,s=void 0);h<o.length;){if(Th.lastIndex=h,u=Th.exec(o),f=u&&u.index!==void 0?u.index:o.length,p=o.charCodeAt(f),!u){n=o.slice(h);break}if(p===10&&h===f&&a)d.push(-3),a=void 0;else switch(a&&(d.push(-5),a=void 0),h<f&&(d.push(o.slice(h,f)),e+=f-h),p){case 0:{d.push(65533),e++;break}case 9:{for(m=Math.ceil(e/4)*4,d.push(-2);e++<m;)d.push(-1);break}case 10:{d.push(-4),e=1;break}default:a=!0,e=1}h=f+1}return c&&(a&&d.push(-5),n&&d.push(n),d.push(null)),d}}const U_=/\\([!-/:-@[-`{-~])|&(#(?:\d{1,7}|x[\da-f]{1,6})|[\da-z]{1,31});/gi;function B_(e){return e.replace(U_,H_)}function H_(e,n,s){if(n)return n;if(s.charCodeAt(0)===35){const r=s.charCodeAt(1),o=r===120||r===88;return Ab(s.slice(o?2:1),o?16:10)}return Ru(s)||e}const Fb={}.hasOwnProperty;function q_(e,n,s){return n&&typeof n=="object"&&(s=n,n=void 0),V_(s)(z_(O_(s).document().write(F_()(e,n,!0))))}function V_(e){const n={transforms:[],canContainEols:["emphasis","fragment","heading","paragraph","strong"],enter:{autolink:o(ke),autolinkProtocol:U,autolinkEmail:U,atxHeading:o(B),blockQuote:o(ee),characterEscape:U,characterReference:U,codeFenced:o(ce),codeFencedFenceInfo:l,codeFencedFenceMeta:l,codeIndented:o(ce,l),codeText:o(ne,l),codeTextData:U,data:U,codeFlowValue:U,definition:o(re),definitionDestinationString:l,definitionLabelString:l,definitionTitleString:l,emphasis:o(J),hardBreakEscape:o(ye),hardBreakTrailing:o(ye),htmlFlow:o(Ce,l),htmlFlowData:U,htmlText:o(Ce,l),htmlTextData:U,image:o(H),label:l,link:o(ke),listItem:o(Ae),listItemValue:f,listOrdered:o(pe,h),listUnordered:o(pe),paragraph:o(Oe),reference:N,referenceString:l,resourceDestinationString:l,resourceTitleString:l,setextHeading:o(B),strong:o(He),thematicBreak:o(Fe)},exit:{atxHeading:d(),atxHeadingSequence:C,autolink:d(),autolinkEmail:Ve,autolinkProtocol:se,blockQuote:d(),characterEscapeValue:E,characterReferenceMarkerHexadecimal:xe,characterReferenceMarkerNumeric:xe,characterReferenceValue:Se,characterReference:je,codeFenced:d(w),codeFencedFence:x,codeFencedFenceInfo:p,codeFencedFenceMeta:g,codeFlowValue:E,codeIndented:d(b),codeText:d(O),codeTextData:E,data:E,definition:d(),definitionDestinationString:k,definitionLabelString:y,definitionTitleString:S,emphasis:d(),hardBreakEscape:d(L),hardBreakTrailing:d(L),htmlFlow:d(F),htmlFlowData:E,htmlText:d(M),htmlTextData:E,image:d(te),label:K,labelText:Z,lineEnding:R,link:d(q),listItem:d(),listOrdered:d(),listUnordered:d(),paragraph:d(),referenceString:G,resourceDestinationString:A,resourceTitleString:I,resource:$,setextHeading:d(P),setextHeadingLineSequence:j,setextHeadingText:v,strong:d(),thematicBreak:d()}};Ub(n,(e||{}).mdastExtensions||[]);const s={};return a;function a(fe){let $e={type:"root",children:[]};const De={stack:[$e],tokenStack:[],config:n,enter:c,exit:u,buffer:l,resume:m,data:s},ot=[];let Be=-1;for(;++Be<fe.length;)if(fe[Be][1].type==="listOrdered"||fe[Be][1].type==="listUnordered")if(fe[Be][0]==="enter")ot.push(Be);else{const we=ot.pop();Be=r(fe,we,Be)}for(Be=-1;++Be<fe.length;){const we=n[fe[Be][0]];Fb.call(we,fe[Be][1].type)&&we[fe[Be][1].type].call(Object.assign({sliceSerialize:fe[Be][2].sliceSerialize},De),fe[Be][1])}if(De.tokenStack.length>0){const we=De.tokenStack[De.tokenStack.length-1];(we[1]||$h).call(De,void 0,we[0])}for($e.position={start:Yi(fe.length>0?fe[0][1].start:{line:1,column:1,offset:0}),end:Yi(fe.length>0?fe[fe.length-2][1].end:{line:1,column:1,offset:0})},Be=-1;++Be<n.transforms.length;)$e=n.transforms[Be]($e)||$e;return $e}function r(fe,$e,De){let ot=$e-1,Be=-1,we=!1,Q,_e,lt,ht;for(;++ot<=De;){const mt=fe[ot];switch(mt[1].type){case"listUnordered":case"listOrdered":case"blockQuote":{mt[0]==="enter"?Be++:Be--,ht=void 0;break}case"lineEndingBlank":{mt[0]==="enter"&&(Q&&!ht&&!Be&&!lt&&(lt=ot),ht=void 0);break}case"linePrefix":case"listItemValue":case"listItemMarker":case"listItemPrefix":case"listItemPrefixWhitespace":break;default:ht=void 0}if(!Be&&mt[0]==="enter"&&mt[1].type==="listItemPrefix"||Be===-1&&mt[0]==="exit"&&(mt[1].type==="listUnordered"||mt[1].type==="listOrdered")){if(Q){let xt=ot;for(_e=void 0;xt--;){const Ie=fe[xt];if(Ie[1].type==="lineEnding"||Ie[1].type==="lineEndingBlank"){if(Ie[0]==="exit")continue;_e&&(fe[_e][1].type="lineEndingBlank",we=!0),Ie[1].type="lineEnding",_e=xt}else if(!(Ie[1].type==="linePrefix"||Ie[1].type==="blockQuotePrefix"||Ie[1].type==="blockQuotePrefixWhitespace"||Ie[1].type==="blockQuoteMarker"||Ie[1].type==="listItemIndent"))break}lt&&(!_e||lt<_e)&&(Q._spread=!0),Q.end=Object.assign({},_e?fe[_e][1].start:mt[1].end),fe.splice(_e||ot,0,["exit",Q,mt[2]]),ot++,De++}if(mt[1].type==="listItemPrefix"){const xt={type:"listItem",_spread:!1,start:Object.assign({},mt[1].start),end:void 0};Q=xt,fe.splice(ot,0,["enter",xt,mt[2]]),ot++,De++,lt=void 0,ht=!0}}}return fe[$e][1]._spread=we,De}function o(fe,$e){return De;function De(ot){c.call(this,fe(ot),ot),$e&&$e.call(this,ot)}}function l(){this.stack.push({type:"fragment",children:[]})}function c(fe,$e,De){this.stack[this.stack.length-1].children.push(fe),this.stack.push(fe),this.tokenStack.push([$e,De||void 0]),fe.position={start:Yi($e.start),end:void 0}}function d(fe){return $e;function $e(De){fe&&fe.call(this,De),u.call(this,De)}}function u(fe,$e){const De=this.stack.pop(),ot=this.tokenStack.pop();if(ot)ot[0].type!==fe.type&&($e?$e.call(this,fe,ot[0]):(ot[1]||$h).call(this,fe,ot[0]));else throw new Error("Cannot close `"+fe.type+"` ("+io({start:fe.start,end:fe.end})+"): it’s not open");De.position.end=Yi(fe.end)}function m(){return Pu(this.stack.pop())}function h(){this.data.expectingFirstListItemValue=!0}function f(fe){if(this.data.expectingFirstListItemValue){const $e=this.stack[this.stack.length-2];$e.start=Number.parseInt(this.sliceSerialize(fe),10),this.data.expectingFirstListItemValue=void 0}}function p(){const fe=this.resume(),$e=this.stack[this.stack.length-1];$e.lang=fe}function g(){const fe=this.resume(),$e=this.stack[this.stack.length-1];$e.meta=fe}function x(){this.data.flowCodeInside||(this.buffer(),this.data.flowCodeInside=!0)}function w(){const fe=this.resume(),$e=this.stack[this.stack.length-1];$e.value=fe.replace(/^(\r?\n|\r)|(\r?\n|\r)$/g,""),this.data.flowCodeInside=void 0}function b(){const fe=this.resume(),$e=this.stack[this.stack.length-1];$e.value=fe.replace(/(\r?\n|\r)$/g,"")}function y(fe){const $e=this.resume(),De=this.stack[this.stack.length-1];De.label=$e,De.identifier=fi(this.sliceSerialize(fe)).toLowerCase()}function S(){const fe=this.resume(),$e=this.stack[this.stack.length-1];$e.title=fe}function k(){const fe=this.resume(),$e=this.stack[this.stack.length-1];$e.url=fe}function C(fe){const $e=this.stack[this.stack.length-1];if(!$e.depth){const De=this.sliceSerialize(fe).length;$e.depth=De}}function v(){this.data.setextHeadingSlurpLineEnding=!0}function j(fe){const $e=this.stack[this.stack.length-1];$e.depth=this.sliceSerialize(fe).codePointAt(0)===61?1:2}function P(){this.data.setextHeadingSlurpLineEnding=void 0}function U(fe){const De=this.stack[this.stack.length-1].children;let ot=De[De.length-1];(!ot||ot.type!=="text")&&(ot=dt(),ot.position={start:Yi(fe.start),end:void 0},De.push(ot)),this.stack.push(ot)}function E(fe){const $e=this.stack.pop();$e.value+=this.sliceSerialize(fe),$e.position.end=Yi(fe.end)}function R(fe){const $e=this.stack[this.stack.length-1];if(this.data.atHardBreak){const De=$e.children[$e.children.length-1];De.position.end=Yi(fe.end),this.data.atHardBreak=void 0;return}!this.data.setextHeadingSlurpLineEnding&&n.canContainEols.includes($e.type)&&(U.call(this,fe),E.call(this,fe))}function L(){this.data.atHardBreak=!0}function F(){const fe=this.resume(),$e=this.stack[this.stack.length-1];$e.value=fe}function M(){const fe=this.resume(),$e=this.stack[this.stack.length-1];$e.value=fe}function O(){const fe=this.resume(),$e=this.stack[this.stack.length-1];$e.value=fe}function q(){const fe=this.stack[this.stack.length-1];if(this.data.inReference){const $e=this.data.referenceType||"shortcut";fe.type+="Reference",fe.referenceType=$e,delete fe.url,delete fe.title}else delete fe.identifier,delete fe.label;this.data.referenceType=void 0}function te(){const fe=this.stack[this.stack.length-1];if(this.data.inReference){const $e=this.data.referenceType||"shortcut";fe.type+="Reference",fe.referenceType=$e,delete fe.url,delete fe.title}else delete fe.identifier,delete fe.label;this.data.referenceType=void 0}function Z(fe){const $e=this.sliceSerialize(fe),De=this.stack[this.stack.length-2];De.label=B_($e),De.identifier=fi($e).toLowerCase()}function K(){const fe=this.stack[this.stack.length-1],$e=this.resume(),De=this.stack[this.stack.length-1];if(this.data.inReference=!0,De.type==="link"){const ot=fe.children;De.children=ot}else De.alt=$e}function A(){const fe=this.resume(),$e=this.stack[this.stack.length-1];$e.url=fe}function I(){const fe=this.resume(),$e=this.stack[this.stack.length-1];$e.title=fe}function $(){this.data.inReference=void 0}function N(){this.data.referenceType="collapsed"}function G(fe){const $e=this.resume(),De=this.stack[this.stack.length-1];De.label=$e,De.identifier=fi(this.sliceSerialize(fe)).toLowerCase(),this.data.referenceType="full"}function xe(fe){this.data.characterReferenceType=fe.type}function Se(fe){const $e=this.sliceSerialize(fe),De=this.data.characterReferenceType;let ot;De?(ot=Ab($e,De==="characterReferenceMarkerNumeric"?10:16),this.data.characterReferenceType=void 0):ot=Ru($e);const Be=this.stack[this.stack.length-1];Be.value+=ot}function je(fe){const $e=this.stack.pop();$e.position.end=Yi(fe.end)}function se(fe){E.call(this,fe);const $e=this.stack[this.stack.length-1];$e.url=this.sliceSerialize(fe)}function Ve(fe){E.call(this,fe);const $e=this.stack[this.stack.length-1];$e.url="mailto:"+this.sliceSerialize(fe)}function ee(){return{type:"blockquote",children:[]}}function ce(){return{type:"code",lang:null,meta:null,value:""}}function ne(){return{type:"inlineCode",value:""}}function re(){return{type:"definition",identifier:"",label:null,title:null,url:""}}function J(){return{type:"emphasis",children:[]}}function B(){return{type:"heading",depth:0,children:[]}}function ye(){return{type:"break"}}function Ce(){return{type:"html",value:""}}function H(){return{type:"image",title:null,url:"",alt:null}}function ke(){return{type:"link",title:null,url:"",children:[]}}function pe(fe){return{type:"list",ordered:fe.type==="listOrdered",start:null,spread:fe._spread,children:[]}}function Ae(fe){return{type:"listItem",spread:fe._spread,checked:null,children:[]}}function Oe(){return{type:"paragraph",children:[]}}function He(){return{type:"strong",children:[]}}function dt(){return{type:"text",value:""}}function Fe(){return{type:"thematicBreak"}}}function Yi(e){return{line:e.line,column:e.column,offset:e.offset}}function Ub(e,n){let s=-1;for(;++s<n.length;){const a=n[s];Array.isArray(a)?Ub(e,a):W_(e,a)}}function W_(e,n){let s;for(s in n)if(Fb.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 $h(e,n){throw e?new Error("Cannot close `"+e.type+"` ("+io({start:e.start,end:e.end})+"): a different token (`"+n.type+"`, "+io({start:n.start,end:n.end})+") is open"):new Error("Cannot close document, a token (`"+n.type+"`, "+io({start:n.start,end:n.end})+") is still open")}function K_(e){const n=this;n.parser=s;function s(a){return q_(a,{...n.data("settings"),...e,extensions:n.data("micromarkExtensions")||[],mdastExtensions:n.data("fromMarkdownExtensions")||[]})}}function G_(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 J_(e,n){const s={type:"element",tagName:"br",properties:{},children:[]};return e.patch(n,s),[e.applyData(n,s),{type:"text",value:`
655
- `}]}function Y_(e,n){const s=n.value?n.value+`
656
- `:"",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 Q_(e,n){const s={type:"element",tagName:"del",properties:{},children:e.all(n)};return e.patch(n,s),e.applyData(n,s)}function X_(e,n){const s={type:"element",tagName:"em",properties:{},children:e.all(n)};return e.patch(n,s),e.applyData(n,s)}function Z_(e,n){const s=typeof e.options.clobberPrefix=="string"?e.options.clobberPrefix:"user-content-",a=String(n.identifier).toUpperCase(),r=Er(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 eM(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 tM(e,n){if(e.options.allowDangerousHtml){const s={type:"raw",value:n.value};return e.patch(n,s),e.applyData(n,s)}}function Bb(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 nM(e,n){const s=String(n.identifier).toUpperCase(),a=e.definitionById.get(s);if(!a)return Bb(e,n);const r={src:Er(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 sM(e,n){const s={src:Er(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 iM(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 aM(e,n){const s=String(n.identifier).toUpperCase(),a=e.definitionById.get(s);if(!a)return Bb(e,n);const r={href:Er(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 rM(e,n){const s={href:Er(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 oM(e,n,s){const a=e.all(n),r=s?lM(s):Hb(n),o={},l=[];if(typeof n.checked=="boolean"){const m=a[0];let h;m&&m.type==="element"&&m.tagName==="p"?h=m:(h={type:"element",tagName:"p",properties:{},children:[]},a.unshift(h)),h.children.length>0&&h.children.unshift({type:"text",value:" "}),h.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 m=a[c];(r||c!==0||m.type!=="element"||m.tagName!=="p")&&l.push({type:"text",value:`
657
- `}),m.type==="element"&&m.tagName==="p"&&!r?l.push(...m.children):l.push(m)}const d=a[a.length-1];d&&(r||d.type!=="element"||d.tagName!=="p")&&l.push({type:"text",value:`
658
- `});const u={type:"element",tagName:"li",properties:o,children:l};return e.patch(n,u),e.applyData(n,u)}function lM(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=Hb(s[a])}return n}function Hb(e){const n=e.spread;return n??e.children.length>1}function cM(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 dM(e,n){const s={type:"element",tagName:"p",properties:{},children:e.all(n)};return e.patch(n,s),e.applyData(n,s)}function uM(e,n){const s={type:"root",children:e.wrap(e.all(n))};return e.patch(n,s),e.applyData(n,s)}function mM(e,n){const s={type:"element",tagName:"strong",properties:{},children:e.all(n)};return e.patch(n,s),e.applyData(n,s)}function hM(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=Eu(n.children[1]),d=kb(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 pM(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 h=n.children[d],f={},p=l?l[d]:void 0;p&&(f.align=p);let g={type:"element",tagName:o,properties:f,children:[]};h&&(g.children=e.all(h),e.patch(h,g),g=e.applyData(h,g)),u.push(g)}const m={type:"element",tagName:"tr",properties:{},children:e.wrap(u,!0)};return e.patch(n,m),e.applyData(n,m)}function fM(e,n){const s={type:"element",tagName:"td",properties:{},children:e.all(n)};return e.patch(n,s),e.applyData(n,s)}const Dh=9,Lh=32;function gM(e){const n=String(e),s=/\r?\n|\r/g;let a=s.exec(n),r=0;const o=[];for(;a;)o.push(Oh(n.slice(r,a.index),r>0,!0),a[0]),r=a.index+a[0].length,a=s.exec(n);return o.push(Oh(n.slice(r),r>0,!1)),o.join("")}function Oh(e,n,s){let a=0,r=e.length;if(n){let o=e.codePointAt(a);for(;o===Dh||o===Lh;)a++,o=e.codePointAt(a)}if(s){let o=e.codePointAt(r-1);for(;o===Dh||o===Lh;)r--,o=e.codePointAt(r-1)}return r>a?e.slice(a,r):""}function bM(e,n){const s={type:"text",value:gM(String(n.value))};return e.patch(n,s),e.applyData(n,s)}function xM(e,n){const s={type:"element",tagName:"hr",properties:{},children:[]};return e.patch(n,s),e.applyData(n,s)}const vM={blockquote:G_,break:J_,code:Y_,delete:Q_,emphasis:X_,footnoteReference:Z_,heading:eM,html:tM,imageReference:nM,image:sM,inlineCode:iM,linkReference:aM,link:rM,listItem:oM,list:cM,paragraph:dM,root:uM,strong:mM,table:hM,tableCell:fM,tableRow:pM,text:bM,thematicBreak:xM,toml:Ho,yaml:Ho,definition:Ho,footnoteDefinition:Ho};function Ho(){}const qb=-1,ac=0,ro=1,Tl=2,Tu=3,$u=4,Du=5,Lu=6,Vb=7,Wb=8,zh=typeof self=="object"?self:globalThis,yM=(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 ac:case qb:return s(l,r);case ro:{const c=s([],r);for(const d of l)c.push(a(d));return c}case Tl:{const c=s({},r);for(const[d,u]of l)c[a(d)]=a(u);return c}case Tu:return s(new Date(l),r);case $u:{const{source:c,flags:d}=l;return s(new RegExp(c,d),r)}case Du:{const c=s(new Map,r);for(const[d,u]of l)c.set(a(d),a(u));return c}case Lu:{const c=s(new Set,r);for(const d of l)c.add(a(d));return c}case Vb:{const{name:c,message:d}=l;return s(new zh[c](d),r)}case Wb: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 zh[o](l),r)};return a},Fh=e=>yM(new Map,e)(0),Ya="",{toString:wM}={},{keys:kM}=Object,Lr=e=>{const n=typeof e;if(n!=="object"||!e)return[ac,n];const s=wM.call(e).slice(8,-1);switch(s){case"Array":return[ro,Ya];case"Object":return[Tl,Ya];case"Date":return[Tu,Ya];case"RegExp":return[$u,Ya];case"Map":return[Du,Ya];case"Set":return[Lu,Ya];case"DataView":return[ro,s]}return s.includes("Array")?[ro,s]:s.includes("Error")?[Vb,s]:[Tl,s]},qo=([e,n])=>e===ac&&(n==="function"||n==="symbol"),jM=(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]=Lr(l);switch(c){case ac:{let m=l;switch(d){case"bigint":c=Wb,m=l.toString();break;case"function":case"symbol":if(e)throw new TypeError("unable to serialize "+d);m=null;break;case"undefined":return r([qb],l)}return r([c,m],l)}case ro:{if(d){let f=l;return d==="DataView"?f=new Uint8Array(l.buffer):d==="ArrayBuffer"&&(f=new Uint8Array(l)),r([d,[...f]],l)}const m=[],h=r([c,m],l);for(const f of l)m.push(o(f));return h}case Tl:{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 m=[],h=r([c,m],l);for(const f of kM(l))(e||!qo(Lr(l[f])))&&m.push([o(f),o(l[f])]);return h}case Tu:return r([c,l.toISOString()],l);case $u:{const{source:m,flags:h}=l;return r([c,{source:m,flags:h}],l)}case Du:{const m=[],h=r([c,m],l);for(const[f,p]of l)(e||!(qo(Lr(f))||qo(Lr(p))))&&m.push([o(f),o(p)]);return h}case Lu:{const m=[],h=r([c,m],l);for(const f of l)(e||!qo(Lr(f)))&&m.push(o(f));return h}}const{message:u}=l;return r([c,{name:d,message:u}],l)};return o},Uh=(e,{json:n,lossy:s}={})=>{const a=[];return jM(!(n||s),!!n,new Map,a)(e),a},$l=typeof structuredClone=="function"?(e,n)=>n&&("json"in n||"lossy"in n)?Fh(Uh(e,n)):structuredClone(e):(e,n)=>Fh(Uh(e,n));function NM(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 SM(e,n){return"Back to reference "+(e+1)+(n>1?"-"+n:"")}function CM(e){const n=typeof e.options.clobberPrefix=="string"?e.options.clobberPrefix:"user-content-",s=e.options.footnoteBackContent||NM,a=e.options.footnoteBackLabel||SM,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 m=e.all(u),h=String(u.identifier).toUpperCase(),f=Er(h.toLowerCase());let p=0;const g=[],x=e.footnoteCounts.get(h);for(;x!==void 0&&++p<=x;){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 w=m[m.length-1];if(w&&w.type==="element"&&w.tagName==="p"){const y=w.children[w.children.length-1];y&&y.type==="text"?y.value+=" ":w.children.push({type:"text",value:" "}),w.children.push(...g)}else m.push(...g);const b={type:"element",tagName:"li",properties:{id:n+"fn-"+f},children:e.wrap(m,!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:{...$l(l),id:"footnote-label"},children:[{type:"text",value:r}]},{type:"text",value:`
659
- `},{type:"element",tagName:"ol",properties:{},children:e.wrap(c,!0)},{type:"text",value:`
660
- `}]}}const rc=(function(e){if(e==null)return AM;if(typeof e=="function")return oc(e);if(typeof e=="object")return Array.isArray(e)?EM(e):_M(e);if(typeof e=="string")return MM(e);throw new Error("Expected function, string, or object as test")});function EM(e){const n=[];let s=-1;for(;++s<e.length;)n[s]=rc(e[s]);return oc(a);function a(...r){let o=-1;for(;++o<n.length;)if(n[o].apply(this,r))return!0;return!1}}function _M(e){const n=e;return oc(s);function s(a){const r=a;let o;for(o in e)if(r[o]!==n[o])return!1;return!0}}function MM(e){return oc(n);function n(s){return s&&s.type===e}}function oc(e){return n;function n(s,a,r){return!!(PM(s)&&e.call(this,s,typeof a=="number"?a:void 0,r||void 0))}}function AM(){return!0}function PM(e){return e!==null&&typeof e=="object"&&"type"in e}const Kb=[],RM=!0,Kd=!1,IM="skip";function Gb(e,n,s,a){let r;typeof n=="function"&&typeof s!="function"?(a=s,s=n):r=n;const o=rc(r),l=a?-1:1;c(e,void 0,[])();function c(d,u,m){const h=d&&typeof d=="object"?d:{};if(typeof h.type=="string"){const p=typeof h.tagName=="string"?h.tagName:typeof h.name=="string"?h.name:void 0;Object.defineProperty(f,"name",{value:"node ("+(d.type+(p?"<"+p+">":""))+")"})}return f;function f(){let p=Kb,g,x,w;if((!n||o(d,u,m[m.length-1]||void 0))&&(p=TM(s(d,m)),p[0]===Kd))return p;if("children"in d&&d.children){const b=d;if(b.children&&p[0]!==IM)for(x=(a?b.children.length:-1)+l,w=m.concat(b);x>-1&&x<b.children.length;){const y=b.children[x];if(g=c(y,x,w)(),g[0]===Kd)return g;x=typeof g[1]=="number"?g[1]:x+l}}return p}}}function TM(e){return Array.isArray(e)?e:typeof e=="number"?[RM,e]:e==null?Kb:[e]}function Ou(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),Gb(e,o,c,r);function c(d,u){const m=u[u.length-1],h=m?m.children.indexOf(d):void 0;return l(d,h,m)}}const Gd={}.hasOwnProperty,$M={};function DM(e,n){const s=n||$M,a=new Map,r=new Map,o=new Map,l={...vM,...s.handlers},c={all:u,applyData:OM,definitionById:a,footnoteById:r,footnoteCounts:o,footnoteOrder:[],handlers:l,one:d,options:s,patch:LM,wrap:FM};return Ou(e,function(m){if(m.type==="definition"||m.type==="footnoteDefinition"){const h=m.type==="definition"?a:r,f=String(m.identifier).toUpperCase();h.has(f)||h.set(f,m)}}),c;function d(m,h){const f=m.type,p=c.handlers[f];if(Gd.call(c.handlers,f)&&p)return p(c,m,h);if(c.options.passThrough&&c.options.passThrough.includes(f)){if("children"in m){const{children:x,...w}=m,b=$l(w);return b.children=c.all(m),b}return $l(m)}return(c.options.unknownHandler||zM)(c,m,h)}function u(m){const h=[];if("children"in m){const f=m.children;let p=-1;for(;++p<f.length;){const g=c.one(f[p],m);if(g){if(p&&f[p-1].type==="break"&&(!Array.isArray(g)&&g.type==="text"&&(g.value=Bh(g.value)),!Array.isArray(g)&&g.type==="element")){const x=g.children[0];x&&x.type==="text"&&(x.value=Bh(x.value))}Array.isArray(g)?h.push(...g):h.push(g)}}}return h}}function LM(e,n){e.position&&(n.position=SE(e))}function OM(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,$l(o)),"children"in s&&s.children&&r!==null&&r!==void 0&&(s.children=r)}return s}function zM(e,n){const s=n.data||{},a="value"in n&&!(Gd.call(s,"hProperties")||Gd.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 FM(e,n){const s=[];let a=-1;for(n&&s.push({type:"text",value:`
661
- `});++a<e.length;)a&&s.push({type:"text",value:`
662
- `}),s.push(e[a]);return n&&e.length>0&&s.push({type:"text",value:`
663
- `}),s}function Bh(e){let n=0,s=e.charCodeAt(n);for(;s===9||s===32;)n++,s=e.charCodeAt(n);return e.slice(n)}function Hh(e,n){const s=DM(e,n),a=s.one(e,void 0),r=CM(s),o=Array.isArray(a)?{type:"root",children:a}:a||{type:"root",children:[]};return r&&o.children.push({type:"text",value:`
664
- `},r),o}function UM(e,n){return e&&"run"in e?async function(s,a){const r=Hh(s,{file:a,...n});await e.run(r,a)}:function(s,a){return Hh(s,{file:a,...e||n})}}function qh(e){if(e)throw e}var Tc,Vh;function BM(){if(Vh)return Tc;Vh=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 m=e.call(u,"constructor"),h=u.constructor&&u.constructor.prototype&&e.call(u.constructor.prototype,"isPrototypeOf");if(u.constructor&&!m&&!h)return!1;var f;for(f in u);return typeof f>"u"||e.call(u,f)},l=function(u,m){s&&m.name==="__proto__"?s(u,m.name,{enumerable:!0,configurable:!0,value:m.newValue,writable:!0}):u[m.name]=m.newValue},c=function(u,m){if(m==="__proto__")if(e.call(u,m)){if(a)return a(u,m).value}else return;return u[m]};return Tc=function d(){var u,m,h,f,p,g,x=arguments[0],w=1,b=arguments.length,y=!1;for(typeof x=="boolean"&&(y=x,x=arguments[1]||{},w=2),(x==null||typeof x!="object"&&typeof x!="function")&&(x={});w<b;++w)if(u=arguments[w],u!=null)for(m in u)h=c(x,m),f=c(u,m),x!==f&&(y&&f&&(o(f)||(p=r(f)))?(p?(p=!1,g=h&&r(h)?h:[]):g=h&&o(h)?h:{},l(x,{name:m,newValue:d(y,g,f)})):typeof f<"u"&&l(x,{name:m,newValue:f}));return x},Tc}var HM=BM();const $c=mg(HM);function Jd(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 qM(){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 m=e[++o];let h=-1;if(d){l(d);return}for(;++h<r.length;)(u[h]===null||u[h]===void 0)&&(u[h]=r[h]);r=u,m?VM(m,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 VM(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 m=u;if(c&&s)throw m;return r(m)}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 Ni={basename:WM,dirname:KM,extname:GM,join:JM,sep:"/"};function WM(e,n){if(n!==void 0&&typeof n!="string")throw new TypeError('"ext" argument must be a string');$o(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 KM(e){if($o(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 GM(e){$o(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 JM(...e){let n=-1,s;for(;++n<e.length;)$o(e[n]),e[n]&&(s=s===void 0?e[n]:s+"/"+e[n]);return s===void 0?".":YM(s)}function YM(e){$o(e);const n=e.codePointAt(0)===47;let s=QM(e,!n);return s.length===0&&!n&&(s="."),s.length>0&&e.codePointAt(e.length-1)===47&&(s+="/"),n?"/"+s:s}function QM(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 $o(e){if(typeof e!="string")throw new TypeError("Path must be a string. Received "+JSON.stringify(e))}const XM={cwd:ZM};function ZM(){return"/"}function Yd(e){return!!(e!==null&&typeof e=="object"&&"href"in e&&e.href&&"protocol"in e&&e.protocol&&e.auth===void 0)}function eA(e){if(typeof e=="string")e=new URL(e);else if(!Yd(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 tA(e)}function tA(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 Dc=["history","path","basename","stem","extname","dirname"];class Jb{constructor(n){let s;n?Yd(n)?s={path:n}:typeof n=="string"||nA(n)?s={value:n}:s=n:s={},this.cwd="cwd"in s?"":XM.cwd(),this.data={},this.history=[],this.messages=[],this.value,this.map,this.result,this.stored;let a=-1;for(;++a<Dc.length;){const o=Dc[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)Dc.includes(r)||(this[r]=s[r])}get basename(){return typeof this.path=="string"?Ni.basename(this.path):void 0}set basename(n){Oc(n,"basename"),Lc(n,"basename"),this.path=Ni.join(this.dirname||"",n)}get dirname(){return typeof this.path=="string"?Ni.dirname(this.path):void 0}set dirname(n){Wh(this.basename,"dirname"),this.path=Ni.join(n||"",this.basename)}get extname(){return typeof this.path=="string"?Ni.extname(this.path):void 0}set extname(n){if(Lc(n,"extname"),Wh(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=Ni.join(this.dirname,this.stem+(n||""))}get path(){return this.history[this.history.length-1]}set path(n){Yd(n)&&(n=eA(n)),Oc(n,"path"),this.path!==n&&this.history.push(n)}get stem(){return typeof this.path=="string"?Ni.basename(this.path,this.extname):void 0}set stem(n){Oc(n,"stem"),Lc(n,"stem"),this.path=Ni.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 Rs(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 Lc(e,n){if(e&&e.includes(Ni.sep))throw new Error("`"+n+"` cannot be a path: did not expect `"+Ni.sep+"`")}function Oc(e,n){if(!e)throw new Error("`"+n+"` cannot be empty")}function Wh(e,n){if(!e)throw new Error("Setting `"+n+"` requires `path` to be set too")}function nA(e){return!!(e&&typeof e=="object"&&"byteLength"in e&&"byteOffset"in e)}const sA=(function(e){const a=this.constructor.prototype,r=a[e],o=function(){return r.apply(o,arguments)};return Object.setPrototypeOf(o,a),o}),iA={}.hasOwnProperty;class zu extends sA{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=qM()}copy(){const n=new zu;let s=-1;for(;++s<this.attachers.length;){const a=this.attachers[s];n.use(...a)}return n.data($c(!0,{},this.namespace)),n}data(n,s){return typeof n=="string"?arguments.length===2?(Uc("data",this.frozen),this.namespace[n]=s,this):iA.call(this.namespace,n)&&this.namespace[n]||void 0:n?(Uc("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=Vo(n),a=this.parser||this.Parser;return zc("parse",a),a(String(s),s)}process(n,s){const a=this;return this.freeze(),zc("process",this.parser||this.Parser),Fc("process",this.compiler||this.Compiler),s?r(void 0,s):new Promise(r);function r(o,l){const c=Vo(n),d=a.parse(c);a.run(d,c,function(m,h,f){if(m||!h||!f)return u(m);const p=h,g=a.stringify(p,f);oA(g)?f.value=g:f.result=g,u(m,f)});function u(m,h){m||!h?l(m):o?o(h):s(void 0,h)}}}processSync(n){let s=!1,a;return this.freeze(),zc("processSync",this.parser||this.Parser),Fc("processSync",this.compiler||this.Compiler),this.process(n,r),Gh("processSync","process",s),a;function r(o,l){s=!0,qh(o),a=l}}run(n,s,a){Kh(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=Vo(s);r.run(n,d,u);function u(m,h,f){const p=h||n;m?c(m):l?l(p):a(void 0,p,f)}}}runSync(n,s){let a=!1,r;return this.run(n,s,o),Gh("runSync","run",a),r;function o(l,c){qh(l),r=c,a=!0}}stringify(n,s){this.freeze();const a=Vo(s),r=this.compiler||this.Compiler;return Fc("stringify",r),Kh(n),r(n,a)}use(n,...s){const a=this.attachers,r=this.namespace;if(Uc("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[m,...h]=u;d(m,h)}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=$c(!0,r.settings,u.settings))}function c(u){let m=-1;if(u!=null)if(Array.isArray(u))for(;++m<u.length;){const h=u[m];o(h)}else throw new TypeError("Expected a list of plugins, not `"+u+"`")}function d(u,m){let h=-1,f=-1;for(;++h<a.length;)if(a[h][0]===u){f=h;break}if(f===-1)a.push([u,...m]);else if(m.length>0){let[p,...g]=m;const x=a[f][1];Jd(x)&&Jd(p)&&(p=$c(!0,x,p)),a[f]=[u,p,...g]}}}}const aA=new zu().freeze();function zc(e,n){if(typeof n!="function")throw new TypeError("Cannot `"+e+"` without `parser`")}function Fc(e,n){if(typeof n!="function")throw new TypeError("Cannot `"+e+"` without `compiler`")}function Uc(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 Kh(e){if(!Jd(e)||typeof e.type!="string")throw new TypeError("Expected node, got `"+e+"`")}function Gh(e,n,s){if(!s)throw new Error("`"+e+"` finished async. Use `"+n+"` instead")}function Vo(e){return rA(e)?e:new Jb(e)}function rA(e){return!!(e&&typeof e=="object"&&"message"in e&&"messages"in e)}function oA(e){return typeof e=="string"||lA(e)}function lA(e){return!!(e&&typeof e=="object"&&"byteLength"in e&&"byteOffset"in e)}const cA="https://github.com/remarkjs/react-markdown/blob/main/changelog.md",Jh=[],Yh={allowDangerousHtml:!0},dA=/^(https?|ircs?|mailto|xmpp)$/i,uA=[{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 bi(e){const n=mA(e),s=hA(e);return pA(n.runSync(n.parse(s),s),e)}function mA(e){const n=e.rehypePlugins||Jh,s=e.remarkPlugins||Jh,a=e.remarkRehypeOptions?{...e.remarkRehypeOptions,...Yh}:Yh;return aA().use(K_).use(s).use(UM,a).use(n)}function hA(e){const n=e.children||"",s=new Jb;return typeof n=="string"&&(s.value=n),s}function pA(e,n){const s=n.allowedElements,a=n.allowElement,r=n.components,o=n.disallowedElements,l=n.skipHtml,c=n.unwrapDisallowed,d=n.urlTransform||fA;for(const m of uA)Object.hasOwn(n,m.from)&&(""+m.from+(m.to?"use `"+m.to+"` instead":"remove it")+cA+m.id,void 0);return Ou(e,u),AE(e,{Fragment:t.Fragment,components:r,ignoreInvalidStyle:!0,jsx:t.jsx,jsxs:t.jsxs,passKeys:!0,passNode:!0});function u(m,h,f){if(m.type==="raw"&&f&&typeof h=="number")return l?f.children.splice(h,1):f.children[h]={type:"text",value:m.value},h;if(m.type==="element"){let p;for(p in Pc)if(Object.hasOwn(Pc,p)&&Object.hasOwn(m.properties,p)){const g=m.properties[p],x=Pc[p];(x===null||x.includes(m.tagName))&&(m.properties[p]=d(String(g||""),p,m))}}if(m.type==="element"){let p=s?!s.includes(m.tagName):o?o.includes(m.tagName):!1;if(!p&&a&&typeof h=="number"&&(p=!a(m,h,f)),p&&f&&typeof h=="number")return c&&m.children?f.children.splice(h,1,...m.children):f.children.splice(h,1),h}}}function fA(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||dA.test(e.slice(0,n))?e:""}function Qh(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 gA(e){if(typeof e!="string")throw new TypeError("Expected a string");return e.replace(/[|\\{}()[\]^$+*?.]/g,"\\$&").replace(/-/g,"\\x2d")}function bA(e,n,s){const r=rc((s||{}).ignore||[]),o=xA(n);let l=-1;for(;++l<o.length;)Gb(e,"text",c);function c(u,m){let h=-1,f;for(;++h<m.length;){const p=m[h],g=f?f.children:void 0;if(r(p,g?g.indexOf(p):void 0,f))return;f=p}if(f)return d(u,m)}function d(u,m){const h=m[m.length-1],f=o[l][0],p=o[l][1];let g=0;const w=h.children.indexOf(u);let b=!1,y=[];f.lastIndex=0;let S=f.exec(u.value);for(;S;){const k=S.index,C={index:S.index,input:S.input,stack:[...m,u]};let v=p(...S,C);if(typeof v=="string"&&(v=v.length>0?{type:"text",value:v}:void 0),v===!1?f.lastIndex=k+1:(g!==k&&y.push({type:"text",value:u.value.slice(g,k)}),Array.isArray(v)?y.push(...v):v&&y.push(v),g=k+S[0].length,b=!0),!f.global)break;S=f.exec(u.value)}return b?(g<u.value.length&&y.push({type:"text",value:u.value.slice(g)}),h.children.splice(w,1,...y)):y=[u],w+y.length}}function xA(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([vA(r[0]),yA(r[1])])}return n}function vA(e){return typeof e=="string"?new RegExp(gA(e),"g"):e}function yA(e){return typeof e=="function"?e:function(){return e}}const Bc="phrasing",Hc=["autolink","link","image","label"];function wA(){return{transforms:[_A],enter:{literalAutolink:jA,literalAutolinkEmail:qc,literalAutolinkHttp:qc,literalAutolinkWww:qc},exit:{literalAutolink:EA,literalAutolinkEmail:CA,literalAutolinkHttp:NA,literalAutolinkWww:SA}}}function kA(){return{unsafe:[{character:"@",before:"[+\\-.\\w]",after:"[\\-.\\w]",inConstruct:Bc,notInConstruct:Hc},{character:".",before:"[Ww]",after:"[\\-.\\w]",inConstruct:Bc,notInConstruct:Hc},{character:":",before:"[ps]",after:"\\/",inConstruct:Bc,notInConstruct:Hc}]}}function jA(e){this.enter({type:"link",title:null,url:"",children:[]},e)}function qc(e){this.config.enter.autolinkProtocol.call(this,e)}function NA(e){this.config.exit.autolinkProtocol.call(this,e)}function SA(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 CA(e){this.config.exit.autolinkEmail.call(this,e)}function EA(e){this.exit(e)}function _A(e){bA(e,[[/(https?:\/\/|www(?=\.))([-.\w]+)([^ \t\r\n]*)/gi,MA],[/(?<=^|\s|\p{P}|\p{S})([-.\w+]+)@([-\w]+(?:\.[-\w]+)+)/gu,AA]],{ignore:["link","linkReference"]})}function MA(e,n,s,a,r){let o="";if(!Yb(r)||(/^w/i.test(n)&&(s=n+s,n="",o="http://"),!PA(s)))return!1;const l=RA(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 AA(e,n,s,a){return!Yb(a,!0)||/[-\d_]$/.test(s)?!1:{type:"link",title:null,url:"mailto:"+n+"@"+s,children:[{type:"text",value:n+"@"+s}]}}function PA(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 RA(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=Qh(e,"(");let o=Qh(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 Yb(e,n){const s=e.input.charCodeAt(e.index-1);return(e.index===0||_a(s)||sc(s))&&(!n||s!==47)}Qb.peek=UA;function IA(){this.buffer()}function TA(e){this.enter({type:"footnoteReference",identifier:"",label:""},e)}function $A(){this.buffer()}function DA(e){this.enter({type:"footnoteDefinition",identifier:"",label:"",children:[]},e)}function LA(e){const n=this.resume(),s=this.stack[this.stack.length-1];s.type,s.identifier=fi(this.sliceSerialize(e)).toLowerCase(),s.label=n}function OA(e){this.exit(e)}function zA(e){const n=this.resume(),s=this.stack[this.stack.length-1];s.type,s.identifier=fi(this.sliceSerialize(e)).toLowerCase(),s.label=n}function FA(e){this.exit(e)}function UA(){return"["}function Qb(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 BA(){return{enter:{gfmFootnoteCallString:IA,gfmFootnoteCall:TA,gfmFootnoteDefinitionLabelString:$A,gfmFootnoteDefinition:DA},exit:{gfmFootnoteCallString:LA,gfmFootnoteCall:OA,gfmFootnoteDefinitionLabelString:zA,gfmFootnoteDefinition:FA}}}function HA(e){let n=!1;return e&&e.firstLineBlank&&(n=!0),{handlers:{footnoteDefinition:s,footnoteReference:Qb},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"),m=o.enter("label");return d+=c.move(o.safe(o.associationId(a),{before:d,after:"]"})),m(),d+=c.move("]:"),a.children&&a.children.length>0&&(c.shift(4),d+=c.move((n?`
665
- `:" ")+o.indentLines(o.containerFlow(a,c.current()),n?Xb:qA))),u(),d}}function qA(e,n,s){return n===0?e:Xb(e,n,s)}function Xb(e,n,s){return(s?"":" ")+e}const VA=["autolink","destinationLiteral","destinationRaw","reference","titleQuote","titleApostrophe"];Zb.peek=YA;function WA(){return{canContainEols:["delete"],enter:{strikethrough:GA},exit:{strikethrough:JA}}}function KA(){return{unsafe:[{character:"~",inConstruct:"phrasing",notInConstruct:VA}],handlers:{delete:Zb}}}function GA(e){this.enter({type:"delete",children:[]},e)}function JA(e){this.exit(e)}function Zb(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 YA(){return"~"}function QA(e){return e.length}function XA(e,n){const s=n||{},a=(s.align||[]).concat(),r=s.stringLength||QA,o=[],l=[],c=[],d=[];let u=0,m=-1;for(;++m<e.length;){const x=[],w=[];let b=-1;for(e[m].length>u&&(u=e[m].length);++b<e[m].length;){const y=ZA(e[m][b]);if(s.alignDelimiters!==!1){const S=r(y);w[b]=S,(d[b]===void 0||S>d[b])&&(d[b]=S)}x.push(y)}l[m]=x,c[m]=w}let h=-1;if(typeof a=="object"&&"length"in a)for(;++h<u;)o[h]=Xh(a[h]);else{const x=Xh(a);for(;++h<u;)o[h]=x}h=-1;const f=[],p=[];for(;++h<u;){const x=o[h];let w="",b="";x===99?(w=":",b=":"):x===108?w=":":x===114&&(b=":");let y=s.alignDelimiters===!1?1:Math.max(1,d[h]-w.length-b.length);const S=w+"-".repeat(y)+b;s.alignDelimiters!==!1&&(y=w.length+y+b.length,y>d[h]&&(d[h]=y),p[h]=y),f[h]=S}l.splice(1,0,f),c.splice(1,0,p),m=-1;const g=[];for(;++m<l.length;){const x=l[m],w=c[m];h=-1;const b=[];for(;++h<u;){const y=x[h]||"";let S="",k="";if(s.alignDelimiters!==!1){const C=d[h]-(w[h]||0),v=o[h];v===114?S=" ".repeat(C):v===99?C%2?(S=" ".repeat(C/2+.5),k=" ".repeat(C/2-.5)):(S=" ".repeat(C/2),k=S):k=" ".repeat(C)}s.delimiterStart!==!1&&!h&&b.push("|"),s.padding!==!1&&!(s.alignDelimiters===!1&&y==="")&&(s.delimiterStart!==!1||h)&&b.push(" "),s.alignDelimiters!==!1&&b.push(S),b.push(y),s.alignDelimiters!==!1&&b.push(k),s.padding!==!1&&b.push(" "),(s.delimiterEnd!==!1||h!==u-1)&&b.push("|")}g.push(s.delimiterEnd===!1?b.join("").replace(/ +$/,""):b.join(""))}return g.join(`
666
- `)}function ZA(e){return e==null?"":String(e)}function Xh(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 eP(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()),tP);return r(),l}function tP(e,n,s){return">"+(s?"":" ")+e}function nP(e,n){return Zh(e,n.inConstruct,!0)&&!Zh(e,n.notInConstruct,!1)}function Zh(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 ep(e,n,s,a){let r=-1;for(;++r<s.unsafe.length;)if(s.unsafe[r].character===`
667
- `&&nP(s.stack,s.unsafe[r]))return/[ \t]/.test(a.before)?"":" ";return`\\
668
- `}function sP(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 iP(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 aP(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 rP(e,n,s,a){const r=aP(s),o=e.value||"",l=r==="`"?"GraveAccent":"Tilde";if(iP(e,s)){const h=s.enter("codeIndented"),f=s.indentLines(o,oP);return h(),f}const c=s.createTracker(a),d=r.repeat(Math.max(sP(o,r)+1,3)),u=s.enter("codeFenced");let m=c.move(d);if(e.lang){const h=s.enter(`codeFencedLang${l}`);m+=c.move(s.safe(e.lang,{before:m,after:" ",encode:["`"],...c.current()})),h()}if(e.lang&&e.meta){const h=s.enter(`codeFencedMeta${l}`);m+=c.move(" "),m+=c.move(s.safe(e.meta,{before:m,after:`
669
- `,encode:["`"],...c.current()})),h()}return m+=c.move(`
670
- `),o&&(m+=c.move(o+`
671
- `)),m+=c.move(d),u(),m}function oP(e,n,s){return(s?"":" ")+e}function Fu(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 lP(e,n,s,a){const r=Fu(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?" ":`
672
- `,...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 cP(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 fo(e){return"&#x"+e.toString(16).toUpperCase()+";"}function Dl(e,n,s){const a=fr(e),r=fr(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}}ex.peek=dP;function ex(e,n,s,a){const r=cP(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),m=Dl(a.before.charCodeAt(a.before.length-1),u,r);m.inside&&(d=fo(u)+d.slice(1));const h=d.charCodeAt(d.length-1),f=Dl(a.after.charCodeAt(0),h,r);f.inside&&(d=d.slice(0,-1)+fo(h));const p=l.move(r);return o(),s.attentionEncodeSurroundingInfo={after:f.outside,before:m.outside},c+d+p}function dP(e,n,s){return s.options.emphasis||"*"}function uP(e,n){let s=!1;return Ou(e,function(a){if("value"in a&&/\r?\n|\r/.test(a.value)||a.type==="break")return s=!0,Kd}),!!((!e.depth||e.depth<3)&&Pu(e)&&(n.options.setext||s))}function mP(e,n,s,a){const r=Math.max(Math.min(6,e.depth||1),1),o=s.createTracker(a);if(uP(e,s)){const m=s.enter("headingSetext"),h=s.enter("phrasing"),f=s.containerPhrasing(e,{...o.current(),before:`
673
- `,after:`
674
- `});return h(),m(),f+`
675
- `+(r===1?"=":"-").repeat(f.length-(Math.max(f.lastIndexOf("\r"),f.lastIndexOf(`
676
- `))+1))}const l="#".repeat(r),c=s.enter("headingAtx"),d=s.enter("phrasing");o.move(l+" ");let u=s.containerPhrasing(e,{before:"# ",after:`
677
- `,...o.current()});return/^[\t ]/.test(u)&&(u=fo(u.charCodeAt(0))+u.slice(1)),u=u?l+" "+u:l,s.options.closeAtx&&(u+=" "+l),d(),c(),u}tx.peek=hP;function tx(e){return e.value||""}function hP(){return"<"}nx.peek=pP;function nx(e,n,s,a){const r=Fu(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 pP(){return"!"}sx.peek=fP;function sx(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 m=s.stack;s.stack=[],l=s.enter("reference");const h=s.safe(s.associationId(e),{before:d,after:"]",...c.current()});return l(),s.stack=m,o(),r==="full"||!u||u!==h?d+=c.move(h+"]"):r==="shortcut"?d=d.slice(0,-1):d+=c.move("]"),d}function fP(){return"!"}ix.peek=gP;function ix(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 gP(){return"`"}function ax(e,n){const s=Pu(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))}rx.peek=bP;function rx(e,n,s,a){const r=Fu(s),o=r==='"'?"Quote":"Apostrophe",l=s.createTracker(a);let c,d;if(ax(e,s)){const m=s.stack;s.stack=[],c=s.enter("autolink");let h=l.move("<");return h+=l.move(s.containerPhrasing(e,{before:h,after:">",...l.current()})),h+=l.move(">"),c(),s.stack=m,h}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 bP(e,n,s){return ax(e,s)?"<":"["}ox.peek=xP;function ox(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 m=s.stack;s.stack=[],l=s.enter("reference");const h=s.safe(s.associationId(e),{before:d,after:"]",...c.current()});return l(),s.stack=m,o(),r==="full"||!u||u!==h?d+=c.move(h+"]"):r==="shortcut"?d=d.slice(0,-1):d+=c.move("]"),d}function xP(){return"["}function Uu(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 vP(e){const n=Uu(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 yP(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 lx(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 wP(e,n,s,a){const r=s.enter("list"),o=s.bulletCurrent;let l=e.ordered?yP(s):Uu(s);const c=e.ordered?l==="."?")":".":vP(s);let d=n&&s.bulletLastUsed?l===s.bulletLastUsed:!1;if(!e.ordered){const m=e.children?e.children[0]:void 0;if((l==="*"||l==="-")&&m&&(!m.children||!m.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),lx(s)===l&&m){let h=-1;for(;++h<e.children.length;){const f=e.children[h];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 kP(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 jP(e,n,s,a){const r=kP(s);let o=s.bulletCurrent||Uu(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()),m);return d(),u;function m(h,f,p){return f?(p?"":" ".repeat(l))+h:(p?o:o+" ".repeat(l-o.length))+h}}function NP(e,n,s,a){const r=s.enter("paragraph"),o=s.enter("phrasing"),l=s.containerPhrasing(e,a);return o(),r(),l}const SP=rc(["break","delete","emphasis","footnote","footnoteReference","image","imageReference","inlineCode","inlineMath","link","linkReference","mdxJsxTextElement","mdxTextExpression","strong","text","textDirective"]);function CP(e,n,s,a){return(e.children.some(function(l){return SP(l)})?s.containerPhrasing:s.containerFlow).call(s,e,a)}function EP(e){const n=e.options.strong||"*";if(n!=="*"&&n!=="_")throw new Error("Cannot serialize strong with `"+n+"` for `options.strong`, expected `*`, or `_`");return n}cx.peek=_P;function cx(e,n,s,a){const r=EP(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),m=Dl(a.before.charCodeAt(a.before.length-1),u,r);m.inside&&(d=fo(u)+d.slice(1));const h=d.charCodeAt(d.length-1),f=Dl(a.after.charCodeAt(0),h,r);f.inside&&(d=d.slice(0,-1)+fo(h));const p=l.move(r+r);return o(),s.attentionEncodeSurroundingInfo={after:f.outside,before:m.outside},c+d+p}function _P(e,n,s){return s.options.strong||"*"}function MP(e,n,s,a){return s.safe(e.value,a)}function AP(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 PP(e,n,s){const a=(lx(s)+(s.options.ruleSpaces?" ":"")).repeat(AP(s));return s.options.ruleSpaces?a.slice(0,-1):a}const dx={blockquote:eP,break:ep,code:rP,definition:lP,emphasis:ex,hardBreak:ep,heading:mP,html:tx,image:nx,imageReference:sx,inlineCode:ix,link:rx,linkReference:ox,list:wP,listItem:jP,paragraph:NP,root:CP,strong:cx,text:MP,thematicBreak:PP};function RP(){return{enter:{table:IP,tableData:tp,tableHeader:tp,tableRow:$P},exit:{codeText:DP,table:TP,tableData:Vc,tableHeader:Vc,tableRow:Vc}}}function IP(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 TP(e){this.exit(e),this.data.inTable=void 0}function $P(e){this.enter({type:"tableRow",children:[]},e)}function Vc(e){this.exit(e)}function tp(e){this.enter({type:"tableCell",children:[]},e)}function DP(e){let n=this.resume();this.data.inTable&&(n=n.replace(/\\([\\|])/g,LP));const s=this.stack[this.stack.length-1];s.type,s.value=n,this.exit(e)}function LP(e,n){return n==="|"?n:e}function OP(e){const n=e||{},s=n.tableCellPadding,a=n.tablePipeAlign,r=n.stringLength,o=s?" ":"|";return{unsafe:[{character:"\r",inConstruct:"tableCell"},{character:`
678
- `,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,x,w){return u(m(p,x,w),p.align)}function c(p,g,x,w){const b=h(p,x,w),y=u([b]);return y.slice(0,y.indexOf(`
679
- `))}function d(p,g,x,w){const b=x.enter("tableCell"),y=x.enter("phrasing"),S=x.containerPhrasing(p,{...w,before:o,after:o});return y(),b(),S}function u(p,g){return XA(p,{align:g,alignDelimiters:a,padding:s,stringLength:r})}function m(p,g,x){const w=p.children;let b=-1;const y=[],S=g.enter("table");for(;++b<w.length;)y[b]=h(w[b],g,x);return S(),y}function h(p,g,x){const w=p.children;let b=-1;const y=[],S=g.enter("tableRow");for(;++b<w.length;)y[b]=d(w[b],p,g,x);return S(),y}function f(p,g,x){let w=dx.inlineCode(p,g,x);return x.stack.includes("tableCell")&&(w=w.replace(/\|/g,"\\$&")),w}}function zP(){return{exit:{taskListCheckValueChecked:np,taskListCheckValueUnchecked:np,paragraph:UP}}}function FP(){return{unsafe:[{atBreak:!0,character:"-",after:"[:|-]"}],handlers:{listItem:BP}}}function np(e){const n=this.stack[this.stack.length-2];n.type,n.checked=e.type==="taskListCheckValueChecked"}function UP(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 BP(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=dx.listItem(e,n,s,{...a,...c.current()});return o&&(d=d.replace(/^(?:[*+-]|\d+\.)([\r\n]| {1,3})/,u)),d;function u(m){return m+l}}function HP(){return[wA(),BA(),WA(),RP(),zP()]}function qP(e){return{extensions:[kA(),HA(e),KA(),OP(e),FP()]}}const VP={tokenize:QP,partial:!0},ux={tokenize:XP,partial:!0},mx={tokenize:ZP,partial:!0},hx={tokenize:eR,partial:!0},WP={tokenize:tR,partial:!0},px={name:"wwwAutolink",tokenize:JP,previous:gx},fx={name:"protocolAutolink",tokenize:YP,previous:bx},Vi={name:"emailAutolink",tokenize:GP,previous:xx},Pi={};function KP(){return{text:Pi}}let xa=48;for(;xa<123;)Pi[xa]=Vi,xa++,xa===58?xa=65:xa===91&&(xa=97);Pi[43]=Vi;Pi[45]=Vi;Pi[46]=Vi;Pi[95]=Vi;Pi[72]=[Vi,fx];Pi[104]=[Vi,fx];Pi[87]=[Vi,px];Pi[119]=[Vi,px];function GP(e,n,s){const a=this;let r,o;return l;function l(h){return!Qd(h)||!xx.call(a,a.previous)||Bu(a.events)?s(h):(e.enter("literalAutolink"),e.enter("literalAutolinkEmail"),c(h))}function c(h){return Qd(h)?(e.consume(h),c):h===64?(e.consume(h),d):s(h)}function d(h){return h===46?e.check(WP,m,u)(h):h===45||h===95||As(h)?(o=!0,e.consume(h),d):m(h)}function u(h){return e.consume(h),r=!0,d}function m(h){return o&&r&&Ls(a.previous)?(e.exit("literalAutolinkEmail"),e.exit("literalAutolink"),n(h)):s(h)}}function JP(e,n,s){const a=this;return r;function r(l){return l!==87&&l!==119||!gx.call(a,a.previous)||Bu(a.events)?s(l):(e.enter("literalAutolink"),e.enter("literalAutolinkWww"),e.check(VP,e.attempt(ux,e.attempt(mx,o),s),s)(l))}function o(l){return e.exit("literalAutolinkWww"),e.exit("literalAutolink"),n(l)}}function YP(e,n,s){const a=this;let r="",o=!1;return l;function l(h){return(h===72||h===104)&&bx.call(a,a.previous)&&!Bu(a.events)?(e.enter("literalAutolink"),e.enter("literalAutolinkHttp"),r+=String.fromCodePoint(h),e.consume(h),c):s(h)}function c(h){if(Ls(h)&&r.length<5)return r+=String.fromCodePoint(h),e.consume(h),c;if(h===58){const f=r.toLowerCase();if(f==="http"||f==="https")return e.consume(h),d}return s(h)}function d(h){return h===47?(e.consume(h),o?u:(o=!0,d)):s(h)}function u(h){return h===null||Il(h)||Pn(h)||_a(h)||sc(h)?s(h):e.attempt(ux,e.attempt(mx,m),s)(h)}function m(h){return e.exit("literalAutolinkHttp"),e.exit("literalAutolink"),n(h)}}function QP(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 XP(e,n,s){let a,r,o;return l;function l(u){return u===46||u===95?e.check(hx,d,c)(u):u===null||Pn(u)||_a(u)||u!==45&&sc(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 ZP(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(hx,n,o)(l):l===null||Pn(l)||_a(l)?n(l):(e.consume(l),r)}function o(l){return l===41&&a++,e.consume(l),r}}function eR(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||Pn(c)||_a(c)?n(c):s(c)}function r(c){return c===null||c===40||c===91||Pn(c)||_a(c)?n(c):a(c)}function o(c){return Ls(c)?l(c):s(c)}function l(c){return c===59?(e.consume(c),a):Ls(c)?(e.consume(c),l):s(c)}}function tR(e,n,s){return a;function a(o){return e.consume(o),r}function r(o){return As(o)?s(o):n(o)}}function gx(e){return e===null||e===40||e===42||e===95||e===91||e===93||e===126||Pn(e)}function bx(e){return!Ls(e)}function xx(e){return!(e===47||Qd(e))}function Qd(e){return e===43||e===45||e===46||e===95||As(e)}function Bu(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 nR={tokenize:dR,partial:!0};function sR(){return{document:{91:{name:"gfmFootnoteDefinition",tokenize:oR,continuation:{tokenize:lR},exit:cR}},text:{91:{name:"gfmFootnoteCall",tokenize:rR},93:{name:"gfmPotentialFootnoteCall",add:"after",tokenize:iR,resolveTo:aR}}}}function iR(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=fi(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 aR(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 rR(e,n,s){const a=this,r=a.parser.gfmFootnotes||(a.parser.gfmFootnotes=[]);let o=0,l;return c;function c(h){return e.enter("gfmFootnoteCall"),e.enter("gfmFootnoteCallLabelMarker"),e.consume(h),e.exit("gfmFootnoteCallLabelMarker"),d}function d(h){return h!==94?s(h):(e.enter("gfmFootnoteCallMarker"),e.consume(h),e.exit("gfmFootnoteCallMarker"),e.enter("gfmFootnoteCallString"),e.enter("chunkString").contentType="string",u)}function u(h){if(o>999||h===93&&!l||h===null||h===91||Pn(h))return s(h);if(h===93){e.exit("chunkString");const f=e.exit("gfmFootnoteCallString");return r.includes(fi(a.sliceSerialize(f)))?(e.enter("gfmFootnoteCallLabelMarker"),e.consume(h),e.exit("gfmFootnoteCallLabelMarker"),e.exit("gfmFootnoteCall"),n):s(h)}return Pn(h)||(l=!0),o++,e.consume(h),h===92?m:u}function m(h){return h===91||h===92||h===93?(e.consume(h),o++,u):u(h)}}function oR(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",m):s(g)}function m(g){if(l>999||g===93&&!c||g===null||g===91||Pn(g))return s(g);if(g===93){e.exit("chunkString");const x=e.exit("gfmFootnoteDefinitionLabelString");return o=fi(a.sliceSerialize(x)),e.enter("gfmFootnoteDefinitionLabelMarker"),e.consume(g),e.exit("gfmFootnoteDefinitionLabelMarker"),e.exit("gfmFootnoteDefinitionLabel"),f}return Pn(g)||(c=!0),l++,e.consume(g),g===92?h:m}function h(g){return g===91||g===92||g===93?(e.consume(g),l++,m):m(g)}function f(g){return g===58?(e.enter("definitionMarker"),e.consume(g),e.exit("definitionMarker"),r.includes(o)||r.push(o),pn(e,p,"gfmFootnoteDefinitionWhitespace")):s(g)}function p(g){return n(g)}}function lR(e,n,s){return e.check(To,n,e.attempt(nR,n,s))}function cR(e){e.exit("gfmFootnoteDefinition")}function dR(e,n,s){const a=this;return pn(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 uR(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 m={type:"strikethrough",start:Object.assign({},l[u][1].start),end:Object.assign({},l[d][1].end)},h={type:"strikethroughText",start:Object.assign({},l[u][1].end),end:Object.assign({},l[d][1].start)},f=[["enter",m,c],["enter",l[u][1],c],["exit",l[u][1],c],["enter",h,c]],p=c.parser.constructs.insideSpan.null;p&&Gs(f,f.length,0,ic(p,l.slice(u+1,d),c)),Gs(f,f.length,0,[["exit",h,c],["enter",l[d][1],c],["exit",l[d][1],c],["exit",m,c]]),Gs(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,m=this.events;let h=0;return f;function f(g){return u===126&&m[m.length-1][1].type!=="characterEscape"?d(g):(l.enter("strikethroughSequenceTemporary"),p(g))}function p(g){const x=fr(u);if(g===126)return h>1?d(g):(l.consume(g),h++,p);if(h<2&&!s)return d(g);const w=l.exit("strikethroughSequenceTemporary"),b=fr(g);return w._open=!b||b===2&&!!x,w._close=!x||x===2&&!!b,c(g)}}}class mR{constructor(){this.map=[]}add(n,s,a){hR(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 hR(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 pR(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 fR(){return{flow:{null:{name:"table",tokenize:gR,resolveAll:bR}}}}function gR(e,n,s){const a=this;let r=0,o=0,l;return c;function c(E){let R=a.events.length-1;for(;R>-1;){const M=a.events[R][1].type;if(M==="lineEnding"||M==="linePrefix")R--;else break}const L=R>-1?a.events[R][1].type:null,F=L==="tableHead"||L==="tableRow"?v:d;return F===v&&a.parser.lazy[a.now().line]?s(E):F(E)}function d(E){return e.enter("tableHead"),e.enter("tableRow"),u(E)}function u(E){return E===124||(l=!0,o+=1),m(E)}function m(E){return E===null?s(E):Wt(E)?o>1?(o=0,a.interrupt=!0,e.exit("tableRow"),e.enter("lineEnding"),e.consume(E),e.exit("lineEnding"),p):s(E):mn(E)?pn(e,m,"whitespace")(E):(o+=1,l&&(l=!1,r+=1),E===124?(e.enter("tableCellDivider"),e.consume(E),e.exit("tableCellDivider"),l=!0,m):(e.enter("data"),h(E)))}function h(E){return E===null||E===124||Pn(E)?(e.exit("data"),m(E)):(e.consume(E),E===92?f:h)}function f(E){return E===92||E===124?(e.consume(E),h):h(E)}function p(E){return a.interrupt=!1,a.parser.lazy[a.now().line]?s(E):(e.enter("tableDelimiterRow"),l=!1,mn(E)?pn(e,g,"linePrefix",a.parser.constructs.disable.null.includes("codeIndented")?void 0:4)(E):g(E))}function g(E){return E===45||E===58?w(E):E===124?(l=!0,e.enter("tableCellDivider"),e.consume(E),e.exit("tableCellDivider"),x):C(E)}function x(E){return mn(E)?pn(e,w,"whitespace")(E):w(E)}function w(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||Wt(E)?k(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"),S):(e.exit("tableDelimiterFiller"),S(E))}function S(E){return mn(E)?pn(e,k,"whitespace")(E):k(E)}function k(E){return E===124?g(E):E===null||Wt(E)?!l||r!==o?C(E):(e.exit("tableDelimiterRow"),e.exit("tableHead"),n(E)):C(E)}function C(E){return s(E)}function v(E){return e.enter("tableRow"),j(E)}function j(E){return E===124?(e.enter("tableCellDivider"),e.consume(E),e.exit("tableCellDivider"),j):E===null||Wt(E)?(e.exit("tableRow"),n(E)):mn(E)?pn(e,j,"whitespace")(E):(e.enter("data"),P(E))}function P(E){return E===null||E===124||Pn(E)?(e.exit("data"),j(E)):(e.consume(E),E===92?U:P)}function U(E){return E===92||E===124?(e.consume(E),P):P(E)}}function bR(e,n){let s=-1,a=!0,r=0,o=[0,0,0,0],l=[0,0,0,0],c=!1,d=0,u,m,h;const f=new mR;for(;++s<e.length;){const p=e[s],g=p[1];p[0]==="enter"?g.type==="tableHead"?(c=!1,d!==0&&(sp(f,n,d,u,m),m=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,h=void 0,o=[0,0,0,0],l=[0,s+1,0,0],c&&(c=!1,m={type:"tableBody",start:Object.assign({},g.start),end:Object.assign({},g.end)},f.add(s,0,[["enter",m,n]])),r=g.type==="tableDelimiterRow"?2:m?3:1):r&&(g.type==="data"||g.type==="tableDelimiterMarker"||g.type==="tableDelimiterFiller")?(a=!1,l[2]===0&&(o[1]!==0&&(l[0]=l[1],h=Wo(f,n,o,r,void 0,h),o=[0,0,0,0]),l[2]=s)):g.type==="tableCellDivider"&&(a?a=!1:(o[1]!==0&&(l[0]=l[1],h=Wo(f,n,o,r,void 0,h)),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],h=Wo(f,n,o,r,s,h)):l[1]!==0&&(h=Wo(f,n,l,r,s,h)),r=0):r&&(g.type==="data"||g.type==="tableDelimiterMarker"||g.type==="tableDelimiterFiller")&&(l[3]=s)}for(d!==0&&sp(f,n,d,u,m),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=pR(n.events,s))}return e}function Wo(e,n,s,a,r,o){const l=a===1?"tableHeader":a===2?"tableDelimiter":"tableData",c="tableContent";s[0]!==0&&(o.end=Object.assign({},sr(n.events,s[0])),e.add(s[0],0,[["exit",o,n]]));const d=sr(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=sr(n.events,s[2]),m=sr(n.events,s[3]),h={type:c,start:Object.assign({},u),end:Object.assign({},m)};if(e.add(s[2],0,[["enter",h,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,x=s[3]-s[2]-1;e.add(g,x,[])}}e.add(s[3]+1,0,[["exit",h,n]])}return r!==void 0&&(o.end=Object.assign({},sr(n.events,r)),e.add(r,0,[["exit",o,n]]),o=void 0),o}function sp(e,n,s,a,r){const o=[],l=sr(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 sr(e,n){const s=e[n],a=s[0]==="enter"?"start":"end";return s[1][a]}const xR={name:"tasklistCheck",tokenize:yR};function vR(){return{text:{91:xR}}}function yR(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 Pn(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 Wt(d)?n(d):mn(d)?e.check({tokenize:wR},n,s)(d):s(d)}}function wR(e,n,s){return pn(e,a,"whitespace");function a(r){return r===null?s(r):n(r)}}function kR(e){return Mb([KP(),sR(),uR(e),fR(),vR()])}const jR={};function xi(e){const n=this,s=e||jR,a=n.data(),r=a.micromarkExtensions||(a.micromarkExtensions=[]),o=a.fromMarkdownExtensions||(a.fromMarkdownExtensions=[]),l=a.toMarkdownExtensions||(a.toMarkdownExtensions=[]);r.push(kR(s)),o.push(HP()),l.push(qP(s))}const NR=45e3,SR=3e3,CR=2e3,ER=1500,ip="fusion:sse-client-id";let Qa=null;const na=new Map;function ap(){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 vx(){if(!(typeof window>"u")){if(Qa)return Qa;try{const e=window.sessionStorage.getItem(ip);if(e)return Qa=e,e;const n=ap();return window.sessionStorage.setItem(ip,n),Qa=n,n}catch{return Qa=ap(),Qa}}}function yx(e){if(!(typeof window>"u"))try{return{parsed:new URL(e,window.location.origin),preserveRelativePath:e.startsWith("/")}}catch{return}}function wx(e){return e.origin===window.location.origin&&e.pathname==="/api/events"}function _R(e){const n=vx();if(!n)return e;const s=yx(e);return!s||!wx(s.parsed)?e:(s.parsed.searchParams.set("clientId",n),s.preserveRelativePath?`${s.parsed.pathname}${s.parsed.search}${s.parsed.hash}`:s.parsed.toString())}function Hu(e,n){const s=vx();if(!s)return;const a=yx(e);if(!a||!wx(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),Mi(`${r.pathname}${r.search}${r.hash}`)}function MR(e){if(typeof window>"u")return;const n=Hu(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 lc(e){e.keepaliveTimer&&(clearInterval(e.keepaliveTimer),e.keepaliveTimer=null)}function rp(e){if(typeof window>"u"||typeof window.fetch!="function")return;const n=Hu(e.url,"keepalive");if(!n)return;const s=typeof AbortController<"u"?new AbortController:null,a=s?window.setTimeout(()=>s.abort(),ER):null;window.fetch(n,{method:"POST",cache:"no-store",signal:s?.signal}).catch(()=>{}).finally(()=>{a!==null&&window.clearTimeout(a)})}function AR(e){lc(e),Hu(e.url,"keepalive")&&(rp(e),e.keepaliveTimer=window.setInterval(()=>{rp(e)},CR))}if(typeof window<"u"){const e=()=>{for(const s of Array.from(na.values()))if(!s.closed){if(lc(s),MR(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(na.values()))a.subscribers.size!==0&&(a.closed=!1,qu(a))};window.addEventListener("pagehide",e),window.addEventListener("beforeunload",e),window.addEventListener("pageshow",n)}function Yr(e){e.heartbeatTimer&&clearTimeout(e.heartbeatTimer),e.heartbeatTimer=setTimeout(()=>{kx(e)},NR)}function kx(e){if(e.heartbeatTimer&&(clearTimeout(e.heartbeatTimer),e.heartbeatTimer=null),e.es&&(e.es.close(),e.es=null),lc(e),e.nativeListeners.clear(),e.closed||e.subscribers.size===0||e.reconnectTimer)return;const n=na.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=na.get(e.url);s&&s===e&&e.subscribers.size>0&&qu(e)},SR)}}function qu(e){if(e.es||e.closed)return;e.reconnectTimer&&(clearTimeout(e.reconnectTimer),e.reconnectTimer=null);const n=new EventSource(Mi(_R(e.url)));e.es=n,AR(e),n.addEventListener("open",()=>{Yr(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);kx(e)}),n.addEventListener("message",()=>Yr(e)),n.addEventListener("heartbeat",()=>Yr(e)),jx(e),Yr(e)}function jx(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=>{Yr(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 PR(e){e.closed=!0,e.heartbeatTimer&&clearTimeout(e.heartbeatTimer),lc(e),e.reconnectTimer&&clearTimeout(e.reconnectTimer),e.es&&e.es.close(),e.es=null,e.nativeListeners.clear(),na.delete(e.url)}function ii(e,n={}){let s=na.get(e);s||(s={url:e,es:null,subscribers:new Set,nativeListeners:new Map,heartbeatTimer:null,keepaliveTimer:null,reconnectTimer:null,hasOpenedOnce:!1,closed:!1},na.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;qu(s),jx(s),r&&queueMicrotask(()=>{s.subscribers.has(a)&&a.onOpen?.()});let o=!0;return()=>{if(!o)return;o=!1;const l=na.get(e);l&&(l.subscribers.delete(a),l.subscribers.size===0&&PR(l))}}const op=100;function Nx(e,n,s){const[a,r]=i.useState([]),[o,l]=i.useState(!1),[c,d]=i.useState(!1),[u,m]=i.useState(null),[h,f]=i.useState(!1),p=i.useRef(null),g=i.useRef(!1),x=i.useRef(0),w=i.useRef(e),b=i.useRef(s),y=i.useRef(n),S=i.useRef(0);(w.current!==e||b.current!==s||y.current!==n)&&(w.current=e,b.current=s,y.current=n,x.current++,g.current=!0,r([]),l(!1),d(!1),m(null),f(!1),p.current&&(p.current(),p.current=null)),i.useEffect(()=>{if(!e||!n){p.current&&(p.current(),p.current=null);return}const j=x.current,P=++S.current;g.current=!1;const U=e,E=s;async function R(){if(!U)return;l(!0),f(!1);try{const F=await lm(U,E,{limit:op});if(g.current||x.current!==j||S.current!==P)return;r(F.entries),d(F.hasMore),m(F.total)}catch{if(g.current||x.current!==j||S.current!==P)return;r([]),d(!1),m(null)}finally{!g.current&&x.current===j&&S.current===P&&l(!1)}const L=E?`?projectId=${encodeURIComponent(E)}`:"";p.current=ii(`/api/tasks/${U}/logs/stream${L}`,{events:{"agent:log":F=>{if(!(g.current||x.current!==j))try{const M=JSON.parse(F.data);r(O=>[...O,M]),m(O=>O!==null?O+1:null)}catch{}}}})}return R(),()=>{g.current=!0,p.current&&(p.current(),p.current=null)}},[e,n,s]);const C=i.useCallback(async()=>{if(!e||h)return;const j=x.current,P=a.length,U=e;f(!0);try{const E=await lm(U,s,{limit:op,offset:P});if(g.current||x.current!==j)return;r(R=>[...E.entries,...R]),d(E.hasMore),m(E.total)}catch{}finally{f(!1)}},[e,s,a.length,h]),v=i.useCallback(()=>r([]),[]);return{entries:a,loading:o,clear:v,loadMore:C,hasMore:c,total:u,loadingMore:h}}const lp="fn-agent-log-markdown",cp="fn-agent-log-tool-output";function dp(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 up(e,n){if(!(typeof window>"u"))try{window.localStorage.setItem(e,n?"true":"false")}catch{}}function RR(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 mp={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})},Sx=50,IR={triage:"Plan"};function hp(e){return e.scrollHeight-(e.scrollTop+e.clientHeight)<=Sx}function Xd(e){return[e.taskId,e.timestamp,e.agent??"",e.type,e.text,e.detail??""].join("|")}function TR(e){const n=new Map;return e.map(s=>{const a=Xd(s),r=n.get(a)??0;return n.set(a,r+1),`${a}|${r}`})}function Cx(e){return e==="tool"||e==="tool_result"||e==="tool_error"}function Wc({detail:e}){const[n,s]=i.useState(!1),a=i.useId(),r=e.split(`
680
- `).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(rn,{size:14}):t.jsx(Mn,{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:e})})]})}function $R(e,n){return e.agent?Cx(e.type)?!0:!n||n.agent!==e.agent||n.type!==e.type:!1}function DR(e,n){const s=[];for(let a=0;a<e.length;a+=1){const{entry:r,hiddenToolBoundaryId:o}=e[a],l=n[a]??`${Xd(r)}|fallback`,c=a>0?e[a-1]:void 0,d=c?.entry,u=$R(r,d)||c!==void 0&&c.hiddenToolBoundaryId!==o;if(r.type==="text"||r.type==="thinking"){const m=[r];let h=a+1;for(;h<e.length;){const p=e[h],g=p.entry;if(g.type!==r.type||g.agent!==r.agent||p.hiddenToolBoundaryId!==o)break;m.push(g),h+=1}const f=n[h-1]??`${Xd(e[h-1].entry)}|fallback`;s.push({kind:r.type,entries:m,key:`${l}->${f}`,showBadge:u}),a=h-1;continue}s.push({kind:"single",entry:r,key:l,showBadge:u})}return s}function LR({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),m=i.useRef(0),h=i.useRef(0),f=i.useRef(null),p=i.useRef(null),[g,x]=i.useState(()=>dp(lp,!0)),[w,b]=i.useState(()=>dp(cp,!0)),[y,S]=i.useState(!1),[k,C]=i.useState(!1),[v,j]=i.useState(!0);i.useEffect(()=>{up(lp,g)},[g]),i.useEffect(()=>{up(cp,w)},[w]);const P=i.useMemo(()=>{if(w)return e.map(I=>({entry:I,hiddenToolBoundaryId:0}));const K=[];let A=0;for(const I of e){if(Cx(I.type)){A+=1;continue}K.push({entry:I,hiddenToolBoundaryId:A})}return K},[e,w]),U=i.useMemo(()=>P.map(K=>K.entry),[P]),E=i.useMemo(()=>TR(U),[U]),R=i.useMemo(()=>DR(P,E),[P,E]);i.useLayoutEffect(()=>{const K=u.current;if(!K)return;const A=e.length,I=m.current,$=h.current||K.scrollHeight,N=E[0]??null,G=E[E.length-1]??null,xe=f.current!==N,Se=p.current!==G;if(A>I)if(I===0)K.scrollTop=K.scrollHeight;else{const je=$-(K.scrollTop+K.clientHeight)<=Sx,se=Se&&!xe,Ve=xe&&!Se;if(se&&je&&(K.scrollTop=K.scrollHeight),Ve){const ee=K.scrollHeight-$;ee>0&&(K.scrollTop+=ee)}}m.current=A,h.current=K.scrollHeight,f.current=N,p.current=G,j(hp(K))},[e,E]);const L=i.useCallback(()=>{const K=u.current;K&&j(hp(K))},[]),F=i.useCallback(()=>{const K=u.current;K&&(K.scrollTop=K.scrollHeight,j(!0))},[]),M=i.useCallback(K=>{K.key==="Escape"&&y&&S(!1)},[y]);i.useEffect(()=>{if(y)return document.addEventListener("keydown",M),()=>{document.removeEventListener("keydown",M)}},[y,M]);const O=s?.provider&&s?.modelId,q=a?.provider&&a?.modelId,te=r?.provider&&r?.modelId,Z=i.useMemo(()=>{const K=[];return O&&K.push({role:"Executor",provider:s.provider,modelId:s.modelId}),q&&K.push({role:"Reviewer",provider:a.provider,modelId:a.modelId}),te&&K.push({role:"Planning",provider:r.provider,modelId:r.modelId}),K},[O,s,q,a,te,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:[Z.map(K=>t.jsx(Sn,{provider:K.provider,size:"sm"},`${K.role}-${K.provider}-${K.modelId??"default"}`)),t.jsx("button",{className:"agent-log-model-expand-btn",onClick:()=>C(K=>!K),"aria-label":k?"Collapse model details":"Expand model details","aria-expanded":k,"aria-controls":"agent-log-model-details","data-testid":"agent-log-model-expand",children:k?t.jsx(rn,{size:14}):t.jsx(Mn,{size:14})})]}),t.jsxs("div",{className:"agent-log-model-header-toggle",children:[t.jsx("button",{className:"agent-log-mode-toggle",onClick:()=>x(K=>!K),"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(K=>!K),"aria-label":w?"Hide tool output":"Show tool output","aria-pressed":w,"data-testid":"agent-log-tool-output-toggle",title:w?"Hide tool calls and results":"Show tool calls and results",children:w?"Tools: On":"Tools: Off"}),t.jsx("button",{className:"agent-log-mode-toggle",onClick:()=>S(K=>!K),"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(jo,{size:14}):t.jsx(Xl,{size:14})})]}),k&&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:"}),O?t.jsxs("span",{className:"agent-log-model-value",children:[t.jsx(Sn,{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(Sn,{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:"}),te?t.jsxs("span",{className:"agent-log-model-value",children:[t.jsx(Sn,{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:L,children:[d!==null&&t.jsxs("div",{className:"agent-log-summary","data-testid":"agent-log-summary",children:["Showing ",U.length," of ",d," entries",!w&&e.length!==U.length?` (${e.length-U.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(bt,{size:14,className:"animate-spin"}),"Loading…"]}):"Load More"})}),R.map(K=>{const A=K.kind==="single"?K.entry:K.entries[0],I=K.showBadge?t.jsx("span",{className:"agent-log-timestamp","data-testid":"agent-log-timestamp",children:RR(A.timestamp)}):null,$=K.showBadge?t.jsxs("span",{className:"agent-log-badge-row",children:[t.jsxs("span",{className:"agent-log-agent-badge",children:["[",IR[A.agent]??A.agent,"]"]}),I]}):null;if(K.kind==="single"){const{entry:G}=K;if(G.type==="tool")return t.jsxs("div",{className:"agent-log-tool",children:[$,t.jsxs("div",{className:"agent-log-tool-title",children:["⚡ ",G.text]}),G.detail?t.jsx(Wc,{detail:G.detail,type:"tool"}):null]},K.key);if(G.type==="tool_result")return t.jsxs("div",{className:"agent-log-tool-result",children:[$,t.jsxs("div",{className:"agent-log-tool-title",children:["✓ ",G.text]}),G.detail?t.jsx(Wc,{detail:G.detail,type:"tool_result"}):null]},K.key);if(G.type==="tool_error")return t.jsxs("div",{className:"agent-log-tool-error",children:[$,t.jsxs("div",{className:"agent-log-tool-title",children:["✗ ",G.text]}),G.detail?t.jsx(Wc,{detail:G.detail,type:"tool_error"}):null]},K.key)}const N=K.kind==="single"?A.text:K.entries.map(G=>G.text).join("");return K.kind==="thinking"?t.jsxs("div",{className:"agent-log-thinking",children:[$,g?t.jsx("div",{className:"markdown-body",children:t.jsx(bi,{remarkPlugins:[xi],components:mp,children:N})}):t.jsx("pre",{className:"agent-log-plain-block",children:N})]},K.key):t.jsxs("div",{className:"agent-log-text",children:[$,g?t.jsx("div",{className:"markdown-body",children:t.jsx(bi,{remarkPlugins:[xi],components:mp,children:N})}):t.jsx("pre",{className:"agent-log-plain-block",children:N})]},K.key)}),!v&&t.jsxs("button",{type:"button",className:"agent-log-return-to-live",onClick:F,"data-testid":"agent-log-return-to-live",children:[t.jsx(rn,{size:12}),t.jsx("span",{children:"Live"})]})]})]})}function gr(e){return e??void 0}function Ko(e){return{provider:gr(e.modelProvider),modelId:gr(e.modelId)}}function Go(e){return{provider:gr(e.validatorModelProvider),modelId:gr(e.validatorModelId)}}function Jo(e){return{provider:gr(e.planningModelProvider),modelId:gr(e.planningModelId)}}function OR(e,n){return Yg(e,n)}function zR(e,n){return Qg(e,n)}function FR(e,n){return Xg(e,n)}function Kc(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 Gc(e){return e.provider&&e.modelId?`${e.provider}/${e.modelId}`:""}function Jc(e,n){return e.provider===n.provider&&e.modelId===n.modelId}function UR(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 BR({task:e,addToast:n,onTaskUpdated:s,settings:a}){const[r,o]=i.useState([]),[l,c]=i.useState([]),[d,u]=i.useState([]),[m,h]=i.useState(!1),[f,p]=i.useState(null),[g,x]=i.useState(()=>Ko(e)),[w,b]=i.useState(()=>Ko(e)),[y,S]=i.useState(()=>Go(e)),[k,C]=i.useState(()=>Go(e)),[v,j]=i.useState(()=>Jo(e)),[P,U]=i.useState(()=>Jo(e)),[E,R]=i.useState(()=>e.thinkingLevel??null),[L,F]=i.useState(()=>e.thinkingLevel??null),[M,O]=i.useState(null),q=i.useRef(e.id);i.useEffect(()=>{h(!0),p(null),Os().then(J=>{o(J.models),c(J.favoriteProviders),u(J.favoriteModels)}).catch(J=>{p(J.message||"Failed to load models")}).finally(()=>{h(!1)})},[]);const te=i.useCallback(async J=>{const B=l,Ce=B.includes(J)?B.filter(H=>H!==J):[J,...B];c(Ce);try{await kn({favoriteProviders:Ce,favoriteModels:d})}catch{c(B),n("Failed to update favorites","error")}},[l,d,n]),Z=i.useCallback(async J=>{const B=d,Ce=B.includes(J)?B.filter(H=>H!==J):[J,...B];u(Ce);try{await kn({favoriteProviders:l,favoriteModels:Ce})}catch{u(B),n("Failed to update model favorites","error")}},[d,l,n]);i.useEffect(()=>{q.current=e.id;const J=Ko(e),B=Go(e),ye=Jo(e);x(J),b(J),S(B),C(B),j(ye),U(ye);const Ce=e.thinkingLevel??null;R(Ce),F(Ce),O(null)},[e.id,e.modelProvider,e.modelId,e.validatorModelProvider,e.validatorModelId,e.planningModelProvider,e.planningModelId,e.thinkingLevel]);const K=i.useMemo(()=>Gc(g),[g]),A=i.useMemo(()=>Gc(y),[y]),I=i.useMemo(()=>Gc(v),[v]),$=i.useMemo(()=>OR(e,a),[e,a]),N=i.useMemo(()=>zR(e,a),[e,a]),G=i.useMemo(()=>FR(e,a),[e,a]),xe=M!==null,Se=i.useCallback(async(J,B)=>{const ye=e.id,Ce=w,H=k,ke=P;O(J);try{const pe=s?J==="executor"?{modelProvider:B.provider??null,modelId:B.modelId??null}:J==="validator"?{validatorModelProvider:B.provider??null,validatorModelId:B.modelId??null}:{planningModelProvider:B.provider??null,planningModelId:B.modelId??null}:{modelProvider:(J==="executor"?B:w).provider??null,modelId:(J==="executor"?B:w).modelId??null,validatorModelProvider:(J==="validator"?B:k).provider??null,validatorModelId:(J==="validator"?B:k).modelId??null,planningModelProvider:(J==="planning"?B:P).provider??null,planningModelId:(J==="planning"?B:P).modelId??null},Ae=await mi(ye,pe);if(q.current!==ye)return;const Oe=Ko(Ae),He=Go(Ae),dt=Jo(Ae);b(Oe),x(Oe),C(He),S(He),U(dt),j(dt),s?.(Ae),n(UR(J,{executor:Oe,validator:He,planning:dt}[J]),"success")}catch(pe){if(q.current!==ye)return;J==="executor"?x(Ce):J==="validator"?S(H):j(ke),n(Pe(pe)||"Failed to save model settings","error")}finally{q.current===ye&&O(null)}},[e.id,w,k,P,n,s]),je=i.useCallback(J=>{const B=Kc(J);x(B),!Jc(B,w)&&Se("executor",B)},[w,Se]),se=i.useCallback(J=>{const B=Kc(J);S(B),!Jc(B,k)&&Se("validator",B)},[k,Se]),Ve=i.useCallback(J=>{const B=Kc(J);j(B),!Jc(B,P)&&Se("planning",B)},[P,Se]),ee=i.useCallback(async J=>{const B=e.id,ye=L,Ce=J===""?null:J;R(Ce),O("thinking");try{const H=await mi(B,{thinkingLevel:Ce});if(q.current!==B)return;const ke=H.thinkingLevel??null;F(ke),R(ke),s?.(H);const pe=a?.defaultThinkingLevel??"off";n(ke===null?`Thinking level set to default (${pe})`:`Thinking level set to ${ke}`,"success")}catch(H){if(q.current!==B)return;R(ye),n(Pe(H)||"Failed to save thinking level","error")}finally{q.current===B&&O(null)}},[e.id,L,a,n,s]),ce=!w.provider&&!w.modelId,ne=!k.provider&&!k.modelId,re=!P.provider&&!P.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."}),m?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:()=>{h(!0),p(null),Os().then(J=>{o(J.models),c(J.favoriteProviders),u(J.favoriteModels)}).catch(J=>p(J.message)).finally(()=>h(!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:ce?t.jsxs("span",{className:"model-badge model-badge-default",children:["Using default",$.provider&&$.modelId?` (${$.provider}/${$.modelId})`:""]}):t.jsxs("span",{className:"model-badge model-badge-custom",children:[w.provider&&t.jsx(Sn,{provider:w.provider,size:"sm"}),w.provider,"/",w.modelId]})}),t.jsx(ys,{id:"executorModel",label:"Executor Model",value:K,onChange:je,models:r,disabled:xe,placeholder:"Select executor model…",favoriteProviders:l,onToggleFavorite:te,favoriteModels:d,onToggleModelFavorite:Z}),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:ne?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:[k.provider&&t.jsx(Sn,{provider:k.provider,size:"sm"}),k.provider,"/",k.modelId]})}),t.jsx(ys,{id:"validatorModel",label:"Reviewer Model",value:A,onChange:se,models:r,disabled:xe,placeholder:"Select reviewer model…",favoriteProviders:l,onToggleFavorite:te,favoriteModels:d,onToggleModelFavorite:Z}),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:re?t.jsxs("span",{className:"model-badge model-badge-default",children:["Using default",G.provider&&G.modelId?` (${G.provider}/${G.modelId})`:""]}):t.jsxs("span",{className:"model-badge model-badge-custom",children:[P.provider&&t.jsx(Sn,{provider:P.provider,size:"sm"}),P.provider,"/",P.modelId]})}),t.jsx(ys,{id:"planningModel",label:"Planning Model",value:I,onChange:Ve,models:r,disabled:xe,placeholder:"Select planning model…",favoriteProviders:l,onToggleFavorite:te,favoriteModels:d,onToggleModelFavorite:Z}),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:L===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:L})}),t.jsxs("select",{id:"thinkingLevel",value:E??"",onChange:J=>ee(J.target.value),disabled:xe,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:ce&&ne&&re&&L===null?"Using project or global default models.":"Model settings are up to date."})]})]})}const HR={open:t.jsx(Wl,{size:16}),closed:t.jsx(wo,{size:16}),merged:t.jsx(wg,{size:16})};function qR({taskId:e,projectId:n,prInfo:s,automationStatus:a,autoMerge:r=!1,isManualPrFlow:o=!1,prAuthAvailable:l,onPrCreated:c,onPrUpdated:d,addToast:u}){const[m,h]=i.useState(!1),[f,p]=i.useState(""),[g,x]=i.useState(""),[w,b]=i.useState(!1),[y,S]=i.useState(!1),[k,C]=i.useState(null),v=i.useCallback(async()=>{if(f.trim()){b(!0);try{const E=await Vj(e,{title:f.trim(),body:g.trim()||void 0},n);c(E),h(!1),p(""),x(""),u(`Created PR #${E.number}`,"success")}catch(E){u(Pe(E)||"Failed to create PR","error")}finally{b(!1)}}},[e,f,g,n,c,u]),j=i.useCallback(async()=>{if(s){S(!0);try{const E=await Wj(e,n);C(E),d(E.prInfo),u("PR status refreshed","success")}catch(E){u(Pe(E)||"Failed to refresh PR","error")}finally{S(!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(Ws,{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(Ws,{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."})]}):m?t.jsxs("div",{className:"pr-section",children:[t.jsxs("h4",{children:[t.jsx(Ws,{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:w,className:"pr-input"}),t.jsx("textarea",{placeholder:"PR description (optional)",value:g,onChange:E=>x(E.target.value),disabled:w,className:"pr-textarea",rows:3}),t.jsxs("div",{className:"pr-actions",children:[t.jsx("button",{className:"btn btn-sm",onClick:()=>h(!1),disabled:w,children:"Cancel"}),t.jsx("button",{className:"btn btn-primary btn-sm",onClick:v,disabled:!f.trim()||w,children:w?"Creating…":"Create PR"})]})]})]}):t.jsxs("div",{className:"pr-section",children:[t.jsxs("h4",{children:[t.jsx(Ws,{size:16,className:"pr-section-icon"}),"Pull Request"]}),t.jsxs("button",{className:"btn btn-primary btn-sm",onClick:()=>h(!0),disabled:!l,title:l?"Create a PR for this task":"PR auth unavailable — run 'gh auth login'",children:[t.jsx(gn,{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 P=HR[s.status]??t.jsx(Wl,{size:16}),U=k?.blockingReasons??[];return t.jsxs("div",{className:"pr-section",children:[t.jsxs("h4",{children:[t.jsx(Ws,{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:P}),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:j,disabled:y,title:"Refresh PR status",children:t.jsx(os,{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:U.length>0?`Waiting for: ${U.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(Ui,{size:14}),s.commentCount]}),t.jsxs("a",{href:s.url,target:"_blank",rel:"noopener noreferrer",className:"pr-link",children:[t.jsx(xg,{size:14}),"View on GitHub"]})]})]})]})}const pp=2e3;function VR(e){const n=e.updatedAt||e.createdAt,s=new Date(n).toLocaleString();return e.updatedAt?`${s} (edited)`:s}function WR(e){return e==="agent"||e==="system"}function KR({task:e,onTaskUpdated:n,addToast:s,currentAuthor:a="user",projectId:r}){const[o,l]=i.useState(""),[c,d]=i.useState(null),[u,m]=i.useState(""),[h,f]=i.useState(!1),[p,g]=i.useState(null),x=i.useMemo(()=>[...e.comments||[]].sort((j,P)=>new Date(P.createdAt).getTime()-new Date(j.createdAt).getTime()),[e.comments]),w=o.length>pp;async function b(){const j=o.trim();if(j){f(!0);try{const P=await uj(e.id,j,r);l(""),n?.(P),s("Comment added","success")}catch(P){s(Pe(P)||"Failed to add comment","error")}finally{f(!1)}}}async function y(j){const P=u.trim();if(P){f(!0);try{const U=await rj(e.id,j,P,r);d(null),m(""),n?.(U),s("Comment updated","success")}catch(U){s(Pe(U)||"Failed to update comment","error")}finally{f(!1)}}}async function S(j){g(j);try{const P=await oj(e.id,j,r);n?.(P),s("Comment deleted","success")}catch(P){s(Pe(P)||"Failed to delete comment","error")}finally{g(null)}}function k(j){j.key==="Enter"&&(j.ctrlKey||j.metaKey)&&(j.preventDefault(),b())}return t.jsxs("div",{className:"detail-section",children:[t.jsx("h4",{children:"Comments"}),x.length===0?t.jsx("div",{className:"detail-log-empty",children:"No comments yet."}):t.jsx("div",{className:"detail-activity-list",children:x.map(j=>{const P=j.author===a,U=c===j.id,E=WR(j.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:j.author}),t.jsx("span",{className:"detail-log-timestamp",children:VR(j)})]}),P&&!U?t.jsxs("div",{className:"comments-actions-row",children:[t.jsx("button",{className:"btn btn-sm",onClick:()=>{d(j.id),m(j.text)},children:"Edit"}),t.jsx("button",{className:"btn btn-danger btn-sm",onClick:()=>void S(j.id),disabled:p===j.id,children:p===j.id?"Deleting…":"Delete"})]}):null]}),U?t.jsxs("div",{className:"comments-edit-form",children:[t.jsx("textarea",{value:u,onChange:R=>m(R.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),m("")},disabled:h,children:"Cancel"}),t.jsx("button",{className:"btn btn-primary btn-sm",onClick:()=>void y(j.id),disabled:h||!u.trim(),children:"Save"})]})]}):t.jsx("div",{className:"detail-log-outcome comments-outcome-text",children:j.text})]},j.id)})}),t.jsxs("div",{className:"comments-compose-form",children:[t.jsx("textarea",{value:o,onChange:j=>l(j.target.value),onKeyDown:k,rows:3,placeholder:"Add a comment",className:"comments-textarea"}),t.jsxs("div",{className:"comments-footer-row",children:[t.jsxs("span",{className:`comments-char-count${w?" comments-char-count--over":""}`,children:[o.length," / ",pp]}),t.jsx("button",{className:"btn btn-primary btn-sm",onClick:()=>void b(),disabled:h||!o.trim()||w,children:h?"Posting…":"Add Comment"})]})]})]})}const fp="Failed to load review data.",GR="No reviewer feedback yet — this task has not produced reviewer-agent feedback in direct mode.";function Or(e){return e?new Date(e).toLocaleString():"Never"}function JR(e){return e==="manual"?"Manual":e==="auto"?"Background":"Initial load"}function YR(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 QR({task:e,projectId:n,onTaskUpdated:s,addToast:a}){const[r,o]=i.useState([]),[l,c]=i.useState(!1),[d,u]=i.useState(!1),[m,h]=i.useState(!0),[f,p]=i.useState(null),[g,x]=i.useState(null),[w,b]=i.useState(e.reviewState??null),y=r.length>0&&!d,S=w?.source==="pull-request",k=i.useMemo(()=>w?YR(w):[],[w]);i.useEffect(()=>{let L=!1;return h(!0),p(null),mS(e.id,n).then(F=>{L||(b(F.reviewState),x(F.emptyMessage??null))}).catch(()=>{L||p(fp)}).finally(()=>{L||h(!1)}),()=>{L=!0}},[e.id,n]);const C=i.useMemo(()=>w?w.source==="pull-request"?`${w.summary?.reviewDecision??"REVIEW_REQUIRED"} · ${k.length} review item(s)`:`${w.summary?.summary??"reviewer-agent"} · ${k.length} review item(s)`:"No review feedback captured yet.",[w,k.length]),v=w?w.source==="pull-request"?w.summary?.reviewDecision:w.summary?.verdict:void 0,j=l?"refreshing":w?.refreshStatus??"ready",P=j==="error"?"status-dot status-dot--error":j==="refreshing"?"status-dot status-dot--pending":"status-dot status-dot--online",U=L=>o(F=>F.includes(L)?F.filter(M=>M!==L):[...F,L]),E=async()=>{try{p(null),c(!0);const L=await hS(e.id,n);if(b(L.reviewState),s?.({...e,reviewState:L.reviewState,prInfo:L.prInfo??e.prInfo}),L.reviewState.refreshStatus==="error"){const F=L.reviewState.refreshError??"Failed to refresh review data.";p(F),a(F,"error");return}a("Review refreshed","success")}catch(L){const F=L instanceof Error?L.message:fp;p(F),a(F,"error")}finally{c(!1)}},R=async()=>{try{if(!w)return;p(null),u(!0);const L=k.filter(M=>r.includes(M.id)).map(M=>{if(!M.item)return{id:M.id,source:w.source==="pull-request"?"pr-review":"reviewer-agent",threadId:M.addressing?.snapshot?.threadId,filePath:M.addressing?.snapshot?.filePath,lineNumber:M.addressing?.snapshot?.lineNumber,author:M.addressing?.snapshot?.authorLogin,summary:M.summary,body:M.body,url:M.addressing?.snapshot?.url};const O=M.item;return{id:M.item.id,source:w.source==="pull-request"?"pr-review":"reviewer-agent",threadId:typeof O.threadId=="string"?O.threadId:void 0,filePath:M.item.path,lineNumber:typeof O.line=="number"?O.line:void 0,author:M.item.author?.login,summary:M.item.summary??M.item.body.slice(0,120),body:M.item.body,url:typeof O.url=="string"?O.url:void 0}}),F=await pS(e.id,L,n);b(F.reviewState),s?.({...F.task,reviewState:F.reviewState}),o([]),a("Same-task AI revision started from selected review feedback","success")}catch(L){const F=L instanceof Error?L.message:"Failed to queue revision";p(F),a(F,"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:C}),v?t.jsx("span",{className:`task-review-tab__decision task-review-tab__decision--${v}`,children:v}):null]}),t.jsxs("div",{className:"task-review-tab__actions",children:[t.jsx("button",{className:"btn btn-sm",onClick:E,disabled:l||m,children:l?"Refreshing…":"Refresh"}),t.jsx("button",{className:"btn btn-primary btn-sm",disabled:!y,onClick:R,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:P,"aria-hidden":"true"}),t.jsxs("span",{children:[j==="error"?"Refresh failed":j==="refreshing"?"Refreshing":"Up to date"," · Last refreshed: ",Or(w?.lastRefreshedAt)," · ",JR(w?.refreshSource)]})]}),m?t.jsx("div",{className:"task-review-tab__meta",children:"Loading review data…"}):null,!m&&f?t.jsx("div",{className:"task-review-tab__error",children:f}):null,!m&&!f&&!S&&k.length===0?t.jsx("div",{className:"task-review-tab__empty",children:g??GR}):null,!m&&!f&&k.length>0?t.jsx("ul",{className:"task-review-tab__list",children:k.map(L=>t.jsx("li",{className:"task-review-tab__item card",children:t.jsxs("label",{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",{type:"checkbox",checked:r.includes(L.id),onChange:()=>U(L.id)}),t.jsxs("span",{className:"task-review-tab__item-summary",children:[L.path?`${L.path}: `:"",L.summary]}),t.jsx("span",{className:`task-review-tab__status task-review-tab__status--${L.status}`,children:L.status})]}),t.jsx("div",{className:"task-review-tab__meta",children:Or(L.createdAt)}),L.addressing?t.jsxs("div",{className:"task-review-tab__meta",children:["Selected: ",Or(L.addressing.selectedAt),L.addressing.startedAt?` · Started: ${Or(L.addressing.startedAt)}`:"",L.addressing.completedAt?` · Completed: ${Or(L.addressing.completedAt)}`:"",L.addressing.error?` · Error: ${L.addressing.error}`:""]}):null,t.jsx("pre",{className:"task-review-tab__body",children:L.body})]})},L.id))}):null,S&&!m&&!f&&k.length===0?t.jsx("div",{className:"task-review-tab__empty",children:"No review items yet."}):null]})}function XR(e){return e?e.slice(0,7):"Unknown"}function ZR({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:XR(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 Ex(e){return e.split(`
681
- `).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}
682
- `},a):t.jsx(kl.Fragment,{children:`${s}
683
- `},a)})}function eI(e){switch(e){case"added":return"A";case"deleted":return"D";case"modified":return"M";default:return"?"}}function tI({isOpen:e,taskId:n,files:s,stats:a,mergeDetails:r,column:o,onClose:l,onRefresh:c}){const[d,u]=i.useState(null),[m,h]=i.useState(!0),f=i.useRef(null);Ai(f,e,"fusion:changes-diff-modal-size");const p=qi(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)},[]),x=i.useCallback(()=>{u(y=>y!==null&&y<s.length-1?y+1:y)},[]);if(i.useEffect(()=>{if(!e)return;const y=S=>{if(S.key==="Escape"){l();return}S.key==="ArrowUp"&&(S.metaKey||S.ctrlKey)&&(S.preventDefault(),g()),S.key==="ArrowDown"&&(S.metaKey||S.ctrlKey)&&(S.preventDefault(),x())};return document.addEventListener("keydown",y),()=>document.removeEventListener("keydown",y)},[e,l,g,x]),!e)return null;const w=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(hi,{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(Vl,{})}),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:x,disabled:d===null||d>=s.length-1,title:"Next file (Ctrl+↓)","aria-label":"Next file",children:t.jsx(Mn,{})})]}),t.jsx("button",{className:`btn btn-sm ${m?"btn-primary":""}`,onClick:()=>h(y=>!y),title:m?"Disable word wrap":"Enable word wrap","aria-label":"Toggle word wrap",children:t.jsx(Nl,{size:14})}),c&&t.jsxs("button",{className:"btn btn-sm",onClick:c,children:[t.jsx(os,{size:14}),"Refresh"]}),t.jsx("button",{className:"modal-close",onClick:l,"aria-label":"Close",children:t.jsx(nn,{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(ko,{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,S)=>t.jsxs("button",{className:`changes-diff-file-item ${d===S?"selected":""}`,onClick:()=>u(S),title:y.path,children:[t.jsx("span",{className:`changes-file-status changes-file-status--${y.status}`,children:eI(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:w?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:w.path}),t.jsxs("span",{className:"changes-diff-file-header-stats",children:["+",w.additions," -",w.deletions]})]}),w.patch?t.jsx("div",{className:"changes-diff-viewer",children:t.jsx("pre",{className:`changes-diff-patch ${m?"changes-diff-patch--wrap":"changes-diff-patch--nowrap"}`,children:t.jsx("code",{children:Ex(w.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(hi,{size:48,opacity:.3}),t.jsx("p",{children:"Select a file to view its diff"})]})})]})]})})}function _x(e){switch(e){case"added":return"A";case"deleted":return"D";case"modified":return"M";default:return"?"}}function Yc(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(ko,{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(hi,{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:_x("unknown")}),t.jsx("span",{className:"changes-file-path",title:a,children:t.jsx("bdo",{dir:"ltr",children:a})})]})},a))})]})}function nI({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}),[m,h]=i.useState(!0),[f,p]=i.useState(null),[g,x]=i.useState(new Set),[w,b]=i.useState(null),[y,S]=i.useState(!0),[k,C]=i.useState(!1),v=a==="done",j=v&&!!r?.commitSha,P=a==="in-progress"||a==="in-review"||j,U=i.useCallback(async()=>{if(!P){h(!1);return}try{h(!0),p(null);const M=await zg(e,void 0,s),O=M.files.map(q=>({path:q.path,status:q.status,additions:q.additions,deletions:q.deletions,patch:q.patch}));c(O),u(M.stats),O.length>0&&(x(new Set([O[0].path])),b(0))}catch(M){p(Pe(M)||"Failed to load diff")}finally{h(!1)}},[e,s,P]);i.useEffect(()=>{U()},[U]);const E=M=>{x(O=>{const q=new Set(O);if(q.has(M))q.delete(M);else{q.add(M);const te=l.findIndex(Z=>Z.path===M);te!==-1&&b(te)}return q})},R=M=>{if(M<0||M>=l.length)return;const O=l[M].path;x(new Set([O])),b(M)},L=w!==null&&w>0,F=w!==null&&w<l.length-1;if(m)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(Ps,{size:16}),t.jsxs("span",{children:["Error loading changes: ",f]})]})});if(!v&&!n)return o&&o.length>0?Yc(o,!1):t.jsx("div",{className:"detail-section",children:t.jsxs("div",{className:"task-changes-state task-changes-state--empty",children:[t.jsx(hi,{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(v&&!j){if(o&&o.length>0)return Yc(o,!0,r);const M=r?.filesChanged,O=r?.insertions,q=r?.deletions,te=M!=null||O!=null||q!=null;return t.jsx("div",{className:"detail-section",children:t.jsxs("div",{className:"task-changes-state task-changes-state--empty",children:[t.jsx(hi,{size:24}),t.jsx("p",{children:"Detailed file changes unavailable."}),t.jsx("span",{className:"task-changes-state-hint",children:te?`Merge summary: ${M??0} file${(M??0)===1?"":"s"} changed, +${O??0} additions, -${q??0} deletions.`:"No merge commit was recorded for this task."})]})})}return l.length===0?o&&o.length>0?Yc(o,v,r):t.jsx("div",{className:"detail-section",children:t.jsxs("div",{className:"task-changes-state task-changes-state--empty",children:[t.jsx(hi,{size:24}),t.jsx("p",{children:"No files modified."}),t.jsx("span",{className:"task-changes-state-hint",children:v?"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:[v&&r&&t.jsxs("div",{className:"commit-diff-meta",children:[r.commitSha&&t.jsxs("div",{className:"commit-diff-sha",children:[t.jsx(ko,{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(hi,{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:()=>L&&R(w-1),disabled:!L,title:"Previous file","aria-label":"Previous file",children:t.jsx(Vl,{})}),t.jsx("span",{className:"changes-nav-indicator","aria-live":"polite",children:w!==null?`${w+1}/${l.length}`:`—/${l.length}`}),t.jsx("button",{className:"btn btn-sm btn-icon",onClick:()=>F&&R(w+1),disabled:!F,title:"Next file","aria-label":"Next file",children:t.jsx(Mn,{})})]}),t.jsx("button",{className:`btn btn-sm ${y?"btn-primary":""}`,onClick:()=>S(M=>!M),title:y?"Disable word wrap":"Enable word wrap","aria-label":"Toggle word wrap",children:t.jsx(Nl,{size:14})})]}),t.jsxs("div",{className:"changes-header-actions-secondary",children:[t.jsx("button",{className:"btn btn-sm",onClick:U,disabled:m,children:"Refresh"}),t.jsx("button",{className:"btn btn-sm btn-icon",onClick:()=>C(!0),title:"Expand to full-screen diff view","aria-label":"Expand diff view",children:t.jsx(Xl,{})})]})]})]}),t.jsx("div",{className:"changes-file-list task-changes-file-list--compact",children:l.map(M=>{const O=g.has(M.path);return t.jsxs("div",{className:`changes-file-item ${O?"expanded":""}`,children:[t.jsxs("button",{className:"changes-file-header",onClick:()=>E(M.path),children:[t.jsx("span",{className:"changes-file-toggle",children:O?t.jsx(rn,{size:14}):t.jsx(Mn,{size:14})}),t.jsx("span",{className:`changes-file-status changes-file-status--${M.status}`,title:M.status,children:_x(M.status)}),t.jsx("span",{className:"changes-file-path",title:M.path,children:t.jsx("bdo",{dir:"ltr",children:M.path})}),t.jsxs("span",{className:"changes-file-stat",title:`+${M.additions} -${M.deletions}`,children:["+",M.additions," -",M.deletions]})]}),O&&M.patch&&t.jsx("div",{className:"changes-file-content",children:t.jsx("pre",{className:`changes-diff-patch ${y?"changes-diff-patch--wrap":"changes-diff-patch--nowrap"}`,children:t.jsx("code",{children:Ex(M.patch)})})})]},M.path)})}),t.jsx(tI,{isOpen:k,taskId:e,files:l,stats:d,mergeDetails:r,column:a,onClose:()=>C(!1),onRefresh:U})]})}function gp(e){return{executorValue:e?.executorProvider&&e?.executorModelId?`${e.executorProvider}/${e.executorModelId}`:"",validatorValue:e?.validatorProvider&&e?.validatorModelId?`${e.validatorProvider}/${e.validatorModelId}`:""}}function sI(e){return e.trim().toLowerCase().replace(/[^a-z0-9_-]+/g,"-").replace(/-+/g,"-").replace(/^[-_]+|[-_]+$/g,"").slice(0,32)||"preset"}function t5(e,n){const s=sI(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 iI(e){return e==="online"?"Online":e==="connecting"?"Connecting":e==="error"?"Error":"Offline"}const bp=["image/png","image/jpeg","image/gif","image/webp"];function aI(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 Mx({mode:e,description:n,onDescriptionChange:s,title:a,onTitleChange:r,dependencies:o,onDependenciesChange:l,branch:c,onBranchChange:d,baseBranch:u,onBaseBranchChange:m,nodeId:h,onNodeIdChange:f,nodeOptions:p,nodeOverrideDisabled:g=!1,nodeOverrideDisabledReason:x,priority:w,onPriorityChange:b,executorModel:y,onExecutorModelChange:S,validatorModel:k,onValidatorModelChange:C,planningModel:v,onPlanningModelChange:j,thinkingLevel:P,onThinkingLevelChange:U,presetMode:E,onPresetModeChange:R,selectedPresetId:L,onSelectedPresetIdChange:F,selectedWorkflowSteps:M,onWorkflowStepsChange:O,onDefaultOnApplied:q,pendingImages:te,onImagesChange:Z,tasks:K,projectId:A,disabled:I=!1,addToast:$,isActive:N=!0,onAutoSaveDescription:G,onPlanningMode:xe,onSubtaskBreakdown:Se,onClose:je,renderBelowPrimary:se,renderBelowModelConfiguration:Ve,hideDependencies:ee,autoExpandMoreOptionsOnSelection:ce=!0,reviewLevel:ne,onReviewLevelChange:re,executionMode:J,onExecutionModeChange:B}){const ye=(ee?!1:o.length>0)||te.length>0||M.length>0||E!=="default"||(w??js)!==js||y!==""||k!==""||(v||"")!==""||(P||"")!==""||ne!==void 0||J==="fast"||(c||"")!==""||(u||"")!==""||(h||"")!=="",[Ce,H]=i.useState(!1),[ke,pe]=i.useState(ce?ye:!1),[Ae,Oe]=i.useState(""),[He,dt]=i.useState([]),[Fe,fe]=i.useState([]),[$e,De]=i.useState([]),[ot,Be]=i.useState(!1),[we,Q]=i.useState(null),[_e,lt]=i.useState([]),[ht,mt]=i.useState("idle"),[xt,Ie]=i.useState(!1),[Ue,pt]=i.useState(!1),[oe,le]=i.useState(!1),ge=i.useRef(null),Ne=i.useRef(null),ue=i.useRef(null),qe=i.useRef(null),me=i.useRef(null),tt=i.useRef(null),Ct=i.useRef(null),wt=i.useRef(!1),$t=i.useRef(ye),Vt=i.useRef(n.trim()),Mt=i.useRef(n.trim());i.useEffect(()=>{N&&(Be(!0),Os().then(ae=>{dt(ae.models),fe(ae.favoriteProviders),De(ae.favoriteModels)}).catch(()=>{}).finally(()=>Be(!1)),Zl(A).then(ae=>Q(ae)).catch(()=>Q(null)),_o(A).then(ae=>lt(ae.filter(Le=>Le.enabled))).catch(()=>lt([])))},[N,A]);const Dt=we?.modelPresets||[],Qt=Dt.find(ae=>ae.id===L),Kt=(ee?!1:o.length>0)||te.length>0||M.length>0||E!=="default"||(w??js)!==js||y!==""||k!==""||(v||"")!==""||(P||"")!==""||ne!==void 0||J==="fast"||(c||"")!==""||(u||"")!==""||(h||"")!=="";i.useEffect(()=>{if(e!=="create"||!N||!we?.autoSelectModelPreset)return;const ae=(we.defaultPresetBySize,void 0);if(ae){const Le=gp(ae);F(ae.id),R("preset"),S(Le.executorValue),C(Le.validatorValue)}},[N,we,Dt,e]);const Bt=i.useRef(!1);i.useEffect(()=>{if(e!=="create"||!N||Bt.current||_e.length===0)return;const ae=_e.filter(At=>At.defaultOn);if(ae.length===0)return;Bt.current=!0;const Le=ae.map(At=>At.id);O(Le),q?.(Le)},[e,N,_e]),i.useEffect(()=>{N||(Bt.current=!1)},[N]),i.useEffect(()=>{if(!ce){$t.current=Kt;return}Kt&&!$t.current&&pe(!0),$t.current=Kt},[Kt,ce]),i.useEffect(()=>{ke||(H(!1),Oe(""))},[ke]),i.useEffect(()=>{e!=="edit"||!N||qe.current&&(qe.current.focus(),qe.current.select())},[e,N]),i.useEffect(()=>{if(!Ce)return;const ae=Le=>{Ne.current&&!Ne.current.contains(Le.target)&&H(!1)};return document.addEventListener("mousedown",ae),()=>document.removeEventListener("mousedown",ae)},[Ce]),i.useEffect(()=>{(e!=="edit"||I)&&le(!1)},[e,I]),i.useEffect(()=>{if(e!=="edit"){mt("idle");return}const ae=n.trim();Vt.current=ae,Mt.current=ae,mt("idle")},[e]),i.useEffect(()=>{if(e!=="edit"||!G||!N)return;const ae=n.trim(),Le=Vt.current;if(ae===Le||ae===Mt.current){tt.current&&(clearTimeout(tt.current),tt.current=null),wt.current||mt("idle");return}return tt.current&&clearTimeout(tt.current),tt.current=setTimeout(async()=>{if(!wt.current){wt.current=!0,mt("saving");try{await G(ae),Mt.current=ae,mt("saved"),Ct.current&&clearTimeout(Ct.current),Ct.current=setTimeout(()=>{mt("idle"),Ct.current=null},2e3)}catch{mt("idle")}finally{wt.current=!1,tt.current=null}}},1500),()=>{tt.current&&(clearTimeout(tt.current),tt.current=null)}},[e,n,G,N]),i.useEffect(()=>()=>{tt.current&&clearTimeout(tt.current),Ct.current&&clearTimeout(Ct.current)},[]),i.useEffect(()=>{if(!xt)return;const ae=Le=>{ge.current&&!ge.current.contains(Le.target)&&Ie(!1)};return document.addEventListener("mousedown",ae),()=>document.removeEventListener("mousedown",ae)},[xt]);const on=i.useCallback(ae=>{const Le=ae.clipboardData?.items;if(Le)for(let At=0;At<Le.length;At++){const Lt=Le[At];if(Lt.type.startsWith("image/")){const Ft=Lt.getAsFile();if(Ft&&bp.includes(Ft.type)){ae.preventDefault(),Z([...te,{file:Ft,previewUrl:URL.createObjectURL(Ft)}]);return}}}},[te,Z]),fn=i.useCallback(ae=>{ae.preventDefault();const Le=ae.dataTransfer.files;for(let At=0;At<Le.length;At++){const Lt=Le[At];if(bp.includes(Lt.type)){Z([...te,{file:Lt,previewUrl:URL.createObjectURL(Lt)}]);return}}},[te,Z]),Jt=i.useCallback(ae=>{const Le=te[ae];Le&&URL.revokeObjectURL(Le.previewUrl),Z(te.filter((At,Lt)=>Lt!==ae))},[te,Z]),an=i.useCallback(ae=>{l(o.includes(ae)?o.filter(Le=>Le!==ae):[...o,ae])},[o,l]),zt=(ae,Le)=>ae.length>Le?ae.slice(0,Le)+"…":ae,en=i.useCallback(ae=>{s(ae.target.value);const Le=ae.target;Le.style.height="auto",Le.style.height=Le.scrollHeight+"px"},[s]),Zt=i.useCallback(()=>{le(ae=>!ae)},[]),dn=i.useCallback(ae=>{!oe||ae.key!=="Escape"||(ae.preventDefault(),ae.stopPropagation(),le(!1))},[oe]),ve=i.useCallback(async ae=>{const Le=n.trim();if(!(!Le||Ue)){pt(!0);try{const At=await Tg(Le,ae,A);s(At),Ie(!1),$("Description refined with AI","success"),ue.current&&(ue.current.style.height="auto",ue.current.style.height=ue.current.scrollHeight+"px")}catch(At){const Lt=$g(At);$(Lt,"error")}finally{pt(!1)}}},[n,Ue,$,s,A]),ze=i.useCallback(async ae=>{const Le=Fe,Lt=Le.includes(ae)?Le.filter(Ft=>Ft!==ae):[ae,...Le];fe(Lt);try{await kn({favoriteProviders:Lt,favoriteModels:$e})}catch{fe(Le)}},[Fe,$e]),We=i.useCallback(async ae=>{const Le=$e,Lt=Le.includes(ae)?Le.filter(Ft=>Ft!==ae):[ae,...Le];De(Lt);try{await kn({favoriteProviders:Fe,favoriteModels:Lt})}catch{De(Le)}},[$e,Fe]),Ze=i.useCallback(ae=>{if(ae<=0)return;const Le=[...M];[Le[ae-1],Le[ae]]=[Le[ae],Le[ae-1]],O(Le)},[M,O]),Ye=i.useCallback(ae=>{if(ae>=M.length-1)return;const Le=[...M];[Le[ae],Le[ae+1]]=[Le[ae+1],Le[ae]],O(Le)},[M,O]),It=i.useCallback(ae=>{O(M.filter(Le=>Le!==ae))},[M,O]),St=new Map;for(const ae of _e)St.set(ae.id,{name:ae.name,description:ae.description});const Ht=K.filter(ae=>!o.includes(ae.id)).sort((ae,Le)=>{const At=Le.createdAt.localeCompare(ae.createdAt);if(At!==0)return At;const Lt=parseInt(ae.id.slice(ae.id.lastIndexOf("-")+1),10)||0;return(parseInt(Le.id.slice(Le.id.lastIndexOf("-")+1),10)||0)-Lt}),jt=Ae?Ht.filter(ae=>ae.id.toLowerCase().includes(Ae.toLowerCase())||ae.title&&ae.title.toLowerCase().includes(Ae.toLowerCase())||ae.description&&ae.description.toLowerCase().includes(Ae.toLowerCase())):Ht;return t.jsxs("div",{className:"task-form",onDrop:fn,onDragOver:ae=>ae.preventDefault(),onPaste:on,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:qe,autoFocus:!0,id:"task-form-title",type:"text",className:"modal-edit-input",placeholder:"Task title",value:a||"",onChange:ae=>r(ae.target.value),disabled:I})]}),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${ht==="idle"?"":" is-visible"}`,"aria-live":"polite",children:ht==="saving"?"Saving...":ht==="saved"?"Saved":""})]}),t.jsxs("div",{className:`description-with-refine${oe?" description--fullscreen":""}`,ref:ge,onKeyDown:dn,children:[oe&&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:Zt,"aria-label":"Collapse description",title:"Collapse description",children:t.jsx(jo,{size:14})})]}),t.jsx("textarea",{ref:ue,autoFocus:e==="create",id:"task-form-description",value:n,onChange:en,placeholder:"What needs to be done?",rows:e==="edit"?8:5,disabled:I||Ue}),(()=>{const ae=!!n.trim()&&!I;return t.jsxs(t.Fragment,{children:[!oe&&t.jsx("button",{type:"button",className:`btn btn-sm description-expand-btn${ae?" description-expand-btn--offset":" description-expand-btn--flush"}`,onClick:Zt,"aria-label":"Expand description",title:"Expand description",children:t.jsx(Xl,{size:14})}),ae&&t.jsxs("button",{type:"button",className:`btn btn-sm refine-button ${Ue?"refine-button--loading":""}`,onClick:()=>Ie(Le=>!Le),disabled:Ue,"data-testid":"refine-button",title:"Refine description with AI",children:[t.jsx(ps,{size:12,style:{verticalAlign:"middle"}}),Ue?"Refining...":"Refine"]})]})})(),xt&&t.jsxs("div",{className:"refine-menu refine-menu--modal",onMouseDown:ae=>ae.preventDefault(),children:[t.jsxs("div",{className:"refine-menu-item",onClick:()=>ve("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:()=>ve("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:()=>ve("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:()=>ve("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"&&(xe||Se)&&t.jsxs("div",{className:"task-form-description-actions","data-testid":"task-form-description-actions",children:[xe&&t.jsx("button",{type:"button",className:"btn btn-sm",onClick:()=>{const ae=n.trim();if(!ae){$("Enter a description first","error");return}je?.(),xe(ae)},disabled:I||!n.trim(),"data-testid":"task-form-plan-button",children:"Plan"}),Se&&t.jsx("button",{type:"button",className:"btn btn-sm",onClick:()=>{const ae=n.trim();if(!ae){$("Enter a description first","error");return}je?.(),Se(ae)},disabled:I||!n.trim(),"data-testid":"task-form-subtask-button",children:"Subtask"})]})]}),se,t.jsxs("button",{type:"button",className:"task-form-more-options-toggle",onClick:()=>pe(ae=>!ae),"aria-expanded":ke,"aria-controls":"task-form-more-options",disabled:I,"data-testid":"task-form-more-options-toggle",children:[t.jsx("span",{children:"More options"}),ke?t.jsx(Ei,{size:14}):t.jsx(rn,{size:14})]}),t.jsxs("div",{id:"task-form-more-options",className:`task-form-more-options${ke?"":" collapsed"}`,"aria-hidden":!ke,hidden:!ke,"data-testid":"task-form-more-options",children:[t.jsxs("div",{className:"form-group",children:[t.jsx("label",{children:"Attachments"}),te.length>0&&t.jsx("div",{className:"inline-create-previews",children:te.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:I,title:"Remove image",children:"×"})]},ae.previewUrl))}),t.jsx("input",{ref:me,type:"file",accept:"image/*",onChange:ae=>{const Le=ae.target.files?.[0];Le&&(Z([...te,{file:Le,previewUrl:URL.createObjectURL(Le)}]),ae.target.value="")},style:{display:"none"}}),t.jsx("button",{type:"button",className:"btn btn-sm",onClick:()=>me.current?.click(),disabled:I,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:h??"",onChange:ae=>f(ae.target.value||void 0),disabled:I||g,children:[t.jsx("option",{value:"",children:"Use project default / local"}),(p??[]).map(ae=>t.jsxs("option",{value:ae.id,children:[ae.name," (",iI(ae.status),")"]},ae.id))]}),(()=>{const ae=(p??[]).find(Le=>Le.id===h);return ae?t.jsx("div",{className:"task-form-node-status",children:t.jsx(Ca,{status:ae.status,showLabel:!0})}):null})(),t.jsx("small",{children:x??"Task override takes priority over project default node routing."})]}),!ee&&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:Ne,children:[t.jsx("button",{type:"button",className:"btn btn-sm dep-trigger",onClick:()=>H(ae=>!ae),disabled:I,children:o.length>0?`${o.length} selected`:"Add dependencies"}),Ce&&t.jsxs("div",{className:"dep-dropdown",children:[t.jsx("input",{className:"dep-dropdown-search",placeholder:"Search tasks…",autoFocus:!0,value:Ae,onChange:ae=>Oe(ae.target.value),onClick:ae=>ae.stopPropagation()}),jt.length===0?t.jsx("div",{className:"dep-dropdown-empty",children:"No available tasks"}):jt.map(ae=>t.jsxs("div",{className:`dep-dropdown-item${o.includes(ae.id)?" selected":""}`,onClick:()=>an(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:zt(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:()=>an(ae),disabled:I,children:"×"})]},ae))})]})}),(d||m)&&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:I})]}),m&&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=>m(ae.target.value),placeholder:"e.g. main",disabled:I})]})]}),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:w??js,onChange:ae=>b(ae.target.value),disabled:I,children:oa.map(ae=>t.jsx("option",{value:ae,children:ae[0].toUpperCase()+ae.slice(1)},ae))})]}),B&&J!==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:J,onChange:ae=>B(ae.target.value),disabled:I,children:[t.jsx("option",{value:"standard",children:"Standard"}),t.jsx("option",{value:"fast",children:"Fast"})]})]}),ot?t.jsx("div",{className:"model-selector-loading",children:"Loading models…"}):He.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"?L:E,onChange:ae=>{const Le=ae.target.value;if(Le==="default"){R("default"),F(""),S(""),C("");return}if(Le==="custom"){R("custom"),F("");return}const At=Dt.find(Ft=>Ft.id===Le),Lt=gp(At);R("preset"),F(Le),S(Lt.executorValue),C(Lt.validatorValue)},disabled:I,children:[t.jsx("option",{value:"default",children:"Use default"}),Dt.length>0?t.jsx("option",{disabled:!0,children:"──────────"}):null,Dt.map(ae=>t.jsx("option",{value:ae.id,children:ae.name},ae.id)),t.jsx("option",{value:"custom",children:"Custom"})]})]}),E==="preset"&&Qt?t.jsxs("small",{children:["Using preset: ",Qt.name]}):null,E==="preset"?t.jsx("button",{type:"button",className:"btn btn-sm",onClick:()=>R("custom"),disabled:I,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(ys,{id:"executor-model",label:"Executor Model",value:y,onChange:ae=>{R("custom"),F(""),S(ae)},models:He,disabled:I||E==="preset",favoriteProviders:Fe,onToggleFavorite:ze,favoriteModels:$e,onToggleModelFavorite:We})]}),t.jsxs("div",{className:"model-select-row",children:[t.jsx("label",{htmlFor:"validator-model",className:"model-select-label",children:"Reviewer"}),t.jsx(ys,{id:"validator-model",label:"Reviewer Model",value:k,onChange:ae=>{R("custom"),F(""),C(ae)},models:He,disabled:I||E==="preset",favoriteProviders:Fe,onToggleFavorite:ze,favoriteModels:$e,onToggleModelFavorite:We})]}),j&&t.jsxs("div",{className:"model-select-row",children:[t.jsx("label",{htmlFor:"planning-model",className:"model-select-label",children:"Planning"}),t.jsx(ys,{id:"planning-model",label:"Planning Model",value:v||"",onChange:ae=>{R("custom"),F(""),j(ae)},models:He,disabled:I||E==="preset",favoriteProviders:Fe,onToggleFavorite:ze,favoriteModels:$e,onToggleModelFavorite:We})]}),U&&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:P||"",onChange:ae=>U(ae.target.value),disabled:I||E==="preset",children:[t.jsxs("option",{value:"",children:["Default (",we?.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"})]})]}),re&&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:ne??"",onChange:ae=>re(ae.target.value===""?void 0:parseInt(ae.target.value,10)),disabled:I,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"})]})]})]})]}),Ve,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:_e.length>0&&_e.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:M.includes(ae.id),onChange:Le=>{O(Le.target.checked?[...M,ae.id]:M.filter(At=>At!==ae.id))},disabled:I}),t.jsxs("div",{children:[t.jsxs("span",{className:"workflow-step-name",children:[ae.name,aI(ae.phase||"pre-merge",ae.id,"workflow-step-phase")]}),t.jsx("div",{className:"workflow-step-description",children:ae.description})]})]},ae.id))})]}),M.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:"}),M.map((ae,Le)=>{const At=St.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:At?.name||ae}),t.jsxs("div",{className:"workflow-step-order-actions",children:[t.jsx("button",{type:"button",className:"btn btn-icon btn-sm",onClick:()=>Ze(Le),disabled:I||Le===0,"data-testid":`workflow-step-move-up-${ae}`,title:"Move up",children:t.jsx(Ei,{})}),t.jsx("button",{type:"button",className:"btn btn-icon btn-sm",onClick:()=>Ye(Le),disabled:I||Le===M.length-1,"data-testid":`workflow-step-move-down-${ae}`,title:"Move down",children:t.jsx(rn,{})}),t.jsx("button",{type:"button",className:"btn btn-icon btn-sm",onClick:()=>It(ae),disabled:I,"data-testid":`workflow-step-remove-${ae}`,title:"Remove",children:t.jsx(nn,{})})]})]},ae)})]})]})]})]})}const xp={pre:({children:e,className:n,...s})=>t.jsx("pre",{...s,className:["workflow-markdown-pre",n].filter(Boolean).join(" "),children:e}),table:({children:e,className:n,...s})=>t.jsx("table",{...s,className:["workflow-markdown-table",n].filter(Boolean).join(" "),children:e})};function rI(e){switch(e){case"passed":return"Passed";case"failed":return"Failed";case"skipped":return"Skipped";case"pending":return"Running…";default:return e}}function oI(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 lI(e){return e?new Date(e).toLocaleString():null}function cI(e){const n=e.split(`
684
- `);return n.length<=1?e:`${n.length} lines`}function Yo(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 dI({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]),e.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:["⚡ ",l.text,l.detail&&t.jsxs("span",{className:"workflow-live-log-detail",children:[" — ",l.detail]})]},c):l.type==="tool_result"?t.jsxs("div",{className:"workflow-live-log-tool-result",children:["✓ ",l.text,l.detail&&t.jsxs("span",{className:"workflow-live-log-detail",children:[" — ",l.detail]})]},c):l.type==="tool_error"?t.jsxs("div",{className:"workflow-live-log-tool-error",children:["✗ ",l.text,l.detail&&t.jsxs("span",{className:"workflow-live-log-detail",children:[" — ",l.detail]})]},c):l.type==="thinking"?t.jsx("div",{className:"workflow-live-log-thinking",children:l.text},c):t.jsx("span",{className:"workflow-live-log-text",children:l.text},c))})}function uI({taskId:e,results:n,loading:s,enabledWorkflowSteps:a,canEdit:r,projectId:o,isTaskInProgress:l,onWorkflowStepsChange:c}){const[d,u]=i.useState({}),[m,h]=i.useState({}),[f,p]=i.useState(null),[g,x]=i.useState([]),[w,b]=i.useState(!1),y=n.some(N=>N.status==="pending"),{entries:S}=Nx(e,!!l&&y,o);i.useEffect(()=>{let N=!1;return _o(o).then(G=>{N||x(G.filter(xe=>xe.enabled))}).catch(()=>{N||x([])}),()=>{N=!0}},[o]);const k=a??[],C=i.useMemo(()=>g.map(N=>({id:N.id,name:N.name,description:N.description,phase:N.phase||"pre-merge"})),[g]),v=i.useMemo(()=>new Map(C.map(N=>[N.id,N])),[C]),j=N=>{u(G=>({...G,[N]:!G[N]}))},P=N=>{h(G=>{const xe=G[N]??"markdown";return{...G,[N]:xe==="markdown"?"plain":"markdown"}})},U=N=>{p(N)},E=()=>{p(null)};i.useEffect(()=>{if(!f)return;const N=G=>{G.key==="Escape"&&E()};return document.addEventListener("keydown",N),()=>{document.removeEventListener("keydown",N)}},[f]);const R=i.useCallback((N,G)=>{if(c){if(G){if(k.includes(N)){c(k);return}c([...k,N]);return}c(k.filter(xe=>xe!==N))}},[c,k]),L=i.useCallback(N=>{if(!c||N<=0)return;const G=[...k];[G[N-1],G[N]]=[G[N],G[N-1]],c(G)},[c,k]),F=i.useCallback(N=>{if(!c||N>=k.length-1)return;const G=[...k];[G[N],G[N+1]]=[G[N+1],G[N]],c(G)},[c,k]),M=i.useCallback(N=>{c&&c(k.filter(G=>G!==N))},[c,k]),O=n.length>0,q=k.length>0;i.useEffect(()=>{r||b(!1)},[r]);const te=i.useMemo(()=>k.map(N=>{const G=v.get(N);return{id:N,name:G?.name||N,description:G?.description||"Step definition not found.",phase:G?.phase||"pre-merge"}}),[k,v]),Z=()=>!r||!w||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:k.includes(N.id),onChange:G=>R(N.id,G.target.checked)}),t.jsxs("div",{children:[t.jsxs("span",{className:"workflow-step-name",children:[N.name,Yo(N.phase,N.id,"workflow-step-phase")]}),t.jsx("div",{className:"workflow-step-description",children:N.description})]})]},N.id))})]}),k.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:"}),k.map((N,G)=>{const xe=v.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:G+1}),t.jsx("span",{className:"workflow-step-order-name",children:xe?.name||N}),t.jsxs("div",{className:"workflow-step-order-actions",children:[t.jsx("button",{type:"button",className:"btn btn-icon btn-sm",onClick:()=>L(G),disabled:G===0,"data-testid":`workflow-step-move-up-${N}`,title:"Move up",children:t.jsx(Ei,{})}),t.jsx("button",{type:"button",className:"btn btn-icon btn-sm",onClick:()=>F(G),disabled:G===k.length-1,"data-testid":`workflow-step-move-down-${N}`,title:"Move down",children:t.jsx(rn,{})}),t.jsx("button",{type:"button",className:"btn btn-icon btn-sm",onClick:()=>M(N),"data-testid":`workflow-step-remove-${N}`,title:"Remove",children:t.jsx(nn,{})})]})]},N)})]})]}),K=()=>{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(!O)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(se=>se.status==="passed").length,G=n.filter(se=>se.status==="failed").length,xe=n.filter(se=>se.status==="skipped").length,Se=n.filter(se=>se.status==="pending").length,je=[`${n.length} step${n.length!==1?"s":""}`];return N>0&&je.push(`${N} passed`),G>0&&je.push(`${G} failed`),xe>0&&je.push(`${xe} skipped`),Se>0&&je.push(`${Se} 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:je.join(" · ")}),n.map((se,Ve)=>{const ee=se.phase||"pre-merge",ce=d[se.workflowStepId]??!1;return t.jsxs("div",{className:`workflow-result-item workflow-result-item--${se.status}`,"data-testid":`workflow-result-item-${se.workflowStepId}`,children:[t.jsxs("div",{className:"workflow-result-header",children:[t.jsxs("div",{className:"workflow-result-name",children:[se.workflowStepName,Yo(ee,se.workflowStepId,"workflow-result-phase")]}),t.jsx("span",{className:`workflow-result-badge workflow-result-badge--${se.status}`,"data-testid":`workflow-result-badge-${se.workflowStepId}`,children:rI(se.status)})]}),t.jsxs("div",{className:"workflow-result-meta",children:[se.startedAt&&t.jsxs("span",{className:"workflow-result-timestamp",children:["Started: ",lI(se.startedAt)]}),se.completedAt&&t.jsx("span",{className:"workflow-result-duration",children:oI(se.startedAt,se.completedAt)})]}),se.status==="pending"&&se.startedAt?t.jsx(dI,{entries:S,startedAt:se.startedAt,stepId:se.workflowStepId}):se.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:()=>j(se.workflowStepId),"data-testid":`workflow-result-toggle-${se.workflowStepId}`,children:ce?"Hide output":"Show output"}),!ce&&t.jsx("span",{className:"workflow-result-output-preview","data-testid":`workflow-result-preview-${se.workflowStepId}`,children:cI(se.output)}),ce&&t.jsxs(t.Fragment,{children:[t.jsx("button",{type:"button",className:"btn btn-sm workflow-result-mode-toggle",onClick:()=>P(se.workflowStepId),"data-testid":`workflow-result-mode-toggle-${se.workflowStepId}`,title:(m[se.workflowStepId]??"markdown")==="markdown"?"Switch to plain text":"Switch to markdown",children:(m[se.workflowStepId]??"markdown")==="markdown"?"Markdown":"Plain"}),t.jsx("button",{type:"button",className:"btn btn-icon btn-sm workflow-result-expand-toggle",onClick:()=>U(se.workflowStepId),"data-testid":`workflow-result-expand-${se.workflowStepId}`,title:"Expand output",children:t.jsx(Xl,{size:12})})]})]}),ce&&t.jsx("div",{className:`workflow-result-output${(m[se.workflowStepId]??"markdown")==="markdown"?" workflow-result-output--markdown":""}`,"data-testid":`workflow-result-output-${se.workflowStepId}`,children:(m[se.workflowStepId]??"markdown")==="markdown"?t.jsx("div",{className:"markdown-body",children:t.jsx(bi,{remarkPlugins:[xi],components:xp,children:se.output})}):t.jsx("pre",{className:"workflow-result-output-text",children:se.output})})]}):null]},`${se.workflowStepId}-${Ve}`)})]})},A=r?t.jsx("button",{type:"button",className:"modal-edit-btn workflow-results-edit-toggle",onClick:()=>b(N=>!N),"data-testid":"workflow-steps-edit-toggle","aria-label":w?"Done editing workflow steps":"Edit workflow steps",title:w?"Done":"Edit",children:w?t.jsxs(t.Fragment,{children:[t.jsx(hs,{size:14}),"Done"]}):t.jsxs(t.Fragment,{children:[t.jsx(Ds,{size:14}),"Edit"]})}):null,I=!s&&!O&&q,$=r&&O;return t.jsxs("div",{className:"workflow-results-tab","data-task-id":e,children:[I?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:[te.length," step",te.length===1?"":"s"]})]}),A]}),t.jsx("div",{className:"workflow-configured-list","data-testid":"workflow-configured-list",children:te.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:[N.name,Yo(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."}),Z()]}):t.jsxs(t.Fragment,{children:[$&&t.jsxs("div",{className:"workflow-results-edit-header","data-testid":"workflow-results-edit-header",children:[t.jsx("h4",{children:"Workflow Steps"}),A]}),K(),Z()]}),f&&(()=>{const N=n.find(Se=>Se.workflowStepId===f);if(!N)return null;const G=m[N.workflowStepId]??"markdown",xe=N.phase||"pre-merge";return t.jsx("div",{className:"workflow-output-modal-overlay",onClick:Se=>{Se.target===Se.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}),Yo(xe,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:()=>P(N.workflowStepId),"data-testid":"workflow-output-modal-mode-toggle",title:G==="markdown"?"Switch to plain text":"Switch to markdown",children:G==="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(nn,{size:16})})]})]}),t.jsx("div",{className:"workflow-output-modal-body",children:t.jsx("div",{className:`workflow-result-output workflow-result-output--expanded${G==="markdown"?" workflow-result-output--markdown":""}`,"data-testid":"workflow-output-modal-content",children:G==="markdown"?t.jsx("div",{className:"markdown-body",children:t.jsx(bi,{remarkPlugins:[xi],components:xp,children:N.output})}):t.jsx("pre",{className:"workflow-result-output-text",children:N.output})})})]})})})()]})}function mI(e){return e==="block"?"Block execution":e==="fallback-local"?"Fall back to local":"Not configured"}const hI=new Set(["planning","researching","executing","finalizing","merging","merging-fix"]);function pI(e){return e!==void 0&&e!=="online"}function fI({task:e,settings:n,addToast:s,onTaskUpdated:a}){const[r,o]=i.useState([]),[l,c]=i.useState(!1),[d,u]=i.useState(null),[m,h]=i.useState(e.nodeId??""),[f,p]=i.useState(!1),g=i.useRef(e.id);i.useEffect(()=>{g.current=e.id,h(e.nodeId??""),p(!1)},[e.id,e.nodeId]),i.useEffect(()=>{c(!0),u(null),_l().then(E=>{o(E)}).catch(E=>{u(Pe(E)||"Failed to load nodes")}).finally(()=>{c(!1)})},[]);const x=i.useMemo(()=>new Map(r.map(E=>[E.id,E])),[r]),w=i.useMemo(()=>[...r].sort((E,R)=>E.name.localeCompare(R.name)),[r]),b=n,y=e.nodeId??b?.defaultNodeId??null,S=e.nodeId?"Per-task override":b?.defaultNodeId?"Project default":"No routing",k=y?x.get(y):void 0,C=k?`${k.name} (${k.type})`:y?`${y} (node unavailable or unknown)`:"Local (no routing configured)",v=e.column==="in-progress"||hI.has(e.status),j=v||f||l,P=i.useCallback(async E=>{if(E===m)return;const R=e.id,L=m;h(E),p(!0);try{const F=await mi(R,{nodeId:E||null});if(g.current!==R)return;h(F.nodeId??""),a?.(F),s(E?"Node override updated":"Node override cleared","success")}catch(F){if(g.current!==R)return;h(L),s(Pe(F)||"Failed to update node override","error")}finally{g.current===R&&p(!1)}},[s,a,m,e.id]),U=i.useCallback(()=>{P("")},[P]);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:[k?t.jsx(Ca,{status:k.status,compact:!0}):null,C,pI(k?.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:S})]}),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:mI(b?.unavailableNodePolicy)})]})]}),v&&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"}),v?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:m,disabled:j,onChange:E=>{P(E.target.value)},children:[t.jsx("option",{value:"",children:"Use project default"}),w.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: ",x.get(e.nodeId)?.name??e.nodeId]}),t.jsx("button",{type:"button",className:"btn btn-sm",disabled:v||f,onClick:U,children:"Clear override"})]}):null]})]})}const gI=/^[a-zA-Z0-9_-]{1,64}$/,bI=200;function vp(e){return e?new Date(e).toLocaleString():""}function xI(e,n=bI){return e.length<=n?e:e.substring(0,n)+"…"}function vI({taskId:e,addToast:n,onTaskUpdated:s,projectId:a,canEdit:r=!1}){const[o,l]=i.useState([]),[c,d]=i.useState(!0),[u,m]=i.useState(null),[h,f]=i.useState(""),[p,g]=i.useState(null),[x,w]=i.useState(""),[b,y]=i.useState(null),[S,k]=i.useState([]),[C,v]=i.useState(!1),[j,P]=i.useState(!1),[U,E]=i.useState(""),[R,L]=i.useState(""),[F,M]=i.useState(!1),[O,q]=i.useState(null),[te,Z]=i.useState(null),[K,A]=i.useState(!1),I=i.useCallback(async()=>{try{const ee=await lj(e,a);l(ee)}catch(ee){n(Pe(ee)||"Failed to load documents","error")}finally{d(!1)}},[e,a,n]);i.useEffect(()=>{I()},[I]);async function $(ee){u===ee.key?(m(null),f(""),g(null),w(""),y(null),k([]),A(!1)):(m(ee.key),f(ee.content),g(null),w(""),y(null),k([]),A(!1))}async function N(ee){if(b===ee)y(null),k([]);else{y(ee),v(!0);try{const ce=await cj(e,ee,a);k(ce)}catch(ce){n(Pe(ce)||"Failed to load revisions","error")}finally{v(!1)}}}function G(){u&&(g(u),w(h))}function xe(){g(null),w("")}async function Se(){if(!(!p||!x.trim())){M(!0);try{await cm(e,p,x,{},a),g(null),w(""),await I();const ee=o.find(ce=>ce.key===p);ee&&f(ee.content),n("Document saved","success")}catch(ee){n(Pe(ee)||"Failed to save document","error")}finally{M(!1)}}}async function je(){const ee=U.trim(),ce=R.trim();if(!ee){n("Document key is required","error");return}if(!gI.test(ee)){n("Invalid key format. Use 1-64 alphanumeric characters, hyphens, or underscores.","error");return}if(!ce){n("Content is required","error");return}M(!0);try{await cm(e,ee,ce,{},a),P(!1),E(""),L(""),await I(),n("Document created","success")}catch(ne){n(Pe(ne)||"Failed to create document","error")}finally{M(!1)}}async function se(ee){q(ee);try{await dj(e,ee,a),Z(null),q(null),u===ee&&(m(null),f("")),b===ee&&(y(null),k([])),await I(),n("Document deleted","success")}catch(ce){n(Pe(ce)||"Failed to delete document","error")}finally{q(null)}}function Ve(ee){f(ee.content),g(null),w("")}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"}),j&&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:U,onChange:ee=>E(ee.target.value),placeholder:"e.g., plan, notes, research",disabled:F}),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:R,onChange:ee=>L(ee.target.value),rows:6,placeholder:"Enter document content…",disabled:F})]}),t.jsxs("div",{className:"form-actions",children:[t.jsx("button",{className:"btn btn-sm",onClick:()=>{P(!1),E(""),L("")},disabled:F,children:"Cancel"}),t.jsx("button",{className:"btn btn-primary btn-sm",onClick:()=>void je(),disabled:F||!U.trim()||!R.trim(),children:F?"Creating…":"Create"})]})]}),o.length===0&&!j?t.jsx("div",{className:"detail-log-empty",children:"No documents yet."}):t.jsx("div",{className:"task-documents-list",children:o.map(ee=>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(ia,{size:14}),t.jsx("span",{className:"task-document-key",children:ee.key}),t.jsxs("span",{className:"task-document-revision-badge",children:["v",ee.revision]})]}),t.jsxs("div",{className:"task-document-meta",children:[t.jsx("span",{className:"task-document-author",children:ee.author}),t.jsx("span",{className:"task-document-timestamp",children:vp(ee.updatedAt||ee.createdAt)})]})]}),u===ee.key&&p!==ee.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:()=>A(ce=>!ce),"aria-label":K?"Switch to plain text":"Switch to markdown","aria-pressed":K,title:K?"Switch to plain text":"Switch to markdown",children:K?"Markdown":"Plain"})}),t.jsx("div",{className:"task-document-content",children:K?t.jsx("div",{className:"task-document-content-markdown",children:t.jsx("div",{className:"markdown-body",children:t.jsx(bi,{remarkPlugins:[xi],children:h})})}):t.jsx("pre",{className:"task-document-content-text",children:h})}),b===ee.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…"}):S.length<=1?t.jsx("div",{className:"detail-log-empty",children:"No previous revisions."}):t.jsx("div",{className:"task-document-revision-list",children:S.filter(ce=>ce.revision<ee.revision).sort((ce,ne)=>ne.revision-ce.revision).map(ce=>t.jsxs("div",{className:"task-document-revision-item",onClick:()=>Ve(ce),children:[t.jsxs("div",{className:"revision-header",children:[t.jsxs("span",{className:"revision-badge",children:["v",ce.revision]}),t.jsx("span",{className:"revision-author",children:ce.author}),t.jsx("span",{className:"revision-timestamp",children:vp(ce.createdAt)})]}),t.jsx("div",{className:"revision-preview",children:xI(ce.content,100)})]},ce.id))})]})]}),p===ee.key&&t.jsxs("div",{className:"task-document-edit-form",children:[t.jsx("textarea",{value:x,onChange:ce=>w(ce.target.value),rows:10,disabled:F}),t.jsxs("div",{className:"form-actions",children:[t.jsx("button",{className:"btn btn-sm",onClick:xe,disabled:F,children:"Cancel"}),t.jsx("button",{className:"btn btn-primary btn-sm",onClick:()=>void Se(),disabled:F||!x.trim(),children:F?"Saving…":"Save"})]})]}),t.jsxs("div",{className:"task-document-actions",children:[t.jsx("button",{className:"btn btn-sm",onClick:()=>void $(ee),children:u===ee.key?t.jsxs(t.Fragment,{children:[t.jsx(Ei,{size:14})," Collapse"]}):t.jsxs(t.Fragment,{children:[t.jsx(rn,{size:14})," Expand"]})}),u===ee.key&&t.jsxs(t.Fragment,{children:[t.jsxs("button",{className:"btn btn-sm",onClick:()=>void N(ee.key),children:[t.jsx(lo,{size:14})," History"]}),r&&p!==ee.key&&t.jsx("button",{className:"btn btn-sm",onClick:G,children:"Edit"}),r&&(te===ee.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 se(ee.key),disabled:O===ee.key,children:O===ee.key?"…":"Yes"}),t.jsx("button",{className:"btn btn-sm",onClick:()=>Z(null),disabled:O===ee.key,children:"No"})]}):t.jsx("button",{className:"btn btn-danger btn-sm",onClick:()=>Z(ee.key),children:t.jsx(vn,{size:14})}))]})]})]},ee.key))}),r&&!j&&t.jsxs("button",{className:"btn btn-sm task-document-new-btn",onClick:()=>P(!0),children:[t.jsx(gn,{size:14})," New Document"]})]})}function Qo(e){return e.toLocaleString()}function Qc(e){const n=new Date(e);return Number.isNaN(n.getTime())?e:n.toLocaleString()}function zr(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 yI(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=lb(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 wI({tokenUsage:e,loading:n,task:s}){const a=Date.now(),r=rb(s?.log??[]),o=r.filter(g=>typeof g.durationMs=="number"),l=o.reduce((g,x)=>g+(x.durationMs??0),0),c=ob(s?.log)??0,d=typeof s?.timedExecutionMs=="number"?s.timedExecutionMs:Math.max(l,c),u=o.reduce((g,x)=>!g||(x.durationMs??0)>(g.durationMs??0)?x:g,void 0),m=yI(s?.workflowStepResults??[]),f=cb(s?.executionStartedAt,s?.executionCompletedAt,a)??(typeof s?.timedExecutionMs=="number"?s.timedExecutionMs:d+m.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:zr(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:m.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:zr(m.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:zr(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} (${zr(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:m.longestStep?`${m.longestStep.name} (${zr(m.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 ${Qc(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:Qo(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:Qo(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:Qo(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:Qo(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:Qc(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:Qc(e.lastUsedAt)})})]})]})]}):t.jsx("div",{className:"task-token-stats-panel__empty",role:"status",children:"No token usage recorded for this task yet."})]})]})}const Vu=new Set(["planning","researching","executing","finalizing","merging","merging-fix"]);function kI(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 jI(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 Ax(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 NI(e,n,s,a){const r=kI(n);if(r)return r;if(Vu.has(e.status??"")||e.column==="in-progress"){const o=Ax(s);if(o.provider&&o.modelId)return o}return Yg(e,a)}function SI(e,n,s,a){const r=jI(n);if(r)return r;if(Vu.has(e.status??"")||e.column==="in-progress"){const o=Ax(s);if(o.provider&&o.modelId)return o}return Qg(e,a)}function CI(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 EI(e,n,s){if(e.planningModelProvider&&e.planningModelId)return{provider:e.planningModelProvider,modelId:e.planningModelId};const a=CI(n);return a||Xg(e,s)}function _I(e){switch(e){case"done":return"var(--color-success)";case"in-progress":return"var(--todo)";case"skipped":return"var(--text-dim)";case"pending":default:return"var(--border)"}}function MI(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()}function AI(e){return e<1024?`${e} B`:e<1024*1024?`${(e/1024).toFixed(1)} KB`:`${(e/(1024*1024)).toFixed(1)} MB`}function PI(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}function yp(e,n){return e.length>n?e.slice(0,n)+"…":e}function wp(e=[],n=[]){return e.length===n.length&&e.every((s,a)=>s===n[a])}function Xc(e){const n=e.indexOf("/");return!e||n===-1?null:{provider:e.slice(0,n),modelId:e.slice(n+1)}}function Zc(e){return e.trim()}function RI(e){const n=e.trim();return n.length>0?n:void 0}function Li(e){return typeof e=="string"&&oa.includes(e)?e:js}function Oi(e){return e==="fast"?"fast":"standard"}function II(e){const n=e?.issueUrl;return typeof n=="string"&&n.length>0?n:void 0}function TI(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 $I=i.lazy(()=>xn(()=>import("./AgentDetailView-ZbHEbYRT.js"),__vite__mapDeps([0,1,2,3,4,5,6,7])).then(e=>({default:e.AgentDetailView})));function DI(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":return{label:"GitHub Import",contextInfo:II(e.sourceMetadata)};case"research":return{label:"Research",contextInfo:TI(e.sourceMetadata)};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 ed=200,LI=new Set(["triage","todo"]);function Px({task:e,projectId:n,tasks:s=[],onOpenDetail:a,onMoveTask:r,onDeleteTask:o,onMergeTask:l,onRetryTask:c,onResetTask:d,onDuplicateTask:u,onTaskUpdated:m,addToast:h,prAuthAvailable:f,initialTab:p="definition",mobileHeaderMode:g="close",embedded:x=!1,onRequestClose:w}){const[b,y]=i.useState(p),[S,k]=i.useState(()=>"prompt"in e?e:null),[C,v]=i.useState(()=>!("prompt"in e));i.useEffect(()=>{if("prompt"in e){k(e),v(!1);return}let z=!1;return v(!0),k(null),Sa(e.id,n).then(he=>{z||(k(he),v(!1))}).catch(()=>{z||v(!1)}),()=>{z=!0}},[e.id,n]);const j=S?{...S,...e,prompt:S.prompt,log:S.log}:{...e,prompt:""},P=e.status==="failed"||e.status==="stuck-killed"||e.status==="planning"||e.status==="needs-replan"||(e.stuckKillCount??0)>0||(e.recoveryRetryCount??0)>0||!!e.nextRecoveryAt,[U,E]=i.useState(null),[R,L]=i.useState(null),F=DI(j,{sourceAgentName:U?.name});i.useEffect(()=>{y(p)},[p]),i.useEffect(()=>{te(!1)},[e.id]);const[M,O]=i.useState("activity"),[q,te]=i.useState(!1),[Z,K]=i.useState(e.attachments||[]),[A,I]=i.useState(!1),[$,N]=i.useState(e.dependencies||[]),[G,xe]=i.useState(!1),[Se,je]=i.useState(""),[se,Ve]=i.useState(null),[ee,ce]=i.useState([]),[ne,re]=i.useState(!1),[J,B]=i.useState(!1),[ye,Ce]=i.useState(!1),[H,ke]=i.useState(!1),[pe,Ae]=i.useState(!1),[Oe,He]=i.useState(j.prompt||""),[dt,Fe]=i.useState(""),[fe,$e]=i.useState(!1),[De,ot]=i.useState(""),[Be,we]=i.useState(!1),[Q,_e]=i.useState(!1),[lt,ht]=i.useState(e.title||""),[mt,xt]=i.useState(e.description||""),[Ie,Ue]=i.useState(e.dependencies||[]),[pt,oe]=i.useState(e.branch??""),[le,ge]=i.useState(e.baseBranch??""),[Ne,ue]=i.useState(""),[qe,me]=i.useState(""),[tt,Ct]=i.useState(""),[wt,$t]=i.useState(""),[Vt,Mt]=i.useState("default"),[Dt,Qt]=i.useState(void 0),[Kt,Bt]=i.useState(js),[on,fn]=i.useState(e.nodeId),[Jt,an]=i.useState(Oi(e.executionMode)),[zt,en]=i.useState(""),[Zt,dn]=i.useState(e.enabledWorkflowSteps||[]),[ve,ze]=i.useState(e.sourceIssue?.provider??""),[We,Ze]=i.useState(e.sourceIssue?.repository??""),[Ye,It]=i.useState(e.sourceIssue?.externalIssueId??""),[St,Ht]=i.useState(e.sourceIssue?.url??""),[jt,ae]=i.useState([]),[Le,At]=i.useState(!1),[Lt,Ft]=i.useState(Li(e.priority)),[Me,ct]=i.useState(!1),[gt,_t]=i.useState(Oi(e.executionMode)),[Yt,Xt]=i.useState(!1),Te=i.useRef(!1),[Je,Nt]=i.useState(!1),[Ut,tn]=i.useState(!1),[Xn,be]=i.useState(!1),it=i.useRef(null),rt=i.useRef(null),at=i.useRef(null),{getSlotsForId:ut}=Vg(n),ie=ut("task-detail-tab").map((z,he)=>({entry:z,tabId:`plugin-${z.pluginId}-${he}`})),st=typeof b=="string"&&b.startsWith("plugin-")?ie.find(z=>z.tabId===b)??null:null;i.useEffect(()=>(Te.current=!0,()=>{Te.current=!1}),[]);const[Gt,Cn]=i.useState(void 0),[fs,On]=i.useState([]),[jn,zn]=i.useState(!1),[hn,Et]=i.useState(e.enabledWorkflowSteps||[]),En=e.column==="in-progress"||Vu.has(e.status);i.useEffect(()=>{ht(e.title||""),xt(e.description||""),oe(e.branch??""),ge(e.baseBranch??""),ze(e.sourceIssue?.provider??""),Ze(e.sourceIssue?.repository??""),It(e.sourceIssue?.externalIssueId??""),Ht(e.sourceIssue?.url??""),an(Oi(e.executionMode)),be(!1),_e(!1)},[e.id,e.title,e.description,e.branch,e.baseBranch,e.sourceIssue,e.executionMode]),i.useEffect(()=>{Et(e.enabledWorkflowSteps||[])},[e.id,e.enabledWorkflowSteps]),i.useEffect(()=>{Ft(Li(e.priority))},[e.id,e.priority]),i.useEffect(()=>{_t(Oi(e.executionMode))},[e.id,e.executionMode]),i.useEffect(()=>{let z=!1;return Zl(n).then(he=>{z||Cn(he)}).catch(()=>{}),()=>{z=!0}},[n]),i.useEffect(()=>{if(b!=="workflow")return;let z=!1;return zn(!0),JN(e.id,n).then(he=>{z||On(he)}).catch(he=>{z||h(`Failed to load workflow results: ${Pe(he)}`,"error")}).finally(()=>{z||zn(!1)}),()=>{z=!0}},[b,e.id,n,h]),i.useEffect(()=>{if(b!=="workflow")return;const z=n?`?projectId=${encodeURIComponent(n)}`:"",he=Qe=>{try{const ft=JSON.parse(Qe.data);ft.id===e.id&&Array.isArray(ft.workflowStepResults)&&On(ft.workflowStepResults)}catch{}};return ii(`/api/events${z}`,{events:{"task:updated":he}})},[b,e.id,n]),i.useEffect(()=>{G||je("")},[G]),i.useEffect(()=>{if(!e.assignedAgentId){Ve(null);return}const z=ee.find(Qe=>Qe.id===e.assignedAgentId);if(z){Ve(z);return}let he=!1;return Dd(e.assignedAgentId,n).then(Qe=>{he||Ve(Qe)}).catch(()=>{he||Ve(null)}),()=>{he=!0}},[e.assignedAgentId,n,ee]),i.useEffect(()=>{if(!e.sourceAgentId){E(null);return}const z=ee.find(Qe=>Qe.id===e.sourceAgentId);if(z){E(z);return}let he=!1;return Promise.resolve(Dd(e.sourceAgentId,n)).then(Qe=>{he||E(Qe??null)}).catch(()=>{he||E(null)}),()=>{he=!0}},[e.sourceAgentId,n,ee]),i.useEffect(()=>{re(!1)},[e.id]),i.useEffect(()=>{if(!(Je||Ut))return;const he=Qe=>{const ft=Qe.target,qt=it.current?.contains(ft),Xe=at.current?.contains(ft);!qt&&Je&&Nt(!1),!Xe&&Ut&&tn(!1)};return document.addEventListener("mousedown",he),()=>document.removeEventListener("mousedown",he)},[Je,Ut]),i.useEffect(()=>{if(!(Je||Ut))return;const he=Qe=>{Qe.key==="Escape"&&(Qe.stopPropagation(),Je&&Nt(!1),Ut&&tn(!1))};return document.addEventListener("keydown",he),()=>document.removeEventListener("keydown",he)},[Je,Ut]),i.useEffect(()=>{Ae(!1),He(j.prompt||""),Fe("")},[e.id,j.prompt]);const yn=LI.has(e.column)&&!Le,ls=i.useCallback(()=>{if(!yn)return;_e(!0),ht(e.title||""),xt(e.description||""),Ue(e.dependencies||[]),oe(e.branch??""),ge(e.baseBranch??"");const z=e.modelProvider&&e.modelId?`${e.modelProvider}/${e.modelId}`:"",he=e.validatorModelProvider&&e.validatorModelId?`${e.validatorModelProvider}/${e.validatorModelId}`:"",Qe=e.planningModelProvider&&e.planningModelId?`${e.planningModelProvider}/${e.planningModelId}`:"";ue(z),me(he),Ct(Qe),$t(e.thinkingLevel??""),fn(e.nodeId),Mt(z||he||Qe?"custom":"default"),en(""),dn(e.enabledWorkflowSteps||[]),an(Oi(e.executionMode)),ze(e.sourceIssue?.provider??""),Ze(e.sourceIssue?.repository??""),It(e.sourceIssue?.externalIssueId??""),Ht(e.sourceIssue?.url??""),ae([]),Qt(e.reviewLevel),Bt(Li(e.priority))},[yn,e]),cs=i.useCallback(()=>{_e(!1),ht(e.title||""),xt(e.description||""),Ue(e.dependencies||[]),oe(e.branch??""),ge(e.baseBranch??""),fn(e.nodeId),ze(e.sourceIssue?.provider??""),Ze(e.sourceIssue?.repository??""),It(e.sourceIssue?.externalIssueId??""),Ht(e.sourceIssue?.url??""),Bt(Li(e.priority)),an(Oi(e.executionMode)),jt.forEach(z=>URL.revokeObjectURL(z.previewUrl)),ae([])},[e.title,e.description,e.dependencies,e.nodeId,e.priority,e.executionMode,jt]),[Hn,qn]=i.useState("idle"),wn=i.useRef(null),Zn=i.useRef(0),_n=i.useCallback(z=>{const he={},Qe=lt.trim(),ft=mt.trim();Qe&&Qe!==(e.title??"")&&(he.title=Qe),z&&ft&&ft!==(e.description??"")&&(he.description=ft),wp(Ie,e.dependencies??[])||(he.dependencies=Ie),wp(Zt,e.enabledWorkflowSteps??[])||(he.enabledWorkflowSteps=Zt);const qt=pt.trim()||null,Xe=e.branch??null;qt!==Xe&&(he.branch=qt);const nt=le.trim()||null,Ot=e.baseBranch??null;nt!==Ot&&(he.baseBranch=nt);const bn=Xc(Ne),Xs=e.modelProvider&&e.modelId?`${e.modelProvider}/${e.modelId}`:"";Ne!==Xs&&(he.modelProvider=bn?.provider??null,he.modelId=bn?.modelId??null);const ci=Xc(qe),rs=e.validatorModelProvider&&e.validatorModelId?`${e.validatorModelProvider}/${e.validatorModelId}`:"";qe!==rs&&(he.validatorModelProvider=ci?.provider??null,he.validatorModelId=ci?.modelId??null);const Jn=Xc(tt),un=e.planningModelProvider&&e.planningModelId?`${e.planningModelProvider}/${e.planningModelId}`:"";tt!==un&&(he.planningModelProvider=Jn?.provider??null,he.planningModelId=Jn?.modelId??null);const Di=e.thinkingLevel??"";wt!==Di&&(he.thinkingLevel=wt!==""?wt:null),(e.nodeId??void 0)!==on&&(he.nodeId=on??null),Dt!==e.reviewLevel&&(he.reviewLevel=Dt),Kt!==Li(e.priority)&&(he.priority=Kt),Jt!==Oi(e.executionMode)&&(he.executionMode=Jt==="fast"?"fast":null);const Es=Zc(ve),qs=Zc(We),Ji=Zc(Ye),fa=RI(St);if(Es.length===0&&qs.length===0&&Ji.length===0&&!fa)e.sourceIssue&&(he.sourceIssue=null);else{if(!Es||!qs||!Ji)return{updates:null,error:"Source issue provider, repository, and issue identifier are required"};const Nv=Number.parseInt(Ji,10),dc=e.sourceIssue?.issueNumber??Nv;if(!Number.isFinite(dc)||dc<=0)return{updates:null,error:"Source issue identifier must be numeric for new metadata"};const Va={provider:Es,repository:qs,externalIssueId:Ji,issueNumber:dc,...fa?{url:fa}:{}},Wa=e.sourceIssue;(!Wa||Wa.provider!==Va.provider||Wa.repository!==Va.repository||Wa.externalIssueId!==Va.externalIssueId||Wa.issueNumber!==Va.issueNumber||(Wa.url??void 0)!==Va.url)&&(he.sourceIssue=Va)}return{updates:he,error:null}},[le,pt,Ie,mt,Jt,Ne,on,tt,Kt,Dt,Zt,Ye,ve,We,St,wt,lt,qe,e]),is=i.useCallback(async z=>{const{updates:he,error:Qe}=_n(z);if(!he)return qn("error"),Qe&&h(`Failed to update ${e.id}: ${Qe}`,"error"),!1;if(Object.keys(he).length===0)return!0;const ft=++Zn.current;At(!0),qn("saving");try{const qt=await mi(e.id,he,n);return ft!==Zn.current?void 0:(m?.(qt),qn("saved"),!0)}catch(qt){return ft===Zn.current&&(qn("error"),h(`Failed to update ${e.id}: ${Pe(qt)}`,"error")),!1}finally{Te.current&&ft===Zn.current&&At(!1)}},[h,_n,m,n,e.id]),Ns=i.useCallback(async z=>{await is(!0)},[is]),es=i.useCallback(async()=>{await is(!0)&&(h(`Updated ${e.id}`,"success"),Te.current&&_e(!1))},[h,is,e.id]);i.useEffect(()=>{if(Q)return wn.current&&clearTimeout(wn.current),wn.current=setTimeout(()=>{is(!1)},700),()=>{wn.current&&(clearTimeout(wn.current),wn.current=null)}},[Q,lt,Ie,pt,le,Ne,qe,tt,wt,on,Dt,Kt,Jt,Zt,ve,We,Ye,St,is]);const ks=i.useCallback(async z=>{const he=Li(z),Qe=Li(e.priority);if(he===Qe){Ft(Qe);return}const ft=Lt;Ft(he),ct(!0);try{const qt=await mi(e.id,{priority:he},n);Ft(Li(qt.priority)),m?.(qt),h(`Priority updated to ${Li(qt.priority)}`,"success")}catch(qt){Ft(ft),h(`Failed to update ${e.id}: ${Pe(qt)}`,"error")}finally{Te.current&&ct(!1)}},[e.id,e.priority,n,Lt,m,h]),Is=i.useCallback(async()=>{const he=Oi(e.executionMode)==="fast"?"standard":"fast",Qe=gt;_t(he),Xt(!0);try{const ft=await mi(e.id,{executionMode:he==="fast"?"fast":null},n),qt=Oi(ft.executionMode);_t(qt),m?.(ft),h(`Execution mode updated to ${qt}`,"success")}catch(ft){_t(Qe),h(`Failed to update ${e.id}: ${Pe(ft)}`,"error")}finally{Te.current&&Xt(!1)}},[e.id,e.executionMode,n,gt,m,h]),Ss=i.useCallback(z=>{Q&&(z.key==="Escape"?(z.preventDefault(),cs()):z.key==="Enter"&&(z.ctrlKey||z.metaKey)&&(z.preventDefault(),es()))},[Q,cs,es]);i.useEffect(()=>{if(Q)return document.addEventListener("keydown",Ss),()=>document.removeEventListener("keydown",Ss)},[Q,Ss]);const X=i.useRef(null),{nodes:_}=nc(),{confirm:de}=ai(),{entries:D,loading:Y,loadMore:Ee,hasMore:Ge,total:kt,loadingMore:Tt}=Nx(e.id,b==="logs"&&M==="agent-log",n),Pt=i.useCallback(()=>{w?.()},[w]);i.useEffect(()=>{if(x)return;const z=he=>{he.key==="Escape"&&!Q&&Pt()};return document.addEventListener("keydown",z),()=>document.removeEventListener("keydown",z)},[x,Pt,Q]);const ln=i.useCallback(async z=>{try{const he=e.steps.some(qt=>qt.status!=="pending"),Qe=(z==="todo"||z==="triage")&&he;let ft;if(Qe){if(await de({title:"Preserve Progress?",message:"This task has completed steps. Keep progress before moving?",confirmLabel:"Keep Progress",cancelLabel:"Reset Progress"}))ft={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 r(e.id,z,ft),Pt(),h(`Moved to ${ns[z]}`,"success")}catch(he){h(Pe(he),"error")}},[e.id,e.steps,r,Pt,h,de]),ts=i.useCallback(async()=>{if(await de({title:"Delete Task",message:`Delete ${e.id}?`,danger:!0}))try{await o(e.id),Pt(),h(`Deleted ${e.id}`,"info")}catch(he){const Qe=PI(he);if(!Qe||Qe.dependentIds.length===0){h(Pe(he),"error");return}const ft=Qe.dependentIds.join(", ");if(!await de({title:"Force Delete Task",message:`${e.id} is a dependency of ${ft}.
685
-
686
- Delete anyway by removing these dependency references first?`,danger:!0}))return;try{await o(e.id,{removeDependencyReferences:!0}),Pt(),h(`Deleted ${e.id} after removing dependency references`,"info")}catch(Xe){h(Pe(Xe),"error")}}},[e.id,o,Pt,h,de]),Rn=i.useCallback(async()=>{await de({title:"Merge Task",message:`Merge ${e.id} into the current branch?`})&&(Pt(),h(`Merging ${e.id}...`,"info"),l(e.id).then(he=>{const Qe=he.merged?`Merged ${e.id} (branch: ${he.branch})`:`Closed ${e.id} (${he.error||"no branch to merge"})`;h(Qe,"success")}).catch(he=>{h(Pe(he),"error")}))},[e.id,l,Pt,h,de]),Fn=i.useCallback(()=>{c&&(Pt(),c(e.id).then(()=>{h(`Retried ${e.id}`,"success")}).catch(z=>{h(Pe(z),"error")}))},[e.id,c,Pt,h]),Un=i.useCallback(()=>{d&&window.confirm(`This will erase all progress for ${e.id} and start the task from scratch. Continue?`)&&(Pt(),d(e.id).then(()=>{h(`Reset ${e.id} — fresh run will be allocated`,"success")}).catch(z=>{h(Pe(z),"error")}))},[e.id,d,Pt,h]),gs=i.useCallback(async()=>{if(!(!u||!await de({title:"Duplicate Task",message:`Duplicate ${e.id}? This will create a new task in Triage with the same description and prompt.`})))try{const he=await u(e.id);Pt(),h(`Duplicated ${e.id} → ${he.id}`,"success")}catch(he){h(Pe(he),"error")}},[e.id,u,Pt,h,de]),Ln=i.useCallback(async()=>{try{e.paused?(await Qk(e.id,n),h(`Unpaused ${e.id}`,"success")):(await Ag(e.id,n),h(`Paused ${e.id}`,"success")),Pt()}catch(z){h(Pe(z),"error")}},[e.id,e.paused,Pt,h]),Vn=i.useCallback(async()=>{try{await tj(e.id,n),h(`Plan approved — ${e.id} moved to Todo`,"success"),Pt()}catch(z){h(Pe(z),"error")}},[e.id,Pt,h]),Wn=i.useCallback(async()=>{if(await de({title:"Reject Plan",message:"Reject this plan? The specification will be discarded and regenerated.",danger:!0}))try{await nj(e.id,n),h(`Plan rejected — ${e.id} returned to Planning for replanning`,"info"),Pt()}catch(he){h(Pe(he),"error")}},[e.id,Pt,h,de]),Kn=i.useCallback(async()=>{if(await de({title:"Rebuild Plan",message:"Rebuild the plan for this task? The task will move to planning for replanning."}))try{await hj(e.id,n),Pt(),h(`Replanning ${e.id}...`,"info")}catch(he){h(Pe(he),"error")}},[e.id,n,Pt,h,de]),Bn=i.useCallback(()=>{$e(!0),ot("")},[]),Nn=i.useCallback(()=>{Nt(!1),tn(!1)},[]),Gn=i.useCallback(z=>{Nn(),ln(z)},[Nn]),ds=i.useCallback(z=>{Nn(),z()},[Nn]),Ts=i.useCallback(()=>{Nn(),Rn()},[Nn,Rn]),Ri=i.useCallback(()=>{$e(!1),ot(""),we(!1)},[]),ca=i.useCallback(async()=>{if(!De.trim()){h("Please enter feedback describing what needs refinement","error");return}if(De.length>2e3){h("Feedback must be 2000 characters or less","error");return}we(!0);try{const z=await pj(e.id,De.trim(),n);h(`Refinement task created: ${z.id}`,"success"),Pt()}catch(z){h(Pe(z),"error")}finally{we(!1)}},[e.id,De,h,Pt]),ri=i.useCallback(async z=>{I(!0);try{const he=await ec(e.id,z,n);K(Qe=>[...Qe,he]),h("Screenshot attached","success")}catch(he){h(Pe(he),"error")}finally{I(!1)}},[e.id,h]),Ta=i.useCallback(async z=>{const he=z.target.files?.[0];he&&(await ri(he),X.current&&(X.current.value=""))},[ri]);i.useEffect(()=>{const z=he=>{const Qe=he.clipboardData?.items;if(Qe)for(let ft=0;ft<Qe.length;ft++){const qt=Qe[ft];if(qt.type.startsWith("image/")){const Xe=qt.getAsFile();if(Xe){he.preventDefault(),ri(Xe);return}}}};return document.addEventListener("paste",z),()=>document.removeEventListener("paste",z)},[ri]);const $a=i.useCallback(z=>{z.preventDefault()},[]),Qs=i.useCallback(z=>{z.preventDefault();const he=z.dataTransfer.files;for(let Qe=0;Qe<he.length;Qe++){const ft=he[Qe];if(ft.type.startsWith("image/")){ri(ft);return}}},[ri]),oi=i.useCallback(async z=>{try{await aj(e.id,z,n),K(he=>he.filter(Qe=>Qe.filename!==z)),h("Attachment deleted","info")}catch(he){h(Pe(he),"error")}},[e.id,h]),Ii=i.useCallback(async z=>{const he=hn;Et(z);try{const Qe=await mi(e.id,{enabledWorkflowSteps:z},n);h("Workflow steps updated","success"),m?.(Qe)}catch(Qe){Et(he),h(`Failed to update workflow steps: ${Pe(Qe)}`,"error")}},[e.id,n,hn,m,h]),da=i.useCallback(async()=>{B(!0);try{const z=await Nr(void 0,n);ce(z),re(!0)}catch(z){h(`Failed to load agents: ${Pe(z)}`,"error"),re(!1)}finally{B(!1)}},[n,h]),Da=i.useCallback(async z=>{try{const he=await wm(e.id,z,n),Qe=ee.find(ft=>ft.id===z)??null;Ve(Qe||(ft=>ft?.id===z?ft:null)),re(!1),m?.(he),h("Assigned agent updated","success")}catch(he){h(`Failed to assign agent: ${Pe(he)}`,"error")}},[e.id,n,ee,m,h]),La=i.useCallback(async()=>{try{const z=await wm(e.id,null,n);Ve(null),re(!1),m?.(z),h("Agent unassigned","success")}catch(z){h(`Failed to unassign agent: ${Pe(z)}`,"error")}},[e.id,n,m,h]),ua=i.useCallback(async z=>{const he=[...$,z];N(he);try{await mi(e.id,{dependencies:he},n)}catch(Qe){N($),h(Pe(Qe),"error")}},[e.id,$,h]),ma=i.useCallback(async(z,he)=>{z.stopPropagation();const Qe=$.filter(ft=>ft!==he);N(Qe);try{await mi(e.id,{dependencies:Qe},n)}catch(ft){N($),h(Pe(ft),"error")}},[e.id,$,h]),Ti=i.useCallback(async z=>{try{const he=await Sa(z,n);a(he)}catch{h(`Failed to load dependency ${z}`,"error")}},[a,h]),Oa=i.useCallback(async z=>{Ce(!0);try{await mi(j.id,{prompt:z},n),h("Spec updated","success"),S&&(S.prompt=z)}catch(he){throw h(Pe(he),"error"),he}finally{Ce(!1)}},[j,S,h]),ha=i.useCallback(async z=>{ke(!0);try{await mj(e.id,z,n),h("AI revision requested. Task moved to planning.","success"),Pt()}catch(he){const Qe=Pe(he);Qe.includes("done")||Qe.includes("archived")?h("Cannot request revision: Task must be in 'triage', 'todo', 'in-progress', or 'in-review' column.","error"):h(Qe,"error")}finally{ke(!1)}},[e.id,h,Pt]),Mr=i.useCallback(()=>{Ae(!0),He(j.prompt||""),Fe("")},[j.prompt]),li=i.useCallback(()=>{Ae(!1),He(j.prompt||""),Fe("")},[j.prompt]),Hs=i.useCallback(async()=>{if(Oe===(j.prompt||"")){li();return}Ae(!1);try{await Oa(Oe)}catch(z){throw Ae(!0),z}},[Oe,j.prompt,Oa,li]),za=i.useCallback(async()=>{dt.trim()&&await ha(dt.trim())},[dt,ha]),Fa=i.useCallback(z=>{z.key==="Escape"?(z.preventDefault(),li()):z.key==="Enter"&&(z.ctrlKey||z.metaKey)&&(z.preventDefault(),Hs())},[li,Hs]),$i=s.filter(z=>z.id!==e.id&&!$.includes(z.id)).sort((z,he)=>{const Qe=he.createdAt.localeCompare(z.createdAt);if(Qe!==0)return Qe;const ft=parseInt(z.id.slice(z.id.lastIndexOf("-")+1),10)||0;return(parseInt(he.id.slice(he.id.lastIndexOf("-")+1),10)||0)-ft}),Ua=se?.name??e.assignedAgentId??null,Ba=i.useMemo(()=>{const z=[];return j.modelProvider&&z.push(j.modelProvider),j.validatorModelProvider&&!z.includes(j.validatorModelProvider)&&z.push(j.validatorModelProvider),j.planningModelProvider&&!z.includes(j.planningModelProvider)&&z.push(j.planningModelProvider),z},[j.modelProvider,j.validatorModelProvider,j.planningModelProvider]),Ha=Ld[e.column]||[],yi=["todo","in-progress"],pa=e.column==="in-review"?yi:Ha,us=pa[0],Ki=pa.slice(1),Cs=Ki.length>0,Gi=i.useCallback(()=>{Nt(!1),rt.current?.focus()},[]),qa=i.useCallback(z=>{if(!Cs){us&&Gn(us);return}const he=z.currentTarget.querySelector(".detail-move-btn__arrow");if(!!(z.target instanceof Element&&z.target.closest(".detail-move-btn__arrow")||he&&z.clientX>0&&z.clientX>=he.getBoundingClientRect().left)){Nt(ft=>!ft),tn(!1);return}us&&Gn(us)},[Cs,us,Gn]),Ke=i.useCallback(z=>{!Cs||!(z.key==="ArrowDown"||z.altKey&&z.key==="ArrowDown")||(z.preventDefault(),Nt(!0),tn(!1))},[Cs]),Rt=i.useCallback(z=>{z.key==="Escape"&&(z.preventDefault(),z.stopPropagation(),Gi())},[Gi]);i.useEffect(()=>{if(!Je)return;it.current?.querySelector(".detail-move-menu-item")?.focus()},[Je]);const cn={"creating-pr":"Creating PR…","awaiting-pr-checks":"Awaiting PR checks","merging-pr":"Merging PR…","merging-fix":"Merging fixes…"},as=e.status?cn[e.status]:void 0,In=Gt?.mergeStrategy??"direct",$s=Gt?.autoMerge??!1,V=In==="pull-request"&&!$s;let Re="Merge & Close";return V&&!as&&(e.prInfo?e.prInfo.status==="open"?Re="Check PR Status":e.prInfo.status==="merged"&&(Re="Finish & Close"):Re="Start PR Review"),t.jsxs("div",{className:x?"task-detail-content task-detail-content--embedded":"task-detail-content",onDragOver:$a,onDrop:Qs,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:ns[e.column]})]}),t.jsxs("div",{className:"modal-header-actions",children:[!Q&&yn&&t.jsx("button",{className:"modal-edit-btn",onClick:ls,title:"Edit task","aria-label":"Edit task",children:t.jsx(Ds,{size:14})}),!x&&g==="back"&&t.jsxs("button",{className:"modal-close task-detail-mobile-back",onClick:Pt,"aria-label":"Back to task list",type:"button",children:[t.jsx(Aa,{"aria-hidden":"true"}),t.jsx("span",{children:"Back"})]}),!x&&g!=="back"&&t.jsx("button",{className:"modal-close",onClick:Pt,"aria-label":"Close",type:"button",children:"×"})]})]}),t.jsxs("div",{className:`detail-body${b==="logs"&&M==="agent-log"&&!Q?" detail-body--agent-log":""}`,children:[Q?t.jsx("div",{className:"modal-edit-form",children:t.jsx(Mx,{mode:"edit",title:lt,onTitleChange:ht,description:mt,onDescriptionChange:xt,dependencies:Ie,onDependenciesChange:Ue,branch:pt,onBranchChange:oe,baseBranch:le,onBaseBranchChange:ge,executorModel:Ne,onExecutorModelChange:ue,validatorModel:qe,onValidatorModelChange:me,planningModel:tt,onPlanningModelChange:Ct,thinkingLevel:wt,onThinkingLevelChange:$t,presetMode:Vt,onPresetModeChange:Mt,selectedPresetId:zt,onSelectedPresetIdChange:en,selectedWorkflowSteps:Zt,onWorkflowStepsChange:dn,pendingImages:jt,onImagesChange:ae,tasks:s.filter(z=>z.id!==e.id),projectId:n,disabled:Le,addToast:h,isActive:Q,onAutoSaveDescription:Ns,reviewLevel:Dt,onReviewLevelChange:Qt,priority:Kt,onPriorityChange:Bt,nodeId:on,onNodeIdChange:fn,nodeOptions:_,nodeOverrideDisabled:En,nodeOverrideDisabledReason:En?"Execution node override is locked while a task is active/in progress.":void 0,executionMode:Jt,onExecutionModeChange:an,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:ve,onChange:z=>ze(z.target.value),disabled:Le,"data-testid":"task-source-provider-input"}),t.jsx("input",{type:"text",className:"modal-edit-input",placeholder:"Repository (e.g. owner/repo)",value:We,onChange:z=>Ze(z.target.value),disabled:Le,"data-testid":"task-source-repository-input"}),t.jsx("input",{type:"text",className:"modal-edit-input",placeholder:"Issue identifier",value:Ye,onChange:z=>It(z.target.value),disabled:Le,"data-testid":"task-source-external-id-input"}),t.jsx("input",{type:"url",className:"modal-edit-input",placeholder:"Issue URL",value:St,onChange:z=>Ht(z.target.value),disabled:Le,"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 z=e.title||e.description||e.id,he=!q&&z.length>ed;return t.jsxs(t.Fragment,{children:[t.jsx("h2",{className:"detail-title",children:he?z.slice(0,ed)+"…":z}),z.length>ed&&t.jsx("button",{className:"detail-description-toggle",onClick:()=>te(!q),children:q?"Show less":"Show more"})]})})(),t.jsxs("div",{className:"detail-meta",children:[t.jsxs("label",{className:`card-priority-badge card-priority-badge--${Lt} detail-priority-chip ${Me?"detail-priority-chip--saving":""}`,children:[t.jsx("span",{children:"Priority:"}),t.jsx("select",{className:"detail-priority-select",value:Lt,onChange:z=>{ks(z.target.value)},disabled:Me,"aria-label":"Task priority",children:oa.map(z=>t.jsx("option",{value:z,children:z},z))})]}),t.jsxs("button",{type:"button",className:`btn btn-sm detail-execution-mode-toggle ${gt==="fast"?"detail-execution-mode-toggle--fast":""} ${Yt?"detail-execution-mode-toggle--saving":""}`,onClick:()=>{Is()},disabled:Yt,"aria-label":`Execution mode: ${gt}`,"aria-pressed":gt==="fast",children:[t.jsx(Qn,{"aria-hidden":"true"}),t.jsx("span",{children:gt==="fast"?"Fast":"Standard"})]}),F&&t.jsxs("div",{className:"detail-provenance",children:[t.jsx(Us,{"aria-hidden":"true"}),t.jsxs("span",{children:[j.sourceType==="agent_heartbeat"?t.jsxs(t.Fragment,{children:["Created by"," ",F.sourceAgentId?t.jsx("button",{type:"button",className:"detail-provenance-link",onClick:()=>L(F.sourceAgentId),children:F.label}):F.label]}):t.jsxs(t.Fragment,{children:["Created via ",F.label]}),F.parentTaskId&&t.jsxs(t.Fragment,{children:[" ","of"," ",t.jsx("button",{type:"button",className:"detail-provenance-link",onClick:()=>Ti(F.parentTaskId),children:F.parentTaskId})]}),F.contextInfo?` (${F.contextInfo})`:""]})]}),(e.prInfo?.number||e.mergeDetails?.prNumber)&&t.jsxs("div",{className:"detail-provenance detail-pr-link-row",children:[t.jsx(Us,{"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",children:["Created ",new Date(e.createdAt).toLocaleDateString()," · Updated"," ",new Date(e.updatedAt).toLocaleDateString()]})]})]}),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})]})]}),!Q&&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"}),ie.map(({entry:z,tabId:he})=>t.jsx("button",{className:`detail-tab${b===he?" detail-tab-active":""}`,onClick:()=>y(he),children:z.slot.label},`plugin-tab-${z.pluginId}-${he}`))]}),b==="workflow"?t.jsx("div",{className:"detail-section",children:t.jsx(uI,{taskId:e.id,results:fs,loading:jn,enabledWorkflowSteps:hn,canEdit:yn,projectId:n,isTaskInProgress:e.column==="in-progress"&&e.status!=="paused",onWorkflowStepsChange:Ii})}):b==="model"?t.jsx("div",{className:"detail-section",children:t.jsx(BR,{task:e,addToast:h,onTaskUpdated:m,settings:Gt})}):b==="logs"?t.jsxs("div",{className:`detail-section${M==="agent-log"?" detail-section--agent-log":""}`,children:[t.jsxs("div",{className:"log-subview-toggle",children:[t.jsx("button",{className:`log-subview-btn${M==="activity"?" log-subview-btn-active":""}`,onClick:()=>O("activity"),children:"Activity"}),t.jsx("button",{className:`log-subview-btn${M==="agent-log"?" log-subview-btn-active":""}`,onClick:()=>O("agent-log"),children:"Agent Log"})]}),M==="agent-log"?t.jsx(LR,{entries:D,loading:Y,executorModel:NI(e,D,se,Gt),validatorModel:SI(e,D,se,Gt),planningModel:EI(e,D,Gt),hasMore:Ge,onLoadMore:Ee,loadingMore:Tt,totalCount:kt}):t.jsxs("div",{className:"detail-activity",children:[t.jsx("h4",{children:"Activity"}),j.activityLogTruncatedCount?t.jsxs("div",{className:"detail-log-truncated",children:["Showing the most recent ",j.log.length," activity entries."]}):null,j.log&&j.log.length>0?t.jsx("div",{className:"detail-activity-list",children:[...j.log].reverse().map((z,he)=>t.jsxs("div",{className:"detail-log-entry",children:[t.jsxs("div",{className:"detail-log-header",children:[t.jsx("span",{className:"detail-log-timestamp",children:MI(z.timestamp)}),t.jsx("span",{className:"detail-log-action",children:z.action})]}),z.outcome&&t.jsx("div",{className:"detail-log-outcome",children:z.outcome})]},he))}):t.jsx("div",{className:"detail-log-empty",children:"(no activity)"})]})]}):b==="changes"?t.jsx(nI,{taskId:e.id,worktree:e.worktree,projectId:n,column:e.column,mergeDetails:e.mergeDetails,modifiedFiles:e.modifiedFiles}):b==="review"?t.jsx(QR,{task:e,addToast:h,projectId:n,onTaskUpdated:m}):b==="comments"?t.jsx(KR,{task:e,addToast:h,projectId:n,onTaskUpdated:m}):b==="documents"?t.jsx(vI,{taskId:e.id,addToast:h,projectId:n,onTaskUpdated:m,canEdit:yn}):st?t.jsx("div",{className:"detail-section",children:t.jsx(ta,{slotId:"task-detail-tab",projectId:n,pluginIds:[st.entry.pluginId]})}):b==="stats"?t.jsx("div",{className:"detail-section",children:t.jsx(wI,{tokenUsage:j.tokenUsage,loading:C,task:j})}):b==="routing"?t.jsx("div",{className:"detail-section",children:t.jsx(fI,{task:e,settings:Gt,addToast:h,onTaskUpdated:m})}):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(bi,{remarkPlugins:[xi],children:e.summary})})]}),t.jsx(ZR,{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(Us,{"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":Xn,"aria-label":Xn?"Collapse source issue details":"Expand source issue details",onClick:()=>be(z=>!z),children:t.jsx(Mn,{size:16,className:Xn?"detail-source-chevron--expanded":void 0})})]}),Xn&&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)"})})]})]})]}),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:[Ba.length>0&&t.jsx("span",{className:"detail-provider-icons","data-testid":"detail-provider-icons",children:Ba.map(z=>t.jsx(Sn,{provider:z,size:"sm"},z))}),t.jsxs("span",{className:"detail-meta-label",children:[t.jsx($n,{size:14,className:"detail-meta-label-icon"}),"Agent"]})]}),t.jsxs("div",{className:"detail-agent-actions",children:[Ua?t.jsxs("span",{className:"detail-agent-chip",children:[t.jsx($n,{size:14}),Ua,t.jsx("button",{className:"detail-agent-clear",onClick:()=>void La(),title:"Unassign agent",children:t.jsx(nn,{size:12})})]}):t.jsx("button",{className:"btn btn-sm",onClick:()=>{ne?re(!1):da()},children:"Assign Agent"}),ne&&t.jsxs("div",{className:"agent-picker-dropdown",children:[J&&t.jsx("div",{className:"agent-picker-loading",children:"Loading agents..."}),!J&&ee.map(z=>t.jsxs("button",{className:`agent-picker-item${e.assignedAgentId===z.id?" selected":""}`,onClick:()=>void Da(z.id),children:[t.jsx($n,{size:14}),t.jsx("span",{className:"agent-picker-name",children:z.name}),t.jsx("span",{className:"agent-picker-role",children:z.role})]},z.id)),!J&&ee.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"}),j.steps&&j.steps.length>0?t.jsxs("div",{className:"step-progress-wrapper",children:[t.jsx("div",{className:"step-progress-bar",children:j.steps.map((z,he)=>t.jsx("div",{className:`step-progress-segment step-progress-segment--${z.status}`,"data-tooltip":`${z.name} (${z.status})`,style:{backgroundColor:_I(z.status)}},he))}),t.jsxs("span",{className:"step-progress-label",children:[j.steps.filter(z=>z.status==="done").length,"/",j.steps.length," step",j.steps.length===1?"":"s"]})]}):t.jsx("div",{className:"step-progress-empty",children:"(no steps defined)"})]}),t.jsxs("div",{className:"detail-section",children:[!pe&&t.jsx("div",{className:"detail-spec-edit-trigger",children:t.jsx("button",{className:"btn btn-sm",onClick:Mr,children:"Edit"})}),pe?t.jsxs("div",{className:"spec-editor-edit-mode",children:[t.jsx("textarea",{className:"spec-editor-textarea",value:Oe,onChange:z=>He(z.target.value),onKeyDown:Fa,disabled:ye,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:li,disabled:ye,children:"Cancel"}),t.jsx("button",{className:"btn btn-primary btn-sm",onClick:()=>void Hs(),disabled:Oe===(j.prompt||"")||ye,children:ye?"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:dt,onChange:z=>Fe(z.target.value),placeholder:"e.g., 'Add more details about error handling', 'Split this into smaller steps', 'Include tests for the API endpoints'...",disabled:H,rows:4,maxLength:2e3}),t.jsxs("div",{className:"spec-editor-revision-actions",children:[t.jsxs("span",{className:"spec-editor-char-count",children:[dt.length,"/2000"]}),t.jsx("button",{className:"btn btn-primary btn-sm",onClick:()=>void za(),disabled:!dt.trim()||H,children:H?"Requesting…":"Request AI Revision"})]})]})]}):C?t.jsx("div",{className:"spec-loading",children:"Loading specification…"}):j.prompt?t.jsx("div",{className:"markdown-body",children:t.jsx(bi,{remarkPlugins:[xi],children:j.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"}),Z.length>0?t.jsx("div",{className:"detail-attachments-grid",children:Z.map(z=>{const he=Mi(`/api/tasks/${e.id}/attachments/${z.filename}`);return t.jsxs("div",{className:"detail-attachment-card",children:[t.jsx("a",{className:"detail-attachment-link",href:he,target:"_blank",rel:"noopener noreferrer",children:t.jsx("img",{src:he,alt:z.originalName,className:"detail-attachment-image"})}),t.jsxs("div",{className:"detail-attachment-meta",children:[z.originalName," (",AI(z.size),")"]}),t.jsx("button",{className:"detail-attachment-delete",onClick:()=>oi(z.filename),title:"Delete attachment",children:"×"})]},z.filename)})}):t.jsx("div",{className:"detail-empty-inline",children:"(no attachments)"}),t.jsx("input",{className:"detail-hidden-file-input",ref:X,type:"file",accept:"image/*",onChange:Ta}),t.jsx("button",{className:"btn btn-sm",onClick:()=>X.current?.click(),disabled:A,children:A?"Uploading…":"Attach Screenshot"})]}),t.jsxs("div",{className:"detail-deps",children:[t.jsx("h4",{children:"Dependencies"}),$.length>0?t.jsx("ul",{className:"detail-dep-list",children:$.map(z=>{const he=s.find(ft=>ft.id===z),Qe=he?.title||he?.description||z;return t.jsxs("li",{className:"detail-dep-item",children:[t.jsxs("span",{className:"detail-dep-link",onClick:()=>Ti(z),onKeyDown:ft=>{(ft.key==="Enter"||ft.key===" ")&&(ft.preventDefault(),Ti(z))},role:"link",tabIndex:0,title:`Click to view ${z}`,children:[t.jsx("span",{className:"detail-dep-id",children:z}),t.jsx("span",{className:"detail-dep-label",children:yp(Qe,40)})]}),t.jsx("button",{className:"dep-remove-btn",onClick:ft=>ma(ft,z),title:`Remove dependency ${z}`,children:"×"})]},z)})}):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:()=>{G&&je(""),xe(z=>!z)},children:"Add Dependency"}),G&&(()=>{const z=Se.toLowerCase(),he=z?$i.filter(Qe=>Qe.id.toLowerCase().includes(z)||Qe.title&&Qe.title.toLowerCase().includes(z)||Qe.description&&Qe.description.toLowerCase().includes(z)):$i;return t.jsxs("div",{className:"dep-dropdown",children:[t.jsx("input",{className:"dep-dropdown-search",placeholder:"Search tasks…",autoFocus:!0,value:Se,onChange:Qe=>je(Qe.target.value),onClick:Qe=>Qe.stopPropagation()}),he.length===0?t.jsx("div",{className:"dep-dropdown-empty",children:"No available tasks"}):he.map(Qe=>t.jsxs("div",{className:"dep-dropdown-item",onClick:()=>{ua(Qe.id),xe(!1)},children:[t.jsx("span",{className:"dep-dropdown-id",children:Qe.id}),t.jsx("span",{className:"dep-dropdown-title",children:yp(Qe.title||Qe.description||Qe.id,30)})]},Qe.id))]})})()]})]}),e.column==="in-review"&&t.jsx("div",{className:"detail-section detail-pr-section",children:t.jsx(qR,{taskId:e.id,projectId:n,prInfo:e.prInfo,automationStatus:e.status??null,autoMerge:Gt?.autoMerge??!1,isManualPrFlow:V,prAuthAvailable:f??!1,onPrCreated:z=>{e.prInfo=z},onPrUpdated:z=>{e.prInfo=z},addToast:h})})]})]})]}),t.jsx("div",{className:"modal-actions",children:Q?t.jsxs(t.Fragment,{children:[t.jsx("span",{className:"modal-edit-hint",children:Hn==="saving"?"Autosaving…":Hn==="saved"?"Saved":Hn==="error"?"Save failed":"Changes autosave as you edit"}),t.jsx("div",{className:"modal-actions-spacer"}),t.jsx("button",{className:"btn btn-sm",onClick:cs,disabled:Le,children:"Cancel"}),t.jsx("button",{className:"btn btn-primary btn-sm",onClick:()=>void es(),disabled:Le,children:Le?"Saving…":"Save"})]}):t.jsxs(t.Fragment,{children:[e.column==="triage"&&e.status==="awaiting-approval"&&j.prompt&&t.jsxs(t.Fragment,{children:[t.jsx("button",{className:"btn btn-primary btn-sm",onClick:Vn,children:"Approve Plan"}),t.jsx("button",{className:"btn btn-danger btn-sm",onClick:Wn,children:"Reject Plan"})]}),e.column==="triage"&&e.status!=="awaiting-approval"&&!P&&t.jsx("button",{className:"btn btn-sm btn-danger",onClick:ts,"aria-label":"Delete task",title:"Delete task",children:"Delete"}),(e.column!=="triage"||e.status==="awaiting-approval"||P||e.paused)&&t.jsxs("div",{className:"detail-actions-dropdown",ref:at,children:[t.jsxs("button",{className:"btn btn-sm",onClick:()=>{tn(z=>!z),Nt(!1)},"aria-haspopup":"menu","aria-expanded":Ut,children:["Actions",t.jsx(rn,{size:12})]}),Ut&&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:()=>ds(ts),children:"Delete"}),u&&t.jsx("button",{className:"detail-actions-menu-item",role:"menuitem",onClick:()=>ds(gs),children:"Duplicate"}),(e.column==="done"||e.column==="in-review")&&t.jsx("button",{className:"detail-actions-menu-item",role:"menuitem",onClick:()=>ds(Bn),children:"Refine"}),t.jsx("button",{className:"detail-actions-menu-item",role:"menuitem",onClick:()=>ds(Kn),children:"Respecify"}),P&&c&&t.jsx("button",{className:"detail-actions-menu-item",role:"menuitem",onClick:()=>ds(Fn),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:()=>ds(Un),children:"Reset"}),e.column!=="done"&&!e.assignedAgentId&&t.jsx("button",{className:"detail-actions-menu-item",role:"menuitem",onClick:()=>ds(Ln),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:it,children:e.column==="in-review"?t.jsxs("div",{className:"detail-move-actions-in-review",children:[t.jsxs("div",{children:[t.jsxs("button",{ref:rt,className:"btn btn-primary btn-sm detail-move-btn",onClick:qa,onKeyDown:Ke,disabled:!us,"aria-label":us?`Move to ${ns[us]}`:void 0,"aria-haspopup":Cs?"menu":void 0,"aria-expanded":Cs?Je:void 0,children:[t.jsxs("span",{className:"detail-move-btn__label",children:["Move to ",us?ns[us]:""]}),Cs&&t.jsx("span",{className:"detail-move-btn__arrow","aria-hidden":"true",children:t.jsx(rn,{size:12})})]}),Je&&Cs&&t.jsx("div",{className:"detail-move-menu",role:"menu",onKeyDown:Rt,children:Ki.map(z=>t.jsx("button",{className:"detail-move-menu-item",role:"menuitem",onClick:()=>Gn(z),onKeyDown:Rt,children:z==="in-progress"?"Back to In Progress":`Move to ${ns[z]}`},z))})]}),as?t.jsx("button",{className:"btn btn-primary btn-sm",disabled:!0,children:as}):t.jsx("button",{className:"btn btn-primary btn-sm",onClick:Ts,children:Re})]}):t.jsxs("div",{children:[t.jsxs("button",{ref:rt,className:"btn btn-primary btn-sm detail-move-btn",onClick:qa,onKeyDown:Ke,disabled:!us,"aria-label":us?`Move to ${ns[us]}`:void 0,"aria-haspopup":Cs?"menu":void 0,"aria-expanded":Cs?Je:void 0,children:[t.jsxs("span",{className:"detail-move-btn__label",children:["Move to ",us?ns[us]:""]}),Cs&&t.jsx("span",{className:"detail-move-btn__arrow","aria-hidden":"true",children:t.jsx(rn,{size:12})})]}),Je&&Cs&&t.jsx("div",{className:"detail-move-menu",role:"menu",onKeyDown:Rt,children:Ki.map(z=>t.jsxs("button",{className:"detail-move-menu-item",role:"menuitem",onClick:()=>Gn(z),onKeyDown:Rt,children:["Move to ",ns[z]]},z))})]})})]})}),fe&&t.jsx("div",{className:"modal-overlay open detail-refine-overlay",onClick:Ri,role:"dialog","aria-modal":"true",children:t.jsxs("div",{className:"modal detail-refine-modal",onClick:z=>z.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:Ri,"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:De,onChange:z=>ot(z.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:[De.length,"/2000 characters"]}),t.jsx("button",{className:"btn btn-primary btn-sm",onClick:ca,disabled:!De.trim()||Be,children:Be?"Creating...":"Create Refinement Task"})]})]}),t.jsx("div",{className:"modal-actions",children:t.jsx("button",{className:"btn btn-sm",onClick:Ri,disabled:Be,children:"Cancel"})})]})}),R&&t.jsx(i.Suspense,{fallback:null,children:t.jsx($I,{agentId:R,projectId:n,onClose:()=>L(null),addToast:h})})]})}function OI({onClose:e,...n}){const s=i.useRef(null);Ai(s,!0,"task-detail-modal-size"),vi(!0);const a=qi(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(Px,{...n,onRequestClose:e})})})}const Xo={triage:"var(--triage)",todo:"var(--todo)","in-progress":"var(--in-progress)","in-review":"var(--in-review)",done:"var(--done)",archived:"var(--text-secondary)"},kp=new Set(["planning","researching","executing","finalizing","merging","merging-fix"]);function jp(e){return e==="merging-fix"?"Merging fixes…":e}const Rx=["title","status","column","dependencies","progress"],zI=["title","status","column"];function FI(e){return e==="online"?"Online":e==="connecting"?"Connecting":e==="error"?"Error":"Offline"}function UI(e){return e==="online"?"●":e==="connecting"?"◐":e==="error"?"✕":"○"}function Np(e){try{const n=An("kb-dashboard-list-columns",e);if(n){const a=JSON.parse(n).filter(r=>Rx.includes(r));if(a.length>0)return new Set(a)}}catch{}return new Set(zI)}function Sp(e){try{const n=An("kb-dashboard-hide-done",e);if(n!==null)return n==="true"}catch{}return!1}function Cp(e){try{const n=An("kb-dashboard-list-collapsed",e);if(n){const a=JSON.parse(n).filter(r=>ea.includes(r));if(a.length>0)return new Set(a)}}catch{}return new Set}function Ep(e){try{const n=An("kb-dashboard-selected-tasks",e);if(n){const s=JSON.parse(n);return new Set(s)}}catch{}return new Set}function _p(e){try{const n=An("kb-dashboard-list-selected-task",e);if(typeof n=="string"&&n.trim().length>0)return n}catch{}return null}function Mp(e){try{const s=An("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 Ll=280,Zd=.65,Zo=16;function eu(e){return Math.max(Ll,e*Zd)}function el(e,n){const s=eu(n);return Math.min(Math.max(e,Ll),s)}function BI(e){return e.status==="executing"||e.column==="in-progress"}function Ap(e){const n=ab(e);return n.total===0||!BI(e)?{label:"-",percent:0,hasProgress:!1}:{label:`${n.completed}/${n.total}`,percent:n.completed/n.total*100,hasProgress:!0}}function HI({tasks:e,onMoveTask:n,onRetryTask:s,onDeleteTask:a,onMergeTask:r,onResetTask:o,onDuplicateTask:l,onOpenDetail:c,addToast:d,globalPaused:u,onNewTask:m,onQuickCreate:h,availableModels:f,favoriteProviders:p=[],favoriteModels:g=[],onToggleFavorite:x,onToggleModelFavorite:w,onPlanningMode:b,onSubtaskBreakdown:y,onTasksUpdated:S,projectId:k,projectName:C,taskStuckTimeoutMs:v,searchQuery:j="",lastFetchTimeMs:P,prAuthAvailable:U}){const[E,R]=i.useState(null),[L,F]=i.useState("asc"),[M,O]=i.useState(null),[q,te]=i.useState(null),[Z,K]=i.useState(null),I=Ys()==="mobile",{confirm:$}=ai(),[N,G]=i.useState(()=>Np(k)),[xe,Se]=i.useState(()=>Sp(k)),[je,se]=i.useState(()=>Cp(k));i.useEffect(()=>{typeof window<"u"&&ss("kb-dashboard-list-columns",JSON.stringify([...N]),k)},[k,N]),i.useEffect(()=>{typeof window<"u"&&ss("kb-dashboard-hide-done",xe.toString(),k)},[xe,k]),i.useEffect(()=>{typeof window<"u"&&ss("kb-dashboard-list-collapsed",JSON.stringify([...je]),k)},[je,k]);const[Ve,ee]=i.useState(!1),[ce,ne]=i.useState(!1),[re,J]=i.useState(()=>Ep(k)),[B,ye]=i.useState(()=>_p(k)),[Ce,H]=i.useState(null),[ke,pe]=i.useState(()=>Mp(k)),Ae=i.useRef(null),Oe=i.useRef(null);i.useEffect(()=>{G(Np(k)),Se(Sp(k)),se(Cp(k)),J(Ep(k));const ve=_p(k);ye(ve),H(ve?e.find(ze=>ze.id===ve)??null:null),pe(Mp(k))},[k,e]),i.useEffect(()=>{typeof window<"u"&&ss("kb-dashboard-selected-tasks",JSON.stringify([...re]),k)},[k,re]),i.useEffect(()=>{if(!(typeof window>"u")){if(B){ss("kb-dashboard-list-selected-task",B,k);return}pr("kb-dashboard-list-selected-task",k)}},[k,B]),i.useEffect(()=>{if(!B){H(null);return}const ve=e.find(ze=>ze.id===B);ve&&H(ze=>!ze||ze.id!==B?ve:{...ze,...ve})},[B,e]),i.useEffect(()=>{if(I||typeof ResizeObserver>"u")return;const ve=Ae.current;if(!ve)return;const ze=()=>{const Ze=el(ke,ve.clientWidth);Ze!==ke&&pe(Ze)};ze();const We=new ResizeObserver(ze);return We.observe(ve),()=>We.disconnect()},[I,ke]),i.useEffect(()=>{if(I||typeof ResizeObserver>"u")return;const ve=Oe.current,ze=Ae.current;if(!ve||!ze)return;let We=null,Ze=ve.offsetWidth;const Ye=new ResizeObserver(()=>{const It=el(ve.offsetWidth,ze.clientWidth);It!==Ze&&(Ze=It,We&&clearTimeout(We),We=setTimeout(()=>{try{ss("kb-dashboard-list-sidebar-width",String(It),k)}catch{}},200))});return Ye.observe(ve),()=>{Ye.disconnect(),We&&clearTimeout(We)}},[I,k]);const He=i.useCallback(()=>{ne(ve=>(ve&&J(new Set),!ve))},[]),dt=i.useCallback(ve=>{J(ze=>{const We=new Set(ze);return We.has(ve)?We.delete(ve):We.add(ve),We})},[]),Fe=i.useCallback(()=>{J(new Set)},[]),fe=i.useCallback(ve=>{G(ze=>{const We=new Set(ze);return We.has(ve)?We.size>1&&We.delete(ve):We.add(ve),We})},[]),$e={title:"Title",status:"Status",column:"Column",dependencies:"Dependencies",progress:"Progress"},De=i.useCallback(ve=>{if(E===ve){F(ze=>ze==="asc"?"desc":"asc");return}R(ve),F("asc")},[E]),ot=i.useCallback(ve=>{K(ze=>ze===ve?null:ve)},[]),Be=i.useCallback(ve=>{se(ze=>{const We=new Set(ze);return We.has(ve)?We.delete(ve):We.add(ve),We})},[]),we=i.useCallback(()=>{K(null)},[]),Q=i.useMemo(()=>{let ve=j?e.filter(Ze=>Ze.id.toLowerCase().includes(j.toLowerCase())||Ze.title&&Ze.title.toLowerCase().includes(j.toLowerCase())||Ze.description.toLowerCase().includes(j.toLowerCase())):[...e];xe&&!Z&&(ve=ve.filter(Ze=>Ze.column!=="done"&&Ze.column!=="archived"));const ze=Z?ve.filter(Ze=>Ze.column===Z):ve,We={triage:[],todo:[],"in-progress":[],"in-review":[],done:[],archived:[]};ze.forEach(Ze=>{const Ye=ju(Ze.column)?Ze.column:Al;We[Ye].push(Ze)});for(const Ze of ea){if(!E){We[Ze]=eb(We[Ze],Ze);continue}We[Ze]=[...We[Ze]].sort((Ye,It)=>{let St=0;switch(E){case"title":St=(Ye.title||Ye.description).localeCompare(It.title||It.description);break;case"status":St=(Ye.status||"").localeCompare(It.status||"");break;case"column":St=Ye.column.localeCompare(It.column);break}return L==="asc"?St:-St})}return We},[e,j,E,L,xe,Z]),_e=i.useMemo(()=>Object.values(Q).reduce((ve,ze)=>ve+ze.length,0),[Q]),lt=i.useMemo(()=>e.filter(ve=>ve.column==="done"||ve.column==="archived").length,[e]),ht=i.useMemo(()=>xe?lt:0,[xe,lt]),mt=i.useCallback(()=>{const ve=Object.values(Q).flat().filter(ze=>ze.column!=="archived").map(ze=>ze.id);J(ze=>{if(ve.every(Ze=>ze.has(Ze))){const Ze=new Set(ze);return ve.forEach(Ye=>Ze.delete(Ye)),Ze}else return new Set([...ze,...ve])})},[Q]),xt=i.useMemo(()=>{const ve=Object.values(Q).flat().filter(ze=>ze.column!=="archived");return ve.length===0?!1:ve.every(ze=>re.has(ze.id))},[Q,re]),Ie=i.useMemo(()=>{const ve=Object.values(Q).flat().filter(We=>We.column!=="archived");if(ve.length===0)return!1;const ze=ve.filter(We=>re.has(We.id)).length;return ze>0&&ze<ve.length},[Q,re]),[Ue,pt]=i.useState("__no_change__"),[oe,le]=i.useState("__no_change__"),[ge,Ne]=i.useState("__no_change__"),[ue,qe]=i.useState([]),[me,tt]=i.useState(!1),Ct=i.useMemo(()=>ge&&ge!=="__no_change__"?ue.find(ve=>ve.id===ge):void 0,[ue,ge]),[wt,$t]=i.useState(!1);i.useEffect(()=>{if(re.size===0)return;let ve=!1;return(async()=>{tt(!0);try{const We=await _l();ve||qe(We)}catch(We){console.error("Failed to fetch nodes for bulk edit",We),ve||qe([])}finally{ve||tt(!1)}})(),()=>{ve=!0}},[re.size]);const Vt=i.useCallback(async()=>{if(re.size===0)return;const ve=Array.from(re).filter(We=>{const Ze=e.find(Ye=>Ye.id===We);return Ze&&Ze.column!=="archived"});if(ve.length===0){d("No valid tasks to update (archived tasks cannot be modified)","error");return}const ze={taskIds:ve};if(Ue!=="__no_change__")if(Ue==="")ze.modelProvider=null,ze.modelId=null;else{const We=Ue.indexOf("/");We!==-1&&(ze.modelProvider=Ue.slice(0,We),ze.modelId=Ue.slice(We+1))}if(oe!=="__no_change__")if(oe==="")ze.validatorModelProvider=null,ze.validatorModelId=null;else{const We=oe.indexOf("/");We!==-1&&(ze.validatorModelProvider=oe.slice(0,We),ze.validatorModelId=oe.slice(We+1))}if(ge!=="__no_change__"&&(ge===""?ze.nodeId=null:ze.nodeId=ge),Object.keys(ze).length===1){d("No changes to apply","info");return}$t(!0);try{const We=await qk(ze.taskIds,ze.modelProvider,ze.modelId,ze.validatorModelProvider,ze.validatorModelId,void 0,void 0,ze.nodeId,k);S&&S(We.updated),d(`Updated ${ve.length} task${ve.length===1?"":"s"}`,"success"),Fe(),pt("__no_change__"),le("__no_change__"),Ne("__no_change__")}catch(We){d(Pe(We)||"Failed to update models","error")}finally{$t(!1)}},[re,e,Ue,oe,ge,k,d,Fe,S]),Mt=i.useCallback(ve=>{if(I){c(ve,{origin:"list-mobile"});return}ye(ve.id),H(ve)},[I,c]),Dt=i.useRef(null),Qt=i.useRef(null);i.useEffect(()=>()=>{Dt.current&&clearTimeout(Dt.current)},[]);const Kt=i.useCallback(ve=>{if(ye(ve.id),H(ve),"prompt"in ve){Qt.current=null,Dt.current&&(clearTimeout(Dt.current),Dt.current=null);return}Qt.current=ve.id,Dt.current&&clearTimeout(Dt.current),Dt.current=setTimeout(()=>{Dt.current=null,Qt.current===ve.id&&Sa(ve.id,k).then(We=>{Qt.current===We.id&&H(Ze=>!Ze||Ze.id!==We.id?Ze:{...Ze,...We})}).catch(()=>{})},200)},[k]),Bt=i.useCallback((ve,ze)=>{if(ze.paused){ve.preventDefault();return}ve.dataTransfer.setData("text/plain",ze.id),ve.dataTransfer.effectAllowed="move",O(ze.id)},[]),on=i.useCallback(()=>{O(null),te(null)},[]),fn=i.useCallback(ve=>{if(I)return;ve.preventDefault();const ze=Ae.current;if(!ze)return;const We=ze.getBoundingClientRect(),Ze=It=>{const St=It.clientX-We.left;pe(el(St,We.width))},Ye=()=>{window.removeEventListener("mousemove",Ze),window.removeEventListener("mouseup",Ye)};window.addEventListener("mousemove",Ze),window.addEventListener("mouseup",Ye)},[I]),Jt=i.useCallback(ve=>{if(I)return;const ze=Ae.current?.clientWidth??0,We=ke/Zd+Zo,Ze=Math.max(ze,We),Ye=eu(Ze);if(ve.key==="ArrowLeft"||ve.key==="ArrowRight"){ve.preventDefault();const It=ve.key==="ArrowLeft"?-Zo:Zo;pe(St=>el(St+It,Ze));return}if(ve.key==="Home"){ve.preventDefault(),pe(Ll);return}ve.key==="End"&&(ve.preventDefault(),pe(Ye))},[I,ke]),an=i.useCallback((ve,ze)=>{ve.preventDefault(),ve.dataTransfer.dropEffect="move",te(ze)},[]),zt=i.useCallback(()=>{te(null)},[]),en=i.useCallback(async(ve,ze)=>{ve.preventDefault(),te(null);const We=ve.dataTransfer.getData("text/plain");if(We){if(ze==="archived"){d("Tasks can only be archived via the archive button","error");return}try{const Ye=e.find(Ht=>Ht.id===We)?.steps.some(Ht=>Ht.status!=="pending")??!1,It=(ze==="todo"||ze==="triage")&&Ye;let St;if(It){if(await $({title:"Preserve Progress?",message:"This task has completed steps. Keep progress before moving?",confirmLabel:"Keep Progress",cancelLabel:"Reset Progress"}))St={preserveProgress:!0};else if(!await $({title:"Reset Progress?",message:"Reset all step progress before moving this task?",confirmLabel:"Reset Progress",cancelLabel:"Cancel Move",danger:!0}))return}await n(We,ze,St)}catch(Ze){d(Pe(Ze),"error")}}},[n,d,e,$]),Zt=ve=>!E||E!==ve?t.jsx(pg,{size:14,className:"sort-icon"}):L==="asc"?t.jsx(ka,{size:14,className:"sort-icon active"}):t.jsx(vo,{size:14,className:"sort-icon active"}),dn=ve=>t.jsxs("div",{id:ve,className:"list-view-options-panel",children:[t.jsx("div",{className:"list-view-options-columns",children:Rx.map(ze=>{const We=N.has(ze),Ze=We&&N.size===1;return t.jsxs("label",{className:`list-column-dropdown-item${Ze?" disabled":""}`,title:Ze?"At least one column must be visible":"",children:[t.jsx("input",{type:"checkbox",checked:We,onChange:()=>fe(ze),disabled:Ze}),t.jsx("span",{children:$e[ze]})]},ze)})}),t.jsxs("button",{className:"btn btn-sm list-hide-done-toggle",onClick:()=>Se(ze=>!ze),"aria-pressed":xe,title:xe?"Show done tasks":"Hide done tasks",children:[xe?t.jsx(kr,{size:14}):t.jsx(mu,{size:14}),xe?"Show Done":"Hide Done"]}),t.jsx("div",{className:"list-drop-zones list-drop-zones--sidebar",children:ea.map(ze=>{const We=e.filter(St=>St.column===ze).length,Ze=ze==="done"||ze==="archived",Ye=xe&&Ze?0:We,It=xe&&Ze&&We>0;return t.jsxs("div",{className:`list-drop-zone${q===ze?" drag-over":""}${Z===ze?" active":""}`,onClick:()=>ot(ze),onDragOver:St=>an(St,ze),onDragLeave:zt,onDrop:St=>en(St,ze),"data-column":ze,children:[t.jsx("span",{className:`list-section-dot dot-${ze}`}),t.jsx("span",{className:"drop-zone-label",children:ns[ze]}),t.jsx("span",{className:"drop-zone-count",children:It?`${Ye} of ${We}`:We})]},ze)})})]});return t.jsxs("div",{className:"list-view",children:[I&&t.jsxs(t.Fragment,{children:[t.jsxs("div",{className:"list-toolbar",children:[t.jsx("button",{className:"btn btn-sm",onClick:He,"aria-pressed":ce,children:ce?"Done Editing":"Bulk Edit"}),t.jsxs("button",{className:"btn btn-sm list-view-options-toggle",onClick:()=>ee(ve=>!ve),"aria-expanded":Ve,"aria-controls":"list-view-options-panel-mobile",children:[t.jsx(Xu,{size:14}),"View options"]}),m?t.jsx("button",{className:"btn btn-task-create btn-sm list-new-task-action",onClick:m,children:"+ New Task"}):null,t.jsx("div",{className:"list-stats",children:Z?`${_e} of ${e.length} tasks in ${ns[Z]}`:`${_e} of ${e.length} tasks`})]}),Ve?t.jsx("div",{className:"list-toolbar-mobile-options",children:dn("list-view-options-panel-mobile")}):null]}),t.jsx("div",{className:"list-table-container",children:t.jsxs("div",{className:I?"":"list-split-layout","data-testid":I?void 0:"list-split-layout",ref:Ae,children:[t.jsxs("div",{className:I?"":"list-split-sidebar","data-testid":I?void 0:"list-split-sidebar",ref:Oe,style:I?void 0:{width:`${ke}px`},children:[!I&&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:[Z?`${_e} of ${e.length} tasks in ${ns[Z]}`:`${_e} of ${e.length} tasks`,ht>0&&!Z&&t.jsxs("span",{className:"list-stats-hidden",children:[" (",ht," hidden)"]})]}),t.jsxs("div",{className:"list-sidebar-controls__actions",children:[t.jsx("button",{className:"btn btn-sm",onClick:He,"aria-pressed":ce,children:ce?"Done Editing":"Bulk Edit"}),m?t.jsx("button",{className:"btn btn-task-create btn-sm list-new-task-action",onClick:m,children:"+ New Task"}):null]}),t.jsxs("div",{className:"list-sidebar-summary-chips",children:[Z?t.jsx("button",{className:"btn btn-sm",onClick:we,"aria-label":"Clear column filter",children:`Filter: ${ns[Z]}`}):null,xe?t.jsx("span",{className:"list-sidebar-chip",children:"Done hidden"}):null,ce?t.jsx("span",{className:"list-sidebar-chip",children:"Bulk edit"}):null,ce&&re.size>0?t.jsx("button",{className:"btn btn-sm",onClick:Fe,children:`${re.size} selected`}):null]})]}),t.jsxs("button",{className:"btn btn-sm list-view-options-toggle",onClick:()=>ee(ve=>!ve),"aria-expanded":Ve,"aria-controls":"list-view-options-panel",children:[t.jsx(Xu,{size:14}),"View options"]}),Ve&&dn("list-view-options-panel"),ce&&re.size>0&&f&&f.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(ys,{models:f,value:Ue,onChange:pt,label:"Executor Model",noChangeValue:"__no_change__",noChangeLabel:"No change",favoriteProviders:p,onToggleFavorite:x,favoriteModels:g,onToggleModelFavorite:w})}),t.jsx("div",{className:"bulk-edit-dropdown",children:t.jsx(ys,{models:f,value:oe,onChange:le,label:"Reviewer Model",noChangeValue:"__no_change__",noChangeLabel:"No change",favoriteProviders:p,onToggleFavorite:x,favoriteModels:g,onToggleModelFavorite:w})}),t.jsxs("div",{className:"bulk-edit-dropdown bulk-edit-node-wrap",children:[t.jsxs("select",{className:"select bulk-node-select",value:ge,onChange:ve=>Ne(ve.target.value),"aria-label":"Node Override",disabled:me,children:[t.jsx("option",{value:"__no_change__",children:"No change"}),t.jsx("option",{value:"",children:"Use project default"}),ue.map(ve=>t.jsx("option",{value:ve.id,children:`${UI(ve.status)} ${ve.name||ve.id} (${FI(ve.status)})`},ve.id))]}),Ct?t.jsx(Ca,{status:Ct.status,showLabel:!0}):null]}),t.jsx("button",{className:"btn btn-primary btn-sm bulk-edit-apply-btn",onClick:Vt,disabled:wt||Ue==="__no_change__"&&oe==="__no_change__"&&ge==="__no_change__",children:wt?"Applying...":"Apply"})]})]}),t.jsx("div",{className:"list-quick-entry-above-table",children:t.jsx(hb,{onCreate:h??(async()=>d("Task creation not available","error")),addToast:d,tasks:e,availableModels:f,onPlanningMode:b,onSubtaskBreakdown:y,projectId:k,autoExpand:!1,favoriteProviders:p,favoriteModels:g,onToggleFavorite:x,onToggleModelFavorite:w})}),_e===0?t.jsx("div",{className:"list-empty",children:j?"No tasks match your filter":"No tasks yet"}):I?t.jsx("div",{className:"list-cards",children:ea.map(ve=>{if(Z&&ve!==Z||xe&&(ve==="done"||ve==="archived")&&!Z)return null;const ze=Q[ve],We=ze.length===0;if(j&&We)return null;const Ze=je.has(ve);return t.jsxs(i.Fragment,{children:[t.jsxs("div",{className:`list-card-section-header${Ze?" list-section-header--collapsed":""}`,onClick:()=>Be(ve),"aria-expanded":!Ze,role:"button",tabIndex:0,onKeyDown:Ye=>{(Ye.key==="Enter"||Ye.key===" ")&&(Ye.preventDefault(),Be(ve))},children:[t.jsx(Mn,{size:14,className:`list-section-chevron${Ze?"":" list-section-chevron--expanded"}`}),t.jsx("span",{className:`list-section-dot dot-${ve}`}),t.jsx("span",{className:"list-section-title",children:ns[ve]}),t.jsx("span",{className:"list-section-count",children:ze.length})]}),!Ze&&t.jsx(t.Fragment,{children:We?t.jsx("div",{className:"list-empty-cell list-card-empty",children:"No tasks"}):ze.map(Ye=>{const It=Ye.status==="failed",St=Ye.paused===!0,Ht=Rl(Ye,v,P),jt=!u&&!It&&!St&&!Ht&&(Ye.column==="in-progress"||kp.has(Ye.status)),ae=typeof Ye.status=="string"&&Ye.status.trim().length>0,Le=!!(Ye.dependencies&&Ye.dependencies.length>0),At=Ap(Ye),Lt=At.hasProgress,Ft=ce;return t.jsxs("div",{className:`list-card${jt?" agent-active":""}${Ft?" list-card--selectable":""}`,onClick:()=>Mt(Ye),"data-id":Ye.id,children:[Ft&&t.jsx("label",{className:"list-card-checkbox",onClick:Me=>Me.stopPropagation(),children:t.jsx("input",{type:"checkbox",checked:re.has(Ye.id),onChange:Me=>{Me.stopPropagation(),dt(Ye.id)},onClick:Me=>Me.stopPropagation(),disabled:Ye.column==="archived","aria-label":`Select ${Ye.id}`})}),t.jsxs("div",{className:"list-card-row",children:[t.jsx("span",{className:"list-card-id",children:Ye.id}),Ye.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(Qn,{"aria-hidden":"true"}),t.jsx("span",{className:"visually-hidden",children:"Fast mode"})]}),t.jsx("span",{className:"list-card-spacer"}),St&&Ye.pausedByAgentId?t.jsx("span",{className:"list-status-badge paused",children:"paused by agent"}):Ht?t.jsx("span",{className:"list-status-badge stuck",children:"Stuck"}):ae?t.jsx("span",{className:`list-status-badge list-status-badge--${Ye.column}${It?" failed":""}${jt?" pulsing":""}`,children:jp(Ye.status??"")}):null]}),t.jsx("div",{className:"list-card-row",children:t.jsx("div",{className:"list-card-title",children:Ye.title||Ye.description})}),(Le||Lt)&&t.jsxs("div",{className:"list-card-row list-card-meta",children:[Le&&t.jsxs("span",{className:"list-dep-badge",title:Ye.dependencies.join(", "),children:[t.jsx(cr,{size:12})," ",Ye.dependencies.length]}),Lt&&t.jsxs("div",{className:"list-progress",children:[t.jsx("div",{className:"list-progress-bar",children:t.jsx("div",{className:"list-progress-fill",style:{width:`${At.percent}%`,backgroundColor:Xo[Ye.column]}})}),t.jsx("span",{className:"list-progress-label",children:At.label})]})]})]},Ye.id)})})]},ve)})}):t.jsxs("table",{className:"list-table",children:[t.jsx("thead",{children:t.jsxs("tr",{children:[ce&&t.jsx("th",{className:"list-header-cell list-header-checkbox",children:t.jsx("input",{type:"checkbox",checked:xt,ref:ve=>{ve&&(ve.indeterminate=Ie)},onChange:mt,"aria-label":"Select all visible tasks"})}),N.has("title")&&t.jsxs("th",{className:"list-header-cell",onClick:()=>De("title"),children:["Title ",Zt("title")]}),N.has("status")&&t.jsxs("th",{className:"list-header-cell",onClick:()=>De("status"),children:["Status ",Zt("status")]}),N.has("column")&&t.jsxs("th",{className:"list-header-cell",onClick:()=>De("column"),children:["Column ",Zt("column")]}),N.has("dependencies")&&t.jsx("th",{className:"list-header-cell",children:"Dependencies"}),N.has("progress")&&t.jsx("th",{className:"list-header-cell",children:"Progress"})]})}),t.jsx("tbody",{children:ea.map(ve=>{if(Z&&ve!==Z||xe&&(ve==="done"||ve==="archived")&&!Z)return null;const ze=Q[ve],We=ze.length===0;if(j&&We)return null;const Ze=je.has(ve);return t.jsxs(i.Fragment,{children:[t.jsx("tr",{className:`list-section-header${Ze?" list-section-header--collapsed":""}`,onClick:()=>Be(ve),"aria-expanded":!Ze,children:t.jsxs("th",{colSpan:N.size+(ce?1:0),className:"list-section-cell",children:[t.jsx(Mn,{size:14,className:`list-section-chevron${Ze?"":" list-section-chevron--expanded"}`}),t.jsx("span",{className:`list-section-dot dot-${ve}`}),t.jsx("span",{className:"list-section-title",children:ns[ve]}),t.jsx("span",{className:"list-section-count",children:ze.length})]})}),!Ze&&t.jsx(t.Fragment,{children:We?t.jsx("tr",{className:"list-section-empty",children:t.jsx("td",{colSpan:N.size+(ce?1:0),className:"list-empty-cell",children:"No tasks"})}):ze.map(Ye=>{const It=Ye.status==="failed",St=Ye.paused===!0,Ht=Rl(Ye,v,P),jt=!u&&!It&&!St&&!Ht&&(Ye.column==="in-progress"||kp.has(Ye.status)),ae=M===Ye.id;return t.jsxs("tr",{className:`list-row${It?" failed":""}${St?" paused":""}${Ht?" stuck":""}${jt?" agent-active":""}${ae?" dragging":""}${B===Ye.id?" list-row--selected":""}`,onClick:()=>Mt(Ye),draggable:!St,onDragStart:Le=>Bt(Le,Ye),onDragEnd:on,"data-id":Ye.id,children:[ce&&t.jsx("td",{className:"list-cell list-cell-checkbox",children:t.jsx("input",{type:"checkbox",checked:re.has(Ye.id),onChange:Le=>{Le.stopPropagation(),dt(Ye.id)},onClick:Le=>Le.stopPropagation(),disabled:Ye.column==="archived","aria-label":`Select ${Ye.id}`})}),N.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:Ye.id}),t.jsxs("div",{className:"list-title-row",children:[Ye.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(Qn,{"aria-hidden":"true"}),t.jsx("span",{className:"visually-hidden",children:"Fast mode"})]}),t.jsx("span",{className:"list-title-text",children:Ye.title||Ye.description})]})]})}),N.has("status")&&t.jsx("td",{className:"list-cell",children:St&&Ye.pausedByAgentId?t.jsx("span",{className:"list-status-badge paused",children:"paused by agent"}):Ht?t.jsx("span",{className:"list-status-badge stuck",children:"Stuck"}):Ye.status?t.jsx("span",{className:`list-status-badge list-status-badge--${Ye.column}${It?" failed":""}${jt?" pulsing":""}`,children:jp(Ye.status??"")}):t.jsx("span",{className:"list-status-badge",children:"-"})}),N.has("column")&&t.jsx("td",{className:"list-cell",children:t.jsx("span",{className:"list-column-badge",style:{background:`${Xo[Ye.column]}20`,color:Xo[Ye.column]},children:ns[Ye.column]})}),N.has("dependencies")&&t.jsx("td",{className:"list-cell list-cell-deps",children:Ye.dependencies&&Ye.dependencies.length>0?t.jsxs("span",{className:"list-dep-badge",title:Ye.dependencies.join(", "),children:[t.jsx(cr,{size:12})," ",Ye.dependencies.length]}):"-"}),N.has("progress")&&t.jsx("td",{className:"list-cell list-cell-progress",children:(()=>{const Le=Ap(Ye);return Le.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:`${Le.percent}%`,backgroundColor:Xo[Ye.column]}})}),t.jsx("span",{className:"list-progress-label",children:Le.label})]}):"-"})()})]},Ye.id)})})]},ve)})})]})]}),!I&&t.jsxs(t.Fragment,{children:[t.jsx("div",{className:"list-split-resize-handle","data-testid":"list-split-resize-handle",onMouseDown:fn,onKeyDown:Jt,role:"separator",tabIndex:0,"aria-orientation":"vertical","aria-label":"Resize task list sidebar","aria-valuemin":Ll,"aria-valuemax":Math.round(eu(Ae.current?.clientWidth??ke/Zd+Zo)),"aria-valuenow":Math.round(ke)}),t.jsx("div",{className:"list-split-detail","data-testid":"list-split-detail",children:Ce?t.jsx("div",{className:"list-split-detail-content","data-testid":"list-split-detail-content",children:t.jsx(Px,{task:Ce,projectId:k,tasks:e,embedded:!0,onOpenDetail:Kt,onMoveTask:n,onDeleteTask:a,onMergeTask:r,onRetryTask:s,onResetTask:o,onDuplicateTask:l,onTaskUpdated:ve=>{H(ze=>!ze||ze.id!==ve.id?ze:{...ze,...ve})},addToast:d,prAuthAvailable:U})}):t.jsx("div",{className:"list-split-detail-empty",children:t.jsx("p",{children:"Select a task to view details"})})})]})]})})]})}const qI={active:{label:"Active",color:"var(--color-success)",icon:Yn},paused:{label:"Paused",color:"var(--color-warning)",icon:pi},errored:{label:"Error",color:"var(--color-error)",icon:Ps},initializing:{label:"Initializing",color:"var(--color-warning)",icon:bt}};function VI(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 Pp(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 WI(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 KI({project:e,health:n,onSelect:s,onPause:a,onResume:r,onRemove:o,availabilityMappings:l=[],isLoading:c=!1}){const[d,u]=i.useState(!1),m=qI[e.status],h=m.icon,f=i.useCallback(()=>{s(e)},[s,e]),p=i.useCallback(S=>{S.stopPropagation(),a(e)},[a,e]),g=i.useCallback(S=>{S.stopPropagation(),r(e)},[r,e]),x=i.useCallback(S=>{if(S.stopPropagation(),!d){u(!0);return}o(e),u(!1)},[d,o,e]),w=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:S=>{(S.key==="Enter"||S.key===" ")&&(S.preventDefault(),f())},children:[t.jsxs("div",{className:"project-card-header",children:[t.jsx("div",{className:"project-card-icon",children:t.jsx(bs,{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(S=>t.jsxs("div",{className:"project-card-availability__row",title:`${S.displayName} → ${S.path}`,children:[t.jsx("span",{className:"project-card-availability__node",children:S.displayName}),t.jsx("span",{className:"project-card-availability__arrow",children:"→"}),t.jsx("code",{className:"project-card-availability__path",children:Pp(S.path,28)})]},`${S.nodeId}-${S.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:Pp(e.path)})]}),t.jsxs("div",{className:"project-card-status-badge",style:{color:m.color,borderColor:m.color},children:[t.jsx(h,{size:12,className:y?"animate-spin":""}),t.jsx("span",{children:m.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:VI(e.lastActivityAt||n?.lastActivityAt)})]}),t.jsxs("div",{className:"project-card-actions",children:[w?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(Yn,{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(pi,{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(yo,{size:14}),t.jsx("span",{children:"Open"})]}),t.jsxs("button",{className:`project-card-action project-card-action-remove ${d?"is-armed":""}`,onClick:x,disabled:c,title:d?"Confirm remove":"Remove project","aria-label":d?"Confirm remove project":"Remove project",children:[t.jsx(vn,{size:14}),t.jsx("span",{children:d?"Confirm":""})]})]})]})]})}const GI=i.memo(KI,WI);function Rp(e){return typeof e=="string"&&e.trim().length>0}function Qr(e){return(e.nodeMappings??[]).filter(s=>Rp(s.nodeId)&&Rp(s.path)).map(s=>({nodeId:s.nodeId,nodeName:s.nodeName,path:s.path,available:s.available!==!1}))}function JI(e,n){return Qr(e).filter(s=>s.nodeId===n.id&&s.available)}function YI(e,n){return JI(e,n).length>0}function QI(e,n){return e.filter(s=>YI(s,n))}function n5(e,n){return QI(e,n).length}function Ip(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 XI(){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(bs,{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(Ks,{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(Dn,{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(Ps,{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 ZI=1e4,Tp=5;function eT(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),m=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+=Tp){const x=e.slice(g,g+Tp),w=await Promise.allSettled(x.map(async b=>{try{return await Nm(b)}catch{return null}}));if(x.forEach((b,y)=>{const S=w[y];p[b]=S.status==="fulfilled"?S.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]),h=i.useCallback(async f=>{try{const p=await Nm(f);s(g=>({...g,[f]:p}))}catch(p){console.error(`Failed to fetch health for project ${f}:`,p)}},[]);return i.useEffect(()=>(u.current=!1,m(),()=>{d.current&&d.current.abort()}),[m]),i.useEffect(()=>{if(e.length!==0)return c.current&&clearInterval(c.current),c.current=setInterval(()=>{m()},ZI),()=>{c.current&&(clearInterval(c.current),c.current=null)}},[m,e.length]),{healthMap:n,loading:a,error:o,refresh:m,refreshProject:h}}function tT({projects:e,loading:n=!1,onSelectProject:s,onAddProject:a,onPauseProject:r,onResumeProject:o,onRemoveProject:l,nodes:c=[]}){const[d,u]=i.useState("all"),[m,h]=i.useState(null),[f,p]=i.useState("activity"),[g,x]=i.useState("desc");i.useEffect(()=>{if(typeof window>"u")return;const F=localStorage.getItem("kb-dashboard-recent-projects");if(F)try{const M=JSON.parse(F);b(M)}catch{}},[]);const[w,b]=i.useState([]),y=i.useMemo(()=>e.map(F=>F.id),[e]),{healthMap:S,loading:k}=eT(y),C=i.useMemo(()=>e.map(F=>({project:F,health:S[F.id]||null})),[e,S]),v=i.useMemo(()=>{let F=[...C];return d!=="all"&&(F=F.filter(({project:M})=>M.status===d)),m!==null&&(F=F.filter(({project:M})=>Qr(M).some(O=>O.available&&O.nodeId===m))),F},[C,d,m]),j=i.useMemo(()=>{const F=[...v];return F.sort((M,O)=>{let q=0;switch(f){case"name":q=M.project.name.localeCompare(O.project.name);break;case"activity":{const te=M.project.lastActivityAt||M.health?.lastActivityAt||M.project.updatedAt,Z=O.project.lastActivityAt||O.health?.lastActivityAt||O.project.updatedAt;q=new Date(Z).getTime()-new Date(te).getTime();break}case"status":{const te={errored:0,initializing:1,paused:2,active:3};q=te[M.project.status]-te[O.project.status];break}}return g==="asc"?q:-q}),F},[v,f,g]),P=i.useMemo(()=>{const F=e.length,M=e.filter(I=>I.status==="active").length,O=e.filter(I=>I.status==="errored").length,q=new Set;e.forEach(I=>{Qr(I).forEach($=>{$.available&&q.add($.nodeId)})});const te=q.size;let Z=0,K=0,A=0;return Object.values(S).forEach(I=>{I&&(Z+=I.activeTaskCount,K+=I.totalTasksCompleted,A+=I.inFlightAgentCount)}),{totalProjects:F,activeProjects:M,erroredProjects:O,totalNodes:te,totalActiveTasks:Z,totalCompletedTasks:K,totalInFlightAgents:A}},[e,S]),U=i.useMemo(()=>({all:e.length,active:e.filter(F=>F.status==="active").length,paused:e.filter(F=>F.status==="paused").length,errored:e.filter(F=>F.status==="errored").length}),[e]),E=i.useMemo(()=>{const F=new Map;return e.forEach(M=>{Qr(M).filter(O=>O.available).forEach(O=>{const q=O.nodeId,te=F.get(q),Z=Ip(q,O,c,M);te?te.count+=1:F.set(q,{name:Z,count:1})})}),Array.from(F.entries()).map(([M,{name:O,count:q}])=>({nodeId:M,name:O,count:q}))},[e,c]),R=i.useCallback(F=>{const M=[F.id,...w.filter(O=>O!==F.id)].slice(0,3);b(M),typeof window<"u"&&localStorage.setItem("kb-dashboard-recent-projects",JSON.stringify(M)),s(F)},[s,w]);return n||k&&e.length>0&&Object.keys(S).length===0?t.jsx(XI,{}):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(ya,{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(gn,{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(aa,{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(bs,{size:16})}),t.jsxs("div",{className:"project-stat__content",children:[t.jsx("span",{className:"project-stat__value",children:P.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(Ks,{size:16})}),t.jsxs("div",{className:"project-stat__content",children:[t.jsx("span",{className:"project-stat__value",children:P.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(Dn,{size:16})}),t.jsxs("div",{className:"project-stat__content",children:[t.jsx("span",{className:"project-stat__value",children:P.totalCompletedTasks}),t.jsx("span",{className:"project-stat__label",children:"Completed"})]})]}),P.erroredProjects>0&&t.jsxs("div",{className:"project-stat project-stat--error",children:[t.jsx("div",{className:"project-stat__icon",children:t.jsx(Ps,{size:16})}),t.jsxs("div",{className:"project-stat__content",children:[t.jsx("span",{className:"project-stat__value",children:P.erroredProjects}),t.jsx("span",{className:"project-stat__label",children:"Errored"})]})]}),P.totalNodes>1&&t.jsxs("div",{className:"project-stat project-stat--nodes",children:[t.jsx("div",{className:"project-stat__icon",children:t.jsx(co,{size:16})}),t.jsxs("div",{className:"project-stat__content",children:[t.jsx("span",{className:"project-stat__value",children:P.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(gn,{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:U.all})]}),t.jsxs("button",{className:`project-filter-tab ${d==="active"?"active":""}`,onClick:()=>u("active"),children:["Active",t.jsx("span",{className:"project-filter-count",children:U.active})]}),t.jsxs("button",{className:`project-filter-tab ${d==="paused"?"active":""}`,onClick:()=>u("paused"),children:["Paused",t.jsx("span",{className:"project-filter-count",children:U.paused})]}),t.jsxs("button",{className:`project-filter-tab ${d==="errored"?"active":""} ${U.errored>0?"has-errors":""}`,onClick:()=>u("errored"),children:["Errored",t.jsx("span",{className:"project-filter-count",children:U.errored})]})]}),E.length>1&&t.jsxs("div",{className:"project-node-filter",children:[t.jsx(co,{size:14}),t.jsxs("select",{value:m??"",onChange:F=>{h(F.target.value||null)},className:"project-node-filter-select","aria-label":"Filter by node",children:[t.jsx("option",{value:"",children:"All Nodes"}),E.map(({nodeId:F,name:M,count:O})=>t.jsxs("option",{value:F??"",children:[M," (",O,")"]},F??"local"))]})]}),t.jsxs("div",{className:"project-sort",children:[t.jsx(jl,{size:14}),t.jsxs("select",{value:`${f}-${g}`,onChange:F=>{const[M,O]=F.target.value.split("-");p(M),x(O)},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(pg,{size:14})]})]}),t.jsx("div",{className:"project-grid",children:j.map(({project:F,health:M})=>{const O=Qr(F).filter(q=>q.available).map(q=>({...q,displayName:Ip(q.nodeId,q,c,F)}));return t.jsx(GI,{project:F,health:M,availabilityMappings:O,onSelect:R,onPause:r,onResume:o,onRemove:l},F.id)})}),j.length===0&&t.jsxs("div",{className:"project-overview__no-results",children:[t.jsx(jl,{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 Wu="kb-planning-last-description",Ku="kb-subtask-last-description",Gu="kb-mission-last-goal";function nT(e,n){ss(Wu,e,n)}function sT(e){return An(Wu,e)||""}function Xa(e){pr(Wu,e)}function iT(e,n){ss(Ku,e,n)}function aT(e){return An(Ku,e)||""}function td(e){pr(Ku,e)}function rT(e,n){ss(Gu,e,n)}function oT(e){return An(Gu,e)||""}function Qi(e){pr(Gu,e)}function lT(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 cT(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 dT(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 si({entries:e,defaultShowThinking:n=!1}){const[s,a]=i.useState({}),r=dT(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,m=c?lT(o):void 0,h=o.question&&m!==void 0?cT(o.question,m):"",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:h||"—"}),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 $p="fusion-tab-id";function uT(){const e=globalThis.crypto;return e&&typeof e.randomUUID=="function"?e.randomUUID():`tab-${Date.now()}-${Math.random().toString(36).slice(2,10)}`}function Ia(){if(typeof window>"u")return"server-tab";const e=window.sessionStorage.getItem($p);if(e)return e;const n=uT();return window.sessionStorage.setItem($p,n),n}function cc(e){const n=i.useMemo(()=>Ia(),[]),[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(E1(e,n)).then(m=>{if(u){if(m.acquired){a(!1),o(null);return}a(!0),o(m.currentHolder)}}).catch(()=>{u&&(a(!1),o(null))}).finally(()=>{u&&c(!1)}),()=>{u=!1;try{const m=_1(e,n);m&&typeof m.catch=="function"&&m.catch(()=>{})}catch{}}},[e,n]),i.useEffect(()=>{if(!e||typeof window>"u")return;const u=()=>{if(typeof navigator.sendBeacon!="function")return;const m=Mi(`/api/ai-sessions/${encodeURIComponent(e)}/lock/beacon?tabId=${encodeURIComponent(n)}`);navigator.sendBeacon(m)};return window.addEventListener("beforeunload",u),()=>{window.removeEventListener("beforeunload",u)}},[e,n]),i.useEffect(()=>!e||typeof EventSource>"u"?void 0:ii("/api/events",{events:{"ai_session:updated":m=>{try{const h=JSON.parse(m.data);if(h.id!==e)return;const f=h.lockedByTab??null;o(f),a(!!(f&&f!==n))}catch{}}}}),[e,n]);const d=i.useCallback(async()=>{if(e){c(!0);try{await Promise.resolve(M1(e,n)),a(!1),o(null)}finally{c(!1)}}},[e,n]);return{isLockedByOther:s,currentHolder:r,takeControl:d,isLoading:l}}const mT="fusion:ai-session-sync",Dp="fusion:ai-session-sync",hT=3e4,pT=6e4;function ki(){return Date.now()}function fT(){const e=globalThis.crypto;return e&&typeof e.randomUUID=="function"?e.randomUUID():`tab-${Date.now()}-${Math.random().toString(36).slice(2,10)}`}function Lp(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 gT{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=fT(),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:ki()})}broadcastUpdate(n){const s=n.timestamp??ki();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??ki();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=ki();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=ki();this.releaseTabOwnership(n,s,a),this.ownedSessions.delete(n),this.publish({type:"tab:inactive",tabId:s,sessionId:n,timestamp:a})}broadcastHeartbeat(n){const s=ki();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(mT),this.channel.onmessage=s=>{const a=Lp(s.data);a&&this.handleIncomingMessage(a)},this.usingStorageFallback=!1;return}catch{}this.usingStorageFallback=!0;const n=s=>{if(!(s.key!==Dp||!s.newValue))try{const a=JSON.parse(s.newValue),r=Lp(a.message);r&&this.handleIncomingMessage(r)}catch{}};window.addEventListener("storage",n),this.cleanupStorageListener=()=>{window.removeEventListener("storage",n)}}startHeartbeat(){this.heartbeatInterval=setInterval(()=>{const n=ki();this.updateHeartbeat(this.tabId,n),this.publish({type:"tab:heartbeat",tabId:this.tabId,timestamp:n})},hT)}startStaleSweep(){this.staleSweepInterval=setInterval(()=>{this.emit()},1e4)}setupBeforeUnloadCleanup(){const n=()=>{for(const[s,a]of this.ownedSessions.entries()){const r=ki();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(Dp,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:ki()});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=ki(),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>pT;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 ji=new gT;function _r(){const e=i.useSyncExternalStore(c=>ji.subscribe(c),()=>ji.getSnapshot(),()=>ji.getSnapshot());i.useEffect(()=>{ji.requestSync()},[]);const n=i.useCallback(c=>{ji.broadcastUpdate(c)},[]),s=i.useCallback(c=>{ji.broadcastCompleted(c)},[]),a=i.useCallback((c,d)=>{ji.broadcastLock(c,d)},[]),r=i.useCallback((c,d)=>{ji.broadcastUnlock(c,d)},[]),o=i.useCallback(c=>{ji.broadcastHeartbeat(c)},[]),l=i.useCallback(()=>{ji.requestSync()},[]);return{tabId:e.tabId,sessions:e.sessions,activeTabMap:e.activeTabMap,broadcastUpdate:n,broadcastCompleted:s,broadcastLock:a,broadcastUnlock:r,broadcastHeartbeat:o,requestSync:l}}function bT(e,n){return e&&n?`${e}/${n}`:""}function xT(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 vT=["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 yT({isOpen:e,onClose:n,onMissionCreated:s,projectId:a,initialGoal:r,resumeSessionId:o}){vi(e);const[l,c]=i.useState(""),[d,u]=i.useState({type:"initial"}),[m,h]=i.useState(null),[f,p]=i.useState([]),[g,x]=i.useState([]),[w,b]=i.useState(null),[y,S]=i.useState(!1),k=i.useRef(!1),[C,v]=i.useState(""),[j,P]=i.useState(!0),[U,E]=i.useState(!1),[R,L]=i.useState(!1),[F,M]=i.useState(!1),O=i.useRef(null),q=i.useRef(null),te=i.useRef(null),Z=i.useRef(null),[K,A]=i.useState(o??null),I=i.useMemo(()=>Ia(),[]),{isLockedByOther:$,takeControl:N,isLoading:G}=cc(e?K:null),{activeTabMap:xe,broadcastUpdate:Se,broadcastCompleted:je,broadcastLock:se,broadcastUnlock:Ve,broadcastHeartbeat:ee}=_r(),{confirm:ce}=ai(),[ne,re]=i.useState(void 0),[J,B]=i.useState(void 0),[ye,Ce]=i.useState([]),[H,ke]=i.useState(!0),[pe,Ae]=i.useState(null),[Oe,He]=i.useState([]),[dt,Fe]=i.useState([]),fe=bT(ne,J);i.useEffect(()=>{(async()=>{try{ke(!0);const Ne=await Os();Ce(Ne.models),He(Ne.favoriteProviders),Fe(Ne.favoriteModels)}catch(Ne){Ae(Pe(Ne)||"Failed to load models")}finally{ke(!1)}})()},[]);const $e=i.useCallback(ge=>{He(Ne=>{const ue=Ne,me=ue.includes(ge)?ue.filter(tt=>tt!==ge):[ge,...ue];return kn({favoriteProviders:me,favoriteModels:dt}).catch(()=>{He(ue)}),me})},[dt]),De=i.useCallback(ge=>{Fe(Ne=>{const ue=Ne,me=ue.includes(ge)?ue.filter(tt=>tt!==ge):[ge,...ue];return kn({favoriteProviders:Oe,favoriteModels:me}).catch(()=>{Fe(ue)}),me})},[Oe]),ot=i.useCallback((ge,Ne)=>{if(!ge||!Ne)return"Using default";const ue=ye.find(qe=>qe.provider===ge&&qe.id===Ne);return ue?`${ue.provider}/${ue.id}`:`${ge}/${Ne}`},[ye]),Be=i.useCallback(ge=>{q.current?.close();const Ne=h1(ge,a,{onThinking:ue=>{v(qe=>qe+ue),Se({sessionId:ge,status:"generating",needsInput:!1,owningTabId:I,type:"mission_interview",title:l.trim()||void 0,projectId:a??null})},onQuestion:ue=>{E(!1),L(!1),Qi(a),u({type:"question",sessionId:ge,question:ue}),v(""),S(!0),Se({sessionId:ge,status:"awaiting_input",needsInput:!0,owningTabId:I,type:"mission_interview",title:l.trim()||void 0,projectId:a??null})},onSummary:ue=>{E(!1),L(!1),Qi(a),u({type:"summary",sessionId:ge,summary:ue}),b(ue),v(""),S(!0),Se({sessionId:ge,status:"complete",needsInput:!1,owningTabId:I,type:"mission_interview",title:l.trim()||void 0,projectId:a??null})},onError:ue=>{const qe=ue||"Session failed while contacting the AI.";E(!1),L(!1),h(null),u({type:"error",sessionId:ge,errorMessage:qe}),v(""),S(!0),te.current=ge,Se({sessionId:ge,status:"error",needsInput:!1,owningTabId:I,type:"mission_interview",title:l.trim()||void 0,projectId:a??null}),je({sessionId:ge,status:"error"})},onComplete:()=>{E(!1),L(!1),te.current=null,je({sessionId:ge,status:"complete"})},onConnectionStateChange:ue=>{E(ue==="reconnecting")}});q.current=Ne},[je,Se,l,a,I]),we=i.useCallback(async ge=>{const Ne=ge??l;if(Ne.trim()){h(null),v(""),p([]),x([]),E(!1),u({type:"loading"});try{const{sessionId:ue}=await c1(Ne.trim(),a,ne&&J?{modelProvider:ne,modelId:J}:void 0);te.current=ue,A(ue),Qi(a),Be(ue),p([])}catch(ue){E(!1),h(Pe(ue)||"Failed to start interview session"),u({type:"initial"}),te.current=null,A(null)}}},[Be,l,ne,J,a]);i.useEffect(()=>{e&&d.type==="initial"&&O.current?.focus()},[e,d.type]),i.useEffect(()=>{if(e&&!r&&!o&&!k.current&&d.type==="initial"){const ge=oT(a);ge&&c(ge)}},[e]),i.useEffect(()=>{if(e&&r&&!k.current&&d.type==="initial"){c(r);const ge=setTimeout(()=>{k.current=!0,we(r)},0);return()=>clearTimeout(ge)}},[e,r,d.type,we]),i.useEffect(()=>{e||(k.current=!1,E(!1),L(!1),A(null))},[e]),i.useEffect(()=>{if(!e||!o||d.type!=="initial")return;let ge=!1;return Ci(o).then(Ne=>{if(ge||!Ne)return;const ue=hr(Ne.conversationHistory);if(x(ue),A(Ne.id),p(ue.map(qe=>qe.response).filter(qe=>!!(qe&&typeof qe=="object"&&!Array.isArray(qe)))),Ne.status==="awaiting_input"&&Ne.currentQuestion)try{Qi(a);const qe=JSON.parse(Ne.currentQuestion);te.current=Ne.id,S(!0),u({type:"question",sessionId:Ne.id,question:qe})}catch{h("Failed to restore session question.")}else if(Ne.status==="complete"&&Ne.result)try{Qi(a);const qe=JSON.parse(Ne.result);te.current=Ne.id,S(!0),b(qe),u({type:"summary",sessionId:Ne.id,summary:qe})}catch{h("Failed to restore session result.")}else Ne.status==="generating"?(te.current=Ne.id,S(!0),Ne.thinkingOutput&&v(Ne.thinkingOutput),u({type:"loading"}),Be(Ne.id)):Ne.status==="error"&&(te.current=Ne.id,S(!0),h(null),u({type:"error",sessionId:Ne.id,errorMessage:Ne.error??"The session encountered an error."}))}).catch(()=>{ge||h("Failed to resume session.")}),()=>{ge=!0}},[Be,e,o,d.type,a]),i.useEffect(()=>{if(!e){Z.current&&(Ve(Z.current,I),Z.current=null);return}if(K&&Z.current!==K){Z.current&&Ve(Z.current,I),se(K,I),Z.current=K;return}!K&&Z.current&&(Ve(Z.current,I),Z.current=null)},[se,Ve,e,K,I]),i.useEffect(()=>{if(!e||!K||Z.current!==K)return;ee(I);const ge=setInterval(()=>{ee(I)},3e4);return()=>{clearInterval(ge)}},[ee,e,K,I]),i.useEffect(()=>()=>{q.current?.close(),q.current=null,Z.current&&(Ve(Z.current,I),Z.current=null)},[Ve,I]),i.useEffect(()=>{if(!e)return;const ge=Ne=>{(d.type==="question"||d.type==="summary")&&(Ne.preventDefault(),Ne.returnValue=""),q.current?.close()};return window.addEventListener("beforeunload",ge),()=>window.removeEventListener("beforeunload",ge)},[e,d]);const Q=i.useCallback(()=>{q.current?.close(),q.current=null,n()},[n]),_e=i.useCallback(async()=>{if(l&&rT(l,a),!(y&&!await ce({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 Ug(d.sessionId,a,I)}catch{}c(""),u({type:"initial"}),h(null),p([]),x([]),b(null),v(""),E(!1),L(!1),S(!1),M(!1),re(void 0),B(void 0),te.current=null,A(null),n()}},[l,y,d,n,a,I,ce]);i.useEffect(()=>{if(!e)return;const ge=Ne=>{Ne.key==="Escape"&&_e()};return document.addEventListener("keydown",ge),()=>document.removeEventListener("keydown",ge)},[e,_e]);const lt=i.useCallback(async ge=>{if(d.type!=="question")return;const{sessionId:Ne}=d;h(null),p(ue=>[...ue,ge]),x(ue=>[...ue,{question:d.question,response:ge}]),u({type:"loading"}),v("");try{Be(Ne),await d1(Ne,ge,a,I),S(!0)}catch(ue){q.current?.close(),q.current=null,h(Pe(ue)||"Failed to submit response"),u({type:"question",sessionId:Ne,question:d.question})}},[d,a,I,Be]),ht=i.useCallback(async()=>{if(d.type!=="error")return;const ge=d.sessionId;h(null),L(!0),v(""),u({type:"loading"}),Be(ge);try{te.current=ge,A(ge),await u1(ge,a,I)}catch(Ne){let ue=Ne;if((Pe(Ne)||"").includes("not in an error state"))try{const me=await Ci(ge);if(!me)throw new Error("Failed to refresh interview session.");const tt=hr(me.conversationHistory);if(x(tt),p(tt.map(Ct=>Ct.response).filter(Ct=>!!(Ct&&typeof Ct=="object"&&!Array.isArray(Ct)))),te.current=me.id,A(me.id),S(!0),me.status==="generating")v(me.thinkingOutput??""),u({type:"loading"}),q.current?.isConnected()||Be(me.id);else if(me.status==="awaiting_input"){if(!me.currentQuestion)throw new Error("Interview session is awaiting input but has no current question.");Qi(a);const Ct=JSON.parse(me.currentQuestion);u({type:"question",sessionId:me.id,question:Ct}),q.current?.isConnected()||Be(me.id)}else if(me.status==="complete"){if(!me.result)throw new Error("Interview session is complete but has no result.");Qi(a);const Ct=JSON.parse(me.result);b(Ct),u({type:"summary",sessionId:me.id,summary:Ct})}else me.status==="error"&&u({type:"error",sessionId:me.id,errorMessage:me.error??"Retry failed. Please try again."});E(!1);return}catch(me){ue=me}q.current?.close(),q.current=null,u({type:"error",sessionId:ge,errorMessage:Pe(ue)||"Retry failed. Please try again."}),E(!1)}finally{L(!1)}},[Be,a,I,d]),mt=i.useCallback(async()=>{if(d.type==="summary"){h(null),M(!0);try{const ge=await m1(d.sessionId,w||void 0,a);s(ge),Qi(a),q.current?.close(),q.current=null,c(""),u({type:"initial"}),h(null),p([]),x([]),b(null),v(""),E(!1),L(!1),S(!1),M(!1),te.current=null,A(null),n()}catch(ge){h(Pe(ge)||"Failed to create mission"),M(!1)}}},[d,w,s,n,a]),xt=()=>d.type==="question"?Math.min(f.length+1,6):6,Ie=d.type==="loading"||d.type==="question"||d.type==="summary"||d.type==="error",Ue=K?xe.get(K):null,pt=Ue&&Ue.tabId!==I,oe=!!(pt&&!Ue.stale),le=$&&(!pt||Ue.stale);return e?t.jsx("div",{className:"modal-overlay open",onClick:ge=>ge.target===ge.currentTarget&&_e(),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(vs,{size:20,className:"icon-triage"}),t.jsx("h3",{children:"Plan Mission with AI"})]}),t.jsxs("div",{className:"modal-header-actions",children:[Ie&&t.jsx("button",{className:"modal-send-to-background",onClick:Q,title:"Send to background","aria-label":"Send to background",children:t.jsx(jo,{size:16})}),t.jsx("button",{className:"modal-close",onClick:_e,"aria-label":"Close",children:t.jsx(nn,{size:20})})]})]}),t.jsxs("div",{className:"planning-modal-body",children:[m&&t.jsx("div",{className:"form-error planning-error",children:m}),U&&t.jsx("div",{className:"form-hint text-muted",children:"Reconnecting…"}),oe&&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(ps,{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:O,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(),we())}})]}),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:vT.map((ge,Ne)=>t.jsx("button",{className:"planning-example-chip",onClick:()=>c(ge),children:ge.length>45?ge.slice(0,45)+"...":ge},Ne))})]}),t.jsxs("div",{className:"planning-model-select-group",children:[t.jsxs("label",{htmlFor:"mission-interview-modal-model",className:"form-label",children:["Planning Model",H&&t.jsx("span",{className:"text-muted text-muted-sm",children:"Loading models…"})]}),t.jsx(ys,{id:"mission-interview-modal-model",label:"Planning Model",value:fe,onChange:ge=>{const{provider:Ne,modelId:ue}=xT(ge);re(Ne),B(ue)},models:ye,disabled:H,favoriteProviders:Oe,onToggleFavorite:$e,favoriteModels:dt,onToggleModelFavorite:De}),pe&&t.jsxs("div",{className:"form-hint form-hint-error",children:[pe," ",t.jsx("button",{type:"button",className:"text-link-btn",onClick:()=>{(async()=>{try{ke(!0);const ge=await Os();Ce(ge.models),He(ge.favoriteProviders),Fe(ge.favoriteModels),Ae(null)}catch(ge){Ae(Pe(ge)||"Failed to load models")}finally{ke(!1)}})()},children:"Retry"})]}),t.jsx("div",{className:"model-selector-current model-selector-current--spaced",children:t.jsx("span",{className:`model-badge ${ne&&J?"model-badge-custom":"model-badge-default"}`,children:ot(ne,J)})})]})]}),t.jsx("div",{className:"planning-view-footer",children:t.jsxs("button",{className:"btn btn-primary planning-start-btn",onClick:()=>we(),disabled:!l.trim(),children:[t.jsx(vs,{size:16,className:"icon-mr-8"}),"Start Interview"]})})]}),d.type==="loading"&&t.jsxs("div",{className:"planning-loading",children:[t.jsx(bt,{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:()=>P(!j),type:"button",children:j?"Hide thinking":"Show thinking"}),j&&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(si,{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:R,children:[R?t.jsx(bt,{size:14,className:"spin"}):t.jsx(os,{size:14}),t.jsx("span",{className:"icon-ml-6",children:R?"Retrying...":"Retry"})]}),t.jsx("button",{className:"btn",onClick:_e,disabled:R,children:"Cancel"})]})]})]})}),d.type==="question"&&t.jsx(wT,{question:d.question,progress:xt(),historyEntries:g,onSubmit:lt}),d.type==="summary"&&w&&t.jsx(kT,{summary:w,historyEntries:g,onSummaryChange:b,onApprove:mt,onStartOver:()=>{u({type:"initial"}),S(!1),b(null),p([]),x([]),A(null),q.current?.close(),q.current=null},isCreating:F}),$&&t.jsx("div",{className:"session-lock-overlay","data-testid":"session-lock-overlay",children:t.jsxs("div",{className:"session-lock-banner",children:[t.jsx(Ql,{size:16}),t.jsx("span",{children:le?"This session is active in another tab":"This session is active in another tab (live heartbeat)"}),le&&t.jsx("button",{type:"button",onClick:()=>{N()},disabled:G,className:"btn btn-primary session-lock-take-control",children:G?"Taking control...":"Take Control"})]})})]})]})}):null}function wT({question:e,progress:n,historyEntries:s,onSubmit:a}){const[r,o]=i.useState({}),[l,c]=i.useState(""),[d,u]=i.useState(""),m=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 h=()=>{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(si,{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(),m())}}),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 x=g.target.checked?[...p,f.id]:p.filter(w=>w!==f.id);o({[e.id]:x})}}),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(Dn,{size:18}),"Yes"]}),t.jsxs("button",{className:`planning-confirm-btn ${r[e.id]===!1?"selected":""}`,onClick:()=>o({[e.id]:!1}),children:[t.jsx(nn,{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:m,disabled:!h(),children:["Continue",t.jsx(yo,{size:16,className:"icon-ml-4"})]})})]})}function kT({summary:e,historyEntries:n,onSummaryChange:s,onApprove:a,onStartOver:r,isCreating:o}){const[l,c]=i.useState(()=>new Set(e.milestones.map((k,C)=>C))),[d,u]=i.useState(()=>{const k=new Set;return e.milestones.forEach((C,v)=>{C.slices.forEach((j,P)=>k.add(`${v}-${P}`))}),k}),m=k=>{c(C=>{const v=new Set(C);return v.has(k)?v.delete(k):v.add(k),v})},h=k=>{u(C=>{const v=new Set(C);return v.has(k)?v.delete(k):v.add(k),v})},f=(k,C)=>{const v=[...e.milestones];v[k]={...v[k],...C},s({...e,milestones:v})},p=(k,C,v)=>{const j=[...e.milestones],P=[...j[k].slices];P[C]={...P[C],...v},j[k]={...j[k],slices:P},s({...e,milestones:j})},g=(k,C,v,j)=>{const P=[...e.milestones],U=[...P[k].slices],E=[...U[C].features];E[v]={...E[v],...j},U[C]={...U[C],features:E},P[k]={...P[k],slices:U},s({...e,milestones:P})},x=k=>{const C=e.milestones.filter((v,j)=>j!==k);s({...e,milestones:C})},w=(k,C)=>{const v=[...e.milestones];v[k]={...v[k],slices:v[k].slices.filter((j,P)=>P!==C)},s({...e,milestones:v})},b=(k,C,v)=>{const j=[...e.milestones],P=[...j[k].slices];P[C]={...P[C],features:P[C].features.filter((U,E)=>E!==v)},j[k]={...j[k],slices:P},s({...e,milestones:j})},y=(k,C)=>{const v=[...e.milestones],j=[...v[k].slices];j[C]={...j[C],features:[...j[C].features,{title:"New feature",description:""}]},v[k]={...v[k],slices:j},s({...e,milestones:v})},S=e.milestones.reduce((k,C)=>k+C.slices.reduce((v,j)=>v+j.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(si,{entries:n}),t.jsx("div",{className:"conversation-separator"})]}),t.jsxs("div",{className:"planning-summary-header",children:[t.jsx(Dn,{size:24,className:"icon-success"}),t.jsx("h4",{children:"Mission Plan Ready"}),t.jsxs("p",{className:"text-muted",children:[e.milestones.length," milestones, ",S," 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:k=>s({...e,missionTitle:k.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:k=>s({...e,missionDescription:k.target.value})})]}),t.jsxs("div",{className:"form-group",children:[t.jsx("label",{children:"Roadmap"}),t.jsx("div",{className:"roadmap-list",children:e.milestones.map((k,C)=>t.jsxs("div",{className:"roadmap-card",children:[t.jsxs("div",{className:"roadmap-card-header",onClick:()=>m(C),children:[l.has(C)?t.jsx(rn,{size:16,className:"icon-text-secondary"}):t.jsx(Mn,{size:16,className:"icon-text-secondary"}),t.jsx(ja,{size:16,className:"icon-milestone"}),t.jsx("input",{type:"text",className:"form-input roadmap-input-title",value:k.title,onChange:v=>f(C,{title:v.target.value}),onClick:v=>v.stopPropagation()}),e.milestones.length>1&&t.jsx("button",{className:"btn-icon roadmap-shrink",onClick:v=>{v.stopPropagation(),x(C)},title:"Remove milestone",children:t.jsx(vn,{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:k.description||"",onChange:v=>f(C,{description:v.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:k.verification||"",onChange:v=>f(C,{verification:v.target.value})})]}),k.slices.map((v,j)=>{const P=`${C}-${j}`;return t.jsxs("div",{className:"roadmap-slice-card",children:[t.jsxs("div",{className:"roadmap-slice-header",onClick:()=>h(P),children:[d.has(P)?t.jsx(rn,{size:14,className:"icon-text-secondary"}):t.jsx(Mn,{size:14,className:"icon-text-secondary"}),t.jsx(Pd,{size:14,className:"icon-slice"}),t.jsx("input",{type:"text",className:"form-input roadmap-input-subtitle",value:v.title,onChange:U=>p(C,j,{title:U.target.value}),onClick:U=>U.stopPropagation()}),k.slices.length>1&&t.jsx("button",{className:"btn-icon roadmap-shrink",onClick:U=>{U.stopPropagation(),w(C,j)},title:"Remove slice",children:t.jsx(vn,{size:12,className:"icon-text-secondary"})})]}),d.has(P)&&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:v.verification||"",onChange:U=>p(C,j,{verification:U.target.value})})]}),v.features.map((U,E)=>t.jsxs("div",{className:"roadmap-feature-row",children:[t.jsx(Sd,{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:U.title,onChange:R=>g(C,j,E,{title:R.target.value})}),U.description&&t.jsx("p",{className:"roadmap-feature-text",children:U.description}),U.acceptanceCriteria&&t.jsxs("p",{className:"roadmap-feature-text--italic",children:["AC: ",U.acceptanceCriteria]})]}),t.jsx("button",{className:"btn-icon roadmap-shrink",onClick:()=>b(C,j,E),title:"Remove feature",children:t.jsx(vn,{size:12,className:"icon-text-secondary"})})]},E)),t.jsxs("button",{className:"btn roadmap-add-feature-btn",onClick:()=>y(C,j),children:[t.jsx(gn,{size:12}),"Add Feature"]})]})]},j)})]})]},C))})]})]})]}),t.jsxs("div",{className:"planning-actions planning-summary-actions",children:[t.jsxs("button",{className:"btn",onClick:r,disabled:o,children:[t.jsx(Aa,{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(bt,{size:16,className:"spin icon-mr-8"}),"Creating Mission..."]}):t.jsxs(t.Fragment,{children:[t.jsx(Dn,{size:16,className:"icon-mr-8"}),"Approve Plan"]})})]})]})}const jT=30,NT=16,ST=16;function CT(){if(typeof window>"u")return!1;const e="ontouchstart"in window||navigator.maxTouchPoints>0,n=window.innerWidth<=768;return e&&n}let yl=null;function Ix(){return yl===null&&(yl=window.visualViewport?.height??window.innerHeight),yl}function ET(e){const n=Ix();e>n&&(yl=e)}function _T(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 Op(){if(typeof window>"u"||!window.visualViewport)return{overlap:0,open:!1,vvHeight:null,vvOffsetTop:0};const e=window.visualViewport,n=_T(document.activeElement),s=e.offsetTop;n||ET(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=Ix(),o=Math.max(0,r-e.offsetTop-e.height);if(o>=jT&&n)return{overlap:o,open:!0,vvHeight:e.height,vvOffsetTop:s};if(o>=NT&&n)return{overlap:o,open:!0,vvHeight:e.height,vvOffsetTop:s};const l=Math.max(0,r-e.height);return n&&l>=ST?{overlap:0,open:!0,vvHeight:e.height,vvOffsetTop:s}:{overlap:0,open:!1,vvHeight:null,vvOffsetTop:0}}function Wi({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||!CT()){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 m=()=>{const v=Op();s(v.overlap),r(v.vvHeight),l(v.vvOffsetTop),d(v.open)},h=()=>{const v=Op();s(v.overlap),r(v.vvHeight),d(v.open)},f=[],p=v=>{if(typeof window>"u")return;const j=window.setTimeout(()=>{typeof window>"u"||m()},v);f.push(j)};let g=null,x=0,w=-1,b=0;const y=()=>{g!==null&&typeof window<"u"&&(window.cancelAnimationFrame(g),g=null)},S=()=>{if(typeof window>"u")return;m();const v=window.visualViewport?.offsetTop??0;if(v===w?b+=1:(b=0,w=v),b>=2||performance.now()>x){g=null;return}g=window.requestAnimationFrame(S)},k=()=>{typeof window>"u"||(y(),x=performance.now()+1500,w=-1,b=0,g=window.requestAnimationFrame(S))},C=()=>{m(),p(50),p(200),p(500),p(1e3),p(1500),k()};return C(),u.addEventListener("resize",m),u.addEventListener("scroll",h),document.addEventListener("focusin",C),document.addEventListener("focusout",m),document.addEventListener("visibilitychange",C),window.addEventListener("pageshow",C),()=>{u.removeEventListener("resize",m),u.removeEventListener("scroll",h),document.removeEventListener("focusin",C),document.removeEventListener("focusout",m),document.removeEventListener("visibilitychange",C),window.removeEventListener("pageshow",C);for(const v of f)clearTimeout(v);y(),s(0),r(null),l(0),d(!1)}},[e]),{keyboardOverlap:n,viewportHeight:a,viewportOffsetTop:o,keyboardOpen:c}}function MT({isOpen:e,onClose:n,onApplied:s,targetType:a,targetId:r,targetTitle:o,missionContext:l,projectId:c,resumeSessionId:d}){const u=Ys();vi(e);const{keyboardOverlap:m,viewportHeight:h,viewportOffsetTop:f,keyboardOpen:p}=Wi({enabled:u==="mobile"}),g=p?{"--keyboard-overlap":`${m}px`,"--vv-offset-top":`${f}px`,...h!==null?{"--vv-height":`${h}px`}:{}}:{},[x,w]=i.useState({type:"initial"}),[b,y]=i.useState(null),[S,k]=i.useState([]),[C,v]=i.useState([]),[j,P]=i.useState(null),[U,E]=i.useState(""),[R,L]=i.useState(!0),[F,M]=i.useState(!1),[O,q]=i.useState(!1),te=i.useRef(null),Z=i.useRef(null),K=i.useRef(null),A=i.useRef(null),[I,$]=i.useState(null),N=i.useMemo(()=>Ia(),[]);cc(e?I:null);const{activeTabMap:G,broadcastUpdate:xe,broadcastCompleted:Se,broadcastLock:je,broadcastUnlock:se,broadcastHeartbeat:Ve}=_r(),ee=a==="milestone"?p1:v1,ce=a==="milestone"?f1:y1,ne=a==="milestone"?g1:w1,re=a==="milestone"?b1:k1,J=a==="milestone"?x1:j1,B=a==="milestone"?"Milestone":"Slice",ye=a==="milestone"?"milestone_interview":"slice_interview",Ce=i.useCallback(Be=>{Z.current?.close();const we=ne(Be,c,{onThinking:Q=>{E(_e=>_e+Q),xe({sessionId:Be,status:"generating",needsInput:!1,owningTabId:N,type:ye,title:o,projectId:c??null})},onQuestion:Q=>{M(!1),H(),w({type:"question",sessionId:Be,question:Q}),E(""),xe({sessionId:Be,status:"awaiting_input",needsInput:!0,owningTabId:N,type:ye,title:o,projectId:c??null})},onSummary:Q=>{M(!1),H(),w({type:"summary",sessionId:Be,summary:Q}),P(Q),E(""),xe({sessionId:Be,status:"complete",needsInput:!1,owningTabId:N,type:ye,title:o,projectId:c??null})},onError:Q=>{const _e=Q||"Session failed while contacting the AI.";M(!1),y(null),w({type:"error",sessionId:Be,errorMessage:_e}),E(""),K.current=Be,xe({sessionId:Be,status:"error",needsInput:!1,owningTabId:N,type:ye,title:o,projectId:c??null}),Se({sessionId:Be,status:"error"})},onComplete:()=>{M(!1),K.current=null,Se({sessionId:Be,status:"complete"})},onConnectionStateChange:Q=>{M(Q==="reconnecting")}});Z.current=we},[Se,xe,ne,ye,c,N,o]),H=()=>{P(null),k([]),v([]),E("")},ke=i.useCallback(async()=>{y(null),H(),M(!1),w({type:"loading"});try{const{sessionId:Be}=await ee(r,c);K.current=Be,$(Be),Ce(Be)}catch(Be){M(!1),y(Pe(Be)||`Failed to start ${B.toLowerCase()} interview`),w({type:"initial"}),K.current=null,$(null)}},[Ce,c,ee,r,B]),pe=i.useCallback(async()=>{y(null),q(!0);try{await J(r,c),s(),w({type:"applied"})}catch(Be){y(Pe(Be)||`Failed to skip ${B.toLowerCase()} interview`),q(!1)}},[s,c,J,r,B]);i.useEffect(()=>{e&&x.type==="initial"&&te.current?.focus()},[e,x.type]),i.useEffect(()=>{if(!e||!d||x.type!=="initial")return;let Be=!1;return Ci(d).then(we=>{if(Be||!we)return;const Q=hr(we.conversationHistory);if(v(Q),$(we.id),k(Q.map(_e=>_e.response).filter(_e=>!!(_e&&typeof _e=="object"&&!Array.isArray(_e)))),we.status==="awaiting_input"&&we.currentQuestion)try{const _e=JSON.parse(we.currentQuestion);K.current=we.id,w({type:"question",sessionId:we.id,question:_e})}catch{y("Failed to restore session question.")}else if(we.status==="complete"&&we.result)try{const _e=JSON.parse(we.result);K.current=we.id,P(_e),w({type:"summary",sessionId:we.id,summary:_e})}catch{y("Failed to restore session result.")}else we.status==="generating"?(K.current=we.id,we.thinkingOutput&&E(we.thinkingOutput),w({type:"loading"}),Ce(we.id)):we.status==="error"&&(K.current=we.id,y(null),w({type:"error",sessionId:we.id,errorMessage:we.error??"The session encountered an error."}))}).catch(()=>{Be||y("Failed to resume session.")}),()=>{Be=!0}},[Ce,e,d,x.type]),i.useEffect(()=>{e||(M(!1),$(null))},[e]),i.useEffect(()=>{if(!(!e||!I)){if(A.current!==I){A.current&&se(A.current,N),je(I,N),A.current=I;return}!I&&A.current&&(se(A.current,N),A.current=null)}},[je,se,e,I,N]),i.useEffect(()=>{if(!e||!I||A.current!==I)return;Ve(N);const Be=setInterval(()=>{Ve(N)},3e4);return()=>{clearInterval(Be)}},[Ve,e,I,N]),i.useEffect(()=>()=>{Z.current?.close(),Z.current=null,A.current&&(se(A.current,N),A.current=null)},[se,N]);const Ae=i.useCallback(()=>{Z.current?.close(),Z.current=null,n()},[n]),Oe=i.useCallback(async()=>{Z.current?.close(),Z.current=null,H(),w({type:"initial"}),y(null),K.current=null,$(null),n()},[n]),He=i.useCallback(async Be=>{if(x.type!=="question")return;const{sessionId:we}=x;y(null),k(Q=>[...Q,Be]),v(Q=>[...Q,{question:x.question,response:Be}]),w({type:"loading"}),E("");try{Ce(we),await ce(we,Be,c,N)}catch(Q){Z.current?.close(),Z.current=null,y(Pe(Q)||"Failed to submit response"),w({type:"question",sessionId:we,question:x.question})}},[Ce,c,ce,N,x]),dt=i.useCallback(async()=>{if(x.type==="summary"){y(null),q(!0);try{await re(x.sessionId,j||void 0,c),s(),w({type:"applied"})}catch(Be){y(Pe(Be)||"Failed to apply interview results"),q(!1)}}},[re,j,s,c,x]),Fe=()=>x.type==="question"?Math.min(S.length+1,6):6,fe=x.type==="loading"||x.type==="question"||x.type==="summary"||x.type==="error",$e=I?G.get(I):null,ot=!!($e&&$e.tabId!==N&&!$e.stale);return e?t.jsx("div",{className:"modal-overlay open",onClick:Be=>Be.target===Be.currentTarget&&Oe(),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(ps,{size:20,className:"icon-triage"}),t.jsxs("h3",{children:["Plan ",B,": ",o]})]}),t.jsxs("div",{className:"modal-header-actions",children:[fe&&t.jsx("button",{className:"modal-send-to-background",onClick:Ae,title:"Send to background","aria-label":"Send to background",children:t.jsx(jo,{size:16})}),t.jsx("button",{className:"modal-close",onClick:Oe,"aria-label":"Close",children:t.jsx(nn,{size:20})})]})]}),t.jsxs("div",{className:"planning-modal-body",children:[b&&t.jsx("div",{className:"form-error planning-error",children:b}),F&&t.jsx("div",{className:"form-hint text-muted",children:"Reconnecting…"}),ot&&t.jsx("div",{className:"form-hint text-muted","data-testid":"session-active-another-tab-banner",children:"Session is active in another tab."}),x.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(ps,{size:32,className:"icon-triage-lg"}),t.jsxs("h4",{children:["Refine ",B," 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 ke(),children:[t.jsx(ps,{size:16,className:"icon-mr-8"}),"Start Interview"]}),t.jsxs("button",{className:"btn planning-use-context-btn",onClick:()=>void pe(),disabled:O,children:[O?t.jsx(bt,{size:16,className:"spin"}):null,"Use Mission Context"]}),t.jsx("button",{className:"btn",onClick:Oe,children:"Cancel"})]})]}),x.type==="loading"&&t.jsxs("div",{className:"planning-loading",children:[t.jsx(bt,{size:40,className:"spin icon-todo"}),t.jsx("p",{children:U?"AI is thinking...":"Preparing next question..."}),t.jsxs("div",{className:"planning-thinking-container",children:[t.jsx("button",{className:"planning-thinking-toggle",onClick:()=>L(!R),type:"button",children:R?"Hide thinking":"Show thinking"}),R&&U&&t.jsx("div",{className:"planning-thinking-output",children:t.jsx("pre",{children:U})})]})]}),x.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(si,{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:x.errorMessage}),t.jsx("div",{className:"ai-error-actions",children:t.jsx("button",{className:"btn",onClick:Oe,children:"Cancel"})})]})]})}),x.type==="question"&&t.jsx(AT,{question:x.question,progress:Fe(),historyEntries:C,onSubmit:He}),x.type==="summary"&&j&&t.jsx(PT,{summary:j,historyEntries:C,onSummaryChange:P,onApply:dt,onCancel:Oe,isApplying:O}),x.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(Dn,{size:48,className:"icon-success"}),t.jsxs("h4",{children:[B," Updated"]}),t.jsxs("p",{className:"text-muted",children:["The ",a,"'s scope and verification have been ",x.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 AT({question:e,progress:n,historyEntries:s,onSubmit:a}){const[r,o]=i.useState({}),[l,c]=i.useState(""),[d,u]=i.useState(""),m=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 h=()=>{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(si,{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(),m())}}),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 x=g.target.checked?[...p,f.id]:p.filter(w=>w!==f.id);o({[e.id]:x})}}),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(Dn,{size:18}),"Yes"]}),t.jsxs("button",{className:`planning-confirm-btn ${r[e.id]===!1?"selected":""}`,onClick:()=>o({[e.id]:!1}),children:[t.jsx(nn,{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:m,disabled:!h(),children:["Continue",t.jsx(yo,{size:16,className:"icon-ml-4"})]})})]})}function PT({summary:e,historyEntries:n,onSummaryChange:s,onApply:a,onCancel:r,isApplying:o}){const[l,c]=i.useState(e),[d,u]=i.useState(!0),m=(h,f)=>{const p={...l,[h]: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(si,{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(rn,{size:16}):t.jsx(Mn,{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:h=>m("description",h.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:h=>m("planningNotes",h.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:h=>m("verification",h.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(bt,{size:16,className:"spin"}):null,"Apply"]}),t.jsx("button",{className:"btn",onClick:r,disabled:o,children:"Cancel"})]})]})}const zp=300,tl=220,nl=560,Fp="fusion:mission-sidebar-width",Fr={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)"}},Up={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)"}},Bp={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)"}},sl={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)"}},il={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)"}},Hp={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)"}},RT=3;function IT(e){return e==="completed"?"planned":e==="needs_update"?"needs_update":"not_started"}function qp({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 Vp(e){return e?e.replace(/_/g," ").replace(/^\w/,n=>n.toUpperCase()):"Not started"}const Wp={title:"",description:"",status:"planning",autopilotEnabled:!1},nd={title:"",description:"",status:"planning",dependencies:[]},sd={title:"",description:"",status:"pending"},id={title:"",description:"",acceptanceCriteria:"",status:"defined"},TT=3600*1e3;function Ol(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 $T(e){if(!e)return"healthy";const n=typeof e.lastErrorAt=="string"&&Date.now()-new Date(e.lastErrorAt).getTime()<=TT,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 DT(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 LT(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 ad(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 Tx=["feature_triaged","feature_completed"],$x=["slice_activated","slice_completed","milestone_completed"],Dx=["mission_started","mission_paused","mission_resumed","mission_completed"],Lx=["autopilot_enabled","autopilot_disabled","autopilot_state_changed","autopilot_retry","autopilot_stale"];function Kp(e,n){switch(n){case"errors":return e==="error"||e==="warning";case"state_changes":return Dx.includes(e);case"tasks":return Tx.includes(e);case"slices":return $x.includes(e);case"autopilot":return Lx.includes(e);default:return!0}}function OT(e){return e==="error"||e==="warning"?"mission-event__type--error":Dx.includes(e)?"mission-event__type--state":Tx.includes(e)?"mission-event__type--task":$x.includes(e)?"mission-event__type--slice":Lx.includes(e)?"mission-event__type--autopilot":"mission-event__type--default"}function zT(e){return e.replace(/_/g," ")}function FT(e,n){return n?e==="watching"?`Watching since ${Ol(n)}`:`Last activation ${Ol(n)}`:null}function UT({isOpen:e,isInline:n=!1,onClose:s,addToast:a,projectId:r,onSelectTask:o,availableTasks:l=[],resumeSessionId:c,targetMissionId:d,milestoneSliceResumeSessionId:u,onMilestoneSliceResumeFetchError:m}){const h=n||e,[f,p]=i.useState([]),[g,x]=i.useState(null),[w,b]=i.useState(!0),[y,S]=i.useState(!1),k=Ys()==="mobile",[C,v]=i.useState(()=>{if(typeof window>"u")return zp;const V=window.localStorage.getItem(Fp),Re=V?Number(V):NaN;return Number.isFinite(Re)?Math.max(tl,Math.min(nl,Re)):zp}),j=i.useCallback(V=>{try{window.localStorage.setItem(Fp,String(V))}catch{}},[]),P=i.useCallback(V=>{if(k)return;V.preventDefault(),V.stopPropagation();const Re=V.currentTarget;typeof Re.setPointerCapture=="function"&&Re.setPointerCapture(V.pointerId);const z=V.clientX,he=C;let Qe=he;document.body.style.userSelect="none";const ft=Xe=>{const nt=Xe.clientX-z,Ot=Math.max(tl,Math.min(nl,he+nt));Qe=Ot,v(Ot)},qt=Xe=>{typeof Re.releasePointerCapture=="function"&&Re.releasePointerCapture(Xe.pointerId),document.body.style.userSelect="",document.removeEventListener("pointermove",ft),document.removeEventListener("pointerup",qt),j(Qe)};document.addEventListener("pointermove",ft),document.addEventListener("pointerup",qt)},[k,j,C]),U=i.useCallback(V=>{if(k||V.key!=="ArrowLeft"&&V.key!=="ArrowRight")return;V.preventDefault();const Re=V.shiftKey?50:10,z=V.key==="ArrowLeft"?-Re:Re,he=Math.max(tl,Math.min(nl,C+z));v(he),j(he)},[k,j,C]),[E,R]=i.useState(!1),[L,F]=i.useState(null),[M,O]=i.useState(Wp),[q,te]=i.useState(!1),[Z,K]=i.useState(new Set),[A,I]=i.useState(new Set),[$,N]=i.useState(null),[G,xe]=i.useState(nd),[Se,je]=i.useState(!1),[se,Ve]=i.useState(null),[ee,ce]=i.useState(sd),[ne,re]=i.useState(!1),[J,B]=i.useState(null),[ye,Ce]=i.useState(null),[H,ke]=i.useState(id),[pe,Ae]=i.useState(!1),[Oe,He]=i.useState(null),[dt,Fe]=i.useState(null),[fe,$e]=i.useState(""),[De,ot]=i.useState(!1),[Be,we]=i.useState([]),[Q,_e]=i.useState(void 0),lt=Q??c,[ht,mt]=i.useState(null),[xt,Ie]=i.useState(null),[Ue,pt]=i.useState(null);i.useEffect(()=>{h&&lt&&ot(!0)},[h,lt]),i.useEffect(()=>{if(!h||lt)return;let V=!1;return xu(r).then(Re=>{if(V)return;const z=Re.filter(he=>he.type==="mission_interview"&&(he.status==="awaiting_input"||he.status==="error"));we(z)}).catch(Re=>{console.warn("[MissionManager] Failed to fetch pending interview sessions:",Re)}),()=>{V=!0}},[h,r,lt]),i.useEffect(()=>{if(!h||!u)return;let V=!1;return Ci(u).then(Re=>{if(!(V||!Re))try{const z=JSON.parse(Re.inputPayload||"{}");z.targetId&&z.targetType&&mt({type:z.targetType,id:z.targetId,title:z.targetTitle||Re.title,resumeSessionId:u})}catch{mt({type:"milestone",id:"",title:Re.title,resumeSessionId:u})}}).catch(Re=>{V||(console.warn("[MissionManager] Failed to fetch session for milestone/slice resume:",Re),m?.())}),()=>{V=!0}},[h,u,m]);const[oe,le]=i.useState(null),[ge,Ne]=i.useState(new Map),[ue,qe]=i.useState(null),[me,tt]=i.useState({title:"",assertion:"",status:"pending"}),[Ct,wt]=i.useState(!1),[$t,Vt]=i.useState(null),[Mt,Dt]=i.useState(new Map),[Qt,Kt]=i.useState(new Set),[Bt,on]=i.useState(new Set),[fn,Jt]=i.useState(null),[an,zt]=i.useState(new Map),[en,Zt]=i.useState(null),[dn,ve]=i.useState(null),[ze,We]=i.useState(!0),[Ze,Ye]=i.useState(new Set),[It,St]=i.useState(new Map),[Ht,jt]=i.useState(null),[ae,Le]=i.useState(new Map),[At,Lt]=i.useState(null),[Ft,Me]=i.useState(new Map),[ct,gt]=i.useState(new Map),[_t,Yt]=i.useState("structure"),[Xt,Te]=i.useState([]),Je=i.useRef([]),Nt=i.useRef([]),Ut=i.useRef(null),tn=i.useRef(null),Xn=i.useRef("structure"),be=i.useRef("all"),[it,rt]=i.useState(!1),[at,ut]=i.useState(0),[vt,ie]=i.useState("all"),[st,Gt]=i.useState(new Set),Cn=i.useRef(null),fs=i.useRef(null);Nt.current=f,Ut.current=g,tn.current=en,Xn.current=_t,be.current=vt;const On=i.useCallback((V="auto")=>{const Re=fs.current;if(Re&&typeof Re.scrollIntoView=="function"){Re.scrollIntoView({block:"end",behavior:V});return}const z=Cn.current;z&&(z.scrollTop=z.scrollHeight)},[]),jn=i.useCallback(()=>{const V=Cn.current;return V?V.scrollHeight-V.scrollTop-V.clientHeight<=100:!0},[]),zn=i.useCallback(async V=>{if(V.length===0){gt(new Map);return}const Re=await DS(r);gt(z=>{const he=new Map(z);for(const[Qe,ft]of Object.entries(Re))DT(ft)&&he.set(Qe,ft);return he})},[r]),hn=i.useCallback(async()=>{try{b(!0);const V=await PS(r);p(V),zn(V)}catch(V){a(Pe(V)||"Failed to load missions","error")}finally{b(!1)}},[a,r,zn]),Et=i.useCallback(async V=>{try{S(!0);const Re=await Fg(V,r);if(!Re||!Array.isArray(Re.milestones)){S(!1);return}if(x(Re),Re.milestones.length>0){const z=Re.milestones[0].id;Zt(z),We(!0),K(new Set([z])),fc(z,r).then(he=>{Ne(Qe=>{const ft=new Map(Qe);return ft.set(z,he),ft})}).catch(()=>{}),gc(z,r).then(he=>{zt(Qe=>{const ft=new Map(Qe);return ft.set(z,he),ft})}).catch(()=>{}),Re.milestones[0].slices.length>0&&I(new Set([Re.milestones[0].slices[0].id]))}else Zt(null),ve(null)}catch(Re){a(Pe(Re)||"Failed to load mission details","error")}finally{S(!1)}},[a,r]);i.useEffect(()=>{if(!h||!en){ve(null);return}let V=!1;return ve(null),Cm(en,r).then(Re=>{if(!V){if(!ad(Re)){ve(null);return}ve(Re),zt(z=>{const he=new Map(z);return he.set(en,Re.rollup),he})}}).catch(()=>{V||ve(null)}),()=>{V=!0}},[h,en,r]),i.useEffect(()=>{We(!0)},[en]);const En=i.useCallback(V=>{!V||V!==tn.current||Cm(V,r).then(Re=>{tn.current!==V||!ad(Re)||(ve(Re),zt(z=>{const he=new Map(z);return he.set(V,Re.rollup),he}))}).catch(()=>{})},[r]),yn=i.useCallback(async(V,Re)=>{const z=Re?.append??!1,he=z?Je.current.length:0;z||(rt(!0),Gt(new Set));try{const Qe=await $S(V,{limit:50,offset:he,eventType:void 0},r),ft=Qe.events.filter(qt=>Kp(qt.eventType,vt));Te(qt=>{if(!z)return Je.current=ft,ft;const Xe=new Set(qt.map(Ot=>Ot.id)),nt=[...qt];for(const Ot of ft)Xe.has(Ot.id)||nt.push(Ot);return Je.current=nt,nt}),ut(Qe.total),z||requestAnimationFrame(()=>{On("auto")})}catch(Qe){a(Pe(Qe)||"Failed to load mission activity","error")}finally{z||rt(!1)}},[a,vt,r,On]);i.useEffect(()=>{Je.current=Xt},[Xt]),i.useEffect(()=>{h&&(hn(),x(null),Zt(null),ve(null),Te([]),ut(0),Yt("structure"),ie("all"),Gt(new Set))},[h,hn]);const ls=i.useRef(null);i.useEffect(()=>{h&&d&&ls.current!==d&&f.length>0&&(ls.current=d,Et(d))},[h,d,f,Et]),i.useEffect(()=>{h||(ls.current=null)},[h]);const cs=i.useRef(!1);i.useEffect(()=>{!h||!n||k||w||cs.current||g||d||f.length!==0&&(cs.current=!0,Et(f[0].id))},[h,n,k,w,f,g,d,Et]),i.useEffect(()=>{h||(cs.current=!1)},[h]),i.useEffect(()=>{!h||!g||_t!=="activity"||yn(g.id)},[_t,h,yn,g,vt]),i.useEffect(()=>{if(!h||typeof EventSource>"u")return;const V=new URLSearchParams;r&&V.set("projectId",r);const Re=`/api/events${V.size>0?`?${V.toString()}`:""}`,z=()=>{zn(Nt.current)},he=rs=>{z();const Jn=rs;if(Jn.data)try{const un=JSON.parse(Jn.data);un?.id&&p(Di=>Di.map(Es=>Es.id===un.id?{...Es,...un}:Es))}catch{}Ut.current&&Et(Ut.current.id)},Qe=rs=>{z(),Ut.current&&Et(Ut.current.id)},ft=()=>{z(),Ut.current&&Et(Ut.current.id)},qt=rs=>{z(),Ut.current&&Et(Ut.current.id)},Xe=rs=>{const Jn=rs;if(Jn.data)try{const un=JSON.parse(Jn.data);un&&un.featureId&&(Qs(un.featureId),oi(un.featureId),un.milestoneId&&En(un.milestoneId))}catch{}},nt=rs=>{const Jn=rs;if(Jn.data)try{const un=JSON.parse(Jn.data);un&&un.featureId&&(Qs(un.featureId),oi(un.featureId),un.milestoneId&&En(un.milestoneId),Ut.current&&Et(Ut.current.id))}catch{}},Ot=rs=>{const Jn=rs;if(Jn.data)try{const un=JSON.parse(Jn.data);un&&un.milestoneId&&(Kn(un.milestoneId),En(un.milestoneId))}catch{}},bn=rs=>{const Jn=rs;if(Jn.data)try{const un=JSON.parse(Jn.data);un&&un.milestoneId&&(Wn(un.milestoneId),Kn(un.milestoneId),En(un.milestoneId))}catch{}};return ii(Re,{events:{"mission:updated":he,"slice:updated":Qe,"feature:updated":ft,"milestone:updated":qt,"mission:event":rs=>{z();const Jn=Ut.current;if(!Jn||Xn.current!=="activity")return;const un=jn(),Di=rs;if(Di.data)try{const Es=JSON.parse(Di.data);if(!LT(Es)||Es.missionId!==Jn.id||!Kp(Es.eventType,be.current))return;Te(qs=>{const Ji=qs.filter(fa=>fa.id!==Es.id);return[Es,...Ji].slice(0,100)}),ut(qs=>qs+1),un&&requestAnimationFrame(()=>{const qs=Cn.current;qs&&(qs.scrollTop=0)})}catch{}},"validator-run:started":Xe,"validator-run:completed":nt,"milestone:validation:updated":Ot,"assertion:created":bn,"assertion:updated":bn,"assertion:deleted":bn,"assertion:linked":bn,"assertion:unlinked":bn,"fix-feature:created":rs=>{const Jn=rs;if(Jn.data)try{const un=JSON.parse(Jn.data);if(un&&un.sourceFeatureId){Qs(un.sourceFeatureId);const Di=un?.feature?.sliceId,Es=Ut.current;if(Di&&Es){const qs=Es.milestones.find(Ji=>Ji.slices.some(fa=>fa.id===Di));qs&&En(qs.id)}Ut.current&&Et(Ut.current.id)}}catch{}}}})},[h,jn,Et,zn,r,En]);const Hn=i.useCallback(V=>{F(V.id),R(!1),O({title:V.title,description:V.description||"",status:V.status,autopilotEnabled:V.autopilotEnabled??!1})},[]),qn=i.useCallback(()=>{F(null),R(!1),O(Wp)},[]),wn=i.useCallback(async()=>{if(!M.title.trim()){a("Mission title is required","error");return}try{if(te(!0),E)await RS({title:M.title.trim(),description:M.description.trim()||void 0,autopilotEnabled:M.autopilotEnabled},r),a("Mission created","success");else if(L){const V={title:M.title.trim(),description:M.description.trim()||void 0,status:M.status,autopilotEnabled:M.autopilotEnabled};M.autopilotEnabled&&(V.autoAdvance=!0),await IS(L,V,r),a("Mission updated","success"),g?.id===L&&await Et(L)}await hn(),qn()}catch(V){a(Pe(V)||"Failed to save mission","error")}finally{te(!1)}},[M,E,L,a,hn,Et,g,qn,r]),Zn=i.useCallback(async V=>{try{await TS(V,r),a("Mission deleted","success"),g?.id===V&&x(null),await hn(),le(null)}catch(Re){a(Pe(Re)||"Failed to delete mission","error")}},[a,hn,g,r]),_n=i.useCallback(()=>{je(!0),N(null),xe(nd)},[]),is=i.useCallback(V=>{N(V.id),je(!1),xe({title:V.title,description:V.description||"",status:V.status,dependencies:V.dependencies})},[]),Ns=i.useCallback(()=>{N(null),je(!1),xe(nd)},[]),es=i.useCallback(async()=>{if(!G.title.trim()){a("Milestone title is required","error");return}try{te(!0),Se&&g?(await LS(g.id,{title:G.title.trim(),description:G.description.trim()||void 0,dependencies:G.dependencies},r),a("Milestone created","success")):$&&(await OS($,{title:G.title.trim(),description:G.description.trim()||void 0,status:G.status,dependencies:G.dependencies},r),a("Milestone updated","success")),await Et(g.id),Ns()}catch(V){a(Pe(V)||"Failed to save milestone","error")}finally{te(!1)}},[G,Se,$,g,a,Et,Ns,M.title,r]),ks=i.useCallback(async V=>{try{await zS(V,r),a("Milestone deleted","success"),await Et(g.id),le(null)}catch(Re){a(Pe(Re)||"Failed to delete milestone","error")}},[a,Et,g,r]),Is=i.useCallback(V=>{Zt(V),We(!0),K(Re=>{const z=new Set(Re);return!z.has(V)?(z.add(V),fc(V,r).then(Qe=>{Ne(ft=>{const qt=new Map(ft);return qt.set(V,Qe),qt})}).catch(()=>{}),gc(V,r).then(Qe=>{zt(ft=>{const qt=new Map(ft);return qt.set(V,Qe),qt})}).catch(()=>{})):z.delete(V),z})},[r]),Ss=i.useCallback(V=>{B(V),re(!0),Ve(null),ce(sd)},[]),X=i.useCallback(V=>{Ve(V.id),re(!1),ce({title:V.title,description:V.description||"",status:V.status})},[]),_=i.useCallback(()=>{Ve(null),re(!1),B(null),ce(sd)},[]),de=i.useCallback(async()=>{if(!ee.title.trim()){a("Slice title is required","error");return}try{te(!0),ne&&J?(await FS(J,{title:ee.title.trim(),description:ee.description.trim()||void 0},r),a("Slice created","success")):se&&(await US(se,{title:ee.title.trim(),description:ee.description.trim()||void 0,status:ee.status},r),a("Slice updated","success")),await Et(g.id),_()}catch(V){a(Pe(V)||"Failed to save slice","error")}finally{te(!1)}},[ee,ne,se,J,g,a,Et,_,r]),D=i.useCallback(async V=>{try{await BS(V,r),a("Slice deleted","success"),await Et(g.id),le(null)}catch(Re){a(Pe(Re)||"Failed to delete slice","error")}},[a,Et,g,r]),Y=i.useCallback(async V=>{try{await HS(V,r),a("Slice activated","success"),await Et(g.id)}catch(Re){a(Pe(Re)||"Failed to activate slice","error")}},[a,Et,g,r]),Ee=i.useCallback(V=>{I(Re=>{const z=new Set(Re);return z.has(V)?z.delete(V):z.add(V),z})},[]),Ge=i.useCallback(V=>{He(V),Ae(!0),Ce(null),ke(id)},[]),kt=i.useCallback(V=>{Ce(V.id),Ae(!1),ke({title:V.title,description:V.description||"",acceptanceCriteria:V.acceptanceCriteria||"",status:V.status})},[]),Tt=i.useCallback(()=>{Ce(null),Ae(!1),He(null),ke(id)},[]),Pt=i.useCallback(async()=>{if(!H.title.trim()){a("Feature title is required","error");return}try{te(!0),pe&&Oe?(await qS(Oe,{title:H.title.trim(),description:H.description.trim()||void 0,acceptanceCriteria:H.acceptanceCriteria.trim()||void 0},r),a("Feature created","success")):ye&&(await VS(ye,{title:H.title.trim(),description:H.description.trim()||void 0,acceptanceCriteria:H.acceptanceCriteria.trim()||void 0,status:H.status},r),a("Feature updated","success")),await Et(g.id),Tt()}catch(V){a(Pe(V)||"Failed to save feature","error")}finally{te(!1)}},[H,pe,ye,Oe,g,a,Et,Tt,r]),ln=i.useCallback(async V=>{try{await WS(V,r),a("Feature deleted","success"),await Et(g.id),le(null)}catch(Re){a(Pe(Re)||"Failed to delete feature","error")}},[a,Et,g,r]),ts=i.useCallback(async()=>{if(!dt||!fe.trim()){a("Task ID is required","error");return}try{await KS(dt,fe.trim(),r),a("Feature linked to task","success"),await Et(g.id),Fe(null),$e("")}catch(V){a(Pe(V)||"Failed to link feature to task","error")}},[dt,fe,a,Et,g,r]),Rn=i.useCallback(async V=>{try{await GS(V,r),a("Feature unlinked from task","success"),await Et(g.id)}catch(Re){a(Pe(Re)||"Failed to unlink feature","error")}},[a,Et,g,r]),Fn=i.useCallback(async V=>{try{te(!0),await JS(V,void 0,void 0,r),a("Feature triaged — task created","success"),await Et(g.id)}catch(Re){a(Pe(Re)||"Failed to triage feature","error")}finally{te(!1)}},[a,Et,g,r]),Un=i.useCallback(async V=>{pt(V);try{const Re=await N1(V,r);Ie({featureId:V,enrichedDescription:Re.description})}catch{await Fn(V)}finally{pt(null)}},[Fn,r]),gs=i.useCallback(async()=>{xt&&(Ie(null),await Fn(xt.featureId))},[Fn,xt]),Ln=i.useCallback(()=>{Ie(null)},[]),Vn=i.useCallback(async V=>{try{te(!0);const Re=await YS(V,r);a(`Triaged ${Re.count} feature${Re.count!==1?"s":""}`,"success"),await Et(g.id)}catch(Re){a(Pe(Re)||"Failed to triage slice features","error")}finally{te(!1)}},[a,Et,g,r]),Wn=i.useCallback(async V=>{try{const Re=await fc(V,r);Ne(z=>{const he=new Map(z);return he.set(V,Re),he})}catch{}},[r]),Kn=i.useCallback(async V=>{try{const Re=await gc(V,r);zt(z=>{const he=new Map(z);return he.set(V,Re),he})}catch{}},[r]),Bn=i.useCallback(async V=>{if(!me.title.trim()||!me.assertion.trim()){a("Title and assertion text are required","error");return}try{te(!0),await QS(V,{title:me.title.trim(),assertion:me.assertion.trim(),status:me.status},r),a("Assertion created","success"),await Wn(V),await Kn(V),wt(!1),tt({title:"",assertion:"",status:"pending"})}catch(Re){a(Pe(Re)||"Failed to create assertion","error")}finally{te(!1)}},[me,a,Wn,Kn,r]),Nn=i.useCallback(V=>{qe(V.id),tt({title:V.title,assertion:V.assertion,status:V.status})},[]),Gn=i.useCallback(()=>{qe(null),wt(!1),tt({title:"",assertion:"",status:"pending"})},[]),ds=i.useCallback(async(V,Re)=>{if(!me.title.trim()||!me.assertion.trim()){a("Title and assertion text are required","error");return}try{te(!0),await XS(V,{title:me.title.trim(),assertion:me.assertion.trim(),status:me.status},r),a("Assertion updated","success"),await Wn(Re),await Kn(Re),Gn()}catch(z){a(Pe(z)||"Failed to update assertion","error")}finally{te(!1)}},[me,a,Wn,Kn,Gn,r]),Ts=i.useCallback(async V=>{try{const Re=await t1(V,r);Dt(z=>{const he=new Map(z);return he.set(V,Re),he})}catch{}},[r]),Ri=i.useCallback(async V=>{const Re=$t!==V;Vt(z=>z===V?null:V),Re&&await Ts(V)},[$t,Ts]),ca=i.useCallback(V=>{Vt(V),Ts(V),requestAnimationFrame(()=>{const Re=document.querySelector(`[data-mission-assertion-id="${V}"]`);Re instanceof HTMLElement&&typeof Re.scrollIntoView=="function"&&Re.scrollIntoView({behavior:"smooth",block:"center"})})},[Ts]),ri=i.useCallback(async(V,Re)=>{try{Kt(z=>new Set(z).add(Re)),await ZS(V,Re,r),a("Feature linked to assertion","success"),await Ts(Re),Jt(null)}catch(z){a(Pe(z)||"Failed to link feature","error")}finally{Kt(z=>{const he=new Set(z);return he.delete(Re),he})}},[a,Ts,r]),Ta=i.useCallback(async(V,Re)=>{const z=`${V}-${Re}`;try{on(he=>new Set(he).add(z)),await e1(V,Re,r),a("Feature unlinked from assertion","success"),await Ts(Re)}catch(he){a(Pe(he)||"Failed to unlink feature","error")}finally{on(he=>{const Qe=new Set(he);return Qe.delete(z),Qe})}},[a,Ts,r]),$a=i.useCallback(async V=>{try{Ye(z=>new Set(z).add(V)),await n1(V,r),a("Validation triggered","success");const Re=await Em(V,r);St(z=>{const he=new Map(z);return he.set(V,Re),he})}catch(Re){a(Pe(Re)||"Failed to trigger validation","error")}finally{Ye(Re=>{const z=new Set(Re);return z.delete(V),z})}},[a,r]),Qs=i.useCallback(async V=>{try{const Re=await Em(V,r);St(z=>{const he=new Map(z);return he.set(V,Re),he})}catch{}},[r]),oi=i.useCallback(async V=>{try{const Re=await s1(V,{limit:10},r);Le(z=>{const he=new Map(z);return he.set(V,Re),he})}catch{}},[r]),Ii=i.useCallback(V=>{const Re=Ut.current;if(Re){for(const z of Re.milestones)for(const he of z.slices)if(he.features.find(ft=>ft.id===V)){K(ft=>{const qt=new Set(ft);return qt.add(z.id),qt}),I(ft=>{const qt=new Set(ft);return qt.add(he.id),qt}),jt(V),Zt(z.id),Qs(V),oi(V),requestAnimationFrame(()=>{const ft=document.querySelector(`[data-mission-feature-id="${V}"]`);ft instanceof HTMLElement&&typeof ft.scrollIntoView=="function"&&ft.scrollIntoView({behavior:"smooth",block:"center"})});return}}},[Qs,oi]),da=i.useCallback(async V=>{try{const Re=await i1(V,r);Me(z=>{const he=new Map(z);return he.set(V,Re),he})}catch{}},[r]),Da=i.useCallback(async V=>{Ht===V?jt(null):(jt(V),await Qs(V),await oi(V))},[Ht,Qs,oi]),La=i.useCallback(async V=>{At===V?Lt(null):(Lt(V),await da(V))},[At,da]),ua=i.useCallback(async V=>{try{await a1(V,r),a("Mission resumed","success"),await Et(V),hn()}catch(Re){a(Pe(Re)||"Failed to resume mission","error")}},[a,Et,hn,r]),ma=i.useCallback(async V=>{try{const z=(await r1(V,r)).pausedTaskIds?.length??0;a(`Mission stopped (${z} task${z!==1?"s":""} paused)`,"success"),await Et(V),hn()}catch(Re){a(Pe(Re)||"Failed to stop mission","error")}},[a,Et,hn,r]),Ti=i.useCallback(async V=>{try{await o1(V,r),a("Mission started — first slice activated","success"),await Et(V),hn()}catch(Re){a(Pe(Re)||"Failed to start mission","error")}},[a,Et,hn,r]),Oa=i.useCallback(async(V,Re)=>{try{await l1(V,{enabled:Re},r),a(Re?"Autopilot enabled":"Autopilot disabled","success"),await Et(V),hn()}catch(z){a(Pe(z)||"Failed to update autopilot","error")}},[a,Et,hn,r]),ha=i.useCallback(V=>{Yt("structure"),Zt(null),ve(null),Te([]),ut(0),ie("all"),Gt(new Set),Et(V.id)},[Et]),Mr=i.useCallback(()=>{x(null),Zt(null),ve(null),Yt("structure"),Te([]),ut(0),ie("all"),Gt(new Set),hn()},[hn]),li=Xt.length<at,Hs=g?.autopilotState??"inactive",za=Hs==="watching"||Hs==="activating",Fa=FT(Hs,g?.lastAutopilotActivityAt),$i=i.useMemo(()=>!dn||!en||!ad(dn)?null:dn.rollup.milestoneId===en?dn:null,[en,dn]),Ua=i.useMemo(()=>{const V=new Map;for(const Re of $i?.validationTelemetry.validationRounds??[]){const z=V.get(Re.featureId);(!z||Re.startedAt>z.startedAt)&&V.set(Re.featureId,Re)}return V},[$i]),Ba=i.useCallback(()=>{!g||it||!li||yn(g.id,{append:!0})},[it,li,yn,g]),Ha=i.useCallback(V=>{Gt(Re=>{const z=new Set(Re);return z.has(V)?z.delete(V):z.add(V),z})},[]),yi=i.useCallback(V=>{V.key==="Enter"&&!V.shiftKey&&(V.preventDefault(),wn())},[wn]),pa=i.useCallback(V=>{V.key==="Enter"&&!V.shiftKey&&(V.preventDefault(),es())},[es]),us=i.useCallback(V=>{V.key==="Enter"&&!V.shiftKey&&(V.preventDefault(),de())},[de]),Ki=i.useCallback(V=>{V.key==="Enter"&&!V.shiftKey&&(V.preventDefault(),Pt())},[Pt]),Cs=i.useRef(null);if(i.useEffect(()=>{if(!h)return;const V=Re=>{Re.key==="Escape"&&s()};return document.addEventListener("keydown",V),()=>document.removeEventListener("keydown",V)},[h,s]),!h)return null;const Gi=()=>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:(Fr[g.status]||Fr.planning).bg,color:(Fr[g.status]||Fr.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:V=>Oa(g.id,V.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(Qn,{size:14,className:"mission-detail__autopilot-icon"}),"Autopilot"]})]}),t.jsxs("span",{className:"mission-status-badge mission-status-badge--sm",style:{backgroundColor:(il[Hs]||il.inactive).bg,color:(il[Hs]||il.inactive).text},"data-testid":"autopilot-state-badge",children:[za&&t.jsx("span",{className:"mission-detail__autopilot-pulse"}),Hs]})]}),Fa&&t.jsx("span",{className:"mission-detail__autopilot-activity mission-relative-time",children:Fa})]}),t.jsxs("div",{className:"mission-detail__actions",children:[g.status==="active"&&t.jsx("button",{className:"mission-icon-btn mission-icon-btn--danger",onClick:()=>ma(g.id),title:"Stop mission","aria-label":"Stop mission",children:t.jsx(Si,{size:14})}),g.status==="blocked"&&t.jsx("button",{className:"mission-icon-btn mission-icon-btn--success",onClick:()=>ua(g.id),title:"Resume mission","aria-label":"Resume mission",children:t.jsx(Yn,{size:14})}),g.status==="planning"&&t.jsx("button",{className:"mission-icon-btn mission-icon-btn--success",onClick:()=>Ti(g.id),title:"Start mission","aria-label":"Start mission",children:t.jsx(Yn,{size:14})}),t.jsx("button",{className:"mission-icon-btn",onClick:()=>Hn(g),title:"Edit mission","aria-label":"Edit mission",children:t.jsx(Ds,{size:14})}),t.jsx("button",{className:"mission-icon-btn mission-icon-btn--danger",onClick:()=>le({type:"mission",id:g.id}),title:"Delete mission","aria-label":"Delete mission",children:t.jsx(vn,{size:14})})]})]}),L===g.id&&t.jsxs("div",{className:"mission-form-card",children:[t.jsx("input",{type:"text",placeholder:"Mission title",value:M.title,onChange:V=>O({...M,title:V.target.value}),onKeyDown:yi,autoFocus:!0}),t.jsx("textarea",{placeholder:"Description (optional)",value:M.description,onChange:V=>O({...M,description:V.target.value}),rows:2}),t.jsxs("div",{className:"mission-form-card__row",children:[t.jsxs("select",{value:M.status,onChange:V=>O({...M,status:V.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:M.autopilotEnabled,onChange:V=>O({...M,autopilotEnabled:V.target.checked})}),t.jsx(Qn,{size:12})," Autopilot"]})]}),t.jsxs("div",{className:"mission-form-card__actions",children:[t.jsxs("button",{className:"mission-btn mission-btn--primary",onClick:wn,disabled:q,children:[q?t.jsx(bt,{size:14,className:"spinner"}):t.jsx(hs,{size:14}),"Update"]}),t.jsx("button",{className:"mission-btn mission-btn--ghost",onClick:qn,children:"Cancel"})]})]}),t.jsxs("div",{className:"mission-detail__tabs",role:"tablist","aria-label":"Mission detail tabs",children:[t.jsx("button",{className:`mission-btn ${_t==="structure"?"mission-btn--primary":"mission-btn--ghost"} mission-btn--sm mission-detail__tab`,onClick:()=>Yt("structure"),role:"tab","aria-selected":_t==="structure","data-testid":"mission-tab-structure",children:"Structure"}),t.jsxs("button",{className:`mission-btn ${_t==="activity"?"mission-btn--primary":"mission-btn--ghost"} mission-btn--sm mission-detail__tab`,onClick:()=>Yt("activity"),role:"tab","aria-selected":_t==="activity","data-testid":"mission-tab-activity",children:["Activity (",at,")"]})]}),_t==="structure"?t.jsxs("div",{className:"mission-detail__milestones",children:[g.milestones.map(V=>{const Re=$i?.rollup.milestoneId===V.id?$i:null,z=Re?.rollup??an.get(V.id),he=Re?.validationTelemetry.validationRounds??[],Qe=Re?.fixFeatures??[],ft=Hp[z?.state??"not_started"]??Hp.not_started,qt=z&&(z.state==="blocked"||z.state==="failed")?Re?.validationTelemetry.validationRounds.find(Xe=>Xe.blockedReason)?.blockedReason:void 0;return t.jsxs("div",{className:"mission-milestone",children:[t.jsxs("div",{className:"mission-milestone__header",onClick:()=>Is(V.id),children:[t.jsx("button",{className:"mission-milestone__expand",children:Z.has(V.id)?t.jsx(rn,{size:16}):t.jsx(Mn,{size:16})}),t.jsx(ja,{size:16,className:"mission-milestone__icon"}),t.jsx("span",{className:"mission-milestone__title",children:V.title}),t.jsx("span",{className:"mission-status-badge mission-status-badge--sm",style:{backgroundColor:Up[V.status].bg,color:Up[V.status].text},children:V.status}),t.jsxs("span",{className:"mission-milestone__count",children:[V.slices.length," slices"]}),t.jsx(qp,{state:IT(V.interviewState)}),z&&t.jsxs(t.Fragment,{children:[t.jsx("span",{className:"mission-status-badge mission-status-badge--sm",style:{backgroundColor:ft.bg,color:ft.text},title:"Validation state",children:Vp(z.state)}),z.totalAssertions>0&&t.jsx("div",{className:"mission-milestone__coverage-bar",title:`${z.passedAssertions??0} of ${z.totalAssertions} assertions passing`,children:t.jsx("div",{className:"mission-milestone__coverage-bar-fill",style:{width:`${(z.passedAssertions??0)/z.totalAssertions*100}%`,backgroundColor:(z.passedAssertions??0)===z.totalAssertions?"var(--color-success)":"var(--color-warning)"}})})]}),V.status!=="complete"&&t.jsx("button",{className:"mission-icon-btn",onClick:()=>mt({type:"milestone",id:V.id,title:V.title}),title:"Plan milestone","aria-label":"Plan milestone",children:t.jsx(ia,{size:14})}),t.jsxs("div",{className:"mission-milestone__actions",onClick:Xe=>Xe.stopPropagation(),children:[t.jsx("button",{className:"mission-icon-btn",onClick:()=>Ss(V.id),title:"Add slice",children:t.jsx(gn,{size:14})}),t.jsx("button",{className:"mission-icon-btn",onClick:()=>is(V),title:"Edit milestone",children:t.jsx(Ds,{size:14})}),t.jsx("button",{className:"mission-icon-btn mission-icon-btn--danger",onClick:()=>le({type:"milestone",id:V.id}),title:"Delete milestone",children:t.jsx(vn,{size:14})})]})]}),Z.has(V.id)&&t.jsxs("div",{className:"mission-milestone__body",children:[(Se||$===V.id)&&t.jsxs("div",{className:"mission-form-card",children:[t.jsx("input",{type:"text",placeholder:"Milestone title",value:G.title,onChange:Xe=>xe({...G,title:Xe.target.value}),onKeyDown:pa,autoFocus:!0}),t.jsx("textarea",{placeholder:"Description (optional)",value:G.description,onChange:Xe=>xe({...G,description:Xe.target.value}),rows:2}),t.jsxs("div",{className:"mission-form-card__actions",children:[t.jsxs("button",{className:"mission-btn mission-btn--primary",onClick:es,disabled:q,children:[q?t.jsx(bt,{size:14,className:"spinner"}):t.jsx(hs,{size:14}),$?"Update":"Create"]}),t.jsx("button",{className:"mission-btn mission-btn--ghost",onClick:Ns,children:"Cancel"})]})]}),Re&&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:[Re.validationTelemetry.totalRuns," rounds",Re.validationTelemetry.lastValidatorStatus?` · Last ${Re.validationTelemetry.lastValidatorStatus}`:""]})]}),qt&&t.jsxs("div",{className:"mission-blocked-reason",children:[t.jsx("strong",{children:"Blocked reason:"})," ",qt]}),he.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:()=>We(Xe=>!Xe),title:ze?"Hide validation rounds":"Show validation rounds",children:[ze?t.jsx(rn,{size:12}):t.jsx(Mn,{size:12}),"Validation rounds (",he.length,")"]}),ze&&t.jsx("div",{className:"mission-validation-rounds__list",children:he.map(Xe=>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--${Xe.validatorStatus}`,children:Xe.validatorStatus}),t.jsx("span",{className:"mission-validation-round__feature",children:Xe.featureTitle}),t.jsxs("span",{className:"mission-validation-round__attempts",children:["impl #",Xe.implementationAttempt," · reviewer #",Xe.validatorAttempt]})]}),t.jsxs("div",{className:"mission-validation-round__links",children:[t.jsx("span",{className:"mission-validation-round__label",children:"Failed assertions:"}),Xe.failedAssertionIds.length>0?t.jsx("div",{className:"mission-validation-round__chip-list",children:Xe.failedAssertionIds.map(nt=>t.jsx("button",{className:"mission-validation-round__link-chip",onClick:()=>ca(nt),title:`Jump to assertion ${nt}`,children:nt},`${Xe.roundId}-${nt}`))}):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:"}),Xe.generatedFixFeatureIds.length>0?t.jsx("div",{className:"mission-validation-round__chip-list",children:Xe.generatedFixFeatureIds.map(nt=>t.jsx("button",{className:"mission-validation-round__link-chip",onClick:()=>Ii(nt),title:`Jump to fix feature ${nt}`,children:nt},`${Xe.roundId}-${nt}`))}):t.jsx("span",{className:"mission-validation-round__empty",children:"None"})]}),Xe.blockedReason&&t.jsx("div",{className:"mission-validation-round__blocked-reason",children:Xe.blockedReason})]},Xe.roundId))})]}),Qe.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:Qe.map(Xe=>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:()=>Ii(Xe.id),title:`Jump to feature ${Xe.id}`,children:Xe.title}),t.jsx("span",{className:"mission-status-badge mission-status-badge--sm",style:{backgroundColor:sl[Xe.status].bg,color:sl[Xe.status].text},children:Xe.status}),Xe.loopState&&t.jsx("span",{className:`mission-loop-state mission-loop-state--${Xe.loopState}`,children:Xe.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:()=>Ii(Xe.sourceFeatureId),title:`Jump to source feature ${Xe.sourceFeatureId}`,children:Xe.sourceFeatureId}),t.jsx("span",{children:"Run:"}),t.jsx("span",{className:"mission-fix-feature__run",children:Xe.runId})]}),Xe.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:Xe.failedAssertionIds.map(nt=>t.jsx("button",{className:"mission-validation-round__link-chip",onClick:()=>ca(nt),title:`Jump to assertion ${nt}`,children:nt},`${Xe.id}-${nt}`))})]})]},Xe.id))})]})]}),t.jsxs("div",{className:"mission-slices",children:[V.slices.map(Xe=>t.jsxs("div",{className:"mission-slice",children:[t.jsxs("div",{className:"mission-slice__header",onClick:()=>Ee(Xe.id),children:[t.jsx("button",{className:"mission-slice__expand",children:A.has(Xe.id)?t.jsx(rn,{size:16}):t.jsx(Mn,{size:16})}),t.jsx(Pd,{size:16,className:"mission-slice__icon"}),t.jsx("span",{className:"mission-slice__title",children:Xe.title}),t.jsx("span",{className:"mission-status-badge mission-status-badge--sm",style:{backgroundColor:Bp[Xe.status].bg,color:Bp[Xe.status].text},children:Xe.status}),t.jsxs("span",{className:"mission-slice__count",children:[Xe.features?.length||0," features"]}),t.jsx(qp,{state:Xe.planState??"not_started"}),Xe.status!=="complete"&&t.jsx("button",{className:"mission-icon-btn",onClick:()=>mt({type:"slice",id:Xe.id,title:Xe.title}),title:"Plan slice","aria-label":"Plan slice",children:t.jsx(ia,{size:14})}),t.jsxs("div",{className:"mission-slice__actions",onClick:nt=>nt.stopPropagation(),children:[Xe.status==="pending"&&t.jsx("button",{className:"mission-icon-btn mission-icon-btn--success",onClick:()=>Y(Xe.id),title:"Activate slice",children:t.jsx(Yn,{size:14})}),Xe.status==="active"&&Xe.features?.some(nt=>nt.status==="defined")&&t.jsx("button",{className:"mission-icon-btn",onClick:()=>Vn(Xe.id),title:"Triage all features",disabled:q,children:q?t.jsx(bt,{size:14,className:"spinner"}):t.jsx(Qn,{size:14})}),t.jsx("button",{className:"mission-icon-btn",onClick:()=>Ge(Xe.id),title:"Add feature",children:t.jsx(gn,{size:14})}),t.jsx("button",{className:"mission-icon-btn",onClick:()=>X(Xe),title:"Edit slice",children:t.jsx(Ds,{size:14})}),t.jsx("button",{className:"mission-icon-btn mission-icon-btn--danger",onClick:()=>le({type:"slice",id:Xe.id}),title:"Delete slice",children:t.jsx(vn,{size:14})})]})]}),A.has(Xe.id)&&t.jsxs("div",{className:"mission-slice__body",children:[ne&&J===V.id&&!se&&t.jsxs("div",{className:"mission-form-card",children:[t.jsx("input",{type:"text",placeholder:"Slice title",value:ee.title,onChange:nt=>ce({...ee,title:nt.target.value}),onKeyDown:us,autoFocus:!0}),t.jsx("textarea",{placeholder:"Description (optional)",value:ee.description,onChange:nt=>ce({...ee,description:nt.target.value}),rows:2}),t.jsxs("div",{className:"mission-form-card__actions",children:[t.jsxs("button",{className:"mission-btn mission-btn--primary",onClick:de,disabled:q,children:[q?t.jsx(bt,{size:14,className:"spinner"}):t.jsx(hs,{size:14}),"Create"]}),t.jsx("button",{className:"mission-btn mission-btn--ghost",onClick:_,children:"Cancel"})]})]}),se===Xe.id&&t.jsxs("div",{className:"mission-form-card",children:[t.jsx("input",{type:"text",placeholder:"Slice title",value:ee.title,onChange:nt=>ce({...ee,title:nt.target.value}),onKeyDown:us,autoFocus:!0}),t.jsx("textarea",{placeholder:"Description (optional)",value:ee.description,onChange:nt=>ce({...ee,description:nt.target.value}),rows:2}),t.jsxs("select",{value:ee.status,onChange:nt=>ce({...ee,status:nt.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:de,disabled:q,children:[q?t.jsx(bt,{size:14,className:"spinner"}):t.jsx(hs,{size:14}),"Update"]}),t.jsx("button",{className:"mission-btn mission-btn--ghost",onClick:_,children:"Cancel"})]})]}),t.jsxs("div",{className:"mission-features",children:[Xe.features?.map(nt=>t.jsxs("div",{className:"mission-feature","data-mission-feature-id":nt.id,children:[t.jsxs("div",{className:"mission-feature__header",children:[t.jsx("button",{className:"mission-feature__expand",onClick:()=>Da(nt.id),title:Ht===nt.id?"Collapse details":"Expand to show run history",children:Ht===nt.id?t.jsx(rn,{size:14}):t.jsx(Mn,{size:14})}),t.jsx(Sd,{size:14,className:"mission-feature__icon"}),t.jsx("span",{className:"mission-feature__title",children:nt.title}),t.jsx("span",{className:"mission-status-badge mission-status-badge--sm",style:{backgroundColor:sl[nt.status].bg,color:sl[nt.status].text},children:nt.status}),nt.loopState&&nt.loopState!=="idle"&&t.jsxs("span",{className:`mission-loop-state mission-loop-state--${nt.loopState}`,title:`Loop state: ${nt.loopState}`,children:[nt.loopState==="implementing"&&"⏳",nt.loopState==="validating"&&"🔄",nt.loopState==="needs_fix"&&"🔧",nt.loopState==="passed"&&"✅",nt.loopState==="blocked"&&"🚫"]}),nt.generatedFromFeatureId&&t.jsx("button",{className:"mission-feature__lineage",onClick:()=>Ii(nt.generatedFromFeatureId),title:`Generated from feature: ${nt.generatedFromFeatureId}`,children:"🔗 Fix"}),(nt.loopState==="validating"||nt.loopState==="needs_fix")&&(()=>{const Ot=It.get(nt.id),bn=Ua.get(nt.id),Xs=Ot?.implementationAttemptCount??bn?.implementationAttempt??nt.implementationAttemptCount??0,ci=Ot?.retryBudgetRemaining??Math.max(0,RT-Xs);return t.jsxs("span",{className:"mission-feature__retry-budget",title:"Implementation attempts and remaining retry budget",children:["Attempt ",Xs," · ",ci," ",ci===1?"retry":"retries"," left"]})})(),nt.loopState==="implementing"&&t.jsx("button",{className:"mission-icon-btn mission-icon-btn--validate",onClick:()=>$a(nt.id),title:"Validate feature",disabled:Ze.has(nt.id),children:Ze.has(nt.id)?t.jsx(bt,{size:14,className:"spinner"}):t.jsx(ps,{size:14})}),nt.taskId&&t.jsx("span",{className:"mission-feature__task-link",onClick:()=>o?.(nt.taskId),title:"Click to view task",children:nt.taskId}),t.jsxs("div",{className:"mission-feature__actions",children:[nt.status==="defined"&&!nt.taskId&&t.jsx("button",{className:"mission-icon-btn",onClick:()=>Un(nt.id),title:"Triage — create task",disabled:q||Ue===nt.id,children:Ue===nt.id?t.jsx(bt,{size:14,className:"spinner"}):t.jsx(Qn,{size:14})}),nt.taskId?t.jsx("button",{className:"mission-icon-btn",onClick:()=>Rn(nt.id),title:"Unlink task",children:t.jsx(tm,{size:14})}):nt.status!=="defined"?t.jsx("button",{className:"mission-icon-btn",onClick:()=>Fe(nt.id),title:"Link to task",children:t.jsx(cr,{size:14})}):null,t.jsx("button",{className:"mission-icon-btn",onClick:()=>kt(nt),title:"Edit feature",children:t.jsx(Ds,{size:14})}),t.jsx("button",{className:"mission-icon-btn mission-icon-btn--danger",onClick:()=>le({type:"feature",id:nt.id}),title:"Delete feature",children:t.jsx(vn,{size:14})})]})]}),nt.description&&t.jsx("p",{className:"mission-feature__description",children:nt.description}),nt.acceptanceCriteria&&t.jsxs("p",{className:"mission-feature__criteria",children:[t.jsx("strong",{children:"Acceptance:"})," ",nt.acceptanceCriteria]}),xt?.featureId===nt.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:xt.enrichedDescription}),t.jsxs("div",{className:"mission-triage-preview__actions",children:[t.jsxs("button",{className:"btn btn-primary",onClick:gs,disabled:q,children:[q?t.jsx(bt,{size:14,className:"spinner"}):null,"Create Task"]}),t.jsx("button",{className:"btn",onClick:Ln,disabled:q,children:"Cancel"})]})]}),ye===nt.id&&t.jsxs("div",{className:"mission-form-card",children:[t.jsx("input",{type:"text",placeholder:"Feature title",value:H.title,onChange:Ot=>ke({...H,title:Ot.target.value}),onKeyDown:Ki,autoFocus:!0}),t.jsx("textarea",{placeholder:"Description (optional)",value:H.description,onChange:Ot=>ke({...H,description:Ot.target.value}),rows:2}),t.jsx("textarea",{placeholder:"Acceptance criteria (optional)",value:H.acceptanceCriteria,onChange:Ot=>ke({...H,acceptanceCriteria:Ot.target.value}),rows:2}),t.jsxs("select",{value:H.status,onChange:Ot=>ke({...H,status:Ot.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:Pt,disabled:q,children:[q?t.jsx(bt,{size:14,className:"spinner"}):t.jsx(hs,{size:14}),"Update"]}),t.jsx("button",{className:"mission-btn mission-btn--ghost",onClick:Tt,children:"Cancel"})]})]}),Ht===nt.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"})}),(ae.get(nt.id)??[]).map(Ot=>t.jsxs("div",{className:"mission-run",children:[t.jsxs("div",{className:"mission-run__header",onClick:()=>La(Ot.id),children:[t.jsx("span",{className:`mission-status-badge mission-status-badge--sm mission-run__status mission-run__status--${Ot.status}`,title:Ot.status,children:Ot.status}),t.jsx("span",{className:"mission-run__time",children:new Date(Ot.startedAt).toLocaleString()}),Ot.completedAt&&t.jsxs("span",{className:"mission-run__duration",children:[Math.round((new Date(Ot.completedAt).getTime()-new Date(Ot.startedAt).getTime())/1e3),"s"]}),Ot.triggerType&&t.jsx("span",{className:"mission-run__trigger",children:Ot.triggerType}),t.jsx("button",{className:"mission-icon-btn",title:At===Ot.id?"Hide details":"Show details",children:At===Ot.id?t.jsx(rn,{size:12}):t.jsx(Mn,{size:12})})]}),At===Ot.id&&Ft.get(Ot.id)&&t.jsxs("div",{className:"mission-run__details",children:[Ot.summary&&t.jsx("p",{className:"mission-run__summary",children:Ot.summary}),Ot.blockedReason&&t.jsxs("p",{className:"mission-run__blocked-reason",children:[t.jsx("strong",{children:"Blocked:"})," ",Ot.blockedReason]}),Ft.get(Ot.id)?.failures&&Ft.get(Ot.id).failures.length>0&&t.jsxs("div",{className:"mission-run__failures",children:[t.jsx("span",{className:"mission-run__failures-title",children:"Failed Assertions:"}),Ft.get(Ot.id).failures.map(bn=>t.jsxs("div",{className:"mission-run__failure",children:[t.jsx("span",{className:"mission-run__failure-message",children:bn.message}),bn.expected&&t.jsxs("span",{className:"mission-run__failure-expected",children:["Expected: ",bn.expected]}),bn.actual&&t.jsxs("span",{className:"mission-run__failure-actual",children:["Actual: ",bn.actual]})]},bn.id))]}),(!Ft.get(Ot.id)?.failures||Ft.get(Ot.id).failures.length===0)&&t.jsx("p",{className:"mission-run__no-failures",children:"No assertion failures"})]})]},Ot.id)),(!ae.get(nt.id)||ae.get(nt.id).length===0)&&t.jsx("div",{className:"mission-run-history__empty",children:"No validation runs yet."})]})]},nt.id)),pe&&Oe===Xe.id&&t.jsxs("div",{className:"mission-form-card",children:[t.jsx("input",{type:"text",placeholder:"Feature title",value:H.title,onChange:nt=>ke({...H,title:nt.target.value}),onKeyDown:Ki,autoFocus:!0}),t.jsx("textarea",{placeholder:"Description (optional)",value:H.description,onChange:nt=>ke({...H,description:nt.target.value}),rows:2}),t.jsx("textarea",{placeholder:"Acceptance criteria (optional)",value:H.acceptanceCriteria,onChange:nt=>ke({...H,acceptanceCriteria:nt.target.value}),rows:2}),t.jsxs("div",{className:"mission-form-card__actions",children:[t.jsxs("button",{className:"mission-btn mission-btn--primary",onClick:Pt,disabled:q,children:[q?t.jsx(bt,{size:14,className:"spinner"}):t.jsx(hs,{size:14}),"Create"]}),t.jsx("button",{className:"mission-btn mission-btn--ghost",onClick:Tt,children:"Cancel"})]})]}),!pe&&(!Xe.features||Xe.features.length===0)&&t.jsxs("div",{className:"mission-manager__empty mission-features__empty",children:[t.jsx(Sd,{size:16}),t.jsx("span",{children:"No fix features generated."})]})]})]})]},Xe.id)),V.slices.length===0&&!ne&&t.jsxs("div",{className:"mission-manager__empty",children:[t.jsx(Pd,{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"}),z&&t.jsx("span",{className:"mission-status-badge mission-status-badge--sm",style:{backgroundColor:ft.bg,color:ft.text},children:Vp(z.state)}),z&&z.totalAssertions>0&&t.jsx("div",{className:"mission-assertions__coverage-bar",title:`${z.passedAssertions??0} of ${z.totalAssertions} assertions passing`,children:t.jsx("div",{className:"mission-assertions__coverage-bar-fill",style:{width:`${(z.passedAssertions??0)/z.totalAssertions*100}%`,backgroundColor:(z.passedAssertions??0)===z.totalAssertions?"var(--color-success)":"var(--color-warning)"}})}),t.jsx("button",{className:"mission-icon-btn",onClick:()=>{wt(!0),qe(null),tt({title:"",assertion:"",status:"pending"})},title:"Add assertion",children:t.jsx(gn,{size:14})})]}),Ct&&t.jsxs("div",{className:"mission-form-card",children:[t.jsx("input",{type:"text",placeholder:"Assertion title",value:me.title,onChange:Xe=>tt({...me,title:Xe.target.value}),autoFocus:!0}),t.jsx("textarea",{placeholder:"Assertion text (what should be true when complete)",value:me.assertion,onChange:Xe=>tt({...me,assertion:Xe.target.value}),rows:2}),t.jsxs("select",{value:me.status,onChange:Xe=>tt({...me,status:Xe.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:()=>Bn(V.id),disabled:q,children:[q?t.jsx(bt,{size:14,className:"spinner"}):t.jsx(hs,{size:14}),"Create"]}),t.jsx("button",{className:"mission-btn mission-btn--ghost",onClick:Gn,children:"Cancel"})]})]}),t.jsxs("div",{className:"mission-assertions__list",children:[(Array.isArray(ge.get(V.id))?ge.get(V.id):[]).map(Xe=>t.jsxs("div",{className:"mission-assertion","data-mission-assertion-id":Xe.id,children:[t.jsx("div",{className:"mission-assertion__header",children:ue===Xe.id?t.jsxs("div",{className:"mission-form-card",children:[t.jsx("input",{type:"text",placeholder:"Assertion title",value:me.title,onChange:nt=>tt({...me,title:nt.target.value}),autoFocus:!0}),t.jsx("textarea",{placeholder:"Assertion text",value:me.assertion,onChange:nt=>tt({...me,assertion:nt.target.value}),rows:2}),t.jsxs("select",{value:me.status,onChange:nt=>tt({...me,status:nt.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:()=>ds(Xe.id,V.id),disabled:q,children:[q?t.jsx(bt,{size:14,className:"spinner"}):t.jsx(hs,{size:14}),"Save"]}),t.jsx("button",{className:"mission-btn mission-btn--ghost",onClick:Gn,children:"Cancel"})]})]}):t.jsxs(t.Fragment,{children:[t.jsx("span",{className:"mission-status-badge mission-status-badge--sm",style:{backgroundColor:(al[Xe.status]??al.pending).bg,color:(al[Xe.status]??al.pending).text},children:Xe.status}),t.jsx("span",{className:"mission-assertion__title",children:Xe.title}),(()=>{const Ot=Mt.get(Xe.id)?.length??0;return Ot>0?t.jsxs("span",{className:"mission-assertion__linked-count",title:`${Ot} linked feature${Ot!==1?"s":""}`,children:["(",Ot," linked)"]}):null})(),t.jsx("button",{className:"mission-icon-btn",onClick:()=>Ri(Xe.id),title:"Toggle details",children:$t===Xe.id?t.jsx(rn,{size:14}):t.jsx(Mn,{size:14})}),t.jsx("button",{className:"mission-icon-btn",onClick:()=>Nn(Xe),title:"Edit assertion",children:t.jsx(Ds,{size:14})}),t.jsx("button",{className:"mission-icon-btn mission-icon-btn--danger",onClick:()=>le({type:"assertion",id:Xe.id}),title:"Delete assertion",children:t.jsx(vn,{size:14})})]})}),$t===Xe.id&&t.jsxs("div",{className:"mission-assertion__body",children:[t.jsx("p",{className:"mission-assertion__text",children:Xe.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()=>{$t!==Xe.id&&await Ri(Xe.id),Jt(fn===Xe.id?null:Xe.id)},title:"Link a feature",children:[t.jsx(cr,{size:12}),"Link Feature"]})]}),fn===Xe.id&&t.jsx("div",{className:"mission-assertion__feature-picker",children:t.jsx("div",{className:"mission-assertion__feature-picker-dropdown",children:(()=>{const nt=new Set((Mt.get(Xe.id)??[]).map(bn=>bn.id)),Ot=[];return g?.milestones.forEach(bn=>bn.slices.forEach(Xs=>Ot.push(...Xs.features.filter(ci=>!nt.has(ci.id))))),Ot.length===0?t.jsx("span",{className:"mission-assertion__feature-picker-empty",children:"All features already linked"}):Ot.map(bn=>t.jsxs("button",{className:"mission-assertion__feature-picker-item",onClick:()=>ri(bn.id,Xe.id),disabled:Qt.has(Xe.id),children:[t.jsx("span",{className:"mission-assertion__feature-picker-title",children:bn.title}),Qt.has(Xe.id)&&t.jsx(bt,{size:12,className:"spinner"})]},bn.id))})()})}),(()=>{const nt=Mt.get(Xe.id)??[];return nt.length===0?t.jsx("span",{className:"mission-assertion__linked-empty",children:"No features linked yet"}):nt.map(Ot=>{const bn=`${Ot.id}-${Xe.id}`,Xs=Bt.has(bn);return t.jsxs("div",{className:"mission-assertion__linked-feature",children:[t.jsx("span",{className:"mission-assertion__linked-feature-title",children:Ot.title}),t.jsx("button",{className:"mission-icon-btn mission-icon-btn--danger",onClick:()=>Ta(Ot.id,Xe.id),disabled:Xs,title:"Unlink feature",children:Xs?t.jsx(bt,{size:12,className:"spinner"}):t.jsx(tm,{size:12})})]},Ot.id)})})()]})]})]},Xe.id)),(!ge.get(V.id)||ge.get(V.id)?.length===0)&&!Ct&&t.jsx("div",{className:"mission-manager__empty mission-assertions__empty",children:t.jsx("span",{children:"No assertions defined. Add one to define completion criteria."})})]})]})]})]})]},V.id)}),g&&!Se&&$===null&&t.jsxs("button",{className:"mission-add-btn",onClick:_n,children:[t.jsx(gn,{size:16}),"Add Milestone"]}),Se&&$===null&&t.jsxs("div",{className:"mission-form-card",children:[t.jsx("input",{type:"text",placeholder:"Milestone title",value:G.title,onChange:V=>xe({...G,title:V.target.value}),onKeyDown:pa,autoFocus:!0}),t.jsx("textarea",{placeholder:"Description (optional)",value:G.description,onChange:V=>xe({...G,description:V.target.value}),rows:2}),t.jsxs("div",{className:"mission-form-card__actions",children:[t.jsxs("button",{className:"mission-btn mission-btn--primary",onClick:es,disabled:q,children:[q?t.jsx(bt,{size:14,className:"spinner"}):t.jsx(hs,{size:14}),"Create"]}),t.jsx("button",{className:"mission-btn mission-btn--ghost",onClick:Ns,children:"Cancel"})]})]}),g.milestones.length===0&&!Se&&t.jsxs("div",{className:"mission-manager__empty",children:[t.jsx(ja,{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:vt,onChange:V=>ie(V.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:[Xt.length," of ",at]})]}),!it&&li&&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:Ba,"data-testid":"mission-activity-load-more",children:"Load more"})}),it?t.jsxs("div",{className:"mission-manager__loading mission-detail__activity-loading",children:[t.jsx(bt,{size:18,className:"spinner"}),t.jsx("span",{children:"Loading mission activity..."})]}):Xt.length===0?t.jsxs("div",{className:"mission-manager__empty",children:[t.jsx(Ks,{size:18}),t.jsx("span",{children:"No events yet."})]}):t.jsxs("div",{ref:Cn,className:"mission-events","data-testid":"mission-activity-events",children:[Xt.map(V=>{const Re=!!(V.metadata&&Object.keys(V.metadata).length>0),z=st.has(V.id);return t.jsxs("div",{className:"mission-event",children:[t.jsxs("div",{className:"mission-event__header",children:[t.jsx("span",{className:`mission-event__type ${OT(V.eventType)}`,children:zT(V.eventType)}),t.jsx("span",{className:"mission-event__time",children:Ol(V.timestamp)})]}),t.jsx("p",{className:"mission-event__description",children:V.description}),t.jsx("span",{className:"mission-event__timestamp",children:new Date(V.timestamp).toLocaleString()}),Re&&t.jsxs("div",{className:"mission-event__metadata",children:[t.jsxs("button",{className:"mission-btn mission-btn--ghost mission-btn--sm",onClick:()=>Ha(V.id),"data-testid":`mission-event-metadata-${V.id}`,children:[z?"Hide":"Show"," metadata"]}),z&&t.jsx("pre",{className:"mission-event__metadata-content",children:JSON.stringify(V.metadata,null,2)})]})]},V.id)}),t.jsx("div",{ref:fs})]})]})]}):null,qa=()=>f.map(V=>{const Re=V,z=g?.id===Re.id,he=Fr[Re.status]||{bg:"",text:""},Qe=Re.summary,ft=ct.get(Re.id),qt=$T(ft),Xe=!!(Qe&&(Qe.totalMilestones>0||Qe.totalFeatures>0)),nt=ft?.totalTasks??0,Ot=ft?.tasksCompleted??0,bn=ft?.tasksFailed??0,Xs=ft?.estimatedCompletionPercent??Qe?.progressPercent??0,ci=Xe||nt>0||bn>0||!!ft?.lastActivityAt;return t.jsxs("div",{className:`mission-list__item ${z?"mission-list__item--selected":""}`,onClick:()=>ha(V),children:[t.jsxs("div",{className:"mission-list__item-content",children:[t.jsxs("div",{className:"mission-list__item-header",children:[t.jsx(vs,{size:16,className:"mission-list__item-icon"}),t.jsx("span",{className:"mission-list__item-title",children:Re.title})]}),t.jsxs("div",{className:"mission-list__item-tags",children:[V.autopilotEnabled&&t.jsx("span",{title:"Autopilot enabled",children:t.jsx(Qn,{size:12,className:"mission-list__item-autopilot-icon"})}),t.jsx("span",{className:`mission-health-badge mission-health-badge--${qt}`,"data-testid":`mission-health-badge-${Re.id}`,"aria-label":`Mission health: ${qt}`}),t.jsx("span",{className:"mission-status-badge mission-status-badge--sm",style:{backgroundColor:he.bg,color:he.text},children:Re.status})]}),Re.description&&t.jsx("p",{className:"mission-list__item-description",children:Re.description}),ci&&t.jsxs("div",{className:"mission-list__item-summary",children:[Xe&&t.jsxs(t.Fragment,{children:[t.jsxs("span",{className:"mission-list__item-stat",children:[Qe.completedMilestones,"/",Qe.totalMilestones," milestones"]}),t.jsxs("span",{className:"mission-list__item-stat",children:[Qe.completedFeatures,"/",Qe.totalFeatures," features"]})]}),t.jsxs("span",{className:"mission-list__item-stat","data-testid":`mission-task-stats-${Re.id}`,children:[Ot,"/",nt," tasks"]}),bn>0&&t.jsxs("button",{className:"mission-list__item-failed",onClick:rs=>{rs.stopPropagation(),ha(V)},"data-testid":`mission-failed-${Re.id}`,title:"View mission failures",children:[bn," failed"]}),t.jsx("div",{className:`mission-list__item-progress mission-list__item-progress--${qt}`,children:t.jsx("div",{className:"mission-list__item-progress-bar",style:{width:`${Xs}%`}})})]}),ci&&t.jsx("div",{className:"mission-list__item-activity",children:t.jsxs("span",{className:"mission-relative-time","data-testid":`mission-last-activity-${Re.id}`,children:["Activity ",Ol(ft?.lastActivityAt)]})})]}),t.jsxs("div",{className:"mission-list__item-actions",onClick:rs=>rs.stopPropagation(),children:[Re.status==="active"&&t.jsx("button",{className:"mission-icon-btn mission-icon-btn--danger",onClick:()=>ma(Re.id),title:"Stop mission",children:t.jsx(Si,{size:14})}),Re.status==="blocked"&&t.jsx("button",{className:"mission-icon-btn mission-icon-btn--success",onClick:()=>ua(Re.id),title:"Resume mission",children:t.jsx(Yn,{size:14})}),Re.status==="planning"&&t.jsx("button",{className:"mission-icon-btn mission-icon-btn--success",onClick:()=>Ti(Re.id),title:"Start mission",children:t.jsx(Yn,{size:14})}),t.jsx("button",{className:"mission-icon-btn",onClick:()=>Hn(V),title:"Edit mission",children:t.jsx(Ds,{size:14})}),t.jsx("button",{className:"mission-icon-btn mission-icon-btn--danger",onClick:()=>le({type:"mission",id:Re.id}),title:"Delete mission",children:t.jsx(vn,{size:14})})]})]},Re.id)}),Ke=({hideBottomButtons:V=!1}={})=>{const Re=k&&f.length>0&&!E,z=!V&&!Re;return t.jsxs("div",{className:"mission-list",children:[E&&t.jsxs("div",{className:"mission-form-card",children:[t.jsx("input",{type:"text",placeholder:"Mission title",value:M.title,onChange:he=>O({...M,title:he.target.value}),onKeyDown:yi,autoFocus:!0}),t.jsx("textarea",{placeholder:"Description (optional)",value:M.description,onChange:he=>O({...M,description:he.target.value}),rows:2}),t.jsxs("div",{className:"mission-form-card__actions",children:[t.jsxs("button",{className:"mission-btn mission-btn--primary",onClick:wn,disabled:q,children:[q?t.jsx(bt,{size:14,className:"spinner"}):t.jsx(hs,{size:14}),"Create"]}),t.jsx("button",{className:"mission-btn mission-btn--ghost",onClick:qn,children:"Cancel"})]})]}),Re&&t.jsx("div",{className:"mission-list__top-action",children:t.jsxs("button",{className:"btn btn-sm btn-task-create mission-list__primary-cta",onClick:()=>ot(!0),children:[t.jsx(ps,{size:14}),"Plan New Mission"]})}),qa(),L&&t.jsxs("div",{className:"mission-form-card",children:[t.jsx("input",{type:"text",placeholder:"Mission title",value:M.title,onChange:he=>O({...M,title:he.target.value}),onKeyDown:yi,autoFocus:!0}),t.jsx("textarea",{placeholder:"Description (optional)",value:M.description,onChange:he=>O({...M,description:he.target.value}),rows:2}),t.jsxs("div",{className:"mission-form-card__row",children:[t.jsxs("select",{value:M.status,onChange:he=>O({...M,status:he.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:M.autopilotEnabled,onChange:he=>O({...M,autopilotEnabled:he.target.checked})}),t.jsx(Qn,{size:12})," Autopilot"]})]}),t.jsxs("div",{className:"mission-form-card__actions",children:[t.jsxs("button",{className:"mission-btn mission-btn--primary",onClick:wn,disabled:q,children:[q?t.jsx(bt,{size:14,className:"spinner"}):t.jsx(hs,{size:14}),"Update"]}),t.jsx("button",{className:"mission-btn mission-btn--ghost",onClick:qn,children:"Cancel"})]})]}),f.length===0&&!E&&t.jsxs("div",{className:"mission-manager__empty mission-manager__empty--large mission-manager__empty--mission",children:[t.jsx(vs,{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:()=>ot(!0),children:[t.jsx(ps,{size:14}),"Plan New Mission"]})]}),!E&&t.jsxs("div",{className:"mission-list__footer",children:[Be.length>0&&t.jsxs("div",{className:"mission-resume-prompt",children:[t.jsx(Ps,{size:16}),t.jsx("span",{children:Be.length===1?`Resume "${Be[0].title}"?`:`${Be.length} interview sessions pending`}),t.jsx("div",{className:"mission-list__resume-actions",children:Be.map(he=>t.jsxs("button",{className:"mission-add-btn",onClick:()=>{_e(he.id),ot(!0),we([])},children:[he.status==="error"?t.jsx(os,{size:14}):t.jsx(ps,{size:14}),he.status==="error"?"Retry":"Resume"]},he.id))})]}),z&&t.jsx("div",{className:"mission-list__footer-actions",children:t.jsxs("button",{className:"mission-add-btn",onClick:()=>ot(!0),children:[t.jsx(ps,{size:16}),"Plan New Mission"]})})]})]})},Rt=()=>t.jsx("div",{className:"mission-confirm-panel mission-confirm-panel--danger",children:t.jsxs("div",{className:"mission-confirm-panel__content",children:[t.jsxs("p",{children:["Delete this ",oe?.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()=>{oe&&(oe.type==="mission"?await Zn(oe.id):oe.type==="milestone"?await ks(oe.id):oe.type==="slice"?await D(oe.id):oe.type==="feature"&&await ln(oe.id))},children:"Delete"}),t.jsx("button",{className:"mission-btn mission-btn--ghost",onClick:()=>le(null),children:"Cancel"})]})]})}),cn=()=>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:fe,onChange:V=>$e(V.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(V=>t.jsxs("button",{className:"mission-task-suggestions__item",onClick:()=>$e(V.id),children:[V.id,": ",V.title||"Untitled"]},V.id))})]}),t.jsxs("div",{className:"mission-confirm-panel__actions",children:[t.jsx("button",{className:"mission-btn mission-btn--primary",onClick:ts,children:"Link"}),t.jsx("button",{className:"mission-btn mission-btn--ghost",onClick:()=>{Fe(null),$e("")},children:"Cancel"})]})]})}),as=t.jsxs("div",{ref:Cs,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:Mr,title:"Back to missions","aria-label":"Back to missions list","data-testid":"mission-back-btn",children:t.jsx(Vl,{size:18})}),t.jsx(vs,{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(nn,{size:18})})]}),k?t.jsxs("div",{className:"mission-manager__body mission-manager__body--stacked",children:[w?t.jsxs("div",{className:"mission-manager__loading",children:[t.jsx(bt,{size:24,className:"spinner"}),t.jsx("span",{children:"Loading missions..."})]}):y?t.jsxs("div",{className:"mission-manager__loading",children:[t.jsx(bt,{size:24,className:"spinner"}),t.jsx("span",{children:"Loading mission details..."})]}):g?Gi():Ke(),oe&&Rt(),dt&&cn()]}):t.jsxs("div",{className:"mission-manager__split",children:[t.jsxs("aside",{className:"mission-manager__sidebar","data-testid":"mission-sidebar","aria-label":"Mission list",style:k?void 0:{width:`${C}px`},children:[t.jsx("div",{className:"mission-manager__sidebar-header",children:t.jsxs("button",{className:"btn btn-sm btn-primary mission-manager__sidebar-cta",onClick:()=>ot(!0),title:"Plan New Mission","aria-label":"Plan New Mission",children:[t.jsx(ps,{size:14}),"Plan New Mission"]})}),t.jsx("div",{className:"mission-manager__sidebar-list",children:w?t.jsxs("div",{className:"mission-manager__loading",children:[t.jsx(bt,{size:24,className:"spinner"}),t.jsx("span",{children:"Loading missions..."})]}):Ke({hideBottomButtons:!0})})]}),!k&&t.jsx("div",{className:"mission-manager__sidebar-resize-handle",role:"separator","aria-orientation":"vertical","aria-valuemin":tl,"aria-valuemax":nl,"aria-valuenow":C,"aria-label":"Resize mission sidebar",tabIndex:0,onPointerDown:P,onKeyDown:U}),t.jsxs("div",{className:"mission-manager__detail-pane",children:[y?t.jsxs("div",{className:"mission-manager__loading",children:[t.jsx(bt,{size:24,className:"spinner"}),t.jsx("span",{children:"Loading mission details..."})]}):g?Gi():t.jsxs("div",{className:"mission-manager__detail-pane-empty","data-testid":"mission-empty-detail",children:[t.jsx(vs,{size:32}),t.jsx("span",{children:"Select a mission to view details"})]}),oe&&Rt(),dt&&cn()]})]})]}),In=t.jsx(yT,{isOpen:De,onClose:()=>ot(!1),onMissionCreated:()=>{hn(),a("Mission created from AI interview","success")},projectId:r,resumeSessionId:lt}),$s=ht?t.jsx(MT,{isOpen:!0,onClose:()=>mt(null),onApplied:()=>{mt(null),g&&Et(g.id)},targetType:ht.type,targetId:ht.id,targetTitle:ht.title,missionContext:g?.title,projectId:r,resumeSessionId:ht.resumeSessionId}):null;return n?t.jsxs(t.Fragment,{children:[as,In,$s]}):t.jsxs(t.Fragment,{children:[t.jsx("div",{className:"mission-manager-overlay open",onClick:V=>V.target===V.currentTarget&&s(),"data-testid":"mission-manager-overlay",role:"dialog","aria-modal":"true",children:as}),In,$s]})}const BT={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})},Gp=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(bi,{remarkPlugins:[xi],components:BT,children:n})})}),rl=2e3;function Jp({recipient:e,replyContext:n,agents:s=[],projectId:a,onSend:r,onCancel:o,addToast:l,isLoadingAgents:c=!1}){const[d,u]=i.useState(e?.id??""),[m,h]=i.useState(e?.type??"agent"),[f,p]=i.useState(""),[g,x]=i.useState(!1),[w,b]=i.useState(!1),[y,S]=i.useState(null),k=i.useRef(null),C=i.useMemo(()=>s.find(F=>F.id===d),[s,d]),v=i.useMemo(()=>e?s.find(F=>F.id===e.id):void 0,[s,e]),j=m==="agent",P=j&&C?.runtimeConfig?.messageResponseMode==="immediate",U=j&&(g||P),E=d.trim()!==""&&f.trim().length>0&&f.length<=rl,R=i.useCallback(async()=>{if(!(!E||w)){b(!0),S(null);try{const F=m==="agent"?"user-to-agent":"system",M=n?{replyTo:{messageId:n.messageId}}:void 0,O=U;await $1({toId:d.trim(),toType:m,content:f.trim(),type:F,...M?{metadata:M}:{},...O?{wakeImmediately:!0}:{}},a),r()}catch(F){const M=Pe(F)||"Failed to send message";S(M),l?.(M,"error")}finally{b(!1)}}},[E,w,d,m,f,U,n,a,r,l]),L=i.useCallback(F=>{u(F),h("agent")},[]);return i.useEffect(()=>{n&&k.current?.focus()},[n]),i.useEffect(()=>{if(!n||typeof window>"u"||window.visualViewport==null)return;const F=()=>{k.current?.scrollIntoView({block:"center",behavior:"auto"})};return window.visualViewport.addEventListener("resize",F),()=>{window.visualViewport?.removeEventListener("resize",F)}},[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(nn,{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:F=>L(F.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(F=>t.jsx("option",{value:F.id,children:F.name||F.id},F.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($n,{size:14}),v?.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:k,className:"message-composer-textarea",placeholder:"Type your message…",value:f,onChange:F=>p(F.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]})})]}),j&&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:U,disabled:P,onChange:F=>x(F.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:P?"(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(Ps,{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:R,disabled:!E||w,"data-testid":"message-composer-send",children:w?t.jsxs(t.Fragment,{children:[t.jsx(bt,{size:14,className:"spin"}),t.jsx("span",{children:"Sending…"})]}):t.jsxs(t.Fragment,{children:[t.jsx(wa,{size:14}),t.jsx("span",{children:"Send"})]})})]})]})}const zl=280,tu=.65,rd=16,Yp=320;function nu(e){return Math.max(zl,e*tu)}function od(e,n){const s=nu(n);return Math.min(Math.max(e,zl),s)}function Qp(e){try{const n=An("kb-dashboard-mailbox-sidebar-width",e);if(!n)return Yp;const s=Number(n);if(Number.isFinite(s)&&s>0)return s}catch{}return Yp}function Xi(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 HT(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 qT(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 Xp(e,n=80){return e.length<=n?e:`${e.slice(0,n)}…`}function Zp(){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 ol(e){return`mailbox-list-message-${e}`}function ld(e){return`mailbox-detail-message-${e}`}function VT(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 WT({projectId:e,addToast:n,onUnreadCountChange:s}){const[a,r]=i.useState("inbox"),[o,l]=i.useState(null),[c,d]=i.useState(null),[u,m]=i.useState(0),[h,f]=i.useState(!1),[p,g]=i.useState(null),[x,w]=i.useState([]),[b,y]=i.useState(!1),[S,k]=i.useState(null),[C,v]=i.useState(null),[j,P]=i.useState(null),[U,E]=i.useState("inbox"),[R,L]=i.useState(null),[F,M]=i.useState([]),[O,q]=i.useState("pending"),[te,Z]=i.useState([]),[K,A]=i.useState(0),[I,$]=i.useState(null),[N,G]=i.useState(""),[xe,Se]=i.useState(!1),je=i.useMemo(()=>new Map(F.map(oe=>[oe.id,oe.name??""])),[F]),se=i.useCallback((oe,le)=>HT(oe,le,je),[je]),ee=Ys()==="mobile",ce=!ee,[ne,re]=i.useState(()=>Qp(e)),J=i.useRef(null),{keyboardOverlap:B,viewportHeight:ye,viewportOffsetTop:Ce,keyboardOpen:H}=Wi({enabled:ee}),ke=i.useMemo(()=>{if(H)return{"--keyboard-overlap":`${B}px`,"--vv-offset-top":`${Ce}px`,...ye!=null?{"--vv-height":`${ye}px`}:{}}},[H,B,ye,Ce]);i.useEffect(()=>{re(Qp(e))},[e]),i.useEffect(()=>{if(!ce)return;const oe=J.current?.clientWidth;oe&&re(le=>od(le,oe))},[ce]),i.useEffect(()=>{if(ce)try{ss("kb-dashboard-mailbox-sidebar-width",String(ne),e)}catch{}},[ce,e,ne]);const pe=i.useCallback(oe=>{if(!ce)return;oe.preventDefault();const le=J.current;if(!le)return;const ge=le.getBoundingClientRect(),Ne=qe=>{const me=qe.clientX-ge.left;re(od(me,ge.width))},ue=()=>{window.removeEventListener("mousemove",Ne),window.removeEventListener("mouseup",ue)};window.addEventListener("mousemove",Ne),window.addEventListener("mouseup",ue)},[ce]),Ae=i.useCallback(oe=>{if(!ce)return;const le=J.current?.clientWidth??0,ge=ne/tu+rd,Ne=Math.max(le,ge),ue=nu(Ne);if(oe.key==="ArrowLeft"||oe.key==="ArrowRight"){oe.preventDefault();const qe=oe.key==="ArrowLeft"?-rd:rd;re(me=>od(me+qe,Ne));return}if(oe.key==="Home"){oe.preventDefault(),re(zl);return}oe.key==="End"&&(oe.preventDefault(),re(ue))},[ce,ne]),Oe=i.useCallback(async()=>{f(!0);try{const oe=await I1({limit:50},e);l(oe),m(oe.unreadCount),s?.(oe.unreadCount)}catch{}finally{f(!1)}},[e,s]),He=i.useCallback(async()=>{f(!0);try{const oe=await T1({limit:50},e);d(oe)}catch{}finally{f(!1)}},[e]),dt=i.useCallback(async oe=>{f(!0);try{const le=await F1(oe,e);L(le)}catch{}finally{f(!1)}},[e]),Fe=i.useCallback(async()=>{try{const oe=await Nr(void 0,e);M(oe)}catch{}},[e]),fe=i.useCallback(async()=>{try{const oe=await Hg(e);m(oe.unreadCount),s?.(oe.unreadCount)}catch{}},[e,s]),$e=i.useCallback(async oe=>{f(!0);try{const le=await Fo({status:oe==="pending"?"pending":void 0,limit:100},e);if(oe==="pending")Z(le.requests);else{const[ge,Ne,ue]=await Promise.all([Fo({status:"approved",limit:100},e),Fo({status:"denied",limit:100},e),Fo({status:"completed",limit:100},e)]);Z([...ge.requests,...Ne.requests,...ue.requests].sort((qe,me)=>me.updatedAt.localeCompare(qe.updatedAt)))}A(le.pendingCount)}catch{}finally{f(!1)}},[e]);i.useEffect(()=>{a==="inbox"?Oe():a==="outbox"?He():a==="agents"?Fe():a==="approvals"&&$e(O)},[a,Oe,He,Fe,$e,O]),i.useEffect(()=>{j&&dt(j)},[j,dt]),i.useEffect(()=>{fe()},[fe]),i.useEffect(()=>{Fe()},[Fe]),i.useEffect(()=>{if(typeof EventSource>"u")return;const oe=e?`?projectId=${encodeURIComponent(e)}`:"",le=()=>{fe(),a==="inbox"?Oe():a==="outbox"?He():a==="approvals"&&$e(O),j&&dt(j)};return ii(`/api/events${oe}`,{events:{"message:sent":le,"message:received":le,"message:read":le,"message:deleted":le,"approval:requested":le,"approval:updated":le,"approval:decided":le}})},[e,a,j,fe,Oe,He,dt,$e,O]);const De=i.useCallback(async oe=>{if(g(oe),!oe.read&&a==="inbox")try{const le=await D1(oe.id,e);le&&l(Ne=>Ne&&{...Ne,messages:Ne.messages.map(ue=>ue.id===le.id?le:ue),unreadCount:Math.max(0,Ne.unreadCount-1)});const ge=Math.max(0,u-1);m(ge),s?.(ge)}catch{}try{const le=await z1(oe.fromId,oe.fromType,e);w(le)}catch{w([oe])}},[e,u,s,a]);i.useEffect(()=>{const oe=Zp();if(!oe)return;const le=[...o?.messages??[],...c?.messages??[],...R?.inbox??[],...R?.outbox??[],...x].find(ge=>ge.id===oe);le&&De(le)},[o,c,R,x,De]),i.useEffect(()=>{const oe=Zp();if(!oe)return;const le=document.getElementById(ld(oe));if(!le)return;le.scrollIntoView({behavior:"smooth",block:"center"}),le.classList.add("mailbox-message-highlight");const ge=window.setTimeout(()=>{le.classList.remove("mailbox-message-highlight")},2e3);return()=>{window.clearTimeout(ge)}},[p,x]);const ot=i.useCallback(()=>{g(null),w([])},[]),Be=i.useCallback(async()=>{try{const oe=await L1(e);m(0),s?.(0),l(le=>le&&{...le,messages:le.messages.map(ge=>({...ge,read:!0})),unreadCount:0}),n?.(`Marked ${oe.markedAsRead} messages as read`,"success")}catch{n?.("Failed to mark messages as read","error")}},[e,n,s]),we=i.useCallback(async oe=>{try{await O1(oe,e),g(null),w([]),a==="inbox"?Oe():a==="outbox"?He():j&&dt(j),n?.("Message deleted","success")}catch{n?.("Failed to delete message","error")}},[e,a,j,Oe,He,dt,n]),Q=i.useCallback(oe=>{k({id:oe.fromId,type:oe.fromType}),v({messageId:oe.id,preview:Xp(oe.content,120)}),y(!0)},[]),_e=i.useCallback(()=>{y(!1),k(null),v(null),n?.("Message sent","success"),a==="outbox"?He():a==="agents"&&j&&dt(j),fe()},[a,He,j,dt,n,fe]),lt=i.useCallback(()=>{k(a==="agents"&&j?{id:j,type:"agent"}:null),v(null),y(!0)},[a,j]),ht=i.useCallback(()=>{y(!1),k(null),v(null)},[]),mt=i.useCallback(async oe=>{try{const le=await _m(oe.id,e);$(le),G("")}catch{n?.("Failed to load approval request","error")}},[e,n]),xt=i.useCallback(async oe=>{if(!(!I||xe)){Se(oe);try{await U1(I.id,{decision:oe,comment:N||void 0},e),await $e(O);const le=await _m(I.id,e);$(le),G(""),n?.(`Request ${oe==="approve"?"approved":"denied"}`,"success")}catch{n?.("Failed to submit decision","error")}finally{Se(!1)}}},[I,xe,N,e,$e,O,n]),Ie=()=>{if(!p||b)return null;const oe=VT(x,p);return t.jsxs("div",{className:"mailbox-message-detail","data-testid":"mailbox-message-detail",id:ld(p.id),children:[t.jsxs("div",{className:"mailbox-message-detail-header",children:[ee&&t.jsx("button",{className:"btn btn-sm btn-secondary",onClick:ot,"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:qT(p.type)}),t.jsx("span",{className:"mailbox-message-time",children:Xi(p.createdAt)})]}),t.jsxs("div",{className:"mailbox-message-detail-actions",children:[p.fromType==="agent"&&t.jsxs("button",{className:"btn btn-sm btn-secondary",onClick:()=>Q(p),"data-testid":"mailbox-reply",children:[t.jsx(Ui,{size:14}),t.jsx("span",{children:"Reply"})]}),t.jsxs("button",{className:"btn btn-sm btn-secondary",onClick:()=>we(p.id),"data-testid":"mailbox-delete",children:[t.jsx(vn,{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($n,{size:14}):t.jsx(Ka,{size:14}),se(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($n,{size:14}):t.jsx(Ka,{size:14}),se(p.toId,p.toType)]})]})]}),oe.length>1&&t.jsxs("div",{className:"mailbox-conversation","data-testid":"mailbox-conversation",children:[t.jsx("div",{className:"mailbox-conversation-label",children:"Conversation"}),oe.map(le=>{const ge=le.metadata?.replyTo?.messageId,Ne=ge?oe.find(ue=>ue.id===ge):void 0;return t.jsxs("div",{id:ld(le.id),className:`mailbox-conversation-msg ${le.id===p.id?"current":""}`,children:[t.jsxs("div",{className:"mailbox-conversation-msg-header",children:[t.jsx("span",{children:se(le.fromId,le.fromType)}),t.jsx("span",{className:"mailbox-message-time",children:Xi(le.createdAt)})]}),ge&&t.jsxs("div",{className:"mailbox-reply-context-static","data-testid":`mailbox-reply-context-${le.id}`,children:["↪ Replying to ",Ne?Xp(Ne.content,60):`message ${ge}`]}),t.jsx(Gp,{content:le.content,className:"mailbox-conversation-msg-body"})]},le.id)})]}),oe.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(Gp,{content:p.content,className:"mailbox-message-body",testId:"mailbox-message-body"})]})]})},Ue=()=>t.jsxs(t.Fragment,{children:[a==="inbox"&&t.jsxs("div",{className:"mailbox-list","data-testid":"mailbox-inbox-list",children:[h&&!o&&t.jsx(cd,{}),o&&o.messages.length===0&&t.jsxs("div",{className:"mailbox-empty","data-testid":"mailbox-inbox-empty",children:[t.jsx(ya,{size:32}),t.jsx("p",{children:"No messages in your inbox"})]}),o?.messages.map(oe=>t.jsxs("div",{id:ol(oe.id),className:`mailbox-item ${oe.read?"":"unread"}`,onClick:()=>De(oe),"data-testid":`mailbox-item-${oe.id}`,children:[t.jsx("div",{className:"mailbox-item-avatar",children:oe.fromType==="agent"?t.jsx($n,{size:16}):t.jsx(Ka,{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:se(oe.fromId,oe.fromType)}),t.jsx("span",{className:"mailbox-item-time",children:Xi(oe.createdAt)})]}),t.jsxs("div",{className:"mailbox-item-preview",children:[oe.content.slice(0,80),oe.content.length>80?"…":""]})]}),!oe.read&&t.jsx("div",{className:"mailbox-item-unread-dot","data-testid":`mailbox-unread-dot-${oe.id}`})]},oe.id))]}),a==="outbox"&&t.jsxs("div",{className:"mailbox-list","data-testid":"mailbox-outbox-list",children:[h&&!c&&t.jsx(cd,{}),c&&c.messages.length===0&&t.jsxs("div",{className:"mailbox-empty","data-testid":"mailbox-outbox-empty",children:[t.jsx(wa,{size:32}),t.jsx("p",{children:"No sent messages"})]}),c?.messages.map(oe=>t.jsxs("div",{id:ol(oe.id),className:"mailbox-item",onClick:()=>De(oe),"data-testid":`mailbox-item-${oe.id}`,children:[t.jsx("div",{className:"mailbox-item-avatar",children:oe.toType==="agent"?t.jsx($n,{size:16}):t.jsx(Ka,{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: ",se(oe.toId,oe.toType)]}),t.jsx("span",{className:"mailbox-item-time",children:Xi(oe.createdAt)})]}),t.jsxs("div",{className:"mailbox-item-preview",children:[oe.content.slice(0,80),oe.content.length>80?"…":""]})]})]},oe.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 ${O==="pending"?"active":""}`,onClick:()=>{q("pending"),$(null)},"data-testid":"mailbox-approval-filter-pending",children:"Pending"}),t.jsx("button",{className:`btn btn-sm btn-secondary mailbox-agent-subtab ${O==="history"?"active":""}`,onClick:()=>{q("history"),$(null)},"data-testid":"mailbox-approval-filter-history",children:"History"})]}),t.jsxs("div",{className:"mailbox-list","data-testid":"mailbox-approval-list",children:[te.length===0&&!h&&t.jsxs("div",{className:"mailbox-empty","data-testid":"mailbox-approval-empty",children:[t.jsx(ya,{size:32}),t.jsx("p",{children:O==="pending"?"No pending approvals":"No historical approvals"})]}),te.map(oe=>t.jsxs("div",{className:"mailbox-item mailbox-approval-item",onClick:()=>void mt(oe),"data-testid":`mailbox-approval-item-${oe.id}`,children:[t.jsx("div",{className:`status-dot mailbox-approval-status-dot mailbox-approval-status-dot--${oe.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:[oe.agentId," · ",oe.actionCategory]}),t.jsx("span",{className:"mailbox-item-time",children:Xi(oe.createdAt)})]}),t.jsx("div",{className:"mailbox-item-preview",children:oe.actionSummary})]}),t.jsx("span",{className:`mailbox-approval-status mailbox-approval-status--${oe.status}`,children:oe.status})]},oe.id))]})]}),a==="agents"&&t.jsx("div",{className:"mailbox-agents","data-testid":"mailbox-agents",children:F.length===0?t.jsxs("div",{className:"mailbox-empty",children:[t.jsx($n,{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:j??"",onChange:oe=>{P(oe.target.value||null),E("inbox")},"data-testid":"mailbox-agent-select",children:[t.jsx("option",{value:"",children:"Select an agent…"}),F.map(oe=>t.jsx("option",{value:oe.id,children:oe.name||oe.id},oe.id))]})}),t.jsxs("button",{className:"btn btn-sm btn-secondary mailbox-compose-btn",onClick:lt,"data-testid":"mailbox-compose-btn",children:[t.jsx(Ui,{size:14}),t.jsx("span",{children:"Compose"})]})]}),j&&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 ${U==="inbox"?"active":""}`,onClick:()=>E("inbox"),"data-testid":"mailbox-agent-subtab-inbox",children:[t.jsx(ya,{size:12}),t.jsx("span",{children:"Inbox"}),R&&R.unreadCount>0&&t.jsx("span",{className:"mailbox-tab-badge",children:R.unreadCount})]}),t.jsxs("button",{className:`btn btn-sm btn-secondary mailbox-agent-subtab ${U==="outbox"?"active":""}`,onClick:()=>E("outbox"),"data-testid":"mailbox-agent-subtab-outbox",children:[t.jsx(wa,{size:12}),t.jsx("span",{children:"Outbox"})]})]}),t.jsxs("div",{className:"mailbox-agents-content",children:[!j&&t.jsxs("div",{className:"mailbox-empty",children:[t.jsx($n,{size:32}),t.jsx("p",{children:"Select an agent to view their mailbox"})]}),j&&h&&!R&&t.jsx(cd,{}),j&&R&&U==="inbox"&&R.inbox.length===0&&t.jsxs("div",{className:"mailbox-empty",children:[t.jsx(ya,{size:32}),t.jsx("p",{children:"No received messages for this agent"})]}),j&&R&&U==="outbox"&&R.outbox.length===0&&t.jsxs("div",{className:"mailbox-empty",children:[t.jsx(wa,{size:32}),t.jsx("p",{children:"No sent messages for this agent"})]}),j&&R&&U==="inbox"&&R.inbox.map(oe=>t.jsxs("div",{id:ol(oe.id),className:`mailbox-item ${oe.read?"":"unread"}`,onClick:()=>De(oe),"data-testid":`mailbox-item-${oe.id}`,children:[t.jsx("div",{className:"mailbox-item-avatar",children:oe.fromType==="agent"?t.jsx($n,{size:16}):t.jsx(Ka,{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:se(oe.fromId,oe.fromType)}),t.jsx("span",{className:"mailbox-item-time",children:Xi(oe.createdAt)})]}),t.jsxs("div",{className:"mailbox-item-preview",children:[oe.content.slice(0,80),oe.content.length>80?"…":""]})]})]},oe.id)),j&&R&&U==="outbox"&&R.outbox.map(oe=>t.jsxs("div",{id:ol(oe.id),className:"mailbox-item",onClick:()=>De(oe),"data-testid":`mailbox-item-${oe.id}`,children:[t.jsx("div",{className:"mailbox-item-avatar",children:oe.toType==="agent"?t.jsx($n,{size:16}):t.jsx(Ka,{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: ",se(oe.toId,oe.toType)]}),t.jsx("span",{className:"mailbox-item-time",children:Xi(oe.createdAt)})]}),t.jsxs("div",{className:"mailbox-item-preview",children:[oe.content.slice(0,80),oe.content.length>80?"…":""]})]})]},oe.id))]})]})})]}),pt=()=>b?t.jsx(Jp,{recipient:S,replyContext:C,agents:F,projectId:e,onSend:_e,onCancel:ht,addToast:n}):p?Ie():a==="approvals"&&I?t.jsxs("div",{className:"mailbox-message-detail mailbox-approval-detail","data-testid":"mailbox-approval-detail",children:[ee&&t.jsx("button",{className:"btn btn-sm btn-secondary",onClick:()=>$(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:I.actionCategory}),t.jsx("span",{className:"mailbox-message-time",children:I.status})]})}),t.jsxs("div",{className:"mailbox-message-body",children:[t.jsx("strong",{children:I.actionSummary}),t.jsxs("p",{children:["Requester: ",I.requester.actorName," (",I.agentId,")"]}),I.taskId&&t.jsxs("p",{children:["Task: ",I.taskId]}),t.jsxs("p",{children:["Requested: ",Xi(I.createdAt)]})]}),t.jsx("div",{className:"mailbox-conversation","data-testid":"mailbox-approval-history",children:I.history.map(oe=>t.jsxs("div",{className:"mailbox-conversation-msg",children:[t.jsxs("div",{className:"mailbox-conversation-msg-header",children:[t.jsx("span",{children:oe.eventType}),t.jsx("span",{children:oe.actor.actorName})]}),oe.note&&t.jsx("div",{className:"mailbox-item-preview",children:oe.note})]},oe.id))}),I.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:N,onChange:oe=>G(oe.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 xt("deny"),disabled:xe!==!1,"data-testid":"mailbox-approval-deny",children:"Deny"}),t.jsx("button",{className:"btn btn-sm btn-primary",onClick:()=>void xt("approve"),disabled:xe!==!1,"data-testid":"mailbox-approval-approve",children:"Approve"})]})]})]}):t.jsxs("div",{className:"mailbox-split-empty","data-testid":"mailbox-split-empty",children:[t.jsx(Na,{size:24}),t.jsx("p",{children:"Select a message to read"})]});return t.jsxs("div",{className:"mailbox-view",style:ke,"data-testid":"mailbox-view",children:[t.jsxs("div",{className:"mailbox-header",children:[t.jsxs("div",{className:"mailbox-title",children:[t.jsx(Na,{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:lt,title:"Compose message","data-testid":"mailbox-header-compose",children:[t.jsx(Ui,{size:14}),t.jsx("span",{children:"Compose"})]}),a==="inbox"&&u>0&&t.jsxs("button",{className:"btn btn-sm btn-secondary",onClick:Be,title:"Mark all as read","data-testid":"mailbox-mark-all-read",children:[t.jsx(Qu,{size:14}),t.jsx("span",{children:"Mark all read"})]}),t.jsx("button",{className:"btn-icon",onClick:()=>{a==="inbox"?Oe():a==="outbox"?He():a==="approvals"?$e(O):j&&dt(j)},disabled:h,title:"Refresh","data-testid":"mailbox-refresh",children:h?t.jsx(bt,{size:14,className:"spin"}):t.jsx(os,{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(ya,{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(wa,{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),$(null)},"data-testid":"mailbox-tab-agents",children:[t.jsx($n,{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),$(null)},"data-testid":"mailbox-tab-approvals",children:[t.jsx(Qu,{size:14}),t.jsx("span",{children:"Approvals"}),K>0&&t.jsx("span",{className:"mailbox-tab-badge","data-testid":"mailbox-approvals-pending-badge",children:K})]})]}),t.jsx("div",{className:"mailbox-content","data-testid":"mailbox-content",children:ce?t.jsxs("div",{className:"mailbox-split-layout","data-testid":"mailbox-split-layout",ref:J,children:[t.jsx("div",{className:"mailbox-split-list-pane","data-testid":"mailbox-split-list-pane",style:{width:`${ne}px`},children:Ue()}),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":zl,"aria-valuemax":Math.round(nu(J.current?.clientWidth??ne/tu)),"aria-valuenow":Math.round(ne),onMouseDown:pe,onKeyDown:Ae}),t.jsx("div",{className:"mailbox-split-detail-pane","data-testid":"mailbox-split-detail-pane",children:pt()})]}):t.jsxs(t.Fragment,{children:[Ie(),a==="approvals"&&I&&pt(),b&&t.jsx(Jp,{recipient:S,replyContext:C,agents:F,projectId:e,onSend:_e,onCancel:ht,addToast:n}),!p&&!I&&!b&&Ue()]})})]})}function cd(){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 KT=640;function GT({isOpen:e,onClose:n,onImport:s,tasks:a,projectId:r}){vi(e);const[o,l]=i.useState(""),[c,d]=i.useState(""),[u,m]=i.useState(""),[h,f]=i.useState(!1),[p,g]=i.useState("issues"),[x,w]=i.useState([]),[b,y]=i.useState(null),[S,k]=i.useState([]),[C,v]=i.useState(null),[j,P]=i.useState(null),[U,E]=i.useState(!1),[R,L]=i.useState([]),[F,M]=i.useState(!1),[O,q]=i.useState(""),te=i.useRef(!1),Z=i.useRef(null);Ai(Z,e,"fusion:github-modal-size");const K=qi(n),[A,I]=i.useState(!1),[$,N]=i.useState("list"),G=i.useRef(null),xe=new Set;for(const we of a){const Q=we.description.match(/Source: (https:\/\/github\.com\/[^/]+\/[^/]+\/issues\/\d+)/);Q&&xe.add(Q[1]);const _e=we.description.match(/PR: (https:\/\/github\.com\/[^/]+\/[^/]+\/pull\/\d+)/);_e&&xe.add(_e[1])}i.useEffect(()=>{if(e)return l(""),d(""),m(""),w([]),y(null),k([]),v(null),g("issues"),P(null),E(!1),L([]),M(!0),q(""),G.current=null,te.current=!0,zj().then(we=>{if(te.current)if(L(we),M(!1),we.length===1){const Q=we[0];l(Q.owner),d(Q.repo),q(Q.name)}else we.length>1&&(l(""),d(""),q(""))}).catch(()=>{te.current&&M(!1)}),()=>{te.current=!1}},[e]);const Se=i.useCallback(we=>{if(q(we),we==="")l(""),d("");else{const Q=R.find(_e=>_e.name===we);Q&&(l(Q.owner),d(Q.repo))}},[R]),je=i.useCallback(async()=>{if(!o.trim()||!c.trim()){P("Repository must be selected");return}f(!0),P(null),w([]),y(null);try{const we=u.split(",").map(_e=>_e.trim()).filter(Boolean),Q=await $j(o.trim(),c.trim(),30,we.length>0?we:void 0);w(Q),Q.length===0&&P("No open issues found")}catch(we){P(Pe(we)||"Failed to fetch issues")}finally{f(!1)}},[o,c,u]),se=i.useCallback(async()=>{if(!o.trim()||!c.trim()){P("Repository must be selected");return}f(!0),P(null),k([]),v(null);try{const we=await Lj(o.trim(),c.trim(),30);k(we),we.length===0&&P("No open pull requests found")}catch(we){P(Pe(we)||"Failed to fetch pull requests")}finally{f(!1)}},[o,c]);i.useEffect(()=>{if(!e||!o.trim()||!c.trim()||h||U)return;const we={owner:o.trim(),repo:c.trim(),labels:u.trim(),tab:p};G.current?.owner===we.owner&&G.current?.repo===we.repo&&G.current?.labels===we.labels&&G.current?.tab===we.tab||(G.current=we,p==="issues"?je():se())},[o,c,u,p,e,h,U,je,se]),i.useEffect(()=>{if(!e)return;const we=Q=>{Q.key==="Escape"&&n()};return document.addEventListener("keydown",we),()=>document.removeEventListener("keydown",we)},[e,n]),i.useEffect(()=>{if(!e)return;const we=()=>{I(window.innerWidth<=KT)};return we(),window.addEventListener("resize",we),()=>window.removeEventListener("resize",we)},[e]);const Ve=i.useCallback(we=>{y(we),A&&N("preview")},[A]),ee=i.useCallback(we=>{v(we),A&&N("preview")},[A]),ce=i.useCallback(()=>{N("list")},[]),ne=i.useCallback(async()=>{if(p==="issues"){if(b===null)return;E(!0),P(null);try{const we=await Dj(o.trim(),c.trim(),b,r);s(we),y(null),A&&$==="preview"&&N("list")}catch(we){const Q=Pe(we);Q?.includes("already imported")?P(Q):P(Q||"Failed to import issue")}finally{E(!1)}}else{if(C===null)return;E(!0),P(null);try{const we=await Oj(o.trim(),c.trim(),C,r);s(we),v(null),A&&$==="preview"&&N("list")}catch(we){const Q=Pe(we);Q?.includes("already imported")?P(Q):P(Q||"Failed to import pull request")}finally{E(!1)}}},[p,b,C,o,c,s,A,$]),re=x.find(we=>we.number===b),J=S.find(we=>we.number===C);if(!e)return null;const B=R.length>0,ye=R.length===1,Ce=x.filter(we=>xe.has(we.html_url)).length,H=S.filter(we=>xe.has(we.html_url)).length,ke=j==="No open issues found",pe=j==="No open pull requests found",Ae=p==="issues"?ke:pe,Oe=!!j&&!ke&&x.length===0&&!h,He=!!j&&!pe&&S.length===0&&!h,dt=p==="issues"?Oe:He,Fe=h||x.length>0||ke||Oe,fe=h||S.length>0||pe||He,$e=p==="issues"?Fe:fe,De=!!j&&x.length>0&&!ke,ot=!!j&&S.length>0&&!pe,Be=p==="issues"?De:ot;return t.jsx("div",{className:"modal-overlay open",...K,role:"dialog","aria-modal":"true",children:t.jsxs("div",{className:"modal modal-lg github-import-modal",ref:Z,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"),v(null)},disabled:h||U,children:[t.jsx(Wl,{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:h||U,children:[t.jsx(Ws,{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:F?t.jsxs("div",{className:"github-import-toolbar__loading",role:"status","aria-live":"polite",children:[t.jsx(bt,{size:16,className:"spin"}),t.jsx("span",{children:"Detecting…"})]}):B?ye?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:R[0].name}),t.jsxs("span",{className:"github-import-remote-pill__repo",children:[R[0].owner,"/",R[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:O,onChange:we=>Se(we.target.value),disabled:h||U,"aria-label":"Select Git remote",children:[t.jsx("option",{value:"",children:"Select remote…"}),R.map(we=>t.jsxs("option",{value:we.name,children:[we.name," (",we.owner,"/",we.repo,")"]},we.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:we=>m(we.target.value),onKeyDown:we=>we.key==="Enter"&&je(),disabled:h||U||!B,"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"?je:se,disabled:h||U||!o.trim()||!c.trim(),"aria-label":h?`Loading ${p}`:`Load ${p} from repository`,title:h?"Loading…":`Load ${p}`,children:[h?t.jsx(bt,{size:14,className:"spin"}):t.jsx(os,{size:14}),t.jsx("span",{children:h?"Loading…":"Load"})]})})]}),!F&&!B&&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"})]}),Be&&t.jsx("div",{className:"form-error github-import-banner",role:"alert",children:j}),t.jsxs("div",{className:"github-import-workspace",children:[t.jsxs("section",{className:`github-import-list-pane ${A?"mobile":""} ${$==="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"&&x.length>0&&t.jsxs("div",{className:"github-import-results-meta","aria-live":"polite",children:[t.jsxs("span",{children:[x.length," issue",x.length===1?"":"s"]}),t.jsxs("span",{children:[Ce," imported"]})]}),p==="pulls"&&S.length>0&&t.jsxs("div",{className:"github-import-results-meta","aria-live":"polite",children:[t.jsxs("span",{children:[S.length," pull request",S.length===1?"":"s"]}),t.jsxs("span",{children:[H," imported"]})]})]}),t.jsxs("div",{className:"github-import-pane-content",children:[!$e&&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."})]})}),h&&t.jsxs("div",{className:"github-import-state github-import-state--loading",role:"status","aria-live":"polite",children:[t.jsx(bt,{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."})]})]}),dt&&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:j})]})}),Ae&&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"&&x.length>0&&t.jsx("div",{className:"issues-list","aria-live":"polite",children:x.map(we=>{const Q=xe.has(we.html_url);return t.jsxs("div",{className:`issue-item ${b===we.number?"selected":""} ${Q?"imported":""}`,onClick:()=>!Q&&Ve(we.number),children:[t.jsx("input",{type:"radio",name:"issue",checked:b===we.number,onChange:()=>Ve(we.number),disabled:Q,"aria-label":`Select issue #${we.number}`}),t.jsxs("div",{className:"issue-main",children:[t.jsxs("div",{className:"issue-heading-row",children:[t.jsxs("span",{className:"issue-number",children:["#",we.number]}),t.jsx("span",{className:"issue-title",children:we.title})]}),we.labels.length>0&&t.jsx("span",{className:"issue-labels",children:we.labels.map(_e=>t.jsx("span",{className:"label-chip",children:_e.name},_e.name))})]}),Q&&t.jsx("span",{className:"imported-badge",children:"Imported"})]},we.number)})}),p==="pulls"&&S.length>0&&t.jsx("div",{className:"issues-list","aria-live":"polite",children:S.map(we=>{const Q=xe.has(we.html_url);return t.jsxs("div",{className:`issue-item ${C===we.number?"selected":""} ${Q?"imported":""}`,onClick:()=>!Q&&ee(we.number),children:[t.jsx("input",{type:"radio",name:"pull",checked:C===we.number,onChange:()=>ee(we.number),disabled:Q,"aria-label":`Select pull request #${we.number}`}),t.jsxs("div",{className:"issue-main",children:[t.jsxs("div",{className:"issue-heading-row",children:[t.jsxs("span",{className:"issue-number",children:["#",we.number]}),t.jsx("span",{className:"issue-title",children:we.title})]}),t.jsxs("span",{className:"pull-branch-info",children:[we.headBranch," → ",we.baseBranch]})]}),Q&&t.jsx("span",{className:"imported-badge",children:"Imported"})]},we.number)})})]})]}),t.jsxs("section",{className:`github-import-preview-pane ${A?"mobile":""} ${$==="preview"?"active":""}`,"data-testid":"github-import-preview-pane","aria-labelledby":"github-import-preview-heading",children:[t.jsxs("div",{className:"github-import-pane-header",children:[A&&t.jsxs("button",{className:"github-import-back-button",onClick:ce,"data-testid":"github-import-back-button","aria-label":`Back to ${p==="issues"?"issues":"pull requests"} list`,children:[t.jsx(Aa,{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"&&re?t.jsxs("div",{className:"issue-preview","data-testid":"github-import-preview-card",children:[t.jsxs("div",{className:"preview-meta",children:["Issue #",re.number]}),t.jsx("div",{className:"preview-title",children:re.title}),t.jsx("div",{className:"preview-body",children:re.body?re.body.slice(0,200)+(re.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"&&J?t.jsxs("div",{className:"issue-preview","data-testid":"github-import-preview-card",children:[t.jsxs("div",{className:"preview-meta",children:["Pull Request #",J.number]}),t.jsx("div",{className:"preview-title",children:J.title}),t.jsxs("div",{className:"preview-branch",children:[t.jsx("strong",{children:"Branch:"})," ",J.headBranch," → ",J.baseBranch]}),t.jsx("div",{className:"preview-body",children:J.body?J.body.slice(0,200)+(J.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:U,children:"Cancel"}),t.jsx("button",{className:"btn btn-primary",onClick:ne,disabled:(p==="issues"?b===null:C===null)||U,children:U?t.jsx(bt,{size:14,className:"spin"}):"Import"})]})]})})}function ti({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(Mn,{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 JT=["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 go(e){return e&&oa.includes(e)?e:js}function dd(e){return{...e,priority:go(e.priority)}}function YT(e,n){return e&&n?`${e}/${n}`:""}function QT(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 XT({isOpen:e,onClose:n,onTaskCreated:s,onTasksCreated:a,tasks:r,initialPlan:o,projectId:l,resumeSessionId:c}){const[d,u]=i.useState(""),[m,h]=i.useState({type:"initial"}),[f,p]=i.useState(null),[g,x]=i.useState([]),[w,b]=i.useState([]),[y,S]=i.useState(null),k=i.useRef(!1),C=i.useRef(!1),[v,j]=i.useState(""),[P,U]=i.useState(!0),[E,R]=i.useState(!1),[L,F]=i.useState(!1),[M,O]=i.useState(null),[q,te]=i.useState(0),Z=i.useRef(null),K=i.useRef(null),A=i.useRef(null),I=i.useRef(null),$=i.useRef(null),N=i.useRef(null),G=i.useRef(null),[xe,Se]=i.useState(c??null),je=i.useMemo(()=>Ia(),[]),{isLockedByOther:se,takeControl:Ve,isLoading:ee}=cc(e?xe:null),{activeTabMap:ce,broadcastUpdate:ne,broadcastCompleted:re,broadcastLock:J,broadcastUnlock:B,broadcastHeartbeat:ye}=_r(),[Ce,H]=i.useState(void 0),[ke,pe]=i.useState(void 0),[Ae,Oe]=i.useState("medium"),[He,dt]=i.useState(""),[Fe,fe]=i.useState([]),[$e,De]=i.useState(!1),[ot,Be]=i.useState(null),[we,Q]=i.useState([]),[_e,lt]=i.useState([]),[ht,mt]=i.useState({}),xt=i.useRef(null),[Ie,Ue]=i.useState([]),[pt,oe]=i.useState(!1),[le,ge]=i.useState(c??null),[Ne,ue]=i.useState(!!c),[qe,me]=i.useState(null),[tt,Ct]=i.useState(!1),wt=i.useRef(!1),$t=i.useRef(null),Vt=i.useRef(""),Mt=i.useRef(null),Dt=i.useRef(null);Ai(K,e,"fusion:planning-modal-size");const Qt=Ys(),{keyboardOverlap:Kt,viewportHeight:Bt,viewportOffsetTop:on,keyboardOpen:fn}=Wi({enabled:Qt==="mobile"});vi(Qt==="mobile"&&e),i.useEffect(()=>{const be=K.current;be&&(fn?(be.style.setProperty("--keyboard-overlap",`${Kt}px`),be.style.setProperty("--vv-offset-top",`${on}px`),Bt!==null?be.style.setProperty("--vv-height",`${Bt}px`):be.style.removeProperty("--vv-height")):(be.style.removeProperty("--keyboard-overlap"),be.style.removeProperty("--vv-offset-top"),be.style.removeProperty("--vv-height")))},[fn,Kt,on,Bt]),i.useEffect(()=>{Vt.current=v},[v]),i.useEffect(()=>{const be=$t.current;if(!be)return;be.scrollHeight-be.scrollTop-be.clientHeight<32&&(be.scrollTop=be.scrollHeight)},[v]),i.useEffect(()=>{if(m.type!=="loading"){O(null),te(0);return}const be=Date.now();O(be),te(0);const it=setInterval(()=>{te(Math.max(0,Math.floor((Date.now()-be)/1e3)))},1e3);return()=>clearInterval(it)},[m.type]),i.useEffect(()=>{if(m.type!=="loading")return;const be=I.current;if(!be)return;let it=!1;const at=setInterval(async()=>{try{const ut=await Ci(be);if(it||!ut||I.current!==be)return;if(ut.status==="awaiting_input"&&ut.currentQuestion){const vt=JSON.parse(ut.currentQuestion);h({type:"question",session:{sessionId:be,currentQuestion:vt,summary:null}}),j("")}else if(ut.status==="complete"&&ut.result){const vt=dd(JSON.parse(ut.result));h({type:"summary",session:{sessionId:be,currentQuestion:null,summary:vt},summary:vt}),S(vt),j("")}}catch{}},8e3);return()=>{it=!0,clearInterval(at)}},[m.type]);const Jt=i.useCallback(()=>{u(""),h({type:"initial"}),p(null),x([]),b([]),S(null),j(""),R(!1),F(!1),H(void 0),pe(void 0),Oe("medium"),dt(""),I.current=null,Se(null)},[]),an=YT(Ce,ke),zt=i.useCallback((be,it)=>{if(!be||!it)return ht.provider&&ht.modelId?`${ht.provider}/${ht.modelId}`:"Using default";const rt=Fe.find(at=>at.provider===be&&at.id===it);return rt?`${rt.provider}/${rt.id}`:`${be}/${it}`},[Fe,ht.modelId,ht.provider]),en=i.useCallback(async()=>{De(!0),Be(null);try{const be=await Os();fe(be.models),Q(be.favoriteProviders),lt(be.favoriteModels),mt({provider:be.resolvedPlanningProvider,modelId:be.resolvedPlanningModelId})}catch(be){Be(Pe(be)||"Failed to load models")}finally{De(!1)}},[]),Zt=i.useCallback(be=>{Q(it=>{const rt=it,ut=rt.includes(be)?rt.filter(vt=>vt!==be):[be,...rt];return kn({favoriteProviders:ut,favoriteModels:_e}).catch(()=>{Q(rt)}),ut})},[_e]),dn=i.useCallback(be=>{lt(it=>{const rt=it,ut=rt.includes(be)?rt.filter(vt=>vt!==be):[be,...rt];return kn({favoriteProviders:we,favoriteModels:ut}).catch(()=>{lt(rt)}),ut})},[we]),ve=i.useCallback(be=>{A.current?.close();const it=()=>I.current!==be,rt=UN(be,l,{onThinking:at=>{it()||(j(ut=>ut+at),ne({sessionId:be,status:"generating",needsInput:!1,owningTabId:je,type:"planning",title:d.trim()||void 0,projectId:l??null}))},onQuestion:at=>{if(it())return;R(!1),F(!1),Xa(l);const ut=Vt.current.trim();ut&&b(vt=>vt[vt.length-1]?.thinkingOutput===ut?vt:[...vt,{thinkingOutput:ut}]),h({type:"question",session:{sessionId:be,currentQuestion:at,summary:null}}),j(""),ne({sessionId:be,status:"awaiting_input",needsInput:!0,owningTabId:je,type:"planning",title:d.trim()||void 0,projectId:l??null})},onSummary:at=>{if(it())return;R(!1),F(!1),Xa(l);const ut=Vt.current.trim();ut&&b(vt=>vt[vt.length-1]?.thinkingOutput===ut?vt:[...vt,{thinkingOutput:ut}]),h({type:"summary",session:{sessionId:be,currentQuestion:null,summary:at},summary:at}),S(at),j(""),ne({sessionId:be,status:"complete",needsInput:!1,owningTabId:je,type:"planning",title:d.trim()||void 0,projectId:l??null})},onError:at=>{const ut=at||"Session failed while contacting the AI.";R(!0),(async()=>{try{const vt=await Ci(be);if(vt&&(vt.status==="generating"||vt.status==="awaiting_input")){ve(be);return}}catch{}R(!1),F(!1),p(null),h(vt=>vt.type==="question"||vt.type==="summary"||vt.type==="error"?{type:"error",session:vt.session,errorMessage:ut}:{type:"error",session:{sessionId:be,currentQuestion:null,summary:null},errorMessage:ut}),j(""),I.current=be,ne({sessionId:be,status:"error",needsInput:!1,owningTabId:je,type:"planning",title:d.trim()||void 0,projectId:l??null}),re({sessionId:be,status:"error"})})()},onComplete:()=>{R(!1),F(!1),I.current=null,re({sessionId:be,status:"complete"})},onConnectionStateChange:at=>{R(at==="reconnecting")}});A.current=rt},[re,ne,d,l,je]),ze=i.useCallback(async be=>{const it=be??d;if(it.trim()){p(null),j(""),b([]),x([]),R(!1),h({type:"loading"});try{const rt=Ce&&ke?{planningModelProvider:Ce,planningModelId:ke}:void 0,at=He.trim()?Number.parseInt(He,10):void 0,ut=$.current,{sessionId:vt}=await jN(it.trim(),l,rt,{planningDepth:Ae,customQuestionCount:Number.isInteger(at)?at:void 0},ut??void 0);$.current=null,I.current=vt,Se(vt),ge(vt),ve(vt),x([])}catch(rt){R(!1),p(Pe(rt)||"Failed to start planning session"),h({type:"initial"}),I.current=null,Se(null)}}},[ve,He,d,Ae,ke,Ce,l]);i.useEffect(()=>{e&&m.type==="initial"&&Z.current?.focus()},[e,m.type]),i.useEffect(()=>{e&&en()},[e,en]),i.useEffect(()=>{if(e&&o&&!k.current&&m.type==="initial"){u(o);const be=setTimeout(()=>{k.current=!0,ze(o)},0);return()=>clearTimeout(be)}else if(e&&!o&&!k.current&&!C.current&&m.type==="initial"){C.current=!0;const be=sT(l);be&&u(be)}},[e,o,m.type,ze,l]);const We=i.useCallback(async be=>{A.current?.close(),A.current=null,p(null),j(""),x([]),b([]),S(null),F(!1),h({type:"loading"});try{const it=await Ci(be);if(!it){ge(null),ue(!1),h({type:"initial"});return}I.current=be,Se(be);const rt=hr(it.conversationHistory);if(b(rt),x(rt.map(at=>at.response).filter(at=>!!(at&&typeof at=="object"&&!Array.isArray(at)))),it.status==="draft"){let at="",ut,vt;try{const ie=it.inputPayload?JSON.parse(it.inputPayload):null;ie&&typeof ie.initialPlan=="string"&&(at=ie.initialPlan),ie&&typeof ie.modelProvider=="string"&&typeof ie.modelId=="string"&&(ut=ie.modelProvider,vt=ie.modelId)}catch{}u(at),H(ut),pe(vt),$.current=be,Dt.current=at?{sessionId:be,initialPlan:at.trim(),modelProvider:ut,modelId:vt}:null,h({type:"initial"})}else if(it.status==="awaiting_input"&&it.currentQuestion){Xa(l);const at=JSON.parse(it.currentQuestion);if(h({type:"question",session:{sessionId:be,currentQuestion:at,summary:null}}),it.thinkingOutput){const ut=it.thinkingOutput.trim();ut&&b(vt=>vt[vt.length-1]?.thinkingOutput===ut?vt:[...vt,{thinkingOutput:ut}])}ve(be)}else if(it.status==="complete"&&it.result){Xa(l);const at=dd(JSON.parse(it.result));h({type:"summary",session:{sessionId:be,currentQuestion:null,summary:at},summary:at}),S(at)}else it.status==="generating"?(h({type:"loading"}),it.thinkingOutput&&j(it.thinkingOutput),ve(be)):it.status==="error"&&h({type:"error",session:{sessionId:be,currentQuestion:null,summary:null},errorMessage:it.error||"Session failed"})}catch{p("Failed to load session"),h({type:"initial"})}},[ve,l]);i.useEffect(()=>{!e||!c||I.current!==c&&G.current!==c&&(ge(c),ue(!0),We(c))},[e,c]),i.useEffect(()=>{e&&le&&(c&&c===le||We(le))},[e]);const Ze=i.useCallback(async()=>{oe(!0);try{const it=(await xu(l,{includeCompleted:!0,includeArchived:tt})).filter(rt=>rt.type==="planning").sort((rt,at)=>Date.parse(at.updatedAt)-Date.parse(rt.updatedAt));Ue(it)}catch{}finally{oe(!1)}},[l,tt]);i.useEffect(()=>{e&&Ze()},[e,Ze]);const Ye=i.useRef(!1);i.useEffect(()=>{const be=Ye.current&&!pt;Ye.current=pt,be&&Qt==="mobile"&&(Ne||c||le||Ie.length>0||ue(!0))},[Qt,Ne,c,le,pt,Ie.length]),i.useEffect(()=>{if(!e)return;const be=l?`?projectId=${encodeURIComponent(l)}`:"",it=at=>{try{const ut=JSON.parse(at.data);if(ut.type!=="planning")return;Ue(vt=>{const ie=vt.findIndex(Gt=>Gt.id===ut.id);return(ie>=0?[...vt.slice(0,ie),ut,...vt.slice(ie+1)]:[ut,...vt]).sort((Gt,Cn)=>Date.parse(Cn.updatedAt)-Date.parse(Gt.updatedAt))})}catch{}},rt=at=>{try{const ut=JSON.parse(at.data);Ue(vt=>vt.filter(ie=>ie.id!==ut))}catch{}};return ii(`/api/events${be}`,{events:{"ai_session:updated":it,"ai_session:deleted":rt},onReconnect:()=>{Ze()}})},[e,l,Ze]);const It=i.useCallback(be=>{if(le===be){ue(!0);return}ge(be),ue(!0),We(be)},[We,le]),St=i.useCallback(()=>{A.current?.close(),A.current=null,$.current=null,N.current&&(clearTimeout(N.current),N.current=null),c&&(G.current=c),Jt(),ge(null),ue(!0)},[Jt,c]),Ht=i.useCallback(()=>{ue(!1)},[]),jt=i.useCallback(async(be,it)=>{const rt=it.trim();if(!(!rt||Dt.current?.sessionId===be&&Dt.current.initialPlan===rt&&Dt.current.modelProvider===Ce&&Dt.current.modelId===ke))try{await P1(be,{initialPlan:rt,modelProvider:Ce&&ke?Ce:void 0,modelId:Ce&&ke?ke:void 0},l),Dt.current={sessionId:be,initialPlan:rt,modelProvider:Ce,modelId:ke}}catch{}},[ke,Ce,l]);i.useEffect(()=>{if(Mt.current&&(clearTimeout(Mt.current),Mt.current=null),!(!e||m.type!=="initial"||!le))return Mt.current=setTimeout(()=>{jt(le,d)},500),()=>{Mt.current&&(clearTimeout(Mt.current),Mt.current=null)}},[d,e,le,jt,m.type]),i.useEffect(()=>{Dt.current=null},[le]),i.useEffect(()=>()=>{Mt.current&&(clearTimeout(Mt.current),Mt.current=null)},[]);const ae=i.useCallback(async be=>{const it=at=>at==="generating"||at==="awaiting_input",rt=Ie.find(at=>at.id===be);if(rt&&it(rt.status))try{await Ig(be,l,je)}catch{}try{await Bg(be)}catch{}re({sessionId:be,status:"complete",timestamp:Date.now()}),Ue(at=>at.filter(ut=>ut.id!==be)),le===be&&(A.current?.close(),A.current=null,Jt(),ge(null),ue(!1)),me(null)},[re,Ie,l,Jt,le,je]),Le=i.useCallback(async be=>{const rt=Ie.find(at=>at.id===be)?.archived===!0;try{rt?await C1(be):await S1(be)}catch{return}Ue(at=>!rt&&!tt?at.filter(ut=>ut.id!==be):at.map(ut=>ut.id===be?{...ut,archived:!rt}:ut)),!rt&&le===be&&!tt&&(A.current?.close(),A.current=null,Jt(),ge(null),ue(!1))},[Ie,Jt,le,ue,tt]);i.useEffect(()=>{e||(k.current=!1,C.current=!1,R(!1),F(!1),Se(null))},[e]),i.useEffect(()=>{if(!e){xt.current&&(B(xt.current,je),xt.current=null);return}if(xe&&xt.current!==xe){xt.current&&B(xt.current,je),J(xe,je),xt.current=xe;return}!xe&&xt.current&&(B(xt.current,je),xt.current=null)},[J,B,e,xe,je]),i.useEffect(()=>{if(!e||!xe||xt.current!==xe)return;ye(je);const be=setInterval(()=>{ye(je)},3e4);return()=>{clearInterval(be)}},[ye,e,xe,je]),i.useEffect(()=>()=>{N.current&&(clearTimeout(N.current),N.current=null),A.current?.close(),A.current=null,xt.current&&(B(xt.current,je),xt.current=null)},[B,je]),i.useEffect(()=>{if(!e)return;const be=()=>{A.current?.close(),A.current=null};return window.addEventListener("beforeunload",be),()=>window.removeEventListener("beforeunload",be)},[e]);const At=i.useCallback((be,it)=>{Mt.current&&(clearTimeout(Mt.current),Mt.current=null),(async()=>{try{await jt(be,it),await R1(be,l)}catch{}})()},[l,jt]),Lt=i.useCallback(()=>{if(Qt!=="mobile")return;const be=document.activeElement;be instanceof HTMLElement&&be.blur(),window.scrollTo(0,0),requestAnimationFrame(()=>{window.scrollTo(0,0)})},[Qt]),Ft=i.useCallback(()=>{d&&m.type==="initial"&&nT(d,l);const be=$.current;be&&d.trim()&&At(be,d),$.current=null,N.current&&(clearTimeout(N.current),N.current=null),A.current?.close(),A.current=null,R(!1),F(!1),Lt(),n()},[At,d,n,l,Lt,m.type]);i.useEffect(()=>{if(!e)return;const be=it=>{it.key==="Escape"&&Ft()};return document.addEventListener("keydown",be),()=>document.removeEventListener("keydown",be)},[e,Ft]);const Me=i.useCallback(async be=>{if(m.type!=="question")return;const{session:it}=m,rt=it.sessionId,at=it.currentQuestion;if(!at){p("No active question in session");return}p(null),x(ut=>[...ut,be]),b(ut=>{const vt=Vt.current.trim();let ie=ut;return vt&&ie[ie.length-1]?.thinkingOutput!==vt&&(ie=[...ie,{thinkingOutput:vt}]),[...ie,{question:at,response:be}]}),h({type:"loading"}),j("");try{await pm(rt,be,l,je)}catch(ut){p(Pe(ut)||"Failed to submit response"),h({type:"question",session:it})}},[l,je,m]),ct=i.useCallback(async()=>{if(m.type!=="summary")return;const{session:be,summary:it}=m,rt=be.sessionId;I.current=rt,Se(rt),p(null),F(!1),j(""),h({type:"loading"}),ve(rt);try{await pm(rt,{refine:!0},l,je)}catch(at){A.current?.close(),A.current=null,p(Pe(at)||"Failed to refine plan"),h({type:"summary",session:be,summary:y??it})}},[ve,y,l,je,m]),gt=i.useCallback(async()=>{const be=I.current;if(be){try{await CN(be,l,je)}catch{}A.current?.close(),A.current=null,R(!1),F(!1),h({type:"error",session:{sessionId:be,currentQuestion:null,summary:null},errorMessage:"Generation stopped by user. You can retry or start a new session."}),j("")}},[l,je]),_t=i.useCallback(async()=>{if(m.type!=="error")return;const be=m.session;p(null),F(!0),j(""),h({type:"loading"}),ve(be.sessionId);try{I.current=be.sessionId,Se(be.sessionId),await SN(be.sessionId,l,je)}catch(it){let rt=it;if((Pe(it)||"").includes("not in an error state"))try{const ut=await Ci(be.sessionId);if(!ut)throw new Error("Failed to refresh planning session.");if(I.current=ut.id,Se(ut.id),ut.status==="generating")j(ut.thinkingOutput??""),h({type:"loading"});else if(ut.status==="awaiting_input"){if(!ut.currentQuestion)throw new Error("Planning session is awaiting input but has no current question.");const vt=JSON.parse(ut.currentQuestion);if(Xa(l),h({type:"question",session:{sessionId:ut.id,currentQuestion:vt,summary:null}}),ut.thinkingOutput){const ie=ut.thinkingOutput.trim();ie&&b(st=>st[st.length-1]?.thinkingOutput===ie?st:[...st,{thinkingOutput:ie}])}A.current?.isConnected()||ve(ut.id)}else if(ut.status==="complete"){if(!ut.result)throw new Error("Planning session is complete but has no result.");const vt=dd(JSON.parse(ut.result));Xa(l),h({type:"summary",session:{sessionId:ut.id,currentQuestion:null,summary:vt},summary:vt}),S(vt)}else ut.status==="error"&&h({type:"error",session:{sessionId:ut.id,currentQuestion:null,summary:null},errorMessage:ut.error||"Retry failed. Please try again."});R(!1);return}catch(ut){rt=ut}A.current?.close(),A.current=null,h({type:"error",session:be,errorMessage:Pe(rt)||"Retry failed. Please try again."}),R(!1)}finally{F(!1)}},[ve,l,je,m]),Yt=i.useCallback(async()=>{if(m.type==="summary"){p(null),h({type:"loading"});try{const be=m.session.sessionId,it=await EN(be,y??void 0,l);s(it),ge(null),Ue(rt=>rt.filter(at=>at.id!==be)),re({sessionId:be,status:"complete",timestamp:Date.now()}),Ft()}catch(be){p(Pe(be)||"Failed to create task"),h({type:"summary",session:m.session,summary:m.summary})}}},[re,y,m,l,s,Ft]),Xt=i.useCallback(async()=>{if(m.type==="summary"){p(null),h({type:"loading"});try{const be=await _N(m.session.sessionId,y??void 0,l);Se(be.sessionId),h({type:"breakdown",sessionId:be.sessionId,subtasks:be.subtasks.map(it=>({...it,priority:go(it.priority)})),dirty:!1})}catch(be){p(Pe(be)||"Failed to start breakdown"),h({type:"summary",session:m.session,summary:m.summary})}}},[y,m,l]),Te=i.useCallback(async()=>{if(m.type==="breakdown"){p(null),h({type:"creating"});try{const be=m.sessionId,it=await MN(be,m.subtasks.map(rt=>({...rt,priority:go(rt.priority)})),l);a(it.tasks),Ue(rt=>rt.filter(at=>at.id!==be)),re({sessionId:be,status:"complete",timestamp:Date.now()}),u(""),h({type:"initial"}),p(null),x([]),b([]),S(null),j(""),H(void 0),pe(void 0),Oe("medium"),dt(""),I.current=null,Se(null),ge(null),Ft()}catch(be){p(Pe(be)||"Failed to create tasks"),h({type:"breakdown",sessionId:m.sessionId,subtasks:m.subtasks,dirty:m.dirty})}}},[re,Ft,m,a,l]),Je=i.useCallback(async()=>{if(m.type!=="question"||g.length===0)return;const be=m.session.sessionId;p(null),h({type:"loading"});try{const it=await NN(be,l,je);x(it.history.map(rt=>rt.response&&typeof rt.response=="object"&&!Array.isArray(rt.response)?rt.response:{[rt.question.id]:rt.response})),b(it.history.map(rt=>({question:rt.question,response:rt.response&&typeof rt.response=="object"&&!Array.isArray(rt.response)?rt.response:{[rt.question.id]:rt.response},thinkingOutput:rt.thinkingOutput}))),j(""),h({type:"question",session:{...m.session,currentQuestion:it.currentQuestion,summary:null}})}catch(it){p(Pe(it)||"Failed to go back to the previous question"),h({type:"question",session:m.session})}},[l,g.length,je,m]),Nt=()=>m.type==="question"?Math.min(g.length+1,3):3,Ut=xe?ce.get(xe):null,tn=Ut&&Ut.tabId!==je,Xn=se&&(!tn||Ut.stale);return e?t.jsx("div",{className:"modal-overlay open",onMouseDown:be=>{wt.current=be.target===be.currentTarget},onClick:be=>{be.target===be.currentTarget&&wt.current&&Ft(),wt.current=!1},role:"dialog","aria-modal":"true",children:t.jsxs("div",{className:"modal modal-lg planning-modal",ref:K,children:[t.jsxs("div",{className:"modal-header",children:[t.jsxs("div",{className:"detail-title-row",children:[Ne&&t.jsx("button",{className:"modal-back planning-mobile-back",onClick:Ht,"aria-label":"Back to sessions",title:"Back to sessions",children:t.jsx(Vl,{size:18})}),t.jsx(_i,{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:Ft,"aria-label":"Close",children:t.jsx(nn,{size:20})})})]}),t.jsxs("div",{className:`planning-modal-body planning-modal-body--split ${Ne?"planning-modal-body--show-detail":"planning-modal-body--show-list"}`,children:[t.jsx(s4,{sessions:Ie,loading:pt,selectedSessionId:le,pendingDeleteId:qe,showArchived:tt,onToggleShowArchived:()=>Ct(be=>!be),onArchive:be=>void Le(be),onSelectSession:It,onNewSession:St,onRequestDelete:me,onConfirmDelete:be=>void ae(be),onCancelDelete:()=>me(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…"}),m.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(ps,{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:Z,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:be=>{const it=be.target.value;u(it),!($.current||it.trim().length===0)&&(N.current&&clearTimeout(N.current),N.current=setTimeout(()=>{if($.current)return;const rt=it.trim();if(!rt)return;kN(rt,l,Ce&&ke?{planningModelProvider:Ce,planningModelId:ke}:void 0).then(ut=>{$.current=ut.sessionId,Ue(vt=>vt.some(st=>st.id===ut.sessionId)?vt:[{id:ut.sessionId,type:"planning",status:"draft",title:ut.title,preview:rt.length>80?`${rt.slice(0,79).trimEnd()}…`:rt,projectId:l??null,lockedByTab:null,updatedAt:new Date().toISOString(),archived:!1},...vt].sort((st,Gt)=>Date.parse(Gt.updatedAt)-Date.parse(st.updatedAt))),ge(ut.sessionId)}).catch(()=>{})},300))},onKeyDown:be=>{be.key==="Enter"&&!be.shiftKey&&d.trim()&&(be.preventDefault(),ze())},onBlur:()=>{const be=$.current;be&&d.trim()&&At(be,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:JT.map((be,it)=>t.jsx("button",{className:"planning-example-chip",onClick:()=>u(be),children:be.length>40?be.slice(0,40)+"...":be},it))})]}),t.jsx(ti,{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",$e&&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(ys,{id:"planning-modal-model",label:"Planning Model",value:an,onChange:be=>{const{provider:it,modelId:rt}=QT(be);H(it),pe(rt)},models:Fe,disabled:$e,favoriteProviders:we,onToggleFavorite:Zt,favoriteModels:_e,onToggleModelFavorite:dn}),ot&&t.jsxs("div",{className:"form-hint form-hint-error",children:[ot," ",t.jsx("button",{type:"button",className:"text-link-btn",onClick:()=>{en()},children:"Retry"})]}),t.jsx("div",{className:"model-selector-current model-selector-current--spaced",children:t.jsx("span",{className:`model-badge ${Ce&&ke?"model-badge-custom":"model-badge-default"}`,children:zt(Ce,ke)})})]}),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(be=>t.jsx("button",{type:"button",className:`planning-depth-chip btn ${Ae===be.value?"btn-primary planning-depth-chip-active":""}`,onClick:()=>Oe(be.value),"aria-pressed":Ae===be.value,children:be.label},be.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:He,onChange:be=>dt(be.target.value),placeholder:"Auto"})]})]})]})]})})]}),t.jsx("div",{className:"planning-view-footer",children:t.jsxs("button",{className:"btn btn-primary planning-start-btn",onClick:()=>ze(),disabled:!d.trim(),children:[t.jsx(_i,{size:16,className:"icon-mr-8"}),"Start Planning"]})})]}),m.type==="loading"&&t.jsxs("div",{className:"planning-loading",children:[t.jsx(bt,{size:40,className:"spin icon-todo"}),t.jsx("p",{children:v?"AI is thinking...":"Generating next question..."}),M&&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:()=>U(!P),type:"button",children:P?"Hide thinking":"Show thinking"}),t.jsx("div",{className:"planning-loading-actions",children:t.jsxs("button",{className:"btn planning-stop-btn",type:"button",onClick:()=>void gt(),children:[t.jsx(iy,{size:14}),t.jsx("span",{className:"icon-ml-6",children:"Stop"})]})}),P&&v&&t.jsx("div",{className:"planning-thinking-output",ref:$t,children:t.jsx("pre",{children:v})})]})]}),m.type==="error"&&t.jsx("div",{className:"planning-summary",children:t.jsxs("div",{className:"planning-view-scroll planning-summary-scroll",children:[w.length>0&&t.jsxs(t.Fragment,{children:[t.jsx(si,{entries:w}),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:m.errorMessage}),t.jsxs("div",{className:"ai-error-actions",children:[t.jsxs("button",{className:"btn btn-primary",onClick:()=>void _t(),disabled:L,children:[L?t.jsx(bt,{size:14,className:"spin"}):t.jsx(os,{size:14}),t.jsx("span",{className:"icon-ml-6",children:L?"Retrying...":"Retry"})]}),t.jsx("button",{className:"btn",onClick:Ft,disabled:L,children:"Dismiss"})]})]})]})}),m.type==="creating"&&t.jsxs("div",{className:"planning-loading",children:[t.jsx(bt,{size:40,className:"spin icon-todo"}),t.jsx("p",{children:"Creating tasks..."})]}),m.type==="question"&&m.session.currentQuestion&&t.jsx("div",{className:"planning-question",children:t.jsx(ZT,{question:m.session.currentQuestion,progress:Nt(),historyEntries:w,onSubmit:Me,onBack:g.length>0?Je:void 0})}),m.type==="summary"&&y&&t.jsx(e4,{summary:y,historyEntries:w,onSummaryChange:S,tasks:r,onCreateTask:Yt,onBreakIntoTasks:Xt,onRefine:()=>{ct()},isLoading:!1}),m.type==="breakdown"&&t.jsx(n4,{subtasks:m.subtasks,dirty:m.dirty,isLoading:!1,onUpdateSubtasks:be=>h({...m,subtasks:be,dirty:!0}),onCreateTasks:Te,onBack:()=>{const it={sessionId:m.sessionId,currentQuestion:null,summary:y??null};y&&h({type:"summary",session:it,summary:y})}})]}),se&&t.jsx("div",{className:"session-lock-overlay","data-testid":"session-lock-overlay",children:t.jsxs("div",{className:"session-lock-banner",children:[t.jsx(Ql,{size:16}),t.jsx("span",{children:Xn?"This session is active in another tab":"This session is active in another tab (live heartbeat)"}),Xn&&t.jsx("button",{type:"button",onClick:()=>{Ve()},disabled:ee,className:"btn btn-primary session-lock-take-control",children:ee?"Taking control...":"Take Control"})]})})]})]})}):null}function ZT({question:e,progress:n,historyEntries:s,onSubmit:a,onBack:r}){const[o,l]=i.useState({}),[c,d]=i.useState(""),[u,m]=i.useState(""),h=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(""),m("")},[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(si,{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(),h())}}),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:x=>{const w=x.target.checked?[...g,p.id]:g.filter(b=>b!==p.id);l({[e.id]:w})}}),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(Dn,{size:18}),"Yes"]}),t.jsxs("button",{className:`planning-confirm-btn ${o[e.id]===!1?"selected":""}`,onClick:()=>l({[e.id]:!1}),children:[t.jsx(nn,{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=>m(p.target.value)})]})]})]})]}),t.jsxs("div",{className:"planning-actions",children:[r&&t.jsxs("button",{className:"btn",onClick:r,children:[t.jsx(Aa,{size:16,className:"icon-mr-4"}),"Back"]}),t.jsxs("button",{className:"btn btn-primary planning-actions-primary",onClick:h,disabled:!f(),children:["Continue",t.jsx(yo,{size:16,className:"icon-ml-4"})]})]})]})}function e4({summary:e,historyEntries:n,onSummaryChange:s,tasks:a,onCreateTask:r,onBreakIntoTasks:o,onRefine:l,isLoading:c}){const[d,u]=i.useState(!1),[m,h]=i.useState(e.suggestedDependencies),f=go(e.priority),p=g=>{const x=m.includes(g)?m.filter(w=>w!==g):[...m,g];h(x),s({...e,suggestedDependencies:x})};return t.jsxs("div",{className:"planning-summary",children:[t.jsxs("div",{className:"planning-view-scroll planning-summary-scroll",children:[n.length>0&&t.jsxs(ti,{summary:"Show user Q&A",className:"planning-summary-qa-disclosure",children:[t.jsx(si,{entries:n}),t.jsx("div",{className:"conversation-separator"})]}),t.jsxs("div",{className:"planning-summary-header",children:[t.jsx(Dn,{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:oa.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 ${m.includes(g.id)?"selected":""}`,children:[t.jsx("input",{type:"checkbox",checked:m.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,x)=>t.jsx("li",{children:g},x))})]})]})]}),t.jsxs("div",{className:"planning-actions planning-summary-actions",children:[t.jsxs("button",{className:"btn",onClick:l,disabled:c,children:[t.jsx(Aa,{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(bt,{size:16,className:"spin icon-mr-8"}),"Creating..."]}):t.jsxs(t.Fragment,{children:[t.jsx(Dn,{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(bt,{size:16,className:"spin icon-mr-8"}),"Breaking down..."]}):t.jsxs(t.Fragment,{children:[t.jsx(Yl,{size:16,className:"icon-mr-8"}),"Break into Tasks"]})})]})]})]})}function ef(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 t4(e){return{id:`subtask-${e}`,title:"",description:"",suggestedSize:"M",priority:js,dependsOn:[]}}function n4({subtasks:e,dirty:n,isLoading:s,onUpdateSubtasks:a,onCreateTasks:r,onBack:o}){const[l,c]=i.useState(null),[d,u]=i.useState(null),[m,h]=i.useState(null),f=i.useRef([]),p=i.useMemo(()=>e.length===0||e.some(j=>!j.title.trim())?!0:ef(e),[e]),g=i.useCallback((j,P)=>{a(e.map(U=>U.id===j?{...U,...P}:U))},[e,a]),x=i.useCallback(()=>{a([...e,t4(e.length+1)])},[e,a]),w=i.useCallback(j=>{a(e.filter(P=>P.id!==j).map(P=>({...P,dependsOn:P.dependsOn.filter(U=>U!==j)})))},[e,a]),b=i.useCallback((j,P)=>{if(P<0||P>=e.length)return;const U=[...e],[E]=U.splice(j,1);U.splice(P,0,E),a(U)},[e,a]),y=i.useCallback(j=>P=>{c(j),P.dataTransfer.setData("text/plain",j),P.dataTransfer.effectAllowed="move"},[]),S=i.useCallback(()=>{c(null),u(null),h(null)},[]),k=i.useCallback(j=>P=>{if(P.preventDefault(),j===l)return;const U=P.currentTarget.getBoundingClientRect(),E=U.top+U.height/2,R=P.clientY<E?"before":"after";u(j),h(R)},[l]),C=i.useCallback(j=>P=>{P.preventDefault();const U=P.dataTransfer.getData("text/plain");if(!U||U===j){S();return}const E=e.findIndex(O=>O.id===U),R=e.findIndex(O=>O.id===j);if(E===-1||R===-1){S();return}const L=[...e],[F]=L.splice(E,1);let M=R;m==="after"&&E<R&&M--,m==="after"&&M++,L.splice(M,0,F),a(L),S()},[e,m,a,S]),v=i.useCallback(j=>{const P=j.currentTarget.getBoundingClientRect(),U=j.clientX,E=j.clientY;(U<P.left||U>P.right||E<P.top||E>P.bottom)&&(u(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(Yl,{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((j,P)=>{const U=l===j.id,E=d===j.id,R=["task-detail-section","subtask-item",U?"subtask-item-dragging":"",E?"subtask-item-drop-target":"",E&&m==="before"?"subtask-item-drop-before":"",E&&m==="after"?"subtask-item-drop-after":""].filter(Boolean).join(" ");return t.jsxs("div",{className:R,"data-testid":`subtask-item-${P}`,draggable:!s,onDragStart:y(j.id),onDragEnd:S,onDragOver:k(j.id),onDrop:C(j.id),onDragLeave:v,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(Jl,{size:16}),t.jsx("strong",{children:j.id})]}),t.jsxs("div",{className:"subtask-item-actions",children:[t.jsx("button",{type:"button",className:"btn btn-icon btn-sm",onClick:()=>b(P,P-1),disabled:s||P===0,title:"Move up","aria-label":"Move subtask up",children:t.jsx(ka,{size:14})}),t.jsx("button",{type:"button",className:"btn btn-icon btn-sm",onClick:()=>b(P,P+1),disabled:s||P===e.length-1,title:"Move down","aria-label":"Move subtask down",children:t.jsx(vo,{size:14})}),t.jsxs("button",{type:"button",className:"btn btn-sm",onClick:()=>w(j.id),disabled:s,children:[t.jsx(vn,{size:14})," Remove"]})]})]}),t.jsxs("div",{className:"form-group",children:[t.jsx("label",{children:"Title"}),t.jsx("input",{ref:L=>{f.current[P]=L},value:j.title,onChange:L=>g(j.id,{title:L.target.value}),onKeyDown:L=>{L.key==="Enter"&&(L.preventDefault(),P<e.length-1&&f.current[P+1]?.focus())},disabled:s})]}),t.jsxs("div",{className:"form-group",children:[t.jsx("label",{children:"Description"}),t.jsx("textarea",{rows:3,value:j.description,onChange:L=>g(j.id,{description:L.target.value}),disabled:s})]}),t.jsxs("div",{className:"planning-summary-meta-row",children:[t.jsxs("div",{className:"form-group",children:[t.jsx("label",{htmlFor:`${j.id}-size`,children:"Size"}),t.jsxs("select",{id:`${j.id}-size`,className:"planning-size-select",value:j.suggestedSize,onChange:L=>g(j.id,{suggestedSize:L.target.value}),disabled:s,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:`${j.id}-priority`,children:"Priority"}),t.jsx("select",{id:`${j.id}-priority`,className:"planning-size-select",value:go(j.priority),onChange:L=>g(j.id,{priority:L.target.value}),disabled:s,children:oa.map(L=>t.jsx("option",{value:L,children:L[0].toUpperCase()+L.slice(1)},L))})]})]}),t.jsxs("div",{className:"form-group",children:[t.jsx("label",{children:"Dependencies"}),t.jsxs("div",{className:"planning-deps-list",children:[e.slice(0,P).filter(L=>L.id!==j.id).map(L=>{const F=j.dependsOn.includes(L.id);return t.jsxs("label",{className:`planning-dep-chip ${F?"selected":""}`,children:[t.jsx("input",{type:"checkbox",checked:F,onChange:()=>{const M=F?j.dependsOn.filter(O=>O!==L.id):[...j.dependsOn,L.id];g(j.id,{dependsOn:M})},disabled:s}),t.jsx("span",{className:"planning-dep-id",children:L.id}),t.jsx("span",{className:"planning-dep-title",children:L.title||"Untitled"})]},L.id)}),P===0&&t.jsx("div",{className:"text-muted",children:"First subtask cannot have dependencies."}),P>0&&e.slice(0,P).filter(L=>L.id!==j.id).length===0&&t.jsx("div",{className:"text-muted",children:"No previous subtasks available."})]})]})]},j.id)}),t.jsxs("button",{type:"button",className:"btn",onClick:x,disabled:s,children:[t.jsx(gn,{size:16,className:"icon-mr-6"})," Add subtask"]}),ef(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:o,disabled:s,children:[t.jsx(Aa,{size:16,className:"icon-mr-4"}),"Back to Summary"]}),t.jsx("button",{className:"btn btn-primary",onClick:r,disabled:s||p,children:s?t.jsxs(t.Fragment,{children:[t.jsx(bt,{size:16,className:"spin icon-mr-6"}),"Creating..."]}):t.jsx(t.Fragment,{children:"Create Tasks"})})]})]})}function s4({sessions:e,loading:n,selectedSessionId:s,pendingDeleteId:a,showArchived:r,onToggleShowArchived:o,onArchive:l,onSelectSession:c,onNewSession:d,onRequestDelete:u,onConfirmDelete:m,onCancelDelete:h}){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(ww,{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,x=f.archived===!0,w=f.status==="complete"||f.status==="error";return t.jsxs("div",{className:`planning-sidebar-item ${p?"selected":""} ${g?"pending-delete":""} ${x?"archived":""}`,children:[t.jsxs("button",{type:"button",className:"planning-sidebar-item-button",onClick:()=>c(f.id),children:[t.jsx(i4,{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(a4,{status:f.status}),t.jsx("span",{"aria-hidden":!0,children:" · "}),t.jsx("span",{children:r4(f.updatedAt)})]})]})]}),g?t.jsxs("div",{className:"planning-sidebar-confirm",children:[t.jsx("button",{type:"button",className:"btn btn-sm btn-danger",onClick:()=>m(f.id),children:"Delete"}),t.jsx("button",{type:"button",className:"btn btn-sm",onClick:h,children:"Cancel"})]}):t.jsxs("div",{className:"planning-sidebar-item-actions",children:[w&&t.jsx("button",{type:"button",className:"planning-sidebar-item-archive",onClick:b=>{b.stopPropagation(),l(f.id)},"aria-label":x?"Unarchive session":"Archive session",title:x?"Unarchive session":"Archive session",children:x?t.jsx(Tv,{size:14}):t.jsx(xo,{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(vn,{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 i4({status:e}){switch(e){case"generating":return t.jsx(bt,{size:14,className:"spin planning-sidebar-status-icon planning-sidebar-status-generating"});case"awaiting_input":return t.jsx(Cd,{size:14,className:"planning-sidebar-status-icon planning-sidebar-status-awaiting"});case"complete":return t.jsx(Dn,{size:14,className:"planning-sidebar-status-icon planning-sidebar-status-complete"});case"error":return t.jsx(Ps,{size:14,className:"planning-sidebar-status-icon planning-sidebar-status-error"});default:return t.jsx(Hi,{size:14,className:"planning-sidebar-status-icon"})}}function a4({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 r4(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 o4(e){return{id:`subtask-${e}`,title:"",description:"",suggestedSize:"M",dependsOn:[]}}function tf(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 l4({isOpen:e,onClose:n,initialDescription:s,onTasksCreated:a,parentTaskId:r,projectId:o,resumeSessionId:l}){const c=Ys();vi(e);const{keyboardOverlap:d,viewportHeight:u,viewportOffsetTop:m,keyboardOpen:h}=Wi({enabled:c==="mobile"}),f=h?{"--keyboard-overlap":`${d}px`,"--vv-offset-top":`${m}px`,...u!==null?{"--vv-height":`${u}px`}:{}}:{},[p,g]=i.useState({type:"initial"}),[x,w]=i.useState([]),[b,y]=i.useState([]),[S,k]=i.useState(""),[C,v]=i.useState(!0),[j,P]=i.useState(!1),[U,E]=i.useState(!1),[R,L]=i.useState(s),[F,M]=i.useState(null),[O,q]=i.useState(!1),[te,Z]=i.useState(null),[K,A]=i.useState(null),[I,$]=i.useState(null),N=i.useRef(null),G=i.useRef([]),xe=i.useRef(!1),Se=i.useRef(null),je=p.type==="generating"||p.type==="editing"||p.type==="creating"||p.type==="error"?p.sessionId:null,se=i.useMemo(()=>Ia(),[]),{isLockedByOther:Ve,takeControl:ee,isLoading:ce}=cc(e?je:null),{activeTabMap:ne,broadcastUpdate:re,broadcastCompleted:J,broadcastLock:B,broadcastUnlock:ye,broadcastHeartbeat:Ce}=_r(),H=i.useMemo(()=>x.length===0||x.some(le=>!le.title.trim())?!0:tf(x),[x]),ke=p.type==="generating"||p.type==="editing"||p.type==="error",pe=je?ne.get(je):null,{confirm:Ae}=ai(),Oe=pe&&pe.tabId!==se,He=!!(Oe&&!pe.stale),dt=Ve&&(!Oe||pe.stale),Fe=i.useCallback(()=>{R&&iT(R,o),N.current?.close(),N.current=null,g({type:"initial"}),w([]),y([]),k(""),v(!0),P(!1),E(!1),M(null),q(!1),xe.current=!1},[R,o]),fe=i.useCallback(()=>{N.current?.close(),N.current=null,n()},[n]),$e=i.useCallback(async()=>{if(!((O||p.type==="editing"||p.type==="creating")&&!await Ae({title:"Discard Changes",message:"Close subtask breakdown? Unsaved changes will be lost.",danger:!0}))){if(je)try{await Dg(je,o,se)}catch{}Fe(),n()}},[O,n,Fe,je,se,p.type,o,Ae]),De=i.useCallback(le=>{N.current?.close(),N.current=iS(le,o,{onThinking:ge=>{k(Ne=>Ne+ge),re({sessionId:le,status:"generating",needsInput:!1,owningTabId:se,type:"subtask",title:R.trim()||void 0,projectId:o??null})},onSubtasks:ge=>{P(!1),E(!1),td(o),w(ge),g({type:"editing",sessionId:le}),q(!1),re({sessionId:le,status:"awaiting_input",needsInput:!0,owningTabId:se,type:"subtask",title:R.trim()||void 0,projectId:o??null})},onError:ge=>{const Ne=ge||"Session failed while contacting the AI.";P(!1),E(!1),M(null),g({type:"error",sessionId:le,errorMessage:Ne}),re({sessionId:le,status:"error",needsInput:!1,owningTabId:se,type:"subtask",title:R.trim()||void 0,projectId:o??null}),J({sessionId:le,status:"error"})},onComplete:()=>{J({sessionId:le,status:"complete"})},onConnectionStateChange:ge=>{P(ge==="reconnecting")}})},[J,re,R,o,se]),ot=i.useCallback(async()=>{if(R.trim()){M(null),y([]),k(""),P(!1);try{const{sessionId:le}=await tS(R.trim(),o);g({type:"generating",sessionId:le}),De(le)}catch(le){M(Pe(le)||"Failed to start subtask breakdown"),g({type:"initial"})}}},[De,R,o]);i.useEffect(()=>{if(!e){Fe();return}if(e&&s&&!xe.current)L(s),xe.current=!0,ot();else if(e&&!s&&!xe.current){const le=aT(o);le&&L(le)}},[e,s,ot,Fe]),i.useEffect(()=>{!e||!l||p.type!=="initial"||(async()=>{try{const le=await Ci(l);if(!le)return;const ge=hr(le.conversationHistory);if(y(ge),le.status==="generating"||le.status==="awaiting_input")k(le.thinkingOutput??""),g({type:"generating",sessionId:l}),De(l);else if(le.status==="complete"&&le.result){td(o);const Ne=JSON.parse(le.result);w(Ne),g({type:"editing",sessionId:l})}else le.status==="error"&&(M(null),g({type:"error",sessionId:l,errorMessage:le.error??"Session encountered an error"}))}catch(le){M(Pe(le)||"Failed to resume session")}})()},[De,e,l,p.type,o]),i.useEffect(()=>{if(!e){Se.current&&(ye(Se.current,se),Se.current=null);return}if(je&&Se.current!==je){Se.current&&ye(Se.current,se),B(je,se),Se.current=je;return}!je&&Se.current&&(ye(Se.current,se),Se.current=null)},[B,ye,e,je,se]),i.useEffect(()=>{if(!e||!je||Se.current!==je)return;Ce(se);const le=setInterval(()=>{Ce(se)},3e4);return()=>{clearInterval(le)}},[Ce,e,je,se]),i.useEffect(()=>()=>{N.current?.close(),Se.current&&(ye(Se.current,se),Se.current=null)},[ye,se]),i.useEffect(()=>{if(!e)return;const le=ge=>{ge.key==="Escape"&&(ge.preventDefault(),$e())};return document.addEventListener("keydown",le),()=>document.removeEventListener("keydown",le)},[e,$e]);const Be=i.useCallback((le,ge)=>{w(Ne=>Ne.map(ue=>ue.id===le?{...ue,...ge}:ue)),q(!0)},[]),we=i.useCallback(()=>{w(le=>[...le,o4(le.length+1)]),q(!0)},[]),Q=i.useCallback(le=>{w(ge=>ge.filter(Ne=>Ne.id!==le).map(Ne=>({...Ne,dependsOn:Ne.dependsOn.filter(ue=>ue!==le)}))),q(!0)},[]),_e=i.useCallback(le=>ge=>{Z(le),ge.dataTransfer.setData("text/plain",le),ge.dataTransfer.effectAllowed="move"},[]),lt=i.useCallback(()=>{Z(null),A(null),$(null)},[]),ht=i.useCallback(le=>ge=>{if(ge.preventDefault(),le===te)return;const Ne=ge.currentTarget.getBoundingClientRect(),ue=Ne.top+Ne.height/2,qe=ge.clientY<ue?"before":"after";A(le),$(qe)},[te]),mt=i.useCallback(le=>ge=>{ge.preventDefault();const Ne=ge.dataTransfer.getData("text/plain");if(!Ne||Ne===le){Z(null),A(null),$(null);return}w(ue=>{const qe=ue.findIndex($t=>$t.id===Ne),me=ue.findIndex($t=>$t.id===le);if(qe===-1||me===-1)return ue;const tt=[...ue],[Ct]=tt.splice(qe,1);let wt=me;return I==="after"&&qe<me&&wt--,I==="after"&&wt++,tt.splice(wt,0,Ct),tt}),q(!0),Z(null),A(null),$(null)},[I]),xt=i.useCallback(le=>{const ge=le.currentTarget.getBoundingClientRect(),Ne=le.clientX,ue=le.clientY;(Ne<ge.left||Ne>ge.right||ue<ge.top||ue>ge.bottom)&&(A(null),$(null))},[]),Ie=i.useCallback((le,ge)=>{ge<0||ge>=x.length||(w(Ne=>{const ue=[...Ne],[qe]=ue.splice(le,1);return ue.splice(ge,0,qe),ue}),q(!0))},[x.length]),Ue=i.useCallback(le=>{G.current[le+1]?.focus()},[]),pt=i.useCallback(async()=>{if(!(!je||H)){M(null),g({type:"creating",sessionId:je});try{const le=await aS(je,x,r,o);a(le.tasks),Fe(),n()}catch(le){M(Pe(le)||"Failed to create tasks"),g({type:"editing",sessionId:je})}}},[H,n,a,r,o,Fe,je,x]),oe=i.useCallback(async()=>{if(p.type!=="error")return;const le=p.sessionId;M(null),E(!0),k(""),g({type:"generating",sessionId:le}),De(le);try{await nS(le,o,se)}catch(ge){let Ne=ge;if((Pe(ge)||"").includes("not in an error state"))try{const qe=await Ci(le);if(!qe)throw new Error("Failed to refresh subtask session.");if(y(hr(qe.conversationHistory)),qe.status==="generating"||qe.status==="awaiting_input")k(qe.thinkingOutput??""),g({type:"generating",sessionId:qe.id}),N.current?.isConnected()||De(qe.id);else if(qe.status==="complete"){if(!qe.result)throw new Error("Subtask session is complete but has no result.");td(o);const me=JSON.parse(qe.result);w(me),g({type:"editing",sessionId:qe.id}),q(!1)}else qe.status==="error"&&g({type:"error",sessionId:qe.id,errorMessage:qe.error??"Retry failed. Please try again."});P(!1);return}catch(qe){Ne=qe}N.current?.close(),N.current=null,g({type:"error",sessionId:le,errorMessage:Pe(Ne)||"Retry failed. Please try again."}),P(!1)}finally{E(!1)}},[De,o,se,p]);return e?t.jsx("div",{className:"modal-overlay open",onClick:le=>le.target===le.currentTarget&&void $e(),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(Yl,{size:20,className:"icon-triage"}),t.jsx("h3",{children:"Subtask Breakdown"})]}),t.jsxs("div",{className:"modal-header-actions",children:[ke&&t.jsx("button",{className:"modal-send-to-background",onClick:fe,title:"Send to background","aria-label":"Send to background",children:t.jsx(jo,{size:16})}),t.jsx("button",{className:"modal-close",onClick:()=>void $e(),"aria-label":"Close",children:t.jsx(nn,{size:20})})]})]}),t.jsxs("div",{className:"planning-modal-body",children:[F&&t.jsx("div",{className:"form-error planning-error",children:F}),j&&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:R})]})}),p.type==="generating"&&t.jsxs("div",{className:"planning-loading",children:[b.length>0&&t.jsxs(t.Fragment,{children:[t.jsx(si,{entries:b,defaultShowThinking:!0}),t.jsx("div",{className:"conversation-separator"})]}),t.jsx(bt,{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:()=>v(!C),type:"button",children:C?"Hide thinking":"Show thinking"}),C&&S&&t.jsx("div",{className:"planning-thinking-output",children:t.jsx("pre",{children:S})})]})]}),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(si,{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 oe(),disabled:U,children:[U?t.jsx(bt,{size:14,className:"spin"}):t.jsx(os,{size:14}),t.jsx("span",{className:"icon-ml-6",children:U?"Retrying...":"Retry"})]}),t.jsx("button",{className:"btn",onClick:()=>void $e(),disabled:U,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(si,{entries:b}),t.jsx("div",{className:"conversation-separator"})]}),t.jsxs("div",{className:"planning-summary-header",children:[t.jsx(Dn,{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:[x.map((le,ge)=>{const Ne=te===le.id,ue=K===le.id,qe=["task-detail-section","subtask-item",Ne?"subtask-item-dragging":"",ue?"subtask-item-drop-target":"",ue&&I==="before"?"subtask-item-drop-before":"",ue&&I==="after"?"subtask-item-drop-after":""].filter(Boolean).join(" ");return t.jsxs("div",{className:qe,"data-testid":`subtask-item-${ge}`,draggable:p.type!=="creating",onDragStart:_e(le.id),onDragEnd:lt,onDragOver:ht(le.id),onDrop:mt(le.id),onDragLeave:xt,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(Jl,{size:16}),t.jsx("strong",{children:le.id})]}),t.jsxs("div",{className:"subtask-item-actions",children:[t.jsx("button",{type:"button",className:"btn btn-icon btn-sm",onClick:()=>Ie(ge,ge-1),disabled:p.type==="creating"||ge===0,title:"Move up","aria-label":"Move subtask up",children:t.jsx(ka,{})}),t.jsx("button",{type:"button",className:"btn btn-icon btn-sm",onClick:()=>Ie(ge,ge+1),disabled:p.type==="creating"||ge===x.length-1,title:"Move down","aria-label":"Move subtask down",children:t.jsx(vo,{})}),t.jsxs("button",{type:"button",className:"btn btn-sm",onClick:()=>Q(le.id),disabled:p.type==="creating",children:[t.jsx(vn,{size:14})," Remove"]})]})]}),t.jsxs("div",{className:"form-group",children:[t.jsx("label",{children:"Title"}),t.jsx("input",{ref:me=>{G.current[ge]=me},value:le.title,onChange:me=>Be(le.id,{title:me.target.value}),onKeyDown:me=>{me.key==="Enter"&&(me.preventDefault(),Ue(ge))},disabled:p.type==="creating"})]}),t.jsxs("div",{className:"form-group",children:[t.jsx("label",{children:"Description"}),t.jsx("textarea",{rows:8,value:le.description,onChange:me=>Be(le.id,{description:me.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:le.suggestedSize,onChange:me=>Be(le.id,{suggestedSize:me.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:[x.slice(0,ge).filter(me=>me.id!==le.id).map(me=>{const tt=le.dependsOn.includes(me.id);return t.jsxs("label",{className:`planning-dep-chip ${tt?"selected":""}`,children:[t.jsx("input",{type:"checkbox",checked:tt,onChange:()=>{const Ct=tt?le.dependsOn.filter(wt=>wt!==me.id):[...le.dependsOn,me.id];Be(le.id,{dependsOn:Ct})},disabled:p.type==="creating"}),t.jsx("span",{className:"planning-dep-id",children:me.id}),t.jsx("span",{className:"planning-dep-title",children:me.title||"Untitled"})]},me.id)}),ge===0&&t.jsx("div",{className:"text-muted",children:"First subtask cannot have dependencies."}),ge>0&&x.slice(0,ge).filter(me=>me.id!==le.id).length===0&&t.jsx("div",{className:"text-muted",children:"No previous subtasks available."})]})]})]},le.id)}),t.jsxs("button",{type:"button",className:"btn",onClick:we,disabled:p.type==="creating",children:[t.jsx(gn,{size:16,className:"icon-mr-6"})," Add subtask"]}),tf(x)&&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 $e(),disabled:p.type==="creating",children:"Cancel"}),t.jsx("button",{className:"btn btn-primary",onClick:()=>void pt(),disabled:p.type==="creating"||H,children:p.type==="creating"?t.jsxs(t.Fragment,{children:[t.jsx(bt,{size:16,className:"spin icon-mr-6"}),"Creating..."]}):t.jsx(t.Fragment,{children:"Create Tasks"})})]})]}),Ve&&t.jsx("div",{className:"session-lock-overlay","data-testid":"session-lock-overlay",children:t.jsxs("div",{className:"session-lock-banner",children:[t.jsx(Ql,{size:16}),t.jsx("span",{children:dt?"This session is active in another tab":"This session is active in another tab (live heartbeat)"}),dt&&t.jsx("button",{type:"button",onClick:()=>{ee()},disabled:ce,className:"btn btn-primary session-lock-take-control",children:ce?"Taking control...":"Take Control"})]})})]})]})}):null}const c4=5,d4=1e3,u4=45e3;function ll(){return{scrollback:null,connected:null,data:[]}}function m4(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),m=i.useRef(null),h=i.useRef(null),f=i.useRef(!1),p=i.useRef(new Set),g=i.useRef(new Set),x=i.useRef(new Set),w=i.useRef(new Set),b=i.useRef(new Set),y=i.useRef(ll()),S=i.useCallback(M=>{p.current.add(M);const O=y.current;return O.data.length>0&&(O.data.forEach(q=>M(q)),O.data=[]),()=>p.current.delete(M)},[]),k=i.useCallback(M=>(g.current.add(M),()=>g.current.delete(M)),[]),C=i.useCallback(M=>{x.current.add(M);const O=y.current;return O.connected&&(M(O.connected),O.connected=null),()=>x.current.delete(M)},[]),v=i.useCallback(M=>{w.current.add(M);const O=y.current;return O.scrollback&&(M(O.scrollback),O.scrollback=null),()=>w.current.delete(M)},[]),j=i.useCallback(M=>(b.current.add(M),()=>b.current.delete(M)),[]),P=i.useCallback(M=>{const O=d.current;O?.readyState===WebSocket.OPEN&&O.send(JSON.stringify({type:"input",data:M}))},[]),U=i.useCallback((M,O)=>{const q=d.current;q?.readyState===WebSocket.OPEN&&q.send(JSON.stringify({type:"resize",cols:M,rows:O}))},[]),E=i.useCallback(()=>{m.current&&(clearTimeout(m.current),m.current=null),h.current&&(clearInterval(h.current),h.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=ll()},[]),R=i.useCallback(()=>{m.current&&(clearTimeout(m.current),m.current=null),h.current&&(clearInterval(h.current),h.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=ll()},[]),L=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 M=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 te=new WebSocket(Mi(q));d.current=te,te.onopen=()=>{if(r.current!==M){te.close();return}y.current=ll(),a("connected"),u.current=0,h.current&&clearInterval(h.current),h.current=setInterval(()=>{r.current===M&&te.readyState===WebSocket.OPEN&&te.send(JSON.stringify({type:"ping"}))},u4)},te.onmessage=Z=>{if(r.current===M)try{const K=JSON.parse(Z.data),A=y.current;switch(K.type){case"data":K.data&&(p.current.size===0&&A.data.push(K.data),p.current.forEach(I=>I(K.data)));break;case"scrollback":K.data&&(A.scrollback=K.data,w.current.forEach(I=>I(K.data)));break;case"connected":K.shell&&K.cwd&&(A.connected={shell:K.shell,cwd:K.cwd},x.current.forEach(I=>I({shell:K.shell,cwd:K.cwd})));break;case"exit":K.exitCode!==void 0&&g.current.forEach(I=>I(K.exitCode));break;case"ping":te.readyState===WebSocket.OPEN&&te.send(JSON.stringify({type:"pong"}));break;case"pong":break}}catch{}},te.onclose=Z=>{if(r.current!==M)return;if(d.current=null,h.current&&(clearInterval(h.current),h.current=null),f.current){a("disconnected");return}if(Z.code===4e3||Z.code===4004){a("disconnected"),Z.code===4004&&b.current.forEach(I=>I());return}if(u.current++,u.current>c4){a("disconnected");return}const K=d4*Math.pow(2,u.current-1);a("reconnecting");const A=r.current;m.current=setTimeout(()=>{r.current===A&&(f.current||L())},Math.min(K,16e3))},te.onerror=()=>{}},[e,n]),F=i.useCallback(()=>{u.current=0,R(),L()},[R,L]);return i.useEffect(()=>(c&&(E(),u.current=0,a("disconnected")),e?L():a("disconnected"),R),[e,n,c,L,R,E]),{connectionStatus:s,sendInput:P,resize:U,onData:S,onExit:k,onConnect:C,onScrollback:v,reconnect:F,onSessionInvalid:j}}const Ox="kb-terminal-tabs",h4=15e3,p4=15e3;function nf(){return`tab-${Date.now()}-${Math.random().toString(36).substring(2,9)}`}function sf(e){if(typeof window>"u")return[];try{const n=An(Ox,e);if(n)return JSON.parse(n)}catch{}return[]}function ud(e){const n=e instanceof Error?e.message:typeof e=="string"?e:"";return n.includes("Failed to parse URL")||n.includes("Invalid URL")}function af(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 f4(e){const[n,s]=i.useState(()=>sf(e)),[a,r]=i.useState(!1),[o,l]=i.useState(!0),[c,d]=i.useState(null),[u,m]=i.useState(0),h=i.useRef(0);i.useEffect(()=>{h.current+=1,s(sf(e)),r(!1),l(!0),d(null)},[e]),i.useEffect(()=>{try{ss(Ox,JSON.stringify(n),e)}catch{}},[e,n]),i.useEffect(()=>{let C=!1;const v=h.current;return(async()=>{if(!C)try{const P=await af(Gj(e),h4,"listTerminalSessions");if(C||v!==h.current)return;const U=new Set(P.map(E=>E.id));l(!0),s(E=>{if(C||v!==h.current)return E;const L=E.map(O=>({...O,_verified:U.has(O.sessionId)})).filter(O=>O._verified);if(L.length===0)return[];const F=L.map(({_verified:O,...q})=>q);return F.find(O=>O.isActive)?F:F.map((O,q)=>({...O,isActive:q===0}))}),r(!0)}catch(P){if(C||v!==h.current)return;const U=ud(P);U||console.warn("Failed to validate terminal sessions with server:",P),l(!U),r(!0)}})(),()=>{C=!0}},[e]),i.useEffect(()=>{if(n.length===0&&a&&o){const C=h.current,v=setTimeout(()=>{af(Lo(void 0,void 0,void 0,e),p4,"createTerminalSession").then(j=>{if(C!==h.current)return;const P={id:nf(),sessionId:j.sessionId,title:`Terminal ${n.length+1}`,isActive:!0,createdAt:Date.now()};s(U=>U.length>0?U:[...U.map(R=>({...R,isActive:!1})),P]),d(null)}).catch(j=>{if(C!==h.current)return;ud(j)||console.error(j);const P=j instanceof Error?j.message:typeof j=="string"?j:"Failed to create terminal session";d(P)})},0);return()=>clearTimeout(v)}},[a,o,n.length,u]);const f=i.useCallback(async()=>{const C=await Lo(void 0,void 0,void 0,e),v={id:nf(),sessionId:C.sessionId,title:`Terminal ${n.length+1}`,isActive:!0,createdAt:Date.now()};return s(j=>[...j.map(U=>({...U,isActive:!1})),v]),v},[n.length]),p=i.useCallback(async()=>f(),[f]),g=i.useCallback(C=>{s(v=>{const j=v.find(R=>R.id===C);if(!j)return v;dm(j.sessionId,e).catch(R=>{console.warn(`Failed to kill terminal session ${j.sessionId}:`,R)});const P=v.findIndex(R=>R.id===C),U=j.isActive,E=v.filter(R=>R.id!==C);if(E.length===0)return[];if(U){const R=Math.min(P,E.length-1);return E.map((L,F)=>({...L,isActive:F===R}))}return E})},[]),x=i.useCallback(C=>{s(v=>{let j=!1;const P=v.map(U=>U.id===C?(j=!0,{...U,isActive:!0}):{...U,isActive:!1});return j?P:v})},[]),w=i.useCallback((C,v)=>{s(j=>j.map(P=>P.id===C?{...P,title:v}:P))},[]),b=i.useCallback(async()=>{s(j=>{const P=j.find(U=>U.isActive);return P&&dm(P.sessionId,e).catch(U=>{console.warn(`Failed to kill old session ${P.sessionId}:`,U)}),j});const C=n.find(j=>j.isActive);if(!C)return;const v=await Lo(void 0,void 0,void 0,e);s(j=>j.map(P=>P.id===C.id?{...P,sessionId:v.sessionId}:P))},[n]),y=i.useCallback(async()=>{const C=n.find(v=>v.isActive);if(C)try{const v=await Lo(void 0,void 0,void 0,e);s(j=>j.map(P=>P.id===C.id?{...P,sessionId:v.sessionId}:P)),d(null)}catch(v){ud(v)||console.error(v);const j=v instanceof Error?v.message:typeof v=="string"?v:"Failed to create terminal session";d(j)}},[n]),S=n.find(C=>C.isActive)??null,k=i.useCallback(()=>{d(null),h.current+=1,m(C=>C+1)},[]);return{tabs:n,activeTab:S,isReady:a,bootstrapError:c,createTab:p,closeTab:g,setActiveTab:x,updateTabTitle:w,restartActiveTab:b,retryBootstrap:k,replaceActiveTabSession:y}}const g4=1e4,b4=[500,1500,3e3],zx="kb-terminal-font-size",Xr=14,x4=8,v4=32,y4='"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 w4(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 k4(e){return`\x1B${e}`}const j4=[{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 Zr(e){return Math.min(v4,Math.max(x4,e))}function N4(){if(typeof window>"u")return Xr;try{const e=window.localStorage.getItem(zx);if(!e)return Xr;const n=Number.parseInt(e,10);return Number.isFinite(n)?Zr(n):Xr}catch{return Xr}}function S4(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 C4(e){return new Promise(n=>setTimeout(n,e))}async function E4(e,n=b4){let s;for(let a=0;a<=n.length;a+=1)try{return await e()}catch(r){if(!S4(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 C4(o)}throw s??new Error("Dynamic import failed")}function rf(){if(typeof window>"u")return!1;const e="ontouchstart"in window||navigator.maxTouchPoints>0,n=window.innerWidth<=768;return e&&n}function _4(){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=M4()-e.offsetTop-e.height;return a>=30&&a>80?a:0}let md=null;function M4(){return md===null&&(md=window.innerHeight),md}function A4({isOpen:e,onClose:n,initialCommand:s,projectId:a}){const[r,o]=i.useState(null),[l,c]=i.useState(null),[d,u]=i.useState(!1),[m,h]=i.useState(null),[f,p]=i.useState(0),[g,x]=i.useState(0),[w,b]=i.useState(null),[y,S]=i.useState(()=>N4()),[k,C]=i.useState(!1),[v,j]=i.useState(null),P=i.useRef(null),U=i.useRef(null),E=i.useRef(!1);Ai(U,e,"fusion:terminal-modal-size");const R=i.useRef(null),L=i.useRef(null),F=i.useRef(!1),M=i.useRef(!1),O=i.useRef(null),q=i.useRef(()=>{}),te=i.useRef(null),Z=i.useRef(0),K=i.useRef(y),A=i.useRef(null),I=i.useRef(a);Z.current=g,K.current=y;const $=i.useCallback(Ie=>{if(Ie&&M.current!==Ie)return;const Ue=L.current,pt=R.current,oe=O.current;if(!(!Ue||!pt)&&!(Ie&&M.current!==Ie))try{Ue.fit(),oe&&oe(pt.cols,pt.rows)}catch{}},[]);i.useEffect(()=>{e&&p(Ie=>Ie+1)},[e]),i.useEffect(()=>{if(!e||!rf())return;const Ie=window.visualViewport;if(!Ie)return;const Ue=()=>{const pt=_4();x(pt),b(Ie.height),pt>0&&U.current?.scrollIntoView&&U.current.scrollIntoView({block:"end",behavior:"smooth"}),A.current!==null&&(cancelAnimationFrame(A.current),A.current=null);const oe=typeof M.current=="string"?M.current:void 0;A.current=requestAnimationFrame(()=>{A.current=null,$(oe)})};return Ue(),Ie.addEventListener("resize",Ue),Ie.addEventListener("scroll",Ue),()=>{Ie.removeEventListener("resize",Ue),Ie.removeEventListener("scroll",Ue),A.current!==null&&(cancelAnimationFrame(A.current),A.current=null),x(0),b(null)}},[$,e]),i.useEffect(()=>{if(!e)return;const Ie=U.current;if(!Ie||typeof ResizeObserver>"u")return;let Ue=null;const pt=new ResizeObserver(()=>{Ue!==null&&cancelAnimationFrame(Ue),Ue=requestAnimationFrame(()=>{Ue=null;const oe=typeof M.current=="string"?M.current:void 0;$(oe)})});return pt.observe(Ie),()=>{pt.disconnect(),Ue!==null&&cancelAnimationFrame(Ue)}},[$,e]);const{tabs:N,activeTab:G,isReady:xe,bootstrapError:Se,createTab:je,closeTab:se,setActiveTab:Ve,updateTabTitle:ee,restartActiveTab:ce,retryBootstrap:ne,replaceActiveTabSession:re}=f4(a),{connectionStatus:J,sendInput:B,resize:ye,onData:Ce,onConnect:H,onExit:ke,onScrollback:pe,reconnect:Ae,onSessionInvalid:Oe}=m4(G?.sessionId??null,a);O.current=ye,q.current=B,i.useEffect(()=>{if(!(typeof window>"u"))try{window.localStorage.setItem(zx,String(y))}catch{}},[y]);const He=i.useCallback(()=>{const Ie=R.current;if(Ie)try{L.current?.fit(),ye(Ie.cols,Ie.rows)}catch{}},[ye]);i.useEffect(()=>{if(!e||!xe)return;const Ie=G?.sessionId;if(!Ie)return;const Ue=I.current!==a;if(Ue&&(I.current=a),M.current===Ie&&R.current&&!Ue)return;R.current&&(M.current!==Ie||Ue)&&(R.current.dispose(),R.current=null,L.current=null,M.current=!1,te.current&&(window.removeEventListener("resize",te.current),te.current=null),u(!1),h(null));let pt=!0,oe;return(async()=>{const ge=E4(()=>Promise.all([xn(()=>import("./vendor-xterm-DzcZoU0P.js").then(me=>me.x),__vite__mapDeps([5,1,6])),xn(()=>import("./addon-fit-C7jRorKK.js").then(me=>me.a),__vite__mapDeps([8,1])),xn(()=>import("./addon-web-links-CkJwd4cQ.js").then(me=>me.a),__vite__mapDeps([9,1]))])),Ne=new Promise((me,tt)=>{oe=setTimeout(()=>{tt(new Error("xterm initialization timed out"))},g4)});let ue,qe;try{const[{Terminal:me},{FitAddon:tt},{WebLinksAddon:Ct}]=await Promise.race([ge,Ne]);if(!pt||!P.current||R.current)return;ue=new me({cursorBlink:!0,cursorStyle:"block",fontSize:K.current,fontFamily:y4,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}),qe=new tt,ue.loadAddon(qe);const wt=new Ct;if(ue.loadAddon(wt),!rf())try{const{WebglAddon:Mt}=await xn(async()=>{const{WebglAddon:Qt}=await import("./addon-webgl-BjvOw43o.js").then(Kt=>Kt.a);return{WebglAddon:Qt}},__vite__mapDeps([10,1])),Dt=new Mt;Dt.onContextLoss(()=>{Dt.dispose()}),ue.loadAddon(Dt)}catch{}ue.open(P.current),oe&&clearTimeout(oe);const $t=P.current?.querySelector(".xterm-helper-textarea");if($t&&$t.focus(),P.current)try{P.current.dispatchEvent(new MouseEvent("click",{bubbles:!0,cancelable:!0}))}catch{}setTimeout(()=>{qe.fit();const Mt=P.current?.querySelector(".xterm-helper-textarea");Mt&&Mt.focus()},50),R.current=ue,L.current=qe,M.current=Ie,Z.current>0&&(A.current!==null&&(cancelAnimationFrame(A.current),A.current=null),A.current=requestAnimationFrame(()=>{A.current=null,$(Ie)})),ue.onData(Mt=>{M.current===Ie&&q.current(Mt)});const Vt=()=>{if(M.current===Ie&&L.current&&R.current)try{L.current.fit();const{cols:Mt,rows:Dt}=R.current;O.current?.(Mt,Dt)}catch{}};window.addEventListener("resize",Vt),te.current&&window.removeEventListener("resize",te.current),te.current=Vt,u(!0),h(null)}catch(me){if(oe&&clearTimeout(oe),!pt)return;const tt=me instanceof Error?me.message:"xterm initialization failed";h(tt)}})(),()=>{pt=!1,oe&&clearTimeout(oe)}},[$,e,xe,G?.sessionId,a]),i.useEffect(()=>{e||(R.current&&(R.current.dispose(),R.current=null),L.current=null,M.current=!1,te.current&&(window.removeEventListener("resize",te.current),te.current=null),u(!1),h(null),F.current=!1,o(null),c(null),C(!1),j(null))},[e]),i.useEffect(()=>{if(!d||!R.current||!G)return;const Ie=G.sessionId,Ue=Ne=>{M.current===Ie&&R.current?.write(Ne)},pt=Ce(Ne=>{Ue(Ne)}),oe=pe(Ne=>{Ue(Ne)}),le=H(Ne=>{ee(G.id,wu(Ne.shell)||Ne.shell)}),ge=ke(Ne=>{M.current===Ie&&(c(Ne),R.current?.write(`\r
687
- \x1B[33m[Process exited with code ${Ne}]\x1B[0m\r
688
- `))});return()=>{pt(),oe(),le(),ge()}},[d,G?.sessionId,G?.id,G,J,Ce,pe,H,ke,ee]),i.useEffect(()=>{J==="connected"&&s&&F.current!==s&&G&&(F.current=s,setTimeout(()=>{B(s+`
689
- `)},500))},[J,s,B,G,f]),i.useEffect(()=>{if(!d||!R.current)return;R.current.options.fontSize=y,A.current!==null&&(cancelAnimationFrame(A.current),A.current=null);const Ie=requestAnimationFrame(()=>{A.current=null,He()});return A.current=Ie,()=>{A.current===Ie&&(cancelAnimationFrame(Ie),A.current=null)}},[y,d,He]),i.useEffect(()=>{if(!e)return;const Ie=Ue=>{if(!(!Ue.ctrlKey&&!Ue.metaKey)){if(Ue.code==="Equal"||Ue.code==="NumpadAdd"){Ue.preventDefault(),S(pt=>Zr(pt+1));return}if(Ue.code==="Minus"||Ue.code==="NumpadSubtract"){Ue.preventDefault(),S(pt=>Zr(pt-1));return}if(Ue.code==="Digit0"||Ue.code==="Numpad0"){Ue.preventDefault(),S(Xr);return}}};return window.addEventListener("keydown",Ie),()=>window.removeEventListener("keydown",Ie)},[e,He]),i.useEffect(()=>{if(!e)return;const Ie=Ue=>{Ue.key==="Escape"&&n()};return document.addEventListener("keydown",Ie),()=>document.removeEventListener("keydown",Ie)},[e,n]),i.useEffect(()=>{J==="connected"&&R.current&&setTimeout(()=>{if(!R.current||!P.current)return;const Ie=P.current.querySelector(".xterm-helper-textarea");Ie&&Ie.focus();try{P.current.dispatchEvent(new MouseEvent("click",{bubbles:!0,cancelable:!0}))}catch{}},100)},[J]);const dt=i.useCallback(()=>{if(!P.current||typeof window<"u"&&typeof window.matchMedia=="function"&&window.matchMedia("(hover: none) and (pointer: coarse)")?.matches===!0)return;R.current?.focus();const Ue=P.current.querySelector(".xterm-helper-textarea");if(!Ue)return;Ue.autocapitalize="off",Ue.autocomplete="off",Ue.autocorrect="off",Ue.spellcheck=!1,Ue.setAttribute("inputmode","text");try{Ue.focus({preventScroll:!0})}catch{Ue.focus()}const pt=Ue.value.length;Ue.setSelectionRange(pt,pt)},[]);i.useEffect(()=>Oe(()=>{R.current?.clear(),c(null),F.current=!1,R.current&&(R.current.dispose(),R.current=null),L.current=null,M.current=!1,te.current&&(window.removeEventListener("resize",te.current),te.current=null),u(!1),h(null),re().catch(Ue=>{console.error("Failed to replace invalid terminal session:",Ue)})}),[Oe,re]);const Fe=i.useCallback(Ie=>{Ie.target===Ie.currentTarget&&(E.current=!0)},[]),fe=i.useCallback(Ie=>{E.current&&Ie.target===Ie.currentTarget&&n(),E.current=!1},[n]),$e=i.useCallback(()=>{R.current?.clear()},[]),De=i.useCallback(async()=>{R.current?.clear(),c(null),F.current=!1;try{await ce()}catch(Ie){o(Pe(Ie)||"Failed to restart terminal session")}},[ce]),ot=i.useCallback(()=>{R.current&&(R.current.dispose(),R.current=null),L.current=null,M.current=!1,te.current&&(window.removeEventListener("resize",te.current),te.current=null),h(null),u(!1)},[]),Be=i.useCallback(()=>{window.location.reload()},[]),we=i.useCallback(()=>{S(Ie=>Zr(Ie+1))},[]),Q=i.useCallback(()=>{S(Ie=>Zr(Ie-1))},[]),_e=i.useCallback(Ie=>{j(Ue=>Ue===Ie?null:Ie)},[]),lt=i.useCallback(Ie=>{if(v==="ctrl"){B(w4(Ie)),j(null);return}if(v==="alt"){B(k4(Ie)),j(null);return}B(Ie)},[B,v]),ht=i.useCallback(Ie=>{B(Ie),j(null)},[B]);if(!e)return null;const mt=()=>{switch(J){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}},xt=!xe||!G&&!Se;return t.jsx("div",{className:"modal-overlay open",onMouseDown:Fe,onMouseUp:fe,role:"dialog","aria-modal":"true","data-testid":"terminal-modal-overlay",style:g>0?{"--overlay-padding-top":"0px"}:void 0,children:t.jsxs("div",{ref:U,className:"modal terminal-modal","data-testid":"terminal-modal",style:g>0?{"--keyboard-overlap":`${g}px`,"--vv-height":w?`${w}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(Ie=>t.jsxs("div",{className:`terminal-tab ${Ie.isActive?"terminal-tab--active":""}`,onClick:()=>Ve(Ie.id),title:Ie.title,role:"tab","aria-selected":Ie.isActive,children:[t.jsx("span",{className:"terminal-tab-label",children:Ie.title}),N.length>1&&t.jsx("button",{className:"terminal-tab-close",onClick:Ue=>{Ue.stopPropagation(),se(Ie.id)},title:"Close tab",children:"×"})]},Ie.id)),t.jsx("button",{className:"terminal-tab terminal-tab--new",onClick:je,title:"New terminal",children:"+"})]}),t.jsxs("div",{className:"terminal-title","data-testid":"terminal-title",children:[t.jsx(Bi,{size:16}),mt()]}),t.jsxs("div",{className:"terminal-actions","data-testid":"terminal-actions",children:[J==="disconnected"&&G&&t.jsxs("button",{className:"terminal-reconnect-btn",onClick:Ae,title:"Reconnect","data-testid":"terminal-reconnect-btn",children:[t.jsx(os,{size:14}),t.jsx("span",{className:"terminal-action-label",children:"Reconnect"})]}),l!==null&&t.jsxs("button",{className:"terminal-restart-btn",onClick:De,title:"New Session","data-testid":"terminal-restart-btn",children:[t.jsx(os,{size:14}),t.jsx("span",{className:"terminal-action-label",children:"New Session"})]}),t.jsxs("button",{className:"terminal-clear-btn",onClick:$e,"data-testid":"terminal-clear-btn",title:"Clear terminal",children:[t.jsx(vn,{size:14}),t.jsx("span",{className:"terminal-action-label",children:"Clear"})]}),t.jsxs("button",{className:"terminal-clear-btn terminal-clear-btn--shortcut",onClick:()=>C(Ie=>!Ie),"data-testid":"terminal-shortcut-toggle",title:"Shortcuts","aria-pressed":k,children:[t.jsx(tw,{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(nn,{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:[xt&&!Se&&t.jsxs("div",{className:"terminal-loading","data-testid":"terminal-loading",children:[t.jsx("div",{className:"terminal-spinner"}),t.jsx("span",{children:"Starting terminal..."})]}),Se&&!G&&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: ",Se]}),t.jsxs("div",{className:"terminal-error-actions",children:[t.jsxs("button",{className:"terminal-retry-btn",onClick:ne,"data-testid":"terminal-retry-btn",children:[t.jsx(os,{size:14}),"Retry"]}),t.jsxs("button",{className:"terminal-retry-btn",onClick:Be,"data-testid":"terminal-bootstrap-refresh-btn",children:[t.jsx(os,{size:14}),"Refresh page"]})]})]})}),m&&G&&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: ",m]}),t.jsxs("div",{className:"terminal-error-actions",children:[t.jsxs("button",{className:"terminal-retry-btn",onClick:ot,"data-testid":"terminal-reinit-btn",children:[t.jsx(os,{size:14}),"Reinitialize"]}),t.jsxs("button",{className:"terminal-retry-btn",onClick:Be,"data-testid":"terminal-xterm-refresh-btn",children:[t.jsx(os,{size:14}),"Refresh page"]})]})]})}),t.jsx("div",{ref:P,className:"terminal-xterm","data-testid":"terminal-xterm",onPointerDown:dt,onTouchStart:dt},G?.sessionId)]}),k&&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 ${v==="ctrl"?"is-active":""}`,"data-testid":"terminal-modifier-ctrl",onClick:()=>_e("ctrl"),"aria-pressed":v==="ctrl",children:"Ctrl"}),t.jsx("button",{type:"button",className:`terminal-shortcut-btn terminal-shortcut-btn--modifier ${v==="alt"?"is-active":""}`,"data-testid":"terminal-modifier-alt",onClick:()=>_e("alt"),"aria-pressed":v==="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"})]}),j4.map(Ie=>t.jsx("button",{type:"button",className:"terminal-shortcut-btn",onClick:()=>lt(Ie.key),title:Ie.description,children:Ie.label},Ie.label))]}),t.jsxs("div",{className:"terminal-status-bar","data-testid":"terminal-status-bar",children:[t.jsxs("span",{className:`terminal-connection-status ${J}`,children:[J==="connected"&&"Connected",J==="connecting"&&"Connecting...",J==="reconnecting"&&"Reconnecting...",J==="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:Q,"data-testid":"terminal-font-size-decrease","aria-label":"Decrease terminal font size",children:t.jsx(Sw,{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:we,"data-testid":"terminal-font-size-increase","aria-label":"Increase terminal font size",children:t.jsx(gn,{size:14})})]}),t.jsx("span",{className:"terminal-shortcuts",children:"Ctrl++/- zoom • ⌨ Shortcuts panel • Esc close"})]})]})})}const Ur={name:"",command:""};function of(e){return/^[a-zA-Z0-9_-]+$/.test(e)}function P4(e,n=60){return e.length<=n?e:e.slice(0,n-3)+"..."}function R4({isOpen:e,onClose:n,addToast:s,projectId:a,onRunScript:r}){vi(e);const[o,l]=i.useState({}),[c,d]=i.useState(!0),[u,m]=i.useState(!1),[h,f]=i.useState(null),[p,g]=i.useState(Ur),[x,w]=i.useState(!1),[b,y]=i.useState(null),[S,k]=i.useState(null),C=qi(n),v=i.useCallback(async()=>{try{d(!0);const q=await mo(a);l(q)}catch(q){s(Pe(q)||"Failed to load scripts","error")}finally{d(!1)}},[s,a]);i.useEffect(()=>{e&&v()},[e,v]);const j=i.useCallback(()=>{m(!0),f(null),g(Ur),k(null)},[]),P=i.useCallback((q,te)=>{f(q),m(!1),g({name:q,command:te}),k(null)},[]),U=i.useCallback(()=>{f(null),m(!1),g(Ur),k(null)},[]),E=i.useCallback(q=>{g(te=>({...te,name:q})),q&&!of(q)?k("Name must contain only letters, numbers, hyphens, and underscores (no spaces)"):k(null)},[]),R=i.useCallback(async()=>{const q=p.name.trim(),te=p.command.trim();if(!q){s("Script name is required","error");return}if(!of(q)){s("Script name must contain only letters, numbers, hyphens, and underscores (no spaces)","error");return}if(!te){s("Script command is required","error");return}w(!0);try{await ZN(q,te,a),s(h?"Script updated":"Script created","success"),f(null),m(!1),g(Ur),k(null),await v()}catch(Z){const K=Pe(Z);K?.includes("already exists")?s("A script with this name already exists","error"):s(K||"Failed to save script","error")}finally{w(!1)}},[p,h,s,v,a]),L=i.useCallback(async q=>{try{await eS(q,a),s("Script deleted","success"),y(null),h===q&&(f(null),g(Ur)),await v()}catch(te){s(Pe(te)||"Failed to delete script","error")}},[h,s,v,a]),F=i.useCallback((q,te)=>{r&&r(q,te)},[r]);if(!e)return null;const M=u||h!==null,O=Object.entries(o).map(([q,te])=>({name:q,command:te}));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(Bi,{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(bt,{size:24,className:"spin",style:{margin:"0 auto 8px",display:"block"}}),"Loading scripts..."]}):M?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:x||h!==null,"data-testid":"script-name-input",style:{width:"100%",borderColor:S?"var(--color-error)":void 0}}),S&&t.jsx("div",{style:{fontSize:"12px",color:"var(--color-error)",marginTop:"4px"},"data-testid":"script-name-error",children:S}),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(te=>({...te,command:q.target.value})),placeholder:"e.g., npm run build",rows:3,disabled:x,"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:U,disabled:x,"data-testid":"script-cancel-btn",children:"Cancel"}),t.jsx("button",{className:"btn btn-primary",onClick:R,disabled:x||!!S,"data-testid":"script-save-btn",children:x?t.jsxs(t.Fragment,{children:[t.jsx(bt,{size:14,className:"spin",style:{marginRight:"6px"}}),"Saving..."]}):h?"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:O.length===0?"No scripts defined":`${O.length} script${O.length===1?"":"s"}`}),t.jsxs("button",{className:"btn btn-primary",onClick:j,"data-testid":"add-script-btn",style:{display:"flex",alignItems:"center",gap:"6px"},children:[t.jsx(gn,{size:14}),"Add Script"]})]}),O.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(Bi,{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:O.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:P4(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:()=>F(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(Yn,{size:12}),"Run"]}),t.jsx("button",{className:"btn-icon",onClick:()=>P(q.name,q.command),title:"Edit","aria-label":`Edit ${q.name}`,"data-testid":`edit-script-${q.name}`,children:t.jsx(gn,{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:()=>L(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(vn,{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(nn,{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(vn,{size:14})})]})]})},q.name))})]})})]})})}function I4(e,n,s){const[a,r]=i.useState([]),[o,l]=i.useState("."),[c,d]=i.useState(!1),[u,m]=i.useState(null),[h,f]=i.useState(0),p=i.useCallback(()=>{f(x=>x+1)},[]),g=i.useCallback(x=>{l(x),m(null)},[]);return i.useEffect(()=>{l("."),m(null),r([])},[e]),i.useEffect(()=>{if(!n||!e)return;let x=!1;async function w(){d(!0),m(null);try{const b=await hN(e,o==="."?void 0:o,s);x||r(b.entries)}catch(b){x||(m(Pe(b)||"Failed to load files"),r([]))}finally{x||d(!1)}}return w(),()=>{x=!0}},[e,o,n,h,s]),{entries:a,currentPath:o,setPath:g,loading:c,error:u,refresh:p}}function T4(e,n,s,a){const[r,o]=i.useState(""),[l,c]=i.useState(""),[d,u]=i.useState(null),[m,h]=i.useState(!1),[f,p]=i.useState(!1),[g,x]=i.useState(null),w=i.useCallback(S=>{o(S),x(null)},[]);i.useEffect(()=>{if(!e||!n){o(""),c(""),u(null),x(null);return}let S=!1;async function k(){h(!0),x(null);try{const C=await pN(e,n,a);S||(o(C.content),c(C.content),u(C.mtime))}catch(C){S||(x(Pe(C)||"Failed to load file"),o(""),c(""),u(null))}finally{S||h(!1)}}return k(),()=>{S=!0}},[e,n,s,a]);const b=r!==l,y=i.useCallback(async()=>{if(!(!e||!n||!b)){p(!0),x(null);try{const S=await fN(e,n,r,a);c(r),u(S.mtime)}catch(S){throw x(Pe(S)||"Failed to save file"),S}finally{p(!1)}}},[e,n,r,b,a]);return{content:r,setContent:w,originalContent:l,loading:m,saving:f,error:g,save:y,hasChanges:b,mtime:d}}const $4=1e4;function D4(e){const s=e.replace(/[\\/]+$/,"").split(/[\\/]/).filter(Boolean);return s[s.length-1]||e||"Project Root"}function L4(e){return{id:e.id,label:e.id,title:e.title,worktree:e.worktree,kind:"task"}}function O4(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 m(){try{const f=await mN(e);if(u)return;s(D4(f.project)),r(f.tasks.map(L4)),d(null)}catch(f){u||d(Pe(f)||"Failed to load workspaces")}finally{u||l(!1)}}m();const h=window.setInterval(()=>{m()},$4);return()=>{u=!0,window.clearInterval(h)}},[e]),{projectName:n,workspaces:a,loading:o,error:c}}function z4(e){return e===void 0?"":e<1024?`${e} B`:e<1024*1024?`${(e/1024).toFixed(1)} KB`:`${(e/(1024*1024)).toFixed(1)} MB`}function F4(e){return e?new Date(e).toLocaleDateString():""}function lf(e,n){return S0(e,n)}const Br={visible:!1,x:0,y:0,entry:null,entryFullPath:""},hd={type:null,entry:null,entryFullPath:""},U4=200,B4=500,cf=10;function H4({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 m=o.current;if(!m)return;const h=m.getBoundingClientRect(),f=window.visualViewport,p=f?.width&&f.width>0?f.width:window.innerWidth,g=f?.height&&f.height>0?f.height:window.innerHeight,x=f?.offsetLeft??0,w=f?.offsetTop??0,b=8;let y=e-x,S=n-w;y+h.width>p-b&&(y=p-b-h.width),S+h.height>g-b&&(S=g-b-h.height),y<b&&(y=b),S<b&&(S=b),c({x:y+x,y:S+w})},[e,n]),i.useEffect(()=>{const m=h=>{h.key==="Escape"&&r()};return document.addEventListener("keydown",m),()=>document.removeEventListener("keydown",m)},[r]);const d=s.type==="directory",u=[{id:"copy",label:"Copy",icon:sa,disabled:!1},{id:"move",label:"Move",icon:_w,disabled:!1},{id:"rename",label:"Rename",icon:Ds,disabled:!1},...d?[{id:"download-zip",label:"Download as ZIP",icon:xo,disabled:!1}]:[{id:"download",label:"Download",icon:py,disabled:!1}],{id:"divider",label:"",icon:sa,disabled:!0},{id:"delete",label:"Delete",icon:vn,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:m=>m.stopPropagation(),children:u.map(m=>m.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 ${m.disabled?"file-browser-context-menu__disabled":""} ${m.id==="delete"?"file-browser-context-menu__item--danger":""}`,disabled:m.disabled,onClick:()=>a(m.id),children:[t.jsx(m.icon,{size:14,className:"file-browser-context-menu__item-icon"}),t.jsx("span",{children:m.label})]},m.id))})})}function q4({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,m]=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 h=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=>m(g.target.value),placeholder:p.placeholder,onKeyDown:h,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 V4({entries:e,currentPath:n,onSelectFile:s,onNavigate:a,loading:r,error:o,onRetry:l,workspace:c,onRefresh:d,projectId:u}){const[m,h]=i.useState(Br),[f,p]=i.useState(hd),[g,x]=i.useState(!1),[w,b]=i.useState(null),[y,S]=i.useState(!1),[k,C]=i.useState(null),v=i.useRef(null),j=i.useRef(null),P=i.useRef(null),U=i.useRef(!1),E=i.useCallback(()=>{v.current!==null&&(window.clearTimeout(v.current),v.current=null),j.current!==null&&(window.clearTimeout(j.current),j.current=null)},[]),R=i.useCallback(()=>{E(),P.current=null,S(!1),C(null)},[E]);i.useEffect(()=>()=>{E()},[E]);const L=i.useCallback((I,$,N,G)=>{h({visible:!0,x:I,y:$,entry:N,entryFullPath:G})},[]),F=i.useCallback((I,$,N)=>{if(I.touches.length!==1)return;const G=I.touches[0];G&&(R(),P.current={x:G.clientX,y:G.clientY},j.current=window.setTimeout(()=>{S(!0),C(N)},U4),v.current=window.setTimeout(()=>{const xe=P.current;xe&&(U.current=!0,S(!1),C(null),E(),L(xe.x,xe.y,$,N))},B4))},[R,E,L]),M=i.useCallback(I=>{const $=P.current,N=I.touches[0];!$||!N||(Math.abs(N.clientX-$.x)>cf||Math.abs(N.clientY-$.y)>cf)&&R()},[R]),O=i.useCallback(()=>{R()},[R]);i.useEffect(()=>{if(!m.visible)return;const I=document.querySelector(".file-browser-list"),$=()=>{U.current=!1,R(),h(Br)};return I?.addEventListener("scroll",$),()=>I?.removeEventListener("scroll",$)},[R,m.visible]),i.useEffect(()=>{if(!m.visible)return;const I=$=>{$.key==="Escape"&&(U.current=!1,h(Br))};return document.addEventListener("keydown",I),()=>document.removeEventListener("keydown",I)},[m.visible]);const q=i.useCallback((I,$)=>{I.preventDefault(),I.stopPropagation(),R(),U.current=!1,L(I.clientX,I.clientY,$,lf(n,$.name))},[R,n,L]),te=i.useCallback(I=>{if(!m.entry)return;U.current=!1;const $=m.entry,N=m.entryFullPath;if(h(Br),I==="download"){if(!c)return;const G=Rg(c,N,u);window.open(Mi(G),"_blank");return}if(I==="download-zip"){if(!c)return;const G=wN(c,N,u);window.open(Mi(G),"_blank");return}p({type:I,entry:$,entryFullPath:N}),b(null)},[m,c,u]),Z=i.useCallback(async I=>{if(!(!f.type||!f.entry||!c)){x(!0),b(null);try{switch(f.type){case"copy":await bN(c,f.entryFullPath,I,u);break;case"move":await xN(c,f.entryFullPath,I,u);break;case"rename":await yN(c,f.entryFullPath,I,u);break;case"delete":await vN(c,f.entryFullPath,u);break}p(hd),d?.()}catch($){b(Pe($)||"Operation failed")}finally{x(!1)}}},[f,c,d,u]),K=i.useCallback(()=>{p(hd),b(null)},[]),A=i.useCallback((I,$)=>{if(U.current){U.current=!1;return}m.visible||(I.type==="directory"?a($):s($))},[m.visible,a,s]);return r?t.jsxs("div",{className:"file-browser-loading",children:[t.jsx(bt,{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(C0(n))},children:[t.jsx(Mn,{size:16,style:{transform:"rotate(-90deg)"}}),"Up one level"]}),t.jsx("span",{className:"file-browser-path",children:n==="."?"Root":Sr(n)})]}),t.jsx("div",{className:"file-browser-list",children:e.length===0?t.jsx("div",{className:"file-browser-empty",children:"(empty directory)"}):e.map(I=>{const $=lf(n,I.name),N=y&&k===$;return t.jsxs("div",{className:`file-node file-node--${I.type} ${N?"file-node--long-pressing":""}`,onClick:()=>A(I,$),onContextMenu:G=>q(G,I),onTouchStart:G=>F(G,I,$),onTouchMove:M,onTouchEnd:O,onTouchCancel:O,children:[t.jsx("div",{className:"file-node-icon",children:I.type==="directory"?t.jsx(bs,{size:16}):t.jsx(yg,{size:16})}),t.jsx("div",{className:"file-node-name",children:I.name}),I.type==="file"&&I.size!==void 0&&t.jsx("div",{className:"file-node-size",children:z4(I.size)}),I.mtime&&t.jsx("div",{className:"file-node-time",children:F4(I.mtime)})]},I.name)})}),m.visible&&m.entry&&t.jsx(H4,{x:m.x,y:m.y,entry:m.entry,onAction:te,onClose:()=>{U.current=!1,h(Br)}}),f.type&&f.entry&&t.jsx(q4,{type:f.type,entry:f.entry,entryFullPath:f.entryFullPath,onConfirm:Z,onCancel:K,loading:g,error:w})]})}function W4(e){if(!e)return!1;const n=e.toLowerCase();return n.endsWith(".md")||n.endsWith(".markdown")||n.endsWith(".mdx")}function K4({content:e,onChange:n,readOnly:s,filePath:a,showLineNumbers:r=!1}){const[o,l]=i.useState(!1),[c,d]=i.useState(!0),u=i.useRef(null),m=W4(a),h=m&&(s?!0:o),f=r&&!s&&!h,p=i.useMemo(()=>f?e.split(`
690
- `).length:0,[e,f]),g=i.useCallback(()=>{l(!1)},[]),x=i.useCallback(()=>{l(!0)},[]),w=i.useCallback(()=>{d(y=>!y)},[]),b=i.useCallback(y=>{u.current&&(u.current.scrollTop=y.currentTarget.scrollTop)},[]);return t.jsxs("div",{className:"file-editor-container",children:[m?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 ${h?"":"btn-primary"}`,onClick:g,disabled:!h,"aria-label":"Edit mode",children:[t.jsx(vg,{size:14}),"Edit"]}),t.jsxs("button",{className:`btn btn-sm ${h?"btn-primary":""}`,onClick:x,disabled:h,"aria-label":"Preview mode",children:[t.jsx(kr,{size:14}),"Preview"]})]}),!s&&t.jsx("button",{className:`btn btn-sm ${c?"btn-primary":""}`,onClick:w,"aria-label":"Toggle word wrap",title:"Toggle word wrap",children:t.jsx(Nl,{size:14})})]}):!s&&t.jsxs("div",{className:"file-editor-toolbar",children:[t.jsx("div",{className:"file-editor-mode-toggle"}),t.jsx("button",{className:`btn btn-sm ${c?"btn-primary":""}`,onClick:w,"aria-label":"Toggle word wrap",title:"Toggle word wrap",children:t.jsx(Nl,{size:14})})]}),h?t.jsx("div",{className:"file-editor-preview markdown-body",children:t.jsx(bi,{remarkPlugins:[xi],children:e})}):t.jsxs("div",{className:`file-editor-textarea-shell ${f?"file-editor-textarea-shell--line-numbers":""}`,children:[f&&t.jsx("div",{className:"file-editor-line-numbers",ref:u,"aria-hidden":"true",children:Array.from({length:p},(y,S)=>t.jsx("div",{className:"file-editor-line-number",children:S+1},`line-${S+1}`))}),t.jsx("textarea",{className:`file-editor-textarea ${c?"file-editor-textarea--wrap":""}`,value:e,onChange:y=>n(y.target.value),onScroll:b,readOnly:s,spellCheck:!1,"aria-label":a?`Editor for ${a}`:"File editor"})]})]})}function G4(e,n=44){if(e)return e.length<=n?e:`${e.slice(0,n-1)}…`}function J4({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(Zu,{size:14}):t.jsx(Md,{size:14}),t.jsx("span",{className:"workspace-selector-trigger-label",children:l}),t.jsx(rn,{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(Zu,{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(Md,{size:14}),t.jsx("span",{children:c.id})]}),c.title&&t.jsx("span",{className:"workspace-selector-option-meta",title:c.title,children:G4(c.title)})]},c.id))]})]})]})}const Y4=768,Q4=280,cl=180,dl=500,df="fusion:file-browser-sidebar-width",uf="kb-files-line-numbers",Fx=new Set([".png",".jpg",".jpeg",".gif",".webp",".ico",".bmp",".svgz"]),X4=new Set([...Fx,".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 pd(e){const n=e.slice(e.lastIndexOf(".")).toLowerCase();return X4.has(n)}function Z4(e){const n=e.slice(e.lastIndexOf(".")).toLowerCase();return Fx.has(n)}function e$({initialWorkspace:e="project",onClose:n,onWorkspaceChange:s,projectId:a}){const{projectName:r,workspaces:o}=O4(a),l=i.useRef(null);Ai(l,!0,"fusion:files-modal-size");const c=qi(n),[d,u]=i.useState(e),[m,h]=i.useState(null),[f,p]=i.useState(!1),[g,x]=i.useState("list"),[w,b]=i.useState(Q4),[y,S]=i.useState(!1),{entries:k,currentPath:C,setPath:v,loading:j,error:P,refresh:U}=I4(d,!0,a),{content:E,setContent:R,originalContent:L,loading:F,saving:M,error:O,save:q,hasChanges:te,mtime:Z}=T4(d,m,!0,a);i.useEffect(()=>{u(e)},[e]),i.useEffect(()=>{const ce=()=>{p(window.innerWidth<=Y4)};return ce(),window.addEventListener("resize",ce),()=>window.removeEventListener("resize",ce)},[]),i.useEffect(()=>{m||x("list")},[m]),i.useEffect(()=>{try{const ce=localStorage.getItem(df);if(!ce)return;const ne=Number.parseInt(ce,10);if(!Number.isNaN(ne)){const re=Math.max(cl,Math.min(dl,ne));b(re)}}catch{}},[]),i.useEffect(()=>{const ce=An(uf,a);S(ce==="true")},[a]),i.useEffect(()=>{const ce=ne=>{ne.key==="Escape"&&n(),(ne.metaKey||ne.ctrlKey)&&ne.key==="s"&&(ne.preventDefault(),te&&!M&&q())};return document.addEventListener("keydown",ce),()=>document.removeEventListener("keydown",ce)},[n,te,M,q]);const K=i.useCallback(ce=>{h(ce),f&&x("editor")},[f]),A=i.useCallback(()=>{x("list")},[]),I=i.useCallback(()=>{R(L)},[L,R]),$=i.useCallback(ce=>{u(ce),h(null),x("list"),s?.(ce)},[s]),N=i.useCallback(ce=>{try{localStorage.setItem(df,String(ce))}catch{}},[]),G=i.useCallback(ce=>{if(f)return;ce.preventDefault(),ce.stopPropagation();const ne=ce.currentTarget;typeof ne.setPointerCapture=="function"&&ne.setPointerCapture(ce.pointerId);const re=ce.clientX,J=w;let B=J;document.body.style.userSelect="none";const ye=H=>{const ke=H.clientX-re,pe=Math.max(cl,Math.min(dl,J+ke));B=pe,b(pe)},Ce=H=>{typeof ne.releasePointerCapture=="function"&&ne.releasePointerCapture(H.pointerId),document.body.style.userSelect="",document.removeEventListener("pointermove",ye),document.removeEventListener("pointerup",Ce),N(B)};document.addEventListener("pointermove",ye),document.addEventListener("pointerup",Ce)},[f,N,w]),xe=i.useCallback(ce=>{if(f)return;const ne=20;if(ce.key!=="ArrowLeft"&&ce.key!=="ArrowRight")return;ce.preventDefault();const re=ce.key==="ArrowLeft"?-ne:ne,J=Math.max(cl,Math.min(dl,w+re));b(J),N(J)},[f,N,w]),Se=i.useCallback(()=>{S(ce=>{const ne=!ce;return ss(uf,String(ne),a),ne})},[a]),se=`Files — ${i.useMemo(()=>d==="project"?"Project":o.find(ce=>ce.id===d)?.id??d,[d,o])}`,Ve=i.useMemo(()=>!m||!Z4(m)?null:Rg(d,m,a),[m,d,a]),ee=ce=>{const ne=new Blob([ce]).size;return ne<1024?`${ne} B`:`${(ne/1024).toFixed(1)} KB`};return t.jsx("div",{className:"modal-overlay open",...c,role:"dialog","aria-modal":"true",children:t.jsxs("div",{className:"modal file-browser-modal",ref:l,children:[t.jsxs("div",{className:"modal-header file-browser-modal-header",children:[t.jsxs("div",{className:"file-browser-header-title",children:[t.jsx(bs,{size:18}),t.jsx("span",{children:se}),m&&t.jsx("span",{className:"file-browser-header-path",children:m})]}),t.jsxs("div",{className:"file-browser-header-actions",children:[t.jsxs("button",{className:`btn btn-sm file-browser-line-numbers-toggle ${y?"btn-primary":""}`,onClick:Se,"aria-label":"Toggle line numbers","aria-pressed":y,title:"Toggle line numbers",children:[t.jsx(cw,{size:14}),t.jsx("span",{children:"Line #"})]}),t.jsx(J4,{currentWorkspace:d,projectName:r,workspaces:o,onSelect:$}),t.jsx("button",{className:"modal-close",onClick:n,"aria-label":"Close",children:t.jsx(nn,{size:20})})]})]}),t.jsxs("div",{className:"file-browser-body",children:[t.jsx("div",{className:`file-browser-sidebar ${f?"mobile":""} ${g==="list"?"active":""}`,style:f?void 0:{width:`${w}px`},children:t.jsx(V4,{entries:k,currentPath:C,onSelectFile:K,onNavigate:v,loading:j,error:P,onRetry:U,workspace:d,onRefresh:U,projectId:a})}),!f&&t.jsx("div",{className:"file-browser-resize-handle",role:"separator","aria-orientation":"vertical","aria-valuemin":cl,"aria-valuemax":dl,"aria-valuenow":w,"aria-label":"Resize sidebar",tabIndex:0,onPointerDown:G,onKeyDown:xe}),t.jsx("div",{className:`file-browser-content ${f?"mobile":""} ${g==="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:[f&&g==="editor"&&t.jsxs("button",{className:"file-browser-back-button",onClick:A,"aria-label":"Back to file list",children:[t.jsx(Aa,{size:16}),t.jsx("span",{children:"Back"})]}),m,pd(m)&&t.jsxs("span",{className:"file-browser-binary-indicator",children:[t.jsx(Ry,{size:12}),"Binary file — read only"]}),Z&&t.jsxs("span",{className:"file-browser-mtime",children:["Modified: ",new Date(Z).toLocaleString()]}),F&&t.jsx("span",{className:"file-browser-loading",children:"Loading..."})]}),t.jsx("div",{className:"file-browser-actions",children:!Ve&&te&&t.jsxs(t.Fragment,{children:[t.jsxs("button",{className:"btn btn-sm",onClick:I,disabled:M,children:[t.jsx(Hw,{size:14}),"Discard"]}),t.jsxs("button",{className:"btn btn-primary btn-sm",onClick:()=>void q(),disabled:M,children:[t.jsx(Sg,{size:14}),M?"Saving...":"Save"]})]})})]}),O&&!Ve&&t.jsx("div",{className:"file-browser-error-banner",children:O}),Ve?t.jsx("div",{className:"file-browser-image-preview",children:t.jsx("img",{src:Ve,alt:m??"",className:"file-browser-image"})}):t.jsx("div",{className:"file-editor-wrapper",children:t.jsx(K4,{content:E,onChange:R,filePath:m,readOnly:pd(m),showLineNumbers:y&&!pd(m)})}),!Ve&&t.jsxs("div",{className:"file-browser-footer",children:[t.jsx("span",{children:ee(E)}),te&&t.jsx("span",{className:"file-browser-unsaved",children:"Unsaved changes"})]})]}):t.jsxs("div",{className:"file-browser-placeholder",children:[t.jsx(bs,{size:48,opacity:.3}),t.jsx("p",{children:"Select a file to edit"})]})})]})]})})}const t$=i.lazy(()=>xn(()=>import("./TodoView-DFNGBDNV.js"),__vite__mapDeps([11,1,5,6,12])).then(e=>({default:e.TodoView})));function n$({onClose:e,projectId:n,addToast:s,onPlanningMode:a}){const r=qi(e),l=Ys()==="mobile",{keyboardOverlap:c,viewportHeight:d,viewportOffsetTop:u,keyboardOpen:m}=Wi({enabled:l});vi(l);const h=m?{"--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:h,children:[t.jsxs("div",{className:"modal-header todo-modal-header",children:[t.jsxs("div",{className:"todo-modal-header-title",children:[t.jsx(ow,{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(nn,{size:20})})]}),t.jsx("div",{className:"todo-modal-body",children:t.jsx(i.Suspense,{fallback:null,children:t.jsx(t$,{projectId:n,addToast:s,onPlanningMode:a,onClose:e,mobileKeyboardActive:l&&m})})})]})})}function s$(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(m=>({...m,loading:!0,error:null}));try{const{providers:m}=await fj();r({providers:m,loading:!1,error:null,lastUpdated:new Date})}catch(m){if(m instanceof Error&&m.name==="AbortError")return;r(h=>({...h,loading:!1,error:Pe(m)||"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 i$(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 a$(e){return e>90?"usage-progress-fill--high":e>70?"usage-progress-fill--medium":"usage-progress-fill--low"}const Ux="kb-usage-hidden-windows",Bx="kb-usage-modal-size",Hx="kb-usage-provider-order";function mf(e){const n=An(Bx,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 hf(e){const n=An(Ux,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 r$(e,n){ss(Ux,JSON.stringify(e),n)}function pf(e){const n=An(Hx,e);if(!n)return[];try{const s=JSON.parse(n);return Array.isArray(s)?s.filter(a=>typeof a=="string"):[]}catch{return[]}}function ff(e,n){ss(Hx,JSON.stringify(e),n)}function qx(e,n,s){return s[e]?.includes(n)??!1}function o$({window:e,viewMode:n,isHidden:s,onToggleHidden:a}){const r=a$(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 w=new Date(e.resetAt).getTime()-Date.now();if(w>0){const b=Math.floor(w/36e5),y=Math.floor(b/24),S=b%24;y>0&&S>0?u=`resets in ${y}d ${S}h`:y>0?u=`resets in ${y}d`:b>0?u=`resets in ${b}h`:u=`resets in ${Math.floor(w/6e4)}m`}}const m=e.pace,h=m!==void 0;let f=0;h&&(f=o?100-m.percentElapsed:m.percentElapsed);const p=m?.status==="ahead",g=m?.status==="behind",x=m?.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(kr,{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}`})}),h&&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:i$(e.resetAt)})]})]}),h&&t.jsxs("div",{className:"usage-pace-row","data-testid":"pace-row",children:[p&&t.jsxs(t.Fragment,{children:[t.jsx(No,{size:14,className:"pace-icon pace-ahead"}),t.jsx("span",{className:"pace-text pace-ahead",children:m.message})]}),g&&t.jsxs(t.Fragment,{children:[t.jsx(uk,{size:14,className:"pace-icon pace-behind"}),t.jsx("span",{className:"pace-text pace-behind",children:m.message})]}),x&&t.jsxs(t.Fragment,{children:[t.jsx(Dn,{size:14,className:"pace-icon pace-ontrack"}),t.jsx("span",{className:"pace-text pace-ontrack",children:m.message})]})]})]})}function l$(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 c$({provider:e,viewMode:n,hiddenWindows:s,onToggleWindow:a,onShowAllHidden:r,isDragging:o,isDragOver:l,dragOverPosition:c,onDragStart:d,onDragOver:u,onDragLeave:m,onDrop:h,onDragEnd:f,isTouchReorderMode:p,canMoveUp:g,canMoveDown:x,onMoveUp:w,onMoveDown:b}){const y=s[e.name]?.length??0,S=()=>{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:m,onDrop:p?void 0:h,onDragEnd:p?void 0:f,children:[t.jsxs("div",{className:"usage-provider-header",children:[t.jsxs("div",{className:"usage-provider-info",children:[t.jsx(Sn,{provider:l$(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:w,disabled:!g,"aria-label":`Move ${e.name} up`,children:t.jsx(Ei,{size:14})}),t.jsx("button",{className:"btn-icon usage-provider-reorder-btn",type:"button",onClick:b,disabled:!x,"aria-label":`Move ${e.name} down`,children:t.jsx(rn,{size:14})})]}),S(),t.jsx("div",{className:"usage-provider-drag-handle","aria-hidden":"true",children:t.jsx(Jl,{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((k,C)=>{const v=qx(e.name,k.label,s);return t.jsx(o$,{window:k,viewMode:n,isHidden:v,onToggleHidden:()=>a(e.name,k.label)},`${e.name}-${k.label}-${C}`)})}):e.status==="ok"?t.jsx("div",{className:"usage-provider-empty",children:"No usage data available"}):null]})}function d$(){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 u$({isOpen:e,onClose:n,projectId:s,anchorRect:a}){const{providers:r,loading:o,error:l,lastUpdated:c,refresh:d}=s$({autoRefresh:e}),[u,m]=i.useState(!1),[h,f]=i.useState(()=>typeof window<"u"?window.innerWidth>=769:!1),[p,g]=i.useState(()=>typeof window>"u"?!1:window.matchMedia?.("(pointer: coarse)").matches??!1),[x,w]=i.useState("used"),[b,y]=i.useState(()=>hf(s)),[S,k]=i.useState(()=>pf(s)),[C,v]=i.useState(null),[j,P]=i.useState(null),[U,E]=i.useState(null),R=i.useRef(null),L=i.useRef(null),F=i.useRef(e),M=i.useRef(!1),[O,q]=i.useState(()=>mf(s));i.useEffect(()=>{q(mf(s))},[s]),i.useEffect(()=>{if(!e||!h)return;const H=L.current;if(!H||typeof ResizeObserver>"u")return;let ke=null;const pe=new ResizeObserver(Ae=>{const Oe=Ae[0];if(!Oe)return;const{width:He,height:dt}=Oe.contentRect;He<=0||dt<=0||(ke&&clearTimeout(ke),ke=setTimeout(()=>{ss(Bx,JSON.stringify({width:Math.round(He),height:Math.round(dt)}),s)},250))});return pe.observe(H),()=>{ke&&clearTimeout(ke),pe.disconnect()}},[e,h,s]),i.useEffect(()=>{e||(M.current=!1)},[e]),i.useEffect(()=>{r.length>0&&(M.current=!0)},[r.length]),i.useEffect(()=>{if(typeof window>"u")return;const H=window.matchMedia?.("(pointer: coarse)"),ke=()=>{f(window.innerWidth>=769),g(H?.matches??!1)};return ke(),window.addEventListener("resize",ke),H?.addEventListener?.("change",ke),()=>{window.removeEventListener("resize",ke),H?.removeEventListener?.("change",ke)}},[]),i.useEffect(()=>{!F.current&&e&&(!c||Date.now()-c.getTime()>5e3)&&d(),F.current=e},[e,c,d]),i.useEffect(()=>{const H=An("kb-usage-view-mode",s);if(H==="used"||H==="remaining"){w(H);return}w("used")},[s]);const te=i.useCallback(H=>{w(H),ss("kb-usage-view-mode",H,s)},[s]);i.useEffect(()=>{y(hf(s)),k(pf(s))},[s]),i.useEffect(()=>{r$(b,s)},[b,s]);const Z=i.useCallback((H,ke)=>{y(pe=>{if(qx(H,ke,pe)){const Ae=(pe[H]??[]).filter(Oe=>Oe!==ke);if(Ae.length===0){const{[H]:Oe,...He}=pe;return He}return{...pe,[H]:Ae}}return{...pe,[H]:[...pe[H]??[],ke]}})},[]),K=i.useCallback(H=>{y(ke=>{if(!ke[H])return ke;const{[H]:pe,...Ae}=ke;return Ae})},[]),A=i.useCallback(H=>{if(S.length===0)return H;const ke=new Map(H.map(Ae=>[Ae.name,Ae])),pe=[];for(const Ae of S){const Oe=ke.get(Ae);Oe&&(pe.push(Oe),ke.delete(Ae))}return[...pe,...ke.values()]},[S]),I=i.useCallback((H,ke)=>{H.dataTransfer.effectAllowed="move",H.dataTransfer.setData("text/plain",ke),v(ke)},[]),$=i.useCallback((H,ke)=>{if(!C||C===ke)return;H.preventDefault(),H.dataTransfer.dropEffect="move";const{top:pe,height:Ae}=H.currentTarget.getBoundingClientRect(),Oe=pe+Ae/2,He=H.clientY<Oe?"before":"after";P(ke),E(He)},[C]),N=i.useCallback((H,ke)=>{H.preventDefault();const pe=C??H.dataTransfer.getData("text/plain");if(!pe||pe===ke){P(null),E(null);return}const Oe=A(r).map(Fe=>Fe.name).filter(Fe=>Fe!==pe),He=Oe.indexOf(ke);if(He<0){P(null),E(null);return}const dt=U==="after"?He+1:He;Oe.splice(dt,0,pe),ff(Oe,s),k(Oe),P(null),E(null)},[C,U,s,r,A]),G=i.useCallback(()=>{v(null),P(null),E(null)},[]),xe=i.useCallback((H,ke)=>{const pe=A(r).map(Fe=>Fe.name),Ae=pe.indexOf(H),Oe=Ae+ke;if(Ae<0||Oe<0||Oe>=pe.length)return;const He=[...pe],[dt]=He.splice(Ae,1);He.splice(Oe,0,dt),ff(He,s),k(He)},[s,r,A]),Se=i.useCallback(async()=>{m(!0),await d(),m(!1)},[d]);i.useEffect(()=>{if(!e)return;const H=ke=>{ke.key==="Escape"&&n()};return document.addEventListener("keydown",H),()=>document.removeEventListener("keydown",H)},[e,n]);const je=i.useCallback(H=>{H.target===H.currentTarget&&n()},[n]);if(!e)return null;const se=!!(a&&h),Ve=8,ee=12,ne=O?.width??420,re=se?Math.min((a?.bottom??0)+Ve,window.innerHeight-ee):void 0,J=se?Math.max(8,(a?.right??0)-ne):void 0,B=h&&O?{width:O.width,height:O.height}:{},ye=A(r),Ce=t.jsxs("div",{ref:L,className:`usage-modal${se?" usage-modal--popover":" modal"}`,"data-testid":"usage-modal",style:se?{position:"fixed",top:re,left:J,...B}:B,children:[t.jsxs("div",{className:"modal-header",children:[t.jsxs("div",{className:"usage-header",children:[t.jsx(Ks,{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 ${x==="used"?"active":""}`,onClick:()=>te("used"),"aria-pressed":x==="used","data-testid":"usage-view-toggle-used",children:"Used"}),t.jsx("button",{className:`usage-view-toggle-btn ${x==="remaining"?"active":""}`,onClick:()=>te("remaining"),"aria-pressed":x==="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(nn,{size:20})})]})]}),t.jsx("div",{className:"usage-content",ref:R,children:(o||!M.current&&!l)&&r.length===0?t.jsx(d$,{}):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:Se,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:ye.map((H,ke)=>t.jsx(c$,{provider:H,viewMode:x,hiddenWindows:b,onToggleWindow:Z,onShowAllHidden:K,isDragging:C===H.name,isDragOver:j===H.name,dragOverPosition:j===H.name?U:null,onDragStart:pe=>I(pe,H.name),onDragOver:pe=>$(pe,H.name),onDragLeave:()=>{j===H.name&&(P(null),E(null))},onDrop:pe=>N(pe,H.name),onDragEnd:G,isTouchReorderMode:p,canMoveUp:ke>0,canMoveDown:ke<ye.length-1,onMoveUp:()=>xe(H.name,-1),onMoveDown:()=>xe(H.name,1)},H.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:Se,disabled:o||u,"data-testid":"usage-refresh-btn",children:[t.jsx(os,{size:14,className:u?"spin":"",style:{marginRight:6}}),"Refresh"]}),t.jsx("button",{className:"btn btn-primary btn-sm",onClick:n,children:"Close"})]})]})]});return se?t.jsxs(t.Fragment,{children:[t.jsx("div",{className:"usage-popover-backdrop",onClick:n,"data-testid":"usage-modal-overlay"}),Ce]}):t.jsx("div",{className:"modal-overlay open",onClick:je,"data-testid":"usage-modal-overlay",children:Ce})}function Vx(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 Fl(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 m$={cron:"var(--color-blue, #3b82f6)",webhook:"var(--color-purple, #a855f7)",api:"var(--color-green, #22c55e)",manual:"var(--color-gray, #6b7280)"},Wx={cron:"Cron",webhook:"Webhook",api:"API",manual:"Manual"},h$={cron:fg,webhook:Cg,api:gg,manual:Qn},p$={parallel:"Concurrent",queue:"Queued",reject:"Exclusive"},f$={run:"Catch up",skip:"Skip missed",run_one:"Catch up (latest)"};function g$({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(Dn,{size:12}):t.jsx(wo,{size:12}),t.jsx("span",{children:e.success?"Success":"Failed"}),n>0&&t.jsx("span",{className:"schedule-run-duration",children:Vx(n)})]})}function b$({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"} ${Fl(e.startedAt)}`,children:[t.jsx("span",{className:`schedule-history-status ${e.success?"success":"failure"}`,children:e.success?t.jsx(Dn,{size:12}):t.jsx(wo,{size:12})}),t.jsx("span",{className:"schedule-history-time",children:Fl(e.startedAt)}),e.triggerType&&t.jsx("span",{className:"routine-history-trigger-type",children:Wx[e.triggerType]}),t.jsx("span",{className:"schedule-history-duration",children:Vx(r)}),s?t.jsx(Ei,{size:12}):t.jsx(rn,{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 x$({routine:e,onEdit:n,onDelete:s,onRun:a,onToggle:r,running:o,lastRunOutput:l}){const[c,d]=i.useState(!1),{confirm:u}=ai(),m=i.useCallback(async()=>{await u({title:"Delete Routine",message:`Delete routine "${e.name}"? This cannot be undone.`,danger:!0})&&s(e)},[e,s,u]),h=m$[e.trigger.type],f=h$[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:h,color:h},children:[t.jsx(f,{size:10}),Wx[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(Kl,{size:10}):t.jsx(bs,{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(bt,{className:"spinner"}):t.jsx(Yn,{})}),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(pi,{}):t.jsx(Yn,{})}),t.jsx("button",{className:"btn-icon",onClick:()=>n(e),title:"Edit","aria-label":`Edit ${e.name}`,children:t.jsx(Ds,{})}),t.jsx("button",{className:"btn-icon",onClick:m,title:"Delete","aria-label":`Delete ${e.name}`,children:t.jsx(vn,{})})]})]}),t.jsxs("div",{className:"routine-card-meta",children:[e.steps&&e.steps.length>0?t.jsxs("div",{className:"routine-meta-item",children:[t.jsx(ja,{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(Hi,{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:p$[e.executionPolicy]})}),t.jsx("div",{className:"routine-meta-item",children:t.jsx("span",{className:"routine-policy-badge",title:`Catch-up policy: ${e.catchUpPolicy}`,children:f$[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:Fl(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:Fl(e.lastRunAt)})]}),e.lastRunResult&&t.jsx(g$,{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(Ei,{size:12}):t.jsx(rn,{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,x)=>t.jsx(b$,{result:g,index:x},`${g.startedAt}-${x}`)),e.runHistory.length>10&&t.jsxs("div",{className:"schedule-history-more",children:["…and ",e.runHistory.length-10," more"]})]})]})]})}function v$({type:e,size:n=12}){return e==="command"?t.jsxs("span",{className:"step-type-badge step-type-command",title:"Command step",children:[t.jsx(Bi,{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(uw,{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(ps,{size:n}),t.jsx("span",{children:"AI Prompt"})]})}function fd(){return typeof crypto<"u"&&typeof crypto.randomUUID=="function"?crypto.randomUUID():`step-${Date.now()}-${Math.random().toString(36).slice(2,11)}`}function y$(e){return e==="command"?{id:fd(),type:e,name:"New Command Step",command:"",continueOnFailure:!1}:e==="ai-prompt"?{id:fd(),type:e,name:"New AI Prompt Step",prompt:"",continueOnFailure:!1}:{id:fd(),type:e,name:"New Create Task Step",taskDescription:"",taskColumn:"triage",continueOnFailure:!1}}function w$({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,m]=i.useState(e.prompt??""),[h,f]=i.useState(e.modelProvider??""),[p,g]=i.useState(e.modelId??""),[x,w]=i.useState(e.taskTitle??""),[b,y]=i.useState(e.taskDescription??""),[S,k]=i.useState(e.taskColumn??"triage"),[C,v]=i.useState(e.timeoutMs),[j,P]=i.useState(e.continueOnFailure??!1),[U,E]=i.useState({}),[R,L]=i.useState([]),[F,M]=i.useState(!1),[O,q]=i.useState(null);i.useEffect(()=>{let I=!1;return M(!0),q(null),Os().then($=>{I||L($.models)}).catch($=>{I||q($ instanceof Error?$.message:"Failed to load models")}).finally(()=>{I||M(!1)}),()=>{I=!0}},[]);const te=i.useCallback(()=>{const I={};return a.trim()||(I.name="Step name is required"),o==="command"&&!c.trim()&&(I.command="Command is required"),o==="ai-prompt"&&!u.trim()&&(I.prompt="Prompt is required"),o==="create-task"&&!b.trim()&&(I.taskDescription="Task description is required"),(o==="ai-prompt"||o==="create-task")&&(h||p)&&(!h||!p)&&(I.modelProvider="Both model provider and model ID must be set together"),C!==void 0&&C<1e3&&(I.timeoutMs="Timeout must be at least 1 second (1000ms)"),E(I),Object.keys(I).length===0},[a,o,c,u,b,h,p,C]),Z=h&&p?`${h}/${p}`:"",K=i.useCallback(I=>{if(!I)f(""),g("");else{const $=I.indexOf("/");$!==-1&&(f(I.slice(0,$)),g(I.slice($+1)))}},[]),A=i.useCallback(()=>{if(!te())return;const I={...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"&&x.trim()?x.trim():void 0,taskDescription:o==="create-task"&&b.trim()?b.trim():void 0,taskColumn:o==="create-task"?S:void 0,modelProvider:(o==="ai-prompt"||o==="create-task")&&h.trim()?h.trim():void 0,modelId:(o==="ai-prompt"||o==="create-task")&&p.trim()?p.trim():void 0,timeoutMs:C||void 0,continueOnFailure:j};o!=="ai-prompt"&&delete I.prompt,o!=="create-task"&&(delete I.taskTitle,delete I.taskDescription,delete I.taskColumn),n(I)},[te,n,e,a,o,c,u,x,b,S,h,p,C,j]);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:I=>r(I.target.value),"aria-invalid":!!U.name}),U.name&&t.jsx("small",{className:"field-error",children:U.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:I=>l(I.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:I=>d(I.target.value),rows:2,"aria-invalid":!!U.command}),U.command&&t.jsx("small",{className:"field-error",children:U.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:I=>m(I.target.value),rows:3,"aria-invalid":!!U.prompt}),U.prompt&&t.jsx("small",{className:"field-error",children:U.prompt})]}),t.jsxs("div",{className:"form-group",children:[t.jsx("label",{htmlFor:`step-model-${e.id}`,children:"Model (optional)"}),t.jsx(ys,{id:`step-model-${e.id}`,label:"Model",models:R,value:Z,onChange:K,placeholder:"Use default",disabled:F}),O&&t.jsx("small",{className:"field-error",children:O}),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:x,onChange:I=>w(I.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:I=>y(I.target.value),rows:4,"aria-invalid":!!U.taskDescription}),U.taskDescription&&t.jsx("small",{className:"field-error",children:U.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:S,onChange:I=>k(I.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(ys,{id:`step-task-model-${e.id}`,label:"Model",models:R,value:Z,onChange:K,placeholder:"Use default",disabled:F}),O&&t.jsx("small",{className:"field-error",children:O}),U.modelProvider&&t.jsx("small",{className:"field-error",children:U.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:I=>v(I.target.value?Number(I.target.value):void 0),"aria-invalid":!!U.timeoutMs}),U.timeoutMs&&t.jsx("small",{className:"field-error",children:U.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:j,onChange:I=>P(I.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:A,children:"Save Step"})]})]})}function k$({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 m=y$(u);n([...e,m]),r(m.id)},[e,n]),l=i.useCallback(u=>{n(e.filter(m=>m.id!==u)),a===u&&r(null)},[e,n,a]),c=i.useCallback((u,m)=>{const h=e.findIndex(g=>g.id===u);if(h<0)return;const f=m==="up"?h-1:h+1;if(f<0||f>=e.length)return;const p=[...e];[p[h],p[f]]=[p[f],p[h]],n(p)},[e,n]),d=i.useCallback(u=>{n(e.map(m=>m.id===u.id?u:m)),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,m)=>t.jsx("div",{className:"step-card",children:a===u.id?t.jsx(w$,{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(Jl,{size:14})}),t.jsx("span",{className:"step-card-index",children:m+1}),t.jsx(v$,{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:m===0,title:"Move up","aria-label":`Move ${u.name} up`,children:t.jsx(Ei,{})}),t.jsx("button",{type:"button",className:"btn-icon",onClick:()=>c(u.id,"down"),disabled:m===e.length-1,title:"Move down","aria-label":`Move ${u.name} down`,children:t.jsx(rn,{})}),t.jsx("button",{type:"button",className:"btn-icon",onClick:()=>r(u.id),title:"Edit","aria-label":`Edit ${u.name}`,children:t.jsx(Ds,{})}),t.jsx("button",{type:"button",className:"btn-icon",onClick:()=>l(u.id),title:"Delete","aria-label":`Delete ${u.name}`,children:t.jsx(vn,{})})]})]})},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(gn,{size:14}),"Add Command Step"]}),t.jsxs("button",{type:"button",className:"btn btn-sm",onClick:()=>o("ai-prompt"),children:[t.jsx(gn,{size:14}),"Add AI Prompt Step"]}),t.jsxs("button",{type:"button",className:"btn btn-sm",onClick:()=>o("create-task"),children:[t.jsx(gn,{size:14}),"Add Create Task Step"]})]})]})}const Kx={hourly:"0 * * * *",daily:"0 0 * * *",weekly:"0 0 * * 1",monthly:"0 0 1 * *"},j$={hourly:"Every hour",daily:"Every day (midnight)",weekly:"Every week (Monday)",monthly:"Every month (1st)",custom:"Custom cron expression"};function N$(e){const n=e.trim();for(const[s,a]of Object.entries(Kx))if(a===n)return s;return"custom"}function S$(e){const n=e.trim().split(/\s+/);return n.length!==5?!1:n.every(s=>/^[\d*,/-]+$/.test(s))}function C$(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 E$(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 _$=[{value:"parallel",label:"Allow concurrent runs"},{value:"queue",label:"Queue after current (one at a time)"},{value:"reject",label:"Reject new runs while running"}],M$=[{value:"skip",label:"Skip missed runs"},{value:"run_one",label:"Run the most recent missed run"},{value:"run",label:"Run all missed runs"}];function gf(){return typeof crypto<"u"&&typeof crypto.randomUUID=="function"?crypto.randomUUID():`step-${Date.now()}-${Math.random().toString(36).slice(2,11)}`}function bf({routine:e,onSubmit:n,onCancel:s,scope:a,projectId:r,onScopeChange:o}){const l=!!e,c=e?E$(e):{triggerType:"cron",cronExpression:"0 * * * *",webhookPath:"",webhookSecret:"",endpoint:""},[d,u]=i.useState(e?.name??""),[m,h]=i.useState(e?.description??""),[f,p]=i.useState(c.triggerType),[g,x]=i.useState(c.cronExpression),[w,b]=i.useState(()=>c.triggerType!=="cron"?"custom":N$(c.cronExpression)),[y,S]=i.useState(c.webhookPath),[k,C]=i.useState(c.webhookSecret),[v,j]=i.useState(c.endpoint),[P,U]=i.useState(e?.executionPolicy??"queue"),[E,R]=i.useState(e?.catchUpPolicy??"run_one"),[L,F]=i.useState(e?.enabled??!0),M=e?.steps&&e.steps.length===1&&e.steps[0].type==="ai-prompt"&&!e.command,O=e?.steps&&e.steps.length===1&&e.steps[0].type==="create-task"&&!e.command,[q,te]=i.useState(e?.steps&&e.steps.length>0&&!M&&!O?"advanced":"simple"),[Z,K]=i.useState(()=>M?"ai-prompt":O?"create-task":"command"),[A,I]=i.useState(e?.command??""),[$,N]=i.useState(e?.steps??[]),[G,xe]=i.useState(!1),[Se,je]=i.useState(e?.timeoutMs??3e5),[se,Ve]=i.useState(M?e.steps?.[0]?.prompt??"":""),[ee,ce]=i.useState(O?e.steps?.[0]?.taskTitle??"":""),[ne,re]=i.useState(O?e.steps?.[0]?.taskDescription??"":""),[J,B]=i.useState(O?e.steps?.[0]?.taskColumn??"triage":"triage"),[ye,Ce]=i.useState(M||O?e.steps?.[0]?.modelProvider??"":""),[H,ke]=i.useState(M||O?e.steps?.[0]?.modelId??"":""),[pe,Ae]=i.useState([]),[Oe,He]=i.useState(!1),[dt,Fe]=i.useState(null),[fe,$e]=i.useState(a??"global"),[De,ot]=i.useState({}),[Be,we]=i.useState(!1),Q=i.useRef(!0);i.useEffect(()=>()=>{Q.current=!1},[]),i.useEffect(()=>{a&&$e(a)},[a]),i.useEffect(()=>{let me=!1;return He(!0),Fe(null),Os().then(tt=>{me||Ae(tt.models)}).catch(tt=>{me||Fe(tt instanceof Error?tt.message:"Failed to load models")}).finally(()=>{me||He(!1)}),()=>{me=!0}},[]);const _e=ye&&H?`${ye}/${H}`:"",lt=i.useCallback(me=>{if(!me){Ce(""),ke("");return}const tt=me.indexOf("/");tt!==-1&&(Ce(me.slice(0,tt)),ke(me.slice(tt+1)))},[]),ht=i.useCallback(()=>{const me={};if(d.trim()||(me.name="Name is required"),fe==="project"&&!r&&(me.scope="Project-specific entries require an active project."),f==="cron"&&w==="custom"&&(g.trim()?S$(g)||(me.cronExpression="Invalid cron format — expected 5 fields (e.g. '0 */6 * * *')"):me.cronExpression="Cron expression is required"),f==="webhook"&&!y.trim()&&(me.webhookPath="Webhook path is required"),f==="api"&&!v.trim()&&(me.endpoint="API endpoint is required"),q==="simple")Z==="command"&&!A.trim()&&(me.command="Command is required"),Z==="ai-prompt"&&!se.trim()&&(me.prompt="Prompt is required"),Z==="create-task"&&!ne.trim()&&(me.taskDescription="Task description is required"),(ye.trim()&&!H.trim()||!ye.trim()&&H.trim())&&(me.model="Both model provider and model ID must be set, or both must be empty");else{$.length===0&&(me.steps="At least one step is required"),G&&(me.stepsEditing="Please save or cancel all step edits before saving the routine");const tt=[];$.forEach((Ct,wt)=>{Ct.name?.trim()||tt.push(`Step ${wt+1}: Name is required`),Ct.type==="command"&&!Ct.command?.trim()&&tt.push(`Step ${wt+1}: Command is required`),Ct.type==="ai-prompt"&&!Ct.prompt?.trim()&&tt.push(`Step ${wt+1}: Prompt is required`),Ct.type==="create-task"&&!Ct.taskDescription?.trim()&&tt.push(`Step ${wt+1}: Task description is required`)}),tt.length>0&&(me.steps=tt.join("; "))}return Se<1e3&&(me.timeoutMs="Timeout must be at least 1 second (1000ms)"),ot(me),Object.keys(me).length===0},[d,f,g,w,y,v,fe,r,q,Z,A,se,ne,ye,H,$,G,Se]),mt=i.useCallback(async me=>{if(me.preventDefault(),!!ht()){we(!0);try{let tt=e?.scope??fe??(r?"project":"global");tt==="project"&&!r&&(tt="global");const Ct=C$(f,g,y,k,v);let wt,$t;q==="simple"?Z==="command"?wt=A.trim()||void 0:Z==="ai-prompt"?$t=[{id:gf(),type:"ai-prompt",name:d.trim(),prompt:se.trim(),modelProvider:ye.trim()||void 0,modelId:H.trim()||void 0}]:$t=[{id:gf(),type:"create-task",name:d.trim(),taskTitle:ee.trim()||void 0,taskDescription:ne.trim(),taskColumn:J,modelProvider:ye.trim()||void 0,modelId:H.trim()||void 0}]:$t=$;const Vt={name:d.trim(),agentId:e?.agentId??"",description:m.trim()||void 0,trigger:Ct,command:wt,steps:$t,timeoutMs:Se,executionPolicy:P,catchUpPolicy:E,enabled:L,scope:tt};await n(Vt)}finally{Q.current&&we(!1)}}},[ht,n,d,m,f,g,y,k,v,q,Z,A,se,ye,H,ee,ne,J,$,Se,P,E,L,fe,r,e?.scope,e?.agentId]),xt="routine-name-error",Ie="routine-cron-error",Ue="routine-webhook-error",pt="routine-endpoint-error",oe="routine-command-error",le="routine-prompt-error",ge="routine-task-description-error",Ne="routine-model-error",ue="routine-timeout-error",qe=i.useCallback(me=>{b(me),me!=="custom"&&x(Kx[me])},[]);return t.jsxs("form",{className:"routine-form",onSubmit:mt,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:me=>u(me.target.value),"aria-invalid":!!De.name,"aria-describedby":De.name?xt:void 0}),De.name&&t.jsx("small",{id:xt,className:"field-error",children:De.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:m,onChange:me=>h(me.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${fe==="global"?" active":""}`,onClick:()=>{$e("global"),o?.("global")},role:"radio","aria-checked":fe==="global"?"true":"false",disabled:!!e?.scope,title:e?.scope?`Scope is locked to ${e.scope} for existing routines`:"Global scope",children:[t.jsx(Kl,{size:12}),"Global"]}),t.jsxs("button",{type:"button",className:`routine-scope-btn${fe==="project"?" active":""}`,onClick:()=>{$e("project"),o?.("project")},role:"radio","aria-checked":fe==="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(bs,{size:12}),"Project"]})]}),t.jsx("small",{children:!r&&!e?.scope?"No active project. Routines will be created at global scope.":fe==="project"&&r?"This routine will be scoped to the current project.":"This routine will be created at global scope."}),De.scope&&t.jsx("small",{className:"field-error",children:De.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(fg,{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(Cg,{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(gg,{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(Qn,{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:w,onChange:me=>qe(me.target.value),children:Object.entries(j$).map(([me,tt])=>t.jsx("option",{value:me,children:tt},me))}),t.jsx("label",{htmlFor:"routine-cron",children:"Cron Expression"}),t.jsx("input",{id:"routine-cron",type:"text",placeholder:"* * * * *",value:g,onChange:me=>x(me.target.value),disabled:w!=="custom","aria-invalid":!!De.cronExpression,"aria-describedby":De.cronExpression?Ie:void 0}),De.cronExpression?t.jsx("small",{id:Ie,className:"field-error",children:De.cronExpression}):t.jsx("small",{children:w==="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:me=>S(me.target.value),"aria-invalid":!!De.webhookPath,"aria-describedby":De.webhookPath?Ue:void 0}),De.webhookPath?t.jsx("small",{id:Ue,className:"field-error",children:De.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:k,onChange:me=>C(me.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:v,onChange:me=>j(me.target.value),"aria-invalid":!!De.endpoint,"aria-describedby":De.endpoint?pt:void 0}),De.endpoint?t.jsx("small",{id:pt,className:"field-error",children:De.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:()=>te("simple"),role:"radio","aria-checked":q==="simple",children:"Simple"}),t.jsx("button",{type:"button",className:`schedule-mode-btn${q==="advanced"?" active":""}`,onClick:()=>te("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${Z==="command"?" active":""}`,onClick:()=>K("command"),role:"radio","aria-checked":Z==="command",children:"Command"}),t.jsx("button",{type:"button",className:`schedule-mode-btn${Z==="ai-prompt"?" active":""}`,onClick:()=>K("ai-prompt"),role:"radio","aria-checked":Z==="ai-prompt",children:"AI Prompt"}),t.jsx("button",{type:"button",className:`schedule-mode-btn${Z==="create-task"?" active":""}`,onClick:()=>K("create-task"),role:"radio","aria-checked":Z==="create-task",children:"Create Task"})]})]}),Z==="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:A,onChange:me=>I(me.target.value),"aria-invalid":!!De.command,"aria-describedby":De.command?oe:void 0}),De.command?t.jsx("small",{id:oe,className:"field-error",children:De.command}):t.jsx("small",{children:"Shell command to execute."})]}):Z==="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:se,onChange:me=>Ve(me.target.value),rows:3,"aria-invalid":!!De.prompt,"aria-describedby":De.prompt?le:void 0}),De.prompt?t.jsx("small",{id:le,className:"field-error",children:De.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(ys,{id:"routine-model",label:"Model",models:pe,value:_e,onChange:lt,placeholder:"Use default",disabled:Oe}),dt&&t.jsx("small",{className:"field-error",children:dt}),De.model&&t.jsx("small",{id:Ne,className:"field-error",children:De.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:ee,onChange:me=>ce(me.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:ne,onChange:me=>re(me.target.value),rows:4,"aria-invalid":!!De.taskDescription,"aria-describedby":De.taskDescription?ge:void 0}),De.taskDescription?t.jsx("small",{id:ge,className:"field-error",children:De.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:J,onChange:me=>B(me.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(ys,{id:"routine-task-model",label:"Executor Model",models:pe,value:_e,onChange:lt,placeholder:"Use default",disabled:Oe}),dt&&t.jsx("small",{className:"field-error",children:dt}),De.model&&t.jsx("small",{id:Ne,className:"field-error",children:De.model})]})]})]}):t.jsxs(t.Fragment,{children:[t.jsx(k$,{steps:$,onChange:N,onEditingChange:xe}),De.steps&&t.jsx("small",{className:"field-error",children:De.steps}),De.stepsEditing&&t.jsx("small",{className:"field-error",children:De.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:Se,onChange:me=>je(Number(me.target.value)),"aria-invalid":!!De.timeoutMs,"aria-describedby":De.timeoutMs?ue:void 0}),De.timeoutMs?t.jsx("small",{id:ue,className:"field-error",children:De.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:P,onChange:me=>U(me.target.value),children:_$.map(me=>t.jsx("option",{value:me.value,children:me.label},me.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:me=>R(me.target.value),children:M$.map(me=>t.jsx("option",{value:me.value,children:me.label},me.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:L,onChange:me=>F(me.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:Be,children:"Cancel"}),t.jsx("button",{type:"submit",className:"btn btn-primary btn-sm",disabled:Be,children:Be?"Saving…":l?"Save Changes":"Create Routine"})]})]})}const A$=3e4;function P$({onClose:e,addToast:n,projectId:s}){const[a,r]=i.useState(()=>s?"project":"global"),[o,l]=i.useState([]),[c,d]=i.useState("list"),[u,m]=i.useState(),[h,f]=i.useState(null),[p,g]=i.useState({}),x=i.useRef(null);Ai(x,!0,"fusion:automation-modal-size");const w=i.useMemo(()=>({scope:a,projectId:a==="project"?s:void 0}),[a,s]),b=i.useCallback(async()=>{try{const M=await BN(w);l(M),g(O=>{const q={...O};for(const te of M){const Z=q[te.id];if(!Z||!te.lastRunResult)continue;const K=te.lastRunResult;K.success===Z.success&&(K.output||"")===Z.output&&(K.error||"")===(Z.error||"")&&delete q[te.id]}return q})}catch(M){n(Pe(M)||"Failed to load routines","error")}},[n,w]);i.useEffect(()=>{b()},[b]),i.useEffect(()=>{const M=setInterval(()=>{b()},A$);return()=>clearInterval(M)},[b]),i.useEffect(()=>{const M=O=>{O.key==="Escape"&&(c!=="list"?(d("list"),m(void 0)):e())};return document.addEventListener("keydown",M),()=>document.removeEventListener("keydown",M)},[e,c]);const y=qi(e),S=i.useCallback(async M=>{try{await HN(M,w),n("Routine created","success"),d("list"),await b()}catch(O){n(Pe(O)||"Failed to create routine","error")}},[n,b,w]),k=i.useCallback(M=>{m(M),d("edit")},[]),C=i.useCallback(async M=>{if(u)try{await bm(u.id,M,w),n("Routine updated","success"),d("list"),m(void 0),await b()}catch(O){n(Pe(O)||"Failed to update routine","error")}},[u,n,b,w]),v=i.useCallback(async M=>{try{await qN(M.id,w),n(`Deleted "${M.name}"`,"success"),await b()}catch(O){n(Pe(O)||"Failed to delete routine","error")}},[n,b,w]),j=i.useCallback(async M=>{f(M.id);try{const{result:O}=await VN(M.id,w);g(q=>({...q,[M.id]:{output:O.output||"",error:O.error,success:O.success}})),O.success?n(`"${M.name}" completed successfully`,"success"):n(`"${M.name}" failed: ${O.error||"Unknown error"}`,"error"),await b()}catch(O){n(Pe(O)||"Failed to run routine","error")}finally{f(null)}},[n,b,w]),P=i.useCallback(async M=>{try{await bm(M.id,{enabled:!M.enabled},w),n(`"${M.name}" ${M.enabled?"disabled":"enabled"}`,"success"),await b()}catch(O){n(Pe(O)||"Failed to toggle routine","error")}},[n,b,w]),U=i.useCallback(()=>{d("list"),m(void 0)},[]);i.useEffect(()=>{c!=="list"&&g({})},[c]);const E=i.useCallback(M=>{r(M),d("list"),m(void 0),g({})},[]),R=()=>c==="create"?t.jsx(bf,{onSubmit:S,onCancel:U,scope:a,projectId:s}):c==="edit"&&u?t.jsx(bf,{routine:u,onSubmit:C,onCancel:U,scope:a,projectId:s}):o.length===0?t.jsxs("div",{className:"routine-empty-state",children:[t.jsx(Qn,{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(gn,{size:14}),"Create your first automation"]})]}):t.jsx("div",{className:"routine-list",children:o.map(M=>t.jsx(x$,{routine:M,onEdit:k,onDelete:v,onRun:j,onToggle:P,running:h===M.id,lastRunOutput:p[M.id]??null},M.id))}),L=()=>R(),F=c==="list"&&o.length>0;return t.jsx("div",{className:"modal-overlay open",...y,children:t.jsxs("div",{ref:x,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(Qn,{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(nn,{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(Kl,{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(bs,{size:14}),"Project"]})]}),t.jsxs("span",{className:"scheduling-count",children:[t.jsx(Qn,{size:14}),o.length," automation",o.length===1?"":"s"]})]}),t.jsx("div",{className:"scheduling-toolbar-right",children:F&&t.jsxs("button",{className:"btn btn-primary btn-sm",onClick:()=>d("create"),"aria-label":"Create new automation",children:[t.jsx(gn,{size:14}),"New Automation"]})})]}),t.jsx("div",{className:"schedule-modal-content",id:"scheduled-tasks-content",children:L()})]})})}const R$=3e4,su=new Map,gd=new Map;function xf(e){return e??"default"}function vf(e){const n=su.get(e);return n?Date.now()>=n.expiresAt?(su.delete(e),null):n:null}function I$(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 T$(e){const n=gd.get(e);if(n)return n;const s=uo().then(({providers:a,ghCli:r})=>{const l={...I$(a,r),ghCli:r,expiresAt:Date.now()+R$};return su.set(e,l),l}).finally(()=>{gd.delete(e)});return gd.set(e,s),s}function Gx(e){const n=xf(e),s=vf(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),m=i.useRef(!!s);return i.useEffect(()=>{let h=!1;const f=xf(e),p=vf(f);if(p)return r(p.hasAiProvider),l(p.hasGithub),c(p.ghCli),u(!1),m.current=!0,()=>{h=!0};m.current=!1;async function g(){!m.current&&u(!0);try{const w=await T$(f);if(h)return;r(w.hasAiProvider),l(w.hasGithub),c(w.ghCli)}catch{}finally{h||(m.current=!0,u(!1))}}return g(),()=>{h=!0}},[e]),i.useMemo(()=>({hasAiProvider:a,hasGithub:o,loading:d,hasWarnings:!a||!o}),[a,o,d])}function Jx({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(nn,{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 $$({isOpen:e,onClose:n,projectId:s,tasks:a,onCreateTask:r,addToast:o,onPlanningMode:l,onSubtaskBreakdown:c}){const{confirm:d}=ai(),u=Ys();vi(e);const{keyboardOverlap:m,viewportHeight:h,viewportOffsetTop:f,keyboardOpen:p}=Wi({enabled:u==="mobile"}),g=p?{"--keyboard-overlap":`${m}px`,"--vv-offset-top":`${f}px`,...h!==null?{"--vv-height":`${h}px`}:{}}:{},[x,w]=i.useState(""),[b,y]=i.useState([]),[S,k]=i.useState(""),[C,v]=i.useState(""),[j,P]=i.useState([]),[U,E]=i.useState(!1),[R,L]=i.useState(""),[F,M]=i.useState(""),[O,q]=i.useState(""),[te,Z]=i.useState(""),[K,A]=i.useState(""),[I,$]=i.useState("default"),[N,G]=i.useState(!1),[xe,Se]=i.useState([]),[je,se]=i.useState(!1),[Ve,ee]=i.useState(void 0),[ce,ne]=i.useState(js),[re,J]=i.useState(void 0),[B,ye]=i.useState(null),[Ce,H]=i.useState([]),[ke,pe]=i.useState(!1),[Ae,Oe]=i.useState(!1),He=i.useRef(null),[dt,Fe]=i.useState(!1),[fe,$e]=i.useState(""),De=i.useRef(null),{hasAiProvider:ot,hasGithub:Be,loading:we}=Gx(s),{nodes:Q}=nc(),_e=i.useCallback(ue=>{se(!0),Se(ue)},[]),lt=i.useCallback(()=>{se(!1)},[]),ht=i.useCallback(async()=>{if(Ce.length>0){pe(!0);return}Oe(!0);try{const ue=await Nr(void 0,s);H(ue),pe(!0)}catch(ue){const qe=Pe(ue);o(qe?`Failed to load agents: ${qe}`:"Failed to load agents","error"),pe(!1)}finally{Oe(!1)}},[Ce.length,s,o]);i.useEffect(()=>{if(!ke)return;const ue=qe=>{He.current&&!He.current.contains(qe.target)&&pe(!1)};return document.addEventListener("mousedown",ue),()=>document.removeEventListener("mousedown",ue)},[ke]),i.useEffect(()=>{if(!dt)return;const ue=qe=>{De.current&&!De.current.contains(qe.target)&&(Fe(!1),$e(""))};return document.addEventListener("mousedown",ue),()=>document.removeEventListener("mousedown",ue)},[dt]);const mt=a.filter(ue=>!b.includes(ue.id)).sort((ue,qe)=>{const me=qe.createdAt.localeCompare(ue.createdAt);if(me!==0)return me;const tt=parseInt(ue.id.slice(ue.id.lastIndexOf("-")+1),10)||0;return(parseInt(qe.id.slice(qe.id.lastIndexOf("-")+1),10)||0)-tt}),xt=fe?mt.filter(ue=>ue.id.toLowerCase().includes(fe.toLowerCase())||ue.title&&ue.title.toLowerCase().includes(fe.toLowerCase())||ue.description&&ue.description.toLowerCase().includes(fe.toLowerCase())):mt,Ie=(ue,qe)=>ue.length>qe?ue.slice(0,qe)+"…":ue;i.useEffect(()=>{const ue=x.trim()!==""||b.length>0||j.length>0||R!==""||F!==""||O!==""||te!==""||xe.length>0||B!==null||Ve!==void 0||ce!==js||re!==void 0||S!==""||C!=="";G(ue)},[x,b,j,R,F,O,te,xe,B,Ve,ce,re,S,C]);const Ue=i.useCallback(async()=>{N&&!await d({title:"Discard Changes",message:"You have unsaved changes. Discard them?",danger:!0})||(j.forEach(ue=>URL.revokeObjectURL(ue.previewUrl)),P([]),w(""),y([]),L(""),M(""),q(""),Z(""),A(""),$("default"),Se([]),se(!1),ye(null),pe(!1),ee(void 0),ne(js),J(void 0),k(""),v(""),G(!1),n())},[N,n,j,d]),pt=i.useCallback(async()=>{const ue=x.trim();if(!(!ue||U)){E(!0);try{const qe=R.indexOf("/"),me=F.indexOf("/"),tt=O.indexOf("/"),Ct=await r({title:void 0,description:ue,column:"triage",dependencies:b.length?b:void 0,enabledWorkflowSteps:je?xe.length>0?xe:[]:void 0,...B?{assignedAgentId:B}:{},modelPresetId:I==="preset"&&K||void 0,modelProvider:R&&qe!==-1?R.slice(0,qe):void 0,modelId:R&&qe!==-1?R.slice(qe+1):void 0,validatorModelProvider:F&&me!==-1?F.slice(0,me):void 0,validatorModelId:F&&me!==-1?F.slice(me+1):void 0,planningModelProvider:O&&tt!==-1?O.slice(0,tt):void 0,planningModelId:O&&tt!==-1?O.slice(tt+1):void 0,thinkingLevel:te!==""?te:void 0,reviewLevel:Ve,priority:ce,nodeId:re,branch:S.trim()===""?void 0:S.trim(),baseBranch:C.trim()===""?void 0:C.trim()});if(j.length>0){const wt=[];for(const $t of j)try{await ec(Ct.id,$t.file,s)}catch{wt.push($t.file.name)}wt.length>0&&o(`Failed to upload: ${wt.join(", ")}`,"error")}j.forEach(wt=>URL.revokeObjectURL(wt.previewUrl)),P([]),w(""),y([]),L(""),M(""),q(""),Z(""),A(""),$("default"),Se([]),se(!1),ye(null),pe(!1),ee(void 0),ne(js),J(void 0),k(""),v(""),o(`Created ${Ct.id}`,"success"),n()}catch(qe){o(Pe(qe)||"Failed to create task","error")}finally{E(!1)}}},[x,b,j,R,F,O,te,U,r,o,n,s,I,K,xe,je,B,Ve,ce,re,S,C]),oe=i.useCallback(ue=>{ue.key==="Escape"&&(ue.preventDefault(),Ue())},[Ue]),ge=(B?Ce.find(ue=>ue.id===B):void 0)?.name??B,Ne=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:De,children:[t.jsx("button",{type:"button",className:"btn btn-sm dep-trigger",onClick:()=>Fe(ue=>!ue),disabled:U,"data-testid":"dep-trigger",children:b.length>0?`${b.length} selected`:"Add dependencies"}),dt&&t.jsxs("div",{className:"dep-dropdown",children:[t.jsx("input",{className:"dep-dropdown-search",placeholder:"Search tasks…",autoFocus:!0,value:fe,onChange:ue=>$e(ue.target.value),onClick:ue=>ue.stopPropagation()}),xt.length===0?t.jsx("div",{className:"dep-dropdown-empty",children:"No available tasks"}):xt.map(ue=>t.jsxs("div",{className:`dep-dropdown-item${b.includes(ue.id)?" selected":""}`,onClick:()=>{y(b.includes(ue.id)?b.filter(qe=>qe!==ue.id):[...b,ue.id]),Fe(!1),$e("")},onMouseDown:qe=>qe.preventDefault(),children:[t.jsx("span",{className:"dep-dropdown-id",children:ue.id}),t.jsx("span",{className:"dep-dropdown-title",children:Ie(ue.title||ue.description||ue.id,30)})]},ue.id))]})]}),b.length>0&&t.jsx("div",{className:"selected-deps",children:b.map(ue=>t.jsxs("span",{className:"dep-chip",children:[ue,t.jsx("button",{type:"button",className:"dep-chip-remove",onClick:()=>y(b.filter(qe=>qe!==ue)),disabled:U,children:"×"})]},ue))})]}),t.jsxs("div",{className:"form-group",children:[t.jsx("label",{children:"Assign Agent"}),t.jsxs("div",{className:"agent-trigger-wrap",ref:He,children:[t.jsxs("button",{type:"button",className:"btn btn-sm dep-trigger",onClick:()=>{ke?pe(!1):ht()},disabled:U,"data-testid":"new-task-agent-button",children:[t.jsx($n,{size:12,style:{verticalAlign:"middle"}}),ge?` ${ge}`:" Assign agent"]}),ke&&t.jsxs("div",{className:"dep-dropdown agent-picker-dropdown",onMouseDown:ue=>ue.preventDefault(),children:[t.jsx("div",{className:"dep-dropdown-search-header",children:"Select agent"}),Ae&&t.jsx("div",{className:"dep-dropdown-empty",children:"Loading agents..."}),!Ae&&Ce.map(ue=>t.jsxs("div",{className:`dep-dropdown-item${B===ue.id?" selected":""}`,onMouseDown:qe=>qe.preventDefault(),onClick:()=>{ye(ue.id===B?null:ue.id),pe(!1)},"data-testid":`agent-option-${ue.id}`,children:[t.jsx($n,{size:12,style:{marginRight:6}}),t.jsx("span",{className:"dep-dropdown-id",children:ue.role}),t.jsx("span",{className:"dep-dropdown-title",children:ue.name})]},ue.id)),!Ae&&Ce.length===0&&t.jsx("div",{className:"dep-dropdown-empty",children:"No agents available"}),B&&t.jsx("div",{className:"dep-dropdown-item",onMouseDown:ue=>ue.preventDefault(),onClick:()=>{ye(null),pe(!1)},children:t.jsx("span",{className:"dep-dropdown-title",children:"Clear selection"})})]})]})]})]});return e?t.jsx("div",{className:"modal-overlay open",onClick:Ue,onKeyDown:oe,role:"dialog","aria-modal":"true",children:t.jsxs("div",{className:"modal modal-lg new-task-modal",onClick:ue=>ue.stopPropagation(),style:g,children:[t.jsxs("div",{className:"modal-header",children:[t.jsx("h3",{children:"New Task"}),t.jsx("button",{className:"modal-close",onClick:Ue,disabled:U,"aria-label":"Close",children:"×"})]}),t.jsxs("div",{className:"modal-body",children:[!we&&t.jsx(Jx,{hasAiProvider:ot,hasGithub:Be}),t.jsx(Mx,{mode:"create",description:x,onDescriptionChange:w,dependencies:b,onDependenciesChange:y,executorModel:R,onExecutorModelChange:L,validatorModel:F,onValidatorModelChange:M,presetMode:I,onPresetModeChange:$,selectedPresetId:K,onSelectedPresetIdChange:A,selectedWorkflowSteps:xe,onWorkflowStepsChange:_e,onDefaultOnApplied:lt,pendingImages:j,onImagesChange:P,tasks:a,projectId:s,disabled:U,addToast:o,isActive:e,onPlanningMode:l,onSubtaskBreakdown:c,onClose:Ue,planningModel:O,onPlanningModelChange:q,thinkingLevel:te,onThinkingLevelChange:Z,reviewLevel:Ve,onReviewLevelChange:ee,priority:ce,onPriorityChange:ne,branch:S,onBranchChange:k,baseBranch:C,onBaseBranchChange:v,nodeId:re,onNodeIdChange:J,nodeOptions:Q,renderBelowPrimary:Ne,hideDependencies:!0,autoExpandMoreOptionsOnSelection:!1})]}),t.jsxs("div",{className:"modal-actions",children:[t.jsx("button",{className:"btn btn-sm",onClick:Ue,disabled:U,children:"Cancel"}),t.jsx("button",{className:"btn btn-primary btn-sm",onClick:pt,disabled:!x.trim()||U,children:U?"Creating...":"Create Task"})]})]})}):null}function ui(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 yf(e,n){return!Number.isFinite(e)||!Number.isFinite(n)||n<=0?"—":`${(e/n*100).toFixed(1)}%`}function D$(e,n){if(n<=0)return"normal";const s=e/n;return s>=.85?"critical":s>=.65?"warning":"normal"}function L$(e,n){if(n<=0)return"normal";const s=e/n;return s>=.5?"critical":s>=.25?"warning":"normal"}function O$(e,n){if(n<=0)return"normal";const s=e/n;return s>=.9?"critical":s>=.75?"warning":"normal"}function z$(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 ul(e){return e==="critical"?"system-stats-modal__value--critical":e==="warning"?"system-stats-modal__value--warning":""}function F$(e){if(!e)return"Not yet";const n=new Date(e);return Number.isNaN(n.getTime())?"Not yet":n.toLocaleString()}function U$({isOpen:e,onClose:n,projectId:s}){const[a,r]=i.useState(null),[o,l]=i.useState(!1),[c,d]=i.useState(null),[u,m]=i.useState(!0),[h,f]=i.useState(90),[p,g]=i.useState(!1),[x,w]=i.useState(!1),[b,y]=i.useState(null),[S,k]=i.useState(null),[C,v]=i.useState(null),j=i.useCallback(async ee=>{l(!0);try{const ce=await CS(s);r(ce),d(null),v(Date.now()),ee?.preserveKillResult||y(null)}catch(ce){d(ce instanceof Error?ce.message:"Failed to load system stats")}finally{l(!1)}},[s]);i.useEffect(()=>{if(!e)return;j();const ee=window.setInterval(()=>{j()},5e3);return()=>{window.clearInterval(ee)}},[e,j]),i.useEffect(()=>{if(!e)return;(async()=>{try{const ce=await Pa();m(ce.vitestAutoKillEnabled??!0),f(ce.vitestKillThresholdPct??90),k(null)}catch(ce){k(ce instanceof Error?ce.message:"Failed to load vitest settings")}})()},[e]),i.useEffect(()=>{if(!e)return;const ee=ce=>{ce.key==="Escape"&&n()};return document.addEventListener("keydown",ee),()=>document.removeEventListener("keydown",ee)},[e,n]);const P=i.useMemo(()=>{if(!a)return[];const ee=a.systemStats,ce=ul(D$(ee.heapUsed,ee.heapLimit)),ne=ul(L$(ee.rss,ee.systemTotalMem));return[{label:"RSS",value:ui(ee.rss),detail:yf(ee.rss,ee.systemTotalMem),className:ne},{label:"Heap Used",value:ui(ee.heapUsed),detail:`of ${ui(ee.heapTotal)}`,className:ce},{label:"Heap Limit",value:ui(ee.heapLimit),detail:"V8 limit"},{label:"External",value:ui(ee.external)},{label:"Array Buffers",value:ui(ee.arrayBuffers)}]},[a]),U=i.useCallback(async ee=>{m(ee);try{await kn({vitestAutoKillEnabled:ee}),k(null)}catch(ce){k(ce instanceof Error?ce.message:"Failed to save vitest settings")}},[]),E=i.useCallback(async ee=>{const ce=Math.min(99,Math.max(50,Number.isFinite(ee)?Math.round(ee):90));f(ce);try{await kn({vitestKillThresholdPct:ce}),k(null)}catch(ne){k(ne instanceof Error?ne.message:"Failed to save vitest settings")}},[]),R=i.useCallback(async()=>{if(!p){if(!x){w(!0);return}g(!0);try{const ee=await ES(s);y(ee),w(!1),await j({preserveKillResult:!0})}catch(ee){d(ee instanceof Error?ee.message:"Failed to kill vitest processes")}finally{g(!1)}}},[x,p,j,s]);if(!e)return null;const L=a?.systemStats,F=o&&!!a,M=C?`Updated ${new Date(C).toLocaleTimeString([],{hour:"2-digit",minute:"2-digit",second:"2-digit"})}`:"Waiting for first update",O=a?.taskStats,q=L?L.systemTotalMem-L.systemFreeMem:0,te=L?O$(q,L.systemTotalMem):"normal",Z=L?ul(te):"",K=L&&Number.isFinite(L.systemTotalMem)&&L.systemTotalMem>0?Math.max(0,Math.min(100,q/L.systemTotalMem*100)):0,A=L?`System memory used: ${K.toFixed(1)}% (${ui(q)} of ${ui(L.systemTotalMem)})`:"System memory usage unavailable",I=a?.vitestProcessCount,$=z$(L?.cpuPercent??null,L?.cpuCount??0),N=ul($),G=L?.cpuPercent??null,xe=G===null?0:Math.max(0,Math.min(100,G)),Se=G===null?"Sampling…":`${G.toFixed(1)}%`,je=G===null?"App CPU usage unavailable: waiting for another sample":`App CPU usage: ${G.toFixed(1)}%`,se=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":"",Ve=F$(a?.vitestLastAutoKillAt);return t.jsx("div",{className:"modal-overlay open",role:"dialog","aria-modal":"true","aria-labelledby":"system-stats-modal-title",onClick:ee=>{ee.target===ee.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(dr,{}),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:M})]}),t.jsx("button",{type:"button",className:"btn-icon",onClick:()=>void j(),title:"Refresh","aria-label":"Refresh system stats",children:t.jsx(os,{size:16,className:F?"system-stats-modal__refresh--spinning":void 0})}),t.jsx("button",{type:"button",className:"modal-close",onClick:n,"aria-label":"Close",children:t.jsx(nn,{})})]})]}),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:P.map(ee=>t.jsxs("div",{className:"system-stats-modal__row",children:[t.jsx("dt",{children:ee.label}),t.jsxs("dd",{children:[t.jsx("span",{className:`system-stats-modal__value ${ee.className}`.trim(),children:ee.value}),ee.detail?t.jsx("span",{className:"system-stats-modal__detail",children:ee.detail}):null]})]},ee.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:Se}),t.jsx("span",{className:"system-stats-modal__detail",children:G===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--${$}`,role:"progressbar","aria-valuenow":Math.round(xe),"aria-valuemin":0,"aria-valuemax":100,"aria-label":je,children:t.jsx("div",{className:`system-stats-modal__memory-progress-fill system-stats-modal__memory-progress-fill--${$}`,style:{width:`${xe}%`}})})})]}),t.jsxs("div",{className:"system-stats-modal__row",children:[t.jsx("dt",{children:"Load Avg"}),t.jsx("dd",{children:L?.loadAvg.map(ee=>ee.toFixed(2)).join(" ")??"—"})]}),t.jsxs("div",{className:"system-stats-modal__row",children:[t.jsx("dt",{children:"Cores"}),t.jsx("dd",{children:L?.cpuCount??"—"})]}),t.jsxs("div",{className:"system-stats-modal__row",children:[t.jsx("dt",{children:"Platform"}),t.jsx("dd",{children:L?.platform??"—"})]}),t.jsxs("div",{className:"system-stats-modal__row",children:[t.jsx("dt",{children:"Node"}),t.jsx("dd",{children:L?.nodeVersion??"—"})]}),t.jsxs("div",{className:"system-stats-modal__row",children:[t.jsx("dt",{children:"PID"}),t.jsx("dd",{children:L?.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 ${Z}`.trim(),children:L?ui(q):"—"}),t.jsx("span",{className:"system-stats-modal__detail",children:L?`${yf(q,L.systemTotalMem)} of ${ui(L.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--${te}`,role:"progressbar","aria-valuenow":Math.round(K),"aria-valuemin":0,"aria-valuemax":100,"aria-label":A,children:t.jsx("div",{className:`system-stats-modal__memory-progress-fill system-stats-modal__memory-progress-fill--${te}`,style:{width:`${K}%`}})})})]}),t.jsxs("div",{className:"system-stats-modal__row",children:[t.jsx("dt",{children:"Memory Free"}),t.jsx("dd",{children:L?ui(L.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:O?.total??0})]}),Object.entries(O?.byColumn??{}).map(([ee,ce])=>t.jsxs("div",{className:"system-stats-modal__row",children:[t.jsx("dt",{children:ee}),t.jsx("dd",{children:ce})]},ee))]})]}),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:O?.agents.idle??0})]}),t.jsxs("div",{className:"system-stats-modal__row",children:[t.jsx("dt",{children:"active"}),t.jsx("dd",{children:O?.agents.active??0})]}),t.jsxs("div",{className:"system-stats-modal__row",children:[t.jsx("dt",{children:"running"}),t.jsx("dd",{children:O?.agents.running??0})]}),t.jsxs("div",{className:"system-stats-modal__row",children:[t.jsx("dt",{children:"error"}),t.jsx("dd",{children:O?.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(Xw,{}),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:I??"—"})]})}),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 R(),disabled:p||I===0,children:[t.jsx(nk,{}),t.jsx("span",{children:x?"Confirm Kill?":"Kill Vitest Processes"})]})}),t.jsxs("label",{className:"system-stats-modal__toggle-row",children:[t.jsx("input",{type:"checkbox",checked:u,onChange:ee=>{U(ee.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:h,"aria-label":"Kill threshold slider (%)",onChange:ee=>{const ce=Number.parseInt(ee.target.value,10);E(Number.isNaN(ce)?90:ce)}}),t.jsx("input",{id:"vitest-threshold-number",type:"number",className:"input",min:50,max:99,value:h,"aria-label":"Kill threshold (%)",onChange:ee=>{const ce=Number.parseInt(ee.target.value,10);E(Number.isNaN(ce)?90:ce)},onBlur:()=>{E(h)}})]})]}),b&&t.jsxs("p",{className:se,children:["Killed ",b.killed," processes"]}),t.jsxs("p",{className:"system-stats-modal__last-kill",children:["Last auto-kill: ",Ve]}),S&&t.jsx("p",{className:"system-stats-modal__kill-result system-stats-modal__kill-result--error",children:S})]})]})]}),c&&a&&t.jsxs("div",{className:"system-stats-modal__footer-error",children:["Latest refresh failed: ",c]})]})})}const B$=5e3;function H$(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),[m,h]=i.useState(null),[f,p]=i.useState(!1),g=i.useRef(null),x=i.useRef(void 0),w=i.useCallback(async()=>{try{u(!0),h(null);let S;o?S=await Sm({limit:a,projectId:n,type:s}):S=(await xm({limit:a,type:s,projectId:n})).map(C=>({...C,projectId:n??"",projectName:""})),c(S),p(S.length===a),S.length>0&&(x.current=S[S.length-1].timestamp)}catch(S){h(S instanceof Error?S.message:"Failed to load activity log")}finally{u(!1)}},[a,n,s,o]),b=i.useCallback(async()=>{if(x.current)try{u(!0);let S;o?S=await Sm({limit:a,projectId:n,type:s,since:x.current}):S=(await xm({limit:a,type:s,since:x.current,projectId:n})).map(C=>({...C,projectId:n??"",projectName:""})),c(k=>[...k,...S]),p(S.length===a),S.length>0&&(x.current=S[S.length-1].timestamp)}catch(S){h(S instanceof Error?S.message:"Failed to load more entries")}finally{u(!1)}},[a,n,s,o]),y=i.useCallback(()=>{c([]),p(!1),x.current=void 0},[]);return i.useEffect(()=>{w()},[w]),i.useEffect(()=>{if(r)return g.current=setInterval(()=>{w()},B$),()=>{g.current&&(clearInterval(g.current),g.current=null)}},[r,w]),{entries:l,loading:d,error:m,refresh:w,clear:y,hasMore:f,loadMore:b}}const bd={"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"},q$={"task:created":t.jsx(gn,{size:14,className:"activity-icon created"}),"task:moved":t.jsx(yo,{size:14,className:"activity-icon moved"}),"task:updated":t.jsx(os,{size:14,className:"activity-icon updated"}),"task:deleted":t.jsx(nn,{size:14,className:"activity-icon deleted"}),"task:merged":t.jsx(Dn,{size:14,className:"activity-icon merged"}),"task:failed":t.jsx(wo,{size:14,className:"activity-icon failed"}),"settings:updated":t.jsx(to,{size:14,className:"activity-icon settings"})};function V$(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 W$({isOpen:e,onClose:n,tasks:s,onOpenTaskDetail:a,projectId:r,projects:o=[],onProjectFilterChange:l,currentProject:c}){const[d,u]=i.useState("all"),[m,h]=i.useState(r||"all"),[f,p]=i.useState(!1);i.useEffect(()=>{h(r||"all")},[r]);const g=d==="all"?void 0:d,x=m==="all"?void 0:m,w=!c&&o.length>0,{entries:b,loading:y,error:S,refresh:k,hasMore:C}=H$({projectId:x,type:g,limit:100,autoRefresh:e,useCentralFeed:w}),v=b.map(R=>({id:R.id,timestamp:R.timestamp,type:R.type,taskId:R.taskId,taskTitle:R.taskTitle,details:R.details,metadata:R.metadata,projectId:R.projectId,projectName:R.projectName})),j=async()=>{try{await WN(),k(),p(!1)}catch{p(!1)}},P=R=>{a&&a(R)},U=R=>{h(R),l?.(R==="all"?void 0:R)};i.useEffect(()=>{if(!e)return;const R=L=>{L.key==="Escape"&&(f?p(!1):n())};return document.addEventListener("keydown",R),()=>document.removeEventListener("keydown",R)},[e,n,f]);const E=d!=="all"||m!=="all";return e?t.jsx("div",{className:"modal-overlay open",onClick:R=>{R.target===R.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(lo,{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(bs,{size:14}),t.jsxs("select",{value:m,onChange:R=>U(R.target.value),className:"activity-log-filter-select","data-testid":"activity-project-filter",children:[t.jsx("option",{value:"all",children:"All Projects"}),o.map(R=>t.jsx("option",{value:R.id,children:R.name},R.id))]})]}),t.jsxs("div",{className:"activity-log-filter",children:[t.jsx(jl,{size:14}),t.jsxs("select",{value:d,onChange:R=>u(R.target.value),className:"activity-log-filter-select","data-testid":"activity-filter",children:[t.jsx("option",{value:"all",children:"All Events"}),Object.entries(bd).map(([R,L])=>t.jsx("option",{value:R,children:L},R))]})]}),t.jsx("button",{className:"activity-log-refresh",onClick:()=>k(),title:"Refresh","data-testid":"activity-refresh",children:y?t.jsx(bt,{size:14,className:"spin"}):t.jsx(os,{size:14})}),v.length>0&&t.jsx("button",{className:"activity-log-clear",onClick:()=>p(!0),title:"Clear Log","data-testid":"activity-clear",children:t.jsx(vn,{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:"}),m!=="all"&&t.jsxs("span",{className:"activity-log-filter-badge",children:["Project: ",o.find(R=>R.id===m)?.name||m]}),d!=="all"&&t.jsxs("span",{className:"activity-log-filter-badge",children:["Type: ",bd[d]]}),t.jsx("button",{className:"activity-log-clear-filters",onClick:()=>{u("all"),h("all"),l?.(void 0)},children:"Clear all"})]}),t.jsxs("div",{className:"activity-log-content","data-testid":"activity-log-content",children:[S&&t.jsxs("div",{className:"activity-log-error","data-testid":"activity-error",children:[t.jsx(Ps,{size:16}),t.jsx("span",{children:S})]}),v.length===0&&!y&&!S&&t.jsxs("div",{className:"activity-log-empty","data-testid":"activity-empty",children:[t.jsx(lo,{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"),h("all"),l?.(void 0)},children:"Clear Filters"})]}),t.jsx("div",{className:"activity-log-list",children:v.map(R=>t.jsxs("div",{className:"activity-log-entry","data-testid":"activity-entry",children:[t.jsx("div",{className:"activity-log-entry-icon",children:q$[R.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:bd[R.type]}),t.jsx("span",{className:"activity-log-entry-time",children:V$(R.timestamp)})]}),t.jsxs("div",{className:"activity-log-entry-details",children:[R.taskId&&t.jsx("button",{className:"activity-log-task-link",onClick:()=>P(R.taskId),"data-testid":"activity-task-link",children:R.taskId}),R.taskTitle&&t.jsx("span",{className:"activity-log-task-title",children:R.taskTitle}),t.jsx("span",{className:"activity-log-entry-text",children:R.details})]}),R.metadata&&Object.keys(R.metadata).length>0&&t.jsxs("div",{className:"activity-log-entry-metadata",children:[typeof R.metadata.from=="string"&&typeof R.metadata.to=="string"&&t.jsxs("span",{className:"activity-log-metadata-item",children:[R.metadata.from," → ",R.metadata.to]}),typeof R.metadata.merged=="boolean"&&t.jsx("span",{className:`activity-log-metadata-item ${R.metadata.merged?"success":"error"}`,children:R.metadata.merged?"Merged":"Not merged"})]})]})]},R.id))}),C&&!y&&t.jsx("button",{className:"activity-log-load-more",onClick:k,"data-testid":"activity-load-more",children:"Load More"}),y&&v.length>0&&t.jsx("div",{className:"activity-log-loading",children:t.jsx(bt,{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:j,children:"Clear Log"})]})]})})]})}):null}const Hr=[{id:"status",label:"Status",icon:Ng},{id:"changes",label:"Changes",icon:_d},{id:"commits",label:"Commits",icon:ko},{id:"branches",label:"Branches",icon:Us},{id:"worktrees",label:"Worktrees",icon:Gy},{id:"stashes",label:"Stashes",icon:xo},{id:"remotes",label:"Remotes",icon:wg}];function wf({status:e}){switch(e){case"added":case"untracked":return t.jsx(Ey,{size:14,className:"gm-file-icon gm-file-added"});case"modified":return t.jsx(vg,{size:14,className:"gm-file-icon gm-file-modified"});case"deleted":return t.jsx(Ny,{size:14,className:"gm-file-icon gm-file-deleted"});case"renamed":case"copied":return t.jsx(ia,{size:14,className:"gm-file-icon gm-file-renamed"});default:return t.jsx(My,{size:14,className:"gm-file-icon"})}}function kf({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 K$(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 br(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 G$({isOpen:e,onClose:n,tasks:s,addToast:a,projectId:r}){const o=ai(),l=Ys();vi(e);const{keyboardOverlap:c,viewportHeight:d,viewportOffsetTop:u,keyboardOpen:m}=Wi({enabled:l==="mobile"}),h=m?{"--keyboard-overlap":`${c}px`,"--vv-offset-top":`${u}px`,...d!==null?{"--vv-height":`${d}px`}:{}}:{},f=i.useCallback(()=>{if(l==="mobile"){const Te=document.activeElement;Te instanceof HTMLElement&&Te.blur(),window.scrollTo(0,0),requestAnimationFrame(()=>{window.scrollTo(0,0)})}n()},[n,l]),[p,g]=i.useState("status"),[x,w]=i.useState(!1),[b,y]=i.useState(null),S=i.useRef(null);Ai(S,e,"fusion:git-modal-size");const k=qi(f),C=K$(a),[v,j]=i.useState(null),[P,U]=i.useState([]),[E,R]=i.useState(new Set),[L,F]=i.useState(""),[M,O]=i.useState(!1),[q,te]=i.useState(null),[Z,K]=i.useState(!1),[A,I]=i.useState(null),[$,N]=i.useState(null),G=i.useRef(0),[xe,Se]=i.useState([]),[je,se]=i.useState(null),[Ve,ee]=i.useState(null),[ce,ne]=i.useState(!1),[re,J]=i.useState(20),[B,ye]=i.useState(""),[Ce,H]=i.useState([]),[ke,pe]=i.useState(""),[Ae,Oe]=i.useState(""),[He,dt]=i.useState(""),[Fe,fe]=i.useState(null),[$e,De]=i.useState([]),[ot,Be]=i.useState(!1),[we,Q]=i.useState(null),[_e,lt]=i.useState(null),[ht,mt]=i.useState(!1),[xt,Ie]=i.useState([]),[Ue,pt]=i.useState([]),[oe,le]=i.useState(""),[ge,Ne]=i.useState(null),[ue,qe]=i.useState(null),[me,tt]=i.useState(null),[Ct,wt]=i.useState(!1),[$t,Vt]=i.useState(null),Mt=i.useRef(0),[Dt,Qt]=i.useState(null),[Kt,Bt]=i.useState(null),on=i.useCallback(async()=>{if(e){w(!0),y(null);try{switch(p){case"status":{const Te=await di(r);j(Te);break}case"changes":{const[Te,Je]=await Promise.all([di(r),Ga(r)]);j(Te),U(Je),R(new Set),N(null),te(null),I(null);break}case"commits":{const Te=await Jj(re,r);Se(Te);break}case"branches":{const[Te,Je]=await Promise.all([Ar(r),di(r)]);H(Te),j(Je);break}case"worktrees":{const Te=await Zj(r);Ie(Te);break}case"stashes":{const Te=await Oo(r);pt(Te),qe(null),tt(null),Vt(null),Mt.current+=1;break}case"remotes":{const Te=await di(r);j(Te);break}}}catch(Te){y(Pe(Te)||"Failed to fetch git data"),a(Pe(Te)||"Failed to fetch git data","error")}finally{w(!1)}}},[p,e,re,a,r]);i.useEffect(()=>{e&&on()},[on,e]),i.useEffect(()=>{if(!e)return;const Te=Je=>{if(Je.key==="Escape"){f();return}if((Je.key==="ArrowUp"||Je.key==="ArrowDown")&&Je.altKey){Je.preventDefault();const Nt=Hr.findIndex(Ut=>Ut.id===p);Je.key==="ArrowUp"&&Nt>0?g(Hr[Nt-1].id):Je.key==="ArrowDown"&&Nt<Hr.length-1&&g(Hr[Nt+1].id)}};return document.addEventListener("keydown",Te),()=>document.removeEventListener("keydown",Te)},[e,f,p]);const fn=i.useCallback(async Te=>{try{await mm(Te,r),a(`Staged ${Te.length} file(s)`,"success");const Je=await Ga(r);U(Je),R(new Set),N(null),te(null),I(null)}catch(Je){a(Pe(Je)||"Failed to stage files","error")}},[a,r]),Jt=i.useCallback(async Te=>{try{await dN(Te,r),a(`Unstaged ${Te.length} file(s)`,"success");const Je=await Ga(r);U(Je),R(new Set),N(null),te(null),I(null)}catch(Je){a(Pe(Je)||"Failed to unstage files","error")}},[a,r]),an=i.useCallback(async Te=>{if(await o.confirm({title:"Discard Changes",message:`Discard changes to ${Te.length} file(s)? This cannot be undone.`,danger:!0}))try{await uN(Te,r),a(`Discarded changes to ${Te.length} file(s)`,"success");const[Nt,Ut]=await Promise.all([Ga(r),di(r)]);U(Nt),j(Ut),R(new Set),N(null),te(null),I(null)}catch(Nt){a(Pe(Nt)||"Failed to discard changes","error")}},[a,r,o]),zt=i.useCallback(async Te=>{if(Te.preventDefault(),!!L.trim()){O(!0);try{const Je=await hm(L.trim(),r);a(`Committed: ${Je.hash}`,"success"),F("");const[Nt,Ut]=await Promise.all([Ga(r),di(r)]);U(Nt),j(Ut),N(null),te(null),I(null)}catch(Je){a(Pe(Je)||"Failed to commit","error")}finally{O(!1)}}},[L,a,r]),en=i.useCallback(async()=>{if(L.trim()){O(!0);try{const Te=P.filter(tn=>!tn.staged).map(tn=>tn.file);Te.length>0&&await mm(Te,r);const Je=await hm(L.trim(),r);a(`Committed: ${Je.hash}`,"success"),F("");const[Nt,Ut]=await Promise.all([Ga(r),di(r)]);U(Nt),j(Ut),N(null),te(null),I(null)}catch(Te){a(Pe(Te)||"Failed to commit","error")}finally{O(!1)}}},[L,P,a,r]),Zt=i.useCallback(async(Te,Je)=>{N({file:Te,staged:Je}),K(!0),I(null);const Nt=G.current+1;G.current=Nt;try{const Ut=await cN(Te,Je,r);if(G.current!==Nt)return;te(Ut)}catch(Ut){if(G.current!==Nt)return;const tn=Pe(Ut)||"Failed to load file diff";te(null),I(tn),a(tn,"error")}finally{G.current===Nt&&K(!1)}},[a,r]),dn=i.useCallback(Te=>{R(Je=>{const Nt=new Set(Je);return Nt.has(Te)?Nt.delete(Te):Nt.add(Te),Nt})},[]),ve=i.useCallback(async Te=>{if(je===Te){se(null),ee(null);return}se(Te),ne(!0);try{const Je=await El(Te,r);ee(Je)}catch(Je){a(Pe(Je)||"Failed to load diff","error"),ee(null)}finally{ne(!1)}},[je,a,r]),ze=i.useCallback(()=>{J(Te=>Math.min(Te+20,100))},[]),We=i.useMemo(()=>{if(!B.trim())return xe;const Te=B.toLowerCase();return xe.filter(Je=>Je.message.toLowerCase().includes(Te)||Je.author.toLowerCase().includes(Te)||Je.shortHash.toLowerCase().includes(Te))},[xe,B]),Ze=i.useCallback(async Te=>{if(Te.preventDefault(),!!ke.trim()){w(!0);try{await eN(ke.trim(),Ae.trim()||void 0,r),a(`Created branch ${ke}`,"success"),pe(""),Oe("");const Je=await Ar(r);H(Je)}catch(Je){a(Pe(Je)||"Failed to create branch","error")}finally{w(!1)}}},[ke,Ae,a,r]),Ye=i.useCallback(async Te=>{w(!0);try{await tN(Te,r),a(`Switched to ${Te}`,"success");const[Je,Nt]=await Promise.all([di(r),Ar(r)]);j(Je),H(Nt)}catch(Je){a(Pe(Je)||"Failed to checkout branch","error")}finally{w(!1)}},[a,r]),It=i.useCallback(async Te=>{if(await o.confirm({title:"Delete Branch",message:`Delete branch "${Te}"?`,danger:!0})){w(!0);try{await um(Te,void 0,r),a(`Deleted branch ${Te}`,"success");const Nt=await Ar(r);H(Nt)}catch(Nt){if(Pe(Nt).includes("not fully merged")){if(await o.confirm({title:"Force Delete Branch",message:"Branch has unmerged commits. Force delete?",danger:!0}))try{await um(Te,!0,r),a(`Force deleted branch ${Te}`,"success");const tn=await Ar(r);H(tn)}catch(tn){a(Pe(tn)||"Failed to delete branch","error")}}else a(Pe(Nt)||"Failed to delete branch","error")}finally{w(!1)}}},[a,r,o]),St=i.useMemo(()=>{if(!He.trim())return Ce;const Te=He.toLowerCase();return Ce.filter(Je=>Je.name.toLowerCase().includes(Te))},[Ce,He]),Ht=i.useCallback(async Te=>{if(Fe===Te){fe(null),De([]),Q(null),lt(null);return}fe(Te),De([]),Q(null),lt(null),Be(!0);try{const Je=await Xj(Te,10,r);De(Je)}catch{De([])}finally{Be(!1)}},[Fe,r]),jt=i.useCallback(async Te=>{if(we===Te){Q(null),lt(null);return}Q(Te),lt(null),mt(!0);try{const Je=await El(Te,r);lt(Je)}catch{lt(null)}finally{mt(!1)}},[we,r]),ae=i.useCallback(()=>{fe(null),De([]),Q(null),lt(null)},[]),Le=i.useCallback(()=>{Mt.current+=1,qe(null),tt(null),Vt(null),wt(!1)},[]),At=i.useCallback(async Te=>{Te.preventDefault(),Ne("create"),Le();try{await aN(oe.trim()||void 0,r),a("Changes stashed","success"),le("");const Je=await Oo(r);pt(Je)}catch(Je){a(Pe(Je)||"Failed to stash changes","error")}finally{Ne(null)}},[oe,a,r,Le]),Lt=i.useCallback(async(Te,Je=!1)=>{Ne(`apply-${Te}`),Le();try{await rN(Te,Je,r),a(Je?"Stash popped":"Stash applied","success");const Nt=await Oo(r);pt(Nt)}catch(Nt){a(Pe(Nt)||"Failed to apply stash","error")}finally{Ne(null)}},[a,r,Le]),Ft=i.useCallback(async Te=>{if(await o.confirm({title:"Drop Stash",message:`Drop stash@{${Te}}? This cannot be undone.`,danger:!0})){Ne(`drop-${Te}`),Le();try{await oN(Te,r),a("Stash dropped","success");const Nt=await Oo(r);pt(Nt)}catch(Nt){a(Pe(Nt)||"Failed to drop stash","error")}finally{Ne(null)}}},[a,r,o,Le]),Me=i.useCallback(async Te=>{if(ue===Te){Le();return}const Je=Mt.current+1;Mt.current=Je,qe(Te),tt(null),Vt(null),wt(!0);try{const Nt=await lN(Te,r);if(Mt.current!==Je)return;tt(Nt)}catch(Nt){if(Mt.current!==Je)return;tt(null),Vt(Pe(Nt)||"Failed to load stash diff")}finally{Mt.current===Je&&wt(!1)}},[ue,r,Le]),ct=i.useCallback(async()=>{Qt("fetch");try{const Te=await nN(void 0,r);Bt(Te),a(Te.message||"Fetch completed",Te.fetched?"success":"info");const Je=await di(r);j(Je)}catch(Te){a(Pe(Te)||"Fetch failed","error")}finally{Qt(null)}},[a,r]),gt=i.useCallback(async Te=>{Qt("pull");try{const Je=await sN(Te,r);if(Bt(Je),Je.conflict)a("Merge conflict detected. Resolve manually.","error");else{const Ut=Te?.rebase?"Pull --rebase completed":"Pull completed";a(Je.message||Ut,"success")}const Nt=await di(r);j(Nt)}catch(Je){a(Pe(Je)||"Pull failed","error")}finally{Qt(null)}},[a,r]),_t=i.useCallback(async()=>{Qt("push");try{const Te=await iN(r);Bt(Te),a(Te.message||"Push completed","success");const Je=await di(r);j(Je)}catch(Te){a(Pe(Te)||"Push failed","error")}finally{Qt(null)}},[a,r]),Yt=i.useMemo(()=>P.filter(Te=>Te.staged),[P]),Xt=i.useMemo(()=>P.filter(Te=>!Te.staged),[P]);return e?t.jsx("div",{className:"modal-overlay open git-manager-modal-overlay",...k,role:"dialog","aria-modal":"true",children:t.jsxs("div",{className:"modal gm-modal",ref:S,style:h,children:[t.jsxs("div",{className:"modal-header",children:[t.jsxs("h3",{children:[t.jsx(Md,{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:on,disabled:x,title:"Refresh",children:t.jsx(os,{size:14,className:x?"spin":""})}),t.jsx("button",{className:"modal-close",onClick:f,"aria-label":"Close",children:t.jsx(nn,{size:18})})]})]}),t.jsxs("div",{className:"gm-layout",children:[t.jsx("nav",{className:"gm-sidebar",role:"tablist","aria-label":"Git Manager Sections",children:Hr.map(Te=>{const Je=Te.icon;return t.jsxs("button",{role:"tab","aria-selected":p===Te.id,className:`gm-nav-item${p===Te.id?" active":""}`,onClick:()=>g(Te.id),children:[t.jsx(Je,{size:16}),t.jsx("span",{className:"gm-nav-label",children:Te.label})]},Te.id)})}),t.jsxs("div",{className:"gm-content",role:"tabpanel",children:[x&&t.jsxs("div",{className:"gm-loading",children:[t.jsx(bt,{size:24,className:"spin"}),t.jsx("span",{children:"Loading..."})]}),b&&!x&&t.jsxs("div",{className:"gm-error",children:[t.jsx(Ps,{size:18}),t.jsx("span",{children:b}),t.jsx("button",{className:"btn btn-sm",onClick:on,children:"Retry"})]}),p==="status"&&!x&&v&&t.jsx(J$,{status:v,copyToClipboard:C}),p==="changes"&&!x&&t.jsx(Y$,{status:v,stagedFiles:Yt,unstagedFiles:Xt,selectedFiles:E,toggleFileSelection:dn,onStageFiles:fn,onUnstageFiles:Jt,onDiscardChanges:an,onSelectDiffFile:Zt,selectedDiffTarget:$,changeDiff:q,loadingChangeDiff:Z,changeDiffError:A,commitMessage:L,setCommitMessage:F,onCommit:zt,onStageAllAndCommit:en,committing:M}),p==="commits"&&!x&&t.jsx(Q$,{commits:We,commitSearch:B,setCommitSearch:ye,selectedCommit:je,commitDiff:Ve,loadingDiff:ce,onCommitClick:ve,onLoadMore:ze,canLoadMore:xe.length>=re&&re<100,copyToClipboard:C}),p==="branches"&&!x&&t.jsx(X$,{branches:St,branchSearch:He,setBranchSearch:dt,newBranchName:ke,setNewBranchName:pe,branchBase:Ae,setBranchBase:Oe,onCreateBranch:Ze,onCheckoutBranch:Ye,onDeleteBranch:It,loading:x,allBranches:Ce,selectedBranch:Fe,branchCommits:$e,loadingBranchCommits:ot,expandedBranchCommit:we,branchCommitDiff:_e,loadingBranchCommitDiff:ht,onSelectBranch:Ht,onBranchCommitClick:jt,onCloseBranchDetails:ae}),p==="worktrees"&&!x&&t.jsx(Z$,{worktrees:xt}),p==="stashes"&&!x&&t.jsx(eD,{stashes:Ue,stashMessage:oe,setStashMessage:le,onCreateStash:At,onApplyStash:Lt,onDropStash:Ft,onToggleStashDiff:Me,stashLoading:ge,expandedStashIndex:ue,stashDiff:me,loadingStashDiff:Ct,stashDiffError:$t}),p==="remotes"&&!x&&t.jsx(tD,{status:v,remoteLoading:Dt,lastRemoteResult:Kt,onFetch:ct,onPull:gt,onPush:_t,addToast:a,projectId:r,copyToClipboard:C})]})]})]})}):null}function J$({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(Us,{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(sa,{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(Ps,{size:12}),"Modified"]}):t.jsxs(t.Fragment,{children:[t.jsx(Dn,{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(ka,{size:12}),e.ahead]}),e.behind>0&&t.jsxs("span",{className:"gm-behind",title:`${e.behind} commit(s) behind`,children:[t.jsx(vo,{size:12}),e.behind]}),e.ahead===0&&e.behind===0&&t.jsxs("span",{className:"gm-in-sync",children:[t.jsx(Dn,{size:12}),"Up to date"]})]})]})]})]})}function Y$({status:e,stagedFiles:n,unstagedFiles:s,selectedFiles:a,toggleFileSelection:r,onStageFiles:o,onUnstageFiles:l,onDiscardChanges:c,onSelectDiffFile:d,selectedDiffTarget:u,changeDiff:m,loadingChangeDiff:h,changeDiffError:f,commitMessage:p,setCommitMessage:g,onCommit:x,onStageAllAndCommit:w,committing:b}){const y=s.filter(k=>a.has(`unstaged:${k.file}`)),S=n.filter(k=>a.has(`staged:${k.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(Us,{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(k=>k.file)),title:"Stage selected",children:[t.jsx(gn,{size:12})," Stage (",y.length,")"]}),t.jsx("button",{className:"btn btn-sm btn-danger",onClick:()=>c(y.map(k=>k.file)),title:"Discard selected",children:t.jsx(wo,{size:12})})]}),s.length>0&&t.jsx("button",{className:"btn btn-sm",onClick:()=>o(s.map(k=>k.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(k=>{const C=u?.file===k.file&&u.staged===!1;return t.jsxs("div",{className:`gm-file-item${C?" active":""}`,onClick:()=>d(k.file,!1),role:"button",tabIndex:0,onKeyDown:v=>{(v.key==="Enter"||v.key===" ")&&(v.preventDefault(),d(k.file,!1))},children:[t.jsx("label",{className:"gm-file-checkbox",onClick:v=>v.stopPropagation(),children:t.jsx("input",{type:"checkbox",checked:a.has(`unstaged:${k.file}`),onChange:()=>r(`unstaged:${k.file}`)})}),t.jsx(wf,{status:k.status}),t.jsx("span",{className:"gm-file-name",title:k.file,children:t.jsx("bdo",{dir:"ltr",children:k.file})}),t.jsx(kf,{status:k.status}),t.jsx("button",{className:"gm-icon-btn",onClick:v=>{v.stopPropagation(),o([k.file])},title:"Stage file",children:t.jsx(gn,{size:12})})]},`unstaged:${k.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:[S.length>0&&t.jsxs("button",{className:"btn btn-sm",onClick:()=>l(S.map(k=>k.file)),title:"Unstage selected",children:["Unstage (",S.length,")"]}),n.length>0&&t.jsx("button",{className:"btn btn-sm",onClick:()=>l(n.map(k=>k.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(k=>{const C=u?.file===k.file&&u.staged===!0;return t.jsxs("div",{className:`gm-file-item staged${C?" active":""}`,onClick:()=>d(k.file,!0),role:"button",tabIndex:0,onKeyDown:v=>{(v.key==="Enter"||v.key===" ")&&(v.preventDefault(),d(k.file,!0))},children:[t.jsx("label",{className:"gm-file-checkbox",onClick:v=>v.stopPropagation(),children:t.jsx("input",{type:"checkbox",checked:a.has(`staged:${k.file}`),onChange:()=>r(`staged:${k.file}`)})}),t.jsx(wf,{status:k.status}),t.jsx("span",{className:"gm-file-name",title:k.file,children:t.jsx("bdo",{dir:"ltr",children:k.file})}),t.jsx(kf,{status:k.status}),t.jsx("button",{className:"gm-icon-btn",onClick:v=>{v.stopPropagation(),l([k.file])},title:"Unstage file",children:t.jsx(nn,{size:12})})]},`staged:${k.file}`)})})]})]}),t.jsx("div",{className:"gm-changes-diff",children:u||h||m||f?t.jsxs("div",{className:"gm-diff-section",children:[u&&t.jsxs("div",{className:"gm-diff-target",children:[t.jsx(_d,{size:14}),t.jsxs("span",{children:[u.staged?"Staged":"Unstaged"," diff: "]}),t.jsx("code",{children:u.file})]}),h&&t.jsxs("div",{className:"gm-diff-loading",children:[t.jsx(bt,{size:16,className:"spin"}),"Loading diff..."]}),f&&!h&&t.jsx("div",{className:"gm-diff-error",children:f}),m&&!h&&t.jsxs("div",{className:"gm-diff-viewer",children:[m.stat&&t.jsx("pre",{className:"gm-diff-stat",children:m.stat}),t.jsx("pre",{className:"gm-diff-patch",children:m.patch})]})]}):t.jsxs("div",{className:"gm-diff-empty",children:[t.jsx(_d,{size:20}),t.jsx("span",{children:"Select a file to view its diff"})]})})]}),t.jsxs("form",{className:"gm-commit-form",onSubmit:x,children:[t.jsx("textarea",{className:"gm-commit-input",placeholder:"Commit message...",value:p,onChange:k=>g(k.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(bt,{size:14,className:"spin"}):t.jsx(wa,{size:14}),"Commit"]}),s.length>0&&t.jsx("button",{type:"button",className:"btn btn-sm",onClick:w,disabled:b||!p.trim(),title:"Stage all and commit",children:"Stage All & Commit"})]})]})]})}function Q$({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(Fi,{size:14}),t.jsx("input",{type:"text",placeholder:"Search commits...",value:n,onChange:m=>s(m.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((m,h)=>t.jsxs("div",{className:"gm-commit-item",children:[t.jsxs("div",{className:"gm-commit-graph",children:[t.jsx("div",{className:"gm-commit-dot"}),h<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(m.hash),children:[t.jsxs("div",{className:"gm-commit-top-row",children:[t.jsx("code",{className:"gm-hash",children:m.shortHash}),t.jsx("span",{className:"gm-commit-message",title:m.message,children:m.message})]}),t.jsxs("div",{className:"gm-commit-meta",children:[t.jsx("span",{children:m.author}),t.jsx("span",{children:"•"}),t.jsx("span",{children:br(m.date)}),m.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(m.hash,"commit hash"),title:"Copy full hash",children:t.jsx(sa,{size:12})})}),a===m.hash&&t.jsx("div",{className:"gm-commit-diff",children:o?t.jsxs("div",{className:"gm-diff-loading",children:[t.jsx(bt,{size:16,className:"spin"}),"Loading diff..."]}):r?t.jsxs(t.Fragment,{children:[m.body&&t.jsx("div",{className:"gm-commit-message-full",children:m.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"})})]})]},m.hash))}),d&&t.jsx("button",{className:"gm-load-more",onClick:c,children:"Load more commits"})]})}function X$({branches:e,branchSearch:n,setBranchSearch:s,newBranchName:a,setNewBranchName:r,branchBase:o,setBranchBase:l,onCreateBranch:c,onCheckoutBranch:d,onDeleteBranch:u,loading:m,allBranches:h,selectedBranch:f,branchCommits:p,loadingBranchCommits:g,expandedBranchCommit:x,branchCommitDiff:w,loadingBranchCommitDiff:b,onSelectBranch:y,onBranchCommitClick:S,onCloseBranchDetails:k}){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(Fi,{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:m}),t.jsxs("select",{value:o,onChange:C=>l(C.target.value),disabled:m,className:"gm-branch-select",children:[t.jsx("option",{value:"",children:"Base: HEAD"}),h.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:m||!a.trim(),children:[t.jsx(gn,{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(hs,{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:br(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:v=>{v.stopPropagation(),d(C.name)},disabled:m,title:"Checkout",children:t.jsx(Us,{size:14})}),t.jsx("button",{className:"btn btn-sm btn-danger",onClick:v=>{v.stopPropagation(),u(C.name)},disabled:m,title:"Delete",children:t.jsx(vn,{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(ko,{size:14}),"Commits on ",C.name]}),t.jsx("button",{className:"gm-icon-btn",onClick:k,title:"Close","data-testid":"close-branch-details",children:t.jsx(nn,{size:14})})]}),g?t.jsxs("div",{className:"gm-branch-details-loading",children:[t.jsx(bt,{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(v=>t.jsxs("div",{className:"gm-branch-commit",children:[t.jsxs("button",{className:"gm-branch-commit-row",onClick:()=>S(v.hash),"data-testid":`branch-commit-${v.shortHash}`,children:[t.jsx("span",{className:"gm-commit-hash",children:v.shortHash}),t.jsx("span",{className:"gm-commit-message",title:v.message,children:v.message}),t.jsxs("div",{className:"gm-commit-meta",children:[t.jsx("span",{children:v.author}),t.jsx("span",{children:"•"}),t.jsx("span",{children:br(v.date)}),v.parents.length>1&&t.jsx("span",{className:"gm-merge-badge",children:"merge"})]})]}),x===v.hash&&t.jsx("div",{className:"gm-commit-diff",children:b?t.jsxs("div",{className:"gm-diff-loading",children:[t.jsx(bt,{size:16,className:"spin"}),"Loading diff..."]}):w?t.jsxs(t.Fragment,{children:[(v.body||v.message)&&t.jsx("div",{className:"gm-commit-message-full",children:v.body||v.message}),w.stat&&t.jsx("pre",{className:"gm-diff-stat",children:w.stat}),t.jsx("pre",{className:"gm-diff-patch",children:w.patch})]}):t.jsx("div",{className:"gm-diff-error",children:"Failed to load diff"})})]},v.hash))})]})]},C.name))})]})}function Z$({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:wu(n.path)||n.path})]}),t.jsxs("div",{className:"gm-worktree-detail",children:[n.branch&&t.jsxs("span",{className:"gm-worktree-branch",children:[t.jsx(Us,{size:12}),n.branch]}),n.taskId&&t.jsx("span",{className:"gm-worktree-task",children:n.taskId})]})]})},n.path))})]})}function eD({stashes:e,stashMessage:n,setStashMessage:s,onCreateStash:a,onApplyStash:r,onDropStash:o,onToggleStashDiff:l,stashLoading:c,expandedStashIndex:d,stashDiff:u,loadingStashDiff:m,stashDiffError:h}){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(bt,{size:14,className:"spin"}):t.jsx(xo,{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(Us,{size:12}),f.branch]}),t.jsx("span",{children:br(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(bt,{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(bt,{size:14,className:"spin"}):t.jsx(vn,{size:14})})]})]}),d===f.index&&t.jsx("div",{className:"gm-stash-diff",children:m?t.jsxs("div",{className:"gm-diff-loading",children:[t.jsx(bt,{size:14,className:"spin"}),"Loading stash diff…"]}):h?t.jsx("div",{className:"gm-diff-error",children:h}):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 tD({status:e,remoteLoading:n,lastRemoteResult:s,onFetch:a,onPull:r,onPush:o,addToast:l,projectId:c,copyToClipboard:d}){const u=Q=>{try{return new URL(Q).hostname}catch{return Q.replace(/^git@/,"").split(":")[0]||Q}},[m,h]=i.useState([]),[f,p]=i.useState(!1),[g,x]=i.useState(null),[w,b]=i.useState(""),[y,S]=i.useState(""),[k,C]=i.useState(null),[v,j]=i.useState(""),[P,U]=i.useState(""),[E,R]=i.useState(!1),[L,F]=i.useState(!1),M=i.useRef(null),[O,q]=i.useState([]),[te,Z]=i.useState(!1),[K,A]=i.useState(null),[I,$]=i.useState([]),[N,G]=i.useState(!1),[xe,Se]=i.useState(null),je=i.useRef(0),se=m.find(Q=>Q.name===K);i.useEffect(()=>{(n!==null||f)&&F(!1)},[n,f]),i.useEffect(()=>{if(!L)return;const Q=lt=>{M.current?.contains(lt.target)||F(!1)},_e=lt=>{lt.key==="Escape"&&F(!1)};return document.addEventListener("mousedown",Q),document.addEventListener("keydown",_e),()=>{document.removeEventListener("mousedown",Q),document.removeEventListener("keydown",_e)}},[L]);const[Ve,ee]=i.useState(null),[ce,ne]=i.useState(null),[re,J]=i.useState(!1),[B,ye]=i.useState(null),[Ce,H]=i.useState(null),[ke,pe]=i.useState(!1);i.useEffect(()=>{Ae()},[]),i.useEffect(()=>{e&&e.ahead>0?Oe():e&&e.ahead===0&&q([])},[e?.ahead]),i.useEffect(()=>{m.length>0&&!K&&A(m[0].name)},[m]),i.useEffect(()=>{K?He(K):($([]),Se(null))},[K]),i.useEffect(()=>{!K||!s||He(K)},[K,s]),i.useEffect(()=>{K&&!m.find(Q=>Q.name===K)&&A(m.length>0?m[0].name:null)},[m,K]);const Ae=async()=>{p(!0);try{const Q=await Fj(c);h(Q)}catch(Q){l(Pe(Q)||"Failed to load remotes","error")}finally{p(!1)}},Oe=async()=>{Z(!0);try{const Q=await Yj(c);q(Q)}catch{q([])}finally{Z(!1)}},He=async Q=>{const _e=je.current+1;je.current=_e,G(!0),Se(null);try{const lt=await Qj(Q,void 0,10,c);if(je.current!==_e)return;$(lt)}catch(lt){if(je.current!==_e)return;Se(Pe(lt)||"Failed to load remote commits"),$([])}finally{je.current===_e&&G(!1)}},dt=ai(),Fe=async Q=>{if(Q.preventDefault(),!(!w.trim()||!y.trim())){x("add");try{await Uj(w.trim(),y.trim(),c),l(`Remote '${w}' added successfully`,"success"),b(""),S(""),R(!1),await Ae()}catch(_e){l(Pe(_e)||"Failed to add remote","error")}finally{x(null)}}},fe=async Q=>{if(await dt.confirm({title:"Remove Remote",message:`Are you sure you want to remove remote '${Q}'?`,danger:!0})){x(`remove-${Q}`);try{await Bj(Q,c),l(`Remote '${Q}' removed`,"success"),await Ae()}catch(lt){l(Pe(lt)||"Failed to remove remote","error")}finally{x(null)}}},$e=async Q=>{if(P.trim()){x(`rename-${Q}`);try{await Hj(Q,P.trim(),c),l(`Remote renamed to '${P.trim()}'`,"success"),C(null),U(""),await Ae()}catch(_e){l(Pe(_e)||"Failed to rename remote","error")}finally{x(null)}}},De=async Q=>{if(v.trim()){x(`url-${Q}`);try{await qj(Q,v.trim(),c),l("Remote URL updated","success"),C(null),j(""),await Ae()}catch(_e){l(Pe(_e)||"Failed to update remote URL","error")}finally{x(null)}}},ot=i.useCallback(async(Q,_e)=>{if(_e==="ahead"){if(Ve===Q){ee(null),ne(null);return}ee(Q),ne(null),J(!0);try{const lt=await El(Q);ne(lt)}catch{ne(null)}finally{J(!1)}}else{if(B===Q){ye(null),H(null);return}ye(Q),H(null),pe(!0);try{const lt=await El(Q);H(lt)}catch{H(null)}finally{pe(!1)}}},[Ve,B]),Be=Q=>{C(`url-${Q.name}`),j(Q.pushUrl||Q.fetchUrl)},we=Q=>{C(`name-${Q.name}`),U(Q.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:()=>R(!E),disabled:g!==null,title:E?"Cancel":"Add Remote",children:E?t.jsx(nn,{size:14}):t.jsx(gn,{size:14})})]}),E&&t.jsxs("form",{className:"gm-remote-form",onSubmit:Fe,children:[t.jsx("input",{type:"text",placeholder:"Remote name",value:w,onChange:Q=>b(Q.target.value),disabled:g==="add",className:"input gm-input"}),t.jsx("input",{type:"text",placeholder:"Repository URL",value:y,onChange:Q=>S(Q.target.value),disabled:g==="add",className:"input gm-input gm-input-url"}),t.jsxs("button",{type:"submit",className:"btn btn-sm btn-primary",disabled:!w.trim()||!y.trim()||g==="add",children:[g==="add"?t.jsx(bt,{size:12,className:"spin"}):t.jsx(gn,{size:12}),"Add"]})]}),f?t.jsxs("div",{className:"gm-loading",children:[t.jsx(bt,{size:16,className:"spin"}),"Loading..."]}):m.length===0?t.jsx("div",{className:"gm-empty",children:"No remotes"}):m.map(Q=>t.jsxs("div",{className:`gm-remote-selector-item${K===Q.name?" selected":""}`,onClick:()=>A(Q.name),role:"button",tabIndex:0,onKeyDown:_e=>{(_e.key==="Enter"||_e.key===" ")&&(_e.preventDefault(),A(Q.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:Q.name}),Q.name==="origin"&&t.jsx("span",{className:"gm-remote-default-badge",children:"default"})]}),t.jsx("span",{className:"gm-remote-selector-host",title:Q.fetchUrl,children:u(Q.fetchUrl)})]}),t.jsx("button",{className:"btn btn-icon btn-sm gm-remote-remove-btn",onClick:_e=>{_e.stopPropagation(),fe(Q.name)},disabled:g!==null,title:"Remove remote",children:t.jsx(vn,{size:14})})]},Q.name))]}),t.jsxs("div",{className:"gm-remote-detail","data-testid":"remote-detail-panel",children:[K&&se?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:K}),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(ka,{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(vo,{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(bt,{size:14,className:"spin"}):t.jsx(os,{size:14}),"Fetch"]}),t.jsxs("div",{className:"gm-pull-split",ref:M,children:[t.jsxs("button",{className:"btn btn-primary gm-pull-split-main",onClick:()=>{F(!1),r({rebase:!1})},disabled:n!==null||f,children:[n==="pull"?t.jsx(bt,{size:14,className:"spin"}):t.jsx(Ws,{size:14}),"Pull"]}),t.jsx("button",{className:"btn btn-primary btn-icon gm-pull-split-toggle",onClick:()=>F(Q=>!Q),disabled:n!==null||f,"aria-label":"Pull options","aria-haspopup":"menu","aria-expanded":L,children:t.jsx(rn,{size:14})}),L?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:()=>{F(!1),r({rebase:!1})},children:"Pull"}),t.jsx("button",{className:"gm-pull-menu-item",role:"menuitem",onClick:()=>{F(!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(bt,{size:14,className:"spin"}):t.jsx(ka,{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:"}),k===`url-${K}`?t.jsxs("div",{className:"gm-remote-edit",children:[t.jsx("input",{type:"text",value:v,onChange:Q=>j(Q.target.value),className:"input gm-input",autoFocus:!0}),t.jsx("button",{className:"btn btn-sm btn-primary",onClick:()=>De(K),disabled:g===`url-${K}`,children:g===`url-${K}`?t.jsx(bt,{size:12,className:"spin"}):t.jsx(hs,{size:12})}),t.jsx("button",{className:"btn btn-sm",onClick:()=>{C(null),j("")},title:"Cancel",children:t.jsx(nn,{size:12})})]}):t.jsxs(t.Fragment,{children:[t.jsx("span",{className:"gm-url-value",title:se.fetchUrl,children:t.jsx("bdo",{dir:"ltr",children:se.fetchUrl})}),t.jsxs("div",{className:"gm-remote-inline-actions",children:[t.jsx("button",{className:"btn btn-icon btn-sm",onClick:()=>d(se.fetchUrl,"fetch URL"),title:"Copy fetch URL",children:t.jsx(sa,{size:14})}),t.jsx("button",{className:"btn btn-icon btn-sm",onClick:()=>Be(se),disabled:g!==null,title:"Edit remote URL",children:t.jsx(Ds,{size:14})})]})]})]}),se.pushUrl&&se.pushUrl!==se.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:se.pushUrl,children:t.jsx("bdo",{dir:"ltr",children:se.pushUrl})}),t.jsx("div",{className:"gm-remote-inline-actions",children:t.jsx("button",{className:"btn btn-icon btn-sm",onClick:()=>d(se.pushUrl,"push URL"),title:"Copy push URL",children:t.jsx(sa,{size:14})})})]})]}),t.jsx("div",{className:"gm-remote-detail-name-row",children:k===`name-${K}`?t.jsxs("div",{className:"gm-remote-edit",children:[t.jsx("input",{type:"text",value:P,onChange:Q=>U(Q.target.value),className:"input gm-input",autoFocus:!0}),t.jsx("button",{className:"btn btn-sm btn-primary",onClick:()=>$e(K),disabled:g===`rename-${K}`,children:g===`rename-${K}`?t.jsx(bt,{size:12,className:"spin"}):t.jsx(hs,{size:12})}),t.jsx("button",{className:"btn btn-sm",onClick:()=>{C(null),U("")},title:"Cancel",children:t.jsx(nn,{size:12})})]}):t.jsx("button",{className:"btn btn-icon btn-sm",onClick:()=>we(se),disabled:g!==null,title:"Edit remote name",children:t.jsx(Ds,{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(ka,{size:14}),"Commits to Push (",e.ahead,")"]})}),te?t.jsxs("div",{className:"gm-loading",children:[t.jsx(bt,{size:14,className:"spin"}),"Loading..."]}):O.length>0?t.jsx("div",{className:"gm-ahead-commits-list","data-testid":"ahead-commits-list",children:O.map(Q=>t.jsxs("div",{className:"gm-commit-item-compact-wrapper",children:[t.jsxs("div",{className:"gm-commit-item-compact gm-commit-clickable",onClick:()=>ot(Q.hash,"ahead"),role:"button",tabIndex:0,onKeyDown:_e=>{(_e.key==="Enter"||_e.key===" ")&&(_e.preventDefault(),ot(Q.hash,"ahead"))},title:"Click to view diff",children:[t.jsx("div",{className:"gm-commit-compact-hash",children:t.jsx("code",{className:"gm-hash",children:Q.shortHash})}),t.jsxs("div",{className:"gm-commit-compact-info",children:[t.jsx("span",{className:"gm-commit-message",title:Q.message,children:Q.message}),t.jsxs("span",{className:"gm-commit-meta",children:[t.jsx("span",{children:Q.author}),t.jsx("span",{children:"•"}),t.jsx("span",{children:br(Q.date)})]})]}),t.jsx("span",{className:"gm-commit-expand-icon",children:Ve===Q.hash?t.jsx(rn,{size:14}):t.jsx(Mn,{size:14})})]}),Ve===Q.hash&&t.jsx("div",{className:"gm-commit-diff gm-commit-diff-compact",children:re?t.jsxs("div",{className:"gm-diff-loading",children:[t.jsx(bt,{size:16,className:"spin"}),"Loading diff..."]}):ce?t.jsxs(t.Fragment,{children:[(Q.body||Q.message)&&t.jsx("div",{className:"gm-commit-message-full",children:Q.body||Q.message}),ce.stat&&t.jsx("pre",{className:"gm-diff-stat",children:ce.stat}),t.jsx("pre",{className:"gm-diff-patch",children:ce.patch})]}):t.jsx("div",{className:"gm-diff-error",children:"Failed to load diff"})})]},Q.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(Ng,{size:14}),"Recent commits on ",K]})}),N?t.jsxs("div",{className:"gm-loading",children:[t.jsx(bt,{size:14,className:"spin"}),"Loading commits..."]}):xe?t.jsxs("div",{className:"gm-error",children:[t.jsx(Ps,{size:14}),xe]}):I.length===0?t.jsxs("div",{className:"gm-empty",children:["No commits found on ",K,". Try fetching first."]}):t.jsx("div",{className:"gm-remote-commits-list","data-testid":"remote-commits-list",children:I.map(Q=>t.jsxs("div",{className:"gm-commit-item-compact-wrapper",children:[t.jsxs("div",{className:"gm-commit-item-compact gm-commit-clickable",onClick:()=>ot(Q.hash,"remote"),role:"button",tabIndex:0,onKeyDown:_e=>{(_e.key==="Enter"||_e.key===" ")&&(_e.preventDefault(),ot(Q.hash,"remote"))},title:"Click to view diff",children:[t.jsx("div",{className:"gm-commit-compact-hash",children:t.jsx("code",{className:"gm-hash",children:Q.shortHash})}),t.jsxs("div",{className:"gm-commit-compact-info",children:[t.jsx("span",{className:"gm-commit-message",title:Q.message,children:Q.message}),t.jsxs("span",{className:"gm-commit-meta",children:[t.jsx("span",{children:Q.author}),t.jsx("span",{children:"•"}),t.jsx("span",{children:br(Q.date)})]})]}),t.jsx("span",{className:"gm-commit-expand-icon",children:B===Q.hash?t.jsx(rn,{size:14}):t.jsx(Mn,{size:14})})]}),B===Q.hash&&t.jsx("div",{className:"gm-commit-diff gm-commit-diff-compact",children:ke?t.jsxs("div",{className:"gm-diff-loading",children:[t.jsx(bt,{size:16,className:"spin"}),"Loading diff..."]}):Ce?t.jsxs(t.Fragment,{children:[(Q.body||Q.message)&&t.jsx("div",{className:"gm-commit-message-full",children:Q.body||Q.message}),Ce.stat&&t.jsx("pre",{className:"gm-diff-stat",children:Ce.stat}),t.jsx("pre",{className:"gm-diff-patch",children:Ce.patch})]}):t.jsx("div",{className:"gm-diff-error",children:"Failed to load diff"})})]},Q.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 Za={name:"",description:"",mode:"prompt",phase:"pre-merge",prompt:"",scriptName:"",enabled:!0,defaultOn:!1,modelProvider:"",modelId:""};function nD(e,n){return e&&n?`${e}/${n}`:""}function sD(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 jf(e){switch(e){case"file-text":return ia;case"check-circle":return Dn;case"shield":return ek;case"zap":return Qn;case"eye":return kr;case"globe":return Kl;case"layout-grid":return aa;case"puzzle":return Ow;default:return Dn}}function Nf(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 iD({isOpen:e,onClose:n,addToast:s,projectId:a}){const[r,o]=i.useState([]),[l,c]=i.useState([]),[d,u]=i.useState({}),[m,h]=i.useState(!0),[f,p]=i.useState(!0),[g,x]=i.useState("my-steps"),[w,b]=i.useState(null),[y,S]=i.useState(!1),[k,C]=i.useState(!1),[v,j]=i.useState(Za),[P,U]=i.useState(!1),[E,R]=i.useState(!1),[L,F]=i.useState(null),[M,O]=i.useState(null),[q,te]=i.useState({}),[Z,K]=i.useState([]),A=i.useRef(null);Ai(A,e,"fusion:workflow-steps-modal-size");const I=i.useCallback(async()=>{try{h(!0);const B=await _o(a);o(B)}catch(B){s(Pe(B)||"Failed to load workflow steps","error")}finally{h(!1)}},[s,a]),$=i.useCallback(async()=>{try{const B=await mo(a);te(B||{})}catch{}},[a]),N=i.useCallback(async()=>{try{const B=await Os();K(B.models||[])}catch{}},[]),G=i.useCallback(async()=>{try{p(!0);const[B,ye]=await Promise.all([YN(),QN()]);c(B.templates);const Ce=Object.fromEntries(ye.templates.map(({pluginId:H,template:ke})=>[ke.id,H]));u(Ce)}catch(B){s(Pe(B)||"Failed to load templates","error")}finally{p(!1)}},[s]);i.useEffect(()=>{e&&(I(),G(),$(),N())},[e,I,G,$,N]);const xe=i.useCallback(()=>{C(!0),S(!1),b(null),j(Za)},[]),Se=i.useCallback(()=>{C(!1),S(!0),b(null),j(Za)},[]),je=i.useCallback(B=>{b(B.id),S(!1),j({name:B.name,description:B.description,mode:B.mode||"prompt",phase:B.phase||"pre-merge",prompt:B.prompt,scriptName:B.scriptName||"",enabled:B.enabled,defaultOn:B.defaultOn||!1,modelProvider:B.modelProvider||"",modelId:B.modelId||""})},[]),se=i.useCallback(()=>{b(null),S(!1),C(!1),j(Za)},[]),Ve=i.useCallback(async()=>{if(!v.name.trim()||!v.description.trim()){s("Name and description are required","error");return}U(!0);try{const B=v.mode==="prompt"&&v.modelProvider&&v.modelId?{modelProvider:v.modelProvider,modelId:v.modelId}:v.mode==="prompt"?{modelProvider:void 0,modelId:void 0}:{};if(y){const ye={name:v.name.trim(),description:v.description.trim(),mode:v.mode,phase:v.phase,prompt:v.mode==="prompt"&&v.prompt.trim()||void 0,scriptName:v.mode==="script"?v.scriptName.trim():void 0,enabled:v.enabled,defaultOn:v.defaultOn||void 0,...B};await vm(ye,a),s("Workflow step created","success")}else w&&(await KN(w,{name:v.name.trim(),description:v.description.trim(),mode:v.mode,phase:v.phase,prompt:v.mode==="prompt"?v.prompt:"",scriptName:v.mode==="script"?v.scriptName.trim():void 0,enabled:v.enabled,defaultOn:v.defaultOn,...B},a),s("Workflow step updated","success"));S(!1),b(null),j(Za),await I()}catch(B){s(Pe(B)||"Failed to save workflow step","error")}finally{U(!1)}},[v,y,w,s,I]),ee=i.useCallback(async B=>{try{await GN(B,a),s("Workflow step deleted","success"),F(null),w===B&&(b(null),j(Za)),await I()}catch(ye){s(Pe(ye)||"Failed to delete workflow step","error")}},[w,s,I]),ce=i.useCallback(async()=>{if(!(!w&&!y)&&v.mode==="prompt"){if(y){if(!v.name.trim()||!v.description.trim()){s("Name and description are required before refining","error");return}U(!0);try{const B=v.modelProvider&&v.modelId?{modelProvider:v.modelProvider,modelId:v.modelId}:{},ye={name:v.name.trim(),description:v.description.trim(),mode:"prompt",prompt:v.prompt.trim()||void 0,enabled:v.enabled,defaultOn:v.defaultOn||void 0,...B},Ce=await vm(ye,a);S(!1),b(Ce.id),R(!0);const H=await ym(Ce.id,a);j(ke=>({...ke,prompt:H.prompt})),s("Prompt refined with AI","success"),await I()}catch(B){s(Pe(B)||"Failed to refine prompt","error")}finally{U(!1),R(!1)}return}if(w){R(!0);try{const B=await ym(w,a);j(ye=>({...ye,prompt:B.prompt})),s("Prompt refined with AI","success"),await I()}catch(B){s(Pe(B)||"Failed to refine prompt","error")}finally{R(!1)}}}},[w,y,v,s,I]),ne=i.useCallback(async B=>{O(B.id);try{await XN(B.id,a),s(`Added ${B.name} workflow step`,"success"),await I(),x("my-steps"),C(!1)}catch(ye){const Ce=Pe(ye);Ce?.includes("already exists")?s(`A workflow step named '${B.name}' already exists`,"error"):s(Ce||"Failed to add workflow step from template","error")}finally{O(null)}},[s,I]),re=qi(n);if(!e)return null;const J=y||w!==null;return t.jsx("div",{className:"modal-overlay open",...re,"data-testid":"workflow-step-manager",children:t.jsxs("div",{ref:A,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:m?t.jsx("div",{className:"wfm-loading",children:"Loading..."}):t.jsxs(t.Fragment,{children:[!J&&t.jsxs("div",{className:"wfm-tab-row",children:[t.jsxs("button",{className:`btn ${g==="my-steps"?"btn-primary":"btn-secondary"} wfm-tab-btn`,onClick:()=>x("my-steps"),"data-testid":"tab-my-steps",children:[t.jsx(Bv,{size:14}),"My Workflow Steps (",r.length,")"]}),t.jsxs("button",{className:`btn ${g==="templates"?"btn-primary":"btn-secondary"} wfm-tab-btn`,onClick:()=>x("templates"),"data-testid":"tab-templates",children:[t.jsx(aa,{size:14}),"Templates (",l.length,")"]})]}),g==="my-steps"&&!J&&!k&&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(B=>t.jsx("div",{className:"wfm-step-card","data-testid":`workflow-step-${B.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:B.name}),t.jsx("span",{className:`wfm-badge ${B.enabled?"wfm-badge-enabled":"wfm-badge-disabled"}`,children:B.enabled?"Enabled":"Disabled"}),t.jsx("span",{className:`wfm-badge ${(B.mode||"prompt")==="script"?"wfm-badge-script":"wfm-badge-prompt"}`,children:(B.mode||"prompt")==="script"?"Script":"AI Prompt"}),t.jsx("span",{className:`wfm-badge ${(B.phase||"pre-merge")==="post-merge"?"wfm-badge-post-merge":"wfm-badge-pre-merge"}`,children:(B.phase||"pre-merge")==="post-merge"?"Post-merge":"Pre-merge"}),B.defaultOn&&t.jsx("span",{className:"wfm-badge wfm-badge-default-on",children:"Default on"})]}),t.jsx("div",{className:"wfm-step-card-desc",children:B.description})]}),t.jsxs("div",{className:"wfm-step-card-actions",children:[t.jsx("button",{className:"btn-icon",onClick:()=>je(B),title:"Edit","aria-label":`Edit ${B.name}`,children:t.jsx(Ds,{size:14})}),L===B.id?t.jsxs("div",{className:"wfm-delete-confirm",children:[t.jsx("button",{className:"btn-icon wfm-delete-confirm-btn",onClick:()=>ee(B.id),title:"Confirm delete","aria-label":`Confirm delete ${B.name}`,children:t.jsx(hs,{size:14})}),t.jsx("button",{className:"btn-icon",onClick:()=>F(null),title:"Cancel delete","aria-label":"Cancel delete",children:t.jsx(nn,{size:14})})]}):t.jsx("button",{className:"btn-icon",onClick:()=>F(B.id),title:"Delete","aria-label":`Delete ${B.name}`,children:t.jsx(vn,{size:14})})]})]})},B.id))})]}),g==="templates"&&!J&&!k&&t.jsx(t.Fragment,{children:f?t.jsxs("div",{className:"wfm-loading",children:[t.jsx(bt,{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(B=>{const ye=jf(B.icon),Ce=Nf(B.category),H=M===B.id;return t.jsx("div",{className:"wfm-template-card","data-testid":`template-${B.id}`,children:t.jsxs("div",{className:"wfm-template-inner",children:[t.jsx("div",{className:"wfm-template-icon",children:t.jsx(ye,{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:B.name}),t.jsx("span",{className:Ce,children:B.category}),d[B.id]&&t.jsx("span",{className:"wfm-badge-category wfm-badge-category-plugin",children:d[B.id]})]}),t.jsx("div",{className:"wfm-template-desc",children:B.description}),t.jsx("button",{className:"btn btn-primary wfm-template-add-btn",onClick:()=>ne(B),disabled:H,"data-testid":`add-template-${B.id}`,children:H?t.jsxs(t.Fragment,{children:[t.jsx(bt,{size:12,className:"spin"}),"Adding..."]}):t.jsxs(t.Fragment,{children:[t.jsx(gn,{size:12}),"Add"]})})]})]})},B.id)})})}),k&&!J&&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:Se,"data-testid":"create-custom-step",children:[t.jsx(gn,{size:14}),"Custom workflow step"]}),f?t.jsxs("div",{className:"wfm-loading","data-testid":"create-chooser-template-loading",children:[t.jsx(bt,{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(B=>{const ye=jf(B.icon),Ce=Nf(B.category),H=M===B.id;return t.jsx("div",{className:"wfm-template-card","data-testid":`chooser-template-${B.id}`,children:t.jsxs("div",{className:"wfm-template-inner",children:[t.jsx("div",{className:"wfm-template-icon",children:t.jsx(ye,{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:B.name}),t.jsx("span",{className:Ce,children:B.category}),d[B.id]&&t.jsx("span",{className:"wfm-badge-category wfm-badge-category-plugin",children:d[B.id]})]}),t.jsx("div",{className:"wfm-template-desc",children:B.description}),t.jsx("button",{className:"btn btn-primary wfm-template-add-btn",onClick:()=>ne(B),disabled:H,"data-testid":`chooser-add-template-${B.id}`,children:H?t.jsxs(t.Fragment,{children:[t.jsx(bt,{size:12,className:"spin"}),"Adding..."]}):t.jsxs(t.Fragment,{children:[t.jsx(gn,{size:12}),"Add template"]})})]})]})},B.id)})})]}),J&&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:v.name,onChange:B=>j(ye=>({...ye,name:B.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:v.description,onChange:B=>j(ye=>({...ye,description:B.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 ${v.mode==="prompt"?"btn-primary":"btn-secondary"} wfm-mode-btn`,onClick:()=>j(B=>({...B,mode:"prompt",scriptName:""})),"data-testid":"mode-prompt",children:[t.jsx(Ui,{size:14}),"AI Prompt"]}),t.jsxs("button",{className:`btn ${v.mode==="script"?"btn-primary":"btn-secondary"} wfm-mode-btn`,onClick:()=>j(B=>({...B,mode:"script",prompt:"",modelProvider:"",modelId:""})),"data-testid":"mode-script",children:[t.jsx(Bi,{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 ${v.phase==="pre-merge"?"btn-primary":"btn-secondary"} wfm-mode-btn`,onClick:()=>j(B=>({...B,phase:"pre-merge"})),"data-testid":"phase-pre-merge",children:"Pre-merge"}),t.jsx("button",{className:`btn ${v.phase==="post-merge"?"btn-primary":"btn-secondary"} wfm-mode-btn`,onClick:()=>j(B=>({...B,phase:"post-merge"})),"data-testid":"phase-post-merge",children:"Post-merge"})]}),t.jsx("div",{className:"wfm-field-hint",children:v.phase==="pre-merge"?"Runs before merge — can block merge on failure":"Runs after merge success — failures are logged but do not block"})]}),v.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:ce,disabled:!v.description.trim()||E,title:"Refine with AI","aria-label":"Refine prompt with AI","data-testid":"refine-btn",children:[E?t.jsx(bt,{size:12,className:"spin"}):t.jsx(ps,{size:12}),t.jsx("span",{children:"Refine with AI"})]})]}),t.jsx("textarea",{value:v.prompt,onChange:B=>j(ye=>({...ye,prompt:B.target.value})),placeholder:"Leave empty to use AI refinement",rows:6,className:"wfm-prompt-textarea","data-testid":"workflow-step-prompt"})]}),v.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"}),v.modelProvider&&v.modelId&&t.jsxs("button",{type:"button",className:"btn-icon wfm-model-clear-btn",onClick:()=>j(B=>({...B,modelProvider:"",modelId:""})),title:"Clear model override (use global default)","data-testid":"clear-model-override",children:[t.jsx(nn,{size:12}),t.jsx("span",{children:"Use default"})]})]}),t.jsx("span",{className:"wfm-model-hint",children:v.modelProvider&&v.modelId?`Using ${v.modelProvider}/${v.modelId}`:"Using global default model"}),t.jsx("div",{"data-testid":"workflow-step-model-select",children:t.jsx(ys,{models:Z,value:nD(v.modelProvider,v.modelId),onChange:B=>{const ye=sD(B);j(Ce=>({...Ce,modelProvider:ye.provider,modelId:ye.modelId}))},placeholder:"Select a model override…",label:"Model override for this workflow step"})})]}),v.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:v.scriptName,onChange:B=>j(ye=>({...ye,scriptName:B.target.value})),"data-testid":"workflow-step-script-select",children:[t.jsx("option",{value:"",children:"Select a script…"}),Object.entries(q).map(([B,ye])=>t.jsxs("option",{value:B,children:[B," (",ye,")"]},B))]})]}),t.jsxs("label",{className:"wfm-checkbox-label",children:[t.jsx("input",{type:"checkbox",checked:v.enabled,onChange:B=>j(ye=>({...ye,enabled:B.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:v.defaultOn,onChange:B=>j(ye=>({...ye,defaultOn:B.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:se,disabled:P,children:"Cancel"}),t.jsx("button",{className:"btn btn-primary",onClick:Ve,disabled:P||!v.name.trim()||!v.description.trim()||v.mode==="script"&&!v.scriptName.trim(),"data-testid":"save-workflow-step",children:P?"Saving...":y?"Create":"Save"})]})]})]})]})}),!J&&!k&&t.jsx("div",{className:"wfm-footer",children:t.jsxs("button",{className:"btn btn-primary wfm-footer-add-btn",onClick:xe,"data-testid":"add-workflow-step",children:[t.jsx(gn,{size:14}),"Add Workflow Step"]})})]})})}const aD=36e5,rD=3e5,xd=[{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 oD(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 lD(e){return typeof e!="number"||!Number.isFinite(e)?aD:Math.max(rD,Math.round(e))}function s5(e){if(xd.some(s=>s.value===e))return[...xd];const n={value:e,label:`${oD(e)} (custom)`};return[...xd,n].sort((s,a)=>s.value-a.value)}const cD=4,dD=5*6e4;function uD(e){const n=lD(e?.heartbeatIntervalMs);return Math.max(n*cD,dD)}function Sf(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 mD(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 hD(e){const{state:n,lastHeartbeatAt:s,lastError:a,pauseReason:r,runtimeConfig:o}=e,l=mD(e),c=l||o?.enabled!==!1;if(n==="error")return{label:a??"Error",icon:t.jsx(Ks,{size:14}),color:"var(--state-error-text)",stateDerived:!a};if(n==="paused")return{label:r?`Paused: ${r}`:"Paused",icon:t.jsx(pi,{size:14}),color:"var(--state-paused-text)",stateDerived:!r};if(n==="running"||l&&n==="active")return{label:"Running",icon:t.jsx(Ks,{size:14}),color:"var(--state-active-text)",stateDerived:!0};if(!c)return{label:"Heartbeat Disabled",icon:t.jsx(pi,{size:14}),color:"var(--state-paused-text)",stateDerived:!1};if(!s)return{label:n==="active"?"Starting...":"Idle",icon:t.jsx($n,{size:14}),color:"var(--text-secondary)",stateDerived:!1};const d=new Date(s).getTime(),u=Date.now()-d,m=uD(o);if(u>m){const h=`No heartbeat for ${Sf(u)} (threshold: ${Sf(m)})`;return{label:"Unresponsive",icon:t.jsx(Ks,{size:14}),color:"var(--state-error-text)",stateDerived:!1,reason:h}}return{label:"Healthy",icon:t.jsx(Yy,{size:14}),color:"var(--state-active-text)",stateDerived:!1}}function iu({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($n,{size:Math.max(14,Math.round(n*.55)),"aria-hidden":"true"})})}const pD="https://github.com/Runfusion/Fusion/issues/new";function fD(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(`
691
- `)});return`${pD}?${r.toString()}`}function gD({open:e,onClose:n,errorText:s,issueContext:a}){const[r,o]=i.useState(!1),l=i.useMemo(()=>fD(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(Ps,{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(hs,{size:14}):t.jsx(sa,{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(xg,{size:14}),"Report on GitHub"]})]})]})}):null}function bD({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(Ps,{size:14}),t.jsx("span",{className:"agent-error-indicator__label",children:s})]}),t.jsx(gD,{open:a,onClose:()=>r(!1),errorText:e,issueContext:n})]})}const ml=[{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 xD({isOpen:e,onClose:n,addToast:s,projectId:a}){const[r,o]=i.useState([]),[l,c]=i.useState(!1),[d,u]=i.useState(!1),[m,h]=i.useState(""),[f,p]=i.useState("custom"),[g,x]=i.useState("all"),[w,b]=i.useState(()=>{if(typeof window>"u")return"list";const $=An("fn-agent-view",a);return $==="board"||$==="list"?$:"list"});i.useEffect(()=>{const $=An("fn-agent-view",a);if($==="board"||$==="list"){b($);return}b("list")},[a]),i.useEffect(()=>{ss("fn-agent-view",w,a)},[a,w]);const[y,S]=i.useState(null),k=i.useRef(null),[C,v]=i.useState(new Set),[j,P]=i.useState(new Map),{confirm:U}=ai(),E=i.useMemo(()=>j.size===0?r:r.map($=>{const N=j.get($.id);return N?{...$,state:N}:$}),[r,j]),R=i.useMemo(()=>g!=="all"?E:[...E].sort(($,N)=>{const G=$.state==="paused"?1:0,xe=N.state==="paused"?1:0;return G!==xe?G-xe:(N.updatedAt??"").localeCompare($.updatedAt??"")}),[E,g]),L=i.useCallback(async()=>{c(!0);try{const N=await Nr(g!=="all"?{state:g}:void 0,a);o(N)}catch($){s(`Failed to load agents: ${Pe($)}`,"error")}finally{c(!1)}},[g,s,a]);i.useEffect(()=>{e&&L()},[e,L]),i.useEffect(()=>{if(!e)return;const $=setInterval(()=>{L()},3e4);return()=>{clearInterval($)}},[e,L]);const F=async()=>{if(m.trim())try{await oS({name:m.trim(),role:f},a),s(`Agent "${m}" created`,"success"),h(""),u(!1),L()}catch($){s(`Failed to create agent: ${Pe($)}`,"error")}},M=async($,N)=>{if(!C.has($)){v(G=>new Set(G).add($)),P(G=>{const xe=new Map(G);return xe.set($,N),xe});try{await cS($,N,a),s(`Agent state updated to ${N}`,"success"),await L(),P(G=>{const xe=new Map(G);return xe.delete($),xe})}catch(G){P(xe=>{const Se=new Map(xe);return Se.delete($),Se}),s(`Failed to update state: ${Pe(G)}`,"error")}finally{v(G=>{const xe=new Set(G);return xe.delete($),xe})}}},O=async($,N)=>{if(await U({title:"Delete Agent",message:`Delete agent "${N}"? This cannot be undone.`,danger:!0}))try{await dS($,a),s(`Agent "${N}" deleted`,"success"),L()}catch(xe){s(`Failed to delete agent: ${Pe(xe)}`,"error")}},q=async($,N)=>{const G=r.find(xe=>xe.id===$);if(G){if(G.role===N){S(null);return}try{await lS($,{role:N},a),s(`Agent role updated to ${ml.find(xe=>xe.value===N)?.label??N}`,"success"),S(null),L()}catch(xe){s(`Failed to update role: ${Pe(xe)}`,"error")}}},te=($,N)=>{$.key==="Escape"&&S(null)},Z=$=>ml.find(N=>N.value===$)?.label??$,K=$=>hD($),A=$=>$.color==="var(--state-active-text)"?"active":$.color==="var(--state-paused-text)"?"paused":$.color==="var(--state-error-text)"?"error":"muted",I=($,N)=>$.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:$=>$.target===$.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($n,{size:20}),"Agents"]}),t.jsxs("div",{className:"modal-actions",children:[t.jsxs("div",{className:"view-toggle",children:[t.jsx("button",{className:`view-toggle-btn${w==="board"?" active":""}`,onClick:()=>b("board"),title:"Board view","aria-label":"Board view","aria-pressed":w==="board",children:t.jsx(aa,{size:16})}),t.jsx("button",{className:`view-toggle-btn${w==="list"?" active":""}`,onClick:()=>b("list"),title:"List view","aria-label":"List view","aria-pressed":w==="list",children:t.jsx(Ad,{size:16})})]}),t.jsx("button",{className:"btn-icon",onClick:()=>void L(),title:"Refresh",disabled:l,children:t.jsx(os,{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(jl,{size:14}),t.jsxs("select",{className:"agent-state-filter-select",value:g,onChange:$=>x($.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(gn,{size:16}),d?"Cancel":"New Agent"]})]}),d&&t.jsxs("div",{className:"agent-create-form",children:[t.jsx("input",{type:"text",placeholder:"Agent name...",value:m,onChange:$=>h($.target.value),onKeyDown:$=>$.key==="Enter"&&F(),className:"input",autoFocus:!0}),t.jsx("select",{className:"select",value:f,onChange:$=>p($.target.value),children:ml.map($=>t.jsxs("option",{value:$.value,children:[$.icon," ",$.label]},$.value))}),t.jsx("button",{className:"btn btn-task-create btn-sm",onClick:()=>void F(),children:"Create"})]}),t.jsx("div",{className:w==="board"?"agent-board":"agent-list",children:R.length===0?t.jsxs("div",{className:"agent-empty",children:[t.jsx($n,{size:48,opacity:.3}),t.jsx("p",{children:"No agents found"}),t.jsx("p",{className:"text-secondary",children:"Create an agent to get started"})]}):w==="board"?R.map($=>{const N=K($),G=I($,N),xe=A(N);return t.jsxs("div",{className:"agent-board-card","data-state":$.state,children:[t.jsxs("div",{className:"agent-board-header",children:[t.jsx("span",{className:"agent-board-icon",children:t.jsx(iu,{agent:$,size:20})}),t.jsx("span",{className:"agent-board-badge","data-state":$.state,children:$.state}),t.jsx("span",{className:"agent-board-health","data-health":xe,title:G.title,children:N.icon})]}),t.jsx("div",{className:"agent-board-name",title:$.name,children:$.name}),t.jsx("div",{className:"agent-board-id",children:$.id}),t.jsxs("div",{className:"agent-board-actions",children:[$.state==="idle"&&t.jsxs(t.Fragment,{children:[t.jsx("button",{className:"btn btn--sm",onClick:()=>void M($.id,"active"),disabled:C.has($.id),title:"Activate",children:t.jsx(Yn,{size:14})}),t.jsx("button",{className:"btn btn--sm btn--danger",onClick:()=>void O($.id,$.name),title:"Delete",children:t.jsx(vn,{size:14})})]}),$.state==="active"&&t.jsxs(t.Fragment,{children:[t.jsx("button",{className:"btn btn--sm",onClick:()=>void M($.id,"paused"),disabled:C.has($.id),title:"Pause",children:t.jsx(pi,{size:14})}),t.jsx("button",{className:"btn btn--sm btn--danger",onClick:()=>void M($.id,"paused"),disabled:C.has($.id),title:"Stop",children:t.jsx(Si,{size:14})})]}),$.state==="paused"&&t.jsxs(t.Fragment,{children:[t.jsx("button",{className:"btn btn--sm",onClick:()=>void M($.id,"active"),disabled:C.has($.id),title:"Resume",children:t.jsx(Yn,{size:14})}),t.jsx("button",{className:"btn btn--sm btn--danger",onClick:()=>void O($.id,$.name),title:"Delete",children:t.jsx(vn,{size:14})})]}),$.state==="running"&&t.jsxs(t.Fragment,{children:[t.jsx("button",{className:"btn btn--sm",onClick:()=>void M($.id,"paused"),disabled:C.has($.id),title:"Pause",children:t.jsx(pi,{size:14})}),t.jsx("button",{className:"btn btn--sm btn--danger",onClick:()=>void M($.id,"paused"),disabled:C.has($.id),title:"Stop",children:t.jsx(Si,{size:14})})]}),$.state==="error"&&t.jsxs(t.Fragment,{children:[t.jsx("button",{className:"btn btn--sm",onClick:()=>void M($.id,"active"),disabled:C.has($.id),title:"Retry",children:t.jsx(Yn,{size:14})}),t.jsx("button",{className:"btn btn--sm btn--danger",onClick:()=>void M($.id,"paused"),disabled:C.has($.id),title:"Stop",children:t.jsx(Si,{size:14})})]})]})]},$.id)}):R.map($=>{const N=K($),G=I($,N),xe=A(N);return t.jsxs("div",{className:"agent-card","data-state":$.state,children:[t.jsxs("div",{className:"agent-card-header",children:[t.jsxs("div",{className:"agent-info",children:[y===$.id?t.jsx("select",{ref:k,className:"select agent-role-select",value:$.role,onChange:Se=>void q($.id,Se.target.value),onKeyDown:Se=>te(Se,$.id),onBlur:()=>S(null),autoFocus:!0,children:ml.map(Se=>t.jsxs("option",{value:Se.value,children:[Se.icon," ",Se.label]},Se.value))}):t.jsx("span",{className:"agent-icon agent-icon--clickable",onClick:()=>S($.id),title:"Click to change role",role:"button",tabIndex:0,onKeyDown:Se=>{(Se.key==="Enter"||Se.key===" ")&&S($.id)},children:t.jsx(iu,{agent:$,size:20})}),t.jsxs("div",{className:"agent-meta",children:[t.jsx("span",{className:"agent-name",children:$.name}),t.jsx("span",{className:"agent-id text-secondary",children:$.id})]})]}),t.jsxs("div",{className:"agent-badges",children:[t.jsx("span",{className:"badge agent-list-state-badge","data-state":$.state,children:$.state}),t.jsxs("span",{className:"badge agent-list-health-badge","data-health":xe,title:G.title,children:[N.icon,G.label?` ${G.label}`:""]}),t.jsx("span",{className:"badge text-secondary",children:Z($.role)})]})]}),t.jsxs("div",{className:"agent-card-body",children:[$.state==="error"&&$.lastError?t.jsx(bD,{errorText:$.lastError,issueContext:{surface:"AgentListModal list",agentId:$.id,agentName:$.name,agentState:$.state,taskId:$.taskId}}):null,$.taskId&&t.jsxs("div",{className:"agent-task",children:[t.jsx("span",{className:"text-secondary",children:"Working on:"}),t.jsx("span",{className:"badge",children:$.taskId})]}),$.lastHeartbeatAt&&t.jsxs("div",{className:"agent-heartbeat",children:[t.jsx("span",{className:"text-secondary",children:"Last heartbeat:"}),t.jsx("span",{children:new Date($.lastHeartbeatAt).toLocaleString()})]})]}),t.jsxs("div",{className:"agent-card-actions",children:[$.state==="idle"&&t.jsxs(t.Fragment,{children:[t.jsxs("button",{className:"btn btn--sm",onClick:()=>void M($.id,"active"),disabled:C.has($.id),title:"Activate",children:[t.jsx(Yn,{size:14})," Start"]}),t.jsxs("button",{className:"btn btn--sm btn--danger",onClick:()=>void O($.id,$.name),title:"Delete",children:[t.jsx(vn,{size:14})," Delete"]})]}),$.state==="active"&&t.jsxs(t.Fragment,{children:[t.jsxs("button",{className:"btn btn--sm",onClick:()=>void M($.id,"paused"),disabled:C.has($.id),title:"Pause",children:[t.jsx(pi,{size:14})," Pause"]}),t.jsxs("button",{className:"btn btn--sm btn--danger",onClick:()=>void M($.id,"paused"),disabled:C.has($.id),title:"Stop",children:[t.jsx(Si,{size:14})," Stop"]})]}),$.state==="paused"&&t.jsxs(t.Fragment,{children:[t.jsxs("button",{className:"btn btn--sm",onClick:()=>void M($.id,"active"),disabled:C.has($.id),title:"Resume",children:[t.jsx(Yn,{size:14})," Resume"]}),t.jsxs("button",{className:"btn btn--sm btn--danger",onClick:()=>void O($.id,$.name),title:"Delete",children:[t.jsx(vn,{size:14})," Delete"]})]}),$.state==="running"&&t.jsxs(t.Fragment,{children:[t.jsxs("button",{className:"btn btn--sm",onClick:()=>void M($.id,"paused"),disabled:C.has($.id),title:"Pause",children:[t.jsx(pi,{size:14})," Pause"]}),t.jsxs("button",{className:"btn btn--sm btn--danger",onClick:()=>void M($.id,"paused"),disabled:C.has($.id),title:"Stop",children:[t.jsx(Si,{size:14})," Stop"]})]}),$.state==="error"&&t.jsxs(t.Fragment,{children:[t.jsxs("button",{className:"btn btn--sm",onClick:()=>void M($.id,"active"),disabled:C.has($.id),title:"Retry",children:[t.jsx(Yn,{size:14})," Retry"]}),t.jsxs("button",{className:"btn btn--sm btn--danger",onClick:()=>void M($.id,"paused"),disabled:C.has($.id),title:"Stop",children:[t.jsx(Si,{size:14})," Stop"]})]})]})]},$.id)})})]})]})}):null}function vD({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 m=i.useCallback(async()=>{try{const b=await gj();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(()=>{m()},[m]);const h=i.useCallback(async()=>{l("testing"),d(null),await m(),u.current&&l(null)},[m]),f=i.useCallback(async b=>{l(b?"enabling":"disabling"),d(null);try{const y=await kj(b);u.current&&d({kind:y.enabled?"enabled":"disabled",restartRequired:y.restartRequired}),n?.(y.enabled),await m()}catch(y){u.current&&d({kind:"error",message:y instanceof Error?y.message:String(y)})}finally{u.current&&l(null)}},[n,m]),p=a?.binary.available??!1,g=a?.enabled??e,x=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."]}),w=t.jsxs(t.Fragment,{children:[t.jsx("button",{type:"button",className:"btn btn-sm",onClick:h,disabled:o!==null,children:o==="testing"?t.jsxs(t.Fragment,{children:[t.jsx(bt,{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(Sn,{provider:"claude-cli",size:"sm"}),t.jsx("strong",{children:"Anthropic — via Claude CLI"}),t.jsx(yD,{status:a,authenticated:e})]}),t.jsx("div",{className:"auth-provider-cli-actions",children:w})]}),t.jsxs("details",{className:"auth-provider-cli-details",children:[t.jsx("summary",{children:"Details"}),t.jsxs("div",{className:"auth-provider-cli-details-body",children:[x,t.jsx(Cf,{status:a,authenticated:e}),c&&t.jsx(Ef,{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(Sn,{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"}),x,t.jsx(Cf,{status:a,authenticated:e})]}),t.jsx("div",{className:"onboarding-provider-card__actions",children:w}),c&&t.jsx(Ef,{action:c})]})}function yD({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 Cf({status:e,authenticated:n}){if(!e)return t.jsxs("small",{className:"settings-muted",children:[t.jsx(bt,{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 Ef({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 wD({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 yj();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 x=await Nj(g);s?.(x.enabled),await d()}finally{c.current&&l(null)}},[s,d]),m=a?.enabled??e,h=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(bt,{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||!h,children:o==="enabling"?"Enabling…":"Enable"})]}),p=a?a.binary.available?m?`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(Sn,{provider:"cursor-cli",size:"sm"}),t.jsx("strong",{children:"Cursor — via Cursor CLI"}),t.jsx("span",{className:`auth-status-badge ${m?"authenticated":"not-authenticated"}`,children:m?"✓ 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(Sn,{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 kD({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 x=await wj();return c.current&&r(x),x},[]);i.useEffect(()=>{d()},[d]);const u=i.useCallback(async x=>{l(x?"enabling":"disabling");try{const w=await Sj(x);n?.(w.enabled),await d()}finally{c.current&&l(null)}},[n,d]),m=i.useCallback(async()=>{l("testing");try{await d()}finally{c.current&&l(null)}},[d]),h=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 m(),disabled:o!==null,children:o==="testing"?t.jsxs(t.Fragment,{children:[t.jsx(bt,{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||!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${h?" 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(Sn,{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(Sn,{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 jD(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 vd({instructions:e,"data-testid":n}){const[s,a]=i.useState(!1),r=jD(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,m)=>t.jsxs("span",{children:[d,u<m.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(hs,{size:12}):t.jsx(sa,{size:12})})]})]},u))}):e})}function ND({value:e,onChange:n,onSubmit:s,prompt:a,placeholder:r,helpText:o,disabled:l=!1,submitLabel:c="Submit code","data-testid":d}){return t.jsxs("div",{className:"oauth-manual-code","data-testid":d,children:[t.jsx("p",{className:"oauth-manual-code__prompt",children:a}),t.jsx("textarea",{className:"form-input oauth-manual-code__input",value:e,onChange:u=>n(u.target.value),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 SD=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"]),CD=/^[a-z][a-z0-9-]*$/,_f=["openai-completions","openai-responses","anthropic-messages","google-generative-ai"];function Mf(){return{id:"",name:"",reasoning:!1}}function ED({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??""),[m,h]=i.useState(e?.baseUrl??""),[f,p]=i.useState(e?.api??"openai-completions"),[g,x]=i.useState(e?.apiKey??""),[w,b]=i.useState(e?.models?.length?e.models:[Mf()]),[y,S]=i.useState(null),k=w.length>1,C=i.useMemo(()=>y??r??null,[y,r]);function v(E,R){b(L=>L.map((F,M)=>M===E?{...F,...R}:F))}function j(E){b(R=>R.length<=1?R:R.filter((L,F)=>F!==E))}function P(){if(!l.trim())return"Provider ID is required.";if(!CD.test(l.trim()))return"Provider ID must be kebab-case.";if(!o&&SD.has(l.trim()))return"Provider ID conflicts with a built-in provider.";if(!m.trim())return"Base URL is required.";try{const E=new URL(m.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 _f.includes(f)?w.length===0?"At least one model is required.":w.some(E=>!E.id?.trim())?"Each model must have a model ID.":null:"API type is required."}async function U(E){E.preventDefault();const R=P();S(R),!R&&await n({id:l.trim(),name:d.trim()||void 0,baseUrl:m.trim(),api:f,apiKey:g.trim()||void 0,models:w.map(L=>({id:L.id.trim(),name:L.name?.trim()||void 0,reasoning:!!L.reasoning,contextWindow:L.contextWindow,maxTokens:L.maxTokens}))})}return t.jsxs("form",{onSubmit:U,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:m,onChange:E=>h(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:_f.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=>x(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:w.map((E,R)=>t.jsxs("div",{className:"custom-provider-form__model-row",children:[t.jsx("input",{className:"input","aria-label":`Model ID ${R+1}`,placeholder:"Model ID",value:E.id,onChange:L=>v(R,{id:L.target.value}),disabled:a}),t.jsx("input",{className:"input","aria-label":`Model name ${R+1}`,placeholder:"Display name",value:E.name??"",onChange:L=>v(R,{name:L.target.value}),disabled:a}),t.jsxs("label",{className:"checkbox-label custom-provider-form__toggle",children:[t.jsx("input",{type:"checkbox",checked:!!E.reasoning,onChange:L=>v(R,{reasoning:L.target.checked}),disabled:a}),"Reasoning"]}),t.jsx("input",{className:"input","aria-label":`Context window ${R+1}`,placeholder:"Context window",type:"number",value:E.contextWindow??"",onChange:L=>v(R,{contextWindow:L.target.value?Number(L.target.value):void 0}),disabled:a}),t.jsx("input",{className:"input","aria-label":`Max tokens ${R+1}`,placeholder:"Max tokens",type:"number",value:E.maxTokens??"",onChange:L=>v(R,{maxTokens:L.target.value?Number(L.target.value):void 0}),disabled:a}),t.jsx("button",{type:"button",className:"btn btn-icon btn-sm",onClick:()=>j(R),disabled:a||!k,"aria-label":`Remove model ${R+1}`,children:"×"})]},`${R}-model`))}),t.jsx("button",{type:"button",className:"btn btn-sm",onClick:()=>b(E=>[...E,Mf()]),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 _D=new Set(["google-antigravity","antigravity","google-gemini-cli"]);function MD(e){return!_D.has(e)}function Af(e){return e.filter(n=>MD(n.id))}const Yx={host:"web",activeProfileId:null,profiles:[]},Qx=i.createContext({shellApi:null,state:Yx,ready:!0,openConnectionManagerSignal:0});function AD({children:e}){const n=i.useMemo(()=>typeof window<"u"?window.fusionShell??null:null,[]),[s,a]=i.useState(Yx),[r,o]=i.useState(!n),[l,c]=i.useState(0);return i.useEffect(()=>{if(!n)return;let d=!1;n.getState().then(h=>{d||(a(h),o(!0))});const u=n.subscribe(h=>{a(h)}),m=()=>{c(h=>h+1)};return window.addEventListener("shell:open-connection-manager",m),()=>{d=!0,u(),window.removeEventListener("shell:open-connection-manager",m)}},[n]),t.jsx(Qx.Provider,{value:{shellApi:n,state:s,ready:r,openConnectionManagerSignal:l},children:e})}function PD(){return i.useContext(Qx)}const RD={host:"web",activeProfileId:null,profiles:[]};function ID(e){if(!e)return RD;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 Ju(e){return new Error(`${e} is only available in native shell mode`)}async function TD(e,n){if(!e)throw Ju("Saving connection profiles");return e.saveProfile(n)}async function $D(e,n){if(!e)throw Ju("Deleting connection profiles");await e.deleteProfile(n)}async function DD(e,n){if(!e)throw Ju("Switching connection profiles");return e.setActiveProfile(n)}function Xx(){const e=PD(),n=i.useMemo(()=>ID(e.state),[e.state]),s=i.useCallback(o=>TD(e.shellApi,o),[e.shellApi]),a=i.useCallback(o=>$D(e.shellApi,o),[e.shellApi]),r=i.useCallback(o=>DD(e.shellApi,o),[e.shellApi]);return{...e,state:n,saveProfile:s,removeProfile:a,setActiveProfile:r}}const Ma="fusion_model_onboarding_state",xr=[],vr=[],Ul=!1,Bl=!1,yr={},LD=void 0,Zi=["ai-setup","github","project-setup","first-task"],OD={"ai-setup":"AI Setup",github:"GitHub","project-setup":"Project","first-task":"First Task",complete:"Complete"};function Js(){if(typeof window>"u")return null;try{const e=localStorage.getItem(Ma);if(!e)return null;const n=JSON.parse(e);return n&&typeof n=="object"&&"currentStep"in n&&typeof n.currentStep=="string"?zD(n):null}catch{return null}}function zD(e){const n=e.postOnboardingDismissedAt??LD;return{...e,completedSteps:e.completedSteps??xr,skippedSteps:e.skippedSteps??vr,dismissed:e.dismissed??Ul,completed:e.completed??Bl,stepData:e.stepData??yr,...n?{postOnboardingDismissedAt:n}:{}}}function hl(e,n){if(!(typeof window>"u")){if(!n){const s={currentStep:e,updatedAt:new Date().toISOString(),completedSteps:xr,skippedSteps:vr,dismissed:Ul,completed:Bl,stepData:yr};try{localStorage.setItem(Ma,JSON.stringify(s))}catch{}return}try{const s=Js(),a=new Date().toISOString(),r=n.completed??Bl;let o=n.dismissed??Ul;r&&(o=!1);const l=n.completedSteps??s?.completedSteps??xr,c=n.skippedSteps??s?.skippedSteps??vr,d={...s?.stepData??yr};if(n.stepData)for(const[m,h]of Object.entries(n.stepData))h!==void 0&&(d[m]={...d[m]??{},...h});const u={currentStep:e,updatedAt:a,completedSteps:l,skippedSteps:c,dismissed:o,completed:r,stepData:d};localStorage.setItem(Ma,JSON.stringify(u))}catch{}}}function FD(e){if(!(typeof window>"u"))try{const n=Js(),s=new Date().toISOString();if(!n){const o={currentStep:e,updatedAt:s,completedSteps:xr,skippedSteps:[e],dismissed:Ul,completed:Bl,stepData:yr};localStorage.setItem(Ma,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(Ma,JSON.stringify(r))}catch{}}function Pf(){if(!(typeof window>"u"))try{const e=Js(),n=new Date().toISOString(),s=e?{...e,completedAt:n,completed:!0,dismissed:!1,updatedAt:n}:{currentStep:"complete",updatedAt:n,completedAt:n,completedSteps:xr,skippedSteps:vr,dismissed:!1,completed:!0,stepData:yr};localStorage.setItem(Ma,JSON.stringify(s))}catch{}}function wr(){const e=Js();return e?e.completed===!0?!0:typeof e.completedAt=="string"&&e.completedAt.length>0:!1}function UD(){if(!(typeof window>"u"))try{const e=Js(),n=new Date().toISOString(),s=e?{...e,updatedAt:n,postOnboardingDismissedAt:n}:{currentStep:"complete",updatedAt:n,completedSteps:xr,skippedSteps:vr,dismissed:!1,completed:!1,stepData:yr,postOnboardingDismissedAt:n};localStorage.setItem(Ma,JSON.stringify(s))}catch{}}function Zx(){const e=Js();return e?typeof e.postOnboardingDismissedAt=="string"&&e.postOnboardingDismissedAt.length>0:!1}function BD(){const e=Js();return!e||wr()?!1:e.currentStep!=="complete"}function HD(){const e=Js();if(!e||wr()||e.currentStep==="complete")return null;const n=e.currentStep,s=OD[n]??WD(e.currentStep);return{currentStep:e.currentStep,label:s,completedSteps:e.completedSteps}}function qD(){const e=Js();return e?e.skippedSteps:vr}function VD(e){const n=Js();return!n||!n.stepData?null:n.stepData[e]??null}function WD(e){return e.replace(/[-_]/g," ").replace(/\b\w/g,n=>n.toUpperCase())}const ev="fusion_onboarding_events",Rf="fusion_onboarding_session_id",KD=200,GD=50;function ei(e,n={}){if(!(typeof window>"u"))try{const s=YD(),a=ZD(n.step),r={type:e,timestamp:new Date().toISOString(),...a?{step:a}:{},metadata:n,sessionId:JD()},o=XD([...s,r]);QD(o)}catch{}}function JD(){if(typeof window>"u")return"server-session";try{const e=sessionStorage.getItem(Rf);if(e)return e;const n=If();return sessionStorage.setItem(Rf,n),n}catch{return If()}}function If(){return typeof crypto<"u"&&typeof crypto.randomUUID=="function"?crypto.randomUUID():`onboarding-${Date.now().toString(36)}-${Math.random().toString(36).slice(2,12)}`}function YD(){try{const e=localStorage.getItem(ev);if(!e)return[];const n=JSON.parse(e);return Array.isArray(n)?n.filter(eL):[]}catch{return[]}}function QD(e){try{localStorage.setItem(ev,JSON.stringify(e))}catch{}}function XD(e){const n=[...e];for(;n.length>KD;)n.splice(0,GD);return n}function ZD(e){if(e==="ai-setup"||e==="github"||e==="first-task"||e==="complete")return e}function eL(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 tL=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}))??[]}),nL={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"}}},tv={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:"..."}},sL={pattern:/^.{8,}$/,hint:"At least 8 characters",example:"..."},Tf={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"};function au(e){if(Tf[e])return Tf[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 yd=["anthropic","openai","google","gemini","ollama"],iL=["anthropic","claude-cli","droid-cli","cursor-cli","llama-cpp","openai-codex","gemini","minimax","kimi","zai"],aL={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"},rL={gemini:["google","gemini"],kimi:["kimi","moonshot","kimi-coding"]};function ru(e){return aL[e]??e}function $f(e){const n=ru(e),s=iL.indexOf(n);return s===-1?Number.POSITIVE_INFINITY:s}function Df(e,n){if(e.authenticated!==n.authenticated)return e.authenticated?-1:1;const s=$f(e.id),a=$f(n.id);if(s!==a)return s-a;const r=ru(e.id),o=ru(n.id);if(r!==o)return r.localeCompare(o);const l=rL[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 oL(e,n){const s=n.trim();if(!s)return"API key is required";const a=tv[e]??sL;return a.pattern.test(s)?null:`${au(e)} keys should follow this format: ${a.hint} (e.g. ${a.example})`}const nv={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"},lL={description:"AI provider — connect to start using AI models",apiKeyInfo:nv};function ou(e){return nL[e]??lL}function cL(e){return ou(e.id).apiKeyInfo??nv}function dL({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 uL({provider:e,apiKeyInfo:n,inputValue:s,isSaving:a,error:r,success:o,isConnected:l,onInputChange:c,onSave:d,onClear:u}){const m=`onboarding-apikey-input-${e.id}`,h=a||!s.trim(),f=tv[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(ti,{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:m,className:"onboarding-apikey-field-label",children:n.fieldLabel}),t.jsxs("div",{className:"onboarding-apikey-input-row",children:[t.jsx("input",{id:m,type:"password",className:p,placeholder:n.inputPlaceholder??"Enter API key",value:s,onChange:x=>c(e.id,x.target.value),onKeyDown:x=>{x.key==="Enter"&&d(e.id,s)},"data-testid":m}),t.jsx("button",{className:"btn btn-primary btn-sm",onClick:()=>d(e.id,s),disabled:h,"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(ti,{summary:"Advanced setup details",children:g})]})}const mL=150;function hL({onComplete:e,addToast:n,projectId:s,onOpenSetupWizard:a,onOpenNewTask:r,onOpenGitHubImport:o,firstCreatedTask:l,onViewTask:c}){const d=Js(),u=d?.currentStep,m=u==="complete"?"ai-setup":Zi.includes(u)?u:"ai-setup",h=d?.completedSteps??[],f=d?.skippedSteps??qD(),[p,g]=i.useState(!0),[x,w]=i.useState(m),[b,y]=i.useState(h),[S,k]=i.useState(f),[C,v]=i.useState(!1),[j,P]=i.useState(""),[U,E]=i.useState(!1),[R,L]=i.useState(null),[F,M]=i.useState(null),[O,q]=i.useState([]),[te,Z]=i.useState(void 0),[K,A]=i.useState(!0),[I,$]=i.useState(null),[N,G]=i.useState({}),[xe,Se]=i.useState({}),[je,se]=i.useState({}),[Ve,ee]=i.useState(null),[ce,ne]=i.useState([]),[re,J]=i.useState(""),[B,ye]=i.useState(!1),[Ce,H]=i.useState({}),[ke,pe]=i.useState({}),[Ae,Oe]=i.useState({}),[He,dt]=i.useState([]),[Fe,fe]=i.useState(!1),[$e,De]=i.useState(!1),[ot,Be]=i.useState(),[we,Q]=i.useState("Remote Server"),[_e,lt]=i.useState(""),[ht,mt]=i.useState(""),[xt,Ie]=i.useState(!1),[Ue,pt]=i.useState(null),oe=i.useRef({}),le=i.useRef(null),ge=i.useRef(null),Ne=i.useRef(null),[ue,qe]=i.useState({}),[me,tt]=i.useState(()=>Js()?.stepData?.github?.skipped===!0),Ct=i.useRef(0),wt=i.useRef(l),{shellApi:$t,state:Vt}=Xx(),Mt=i.useRef(!1),Dt=d?.currentStep,Qt=!!d&&d.currentStep!=="complete";Ai(ge,p,"fusion:model-onboarding-modal-size"),i.useEffect(()=>{const _=le.current;_&&(_.scrollTop=0)},[x]);const[Kt,Bt]=i.useState(()=>Js()?.stepData?.["ai-setup"]?.skippedProviders??{}),on=[{key:"ai-setup",label:"AI Setup"},{key:"github",label:"GitHub"},{key:"project-setup",label:"Project"},{key:"first-task",label:"First Task"}],fn=on.findIndex(_=>_.key===x),Jt=x==="complete"?on.length:fn;i.useEffect(()=>{x!=="complete"&&hl(x,{completedSteps:b,skippedSteps:S})},[x,b,S]),i.useEffect(()=>{Mt.current||(Mt.current=!0,ei("onboarding:wizard-opened",{source:Qt?"resume":"initial",resumedFromStep:Dt}))},[Qt,Dt]),i.useEffect(()=>{const _=wt.current!=null,de=l!=null;!_&&de&&v(!0),de||v(!1),wt.current=l},[l]);const an=i.useRef(m);i.useEffect(()=>{if(an.current==="ai-setup"&&x!=="ai-setup"&&!O.some(de=>de.id!=="github"&&de.authenticated)){const de={};for(const D of O)D.id!=="github"&&!D.authenticated&&!Kt[D.id]&&(de[D.id]=!0);if(Object.keys(de).length>0){const D={...Kt,...de};Bt(D),hl(x,{stepData:{"ai-setup":{skippedProviders:D}}})}}an.current=x},[x,O,Kt]);const zt=i.useCallback(async()=>{try{const{providers:_,ghCli:de}=await uo(),D=Af(_);q(D),Z(de),G(Y=>{const Ee={};for(const[Ge,kt]of Object.entries(Y)){const Tt=D.find(Pt=>Pt.id===Ge);Tt&&!Tt.authenticated&&Tt.loginInProgress&&(Ee[Ge]=kt)}return Object.keys(Ee).length===Object.keys(Y).length?Y:Ee}),qe(Y=>{let Ee=!1;const Ge={...Y};for(const[kt,Tt]of Object.entries(Y)){if(Tt!=="pending")continue;D.find(ln=>ln.id===kt)?.loginInProgress||(delete Ge[kt],Ee=!0)}return Ee?Ge:Y}),Bt(Y=>{const Ee={...Y};for(const Ge of D)Ge.authenticated&&Ee[Ge.id]&&delete Ee[Ge.id];return Object.keys(Ee).length===Object.keys(Y).length?Y:Ee})}catch{}},[]),en=i.useCallback(async()=>{try{const _=await Cj();dt((_.providers??[]).map(tL))}catch{}},[]),Zt=i.useCallback(async _=>{De(!0),Be(void 0);try{await _j(_),await en(),await Os().then(de=>ne(de.models??[])),fe(!1)}catch(de){Be(Pe(de)||"Failed to create custom provider")}finally{De(!1)}},[en]),dn=i.useRef(!1);i.useEffect(()=>{x==="ai-setup"&&en(),dn.current&&zt(),dn.current=x!=="ai-setup"},[x,zt,en]),i.useEffect(()=>{if(!O.some(D=>D.loginInProgress))return;const de=setInterval(()=>{zt()},2e3);return()=>clearInterval(de)},[O,zt]);const ve=O.find(_=>_.id==="github"),ze=!!ve,We=ve?.authenticated??!1,Ze=ve?.loginInProgress??!1,Ye=te?.authenticated??!1,It=We||Ye,St=!We&&Ye,Ht=i.useCallback(_=>{if(_.authenticated)return"connected";const de=ue?.[_.id];return de==="timeout"||de==="failed"?"retry":Kt[_.id]?"skipped":"not-connected"},[ue,Kt]);function jt({status:_}){const de={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:D,className:Y}=de[_];return t.jsx("span",{"data-testid":"provider-status-badge",className:Y,"data-status":_,children:D})}const ae=i.useCallback(()=>{if(It)return"connected";const _=ue.github;return _==="pending"?"pending":_==="failed"||_==="timeout"?"failed":me?"skipped":"not-connected"},[It,ue,me]);function Le({status:_}){const de={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:D,className:Y}=de[_];return t.jsx("span",{"data-testid":"github-status-badge",className:Y,"data-status":_,children:D})}const At=i.useCallback(async()=>{try{const _=await Os();ne(_.models)}catch{}},[]),Lt=i.useCallback(async()=>{try{const _=await Pa();if(_.defaultProvider&&_.defaultModelId){const de=`${_.defaultProvider}/${_.defaultModelId}`;J(de)}}catch{}},[]);i.useEffect(()=>{Promise.all([zt(),At(),Lt()]).finally(()=>A(!1))},[zt,At,Lt]),i.useEffect(()=>{const _=VD("ai-setup");if(_?.loginOutcomes){const de=_.loginOutcomes,D={};for(const[Y,Ee]of Object.entries(de))Ee!=="pending"&&(D[Y]=Ee);Object.keys(D).length>0&&qe(D)}},[]);const Ft=i.useCallback((_,de)=>{hl(x,{completedSteps:b,stepData:{"ai-setup":{loginOutcomes:{[_]:de}}}})},[x,b]);i.useEffect(()=>{const _=Object.entries(ue).filter(([de,D])=>D!=="pending");for(const[de,D]of _)Ft(de,D)},[ue,Ft]),i.useEffect(()=>()=>{Ne.current&&clearInterval(Ne.current),Object.values(oe.current).forEach(clearTimeout),oe.current={}},[]);const Me=i.useCallback(_=>{tt(_),hl(x,{completedSteps:b,stepData:{github:{skipped:_}}})},[x,b]),ct=i.useCallback(_=>_==="complete"?-1:Zi.indexOf(_),[]),gt=i.useCallback(()=>{y(de=>[...new Set([...de,x])]),k(de=>de.filter(D=>D!==x)),ei("onboarding:step-completed",{step:x}),x==="github"&&!We&&Me(!1);const _=ct(x);_>=0&&_<Zi.length-1&&w(Zi[_+1])},[x,We,Me,ct]),_t=i.useCallback(()=>{k(de=>[...new Set([...de,x])]),FD(x),ei("onboarding:step-skipped",{step:x}),x==="github"&&!We&&Me(!0);const _=ct(x);_>=0&&_<Zi.length-1&&w(Zi[_+1])},[x,We,Me,ct]),Yt=i.useCallback(()=>{const _=x;y(D=>D.filter(Y=>Y!==_)),k(D=>D.filter(Y=>Y!==_)),_==="github"&&!We&&Me(!1);const de=ct(x);de>0&&w(Zi[de-1])},[x,We,Me,ct]),Xt=i.useCallback(()=>{_t()},[_t]),Te=i.useCallback(async _=>{qe(D=>{const Y=D[_];if(Y&&Y!=="pending"){const{[_]:Ee,...Ge}=D;return Ge}return D});const de=()=>{G(D=>{if(!(_ in D))return D;const Y={...D};return delete Y[_],Y}),Se(D=>{if(!(_ in D))return D;const Y={...D};return delete Y[_],Y}),se(D=>{if(!(_ in D))return D;const Y={...D};return delete Y[_],Y})};de(),qe(D=>({...D,[_]:"pending"})),$(_),Ct.current=0;try{const{url:D,instructions:Y,manualCode:Ee}=await Mj(_);Y?.trim()&&G(Ge=>({...Ge,[_]:Y})),Ee&&Se(Ge=>({...Ge,[_]:Ee})),window.open(Mi(D),"_blank"),Ne.current=setInterval(async()=>{if(Ct.current++,Ct.current>=mL){Ne.current&&(clearInterval(Ne.current),Ne.current=null),$(null),q(Ge=>Ge.map(kt=>kt.id===_?{...kt,loginInProgress:!1}:kt)),qe(Ge=>({...Ge,[_]:"timeout"})),de(),n("Login timed out. Please try again.","warning");return}try{const{providers:Ge,ghCli:kt}=await uo(),Tt=Af(Ge);q(Tt),Z(kt);const Pt=Tt.find(ln=>ln.id===_);if(Pt?.authenticated){Ne.current&&(clearInterval(Ne.current),Ne.current=null),$(null),qe(ln=>({...ln,[_]:"success"})),de(),_==="github"&&Me(!1),n("Login successful","success");return}Pt?.loginInProgress||(Ne.current&&(clearInterval(Ne.current),Ne.current=null),$(null),qe(ln=>({...ln,[_]:"failed"})),de(),n("Login did not complete. Please try again.","error"))}catch{}},2e3)}catch(D){D instanceof Error&&D.message.includes("already in progress")||D&&typeof D=="object"&&"status"in D&&D.status===409?(n("Login already in progress. Cancel it to retry.","warning"),qe(Ee=>({...Ee,[_]:"pending"})),zt()):(n(D instanceof Error?D.message:"Login failed","error"),qe(Ee=>({...Ee,[_]:"failed"}))),$(null),de()}},[n,zt,Me]),Je=i.useCallback(async _=>{const de=je[_]?.trim();if(!de){n("Paste the full redirect URL or authorization code first.","warning");return}ee(_);try{(await Aj(_,de)).submitted?(se(Y=>{if(!(_ in Y))return Y;const Ee={...Y};return delete Ee[_],Ee}),n("Authorization code received. Finishing login…","success")):n("That authorization code was already submitted. Waiting for login…","warning")}catch(D){n(Pe(D)||"Failed to submit authorization code","error")}finally{ee(null)}},[n,je]),Nt=i.useCallback(async _=>{Ne.current&&(clearInterval(Ne.current),Ne.current=null),$(_),Ct.current=0,q(de=>de.map(D=>D.id===_?{...D,loginInProgress:!1}:D)),qe(de=>({...de,[_]:"cancelled"}));try{await Rj(_),await zt().catch(()=>{}),n("Login cancelled","success")}catch(de){n(Pe(de)||"Failed to cancel login","error")}finally{$(null),G(de=>{if(!(_ in de))return de;const D={...de};return delete D[_],D}),Se(de=>{if(!(_ in de))return de;const D={...de};return delete D[_],D}),se(de=>{if(!(_ in de))return de;const D={...de};return delete D[_],D}),ee(de=>de===_?null:de)}},[n,zt]),Ut=i.useCallback((_,de)=>{H(Y=>({...Y,[_]:de}));const D=oe.current[_];D&&(clearTimeout(D),delete oe.current[_]),pe(Y=>{if(!Y[_])return Y;const Ee={...Y};return delete Ee[_],Ee}),Oe(Y=>{if(!Y[_])return Y;const Ee={...Y};return delete Ee[_],Ee})},[]),tn=i.useCallback(()=>{const _=le.current;if(!_)return;const de=typeof window<"u"&&typeof window.matchMedia=="function"&&window.matchMedia("(prefers-reduced-motion: reduce)").matches;try{if(typeof _.scrollTo=="function"){_.scrollTo({top:0,behavior:de?"auto":"smooth"});return}}catch{}_.scrollTop=0},[]),Xn=i.useCallback(async(_,de)=>{const D=(de??Ce[_]??"").trim(),Y=oL(_,D);if(Y){pe(Ge=>({...Ge,[_]:Y}));return}const Ee=oe.current[_];Ee&&(clearTimeout(Ee),delete oe.current[_]),$(_),pe(Ge=>{const kt={...Ge};return delete kt[_],kt}),Oe(Ge=>{if(!Ge[_])return Ge;const kt={...Ge};return delete kt[_],kt});try{await Ij(_,D),await zt(),tn(),H(Ge=>{const kt={...Ge};return delete kt[_],kt}),pe(Ge=>{if(!Ge[_])return Ge;const kt={...Ge};return delete kt[_],kt}),Oe(Ge=>({...Ge,[_]:"✓ Key saved"})),oe.current[_]=setTimeout(()=>{Oe(Ge=>{if(!Ge[_])return Ge;const kt={...Ge};return delete kt[_],kt}),delete oe.current[_]},3e3),n("API key saved","success")}catch(Ge){const kt=Ge instanceof TypeError&&Ge.message.includes("Failed to fetch")?"Could not reach the server. Check your connection and try again.":Ge instanceof Error?Ge.message:"Failed to save API key";pe(Tt=>({...Tt,[_]:kt})),Oe(Tt=>{if(!Tt[_])return Tt;const Pt={...Tt};return delete Pt[_],Pt}),n(kt,"error")}finally{$(null)}},[Ce,n,zt,tn]),be=i.useCallback(async _=>{$(_);try{await Tj(_),await zt(),n("API key removed","success")}catch(de){n(de instanceof Error?de.message:"Failed to clear API key","error")}finally{$(null)}},[n,zt]),it=i.useCallback(async _=>{$(_);try{await Pj(_),await zt(),n("Logged out","success")}catch(de){n(de instanceof Error?de.message:"Logout failed","error")}finally{$(null)}},[n,zt]),rt=i.useCallback(_=>{J(_)},[]),at=i.useCallback(async()=>{try{const _={modelOnboardingComplete:!0};if(re){const de=re.indexOf("/"),D=de!==-1?re.slice(0,de):void 0,Y=de!==-1?re.slice(de+1):re,Ee=ce.find(Ge=>Ge.id===Y);Ee?(_.defaultProvider=Ee.provider,_.defaultModelId=Ee.id):D&&Y&&(_.defaultProvider=D,_.defaultModelId=Y)}await kn(_),Pf()}catch{}},[re,ce,kn,Pf]),ut=i.useCallback(async()=>{const _=[...new Set([...b,"first-task"])];ye(!0);try{await at(),ei("onboarding:completed",{completedSteps:_,skippedSteps:S}),y(_),k(de=>de.filter(D=>D!=="first-task")),w("complete")}finally{ye(!1)}},[at,b,S]),vt=i.useCallback(async()=>{if(!s)return;const _=j.trim();if(!_){L("Please enter a task description.");return}L(null),E(!0);let de=!1;try{const D=await Mg({description:_,source:{sourceType:"dashboard_ui"}},s);M(D),v(!0),ei("onboarding:first-task-created",{taskId:D?.id}),n("Task created","success"),de=!0}catch(D){const Y=D instanceof Error?D.message:"Something went wrong creating your task. Please try again.";L(Y),n(Y,"error")}finally{E(!1)}de&&at()},[s,j,n,at]),ie=i.useCallback(async()=>{ye(!0);try{await at()}finally{ye(!1)}ei("onboarding:open-new-task",{}),r?.()},[at,r]),st=i.useCallback(async()=>{if(It){ye(!0);try{await at()}finally{ye(!1)}g(!1),e(),ei("onboarding:open-github-import",{}),o?.()}},[at,It,e,o]),Gt=i.useCallback(async()=>{ei("onboarding:dismissed",{currentStep:x,completedSteps:b,skippedSteps:S}),ye(!0);try{await kn({modelOnboardingComplete:!0})}catch{}g(!1),e()},[x,b,S,e]),Cn=i.useCallback(()=>{ei("onboarding:finished",{}),g(!1),e()},[e]),fs=i.useCallback(()=>{const _=l??F;_&&(at(),c?.(_),e())},[l,F,at,c,e]),On=i.useCallback(()=>{at(),e()},[at,e]),jn=ae(),zn=O.filter(_=>_.id!=="github"),hn=Vt.host!=="web"&&!Vt.activeProfileId,Et=[...zn].sort(Df),En=Et.some(_=>!_.type||_.type==="oauth"),yn=Et.some(_=>_.type==="api_key"),ls=zn.filter(_=>_.authenticated),cs=ls.length>0,Hn=!!s,qn=x==="github"&&!cs,wn=i.useCallback(async()=>{if($t){pt(null),Ie(!0);try{const _=await $t.saveProfile({name:we,serverUrl:_e,authToken:ht.trim()?ht:null});try{await $t.setActiveProfile(_.id)}catch(de){pt(Pe(de)||"Saved profile but failed to activate it");return}lt(""),mt(""),n("Remote server profile saved","success")}catch(_){pt(Pe(_)||"Failed to save shell connection")}finally{Ie(!1)}}},[$t,we,_e,ht,n]);if(!p)return null;const Zn=(()=>{if(!re)return"";const _=re.indexOf("/"),de=_===-1?void 0:re.slice(0,_),D=_===-1?re:re.slice(_+1),Y=ce.find(Ee=>Ee.id===D&&(!de||Ee.provider===de));return Y?.name?Y.name:de?`${au(de)} ${D}`:re})(),_n=[];if(Hn?_n.push({label:"Project",status:"connected",detail:"Project selected — task creation and imports are available"}):_n.push({label:"Project",status:"missing",detail:"Register a project to enable task creation and imports"}),cs){const _=au(ls[0]?.id??"");_n.push({label:"AI Provider",status:"connected",detail:`${_} connected — AI agents can work on tasks`})}else zn.length>0&&zn.some(_=>Kt[_.id])?_n.push({label:"AI Provider",status:"skipped",detail:"AI agents won't be available until you connect a provider"}):_n.push({label:"AI Provider",status:"missing",detail:"Connect a provider in Settings → AI Setup"});It?_n.push({label:"GitHub",status:"connected",detail:St?"Connected via GitHub CLI — imports and PR tracking are available":"Issues and PRs can be imported"}):!ze||me?_n.push({label:"GitHub",status:"skipped",detail:"You can connect anytime from Settings"}):_n.push({label:"GitHub",status:"missing",detail:"Connect to import issues as tasks"}),Zn&&_n.push({label:"Default Model",status:"connected",detail:Zn});const is=l??F,Ns=is?.description?.split(`
692
- `)[0]?.trim()||is?.title||"",es=new Set(yd),ks=Et.filter(_=>es.has(_.id)).sort((_,de)=>{const D=yd.indexOf(_.id),Y=yd.indexOf(de.id);return D!==Y?D-Y:Df(_,de)}),Is=Et.filter(_=>_.authenticated&&!es.has(_.id)),Ss=Et.filter(_=>!_.authenticated&&!es.has(_.id)),X=_=>{const de=ue[_.id]==="timeout"||ue[_.id]==="failed"||ue[_.id]==="cancelled",D=_.loginInProgress&&!de;if(_.id==="llama-cpp"&&_.type==="cli")return t.jsx(kD,{authenticated:_.authenticated,onToggled:()=>{zt()}},_.id);if(_.id==="claude-cli"&&_.type==="cli")return t.jsx(vD,{authenticated:_.authenticated,onToggled:()=>{zt()}},_.id);if(_.id==="cursor-cli"&&_.type==="cli")return t.jsx(wD,{authenticated:_.authenticated,onToggled:()=>{zt()}},_.id);if(_.type==="api_key"){const Y=ou(_.id),Ee=cL(_);return t.jsxs("div",{"data-testid":`onboarding-provider-card-${_.id}`,className:`onboarding-provider-card${_.authenticated?" onboarding-provider-card--connected":""}`,children:[t.jsx("div",{className:"onboarding-provider-card__icon","data-testid":`onboarding-provider-icon-${_.id}`,"aria-hidden":"true",children:t.jsx(Sn,{provider:_.id,size:"md"})}),t.jsxs("div",{className:"onboarding-provider-card__body",children:[t.jsxs("strong",{className:"onboarding-provider-card__name",children:[t.jsx(kg,{size:14,className:"onboarding-provider-key-icon"}),_.name]}),t.jsx("span",{className:"onboarding-provider-card__description",children:Y.description}),t.jsx(jt,{status:Ht(_)}),_.authenticated&&_.keyHint&&t.jsxs("span",{className:"auth-key-hint",children:["Key: ",_.keyHint]})]}),t.jsx("div",{className:"onboarding-provider-card__actions onboarding-provider-card__actions--api-key",children:t.jsx(uL,{provider:_,apiKeyInfo:Ee,inputValue:Ce[_.id]??"",isSaving:I===_.id,error:ke[_.id],success:Ae[_.id],isConnected:_.authenticated,onInputChange:Ut,onSave:Xn,onClear:be})})]},_.id)}return t.jsxs("div",{"data-testid":`onboarding-provider-card-${_.id}`,className:`onboarding-provider-card${_.authenticated?" onboarding-provider-card--connected":""}`,children:[t.jsx("div",{className:"onboarding-provider-card__icon","data-testid":`onboarding-provider-icon-${_.id}`,"aria-hidden":"true",children:t.jsx(Sn,{provider:_.id,size:"md"})}),t.jsxs("div",{className:"onboarding-provider-card__body",children:[t.jsx("strong",{className:"onboarding-provider-card__name",children:_.name}),t.jsx("span",{className:"onboarding-provider-card__description",children:ou(_.id).description}),t.jsx(jt,{status:Ht(_)})]}),t.jsx("div",{className:"onboarding-provider-card__actions",children:I===_.id?_.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 Nt(_.id),children:"Cancel"})]}):D?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 Nt(_.id),children:"Cancel"})]}):_.authenticated?t.jsx("button",{className:"btn btn-sm",onClick:()=>it(_.id),children:"Logout"}):t.jsx("button",{className:"btn btn-primary btn-sm",onClick:()=>Te(_.id),children:"Login"})}),(I===_.id||D)&&N[_.id]&&t.jsx(vd,{instructions:N[_.id],"data-testid":`onboarding-login-instructions-${_.id}`}),(I===_.id||D)&&xe[_.id]&&t.jsx(ND,{value:je[_.id]??"",onChange:Y=>se(Ee=>({...Ee,[_.id]:Y})),onSubmit:()=>void Je(_.id),prompt:xe[_.id].prompt,placeholder:xe[_.id].placeholder,helpText:xe[_.id].helpText,disabled:Ve===_.id,submitLabel:Ve===_.id?"Submitting…":"Submit code","data-testid":`onboarding-manual-code-${_.id}`}),ue[_.id]==="timeout"&&I!==_.id&&t.jsx("p",{className:"onboarding-helper-text onboarding-inline-feedback",children:"Login timed out. Please try again."}),ue[_.id]==="failed"&&I!==_.id&&t.jsx("p",{className:"field-error onboarding-inline-feedback",children:"Login failed. Please try again."})]},_.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:ge,children:[t.jsxs("div",{className:"model-onboarding-header",children:[t.jsxs("h2",{id:"onboarding-title",className:"model-onboarding-title",children:[x==="ai-setup"&&t.jsxs(t.Fragment,{children:[t.jsx(Qn,{size:24})," Set Up AI ",t.jsx("span",{className:"onboarding-optional-badge",children:"Optional"})]}),x==="github"&&t.jsxs(t.Fragment,{children:[t.jsx(Ws,{size:24})," Connect GitHub ",t.jsx("span",{className:"onboarding-optional-badge",children:"Optional"})]}),x==="project-setup"&&t.jsxs(t.Fragment,{children:[t.jsx(em,{size:24})," Set Up Your Project"]}),x==="first-task"&&t.jsxs(t.Fragment,{children:[t.jsx(em,{size:24})," Create Your First Task"]}),x==="complete"&&t.jsxs(t.Fragment,{children:[t.jsx(Dn,{size:24})," All Set!"]})]}),x!=="complete"&&t.jsx("button",{className:"modal-close",onClick:Gt,"aria-label":"Skip onboarding",title:"Skip for now",children:t.jsx(nn,{size:20})})]}),t.jsx("div",{className:"model-onboarding-steps",children:on.map((_,de)=>{const D=Jt>de,Y=b.includes(_.key)&&D,Ee=S.includes(_.key)&&!b.includes(_.key)&&D,Ge=Y||Ee;return t.jsxs("div",{className:"onboarding-step-wrapper",children:[de>0&&t.jsx("div",{className:`model-onboarding-step-connector ${de<=Jt?"done":""}`}),Ge?t.jsxs("button",{className:`model-onboarding-step-indicator ${x===_.key?"active":""} ${Y?"done":""} ${Ee?"skipped":""}`,onClick:()=>w(_.key),"aria-label":`Go back to ${_.label}`,title:`Review ${_.label}`,children:[t.jsx("span",{className:"step-number",children:Y?t.jsx(Dn,{size:14}):Ee?t.jsx("span",{className:"onboarding-step-skip-mark",children:"–"}):de+1}),t.jsx("span",{className:"step-label",children:_.label})]}):t.jsxs("div",{className:`model-onboarding-step-indicator ${x===_.key?"active":""} ${Y?"done":""} ${Ee?"skipped":""}`,children:[t.jsx("span",{className:"step-number",children:Y?t.jsx(Dn,{size:14}):Ee?t.jsx("span",{className:"onboarding-step-skip-mark",children:"–"}):de+1}),t.jsx("span",{className:"step-label",children:_.label})]})]},_.key)})}),t.jsxs("div",{className:"model-onboarding-content",ref:le,children:[x==="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."}),hn&&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:we,onChange:_=>Q(_.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:_e,onChange:_=>lt(_.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:ht,onChange:_=>mt(_.target.value)}),Ue&&t.jsx("small",{className:"field-error",children:Ue}),t.jsxs("div",{className:"onboarding-apikey-input-row",children:[t.jsx("button",{type:"button",className:"btn btn-sm",onClick:()=>void $t?.openConnectionManager(),children:"Open manager"}),t.jsx("button",{type:"button",className:"btn btn-primary btn-sm",onClick:()=>void wn(),disabled:!_e.trim()||xt,children:xt?"Saving…":"Save remote server"})]})]}),!K&&O.length>0&&(()=>{const _=O.filter(Ge=>Ge.id!=="github"&&Ge.authenticated).length,de=O.filter(Ge=>Ge.id!=="github").length,D=Object.keys(Kt).filter(Ge=>!O.find(kt=>kt.id===Ge)?.authenticated).length;if(de===0)return null;let Y="onboarding-provider-summary",Ee="";return _>0?(Y+=" onboarding-provider-summary--connected",Ee=`✓ ${_} of ${de} provider${de!==1?"s":""} connected`):D>0?(Y+=" onboarding-provider-summary--skipped",Ee=`${D} provider${D!==1?"s":""} skipped`):(Y+=" onboarding-provider-summary--none",Ee="No providers connected yet"),t.jsx("div",{className:Y,"data-testid":"provider-summary",children:Ee})})(),t.jsx(ta,{slotId:"onboarding-recommendation-card",projectId:s}),t.jsx(ti,{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."})}),O.length>0&&!O.some(_=>_.authenticated)&&t.jsx("p",{className:"onboarding-helper-text",children:"Skip this step if you'd like — you can always add providers later from Settings."}),K?t.jsxs("div",{className:"model-onboarding-loading",children:[t.jsx(bt,{size:24,className:"animate-spin"}),t.jsx("span",{children:"Loading providers…"})]}):O.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(ta,{slotId:"onboarding-provider-card",projectId:s,renderPlaceholder:!1,actions:{refreshAuthProviders:()=>{zt()}}}),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"}),ks.length>0?t.jsx("div",{className:"model-onboarding-providers",children:ks.map(_=>X(_))}):t.jsx("p",{className:"onboarding-helper-text",children:"No quick-start providers are available in this environment."})]}),Is.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:Is.map(_=>X(_))})]}),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(ti,{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."})}),ce.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(ys,{models:ce,value:re,onChange:rt,placeholder:"Select a default model…",label:"Default model"})}),re&&t.jsx("div",{className:"onboarding-model-preview",children:t.jsxs("small",{className:"settings-muted",children:["Selected:"," ",ce.find(_=>_.id===re)?.name??re]})})]}),t.jsx(ti,{summary:"Advanced provider settings",className:"onboarding-provider-advanced",children:t.jsxs("div",{"data-testid":"onboarding-advanced-provider-settings",children:[Ss.length>0?t.jsx("div",{className:"model-onboarding-providers",children:Ss.map(_=>X(_))}):t.jsx("p",{className:"onboarding-helper-text",children:"All currently available providers are already shown above."}),He.length>0?t.jsx("div",{className:"onboarding-custom-provider-list",children:He.map(_=>t.jsxs("div",{className:"onboarding-custom-provider-item",children:[t.jsx(Sn,{provider:_.id,size:"sm"}),t.jsx("span",{children:_.name||_.id})]},_.id))}):null,Fe?t.jsx(ED,{onSave:Zt,onCancel:()=>{fe(!1),Be(void 0)},saving:$e,error:ot}):t.jsx("button",{type:"button",className:"btn btn-sm",onClick:()=>fe(!0),children:"Add custom provider"})]})}),En&&t.jsx(ti,{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."})}),yn&&t.jsx(ti,{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(ta,{slotId:"onboarding-setup-help",projectId:s})]})]}),x==="github"&&t.jsxs("div",{className:"model-onboarding-github",children:[It?t.jsx("p",{className:"model-onboarding-description",children:St?"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."}),!It&&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"})]})}),qn&&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(ti,{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."})}),ze?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(Ws,{size:16,className:"onboarding-provider-title-icon"}),"GitHub"]}),t.jsx("span",{"data-testid":"onboarding-auth-status-github",children:t.jsx(Le,{status:jn})})]}),We&&(I==="github"?t.jsx("button",{className:"btn btn-sm",disabled:!0,children:"Logging out…"}):t.jsx("button",{className:"btn btn-sm",onClick:()=>it("github"),children:"Disconnect"}))]}),(jn==="not-connected"||jn==="pending")&&t.jsxs("div",{className:"onboarding-github-connect-cta","data-testid":"onboarding-github-connect-cta",children:[I==="github"||Ze?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 Nt("github"),children:"Cancel"})]}):t.jsxs("button",{className:"btn btn-primary btn-sm",onClick:()=>Te("github"),children:[t.jsx(Ws,{size:16}),"Connect"]}),(I==="github"||Ze)&&N.github&&t.jsx(vd,{instructions:N.github,"data-testid":"onboarding-login-instructions-github"})]}),jn==="connected"&&t.jsx("div",{className:"onboarding-github-feedback onboarding-github-feedback--success",children:St?"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."}),jn==="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:()=>Te("github"),children:"Retry"}),t.jsx("button",{className:"onboarding-skip-step-link",onClick:Xt,children:"Skip for now"})]})]}),jn==="pending"&&t.jsx("div",{className:"onboarding-github-feedback onboarding-github-feedback--info",children:"Waiting for GitHub authorization…"}),jn==="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:()=>Te("github"),children:"Connect anyway"})})]}),jn==="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(Sn,{provider:"github",size:"lg"})}),St?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:()=>w("project-setup"),children:St?"Continue with gh CLI auth →":"Continue without GitHub →"}),St&&(I==="github"||Ze?t.jsxs("button",{className:"btn btn-sm",disabled:!0,children:[t.jsx(bt,{size:14,className:"onboarding-spinner"}),"Waiting for OAuth login…"]}):t.jsxs("button",{className:"btn btn-sm",onClick:()=>Te("github"),children:[t.jsx(Sn,{provider:"github",size:"sm"}),"Connect OAuth (optional)"]}))]}),St&&(I==="github"||Ze)&&N.github&&t.jsx(vd,{instructions:N.github,"data-testid":"onboarding-login-instructions-github"})]})]}),x==="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."}),Hn?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(ti,{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."})})]}),x==="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."}),C&&is?t.jsxs("div",{className:"onboarding-task-created",children:[t.jsx(Dn,{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:is.id}),Ns&&t.jsx("p",{className:"onboarding-task-created__description",children:Ns}),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:fs,children:"View Task"}),t.jsx("button",{type:"button",className:"btn",onClick:On,children:"Go to Dashboard"})]})]}):t.jsxs(t.Fragment,{children:[Hn?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:j,onChange:_=>{P(_.target.value),L(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:vt,disabled:U,"data-testid":"onboarding-first-task-submit",children:U?t.jsxs(t.Fragment,{children:[t.jsx(bt,{size:16,className:"animate-spin"}),t.jsx("span",{children:"Creating task…"})]}):"Create First Task"})})]}),R&&t.jsxs("div",{className:"onboarding-task-error",role:"alert","data-testid":"onboarding-task-error",children:[t.jsx("p",{className:"field-error",children:R}),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(dL,{items:_n}),Hn&&t.jsxs(t.Fragment,{children:[t.jsx(ti,{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:ie,disabled:B,children:[t.jsx("div",{className:"cta-icon",children:t.jsx(gn,{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${It?"":" onboarding-cta-card--disabled"}`,"data-testid":"cta-github-import",onClick:st,disabled:B||!It,children:[t.jsx("div",{className:"cta-icon",children:t.jsx(Ws,{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"}),!It&&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."]})]})]})]}),x==="complete"&&t.jsxs("div",{className:"model-onboarding-complete",children:[t.jsx(Dn,{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:[x==="ai-setup"&&t.jsxs(t.Fragment,{children:[t.jsx("button",{className:"btn btn-sm",onClick:Gt,disabled:B,children:"Skip for now"}),t.jsx("button",{className:"onboarding-skip-step-link",onClick:_t,children:"Skip setup →"}),t.jsx("button",{className:"btn btn-primary",onClick:gt,children:"Next →"})]}),x==="github"&&t.jsxs(t.Fragment,{children:[t.jsx("button",{className:"btn btn-sm",onClick:Yt,children:"← Back"}),t.jsx("button",{className:"onboarding-skip-step-link",onClick:_t,children:"Skip GitHub →"}),t.jsx("button",{className:"btn btn-primary",onClick:gt,children:"Next →"})]}),x==="project-setup"&&t.jsxs(t.Fragment,{children:[t.jsx("button",{className:"btn btn-sm",onClick:Yt,children:"← Back"}),t.jsx("button",{className:"btn btn-primary",onClick:gt,disabled:!Hn,children:"Next →"})]}),x==="first-task"&&!C&&t.jsxs(t.Fragment,{children:[t.jsx("button",{className:"btn btn-sm",onClick:Yt,children:"← Back"}),t.jsx("button",{className:"btn btn-primary",onClick:ut,disabled:B,children:B?t.jsxs(t.Fragment,{children:[t.jsx(bt,{size:16,className:"animate-spin"}),t.jsx("span",{children:"Saving…"})]}):"Finish Setup"})]}),x==="complete"&&t.jsxs("button",{className:"btn btn-primary",onClick:Cn,children:[t.jsx(Dn,{size:16}),t.jsx("span",{children:"Get Started"})]})]})]})})}function sv({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 pL=i.lazy(()=>xn(()=>import("./SetupWizardModal-BKscasuh.js"),__vite__mapDeps([13,1,14,15,16,17,5,6,18])).then(e=>({default:e.SetupWizardModal}))),fL=i.lazy(()=>xn(()=>import("./SettingsModal-BAgB4_AR.js"),__vite__mapDeps([19,1,20,21,22,2,5,6,23])).then(e=>({default:e.SettingsModal})));function gL(){(typeof window<"u"&&window.requestIdleCallback||(n=>globalThis.setTimeout(n,200)))(()=>{xn(()=>import("./SettingsModal-BAgB4_AR.js"),__vite__mapDeps([19,1,20,21,22,2,5,6,23]))},{timeout:1500})}function bL({projectId:e,tasks:n,projects:s,currentProject:a,addToast:r,toasts:o,removeToast:l,modalManager:c,projectActions:d,taskHandlers:u,taskOperations:m,deepLink:h,settings:f,onSettingsClose:p,onReopenOnboarding:g}){const[x,w]=i.useState(null),b=c.detailTask?(()=>{const j=n.find(P=>P.id===c.detailTask?.id);return j?"prompt"in c.detailTask?{...c.detailTask,...j,prompt:c.detailTask.prompt,log:c.detailTask.log}:j:c.detailTask})():null,y=p??c.closeSettings,S=i.useCallback(()=>{c.openNewTask()},[c]),k=i.useCallback(()=>{c.openGitHubImport()},[c]),C=i.useCallback(j=>{w(null),c.closeModelOnboarding(),c.openDetailTask(j)},[c]),v=i.useCallback(async j=>{const P=await u.handleModalCreate(j);return c.modelOnboardingOpen&&w(P),P},[u.handleModalCreate,c.modelOnboardingOpen]);return i.useEffect(()=>{!c.modelOnboardingOpen&&x&&w(null)},[c.modelOnboardingOpen,x]),i.useEffect(()=>{gL()},[]),t.jsxs(t.Fragment,{children:[b&&t.jsx(ga,{children:t.jsx(OI,{task:b,projectId:e,tasks:n,onClose:h.handleDetailClose,onOpenDetail:c.openDetailTask,mobileHeaderMode:c.detailTaskOrigin==="list-mobile"?"back":"close",onMoveTask:m.moveTask,onDeleteTask:m.deleteTask,onMergeTask:m.mergeTask,onRetryTask:m.retryTask,onResetTask:m.resetTask,onDuplicateTask:m.duplicateTask,onTaskUpdated:c.updateDetailTask,addToast:r,prAuthAvailable:f.prAuthAvailable,initialTab:c.detailTaskInitialTab})}),c.settingsOpen&&t.jsx(ga,{children:t.jsx(i.Suspense,{fallback:null,children:t.jsx(fL,{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(GT,{isOpen:c.githubImportOpen,onClose:c.closeGitHubImport,onImport:u.handleGitHubImport,tasks:n,projectId:e}),t.jsx(ga,{children:t.jsx(XT,{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(ga,{children:t.jsx(l4,{isOpen:c.isSubtaskOpen,onClose:c.closeSubtask,initialDescription:c.subtaskInitialDescription??"",onTasksCreated:u.handleSubtaskTasksCreated,projectId:e,resumeSessionId:c.subtaskResumeSessionId})}),t.jsx(A4,{isOpen:c.terminalOpen,onClose:c.closeTerminal,initialCommand:c.terminalInitialCommand,projectId:e}),t.jsx(R4,{isOpen:c.scriptsOpen,onClose:c.closeScripts,addToast:r,onRunScript:c.runScript,projectId:e}),c.filesOpen&&t.jsx(e$,{initialWorkspace:c.fileBrowserWorkspace,isOpen:!0,onClose:c.closeFiles,onWorkspaceChange:c.setFileWorkspace,projectId:e}),c.todosOpen&&t.jsx(n$,{isOpen:!0,onClose:c.closeTodos,addToast:r,projectId:e,onPlanningMode:c.openPlanningWithInitialPlan}),t.jsx(u$,{isOpen:c.usageOpen,onClose:c.closeUsage,projectId:e,anchorRect:c.usageAnchorRect}),t.jsx(U$,{isOpen:c.systemStatsOpen,onClose:c.closeSystemStats,projectId:e}),c.schedulesOpen&&t.jsx(P$,{onClose:c.closeSchedules,addToast:r,projectId:e}),t.jsx(ga,{children:t.jsx($$,{isOpen:c.newTaskModalOpen,onClose:c.closeNewTask,tasks:n,onCreateTask:v,addToast:r,projectId:e,onPlanningMode:c.openPlanningWithInitialPlan,onSubtaskBreakdown:c.openSubtaskBreakdown})}),t.jsx(W$,{isOpen:c.activityLogOpen,onClose:c.closeActivityLog,tasks:n,projectId:e,projects:s,currentProject:a,onOpenTaskDetail:j=>{const P=n.find(U=>U.id===j);P&&c.openDetailTask(P)}}),t.jsx(ga,{children:t.jsx(G$,{isOpen:c.gitManagerOpen,onClose:c.closeGitManager,tasks:n,addToast:r,projectId:e})}),t.jsx(ga,{children:t.jsx(iD,{isOpen:c.workflowStepsOpen,onClose:c.closeWorkflowSteps,addToast:r,projectId:e})}),t.jsx(xD,{isOpen:c.agentsOpen,onClose:c.closeAgents,addToast:r,projectId:e}),c.setupWizardOpen&&t.jsx(i.Suspense,{fallback:null,children:t.jsx(pL,{onProjectRegistered:d.handleSetupComplete,onClose:c.closeSetupWizard})}),c.modelOnboardingOpen&&t.jsx(hL,{onComplete:d.handleModelOnboardingComplete,addToast:r,projectId:e??"",onOpenSetupWizard:d.handleAddProject,onOpenNewTask:S,onOpenGitHubImport:k,firstCreatedTask:x,onViewTask:C}),t.jsx(sv,{toasts:o,onRemove:l})]})}function xL({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 lu=[{id:"projects",label:"Loading projects"},{id:"project",label:"Selecting project"},{id:"tasks",label:"Fetching tasks"}];function vL(e,n){if(n==="ready")return"done";const s=lu.findIndex(r=>r.id===n),a=lu.findIndex(r=>r.id===e);return a<s?"done":a===s?"active":"pending"}function yL({stage:e}){const[n]=i.useState(()=>yk());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:lu.map(s=>{const a=vL(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(bt,{className:"dashboard-loader__spinner animate-spin",size:14}):"•"}),t.jsx("span",{className:"dashboard-loader__step-label",children:s.label})]},s.id)})})]})})}const wL=5e3;function kL(e,n,s){return e||n&&s===0?"idle":n&&s>0?"paused":s>0?"running":"idle"}function jL(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++,Rl(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 NL(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),m=i.useRef(null),h=i.useRef(null),f=i.useCallback(async()=>{h.current&&h.current.abort(),h.current=new AbortController;try{c(!0),u(null);const w=await SS(n);o(w)}catch(w){if(w instanceof Error&&w.name==="AbortError")return;u(w instanceof Error?w.message:"Failed to fetch executor stats")}finally{c(!1)}},[n]);i.useEffect(()=>(f(),()=>{h.current&&h.current.abort()}),[f]),i.useEffect(()=>(m.current&&clearInterval(m.current),m.current=setInterval(()=>{f()},wL),()=>{m.current&&(clearInterval(m.current),m.current=null)}),[f]);const p=jL(e,s,a),g=kL(r.globalPause,r.enginePaused,p.runningTaskCount);return{stats:{...p,executorState:g,maxConcurrent:r.maxConcurrent,lastActivityAt:r.lastActivityAt},loading:l,error:d,refresh:f}}const SL={planning:_i,subtask:ja,mission_interview:vs,milestone_interview:vs,slice_interview:vs},CL={planning:"Planning",subtask:"Subtask Breakdown",mission_interview:"Mission Interview",milestone_interview:"Milestone Interview",slice_interview:"Slice Interview"};function EL({sessions:e,generating:n,needsInput:s,onOpenSession:a,onDismissSession:r}){const{confirm:o}=ai(),[l,c]=i.useState(!1),[d,u]=i.useState(new Set),m=i.useRef(null),h=i.useRef(new Map),f=i.useRef(null),{activeTabMap:p}=_r(),g=i.useMemo(()=>Ia(),[]);if(i.useEffect(()=>{if(!l)return;const b=y=>{m.current&&!m.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 S of e){const k=p.get(S.id),C=[S.status,S.updatedAt,k?.tabId??S.lockedByTab??"",k?.stale?"stale":"fresh"].join("|"),v=h.current.get(S.id);v&&v!==C&&b.add(S.id),y.set(S.id,C)}if(h.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 x=e.length,w=s>0;return t.jsxs("div",{ref:m,className:"background-tasks-indicator",children:[t.jsxs("button",{className:`background-tasks-indicator__pill${w?" background-tasks-indicator__pill--attention":""}`,onClick:()=>c(b=>!b),title:`${x} background AI task${x!==1?"s":""}${s>0?` (${s} need${s!==1?"":"s"} input)`:""}`,children:[n>0&&t.jsx(bt,{size:12,style:{animation:"spin 1s linear infinite"}}),s>0&&n===0&&t.jsx(Cd,{size:12}),t.jsxs("span",{children:["AI ",x]})]}),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=SL[b.type],S=b.status==="generating",k=b.status==="awaiting_input",C=b.status==="error",v=p.get(b.id),j=v?.tabId??b.lockedByTab??null,P=!!(j&&j!==g&&!v?.stale),U=d.has(b.id);return t.jsxs("div",{className:`background-tasks-indicator__item${U?" background-tasks-indicator__item--updated":""}`,style:{transition:"background-color 220ms ease, transform 220ms ease",backgroundColor:U?"var(--color-accent-soft, rgba(59, 130, 246, 0.14))":void 0,transform:U?"translateY(-1px)":void 0},onClick:async()=>{P&&!await o({title:"Open Active Session",message:"This session is active in another tab. Open anyway?"})||(a(b),c(!1))},children:[C?t.jsx(Ps,{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":CL[b.type],S&&" — generating...",k&&!P&&" — needs input",k&&P&&" — active in another tab"]})]}),S&&t.jsx(bt,{size:14,className:"background-tasks-indicator__session-icon",style:{animation:"spin 1s linear infinite",color:"var(--color-success)"}}),k&&!P&&t.jsx(Cd,{size:14,className:"background-tasks-indicator__session-icon",style:{color:"var(--triage)"}}),k&&P&&t.jsx(Ql,{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(nn,{size:12})})]},b.id)})})]})]})}function _L(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 ML(e){switch(e){case"running":return{label:"Running",color:"var(--color-success)",icon:Yn};case"paused":return{label:"Paused",color:"var(--triage)",icon:pi};case"idle":default:return{label:"Idle",color:"var(--text-muted)",icon:Qn}}}function AL({tasks:e,projectId:n,taskStuckTimeoutMs:s,backgroundSessions:a,backgroundGenerating:r,backgroundNeedsInput:o,onOpenBackgroundSession:l,onDismissBackgroundSession:c,lastFetchTimeMs:d,currentProjectPath:u,onOpenProjectDirectory:m,keyboardOpen:h}){if(h)return null;const{stats:f,loading:p,error:g}=NL(e,n,s,d),[x,w]=i.useState(!1),b=i.useMemo(()=>ML(f.executorState),[f.executorState]),y=i.useMemo(()=>_L(f.lastActivityAt),[f.lastActivityAt]),S=b.icon;return g?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(No,{size:14}),g]})}):p&&f.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 ${f.executorState==="running"?"executor-status-bar--running":""}`,role:"status","aria-label":"Executor status",children:[a&&a.length>0&&l&&c&&t.jsxs(t.Fragment,{children:[t.jsx(EL,{sessions:a,generating:r??0,needsInput:o??0,onOpenSession:l,onDismissSession:c}),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:f.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 ${f.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:f.runningTaskCount}),t.jsx("span",{className:"executor-status-bar__separator","aria-hidden":"true",children:"/"}),t.jsx("span",{className:"executor-status-bar__max",children:f.maxConcurrent})]}),t.jsx("span",{className:"executor-status-bar__divider","aria-hidden":"true"}),f.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:f.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 ${f.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 ${f.blockedTaskCount>0?"executor-status-bar__count--warning":""}`,children:f.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:f.inReviewCount})]}),u&&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${x?" executor-status-bar__folder-toggle--active":""}`,onClick:()=>w(k=>!k),"aria-label":x?"Hide project directory":"Show project directory","aria-expanded":x,"data-testid":"executor-project-path-toggle",title:x?"Hide project directory":"Show project directory",children:t.jsx(bs,{size:12,"aria-hidden":"true"})}),x&&t.jsx("button",{className:"executor-status-bar__project-path",onClick:m,title:u,"data-testid":"executor-project-path-link",children:u})]})]}),t.jsx("div",{className:"executor-status-bar__spacer"}),t.jsxs("div",{className:"executor-status-bar__segment executor-status-bar__segment--time",children:[t.jsx(Hi,{size:12,className:"executor-status-bar__icon","aria-hidden":"true"}),t.jsx("span",{className:"executor-status-bar__time",children:y})]}),t.jsx("span",{className:"executor-status-bar__divider","aria-hidden":"true"}),t.jsxs("div",{className:"executor-status-bar__segment",children:[t.jsx(S,{size:12,style:{color:b.color},"aria-hidden":"true"}),t.jsx("span",{className:"executor-status-bar__state",style:{color:b.color},children:b.label})]})]})}const PL={planning:_i,subtask:ja,mission_interview:vs,milestone_interview:vs,slice_interview:vs},RL={planning:"Planning",subtask:"Subtask Breakdown",mission_interview:"Mission Interview",milestone_interview:"Milestone Interview",slice_interview:"Slice Interview"},iv="fusion:session-banner-dismissed";function eo(e){if(!e)return 0;const n=Date.parse(e);return Number.isFinite(n)?n:0}function IL(){if(typeof window>"u")return new Map;try{const e=window.localStorage.getItem(iv);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 TL(e){if(!(typeof window>"u"))try{const n={};for(const[s,a]of e)n[s]=a;window.localStorage.setItem(iv,JSON.stringify(n))}catch{}}const zi=IL();function $L({sessions:e,onResumeSession:n,onDismissSession:s,onDismissAll:a}){const[r,o]=i.useState(0),l=()=>{TL(zi),o(g=>g+1)};i.useEffect(()=>{if(zi.size===0)return;const g=new Map(e.map(w=>[w.id,w]));let x=!1;for(const[w,b]of zi){const y=g.get(w);if(!y)continue;if(!(y.status==="awaiting_input"||y.status==="error")){zi.delete(w),x=!0;continue}eo(y.updatedAt)>b&&(zi.delete(w),x=!0)}x&&l()},[e]);const c=i.useMemo(()=>e.filter(g=>{if(g.status!=="awaiting_input"&&g.status!=="error")return!1;const x=zi.get(g.id);return x===void 0?!0:eo(g.updatedAt)>x}),[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 m="";d>0&&u>0?m=`${d} AI session${d===1?"":"s"} need${d===1?"s":""} your input, ${u} failed`:d>0?m=`${d} AI session${d===1?"":"s"} need${d===1?"s":""} your input`:u>0&&(m=`${u} AI session${u===1?"":"s"} failed`);const h=g=>{zi.set(g.id,Math.max(eo(g.updatedAt),Date.now())),l()},f=g=>{zi.delete(g.id),l(),n(g)},p=()=>{const g=Date.now();for(const x of c)zi.set(x.id,Math.max(eo(x.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(Ps,{size:16,"aria-hidden":"true"}),t.jsx("span",{children:m})]}),t.jsxs("button",{className:"session-notification-banner__dismiss-all",onClick:p,children:[t.jsx(nn,{size:14,"aria-hidden":"true"}),t.jsx("span",{children:"Dismiss all"})]})]}),t.jsx("div",{className:"session-notification-banner__list",children:c.map(g=>{const x=PL[g.type],w=g.status==="error";return t.jsxs("article",{className:`session-notification-banner__item${w?" 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:[w?t.jsx(Ps,{size:16,className:"session-notification-banner__type-icon session-notification-banner__type-icon--error","aria-hidden":"true"}):t.jsx(x,{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:w?"Failed":RL[g.type]})]})]}),t.jsxs("div",{className:"session-notification-banner__actions",children:[t.jsx("button",{className:"session-notification-banner__resume",onClick:()=>f(g),children:w?"Retry":"Resume"}),t.jsx("button",{className:"session-notification-banner__dismiss",onClick:()=>{h(g),s(g.id)},"aria-label":`Dismiss ${g.title}`,children:t.jsx(nn,{size:14,"aria-hidden":"true"})})]})]},g.id)})})]})}const av="fusion:cli-binary-banner-dismissed";function DL(){if(typeof window>"u")return!1;try{return window.localStorage.getItem(av)==="1"}catch{return!1}}function LL(){if(!(typeof window>"u"))try{window.localStorage.setItem(av,"1")}catch{}}function OL({onOpenSettings:e}){const[n,s]=i.useState(null),[a,r]=i.useState(()=>DL()),[o,l]=i.useState(!1),[c,d]=i.useState(null);i.useEffect(()=>{if(a)return;let y=!1;return bj().then(S=>{y||s(S)}).catch(()=>{}),()=>{y=!0}},[a]);const u=i.useCallback(async()=>{l(!0),d(null);try{const y=await xj();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)}},[]),m=i.useCallback(()=>{LL(),r(!0)},[]);if(a||!n||n.state==="installed"||n.state==="skipped")return null;const h=n.state==="version-mismatch",f=n.binary.version,p=n.expectedVersion,g=h?"Update the Fusion CLI":"Install the Fusion CLI",x=h?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."]}),w=h?"Update with npm":"Install with npm",b=h?"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:x}),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:w}),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:m,children:t.jsx(nn,{size:16})})]})}function zL({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:"npm i -g @runfusion/fusion"})," to update. "," ",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(nn,{size:16,"aria-hidden":"true"})})]})}function FL({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(No,{"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(ya,{"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(nn,{"aria-hidden":"true"})})]})]})})}function UL({onResume:e}){const n=HD();if(!n)return null;const s=n.completedSteps.length,a=Zi.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(ps,{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:()=>{ei("onboarding:resumed",{source:"resume-card",resumedFromStep:n.currentStep}),e()},children:[t.jsx(Yn,{size:14,"aria-hidden":"true"}),t.jsx("span",{children:"Continue onboarding"})]})})]})}function BL({onOpenSettings:e,onOpenModelOnboarding:n}){const s=wr(),a=Zx(),[r,o]=i.useState(!0),[l,c]=i.useState(!1),[d,u]=i.useState(!1),[m,h]=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[S,k]=await Promise.all([uo(),Pa()]);if(b)return;const C=S.providers??[],v=C.find(R=>R.id==="github"),P=!C.some(R=>R.id!=="github"&&R.authenticated),U=!k.defaultProvider&&!k.defaultModelId,E=v?!v.authenticated:!1;h({needsAiProvider:P,needsDefaultModel:U,needsGitHub:E})}catch{b||c(!0)}finally{b||o(!1)}})(),()=>{b=!0}},[s,a]);const f=i.useCallback(()=>{UD(),u(!0)},[]),p=i.useCallback(()=>{n()},[n]),g=i.useCallback(()=>{e("global-models")},[e]),x=i.useCallback(()=>{e("authentication")},[e]),w=i.useMemo(()=>{const b=[];return m.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:Qn}),m.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:kg}),m.needsGitHub&&b.push({id:"github",title:"Connect GitHub",description:"Connect GitHub to import issues and track pull requests",actionLabel:"Connect GitHub",onAction:x,icon:Ws}),b},[m.needsAiProvider,m.needsDefaultModel,m.needsGitHub,x,g,p]);return!s||a||d||r||l||w.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(_i,{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:w.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(ta,{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(nn,{size:16,"aria-hidden":!0})})]})}function HL({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 pl(e){return e>99?"99+":String(e)}function qL({view:e,onChangeView:n,footerVisible:s,modalOpen:a=!1,keyboardOpen:r=!1,onOpenSettings:o,onOpenActivityLog:l,onOpenSystemStats:c,onOpenMailbox:d,mailboxUnreadCount:u=0,mailboxPendingApprovalCount:m=0,chatHasUnreadResponse:h=!1,onOpenGitManager:f,onOpenWorkflowSteps:p,onOpenSchedules:g,onOpenScripts:x,onToggleTerminal:w,onOpenFiles:b,onOpenTodos:y,todosOpen:S=!1,onOpenGitHubImport:k,onOpenPlanning:C,onResumePlanning:v,activePlanningSessionCount:j=0,onOpenUsage:P,onRunScript:U,projectId:E,onViewAllProjects:R,showSkillsTab:L,experimentalFeatures:F,onOpenNodes:M,pluginDashboardViews:O=[],shellConnectionControl:q}){const te=Ys(),[Z,K]=i.useState(!1),[A,I]=i.useState(!1),[$,N]=i.useState({}),[G,xe]=i.useState(!1),Se=i.useMemo(()=>Object.entries($).sort(([pe],[Ae])=>pe.localeCompare(Ae)),[$]);i.useEffect(()=>{if(!A)return;let pe=!1;return xe(!0),mo(E).then(Ae=>{pe||N(Ae)}).catch(()=>{pe||N({})}).finally(()=>{pe||xe(!1)}),()=>{pe=!0}},[A,E]);const je=i.useCallback(()=>K(!1),[]),se=i.useCallback(pe=>{je(),pe?.()},[je]);if(i.useEffect(()=>{if(!Z)return;const pe=Ae=>{Ae.key==="Escape"&&K(!1)};return document.addEventListener("keydown",pe),()=>document.removeEventListener("keydown",pe)},[Z]),te!=="mobile"||a||r)return null;const Ve=j>0&&v?v:C,ee=!!L,ce=!!F?.todoView,ne=ee,re=ee&&!ne,ye=O.filter(pe=>pe.view.placement==="primary").sort((pe,Ae)=>(pe.view.order??Number.MAX_SAFE_INTEGER)-(Ae.view.order??Number.MAX_SAFE_INTEGER)).slice(0,1),Ce=new Set(ye.map(pe=>`${pe.pluginId}:${pe.view.viewId}`)),H=O.filter(pe=>!Ce.has(`${pe.pluginId}:${pe.view.viewId}`)).sort((pe,Ae)=>(pe.view.order??Number.MAX_SAFE_INTEGER)-(Ae.view.order??Number.MAX_SAFE_INTEGER)),ke=e==="documents"||!!F?.evalsView&&e==="evals"||e==="research"||e==="insights"||e==="memory"||e==="devserver"||e==="dev-server"||S&&ce||e==="skills"&&!ne||e==="graph"||rr(e)&&!ye.some(pe=>no(pe.pluginId,pe.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(aa,{}),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($n,{}),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(vs,{}),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(Ui,{}),h&&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(Na,{}),m>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:pl(u)})]}),ne&&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(Qn,{}),t.jsx("span",{className:"mobile-nav-tab-label",children:"Skills"})]}),ye.map(pe=>{const Ae=no(pe.pluginId,pe.view.viewId),Oe=Ml(pe.view.icon);return t.jsxs("button",{type:"button",className:`mobile-nav-tab${e===Ae||e==="graph"&&pe.pluginId==="fusion-plugin-dependency-graph"&&pe.view.viewId==="graph"?" mobile-nav-tab--active":""}`,"data-testid":`mobile-nav-tab-plugin-${pe.pluginId}-${pe.view.viewId}`,role:"tab","aria-selected":e===Ae||e==="graph"&&pe.pluginId==="fusion-plugin-dependency-graph"&&pe.view.viewId==="graph",onClick:()=>n(pe.pluginId==="fusion-plugin-dependency-graph"&&pe.view.viewId==="graph"?"graph":Ae),children:[t.jsx(Oe,{}),t.jsx("span",{className:"mobile-nav-tab-label",children:pe.view.label})]},`${pe.pluginId}:${pe.view.viewId}`)}),t.jsxs("button",{type:"button",className:`mobile-nav-tab${ke?" mobile-nav-tab--active":""}`,"data-testid":"mobile-nav-tab-more",role:"tab","aria-selected":!1,onClick:()=>K(pe=>!pe),children:[t.jsx(Ed,{}),t.jsx("span",{className:"mobile-nav-tab-label",children:"More"})]})]}),Z&&t.jsxs(t.Fragment,{children:[t.jsx("div",{className:"mobile-more-sheet-backdrop",onClick:je}),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"}),q?t.jsx("div",{className:"mobile-more-shell-connection","data-testid":"mobile-more-shell-connection",children:q}):null,t.jsxs("button",{type:"button",className:"mobile-more-item","data-testid":"mobile-more-item-mailbox",onClick:()=>se(d),children:[t.jsx(Na,{}),t.jsx("span",{children:"Mailbox"}),u>0&&t.jsx("span",{className:"mobile-more-item-badge mobile-more-item-badge--unread",children:pl(u)}),m>0&&t.jsx("span",{className:"mobile-more-item-badge",children:pl(m)})]}),t.jsxs("button",{type:"button",className:"mobile-more-item","data-testid":"mobile-more-item-activity",onClick:()=>se(l),children:[t.jsx(Ks,{}),t.jsx("span",{children:"Activity Log"})]}),t.jsxs("button",{type:"button",className:"mobile-more-item","data-testid":"mobile-more-item-system-stats",onClick:()=>se(c),children:[t.jsx(dr,{}),t.jsx("span",{children:"System Stats"})]}),t.jsxs("button",{type:"button",className:"mobile-more-item","data-testid":"mobile-more-item-git",onClick:()=>se(f),children:[t.jsx(Us,{}),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:()=>se(w),children:[t.jsx(Bi,{}),t.jsx("span",{children:"Terminal"})]}),t.jsx("button",{type:"button",className:"mobile-more-split-toggle","data-testid":"mobile-more-terminal-split-toggle",onClick:()=>I(pe=>!pe),"aria-expanded":A,"aria-haspopup":"menu","aria-label":"Show scripts",children:t.jsx(Mn,{size:14,className:`mobile-more-chevron${A?" mobile-more-chevron--open":""}`})})]}),A&&t.jsx("div",{className:"mobile-more-submenu",role:"menu","aria-label":"Scripts submenu",children:G?t.jsxs("div",{className:"mobile-more-submenu-loading","data-testid":"mobile-more-scripts-loading",children:[t.jsx(bt,{className:"animate-spin"}),t.jsx("span",{children:"Loading scripts…"})]}):Se.length>0?t.jsxs(t.Fragment,{children:[Se.map(([pe,Ae])=>t.jsxs("button",{type:"button",className:"mobile-more-item mobile-more-subitem","data-testid":`mobile-more-script-item-${pe}`,onClick:()=>{U&&U(pe,Ae),je(),I(!1)},children:[t.jsx(Yn,{}),t.jsx("span",{children:pe})]},pe)),x&&t.jsxs("button",{type:"button",className:"mobile-more-item mobile-more-subitem mobile-more-subitem--manage","data-testid":"mobile-more-scripts-manage",onClick:()=>{je(),I(!1),x()},children:[t.jsx(hi,{}),t.jsx("span",{children:"Manage Scripts…"})]})]}):x&&t.jsxs("button",{type:"button",className:"mobile-more-item mobile-more-subitem","data-testid":"mobile-more-scripts-manage",onClick:()=>{je(),I(!1),x()},children:[t.jsx(hi,{}),t.jsx("span",{children:"No scripts — add one…"})]})}),t.jsxs("button",{type:"button",className:"mobile-more-item","data-testid":"mobile-more-item-files",onClick:()=>se(b),children:[t.jsx(bs,{}),t.jsx("span",{children:"Files"})]}),t.jsxs("button",{type:"button",className:"mobile-more-item","data-testid":"mobile-more-item-planning",onClick:()=>se(Ve),children:[t.jsx(_i,{}),t.jsx("span",{children:"Planning"}),j>0&&t.jsx("span",{className:"mobile-more-item-badge",children:pl(j)})]}),t.jsxs("button",{type:"button",className:"mobile-more-item","data-testid":"mobile-more-item-workflow",onClick:()=>se(p),children:[t.jsx(Sl,{}),t.jsx("span",{children:"Workflow Steps"})]}),t.jsxs("button",{type:"button",className:"mobile-more-item","data-testid":"mobile-more-item-schedules",onClick:()=>se(g),children:[t.jsx(Hi,{}),t.jsx("span",{children:"Automation"})]}),t.jsxs("button",{type:"button",className:"mobile-more-item","data-testid":"mobile-more-item-github",onClick:()=>se(k),children:[t.jsx(HL,{}),t.jsx("span",{children:"Import from GitHub"})]}),t.jsxs("button",{type:"button",className:"mobile-more-item","data-testid":"mobile-more-item-usage",onClick:()=>se(P),children:[t.jsx(Ks,{}),t.jsx("span",{children:"Usage"})]}),t.jsxs("button",{type:"button",className:"mobile-more-item","data-testid":"mobile-more-item-projects",onClick:()=>se(R),children:[t.jsx(Gl,{}),t.jsx("span",{children:"Projects"})]}),t.jsxs("button",{type:"button",className:"mobile-more-item","data-testid":"mobile-more-item-documents",onClick:()=>se(()=>n("documents")),children:[t.jsx(ia,{}),t.jsx("span",{children:"Documents"})]}),F?.evalsView&&t.jsxs("button",{type:"button",className:"mobile-more-item","data-testid":"mobile-more-item-evals",onClick:()=>se(()=>n("evals")),children:[t.jsx(vs,{}),t.jsx("span",{children:"Evals"})]}),re&&t.jsxs("button",{type:"button",className:"mobile-more-item","data-testid":"mobile-more-item-skills",onClick:()=>se(()=>n("skills")),children:[t.jsx(Qn,{}),t.jsx("span",{children:"Skills"})]}),F?.researchView&&t.jsxs("button",{type:"button",className:"mobile-more-item","data-testid":"mobile-more-item-research",onClick:()=>se(()=>n("research")),children:[t.jsx(Fi,{}),t.jsx("span",{children:"Research"})]}),F?.insights&&t.jsxs("button",{type:"button",className:"mobile-more-item","data-testid":"mobile-more-item-insights",onClick:()=>se(()=>n("insights")),children:[t.jsx(ps,{}),t.jsx("span",{children:"Insights"})]}),F?.memoryView&&t.jsxs("button",{type:"button",className:"mobile-more-item","data-testid":"mobile-more-item-memory",onClick:()=>se(()=>n("memory")),children:[t.jsx(oo,{}),t.jsx("span",{children:"Memory"})]}),F?.devServerView&&t.jsxs("button",{type:"button",className:"mobile-more-item","data-testid":"mobile-more-item-dev-server",onClick:()=>{se(()=>n("dev-server"))},children:[t.jsx(dr,{}),t.jsx("span",{children:"Dev Server"})]}),F?.nodesView&&M&&t.jsxs("button",{type:"button",className:"mobile-more-item","data-testid":"mobile-more-item-nodes",onClick:()=>se(M),children:[t.jsx(Aw,{}),t.jsx("span",{children:"Nodes"})]}),ce&&t.jsxs("button",{type:"button",className:"mobile-more-item","data-testid":"mobile-more-item-todos",onClick:()=>se(()=>y?.()),children:[t.jsx(hu,{}),t.jsx("span",{children:"Todos"})]}),H.map(pe=>{const Ae=no(pe.pluginId,pe.view.viewId),Oe=Ml(pe.view.icon);return t.jsxs("button",{type:"button",className:"mobile-more-item","data-testid":`mobile-more-item-plugin-${pe.pluginId}-${pe.view.viewId}`,onClick:()=>se(()=>n(pe.pluginId==="fusion-plugin-dependency-graph"&&pe.view.viewId==="graph"?"graph":Ae)),children:[t.jsx(Oe,{}),t.jsx("span",{children:pe.view.label})]},`${pe.pluginId}:${pe.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:()=>se(o),children:[t.jsx(to,{}),t.jsx("span",{children:"Settings"})]})]})]})]})}function Lf(e){return e.trim().toLowerCase().replace(/[\s-]+/g,"_").replace(/_+/g,"_")}function rv(e,n){const s=n.trim();if(!s)return!0;const a=Lf(s);return Lf(e).includes(a)||e.toLowerCase().includes(s.toLowerCase())}function VL({agents:e,filter:n,highlightedIndex:s,visible:a,onSelect:r,position:o="below"}){const l=i.useMemo(()=>e.filter(c=>rv(c.name,n)),[e,n]);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:l.length===0?t.jsx("div",{className:"agent-mention-empty",children:"No agents found"}):l.map((c,d)=>t.jsxs("button",{type:"button",className:`agent-mention-item${d===s?" agent-mention-item--highlighted":""}`,"data-testid":`agent-mention-item-${c.id}`,onMouseDown:u=>u.preventDefault(),onClick:()=>r(c),role:"option","aria-selected":d===s,children:[t.jsx(iu,{agent:c,size:20}),t.jsx("span",{className:"agent-mention-name",children:c.name}),t.jsx("span",{className:"agent-mention-role",children:c.role})]},c.id))}):null}function Of(e){const{sessionId:n,tempUserMessageId:s,setStreamingText:a,setStreamingThinking:r,setStreamingToolCalls:o,cancelStreamingFlushesRef:l,addToast:c,onDone:d,onError:u,onFallbackSession:m}=e;let h="",f="",p=[],g,x=null,w=null;const b=()=>{x=null,a(h)},y=()=>{w=null,r(f)},S=()=>{x!==null&&(cancelAnimationFrame(x),x=null),w!==null&&(cancelAnimationFrame(w),w=null)};return l.current=S,{handlers:{onThinking:C=>{f+=C,w===null&&(w=requestAnimationFrame(y))},onText:C=>{h+=C,x===null&&(x=requestAnimationFrame(b))},onToolStart:C=>{p=[...p,{toolName:C.toolName,args:C.args,isError:!1,status:"running"}],o(p)},onToolEnd:C=>{const v=[...p];for(let j=v.length-1;j>=0;j--){const P=v[j];if(P?.toolName===C.toolName&&P.status==="running"){v[j]={...P,status:"completed",isError:C.isError,result:C.result},p=v,o(v);return}}p=[...v,{toolName:C.toolName,isError:C.isError,result:C.result,status:"completed"}],o(p)},onFallback:C=>{g=C,m?.(C,n),c?.(`Primary model unavailable. Switched to fallback ${C.fallbackModel}.`,"warning")},onDone:C=>{S(),d({messageId:C.messageId,message:C.message,accumulated:{text:h,thinking:f,toolCalls:p,fallbackInfo:g}})},onError:C=>{S(),u(C,s)}},cancelFlushes:S}}const WL=["load failed","failed to fetch","networkerror when attempting to fetch resource.","connection aborted","connection closed unexpectedly","network error"];function KL(e){const n=e.trim().toLowerCase();return n?WL.some(s=>n.includes(s)):!1}function GL(){const e=i.useRef(null),n=i.useRef(null);i.useEffect(()=>{if(typeof document>"u")return;const r=()=>{const o=Date.now();if(document.visibilityState==="hidden"){e.current=o;return}document.visibilityState==="visible"&&(n.current=o)};return r(),document.addEventListener("visibilitychange",r),()=>document.removeEventListener("visibilitychange",r)},[]);const s=i.useCallback(()=>typeof document<"u"&&document.visibilityState==="hidden",[]),a=i.useCallback((r=5e3)=>{const o=e.current;if(o===null)return!1;const l=Date.now();if(s())return l-o<=r;const c=n.current;return c===null||c<o?!1:l-c<=r},[s]);return i.useMemo(()=>({isHiddenNow:s,wasRecentlyHidden:a}),[s,a])}const ar="__fn_agent__";function ov(e,n){const s=typeof e=="string"?e.trim():"",a=typeof n=="string"?n.trim():"";return!s||!a?{}:{modelProvider:s,modelId:a}}function fl(e,n,s){const a=typeof e=="string"?e.trim():"",r=ov(n,s),o=a||(r.modelProvider&&r.modelId?ar:"");return o?{agentId:o,...r}:null}function gl(e,n,s){const a=ov(n,s),r=a.modelProvider??"",o=a.modelId??"";return`${e}::${r}/${o}`}function zf(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 JL(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 YL(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 er(e){return{id:e.id,sessionId:e.sessionId,role:e.role,content:e.content,thinkingOutput:e.thinkingOutput,toolCalls:JL(e.metadata),fallbackInfo:YL(e.metadata),createdAt:e.createdAt}}function QL(e,n){const[s,a]=i.useState(null),[r,o]=i.useState([]),[l,c]=i.useState(!1),[d,u]=i.useState([]),[m,h]=i.useState(!1),[f,p]=i.useState(!1),[g,x]=i.useState(""),[w,b]=i.useState(""),[y,S]=i.useState([]),[k,C]=i.useState(""),v=i.useRef(null),j=i.useRef(!1),P=i.useRef(null),U=i.useRef(""),E=i.useRef(f);E.current=f;const R=i.useRef(null),L=i.useRef(""),F=i.useRef(null),M=i.useRef(s);M.current=s;const O=i.useRef(0),q=3,te=i.useRef(!1);i.useEffect(()=>{U.current=k},[k]);const Z=i.useCallback(async()=>{c(!0);try{const J=await Mm(e);o(J.sessions)}catch(J){console.error("[useQuickChat] Failed to refresh sessions:",J)}finally{c(!1)}},[e]),K=i.useCallback(async J=>{const B={agentId:J.agentId};return J.modelProvider&&J.modelId&&(B.modelProvider=J.modelProvider,B.modelId=J.modelId),(await W1(B,e)).session},[e]),A=i.useCallback(J=>{if(v.current||!J)return!0;j.current=!1,p(!0);const{handlers:B}=Of({sessionId:J,tempUserMessageId:"",setStreamingText:x,setStreamingThinking:b,setStreamingToolCalls:S,cancelStreamingFlushesRef:P,addToast:n,onFallbackSession:(ye,Ce)=>{const H=zf(ye.fallbackModel);o(ke=>ke.map(pe=>pe.id===Ce?{...pe,...H}:pe)),a(ke=>ke&&ke.id===Ce?{...ke,...H}:ke)},onDone:()=>{x(""),b(""),S([]),p(!1),E.current=!1,v.current=null,Pr(J,{limit:50},e).then(ye=>{u(ye.messages.map(er))}).catch(()=>{})},onError:ye=>{x(""),b(""),S([]),p(!1),E.current=!1,v.current=null;const Ce=typeof ye=="string"&&ye.trim()?ye:"Failed to get response";n?.(Ce,"error"),Pr(J,{limit:50},e).then(H=>{u(H.messages.map(er))}).catch(()=>{})}});return v.current=Y1(J,B,e),!0},[n,e]),I=i.useCallback(async(J,B,ye)=>{const Ce=fl(J,B,ye);if(!Ce)return;const H=gl(Ce.agentId,Ce.modelProvider,Ce.modelId);c(!0);try{const{session:ke}=await V1({agentId:Ce.agentId,modelProvider:Ce.modelProvider,modelId:Ce.modelId},e);if(ke)a(ke),L.current=H,ke.isGenerating&&(x(""),A(ke.id));else{const pe=await K(Ce);a(pe),L.current=H}O.current=0}catch(ke){console.error("[useQuickChat] Failed to initialize session:",ke),O.current+=1,O.current<=q&&n?.("Failed to initialize chat","error")}finally{c(!1)}},[A,e,n,K]),$=i.useCallback(async()=>{if(s){h(!0);try{const J=await Pr(s.id,{limit:50},e);u(J.messages.map(er))}catch(J){console.error("[useQuickChat] Failed to load messages:",J)}finally{h(!1)}}},[s,e]);i.useEffect(()=>{s?$():u([])},[s,$]),i.useEffect(()=>{if(!s?.isGenerating||(v.current||A(s.id),!E.current||v.current||!s))return;const J=setInterval(async()=>{if(!E.current||v.current||!s){clearInterval(J);return}try{if(!(await K1(s.id,e)).session.isGenerating){clearInterval(J);const ye=await Pr(s.id,{limit:50},e);u(ye.messages.map(er)),x(""),b(""),S([]),p(!1)}}catch{}},3e3);return()=>clearInterval(J)},[s,A,e]);const N=i.useCallback(async()=>{if(s){h(!0);try{const J=await Pr(s.id,{limit:50},e);u(J.messages.map(er))}catch(J){console.error("[useQuickChat] Failed to reload messages:",J)}finally{h(!1)}}},[s,e]),G=i.useCallback(()=>{P.current?.(),P.current=null,U.current="",C(""),x(""),b(""),S([]),p(!1)},[]),xe=i.useCallback(async(J,B,ye)=>{const Ce=fl(J,B,ye);if(!Ce)return;const H=gl(Ce.agentId,Ce.modelProvider,Ce.modelId);F.current=Ce;const ke=H===L.current&&M.current;if(ke||(v.current&&(v.current.close(),v.current=null),G()),ke){await N();return}a(null),u([]),L.current=H,await I(Ce.agentId,Ce.modelProvider,Ce.modelId)},[I,N,G]),Se=i.useCallback(async J=>{const B=fl(J.agentId,J.modelProvider??void 0,J.modelId??void 0);B&&(F.current=B,L.current=gl(B.agentId,B.modelProvider,B.modelId),v.current&&(v.current.close(),v.current=null),G(),a(J),J.isGenerating&&(x(""),A(J.id)))},[A,G]),je=i.useCallback(async(J,B)=>{await xe(ar,J,B)},[xe]),se=i.useCallback(async(J,B,ye)=>{const H=fl(J??"",B,ye)??F.current;if(!H)return;F.current=H;const ke=gl(H.agentId,H.modelProvider,H.modelId);te.current=!0,O.current=0,v.current&&(v.current.close(),v.current=null),G(),u([]),a(null),c(!0);try{const pe=await K(H);a(pe),L.current=ke;const Ae=await Mm(e);o(Ae.sessions)}catch(pe){console.error("[useQuickChat] Failed to start a fresh session:",pe),n?.("Failed to start a new chat","error")}finally{te.current=!1,c(!1)}},[n,K,e,G]),Ve=i.useCallback(()=>{s&&(j.current=!0,P.current?.(),P.current=null,v.current?.close(),v.current=null,G1(s.id,e).catch(()=>{}),p(!1),x(""),b(""),S([]))},[s,e]),ee=i.useCallback(()=>{U.current="",C("")},[]),ce=i.useRef(()=>Promise.resolve()),ne=GL(),re=i.useCallback((J,B)=>{if(!s||!J.trim()&&(!B||B.length===0))return Promise.resolve();if(E.current)return B&&B.length>0?Promise.reject(new Error("Cannot send attachments while a response is streaming")):(U.current=J,C(J),n?.("Still waiting for previous response — message queued","warning"),Promise.resolve());const ye=new Promise((Ce,H)=>{R.current={resolve:Ce,reject:H},j.current=!1,v.current&&(v.current.close(),v.current=null);const ke=`temp-${Date.now()}`,pe={id:ke,sessionId:s.id,role:"user",content:J,createdAt:new Date().toISOString()};u(Oe=>[...Oe,pe]),x(""),b(""),S([]),p(!0);const{handlers:Ae}=Of({sessionId:s.id,tempUserMessageId:ke,setStreamingText:x,setStreamingThinking:b,setStreamingToolCalls:S,cancelStreamingFlushesRef:P,addToast:n,onFallbackSession:(Oe,He)=>{const dt=zf(Oe.fallbackModel);o(Fe=>Fe.map(fe=>fe.id===He?{...fe,...dt}:fe)),a(Fe=>Fe&&Fe.id===He?{...Fe,...dt}:Fe)},onDone:({messageId:Oe,message:He,accumulated:dt})=>{const Fe=He?er(He):{id:Oe||`msg-${Date.now()}`,sessionId:s.id,role:"assistant",content:dt.text,thinkingOutput:dt.thinking||void 0,toolCalls:dt.toolCalls.length>0?dt.toolCalls:void 0,fallbackInfo:dt.fallbackInfo,createdAt:new Date().toISOString()};u($e=>[...$e,Fe]),x(""),b(""),S([]),p(!1),E.current=!1,v.current=null,R.current?.resolve(),R.current=null;const fe=U.current.trim();fe&&(U.current="",C(""),ce.current(fe))},onError:Oe=>{x(""),b(""),S([]),p(!1),E.current=!1,v.current=null,console.error("[useQuickChat] Stream error:",Oe);const He=typeof Oe=="string"&&Oe.trim()?Oe:"Failed to get response";if(typeof Oe=="string"&&KL(Oe)&&(ne.isHiddenNow()||ne.wasRecentlyHidden(5e3))?(console.info("[useQuickChat] Suppressed tab-suspension stream error:",Oe),R.current?.resolve()):(n?.(He,"error"),R.current?.reject(new Error(He))),R.current=null,!j.current){const Fe=U.current.trim();Fe&&(U.current="",C(""),ce.current(Fe))}N()}});v.current=J1(s.id,J,Ae,B,e)});return ye.catch(()=>{}),ye},[s,e,n,N,ne]);return ce.current=re,i.useEffect(()=>()=>{v.current&&(v.current.close(),v.current=null)},[]),i.useMemo(()=>({activeSession:s,sessions:r,sessionsLoading:l,messages:d,messagesLoading:m,isStreaming:f,streamingText:g,streamingThinking:w,streamingToolCalls:y,pendingMessage:k,sendMessage:re,stopStreaming:Ve,clearPendingMessage:ee,switchSession:xe,selectSession:Se,startModelChat:je,startFreshSession:se,refreshSessions:Z,loadMessages:$,reloadMessages:N,skipNextSessionInitRef:te}),[s,r,l,d,m,f,g,w,y,k,re,Ve,ee,xe,Se,je,se,Z,$,N])}function XL(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,x=g&&g!=="all"?{state:g}:void 0,w=n?.showSystemAgents??!1,b=await Nr({...x,...p,includeEphemeral:p?.includeEphemeral??w},e),y=Array.from(new Map(b.map(S=>[S.id,S])).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 uS(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 ii(`/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 m=i.useCallback(async()=>{await Promise.all([d(),u()])},[d,u]),h=n?.showSystemAgents??!1,f=s.filter(p=>p.state!=="active"&&p.state!=="running"?!1:h||!q0(p));return{agents:s,activeAgents:f,stats:r,isLoading:l,loadAgents:d,loadStats:u,refreshAgents:m}}function ZL({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=N0(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(yg,{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 eO=200;function tO(e={}){const{projectId:n,workspace:s="project"}=e,[a,r]=i.useState(!1),[o,l]=i.useState(""),[c,d]=i.useState(-1),[u,m]=i.useState([]),[h,f]=i.useState(!1),[p,g]=i.useState(0),x=i.useRef(null),w=i.useRef(null);i.useEffect(()=>()=>{x.current&&clearTimeout(x.current),w.current?.abort()},[]);const b=i.useCallback((v,j)=>{if(j<0||j>v.length){r(!1);return}const P=U=>/[a-zA-Z0-9/_.-]/.test(U);for(let U=j-1;U>=0;U--){if(v[U]==="#")if(U===0){const E=v.slice(U+1,j);d(U),l(E),g(0),r(!0);return}else{const E=v[U-1];if(/[\s,.;:!?'"()[\]{}]/.test(E)){const R=v.slice(U+1,j);d(U),l(R),g(0),r(!0);return}r(!1);return}if(!P(v[U])){r(!1);return}}r(!1)},[]),y=i.useCallback(()=>{r(!1),l(""),d(-1),m([]),g(0),f(!1)},[]),S=i.useCallback(async v=>{if(!v.trim()){m([]),f(!1);return}w.current?.abort(),w.current=new AbortController;try{f(!0);const j=await gN(v,s,n);m(j.files),g(0)}catch(j){j.name!=="AbortError"&&m([])}finally{f(!1)}},[s,n]);i.useEffect(()=>{if(a)return x.current&&clearTimeout(x.current),x.current=setTimeout(()=>{S(o)},eO),()=>{x.current&&clearTimeout(x.current)}},[o,a,S]);const k=i.useCallback((v,j)=>{if(!a||c<0)return j;const P=j.slice(0,c),U=j.slice(c+1),E=U.match(/[\s]|$/),R=E?E.index:U.length,L=U.slice(R);return`${P}#${v.path}${L}`},[a,c]),C=i.useCallback((v,j)=>{if(!a||u.length===0)return!1;switch(v.key){case"ArrowDown":return v.preventDefault(),g(P=>Math.min(P+1,u.length-1)),!0;case"ArrowUp":return v.preventDefault(),g(P=>Math.max(P-1,0)),!0;case"Enter":case"Tab":return u[p]?(v.preventDefault(),!0):!1;case"Escape":return v.preventDefault(),y(),!0;default:return!1}},[a,u,p,y]);return{mentionActive:a,files:u,loading:h,mentionQuery:o,selectedIndex:p,setSelectedIndex:g,detectMention:b,selectFile:k,dismissMention:y,handleKeyDown:C}}function nO(e){return`${e.name?.trim()||e.id} (${e.role})`}function qr(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 sO(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 iO(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 aO(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 lv(e,n=!1){if(!e||e.length===0)return null;const s=(f,p)=>{const g=f.status==="running",x=f.status==="completed"&&f.isError,w=iO(f.args),b=aO(f.result),y=g?w:b?`result: ${b}`:w?`args: ${w}`:null,S=n?null:y,k=g?"running":x?"error":"completed";return t.jsxs("details",{className:`chat-tool-call${g?" chat-tool-call--running":""}${x?" 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}),S&&t.jsx("span",{className:"chat-tool-call-preview",title:S,children:S}),t.jsx("span",{className:"chat-tool-call-status-text",children:k})]}),t.jsxs("div",{className:"chat-tool-call-content",children:[w&&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:w})]}),b&&t.jsxs("div",{className:`chat-tool-call-row${x?" 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(nm,{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),m=u>0?`${d.join(", ")}, +${u} more`:d.join(", "),h=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(nm,{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:m,children:m}),h&&t.jsx("span",{className:"chat-tool-calls-group-status",children:h})]}),e.map((f,p)=>s(f,p))]})})}const cv={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 Ff(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 rO(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 bl={width:320,height:400},oO=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"]),lO=[".png",".jpg",".jpeg",".gif",".webp",".txt",".json",".yaml",".yml",".log",".csv",".xml",".md"];function cO(e){return e.type.startsWith("image/")}function dO(e){if(oO.has(e.type))return!0;const n=e.name.toLowerCase();return lO.some(s=>n.endsWith(s))}const tr={width:280,height:260},Ms=768,nr=8;function uO(e,n){const s=i.useCallback(()=>{if(typeof window>"u")return 0;const k=getComputedStyle(document.documentElement).getPropertyValue("--executor-footer-height").trim();return k&&parseFloat(k)||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 k=`fusion-quick-chat-position-${e||"default"}`;try{const C=localStorage.getItem(k);if(C){const v=JSON.parse(C);if(typeof v.x=="number"&&typeof v.y=="number"&&!isNaN(v.x)&&!isNaN(v.y))return v}}catch{}return a()}),[l,c]=i.useState(!1),d=i.useRef(null),u=i.useRef(r),m=i.useRef(null),h=i.useRef(null),f=n??i.useRef(!1);i.useEffect(()=>{u.current=r},[r]);const p=i.useCallback(k=>{if(typeof window>"u")return k;const C=48,v=window.innerWidth<=768?4:8,j=window.innerWidth<=768?44:0,P=window.innerWidth>768?s():0,U=window.innerWidth-C-v,E=window.innerHeight-C-v-j-P;return{x:Math.max(v,Math.min(U,k.x)),y:Math.max(v,Math.min(E,k.y))}},[s]),g=i.useCallback(k=>{if(typeof window>"u")return;const C=`fusion-quick-chat-position-${e||"default"}`;try{localStorage.setItem(C,JSON.stringify(k))}catch{}},[e]),x=i.useCallback(()=>{if(!d.current)return;const k=h.current,C=m.current;k&&C!==null&&typeof k.releasePointerCapture=="function"&&k.releasePointerCapture(C),d.current=null,m.current=null,h.current=null,c(!1),document.body.style.userSelect="",f.current&&g(u.current),document.removeEventListener("pointermove",w),document.removeEventListener("pointerup",b),document.removeEventListener("pointercancel",y)},[g]),w=i.useCallback(k=>{if(!d.current||m.current!==null&&k.pointerId!==m.current)return;const C=k.clientX-d.current.pointerX,v=k.clientY-d.current.pointerY;if((Math.abs(C)>=5||Math.abs(v)>=5)&&(f.current=!0),!f.current)return;const j=d.current.x-C,P=d.current.y-v,U=p({x:j,y:P});u.current=U,o(U)},[p]),b=i.useCallback(k=>{m.current!==null&&k.pointerId!==m.current||x()},[x]),y=i.useCallback(k=>{m.current!==null&&k.pointerId!==m.current||x()},[x]),S=i.useCallback(k=>{if(k.button!==0&&k.pointerType==="mouse")return;const C=k.currentTarget;k.preventDefault(),typeof C.setPointerCapture=="function"&&C.setPointerCapture(k.pointerId);const v=u.current;d.current={x:v.x,y:v.y,pointerX:k.clientX,pointerY:k.clientY},m.current=k.pointerId,h.current=C,f.current=!1,c(!0),document.body.style.userSelect="none",document.addEventListener("pointermove",w,{passive:!0}),document.addEventListener("pointerup",b),document.addEventListener("pointercancel",y)},[y,w,b]);return i.useEffect(()=>()=>{document.removeEventListener("pointermove",w),document.removeEventListener("pointerup",b),document.removeEventListener("pointercancel",y),document.body.style.userSelect=""},[y,w,b]),{position:r,isDragging:l,handlePointerDown:S}}function mO(e,n,s){const a=`fusion:quick-chat-size-${e||"default"}`,r=i.useCallback(()=>typeof window<"u"&&window.innerWidth>Ms,[]),o=i.useCallback((f,p,g)=>{if(typeof window>"u")return f;const x=Math.max(tr.width,window.innerWidth-p-nr),w=Math.max(tr.height,window.innerHeight-g-nr);return{width:Math.max(tr.width,Math.min(x,f.width)),height:Math.max(tr.height,Math.min(w,f.height))}},[]),l=i.useCallback(()=>{if(typeof window>"u"||window.innerWidth<=Ms)return bl;try{const f=localStorage.getItem(a);if(!f)return bl;const p=JSON.parse(f);return typeof p.width!="number"||typeof p.height!="number"?bl:{width:p.width,height:p.height}}catch{return bl}},[a]),[c,d]=i.useState(l),[u,m]=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 h=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 x={pointerX:f.clientX,pointerY:f.clientY,width:c.width,height:c.height,anchorRight:u.right,anchorBottom:u.bottom};document.body.style.userSelect="none";const w=y=>{const S=y.clientX-x.pointerX,k=y.clientY-x.pointerY;let C=x.width,v=x.height,j=x.anchorRight,P=x.anchorBottom;if(p.includes("w")&&(C=x.width-S),p.includes("e")){const M=S;C=x.width+M,j=x.anchorRight-M}if(p.includes("n")&&(v=x.height-k),p.includes("s")){const M=k;v=x.height+M,P=x.anchorBottom-M}const U=n+j,E=s+P,R=o({width:C,height:v},U,E),L=Math.max(nr-n,Math.min(window.innerWidth-n-tr.width-nr,j)),F=Math.max(nr-s,Math.min(window.innerHeight-s-tr.height-nr,P));d(R),m({right:L,bottom:F})},b=y=>{typeof g.releasePointerCapture=="function"&&g.releasePointerCapture(y.pointerId),document.body.style.userSelect="",document.removeEventListener("pointermove",w),document.removeEventListener("pointerup",b);try{localStorage.setItem(a,JSON.stringify({width:c.width,height:c.height}))}catch{}};document.addEventListener("pointermove",w),document.addEventListener("pointerup",b)},[u.bottom,u.right,o,s,n,r,c.height,c.width,a]);return{panelSize:c,anchorOffset:u,handleResizeStart:h}}const Uf=i.memo(function({message:n,forcePlain:s,mentionAgentsByName:a,onToggleRender:r}){const o=n.role==="user",l=i.useMemo(()=>{if(!o)return null;const d=n.content,u=/@([\w-]+)/g,m=[];let h=0,f=u.exec(d);for(;f;){const[p,g=""]=f,x=f.index;x>h&&m.push(d.slice(h,x));const w=g.replace(/_/g," ").toLowerCase(),b=a.get(w);b?m.push(t.jsxs("span",{className:"chat-mention-chip",children:["@",b.name.replace(/\s+/g,"_")]},`${b.id}-${x}`)):m.push(p),h=x+p.length,f=u.exec(d)}return h<d.length&&m.push(d.slice(h)),m.length===0?d:m},[o,n.content,a]),c=i.useMemo(()=>o?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(bi,{remarkPlugins:[xi],components:cv,children:n.content})}),[o,s,n.content]);return t.jsxs("div",{className:`quick-chat-panel-message ${o?"quick-chat-panel-message--sent":"quick-chat-panel-message--received"}`,"data-testid":`quick-chat-message-${n.id}`,children:[o?t.jsx("p",{children:l}):t.jsxs(t.Fragment,{children:[c,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:()=>r(n.id),children:s?t.jsx(mu,{size:14}):t.jsx(kr,{size:14})})]}),lv(n.toolCalls,!0)]})});function hO({projectId:e,addToast:n,showFAB:s=!0,open:a,onOpenChange:r,favoriteProviders:o=[],favoriteModels:l=[],onToggleFavorite:c,onToggleModelFavorite:d}){const{agents:u}=XL(e),[m,h]=i.useState(!1),f=a!==void 0,p=f?a:m,g=f?D=>{r?.(typeof D=="function"?D(p):D)}:h;Wi({enabled:p});const x=Ys(),[w,b]=i.useState("agent"),[y,S]=i.useState(""),[k,C]=i.useState(!1),[v,j]=i.useState("model"),[P,U]=i.useState(""),[E,R]=i.useState(""),[L,F]=i.useState([]),[M,O]=i.useState(!1),[q,te]=i.useState(""),[Z,K]=i.useState(""),[A,I]=i.useState(""),[$,N]=i.useState([]),[G,xe]=i.useState(!1),[Se,je]=i.useState(!1),[se,Ve]=i.useState(""),[ee,ce]=i.useState(0),[ne,re]=i.useState(""),[J,B]=i.useState(!1),[ye,Ce]=i.useState(0),[H,ke]=i.useState(-1),[pe,Ae]=i.useState(()=>new Set),[Oe,He]=i.useState(!1),[dt,Fe]=i.useState([]),[fe,$e]=i.useState(!1),[De,ot]=i.useState(!1),[,Be]=i.useState(!1),[we,Q]=i.useState({top:0,left:0}),_e=tO({projectId:e}),lt=i.useCallback(D=>{if(!D||!_e.mentionActive)return;const Y=D.getBoundingClientRect();Q({top:Y.top-260,left:Y.left+8})},[_e.mentionActive]),ht=i.useRef(!1),mt=i.useRef(!1),xt=i.useRef(""),Ie=i.useRef(0),Ue=i.useRef(null),pt=i.useRef(null),oe=i.useRef(0),{position:le,isDragging:ge,handlePointerDown:Ne}=uO(e,ht),ue=le.y+60,{panelSize:qe,anchorOffset:me,handleResizeStart:tt}=mO(e,le.x,ue),Ct=typeof window<"u"&&window.innerWidth>Ms,{activeSession:wt,messages:$t,isStreaming:Vt,streamingText:Mt,streamingThinking:Dt,streamingToolCalls:Qt,sessions:Kt,sessionsLoading:Bt,messagesLoading:on,sendMessage:fn,stopStreaming:Jt,pendingMessage:an,clearPendingMessage:zt,switchSession:en,selectSession:Zt,startModelChat:dn,startFreshSession:ve,refreshSessions:ze,skipNextSessionInitRef:We}=QL(e,n),Ze=i.useRef(null),Ye=i.useRef(null),It=i.useRef(null),St=i.useRef(null),Ht=i.useRef(null),jt=i.useRef([]),ae=i.useRef(!1),Le=i.useRef(!1),At=i.useRef(!1),Lt=i.useRef(null),Ft=i.useRef(!1),Me=i.useRef(!1),ct=i.useRef({isOpen:!1,sessionId:null});i.useEffect(()=>{if(!p||typeof window>"u"||typeof document>"u"||window.innerWidth>Ms)return;const D=window.scrollY,Y=document.documentElement,Ee=document.body,Ge={htmlOverflow:Y.style.overflow,bodyOverflow:Ee.style.overflow};return window.scrollTo(0,0),Y.style.overflow="hidden",Ee.style.overflow="hidden",()=>{Y.style.overflow=Ge.htmlOverflow,Ee.style.overflow=Ge.bodyOverflow,window.scrollTo(0,D)}},[p]),i.useLayoutEffect(()=>{if(!p||typeof window>"u"||!window.visualViewport)return;const D=Ze.current;if(!D)return;const Y=window.visualViewport,Ee=()=>{Ft.current||(D.style.setProperty("--vv-height",`${Y.height}px`),D.style.setProperty("--vv-offset-top",`${Y.offsetTop||0}px`))};return Ee(),Y.addEventListener("resize",Ee),Y.addEventListener("scroll",Ee),()=>{Y.removeEventListener("resize",Ee),Y.removeEventListener("scroll",Ee)}},[p]);const gt=q||Z,_t=i.useMemo(()=>qr(gt),[gt]),Yt=i.useMemo(()=>w==="model"&&wt?.modelProvider&&wt?.modelId?`${wt.modelProvider}/${wt.modelId}`:gt,[wt?.modelId,wt?.modelProvider,w,gt]),Xt=i.useMemo(()=>qr(Yt),[Yt]),Te=i.useMemo(()=>L.find(D=>`${D.provider}/${D.id}`===Yt)??null,[Yt,L]),Je=i.useMemo(()=>sO(Te,Xt),[Te,Xt]),Nt=i.useMemo(()=>w==="model"?_t?`${ar}::${_t.modelProvider}/${_t.modelId}`:"":y?`${y}::`:"",[w,y,_t]),tn=!(w==="agent"?!!y:!!_t)||!wt;i.useEffect(()=>{if(u.length===0){S(""),b("model");return}u.some(Y=>Y.id===y)||S(u[0]?.id??"")},[u,y]),i.useEffect(()=>{!p||mt.current||(mt.current=!0,O(!0),Os().then(D=>{const Y=D.models??[];if(F(Y),q||Y.length===0)return;const Ee=D.defaultProvider,Ge=D.defaultModelId;if(Ee&&Ge){const Tt=`${Ee}/${Ge}`;if(Y.some(ln=>`${ln.provider}/${ln.id}`===Tt)){K(Tt),te(Tt),b("model");return}}K("");const kt=Y[0];kt&&te(`${kt.provider}/${kt.id}`)}).catch(D=>{console.error("[QuickChatFAB] Failed to load models:",D),F([]),K("")}).finally(()=>{O(!1)}))},[p,u.length,q]),i.useEffect(()=>{!p||!e||(xe(!0),q1(e).then(D=>{N(D)}).catch(()=>{N([])}).finally(()=>{xe(!1)}))},[p,e]),i.useEffect(()=>{p&&ze()},[p,ze]),i.useEffect(()=>{if(!p){xt.current="";return}if(!Nt){xt.current="";return}if(We.current){xt.current=Nt;return}const D=Nt===xt.current&&!wt&&!Bt;if(!(Nt===xt.current&&!D)){if(xt.current=Nt,w==="model"&&_t){dn(_t.modelProvider,_t.modelId);return}w==="agent"&&y&&en(y)}},[p,w,_t,y,Nt,wt,Bt,dn,en,We]),i.useEffect(()=>{p||(B(!1),re(""),ke(-1),je(!1),Ve(""),ce(0),jt.current.forEach(D=>{D.previewUrl&&URL.revokeObjectURL(D.previewUrl)}),Fe([]))},[p]),i.useEffect(()=>{jt.current=dt},[dt]),i.useEffect(()=>{if(!p){ae.current=!1;return}typeof window>"u"||(ae.current=window.innerWidth<=Ms)},[p]),i.useEffect(()=>{if(!p||tn||!ae.current)return;const D=St.current;if(!D)return;const Y=document.activeElement,Ee=Y?Ze.current?.contains(Y):!1,Ge=Y===document.body,kt=Y===Lt.current;if(!Ee&&!Ge&&!kt){ae.current=!1;return}if(kt){D.focus({preventScroll:!0}),ae.current=!1;return}const Tt=requestAnimationFrame(()=>{D.focus(),ae.current=!1});return()=>cancelAnimationFrame(Tt)},[p,tn]),i.useEffect(()=>()=>{jt.current.forEach(D=>{D.previewUrl&&URL.revokeObjectURL(D.previewUrl)})},[]);const Xn=i.useCallback(()=>{C(!0),j("model"),U(u[0]?.id??""),R(q||Z||"")},[u,Z,q]),be=i.useMemo(()=>u.find(D=>D.id===y)??null,[u,y]),it=i.useMemo(()=>{const D=se.trim().toLowerCase();return(D?$.filter(Ee=>Ee.name.toLowerCase().includes(D)):$).slice(0,10)},[$,se]),rt=i.useMemo(()=>u.filter(D=>rv(D.name,ne)),[u,ne]),at=i.useMemo(()=>{const D=new Map;for(const Y of u)D.set(Y.name.toLowerCase(),Y);return D},[u]);i.useEffect(()=>{ce(0)},[it]),i.useEffect(()=>{Ce(0)},[ne,J]),i.useEffect(()=>()=>{Ue.current!==null&&(window.clearTimeout(Ue.current),Ue.current=null),pt.current!==null&&(window.clearTimeout(pt.current),pt.current=null)},[]),i.useEffect(()=>{if(!p)return;const D=Ee=>{const Ge=Ee.target;Ze.current?.contains(Ge)||Ye.current?.contains(Ge)||Ge.closest(".model-combobox-dropdown--portal")||g(!1)},Y=Ee=>{Ee.key==="Escape"&&g(!1)};return document.addEventListener("mousedown",D),document.addEventListener("keydown",Y),()=>{document.removeEventListener("mousedown",D),document.removeEventListener("keydown",Y)}},[p,g]);const ut=i.useCallback(()=>{const D=It.current;if(!D)return;const Ee=D.scrollTop+D.clientHeight>=D.scrollHeight-50;ot(!Ee),Me.current=!Ee},[]),vt=i.useCallback(D=>{if(!D.isConnected)return;let Y=0,Ee=0,Ge=-1;const kt=6,Tt=()=>{if(D.isConnected){if(D.scrollTop=D.scrollHeight,D.scrollHeight===Ge?Ee+=1:(Ee=0,Ge=D.scrollHeight),Y+=1,Y>=kt||Ee>=2){ot(!1),Me.current=!1;return}window.requestAnimationFrame(Tt)}};Tt()},[]),ie=i.useCallback(()=>{const D=It.current;D&&vt(D)},[vt]);i.useLayoutEffect(()=>{const D=wt?.id??null,Y=ct.current;if(ct.current={isOpen:p,sessionId:D},!p||!D)return;const Ee=!Y.isOpen&&p,Ge=Y.isOpen&&Y.sessionId!==D;if(!Ee&&!Ge)return;const kt=It.current;kt&&vt(kt)},[p,wt?.id,vt]),i.useEffect(()=>{p&&(Me.current||ie())},[$t,Mt,Dt,Vt,p,ie]);const st=i.useMemo(()=>{const D=new Map(u.map(Ee=>[Ee.id,Ee.name?.trim()||Ee.id])),Y=new Map(L.map(Ee=>[`${Ee.provider}/${Ee.id}`,Ee.name?.trim()||""]));return Kt.map((Ee,Ge)=>{const kt=Ee.title?.trim()||`Session ${Ge+1}`;let Tt=null;if(Ee.agentId&&Ee.agentId!==ar)Tt=D.get(Ee.agentId)||Ee.agentId;else if(Ee.modelProvider&&Ee.modelId){const Pt=`${Ee.modelProvider}/${Ee.modelId}`,ln=Y.get(Pt);Tt=ln?`${ln} [${Pt}]`:Pt}return{id:Ee.id,label:Tt?`${kt} — ${Tt}`:kt}})},[u,L,Kt]),Gt=i.useMemo(()=>w==="agent"?be?`Message ${be.name||be.id}`:"Select an agent to start chatting":Je?`Message ${Je}`:"Select a model to start chatting",[w,be,Je]),Cn=i.useCallback(D=>{const Y=Kt.find(Ee=>Ee.id===D);Y&&(Y.modelProvider&&Y.modelId?(b("model"),te(`${Y.modelProvider}/${Y.modelId}`)):(b("agent"),S(Y.agentId)),Zt(Y))},[Zt,Kt]),fs=i.useCallback(async()=>{if(!Bt){if(v==="agent"){if(!P)return;b("agent"),S(P),await ve(P)}else{const D=qr(E||q||Z);if(!D)return;b("model"),te(`${D.modelProvider}/${D.modelId}`),await ve(ar,D.modelProvider,D.modelId)}await ze(),C(!1),j("model")}},[Z,P,v,E,ze,q,Bt,ve]),On=an.length>50?`${an.slice(0,50)}…`:an,jn=i.useCallback(D=>{if(!D||D.length===0)return;const Y=[];for(let Ee=0;Ee<D.length;Ee+=1){const Ge=D[Ee];dO(Ge)&&Y.push({file:Ge,previewUrl:cO(Ge)?URL.createObjectURL(Ge):""})}Y.length>0&&Fe(Ee=>[...Ee,...Y])},[]),zn=i.useCallback(D=>{Fe(Y=>{const Ee=Y[D];return Ee?.previewUrl&&URL.revokeObjectURL(Ee.previewUrl),Y.filter((Ge,kt)=>kt!==D)})},[]),hn=i.useCallback(D=>{jn(D.clipboardData?.files)},[jn]),Et=i.useCallback(()=>{if(typeof window>"u"||window.innerWidth>Ms)return;const D=St.current;!D||D.disabled||D.focus({preventScroll:!0})},[]),En=i.useCallback(()=>{typeof window>"u"||window.innerWidth>Ms||(At.current=!0)},[]),yn=i.useCallback(async()=>{const D=A.trim(),Y=jt.current;if(!(!D&&Y.length===0)&&!tn){if(I(""),B(!1),re(""),ke(-1),D==="/help"){He(!0),Et(),At.current=!1;return}if(D==="/clear"){Jt(),zt(),Y.forEach(Ee=>{Ee.previewUrl&&URL.revokeObjectURL(Ee.previewUrl)}),Fe(Ee=>Ee.filter(Ge=>!Y.includes(Ge)));try{if(w==="model"){const Ee=qr(gt);if(!Ee)return;await ve(ar,Ee.modelProvider,Ee.modelId)}else y&&await ve(y)}catch{n("Failed to clear conversation","error")}finally{Et(),At.current=!1}return}try{He(!1),await fn(D,Y.map(Ee=>Ee.file)),Y.forEach(Ee=>{Ee.previewUrl&&URL.revokeObjectURL(Ee.previewUrl)}),Fe(Ee=>Ee.filter(Ge=>!Y.includes(Ge)))}catch{}finally{Et(),At.current=!1}}},[n,w,zt,Et,tn,A,gt,y,fn,ve,Jt]),ls=i.useCallback(D=>{D.preventDefault(),oe.current+=1,$e(!0)},[]),cs=i.useCallback(D=>{D.preventDefault(),D.dataTransfer.dropEffect="copy",$e(!0)},[]),Hn=i.useCallback(D=>{D.preventDefault(),oe.current=Math.max(0,oe.current-1),oe.current===0&&$e(!1)},[]),qn=i.useCallback(D=>{D.preventDefault(),oe.current=0,$e(!1),jn(D.dataTransfer?.files)},[jn]),wn=i.useCallback((D,Y)=>{const Ee=rO(D,Y);if(Ee){B(!0),re(Ee.filter),ke(Ee.start);return}B(!1),re(""),ke(-1)},[]),Zn=i.useCallback(D=>{I(Y=>{const Ee=Ff(Y);if(!Ee)return Y;const Ge=`/skill:${D.name} `,kt=Y.slice(0,Ee.start)+Ge+Y.slice(Ee.end);return window.requestAnimationFrame(()=>{St.current&&St.current.focus()}),kt}),je(!1),Ve(""),ce(0)},[]),_n=i.useCallback(D=>{const Y=St.current;if(!Y||H<0)return;const Ee=Y.selectionStart??Ie.current,Ge=Y.selectionEnd??Ee,kt=Math.max(Ee,Ge),Tt=Math.min(H,kt),ln=`${`@${D.name.replace(/\s+/g,"_")}`} `,ts=A.slice(0,Tt)+ln+A.slice(kt),Rn=Tt+ln.length;I(ts),B(!1),re(""),Ce(0),ke(-1),window.requestAnimationFrame(()=>{St.current&&(St.current.focus(),St.current.setSelectionRange(Rn,Rn))})},[H,A]),is=i.useCallback(D=>{const Y=D.target.value,Ee=D.target.selectionStart??Y.length;Ie.current=Ee,I(Y),Oe&&Y.trim().length>0&&He(!1),wn(Y,Ee);const Ge=Ff(Y);Ge?(je(!0),Ve(Ge.filter)):(je(!1),Ve("")),_e.detectMention(Y,Ee),Be(_e.mentionActive),_e.mentionActive&&lt(D.target)},[Oe,wn,_e,lt]),Ns=i.useCallback(()=>{if(At.current){window.requestAnimationFrame(()=>{Et()});return}typeof window<"u"&&window.innerWidth<=Ms&&Ze.current&&(Ft.current=!0,Ze.current.style.removeProperty("--vv-height"),Ze.current.style.removeProperty("--vv-offset-top"),window.setTimeout(()=>{Ft.current=!1},450)),Ue.current!==null&&window.clearTimeout(Ue.current),Ue.current=window.setTimeout(()=>{B(!1),re(""),ke(-1),Be(!1),_e.dismissMention(),Ue.current=null},120),pt.current!==null&&window.clearTimeout(pt.current),pt.current=window.setTimeout(()=>{je(!1),pt.current=null},120)},[_e,Et]),es=i.useCallback(()=>{Ft.current=!1,Ue.current!==null&&(window.clearTimeout(Ue.current),Ue.current=null),pt.current!==null&&(window.clearTimeout(pt.current),pt.current=null)},[]),ks=i.useCallback(D=>{const Y=D.currentTarget,Ee=Y.selectionStart??Y.value.length;Ie.current=Ee,wn(Y.value,Ee),_e.detectMention(Y.value,Ee),Be(_e.mentionActive),_e.mentionActive&&lt(Y)},[wn,_e,lt]),Is=i.useCallback(D=>{D.key!=="Escape"&&ks(D)},[ks]),Ss=i.useCallback(D=>{Ae(Y=>{const Ee=new Set(Y);return Ee.has(D)?Ee.delete(D):Ee.add(D),Ee})},[]),X=i.useCallback((D,Y=!1)=>Y?t.jsx("div",{className:"quick-chat-message-content quick-chat-message-content--plain",children:D}):t.jsx("div",{className:"quick-chat-message-content quick-chat-message-content--markdown",children:t.jsx(bi,{remarkPlugins:[xi],components:cv,children:D})}),[]),_=i.useCallback(D=>{if(Ie.current=D.currentTarget.selectionStart??Ie.current,_e.mentionActive&&_e.files.length>0){if(_e.handleKeyDown(D,A),D.key==="Enter"||D.key==="Tab"){const Y=_e.files[_e.selectedIndex];if(Y){const Ee=_e.selectFile(Y,A);I(Ee),_e.dismissMention(),Be(!1)}}return}if(J&&D.key==="ArrowDown"){D.preventDefault(),rt.length>0&&Ce(Y=>(Y+1)%rt.length);return}if(J&&D.key==="ArrowUp"){D.preventDefault(),rt.length>0&&Ce(Y=>Y===0?rt.length-1:Y-1);return}if(J&&D.key==="Enter"){D.preventDefault();const Y=rt[ye]??rt[0];Y&&_n(Y);return}if(J&&D.key==="Escape"){D.preventDefault(),D.stopPropagation(),B(!1),re(""),ke(-1);return}if(Se&&it.length>0&&D.key==="ArrowDown"){D.preventDefault(),ce(Y=>(Y+1)%it.length);return}if(Se&&it.length>0&&D.key==="ArrowUp"){D.preventDefault(),ce(Y=>Y===0?it.length-1:Y-1);return}if(Se&&(D.key==="Enter"||D.key==="Tab")){D.preventDefault();const Y=it[ee]??it[0];Y&&Zn(Y);return}if(Se&&D.key==="Escape"){D.preventDefault(),je(!1),Ve("");return}D.key!=="Enter"||D.shiftKey||(D.preventDefault(),yn())},[J,rt,ye,_n,yn,_e,A,Se,it,ee,Zn]),de=i.useCallback(()=>{if(ht.current){ht.current=!1;return}if(p){g(!1);return}typeof window<"u"&&window.innerWidth<=Ms&&Lt.current?.focus({preventScroll:!0}),g(!0)},[p,g]);return t.jsxs(t.Fragment,{children:[t.jsx("input",{ref:Lt,type:"text",className:"quick-chat-stealth-input","aria-hidden":"true",tabIndex:-1}),s&&t.jsx("button",{ref:Ye,type:"button",className:"quick-chat-fab","aria-label":"Open quick chat","data-testid":"quick-chat-fab","data-dragging":ge?"true":"false",style:{right:le.x,bottom:le.y},onPointerDown:Ne,onClick:de,children:t.jsx(Ui,{size:24})}),p&&t.jsxs("div",{className:"quick-chat-panel",ref:Ze,"data-testid":"quick-chat-panel",style:{...Ct?{right:le.x+me.right,bottom:ue+me.bottom,width:qe.width,height:qe.height}:{}},children:[Ct&&t.jsxs(t.Fragment,{children:[t.jsx("div",{className:"quick-chat-resize-handle","data-resize-direction":"n","data-testid":"quick-chat-resize-n",onPointerDown:tt,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:tt,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:tt,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:tt,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:tt,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:tt,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:tt,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:tt,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"}),w==="model"&&Je&&(()=>{const D=Te?.provider??Xt?.modelProvider??"";return x==="mobile"&&Je.length>12&&D?t.jsx("span",{className:"quick-chat-model-tag quick-chat-model-tag--icon","data-testid":"quick-chat-model-tag",title:Je,"aria-label":Je,children:t.jsx(Sn,{provider:D,size:"sm"})}):t.jsx("span",{className:"quick-chat-model-tag","data-testid":"quick-chat-model-tag",title:Je,children:Je})})()]}),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:Xn,disabled:Bt,children:t.jsx(gn,{size:16})}),t.jsx("button",{type:"button",className:"btn-icon","aria-label":"Close quick chat","data-testid":"quick-chat-close",onClick:()=>g(!1),children:t.jsx(nn,{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:wt?.id??"",onChange:D=>Cn(D.target.value),"data-testid":"quick-chat-session-dropdown",children:[t.jsx("option",{value:"",disabled:!0,children:Bt?"Loading sessions…":"Select a session"}),st.map(D=>t.jsx("option",{value:D.id,children:D.label},D.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${v==="model"?" quick-chat-mode-btn--active":""}`,"data-testid":"quick-chat-inline-mode-model",onClick:()=>j("model"),children:"Model"}),t.jsx("button",{type:"button",className:`quick-chat-mode-btn${v==="agent"?" quick-chat-mode-btn--active":""}`,"data-testid":"quick-chat-inline-mode-agent",onClick:()=>j("agent"),children:"Agent"})]}),v==="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:P,onChange:D=>U(D.target.value),"data-testid":"quick-chat-new-agent-select",children:u.map(D=>t.jsx("option",{value:D.id,children:nO(D)},D.id))})]}):t.jsx("div",{className:"quick-chat-panel-agent-select","data-testid":"quick-chat-new-model-select",children:t.jsx(ys,{id:"quick-chat-new-model-select",models:L,value:E,onChange:R,label:"Select model override",placeholder:M?"Loading models…":"Select a model",disabled:M||L.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:()=>{C(!1),j("model")},children:"Cancel"}),t.jsx("button",{type:"button",className:"btn btn-primary","data-testid":"quick-chat-new-session-submit",onClick:()=>void fs(),disabled:Bt||(v==="agent"?!P:!qr(E||q||Z)),children:"Create"})]})]}),t.jsx("div",{className:"quick-chat-panel-messages",ref:It,"data-testid":"quick-chat-messages",onScroll:ut,children:Bt?t.jsx("div",{className:"quick-chat-panel-empty",children:"Loading conversation…"}):Vt?t.jsxs(t.Fragment,{children:[$t.map(D=>t.jsx(Uf,{message:D,forcePlain:D.role!=="user"&&pe.has(D.id),mentionAgentsByName:at,onToggleRender:Ss},D.id)),Oe&&t.jsx("div",{className:"quick-chat-panel-message quick-chat-panel-message--received","data-testid":"quick-chat-help-message",children:X("Available commands:\n- `/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:[Mt?t.jsxs(t.Fragment,{children:[t.jsx("div",{"data-testid":"quick-chat-streaming-text",children:X(Mt,pe.has("__streaming__"))}),t.jsx("button",{type:"button",className:`quick-chat-message-render-toggle${pe.has("__streaming__")?" quick-chat-message-render-toggle--plain":""}`,"data-testid":"quick-chat-message-render-toggle","aria-label":pe.has("__streaming__")?"Show rendered markdown":"Show plain text",onClick:()=>Ss("__streaming__"),children:pe.has("__streaming__")?t.jsx(mu,{size:14}):t.jsx(kr,{size:14})})]}):t.jsx("p",{className:"quick-chat-panel-waiting","data-testid":"quick-chat-waiting",children:Dt?"Thinking…":"Connecting…"}),lv(Qt,!0),Dt&&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:Dt})]})]})]}):on?t.jsx("div",{className:"quick-chat-panel-empty",children:"Loading conversation…"}):$t.length===0&&!Mt&&!Dt&&!Vt&&!Oe?t.jsx("div",{className:"quick-chat-panel-empty",children:"No messages yet. Start the conversation!"}):t.jsxs(t.Fragment,{children:[$t.map(D=>t.jsx(Uf,{message:D,forcePlain:D.role!=="user"&&pe.has(D.id),mentionAgentsByName:at,onToggleRender:Ss},D.id)),Oe&&t.jsx("div",{className:"quick-chat-panel-message quick-chat-panel-message--received","data-testid":"quick-chat-help-message",children:X("Available commands:\n- `/clear` — Clear conversation and start fresh\n- `/skill:{name}` — Use a specific skill\n- `/help` — Show this help")})]})}),De&&t.jsxs("button",{type:"button",className:"btn btn-sm quick-chat-jump-to-latest","data-testid":"quick-chat-jump-to-latest",onClick:ie,children:[t.jsx(rn,{size:14}),"Latest"]}),dt.length>0&&t.jsx("div",{className:"quick-chat-attachment-previews","data-testid":"quick-chat-attachment-previews",children:dt.map((D,Y)=>t.jsxs("div",{className:"quick-chat-attachment-preview","data-testid":`quick-chat-attachment-preview-${Y}`,children:[D.previewUrl?t.jsx("img",{src:D.previewUrl,alt:D.file.name}):t.jsx("span",{className:"quick-chat-attachment-preview-name",children:D.file.name}),t.jsx("button",{type:"button",className:"quick-chat-attachment-remove","data-testid":`quick-chat-attachment-remove-${Y}`,"aria-label":`Remove ${D.file.name}`,onClick:()=>zn(Y),children:"×"})]},`${D.file.name}-${Y}`))}),t.jsx("div",{className:"quick-chat-panel-input",children:t.jsxs("div",{className:`quick-chat-input-wrapper${fe?" quick-chat-input-wrapper--dragover":""}`,onDragEnter:ls,onDragOver:cs,onDragLeave:Hn,onDrop:qn,children:[t.jsx("input",{ref:Ht,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:D=>{jn(D.target.files),D.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:()=>Ht.current?.click(),children:t.jsx(jg,{size:16})}),t.jsx("input",{ref:St,type:"text",value:A,onChange:is,onKeyDown:_,onKeyUp:Is,onClick:ks,onBlur:Ns,onFocus:es,onPaste:hn,onTouchStart:D=>{typeof window>"u"||window.innerWidth>Ms||document.activeElement!==D.currentTarget&&(D.preventDefault(),D.currentTarget.focus({preventScroll:!0}))},placeholder:Gt,disabled:tn,"data-testid":"quick-chat-input"}),Vt?t.jsx("button",{type:"button",className:"chat-input-stop quick-chat-send-btn",onPointerDown:D=>{typeof window>"u"||window.innerWidth>Ms||(D.preventDefault(),D.pointerType&&D.pointerType!=="mouse"&&(Le.current=!0,Jt()))},onTouchStart:D=>{typeof window>"u"||window.innerWidth>Ms||(D.preventDefault(),Le.current=!0,Jt())},onMouseDown:D=>{typeof window>"u"||window.innerWidth>Ms||D.preventDefault()},onClick:()=>{if(Le.current){Le.current=!1;return}Jt()},"aria-label":"Stop generation","data-testid":"quick-chat-stop",children:t.jsx(Si,{size:14})}):t.jsx("button",{type:"button",className:"quick-chat-send-btn",onPointerDown:D=>{typeof window>"u"||window.innerWidth>Ms||(D.preventDefault(),D.pointerType&&D.pointerType!=="mouse"&&(Le.current=!0,En(),Et(),yn()))},onTouchStart:D=>{typeof window>"u"||window.innerWidth>Ms||(D.preventDefault(),Le.current=!0,En(),Et(),yn())},onMouseDown:D=>{typeof window>"u"||window.innerWidth>Ms||D.preventDefault()},onClick:()=>{if(Le.current){Le.current=!1;return}yn()},disabled:tn||A.trim().length===0&&dt.length===0,"data-testid":"quick-chat-send",children:t.jsx(wa,{size:16})})]}),t.jsx(VL,{agents:u,filter:ne,highlightedIndex:ye,visible:J,onSelect:_n,position:"above"}),t.jsx(ZL,{visible:_e.mentionActive&&!J,position:we,files:_e.files,selectedIndex:_e.selectedIndex,onSelect:D=>{const Y=_e.selectFile(D,A);I(Y),_e.dismissMention(),Be(!1),St.current?.focus()},loading:_e.loading}),Se&&t.jsx("div",{className:"chat-skill-menu","data-testid":"quick-chat-skill-menu",role:"listbox","aria-label":"Skill suggestions",children:G?t.jsx("div",{className:"chat-skill-menu-empty",children:"Loading skills…"}):it.length===0?t.jsx("div",{className:"chat-skill-menu-empty",children:se?"No skills found":"No skills available"}):it.map((D,Y)=>t.jsxs("button",{type:"button",role:"option","aria-selected":Y===ee,className:`chat-skill-menu-item${Y===ee?" chat-skill-menu-item--highlighted":""}`,onMouseDown:Ee=>Ee.preventDefault(),onMouseEnter:()=>ce(Y),onClick:()=>Zn(D),children:[t.jsx("span",{className:"chat-skill-menu-item-name",children:D.name}),t.jsx("span",{className:"chat-skill-menu-item-description",title:D.relativePath,children:D.relativePath})]},D.id))}),an&&t.jsxs("div",{className:"chat-pending-message","data-testid":"chat-pending-indicator",children:[t.jsx("span",{children:`Queued: ${On}`}),t.jsx("button",{type:"button",className:"chat-pending-message-dismiss","aria-label":"Dismiss queued message","data-testid":"chat-pending-dismiss",onClick:zt,children:"×"})]})]})})]})]})}function Vr(e){if(!e)return 0;const n=Date.parse(e);return Number.isFinite(n)?n:0}function Bf(e){return e.status==="generating"||e.status==="awaiting_input"}function Wr(e){return e==="complete"||e==="error"}function pO(e){const[n,s]=i.useState([]),a=i.useRef(new Map),r=i.useRef(new Map),{sessions:o,broadcastUpdate:l,broadcastCompleted:c,requestSync:d}=_r(),u=i.useCallback(()=>{xu(e).then(p=>{const g=p.filter(w=>{const b=Vr(w.updatedAt),y=r.current.get(w.id);return y===void 0?!0:b<=y?!1:(r.current.delete(w.id),!0)}),x=new Map;for(const w of g)x.set(w.id,Vr(w.updatedAt));a.current=x,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 x=new Map(p.map(w=>[w.id,w]));for(const w of o.values()){if(e&&w.projectId&&w.projectId!==e)continue;const b=w.lastEventTimestamp,y=a.current.get(w.sessionId)??0;if(b<y)continue;const S=r.current.get(w.sessionId);if(S!==void 0&&b<=S)continue;if(S!==void 0&&b>S&&!Wr(w.status)&&r.current.delete(w.sessionId),Wr(w.status)){x.delete(w.sessionId)&&(g=!0),a.current.set(w.sessionId,b);continue}const k=x.get(w.sessionId),C=w.type??k?.type,v=w.title??k?.title;if(!k&&(!C||!v))continue;const j={id:w.sessionId,type:C??"planning",status:w.status,title:v??"AI Session",projectId:w.projectId??k?.projectId??e??null,lockedByTab:w.owningTabId??k?.lockedByTab??null,updatedAt:w.updatedAt??k?.updatedAt??new Date(b).toISOString()},P=x.get(w.sessionId);(!P||P.status!==j.status||P.title!==j.title||P.type!==j.type||P.projectId!==j.projectId||P.lockedByTab!==j.lockedByTab||P.updatedAt!==j.updatedAt)&&(x.set(w.sessionId,j),a.current.set(w.sessionId,b),g=!0)}return g?[...x.values()].sort((w,b)=>Vr(b.updatedAt)-Vr(w.updatedAt)):p})},[e,o]),i.useEffect(()=>{const p=e?`?projectId=${encodeURIComponent(e)}`:"",g=w=>{try{const b=JSON.parse(w.data),y=Vr(b.updatedAt)||Date.now();s(S=>{const k=a.current.get(b.id)??0;if(y<k)return S;const C=r.current.get(b.id);if(C!==void 0&&y<=C)return S;if(C!==void 0&&y>C&&!Wr(b.status)&&r.current.delete(b.id),a.current.set(b.id,y),Wr(b.status))return S.filter(j=>j.id!==b.id);const v=S.findIndex(j=>j.id===b.id);if(v>=0){const j=[...S];return j[v]=b,j}return Bf(b)?[b,...S]:S}),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}),Wr(b.status)&&c({sessionId:b.id,status:b.status,timestamp:y})}catch{}},x=w=>{try{const b=JSON.parse(w.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(S=>S.filter(k=>k.id!==b))}catch{}};return ii(`/api/events${p}`,{events:{"ai_session:updated":g,"ai_session:deleted":x},onReconnect:()=>{u()}})},[c,l,e,u]);const m=i.useCallback(async p=>{const x=n.find(S=>S.id===p)?.type,w=Ia();let b=!1;if(x==="planning")try{await Ig(p,e,w)}catch(S){b=!0,S instanceof Error&&S.message.includes("locked")&&console.warn(`[useBackgroundSessions] Forcing dismiss of planning session ${p} despite lock by another tab`)}else if(x==="subtask")try{await Dg(p,e,w)}catch(S){b=!0,S instanceof Error&&S.message.includes("locked")&&console.warn(`[useBackgroundSessions] Forcing dismiss of subtask session ${p} despite lock by another tab`)}else if(x==="mission_interview")try{await Ug(p,e,w)}catch(S){b=!0,S instanceof Error&&S.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 Bg(p)}catch{}s(S=>S.filter(k=>k.id!==p))},[c,e,n]),h=i.useMemo(()=>n.filter(p=>Bf(p)),[n]),f=i.useMemo(()=>h.filter(p=>p.type==="planning"),[h]);return{sessions:h,generating:h.filter(p=>p.status==="generating").length,needsInput:h.filter(p=>p.status==="awaiting_input").length,planningSessions:f,dismissSession:m,refresh:u}}const Hl="fusion:hide-session-banners",cu="fusion:session-banner-pref-changed";function fO(){if(typeof window>"u")return!1;try{return window.localStorage.getItem(Hl)==="1"}catch{return!1}}function gO(e){if(typeof window>"u")return()=>{};const n=a=>{a.key===Hl&&e()},s=()=>e();return window.addEventListener("storage",n),window.addEventListener(cu,s),()=>{window.removeEventListener("storage",n),window.removeEventListener(cu,s)}}function i5(e){if(!(typeof window>"u"))try{e?window.localStorage.setItem(Hl,"1"):window.localStorage.removeItem(Hl),window.dispatchEvent(new Event(cu))}catch{}}function bO(){return i.useSyncExternalStore(gO,fO,()=>!1)}function xs(e){return{...e,column:Zg(e.column),dependencies:Array.isArray(e.dependencies)?e.dependencies:[],steps:Array.isArray(e.steps)?e.steps:[],log:Array.isArray(e.log)?e.log:[]}}function Hf(e,n){return!e&&!n?0:e?n?e.localeCompare(n):1:-1}function xO(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 wd(e,n){if(Hf(n.updatedAt,e.updatedAt)<0)return e;if(e.column===n.column)return xO(e,n);const a=Hf(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 vO(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),m=i.useRef(0),h=i.useRef(0),f=i.useRef(s),p=i.useRef(null),g=i.useRef(void 0),x=i.useRef(0),w=i.useRef(n);u.current=r,f.current=s,w.current!==n&&(w.current=n,x.current++);const b=1e3,y=i.useCallback(async Z=>{const K=++m.current,A=n,I=Z?.searchQueryOverride??f.current,$=Z?.includeArchivedOverride??d.current;try{const N=await Hk(void 0,void 0,A,I,$);if(m.current!==K||n!==A)return;o(N.map(xs)),g.current=Date.now()}catch{if(m.current!==K||n!==A)return;if(Z?.clearOnError){o([]);return}o(N=>N)}},[n]);p.current=y;const S=i.useCallback(async()=>{d.current||(c(!0),d.current=!0,await p.current({includeArchivedOverride:!0}))},[]),k=i.useRef(s);i.useEffect(()=>{if(s===void 0&&k.current===void 0)return;k.current=s;const Z=setTimeout(()=>{y({searchQueryOverride:s})},300);return()=>clearTimeout(Z)},[s]),i.useEffect(()=>{y({clearOnError:!0});const Z=()=>{if(document.visibilityState!=="visible")return;const K=Date.now();K-h.current<b||(h.current=K,y())};return document.addEventListener("visibilitychange",Z),()=>{document.removeEventListener("visibilitychange",Z)}},[y]),i.useEffect(()=>{if(a===!1)return;const Z=x.current,K=n?`?projectId=${encodeURIComponent(n)}`:"",A=()=>x.current!==Z;let I=!0;const $=se=>{if(A())return;const Ve=xs(JSON.parse(se.data));if(f.current){p.current({searchQueryOverride:f.current});return}o(ee=>{const ce=ee.findIndex(B=>B.id===Ve.id);if(ce===-1)return[...ee,Ve];const ne=ee[ce],re=wd(ne,Ve);if(re===ne)return ee;const J=[...ee];return J[ce]=re,J}),g.current=Date.now()},N=se=>{if(A())return;if(f.current){p.current({searchQueryOverride:f.current});return}const{task:Ve,to:ee}=JSON.parse(se.data),ce=xs(Ve),ne={...ce,column:Zg(ee,ce.column)};o(re=>{const J=re.findIndex(ye=>ye.id===ne.id);if(J===-1)return[...re,ne];const B=[...re];return B[J]=ne,B}),g.current=Date.now()},G=se=>{if(A())return;if(f.current){p.current({searchQueryOverride:f.current});return}const Ve=xs(JSON.parse(se.data));o(ee=>{const ce=ee.findIndex(B=>B.id===Ve.id);if(ce===-1)return[...ee,Ve];const ne=ee[ce],re=wd(ne,Ve);if(re===ne)return ee;const J=[...ee];return J[ce]=re,J}),g.current=Date.now()},xe=se=>{if(A())return;if(f.current){p.current({searchQueryOverride:f.current});return}const Ve=xs(JSON.parse(se.data));o(ee=>ee.filter(ce=>ce.id!==Ve.id))},Se=se=>{if(A())return;if(f.current){p.current({searchQueryOverride:f.current});return}const{task:Ve}=JSON.parse(se.data),ce={...xs(Ve),column:"done"};o(ne=>{const re=ne.findIndex(B=>B.id===ce.id);if(re===-1)return[...ne,ce];const J=[...ne];return J[re]=ce,J})},je=ii(`/api/events${K}`,{events:{"task:created":$,"task:moved":N,"task:updated":G,"task:deleted":xe,"task:merged":Se},onReconnect:()=>{I&&(A()||p.current())}});return()=>{I=!1,je()}},[n,a]);const C=i.useCallback(async Z=>{const K=xs(await Mg(Z,n));return o(A=>A.some(I=>I.id===K.id)?A:[...A,K]),K},[n]),v=i.useCallback(async(Z,K,A)=>xs(await Vk(Z,K,n,A)),[n]),j=i.useCallback(async Z=>xs(await Ag(Z,n)),[n]),P=i.useCallback(async(Z,K)=>xs(await Wk(Z,n,K)),[n]),U=i.useCallback(async Z=>Kk(Z,n),[n]),E=i.useCallback(async Z=>xs(await Gk(Z,n)),[n]),R=i.useCallback(async Z=>xs(await Jk(Z,n)),[n]),L=i.useCallback(async Z=>{const K=xs(await Yk(Z,n));return o(A=>A.some(I=>I.id===K.id)?A:[...A,K]),K},[n]),F=i.useCallback(async(Z,K)=>{const A=u.current.find($=>$.id===Z),I=A?{...A,...K,updatedAt:new Date().toISOString()}:void 0;I&&o($=>$.map(N=>N.id===Z?I:N));try{const $=xs(await mi(Z,K,n));return o(N=>N.map(G=>G.id===Z?$:G)),$}catch($){throw A&&o(N=>N.map(G=>G.id===Z?A:G)),$}},[n]),M=i.useCallback(async Z=>{const K=xs(await Xk(Z,n));return o(A=>A.map(I=>I.id===Z?K:I)),K},[n]),O=i.useCallback(async Z=>{const K=xs(await Zk(Z,n));return o(A=>A.map(I=>I.id===Z?K:I)),K},[n]),q=i.useCallback(async()=>{const K=(await ej(n)).map(xs);return o(A=>A.map(I=>K.find(N=>N.id===I.id)||I)),K},[n]),te=i.useCallback(Z=>{if(Z.length===0)return;if(f.current){p.current({searchQueryOverride:f.current});return}const K=Z.map(xs);o(A=>{let I=A;for(const $ of K){const N=I.findIndex(Se=>Se.id===$.id);if(N===-1){I===A&&(I=[...A]),I.push($);continue}const G=I[N],xe=wd(G,$);xe!==G&&(I===A&&(I=[...A]),I[N]=xe)}return I}),g.current=Date.now()},[]);return{tasks:r,createTask:C,moveTask:v,pauseTask:j,deleteTask:P,mergeTask:U,retryTask:E,resetTask:R,duplicateTask:L,updateTask:F,archiveTask:M,unarchiveTask:O,archiveAllDone:q,loadArchivedTasks:S,includeArchived:l,ingestCreatedTasks:te,lastFetchTimeMs:g.current}}const yO=5e3,wO=1e3;function kO(e){const s=(fS(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 qf(e){return e.map(n=>({...n,nodeMappings:kO(n)}))}function jO(){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 km();n(qf(f))}catch(f){o(f instanceof Error?f.message:"Failed to fetch projects")}},[]);i.useEffect(()=>{let f=!1;async function p(){a(!0);const x=performance.now();try{const w=await km(),b=qf(w),y=Math.round(performance.now()-x);console.log(`[useProjects] initial fetchProjectsAcrossNodes took ${y}ms (${b.length} projects)`),f||(n(b),o(null))}catch(w){const b=Math.round(performance.now()-x);console.warn(`[useProjects] initial fetch failed after ${b}ms: ${w instanceof Error?w.message:String(w)}`),f||o(w instanceof Error?w.message:"Failed to fetch projects")}finally{f||a(!1)}}p();const g=()=>{if(document.visibilityState!=="visible")return;const x=Date.now();x-c.current<wO||(c.current=x,d())};return document.addEventListener("visibilitychange",g),()=>{f=!0,document.removeEventListener("visibilitychange",g)}},[d]),i.useEffect(()=>{if(!s)return l.current=setInterval(()=>{d()},yO),()=>{l.current&&(clearInterval(l.current),l.current=null)}},[s,d]);const u=i.useCallback(async f=>{const p=await jS(f);return n(g=>[...g,p]),p},[]),m=i.useCallback(async(f,p)=>{const g=await AS(f,p);return n(x=>x.map(w=>w.id===f?g:w)),g},[]),h=i.useCallback(async f=>{await Og(f),n(p=>p.filter(g=>g.id!==f))},[]);return{projects:e,loading:s,error:r,refresh:d,register:u,update:m,unregister:h}}const NO="kb-dashboard-current-project";function SO(e){return e??"local"}function CO(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),m=SO(s);i.useEffect(()=>{let p=!1;async function g(){try{const x=await Pa();if(p)return;u.current=x.dashboardCurrentProjectIdByNode??{};const w=u.current[m];if(w){const b=e.find(y=>y.id===w);b&&(r(b),c.current=!0)}if(!w)try{const b=localStorage.getItem(NO);if(b){const y=JSON.parse(b);y?.id&&e.some(k=>k.id===y.id)&&(r(y),c.current=!0,u.current={...u.current,[m]:y.id},await kn({dashboardCurrentProjectIdByNode:u.current}).catch(()=>{}))}}catch{}}catch{}finally{p||l(!1)}}return g(),()=>{p=!0}},[m,e]),i.useEffect(()=>{if(!o){if(a){if(!e.some(x=>x.id===a.id)&&e.length>0){const x=e.find(w=>w.status==="active");r(x||e[0]||null);return}const g={...u.current,[m]:a.id};u.current=g,kn({dashboardCurrentProjectIdByNode:g}).catch(()=>{})}else if(e.length>0&&!d.current){const p=e.find(g=>g.status==="active");p&&r(p)}}},[a,e,o,m]);const h=i.useCallback(p=>{if(d.current=!1,r(p),p){const g={...u.current,[m]:p.id};u.current=g,kn({dashboardCurrentProjectIdByNode:g}).catch(()=>{})}},[m]),f=i.useCallback(()=>{d.current=!0,r(null);const p={...u.current};delete p[m],u.current=p,kn({dashboardCurrentProjectIdByNode:p}).catch(()=>{})},[m]);return{currentProject:a,setCurrentProject:h,clearCurrentProject:f,loading:o}}const dv=i.createContext(null);function EO({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(m=>m.id!==c))},[]),l=i.useCallback((c,d="info")=>{const u=a.current++;s(h=>[...h,{id:u,message:c,type:d}]);const m=setTimeout(()=>o(u),4e3);r.current.set(u,m)},[o]);return i.useEffect(()=>()=>{r.current.forEach(c=>clearTimeout(c)),r.current.clear()},[]),kl.createElement(dv.Provider,{value:{toasts:n,addToast:l,removeToast:o}},e)}function _O(){const e=i.useContext(dv);if(!e)throw new Error("useToast must be used within ToastProvider");return e}const uv="kb-dashboard-theme-mode",mv="kb-dashboard-color-theme",hv="kb-dashboard-font-scale-pct",du=100,MO=85,AO=125,pv=[...B0],uu="theme-data",Kr="theme-data.css";function PO(){const e=document.baseURI||(typeof document.location<"u"?document.location.href:"");return e?e.startsWith("http://")||e.startsWith("https://")?new URL(`/${Kr}`,e).toString():e.startsWith("file://")?e.endsWith("/")?e.slice(0,-1)+`/${Kr}`:e.replace(/\/[^/]+$/,`/${Kr}`):`/${Kr}`:`/${Kr}`}const Fs=typeof window<"u",RO=Fs?i.useLayoutEffect:i.useEffect;function fv(e){return e==="dark"||e==="light"||e==="system"}function Vf(){if(!Fs)return"dark";try{const e=localStorage.getItem(uv);if(fv(e))return e}catch{}return"dark"}function Wf(){if(!Fs)return"default";try{const e=localStorage.getItem(mv);if(e&&pv.includes(e))return e}catch{}return"default"}function Kf(e){if(Fs)try{localStorage.setItem(uv,e)}catch{}}function Gf(e){if(Fs)try{localStorage.setItem(mv,e)}catch{}}function bo(e){return typeof e!="number"||!Number.isFinite(e)?du:Math.min(AO,Math.max(MO,Math.round(e)))}function Jf(){if(!Fs)return du;try{const e=Number(localStorage.getItem(hv));return bo(e)}catch{return du}}function Yf(e){if(Fs)try{localStorage.setItem(hv,String(bo(e)))}catch{}}function IO(e,n){return e==="system"?n?"dark":"light":e}function TO(e,n,s,a){if(!Fs)return;const r=IO(e,a);document.documentElement.setAttribute("data-theme",r),document.documentElement.setAttribute("data-color-theme",n),document.documentElement.style.fontSize=`${bo(s)}%`}function Qf(){if(!Fs)return;const e=PO(),n=document.getElementById(uu);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=uu,document.head.appendChild(s)}function Xf(){if(!Fs)return;const e=document.getElementById(uu);e&&e.remove()}function $O(){const[e,n]=i.useState(()=>Vf()),[s,a]=i.useState(()=>Wf()),[r,o]=i.useState(()=>Jf()),[l,c]=i.useState(!0),[d,u]=i.useState(()=>Fs?window.matchMedia("(prefers-color-scheme: dark)").matches:!0),m=i.useRef(e),h=i.useRef(s),f=i.useRef(r),p=i.useRef(!1),g=i.useRef(!1),x=i.useRef(!1);i.useEffect(()=>{m.current=e},[e]),i.useEffect(()=>{h.current=s},[s]),i.useEffect(()=>{f.current=r},[r]),i.useEffect(()=>{if(!Fs||!l)return;let S=!1;return Pa().then(k=>{if(!S&&(fv(k.themeMode)&&!p.current&&(m.current!==k.themeMode&&(m.current=k.themeMode,n(k.themeMode)),Vf()!==k.themeMode&&Kf(k.themeMode)),k.colorTheme&&pv.includes(k.colorTheme)&&!g.current&&(h.current!==k.colorTheme&&(h.current=k.colorTheme,a(k.colorTheme)),Wf()!==k.colorTheme&&Gf(k.colorTheme)),!x.current)){const C=bo(k.dashboardFontScalePct);f.current!==C&&(f.current=C,o(C)),Jf()!==C&&Yf(C)}}).catch(k=>{console.warn("[useTheme] Failed to hydrate theme from global settings",k)}).finally(()=>{S||c(!1)}),()=>{S=!0}},[l]),i.useEffect(()=>{if(!Fs)return;const S=window.matchMedia("(prefers-color-scheme: dark)"),k=C=>{u(C.matches)};return S.addEventListener("change",k),()=>S.removeEventListener("change",k)},[]),RO(()=>{TO(e,s,r,d)},[e,s,r,d]),i.useEffect(()=>{!Fs||l||(s!=="default"?Qf():Xf())},[s,l]);const w=i.useCallback(S=>{p.current=!0,m.current=S,n(S),Kf(S),kn({themeMode:S}).catch(k=>{console.warn("[useTheme] Failed to persist themeMode to global settings",k)})},[]),b=i.useCallback(S=>{g.current=!0,h.current=S,a(S),Gf(S),S!=="default"?Qf():Xf(),kn({colorTheme:S}).catch(k=>{console.warn("[useTheme] Failed to persist colorTheme to global settings",k)})},[]),y=i.useCallback(S=>{const k=bo(S);x.current=!0,f.current=k,o(k),Yf(k),kn({dashboardFontScalePct:k}).catch(C=>{console.warn("[useTheme] Failed to persist dashboardFontScalePct to global settings",C)})},[]);return{themeMode:e,colorTheme:s,dashboardFontScalePct:r,setThemeMode:w,setColorTheme:b,setDashboardFontScalePct:y,isSystemDark:d}}function DO(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),[m,h]=i.useState(!1),[f,p]=i.useState(null),[g,x]=i.useState(void 0),[w,b]=i.useState(null),[y,S]=i.useState("definition"),[k,C]=i.useState(null),[v,j]=i.useState(!1),[P,U]=i.useState(void 0),[E,R]=i.useState(!1),[L,F]=i.useState(!1),[M,O]=i.useState(!1),[q,te]=i.useState(null),[Z,K]=i.useState(!1),[A,I]=i.useState(!1),[$,N]=i.useState(void 0),[G,xe]=i.useState(!1),[Se,je]=i.useState(!1),[se,Ve]=i.useState("project"),[ee,ce]=i.useState(!1),[ne,re]=i.useState(!1),[J,B]=i.useState(!1),[ye,Ce]=i.useState(!1),[H,ke]=i.useState(!1),[pe,Ae]=i.useState(!1),[Oe,He]=i.useState(!1),dt=!!(w||v||s||r||m||A||G||Se||ee||ne||J||H||ye||M||Z||E||L||pe||Oe),Fe=i.useCallback(()=>a(!0),[]),fe=i.useCallback(()=>a(!1),[]),$e=i.useCallback(()=>o(!0),[]),De=i.useCallback(jt=>{c(jt),o(!0)},[]),ot=i.useCallback(()=>{const jt=n[0];jt&&(u(jt.id),o(!0))},[n]),Be=i.useCallback(jt=>{u(jt),o(!0)},[]),we=i.useCallback(()=>{o(!1),c(null),u(void 0)},[]),Q=i.useCallback(jt=>{p(jt),h(!0)},[]),_e=i.useCallback(jt=>{x(jt),h(!0)},[]),lt=i.useCallback(()=>{h(!1),p(null),x(void 0)},[]),ht=i.useCallback((jt,ae="definition",Le)=>{b(jt),S(ae),C(Le?.origin??null)},[]),mt=i.useCallback(jt=>{b(jt),S("changes"),C(null)},[]),xt=i.useCallback(jt=>{b(ae=>ae&&{...ae,...jt})},[]),Ie=i.useCallback(()=>{b(null),C(null)},[]),Ue=i.useCallback(jt=>{U(jt),j(!0)},[]),pt=i.useCallback(()=>{j(!1),U(void 0)},[]),oe=i.useCallback(()=>R(!0),[]),le=i.useCallback(()=>R(!1),[]),ge=i.useCallback(()=>F(!0),[]),Ne=i.useCallback(()=>F(!1),[]),ue=i.useCallback(jt=>{te(jt??null),O(!0)},[]),qe=i.useCallback(()=>{O(!1),te(null)},[]),me=i.useCallback(()=>K(!0),[]),tt=i.useCallback(()=>K(!1),[]),Ct=i.useCallback(()=>{I(jt=>!jt)},[]),wt=i.useCallback(()=>{I(!1),N(void 0)},[]),$t=i.useCallback(()=>xe(!0),[]),Vt=i.useCallback(()=>xe(!1),[]),Mt=i.useCallback(()=>je(!0),[]),Dt=i.useCallback(()=>je(!1),[]),Qt=i.useCallback(jt=>{Ve(jt)},[]),Kt=i.useCallback(()=>ce(!0),[]),Bt=i.useCallback(()=>ce(!1),[]),on=i.useCallback(()=>re(!0),[]),fn=i.useCallback(()=>re(!1),[]),Jt=i.useCallback(()=>B(!0),[]),an=i.useCallback(()=>B(!1),[]),zt=i.useCallback(()=>Ce(!0),[]),en=i.useCallback(()=>Ce(!1),[]),Zt=i.useCallback(()=>ke(!0),[]),dn=i.useCallback(()=>ke(!1),[]),ve=i.useCallback(async(jt,ae)=>{ke(!1),N(ae),I(!0)},[]),ze=i.useCallback(()=>Ae(!0),[]),We=i.useCallback(()=>Ae(!1),[]),Ze=i.useCallback(()=>He(!0),[]),Ye=i.useCallback(()=>He(!1),[]),It=i.useCallback((jt,ae)=>{ae(`Created ${jt.id} from planning mode`,"success"),o(!1),c(null)},[]),St=i.useCallback((jt,ae)=>{const Le=jt.map(At=>At.id).join(", ");ae(`Created ${Le} from planning mode`,"success"),o(!1),c(null)},[]),Ht=i.useCallback((jt,ae)=>{const Le=jt.map(At=>At.id).join(", ");ae(`Created ${Le} from subtask breakdown`,"success"),h(!1),p(null)},[]);return{newTaskModalOpen:s,isPlanningOpen:r,planningInitialPlan:l,planningResumeSessionId:d,isSubtaskOpen:m,subtaskInitialDescription:f,subtaskResumeSessionId:g,detailTask:w,detailTaskInitialTab:y,detailTaskOrigin:k,settingsOpen:v,settingsInitialSection:P,schedulesOpen:E,githubImportOpen:L,usageOpen:M,usageAnchorRect:q,systemStatsOpen:Z,terminalOpen:A,terminalInitialCommand:$,filesOpen:G,todosOpen:Se,fileBrowserWorkspace:se,activityLogOpen:ee,gitManagerOpen:ne,workflowStepsOpen:J,agentsOpen:ye,scriptsOpen:H,setupWizardOpen:pe,modelOnboardingOpen:Oe,anyModalOpen:dt,openNewTask:Fe,closeNewTask:fe,openPlanning:$e,openPlanningWithInitialPlan:De,resumePlanning:ot,openPlanningWithSession:Be,closePlanning:we,openSubtaskBreakdown:Q,openSubtaskWithSession:_e,closeSubtask:lt,openDetailTask:ht,openDetailWithChangesTab:mt,updateDetailTask:xt,closeDetailTask:Ie,openSettings:Ue,closeSettings:pt,openSchedules:oe,closeSchedules:le,openGitHubImport:ge,closeGitHubImport:Ne,openUsage:ue,closeUsage:qe,openSystemStats:me,closeSystemStats:tt,toggleTerminal:Ct,closeTerminal:wt,openFiles:$t,closeFiles:Vt,openTodos:Mt,closeTodos:Dt,setFileWorkspace:Qt,openActivityLog:Kt,closeActivityLog:Bt,openGitManager:on,closeGitManager:fn,openWorkflowSteps:Jt,closeWorkflowSteps:an,openAgents:zt,closeAgents:en,openScripts:Zt,closeScripts:dn,runScript:ve,openSetupWizard:ze,closeSetupWizard:We,openModelOnboarding:Ze,closeModelOnboarding:Ye,onPlanningTaskCreated:It,onPlanningTasksCreated:St,onSubtaskTasksCreated:Ht}}function LO(e){const[n,s]=i.useState(2),[a,r]=i.useState("."),[o,l]=i.useState(!0),[c,d]=i.useState(!1),[u,m]=i.useState(!1),[h,f]=i.useState(void 0),[p,g]=i.useState(!1),[x,w]=i.useState(!1),[b,y]=i.useState(!1),[S,k]=i.useState({}),[C,v]=i.useState(!1),[j,P]=i.useState(!1),[U,E]=i.useState(!1),[R,L]=i.useState(!1),[F,M]=i.useState(!0),O=i.useCallback(async()=>{const[I,$]=await Promise.allSettled([sj(e),Zl(e)]);if(I.status==="fulfilled"&&(s(I.value.maxConcurrent),r(I.value.rootDir)),$.status==="fulfilled"){const N=$.value;l(!!N.autoMerge),d(!!N.globalPause),m(!!N.enginePaused),w(!!N.prAuthAvailable),f(N.taskStuckTimeoutMs),g(N.showQuickChatFAB===!0),k(N.experimentalFeatures??{});const G=N.experimentalFeatures??{};v(G.insights===!0),P(G.memoryView===!0),E(G.devServerView===!0||G.devServer===!0),L(G.todoView===!0);const xe=N.autoReloadOnVersionChange!==!1;M(xe),mc(xe)}y(!0)},[e]);i.useEffect(()=>{y(!1),k({}),v(!1),P(!1),E(!1),L(!1),O()},[O]);const q=i.useCallback(async()=>{const I=!o;l(I);try{await Do({autoMerge:I},e)}catch{l(!I)}},[o,e]),te=i.useCallback(async()=>{const I=!c;d(I);try{await Do({globalPause:I,globalPauseReason:I?"manual":void 0},e)}catch{d(!I)}},[c,e]),Z=i.useCallback(async()=>{const I=!u;m(I);try{await Do({enginePaused:I},e)}catch{m(!I)}},[u,e]),K=i.useCallback(async()=>{const I=!p;g(I);try{await Do({showQuickChatFAB:I},e)}catch{g(!I)}},[p,e]),A=i.useCallback(async()=>{const I=!F;M(I),mc(I);try{await kn({autoReloadOnVersionChange:I})}catch{M(!I),mc(!I)}},[F]);return{maxConcurrent:n,rootDir:a,autoMerge:o,globalPaused:c,enginePaused:u,taskStuckTimeoutMs:h,showQuickChatFAB:p,prAuthAvailable:x,settingsLoaded:b,experimentalFeatures:S,insightsEnabled:C,memoryEnabled:j,devServerEnabled:U,todosEnabled:R,autoReloadOnVersionChange:F,toggleAutoMerge:q,toggleGlobalPause:te,toggleEnginePause:Z,toggleShowQuickChatFAB:K,toggleAutoReloadOnVersionChange:A,refresh:O}}function OO(e){const{projectId:n,projects:s,projectsLoading:a,currentProject:r,setCurrentProject:o,addToast:l,openTaskDetail:c,closeTaskDetail:d}=e,u=i.useRef(!1),m=i.useRef(!1),h=i.useRef(null);return i.useEffect(()=>{if(!m.current){const b=window.location.pathname.match(/^\/tasks\/([A-Z]+-\d+)\/?$/);if(b){const y=b[1];if(/^[A-Z]+-\d+$/.test(y)){const S=new URLSearchParams(window.location.search);S.set("task",y);const k=S.toString(),C=window.history.state??{};window.history.replaceState(C,"",k?`/?${k}`:"/"),m.current=!0}}}const p=new URLSearchParams(window.location.search),g=p.get("project"),x=p.get("task");if(!x||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,Sa(x,g??n).then(b=>{c(b),h.current=x}).catch(()=>{l(`Task ${x} not found`,"error")})},[n,s,a,r,o,l,c]),{handleDetailClose:i.useCallback(()=>{if(h.current){const p=new URLSearchParams(window.location.search);p.delete("task");const g=p.toString(),x=window.history.state??{};window.history.replaceState(x,"",g?`${window.location.pathname}?${g}`:window.location.pathname),h.current=null}d()},[d])}}function zO(){const[e,n]=i.useState([]),[s,a]=i.useState([]),[r,o]=i.useState([]),l=i.useRef(s),c=i.useRef(r);i.useEffect(()=>{Os().then(m=>{n(m.models),l.current=m.favoriteProviders,c.current=m.favoriteModels,a(m.favoriteProviders),o(m.favoriteModels)}).catch(()=>{})},[]),i.useEffect(()=>{l.current=s},[s]),i.useEffect(()=>{c.current=r},[r]);const d=i.useCallback(async m=>{const h=l.current,p=h.includes(m)?h.filter(g=>g!==m):[m,...h];l.current=p,a(()=>p);try{await kn({favoriteProviders:p,favoriteModels:c.current})}catch(g){throw l.current=h,a(()=>h),g}},[]),u=i.useCallback(async m=>{const h=c.current,p=h.includes(m)?h.filter(g=>g!==m):[m,...h];c.current=p,o(()=>p);try{await kn({favoriteProviders:l.current,favoriteModels:p})}catch(g){throw c.current=h,o(()=>h),g}},[]);return{availableModels:e,favoriteProviders:s,favoriteModels:r,toggleFavoriteProvider:d,toggleFavoriteModel:u}}function FO({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;uo().then(({providers:d})=>{const u=d.some(h=>h.authenticated);if(d.length>0&&!u||d.length>0&&u)return Pa().then(h=>{const f=!!(h.defaultProvider&&h.defaultModelId);(h.modelOnboardingComplete===!1||h.modelOnboardingComplete===void 0)&&(!u||!f)&&!wr()?l=!0:!u&&!wr()&&(c=!0)})}).then(()=>{if(o.current){r.current=!1;return}l?(ei("onboarding:auto-triggered",{trigger:"first-run"}),s()):c&&(ei("onboarding:auto-triggered",{trigger:"missing-provider"}),a("authentication"))}).catch(()=>{})},[e,n,s,a])}const Zf="kb-update-banner-dismissed";function UO(){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 h=sessionStorage.getItem(Zf)==="true";u(h);let f=!1;return ij().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 m=i.useCallback(()=>{u(!0),sessionStorage.setItem(Zf,"true")},[]);return{updateAvailable:s,latestVersion:r,currentVersion:l,loading:e,dismissed:d,dismiss:m}}const BO=["board","list","graph","agents","missions","chat","documents","research","evals","skills","mailbox","insights","memory","devserver","dev-server"];function HO(e){return e!==null&&BO.includes(e)}function kd(e){return e!==null&&(HO(e)||rr(e))}const qO=Ro("roadmap-planner","roadmaps");function eg(e){return e==="devserver"?"dev-server":e}function tg(e){return e!=="roadmaps"?"board":_0("roadmap-planner","roadmaps")?qO:"board"}function VO(e){const{projectsLoading:n,projectsError:s,currentProjectLoading:a,currentProject:r,projectsLength:o,setupWizardOpen:l,openSetupWizard:c,themeMode:d,setThemeMode:u}=e,[m,h]=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=An("kb-dashboard-task-view");return b==="roadmaps"?tg(b):kd(b)?b:"board"}),g=i.useRef(!1);i.useEffect(()=>{window.localStorage.setItem("kb-dashboard-view-mode",m)},[m]),i.useEffect(()=>{const b=An("kb-dashboard-task-view",r?.id);if(b==="roadmaps")p(tg(b));else if(kd(b)){const y=!g.current&&b==="devserver";p(y?"devserver":eg(b))}else p("board");r?.id&&(g.current=!0)},[r?.id]),i.useEffect(()=>{ss("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&&kd(b)&&p(eg(b))},[]),i.useEffect(()=>{n||a||r&&m==="overview"&&h("project")},[n,a,r,m]),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 x=i.useCallback(b=>{p(b)},[]),w=i.useCallback(()=>{const b=["dark","light","system"],y=b.indexOf(d),S=b[(y+1)%b.length];u(S)},[d,u]);return{viewMode:m,setViewMode:h,taskView:f,setTaskView:p,handleChangeTaskView:x,handleToggleTheme:w}}function WO(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 h=d.type==="modal"?d.close:d.revert,f=c.type==="modal"?c.close:c.revert;if(h===f)return}s.current.push(c);const u=s.current.length,m=typeof window<"u"&&window.history.state?window.history.state:{};window.history.pushState({...m,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,m=s.current.length;if(u>=m)return;const h=m-u;if(!(h<=0)){a.current=!0;try{for(let f=0;f<h;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 jd=new Map,KO=6e4;function GO(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),m=i.useCallback(()=>{const h=e??"default";jd.delete(h),d(f=>f+1)},[e]);return i.useEffect(()=>{const h=e??"default";let f=!1;async function p(){const g=jd.get(h);if(g&&Date.now()<g.expiresAt){if(f)return;s(g.views),r(!1);return}u.current||r(!0),l(null);try{const x=await H1(e);if(f)return;jd.set(h,{views:x,expiresAt:Date.now()+KO}),s(x)}catch(x){if(f)return;l(x instanceof Error?x.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:m}),[n,a,o,m])}function JO({taskView:e,context:n}){return t.jsx(M0,{viewId:e,context:n})}let ng=!1;function YO(e){return function(){return`Bundled plugin view unavailable: ${e}`}}async function sg(e,n){try{const a=(await import(e))[n];if(a)return{default:a}}catch{}return{default:YO(e)}}function gv(){ng||(ng=!0,Km("fusion-plugin-dependency-graph","graph",i.lazy(()=>sg("@fusion-plugin-examples/dependency-graph/dashboard-view","DependencyGraphDashboardView"))),Km("roadmap-planner","roadmaps",i.lazy(()=>sg("@fusion-plugin-examples/roadmap/dashboard-view","RoadmapDashboardView"))))}function QO(e){const{setCurrentProject:n,clearCurrentProject:s,setViewMode:a,currentProject:r,refreshProjects:o,toggleFavoriteProvider:l,toggleFavoriteModel:c,addToast:d,openSettings:u,openSetupWizard:m,closeSetupWizard:h,closeModelOnboarding:f}=e,p=i.useCallback(P=>{n(P),a("project")},[n,a]),g=i.useCallback(()=>{s(),a("overview")},[s,a]),x=i.useCallback(()=>{u()},[u]),w=i.useCallback(()=>{m()},[m]),b=i.useCallback(P=>{h(),n(P),a("project"),d(`Project ${P.name} registered successfully`,"success"),o()},[h,n,a,d,o]),y=i.useCallback(()=>{f()},[f]),S=i.useCallback(async P=>{try{await _S(P.id),d(`Project ${P.name} paused`,"success"),await o()}catch{d(`Failed to pause project ${P.name}`,"error")}},[d,o]),k=i.useCallback(async P=>{try{await MS(P.id),d(`Project ${P.name} resumed`,"success"),await o()}catch{d(`Failed to resume project ${P.name}`,"error")}},[d,o]),C=i.useCallback(async P=>{try{await Og(P.id),d(`Project ${P.name} removed`,"success"),r?.id===P.id&&(s(),a("overview")),await o()}catch{d(`Failed to remove project ${P.name}`,"error")}},[r,s,a,d,o]),v=i.useCallback(async P=>{try{await l(P)}catch{d("Failed to update favorites","error")}},[l,d]),j=i.useCallback(async P=>{try{await c(P)}catch{d("Failed to update model favorites","error")}},[c,d]);return{handleSelectProject:p,handleViewAllProjects:g,handleOpenSettings:x,handleAddProject:w,handleSetupComplete:b,handleModelOnboardingComplete:y,handlePauseProject:S,handleResumeProject:k,handleRemoveProject:C,handleToggleFavorite:v,handleToggleModelFavorite:j}}function XO(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]),m=i.useCallback(p=>{s(p),r(p,l)},[l,s,r]),h=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:m,handleSubtaskTasksCreated:h,handleGitHubImport:f}}function ZO(e,n){const{projectId:s,searchQuery:a}=n??{},[r,o]=i.useState([]),[l,c]=i.useState([]),[d,u]=i.useState(null),[m,h]=i.useState(!1),[f,p]=i.useState(null),g=i.useRef(null),x=i.useCallback(async()=>{if(!e){o([]),c([]),u(null),h(!1),p(null);return}g.current?.abort();const b=new AbortController;g.current=b,h(!0),p(null);try{const y=[Q1(e),X1(e)];s&&(y.push(Z1(e,s,a)),y.push(e0(e,s)));const S=await Promise.allSettled(y);if(b.signal.aborted)return;const k=S[0],C=S[1];if(k.status==="rejected"){p(`Failed to fetch node health: ${k.reason}`),h(!1);return}if(u(k.value),C.status==="rejected"){p(`Failed to fetch projects: ${C.reason}`),h(!1);return}if(o(C.value),s&&S[2]){const v=S[2];if(v.status==="rejected"){p(`Failed to fetch tasks: ${v.reason}`),h(!1);return}v.status==="fulfilled"&&c(v.value)}h(!1)}catch(y){b.signal.aborted||(p(y instanceof Error?y.message:"Unknown error"),h(!1))}},[e,s,a]);i.useEffect(()=>(x(),()=>{g.current?.abort()}),[x]);const w=i.useCallback(()=>{x()},[x]);return{projects:r,tasks:l,health:d,loading:m,error:f,refresh:w}}function ez(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 ii(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 tz="fusion-dashboard-current-node",bv=i.createContext(null);function nz({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 m=!1;async function h(){try{const f=await Pa();if(m)return;l.current=f.dashboardCurrentNodeId;const p=f.dashboardCurrentNodeId;if(p&&(o.current=!0),!p)try{const g=localStorage.getItem(tz);if(g){const x=JSON.parse(g);x?.id&&x?.type==="remote"&&(l.current=x.id,await kn({dashboardCurrentNodeId:x.id}).catch(()=>{}))}}catch{}}catch{}finally{m||r(!1)}}return h(),()=>{m=!0}},[]),i.useEffect(()=>{if(!a)if(n&&n.type==="remote"&&n.id){const m=n.id;l.current!==m&&(l.current=m,kn({dashboardCurrentNodeId:m}).catch(()=>{}))}else n===null&&l.current!==void 0&&(l.current=void 0,kn({dashboardCurrentNodeId:void 0}).catch(()=>{}))},[n,a]);const c=i.useCallback(m=>{s(m)},[]),d=i.useCallback(()=>{s(null),l.current=void 0,kn({dashboardCurrentNodeId:void 0}).catch(()=>{})},[]),u={currentNode:n,currentNodeId:n?.id??null,isRemote:n!==null&&n.type==="remote",setCurrentNode:c,clearCurrentNode:d};return t.jsx(bv.Provider,{value:u,children:e})}function sz(){const e=i.useContext(bv);if(e===null)throw new Error("useNodeContext must be used within a NodeProvider");return e}const iz=["shellKind","shellMode","profileId","serverBaseUrl","serverLabel","shellCanOpenConnectionManager","hostKind","mode","connectionId","serverUrl","canOpenConnectionManager"],az=["__FUSION_SHELL_HOST_CONTEXT__","__fusionShellHostContext","__FUSION_SHELL_CONTEXT__"];let ql=null,ig=!1;function rz(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 oz(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 xv(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 lz(e){return e==="local"||e==="remote"?e:void 0}function vv(e){const n=lz(e.mode),s=typeof e.connectionId=="string"&&e.connectionId.trim()?e.connectionId:void 0,a=oz(e.serverUrl),r=rz(e.canOpenConnectionManager);return{kind:e.kind,...n?{mode:n}:{},...s?{connectionId:s}:{},...a?{serverUrl:a}:{},...r!==void 0?{canOpenConnectionManager:r}:{}}}function cz(e){for(const n of az){const s=e[n];if(!s||typeof s!="object")continue;const a=s,r=xv(a.kind??a.shellKind??a.hostKind);if(r)return r==="browser"?{kind:r}:vv({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 dz(e){let n;try{n=new URL(e.location.href)}catch{return null}const s=n.searchParams,a=xv(s.get("hostKind")??s.get("kind")??s.get("shellKind"));return a?a==="browser"?{kind:a}:vv({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 uz(e){try{const n=new URL(e.location.href);let s=!1;for(const r of iz)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 mz(e=window){const n=cz(e);if(n)return n;const s=dz(e);return s||(typeof e.fusionAPI<"u"?{kind:"desktop-shell"}:{kind:"browser"})}function yv(e=window){return!ig&&typeof window<"u"&&(ql=mz(e),uz(e),ig=!0),ql??{kind:"browser"}}function hz(){return ql||(typeof window>"u"?{kind:"browser"}:yv(window))}const pz={kind:"browser"},wv=i.createContext({host:pz,isNativeShell:!1,kind:"browser"});function fz(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 gz({children:e}){const n=i.useMemo(()=>fz(hz()),[]);return t.jsx(wv.Provider,{value:n,children:e})}function bz(){return i.useContext(wv)}function xz(e,n){const s=new URL(e);return n&&s.searchParams.set("rt",n),s.toString()}function vz({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(""),[m,h]=i.useState(""),[f,p]=i.useState(null),[g,x]=i.useState(!1),[w,b]=i.useState(!1),y=s.host==="desktop-shell";i.useEffect(()=>{y&&o(s.desktopMode??"remote")},[y,s.desktopMode]);const S=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),x(!0);try{const k=await n.startQrScan();u(k.serverUrl),h(k.authToken??"")}catch(k){p(k.message)}finally{x(!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:k=>c(k.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:k=>u(k.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:m,onChange:k=>h(k.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:!S||w,onClick:async()=>{p(null),b(!0);try{if(y&&r==="local"){await n.setDesktopMode("local"),a();return}const k=await n.saveProfile({name:l.trim()||"Remote Server",serverUrl:d,authToken:m||null});if(y&&await n.setDesktopMode("remote"),await n.setActiveProfile(k.id),typeof window<"u"&&s.host!=="web"){window.location.href=xz(k.serverUrl,k.authToken??null);return}a()}catch(k){p(k.message)}finally{b(!1)}},children:w?"Saving…":"Continue"})})]})}):null}function yz({open:e,shellApi:n,shellState:s,onClose:a}){const r=i.useMemo(()=>s.profiles.find(v=>v.id===s.activeProfileId)??null,[s.activeProfileId,s.profiles]),[o,l]=i.useState(null),[c,d]=i.useState({}),[u,m]=i.useState(null),[h,f]=i.useState(null);if(!e)return null;const p=o==="__new__",g=p?null:s.profiles.find(v=>v.id===o)??r,x=c.name??g?.name??"",w=c.serverUrl??g?.serverUrl??"",b=c.authToken??g?.authToken??"",y=()=>{l(null),d({}),f(null)},S=async()=>{f(null);try{const v=new URL(w.trim());if(!/^https?:$/.test(v.protocol))throw new Error("Server URL must use http or https");const j=await n.saveProfile({id:p?void 0:o??g?.id,name:x||"Remote Server",serverUrl:w,authToken:b||null});await n.setActiveProfile(j.id),l(j.id),d({})}catch(v){f(v.message)}},k=async()=>{f(null);try{const v=await n.startQrScan();l("__new__"),d({name:"",serverUrl:v.serverUrl,authToken:v.authToken??""})}catch(v){f(v.message)}},C=async()=>{u&&(await n.deleteProfile(u.id),m(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 k(),children:"Scan QR"})]})]}):s.profiles.map(v=>t.jsxs("div",{className:"card native-shell-connection-manager__profile",children:[t.jsxs("div",{children:[t.jsx("strong",{children:v.name}),t.jsx("div",{className:"settings-muted",children:v.serverUrl}),v.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 ${v.name}`,onClick:()=>{l(v.id),d(v)},children:"Edit"}),t.jsx("button",{type:"button",className:"btn btn-sm","aria-label":`Use ${v.name}`,onClick:()=>void n.setActiveProfile(v.id),children:"Use"}),t.jsx("button",{type:"button",className:"btn btn-sm btn-danger","aria-label":`Delete ${v.name}`,onClick:()=>m(v),children:"Delete"})]})]},v.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 k(),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:x,onChange:v=>d(j=>({...j,name:v.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:w,onChange:v=>d(j=>({...j,serverUrl:v.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:v=>d(j=>({...j,authToken:v.target.value}))}),h&&t.jsx("p",{className:"form-error",role:"alert",children:h})]}),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:()=>m(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 S(),disabled:!w.trim(),children:"Save"})]})]})})}function wz(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 ag({status:e,onError:n}){if(e.hostKind==="browser"||!e.available)return null;const s=wz(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 kz(e){if(e)try{return new URL(e).origin}catch{return}}function jz(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 Nz(e){if(!e?.getState)return null;try{return await e.getState()}catch{return null}}async function Sz(e,n=window){const s=n.fusionAPI,a=n.fusionShell,r=await Nz(a),o=r?jz(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=kz(o?.serverUrl??(e.kind==="browser"?void 0:e.serverUrl)),m=e.kind==="desktop-shell"&&typeof s?.openConnectionManager=="function",h=e.kind==="mobile-shell"&&typeof a?.openConnectionManager=="function",f=m||h;return{hostKind:e.kind,available:f,...l?{mode:l}:{},...c?{profileId:c}:{},...d?{profileLabel:d}:{},...u?{serverOrigin:u}:{},openConnectionManager:async()=>{try{return m?(await s.openConnectionManager?.(),{ok:!0}):h?(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 Cz({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&&(Ik(l),window.location.reload())},[n]),o=i.useCallback(()=>{Tk(),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 Ez=200,_z=i.lazy(()=>xn(()=>import("./AgentsView-B3jYk8Kt.js"),__vite__mapDeps([24,1,3,4,25,15,5,6,26])).then(e=>({default:e.AgentsView}))),Mz=i.lazy(()=>xn(()=>import("./DocumentsView-DNHu1T8K.js"),__vite__mapDeps([27,1,5,6,28])).then(e=>({default:e.DocumentsView}))),Az=i.lazy(()=>xn(()=>import("./InsightsView-vp0RE8Mg.js"),__vite__mapDeps([29,1,22,5,6,30])).then(e=>({default:e.InsightsView}))),Pz=i.lazy(()=>xn(()=>import("./ResearchView-BhWqfdV0.js"),__vite__mapDeps([31,1,5,6,32])).then(e=>({default:e.ResearchView}))),Rz=i.lazy(()=>xn(()=>import("./EvalsView-CpRobtDi.js"),__vite__mapDeps([33,1,5,6,34])).then(e=>({default:e.EvalsView}))),Iz=i.lazy(()=>xn(()=>import("./NodesView-DMj6HGeC.js"),__vite__mapDeps([35,1,17,25,5,6,36])).then(e=>({default:e.NodesView}))),Tz=i.lazy(()=>xn(()=>import("./ChatView-DhPkiEGs.js"),__vite__mapDeps([37,1,5,6,38])).then(e=>({default:e.ChatView}))),$z=i.lazy(()=>xn(()=>import("./SkillsView-BdELqTy7.js"),__vite__mapDeps([39,1,5,6,40])).then(e=>({default:e.SkillsView}))),Dz=i.lazy(()=>xn(()=>import("./MemoryView-PSc5lGJt.js"),__vite__mapDeps([41,1,20,21,5,6,42])).then(e=>({default:e.MemoryView}))),Lz=i.lazy(()=>xn(()=>import("./DevServerView-DyGDEiBP.js"),__vite__mapDeps([43,1,5,6,44])).then(e=>({default:e.DevServerView})));i.lazy(()=>xn(()=>import("./TodoView-DFNGBDNV.js"),__vite__mapDeps([11,1,5,6,12])).then(e=>({default:e.TodoView})));function Oz(){(typeof window<"u"&&window.requestIdleCallback||(n=>setTimeout(n,200)))(()=>{xn(()=>import("./AgentsView-B3jYk8Kt.js"),__vite__mapDeps([24,1,3,4,25,15,5,6,26])),xn(()=>import("./DocumentsView-DNHu1T8K.js"),__vite__mapDeps([27,1,5,6,28])),xn(()=>import("./InsightsView-vp0RE8Mg.js"),__vite__mapDeps([29,1,22,5,6,30])),xn(()=>import("./ResearchView-BhWqfdV0.js"),__vite__mapDeps([31,1,5,6,32])),xn(()=>import("./EvalsView-CpRobtDi.js"),__vite__mapDeps([33,1,5,6,34])),xn(()=>import("./NodesView-DMj6HGeC.js"),__vite__mapDeps([35,1,17,25,5,6,36])),xn(()=>import("./ChatView-DhPkiEGs.js"),__vite__mapDeps([37,1,5,6,38])),xn(()=>import("./SkillsView-BdELqTy7.js"),__vite__mapDeps([39,1,5,6,40])),xn(()=>import("./MemoryView-PSc5lGJt.js"),__vite__mapDeps([41,1,20,21,5,6,42])),xn(()=>import("./DevServerView-DyGDEiBP.js"),__vite__mapDeps([43,1,5,6,44])),xn(()=>import("./TodoView-DFNGBDNV.js"),__vite__mapDeps([11,1,5,6,12]))})}gv();const Nd="kb-setup-warning-dismissed",zz="kb-chat-active-session",rg="kb-dashboard-working-branch-filter",og="kb-dashboard-base-branch-filter",lg="__fusion:no-branch__",kv="fusion:approval-banner-dismissed";function Fz(e,n){return e==="awaiting-approval"&&n!=="awaiting-approval"}function cg(e){if(!e)return 0;const n=Date.parse(e);return Number.isFinite(n)?n:0}function Uz(){if(typeof window>"u")return new Map;try{const e=window.localStorage.getItem(kv);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 dg(e){if(!(typeof window>"u"))try{const n={};for(const[s,a]of e)n[s]=a;window.localStorage.setItem(kv,JSON.stringify(n))}catch{}}function Bz(e,n){const s=new URL(e);return n&&s.searchParams.set("rt",n),s.toString()}function Hz(e,n,s){return!n||s||e.host==="web"?!1:e.host==="mobile-shell"?!e.activeProfileId:e.desktopMode==="local"?!1:!e.activeProfileId}function qz(){const{toasts:e,addToast:n,removeToast:s}=_O(),{shellApi:a,state:r,ready:o,openConnectionManagerSignal:l}=Xx(),c=bz();i.useEffect(()=>{Oz()},[]);const{projects:d,loading:u,error:m,refresh:h}=jO(),{nodes:f}=nc(),{currentNode:p,currentNodeId:g,isRemote:x,setCurrentNode:w,clearCurrentNode:b}=sz(),{currentProject:y,setCurrentProject:S,clearCurrentProject:k,loading:C}=CO(d,{nodeId:g}),{hasAiProvider:v,hasGithub:j,loading:P,hasWarnings:U}=Gx(y?.id),{updateAvailable:E,latestVersion:R,currentVersion:L,dismissed:F,dismiss:M}=UO();i.useEffect(()=>{if(g&&!p&&f.length>0){const Ke=f.find(Rt=>Rt.id===g);if(Ke){w(Ke);return}}g&&f.length>0&&(f.some(Rt=>Rt.id===g)||b())},[g,p,f,w,b]);const[O,q]=i.useState(""),[te,Z]=i.useState(""),[K,A]=i.useState("");i.useEffect(()=>{Z(An(rg,y?.id)??""),A(An(og,y?.id)??"")},[y?.id]);const I=i.useCallback(Ke=>{Z(Ke),ss(rg,Ke,y?.id)},[y?.id]),$=i.useCallback(Ke=>{A(Ke),ss(og,Ke,y?.id)},[y?.id]),N=ZO(g,{projectId:y?.id,searchQuery:O||void 0});ez(g);const G=x&&N.projects.length>0?N.projects:d,{themeMode:xe,colorTheme:Se,dashboardFontScalePct:je,setThemeMode:se,setColorTheme:Ve,setDashboardFontScalePct:ee}=$O(),{sessions:ce,generating:ne,needsInput:re,planningSessions:J,dismissSession:B}=pO(y?.id),ye=ce.filter(Ke=>Ke.status==="awaiting_input"||Ke.status==="error"),Ce=bO(),H=DO({projectId:y?.id,planningSessions:J}),pe=Ys()==="mobile",{pushNav:Ae,replaceCurrent:Oe}=WO({enabled:!0}),{viewMode:He,setViewMode:dt,taskView:Fe,handleChangeTaskView:fe}=VO({projectsLoading:u,projectsError:m,currentProjectLoading:C,currentProject:y,projectsLength:d.length,setupWizardOpen:H.setupWizardOpen,openSetupWizard:H.openSetupWizard,themeMode:xe,setThemeMode:se}),{views:$e}=GO(y?.id),De=i.useMemo(()=>{const Ke=$e.find(Rt=>Rt.pluginId==="fusion-plugin-dependency-graph"&&Rt.view.viewId==="graph");return Ke?`plugin:${Ke.pluginId}:${Ke.view.viewId}`:null},[$e]),ot=i.useCallback(Ke=>{Ke==="missions"&&(Lt(void 0),Me(void 0),gt(void 0));const Rt=Fe;fe(Ke),Rt!==Ke&&Ae({type:"view",revert:()=>fe(Rt)})},[fe,Fe,Ae]),Be=Fe==="board"||Fe==="list",{tasks:we,createTask:Q,moveTask:_e,pauseTask:lt,deleteTask:ht,mergeTask:mt,retryTask:xt,resetTask:Ie,updateTask:Ue,duplicateTask:pt,archiveTask:oe,unarchiveTask:le,archiveAllDone:ge,loadArchivedTasks:Ne,ingestCreatedTasks:ue,lastFetchTimeMs:qe}=vO({...y?{projectId:y.id}:{},searchQuery:O||void 0,sseEnabled:Be}),me=x&&N.tasks.length>0?N.tasks:we,[tt,Ct]=i.useState(!1),[wt,$t]=i.useState(0),Vt=i.useRef(performance.now()),Mt=i.useRef(!1),Dt=i.useRef(!1),Qt=i.useMemo(()=>u?"projects":C?"project":"tasks",[u,C]);i.useEffect(()=>{if(!u&&!Mt.current){Mt.current=!0;const Ke=`projects loaded at ${Math.round(performance.now()-Vt.current)}ms from mount`;console.log(`[App] ${Ke}`)}if(!C&&!Dt.current){Dt.current=!0;const Ke=`current-project resolved at ${Math.round(performance.now()-Vt.current)}ms from mount`;console.log(`[App] ${Ke}`)}},[u,C]),i.useEffect(()=>{if(tt||u||C)return;const Ke=performance.now(),Rt=window.setTimeout(()=>{const cn=`dashboard ready at ${Math.round(performance.now()-Vt.current)}ms from mount (settle delay=${Math.round(performance.now()-Ke)}ms)`;console.log(`[App] ${cn}`),Ct(!0)},Ez);return()=>{window.clearTimeout(Rt)}},[tt,u,C]);const{keyboardOpen:Kt}=Wi({enabled:pe}),Bt=pe&&Kt&&!H.anyModalOpen;vi(Bt);const[on,fn]=i.useState(0),[Jt,an]=i.useState(0),[zt,en]=i.useState(!1),[Zt,dn]=i.useState(null),ve=i.useRef(new Map),ze=i.useRef(new Set),We=i.useRef(Uz()),Ze=i.useCallback(()=>{Hg(y?.id).then(Ke=>{fn(Ke.unreadCount),an(Ke.pendingApprovalCount??0)}).catch(Ke=>{console.warn("[App] Failed to fetch mailbox unread count:",Ke)})},[y?.id]);i.useEffect(()=>{const Ke=new Map,Rt=new Set;for(const cn of we)Ke.set(cn.id,cn.status),cn.status==="awaiting-approval"&&Rt.add(`task:${cn.id}`);ve.current=Ke,ze.current=Rt},[we]),i.useEffect(()=>{Ze();const Ke=new URLSearchParams;y?.id&&Ke.set("projectId",y.id);const Rt=Ke.size>0?`?${Ke.toString()}`:"",cn=as=>{const In=We.current.get(as.dedupeKey);In!==void 0&&as.updatedAtMs<=In||dn(as)};return ii(`/api/events${Rt}`,{onReconnect:Ze,events:{"message:sent":Ze,"message:received":Ze,"message:read":Ze,"message:deleted":Ze,"approval:requested":as=>{Ze();try{const In=JSON.parse(as.data),$s=In.id?`approval:${In.id}`:In.taskId?`task:${In.taskId}`:void 0;if(!$s||ze.current.has($s))return;ze.current.add($s),cn({dedupeKey:$s,updatedAtMs:cg(In.updatedAt??In.createdAt)})}catch{}},"approval:updated":Ze,"approval:decided":Ze,"task:updated":as=>{try{const In=JSON.parse(as.data);if(!In?.id)return;const $s=`task:${In.id}`,V=ve.current.get(In.id);if(ve.current.set(In.id,In.status),In.status!=="awaiting-approval"){ze.current.delete($s),We.current.delete($s),dg(We.current);return}if(ze.current.has($s))return;Fz(In.status,V)&&(ze.current.add($s),cn({dedupeKey:$s,updatedAtMs:cg(In.updatedAt)}),Ze())}catch{}}}})},[y?.id,Ze]),i.useEffect(()=>{Fe==="chat"&&en(!1)},[Fe]),i.useEffect(()=>{const Ke=new URLSearchParams;y?.id&&Ke.set("projectId",y.id);const Rt=Ke.size>0?`?${Ke.toString()}`:"";return ii(`/api/events${Rt}`,{events:{"chat:message:added":cn=>{try{const as=JSON.parse(cn.data),In=An(zz,y?.id);if(!In||as.role!=="assistant"||Fe==="chat"||as.sessionId!==In||as.projectId&&y?.id&&as.projectId!==y.id)return;en(!0)}catch{}}}})},[y?.id,Fe]);const Ye=i.useMemo(()=>Array.from(new Set(me.map(Ke=>Ke.branch?.trim()).filter(Ke=>!!(Ke&&Ke.length>0)))).sort((Ke,Rt)=>Ke.localeCompare(Rt)),[me]),It=i.useMemo(()=>Array.from(new Set(me.map(Ke=>Ke.baseBranch?.trim()).filter(Ke=>!!(Ke&&Ke.length>0)))).sort((Ke,Rt)=>Ke.localeCompare(Rt)),[me]),St=i.useMemo(()=>me.filter(Ke=>{const Rt=Ke.branch?.trim()??"",cn=Ke.baseBranch?.trim()??"";if(te===lg){if(Rt.length>0)return!1}else if(te.length>0&&Rt!==te)return!1;if(K===lg){if(cn.length>0)return!1}else if(K.length>0&&cn!==K)return!1;return!0}),[me,te,K]),[Ht,jt]=i.useState(!1),[ae,Le]=i.useState(!1),[At,Lt]=i.useState(void 0),[Ft,Me]=i.useState(void 0),[ct,gt]=i.useState(void 0),[_t,Yt]=i.useState(!1),[Xt,Te]=i.useState(!1),[Je,Nt]=i.useState(()=>An(Nd,y?.id)==="true");i.useEffect(()=>{Nt(An(Nd,y?.id)==="true")},[y?.id]),i.useEffect(()=>{const Ke=()=>{Te(!0)};return window.addEventListener(Td,Ke),()=>{window.removeEventListener(Td,Ke)}},[]);const Ut=i.useCallback(()=>{ss(Nd,"true",y?.id),Nt(!0)},[y?.id]),{maxConcurrent:tn,autoMerge:Xn,globalPaused:be,enginePaused:it,taskStuckTimeoutMs:rt,showQuickChatFAB:at,prAuthAvailable:ut,settingsLoaded:vt,experimentalFeatures:ie,insightsEnabled:st,memoryEnabled:Gt,devServerEnabled:Cn,todosEnabled:fs,toggleAutoMerge:On,toggleGlobalPause:jn,toggleEnginePause:zn,refresh:hn}=LO(y?.id),Et=ie.skillsView===!0,En=ie.nodesView===!0,yn=ie.researchView===!0,ls=ie.evalsView===!0,cs=ie.agentOnboarding===!0,Hn=!0,qn=i.useCallback(()=>{H.closeSettings(),$t(Ke=>Ke+1),hn()},[H,hn]);i.useEffect(()=>{if(vt&&!rr(Fe)){if(Fe==="graph"&&!De){fe("board");return}Fe==="skills"&&!Et&&fe("board"),Fe==="insights"&&!st&&fe("board"),Fe==="memory"&&!Gt&&fe("board"),(Fe==="devserver"||Fe==="dev-server")&&!Cn&&fe("board"),Fe==="research"&&!yn&&fe("board"),Fe==="evals"&&!ls&&fe("board")}},[Fe,vt,Et,st,fe,Hn,Gt,Cn,yn,ls,De]),i.useEffect(()=>{Ht&&!En&&jt(!1)},[Ht,En]);const{availableModels:wn,favoriteProviders:Zn,favoriteModels:_n,toggleFavoriteProvider:is,toggleFavoriteModel:Ns}=zO();FO({projectId:y?.id,setupWizardOpen:H.setupWizardOpen,openModelOnboarding:H.openModelOnboarding,openSettings:H.openSettings});const{handleSelectProject:es,handleViewAllProjects:ks,handleAddProject:Is,handleSetupComplete:Ss,handleModelOnboardingComplete:X,handlePauseProject:_,handleResumeProject:de,handleRemoveProject:D,handleToggleFavorite:Y,handleToggleModelFavorite:Ee}=QO({setCurrentProject:S,clearCurrentProject:k,setViewMode:dt,currentProject:y,refreshProjects:h,toggleFavoriteProvider:is,toggleFavoriteModel:Ns,addToast:n,openSettings:H.openSettings,openSetupWizard:H.openSetupWizard,closeSetupWizard:H.closeSetupWizard,closeModelOnboarding:H.closeModelOnboarding}),{handleDetailClose:Ge}=OO({projectId:y?.id,projects:d,projectsLoading:u,currentProject:y,setCurrentProject:S,addToast:n,openTaskDetail:H.openDetailTask,closeTaskDetail:H.closeDetailTask}),kt=i.useCallback(async({insightId:Ke,title:Rt,description:cn})=>{await Q({title:Rt,description:cn,column:"triage",source:{sourceType:"dashboard_ui",sourceMetadata:{origin:"insights",insightId:Ke}}})},[Q]),{handleBoardQuickCreate:Tt,handleModalCreate:Pt,handlePlanningTaskCreated:ln,handlePlanningTasksCreated:ts,handleSubtaskTasksCreated:Rn,handleGitHubImport:Fn}=XO({createTask:Q,ingestCreatedTasks:ue,onPlanningTaskCreated:H.onPlanningTaskCreated,onPlanningTasksCreated:H.onPlanningTasksCreated,onSubtaskTasksCreated:H.onSubtaskTasksCreated,addToast:n}),Un=i.useCallback((Ke,Rt)=>{Rt==="changes"?H.openDetailWithChangesTab(Ke):H.openDetailTask(Ke,Rt),Ae({type:"modal",close:H.closeDetailTask})},[H,Ae]),gs=i.useCallback(async Ke=>{try{const Rt=await Sa(Ke,y?.id);H.openDetailTask(Rt,"logs"),Ae({type:"modal",close:H.closeDetailTask})}catch(Rt){n(`Failed to open task logs: ${Rt.message}`,"error")}},[H,y?.id,n,Ae]),[Ln,Vn]=i.useState([]);i.useEffect(()=>{let Ke=!1;return _o(y?.id).then(Rt=>{Ke||Vn(Rt)}).catch(()=>{Ke||Vn([])}),()=>{Ke=!0}},[y?.id]);const Wn=i.useMemo(()=>new Map(Ln.map(Ke=>[Ke.id,Ke.name])),[Ln]);i.useCallback(()=>{En&&jt(Ke=>!Ke)},[En]);const Kn=i.useCallback(()=>{En&&(Ht?jt(!1):(jt(!0),Ae({type:"view",revert:()=>jt(!1)})))},[En,Ht,Ae]),Bn=i.useCallback((Ke,Rt,cn)=>{H.openDetailTask(Ke,Rt,cn),Ae({type:"modal",close:H.closeDetailTask})},[H,Ae]),Nn=i.useCallback(Ke=>{H.openSettings(Ke),Ae({type:"modal",close:qn})},[H,Ae,qn]),Gn=i.useCallback(()=>{H.openNewTask(),Ae({type:"modal",close:H.closeNewTask})},[H,Ae]),ds=i.useCallback(()=>{H.openPlanning(),Ae({type:"modal",close:H.closePlanning})},[H,Ae]),Ts=i.useCallback(Ke=>{H.openPlanningWithInitialPlan(Ke),Ae({type:"modal",close:H.closePlanning})},[H,Ae]),Ri=i.useCallback(()=>{H.resumePlanning(),Ae({type:"modal",close:H.closePlanning})},[H,Ae]),ca=i.useCallback(Ke=>{H.openSubtaskBreakdown(Ke),Ae({type:"modal",close:H.closeSubtask})},[H,Ae]),ri=i.useCallback(()=>{H.openGitHubImport(),Ae({type:"modal",close:H.closeGitHubImport})},[H,Ae]),Ta=i.useCallback(()=>{H.terminalOpen?H.toggleTerminal():(H.toggleTerminal(),Ae({type:"modal",close:H.closeTerminal}))},[H,Ae]),$a=i.useCallback(()=>{H.openFiles(),Ae({type:"modal",close:H.closeFiles})},[H,Ae]),Qs=i.useCallback(()=>{H.openTodos(),Ae({type:"modal",close:H.closeTodos})},[H,Ae]),oi=i.useCallback(()=>{H.openActivityLog(),Ae({type:"modal",close:H.closeActivityLog})},[H,Ae]),Ii=i.useCallback(()=>{H.openGitManager(),Ae({type:"modal",close:H.closeGitManager})},[H,Ae]),da=i.useCallback(()=>{H.openSystemStats(),Ae({type:"modal",close:H.closeSystemStats})},[H,Ae]),Da=i.useCallback(()=>{H.openSchedules(),Ae({type:"modal",close:H.closeSchedules})},[H,Ae]),La=i.useCallback(()=>{H.openScripts(),Ae({type:"modal",close:H.closeScripts})},[H,Ae]),ua=i.useCallback(()=>{H.openWorkflowSteps(),Ae({type:"modal",close:H.closeWorkflowSteps})},[H,Ae]),ma=i.useCallback(Ke=>{H.openUsage(Ke),Ae({type:"modal",close:H.closeUsage})},[H,Ae]),Ti=i.useCallback(async(Ke,Rt)=>{await H.runScript(Ke,Rt),Oe({type:"modal",close:H.closeTerminal})},[H,Oe]),Oa=i.useCallback(()=>{H.closeSettings(),H.openModelOnboarding(),Oe({type:"modal",close:H.closeModelOnboarding})},[H,Oe]),ha=i.useCallback(()=>{H.setFileWorkspace("project"),H.openFiles()},[H]),Mr=i.useCallback(async()=>{Le(!0);try{await h()}finally{Le(!1)}},[h]),li=i.useCallback(Ke=>{Me(Ke),Lt(void 0),fe("missions")},[fe]),Hs=i.useCallback(Ke=>{Ke.type==="planning"?H.openPlanningWithSession(Ke.id):Ke.type==="subtask"?H.openSubtaskWithSession(Ke.id):Ke.type==="mission_interview"?(Me(void 0),Lt(Ke.id),gt(void 0),fe("missions")):(Ke.type==="milestone_interview"||Ke.type==="slice_interview")&&(Lt(void 0),Me(void 0),gt(Ke.id),fe("missions"))},[fe,H]),za=i.useCallback(()=>{},[]),Fa=i.useCallback(()=>{},[]),[$i,Ua]=i.useState(!1),[Ba,Ha]=i.useState(!1),[yi,pa]=i.useState(null),us=Hz(r,o,$i);i.useEffect(()=>{!a||l===0||Ha(!0)},[a,l]),i.useEffect(()=>{let Ke=!1;return Sz(c.host).then(Rt=>{Ke||pa(Rt)}),()=>{Ke=!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 Ke=r.profiles.find(cn=>cn.id===r.activeProfileId);if(!Ke||typeof window>"u")return;const Rt=Bz(Ke.serverUrl,Ke.authToken??null);window.location.href!==Rt&&(window.location.href=Rt)},[r]);const Ki=!u&&!C&&d.length===0&&!y&&!!m,Cs=()=>{if(Ki)return t.jsx(xL,{errorMessage:m??"Failed to fetch projects",isRetrying:ae,onRetry:Mr,onManageConnection:a?()=>{a.openConnectionManager()}:void 0});if(Ht)return t.jsx("div",{className:"nodes-management-overlay",children:t.jsx(_s,{children:t.jsx(i.Suspense,{fallback:null,children:t.jsx(Iz,{addToast:n,onClose:()=>jt(!1)})})})});if(He==="overview")return t.jsx(_s,{children:t.jsx(tT,{projects:d,loading:u,onSelectProject:es,onAddProject:Is,onPauseProject:_,onResumeProject:de,onRemoveProject:D,nodes:f})});const Ke=Fe==="graph"?De:rr(Fe)?Fe:null;return Ke?t.jsx(_s,{children:t.jsx(JO,{taskView:Ke,context:{projectId:y?.id,tasks:x&&N.tasks.length>0?N.tasks:we,workflowSteps:Ln,openTaskDetail:(Rt,cn)=>Bn(Rt,cn),renderTaskCard:Rt=>t.jsx(ho,{task:Rt,projectId:y?.id,onOpenDetail:cn=>Bn(cn),addToast:n,workflowStepNameLookup:Wn,disableDrag:!0}),addToast:n}})}):Fe==="skills"?!vt||!Et?null:t.jsx(_s,{children:t.jsx(i.Suspense,{fallback:null,children:t.jsx($z,{addToast:n,projectId:y?.id,onClose:()=>fe("board")})})}):Fe==="chat"?t.jsx(_s,{children:t.jsx(i.Suspense,{fallback:null,children:t.jsx(Tz,{addToast:n,projectId:y?.id})})}):Fe==="mailbox"?t.jsx(_s,{children:t.jsx(WT,{projectId:y?.id,addToast:n,onUnreadCountChange:fn})}):Fe==="missions"?t.jsx(_s,{children:t.jsx(UT,{isInline:!0,isOpen:!0,onClose:()=>{Me(void 0),Lt(void 0),gt(void 0),fe("board")},addToast:n,projectId:y?.id,onSelectTask:Rt=>{const cn=we.find(as=>as.id===Rt);cn&&Bn(cn)},availableTasks:we.map(Rt=>({id:Rt.id,title:Rt.title})),resumeSessionId:At,targetMissionId:Ft,milestoneSliceResumeSessionId:ct,onMilestoneSliceResumeFetchError:()=>gt(void 0)})}):Fe==="agents"&&Hn?t.jsx(_s,{children:t.jsx(i.Suspense,{fallback:null,children:t.jsx(_z,{addToast:n,projectId:y?.id,onOpenTaskLogs:gs,agentOnboardingEnabled:cs})})}):Fe==="documents"?t.jsx(_s,{children:t.jsx(i.Suspense,{fallback:null,children:t.jsx(Mz,{projectId:y?.id,addToast:n,onOpenDetail:Bn})})}):Fe==="insights"?!vt||!st?null:t.jsx(_s,{children:t.jsx(i.Suspense,{fallback:null,children:t.jsx(Az,{projectId:y?.id,addToast:n,onClose:()=>fe("board"),onCreateTask:kt})})}):Fe==="research"?!vt||!yn?null:t.jsx(_s,{children:t.jsx(i.Suspense,{fallback:null,children:t.jsx(Pz,{projectId:y?.id,addToast:n,onOpenSettings:Rt=>H.openSettings(Rt),readinessVersion:wt})})}):Fe==="evals"?!vt||!ls?null:t.jsx(_s,{children:t.jsx(i.Suspense,{fallback:null,children:t.jsx(Rz,{projectId:y?.id,onOpenSettings:Rt=>H.openSettings(Rt),onOpenTaskDetail:Rt=>{Sa(Rt,y?.id).then(cn=>Bn(cn)).catch(cn=>n(cn instanceof Error?cn.message:"Failed to open task detail","error"))}})})}):Fe==="memory"?!vt||!Gt?null:t.jsx(_s,{children:t.jsx(i.Suspense,{fallback:null,children:t.jsx(Dz,{addToast:n,projectId:y?.id})})}):Fe==="devserver"||Fe==="dev-server"?!vt||!Cn?null:t.jsx(_s,{children:t.jsx(i.Suspense,{fallback:null,children:t.jsx(Lz,{addToast:n,projectId:y?.id})})}):Fe==="board"?t.jsx(_s,{children:t.jsx(XC,{tasks:St,projectId:y?.id,maxConcurrent:tn,onMoveTask:_e,onPauseTask:lt,onOpenDetail:Bn,addToast:n,onQuickCreate:Tt,onNewTask:Gn,onPlanningMode:Ts,onSubtaskBreakdown:ca,autoMerge:Xn,onToggleAutoMerge:On,globalPaused:be,onUpdateTask:Ue,onRetryTask:xt,onArchiveTask:oe,onUnarchiveTask:le,onDeleteTask:ht,onArchiveAllDone:ge,onLoadArchivedTasks:Ne,searchQuery:O,availableModels:wn,onOpenDetailWithTab:Un,favoriteProviders:Zn,favoriteModels:_n,onToggleFavorite:Y,onToggleModelFavorite:Ee,taskStuckTimeoutMs:rt,onOpenMission:li,lastFetchTimeMs:qe})}):t.jsx(_s,{children:t.jsx(HI,{tasks:x&&N.tasks.length>0?N.tasks:we,projectId:y?.id,onMoveTask:_e,onRetryTask:xt,onDeleteTask:ht,onMergeTask:mt,onResetTask:Ie,onDuplicateTask:pt,onOpenDetail:(Rt,cn)=>Bn(Rt,void 0,cn),addToast:n,globalPaused:be,onNewTask:Gn,onQuickCreate:Tt,onPlanningMode:Ts,onSubtaskBreakdown:ca,availableModels:wn,favoriteProviders:Zn,favoriteModels:_n,onToggleFavorite:Y,onToggleModelFavorite:Ee,taskStuckTimeoutMs:rt,searchQuery:O,lastFetchTimeMs:qe,prAuthAvailable:ut})})};if(!tt)return t.jsxs(t.Fragment,{children:[t.jsx(yL,{stage:Qt}),t.jsx(sv,{toasts:e,onRemove:s})]});const Gi=!H.modelOnboardingOpen&&BD(),qa=!H.modelOnboardingOpen&&!Gi&&wr()&&!Zx();return t.jsxs(t.Fragment,{children:[t.jsx(I0,{shellHost:c.host,onOpenSettings:Nn,onOpenGitHubImport:ri,onOpenPlanning:ds,onResumePlanning:Ri,activePlanningSessionCount:J.length,onOpenUsage:ma,onOpenActivityLog:oi,onOpenSystemStats:da,onOpenMailbox:()=>ot("mailbox"),mailboxUnreadCount:on,mailboxPendingApprovalCount:Jt,chatHasUnreadResponse:zt,onOpenSchedules:Da,onOpenGitManager:Ii,onOpenNodes:Kn,showNodesButton:En,onOpenWorkflowSteps:ua,onOpenScripts:La,onRunScript:Ti,onToggleTerminal:Ta,onOpenFiles:$a,filesOpen:H.filesOpen,onOpenTodos:Qs,todosOpen:H.todosOpen,todosEnabled:fs,globalPaused:be,enginePaused:it,onToggleGlobalPause:jn,onToggleEnginePause:zn,view:Fe,onChangeView:He==="project"&&y?ot:void 0,showSkillsTab:Et,showAgentsTab:Hn,searchQuery:O,onSearchChange:q,branchFilter:te,baseBranchFilter:K,branchOptions:Ye,baseBranchOptions:It,onBranchFilterChange:I,onBaseBranchFilterChange:$,projects:G,currentProject:y,onSelectProject:es,onViewAllProjects:ks,projectId:y?.id,mobileNavEnabled:pe,availableNodes:f,currentNode:p,onSelectNode:Ke=>{Ke===null?b():w(Ke)},isRemote:x,experimentalFeatures:{insights:st,memoryView:Gt,devServer:Cn,devServerView:Cn,researchView:yn,evalsView:ls},pluginDashboardViews:$e,shellConnectionControl:!pe&&yi?t.jsx(ag,{status:yi,onError:Ke=>n(Ke,"error")}):void 0}),He==="project"&&y&&!Ht&&Fe!=="missions"&&!H.isPlanningOpen&&!Ce&&t.jsx($L,{sessions:ye,onResumeSession:Hs,onDismissSession:za,onDismissAll:Fa}),He==="project"&&y&&t.jsx(OL,{onOpenSettings:()=>H.openSettings("general")}),He==="project"&&y&&Gi&&t.jsx(UL,{onResume:H.openModelOnboarding}),He==="project"&&y&&qa&&t.jsx(BL,{onOpenModelOnboarding:H.openModelOnboarding,onOpenSettings:Ke=>H.openSettings(Ke)}),He==="project"&&y&&E&&R&&L&&!F&&t.jsx(zL,{latestVersion:R,currentVersion:L,onDismiss:M}),He==="project"&&y&&!P&&U&&!Je&&t.jsx(Jx,{hasAiProvider:v,hasGithub:j,onDismiss:Ut}),He==="project"&&y&&Zt&&t.jsx(FL,{pendingCount:Math.max(Jt,1),onOpenMailbox:()=>ot("mailbox"),onDismiss:()=>{We.current.set(Zt.dedupeKey,Math.max(Date.now(),Zt.updatedAtMs)),dg(We.current),dn(null)}}),t.jsx("div",{className:`project-content${He==="project"&&y?" project-content--with-footer":""}${pe&&!Bt?" project-content--with-mobile-nav":""}`,children:Cs()}),He==="project"&&y&&!Ht&&t.jsx(AL,{tasks:x&&N.tasks.length>0?N.tasks:we,projectId:y.id,taskStuckTimeoutMs:rt,backgroundSessions:ce,backgroundGenerating:ne,backgroundNeedsInput:re,onOpenBackgroundSession:Hs,onDismissBackgroundSession:B,lastFetchTimeMs:qe,currentProjectPath:y.path,onOpenProjectDirectory:ha,keyboardOpen:Bt}),t.jsx(qL,{view:Fe,onChangeView:He==="project"&&y?ot:()=>{},footerVisible:He==="project"&&!!y,modalOpen:H.anyModalOpen,keyboardOpen:Bt,onOpenSettings:Nn,onOpenActivityLog:oi,onOpenSystemStats:da,onOpenMailbox:()=>ot("mailbox"),onOpenNodes:Kn,mailboxUnreadCount:on,mailboxPendingApprovalCount:Jt,chatHasUnreadResponse:zt,onOpenGitManager:Ii,onOpenWorkflowSteps:ua,onOpenSchedules:Da,onOpenScripts:La,onToggleTerminal:Ta,onOpenFiles:$a,onOpenTodos:Qs,todosOpen:H.todosOpen,onOpenGitHubImport:ri,onOpenPlanning:ds,onResumePlanning:Ri,activePlanningSessionCount:J.length,onOpenUsage:()=>ma(null),onViewAllProjects:ks,onRunScript:Ti,projectId:y?.id,showSkillsTab:Et,experimentalFeatures:{insights:st,memoryView:Gt,devServer:Cn,devServerView:Cn,todoView:fs,researchView:yn,evalsView:ls,nodesView:En},pluginDashboardViews:$e,shellConnectionControl:pe&&yi?t.jsx(ag,{status:yi,onError:Ke=>n(Ke,"error")}):void 0}),He==="project"&&y&&Fe!=="chat"&&Fe!=="mailbox"&&Fe!=="insights"&&Fe!=="evals"&&Fe!=="devserver"&&Fe!=="dev-server"&&Fe!=="graph"&&!rr(Fe)&&t.jsx(hO,{projectId:y.id,addToast:n,showFAB:at,open:_t,onOpenChange:Yt,favoriteProviders:Zn,favoriteModels:_n,onToggleFavorite:Y,onToggleModelFavorite:Ee}),t.jsx(bL,{projectId:y?.id,tasks:we,projects:d,currentProject:y,addToast:n,toasts:e,removeToast:s,modalManager:H,projectActions:{handleAddProject:Is,handleSetupComplete:Ss,handleModelOnboardingComplete:X},taskHandlers:{handleModalCreate:Pt,handlePlanningTaskCreated:ln,handlePlanningTasksCreated:ts,handleSubtaskTasksCreated:Rn,handleGitHubImport:Fn},taskOperations:{moveTask:_e,deleteTask:ht,mergeTask:mt,retryTask:xt,resetTask:Ie,duplicateTask:pt},deepLink:{handleDetailClose:Ge},settings:{prAuthAvailable:ut,themeMode:xe,colorTheme:Se,dashboardFontScalePct:je,setThemeMode:se,setColorTheme:Ve,setDashboardFontScalePct:ee},onSettingsClose:qn,onReopenOnboarding:Oa}),t.jsx(Cz,{open:Xt}),a&&t.jsxs(t.Fragment,{children:[t.jsx(vz,{open:us,shellApi:a,shellState:r,onComplete:()=>Ua(!0)}),t.jsx(yz,{open:Ba,shellApi:a,shellState:r,onClose:()=>Ha(!1)})]})]})}function Vz(){return t.jsx(EO,{children:t.jsx(gz,{children:t.jsx(AD,{children:t.jsx(nz,{children:t.jsx(K0,{children:t.jsx(qz,{})})})})})})}function jv(e){e.postMessage({type:"SKIP_WAITING"})}function ug(e){e.addEventListener("statechange",()=>{e.state==="installed"&&navigator.serviceWorker.controller&&jv(e)})}function Wz(){if(!("serviceWorker"in navigator))return;const e=!!navigator.serviceWorker.controller;let n=!1;navigator.serviceWorker.addEventListener("controllerchange",()=>{n||!e||(n=!0,fu("service worker activated new version"))}),navigator.serviceWorker.register("/sw.js").then(s=>{console.log("SW registered:",s.scope),s.waiting&&navigator.serviceWorker.controller&&jv(s.waiting),s.installing&&ug(s.installing),s.addEventListener("updatefound",()=>{const a=s.installing;a&&ug(a)})}).catch(s=>{console.log("SW registration failed:",s)})}Uk();Ck();yv();gv();Sv.createRoot(document.getElementById("root")).render(t.jsx(i.StrictMode,{children:t.jsx(Ek,{children:t.jsx(Vz,{})})}));Wz();export{lS as $,Ks as A,$n as B,Dn as C,q0 as D,j3 as E,ia as F,Kl as G,Ad as H,gn as I,jl as J,s5 as K,bt as L,jo as M,Aw as N,bD as O,Sn as P,xd as Q,os as R,Fi as S,No as T,Yn as U,pi as V,vn as W,nn as X,hD as Y,Qn as Z,xn as _,rn as a,nc as a$,rD as a0,oD as a1,cS as a2,y3 as a3,dS as a4,IF as a5,TF as a6,pN as a7,mu as a8,kr as a9,U6 as aA,z6 as aB,_g as aC,Hk as aD,uo as aE,$6 as aF,L6 as aG,D6 as aH,G6 as aI,W6 as aJ,K6 as aK,J6 as aL,n5 as aM,co as aN,Sd as aO,ek as aP,Si as aQ,Vw as aR,py as aS,QI as aT,Ds as aU,Sg as aV,Hw as aW,T3 as aX,$3 as aY,D3 as aZ,L3 as a_,Aa as aa,bi as ab,xi as ac,Ei as ad,_6 as ae,I6 as af,R6 as ag,M6 as ah,T6 as ai,A6 as aj,P6 as ak,ps as al,xo as am,to as an,Ps as ao,uk as ap,_i as aq,xg as ar,Hi as as,Tv as at,O6 as au,F6 as av,V6 as aw,q6 as ax,H6 as ay,B6 as az,Mn as b,DN as b$,jO as b0,Mm as b1,Pr as b2,Of as b3,Y1 as b4,pr as b5,W1 as b6,y6 as b7,w6 as b8,G1 as b9,hF as bA,mF as bB,uF as bC,pF as bD,jF as bE,NF as bF,yF as bG,bF as bH,xF as bI,vF as bJ,gF as bK,fF as bL,dF as bM,wF as bN,K4 as bO,e3 as bP,ZF as bQ,r3 as bR,XF as bS,t3 as bT,n3 as bU,s3 as bV,i3 as bW,ON as bX,a3 as bY,bu as bZ,$N as b_,GL as ba,J1 as bb,KL as bc,S6 as bd,C6 as be,k6 as bf,j6 as bg,N6 as bh,E6 as bi,tO as bj,Wi as bk,rv as bl,q1 as bm,hs as bn,sa as bo,Vl as bp,wa as bq,jg as br,VL as bs,ZL as bt,yg as bu,nm as bv,Ui as bw,x6 as bx,b6 as by,v6 as bz,et as c,P3 as c$,LN as c0,TN as c1,QF as c2,Xl as c3,Xw as c4,dr as c5,B3 as c6,H3 as c7,q3 as c8,V3 as c9,Cj as cA,WF as cB,Ej as cC,KF as cD,ti as cE,Ai as cF,bO as cG,I4 as cH,SF as cI,z3 as cJ,Qz as cK,Xz as cL,Af as cM,A3 as cN,Zz as cO,tF as cP,cF as cQ,lF as cR,Fj as cS,Mj as cT,Mi as cU,Aj as cV,Rj as cW,Pj as cX,Ij as cY,Tj as cZ,_F as c_,W3 as ca,K3 as cb,G3 as cc,U3 as cd,Mg as ce,ow as cf,ur as cg,jS as ch,Ik as ci,Tk as cj,bj as ck,xj as cl,c6 as cm,DF as cn,$F as co,d6 as cp,LF as cq,VF as cr,BF as cs,OF as ct,HF as cu,zF as cv,qF as cw,FF as cx,UF as cy,Bv as cz,M3 as d,m3 as d$,R3 as d0,I3 as d1,qi as d2,Q6 as d3,X6 as d4,F3 as d5,nF as d6,Cd as d7,bs as d8,V4 as d9,Y3 as dA,Z3 as dB,t6 as dC,Dd as dD,lm as dE,b3 as dF,v3 as dG,F1 as dH,Na as dI,Us as dJ,Yy as dK,n6 as dL,k3 as dM,wo as dN,LR as dO,ya as dP,x3 as dQ,S3 as dR,N3 as dS,vg as dT,f3 as dU,p3 as dV,l3 as dW,c3 as dX,aD as dY,Ka as dZ,w3 as d_,vD as da,wD as db,kD as dc,ta as dd,vd as de,ND as df,iF as dg,eF as dh,aF as di,sF as dj,rF as dk,oF as dl,Ca as dm,i5 as dn,F0 as dp,tc as dq,Z6 as dr,gp as ds,e5 as dt,t5 as du,kF as dv,J3 as dw,Q3 as dx,e6 as dy,X3 as dz,E3 as e,u3 as e0,fN as e1,h3 as e2,g3 as e3,s6 as e4,D1 as e5,d3 as e6,o3 as e7,si as e8,YF as e9,GF as ea,JF as eb,i6 as ec,u6 as ed,Pd as ee,p6 as ef,f6 as eg,h6 as eh,o6 as ei,r6 as ej,l6 as ek,a6 as el,m6 as em,O3 as en,Y6 as eo,MF as ep,CF as eq,EF as er,Ow as es,PF as et,RF as eu,AF as ev,Sa as f,_3 as g,Os as h,Nr as i,kn as j,iu as k,g6 as l,ys as m,oS as n,C3 as o,Ys as p,XL as q,lD as r,ii as s,An as t,vi as u,ai as v,ss as w,Zl as x,Do as y,Pe as z};