@runfusion/fusion 0.77.0-beta.6 → 0.77.0-beta.7

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 (166) hide show
  1. package/dist/bin.js +42309 -39335
  2. package/dist/child-process-worker.js +7394 -4875
  3. package/dist/client/.vite/manifest.json +267 -330
  4. package/dist/client/assets/{AgentDetailView-oyY72uSo.js → AgentDetailView-C1eh_vXv.js} +4 -4
  5. package/dist/client/assets/{AgentPermissionPolicyEditor-C3Qo9p1M.js → AgentPermissionPolicyEditor-CeKsO1LR.js} +2 -2
  6. package/dist/client/assets/{AgentsView-M2MhTIGW.js → AgentsView-BNe2ABOc.js} +4 -4
  7. package/dist/client/assets/{CommandCenter-CpcAt6jt.js → CommandCenter-BuREM-G1.js} +18 -18
  8. package/dist/client/assets/DevServerView-D0i1b-QO.js +1 -0
  9. package/dist/client/assets/DirectoryPicker-VOx91hQt.js +1 -0
  10. package/dist/client/assets/DocumentsView-CO5W_WVb.js +1 -0
  11. package/dist/client/assets/EvalsView-BqSINSrZ.js +1 -0
  12. package/dist/client/assets/ExperimentalAgentOnboardingModal-DEcFgONi.js +1 -0
  13. package/dist/client/assets/{GoalsView-DPj59B3l.js → GoalsView-DZ57wXmJ.js} +1 -1
  14. package/dist/client/assets/{InsightsView-QLJNkKJp.js → InsightsView-DSWfXG7Q.js} +3 -3
  15. package/dist/client/assets/{MemoryView-CDCS-1ig.js → MemoryView-BEX10uhl.js} +1 -1
  16. package/dist/client/assets/{PiExtensionsManager-DktXXrmF.js → PiExtensionsManager-DcAmXXoR.js} +2 -2
  17. package/dist/client/assets/PluginManager-BU0omQUv.js +1 -0
  18. package/dist/client/assets/{PullRequestView-CkObT6e3.js → PullRequestView-B-JL_8Kk.js} +2 -2
  19. package/dist/client/assets/{ReportModal-B5LTdDgi.js → ReportModal-DxggF_RH.js} +5 -5
  20. package/dist/client/assets/{ResearchView-CryFrV8l.js → ResearchView-CnwTXfQO.js} +1 -1
  21. package/dist/client/assets/{SecretsView-9YcNW_fo.js → SecretsView-BDvzsLFz.js} +1 -1
  22. package/dist/client/assets/SettingsModal-801eFQ9u.js +21 -0
  23. package/dist/client/assets/{SettingsModal-llkoaJev.js → SettingsModal-BZHeQ3ED.js} +1 -1
  24. package/dist/client/assets/{SettingsTextareaRow-B_Legu-A.js → SettingsTextareaRow-B0rTuelr.js} +1 -1
  25. package/dist/client/assets/SetupWizardModal-CoExPwIn.js +2 -0
  26. package/dist/client/assets/{SkillsView-CSeauwIw.js → SkillsView-WVP25LPj.js} +1 -1
  27. package/dist/client/assets/WorkflowNodeEditor-pCMyKcnS.js +8 -0
  28. package/dist/client/assets/{agent-import-generation-CttglSmZ.js → agent-import-generation-M_hKtjgN.js} +1 -1
  29. package/dist/client/assets/{agentsOrgChartLayout-f-9mwRbD.js → agentsOrgChartLayout-DjvIMhFD.js} +1 -1
  30. package/dist/client/assets/{app-C_PTWuI1.js → app-BOvA34XN.js} +3 -3
  31. package/dist/client/assets/{app-BBSLJDbV.js → app-Bic4iWXQ.js} +3 -3
  32. package/dist/client/assets/{app-Bvr57EZQ.js → app-BlbH7Tir.js} +2 -2
  33. package/dist/client/assets/{app-DwvelD-n.js → app-C6TctczU.js} +3 -3
  34. package/dist/client/assets/{app-DRW5hIgr.js → app-D3qZmEIu.js} +3 -3
  35. package/dist/client/assets/{app-BKwOvuxE.js → app-DLnMkUt5.js} +2 -2
  36. package/dist/client/assets/{app-DKx18PHE.js → app-mNy0DeDM.js} +3 -3
  37. package/dist/client/assets/{architectureDiagram-3BPJPVTR-DA_Hm_di.js → architectureDiagram-3BPJPVTR-CkzEm8i9.js} +1 -1
  38. package/dist/client/assets/{blockDiagram-GPEHLZMM-JF7K8CcV.js → blockDiagram-GPEHLZMM-Dc-dUMjY.js} +1 -1
  39. package/dist/client/assets/{c4Diagram-AAUBKEIU-DN-wklCP.js → c4Diagram-AAUBKEIU-DnYjsrR0.js} +1 -1
  40. package/dist/client/assets/channel-CxQ40s_U.js +1 -0
  41. package/dist/client/assets/{chunk-2J33WTMH-ChtjU8Cu.js → chunk-2J33WTMH-0E1GEFEr.js} +1 -1
  42. package/dist/client/assets/{chunk-4BX2VUAB-dJL0n3nn.js → chunk-4BX2VUAB-Dj5oZd51.js} +1 -1
  43. package/dist/client/assets/{chunk-55IACEB6-Bfg-QB9A.js → chunk-55IACEB6-DfNT0s8E.js} +1 -1
  44. package/dist/client/assets/{chunk-727SXJPM-BHPPwYUS.js → chunk-727SXJPM-BnFjhiIQ.js} +1 -1
  45. package/dist/client/assets/{chunk-AQP2D5EJ-DIIpPUQN.js → chunk-AQP2D5EJ-DR84wSqR.js} +1 -1
  46. package/dist/client/assets/{chunk-FMBD7UC4-D230R32b.js → chunk-FMBD7UC4-IjByNOrR.js} +1 -1
  47. package/dist/client/assets/{chunk-ND2GUHAM-0Lhp5CRv.js → chunk-ND2GUHAM-By0q_jZm.js} +1 -1
  48. package/dist/client/assets/{chunk-QZHKN3VN-BxbHBfKJ.js → chunk-QZHKN3VN-BELcl3N5.js} +1 -1
  49. package/dist/client/assets/classDiagram-4FO5ZUOK-C2ARdiRL.js +1 -0
  50. package/dist/client/assets/classDiagram-v2-Q7XG4LA2-C2ARdiRL.js +1 -0
  51. package/dist/client/assets/{common-13IRj_PO.js → common-BsNuuNOe.js} +1 -1
  52. package/dist/client/assets/{common-BBynATth.js → common-CASsTuSW.js} +1 -1
  53. package/dist/client/assets/{common-BG-vw0tL.js → common-CfyFt5OG.js} +1 -1
  54. package/dist/client/assets/{common-DSo46rnH.js → common-DS98trLj.js} +1 -1
  55. package/dist/client/assets/common-DeoHWJCq.js +1 -0
  56. package/dist/client/assets/common-PpMdoH5r.js +1 -0
  57. package/dist/client/assets/{common-vpHuuvkd.js → common-cN--mrmm.js} +1 -1
  58. package/dist/client/assets/{cose-bilkent-S5V4N54A-3vEwhfYz.js → cose-bilkent-S5V4N54A-D4cCw9-_.js} +1 -1
  59. package/dist/client/assets/{dagre-BM42HDAG-Br44UsdY.js → dagre-BM42HDAG-JJp5dVeY.js} +1 -1
  60. package/dist/client/assets/dashboard-view-6zPJm9zC.js +1 -0
  61. package/dist/client/assets/{dashboard-view-_EglxMDl.js → dashboard-view-Bl9CPhxE.js} +1 -1
  62. package/dist/client/assets/{dashboard-view-BldxxYfz.js → dashboard-view-C5Nt8cvY.js} +1 -1
  63. package/dist/client/assets/{dashboard-view-CcPcELPx.js → dashboard-view-MAC_LHDX.js} +2 -2
  64. package/dist/client/assets/{diagram-2AECGRRQ-CLNxbHUP.js → diagram-2AECGRRQ-D4L7j_t_.js} +1 -1
  65. package/dist/client/assets/{diagram-5GNKFQAL-D3cNAeQH.js → diagram-5GNKFQAL-VAGFaXqG.js} +1 -1
  66. package/dist/client/assets/{diagram-KO2AKTUF-DkX7h6to.js → diagram-KO2AKTUF-hqXSggfW.js} +1 -1
  67. package/dist/client/assets/{diagram-LMA3HP47-6iQIiYUr.js → diagram-LMA3HP47-B3eAIuy8.js} +1 -1
  68. package/dist/client/assets/{diagram-OG6HWLK6-Caje3229.js → diagram-OG6HWLK6-BGufp0RK.js} +1 -1
  69. package/dist/client/assets/{erDiagram-TEJ5UH35-BkU-1HB1.js → erDiagram-TEJ5UH35-DplXdx8w.js} +1 -1
  70. package/dist/client/assets/{flowDiagram-I6XJVG4X-BRx3V6RE.js → flowDiagram-I6XJVG4X-C1Ms2bko.js} +1 -1
  71. package/dist/client/assets/{folder-open-BaSOBfk2.js → folder-open-nMraSDXu.js} +1 -1
  72. package/dist/client/assets/{ganttDiagram-6RSMTGT7-D9f1kH3t.js → ganttDiagram-6RSMTGT7-DVgxMtXb.js} +1 -1
  73. package/dist/client/assets/{gitGraphDiagram-PVQCEYII-CQwmZcRd.js → gitGraphDiagram-PVQCEYII-DH2_n0J8.js} +1 -1
  74. package/dist/client/assets/index-BJc-A7eB.css +1 -0
  75. package/dist/client/assets/index-CBFPgFTp.js +2787 -0
  76. package/dist/client/assets/{infoDiagram-5YYISTIA-DYWBkGjG.js → infoDiagram-5YYISTIA-DmZdWVcU.js} +1 -1
  77. package/dist/client/assets/{ishikawaDiagram-YF4QCWOH-Df0Nzvh4.js → ishikawaDiagram-YF4QCWOH-DsEIHSXr.js} +1 -1
  78. package/dist/client/assets/{journeyDiagram-JHISSGLW-bSvrZSyZ.js → journeyDiagram-JHISSGLW-CsfIWmu1.js} +1 -1
  79. package/dist/client/assets/{kanban-definition-UN3LZRKU-yHJ101M8.js → kanban-definition-UN3LZRKU-CQKqeZvc.js} +1 -1
  80. package/dist/client/assets/{mermaid.core-Bc_0VLJw.js → mermaid.core-DkC_dr4-.js} +4 -4
  81. package/dist/client/assets/{mindmap-definition-RKZ34NQL-DWRnMguM.js → mindmap-definition-RKZ34NQL-RnmE-NUe.js} +1 -1
  82. package/dist/client/assets/{pieDiagram-4H26LBE5-Ds-DEOqr.js → pieDiagram-4H26LBE5-DPu6FPc4.js} +1 -1
  83. package/dist/client/assets/{puzzle-CdYF81IT.js → puzzle-DwhHOf32.js} +1 -1
  84. package/dist/client/assets/{quadrantDiagram-W4KKPZXB-Bz-j2fkf.js → quadrantDiagram-W4KKPZXB-CYbypO2p.js} +1 -1
  85. package/dist/client/assets/{requirementDiagram-4Y6WPE33-BaQ_PaZ-.js → requirementDiagram-4Y6WPE33-DFk1vK_N.js} +1 -1
  86. package/dist/client/assets/{sankeyDiagram-5OEKKPKP-pUCz8V4-.js → sankeyDiagram-5OEKKPKP-CkUY1Zzu.js} +1 -1
  87. package/dist/client/assets/{sequenceDiagram-3UESZ5HK-CFwUMspe.js → sequenceDiagram-3UESZ5HK-CFivaLOO.js} +1 -1
  88. package/dist/client/assets/{standing-instructions-template-Crocrob7.js → standing-instructions-template-BbqKGAC1.js} +2 -2
  89. package/dist/client/assets/{stateDiagram-AJRCARHV-CHZwo-vd.js → stateDiagram-AJRCARHV-BPeD5PwG.js} +1 -1
  90. package/dist/client/assets/{stateDiagram-v2-BHNVJYJU-BTvKaIZR.js → stateDiagram-v2-BHNVJYJU-DduiCPMb.js} +1 -1
  91. package/dist/client/assets/{timeline-definition-PNZ67QCA-Cn3XIoz2.js → timeline-definition-PNZ67QCA-CGUNNVro.js} +1 -1
  92. package/dist/client/assets/{upload--GqImz6h.js → upload-BS96H1o7.js} +1 -1
  93. package/dist/client/assets/{users-B0h1q4x6.js → users--irrWoyU.js} +1 -1
  94. package/dist/client/assets/{vennDiagram-CIIHVFJN-CS0FNVU_.js → vennDiagram-CIIHVFJN-CybTaJJH.js} +1 -1
  95. package/dist/client/assets/{wardley-L42UT6IY-DdYkfF5d.js → wardley-L42UT6IY-DSxaSCGi.js} +1 -1
  96. package/dist/client/assets/{wardleyDiagram-YWT4CUSO-B_rFmPCh.js → wardleyDiagram-YWT4CUSO-YFb0AxNt.js} +1 -1
  97. package/dist/client/assets/{xychartDiagram-2RQKCTM6-CCoaCgmc.js → xychartDiagram-2RQKCTM6-Cv6zlMJC.js} +1 -1
  98. package/dist/client/index.html +2 -2
  99. package/dist/client/version.json +1 -1
  100. package/dist/droid-cli/package.json +1 -1
  101. package/dist/extension.js +23565 -20733
  102. package/dist/migrations/0065_fn_149_review_convergence_stage.sql +3 -0
  103. package/dist/pi-claude-cli/package.json +1 -1
  104. package/dist/plugin-sdk/index.d.ts +57 -10
  105. package/dist/plugin-sdk/index.js +103 -33
  106. package/dist/plugins/fusion-plugin-acp-runtime/bundled.js +158 -36
  107. package/dist/plugins/fusion-plugin-acp-runtime/package.json +1 -1
  108. package/dist/plugins/fusion-plugin-claude-runtime/bundled.js +103 -33
  109. package/dist/plugins/fusion-plugin-claude-runtime/package.json +1 -1
  110. package/dist/plugins/fusion-plugin-cli-printing-press/bundled.js +103 -33
  111. package/dist/plugins/fusion-plugin-cli-printing-press/package.json +1 -1
  112. package/dist/plugins/fusion-plugin-compound-engineering/bundled.js +103 -33
  113. package/dist/plugins/fusion-plugin-compound-engineering/package.json +1 -1
  114. package/dist/plugins/fusion-plugin-cursor-runtime/bundled.js +103 -33
  115. package/dist/plugins/fusion-plugin-cursor-runtime/package.json +1 -1
  116. package/dist/plugins/fusion-plugin-dependency-graph/bundled.js +103 -33
  117. package/dist/plugins/fusion-plugin-dependency-graph/package.json +1 -1
  118. package/dist/plugins/fusion-plugin-droid-runtime/bundled.js +103 -33
  119. package/dist/plugins/fusion-plugin-droid-runtime/package.json +1 -1
  120. package/dist/plugins/fusion-plugin-grok-runtime/bundled.js +103 -33
  121. package/dist/plugins/fusion-plugin-grok-runtime/package.json +1 -1
  122. package/dist/plugins/fusion-plugin-hermes-runtime/bundled.js +103 -33
  123. package/dist/plugins/fusion-plugin-hermes-runtime/package.json +1 -1
  124. package/dist/plugins/fusion-plugin-linear-import/bundled.js +103 -33
  125. package/dist/plugins/fusion-plugin-linear-import/package.json +1 -1
  126. package/dist/plugins/fusion-plugin-omp-runtime/bundled.js +103 -33
  127. package/dist/plugins/fusion-plugin-omp-runtime/package.json +1 -1
  128. package/dist/plugins/fusion-plugin-openclaw-runtime/bundled.js +103 -33
  129. package/dist/plugins/fusion-plugin-openclaw-runtime/package.json +1 -1
  130. package/dist/plugins/fusion-plugin-paperclip-runtime/bundled.js +103 -33
  131. package/dist/plugins/fusion-plugin-paperclip-runtime/package.json +1 -1
  132. package/dist/plugins/fusion-plugin-quality/bundled.js +103 -33
  133. package/dist/plugins/fusion-plugin-quality/package.json +1 -1
  134. package/dist/plugins/fusion-plugin-reports/bundled.js +103 -33
  135. package/dist/plugins/fusion-plugin-reports/package.json +1 -1
  136. package/dist/plugins/fusion-plugin-roadmap/bundled.js +103 -33
  137. package/dist/plugins/fusion-plugin-roadmap/package.json +1 -1
  138. package/dist/plugins/fusion-plugin-todos/bundled.js +103 -33
  139. package/dist/plugins/fusion-plugin-todos/package.json +1 -1
  140. package/dist/plugins/fusion-plugin-whatsapp-chat/bundled.js +103 -33
  141. package/dist/plugins/fusion-plugin-whatsapp-chat/package.json +1 -1
  142. package/package.json +1 -1
  143. package/skill/fusion/references/engine-tools.md +5 -5
  144. package/dist/client/assets/ChatView-DS4XiCm_.css +0 -1
  145. package/dist/client/assets/ChatView-zKrUSqiQ.js +0 -13
  146. package/dist/client/assets/DevServerView-CjTneoG7.js +0 -1
  147. package/dist/client/assets/DirectoryPicker-BY6V5HLV.js +0 -1
  148. package/dist/client/assets/DocumentsView-RDK56-qg.js +0 -1
  149. package/dist/client/assets/EvalsView-DKK4ceUW.js +0 -1
  150. package/dist/client/assets/ExperimentalAgentOnboardingModal-DiBPZVwC.js +0 -1
  151. package/dist/client/assets/PluginManager-CQ3iEFMq.js +0 -1
  152. package/dist/client/assets/SessionTerminal-2ZSXmOkG.css +0 -1
  153. package/dist/client/assets/SessionTerminal-BWsA9puD.js +0 -2
  154. package/dist/client/assets/SettingsModal-CL6aiXiI.js +0 -21
  155. package/dist/client/assets/SetupWizardModal-DLA4UAGp.js +0 -2
  156. package/dist/client/assets/WorkflowNodeEditor-CGgMiiWy.js +0 -8
  157. package/dist/client/assets/channel-CwFfFSI9.js +0 -1
  158. package/dist/client/assets/classDiagram-4FO5ZUOK-C8dZsxxX.js +0 -1
  159. package/dist/client/assets/classDiagram-v2-Q7XG4LA2-C8dZsxxX.js +0 -1
  160. package/dist/client/assets/common-DbOCE-0i.js +0 -1
  161. package/dist/client/assets/common-DnXF4Jmj.js +0 -1
  162. package/dist/client/assets/dashboard-view-B0OM3KYC.js +0 -1
  163. package/dist/client/assets/index-B8PcG8AJ.js +0 -2774
  164. package/dist/client/assets/index-Dki2LBAp.css +0 -1
  165. package/dist/client/assets/shield-alert-4qeU3_Rm.js +0 -6
  166. package/dist/client/assets/useDiscoveredSkillsCache-BEHgTFai.js +0 -1
@@ -0,0 +1 @@
1
+ import{r as n,j as r}from"./vendor-react-SZ_qB27O.js";import{a as z,w as T,d1 as ar,b5 as ir,aK as Or,cP as le,L as ge,au as Fr,d2 as zr,d3 as $r,d4 as Hr,C as Br,d5 as or,aP as lr,d6 as me,d7 as Vr,d8 as Wr,d9 as Ir,V as qr,da as Jr,bJ as Xr,bM as Kr,db as Gr,p as We,X as Yr,aF as Qr,R as Zr}from"./index-CBFPgFTp.js";import{u as we}from"./vendor-i18n-Duky4gdQ.js";import"./vendor-codemirror-CcrtqoCy.js";import"./vendor-reactflow-BlIeoTu4.js";import"./vendor-xterm-BNq00GSj.js";function Ie(e){const t=typeof e.source=="string"&&e.source.trim().length>0?e.source.trim():"root",s=t==="root"?".":t,i=e.name,a=typeof e.packagePath=="string"&&e.packagePath.trim().length>0?e.packagePath.trim():s,u=typeof e.confidence=="number"?e.confidence:1,f=t==="root"?"root":t,m=typeof e.packageName=="string"&&e.packageName.trim().length>0?e.packageName.trim():"project";return{name:e.name,command:e.command,scriptName:i,packagePath:a,confidence:u,cwd:s,source:t,workspaceName:typeof e.packageName=="string"?e.packageName:void 0,label:`${m} · ${i} (${f})`}}function se(e){const t=e.status,s=t==="starting"||t==="running"||t==="failed"||t==="stopped"?t:"stopped",i=typeof e.previewUrl=="string"?e.previewUrl:e.detectedUrl,a=typeof e.manualPreviewUrl=="string"?e.manualPreviewUrl:e.manualUrl;return{id:typeof e.id=="string"?e.id:"",name:typeof e.name=="string"&&e.name.length>0?e.name:"default",status:s,command:typeof e.command=="string"?e.command:"",scriptName:typeof e.scriptId=="string"?e.scriptId:"",cwd:typeof e.cwd=="string"?e.cwd:"",pid:e.pid,startedAt:e.startedAt,previewUrl:i,detectedUrl:typeof e.detectedUrl=="string"?e.detectedUrl:i,detectedPort:e.detectedPort,manualPreviewUrl:a,manualUrl:typeof e.manualUrl=="string"?e.manualUrl:a,logs:Array.isArray(e.logHistory)?e.logHistory:[],exitCode:e.exitCode}}function et(e,t){return{id:typeof e.id=="number"&&Number.isFinite(e.id)?e.id:t,text:typeof e.text=="string"?e.text:typeof e.line=="string"?e.line:"",stream:e.stream==="stderr"?"stderr":"stdout",timestamp:typeof e.timestamp=="string"?e.timestamp:""}}function rt(e){const s=(Array.isArray(e.lines)?e.lines:[]).map((i,a)=>et(i,a+1));return{lines:s,totalLines:typeof e.totalLines=="number"&&Number.isFinite(e.totalLines)?e.totalLines:s.length}}function tt(e,t){const s=typeof t.maxLines=="number"&&Number.isFinite(t.maxLines)?Math.max(1,Math.floor(t.maxLines)):100,i=typeof t.offset=="number"&&Number.isFinite(t.offset)?Math.max(0,Math.floor(t.offset)):0,a=typeof t.lastEventId=="number"&&Number.isFinite(t.lastEventId)?Math.max(0,Math.floor(t.lastEventId)):null,u=e.length,f=e.map((N,$)=>({id:$+1,text:N,stream:"stdout",timestamp:""}));if(a!==null)return{lines:f.filter(N=>N.id>a).slice(0,s),totalLines:u};const m=Math.max(u-i,0),C=Math.max(m-s,0);return{lines:f.slice(C,m),totalLines:u}}function qe(e){return Array.isArray(e)?e.map(Ie):(e.candidates??[]).map(Ie)}async function cr(e){try{const t=await z(T("/dev-server/candidates",e));return qe(t)}catch(t){if(t instanceof Error&&/\/dev-server\/candidates/.test(t.message)){const s=await z(T("/dev-server/detect",e));return qe(s)}throw t}}function be(e){return z(T("/dev-server/status",e)).then(se)}async function Ee(e={},t){const s=new URLSearchParams;typeof e.maxLines=="number"&&Number.isFinite(e.maxLines)&&s.set("maxLines",String(Math.max(1,Math.floor(e.maxLines)))),typeof e.offset=="number"&&Number.isFinite(e.offset)&&s.set("offset",String(Math.max(0,Math.floor(e.offset)))),typeof e.lastEventId=="number"&&Number.isFinite(e.lastEventId)&&s.set("lastEventId",String(Math.max(0,Math.floor(e.lastEventId))));const i=s.size>0?`?${s.toString()}`:"";try{const a=await z(T(`/dev-server/logs/history${i}`,t));return rt(a)}catch(a){if(a instanceof Error&&/\/dev-server\/logs\/history/.test(a.message)){const u=await be(t);return tt(u.logs,e)}throw a}}function dr(e,t){const s=e.cwd??e.packagePath??".",i=e.scriptName;return z(T("/dev-server/start",t),{method:"POST",body:JSON.stringify({command:e.command,scriptName:i,scriptId:i,cwd:s,packagePath:e.packagePath})}).then(se)}function vr(e){return z(T("/dev-server/stop",e),{method:"POST"}).then(se)}function ur(e){return z(T("/dev-server/restart",e),{method:"POST"}).then(se)}async function mr(e,t){const s=typeof e=="string"?{url:e}:e;try{const i=await z(T("/dev-server/preview-url",t),{method:"POST",body:JSON.stringify(s)});return se(i)}catch(i){if(i instanceof Error&&/\/dev-server\/preview-url/.test(i.message)){const a=await z(T("/dev-server/preview-url",t),{method:"PUT",body:JSON.stringify(s)});return se(a)}throw i}}function Pe(e){return ar(T("/dev-server/logs/stream",e))}async function Me(e){try{return(await z(T("/devserver",e))).sessions??[]}catch{try{const t=await be(e);return[{config:{id:t.id??"default",name:t.name??"Dev Server",command:t.command??"",cwd:t.cwd??"."},status:t.status,runtime:t.pid?{pid:t.pid,startedAt:t.startedAt??new Date().toISOString(),exitCode:t.exitCode??void 0,previewUrl:t.previewUrl}:void 0,previewUrl:t.previewUrl??t.detectedUrl??void 0,logHistory:(t.logs??[]).map(i=>({timestamp:new Date().toISOString(),stream:i.startsWith("[stderr]")?"stderr":"stdout",text:i.replace(/^\[stderr\]\s*/,"")}))}]}catch{return[]}}}async function pr(e,t){try{return await z(T(`/devserver/${encodeURIComponent(e)}`,t))}catch{try{const s=await be(t);return!e||e==="default"||e===s.id?{config:{id:s.id??"default",name:s.name??"Dev Server",command:s.command??"",cwd:s.cwd??"."},status:s.status,runtime:s.pid?{pid:s.pid,startedAt:s.startedAt??new Date().toISOString(),exitCode:s.exitCode??void 0,previewUrl:s.previewUrl}:void 0,previewUrl:s.previewUrl??s.detectedUrl??void 0,logHistory:(s.logs??[]).map(i=>({timestamp:new Date().toISOString(),stream:i.startsWith("[stderr]")?"stderr":"stdout",text:i.replace(/^\[stderr\]\s*/,"")}))}:null}catch{return null}}}async function Je(e,t){try{return await z(T(`/devserver/${encodeURIComponent(e)}/start`,t),{method:"POST"})}catch{const s=await dr({command:""},t);return{config:{id:s.id??e,name:s.name??"Dev Server",command:s.command??"",cwd:s.cwd??"."},status:s.status,runtime:s.pid?{pid:s.pid,startedAt:s.startedAt??new Date().toISOString(),exitCode:s.exitCode??void 0,previewUrl:s.previewUrl}:void 0,previewUrl:s.previewUrl??s.detectedUrl??void 0,logHistory:(s.logs??[]).map(i=>({timestamp:new Date().toISOString(),stream:i.startsWith("[stderr]")?"stderr":"stdout",text:i.replace(/^\[stderr\]\s*/,"")}))}}}async function Xe(e,t){try{return await z(T(`/devserver/${encodeURIComponent(e)}/stop`,t),{method:"POST"})}catch{const s=await vr(t);return{config:{id:s.id??e,name:s.name??"Dev Server",command:s.command??"",cwd:s.cwd??"."},status:s.status,runtime:s.pid?{pid:s.pid,startedAt:s.startedAt??new Date().toISOString(),exitCode:s.exitCode??void 0,previewUrl:s.previewUrl}:void 0,previewUrl:s.previewUrl??s.detectedUrl??void 0,logHistory:(s.logs??[]).map(i=>({timestamp:new Date().toISOString(),stream:i.startsWith("[stderr]")?"stderr":"stdout",text:i.replace(/^\[stderr\]\s*/,"")}))}}}async function Ke(e,t){try{return await z(T(`/devserver/${encodeURIComponent(e)}/restart`,t),{method:"POST"})}catch{const s=await ur(t);return{config:{id:s.id??e,name:s.name??"Dev Server",command:s.command??"",cwd:s.cwd??"."},status:s.status,runtime:s.pid?{pid:s.pid,startedAt:s.startedAt??new Date().toISOString(),exitCode:s.exitCode??void 0,previewUrl:s.previewUrl}:void 0,previewUrl:s.previewUrl??s.detectedUrl??void 0,logHistory:(s.logs??[]).map(i=>({timestamp:new Date().toISOString(),stream:i.startsWith("[stderr]")?"stderr":"stdout",text:i.replace(/^\[stderr\]\s*/,"")}))}}}async function Ge(e,t,s){try{const i=await z(T(`/devserver/${encodeURIComponent(e)}/preview`,s),{method:"POST",body:JSON.stringify({url:t})});return{url:i.url??null,source:i.source??null}}catch{const i=await mr({url:t},s);return{url:i.previewUrl??i.manualUrl??null,source:"manual"}}}async function Le(e){try{return(await z(T("/devserver/detect",e))).candidates??[]}catch{try{return(await cr(e)).map(s=>({name:s.name,command:s.command,cwd:s.cwd,scriptName:s.scriptName,packagePath:s.packagePath}))}catch{return[]}}}function st(e,t){return ar(T(`/devserver/${encodeURIComponent(e)}/logs/stream`,t))}const _e=500,nt=3e3;function J(e){return e instanceof Error?e.message:String(e)}function fr(e){return e.length<=_e?e:e.slice(-_e)}function je(e,t){return fr([...e,t])}function te(e){try{return JSON.parse(e)}catch{return null}}function pe(e){const t=e.text??"";return e.stream==="stderr"?`[stderr] ${t}`:t}function at(e){return e?.previewUrl??null}async function Ye(e){return be(e)}async function Qe(e,t){return dr(e,t)}async function it(e){return vr(e)}async function ot(e){return ur(e)}async function Ze(e){return cr(e)}function K(e){try{return e()}catch{return null}}function Re(){return typeof K(()=>Me)=="function"&&typeof K(()=>pr)=="function"}function ee(e){return{config:{id:e.id??"default",name:e.name??"Dev Server",command:e.command??"",cwd:e.cwd??"."},status:e.status,runtime:e.pid?{pid:e.pid,startedAt:e.startedAt??new Date().toISOString(),exitCode:e.exitCode??void 0,previewUrl:e.previewUrl}:void 0,previewUrl:e.previewUrl??e.detectedUrl??e.manualUrl??void 0,logHistory:(e.logs??[]).map(t=>({timestamp:new Date().toISOString(),stream:t.startsWith("[stderr]")?"stderr":"stdout",text:t.replace(/^\[stderr\]\s*/,"")}))}}function lt(e){const{t}=we("app"),[s,i]=n.useState(null),[a,u]=n.useState([]),[f,m]=n.useState([]),[C,N]=n.useState([]),[$,L]=n.useState(!0),[E,h]=n.useState(null),v=n.useRef(0),[g,k]=n.useState(null),A=n.useCallback(d=>{if(i(d),d?.logHistory){const l=d.logHistory.slice(-_e).map(pe);m(l)}},[]),U=n.useCallback(async()=>{const d=v.current;try{if(Re())if(g){const l=await pr(g,e);if(v.current!==d)return;A(l)}else{const l=await Me(e);if(v.current!==d)return;u(l),l.length>0&&(k(l[0].config.id),A(l[0]))}else{const l=await Ye(e);if(v.current!==d)return;const b=ee(l);u([b]),A(b)}h(null)}catch(l){if(v.current!==d)return;h(J(l))}},[A,e,g]);n.useEffect(()=>{v.current+=1;const d=v.current;i(null),u([]),m([]),N([]),L(!0),h(null),k(null),(async()=>{try{const[b,p]=await Promise.allSettled([Re()?Me(e):Ye(e).then(x=>[ee(x)]),typeof K(()=>Le)=="function"?Le(e):Ze(e).then(x=>x.map(R=>({name:R.name,command:R.command,cwd:R.cwd,scriptName:R.scriptName,packagePath:R.packagePath})))]);if(v.current!==d)return;let w=null;if(b.status==="fulfilled"){const x=b.value;if(u(x),x.length>0){const R=x[0];Re()&&k(R.config.id),A(R)}}else w=J(b.reason);p.status==="fulfilled"&&N(p.value),w&&h(w)}catch(b){if(v.current!==d)return;h(J(b))}finally{v.current===d&&L(!1)}})()},[A,e]),n.useEffect(()=>{const d=g?st(g,e):typeof K(()=>Pe)=="function"?Pe(e):null;if(!d)return;const l=v.current,b=ir(d,{events:{history:p=>{if(v.current!==l)return;const w=te(p.data);if(w?.lines){const x=w.lines.map(pe);m(fr(x))}},log:p=>{if(v.current!==l)return;const w=te(p.data);if(w){const x=typeof w.line=="string"?w.line:pe(w);m(R=>je(R,x))}},"dev-server:log":p=>{if(v.current!==l)return;const w=te(p.data);if(w){const x=typeof w.line=="string"?w.line:pe(w);m(R=>je(R,x))}},"dev-server:output":p=>{if(v.current!==l)return;const w=te(p.data);w?.line&&m(x=>je(x,w.line))},status:p=>{if(v.current!==l)return;const w=te(p.data),x=w?.status;x&&i(R=>R&&{...R,status:x,runtime:w.pid?{...R.runtime??{startedAt:new Date().toISOString()},pid:w.pid}:R.runtime})},"dev-server:status":p=>{if(v.current!==l)return;const w=te(p.data);if(w?.status){const x=ee(w);i(x),u([x])}},stopped:()=>{v.current},failed:()=>{v.current}},onReconnect:()=>{v.current===l&&U()},onError:()=>{v.current===l&&h(p=>p??t("devserver.lostConnection","Lost log stream connection."))}});return()=>{b()}},[e,U,g]);const O=s?.status==="running"||s?.status==="starting";Or(U,nt,{enabled:O});const j=n.useCallback(async(d,l)=>{v.current+=1;const b=v.current;try{let p;const w=typeof l=="string"&&l.length>0,x=s?.config?.cwd??".";if(!(w&&l!==x)&&g&&typeof K(()=>Je)=="function")p=await Je(g,e);else{const ne=await Qe({command:d,cwd:l},e);p=ee(ne)}if(v.current!==b)return;i(p),h(null)}catch(p){if(v.current!==b)return;throw h(J(p)),p}},[e,s?.config?.cwd,g]),H=n.useCallback(async()=>{v.current+=1;const d=v.current;try{let l;if(g&&typeof K(()=>Xe)=="function")l=await Xe(g,e);else{const b=await it(e);l=ee(b)}if(v.current!==d)return;i(l),h(null)}catch(l){if(v.current!==d)return;throw h(J(l)),l}},[e,g]),I=n.useCallback(async()=>{v.current+=1;const d=v.current;try{let l;if(g&&typeof K(()=>Ke)=="function")l=await Ke(g,e);else{const b=await ot(e);l=ee(b)}if(v.current!==d)return;i(l),h(null)}catch(l){if(v.current!==d)return;throw h(J(l)),l}},[e,g]),B=n.useCallback(async d=>{v.current+=1;const l=v.current;try{let b;if(g&&typeof K(()=>Ge)=="function")b=await Ge(g,d,e);else{const p=await mr({url:d},e);b={url:p.manualUrl??p.previewUrl??p.detectedUrl??null,source:p.manualUrl?"manual":"auto"}}if(v.current!==l)return;i(p=>p?{...p,previewUrl:b.url??void 0}:null),h(null)}catch(b){if(v.current!==l)return;throw h(J(b)),b}},[e,g]),P=n.useCallback(async()=>{v.current+=1;const d=v.current;try{let l;try{l=await Le(e)}catch{l=(await Ze(e)).map(p=>({name:p.name,command:p.command,cwd:p.cwd,scriptName:p.scriptName,packagePath:p.packagePath}))}if(v.current!==d)return;N(l),h(null)}catch(l){if(v.current!==d)return;throw h(J(l)),l}},[e]),V=n.useCallback(async(d,l)=>{if(typeof d!="string"&&!g)try{const w=d,x=await Qe({command:w.command,cwd:w.cwd,scriptName:w.scriptName,packagePath:w.packagePath??w.cwd},e),R=ee(x);i(R),u([R]),h(null);return}catch(w){throw h(J(w)),w}const b=typeof d=="string"?d:d.command,p=typeof d=="string"?l:d.cwd;await j(b,p)},[e,j,g]),c=n.useCallback(async()=>{await H()},[H]),M=n.useCallback(async()=>{await I()},[I]),F=n.useCallback(async d=>{await B(d)},[B]),W=n.useCallback(async()=>{await P()},[P]),D=n.useCallback(async()=>{await U()},[U]),S=at(s),y=s?{...s,pid:s.runtime?.pid}:null;return{session:s,sessions:a,logs:f,detectedCommands:C,previewUrl:S,isLoading:$,error:E,startServer:j,stopServer:H,restartServer:I,setPreviewUrl:B,detectCommands:P,refresh:U,candidates:C,serverState:y,loading:$,start:V,stop:c,restart:M,setManualUrl:F,detect:W,refreshStatus:D}}const er=500,rr=100;function hr(e){return e.length>er?e.slice(-er):e}function gr(e){return e==="stderr"?"stderr":"stdout"}function fe(e){try{return JSON.parse(e.data)}catch{return null}}function he(e,t){return{id:typeof e.id=="number"&&Number.isFinite(e.id)?e.id:t,text:typeof e.text=="string"?e.text:"",stream:gr(e.stream),timestamp:typeof e.timestamp=="string"?e.timestamp:""}}function ct(e,t){return{id:t,text:e,stream:"stdout",timestamp:""}}function Ue(e,t){if(t.length===0)return e;const s=[...e],i=new Set(e.map(a=>a.id));for(const a of t)i.has(a.id)||(i.add(a.id),s.push(a));return s.sort((a,u)=>a.id-u.id),hr(s)}function dt(e,t){const[s,i]=n.useState([]),[a,u]=n.useState(!1),[f,m]=n.useState(!1),[C,N]=n.useState(!1),[$,L]=n.useState(null),E=n.useRef(null),h=n.useRef(!1),v=n.useRef(0),g=n.useRef(0),k=n.useRef(e),A=n.useRef(t),U=n.useRef(0),O=n.useRef(1);(k.current!==e||A.current!==t)&&(k.current=e,A.current=t,v.current++,le({view:"useDevServerLogs",trigger:"project-context-change",projectId:e,replayAttempted:!1,reason:"context-version-bumped"}),h.current=!0,U.current=0,O.current=1,i([]),u(!1),m(!1),N(!1),L(null),E.current&&(E.current(),E.current=null)),n.useEffect(()=>{if(!t){E.current&&(E.current(),E.current=null);return}const P=v.current,V=++g.current;h.current=!1,u(!0);const c=(D,S)=>{const y=hr(D);i(y),L(S),N(S!==null?S>y.length:!1);const d=y.length>0?y[y.length-1].id:0;U.current=d,O.current=d+1},M=D=>{if(h.current||v.current!==P||!D||typeof D!="object")return;const S=D.lines;if(!Array.isArray(S))return;if(S.length>0&&typeof S[0]=="string"){const d=S.filter(l=>typeof l=="string").map((l,b)=>ct(l,b+1));c(d,d.length);return}const y=S.filter(d=>!!d&&typeof d=="object").map((d,l)=>he(d,l+1));c(y,y.length)},F=D=>{if(h.current||v.current!==P)return;const S=typeof D.text=="string"?D.text:typeof D.line=="string"?D.line:null;if(!S)return;const y=O.current,d=typeof D.id=="number"&&Number.isFinite(D.id)?D.id:y,l={id:d,text:S,stream:gr(D.stream),timestamp:typeof D.timestamp=="string"?D.timestamp:""};U.current=Math.max(U.current,d),O.current=Math.max(O.current,d+1),i(b=>Ue(b,[l])),L(b=>b===null?b:Math.max(b+1,l.id))};async function W(){try{const S=await Ee({maxLines:rr},e);if(h.current||v.current!==P||g.current!==V)return;const y=S.lines.map((d,l)=>he(d,l+1));c(y,S.totalLines)}catch{if(h.current||v.current!==P||g.current!==V)return;c([],null)}finally{!h.current&&v.current===P&&g.current===V&&u(!1)}const D=Pe(e);E.current=ir(D,{events:{"dev-server:log":S=>{const y=fe(S);y&&F(y)},log:S=>{const y=fe(S);y&&F(y)},history:S=>{const y=fe(S);M(y)},"dev-server:history":S=>{const y=fe(S);M(y)}},onReconnect:()=>{le({view:"useDevServerLogs",trigger:"sse-reconnect",projectId:e,replayAttempted:!0,replayFromEventId:U.current??null,sseChannel:D,reason:"history-replay"}),!(h.current||v.current!==P)&&Ee({lastEventId:U.current,maxLines:50},e).then(S=>{if(h.current||v.current!==P)return;const y=S.lines.map((d,l)=>he(d,O.current+l));if(y.length>0){const d=y[y.length-1].id;U.current=Math.max(U.current,d),O.current=Math.max(O.current,d+1)}i(d=>Ue(d,y)),L(S.totalLines)}).catch(()=>{})}}),le({view:"useDevServerLogs",trigger:"sse-open",projectId:e,replayAttempted:!1,sseChannel:D})}return W(),()=>{h.current=!0,E.current&&(E.current(),E.current=null)}},[t,e]);const H=n.useCallback(async()=>{if(!t||f)return;const P=v.current,V=s.length;m(!0);try{const c=await Ee({maxLines:rr,offset:V},e);if(h.current||v.current!==P)return;const M=c.lines.map((F,W)=>he(F,W+1));i(F=>Ue(M,F)),N(c.totalLines>V+M.length),L(c.totalLines)}catch{}finally{m(!1)}},[t,s.length,f,e]),I=n.useCallback(()=>{i([])},[]),B=E.current!==null&&!a&&!h.current;return{entries:s,loading:a,loadingMore:f,hasMore:C,total:$,loadMore:H,clear:I,logs:s,isStreaming:B,clearLogs:I}}const vt="This preview appears to block iframe embedding. Open it in a new tab instead.",ut="The preview URL could not be loaded. Verify the server is running and the URL is correct.",mt="Preview is taking longer than expected and may block iframe embedding.";function pt(e){return e==="blocked"?vt:e==="error"?ut:null}function ft(e,t={}){const{loadTimeoutMs:s=1e4,detectionMethod:i=null}=t,a=n.useRef(null),u=n.useRef(null),[f,m]=n.useState("unknown"),[C,N]=n.useState(null),[$]=n.useState(i),L=n.useCallback(()=>{u.current!==null&&(window.clearTimeout(u.current),u.current=null)},[]),E=n.useCallback(j=>{m(j),N(pt(j))},[]),h=n.useCallback(()=>{m("blocked"),N(mt)},[]);n.useEffect(()=>{if(L(),!e){m("unknown"),N(null);return}m("unknown"),N(null);let j=!1;return queueMicrotask(()=>{j||(m("loading"),N(null))}),()=>{j=!0,L()}},[L,e]),n.useEffect(()=>{if(f!=="loading"){L();return}const j=setTimeout(()=>{u.current=null,h()},s);return u.current=j,()=>{clearTimeout(j),u.current===j&&(u.current=null)}},[L,f,s,h]);const v=n.useCallback(()=>{const j=a.current;if(!j){E("embedded");return}try{if(j.contentWindow?.location?.href==="about:blank"&&j.src!=="about:blank"){E("blocked");return}}catch{}E("embedded")},[E]),g=n.useCallback(()=>{E("error")},[E]);n.useEffect(()=>{if(L(),!e){m("unknown"),N(null);return}m("unknown"),N(null)},[L]);const k=n.useCallback(()=>{L(),m("unknown"),N(null)},[L]),A=k,U=n.useMemo(()=>f==="embedded",[f]),O=n.useMemo(()=>f==="blocked"||f==="error",[f]);return{embedStatus:f,isEmbedded:U,isBlocked:O,blockReason:C,detectionMethod:$,iframeRef:a,resetEmbedStatus:k,setEmbedStatus:E,retry:A,embedContext:C,handleIframeLoad:v,handleIframeError:g}}const ht=/\x1b\[[0-9;]*m/g,gt=50;function wt(e){return e.scrollHeight-(e.scrollTop+e.clientHeight)<=gt}function Ae(e){return e.replace(ht,"")}function bt(e){if(!e)return"";const t=new Date(e);return Number.isNaN(t.getTime())?"":t.toLocaleTimeString([],{hour:"2-digit",minute:"2-digit",second:"2-digit",hour12:!1})}function xt(e){return e.replace(/[.*+?^${}()|[\]\\]/g,"\\$&")}function yt(e){if(e.stream==="stderr")return"error";const t=Ae(e.text).toLowerCase();return/\b(warn|warning)\b/.test(t)?"warn":/\b(error|fatal)\b/.test(t)?"error":"info"}function St(e,t){if(!t)return e;const s=new RegExp(`(${xt(t)})`,"ig"),i=e.split(s),a=t.toLowerCase();return r.jsx(r.Fragment,{children:i.map((u,f)=>u.toLowerCase()===a?r.jsx("mark",{children:u},`${u}-${f}`):r.jsx("span",{children:u},`${u}-${f}`))})}function Nt({entries:e,loading:t,loadingMore:s,hasMore:i,total:a,onLoadMore:u,isRunning:f}){const{t:m}=we("app"),C=n.useRef(null),N=n.useRef(e.length),$=n.useRef(f),[L,E]=n.useState(!1),[h,v]=n.useState(!1),g=n.useRef(!1),[k,A]=n.useState(""),[U,O]=n.useState("all"),j=n.useMemo(()=>U==="all"?e:e.filter(c=>yt(c)===U),[e,U]),H=n.useMemo(()=>{const c=k.trim().toLowerCase();return c?j.filter(M=>Ae(M.text).toLowerCase().includes(c)):j},[j,k]),I=H.length,B=n.useCallback(c=>{g.current=c,v(c)},[]),P=n.useCallback(()=>{const c=C.current;c&&(c.scrollTop=c.scrollHeight,B(!1))},[B]);n.useEffect(()=>{const c=$.current,M=N.current,F=e.length>M;f&&(!c||!h&&F)&&P(),$.current=f,N.current=e.length},[e.length,f,h,P]);const V=n.useCallback(()=>{const c=C.current;c&&B(!wt(c))},[B]);return n.useEffect(()=>{t||e.length===0||!h&&f&&P()},[e,f,h,t,P]),n.useEffect(()=>{const c=C.current;if(!c||!f||typeof MutationObserver>"u")return;const M=new MutationObserver(()=>{g.current||P()});return M.observe(c,{childList:!0,characterData:!0,subtree:!0}),()=>M.disconnect()},[f,P]),t&&e.length===0?r.jsx("section",{className:"devserver-log-viewer","data-testid":"devserver-log-viewer",children:r.jsxs("div",{className:"devserver-log-viewer__loading","data-testid":"devserver-log-loading",children:[r.jsx(ge,{size:16,className:"devserver-log-viewer__spinner"}),r.jsx("span",{children:m("devserver.loadingLogs","Loading logs…")})]})}):r.jsxs("section",{className:`devserver-log-viewer${L?" devserver-log-viewer--fullscreen":""}`,"data-testid":"devserver-log-viewer",children:[r.jsxs("header",{className:"devserver-log-viewer__toolbar",children:[r.jsxs("div",{className:"devserver-log-viewer__toolbar-meta",children:[r.jsx("span",{className:"devserver-log-viewer__title",children:m("devserver.logs","Logs")}),r.jsxs("span",{className:"devserver-log-viewer__count","data-testid":"devserver-log-count",children:[a!==null?`${e.length}/${a}`:`${e.length}`," ",m("devserver.lines","lines")]})]}),r.jsxs("div",{className:"devserver-log-viewer__toolbar-actions",children:[r.jsxs("label",{className:"devserver-log-viewer__severity",htmlFor:"devserver-log-severity-filter",children:[r.jsx("span",{className:"visually-hidden",children:m("devserver.filterBySeverity","Filter logs by severity")}),r.jsxs("select",{id:"devserver-log-severity-filter",className:"select devserver-log-viewer__severity-select",value:U,onChange:c=>O(c.target.value),"data-testid":"devserver-log-severity-filter","aria-label":m("devserver.filterBySeverity","Filter logs by severity"),children:[r.jsx("option",{value:"all",children:m("devserver.allSeverities","All severities")}),r.jsx("option",{value:"info",children:m("devserver.info","Info")}),r.jsx("option",{value:"warn",children:m("devserver.warn","Warn")}),r.jsx("option",{value:"error",children:m("devserver.error","Error")})]})]}),r.jsxs("label",{className:"devserver-log-viewer__search",htmlFor:"devserver-log-search",children:[r.jsx("span",{className:"visually-hidden",children:m("devserver.searchLogs","Search logs")}),r.jsx(Fr,{size:14}),r.jsx("input",{id:"devserver-log-search",className:"input devserver-log-viewer__search-input",type:"text",value:k,onChange:c=>A(c.target.value),placeholder:m("devserver.searchLogs","Search logs"),"data-testid":"devserver-log-search-input","aria-label":m("devserver.searchLogs","Search logs")})]}),k.trim().length>0&&r.jsx("span",{className:"devserver-log-viewer__matches","data-testid":"devserver-log-match-count",children:m("devserver.matchCount",{count:I,defaultValue_one:"{{count}} match",defaultValue_other:"{{count}} matches"})}),r.jsx("button",{type:"button",className:"btn btn-sm btn-icon",onClick:()=>E(c=>!c),"data-testid":"devserver-log-fullscreen-toggle","aria-label":L?m("devserver.exitFullscreen","Exit fullscreen logs"):m("devserver.enterFullscreen","Enter fullscreen logs"),children:L?r.jsx(zr,{size:14}):r.jsx($r,{size:14})})]})]}),r.jsxs("div",{className:"devserver-log-viewer__body",children:[i&&r.jsx("div",{className:"devserver-log-viewer__load-more","data-testid":"devserver-log-load-more",children:r.jsx("button",{type:"button",className:"btn btn-sm touch-target",onClick:u,disabled:s,"data-testid":"devserver-log-load-more-button",children:s?r.jsxs(r.Fragment,{children:[r.jsx(ge,{size:14,className:"devserver-log-viewer__spinner"}),m("devserver.loadingOlderLogs","Loading older logs…")]}):m("devserver.loadOlderLogs","Load older logs")})}),r.jsxs("div",{ref:C,className:"devserver-log-viewer__content",onScroll:V,"data-testid":"devserver-log-content",children:[!t&&H.length===0&&r.jsx("p",{className:"devserver-log-viewer__empty","data-testid":"devserver-log-empty",children:e.length===0?m("devserver.noLogsYet","No logs yet. Start the dev server to see output."):j.length===0?m("devserver.noMatchesSeverity","No log lines match the selected severity."):m("devserver.noMatchesSearch","No log lines match your search.")}),H.map(c=>{const M=Ae(c.text),F=bt(c.timestamp);return r.jsxs("div",{className:"devserver-log-line",children:[F&&r.jsx("span",{className:"devserver-log-timestamp","data-testid":"devserver-log-timestamp",children:F}),c.stream==="stderr"&&r.jsx("span",{className:"devserver-log-stream-badge","data-testid":"devserver-log-stderr-badge",children:m("devserver.errBadge","ERR")}),r.jsx("span",{className:"devserver-log-text",children:Hr(St(M,k.trim()))})]},c.id)})]}),h&&f&&r.jsxs("button",{type:"button",className:"btn btn-sm devserver-log-viewer__new-logs-button",onClick:P,"data-testid":"devserver-log-jump-button",children:[r.jsx(Br,{size:14}),m("devserver.newLogs","New logs")]})]})]})}const kt="devserver-preview-iframe";function Ct({url:e,embedStatus:t,onEmbedStatusChange:s,iframeRef:i,blockReason:a,onRetry:u,className:f=kt,embedContext:m}){const{t:C}=we("app"),N=a??m??null,[$,L]=n.useState(0);n.useEffect(()=>{!e||t!=="unknown"||(L(g=>g+1),s("loading"))},[t,s,e]);const E=n.useCallback(()=>{const g=i.current;if(!g){s("embedded");return}try{if(g.contentWindow?.location?.href==="about:blank"&&g.src!=="about:blank"){s("blocked");return}}catch{}s("embedded")},[i,s]),h=n.useCallback(g=>{g.stopPropagation(),s("error")},[s]),v=n.useCallback(()=>{e&&window.open(e,"_blank","noopener,noreferrer")},[e]);return e?r.jsxs("div",{className:"devserver-preview-iframe-shell",children:[r.jsx("iframe",{src:e,ref:i,sandbox:"allow-scripts allow-same-origin allow-forms allow-popups allow-popups-to-escape-sandbox",className:f,title:"Dev server preview",onLoad:E,onError:h,onErrorCapture:h,"data-testid":"devserver-preview-iframe"},`${e}-${$}`),t==="loading"&&r.jsxs("div",{className:"devserver-preview-overlay","data-testid":"devserver-preview-loading",children:[r.jsx(ge,{size:16,className:"dev-server-spin"}),r.jsx("span",{children:C("preview.loading","Loading preview...")})]}),t==="blocked"&&r.jsxs("div",{className:"devserver-preview-blocked-panel",role:"alert","data-testid":"devserver-preview-blocked-panel",children:[r.jsx(or,{className:"devserver-preview-blocked-icon","aria-hidden":"true"}),r.jsxs("div",{children:[r.jsx("p",{className:"devserver-preview-blocked-title",children:C("preview.blockedTitle","Preview cannot be embedded")}),N&&r.jsx("p",{className:"devserver-preview-blocked-context",children:N})]}),r.jsx("p",{className:"devserver-preview-blocked-description",children:C("preview.blockedDescription","You can view the preview in a separate browser tab.")}),r.jsxs("div",{className:"devserver-preview-blocked-actions",children:[r.jsx("button",{type:"button",className:"btn btn-primary",onClick:v,children:C("preview.openInNewTab","Open in new tab")}),u&&r.jsx("button",{type:"button",className:"btn btn-sm",onClick:u,children:C("actions.retry","Retry")})]})]}),t==="error"&&r.jsxs("div",{className:"devserver-preview-error-panel",role:"alert","data-testid":"devserver-preview-error-panel",children:[r.jsx(lr,{className:"devserver-preview-blocked-icon","aria-hidden":"true"}),r.jsxs("div",{children:[r.jsx("p",{className:"devserver-preview-blocked-title",children:C("preview.errorTitle","Unable to load preview")}),N&&r.jsx("p",{className:"devserver-preview-blocked-context",children:N})]}),r.jsx("p",{className:"devserver-preview-blocked-description",children:C("preview.blockedDescription","You can view the preview in a separate browser tab.")}),r.jsxs("div",{className:"devserver-preview-blocked-actions",children:[r.jsx("button",{type:"button",className:"btn btn-primary",onClick:v,children:C("preview.openInNewTab","Open in new tab")}),u&&r.jsx("button",{type:"button",className:"btn btn-sm",onClick:u,children:C("actions.retry","Retry")})]})]})]}):null}function Et(e){return{stopped:{className:"dev-server-status-badge--stopped",label:e("devserver.status.stopped","Stopped")},starting:{className:"dev-server-status-badge--starting",label:e("devserver.status.starting","Starting...")},running:{className:"dev-server-status-badge--running",label:e("devserver.status.running","Running")},stopping:{className:"dev-server-status-badge--starting",label:e("devserver.status.stopping","Stopping...")},failed:{className:"dev-server-status-badge--failed",label:e("devserver.status.failed","Failed")}}}const Lt=480;function jt(){return typeof window>"u"||typeof window.matchMedia!="function"?!1:window.matchMedia("(max-width: 768px)").matches}function wr(e){if(e.closest(".right-dock-expand-modal__body"))return null;const t=e.parentElement;return t?.classList.contains("right-dock__body")?t:null}function Rt(e){return e.clientWidth>0?e.clientWidth:e.getBoundingClientRect().width}function Ut(e){if(!e||jt())return!1;const t=wr(e);return t?Rt(t)<=Lt:!1}function Dt(e){const[t,s]=n.useState(!1);return n.useEffect(()=>{const i=e.current;if(!i){s(!1);return}const a=wr(i),u=()=>s(Ut(i));if(u(),!a||typeof ResizeObserver>"u")return window.addEventListener("resize",u),()=>window.removeEventListener("resize",u);const f=new ResizeObserver(u);return f.observe(a),window.addEventListener("resize",u),()=>{f.disconnect(),window.removeEventListener("resize",u)}},[e]),t}let De=!1;function tr(e){return e instanceof Error?e.message:String(e)}function br(e){return e==="."?"root":e}function sr(e){return e?e==="root"?".":e:null}function nr(e,t,s){return!t||e.scriptName!==t?!1:s?br(e.cwd)===s:!0}function Pt(e){return e.cwd==="."?"root":e.cwd}function Mt(e){return e.length<=60?e:`${e.slice(0,60)}…`}function $t({addToast:e,projectId:t,tasks:s,columnFlagsByTaskId:i}){const{t:a}=we("app");n.useEffect(()=>(le({view:"DevServerView",trigger:De?"route-active":"remount",projectId:t,replayAttempted:!1}),De=!1,()=>{De=!0,le({view:"DevServerView",trigger:"route-inactive",projectId:t,replayAttempted:!1})}),[t]);const{session:u,detectedCommands:f,previewUrl:m,isLoading:C,error:N,startServer:$,stopServer:L,restartServer:E,setPreviewUrl:h,detectCommands:v,refresh:g}=lt(t),k=u?.status??"stopped",A=k==="running"||k==="starting",U=Et(a),O=U[k]??U.stopped,{entries:j,loading:H,loadingMore:I,hasMore:B,total:P,loadMore:V}=dt(t,!!t),c=m,M=u?.config?.cwd??null,F=n.useRef(null),W=Dt(F),[D,S]=n.useState(!0),[y,d]=n.useState(()=>me(t)?.commandInput??""),[l,b]=n.useState(""),[p,w]=n.useState(()=>me(t)?.selectedScript??null),[x,R]=n.useState(()=>me(t)?.selectedTaskId??null),ne=n.useRef(t);n.useEffect(()=>{if(ne.current===t)return;ne.current=t;const o=me(t);d(o?.commandInput??""),w(o?.selectedScript??null),R(o?.selectedTaskId??null)},[t]),n.useEffect(()=>{ne.current===t&&Vr({selectedScript:p,selectedTaskId:x,commandInput:y},t)},[y,t,p,x]);const[G,Te]=n.useState(null),Y=n.useMemo(()=>(s??[]).filter(o=>Wr(i?.get(o.id),o.column)&&typeof o.worktree=="string"&&o.worktree.length>0),[s,i]),X=n.useMemo(()=>Y.find(o=>o.id===x)??null,[Y,x]);n.useEffect(()=>{x&&!Y.some(o=>o.id===x)&&R(null)},[Y,x]);const[ae,xr]=n.useState("embedded"),[ie,xe]=n.useState(!1),Oe=n.useRef(null),ye=n.useRef(null),yr=ae==="embedded"?c:null,{embedStatus:q,setEmbedStatus:Sr,resetEmbedStatus:ce,iframeRef:re,isEmbedded:Nr,isBlocked:Se,blockReason:Ne,retry:Fe}=ft(yr),[ze,Q]=n.useState(!1),$e=n.useRef(q);n.useEffect(()=>{const o=$e.current!==q;Se&&o&&Q(!0),q==="embedded"&&Q(!1),$e.current=q},[q,Se]),n.useEffect(()=>{Q(!1)},[c]);const de=n.useMemo(()=>{if(!p)return null;const o=sr(M);return f.find(_=>!(_.scriptName!==p||o&&_.cwd!==o||u?.config?.command&&_.command!==u.config.command))??f.find(_=>nr(_,p,M))??null},[f,u?.config?.command,p,M]);n.useEffect(()=>{typeof v=="function"&&v().catch(o=>{e(tr(o),"error")})},[e,v]),n.useEffect(()=>{if(p){S(!1);return}S(!0)},[p]),n.useEffect(()=>{if(u?.status==="running"||u?.status==="starting"){u.config?.command?.trim().length>0&&d(u.config.command);return}if(de){d(o=>o.trim().length>0?o:de.command);return}f.length>0&&d(o=>o.trim().length>0?o:f[0]?.command??"")},[f,de,u?.config?.command,u?.status]),n.useEffect(()=>{b(c??"")},[c]);const ve=n.useCallback(()=>{xe(!1),window.requestAnimationFrame(()=>Oe.current?.focus())},[]),kr=Ir(ve);n.useEffect(()=>{if(!ie)return;ye.current?.focus();const o=_=>{if(_.key==="Escape"){ve();return}if(_.key!=="Tab")return;const oe=Array.from(ye.current?.querySelectorAll('button:not([disabled]), [href], input:not([disabled]), select:not([disabled]), textarea:not([disabled]), [tabindex]:not([tabindex="-1"])')??[]).filter(Ve=>!Ve.hasAttribute("disabled")&&Ve.getAttribute("aria-hidden")!=="true"),Z=oe[0],Ce=oe.at(-1);!Z||!Ce||(_.shiftKey&&document.activeElement===Z?(_.preventDefault(),Ce.focus()):!_.shiftKey&&document.activeElement===Ce&&(_.preventDefault(),Z.focus()))};return document.addEventListener("keydown",o),()=>document.removeEventListener("keydown",o)},[ve,ie]),n.useEffect(()=>{!W&&ie&&xe(!1)},[W,ie]);const ke=n.useCallback(()=>{c&&window.open(c,"_blank","noopener,noreferrer")},[c]),He=n.useCallback(()=>{Q(!1),Fe()},[Fe]),Cr=n.useCallback(()=>{try{const o=re.current;if(o?.contentWindow){o.contentWindow.location.reload(),Q(!1),ce();return}}catch{}if(!(!c||!re.current))try{const o=new URL(c);o.searchParams.set("_t",Date.now().toString()),re.current.src=o.toString(),Q(!1),ce()}catch{re.current.src=c,Q(!1),ce()}},[c,re,ce]),ue=n.useCallback(async(o,_,oe)=>{Te(o);try{await _(),e(oe,"success")}catch(Z){e(tr(Z),"error")}finally{Te(null)}},[e]),Er=n.useCallback(o=>{w(o.scriptName),S(!1),d(o.command),e(a("devserver.toast.selectedScript","Selected {{name}} script.",{name:o.scriptName}),"success")},[e]),Lr=n.useCallback(()=>{w(null),S(!0),e(a("devserver.toast.clearedScript","Cleared selected dev server script."),"success")},[e]),jr=n.useCallback(o=>{A&&o&&o!==x&&e(a("devserver.restartToApplyTask","Restart the dev server to apply the selected task's worktree."),"info"),R(o)},[e,A,x,a]),Rr=()=>{const o=y.trim();if(o.length===0){e(a("devserver.toast.enterCommand","Enter a command before starting the dev server."),"warning");return}const _=sr(M)??".",Z=X?.worktree??null??de?.cwd??_;ue("start",()=>$(o,Z),a("devserver.toast.started","Dev server started."))},Ur=()=>{ue("stop",L,a("devserver.toast.stopped","Dev server stopped."))},Dr=()=>{ue("restart",E,a("devserver.toast.restarted","Dev server restarted."))},Pr=()=>{const o=l.trim(),_=o.length>0?o:null;ue("preview",()=>h(_),_?a("devserver.toast.previewUpdated","Preview URL updated."):a("devserver.toast.previewCleared","Preview URL override cleared."))},Mr=n.useCallback(()=>{N&&g()},[N,g]),_r=k==="starting"||k==="running"||G!==null,Ar=k==="stopped"||G!==null,Tr=k==="stopped"||k==="starting"||G!==null,Be=()=>r.jsxs(r.Fragment,{children:[r.jsxs("div",{className:"devserver-preview-header",children:[r.jsxs("div",{className:"devserver-preview-title",children:[r.jsx(We,{size:14}),r.jsx("span",{children:a("devserver.preview","Preview")})]}),r.jsxs("span",{className:"devserver-preview-url-badge devserver-preview-url-badge--auto",title:c??a("devserver.noPreviewUrl","No preview URL"),"data-testid":"devserver-preview-url-badge",children:[a("devserver.auto","Auto"),c?` · ${c}`:a("devserver.notAvailable"," · Not available")]}),r.jsxs("div",{className:"devserver-preview-actions",children:[r.jsx("button",{type:"button",className:"btn btn-sm",onClick:()=>xr(o=>o==="embedded"?"external":"embedded"),"data-testid":"devserver-preview-mode-toggle",children:ae==="embedded"?a("devserver.externalOnly","External only"):a("devserver.embedded","Embedded")}),r.jsx("button",{type:"button",className:"btn btn-sm btn-icon",title:a("devserver.openInNewTab","Open in new tab"),onClick:ke,disabled:!c,"data-testid":"devserver-preview-open-tab",children:r.jsx(Qr,{})}),r.jsx("button",{type:"button",className:"btn btn-sm btn-icon",title:a("devserver.refreshPreview","Refresh preview"),onClick:Cr,disabled:!c,"data-testid":"devserver-preview-refresh",children:r.jsx(Zr,{})})]})]}),r.jsxs("div",{className:"devserver-preview-container","data-embed-status":q,"data-embedded":Nr?"true":"false",children:[!c&&!A&&r.jsx("p",{className:"devserver-preview-empty",children:a("devserver.startDevServer","Start a dev server to see a live preview here.")}),!c&&A&&r.jsx("p",{className:"devserver-preview-empty",children:a("devserver.noPreviewDetected","No preview URL detected. Start the dev server or set a manual URL to preview your app.")}),c&&ae==="external"&&r.jsxs("div",{className:"devserver-preview-external-only","data-testid":"devserver-preview-external-only",children:[r.jsx("p",{children:a("devserver.embeddedPreviewDisabled","Embedded preview is disabled. Open your app in a separate browser tab.")}),r.jsx("button",{type:"button",className:"btn btn-primary btn-sm touch-target",onClick:ke,"data-testid":"devserver-preview-external-open-tab",children:a("devserver.openInNewTab","Open in new tab")})]}),c&&ae==="embedded"&&ze&&Se&&r.jsxs("div",{className:q==="error"?"devserver-preview-error-panel":"devserver-preview-blocked-panel","data-testid":"devserver-preview-fallback",role:"alert",children:[q==="error"?r.jsx(lr,{className:"devserver-preview-blocked-icon","aria-hidden":"true"}):r.jsx(or,{className:"devserver-preview-blocked-icon","aria-hidden":"true"}),r.jsxs("div",{children:[r.jsx("p",{className:"devserver-preview-blocked-title",children:q==="error"?a("devserver.previewFailed","Preview failed"):a("devserver.previewBlocked","Preview blocked")}),Ne&&r.jsx("p",{className:"devserver-preview-blocked-context",children:Ne})]}),r.jsx("p",{className:"devserver-preview-blocked-description",children:a("devserver.openPreviewOrRetry","Open the preview in a new tab, or retry embedded mode after checking your server settings.")}),r.jsxs("div",{className:"devserver-preview-blocked-actions",children:[r.jsx("button",{type:"button",className:"btn btn-primary",onClick:ke,"data-testid":"devserver-preview-fallback-open-tab",children:a("devserver.openPreviewInNewTab","Open preview in new tab")}),r.jsx("button",{type:"button",className:"btn btn-sm",onClick:He,"data-testid":"devserver-preview-fallback-retry",children:a("devserver.retryEmbeddedPreview","Retry embedded preview")})]})]}),c&&ae==="embedded"&&!ze&&r.jsx(Ct,{url:c,embedStatus:q,onEmbedStatusChange:Sr,iframeRef:re,blockReason:Ne,onRetry:He})]})]});return r.jsxs("div",{ref:F,className:"dev-server-view","data-testid":"dev-server-view","data-narrow-right-dock-preview":W?"true":"false",children:[r.jsx(qr,{icon:Jr,title:a("devserver.title","Dev Server"),actions:r.jsxs(r.Fragment,{children:[r.jsx("span",{className:"dev-server-header-title",children:r.jsx("span",{className:`dev-server-status-badge ${O.className}`,"data-testid":"dev-server-status-badge",children:O.label})}),r.jsxs("div",{className:"dev-server-header-actions",children:[r.jsxs("button",{type:"button",className:"btn btn-primary btn-sm",onClick:Rr,disabled:_r,"data-testid":"dev-server-start-button",children:[r.jsx(Xr,{size:14}),r.jsx("span",{children:G==="start"?a("devserver.starting","Starting..."):a("devserver.start","Start")})]}),r.jsxs("button",{type:"button",className:"btn btn-danger btn-sm",onClick:Ur,disabled:Ar,"data-testid":"dev-server-stop-button",children:[r.jsx(Kr,{size:14}),r.jsx("span",{children:G==="stop"?a("devserver.stopping","Stopping..."):a("devserver.stop","Stop")})]}),r.jsxs("button",{type:"button",className:"btn btn-sm",onClick:Dr,disabled:Tr,"data-testid":"dev-server-restart-button",children:[r.jsx(Gr,{size:14}),r.jsx("span",{children:G==="restart"?a("devserver.restarting","Restarting..."):a("devserver.restart","Restart")})]})]})]})}),r.jsxs("section",{className:"dev-server-panel dev-server-config","aria-label":a("devserver.configurationLabel","Dev server configuration"),children:[r.jsxs("div",{className:"dev-server-section-header",children:[r.jsx("h3",{children:a("devserver.configuration","Configuration")}),C&&r.jsx("span",{className:"dev-server-muted",children:a("devserver.loading","Loading...")})]}),C&&!u&&f.length===0&&r.jsxs("div",{className:"dev-server-loading-state","data-testid":"dev-server-loading-state",children:[r.jsx(ge,{size:16,className:"dev-server-spin"}),r.jsx("span",{children:a("devserver.loadingConfig","Loading dev server configuration...")})]}),N&&r.jsxs("div",{className:"dev-server-error-box",role:"alert","data-testid":"dev-server-error-box",children:[r.jsx("p",{children:N}),r.jsx("button",{type:"button",className:"btn btn-sm",onClick:Mr,children:a("devserver.retry","Retry")})]}),r.jsxs("div",{className:"dev-server-section",children:[r.jsx("h3",{children:a("devserver.scriptSelection","Script Selection")}),p&&r.jsxs("div",{className:"dev-server-selected","data-testid":"dev-server-selected-summary",children:[r.jsx("span",{className:"dev-server-candidate-name",children:p}),r.jsx("span",{className:"dev-server-candidate-source",children:M??"root"}),r.jsx("button",{type:"button",className:"btn btn-sm",onClick:()=>S(!0),"data-testid":"dev-server-change-selection",children:a("devserver.change","Change")}),r.jsx("button",{type:"button",className:"btn btn-danger btn-sm",onClick:Lr,"data-testid":"dev-server-clear-selection",children:a("devserver.clear","Clear")})]}),D&&f.length===0&&r.jsx("p",{className:"dev-server-empty-state","data-testid":"dev-server-empty-candidates",children:a("devserver.noScriptsDetected","No dev server scripts detected. Check that your project has a package.json with a dev, start, or similar script.")}),D&&f.length>0&&r.jsx("div",{className:"dev-server-candidates","data-testid":"dev-server-candidates",children:f.map(o=>{const _=nr(o,p,M);return r.jsxs("button",{type:"button",className:`dev-server-candidate ${_?"dev-server-candidate--selected":""}`,onClick:()=>Er(o),"data-testid":`dev-server-candidate-${o.scriptName}-${br(o.cwd)}`,children:[r.jsx("span",{className:"dev-server-candidate-name",children:o.scriptName}),r.jsx("span",{className:"dev-server-candidate-command",children:Mt(o.command)}),r.jsx("span",{className:"dev-server-candidate-source",children:Pt(o)})]},`${o.cwd}::${o.scriptName}::${o.command}`)})})]}),r.jsxs("div",{className:"dev-server-section dev-server-executing-task-section",children:[r.jsx("h3",{children:a("devserver.executingTask","Executing Task")}),r.jsxs("div",{className:"dev-server-field-group",children:[r.jsx("label",{htmlFor:"dev-server-task-picker",className:"dev-server-label",children:a("devserver.executingTask","Executing Task")}),r.jsxs("select",{id:"dev-server-task-picker",className:"input dev-server-task-picker",value:x??"",onChange:o=>jr(o.target.value.length>0?o.target.value:null),disabled:Y.length===0,"aria-label":a("devserver.executingTask","Executing Task"),"data-testid":"dev-server-task-picker",children:[r.jsx("option",{value:"",children:a("devserver.projectRootNoTask","Project root (no task)")}),Y.map(o=>r.jsx("option",{value:o.id,children:o.title?`${o.id} — ${o.title}`:o.id},o.id))]}),Y.length===0&&r.jsx("p",{className:"dev-server-empty-state","data-testid":"dev-server-no-executing-tasks",children:a("devserver.noExecutingTasks","No executing tasks with a worktree available. Start a task to target its worktree.")}),X&&r.jsxs("div",{className:"dev-server-task-descriptor","data-testid":"dev-server-task-descriptor",children:[r.jsx("div",{className:"dev-server-task-descriptor-header",children:r.jsx("span",{className:"dev-server-candidate-name",children:X.title?`${X.id} — ${X.title}`:X.id})}),r.jsx("p",{className:"dev-server-task-description",children:X.description}),r.jsxs("div",{className:"dev-server-task-worktree",children:[r.jsx("span",{className:"dev-server-label",children:a("devserver.targetWorktree","Target worktree")}),r.jsx("code",{children:X.worktree})]})]})]})]}),r.jsxs("div",{className:"dev-server-field-group",children:[r.jsx("label",{htmlFor:"dev-server-command",className:"dev-server-label",children:a("devserver.command","Command")}),r.jsx("input",{id:"dev-server-command",className:"input",value:y,onChange:o=>d(o.target.value),placeholder:"pnpm dev","data-testid":"dev-server-command-input",readOnly:k==="running"||k==="starting"})]}),(k==="running"||k==="starting")&&u&&r.jsxs("div",{className:"dev-server-current-command","data-testid":"dev-server-current-command",children:[r.jsx("span",{className:"dev-server-label",children:a("devserver.runningCommand","Running command")}),r.jsx("code",{children:u.config?.command??y})]}),r.jsxs("div",{className:"dev-server-preview-override",children:[r.jsx("label",{htmlFor:"dev-server-preview-input",className:"dev-server-label",children:a("devserver.previewUrlOverride","Preview URL Override")}),r.jsx("input",{id:"dev-server-preview-input",className:"input",type:"url",value:l,onChange:o=>b(o.target.value),placeholder:"http://localhost:3000","data-testid":"dev-server-preview-input"}),r.jsx("button",{type:"button",className:"btn btn-primary btn-sm",onClick:Pr,disabled:G==="preview","data-testid":"dev-server-set-preview",children:a("devserver.save","Save")})]}),c&&r.jsx("p",{className:"dev-server-preview-hint",children:a("devserver.autoDetected","Auto-detected: {{url}}",{url:c})})]}),r.jsx("div",{className:"dev-server-content",children:r.jsxs("section",{className:"dev-server-panel dev-server-logs-panel","data-testid":"dev-server-logs-panel","aria-label":a("devserver.logsLabel","Dev server logs"),children:[r.jsxs("div",{className:"dev-server-section-header",children:[r.jsx("h3",{children:a("devserver.logs","Logs")}),r.jsx("span",{className:"dev-server-muted",children:a("devserver.lines","{{count}} lines",{count:P??j.length})})]}),r.jsx("div",{className:"dev-server-logs-viewer","data-testid":"dev-server-log-viewer",children:r.jsx(Nt,{entries:j,loading:H,loadingMore:I,hasMore:B,total:P,onLoadMore:V,isRunning:A})})]})}),W?r.jsxs("section",{className:"dev-server-panel devserver-preview-modal-launcher","data-testid":"devserver-preview-modal-launcher","aria-label":a("devserver.previewLabel","Dev server preview"),children:[r.jsxs("div",{className:"devserver-preview-modal-launcher__copy",children:[r.jsxs("div",{className:"devserver-preview-title",children:[r.jsx(We,{size:14}),r.jsx("span",{children:a("devserver.preview","Preview")})]}),r.jsx("span",{className:"devserver-preview-url-badge devserver-preview-url-badge--auto",title:c??a("devserver.noPreviewUrl","No preview URL"),"data-testid":"devserver-preview-url-badge",children:c||a("devserver.notAvailable","Not available")})]}),r.jsx("p",{className:"devserver-preview-modal-launcher__description",children:c?a("devserver.previewModalLauncherDescription","Open the live preview in a modal so logs and configuration stay usable in this narrow dock."):a("devserver.previewModalLauncherUnavailable","Start the dev server or set a preview URL to open the preview modal.")}),r.jsx("button",{type:"button",className:"btn btn-primary btn-sm",ref:Oe,onClick:()=>xe(!0),"data-testid":"devserver-preview-modal-open",children:a("devserver.openPreview","Open preview")})]}):r.jsx("section",{className:"dev-server-panel devserver-preview-panel","data-testid":"devserver-preview-panel","aria-label":a("devserver.previewLabel","Dev server preview"),children:Be()}),W&&ie&&r.jsx("div",{className:"modal-overlay open devserver-preview-modal-overlay",...kr,children:r.jsxs("div",{className:"modal devserver-preview-modal",role:"dialog","aria-modal":"true","aria-labelledby":"devserver-preview-modal-title",tabIndex:-1,ref:ye,"data-testid":"devserver-preview-modal",children:[r.jsxs("div",{className:"devserver-preview-modal__titlebar",children:[r.jsx("h2",{id:"devserver-preview-modal-title",children:a("devserver.preview","Preview")}),r.jsx("button",{type:"button",className:"btn btn-sm btn-icon",onClick:ve,"aria-label":a("devserver.closePreviewModal","Close preview modal"),"data-testid":"devserver-preview-modal-close",children:r.jsx(Yr,{})})]}),r.jsx("div",{className:"devserver-preview-modal__body",children:Be()})]})})]})}export{$t as DevServerView};
@@ -0,0 +1 @@
1
+ import{r as n,j as r}from"./vendor-react-SZ_qB27O.js";import{K as z,N as D,O as S,Q as f,g as j,U as T,E as B,p as A,P as K,L,h as N}from"./index-CBFPgFTp.js";import{u as U}from"./vendor-i18n-Duky4gdQ.js";import{F as R}from"./folder-open-nMraSDXu.js";function J({value:b,onChange:h,placeholder:F,onInputKeyDown:g,nodeId:k,localNodeId:m,selectCreatedDirectory:x=!1}){const{t:i}=U("app"),[e,s]=n.useState({isOpen:!1,loading:!1,error:null,currentPath:"",parentPath:null,entries:[],showHidden:!1,createFolderOpen:!1,createFolderError:null}),[p,u]=n.useState(""),d=n.useCallback(async(t,c=!1)=>{s(o=>({...o,loading:!0,error:null}));try{const o=await z(t,c,k,m);s(a=>({...a,loading:!1,currentPath:o.currentPath,parentPath:o.parentPath,entries:o.entries}))}catch(o){s(a=>({...a,loading:!1,error:o instanceof Error?o.message:"Failed to browse directory"}))}},[k,m]),C=n.useCallback(()=>{s(t=>t.isOpen?{...t,isOpen:!1}:{...t,isOpen:!0})},[]);n.useEffect(()=>{e.isOpen&&!e.loading&&!e.currentPath&&!e.error&&d(b||void 0,e.showHidden)},[e.isOpen,e.loading,e.currentPath,e.error,b,e.showHidden,d,k,m]);const y=n.useCallback(t=>{d(t,e.showHidden)},[d,e.showHidden]),H=n.useCallback(()=>{h(e.currentPath),s(t=>({...t,isOpen:!1}))},[e.currentPath,h]),E=n.useCallback(()=>{s(t=>{const c=!t.showHidden;return{...t,showHidden:c}})},[]);n.useEffect(()=>{e.isOpen&&e.currentPath&&d(e.currentPath,e.showHidden)},[e.showHidden,d]);const w=n.useCallback(()=>{s(t=>({...t,createFolderOpen:!t.createFolderOpen,createFolderError:null})),u("")},[]),P=n.useCallback(async()=>{if(!p.trim()||!e.currentPath)return;const t=p.trim();if(t.includes("/")||t.includes("\\")||t.includes("..")){s(a=>({...a,createFolderError:i("dirPicker.createFolderError","Folder name cannot contain path separators or '..'")}));return}const c=e.currentPath.includes("\\")?"\\":"/",o=e.currentPath.endsWith(c)?e.currentPath+t:e.currentPath+c+t;s(a=>({...a,loading:!0,createFolderError:null}));try{const a=await D(o);u(""),s(l=>({...l,createFolderOpen:!1})),x?(h(a.path),await d(a.path,e.showHidden),s(l=>l.error?{...l,isOpen:!1,error:null}:l)):await d(e.currentPath,e.showHidden)}catch(a){s(l=>({...l,loading:!1,createFolderError:a instanceof Error?a.message:"Failed to create folder"}))}},[p,e.currentPath,e.showHidden,d,h,x]),O=n.useCallback(t=>{t.key==="Enter"?(t.preventDefault(),P()):t.key==="Escape"&&(s(c=>({...c,createFolderOpen:!1,createFolderError:null})),u(""))},[P]),v=e.currentPath?S(e.currentPath):[];return r.jsxs("div",{className:"directory-picker",children:[r.jsxs("div",{className:"directory-picker-input-row",children:[r.jsx("input",{type:"text",className:"input directory-picker-input",value:b,onChange:t=>h(t.target.value),onKeyDown:g,placeholder:F||i("dirPicker.defaultPlaceholder","/path/to/your/project")}),r.jsxs("button",{type:"button",className:"btn btn-secondary btn-sm directory-picker-browse-btn",onClick:C,"aria-label":e.isOpen?i("dirPicker.closeBrowser","Close directory browser"):i("dirPicker.openBrowser","Browse directories"),children:[e.isOpen?r.jsx(R,{size:16}):r.jsx(f,{size:16}),r.jsx("span",{children:i("dirPicker.browse","Browse")})]})]}),e.isOpen&&r.jsxs("div",{className:"directory-picker-browser",role:"tree","aria-label":i("dirPicker.ariaLabel","Directory browser"),children:[r.jsx("div",{className:"directory-picker-breadcrumbs",children:v.map((t,c)=>r.jsxs("span",{className:"directory-picker-breadcrumb-item",children:[c>0&&r.jsx(j,{size:12,className:"directory-picker-breadcrumb-sep"}),r.jsx("button",{type:"button",className:"directory-picker-breadcrumb",onClick:()=>y(t.path),title:t.path,children:t.label})]},t.path))}),r.jsxs("div",{className:"directory-picker-toolbar",children:[e.parentPath&&r.jsxs("button",{type:"button",className:"btn btn-sm btn-secondary directory-picker-up-btn",onClick:()=>y(e.parentPath),"aria-label":i("dirPicker.parentDir","Go to parent directory"),title:i("dirPicker.parentDirTitle","Parent directory"),children:[r.jsx(T,{size:14}),r.jsx("span",{children:i("dirPicker.up","Up")})]}),r.jsxs("button",{type:"button",className:"btn btn-sm btn-secondary directory-picker-hidden-toggle",onClick:E,"aria-label":e.showHidden?i("dirPicker.hideHiddenAria","Hide hidden directories"):i("dirPicker.showHiddenAria","Show hidden directories"),title:e.showHidden?i("dirPicker.hideHiddenTitle","Hide hidden"):i("dirPicker.showHiddenTitle","Show hidden"),children:[e.showHidden?r.jsx(B,{size:14}):r.jsx(A,{size:14}),r.jsx("span",{children:e.showHidden?i("dirPicker.hideHidden","Hide hidden"):i("dirPicker.showHidden","Show hidden")})]}),r.jsxs("button",{type:"button",className:"btn btn-sm btn-secondary directory-picker-create-folder-toggle",onClick:w,"aria-label":i("dirPicker.createFolderAria","Create new folder"),title:i("dirPicker.createFolderTitle","Create folder"),children:[r.jsx(K,{size:14}),r.jsx("span",{children:i("dirPicker.createFolder","New folder")})]})]}),e.loading?r.jsxs("div",{className:"directory-picker-loading",children:[r.jsx(L,{size:20,className:"animate-spin"}),r.jsx("span",{children:i("dirPicker.loading","Loading…")})]}):e.error?r.jsxs("div",{className:"directory-picker-error",children:[r.jsx(N,{size:16}),r.jsx("span",{children:e.error})]}):r.jsx("div",{className:"directory-picker-entries",children:e.entries.length===0?r.jsx("div",{className:"directory-picker-empty",children:i("dirPicker.noSubdirs","No subdirectories")}):e.entries.map(t=>r.jsxs("button",{type:"button",className:"directory-picker-entry",onClick:()=>y(t.path),role:"treeitem",title:t.path,children:[r.jsx(f,{size:16,className:"directory-picker-entry-icon"}),r.jsx("span",{className:"directory-picker-entry-name",children:t.name}),t.hasChildren&&r.jsx(j,{size:14,className:"directory-picker-entry-arrow"})]},t.path))}),e.createFolderOpen&&r.jsxs("div",{className:"directory-picker-create-folder",children:[r.jsx("input",{type:"text",className:"input directory-picker-create-folder-input",value:p,onChange:t=>u(t.target.value),onKeyDown:O,placeholder:i("dirPicker.newFolderPlaceholder","Folder name"),autoFocus:!0}),r.jsxs("div",{className:"directory-picker-create-folder-actions",children:[r.jsx("button",{type:"button",className:"btn btn-sm btn-primary",onClick:P,disabled:!p.trim()||e.loading||!e.currentPath,children:i("dirPicker.createFolderConfirm","Create")}),r.jsx("button",{type:"button",className:"btn btn-sm btn-secondary",onClick:w,children:i("dirPicker.cancel","Cancel")})]}),e.createFolderError&&r.jsxs("div",{className:"directory-picker-create-folder-error",children:[r.jsx(N,{size:14}),r.jsx("span",{children:e.createFolderError})]})]}),r.jsxs("div",{className:"directory-picker-actions",children:[r.jsx("span",{className:"directory-picker-selected-path",title:e.currentPath,children:e.currentPath}),r.jsx("button",{type:"button",className:"btn btn-primary directory-picker-select-btn",onClick:H,children:i("dirPicker.select","Select")})]})]})]})}export{J as D};
@@ -0,0 +1 @@
1
+ import{r as n,j as e}from"./vendor-react-SZ_qB27O.js";import{ab as Ue,ac as Ve,ad as Ht,ae as zt,af as It,ag as Ye,ah as Ot,ai as $t,aj as fe,ak as Bt,al as qe,am as _t,an as Ut,ao as Vt,ap as qt,aq as Pe,ar as Qt,as as Qe,V as Gt,at as ce,E as Wt,p as Kt,au as Yt,X as Xt,R as Jt,av as ke,A as Ge,v as We,aw as Ke,j as Ee,r as De,ax as Zt,ay as Xe,az as es,aA as ts,aB as ss,aC as ns,z as as,aD as cs,aE as os,aF as rs,aG as is}from"./index-CBFPgFTp.js";import{u as ls}from"./vendor-i18n-Duky4gdQ.js";import"./vendor-codemirror-CcrtqoCy.js";import"./vendor-reactflow-BlIeoTu4.js";import"./vendor-xterm-BNq00GSj.js";function ds(a){const{projectId:d,searchQuery:m,includeProjectFiles:y=!0}=a??{},v=d?`${Ht.DOCUMENTS_PREFIX}${d}`:null,[w,t]=n.useState(()=>{if(!v)return[];const b=Ue(v,{maxAgeMs:Ve});return Array.isArray(b)?b:[]}),[l,r]=n.useState([]),[A,u]=n.useState(()=>w.length===0),[P,p]=n.useState(null),f=n.useRef(null),j=n.useRef(w.length>0),h=n.useRef(null),{capture:N}=zt(d,"useDocuments"),E=n.useCallback(async()=>{const b=N();f.current&&f.current.abort();const T=new AbortController;f.current=T;const J=!j.current;J&&u(!0),p(null);const V=It(m?{q:m}:void 0,d),Z=y?Ye(d):Promise.resolve({files:[]}),[S,C]=await Promise.allSettled([V,Z]);if(T.signal.aborted||b.isStale())return;let re=null;if(S.status==="fulfilled"){if(t(S.value),v){const D=S.value.length>500?S.value.slice(0,500):S.value;Ot(v,D,{maxBytes:5e5})}j.current=!0}else re=S.reason instanceof Error?S.reason.message:String(S.reason);if(C.status==="fulfilled"){const D=C.value.files,W=m?.trim().toLowerCase(),ie=W?D.filter(ee=>ee.name.toLowerCase().includes(W)||ee.path.toLowerCase().includes(W)):D;r(ie)}p(re),J&&u(!1)},[v,N,y,d,m]);return n.useEffect(()=>{if(r([]),!v){j.current=!1,t([]),u(!0);return}const b=Ue(v,{maxAgeMs:Ve});Array.isArray(b)?(t(b),j.current=!0,u(!1)):(j.current=!1,t([]),u(!0))},[v]),n.useEffect(()=>(h.current&&clearTimeout(h.current),h.current=setTimeout(()=>{E()},300),()=>{h.current&&clearTimeout(h.current)}),[E]),n.useEffect(()=>(E(),()=>{f.current&&f.current.abort()}),[]),{documents:w,projectFiles:l,loading:A,error:P,refresh:E}}function us(a,d){const[m,y]=n.useState([]),[v,w]=n.useState(!0),[t,l]=n.useState(null),r=n.useRef(null),A=n.useRef(!1),u=d?.showHidden??!1,P=n.useCallback(async p=>{r.current&&r.current.abort();const f=new AbortController;r.current=f;const j=!A.current;j&&w(!0),l(null);try{const h=await Ye(a,{showHidden:p?.showHidden??u});if(f.signal.aborted)return;y(h.files),A.current=!0}catch(h){if(f.signal.aborted)return;l(h instanceof Error?h.message:String(h))}finally{!f.signal.aborted&&j&&w(!1)}},[a,u]);return n.useEffect(()=>(A.current=!1,P({showHidden:u}),()=>{r.current&&r.current.abort()}),[P,u]),{files:m,loading:v,error:t,refresh:P}}const ms=768,hs={image:ns,doc:ce,pdf:ss,video:ts,audio:es,other:Xe};function oe(a){return a?new Date(a).toLocaleString():""}function fs(a){return a<1024?`${a} B`:a<1024*1024?`${(a/1024).toFixed(a>=10*1024?0:1)} KB`:`${(a/(1024*1024)).toFixed(1)} MB`}function ks(a,d){return d?d.archived?"status-dot status-dot--offline":d.complete?"status-dot status-dot--online":d.intake||d.hold?"status-dot status-dot--pending":"status-dot status-dot--connecting":a==="done"?"status-dot status-dot--online":a==="archived"?"status-dot status-dot--offline":ps.has(a)?"status-dot status-dot--pending":"status-dot status-dot--connecting"}const ps=new Set(["triage","todo"]);function Je(a,d){switch(d){case"image":return a("documents.artifactCategoryImage","Image");case"doc":return a("documents.artifactCategoryDoc","Document");case"pdf":return a("documents.artifactCategoryPdf","PDF");case"video":return a("documents.artifactCategoryVideo","Video");case"audio":return a("documents.artifactCategoryAudioSingle","Audio");case"other":return a("documents.artifactCategoryOtherSingle","Other")}}function js(a,d){return d?[a.title,a.description,a.taskId,a.taskTitle,a.mimeType,a.authorId].some(m=>m?.toLowerCase().includes(d)):!0}function xs(a){const d=a.mimeType?.toLowerCase().split(";",1)[0]??"";return!!a.content||a.type==="document"||d.startsWith("text/")||d==="application/json"||d==="application/xml"}function bs({artifact:a,projectId:d,content:m,loading:y,error:v,renderMarkdown:w,onToggleMarkdown:t,onOpenTask:l,t:r}){const[A,u]=n.useState(null),[P,p]=n.useState(!1),f=Pe(a),j=Je(r,f),h=a.title||r("documents.untitledArtifact","Untitled artifact"),N=as(a.id,d),E=f==="doc"&&xs(a);n.useEffect(()=>{u(null)},[a.id]);const b=A?e.jsx("p",{className:"documents-content-state documents-content-state--error",children:A}):null,T=f==="image"?e.jsxs(e.Fragment,{children:[b,e.jsx("button",{type:"button",className:"documents-task-artifact-image-button",onClick:()=>p(!0),"aria-label":r("documents.expandImageArtifact","Expand image artifact {{title}}",{title:h}),children:e.jsx(cs,{className:"documents-task-artifact-media",artifactId:a.id,projectId:d,title:h,onError:()=>u(r("documents.artifactMediaFailed","Failed to load artifact preview."))})}),P&&e.jsx(os,{artifactId:a.id,projectId:d,title:h,onClose:()=>p(!1)})]}):f==="video"?e.jsxs(e.Fragment,{children:[b,e.jsx("video",{className:"documents-task-artifact-media",controls:!0,src:N,"aria-label":r("documents.videoArtifactLabel","Video artifact: {{title}}",{title:h}),onError:()=>u(r("documents.artifactMediaFailed","Failed to load artifact preview."))})]}):f==="audio"?e.jsxs(e.Fragment,{children:[b,e.jsx("audio",{className:"documents-task-artifact-audio",controls:!0,src:N,"aria-label":r("documents.audioArtifactLabel","Audio artifact: {{title}}",{title:h}),onError:()=>u(r("documents.artifactMediaFailed","Failed to load artifact preview."))})]}):f==="pdf"?e.jsxs("div",{className:"documents-task-artifact-pdf",children:[e.jsx("iframe",{title:r("documents.pdfArtifactTitle","PDF artifact: {{title}}",{title:h}),src:N}),e.jsxs("a",{className:"btn btn-sm",href:N,target:"_blank",rel:"noreferrer",children:[e.jsx(rs,{size:14,"aria-hidden":"true"}),r("documents.openInNewTab","Open in new tab")]})]}):f==="doc"&&E?y?e.jsx("p",{className:"documents-content-state",children:e.jsx(ke,{label:r("documents.loadingArtifactContent","Loading artifact content…")})}):v?e.jsx("p",{className:"documents-content-state documents-content-state--error",children:v}):w?e.jsx("div",{className:"documents-content-markdown documents-task-artifact-doc-content",children:e.jsx("div",{className:"markdown-body",children:e.jsx(Ee,{remarkPlugins:[De],children:m??a.content??""})})}):e.jsx("pre",{className:"document-card-content-text documents-content-viewer-text documents-task-artifact-doc-content",children:m??a.content??""}):e.jsxs("div",{className:"documents-task-artifact-download",children:[e.jsx(Xe,{size:24,"aria-hidden":"true"}),e.jsx("p",{children:a.description||r("documents.binaryArtifactFallback","This artifact cannot be previewed inline.")}),e.jsxs("a",{className:"btn btn-sm",href:N,target:"_blank",rel:"noreferrer","data-testid":"task-artifact-open-link",children:[e.jsx(is,{size:14,"aria-hidden":"true"}),r("documents.openArtifact","Open artifact")]})]});return e.jsxs("div",{className:"documents-content-viewer documents-task-artifact-viewer",children:[e.jsxs("div",{className:"documents-content-header documents-task-document-header",children:[e.jsxs("p",{className:"documents-file-path-header",children:[a.taskId," / ",h]}),f==="doc"&&E?e.jsx("button",{className:"btn btn-sm document-mode-toggle",onClick:t,"aria-label":w?r("documents.switchToPlainText","Switch to plain text"):r("documents.switchToMarkdown","Switch to markdown"),"aria-pressed":w,title:w?r("documents.switchToPlainText","Switch to plain text"):r("documents.switchToMarkdown","Switch to markdown"),children:w?r("documents.markdown","Markdown"):r("documents.plain","Plain")}):null]}),e.jsxs("div",{className:"document-card-meta documents-task-document-meta documents-task-artifact-meta",children:[e.jsx("span",{children:j}),e.jsx("span",{className:"document-card-separator",children:"·"}),e.jsx("span",{children:a.authorId||r("documents.unknownAuthor","unknown")}),e.jsx("span",{className:"document-card-separator",children:"·"}),e.jsx("span",{children:oe(a.updatedAt)}),a.taskId?e.jsxs(e.Fragment,{children:[e.jsx("span",{className:"document-card-separator",children:"·"}),e.jsx("button",{className:"documents-task-artifact-open-task",onClick:()=>void l(a.taskId),children:r("documents.openTask","Open task")})]}):null]}),a.description?e.jsx("p",{className:"documents-task-artifact-description",children:a.description}):null,e.jsx("div",{className:`documents-task-artifact-preview documents-task-artifact-preview--${f}`,children:T})]})}function ys({projectId:a,columnFlagsByTaskId:d,addToast:m,onOpenDetail:y,onOpenArtifactTaskDetail:v,onSendSelectionToTask:w}){const{t}=ls("app"),[l,r]=n.useState("artifacts"),A=$t(),[u,P]=n.useState(""),[p,f]=n.useState(null),[j,h]=n.useState(null),[N,E]=n.useState(!1),[b,T]=n.useState(null),[J,V]=n.useState(!1),[Z,S]=n.useState(null),[C,re]=n.useState(!1),D=n.useRef(0),W=n.useRef(null),ie=n.useRef(null),ee=n.useRef(null),Le=n.useRef(null),[K,Me]=n.useState(!1),[Ze,Re]=n.useState(new Map),[et,R]=n.useState(null),[pe,L]=n.useState(""),[le,M]=n.useState(null),[q,F]=n.useState(null),[de,je]=n.useState(!1),[tt,H]=n.useState(null),[st,B]=n.useState(!1),[nt,z]=n.useState(null),[at,xe]=n.useState(!0),te=n.useRef(0),[be,Q]=n.useState(!1),[ue,_]=n.useState(""),[we,ge]=n.useState(!1),[me,He]=n.useState(!1),ct=fe(W,{locked:me}),ot=fe(ie,{locked:me}),rt=fe(ee,{locked:me}),it=fe(Le,{locked:me}),ve=K?ct:ot,Ne=l==="tasks"?u.trim():"",lt=l==="artifacts"?u.trim():"",{documents:se,loading:dt,error:ut,refresh:ne}=ds({projectId:a,searchQuery:Ne||void 0,includeProjectFiles:!1}),{files:G,loading:mt,error:ht,refresh:ze}=us(a,{showHidden:N}),{artifacts:I,loading:ft,error:kt,refresh:Se}=Bt({projectId:a,searchQuery:lt||void 0});n.useEffect(()=>{const s=()=>{re(window.innerWidth<=ms)};return s(),window.addEventListener("resize",s),()=>{window.removeEventListener("resize",s)}},[]),n.useEffect(()=>{r("artifacts"),f(null),h(null),E(!1),T(null),S(null),V(!1),Me(!1),Re(new Map),R(null),L(""),M(null),F(null),je(!1),H(null),B(!1),z(null),xe(!0),Q(!1),_(""),ge(!1)},[a]);const Y=n.useMemo(()=>{const s=Ne.toLowerCase(),c=new Map;for(const o of se){const x=c.get(o.taskId)??{documents:[],artifacts:[]};x.documents.push(o),c.set(o.taskId,x)}for(const o of I){if(!o.taskId||!js(o,s))continue;const x=c.get(o.taskId)??{documents:[],artifacts:[]};x.artifacts.push(o),c.set(o.taskId,x)}return Array.from(c.entries()).map(([o,x])=>{const $=[...x.documents].sort((g,ae)=>ae.updatedAt.localeCompare(g.updatedAt)),U=[...x.artifacts].sort((g,ae)=>ae.updatedAt.localeCompare(g.updatedAt)),Ae=[$[0]?.updatedAt,U[0]?.updatedAt].filter(Boolean).sort().at(-1)??"",k=$.find(g=>g.taskTitle)?.taskTitle??U.find(g=>g.taskTitle)?.taskTitle;return{taskId:o,taskTitle:k,taskColumn:$.find(g=>g.taskColumn)?.taskColumn??U.find(g=>g.taskColumn)?.taskColumn,documents:$,artifacts:U,latestUpdated:Ae}}).filter(o=>o.documents.length>0||o.artifacts.length>0).sort((o,x)=>x.latestUpdated.localeCompare(o.latestUpdated))},[I,se,Ne]),i=n.useMemo(()=>j?.kind!=="document"?null:se.find(s=>s.id===j.id)??null,[se,j]),O=n.useMemo(()=>j?.kind!=="artifact"?null:I.find(s=>s.id===j.id)??null,[I,j]),he=i??O;n.useEffect(()=>{if(!j)return;Y.some(c=>j.kind==="document"?c.documents.some(o=>o.id===j.id):c.artifacts.some(o=>o.id===j.id))||(h(null),R(null),L(""),M(null),F(null),H(null),B(!1),z(null))},[Y,j]);const Ce=n.useMemo(()=>{const s=u.trim().toLowerCase();return s?G.filter(c=>{const o=c.path.toLowerCase(),x=c.name.toLowerCase();return o.includes(s)||x.includes(s)}):G},[G,u]);n.useEffect(()=>{if(!p)return;G.some(c=>c.path===p.path)||(f(null),T(null),S(null),V(!1))},[G,p]);const pt=n.useCallback(s=>{P(s.target.value)},[]),jt=n.useCallback(()=>{P("")},[]),ye=n.useCallback(s=>{r(s),s!=="tasks"&&(h(null),R(null),L(""),M(null),F(null),H(null),B(!1),z(null)),s!=="project"&&(Q(!1),_(""))},[]),xt=n.useCallback(async s=>{try{const c=await qe(s,a);y(c)}catch{m(`Failed to open task ${s}`,"error")}},[a,y,m]),Ie=n.useCallback(async s=>{try{const c=await qe(s,a);(v??y)(c)}catch{m(`Failed to open task ${s}`,"error")}},[a,v,y,m]),bt=n.useCallback(async s=>{f(s),V(!0),S(null),T(null),Q(!1),_("");const c=D.current+1;D.current=c;try{const o=await _t("project",s.path,a);if(D.current!==c)return;T(o.content)}catch(o){if(D.current!==c)return;const x=o instanceof Error?o.message:`Failed to open ${s.path}`;S(x),m(x,"error")}finally{D.current===c&&V(!1)}},[a,m]),wt=n.useCallback(()=>{f(null),T(null),S(null),V(!1),Q(!1),_("")},[]),gt=n.useCallback(()=>{b!==null&&(_(b),Q(!0))},[b]),vt=n.useCallback(()=>{Q(!1),_("")},[]),Nt=n.useCallback(async()=>{if(p){ge(!0);try{await Ut("project",p.path,ue,a),T(ue),Q(!1),_(""),m(t("documents.projectFileSaved","File saved"),"success")}catch(s){m(s instanceof Error?s.message:String(s),"error")}finally{ge(!1)}}},[p,ue,a,m,t]),St=n.useCallback(s=>{h({kind:"document",id:s}),R(null),L(""),M(null),F(null),H(null),B(!1),z(null)},[]),Ct=n.useCallback(s=>{h({kind:"artifact",id:s}),R(null),L(""),M(null),F(null),H(null),z(null),xe(!0)},[]),yt=n.useCallback(()=>{h(null),R(null),L(""),M(null),F(null),H(null),B(!1),z(null)},[]),Tt=n.useCallback(s=>{Re(c=>{const o=new Map(c),x=o.get(s)??!0;return o.set(s,!x),o})},[]),Ft=n.useCallback(()=>{i&&(L(i.content),R(i.id),M({revision:i.revision,contentHash:i.contentHash}),F(null))},[i]),At=n.useCallback(()=>{R(null),L(""),M(null),F(null)},[]),Pt=n.useCallback(()=>{q&&(M(q),F(null))},[q]),Et=n.useCallback(async()=>{if(!(!i||!le||q)){je(!0);try{await Vt(i.taskId,i.key,pe,{expectedRevision:le.revision,expectedContentHash:le.contentHash},a),await ne(),R(null),L(""),M(null),F(null),m(t("documents.taskDocumentSaved","Document saved"),"success")}catch(s){if(typeof s=="object"&&s!==null&&"status"in s&&s.status===409)try{const c=await qt(i.taskId,i.key,a);await ne(),F({revision:c.revision,contentHash:c.contentHash}),m(t("documents.taskDocumentStale","This document changed since you opened it. Your draft is preserved; review the latest revision, then choose Rebase draft before saving."),"error")}catch(c){m(c instanceof Error?c.message:String(c),"error")}else m(s instanceof Error?s.message:String(s),"error")}finally{je(!1)}}},[i,pe,le,q,a,ne,m,t]);n.useEffect(()=>{if(!O||Pe(O)!=="doc"){H(null),B(!1),z(null);return}const s=te.current+1;te.current=s,B(!0),z(null),H(null),Qt(O.id,a).then(c=>{te.current===s&&H(c.content??O.content??"")}).catch(c=>{te.current===s&&z(c instanceof Error?c.message:String(c))}).finally(()=>{te.current===s&&B(!1)})},[a,O]);const Oe=l==="project"?ht:l==="tasks"?ut:kt,Dt=n.useCallback(async()=>{if(l==="project"){await ze();return}if(l==="tasks"){await ne();return}await Se()},[l,Se,ze,ne]),$e=l==="project"?Ce.length:l==="tasks"?Y.length:I.length,X=i?Ze.get(i.id)??!0:!1,Te=X?rt:it,Fe=i!==null&&et===i.id,Lt=l==="project"&&p&&!be&&w&&ve?e.jsx(Qe,{selectedText:ve.selectedText,anchorRect:ve.anchorRect,filePath:p.path,onSubmit:w,onOpenChange:He}):null,Mt=l==="tasks"&&i&&!Fe&&w&&Te?e.jsx(Qe,{selectedText:Te.selectedText,anchorRect:Te.anchorRect,filePath:`${i.taskId}/${i.key}`,onSubmit:w,onOpenChange:He}):null,Be=l==="project"?t("documents.searchProjectFiles","Search project markdown files…"):l==="tasks"?t("documents.searchTaskDocuments","Search task documents…"):t("documents.searchArtifacts","Search artifacts…");return e.jsxs("div",{className:"documents-view",children:[e.jsxs("div",{className:"documents-view-header",children:[e.jsx(Gt,{icon:ce,title:t("documents.title","Artifacts"),actions:e.jsx("span",{className:"documents-view-count",children:t("documents.resultCount","{{count}} result{{plural}}",{count:$e,plural:$e!==1?"s":""})})}),e.jsxs("div",{className:"documents-controls-row",children:[e.jsxs("div",{className:"documents-tab-bar",role:"tablist","aria-label":t("documents.sectionsLabel","Documents sections"),children:[e.jsxs("button",{className:`btn documents-tab${l==="artifacts"?" active":""}`,role:"tab","aria-selected":l==="artifacts","aria-label":t("documents.showArtifacts","Show artifacts"),onClick:()=>ye("artifacts"),children:[t("documents.artifactsTab","Artifacts"),e.jsx("span",{className:"documents-tab-count",children:I.length})]}),e.jsxs("button",{className:`btn documents-tab${l==="project"?" active":""}`,role:"tab","aria-selected":l==="project","aria-label":t("documents.showProjectFiles","Show project markdown files"),onClick:()=>ye("project"),children:[t("documents.projectFilesTab","Project Files"),e.jsx("span",{className:"documents-tab-count",children:G.length})]}),e.jsxs("button",{className:`btn documents-tab${l==="tasks"?" active":""}`,role:"tab","aria-selected":l==="tasks","aria-label":t("documents.showTaskDocuments","Show task documents"),onClick:()=>ye("tasks"),children:[t("documents.taskDocumentsTab","Task Documents"),e.jsx("span",{className:"documents-tab-count",children:Y.length})]})]}),l==="project"&&e.jsxs("button",{className:"btn btn-sm documents-hidden-toggle",onClick:()=>E(s=>!s),"aria-pressed":N,"aria-label":N?t("documents.hideHidden","Hide hidden project files"):t("documents.showHidden","Show hidden project files"),title:N?t("documents.hideHiddenFiles","Hide hidden files"):t("documents.showHiddenFiles","Show hidden files"),children:[N?e.jsx(Wt,{size:14}):e.jsx(Kt,{size:14}),N?t("documents.hideHiddenLabel","Hide Hidden"):t("documents.showHiddenLabel","Show Hidden")]}),e.jsxs("div",{className:"documents-search",children:[e.jsx(Yt,{size:16,className:"documents-search-icon"}),e.jsx("input",{type:"text",className:"documents-search-input",placeholder:Be,value:u,onChange:pt,"aria-label":Be}),u&&e.jsx("button",{className:"documents-search-clear",onClick:jt,"aria-label":t("documents.clearSearch","Clear search"),children:e.jsx(Xt,{size:16})})]})]})]}),e.jsx("div",{className:"documents-view-content",children:Oe?e.jsxs("div",{className:"documents-view-error",children:[e.jsx("p",{children:t("documents.failedToLoad","Failed to load {{type}}: {{error}}",{type:l==="project"?t("documents.projectFiles","project files"):l==="tasks"?t("documents.taskDocuments","task documents"):t("documents.artifacts","artifacts"),error:Oe})}),e.jsxs("button",{className:"btn btn-primary",onClick:()=>void Dt(),"aria-label":t("documents.retryLoading","Retry loading documents"),children:[e.jsx(Jt,{size:16}),t("documents.retry","Retry")]})]}):l==="project"?mt&&G.length===0?e.jsx("div",{className:"documents-view-loading",children:e.jsx("p",{children:e.jsx(ke,{label:t("documents.loadingProjectFiles","Loading project markdown files…")})})}):Ce.length===0?e.jsx("div",{className:"documents-view-empty",children:u.trim()?e.jsx("p",{children:t("documents.noMatchProject",'No project markdown files match "{{query}}".',{query:u.trim()})}):e.jsxs(e.Fragment,{children:[e.jsx(ce,{size:48,className:"documents-view-empty-icon"}),e.jsx("p",{children:t("documents.noMarkdownFiles","No Markdown files found in this project.")})]})}):e.jsxs("div",{className:`documents-project-layout${C?" documents-project-layout--mobile":""}`,children:[(!C||!p)&&e.jsx("aside",{className:"documents-view-sidebar","aria-label":t("documents.projectMarkdownFilesLabel","Project markdown files"),children:e.jsx("ul",{className:"markdown-file-list",children:Ce.map(s=>{const c=p?.path===s.path;return e.jsx("li",{className:"markdown-file-list-item",children:e.jsxs("button",{className:`markdown-file-item${c?" markdown-file-item--selected":""}`,onClick:()=>void bt(s),"aria-label":`Open ${s.path}`,"aria-current":c?"true":void 0,children:[e.jsx("span",{className:"markdown-file-item-name",children:s.name}),e.jsx("span",{className:"markdown-file-item-path",children:s.path}),e.jsxs("span",{className:"markdown-file-item-meta",children:[fs(s.size)," · ",oe(s.mtime)]})]})},s.path)})})}),(!C||p)&&e.jsxs("section",{className:"documents-view-main","aria-label":t("documents.projectFilePreviewLabel","Project file content preview"),children:[C&&p&&e.jsxs("button",{className:"btn btn-sm documents-mobile-back",onClick:wt,"aria-label":t("documents.backToFilesList","Back to project files list"),children:[e.jsx(Ge,{size:14}),t("documents.backToFiles","Back to files")]}),p?e.jsxs("div",{className:"documents-content-viewer",children:[e.jsxs("div",{className:"documents-content-header",children:[e.jsx("p",{className:"documents-file-path-header",children:p.path}),e.jsx("div",{className:"documents-task-document-actions",children:be?e.jsxs(e.Fragment,{children:[e.jsx("button",{className:"btn btn-sm",onClick:vt,disabled:we,children:t("documents.cancelEdit","Cancel")}),e.jsx("button",{className:"btn btn-sm btn-primary",onClick:()=>void Nt(),disabled:we,children:we?t("documents.saving","Saving…"):t("documents.saveProjectFile","Save")})]}):e.jsxs(e.Fragment,{children:[e.jsx("button",{className:"btn btn-sm document-mode-toggle",onClick:()=>Me(s=>!s),"aria-label":K?t("documents.switchToPlainText","Switch to plain text"):t("documents.switchToMarkdown","Switch to markdown"),"aria-pressed":K,title:K?t("documents.switchToPlainText","Switch to plain text"):t("documents.switchToMarkdown","Switch to markdown"),children:K?t("documents.markdown","Markdown"):t("documents.plain","Plain")}),e.jsxs("button",{className:"btn btn-sm",onClick:gt,disabled:J||Z!==null||b===null,"aria-label":t("documents.editProjectFile","Edit project file"),children:[e.jsx(We,{size:14,"aria-hidden":"true"}),t("documents.edit","Edit")]})]})})]}),J?e.jsx("p",{className:"documents-content-state",children:e.jsx(ke,{label:t("documents.loadingFileContent","Loading file content…")})}):Z?e.jsx("p",{className:"documents-content-state documents-content-state--error",children:Z}):be?e.jsx("div",{className:"documents-task-document-editor","aria-label":t("documents.projectFileContentEditor","Project file content editor"),children:e.jsx(Ke,{content:ue,onChange:_,filePath:p.path,forceToolbarActionsVisible:!0})}):K?e.jsx("div",{ref:W,className:"documents-content-markdown",children:e.jsx("div",{className:"markdown-body",children:e.jsx(Ee,{remarkPlugins:[De],children:b??""})})}):e.jsx("pre",{ref:ie,className:"document-card-content-text documents-content-viewer-text",children:b??""}),Lt]}):e.jsx("div",{className:"documents-view-empty",children:e.jsx("p",{children:t("documents.selectFile","Select a Markdown file to view its content.")})})]})]}):l==="artifacts"?ft&&I.length===0?e.jsx("div",{className:"documents-view-loading",children:e.jsx("p",{children:t("documents.loadingArtifacts","Loading artifacts…")})}):I.length===0?e.jsx("div",{className:"documents-view-empty",children:u.trim()?e.jsx("p",{children:t("documents.noMatchArtifacts",'No artifacts match "{{query}}".',{query:u.trim()})}):e.jsxs(e.Fragment,{children:[e.jsx(ce,{size:48,className:"documents-view-empty-icon"}),e.jsx("p",{children:t("documents.noArtifacts","No artifacts yet.")}),e.jsx("p",{className:"documents-view-empty-hint",children:t("documents.artifactsCreatedBy","Agents register screenshots, wireframes, mockups, recordings, and documents here as they work on tasks.")})]})}):e.jsx(Zt,{artifacts:I,projectId:a,isMobile:C,addToast:m,onOpenTask:Ie,onArtifactUpdated:()=>void Se()}):dt&&se.length===0?e.jsx("div",{className:"documents-view-loading",children:e.jsx("p",{children:e.jsx(ke,{label:t("documents.loadingTaskDocuments","Loading task documents…")})})}):Y.length===0?e.jsx("div",{className:"documents-view-empty",children:u.trim()?e.jsx("p",{children:t("documents.noMatchTask",'No task documents match "{{query}}".',{query:u.trim()})}):e.jsxs(e.Fragment,{children:[e.jsx(ce,{size:48,className:"documents-view-empty-icon"}),e.jsx("p",{children:t("documents.noTaskDocuments","No task documents yet.")}),e.jsx("p",{className:"documents-view-empty-hint",children:t("documents.documentsCreatedIn","Documents are created in task detail tabs.")})]})}):e.jsxs("div",{className:`documents-project-layout documents-task-documents-layout${C?" documents-project-layout--mobile":""}`,children:[(!C||!he)&&e.jsx("aside",{className:"documents-view-sidebar documents-task-documents-sidebar","aria-label":t("documents.taskDocumentsListLabel","Task documents"),children:Y.map(({taskId:s,taskTitle:c,taskColumn:o,documents:x,artifacts:$})=>{const U=o?A(o):null,Ae=o?ks(o,d?.get(s)):"status-dot";return e.jsxs("section",{className:"documents-task-sidebar-group","aria-labelledby":`documents-task-group-${s}`,children:[e.jsxs("div",{className:"documents-task-sidebar-group-header",children:[e.jsxs("div",{className:"documents-task-sidebar-title-wrap",children:[e.jsxs("h3",{id:`documents-task-group-${s}`,className:"documents-task-sidebar-title",children:[e.jsx("span",{className:"documents-group-task-id",children:s}),e.jsx("span",{className:"documents-group-task-title",children:c||t("documents.untitled","Untitled")})]}),U?e.jsxs("span",{className:"documents-group-status badge","aria-label":t("documents.taskStatusAria","Task status: {{status}}",{status:U}),children:[e.jsx("span",{className:Ae,"aria-hidden":"true"}),e.jsx("span",{children:U})]}):null]}),e.jsxs("div",{className:"documents-task-sidebar-actions",children:[e.jsx("span",{className:"documents-group-count",children:t("documents.taskOutputCount","{{docCount}} doc{{docPlural}} · {{artifactCount}} artifact{{artifactPlural}}",{docCount:x.length,docPlural:x.length!==1?"s":"",artifactCount:$.length,artifactPlural:$.length!==1?"s":""})}),e.jsx("button",{className:"documents-group-task-link",onClick:()=>void xt(s),"aria-label":t("documents.openTaskAria","Open task {{taskId}}: {{title}}",{taskId:s,title:c||t("documents.untitled","Untitled")}),children:t("documents.openTask","Open task")})]})]}),e.jsxs("ul",{className:"markdown-file-list documents-task-document-list",children:[x.map(k=>{const g=i?.id===k.id;return e.jsx("li",{className:"markdown-file-list-item",children:e.jsxs("button",{className:`markdown-file-item documents-task-document-item${g?" markdown-file-item--selected":""}`,onClick:()=>St(k.id),"aria-label":t("documents.openTaskDocument","Open {{taskId}} {{key}}",{taskId:k.taskId,key:k.key}),"aria-current":g?"true":void 0,children:[e.jsx("span",{className:"markdown-file-item-name",children:k.key}),e.jsxs("span",{className:"markdown-file-item-path",children:[k.taskId," · ",k.taskTitle||t("documents.untitled","Untitled")]}),e.jsxs("span",{className:"markdown-file-item-meta",children:[t("documents.revisionShort","v{{revision}}",{revision:k.revision})," · ",k.author," · ",oe(k.updatedAt)]})]})},`document-${k.id}`)}),$.length>0?e.jsxs("li",{className:"documents-task-artifacts-subsection","aria-label":t("documents.taskArtifactsSubsection","Task artifacts"),children:[e.jsx("div",{className:"documents-task-artifacts-label",children:t("documents.taskArtifactsLabel","Artifacts")}),e.jsx("ul",{className:"markdown-file-list documents-task-artifact-list",children:$.map(k=>{const g=Pe(k),ae=hs[g],Rt=Je(t,g),_e=O?.id===k.id;return e.jsx("li",{className:"markdown-file-list-item",children:e.jsxs("button",{className:`markdown-file-item documents-task-document-item documents-task-artifact-item${_e?" markdown-file-item--selected":""}`,onClick:()=>Ct(k.id),"aria-label":t("documents.openTaskArtifact","Open {{taskId}} artifact {{title}}",{taskId:s,title:k.title||t("documents.untitledArtifact","Untitled artifact")}),"aria-current":_e?"true":void 0,children:[e.jsxs("span",{className:"documents-task-artifact-title-row",children:[e.jsx(ae,{size:14,"aria-hidden":"true"}),e.jsx("span",{className:"markdown-file-item-name",children:k.title||t("documents.untitledArtifact","Untitled artifact")})]}),e.jsxs("span",{className:"markdown-file-item-path",children:[Rt," · ",k.mimeType||k.type]}),e.jsxs("span",{className:"markdown-file-item-meta",children:[k.authorId||t("documents.unknownAuthor","unknown")," · ",oe(k.updatedAt)]})]})},`artifact-${k.id}`)})})]}):null]})]},s)})}),(!C||he)&&e.jsxs("section",{className:"documents-view-main","aria-label":t("documents.taskDocumentPreviewLabel","Task document content preview"),children:[C&&he&&e.jsxs("button",{className:"btn btn-sm documents-mobile-back",onClick:yt,"aria-label":t("documents.backToTaskDocumentsList","Back to task documents list"),children:[e.jsx(Ge,{size:14}),t("documents.backToTaskDocuments","Back to documents")]}),he?O?e.jsx(bs,{artifact:O,projectId:a,content:tt,loading:st,error:nt,renderMarkdown:at,onToggleMarkdown:()=>xe(s=>!s),onOpenTask:Ie,t}):i?e.jsxs("div",{className:"documents-content-viewer documents-task-document-viewer",children:[e.jsxs("div",{className:"documents-content-header documents-task-document-header",children:[e.jsxs("p",{className:"documents-file-path-header",children:[i.taskId," / ",i.key]}),e.jsx("div",{className:"documents-task-document-actions",children:Fe?e.jsxs(e.Fragment,{children:[e.jsx("button",{className:"btn btn-sm",onClick:At,disabled:de,children:t("documents.cancelEdit","Cancel")}),q&&e.jsx("button",{className:"btn btn-sm",onClick:Pt,disabled:de,children:t("documents.rebaseTaskDocument","Rebase draft")}),e.jsx("button",{className:"btn btn-sm btn-primary",onClick:()=>void Et(),disabled:de||q!==null,children:de?t("documents.saving","Saving…"):t("documents.saveTaskDocument","Save")})]}):e.jsxs(e.Fragment,{children:[e.jsx("button",{className:"btn btn-sm document-mode-toggle",onClick:()=>Tt(i.id),"aria-label":X?t("documents.switchToPlainText","Switch to plain text"):t("documents.switchToMarkdown","Switch to markdown"),"aria-pressed":X,title:X?t("documents.switchToPlainText","Switch to plain text"):t("documents.switchToMarkdown","Switch to markdown"),children:X?t("documents.markdown","Markdown"):t("documents.plain","Plain")}),e.jsxs("button",{className:"btn btn-sm",onClick:Ft,"aria-label":t("documents.editTaskDocument","Edit task document"),children:[e.jsx(We,{size:14,"aria-hidden":"true"}),t("documents.edit","Edit")]})]})})]}),e.jsxs("div",{className:"document-card-meta documents-task-document-meta",children:[e.jsx("span",{className:"document-card-author",children:i.author}),e.jsx("span",{className:"document-card-separator",children:"·"}),e.jsx("span",{children:t("documents.revisionShort","v{{revision}}",{revision:i.revision})}),e.jsx("span",{className:"document-card-separator",children:"·"}),e.jsx("span",{className:"document-card-date",children:oe(i.updatedAt)})]}),Fe?e.jsx("div",{className:"documents-task-document-editor","aria-label":t("documents.taskDocumentContentEditor","Task document content editor"),children:e.jsx(Ke,{content:pe,onChange:L,filePath:i.key.includes(".")?i.key:`${i.key}.md`,forceToolbarActionsVisible:!0})}):X?e.jsx("div",{ref:ee,className:"documents-content-markdown",children:e.jsx("div",{className:"markdown-body",children:e.jsx(Ee,{remarkPlugins:[De],children:i.content})})}):e.jsx("pre",{ref:Le,className:"document-card-content-text documents-content-viewer-text",children:i.content}),Mt]}):null:e.jsx("div",{className:"documents-view-empty",children:e.jsx("p",{children:t("documents.selectTaskDocument","Select a task document or artifact to view its content.")})})]})]})})]})}export{ys as DocumentsView,ks as getTaskColumnStatusDotClass};
@@ -0,0 +1 @@
1
+ import{r as l,j as e}from"./vendor-react-SZ_qB27O.js";import{ab as L,ac as P,ad as $,aH as Y,aI as Q,ah as H,aJ as Z,aK as ee,aL as se,V as O,T as K,aM as ae,R as te,av as le,s as re,l as ne,aF as ie}from"./index-CBFPgFTp.js";import{u as ce}from"./vendor-i18n-Duky4gdQ.js";import"./vendor-codemirror-CcrtqoCy.js";import"./vendor-reactflow-BlIeoTu4.js";import"./vendor-xterm-BNq00GSj.js";const oe=300,de=15e3;function B(r){if(!r.trim())return;const a=Number(r);return Number.isFinite(a)?a:void 0}function I(...r){for(const a of r)if(Array.isArray(a))return a;return[]}function f(r){return typeof r=="object"&&r!==null?r:{}}function X(r){const a=f(r),m=f(a.taskSnapshot);return{id:String(a.id??a.evalId??""),runId:String(a.runId??a.batchId??""),taskId:String(a.taskId??m.taskId??""),taskTitle:String(m.title??a.taskTitle??a.title??"Untitled task"),createdAt:String(a.createdAt??a.timestamp??a.updatedAt??new Date(0).toISOString()),overallScore:typeof a.overallScore=="number"?a.overallScore:null,maxScore:typeof a.maxScore=="number"?a.maxScore:null,categoryScores:I(a.categoryScores,f(a.scores).categories)}}function ue(r){const a=f(r);return{...X(a),rationale:String(a.rationale??a.summary??""),evidence:I(a.evidence,f(a.details).evidence),followUps:I(a.followUps,f(a.recommendations).followUps)}}function ve(r){const a=r?.projectId,m=a??"",t=`${$.EVALS_RUNS_PREFIX}${m}`,h=`${$.EVALS_RESULTS_PREFIX}${m}`,p=L(t,{maxAgeMs:P}),v=L(h,{maxAgeMs:P}),S=l.useRef(Array.isArray(p)&&p.length>0||Array.isArray(v)&&v.length>0),[o,g]=l.useState({q:"",runId:"",scoreMin:"",scoreMax:""}),[N,w]=l.useState(()=>Array.isArray(p)?p:[]),[d,M]=l.useState(()=>Array.isArray(v)?v:[]),[u,A]=l.useState(null),[F,R]=l.useState(null),[s,i]=l.useState(0),[y,j]=l.useState(!S.current),[W,z]=l.useState(null),C=l.useRef(0),V=l.useRef(a),T=l.useRef(u);T.current=u;const k=l.useCallback(async()=>{const c=++C.current;S.current||j(!0),z(null);try{const[n,x]=await Promise.all([Y({q:o.q||void 0,runId:o.runId||void 0,scoreMin:B(o.scoreMin),scoreMax:B(o.scoreMax),limit:100,offset:0},a),Q(a)]);if(c!==C.current)return;const E=I(n.results,n.evals,n.items).map(X);M(E),H(h,E.length>500?E.slice(0,500):E,{maxBytes:5e5}),i(typeof n.count=="number"?n.count:E.length);const q=I(x.runs,x.items).map(U=>{const b=f(U),D=f(b.counts);return{id:String(b.id??""),createdAt:String(b.createdAt??""),completedAt:typeof b.completedAt=="string"?b.completedAt:void 0,status:String(b.status??"pending"),evaluatedTaskCount:typeof D.totalTasks=="number"?D.totalTasks:0}});w(q),H(t,q,{maxBytes:5e5}),S.current=!0,T.current&&!E.some(U=>U.id===T.current)&&(A(null),R(null))}catch(n){if(c!==C.current)return;z(n instanceof Error?n.message:"Failed to load evals")}finally{c===C.current&&j(!1)}},[o.q,o.runId,o.scoreMax,o.scoreMin,a,h,t]),_=l.useCallback(async c=>{const n=await Z(c,a),x=n.result??n;R(ue(x))},[a]);l.useEffect(()=>{if(V.current===a)return;V.current=a;const c=L(t,{maxAgeMs:P}),n=L(h,{maxAgeMs:P}),x=Array.isArray(c)&&c.length>0||Array.isArray(n)&&n.length>0;w(Array.isArray(c)?c:[]),M(Array.isArray(n)?n:[]),j(!x),S.current=x},[a,h,t]),l.useEffect(()=>{const c=window.setTimeout(()=>{k()},oe);return()=>window.clearTimeout(c)},[k]),l.useEffect(()=>{if(!u){R(null);return}_(u)},[_,u]);const G=l.useCallback(()=>{k(),u&&_(u)},[_,k,u]);ee(G,de);const J=l.useCallback(c=>{T.current=c,A(c)},[]);return{loading:y,error:W,results:d,count:s,runs:N,filters:o,setFilters:g,refresh:k,selectedEvalId:u,setSelectedEvalId:J,selectedEval:F}}function je({projectId:r,onOpenSettings:a,onOpenTaskDetail:m}){const{t}=ce("app"),{loading:h,error:p,results:v,runs:S,filters:o,setFilters:g,selectedEvalId:N,setSelectedEvalId:w,selectedEval:d,refresh:M}=ve({projectId:r}),[u,A]=l.useState(!0);l.useEffect(()=>{let s=!1;return se(r).then(i=>{if(s)return;const y=i.evalSettings?.enabled;A(y??!1)}).catch(()=>{s||A(!1)}),()=>{s=!0}},[r]);const F=v.length>0,R=l.useMemo(()=>v.find(s=>s.id===N)??null,[v,N]);return u?e.jsxs("section",{className:"evals-view","data-testid":"evals-view",children:[e.jsx(O,{icon:K,title:t("evals.title","Evals")}),e.jsxs("div",{className:"evals-view__body",children:[e.jsxs("div",{className:"evals-list card",children:[e.jsxs("div",{className:"evals-toolbar",children:[e.jsx("input",{className:"input",placeholder:t("evals.searchPlaceholder","Search task or rationale"),value:o.q,onChange:s=>g(i=>({...i,q:s.target.value}))}),e.jsxs("select",{className:"select",value:o.runId,onChange:s=>g(i=>({...i,runId:s.target.value})),children:[e.jsx("option",{value:"",children:t("evals.allRuns","All runs")}),S.map(s=>e.jsx("option",{value:s.id,children:s.id},s.id))]}),e.jsx("input",{className:"input",placeholder:t("evals.minScorePlaceholder","Min score"),value:o.scoreMin,onChange:s=>g(i=>({...i,scoreMin:s.target.value}))}),e.jsx("input",{className:"input",placeholder:t("evals.maxScorePlaceholder","Max score"),value:o.scoreMax,onChange:s=>g(i=>({...i,scoreMax:s.target.value}))}),e.jsx("button",{className:"btn btn-icon",type:"button",onClick:()=>void M(),"aria-label":t("evals.refreshAria","Refresh evals"),children:e.jsx(te,{size:16})})]}),h&&e.jsx("p",{className:"evals-state","data-testid":"evals-loading",children:e.jsx(le,{label:t("evals.loading","Loading evals…")})}),p&&e.jsx("p",{className:"evals-state evals-state--error",children:p}),!h&&!p&&!F&&e.jsx("p",{className:"evals-state",children:t("evals.empty","No evals yet. Scheduled evals review tasks completed since the last run.")}),e.jsx("ul",{className:"evals-results","data-testid":"evals-results",children:v.map(s=>e.jsx("li",{children:e.jsxs("button",{className:`evals-result ${s.id===N?"evals-result--active":""}`,type:"button",onClick:()=>w(s.id),draggable:ne(),onDragStart:i=>{re(i.dataTransfer,{kind:"eval-result",id:s.id,projectId:r})},children:[e.jsx("span",{className:"evals-result-title",children:s.taskTitle}),e.jsxs("span",{className:"evals-result-meta",children:[s.taskId," · ",s.runId," · ",s.overallScore??t("evals.naPlaceholder","n/a")]})]})},s.id))})]}),e.jsxs("div",{className:"evals-detail card","data-testid":"evals-detail",children:[!d&&e.jsx("p",{className:"evals-state",children:t("evals.selectPrompt","Select an evaluation to inspect scores, rationale, and evidence.")}),d&&e.jsxs(e.Fragment,{children:[e.jsx("h3",{className:"evals-detail-title",children:R?.taskTitle??d.taskTitle}),e.jsxs("p",{className:"evals-result-meta",children:[d.taskId," · ",d.runId]}),e.jsx("p",{className:"evals-score",children:t("evals.overallScore","Overall score: {{score}}",{score:d.overallScore??t("evals.naPlaceholder","n/a")})}),e.jsx("ul",{className:"evals-categories",children:d.categoryScores.map(s=>e.jsxs("li",{children:[s.category,": ",s.finalScore]},s.category))}),e.jsx("p",{className:"evals-rationale",children:d.rationale||t("evals.noRationale","No rationale recorded.")}),e.jsxs("div",{children:[e.jsx("h4",{children:t("evals.evidenceHeading","Evidence")}),e.jsx("ul",{className:"evals-links",children:d.evidence.map((s,i)=>{const y=typeof s.metadata?.taskId=="string"?s.metadata.taskId:void 0,j=typeof s.metadata?.url=="string"?s.metadata.url:void 0;return e.jsx("li",{children:y?e.jsx("button",{type:"button",className:"btn",onClick:()=>m?.(y),children:s.ref}):j?e.jsxs("a",{href:j,target:"_blank",rel:"noreferrer",className:"evals-external-link",children:[s.ref,e.jsx(ie,{size:14})]}):e.jsx("span",{children:s.ref})},`${s.ref}-${i}`)})})]}),e.jsxs("div",{children:[e.jsx("h4",{children:t("evals.suggestedFollowupsHeading","Suggested follow-up tasks")}),e.jsxs("ul",{className:"evals-follow-ups",children:[d.followUps.length===0&&e.jsx("li",{children:t("evals.noFollowups","None")}),d.followUps.map(s=>e.jsxs("li",{children:[e.jsx("strong",{children:s.title}),e.jsx("p",{children:s.rationale})]},s.suggestionId))]})]})]})]})]})]}):e.jsxs("section",{className:"evals-view","data-testid":"evals-disabled",children:[e.jsx(O,{icon:K,title:t("evals.title","Evals")}),e.jsxs("div",{className:"evals-view__empty",children:[e.jsx("h2",{className:"evals-title",children:t("evals.disabledTitle","Scheduled evals are disabled")}),e.jsx("p",{className:"evals-empty-copy",children:t("evals.enablePrompt","Enable Scheduled Evals to review scored tasks, evidence, and follow-up recommendations.")}),e.jsxs("button",{className:"btn btn-primary",type:"button",onClick:()=>a?.("scheduled-evals"),children:[e.jsx(ae,{size:16}),t("evals.openSettings","Open Scheduled Evals Settings")]})]})]})}export{je as EvalsView};
@@ -0,0 +1 @@
1
+ import{r as s,j as e}from"./vendor-react-SZ_qB27O.js";import{B as F,D as V,F as W,G as $,H as z,I as K,J as B}from"./index-CBFPgFTp.js";import{u as J}from"./vendor-i18n-Duky4gdQ.js";import"./vendor-codemirror-CcrtqoCy.js";import"./vendor-reactflow-BlIeoTu4.js";import"./vendor-xterm-BNq00GSj.js";function te({isOpen:l,onClose:R,onUseDraft:M,projectId:x,existingAgents:P,mode:w="create",existingAgentConfig:L}){const{t:n}=J("app"),[g,d]=s.useState("initial"),[f,_]=s.useState(""),[c,S]=s.useState(null),[C,I]=s.useState(""),[k,A]=s.useState("answer"),[p,v]=s.useState(""),[t,H]=s.useState(null),[T,h]=s.useState(null),[E,y]=s.useState([]),b=w==="edit",o=s.useRef(l),N=s.useCallback(()=>{d("initial"),_(""),S(null),I(""),A("answer"),v(""),H(null),h(null),y([])},[]),D=s.useMemo(()=>F.map(a=>({id:a.id,label:a.name,description:a.description})),[]);s.useEffect(()=>{if(o.current=l,!c)return;const a=V(c,x,{onThinking:r=>{o.current&&y(Q=>{const u=[...Q],j=u[u.length-1];return j&&!j.question?(u[u.length-1]={...j,thinkingOutput:`${j.thinkingOutput??""}${r}`},u):[...u,{response:{},thinkingOutput:r}]})},onQuestion:r=>{o.current&&(I(r.question),A(r.id),d("question"))},onSummary:r=>{o.current&&(H(r),d("summary"))},onError:r=>{o.current&&(h(r),d("error"))}});return()=>{o.current=!1,a.close()}},[l,c,x]);const m=async()=>{o.current=!1;try{c&&await z(c,x)}catch{}finally{N(),R()}};if(s.useEffect(()=>{o.current=l,l||N()},[l,N]),!l)return null;const i=a=>a==null||a===""?e.jsx("em",{className:"experimental-agent-onboarding-modal__summary-empty",children:n("agents.onboarding.notSet","Not set")}):e.jsx("span",{children:a}),O=async()=>{d("loading"),h(null);try{const a=await K(f,{mode:w,existingAgentConfig:L,existingAgents:P.map(r=>({id:r.id,name:r.name,role:r.role})),templates:D},x);if(!o.current)return;S(a.sessionId)}catch(a){if(!o.current)return;h(a.message),d("error")}},q=async()=>{if(c){d("loading"),h(null);try{const a={[k]:p};if(y(r=>[...r,{question:{id:k,type:"text",question:C},response:a}]),await B(c,a,x),!o.current)return;v("")}catch(a){if(!o.current)return;h(a.message),d("error")}}},G=async()=>{t&&(M(t),await m())};return e.jsx(W,{windowKey:"experimental-agent-onboarding",modal:!0,title:n("agents.onboarding.title","AI Interview"),ariaLabel:n("agents.onboarding.dialogLabel","AI Interview"),onClose:()=>void m(),hideHeader:!0,dragHandleSelector:".experimental-agent-onboarding-modal .modal-header",className:"floating-window--experimental-agent-onboarding",defaultSize:{width:720,height:620},minSize:{width:420,height:320},persistGeometryKey:"floating-window:experimental-agent-onboarding",suspendGeometryPersistenceOnMobile:!0,suspendGeometryPersistenceOnShortViewport:!0,children:e.jsxs("div",{className:"modal modal-lg experimental-agent-onboarding-modal",children:[e.jsxs("div",{className:"modal-header",children:[e.jsx("h3",{children:n("agents.onboarding.title","AI Interview")}),e.jsx("button",{className:"modal-close",onClick:()=>void m(),"aria-label":n("common.closeAriaLabel","Close"),children:"×"})]}),E.length>0&&e.jsx($,{entries:E}),g==="initial"&&e.jsxs("div",{className:"form-group",children:[e.jsx("label",{htmlFor:"agent-onboarding-intent",children:b?n("agents.onboarding.intentLabelEdit","What should this agent change or improve?"):n("agents.onboarding.intentLabelCreate","What should this new agent own?")}),e.jsx("textarea",{id:"agent-onboarding-intent",className:"input experimental-agent-onboarding-modal__textarea",value:f,onChange:a=>_(a.target.value)}),e.jsxs("div",{className:"modal-actions",children:[e.jsx("button",{className:"btn",onClick:()=>void m(),children:n("common.cancel","Cancel")}),e.jsx("button",{className:"btn btn-primary",disabled:!f.trim(),onClick:()=>void O(),children:b?n("agents.onboarding.startInterview","Start interview"):n("agents.onboarding.startOnboarding","Start onboarding")})]})]}),(g==="loading"||g==="question")&&e.jsxs("div",{className:"form-group",children:[e.jsx("label",{htmlFor:"agent-onboarding-answer",children:C||n("agents.onboarding.thinking","Thinking...")}),e.jsx("textarea",{id:"agent-onboarding-answer",className:"input experimental-agent-onboarding-modal__textarea",value:p,onChange:a=>v(a.target.value)}),e.jsxs("div",{className:"modal-actions",children:[e.jsx("button",{className:"btn",onClick:()=>void m(),children:n("common.cancel","Cancel")}),e.jsx("button",{className:"btn btn-primary",disabled:g==="loading"||!p.trim(),onClick:()=>void q(),children:n("agents.onboarding.continue","Continue")})]})]}),g==="summary"&&t&&e.jsxs("div",{className:"form-group",children:[e.jsx("label",{children:b?n("agents.onboarding.updatedDraftReady","Updated draft ready for review"):n("agents.onboarding.draftReady","Draft ready for review")}),e.jsx("p",{className:"experimental-agent-onboarding-modal__summary-intro",children:n("agents.onboarding.draftIntro","Review this generated draft. Nothing is applied until you confirm.")}),e.jsxs("div",{className:"experimental-agent-onboarding-modal__summary card",children:[e.jsxs("div",{className:"experimental-agent-onboarding-modal__summary-section",children:[e.jsx("h4",{children:n("agents.onboarding.sectionIdentity","Identity")}),e.jsxs("dl",{className:"experimental-agent-onboarding-modal__summary-list",children:[e.jsxs("div",{children:[e.jsx("dt",{children:n("agents.onboarding.fieldName","Name")}),e.jsx("dd",{children:i(t.name)})]}),e.jsxs("div",{children:[e.jsx("dt",{children:n("agents.onboarding.fieldRole","Role")}),e.jsx("dd",{children:i(t.role)})]}),e.jsxs("div",{children:[e.jsx("dt",{children:n("agents.onboarding.fieldTitle","Title")}),e.jsx("dd",{children:i(t.title)})]}),e.jsxs("div",{children:[e.jsx("dt",{children:n("agents.onboarding.fieldIcon","Icon")}),e.jsx("dd",{children:i(t.icon)})]}),e.jsxs("div",{children:[e.jsx("dt",{children:n("agents.onboarding.fieldReportsTo","Reports To")}),e.jsx("dd",{children:i(t.reportsTo)})]})]})]}),e.jsxs("div",{className:"experimental-agent-onboarding-modal__summary-section",children:[e.jsx("h4",{children:n("agents.onboarding.sectionConfiguration","Configuration")}),e.jsxs("dl",{className:"experimental-agent-onboarding-modal__summary-list",children:[e.jsxs("div",{children:[e.jsx("dt",{children:n("agents.onboarding.fieldInlineInstructions","Inline Instructions")}),e.jsx("dd",{className:"experimental-agent-onboarding-modal__summary-block",children:i(t.instructionsText)})]}),e.jsxs("div",{children:[e.jsx("dt",{children:n("agents.onboarding.fieldSoul","Soul")}),e.jsx("dd",{className:"experimental-agent-onboarding-modal__summary-block",children:i(t.soul)})]}),e.jsxs("div",{children:[e.jsx("dt",{children:n("agents.onboarding.fieldAgentMemory","Agent Memory")}),e.jsx("dd",{className:"experimental-agent-onboarding-modal__summary-block",children:i(t.memory)})]}),e.jsxs("div",{children:[e.jsx("dt",{children:n("agents.onboarding.fieldSkills","Skills")}),e.jsx("dd",{children:i(t.skills?.join(", "))})]}),e.jsxs("div",{children:[e.jsx("dt",{children:n("agents.onboarding.fieldThinkingLevel","Thinking Level")}),e.jsx("dd",{children:i(t.thinkingLevel)})]}),e.jsxs("div",{children:[e.jsx("dt",{children:n("agents.onboarding.fieldMaxTurns","Max Turns")}),e.jsx("dd",{children:i(t.maxTurns)})]}),e.jsxs("div",{children:[e.jsx("dt",{children:n("agents.onboarding.fieldTemplate","Template")}),e.jsx("dd",{children:i(t.templateId)})]}),e.jsxs("div",{children:[e.jsx("dt",{children:n("agents.onboarding.fieldPatternAgent","Pattern Agent")}),e.jsx("dd",{children:i(t.patternAgentId)})]})]})]}),(t.heartbeatProcedurePath||t.heartbeatIntervalMs||t.heartbeatEnabled!==void 0||t.modelHint||t.runtimeHint)&&e.jsxs("div",{className:"experimental-agent-onboarding-modal__summary-section",children:[e.jsx("h4",{children:n("agents.onboarding.sectionRuntimeHints","Runtime Hints")}),e.jsxs("dl",{className:"experimental-agent-onboarding-modal__summary-list",children:[e.jsxs("div",{children:[e.jsx("dt",{children:n("agents.onboarding.fieldHeartbeatPath","Heartbeat Procedure Path")}),e.jsx("dd",{children:i(t.heartbeatProcedurePath)})]}),e.jsxs("div",{children:[e.jsx("dt",{children:n("agents.onboarding.fieldHeartbeatInterval","Heartbeat Interval")}),e.jsx("dd",{children:i(t.heartbeatIntervalMs?`${t.heartbeatIntervalMs}ms`:void 0)})]}),e.jsxs("div",{children:[e.jsx("dt",{children:n("agents.onboarding.fieldHeartbeatEnabled","Heartbeat Enabled")}),e.jsx("dd",{children:i(t.heartbeatEnabled===void 0?void 0:t.heartbeatEnabled?n("agents.onboarding.yes","yes"):n("agents.onboarding.no","no"))})]}),e.jsxs("div",{children:[e.jsx("dt",{children:n("agents.onboarding.fieldModelHint","Model Hint")}),e.jsx("dd",{children:i(t.modelHint)})]}),e.jsxs("div",{children:[e.jsx("dt",{children:n("agents.onboarding.fieldRuntimeHint","Runtime Hint")}),e.jsx("dd",{children:i(t.runtimeHint)})]})]})]}),t.rationale&&e.jsxs("div",{className:"experimental-agent-onboarding-modal__summary-section",children:[e.jsx("h4",{children:n("agents.onboarding.sectionRationale","Rationale")}),e.jsx("p",{className:"experimental-agent-onboarding-modal__summary-block",children:t.rationale})]})]}),e.jsxs("div",{className:"modal-actions",children:[e.jsx("button",{className:"btn",onClick:()=>void m(),children:n("common.cancel","Cancel")}),e.jsx("button",{className:"btn btn-primary",onClick:()=>void G(),children:b?n("agents.onboarding.applyDraftSettings","Apply draft to settings form"):n("agents.onboarding.applyDraftAgent","Apply draft to agent form")})]})]}),g==="error"&&T&&e.jsxs("div",{className:"form-group",children:[e.jsx("div",{className:"form-error",children:T}),e.jsx("div",{className:"modal-actions",children:e.jsx("button",{className:"btn",onClick:()=>void m(),children:n("common.close","Close")})})]})]})})}export{te as ExperimentalAgentOnboardingModal};
@@ -1,2 +1,2 @@
1
- import{r as n,j as t}from"./vendor-react-SZ_qB27O.js";import{V as js,T as ws,P as Ns,m as Es,n as Ss,o as $s,p as Ms,X as Cs,s as Ts,q as As,u as Gs,v as Ls}from"./index-B8PcG8AJ.js";import{u as Ds}from"./vendor-i18n-Duky4gdQ.js";import"./vendor-codemirror-CcrtqoCy.js";import"./vendor-reactflow-BlIeoTu4.js";import"./vendor-xterm-BNq00GSj.js";const Ps=5,Fs=3,Rs=280;function h(d,m){if(!m)return d;const r=d.includes("?")?"&":"?";return`${d}${r}projectId=${encodeURIComponent(m)}`}function is(d){return!!(d&&typeof d=="object"&&"code"in d&&d.code==="ACTIVE_GOAL_LIMIT_EXCEEDED")}function Hs({initialGoals:d,anchorGoalId:m,projectId:r,onNavigateToMission:as}){const{t:a}=Ds("app"),[c,k]=n.useState(()=>d??[]),[ns,j]=n.useState(null),p=n.useRef(null),[w,L]=n.useState(d===void 0),[D,l]=n.useState(null),[os,P]=n.useState(!1),[v,F]=n.useState(""),[R,N]=n.useState(""),[U,u]=n.useState(null),[O,_]=n.useState(!1),[y,E]=n.useState(!1),[S,V]=n.useState(null),[q,$]=n.useState(""),[B,M]=n.useState(""),[H,f]=n.useState(null),[I,z]=n.useState(!1),[ls,rs]=n.useState(()=>new Set),[ds,cs]=n.useState([]),[x,C]=n.useState({}),[T,W]=n.useState({}),[A,K]=n.useState(null),[us,X]=n.useState(null);n.useEffect(()=>{if(d!==void 0)return;let s=!0;return(async()=>{try{L(!0),l(null);const i=await fetch(h("/api/goals",r));if(!i.ok)throw new Error(`Failed to load goals (${i.status})`);const o=await i.json();if(!s)return;k(Array.isArray(o.goals)?o.goals:[])}catch{if(!s)return;l(a("goals.loadError","Unable to load goals right now. Please try again."))}finally{s&&L(!1)}})(),()=>{s=!1}},[d,r]),n.useEffect(()=>{let s=!0;return(async()=>{try{const i=await fetch(h("/api/missions",r));if(!i.ok)throw new Error(`Failed to load missions (${i.status})`);const o=await i.json(),g=Array.isArray(o)?o:Array.isArray(o.missions)?o.missions:[];s&&cs(g.map(b=>({id:b.id,title:b.title,status:b.status})))}catch{s&&l(a("goals.missionsLoadError","Unable to load missions right now. Please try again."))}})(),()=>{s=!1}},[r,a]);const J=async s=>{const e=await fetch(h(`/api/goals/${encodeURIComponent(s)}/missions`,r));if(!e.ok)throw new Error(`Failed to load linked missions (${e.status})`);const i=await e.json();return Array.isArray(i.missions)?i.missions:[]};n.useEffect(()=>{let s=!0;return(async()=>{if(c.length===0){C({});return}try{const i=await Promise.all(c.map(async o=>[o.id,await J(o.id)]));s&&C(Object.fromEntries(i))}catch{s&&l(a("goals.linkedMissionsLoadError","Unable to load linked missions right now. Please try again."))}})(),()=>{s=!1}},[c,a]);const G=n.useMemo(()=>c.filter(s=>s.status==="active").length,[c]),gs=G>=Fs&&G<=Ps;n.useEffect(()=>{if(!m){j(null);return}const s=document.getElementById(`goal-card-${m}`);if(s)return j(m),typeof s.scrollIntoView=="function"&&s.scrollIntoView({behavior:"smooth",block:"center"}),p.current&&clearTimeout(p.current),p.current=setTimeout(()=>{j(e=>e===m?null:e),p.current=null},1600),()=>{p.current&&(clearTimeout(p.current),p.current=null)}},[m,c]);function ms(){l(null),u(null),P(!0)}function hs(s){V(s.id),$(s.title),M(s.description??""),f(null)}function Q(){V(null),$(""),M(""),f(null)}function Y(){P(!1),F(""),N(""),u(null),E(!1)}async function ps(){const s=v.trim();if(!s){u(a("goals.titleRequired","Title is required."));return}try{E(!0),u(null);const e=await Gs(s,r);N(e)}catch(e){u(Ls(e))}finally{E(!1)}}async function fs(){const s=v.trim();if(!s){u(a("goals.titleRequired","Title is required."));return}try{_(!0),u(null),l(null);const e=await fetch(h("/api/goals",r),{method:"POST",headers:{"content-type":"application/json"},body:JSON.stringify({title:s,description:R})});if(e.ok){const o=await e.json();k(g=>[...g,o]),Y();return}let i=null;try{i=await e.json()}catch{i=null}if(e.status===409&&is(i)){l(a("goals.capError","Cannot activate more than 5 goals. Resolve an active goal before activating another."));return}u(a("goals.createError","Unable to create goal right now. Please try again."))}catch{u(a("goals.createError","Unable to create goal right now. Please try again."))}finally{_(!1)}}async function bs(){if(!S)return;const s=q.trim();if(!s){f(a("goals.titleRequired","Title is required."));return}try{z(!0),f(null);const e=await fetch(h(`/api/goals/${S}`,r),{method:"PATCH",headers:{"content-type":"application/json"},body:JSON.stringify({title:s,description:B})});if(!e.ok)throw new Error(`Failed to update goal (${e.status})`);const i=await e.json();k(o=>o.map(g=>g.id===i.id?i:g)),Q()}catch{f(a("goals.saveError","Unable to save goal right now. Please try again."))}finally{z(!1)}}function ks(s){return s.length>Rs||s.includes(`
1
+ import{r as n,j as t}from"./vendor-react-SZ_qB27O.js";import{V as js,T as ws,P as Ns,S as Es,j as Ss,r as $s,k as Ms,X as Cs,s as Ts,l as As,m as Gs,n as Ls}from"./index-CBFPgFTp.js";import{u as Ds}from"./vendor-i18n-Duky4gdQ.js";import"./vendor-codemirror-CcrtqoCy.js";import"./vendor-reactflow-BlIeoTu4.js";import"./vendor-xterm-BNq00GSj.js";const Ps=5,Fs=3,Rs=280;function h(d,m){if(!m)return d;const r=d.includes("?")?"&":"?";return`${d}${r}projectId=${encodeURIComponent(m)}`}function is(d){return!!(d&&typeof d=="object"&&"code"in d&&d.code==="ACTIVE_GOAL_LIMIT_EXCEEDED")}function Hs({initialGoals:d,anchorGoalId:m,projectId:r,onNavigateToMission:as}){const{t:a}=Ds("app"),[c,k]=n.useState(()=>d??[]),[ns,j]=n.useState(null),p=n.useRef(null),[w,L]=n.useState(d===void 0),[D,l]=n.useState(null),[os,P]=n.useState(!1),[v,F]=n.useState(""),[R,N]=n.useState(""),[U,u]=n.useState(null),[O,_]=n.useState(!1),[y,E]=n.useState(!1),[S,V]=n.useState(null),[q,$]=n.useState(""),[B,M]=n.useState(""),[H,f]=n.useState(null),[I,z]=n.useState(!1),[ls,rs]=n.useState(()=>new Set),[ds,cs]=n.useState([]),[x,C]=n.useState({}),[T,W]=n.useState({}),[A,K]=n.useState(null),[us,X]=n.useState(null);n.useEffect(()=>{if(d!==void 0)return;let s=!0;return(async()=>{try{L(!0),l(null);const i=await fetch(h("/api/goals",r));if(!i.ok)throw new Error(`Failed to load goals (${i.status})`);const o=await i.json();if(!s)return;k(Array.isArray(o.goals)?o.goals:[])}catch{if(!s)return;l(a("goals.loadError","Unable to load goals right now. Please try again."))}finally{s&&L(!1)}})(),()=>{s=!1}},[d,r]),n.useEffect(()=>{let s=!0;return(async()=>{try{const i=await fetch(h("/api/missions",r));if(!i.ok)throw new Error(`Failed to load missions (${i.status})`);const o=await i.json(),g=Array.isArray(o)?o:Array.isArray(o.missions)?o.missions:[];s&&cs(g.map(b=>({id:b.id,title:b.title,status:b.status})))}catch{s&&l(a("goals.missionsLoadError","Unable to load missions right now. Please try again."))}})(),()=>{s=!1}},[r,a]);const J=async s=>{const e=await fetch(h(`/api/goals/${encodeURIComponent(s)}/missions`,r));if(!e.ok)throw new Error(`Failed to load linked missions (${e.status})`);const i=await e.json();return Array.isArray(i.missions)?i.missions:[]};n.useEffect(()=>{let s=!0;return(async()=>{if(c.length===0){C({});return}try{const i=await Promise.all(c.map(async o=>[o.id,await J(o.id)]));s&&C(Object.fromEntries(i))}catch{s&&l(a("goals.linkedMissionsLoadError","Unable to load linked missions right now. Please try again."))}})(),()=>{s=!1}},[c,a]);const G=n.useMemo(()=>c.filter(s=>s.status==="active").length,[c]),gs=G>=Fs&&G<=Ps;n.useEffect(()=>{if(!m){j(null);return}const s=document.getElementById(`goal-card-${m}`);if(s)return j(m),typeof s.scrollIntoView=="function"&&s.scrollIntoView({behavior:"smooth",block:"center"}),p.current&&clearTimeout(p.current),p.current=setTimeout(()=>{j(e=>e===m?null:e),p.current=null},1600),()=>{p.current&&(clearTimeout(p.current),p.current=null)}},[m,c]);function ms(){l(null),u(null),P(!0)}function hs(s){V(s.id),$(s.title),M(s.description??""),f(null)}function Q(){V(null),$(""),M(""),f(null)}function Y(){P(!1),F(""),N(""),u(null),E(!1)}async function ps(){const s=v.trim();if(!s){u(a("goals.titleRequired","Title is required."));return}try{E(!0),u(null);const e=await Gs(s,r);N(e)}catch(e){u(Ls(e))}finally{E(!1)}}async function fs(){const s=v.trim();if(!s){u(a("goals.titleRequired","Title is required."));return}try{_(!0),u(null),l(null);const e=await fetch(h("/api/goals",r),{method:"POST",headers:{"content-type":"application/json"},body:JSON.stringify({title:s,description:R})});if(e.ok){const o=await e.json();k(g=>[...g,o]),Y();return}let i=null;try{i=await e.json()}catch{i=null}if(e.status===409&&is(i)){l(a("goals.capError","Cannot activate more than 5 goals. Resolve an active goal before activating another."));return}u(a("goals.createError","Unable to create goal right now. Please try again."))}catch{u(a("goals.createError","Unable to create goal right now. Please try again."))}finally{_(!1)}}async function bs(){if(!S)return;const s=q.trim();if(!s){f(a("goals.titleRequired","Title is required."));return}try{z(!0),f(null);const e=await fetch(h(`/api/goals/${S}`,r),{method:"PATCH",headers:{"content-type":"application/json"},body:JSON.stringify({title:s,description:B})});if(!e.ok)throw new Error(`Failed to update goal (${e.status})`);const i=await e.json();k(o=>o.map(g=>g.id===i.id?i:g)),Q()}catch{f(a("goals.saveError","Unable to save goal right now. Please try again."))}finally{z(!1)}}function ks(s){return s.length>Rs||s.includes(`
2
2
  `)}function vs(s){rs(e=>{const i=new Set(e);return i.has(s)?i.delete(s):i.add(s),i})}function Z(s){const e=new Set((x[s]??[]).map(i=>i.id));return ds.filter(i=>!e.has(i.id))}async function ss(s){const e=await J(s);C(i=>({...i,[s]:e})),W(i=>({...i,[s]:""}))}async function ys(s){const e=T[s];if(e)try{K(s),l(null);const i=await fetch(h(`/api/missions/${encodeURIComponent(e)}/goals/${encodeURIComponent(s)}`,r),{method:"POST"});if(!i.ok)throw new Error(`Failed to link mission (${i.status})`);await ss(s)}catch{l(a("goals.linkMissionError","Unable to link mission right now. Please try again."))}finally{K(null)}}async function xs(s,e){try{X(`${s}:${e}`),l(null);const i=await fetch(h(`/api/missions/${encodeURIComponent(e)}/goals/${encodeURIComponent(s)}`,r),{method:"DELETE"});if(!i.ok)throw new Error(`Failed to unlink mission (${i.status})`);await ss(s)}catch{l(a("goals.unlinkMissionError","Unable to unlink mission right now. Please try again."))}finally{X(null)}}async function ts(s){const e=s.status==="active"?`/api/goals/${s.id}/archive`:`/api/goals/${s.id}/unarchive`;try{l(null);const i=await fetch(h(e,r),{method:"POST"});if(i.ok){const g=await i.json();k(b=>b.map(es=>es.id===g.id?g:es));return}let o=null;try{o=await i.json()}catch{o=null}if(i.status===409&&is(o)){l(a("goals.capError","Cannot activate more than 5 goals. Resolve an active goal before activating another."));return}l(a("goals.updateError","Unable to update goal status right now. Please try again."))}catch{l(a("goals.updateError","Unable to update goal status right now. Please try again."))}}return t.jsxs("section",{className:"goals-view","data-testid":"goals-view",children:[t.jsx(js,{icon:ws,title:a("goals.title","Goals"),actions:t.jsxs(t.Fragment,{children:[t.jsx("p",{className:"goals-count","data-testid":"goals-active-count",children:a("goals.activeCount","{{count}} active goals",{count:G})}),t.jsxs("button",{type:"button",className:"btn btn-primary goals-add-button",onClick:ms,"data-testid":"goals-add-button",children:[t.jsx(Ns,{size:18,"aria-hidden":"true"}),a("goals.addGoal","Add Goal")]})]})}),t.jsxs("div",{className:"goals-view__content",children:[os?t.jsxs("div",{className:"card goals-form","data-testid":"goals-form",children:[t.jsx("label",{className:"goals-form-label",htmlFor:"goals-form-title",children:a("goals.labelTitle","Title")}),t.jsx("input",{id:"goals-form-title",className:"input",type:"text",value:v,maxLength:200,onChange:s=>F(s.target.value),"data-testid":"goals-form-title"}),t.jsxs("div",{className:"goals-form-label-row",children:[t.jsx("label",{className:"goals-form-label",htmlFor:"goals-form-description",children:a("goals.labelDescription","Description")}),t.jsxs("button",{type:"button",className:"btn goals-form-draft-button",onClick:()=>void ps(),disabled:!v.trim()||y,"data-testid":"goals-form-draft-ai",children:[t.jsx(Es,{"aria-hidden":"true"}),y?a("goals.drafting","Drafting…"):a("goals.draftWithAi","Draft with AI")]})]}),t.jsx("textarea",{id:"goals-form-description",className:"input",value:R,maxLength:5e3,onChange:s=>N(s.target.value),"data-testid":"goals-form-description"}),U?t.jsx("p",{className:"form-error goals-error",role:"alert",children:U}):null,t.jsxs("div",{className:"goals-form-actions",children:[t.jsx("button",{type:"button",className:"btn btn-primary",onClick:()=>void fs(),disabled:O||y,"data-testid":"goals-form-submit",children:a("actions.save","Save")}),t.jsx("button",{type:"button",className:"btn",onClick:Y,disabled:O||y,"data-testid":"goals-form-cancel",children:a("actions.cancel","Cancel")})]})]}):null,gs?t.jsx("p",{className:"goals-warning",role:"status",children:a("goals.capWarning","Approaching the 5-active goal cap. Keep active goals focused.")}):null,D?t.jsx("p",{className:"form-error goals-error",role:"alert","data-testid":"goals-error",children:D}):null,w?t.jsx("p",{className:"goals-loading",role:"status","data-testid":"goals-loading",children:a("goals.loading","Loading goals…")}):null,!w&&c.length===0?t.jsx("div",{className:"goals-empty card","data-testid":"goals-empty-state",children:a("goals.emptyState","No goals yet. Add one to begin tracking strategic outcomes.")}):null,!w&&c.length>0?t.jsx("div",{className:"goals-list","data-testid":"goals-list",children:c.map(s=>t.jsxs("article",{id:`goal-card-${s.id}`,className:`card goals-card ${s.status==="archived"?"goals-card-archived":""} ${ns===s.id?"goals-card--anchored":""}`.trim(),"data-testid":`goal-card-${s.id}`,draggable:As(),onDragStart:e=>{Ts(e.dataTransfer,{kind:"goal",id:s.id,projectId:r})},children:[S===s.id?t.jsxs("div",{className:"goals-card-main goals-card-edit",children:[t.jsx("label",{className:"goals-form-label",htmlFor:`goal-edit-title-${s.id}`,children:a("goals.labelTitle","Title")}),t.jsx("input",{id:`goal-edit-title-${s.id}`,className:"input",type:"text",value:q,maxLength:200,onChange:e=>$(e.target.value),"data-testid":`goal-edit-title-${s.id}`}),t.jsx("label",{className:"goals-form-label",htmlFor:`goal-edit-description-${s.id}`,children:a("goals.labelDescription","Description")}),t.jsx("textarea",{id:`goal-edit-description-${s.id}`,className:"input",value:B,maxLength:5e3,onChange:e=>M(e.target.value),"data-testid":`goal-edit-description-${s.id}`}),H?t.jsx("p",{className:"form-error goals-error",role:"alert",children:H}):null,t.jsxs("div",{className:"goals-card-actions",children:[t.jsx("button",{type:"button",className:"btn btn-primary",onClick:()=>void bs(),disabled:I,"data-testid":`goal-edit-save-${s.id}`,children:a("actions.save","Save")}),t.jsx("button",{type:"button",className:"btn",onClick:Q,disabled:I,"data-testid":`goal-edit-cancel-${s.id}`,children:a("actions.cancel","Cancel")})]})]}):t.jsxs(t.Fragment,{children:[t.jsxs("div",{className:"goals-card-main",children:[t.jsx("h3",{className:"goals-card-title",children:s.title}),s.description?(()=>{const e=ks(s.description),i=ls.has(s.id);return t.jsxs(t.Fragment,{children:[t.jsx("div",{className:`markdown-body goals-card-description ${e&&!i?"goals-card-description-collapsed":""}`.trim(),children:t.jsx(Ss,{remarkPlugins:[$s],children:s.description})}),e?t.jsx("button",{type:"button",className:"btn goals-card-description-toggle","aria-expanded":i,"data-testid":`goal-description-toggle-${s.id}`,onClick:()=>vs(s.id),children:i?a("actions.showLess","Show less"):a("actions.showMore","Show more")}):null]})})():null,t.jsxs("p",{className:"goals-card-status",children:[a("goals.status","Status"),": ",s.status]})]}),t.jsxs("div",{className:"goals-card-actions",children:[t.jsx("button",{type:"button",className:"btn",onClick:()=>hs(s),"data-testid":`goal-edit-${s.id}`,children:a("actions.edit","Edit")}),s.status==="active"?t.jsx("button",{type:"button",className:"btn goals-activate-button",onClick:()=>void ts(s),"data-testid":`goal-archive-${s.id}`,children:a("goals.archive","Archive")}):t.jsx("button",{type:"button",className:"btn goals-activate-button",onClick:()=>void ts(s),"data-testid":`goal-unarchive-${s.id}`,children:a("goals.unarchive","Unarchive")})]})]}),t.jsxs("section",{className:"goals-linked-missions","aria-label":a("goals.linkedMissions","Linked missions"),children:[t.jsxs("div",{className:"goals-linked-missions-header",children:[t.jsx("h4",{className:"goals-linked-missions-title",children:a("goals.linkedMissionsTitle","Linked Missions")}),t.jsx("span",{className:"goals-linked-missions-count",children:a("goals.linkedMissionsCount",{count:x[s.id]?.length??0,defaultValue_one:"{{count}} linked",defaultValue_other:"{{count}} linked"})})]}),t.jsxs("div",{className:"goals-linked-missions-controls",children:[t.jsxs("select",{className:"input goals-linked-missions-picker","data-testid":`goal-mission-picker-${s.id}`,value:T[s.id]??"",onChange:e=>W(i=>({...i,[s.id]:e.target.value})),"aria-label":a("goals.missionPicker","Mission to link"),disabled:A===s.id||Z(s.id).length===0,children:[t.jsx("option",{value:"",children:a("goals.selectMission","Select a mission")}),Z(s.id).map(e=>t.jsx("option",{value:e.id,children:e.title},e.id))]}),t.jsxs("button",{type:"button",className:"btn btn-primary goals-linked-missions-link-button","data-testid":`goal-mission-link-button-${s.id}`,disabled:!T[s.id]||A===s.id,onClick:()=>void ys(s.id),children:[t.jsx(Ms,{size:16,"aria-hidden":"true"}),A===s.id?a("goals.linkingMission","Linking…"):a("goals.linkMission","Link mission")]})]}),(x[s.id]?.length??0)>0?t.jsx("div",{className:"goals-linked-missions-list",children:(x[s.id]??[]).map(e=>t.jsxs("div",{className:"goals-linked-mission-chip","data-testid":`goal-linked-mission-chip-${e.id}`,children:[t.jsx("button",{type:"button",className:"btn goals-linked-mission-link",onClick:()=>as?.(e.id),children:e.title}),t.jsx("span",{className:"goals-linked-mission-status",children:e.status}),t.jsx("button",{type:"button",className:"btn-icon goals-linked-mission-unlink","data-testid":`goal-linked-mission-unlink-${e.id}`,"aria-label":a("goals.unlinkMission","Unlink mission"),disabled:us===`${s.id}:${e.id}`,onClick:()=>void xs(s.id,e.id),children:t.jsx(Cs,{size:16,"aria-hidden":"true"})})]},e.id))}):t.jsx("p",{className:"goals-linked-missions-empty",children:a("goals.noLinkedMissions","No linked missions.")})]})]},s.id))}):null]})]})}export{Hs as GoalsView};
@@ -1,11 +1,11 @@
1
- import{r as i,j as e}from"./vendor-react-SZ_qB27O.js";import{c as ze,r as le,e as Ce,S as je,cL as Me,cM as Je,b as Ne,cN as es,cO as ss,cP as ts,cQ as is,cR as ns,cS as as,cT as Ie,cU as rs,cV as os,cW as cs,cs as ls,cX as Re,V as hs,m as Y,bY as ds,X as Ae,cY as fe,R as q,a3 as gs,cx as us,as as De,l as ae,bH as ve,bG as Te,P as $e,aU as ms,b2 as Pe,cZ as fs,s as vs,q as xs}from"./index-B8PcG8AJ.js";import{u as Ge}from"./vendor-i18n-Duky4gdQ.js";import{U as Ee}from"./users-B0h1q4x6.js";import"./vendor-codemirror-CcrtqoCy.js";import"./vendor-reactflow-BlIeoTu4.js";import"./vendor-xterm-BNq00GSj.js";/**
1
+ import{r as i,j as e}from"./vendor-react-SZ_qB27O.js";import{c as ze,ab as le,ac as Ce,ad as je,cy as Me,cz as Ze,ah as Ne,cA as es,cB as ss,cC as ts,cD as is,cE as ns,cF as as,cG as Ie,cH as rs,cI as os,cJ as cs,cf as ls,cK as Ae,V as hs,S as W,bK as ds,X as Re,cL as fe,R as q,aM as gs,ck as us,a8 as De,h as ae,bt as ve,bs as Ee,P as $e,aF as ms,aQ as Pe,cM as fs,s as vs,l as ys}from"./index-CBFPgFTp.js";import{u as Ge}from"./vendor-i18n-Duky4gdQ.js";import{U as Te}from"./users--irrWoyU.js";import"./vendor-codemirror-CcrtqoCy.js";import"./vendor-reactflow-BlIeoTu4.js";import"./vendor-xterm-BNq00GSj.js";/**
2
2
  * @license lucide-react v1.7.0 - ISC
3
3
  *
4
4
  * This source code is licensed under the ISC license.
5
5
  * See the LICENSE file in the root directory of this source tree.
6
- */const ys=[["path",{d:"M12 10h.01",key:"1nrarc"}],["path",{d:"M12 14h.01",key:"1etili"}],["path",{d:"M12 6h.01",key:"1vi96p"}],["path",{d:"M16 10h.01",key:"1m94wz"}],["path",{d:"M16 14h.01",key:"1gbofw"}],["path",{d:"M16 6h.01",key:"1x0f13"}],["path",{d:"M8 10h.01",key:"19clt8"}],["path",{d:"M8 14h.01",key:"6423bh"}],["path",{d:"M8 6h.01",key:"1dz90k"}],["path",{d:"M9 22v-3a1 1 0 0 1 1-1h4a1 1 0 0 1 1 1v3",key:"cabbwy"}],["rect",{x:"4",y:"2",width:"16",height:"20",rx:"2",key:"1uxh74"}]],ps=ze("building",ys);/**
6
+ */const xs=[["path",{d:"M12 10h.01",key:"1nrarc"}],["path",{d:"M12 14h.01",key:"1etili"}],["path",{d:"M12 6h.01",key:"1vi96p"}],["path",{d:"M16 10h.01",key:"1m94wz"}],["path",{d:"M16 14h.01",key:"1gbofw"}],["path",{d:"M16 6h.01",key:"1x0f13"}],["path",{d:"M8 10h.01",key:"19clt8"}],["path",{d:"M8 14h.01",key:"6423bh"}],["path",{d:"M8 6h.01",key:"1dz90k"}],["path",{d:"M9 22v-3a1 1 0 0 1 1-1h4a1 1 0 0 1 1 1v3",key:"cabbwy"}],["rect",{x:"4",y:"2",width:"16",height:"20",rx:"2",key:"1uxh74"}]],ps=ze("building",xs);/**
7
7
  * @license lucide-react v1.7.0 - ISC
8
8
  *
9
9
  * This source code is licensed under the ISC license.
10
10
  * See the LICENSE file in the root directory of this source tree.
11
- */const bs=[["path",{d:"M3 3v16a2 2 0 0 0 2 2h16",key:"c24i48"}],["path",{d:"m19 9-5 5-4-4-3 3",key:"2osh9i"}]],ks=ze("chart-line",bs),me=["architecture","quality","workflow","performance","reliability","security","ux","testability","documentation","dependency","features","competitive_analysis","research","trends","other"],Fe={quality:"Quality",performance:"Performance",architecture:"Architecture",security:"Security",reliability:"Reliability",ux:"User Experience",testability:"Testability",documentation:"Documentation",dependency:"Dependencies",workflow:"Workflow",other:"Other",features:"Features",competitive_analysis:"Competitive Analysis",research:"Research",trends:"Trends"};function Ss(g,m){const M=Date.parse(g.createdAt),p=Date.parse(m.createdAt),b=Number.isFinite(M),s=Number.isFinite(p);return!b||!s?b?-1:s?1:0:M!==p?p-M:g.id===m.id?0:g.id<m.id?1:-1}function ws(g){const{t:m}=Ge("app"),M=g??"",p=`${je.INSIGHTS_PREFIX}${M}`,b=`${je.INSIGHT_LATEST_RUN_PREFIX}${M}`,s=le(p,{maxAgeMs:Ce}),K=le(b,{maxAgeMs:Me}),P=i.useRef(Array.isArray(s)&&s.length>0),U=i.useCallback(r=>m(`insights.category.${r}`,Fe[r]??r),[m]),[x,N]=i.useState(()=>Array.isArray(s)?s:[]),[H,Q]=i.useState(()=>me.map(r=>({category:r,label:Fe[r]??r,items:[],isLoading:!1,error:null}))),[O,E]=i.useState(!(Array.isArray(s)&&s.length>0)),[Z,F]=i.useState(null),[G,I]=i.useState(K??null),[L,_]=i.useState(!1),[w,z]=i.useState(null),[T,B]=i.useState(new Map),[J,l]=i.useState(new Map),[k,u]=i.useState(new Map),[y,h]=i.useState(new Map),[C,R]=i.useState(!1),v=i.useCallback(async()=>{P.current||E(!0),F(null);try{const n=(await Je({status:void 0,limit:1e3},g)).insights.filter(d=>d.status!=="dismissed");N(n),Ne(p,n.length>500?n.slice(0,500):n,{maxBytes:5e5});const o=await es(g);o.runs.length>0&&(I(o.runs[0]),Ne(b,o.runs[0],{maxBytes:5e5})),P.current=!0}catch(r){const n=r instanceof Error?r.message:"Failed to fetch insights";F(n)}finally{E(!1)}},[p,b,g]),ee=i.useCallback(()=>{R(r=>!r)},[]),j=i.useCallback(async(r,n,o)=>{_(!0),z(null);try{const d=await ss("manual",void 0,g,r,n,o);I(d),d.status==="completed"?await v():d.status==="failed"&&d.error&&z(d.error)}catch(d){if(d instanceof ts&&d.status===409&&d.details?.code==="ACTIVE_RUN_CONFLICT"){const re=typeof d.details.activeRunId=="string"?d.details.activeRunId:null;if(re)try{const ue=await is(re,g);I(ue)}catch{}throw z("Insight generation is already running"),d}const S=d instanceof Error?d.message:"Failed to generate insights";throw z(S),d}finally{_(!1)}},[g,v]),D=i.useCallback(async r=>{B(n=>{const o=new Map(n);return o.set(r,{running:!0,error:null}),o});try{await ns(r,g),N(n=>n.filter(o=>o.id!==r)),B(n=>{const o=new Map(n);return o.set(r,{running:!1,error:null}),o})}catch(n){const o=n instanceof Error?n.message:"Failed to dismiss insight";throw B(d=>{const S=new Map(d);return S.set(r,{running:!1,error:o}),S}),n}},[g]),V=i.useCallback(async r=>{l(n=>{const o=new Map(n);return o.set(r,{running:!0,error:null}),o});try{const n=await as(r,g);return await Ie(r,g),N(o=>o.map(d=>d.id===r?{...d,status:"archived",updatedAt:new Date().toISOString()}:d)),l(o=>{const d=new Map(o);return d.set(r,{running:!1,error:null}),d}),{title:n.suggestedTitle,description:n.suggestedDescription}}catch(n){const o=n instanceof Error?n.message:"Failed to create task";throw l(d=>{const S=new Map(d);return S.set(r,{running:!1,error:o}),S}),n}},[g]);i.useEffect(()=>{const r=new Map;for(const n of me)r.set(n,[]);for(const n of x){if(!C&&n.status==="archived")continue;const o=r.get(n.category)??[];r.set(n.category,[...o,n])}Q(me.map(n=>({category:n,label:U(n),items:[...r.get(n)??[]].sort(Ss),isLoading:!1,error:null})))},[x,C,U]);const he=i.useCallback(async r=>{u(n=>{const o=new Map(n);return o.set(r,{running:!0,error:null}),o});try{await Ie(r,g),N(n=>n.map(o=>o.id===r?{...o,status:"archived",updatedAt:new Date().toISOString()}:o)),u(n=>{const o=new Map(n);return o.set(r,{running:!1,error:null}),o})}catch(n){const o=n instanceof Error?n.message:"Failed to archive insight";throw u(d=>{const S=new Map(d);return S.set(r,{running:!1,error:o}),S}),n}},[g]),de=i.useCallback(async r=>{h(n=>{const o=new Map(n);return o.set(r,{running:!0,error:null}),o});try{await rs(r,g),N(n=>n.map(o=>o.id===r?{...o,status:"confirmed",updatedAt:new Date().toISOString()}:o)),h(n=>{const o=new Map(n);return o.set(r,{running:!1,error:null}),o})}catch(n){const o=n instanceof Error?n.message:"Failed to unarchive insight";throw h(d=>{const S=new Map(d);return S.set(r,{running:!1,error:o}),S}),n}},[g]),ge=i.useMemo(()=>H.reduce((r,n)=>r+n.items.length,0),[H]),A=i.useMemo(()=>0,[]),te=i.useMemo(()=>x.filter(r=>r.status==="archived").length,[x]);return i.useEffect(()=>{const r=le(p,{maxAgeMs:Ce}),n=le(b,{maxAgeMs:Me}),o=Array.isArray(r)&&r.length>0;N(Array.isArray(r)?r:[]),I(n??null),E(!o),P.current=o},[p,b]),i.useEffect(()=>{v()},[v]),{sections:H,loading:O,error:Z,latestRun:G,isRunInFlight:L,runError:w,refresh:v,runInsights:j,dismiss:D,createTask:V,archive:he,unarchive:de,toggleShowArchived:ee,dismissStates:T,createTaskStates:J,archiveStates:k,unarchiveStates:y,totalCount:ge,dismissedCount:A,archivedCount:te,showArchived:C}}const Cs=20,js=50;function Ms(g){const[m,M]=i.useState([]),[p,b]=i.useState(!0),[s,K]=i.useState(!1),[P,U]=i.useState(null),[x,N]=i.useState(!1),[H,Q]=i.useState(0),[O,E]=i.useState(!1),[Z,F]=i.useState(new Map),G=i.useRef(0),I=i.useRef(0),L=i.useRef(!1),_=i.useRef(new Set),w=i.useRef(0),z=i.useRef(g),T=i.useCallback(async k=>{if(L.current)return;L.current=!0;const u=w.current,y=k?0:G.current;k?b(!0):K(!0),U(null);try{const h=await os(g,{limit:js,offset:y});if(u!==w.current)return;M(v=>{const ee=k?[]:v,j=new Set(ee.map(D=>`${D.taskId}:${D.recommendation.id}`));return[...ee,...h.items.filter(D=>{const V=`${D.taskId}:${D.recommendation.id}`;return j.has(V)?!1:(j.add(V),!0)})]}),G.current=h.rowOffset+h.returnedRowCount,I.current=k?1:I.current+1,Q(h.totalRowCount);const R=I.current>=Cs&&h.hasMore;E(R),N(R?!1:h.hasMore)}catch(h){u===w.current&&U(h instanceof Error?h.message:"Failed to fetch task recommendations")}finally{u===w.current&&(b(!1),K(!1)),L.current=!1}},[g]),B=i.useCallback(async()=>{G.current=0,I.current=0,E(!1),await T(!0)},[T]);i.useEffect(()=>{z.current=g,w.current+=1,L.current=!1,_.current.clear(),G.current=0,I.current=0,M([]),N(!1),Q(0),E(!1),F(new Map),T(!0)},[T,g]);const J=i.useCallback(async()=>{!x||O||L.current||await T(!1)},[T,x,O]),l=i.useCallback(async(k,u)=>{const y=`${k}:${u}`;if(_.current.has(y))return;_.current.add(y);const h=w.current;F(C=>new Map(C).set(y,{running:!0,error:null}));try{const C=await cs(k,u,z.current);if(h!==w.current)return;M(R=>R.map(v=>v.taskId===k&&v.recommendation.id===u?{...v,recommendation:{...v.recommendation,createdTaskId:C.task.id}}:v)),F(R=>new Map(R).set(y,{running:!1,error:null}))}catch(C){h===w.current&&F(R=>new Map(R).set(y,{running:!1,error:C instanceof Error?C.message:"Could not create task"}))}finally{h===w.current&&_.current.delete(y)}},[]);return{items:m,loading:p,loadingMore:s,error:P,hasMore:x,totalRowCount:H,truncated:O,refresh:B,loadMore:J,createTask:l,createStates:Z}}const Ue=["Backlog health:","Backlog pressure detected","Stale paused todo","Backlog health: dependency-blocked todos"];function Le(g){return Ue.some(m=>g.title.startsWith(m))}const _e={architecture:ps,quality:De,workflow:Pe,performance:Te,reliability:q,security:ae,ux:Ee,testability:fe,documentation:ms,dependency:$e,features:ve,competitive_analysis:Ee,research:ks,trends:Te,other:Y};function Ls({projectId:g,addToast:m,onClose:M,onCreateTask:p,models:b}){const{t:s}=Ge("app"),{sections:K,loading:P,error:U,latestRun:x,isRunInFlight:N,runError:H,refresh:Q,runInsights:O,dismiss:E,createTask:Z,archive:F=async()=>{},unarchive:G=async()=>{},toggleShowArchived:I=()=>{},dismissStates:L,createTaskStates:_,archiveStates:w=new Map,unarchiveStates:z=new Map,totalCount:T,archivedCount:B=0,showArchived:J=!1}=ws(g),l=Ms(g),[k,u]=i.useState(null),[y,h]=i.useState("info"),[C,R]=i.useState(!1),[v,ee]=i.useState(!1),[j,D]=i.useState(()=>localStorage.getItem("fusion-insight-model")??""),[V,he]=i.useState(()=>localStorage.getItem("fusion-insight-thinking")??""),[de,ge]=i.useState([]),[A,te]=i.useState([]),[r,n]=i.useState([]),[o,d]=i.useState();i.useEffect(()=>{b||ls().then(t=>{ge(t.models),te(t.favoriteProviders),n(t.favoriteModels),d(t.resolvedPlanningProvider);const a=localStorage.getItem("fusion-insight-model");a&&(t.models.some(f=>`${f.provider}/${f.id}`===a)||(localStorage.removeItem("fusion-insight-model"),D("")))}).catch(()=>{})},[b]);const S=b??de,re=i.useMemo(()=>A.length>0?A:o?[o]:[],[A,o]),ue=i.useCallback(async t=>{const c=A.includes(t)?A.filter(f=>f!==t):[t,...A];te(c);try{await Re({favoriteProviders:c,favoriteModels:r})}catch{te(A)}},[A,r]),He=i.useCallback(async t=>{const c=r.includes(t)?r.filter(f=>f!==t):[t,...r];n(c);try{await Re({favoriteProviders:A,favoriteModels:c})}catch{n(r)}},[r,A]),Oe=i.useCallback(t=>{D(t),t?localStorage.setItem("fusion-insight-model",t):localStorage.removeItem("fusion-insight-model")},[]),Be=i.useCallback(t=>{he(t),t?localStorage.setItem("fusion-insight-thinking",t):localStorage.removeItem("fusion-insight-thinking")},[]),ie=i.useMemo(()=>K.filter(t=>t.items.length>0),[K]),xe=i.useMemo(()=>ie.reduce((t,a)=>t+a.items.filter(Le).length,0),[ie]),X=i.useMemo(()=>v?ie.map(t=>({...t,items:t.items.filter(Le)})).filter(t=>t.items.length>0):ie,[ie,v]),[$,ne]=i.useState(null);i.useEffect(()=>{if($==="recommendations"&&l.items.length>0)return;if(X.length===0){l.items.length>0?ne("recommendations"):$!==null&&ne(null);return}$&&X.some(a=>a.category===$&&a.items.length>0)||ne(X[0]?.category??(l.items.length>0?"recommendations":null))},[X,$,l.items.length]);const W=i.useMemo(()=>$==="recommendations"?void 0:X.find(t=>t.category===$)??X[0],[X,$]);i.useEffect(()=>{if(k){const t=setTimeout(()=>u(null),5e3);return()=>clearTimeout(t)}},[k]);const ye=i.useCallback(async()=>{try{u(s("insights.generatingInsights","Generating insights...")),h("info");let t,a;if(j){const c=j.indexOf("/");if(c!==-1){const f=j.slice(0,c),oe=j.slice(c+1);f&&oe&&(t=f,a=oe)}}await O(t,a,V||void 0),u(s("insights.generationStarted","Insight generation started")),h("success"),m(s("insights.generationStarted","Insight generation started"),"success")}catch(t){const a=t instanceof Error?t.message:s("insights.failedToStart","Failed to start generation");if(a==="Insight generation is already running"){u(s("insights.alreadyRunning","Insight generation is already running. Showing the active run.")),h("info"),m(s("insights.alreadyRunningShort","Insight generation is already running"),"info");return}u(a),h("error"),m(a,"error")}},[O,m,j,V,s]),Ve=i.useCallback(async(t,a)=>{try{u(s("insights.dismissing",'Dismissing "{{title}}"...',{title:a})),h("info"),await E(t),u(s("insights.dismissed",'Dismissed "{{title}}"',{title:a})),h("success"),m(s("insights.dismissedMsg","Insight dismissed: {{title}}",{title:a}),"success")}catch(c){const f=c instanceof Error?c.message:s("insights.failedToDismiss","Failed to dismiss insight");u(f),h("error"),m(f,"error")}},[E,m,s]),Xe=i.useCallback(async(t,a)=>{try{u(s("insights.archiving",'Archiving "{{title}}"...',{title:a})),h("info"),await F(t),u(s("insights.archived",'Archived "{{title}}"',{title:a})),h("success"),m(s("insights.archivedMsg","Insight archived: {{title}}",{title:a}),"success")}catch(c){const f=c instanceof Error?c.message:s("insights.failedToArchive","Failed to archive insight");u(f),h("error"),m(f,"error")}},[F,m,s]),We=i.useCallback(async(t,a)=>{try{u(s("insights.unarchiving",'Unarchiving "{{title}}"...',{title:a})),h("info"),await G(t),u(s("insights.unarchived",'Unarchived "{{title}}"',{title:a})),h("success"),m(s("insights.unarchivedMsg","Insight unarchived: {{title}}",{title:a}),"success")}catch(c){const f=c instanceof Error?c.message:s("insights.failedToUnarchive","Failed to unarchive insight");u(f),h("error"),m(f,"error")}},[G,m,s]),Ye=i.useCallback(async(t,a)=>{try{if(u(s("insights.creatingTask",'Creating task from "{{title}}"...',{title:a})),h("info"),!p)throw new Error(s("insights.taskCreationUnavailable","Task creation is unavailable in this view"));const c=await Z(t);if(!c)throw new Error(s("insights.failedToPreparePayload","Failed to prepare task payload from insight"));await p({insightId:t,title:c.title,description:c.description}),u(s("insights.taskCreated",'Task created from "{{title}}"',{title:a})),h("success"),m(s("insights.taskCreatedMsg","Task created: {{title}}",{title:c.title}),"success")}catch(c){const f=c instanceof Error?c.message:s("insights.failedToCreateTask","Failed to create task");u(f),h("error"),m(f,"error")}},[Z,p,m,s]),qe=t=>{const a=_e[t.category]??Y,c=W?.category===t.category;return e.jsx("li",{children:e.jsxs("button",{type:"button",className:`insights-category-item${c?" insights-category-item--active":""}`,onClick:()=>ne(t.category),"aria-current":c?"true":void 0,"data-testid":`insights-category-${t.category}`,children:[e.jsx(a,{size:16,className:"insights-category-icon"}),e.jsx("span",{className:"insights-category-label",children:t.label}),e.jsx("span",{className:"insights-category-count",children:t.items.length})]})},t.category)},Ke=()=>e.jsxs("section",{className:"insights-section insights-recommendations","data-testid":"insights-section-recommendations",children:[e.jsx("div",{className:"insights-section-header",children:e.jsxs("div",{className:"insights-section-title",children:[e.jsx(ve,{size:18,className:"insights-section-icon"}),e.jsx("h3",{children:s("insights.recommendations.title","Task Recommendations")}),e.jsx("span",{className:"insights-section-count",children:l.items.length})]})}),e.jsx("p",{className:"insights-recommendations__count",children:s("insights.recommendations.count","Showing {{shown}} of {{total}} source tasks",{shown:l.items.length,total:l.totalRowCount})}),e.jsx("ul",{className:"insights-list",children:l.items.map(t=>{const a=`${t.taskId}:${t.recommendation.id}`,c=l.createStates.get(a),f=t.recommendation.createdTaskId;return e.jsxs("li",{className:"insight-item insights-recommendations__item","data-testid":`task-recommendation-${a}`,children:[e.jsxs("div",{className:"insight-item-header",children:[e.jsx("h4",{className:"insight-item-title",children:t.recommendation.title}),e.jsx("span",{className:"insights-category-count",children:t.recommendation.category})]}),e.jsx("p",{children:t.recommendation.description}),e.jsx("p",{className:"insights-recommendations__source",children:s("insights.recommendations.source","Source: {{task}}",{task:t.taskTitle?`${t.taskId} — ${t.taskTitle}`:t.taskId})}),f?e.jsx("span",{role:"status",children:s("taskDetail.recommendations.created","Created {{taskId}}",{taskId:f})}):e.jsxs("div",{children:[e.jsx("button",{className:"btn btn-primary",type:"button",disabled:c?.running,onClick:()=>void l.createTask(t.taskId,t.recommendation.id),children:c?.running?s("taskDetail.recommendations.creating","Creating…"):c?.error?s("taskDetail.recommendations.retry","Retry creating task"):s("taskDetail.recommendations.create","Create task")}),c?.error&&e.jsx("span",{role:"status",children:s("taskDetail.recommendations.error","Could not create task. Try again.")})]})]},a)})}),l.truncated?e.jsx("p",{role:"status",children:s("insights.recommendations.truncated","Showing the first 20 pages. Refresh to see the latest recommendations.")}):l.hasMore?e.jsx("button",{className:"btn",type:"button",disabled:l.loadingMore,onClick:()=>void l.loadMore(),children:l.loadingMore?s("insights.recommendations.loadingMore","Loading more…"):s("insights.recommendations.loadMore","Load more")}):null,l.error&&!l.loading&&e.jsxs("div",{role:"status",children:[e.jsx("span",{children:s("insights.recommendations.loadMoreFailed","Could not load more recommendations.")}),e.jsx("button",{className:"btn",type:"button",onClick:()=>void(l.hasMore?l.loadMore():l.refresh()),children:s("actions.retry","Retry")})]})]}),Qe=()=>{if(!W)return null;const t=_e[W.category]??Y;return e.jsxs("section",{className:"insights-section","data-testid":`insights-section-${W.category}`,children:[e.jsx("div",{className:"insights-section-header",children:e.jsxs("div",{className:"insights-section-title",children:[e.jsx(t,{size:18,className:"insights-section-icon"}),e.jsx("h3",{children:W.label}),e.jsx("span",{className:"insights-section-count",children:W.items.length})]})}),e.jsx("div",{className:"insights-section-content",children:e.jsx("ul",{className:"insights-list",children:W.items.map(a=>{const c=L.get(a.id),f=_.get(a.id),oe=w.get(a.id),Ze=z.get(a.id),pe=c?.running??!1,be=f?.running??!1,ke=oe?.running??!1,Se=Ze?.running??!1,we=a.status==="archived",ce=W.items.some(se=>L.get(se.id)?.running||_.get(se.id)?.running||w.get(se.id)?.running||z.get(se.id)?.running);return e.jsxs("li",{className:`insight-item${we?" insight-item--archived":""}`,"data-insight-id":a.id,draggable:xs(),onDragStart:se=>{vs(se.dataTransfer,{kind:"research-finding",id:a.id,projectId:g})},children:[e.jsxs("div",{className:"insight-item-header",children:[e.jsx("h4",{className:"insight-item-title",children:a.title}),e.jsxs("div",{className:"insight-item-actions",children:[we?e.jsx("button",{className:"insight-item-action-btn",onClick:()=>void We(a.id,a.title),disabled:Se||ce,title:s("insights.unarchiveTitle","Unarchive this insight"),"aria-label":s("insights.unarchiveLabel","Unarchive this insight"),"data-testid":`unarchive-${a.id}`,children:Se?e.jsx(q,{size:16,className:"spin"}):e.jsx(fs,{size:16})}):e.jsxs(e.Fragment,{children:[e.jsx("button",{className:"insight-item-action-btn",onClick:()=>void Ye(a.id,a.title),disabled:be||ce,title:s("insights.createTaskTitle","Create task from this insight"),"aria-label":s("insights.createTaskLabel","Create task from this insight"),"data-testid":`create-task-${a.id}`,children:be?e.jsx(q,{size:16,className:"spin"}):e.jsx($e,{size:16})}),e.jsx("button",{className:"insight-item-action-btn",onClick:()=>void Xe(a.id,a.title),disabled:ke||ce,title:s("insights.archiveTitle","Archive this insight"),"aria-label":s("insights.archiveLabel","Archive this insight"),"data-testid":`archive-${a.id}`,children:ke?e.jsx(q,{size:16,className:"spin"}):e.jsx(fe,{size:16})})]}),e.jsx("button",{className:"insight-item-action-btn",onClick:()=>void Ve(a.id,a.title),disabled:pe||ce,title:s("insights.dismissTitle","Dismiss this insight"),"aria-label":s("insights.dismissLabel","Dismiss this insight"),"data-testid":`dismiss-${a.id}`,children:pe?e.jsx(q,{size:16,className:"spin"}):e.jsx(Ae,{size:16})})]})]}),a.content&&e.jsx("p",{className:"insight-item-content",children:a.content}),e.jsxs("div",{className:"insight-item-meta",children:[e.jsx("span",{className:`insight-item-status insight-item-status--${a.status}`,children:a.status}),a.createdAt&&e.jsxs("span",{className:"insight-item-date",children:[e.jsx(Pe,{size:12}),new Date(a.createdAt).toLocaleDateString()]})]})]},a.id)})})})]})};return e.jsxs("div",{className:"insights-view","data-testid":"insights-view",children:[e.jsx(hs,{icon:Y,title:s("insights.title","Insights"),actions:e.jsxs(e.Fragment,{children:[e.jsxs("span",{className:"insights-view-count",children:[T," ",s("common.total","total")]}),xe>0&&e.jsxs("button",{className:`btn btn-sm insights-backlog-health-toggle${v?" btn-icon--active":""}`,onClick:()=>ee(t=>!t),"aria-pressed":v,"aria-label":v?s("insights.showAllInsights","Show all insights"):s("insights.showBacklogHealth","Show only backlog health insights"),"data-testid":"toggle-backlog-health",title:Ue.join(", "),children:[e.jsx(ds,{size:14}),v?s("insights.allInsights","All Insights"):s("insights.backlogHealth","Backlog")," ",e.jsxs("span",{children:["(",xe,")"]})]}),M&&e.jsx("button",{className:"btn btn-sm insights-view-close",onClick:M,"aria-label":s("actions.closeInsightsView","Close insights view"),title:s("actions.close","Close"),children:e.jsx(Ae,{size:16})}),B>0&&e.jsxs("button",{className:"btn btn-sm insights-show-archived-toggle",onClick:I,"aria-label":J?s("insights.hideArchived","Hide archived insights"):s("insights.showArchived","Show archived insights"),"data-testid":"toggle-archived-insights",children:[e.jsx(fe,{size:14}),J?s("insights.hideArchivedLabel","Archived"):s("insights.showArchivedLabel","Archived ({{count}})",{count:B})]}),e.jsx("button",{className:"btn btn-icon btn-sm insights-refresh-btn",onClick:()=>void Q(),disabled:P,"aria-label":s("actions.refreshInsights","Refresh insights"),title:s("actions.refreshInsights","Refresh insights"),"data-testid":"refresh-insights",children:e.jsx(q,{size:14,className:P?"spin":""})}),e.jsxs("button",{className:"btn btn-sm insights-model-toggle",onClick:()=>R(t=>!t),"aria-label":s("insights.configureModel","Configure insight generation model"),"aria-expanded":C,"data-testid":"toggle-model-config",title:j?s("insights.modelConfigured","Model: {{model}}",{model:j}):s("insights.configureModelTitle","Configure model"),children:[e.jsx(gs,{size:14}),j&&e.jsx("span",{className:"insights-model-indicator"})]}),e.jsx("button",{className:"btn btn-primary btn-sm",onClick:()=>void ye(),disabled:N,"aria-label":s("insights.generateInsights","Generate new insights"),"data-testid":"run-insights",children:N?e.jsxs(e.Fragment,{children:[e.jsx(q,{size:14,className:"spin"}),s("insights.generating","Generating...")]}):e.jsxs(e.Fragment,{children:[e.jsx(Y,{size:14}),s("insights.generateInsightsBtn","Generate Insights")]})})]})}),C&&e.jsxs("div",{className:"insights-model-config","data-testid":"model-config",children:[e.jsx("label",{htmlFor:"insight-model-select",className:"insights-model-label",children:s("insights.model","Model")}),e.jsx(us,{models:S,value:j,onChange:Oe,placeholder:s("insights.usePlanningDefault","Use planning default"),label:s("insights.generationModel","Insight generation model"),disabled:N,id:"insight-model-select",favoriteProviders:re,favoriteModels:r,onToggleFavorite:ue,onToggleModelFavorite:He,showThinkingLevel:!0,thinkingLevel:V,onThinkingLevelChange:Be,defaultThinkingLevel:"off"})]}),e.jsx("div",{className:"insights-status-region","aria-live":"polite","data-testid":"insights-status",children:k&&e.jsxs("div",{className:`insights-status-message insights-status-message--${y}`,role:y==="error"?"alert":void 0,children:[y==="success"&&e.jsx(De,{size:16}),y==="error"&&e.jsx(ae,{size:16}),y==="info"&&e.jsx(Y,{size:16}),e.jsx("span",{children:k})]})}),H&&e.jsxs("div",{className:"insights-error-callout",role:"alert","data-testid":"run-error",children:[e.jsx(ae,{size:16}),e.jsx("span",{children:H})]}),x&&e.jsx("div",{className:"insights-run-info","data-testid":"latest-run",children:e.jsxs("span",{className:"insights-run-status",children:[s("insights.latestRun","Latest run:")," ",x.status,x.status==="completed"&&e.jsxs(e.Fragment,{children:[" — ",s("insights.runCompleted","{{created}} created, {{updated}} updated",{created:x.insightsCreated,updated:x.insightsUpdated})]}),x.status==="failed"&&x.error&&e.jsxs(e.Fragment,{children:[" — ",x.error]})]})}),l.error&&!l.loading&&l.items.length===0&&e.jsxs("div",{className:"insights-error-callout",role:"status","data-testid":"task-recommendations-error",children:[e.jsx(ae,{size:16}),e.jsx("span",{children:s("insights.recommendations.loadMoreFailed","Could not load more recommendations.")}),e.jsx("button",{className:"btn btn-sm",type:"button",onClick:()=>void l.refresh(),children:s("actions.retry","Retry")})]}),P?e.jsxs("div",{className:"insights-loading","data-testid":"insights-loading",children:[e.jsx(q,{size:24,className:"spin"}),e.jsx("p",{children:s("insights.loading","Loading insights...")})]}):U?e.jsxs("div",{className:"insights-error","data-testid":"insights-error",children:[e.jsx(ae,{size:24}),e.jsx("p",{children:U}),e.jsx("button",{className:"btn btn-sm",onClick:()=>void Q(),children:s("actions.retry","Retry")})]}):T===0&&l.items.length===0?e.jsxs("div",{className:"insights-empty","data-testid":"insights-empty",children:[e.jsx(Y,{size:48}),e.jsx("h3",{children:s("insights.noInsightsYet","No insights yet")}),e.jsx("p",{children:s("insights.generateDescription","Generate insights to get AI-powered recommendations for your project.")}),e.jsxs("button",{className:"btn btn-primary",onClick:()=>void ye(),children:[e.jsx(Y,{size:14}),s("insights.generateFirst","Generate First Insights")]})]}):e.jsxs("div",{className:"insights-body",children:[e.jsx("aside",{className:"insights-sidebar","aria-label":s("insights.categoriesLabel","Insight categories"),children:e.jsxs("ul",{className:"insights-category-list",children:[X.map(qe),l.items.length>0&&e.jsx("li",{children:e.jsxs("button",{type:"button",className:`insights-category-item${$==="recommendations"?" insights-category-item--active":""}`,onClick:()=>ne("recommendations"),"data-testid":"insights-category-recommendations",children:[e.jsx(ve,{size:16,className:"insights-category-icon"}),e.jsx("span",{className:"insights-category-label",children:s("insights.recommendations.title","Task Recommendations")}),e.jsxs("span",{className:"insights-category-count",children:[l.items.length,l.hasMore?`/${l.totalRowCount}`:""]})]})})]})}),e.jsx("div",{className:"insights-detail",children:$==="recommendations"?Ke():Qe()})]})]})}export{Ls as InsightsView};
11
+ */const ks=[["path",{d:"M3 3v16a2 2 0 0 0 2 2h16",key:"c24i48"}],["path",{d:"m19 9-5 5-4-4-3 3",key:"2osh9i"}]],bs=ze("chart-line",ks),me=["architecture","quality","workflow","performance","reliability","security","ux","testability","documentation","dependency","features","competitive_analysis","research","trends","other"],Fe={quality:"Quality",performance:"Performance",architecture:"Architecture",security:"Security",reliability:"Reliability",ux:"User Experience",testability:"Testability",documentation:"Documentation",dependency:"Dependencies",workflow:"Workflow",other:"Other",features:"Features",competitive_analysis:"Competitive Analysis",research:"Research",trends:"Trends"};function Ss(g,m){const M=Date.parse(g.createdAt),p=Date.parse(m.createdAt),k=Number.isFinite(M),s=Number.isFinite(p);return!k||!s?k?-1:s?1:0:M!==p?p-M:g.id===m.id?0:g.id<m.id?1:-1}function ws(g){const{t:m}=Ge("app"),M=g??"",p=`${je.INSIGHTS_PREFIX}${M}`,k=`${je.INSIGHT_LATEST_RUN_PREFIX}${M}`,s=le(p,{maxAgeMs:Ce}),Y=le(k,{maxAgeMs:Me}),P=i.useRef(Array.isArray(s)&&s.length>0),H=i.useCallback(r=>m(`insights.category.${r}`,Fe[r]??r),[m]),[y,N]=i.useState(()=>Array.isArray(s)?s:[]),[U,Q]=i.useState(()=>me.map(r=>({category:r,label:Fe[r]??r,items:[],isLoading:!1,error:null}))),[O,T]=i.useState(!(Array.isArray(s)&&s.length>0)),[J,F]=i.useState(null),[G,I]=i.useState(Y??null),[L,_]=i.useState(!1),[w,z]=i.useState(null),[E,B]=i.useState(new Map),[Z,l]=i.useState(new Map),[b,u]=i.useState(new Map),[x,h]=i.useState(new Map),[C,A]=i.useState(!1),v=i.useCallback(async()=>{P.current||T(!0),F(null);try{const n=(await Ze({status:void 0,limit:1e3},g)).insights.filter(d=>d.status!=="dismissed");N(n),Ne(p,n.length>500?n.slice(0,500):n,{maxBytes:5e5});const o=await es(g);o.runs.length>0&&(I(o.runs[0]),Ne(k,o.runs[0],{maxBytes:5e5})),P.current=!0}catch(r){const n=r instanceof Error?r.message:"Failed to fetch insights";F(n)}finally{T(!1)}},[p,k,g]),ee=i.useCallback(()=>{A(r=>!r)},[]),j=i.useCallback(async(r,n,o)=>{_(!0),z(null);try{const d=await ss("manual",void 0,g,r,n,o);I(d),d.status==="completed"?await v():d.status==="failed"&&d.error&&z(d.error)}catch(d){if(d instanceof ts&&d.status===409&&d.details?.code==="ACTIVE_RUN_CONFLICT"){const re=typeof d.details.activeRunId=="string"?d.details.activeRunId:null;if(re)try{const ue=await is(re,g);I(ue)}catch{}throw z("Insight generation is already running"),d}const S=d instanceof Error?d.message:"Failed to generate insights";throw z(S),d}finally{_(!1)}},[g,v]),D=i.useCallback(async r=>{B(n=>{const o=new Map(n);return o.set(r,{running:!0,error:null}),o});try{await ns(r,g),N(n=>n.filter(o=>o.id!==r)),B(n=>{const o=new Map(n);return o.set(r,{running:!1,error:null}),o})}catch(n){const o=n instanceof Error?n.message:"Failed to dismiss insight";throw B(d=>{const S=new Map(d);return S.set(r,{running:!1,error:o}),S}),n}},[g]),V=i.useCallback(async r=>{l(n=>{const o=new Map(n);return o.set(r,{running:!0,error:null}),o});try{const n=await as(r,g);return await Ie(r,g),N(o=>o.map(d=>d.id===r?{...d,status:"archived",updatedAt:new Date().toISOString()}:d)),l(o=>{const d=new Map(o);return d.set(r,{running:!1,error:null}),d}),{title:n.suggestedTitle,description:n.suggestedDescription}}catch(n){const o=n instanceof Error?n.message:"Failed to create task";throw l(d=>{const S=new Map(d);return S.set(r,{running:!1,error:o}),S}),n}},[g]);i.useEffect(()=>{const r=new Map;for(const n of me)r.set(n,[]);for(const n of y){if(!C&&n.status==="archived")continue;const o=r.get(n.category)??[];r.set(n.category,[...o,n])}Q(me.map(n=>({category:n,label:H(n),items:[...r.get(n)??[]].sort(Ss),isLoading:!1,error:null})))},[y,C,H]);const he=i.useCallback(async r=>{u(n=>{const o=new Map(n);return o.set(r,{running:!0,error:null}),o});try{await Ie(r,g),N(n=>n.map(o=>o.id===r?{...o,status:"archived",updatedAt:new Date().toISOString()}:o)),u(n=>{const o=new Map(n);return o.set(r,{running:!1,error:null}),o})}catch(n){const o=n instanceof Error?n.message:"Failed to archive insight";throw u(d=>{const S=new Map(d);return S.set(r,{running:!1,error:o}),S}),n}},[g]),de=i.useCallback(async r=>{h(n=>{const o=new Map(n);return o.set(r,{running:!0,error:null}),o});try{await rs(r,g),N(n=>n.map(o=>o.id===r?{...o,status:"confirmed",updatedAt:new Date().toISOString()}:o)),h(n=>{const o=new Map(n);return o.set(r,{running:!1,error:null}),o})}catch(n){const o=n instanceof Error?n.message:"Failed to unarchive insight";throw h(d=>{const S=new Map(d);return S.set(r,{running:!1,error:o}),S}),n}},[g]),ge=i.useMemo(()=>U.reduce((r,n)=>r+n.items.length,0),[U]),R=i.useMemo(()=>0,[]),te=i.useMemo(()=>y.filter(r=>r.status==="archived").length,[y]);return i.useEffect(()=>{const r=le(p,{maxAgeMs:Ce}),n=le(k,{maxAgeMs:Me}),o=Array.isArray(r)&&r.length>0;N(Array.isArray(r)?r:[]),I(n??null),T(!o),P.current=o},[p,k]),i.useEffect(()=>{v()},[v]),{sections:U,loading:O,error:J,latestRun:G,isRunInFlight:L,runError:w,refresh:v,runInsights:j,dismiss:D,createTask:V,archive:he,unarchive:de,toggleShowArchived:ee,dismissStates:E,createTaskStates:Z,archiveStates:b,unarchiveStates:x,totalCount:ge,dismissedCount:R,archivedCount:te,showArchived:C}}const Cs=20,js=50;function Ms(g){const[m,M]=i.useState([]),[p,k]=i.useState(!0),[s,Y]=i.useState(!1),[P,H]=i.useState(null),[y,N]=i.useState(!1),[U,Q]=i.useState(0),[O,T]=i.useState(!1),[J,F]=i.useState(new Map),G=i.useRef(0),I=i.useRef(0),L=i.useRef(!1),_=i.useRef(new Set),w=i.useRef(0),z=i.useRef(g),E=i.useCallback(async b=>{if(L.current)return;L.current=!0;const u=w.current,x=b?0:G.current;b?k(!0):Y(!0),H(null);try{const h=await os(g,{limit:js,offset:x});if(u!==w.current)return;M(v=>{const ee=b?[]:v,j=new Set(ee.map(D=>`${D.taskId}:${D.recommendation.id}`));return[...ee,...h.items.filter(D=>{const V=`${D.taskId}:${D.recommendation.id}`;return j.has(V)?!1:(j.add(V),!0)})]}),G.current=h.rowOffset+h.returnedRowCount,I.current=b?1:I.current+1,Q(h.totalRowCount);const A=I.current>=Cs&&h.hasMore;T(A),N(A?!1:h.hasMore)}catch(h){u===w.current&&H(h instanceof Error?h.message:"Failed to fetch task recommendations")}finally{u===w.current&&(k(!1),Y(!1)),L.current=!1}},[g]),B=i.useCallback(async()=>{G.current=0,I.current=0,T(!1),await E(!0)},[E]);i.useEffect(()=>{z.current=g,w.current+=1,L.current=!1,_.current.clear(),G.current=0,I.current=0,M([]),N(!1),Q(0),T(!1),F(new Map),E(!0)},[E,g]);const Z=i.useCallback(async()=>{!y||O||L.current||await E(!1)},[E,y,O]),l=i.useCallback(async(b,u)=>{const x=`${b}:${u}`;if(_.current.has(x))return;_.current.add(x);const h=w.current;F(C=>new Map(C).set(x,{running:!0,error:null}));try{const C=await cs(b,u,z.current);if(h!==w.current)return;M(A=>A.map(v=>v.taskId===b&&v.recommendation.id===u?{...v,recommendation:{...v.recommendation,createdTaskId:C.task.id}}:v)),F(A=>new Map(A).set(x,{running:!1,error:null}))}catch(C){h===w.current&&F(A=>new Map(A).set(x,{running:!1,error:C instanceof Error?C.message:"Could not create task"}))}finally{h===w.current&&_.current.delete(x)}},[]);return{items:m,loading:p,loadingMore:s,error:P,hasMore:y,totalRowCount:U,truncated:O,refresh:B,loadMore:Z,createTask:l,createStates:J}}const He=["Backlog health:","Backlog pressure detected","Stale paused todo","Backlog health: dependency-blocked todos"];function Le(g){return He.some(m=>g.title.startsWith(m))}const _e={architecture:ps,quality:De,workflow:Pe,performance:Ee,reliability:q,security:ae,ux:Te,testability:fe,documentation:ms,dependency:$e,features:ve,competitive_analysis:Te,research:bs,trends:Ee,other:W};function Ls({projectId:g,addToast:m,onClose:M,onCreateTask:p,models:k}){const{t:s}=Ge("app"),{sections:Y,loading:P,error:H,latestRun:y,isRunInFlight:N,runError:U,refresh:Q,runInsights:O,dismiss:T,createTask:J,archive:F=async()=>{},unarchive:G=async()=>{},toggleShowArchived:I=()=>{},dismissStates:L,createTaskStates:_,archiveStates:w=new Map,unarchiveStates:z=new Map,totalCount:E,archivedCount:B=0,showArchived:Z=!1}=ws(g),l=Ms(g),[b,u]=i.useState(null),[x,h]=i.useState("info"),[C,A]=i.useState(!1),[v,ee]=i.useState(!1),[j,D]=i.useState(()=>localStorage.getItem("fusion-insight-model")??""),[V,he]=i.useState(()=>localStorage.getItem("fusion-insight-thinking")??""),[de,ge]=i.useState([]),[R,te]=i.useState([]),[r,n]=i.useState([]),[o,d]=i.useState();i.useEffect(()=>{k||ls().then(t=>{ge(t.models),te(t.favoriteProviders),n(t.favoriteModels),d(t.resolvedPlanningProvider);const a=localStorage.getItem("fusion-insight-model");a&&(t.models.some(f=>`${f.provider}/${f.id}`===a)||(localStorage.removeItem("fusion-insight-model"),D("")))}).catch(()=>{})},[k]);const S=k??de,re=i.useMemo(()=>R.length>0?R:o?[o]:[],[R,o]),ue=i.useCallback(async t=>{const c=R.includes(t)?R.filter(f=>f!==t):[t,...R];te(c);try{await Ae({favoriteProviders:c,favoriteModels:r})}catch{te(R)}},[R,r]),Ue=i.useCallback(async t=>{const c=r.includes(t)?r.filter(f=>f!==t):[t,...r];n(c);try{await Ae({favoriteProviders:R,favoriteModels:c})}catch{n(r)}},[r,R]),Oe=i.useCallback(t=>{D(t),t?localStorage.setItem("fusion-insight-model",t):localStorage.removeItem("fusion-insight-model")},[]),Be=i.useCallback(t=>{he(t),t?localStorage.setItem("fusion-insight-thinking",t):localStorage.removeItem("fusion-insight-thinking")},[]),ie=i.useMemo(()=>Y.filter(t=>t.items.length>0),[Y]),ye=i.useMemo(()=>ie.reduce((t,a)=>t+a.items.filter(Le).length,0),[ie]),X=i.useMemo(()=>v?ie.map(t=>({...t,items:t.items.filter(Le)})).filter(t=>t.items.length>0):ie,[ie,v]),[$,ne]=i.useState(null);i.useEffect(()=>{if($==="recommendations"&&l.items.length>0)return;if(X.length===0){l.items.length>0?ne("recommendations"):$!==null&&ne(null);return}$&&X.some(a=>a.category===$&&a.items.length>0)||ne(X[0]?.category??(l.items.length>0?"recommendations":null))},[X,$,l.items.length]);const K=i.useMemo(()=>$==="recommendations"?void 0:X.find(t=>t.category===$)??X[0],[X,$]);i.useEffect(()=>{if(b){const t=setTimeout(()=>u(null),5e3);return()=>clearTimeout(t)}},[b]);const xe=i.useCallback(async()=>{try{u(s("insights.generatingInsights","Generating insights...")),h("info");let t,a;if(j){const c=j.indexOf("/");if(c!==-1){const f=j.slice(0,c),oe=j.slice(c+1);f&&oe&&(t=f,a=oe)}}await O(t,a,V||void 0),u(s("insights.generationStarted","Insight generation started")),h("success"),m(s("insights.generationStarted","Insight generation started"),"success")}catch(t){const a=t instanceof Error?t.message:s("insights.failedToStart","Failed to start generation");if(a==="Insight generation is already running"){u(s("insights.alreadyRunning","Insight generation is already running. Showing the active run.")),h("info"),m(s("insights.alreadyRunningShort","Insight generation is already running"),"info");return}u(a),h("error"),m(a,"error")}},[O,m,j,V,s]),Ve=i.useCallback(async(t,a)=>{try{u(s("insights.dismissing",'Dismissing "{{title}}"...',{title:a})),h("info"),await T(t),u(s("insights.dismissed",'Dismissed "{{title}}"',{title:a})),h("success"),m(s("insights.dismissedMsg","Insight dismissed: {{title}}",{title:a}),"success")}catch(c){const f=c instanceof Error?c.message:s("insights.failedToDismiss","Failed to dismiss insight");u(f),h("error"),m(f,"error")}},[T,m,s]),Xe=i.useCallback(async(t,a)=>{try{u(s("insights.archiving",'Archiving "{{title}}"...',{title:a})),h("info"),await F(t),u(s("insights.archived",'Archived "{{title}}"',{title:a})),h("success"),m(s("insights.archivedMsg","Insight archived: {{title}}",{title:a}),"success")}catch(c){const f=c instanceof Error?c.message:s("insights.failedToArchive","Failed to archive insight");u(f),h("error"),m(f,"error")}},[F,m,s]),Ke=i.useCallback(async(t,a)=>{try{u(s("insights.unarchiving",'Unarchiving "{{title}}"...',{title:a})),h("info"),await G(t),u(s("insights.unarchived",'Unarchived "{{title}}"',{title:a})),h("success"),m(s("insights.unarchivedMsg","Insight unarchived: {{title}}",{title:a}),"success")}catch(c){const f=c instanceof Error?c.message:s("insights.failedToUnarchive","Failed to unarchive insight");u(f),h("error"),m(f,"error")}},[G,m,s]),We=i.useCallback(async(t,a)=>{try{if(u(s("insights.creatingTask",'Creating task from "{{title}}"...',{title:a})),h("info"),!p)throw new Error(s("insights.taskCreationUnavailable","Task creation is unavailable in this view"));const c=await J(t);if(!c)throw new Error(s("insights.failedToPreparePayload","Failed to prepare task payload from insight"));await p({insightId:t,title:c.title,description:c.description}),u(s("insights.taskCreated",'Task created from "{{title}}"',{title:a})),h("success"),m(s("insights.taskCreatedMsg","Task created: {{title}}",{title:c.title}),"success")}catch(c){const f=c instanceof Error?c.message:s("insights.failedToCreateTask","Failed to create task");u(f),h("error"),m(f,"error")}},[J,p,m,s]),qe=t=>{const a=_e[t.category]??W,c=K?.category===t.category;return e.jsx("li",{children:e.jsxs("button",{type:"button",className:`insights-category-item${c?" insights-category-item--active":""}`,onClick:()=>ne(t.category),"aria-current":c?"true":void 0,"data-testid":`insights-category-${t.category}`,children:[e.jsx(a,{size:16,className:"insights-category-icon"}),e.jsx("span",{className:"insights-category-label",children:t.label}),e.jsx("span",{className:"insights-category-count",children:t.items.length})]})},t.category)},Ye=()=>e.jsxs("section",{className:"insights-section insights-recommendations","data-testid":"insights-section-recommendations",children:[e.jsx("div",{className:"insights-section-header",children:e.jsxs("div",{className:"insights-section-title",children:[e.jsx(ve,{size:18,className:"insights-section-icon"}),e.jsx("h3",{children:s("insights.recommendations.title","Task Recommendations")}),e.jsx("span",{className:"insights-section-count",children:l.items.length})]})}),e.jsx("p",{className:"insights-recommendations__count",children:s("insights.recommendations.count","Showing {{shown}} of {{total}} source tasks",{shown:l.items.length,total:l.totalRowCount})}),e.jsx("ul",{className:"insights-list",children:l.items.map(t=>{const a=`${t.taskId}:${t.recommendation.id}`,c=l.createStates.get(a),f=t.recommendation.createdTaskId;return e.jsxs("li",{className:"insight-item insights-recommendations__item","data-testid":`task-recommendation-${a}`,children:[e.jsxs("div",{className:"insight-item-header",children:[e.jsx("h4",{className:"insight-item-title",children:t.recommendation.title}),e.jsx("span",{className:"insights-category-count",children:t.recommendation.category})]}),e.jsx("p",{children:t.recommendation.description}),e.jsx("p",{className:"insights-recommendations__source",children:s("insights.recommendations.source","Source: {{task}}",{task:t.taskTitle?`${t.taskId} — ${t.taskTitle}`:t.taskId})}),f?e.jsx("span",{role:"status",children:s("taskDetail.recommendations.created","Created {{taskId}}",{taskId:f})}):e.jsxs("div",{children:[e.jsx("button",{className:"btn btn-primary",type:"button",disabled:c?.running,onClick:()=>void l.createTask(t.taskId,t.recommendation.id),children:c?.running?s("taskDetail.recommendations.creating","Creating…"):c?.error?s("taskDetail.recommendations.retry","Retry creating task"):s("taskDetail.recommendations.create","Create task")}),c?.error&&e.jsx("span",{role:"status",children:s("taskDetail.recommendations.error","Could not create task. Try again.")})]})]},a)})}),l.truncated?e.jsx("p",{role:"status",children:s("insights.recommendations.truncated","Showing the first 20 pages. Refresh to see the latest recommendations.")}):l.hasMore?e.jsx("button",{className:"btn",type:"button",disabled:l.loadingMore,onClick:()=>void l.loadMore(),children:l.loadingMore?s("insights.recommendations.loadingMore","Loading more…"):s("insights.recommendations.loadMore","Load more")}):null,l.error&&!l.loading&&e.jsxs("div",{role:"status",children:[e.jsx("span",{children:s("insights.recommendations.loadMoreFailed","Could not load more recommendations.")}),e.jsx("button",{className:"btn",type:"button",onClick:()=>void(l.hasMore?l.loadMore():l.refresh()),children:s("actions.retry","Retry")})]})]}),Qe=()=>{if(!K)return null;const t=_e[K.category]??W;return e.jsxs("section",{className:"insights-section","data-testid":`insights-section-${K.category}`,children:[e.jsx("div",{className:"insights-section-header",children:e.jsxs("div",{className:"insights-section-title",children:[e.jsx(t,{size:18,className:"insights-section-icon"}),e.jsx("h3",{children:K.label}),e.jsx("span",{className:"insights-section-count",children:K.items.length})]})}),e.jsx("div",{className:"insights-section-content",children:e.jsx("ul",{className:"insights-list",children:K.items.map(a=>{const c=L.get(a.id),f=_.get(a.id),oe=w.get(a.id),Je=z.get(a.id),pe=c?.running??!1,ke=f?.running??!1,be=oe?.running??!1,Se=Je?.running??!1,we=a.status==="archived",ce=K.items.some(se=>L.get(se.id)?.running||_.get(se.id)?.running||w.get(se.id)?.running||z.get(se.id)?.running);return e.jsxs("li",{className:`insight-item${we?" insight-item--archived":""}`,"data-insight-id":a.id,draggable:ys(),onDragStart:se=>{vs(se.dataTransfer,{kind:"research-finding",id:a.id,projectId:g})},children:[e.jsxs("div",{className:"insight-item-header",children:[e.jsx("h4",{className:"insight-item-title",children:a.title}),e.jsxs("div",{className:"insight-item-actions",children:[we?e.jsx("button",{className:"insight-item-action-btn",onClick:()=>void Ke(a.id,a.title),disabled:Se||ce,title:s("insights.unarchiveTitle","Unarchive this insight"),"aria-label":s("insights.unarchiveLabel","Unarchive this insight"),"data-testid":`unarchive-${a.id}`,children:Se?e.jsx(q,{size:16,className:"spin"}):e.jsx(fs,{size:16})}):e.jsxs(e.Fragment,{children:[e.jsx("button",{className:"insight-item-action-btn",onClick:()=>void We(a.id,a.title),disabled:ke||ce,title:s("insights.createTaskTitle","Create task from this insight"),"aria-label":s("insights.createTaskLabel","Create task from this insight"),"data-testid":`create-task-${a.id}`,children:ke?e.jsx(q,{size:16,className:"spin"}):e.jsx($e,{size:16})}),e.jsx("button",{className:"insight-item-action-btn",onClick:()=>void Xe(a.id,a.title),disabled:be||ce,title:s("insights.archiveTitle","Archive this insight"),"aria-label":s("insights.archiveLabel","Archive this insight"),"data-testid":`archive-${a.id}`,children:be?e.jsx(q,{size:16,className:"spin"}):e.jsx(fe,{size:16})})]}),e.jsx("button",{className:"insight-item-action-btn",onClick:()=>void Ve(a.id,a.title),disabled:pe||ce,title:s("insights.dismissTitle","Dismiss this insight"),"aria-label":s("insights.dismissLabel","Dismiss this insight"),"data-testid":`dismiss-${a.id}`,children:pe?e.jsx(q,{size:16,className:"spin"}):e.jsx(Re,{size:16})})]})]}),a.content&&e.jsx("p",{className:"insight-item-content",children:a.content}),e.jsxs("div",{className:"insight-item-meta",children:[e.jsx("span",{className:`insight-item-status insight-item-status--${a.status}`,children:a.status}),a.createdAt&&e.jsxs("span",{className:"insight-item-date",children:[e.jsx(Pe,{size:12}),new Date(a.createdAt).toLocaleDateString()]})]})]},a.id)})})})]})};return e.jsxs("div",{className:"insights-view","data-testid":"insights-view",children:[e.jsx(hs,{icon:W,title:s("insights.title","Insights"),actions:e.jsxs(e.Fragment,{children:[e.jsxs("span",{className:"insights-view-count",children:[E," ",s("common.total","total")]}),ye>0&&e.jsxs("button",{className:`btn btn-sm insights-backlog-health-toggle${v?" btn-icon--active":""}`,onClick:()=>ee(t=>!t),"aria-pressed":v,"aria-label":v?s("insights.showAllInsights","Show all insights"):s("insights.showBacklogHealth","Show only backlog health insights"),"data-testid":"toggle-backlog-health",title:He.join(", "),children:[e.jsx(ds,{size:14}),v?s("insights.allInsights","All Insights"):s("insights.backlogHealth","Backlog")," ",e.jsxs("span",{children:["(",ye,")"]})]}),M&&e.jsx("button",{className:"btn btn-sm insights-view-close",onClick:M,"aria-label":s("actions.closeInsightsView","Close insights view"),title:s("actions.close","Close"),children:e.jsx(Re,{size:16})}),B>0&&e.jsxs("button",{className:"btn btn-sm insights-show-archived-toggle",onClick:I,"aria-label":Z?s("insights.hideArchived","Hide archived insights"):s("insights.showArchived","Show archived insights"),"data-testid":"toggle-archived-insights",children:[e.jsx(fe,{size:14}),Z?s("insights.hideArchivedLabel","Archived"):s("insights.showArchivedLabel","Archived ({{count}})",{count:B})]}),e.jsx("button",{className:"btn btn-icon btn-sm insights-refresh-btn",onClick:()=>void Q(),disabled:P,"aria-label":s("actions.refreshInsights","Refresh insights"),title:s("actions.refreshInsights","Refresh insights"),"data-testid":"refresh-insights",children:e.jsx(q,{size:14,className:P?"spin":""})}),e.jsxs("button",{className:"btn btn-sm insights-model-toggle",onClick:()=>A(t=>!t),"aria-label":s("insights.configureModel","Configure insight generation model"),"aria-expanded":C,"data-testid":"toggle-model-config",title:j?s("insights.modelConfigured","Model: {{model}}",{model:j}):s("insights.configureModelTitle","Configure model"),children:[e.jsx(gs,{size:14}),j&&e.jsx("span",{className:"insights-model-indicator"})]}),e.jsx("button",{className:"btn btn-primary btn-sm",onClick:()=>void xe(),disabled:N,"aria-label":s("insights.generateInsights","Generate new insights"),"data-testid":"run-insights",children:N?e.jsxs(e.Fragment,{children:[e.jsx(q,{size:14,className:"spin"}),s("insights.generating","Generating...")]}):e.jsxs(e.Fragment,{children:[e.jsx(W,{size:14}),s("insights.generateInsightsBtn","Generate Insights")]})})]})}),C&&e.jsxs("div",{className:"insights-model-config","data-testid":"model-config",children:[e.jsx("label",{htmlFor:"insight-model-select",className:"insights-model-label",children:s("insights.model","Model")}),e.jsx(us,{models:S,value:j,onChange:Oe,placeholder:s("insights.usePlanningDefault","Use planning default"),label:s("insights.generationModel","Insight generation model"),disabled:N,id:"insight-model-select",favoriteProviders:re,favoriteModels:r,onToggleFavorite:ue,onToggleModelFavorite:Ue,showThinkingLevel:!0,thinkingLevel:V,onThinkingLevelChange:Be,defaultThinkingLevel:"off"})]}),e.jsx("div",{className:"insights-status-region","aria-live":"polite","data-testid":"insights-status",children:b&&e.jsxs("div",{className:`insights-status-message insights-status-message--${x}`,role:x==="error"?"alert":void 0,children:[x==="success"&&e.jsx(De,{size:16}),x==="error"&&e.jsx(ae,{size:16}),x==="info"&&e.jsx(W,{size:16}),e.jsx("span",{children:b})]})}),U&&e.jsxs("div",{className:"insights-error-callout",role:"alert","data-testid":"run-error",children:[e.jsx(ae,{size:16}),e.jsx("span",{children:U})]}),y&&e.jsx("div",{className:"insights-run-info","data-testid":"latest-run",children:e.jsxs("span",{className:"insights-run-status",children:[s("insights.latestRun","Latest run:")," ",y.status,y.status==="completed"&&e.jsxs(e.Fragment,{children:[" — ",s("insights.runCompleted","{{created}} created, {{updated}} updated",{created:y.insightsCreated,updated:y.insightsUpdated})]}),y.status==="failed"&&y.error&&e.jsxs(e.Fragment,{children:[" — ",y.error]})]})}),l.error&&!l.loading&&l.items.length===0&&e.jsxs("div",{className:"insights-error-callout",role:"status","data-testid":"task-recommendations-error",children:[e.jsx(ae,{size:16}),e.jsx("span",{children:s("insights.recommendations.loadMoreFailed","Could not load more recommendations.")}),e.jsx("button",{className:"btn btn-sm",type:"button",onClick:()=>void l.refresh(),children:s("actions.retry","Retry")})]}),P?e.jsxs("div",{className:"insights-loading","data-testid":"insights-loading",children:[e.jsx(q,{size:24,className:"spin"}),e.jsx("p",{children:s("insights.loading","Loading insights...")})]}):H?e.jsxs("div",{className:"insights-error","data-testid":"insights-error",children:[e.jsx(ae,{size:24}),e.jsx("p",{children:H}),e.jsx("button",{className:"btn btn-sm",onClick:()=>void Q(),children:s("actions.retry","Retry")})]}):E===0&&l.items.length===0?e.jsxs("div",{className:"insights-empty","data-testid":"insights-empty",children:[e.jsx(W,{size:48}),e.jsx("h3",{children:s("insights.noInsightsYet","No insights yet")}),e.jsx("p",{children:s("insights.generateDescription","Generate insights to get AI-powered recommendations for your project.")}),e.jsxs("button",{className:"btn btn-primary",onClick:()=>void xe(),children:[e.jsx(W,{size:14}),s("insights.generateFirst","Generate First Insights")]})]}):e.jsxs("div",{className:"insights-body",children:[e.jsx("aside",{className:"insights-sidebar","aria-label":s("insights.categoriesLabel","Insight categories"),children:e.jsxs("ul",{className:"insights-category-list",children:[X.map(qe),l.items.length>0&&e.jsx("li",{children:e.jsxs("button",{type:"button",className:`insights-category-item${$==="recommendations"?" insights-category-item--active":""}`,onClick:()=>ne("recommendations"),"data-testid":"insights-category-recommendations",children:[e.jsx(ve,{size:16,className:"insights-category-icon"}),e.jsx("span",{className:"insights-category-label",children:s("insights.recommendations.title","Task Recommendations")}),e.jsxs("span",{className:"insights-category-count",children:[l.items.length,l.hasMore?`/${l.totalRowCount}`:""]})]})})]})}),e.jsx("div",{className:"insights-detail",children:$==="recommendations"?Ye():Qe()})]})]})}export{Ls as InsightsView};