@runfusion/fusion 0.77.0-beta.2 → 0.77.0-beta.4

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 (173) hide show
  1. package/dist/bin.js +12324 -8618
  2. package/dist/child-process-worker.js +8252 -6106
  3. package/dist/client/.vite/manifest.json +294 -267
  4. package/dist/client/assets/{AgentDetailView-Dew3af1O.js → AgentDetailView-CH6GtXl9.js} +3 -3
  5. package/dist/client/assets/{AgentPermissionPolicyEditor-CxPQffiY.js → AgentPermissionPolicyEditor-YTEpMhUx.js} +1 -1
  6. package/dist/client/assets/{AgentsView-Cr4LDGdt.js → AgentsView-XOHHDo4a.js} +4 -4
  7. package/dist/client/assets/ChatView-gH7QX3TI.js +13 -0
  8. package/dist/client/assets/{CommandCenter-DCC90LOP.js → CommandCenter-BsH-R15f.js} +3 -3
  9. package/dist/client/assets/{DevServerView-B5b520w6.js → DevServerView-CKOa-lkc.js} +1 -1
  10. package/dist/client/assets/{DirectoryPicker-1JvRd5mC.js → DirectoryPicker-DHUYTE-j.js} +1 -1
  11. package/dist/client/assets/DocumentsView-BPzrxeP-.js +1 -0
  12. package/dist/client/assets/{EvalsView-a3LhgRSo.js → EvalsView-DojCiv47.js} +1 -1
  13. package/dist/client/assets/{ExperimentalAgentOnboardingModal-vdVa8h7F.js → ExperimentalAgentOnboardingModal-DuurZ8qe.js} +1 -1
  14. package/dist/client/assets/{GoalsView-Dz2o91fd.js → GoalsView-DDWPXcG1.js} +1 -1
  15. package/dist/client/assets/{InsightsView-De3R_46d.js → InsightsView-CgkMOD1A.js} +3 -3
  16. package/dist/client/assets/MemoryView-Cj49_z7O.js +3 -0
  17. package/dist/client/assets/{PiExtensionsManager-C9JABO_4.js → PiExtensionsManager-B_rRJiOd.js} +1 -1
  18. package/dist/client/assets/PluginManager-Dxwi88oY.js +1 -0
  19. package/dist/client/assets/{PullRequestView-DT8vTeVi.js → PullRequestView-z-5v2hQT.js} +2 -2
  20. package/dist/client/assets/ReportModal-DmOPEYWp.js +21 -0
  21. package/dist/client/assets/ReportModal-lzN_xrnM.css +1 -0
  22. package/dist/client/assets/{ResearchView-cNsjYu8F.js → ResearchView-D90Jbzbx.js} +2 -2
  23. package/dist/client/assets/{SecretsView-BAmf7KyS.js → SecretsView-CSyjZl5L.js} +1 -1
  24. package/dist/client/assets/SessionTerminal-Bwb8nGmU.js +2 -0
  25. package/dist/client/assets/SettingsModal-BAzmMjr9.js +21 -0
  26. package/dist/client/assets/SettingsModal-C5ic1ls7.css +1 -0
  27. package/dist/client/assets/{SettingsModal-C_9RiEI7.js → SettingsModal-CJof1Ett.js} +1 -1
  28. package/dist/client/assets/{SettingsTextareaRow-D8RHSj8b.js → SettingsTextareaRow-BYchnHfW.js} +1 -1
  29. package/dist/client/assets/SetupWizardModal-NqV-erVf.js +2 -0
  30. package/dist/client/assets/{SkillsView-DyeCwYit.js → SkillsView-BUrkIJ-p.js} +1 -1
  31. package/dist/client/assets/{WorkflowNodeEditor-C5Jc9w_A.js → WorkflowNodeEditor-DcPk2A1Z.js} +1 -1
  32. package/dist/client/assets/{agent-import-generation-SCPNeF25.js → agent-import-generation-X16OLfrL.js} +1 -1
  33. package/dist/client/assets/{agentsOrgChartLayout-CqKtNCjy.js → agentsOrgChartLayout-BhPIXckU.js} +1 -1
  34. package/dist/client/assets/app-B-TfWH9b.js +5 -0
  35. package/dist/client/assets/app-B2RDV_-t.js +13 -0
  36. package/dist/client/assets/app-CDo0mF2S.js +5 -0
  37. package/dist/client/assets/app-Cc18kAQS.js +13 -0
  38. package/dist/client/assets/app-DFF79EUn.js +13 -0
  39. package/dist/client/assets/app-DSeFHxgj.js +13 -0
  40. package/dist/client/assets/app-Ducr0y6r.js +13 -0
  41. package/dist/client/assets/{architectureDiagram-3BPJPVTR-Cz2HYn0b.js → architectureDiagram-3BPJPVTR-WArMtdqy.js} +1 -1
  42. package/dist/client/assets/{blockDiagram-GPEHLZMM-IimJVscG.js → blockDiagram-GPEHLZMM-emScogdV.js} +1 -1
  43. package/dist/client/assets/{c4Diagram-AAUBKEIU-C-xii7zn.js → c4Diagram-AAUBKEIU-CBY7-E0T.js} +1 -1
  44. package/dist/client/assets/channel-CP2ySYs0.js +1 -0
  45. package/dist/client/assets/{chunk-2J33WTMH-DQ-9Xccu.js → chunk-2J33WTMH-Bcai1sOm.js} +1 -1
  46. package/dist/client/assets/{chunk-4BX2VUAB-DmdAX9Bx.js → chunk-4BX2VUAB-hjiKRusj.js} +1 -1
  47. package/dist/client/assets/{chunk-55IACEB6-IF2bk5IL.js → chunk-55IACEB6-DpO9nIb0.js} +1 -1
  48. package/dist/client/assets/{chunk-727SXJPM-AeYpIzVu.js → chunk-727SXJPM-B9JanA0o.js} +1 -1
  49. package/dist/client/assets/{chunk-AQP2D5EJ-DV942DD9.js → chunk-AQP2D5EJ-D6zdnEUE.js} +1 -1
  50. package/dist/client/assets/{chunk-FMBD7UC4-Bt_riVlZ.js → chunk-FMBD7UC4-CRkrJ51d.js} +1 -1
  51. package/dist/client/assets/{chunk-ND2GUHAM-CbyjNbXR.js → chunk-ND2GUHAM-BLQsKt7a.js} +1 -1
  52. package/dist/client/assets/{chunk-QZHKN3VN-DqiRniYQ.js → chunk-QZHKN3VN-MCOlJ723.js} +1 -1
  53. package/dist/client/assets/classDiagram-4FO5ZUOK-DKkOBtzM.js +1 -0
  54. package/dist/client/assets/classDiagram-v2-Q7XG4LA2-DKkOBtzM.js +1 -0
  55. package/dist/client/assets/{cose-bilkent-S5V4N54A-UCvthviL.js → cose-bilkent-S5V4N54A-Cv1XmKKG.js} +1 -1
  56. package/dist/client/assets/{dagre-BM42HDAG-DnMlT1Oi.js → dagre-BM42HDAG-flnNS_RW.js} +1 -1
  57. package/dist/client/assets/{dashboard-view-C9D0aoRW.js → dashboard-view-CC1aH-lp.js} +1 -1
  58. package/dist/client/assets/{dashboard-view-myjM9tr8.js → dashboard-view-CrV-rL9Q.js} +1 -1
  59. package/dist/client/assets/{dashboard-view-JysoyDRX.js → dashboard-view-DEAYb_TZ.js} +1 -1
  60. package/dist/client/assets/{dashboard-view-Cz0sp2Wl.js → dashboard-view-Dz7kqcJc.js} +1 -1
  61. package/dist/client/assets/{diagram-2AECGRRQ-BYFiqXGw.js → diagram-2AECGRRQ-Z3S7b_6_.js} +1 -1
  62. package/dist/client/assets/{diagram-5GNKFQAL-DZU3pSYq.js → diagram-5GNKFQAL-BAZHdMFq.js} +1 -1
  63. package/dist/client/assets/{diagram-KO2AKTUF-0ybdKuMm.js → diagram-KO2AKTUF-C2y3S8F0.js} +1 -1
  64. package/dist/client/assets/{diagram-LMA3HP47-Rxbgnbsp.js → diagram-LMA3HP47-Bfz0_IvT.js} +1 -1
  65. package/dist/client/assets/{diagram-OG6HWLK6-BAU_hTeV.js → diagram-OG6HWLK6-BBmSQsTI.js} +1 -1
  66. package/dist/client/assets/{erDiagram-TEJ5UH35-zr8HrwTt.js → erDiagram-TEJ5UH35-DnpdQi66.js} +1 -1
  67. package/dist/client/assets/{flowDiagram-I6XJVG4X-CrTw0iFw.js → flowDiagram-I6XJVG4X-IybTR_zf.js} +1 -1
  68. package/dist/client/assets/{folder-open-DnAlsXXn.js → folder-open-Dntm63x4.js} +1 -1
  69. package/dist/client/assets/{ganttDiagram-6RSMTGT7-CCORsxxz.js → ganttDiagram-6RSMTGT7-DEQOe2E9.js} +1 -1
  70. package/dist/client/assets/{gitGraphDiagram-PVQCEYII-C07wWSjj.js → gitGraphDiagram-PVQCEYII-BOKc-h63.js} +1 -1
  71. package/dist/client/assets/index-DXpztECA.css +1 -0
  72. package/dist/client/assets/index-I32FijPT.js +2821 -0
  73. package/dist/client/assets/{infoDiagram-5YYISTIA-hAeccD_4.js → infoDiagram-5YYISTIA-LqaYIdbj.js} +1 -1
  74. package/dist/client/assets/{ishikawaDiagram-YF4QCWOH-WLCzv-NH.js → ishikawaDiagram-YF4QCWOH-a8qd512s.js} +1 -1
  75. package/dist/client/assets/{journeyDiagram-JHISSGLW-ClnasNhy.js → journeyDiagram-JHISSGLW-BgoNyeiy.js} +1 -1
  76. package/dist/client/assets/{kanban-definition-UN3LZRKU-CAuARhUz.js → kanban-definition-UN3LZRKU-Bqwow7D3.js} +1 -1
  77. package/dist/client/assets/{mermaid.core-Bh02RvfX.js → mermaid.core-B2zD934i.js} +4 -4
  78. package/dist/client/assets/{mindmap-definition-RKZ34NQL-KNTlbW4V.js → mindmap-definition-RKZ34NQL-CCTOigWu.js} +1 -1
  79. package/dist/client/assets/{pieDiagram-4H26LBE5-BouAfBEw.js → pieDiagram-4H26LBE5-Bq5DtXKR.js} +1 -1
  80. package/dist/client/assets/pixelify-sans-cyrillic-400-normal-DfOZNMlW.woff +0 -0
  81. package/dist/client/assets/pixelify-sans-latin-400-normal-DLrIX9QE.woff2 +0 -0
  82. package/dist/client/assets/pixelify-sans-latin-400-normal-JapMNN6Z.woff +0 -0
  83. package/dist/client/assets/pixelify-sans-latin-ext-400-normal-BkfTUL4s.woff +0 -0
  84. package/dist/client/assets/pixelify-sans-latin-ext-400-normal-DdH6zlBQ.woff2 +0 -0
  85. package/dist/client/assets/{puzzle-CC8Ur3Cy.js → puzzle-VhTPiCit.js} +1 -1
  86. package/dist/client/assets/{quadrantDiagram-W4KKPZXB-wTdkCUJU.js → quadrantDiagram-W4KKPZXB-CGMP3nUx.js} +1 -1
  87. package/dist/client/assets/{requirementDiagram-4Y6WPE33-BnjY4Tc_.js → requirementDiagram-4Y6WPE33-Ckeu_szu.js} +1 -1
  88. package/dist/client/assets/{sankeyDiagram-5OEKKPKP-C-QsS08u.js → sankeyDiagram-5OEKKPKP-SWbBDD4d.js} +1 -1
  89. package/dist/client/assets/{sequenceDiagram-3UESZ5HK-DD36MILE.js → sequenceDiagram-3UESZ5HK-CiJrmL_G.js} +1 -1
  90. package/dist/client/assets/{shield-alert-DcXc56Fy.js → shield-alert-BBDlP6A5.js} +1 -1
  91. package/dist/client/assets/{standing-instructions-template-BF5y1BLz.js → standing-instructions-template-viu_kgDX.js} +2 -2
  92. package/dist/client/assets/{stateDiagram-AJRCARHV-WTq1wQr1.js → stateDiagram-AJRCARHV-DTCzK5Gt.js} +1 -1
  93. package/dist/client/assets/{stateDiagram-v2-BHNVJYJU-eILJdjII.js → stateDiagram-v2-BHNVJYJU-BIGAwFTT.js} +1 -1
  94. package/dist/client/assets/{timeline-definition-PNZ67QCA-PRNwI0NR.js → timeline-definition-PNZ67QCA-BQZEFEug.js} +1 -1
  95. package/dist/client/assets/{upload-qH_64O-B.js → upload-D5w3Ehwp.js} +1 -1
  96. package/dist/client/assets/{useDiscoveredSkillsCache-C-GPCNaO.js → useDiscoveredSkillsCache-D6zMSIaS.js} +1 -1
  97. package/dist/client/assets/{users-D2UesRE4.js → users-Bohihi_o.js} +1 -1
  98. package/dist/client/assets/{vennDiagram-CIIHVFJN-CG2Z4T4O.js → vennDiagram-CIIHVFJN-DnHguEv8.js} +1 -1
  99. package/dist/client/assets/{wardley-L42UT6IY-gO_fGvF9.js → wardley-L42UT6IY-BOqYltGN.js} +1 -1
  100. package/dist/client/assets/{wardleyDiagram-YWT4CUSO-BkyNpjUb.js → wardleyDiagram-YWT4CUSO-Re0Ery2M.js} +1 -1
  101. package/dist/client/assets/{xychartDiagram-2RQKCTM6-CMlZsiPq.js → xychartDiagram-2RQKCTM6-CnVq21b2.js} +1 -1
  102. package/dist/client/index.html +4 -4
  103. package/dist/client/theme-data.css +183 -1
  104. package/dist/client/version.json +1 -1
  105. package/dist/droid-cli/package.json +1 -1
  106. package/dist/extension.js +9275 -6726
  107. package/dist/pi-claude-cli/package.json +1 -1
  108. package/dist/pi-claude-cli/src/__tests__/event-bridge.test.ts +29 -1
  109. package/dist/pi-claude-cli/src/event-bridge.ts +10 -4
  110. package/dist/plugin-sdk/index.d.ts +25 -3
  111. package/dist/plugin-sdk/index.js +10 -1
  112. package/dist/plugins/fusion-plugin-acp-runtime/bundled.js +12 -2
  113. package/dist/plugins/fusion-plugin-acp-runtime/package.json +1 -1
  114. package/dist/plugins/fusion-plugin-claude-runtime/bundled.js +12 -2
  115. package/dist/plugins/fusion-plugin-claude-runtime/package.json +1 -1
  116. package/dist/plugins/fusion-plugin-cli-printing-press/bundled.js +10 -1
  117. package/dist/plugins/fusion-plugin-cli-printing-press/package.json +1 -1
  118. package/dist/plugins/fusion-plugin-compound-engineering/bundled.js +10 -1
  119. package/dist/plugins/fusion-plugin-compound-engineering/package.json +1 -1
  120. package/dist/plugins/fusion-plugin-cursor-runtime/bundled.js +10 -1
  121. package/dist/plugins/fusion-plugin-cursor-runtime/package.json +1 -1
  122. package/dist/plugins/fusion-plugin-dependency-graph/bundled.js +10 -1
  123. package/dist/plugins/fusion-plugin-dependency-graph/package.json +1 -1
  124. package/dist/plugins/fusion-plugin-droid-runtime/bundled.js +12 -2
  125. package/dist/plugins/fusion-plugin-droid-runtime/package.json +1 -1
  126. package/dist/plugins/fusion-plugin-grok-runtime/bundled.js +12 -2
  127. package/dist/plugins/fusion-plugin-grok-runtime/package.json +1 -1
  128. package/dist/plugins/fusion-plugin-hermes-runtime/bundled.js +10 -1
  129. package/dist/plugins/fusion-plugin-hermes-runtime/package.json +1 -1
  130. package/dist/plugins/fusion-plugin-linear-import/bundled.js +10 -1
  131. package/dist/plugins/fusion-plugin-linear-import/package.json +1 -1
  132. package/dist/plugins/fusion-plugin-omp-runtime/bundled.js +12 -2
  133. package/dist/plugins/fusion-plugin-omp-runtime/package.json +1 -1
  134. package/dist/plugins/fusion-plugin-openclaw-runtime/bundled.js +10 -1
  135. package/dist/plugins/fusion-plugin-openclaw-runtime/package.json +1 -1
  136. package/dist/plugins/fusion-plugin-paperclip-runtime/bundled.js +10 -1
  137. package/dist/plugins/fusion-plugin-paperclip-runtime/package.json +1 -1
  138. package/dist/plugins/fusion-plugin-quality/bundled.js +10 -1
  139. package/dist/plugins/fusion-plugin-quality/package.json +1 -1
  140. package/dist/plugins/fusion-plugin-reports/bundled.js +10 -1
  141. package/dist/plugins/fusion-plugin-reports/package.json +1 -1
  142. package/dist/plugins/fusion-plugin-roadmap/bundled.js +10 -1
  143. package/dist/plugins/fusion-plugin-roadmap/package.json +1 -1
  144. package/dist/plugins/fusion-plugin-todos/bundled.js +10 -1
  145. package/dist/plugins/fusion-plugin-todos/package.json +1 -1
  146. package/dist/plugins/fusion-plugin-whatsapp-chat/bundled.js +10 -1
  147. package/dist/plugins/fusion-plugin-whatsapp-chat/package.json +1 -1
  148. package/package.json +1 -1
  149. package/skill/fusion/SKILL.md +1 -1
  150. package/skill/fusion/references/extension-tools.md +17 -0
  151. package/skill/fusion/references/fusion-capabilities.md +2 -0
  152. package/dist/client/assets/ChatView-cNYtYx05.js +0 -13
  153. package/dist/client/assets/DocumentsView-ksK9f7xt.js +0 -1
  154. package/dist/client/assets/MemoryView-Cagk2wZG.js +0 -3
  155. package/dist/client/assets/PluginManager-D2csmdQa.js +0 -1
  156. package/dist/client/assets/ReportModal-M3uh98sc.css +0 -1
  157. package/dist/client/assets/ReportModal-YMP6V4vu.js +0 -21
  158. package/dist/client/assets/SessionTerminal-BjGcxq22.js +0 -2
  159. package/dist/client/assets/SettingsModal-C0FY8MPW.css +0 -1
  160. package/dist/client/assets/SettingsModal-DLfy2e_5.js +0 -21
  161. package/dist/client/assets/SetupWizardModal-DRJ96pHQ.js +0 -2
  162. package/dist/client/assets/app-BgpuMvTU.js +0 -13
  163. package/dist/client/assets/app-BlexHhbW.js +0 -13
  164. package/dist/client/assets/app-BsuUOR0P.js +0 -13
  165. package/dist/client/assets/app-DQVOujmO.js +0 -13
  166. package/dist/client/assets/app-DjyTRx1N.js +0 -5
  167. package/dist/client/assets/app-Dniggype.js +0 -13
  168. package/dist/client/assets/app-EV-lyZ0T.js +0 -5
  169. package/dist/client/assets/channel-D-UHgx8G.js +0 -1
  170. package/dist/client/assets/classDiagram-4FO5ZUOK-Do-8MdAc.js +0 -1
  171. package/dist/client/assets/classDiagram-v2-Q7XG4LA2-Do-8MdAc.js +0 -1
  172. package/dist/client/assets/index-B_z7OKl4.js +0 -2818
  173. package/dist/client/assets/index-DPo-IAb2.css +0 -1
@@ -1,11 +1,11 @@
1
- import{r as i,j as e}from"./vendor-react-SZ_qB27O.js";import{c as ze,r as le,e as Ce,S as je,cJ as Me,cK as Ze,b as Ne,cL as es,cM as ss,cN as ts,cO as is,cP as ns,cQ as as,cR as Ie,cS as rs,cT as os,cU as cs,cq as ls,cV as Re,V as hs,m as q,bW as ds,X as Ae,cW as fe,R as K,a3 as gs,cv as us,as as De,l as ae,bF as ve,bE as Te,P as $e,aS as ms,b0 as Pe,cX as fs,s as vs,q as ys}from"./index-B_z7OKl4.js";import{u as Ge}from"./vendor-i18n-Duky4gdQ.js";import{U as Ee}from"./users-D2UesRE4.js";import"./vendor-codemirror-CcrtqoCy.js";import"./vendor-reactflow-BlIeoTu4.js";import"./vendor-xterm-BNq00GSj.js";/**
1
+ import{r as i,j as e}from"./vendor-react-SZ_qB27O.js";import{c as ze,r as le,e as Ce,S as je,cL as Me,cM as Je,b as Ne,cN as es,cO as ss,cP as ts,cQ as is,cR as ns,cS as as,cT as Ie,cU as rs,cV as os,cW as cs,cs as ls,cX as Re,V as hs,m as Y,bY as ds,X as Ae,cY as fe,R as q,a3 as gs,cx as us,as as De,l as ae,bH as ve,bG as Te,P as $e,aU as ms,b2 as Pe,cZ as fs,s as vs,q as xs}from"./index-I32FijPT.js";import{u as Ge}from"./vendor-i18n-Duky4gdQ.js";import{U as Ee}from"./users-Bohihi_o.js";import"./vendor-codemirror-CcrtqoCy.js";import"./vendor-reactflow-BlIeoTu4.js";import"./vendor-xterm-BNq00GSj.js";/**
2
2
  * @license lucide-react v1.7.0 - ISC
3
3
  *
4
4
  * This source code is licensed under the ISC license.
5
5
  * See the LICENSE file in the root directory of this source tree.
6
- */const xs=[["path",{d:"M12 10h.01",key:"1nrarc"}],["path",{d:"M12 14h.01",key:"1etili"}],["path",{d:"M12 6h.01",key:"1vi96p"}],["path",{d:"M16 10h.01",key:"1m94wz"}],["path",{d:"M16 14h.01",key:"1gbofw"}],["path",{d:"M16 6h.01",key:"1x0f13"}],["path",{d:"M8 10h.01",key:"19clt8"}],["path",{d:"M8 14h.01",key:"6423bh"}],["path",{d:"M8 6h.01",key:"1dz90k"}],["path",{d:"M9 22v-3a1 1 0 0 1 1-1h4a1 1 0 0 1 1 1v3",key:"cabbwy"}],["rect",{x:"4",y:"2",width:"16",height:"20",rx:"2",key:"1uxh74"}]],ps=ze("building",xs);/**
6
+ */const ys=[["path",{d:"M12 10h.01",key:"1nrarc"}],["path",{d:"M12 14h.01",key:"1etili"}],["path",{d:"M12 6h.01",key:"1vi96p"}],["path",{d:"M16 10h.01",key:"1m94wz"}],["path",{d:"M16 14h.01",key:"1gbofw"}],["path",{d:"M16 6h.01",key:"1x0f13"}],["path",{d:"M8 10h.01",key:"19clt8"}],["path",{d:"M8 14h.01",key:"6423bh"}],["path",{d:"M8 6h.01",key:"1dz90k"}],["path",{d:"M9 22v-3a1 1 0 0 1 1-1h4a1 1 0 0 1 1 1v3",key:"cabbwy"}],["rect",{x:"4",y:"2",width:"16",height:"20",rx:"2",key:"1uxh74"}]],ps=ze("building",ys);/**
7
7
  * @license lucide-react v1.7.0 - ISC
8
8
  *
9
9
  * This source code is licensed under the ISC license.
10
10
  * See the LICENSE file in the root directory of this source tree.
11
- */const bs=[["path",{d:"M3 3v16a2 2 0 0 0 2 2h16",key:"c24i48"}],["path",{d:"m19 9-5 5-4-4-3 3",key:"2osh9i"}]],ks=ze("chart-line",bs),me=["architecture","quality","workflow","performance","reliability","security","ux","testability","documentation","dependency","features","competitive_analysis","research","trends","other"],Fe={quality:"Quality",performance:"Performance",architecture:"Architecture",security:"Security",reliability:"Reliability",ux:"User Experience",testability:"Testability",documentation:"Documentation",dependency:"Dependencies",workflow:"Workflow",other:"Other",features:"Features",competitive_analysis:"Competitive Analysis",research:"Research",trends:"Trends"};function Ss(g,m){const M=Date.parse(g.createdAt),p=Date.parse(m.createdAt),b=Number.isFinite(M),s=Number.isFinite(p);return!b||!s?b?-1:s?1:0:M!==p?p-M:g.id===m.id?0:g.id<m.id?1:-1}function ws(g){const{t:m}=Ge("app"),M=g??"",p=`${je.INSIGHTS_PREFIX}${M}`,b=`${je.INSIGHT_LATEST_RUN_PREFIX}${M}`,s=le(p,{maxAgeMs:Ce}),Y=le(b,{maxAgeMs:Me}),P=i.useRef(Array.isArray(s)&&s.length>0),U=i.useCallback(r=>m(`insights.category.${r}`,Fe[r]??r),[m]),[y,N]=i.useState(()=>Array.isArray(s)?s:[]),[H,Q]=i.useState(()=>me.map(r=>({category:r,label:Fe[r]??r,items:[],isLoading:!1,error:null}))),[O,E]=i.useState(!(Array.isArray(s)&&s.length>0)),[J,F]=i.useState(null),[G,I]=i.useState(Y??null),[L,_]=i.useState(!1),[w,z]=i.useState(null),[T,B]=i.useState(new Map),[Z,l]=i.useState(new Map),[k,u]=i.useState(new Map),[x,h]=i.useState(new Map),[C,R]=i.useState(!1),v=i.useCallback(async()=>{P.current||E(!0),F(null);try{const n=(await Ze({status:void 0,limit:1e3},g)).insights.filter(d=>d.status!=="dismissed");N(n),Ne(p,n.length>500?n.slice(0,500):n,{maxBytes:5e5});const o=await es(g);o.runs.length>0&&(I(o.runs[0]),Ne(b,o.runs[0],{maxBytes:5e5})),P.current=!0}catch(r){const n=r instanceof Error?r.message:"Failed to fetch insights";F(n)}finally{E(!1)}},[p,b,g]),ee=i.useCallback(()=>{R(r=>!r)},[]),j=i.useCallback(async(r,n,o)=>{_(!0),z(null);try{const d=await ss("manual",void 0,g,r,n,o);I(d),d.status==="completed"?await v():d.status==="failed"&&d.error&&z(d.error)}catch(d){if(d instanceof ts&&d.status===409&&d.details?.code==="ACTIVE_RUN_CONFLICT"){const re=typeof d.details.activeRunId=="string"?d.details.activeRunId:null;if(re)try{const ue=await is(re,g);I(ue)}catch{}throw z("Insight generation is already running"),d}const S=d instanceof Error?d.message:"Failed to generate insights";throw z(S),d}finally{_(!1)}},[g,v]),D=i.useCallback(async r=>{B(n=>{const o=new Map(n);return o.set(r,{running:!0,error:null}),o});try{await ns(r,g),N(n=>n.filter(o=>o.id!==r)),B(n=>{const o=new Map(n);return o.set(r,{running:!1,error:null}),o})}catch(n){const o=n instanceof Error?n.message:"Failed to dismiss insight";throw B(d=>{const S=new Map(d);return S.set(r,{running:!1,error:o}),S}),n}},[g]),V=i.useCallback(async r=>{l(n=>{const o=new Map(n);return o.set(r,{running:!0,error:null}),o});try{const n=await as(r,g);return await Ie(r,g),N(o=>o.map(d=>d.id===r?{...d,status:"archived",updatedAt:new Date().toISOString()}:d)),l(o=>{const d=new Map(o);return d.set(r,{running:!1,error:null}),d}),{title:n.suggestedTitle,description:n.suggestedDescription}}catch(n){const o=n instanceof Error?n.message:"Failed to create task";throw l(d=>{const S=new Map(d);return S.set(r,{running:!1,error:o}),S}),n}},[g]);i.useEffect(()=>{const r=new Map;for(const n of me)r.set(n,[]);for(const n of y){if(!C&&n.status==="archived")continue;const o=r.get(n.category)??[];r.set(n.category,[...o,n])}Q(me.map(n=>({category:n,label:U(n),items:[...r.get(n)??[]].sort(Ss),isLoading:!1,error:null})))},[y,C,U]);const he=i.useCallback(async r=>{u(n=>{const o=new Map(n);return o.set(r,{running:!0,error:null}),o});try{await Ie(r,g),N(n=>n.map(o=>o.id===r?{...o,status:"archived",updatedAt:new Date().toISOString()}:o)),u(n=>{const o=new Map(n);return o.set(r,{running:!1,error:null}),o})}catch(n){const o=n instanceof Error?n.message:"Failed to archive insight";throw u(d=>{const S=new Map(d);return S.set(r,{running:!1,error:o}),S}),n}},[g]),de=i.useCallback(async r=>{h(n=>{const o=new Map(n);return o.set(r,{running:!0,error:null}),o});try{await rs(r,g),N(n=>n.map(o=>o.id===r?{...o,status:"confirmed",updatedAt:new Date().toISOString()}:o)),h(n=>{const o=new Map(n);return o.set(r,{running:!1,error:null}),o})}catch(n){const o=n instanceof Error?n.message:"Failed to unarchive insight";throw h(d=>{const S=new Map(d);return S.set(r,{running:!1,error:o}),S}),n}},[g]),ge=i.useMemo(()=>H.reduce((r,n)=>r+n.items.length,0),[H]),A=i.useMemo(()=>0,[]),te=i.useMemo(()=>y.filter(r=>r.status==="archived").length,[y]);return i.useEffect(()=>{const r=le(p,{maxAgeMs:Ce}),n=le(b,{maxAgeMs:Me}),o=Array.isArray(r)&&r.length>0;N(Array.isArray(r)?r:[]),I(n??null),E(!o),P.current=o},[p,b]),i.useEffect(()=>{v()},[v]),{sections:H,loading:O,error:J,latestRun:G,isRunInFlight:L,runError:w,refresh:v,runInsights:j,dismiss:D,createTask:V,archive:he,unarchive:de,toggleShowArchived:ee,dismissStates:T,createTaskStates:Z,archiveStates:k,unarchiveStates:x,totalCount:ge,dismissedCount:A,archivedCount:te,showArchived:C}}const Cs=20,js=50;function Ms(g){const[m,M]=i.useState([]),[p,b]=i.useState(!0),[s,Y]=i.useState(!1),[P,U]=i.useState(null),[y,N]=i.useState(!1),[H,Q]=i.useState(0),[O,E]=i.useState(!1),[J,F]=i.useState(new Map),G=i.useRef(0),I=i.useRef(0),L=i.useRef(!1),_=i.useRef(new Set),w=i.useRef(0),z=i.useRef(g),T=i.useCallback(async k=>{if(L.current)return;L.current=!0;const u=w.current,x=k?0:G.current;k?b(!0):Y(!0),U(null);try{const h=await os(g,{limit:js,offset:x});if(u!==w.current)return;M(v=>{const ee=k?[]:v,j=new Set(ee.map(D=>`${D.taskId}:${D.recommendation.id}`));return[...ee,...h.items.filter(D=>{const V=`${D.taskId}:${D.recommendation.id}`;return j.has(V)?!1:(j.add(V),!0)})]}),G.current=h.rowOffset+h.returnedRowCount,I.current=k?1:I.current+1,Q(h.totalRowCount);const R=I.current>=Cs&&h.hasMore;E(R),N(R?!1:h.hasMore)}catch(h){u===w.current&&U(h instanceof Error?h.message:"Failed to fetch task recommendations")}finally{u===w.current&&(b(!1),Y(!1)),L.current=!1}},[g]),B=i.useCallback(async()=>{G.current=0,I.current=0,E(!1),await T(!0)},[T]);i.useEffect(()=>{z.current=g,w.current+=1,L.current=!1,_.current.clear(),G.current=0,I.current=0,M([]),N(!1),Q(0),E(!1),F(new Map),T(!0)},[T,g]);const Z=i.useCallback(async()=>{!y||O||L.current||await T(!1)},[T,y,O]),l=i.useCallback(async(k,u)=>{const x=`${k}:${u}`;if(_.current.has(x))return;_.current.add(x);const h=w.current;F(C=>new Map(C).set(x,{running:!0,error:null}));try{const C=await cs(k,u,z.current);if(h!==w.current)return;M(R=>R.map(v=>v.taskId===k&&v.recommendation.id===u?{...v,recommendation:{...v.recommendation,createdTaskId:C.task.id}}:v)),F(R=>new Map(R).set(x,{running:!1,error:null}))}catch(C){h===w.current&&F(R=>new Map(R).set(x,{running:!1,error:C instanceof Error?C.message:"Could not create task"}))}finally{h===w.current&&_.current.delete(x)}},[]);return{items:m,loading:p,loadingMore:s,error:P,hasMore:y,totalRowCount:H,truncated:O,refresh:B,loadMore:Z,createTask:l,createStates:J}}const Ue=["Backlog health:","Backlog pressure detected","Stale paused todo","Backlog health: dependency-blocked todos"];function Le(g){return Ue.some(m=>g.title.startsWith(m))}const _e={architecture:ps,quality:De,workflow:Pe,performance:Te,reliability:K,security:ae,ux:Ee,testability:fe,documentation:ms,dependency:$e,features:ve,competitive_analysis:Ee,research:ks,trends:Te,other:q};function Ls({projectId:g,addToast:m,onClose:M,onCreateTask:p,models:b}){const{t:s}=Ge("app"),{sections:Y,loading:P,error:U,latestRun:y,isRunInFlight:N,runError:H,refresh:Q,runInsights:O,dismiss:E,createTask:J,archive:F=async()=>{},unarchive:G=async()=>{},toggleShowArchived:I=()=>{},dismissStates:L,createTaskStates:_,archiveStates:w=new Map,unarchiveStates:z=new Map,totalCount:T,archivedCount:B=0,showArchived:Z=!1}=ws(g),l=Ms(g),[k,u]=i.useState(null),[x,h]=i.useState("info"),[C,R]=i.useState(!1),[v,ee]=i.useState(!1),[j,D]=i.useState(()=>localStorage.getItem("fusion-insight-model")??""),[V,he]=i.useState(()=>localStorage.getItem("fusion-insight-thinking")??""),[de,ge]=i.useState([]),[A,te]=i.useState([]),[r,n]=i.useState([]),[o,d]=i.useState();i.useEffect(()=>{b||ls().then(t=>{ge(t.models),te(t.favoriteProviders),n(t.favoriteModels),d(t.resolvedPlanningProvider);const a=localStorage.getItem("fusion-insight-model");a&&(t.models.some(f=>`${f.provider}/${f.id}`===a)||(localStorage.removeItem("fusion-insight-model"),D("")))}).catch(()=>{})},[b]);const S=b??de,re=i.useMemo(()=>A.length>0?A:o?[o]:[],[A,o]),ue=i.useCallback(async t=>{const c=A.includes(t)?A.filter(f=>f!==t):[t,...A];te(c);try{await Re({favoriteProviders:c,favoriteModels:r})}catch{te(A)}},[A,r]),He=i.useCallback(async t=>{const c=r.includes(t)?r.filter(f=>f!==t):[t,...r];n(c);try{await Re({favoriteProviders:A,favoriteModels:c})}catch{n(r)}},[r,A]),Oe=i.useCallback(t=>{D(t),t?localStorage.setItem("fusion-insight-model",t):localStorage.removeItem("fusion-insight-model")},[]),Be=i.useCallback(t=>{he(t),t?localStorage.setItem("fusion-insight-thinking",t):localStorage.removeItem("fusion-insight-thinking")},[]),ie=i.useMemo(()=>Y.filter(t=>t.items.length>0),[Y]),ye=i.useMemo(()=>ie.reduce((t,a)=>t+a.items.filter(Le).length,0),[ie]),X=i.useMemo(()=>v?ie.map(t=>({...t,items:t.items.filter(Le)})).filter(t=>t.items.length>0):ie,[ie,v]),[$,ne]=i.useState(null);i.useEffect(()=>{if($==="recommendations"&&l.items.length>0)return;if(X.length===0){l.items.length>0?ne("recommendations"):$!==null&&ne(null);return}$&&X.some(a=>a.category===$&&a.items.length>0)||ne(X[0]?.category??(l.items.length>0?"recommendations":null))},[X,$,l.items.length]);const W=i.useMemo(()=>$==="recommendations"?void 0:X.find(t=>t.category===$)??X[0],[X,$]);i.useEffect(()=>{if(k){const t=setTimeout(()=>u(null),5e3);return()=>clearTimeout(t)}},[k]);const xe=i.useCallback(async()=>{try{u(s("insights.generatingInsights","Generating insights...")),h("info");let t,a;if(j){const c=j.indexOf("/");if(c!==-1){const f=j.slice(0,c),oe=j.slice(c+1);f&&oe&&(t=f,a=oe)}}await O(t,a,V||void 0),u(s("insights.generationStarted","Insight generation started")),h("success"),m(s("insights.generationStarted","Insight generation started"),"success")}catch(t){const a=t instanceof Error?t.message:s("insights.failedToStart","Failed to start generation");if(a==="Insight generation is already running"){u(s("insights.alreadyRunning","Insight generation is already running. Showing the active run.")),h("info"),m(s("insights.alreadyRunningShort","Insight generation is already running"),"info");return}u(a),h("error"),m(a,"error")}},[O,m,j,V,s]),Ve=i.useCallback(async(t,a)=>{try{u(s("insights.dismissing",'Dismissing "{{title}}"...',{title:a})),h("info"),await E(t),u(s("insights.dismissed",'Dismissed "{{title}}"',{title:a})),h("success"),m(s("insights.dismissedMsg","Insight dismissed: {{title}}",{title:a}),"success")}catch(c){const f=c instanceof Error?c.message:s("insights.failedToDismiss","Failed to dismiss insight");u(f),h("error"),m(f,"error")}},[E,m,s]),Xe=i.useCallback(async(t,a)=>{try{u(s("insights.archiving",'Archiving "{{title}}"...',{title:a})),h("info"),await F(t),u(s("insights.archived",'Archived "{{title}}"',{title:a})),h("success"),m(s("insights.archivedMsg","Insight archived: {{title}}",{title:a}),"success")}catch(c){const f=c instanceof Error?c.message:s("insights.failedToArchive","Failed to archive insight");u(f),h("error"),m(f,"error")}},[F,m,s]),We=i.useCallback(async(t,a)=>{try{u(s("insights.unarchiving",'Unarchiving "{{title}}"...',{title:a})),h("info"),await G(t),u(s("insights.unarchived",'Unarchived "{{title}}"',{title:a})),h("success"),m(s("insights.unarchivedMsg","Insight unarchived: {{title}}",{title:a}),"success")}catch(c){const f=c instanceof Error?c.message:s("insights.failedToUnarchive","Failed to unarchive insight");u(f),h("error"),m(f,"error")}},[G,m,s]),qe=i.useCallback(async(t,a)=>{try{if(u(s("insights.creatingTask",'Creating task from "{{title}}"...',{title:a})),h("info"),!p)throw new Error(s("insights.taskCreationUnavailable","Task creation is unavailable in this view"));const c=await J(t);if(!c)throw new Error(s("insights.failedToPreparePayload","Failed to prepare task payload from insight"));await p({insightId:t,title:c.title,description:c.description}),u(s("insights.taskCreated",'Task created from "{{title}}"',{title:a})),h("success"),m(s("insights.taskCreatedMsg","Task created: {{title}}",{title:c.title}),"success")}catch(c){const f=c instanceof Error?c.message:s("insights.failedToCreateTask","Failed to create task");u(f),h("error"),m(f,"error")}},[J,p,m,s]),Ke=t=>{const a=_e[t.category]??q,c=W?.category===t.category;return e.jsx("li",{children:e.jsxs("button",{type:"button",className:`insights-category-item${c?" insights-category-item--active":""}`,onClick:()=>ne(t.category),"aria-current":c?"true":void 0,"data-testid":`insights-category-${t.category}`,children:[e.jsx(a,{size:16,className:"insights-category-icon"}),e.jsx("span",{className:"insights-category-label",children:t.label}),e.jsx("span",{className:"insights-category-count",children:t.items.length})]})},t.category)},Ye=()=>e.jsxs("section",{className:"insights-section insights-recommendations","data-testid":"insights-section-recommendations",children:[e.jsx("div",{className:"insights-section-header",children:e.jsxs("div",{className:"insights-section-title",children:[e.jsx(ve,{size:18,className:"insights-section-icon"}),e.jsx("h3",{children:s("insights.recommendations.title","Task Recommendations")}),e.jsx("span",{className:"insights-section-count",children:l.items.length})]})}),e.jsx("p",{className:"insights-recommendations__count",children:s("insights.recommendations.count","Showing {{shown}} of {{total}} source tasks",{shown:l.items.length,total:l.totalRowCount})}),e.jsx("ul",{className:"insights-list",children:l.items.map(t=>{const a=`${t.taskId}:${t.recommendation.id}`,c=l.createStates.get(a),f=t.recommendation.createdTaskId;return e.jsxs("li",{className:"insight-item insights-recommendations__item","data-testid":`task-recommendation-${a}`,children:[e.jsxs("div",{className:"insight-item-header",children:[e.jsx("h4",{className:"insight-item-title",children:t.recommendation.title}),e.jsx("span",{className:"insights-category-count",children:t.recommendation.category})]}),e.jsx("p",{children:t.recommendation.description}),e.jsx("p",{className:"insights-recommendations__source",children:s("insights.recommendations.source","Source: {{task}}",{task:t.taskTitle?`${t.taskId} — ${t.taskTitle}`:t.taskId})}),f?e.jsx("span",{role:"status",children:s("taskDetail.recommendations.created","Created {{taskId}}",{taskId:f})}):e.jsxs("div",{children:[e.jsx("button",{className:"btn btn-primary",type:"button",disabled:c?.running,onClick:()=>void l.createTask(t.taskId,t.recommendation.id),children:c?.running?s("taskDetail.recommendations.creating","Creating…"):c?.error?s("taskDetail.recommendations.retry","Retry creating task"):s("taskDetail.recommendations.create","Create task")}),c?.error&&e.jsx("span",{role:"status",children:s("taskDetail.recommendations.error","Could not create task. Try again.")})]})]},a)})}),l.truncated?e.jsx("p",{role:"status",children:s("insights.recommendations.truncated","Showing the first 20 pages. Refresh to see the latest recommendations.")}):l.hasMore?e.jsx("button",{className:"btn",type:"button",disabled:l.loadingMore,onClick:()=>void l.loadMore(),children:l.loadingMore?s("insights.recommendations.loadingMore","Loading more…"):s("insights.recommendations.loadMore","Load more")}):null,l.error&&!l.loading&&e.jsxs("div",{role:"status",children:[e.jsx("span",{children:s("insights.recommendations.loadMoreFailed","Could not load more recommendations.")}),e.jsx("button",{className:"btn",type:"button",onClick:()=>void(l.hasMore?l.loadMore():l.refresh()),children:s("actions.retry","Retry")})]})]}),Qe=()=>{if(!W)return null;const t=_e[W.category]??q;return e.jsxs("section",{className:"insights-section","data-testid":`insights-section-${W.category}`,children:[e.jsx("div",{className:"insights-section-header",children:e.jsxs("div",{className:"insights-section-title",children:[e.jsx(t,{size:18,className:"insights-section-icon"}),e.jsx("h3",{children:W.label}),e.jsx("span",{className:"insights-section-count",children:W.items.length})]})}),e.jsx("div",{className:"insights-section-content",children:e.jsx("ul",{className:"insights-list",children:W.items.map(a=>{const c=L.get(a.id),f=_.get(a.id),oe=w.get(a.id),Je=z.get(a.id),pe=c?.running??!1,be=f?.running??!1,ke=oe?.running??!1,Se=Je?.running??!1,we=a.status==="archived",ce=W.items.some(se=>L.get(se.id)?.running||_.get(se.id)?.running||w.get(se.id)?.running||z.get(se.id)?.running);return e.jsxs("li",{className:`insight-item${we?" insight-item--archived":""}`,"data-insight-id":a.id,draggable:ys(),onDragStart:se=>{vs(se.dataTransfer,{kind:"research-finding",id:a.id,projectId:g})},children:[e.jsxs("div",{className:"insight-item-header",children:[e.jsx("h4",{className:"insight-item-title",children:a.title}),e.jsxs("div",{className:"insight-item-actions",children:[we?e.jsx("button",{className:"insight-item-action-btn",onClick:()=>void We(a.id,a.title),disabled:Se||ce,title:s("insights.unarchiveTitle","Unarchive this insight"),"aria-label":s("insights.unarchiveLabel","Unarchive this insight"),"data-testid":`unarchive-${a.id}`,children:Se?e.jsx(K,{size:16,className:"spin"}):e.jsx(fs,{size:16})}):e.jsxs(e.Fragment,{children:[e.jsx("button",{className:"insight-item-action-btn",onClick:()=>void qe(a.id,a.title),disabled:be||ce,title:s("insights.createTaskTitle","Create task from this insight"),"aria-label":s("insights.createTaskLabel","Create task from this insight"),"data-testid":`create-task-${a.id}`,children:be?e.jsx(K,{size:16,className:"spin"}):e.jsx($e,{size:16})}),e.jsx("button",{className:"insight-item-action-btn",onClick:()=>void Xe(a.id,a.title),disabled:ke||ce,title:s("insights.archiveTitle","Archive this insight"),"aria-label":s("insights.archiveLabel","Archive this insight"),"data-testid":`archive-${a.id}`,children:ke?e.jsx(K,{size:16,className:"spin"}):e.jsx(fe,{size:16})})]}),e.jsx("button",{className:"insight-item-action-btn",onClick:()=>void Ve(a.id,a.title),disabled:pe||ce,title:s("insights.dismissTitle","Dismiss this insight"),"aria-label":s("insights.dismissLabel","Dismiss this insight"),"data-testid":`dismiss-${a.id}`,children:pe?e.jsx(K,{size:16,className:"spin"}):e.jsx(Ae,{size:16})})]})]}),a.content&&e.jsx("p",{className:"insight-item-content",children:a.content}),e.jsxs("div",{className:"insight-item-meta",children:[e.jsx("span",{className:`insight-item-status insight-item-status--${a.status}`,children:a.status}),a.createdAt&&e.jsxs("span",{className:"insight-item-date",children:[e.jsx(Pe,{size:12}),new Date(a.createdAt).toLocaleDateString()]})]})]},a.id)})})})]})};return e.jsxs("div",{className:"insights-view","data-testid":"insights-view",children:[e.jsx(hs,{icon:q,title:s("insights.title","Insights"),actions:e.jsxs(e.Fragment,{children:[e.jsxs("span",{className:"insights-view-count",children:[T," ",s("common.total","total")]}),ye>0&&e.jsxs("button",{className:`btn btn-sm insights-backlog-health-toggle${v?" btn-icon--active":""}`,onClick:()=>ee(t=>!t),"aria-pressed":v,"aria-label":v?s("insights.showAllInsights","Show all insights"):s("insights.showBacklogHealth","Show only backlog health insights"),"data-testid":"toggle-backlog-health",title:Ue.join(", "),children:[e.jsx(ds,{size:14}),v?s("insights.allInsights","All Insights"):s("insights.backlogHealth","Backlog")," ",e.jsxs("span",{children:["(",ye,")"]})]}),M&&e.jsx("button",{className:"btn btn-sm insights-view-close",onClick:M,"aria-label":s("actions.closeInsightsView","Close insights view"),title:s("actions.close","Close"),children:e.jsx(Ae,{size:16})}),B>0&&e.jsxs("button",{className:"btn btn-sm insights-show-archived-toggle",onClick:I,"aria-label":Z?s("insights.hideArchived","Hide archived insights"):s("insights.showArchived","Show archived insights"),"data-testid":"toggle-archived-insights",children:[e.jsx(fe,{size:14}),Z?s("insights.hideArchivedLabel","Archived"):s("insights.showArchivedLabel","Archived ({{count}})",{count:B})]}),e.jsx("button",{className:"btn btn-icon btn-sm insights-refresh-btn",onClick:()=>void Q(),disabled:P,"aria-label":s("actions.refreshInsights","Refresh insights"),title:s("actions.refreshInsights","Refresh insights"),"data-testid":"refresh-insights",children:e.jsx(K,{size:14,className:P?"spin":""})}),e.jsxs("button",{className:"btn btn-sm insights-model-toggle",onClick:()=>R(t=>!t),"aria-label":s("insights.configureModel","Configure insight generation model"),"aria-expanded":C,"data-testid":"toggle-model-config",title:j?s("insights.modelConfigured","Model: {{model}}",{model:j}):s("insights.configureModelTitle","Configure model"),children:[e.jsx(gs,{size:14}),j&&e.jsx("span",{className:"insights-model-indicator"})]}),e.jsx("button",{className:"btn btn-primary btn-sm",onClick:()=>void xe(),disabled:N,"aria-label":s("insights.generateInsights","Generate new insights"),"data-testid":"run-insights",children:N?e.jsxs(e.Fragment,{children:[e.jsx(K,{size:14,className:"spin"}),s("insights.generating","Generating...")]}):e.jsxs(e.Fragment,{children:[e.jsx(q,{size:14}),s("insights.generateInsightsBtn","Generate Insights")]})})]})}),C&&e.jsxs("div",{className:"insights-model-config","data-testid":"model-config",children:[e.jsx("label",{htmlFor:"insight-model-select",className:"insights-model-label",children:s("insights.model","Model")}),e.jsx(us,{models:S,value:j,onChange:Oe,placeholder:s("insights.usePlanningDefault","Use planning default"),label:s("insights.generationModel","Insight generation model"),disabled:N,id:"insight-model-select",favoriteProviders:re,favoriteModels:r,onToggleFavorite:ue,onToggleModelFavorite:He,showThinkingLevel:!0,thinkingLevel:V,onThinkingLevelChange:Be,defaultThinkingLevel:"off"})]}),e.jsx("div",{className:"insights-status-region","aria-live":"polite","data-testid":"insights-status",children:k&&e.jsxs("div",{className:`insights-status-message insights-status-message--${x}`,role:x==="error"?"alert":void 0,children:[x==="success"&&e.jsx(De,{size:16}),x==="error"&&e.jsx(ae,{size:16}),x==="info"&&e.jsx(q,{size:16}),e.jsx("span",{children:k})]})}),H&&e.jsxs("div",{className:"insights-error-callout",role:"alert","data-testid":"run-error",children:[e.jsx(ae,{size:16}),e.jsx("span",{children:H})]}),y&&e.jsx("div",{className:"insights-run-info","data-testid":"latest-run",children:e.jsxs("span",{className:"insights-run-status",children:[s("insights.latestRun","Latest run:")," ",y.status,y.status==="completed"&&e.jsxs(e.Fragment,{children:[" — ",s("insights.runCompleted","{{created}} created, {{updated}} updated",{created:y.insightsCreated,updated:y.insightsUpdated})]}),y.status==="failed"&&y.error&&e.jsxs(e.Fragment,{children:[" — ",y.error]})]})}),l.error&&!l.loading&&l.items.length===0&&e.jsxs("div",{className:"insights-error-callout",role:"status","data-testid":"task-recommendations-error",children:[e.jsx(ae,{size:16}),e.jsx("span",{children:s("insights.recommendations.loadMoreFailed","Could not load more recommendations.")}),e.jsx("button",{className:"btn btn-sm",type:"button",onClick:()=>void l.refresh(),children:s("actions.retry","Retry")})]}),P?e.jsxs("div",{className:"insights-loading","data-testid":"insights-loading",children:[e.jsx(K,{size:24,className:"spin"}),e.jsx("p",{children:s("insights.loading","Loading insights...")})]}):U?e.jsxs("div",{className:"insights-error","data-testid":"insights-error",children:[e.jsx(ae,{size:24}),e.jsx("p",{children:U}),e.jsx("button",{className:"btn btn-sm",onClick:()=>void Q(),children:s("actions.retry","Retry")})]}):T===0&&l.items.length===0?e.jsxs("div",{className:"insights-empty","data-testid":"insights-empty",children:[e.jsx(q,{size:48}),e.jsx("h3",{children:s("insights.noInsightsYet","No insights yet")}),e.jsx("p",{children:s("insights.generateDescription","Generate insights to get AI-powered recommendations for your project.")}),e.jsxs("button",{className:"btn btn-primary",onClick:()=>void xe(),children:[e.jsx(q,{size:14}),s("insights.generateFirst","Generate First Insights")]})]}):e.jsxs("div",{className:"insights-body",children:[e.jsx("aside",{className:"insights-sidebar","aria-label":s("insights.categoriesLabel","Insight categories"),children:e.jsxs("ul",{className:"insights-category-list",children:[X.map(Ke),l.items.length>0&&e.jsx("li",{children:e.jsxs("button",{type:"button",className:`insights-category-item${$==="recommendations"?" insights-category-item--active":""}`,onClick:()=>ne("recommendations"),"data-testid":"insights-category-recommendations",children:[e.jsx(ve,{size:16,className:"insights-category-icon"}),e.jsx("span",{className:"insights-category-label",children:s("insights.recommendations.title","Task Recommendations")}),e.jsxs("span",{className:"insights-category-count",children:[l.items.length,l.hasMore?`/${l.totalRowCount}`:""]})]})})]})}),e.jsx("div",{className:"insights-detail",children:$==="recommendations"?Ye():Qe()})]})]})}export{Ls as InsightsView};
11
+ */const bs=[["path",{d:"M3 3v16a2 2 0 0 0 2 2h16",key:"c24i48"}],["path",{d:"m19 9-5 5-4-4-3 3",key:"2osh9i"}]],ks=ze("chart-line",bs),me=["architecture","quality","workflow","performance","reliability","security","ux","testability","documentation","dependency","features","competitive_analysis","research","trends","other"],Fe={quality:"Quality",performance:"Performance",architecture:"Architecture",security:"Security",reliability:"Reliability",ux:"User Experience",testability:"Testability",documentation:"Documentation",dependency:"Dependencies",workflow:"Workflow",other:"Other",features:"Features",competitive_analysis:"Competitive Analysis",research:"Research",trends:"Trends"};function Ss(g,m){const M=Date.parse(g.createdAt),p=Date.parse(m.createdAt),b=Number.isFinite(M),s=Number.isFinite(p);return!b||!s?b?-1:s?1:0:M!==p?p-M:g.id===m.id?0:g.id<m.id?1:-1}function ws(g){const{t:m}=Ge("app"),M=g??"",p=`${je.INSIGHTS_PREFIX}${M}`,b=`${je.INSIGHT_LATEST_RUN_PREFIX}${M}`,s=le(p,{maxAgeMs:Ce}),K=le(b,{maxAgeMs:Me}),P=i.useRef(Array.isArray(s)&&s.length>0),U=i.useCallback(r=>m(`insights.category.${r}`,Fe[r]??r),[m]),[x,N]=i.useState(()=>Array.isArray(s)?s:[]),[H,Q]=i.useState(()=>me.map(r=>({category:r,label:Fe[r]??r,items:[],isLoading:!1,error:null}))),[O,E]=i.useState(!(Array.isArray(s)&&s.length>0)),[Z,F]=i.useState(null),[G,I]=i.useState(K??null),[L,_]=i.useState(!1),[w,z]=i.useState(null),[T,B]=i.useState(new Map),[J,l]=i.useState(new Map),[k,u]=i.useState(new Map),[y,h]=i.useState(new Map),[C,R]=i.useState(!1),v=i.useCallback(async()=>{P.current||E(!0),F(null);try{const n=(await Je({status:void 0,limit:1e3},g)).insights.filter(d=>d.status!=="dismissed");N(n),Ne(p,n.length>500?n.slice(0,500):n,{maxBytes:5e5});const o=await es(g);o.runs.length>0&&(I(o.runs[0]),Ne(b,o.runs[0],{maxBytes:5e5})),P.current=!0}catch(r){const n=r instanceof Error?r.message:"Failed to fetch insights";F(n)}finally{E(!1)}},[p,b,g]),ee=i.useCallback(()=>{R(r=>!r)},[]),j=i.useCallback(async(r,n,o)=>{_(!0),z(null);try{const d=await ss("manual",void 0,g,r,n,o);I(d),d.status==="completed"?await v():d.status==="failed"&&d.error&&z(d.error)}catch(d){if(d instanceof ts&&d.status===409&&d.details?.code==="ACTIVE_RUN_CONFLICT"){const re=typeof d.details.activeRunId=="string"?d.details.activeRunId:null;if(re)try{const ue=await is(re,g);I(ue)}catch{}throw z("Insight generation is already running"),d}const S=d instanceof Error?d.message:"Failed to generate insights";throw z(S),d}finally{_(!1)}},[g,v]),D=i.useCallback(async r=>{B(n=>{const o=new Map(n);return o.set(r,{running:!0,error:null}),o});try{await ns(r,g),N(n=>n.filter(o=>o.id!==r)),B(n=>{const o=new Map(n);return o.set(r,{running:!1,error:null}),o})}catch(n){const o=n instanceof Error?n.message:"Failed to dismiss insight";throw B(d=>{const S=new Map(d);return S.set(r,{running:!1,error:o}),S}),n}},[g]),V=i.useCallback(async r=>{l(n=>{const o=new Map(n);return o.set(r,{running:!0,error:null}),o});try{const n=await as(r,g);return await Ie(r,g),N(o=>o.map(d=>d.id===r?{...d,status:"archived",updatedAt:new Date().toISOString()}:d)),l(o=>{const d=new Map(o);return d.set(r,{running:!1,error:null}),d}),{title:n.suggestedTitle,description:n.suggestedDescription}}catch(n){const o=n instanceof Error?n.message:"Failed to create task";throw l(d=>{const S=new Map(d);return S.set(r,{running:!1,error:o}),S}),n}},[g]);i.useEffect(()=>{const r=new Map;for(const n of me)r.set(n,[]);for(const n of x){if(!C&&n.status==="archived")continue;const o=r.get(n.category)??[];r.set(n.category,[...o,n])}Q(me.map(n=>({category:n,label:U(n),items:[...r.get(n)??[]].sort(Ss),isLoading:!1,error:null})))},[x,C,U]);const he=i.useCallback(async r=>{u(n=>{const o=new Map(n);return o.set(r,{running:!0,error:null}),o});try{await Ie(r,g),N(n=>n.map(o=>o.id===r?{...o,status:"archived",updatedAt:new Date().toISOString()}:o)),u(n=>{const o=new Map(n);return o.set(r,{running:!1,error:null}),o})}catch(n){const o=n instanceof Error?n.message:"Failed to archive insight";throw u(d=>{const S=new Map(d);return S.set(r,{running:!1,error:o}),S}),n}},[g]),de=i.useCallback(async r=>{h(n=>{const o=new Map(n);return o.set(r,{running:!0,error:null}),o});try{await rs(r,g),N(n=>n.map(o=>o.id===r?{...o,status:"confirmed",updatedAt:new Date().toISOString()}:o)),h(n=>{const o=new Map(n);return o.set(r,{running:!1,error:null}),o})}catch(n){const o=n instanceof Error?n.message:"Failed to unarchive insight";throw h(d=>{const S=new Map(d);return S.set(r,{running:!1,error:o}),S}),n}},[g]),ge=i.useMemo(()=>H.reduce((r,n)=>r+n.items.length,0),[H]),A=i.useMemo(()=>0,[]),te=i.useMemo(()=>x.filter(r=>r.status==="archived").length,[x]);return i.useEffect(()=>{const r=le(p,{maxAgeMs:Ce}),n=le(b,{maxAgeMs:Me}),o=Array.isArray(r)&&r.length>0;N(Array.isArray(r)?r:[]),I(n??null),E(!o),P.current=o},[p,b]),i.useEffect(()=>{v()},[v]),{sections:H,loading:O,error:Z,latestRun:G,isRunInFlight:L,runError:w,refresh:v,runInsights:j,dismiss:D,createTask:V,archive:he,unarchive:de,toggleShowArchived:ee,dismissStates:T,createTaskStates:J,archiveStates:k,unarchiveStates:y,totalCount:ge,dismissedCount:A,archivedCount:te,showArchived:C}}const Cs=20,js=50;function Ms(g){const[m,M]=i.useState([]),[p,b]=i.useState(!0),[s,K]=i.useState(!1),[P,U]=i.useState(null),[x,N]=i.useState(!1),[H,Q]=i.useState(0),[O,E]=i.useState(!1),[Z,F]=i.useState(new Map),G=i.useRef(0),I=i.useRef(0),L=i.useRef(!1),_=i.useRef(new Set),w=i.useRef(0),z=i.useRef(g),T=i.useCallback(async k=>{if(L.current)return;L.current=!0;const u=w.current,y=k?0:G.current;k?b(!0):K(!0),U(null);try{const h=await os(g,{limit:js,offset:y});if(u!==w.current)return;M(v=>{const ee=k?[]:v,j=new Set(ee.map(D=>`${D.taskId}:${D.recommendation.id}`));return[...ee,...h.items.filter(D=>{const V=`${D.taskId}:${D.recommendation.id}`;return j.has(V)?!1:(j.add(V),!0)})]}),G.current=h.rowOffset+h.returnedRowCount,I.current=k?1:I.current+1,Q(h.totalRowCount);const R=I.current>=Cs&&h.hasMore;E(R),N(R?!1:h.hasMore)}catch(h){u===w.current&&U(h instanceof Error?h.message:"Failed to fetch task recommendations")}finally{u===w.current&&(b(!1),K(!1)),L.current=!1}},[g]),B=i.useCallback(async()=>{G.current=0,I.current=0,E(!1),await T(!0)},[T]);i.useEffect(()=>{z.current=g,w.current+=1,L.current=!1,_.current.clear(),G.current=0,I.current=0,M([]),N(!1),Q(0),E(!1),F(new Map),T(!0)},[T,g]);const J=i.useCallback(async()=>{!x||O||L.current||await T(!1)},[T,x,O]),l=i.useCallback(async(k,u)=>{const y=`${k}:${u}`;if(_.current.has(y))return;_.current.add(y);const h=w.current;F(C=>new Map(C).set(y,{running:!0,error:null}));try{const C=await cs(k,u,z.current);if(h!==w.current)return;M(R=>R.map(v=>v.taskId===k&&v.recommendation.id===u?{...v,recommendation:{...v.recommendation,createdTaskId:C.task.id}}:v)),F(R=>new Map(R).set(y,{running:!1,error:null}))}catch(C){h===w.current&&F(R=>new Map(R).set(y,{running:!1,error:C instanceof Error?C.message:"Could not create task"}))}finally{h===w.current&&_.current.delete(y)}},[]);return{items:m,loading:p,loadingMore:s,error:P,hasMore:x,totalRowCount:H,truncated:O,refresh:B,loadMore:J,createTask:l,createStates:Z}}const Ue=["Backlog health:","Backlog pressure detected","Stale paused todo","Backlog health: dependency-blocked todos"];function Le(g){return Ue.some(m=>g.title.startsWith(m))}const _e={architecture:ps,quality:De,workflow:Pe,performance:Te,reliability:q,security:ae,ux:Ee,testability:fe,documentation:ms,dependency:$e,features:ve,competitive_analysis:Ee,research:ks,trends:Te,other:Y};function Ls({projectId:g,addToast:m,onClose:M,onCreateTask:p,models:b}){const{t:s}=Ge("app"),{sections:K,loading:P,error:U,latestRun:x,isRunInFlight:N,runError:H,refresh:Q,runInsights:O,dismiss:E,createTask:Z,archive:F=async()=>{},unarchive:G=async()=>{},toggleShowArchived:I=()=>{},dismissStates:L,createTaskStates:_,archiveStates:w=new Map,unarchiveStates:z=new Map,totalCount:T,archivedCount:B=0,showArchived:J=!1}=ws(g),l=Ms(g),[k,u]=i.useState(null),[y,h]=i.useState("info"),[C,R]=i.useState(!1),[v,ee]=i.useState(!1),[j,D]=i.useState(()=>localStorage.getItem("fusion-insight-model")??""),[V,he]=i.useState(()=>localStorage.getItem("fusion-insight-thinking")??""),[de,ge]=i.useState([]),[A,te]=i.useState([]),[r,n]=i.useState([]),[o,d]=i.useState();i.useEffect(()=>{b||ls().then(t=>{ge(t.models),te(t.favoriteProviders),n(t.favoriteModels),d(t.resolvedPlanningProvider);const a=localStorage.getItem("fusion-insight-model");a&&(t.models.some(f=>`${f.provider}/${f.id}`===a)||(localStorage.removeItem("fusion-insight-model"),D("")))}).catch(()=>{})},[b]);const S=b??de,re=i.useMemo(()=>A.length>0?A:o?[o]:[],[A,o]),ue=i.useCallback(async t=>{const c=A.includes(t)?A.filter(f=>f!==t):[t,...A];te(c);try{await Re({favoriteProviders:c,favoriteModels:r})}catch{te(A)}},[A,r]),He=i.useCallback(async t=>{const c=r.includes(t)?r.filter(f=>f!==t):[t,...r];n(c);try{await Re({favoriteProviders:A,favoriteModels:c})}catch{n(r)}},[r,A]),Oe=i.useCallback(t=>{D(t),t?localStorage.setItem("fusion-insight-model",t):localStorage.removeItem("fusion-insight-model")},[]),Be=i.useCallback(t=>{he(t),t?localStorage.setItem("fusion-insight-thinking",t):localStorage.removeItem("fusion-insight-thinking")},[]),ie=i.useMemo(()=>K.filter(t=>t.items.length>0),[K]),xe=i.useMemo(()=>ie.reduce((t,a)=>t+a.items.filter(Le).length,0),[ie]),X=i.useMemo(()=>v?ie.map(t=>({...t,items:t.items.filter(Le)})).filter(t=>t.items.length>0):ie,[ie,v]),[$,ne]=i.useState(null);i.useEffect(()=>{if($==="recommendations"&&l.items.length>0)return;if(X.length===0){l.items.length>0?ne("recommendations"):$!==null&&ne(null);return}$&&X.some(a=>a.category===$&&a.items.length>0)||ne(X[0]?.category??(l.items.length>0?"recommendations":null))},[X,$,l.items.length]);const W=i.useMemo(()=>$==="recommendations"?void 0:X.find(t=>t.category===$)??X[0],[X,$]);i.useEffect(()=>{if(k){const t=setTimeout(()=>u(null),5e3);return()=>clearTimeout(t)}},[k]);const ye=i.useCallback(async()=>{try{u(s("insights.generatingInsights","Generating insights...")),h("info");let t,a;if(j){const c=j.indexOf("/");if(c!==-1){const f=j.slice(0,c),oe=j.slice(c+1);f&&oe&&(t=f,a=oe)}}await O(t,a,V||void 0),u(s("insights.generationStarted","Insight generation started")),h("success"),m(s("insights.generationStarted","Insight generation started"),"success")}catch(t){const a=t instanceof Error?t.message:s("insights.failedToStart","Failed to start generation");if(a==="Insight generation is already running"){u(s("insights.alreadyRunning","Insight generation is already running. Showing the active run.")),h("info"),m(s("insights.alreadyRunningShort","Insight generation is already running"),"info");return}u(a),h("error"),m(a,"error")}},[O,m,j,V,s]),Ve=i.useCallback(async(t,a)=>{try{u(s("insights.dismissing",'Dismissing "{{title}}"...',{title:a})),h("info"),await E(t),u(s("insights.dismissed",'Dismissed "{{title}}"',{title:a})),h("success"),m(s("insights.dismissedMsg","Insight dismissed: {{title}}",{title:a}),"success")}catch(c){const f=c instanceof Error?c.message:s("insights.failedToDismiss","Failed to dismiss insight");u(f),h("error"),m(f,"error")}},[E,m,s]),Xe=i.useCallback(async(t,a)=>{try{u(s("insights.archiving",'Archiving "{{title}}"...',{title:a})),h("info"),await F(t),u(s("insights.archived",'Archived "{{title}}"',{title:a})),h("success"),m(s("insights.archivedMsg","Insight archived: {{title}}",{title:a}),"success")}catch(c){const f=c instanceof Error?c.message:s("insights.failedToArchive","Failed to archive insight");u(f),h("error"),m(f,"error")}},[F,m,s]),We=i.useCallback(async(t,a)=>{try{u(s("insights.unarchiving",'Unarchiving "{{title}}"...',{title:a})),h("info"),await G(t),u(s("insights.unarchived",'Unarchived "{{title}}"',{title:a})),h("success"),m(s("insights.unarchivedMsg","Insight unarchived: {{title}}",{title:a}),"success")}catch(c){const f=c instanceof Error?c.message:s("insights.failedToUnarchive","Failed to unarchive insight");u(f),h("error"),m(f,"error")}},[G,m,s]),Ye=i.useCallback(async(t,a)=>{try{if(u(s("insights.creatingTask",'Creating task from "{{title}}"...',{title:a})),h("info"),!p)throw new Error(s("insights.taskCreationUnavailable","Task creation is unavailable in this view"));const c=await Z(t);if(!c)throw new Error(s("insights.failedToPreparePayload","Failed to prepare task payload from insight"));await p({insightId:t,title:c.title,description:c.description}),u(s("insights.taskCreated",'Task created from "{{title}}"',{title:a})),h("success"),m(s("insights.taskCreatedMsg","Task created: {{title}}",{title:c.title}),"success")}catch(c){const f=c instanceof Error?c.message:s("insights.failedToCreateTask","Failed to create task");u(f),h("error"),m(f,"error")}},[Z,p,m,s]),qe=t=>{const a=_e[t.category]??Y,c=W?.category===t.category;return e.jsx("li",{children:e.jsxs("button",{type:"button",className:`insights-category-item${c?" insights-category-item--active":""}`,onClick:()=>ne(t.category),"aria-current":c?"true":void 0,"data-testid":`insights-category-${t.category}`,children:[e.jsx(a,{size:16,className:"insights-category-icon"}),e.jsx("span",{className:"insights-category-label",children:t.label}),e.jsx("span",{className:"insights-category-count",children:t.items.length})]})},t.category)},Ke=()=>e.jsxs("section",{className:"insights-section insights-recommendations","data-testid":"insights-section-recommendations",children:[e.jsx("div",{className:"insights-section-header",children:e.jsxs("div",{className:"insights-section-title",children:[e.jsx(ve,{size:18,className:"insights-section-icon"}),e.jsx("h3",{children:s("insights.recommendations.title","Task Recommendations")}),e.jsx("span",{className:"insights-section-count",children:l.items.length})]})}),e.jsx("p",{className:"insights-recommendations__count",children:s("insights.recommendations.count","Showing {{shown}} of {{total}} source tasks",{shown:l.items.length,total:l.totalRowCount})}),e.jsx("ul",{className:"insights-list",children:l.items.map(t=>{const a=`${t.taskId}:${t.recommendation.id}`,c=l.createStates.get(a),f=t.recommendation.createdTaskId;return e.jsxs("li",{className:"insight-item insights-recommendations__item","data-testid":`task-recommendation-${a}`,children:[e.jsxs("div",{className:"insight-item-header",children:[e.jsx("h4",{className:"insight-item-title",children:t.recommendation.title}),e.jsx("span",{className:"insights-category-count",children:t.recommendation.category})]}),e.jsx("p",{children:t.recommendation.description}),e.jsx("p",{className:"insights-recommendations__source",children:s("insights.recommendations.source","Source: {{task}}",{task:t.taskTitle?`${t.taskId} — ${t.taskTitle}`:t.taskId})}),f?e.jsx("span",{role:"status",children:s("taskDetail.recommendations.created","Created {{taskId}}",{taskId:f})}):e.jsxs("div",{children:[e.jsx("button",{className:"btn btn-primary",type:"button",disabled:c?.running,onClick:()=>void l.createTask(t.taskId,t.recommendation.id),children:c?.running?s("taskDetail.recommendations.creating","Creating…"):c?.error?s("taskDetail.recommendations.retry","Retry creating task"):s("taskDetail.recommendations.create","Create task")}),c?.error&&e.jsx("span",{role:"status",children:s("taskDetail.recommendations.error","Could not create task. Try again.")})]})]},a)})}),l.truncated?e.jsx("p",{role:"status",children:s("insights.recommendations.truncated","Showing the first 20 pages. Refresh to see the latest recommendations.")}):l.hasMore?e.jsx("button",{className:"btn",type:"button",disabled:l.loadingMore,onClick:()=>void l.loadMore(),children:l.loadingMore?s("insights.recommendations.loadingMore","Loading more…"):s("insights.recommendations.loadMore","Load more")}):null,l.error&&!l.loading&&e.jsxs("div",{role:"status",children:[e.jsx("span",{children:s("insights.recommendations.loadMoreFailed","Could not load more recommendations.")}),e.jsx("button",{className:"btn",type:"button",onClick:()=>void(l.hasMore?l.loadMore():l.refresh()),children:s("actions.retry","Retry")})]})]}),Qe=()=>{if(!W)return null;const t=_e[W.category]??Y;return e.jsxs("section",{className:"insights-section","data-testid":`insights-section-${W.category}`,children:[e.jsx("div",{className:"insights-section-header",children:e.jsxs("div",{className:"insights-section-title",children:[e.jsx(t,{size:18,className:"insights-section-icon"}),e.jsx("h3",{children:W.label}),e.jsx("span",{className:"insights-section-count",children:W.items.length})]})}),e.jsx("div",{className:"insights-section-content",children:e.jsx("ul",{className:"insights-list",children:W.items.map(a=>{const c=L.get(a.id),f=_.get(a.id),oe=w.get(a.id),Ze=z.get(a.id),pe=c?.running??!1,be=f?.running??!1,ke=oe?.running??!1,Se=Ze?.running??!1,we=a.status==="archived",ce=W.items.some(se=>L.get(se.id)?.running||_.get(se.id)?.running||w.get(se.id)?.running||z.get(se.id)?.running);return e.jsxs("li",{className:`insight-item${we?" insight-item--archived":""}`,"data-insight-id":a.id,draggable:xs(),onDragStart:se=>{vs(se.dataTransfer,{kind:"research-finding",id:a.id,projectId:g})},children:[e.jsxs("div",{className:"insight-item-header",children:[e.jsx("h4",{className:"insight-item-title",children:a.title}),e.jsxs("div",{className:"insight-item-actions",children:[we?e.jsx("button",{className:"insight-item-action-btn",onClick:()=>void We(a.id,a.title),disabled:Se||ce,title:s("insights.unarchiveTitle","Unarchive this insight"),"aria-label":s("insights.unarchiveLabel","Unarchive this insight"),"data-testid":`unarchive-${a.id}`,children:Se?e.jsx(q,{size:16,className:"spin"}):e.jsx(fs,{size:16})}):e.jsxs(e.Fragment,{children:[e.jsx("button",{className:"insight-item-action-btn",onClick:()=>void Ye(a.id,a.title),disabled:be||ce,title:s("insights.createTaskTitle","Create task from this insight"),"aria-label":s("insights.createTaskLabel","Create task from this insight"),"data-testid":`create-task-${a.id}`,children:be?e.jsx(q,{size:16,className:"spin"}):e.jsx($e,{size:16})}),e.jsx("button",{className:"insight-item-action-btn",onClick:()=>void Xe(a.id,a.title),disabled:ke||ce,title:s("insights.archiveTitle","Archive this insight"),"aria-label":s("insights.archiveLabel","Archive this insight"),"data-testid":`archive-${a.id}`,children:ke?e.jsx(q,{size:16,className:"spin"}):e.jsx(fe,{size:16})})]}),e.jsx("button",{className:"insight-item-action-btn",onClick:()=>void Ve(a.id,a.title),disabled:pe||ce,title:s("insights.dismissTitle","Dismiss this insight"),"aria-label":s("insights.dismissLabel","Dismiss this insight"),"data-testid":`dismiss-${a.id}`,children:pe?e.jsx(q,{size:16,className:"spin"}):e.jsx(Ae,{size:16})})]})]}),a.content&&e.jsx("p",{className:"insight-item-content",children:a.content}),e.jsxs("div",{className:"insight-item-meta",children:[e.jsx("span",{className:`insight-item-status insight-item-status--${a.status}`,children:a.status}),a.createdAt&&e.jsxs("span",{className:"insight-item-date",children:[e.jsx(Pe,{size:12}),new Date(a.createdAt).toLocaleDateString()]})]})]},a.id)})})})]})};return e.jsxs("div",{className:"insights-view","data-testid":"insights-view",children:[e.jsx(hs,{icon:Y,title:s("insights.title","Insights"),actions:e.jsxs(e.Fragment,{children:[e.jsxs("span",{className:"insights-view-count",children:[T," ",s("common.total","total")]}),xe>0&&e.jsxs("button",{className:`btn btn-sm insights-backlog-health-toggle${v?" btn-icon--active":""}`,onClick:()=>ee(t=>!t),"aria-pressed":v,"aria-label":v?s("insights.showAllInsights","Show all insights"):s("insights.showBacklogHealth","Show only backlog health insights"),"data-testid":"toggle-backlog-health",title:Ue.join(", "),children:[e.jsx(ds,{size:14}),v?s("insights.allInsights","All Insights"):s("insights.backlogHealth","Backlog")," ",e.jsxs("span",{children:["(",xe,")"]})]}),M&&e.jsx("button",{className:"btn btn-sm insights-view-close",onClick:M,"aria-label":s("actions.closeInsightsView","Close insights view"),title:s("actions.close","Close"),children:e.jsx(Ae,{size:16})}),B>0&&e.jsxs("button",{className:"btn btn-sm insights-show-archived-toggle",onClick:I,"aria-label":J?s("insights.hideArchived","Hide archived insights"):s("insights.showArchived","Show archived insights"),"data-testid":"toggle-archived-insights",children:[e.jsx(fe,{size:14}),J?s("insights.hideArchivedLabel","Archived"):s("insights.showArchivedLabel","Archived ({{count}})",{count:B})]}),e.jsx("button",{className:"btn btn-icon btn-sm insights-refresh-btn",onClick:()=>void Q(),disabled:P,"aria-label":s("actions.refreshInsights","Refresh insights"),title:s("actions.refreshInsights","Refresh insights"),"data-testid":"refresh-insights",children:e.jsx(q,{size:14,className:P?"spin":""})}),e.jsxs("button",{className:"btn btn-sm insights-model-toggle",onClick:()=>R(t=>!t),"aria-label":s("insights.configureModel","Configure insight generation model"),"aria-expanded":C,"data-testid":"toggle-model-config",title:j?s("insights.modelConfigured","Model: {{model}}",{model:j}):s("insights.configureModelTitle","Configure model"),children:[e.jsx(gs,{size:14}),j&&e.jsx("span",{className:"insights-model-indicator"})]}),e.jsx("button",{className:"btn btn-primary btn-sm",onClick:()=>void ye(),disabled:N,"aria-label":s("insights.generateInsights","Generate new insights"),"data-testid":"run-insights",children:N?e.jsxs(e.Fragment,{children:[e.jsx(q,{size:14,className:"spin"}),s("insights.generating","Generating...")]}):e.jsxs(e.Fragment,{children:[e.jsx(Y,{size:14}),s("insights.generateInsightsBtn","Generate Insights")]})})]})}),C&&e.jsxs("div",{className:"insights-model-config","data-testid":"model-config",children:[e.jsx("label",{htmlFor:"insight-model-select",className:"insights-model-label",children:s("insights.model","Model")}),e.jsx(us,{models:S,value:j,onChange:Oe,placeholder:s("insights.usePlanningDefault","Use planning default"),label:s("insights.generationModel","Insight generation model"),disabled:N,id:"insight-model-select",favoriteProviders:re,favoriteModels:r,onToggleFavorite:ue,onToggleModelFavorite:He,showThinkingLevel:!0,thinkingLevel:V,onThinkingLevelChange:Be,defaultThinkingLevel:"off"})]}),e.jsx("div",{className:"insights-status-region","aria-live":"polite","data-testid":"insights-status",children:k&&e.jsxs("div",{className:`insights-status-message insights-status-message--${y}`,role:y==="error"?"alert":void 0,children:[y==="success"&&e.jsx(De,{size:16}),y==="error"&&e.jsx(ae,{size:16}),y==="info"&&e.jsx(Y,{size:16}),e.jsx("span",{children:k})]})}),H&&e.jsxs("div",{className:"insights-error-callout",role:"alert","data-testid":"run-error",children:[e.jsx(ae,{size:16}),e.jsx("span",{children:H})]}),x&&e.jsx("div",{className:"insights-run-info","data-testid":"latest-run",children:e.jsxs("span",{className:"insights-run-status",children:[s("insights.latestRun","Latest run:")," ",x.status,x.status==="completed"&&e.jsxs(e.Fragment,{children:[" — ",s("insights.runCompleted","{{created}} created, {{updated}} updated",{created:x.insightsCreated,updated:x.insightsUpdated})]}),x.status==="failed"&&x.error&&e.jsxs(e.Fragment,{children:[" — ",x.error]})]})}),l.error&&!l.loading&&l.items.length===0&&e.jsxs("div",{className:"insights-error-callout",role:"status","data-testid":"task-recommendations-error",children:[e.jsx(ae,{size:16}),e.jsx("span",{children:s("insights.recommendations.loadMoreFailed","Could not load more recommendations.")}),e.jsx("button",{className:"btn btn-sm",type:"button",onClick:()=>void l.refresh(),children:s("actions.retry","Retry")})]}),P?e.jsxs("div",{className:"insights-loading","data-testid":"insights-loading",children:[e.jsx(q,{size:24,className:"spin"}),e.jsx("p",{children:s("insights.loading","Loading insights...")})]}):U?e.jsxs("div",{className:"insights-error","data-testid":"insights-error",children:[e.jsx(ae,{size:24}),e.jsx("p",{children:U}),e.jsx("button",{className:"btn btn-sm",onClick:()=>void Q(),children:s("actions.retry","Retry")})]}):T===0&&l.items.length===0?e.jsxs("div",{className:"insights-empty","data-testid":"insights-empty",children:[e.jsx(Y,{size:48}),e.jsx("h3",{children:s("insights.noInsightsYet","No insights yet")}),e.jsx("p",{children:s("insights.generateDescription","Generate insights to get AI-powered recommendations for your project.")}),e.jsxs("button",{className:"btn btn-primary",onClick:()=>void ye(),children:[e.jsx(Y,{size:14}),s("insights.generateFirst","Generate First Insights")]})]}):e.jsxs("div",{className:"insights-body",children:[e.jsx("aside",{className:"insights-sidebar","aria-label":s("insights.categoriesLabel","Insight categories"),children:e.jsxs("ul",{className:"insights-category-list",children:[X.map(qe),l.items.length>0&&e.jsx("li",{children:e.jsxs("button",{type:"button",className:`insights-category-item${$==="recommendations"?" insights-category-item--active":""}`,onClick:()=>ne("recommendations"),"data-testid":"insights-category-recommendations",children:[e.jsx(ve,{size:16,className:"insights-category-icon"}),e.jsx("span",{className:"insights-category-label",children:s("insights.recommendations.title","Task Recommendations")}),e.jsxs("span",{className:"insights-category-count",children:[l.items.length,l.hasMore?`/${l.totalRowCount}`:""]})]})})]})}),e.jsx("div",{className:"insights-detail",children:$==="recommendations"?Ke():Qe()})]})]})}export{Ls as InsightsView};
@@ -0,0 +1,3 @@
1
+ import{r as n,j as e}from"./vendor-react-SZ_qB27O.js";import{u as $e,f as we,a as ke,s as Ke,i as _e,t as Ue,b as Ce,c as Ee,d as Be,e as Qe,g as We,h as Ve}from"./SettingsModal-CJof1Ett.js";import{a as ee,w as te,dc as Ye,a_ as Xe,V as Ze,dd as Je,L as _,aL as Fe}from"./index-I32FijPT.js";import{u as Ne}from"./vendor-i18n-Duky4gdQ.js";import"./vendor-codemirror-CcrtqoCy.js";import"./vendor-reactflow-BlIeoTu4.js";import"./vendor-xterm-BNq00GSj.js";function pe(i){const s=Object.entries(i).flatMap(([r,t])=>Array.isArray(t)?t.filter(Boolean).map(c=>[r,c]):t===void 0||t===""?[]:[[r,String(t)]]);return s.length?`?${s.map(([r,t])=>`${encodeURIComponent(r)}=${encodeURIComponent(t)}`).join("&")}`:""}function et(i){return ee(te("/knowledge/graph/status",i))}function tt(i,s={}){return ee(te(`/knowledge/graph/nodes${pe(s)}`,i))}function st(i,s){return ee(te(`/knowledge/graph/node${pe({id:s})}`,i))}function Ae(i,s){return ee(te(`/knowledge/graph/neighbors${pe(s)}`,i))}function at(i,s){return ee(te(`/knowledge/graph/path${pe(s)}`,i))}function nt(i,s=!1){return ee(te("/knowledge/graph/build",i),{method:"POST",body:JSON.stringify({force:s})})}const J=".fusion/memory/MEMORY.md",rt=5e4,lt="0 3 * * *",it="0 4 * * *";function ge(i){return{memoryEnabled:i.memoryEnabled!==!1,memoryAutoSummarizeEnabled:i.memoryAutoSummarizeEnabled??!1,memoryAutoSummarizeThresholdChars:i.memoryAutoSummarizeThresholdChars??rt,memoryAutoSummarizeSchedule:i.memoryAutoSummarizeSchedule??lt,memoryDreamsEnabled:i.memoryDreamsEnabled??!1,memoryDreamsSchedule:i.memoryDreamsSchedule??it}}function Me(i,s){return i.some(r=>r.path===s)?s:i.find(r=>r.path===J)?.path??i[0]?.path??J}function ot(i={}){const{projectId:s}=i,[r,t]=n.useState(null),[c,v]=n.useState(!0),[d,M]=n.useState(!1),[E,k]=n.useState(()=>ge({})),[f,w]=n.useState(!0),[m,a]=n.useState(!1),[h,F]=n.useState([]),[U,G]=n.useState(!0),[N,D]=n.useState(J),[I,R]=n.useState(""),[se,B]=n.useState(!1),[p,g]=n.useState(!1),[H,L]=n.useState(!1),[S,P]=n.useState(!1),[Y,T]=n.useState(!1),[x,Q]=n.useState(null),[u,y]=n.useState(!0),[b,W]=n.useState(!1),[le,ae]=n.useState(!1),{status:ne,loading:be,refresh:$}=$e({projectId:s}),re=n.useCallback(o=>{R(o),g(!0)},[]),X=n.useCallback(async o=>{B(!0);try{const{content:j}=await we(o,s);D(o),R(j),g(!1)}finally{B(!1)}},[s]),q=n.useCallback(async()=>{G(!0);try{const{files:o}=await ke(s);if(F(o),o.length===0){D(J),R(""),g(!1);return}const j=Me(o,N);j!==N&&await X(j)}finally{G(!1)}},[s,N,X]);n.useEffect(()=>{let o=!1;async function j(){try{const A=await Ee(s);o||(t(A.content),M(A.exists),v(!1))}catch{o||(t(null),M(!1),v(!1))}}return j(),()=>{o=!0}},[s]),n.useEffect(()=>{let o=!1;async function j(){w(!0);try{const A=await Xe(s);o||k(ge(A))}catch{o||k(ge({}))}finally{o||w(!1)}}return j(),()=>{o=!0}},[s]);const ie=n.useRef(N);n.useEffect(()=>{ie.current=N},[N]),n.useEffect(()=>{let o=!1;async function j(){G(!0);try{const{files:A}=await ke(s);if(o)return;if(F(A),A.length===0){D(J),R(""),g(!1);return}const ue=Me(A,ie.current),{content:je}=await we(ue,s);if(o)return;D(ue),R(je),g(!1)}catch{o||(F([]),D(J),R(""),g(!1))}finally{o||G(!1)}}return j(),()=>{o=!0}},[s]),n.useEffect(()=>{let o=!1;async function j(){try{const A=await Ce(s);o||(Q(A),y(!1))}catch{o||(Q(null),y(!1))}}return j(),()=>{o=!0}},[s]);const oe=n.useCallback(async o=>{a(!0);try{const j=await Ye(o,s);k(ge(j))}finally{a(!1)}},[s]),me=n.useCallback(async o=>{await X(o)},[X]),ce=n.useCallback(async()=>{if(p){L(!0);try{await Ke(N,I,s),g(!1),await q()}finally{L(!1)}}},[I,p,N,s,q]),de=n.useCallback(async()=>{ae(!0);try{const o=await _e(s);return await $(),o}finally{ae(!1)}},[s,$]),he=n.useCallback(async o=>Ue(o,s),[s]),Z=n.useCallback(async()=>{try{const o=await Ce(s);Q(o)}catch{Q(null)}},[s]),K=n.useCallback(async()=>{try{const o=await Ee(s);t(o.content),M(o.exists)}catch{t(null),M(!1)}},[s]),z=n.useCallback(async o=>{await Be(o,s),await K()},[s,K]),xe=n.useCallback(async()=>{P(!0);try{const o=await Qe(s);return await Promise.all([K(),Z()]),{success:o.success,summary:o.summary}}finally{P(!1)}},[s,K,Z]),V=n.useCallback(async()=>{T(!0);try{return await We(s)}finally{T(!1)}},[s]),fe=n.useCallback(async o=>{W(!0);try{const j=await Ve(o,s),A=j.path??o;D(A),R(j.content),g(!1),await q()}finally{W(!1)}},[s,q]);return{insightsContent:r,insightsLoading:c,insightsExists:d,refreshInsights:K,saveInsights:z,memorySettings:E,settingsLoading:f,savingMemorySettings:m,saveMemorySettings:oe,memoryFiles:h,memoryFilesLoading:U,selectedFilePath:N,selectedFileContent:I,selectedFileLoading:se,selectedFileDirty:p,setSelectedFileContent:re,selectFile:me,saveSelectedFile:ce,savingSelectedFile:H,reloadMemoryFiles:q,backendStatus:ne,backendLoading:be,extractInsights:xe,extracting:S,triggerDreamNow:V,dreamRunning:Y,auditReport:x,auditLoading:u,refreshAudit:Z,compactMemory:fe,compacting:b,installQmdAction:de,installingQmd:le,testRetrieval:he}}const De={limit:50,offset:0};function mt({projectId:i,enabled:s}){const[r,t]=n.useState(null),[c,v]=n.useState(De),[d,M]=n.useState(null),[E,k]=n.useState(null),[f,w]=n.useState(null),[m,a]=n.useState({direction:"both",depth:1}),[h,F]=n.useState(null),[U,G]=n.useState({fromId:"",toId:"",maxHops:6}),[N,D]=n.useState(null),[I,R]=n.useState(!1),[se,B]=n.useState(!1),[p,g]=n.useState(null),H=n.useRef(0),L=n.useRef(0),S=n.useRef(0),P=n.useCallback(async()=>{try{const u=await et(i);t(u),G(y=>({...y,maxHops:u.pathLimits.defaultMaxHops}))}catch(u){g(u instanceof Error?u.message:String(u))}},[i]);n.useEffect(()=>{P()},[s,P]),n.useEffect(()=>{if(!r?.available)return;const u=++H.current;R(!0);const y=window.setTimeout(()=>void tt(i,c).then(b=>{u===H.current&&M(b)}).catch(b=>{u===H.current&&g(b instanceof Error?b.message:String(b))}).finally(()=>{u===H.current&&R(!1)}),250);return()=>window.clearTimeout(y)},[s,c,i,r?.available]);const Y=n.useCallback(async(u=E)=>{if(!u)return;const y=++L.current;try{const b=await Ae(i,{nodeId:u,...m});y===L.current&&F(b)}catch(b){y===L.current&&g(b instanceof Error?b.message:String(b))}},[m,i,E]),T=n.useCallback(async u=>{const y=++L.current;k(u);try{const[b,W]=await Promise.all([st(i,u),Ae(i,{nodeId:u,...m})]);y===L.current&&(w(b),F(W))}catch(b){y===L.current&&g(b instanceof Error?b.message:String(b))}},[m,i]),x=n.useCallback(async()=>{const u=++S.current;D(null),g(null);try{const y=await at(i,U);u===S.current&&D(y)}catch(y){u===S.current&&g(y instanceof Error?y.message:String(y))}},[U,i]),Q=n.useCallback(async(u=!1)=>{B(!0);try{await nt(i,u),await P()}catch(y){g(y instanceof Error?y.message:String(y))}finally{B(!1)}},[i,P]);return{status:r,filters:c,setFilters:v,nodes:d,loading:I,selectedId:E,detail:f,selectNode:T,neighborOptions:m,setNeighborOptions:a,neighborResults:h,refreshNeighbors:Y,pathInput:U,setPathInput:G,pathResult:N,findPath:x,rebuild:Q,rebuilding:se,refreshStatus:P,error:p,clearFilters:()=>v(De)}}const ct=["file","module","symbol","doc-concept","rationale"],dt=["function","class","interface","type-alias","enum","variable","namespace","alias"],ht=["contains","imports","re-exports","relates-to","rationale-supports"];function ve({id:i,onSelect:s}){return e.jsx("button",{type:"button",className:"btn btn-ghost knowledge-graph-endpoint",onClick:()=>s(i),children:i})}function Ie({title:i,edges:s,total:r,endpoint:t,onSelect:c}){const{t:v}=Ne("app");return e.jsxs("section",{className:"knowledge-graph-edge-list",children:[e.jsxs("h4",{children:[i," ",e.jsx("span",{children:v("knowledgeGraph.showingOf","showing {{shown}} of {{total}}",{shown:s.length,total:r})})]}),s.length===0?e.jsx("p",{className:"knowledge-graph-muted",children:v("knowledgeGraph.none","None")}):e.jsx("ul",{children:s.map(d=>e.jsxs("li",{children:[e.jsx("span",{children:d.kind}),e.jsx("span",{className:`knowledge-graph-provenance knowledge-graph-provenance--${d.provenance}`,children:d.provenance}),e.jsx(ve,{id:d[t],onSelect:c})]},d.id))})]})}function ut({projectId:i,addToast:s}){const{t:r}=Ne("app"),t=mt({projectId:i,enabled:!0}),[c,v]=n.useState(!1);if(n.useEffect(()=>{t.error&&s(t.error,"error")},[s,t.error]),!t.status&&t.error)return e.jsx("div",{className:"knowledge-graph-panel knowledge-graph-error","data-testid":"knowledge-graph-error",children:t.error});if(!t.status)return e.jsx("div",{className:"knowledge-graph-panel","data-testid":"knowledge-graph-loading",children:r("memory.graphLoading","Loading knowledge graph…")});if(!t.status.available)return e.jsxs("div",{className:"knowledge-graph-panel knowledge-graph-empty","data-testid":"knowledge-graph-no-graph",children:[e.jsxs("p",{children:[r("memory.graphUnavailable","Graph unavailable"),": ",t.status.recoveryReason]}),e.jsx("button",{type:"button",className:"btn",onClick:()=>void t.rebuild(!1),children:r("memory.graphBuild","Build graph")})]});const d=a=>t.setFilters({...t.filters,...a,offset:0}),M=a=>{const h=t.filters.kinds??[];d({kinds:h.includes(a)?h.filter(F=>F!==a):[...h,a]})},E=a=>{const h=t.neighborOptions.edgeKinds??[];t.setNeighborOptions({...t.neighborOptions,edgeKinds:h.includes(a)?h.filter(F=>F!==a):[...h,a]})},k=t.selectedId,f=t.status.pathLimits,w=t.pathResult?.outcome==="found"?t.pathResult.path:null,m=t.pathResult?.outcome==="found"?t.pathResult.hops:void 0;return e.jsxs("section",{className:"knowledge-graph-panel","data-testid":"knowledge-graph-panel",children:[e.jsxs("header",{className:"knowledge-graph-status card",children:[e.jsxs("div",{children:[e.jsxs("strong",{children:[t.status.nodeCount," ",r("memory.graphNodes","nodes")," · ",t.status.edgeCount," ",r("memory.graphEdges","edges")]}),e.jsx("span",{children:t.status.graphDir})]}),e.jsxs("dl",{children:[e.jsxs("div",{children:[e.jsx("dt",{children:r("knowledgeGraph.nodeKinds","Node kinds")}),e.jsx("dd",{children:Object.entries(t.status.nodeKindCounts??{}).map(([a,h])=>`${a}: ${h}`).join(" · ")||"—"})]}),e.jsxs("div",{children:[e.jsx("dt",{children:r("knowledgeGraph.edgeKinds","Edge kinds")}),e.jsx("dd",{children:Object.entries(t.status.edgeKindCounts??{}).map(([a,h])=>`${a}: ${h}`).join(" · ")||"—"})]}),e.jsxs("div",{children:[e.jsx("dt",{children:r("knowledgeGraph.provenance","Provenance")}),e.jsx("dd",{children:Object.entries(t.status.provenanceCounts??{}).map(([a,h])=>`${a}: ${h}`).join(" · ")||"—"})]})]}),e.jsxs("label",{className:"knowledge-graph-toggle",children:[e.jsx("input",{type:"checkbox",checked:c,onChange:a=>v(a.target.checked)})," ",r("memory.graphForce","Force rebuild")]}),e.jsx("button",{type:"button",className:"btn",disabled:t.rebuilding,onClick:()=>void t.rebuild(c),children:t.rebuilding?r("memory.graphRebuilding","Rebuilding…"):r("memory.graphRebuild","Rebuild")})]}),e.jsxs("section",{className:"knowledge-graph-filters card","aria-label":r("memory.graphFilters","Graph filters"),children:[e.jsx("div",{className:"knowledge-graph-kind-options",children:ct.map(a=>e.jsxs("label",{children:[e.jsx("input",{type:"checkbox",checked:(t.filters.kinds??[]).includes(a),onChange:()=>M(a)})," ",a]},a))}),e.jsx("input",{className:"input","aria-label":"Path prefix",placeholder:"Path prefix",value:t.filters.pathPrefix??"",onChange:a=>d({pathPrefix:a.target.value})}),e.jsx("input",{className:"input","aria-label":"Node id prefix",placeholder:"Node id prefix",value:t.filters.idPrefix??"",onChange:a=>d({idPrefix:a.target.value})}),e.jsx("input",{className:"input","aria-label":"Name regex",placeholder:"Name regex",value:t.filters.namePattern??"",onChange:a=>d({namePattern:a.target.value})}),e.jsxs("select",{className:"select","aria-label":"FNXC area",value:t.filters.fnxcArea??"",onChange:a=>d({fnxcArea:a.target.value||void 0}),children:[e.jsx("option",{value:"",children:r("knowledgeGraph.allFnxcAreas","All FNXC areas")}),t.status.fnxcAreas?.map(a=>e.jsx("option",{value:a,children:a},a))]}),e.jsxs("select",{className:"select","aria-label":"Symbol kind",value:t.filters.symbolKind??"",onChange:a=>d({symbolKind:a.target.value||void 0}),children:[e.jsx("option",{value:"",children:r("knowledgeGraph.allSymbolKinds","All symbol kinds")}),dt.map(a=>e.jsx("option",{children:a},a))]}),e.jsxs("select",{className:"select","aria-label":"Owner",value:t.filters.owner??"",onChange:a=>d({owner:a.target.value||void 0}),children:[e.jsx("option",{value:"",children:r("knowledgeGraph.allOwners","All owners")}),e.jsx("option",{value:"file",children:r("knowledgeGraph.ownerFile","file")}),e.jsx("option",{value:"derived",children:r("knowledgeGraph.ownerDerived","derived")})]}),e.jsx("select",{className:"select","aria-label":"Result limit",value:t.filters.limit??50,onChange:a=>d({limit:Number(a.target.value)}),children:[25,50,100,200].map(a=>e.jsx("option",{value:a,children:r("knowledgeGraph.limitResults","{{limit}} results",{limit:a})},a))}),e.jsx("button",{type:"button",className:"btn btn-ghost",onClick:t.clearFilters,children:r("memory.graphClearFilters","Clear filters")})]}),e.jsxs("div",{className:"knowledge-graph-layout",children:[e.jsxs("section",{className:"card knowledge-graph-results",children:[e.jsxs("h3",{children:[t.nodes?.total??0," ",r("memory.graphResults","results")]}),t.loading?e.jsx("p",{"data-testid":"knowledge-graph-searching",children:r("knowledgeGraph.searching","Searching…")}):t.nodes?.nodes.length?e.jsxs(e.Fragment,{children:[e.jsx("ul",{children:t.nodes.nodes.map(a=>e.jsx("li",{children:e.jsxs("button",{type:"button",className:"btn btn-ghost",onClick:()=>void t.selectNode(a.id),children:[e.jsxs("strong",{children:[a.kind,": ",a.name]}),e.jsxs("span",{children:[a.id," · ",a.ownerPath,":",a.source.line]})]})},a.id))}),e.jsxs("div",{className:"knowledge-graph-pagination",children:[e.jsx("button",{type:"button",className:"btn btn-ghost",disabled:!t.filters.offset,onClick:()=>d({offset:Math.max(0,(t.filters.offset??0)-(t.filters.limit??50))}),children:r("knowledgeGraph.previous","Previous")}),e.jsx("button",{type:"button",className:"btn btn-ghost",disabled:(t.filters.offset??0)+(t.filters.limit??50)>=(t.nodes?.total??0),onClick:()=>d({offset:(t.filters.offset??0)+(t.filters.limit??50)}),children:r("knowledgeGraph.next","Next")})]})]}):e.jsx("p",{"data-testid":"knowledge-graph-no-results",children:r("memory.graphNoResults","No matching nodes.")})]}),e.jsx("section",{className:"card knowledge-graph-detail",children:t.detail?e.jsxs(e.Fragment,{children:[e.jsx("h3",{children:t.detail.node.name}),e.jsx("p",{children:t.detail.node.id}),e.jsxs("p",{children:[t.detail.node.ownerPath,":",t.detail.node.source.line]}),e.jsx(Ie,{title:r("knowledgeGraph.outgoing","Outgoing"),edges:t.detail.outgoing,total:t.detail.outgoingTotal,endpoint:"to",onSelect:a=>void t.selectNode(a)}),e.jsx(Ie,{title:r("knowledgeGraph.incoming","Incoming"),edges:t.detail.incoming,total:t.detail.incomingTotal,endpoint:"from",onSelect:a=>void t.selectNode(a)})]}):e.jsx("p",{className:"knowledge-graph-muted",children:r("knowledgeGraph.selectNodeHint","Select a node to inspect its edges.")})})]}),t.detail&&e.jsxs("section",{className:"knowledge-graph-neighbors card",children:[e.jsx("h3",{children:r("knowledgeGraph.neighbors","Neighbors")}),e.jsxs("select",{className:"select","aria-label":"Neighbor direction",value:t.neighborOptions.direction,onChange:a=>t.setNeighborOptions({...t.neighborOptions,direction:a.target.value}),children:[e.jsx("option",{value:"out",children:r("knowledgeGraph.outgoing","Outgoing")}),e.jsx("option",{value:"in",children:r("knowledgeGraph.incoming","Incoming")}),e.jsx("option",{value:"both",children:r("knowledgeGraph.bothDirections","Both directions")})]}),e.jsx("select",{className:"select","aria-label":"Neighbor depth",value:t.neighborOptions.depth,onChange:a=>t.setNeighborOptions({...t.neighborOptions,depth:Number(a.target.value)}),children:[1,2,3].map(a=>e.jsx("option",{value:a,children:r("knowledgeGraph.depth","Depth {{depth}}",{depth:a})},a))}),e.jsx("div",{className:"knowledge-graph-kind-options",children:ht.map(a=>e.jsxs("label",{children:[e.jsx("input",{type:"checkbox",checked:(t.neighborOptions.edgeKinds??[]).includes(a),onChange:()=>E(a)})," ",a]},a))}),e.jsx("button",{type:"button",className:"btn btn-ghost",onClick:()=>void t.refreshNeighbors(),children:r("knowledgeGraph.refreshNeighbors","Refresh neighbors")}),t.neighborResults?.neighbors.length?e.jsx("ul",{children:t.neighborResults.neighbors.map(a=>e.jsxs("li",{children:[e.jsx("span",{children:r("knowledgeGraph.distance","distance {{distance}}",{distance:a.distance})}),e.jsx(ve,{id:a.node.id,onSelect:h=>void t.selectNode(h)})]},a.node.id))}):e.jsx("p",{className:"knowledge-graph-muted",children:r("knowledgeGraph.noNeighbors","No neighbors found.")})]}),e.jsxs("section",{className:"knowledge-graph-path card",children:[e.jsx("h3",{children:r("knowledgeGraph.shortestPath","Shortest path")}),e.jsx("input",{className:"input","aria-label":"From node id",placeholder:"From node id",value:t.pathInput.fromId,onChange:a=>t.setPathInput({...t.pathInput,fromId:a.target.value})}),e.jsx("input",{className:"input","aria-label":"To node id",placeholder:"To node id",value:t.pathInput.toId,onChange:a=>t.setPathInput({...t.pathInput,toId:a.target.value})}),e.jsx("input",{className:"input","aria-label":"Maximum hops",type:"number",min:"1",max:f.maxHops,value:t.pathInput.maxHops,onChange:a=>t.setPathInput({...t.pathInput,maxHops:Number(a.target.value)})}),k&&e.jsxs(e.Fragment,{children:[e.jsx("button",{type:"button",className:"btn btn-ghost",onClick:()=>t.setPathInput({...t.pathInput,fromId:k}),children:r("knowledgeGraph.useSelectedFrom","Use selected as from")}),e.jsx("button",{type:"button",className:"btn btn-ghost",onClick:()=>t.setPathInput({...t.pathInput,toId:k}),children:r("knowledgeGraph.useSelectedTo","Use selected as to")})]}),e.jsx("button",{type:"button",className:"btn",onClick:()=>void t.findPath(),children:r("knowledgeGraph.findPath","Find path")}),w&&e.jsxs("div",{"data-testid":"knowledge-graph-path-found",children:[e.jsx("strong",{children:r("knowledgeGraph.hops","{{count}} hops",{count:m})}),e.jsx("div",{className:"knowledge-graph-path-chain",children:w.nodes.map((a,h)=>e.jsxs("span",{children:[e.jsx(ve,{id:a.id,onSelect:F=>void t.selectNode(F)}),h<w.edges.length&&e.jsx("em",{children:w.edges[h].kind})]},a.id))})]}),t.pathResult?.outcome==="not-found"&&e.jsx("p",{"data-testid":"knowledge-graph-path-not-found",children:r("knowledgeGraph.noPath","No path exists between these nodes.")}),t.pathResult?.outcome==="limit-reached"&&e.jsxs("div",{"data-testid":"knowledge-graph-path-limit-reached",children:[e.jsx("p",{children:r("knowledgeGraph.pathLimitReached","No path found within {{maxHops}} hops; {{limit}} was reached.",{maxHops:t.pathResult.maxHops,limit:t.pathResult.limit})}),t.pathInput.maxHops<f.maxHops&&e.jsx("button",{type:"button",className:"btn btn-ghost",onClick:()=>t.setPathInput({...t.pathInput,maxHops:Math.min(f.maxHops,t.pathInput.maxHops+1)}),children:r("knowledgeGraph.raiseHopLimit","Raise hop limit")})]}),t.error&&e.jsx("p",{"data-testid":"knowledge-graph-path-error",className:"knowledge-graph-error",children:t.error})]})]})}const yt={Patterns:"pattern",Principles:"principle",Conventions:"convention",Pitfalls:"pitfall",Context:"context"},gt=72;function pt(i,s){if(i.length<=s)return i;const r=Math.max(1,s-1),t=Math.ceil(r/2),c=Math.floor(r/2);return`${i.slice(0,t)}…${i.slice(i.length-c)}`}function bt(i){const s=`${i.label} — ${i.path}`;return pt(s,gt)}function xt(i){if(!i)return[];const s=[],r=i.split(/(?=^## )/m);for(const t of r){const c=t.trim();if(!c)continue;const v=c.match(/^##\s+(.+?)(\n|$)/);if(v){const d=v[1].trim(),M=yt[d]??d.toLowerCase(),E=c.slice(v[0].length).replace(/<!--[\s\S]*?-->/g,"").trim(),k=E.split(`
2
+ `).reduce((f,w)=>{const m=w.trim();return/^[-*]\s+/.test(w)?f.push(m.replace(/^[-*]\s+/,"")):m.length>0&&f.length>0&&(f[f.length-1]=`${f[f.length-1]}
3
+ ${w.trimEnd()}`),f},[]);(k.length>0||E.length>0)&&s.push({name:d,key:M,items:k.length>0?k:E.length>0?[E]:[],expanded:!0})}}return s}function ft(i){if(!i)return null;const s=i.match(/##\s+Last\s+Updated:\s*(\d{4}-\d{2}-\d{2})/i);return s?s[1]:null}function jt(i){return i.reduce((s,r)=>s+r.items.length,0)}function Ft({projectId:i,addToast:s,onSendSelectionToTask:r}){const{t}=Ne("app"),[c,v]=n.useState("working"),[d,M]=n.useState(new Set),[E,k]=n.useState(!1),[f,w]=n.useState(null),[m,a]=n.useState({memoryEnabled:!0,memoryAutoSummarizeEnabled:!1,memoryAutoSummarizeThresholdChars:5e4,memoryAutoSummarizeSchedule:"0 3 * * *",memoryDreamsEnabled:!1,memoryDreamsSchedule:"0 4 * * *"}),[h,F]=n.useState(""),[U,G]=n.useState(!1),[N,D]=n.useState(null),{insightsContent:I,insightsLoading:R,insightsExists:se,saveInsights:B,memorySettings:p,settingsLoading:g,saveMemorySettings:H,savingMemorySettings:L,backendStatus:S,backendLoading:P,extractInsights:Y,extracting:T,auditReport:x,auditLoading:Q,refreshAudit:u,compactMemory:y,compacting:b,installQmdAction:W,installingQmd:le,testRetrieval:ae,memoryFiles:ne,memoryFilesLoading:be,selectedFilePath:$,selectedFileContent:re,selectedFileLoading:X,selectedFileDirty:q,setSelectedFileContent:ie,selectFile:oe,saveSelectedFile:me,savingSelectedFile:ce,reloadMemoryFiles:de,triggerDreamNow:he,dreamRunning:Z}=ot({projectId:i});n.useEffect(()=>{a(p)},[p]);const K=n.useMemo(()=>m.memoryEnabled!==p.memoryEnabled||m.memoryAutoSummarizeEnabled!==p.memoryAutoSummarizeEnabled||m.memoryAutoSummarizeThresholdChars!==p.memoryAutoSummarizeThresholdChars||m.memoryAutoSummarizeSchedule!==p.memoryAutoSummarizeSchedule||m.memoryDreamsEnabled!==p.memoryDreamsEnabled||m.memoryDreamsSchedule!==p.memoryDreamsSchedule,[m,p]),z=n.useMemo(()=>ne.find(l=>l.path===$),[ne,$]),xe=z?z.layer==="long-term"?t("memory.layerDescLongTerm","Curated durable decisions, conventions, constraints, and pitfalls promoted from dreams."):z.layer==="daily"?t("memory.layerDescDaily","Raw daily observations, open loops, and running context for dream processing."):t("memory.layerDescDreams","Synthesized patterns and open loops promoted from daily memory."):t("memory.editorDefaultDescription","Edits the selected memory file."),V=n.useMemo(()=>xt(I),[I]),fe=n.useMemo(()=>jt(V),[V]),o=n.useMemo(()=>ft(I),[I]),j=n.useCallback(l=>{M(C=>{const O=new Set(C);return O.has(l)?O.delete(l):O.add(l),O})},[]),A=n.useCallback(async l=>{try{await oe(l)}catch{s(t("memory.loadFileFailed","Failed to load memory file"),"error")}},[oe,s]),ue=n.useCallback(async()=>{try{await me(),s(t("memory.memorySaved","Memory saved"),"success")}catch{s(t("memory.saveMemoryFailed","Failed to save memory"),"error")}},[me,s]),je=n.useCallback(async()=>{if(!K)return;const l={};m.memoryEnabled!==p.memoryEnabled&&(l.memoryEnabled=m.memoryEnabled),m.memoryAutoSummarizeEnabled!==p.memoryAutoSummarizeEnabled&&(l.memoryAutoSummarizeEnabled=m.memoryAutoSummarizeEnabled),m.memoryAutoSummarizeThresholdChars!==p.memoryAutoSummarizeThresholdChars&&(l.memoryAutoSummarizeThresholdChars=m.memoryAutoSummarizeThresholdChars),m.memoryAutoSummarizeSchedule!==p.memoryAutoSummarizeSchedule&&(l.memoryAutoSummarizeSchedule=m.memoryAutoSummarizeSchedule),m.memoryDreamsEnabled!==p.memoryDreamsEnabled&&(l.memoryDreamsEnabled=m.memoryDreamsEnabled),m.memoryDreamsSchedule!==p.memoryDreamsSchedule&&(l.memoryDreamsSchedule=m.memoryDreamsSchedule);try{await H(l),s(t("memory.settingsSaved","Memory settings saved"),"success")}catch{s(t("memory.saveSettingsFailed","Failed to save memory settings"),"error")}},[K,m,p,H,s]),Re=n.useCallback(async()=>{try{const l=await W();s(l.qmdAvailable?t("memory.qmdInstallSuccess","qmd installed successfully"):t("memory.qmdInstallUnavailable","qmd install finished, but qmd is still unavailable"),l.qmdAvailable?"success":"info")}catch{s(t("memory.installQmdFailed","Failed to install qmd"),"error")}},[W,s]),Le=n.useCallback(async()=>{G(!0),D(null);try{const l=await ae(h);D(l),s(l.qmdAvailable?t("memory.retrievalTestComplete","Memory retrieval test complete"):t("memory.retrievalTestFallback","qmd is not installed; local fallback was used"),l.qmdAvailable?"success":"info")}catch{s(t("memory.retrievalTestFailed","Failed to test memory retrieval"),"error")}finally{G(!1)}},[h,ae,s]),ze=n.useCallback(async()=>{try{await he(),s(t("memory.dreamProcessingComplete","Dream processing completed"),"success"),await de()}catch(l){s(l instanceof Error?l.message:t("memory.dreamProcessingFailed","Failed to run dream processing"),"error")}},[he,de,s]),Pe=n.useCallback(async()=>{try{await y($),s(t("memory.fileCompacted","Memory file compacted"),"success")}catch{s(t("memory.compactFailed","Failed to compact memory"),"error")}},[y,$,s]),Se=n.useCallback(async()=>{try{const l=await Y();s(l.summary,"success")}catch(l){s(l instanceof Error?l.message:t("memory.extractInsightsFailed","Failed to extract insights"),"error")}},[Y,s]),Ge=n.useCallback(async()=>{if(f!==null)try{await B(f),k(!1),w(null),s(t("memory.insightsSaved","Insights saved"),"success")}catch{s(t("memory.saveInsightsFailed","Failed to save insights"),"error")}},[f,B,s]),qe=n.useCallback(()=>{w(I??""),k(!0)},[I]),Oe=n.useCallback(()=>{k(!1),w(null)},[]),He=!P&&S!==null,ye=S?.capabilities?.writable??!1;return e.jsxs("div",{className:"memory-view",children:[e.jsx(Ze,{icon:Je,title:t("memory.title","Memory")}),e.jsxs("div",{className:"memory-view-tabs",role:"tablist",children:[e.jsx("button",{type:"button",role:"tab","aria-selected":c==="working",className:`memory-view-tab${c==="working"?" memory-view-tab--active":""}`,onClick:()=>v("working"),"data-testid":"memory-tab-working",children:t("memory.tabWorking","Working Memory")}),e.jsx("button",{type:"button",role:"tab","aria-selected":c==="insights",className:`memory-view-tab${c==="insights"?" memory-view-tab--active":""}`,onClick:()=>v("insights"),"data-testid":"memory-tab-insights",children:t("memory.tabInsights","Insights")}),e.jsx("button",{type:"button",role:"tab","aria-selected":c==="graph",className:`memory-view-tab${c==="graph"?" memory-view-tab--active":""}`,onClick:()=>v("graph"),"data-testid":"memory-tab-graph",children:t("memory.tabGraph","Knowledge Graph")}),e.jsx("button",{type:"button",role:"tab","aria-selected":c==="engines",className:`memory-view-tab${c==="engines"?" memory-view-tab--active":""}`,onClick:()=>v("engines"),"data-testid":"memory-tab-engines",children:t("memory.tabEngines","Engines")})]}),e.jsxs("div",{className:"memory-view-content",children:[c==="graph"&&e.jsx(ut,{projectId:i,addToast:s}),c==="working"&&e.jsxs("div",{className:"memory-working-tab",children:[He&&!ye&&e.jsx("div",{className:"memory-readonly-banner",children:t("memory.readOnlyBanner","This memory backend is read-only. Changes cannot be saved.")}),be||X?e.jsxs("div",{className:"memory-empty-state",children:[e.jsx(_,{size:20,className:"animate-spin"}),e.jsx("span",{children:t("memory.loadingFile","Loading memory file…")})]}):e.jsxs(e.Fragment,{children:[e.jsxs("div",{className:"memory-editor-section",children:[e.jsxs("div",{className:"form-group",children:[e.jsx("label",{htmlFor:"memoryViewFilePath",children:t("memory.fileLabel","Memory File")}),e.jsx("select",{id:"memoryViewFilePath",className:"select",value:$,onChange:l=>{A(l.target.value)},disabled:q,children:ne.map(l=>e.jsx("option",{value:l.path,title:`${l.label} — ${l.path}`,children:bt(l)},l.path))}),e.jsx("small",{children:q?t("memory.fileSwitchDirtyHint","Save or discard the current edits before switching files."):t("memory.fileSwitchHint","Choose any project memory file to view or edit.")})]}),z&&e.jsxs("div",{className:"memory-file-summary",children:[e.jsx("span",{children:z.layer==="long-term"?t("memory.layerLongTerm","Long-term"):z.layer==="daily"?t("memory.layerDaily","Daily"):t("memory.layerDreams","Dreams")}),e.jsx("strong",{children:z.path}),e.jsx("small",{children:t("memory.fileSummary","{{size}} bytes · updated {{updatedAt}}",{size:z.size.toLocaleString(),updatedAt:new Date(z.updatedAt).toLocaleString()})})]}),e.jsxs("div",{className:"form-group memory-editor-form-group",children:[e.jsx("label",{children:z?.label||t("memory.editorLabel","Memory Editor")}),e.jsx("small",{children:xe}),e.jsx("div",{className:"memory-editor-container",children:e.jsx(Fe,{content:re,onChange:ie,readOnly:!ye,filePath:$,forceToolbarActionsVisible:!0,onSendSelectionToTask:r})})]})]}),e.jsxs("div",{className:"memory-action-bar",children:[e.jsx("span",{className:"memory-char-count",children:t("memory.charCount","{{count}} characters",{count:re.length})}),e.jsx("div",{className:"memory-flex-spacer"}),ye&&re.length>0&&e.jsx("button",{type:"button",className:"btn btn-secondary btn-sm",onClick:Pe,disabled:b||q,children:b?e.jsxs(e.Fragment,{children:[e.jsx(_,{size:14,className:"animate-spin"}),t("memory.compacting","Compacting…")]}):t("memory.compactSelectedFile","Compact Selected File")}),q&&ye&&e.jsx("button",{type:"button",className:"btn btn-primary btn-sm",onClick:ue,disabled:ce,children:ce?e.jsxs(e.Fragment,{children:[e.jsx(_,{size:14,className:"animate-spin"}),t("memory.saving","Saving…")]}):t("memory.save","Save")})]}),e.jsxs("div",{className:"memory-config-section",children:[e.jsxs("div",{className:"memory-settings-group",children:[e.jsxs("div",{className:"form-group memory-toggle-row",children:[e.jsxs("label",{htmlFor:"memoryDreamsEnabled",className:"checkbox-label",title:t("memory.dreamsEnabledTooltip","Daily notes are distilled into DREAMS.md and reusable lessons are promoted into MEMORY.md."),children:[e.jsx("input",{id:"memoryDreamsEnabled",type:"checkbox",checked:m.memoryDreamsEnabled,onChange:l=>{a(C=>({...C,memoryDreamsEnabled:l.target.checked}))},disabled:!m.memoryEnabled||g}),t("memory.dreamsEnabledLabel","Process dreams from daily memory")]}),e.jsx("small",{children:t("memory.dreamsEnabledHint","Turns daily notes into DREAMS.md and promotes reusable lessons into MEMORY.md.")})]}),m.memoryEnabled&&m.memoryDreamsEnabled&&e.jsxs(e.Fragment,{children:[e.jsxs("div",{className:"form-group",children:[e.jsx("label",{htmlFor:"memoryDreamsSchedule",children:t("memory.dreamsScheduleLabel","Dream Schedule")}),e.jsx("input",{id:"memoryDreamsSchedule",type:"text",className:"input",value:m.memoryDreamsSchedule,onChange:l=>{a(C=>({...C,memoryDreamsSchedule:l.target.value}))},placeholder:"0 4 * * *",disabled:g}),e.jsx("small",{children:t("memory.dreamsScheduleHint","Cron expression for dream processing.")})]}),e.jsxs("div",{className:"form-group",children:[e.jsx("button",{type:"button",className:"btn btn-sm",onClick:ze,disabled:Z||!m.memoryDreamsEnabled,children:Z?e.jsxs(e.Fragment,{children:[e.jsx(_,{size:14,className:"animate-spin"}),t("memory.dreaming","Dreaming…")]}):t("memory.dreamNow","Dream Now")}),e.jsx("small",{children:t("memory.dreamNowHint","Manually trigger dream processing now.")})]})]})]}),e.jsxs("div",{className:"memory-settings-group",children:[e.jsxs("div",{className:"form-group memory-toggle-row",children:[e.jsxs("label",{htmlFor:"memoryAutoSummarizeEnabled",className:"checkbox-label",children:[e.jsx("input",{id:"memoryAutoSummarizeEnabled",type:"checkbox",checked:m.memoryAutoSummarizeEnabled,onChange:l=>{a(C=>({...C,memoryAutoSummarizeEnabled:l.target.checked}))},disabled:!m.memoryEnabled||g}),t("memory.autoSummarizeLabel","Auto-summarize memory")]}),e.jsx("small",{children:t("memory.autoSummarizeHint","Automatically compacts memory when it exceeds the threshold on a schedule.")})]}),m.memoryEnabled&&m.memoryAutoSummarizeEnabled&&e.jsxs(e.Fragment,{children:[e.jsxs("div",{className:"form-group",children:[e.jsx("label",{htmlFor:"memoryAutoSummarizeThresholdChars",children:t("memory.compactionThresholdLabel","Compaction Threshold (chars)")}),e.jsx("input",{id:"memoryAutoSummarizeThresholdChars",type:"number",className:"input",value:m.memoryAutoSummarizeThresholdChars,onChange:l=>{a(C=>({...C,memoryAutoSummarizeThresholdChars:parseInt(l.target.value,10)||5e4}))},min:1e3,disabled:g}),e.jsx("small",{children:t("memory.compactionThresholdHint","Memory will be compacted when it exceeds this character count")})]}),e.jsxs("div",{className:"form-group",children:[e.jsx("label",{htmlFor:"memoryAutoSummarizeSchedule",children:t("memory.autoSummarizeScheduleLabel","Schedule (cron)")}),e.jsx("input",{id:"memoryAutoSummarizeSchedule",type:"text",className:"input",value:m.memoryAutoSummarizeSchedule,onChange:l=>{a(C=>({...C,memoryAutoSummarizeSchedule:l.target.value}))},placeholder:"0 3 * * *",disabled:g}),e.jsx("small",{children:t("memory.autoSummarizeScheduleHint","Cron expression for auto-summarize schedule (default: daily at 3 AM)")})]})]})]}),!m.memoryEnabled&&e.jsx("div",{className:"settings-empty-state memory-status-message",children:t("memory.disabledMessage","Memory is currently disabled. Enable memory tools in Settings to edit these automations.")}),K&&e.jsx("div",{className:"memory-action-bar",children:e.jsx("button",{type:"button",className:"btn btn-primary btn-sm",onClick:je,disabled:L||g,children:L?e.jsxs(e.Fragment,{children:[e.jsx(_,{size:14,className:"animate-spin"}),t("memory.saving","Saving…")]}):t("memory.saveSettings","Save Settings")})})]})]})]}),c==="insights"&&e.jsx("div",{className:"memory-insights-tab",children:R?e.jsxs("div",{className:"memory-empty-state",children:[e.jsx(_,{size:20,className:"animate-spin"}),e.jsx("span",{children:t("memory.loadingInsights","Loading insights…")})]}):E?e.jsxs("div",{className:"memory-insights-editor-layout",children:[e.jsx("div",{className:"memory-editor-container",children:e.jsx(Fe,{content:f??"",onChange:w,readOnly:!1,filePath:".fusion/memory/memory-insights.md",forceToolbarActionsVisible:!0,onSendSelectionToTask:r})}),e.jsxs("div",{className:"memory-action-bar",children:[e.jsx("button",{type:"button",className:"btn btn-secondary btn-sm",onClick:Oe,children:t("memory.cancel","Cancel")}),e.jsx("button",{type:"button",className:"btn btn-primary btn-sm",onClick:Ge,children:t("memory.saveInsights","Save Insights")})]})]}):!se||V.length===0?e.jsxs("div",{className:"memory-empty-state",children:[e.jsx("p",{children:t("memory.noInsights","No insights extracted yet.")}),e.jsx("p",{children:t("memory.noInsightsHint",'Insights are automatically extracted from working memory. Click "Extract Now" to trigger extraction manually.')}),e.jsx("button",{type:"button",className:"btn btn-primary btn-sm memory-empty-extract-button",onClick:Se,disabled:T,children:T?e.jsxs(e.Fragment,{children:[e.jsx(_,{size:14,className:"animate-spin"}),t("memory.extracting","Extracting…")]}):t("memory.extractNow","Extract Now")})]}):e.jsxs(e.Fragment,{children:[e.jsxs("div",{className:"memory-stats-row",children:[e.jsxs("div",{className:"memory-stat-card",children:[e.jsx("div",{className:"memory-stat-value",children:fe}),e.jsx("div",{className:"memory-stat-label",children:t("memory.totalInsights","Total Insights")})]}),e.jsxs("div",{className:"memory-stat-card",children:[e.jsx("div",{className:"memory-stat-value",children:V.length}),e.jsx("div",{className:"memory-stat-label",children:t("memory.categories","Categories")})]}),o&&e.jsxs("div",{className:"memory-stat-card",children:[e.jsx("div",{className:"memory-stat-value memory-stat-value--updated",children:o}),e.jsx("div",{className:"memory-stat-label",children:t("memory.lastUpdated","Last Updated")})]})]}),e.jsxs("div",{className:"memory-action-bar",children:[e.jsx("button",{type:"button",className:"btn btn-primary btn-sm",onClick:Se,disabled:T,children:T?e.jsxs(e.Fragment,{children:[e.jsx(_,{size:14,className:"animate-spin"}),t("memory.extracting","Extracting…")]}):t("memory.extractNow","Extract Now")}),e.jsx("button",{type:"button",className:"btn btn-secondary btn-sm",onClick:qe,children:t("memory.editRaw","Edit Raw")})]}),e.jsx("div",{className:"memory-categories-list",children:V.map(l=>{const C=!d.has(l.key);return e.jsxs("div",{className:"memory-category-section",children:[e.jsxs("div",{className:"memory-category-header",onClick:()=>j(l.key),role:"button",tabIndex:0,onKeyDown:O=>{(O.key==="Enter"||O.key===" ")&&(O.preventDefault(),j(l.key))},children:[e.jsx("h4",{children:l.name}),e.jsx("span",{className:"memory-category-count",children:l.items.length})]}),C&&e.jsx("div",{className:"memory-category-items",children:l.items.map((O,Te)=>e.jsx("div",{className:"memory-insight-item",children:O.replace(/^-\s+/,"").replace(/^\*\s+/,"")},Te))})]},l.key)})})]})}),c==="engines"&&e.jsx("div",{className:"memory-engines-tab",children:P||Q?e.jsxs("div",{className:"memory-empty-state",children:[e.jsx(_,{size:20,className:"animate-spin"}),e.jsx("span",{children:t("memory.loadingEngineStatus","Loading engine status…")})]}):e.jsxs(e.Fragment,{children:[e.jsxs("div",{className:"memory-engine-card memory-qmd-card",children:[e.jsx("h3",{children:t("memory.qmdIntegrationTitle","QMD Integration")}),S?.qmdAvailable===!0?e.jsxs("div",{className:"memory-engine-status",children:[e.jsx("span",{className:"memory-health-badge memory-health-badge--healthy",children:t("memory.qmdInstalled","Installed")}),e.jsx("span",{className:"memory-char-count",children:t("memory.qmdAvailableOnPath","qmd is available on PATH.")})]}):S?.qmdAvailable===!1?e.jsxs("div",{className:"settings-empty-state memory-status-message",children:[e.jsxs("span",{children:[t("memory.qmdNotInstalled","qmd is not installed. Search will use local files. Install indexed retrieval:")," ",e.jsx("code",{children:S.qmdInstallCommand||"bun install -g @tobilu/qmd"})]}),e.jsx("button",{type:"button",className:"btn btn-secondary btn-sm",onClick:Re,disabled:le,children:le?t("memory.installing","Installing…"):t("memory.installQmd","Install qmd")})]}):e.jsxs("div",{className:"memory-engine-status",children:[e.jsx("span",{className:"memory-health-badge",children:t("memory.qmdChecking","Checking")}),e.jsx("span",{className:"memory-char-count",children:t("memory.qmdCheckingAvailability","Checking qmd availability…")})]})]}),e.jsxs("div",{className:"memory-engine-card memory-retrieval-card",children:[e.jsx("h3",{children:t("memory.testMemorySearchTitle","Test Memory Search")}),e.jsxs("div",{className:"memory-retrieval-input-row",children:[e.jsx("input",{type:"text",className:"input",value:h,onChange:l=>F(l.target.value),placeholder:t("memory.searchPlaceholder","Search memory with qmd")}),e.jsx("button",{type:"button",className:"btn btn-secondary btn-sm",onClick:Le,disabled:U,children:U?t("memory.testing","Testing…"):t("memory.testRetrieval","Test Retrieval")})]}),e.jsx("small",{className:"settings-muted",children:t("memory.testSearchHint","Runs the same qmd-backed memory_search path agents use.")}),N&&e.jsxs("div",{className:"memory-test-result",children:[e.jsx("strong",{children:t("memory.testResultCount",'{{count}} result for "{{query}}"',{count:N.results.length,query:N.query,defaultValue_one:'{{count}} result for "{{query}}"',defaultValue_other:'{{count}} results for "{{query}}"'})}),e.jsx("small",{children:t("memory.testResultStatus","qmd {{qmdStatus}} · {{fallbackStatus}}",{qmdStatus:N.qmdAvailable?t("memory.qmdStatusAvailable","available"):t("memory.qmdStatusMissing","missing"),fallbackStatus:N.usedFallback?t("memory.localFallbackUsed","local fallback used"):t("memory.qmdPathUsed","qmd path used")})}),N.results.length>0?e.jsx("ul",{children:N.results.map((l,C)=>e.jsxs("li",{children:[e.jsxs("span",{children:[l.path,":",l.lineStart]}),e.jsx("p",{children:l.snippet})]},`${l.path}-${l.lineStart}-${C}`))}):e.jsx("small",{children:t("memory.noMatchingMemory","No matching memory found.")})]})]}),e.jsxs("div",{className:"memory-engine-card",children:[e.jsx("h3",{children:t("memory.currentBackendTitle","Current Backend")}),e.jsx("div",{className:"memory-engine-status",children:e.jsx("span",{className:"memory-emphasis-text",children:S?.currentBackend==="file"?t("memory.backendFile","File (.fusion/memory/, agent/<agent-name>/memory/)"):S?.currentBackend==="readonly"?t("memory.backendReadonly","Read-Only"):S?.currentBackend==="qmd"?t("memory.backendQmd","QMD (Quantized Memory Distillation)"):S?.currentBackend??"unknown"})}),e.jsxs("div",{className:"memory-capability-row",children:[S?.capabilities?.readable&&e.jsx("span",{className:"memory-capability-badge",children:t("memory.capReadable","Readable")}),S?.capabilities?.writable&&e.jsx("span",{className:"memory-capability-badge",children:t("memory.capWritable","Writable")}),S?.capabilities?.supportsAtomicWrite&&e.jsx("span",{className:"memory-capability-badge",children:t("memory.capAtomicWrites","Atomic Writes")}),S?.capabilities?.persistent&&e.jsx("span",{className:"memory-capability-badge",children:t("memory.capPersistent","Persistent")})]})]}),x&&e.jsxs("div",{className:"memory-engine-card",children:[e.jsxs("div",{className:"memory-health-header",children:[e.jsx("h3",{children:t("memory.healthStatusTitle","Health Status")}),e.jsx("span",{className:`memory-health-badge memory-health-badge--${x.health}`,children:x.health==="healthy"?t("memory.healthHealthy","Healthy"):x.health==="warning"?t("memory.healthWarning","Warning"):t("memory.healthIssues","Issues Found")})]}),e.jsxs("div",{className:"memory-health-grid",children:[e.jsxs("div",{children:[e.jsx("div",{className:"memory-health-label",children:t("memory.workingMemoryLabel","Working Memory")}),e.jsx("div",{className:"memory-emphasis-text",children:t("memory.sizeChars","{{size}} chars",{size:x.workingMemory.size})}),e.jsx("div",{className:"memory-health-detail",children:t("memory.sectionCount","{{count}} sections",{count:x.workingMemory.sectionCount})})]}),e.jsxs("div",{children:[e.jsx("div",{className:"memory-health-label",children:t("memory.insightsMemoryLabel","Insights Memory")}),e.jsx("div",{className:"memory-emphasis-text",children:t("memory.sizeChars","{{size}} chars",{size:x.insightsMemory.size})}),e.jsx("div",{className:"memory-health-detail",children:t("memory.insightCount","{{count}} insights",{count:x.insightsMemory.insightCount})})]})]}),e.jsxs("div",{className:"memory-health-section",children:[e.jsx("div",{className:"memory-health-label",children:t("memory.lastExtractionLabel","Last Extraction")}),e.jsx("div",{className:"memory-emphasis-text",children:x.extraction.success?e.jsx("span",{className:"memory-status-text memory-status-text--success",children:t("memory.extractionSuccess","Success")}):e.jsx("span",{className:"memory-status-text memory-status-text--error",children:t("memory.extractionFailed","Failed")})}),e.jsx("div",{className:"memory-health-detail",children:x.extraction.summary||t("memory.insightsExtracted","{{count}} insights extracted",{count:x.extraction.insightCount})})]}),e.jsxs("div",{className:"memory-health-section",children:[e.jsx("div",{className:"memory-health-label",children:t("memory.pruningLabel","Pruning")}),e.jsx("div",{className:"memory-emphasis-text",children:x.pruning.applied?e.jsx("span",{className:"memory-status-text memory-status-text--warning",children:t("memory.pruningApplied","Applied")}):e.jsx("span",{className:"memory-status-text memory-status-text--muted",children:t("memory.pruningNotNeeded","Not needed")})}),x.pruning.applied&&e.jsx("div",{className:"memory-health-detail",children:x.pruning.reason})]})]}),x&&x.checks.length>0&&e.jsxs("div",{className:"memory-engine-card",children:[e.jsx("h3",{children:t("memory.auditChecksTitle","Audit Checks")}),e.jsx("div",{children:x.checks.map(l=>e.jsxs("div",{className:"memory-audit-check",children:[e.jsx("span",{className:l.passed?"memory-audit-check-passed":"memory-audit-check-failed",children:l.passed?"✓":"✗"}),e.jsxs("div",{className:"memory-audit-check-content",children:[e.jsx("div",{className:"memory-emphasis-text",children:l.name}),e.jsx("div",{className:"memory-health-detail",children:l.details})]})]},l.id))})]}),e.jsx("div",{className:"memory-action-bar",children:e.jsx("button",{type:"button",className:"btn btn-secondary btn-sm",onClick:()=>u(),children:t("memory.runAudit","Run Audit")})}),e.jsxs("div",{className:"memory-settings-note",children:[e.jsx("span",{children:t("memory.settingsNote","Note: Change backend type in")}),e.jsx("button",{type:"button",className:"memory-settings-note-button",onClick:()=>{s(t("memory.settingsNoteToast","Open Settings → Memory to change backend type"),"info")},children:t("memory.settingsNoteLink","Settings → Memory")})]})]})})]})]})}export{Ft as MemoryView};
@@ -1,4 +1,4 @@
1
- import{r as l,j as e}from"./vendor-react-SZ_qB27O.js";import{c as V,b8 as Y,b9 as Z,ba as T,R as L,aK as D,aN as P,P as ee,C as se,k as ae,F as ie,aI as B,bb as ne,bc as te,bd as I,X as re}from"./index-B_z7OKl4.js";import{u as le}from"./vendor-i18n-Duky4gdQ.js";import{P as $}from"./puzzle-CC8Ur3Cy.js";import{B as A}from"./AgentPermissionPolicyEditor-CxPQffiY.js";import"./vendor-codemirror-CcrtqoCy.js";import"./vendor-reactflow-BlIeoTu4.js";import"./vendor-xterm-BNq00GSj.js";/**
1
+ import{r as l,j as e}from"./vendor-react-SZ_qB27O.js";import{c as V,ba as Y,bb as Z,bc as T,R as L,aK as D,aN as P,P as ee,C as se,k as ae,F as ie,aI as B,bd as ne,be as te,bf as I,X as re}from"./index-I32FijPT.js";import{u as le}from"./vendor-i18n-Duky4gdQ.js";import{P as $}from"./puzzle-VhTPiCit.js";import{B as A}from"./AgentPermissionPolicyEditor-YTEpMhUx.js";import"./vendor-codemirror-CcrtqoCy.js";import"./vendor-reactflow-BlIeoTu4.js";import"./vendor-xterm-BNq00GSj.js";/**
2
2
  * @license lucide-react v1.7.0 - ISC
3
3
  *
4
4
  * This source code is licensed under the ISC license.
@@ -0,0 +1 @@
1
+ import{r as d,j as e}from"./vendor-react-SZ_qB27O.js";import{ag as ze,bg as He,bh as Ve,bi as ge,bj as Qe,X as me,aU as Ke,bk as Je,aK as he,P as be,b3 as ye,F as xe,R as fe,aN as Ye,a3 as Xe,bl as Ze,bm as es,bn as ss,bo as ns,bp as is,bq as ts,br as as,bs as Q,bt as ls,bu as rs}from"./index-I32FijPT.js";import{D as os}from"./DirectoryPicker-DHUYTE-j.js";import{u as Ce}from"./vendor-i18n-Duky4gdQ.js";import"./vendor-codemirror-CcrtqoCy.js";import"./vendor-reactflow-BlIeoTu4.js";import"./vendor-xterm-BNq00GSj.js";import"./folder-open-Dntm63x4.js";const us="/api/plugins/fusion-plugin-whatsapp-chat",cs=/^\d+$/;function K(r,c){const p=c?`?projectId=${encodeURIComponent(c)}`:"";return`${us}${r}${p}`}function ps({projectId:r,settings:c}){const{t:p}=Ce("app"),[n,x]=d.useState(null),[f,F]=d.useState(null),[L,_]=d.useState(()=>String(c?.pairingPhoneNumber??"")),[A,w]=d.useState(null),[P,k]=d.useState(null),v=d.useCallback(async()=>{try{const a=await fetch(K("/status",r)),y=await a.json();if(!a.ok)throw new Error(y.error??"WhatsApp pairing is unavailable. Enable the plugin and try again.");x(y),F(null)}catch(a){F(a instanceof Error?a.message:String(a))}},[r]);d.useEffect(()=>{v();const a=window.setInterval(()=>void v(),5e3);return()=>window.clearInterval(a)},[v]);const O=async()=>{const a=L.trim();if(!a||!cs.test(a)){w("Enter an E.164 phone number using digits only, without +.");return}k("code"),w(null);try{const y=await fetch(K("/pair-code",r),{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify({phoneNumber:a,...r?{projectId:r}:{}})}),m=await y.json();if(!y.ok)throw new Error(m.error??"Could not request a pairing code.");x(j=>({status:"awaiting-code",...j,pairingCode:m.pairingCode})),await v()}catch(y){w(y instanceof Error?y.message:String(y))}finally{k(null)}},U=async()=>{k("logout"),w(null);try{const a=await fetch(K("/logout",r),{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify(r?{projectId:r}:{})});if(!a.ok){const y=await a.json();throw new Error(y.error??"Could not log out from WhatsApp.")}await v()}catch(a){w(a instanceof Error?a.message:String(a))}finally{k(null)}},B=c?.pairingMode==="code"?"code":"qr",R=n?.status??"starting";return e.jsxs("section",{className:"whatsapp-pairing-panel","aria-labelledby":"whatsapp-pairing-heading",children:[e.jsxs("div",{className:"whatsapp-pairing-heading-row",children:[e.jsxs("div",{children:[e.jsx("h5",{id:"whatsapp-pairing-heading",className:"plugin-detail-section-heading",children:p("whatsapp.pairing","WhatsApp pairing")}),e.jsx("p",{className:"whatsapp-pairing-description",children:p("whatsapp.description","Pair and monitor this project's WhatsApp connection here.")})]}),e.jsx("button",{className:"btn btn-secondary btn-sm",type:"button",onClick:()=>void v(),children:p("whatsapp.refreshStatus","Refresh status")})]}),e.jsxs("div",{className:`whatsapp-pairing-status whatsapp-pairing-status--${R}`,role:"status","data-testid":"whatsapp-pairing-status",children:[e.jsxs("strong",{children:[p("whatsapp.status","Status:")," ",R]}),n?.jid&&e.jsx("span",{children:p("whatsapp.connectedAs","Connected as {{jid}}",{jid:n.jid})}),(n?.lastError||f)&&e.jsx("span",{className:"field-error",children:n?.lastError??f})]}),R==="awaiting-qr"&&e.jsx("div",{className:"whatsapp-pairing-qr","data-testid":"whatsapp-pairing-qr",children:n?.qrDataUrl?e.jsx("img",{src:n.qrDataUrl,alt:p("whatsapp.qrCode","WhatsApp pairing QR code"),className:"whatsapp-pairing-qr-image"}):e.jsx("p",{className:"text-muted",children:p("whatsapp.waitingQr","Waiting for a fresh QR code. Keep this panel open and refresh if needed.")})}),(B==="code"||R==="awaiting-code")&&e.jsxs("div",{className:"whatsapp-pairing-code",children:[e.jsx("label",{htmlFor:"whatsapp-pairing-phone",children:p("whatsapp.phoneNumber","Phone number (E.164 digits without +)")}),e.jsxs("div",{className:"whatsapp-pairing-code-controls",children:[e.jsx("input",{id:"whatsapp-pairing-phone",className:"input",value:L,onChange:a=>_(a.target.value),inputMode:"numeric"}),e.jsx("button",{className:"btn btn-secondary",type:"button",onClick:()=>void O(),disabled:P!==null,children:P==="code"?p("whatsapp.requestingCode","Requesting code..."):p("whatsapp.requestPairingCode","Request pairing code")})]}),n?.pairingCode&&e.jsx("output",{className:"whatsapp-pairing-code-output",children:n.pairingCode})]}),R==="connected"&&e.jsx("p",{className:"whatsapp-pairing-success",children:p("whatsapp.connectedSuccess","WhatsApp is paired and ready to receive messages from allowed senders.")}),A&&e.jsx("p",{className:"field-error",children:A}),e.jsx("button",{className:"btn btn-danger",type:"button",onClick:()=>void U(),disabled:P!==null,"data-testid":"whatsapp-pairing-logout",children:P==="logout"?p("whatsapp.loggingOut","Logging out..."):p("whatsapp.logoutRepair","Logout and re-pair")}),e.jsxs("aside",{className:"whatsapp-pairing-instructions","aria-label":p("whatsapp.instructionsLabel","WhatsApp pairing instructions"),"data-testid":"whatsapp-pairing-instructions",children:[e.jsx("h6",{children:p("whatsapp.pairingConfiguration","Pairing and configuration")}),e.jsxs("ol",{children:[e.jsx("li",{children:p("whatsapp.installPlugin","Install and enable this plugin, then keep this settings panel open.")}),e.jsx("li",{children:p("whatsapp.allowedSenders","Set {{label}}; an empty list blocks all inbound messages.",{label:"Allowed WhatsApp Senders"})}),e.jsx("li",{children:p("whatsapp.choosePairingMethod","Choose {{qr}} to scan in WhatsApp Linked Devices, or {{code}} to enter a phone number and request a pairing code.",{qr:"QR",code:"code"})}),e.jsx("li",{children:p("whatsapp.waitConnected","Wait for the status above to become {{status}}.",{status:"connected"})}),e.jsx("li",{children:p("whatsapp.repairInstructions","Use Logout and re-pair to start over. If QR is still pending, wait briefly or refresh status for a new code.")})]})]})]})}const Pe="fusion-plugin-agent-browser",je={enabled:{type:"boolean",label:"Enable Agent Browser",group:"General"},installChannel:{type:"enum",label:"Install Channel",enumValues:["stable","beta","nightly"],defaultValue:"stable",group:"General"},commandTimeoutMs:{type:"number",label:"Command Timeout (ms)",defaultValue:12e4,group:"General"},headlessMode:{type:"boolean",label:"Headless Mode",defaultValue:!0,group:"Browser"},allowedDomains:{type:"array",label:"Allowed Domains",itemType:"string",group:"Browser"},promptExecutorSystem:{type:"string",label:"Executor System Prompt",multiline:!0,group:"Prompt Contributions"},promptExecutorTask:{type:"string",label:"Executor Task Prompt",multiline:!0,group:"Prompt Contributions"},promptTriage:{type:"string",label:"Triage Prompt",multiline:!0,group:"Prompt Contributions"},promptReviewer:{type:"string",label:"Reviewer Prompt",multiline:!0,group:"Prompt Contributions"},promptHeartbeat:{type:"string",label:"Heartbeat Prompt",multiline:!0,group:"Prompt Contributions"},skillExposure:{type:"enum",label:"Skill Exposure",enumValues:["none","selected","all"],defaultValue:"selected",group:"Skills"}},Ne={General:"plugins.agentBrowser.groupGeneral",Browser:"plugins.agentBrowser.groupBrowser","Prompt Contributions":"plugins.agentBrowser.groupPromptContributions",Skills:"plugins.agentBrowser.groupSkills"},Se={"Enable Agent Browser":"plugins.agentBrowser.labelEnabled","Install Channel":"plugins.agentBrowser.labelInstallChannel","Command Timeout (ms)":"plugins.agentBrowser.labelCommandTimeoutMs","Headless Mode":"plugins.agentBrowser.labelHeadlessMode","Allowed Domains":"plugins.agentBrowser.labelAllowedDomains","Executor System Prompt":"plugins.agentBrowser.labelPromptExecutorSystem","Executor Task Prompt":"plugins.agentBrowser.labelPromptExecutorTask","Triage Prompt":"plugins.agentBrowser.labelPromptTriage","Reviewer Prompt":"plugins.agentBrowser.labelPromptReviewer","Heartbeat Prompt":"plugins.agentBrowser.labelPromptHeartbeat","Skill Exposure":"plugins.agentBrowser.labelSkillExposure"},we=[{id:"fusion-plugin-hermes-runtime",name:"Hermes Runtime",description:"Runtime provider for Hermes CLI-backed execution.",category:"runtime",path:"./plugins/fusion-plugin-hermes-runtime",experimental:!0},{id:"fusion-plugin-paperclip-runtime",name:"Paperclip Runtime",description:"Runtime provider for Paperclip agent connections.",category:"runtime",path:"./plugins/fusion-plugin-paperclip-runtime"},{id:"fusion-plugin-openclaw-runtime",name:"OpenClaw Runtime",description:"Runtime provider for OpenClaw execution.",category:"runtime",path:"./plugins/fusion-plugin-openclaw-runtime",experimental:!0},{id:"fusion-plugin-droid-runtime",name:"Droid Runtime",description:"Runtime provider for Droid CLI execution.",category:"runtime",path:"./plugins/fusion-plugin-droid-runtime",experimental:!0},{id:"fusion-plugin-dependency-graph",name:"Dependency Graph",description:"Dashboard plugin for task dependency graph visualization.",category:"integration",path:"./plugins/fusion-plugin-dependency-graph"},{id:"fusion-plugin-reports",name:"Reports",description:"View report history, compare runs side-by-side, and export standalone HTML summaries.",category:"integration",path:"./plugins/fusion-plugin-reports"},{id:"fusion-plugin-whatsapp-chat",name:"WhatsApp Chat",description:"Pairs to WhatsApp Web (multi-device) with QR or pairing code, then bridges direct chats to a Fusion agent.",category:"integration",path:"./plugins/fusion-plugin-whatsapp-chat"},{id:"fusion-plugin-cli-printing-press",name:"CLI Printing Press",description:"Guided wizard for drafting external service CLI definitions.",category:"integration",path:"./plugins/fusion-plugin-cli-printing-press"},{id:"fusion-plugin-compound-engineering",name:"Compound Engineering",description:"A dedicated dashboard surface for compound-engineering artifacts and interactive ce-* sessions.",category:"integration",path:"./plugins/fusion-plugin-compound-engineering"},{id:"fusion-plugin-quality",name:"Quality",description:"Task QA tab and Quality hub: preview servers, test runs, reports, screenshots, and suggested cases.",category:"integration",path:"./plugins/fusion-plugin-quality"},{id:"fusion-plugin-linear-import",name:"Linear Import",description:"Browse Linear issues and import selected issues as Fusion triage tasks through plugin-owned settings.",category:"integration",path:"./plugins/fusion-plugin-linear-import"},{id:Pe,name:"Agent Browser",description:"Built-in integration metadata. Package install support lands in FN-3101.",category:"integration",hasSetup:!0}],T={started:"var(--color-success)",loaded:"var(--color-warning)",error:"var(--color-error)",stopped:"var(--color-muted)",installed:"var(--color-info)"};function ds(r){const c=r.settingsSchema,p=c&&Object.keys(c).length>0;return r.id!==Pe?p?c:void 0:p?{...je,...c}:je}function gs(r){const c=new Map,p=[];for(const[n,x]of Object.entries(r))if(x.group){const f=c.get(x.group)??[];f.push([n,x]),c.set(x.group,f)}else p.push([n,x]);return{grouped:c,ungrouped:p}}function ve(r,c="plugin-error-text"){return r.state!=="error"||!r.error?null:e.jsx("p",{className:c,title:r.error,children:r.error})}function ws({addToast:r,projectId:c,onPluginsChanged:p}){const{t:n}=Ce("app"),[x,f]=d.useState([]),[F,L]=d.useState(!0),[_,A]=d.useState(!1),[w,P]=d.useState(""),[k,v]=d.useState(!1),[O,U]=d.useState(!1),[B,R]=d.useState(null),[a,y]=d.useState(null),[m,j]=d.useState({}),[Re,J]=d.useState(!1),[Y,X]=d.useState(null),[Z,Ee]=d.useState([]),[Ie,ee]=d.useState(!0),[se,ne]=d.useState(null),[N,ke]=d.useState(""),[S,Be]=d.useState(""),[Ae,ie]=d.useState(null),q=d.useRef(null),[Fe,z]=d.useState({}),[Le,te]=d.useState(null),[$,ae]=d.useState(null),{confirm:qe}=ze(),b=d.useCallback(async(s=!1,i)=>{try{s||L(!0);const l=await He(c);f(i?l.some(o=>o.id===i.id)?l.map(o=>o.id===i.id?i:o):[...l,i]:l)}catch(l){r(n("plugins.loadFailed","Failed to load plugins: {{error}}",{error:l instanceof Error?l.message:String(l)}),"error")}finally{s||L(!1)}},[c,r]),E=d.useCallback(async(s=N,i=S)=>{try{ee(!0),ne(null);const l=await Ve(s,i||void 0,c);Ee(l)}catch(l){const o=l instanceof Error?l.message:String(l);ne(o)}finally{ee(!1)}},[c,S,N]);d.useEffect(()=>{b()},[b]),d.useEffect(()=>(q.current&&clearTimeout(q.current),q.current=setTimeout(()=>{E(N,S)},300),()=>{q.current&&clearTimeout(q.current)}),[E,S,N]),d.useEffect(()=>{const s=we.filter(l=>l.hasSetup&&x.some(o=>o.id===l.id));if(s.length===0)return;let i=!1;return Promise.all(s.map(async l=>{try{const o=await ge(l.id,c);if(i)return;z(g=>({...g,[l.id]:o}))}catch{if(i)return;z(o=>({...o,[l.id]:{hasSetup:!0,setupCheckDeferred:!0,deferredReason:"plugin-not-started",pluginState:"installed"}}))}})),()=>{i=!0}},[x,c]);const De=d.useRef([]);De.current=x,d.useEffect(()=>{const s=c?`?projectId=${encodeURIComponent(c)}`:"",i=l=>{try{const o=JSON.parse(l.data);if(o.scope==="project"&&(o.projectId??c)!==c)return;switch(o.transition){case"installing":case"enabled":case"disabled":case"settings-updated":E(N,S),f(g=>{const u=g.findIndex(t=>t.id===o.pluginId);if(u>=0){const t=[...g];return t[u]={...t[u],enabled:o.enabled,state:o.state,settings:o.settings,error:o.error},t}else return b(),g});break;case"state-changed":f(g=>{const u=g.findIndex(t=>t.id===o.pluginId);if(u>=0){const t=[...g];return t[u]={...t[u],state:o.state,error:o.error},t}return g});break;case"uninstalled":f(g=>g.filter(u=>u.id!==o.pluginId)),E(N,S);break;case"error":f(g=>{const u=g.findIndex(t=>t.id===o.pluginId);if(u>=0){const t=[...g];return t[u]={...t[u],state:o.state,error:o.error},t}return g});break}}catch{}};return Qe(`/api/events${s}`,{events:{"plugin:lifecycle":i},onReconnect:()=>{b(),E(N,S)}})},[c,b,E,S,N]);const le=async()=>{if(!w.trim()){r(n("plugins.installPathRequired","Please enter a plugin path"),"error");return}try{v(!0),await Q({path:w,...O?{aiScanOnLoad:!0}:{}},c),r(n("plugins.installedGlobally","Plugin installed globally"),"success"),A(!1),P(""),U(!1),await b(),p?.()}catch(s){r(n("plugins.installFailed","Failed to install plugin: {{error}}",{error:s instanceof Error?s.message:String(s)}),"error")}finally{v(!1)}},Ge=async s=>{if(!s.path){r(n("plugins.builtinNoPackage","{{name}} is built in and does not have an installable package yet",{name:s.name}),"warning");return}try{X(s.id),await Q({path:s.path},c),r(n("plugins.builtinInstalledGlobally","{{name}} installed globally",{name:s.name}),"success"),await b(),p?.()}catch(i){r(n("plugins.builtinInstallFailed","Failed to install {{name}}: {{error}}",{name:s.name,error:i instanceof Error?i.message:String(i)}),"error")}finally{X(null)}},Oe=async s=>{if(!s.path){r(n("plugins.registryNotInstallable","{{name}} is not available for one-click install yet",{name:s.name}),"warning");return}try{ie(s.id),await Q({path:s.path},c),r(n("plugins.registryInstalled","{{name}} installed and enabled",{name:s.name}),"success"),await b(),p?.(),await E(N,S)}catch(i){r(n("plugins.registryInstallFailed","Failed to install {{name}}: {{error}}",{name:s.name,error:i instanceof Error?i.message:String(i)}),"error")}finally{ie(null)}},re=async s=>{try{ae(s.id);const i=await rs(s.id,c);if(!i.success){r(n("plugins.setupInstallFailed","Failed to install {{name}} setup: {{error}}",{name:s.name,error:i.error??n("plugins.unknownError","unknown error")}),"error");return}r(n("plugins.setupInstalled","{{name}} setup installed",{name:s.name}),"success"),te(s.id);const l=await ge(s.id,c);z(o=>({...o,[s.id]:l}))}catch(i){r(n("plugins.setupInstallFailed","Failed to install {{name}} setup: {{error}}",{name:s.name,error:i instanceof Error?i.message:String(i)}),"error")}finally{ae(null),te(null)}},H=async s=>{try{const i=await ts(s.id,c);if(f(l=>l.map(o=>o.id===i.id?i:o)),i.state==="error"){r(n("plugins.enableFailed","Failed to enable {{name}}: {{error}}",{name:s.name,error:i.error??n("plugins.unknownError","unknown error")}),"error"),await b();return}r(n("plugins.enabledForProject","{{name}} enabled for this project",{name:s.name}),"success"),await b(!0,i),p?.()}catch(i){r(n("plugins.enablePluginFailed","Failed to enable plugin: {{error}}",{error:i instanceof Error?i.message:String(i)}),"error")}},V=async s=>{try{const i=await is(s.id,c);f(l=>l.map(o=>o.id===i.id?i:o)),r(n("plugins.disabledForProject","{{name}} disabled for this project",{name:s.name}),"success"),await b(!0,i),p?.()}catch(i){r(n("plugins.disablePluginFailed","Failed to disable plugin: {{error}}",{error:i instanceof Error?i.message:String(i)}),"error")}},Ue=async s=>{s.enabled?await V(s):await H(s)},oe=async s=>{try{R(s.id),await ns(s.id,c),r(n("plugins.reloaded","{{name}} reloaded",{name:s.name}),"success"),await b()}catch(i){r(n("plugins.reloadFailed","Failed to reload plugin: {{error}}",{error:i instanceof Error?i.message:String(i)}),"error")}finally{R(null)}},ue=async s=>{if(await qe({title:n("plugins.uninstallTitle","Uninstall Plugin Globally"),message:n("plugins.uninstallConfirm",'Are you sure you want to uninstall "{{name}}" globally (all projects)?',{name:s.name}),danger:!0}))try{await as(s.id,c),r(n("plugins.uninstalledGlobally","{{name}} uninstalled globally",{name:s.name}),"success"),await b(),p?.(),y(null)}catch(l){r(n("plugins.uninstallFailed","Failed to uninstall plugin: {{error}}",{error:l instanceof Error?l.message:String(l)}),"error")}},$e=async(s,i)=>{try{await Ze(s.id,{aiScanOnLoad:i},c),r(i?n("plugins.aiScanEnabled","AI scan on load enabled"):n("plugins.aiScanDisabled","AI scan on load disabled"),"success"),await b()}catch(l){r(n("plugins.updateFailed","Failed to update plugin: {{error}}",{error:l instanceof Error?l.message:String(l)}),"error")}},We=async s=>{try{await es(s.id,c),r(n("plugins.rescanned","{{name}} rescanned",{name:s.name}),"success"),await b()}catch(i){r(n("plugins.rescanFailed","Failed to rescan plugin: {{error}}",{error:i instanceof Error?i.message:String(i)}),"error")}},W=async s=>{y(s);try{J(!0);const i=await ls(s.id,c);j(i)}catch{j({})}finally{J(!1)}},Me=async()=>{if(a)try{await ss(a.id,m,c),r(n("plugins.settingsSaved","Settings saved"),"success")}catch(s){r(n("plugins.saveSettingsFailed","Failed to save settings: {{error}}",{error:s instanceof Error?s.message:String(s)}),"error")}};if(a)return e.jsxs("div",{className:"plugin-manager-detail","data-testid":"plugin-manager-detail",children:[e.jsxs("div",{className:"plugin-manager-detail-header",children:[e.jsx("button",{className:"btn-icon",onClick:()=>y(null),"aria-label":n("plugins.backToList","Back to plugin list"),children:e.jsx(me,{size:16})}),e.jsxs("div",{className:"plugin-detail-title",children:[e.jsxs("div",{className:"plugin-detail-title-copy",children:[e.jsx("h4",{className:"plugin-detail-name",children:a.name}),ve(a,"plugin-error-text plugin-error-text--detail")]}),e.jsx("span",{className:"plugin-state-badge",style:{color:T[a.state]||T.installed},children:a.state})]})]}),e.jsxs("div",{className:"plugin-detail-content",children:[e.jsxs("div",{className:"plugin-detail-card",children:[a.description&&e.jsx("p",{className:"plugin-description",children:a.description}),a.author&&e.jsxs("p",{className:"plugin-detail-meta-row",children:[e.jsx("span",{className:"text-muted",children:n("plugins.author","Author:")}),a.author]}),a.homepage&&e.jsxs("p",{className:"plugin-detail-meta-row plugin-homepage",children:[e.jsx("span",{className:"text-muted",children:n("plugins.homepage","Homepage:")}),e.jsxs("a",{href:a.homepage,target:"_blank",rel:"noopener noreferrer",children:[a.homepage,e.jsx(Ke,{size:12})]})]}),e.jsxs("p",{className:"plugin-detail-meta-row",children:[e.jsx("span",{className:"text-muted",children:n("plugins.version","Version:")}),a.version]})]}),e.jsxs("div",{className:"plugin-detail-card",children:[e.jsx("h5",{className:"plugin-detail-section-heading",children:n("plugins.securityScan","Security Scan")}),e.jsxs("div",{className:"plugin-security-row",children:[e.jsxs("label",{className:"checkbox-label",children:[e.jsx("input",{type:"checkbox",checked:!!a.aiScanOnLoad,onChange:s=>void $e(a,s.target.checked)}),n("plugins.enableAiScanBeforeLoad","Enable AI scan before load/reload")]}),e.jsxs("button",{className:"btn btn-secondary btn-sm",onClick:()=>void We(a),children:[e.jsx(Je,{size:14})," ",n("plugins.rescanAndReload","Rescan and Reload")]})]}),e.jsx("p",{className:"text-muted",children:n("plugins.aiScanHint","Turning this on only updates configuration. Use Rescan and Reload to run it now.")}),a.lastSecurityScan?e.jsxs("div",{className:"plugin-security-results",children:[e.jsxs("div",{className:"plugin-security-header",children:[e.jsx("span",{className:`plugin-state-badge plugin-security-badge plugin-security-badge--${a.lastSecurityScan.verdict}`,children:a.lastSecurityScan.verdict}),e.jsx("span",{className:"text-muted",children:a.lastSecurityScan.scannedAt})]}),e.jsx("p",{className:"plugin-security-summary",children:a.lastSecurityScan.summary}),e.jsxs("details",{children:[e.jsx("summary",{children:n("plugins.findings","Findings ({{count}})",{count:a.lastSecurityScan.findings.length})}),e.jsx("ul",{className:"plugin-security-findings",children:a.lastSecurityScan.findings.map((s,i)=>e.jsxs("li",{children:[e.jsx("strong",{children:s.severity})," ",s.category," — ",s.file,": ",s.reason]},`${s.file}-${i}`))})]})]}):e.jsx("p",{className:"text-muted",children:n("plugins.noSecurityScan","No security scan has been run yet.")})]}),e.jsxs("div",{className:"plugin-detail-card",children:[e.jsx("h5",{className:"plugin-detail-section-heading",children:n("plugins.settings","Settings")}),a.id==="fusion-plugin-whatsapp-chat"&&e.jsx(ps,{projectId:c,settings:m}),Re?e.jsx("p",{className:"text-muted",children:e.jsx(he,{label:n("plugins.loading","Loading...")})}):(()=>{const s=ds(a);return s&&Object.keys(s).length>0?e.jsxs("div",{className:"plugin-settings-form",children:[(()=>{const{grouped:i,ungrouped:l}=gs(s),o=[];l.length>0&&o.push({title:null,entries:l});for(const[g,u]of i.entries())o.push({title:g,entries:u});return o.map(g=>e.jsxs("div",{className:g.title?"plugin-settings-group":void 0,children:[g.title&&e.jsx("h6",{className:"plugin-settings-group-heading",children:Ne[g.title]?n(Ne[g.title],g.title):g.title}),g.entries.map(([u,t])=>{const I=`setting-${u}-help`,D=t.label?Se[t.label]?n(Se[t.label],t.label):t.label:u;return e.jsxs("div",{className:"form-group",children:[e.jsxs("label",{htmlFor:`setting-${u}`,children:[D,t.required&&" *"]}),t.type==="string"&&!t.multiline&&e.jsx("input",{className:"input",type:"text",id:`setting-${u}`,value:m[u]??"",onChange:h=>j({...m,[u]:h.target.value}),placeholder:t.description,"aria-describedby":t.description&&!t.required?I:void 0}),t.type==="string"&&t.multiline&&e.jsx("textarea",{className:"input",id:`setting-${u}`,rows:4,value:m[u]??"",onChange:h=>j({...m,[u]:h.target.value}),placeholder:t.description,"aria-describedby":t.description&&!t.required?I:void 0}),t.type==="password"&&e.jsx("input",{className:"input",type:"password",id:`setting-${u}`,value:m[u]??"",onChange:h=>j({...m,[u]:h.target.value}),placeholder:t.description,"aria-describedby":t.description&&!t.required?I:void 0}),t.type==="number"&&e.jsx("input",{className:"input",type:"number",id:`setting-${u}`,value:m[u]??"",onChange:h=>j({...m,[u]:Number(h.target.value)}),"aria-describedby":t.description&&!t.required?I:void 0}),t.type==="boolean"&&e.jsxs("label",{className:"checkbox-label",children:[e.jsx("input",{type:"checkbox",checked:m[u]??!1,onChange:h=>j({...m,[u]:h.target.checked})}),t.description]}),t.type==="enum"&&e.jsxs("select",{className:"select",id:`setting-${u}`,value:m[u]??"",onChange:h=>j({...m,[u]:h.target.value}),"aria-describedby":t.description&&!t.required?I:void 0,children:[e.jsx("option",{value:"",children:n("plugins.selectOption","Select...")}),t.enumValues?.map(h=>e.jsx("option",{value:h,children:h},h))]}),t.type==="array"&&e.jsxs("div",{className:"plugin-settings-array",children:[m[u]?.map((h,C)=>e.jsxs("div",{className:"plugin-settings-array-item",children:[e.jsx("input",{className:"input",type:t.itemType==="number"?"number":"text",value:h??"",onChange:M=>{const G=M.target.value,de=[...m[u]||[]];de[C]=t.itemType==="number"?Number(G):G,j({...m,[u]:de})}}),e.jsx("button",{className:"btn-icon",onClick:()=>{const G=[...m[u]||[]];G.splice(C,1),j({...m,[u]:G})},"aria-label":n("plugins.removeItem","Remove item"),children:e.jsx(me,{size:14})})]},C)),e.jsxs("button",{className:"btn btn-secondary",onClick:()=>{const h=m[u]||[],C=t.itemType==="number"?0:"";j({...m,[u]:[...h,C]})},children:[e.jsx(be,{size:14})," ",n("plugins.addItem","Add Item")]})]}),t.description&&!t.required&&!t.multiline&&e.jsx("span",{id:I,className:"form-help",children:t.description})]},u)})]},g.title??"ungrouped"))})(),e.jsx("button",{className:"btn btn-primary",onClick:Me,children:n("plugins.saveSettings","Save Settings")})]}):e.jsx("p",{className:"text-muted",children:n("plugins.noConfigurableSettings","No configurable settings.")})})()]}),e.jsxs("div",{className:"plugin-detail-actions",children:[a.state==="started"&&e.jsxs("button",{className:"btn btn-secondary",onClick:()=>oe(a),disabled:B===a.id,children:[e.jsx(ye,{size:14,className:B===a.id?"spin":""}),B===a.id?n("plugins.reloading","Reloading..."):n("plugins.reload","Reload")]}),a.enabled?e.jsx("button",{className:"btn btn-secondary",onClick:()=>V(a),children:n("plugins.disableInProject","Disable in Project")}):e.jsx("button",{className:"btn btn-primary",onClick:()=>H(a),children:n("plugins.enableInProject","Enable in Project")}),e.jsxs("button",{className:"btn btn-danger",onClick:()=>ue(a),children:[e.jsx(xe,{size:14})," ",n("plugins.uninstallGlobally","Uninstall Globally")]})]})]})]});const ce=new Map(x.map(s=>[s.id,s])),pe=x,Te=()=>e.jsxs("section",{className:"plugin-registry-section","aria-label":n("plugins.browseRegistry","Browse Registry"),children:[e.jsxs("div",{className:"plugin-registry-header",children:[e.jsxs("div",{className:"plugin-registry-heading-copy",children:[e.jsx("h4",{className:"plugin-registry-heading",children:n("plugins.browseRegistry","Browse Registry")}),e.jsx("p",{className:"plugin-registry-description",children:n("plugins.registryDescription","Discover curated runtimes and integrations that can be added to this Fusion workspace.")})]}),e.jsxs("div",{className:"plugin-registry-controls",children:[e.jsxs("label",{className:"plugin-registry-category-label",children:[e.jsx("span",{className:"sr-only",children:n("plugins.registryCategory","Registry category")}),e.jsxs("select",{className:"select plugin-registry-category-select",value:S,onChange:s=>Be(s.target.value),"aria-label":n("plugins.registryCategory","Registry category"),children:[e.jsx("option",{value:"",children:n("plugins.registryCategoryAll","All Categories")}),e.jsx("option",{value:"runtime",children:n("plugins.registryCategoryRuntime","Runtime")}),e.jsx("option",{value:"integration",children:n("plugins.registryCategoryIntegration","Integration")})]})]}),e.jsxs("label",{className:"plugin-registry-search-label",children:[e.jsx("span",{className:"sr-only",children:n("plugins.searchRegistry","Search registry")}),e.jsx("input",{className:"input plugin-registry-search-input",type:"search",value:N,onChange:s=>ke(s.target.value),placeholder:n("plugins.searchRegistryPlaceholder","Search registry plugins")})]})]})]}),Ie?e.jsxs("div",{className:"plugin-registry-state",role:"status",children:[e.jsx(fe,{size:14,className:"spin"}),n("plugins.registryLoading","Loading registry...")]}):se?e.jsxs("div",{className:"plugin-registry-state plugin-registry-state--error",role:"alert",children:[e.jsx("span",{children:n("plugins.registryLoadFailed","Failed to load registry: {{error}}",{error:se})}),e.jsx("button",{className:"btn btn-secondary btn-sm plugin-registry-retry",onClick:()=>void E(N,S),children:n("plugins.retry","Retry")})]}):Z.length===0?e.jsx("div",{className:"plugin-registry-state",children:N.trim()?n("plugins.registryEmptySearch","No registry plugins match your search."):n("plugins.registryEmpty","No registry plugins are available.")}):e.jsx("div",{className:"plugin-registry-list","aria-label":n("plugins.registryPluginResults","Registry plugin results"),children:Z.map(s=>{const i=ce.get(s.id),l=Ae===s.id;return e.jsxs("div",{className:"plugin-registry-item",children:[e.jsxs("div",{className:"plugin-registry-meta",children:[e.jsxs("div",{className:"plugin-registry-title-row",children:[e.jsx("span",{className:"plugin-registry-name",children:s.name}),e.jsxs("span",{className:"plugin-registry-version",children:["v",s.version]}),e.jsx("span",{className:"plugin-registry-badge",children:s.category}),s.installed&&e.jsxs("span",{className:"plugin-registry-status plugin-registry-status--installed",children:[n("plugins.statusInstalled","Installed"),s.installedVersion&&s.installedVersion!==s.version?` · v${s.installedVersion}`:""]})]}),e.jsx("span",{className:"plugin-registry-description-text",children:s.description}),e.jsx("span",{className:"plugin-registry-author",children:n("plugins.registryByAuthor","By {{author}}",{author:s.author})})]}),e.jsx("div",{className:"plugin-registry-actions",children:s.installed?e.jsx("button",{className:"btn btn-secondary btn-sm plugin-registry-action",onClick:()=>{i?W(i):b()},children:n("plugins.manage","Manage")}):s.canInstall?e.jsx("button",{className:"btn btn-primary btn-sm plugin-registry-action",onClick:()=>void Oe(s),disabled:l,children:l?n("plugins.installing","Installing..."):n("plugins.installFromRegistry","Install")}):e.jsx("span",{className:"plugin-registry-coming-soon",children:n("plugins.registryComingSoon","Coming Soon")})})]},s.id)})})]}),_e=()=>e.jsxs("section",{className:"plugin-builtins-section","aria-label":n("plugins.builtinPlugins","Built-in Plugins"),children:[e.jsxs("div",{className:"plugin-builtins-header",children:[e.jsx("h4",{className:"plugin-builtins-heading",children:n("plugins.builtinPlugins","Built-in Plugins")}),e.jsx("p",{className:"plugin-builtins-description",children:n("plugins.builtinPluginsCatalog","Built-in plugin catalog for runtimes and integrations.")})]}),e.jsx("div",{className:"plugin-builtins-list","aria-label":n("plugins.builtinPluginRecommendations","Built-in plugin recommendations"),children:we.map(s=>{const i=ce.get(s.id),l=!!i,o=Fe[s.id],g=!!(o&&"setupCheckDeferred"in o&&o.setupCheckDeferred),u=o&&"status"in o?o.status:void 0,t=l&&s.hasSetup&&o?.hasSetup&&!g&&i?.state==="started"&&(u==="not-installed"||u==="error"),I=l&&o?.hasSetup&&u==="installed",D=Le===s.id,h=!s.path,C=s.category==="runtime",M=i?.enabled;return e.jsxs("div",{className:"plugin-builtins-item",children:[e.jsxs("div",{className:"plugin-builtins-meta",children:[e.jsx("span",{className:"plugin-builtins-name",children:s.name}),s.experimental&&e.jsx("span",{className:"plugin-builtins-runtime-badge",children:n("plugins.experimental","Experimental")}),e.jsx("span",{className:"plugin-builtins-runtime-badge",children:s.category}),e.jsx("span",{className:`plugin-builtins-status ${l?"plugin-builtins-status--installed":"plugin-builtins-status--available"}`,children:l?n("plugins.statusInstalled","Installed"):h?n("plugins.statusBuiltIn","Built in"):n("plugins.statusNotInstalled","Not installed")}),C&&M===!1&&e.jsx("span",{className:"plugin-builtins-setup-status plugin-builtins-setup-status--warning",children:n("plugins.builtinDisabled","Disabled")}),t&&e.jsx("span",{className:"plugin-builtins-setup-status plugin-builtins-setup-status--warning",children:n("plugins.setupRequired","Setup required")}),I&&e.jsx("span",{className:"plugin-builtins-setup-status plugin-builtins-setup-status--ready",children:n("plugins.setupReady","Setup ready")}),D&&e.jsx("span",{className:"plugin-builtins-setup-status plugin-builtins-setup-status--pending",children:n("plugins.checkingSetup","Checking setup...")}),g&&e.jsx("span",{className:"plugin-builtins-setup-status plugin-builtins-setup-status--deferred",children:n("plugins.startPluginToCheckSetup","Start plugin to check setup")}),e.jsx("span",{className:"plugin-builtins-description-text",children:s.description})]}),e.jsxs("div",{className:"plugin-builtins-actions",children:[C&&i&&e.jsxs("label",{className:"toggle-switch",children:[e.jsx("input",{type:"checkbox",checked:i.enabled,onChange:()=>void Ue(i),"aria-label":i.enabled?n("plugins.disablePlugin","Disable {{name}}",{name:s.name}):n("plugins.enablePlugin","Enable {{name}}",{name:s.name})}),e.jsx("span",{className:"toggle-slider"})]}),h?l&&t?e.jsx("button",{className:"btn btn-primary btn-sm",onClick:()=>void re(s),disabled:$===s.id||D,children:$===s.id?n("plugins.settingUp","Setting up..."):n("plugins.installSetup","Install Setup")}):l&&i?e.jsx("button",{className:"btn btn-secondary btn-sm",onClick:()=>void W(i),children:n("plugins.manage","Manage")}):C?null:e.jsx("span",{className:"plugin-builtins-metadata-only",children:n("plugins.builtinMetadataOnly","Built-in metadata only")}):e.jsx("button",{className:`btn ${l&&!t?"btn-secondary":"btn-primary"} btn-sm`,onClick:()=>{if(!l){Ge(s);return}if(t){re(s);return}i&&W(i)},disabled:Y===s.id||$===s.id||D,children:l?t?$===s.id?n("plugins.settingUp","Setting up..."):n("plugins.installSetup","Install Setup"):n("plugins.manage","Manage"):Y===s.id?n("plugins.installing","Installing..."):n("plugins.installNamed","Install {{name}}",{name:s.name})})]})]},s.id)})})]});return e.jsxs("div",{className:"plugin-manager","data-testid":"plugin-manager",children:[e.jsxs("div",{className:"plugin-manager-header",children:[e.jsx("span",{className:"plugin-manager-header-title",children:n("plugins.installedPlugins","Installed Plugins")}),e.jsxs("div",{className:"plugin-manager-actions",children:[e.jsxs("button",{className:"btn btn-sm",onClick:()=>void b(),title:n("plugins.refresh","Refresh"),"aria-label":n("plugins.refreshPluginList","Refresh plugin list"),children:[e.jsx(fe,{size:14,className:F?"spin":""}),n("plugins.refresh","Refresh")]}),e.jsxs("button",{className:"btn btn-primary btn-sm",onClick:()=>A(!0),children:[e.jsx(be,{size:14})," ",n("plugins.install","Install")]})]})]}),_&&e.jsxs("div",{className:"plugin-install-form",children:[e.jsx("p",{className:"plugin-install-hint",children:n("plugins.installHint","Browse to a plugin package root (contains manifest.json) or a built dist directory.")}),e.jsx(os,{value:w,onChange:P,placeholder:n("plugins.installPathPlaceholder","Absolute path to plugin directory or dist folder"),onInputKeyDown:s=>{s.key==="Enter"&&(s.preventDefault(),le())}}),e.jsxs("label",{className:"checkbox-label",children:[e.jsx("input",{type:"checkbox",checked:O,onChange:s=>U(s.target.checked)}),n("plugins.enableAiSecurityScan","Enable AI security scan on load")]}),e.jsxs("div",{className:"plugin-install-actions",children:[e.jsx("button",{className:"btn btn-primary",onClick:le,disabled:k||!w.trim(),children:k?n("plugins.installing","Installing..."):n("plugins.installPluginGlobally","Install Plugin Globally")}),e.jsx("button",{className:"btn btn-secondary",onClick:()=>{A(!1),P("")},children:n("plugins.cancel","Cancel")})]})]}),F?e.jsx("div",{className:"settings-empty-state",children:e.jsx(he,{label:n("plugins.loadingPlugins","Loading plugins...")})}):e.jsxs(e.Fragment,{children:[pe.length===0?e.jsxs("div",{className:"settings-empty-state",children:[e.jsx(Ye,{size:32,className:"text-muted"}),e.jsx("p",{children:n("plugins.noPluginsInstalled","No plugins installed.")}),e.jsx("p",{className:"text-muted",children:n("plugins.noPluginsHint","Install a plugin to get started, or use the built-in catalog below.")})]}):e.jsx("div",{className:"plugin-list",children:pe.map(s=>e.jsxs("div",{className:"plugin-item",children:[e.jsx("div",{className:"plugin-info",children:e.jsxs("div",{className:"plugin-copy",children:[e.jsxs("div",{className:"plugin-copy-header",children:[e.jsx("span",{className:"plugin-name",children:s.name}),e.jsxs("span",{className:"plugin-version text-muted",children:["v",s.version]}),e.jsx("span",{className:"plugin-state-badge",style:{color:T[s.state]||T.installed},children:s.state})]}),ve(s)]})}),e.jsxs("div",{className:"plugin-actions",children:[s.state==="started"&&e.jsx("button",{className:"btn-icon",onClick:()=>oe(s),disabled:B===s.id,title:n("plugins.reload","Reload"),children:e.jsx(ye,{size:14,className:B===s.id?"spin":""})}),e.jsxs("label",{className:"toggle-switch",children:[e.jsx("input",{type:"checkbox",checked:s.enabled,onChange:()=>s.enabled?V(s):H(s),"aria-label":s.enabled?n("plugins.disablePlugin","Disable {{name}}",{name:s.name}):n("plugins.enablePlugin","Enable {{name}}",{name:s.name})}),e.jsx("span",{className:"toggle-slider"})]}),e.jsx("button",{className:"btn-icon",onClick:()=>W(s),title:n("plugins.settings","Settings"),children:e.jsx(Xe,{size:14})}),e.jsx("button",{className:"btn-icon",onClick:()=>ue(s),title:n("plugins.uninstallGloballyTitle","Uninstall globally"),children:e.jsx(xe,{size:14})})]})]},s.id))}),_e(),Te()]})]})}export{je as AGENT_BROWSER_SETTINGS_SCHEMA,Pe as BUILTIN_AGENT_BROWSER_PLUGIN_ID,we as BUILTIN_PLUGINS,ws as PluginManager,T as STATE_COLORS};
@@ -1,6 +1,6 @@
1
- import{r as a,j as e}from"./vendor-react-SZ_qB27O.js";import{c as te,V as ie,a_ as k,a$ as N,b0 as C,b1 as F,b2 as M,b3 as ae,b4 as X,aS as Z,as as K,a as E}from"./index-B_z7OKl4.js";import{u as ne}from"./vendor-i18n-Duky4gdQ.js";import"./vendor-codemirror-CcrtqoCy.js";import"./vendor-reactflow-BlIeoTu4.js";import"./vendor-xterm-BNq00GSj.js";/**
1
+ import{r as a,j as e}from"./vendor-react-SZ_qB27O.js";import{c as te,V as ie,b0 as k,b1 as N,b2 as C,b3 as F,b4 as M,b5 as ae,b6 as X,aU as Z,as as K,a as E}from"./index-I32FijPT.js";import{u as ne}from"./vendor-i18n-Duky4gdQ.js";import"./vendor-codemirror-CcrtqoCy.js";import"./vendor-reactflow-BlIeoTu4.js";import"./vendor-xterm-BNq00GSj.js";/**
2
2
  * @license lucide-react v1.7.0 - ISC
3
3
  *
4
4
  * This source code is licensed under the ISC license.
5
5
  * See the LICENSE file in the root directory of this source tree.
6
- */const le=[["path",{d:"M15 5.88 14 10h5.83a2 2 0 0 1 1.92 2.56l-2.33 8A2 2 0 0 1 17.5 22H4a2 2 0 0 1-2-2v-8a2 2 0 0 1 2-2h2.76a2 2 0 0 0 1.79-1.11L12 2a3.13 3.13 0 0 1 3 3.88Z",key:"emmmcr"}],["path",{d:"M7 10v12",key:"1qc93n"}]],de=te("thumbs-up",le);function ce(t){return async s=>{const n=t?`?projectId=${encodeURIComponent(t)}`:"";return(await E(`/pull-requests/${s}${n}`)).pullRequest}}function oe(t){return async()=>{const s=t?`?projectId=${encodeURIComponent(t)}`:"";return(await E(`/pull-requests${s}`)).pullRequests}}function pe(t){return async(s,n,o)=>(await E(`/pull-requests/${n}/${s==="automerge"?"automerge":s}`,{method:"POST",body:JSON.stringify({...o??{},...t?{projectId:t}:{}}),headers:{"content-type":"application/json"}})).pullRequest}function V({rollup:t}){return t==="success"?e.jsx(K,{size:14,className:"pr-icon-success"}):t==="failure"?e.jsx(X,{size:14,className:"pr-icon-failure"}):t==="pending"?e.jsx(C,{size:14,className:"pr-icon-pending"}):e.jsx("span",{className:"pr-icon-none",children:"—"})}const ue=15e3;async function J(t,s){const n=new Promise((o,l)=>setTimeout(()=>l(new Error(s)),ue));return Promise.race([t,n])}function fe(t){const{t:s}=ne("app"),{detail:n,pullRequestId:o,projectId:l,onAction:R,loadPullRequest:S,loadPullRequests:$}=t,h=n!==void 0,[L,q]=a.useState(null),[i,x]=a.useState(n??null),[v,p]=a.useState(null),[T,I]=a.useState([]),[A,U]=a.useState(null),[u,_]=a.useState(null),[Q,B]=a.useState(!1),[W,j]=a.useState(!1),[Y,G]=a.useState(!1),H=a.useMemo(()=>S??ce(l),[S,l]),O=a.useMemo(()=>$??oe(l),[$,l]),D=a.useMemo(()=>R??pe(l),[R,l]),z=o??L??void 0,ee=!h&&!o&&!L,se=!h&&!o&&!!L,f=a.useCallback(async()=>{if(h){x(n??null),p(null),j(!1);return}if(!z){try{p(null),U(null),G(!0),x(null),I(await J(O(),"Timed out loading pull requests"))}catch(r){I([]),U(r instanceof Error?r.message:s("pr.view.listError","Failed to load pull requests"))}finally{G(!1)}return}try{p(null),j(!0),x(await J(H(z),"Timed out loading pull request"))}catch(r){p(r instanceof Error?r.message:"Failed to load PR")}finally{j(!1)}},[z,n,h,H,O,s]);a.useEffect(()=>{f()},[f]),a.useEffect(()=>{if(h)return;const r=()=>void f();return window.addEventListener("fusion:store-changed",r),()=>window.removeEventListener("fusion:store-changed",r)},[h,f]);const g=a.useCallback(async(r,re)=>{if(i)try{_(r),p(null);const w=await D(r,i.id,re);x(w)}catch(w){p(w instanceof Error?w.message:`Action ${r} failed`)}finally{_(null),B(!1)}},[i,D]),d=e.jsx(ie,{icon:k,title:s("pr.view.title","Pull Requests")});if(ee)return A?e.jsxs("div",{className:"pr-view pr-view--error","data-testid":"pr-list-error",children:[d,e.jsxs("div",{className:"pr-list-state pr-list-state--error",children:[e.jsx(N,{size:16})," ",A]})]}):Y?e.jsxs("div",{className:"pr-view pr-view--loading","data-testid":"pr-list-loading",children:[d,e.jsx("div",{className:"pr-list-state",children:s("pr.view.listLoading","Loading pull requests…")})]}):T.length===0?e.jsxs("div",{className:"pr-view pr-view--empty","data-testid":"pr-list-empty",children:[d,e.jsxs("div",{className:"pr-list-state",children:[e.jsx(k,{size:16})," ",s("pr.view.listEmpty","No active pull requests to show.")]})]}):e.jsxs("div",{className:"pr-view","data-testid":"pr-list",children:[d,e.jsx("div",{className:"pr-list-title",children:s("pr.view.listTitle","Active pull requests")}),e.jsx("div",{className:"pr-list-items",children:T.map(r=>e.jsxs("button",{type:"button",className:"pr-list-item","data-testid":"pr-list-item","aria-label":s("pr.view.listItemLabel","Open pull request {{repo}} {{number}}",{repo:r.repo,number:r.prNumber!=null?`#${r.prNumber}`:r.headBranch}),onClick:()=>{p(null),j(!0),q(r.id)},children:[e.jsxs("span",{className:"pr-list-item-main",children:[e.jsx("span",{className:"pr-list-item-repo",children:r.repo}),r.prNumber!=null&&e.jsxs("span",{className:"pr-list-item-number",children:["#",r.prNumber]}),e.jsx("span",{className:"pr-list-item-branch",children:r.headBranch})]}),e.jsxs("span",{className:"pr-list-item-meta",children:[e.jsx("span",{className:`pr-identity-state pr-identity-state--${r.state}`,children:r.state}),e.jsxs("span",{className:"pr-list-item-checks",children:[e.jsx(V,{rollup:r.summary.checksRollup})," ",r.summary.checksRollup]})]})]},r.id))})]});if(v&&!i)return e.jsxs("div",{className:"pr-view pr-view--error","data-testid":"pr-view-error",children:[e.jsx(N,{size:16})," ",v]});if(!i)return W?e.jsx("div",{className:"pr-view pr-view--loading","data-testid":"pr-view-loading",children:s("pr.view.loading","Loading PR…")}):e.jsxs("div",{className:"pr-view pr-view--empty","data-testid":"pr-view-empty",children:[e.jsx(k,{size:16})," ",s("pr.view.empty","No pull request to show.")]});const{state:c,summary:m}=i,b=se?e.jsx("button",{type:"button",className:"pr-back-to-list btn","data-testid":"pr-back-to-list",onClick:()=>q(null),children:s("pr.view.backToList","Back to list")}):null;if(c==="creating")return e.jsxs("div",{className:"pr-view","data-testid":"pr-view","data-state":"creating",children:[d,b,e.jsx(y,{detail:i}),e.jsxs("div",{className:"pr-placeholder","data-testid":"pr-creating",children:[e.jsx(C,{size:16})," ",s("pr.view.creating","Creating PR…")]})]});if(c==="failed")return e.jsxs("div",{className:"pr-view","data-testid":"pr-view","data-state":"failed",children:[d,b,e.jsx(y,{detail:i}),e.jsxs("div",{className:"pr-error-reason","data-testid":"pr-failed",children:[e.jsx(N,{size:16,className:"pr-icon-failure"}),e.jsx("span",{children:i.failureReason??s("pr.view.creationFailed","PR creation failed")})]}),e.jsx("div",{className:"pr-action-bar",children:e.jsxs("button",{type:"button",className:"pr-action pr-action--retry","data-testid":"pr-retry-create",disabled:u==="retry-create",onClick:()=>void g("retry-create"),children:[e.jsx(F,{size:14})," ",s("pr.view.retryCreation","Retry PR creation")]})}),v&&e.jsx("div",{className:"pr-inline-error",children:v})]});if(i.unverified)return e.jsxs("div",{className:"pr-view","data-testid":"pr-view","data-state":"unverified",children:[d,b,e.jsx(y,{detail:i}),e.jsxs("div",{className:"pr-notice pr-notice--unverified","data-testid":"pr-unverified",children:[e.jsx(C,{size:16})," ",s("pr.view.verifyingGithub","Verifying with GitHub…")]}),e.jsx("div",{className:"pr-action-bar",children:e.jsxs("button",{type:"button",className:"pr-action","data-testid":"pr-merge",disabled:!0,title:s("pr.view.mergeDisabledUntilVerified","Merge is disabled until GitHub verifies this PR"),children:[e.jsx(M,{size:14})," ",s("pr.view.merge","Merge")]})})]});const P=m.conflicting;return e.jsxs("div",{className:"pr-view","data-testid":"pr-view","data-state":c,children:[d,b,e.jsx(y,{detail:i}),c==="responding"&&e.jsxs("div",{className:"pr-banner pr-banner--responding","data-testid":"pr-responding",children:[e.jsx(ae,{size:16})," ",s("pr.view.responsePending","Response run in progress — {{count}} threads pending",{count:m.pendingThreads})]}),e.jsxs("div",{className:"pr-action-bar","data-testid":"pr-action-bar",children:[e.jsxs("button",{type:"button",className:"pr-action pr-action--approve","data-testid":"pr-approve",disabled:c==="responding"||u==="approve",onClick:()=>void g("approve"),children:[e.jsx(de,{size:14})," ",s("pr.view.approve","Approve")]}),e.jsxs("button",{type:"button",className:"pr-action pr-action--retry","data-testid":"pr-retry",disabled:c==="responding"||u==="retry",title:c==="responding"?s("pr.view.responseAlreadyInProgress","A response run is already in progress"):void 0,onClick:()=>void g("retry"),children:[e.jsx(F,{size:14})," ",s("pr.view.requestRetry","Request retry")]}),Q?e.jsxs("button",{type:"button",className:"pr-action pr-action--merge-confirm","data-testid":"pr-merge-confirm",disabled:u==="merge",onClick:()=>void g("merge"),children:[e.jsx(M,{size:14})," ",s("pr.view.confirmMerge","Confirm merge")]}):e.jsxs("button",{type:"button",className:"pr-action pr-action--merge","data-testid":"pr-merge",disabled:P||c==="responding"||u==="merge",title:P?s("pr.view.resolveConflictsBeforeMerge","Resolve conflicts on GitHub before merging"):void 0,onClick:()=>B(!0),children:[e.jsx(M,{size:14})," ",s("pr.view.merge","Merge")]}),e.jsxs("button",{type:"button",className:"pr-action pr-action--close","data-testid":"pr-close",disabled:u==="close",onClick:()=>void g("close"),children:[e.jsx(X,{size:14})," ",s("pr.view.close","Close")]}),e.jsxs("label",{className:"pr-automerge-toggle","data-testid":"pr-automerge",children:[e.jsx("input",{type:"checkbox",checked:i.autoMerge,disabled:u==="automerge",onChange:r=>void g("automerge",{enabled:r.target.checked})}),e.jsx("span",{children:s("pr.view.autoMerge","Auto-merge")}),e.jsx("span",{className:"pr-automerge-gate","data-testid":"pr-automerge-gate",children:m.autoMergeReason})]})]}),P&&i.prUrl&&e.jsxs("a",{className:"pr-conflict-link","data-testid":"pr-conflict-link",href:i.prUrl,target:"_blank",rel:"noopener noreferrer",children:[s("pr.view.resolveConflictsOnGithub","Resolve conflicts on GitHub")," ",e.jsx(Z,{size:12})]}),e.jsxs("div",{className:"pr-summary","data-testid":"pr-summary",children:[e.jsxs("span",{className:"pr-summary-item","data-testid":"pr-summary-mergeable",children:[s("pr.view.mergeableLabel","Mergeable:")," ",m.mergeable]}),e.jsxs("span",{className:"pr-summary-item","data-testid":"pr-summary-review",children:[s("pr.view.reviewLabel","Review:")," ",m.reviewDecision??s("pr.view.none","none")]}),e.jsxs("span",{className:"pr-summary-item","data-testid":"pr-summary-checks",children:[e.jsx(V,{rollup:m.checksRollup})," ",m.checksRollup]})]}),e.jsx("div",{className:"pr-threads","data-testid":"pr-threads",children:i.threads.length===0?e.jsx("div",{className:"pr-threads-empty",children:s("pr.view.noReviewThreads","No review threads.")}):i.threads.map(r=>e.jsxs("div",{className:`pr-thread pr-thread--${r.outcome} ${r.outcome==="disagreed"?"pr-thread--agent-disagreement":""}`,"data-testid":`pr-thread-${r.outcome}`,"data-agent-disagreement":r.outcome==="disagreed"?"true":"false",children:[e.jsxs("div",{className:"pr-thread-head",children:[r.outcome==="pending"&&e.jsxs("span",{className:"pr-thread-pending",children:[e.jsx(C,{size:12})," ",s("pr.view.threadPending","pending")]}),r.outcome==="disagreed"&&e.jsxs("span",{className:"pr-thread-disagreed",children:[e.jsx(N,{size:12})," ",s("pr.view.agentDisagreed","agent disagreed")]}),r.outcome==="fixed"&&e.jsxs("span",{className:"pr-thread-fixed",children:[e.jsx(K,{size:12})," ",s("pr.view.threadFixed","fixed")]}),e.jsx("span",{className:"pr-thread-id",children:r.threadId})]}),r.fixCommitSha&&e.jsx("div",{className:"pr-thread-reply","data-testid":"pr-thread-reply",children:s("pr.view.agentReplyFix","Agent reply — fix {{sha}}",{sha:r.fixCommitSha.slice(0,8)})})]},`${r.threadId}:${r.headOid}`))}),v&&e.jsx("div",{className:"pr-inline-error",children:v})]})}function y({detail:t}){return e.jsxs("div",{className:"pr-identity","data-testid":"pr-identity",children:[e.jsx(k,{size:16}),e.jsx("span",{className:"pr-identity-repo",children:t.repo}),t.prNumber!=null?t.prUrl?e.jsxs("a",{className:"pr-identity-number",href:t.prUrl,target:"_blank",rel:"noopener noreferrer",children:["#",t.prNumber," ",e.jsx(Z,{size:12})]}):e.jsxs("span",{className:"pr-identity-number",children:["#",t.prNumber]}):null,e.jsx("span",{className:"pr-identity-branch",children:t.headBranch}),e.jsx("span",{className:`pr-identity-state pr-identity-state--${t.state}`,children:t.state})]})}export{fe as PullRequestView};
6
+ */const le=[["path",{d:"M15 5.88 14 10h5.83a2 2 0 0 1 1.92 2.56l-2.33 8A2 2 0 0 1 17.5 22H4a2 2 0 0 1-2-2v-8a2 2 0 0 1 2-2h2.76a2 2 0 0 0 1.79-1.11L12 2a3.13 3.13 0 0 1 3 3.88Z",key:"emmmcr"}],["path",{d:"M7 10v12",key:"1qc93n"}]],de=te("thumbs-up",le);function ce(t){return async s=>{const n=t?`?projectId=${encodeURIComponent(t)}`:"";return(await E(`/pull-requests/${s}${n}`)).pullRequest}}function oe(t){return async()=>{const s=t?`?projectId=${encodeURIComponent(t)}`:"";return(await E(`/pull-requests${s}`)).pullRequests}}function pe(t){return async(s,n,o)=>(await E(`/pull-requests/${n}/${s==="automerge"?"automerge":s}`,{method:"POST",body:JSON.stringify({...o??{},...t?{projectId:t}:{}}),headers:{"content-type":"application/json"}})).pullRequest}function V({rollup:t}){return t==="success"?e.jsx(K,{size:14,className:"pr-icon-success"}):t==="failure"?e.jsx(X,{size:14,className:"pr-icon-failure"}):t==="pending"?e.jsx(C,{size:14,className:"pr-icon-pending"}):e.jsx("span",{className:"pr-icon-none",children:"—"})}const ue=15e3;async function J(t,s){const n=new Promise((o,l)=>setTimeout(()=>l(new Error(s)),ue));return Promise.race([t,n])}function fe(t){const{t:s}=ne("app"),{detail:n,pullRequestId:o,projectId:l,onAction:R,loadPullRequest:q,loadPullRequests:S}=t,h=n!==void 0,[L,T]=a.useState(null),[i,x]=a.useState(n??null),[v,p]=a.useState(null),[$,I]=a.useState([]),[A,U]=a.useState(null),[u,B]=a.useState(null),[Q,G]=a.useState(!1),[W,j]=a.useState(!1),[Y,H]=a.useState(!1),_=a.useMemo(()=>q??ce(l),[q,l]),O=a.useMemo(()=>S??oe(l),[S,l]),D=a.useMemo(()=>R??pe(l),[R,l]),z=o??L??void 0,ee=!h&&!o&&!L,se=!h&&!o&&!!L,f=a.useCallback(async()=>{if(h){x(n??null),p(null),j(!1);return}if(!z){try{p(null),U(null),H(!0),x(null),I(await J(O(),"Timed out loading pull requests"))}catch(r){I([]),U(r instanceof Error?r.message:s("pr.view.listError","Failed to load pull requests"))}finally{H(!1)}return}try{p(null),j(!0),x(await J(_(z),"Timed out loading pull request"))}catch(r){p(r instanceof Error?r.message:"Failed to load PR")}finally{j(!1)}},[z,n,h,_,O,s]);a.useEffect(()=>{f()},[f]),a.useEffect(()=>{if(h)return;const r=()=>void f();return window.addEventListener("fusion:store-changed",r),()=>window.removeEventListener("fusion:store-changed",r)},[h,f]);const g=a.useCallback(async(r,re)=>{if(i)try{B(r),p(null);const w=await D(r,i.id,re);x(w)}catch(w){p(w instanceof Error?w.message:`Action ${r} failed`)}finally{B(null),G(!1)}},[i,D]),d=e.jsx(ie,{icon:k,title:s("pr.view.title","Pull Requests")});if(ee)return A?e.jsxs("div",{className:"pr-view pr-view--error","data-testid":"pr-list-error",children:[d,e.jsxs("div",{className:"pr-list-state pr-list-state--error",children:[e.jsx(N,{size:16})," ",A]})]}):Y?e.jsxs("div",{className:"pr-view pr-view--loading","data-testid":"pr-list-loading",children:[d,e.jsx("div",{className:"pr-list-state",children:s("pr.view.listLoading","Loading pull requests…")})]}):$.length===0?e.jsxs("div",{className:"pr-view pr-view--empty","data-testid":"pr-list-empty",children:[d,e.jsxs("div",{className:"pr-list-state",children:[e.jsx(k,{size:16})," ",s("pr.view.listEmpty","No active pull requests to show.")]})]}):e.jsxs("div",{className:"pr-view","data-testid":"pr-list",children:[d,e.jsx("div",{className:"pr-list-title",children:s("pr.view.listTitle","Active pull requests")}),e.jsx("div",{className:"pr-list-items",children:$.map(r=>e.jsxs("button",{type:"button",className:"pr-list-item","data-testid":"pr-list-item","aria-label":s("pr.view.listItemLabel","Open pull request {{repo}} {{number}}",{repo:r.repo,number:r.prNumber!=null?`#${r.prNumber}`:r.headBranch}),onClick:()=>{p(null),j(!0),T(r.id)},children:[e.jsxs("span",{className:"pr-list-item-main",children:[e.jsx("span",{className:"pr-list-item-repo",children:r.repo}),r.prNumber!=null&&e.jsxs("span",{className:"pr-list-item-number",children:["#",r.prNumber]}),e.jsx("span",{className:"pr-list-item-branch",children:r.headBranch})]}),e.jsxs("span",{className:"pr-list-item-meta",children:[e.jsx("span",{className:`pr-identity-state pr-identity-state--${r.state}`,children:r.state}),e.jsxs("span",{className:"pr-list-item-checks",children:[e.jsx(V,{rollup:r.summary.checksRollup})," ",r.summary.checksRollup]})]})]},r.id))})]});if(v&&!i)return e.jsxs("div",{className:"pr-view pr-view--error","data-testid":"pr-view-error",children:[e.jsx(N,{size:16})," ",v]});if(!i)return W?e.jsx("div",{className:"pr-view pr-view--loading","data-testid":"pr-view-loading",children:s("pr.view.loading","Loading PR…")}):e.jsxs("div",{className:"pr-view pr-view--empty","data-testid":"pr-view-empty",children:[e.jsx(k,{size:16})," ",s("pr.view.empty","No pull request to show.")]});const{state:c,summary:m}=i,b=se?e.jsx("button",{type:"button",className:"pr-back-to-list btn","data-testid":"pr-back-to-list",onClick:()=>T(null),children:s("pr.view.backToList","Back to list")}):null;if(c==="creating")return e.jsxs("div",{className:"pr-view","data-testid":"pr-view","data-state":"creating",children:[d,b,e.jsx(y,{detail:i}),e.jsxs("div",{className:"pr-placeholder","data-testid":"pr-creating",children:[e.jsx(C,{size:16})," ",s("pr.view.creating","Creating PR…")]})]});if(c==="failed")return e.jsxs("div",{className:"pr-view","data-testid":"pr-view","data-state":"failed",children:[d,b,e.jsx(y,{detail:i}),e.jsxs("div",{className:"pr-error-reason","data-testid":"pr-failed",children:[e.jsx(N,{size:16,className:"pr-icon-failure"}),e.jsx("span",{children:i.failureReason??s("pr.view.creationFailed","PR creation failed")})]}),e.jsx("div",{className:"pr-action-bar",children:e.jsxs("button",{type:"button",className:"pr-action pr-action--retry","data-testid":"pr-retry-create",disabled:u==="retry-create",onClick:()=>void g("retry-create"),children:[e.jsx(F,{size:14})," ",s("pr.view.retryCreation","Retry PR creation")]})}),v&&e.jsx("div",{className:"pr-inline-error",children:v})]});if(i.unverified)return e.jsxs("div",{className:"pr-view","data-testid":"pr-view","data-state":"unverified",children:[d,b,e.jsx(y,{detail:i}),e.jsxs("div",{className:"pr-notice pr-notice--unverified","data-testid":"pr-unverified",children:[e.jsx(C,{size:16})," ",s("pr.view.verifyingGithub","Verifying with GitHub…")]}),e.jsx("div",{className:"pr-action-bar",children:e.jsxs("button",{type:"button",className:"pr-action","data-testid":"pr-merge",disabled:!0,title:s("pr.view.mergeDisabledUntilVerified","Merge is disabled until GitHub verifies this PR"),children:[e.jsx(M,{size:14})," ",s("pr.view.merge","Merge")]})})]});const P=m.conflicting;return e.jsxs("div",{className:"pr-view","data-testid":"pr-view","data-state":c,children:[d,b,e.jsx(y,{detail:i}),c==="responding"&&e.jsxs("div",{className:"pr-banner pr-banner--responding","data-testid":"pr-responding",children:[e.jsx(ae,{size:16})," ",s("pr.view.responsePending","Response run in progress — {{count}} threads pending",{count:m.pendingThreads})]}),e.jsxs("div",{className:"pr-action-bar","data-testid":"pr-action-bar",children:[e.jsxs("button",{type:"button",className:"pr-action pr-action--approve","data-testid":"pr-approve",disabled:c==="responding"||u==="approve",onClick:()=>void g("approve"),children:[e.jsx(de,{size:14})," ",s("pr.view.approve","Approve")]}),e.jsxs("button",{type:"button",className:"pr-action pr-action--retry","data-testid":"pr-retry",disabled:c==="responding"||u==="retry",title:c==="responding"?s("pr.view.responseAlreadyInProgress","A response run is already in progress"):void 0,onClick:()=>void g("retry"),children:[e.jsx(F,{size:14})," ",s("pr.view.requestRetry","Request retry")]}),Q?e.jsxs("button",{type:"button",className:"pr-action pr-action--merge-confirm","data-testid":"pr-merge-confirm",disabled:u==="merge",onClick:()=>void g("merge"),children:[e.jsx(M,{size:14})," ",s("pr.view.confirmMerge","Confirm merge")]}):e.jsxs("button",{type:"button",className:"pr-action pr-action--merge","data-testid":"pr-merge",disabled:P||c==="responding"||u==="merge",title:P?s("pr.view.resolveConflictsBeforeMerge","Resolve conflicts on GitHub before merging"):void 0,onClick:()=>G(!0),children:[e.jsx(M,{size:14})," ",s("pr.view.merge","Merge")]}),e.jsxs("button",{type:"button",className:"pr-action pr-action--close","data-testid":"pr-close",disabled:u==="close",onClick:()=>void g("close"),children:[e.jsx(X,{size:14})," ",s("pr.view.close","Close")]}),e.jsxs("label",{className:"pr-automerge-toggle","data-testid":"pr-automerge",children:[e.jsx("input",{type:"checkbox",checked:i.autoMerge,disabled:u==="automerge",onChange:r=>void g("automerge",{enabled:r.target.checked})}),e.jsx("span",{children:s("pr.view.autoMerge","Auto-merge")}),e.jsx("span",{className:"pr-automerge-gate","data-testid":"pr-automerge-gate",children:m.autoMergeReason})]})]}),P&&i.prUrl&&e.jsxs("a",{className:"pr-conflict-link","data-testid":"pr-conflict-link",href:i.prUrl,target:"_blank",rel:"noopener noreferrer",children:[s("pr.view.resolveConflictsOnGithub","Resolve conflicts on GitHub")," ",e.jsx(Z,{size:12})]}),e.jsxs("div",{className:"pr-summary","data-testid":"pr-summary",children:[e.jsxs("span",{className:"pr-summary-item","data-testid":"pr-summary-mergeable",children:[s("pr.view.mergeableLabel","Mergeable:")," ",m.mergeable]}),e.jsxs("span",{className:"pr-summary-item","data-testid":"pr-summary-review",children:[s("pr.view.reviewLabel","Review:")," ",m.reviewDecision??s("pr.view.none","none")]}),e.jsxs("span",{className:"pr-summary-item","data-testid":"pr-summary-checks",children:[e.jsx(V,{rollup:m.checksRollup})," ",m.checksRollup]})]}),e.jsx("div",{className:"pr-threads","data-testid":"pr-threads",children:i.threads.length===0?e.jsx("div",{className:"pr-threads-empty",children:s("pr.view.noReviewThreads","No review threads.")}):i.threads.map(r=>e.jsxs("div",{className:`pr-thread pr-thread--${r.outcome} ${r.outcome==="disagreed"?"pr-thread--agent-disagreement":""}`,"data-testid":`pr-thread-${r.outcome}`,"data-agent-disagreement":r.outcome==="disagreed"?"true":"false",children:[e.jsxs("div",{className:"pr-thread-head",children:[r.outcome==="pending"&&e.jsxs("span",{className:"pr-thread-pending",children:[e.jsx(C,{size:12})," ",s("pr.view.threadPending","pending")]}),r.outcome==="disagreed"&&e.jsxs("span",{className:"pr-thread-disagreed",children:[e.jsx(N,{size:12})," ",s("pr.view.agentDisagreed","agent disagreed")]}),r.outcome==="fixed"&&e.jsxs("span",{className:"pr-thread-fixed",children:[e.jsx(K,{size:12})," ",s("pr.view.threadFixed","fixed")]}),e.jsx("span",{className:"pr-thread-id",children:r.threadId})]}),r.fixCommitSha&&e.jsx("div",{className:"pr-thread-reply","data-testid":"pr-thread-reply",children:s("pr.view.agentReplyFix","Agent reply — fix {{sha}}",{sha:r.fixCommitSha.slice(0,8)})})]},`${r.threadId}:${r.headOid}`))}),v&&e.jsx("div",{className:"pr-inline-error",children:v})]})}function y({detail:t}){return e.jsxs("div",{className:"pr-identity","data-testid":"pr-identity",children:[e.jsx(k,{size:16}),e.jsx("span",{className:"pr-identity-repo",children:t.repo}),t.prNumber!=null?t.prUrl?e.jsxs("a",{className:"pr-identity-number",href:t.prUrl,target:"_blank",rel:"noopener noreferrer",children:["#",t.prNumber," ",e.jsx(Z,{size:12})]}):e.jsxs("span",{className:"pr-identity-number",children:["#",t.prNumber]}):null,e.jsx("span",{className:"pr-identity-branch",children:t.headBranch}),e.jsx("span",{className:`pr-identity-state pr-identity-state--${t.state}`,children:t.state})]})}export{fe as PullRequestView};