@runfusion/fusion 0.76.0-beta.2 → 0.76.0-beta.3

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 (144) hide show
  1. package/dist/bin.js +323 -59
  2. package/dist/child-process-worker.js +274 -42
  3. package/dist/client/.vite/manifest.json +273 -273
  4. package/dist/client/assets/{AgentDetailView-gak4EWTI.js → AgentDetailView-T767kKTg.js} +1 -1
  5. package/dist/client/assets/{AgentPermissionPolicyEditor-DP1QbZL-.js → AgentPermissionPolicyEditor--u9jyUf2.js} +1 -1
  6. package/dist/client/assets/{AgentsView-DAMRTKzI.js → AgentsView-6Ifu7qDr.js} +5 -5
  7. package/dist/client/assets/{ChatView-iE-2gf5P.js → ChatView-BV3lixQi.js} +1 -1
  8. package/dist/client/assets/{CommandCenter-B6RnkLYm.js → CommandCenter-CSRYoveB.js} +1 -1
  9. package/dist/client/assets/{DevServerView-DcFL_LzK.js → DevServerView-B9So_oYx.js} +1 -1
  10. package/dist/client/assets/{DirectoryPicker-CtjqrYoO.js → DirectoryPicker-BhyDL_2m.js} +1 -1
  11. package/dist/client/assets/{DocumentsView-BkAe2S4H.js → DocumentsView-pbERA7O-.js} +1 -1
  12. package/dist/client/assets/{EvalsView-CbGA9dMn.js → EvalsView-DJQ4ltCg.js} +1 -1
  13. package/dist/client/assets/{ExperimentalAgentOnboardingModal-CMgO_S8T.js → ExperimentalAgentOnboardingModal-BwJuzkzB.js} +1 -1
  14. package/dist/client/assets/{GoalsView-_3P9J5sf.js → GoalsView-B6X5_0Ve.js} +1 -1
  15. package/dist/client/assets/InsightsView-CJgI0J7S.js +11 -0
  16. package/dist/client/assets/{InsightsView-Gn5lOBA0.css → InsightsView-DAAXuX4v.css} +1 -1
  17. package/dist/client/assets/{MemoryView-DwJas8vi.js → MemoryView-BHq1AHPu.js} +1 -1
  18. package/dist/client/assets/{PiExtensionsManager-B_LiW_e9.js → PiExtensionsManager-B8At6fO8.js} +1 -1
  19. package/dist/client/assets/{PluginManager-BkB6WLQc.js → PluginManager-k7hV7_9e.js} +1 -1
  20. package/dist/client/assets/{PullRequestView-DcH5tmYc.js → PullRequestView-B1hZFrWo.js} +1 -1
  21. package/dist/client/assets/{ReportModal-BOEbqtqG.js → ReportModal-C46V_zEa.js} +1 -1
  22. package/dist/client/assets/{ResearchView-Dp6V42pI.js → ResearchView-D8G85BYN.js} +2 -2
  23. package/dist/client/assets/{SecretsView-BCqXHB2L.js → SecretsView-CTri9LRK.js} +1 -1
  24. package/dist/client/assets/{SessionTerminal-CkdoQv4y.js → SessionTerminal-BRf6r4Vp.js} +1 -1
  25. package/dist/client/assets/SettingsModal-D0RBeZik.js +21 -0
  26. package/dist/client/assets/{SettingsModal-Dc7YG6KB.js → SettingsModal-rUQcSTJp.js} +1 -1
  27. package/dist/client/assets/{SettingsTextareaRow-WSkBoAOO.js → SettingsTextareaRow-BirlBcem.js} +1 -1
  28. package/dist/client/assets/{SetupWizardModal-VTrJAsKd.js → SetupWizardModal-xnCBM9EL.js} +2 -2
  29. package/dist/client/assets/{SkillsView-CXeXOxfF.js → SkillsView-O5U0ep50.js} +1 -1
  30. package/dist/client/assets/{WorkflowNodeEditor-DoxLGPRF.js → WorkflowNodeEditor-BX4d2qqF.js} +3 -3
  31. package/dist/client/assets/{agent-import-generation-upc0yw-M.js → agent-import-generation-DnqVkPkz.js} +1 -1
  32. package/dist/client/assets/{agentsOrgChartLayout-C3iumMrW.js → agentsOrgChartLayout-CKuzbhFf.js} +1 -1
  33. package/dist/client/assets/app-B2FwULu2.js +5 -0
  34. package/dist/client/assets/{app-BA9gw9hx.js → app-B6nJaqAl.js} +2 -2
  35. package/dist/client/assets/{app-B_lScKc1.js → app-CGXZeIRc.js} +2 -2
  36. package/dist/client/assets/{app-DG_vjDw5.js → app-CGtkeBF5.js} +3 -3
  37. package/dist/client/assets/{app-GBgoY-oh.js → app-CNzN1Plu.js} +2 -2
  38. package/dist/client/assets/{app-B0KFGP8D.js → app-DLs-f5yM.js} +3 -3
  39. package/dist/client/assets/{app-DeHIOCEP.js → app-DsvtcRUG.js} +2 -2
  40. package/dist/client/assets/{architectureDiagram-3BPJPVTR-D6jqc3fJ.js → architectureDiagram-3BPJPVTR-gi467xY0.js} +1 -1
  41. package/dist/client/assets/{blockDiagram-GPEHLZMM-DY3AKuPD.js → blockDiagram-GPEHLZMM-B_gpcYiR.js} +1 -1
  42. package/dist/client/assets/{c4Diagram-AAUBKEIU-CpD52V4g.js → c4Diagram-AAUBKEIU-DeylEYsQ.js} +1 -1
  43. package/dist/client/assets/channel-BoE8DeM4.js +1 -0
  44. package/dist/client/assets/{chunk-2J33WTMH-CPeIHyAX.js → chunk-2J33WTMH-BL2WY0HN.js} +1 -1
  45. package/dist/client/assets/{chunk-4BX2VUAB-ivAwI4xM.js → chunk-4BX2VUAB-BkLExGMe.js} +1 -1
  46. package/dist/client/assets/{chunk-55IACEB6-BtVQ5XaZ.js → chunk-55IACEB6-CSTvCF5T.js} +1 -1
  47. package/dist/client/assets/{chunk-727SXJPM-1eap1vDU.js → chunk-727SXJPM-9J8pKk4x.js} +1 -1
  48. package/dist/client/assets/{chunk-AQP2D5EJ-B2NB3BW9.js → chunk-AQP2D5EJ-DXC1vPWr.js} +1 -1
  49. package/dist/client/assets/{chunk-FMBD7UC4-Hk_smNYv.js → chunk-FMBD7UC4-CFRUb-zD.js} +1 -1
  50. package/dist/client/assets/{chunk-ND2GUHAM-BmGCAojk.js → chunk-ND2GUHAM-B87HFYS8.js} +1 -1
  51. package/dist/client/assets/{chunk-QZHKN3VN-D0aXZ8CV.js → chunk-QZHKN3VN-CTjHiGbd.js} +1 -1
  52. package/dist/client/assets/classDiagram-4FO5ZUOK-qnbLX_9_.js +1 -0
  53. package/dist/client/assets/classDiagram-v2-Q7XG4LA2-qnbLX_9_.js +1 -0
  54. package/dist/client/assets/{cose-bilkent-S5V4N54A-DAbu_gnF.js → cose-bilkent-S5V4N54A-D3Edq3L9.js} +1 -1
  55. package/dist/client/assets/{dagre-BM42HDAG-BdmLlrDJ.js → dagre-BM42HDAG-CwwbeQfN.js} +1 -1
  56. package/dist/client/assets/{dashboard-view-CULL1yhL.js → dashboard-view-BLAoW3D4.js} +1 -1
  57. package/dist/client/assets/{dashboard-view-PRCWCSLm.js → dashboard-view-DAlJxqiJ.js} +1 -1
  58. package/dist/client/assets/{dashboard-view-BoFBSXUn.js → dashboard-view-QxQwJFLz.js} +1 -1
  59. package/dist/client/assets/{dashboard-view-CxXMDfNY.js → dashboard-view-aPzfv99T.js} +1 -1
  60. package/dist/client/assets/{diagram-2AECGRRQ-PpqLbVUA.js → diagram-2AECGRRQ-koJWWXE4.js} +1 -1
  61. package/dist/client/assets/{diagram-5GNKFQAL-9rkGmTwh.js → diagram-5GNKFQAL-Yob5cOKT.js} +1 -1
  62. package/dist/client/assets/{diagram-KO2AKTUF-BT-efOMo.js → diagram-KO2AKTUF-DelvFSkK.js} +1 -1
  63. package/dist/client/assets/{diagram-LMA3HP47-w79OWFxg.js → diagram-LMA3HP47-CMput2h2.js} +1 -1
  64. package/dist/client/assets/{diagram-OG6HWLK6-Bye9I5IO.js → diagram-OG6HWLK6-04VXDl79.js} +1 -1
  65. package/dist/client/assets/{erDiagram-TEJ5UH35-aodREgDf.js → erDiagram-TEJ5UH35-C9iP8Uyp.js} +1 -1
  66. package/dist/client/assets/{flowDiagram-I6XJVG4X-D0DKItY3.js → flowDiagram-I6XJVG4X-DENQvu_t.js} +1 -1
  67. package/dist/client/assets/{folder-open-CqvaMJvx.js → folder-open-D-554oji.js} +1 -1
  68. package/dist/client/assets/{ganttDiagram-6RSMTGT7-CZVApkvw.js → ganttDiagram-6RSMTGT7-BqOttZAT.js} +1 -1
  69. package/dist/client/assets/{gitGraphDiagram-PVQCEYII-D_ynwJ4p.js → gitGraphDiagram-PVQCEYII-CDcydi-5.js} +1 -1
  70. package/dist/client/assets/{index-BzAldNrK.css → index-CXTd3LAB.css} +1 -1
  71. package/dist/client/assets/{index-DWRJyaa3.js → index-CtYRoouR.js} +264 -264
  72. package/dist/client/assets/{infoDiagram-5YYISTIA-pJG6zxjk.js → infoDiagram-5YYISTIA-B5LQQnxt.js} +1 -1
  73. package/dist/client/assets/{ishikawaDiagram-YF4QCWOH-nFZ5laUo.js → ishikawaDiagram-YF4QCWOH-DpFEt7D2.js} +1 -1
  74. package/dist/client/assets/{journeyDiagram-JHISSGLW-CWpCaAIe.js → journeyDiagram-JHISSGLW-MELtgu22.js} +1 -1
  75. package/dist/client/assets/{kanban-definition-UN3LZRKU-ATkPspKa.js → kanban-definition-UN3LZRKU-h33PLATd.js} +1 -1
  76. package/dist/client/assets/{mermaid.core-CDXPNs7a.js → mermaid.core-Dk2mUPOq.js} +4 -4
  77. package/dist/client/assets/{mindmap-definition-RKZ34NQL-BkqS9tpe.js → mindmap-definition-RKZ34NQL-B_T4O2-B.js} +1 -1
  78. package/dist/client/assets/{pieDiagram-4H26LBE5-DEUyVLs-.js → pieDiagram-4H26LBE5-B1YIFkRl.js} +1 -1
  79. package/dist/client/assets/{puzzle-DQ0y1-XK.js → puzzle-hvecxlpJ.js} +1 -1
  80. package/dist/client/assets/{quadrantDiagram-W4KKPZXB-ESBJNK5c.js → quadrantDiagram-W4KKPZXB-BoGQR_hO.js} +1 -1
  81. package/dist/client/assets/{requirementDiagram-4Y6WPE33-CqPs7zcv.js → requirementDiagram-4Y6WPE33-BSDmUBIx.js} +1 -1
  82. package/dist/client/assets/{sankeyDiagram-5OEKKPKP-CkFN0m14.js → sankeyDiagram-5OEKKPKP-Dz_GqOa5.js} +1 -1
  83. package/dist/client/assets/{sequenceDiagram-3UESZ5HK-Dx2nDuMO.js → sequenceDiagram-3UESZ5HK-B6twjYUH.js} +1 -1
  84. package/dist/client/assets/{shield-alert-BS05s4RM.js → shield-alert-BX4WRJOv.js} +1 -1
  85. package/dist/client/assets/{standing-instructions-template-xprxYNHm.js → standing-instructions-template-BJY317CC.js} +1 -1
  86. package/dist/client/assets/{stateDiagram-AJRCARHV-EUPmRFGd.js → stateDiagram-AJRCARHV-DuwqWLx-.js} +1 -1
  87. package/dist/client/assets/{stateDiagram-v2-BHNVJYJU-DcQ2mhi5.js → stateDiagram-v2-BHNVJYJU-Bu8Sk187.js} +1 -1
  88. package/dist/client/assets/{timeline-definition-PNZ67QCA-D4YO_3V-.js → timeline-definition-PNZ67QCA-BS6VnqSI.js} +1 -1
  89. package/dist/client/assets/{upload-BjyBtxo7.js → upload-CaDoyaMW.js} +1 -1
  90. package/dist/client/assets/{users-D5ogZ7WQ.js → users-C5uCLwVM.js} +1 -1
  91. package/dist/client/assets/{vennDiagram-CIIHVFJN-BT5_XuQL.js → vennDiagram-CIIHVFJN-CUbzqT5Y.js} +1 -1
  92. package/dist/client/assets/{wardley-L42UT6IY-X_ZMW457.js → wardley-L42UT6IY-Mv-NotFS.js} +1 -1
  93. package/dist/client/assets/{wardleyDiagram-YWT4CUSO-GK9nONHU.js → wardleyDiagram-YWT4CUSO-DuYpvLZX.js} +1 -1
  94. package/dist/client/assets/{xychartDiagram-2RQKCTM6-Dw3zXHAq.js → xychartDiagram-2RQKCTM6-24_7QXdw.js} +1 -1
  95. package/dist/client/index.html +2 -2
  96. package/dist/client/version.json +1 -1
  97. package/dist/droid-cli/package.json +1 -1
  98. package/dist/extension.js +285 -47
  99. package/dist/pi-claude-cli/package.json +1 -1
  100. package/dist/plugin-sdk/index.d.ts +23 -0
  101. package/dist/plugin-sdk/index.js +2 -0
  102. package/dist/plugins/fusion-plugin-acp-runtime/bundled.js +2 -0
  103. package/dist/plugins/fusion-plugin-acp-runtime/package.json +1 -1
  104. package/dist/plugins/fusion-plugin-claude-runtime/bundled.js +2 -0
  105. package/dist/plugins/fusion-plugin-claude-runtime/package.json +1 -1
  106. package/dist/plugins/fusion-plugin-cli-printing-press/bundled.js +2 -0
  107. package/dist/plugins/fusion-plugin-cli-printing-press/package.json +1 -1
  108. package/dist/plugins/fusion-plugin-compound-engineering/bundled.js +2 -0
  109. package/dist/plugins/fusion-plugin-compound-engineering/package.json +1 -1
  110. package/dist/plugins/fusion-plugin-cursor-runtime/bundled.js +2 -0
  111. package/dist/plugins/fusion-plugin-cursor-runtime/package.json +1 -1
  112. package/dist/plugins/fusion-plugin-dependency-graph/bundled.js +2 -0
  113. package/dist/plugins/fusion-plugin-dependency-graph/package.json +1 -1
  114. package/dist/plugins/fusion-plugin-droid-runtime/bundled.js +2 -0
  115. package/dist/plugins/fusion-plugin-droid-runtime/package.json +1 -1
  116. package/dist/plugins/fusion-plugin-grok-runtime/bundled.js +2 -0
  117. package/dist/plugins/fusion-plugin-grok-runtime/package.json +1 -1
  118. package/dist/plugins/fusion-plugin-hermes-runtime/bundled.js +2 -0
  119. package/dist/plugins/fusion-plugin-hermes-runtime/package.json +1 -1
  120. package/dist/plugins/fusion-plugin-linear-import/bundled.js +2 -0
  121. package/dist/plugins/fusion-plugin-linear-import/package.json +1 -1
  122. package/dist/plugins/fusion-plugin-omp-runtime/bundled.js +2 -0
  123. package/dist/plugins/fusion-plugin-omp-runtime/package.json +1 -1
  124. package/dist/plugins/fusion-plugin-openclaw-runtime/bundled.js +2 -0
  125. package/dist/plugins/fusion-plugin-openclaw-runtime/package.json +1 -1
  126. package/dist/plugins/fusion-plugin-paperclip-runtime/bundled.js +2 -0
  127. package/dist/plugins/fusion-plugin-paperclip-runtime/package.json +1 -1
  128. package/dist/plugins/fusion-plugin-quality/bundled.js +2 -0
  129. package/dist/plugins/fusion-plugin-quality/package.json +1 -1
  130. package/dist/plugins/fusion-plugin-reports/bundled.js +2 -0
  131. package/dist/plugins/fusion-plugin-reports/package.json +1 -1
  132. package/dist/plugins/fusion-plugin-roadmap/bundled.js +2 -0
  133. package/dist/plugins/fusion-plugin-roadmap/package.json +1 -1
  134. package/dist/plugins/fusion-plugin-todos/bundled.js +2 -0
  135. package/dist/plugins/fusion-plugin-todos/package.json +1 -1
  136. package/dist/plugins/fusion-plugin-whatsapp-chat/bundled.js +2 -0
  137. package/dist/plugins/fusion-plugin-whatsapp-chat/package.json +1 -1
  138. package/package.json +1 -1
  139. package/dist/client/assets/InsightsView-DOhO7xH5.js +0 -11
  140. package/dist/client/assets/SettingsModal-D4Fn4GlS.js +0 -21
  141. package/dist/client/assets/app-DBCGrz-f.js +0 -5
  142. package/dist/client/assets/channel-CaxOu15c.js +0 -1
  143. package/dist/client/assets/classDiagram-4FO5ZUOK-DXIkGbsl.js +0 -1
  144. package/dist/client/assets/classDiagram-v2-Q7XG4LA2-DXIkGbsl.js +0 -1
@@ -1 +1 @@
1
- import{r as d,j as e}from"./vendor-react-SZ_qB27O.js";import{ab as _e,be as ze,bf as He,bg as ge,bh as Ve,X as me,aR as Qe,bi as Je,aJ as he,P as be,b1 as ye,x as xe,R as fe,aM as Ke,_ as Ye,bj as Xe,bk as Ze,bl as es,bm as ss,bn as ns,bo as is,bp as ts,bq as Q,br as as,bs as ls}from"./index-DWRJyaa3.js";import{D as rs}from"./DirectoryPicker-CtjqrYoO.js";import{u as os}from"./vendor-i18n-Duky4gdQ.js";import"./vendor-codemirror-CcrtqoCy.js";import"./vendor-reactflow-BlIeoTu4.js";import"./vendor-xterm-BNq00GSj.js";import"./folder-open-CqvaMJvx.js";const us="/api/plugins/fusion-plugin-whatsapp-chat",cs=/^\d+$/;function J(l,c){const g=c?`?projectId=${encodeURIComponent(c)}`:"";return`${us}${l}${g}`}function ds({projectId:l,settings:c}){const[g,n]=d.useState(null),[x,f]=d.useState(null),[A,q]=d.useState(()=>String(c?.pairingPhoneNumber??"")),[G,w]=d.useState(null),[C,E]=d.useState(null),P=d.useCallback(async()=>{try{const m=await fetch(J("/status",l)),o=await m.json();if(!m.ok)throw new Error(o.error??"WhatsApp pairing is unavailable. Enable the plugin and try again.");n(o),f(null)}catch(m){f(m instanceof Error?m.message:String(m))}},[l]);d.useEffect(()=>{P();const m=window.setInterval(()=>void P(),5e3);return()=>window.clearInterval(m)},[P]);const O=async()=>{const m=A.trim();if(!m||!cs.test(m)){w("Enter an E.164 phone number using digits only, without +.");return}E("code"),w(null);try{const o=await fetch(J("/pair-code",l),{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify({phoneNumber:m,...l?{projectId:l}:{}})}),B=await o.json();if(!o.ok)throw new Error(B.error??"Could not request a pairing code.");n(h=>({status:"awaiting-code",...h,pairingCode:B.pairingCode})),await P()}catch(o){w(o instanceof Error?o.message:String(o))}finally{E(null)}},U=async()=>{E("logout"),w(null);try{const m=await fetch(J("/logout",l),{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify(l?{projectId:l}:{})});if(!m.ok){const o=await m.json();throw new Error(o.error??"Could not log out from WhatsApp.")}await P()}catch(m){w(m instanceof Error?m.message:String(m))}finally{E(null)}},$=c?.pairingMode==="code"?"code":"qr",N=g?.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:"WhatsApp pairing"}),e.jsx("p",{className:"whatsapp-pairing-description",children:"Pair and monitor this project's WhatsApp connection here."})]}),e.jsx("button",{className:"btn btn-secondary btn-sm",type:"button",onClick:()=>void P(),children:"Refresh status"})]}),e.jsxs("div",{className:`whatsapp-pairing-status whatsapp-pairing-status--${N}`,role:"status","data-testid":"whatsapp-pairing-status",children:[e.jsxs("strong",{children:["Status: ",N]}),g?.jid&&e.jsxs("span",{children:["Connected as ",g.jid]}),(g?.lastError||x)&&e.jsx("span",{className:"field-error",children:g?.lastError??x})]}),N==="awaiting-qr"&&e.jsx("div",{className:"whatsapp-pairing-qr","data-testid":"whatsapp-pairing-qr",children:g?.qrDataUrl?e.jsx("img",{src:g.qrDataUrl,alt:"WhatsApp pairing QR code",className:"whatsapp-pairing-qr-image"}):e.jsx("p",{className:"text-muted",children:"Waiting for a fresh QR code. Keep this panel open and refresh if needed."})}),($==="code"||N==="awaiting-code")&&e.jsxs("div",{className:"whatsapp-pairing-code",children:[e.jsx("label",{htmlFor:"whatsapp-pairing-phone",children:"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:A,onChange:m=>q(m.target.value),inputMode:"numeric"}),e.jsx("button",{className:"btn btn-secondary",type:"button",onClick:()=>void O(),disabled:C!==null,children:C==="code"?"Requesting code...":"Request pairing code"})]}),g?.pairingCode&&e.jsx("output",{className:"whatsapp-pairing-code-output",children:g.pairingCode})]}),N==="connected"&&e.jsx("p",{className:"whatsapp-pairing-success",children:"WhatsApp is paired and ready to receive messages from allowed senders."}),G&&e.jsx("p",{className:"field-error",children:G}),e.jsx("button",{className:"btn btn-danger",type:"button",onClick:()=>void U(),disabled:C!==null,"data-testid":"whatsapp-pairing-logout",children:C==="logout"?"Logging out...":"Logout and re-pair"}),e.jsxs("aside",{className:"whatsapp-pairing-instructions","aria-label":"WhatsApp pairing instructions","data-testid":"whatsapp-pairing-instructions",children:[e.jsx("h6",{children:"Pairing and configuration"}),e.jsxs("ol",{children:[e.jsx("li",{children:"Install and enable this plugin, then keep this settings panel open."}),e.jsxs("li",{children:["Set ",e.jsx("strong",{children:"Allowed WhatsApp Senders"}),"; an empty list blocks all inbound messages."]}),e.jsxs("li",{children:["Choose ",e.jsx("strong",{children:"QR"})," to scan in WhatsApp Linked Devices, or ",e.jsx("strong",{children:"code"})," to enter a phone number and request a pairing code."]}),e.jsxs("li",{children:["Wait for the status above to become ",e.jsx("strong",{children:"connected"}),"."]}),e.jsx("li",{children:"Use Logout and re-pair to start over. If QR is still pending, wait briefly or refresh status for a new code."})]})]})]})}const Ce="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"},ve=[{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:Ce,name:"Agent Browser",description:"Built-in integration metadata. Package install support lands in FN-3101.",category:"integration",hasSetup:!0}],_={started:"var(--color-success)",loaded:"var(--color-warning)",error:"var(--color-error)",stopped:"var(--color-muted)",installed:"var(--color-info)"};function ps(l){const c=l.settingsSchema,g=c&&Object.keys(c).length>0;return l.id!==Ce?g?c:void 0:g?{...je,...c}:je}function gs(l){const c=new Map,g=[];for(const[n,x]of Object.entries(l))if(x.group){const f=c.get(x.group)??[];f.push([n,x]),c.set(x.group,f)}else g.push([n,x]);return{grouped:c,ungrouped:g}}function we(l,c="plugin-error-text"){return l.state!=="error"||!l.error?null:e.jsx("p",{className:c,title:l.error,children:l.error})}function vs({addToast:l,projectId:c,onPluginsChanged:g}){const{t:n}=os("app"),[x,f]=d.useState([]),[A,q]=d.useState(!0),[G,w]=d.useState(!1),[C,E]=d.useState(""),[P,O]=d.useState(!1),[U,$]=d.useState(!1),[N,m]=d.useState(null),[o,B]=d.useState(null),[h,S]=d.useState({}),[Pe,K]=d.useState(!1),[Y,X]=d.useState(null),[Z,Re]=d.useState([]),[Ee,ee]=d.useState(!0),[se,ne]=d.useState(null),[j,Ie]=d.useState(""),[v,ke]=d.useState(""),[Be,ie]=d.useState(null),F=d.useRef(null),[Ae,z]=d.useState({}),[Fe,te]=d.useState(null),[W,ae]=d.useState(null),{confirm:Le}=_e(),y=d.useCallback(async(s=!1,i)=>{try{s||q(!0);const a=await ze(c);f(i?a.some(r=>r.id===i.id)?a.map(r=>r.id===i.id?i:r):[...a,i]:a)}catch(a){l(n("plugins.loadFailed","Failed to load plugins: {{error}}",{error:a instanceof Error?a.message:String(a)}),"error")}finally{s||q(!1)}},[c,l]),I=d.useCallback(async(s=j,i=v)=>{try{ee(!0),ne(null);const a=await He(s,i||void 0,c);Re(a)}catch(a){const r=a instanceof Error?a.message:String(a);ne(r)}finally{ee(!1)}},[c,v,j]);d.useEffect(()=>{y()},[y]),d.useEffect(()=>(F.current&&clearTimeout(F.current),F.current=setTimeout(()=>{I(j,v)},300),()=>{F.current&&clearTimeout(F.current)}),[I,v,j]),d.useEffect(()=>{const s=ve.filter(a=>a.hasSetup&&x.some(r=>r.id===a.id));if(s.length===0)return;let i=!1;return Promise.all(s.map(async a=>{try{const r=await ge(a.id,c);if(i)return;z(p=>({...p,[a.id]:r}))}catch{if(i)return;z(r=>({...r,[a.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=a=>{try{const r=JSON.parse(a.data);if(r.scope==="project"&&(r.projectId??c)!==c)return;switch(r.transition){case"installing":case"enabled":case"disabled":case"settings-updated":I(j,v),f(p=>{const u=p.findIndex(t=>t.id===r.pluginId);if(u>=0){const t=[...p];return t[u]={...t[u],enabled:r.enabled,state:r.state,settings:r.settings,error:r.error},t}else return y(),p});break;case"state-changed":f(p=>{const u=p.findIndex(t=>t.id===r.pluginId);if(u>=0){const t=[...p];return t[u]={...t[u],state:r.state,error:r.error},t}return p});break;case"uninstalled":f(p=>p.filter(u=>u.id!==r.pluginId)),I(j,v);break;case"error":f(p=>{const u=p.findIndex(t=>t.id===r.pluginId);if(u>=0){const t=[...p];return t[u]={...t[u],state:r.state,error:r.error},t}return p});break}}catch{}};return Ve(`/api/events${s}`,{events:{"plugin:lifecycle":i},onReconnect:()=>{y(),I(j,v)}})},[c,y,I,v,j]);const le=async()=>{if(!C.trim()){l(n("plugins.installPathRequired","Please enter a plugin path"),"error");return}try{O(!0),await Q({path:C,...U?{aiScanOnLoad:!0}:{}},c),l(n("plugins.installedGlobally","Plugin installed globally"),"success"),w(!1),E(""),$(!1),await y(),g?.()}catch(s){l(n("plugins.installFailed","Failed to install plugin: {{error}}",{error:s instanceof Error?s.message:String(s)}),"error")}finally{O(!1)}},qe=async s=>{if(!s.path){l(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),l(n("plugins.builtinInstalledGlobally","{{name}} installed globally",{name:s.name}),"success"),await y(),g?.()}catch(i){l(n("plugins.builtinInstallFailed","Failed to install {{name}}: {{error}}",{name:s.name,error:i instanceof Error?i.message:String(i)}),"error")}finally{X(null)}},Ge=async s=>{if(!s.path){l(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),l(n("plugins.registryInstalled","{{name}} installed and enabled",{name:s.name}),"success"),await y(),g?.(),await I(j,v)}catch(i){l(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 ls(s.id,c);if(!i.success){l(n("plugins.setupInstallFailed","Failed to install {{name}} setup: {{error}}",{name:s.name,error:i.error??n("plugins.unknownError","unknown error")}),"error");return}l(n("plugins.setupInstalled","{{name}} setup installed",{name:s.name}),"success"),te(s.id);const a=await ge(s.id,c);z(r=>({...r,[s.id]:a}))}catch(i){l(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 is(s.id,c);if(f(a=>a.map(r=>r.id===i.id?i:r)),i.state==="error"){l(n("plugins.enableFailed","Failed to enable {{name}}: {{error}}",{name:s.name,error:i.error??n("plugins.unknownError","unknown error")}),"error"),await y();return}l(n("plugins.enabledForProject","{{name}} enabled for this project",{name:s.name}),"success"),await y(!0,i),g?.()}catch(i){l(n("plugins.enablePluginFailed","Failed to enable plugin: {{error}}",{error:i instanceof Error?i.message:String(i)}),"error")}},V=async s=>{try{const i=await ns(s.id,c);f(a=>a.map(r=>r.id===i.id?i:r)),l(n("plugins.disabledForProject","{{name}} disabled for this project",{name:s.name}),"success"),await y(!0,i),g?.()}catch(i){l(n("plugins.disablePluginFailed","Failed to disable plugin: {{error}}",{error:i instanceof Error?i.message:String(i)}),"error")}},Oe=async s=>{s.enabled?await V(s):await H(s)},oe=async s=>{try{m(s.id),await ss(s.id,c),l(n("plugins.reloaded","{{name}} reloaded",{name:s.name}),"success"),await y()}catch(i){l(n("plugins.reloadFailed","Failed to reload plugin: {{error}}",{error:i instanceof Error?i.message:String(i)}),"error")}finally{m(null)}},ue=async s=>{if(await Le({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 ts(s.id,c),l(n("plugins.uninstalledGlobally","{{name}} uninstalled globally",{name:s.name}),"success"),await y(),g?.(),B(null)}catch(a){l(n("plugins.uninstallFailed","Failed to uninstall plugin: {{error}}",{error:a instanceof Error?a.message:String(a)}),"error")}},Ue=async(s,i)=>{try{await Xe(s.id,{aiScanOnLoad:i},c),l(i?n("plugins.aiScanEnabled","AI scan on load enabled"):n("plugins.aiScanDisabled","AI scan on load disabled"),"success"),await y()}catch(a){l(n("plugins.updateFailed","Failed to update plugin: {{error}}",{error:a instanceof Error?a.message:String(a)}),"error")}},$e=async s=>{try{await Ze(s.id,c),l(n("plugins.rescanned","{{name}} rescanned",{name:s.name}),"success"),await y()}catch(i){l(n("plugins.rescanFailed","Failed to rescan plugin: {{error}}",{error:i instanceof Error?i.message:String(i)}),"error")}},M=async s=>{B(s);try{K(!0);const i=await as(s.id,c);S(i)}catch{S({})}finally{K(!1)}},We=async()=>{if(o)try{await es(o.id,h,c),l(n("plugins.settingsSaved","Settings saved"),"success")}catch(s){l(n("plugins.saveSettingsFailed","Failed to save settings: {{error}}",{error:s instanceof Error?s.message:String(s)}),"error")}};if(o)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:()=>B(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:o.name}),we(o,"plugin-error-text plugin-error-text--detail")]}),e.jsx("span",{className:"plugin-state-badge",style:{color:_[o.state]||_.installed},children:o.state})]})]}),e.jsxs("div",{className:"plugin-detail-content",children:[e.jsxs("div",{className:"plugin-detail-card",children:[o.description&&e.jsx("p",{className:"plugin-description",children:o.description}),o.author&&e.jsxs("p",{className:"plugin-detail-meta-row",children:[e.jsx("span",{className:"text-muted",children:n("plugins.author","Author:")}),o.author]}),o.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:o.homepage,target:"_blank",rel:"noopener noreferrer",children:[o.homepage,e.jsx(Qe,{size:12})]})]}),e.jsxs("p",{className:"plugin-detail-meta-row",children:[e.jsx("span",{className:"text-muted",children:n("plugins.version","Version:")}),o.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:!!o.aiScanOnLoad,onChange:s=>void Ue(o,s.target.checked)}),n("plugins.enableAiScanBeforeLoad","Enable AI scan before load/reload")]}),e.jsxs("button",{className:"btn btn-secondary btn-sm",onClick:()=>void $e(o),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.")}),o.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--${o.lastSecurityScan.verdict}`,children:o.lastSecurityScan.verdict}),e.jsx("span",{className:"text-muted",children:o.lastSecurityScan.scannedAt})]}),e.jsx("p",{className:"plugin-security-summary",children:o.lastSecurityScan.summary}),e.jsxs("details",{children:[e.jsx("summary",{children:n("plugins.findings","Findings ({{count}})",{count:o.lastSecurityScan.findings.length})}),e.jsx("ul",{className:"plugin-security-findings",children:o.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")}),o.id==="fusion-plugin-whatsapp-chat"&&e.jsx(ds,{projectId:c,settings:h}),Pe?e.jsx("p",{className:"text-muted",children:e.jsx(he,{label:n("plugins.loading","Loading...")})}):(()=>{const s=ps(o);return s&&Object.keys(s).length>0?e.jsxs("div",{className:"plugin-settings-form",children:[(()=>{const{grouped:i,ungrouped:a}=gs(s),r=[];a.length>0&&r.push({title:null,entries:a});for(const[p,u]of i.entries())r.push({title:p,entries:u});return r.map(p=>e.jsxs("div",{className:p.title?"plugin-settings-group":void 0,children:[p.title&&e.jsx("h6",{className:"plugin-settings-group-heading",children:Ne[p.title]?n(Ne[p.title],p.title):p.title}),p.entries.map(([u,t])=>{const k=`setting-${u}-help`,L=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:[L,t.required&&" *"]}),t.type==="string"&&!t.multiline&&e.jsx("input",{className:"input",type:"text",id:`setting-${u}`,value:h[u]??"",onChange:b=>S({...h,[u]:b.target.value}),placeholder:t.description,"aria-describedby":t.description&&!t.required?k:void 0}),t.type==="string"&&t.multiline&&e.jsx("textarea",{className:"input",id:`setting-${u}`,rows:4,value:h[u]??"",onChange:b=>S({...h,[u]:b.target.value}),placeholder:t.description,"aria-describedby":t.description&&!t.required?k:void 0}),t.type==="password"&&e.jsx("input",{className:"input",type:"password",id:`setting-${u}`,value:h[u]??"",onChange:b=>S({...h,[u]:b.target.value}),placeholder:t.description,"aria-describedby":t.description&&!t.required?k:void 0}),t.type==="number"&&e.jsx("input",{className:"input",type:"number",id:`setting-${u}`,value:h[u]??"",onChange:b=>S({...h,[u]:Number(b.target.value)}),"aria-describedby":t.description&&!t.required?k:void 0}),t.type==="boolean"&&e.jsxs("label",{className:"checkbox-label",children:[e.jsx("input",{type:"checkbox",checked:h[u]??!1,onChange:b=>S({...h,[u]:b.target.checked})}),t.description]}),t.type==="enum"&&e.jsxs("select",{className:"select",id:`setting-${u}`,value:h[u]??"",onChange:b=>S({...h,[u]:b.target.value}),"aria-describedby":t.description&&!t.required?k:void 0,children:[e.jsx("option",{value:"",children:n("plugins.selectOption","Select...")}),t.enumValues?.map(b=>e.jsx("option",{value:b,children:b},b))]}),t.type==="array"&&e.jsxs("div",{className:"plugin-settings-array",children:[h[u]?.map((b,R)=>e.jsxs("div",{className:"plugin-settings-array-item",children:[e.jsx("input",{className:"input",type:t.itemType==="number"?"number":"text",value:b??"",onChange:T=>{const D=T.target.value,pe=[...h[u]||[]];pe[R]=t.itemType==="number"?Number(D):D,S({...h,[u]:pe})}}),e.jsx("button",{className:"btn-icon",onClick:()=>{const D=[...h[u]||[]];D.splice(R,1),S({...h,[u]:D})},"aria-label":n("plugins.removeItem","Remove item"),children:e.jsx(me,{size:14})})]},R)),e.jsxs("button",{className:"btn btn-secondary",onClick:()=>{const b=h[u]||[],R=t.itemType==="number"?0:"";S({...h,[u]:[...b,R]})},children:[e.jsx(be,{size:14})," ",n("plugins.addItem","Add Item")]})]}),t.description&&!t.required&&!t.multiline&&e.jsx("span",{id:k,className:"form-help",children:t.description})]},u)})]},p.title??"ungrouped"))})(),e.jsx("button",{className:"btn btn-primary",onClick:We,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:[o.state==="started"&&e.jsxs("button",{className:"btn btn-secondary",onClick:()=>oe(o),disabled:N===o.id,children:[e.jsx(ye,{size:14,className:N===o.id?"spin":""}),N===o.id?n("plugins.reloading","Reloading..."):n("plugins.reload","Reload")]}),o.enabled?e.jsx("button",{className:"btn btn-secondary",onClick:()=>V(o),children:n("plugins.disableInProject","Disable in Project")}):e.jsx("button",{className:"btn btn-primary",onClick:()=>H(o),children:n("plugins.enableInProject","Enable in Project")}),e.jsxs("button",{className:"btn btn-danger",onClick:()=>ue(o),children:[e.jsx(xe,{size:14})," ",n("plugins.uninstallGlobally","Uninstall Globally")]})]})]})]});const ce=new Map(x.map(s=>[s.id,s])),de=x,Me=()=>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:v,onChange:s=>ke(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:j,onChange:s=>Ie(s.target.value),placeholder:n("plugins.searchRegistryPlaceholder","Search registry plugins")})]})]})]}),Ee?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 I(j,v),children:n("plugins.retry","Retry")})]}):Z.length===0?e.jsx("div",{className:"plugin-registry-state",children:j.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),a=Be===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?M(i):y()},children:n("plugins.manage","Manage")}):s.canInstall?e.jsx("button",{className:"btn btn-primary btn-sm plugin-registry-action",onClick:()=>void Ge(s),disabled:a,children:a?n("plugins.installing","Installing..."):n("plugins.installFromRegistry","Install")}):e.jsx("span",{className:"plugin-registry-coming-soon",children:n("plugins.registryComingSoon","Coming Soon")})})]},s.id)})})]}),Te=()=>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:ve.map(s=>{const i=ce.get(s.id),a=!!i,r=Ae[s.id],p=!!(r&&"setupCheckDeferred"in r&&r.setupCheckDeferred),u=r&&"status"in r?r.status:void 0,t=a&&s.hasSetup&&r?.hasSetup&&!p&&i?.state==="started"&&(u==="not-installed"||u==="error"),k=a&&r?.hasSetup&&u==="installed",L=Fe===s.id,b=!s.path,R=s.category==="runtime",T=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 ${a?"plugin-builtins-status--installed":"plugin-builtins-status--available"}`,children:a?n("plugins.statusInstalled","Installed"):b?n("plugins.statusBuiltIn","Built in"):n("plugins.statusNotInstalled","Not installed")}),R&&T===!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")}),k&&e.jsx("span",{className:"plugin-builtins-setup-status plugin-builtins-setup-status--ready",children:n("plugins.setupReady","Setup ready")}),L&&e.jsx("span",{className:"plugin-builtins-setup-status plugin-builtins-setup-status--pending",children:n("plugins.checkingSetup","Checking setup...")}),p&&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:[R&&i&&e.jsxs("label",{className:"toggle-switch",children:[e.jsx("input",{type:"checkbox",checked:i.enabled,onChange:()=>void Oe(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"})]}),b?a&&t?e.jsx("button",{className:"btn btn-primary btn-sm",onClick:()=>void re(s),disabled:W===s.id||L,children:W===s.id?n("plugins.settingUp","Setting up..."):n("plugins.installSetup","Install Setup")}):a&&i?e.jsx("button",{className:"btn btn-secondary btn-sm",onClick:()=>void M(i),children:n("plugins.manage","Manage")}):R?null:e.jsx("span",{className:"plugin-builtins-metadata-only",children:n("plugins.builtinMetadataOnly","Built-in metadata only")}):e.jsx("button",{className:`btn ${a&&!t?"btn-secondary":"btn-primary"} btn-sm`,onClick:()=>{if(!a){qe(s);return}if(t){re(s);return}i&&M(i)},disabled:Y===s.id||W===s.id||L,children:a?t?W===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 y(),title:n("plugins.refresh","Refresh"),"aria-label":n("plugins.refreshPluginList","Refresh plugin list"),children:[e.jsx(fe,{size:14,className:A?"spin":""}),n("plugins.refresh","Refresh")]}),e.jsxs("button",{className:"btn btn-primary btn-sm",onClick:()=>w(!0),children:[e.jsx(be,{size:14})," ",n("plugins.install","Install")]})]})]}),G&&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(rs,{value:C,onChange:E,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:U,onChange:s=>$(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:P||!C.trim(),children:P?n("plugins.installing","Installing..."):n("plugins.installPluginGlobally","Install Plugin Globally")}),e.jsx("button",{className:"btn btn-secondary",onClick:()=>{w(!1),E("")},children:n("plugins.cancel","Cancel")})]})]}),A?e.jsx("div",{className:"settings-empty-state",children:e.jsx(he,{label:n("plugins.loadingPlugins","Loading plugins...")})}):e.jsxs(e.Fragment,{children:[de.length===0?e.jsxs("div",{className:"settings-empty-state",children:[e.jsx(Ke,{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:de.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:_[s.state]||_.installed},children:s.state})]}),we(s)]})}),e.jsxs("div",{className:"plugin-actions",children:[s.state==="started"&&e.jsx("button",{className:"btn-icon",onClick:()=>oe(s),disabled:N===s.id,title:n("plugins.reload","Reload"),children:e.jsx(ye,{size:14,className:N===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:()=>M(s),title:n("plugins.settings","Settings"),children:e.jsx(Ye,{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))}),Te(),Me()]})]})}export{je as AGENT_BROWSER_SETTINGS_SCHEMA,Ce as BUILTIN_AGENT_BROWSER_PLUGIN_ID,ve as BUILTIN_PLUGINS,vs as PluginManager,_ as STATE_COLORS};
1
+ import{r as d,j as e}from"./vendor-react-SZ_qB27O.js";import{ab as _e,be as ze,bf as He,bg as ge,bh as Ve,X as me,aR as Qe,bi as Je,aJ as he,P as be,b1 as ye,x as xe,R as fe,aM as Ke,_ as Ye,bj as Xe,bk as Ze,bl as es,bm as ss,bn as ns,bo as is,bp as ts,bq as Q,br as as,bs as ls}from"./index-CtYRoouR.js";import{D as rs}from"./DirectoryPicker-BhyDL_2m.js";import{u as os}from"./vendor-i18n-Duky4gdQ.js";import"./vendor-codemirror-CcrtqoCy.js";import"./vendor-reactflow-BlIeoTu4.js";import"./vendor-xterm-BNq00GSj.js";import"./folder-open-D-554oji.js";const us="/api/plugins/fusion-plugin-whatsapp-chat",cs=/^\d+$/;function J(l,c){const g=c?`?projectId=${encodeURIComponent(c)}`:"";return`${us}${l}${g}`}function ds({projectId:l,settings:c}){const[g,n]=d.useState(null),[x,f]=d.useState(null),[A,q]=d.useState(()=>String(c?.pairingPhoneNumber??"")),[G,w]=d.useState(null),[C,E]=d.useState(null),P=d.useCallback(async()=>{try{const m=await fetch(J("/status",l)),o=await m.json();if(!m.ok)throw new Error(o.error??"WhatsApp pairing is unavailable. Enable the plugin and try again.");n(o),f(null)}catch(m){f(m instanceof Error?m.message:String(m))}},[l]);d.useEffect(()=>{P();const m=window.setInterval(()=>void P(),5e3);return()=>window.clearInterval(m)},[P]);const O=async()=>{const m=A.trim();if(!m||!cs.test(m)){w("Enter an E.164 phone number using digits only, without +.");return}E("code"),w(null);try{const o=await fetch(J("/pair-code",l),{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify({phoneNumber:m,...l?{projectId:l}:{}})}),B=await o.json();if(!o.ok)throw new Error(B.error??"Could not request a pairing code.");n(h=>({status:"awaiting-code",...h,pairingCode:B.pairingCode})),await P()}catch(o){w(o instanceof Error?o.message:String(o))}finally{E(null)}},U=async()=>{E("logout"),w(null);try{const m=await fetch(J("/logout",l),{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify(l?{projectId:l}:{})});if(!m.ok){const o=await m.json();throw new Error(o.error??"Could not log out from WhatsApp.")}await P()}catch(m){w(m instanceof Error?m.message:String(m))}finally{E(null)}},$=c?.pairingMode==="code"?"code":"qr",N=g?.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:"WhatsApp pairing"}),e.jsx("p",{className:"whatsapp-pairing-description",children:"Pair and monitor this project's WhatsApp connection here."})]}),e.jsx("button",{className:"btn btn-secondary btn-sm",type:"button",onClick:()=>void P(),children:"Refresh status"})]}),e.jsxs("div",{className:`whatsapp-pairing-status whatsapp-pairing-status--${N}`,role:"status","data-testid":"whatsapp-pairing-status",children:[e.jsxs("strong",{children:["Status: ",N]}),g?.jid&&e.jsxs("span",{children:["Connected as ",g.jid]}),(g?.lastError||x)&&e.jsx("span",{className:"field-error",children:g?.lastError??x})]}),N==="awaiting-qr"&&e.jsx("div",{className:"whatsapp-pairing-qr","data-testid":"whatsapp-pairing-qr",children:g?.qrDataUrl?e.jsx("img",{src:g.qrDataUrl,alt:"WhatsApp pairing QR code",className:"whatsapp-pairing-qr-image"}):e.jsx("p",{className:"text-muted",children:"Waiting for a fresh QR code. Keep this panel open and refresh if needed."})}),($==="code"||N==="awaiting-code")&&e.jsxs("div",{className:"whatsapp-pairing-code",children:[e.jsx("label",{htmlFor:"whatsapp-pairing-phone",children:"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:A,onChange:m=>q(m.target.value),inputMode:"numeric"}),e.jsx("button",{className:"btn btn-secondary",type:"button",onClick:()=>void O(),disabled:C!==null,children:C==="code"?"Requesting code...":"Request pairing code"})]}),g?.pairingCode&&e.jsx("output",{className:"whatsapp-pairing-code-output",children:g.pairingCode})]}),N==="connected"&&e.jsx("p",{className:"whatsapp-pairing-success",children:"WhatsApp is paired and ready to receive messages from allowed senders."}),G&&e.jsx("p",{className:"field-error",children:G}),e.jsx("button",{className:"btn btn-danger",type:"button",onClick:()=>void U(),disabled:C!==null,"data-testid":"whatsapp-pairing-logout",children:C==="logout"?"Logging out...":"Logout and re-pair"}),e.jsxs("aside",{className:"whatsapp-pairing-instructions","aria-label":"WhatsApp pairing instructions","data-testid":"whatsapp-pairing-instructions",children:[e.jsx("h6",{children:"Pairing and configuration"}),e.jsxs("ol",{children:[e.jsx("li",{children:"Install and enable this plugin, then keep this settings panel open."}),e.jsxs("li",{children:["Set ",e.jsx("strong",{children:"Allowed WhatsApp Senders"}),"; an empty list blocks all inbound messages."]}),e.jsxs("li",{children:["Choose ",e.jsx("strong",{children:"QR"})," to scan in WhatsApp Linked Devices, or ",e.jsx("strong",{children:"code"})," to enter a phone number and request a pairing code."]}),e.jsxs("li",{children:["Wait for the status above to become ",e.jsx("strong",{children:"connected"}),"."]}),e.jsx("li",{children:"Use Logout and re-pair to start over. If QR is still pending, wait briefly or refresh status for a new code."})]})]})]})}const Ce="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"},ve=[{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:Ce,name:"Agent Browser",description:"Built-in integration metadata. Package install support lands in FN-3101.",category:"integration",hasSetup:!0}],_={started:"var(--color-success)",loaded:"var(--color-warning)",error:"var(--color-error)",stopped:"var(--color-muted)",installed:"var(--color-info)"};function ps(l){const c=l.settingsSchema,g=c&&Object.keys(c).length>0;return l.id!==Ce?g?c:void 0:g?{...je,...c}:je}function gs(l){const c=new Map,g=[];for(const[n,x]of Object.entries(l))if(x.group){const f=c.get(x.group)??[];f.push([n,x]),c.set(x.group,f)}else g.push([n,x]);return{grouped:c,ungrouped:g}}function we(l,c="plugin-error-text"){return l.state!=="error"||!l.error?null:e.jsx("p",{className:c,title:l.error,children:l.error})}function vs({addToast:l,projectId:c,onPluginsChanged:g}){const{t:n}=os("app"),[x,f]=d.useState([]),[A,q]=d.useState(!0),[G,w]=d.useState(!1),[C,E]=d.useState(""),[P,O]=d.useState(!1),[U,$]=d.useState(!1),[N,m]=d.useState(null),[o,B]=d.useState(null),[h,S]=d.useState({}),[Pe,K]=d.useState(!1),[Y,X]=d.useState(null),[Z,Re]=d.useState([]),[Ee,ee]=d.useState(!0),[se,ne]=d.useState(null),[j,Ie]=d.useState(""),[v,ke]=d.useState(""),[Be,ie]=d.useState(null),F=d.useRef(null),[Ae,z]=d.useState({}),[Fe,te]=d.useState(null),[W,ae]=d.useState(null),{confirm:Le}=_e(),y=d.useCallback(async(s=!1,i)=>{try{s||q(!0);const a=await ze(c);f(i?a.some(r=>r.id===i.id)?a.map(r=>r.id===i.id?i:r):[...a,i]:a)}catch(a){l(n("plugins.loadFailed","Failed to load plugins: {{error}}",{error:a instanceof Error?a.message:String(a)}),"error")}finally{s||q(!1)}},[c,l]),I=d.useCallback(async(s=j,i=v)=>{try{ee(!0),ne(null);const a=await He(s,i||void 0,c);Re(a)}catch(a){const r=a instanceof Error?a.message:String(a);ne(r)}finally{ee(!1)}},[c,v,j]);d.useEffect(()=>{y()},[y]),d.useEffect(()=>(F.current&&clearTimeout(F.current),F.current=setTimeout(()=>{I(j,v)},300),()=>{F.current&&clearTimeout(F.current)}),[I,v,j]),d.useEffect(()=>{const s=ve.filter(a=>a.hasSetup&&x.some(r=>r.id===a.id));if(s.length===0)return;let i=!1;return Promise.all(s.map(async a=>{try{const r=await ge(a.id,c);if(i)return;z(p=>({...p,[a.id]:r}))}catch{if(i)return;z(r=>({...r,[a.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=a=>{try{const r=JSON.parse(a.data);if(r.scope==="project"&&(r.projectId??c)!==c)return;switch(r.transition){case"installing":case"enabled":case"disabled":case"settings-updated":I(j,v),f(p=>{const u=p.findIndex(t=>t.id===r.pluginId);if(u>=0){const t=[...p];return t[u]={...t[u],enabled:r.enabled,state:r.state,settings:r.settings,error:r.error},t}else return y(),p});break;case"state-changed":f(p=>{const u=p.findIndex(t=>t.id===r.pluginId);if(u>=0){const t=[...p];return t[u]={...t[u],state:r.state,error:r.error},t}return p});break;case"uninstalled":f(p=>p.filter(u=>u.id!==r.pluginId)),I(j,v);break;case"error":f(p=>{const u=p.findIndex(t=>t.id===r.pluginId);if(u>=0){const t=[...p];return t[u]={...t[u],state:r.state,error:r.error},t}return p});break}}catch{}};return Ve(`/api/events${s}`,{events:{"plugin:lifecycle":i},onReconnect:()=>{y(),I(j,v)}})},[c,y,I,v,j]);const le=async()=>{if(!C.trim()){l(n("plugins.installPathRequired","Please enter a plugin path"),"error");return}try{O(!0),await Q({path:C,...U?{aiScanOnLoad:!0}:{}},c),l(n("plugins.installedGlobally","Plugin installed globally"),"success"),w(!1),E(""),$(!1),await y(),g?.()}catch(s){l(n("plugins.installFailed","Failed to install plugin: {{error}}",{error:s instanceof Error?s.message:String(s)}),"error")}finally{O(!1)}},qe=async s=>{if(!s.path){l(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),l(n("plugins.builtinInstalledGlobally","{{name}} installed globally",{name:s.name}),"success"),await y(),g?.()}catch(i){l(n("plugins.builtinInstallFailed","Failed to install {{name}}: {{error}}",{name:s.name,error:i instanceof Error?i.message:String(i)}),"error")}finally{X(null)}},Ge=async s=>{if(!s.path){l(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),l(n("plugins.registryInstalled","{{name}} installed and enabled",{name:s.name}),"success"),await y(),g?.(),await I(j,v)}catch(i){l(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 ls(s.id,c);if(!i.success){l(n("plugins.setupInstallFailed","Failed to install {{name}} setup: {{error}}",{name:s.name,error:i.error??n("plugins.unknownError","unknown error")}),"error");return}l(n("plugins.setupInstalled","{{name}} setup installed",{name:s.name}),"success"),te(s.id);const a=await ge(s.id,c);z(r=>({...r,[s.id]:a}))}catch(i){l(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 is(s.id,c);if(f(a=>a.map(r=>r.id===i.id?i:r)),i.state==="error"){l(n("plugins.enableFailed","Failed to enable {{name}}: {{error}}",{name:s.name,error:i.error??n("plugins.unknownError","unknown error")}),"error"),await y();return}l(n("plugins.enabledForProject","{{name}} enabled for this project",{name:s.name}),"success"),await y(!0,i),g?.()}catch(i){l(n("plugins.enablePluginFailed","Failed to enable plugin: {{error}}",{error:i instanceof Error?i.message:String(i)}),"error")}},V=async s=>{try{const i=await ns(s.id,c);f(a=>a.map(r=>r.id===i.id?i:r)),l(n("plugins.disabledForProject","{{name}} disabled for this project",{name:s.name}),"success"),await y(!0,i),g?.()}catch(i){l(n("plugins.disablePluginFailed","Failed to disable plugin: {{error}}",{error:i instanceof Error?i.message:String(i)}),"error")}},Oe=async s=>{s.enabled?await V(s):await H(s)},oe=async s=>{try{m(s.id),await ss(s.id,c),l(n("plugins.reloaded","{{name}} reloaded",{name:s.name}),"success"),await y()}catch(i){l(n("plugins.reloadFailed","Failed to reload plugin: {{error}}",{error:i instanceof Error?i.message:String(i)}),"error")}finally{m(null)}},ue=async s=>{if(await Le({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 ts(s.id,c),l(n("plugins.uninstalledGlobally","{{name}} uninstalled globally",{name:s.name}),"success"),await y(),g?.(),B(null)}catch(a){l(n("plugins.uninstallFailed","Failed to uninstall plugin: {{error}}",{error:a instanceof Error?a.message:String(a)}),"error")}},Ue=async(s,i)=>{try{await Xe(s.id,{aiScanOnLoad:i},c),l(i?n("plugins.aiScanEnabled","AI scan on load enabled"):n("plugins.aiScanDisabled","AI scan on load disabled"),"success"),await y()}catch(a){l(n("plugins.updateFailed","Failed to update plugin: {{error}}",{error:a instanceof Error?a.message:String(a)}),"error")}},$e=async s=>{try{await Ze(s.id,c),l(n("plugins.rescanned","{{name}} rescanned",{name:s.name}),"success"),await y()}catch(i){l(n("plugins.rescanFailed","Failed to rescan plugin: {{error}}",{error:i instanceof Error?i.message:String(i)}),"error")}},M=async s=>{B(s);try{K(!0);const i=await as(s.id,c);S(i)}catch{S({})}finally{K(!1)}},We=async()=>{if(o)try{await es(o.id,h,c),l(n("plugins.settingsSaved","Settings saved"),"success")}catch(s){l(n("plugins.saveSettingsFailed","Failed to save settings: {{error}}",{error:s instanceof Error?s.message:String(s)}),"error")}};if(o)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:()=>B(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:o.name}),we(o,"plugin-error-text plugin-error-text--detail")]}),e.jsx("span",{className:"plugin-state-badge",style:{color:_[o.state]||_.installed},children:o.state})]})]}),e.jsxs("div",{className:"plugin-detail-content",children:[e.jsxs("div",{className:"plugin-detail-card",children:[o.description&&e.jsx("p",{className:"plugin-description",children:o.description}),o.author&&e.jsxs("p",{className:"plugin-detail-meta-row",children:[e.jsx("span",{className:"text-muted",children:n("plugins.author","Author:")}),o.author]}),o.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:o.homepage,target:"_blank",rel:"noopener noreferrer",children:[o.homepage,e.jsx(Qe,{size:12})]})]}),e.jsxs("p",{className:"plugin-detail-meta-row",children:[e.jsx("span",{className:"text-muted",children:n("plugins.version","Version:")}),o.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:!!o.aiScanOnLoad,onChange:s=>void Ue(o,s.target.checked)}),n("plugins.enableAiScanBeforeLoad","Enable AI scan before load/reload")]}),e.jsxs("button",{className:"btn btn-secondary btn-sm",onClick:()=>void $e(o),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.")}),o.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--${o.lastSecurityScan.verdict}`,children:o.lastSecurityScan.verdict}),e.jsx("span",{className:"text-muted",children:o.lastSecurityScan.scannedAt})]}),e.jsx("p",{className:"plugin-security-summary",children:o.lastSecurityScan.summary}),e.jsxs("details",{children:[e.jsx("summary",{children:n("plugins.findings","Findings ({{count}})",{count:o.lastSecurityScan.findings.length})}),e.jsx("ul",{className:"plugin-security-findings",children:o.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")}),o.id==="fusion-plugin-whatsapp-chat"&&e.jsx(ds,{projectId:c,settings:h}),Pe?e.jsx("p",{className:"text-muted",children:e.jsx(he,{label:n("plugins.loading","Loading...")})}):(()=>{const s=ps(o);return s&&Object.keys(s).length>0?e.jsxs("div",{className:"plugin-settings-form",children:[(()=>{const{grouped:i,ungrouped:a}=gs(s),r=[];a.length>0&&r.push({title:null,entries:a});for(const[p,u]of i.entries())r.push({title:p,entries:u});return r.map(p=>e.jsxs("div",{className:p.title?"plugin-settings-group":void 0,children:[p.title&&e.jsx("h6",{className:"plugin-settings-group-heading",children:Ne[p.title]?n(Ne[p.title],p.title):p.title}),p.entries.map(([u,t])=>{const k=`setting-${u}-help`,L=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:[L,t.required&&" *"]}),t.type==="string"&&!t.multiline&&e.jsx("input",{className:"input",type:"text",id:`setting-${u}`,value:h[u]??"",onChange:b=>S({...h,[u]:b.target.value}),placeholder:t.description,"aria-describedby":t.description&&!t.required?k:void 0}),t.type==="string"&&t.multiline&&e.jsx("textarea",{className:"input",id:`setting-${u}`,rows:4,value:h[u]??"",onChange:b=>S({...h,[u]:b.target.value}),placeholder:t.description,"aria-describedby":t.description&&!t.required?k:void 0}),t.type==="password"&&e.jsx("input",{className:"input",type:"password",id:`setting-${u}`,value:h[u]??"",onChange:b=>S({...h,[u]:b.target.value}),placeholder:t.description,"aria-describedby":t.description&&!t.required?k:void 0}),t.type==="number"&&e.jsx("input",{className:"input",type:"number",id:`setting-${u}`,value:h[u]??"",onChange:b=>S({...h,[u]:Number(b.target.value)}),"aria-describedby":t.description&&!t.required?k:void 0}),t.type==="boolean"&&e.jsxs("label",{className:"checkbox-label",children:[e.jsx("input",{type:"checkbox",checked:h[u]??!1,onChange:b=>S({...h,[u]:b.target.checked})}),t.description]}),t.type==="enum"&&e.jsxs("select",{className:"select",id:`setting-${u}`,value:h[u]??"",onChange:b=>S({...h,[u]:b.target.value}),"aria-describedby":t.description&&!t.required?k:void 0,children:[e.jsx("option",{value:"",children:n("plugins.selectOption","Select...")}),t.enumValues?.map(b=>e.jsx("option",{value:b,children:b},b))]}),t.type==="array"&&e.jsxs("div",{className:"plugin-settings-array",children:[h[u]?.map((b,R)=>e.jsxs("div",{className:"plugin-settings-array-item",children:[e.jsx("input",{className:"input",type:t.itemType==="number"?"number":"text",value:b??"",onChange:T=>{const D=T.target.value,pe=[...h[u]||[]];pe[R]=t.itemType==="number"?Number(D):D,S({...h,[u]:pe})}}),e.jsx("button",{className:"btn-icon",onClick:()=>{const D=[...h[u]||[]];D.splice(R,1),S({...h,[u]:D})},"aria-label":n("plugins.removeItem","Remove item"),children:e.jsx(me,{size:14})})]},R)),e.jsxs("button",{className:"btn btn-secondary",onClick:()=>{const b=h[u]||[],R=t.itemType==="number"?0:"";S({...h,[u]:[...b,R]})},children:[e.jsx(be,{size:14})," ",n("plugins.addItem","Add Item")]})]}),t.description&&!t.required&&!t.multiline&&e.jsx("span",{id:k,className:"form-help",children:t.description})]},u)})]},p.title??"ungrouped"))})(),e.jsx("button",{className:"btn btn-primary",onClick:We,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:[o.state==="started"&&e.jsxs("button",{className:"btn btn-secondary",onClick:()=>oe(o),disabled:N===o.id,children:[e.jsx(ye,{size:14,className:N===o.id?"spin":""}),N===o.id?n("plugins.reloading","Reloading..."):n("plugins.reload","Reload")]}),o.enabled?e.jsx("button",{className:"btn btn-secondary",onClick:()=>V(o),children:n("plugins.disableInProject","Disable in Project")}):e.jsx("button",{className:"btn btn-primary",onClick:()=>H(o),children:n("plugins.enableInProject","Enable in Project")}),e.jsxs("button",{className:"btn btn-danger",onClick:()=>ue(o),children:[e.jsx(xe,{size:14})," ",n("plugins.uninstallGlobally","Uninstall Globally")]})]})]})]});const ce=new Map(x.map(s=>[s.id,s])),de=x,Me=()=>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:v,onChange:s=>ke(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:j,onChange:s=>Ie(s.target.value),placeholder:n("plugins.searchRegistryPlaceholder","Search registry plugins")})]})]})]}),Ee?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 I(j,v),children:n("plugins.retry","Retry")})]}):Z.length===0?e.jsx("div",{className:"plugin-registry-state",children:j.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),a=Be===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?M(i):y()},children:n("plugins.manage","Manage")}):s.canInstall?e.jsx("button",{className:"btn btn-primary btn-sm plugin-registry-action",onClick:()=>void Ge(s),disabled:a,children:a?n("plugins.installing","Installing..."):n("plugins.installFromRegistry","Install")}):e.jsx("span",{className:"plugin-registry-coming-soon",children:n("plugins.registryComingSoon","Coming Soon")})})]},s.id)})})]}),Te=()=>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:ve.map(s=>{const i=ce.get(s.id),a=!!i,r=Ae[s.id],p=!!(r&&"setupCheckDeferred"in r&&r.setupCheckDeferred),u=r&&"status"in r?r.status:void 0,t=a&&s.hasSetup&&r?.hasSetup&&!p&&i?.state==="started"&&(u==="not-installed"||u==="error"),k=a&&r?.hasSetup&&u==="installed",L=Fe===s.id,b=!s.path,R=s.category==="runtime",T=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 ${a?"plugin-builtins-status--installed":"plugin-builtins-status--available"}`,children:a?n("plugins.statusInstalled","Installed"):b?n("plugins.statusBuiltIn","Built in"):n("plugins.statusNotInstalled","Not installed")}),R&&T===!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")}),k&&e.jsx("span",{className:"plugin-builtins-setup-status plugin-builtins-setup-status--ready",children:n("plugins.setupReady","Setup ready")}),L&&e.jsx("span",{className:"plugin-builtins-setup-status plugin-builtins-setup-status--pending",children:n("plugins.checkingSetup","Checking setup...")}),p&&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:[R&&i&&e.jsxs("label",{className:"toggle-switch",children:[e.jsx("input",{type:"checkbox",checked:i.enabled,onChange:()=>void Oe(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"})]}),b?a&&t?e.jsx("button",{className:"btn btn-primary btn-sm",onClick:()=>void re(s),disabled:W===s.id||L,children:W===s.id?n("plugins.settingUp","Setting up..."):n("plugins.installSetup","Install Setup")}):a&&i?e.jsx("button",{className:"btn btn-secondary btn-sm",onClick:()=>void M(i),children:n("plugins.manage","Manage")}):R?null:e.jsx("span",{className:"plugin-builtins-metadata-only",children:n("plugins.builtinMetadataOnly","Built-in metadata only")}):e.jsx("button",{className:`btn ${a&&!t?"btn-secondary":"btn-primary"} btn-sm`,onClick:()=>{if(!a){qe(s);return}if(t){re(s);return}i&&M(i)},disabled:Y===s.id||W===s.id||L,children:a?t?W===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 y(),title:n("plugins.refresh","Refresh"),"aria-label":n("plugins.refreshPluginList","Refresh plugin list"),children:[e.jsx(fe,{size:14,className:A?"spin":""}),n("plugins.refresh","Refresh")]}),e.jsxs("button",{className:"btn btn-primary btn-sm",onClick:()=>w(!0),children:[e.jsx(be,{size:14})," ",n("plugins.install","Install")]})]})]}),G&&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(rs,{value:C,onChange:E,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:U,onChange:s=>$(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:P||!C.trim(),children:P?n("plugins.installing","Installing..."):n("plugins.installPluginGlobally","Install Plugin Globally")}),e.jsx("button",{className:"btn btn-secondary",onClick:()=>{w(!1),E("")},children:n("plugins.cancel","Cancel")})]})]}),A?e.jsx("div",{className:"settings-empty-state",children:e.jsx(he,{label:n("plugins.loadingPlugins","Loading plugins...")})}):e.jsxs(e.Fragment,{children:[de.length===0?e.jsxs("div",{className:"settings-empty-state",children:[e.jsx(Ke,{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:de.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:_[s.state]||_.installed},children:s.state})]}),we(s)]})}),e.jsxs("div",{className:"plugin-actions",children:[s.state==="started"&&e.jsx("button",{className:"btn-icon",onClick:()=>oe(s),disabled:N===s.id,title:n("plugins.reload","Reload"),children:e.jsx(ye,{size:14,className:N===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:()=>M(s),title:n("plugins.settings","Settings"),children:e.jsx(Ye,{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))}),Te(),Me()]})]})}export{je as AGENT_BROWSER_SETTINGS_SCHEMA,Ce as BUILTIN_AGENT_BROWSER_PLUGIN_ID,ve as BUILTIN_PLUGINS,vs as PluginManager,_ as STATE_COLORS};
@@ -1,4 +1,4 @@
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,aR as Z,an as K,a as E}from"./index-DWRJyaa3.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,a_ as k,a$ as N,b0 as C,b1 as F,b2 as M,b3 as ae,b4 as X,aR as Z,an as K,a as E}from"./index-CtYRoouR.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.
@@ -1,4 +1,4 @@
1
- import{r as o,j as e,b as se}from"./vendor-react-SZ_qB27O.js";import{c as _,dh as re,dk as Q,aa as le,C as X,dl as ne,dm as oe,q as ce,b3 as ie,bP as he,dn as A,dp as de,dq as Y}from"./index-DWRJyaa3.js";import{u as V}from"./vendor-i18n-Duky4gdQ.js";/**
1
+ import{r as o,j as e,b as se}from"./vendor-react-SZ_qB27O.js";import{c as _,dj as re,dm as Q,aa as le,C as X,dn as ne,dp as oe,q as ce,b3 as ie,bF as he,dq as A,dr as de,ds as Y}from"./index-CtYRoouR.js";import{u as V}from"./vendor-i18n-Duky4gdQ.js";/**
2
2
  * @license lucide-react v1.7.0 - ISC
3
3
  *
4
4
  * This source code is licensed under the ISC license.
@@ -1,2 +1,2 @@
1
- import{r as c,j as e}from"./vendor-react-SZ_qB27O.js";import{ap as X,aq as ue,ar as he,bz as me,cX as Se,av as ce,cY as _e,bh as je,cZ as Y,aW as we,c_ as ke,c$ as Ne,d0 as Ce,d1 as Ee,d2 as Ae,d3 as Te,d4 as Pe,bD as Le,d5 as Ie,d6 as Fe,d7 as Me,d8 as De,aX as qe,ag as He,V as Ue,aI as pe,L as Oe,aJ as Ve}from"./index-DWRJyaa3.js";import{u as fe}from"./vendor-i18n-Duky4gdQ.js";import"./vendor-codemirror-CcrtqoCy.js";import"./vendor-reactflow-BlIeoTu4.js";import"./vendor-xterm-BNq00GSj.js";const $e="builtin",Q={pageFetch:!0,github:!1,localDocs:!0,llmSynthesis:!0};function ie(a){const n=a?.researchGlobalDefaults,l=a?.researchSettings;return{enabled:l?.enabled??a?.researchEnabled??a?.researchGlobalEnabled??!0,searchProvider:l?.searchProvider??n?.searchProvider??a?.researchGlobalWebSearchProvider??$e,synthesisProvider:l?.synthesisProvider??n?.synthesisProvider,synthesisModelId:l?.synthesisModelId??n?.synthesisModelId,enabledSources:{webSearch:!0,pageFetch:l?.enabledSources?.pageFetch??n?.enabledSources?.pageFetch??Q.pageFetch,github:l?.enabledSources?.github??n?.enabledSources?.github??Q.github,localDocs:l?.enabledSources?.localDocs??n?.enabledSources?.localDocs??Q.localDocs,llmSynthesis:l?.enabledSources?.llmSynthesis??n?.enabledSources?.llmSynthesis??Q.llmSynthesis},limits:{maxConcurrentRuns:l?.limits?.maxConcurrentRuns??a?.researchMaxConcurrentRuns??a?.researchGlobalMaxConcurrentRuns??3,maxSourcesPerRun:l?.limits?.maxSourcesPerRun??n?.maxSourcesPerRun??a?.researchMaxSourcesPerRun??a?.researchGlobalMaxSourcesPerRun??20,maxDurationMs:l?.limits?.maxDurationMs??a?.researchDefaultTimeout??a?.researchGlobalDefaultTimeout??3e5,requestTimeoutMs:l?.limits?.requestTimeoutMs??a?.researchGlobalFetchTimeoutMs??3e4},defaultExportFormat:n?.defaultExportFormat??"markdown"}}function be(a){const n=typeof a.id=="string"?a.id.trim():"";if(n)return n;const l=f=>f.trim().replace(/\s+/g," ").toLowerCase(),m=[l(a.heading??""),l(a.content??""),...[...a.sources??[]].map(l).filter(Boolean).sort()].join(`
2
- `);let s=2166136261;for(let f=0;f<m.length;f+=1)s^=m.charCodeAt(f),s=Math.imul(s,16777619);return`finding-${(s>>>0).toString(16).padStart(8,"0")}`}const Ge=300,Be=4e3,We=["queued","running","cancelling","retry_waiting"];function le(a,n){if(a instanceof Le){const l=a;return{message:a.message,status:a.status,code:l.researchCode??"INTERNAL_ERROR",setupHint:l.setupHint,retryable:l.retryable}}return a instanceof Error?{message:a.message,code:"INTERNAL_ERROR"}:{message:n,code:"INTERNAL_ERROR"}}function ze(a){if(!a)return{cancelable:!1,retryable:!1,isTransitioning:!1,blockingReason:"No run selected"};const n=We.includes(a.status),l=a.status==="queued"||a.status==="running",m=a.lifecycle?.retryable,s=a.status==="failed"||a.status==="timed_out",f=!!(s&&m);let x;return!l&&n?x="Run is already transitioning":!l&&a.status==="completed"?x="Completed runs cannot be cancelled":!l&&a.status==="cancelled"?x="Run is already cancelled":!l&&a.status==="retry_exhausted"?x="Retry attempts exhausted":!l&&a.status==="failed"?x="Failed runs cannot be cancelled":!l&&a.status==="timed_out"&&(x="Timed out runs cannot be cancelled"),!f&&s&&m===!1&&(x=a.lifecycle?.errorCode==="RETRY_EXHAUSTED"?"Retry attempts exhausted":"Run is not retryable"),{cancelable:l,retryable:f,isTransitioning:n,blockingReason:x}}function Ke(a){const n=a?.projectId,l=n??"",m=`${he.RESEARCH_RUNS_PREFIX}${l}`,s=`${he.RESEARCH_SELECTED_ID_PREFIX}${l}`,f=X(m,{maxAgeMs:ue}),x=X(s,{maxAgeMs:me}),r=c.useRef(Array.isArray(f)&&f.length>0),[D,M]=c.useState(()=>Array.isArray(f)?f:[]),[h,A]=c.useState(x??null),[P,w]=c.useState(null),[O,q]=c.useState({available:!0}),[V,L]=c.useState(!(Array.isArray(f)&&f.length>0)),[G,H]=c.useState(null),[B,k]=c.useState(null),[N,I]=c.useState(""),_=c.useRef(0),R=c.useRef(0),C=c.useRef(n);c.useEffect(()=>{C.current!==n&&(C.current=n,R.current++);const o=X(m,{maxAgeMs:ue}),d=X(s,{maxAgeMs:me}),p=Array.isArray(o)&&o.length>0;M(Array.isArray(o)?o:[]),A(d??null),w(null),L(!p),r.current=p},[n,m,s]);const S=c.useCallback(async(o=N)=>{const d=++_.current,p=n;r.current||L(!0),H(null),k(null);try{const y=await Se({q:o||void 0,limit:100},p);if(d!==_.current||p!==n)return;M(y.runs),ce(m,y.runs,{maxBytes:5e5}),r.current=!0,q(y.availability),h&&!y.runs.some(g=>g.id===h)&&(A(null),ce(s,null,{maxBytes:5e5}),w(null))}catch(y){if(d!==_.current||p!==n)return;const g=le(y,"Failed to load research runs");H(g.message),k(g)}finally{d===_.current&&L(!1)}},[n,m,N,s,h]),i=c.useCallback(async o=>{const d=await _e(o,n);return w(d.run),q(d.availability),d.run},[n]);c.useEffect(()=>{r.current||L(!0);const o=window.setTimeout(()=>{S(N)},Ge);return()=>window.clearTimeout(o)},[S,N]),c.useEffect(()=>{if(!h){w(null);return}i(h)},[i,h]),c.useEffect(()=>{const o=R.current,d=()=>R.current!==o,p=n?`?projectId=${encodeURIComponent(n)}`:"";let y=!0;const g=()=>{!y||d()||(S(),h&&i(h))},j=`/api/events${p}`,$=je(j,{events:{"research:run:created":g,"research:run:updated":g,"research:run:completed":g,"research:run:failed":g,"research:run:cancelled":g},onReconnect:()=>{Y({view:"useResearch",trigger:"sse-reconnect",projectId:n,replayAttempted:!1,sseChannel:j}),g()}});return Y({view:"useResearch",trigger:"sse-open",projectId:n,replayAttempted:!1,sseChannel:j}),()=>{y=!1,$()}},[n,S,h,i]);const E=c.useCallback(()=>{S(),h&&i(h)},[S,h,i]);we(E,Be);const T=c.useCallback(o=>{A(o),ce(s,o,{maxBytes:5e5})},[s]);return{runs:D,selectedRun:P,selectedRunId:h,setSelectedRunId:T,availability:O,loading:V,error:G,searchQuery:N,setSearchQuery:I,refresh:S,createRun:o=>Pe(o,n),cancelRun:async o=>{try{k(null);const d=await Te(o,n);return h===o&&w(d.run),await S(),d}catch(d){const p=le(d,"Failed to cancel run");throw k(p),p}},retryRun:async o=>{try{k(null);const d=await Ae(o,n);return h===o&&w(d.run),await S(),d}catch(d){const p=le(d,"Failed to retry run");throw k(p),p}},exportRun:(o,d)=>Ee(o,d,n),createTaskFromRun:(o,d,p,y,g,j)=>Ce(o,{title:d,findingId:p,description:y,priority:g,attachExport:j},n),attachRunToTask:(o,d,p,y)=>Ne(o,{taskId:d,findingId:p,attachExport:y},n),promoteFinding:(o,d)=>ke(o,d,n),uiError:B,runActionState:ze(P),statusCounts:D.reduce((o,d)=>(o[d.status]+=1,o),{queued:0,running:0,cancelling:0,retry_waiting:0,completed:0,failed:0,cancelled:0,timed_out:0,retry_exhausted:0})}}function Xe({open:a,mode:n,run:l,finding:m,projectId:s,onClose:f,onConfirm:x}){const{t:r}=fe("app");Ie(a);const[D,M]=c.useState(!1),[h,A]=c.useState(""),[P,w]=c.useState(""),[O,q]=c.useState("normal"),[V,L]=c.useState(""),[G,H]=c.useState([]),[B,k]=c.useState(!1),[N,I]=c.useState(!1),{boardWorkflows:_}=Fe({projectId:s}),R=c.useMemo(()=>{const i=new Map;for(const E of _?.workflows??[])for(const T of E.columns)i.has(T.id)||i.set(T.id,T.flags);return E=>Me(i.get(E),E)},[_]),C=c.useMemo(()=>{const i=(m.content??"").split(/(?<=[.!?])\s+/)[0]??"";return`${m.heading||r("research.defaultFindingHeading","Research finding")} — ${i}`.trim()},[m.content,m.heading,r]);c.useEffect(()=>{a&&(M(!1),A(`Research: ${m.heading||l.title}`),w(C),q("normal"),L(""))},[a,n,m.heading,C,l.title]),c.useEffect(()=>{if(!a||n!=="enrich")return;let i=!1;return H([]),k(!0),De(50,0,s).then(E=>{i||H(E.filter(T=>!R(T.column)))}).finally(()=>{i||k(!1)}),()=>{i=!0}},[a,n,s,R]);const S=V.trim();return a?e.jsx("div",{className:"modal-overlay open",role:"presentation",onClick:f,children:e.jsxs("div",{className:"modal modal-lg research-task-action-modal",role:"dialog","aria-modal":"true",onClick:i=>i.stopPropagation(),children:[e.jsxs("div",{className:"modal-header",children:[e.jsx("h3",{children:n==="create"?r("research.createTaskTitle","Create task from finding"):r("research.enrichTaskTitle","Enrich existing task")}),e.jsx("button",{className:"modal-close",type:"button","aria-label":r("actions.close","Close"),onClick:f,children:"×"})]}),e.jsxs("div",{className:"research-task-action-modal__body",children:[e.jsxs("div",{className:"card research-task-action-modal__preview",children:[e.jsxs("p",{children:[e.jsxs("strong",{children:[r("research.runLabel","Run:")," "]})," ",l.id]}),e.jsxs("p",{children:[e.jsxs("strong",{children:[r("research.findingLabel","Finding:")," "]})," ",m.id,m.heading?` — ${m.heading}`:""]}),e.jsx("p",{children:C||r("research.noPreview","No preview available.")})]}),n==="create"?e.jsxs(e.Fragment,{children:[e.jsxs("label",{className:"research-task-action-modal__field",children:[r("research.titleLabel","Title"),e.jsx("input",{className:"input",value:h,onChange:i=>A(i.target.value)})]}),e.jsxs("label",{className:"research-task-action-modal__field",children:[r("research.descriptionLabel","Description"),e.jsx("textarea",{className:"input research-task-action-modal__textarea",value:P,onChange:i=>w(i.target.value)})]}),e.jsxs("label",{className:"research-task-action-modal__field",children:[r("research.priorityLabel","Priority"),e.jsxs("select",{className:"select",value:O,onChange:i=>q(i.target.value),children:[e.jsx("option",{value:"low",children:r("research.priorityLow","Low")}),e.jsx("option",{value:"normal",children:r("research.priorityNormal","Normal")}),e.jsx("option",{value:"high",children:r("research.priorityHigh","High")}),e.jsx("option",{value:"urgent",children:r("research.priorityUrgent","Urgent")})]})]})]}):e.jsxs("label",{className:"research-task-action-modal__field",children:[r("research.targetTaskLabel","Target task"),e.jsx("input",{className:"input",list:"research-task-action-task-list",value:V,placeholder:B?r("research.loadingTasks","Loading tasks…"):r("research.enterTaskId","Enter task ID"),onChange:i=>L(i.target.value)}),e.jsx("datalist",{id:"research-task-action-task-list",children:G.map(i=>e.jsx("option",{value:i.id,children:i.title},i.id))})]}),e.jsxs("label",{className:"checkbox-label",children:[e.jsx("input",{type:"checkbox",checked:D,onChange:i=>M(i.target.checked)}),e.jsx("span",{children:r("research.attachExport","Attach markdown export artifact")})]})]}),e.jsxs("div",{className:"modal-actions",children:[e.jsx("button",{className:"btn",type:"button",onClick:f,children:r("actions.cancel","Cancel")}),e.jsx("button",{className:"btn btn-primary",type:"button",disabled:N||n==="enrich"&&!S,onClick:()=>{I(!0),x({taskId:n==="enrich"?S:void 0,title:n==="create"?h.trim():void 0,description:n==="create"?P.trim():void 0,priority:n==="create"?O:void 0,attachExport:D}).finally(()=>I(!1))},children:n==="create"?r("research.createTaskButton","Create Task"):r("research.enrichTaskButton","Enrich Task")})]})]})}):null}const Qe=["web-search","page-fetch","github","local-docs","llm-synthesis"],Ye={"web-search":"webSearch","page-fetch":"pageFetch",github:"github","local-docs":"localDocs","llm-synthesis":"llmSynthesis"};function Je(a){return{"web-search":a("research.providerWebSearch","Web Search"),"page-fetch":a("research.providerPageFetch","Page Fetch"),github:a("research.providerGitHub","GitHub"),"local-docs":a("research.providerLocalDocs","Local Docs"),"llm-synthesis":a("research.providerLlmSynthesis","LLM Synthesis")}}let oe=!1;function cs({projectId:a,addToast:n,onOpenSettings:l,readinessVersion:m=0}){const{t:s}=fe("app"),f=Je(s);c.useEffect(()=>(Y({view:"ResearchView",trigger:oe?"route-active":"remount",projectId:a,replayAttempted:!1}),oe=!1,()=>{oe=!0,Y({view:"ResearchView",trigger:"route-inactive",projectId:a,replayAttempted:!1})}),[a]);const{runs:x,selectedRun:r,selectedRunId:D,setSelectedRunId:M,availability:h,loading:A,error:P,searchQuery:w,setSearchQuery:O,createRun:q,cancelRun:V,retryRun:L,exportRun:G,createTaskFromRun:H,attachRunToTask:B,promoteFinding:k,statusCounts:N,refresh:I,uiError:_,runActionState:R}=Ke({projectId:a}),[C,S]=c.useState(""),[i,E]=c.useState(()=>ie(void 0)),[T,o]=c.useState([]),[d,p]=c.useState(!1),[y,g]=c.useState([]),[j,$]=c.useState(null),[U,K]=c.useState(null),[J,ve]=c.useState(""),Z=h.supportedProviders??Qe,ee=i.searchProvider,se=t=>t==="web-search"?!0:i.enabledSources[Ye[t]];c.useEffect(()=>{const t=Z.filter(u=>se(u));g(u=>{const b=u.filter(v=>t.includes(v));return b.length>0?b:t})},[i.enabledSources,Z]),c.useEffect(()=>{let t=!1;return Promise.all([qe(a),He().catch(()=>({providers:[]}))]).then(([u,b])=>{t||(E(ie(u)),o(b.providers.filter(v=>v.type==="api_key").map(v=>({id:v.id,authenticated:v.authenticated}))))}).catch(()=>{t||E(ie(void 0))}),()=>{t=!0}},[a,m]);const xe=c.useMemo(()=>r?r.status:s("research.noRunSelected","No run selected"),[r,s]),ye=c.useMemo(()=>r?r.status==="queued"||r.status==="retry_waiting"?"status-dot status-dot--pending":r.status==="running"?"status-dot status-dot--connecting":r.status==="completed"?"status-dot status-dot--online":r.status==="failed"||r.status==="cancelled"?"status-dot status-dot--error":"status-dot":"status-dot",[r]),re=h.supportedExportFormats??["markdown","json","html"],te=c.useMemo(()=>new Map(T.map(t=>[t.id,t.authenticated])),[T]),ae=c.useMemo(()=>{const t=new Set;return i.enabledSources.webSearch&&ee&&t.add(ee),i.enabledSources.llmSynthesis&&i.synthesisProvider&&t.add(i.synthesisProvider),[...t].filter(u=>te.has(u))},[i.enabledSources.llmSynthesis,i.enabledSources.webSearch,i.synthesisProvider,ee,te]).find(t=>te.get(t)!==!0),W=c.useMemo(()=>h.available?i.enabled?ae?{reason:s("research.missingApiKey","Missing API key for {{provider}}.",{provider:ae}),details:s("research.addCredentialsHint","Add provider credentials in Authentication settings."),settingsSection:"authentication"}:null:{reason:s("research.disabled","Research is disabled for this project."),details:s("research.enableResearchHint","Enable project research settings to create runs."),settingsSection:"research-project"}:{reason:h.reason??s("research.unavailable","Research is unavailable for this project."),details:h.setupInstructions,settingsSection:"research-project"},[h.available,h.reason,h.setupInstructions,i.enabled,ae,s]),z=async(t,u,b)=>{$(t);try{await u(),n?.(b,"success"),await I()}catch(v){n?.(v instanceof Error?v.message:s("research.actionFailed","Action failed"),"error")}finally{$(null)}},ne=async t=>{if(r){$(`export-${t}`);try{const u=await G(r.id,t),b=new Blob([u.content],{type:"text/plain;charset=utf-8"}),v=URL.createObjectURL(b),F=document.createElement("a");F.href=v,F.download=u.filename,document.body.appendChild(F),F.click(),F.remove(),URL.revokeObjectURL(v),n?.(s("research.exportedFile","Exported {{filename}}",{filename:u.filename}),"success")}catch(u){n?.(u instanceof Error?u.message:s("research.exportFailed","Export failed"),"error")}finally{$(null)}}},ge=async()=>{if(C.trim()){p(!0);try{const t=y.filter(b=>se(b));if(t.length===0){p(!1),n?.(s("research.noSourcesAvailable","No enabled research sources are available for this project."),"error");return}const u=await q({query:C.trim(),providers:t});M(u.run.id),S(""),n?.(s("research.runCreated","Research run created"),"success"),await I()}catch(t){n?.(t instanceof Error?t.message:s("research.createRunFailed","Failed to create run"),"error")}finally{p(!1)}}};return e.jsxs("section",{className:"research-view","aria-label":s("research.viewLabel","Research view"),children:[e.jsx(Ue,{icon:pe,title:s("research.title","Research"),actions:e.jsx("button",{className:"btn",type:"button",onClick:()=>void I(),children:s("actions.refresh","Refresh")})}),e.jsx("p",{className:"research-view__subtitle",children:s("research.subtitle","Cited search and synthesis runs: gather sources, fetch content, and synthesize findings.")}),W?e.jsxs("div",{className:"research-view__state research-view__state--error card","data-testid":"research-state-unavailable",children:[e.jsx("p",{children:W.reason}),W.details&&e.jsx("p",{children:W.details}),e.jsx("p",{children:s("research.currentDefaults","Current defaults: provider {{provider}}, max sources {{maxSources}}",{provider:i.searchProvider??s("research.notSet","(not set)"),maxSources:i.limits.maxSourcesPerRun})}),e.jsxs("div",{className:"research-view__actions",children:[e.jsx("button",{className:"btn",type:"button",onClick:()=>void I(),children:s("actions.refresh","Refresh")}),e.jsx("button",{className:"btn btn-primary",type:"button",onClick:()=>l?.(W.settingsSection),children:s("actions.openSettings","Open Settings")})]})]}):e.jsx(e.Fragment,{children:e.jsxs("div",{className:"research-view__layout",children:[e.jsx("aside",{className:"research-view__sidebar card",children:e.jsxs("div",{className:"research-view__sidebar-content",children:[e.jsxs("div",{className:"research-view__form",children:[e.jsxs("div",{className:"form-group",children:[e.jsx("label",{htmlFor:"research-query",children:s("research.queryLabel","Query")}),e.jsx("textarea",{id:"research-query",className:"input research-view__textarea",value:C,onChange:t=>S(t.target.value)})]}),e.jsxs("div",{className:"form-group",children:[e.jsx("label",{children:s("research.providersLabel","Providers")}),e.jsx("div",{className:"research-view__providers",children:Z.map(t=>{const u=se(t),b=t==="web-search";return e.jsxs("label",{className:"checkbox-label",children:[e.jsx("input",{type:"checkbox",checked:b||y.includes(t),disabled:b||!u,onChange:()=>{b||!u||g(v=>v.includes(t)?v.filter(F=>F!==t):[...v,t])}}),e.jsxs("span",{children:[f[t]??t,b?e.jsx("span",{className:"research-view__provider-lock",children:s("research.alwaysOn","Always on")}):null]})]},t)})})]}),e.jsxs("button",{className:"btn btn-primary",type:"button",disabled:!C.trim()||d,onClick:()=>void ge(),children:[d?e.jsx(Oe,{className:"animate-spin",size:14}):null,s("research.createRun","Create Run")]})]}),e.jsxs("div",{className:"research-view__history-header form-group",children:[e.jsx("label",{htmlFor:"research-run-search",children:s("actions.search","Search")}),e.jsxs("div",{className:"research-view__history-search-row",children:[e.jsx(pe,{size:14}),e.jsx("input",{id:"research-run-search",className:"input",placeholder:s("research.searchRunsPlaceholder","Search runs"),value:w,onChange:t=>O(t.target.value)})]})]}),e.jsx("div",{className:"research-view__history","data-testid":"research-state-running",children:x.map(t=>e.jsxs("button",{type:"button",className:`research-view__history-item card${D===t.id?" research-view__history-item--active":""}`,onClick:()=>M(t.id),children:[e.jsx("span",{className:"card-id",children:t.id}),e.jsx("span",{children:t.title})]},t.id))})]})}),e.jsxs("div",{className:"research-view__reader card",children:[A&&e.jsx("p",{"data-testid":"research-state-loading",children:e.jsx(Ve,{label:s("research.loadingRuns","Loading research runs…")})}),!A&&P&&e.jsx("p",{"data-testid":"research-state-error",children:P}),!A&&!P&&x.length===0&&e.jsx("p",{"data-testid":"research-state-empty",children:s("research.noRunsYet","No research runs yet")}),e.jsxs("div",{className:"research-view__reader-content",children:[r&&e.jsxs("div",{className:"research-view__run-detail",children:[e.jsxs("div",{className:"research-view__status-row",children:[e.jsx("span",{className:ye}),e.jsx("strong",{children:xe})]}),e.jsx("h3",{className:"research-view__run-title",children:r.title}),e.jsx("p",{className:"research-view__run-query",children:r.query}),e.jsx("p",{className:"research-view__run-summary","data-testid":"research-state-results",children:r.results?.summary??s("research.noSummaryYet","No summary yet.")}),e.jsxs("div",{className:"research-view__actions",children:[e.jsx("button",{className:"btn",type:"button",title:R.cancelable?void 0:R.blockingReason,disabled:j==="cancel"||j==="retry"||!R.cancelable,onClick:()=>void z("cancel",()=>V(r.id),s("research.runCancelled","Run cancelled")),children:s("actions.cancel","Cancel")}),e.jsx("button",{className:"btn",type:"button",title:R.retryable?void 0:R.blockingReason,disabled:j==="cancel"||j==="retry"||!R.retryable,onClick:()=>void z("retry",()=>L(r.id),s("research.runRetried","Run retried")),children:s("actions.retry","Retry")}),re.includes("markdown")&&e.jsx("button",{className:"btn",type:"button",disabled:j==="export-markdown",onClick:()=>void ne("markdown"),children:s("research.exportMd","Export MD")}),re.includes("json")&&e.jsx("button",{className:"btn",type:"button",disabled:j==="export-json",onClick:()=>void ne("json"),children:s("research.exportJson","Export JSON")}),re.includes("html")&&e.jsx("button",{className:"btn",type:"button",disabled:j==="export-html",onClick:()=>void ne("html"),children:s("research.exportHtml","Export HTML")})]}),r.error&&e.jsx("p",{className:"research-view__error",children:r.error}),_&&e.jsxs("div",{className:"form-error",role:"alert",children:[e.jsx("p",{children:_.message}),_.setupHint&&e.jsx("p",{children:_.setupHint}),_.code==="MISSING_CREDENTIALS"&&e.jsx("button",{className:"btn btn-sm",type:"button",onClick:()=>l?.("authentication"),children:s("research.openAuthSettings","Open Authentication Settings")}),_.code==="FEATURE_DISABLED"&&e.jsx("button",{className:"btn btn-sm",type:"button",onClick:()=>l?.("research-project"),children:s("research.openResearchSettings","Open Research Settings")})]}),R.blockingReason&&e.jsx("p",{className:"research-view__run-query",children:R.blockingReason}),Array.isArray(r.results?.findings)&&r.results.findings.length>0&&e.jsx("div",{className:"research-view__findings",children:r.results.findings.map(t=>{const u=be(t);return e.jsxs("article",{className:"research-view__finding card",children:[e.jsx("h4",{children:t.heading}),e.jsx("p",{children:t.content}),e.jsxs("div",{className:"research-view__actions research-view__finding-actions",children:[e.jsx("button",{className:"btn btn-primary btn-sm",type:"button",onClick:()=>K({mode:"create",findingId:u}),children:s("research.createTask","Create Task")}),e.jsx("button",{className:"btn btn-sm",type:"button",onClick:()=>K({mode:"enrich",findingId:u}),children:s("research.enrichTask","Enrich Task")}),e.jsx("input",{className:"input","aria-label":s("research.destinationSlice","Destination slice ID"),value:J,onChange:b=>ve(b.target.value),placeholder:s("research.destinationSlice","Destination slice ID")}),e.jsx("button",{className:"btn btn-sm",type:"button",disabled:r.status!=="completed"||!J.trim()||j===`promote-${u}`,onClick:()=>void z(`promote-${u}`,()=>k(r.id,{findingId:u,sliceId:J.trim()}),s("research.findingPromoted","Finding promoted to roadmap")),children:s("research.promoteFinding","Promote to roadmap")})]})]},u)})}),Array.isArray(r.results?.citations)&&r.results.citations.length>0&&e.jsx("ul",{className:"research-view__citations",children:r.results.citations.map(t=>e.jsx("li",{children:e.jsx("a",{href:t,target:"_blank",rel:"noreferrer",children:t})},t))}),r.events.length>0&&e.jsxs("details",{children:[e.jsx("summary",{children:s("research.runHistory","Run history")}),e.jsx("ul",{className:"research-view__events",children:r.events.map(t=>e.jsx("li",{children:t.message},t.id))})]})]}),!r&&x.length>0&&e.jsx("p",{children:s("research.selectRunToViewDetails","Select a run to view details.")}),e.jsxs("div",{className:"research-view__stats",children:[e.jsxs("div",{className:"research-view__stat-card",children:[e.jsx("div",{className:"research-view__stat-label",children:s("research.statRunning","Running")}),e.jsx("div",{className:"research-view__stat-value",children:N.running})]}),e.jsxs("div",{className:"research-view__stat-card",children:[e.jsx("div",{className:"research-view__stat-label",children:s("research.statCompleted","Completed")}),e.jsx("div",{className:"research-view__stat-value",children:N.completed})]}),e.jsxs("div",{className:"research-view__stat-card",children:[e.jsx("div",{className:"research-view__stat-label",children:s("research.statFailed","Failed")}),e.jsx("div",{className:"research-view__stat-value",children:N.failed})]})]})]})]})]})}),r&&U&&(()=>{const t=r.results?.findings?.findIndex(b=>be(b)===U.findingId)??-1,u=t>=0?r.results.findings[t]:null;return u?e.jsx(Xe,{open:!0,mode:U.mode,run:r,finding:{id:U.findingId,heading:u.heading,content:u.content},projectId:a,onClose:()=>K(null),onConfirm:async({taskId:b,title:v,description:F,priority:Re,attachExport:de})=>{U.mode==="create"?await z("create-task",()=>H(r.id,v,U.findingId,F,Re,de),s("research.taskCreatedFromResearch","Task created from research")):b&&await z("attach-task",()=>B(r.id,b,U.findingId,de),s("research.taskEnrichedFromResearch","Task enriched from research")),K(null)}}):null})()]})}export{cs as ResearchView};
1
+ import{r as c,j as e}from"./vendor-react-SZ_qB27O.js";import{ap as Q,aq as ue,ar as he,cK as me,cZ as Se,av as ce,c_ as _e,bh as je,c$ as Y,aW as we,d0 as ke,d1 as Ne,d2 as Ce,d3 as Ee,d4 as Ae,d5 as Te,d6 as Pe,cO as Le,d7 as Ie,d8 as Fe,d9 as Me,da as De,aX as qe,ag as He,V as Oe,aI as pe,L as Ue,aJ as Ve}from"./index-CtYRoouR.js";import{u as fe}from"./vendor-i18n-Duky4gdQ.js";import"./vendor-codemirror-CcrtqoCy.js";import"./vendor-reactflow-BlIeoTu4.js";import"./vendor-xterm-BNq00GSj.js";const $e="builtin",X={pageFetch:!0,github:!1,localDocs:!0,llmSynthesis:!0};function ie(a){const n=a?.researchGlobalDefaults,l=a?.researchSettings;return{enabled:l?.enabled??a?.researchEnabled??a?.researchGlobalEnabled??!0,searchProvider:l?.searchProvider??n?.searchProvider??a?.researchGlobalWebSearchProvider??$e,synthesisProvider:l?.synthesisProvider??n?.synthesisProvider,synthesisModelId:l?.synthesisModelId??n?.synthesisModelId,enabledSources:{webSearch:!0,pageFetch:l?.enabledSources?.pageFetch??n?.enabledSources?.pageFetch??X.pageFetch,github:l?.enabledSources?.github??n?.enabledSources?.github??X.github,localDocs:l?.enabledSources?.localDocs??n?.enabledSources?.localDocs??X.localDocs,llmSynthesis:l?.enabledSources?.llmSynthesis??n?.enabledSources?.llmSynthesis??X.llmSynthesis},limits:{maxConcurrentRuns:l?.limits?.maxConcurrentRuns??a?.researchMaxConcurrentRuns??a?.researchGlobalMaxConcurrentRuns??3,maxSourcesPerRun:l?.limits?.maxSourcesPerRun??n?.maxSourcesPerRun??a?.researchMaxSourcesPerRun??a?.researchGlobalMaxSourcesPerRun??20,maxDurationMs:l?.limits?.maxDurationMs??a?.researchDefaultTimeout??a?.researchGlobalDefaultTimeout??3e5,requestTimeoutMs:l?.limits?.requestTimeoutMs??a?.researchGlobalFetchTimeoutMs??3e4},defaultExportFormat:n?.defaultExportFormat??"markdown"}}function be(a){const n=typeof a.id=="string"?a.id.trim():"";if(n)return n;const l=f=>f.trim().replace(/\s+/g," ").toLowerCase(),m=[l(a.heading??""),l(a.content??""),...[...a.sources??[]].map(l).filter(Boolean).sort()].join(`
2
+ `);let s=2166136261;for(let f=0;f<m.length;f+=1)s^=m.charCodeAt(f),s=Math.imul(s,16777619);return`finding-${(s>>>0).toString(16).padStart(8,"0")}`}const Ge=300,Be=4e3,We=["queued","running","cancelling","retry_waiting"];function le(a,n){if(a instanceof Le){const l=a;return{message:a.message,status:a.status,code:l.researchCode??"INTERNAL_ERROR",setupHint:l.setupHint,retryable:l.retryable}}return a instanceof Error?{message:a.message,code:"INTERNAL_ERROR"}:{message:n,code:"INTERNAL_ERROR"}}function ze(a){if(!a)return{cancelable:!1,retryable:!1,isTransitioning:!1,blockingReason:"No run selected"};const n=We.includes(a.status),l=a.status==="queued"||a.status==="running",m=a.lifecycle?.retryable,s=a.status==="failed"||a.status==="timed_out",f=!!(s&&m);let x;return!l&&n?x="Run is already transitioning":!l&&a.status==="completed"?x="Completed runs cannot be cancelled":!l&&a.status==="cancelled"?x="Run is already cancelled":!l&&a.status==="retry_exhausted"?x="Retry attempts exhausted":!l&&a.status==="failed"?x="Failed runs cannot be cancelled":!l&&a.status==="timed_out"&&(x="Timed out runs cannot be cancelled"),!f&&s&&m===!1&&(x=a.lifecycle?.errorCode==="RETRY_EXHAUSTED"?"Retry attempts exhausted":"Run is not retryable"),{cancelable:l,retryable:f,isTransitioning:n,blockingReason:x}}function Ke(a){const n=a?.projectId,l=n??"",m=`${he.RESEARCH_RUNS_PREFIX}${l}`,s=`${he.RESEARCH_SELECTED_ID_PREFIX}${l}`,f=Q(m,{maxAgeMs:ue}),x=Q(s,{maxAgeMs:me}),r=c.useRef(Array.isArray(f)&&f.length>0),[D,M]=c.useState(()=>Array.isArray(f)?f:[]),[h,A]=c.useState(x??null),[P,w]=c.useState(null),[U,q]=c.useState({available:!0}),[V,L]=c.useState(!(Array.isArray(f)&&f.length>0)),[G,H]=c.useState(null),[B,k]=c.useState(null),[N,I]=c.useState(""),_=c.useRef(0),R=c.useRef(0),C=c.useRef(n);c.useEffect(()=>{C.current!==n&&(C.current=n,R.current++);const o=Q(m,{maxAgeMs:ue}),d=Q(s,{maxAgeMs:me}),p=Array.isArray(o)&&o.length>0;M(Array.isArray(o)?o:[]),A(d??null),w(null),L(!p),r.current=p},[n,m,s]);const S=c.useCallback(async(o=N)=>{const d=++_.current,p=n;r.current||L(!0),H(null),k(null);try{const y=await Se({q:o||void 0,limit:100},p);if(d!==_.current||p!==n)return;M(y.runs),ce(m,y.runs,{maxBytes:5e5}),r.current=!0,q(y.availability),h&&!y.runs.some(g=>g.id===h)&&(A(null),ce(s,null,{maxBytes:5e5}),w(null))}catch(y){if(d!==_.current||p!==n)return;const g=le(y,"Failed to load research runs");H(g.message),k(g)}finally{d===_.current&&L(!1)}},[n,m,N,s,h]),i=c.useCallback(async o=>{const d=await _e(o,n);return w(d.run),q(d.availability),d.run},[n]);c.useEffect(()=>{r.current||L(!0);const o=window.setTimeout(()=>{S(N)},Ge);return()=>window.clearTimeout(o)},[S,N]),c.useEffect(()=>{if(!h){w(null);return}i(h)},[i,h]),c.useEffect(()=>{const o=R.current,d=()=>R.current!==o,p=n?`?projectId=${encodeURIComponent(n)}`:"";let y=!0;const g=()=>{!y||d()||(S(),h&&i(h))},j=`/api/events${p}`,$=je(j,{events:{"research:run:created":g,"research:run:updated":g,"research:run:completed":g,"research:run:failed":g,"research:run:cancelled":g},onReconnect:()=>{Y({view:"useResearch",trigger:"sse-reconnect",projectId:n,replayAttempted:!1,sseChannel:j}),g()}});return Y({view:"useResearch",trigger:"sse-open",projectId:n,replayAttempted:!1,sseChannel:j}),()=>{y=!1,$()}},[n,S,h,i]);const E=c.useCallback(()=>{S(),h&&i(h)},[S,h,i]);we(E,Be);const T=c.useCallback(o=>{A(o),ce(s,o,{maxBytes:5e5})},[s]);return{runs:D,selectedRun:P,selectedRunId:h,setSelectedRunId:T,availability:U,loading:V,error:G,searchQuery:N,setSearchQuery:I,refresh:S,createRun:o=>Pe(o,n),cancelRun:async o=>{try{k(null);const d=await Te(o,n);return h===o&&w(d.run),await S(),d}catch(d){const p=le(d,"Failed to cancel run");throw k(p),p}},retryRun:async o=>{try{k(null);const d=await Ae(o,n);return h===o&&w(d.run),await S(),d}catch(d){const p=le(d,"Failed to retry run");throw k(p),p}},exportRun:(o,d)=>Ee(o,d,n),createTaskFromRun:(o,d,p,y,g,j)=>Ce(o,{title:d,findingId:p,description:y,priority:g,attachExport:j},n),attachRunToTask:(o,d,p,y)=>Ne(o,{taskId:d,findingId:p,attachExport:y},n),promoteFinding:(o,d)=>ke(o,d,n),uiError:B,runActionState:ze(P),statusCounts:D.reduce((o,d)=>(o[d.status]+=1,o),{queued:0,running:0,cancelling:0,retry_waiting:0,completed:0,failed:0,cancelled:0,timed_out:0,retry_exhausted:0})}}function Qe({open:a,mode:n,run:l,finding:m,projectId:s,onClose:f,onConfirm:x}){const{t:r}=fe("app");Ie(a);const[D,M]=c.useState(!1),[h,A]=c.useState(""),[P,w]=c.useState(""),[U,q]=c.useState("normal"),[V,L]=c.useState(""),[G,H]=c.useState([]),[B,k]=c.useState(!1),[N,I]=c.useState(!1),{boardWorkflows:_}=Fe({projectId:s}),R=c.useMemo(()=>{const i=new Map;for(const E of _?.workflows??[])for(const T of E.columns)i.has(T.id)||i.set(T.id,T.flags);return E=>Me(i.get(E),E)},[_]),C=c.useMemo(()=>{const i=(m.content??"").split(/(?<=[.!?])\s+/)[0]??"";return`${m.heading||r("research.defaultFindingHeading","Research finding")} — ${i}`.trim()},[m.content,m.heading,r]);c.useEffect(()=>{a&&(M(!1),A(`Research: ${m.heading||l.title}`),w(C),q("normal"),L(""))},[a,n,m.heading,C,l.title]),c.useEffect(()=>{if(!a||n!=="enrich")return;let i=!1;return H([]),k(!0),De(50,0,s).then(E=>{i||H(E.filter(T=>!R(T.column)))}).finally(()=>{i||k(!1)}),()=>{i=!0}},[a,n,s,R]);const S=V.trim();return a?e.jsx("div",{className:"modal-overlay open",role:"presentation",onClick:f,children:e.jsxs("div",{className:"modal modal-lg research-task-action-modal",role:"dialog","aria-modal":"true",onClick:i=>i.stopPropagation(),children:[e.jsxs("div",{className:"modal-header",children:[e.jsx("h3",{children:n==="create"?r("research.createTaskTitle","Create task from finding"):r("research.enrichTaskTitle","Enrich existing task")}),e.jsx("button",{className:"modal-close",type:"button","aria-label":r("actions.close","Close"),onClick:f,children:"×"})]}),e.jsxs("div",{className:"research-task-action-modal__body",children:[e.jsxs("div",{className:"card research-task-action-modal__preview",children:[e.jsxs("p",{children:[e.jsxs("strong",{children:[r("research.runLabel","Run:")," "]})," ",l.id]}),e.jsxs("p",{children:[e.jsxs("strong",{children:[r("research.findingLabel","Finding:")," "]})," ",m.id,m.heading?` — ${m.heading}`:""]}),e.jsx("p",{children:C||r("research.noPreview","No preview available.")})]}),n==="create"?e.jsxs(e.Fragment,{children:[e.jsxs("label",{className:"research-task-action-modal__field",children:[r("research.titleLabel","Title"),e.jsx("input",{className:"input",value:h,onChange:i=>A(i.target.value)})]}),e.jsxs("label",{className:"research-task-action-modal__field",children:[r("research.descriptionLabel","Description"),e.jsx("textarea",{className:"input research-task-action-modal__textarea",value:P,onChange:i=>w(i.target.value)})]}),e.jsxs("label",{className:"research-task-action-modal__field",children:[r("research.priorityLabel","Priority"),e.jsxs("select",{className:"select",value:U,onChange:i=>q(i.target.value),children:[e.jsx("option",{value:"low",children:r("research.priorityLow","Low")}),e.jsx("option",{value:"normal",children:r("research.priorityNormal","Normal")}),e.jsx("option",{value:"high",children:r("research.priorityHigh","High")}),e.jsx("option",{value:"urgent",children:r("research.priorityUrgent","Urgent")})]})]})]}):e.jsxs("label",{className:"research-task-action-modal__field",children:[r("research.targetTaskLabel","Target task"),e.jsx("input",{className:"input",list:"research-task-action-task-list",value:V,placeholder:B?r("research.loadingTasks","Loading tasks…"):r("research.enterTaskId","Enter task ID"),onChange:i=>L(i.target.value)}),e.jsx("datalist",{id:"research-task-action-task-list",children:G.map(i=>e.jsx("option",{value:i.id,children:i.title},i.id))})]}),e.jsxs("label",{className:"checkbox-label",children:[e.jsx("input",{type:"checkbox",checked:D,onChange:i=>M(i.target.checked)}),e.jsx("span",{children:r("research.attachExport","Attach markdown export artifact")})]})]}),e.jsxs("div",{className:"modal-actions",children:[e.jsx("button",{className:"btn",type:"button",onClick:f,children:r("actions.cancel","Cancel")}),e.jsx("button",{className:"btn btn-primary",type:"button",disabled:N||n==="enrich"&&!S,onClick:()=>{I(!0),x({taskId:n==="enrich"?S:void 0,title:n==="create"?h.trim():void 0,description:n==="create"?P.trim():void 0,priority:n==="create"?U:void 0,attachExport:D}).finally(()=>I(!1))},children:n==="create"?r("research.createTaskButton","Create Task"):r("research.enrichTaskButton","Enrich Task")})]})]})}):null}const Xe=["web-search","page-fetch","github","local-docs","llm-synthesis"],Ye={"web-search":"webSearch","page-fetch":"pageFetch",github:"github","local-docs":"localDocs","llm-synthesis":"llmSynthesis"};function Je(a){return{"web-search":a("research.providerWebSearch","Web Search"),"page-fetch":a("research.providerPageFetch","Page Fetch"),github:a("research.providerGitHub","GitHub"),"local-docs":a("research.providerLocalDocs","Local Docs"),"llm-synthesis":a("research.providerLlmSynthesis","LLM Synthesis")}}let oe=!1;function cs({projectId:a,addToast:n,onOpenSettings:l,readinessVersion:m=0}){const{t:s}=fe("app"),f=Je(s);c.useEffect(()=>(Y({view:"ResearchView",trigger:oe?"route-active":"remount",projectId:a,replayAttempted:!1}),oe=!1,()=>{oe=!0,Y({view:"ResearchView",trigger:"route-inactive",projectId:a,replayAttempted:!1})}),[a]);const{runs:x,selectedRun:r,selectedRunId:D,setSelectedRunId:M,availability:h,loading:A,error:P,searchQuery:w,setSearchQuery:U,createRun:q,cancelRun:V,retryRun:L,exportRun:G,createTaskFromRun:H,attachRunToTask:B,promoteFinding:k,statusCounts:N,refresh:I,uiError:_,runActionState:R}=Ke({projectId:a}),[C,S]=c.useState(""),[i,E]=c.useState(()=>ie(void 0)),[T,o]=c.useState([]),[d,p]=c.useState(!1),[y,g]=c.useState([]),[j,$]=c.useState(null),[O,K]=c.useState(null),[J,ve]=c.useState(""),Z=h.supportedProviders??Xe,ee=i.searchProvider,se=t=>t==="web-search"?!0:i.enabledSources[Ye[t]];c.useEffect(()=>{const t=Z.filter(u=>se(u));g(u=>{const b=u.filter(v=>t.includes(v));return b.length>0?b:t})},[i.enabledSources,Z]),c.useEffect(()=>{let t=!1;return Promise.all([qe(a),He().catch(()=>({providers:[]}))]).then(([u,b])=>{t||(E(ie(u)),o(b.providers.filter(v=>v.type==="api_key").map(v=>({id:v.id,authenticated:v.authenticated}))))}).catch(()=>{t||E(ie(void 0))}),()=>{t=!0}},[a,m]);const xe=c.useMemo(()=>r?r.status:s("research.noRunSelected","No run selected"),[r,s]),ye=c.useMemo(()=>r?r.status==="queued"||r.status==="retry_waiting"?"status-dot status-dot--pending":r.status==="running"?"status-dot status-dot--connecting":r.status==="completed"?"status-dot status-dot--online":r.status==="failed"||r.status==="cancelled"?"status-dot status-dot--error":"status-dot":"status-dot",[r]),re=h.supportedExportFormats??["markdown","json","html"],te=c.useMemo(()=>new Map(T.map(t=>[t.id,t.authenticated])),[T]),ae=c.useMemo(()=>{const t=new Set;return i.enabledSources.webSearch&&ee&&t.add(ee),i.enabledSources.llmSynthesis&&i.synthesisProvider&&t.add(i.synthesisProvider),[...t].filter(u=>te.has(u))},[i.enabledSources.llmSynthesis,i.enabledSources.webSearch,i.synthesisProvider,ee,te]).find(t=>te.get(t)!==!0),W=c.useMemo(()=>h.available?i.enabled?ae?{reason:s("research.missingApiKey","Missing API key for {{provider}}.",{provider:ae}),details:s("research.addCredentialsHint","Add provider credentials in Authentication settings."),settingsSection:"authentication"}:null:{reason:s("research.disabled","Research is disabled for this project."),details:s("research.enableResearchHint","Enable project research settings to create runs."),settingsSection:"research-project"}:{reason:h.reason??s("research.unavailable","Research is unavailable for this project."),details:h.setupInstructions,settingsSection:"research-project"},[h.available,h.reason,h.setupInstructions,i.enabled,ae,s]),z=async(t,u,b)=>{$(t);try{await u(),n?.(b,"success"),await I()}catch(v){n?.(v instanceof Error?v.message:s("research.actionFailed","Action failed"),"error")}finally{$(null)}},ne=async t=>{if(r){$(`export-${t}`);try{const u=await G(r.id,t),b=new Blob([u.content],{type:"text/plain;charset=utf-8"}),v=URL.createObjectURL(b),F=document.createElement("a");F.href=v,F.download=u.filename,document.body.appendChild(F),F.click(),F.remove(),URL.revokeObjectURL(v),n?.(s("research.exportedFile","Exported {{filename}}",{filename:u.filename}),"success")}catch(u){n?.(u instanceof Error?u.message:s("research.exportFailed","Export failed"),"error")}finally{$(null)}}},ge=async()=>{if(C.trim()){p(!0);try{const t=y.filter(b=>se(b));if(t.length===0){p(!1),n?.(s("research.noSourcesAvailable","No enabled research sources are available for this project."),"error");return}const u=await q({query:C.trim(),providers:t});M(u.run.id),S(""),n?.(s("research.runCreated","Research run created"),"success"),await I()}catch(t){n?.(t instanceof Error?t.message:s("research.createRunFailed","Failed to create run"),"error")}finally{p(!1)}}};return e.jsxs("section",{className:"research-view","aria-label":s("research.viewLabel","Research view"),children:[e.jsx(Oe,{icon:pe,title:s("research.title","Research"),actions:e.jsx("button",{className:"btn",type:"button",onClick:()=>void I(),children:s("actions.refresh","Refresh")})}),e.jsx("p",{className:"research-view__subtitle",children:s("research.subtitle","Cited search and synthesis runs: gather sources, fetch content, and synthesize findings.")}),W?e.jsxs("div",{className:"research-view__state research-view__state--error card","data-testid":"research-state-unavailable",children:[e.jsx("p",{children:W.reason}),W.details&&e.jsx("p",{children:W.details}),e.jsx("p",{children:s("research.currentDefaults","Current defaults: provider {{provider}}, max sources {{maxSources}}",{provider:i.searchProvider??s("research.notSet","(not set)"),maxSources:i.limits.maxSourcesPerRun})}),e.jsxs("div",{className:"research-view__actions",children:[e.jsx("button",{className:"btn",type:"button",onClick:()=>void I(),children:s("actions.refresh","Refresh")}),e.jsx("button",{className:"btn btn-primary",type:"button",onClick:()=>l?.(W.settingsSection),children:s("actions.openSettings","Open Settings")})]})]}):e.jsx(e.Fragment,{children:e.jsxs("div",{className:"research-view__layout",children:[e.jsx("aside",{className:"research-view__sidebar card",children:e.jsxs("div",{className:"research-view__sidebar-content",children:[e.jsxs("div",{className:"research-view__form",children:[e.jsxs("div",{className:"form-group",children:[e.jsx("label",{htmlFor:"research-query",children:s("research.queryLabel","Query")}),e.jsx("textarea",{id:"research-query",className:"input research-view__textarea",value:C,onChange:t=>S(t.target.value)})]}),e.jsxs("div",{className:"form-group",children:[e.jsx("label",{children:s("research.providersLabel","Providers")}),e.jsx("div",{className:"research-view__providers",children:Z.map(t=>{const u=se(t),b=t==="web-search";return e.jsxs("label",{className:"checkbox-label",children:[e.jsx("input",{type:"checkbox",checked:b||y.includes(t),disabled:b||!u,onChange:()=>{b||!u||g(v=>v.includes(t)?v.filter(F=>F!==t):[...v,t])}}),e.jsxs("span",{children:[f[t]??t,b?e.jsx("span",{className:"research-view__provider-lock",children:s("research.alwaysOn","Always on")}):null]})]},t)})})]}),e.jsxs("button",{className:"btn btn-primary",type:"button",disabled:!C.trim()||d,onClick:()=>void ge(),children:[d?e.jsx(Ue,{className:"animate-spin",size:14}):null,s("research.createRun","Create Run")]})]}),e.jsxs("div",{className:"research-view__history-header form-group",children:[e.jsx("label",{htmlFor:"research-run-search",children:s("actions.search","Search")}),e.jsxs("div",{className:"research-view__history-search-row",children:[e.jsx(pe,{size:14}),e.jsx("input",{id:"research-run-search",className:"input",placeholder:s("research.searchRunsPlaceholder","Search runs"),value:w,onChange:t=>U(t.target.value)})]})]}),e.jsx("div",{className:"research-view__history","data-testid":"research-state-running",children:x.map(t=>e.jsxs("button",{type:"button",className:`research-view__history-item card${D===t.id?" research-view__history-item--active":""}`,onClick:()=>M(t.id),children:[e.jsx("span",{className:"card-id",children:t.id}),e.jsx("span",{children:t.title})]},t.id))})]})}),e.jsxs("div",{className:"research-view__reader card",children:[A&&e.jsx("p",{"data-testid":"research-state-loading",children:e.jsx(Ve,{label:s("research.loadingRuns","Loading research runs…")})}),!A&&P&&e.jsx("p",{"data-testid":"research-state-error",children:P}),!A&&!P&&x.length===0&&e.jsx("p",{"data-testid":"research-state-empty",children:s("research.noRunsYet","No research runs yet")}),e.jsxs("div",{className:"research-view__reader-content",children:[r&&e.jsxs("div",{className:"research-view__run-detail",children:[e.jsxs("div",{className:"research-view__status-row",children:[e.jsx("span",{className:ye}),e.jsx("strong",{children:xe})]}),e.jsx("h3",{className:"research-view__run-title",children:r.title}),e.jsx("p",{className:"research-view__run-query",children:r.query}),e.jsx("p",{className:"research-view__run-summary","data-testid":"research-state-results",children:r.results?.summary??s("research.noSummaryYet","No summary yet.")}),e.jsxs("div",{className:"research-view__actions",children:[e.jsx("button",{className:"btn",type:"button",title:R.cancelable?void 0:R.blockingReason,disabled:j==="cancel"||j==="retry"||!R.cancelable,onClick:()=>void z("cancel",()=>V(r.id),s("research.runCancelled","Run cancelled")),children:s("actions.cancel","Cancel")}),e.jsx("button",{className:"btn",type:"button",title:R.retryable?void 0:R.blockingReason,disabled:j==="cancel"||j==="retry"||!R.retryable,onClick:()=>void z("retry",()=>L(r.id),s("research.runRetried","Run retried")),children:s("actions.retry","Retry")}),re.includes("markdown")&&e.jsx("button",{className:"btn",type:"button",disabled:j==="export-markdown",onClick:()=>void ne("markdown"),children:s("research.exportMd","Export MD")}),re.includes("json")&&e.jsx("button",{className:"btn",type:"button",disabled:j==="export-json",onClick:()=>void ne("json"),children:s("research.exportJson","Export JSON")}),re.includes("html")&&e.jsx("button",{className:"btn",type:"button",disabled:j==="export-html",onClick:()=>void ne("html"),children:s("research.exportHtml","Export HTML")})]}),r.error&&e.jsx("p",{className:"research-view__error",children:r.error}),_&&e.jsxs("div",{className:"form-error",role:"alert",children:[e.jsx("p",{children:_.message}),_.setupHint&&e.jsx("p",{children:_.setupHint}),_.code==="MISSING_CREDENTIALS"&&e.jsx("button",{className:"btn btn-sm",type:"button",onClick:()=>l?.("authentication"),children:s("research.openAuthSettings","Open Authentication Settings")}),_.code==="FEATURE_DISABLED"&&e.jsx("button",{className:"btn btn-sm",type:"button",onClick:()=>l?.("research-project"),children:s("research.openResearchSettings","Open Research Settings")})]}),R.blockingReason&&e.jsx("p",{className:"research-view__run-query",children:R.blockingReason}),Array.isArray(r.results?.findings)&&r.results.findings.length>0&&e.jsx("div",{className:"research-view__findings",children:r.results.findings.map(t=>{const u=be(t);return e.jsxs("article",{className:"research-view__finding card",children:[e.jsx("h4",{children:t.heading}),e.jsx("p",{children:t.content}),e.jsxs("div",{className:"research-view__actions research-view__finding-actions",children:[e.jsx("button",{className:"btn btn-primary btn-sm",type:"button",onClick:()=>K({mode:"create",findingId:u}),children:s("research.createTask","Create Task")}),e.jsx("button",{className:"btn btn-sm",type:"button",onClick:()=>K({mode:"enrich",findingId:u}),children:s("research.enrichTask","Enrich Task")}),e.jsx("input",{className:"input","aria-label":s("research.destinationSlice","Destination slice ID"),value:J,onChange:b=>ve(b.target.value),placeholder:s("research.destinationSlice","Destination slice ID")}),e.jsx("button",{className:"btn btn-sm",type:"button",disabled:r.status!=="completed"||!J.trim()||j===`promote-${u}`,onClick:()=>void z(`promote-${u}`,()=>k(r.id,{findingId:u,sliceId:J.trim()}),s("research.findingPromoted","Finding promoted to roadmap")),children:s("research.promoteFinding","Promote to roadmap")})]})]},u)})}),Array.isArray(r.results?.citations)&&r.results.citations.length>0&&e.jsx("ul",{className:"research-view__citations",children:r.results.citations.map(t=>e.jsx("li",{children:e.jsx("a",{href:t,target:"_blank",rel:"noreferrer",children:t})},t))}),r.events.length>0&&e.jsxs("details",{children:[e.jsx("summary",{children:s("research.runHistory","Run history")}),e.jsx("ul",{className:"research-view__events",children:r.events.map(t=>e.jsx("li",{children:t.message},t.id))})]})]}),!r&&x.length>0&&e.jsx("p",{children:s("research.selectRunToViewDetails","Select a run to view details.")}),e.jsxs("div",{className:"research-view__stats",children:[e.jsxs("div",{className:"research-view__stat-card",children:[e.jsx("div",{className:"research-view__stat-label",children:s("research.statRunning","Running")}),e.jsx("div",{className:"research-view__stat-value",children:N.running})]}),e.jsxs("div",{className:"research-view__stat-card",children:[e.jsx("div",{className:"research-view__stat-label",children:s("research.statCompleted","Completed")}),e.jsx("div",{className:"research-view__stat-value",children:N.completed})]}),e.jsxs("div",{className:"research-view__stat-card",children:[e.jsx("div",{className:"research-view__stat-label",children:s("research.statFailed","Failed")}),e.jsx("div",{className:"research-view__stat-value",children:N.failed})]})]})]})]})]})}),r&&O&&(()=>{const t=r.results?.findings?.findIndex(b=>be(b)===O.findingId)??-1,u=t>=0?r.results.findings[t]:null;return u?e.jsx(Qe,{open:!0,mode:O.mode,run:r,finding:{id:O.findingId,heading:u.heading,content:u.content},projectId:a,onClose:()=>K(null),onConfirm:async({taskId:b,title:v,description:F,priority:Re,attachExport:de})=>{O.mode==="create"?await z("create-task",()=>H(r.id,v,O.findingId,F,Re,de),s("research.taskCreatedFromResearch","Task created from research")):b&&await z("attach-task",()=>B(r.id,b,O.findingId,de),s("research.taskEnrichedFromResearch","Task enriched from research")),K(null)}}):null})()]})}export{cs as ResearchView};
@@ -1 +1 @@
1
- import{r as t,j as e}from"./vendor-react-SZ_qB27O.js";import{w as A,V as we,o as ke,R as ce,P as Re,E as ne,p as le,q as Le,u as Te,v as Ae,x as Me,C as qe,g as De,y as Ve}from"./index-DWRJyaa3.js";import{u as Ke}from"./vendor-i18n-Duky4gdQ.js";import"./vendor-codemirror-CcrtqoCy.js";import"./vendor-reactflow-BlIeoTu4.js";import"./vendor-xterm-BNq00GSj.js";const Oe="__sync_passphrase__",Y={key:"",value:"",description:"",scope:"project",accessPolicy:"prompt",envExportable:!1,envExportKey:""},d={className:"secrets-action-icon","aria-hidden":!0,style:{width:"1em",height:"1em"}},Fe={...d,className:"secrets-action-icon spin"},Ye=({addToast:p,projectId:l})=>{const{t:a}=Ke("app"),[z,G]=t.useState([]),[oe,U]=t.useState(),[Q,W]=t.useState(!0),[X,M]=t.useState(null),[ie,q]=t.useState(),[Z,b]=t.useState(null),[h,D]=t.useState(null),[de,x]=t.useState(!1),[ue,C]=t.useState(null),[c,i]=t.useState(Y),[V,E]=t.useState(!1),[ee,f]=t.useState({}),[pe,K]=t.useState(null),[m,se]=t.useState(!1),[he,ae]=t.useState(),[me,O]=t.useState(!1),[w,F]=t.useState(""),[_,B]=t.useState(""),[ye,$]=t.useState(!1),[H,xe]=t.useState(!1),v=t.useRef(new Map),I=t.useRef(new Map),j=t.useRef(0),k=t.useRef(0),o=t.useRef(l);o.current!==l&&(o.current=l,j.current+=1,k.current+=1);const y=t.useCallback(s=>A(s,l),[l]),u=t.useCallback(async(s,r)=>{const n=await fetch(s,{...r,headers:{"Content-Type":"application/json",...r?.headers??{}}});if(!n.ok){const g=await n.json().catch(()=>({error:"Request failed"}));throw new Error(String(g?.error??"Request failed"))}if(n.status!==204)return n.json()},[]),S=t.useCallback(async()=>{const s=l;if(o.current!==s)return;const r=++j.current;W(!0),M(null),q(void 0);try{const n=await u(y("/api/secrets"));r===j.current&&o.current===s&&(G(n.secrets),U(s))}catch(n){r===j.current&&o.current===s&&(M(n instanceof Error?n.message:String(n)),q(s))}finally{r===j.current&&o.current===s&&W(!1)}},[l,y,u]),R=t.useCallback(async()=>{const s=l;if(o.current!==s)return;const r=++k.current;try{const n=await u(y("/api/secrets/sync-passphrase"));r===k.current&&o.current===s&&(se(!!n.configured),ae(s))}catch(n){r===k.current&&o.current===s&&p?.(a("secrets.errorLoadSyncStatus","Failed to load sync passphrase status: {{error}}",{error:n instanceof Error?n.message:String(n)}),"error")}},[p,l,y,u,a]);t.useEffect(()=>(G([]),U(void 0),f({}),K(null),se(!1),ae(void 0),M(null),q(void 0),b(null),D(null),x(!1),E(!1),C(null),O(!1),F(""),B(""),$(!1),S(),R(),()=>{v.current.forEach(s=>clearTimeout(s)),I.current.forEach(s=>clearTimeout(s))}),[S,R,l]);const J=()=>{O(!1),F(""),B("")},ve=async(s,r)=>{await u(A("/api/secrets/sync-passphrase",r),{method:"PUT",body:JSON.stringify({passphrase:s})})},be=async()=>{const s=l;$(!0);try{if(await ve(w,s),o.current!==s)return;p?.(m?a("secrets.syncPassphraseRotated","Sync passphrase rotated"):a("secrets.syncPassphraseSet","Sync passphrase set"),"success"),J(),await R()}catch(r){o.current===s&&p?.(a("secrets.errorSaveSyncPassphrase","Failed to save sync passphrase: {{error}}",{error:r instanceof Error?r.message:String(r)}),"error")}finally{o.current===s&&$(!1)}},fe=async()=>{if(!window.confirm(a("secrets.confirmClearSyncPassphrase","Clear the cross-node sync passphrase? Existing sync pairs will stop working until you set a new passphrase.")))return;const r=l;try{if(await u(A("/api/secrets/sync-passphrase",r),{method:"DELETE"}),o.current!==r)return;p?.(a("secrets.syncPassphraseCleared","Sync passphrase cleared"),"success"),await R()}catch(n){o.current===r&&p?.(a("secrets.errorClearSyncPassphrase","Failed to clear sync passphrase: {{error}}",{error:n instanceof Error?n.message:String(n)}),"error")}},je=()=>{D(null),i(Y),x(!0),E(!1),b(null)},Se=s=>{D(s),i({key:s.key,value:"",description:s.description??"",scope:s.scope,accessPolicy:s.accessPolicy,envExportable:s.envExportable,envExportKey:s.envExportKey??""}),x(!0),E(!1),b(null)},ge=async()=>{const s=l;b(null);try{if(h){const r={key:c.key,description:c.description||null,accessPolicy:c.accessPolicy,envExportable:c.envExportable,envExportKey:c.envExportable&&c.envExportKey||null};c.value&&(r.value=c.value),await u(y(`/api/secrets/${h.scope}/${h.id}`),{method:"PATCH",body:JSON.stringify(r)})}else await u(y("/api/secrets"),{method:"POST",body:JSON.stringify({scope:c.scope,key:c.key,value:c.value,description:c.description||null,accessPolicy:c.accessPolicy,envExportable:c.envExportable,envExportKey:c.envExportable&&c.envExportKey||null})});if(o.current!==s)return;x(!1),i(Y),await S()}catch(r){o.current===s&&b(r instanceof Error?r.message:String(r))}},Ne=s=>{const r=v.current.get(s.id);r&&(clearTimeout(r),v.current.delete(s.id)),f(n=>({...n,[s.id]:null}))},Pe=async s=>{const r=l,n=await u(y(`/api/secrets/${s.scope}/${s.id}/reveal`),{method:"POST"});if(o.current!==r)return;f(P=>({...P,[s.id]:n.value})),p?.(a("secrets.revealed","Revealed"),"success");const g=setTimeout(()=>{f(P=>({...P,[s.id]:null})),v.current.delete(s.id)},3e4),N=v.current.get(s.id);N&&clearTimeout(N),v.current.set(s.id,g)},Ce=async s=>{const r=ee[s.id];if(!r)return;if(!await Ve(r)){p?.(a("secrets.copyFailed","Failed to copy secret"),"error");return}K(s.id),p?.(a("secrets.copied","Copied"),"success");const g=setTimeout(()=>{K(null),f(P=>({...P,[s.id]:null}))},1500),N=I.current.get(s.id);N&&clearTimeout(N),I.current.set(s.id,g)},Ee=async s=>{const r=l;await u(A(`/api/secrets/${s.scope}/${s.id}`,r),{method:"DELETE"}),o.current===r&&(C(null),await S())},L=oe===l,T=he===l,re=t.useMemo(()=>[...L?z:[]].filter(s=>!(s.scope==="global"&&s.key===Oe)).sort((s,r)=>s.key.localeCompare(r.key)),[z,L]),te=w.length>0&&w===_;return e.jsxs("section",{className:"secrets-view",children:[e.jsx(we,{icon:ke,title:a("secrets.title","Secrets"),actions:e.jsxs(e.Fragment,{children:[e.jsxs("button",{className:"btn btn-sm",onClick:()=>void S(),children:[e.jsx(ce,{...d})," ",a("secrets.refresh","Refresh")]}),e.jsxs("button",{className:"btn btn-primary btn-sm",onClick:je,children:[e.jsx(Re,{...d})," ",a("secrets.addSecret","Add Secret")]})]})}),X&&ie===l?e.jsx("div",{className:"form-error",children:X}):null,Q||!L?e.jsxs("div",{className:"secrets-loading",children:[e.jsx(ce,{...Fe})," ",a("secrets.loading","Loading…")]}):null,!Q&&L&&re.length===0?e.jsx("div",{className:"secrets-empty",children:a("secrets.empty","No secrets found.")}):null,e.jsx("div",{className:"secrets-list",children:re.map(s=>{const r=ee[s.id];return e.jsxs("article",{className:"card secrets-row",children:[e.jsxs("div",{className:"secrets-row-main",children:[e.jsx("div",{className:"secrets-row-key",children:s.key}),e.jsxs("div",{className:"secrets-row-meta",children:[e.jsx("span",{className:"secrets-chip",children:s.scope}),e.jsx("span",{className:"secrets-chip",children:s.accessPolicy}),s.envExportable?e.jsx("span",{className:"secrets-chip",children:a("secrets.envExportableChip","env exportable")}):null]}),r?e.jsx("pre",{className:"secrets-revealed",children:r}):null]}),e.jsxs("div",{className:"secrets-row-side",children:[e.jsx("span",{className:"secrets-row-read",children:s.lastReadAt?new Date(s.lastReadAt).toLocaleString():a("secrets.neverRead","Never read")}),e.jsxs("div",{className:"secrets-row-actions",children:[e.jsx("button",{type:"button",className:"btn btn-icon secrets-visibility-toggle",onClick:()=>{if(r){Ne(s);return}Pe(s)},"aria-label":r?a("secrets.hideAriaLabel","Hide"):a("secrets.revealAriaLabel","Reveal"),children:r?e.jsx(ne,{...d}):e.jsx(le,{...d})}),e.jsx("button",{className:"btn btn-icon",onClick:()=>void Ce(s),"aria-label":a("secrets.copyAriaLabel","Copy"),disabled:!r,children:pe===s.id?e.jsx(Le,{...d}):e.jsx(Te,{...d})}),e.jsx("button",{className:"btn btn-icon",onClick:()=>Se(s),"aria-label":a("secrets.editAriaLabel","Edit"),children:e.jsx(Ae,{...d})}),e.jsx("button",{className:"btn btn-icon btn-danger",onClick:()=>C(s.id),"aria-label":a("secrets.deleteAriaLabel","Delete"),children:e.jsx(Me,{...d})})]}),ue===s.id?e.jsxs("div",{className:"secrets-confirm",children:[e.jsx("button",{className:"btn btn-sm btn-danger",onClick:()=>void Ee(s),children:a("secrets.confirmDelete","Confirm")}),e.jsx("button",{className:"btn btn-sm",onClick:()=>C(null),children:a("secrets.cancelDelete","Cancel")})]}):null]})]},s.id)})}),e.jsxs("article",{className:"card secrets-sync-card secrets-sync-disclosure",children:[e.jsxs("button",{type:"button",className:"secrets-sync-disclosure-toggle","data-testid":"secrets-passphrase-disclosure","aria-expanded":H,"aria-controls":"secrets-sync-disclosure-panel",onClick:()=>xe(s=>!s),children:[H?e.jsx(qe,{size:16,"aria-hidden":"true"}):e.jsx(De,{size:16,"aria-hidden":"true"}),e.jsx("span",{children:a("secrets.syncPassphraseTitle","Cross-Node Sync Passphrase")})]}),H?e.jsxs("div",{id:"secrets-sync-disclosure-panel",className:"secrets-sync-disclosure-panel",children:[e.jsxs("div",{className:"secrets-sync-header",children:[e.jsxs("p",{className:"secrets-sync-status",children:[e.jsx("span",{className:`status-dot ${T&&m?"status-dot--online":"status-dot--pending"}`,"aria-hidden":"true"})," ",T&&m?a("secrets.syncConfigured","Configured"):a("secrets.syncNotConfigured","Not configured")]}),e.jsxs("div",{className:"secrets-sync-actions",children:[e.jsx("button",{className:"btn",onClick:()=>O(!0),children:T&&m?a("secrets.rotateSyncPassphrase","Rotate"):a("secrets.setPassphrase","Set passphrase")}),T&&m?e.jsx("button",{className:"btn btn-danger",onClick:()=>void fe(),children:a("secrets.clearSyncPassphrase","Clear")}):null]})]}),e.jsx("p",{className:"secrets-sync-copy",children:a("secrets.syncPassphraseDescription","Shared passphrase used to wrap cross-node secret bundles. Both nodes in a sync pair must share the same value. Stored locally only; never transmitted.")})]}):null]}),me?e.jsx("div",{className:"modal-overlay open",role:"presentation",children:e.jsxs("div",{className:"modal",role:"dialog","aria-modal":"true","aria-label":m?a("secrets.rotateSyncPassphraseModalTitle","Rotate sync passphrase"):a("secrets.setSyncPassphraseModalTitle","Set sync passphrase"),children:[e.jsxs("div",{className:"modal-header",children:[e.jsx("h3",{children:m?a("secrets.rotateSyncPassphraseModalTitle","Rotate sync passphrase"):a("secrets.setSyncPassphraseModalTitle","Set sync passphrase")}),e.jsx("button",{className:"modal-close",onClick:J,"aria-label":a("secrets.closeAriaLabel","Close"),children:"×"})]}),e.jsxs("div",{className:"secrets-modal-body",children:[e.jsxs("div",{className:"form-group",children:[e.jsx("label",{children:a("secrets.passphraseLabel","Passphrase")}),e.jsx("input",{"aria-label":a("secrets.passphraseLabel","Passphrase"),className:"input",type:"password",autoComplete:"new-password",value:w,onChange:s=>F(s.target.value)})]}),e.jsxs("div",{className:"form-group",children:[e.jsx("label",{children:a("secrets.confirmPassphraseLabel","Confirm passphrase")}),e.jsx("input",{"aria-label":a("secrets.confirmPassphraseLabel","Confirm passphrase"),className:"input",type:"password",autoComplete:"new-password",value:_,onChange:s=>B(s.target.value)})]}),!te&&_.length>0?e.jsx("div",{className:"form-error",children:a("secrets.passphraseMustMatch","Passphrases must match.")}):null]}),e.jsx("div",{className:"modal-actions",children:e.jsxs("div",{className:"modal-actions-right",children:[e.jsx("button",{className:"btn",onClick:J,children:a("secrets.cancelBtn","Cancel")}),e.jsx("button",{className:"btn btn-primary",onClick:()=>void be(),disabled:!te||ye,children:m?a("secrets.rotateSyncPassphrase","Rotate"):a("secrets.setPassphrase","Set passphrase")})]})})]})}):null,de?e.jsx("div",{className:"modal-overlay open",role:"presentation",children:e.jsxs("div",{className:"modal",role:"dialog","aria-modal":"true","aria-label":h?a("secrets.editSecretModalTitle","Edit secret"):a("secrets.addSecretModalTitle","Add secret"),children:[e.jsxs("div",{className:"modal-header",children:[e.jsx("h3",{children:h?a("secrets.editSecretModalTitle","Edit secret"):a("secrets.addSecretModalTitle","Add secret")}),e.jsx("button",{className:"modal-close",onClick:()=>x(!1),"aria-label":a("secrets.closeAriaLabel","Close"),children:"×"})]}),e.jsxs("div",{className:"secrets-modal-body",children:[e.jsxs("div",{className:"form-group",children:[e.jsx("label",{children:a("secrets.keyLabel","Key")}),e.jsx("input",{className:"input",value:c.key,onChange:s=>i(r=>({...r,key:s.target.value}))})]}),e.jsxs("div",{className:"form-group",children:[e.jsx("label",{children:a("secrets.valueLabel","Value")}),e.jsxs("div",{className:"secrets-value-row",children:[e.jsx("input",{className:"input",type:V?"text":"password",autoComplete:"off",spellCheck:!1,value:c.value,onChange:s=>i(r=>({...r,value:s.target.value}))}),e.jsx("button",{type:"button",className:"btn btn-icon secrets-visibility-toggle",onClick:()=>E(s=>!s),"aria-label":V?a("secrets.hideValueAriaLabel","Hide value"):a("secrets.showValueAriaLabel","Show value"),children:V?e.jsx(ne,{...d}):e.jsx(le,{...d})})]})]}),e.jsxs("div",{className:"form-group",children:[e.jsx("label",{children:a("secrets.descriptionLabel","Description")}),e.jsx("textarea",{className:"input",value:c.description,onChange:s=>i(r=>({...r,description:s.target.value}))})]}),e.jsxs("div",{className:"form-group",children:[e.jsx("label",{children:a("secrets.scopeLabel","Scope")}),e.jsxs("div",{className:"secrets-radio-row",children:[e.jsxs("label",{children:[e.jsx("input",{type:"radio",checked:c.scope==="project",onChange:()=>i(s=>({...s,scope:"project"})),disabled:!!h})," ",a("secrets.scopeProject","Project")]}),e.jsxs("label",{children:[e.jsx("input",{type:"radio",checked:c.scope==="global",onChange:()=>i(s=>({...s,scope:"global"})),disabled:!!h})," ",a("secrets.scopeGlobal","Global")]})]})]}),e.jsxs("div",{className:"form-group",children:[e.jsx("label",{children:a("secrets.accessPolicyLabel","Access policy")}),e.jsxs("select",{className:"select",value:c.accessPolicy,onChange:s=>i(r=>({...r,accessPolicy:s.target.value})),children:[e.jsx("option",{value:"auto",children:a("secrets.accessPolicyAuto","auto")}),e.jsx("option",{value:"prompt",children:a("secrets.accessPolicyPrompt","prompt")}),e.jsx("option",{value:"deny",children:a("secrets.accessPolicyDeny","deny")})]})]}),e.jsx("div",{className:"form-group",children:e.jsxs("label",{className:"checkbox-label",children:[e.jsx("input",{type:"checkbox",checked:c.envExportable,onChange:s=>i(r=>({...r,envExportable:s.target.checked}))})," ",a("secrets.exportToEnvLabel","Export to env")]})}),c.envExportable?e.jsxs("div",{className:"form-group",children:[e.jsx("label",{children:a("secrets.envKeyLabel","Env key")}),e.jsx("input",{className:"input",value:c.envExportKey,onChange:s=>i(r=>({...r,envExportKey:s.target.value}))})]}):null,Z?e.jsx("div",{className:"form-error",children:Z}):null]}),e.jsx("div",{className:"modal-actions",children:e.jsxs("div",{className:"modal-actions-right",children:[e.jsx("button",{className:"btn",onClick:()=>x(!1),children:a("secrets.cancelBtn","Cancel")}),e.jsx("button",{className:"btn btn-primary",onClick:()=>void ge(),children:h?a("secrets.saveBtn","Save"):a("secrets.createBtn","Create")})]})})]})}):null]})};export{Ye as SecretsView};
1
+ import{r as t,j as e}from"./vendor-react-SZ_qB27O.js";import{w as A,V as we,o as ke,R as ce,P as Re,E as ne,p as le,q as Le,u as Te,v as Ae,x as Me,C as qe,g as De,y as Ve}from"./index-CtYRoouR.js";import{u as Ke}from"./vendor-i18n-Duky4gdQ.js";import"./vendor-codemirror-CcrtqoCy.js";import"./vendor-reactflow-BlIeoTu4.js";import"./vendor-xterm-BNq00GSj.js";const Oe="__sync_passphrase__",Y={key:"",value:"",description:"",scope:"project",accessPolicy:"prompt",envExportable:!1,envExportKey:""},d={className:"secrets-action-icon","aria-hidden":!0,style:{width:"1em",height:"1em"}},Fe={...d,className:"secrets-action-icon spin"},Ye=({addToast:p,projectId:l})=>{const{t:a}=Ke("app"),[z,G]=t.useState([]),[oe,U]=t.useState(),[Q,W]=t.useState(!0),[X,M]=t.useState(null),[ie,q]=t.useState(),[Z,b]=t.useState(null),[h,D]=t.useState(null),[de,x]=t.useState(!1),[ue,C]=t.useState(null),[c,i]=t.useState(Y),[V,E]=t.useState(!1),[ee,f]=t.useState({}),[pe,K]=t.useState(null),[m,se]=t.useState(!1),[he,ae]=t.useState(),[me,O]=t.useState(!1),[w,F]=t.useState(""),[_,B]=t.useState(""),[ye,$]=t.useState(!1),[H,xe]=t.useState(!1),v=t.useRef(new Map),I=t.useRef(new Map),j=t.useRef(0),k=t.useRef(0),o=t.useRef(l);o.current!==l&&(o.current=l,j.current+=1,k.current+=1);const y=t.useCallback(s=>A(s,l),[l]),u=t.useCallback(async(s,r)=>{const n=await fetch(s,{...r,headers:{"Content-Type":"application/json",...r?.headers??{}}});if(!n.ok){const g=await n.json().catch(()=>({error:"Request failed"}));throw new Error(String(g?.error??"Request failed"))}if(n.status!==204)return n.json()},[]),S=t.useCallback(async()=>{const s=l;if(o.current!==s)return;const r=++j.current;W(!0),M(null),q(void 0);try{const n=await u(y("/api/secrets"));r===j.current&&o.current===s&&(G(n.secrets),U(s))}catch(n){r===j.current&&o.current===s&&(M(n instanceof Error?n.message:String(n)),q(s))}finally{r===j.current&&o.current===s&&W(!1)}},[l,y,u]),R=t.useCallback(async()=>{const s=l;if(o.current!==s)return;const r=++k.current;try{const n=await u(y("/api/secrets/sync-passphrase"));r===k.current&&o.current===s&&(se(!!n.configured),ae(s))}catch(n){r===k.current&&o.current===s&&p?.(a("secrets.errorLoadSyncStatus","Failed to load sync passphrase status: {{error}}",{error:n instanceof Error?n.message:String(n)}),"error")}},[p,l,y,u,a]);t.useEffect(()=>(G([]),U(void 0),f({}),K(null),se(!1),ae(void 0),M(null),q(void 0),b(null),D(null),x(!1),E(!1),C(null),O(!1),F(""),B(""),$(!1),S(),R(),()=>{v.current.forEach(s=>clearTimeout(s)),I.current.forEach(s=>clearTimeout(s))}),[S,R,l]);const J=()=>{O(!1),F(""),B("")},ve=async(s,r)=>{await u(A("/api/secrets/sync-passphrase",r),{method:"PUT",body:JSON.stringify({passphrase:s})})},be=async()=>{const s=l;$(!0);try{if(await ve(w,s),o.current!==s)return;p?.(m?a("secrets.syncPassphraseRotated","Sync passphrase rotated"):a("secrets.syncPassphraseSet","Sync passphrase set"),"success"),J(),await R()}catch(r){o.current===s&&p?.(a("secrets.errorSaveSyncPassphrase","Failed to save sync passphrase: {{error}}",{error:r instanceof Error?r.message:String(r)}),"error")}finally{o.current===s&&$(!1)}},fe=async()=>{if(!window.confirm(a("secrets.confirmClearSyncPassphrase","Clear the cross-node sync passphrase? Existing sync pairs will stop working until you set a new passphrase.")))return;const r=l;try{if(await u(A("/api/secrets/sync-passphrase",r),{method:"DELETE"}),o.current!==r)return;p?.(a("secrets.syncPassphraseCleared","Sync passphrase cleared"),"success"),await R()}catch(n){o.current===r&&p?.(a("secrets.errorClearSyncPassphrase","Failed to clear sync passphrase: {{error}}",{error:n instanceof Error?n.message:String(n)}),"error")}},je=()=>{D(null),i(Y),x(!0),E(!1),b(null)},Se=s=>{D(s),i({key:s.key,value:"",description:s.description??"",scope:s.scope,accessPolicy:s.accessPolicy,envExportable:s.envExportable,envExportKey:s.envExportKey??""}),x(!0),E(!1),b(null)},ge=async()=>{const s=l;b(null);try{if(h){const r={key:c.key,description:c.description||null,accessPolicy:c.accessPolicy,envExportable:c.envExportable,envExportKey:c.envExportable&&c.envExportKey||null};c.value&&(r.value=c.value),await u(y(`/api/secrets/${h.scope}/${h.id}`),{method:"PATCH",body:JSON.stringify(r)})}else await u(y("/api/secrets"),{method:"POST",body:JSON.stringify({scope:c.scope,key:c.key,value:c.value,description:c.description||null,accessPolicy:c.accessPolicy,envExportable:c.envExportable,envExportKey:c.envExportable&&c.envExportKey||null})});if(o.current!==s)return;x(!1),i(Y),await S()}catch(r){o.current===s&&b(r instanceof Error?r.message:String(r))}},Ne=s=>{const r=v.current.get(s.id);r&&(clearTimeout(r),v.current.delete(s.id)),f(n=>({...n,[s.id]:null}))},Pe=async s=>{const r=l,n=await u(y(`/api/secrets/${s.scope}/${s.id}/reveal`),{method:"POST"});if(o.current!==r)return;f(P=>({...P,[s.id]:n.value})),p?.(a("secrets.revealed","Revealed"),"success");const g=setTimeout(()=>{f(P=>({...P,[s.id]:null})),v.current.delete(s.id)},3e4),N=v.current.get(s.id);N&&clearTimeout(N),v.current.set(s.id,g)},Ce=async s=>{const r=ee[s.id];if(!r)return;if(!await Ve(r)){p?.(a("secrets.copyFailed","Failed to copy secret"),"error");return}K(s.id),p?.(a("secrets.copied","Copied"),"success");const g=setTimeout(()=>{K(null),f(P=>({...P,[s.id]:null}))},1500),N=I.current.get(s.id);N&&clearTimeout(N),I.current.set(s.id,g)},Ee=async s=>{const r=l;await u(A(`/api/secrets/${s.scope}/${s.id}`,r),{method:"DELETE"}),o.current===r&&(C(null),await S())},L=oe===l,T=he===l,re=t.useMemo(()=>[...L?z:[]].filter(s=>!(s.scope==="global"&&s.key===Oe)).sort((s,r)=>s.key.localeCompare(r.key)),[z,L]),te=w.length>0&&w===_;return e.jsxs("section",{className:"secrets-view",children:[e.jsx(we,{icon:ke,title:a("secrets.title","Secrets"),actions:e.jsxs(e.Fragment,{children:[e.jsxs("button",{className:"btn btn-sm",onClick:()=>void S(),children:[e.jsx(ce,{...d})," ",a("secrets.refresh","Refresh")]}),e.jsxs("button",{className:"btn btn-primary btn-sm",onClick:je,children:[e.jsx(Re,{...d})," ",a("secrets.addSecret","Add Secret")]})]})}),X&&ie===l?e.jsx("div",{className:"form-error",children:X}):null,Q||!L?e.jsxs("div",{className:"secrets-loading",children:[e.jsx(ce,{...Fe})," ",a("secrets.loading","Loading…")]}):null,!Q&&L&&re.length===0?e.jsx("div",{className:"secrets-empty",children:a("secrets.empty","No secrets found.")}):null,e.jsx("div",{className:"secrets-list",children:re.map(s=>{const r=ee[s.id];return e.jsxs("article",{className:"card secrets-row",children:[e.jsxs("div",{className:"secrets-row-main",children:[e.jsx("div",{className:"secrets-row-key",children:s.key}),e.jsxs("div",{className:"secrets-row-meta",children:[e.jsx("span",{className:"secrets-chip",children:s.scope}),e.jsx("span",{className:"secrets-chip",children:s.accessPolicy}),s.envExportable?e.jsx("span",{className:"secrets-chip",children:a("secrets.envExportableChip","env exportable")}):null]}),r?e.jsx("pre",{className:"secrets-revealed",children:r}):null]}),e.jsxs("div",{className:"secrets-row-side",children:[e.jsx("span",{className:"secrets-row-read",children:s.lastReadAt?new Date(s.lastReadAt).toLocaleString():a("secrets.neverRead","Never read")}),e.jsxs("div",{className:"secrets-row-actions",children:[e.jsx("button",{type:"button",className:"btn btn-icon secrets-visibility-toggle",onClick:()=>{if(r){Ne(s);return}Pe(s)},"aria-label":r?a("secrets.hideAriaLabel","Hide"):a("secrets.revealAriaLabel","Reveal"),children:r?e.jsx(ne,{...d}):e.jsx(le,{...d})}),e.jsx("button",{className:"btn btn-icon",onClick:()=>void Ce(s),"aria-label":a("secrets.copyAriaLabel","Copy"),disabled:!r,children:pe===s.id?e.jsx(Le,{...d}):e.jsx(Te,{...d})}),e.jsx("button",{className:"btn btn-icon",onClick:()=>Se(s),"aria-label":a("secrets.editAriaLabel","Edit"),children:e.jsx(Ae,{...d})}),e.jsx("button",{className:"btn btn-icon btn-danger",onClick:()=>C(s.id),"aria-label":a("secrets.deleteAriaLabel","Delete"),children:e.jsx(Me,{...d})})]}),ue===s.id?e.jsxs("div",{className:"secrets-confirm",children:[e.jsx("button",{className:"btn btn-sm btn-danger",onClick:()=>void Ee(s),children:a("secrets.confirmDelete","Confirm")}),e.jsx("button",{className:"btn btn-sm",onClick:()=>C(null),children:a("secrets.cancelDelete","Cancel")})]}):null]})]},s.id)})}),e.jsxs("article",{className:"card secrets-sync-card secrets-sync-disclosure",children:[e.jsxs("button",{type:"button",className:"secrets-sync-disclosure-toggle","data-testid":"secrets-passphrase-disclosure","aria-expanded":H,"aria-controls":"secrets-sync-disclosure-panel",onClick:()=>xe(s=>!s),children:[H?e.jsx(qe,{size:16,"aria-hidden":"true"}):e.jsx(De,{size:16,"aria-hidden":"true"}),e.jsx("span",{children:a("secrets.syncPassphraseTitle","Cross-Node Sync Passphrase")})]}),H?e.jsxs("div",{id:"secrets-sync-disclosure-panel",className:"secrets-sync-disclosure-panel",children:[e.jsxs("div",{className:"secrets-sync-header",children:[e.jsxs("p",{className:"secrets-sync-status",children:[e.jsx("span",{className:`status-dot ${T&&m?"status-dot--online":"status-dot--pending"}`,"aria-hidden":"true"})," ",T&&m?a("secrets.syncConfigured","Configured"):a("secrets.syncNotConfigured","Not configured")]}),e.jsxs("div",{className:"secrets-sync-actions",children:[e.jsx("button",{className:"btn",onClick:()=>O(!0),children:T&&m?a("secrets.rotateSyncPassphrase","Rotate"):a("secrets.setPassphrase","Set passphrase")}),T&&m?e.jsx("button",{className:"btn btn-danger",onClick:()=>void fe(),children:a("secrets.clearSyncPassphrase","Clear")}):null]})]}),e.jsx("p",{className:"secrets-sync-copy",children:a("secrets.syncPassphraseDescription","Shared passphrase used to wrap cross-node secret bundles. Both nodes in a sync pair must share the same value. Stored locally only; never transmitted.")})]}):null]}),me?e.jsx("div",{className:"modal-overlay open",role:"presentation",children:e.jsxs("div",{className:"modal",role:"dialog","aria-modal":"true","aria-label":m?a("secrets.rotateSyncPassphraseModalTitle","Rotate sync passphrase"):a("secrets.setSyncPassphraseModalTitle","Set sync passphrase"),children:[e.jsxs("div",{className:"modal-header",children:[e.jsx("h3",{children:m?a("secrets.rotateSyncPassphraseModalTitle","Rotate sync passphrase"):a("secrets.setSyncPassphraseModalTitle","Set sync passphrase")}),e.jsx("button",{className:"modal-close",onClick:J,"aria-label":a("secrets.closeAriaLabel","Close"),children:"×"})]}),e.jsxs("div",{className:"secrets-modal-body",children:[e.jsxs("div",{className:"form-group",children:[e.jsx("label",{children:a("secrets.passphraseLabel","Passphrase")}),e.jsx("input",{"aria-label":a("secrets.passphraseLabel","Passphrase"),className:"input",type:"password",autoComplete:"new-password",value:w,onChange:s=>F(s.target.value)})]}),e.jsxs("div",{className:"form-group",children:[e.jsx("label",{children:a("secrets.confirmPassphraseLabel","Confirm passphrase")}),e.jsx("input",{"aria-label":a("secrets.confirmPassphraseLabel","Confirm passphrase"),className:"input",type:"password",autoComplete:"new-password",value:_,onChange:s=>B(s.target.value)})]}),!te&&_.length>0?e.jsx("div",{className:"form-error",children:a("secrets.passphraseMustMatch","Passphrases must match.")}):null]}),e.jsx("div",{className:"modal-actions",children:e.jsxs("div",{className:"modal-actions-right",children:[e.jsx("button",{className:"btn",onClick:J,children:a("secrets.cancelBtn","Cancel")}),e.jsx("button",{className:"btn btn-primary",onClick:()=>void be(),disabled:!te||ye,children:m?a("secrets.rotateSyncPassphrase","Rotate"):a("secrets.setPassphrase","Set passphrase")})]})})]})}):null,de?e.jsx("div",{className:"modal-overlay open",role:"presentation",children:e.jsxs("div",{className:"modal",role:"dialog","aria-modal":"true","aria-label":h?a("secrets.editSecretModalTitle","Edit secret"):a("secrets.addSecretModalTitle","Add secret"),children:[e.jsxs("div",{className:"modal-header",children:[e.jsx("h3",{children:h?a("secrets.editSecretModalTitle","Edit secret"):a("secrets.addSecretModalTitle","Add secret")}),e.jsx("button",{className:"modal-close",onClick:()=>x(!1),"aria-label":a("secrets.closeAriaLabel","Close"),children:"×"})]}),e.jsxs("div",{className:"secrets-modal-body",children:[e.jsxs("div",{className:"form-group",children:[e.jsx("label",{children:a("secrets.keyLabel","Key")}),e.jsx("input",{className:"input",value:c.key,onChange:s=>i(r=>({...r,key:s.target.value}))})]}),e.jsxs("div",{className:"form-group",children:[e.jsx("label",{children:a("secrets.valueLabel","Value")}),e.jsxs("div",{className:"secrets-value-row",children:[e.jsx("input",{className:"input",type:V?"text":"password",autoComplete:"off",spellCheck:!1,value:c.value,onChange:s=>i(r=>({...r,value:s.target.value}))}),e.jsx("button",{type:"button",className:"btn btn-icon secrets-visibility-toggle",onClick:()=>E(s=>!s),"aria-label":V?a("secrets.hideValueAriaLabel","Hide value"):a("secrets.showValueAriaLabel","Show value"),children:V?e.jsx(ne,{...d}):e.jsx(le,{...d})})]})]}),e.jsxs("div",{className:"form-group",children:[e.jsx("label",{children:a("secrets.descriptionLabel","Description")}),e.jsx("textarea",{className:"input",value:c.description,onChange:s=>i(r=>({...r,description:s.target.value}))})]}),e.jsxs("div",{className:"form-group",children:[e.jsx("label",{children:a("secrets.scopeLabel","Scope")}),e.jsxs("div",{className:"secrets-radio-row",children:[e.jsxs("label",{children:[e.jsx("input",{type:"radio",checked:c.scope==="project",onChange:()=>i(s=>({...s,scope:"project"})),disabled:!!h})," ",a("secrets.scopeProject","Project")]}),e.jsxs("label",{children:[e.jsx("input",{type:"radio",checked:c.scope==="global",onChange:()=>i(s=>({...s,scope:"global"})),disabled:!!h})," ",a("secrets.scopeGlobal","Global")]})]})]}),e.jsxs("div",{className:"form-group",children:[e.jsx("label",{children:a("secrets.accessPolicyLabel","Access policy")}),e.jsxs("select",{className:"select",value:c.accessPolicy,onChange:s=>i(r=>({...r,accessPolicy:s.target.value})),children:[e.jsx("option",{value:"auto",children:a("secrets.accessPolicyAuto","auto")}),e.jsx("option",{value:"prompt",children:a("secrets.accessPolicyPrompt","prompt")}),e.jsx("option",{value:"deny",children:a("secrets.accessPolicyDeny","deny")})]})]}),e.jsx("div",{className:"form-group",children:e.jsxs("label",{className:"checkbox-label",children:[e.jsx("input",{type:"checkbox",checked:c.envExportable,onChange:s=>i(r=>({...r,envExportable:s.target.checked}))})," ",a("secrets.exportToEnvLabel","Export to env")]})}),c.envExportable?e.jsxs("div",{className:"form-group",children:[e.jsx("label",{children:a("secrets.envKeyLabel","Env key")}),e.jsx("input",{className:"input",value:c.envExportKey,onChange:s=>i(r=>({...r,envExportKey:s.target.value}))})]}):null,Z?e.jsx("div",{className:"form-error",children:Z}):null]}),e.jsx("div",{className:"modal-actions",children:e.jsxs("div",{className:"modal-actions-right",children:[e.jsx("button",{className:"btn",onClick:()=>x(!1),children:a("secrets.cancelBtn","Cancel")}),e.jsx("button",{className:"btn btn-primary",onClick:()=>void ge(),children:h?a("secrets.saveBtn","Save"):a("secrets.createBtn","Create")})]})})]})}):null]})};export{Ye as SecretsView};
@@ -1,2 +1,2 @@
1
1
  const __vite__mapDeps=(i,m=__vite__mapDeps,d=(m.f||(m.f=["assets/vendor-xterm-BNq00GSj.js","assets/vendor-react-SZ_qB27O.js","assets/vendor-xterm-LZoznX6r.css","assets/addon-fit-C1WQXRvu.js","assets/addon-webgl-uLc0RKcC.js"])))=>i.map(i=>d[i]);
2
- import{K as Pe,N as z,O as de,Q as J,U as ue,W as F,Y as je,_ as Me,p as Le,$ as De,a0 as Y,a1 as Oe,a2 as Ae,a as ze,a3 as K,a4 as Fe,a5 as Be}from"./index-DWRJyaa3.js";import{r as i,j as t}from"./vendor-react-SZ_qB27O.js";import"./vendor-xterm-BNq00GSj.js";import{u as Ie}from"./vendor-i18n-Duky4gdQ.js";import{S as Ke}from"./shield-alert-BS05s4RM.js";import"./vendor-codemirror-CcrtqoCy.js";import"./vendor-reactflow-BlIeoTu4.js";const We=32*1024,$e=1e4,Ue=100,Qe="\x1B",Ve=" ",Je="",Ye="\x1B[A",Ge="\x1B[B",He="\x1B[C",qe="\x1B[D",W={ctrl:"Ctrl",escape:"Esc",tab:"Tab",ctrlC:"^C"};function me(m){if(m.length!==1)return null;const o=m.toUpperCase().charCodeAt(0);return o>=64&&o<=95?String.fromCharCode(o&31):null}function Ze(){const[m,f]=i.useState(()=>Y());return i.useEffect(()=>{if(typeof window>"u"||typeof window.matchMedia!="function")return;const o=window.matchMedia(Oe),r=window.visualViewport,y=()=>f(Y());return y(),typeof r?.addEventListener=="function"&&r.addEventListener("resize",y),typeof o.addEventListener=="function"?(o.addEventListener("change",y),()=>{o.removeEventListener("change",y),typeof r?.removeEventListener=="function"&&r.removeEventListener("resize",y)}):(o.addListener(y),()=>{o.removeListener(y),typeof r?.removeEventListener=="function"&&r.removeEventListener("resize",y)})},[]),m}function Xe(m,f){if(typeof window>"u")return"";const r=`${window.location.protocol==="https:"?"wss:":"ws:"}//${window.location.host}/api/cli-sessions/ws?sessionId=${encodeURIComponent(m)}&ticket=${encodeURIComponent(f)}`;return Be(r)}function et(){return/Mac|iPhone|iPad|iPod/i.test(navigator.platform)}function tt(m){if(typeof window<"u"&&typeof window.atob=="function"){const f=window.atob(m),o=new Uint8Array(f.length);for(let r=0;r<f.length;r++)o[r]=f.charCodeAt(r);return new TextDecoder("utf-8").decode(o)}return Buffer.from(m,"base64").toString("utf8")}function ut({sessionId:m,readOnly:f=!1,posture:o,mode:r="live",projectId:y,onConfirmAdvance:g,showConfirmAdvance:$=!1,onOpenAdapterSettings:G,active:H=!0}){const{t:a}=Ie("app"),x=i.useRef(null),v=i.useRef(null),N=i.useRef(null),R=i.useRef(null),h=i.useRef(null),[q,Z]=i.useState(!1),[fe,U]=i.useState(!1),[X,ee]=i.useState(!1),P=Ze(),{keyboardOpen:B,keyboardOverlap:pe}=Pe({enabled:P}),ye=i.useRef(null),[_,te]=i.useState(""),[j,D]=i.useState(!1),[be,he]=i.useState(()=>z().customShortcuts),[ne,ie]=i.useState(null),se=f||ne===!0,O=!f&&ne===!1&&r==="live",b=i.useCallback(e=>{if(!e||!O)return;const n=h.current;n?.readyState===WebSocket.OPEN&&n.send(JSON.stringify({type:"input",data:e}))},[O]),M=i.useCallback(e=>{if(j){const n=me(e);if(D(!1),n){b(n);return}}b(e)},[j,b]),c=i.useCallback(e=>{e.preventDefault()},[]),we=i.useCallback(e=>{e?.preventDefault?.(),_&&b(_),b("\r"),te("")},[_,b]),Se=i.useCallback(e=>{if(j&&e.length>_.length){const n=e.slice(_.length,_.length+1),l=me(n);if(D(!1),l){b(l);return}}te(e)},[j,_,b]);i.useEffect(()=>{$&&U(!1)},[$,m]);const E=i.useCallback((e,n)=>{const l=h.current;l?.readyState===WebSocket.OPEN&&l.send(JSON.stringify({type:"resize",cols:e,rows:n}))},[]),oe=i.useCallback(()=>{const e=v.current;if(!e)return;const n=z(),l=de(n.fontFamily);e.options.fontFamily=l,x.current?.style.setProperty("--terminal-glyph-font-family",J(n.fontFamily)),e.options.fontSize=n.fontSize,e.options.cursorStyle=n.cursorStyle,e.options.cursorBlink=n.cursorBlink&&O;try{N.current?.fit?.(),E(e.cols,e.rows)}catch{}ue(n.fontSize,l).then(k=>{if(!(!k||v.current!==e||e.options.fontSize!==n.fontSize||e.options.fontFamily!==l)){F(e,l),e.options.fontSize=n.fontSize;try{N.current?.fit?.(),E(e.cols,e.rows),F(e,l),e.refresh(0,Math.max(0,e.rows-1))}catch{}}},()=>{})},[O,E]);i.useEffect(()=>{if(typeof window>"u")return;const e=n=>{n.key===Ae&&(oe(),he(z().customShortcuts))};return window.addEventListener("storage",e),()=>window.removeEventListener("storage",e)},[oe]);const[_e,ke]=i.useState(0);i.useEffect(()=>{if(!H)return;const e=v.current,n=N.current;if(e&&n?.fit)try{n.fit(),E(e.cols,e.rows),F(e,String(e.options.fontFamily??"")),e.refresh(0,Math.max(0,e.rows-1))}catch{}const l=h.current;l&&l.readyState!==WebSocket.OPEN&&l.readyState!==WebSocket.CONNECTING&&ke(k=>k+1)},[H,E]),i.useEffect(()=>{if(!m||typeof window>"u")return;let e=!1,n=null,l=null,k=0;ie(null);const Q=E,Te=p=>{if(k+=p,k<We)return;const w=h.current;w?.readyState===WebSocket.OPEN&&w.send(JSON.stringify({type:"ack",bytes:k})),k=0};return(async()=>{let p;try{p=await ze(`/cli-sessions/${encodeURIComponent(m)}/attach-ticket`,{method:"POST",body:JSON.stringify(y?{projectId:y}:{})})}catch{return}if(e)return;ie(p.readOnly);const w=!f&&!p.readOnly&&r==="live",[{Terminal:ge},{FitAddon:xe},{Unicode11Addon:Ne}]=await Promise.all([K(()=>import("./vendor-xterm-BNq00GSj.js").then(d=>d.x),__vite__mapDeps([0,1,2])),K(()=>import("./addon-fit-C1WQXRvu.js").then(d=>d.a),__vite__mapDeps([3,1])),K(()=>import("./addon-unicode11-D3Fsv-Po.js"),[])]);if(e||!x.current)return;const S=z(),A=de(S.fontFamily);x.current.style.setProperty("--terminal-glyph-font-family",J(S.fontFamily));const s=new ge({convertEol:!1,cursorBlink:S.cursorBlink&&w,cursorStyle:S.cursorStyle,disableStdin:!w,scrollback:$e,fontFamily:A,fontSize:S.fontSize}),L=new xe;s.loadAddon(L);const Re=new Ne;if(s.loadAddon(Re),s.unicode.activeVersion="11",Fe(()=>{s.open(x.current)}),v.current=s,N.current=L,S.renderer==="auto"&&!Y())try{const{WebglAddon:d}=await K(async()=>{const{WebglAddon:u}=await import("./addon-webgl-uLc0RKcC.js").then(C=>C.a);return{WebglAddon:u}},__vite__mapDeps([4,1]));if(!e){const u=new d;u.onContextLoss(()=>{try{u.dispose()}catch{}R.current===u&&(R.current=null)}),s.loadAddon(u),R.current=u}}catch{}try{L.fit()}catch{}(async()=>{if(!(!await ue(S.fontSize,A)||e||v.current!==s||N.current!==L||s.options.fontSize!==S.fontSize||s.options.fontFamily!==A))try{F(s,A),s.options.fontSize=S.fontSize,L.fit(),Q(s.cols,s.rows),F(s,A),s.refresh(0,Math.max(0,s.rows-1))}catch{}})(),w&&(s.onData(d=>{const u=h.current;u?.readyState===WebSocket.OPEN&&u.send(JSON.stringify({type:"input",data:d}))}),s.attachCustomKeyEventHandler(d=>{if(d.type!=="keydown"||!(et()?d.metaKey:d.ctrlKey)||d.altKey||d.shiftKey)return!0;const C=d.key.toLowerCase();if(C==="c"){const T=s.hasSelection()?s.getSelection():"";return T?(navigator.clipboard?.writeText(T).catch(()=>{}),!1):!0}if(C==="v"){const T=navigator.clipboard?.readText;return T&&T.call(navigator.clipboard).then(le=>{if(!le)return;const ce=h.current;ce?.readyState===WebSocket.OPEN&&ce.send(JSON.stringify({type:"input",data:le}))}).catch(()=>{}),!1}return!0})),n=new ResizeObserver(()=>{l&&clearTimeout(l),l=setTimeout(()=>{try{L.fit(),Q(s.cols,s.rows),s.refresh(0,Math.max(0,s.rows-1))}catch{}},Ue)}),n.observe(x.current);const V=new WebSocket(Xe(m,p.ticket));h.current=V,V.onopen=()=>{Q(s.cols,s.rows)},V.onmessage=d=>{let u;try{u=JSON.parse(typeof d.data=="string"?d.data:"")}catch{return}switch(u.type){case"scrollback":case"data":{if(typeof u.data!="string")return;const C=tt(u.data),T=C.length;s.write(C,()=>Te(T));break}}}})(),()=>{e=!0,l&&clearTimeout(l),n&&n.disconnect();const p=h.current;if(p){p.onopen=null,p.onmessage=null,p.onclose=null,p.onerror=null;try{p.close()}catch{}h.current=null}if(R.current){try{R.current.dispose()}catch{}R.current=null}const w=v.current;if(w){try{w.dispose()}catch{}v.current=null}N.current=null}},[m,f,r,y,E,_e]);const re=i.useMemo(()=>r==="idle"?a("cliTerminal.replayIdle","Session idle"):r==="ended"?a("cliTerminal.replayEnded","Session ended"):null,[r,a]),ve=i.useCallback(async()=>{if(g){ee(!0);try{await g("advance"),U(!0)}finally{ee(!1)}}},[g]),Ee=i.useCallback(async()=>{g&&await g("not-yet"),U(!0)},[g]),I=!!o?.elevated,ae=o?.elevatedFlags?.join(", "),Ce={"--terminal-glyph-font-family":J(z().fontFamily)};return t.jsxs("div",{className:`cli-session-terminal${P?" cli-session-terminal--mobile":""}${P&&B?" cli-session-terminal--keyboard-open":""}`,"data-mode":r,"data-read-only":se,"data-mobile":P,"data-keyboard-open":P&&B,children:[t.jsxs("header",{className:"cli-session-terminal__header",children:[o&&t.jsxs("div",{className:"cli-session-terminal__posture-wrap",children:[t.jsxs("button",{type:"button",className:`cli-posture-chip${I?" cli-posture-chip--elevated":""}`,"data-elevated":I,"aria-expanded":q,onClick:()=>Z(e=>!e),children:[I?t.jsx(Ke,{size:13,"aria-hidden":"true"}):t.jsx(je,{size:13,"aria-hidden":"true"}),t.jsx("span",{className:"cli-posture-chip__name",children:o.adapterName}),o.mode&&t.jsx("span",{className:"cli-posture-chip__mode",children:o.mode}),I&&ae&&t.jsx("span",{className:"cli-posture-chip__flag",children:ae})]}),q&&t.jsxs("div",{className:"cli-posture-tooltip",role:"tooltip",children:[t.jsx("p",{className:"cli-posture-tooltip__title",children:a("cliTerminal.postureResolved","Resolved posture")}),t.jsxs("ul",{className:"cli-posture-tooltip__list",children:[(o.resolved??[]).map((e,n)=>t.jsx("li",{children:e},n)),(o.resolved??[]).length===0&&t.jsx("li",{children:o.mode??a("cliTerminal.postureBaseline","Baseline")})]}),G&&t.jsxs("button",{type:"button",className:"cli-posture-tooltip__settings",onClick:()=>{Z(!1),G()},children:[t.jsx(Me,{size:12,"aria-hidden":"true"}),a("cliTerminal.adapterSettings","Adapter settings")]})]})]}),se&&t.jsxs("span",{className:"cli-session-terminal__readonly-badge",children:[t.jsx(Le,{size:12,"aria-hidden":"true"}),a("cliTerminal.readOnly","Read-only")]}),re&&t.jsx("span",{className:"cli-session-terminal__replay-badge","data-replay-mode":r,children:re})]}),t.jsx("div",{className:"cli-session-terminal__viewport-shell",children:t.jsx("div",{className:"cli-session-terminal__viewport",ref:x,"data-testid":"cli-terminal-viewport",style:Ce})}),$&&!fe&&t.jsxs("div",{className:"cli-session-terminal__advance-strip",role:"region",children:[t.jsx("span",{className:"cli-session-terminal__advance-copy",children:a("cliTerminal.advancePrompt","This session looks idle — advance to review?")}),t.jsxs("div",{className:"cli-session-terminal__advance-actions",children:[t.jsx("button",{type:"button",className:"cli-session-terminal__advance-btn",disabled:X,onClick:ve,children:a("cliTerminal.advance","Advance")}),t.jsx("button",{type:"button",className:"cli-session-terminal__advance-btn cli-session-terminal__advance-btn--secondary",disabled:X,onClick:Ee,children:a("cliTerminal.notYet","Not yet")})]})]}),P&&O&&t.jsxs("div",{className:`cli-session-terminal__mobile-bar${B?" cli-session-terminal__mobile-bar--keyboard-open":""}`,"data-testid":"cli-terminal-mobile-bar",style:B?{bottom:`${pe}px`}:void 0,children:[t.jsxs("div",{className:"cli-session-terminal__key-row","data-testid":"cli-terminal-key-bar",children:[t.jsx("button",{type:"button",className:`cli-terminal-key cli-terminal-key--ctrl${j?" cli-terminal-key--active":""}`,"data-testid":"cli-key-ctrl","aria-label":a("cliTerminal.mobileKeyCtrl","Sticky Ctrl modifier"),"aria-pressed":j,onPointerDown:c,onMouseDown:c,onClick:()=>D(e=>!e),children:W.ctrl}),t.jsx("button",{type:"button",className:"cli-terminal-key","data-testid":"cli-key-esc","aria-label":a("cliTerminal.mobileKeyEsc","Send Escape"),onPointerDown:c,onMouseDown:c,onClick:()=>M(Qe),children:W.escape}),t.jsx("button",{type:"button",className:"cli-terminal-key","data-testid":"cli-key-tab","aria-label":a("cliTerminal.mobileKeyTab","Send Tab"),onPointerDown:c,onMouseDown:c,onClick:()=>M(Ve),children:W.tab}),t.jsx("button",{type:"button",className:"cli-terminal-key cli-terminal-key--ctrlc","data-testid":"cli-key-ctrl-c","aria-label":a("cliTerminal.mobileKeyCtrlC","Send Ctrl-C"),onPointerDown:c,onMouseDown:c,onClick:()=>{D(!1),b(Je)},children:W.ctrlC}),t.jsx("button",{type:"button",className:"cli-terminal-key","data-testid":"cli-key-arrow-up","aria-label":a("cliTerminal.mobileKeyArrowUp","Cursor up"),onPointerDown:c,onMouseDown:c,onClick:()=>M(Ye),children:"↑"}),t.jsx("button",{type:"button",className:"cli-terminal-key","data-testid":"cli-key-arrow-down","aria-label":a("cliTerminal.mobileKeyArrowDown","Cursor down"),onPointerDown:c,onMouseDown:c,onClick:()=>M(Ge),children:"↓"}),t.jsx("button",{type:"button",className:"cli-terminal-key","data-testid":"cli-key-arrow-left","aria-label":a("cliTerminal.mobileKeyArrowLeft","Cursor left"),onPointerDown:c,onMouseDown:c,onClick:()=>M(qe),children:"←"}),t.jsx("button",{type:"button",className:"cli-terminal-key","data-testid":"cli-key-arrow-right","aria-label":a("cliTerminal.mobileKeyArrowRight","Cursor right"),onPointerDown:c,onMouseDown:c,onClick:()=>M(He),children:"→"}),be.map(e=>t.jsx("button",{type:"button",className:"cli-terminal-key cli-terminal-key--custom","data-testid":`cli-terminal-custom-shortcut-${e.id}`,title:e.label,"aria-label":e.label,onPointerDown:c,onMouseDown:c,onClick:()=>{D(!1),b(De(e.value))},children:e.label},e.id))]}),t.jsxs("form",{className:"cli-session-terminal__input-row",onSubmit:we,children:[t.jsx("input",{ref:ye,type:"text",className:"cli-session-terminal__mobile-input","data-testid":"cli-terminal-mobile-input",value:_,placeholder:a("cliTerminal.mobileInputPlaceholder","Type to send to the session…"),autoCapitalize:"off",autoCorrect:"off",autoComplete:"off",spellCheck:!1,onChange:e=>Se(e.target.value)}),t.jsx("button",{type:"submit",className:"cli-session-terminal__mobile-send","data-testid":"cli-terminal-mobile-send","aria-label":a("cliTerminal.mobileSend","Send"),onPointerDown:c,onMouseDown:c,children:a("cliTerminal.mobileSend","Send")})]})]})]})}export{ut as SessionTerminal};
2
+ import{K as Pe,N as z,O as de,Q as J,U as ue,W as F,Y as je,_ as Me,p as Le,$ as De,a0 as Y,a1 as Oe,a2 as Ae,a as ze,a3 as K,a4 as Fe,a5 as Be}from"./index-CtYRoouR.js";import{r as i,j as t}from"./vendor-react-SZ_qB27O.js";import"./vendor-xterm-BNq00GSj.js";import{u as Ie}from"./vendor-i18n-Duky4gdQ.js";import{S as Ke}from"./shield-alert-BX4WRJOv.js";import"./vendor-codemirror-CcrtqoCy.js";import"./vendor-reactflow-BlIeoTu4.js";const We=32*1024,$e=1e4,Ue=100,Qe="\x1B",Ve=" ",Je="",Ye="\x1B[A",Ge="\x1B[B",He="\x1B[C",qe="\x1B[D",W={ctrl:"Ctrl",escape:"Esc",tab:"Tab",ctrlC:"^C"};function me(m){if(m.length!==1)return null;const o=m.toUpperCase().charCodeAt(0);return o>=64&&o<=95?String.fromCharCode(o&31):null}function Ze(){const[m,f]=i.useState(()=>Y());return i.useEffect(()=>{if(typeof window>"u"||typeof window.matchMedia!="function")return;const o=window.matchMedia(Oe),r=window.visualViewport,y=()=>f(Y());return y(),typeof r?.addEventListener=="function"&&r.addEventListener("resize",y),typeof o.addEventListener=="function"?(o.addEventListener("change",y),()=>{o.removeEventListener("change",y),typeof r?.removeEventListener=="function"&&r.removeEventListener("resize",y)}):(o.addListener(y),()=>{o.removeListener(y),typeof r?.removeEventListener=="function"&&r.removeEventListener("resize",y)})},[]),m}function Xe(m,f){if(typeof window>"u")return"";const r=`${window.location.protocol==="https:"?"wss:":"ws:"}//${window.location.host}/api/cli-sessions/ws?sessionId=${encodeURIComponent(m)}&ticket=${encodeURIComponent(f)}`;return Be(r)}function et(){return/Mac|iPhone|iPad|iPod/i.test(navigator.platform)}function tt(m){if(typeof window<"u"&&typeof window.atob=="function"){const f=window.atob(m),o=new Uint8Array(f.length);for(let r=0;r<f.length;r++)o[r]=f.charCodeAt(r);return new TextDecoder("utf-8").decode(o)}return Buffer.from(m,"base64").toString("utf8")}function ut({sessionId:m,readOnly:f=!1,posture:o,mode:r="live",projectId:y,onConfirmAdvance:g,showConfirmAdvance:$=!1,onOpenAdapterSettings:G,active:H=!0}){const{t:a}=Ie("app"),x=i.useRef(null),v=i.useRef(null),N=i.useRef(null),R=i.useRef(null),h=i.useRef(null),[q,Z]=i.useState(!1),[fe,U]=i.useState(!1),[X,ee]=i.useState(!1),P=Ze(),{keyboardOpen:B,keyboardOverlap:pe}=Pe({enabled:P}),ye=i.useRef(null),[_,te]=i.useState(""),[j,D]=i.useState(!1),[be,he]=i.useState(()=>z().customShortcuts),[ne,ie]=i.useState(null),se=f||ne===!0,O=!f&&ne===!1&&r==="live",b=i.useCallback(e=>{if(!e||!O)return;const n=h.current;n?.readyState===WebSocket.OPEN&&n.send(JSON.stringify({type:"input",data:e}))},[O]),M=i.useCallback(e=>{if(j){const n=me(e);if(D(!1),n){b(n);return}}b(e)},[j,b]),c=i.useCallback(e=>{e.preventDefault()},[]),we=i.useCallback(e=>{e?.preventDefault?.(),_&&b(_),b("\r"),te("")},[_,b]),Se=i.useCallback(e=>{if(j&&e.length>_.length){const n=e.slice(_.length,_.length+1),l=me(n);if(D(!1),l){b(l);return}}te(e)},[j,_,b]);i.useEffect(()=>{$&&U(!1)},[$,m]);const E=i.useCallback((e,n)=>{const l=h.current;l?.readyState===WebSocket.OPEN&&l.send(JSON.stringify({type:"resize",cols:e,rows:n}))},[]),oe=i.useCallback(()=>{const e=v.current;if(!e)return;const n=z(),l=de(n.fontFamily);e.options.fontFamily=l,x.current?.style.setProperty("--terminal-glyph-font-family",J(n.fontFamily)),e.options.fontSize=n.fontSize,e.options.cursorStyle=n.cursorStyle,e.options.cursorBlink=n.cursorBlink&&O;try{N.current?.fit?.(),E(e.cols,e.rows)}catch{}ue(n.fontSize,l).then(k=>{if(!(!k||v.current!==e||e.options.fontSize!==n.fontSize||e.options.fontFamily!==l)){F(e,l),e.options.fontSize=n.fontSize;try{N.current?.fit?.(),E(e.cols,e.rows),F(e,l),e.refresh(0,Math.max(0,e.rows-1))}catch{}}},()=>{})},[O,E]);i.useEffect(()=>{if(typeof window>"u")return;const e=n=>{n.key===Ae&&(oe(),he(z().customShortcuts))};return window.addEventListener("storage",e),()=>window.removeEventListener("storage",e)},[oe]);const[_e,ke]=i.useState(0);i.useEffect(()=>{if(!H)return;const e=v.current,n=N.current;if(e&&n?.fit)try{n.fit(),E(e.cols,e.rows),F(e,String(e.options.fontFamily??"")),e.refresh(0,Math.max(0,e.rows-1))}catch{}const l=h.current;l&&l.readyState!==WebSocket.OPEN&&l.readyState!==WebSocket.CONNECTING&&ke(k=>k+1)},[H,E]),i.useEffect(()=>{if(!m||typeof window>"u")return;let e=!1,n=null,l=null,k=0;ie(null);const Q=E,Te=p=>{if(k+=p,k<We)return;const w=h.current;w?.readyState===WebSocket.OPEN&&w.send(JSON.stringify({type:"ack",bytes:k})),k=0};return(async()=>{let p;try{p=await ze(`/cli-sessions/${encodeURIComponent(m)}/attach-ticket`,{method:"POST",body:JSON.stringify(y?{projectId:y}:{})})}catch{return}if(e)return;ie(p.readOnly);const w=!f&&!p.readOnly&&r==="live",[{Terminal:ge},{FitAddon:xe},{Unicode11Addon:Ne}]=await Promise.all([K(()=>import("./vendor-xterm-BNq00GSj.js").then(d=>d.x),__vite__mapDeps([0,1,2])),K(()=>import("./addon-fit-C1WQXRvu.js").then(d=>d.a),__vite__mapDeps([3,1])),K(()=>import("./addon-unicode11-D3Fsv-Po.js"),[])]);if(e||!x.current)return;const S=z(),A=de(S.fontFamily);x.current.style.setProperty("--terminal-glyph-font-family",J(S.fontFamily));const s=new ge({convertEol:!1,cursorBlink:S.cursorBlink&&w,cursorStyle:S.cursorStyle,disableStdin:!w,scrollback:$e,fontFamily:A,fontSize:S.fontSize}),L=new xe;s.loadAddon(L);const Re=new Ne;if(s.loadAddon(Re),s.unicode.activeVersion="11",Fe(()=>{s.open(x.current)}),v.current=s,N.current=L,S.renderer==="auto"&&!Y())try{const{WebglAddon:d}=await K(async()=>{const{WebglAddon:u}=await import("./addon-webgl-uLc0RKcC.js").then(C=>C.a);return{WebglAddon:u}},__vite__mapDeps([4,1]));if(!e){const u=new d;u.onContextLoss(()=>{try{u.dispose()}catch{}R.current===u&&(R.current=null)}),s.loadAddon(u),R.current=u}}catch{}try{L.fit()}catch{}(async()=>{if(!(!await ue(S.fontSize,A)||e||v.current!==s||N.current!==L||s.options.fontSize!==S.fontSize||s.options.fontFamily!==A))try{F(s,A),s.options.fontSize=S.fontSize,L.fit(),Q(s.cols,s.rows),F(s,A),s.refresh(0,Math.max(0,s.rows-1))}catch{}})(),w&&(s.onData(d=>{const u=h.current;u?.readyState===WebSocket.OPEN&&u.send(JSON.stringify({type:"input",data:d}))}),s.attachCustomKeyEventHandler(d=>{if(d.type!=="keydown"||!(et()?d.metaKey:d.ctrlKey)||d.altKey||d.shiftKey)return!0;const C=d.key.toLowerCase();if(C==="c"){const T=s.hasSelection()?s.getSelection():"";return T?(navigator.clipboard?.writeText(T).catch(()=>{}),!1):!0}if(C==="v"){const T=navigator.clipboard?.readText;return T&&T.call(navigator.clipboard).then(le=>{if(!le)return;const ce=h.current;ce?.readyState===WebSocket.OPEN&&ce.send(JSON.stringify({type:"input",data:le}))}).catch(()=>{}),!1}return!0})),n=new ResizeObserver(()=>{l&&clearTimeout(l),l=setTimeout(()=>{try{L.fit(),Q(s.cols,s.rows),s.refresh(0,Math.max(0,s.rows-1))}catch{}},Ue)}),n.observe(x.current);const V=new WebSocket(Xe(m,p.ticket));h.current=V,V.onopen=()=>{Q(s.cols,s.rows)},V.onmessage=d=>{let u;try{u=JSON.parse(typeof d.data=="string"?d.data:"")}catch{return}switch(u.type){case"scrollback":case"data":{if(typeof u.data!="string")return;const C=tt(u.data),T=C.length;s.write(C,()=>Te(T));break}}}})(),()=>{e=!0,l&&clearTimeout(l),n&&n.disconnect();const p=h.current;if(p){p.onopen=null,p.onmessage=null,p.onclose=null,p.onerror=null;try{p.close()}catch{}h.current=null}if(R.current){try{R.current.dispose()}catch{}R.current=null}const w=v.current;if(w){try{w.dispose()}catch{}v.current=null}N.current=null}},[m,f,r,y,E,_e]);const re=i.useMemo(()=>r==="idle"?a("cliTerminal.replayIdle","Session idle"):r==="ended"?a("cliTerminal.replayEnded","Session ended"):null,[r,a]),ve=i.useCallback(async()=>{if(g){ee(!0);try{await g("advance"),U(!0)}finally{ee(!1)}}},[g]),Ee=i.useCallback(async()=>{g&&await g("not-yet"),U(!0)},[g]),I=!!o?.elevated,ae=o?.elevatedFlags?.join(", "),Ce={"--terminal-glyph-font-family":J(z().fontFamily)};return t.jsxs("div",{className:`cli-session-terminal${P?" cli-session-terminal--mobile":""}${P&&B?" cli-session-terminal--keyboard-open":""}`,"data-mode":r,"data-read-only":se,"data-mobile":P,"data-keyboard-open":P&&B,children:[t.jsxs("header",{className:"cli-session-terminal__header",children:[o&&t.jsxs("div",{className:"cli-session-terminal__posture-wrap",children:[t.jsxs("button",{type:"button",className:`cli-posture-chip${I?" cli-posture-chip--elevated":""}`,"data-elevated":I,"aria-expanded":q,onClick:()=>Z(e=>!e),children:[I?t.jsx(Ke,{size:13,"aria-hidden":"true"}):t.jsx(je,{size:13,"aria-hidden":"true"}),t.jsx("span",{className:"cli-posture-chip__name",children:o.adapterName}),o.mode&&t.jsx("span",{className:"cli-posture-chip__mode",children:o.mode}),I&&ae&&t.jsx("span",{className:"cli-posture-chip__flag",children:ae})]}),q&&t.jsxs("div",{className:"cli-posture-tooltip",role:"tooltip",children:[t.jsx("p",{className:"cli-posture-tooltip__title",children:a("cliTerminal.postureResolved","Resolved posture")}),t.jsxs("ul",{className:"cli-posture-tooltip__list",children:[(o.resolved??[]).map((e,n)=>t.jsx("li",{children:e},n)),(o.resolved??[]).length===0&&t.jsx("li",{children:o.mode??a("cliTerminal.postureBaseline","Baseline")})]}),G&&t.jsxs("button",{type:"button",className:"cli-posture-tooltip__settings",onClick:()=>{Z(!1),G()},children:[t.jsx(Me,{size:12,"aria-hidden":"true"}),a("cliTerminal.adapterSettings","Adapter settings")]})]})]}),se&&t.jsxs("span",{className:"cli-session-terminal__readonly-badge",children:[t.jsx(Le,{size:12,"aria-hidden":"true"}),a("cliTerminal.readOnly","Read-only")]}),re&&t.jsx("span",{className:"cli-session-terminal__replay-badge","data-replay-mode":r,children:re})]}),t.jsx("div",{className:"cli-session-terminal__viewport-shell",children:t.jsx("div",{className:"cli-session-terminal__viewport",ref:x,"data-testid":"cli-terminal-viewport",style:Ce})}),$&&!fe&&t.jsxs("div",{className:"cli-session-terminal__advance-strip",role:"region",children:[t.jsx("span",{className:"cli-session-terminal__advance-copy",children:a("cliTerminal.advancePrompt","This session looks idle — advance to review?")}),t.jsxs("div",{className:"cli-session-terminal__advance-actions",children:[t.jsx("button",{type:"button",className:"cli-session-terminal__advance-btn",disabled:X,onClick:ve,children:a("cliTerminal.advance","Advance")}),t.jsx("button",{type:"button",className:"cli-session-terminal__advance-btn cli-session-terminal__advance-btn--secondary",disabled:X,onClick:Ee,children:a("cliTerminal.notYet","Not yet")})]})]}),P&&O&&t.jsxs("div",{className:`cli-session-terminal__mobile-bar${B?" cli-session-terminal__mobile-bar--keyboard-open":""}`,"data-testid":"cli-terminal-mobile-bar",style:B?{bottom:`${pe}px`}:void 0,children:[t.jsxs("div",{className:"cli-session-terminal__key-row","data-testid":"cli-terminal-key-bar",children:[t.jsx("button",{type:"button",className:`cli-terminal-key cli-terminal-key--ctrl${j?" cli-terminal-key--active":""}`,"data-testid":"cli-key-ctrl","aria-label":a("cliTerminal.mobileKeyCtrl","Sticky Ctrl modifier"),"aria-pressed":j,onPointerDown:c,onMouseDown:c,onClick:()=>D(e=>!e),children:W.ctrl}),t.jsx("button",{type:"button",className:"cli-terminal-key","data-testid":"cli-key-esc","aria-label":a("cliTerminal.mobileKeyEsc","Send Escape"),onPointerDown:c,onMouseDown:c,onClick:()=>M(Qe),children:W.escape}),t.jsx("button",{type:"button",className:"cli-terminal-key","data-testid":"cli-key-tab","aria-label":a("cliTerminal.mobileKeyTab","Send Tab"),onPointerDown:c,onMouseDown:c,onClick:()=>M(Ve),children:W.tab}),t.jsx("button",{type:"button",className:"cli-terminal-key cli-terminal-key--ctrlc","data-testid":"cli-key-ctrl-c","aria-label":a("cliTerminal.mobileKeyCtrlC","Send Ctrl-C"),onPointerDown:c,onMouseDown:c,onClick:()=>{D(!1),b(Je)},children:W.ctrlC}),t.jsx("button",{type:"button",className:"cli-terminal-key","data-testid":"cli-key-arrow-up","aria-label":a("cliTerminal.mobileKeyArrowUp","Cursor up"),onPointerDown:c,onMouseDown:c,onClick:()=>M(Ye),children:"↑"}),t.jsx("button",{type:"button",className:"cli-terminal-key","data-testid":"cli-key-arrow-down","aria-label":a("cliTerminal.mobileKeyArrowDown","Cursor down"),onPointerDown:c,onMouseDown:c,onClick:()=>M(Ge),children:"↓"}),t.jsx("button",{type:"button",className:"cli-terminal-key","data-testid":"cli-key-arrow-left","aria-label":a("cliTerminal.mobileKeyArrowLeft","Cursor left"),onPointerDown:c,onMouseDown:c,onClick:()=>M(qe),children:"←"}),t.jsx("button",{type:"button",className:"cli-terminal-key","data-testid":"cli-key-arrow-right","aria-label":a("cliTerminal.mobileKeyArrowRight","Cursor right"),onPointerDown:c,onMouseDown:c,onClick:()=>M(He),children:"→"}),be.map(e=>t.jsx("button",{type:"button",className:"cli-terminal-key cli-terminal-key--custom","data-testid":`cli-terminal-custom-shortcut-${e.id}`,title:e.label,"aria-label":e.label,onPointerDown:c,onMouseDown:c,onClick:()=>{D(!1),b(De(e.value))},children:e.label},e.id))]}),t.jsxs("form",{className:"cli-session-terminal__input-row",onSubmit:we,children:[t.jsx("input",{ref:ye,type:"text",className:"cli-session-terminal__mobile-input","data-testid":"cli-terminal-mobile-input",value:_,placeholder:a("cliTerminal.mobileInputPlaceholder","Type to send to the session…"),autoCapitalize:"off",autoCorrect:"off",autoComplete:"off",spellCheck:!1,onChange:e=>Se(e.target.value)}),t.jsx("button",{type:"submit",className:"cli-session-terminal__mobile-send","data-testid":"cli-terminal-mobile-send","aria-label":a("cliTerminal.mobileSend","Send"),onPointerDown:c,onMouseDown:c,children:a("cliTerminal.mobileSend","Send")})]})]})]})}export{ut as SessionTerminal};