flujo-ai 3.40.0 → 3.41.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (278) hide show
  1. package/.next/BUILD_ID +1 -1
  2. package/.next/app-build-manifest.json +400 -384
  3. package/.next/app-path-routes-manifest.json +53 -53
  4. package/.next/build-manifest.json +5 -5
  5. package/.next/prerender-manifest.json +33 -33
  6. package/.next/react-loadable-manifest.json +9 -9
  7. package/.next/server/app/_not-found/page_client-reference-manifest.js +1 -1
  8. package/.next/server/app/_not-found.html +1 -1
  9. package/.next/server/app/_not-found.rsc +3 -3
  10. package/.next/server/app/api/approvals/[id]/route_client-reference-manifest.js +1 -1
  11. package/.next/server/app/api/approvals/route_client-reference-manifest.js +1 -1
  12. package/.next/server/app/api/backup/route_client-reference-manifest.js +1 -1
  13. package/.next/server/app/api/browse/route_client-reference-manifest.js +1 -1
  14. package/.next/server/app/api/bugs/enhance/route_client-reference-manifest.js +1 -1
  15. package/.next/server/app/api/cwd/route_client-reference-manifest.js +1 -1
  16. package/.next/server/app/api/encryption/secure/route_client-reference-manifest.js +1 -1
  17. package/.next/server/app/api/env/route_client-reference-manifest.js +1 -1
  18. package/.next/server/app/api/flow/[id]/convert-process-to-subflow/route_client-reference-manifest.js +1 -1
  19. package/.next/server/app/api/flow/[id]/route_client-reference-manifest.js +1 -1
  20. package/.next/server/app/api/flow/[id]/versions/[versionId]/route_client-reference-manifest.js +1 -1
  21. package/.next/server/app/api/flow/[id]/versions/route_client-reference-manifest.js +1 -1
  22. package/.next/server/app/api/flow/assist/route_client-reference-manifest.js +1 -1
  23. package/.next/server/app/api/flow/compile/route_client-reference-manifest.js +1 -1
  24. package/.next/server/app/api/flow/generate/route_client-reference-manifest.js +1 -1
  25. package/.next/server/app/api/flow/generator/route_client-reference-manifest.js +1 -1
  26. package/.next/server/app/api/flow/improve/route_client-reference-manifest.js +1 -1
  27. package/.next/server/app/api/flow/prompt-renderer/route_client-reference-manifest.js +1 -1
  28. package/.next/server/app/api/flow/quick-chat/route_client-reference-manifest.js +1 -1
  29. package/.next/server/app/api/flow/repair/route_client-reference-manifest.js +1 -1
  30. package/.next/server/app/api/flow/route_client-reference-manifest.js +1 -1
  31. package/.next/server/app/api/git/route_client-reference-manifest.js +1 -1
  32. package/.next/server/app/api/init/route_client-reference-manifest.js +1 -1
  33. package/.next/server/app/api/local-models/capability/route_client-reference-manifest.js +1 -1
  34. package/.next/server/app/api/local-models/pull/route_client-reference-manifest.js +1 -1
  35. package/.next/server/app/api/local-models/suggest/route_client-reference-manifest.js +1 -1
  36. package/.next/server/app/api/mcp/app-sandbox/route_client-reference-manifest.js +1 -1
  37. package/.next/server/app/api/mcp/cancel/route_client-reference-manifest.js +1 -1
  38. package/.next/server/app/api/mcp/flujo/authoring/route_client-reference-manifest.js +1 -1
  39. package/.next/server/app/api/mcp/flujo/automation/route_client-reference-manifest.js +1 -1
  40. package/.next/server/app/api/mcp/flujo/flows/route_client-reference-manifest.js +1 -1
  41. package/.next/server/app/api/mcp/flujo/resources/read/route_client-reference-manifest.js +1 -1
  42. package/.next/server/app/api/mcp/flujo/resources/route_client-reference-manifest.js +1 -1
  43. package/.next/server/app/api/mcp/flujo/servers/route_client-reference-manifest.js +1 -1
  44. package/.next/server/app/api/mcp/flujo/state/route_client-reference-manifest.js +1 -1
  45. package/.next/server/app/api/mcp/flujo/tools/route_client-reference-manifest.js +1 -1
  46. package/.next/server/app/api/mcp/oauth-capability/route_client-reference-manifest.js +1 -1
  47. package/.next/server/app/api/mcp/servers/[name]/prompts/get/route_client-reference-manifest.js +1 -1
  48. package/.next/server/app/api/mcp/servers/[name]/prompts/route_client-reference-manifest.js +1 -1
  49. package/.next/server/app/api/mcp/servers/[name]/resources/read/route_client-reference-manifest.js +1 -1
  50. package/.next/server/app/api/mcp/servers/[name]/resources/route_client-reference-manifest.js +1 -1
  51. package/.next/server/app/api/mcp/servers/[name]/route_client-reference-manifest.js +1 -1
  52. package/.next/server/app/api/mcp/servers/[name]/status/route_client-reference-manifest.js +1 -1
  53. package/.next/server/app/api/mcp/servers/[name]/tools/[toolName]/route_client-reference-manifest.js +1 -1
  54. package/.next/server/app/api/mcp/servers/[name]/tools/route_client-reference-manifest.js +1 -1
  55. package/.next/server/app/api/mcp/servers/route_client-reference-manifest.js +1 -1
  56. package/.next/server/app/api/mcp/test-connection/route_client-reference-manifest.js +1 -1
  57. package/.next/server/app/api/mcp/test-connection/stream/route_client-reference-manifest.js +1 -1
  58. package/.next/server/app/api/mcp-registry/route_client-reference-manifest.js +1 -1
  59. package/.next/server/app/api/mcp-registry/spotlight/route_client-reference-manifest.js +1 -1
  60. package/.next/server/app/api/model/[id]/route_client-reference-manifest.js +1 -1
  61. package/.next/server/app/api/model/provider/route_client-reference-manifest.js +1 -1
  62. package/.next/server/app/api/model/route_client-reference-manifest.js +1 -1
  63. package/.next/server/app/api/model/test/route_client-reference-manifest.js +1 -1
  64. package/.next/server/app/api/oauth/callback/route_client-reference-manifest.js +1 -1
  65. package/.next/server/app/api/oauth/initiate/route_client-reference-manifest.js +1 -1
  66. package/.next/server/app/api/oauth/reset/route_client-reference-manifest.js +1 -1
  67. package/.next/server/app/api/packages/build/route_client-reference-manifest.js +1 -1
  68. package/.next/server/app/api/packages/derive-secrets/route_client-reference-manifest.js +1 -1
  69. package/.next/server/app/api/packages/install/route_client-reference-manifest.js +1 -1
  70. package/.next/server/app/api/packages/install/status/route_client-reference-manifest.js +1 -1
  71. package/.next/server/app/api/packages/installed/route_client-reference-manifest.js +1 -1
  72. package/.next/server/app/api/packages/resolve/route_client-reference-manifest.js +1 -1
  73. package/.next/server/app/api/packages/scan-targets/route_client-reference-manifest.js +1 -1
  74. package/.next/server/app/api/packages/search/route_client-reference-manifest.js +1 -1
  75. package/.next/server/app/api/packages/uninstall/route_client-reference-manifest.js +1 -1
  76. package/.next/server/app/api/planned-executions/[id]/route_client-reference-manifest.js +1 -1
  77. package/.next/server/app/api/planned-executions/[id]/run/route_client-reference-manifest.js +1 -1
  78. package/.next/server/app/api/planned-executions/[id]/runs/route_client-reference-manifest.js +1 -1
  79. package/.next/server/app/api/planned-executions/preview-schedule/route_client-reference-manifest.js +1 -1
  80. package/.next/server/app/api/planned-executions/reconcile/route_client-reference-manifest.js +1 -1
  81. package/.next/server/app/api/planned-executions/route_client-reference-manifest.js +1 -1
  82. package/.next/server/app/api/registry/auth/resend/route_client-reference-manifest.js +1 -1
  83. package/.next/server/app/api/registry/auth/reset/route_client-reference-manifest.js +1 -1
  84. package/.next/server/app/api/registry/auth/route_client-reference-manifest.js +1 -1
  85. package/.next/server/app/api/registry/feedback/route_client-reference-manifest.js +1 -1
  86. package/.next/server/app/api/registry/oauth/callback/route_client-reference-manifest.js +1 -1
  87. package/.next/server/app/api/registry/oauth/initiate/route_client-reference-manifest.js +1 -1
  88. package/.next/server/app/api/registry/packages/route_client-reference-manifest.js +1 -1
  89. package/.next/server/app/api/registry/publish/route_client-reference-manifest.js +1 -1
  90. package/.next/server/app/api/registry/settings/route_client-reference-manifest.js +1 -1
  91. package/.next/server/app/api/restore/route_client-reference-manifest.js +1 -1
  92. package/.next/server/app/api/runs/active/route_client-reference-manifest.js +1 -1
  93. package/.next/server/app/api/setup/ai-cli/route_client-reference-manifest.js +1 -1
  94. package/.next/server/app/api/statistics/route_client-reference-manifest.js +1 -1
  95. package/.next/server/app/api/storage/route_client-reference-manifest.js +1 -1
  96. package/.next/server/app/api/telemetry/daily-active/route.js +1 -1
  97. package/.next/server/app/api/telemetry/daily-active/route_client-reference-manifest.js +1 -1
  98. package/.next/server/app/api/update/route_client-reference-manifest.js +1 -1
  99. package/.next/server/app/api/waves/route_client-reference-manifest.js +1 -1
  100. package/.next/server/app/api/webhooks/[id]/route_client-reference-manifest.js +1 -1
  101. package/.next/server/app/automation/triggers/page.js +1 -1
  102. package/.next/server/app/automation/triggers/page.js.nft.json +1 -1
  103. package/.next/server/app/automation/triggers/page_client-reference-manifest.js +1 -1
  104. package/.next/server/app/automation/triggers.html +1 -1
  105. package/.next/server/app/automation/triggers.rsc +4 -4
  106. package/.next/server/app/automation/waves/page_client-reference-manifest.js +1 -1
  107. package/.next/server/app/automation/waves.html +1 -1
  108. package/.next/server/app/automation/waves.rsc +4 -4
  109. package/.next/server/app/chat/page.js +2 -2
  110. package/.next/server/app/chat/page_client-reference-manifest.js +1 -1
  111. package/.next/server/app/chat.html +1 -1
  112. package/.next/server/app/chat.rsc +4 -4
  113. package/.next/server/app/docs/page.js +3 -3
  114. package/.next/server/app/docs/page_client-reference-manifest.js +1 -1
  115. package/.next/server/app/docs.html +1 -1
  116. package/.next/server/app/docs.rsc +4 -4
  117. package/.next/server/app/executions/page.js +1 -1
  118. package/.next/server/app/executions/page.js.nft.json +1 -1
  119. package/.next/server/app/executions/page_client-reference-manifest.js +1 -1
  120. package/.next/server/app/executions.html +1 -1
  121. package/.next/server/app/executions.rsc +4 -4
  122. package/.next/server/app/flows/page.js +5 -3
  123. package/.next/server/app/flows/page.js.nft.json +1 -1
  124. package/.next/server/app/flows/page_client-reference-manifest.js +1 -1
  125. package/.next/server/app/flows.html +1 -1
  126. package/.next/server/app/flows.rsc +4 -4
  127. package/.next/server/app/index.html +1 -1
  128. package/.next/server/app/index.rsc +4 -4
  129. package/.next/server/app/mcp/page.js +73 -44
  130. package/.next/server/app/mcp/page.js.nft.json +1 -1
  131. package/.next/server/app/mcp/page_client-reference-manifest.js +1 -1
  132. package/.next/server/app/mcp-flows/route.js +1 -1
  133. package/.next/server/app/mcp-flows/route_client-reference-manifest.js +1 -1
  134. package/.next/server/app/mcp-proxy/[server]/route.js +1 -1
  135. package/.next/server/app/mcp-proxy/[server]/route_client-reference-manifest.js +1 -1
  136. package/.next/server/app/mcp.html +1 -1
  137. package/.next/server/app/mcp.rsc +4 -4
  138. package/.next/server/app/models/page.js +7 -7
  139. package/.next/server/app/models/page_client-reference-manifest.js +1 -1
  140. package/.next/server/app/packages/page.js +1 -1
  141. package/.next/server/app/packages/page_client-reference-manifest.js +1 -1
  142. package/.next/server/app/packages.html +1 -1
  143. package/.next/server/app/packages.rsc +4 -4
  144. package/.next/server/app/page.js +2 -2
  145. package/.next/server/app/page_client-reference-manifest.js +1 -1
  146. package/.next/server/app/settings/page.js +2 -2
  147. package/.next/server/app/settings/page_client-reference-manifest.js +1 -1
  148. package/.next/server/app/settings.html +1 -1
  149. package/.next/server/app/settings.rsc +4 -4
  150. package/.next/server/app/statistics/page.js +2 -2
  151. package/.next/server/app/statistics/page_client-reference-manifest.js +1 -1
  152. package/.next/server/app/statistics.html +1 -1
  153. package/.next/server/app/statistics.rsc +4 -4
  154. package/.next/server/app/v1/chat/completions/route_client-reference-manifest.js +1 -1
  155. package/.next/server/app/v1/chat/conversations/[conversationId]/breakpoints/route_client-reference-manifest.js +1 -1
  156. package/.next/server/app/v1/chat/conversations/[conversationId]/cancel/route_client-reference-manifest.js +1 -1
  157. package/.next/server/app/v1/chat/conversations/[conversationId]/debug/continue/route_client-reference-manifest.js +1 -1
  158. package/.next/server/app/v1/chat/conversations/[conversationId]/debug/step/route_client-reference-manifest.js +1 -1
  159. package/.next/server/app/v1/chat/conversations/[conversationId]/edit-state/route_client-reference-manifest.js +1 -1
  160. package/.next/server/app/v1/chat/conversations/[conversationId]/events/route_client-reference-manifest.js +1 -1
  161. package/.next/server/app/v1/chat/conversations/[conversationId]/inject/route_client-reference-manifest.js +1 -1
  162. package/.next/server/app/v1/chat/conversations/[conversationId]/resources/[resourceId]/content/route_client-reference-manifest.js +1 -1
  163. package/.next/server/app/v1/chat/conversations/[conversationId]/resources/route_client-reference-manifest.js +1 -1
  164. package/.next/server/app/v1/chat/conversations/[conversationId]/respond/route_client-reference-manifest.js +1 -1
  165. package/.next/server/app/v1/chat/conversations/[conversationId]/revert/route_client-reference-manifest.js +1 -1
  166. package/.next/server/app/v1/chat/conversations/[conversationId]/route_client-reference-manifest.js +1 -1
  167. package/.next/server/app/v1/chat/conversations/route_client-reference-manifest.js +1 -1
  168. package/.next/server/app/v1/chat/events/route_client-reference-manifest.js +1 -1
  169. package/.next/server/app/v1/models/route_client-reference-manifest.js +1 -1
  170. package/.next/server/app/waves/page_client-reference-manifest.js +1 -1
  171. package/.next/server/app/waves.html +1 -1
  172. package/.next/server/app/waves.rsc +4 -4
  173. package/.next/server/app-paths-manifest.json +53 -53
  174. package/.next/server/chunks/1227.js +1 -1
  175. package/.next/server/chunks/1403.js +2 -2
  176. package/.next/server/chunks/1539.js +1 -1
  177. package/.next/server/chunks/2069.js +1 -1
  178. package/.next/server/chunks/2372.js +1 -1
  179. package/.next/server/chunks/2828.js +2 -2
  180. package/.next/server/chunks/3422.js +1 -0
  181. package/.next/server/chunks/3945.js +3 -3
  182. package/.next/server/chunks/519.js +2 -2
  183. package/.next/server/chunks/5444.js +2 -2
  184. package/.next/server/chunks/5750.js +1 -1
  185. package/.next/server/chunks/5918.js +10 -10
  186. package/.next/server/chunks/6226.js +2 -2
  187. package/.next/server/chunks/9088.js +2 -2
  188. package/.next/server/chunks/9490.js +5 -0
  189. package/.next/server/chunks/9543.js +3 -3
  190. package/.next/server/chunks/9624.js +8 -8
  191. package/.next/server/middleware-build-manifest.js +1 -1
  192. package/.next/server/middleware-manifest.json +1 -1
  193. package/.next/server/middleware-react-loadable-manifest.js +1 -1
  194. package/.next/server/pages/404.html +1 -1
  195. package/.next/server/pages/500.html +1 -1
  196. package/.next/server/server-reference-manifest.js +1 -1
  197. package/.next/server/server-reference-manifest.json +1 -1
  198. package/.next/static/chunks/{1161-19176c3e7c655121.js → 1161-563a8028f59f00de.js} +1 -1
  199. package/.next/static/chunks/1521-9ad145dcb8e3abfc.js +1 -0
  200. package/.next/static/chunks/1576.06797b29a19fa26c.js +1 -0
  201. package/.next/static/chunks/{4386-e9621d3c94969a68.js → 2005-f9d38c39f10c321f.js} +1 -1
  202. package/.next/static/chunks/2493-da85c47ef972c066.js +1 -0
  203. package/.next/static/chunks/361.c88d43436e974006.js +1 -0
  204. package/.next/static/chunks/3731-c18f48522b159d7f.js +1 -0
  205. package/.next/static/chunks/3781.5086bce03aa281f7.js +1 -0
  206. package/.next/static/chunks/3969-15a32253b112652c.js +1 -0
  207. package/.next/static/chunks/4167.2ce97ca450815df1.js +1 -0
  208. package/.next/static/chunks/4814-52b7254ab573a455.js +1 -0
  209. package/.next/static/chunks/4965.d401547984d71b7a.js +1 -0
  210. package/.next/static/chunks/5148-9174ba300221fd1b.js +1 -0
  211. package/.next/static/chunks/5417-fb7d3760cc288ab1.js +1 -0
  212. package/.next/static/chunks/5967-34735763d1b03ccc.js +1 -0
  213. package/.next/static/chunks/7260-743e4b0cc4211dcb.js +1 -0
  214. package/.next/static/chunks/7711-7323dabe7dc02311.js +1 -0
  215. package/.next/static/chunks/8124-f99060fe1dfc119e.js +1 -0
  216. package/.next/static/chunks/8135-7fe07a34a8c49967.js +1 -0
  217. package/.next/static/chunks/8529.6187e01de8e9a692.js +1 -0
  218. package/.next/static/chunks/9136-e9ee57cc581ddd50.js +1 -0
  219. package/.next/static/chunks/9140.9180b569c4b26168.js +1 -0
  220. package/.next/static/chunks/9195-6a18a5867bb76c64.js +1 -0
  221. package/.next/static/chunks/app/automation/triggers/{page-594a6294c58344bf.js → page-34b9a8a2e6f28c2f.js} +1 -1
  222. package/.next/static/chunks/app/automation/waves/{page-ce2fef4996cad8e6.js → page-fd4929ea308183b2.js} +1 -1
  223. package/.next/static/chunks/app/chat/page-fb8a33db7628ecd0.js +1 -0
  224. package/.next/static/chunks/app/docs/page-3e21583b1cd5d7ca.js +1 -0
  225. package/.next/static/chunks/app/executions/{page-fcc848de86714386.js → page-56ecca56c17c05d7.js} +1 -1
  226. package/.next/static/chunks/app/flows/page-8c1a656197b15894.js +1 -0
  227. package/.next/static/chunks/app/layout-6e2756704ddc9f39.js +1 -0
  228. package/.next/static/chunks/app/mcp/page-4c4390354fdd94c8.js +1 -0
  229. package/.next/static/chunks/app/models/error-ea477f0ad52f4dcb.js +1 -0
  230. package/.next/static/chunks/app/models/page-e237ac64a0f62c3d.js +1 -0
  231. package/.next/static/chunks/app/packages/page-8680e4bea6b7ea45.js +1 -0
  232. package/.next/static/chunks/app/page-6dca06b6b7667181.js +1 -0
  233. package/.next/static/chunks/app/settings/page-a5f7fedcbf9e3a7f.js +1 -0
  234. package/.next/static/chunks/app/statistics/page-f9f9627d1c1ff963.js +1 -0
  235. package/.next/static/chunks/app/waves/{page-5b53af3eb9409414.js → page-7529febc48eb473d.js} +1 -1
  236. package/.next/static/chunks/{webpack-9fbd3587b9ef4dca.js → webpack-f3df493faa0bd612.js} +1 -1
  237. package/.next/static/css/{400b1b927c3ffaf6.css → 9f9b7f1374ac2d01.css} +1 -1
  238. package/.next/trace +11 -11
  239. package/README.md +1 -1
  240. package/mcp-servers/bash/package.json +1 -1
  241. package/mcp-servers/browser/package.json +1 -1
  242. package/mcp-servers/filesystem/package.json +1 -1
  243. package/mcp-servers/flujo/package.json +1 -1
  244. package/package.json +5 -5
  245. package/.next/server/chunks/7508.js +0 -5
  246. package/.next/server/chunks/8598.js +0 -1
  247. package/.next/static/chunks/1521-1c98c9a56726e053.js +0 -1
  248. package/.next/static/chunks/1576.bc6ae6c9e6d939d8.js +0 -1
  249. package/.next/static/chunks/2005.300528b5119c2d38.js +0 -1
  250. package/.next/static/chunks/2499-92cd97ce4993999f.js +0 -1
  251. package/.next/static/chunks/361.51d642c530c84295.js +0 -1
  252. package/.next/static/chunks/3731-64070760ae44448f.js +0 -1
  253. package/.next/static/chunks/4814-31eb5f3b10c651c1.js +0 -1
  254. package/.next/static/chunks/4965.39e24b54c3c6ca58.js +0 -1
  255. package/.next/static/chunks/5967-59fde8c214c9ca9f.js +0 -1
  256. package/.next/static/chunks/6417.70056fe81ca21682.js +0 -1
  257. package/.next/static/chunks/7711-4b017720ec49c96d.js +0 -1
  258. package/.next/static/chunks/8124-94140ee1dd8ed87c.js +0 -1
  259. package/.next/static/chunks/8135-5b975b9014f8920b.js +0 -1
  260. package/.next/static/chunks/8529.b5a43e728bb5bb8a.js +0 -1
  261. package/.next/static/chunks/9001-4c27a608feddb878.js +0 -1
  262. package/.next/static/chunks/9136-9c415453ec02519c.js +0 -1
  263. package/.next/static/chunks/9140.6502327a2c098d33.js +0 -1
  264. package/.next/static/chunks/9195-3c9c4300e7505d9e.js +0 -1
  265. package/.next/static/chunks/9524-b9d2c7e4426edd07.js +0 -1
  266. package/.next/static/chunks/app/chat/page-203cb7bf21638ada.js +0 -1
  267. package/.next/static/chunks/app/docs/page-c466a58caf5e3336.js +0 -1
  268. package/.next/static/chunks/app/flows/page-172c759ca81ba02f.js +0 -1
  269. package/.next/static/chunks/app/layout-a6ca531683a518a7.js +0 -1
  270. package/.next/static/chunks/app/mcp/page-0a96e6b30e45b1e6.js +0 -1
  271. package/.next/static/chunks/app/models/error-1964203c5c6e7d0e.js +0 -1
  272. package/.next/static/chunks/app/models/page-ad1cbea6d3324966.js +0 -1
  273. package/.next/static/chunks/app/packages/page-dda48425be9fc137.js +0 -1
  274. package/.next/static/chunks/app/page-04189aa1b1318c2d.js +0 -1
  275. package/.next/static/chunks/app/settings/page-906c229c87011ead.js +0 -1
  276. package/.next/static/chunks/app/statistics/page-9b13a95549f438c0.js +0 -1
  277. /package/.next/static/{b1aMk0634gkkiunttd1SQ → utOrEUSzguWncIosxgCeR}/_buildManifest.js +0 -0
  278. /package/.next/static/{b1aMk0634gkkiunttd1SQ → utOrEUSzguWncIosxgCeR}/_ssgManifest.js +0 -0
@@ -1 +0,0 @@
1
- (self.webpackChunk_N_E=self.webpackChunk_N_E||[]).push([[8457],{66150:(e,t,n)=>{"use strict";n.r(t),n.d(t,{default:()=>nY});var a=n(95155),o=n(12115),r=n(97322),l=n(20063),i=n(15712),s=n(94049),d=n(22003),c=n(25635),u=n(78470),h=n(41983),p=n(13315),g=n(9562),f=n(28548),m=n(91871),v=n(3339),x=n(67895),y=n(2778),b=n(52363),w=n(65036),A=n(50001),j=n(75912),k=n(33567),I=n(22719),S=n(11096),C=n(76530),E=n(36741),T=n(60691),N=n(47419),z=n(78410),M=n(14915),D=n(55930),R=n(56900),F=n(26922),P=n(29692),O=n(23820),_=n(73707),W=n(17681),q=n(21067),L=n(56422),U=n(52641),H=n(55606),B=n(86973),K=n(41602),G=n(50430),X=n(4484),J=n(86946),Q=n(19219),Y=n(51611),V=n(12140),Z=n(63186),$=n(62962),ee=n(51331),et=n(97736),en=n(16024),ea=n(44055),eo=n(38343),er=n(45413),el=n(41450),ei=n(52393),es=n(60700),ed=n(15023),ec=n(39297);function eu(e){return"string"==typeof e&&e.startsWith("quickchat-")}n(77890);var eh=n(88377),ep=n(38459);let eg="wave:__adhoc__",ef="wave:__archived__";var em=n(97104);function ev(e){let{nodes:t,childrenByParent:n,renderItem:o,expanded:r,onToggle:l,depth:i=0,visited:d,maxDepth:c=20}=e;if(!t||0===t.length||i>c)return null;let u=null!=d?d:new Set;return(0,a.jsx)(a.Fragment,{children:t.map(e=>{var t;if(u.has(e.id))return null;let d=null!=(t=n.get(e.id))?t:[],p=d.length>0&&i<c,g=!1!==r[e.id],f=new Set(u);return f.add(e.id),(0,a.jsxs)(s.default,{sx:{pl:1.5*(i>0),borderLeft:i>0?"1px dashed rgba(128,128,128,0.35)":"none"},children:[(0,a.jsxs)(s.default,{sx:{display:"flex",alignItems:"flex-start"},children:[p?(0,a.jsx)(h.A,{size:"small",onClick:()=>l(e.id),"aria-label":g?"Collapse chain":"Expand chain",sx:{mt:.5,flexShrink:0},children:g?(0,a.jsx)($.A,{fontSize:"small"}):(0,a.jsx)(Z.A,{fontSize:"small"})}):(0,a.jsx)(s.default,{sx:{width:34,flexShrink:0}}),(0,a.jsx)(s.default,{sx:{flex:1,minWidth:0},children:o(e,i)})]}),p&&(0,a.jsx)(G.A,{in:g,timeout:"auto",unmountOnExit:!0,children:(0,a.jsx)(ev,{nodes:d,childrenByParent:n,renderItem:o,expanded:r,onToggle:l,depth:i+1,visited:f,maxDepth:c})})]},e.id)})})}function ex(e){var t,n;let a=new Map;for(let t of e)a.set(t.id,t);let o=new Map,r=[],l=e=>e.parentConversationId&&e.parentConversationId!==e.id?e.parentConversationId:null;for(let n of e){let e=l(n);if(e&&a.has(e)){let a=null!=(t=o.get(e))?t:[];a.push(n),o.set(e,a)}else r.push(n)}let i=new Set,s=[...r];for(;s.length;){let e=s.pop();if(!i.has(e.id))for(let t of(i.add(e.id),null!=(n=o.get(e.id))?n:[]))s.push(t)}let d=new Set(r.map(e=>e.id));for(let t of e)i.has(t.id)||d.has(t.id)||(r.push(t),d.add(t.id));return{roots:r,childrenByParent:o}}var ey=n(8532),eb=n(26796);let ew={chat:{label:"User chat",description:"Started interactively from the chat workspace"},api:{label:"API",description:"Started through the chat completions API"},schedule:{label:"Automation",description:"Started by a planned execution or automation trigger"},trigger:{label:"Trigger",description:"Started by an unattended runtime trigger"},subflow:{label:"Subagent",description:"Spawned as a subagent by another conversation"},mcp:{label:"MCP run",description:"Started through FLUJO's MCP interface"},internal:{label:"Internal",description:"Started by an internal FLUJO tool"},unknown:{label:"Unknown origin",description:"Origin metadata was not recorded for this older conversation"}};function eA(e,t){return{key:e,...ew[e],inferred:t}}function ej(e){return e.source&&e.source in ew?eA(e.source,!1):e.parentConversationId?eA("subflow",!0):e.plannedExecutionId?eA("schedule",!0):eA("unknown",!0)}var ek=n(53868);let eI={group:"flujo-ui:chat-sidebar:group",status:"flujo-ui:chat-sidebar:status",flow:"flujo-ui:chat-sidebar:flow",date:"flujo-ui:chat-sidebar:date",collapsed:"flujo-ui:chat-sidebar:collapsed",searchDim:"flujo-ui:chat-sidebar:search-dim"},eS=[{value:"all",label:"Any status"},{value:"running",label:"Processing"},{value:"awaiting_tool_approval",label:"Awaiting approval"},{value:"paused_debug",label:"Paused (debug)"},{value:"completed",label:"Completed"},{value:"error",label:"Error"}],eC=[{value:"all",label:"Any time"},{value:"today",label:"Last 24h"},{value:"7d",label:"Last 7 days"},{value:"30d",label:"Last 30 days"}],eE=[{value:"none",label:"No grouping"},{value:"date",label:"Group by date"},{value:"flow",label:"Group by agent"},{value:"origin",label:"Group by origin"},{value:"wave",label:"Group by wave"},{value:"chain",label:"Group by chain"}],eT={chat:en.A,api:el.A,schedule:ea.A,trigger:er.A,subflow:eo.A,mcp:ei.A,internal:es.A,unknown:ed.A},eN=o.memo(e=>{let{conversations:t,currentConversationId:n,onSelectConversation:r,onDeleteConversation:l,onBulkDelete:i,onStopConversation:d,onNewConversation:p,onQuickChat:v,onCollapse:x,flowNames:I={}}=e,C=(0,k.A)(),{visualStyle:E}=(0,eb.useTheme)(),T="modern"===E,[z,M]=o.useState(""),[D,R]=o.useState({open:!1,ids:[],label:""}),[F,P]=(0,em.Xk)(eI.searchDim,"title"),[en,ea]=o.useState(null),[eo,er]=(0,em.Xk)(eI.group,"none"),[el,ei]=(0,em.Xk)(eI.status,"all"),[es,ed]=(0,em.Xk)(eI.flow,"all"),[ew,eA]=(0,em.Xk)(eI.date,"all"),[eN,ez]=(0,em.Xk)(eI.collapsed,{}),[eM,eD]=o.useState(null),eR=(0,o.useMemo)(()=>t.map(e=>{var t;return"".concat(e.id,":").concat(null!=(t=e.plannedExecutionId)?t:"")}).join("\0"),[t]);o.useEffect(()=>{if("wave"!==eo)return;let e=!1;return fetch("/api/waves").then(e=>e.ok?e.json():null).then(t=>{!e&&t&&eD(t)}).catch(()=>{}),()=>{e=!0}},[eo,eR]);let eF=(0,o.useMemo)(()=>(function(e){let t=new Map;if(!(null==e?void 0:e.waves))return t;for(let a of e.waves){var n;let e=null==(n=a.rootExecutionIds)?void 0:n[0],o=e&&a.nodes.find(t=>t.executionId===e)||a.nodes[0],r=(null==o?void 0:o.name)||(null==o?void 0:o.flowName)||a.id;for(let e of a.nodes)t.set(e.executionId,{waveId:a.id,label:r})}return t})(eM),[eM]);o.useEffect(()=>{let e=z.trim();if("content"!==F||0===e.length)return void ea(null);let t=!1,n=setTimeout(()=>{fetch("/v1/chat/conversations?search=".concat(encodeURIComponent(e),"&dimension=content")).then(e=>e.ok?e.json():[]).then(e=>{t||ea(new Set(Array.isArray(e)?e.map(e=>e.id):[]))}).catch(()=>{t||ea(new Set)})},300);return()=>{t=!0,clearTimeout(n)}},[z,F]);let eP=o.useCallback(e=>{var t;return e?eu(e)?{key:"flow:__quickchat__",label:"Quick Chat"}:{key:"flow:".concat(e),label:null!=(t=I[e])?t:"Unknown agent"}:{key:"flow:__none__",label:"No agent"}},[I]),eO=(0,o.useMemo)(()=>{let e=new Map;for(let n of t){let t=eP(n.flowId);e.has(t.key)||e.set(t.key,t.label)}return Array.from(e.entries()).map(e=>{let[t,n]=e;return{key:t,label:n}}).sort((e,t)=>e.label.localeCompare(t.label))},[t,eP]),e_=(0,o.useMemo)(()=>{let e=z.trim().toLowerCase(),n=Date.now(),a="today"===ew?n-864e5:"7d"===ew?n-6048e5:"30d"===ew?n-2592e6:0;return t.filter(t=>{if("all"!==el&&t.status!==el||"all"!==es&&eP(t.flowId).key!==es||a&&t.updatedAt<a)return!1;if(e)if("content"===F){if(!en||!en.has(t.id))return!1}else{let n=ej(t);if(!"".concat(t.title," ").concat(eP(t.flowId).label," ").concat(n.label).toLowerCase().includes(e))return!1}return!0}).sort((e,t)=>{var n,a;return(null!=(n=t.lastUserMessageAt)?n:t.updatedAt)-(null!=(a=e.lastUserMessageAt)?a:e.updatedAt)})},[t,z,F,en,el,es,ew,eP]),eW=(0,o.useMemo)(()=>"none"===eo?[{key:"all",label:"",items:e_}]:"wave"===eo?function(e){let t=new Set([eg,ef]);return[...e.filter(e=>!t.has(e.key)),...e.filter(e=>t.has(e.key))]}((0,ep.Az)(e_,e=>(function(e,t){if(!e)return{key:eg,label:"Ad-hoc"};let n=t.get(e);return n?{key:"wave:".concat(n.waveId),label:n.label}:{key:ef,label:"Archived / no longer scheduled"}})(e.plannedExecutionId,eF))):(0,ep.Az)(e_,e=>{if("date"===eo)return(0,eh.K)(e.updatedAt);if("origin"===eo){let t=ej(e);return{key:"origin:".concat(t.key),label:t.label}}return eP(e.flowId)}),[e_,eo,eP,eF]),eq=(0,o.useMemo)(()=>"chain"===eo?ex(e_):{roots:[],childrenByParent:new Map},[eo,e_]),[eL,eU]=o.useState({}),eH=o.useCallback(e=>{eU(t=>({...t,[e]:!1===t[e]}))},[]),eB=(0,o.useMemo)(()=>{let e=new Map;if("wave"!==eo)return e;for(let t of eW)e.set(t.key,ex(t.items));return e},[eo,eW]),eK=+("all"!==el)+ +("all"!==es)+ +("all"!==ew),eG=e=>{let t=!!d&&("running"===e.status||"awaiting_tool_approval"===e.status),o=eP(e.flowId),i="flow:__quickchat__"===o.key,p=e.id===n,g=ej(e),m=eT[g.key],v=function(e,t){switch(e){case"subflow":return t.palette.warning.main;case"schedule":case"trigger":return ek.L.light.signal;case"mcp":return t.palette.info.main;default:return t.palette.primary.main}}(g.key,C),x=function(e,t){switch(e){case"running":return t.palette.primary.main;case"awaiting_tool_approval":return t.palette.warning.main;case"paused_debug":return t.palette.secondary.main;case"completed":return t.palette.success.main;case"capped":return t.palette.info.main;case"error":return t.palette.error.main;default:return t.palette.text.disabled}}(e.status,C),y=p?"dark"===C.palette.mode?.38:.3:"dark"===C.palette.mode?.3:.23;return(0,a.jsx)(O.Ay,{"data-conversation-origin":g.key,disablePadding:!0,secondaryAction:(0,a.jsxs)(s.default,{className:"conversation-card-actions",sx:T?{display:"flex",zIndex:2,gap:.25,opacity:+!!p,transition:"opacity 160ms ease",bgcolor:(0,ey.X4)(C.palette.background.paper,.72),borderRadius:2,backdropFilter:"blur(12px)","& .MuiIconButton-root":{width:30,height:30}}:{display:"flex"},children:[t&&(0,a.jsx)(u.A,{title:"Stop this run",children:(0,a.jsx)(h.A,{edge:"end",size:"small","aria-label":"stop run",onClick:t=>{t.stopPropagation(),d(e.id)},children:(0,a.jsx)(N.A,{color:"error",fontSize:"small"})})}),(0,a.jsx)(u.A,{title:"Delete conversation",children:(0,a.jsx)(h.A,{edge:"end",size:"small","aria-label":"delete",onClick:t=>{t.stopPropagation(),l(e.id)},children:(0,a.jsx)(X.A,{fontSize:"small"})})})]}),sx:T?{position:"relative",mb:.9,border:"1px solid",borderColor:p?(0,ey.X4)(v,.68):(0,ey.X4)(v,.32),borderRadius:2.5,overflow:"hidden",opacity:1,bgcolor:(0,ey.X4)(C.palette.background.paper,"dark"===C.palette.mode?.72:.82),backgroundImage:function(e,t,n){let a=(0,ey.X4)(e,n),o=(0,ey.X4)(t,n);return"linear-gradient(90deg, ".concat(a," 0%, ").concat(a," 90%, ").concat(o," 90%, ").concat(o," 100%)")}(v,x,y),boxShadow:p?"0 10px 30px ".concat((0,ey.X4)(v,.24)):"0 5px 20px ".concat((0,ey.X4)(v,"dark"===C.palette.mode?.12:.08)),transition:"transform 160ms ease, border-color 160ms ease, box-shadow 160ms ease, background-color 160ms ease","&::before":{content:'""',position:"absolute",inset:"10px auto 10px 0",width:p?4:3,borderRadius:"0 4px 4px 0",bgcolor:v},"&::after":{content:'""',position:"absolute",zIndex:0,top:0,bottom:0,left:"90%",width:1,bgcolor:(0,ey.X4)(x,.5),pointerEvents:"none"},"&:hover":{transform:"translateY(-1px)",borderColor:(0,ey.X4)(v,.58),boxShadow:"0 10px 28px ".concat((0,ey.X4)(v,"dark"===C.palette.mode?.2:.14)),"& .conversation-card-actions":{opacity:1}},"&:focus-within .conversation-card-actions":{opacity:1},"@media (hover: none)":{"& .conversation-card-actions":{opacity:1}}}:{opacity:p?1:.7},children:(0,a.jsx)(_.A,{selected:p,onClick:()=>r(e.id),"aria-label":"Open ".concat(e.title,", origin: ").concat(g.label,", status: ").concat((e=>{switch(e){case"running":return"Processing";case"awaiting_tool_approval":return"Waiting for tool approval";case"paused_debug":return"Paused in debug mode";case"completed":return"Completed";case"capped":return"Landed at turn limit (summary produced)";case"error":return"Error";default:return""}})(e.status)||"Unknown"),sx:{position:"relative",zIndex:1,pr:t?12:7,px:T?1.5:2,py:T?1.25:1,alignItems:"flex-start",borderRadius:"inherit","&.Mui-selected":{bgcolor:"transparent"},"&.Mui-selected:hover":{bgcolor:(0,ey.X4)(C.palette.primary.main,.04)}},children:(0,a.jsx)(W.A,{sx:{my:0,minWidth:0},primary:(0,a.jsx)(s.default,{sx:{display:"flex",alignItems:"center"},children:(0,a.jsx)(u.A,{title:e.title,enterDelay:500,children:(0,a.jsx)(c.A,{component:"span",fontWeight:p?760:T?650:"normal",sx:{display:"-webkit-box",WebkitLineClamp:2,WebkitBoxOrient:"vertical",overflow:"hidden",wordBreak:"break-word",fontSize:T?"0.9rem":void 0,lineHeight:T?1.35:void 0},children:e.title})})}),secondary:(0,a.jsxs)(s.default,{component:"span",sx:{display:"flex",alignItems:"center",gap:.75,mt:.8,flexWrap:"wrap"},children:["origin"!==eo&&(0,a.jsx)(u.A,{title:"".concat(g.description).concat(g.inferred?" (inferred from legacy metadata)":""),children:(0,a.jsx)(f.A,{icon:(0,a.jsx)(m,{}),label:g.label,size:"small",variant:"outlined",sx:{height:T?22:20,color:T?v:void 0,borderColor:T?(0,ey.X4)(v,.72):void 0,bgcolor:T?(0,ey.X4)(v,.13):void 0,"& .MuiChip-icon":{fontSize:14,color:T?v:void 0},"& .MuiChip-label":{px:.75,fontSize:"0.68rem",fontWeight:T?700:500}}})}),"flow"!==eo&&(0,a.jsx)(u.A,{title:i?"Quick Chat (no saved agent)":"Agent: ".concat(o.label),children:(0,a.jsx)(f.A,{icon:i?(0,a.jsx)(S.A,{}):void 0,label:o.label,size:"small",variant:"outlined",color:i?"secondary":"default",sx:{maxWidth:"100%",height:T?22:20,"& .MuiChip-icon":{fontSize:14},"& .MuiChip-label":{px:.75,fontSize:"0.68rem"}}})}),(0,a.jsxs)(s.default,{component:"span",sx:{display:"inline-flex",alignItems:"center",gap:.35,ml:"auto"},children:[T&&(0,a.jsx)(ec.A,{"aria-hidden":"true",sx:{fontSize:13,color:"text.disabled"}}),(0,a.jsx)(c.A,{component:"span",variant:"caption",color:"text.secondary",sx:{whiteSpace:"nowrap"},children:new Date(e.updatedAt).toLocaleDateString(void 0,{month:"short",day:"numeric",hour:"2-digit",minute:"2-digit"})})]})]}),secondaryTypographyProps:{component:"div"}})})},e.id)},eX=t.length,eJ=e_.length;return(0,a.jsxs)(a.Fragment,{children:[(0,a.jsxs)(s.default,{sx:{p:T?2:1.5,display:"flex",justifyContent:"space-between",alignItems:"center",gap:T?1:.7,background:T?"linear-gradient(135deg, ".concat((0,ey.X4)(C.palette.primary.main,.14),", ").concat((0,ey.X4)(C.palette.secondary.main,.05)," 58%, transparent)"):"linear-gradient(120deg, rgba(139,124,255,.09), transparent 62%)"},children:[x&&(0,a.jsx)(u.A,{title:"Hide sidebar",children:(0,a.jsx)(h.A,{size:"small",onClick:x,"aria-label":"Hide conversation sidebar",children:(0,a.jsx)(Q.A,{})})}),(0,a.jsxs)(s.default,{sx:{flex:1,minWidth:0},children:[(0,a.jsx)(c.A,{variant:"caption",sx:{display:"block",color:"primary.light",fontWeight:760,letterSpacing:".1em"},children:"AGENT RUNS"}),(0,a.jsx)(c.A,{variant:"h6",noWrap:!0,children:"Conversations"})]}),t.length>0&&(0,a.jsx)(u.A,{title:"Delete all conversations",children:(0,a.jsx)("span",{children:(0,a.jsx)(h.A,{size:"small",color:"error","aria-label":"Delete all conversations",onClick:()=>R({open:!0,ids:t.map(e=>e.id),label:"Delete all ".concat(t.length," conversation(s)?")}),children:(0,a.jsx)(ee.A,{fontSize:"small"})})})}),e_.length>0&&e_.length<t.length&&(0,a.jsx)(u.A,{title:"Delete visible conversations (matching current filter)",children:(0,a.jsx)("span",{children:(0,a.jsx)(h.A,{size:"small",color:"error","aria-label":"Delete visible conversations",onClick:()=>R({open:!0,ids:e_.map(e=>e.id),label:"Delete ".concat(e_.length," visible conversation(s)?")}),children:(0,a.jsx)(et.A,{fontSize:"small"})})})}),v&&(0,a.jsx)(u.A,{title:"Quick Chat: a model + optional connected apps, no saved agent",children:(0,a.jsx)(m.A,{variant:"outlined",color:"primary",startIcon:(0,a.jsx)(S.A,{}),onClick:v,size:"small",children:"Quick"})}),(0,a.jsx)(m.A,{variant:"contained",color:"primary",startIcon:(0,a.jsx)(J.A,{}),onClick:p,size:"small",children:"New"})]}),(0,a.jsx)(q.A,{}),(0,a.jsxs)(s.default,{sx:{px:1.5,pt:1.5,pb:1.2,display:"flex",flexDirection:"column",gap:1,bgcolor:T?(0,ey.X4)(C.palette.background.paper,.22):"rgba(127,127,160,.035)"},children:[(0,a.jsxs)(s.default,{sx:{display:"flex",gap:1},children:[(0,a.jsx)(g.A,{size:"small",sx:{flex:1},placeholder:"content"===F?"Search message content…":"Search title, origin or agent…",value:z,onChange:e=>M(e.target.value),InputProps:{startAdornment:(0,a.jsx)(L.A,{position:"start",children:(0,a.jsx)(Y.A,{fontSize:"small"})}),endAdornment:z?(0,a.jsx)(L.A,{position:"end",children:(0,a.jsx)(h.A,{size:"small","aria-label":"Clear search",onClick:()=>M(""),children:(0,a.jsx)(V.A,{fontSize:"small"})})}):void 0}}),(0,a.jsx)(U.A,{size:"small",sx:{minWidth:100},children:(0,a.jsxs)(H.A,{value:F,onChange:e=>P(e.target.value),"aria-label":"Search dimension",children:[(0,a.jsx)(B.A,{value:"title",children:"Title"}),(0,a.jsx)(B.A,{value:"content",children:"Content"})]})})]}),(0,a.jsxs)(s.default,{sx:{display:"flex",flexWrap:"wrap",gap:1},children:[(0,a.jsx)(U.A,{size:"small",sx:{minWidth:128,flex:"1 1 128px"},children:(0,a.jsx)(H.A,{value:eo,onChange:e=>er(e.target.value),"aria-label":"Group conversations",children:eE.map(e=>(0,a.jsx)(B.A,{value:e.value,children:e.label},e.value))})}),(0,a.jsx)(U.A,{size:"small",sx:{minWidth:128,flex:"1 1 128px"},children:(0,a.jsx)(H.A,{value:el,onChange:e=>ei(e.target.value),"aria-label":"Filter by status",children:eS.map(e=>(0,a.jsx)(B.A,{value:e.value,children:e.label},e.value))})}),(0,a.jsx)(U.A,{size:"small",sx:{minWidth:128,flex:"1 1 128px"},children:(0,a.jsxs)(H.A,{value:eO.some(e=>e.key===es)?es:"all",onChange:e=>ed(e.target.value),"aria-label":"Filter by agent",children:[(0,a.jsx)(B.A,{value:"all",children:"Any agent"}),eO.map(e=>(0,a.jsx)(B.A,{value:e.key,children:e.label},e.key))]})}),(0,a.jsx)(U.A,{size:"small",sx:{minWidth:128,flex:"1 1 128px"},children:(0,a.jsx)(H.A,{value:ew,onChange:e=>eA(e.target.value),"aria-label":"Filter by date",children:eC.map(e=>(0,a.jsx)(B.A,{value:e.value,children:e.label},e.value))})})]}),(z||eK>0)&&(0,a.jsxs)(s.default,{sx:{display:"flex",alignItems:"center",justifyContent:"space-between"},children:[(0,a.jsxs)(c.A,{variant:"caption",color:"text.secondary",children:[eJ," of ",eX]}),(0,a.jsx)(m.A,{size:"small",onClick:()=>{M(""),ei("all"),ed("all"),eA("all")},children:"Clear filters"})]})]}),(0,a.jsx)(q.A,{}),(0,a.jsx)(K.A,{"aria-label":"Conversations",sx:{overflow:"auto",flex:1,px:T?1.25:1,py:T?1.5:1,scrollbarGutter:"stable"},children:0===eX?(0,a.jsx)(O.Ay,{children:(0,a.jsx)(W.A,{primary:"No conversations yet",secondary:"Start a new conversation",primaryTypographyProps:{align:"center"},secondaryTypographyProps:{align:"center"}})}):0===eJ?(0,a.jsx)(O.Ay,{children:(0,a.jsx)(W.A,{primary:"No matching conversations",secondary:"Try a different search or filter",primaryTypographyProps:{align:"center"},secondaryTypographyProps:{align:"center"}})}):"chain"===eo?(0,a.jsx)(ev,{nodes:eq.roots,childrenByParent:eq.childrenByParent,renderItem:e=>eG(e),expanded:eL,onToggle:eH}):"none"===eo?e_.map(eG):eW.map(e=>{let t=!!eN[e.key],n="wave"===eo?eB.get(e.key):void 0;return(0,a.jsxs)(s.default,{children:[(0,a.jsxs)(_.A,{onClick:()=>(e=>{ez(t=>({...t,[e]:!t[e]}))})(e.key),sx:{py:.5,bgcolor:"action.hover"},children:[t?(0,a.jsx)(Z.A,{fontSize:"small"}):(0,a.jsx)($.A,{fontSize:"small"}),(0,a.jsx)(c.A,{variant:"overline",sx:{ml:.5,flex:1,lineHeight:1.6},noWrap:!0,children:e.label}),(0,a.jsx)(f.A,{label:e.items.length,size:"small",sx:{height:18,"& .MuiChip-label":{px:.75,fontSize:"0.7rem"}}})]}),(0,a.jsx)(G.A,{in:!t,timeout:"auto",unmountOnExit:!0,children:n?(0,a.jsx)(ev,{nodes:n.roots,childrenByParent:n.childrenByParent,renderItem:e=>eG(e),expanded:eL,onToggle:eH}):e.items.map(eG)})]},e.key)})}),(0,a.jsxs)(y.A,{open:D.open,onClose:()=>R(e=>({...e,open:!1})),"aria-labelledby":"bulk-delete-dialog-title",children:[(0,a.jsx)(b.A,{id:"bulk-delete-dialog-title",children:"Confirm deletion"}),(0,a.jsx)(w.A,{children:(0,a.jsxs)(A.A,{children:[D.label," This cannot be undone."]})}),(0,a.jsxs)(j.A,{children:[(0,a.jsx)(m.A,{onClick:()=>R(e=>({...e,open:!1})),children:"Cancel"}),(0,a.jsx)(m.A,{color:"error",onClick:async()=>{R(e=>({...e,open:!1})),await i(D.ids)},autoFocus:!0,children:"Delete"})]})]})]})});var ez=n(76750),eM=n(10915),eD=n(66177),eR=n(26188),eF=n(77073),eP=n(39486),eO=n(82446),e_=n(37596),eW=n(23731);function eq(e,t){return 1===e.length&&e.every(e=>{var n;let a=null!=(n=t[e])?n:[];return a.includes("pip")&&a.includes("fullscreen")})}let eL=e=>{let{conversationId:t,entries:n,activeKey:r,onSelectTab:l,onCloseTab:i,onAppMessage:d,onUpdateModelContext:p,onRegisterTeardown:g}=e,f=(0,k.A)(),[m,v]=(0,o.useState)(!1),[x,y]=(0,o.useState)(!1),[b,w]=(0,o.useState)({}),[A,j]=(0,o.useState)([]),I=(0,o.useMemo)(()=>new Set(n.map(e=>e.key)),[n]),S=(0,o.useMemo)(()=>A.filter(e=>I.has(e)),[A,I]),C=(0,o.useMemo)(()=>S.length>0?S:r?[r]:[],[S,r]),E=(0,o.useMemo)(()=>new Set(C),[C]),T=(0,o.useMemo)(()=>eq(C,b),[b,C]),N=Math.max(1,Math.ceil(Math.sqrt(C.length)));return((0,o.useEffect)(()=>{w(e=>{let t=Object.fromEntries(Object.entries(e).filter(e=>{let[t]=e;return I.has(t)}));return Object.keys(t).length===Object.keys(e).length?e:t})},[I]),(0,o.useEffect)(()=>{x&&!T&&y(!1)},[x,T]),0===n.length)?null:(0,a.jsxs)(s.default,{"data-testid":"dev-canvas-dock",sx:{borderTop:1,borderColor:"divider",bgcolor:"background.paper",display:"flex",flexDirection:"column",minHeight:0,...x?{position:"fixed",inset:16,zIndex:1300,borderRadius:1,boxShadow:6,border:1}:{maxHeight:"45vh"}},children:[(0,a.jsxs)(s.default,{sx:{display:"flex",alignItems:"center",gap:.5,px:1,py:.5,bgcolor:"action.hover"},children:[(0,a.jsx)(eR.A,{fontSize:"small",color:"primary"}),(0,a.jsx)(c.A,{variant:"caption",sx:{fontWeight:600,mr:1},children:"Canvas"}),(0,a.jsx)(s.default,{sx:{display:"flex",gap:.5,overflowX:"auto",flex:1,minWidth:0},children:n.map(e=>{let t=e.key===r,n=S.includes(e.key);return(0,a.jsxs)(s.default,{onClick:()=>(e=>{x&&!eq([e],b)&&y(!1),l(e)})(e.key),sx:{display:"flex",alignItems:"center",gap:.5,px:1,py:.25,borderRadius:1,cursor:"pointer",whiteSpace:"nowrap",border:1,borderColor:t?"primary.main":"divider",bgcolor:t?"action.selected":"transparent"},title:"".concat(e.serverName," — ").concat(e.uri),children:[(0,a.jsx)(eD.A,{color:"primary",variant:"dot",invisible:!e.unread,children:(0,a.jsx)(c.A,{variant:"caption",sx:{fontWeight:t?600:400},children:function(e){return e.replace(/\/+$/,"").split("/").pop()||e}(e.uri)})}),(0,a.jsx)(c.A,{variant:"caption",color:"text.secondary",sx:{fontSize:"0.65rem"},children:e.serverName}),(0,a.jsx)(u.A,{title:n?"Remove from split":"Add to split view",children:(0,a.jsx)(h.A,{size:"small",sx:{p:.25},color:n?"primary":"default",onClick:t=>{t.stopPropagation(),(e=>{x&&y(!1),j(t=>t.includes(e)?t.filter(t=>t!==e):[...t,e])})(e.key)},"aria-label":"Toggle split view",children:(0,a.jsx)(e_.A,{sx:{fontSize:14}})})}),(0,a.jsx)(u.A,{title:"Close",children:(0,a.jsx)(h.A,{size:"small",sx:{p:.25},onClick:t=>{t.stopPropagation(),i(e.key)},"aria-label":"Close canvas tab",children:(0,a.jsx)(eF.A,{sx:{fontSize:14}})})})]},e.key)})}),(0,a.jsx)(u.A,{title:x?"Exit fullscreen":T?"Fullscreen":"Every visible app must declare pip and fullscreen support",children:(0,a.jsx)("span",{children:(0,a.jsx)(h.A,{size:"small",disabled:!x&&!T,onClick:()=>y(e=>!e),"aria-label":"Toggle canvas fullscreen",children:x?(0,a.jsx)(eO.A,{fontSize:"small"}):(0,a.jsx)(eP.A,{fontSize:"small"})})})}),(0,a.jsx)(u.A,{title:m?"Expand canvas":"Collapse canvas",children:(0,a.jsx)(h.A,{size:"small",onClick:()=>{!m&&x&&y(!1),v(e=>!e)},"aria-label":"Toggle canvas collapse",children:m?(0,a.jsx)($.A,{fontSize:"small"}):(0,a.jsx)(Z.A,{fontSize:"small"})})})]}),(0,a.jsx)(s.default,{sx:{display:m?"none":"grid",position:"relative",gridTemplateColumns:"repeat(".concat(N,", minmax(0, 1fr))"),gap:1,p:1,flex:1,height:x?"auto":320,minHeight:0,overflow:"hidden"},children:n.map(e=>{var n;let o=!m&&E.has(e.key);return(0,a.jsx)(s.default,{sx:{display:"flex",...o?{position:"relative"}:{position:"absolute",inset:0,visibility:"hidden",pointerEvents:"none"},flexDirection:"column",minHeight:0,border:1,borderColor:"divider",borderRadius:1,overflow:"hidden",bgcolor:"dark"===f.palette.mode?"#111":"#fff"},children:(0,a.jsx)(eW.Ay,{docked:!0,visible:o,conversationId:t,serverName:e.serverName,uri:e.uri,toolName:e.toolName,toolArgs:e.latestToolArgs,toolResultContent:e.latestResultContent,toolCancelledReason:e.latestToolCancelledReason,toolIsError:e.latestToolIsError,toolUpdateId:null!=(n=e.latestToolUpdateId)?n:e.updatedAt,onAppMessage:d,onUpdateModelContext:p,hostDisplayMode:x&&o?"fullscreen":"pip",onAvailableDisplayModes:t=>{w(n=>{var a;let o=null!=(a=n[e.key])?a:[];return o.length===t.length&&o.every((e,n)=>e===t[n])?n:{...n,[e.key]:t}})},onRequestDisplayMode:(t,n)=>((e,t,n)=>{let a=x&&E.has(e)?"fullscreen":"pip";return t===a?a:"fullscreen"===t&&1===C.length&&C[0]===e&&n.includes("pip")&&n.includes("fullscreen")?(y(!0),"fullscreen"):"pip"===t&&"fullscreen"===a&&n.includes("pip")?(y(!1),"pip"):a})(e.key,t,n),onRequestClose:()=>i(e.key),onRegisterTeardown:(e,n)=>{null==g||g(t,e,n)}})},e.key)})})]})},eU={entries:{},order:[],activeKey:null};function eH(e,t){return"".concat(e,"::").concat(t)}function eB(e){let t=arguments.length>1&&void 0!==arguments[1]?arguments[1]:16,n=arguments.length>2?arguments[2]:void 0,a=Math.max(1,Math.floor(t));if(e.order.length<=a)return{state:e,evicted:[]};let o={...e.entries},r=[...e.order],l=[];for(;r.length>a;){let e=null,t=1/0;for(let a of r){var i,s;if(a===n)continue;let r=null!=(s=null==(i=o[a])?void 0:i.lastActiveAt)?s:0;r<t&&(t=r,e=a)}if(!e)break;delete o[e],r=r.filter(t=>t!==e),l.push(e)}let d=e.activeKey;return d&&!o[d]&&(d=r.length?r[r.length-1]:null),{state:{entries:o,order:r,activeKey:d},evicted:l}}function eK(e,t){var n,a,o,r,l;let i=arguments.length>2&&void 0!==arguments[2]?arguments[2]:Date.now(),s=arguments.length>3&&void 0!==arguments[3]?arguments[3]:16,d=null!=(n=t.instanceKey)?n:eH(t.serverName,t.uri),c=e.entries[d],u={key:d,serverName:t.serverName,uri:t.uri,toolName:null!=(a=t.toolName)?a:null==c?void 0:c.toolName,latestToolArgs:null!=(o=t.toolArgs)?o:null==c?void 0:c.latestToolArgs,latestResultContent:void 0!==t.cancelledReason?void 0:null!=(r=t.resultContent)?r:null==c?void 0:c.latestResultContent,latestToolCancelledReason:void 0!==t.cancelledReason?t.cancelledReason:void 0!==t.resultContent||null==c?void 0:c.latestToolCancelledReason,latestToolIsError:void 0!==t.cancelledReason?void 0:void 0!==t.isError?t.isError:void 0===t.resultContent&&(null==c?void 0:c.latestToolIsError),latestToolUpdateId:null!=(l=t.updateId)?l:null==c?void 0:c.latestToolUpdateId,unread:!1,lastActiveAt:i,updatedAt:i,consent:null==c?void 0:c.consent},h={...e.entries,[d]:u};return eB({entries:h,order:c?e.order:[...e.order,d],activeKey:d},s,d)}function eG(e,t){if(!e.entries[t])return e;let n={...e.entries};delete n[t];let a=e.order.filter(e=>e!==t),o=e.activeKey;if(o===t){o=null;let e=-1/0;for(let t of a){var r,l;let a=null!=(l=null==(r=n[t])?void 0:r.lastActiveAt)?l:0;a>=e&&(e=a,o=t)}}return{entries:n,order:a,activeKey:o}}function eX(e,t){var n;return null!=(n=e[t])?n:[]}function eJ(e,t){if(!(t in e))return e;let n={...e};return delete n[t],n}function eQ(e,t,n){let a=eX(e,t),o=a.filter(e=>e.id!==n);if(o.length===a.length)return e;let r={...e};return o.length>0?r[t]=o:delete r[t],r}var eY=n(4474),eV=n(25731),eZ=n(62617),e$=n(12857),e0=n(16186);let e1={byIndex:{}};function e2(e,t,n){for(let a=0;a<t;a++)e[a]||(e[a]={laneIndex:a,laneCount:t,label:"Lane ".concat(a+1,"/").concat(t),status:"pending",lastEventAt:n})}let e5=["the Moon’s night janitor","a time-traveling intern","three unionized pigeons","the neighborhood wizard","a deeply skeptical goldfish","the museum’s newest ghost","an off-duty oracle","the last honest pirate","a committee of raccoons","the office cryptozoologist","a surprisingly calm astronaut","the royal beekeeper","the lighthouse keeper’s cat","a detective from next Thursday","the village’s backup dragon","an accountant with a jetpack","the submarine’s etiquette officer","a retired supervillain","the expedition’s emotional-support goose","a knight from customer support","the train conductor’s imaginary friend","an archaeologist in slippers","the weather station’s resident crow","a philosopher who only answers in receipts"],e6=["the emergency moon ladder","a left sock with diplomatic immunity","the ceremonial stapler","an umbrella labeled “indoor use only”","the spare compass that points to lunch","a suspiciously warm snow globe","the department’s last clean teaspoon","a map of places that deny existing","the prototype self-folding napkin","a briefcase full of polite thunder","the antique Wi-Fi divining rod","a sandwich with its own legal counsel","the backup sun","a jar of premium silence","the haunted office printer","an extremely load-bearing baguette","the pocket-sized drawbridge","a key marked “probably not this one”","the inflatable anvil","a coupon for one free prophecy","the reversible telescope","a wheelbarrow of classified confetti","the world’s least decisive pendulum","a small but ambitious volcano"],e3=["the Moon’s lost-and-found","an underwater post office","the Bermuda Triangle gift shop","a castle with suspiciously good Wi-Fi","the attic behind the other attic","the North Pole’s complaint department","platform nine and three quarters-ish","the quiet end of a black hole","a library shelved by emotional intensity","the basement of the cloud","the international waters of the office kitchen","a forest currently pretending to be a spreadsheet","the volcano’s visitors’ center","the tiny door behind the grandfather clock","the republic of Lost Luggage","the observatory’s snack balcony","the castle moat’s shallow end","a desert with excellent room service","the museum of almost-correct inventions","the second-most-secret laboratory","the train station at the end of causality","the dragon’s fire-safety seminar","an island visible only on Tuesdays","the supply closet’s northern frontier"],e4=["one bent paperclip","a calibrated rubber chicken","the good magnifying glass","a teaspoon and unreasonable confidence","an abacus borrowed from the future","a laser pointer approved by three cats","the emergency accordion","a ruler that exaggerates slightly","a compass and a strongly worded memo","the laboratory’s ceremonial whisk","a pocket sundial","two magnets and an alibi","a wrench translated from the original Latin","the tiny hammer reserved for diplomacy","a roll of tape with tenure","an ethically sourced crystal ball","a slide rule haunted by fractions","the expedition’s backup kazoo","a spirit level with low self-esteem","the left-handed telescope","a clipboard of uncertain authority","four meters of emergency string","a borrowed weather vane","the instruction manual’s missing page"],e8=["fold a fitted sheet in four dimensions","whistle in a legally distinct key","parallel-park a gondola","alphabetize fog","moonwalk without disturbing the tides","forge a doctor’s note for a dragon","juggle increasingly theoretical objects","read the room’s source code","negotiate with an automatic door","brew tea at escape velocity","translate sarcasm into semaphore","win an argument with a sundial","smuggle daylight through customs","assemble furniture from the prophecy alone","tell north from suspiciously north","interview a witness who has not happened yet","balance a budget on a unicycle","write cursive in zero gravity","herd cats across a loading screen","perform first aid on a metaphor","land a paper airplane in international waters","make small talk with the abyss","reverse politely out of a time loop","explain taxes to a medieval peasant"],e7=["why the Moon has a service entrance","who keeps moving Wednesday","whether gravity has read the terms and conditions","where all the matching socks defected to","why the office plant knows Morse code","who put the echo on speakerphone","whether pigeons are billing by the hour","why the horizon looks freshly painted","where the staircase goes on its lunch break","who authorized a sequel to Tuesday","why the compass keeps pointing at Gary","whether the sea is just extremely committed soup","who taught the photocopier dramatic timing","why the future keeps returning our mail","where the extra five minutes came from","whether the castle is zoned for hauntings","why the treasure map has restaurant reviews","who keeps feeding the plot holes","whether the stars are alphabetized from the other side","why the elevator sighs at floor seven","where the thunder stores its receipts","who scheduled the eclipse during lunch","whether the mirror is freelancing","why the emergency exit leads to 1843"],e9=["gravity is only a strongly held opinion","Tuesday can be postponed with enough paperwork","the Moon is mostly decorative","every maze has a customer-service desk","time flies because walking was over budget","the ocean is hiding a second, smaller ocean","all ravens share one extremely busy lawyer","history is written by whoever found a pen","the shortest distance between two points is under renovation","a watched kettle merely becomes self-conscious","clouds are mountains with commitment issues","the floor is lava only during business hours","silence is just sound wearing formal clothes","mirrors are windows with excellent boundaries","the map is avoiding the territory","luck is outsourced coincidence","every locked door is a wall with ambitions","the early bird is covering somebody else’s shift","facts travel faster when carrying gossip","all prophecies are drafts until approved","the Sun is running a very long free trial","common sense is currently in beta","the past has an aggressive returns policy","reality rounds up at checkout"],te=["a receipt dated next Thursday","three footprints leading into a wall","a pie chart drawn by an actual pie","the testimony of a very nervous hat","an alibi written in disappearing ink","a voicemail from the Bronze Age","one feather wearing a visitor badge","a map that blushes near the border","the minutes from tomorrow’s meeting","a shadow with the wrong forwarding address","four identical keys and no visible lock","an eyewitness account from the mirror","a weather forecast for indoors","the fingerprints of someone wearing oven mitts","a bookmark found at the scene","an invoice for seven metric mysteries","a trail of increasingly formal breadcrumbs","security footage filmed in watercolor","the sworn statement of a garden gnome","an ominous but properly formatted spreadsheet","a compass pointing firmly at the suspect","the original napkin calculations","a tiny parachute with no registered owner","a note saying “this is not a clue”"],tt=["the minutes from a meeting that never occurred","a permit to operate one moonbeam","the dragon’s expense report","an apology addressed to the concept of distance","the unabridged history of the lunch queue","a warranty for the laws of physics","the lighthouse’s performance review","a cease-and-desist from the future","the treasure map’s privacy policy","the official taxonomy of awkward silences","a user manual for d\xe9j\xe0 vu","the penguins’ collective-bargaining agreement","a strongly footnoted ghost story","the castle’s annual moat survey","an incident report filed by the incident","the instruction manual for Wednesday","a peer-reviewed shopping list","the classified appendix to the phone book","a risk assessment for opening this risk assessment","the prophecy’s change log","the submarine’s upstairs floor plan","a passport issued to an idea","the weather’s written explanation","the terms of service for coincidence"],tn=["a strongly worded puppet show","interpretive semaphore","a twelve-slide cave painting","an opera for one nervous kazoo","a legally binding limerick","a pop-up spreadsheet","a detective novel with only footnotes","a weather forecast performed by spoons","an annotated treasure map","a silent film with aggressive subtitles","a bar chart made of actual bars","a medieval group chat","a three-act voicemail","a tasteful arrangement of warning cones","a sonnet with technical diagrams","an escape room for accountants","a very small parade","a recipe with courtroom sketches","a flowchart that knows too much","a constellation visible from the break room","a memo delivered by trebuchet","a musical number in the original binary","an emotionally available pie chart","a documentary narrated by the suspect"],ta=["the annual eclipse rehearsal","the emergency tea ceremony","a surprise inspection of gravity","the interdepartmental moon landing","the ceremonial changing of the Wi-Fi password","the grand reopening of yesterday","the regional hide-and-seek finals","a fire drill for the underwater office","the quarterly meeting of anonymous time travelers","the lighthouse’s indoor picnic","the official launch of the backup plan","a retirement party for the old horizon","the expedition’s mandatory talent show","the castle’s bring-your-own-ghost night","the first annual coincidence convention","the unveiling of the smaller Big Ben","the neighborhood’s silent alarm concert","a ribbon-cutting for the infinite corridor","the volcano’s open-house afternoon","the rehearsal dinner for breakfast","the maritime spelling bee","the museum’s live demonstration of ancient Wi-Fi","the parade of plausible deniability","the surprise audit of the surprise party"],to=["the fire inspector walks in holding burnt toast","the inventor arrives to deny inventing it","the one person mentioned in the footnote calls","the lights flicker in perfect Morse code","tomorrow phones to ask for its receipt back","the missing witness emerges from the coat rack","the smoke alarm chooses that moment to pass its exam","the prophecy is delivered with the groceries","every clock in the building clears its throat","the emergency drill becomes unexpectedly relevant","a lawyer for the squirrels requests a sidebar","the Moon sends a calendar invitation","the “decorative” lever begins counting down","the alibi walks past the window wearing sunglasses","a second, identical meeting starts next door","the backup plan asks to speak privately","the weather apologizes and does it anyway","the map adds a tiny “you are kidding” marker","someone finds the exact missing page under the manual","the coincidence department closes for coincidence","the only adult in the room turns out to be the goose","the supposedly empty box starts taking minutes","a comet arrives several centuries early for the appointment","the narrator is asked to leave the premises"],tr=["the paperwork remains cautiously optimistic","the control group demands a sequel","nobody makes eye contact with the lever","the hypothesis requests legal representation","lunch is promoted to a critical dependency","the committee calls it “mostly reproducible”","the nearest calendar quietly resigns","three historians ask for a clean take","the manual insists this is the expected behavior","morale improves for completely unrelated reasons","the graph develops a concerning subplot","the witness changes species mid-statement","the budget gains a mysterious weather category","the experiment is renewed for another season","the floor plan adds an escape clause","the results are peer-reviewed by nearby ducks","management upgrades the problem to a tradition","the emergency confetti is deployed","the timeline asks everyone to stop touching it","the incident receives a commemorative plaque","the laws of physics issue a narrow exemption","the applause is traced to an empty cupboard","the conclusion is sent back for better handwriting","the universe marks the ticket as resolved"],tl=["without waking the timeline","before the alibi expires","using the scenic laws of physics","without involving a second moon","while remaining technically indoors","before the committee discovers the first attempt","under strict accordion silence","with no more than one ceremonial explosion","without voiding the prophecy","while the adults are distracted by the goose","before Tuesday notices","without making the map self-conscious","under maritime library rules","before gravity’s lunch break","using only locally sourced coincidences","without alerting the Department of Foreshadowing","while the clocks are looking elsewhere","before the warranty becomes sentient","under an assumed constellation","without exceeding the recommended number of ravens","during a brief lapse in causality","before anyone reads the label","while maintaining plausible choreography","in accordance with ancient snack protocol"],ti=["cups of existential dread","nautical eyebrows","metric rumors","decibels of side-eye","standardized moonbeams","imperial breadcrumbs","handfuls per fortnight","degrees of unnecessary suspense","liters of plausible deniability","horsepower per pigeon","compressed Tuesdays","average-sized astonishments","knots of awkward silence","parcels per prophecy","spoons of gravitational intent","pages per dragon","microfortnights","bells per invisible bicycle","cubits of Wi-Fi","watts of mild concern","fathoms of paperwork","bananas for scale","chronological teaspoons","certified vibes"],ts=["historically damp","emotionally load-bearing","ceremonially reversible","unexpectedly bilingual","legally moon-adjacent","structurally optimistic","haunted within tolerance","approximately royal","suspiciously aerodynamic","peer-reviewed by geese","waterproof on paper","chronologically freelance","ethically invisible","medieval after taxes","quantum but house-trained","officially unofficial","north-facing in spirit","dramatically underqualified","mostly harmless before noon","weather-resistant emotionally","licensed for indoor thunder","alphabetically waterproof","locally impossible","upside-down compatible"],td=(e,t)=>({count:e.reduce((e,t)=>e*t.length,1),render:n=>{let a=n,o=e.map(e=>{let t=e[a%e.length];return a=Math.floor(a/e.length),t});return"".concat(t(...o),"…")}}),tc=["Landing on the Moon before breakfast and discovering the caf\xe9 is cash-only","Discovering magnetism when the fridge refuses to return the shopping list","Inventing time travel five minutes after the patent office closes","Finding the missing sock serving as ambassador to the laundry basket","Testing the smoke alarm precisely as the fire inspector burns the toast","Following the treasure map to the cartographer’s surprise birthday party","Proving ghosts exist while trying to dispute the attic’s utility bill","Calling tech support and reaching the knight who installed the original drawbridge","Opening the emergency umbrella during the building’s first indoor rainstorm","Learning semaphore just as everyone else switches to carrier pigeons","Repairing the time machine with a part delivered tomorrow morning","Locating the fountain of youth behind the retirement home’s vending machine","Winning hide-and-seek after accidentally entering a parallel dimension","Photographing Bigfoot while he photographs an even bigger foot","Explaining gravity to an apple moments before it files a complaint","Missing the train to punctuality because it departed early","Returning a library book about procrastination exactly forty years late","Discovering Atlantis after taking the wrong exit from the aquarium","Meeting the inventor of awkward silence in a stalled elevator","Finding north after the compass asks a nearby goose for directions","Solving the cold case when the evidence requests a warmer office","Interviewing the future and learning it has not prepared either","Reaching the end of the rainbow during a paint shortage","Unmasking the phantom at the annual mask-inspection conference","Teaching a goldfish algebra on the exact day it remembers everything","Filing the weather report while a small cloud edits over one shoulder","Finding a needle in the haystack and discovering it runs the lost-and-found","Escaping the maze through its employee entrance during orientation","Asking the oracle for directions and being handed the same broken compass","Crossing the international date line and forgetting to declare yesterday","Calling a meeting about unnecessary meetings; the duplicate invite arrives immediately","Measuring twice and discovering the ruler has been exaggerating for years","Auditing the Bermuda Triangle when all three corners submit different receipts","Looking for intelligent life while the office printer watches in silence","Inventing the self-opening door just as the cat learns to operate handles","Rehearsing the fire drill while the volcano requests a visitor badge","Tracing an anonymous tip back to the detective’s own future voicemail","Breaking the sound barrier during the library’s mandatory quiet hour","Finding buried treasure beneath the “no digging” sign installer’s lunchbox","Mapping an imaginary island until it sends a correction to the coastline","Launching a paper airplane and receiving an international arrival notice","Discovering the shortcut is maintained by the scenic-route committee","Calling the coincidence hotline at the exact moment it calls back","Taking a rain check and accidentally triggering a bank fraud investigation","Turning over a new leaf and finding the old one has a forwarding address","Reading the room just as it publishes an amended edition","Checking under the bed while the monster checks the closet for humans","Finding the skeleton key attending a locksmith convention under an alias","Observing a moment of silence until the moment asks for another minute","Following the chain of command to a very authoritative bicycle lock","Testing the emergency exit and stepping into the building’s grand opening","Discovering perpetual motion while chasing the office chair downhill","Asking for a sign and receiving a municipal permit application","Looking on the bright side until it requests protective eyewear","Running out of thyme while the time machine idles beside the herb garden","Finding common ground at the property line between two feuding surveyors","Reaching a fork in the road during the cutlery delivery strike","Preparing for the unexpected and accidentally spoiling its surprise party","Following protocol until it ducks into an alley and changes hats","Closing the loop just as the loop files to remain open","Checking the fine print with a microscope borrowed from the contract lawyer","Discovering the elephant in the room has been chairing the meeting remotely","Trying to think outside the box while the box conducts an exit interview","Taking the path of least resistance directly into an electrical inspection","Asking what could possibly go wrong and receiving a numbered agenda","Putting two and two together during the mathematicians’ separation hearing","Getting cold feet beside the penguin expedition’s heated boot rack","Searching for a silver lining in the cloud’s lost-property envelope","Calling it a day only for Thursday to answer","Reading between the lines and meeting the editor hiding there","Holding all the cards when the magician reports a deck shortage","Waiting for the dust to settle while it negotiates a longer lease","Moving heaven and earth during the celestial zoning board’s lunch break","Finding the last straw employed as the camel’s risk assessor","Keeping an eye on the clock until it asks about the other eye","Getting the ball rolling moments before the hill-inspection team arrives","Opening a can of worms at the fisheries department’s potluck","Burning the midnight oil when the night-shift fire marshal knocks","Leaving no stone unturned except the one running the geology seminar","Pulling strings at the marionette ethics hearing by pure coincidence","Barking up the wrong tree while the correct tree quietly changes parks","Stealing someone’s thunder and finding their name engraved on the lightning","Going back to square one just as it is rezoned as a triangle","Finding a loophole occupied by a very small zoning attorney","Putting the cart before the horse during autonomous-vehicle testing","Letting the cat out of the bag at the luggage-security briefing","Watching history repeat itself because nobody saved the first draft","Meeting opportunity after it knocks on the neighboring timeline","Following a gut feeling to the gastroenterologists’ navigation workshop","Taking matters into our own hands and discovering they require gloves","Making ends meet at the annual rope-makers’ networking breakfast","Hitting the nail on the head during the helmet certification test","Going the extra mile and finding it already claimed by the marathon","Getting ducks in a row moments before the parade switches to geese","Changing horses midstream during the bridge inspector’s coffee break","Finding the writing on the wall listed as a protected historical document","Throwing caution to the wind just as the wind’s lawyer arrives"],tu=["the paperwork had somehow arrived first","nobody mentions this was on the agenda","the witness calls it an unrelated miracle","the calendar claims prior knowledge","the nearest goose looks vindicated","three departments take simultaneous credit","the instruction manual skips this chapter","the timing is described as “within tolerance”","the control group applauds from inside a cupboard","the universe denies coordinating anything","the coincidence officer asks for a quieter coincidence","the footnote is promoted to headline","the backup plan quietly changes its name","the map pretends not to recognize the location","the forecast insists this is seasonal","the legal team requests the extended version","the clock refuses to corroborate","the prophecy asks not to be dragged into this","the entire incident fits suspiciously well on the form","the narrator checks the script twice","the odds department closes early","the alibi develops excellent comic timing","history marks the event as “needs review”","lunch proceeds under heightened security"],th=[td([e6,e4,e3,tl],(e,t,n,a)=>"Calibrating ".concat(e," in ").concat(n," using ").concat(t,", ").concat(a)),td([e5,e8,ta,tr],(e,t,n,a)=>"Teaching ".concat(e," to ").concat(t," for ").concat(n,"; ").concat(a)),td([e7,te,e4,e3],(e,t,n,a)=>"Investigating ".concat(e," using ").concat(t," and ").concat(n," beneath ").concat(a)),td([tt,e5,tn,tl],(e,t,n,a)=>"Rewriting ".concat(e," for ").concat(t," as ").concat(n,", ").concat(a)),td([e6,e5,e6,tr],(e,t,n,a)=>"Negotiating ".concat(e," away from ").concat(t," in exchange for ").concat(n,"; ").concat(a)),td([tt,tn,e9,e5],(e,t,n,a)=>"Translating ".concat(e," into ").concat(t," for ").concat(a,", on the theory that ").concat(n)),td([e9,e3,e4,tr],(e,t,n,a)=>"Testing whether ".concat(e," inside ").concat(t," with ").concat(n,"; ").concat(a)),td([e6,e3,e5,to],(e,t,n,a)=>"Searching ".concat(t," for ").concat(e," alongside ").concat(n,", just as ").concat(a)),td([e5,e8,to,tr],(e,t,n,a)=>"Asking ".concat(e," to ").concat(t,"; ").concat(n,", and ").concat(a)),td([e6,e3,e9,tl],(e,t,n,a)=>"Launching ".concat(e," toward ").concat(t,", powered entirely by the belief that ").concat(n,", ").concat(a)),td([e3,e6,te,to],(e,t,n,a)=>"Auditing ".concat(e," for signs of ").concat(t,"; finding ").concat(n," precisely when ").concat(a)),td([e6,e6,ti,tr],(e,t,n,a)=>"Comparing ".concat(e," with ").concat(t," in ").concat(n,"; ").concat(a)),td([e5,e9,te,tn],(e,t,n,a)=>"Persuading ".concat(e," that ").concat(t," using ").concat(n," presented as ").concat(a)),td([e6,e3,e5,to],(e,t,n,a)=>"Quietly hiding ".concat(e," inside ").concat(t," moments before ").concat(n," arrives and ").concat(a)),td([e8,ta,e5,to],(e,t,n,a)=>"Rehearsing how to ".concat(e," for ").concat(t," with ").concat(n,", until ").concat(a)),td([e6,ts,ti,tr],(e,t,n,a)=>"Cataloguing ".concat(e," as ").concat(t,", measured in ").concat(n,"; ").concat(a)),td([e6,te,e4,e9],(e,t,n,a)=>"Reverse-engineering ".concat(e," from ").concat(t," with ").concat(n,", assuming ").concat(a)),td([e6,e3,e4,tl],(e,t,n,a)=>"Installing ".concat(e," at ").concat(t," with ").concat(n,", ").concat(a)),td([te,e3,e3,e5],(e,t,n,a)=>"Following ".concat(e," from ").concat(t," to ").concat(n,", where ").concat(a," has been waiting politely")),td([e6,e5,tt,tr],(e,t,n,a)=>"Preparing ".concat(e," for ").concat(t," according to ").concat(n,"; ").concat(a)),td([e7,e8,to,e5],(e,t,n,a)=>"Discovering ".concat(e," while trying to ").concat(t,"; ").concat(n,", and ").concat(a," calls it beginner’s luck")),td([e5,e9,to,te],(e,t,n,a)=>"The exact moment ".concat(e," announces that ").concat(t,", ").concat(n,"; nearby, ").concat(a," suddenly looks relevant")),td([e6,e3,ta,to],(e,t,n,a)=>"Returning ".concat(e," to ").concat(t," on the day of ").concat(n,", just as ").concat(a)),td([e6,to,tr,tl],(e,t,n,a)=>"Testing ".concat(e," precisely when ").concat(t,"; ").concat(n,", ").concat(a)),td([e3,ta,e5,e6],(e,t,n,a)=>"Booking ".concat(e," for ").concat(t,", unaware that ").concat(n," has already reserved it for ").concat(a)),td([e6,e3,e5,tt],(e,t,n,a)=>"Finally finding ".concat(e," in ").concat(t,", one minute after ").concat(n," files ").concat(a)),td([ta,e8,e5,tr],(e,t,n,a)=>"Trying to avoid ".concat(e,"; accidentally learning to ").concat(t,", which ").concat(n," records as a success; ").concat(a)),td([e5,e7,to,tn],(e,t,n,a)=>"Calling ".concat(e," about ").concat(t," while ").concat(n,"; explaining it all through ").concat(a)),td([e9,to,e5,tr],(e,t,n,a)=>"Promising everyone that ".concat(e," seconds before ").concat(t,"; ").concat(n," takes notes and ").concat(a)),td([te,e3,e5,e6],(e,t,n,a)=>"Following ".concat(e," to ").concat(t,", where ").concat(n," happens to be returning ").concat(a)),td([ta,to,tt,tr],(e,t,n,a)=>"Scheduling ".concat(e," around the moment ").concat(t,"; ").concat(n," says this was inevitable, and ").concat(a)),td([e5,e6,e3,to],(e,t,n,a)=>"Watching ".concat(e," carry ").concat(t," into ").concat(n,", just as ").concat(a)),td([e7,tt,e5,tr],(e,t,n,a)=>"Cross-referencing ".concat(e," against ").concat(t," with ").concat(n,"; ").concat(a)),td([e3,ti,e4,ts],(e,t,n,a)=>"Surveying ".concat(e," in ").concat(t," with ").concat(n,"; initial findings are ").concat(a)),td([e5,ta,tn,tl],(e,t,n,a)=>"Briefing ".concat(e," on ").concat(t," through ").concat(n,", ").concat(a)),td([e6,tt,te,tr],(e,t,n,a)=>"Fact-checking ".concat(e," against ").concat(t," and ").concat(n,"; ").concat(a)),td([e3,e9,to,tl],(e,t,n,a)=>"Mapping ".concat(e," under the assumption that ").concat(t,"; ").concat(n,", ").concat(a)),td([e5,e6,e4,ts],(e,t,n,a)=>"Helping ".concat(e," untangle ").concat(t," with ").concat(n,"; the knot is reportedly ").concat(a)),td([ta,tt,tn,tr],(e,t,n,a)=>"Documenting ".concat(e," in ").concat(t," as ").concat(n,"; ").concat(a)),td([e8,e4,ti,tl],(e,t,n,a)=>"Attempting to ".concat(e," with ").concat(t,", budgeting exactly seven ").concat(n,", ").concat(a)),...Array.from({length:8},(e,t)=>td([tc.filter((e,n)=>n%8===t),tu],(e,t)=>"".concat(e,"; ").concat(t)))];th.reduce((e,t)=>e+t.count,0);let tp=(e,t)=>{let n=Math.abs(e),a=Math.abs(t);for(;0!==a;)[n,a]=[a,n%a];return n},tg=e=>{let t=0|e;return((t=Math.imul((t=Math.imul(t^t>>>16,0x21f0aaad))^t>>>15,0x735a2d97))^t>>>15)>>>0},tf=(e,t)=>{let n=tg(t)%(e-1)+1;for(;1!==tp(n,e);)n=n%(e-1)+1;return n},tm=e=>{let{lane:t,onOpenLane:n}=e,o=!!t.laneConversationId&&!!n,r="pending"===t.status;return(0,a.jsxs)(s.default,{onClick:o?()=>n(t.laneConversationId):void 0,sx:{display:"flex",alignItems:"center",gap:1,px:1,py:.25,borderRadius:1,...o&&{cursor:"pointer","&:hover":{bgcolor:"action.hover",textDecoration:"underline"}}},children:["running"===t.status&&(0,a.jsx)(eY.default,{size:14,sx:{flexShrink:0}}),"completed"===t.status&&(0,a.jsx)(E.A,{sx:{fontSize:16,flexShrink:0},color:"success"}),"error"===t.status&&(0,a.jsx)(e$.A,{sx:{fontSize:16,flexShrink:0},color:"error"}),r&&(0,a.jsx)(e0.A,{sx:{fontSize:16,flexShrink:0},color:"disabled"}),(0,a.jsxs)(c.A,{variant:"caption",color:r?"text.disabled":"textSecondary",sx:{overflow:"hidden",textOverflow:"ellipsis",whiteSpace:"nowrap"},children:[t.label,r&&" — queued","running"===t.status&&t.activity&&(0,a.jsxs)(c.A,{component:"span",variant:"caption",color:"text.disabled",children:[" \xb7 ",t.activity]})]})]})},tv=e=>{var t,n;let{liveStats:r,onStop:l,stopDisabled:i,awaitingApproval:d,lanes:u,onOpenLane:h,onAttachDebugger:p}=e,[g,f]=(0,o.useState)(()=>Date.now()),[v]=(0,o.useState)(()=>Date.now()),[x,y]=(0,o.useState)(!1);(0,o.useEffect)(()=>{let e=setInterval(()=>f(Date.now()),1e3);return()=>clearInterval(e)},[]);let b=r?Math.max(0,Math.round((g-r.startedAt)/1e3)):0,w=r?Math.round((g-r.lastEventAt)/1e3):0,A=!d&&!!r&&w>=60,j=null!=(t=null==r?void 0:r.startedAt)?t:v,k=((e,t)=>{let n=Math.max(0,Math.floor(e)),a=Math.floor(t),o=th.length,r=(tg(a)%o+n*tf(o,0x6d2b79f5^a))%o,l=th[r],i=Math.floor(n/o),s=(tg(a^Math.imul(r+1,0x9e3779b1))%l.count+i*tf(l.count,a^Math.imul(r+1,0x85ebca6b)))%l.count;return l.render(s)})(Math.floor(Math.max(0,g-j)/1e4),j),I=u?Object.values(u.byIndex).sort((e,t)=>e.laneIndex-t.laneIndex):[],S=I.length>0?(e=>{let t=e.filter(e=>"running"===e.status).length,n=e.filter(e=>"pending"===e.status).length,a=e.filter(e=>"completed"===e.status).length,o=e.filter(e=>"error"===e.status).length;if(0===t&&0===n&&o>0)return{text:"".concat(o,"/").concat(e.length," lanes failed — partial results"),warning:!0};let r=[t>0?"".concat(t," running"):"",n>0?"".concat(n," queued"):"",a>0?"".concat(a," done"):"",o>0?"".concat(o," failed"):""].filter(Boolean);return{text:"".concat(e.length," lanes — ").concat(r.join(", ")),warning:o>0}})(I):null;return(0,a.jsxs)(s.default,{sx:{display:"flex",flexDirection:"column",alignItems:"center",my:2,gap:.5},children:[(0,a.jsxs)(s.default,{sx:{display:"flex",alignItems:"center",gap:2},children:[d?(0,a.jsx)(eV.A,{fontSize:"small",color:"warning"}):(0,a.jsx)(eY.default,{size:20,color:A?"warning":"primary"}),(0,a.jsx)(c.A,{variant:"body2",color:"textSecondary",children:d?"Waiting for tool approval":(null==r?void 0:r.activeNode)?"Running: ".concat(r.activeNode):"Working…"}),p&&!d&&(0,a.jsx)(m.A,{variant:"outlined",color:"primary",size:"small",startIcon:(0,a.jsx)(eZ.A,{fontSize:"small"}),onClick:()=>{y(!0),p()},disabled:x,children:x?"Attaching…":"Attach debugger"}),(0,a.jsx)(m.A,{variant:"outlined",color:"secondary",size:"small",onClick:l,disabled:i,children:"Stop"})]}),!d&&(0,a.jsx)(c.A,{variant:"caption",color:"text.disabled",sx:{fontStyle:"italic"},"aria-live":"polite",children:k}),S&&(0,a.jsxs)(s.default,{sx:{display:"flex",flexDirection:"column",alignItems:"stretch",minWidth:280,maxWidth:520},children:[(0,a.jsx)(c.A,{variant:"caption",color:S.warning?"warning.main":"textSecondary",sx:{px:1,fontWeight:500},children:S.text}),I.map(e=>(0,a.jsx)(tm,{lane:e,onOpenLane:h},e.laneIndex))]}),!d&&(0,a.jsxs)(c.A,{variant:"caption",color:A?"warning.main":"textSecondary",children:[(null!=(n=null==r?void 0:r.totalTokens)?n:0).toLocaleString()," tokens \xb7 ",b,"s elapsed",A?" \xb7 no activity for ".concat(w,"s — may be stuck"):""]})]})};var tx=n(2300),ty=n(52005),tb=n(54121);let tw=e=>{let{todos:t}=e;if(!t||0===t.length)return null;let n=t.filter(e=>"done"===e.status).length,o=t.length>0?Math.round(n/t.length*100):0;return(0,a.jsxs)(tx.A,{variant:"outlined",sx:{mt:2,p:1.5,borderRadius:2},children:[(0,a.jsxs)(s.default,{sx:{display:"flex",alignItems:"center",justifyContent:"space-between",mb:1},children:[(0,a.jsx)(c.A,{variant:"subtitle2",sx:{fontWeight:600},children:"Tasks"}),(0,a.jsxs)(c.A,{variant:"caption",color:"text.secondary",children:[n," of ",t.length," done"]})]}),(0,a.jsx)(ty.A,{variant:"determinate",value:o,sx:{mb:1,borderRadius:1}}),(0,a.jsx)(s.default,{component:"ul",sx:{listStyle:"none",m:0,p:0},children:t.map(e=>(0,a.jsxs)(s.default,{component:"li",sx:{display:"flex",alignItems:"center",gap:1,py:.25},children:[function(e){switch(e){case"done":return(0,a.jsx)(E.A,{fontSize:"small",color:"success"});case"in_progress":return(0,a.jsx)(tb.A,{fontSize:"small",color:"info"});case"cancelled":return(0,a.jsx)(e$.A,{fontSize:"small",color:"disabled"});default:return(0,a.jsx)(e0.A,{fontSize:"small",color:"disabled"})}}(e.status),(0,a.jsx)(c.A,{variant:"body2",sx:{textDecoration:"done"===e.status||"cancelled"===e.status?"line-through":"none",color:"done"===e.status||"cancelled"===e.status?"text.secondary":"text.primary"},children:e.content})]},e.id))})]})};var tA=n(88538),tj=n(16963),tk=n(2456),tI=n(64792),tS=n(71356),tC=n(45202),tE=n(77998);let tT=e=>e>=1e3?"".concat((e/1e3).toFixed(e>=1e5?0:1),"k"):"".concat(e),tN=e=>{var t;let{usage:n,contextInfo:r,availableNodes:l}=e,[i,d]=(0,o.useState)(null);if(!n&&!r)return null;let h=(null==n?void 0:n.byNode)?Object.entries(n.byNode):[],p=null!=(t=null==n?void 0:n.cacheReadTokens)?t:0,g=n?Math.max(0,n.promptTokens-p):0,m=n?Math.max(0,n.totalTokens-p):0,v=(null==r?void 0:r.contextWindow)&&r.contextWindow>0?Math.min(100,Math.round(r.promptTokens/r.contextWindow*100)):void 0;return(0,a.jsxs)(s.default,{sx:{display:"flex",alignItems:"center",gap:1.5,flexShrink:0},children:[n&&m>0&&(0,a.jsxs)(a.Fragment,{children:[(0,a.jsx)(u.A,{title:"Tokens this conversation — ".concat(g.toLocaleString()," prompt / ").concat(n.completionTokens.toLocaleString()," completion").concat(p>0?" (+".concat(p.toLocaleString()," cached reads, not counted)"):"",". Click for the per-node breakdown."),children:(0,a.jsx)(f.A,{icon:(0,a.jsx)(tE.A,{}),label:"".concat(tT(m)," tokens"),size:"small",variant:"outlined",onClick:e=>d(e.currentTarget),sx:{cursor:"pointer"}})}),(0,a.jsx)(tA.Ay,{open:!!i,anchorEl:i,onClose:()=>d(null),anchorOrigin:{vertical:"bottom",horizontal:"right"},transformOrigin:{vertical:"top",horizontal:"right"},children:(0,a.jsxs)(s.default,{sx:{p:2,maxWidth:420},children:[(0,a.jsx)(c.A,{variant:"subtitle2",sx:{mb:1},children:"Token usage by node"}),(0,a.jsxs)(tj.A,{size:"small",children:[(0,a.jsx)(tk.A,{children:(0,a.jsxs)(tI.A,{children:[(0,a.jsx)(tS.A,{children:"Node"}),(0,a.jsx)(tS.A,{align:"right",children:"Prompt"}),(0,a.jsx)(tS.A,{align:"right",children:"Completion"}),(0,a.jsx)(tS.A,{align:"right",children:"Total"})]})}),(0,a.jsxs)(tC.A,{children:[h.map(e=>{let[t,n]=e;return(0,a.jsxs)(tI.A,{children:[(0,a.jsx)(tS.A,{children:(0,a.jsx)(u.A,{title:t,children:(0,a.jsx)("span",{children:(e=>{var t;return(null==(t=l.find(t=>t.id===e))?void 0:t.label)||"".concat(e.substring(0,8),"…")})(t)})})}),(0,a.jsx)(tS.A,{align:"right",children:n.promptTokens.toLocaleString()}),(0,a.jsx)(tS.A,{align:"right",children:n.completionTokens.toLocaleString()}),(0,a.jsx)(tS.A,{align:"right",children:n.totalTokens.toLocaleString()})]},t)}),(0,a.jsxs)(tI.A,{children:[(0,a.jsx)(tS.A,{sx:{fontWeight:"bold"},children:"Total"}),(0,a.jsx)(tS.A,{align:"right",sx:{fontWeight:"bold"},children:n.promptTokens.toLocaleString()}),(0,a.jsx)(tS.A,{align:"right",sx:{fontWeight:"bold"},children:n.completionTokens.toLocaleString()}),(0,a.jsx)(tS.A,{align:"right",sx:{fontWeight:"bold"},children:n.totalTokens.toLocaleString()})]})]})]}),p>0&&(0,a.jsxs)(c.A,{variant:"caption",color:"text.secondary",sx:{display:"block",mt:1},children:["Prompt totals include ",p.toLocaleString()," tokens re-read from the prompt cache. The header chip shows the fresh figure (",m.toLocaleString(),") with those cached reads excluded."]})]})})]}),r&&void 0!==v&&(0,a.jsx)(u.A,{title:"Context of the latest call".concat(r.modelDisplayName?" (".concat(r.modelDisplayName,")"):"",": ").concat(r.promptTokens.toLocaleString()," of ").concat(r.contextWindow.toLocaleString()," tokens"),children:(0,a.jsxs)(s.default,{sx:{display:"flex",alignItems:"center",gap:1,minWidth:140},children:[(0,a.jsx)(ty.A,{variant:"determinate",value:v,color:v>=90?"error":v>=70?"warning":"primary",sx:{flex:1,height:6,borderRadius:3}}),(0,a.jsxs)(c.A,{variant:"caption",color:"text.secondary",sx:{whiteSpace:"nowrap"},children:[tT(r.promptTokens),"/",tT(r.contextWindow)," (",v,"%)"]})]})}),r&&void 0===v&&(0,a.jsx)(u.A,{title:"Prompt size of the latest call".concat(r.modelDisplayName?" (".concat(r.modelDisplayName,")"):"",". Set the model's Context Window in its settings to see a usage meter."),children:(0,a.jsxs)(c.A,{variant:"caption",color:"text.secondary",sx:{whiteSpace:"nowrap"},children:["ctx ",tT(r.promptTokens)]})})]})};var tz=n(75870),tM=n(95436),tD=n(99944),tR=n(22822),tF=n(43076),tP=n(17897),tO=n(73288);let t_=(0,tO.h)("frontend/components/Chat/QuickChatDialog"),tW=e=>{let{open:t,onClose:n,onStart:r}=e,[l,i]=(0,o.useState)([]),[u,p]=(0,o.useState)([]),[v,x]=(0,o.useState)(!1),[A,k]=(0,o.useState)(null),[I,S]=(0,o.useState)(""),[C,E]=(0,o.useState)(""),[T,N]=(0,o.useState)({}),[z,M]=(0,o.useState)(!1),[D,R]=(0,o.useState)(null);(0,o.useEffect)(()=>{if(!t)return;let e=!1;return x(!0),k(null),(async()=>{try{let[t,n]=await Promise.all([tF.N.loadModels(),tP.S.loadServerConfigs()]);if(e)return;i(t);let a=Array.isArray(n)?n.filter(e=>!e.disabled).map(e=>e.name):[];p(a),S(e=>{var n;return e||(null==(n=t[0])?void 0:n.id)||""})}catch(t){e||(t_.warn("Failed to load models/servers for quick chat",t),k("Could not load models or servers."))}finally{e||x(!1)}})(),()=>{e=!0}},[t]),(0,o.useEffect)(()=>{t||(E(""),N({}),R(null),M(!1))},[t]);let F=(0,o.useCallback)(e=>{N(t=>{let n=t[e];return(null==n?void 0:n.selected)?{...t,[e]:{...n,selected:!1}}:{...t,[e]:{...null!=n?n:{tools:null,expanded:!1},selected:!0}}})},[]),P=(0,o.useCallback)(async e=>{N(t=>{var n;let a=null!=(n=t[e])?n:{selected:!1,tools:null,expanded:!1};return{...t,[e]:{...a,expanded:!a.expanded}}});let t=T[e];if(!(null==t?void 0:t.available)&&!(null==t?void 0:t.loading)){N(t=>{var n;return{...t,[e]:{...null!=(n=t[e])?n:{selected:!1,tools:null,expanded:!0},loading:!0}}});try{let{tools:t}=await tP.S.listServerTools(e),n=Array.isArray(t)?t.map(e=>e.name).filter(Boolean):[];N(t=>{var a;return{...t,[e]:{...null!=(a=t[e])?a:{selected:!1,tools:null,expanded:!0},available:n,loading:!1}}})}catch(t){t_.warn("Failed to load tools for ".concat(e),t),N(t=>{var n;return{...t,[e]:{...null!=(n=t[e])?n:{selected:!1,tools:null,expanded:!0},available:[],loading:!1}}})}}},[T]),O=(0,o.useCallback)((e,t,n)=>{N(a=>{var o,r;let l=null!=(o=a[e])?o:{selected:!0,tools:null,expanded:!0},i=new Set(null!=(r=l.tools)?r:new Set(n));return i.has(t)?i.delete(t):i.add(t),{...a,[e]:{...l,selected:!0,tools:i}}})},[]),_=!!I&&!z&&!v,W=async()=>{if(!I)return void R("Pick a model to chat with.");M(!0),R(null);let e=u.filter(e=>{var t;return null==(t=T[e])?void 0:t.selected}).map(e=>{let t=T[e];return!t.tools||t.available&&t.tools.size===t.available.length?{name:e}:{name:e,enabledTools:[...t.tools]}});try{await r({modelId:I,servers:e,systemPrompt:C.trim()||void 0})}catch(e){t_.warn("Quick chat failed to start",e),R(e instanceof Error?e.message:"Could not start the quick chat."),M(!1)}};return(0,a.jsxs)(y.A,{open:t,onClose:z?void 0:n,maxWidth:"sm",fullWidth:!0,children:[(0,a.jsx)(b.A,{children:"Quick Chat"}),(0,a.jsxs)(w.A,{children:[(0,a.jsx)(c.A,{variant:"body2",color:"text.secondary",sx:{mb:2},children:"Chat with a model and, optionally, some MCP servers — no need to build and save a flow."}),A&&(0,a.jsx)(d.A,{severity:"error",sx:{mb:2},children:A}),(0,a.jsxs)(U.A,{fullWidth:!0,size:"small",sx:{mb:2},disabled:v,children:[(0,a.jsx)(tM.A,{id:"quick-chat-model-label",children:"Model"}),(0,a.jsxs)(H.A,{labelId:"quick-chat-model-label",label:"Model",value:I,onChange:e=>S(e.target.value),children:[0===l.length&&(0,a.jsx)(B.A,{value:"",disabled:!0,children:v?"Loading…":"No models configured"}),l.map(e=>(0,a.jsx)(B.A,{value:e.id,children:e.displayName||e.name},e.id))]})]}),(0,a.jsx)(g.A,{fullWidth:!0,size:"small",multiline:!0,minRows:2,maxRows:6,label:"System prompt (optional)",placeholder:"e.g. You are a concise coding agent.",value:C,onChange:e=>E(e.target.value),sx:{mb:2}}),(0,a.jsx)(q.A,{sx:{mb:1}}),(0,a.jsx)(c.A,{variant:"subtitle2",gutterBottom:!0,children:"MCP servers (optional)"}),v?(0,a.jsx)(s.default,{sx:{display:"flex",justifyContent:"center",my:2},children:(0,a.jsx)(eY.default,{size:22})}):0===u.length?(0,a.jsx)(c.A,{variant:"body2",color:"text.secondary",children:"No connected MCP servers. You can still chat with the model alone."}):u.map(e=>{let t=T[e],n=!!(null==t?void 0:t.selected),o=null==t?void 0:t.available,r=null==t?void 0:t.tools;return(0,a.jsxs)(s.default,{sx:{mb:.5},children:[(0,a.jsxs)(s.default,{sx:{display:"flex",alignItems:"center"},children:[(0,a.jsx)(tD.A,{sx:{flexGrow:1,mr:0},control:(0,a.jsx)(tR.A,{size:"small",checked:n,onChange:()=>F(e)}),label:(0,a.jsxs)(s.default,{sx:{display:"flex",alignItems:"center",gap:1},children:[(0,a.jsx)(c.A,{variant:"body2",children:e}),n&&(0,a.jsx)(f.A,{size:"small",variant:"outlined",label:r?"".concat(r.size," tool").concat(1===r.size?"":"s"):"all tools"})]})}),(0,a.jsx)(h.A,{size:"small",onClick:()=>P(e),"aria-label":"customize ".concat(e," tools"),children:(null==t?void 0:t.expanded)?(0,a.jsx)($.A,{fontSize:"small"}):(0,a.jsx)(Z.A,{fontSize:"small"})})]}),(0,a.jsx)(G.A,{in:!!(null==t?void 0:t.expanded),unmountOnExit:!0,children:(0,a.jsx)(s.default,{sx:{pl:4,pb:1},children:(null==t?void 0:t.loading)?(0,a.jsx)(eY.default,{size:16}):o&&o.length>0?o.map(t=>{let n=!r||r.has(t);return(0,a.jsx)(tD.A,{sx:{display:"flex"},control:(0,a.jsx)(tR.A,{size:"small",checked:n,onChange:()=>O(e,t,o)}),label:(0,a.jsx)(c.A,{variant:"caption",children:t})},t)}):(0,a.jsx)(c.A,{variant:"caption",color:"text.secondary",children:o?"No tools reported (server may be offline).":""})})})]},e)}),D&&(0,a.jsx)(d.A,{severity:"error",sx:{mt:2},children:D})]}),(0,a.jsxs)(j.A,{children:[(0,a.jsx)(m.A,{onClick:n,disabled:z,children:"Cancel"}),(0,a.jsx)(m.A,{variant:"contained",onClick:W,disabled:!_,startIcon:z?(0,a.jsx)(eY.default,{size:16,color:"inherit"}):void 0,children:z?"Starting…":"Start chat"})]})]})};var tq=n(98267),tL=n(20537),tU=n(37960),tH=n(49692),tB=n(54178),tK=n(11305),tG=n(48116),tX=n(22539),tJ=n(90057),tQ=n(41603),tY=n(53911);let tV={byNode:{},byResource:{},byResourceName:{},resourceVersion:0};function tZ(e,t){return"".concat(e," ").concat(t)}let t$="root",t0=e=>{var t,n;return"subflow:start"===e.type||"subflow:done"===e.type?null!=(t=e.depth)?t:1:null!=(n=e.depth)?n:0},t1=(e,t)=>null==t.laneIndex||null==e.laneIndex||e.laneIndex===t.laneIndex,t2=(e,t)=>{for(let n=e.order.length-1;n>=0;n-=1){let a=e.frames[e.order[n]];if(a&&t(a))return a}},t5=(e,t,n)=>{var a;return n<=1?e.frames[e.rootKey]:null!=(a=t2(e,e=>"active"===e.status&&e.depth===n-1&&t1(e,t)))?a:e.frames[e.rootKey]},t6=(e,t)=>{var n;let a=t0(t);return a<=0?e.frames[e.rootKey]:null!=(n=t2(e,e=>"active"===e.status&&e.depth===a&&t1(e,t)))?n:e.frames[e.rootKey]},t3=e=>{var t;return"node"in e?null==(t=e.node)?void 0:t.nodeId:void 0},t4=e=>"resource:read"===e.type?"resource-read":"resource:write"===e.type?"resource-write":"active";var t8=n(49501),t7=n(59323),t9=n(72308),ne=n(6422),nt=n(48363);let nn=(0,tO.h)("frontend/components/Chat/RunResourcesPanel"),na=e=>{let{conversationId:t,refreshToken:n}=e,[r,l]=(0,o.useState)(null),[i,d]=(0,o.useState)(null);return((0,o.useEffect)(()=>{if(!t)return;let e=!1;return fetch("/v1/chat/conversations/".concat(encodeURIComponent(t),"/resources")).then(async e=>{if(!e.ok)throw Error("HTTP ".concat(e.status));return e.json()}).then(t=>{e||(l(Array.isArray(t.resources)?t.resources:[]),d(null))}).catch(t=>{e||(nn.warn("Failed to load run resources",t),d(t instanceof Error?t.message:String(t)))}),()=>{e=!0}},[t,n]),i)?(0,a.jsxs)(c.A,{variant:"caption",color:"text.secondary",children:["Run data unavailable (",i,")"]}):null===r?(0,a.jsx)(s.default,{sx:{display:"flex",justifyContent:"center",p:1},children:(0,a.jsx)(eY.default,{size:16})}):0===r.length?(0,a.jsx)(c.A,{variant:"caption",color:"text.secondary",children:"No data artifacts captured in this run yet."}):(0,a.jsx)(K.A,{dense:!0,disablePadding:!0,children:[...r].sort((e,t)=>t.createdAt-e.createdAt).map(e=>{var t,n,o,r,l;return(0,a.jsxs)(O.Ay,{disableGutters:!0,sx:{alignItems:"flex-start"},children:[(0,a.jsx)(t8.A,{sx:{minWidth:30,mt:.5},children:function(e){switch(e){case"image":return(0,a.jsx)(t9.A,{fontSize:"small",sx:{color:"#009688"}});case"audio":return(0,a.jsx)(ne.A,{fontSize:"small",sx:{color:"#009688"}});case"link":return(0,a.jsx)(nt.A,{fontSize:"small",sx:{color:"#009688"}});default:return(0,a.jsx)(t7.A,{fontSize:"small",sx:{color:"#009688"}})}}(e.kind)}),(0,a.jsx)(W.A,{primary:(0,a.jsxs)(s.default,{sx:{display:"flex",alignItems:"center",gap:.5,flexWrap:"wrap"},children:[(0,a.jsx)(c.A,{variant:"body2",sx:{fontWeight:500},children:null!=(n=e.name)?n:"".concat(e.kind,"-").concat(e.id.slice(0,8))}),e.mimeType&&(0,a.jsx)(f.A,{label:e.mimeType,size:"small",variant:"outlined",sx:{height:18,fontSize:"0.65rem"}}),e.archive&&(0,a.jsx)(f.A,{label:"page"===e.archive.role?"archive page ".concat((null!=(o=e.archive.pageIndex)?o:0)+1,"/").concat(null!=(r=e.archive.pageCount)?r:"?"):"archive source",size:"small",color:"info",variant:"outlined",sx:{height:18,fontSize:"0.65rem"}}),(0,a.jsx)(c.A,{variant:"caption",color:"text.secondary",children:function(e){return e<1024?"".concat(e," B"):e<1048576?"".concat(Math.round(e/1024)," KB"):"".concat((e/1048576).toFixed(1)," MB")}(e.size)})]}),secondary:(0,a.jsxs)(c.A,{variant:"caption",color:"text.secondary",component:"span",sx:{wordBreak:"break-all"},children:["by ",function(e){var t,n,a,o,r,l,i;let s=e.producedBy;switch(s.source){case"tool-result":return"tool ".concat(null!=(t=s.server)?t:"?","/").concat(null!=(n=s.toolName)?n:"?");case"tool-args":return"tool args ".concat(null!=(a=s.server)?a:"?","/").concat(null!=(o=s.toolName)?o:"?");case"capture":return"step ".concat(null!=(l=null!=(r=s.nodeName)?r:s.nodeId)?l:"?");case"mcp-link":return"link from ".concat(null!=(i=s.server)?i:"?");case"visual-archive":return"visual context archive";default:return"run"}}(e),e.readBy.length>0?" \xb7 read ".concat(e.readBy.length,"\xd7"):"",(null!=(l=null==(t=e.verifications)?void 0:t.length)?l:0)>0?" \xb7 verified ".concat(e.verifications.filter(e=>e.ok).length,"/").concat(e.verifications.length):"",e.sha256?" \xb7 sha256 ".concat(e.sha256.slice(0,12),"…"):""," \xb7 ",e.uri]})})]},e.id)})})};var no=n(14913),nr=n(57883);let nl={system:{label:"system",color:"secondary"},sent:{label:"sent",color:"success"},folded:{label:"folded",color:"warning"},"scoped-out":{label:"scoped out",color:"info"},"handoff-stripped":{label:"handoff plumbing",color:"default"}},ni={whiteSpace:"pre-wrap",wordBreak:"break-word",margin:0,fontSize:"0.75rem",fontFamily:"inherit"},ns=e=>{let{role:t,content:n,toolCallNames:o,status:r,faded:l}=e;return(0,a.jsxs)(tx.A,{variant:"outlined",sx:{p:1,mb:.75,opacity:l?.55:1,borderStyle:l?"dashed":"solid"},children:[(0,a.jsxs)(s.default,{sx:{display:"flex",alignItems:"center",gap:.5,mb:.5,flexWrap:"wrap"},children:[(0,a.jsx)(f.A,{size:"small",label:t,color:function(e){switch(e){case"system":return"secondary";case"user":return"primary";case"assistant":return"success";case"tool":return"info";default:return"default"}}(t),variant:"outlined"}),o&&o.length>0&&(0,a.jsx)(f.A,{size:"small",variant:"outlined",label:"\uD83D\uDD27 ".concat(o.join(", ")),sx:{maxWidth:"100%"}}),r&&"sent"!==r&&"system"!==r&&(0,a.jsx)(f.A,{size:"small",color:nl[r].color,label:nl[r].label})]}),n.trim().length>0?(0,a.jsx)("pre",{style:ni,children:n}):(0,a.jsx)(c.A,{variant:"caption",color:"textSecondary",children:"(no text content)"})]})},nd=e=>{let{provenance:t}=e;return(0,a.jsxs)(s.default,{children:[(0,a.jsx)(c.A,{variant:"caption",color:"textSecondary",sx:{display:"block",mb:.5},children:"Full threaded history — greyed rows are not sent to the model."}),t.map((e,t)=>{var n,o;return(0,a.jsx)(ns,{role:e.role,content:null!=(n=e.preview)?n:"",toolCallNames:e.toolCallNames,status:e.status,faded:"sent"!==e.status&&"system"!==e.status},null!=(o=e.id)?o:"hist-".concat(t))}),t.some(e=>"sent"!==e.status&&"system"!==e.status)&&(0,a.jsx)(c.A,{variant:"caption",color:"textSecondary",sx:{display:"block",mt:1},children:"Hover a badge label to understand why a message is not on the wire: folded (outputMode), scoped out (inputMode), or handoff plumbing (tool-call strip)."})]})},nc=()=>{},nu=e=>{let{modelInput:t,conversationId:n}=e,[r,l]=(0,o.useState)("wire"),{systemMessage:i,wireMessages:d,provenance:u,counts:h,inputMode:p}=t,g=(0,o.useMemo)(()=>(d||[]).filter(e=>"system"!==e.role),[d]);return(0,a.jsxs)(s.default,{sx:{height:"100%",display:"flex",flexDirection:"column",p:1},children:[(0,a.jsxs)(s.default,{sx:{display:"flex",alignItems:"center",gap:.5,flexWrap:"wrap",mb:1},children:[(0,a.jsx)(c.A,{variant:"caption",color:"textSecondary",children:function(e){return"".concat(e.threaded," in history → ").concat(e.sent," sent")+(e.folded?" \xb7 ".concat(e.folded," folded"):"")+(e.scopedOut?" \xb7 ".concat(e.scopedOut," scoped out"):"")+(e.handoffStripped?" \xb7 ".concat(e.handoffStripped," handoff-stripped"):"")}(h)}),p&&"full-history"!==p&&(0,a.jsx)(f.A,{size:"small",variant:"outlined",label:"inputMode: ".concat(p)})]}),(0,a.jsxs)(tq.A,{sx:{boxShadow:"none","&:before":{display:"none"}},children:[(0,a.jsx)(tL.A,{expandIcon:(0,a.jsx)(Z.A,{}),sx:{minHeight:"36px","& .MuiAccordionSummary-content":{margin:"8px 0"}},children:(0,a.jsx)(c.A,{variant:"caption",children:(0,a.jsx)("b",{children:"System message"})})}),(0,a.jsx)(tU.A,{sx:{p:0},children:i&&i.content.trim().length>0?(0,a.jsx)(tx.A,{variant:"outlined",sx:{p:1,maxHeight:220,overflowY:"auto"},children:(0,a.jsx)("pre",{style:{whiteSpace:"pre-wrap",wordBreak:"break-word",margin:0,fontSize:"0.75rem",fontFamily:"inherit"},children:i.content})}):(0,a.jsx)(c.A,{variant:"caption",color:"textSecondary",children:"(no system message)"})})]}),(0,a.jsxs)(no.A,{size:"small",exclusive:!0,value:r,onChange:(e,t)=>{t&&l(t)},sx:{my:1},children:[(0,a.jsx)(nr.A,{value:"wire",children:"What the model sees"}),(0,a.jsx)(nr.A,{value:"annotated",children:"Full history (annotated)"})]}),(0,a.jsx)(s.default,{sx:{flexGrow:1,overflowY:"auto",minHeight:0},children:"wire"===r?0===g.length?(0,a.jsx)(c.A,{variant:"body2",color:"textSecondary",sx:{p:1},children:"No conversation messages — the model sees only the system message."}):(0,a.jsx)(ez.A,{messages:g,conversationId:n?"debug-".concat(n):void 0,onToggleDisabled:nc,onSplitConversation:nc}):(0,a.jsx)(nd,{provenance:u})})]})},nh=(0,tO.h)("frontend/components/Chat/DebuggerCanvas"),np={start:tQ.vm,process:tQ.Uw,finish:tQ.IK,mcp:tQ.v2,subflow:tQ.lA,resource:tQ.z9},ng={custom:tY.jY,mcpEdge:tY.oY,resourceEdge:tY.sZ},nf=[],nm=["conversation","tracker","detail"],nv={conversation:"Conversation",tracker:"Execution Tracker",detail:"Detail"},nx="flujo-debugger-section-order",ny="flujo-debugger-section-visible",nb="flujo-debugger-conv-width",nw="flujo-debugger-detail-width";function nA(e,t){let n=Number(window.localStorage.getItem(e));return Number.isFinite(n)&&n>=240?n:t}let nj=(0,tG.Ay)(tx.A)(e=>{let{theme:t}=e;return{display:"flex",flexDirection:"column",height:"100%",overflow:"hidden",padding:t.spacing(1)}}),nk=(0,tG.Ay)(s.default)(e=>{let{theme:t}=e;return{padding:t.spacing(1,2),borderBottom:"1px solid ".concat(t.palette.divider)}}),nI=(0,tG.Ay)(s.default)({flexGrow:1,display:"flex",overflow:"hidden",minHeight:0}),nS=(0,tG.Ay)(s.default)(e=>{let{theme:t}=e;return{width:"200px",flexShrink:0,borderRight:"1px solid ".concat(t.palette.divider),overflowY:"auto",padding:t.spacing(1)}}),nC=(0,tG.Ay)(s.default)({flexGrow:1,position:"relative",height:"100%"}),nE=(0,tG.Ay)(s.default)(e=>{let{theme:t}=e;return{padding:t.spacing(1,2),borderTop:"1px solid ".concat(t.palette.divider),display:"flex",gap:t.spacing(1),justifyContent:"center"}}),nT=(0,tG.Ay)(s.default)(e=>{let{theme:t}=e;return{width:"6px",flexShrink:0,cursor:"col-resize",backgroundColor:t.palette.divider,transition:"background-color 120ms",touchAction:"none","&:hover":{backgroundColor:t.palette.primary.main}}}),nN=e=>{var t,n,r,l,i,p,g,f,v;let{debugState:x,conversationId:y,onStep:b,onStepOver:w,onContinue:A,onCancel:j,isLoading:I,breakpoints:S,onToggleBreakpoint:C,onClose:E,isExpanded:T,onToggleExpand:N,liveActivity:z,executionEvents:M=nf}=e,D=(0,k.A)(),[F,P]=(0,o.useState)(x.executionTrace&&x.executionTrace.length>0?x.executionTrace.length-1:-1),[q,L]=(0,o.useState)(()=>(function(){try{let e=JSON.parse(window.localStorage.getItem(nx)||"null");if(Array.isArray(e)){let t=e.filter(e=>nm.includes(e)),n=nm.filter(e=>!t.includes(e));if(t.length+n.length===nm.length)return[...t,...n]}}catch(e){}return[...nm]})()),[U,H]=(0,o.useState)(()=>(function(){let e={conversation:!0,tracker:!0,detail:!0};try{let t=JSON.parse(window.localStorage.getItem(ny)||"null");if(t&&"object"==typeof t)for(let n of nm)"boolean"==typeof t[n]&&(e[n]=t[n])}catch(e){}return e})()),[B,G]=(0,o.useState)(()=>nA(nb,480)),[X,J]=(0,o.useState)(()=>nA(nw,320)),Y=(0,o.useMemo)(()=>{var e;return function(e,t){let n={key:t$,parentKey:null,flowId:e,displayName:"Root flow",depth:0,status:"active",startedSeq:0,nodeActivity:{}},a={rootKey:n.key,activeFrameKey:n.key,frames:{[n.key]:n},order:[n.key]};for(let e of t){var o,r,l,i,s,d;let t=t0(e);if(t<0||t>8)continue;if("run:start"===e.type){a.activeFrameKey=n.key;continue}if("subflow:start"===e.type){if(!e.subflowId||t<=0)continue;let n=t5(a,e,t),s=null==e.laneIndex?"":":lane-".concat(e.laneIndex),d="".concat(n.key,":").concat(null!=(i=null==(o=e.node)?void 0:o.nodeId)?i:"subflow",":").concat(e.subflowId).concat(s,":seq-").concat(e.seq),c={key:d,parentKey:n.key,flowId:e.subflowId,invokingNodeId:null==(r=e.node)?void 0:r.nodeId,displayName:e.laneTitle||e.subflowName||e.subflowId,depth:t,laneIndex:e.laneIndex,laneCount:e.laneCount,laneTitle:e.laneTitle,status:"active",startedSeq:e.seq,nodeActivity:{}};a.frames[d]=c,a.order.push(d),a.activeFrameKey=d,(null==(l=e.node)?void 0:l.nodeId)&&(n.nodeActivity[e.node.nodeId]={kind:"active",ts:e.timestamp});continue}if("subflow:done"===e.type){let o=t2(a,n=>{var a;return"active"===n.status&&n.depth===t&&n.flowId===e.subflowId&&((null==(a=e.node)?void 0:a.nodeId)==null||n.invokingNodeId===e.node.nodeId)&&t1(n,e)});if(!o)continue;o.status=e.status,o.endedSeq=e.seq,a.activeFrameKey=null!=(s=o.parentKey)?s:n.key;let r=a.frames[null!=(d=o.parentKey)?d:n.key];o.invokingNodeId&&r&&(r.nodeActivity[o.invokingNodeId]={kind:"active",ts:e.timestamp});continue}let c=t6(a,e);a.activeFrameKey=c.key;let u=t3(e);u&&(c.nodeActivity[u]={kind:t4(e),ts:e.timestamp})}return a}(null!=(e=x.flowId)?e:"",M)},[x.flowId,M]),[V,$]=(0,o.useState)(t$),[ee,et]=(0,o.useState)({}),en=(0,o.useRef)(new Set),ea=(0,o.useRef)(0),[eo,er,el]=(0,tX.ck)([]),[ei,es,ed]=(0,tX.fM)([]);(0,o.useEffect)(()=>{window.localStorage.setItem(nx,JSON.stringify(q))},[q]),(0,o.useEffect)(()=>{window.localStorage.setItem(ny,JSON.stringify(U))},[U]),(0,o.useEffect)(()=>{window.localStorage.setItem(nb,String(Math.round(B)))},[B]),(0,o.useEffect)(()=>{window.localStorage.setItem(nw,String(Math.round(X)))},[X]),(0,o.useEffect)(()=>{var e;let t=(null==(e=x.executionTrace)?void 0:e.length)||0;t>0?(P(e=>Math.min(e,t-1)),F<t-1&&P(t-1)):P(-1)},[x.executionTrace]),(0,o.useEffect)(()=>{$(Y.activeFrameKey)},[Y.activeFrameKey,M.length]);let ec=(0,o.useMemo)(()=>Array.from(new Set(Y.order.map(e=>{var t;return null==(t=Y.frames[e])?void 0:t.flowId}).filter(Boolean))),[Y]);(0,o.useEffect)(()=>{ea.current+=1,en.current.clear(),et({}),$(t$)},[y,x.flowId]),(0,o.useEffect)(()=>{let e=ea.current;for(let t of ec)!t||en.current.has(t)||(en.current.add(t),et(e=>({...e,[t]:{status:"loading"}})),tJ.g.getFlow(t).then(n=>{ea.current===e&&et(e=>({...e,[t]:n?{status:"ready",flow:n}:{status:"missing"}}))}).catch(n=>{if(ea.current!==e)return;let a=n instanceof Error?n.message:"Failed to load flow ".concat(t,".");nh.error("Error loading debugger flow definition:",n),et(e=>({...e,[t]:{status:"error",message:a}}))}))},[y,x.flowId,ec]);let eu=null!=(g=null!=(p=Y.frames[V])?p:Y.frames[Y.activeFrameKey])?g:Y.frames[t$],eh=ee[eu.flowId],ep=eu;for(;(null==(t=ee[ep.flowId])?void 0:t.status)!=="ready"&&ep.parentKey;)ep=null!=(f=Y.frames[ep.parentKey])?f:Y.frames[t$];let eg=ee[ep.flowId],ef=(null==eg?void 0:eg.status)==="ready"?eg.flow:null,em=ee[null!=(v=x.flowId)?v:""],ev=!!x.flowId&&!ef&&(!em||"loading"===em.status),ex=x.flowId?(null==em?void 0:em.status)==="missing"?"Flow with ID ".concat(x.flowId," not found."):(null==em?void 0:em.status)==="error"?em.message:null:"Flow ID is missing in debug state.",ey=eu.key!==t$&&(null==eh?void 0:eh.status)!=="ready"?(null==eh?void 0:eh.status)!=="loading"&&eh?"Flow ".concat(eu.displayName," is unavailable; showing its parent flow."):"Loading ".concat(eu.displayName,"; showing its parent flow for now."):null;(0,o.useEffect)(()=>{if(!ef){er([]),es([]);return}nh.debug("Setting debugger graph for flow ".concat(ef.id)),er(ef.nodes.map(e=>({...e,draggable:!1,selectable:!1,connectable:!1}))),es(ef.edges.map(e=>({...e,selectable:!1})))},[ef,er,es]);let eb=(0,o.useCallback)(()=>{if(nh.debug("Previous button clicked. Current index: ".concat(F)),F>0){let e=F-1;nh.debug("Setting current step index to: ".concat(e)),P(e)}else nh.debug("Already at the first step, cannot go previous.")},[F]),ew=(0,o.useCallback)(()=>{var e;if(nh.debug("Next button clicked. Current index: ".concat(F,", Trace length: ").concat(null==(e=x.executionTrace)?void 0:e.length)),x.executionTrace&&F<x.executionTrace.length-1){let e=F+1;nh.debug("Navigating to next trace step: ".concat(e)),P(e)}else nh.info("At end of trace, triggering API call for next step."),b()},[F,x.executionTrace,b]),eA=(0,o.useMemo)(()=>{if(x.executionTrace&&F>=0&&F<x.executionTrace.length)return x.executionTrace[F]},[x.executionTrace,F]),ej=(0,o.useMemo)(()=>(null==eA?void 0:eA.modelInputs)&&eA.modelInputs.length>0?eA.modelInputs:(null==eA?void 0:eA.modelInput)?[eA.modelInput]:void 0,[eA]),[ek,eI]=(0,o.useState)(0);(0,o.useEffect)(()=>{eI(0)},[F]);let eS=ej?Math.min(ek,ej.length-1):0,eC=null==ej?void 0:ej[eS],[eE,eT]=(0,o.useState)(()=>Date.now());(0,o.useEffect)(()=>{eT(Date.now())},[M.length]),(0,o.useEffect)(()=>{if(!z)return;let e=()=>{let e=Date.now();return[...Object.values(z.byNode),...Object.values(z.byResource),...Object.values(z.byResourceName)].some(t=>e-t.ts<4e3)};if(!e())return;let t=setInterval(()=>{eT(Date.now()),e()||clearInterval(t)},350);return()=>clearInterval(t)},[z]);let eN=(0,o.useCallback)(e=>{var t,n;let a=ep.nodeActivity[e.id];if(a&&eE-a.ts<4e3)return a;if(ep.key!==t$||!z)return null;let o=z.byNode[e.id];if(o&&eE-o.ts<4e3)return o;let r=e.data;if((null!=(t=null==r?void 0:r.type)?t:e.type)!=="resource")return null;let l=null!=(n=null==r?void 0:r.properties)?n:{},i="run"===l.scope?"string"==typeof l.runName?z.byResourceName[l.runName]:void 0:"string"==typeof l.boundServer&&"string"==typeof l.uri?z.byResource[tZ(l.boundServer,l.uri)]:void 0;return i&&eE-i.ts<4e3?{kind:"read"===i.kind?"resource-read":"resource-write",ts:i.ts}:null},[ep,z,eE]),ez=(0,o.useMemo)(()=>{let e=ep.key===t$?null==eA?void 0:eA.nodeId:void 0;return eo.map(t=>{var n;let a=t.id===e,o=null==S?void 0:S.includes(t.id),r=a?null:eN(t),l=r?Math.max(.25,1-(eE-r.ts)/4e3):0,i=(null==r?void 0:r.kind)==="active"?D.palette.primary.main:"#009688";return{...t,style:{...t.style,border:a?"2px solid ".concat(D.palette.warning.main):r?"2px solid ".concat(i):o?"2px dashed ".concat(D.palette.error.main):null==(n=t.style)?void 0:n.border,boxShadow:a?"0 0 10px ".concat(D.palette.warning.light):r?"0 0 ".concat("resource-write"===r.kind?14:10,"px ").concat(i).concat(Math.round(255*l).toString(16).padStart(2,"0")):void 0}}})},[eo,ep.key,eA,S,D,eN,eE]),eM=(0,o.useMemo)(()=>(function(e,t){let n=[],a=new Set,o=e.frames[t];for(;o&&!a.has(o.key)&&n.length<=8;)n.unshift(o),a.add(o.key),o=o.parentKey?e.frames[o.parentKey]:void 0;return n})(Y,eu.key),[Y,eu.key]),eD=(0,o.useCallback)(e=>{let t=ee[e.flowId],n=e.key===t$&&(null==t?void 0:t.status)==="ready"?t.flow.name:e.displayName;return null==e.laneIndex?n:"".concat(n," \xb7 lane ").concat(e.laneIndex+1)},[ee]),eR=(0,o.useMemo)(()=>q.filter(e=>U[e]),[q,U]),e_=(0,o.useCallback)(e=>{H(t=>({...t,[e]:!t[e]}))},[]),eW=(0,o.useCallback)((e,t)=>{L(n=>{let a=n.indexOf(e),o=a+t;if(a<0||o<0||o>=n.length)return n;let r=[...n];return[r[a],r[o]]=[r[o],r[a]],r})},[]),eq=(0,o.useCallback)((e,t,n)=>{n.preventDefault();let a=n.clientX,o="conversation"===e?B:X,r="conversation"===e?G:J,l=document.body.style.userSelect,i=document.body.style.cursor;document.body.style.userSelect="none",document.body.style.cursor="col-resize";let s=e=>{r(Math.min(Math.max(o+t*(e.clientX-a),240),1100))},d=()=>{window.removeEventListener("pointermove",s),window.removeEventListener("pointerup",d),document.body.style.userSelect=l,document.body.style.cursor=i};window.addEventListener("pointermove",s),window.addEventListener("pointerup",d)},[B,X]),eL=(0,a.jsx)(s.default,{sx:{flexGrow:1,overflow:"hidden",minHeight:0,display:"flex",flexDirection:"column"},children:eA?eC&&ej?(0,a.jsxs)(s.default,{sx:{flexGrow:1,minHeight:0,display:"flex",flexDirection:"column"},children:[ej.length>1&&(0,a.jsxs)(s.default,{sx:{display:"flex",alignItems:"center",justifyContent:"center",gap:.5,px:1,py:.5,borderBottom:"1px solid ".concat(D.palette.divider)},children:[(0,a.jsx)(u.A,{title:"Previous model call",children:(0,a.jsx)("span",{children:(0,a.jsx)(h.A,{size:"small",onClick:()=>eI(e=>Math.max(0,Math.min(e,ej.length-1)-1)),disabled:eS<=0,"aria-label":"Previous model call",children:(0,a.jsx)(Q.A,{fontSize:"small"})})})}),(0,a.jsxs)(c.A,{variant:"caption",color:"textSecondary",children:["Model call ",eS+1," / ",ej.length]}),(0,a.jsx)(u.A,{title:"Next model call",children:(0,a.jsx)("span",{children:(0,a.jsx)(h.A,{size:"small",onClick:()=>eI(e=>Math.min(ej.length-1,Math.min(e,ej.length-1)+1)),disabled:eS>=ej.length-1,"aria-label":"Next model call",children:(0,a.jsx)(tH.A,{fontSize:"small"})})})})]}),(0,a.jsx)(s.default,{sx:{flexGrow:1,minHeight:0,overflow:"hidden",display:"flex",flexDirection:"column"},children:(0,a.jsx)(nu,{modelInput:eC,conversationId:y})})]}):(0,a.jsx)(c.A,{variant:"body2",color:"textSecondary",sx:{p:2},children:"No model call for this step."}):(0,a.jsx)(c.A,{variant:"body2",color:"textSecondary",sx:{p:2},children:"Select a step from the execution tracker."})}),eU={conversation:eL,tracker:(0,a.jsxs)(s.default,{sx:{flexGrow:1,display:"flex",overflow:"hidden",minHeight:0},children:[(0,a.jsxs)(nS,{children:[(0,a.jsx)(c.A,{variant:"caption",color:"textSecondary",gutterBottom:!0,sx:{display:"block"},children:"Execution Trace"}),(0,a.jsxs)(K.A,{dense:!0,disablePadding:!0,children:[null==(n=x.executionTrace)?void 0:n.map((e,t)=>(0,a.jsx)(O.Ay,{disablePadding:!0,children:(0,a.jsx)(_.A,{selected:t===F,onClick:()=>(e=>{x.executionTrace&&e>=0&&e<x.executionTrace.length?(nh.debug("Trace step selected: ".concat(e)),P(e)):nh.warn("Invalid step index selected: ".concat(e))})(t),children:(0,a.jsx)(W.A,{primary:"".concat(e.stepIndex,": ").concat(e.nodeName||e.nodeId),secondary:e.nodeType})})},e.stepIndex)),I&&(0,a.jsx)(O.Ay,{children:(0,a.jsx)(eY.default,{size:20,sx:{margin:"auto"}})})]})]}),(0,a.jsx)(nC,{children:(0,a.jsxs)(s.default,{sx:{height:"100%",minHeight:0,display:"flex",flexDirection:"column"},children:[(0,a.jsxs)(s.default,{sx:{px:1,py:.5,borderBottom:"1px solid ".concat(D.palette.divider),flexShrink:0},children:[(0,a.jsxs)(s.default,{sx:{display:"flex",alignItems:"center",gap:.25,overflowX:"auto"},children:[eu.parentKey&&(0,a.jsx)(u.A,{title:"Back to parent flow",children:(0,a.jsx)(h.A,{size:"small",onClick:()=>{var e;return $(null!=(e=eu.parentKey)?e:t$)},"aria-label":"Back to parent flow",children:(0,a.jsx)(Q.A,{fontSize:"small"})})}),eM.map((e,t)=>(0,a.jsxs)(o.Fragment,{children:[t>0&&(0,a.jsx)(tH.A,{color:"disabled",fontSize:"small"}),(0,a.jsx)(m.A,{size:"small",variant:e.key===eu.key?"contained":"text",onClick:()=>$(e.key),sx:{minWidth:0,whiteSpace:"nowrap",textTransform:"none"},children:eD(e)})]},e.key))]}),Y.order.length>1&&(0,a.jsxs)(s.default,{sx:{display:"flex",alignItems:"center",gap:.5,mt:.25,overflowX:"auto"},children:[(0,a.jsx)(c.A,{variant:"caption",color:"textSecondary",sx:{flexShrink:0},children:"Frames:"}),Y.order.slice(1).map(e=>{let t=Y.frames[e];return(0,a.jsxs)(m.A,{size:"small",variant:t.key===eu.key?"outlined":"text",color:"error"===t.status?"error":"inherit",onClick:()=>$(t.key),sx:{minWidth:0,py:0,whiteSpace:"nowrap",textTransform:"none",fontSize:"0.7rem"},children:[eD(t)," \xb7 ",t.status]},e)})]})]}),ey&&(0,a.jsx)(d.A,{severity:(null==eh?void 0:eh.status)!=="loading"&&eh?"warning":"info",sx:{m:1,mb:0,py:0,flexShrink:0},children:ey}),(0,a.jsx)(s.default,{sx:{flexGrow:1,minHeight:0,position:"relative"},children:ev?(0,a.jsx)(s.default,{sx:{display:"flex",justifyContent:"center",alignItems:"center",height:"100%"},children:(0,a.jsx)(eY.default,{})}):ex?(0,a.jsx)(d.A,{severity:"error",sx:{margin:2},children:ex}):(0,a.jsx)(tX.Ln,{children:(0,a.jsx)(tX.Gc,{nodes:ez,edges:ei,onNodesChange:el,onEdgesChange:ed,nodeTypes:np,edgeTypes:ng,fitView:!0,attributionPosition:"bottom-right",nodesDraggable:!1,nodesConnectable:!1,elementsSelectable:!1,panOnDrag:!0,zoomOnScroll:!0,zoomOnPinch:!0,zoomOnDoubleClick:!1,onNodeClick:(e,t)=>{e.preventDefault(),C&&C(t.id)},onEdgeClick:e=>e.preventDefault(),onPaneClick:()=>{}})})})]})})]}),detail:(0,a.jsxs)(s.default,{sx:{flexGrow:1,overflowY:"auto",minHeight:0,p:2},children:[eA?(0,a.jsxs)(s.default,{children:[(0,a.jsxs)(c.A,{variant:"body2",children:[(0,a.jsx)("b",{children:"Node:"})," ",eA.nodeName," (",eA.nodeId,")"]}),(0,a.jsxs)(c.A,{variant:"body2",children:[(0,a.jsx)("b",{children:"Type:"})," ",eA.nodeType]}),(0,a.jsxs)(c.A,{variant:"body2",children:[(0,a.jsx)("b",{children:"Timestamp:"})," ",new Date(eA.timestamp).toLocaleString()]}),(0,a.jsxs)(c.A,{variant:"body2",children:[(0,a.jsx)("b",{children:"Action Taken:"})," ",eA.actionTaken]}),(0,a.jsxs)(tq.A,{sx:{mt:2,boxShadow:"none","&:before":{display:"none"}},children:[(0,a.jsx)(tL.A,{expandIcon:(0,a.jsx)(Z.A,{}),sx:{minHeight:"36px","& .MuiAccordionSummary-content":{margin:"8px 0"}},children:(0,a.jsx)(c.A,{variant:"caption",children:"Prep Result"})}),(0,a.jsx)(tU.A,{sx:{p:0},children:(0,a.jsx)("pre",{style:{whiteSpace:"pre-wrap",wordBreak:"break-all",maxHeight:"200px",overflowY:"auto",background:"var(--surface-raised)",color:"var(--foreground)",padding:"8px",borderRadius:"4px",fontSize:"0.75rem",margin:0},children:JSON.stringify(eA.prepResultSnapshot,null,2)})})]}),(0,a.jsxs)(tq.A,{sx:{boxShadow:"none","&:before":{display:"none"}},children:[(0,a.jsx)(tL.A,{expandIcon:(0,a.jsx)(Z.A,{}),sx:{minHeight:"36px","& .MuiAccordionSummary-content":{margin:"8px 0"}},children:(0,a.jsxs)(c.A,{variant:"caption",color:(null==(r=eA.execResultSnapshot)?void 0:r.success)===!1?"error":"inherit",children:["Exec Result ",(null==(l=eA.execResultSnapshot)?void 0:l.success)===!1?"(Error)":""]})}),(0,a.jsx)(tU.A,{sx:{p:0},children:(null==(i=eA.execResultSnapshot)?void 0:i.success)===!1?(0,a.jsxs)(s.default,{sx:{p:1,background:D.palette.error.light,borderRadius:1},children:[(0,a.jsxs)(c.A,{variant:"body2",color:"error",gutterBottom:!0,children:[(0,a.jsx)("b",{children:"Error:"})," ",eA.execResultSnapshot.error||"Unknown error"]}),eA.execResultSnapshot.errorDetails&&(0,a.jsx)("pre",{style:{whiteSpace:"pre-wrap",wordBreak:"break-all",maxHeight:"150px",overflowY:"auto",background:"var(--surface-raised)",color:"var(--foreground)",padding:"4px",borderRadius:"4px",fontSize:"0.75rem",margin:0},children:JSON.stringify(eA.execResultSnapshot.errorDetails,null,2)})]}):(0,a.jsx)("pre",{style:{whiteSpace:"pre-wrap",wordBreak:"break-all",maxHeight:"200px",overflowY:"auto",background:"var(--surface-raised)",color:"var(--foreground)",padding:"8px",borderRadius:"4px",fontSize:"0.75rem",margin:0},children:JSON.stringify(eA.execResultSnapshot,null,2)})})]}),(0,a.jsxs)(tq.A,{sx:{boxShadow:"none","&:before":{display:"none"}},children:[(0,a.jsx)(tL.A,{expandIcon:(0,a.jsx)(Z.A,{}),sx:{minHeight:"36px","& .MuiAccordionSummary-content":{margin:"8px 0"}},children:(0,a.jsx)(c.A,{variant:"caption",children:"State Before"})}),(0,a.jsx)(tU.A,{sx:{p:0},children:(0,a.jsx)("pre",{style:{whiteSpace:"pre-wrap",wordBreak:"break-all",maxHeight:"200px",overflowY:"auto",background:"var(--surface-raised)",color:"var(--foreground)",padding:"8px",borderRadius:"4px",fontSize:"0.75rem",margin:0},children:JSON.stringify(eA.stateBefore,null,2)})})]}),(0,a.jsxs)(tq.A,{sx:{boxShadow:"none","&:before":{display:"none"}},children:[(0,a.jsx)(tL.A,{expandIcon:(0,a.jsx)(Z.A,{}),sx:{minHeight:"36px","& .MuiAccordionSummary-content":{margin:"8px 0"}},children:(0,a.jsx)(c.A,{variant:"caption",children:"State After"})}),(0,a.jsx)(tU.A,{sx:{p:0},children:(0,a.jsx)("pre",{style:{whiteSpace:"pre-wrap",wordBreak:"break-all",maxHeight:"200px",overflowY:"auto",background:"var(--surface-raised)",color:"var(--foreground)",padding:"8px",borderRadius:"4px",fontSize:"0.75rem",margin:0},children:JSON.stringify(eA.stateAfter,null,2)})})]})]}):(0,a.jsx)(c.A,{variant:"body2",color:"textSecondary",children:"Select a step from the execution tracker."}),(0,a.jsxs)(tq.A,{defaultExpanded:!0,sx:{mt:2,boxShadow:"none","&:before":{display:"none"}},children:[(0,a.jsx)(tL.A,{expandIcon:(0,a.jsx)(Z.A,{}),sx:{minHeight:"36px","& .MuiAccordionSummary-content":{margin:"8px 0"}},children:(0,a.jsx)(c.A,{variant:"caption",children:"Run Data"})}),(0,a.jsx)(tU.A,{sx:{p:0},children:(0,a.jsx)(na,{conversationId:y,refreshToken:null==z?void 0:z.resourceVersion})})]})]})};return(0,a.jsxs)(nj,{elevation:2,children:[(0,a.jsxs)(nk,{sx:{display:"flex",alignItems:"flex-start",justifyContent:"space-between"},children:[(0,a.jsxs)(s.default,{children:[(0,a.jsx)(c.A,{variant:"h6",children:"Flow Debugger"}),(0,a.jsxs)(c.A,{variant:"caption",color:"textSecondary",display:"block",children:["Click a node to toggle a breakpoint",S&&S.length>0?" \xb7 ".concat(S.length," active"):""]})]}),(0,a.jsxs)(s.default,{sx:{display:"flex",alignItems:"center",gap:.5},children:[(0,a.jsx)(u.A,{title:U.conversation?"Hide Conversation":"Show Conversation",children:(0,a.jsx)(h.A,{size:"small",onClick:()=>e_("conversation"),color:U.conversation?"primary":"default","aria-label":U.conversation?"Hide Conversation":"Show Conversation",children:(0,a.jsx)(tB.A,{fontSize:"small"})})}),(0,a.jsx)(u.A,{title:U.tracker?"Hide Execution Tracker":"Show Execution Tracker",children:(0,a.jsx)(h.A,{size:"small",onClick:()=>e_("tracker"),color:U.tracker?"primary":"default","aria-label":U.tracker?"Hide Execution Tracker":"Show Execution Tracker",children:(0,a.jsx)(R.A,{fontSize:"small"})})}),(0,a.jsx)(u.A,{title:U.detail?"Hide Detail":"Show Detail",children:(0,a.jsx)(h.A,{size:"small",onClick:()=>e_("detail"),color:U.detail?"primary":"default","aria-label":U.detail?"Hide Detail":"Show Detail",children:(0,a.jsx)(tK.A,{fontSize:"small"})})}),N&&(0,a.jsx)(u.A,{title:T?"Exit full screen":"Expand to full screen",children:(0,a.jsx)(h.A,{size:"small",onClick:N,"aria-label":T?"Exit full screen":"Expand to full screen",children:T?(0,a.jsx)(eO.A,{fontSize:"small"}):(0,a.jsx)(eP.A,{fontSize:"small"})})}),E&&(0,a.jsx)(u.A,{title:"Close debugger",children:(0,a.jsx)(h.A,{size:"small",onClick:E,"aria-label":"Close debugger",children:(0,a.jsx)(eF.A,{fontSize:"small"})})})]})]}),(0,a.jsx)(nI,{children:0===eR.length?(0,a.jsx)(s.default,{sx:{display:"flex",alignItems:"center",justifyContent:"center",width:"100%",p:3},children:(0,a.jsx)(c.A,{variant:"body2",color:"textSecondary",children:"All sections are hidden — use the toolbar toggles above to show a section."})}):eR.map((e,t)=>(0,a.jsxs)(o.Fragment,{children:[(e=>{let t="tracker"!==e,n="conversation"===e?B:"detail"===e?X:void 0;return(0,a.jsxs)(s.default,{sx:{...t?{width:n,flexShrink:0}:{flexGrow:1,minWidth:300},display:"flex",flexDirection:"column",overflow:"hidden",minHeight:0},children:[(e=>{let t=eR.indexOf(e);return(0,a.jsxs)(s.default,{sx:{display:"flex",alignItems:"center",justifyContent:"space-between",px:1,py:.5,borderBottom:"1px solid ".concat(D.palette.divider)},children:[(0,a.jsx)(c.A,{variant:"subtitle2",noWrap:!0,children:nv[e]}),(0,a.jsxs)(s.default,{sx:{display:"flex"},children:[(0,a.jsx)(u.A,{title:"Move left",children:(0,a.jsx)("span",{children:(0,a.jsx)(h.A,{size:"small",onClick:()=>eW(e,-1),disabled:t<=0,"aria-label":"Move ".concat(nv[e]," left"),children:(0,a.jsx)(Q.A,{fontSize:"small"})})})}),(0,a.jsx)(u.A,{title:"Move right",children:(0,a.jsx)("span",{children:(0,a.jsx)(h.A,{size:"small",onClick:()=>eW(e,1),disabled:t<0||t>=eR.length-1,"aria-label":"Move ".concat(nv[e]," right"),children:(0,a.jsx)(tH.A,{fontSize:"small"})})})}),(0,a.jsx)(u.A,{title:"Hide section",children:(0,a.jsx)(h.A,{size:"small",onClick:()=>e_(e),"aria-label":"Hide ".concat(nv[e]),children:(0,a.jsx)(eF.A,{fontSize:"small"})})})]})]})})(e),eU[e]]},e)})(e),t<eR.length-1&&((e,t)=>{let n="tracker"!==e?e:"tracker"!==t?t:null;if(!n)return null;let o="tracker"!==e?1:-1;return(0,a.jsx)(nT,{onPointerDown:e=>eq(n,o,e),"aria-label":"Resize ".concat(nv[n]," section")},"resizer-".concat(e,"-").concat(t))})(e,eR[t+1])]},e))}),(0,a.jsxs)(nE,{children:[(0,a.jsx)(m.A,{variant:"outlined",size:"small",onClick:eb,disabled:I||F<=0,children:"Previous"}),(0,a.jsx)(m.A,{variant:"contained",size:"small",onClick:ew,disabled:I||-1===F,children:x.executionTrace&&F<x.executionTrace.length-1?"Next Trace Step":"Step Next"}),w&&(0,a.jsx)(m.A,{variant:"outlined",size:"small",onClick:w,disabled:I,children:"Step Over"}),(0,a.jsx)(m.A,{variant:"contained",color:"secondary",size:"small",onClick:A,disabled:I,children:"Continue"}),(0,a.jsx)(m.A,{variant:"outlined",color:"error",size:"small",onClick:j,disabled:I,children:"Stop"})]})]})},nz=(0,tO.h)("frontend/components/Chat/ExecutedFlowPanel"),nM={start:tQ.vm,process:tQ.Uw,finish:tQ.IK,mcp:tQ.v2,subflow:tQ.lA,resource:tQ.z9,signal:tQ.z3},nD={custom:tY.jY,mcpEdge:tY.oY,resourceEdge:tY.sZ},nR=e=>{let{flowId:t,flowSnapshot:n,executedNodeIds:r,liveActivity:l,onClose:i}=e,p=(0,k.A)(),[g,f]=(0,o.useState)(null),[m,v]=(0,o.useState)(!0),[x,y]=(0,o.useState)(null),[b,w,A]=(0,tX.ck)([]),[j,I,S]=(0,tX.fM)([]);(0,o.useEffect)(()=>{let e=!1;return(async()=>{v(!0),y(null);try{if(n&&Array.isArray(n.nodes)){e||f(n);return}if(!t)throw Error("No agent is associated with this conversation yet.");nz.debug("Loading flow definition for ID: ".concat(t));let a=await tJ.g.getFlow(t);if(!a)throw Error("Flow with ID ".concat(t," not found."));e||f(a)}catch(t){nz.error("Error loading flow definition:",t),e||(y(t instanceof Error?t.message:"Failed to load the agent."),f(null))}finally{e||v(!1)}})(),()=>{e=!0}},[t,n]),(0,o.useEffect)(()=>{g&&(w(g.nodes.map(e=>({...e,draggable:!1,selectable:!1,connectable:!1}))),I(g.edges.map(e=>({...e,selectable:!1}))))},[g,w,I]);let C=(0,o.useMemo)(()=>new Set(r),[r]),[E,T]=(0,o.useState)(()=>Date.now());(0,o.useEffect)(()=>{if(!l)return;let e=()=>Object.values(l.byNode).some(e=>Date.now()-e.ts<4e3);if(!e())return;let t=setInterval(()=>{T(Date.now()),e()||clearInterval(t)},350);return()=>clearInterval(t)},[l]);let N=(0,o.useMemo)(()=>b.map(e=>{let t=C.has(e.id),n=null==l?void 0:l.byNode[e.id],a=!!n&&E-n.ts<4e3;return{...e,style:{...e.style,opacity:t||a?1:.4,border:a?"2px solid ".concat(p.palette.primary.main):t?"2px solid ".concat(p.palette.success.main):"1px solid ".concat(p.palette.divider),boxShadow:a?"0 0 10px ".concat(p.palette.primary.light):t?"0 0 8px ".concat(p.palette.success.light):void 0}}}),[b,C,l,E,p]);return(0,a.jsxs)(s.default,{sx:{display:"flex",flexDirection:"column",height:"100%",borderLeft:1,borderColor:"divider",minWidth:0},children:[(0,a.jsxs)(s.default,{sx:{display:"flex",alignItems:"center",gap:1,px:1.5,py:1,borderBottom:1,borderColor:"divider",flexShrink:0},children:[(0,a.jsx)(R.A,{fontSize:"small",color:"action"}),(0,a.jsx)(c.A,{variant:"subtitle2",sx:{flex:1,minWidth:0},noWrap:!0,children:"Executed Steps"}),(0,a.jsx)(u.A,{title:"Hide panel",children:(0,a.jsx)(h.A,{size:"small",onClick:i,"aria-label":"Hide executed steps panel",children:(0,a.jsx)(eF.A,{fontSize:"small"})})})]}),(0,a.jsx)(s.default,{sx:{flex:1,minHeight:0,position:"relative"},children:m?(0,a.jsx)(s.default,{sx:{display:"flex",justifyContent:"center",alignItems:"center",height:"100%"},children:(0,a.jsx)(eY.default,{})}):x?(0,a.jsx)(d.A,{severity:"info",sx:{m:2},children:x}):(0,a.jsx)(tX.Ln,{children:(0,a.jsx)(tX.Gc,{nodes:N,edges:j,onNodesChange:A,onEdgesChange:S,nodeTypes:nM,edgeTypes:nD,fitView:!0,attributionPosition:"bottom-right",nodesDraggable:!1,nodesConnectable:!1,elementsSelectable:!1,panOnDrag:!0,zoomOnScroll:!0,zoomOnPinch:!0,zoomOnDoubleClick:!1})})})]})};function nF(e){var t;return null==e||null==(t=e.nodes)?void 0:t.find(e=>{var t,n;return(null!=(n=null==e?void 0:e.type)?n:null==e||null==(t=e.data)?void 0:t.type)==="start"})}var nP=n(94929),nO=n(74879),n_=n(29155),nW=n(63650),nq=n(49479);let nL=(0,tO.h)("frontend/components/Chat/index");function nU(e){let t=(0,o.useRef)(e);return t.current=e,(0,o.useCallback)(function(){for(var e=arguments.length,n=Array(e),a=0;a<e;a++)n[a]=arguments[a];return t.current(...n)},[])}function nH(e){var t,n;if(Array.isArray(e.content))return e.content;let a="string"==typeof e.content?e.content:"",o=null!=(t=e.attachments)?t:[],r=o.filter(e=>"document"===e.type&&!e.content.startsWith("data:")),l=o.filter(e=>"image"===e.type),i=o.filter(e=>"image"!==e.type&&!r.includes(e));if(r.length>0&&(a+="\n\n"+r.map(e=>"[DOCUMENT]: ".concat(e.content)).join("\n\n")),0===l.length&&0===i.length)return a;let s=[];for(let e of(a.trim()&&s.push({type:"text",text:a}),l))s.push({type:"image_url",image_url:{url:e.content}});for(let e of i)if("audio"===e.type){let t=/^data:([^;,]+);base64,([\s\S]*)$/.exec(e.content),a=null!=(n=e.mimeType)?n:null==t?void 0:t[1];t&&("audio/wav"===a||"audio/mpeg"===a)?s.push({type:"input_audio",input_audio:{data:t[2],format:"audio/mpeg"===a?"mp3":"wav"}}):s.push({type:"audio_url",audio_url:{url:e.content,mime_type:a}}),e.transcript&&s.push({type:"text",text:"[Audio transcript]: ".concat(e.transcript)})}else"video"===e.type?s.push({type:"video_url",video_url:{url:e.content,mime_type:e.mimeType}}):s.push({type:"file",file:{file_data:e.content,filename:e.originalName,mime_type:e.mimeType}});return s}let nB=/cancelled by user|execution cancelled/i,nK=e=>{var t,n;return(null==e?void 0:e.code)==="cancelled"||(null==e||null==(t=e.error)?void 0:t.code)==="cancelled"||[null==e?void 0:e.message,"string"==typeof(null==e||null==(n=e.body)?void 0:n.error)?e.body.error:void 0].some(e=>"string"==typeof e&&nB.test(e))},nG=()=>{var e,t,n,r,O,_,W;let q=(0,l.useRouter)(),L=(0,k.A)(),U=(0,i.A)(L.breakpoints.down("lg"),{noSsr:!0}),[H,B]=(0,o.useState)([]),[K,G]=(0,o.useState)(!0),[X,J]=(0,o.useState)(null),[Q,Y]=(0,o.useState)(null),[V,Z]=(0,o.useState)(!1),[$,ee]=(0,o.useState)(null),[et,en]=(0,P.Mj)(P.Zg.CURRENT_CONVERSATION_ID,null),ea=(0,o.useRef)(et),eo=(0,o.useRef)(new Map),er=(0,o.useRef)(0),el=(0,o.useCallback)(e=>{let t=er.current+1;er.current=t;let n=ea.current;if(n===e)return void en(e);let a=n?"".concat(n,"\0"):null,o=a?[...eo.current.entries()].filter(e=>{let[t]=e;return t.startsWith(a)}).map(e=>{let[,t]=e;return t}):[];if(0===o.length){ea.current=e,en(e);return}Promise.allSettled(o.map(e=>e())).then(()=>{er.current===t&&(ea.current=e,en(e))})},[en]),[ei,es]=(0,P.Mj)(P.Zg.LAST_PICKED_FLOW_ID,null),[ed,ec]=(0,o.useState)(!1),[eh,ep]=(0,o.useState)(new Set),eg=(0,o.useCallback)((e,t)=>{e&&ep(n=>{if(t===n.has(e))return n;let a=new Set(n);return t?a.add(e):a.delete(e),a})},[]),[ef,em]=(0,o.useState)({}),ev=(0,o.useRef)(!1),[ex,ey]=(0,o.useState)(null),[eb,ew]=(0,o.useState)([]),[eA,ej]=(0,o.useState)(!1),[ek,eI]=(0,o.useState)(!1),[eS,eC]=(0,o.useState)(""),[eE,eT]=(0,o.useState)(!1),[eD,eR]=(0,o.useState)(null),[eF,eP]=(0,o.useState)(null),[eO,e_]=(0,o.useState)(null),[eq,eY]=(0,o.useState)(null),[eV,eZ]=(0,o.useState)(null),[e$,e0]=(0,o.useState)(null),[e5,e6]=(0,o.useState)(!1),[e3,e4]=(0,o.useState)(null),[e8,e7]=(0,o.useState)(!1),[e9,te]=(0,o.useState)(()=>{let e=Number(window.localStorage.getItem("flujo-debugger-width"));return Number.isFinite(e)&&e>0?e:0}),[tt,tn]=(0,o.useState)(()=>"1"===window.localStorage.getItem("flujo-debugger-expanded"));(0,o.useEffect)(()=>{window.localStorage.setItem("flujo-debugger-expanded",tt?"1":"0")},[tt]);let[ta,to]=(0,o.useState)(()=>"1"===window.localStorage.getItem("flujo-workflow-panel-visible"));(0,o.useEffect)(()=>{window.localStorage.setItem("flujo-workflow-panel-visible",ta?"1":"0")},[ta]);let[tr,tl]=(0,o.useState)(()=>{let e=Number(window.localStorage.getItem("flujo-workflow-panel-width"));return Number.isFinite(e)&&e>0?e:320}),ti=(0,o.useCallback)(e=>{e.preventDefault();let t=e.clientX,n=0;tl(e=>(n=e,e));let a=document.body.style.userSelect,o=document.body.style.cursor;document.body.style.userSelect="none",document.body.style.cursor="col-resize";let r=e=>{tl(Math.min(Math.max(n+(t-e.clientX),240),Math.round(.7*window.innerWidth)))},l=()=>{window.removeEventListener("pointermove",r),window.removeEventListener("pointerup",l),document.body.style.userSelect=a,document.body.style.cursor=o,tl(e=>(e>0&&window.localStorage.setItem("flujo-workflow-panel-width",String(Math.round(e))),e))};window.addEventListener("pointermove",r),window.addEventListener("pointerup",l)},[]),ts=(0,o.useCallback)(e=>{e.preventDefault();let t=document.body.style.userSelect,n=document.body.style.cursor;document.body.style.userSelect="none",document.body.style.cursor="col-resize";let a=e=>{te(Math.min(Math.max(window.innerWidth-e.clientX,360),Math.round(.85*window.innerWidth)))},o=()=>{window.removeEventListener("pointermove",a),window.removeEventListener("pointerup",o),document.body.style.userSelect=t,document.body.style.cursor=n,te(e=>(e>0&&window.localStorage.setItem("flujo-debugger-width",String(Math.round(e))),e))};window.addEventListener("pointermove",a),window.addEventListener("pointerup",o)},[]),[td,tc]=(0,o.useState)(()=>{let e=Number(window.localStorage.getItem("flujo-chat-sidebar-width"));return Number.isFinite(e)&&e>0?e:300}),[tu,th]=(0,o.useState)(()=>"1"===window.localStorage.getItem("flujo-chat-sidebar-collapsed")),[tp,tg]=(0,o.useState)(!1),tf=U?!tp:tu,tm=(0,o.useCallback)(()=>{if(U)return void tg(e=>!e);th(e=>{let t=!e;return window.localStorage.setItem("flujo-chat-sidebar-collapsed",t?"1":"0"),t})},[U]),tx=nU(e=>{el(e),U&&tg(!1)}),ty=(0,o.useCallback)(e=>{e.preventDefault();let t=document.body.style.userSelect,n=document.body.style.cursor;document.body.style.userSelect="none",document.body.style.cursor="col-resize";let a=e=>{tc(Math.min(Math.max(e.clientX,220),560))},o=()=>{window.removeEventListener("pointermove",a),window.removeEventListener("pointerup",o),document.body.style.userSelect=t,document.body.style.cursor=n,tc(e=>(e>0&&window.localStorage.setItem("flujo-chat-sidebar-width",String(Math.round(e))),e))};window.addEventListener("pointermove",a),window.addEventListener("pointerup",o)},[]),[tb,tA]=(0,o.useState)(null),[tj,tk]=(0,o.useState)(tV),[tI,tS]=(0,o.useState)([]),[tC,tE]=(0,o.useState)(e1),[tT,tM]=(0,o.useState)([]),[tD,tR]=(0,o.useState)(new Set),[tF,tP]=(0,o.useState)([]),[tO,t_]=(0,o.useState)(null),tq=(0,o.useRef)(null),tL=(0,o.useRef)(null),tU=(0,o.useRef)(null),tH=(0,o.useRef)(-1),tB=(0,o.useRef)(new Map);(0,o.useEffect)(()=>{ea.current=et},[et]);let tK=(0,o.useRef)(new Set),tG=(0,o.useRef)(null),tX=(0,o.useRef)(!1),tQ=(0,o.useRef)(new Set),tY=(0,o.useRef)(new Set),[t$,t0]=(0,o.useState)(new Set),t1=(0,o.useCallback)((e,t)=>{e&&(t?tY.current.add(e):tY.current.delete(e),t0(new Set(tY.current)))},[]),t2=(0,o.useRef)(null),t5=(0,o.useRef)(!0),[t6,t3]=(0,o.useState)(!1),t4=(0,o.useCallback)(function(){let e=arguments.length>0&&void 0!==arguments[0]?arguments[0]:"auto",t=t2.current;t&&t.scrollTo({top:t.scrollHeight,behavior:e})},[]),t8=(0,o.useCallback)(()=>{let e=t2.current;if(!e)return;let t=e.scrollHeight-e.scrollTop-e.clientHeight<80;t5.current=t,t3(!t)},[]),t7=(0,o.useCallback)(()=>{t5.current=!0,t3(!1),t4("smooth")},[t4]);(0,o.useEffect)(()=>{t5.current=!0,t3(!1)},[et]),(0,o.useEffect)(()=>{t5.current&&t4("auto")},[null==Q?void 0:Q.messages,t4]);let t9=(0,o.useRef)(null);(0,o.useEffect)(()=>{t9.current=tO},[tO]),(0,o.useEffect)(()=>{let e=window.location.origin+"/v1";tq.current=new n_.Ay({baseURL:e,apiKey:"FLUJO",dangerouslyAllowBrowser:!0,maxRetries:0,timeout:18e6})},[]),(0,o.useEffect)(()=>{(async()=>{nL.debug("Loading flows");try{let e=await tJ.g.loadFlows();ew(e)}catch(e){nL.error("Error loading flows:",e)}})()},[]);let ne=(0,o.useCallback)((e,t)=>{var n;let a=null!=(n=null==t?void 0:t.silent)&&n,o=async()=>{nL.debug("Fetching conversation list from backend",{silent:a}),a||(G(!0),J(null));let t=[],n=!1;try{for(let e of t=(await nq.O.listConversations()).filter(e=>!tQ.current.has(e.id)).sort((e,t)=>{var n,a;return(null!=(n=t.lastUserMessageAt)?n:t.updatedAt)-(null!=(a=e.lastUserMessageAt)?a:e.updatedAt)}))tK.current.delete(e.id);B(e=>{let n=e.filter(e=>tK.current.has(e.id)),a=n.length>0?[...n,...t].sort((e,t)=>{var n,a;return(null!=(n=t.lastUserMessageAt)?n:t.updatedAt)-(null!=(a=e.lastUserMessageAt)?a:e.updatedAt)}):t;return((e,t)=>e.length===t.length&&e.every((e,n)=>{var a,o,r,l;let i=t[n];return e.id===i.id&&e.title===i.title&&e.flowId===i.flowId&&e.status===i.status&&(null==(a=e.recovery)?void 0:a.classification)===(null==(o=i.recovery)?void 0:o.classification)&&(null==(r=e.recovery)?void 0:r.updatedAt)===(null==(l=i.recovery)?void 0:l.updatedAt)&&e.plannedExecutionId===i.plannedExecutionId&&e.source===i.source&&e.parentConversationId===i.parentConversationId&&e.rootConversationId===i.rootConversationId&&e.createdAt===i.createdAt&&e.updatedAt===i.updatedAt&&e.lastUserMessageAt===i.lastUserMessageAt}))(e,a)?e:a}),nL.info("Fetched ".concat(t.length," conversations for the list"))}catch(e){n=!0,nL.error("Error fetching conversation list:",e),a||(J("Failed to load conversation history."),B([]))}finally{if(a||G(!1),a||n)return;let o=void 0!==e?e:ea.current,r=ea.current;if(o&&(e=>t.some(t=>t.id===e)||tK.current.has(e))(o))o!==r&&(nL.debug("Setting currentConversationId to ".concat(o," after fetch/operation.")),el(o));else if(t.length>0){let e=t[0].id;e!==r&&(nL.debug("Selecting most recent conversation ".concat(e," after fetch/operation.")),el(e))}else null===r||tK.current.has(r)||(nL.debug("No conversations available after fetch/operation, clearing selection."),el(null))}};if(!a)return o();if(tG.current)return tX.current=!0,tG.current;let r=(async()=>{do tX.current=!1,await o();while(tX.current)})().finally(()=>{tG.current===r&&(tG.current=null)});return tG.current=r,r},[el]);(0,o.useEffect)(()=>{ne()},[]),(0,o.useEffect)(()=>{let e=null,t=null,n=null,a=!1,o=0,r=()=>{e&&clearTimeout(e),t&&clearTimeout(t),e=null,t=null},l=()=>{e&&clearTimeout(e),a||"visible"!==document.visibilityState||(e=setTimeout(()=>{e=null,o=Date.now(),ne(void 0,{silent:!0}).finally(l)},3e4))},i=()=>{a||"visible"!==document.visibilityState||t||(t=setTimeout(()=>{t=null,o=Date.now(),ne(void 0,{silent:!0}).finally(l)},Math.max(200,5e3-(Date.now()-o))))},s=()=>{n||a||"visible"!==document.visibilityState||(n=nq.O.subscribeToSidebarEvents({onEvent:i}))},d=()=>{null==n||n.close(),n=null},c=()=>{if("visible"!==document.visibilityState){r(),d();return}s(),o=Date.now(),ne(void 0,{silent:!0}).finally(l)};return o=Date.now(),s(),l(),document.addEventListener("visibilitychange",c),()=>{a=!0,r(),d(),document.removeEventListener("visibilitychange",c)}},[ne]);let nt=(0,o.useCallback)(async e=>{if(tK.current.has(e))return void nL.debug("Skipping detail fetch for client-only conversation",{conversationId:e});if(ea.current!==e){nL.debug("Detail fetch requested for non-viewed conversation; refreshing list instead",{conversationId:e}),ne(void 0,{silent:!0});return}nL.debug("Fetching detailed conversation",{conversationId:e}),Z(!0),ee(null);try{let t=await nq.O.getConversation(e);if(ea.current!==e)return void nL.debug("Discarding stale detailed conversation response",{fetchedId:e,currentId:ea.current});void 0===t.mcpAppContexts||tB.current.has(e)||tB.current.set(e,{...t.mcpAppContexts}),Y(t),B(n=>n.map(n=>{var a;return n.id===e?{...n,title:t.title,flowId:t.flowId,updatedAt:t.updatedAt,status:null!=(a=t.status)?a:n.status}:n}).sort((e,t)=>{var n,a;return(null!=(n=t.lastUserMessageAt)?n:t.updatedAt)-(null!=(a=e.lastUserMessageAt)?a:e.updatedAt)})),nL.info("Fetched detailed conversation successfully",{conversationId:e})}catch(t){if(nL.error("Error fetching detailed conversation:",{conversationId:e,err:t}),ea.current!==e)return;t instanceof nq.b&&404===t.status?(ee("Conversation ".concat(e," not found.")),el(null),ne()):ee("Failed to load details for conversation ".concat(e,".")),Y(null)}finally{ea.current===e&&Z(!1)}},[ne,el]);(0,o.useEffect)(()=>{eR(null),eZ(null),et?nt(et):(Y(null),Z(!1),ee(null))},[et,nt]),(0,o.useEffect)(()=>{if(Q){var e;ej(null!=(e=Q.requireApproval)&&e)}},[null==Q?void 0:Q.id]);let nn=(0,o.useCallback)(async e=>{if(ej(e),et)try{await nq.O.updateConversationApproval(et,e)}catch(e){nL.warn("Failed to persist requireApproval setting",{conversationId:et,err:e})}},[et]),na=H.find(e=>e.id===et)||null,no=(0,o.useMemo)(()=>{let e={};for(let t of eb)t.id&&(e[t.id]=t.name);return e},[eb]),nr=(0,o.useMemo)(()=>eb.find(e=>e.id===(null==Q?void 0:Q.flowId))||null,[eb,null==Q?void 0:Q.flowId]),nl=(0,o.useMemo)(()=>{var e;return(null==nr||null==(e=nr.nodes)?void 0:e.map(e=>({id:e.id,label:e.data.label||e.id})))||[]},[nr]),ni=(0,o.useMemo)(()=>{var e;return function(e){var t,n,a,o;let r=new Set;return null==(t=e.messages)||t.forEach(e=>{(null==e?void 0:e.processNodeId)&&r.add(e.processNodeId)}),null==(n=e.nodeExecutionTracker)||n.forEach(e=>{(null==e?void 0:e.nodeId)&&r.add(e.nodeId)}),null==(a=e.executionTrace)||a.forEach(e=>{(null==e?void 0:e.nodeId)&&r.add(e.nodeId)}),null==(o=e.sseVisitedIds)||o.forEach(e=>{e&&r.add(e)}),Array.from(r)}({messages:null==Q?void 0:Q.messages,nodeExecutionTracker:null==e3||null==(e=e3.trackingInfo)?void 0:e.nodeExecutionTracker,executionTrace:null==e3?void 0:e3.executionTrace,sseVisitedIds:tD})},[null==Q?void 0:Q.messages,e3,tD]);(0,o.useEffect)(()=>{tR(new Set),tS([])},[null==Q?void 0:Q.id]);let ns=(0,o.useMemo)(()=>{var e,t,n;let a=e=>!!e&&nl.some(t=>t.id===e);if(a(eV))return eV;if(a(null==Q?void 0:Q.currentNodeId))return Q.currentNodeId;let o=null!=(t=null==Q?void 0:Q.messages)?t:[];for(let e=o.length-1;e>=0;e--){let t=o[e];if("assistant"===t.role&&a(t.processNodeId))return t.processNodeId}return null!=(n=null==(e=nl[0])?void 0:e.id)?n:null},[eV,Q,nl]),nd=async e=>{var t,n,a,o;nL.debug("Attempting to create new conversation"),ey(null);let r="string"!=typeof e||eu(e)?void 0:eb.find(t=>t.id===e),l=ei&&!eu(ei)?eb.find(e=>e.id===ei):void 0,i=(null==(t=null!=(a=null!=(n=null!=r?r:l)?n:eb.find(e=>e.favorite))?a:eb[0])?void 0:t.id)||null;if(!i){nL.error("Cannot create conversation: No flows available or first flow has no ID."),ey("Cannot create a new conversation: No agents available.");return}let s=(0,nO.A)(),d=Date.now(),c={id:s,title:"New Conversation",flowId:i,createdAt:d,updatedAt:d};try{nL.info("Sending request to create conversation on backend",{payload:JSON.stringify(c)});let e=await nq.O.createConversation(c);nL.info("Successfully created conversation on backend",{conversationId:e.id}),B(t=>[e,...t].sort((e,t)=>{var n,a;return(null!=(n=t.lastUserMessageAt)?n:t.updatedAt)-(null!=(a=e.lastUserMessageAt)?a:e.updatedAt)})),el(e.id),Y({id:e.id,title:e.title,flowId:e.flowId,createdAt:e.createdAt,updatedAt:e.updatedAt,messages:[]}),Z(!1),ee(null)}catch(t){nL.error("Error creating conversation on backend:",t);let e="Failed to create conversation on the server.";t instanceof nq.b?e+=" Error: ".concat((null==(o=t.body)?void 0:o.error)||t.message):t instanceof Error&&(e+=" Error: ".concat(t.message)),ey(e)}},nc=(0,o.useRef)(!1);(0,o.useEffect)(()=>{if(nc.current||0===eb.length)return;let e=new URLSearchParams(window.location.search).get("flow");if(!e){nc.current=!0;return}nc.current=!0,eb.some(t=>t.id===e)&&!eu(e)&&nd(e),q.replace("/chat")},[eb]);let[nu,nh]=(0,o.useState)(!1),np=async e=>{ey(null);let t=(0,nO.A)(),{flow:n}=await nq.O.synthesizeQuickChat({conversationId:t,modelId:e.modelId,servers:e.servers,systemPrompt:e.systemPrompt}),a=Date.now(),o=await nq.O.createConversation({id:t,title:"Quick Chat",flowId:n.id,flowSnapshot:n,createdAt:a,updatedAt:a});B(e=>[o,...e].sort((e,t)=>{var n,a;return(null!=(n=t.lastUserMessageAt)?n:t.updatedAt)-(null!=(a=e.lastUserMessageAt)?a:e.updatedAt)})),el(o.id),Y({id:o.id,title:o.title,flowId:o.flowId,createdAt:o.createdAt,updatedAt:o.updatedAt,messages:[]}),Z(!1),ee(null),nh(!1)},ng=(0,o.useCallback)(e=>{nL.debug("Updating detailed conversation state locally",{conversationId:e.id});let t={...e,updatedAt:Date.now()};Y(t),B(e=>e.map(e=>e.id===t.id?{...e,title:t.title,updatedAt:t.updatedAt}:e).sort((e,t)=>{var n,a;return(null!=(n=t.lastUserMessageAt)?n:t.updatedAt)-(null!=(a=e.lastUserMessageAt)?a:e.updatedAt)}))},[]),nf=(0,o.useCallback)(()=>{tU.current&&(nL.debug("Closing execution event stream"),tU.current.close(),tU.current=null)},[]),nm=(0,o.useCallback)((e,t)=>{B(n=>{let a=n.findIndex(t=>t.id===e);if(-1===a||n[a].status===t)return n;let o=[...n];return o[a]={...o[a],status:t},o})},[]),nv=(0,o.useCallback)(e=>{var t,n,a,o,r,l,i;if("number"==typeof e.seq){if(e.seq<=tH.current)return;tH.current=e.seq}("run:start"===e.type||"run:done"===e.type||"run:paused"===e.type||"breakpoint:hit"===e.type||"subflow:start"===e.type||"subflow:done"===e.type||"node:enter"===e.type||"node:exit"===e.type||"resource:read"===e.type||"resource:write"===e.type||"error"===e.type)&&tS(t=>{if("run:start"===e.type)return[e];let n=[...t,e];return n.length>2e3?n.slice(n.length-2e3):n});let s=e=>tA(t=>{var n,a,o,r;return{totalTokens:null!=(a=null!=(n=e.totalTokens)?n:null==t?void 0:t.totalTokens)?a:0,activeNode:void 0!==e.activeNode?e.activeNode:null!=(o=null==t?void 0:t.activeNode)?o:null,startedAt:null!=(r=null==t?void 0:t.startedAt)?r:Date.now(),lastEventAt:Date.now()}}),d=e=>tk(t=>{let n=Date.now(),a={byNode:{...t.byNode},byResource:{...t.byResource},byResourceName:{...t.byResourceName},resourceVersion:t.resourceVersion};return e(a),function(e,t){let n=e=>{let n={};for(let[a,o]of Object.entries(e))t-o.ts<4e3&&(n[a]=o);return n};return{byNode:n(e.byNode),byResource:n(e.byResource),byResourceName:n(e.byResourceName),resourceVersion:e.resourceVersion}}(a,n)});if(null!=e.laneIndex)switch(tE(t=>(function(e,t){var n,a,o,r,l,i;let s=arguments.length>2&&void 0!==arguments[2]?arguments[2]:Date.now(),d=t.laneIndex,c=t.laneCount;if(null==d||null==c)return e;let u=("subflow:start"===t.type||"subflow:done"===t.type)&&1===t.depth;if(u&&"subflow:start"===t.type){let r=null==(n=t.node)?void 0:n.nodeId,l=e.ownerNodeId&&r&&e.ownerNodeId!==r?{}:{...e.byIndex};return e2(l,c,s),l[d]={laneIndex:d,laneCount:c,label:t.laneTitle||function(e,t,n){let a=e.subflowName||e.subflowId;return a?"".concat(a," ").concat(t+1,"/").concat(n):"Lane ".concat(t+1,"/").concat(n)}(t,d,c),laneConversationId:null!=(o=t.laneConversationId)?o:null==(a=l[d])?void 0:a.laneConversationId,status:"running",lastEventAt:s},{ownerNodeId:null!=r?r:e.ownerNodeId,byIndex:l}}if(u&&"subflow:done"===t.type){let n={...e.byIndex};e2(n,c,s);let a=n[d];return n[d]={...a,label:a.label&&"pending"!==a.status?a.label:t.laneTitle||a.label,laneConversationId:null!=(l=a.laneConversationId)?l:t.laneConversationId,status:"capped"===t.status?"completed":t.status,activity:void 0,lastEventAt:s},{ownerNodeId:null!=(i=e.ownerNodeId)?i:null==(r=t.node)?void 0:r.nodeId,byIndex:n}}let h=function(e){switch(e.type){case"node:enter":var t,n;return(null==(t=e.node)?void 0:t.nodeName)||(null==(n=e.node)?void 0:n.nodeId)||void 0;case"tool:call":return e.name;case"tool:progress":return e.message?"".concat(e.name," — ").concat(e.message):e.name;case"subflow:start":return"↳ ".concat(e.subflowName||e.subflowId);case"handoff":return"→ ".concat(e.toNodeId);default:return}}(t);if(void 0===h)return e;let p=e.byIndex[d];if(p&&p.activity===h&&"pending"!==p.status||p&&("completed"===p.status||"error"===p.status))return e;let g={...e.byIndex};e2(g,c,s);let f=g[d];return g[d]={...f,status:"pending"===f.status?"running":f.status,activity:h,lastEventAt:s},{ownerNodeId:e.ownerNodeId,byIndex:g}})(t,e)),e.type){case"node:enter":if(null==(t=e.node)?void 0:t.nodeId){let t=e.node.nodeId;d(e=>{e.byNode[t]={kind:"active",ts:Date.now()}}),tR(e=>e.has(t)?e:new Set(e).add(t))}s({});return;case"tool:call":case"tool:progress":case"subflow:start":case"handoff":s({});return}switch(e.type){case"run:start":tA({totalTokens:0,activeNode:null,startedAt:Date.now(),lastEventAt:Date.now()}),tk(tV),tE(e1),tM([]),e.conversationId&&(nm(e.conversationId,"running"),t1(e.conversationId,!1));break;case"model:delta":s({}),Y(t=>{var n,a,o,r,l,i,s,d,c,u,h;if(!t||t.id!==e.conversationId)return t;let p=t.messages.findIndex(t=>t.id===e.messageId),g=p>=0?t.messages[p]:{id:e.messageId,role:"assistant",content:"",timestamp:e.timestamp,processNodeId:null==(n=e.node)?void 0:n.nodeId};if("assistant"!==g.role)return t;let f=[...null!=(a=g.tool_calls)?a:[]],m=e.toolCallDelta;if(m){let t=f[m.index];f[m.index]={id:null!=(r=null!=(o=m.id)?o:null==t?void 0:t.id)?r:"pending_".concat(e.messageId,"_").concat(m.index),type:"function",function:{name:"".concat(null!=(l=null==t?void 0:t.function.name)?l:"").concat(null!=(i=m.nameDelta)?i:""),arguments:"".concat(null!=(s=null==t?void 0:t.function.arguments)?s:"").concat(null!=(d=m.argumentsDelta)?d:"")}}}let v={...g,content:"".concat("string"==typeof g.content?g.content:"").concat(null!=(c=e.delta)?c:""),...e.mediaPart?{media:[...null!=(u=g.media)?u:[],...(null!=(h=g.media)?h:[]).some(t=>{var n,a,o;return t.type===(null==(n=e.mediaPart)?void 0:n.type)&&t.url===(null==(a=e.mediaPart)?void 0:a.url)&&t.resourceUri===(null==(o=e.mediaPart)?void 0:o.resourceUri)})?[]:[e.mediaPart]]}:{},...f.length>0?{tool_calls:f}:{}},x=[...t.messages];return p>=0?x[p]=v:x.push(v),{...t,messages:x}});break;case"model:end":s({}),e.discard&&e.messageId&&Y(t=>{if(!t||t.id!==e.conversationId)return t;let n=t.messages.filter(t=>t.id!==e.messageId);return n.length===t.messages.length?t:{...t,messages:n}});break;case"message":{let t=e.message;s({}),Y(n=>{let a;if(!n||n.id!==e.conversationId)return n;let o=n.messages.findIndex(e=>e.id===t.id);return o>=0?(a=[...n.messages])[o]={...a[o],...t}:a=[...n.messages,t],{...n,messages:a}});break}case"node:changed-files":{s({});let t=null==(n=e.node)?void 0:n.nodeId;if(!t||0===e.changedFiles.length)break;Y(n=>{if(!n||n.id!==e.conversationId)return n;let a=n.messages.findLastIndex(e=>e.processNodeId===t);if(a<0)return n;let o=[...n.messages];return o[a]={...o[a],changedFiles:e.changedFiles.map(e=>{let{path:t,status:n}=e;return{path:t,status:n}})},{...n,messages:o}});break}case"usage":tA(t=>{var n,a,o;return{totalTokens:(null!=(n=null==t?void 0:t.totalTokens)?n:0)+(e.totalTokens||0),activeNode:null!=(a=null==t?void 0:t.activeNode)?a:null,startedAt:null!=(o=null==t?void 0:t.startedAt)?o:Date.now(),lastEventAt:Date.now()}});break;case"node:enter":if(s({activeNode:(null==(a=e.node)?void 0:a.nodeName)||(null==(o=e.node)?void 0:o.nodeId)||null}),null==(r=e.node)?void 0:r.nodeId){let t=e.node.nodeId;d(e=>{e.byNode[t]={kind:"active",ts:Date.now()}}),tR(e=>e.has(t)?e:new Set(e).add(t))}break;case"resource:read":case"resource:write":{let t="resource:read"===e.type?"read":"write";if("resource:write"===e.type&&"snapshot"===e.source&&e.snapshot&&(null==(l=e.node)?void 0:l.nodeId)&&e.conversationId===ea.current){let t=e.node.nodeId,n=e.snapshot.root;nX(e.conversationId),nD(a=>{var o,r,l,i;return eK(a,{serverName:"filesystem",uri:"ui://devcanvas/diff",instanceKey:"snapshot::".concat(t,"::").concat(n),toolName:"snapshot_diff",resultContent:JSON.stringify({snapshotDiff:{nodeId:t,nodeName:null==(o=e.node)?void 0:o.nodeName,root:n,startSnapshot:null==(r=e.snapshot)?void 0:r.startSnapshot,endSnapshot:null==(l=e.snapshot)?void 0:l.endSnapshot,changedFiles:null==(i=e.snapshot)?void 0:i.changedFiles,resourceUri:e.uri}}),updateId:e.seq},Date.now(),Number.MAX_SAFE_INTEGER).state})}d(n=>{var a;let o=Date.now();(null==(a=e.node)?void 0:a.nodeId)&&(n.byNode[e.node.nodeId]={kind:"read"===t?"resource-read":"resource-write",ts:o}),e.server&&e.uri&&(n.byResource[tZ(e.server,e.uri)]={kind:t,ts:o}),e.name&&(n.byResourceName[e.name]={kind:t,ts:o}),"write"===t&&(n.resourceVersion=n.resourceVersion+1)}),s({});break}case"todo:update":tM(null!=(i=e.todos)?i:[]),s({});break;case"tool:call":s({activeNode:e.name});break;case"tool:progress":s({activeNode:e.message?"".concat(e.name," — ").concat(e.message):e.name});break;case"subflow:start":s({activeNode:"↳ ".concat(e.subflowName||e.subflowId)});break;case"handoff":s({activeNode:"→ ".concat(e.toNodeId)});break;case"run:awaiting_approval":e.conversationId&&e.conversationId===ea.current&&eR(e.pendingToolCalls||[]),e.conversationId&&nm(e.conversationId,"awaiting_tool_approval");break;case"run:awaiting_elicitation":e.conversationId&&e.conversationId===ea.current&&eP({elicitationId:e.elicitationId,message:e.message,requestedSchema:e.requestedSchema});break;case"run:awaiting_question":e.conversationId&&e.conversationId===ea.current&&e_({questionId:e.questionId,questions:e.questions});break;case"breakpoint:hit":case"run:paused":ec(!1),e.conversationId&&(eg(e.conversationId,!1),nm(e.conversationId,"paused_debug")),e6(!0);break;case"run:done":if(e.conversationId&&(eg(e.conversationId,!1),nm(e.conversationId,e.status)),e.conversationId===ea.current&&(eP(null),e_(null)),e.conversationId&&t9.current&&e.conversationId!==t9.current)break;tA(null),tk(tV),tE(e1),ec(!1),t_(null),nf(),e.conversationId&&e.conversationId===ea.current?nt(e.conversationId):ne(void 0,{silent:!0});break;case"error":ey(e.message||"Execution error");break;default:s({})}},[nf,nt,ne,eg,nm,t1]),nx=(0,o.useCallback)((e,t)=>(nf(),tH.current=void 0!==t?t-1:-1,tE(e1),new Promise(n=>{let a=!1,o=()=>{a||(a=!0,n())};try{tU.current=nq.O.subscribeToEvents(e,{onEvent:nv,onOpen:o},t),setTimeout(o,1500)}catch(t){nL.error("Failed to open execution event stream",{conversationId:e,err:t}),o()}})),[nv,nf]);(0,o.useEffect)(()=>{if(et&&(null==na?void 0:na.status)==="running"&&t9.current!==et){if(tY.current.has(et))return void nL.debug("Skipping re-attach to a conversation the user just stopped",{conversationId:et});nL.info("Re-attaching to in-progress run",{conversationId:et}),t9.current=et,ec(!0),t_(et),eg(et,!0),tA(e=>null!=e?e:{totalTokens:0,activeNode:null,startedAt:Date.now(),lastEventAt:Date.now()}),nx(et,0)}},[et,null==na?void 0:na.status,nx]);let ny=async e=>{nL.debug("Attempting to delete conversation",{conversationId:e}),ey(null),tQ.current.add(e);let t=tK.current.delete(e);t9.current===e&&(nf(),ec(!1),t_(null),tA(null),tE(e1)),eg(e,!1),em(t=>eJ(t,e));let n=H.filter(t=>t.id!==e);B(n);let a=et;et===e&&(n.length>0?(a=n[0].id,nL.debug("Deleted current conversation, selecting next most recent",{nextSelectionId:a})):(a=null,nL.debug("Deleted last conversation, clearing selection")),el(a));try{await nq.O.deleteConversation(e),nL.info("Successfully deleted conversation on backend",{conversationId:e})}catch(n){nL.error("Error deleting conversation:",{conversationId:e,err:n}),ey("Failed to delete conversation ".concat(e,". Please try again.")),tQ.current.delete(e),t&&tK.current.add(e),B(H),el(et)}},nb=async e=>{if(!e.length)return;ey(null);let t=new Set(e);e.forEach(e=>tQ.current.add(e));let n=ea.current;n&&t.has(n)&&t9.current===n&&(nf(),ec(!1),t_(null),tA(null),tE(e1)),e.forEach(e=>{eg(e,!1),em(t=>eJ(t,e))}),B(e=>e.filter(e=>!t.has(e.id))),n&&t.has(n)&&el(null);try{let t=await nq.O.deleteConversations(e);nL.info("Bulk delete succeeded",{requested:e.length,...t})}catch(t){nL.error("Bulk delete failed",{err:t}),ey("Failed to delete conversations. Please try again."),e.forEach(e=>tQ.current.delete(e)),B(H),el(et)}},nw=async e=>{if(nL.debug("Flow selected, attempting to update",{flowId:e,currentConversationId:et}),ey(null),!et){nL.warn("Cannot update flow: No conversation selected."),ey("Please select a conversation first.");return}Q&&Q.id===et&&Y({...Q,flowId:e,updatedAt:Date.now()}),B(t=>t.map(t=>t.id===et?{...t,flowId:e,updatedAt:Date.now()}:t).sort((e,t)=>{var n,a;return(null!=(n=t.lastUserMessageAt)?n:t.updatedAt)-(null!=(a=e.lastUserMessageAt)?a:e.updatedAt)}));try{let t=await nq.O.updateConversationFlow(et,e);nL.info("Successfully updated flowId on backend",{conversationId:et,flowId:e}),Y(e=>e&&e.id===et?(nL.debug("Confirming detailedConversation update from server response",{conversationId:et,flowId:t.flowId}),{...e,flowId:t.flowId,updatedAt:t.updatedAt}):(nL.debug("Skipping detailedConversation update, ID mismatch or null state",{currentDetailedId:null==e?void 0:e.id,targetId:et}),e)),B(e=>e.map(e=>e.id===et?t:e).sort((e,t)=>{var n,a;return(null!=(n=t.lastUserMessageAt)?n:t.updatedAt)-(null!=(a=e.lastUserMessageAt)?a:e.updatedAt)}))}catch(a){nL.error("Error updating flowId on backend:",{conversationId:et,flowId:e,err:a});let n="Failed to update the selected agent.";if(a instanceof nq.b){var t;n+=" Error: ".concat((null==(t=a.body)?void 0:t.error)||a.message)}else a instanceof Error&&(n+=" Error: ".concat(a.message));ey(n),Y(Q),B(H)}},nA=()=>{var e,t;eC(null!=(t=null!=(e=null==Q?void 0:Q.title)?e:null==na?void 0:na.title)?t:""),eI(!0)},nj=async()=>{var e,t;if(eI(!1),!et)return;let n=null!=(t=null!=(e=null==Q?void 0:Q.title)?e:null==na?void 0:na.title)?t:"",a=eS.trim().slice(0,200);if(a&&a!==n){Y(e=>e&&e.id===et?{...e,title:a}:e),B(e=>e.map(e=>e.id===et?{...e,title:a}:e));try{let e=await nq.O.updateConversationTitle(et,a);Y(t=>t&&t.id===et?{...t,title:e.title}:t),B(t=>t.map(t=>t.id===et?{...t,title:e.title}:t))}catch(e){nL.warn("Failed to rename conversation",{conversationId:et,err:e}),Y(e=>e&&e.id===et?{...e,title:n}:e),B(e=>e.map(e=>e.id===et?{...e,title:n}:e)),ey("Failed to rename the conversation.")}}},nk=async function(e){var t;let n,a=arguments.length>1&&void 0!==arguments[1]?arguments[1]:[],o=arguments.length>2?arguments[2]:void 0;if(!e.trim()&&0===a.length)return;if(!Q){nL.error("Cannot send message, detailed conversation not loaded."),ey("Cannot send message: conversation details not loaded.");return}if(!(null==o?void 0:o.fromQueue)&&eh.has(Q.id)){let t=Q.id;if(0!==a.length||eV){let n={id:(0,nO.A)(),content:e,attachments:a,nodeOverride:null!=eV?eV:null,timestamp:Date.now()};em(e=>({...e,[t]:[...eX(e,t),n]})),eZ(null),nL.debug("Run in progress — queued message (not steerable)",{conversationId:t,queuedId:n.id,reason:a.length>0?"attachments":"node-override"});return}{let n=(0,nO.A)(),{delivered:a}=await nq.O.injectMessage(t,e,n);if(a){let a={id:n,role:"user",content:e,timestamp:Date.now()};ng({...Q,messages:[...Q.messages,a]}),nL.debug("Run in progress — injected steering message into the live run",{conversationId:t,messageId:n});return}nL.debug("Steering rejected (run no longer live) — sending as a normal turn",{conversationId:t})}}nL.debug("Sending message",{conversationId:Q.id,contentLength:e.length,attachmentsCount:a.length});let r=Q.messages,l=!r.some(e=>"user"===e.role),i=Q.flowId,s=(null==o?void 0:o.fromQueue)?null!=(t=o.nodeOverride)?t:null:eV;if(s)n=s,(null==o?void 0:o.fromQueue)||eZ(null),nL.debug("Assigning manually picked node ID to user message: ".concat(n));else if(l){let e=nF(eb.find(e=>e.id===i));e?(n=e.id,nL.debug("Assigning start node ID to first user message: ".concat(n))):nL.warn("Could not find start node for flow ".concat(i,". User message will not have a processNodeId."))}else if((null==na?void 0:na.status)==="error"){let e=nF(eb.find(e=>e.id===i));e?(n=e.id,nL.debug("Post-error message: re-driving turn from start node ID: ".concat(n))):nL.warn("Could not find start node for post-error message in flow ".concat(i,". User message will not have a processNodeId."))}else{for(let e=r.length-1;e>=0;e--){let t=r[e];if("assistant"===t.role&&t.processNodeId){n=t.processNodeId,nL.debug("Assigning last assistant node ID to user message: ".concat(n));break}}if(!n){let e=nF(eb.find(e=>e.id===i));e?(n=e.id,nL.debug("No prior assistant node ID found, falling back to start node ID: ".concat(n))):nL.warn("Could not find start node for fallback in flow ".concat(i,". User message will not have a processNodeId."))}}let d={id:(0,nO.A)(),role:"user",content:e,timestamp:Date.now(),attachments:a.length>0?a:void 0,processNodeId:n},c={...Q,messages:[...Q.messages,d]};ng(c),c.flowId?await nC(c):(ey("Please select an agent for this conversation before sending messages"),Y(Q))},nI=(0,o.useCallback)((e,t)=>{nL.verbose("Handling API response data",JSON.stringify(e)),eg(t,"running"===e.status);let n=t9.current===t,a=ea.current===t;if("paused_debug"===e.status&&e.debugState)return(nL.info("API Response: Paused for debugging",{conversationId:t}),a)?(e4(e.debugState),e6(!0),e7(!0),ec(!1),t_(null),nf(),nS(),Y(n=>(null==n?void 0:n.id)===t&&e.debugState.messages&&JSON.stringify(n.messages)!==JSON.stringify(e.debugState.messages)?(nL.debug("Updating detailed conversation messages from debug state"),{...n,messages:e.debugState.messages,updatedAt:e.debugState.updatedAt}):n),B(n=>n.map(n=>{var a,o;return n.id===t?{...n,title:null!=(a=e.debugState.title)?a:n.title,flowId:null!=(o=e.debugState.flowId)?o:n.flowId,status:"paused_debug",updatedAt:e.debugState.updatedAt}:n}).sort((e,t)=>{var n,a;return(null!=(n=t.lastUserMessageAt)?n:t.updatedAt)-(null!=(a=e.lastUserMessageAt)?a:e.updatedAt)}))):(nm(t,"paused_debug"),n&&(ec(!1),t_(null),nf(),nS())),!0;if(("completed"===e.status||"error"===e.status)&&a?(nL.info("API Response: Execution completed or errored (Status: ".concat(e.status,"). Hiding debugger panel."),{conversationId:t}),e6(!1),e4(null),e7(!1)):nL.debug("API Response: Status is '".concat(e.status,"'. Debugger panel visibility unchanged (currently ").concat(e5?"visible":"hidden",")."),{conversationId:t}),e.messages&&e.conversation_id===t){let n=e.messages.map((e,n)=>"number"!=typeof e.timestamp||isNaN(e.timestamp)?(nL.warn("Invalid timestamp found in message index ".concat(n," from API response. Defaulting to Date.now()."),{conversationId:t,messageId:e.id,invalidTimestamp:e.timestamp}),{...e,timestamp:Date.now()}):e);Y(a=>{var o,r;let l=a;return(null==a?void 0:a.id)===t&&JSON.stringify(a.messages)!==JSON.stringify(n)&&(nL.info("API Response/Polling: Updating detailed conversation messages",{conversationId:t,newMessageCount:n.length}),l={...a,messages:n,updatedAt:e.updatedAt||a.updatedAt}),nL.debug("Polling: setDetailedConversation callback executed.",{conversationId:t,messagesChanged:l!==a,newMessageCount:null!=(r=null==l||null==(o=l.messages)?void 0:o.length)?r:"N/A"}),l})}if("awaiting_tool_approval"===e.status)nL.info("API Response/Polling: Pausing for tool approval",{conversationId:t}),a&&eR(e.pendingToolCalls||[]),n&&(ec(!1),t_(null),nf(),nS());else if("completed"===e.status||"error"===e.status){if(nL.info("API Response/Polling: Stopping due to final status",{conversationId:t,status:e.status}),n&&(nS(),ec(!1),t_(null),nf()),"error"===e.status){var o,r;let l=(null==(o=e.error)?void 0:o.message)||(null==(r=e.lastResponse)?void 0:r.error)||"Unknown error during execution";nB.test(l)||tY.current.has(t)?(t1(t,!0),(n||a)&&ey(null),nL.info("API Response/Polling: Execution cancelled by user",{conversationId:t})):(ey(l),nL.error("API Response/Polling: Execution resulted in error",{conversationId:t,error:e.error||e.lastResponse}))}nt(t)}else"running"!==e.status||e5?a&&eR(null):(a&&eR(null),n&&!tL.current&&ec(!0));return e.conversation_id===t&&B(n=>n.map(n=>{var a,o,r;return n.id===t?{...n,title:null!=(a=e.title)?a:n.title,flowId:null!=(o=e.flowId)?o:n.flowId,status:null!=(r=e.status)?r:n.status,updatedAt:e.updatedAt||n.updatedAt}:n}).sort((e,t)=>{var n,a;return(null!=(n=t.lastUserMessageAt)?n:t.updatedAt)-(null!=(a=e.lastUserMessageAt)?a:e.updatedAt)})),!1},[Y,eR,ec,ey,e6,e4,B,nt,nf,eg,nm,t1]),nS=()=>{tL.current&&(nL.debug("Stopping polling interval"),clearInterval(tL.current),tL.current=null)};(0,o.useEffect)(()=>()=>{nf()},[nf]);let nC=async e=>{if(!(null==e?void 0:e.id)||!e.flowId||!tq.current)return nL.error("Cannot send to completions: Missing conversation ID or flow ID.",{id:null==e?void 0:e.id,flowId:null==e?void 0:e.flowId}),ey("Cannot send message: This conversation is missing its agent."),!1;eR(null),ey(null),ec(!0),t_(e.id),eg(e.id,!0),t1(e.id,!1);let t=tK.current.delete(e.id);tA({totalTokens:0,activeNode:null,startedAt:Date.now(),lastEventAt:Date.now()}),await nx(e.id);let n=!1;try{let t;if(eu(e.flowId))t="flow-Quick Chat",nL.debug("Sending quick chat to completions",{flowId:e.flowId,conversationId:e.id});else{let n=await tJ.g.getFlow(e.flowId);if(!n)throw Error("Flow with ID ".concat(e.flowId," not found"));t="flow-".concat(n.name),nL.debug("Sending to chat completions",{flowId:e.flowId,flowName:n.name,conversationId:e.id})}let a=e.messages.filter(e=>{var t;return!e.disabled&&!((null!=(t=e.depth)?t:0)>0)}).map(e=>{let t=nH(e),n=e.processNodeId,a={id:e.id,timestamp:e.timestamp};return"user"===e.role?{role:"user",content:t,...a,processNodeId:n}:"assistant"===e.role?{role:"assistant",content:t,tool_calls:e.tool_calls,...a,processNodeId:n}:"system"===e.role?{role:"system",content:t,...a,processNodeId:n}:"tool"===e.role?e.tool_call_id?{role:"tool",content:t,tool_call_id:e.tool_call_id,...a,processNodeId:n}:{role:"user",content:"string"==typeof t?"Tool result: ".concat(t):t,...a,processNodeId:n}:{role:"user",content:t,...a,processNodeId:n}}),o=await tq.current.chat.completions.create({model:t,messages:a,stream:!1,metadata:(()=>{let t=tB.current.get(e.id),n={flujo:"true",requireApproval:eA?"true":void 0,flujodebug:eE?"true":void 0,conversationId:e.id,mcpAppContexts:void 0===t?void 0:JSON.stringify(t)},a={};return n.flujo&&(a.flujo=n.flujo),n.requireApproval&&(a.requireApproval=n.requireApproval),n.flujodebug&&(a.flujodebug=n.flujodebug),n.conversationId&&(a.conversationId=n.conversationId),void 0!==n.mcpAppContexts&&(a.mcpAppContexts=n.mcpAppContexts),a})()});nL.debug("Chat completion initial response received",{completionId:o.id}),n=!0;let r={...o,status:o.status||"completed",conversation_id:e.id,messages:o.messages||e.messages,pendingToolCalls:o.pendingToolCalls,debugState:o.debugState,error:o.error,lastResponse:o.lastResponse,updatedAt:o.updatedAt||Date.now()},l=nI(r,e.id);l||tL.current?l&&nL.debug("Debug state handled, polling remains stopped."):nL.debug("Starting polling after initial non-debug response.")}catch(r){if(nK(r)||tY.current.has(e.id))return nL.info("Chat completion cancelled by user",{conversationId:e.id}),n=!1,eg(e.id,!1),t1(e.id,!0),t9.current===e.id&&(nS(),ec(!1),t_(null),nf(),ey(null)),n;nL.error("Error calling chat completions API:",r),n=!1;let o="An error occurred while sending the message.";if(r instanceof nW.LG)o="API Error: ".concat(r.message," (Status: ").concat(r.status,")"),r.code&&(o+=" (Code: ".concat(r.code,")")),r.type&&(o+=" [Type: ".concat(r.type,"]")),nL.verbose("APIError details",JSON.stringify(r));else if(r instanceof nW.vc){o="OpenAI Error: ".concat(r.message);let e=r.error;e&&"object"==typeof e&&(e.code&&(o+=" (Code: ".concat(e.code,")")),e.type&&(o+=" [Type: ".concat(e.type,"]"))),nL.verbose("OpenAIError details",JSON.stringify(r))}else if(r instanceof nq.b){var a;o="Error: ".concat((null==(a=r.body)?void 0:a.error)||r.message),r.status&&(o+=" (Status: ".concat(r.status,")")),nL.verbose("ChatApiError details",JSON.stringify(r.body))}else r instanceof Error&&(o=r.message);ey(o),eg(e.id,!1),t9.current===e.id&&(nS(),ec(!1),t_(null),nf()),t&&tK.current.add(e.id)}finally{}return n},nE=(0,o.useRef)(nk);nE.current=nk;let nT=(0,o.useCallback)(e=>!!et&&ea.current===et&&(nE.current(e),!0),[et]),nz=(0,o.useCallback)((e,t)=>{var n;if(!et||ea.current!==et)return!1;let a={...null!=(n=tB.current.get(et))?n:{}};return(void 0===t.content&&void 0===t.structuredContent?delete a[e]:a[e]=t,(0,eW.Yw)(a)>eW.uJ)?(nL.warn("Rejected oversized aggregate MCP App model context",{conversationId:et,appKey:e}),!1):(tB.current.set(et,a),!0)},[et]),[nM,nD]=(0,o.useState)(eU),[nG,nX]=(0,o.useState)(et),nJ=(0,o.useRef)(new Set),nQ=(0,o.useCallback)((e,t,n)=>{let a="".concat(e,"\0").concat(t);n?eo.current.set(a,n):eo.current.delete(a)},[]),nY=(0,o.useCallback)((e,t)=>{et&&nQ(et,e,t)},[et,nQ]),nV=(0,o.useCallback)(e=>{nX(ea.current),nD(t=>{let{state:n}=eK(t,e,Date.now(),Number.MAX_SAFE_INTEGER);return n})},[]),nZ=(0,o.useCallback)(e=>{nD(t=>(function(e,t){let n=arguments.length>2&&void 0!==arguments[2]?arguments[2]:Date.now(),a=e.entries[t];if(!a)return e;let o={...a,unread:!1,lastActiveAt:n};return{...e,entries:{...e.entries,[t]:o},activeKey:t}})(t,e))},[]),n$=(0,o.useCallback)(e=>{if(!et)return;let t=eo.current.get("".concat(et,"\0").concat(e)),n=()=>{ea.current===et&&nD(t=>eG(t,e))};t?t().finally(n):n()},[et]);(0,o.useEffect)(()=>{nX(et),nD(eU)},[et]);let n0=nM.order.join("|");(0,o.useEffect)(()=>{let e=null==Q?void 0:Q.messages;if(!e||!Q||Q.id!==et||nG!==et)return;let t=new Map;for(let n of e)if("assistant"===n.role&&Array.isArray(n.tool_calls))for(let e of n.tool_calls)"function"===e.type&&e.id&&t.set(e.id,e);let n=new Map;for(let o of e){let e=o.ui;if("tool"===o.role&&(null==e?void 0:e.uri)&&(null==e?void 0:e.serverName)&&"string"==typeof o.content){var a;let r="string"==typeof o.tool_call_id?t.get(o.tool_call_id):void 0,l={serverName:e.serverName,uri:e.uri,toolName:null!=(a=e.toolName)?a:(null==r?void 0:r.type)==="function"?r.function.name:void 0,toolArgs:(null==r?void 0:r.type)==="function"?r.function.arguments:void 0,resultContent:o.content,cancelledReason:e.cancelledReason,isError:e.isError,updateId:o.id};n.set("".concat(e.serverName,"::").concat(e.uri),l)}}nD(e=>{let t=e;for(let e of t.order){let a=t.entries[e],o=n.get(e);a&&o&&(o.updateId!==a.latestToolUpdateId||o.toolArgs!==a.latestToolArgs||void 0===o.cancelledReason&&o.resultContent!==a.latestResultContent||o.cancelledReason!==a.latestToolCancelledReason||o.isError!==a.latestToolIsError)&&(t=function(e,t){var n,a,o,r,l;let i=arguments.length>2&&void 0!==arguments[2]?arguments[2]:Date.now(),s=null!=(n=t.instanceKey)?n:eH(t.serverName,t.uri),d=e.entries[s];if(!d)return e;let c=e.activeKey===s,u={...d,toolName:null!=(a=t.toolName)?a:d.toolName,latestToolArgs:null!=(o=t.toolArgs)?o:d.latestToolArgs,latestResultContent:void 0!==t.cancelledReason?void 0:null!=(r=t.resultContent)?r:d.latestResultContent,latestToolCancelledReason:void 0!==t.cancelledReason?t.cancelledReason:void 0!==t.resultContent?void 0:d.latestToolCancelledReason,latestToolIsError:void 0!==t.cancelledReason?void 0:void 0!==t.isError?t.isError:void 0===t.resultContent&&d.latestToolIsError,latestToolUpdateId:null!=(l=t.updateId)?l:d.latestToolUpdateId,updatedAt:i,unread:!c,lastActiveAt:c?i:d.lastActiveAt};return{...e,entries:{...e.entries,[s]:u}}}(t,o))}return t})},[n0,nG,et,null==Q?void 0:Q.id,null==Q?void 0:Q.messages]),(0,o.useEffect)(()=>{var e;if(!et||nG!==et||nM.order.length<=16)return;let{evicted:t}=eB(nM,16,null!=(e=nM.activeKey)?e:void 0);for(let e of t){let t="".concat(et,"\0").concat(e);if(nJ.current.has(t))continue;nJ.current.add(t),nL.info("Canvas tab cap reached — gracefully evicting (LRU): ".concat(e));let n=eo.current.get(t);(n?n():Promise.resolve()).finally(()=>{nJ.current.delete(t),ea.current===et&&nD(t=>eG(t,e))})}},[nM,nG,et]);let n1=async(e,t,n)=>{if(!Q)return;nL.debug("Editing message",{messageId:e,contentLength:t.length,processNodeId:n});let a=Q.messages.findIndex(t=>t.id===e);if(-1===a)return;let o={...Q.messages[a],content:t,timestamp:Date.now(),processNodeId:n||void 0},r=[...Q.messages.slice(0,a),o],l={...Q,messages:r};if(ng(l),l.flowId){let e=tB.current.get(l.id),t={flujo:"true",requireApproval:eA?"true":void 0,flujodebug:eE?"true":void 0,conversationId:l.id,processNodeId:n||void 0,mcpAppContexts:void 0===e?void 0:JSON.stringify(e)};if(!tq.current)return;ey(null),ec(!0),t_(l.id),eg(l.id,!0),t1(l.id,!1),tA({totalTokens:0,activeNode:null,startedAt:Date.now(),lastEventAt:Date.now()}),await nx(l.id);try{let e=await tJ.g.getFlow(l.flowId);if(!e)throw Error("Flow with ID ".concat(l.flowId," not found"));let n=l.messages.filter(e=>{var t;return!e.disabled&&!((null!=(t=e.depth)?t:0)>0)}).map(e=>{let t=nH(e),n={id:e.id,timestamp:e.timestamp,processNodeId:e.processNodeId};return"user"===e.role?{role:"user",content:t,...n}:"assistant"===e.role?{role:"assistant",content:t,tool_calls:e.tool_calls,...n}:"system"===e.role?{role:"system",content:t,...n}:"tool"===e.role?e.tool_call_id?{role:"tool",content:t,tool_call_id:e.tool_call_id,...n}:{role:"user",content:"string"==typeof t?"Tool result: ".concat(t):t,...n}:{role:"user",content:t,...n}}),a=await tq.current.chat.completions.create({model:"flow-".concat(e.name),messages:n,stream:!1,metadata:(()=>{let e={};return t.flujo&&(e.flujo=t.flujo),t.requireApproval&&(e.requireApproval=t.requireApproval),t.flujodebug&&(e.flujodebug=t.flujodebug),t.conversationId&&(e.conversationId=t.conversationId),t.processNodeId&&(e.processNodeId=t.processNodeId),void 0!==t.mcpAppContexts&&(e.mcpAppContexts=t.mcpAppContexts),e})()}),o={...a,status:a.status||"completed",conversation_id:l.id,messages:a.messages||l.messages,pendingToolCalls:a.pendingToolCalls,debugState:a.debugState,error:a.error,updatedAt:a.updatedAt||Date.now()};nI(o,l.id)}catch(e){nK(e)||tY.current.has(l.id)?(nL.info("Edited-message run cancelled by user",{conversationId:l.id}),t1(l.id,!0)):(nL.error("Error sending edited message:",e),ey(e instanceof Error?e.message:"Failed to send edited message")),eg(l.id,!1),t9.current===l.id&&(ec(!1),t_(null),nf())}}},n2=(0,o.useCallback)(e=>{var t,n,a;let o=null==Q?void 0:Q.messages.find(t=>t.id===e);o&&"user"===o.role&&"string"==typeof o.content&&e0({messageId:e,content:o.content,nodeId:null!=(a=o.processNodeId)?a:null!=(n=null==(t=nl[0])?void 0:t.id)?n:null})},[Q,nl]),n5=(0,o.useCallback)(e=>{e0(t=>t?{...t,content:e}:t)},[]),n6=(0,o.useCallback)(e=>{e0(t=>t?{...t,nodeId:e}:t)},[]),n3=(0,o.useCallback)(()=>e0(null),[]),n4=async(e,t,n,a)=>{if(et){nL.info("Handling tool response: ".concat(e),{conversationId:et,toolCallId:t,always:n}),eR(null),ec(!0),t_(et),eg(et,!0),ey(null),await nx(et);try{let o=await nq.O.respondToToolCall(et,e,t,n,a);nL.debug("Tool response successful",{conversationId:et,action:e,toolCallId:t}),nI(o,et)}catch(a){if(nK(a)||tY.current.has(et)){nL.info("Tool-response resume cancelled by user",{conversationId:et}),t1(et,!0),t9.current===et&&ec(!1),eg(et,!1);return}nL.error("Error sending tool response (".concat(e,")"),{conversationId:et,toolCallId:t,err:a});let n="Failed to ".concat(e," tool call.");if(a instanceof nq.b){var o;n+=" Error: ".concat((null==(o=a.body)?void 0:o.error)||a.message)}else a instanceof Error&&(n+=" Error: ".concat(a.message));ey(n),t9.current===et&&ec(!1),eg(et,!1)}}},n8=async(e,t)=>{if(et){nL.info("Submitting elicitation form",{conversationId:et,elicitationId:e}),eP(null);try{await fetch("/v1/chat/conversations/".concat(et,"/respond"),{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify({action:"elicitation-submit",elicitationId:e,content:t})})}catch(t){nL.error("Failed to submit elicitation",{conversationId:et,elicitationId:e,err:t})}}},n7=async e=>{if(et){nL.info("Cancelling elicitation",{conversationId:et,elicitationId:e}),eP(null);try{await fetch("/v1/chat/conversations/".concat(et,"/respond"),{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify({action:"elicitation-cancel",elicitationId:e})})}catch(t){nL.error("Failed to cancel elicitation",{conversationId:et,elicitationId:e,err:t})}}},n9=async(e,t)=>{if(et){nL.info("Answering question",{conversationId:et,questionId:e}),e_(null);try{await fetch("/v1/chat/conversations/".concat(et,"/respond"),{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify({action:"question-answer",questionId:e,answers:t})})}catch(t){nL.error("Failed to answer question",{conversationId:et,questionId:e,err:t})}}},ae=async e=>{if(et){nL.info("Declining question",{conversationId:et,questionId:e}),e_(null);try{await fetch("/v1/chat/conversations/".concat(et,"/respond"),{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify({action:"question-decline",questionId:e})})}catch(t){nL.error("Failed to decline question",{conversationId:et,questionId:e,err:t})}}},at=async()=>{if(et&&e5){nL.info("Handling debug step request",{conversationId:et}),ec(!0),t_(et),eg(et,!0),ey(null),await nx(et);try{let e=await nq.O.debugStep(et);nI(e,et)}catch(e){nL.error("Error during debug step API call",{conversationId:et,err:e}),ey(e instanceof Error?e.message:"Failed to execute debug step."),ec(!1),eg(et,!1),e6(!1),e4(null)}finally{}}},an=async()=>{if(et&&e5){nL.info("Handling debug continue request",{conversationId:et}),ec(!0),t_(et),eg(et,!0),ey(null),e6(!1),await nx(et);try{let e=await nq.O.debugContinue(et);nI(e,et)}catch(e){nL.error("Error during debug continue API call",{conversationId:et,err:e}),ey(e instanceof Error?e.message:"Failed to continue execution."),ec(!1),eg(et,!1)}finally{}}};(0,o.useEffect)(()=>{if(e3){var e;tP(null!=(e=e3.breakpoints)?e:[])}},[e3]);let aa=(0,o.useCallback)(async e=>{if(!et)return;let t=tF.includes(e)?tF.filter(t=>t!==e):[...tF,e];tP(t);try{await nq.O.setBreakpoints(et,t)}catch(e){nL.error("Failed to update breakpoints",{conversationId:et,err:e}),tP(tF)}},[tF,et]),ao=(0,o.useCallback)(async()=>{if(et){nL.info("Attaching debugger to running conversation",{conversationId:et});try{await nq.O.setBreakpoints(et,["*"])}catch(e){nL.error("Failed to attach debugger",{conversationId:et,err:e}),ey(e instanceof Error?e.message:"Failed to attach debugger.")}}},[et]),ar=async()=>{if(!et||!e5)return;let e=null==e3?void 0:e3.currentNodeId;ec(!0),t_(et),eg(et,!0),ey(null),await nx(et);try{for(let o=0;o<50;o++){var t,n,a;let o=await nq.O.debugStep(et),r=null!=(a=null==o?void 0:o.status)?a:null==o||null==(t=o.debugState)?void 0:t.status,l=null==o||null==(n=o.debugState)?void 0:n.currentNodeId;if("paused_debug"!==r||l&&l!==e)return void nI(o,et)}nL.warn("Step Over hit iteration cap",{conversationId:et}),ec(!1),eg(et,!1)}catch(e){nL.error("Error during step over",{conversationId:et,err:e}),ey(e instanceof Error?e.message:"Failed to step over."),ec(!1),eg(et,!1)}},al=async()=>{if(et){nL.info("Cancelling request",{conversationId:et}),nS(),ec(!1),t_(null),eg(et,!1),t1(et,!0),e7(!1),nf(),eR(null),ey(null);try{await nq.O.cancel(et),nL.debug("Cancel request sent successfully",{conversationId:et}),await nt(et)}catch(e){nL.error("Error sending cancel request",{conversationId:et,err:e}),ey("Failed to send cancel request to the server.")}}},ai=async e=>{if(e===et)return void await al();nL.info("Stopping background conversation",{conversationId:e}),t1(e,!0);try{await nq.O.cancel(e),eg(e,!1),await ne(void 0,{silent:!0})}catch(t){nL.error("Error stopping background conversation",{conversationId:e,err:t}),ey("Failed to send cancel request to the server.")}},as=async()=>{nL.info("Closing debugger panel",{conversationId:et}),e6(!1),e4(null),e7(!1),await al()};nL.debug("Rendering Chat component",{currentConversationId:et,isHandleEditMessageDefined:!0});let ad=(e8||e5)&&!!e3&&!!et,ac=(null==na?void 0:na.status)==="awaiting_tool_approval"||!!eD,au=!(ac||(null==na?void 0:na.status)==="paused_debug")&&(ed&&tO===et||!!et&&eh.has(et)||(null==na?void 0:na.status)==="running"),ah=!au&&!!et&&t$.has(et);(0,o.useEffect)(()=>{if(!et||ev.current||!Q||Q.id!==et)return;let e=eX(ef,et)[0];if(!e||!function(e){return!e.running&&!e.pendingApproval&&!e.debugPaused&&!e.hasError&&!e.stopped}({running:eh.has(et),pendingApproval:!!eD,debugPaused:e5,hasError:(null==na?void 0:na.status)==="error",stopped:ah}))return;ev.current=!0;let t=setTimeout(async()=>{try{em(t=>eQ(t,et,e.id)),await nk(e.content,e.attachments,{fromQueue:!0,nodeOverride:e.nodeOverride,queuedId:e.id})}catch(t){em(t=>(function(e,t,n){let a=eX(e,t).filter(e=>e.id!==n.id);return{...e,[t]:[n,...a]}})(t,et,e))}finally{ev.current=!1}},0);return()=>clearTimeout(t)},[et,Q,ef,eh,eD,e5,null==na?void 0:na.status,ah]);let ap=nU(ny),ag=nU(nb),af=nU(ai),am=nU(nd),av=(0,o.useCallback)(()=>nh(!0),[]),ax=K?(0,a.jsx)(s.default,{sx:{display:"flex",justifyContent:"center",alignItems:"center",height:"100%",p:2},children:(0,a.jsx)(nP.default,{size:"medium",color:"primary"})}):X?(0,a.jsx)(d.A,{severity:"error",sx:{m:2},children:X}):(0,a.jsx)(eN,{conversations:H,flowNames:no,currentConversationId:et,onSelectConversation:tx,onDeleteConversation:ap,onBulkDelete:ag,onStopConversation:af,onNewConversation:am,onQuickChat:av,onCollapse:tm});return(0,a.jsxs)(s.default,{sx:{display:"flex",height:"calc(100dvh - var(--app-bar-height))",minHeight:0,overflow:"hidden",position:"relative",bgcolor:"transparent"},children:[(0,a.jsx)(c.A,{component:"h1",className:"sr-only",children:"Chat"}),tf&&(0,a.jsx)(s.default,{sx:{width:40,flexShrink:0,borderRight:1,borderColor:"divider",display:"flex",justifyContent:"center",alignItems:"flex-start",pt:1.4,bgcolor:"var(--surface-glass)",backdropFilter:"blur(18px)"},children:(0,a.jsx)(u.A,{title:"Show conversation sidebar",children:(0,a.jsx)(h.A,{size:"small",onClick:tm,"aria-label":"Show conversation sidebar",children:(0,a.jsx)(z.A,{fontSize:"small"})})})}),U&&(0,a.jsx)(p.Ay,{anchor:"left",open:tp,onClose:()=>tg(!1),ModalProps:{keepMounted:!0},PaperProps:{sx:{width:"min(86vw, 340px)",maxWidth:"calc(100vw - 28px)",display:"flex",flexDirection:"column",bgcolor:"var(--surface-glass)",backgroundImage:"none",backdropFilter:"blur(22px) saturate(140%)",boxShadow:"24px 0 70px rgba(0,0,0,.45)"}},children:ax}),!U&&!tu&&(0,a.jsx)(s.default,{sx:{width:td,flexShrink:0,borderRight:1,borderColor:"divider",display:"flex",flexDirection:"column",bgcolor:"var(--surface-glass)",backdropFilter:"blur(18px) saturate(135%)"},children:ax}),!U&&!tu&&(0,a.jsx)(s.default,{onPointerDown:ty,onKeyDown:e=>{("ArrowLeft"===e.key||"ArrowRight"===e.key)&&(e.preventDefault(),tc(t=>{let n=Math.min(560,Math.max(220,t+("ArrowRight"===e.key?16:-16)));return window.localStorage.setItem("flujo-chat-sidebar-width",String(n)),n}))},role:"separator",tabIndex:0,"aria-orientation":"vertical","aria-valuemin":220,"aria-valuemax":560,"aria-valuenow":Math.round(td),sx:{position:"relative",width:"8px",flexShrink:0,cursor:"col-resize",bgcolor:"transparent",transition:"background-color 120ms","&::after":{position:"absolute",top:0,bottom:0,left:"50%",width:1,content:'""',bgcolor:"divider",transition:"width 120ms, background-color 120ms"},"&:hover::after":{width:2,bgcolor:"primary.main"},"&:focus-visible::after":{width:3,bgcolor:"primary.main"},touchAction:"none"},"aria-label":"Resize conversation sidebar"}),(0,a.jsxs)(s.default,{sx:{flex:1,height:"100%",display:"flex",minWidth:0,minHeight:0},children:[(0,a.jsxs)(s.default,{sx:{flex:1,minWidth:0,display:"flex",flexDirection:"column",height:"100%"},children:[et&&(0,a.jsx)(s.default,{sx:{px:{xs:2,md:3},py:1.35,display:"flex",alignItems:"center",gap:1,minWidth:0,borderBottom:1,borderColor:"divider",bgcolor:"var(--surface-glass)",backdropFilter:"blur(16px)"},children:ek?(0,a.jsx)(g.A,{value:eS,onChange:e=>eC(e.target.value),onBlur:nj,onKeyDown:e=>{"Enter"===e.key?(e.preventDefault(),nj()):"Escape"===e.key&&eI(!1)},size:"small",autoFocus:!0,fullWidth:!0,inputProps:{maxLength:200,"aria-label":"Conversation title"}}):(0,a.jsxs)(a.Fragment,{children:[(0,a.jsx)(c.A,{variant:"h6",noWrap:!0,onClick:nA,title:(null==Q?void 0:Q.title)||(null==na?void 0:na.title)||"",sx:{flex:1,minWidth:0,cursor:"text"},children:(null==Q?void 0:Q.title)||(null==na?void 0:na.title)||"Untitled Conversation"}),(0,a.jsx)(u.A,{title:"Rename conversation",children:(0,a.jsx)(h.A,{size:"small",onClick:nA,"aria-label":"Rename conversation",children:(0,a.jsx)(M.A,{fontSize:"small"})})}),(0,a.jsx)(u.A,{title:ta?"Hide executed steps":"Show executed steps",children:(0,a.jsx)(h.A,{size:"small",color:ta?"primary":"default",onClick:()=>to(e=>!e),"aria-label":"Toggle executed steps panel",children:(0,a.jsx)(R.A,{fontSize:"small"})})})]})}),et&&(0,a.jsxs)(s.default,{sx:{px:{xs:2,md:3},py:1.25,borderBottom:1,borderColor:"divider",display:"flex",alignItems:"center",gap:2,bgcolor:"var(--surface-glass)",backdropFilter:"blur(16px)"},children:[(0,a.jsx)(s.default,{sx:{flex:1,minWidth:0},children:eu((null==na?void 0:na.flowId)||(null==Q?void 0:Q.flowId))?(0,a.jsx)(f.A,{color:"primary",variant:"outlined",icon:(0,a.jsx)(S.A,{}),label:"Quick Chat"}):(0,a.jsxs)(s.default,{sx:{display:"flex",alignItems:"flex-start",gap:.5},children:[(0,a.jsx)(tz.A,{selectedFlowId:(null==na?void 0:na.flowId)||(null==Q?void 0:Q.flowId)||null,onSelectFlow:e=>{var t,n,a,o;if(!et){nL.warn("Cannot update flow: No conversation selected."),ey("Please select a conversation first.");return}eu(e)||es(e);let r=null!=(a=null!=(n=null==Q?void 0:Q.flowId)?n:null==na?void 0:na.flowId)?a:null;if((null!=(o=null==Q||null==(t=Q.messages)?void 0:t.length)?o:0)>0&&r&&e!==r){nL.debug("Flow switch on executed conversation — asking for confirmation",{flowId:e,currentFlowId:r}),eY(e);return}nw(e)},disabled:e5}),(()=>{let e=(null==na?void 0:na.flowId)||(null==Q?void 0:Q.flowId)||null;return e?(0,a.jsx)(u.A,{title:"Open this agent in the editor",children:(0,a.jsx)(h.A,{color:"primary",onClick:()=>q.push("/flows?flow=".concat(encodeURIComponent(e))),children:(0,a.jsx)(D.A,{})})}):null})()]})}),(0,a.jsx)(tN,{usage:null==Q?void 0:Q.usage,contextInfo:null==Q?void 0:Q.contextInfo,availableNodes:nl})]}),(0,a.jsxs)(s.default,{sx:{flex:1,minHeight:0,position:"relative",display:"flex",flexDirection:"column"},children:[(0,a.jsx)(s.default,{ref:t2,onScroll:t8,sx:{flex:1,overflow:"auto",px:{xs:1.5,sm:2.5,lg:4},py:2.5,"& > *":{width:"100%",maxWidth:{xs:960,lg:"none"},mx:"auto"}},children:V?(0,a.jsx)(s.default,{sx:{display:"flex",justifyContent:"center",alignItems:"center",height:"100%"},children:(0,a.jsx)(nP.default,{size:"medium",color:"primary"})}):$?(0,a.jsx)(d.A,{severity:"error",sx:{m:2},children:$}):Q?(0,a.jsxs)(a.Fragment,{children:[(0,a.jsx)(ez.A,{messages:Q.messages,pendingToolCalls:eD,pendingElicitation:eF,availableNodes:nl,conversationId:Q.id,editingMessageId:null!=(O=null==e$?void 0:e$.messageId)?O:null,onToggleDisabled:e=>{if(!Q)return;nL.debug("Toggling message disabled state",{messageId:e});let t=Q.messages.map(t=>t.id===e?{...t,disabled:!t.disabled}:t);ng({...Q,messages:t})},onSplitConversation:e=>{if(!Q)return;nL.debug("Splitting conversation at message",{messageId:e});let t=Q.messages.findIndex(t=>t.id===e);if(-1===t)return;let n=Q.messages.slice(0,t+1),a=(0,nO.A)(),o={id:a,title:"Split from ".concat(Q.title),messages:n,flowId:Q.flowId,createdAt:Date.now(),updatedAt:Date.now()},r={id:a,title:o.title,flowId:o.flowId,createdAt:o.createdAt,updatedAt:o.updatedAt};tK.current.add(a),B(e=>[r,...e].sort((e,t)=>{var n,a;return(null!=(n=t.lastUserMessageAt)?n:t.updatedAt)-(null!=(a=e.lastUserMessageAt)?a:e.updatedAt)})),el(a),Y(o),Z(!1),ee(null)},onRevertToHere:()=>nt(Q.id),onBeginEditMessage:n2,onApproveToolCall:(e,t)=>{n4("approve",e,t)},onRejectToolCall:(e,t,n)=>{n4("reject",e,t,n)},onSubmitElicitation:n8,onCancelElicitation:n7,pendingQuestion:eO,onAnswerQuestion:n9,onDeclineQuestion:ae,onAppMessage:nT,onUpdateModelContext:nz,onRegisterAppTeardown:nY,onOpenInCanvas:nV,queuedMessages:eX(ef,Q.id),queueHoldReason:function(e){return e.stopped?"Held — you stopped this run. Send again to continue.":e.hasError?"Held — the last run failed. Retry or send again to continue.":e.pendingApproval?"Held — waiting for tool approval.":e.debugPaused?"Held — paused in the debugger.":null}({running:eh.has(Q.id),pendingApproval:!!eD,debugPaused:e5,hasError:(null==na?void 0:na.status)==="error",stopped:ah})}),!ed&&!e5&&Q.messages.length>0&&(null==na?void 0:na.status)==="completed"&&(0,a.jsx)(s.default,{sx:{display:"flex",justifyContent:"center",my:2},children:(0,a.jsx)(d.A,{icon:(0,a.jsx)(E.A,{fontSize:"inherit"}),severity:"success",variant:"filled",sx:{borderRadius:2,py:.5},children:"Conversation completed"})}),!ed&&!e5&&ah&&(0,a.jsx)(s.default,{sx:{display:"flex",justifyContent:"center",my:2},children:(0,a.jsx)(d.A,{icon:(0,a.jsx)(N.A,{fontSize:"inherit"}),severity:"info",variant:"outlined",sx:{borderRadius:2,py:.5,alignItems:"center"},action:(0,a.jsx)(m.A,{color:"inherit",size:"small",startIcon:(0,a.jsx)(C.A,{}),onClick:()=>nC(Q),children:"Resume"}),children:"Conversation stopped"})}),!ed&&!e5&&!ah&&(null==Q?void 0:Q.recovery)&&("interrupted"===Q.recovery.classification||Q.recovery.manualActionRequired)&&(0,a.jsx)(s.default,{sx:{display:"flex",justifyContent:"center",my:2},children:(0,a.jsxs)(d.A,{icon:(0,a.jsx)(T.A,{fontSize:"inherit"}),severity:"warning",variant:"filled",sx:{borderRadius:2,py:.5,alignItems:"center",maxWidth:760},action:(0,a.jsx)(m.A,{color:"inherit",size:"small",startIcon:(0,a.jsx)(C.A,{}),onClick:()=>nC(Q),children:"Restart turn"}),children:[(0,a.jsxs)(c.A,{variant:"body2",fontWeight:600,children:["Recovery required",(null==(e=Q.recovery.currentCheckpoint)?void 0:e.nodeId)?" at node ".concat(Q.recovery.currentCheckpoint.nodeId):""]}),Q.recovery.sideEffectWarning&&(0,a.jsx)(c.A,{variant:"caption",component:"div",children:Q.recovery.sideEffectWarning})]})}),!ed&&!e5&&!ex&&!ah&&(null==Q||null==(t=Q.recovery)?void 0:t.classification)!=="interrupted"&&!(null==Q||null==(n=Q.recovery)?void 0:n.manualActionRequired)&&(null==na?void 0:na.status)==="error"&&(0,a.jsx)(s.default,{sx:{display:"flex",justifyContent:"center",my:2},children:(0,a.jsx)(d.A,{icon:(0,a.jsx)(T.A,{fontSize:"inherit"}),severity:"error",variant:"filled",sx:{borderRadius:2,py:.5,alignItems:"center"},action:(0,a.jsx)(m.A,{color:"inherit",size:"small",startIcon:(0,a.jsx)(C.A,{}),onClick:()=>{nC(Q)},children:"Retry"}),children:"Conversation ended with an error"})}),au&&tT.length>0&&(0,a.jsx)(tw,{todos:tT}),au&&!e5&&(0,a.jsx)(tv,{liveStats:tb,lanes:tC,onOpenLane:el,onStop:al,stopDisabled:!et,onAttachDebugger:ed&&tO===et&&!e8?ao:void 0}),!au&&ac&&!e5&&(0,a.jsx)(tv,{liveStats:tb,lanes:tC,onOpenLane:el,awaitingApproval:!0,onStop:al,stopDisabled:!et}),ex&&(0,a.jsx)(d.A,{severity:"error",sx:{mt:2},action:(0,a.jsx)(m.A,{color:"inherit",size:"small",startIcon:(0,a.jsx)(C.A,{}),onClick:()=>{Q&&nC(Q)},children:"Retry"}),children:ex})]}):(0,a.jsx)(c.A,{variant:"body1",color:"textSecondary",align:"center",sx:{mt:4},children:H.length>0?"Select a conversation or create a new one.":"Create a new conversation to start chatting."})}),(0,a.jsx)(v.A,{in:t6,unmountOnExit:!0,children:(0,a.jsx)(x.A,{size:"small",color:"primary","aria-label":"Scroll to latest messages",onClick:t7,sx:{position:"absolute",bottom:16,right:24,zIndex:2},children:(0,a.jsx)(I.A,{})})})]}),et&&(0,a.jsx)(eL,{conversationId:et,entries:nG===et?function(e){return e.order.map(t=>e.entries[t]).filter(e=>!!e)}(nM):[],activeKey:nM.activeKey,onSelectTab:nZ,onCloseTab:n$,onAppMessage:nT,onUpdateModelContext:nz,onRegisterTeardown:nQ},et),(0,a.jsxs)(s.default,{sx:{p:0,borderTop:1,borderColor:"divider",background:"linear-gradient(to top, var(--background) 35%, transparent)"},children:[et&&eX(ef,et).length>0&&(0,a.jsxs)(s.default,{"data-testid":"queued-messages",sx:{mb:1,display:"flex",flexWrap:"wrap",gap:1,alignItems:"center"},children:[(0,a.jsxs)(c.A,{variant:"caption",color:"text.secondary",sx:{display:"flex",alignItems:"center",gap:.5},children:[(0,a.jsx)(F.A,{fontSize:"inherit"})," Queued:"]}),eX(ef,et).map(e=>(0,a.jsx)(f.A,{size:"small",variant:"outlined",label:e.content.trim().slice(0,40)||(e.attachments.length?"".concat(e.attachments.length," attachment(s)"):"message"),onDelete:()=>em(t=>eQ(t,et,e.id))},e.id))]}),(0,a.jsx)(eM.A,{onSendMessage:nk,disabled:V||!((null==Q?void 0:Q.flowId)||(null==na?void 0:na.flowId))||!!eD||e5,requireApproval:eA,onRequireApprovalChange:nn,executeInDebugger:eE,onExecuteInDebuggerChange:eT,availableNodes:nl,flow:nr,currentNodeId:ns,nodeOverrideActive:!!eV,onSelectNode:eZ,editing:e$,onEditingContentChange:n5,onEditingNodeChange:n6,onSaveEdit:()=>{e$&&e$.content.trim()&&(n1(e$.messageId,e$.content,e$.nodeId||""),e0(null))},onCancelEdit:n3})]})]})," ",ta&&et&&!U&&(0,a.jsxs)(a.Fragment,{children:[(0,a.jsx)(s.default,{onPointerDown:ti,onKeyDown:e=>{("ArrowLeft"===e.key||"ArrowRight"===e.key)&&(e.preventDefault(),tl(t=>{let n=Math.min(Math.max(240,Math.round(.7*window.innerWidth)),Math.max(240,t+("ArrowRight"===e.key?-16:16)));return window.localStorage.setItem("flujo-workflow-panel-width",String(n)),n}))},role:"separator",tabIndex:0,"aria-orientation":"vertical","aria-valuemin":240,"aria-valuemax":Math.max(240,Math.round(.7*window.innerWidth)),"aria-valuenow":Math.min(Math.max(240,Math.round(.7*window.innerWidth)),Math.round(tr)),sx:{width:"6px",flexShrink:0,display:{xs:"none",lg:"block"},cursor:"col-resize",bgcolor:"divider",transition:"background-color 120ms","&:hover":{bgcolor:"primary.main"},"&:focus-visible":{bgcolor:"primary.main"},touchAction:"none"},"aria-label":"Resize executed steps panel"}),(0,a.jsx)(s.default,{sx:{width:{xs:"100%",lg:"".concat(tr,"px")},minWidth:{xs:0,lg:240},maxWidth:{xs:"none",lg:"70vw"},flexShrink:0,display:"flex",flexDirection:"column",height:"100%",position:{xs:"absolute",lg:"static"},inset:{xs:0,lg:"auto"},zIndex:{xs:36,lg:"auto"},bgcolor:"background.default"},children:(0,a.jsx)(nR,{flowId:(null==Q?void 0:Q.flowId)||(null==na?void 0:na.flowId)||null,flowSnapshot:null!=(_=null==e3?void 0:e3.flowSnapshot)?_:null,executedNodeIds:ni,liveActivity:tj,onClose:()=>to(!1)})})]}),ad&&e3&&et&&!tt&&!U&&(0,a.jsxs)(a.Fragment,{children:[(0,a.jsx)(s.default,{onPointerDown:ts,onKeyDown:e=>{("ArrowLeft"===e.key||"ArrowRight"===e.key)&&(e.preventDefault(),te(t=>{let n=Math.min(Math.max(360,Math.round(.85*window.innerWidth)),Math.max(360,(t||Math.round(.5*window.innerWidth))+("ArrowRight"===e.key?-16:16)));return window.localStorage.setItem("flujo-debugger-width",String(n)),n}))},role:"separator",tabIndex:0,"aria-orientation":"vertical","aria-valuemin":360,"aria-valuemax":Math.max(360,Math.round(.85*window.innerWidth)),"aria-valuenow":Math.min(Math.max(360,Math.round(.85*window.innerWidth)),Math.round(e9||.5*window.innerWidth)),sx:{width:"6px",flexShrink:0,display:{xs:"none",lg:"block"},cursor:"col-resize",bgcolor:"divider",transition:"background-color 120ms","&:hover":{bgcolor:"primary.main"},"&:focus-visible":{bgcolor:"primary.main"},touchAction:"none"},"aria-label":"Resize debugger panel"}),(0,a.jsx)(s.default,{sx:{width:{xs:"100%",lg:e9?"".concat(e9,"px"):"50%"},minWidth:{xs:0,lg:360},maxWidth:{xs:"none",lg:"85vw"},flexShrink:0,display:"flex",flexDirection:"column",height:"100%",position:{xs:"absolute",lg:"static"},inset:{xs:0,lg:"auto"},zIndex:{xs:40,lg:"auto"},bgcolor:"background.default"},children:(0,a.jsx)(nN,{debugState:e3,conversationId:et,liveActivity:tj,executionEvents:tI,onStep:at,onStepOver:ar,onContinue:an,onCancel:al,isLoading:ed,breakpoints:tF,onToggleBreakpoint:aa,onClose:as,isExpanded:tt,onToggleExpand:()=>tn(e=>!e)})})]})]})," ",ta&&et&&U&&!ad&&(0,a.jsx)(y.A,{fullScreen:!0,open:!0,onClose:()=>to(!1),"aria-label":"Executed steps",children:(0,a.jsx)(s.default,{sx:{height:"100%",display:"flex",flexDirection:"column",bgcolor:"background.default"},children:(0,a.jsx)(nR,{flowId:(null==Q?void 0:Q.flowId)||(null==na?void 0:na.flowId)||null,flowSnapshot:null!=(W=null==e3?void 0:e3.flowSnapshot)?W:null,executedNodeIds:ni,liveActivity:tj,onClose:()=>to(!1)})})}),ad&&e3&&et&&(tt||U)&&(0,a.jsx)(y.A,{fullScreen:!0,open:!0,onClose:()=>{U?as():tn(!1)},"aria-label":"Flow debugger",children:(0,a.jsx)(s.default,{sx:{height:"100%",display:"flex",flexDirection:"column"},children:(0,a.jsx)(nN,{debugState:e3,conversationId:et,liveActivity:tj,executionEvents:tI,onStep:at,onStepOver:ar,onContinue:an,onCancel:al,isLoading:ed,breakpoints:tF,onToggleBreakpoint:aa,onClose:as,isExpanded:tt||U,onToggleExpand:()=>{U?as():tn(e=>!e)}})})}),(0,a.jsxs)(y.A,{open:!!eq,onClose:()=>eY(null),children:[(0,a.jsx)(b.A,{children:"Switch agent?"}),(0,a.jsx)(w.A,{children:(0,a.jsxs)(A.A,{children:["This conversation has already been processed with its current agent."," ","If you switch to"," ",(0,a.jsx)("strong",{children:(null==(r=eb.find(e=>e.id===eq))?void 0:r.name)||"the selected agent"}),","," ","the conversation will continue from that agent's starting point."]})}),(0,a.jsxs)(j.A,{children:[(0,a.jsx)(m.A,{onClick:()=>eY(null),children:"Cancel"}),(0,a.jsx)(m.A,{variant:"contained",onClick:()=>{eY(null),eq&&nw(eq)},children:"Switch Agent"})]})]}),(0,a.jsx)(tW,{open:nu,onClose:()=>nh(!1),onStart:np})]})},nX=(0,tO.h)("frontend/components/ClientOnly");function nJ(e){let{children:t}=e,[n,r]=(0,o.useState)(!1);return((0,o.useEffect)(()=>(nX.debug("ClientOnly component mounted"),r(!0),()=>{nX.debug("ClientOnly component unmounted")}),[]),n)?(nX.debug("ClientOnly component rendering children"),(0,a.jsx)(a.Fragment,{children:t})):(nX.debug("ClientOnly component rendering null (not yet mounted)"),null)}let nQ=(0,tO.h)("app/chat/page");function nY(){return nQ.debug("Rendering ChatPage"),(0,a.jsx)(r.A,{maxWidth:!1,disableGutters:!0,children:(0,a.jsx)(nJ,{children:(0,a.jsx)(nG,{})})})}},75870:(e,t,n)=>{"use strict";n.d(t,{A:()=>g});var a=n(95155),o=n(12115),r=n(94049),l=n(25635),i=n(4474),s=n(91871),d=n(56900),c=n(90057),u=n(96362),h=n(92241),p=n(68503);let g=e=>{let{selectedFlowId:t,onSelectFlow:n,disabled:g=!1,hideLabel:f=!1}=e,[m,v]=(0,o.useState)([]),[x,y]=(0,o.useState)(!0),[b,w]=(0,o.useState)(null),[A,j]=(0,o.useState)(!1);(0,o.useEffect)(()=>{(async()=>{y(!0),w(null);try{let e=await c.g.loadFlows();v(e)}catch(e){console.error("Error loading flows:",e),w("Failed to load agents")}finally{y(!1)}})()},[]);let k=e=>{n(e),j(!1)},I=async e=>{let t=m.find(t=>t.id===e);if(!t)return;let n=!t.favorite,a={...t,favorite:n||void 0};try{(await c.g.updateFlow(a)).success&&v(t=>t.map(t=>t.id===e?a:t))}catch(e){console.error("Error toggling flow favorite:",e)}},S=(0,p.E)("flows",m),C=e=>({key:e.id,content:(e=>(0,a.jsx)(h.A,{flow:e,selected:e.id===t,onSelect:k,onToggleFavorite:I,pickerMode:!0}))(e)}),E=S.items.map(C),T=S.groups?S.groups.map(e=>({...e,items:e.items.map(C)})):null,N=(()=>{if(!t)return"";let e=m.find(e=>e.id===t);return e?e.name:""})();return(0,a.jsxs)(r.default,{children:[!f&&(0,a.jsx)(l.A,{variant:"subtitle1",gutterBottom:!0,children:"Select Agent"}),x?(0,a.jsxs)(r.default,{sx:{display:"flex",alignItems:"center",gap:1},children:[(0,a.jsx)(i.default,{size:20}),(0,a.jsx)(l.A,{variant:"body2",color:"text.secondary",children:"Loading agents..."})]}):b?(0,a.jsx)(l.A,{color:"error",variant:"body2",children:b}):0===m.length?(0,a.jsx)(l.A,{variant:"body2",color:"text.secondary",children:"No agents available. Create an agent first."}):(0,a.jsxs)(a.Fragment,{children:[(0,a.jsx)(s.A,{variant:"outlined",startIcon:(0,a.jsx)(d.A,{}),onClick:()=>j(!0),disabled:g,sx:{textTransform:"none",maxWidth:"100%"},children:(0,a.jsx)(r.default,{component:"span",sx:{overflow:"hidden",textOverflow:"ellipsis",whiteSpace:"nowrap"},children:t&&N||"Select an agent"})}),(0,a.jsx)(l.A,{variant:"caption",color:"text.secondary",display:"block",sx:{mt:.5},children:t?'Using "'.concat(N,'" agent for this conversation'):"Select an agent for this conversation"}),(0,a.jsx)(u.A,{open:A,onClose:()=>j(!1),title:"Select an agent",description:"Pick the agent for this conversation.",skeleton:(0,a.jsx)(h.o,{}),emptyMessage:"No agents available. Create an agent first.",searchable:!0,searchPlaceholder:"Search agents…",searchTerm:S.searchTerm,onSearchChange:S.setSearchTerm,items:E,groups:T,collapsedKeys:S.collapsedKeys,onToggleGroup:S.toggleGroup})]})]})}},79415:(e,t,n)=>{Promise.resolve().then(n.bind(n,66150))}},e=>{e.O(0,[1137,3862,7926,4754,7758,3392,2678,981,1983,1871,5954,9562,3816,3272,155,4123,8598,9611,3303,5418,1675,4386,6547,8620,4483,4755,9053,1161,4814,1521,3731,5967,8441,1255,7358],()=>e(e.s=79415)),_N_E=e.O()}]);