collavre 0.24.1 → 0.30.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 (1320) hide show
  1. checksums.yaml +4 -4
  2. data/README.md +19 -11
  3. data/app/assets/images/collavre/kollavy.png +0 -0
  4. data/app/assets/images/collavre/kollavy.svg +9 -0
  5. data/app/assets/stylesheets/collavre/actiontext.css +24 -165
  6. data/app/assets/stylesheets/collavre/activity_logs.css +23 -12
  7. data/app/assets/stylesheets/collavre/agent_connections.css +196 -0
  8. data/app/assets/stylesheets/collavre/agent_gateways.css +153 -0
  9. data/app/assets/stylesheets/collavre/attachment_card.css +34 -0
  10. data/app/assets/stylesheets/collavre/comments_popup.css +668 -165
  11. data/app/assets/stylesheets/collavre/creatives.css +1165 -155
  12. data/app/assets/stylesheets/collavre/dark_mode.css +0 -20
  13. data/app/assets/stylesheets/collavre/design_tokens.css +79 -0
  14. data/app/assets/stylesheets/collavre/desktop_setup.css +241 -0
  15. data/app/assets/stylesheets/collavre/gnb.css +64 -3
  16. data/app/assets/stylesheets/collavre/image_lightbox.css +12 -0
  17. data/app/assets/stylesheets/collavre/landing.css +130 -106
  18. data/app/assets/stylesheets/collavre/llm_usages.css +67 -0
  19. data/app/assets/stylesheets/collavre/mention_menu.css +50 -0
  20. data/app/assets/stylesheets/collavre/modal_dialog.css +66 -3
  21. data/app/assets/stylesheets/collavre/notice_bar.css +465 -0
  22. data/app/assets/stylesheets/collavre/org_chart.css +0 -4
  23. data/app/assets/stylesheets/collavre/popup.css +29 -18
  24. data/app/assets/stylesheets/collavre/print.css +0 -1
  25. data/app/assets/stylesheets/collavre/search_popup.css +1 -35
  26. data/app/assets/stylesheets/collavre/secret_fields.css +3 -0
  27. data/app/assets/stylesheets/collavre/slide_view.css +221 -4
  28. data/app/assets/stylesheets/collavre/workflow_editor.css +101 -0
  29. data/app/assets/stylesheets/collavre/workspace.css +310 -0
  30. data/app/channels/collavre/agent_channel.rb +61 -43
  31. data/app/channels/collavre/comments_presence_channel.rb +181 -21
  32. data/app/channels/collavre/inbox_badge_channel.rb +7 -1
  33. data/app/components/collavre/command_menu_component.html.erb +5 -0
  34. data/app/components/collavre/command_menu_component.rb +8 -0
  35. data/app/components/collavre/comment_user_menu_component.html.erb +61 -0
  36. data/app/components/collavre/comment_user_menu_component.rb +14 -0
  37. data/app/components/collavre/cron_badge_component.html.erb +80 -0
  38. data/app/components/collavre/cron_badge_component.rb +50 -0
  39. data/app/components/collavre/inbox/badge_component.rb +6 -13
  40. data/app/components/collavre/progress_filter_component.html.erb +2 -2
  41. data/app/components/collavre/progress_filter_component.rb +20 -0
  42. data/app/controllers/collavre/admin/orchestration_controller.rb +59 -32
  43. data/app/controllers/collavre/admin/settings_controller.rb +80 -8
  44. data/app/controllers/collavre/agent_connections_controller.rb +153 -0
  45. data/app/controllers/collavre/agent_gateways_controller.rb +132 -0
  46. data/app/controllers/collavre/agent_models_controller.rb +55 -0
  47. data/app/controllers/collavre/agent_provisioning_controller.rb +88 -0
  48. data/app/controllers/collavre/api/v1/agents_controller.rb +81 -249
  49. data/app/controllers/collavre/api/v1/task_suspensions_controller.rb +60 -0
  50. data/app/controllers/collavre/application_controller.rb +13 -2
  51. data/app/controllers/collavre/attachments_controller.rb +12 -12
  52. data/app/controllers/collavre/comment_read_pointers_controller.rb +69 -40
  53. data/app/controllers/collavre/comments/activity_logs_controller.rb +2 -0
  54. data/app/controllers/collavre/comments/reactions_controller.rb +10 -12
  55. data/app/controllers/collavre/comments/resends_controller.rb +21 -0
  56. data/app/controllers/collavre/comments/versions_controller.rb +24 -21
  57. data/app/controllers/collavre/comments_controller.rb +104 -139
  58. data/app/controllers/collavre/concerns/creative_history_trackable.rb +31 -0
  59. data/app/controllers/collavre/concerns/shareable.rb +9 -3
  60. data/app/controllers/collavre/concerns/tree_manageable.rb +4 -0
  61. data/app/controllers/collavre/creative_change_sets_controller.rb +112 -0
  62. data/app/controllers/collavre/creative_imports_controller.rb +9 -1
  63. data/app/controllers/collavre/creative_invitations_controller.rb +2 -11
  64. data/app/controllers/collavre/creative_shares_controller.rb +7 -15
  65. data/app/controllers/collavre/creatives/attachments_controller.rb +16 -4
  66. data/app/controllers/collavre/creatives/file_drops_controller.rb +35 -0
  67. data/app/controllers/collavre/creatives/ppt_previews_controller.rb +66 -0
  68. data/app/controllers/collavre/creatives_controller.rb +186 -276
  69. data/app/controllers/collavre/crons_controller.rb +48 -0
  70. data/app/controllers/collavre/desktop_gateway_registrations_controller.rb +156 -0
  71. data/app/controllers/collavre/desktop_setup_controller.rb +102 -0
  72. data/app/controllers/collavre/desktop_sidecar_health_controller.rb +23 -0
  73. data/app/controllers/collavre/features_controller.rb +57 -0
  74. data/app/controllers/collavre/google_auth_controller.rb +3 -4
  75. data/app/controllers/collavre/inline_agent_logins_controller.rb +79 -0
  76. data/app/controllers/collavre/invites_controller.rb +12 -1
  77. data/app/controllers/collavre/llm_models_controller.rb +8 -0
  78. data/app/controllers/collavre/llm_usages_controller.rb +51 -0
  79. data/app/controllers/collavre/notices_controller.rb +20 -0
  80. data/app/controllers/collavre/onboarding_replays_controller.rb +10 -0
  81. data/app/controllers/collavre/public_assets_controller.rb +48 -4
  82. data/app/controllers/collavre/seo_controller.rb +83 -0
  83. data/app/controllers/collavre/sessions_controller.rb +5 -9
  84. data/app/controllers/collavre/tasks_controller.rb +40 -6
  85. data/app/controllers/collavre/topics_controller.rb +136 -74
  86. data/app/controllers/collavre/user_creative_preferences_controller.rb +182 -31
  87. data/app/controllers/collavre/user_notices_controller.rb +64 -0
  88. data/app/controllers/collavre/user_themes_controller.rb +11 -7
  89. data/app/controllers/collavre/users_controller.rb +1 -0
  90. data/app/controllers/concerns/collavre/active_storage_access.rb +127 -0
  91. data/app/controllers/concerns/collavre/api/claude_channel_prompts.rb +209 -0
  92. data/app/controllers/concerns/collavre/blob_access_control.rb +57 -0
  93. data/app/controllers/concerns/collavre/comments/approval_actions.rb +24 -22
  94. data/app/controllers/concerns/collavre/comments/approval_gate_actions.rb +29 -0
  95. data/app/controllers/concerns/collavre/comments/batch_operations.rb +16 -4
  96. data/app/controllers/concerns/collavre/comments/comment_scoping.rb +4 -2
  97. data/app/controllers/concerns/collavre/comments/conversion.rb +1 -1
  98. data/app/controllers/concerns/collavre/comments/history_topic_guard.rb +22 -0
  99. data/app/controllers/concerns/collavre/creative_destroyable.rb +41 -0
  100. data/app/controllers/concerns/collavre/creative_permission_guard.rb +6 -0
  101. data/app/controllers/concerns/collavre/creative_type_editable.rb +76 -0
  102. data/app/controllers/concerns/collavre/loopback_request.rb +32 -0
  103. data/app/controllers/concerns/collavre/origin_verification.rb +29 -0
  104. data/app/controllers/concerns/collavre/permission_update_response.rb +23 -0
  105. data/app/controllers/concerns/collavre/proxy_error_response.rb +14 -0
  106. data/app/controllers/concerns/collavre/public_creative_page.rb +52 -0
  107. data/app/controllers/concerns/collavre/public_creative_redirectable.rb +31 -0
  108. data/app/controllers/concerns/collavre/successful_authentication.rb +12 -0
  109. data/app/controllers/concerns/collavre/svg_streaming.rb +39 -0
  110. data/app/controllers/concerns/collavre/topics/reserved_topic_guard.rb +52 -0
  111. data/app/controllers/concerns/collavre/user_creative_preferences_controller/persistence.rb +98 -0
  112. data/app/controllers/concerns/collavre/users_controller/admin_operations.rb +38 -12
  113. data/app/controllers/concerns/collavre/users_controller/ai_profile_access.rb +25 -0
  114. data/app/controllers/concerns/collavre/users_controller/ai_user_management.rb +182 -32
  115. data/app/controllers/concerns/collavre/users_controller/contact_management.rb +31 -18
  116. data/app/controllers/concerns/collavre/users_controller/profile_and_settings.rb +15 -15
  117. data/app/controllers/concerns/collavre/users_controller/registration.rb +9 -13
  118. data/app/controllers/concerns/collavre/workflow_editable.rb +112 -0
  119. data/app/errors/collavre/approval_gate_pending_error.rb +12 -0
  120. data/app/errors/collavre/approval_pending_error.rb +5 -2
  121. data/app/errors/collavre/screening_pending_error.rb +17 -0
  122. data/app/errors/collavre/task_suspended_error.rb +11 -0
  123. data/app/errors/collavre/turn_deadline_error.rb +20 -0
  124. data/app/helpers/collavre/activity_logs_helper.rb +26 -0
  125. data/app/helpers/collavre/application_helper.rb +45 -41
  126. data/app/helpers/collavre/creative_move_helper.rb +15 -0
  127. data/app/helpers/collavre/creatives_helper.rb +158 -72
  128. data/app/helpers/collavre/navigation_helper.rb +134 -0
  129. data/app/helpers/collavre/public_assets_helper.rb +14 -0
  130. data/app/helpers/collavre/public_creatives_helper.rb +44 -0
  131. data/app/javascript/__tests__/slide_view.test.js +30 -0
  132. data/app/javascript/collavre.js +4 -2
  133. data/app/javascript/collavre_pdf_viewer.js +3 -0
  134. data/app/javascript/collavre_pdf_worker.js +1 -0
  135. data/app/javascript/comments/__tests__/user_menu.test.js +137 -0
  136. data/app/javascript/comments/user_menu.js +205 -0
  137. data/app/javascript/components/EmojiPicker.js +90 -0
  138. data/app/javascript/components/HeadingButtons.js +45 -0
  139. data/app/javascript/components/HistoryButtons.jsx +26 -0
  140. data/app/javascript/components/ImageResizer.jsx +11 -30
  141. data/app/javascript/components/InlineLexicalEditor.jsx +29 -78
  142. data/app/javascript/components/__tests__/EmojiPicker.test.js +127 -0
  143. data/app/javascript/components/__tests__/HeadingButtons.test.js +111 -0
  144. data/app/javascript/components/__tests__/creative_tree_row_document_view.test.js +814 -0
  145. data/app/javascript/components/__tests__/creative_tree_row_parent_id.test.js +32 -2
  146. data/app/javascript/components/__tests__/creative_tree_row_progress_toggle.test.js +255 -0
  147. data/app/javascript/components/__tests__/document_row_swipe.test.js +206 -0
  148. data/app/javascript/components/creative_header_progress.js +24 -0
  149. data/app/javascript/components/creative_tree_row.js +96 -99
  150. data/app/javascript/components/creative_tree_row_document_view.js +251 -0
  151. data/app/javascript/components/document_row_swipe.js +107 -0
  152. data/app/javascript/components/plugins/__tests__/creative_links_plugin.test.js +59 -0
  153. data/app/javascript/components/plugins/__tests__/image_upload_plugin.test.js +107 -0
  154. data/app/javascript/components/plugins/creative_links_plugin.js +24 -0
  155. data/app/javascript/components/plugins/image_upload_plugin.jsx +24 -28
  156. data/app/javascript/components/plugins/markdown_shortcuts_plugin.jsx +5 -2
  157. data/app/javascript/controllers/__tests__/agent_connection_controller.test.js +625 -0
  158. data/app/javascript/controllers/__tests__/agent_vendor_controller.test.js +94 -0
  159. data/app/javascript/controllers/__tests__/comment_agent_model_controller.test.js +148 -0
  160. data/app/javascript/controllers/__tests__/comment_approval_controls.test.js +45 -0
  161. data/app/javascript/controllers/__tests__/comment_user_menu_controller.test.js +285 -0
  162. data/app/javascript/controllers/__tests__/comment_version_controller.test.js +51 -0
  163. data/app/javascript/controllers/__tests__/controller_csrf_requests.test.js +137 -0
  164. data/app/javascript/controllers/__tests__/creative_history_controller.test.js +123 -0
  165. data/app/javascript/controllers/__tests__/creative_history_detail_controller.test.js +104 -0
  166. data/app/javascript/controllers/__tests__/creative_history_undo_controller.test.js +55 -0
  167. data/app/javascript/controllers/__tests__/creative_image_lightbox_controller.test.js +583 -0
  168. data/app/javascript/controllers/__tests__/creative_move_controller.test.js +713 -0
  169. data/app/javascript/controllers/__tests__/cron_badge_controller.test.js +436 -0
  170. data/app/javascript/controllers/__tests__/desktop_proxy_setup_controller.test.js +96 -0
  171. data/app/javascript/controllers/__tests__/document_preview_controller.test.js +33 -0
  172. data/app/javascript/controllers/__tests__/entity_list_controller.test.js +270 -0
  173. data/app/javascript/controllers/__tests__/expansion_controller.test.js +235 -0
  174. data/app/javascript/controllers/__tests__/index.test.js +48 -0
  175. data/app/javascript/controllers/__tests__/inline_creative_picker_controller.test.js +232 -0
  176. data/app/javascript/controllers/__tests__/last_visited_creative_controller.test.js +103 -0
  177. data/app/javascript/controllers/__tests__/link_creative_controller.test.js +354 -2
  178. data/app/javascript/controllers/__tests__/notice_bar_controller.test.js +1076 -0
  179. data/app/javascript/controllers/__tests__/popup_menu_controller.test.js +267 -0
  180. data/app/javascript/controllers/__tests__/progress_filter_controller.test.js +134 -0
  181. data/app/javascript/controllers/__tests__/search_popup_controller.test.js +324 -0
  182. data/app/javascript/controllers/__tests__/share_modal_public_link.test.js +113 -0
  183. data/app/javascript/controllers/__tests__/share_user_search_controller.test.js +17 -0
  184. data/app/javascript/controllers/__tests__/tabs_controller.test.js +137 -0
  185. data/app/javascript/controllers/__tests__/tool_category_controller.test.js +116 -0
  186. data/app/javascript/controllers/__tests__/topic_list_controller.test.js +125 -0
  187. data/app/javascript/controllers/__tests__/workspace_tree_controller.test.js +1746 -0
  188. data/app/javascript/controllers/agent_auth_controller.js +245 -0
  189. data/app/javascript/controllers/agent_connection_controller.js +197 -0
  190. data/app/javascript/controllers/agent_vendor_controller.js +69 -0
  191. data/app/javascript/controllers/comment_agent_model_controller.js +87 -0
  192. data/app/javascript/controllers/comment_controller.js +34 -75
  193. data/app/javascript/controllers/comment_image_lightbox_controller.js +15 -0
  194. data/app/javascript/controllers/comment_user_menu_controller.js +122 -0
  195. data/app/javascript/controllers/comment_version_controller.js +10 -8
  196. data/app/javascript/controllers/comments/__tests__/comment_form_request.test.js +72 -0
  197. data/app/javascript/controllers/comments/__tests__/comment_list_response.test.js +30 -0
  198. data/app/javascript/controllers/comments/__tests__/comment_read_tracker.test.js +71 -0
  199. data/app/javascript/controllers/comments/__tests__/contexts_controller_context_list.test.js +466 -0
  200. data/app/javascript/controllers/comments/__tests__/contexts_controller_dnd.test.js +484 -0
  201. data/app/javascript/controllers/comments/__tests__/creative_quote_review_controller.test.js +111 -0
  202. data/app/javascript/controllers/comments/__tests__/drop_trigger_controller.test.js +48 -0
  203. data/app/javascript/controllers/comments/__tests__/feature_cards_controller.test.js +223 -0
  204. data/app/javascript/controllers/comments/__tests__/form_controller_default_placeholder.test.js +83 -0
  205. data/app/javascript/controllers/comments/__tests__/form_controller_double_submit.test.js +38 -0
  206. data/app/javascript/controllers/comments/__tests__/form_controller_draft.test.js +2254 -0
  207. data/app/javascript/controllers/comments/__tests__/form_controller_ime_send.test.js +324 -0
  208. data/app/javascript/controllers/comments/__tests__/form_controller_review.test.js +377 -2
  209. data/app/javascript/controllers/comments/__tests__/form_controller_search_submit.test.js +106 -0
  210. data/app/javascript/controllers/comments/__tests__/form_controller_stashed_draft.test.js +134 -0
  211. data/app/javascript/controllers/comments/__tests__/form_controller_stashed_draft_creative_switch.test.js +166 -0
  212. data/app/javascript/controllers/comments/__tests__/form_controller_stashed_draft_failure.test.js +183 -0
  213. data/app/javascript/controllers/comments/__tests__/form_draft_manager.test.js +154 -0
  214. data/app/javascript/controllers/comments/__tests__/inline_login_preservation.test.js +23 -0
  215. data/app/javascript/controllers/comments/__tests__/list_controller_approval_gate.test.js +51 -0
  216. data/app/javascript/controllers/comments/__tests__/list_controller_batch_delete.test.js +97 -0
  217. data/app/javascript/controllers/comments/__tests__/list_controller_deep_link_topic.test.js +467 -0
  218. data/app/javascript/controllers/comments/__tests__/list_controller_dnd.test.js +26 -0
  219. data/app/javascript/controllers/comments/__tests__/list_controller_docked.test.js +168 -0
  220. data/app/javascript/controllers/comments/__tests__/list_controller_load_result.test.js +56 -0
  221. data/app/javascript/controllers/comments/__tests__/list_controller_loading.test.js +43 -0
  222. data/app/javascript/controllers/comments/__tests__/list_controller_prev_message.test.js +217 -1
  223. data/app/javascript/controllers/comments/__tests__/list_controller_read_pointer.test.js +288 -0
  224. data/app/javascript/controllers/comments/__tests__/list_controller_resend.test.js +69 -0
  225. data/app/javascript/controllers/comments/__tests__/list_controller_resume_pagination.test.js +191 -0
  226. data/app/javascript/controllers/comments/__tests__/list_controller_stream_archived.test.js +221 -0
  227. data/app/javascript/controllers/comments/__tests__/list_controller_stream_search.test.js +104 -0
  228. data/app/javascript/controllers/comments/__tests__/loading_controller.test.js +83 -0
  229. data/app/javascript/controllers/comments/__tests__/mention_menu_controller.test.js +59 -0
  230. data/app/javascript/controllers/comments/__tests__/placeholder_controller.test.js +79 -0
  231. data/app/javascript/controllers/comments/__tests__/popup_controller.test.js +1070 -3
  232. data/app/javascript/controllers/comments/__tests__/popup_exit_target.test.js +118 -0
  233. data/app/javascript/controllers/comments/__tests__/popup_focus.test.js +72 -0
  234. data/app/javascript/controllers/comments/__tests__/popup_fullscreen.test.js +320 -0
  235. data/app/javascript/controllers/comments/__tests__/popup_initial_url.test.js +103 -0
  236. data/app/javascript/controllers/comments/__tests__/popup_resume_resync.test.js +154 -0
  237. data/app/javascript/controllers/comments/__tests__/presence_controller.test.js +775 -15
  238. data/app/javascript/controllers/comments/__tests__/presence_controller_agent_online.test.js +244 -0
  239. data/app/javascript/controllers/comments/__tests__/presence_controller_participant_list.test.js +570 -0
  240. data/app/javascript/controllers/comments/__tests__/resend_action.test.js +137 -0
  241. data/app/javascript/controllers/comments/__tests__/review_quotes_store.test.js +27 -0
  242. data/app/javascript/controllers/comments/__tests__/run_options_controller.test.js +248 -0
  243. data/app/javascript/controllers/comments/__tests__/topics_controller_action_errors.test.js +6 -0
  244. data/app/javascript/controllers/comments/__tests__/topics_controller_archived.test.js +924 -0
  245. data/app/javascript/controllers/comments/__tests__/topics_controller_creation_container.test.js +165 -0
  246. data/app/javascript/controllers/comments/__tests__/topics_controller_creation_scroll.test.js +92 -0
  247. data/app/javascript/controllers/comments/__tests__/topics_controller_delete.test.js +361 -0
  248. data/app/javascript/controllers/comments/__tests__/topics_controller_dnd.test.js +120 -0
  249. data/app/javascript/controllers/comments/__tests__/topics_controller_docked.test.js +32 -0
  250. data/app/javascript/controllers/comments/__tests__/topics_controller_last_topic_echo.test.js +1938 -0
  251. data/app/javascript/controllers/comments/__tests__/topics_controller_primary_agent.test.js +112 -2
  252. data/app/javascript/controllers/comments/__tests__/topics_controller_scroll.test.js +199 -0
  253. data/app/javascript/controllers/comments/__tests__/topics_controller_selection_race.test.js +1253 -0
  254. data/app/javascript/controllers/comments/__tests__/topics_controller_topic_list.test.js +313 -0
  255. data/app/javascript/controllers/comments/approval_request_options.js +12 -0
  256. data/app/javascript/controllers/comments/comment_form_request.js +26 -0
  257. data/app/javascript/controllers/comments/comment_list_response.js +20 -0
  258. data/app/javascript/controllers/comments/comment_read_tracker.js +143 -0
  259. data/app/javascript/controllers/comments/contexts_controller.js +338 -226
  260. data/app/javascript/controllers/comments/creative_chat_navigation.js +50 -0
  261. data/app/javascript/controllers/comments/creative_quote_review_controller.js +30 -0
  262. data/app/javascript/controllers/comments/drop_trigger_controller.js +2 -7
  263. data/app/javascript/controllers/comments/feature_cards_controller.js +83 -0
  264. data/app/javascript/controllers/comments/form_controller.js +375 -175
  265. data/app/javascript/controllers/comments/form_draft_manager.js +269 -0
  266. data/app/javascript/controllers/comments/form_draft_migration.js +142 -0
  267. data/app/javascript/controllers/comments/form_draft_persistence.js +228 -0
  268. data/app/javascript/controllers/comments/inline_login_preservation.js +18 -0
  269. data/app/javascript/controllers/comments/list_controller.js +283 -186
  270. data/app/javascript/controllers/comments/loading_controller.js +48 -0
  271. data/app/javascript/controllers/comments/mention_menu_controller.js +1 -24
  272. data/app/javascript/controllers/comments/optimistic_removal.js +15 -0
  273. data/app/javascript/controllers/comments/pagination_state.js +20 -0
  274. data/app/javascript/controllers/comments/placeholder_controller.js +30 -0
  275. data/app/javascript/controllers/comments/popup_controller.js +379 -473
  276. data/app/javascript/controllers/comments/popup_creative_progress.js +51 -0
  277. data/app/javascript/controllers/comments/popup_exit_target.js +92 -0
  278. data/app/javascript/controllers/comments/popup_focus.js +5 -0
  279. data/app/javascript/controllers/comments/popup_fullscreen.js +335 -0
  280. data/app/javascript/controllers/comments/popup_resume_resync.js +28 -0
  281. data/app/javascript/controllers/comments/popup_url_open.js +22 -0
  282. data/app/javascript/controllers/comments/presence_controller.js +598 -183
  283. data/app/javascript/controllers/comments/previous_message_navigation.js +154 -0
  284. data/app/javascript/controllers/comments/resend_action.js +63 -0
  285. data/app/javascript/controllers/comments/review_quotes_store.js +11 -8
  286. data/app/javascript/controllers/comments/run_options_controller.js +145 -0
  287. data/app/javascript/controllers/comments/topics/last_topic_save.js +124 -0
  288. data/app/javascript/controllers/comments/topics/reserved_topic_deletion.js +25 -0
  289. data/app/javascript/controllers/comments/topics/save_order_state.js +127 -0
  290. data/app/javascript/controllers/comments/topics/selection_restore_state.js +42 -0
  291. data/app/javascript/controllers/comments/topics/self_echo_state.js +24 -0
  292. data/app/javascript/controllers/comments/topics_controller.js +1723 -240
  293. data/app/javascript/controllers/common_popup_controller.js +2 -2
  294. data/app/javascript/controllers/creative_history_controller.js +57 -0
  295. data/app/javascript/controllers/creative_history_detail_controller.js +41 -0
  296. data/app/javascript/controllers/creative_history_undo_controller.js +19 -0
  297. data/app/javascript/controllers/creative_image_lightbox_controller.js +114 -0
  298. data/app/javascript/controllers/creative_move_controller.js +202 -0
  299. data/app/javascript/controllers/creatives/__tests__/document_selection_controller.test.js +241 -0
  300. data/app/javascript/controllers/creatives/__tests__/document_view_controller.test.js +173 -0
  301. data/app/javascript/controllers/creatives/__tests__/drag_drop_controller.test.js +74 -0
  302. data/app/javascript/controllers/creatives/__tests__/import_controller.test.js +48 -0
  303. data/app/javascript/controllers/creatives/__tests__/select_mode_controller.test.js +250 -0
  304. data/app/javascript/controllers/creatives/__tests__/tree_controller.test.js +1210 -2
  305. data/app/javascript/controllers/creatives/__tests__/workflow_rule_controller.test.js +322 -0
  306. data/app/javascript/controllers/creatives/__tests__/write_access_request_controller.test.js +125 -0
  307. data/app/javascript/controllers/creatives/document_selection_controller.js +77 -0
  308. data/app/javascript/controllers/creatives/document_view_controller.js +82 -0
  309. data/app/javascript/controllers/creatives/drag_drop_controller.js +13 -19
  310. data/app/javascript/controllers/creatives/expansion_controller.js +21 -19
  311. data/app/javascript/controllers/creatives/import_controller.js +1 -1
  312. data/app/javascript/controllers/creatives/select_mode_controller.js +38 -6
  313. data/app/javascript/controllers/creatives/tree_controller.js +260 -59
  314. data/app/javascript/controllers/creatives/workflow_rule_controller.js +96 -0
  315. data/app/javascript/controllers/creatives/workflow_rule_form.js +183 -0
  316. data/app/javascript/controllers/creatives/write_access_request_controller.js +58 -0
  317. data/app/javascript/controllers/cron_badge_controller.js +187 -0
  318. data/app/javascript/controllers/desktop_proxy_setup_controller.js +51 -0
  319. data/app/javascript/controllers/document_preview_controller.js +16 -0
  320. data/app/javascript/controllers/entity_list_controller.js +147 -0
  321. data/app/javascript/controllers/gateway_check_controller.js +34 -0
  322. data/app/javascript/controllers/image_lightbox_controller.js +29 -70
  323. data/app/javascript/controllers/image_lightbox_values.js +13 -0
  324. data/app/javascript/controllers/index.js +106 -8
  325. data/app/javascript/controllers/inline_creative_picker_controller.js +110 -0
  326. data/app/javascript/controllers/last_visited_creative_controller.js +58 -0
  327. data/app/javascript/controllers/link_creative_controller.js +102 -28
  328. data/app/javascript/controllers/notice_bar_controller.js +364 -0
  329. data/app/javascript/controllers/org_chart_controller.js +2 -23
  330. data/app/javascript/controllers/popup_menu_controller.js +128 -45
  331. data/app/javascript/controllers/progress_filter_controller.js +12 -22
  332. data/app/javascript/controllers/search_popup_controller.js +72 -50
  333. data/app/javascript/controllers/searchable_list_controller.js +30 -0
  334. data/app/javascript/controllers/share_modal_controller.js +18 -56
  335. data/app/javascript/controllers/share_user_search_controller.js +3 -13
  336. data/app/javascript/controllers/tabs_controller.js +5 -1
  337. data/app/javascript/controllers/tool_category_controller.js +39 -0
  338. data/app/javascript/controllers/topic_list_controller.js +42 -31
  339. data/app/javascript/controllers/topic_search_controller.js +2 -4
  340. data/app/javascript/controllers/workspace_tree_controller.js +803 -0
  341. data/app/javascript/creatives/__tests__/row_progress.test.js +155 -0
  342. data/app/javascript/creatives/__tests__/tree_reload_events.test.js +101 -0
  343. data/app/javascript/creatives/__tests__/tree_renderer.test.js +195 -0
  344. data/app/javascript/creatives/__tests__/tree_view_state.test.js +277 -0
  345. data/app/javascript/creatives/branch_expansion.js +39 -0
  346. data/app/javascript/creatives/drag_drop/__tests__/command_integration.test.js +194 -0
  347. data/app/javascript/creatives/drag_drop/__tests__/creative_tree_drop.test.js +964 -0
  348. data/app/javascript/creatives/drag_drop/__tests__/drop_completion_empty_state.test.js +98 -0
  349. data/app/javascript/creatives/drag_drop/__tests__/event_handlers_data.test.js +329 -0
  350. data/app/javascript/creatives/drag_drop/__tests__/file_drop.test.js +99 -0
  351. data/app/javascript/creatives/drag_drop/__tests__/hover_expand.test.js +134 -0
  352. data/app/javascript/creatives/drag_drop/__tests__/indicator.test.js +36 -0
  353. data/app/javascript/creatives/drag_drop/__tests__/move_command.test.js +471 -0
  354. data/app/javascript/creatives/drag_drop/__tests__/move_command_dom_recovery.test.js +346 -0
  355. data/app/javascript/creatives/drag_drop/__tests__/move_command_queued_saves.test.js +201 -0
  356. data/app/javascript/creatives/drag_drop/__tests__/move_feedback.test.js +79 -0
  357. data/app/javascript/creatives/drag_drop/__tests__/source_window_bundle.test.js +141 -0
  358. data/app/javascript/creatives/drag_drop/__tests__/state.test.js +36 -0
  359. data/app/javascript/creatives/drag_drop/__tests__/topic_move_released_agent.test.js +125 -0
  360. data/app/javascript/creatives/drag_drop/__tests__/touch_tree_integration.test.js +209 -0
  361. data/app/javascript/creatives/drag_drop/__tests__/workspace_tree_adapter.test.js +517 -0
  362. data/app/javascript/creatives/drag_drop/__tests__/workspace_tree_dom.test.js +105 -0
  363. data/app/javascript/creatives/drag_drop/dom.js +9 -0
  364. data/app/javascript/creatives/drag_drop/event_handlers.js +291 -431
  365. data/app/javascript/creatives/drag_drop/file_drop.js +60 -0
  366. data/app/javascript/creatives/drag_drop/indicator.js +2 -1
  367. data/app/javascript/creatives/drag_drop/move_command.js +297 -0
  368. data/app/javascript/creatives/drag_drop/move_feedback.js +22 -0
  369. data/app/javascript/creatives/drag_drop/operations.js +73 -0
  370. data/app/javascript/creatives/drag_drop/state.js +10 -1
  371. data/app/javascript/creatives/drag_drop/workspace_tree_adapter.js +161 -0
  372. data/app/javascript/creatives/drag_drop/workspace_tree_dom.js +52 -0
  373. data/app/javascript/creatives/row_progress.js +96 -0
  374. data/app/javascript/creatives/tree_reload_events.js +42 -0
  375. data/app/javascript/creatives/tree_renderer.js +132 -40
  376. data/app/javascript/creatives/tree_view_state.js +87 -0
  377. data/app/javascript/lib/__tests__/chat_drafts.test.js +1458 -0
  378. data/app/javascript/lib/__tests__/common_popup_bounds.test.js +8 -3
  379. data/app/javascript/lib/__tests__/common_popup_placement.test.js +374 -0
  380. data/app/javascript/lib/__tests__/common_popup_reshow.test.js +131 -0
  381. data/app/javascript/lib/__tests__/creative_link_prefetch.test.js +46 -0
  382. data/app/javascript/lib/__tests__/creative_quote.test.js +343 -0
  383. data/app/javascript/lib/__tests__/creative_title.test.js +15 -0
  384. data/app/javascript/lib/__tests__/entity_list_popup.test.js +47 -0
  385. data/app/javascript/lib/__tests__/html_escape.test.js +29 -0
  386. data/app/javascript/lib/__tests__/last_visited_creative.test.js +87 -0
  387. data/app/javascript/lib/__tests__/permission_update.test.js +38 -0
  388. data/app/javascript/lib/__tests__/popup_toggle_guard.test.js +82 -0
  389. data/app/javascript/lib/__tests__/ppt_background.test.js +86 -0
  390. data/app/javascript/lib/__tests__/ppt_connector.test.js +80 -0
  391. data/app/javascript/lib/__tests__/ppt_formatting.test.js +246 -0
  392. data/app/javascript/lib/__tests__/ppt_media.test.js +86 -0
  393. data/app/javascript/lib/__tests__/quote_selection_popup.test.js +100 -0
  394. data/app/javascript/lib/__tests__/skill_html_entities.test.js +23 -0
  395. data/app/javascript/lib/__tests__/touch_drag_tap.test.js +31 -0
  396. data/app/javascript/lib/__tests__/touch_drag_targets.test.js +293 -0
  397. data/app/javascript/lib/__tests__/turbo_stream_actions.test.js +218 -0
  398. data/app/javascript/lib/__tests__/workspace_scroll_restoration.test.js +310 -0
  399. data/app/javascript/lib/__tests__/workspace_tree_removal.test.js +108 -0
  400. data/app/javascript/lib/api/__tests__/creatives.test.js +94 -0
  401. data/app/javascript/lib/api/__tests__/csrf_fetch.test.js +27 -0
  402. data/app/javascript/lib/api/__tests__/drag_drop.test.js +136 -0
  403. data/app/javascript/lib/api/__tests__/expansion_intent.test.js +75 -0
  404. data/app/javascript/lib/api/__tests__/expansion_save_queue.test.js +110 -0
  405. data/app/javascript/lib/api/__tests__/queue_manager.test.js +237 -0
  406. data/app/javascript/lib/api/__tests__/queue_reconciliation.test.js +57 -0
  407. data/app/javascript/lib/api/__tests__/queue_recovery.test.js +28 -0
  408. data/app/javascript/lib/api/__tests__/topics_save_last_topic.test.js +112 -0
  409. data/app/javascript/lib/api/creatives.js +35 -13
  410. data/app/javascript/lib/api/csrf_fetch.js +6 -4
  411. data/app/javascript/lib/api/drag_drop.js +25 -1
  412. data/app/javascript/lib/api/expansion_intent.js +28 -0
  413. data/app/javascript/lib/api/expansion_save_queue.js +51 -0
  414. data/app/javascript/lib/api/queue_completion.js +30 -0
  415. data/app/javascript/lib/api/queue_manager.js +34 -50
  416. data/app/javascript/lib/api/queue_reconciliation.js +44 -0
  417. data/app/javascript/lib/api/queue_recovery.js +24 -0
  418. data/app/javascript/lib/api/topics.js +63 -5
  419. data/app/javascript/lib/chat_drafts.js +786 -0
  420. data/app/javascript/lib/common_popup.js +164 -25
  421. data/app/javascript/lib/creative_link_prefetch.js +27 -0
  422. data/app/javascript/lib/creative_quote.js +135 -0
  423. data/app/javascript/lib/creative_title.js +9 -0
  424. data/app/javascript/lib/creative_tree_invalidation.js +4 -0
  425. data/app/javascript/lib/dnd/__tests__/bundle_image.test.js +32 -0
  426. data/app/javascript/lib/dnd/__tests__/envelope.test.js +262 -0
  427. data/app/javascript/lib/dnd/__tests__/hit_test.test.js +69 -0
  428. data/app/javascript/lib/dnd/__tests__/preview.test.js +22 -0
  429. data/app/javascript/lib/dnd/__tests__/registry.test.js +797 -0
  430. data/app/javascript/lib/dnd/__tests__/session.test.js +213 -0
  431. data/app/javascript/lib/dnd/__tests__/session_without_window.test.js +15 -0
  432. data/app/javascript/lib/dnd/__tests__/touch_bridge.test.js +532 -0
  433. data/app/javascript/lib/dnd/creative_label.js +21 -0
  434. data/app/javascript/lib/dnd/envelope.js +194 -0
  435. data/app/javascript/lib/dnd/hit_test.js +42 -0
  436. data/app/javascript/lib/dnd/preview.js +10 -0
  437. data/app/javascript/lib/dnd/registry.js +315 -0
  438. data/app/javascript/lib/dnd/session.js +152 -0
  439. data/app/javascript/lib/dnd/touch_bridge.js +184 -0
  440. data/app/javascript/lib/editor/__tests__/code_languages.test.js +1 -5
  441. data/app/javascript/lib/editor/code_languages.js +0 -1
  442. data/app/javascript/lib/entity_list_popup.js +45 -0
  443. data/app/javascript/lib/html_escape.js +12 -0
  444. data/app/javascript/lib/image_lightbox_pan.js +31 -0
  445. data/app/javascript/lib/last_visited_creative.js +97 -0
  446. data/app/javascript/lib/lexical/__tests__/attachment_payload.test.js +12 -189
  447. data/app/javascript/lib/lexical/__tests__/creative_link_drop.test.js +414 -0
  448. data/app/javascript/lib/lexical/__tests__/creative_link_node.test.js +212 -0
  449. data/app/javascript/lib/lexical/__tests__/creative_link_trigger.test.js +133 -0
  450. data/app/javascript/lib/lexical/__tests__/file_drop.test.js +288 -0
  451. data/app/javascript/lib/lexical/__tests__/link_toolbar.test.js +62 -0
  452. data/app/javascript/lib/lexical/attachment_node.jsx +21 -42
  453. data/app/javascript/lib/lexical/attachment_payload.js +0 -274
  454. data/app/javascript/lib/lexical/attachment_presentation.js +57 -0
  455. data/app/javascript/lib/lexical/creative_link_drop.js +98 -0
  456. data/app/javascript/lib/lexical/creative_link_node.js +127 -0
  457. data/app/javascript/lib/lexical/creative_link_trigger.js +98 -0
  458. data/app/javascript/lib/lexical/file_drop.js +106 -0
  459. data/app/javascript/lib/lexical/link_toolbar.js +23 -0
  460. data/app/javascript/lib/lexical/ppt_attachment.js +26 -0
  461. data/app/javascript/lib/lexical/upload_anchor_node.js +16 -0
  462. data/app/javascript/lib/lexical/upload_nodes.js +6 -0
  463. data/app/javascript/lib/media_loading.js +25 -0
  464. data/app/javascript/lib/permission_update.js +21 -0
  465. data/app/javascript/lib/popup_toggle_guard.js +56 -0
  466. data/app/javascript/lib/ppt_background.js +48 -0
  467. data/app/javascript/lib/ppt_chart.js +59 -0
  468. data/app/javascript/lib/ppt_connector.js +63 -0
  469. data/app/javascript/lib/ppt_formatting.js +138 -0
  470. data/app/javascript/lib/ppt_media.js +61 -0
  471. data/app/javascript/lib/quote_selection_popup.js +67 -0
  472. data/app/javascript/lib/responsive_images.js +0 -12
  473. data/app/javascript/lib/search_combobox.js +61 -0
  474. data/app/javascript/lib/share_modal_links.js +35 -0
  475. data/app/javascript/lib/touch_drag.js +119 -37
  476. data/app/javascript/lib/turbo_stream_actions.js +41 -16
  477. data/app/javascript/lib/utils/__tests__/attachment_rendering.test.js +189 -0
  478. data/app/javascript/lib/utils/__tests__/creative_link_navigation.test.js +301 -0
  479. data/app/javascript/lib/utils/__tests__/filter_navigation.test.js +226 -0
  480. data/app/javascript/lib/utils/__tests__/focus.test.js +144 -0
  481. data/app/javascript/lib/utils/__tests__/markdown.test.js +44 -0
  482. data/app/javascript/lib/utils/__tests__/mermaid_math.test.js +24 -0
  483. data/app/javascript/lib/utils/__tests__/sanitize_description.test.js +10 -0
  484. data/app/javascript/lib/utils/creative_link_navigation.js +64 -0
  485. data/app/javascript/lib/utils/filter_navigation.js +114 -0
  486. data/app/javascript/lib/utils/focus.js +36 -0
  487. data/app/javascript/lib/utils/markdown.js +0 -4
  488. data/app/javascript/lib/utils/sanitize_description.js +12 -4
  489. data/app/javascript/lib/utils/workspace_chat_navigation.js +25 -0
  490. data/app/javascript/lib/viewport_region.js +20 -0
  491. data/app/javascript/lib/workspace_scroll_restoration.js +134 -0
  492. data/app/javascript/lib/workspace_tree_removal.js +91 -0
  493. data/app/javascript/lib/workspace_tree_visibility.js +25 -0
  494. data/app/javascript/modules/__tests__/background_creative_create.test.js +114 -0
  495. data/app/javascript/modules/__tests__/command_args_form.test.js +96 -0
  496. data/app/javascript/modules/__tests__/command_menu_creative_picker.test.js +62 -0
  497. data/app/javascript/modules/__tests__/command_menu_details.test.js +199 -0
  498. data/app/javascript/modules/__tests__/command_menu_typeahead.test.js +267 -0
  499. data/app/javascript/modules/__tests__/creative_inline_dataset.test.js +35 -0
  500. data/app/javascript/modules/__tests__/creative_inline_payload.test.js +35 -0
  501. data/app/javascript/modules/__tests__/creative_link_picker.test.js +85 -0
  502. data/app/javascript/modules/__tests__/creative_row_editor_archive.test.js +391 -0
  503. data/app/javascript/modules/__tests__/creative_row_editor_background_create.test.js +2147 -0
  504. data/app/javascript/modules/__tests__/creative_row_editor_delegated_clicks.test.js +158 -0
  505. data/app/javascript/modules/__tests__/creative_row_editor_empty_state_recovery.test.js +214 -0
  506. data/app/javascript/modules/__tests__/creative_row_editor_empty_state_removal.test.js +468 -0
  507. data/app/javascript/modules/__tests__/creative_row_editor_instant_reveal.test.js +186 -0
  508. data/app/javascript/modules/__tests__/creative_row_editor_save_paths.test.js +1132 -0
  509. data/app/javascript/modules/__tests__/creative_row_editor_session.test.js +144 -0
  510. data/app/javascript/modules/__tests__/creative_save_state.test.js +165 -0
  511. data/app/javascript/modules/__tests__/creative_tree_dom.test.js +30 -0
  512. data/app/javascript/modules/__tests__/creative_tree_empty_state.test.js +186 -0
  513. data/app/javascript/modules/__tests__/creative_type_editor.test.js +203 -0
  514. data/app/javascript/modules/__tests__/dom_listener_registry.test.js +67 -0
  515. data/app/javascript/modules/__tests__/failed_creative_save.test.js +65 -0
  516. data/app/javascript/modules/__tests__/html_content_empty.test.js +11 -0
  517. data/app/javascript/modules/__tests__/integration_wizard.test.js +139 -0
  518. data/app/javascript/modules/__tests__/mention_menu.test.js +190 -0
  519. data/app/javascript/modules/__tests__/notice_bar_motion.test.js +132 -0
  520. data/app/javascript/modules/__tests__/notice_bar_sheet.test.js +108 -0
  521. data/app/javascript/modules/__tests__/notice_bar_spotlight.test.js +109 -0
  522. data/app/javascript/modules/__tests__/notice_bar_storage.test.js +31 -0
  523. data/app/javascript/modules/__tests__/notice_bar_toasts.test.js +71 -0
  524. data/app/javascript/modules/__tests__/notice_bar_view.test.js +89 -0
  525. data/app/javascript/modules/__tests__/pdf_assets.test.js +26 -0
  526. data/app/javascript/modules/__tests__/pdf_document.test.js +231 -0
  527. data/app/javascript/modules/__tests__/persisted_creative_tree.test.js +48 -0
  528. data/app/javascript/modules/__tests__/ppt_viewer.test.js +219 -0
  529. data/app/javascript/modules/__tests__/queued_creative_row.test.js +206 -0
  530. data/app/javascript/modules/__tests__/recovered_creative_position.test.js +57 -0
  531. data/app/javascript/modules/__tests__/slide_view_attachments.test.js +71 -0
  532. data/app/javascript/modules/__tests__/support/inline_editor_dom.js +183 -0
  533. data/app/javascript/modules/__tests__/viewer_navigation.test.js +42 -0
  534. data/app/javascript/modules/background_creative_create.js +326 -0
  535. data/app/javascript/modules/command_args_form.js +30 -40
  536. data/app/javascript/modules/command_menu.js +171 -55
  537. data/app/javascript/modules/creative_inline_dataset.js +34 -0
  538. data/app/javascript/modules/creative_inline_payload.js +10 -14
  539. data/app/javascript/modules/creative_link_picker.js +56 -0
  540. data/app/javascript/modules/creative_removal.js +39 -0
  541. data/app/javascript/modules/creative_row_editor.js +818 -634
  542. data/app/javascript/modules/creative_row_editor_delegated_clicks.js +87 -0
  543. data/app/javascript/modules/creative_save_state.js +141 -0
  544. data/app/javascript/modules/creative_tree_dom.js +4 -0
  545. data/app/javascript/modules/creative_tree_empty_state.js +80 -0
  546. data/app/javascript/modules/creative_type_editor.js +139 -0
  547. data/app/javascript/modules/dom_listener_registry.js +23 -0
  548. data/app/javascript/modules/failed_creative_save.js +42 -0
  549. data/app/javascript/modules/html_content_empty.js +5 -3
  550. data/app/javascript/modules/integration_wizard.js +68 -19
  551. data/app/javascript/modules/keep_goal_text.js +4 -0
  552. data/app/javascript/modules/lexical_inline_editor.jsx +9 -2
  553. data/app/javascript/modules/mention_menu.js +36 -25
  554. data/app/javascript/modules/notice_bar/__tests__/refresh.test.js +177 -0
  555. data/app/javascript/modules/notice_bar/motion.js +59 -0
  556. data/app/javascript/modules/notice_bar/refresh.js +53 -0
  557. data/app/javascript/modules/notice_bar/sheet.js +102 -0
  558. data/app/javascript/modules/notice_bar/spotlight.js +78 -0
  559. data/app/javascript/modules/notice_bar/storage.js +14 -0
  560. data/app/javascript/modules/notice_bar/toasts.js +49 -0
  561. data/app/javascript/modules/notice_bar/view.js +101 -0
  562. data/app/javascript/modules/pdf_document.js +65 -0
  563. data/app/javascript/modules/pending_creative_sync.js +23 -0
  564. data/app/javascript/modules/persisted_creative_tree.js +39 -0
  565. data/app/javascript/modules/ppt_viewer.js +76 -0
  566. data/app/javascript/modules/queued_creative_row.js +128 -0
  567. data/app/javascript/modules/recovered_creative_position.js +52 -0
  568. data/app/javascript/modules/slide_view.js +9 -3
  569. data/app/javascript/modules/viewer_navigation.js +16 -0
  570. data/app/javascript/slide_view.js +9 -0
  571. data/app/javascript/utils/__tests__/caret_anchor.test.js +75 -0
  572. data/app/javascript/utils/__tests__/chevron_icons.test.js +15 -0
  573. data/app/javascript/utils/caret_position.js +10 -0
  574. data/app/javascript/utils/chevron_icons.js +7 -0
  575. data/app/jobs/collavre/agent_provisioning_sync_job.rb +79 -0
  576. data/app/jobs/collavre/ai_agent_job.rb +346 -135
  577. data/app/jobs/collavre/approval_continuation_job.rb +102 -0
  578. data/app/jobs/collavre/approval_gate_resume_job.rb +22 -0
  579. data/app/jobs/collavre/async_approval_resume_job.rb +20 -0
  580. data/app/jobs/collavre/async_approval_sweep_job.rb +44 -0
  581. data/app/jobs/collavre/batch_destroy_comments_job.rb +17 -0
  582. data/app/jobs/collavre/cancel_offline_delegated_tasks_job.rb +34 -106
  583. data/app/jobs/collavre/cdn_invalidation_job.rb +62 -0
  584. data/app/jobs/collavre/claude_approval_resume_job.rb +15 -0
  585. data/app/jobs/collavre/comment_badges_broadcast_job.rb +28 -0
  586. data/app/jobs/collavre/comment_link_preview_job.rb +33 -0
  587. data/app/jobs/collavre/comment_notification_job.rb +14 -0
  588. data/app/jobs/collavre/comment_push_delivery_sweep_job.rb +25 -0
  589. data/app/jobs/collavre/compress_job.rb +36 -49
  590. data/app/jobs/collavre/creative_broadcast_job.rb +166 -56
  591. data/app/jobs/collavre/creative_history_notice_job.rb +40 -0
  592. data/app/jobs/collavre/creative_history_prune_job.rb +86 -0
  593. data/app/jobs/collavre/creative_tree_invalidation_job.rb +33 -0
  594. data/app/jobs/collavre/cron_action_job.rb +55 -20
  595. data/app/jobs/collavre/cron_scheduler_job.rb +44 -3
  596. data/app/jobs/collavre/drop_trigger_job.rb +54 -35
  597. data/app/jobs/collavre/endpoint_health_probe_job.rb +23 -0
  598. data/app/jobs/collavre/endpoint_health_sweep_job.rb +22 -0
  599. data/app/jobs/collavre/gateway_health_probe_job.rb +33 -0
  600. data/app/jobs/collavre/gateway_health_sweep_job.rb +22 -0
  601. data/app/jobs/collavre/inline_agent_replay_job.rb +32 -0
  602. data/app/jobs/collavre/keep_loop_reconcile_job.rb +57 -0
  603. data/app/jobs/collavre/merge_comments_job.rb +37 -44
  604. data/app/jobs/collavre/offline_task_sweep_job.rb +44 -0
  605. data/app/jobs/collavre/permission_cache_job.rb +19 -10
  606. data/app/jobs/collavre/purge_unreferenced_blob_job.rb +19 -0
  607. data/app/jobs/collavre/push_notification_job.rb +65 -20
  608. data/app/jobs/collavre/recover_interrupted_tasks_job.rb +79 -0
  609. data/app/jobs/collavre/restore_dropped_dispatches_job.rb +17 -0
  610. data/app/jobs/collavre/resume_suspended_tasks_job.rb +29 -0
  611. data/app/jobs/collavre/solid_queue_worker_watchdog_job.rb +108 -0
  612. data/app/jobs/collavre/stuck_detector_job.rb +1 -1
  613. data/app/jobs/collavre/touch_creative_subtree_job.rb +14 -0
  614. data/app/jobs/collavre/trigger_loop_check_job.rb +104 -105
  615. data/app/jobs/collavre/trigger_loop_verify_job.rb +51 -82
  616. data/app/jobs/collavre/workflow_outbox_job.rb +10 -0
  617. data/app/jobs/collavre/workflow_push_job.rb +11 -0
  618. data/app/jobs/collavre/workflow_sweep_job.rb +11 -0
  619. data/app/jobs/concerns/collavre/comment_serializable.rb +3 -1
  620. data/app/jobs/concerns/collavre/dispatch_admission.rb +95 -0
  621. data/app/jobs/concerns/collavre/trigger_loop_helpers.rb +178 -13
  622. data/app/models/collavre/agent_gateway.rb +276 -0
  623. data/app/models/collavre/agent_subscription.rb +4 -4
  624. data/app/models/collavre/agent_workspace.rb +245 -0
  625. data/app/models/collavre/blob_access_flag.rb +24 -0
  626. data/app/models/collavre/channel.rb +17 -0
  627. data/app/models/collavre/comment/approvable.rb +14 -1
  628. data/app/models/collavre/comment/approval_gate.rb +98 -0
  629. data/app/models/collavre/comment/batch_destruction.rb +173 -0
  630. data/app/models/collavre/comment/broadcastable.rb +40 -52
  631. data/app/models/collavre/comment/bulk_follow_up_jobs.rb +29 -0
  632. data/app/models/collavre/comment/claude_channel_permission.rb +59 -5
  633. data/app/models/collavre/comment/creative_quote.rb +55 -0
  634. data/app/models/collavre/comment/image_cdn_eviction.rb +36 -0
  635. data/app/models/collavre/comment/notifiable.rb +157 -79
  636. data/app/models/collavre/comment/suspension_notice.rb +20 -0
  637. data/app/models/collavre/comment/topic_membership.rb +61 -0
  638. data/app/models/collavre/comment/trigger_loop_resume.rb +77 -0
  639. data/app/models/collavre/comment.rb +350 -121
  640. data/app/models/collavre/comment_notification_delivery.rb +72 -0
  641. data/app/models/collavre/comment_presence_store/cache_batches.rb +64 -0
  642. data/app/models/collavre/comment_presence_store.rb +272 -12
  643. data/app/models/collavre/comment_read_pointer.rb +9 -15
  644. data/app/models/collavre/comment_version.rb +4 -0
  645. data/app/models/collavre/creative/ai_write_policy.rb +26 -0
  646. data/app/models/collavre/creative/contextual.rb +153 -0
  647. data/app/models/collavre/creative/describable.rb +42 -27
  648. data/app/models/collavre/creative/history_trackable.rb +104 -0
  649. data/app/models/collavre/creative/linkable.rb +21 -1
  650. data/app/models/collavre/creative/permissible.rb +23 -20
  651. data/app/models/collavre/creative/publishable.rb +65 -0
  652. data/app/models/collavre/creative/type_selectable.rb +25 -0
  653. data/app/models/collavre/creative.rb +55 -114
  654. data/app/models/collavre/creative_change.rb +55 -0
  655. data/app/models/collavre/creative_change_set.rb +71 -0
  656. data/app/models/collavre/creative_share.rb +128 -4
  657. data/app/models/collavre/current.rb +9 -1
  658. data/app/models/collavre/llm_model.rb +63 -0
  659. data/app/models/collavre/llm_usage/requester.rb +9 -0
  660. data/app/models/collavre/llm_usage.rb +33 -0
  661. data/app/models/collavre/mcp_tool.rb +25 -3
  662. data/app/models/collavre/orchestrator_policy.rb +25 -29
  663. data/app/models/collavre/preview_channel.rb +1 -15
  664. data/app/models/collavre/retired_task_execution.rb +9 -0
  665. data/app/models/collavre/system_setting.rb +72 -9
  666. data/app/models/collavre/task/approval_gate_cleanup.rb +23 -0
  667. data/app/models/collavre/task/async_approval.rb +30 -0
  668. data/app/models/collavre/task.rb +194 -29
  669. data/app/models/collavre/task_merged_instruction.rb +6 -0
  670. data/app/models/collavre/tool_usage/requester.rb +9 -0
  671. data/app/models/collavre/tool_usage.rb +69 -0
  672. data/app/models/collavre/topic.rb +89 -0
  673. data/app/models/collavre/user/ai_capabilities.rb +38 -0
  674. data/app/models/collavre/user.rb +114 -50
  675. data/app/models/collavre/user_creative_preference.rb +27 -1
  676. data/app/models/collavre/user_notice.rb +64 -0
  677. data/app/models/collavre/workflow/chain.rb +27 -0
  678. data/app/models/collavre/workflow/execution.rb +28 -0
  679. data/app/models/collavre/workflow/outbox.rb +43 -0
  680. data/app/models/collavre/workflow/receipt.rb +26 -0
  681. data/app/models/concerns/collavre/agent_liveness.rb +95 -0
  682. data/app/models/concerns/collavre/agent_run_options.rb +45 -0
  683. data/app/models/concerns/collavre/ai_agent_resolvable.rb +30 -7
  684. data/app/models/concerns/collavre/comment/dispatch_revocation.rb +99 -0
  685. data/app/models/concerns/collavre/comment/keep_loop.rb +166 -0
  686. data/app/models/concerns/collavre/creation_events.rb +25 -0
  687. data/app/models/concerns/collavre/creative/trigger_loop.rb +57 -0
  688. data/app/models/concerns/collavre/creative_history_topic.rb +34 -0
  689. data/app/models/concerns/collavre/creative_reserved_topics.rb +25 -0
  690. data/app/models/concerns/collavre/has_inbox_creative.rb +9 -1
  691. data/app/models/concerns/collavre/system_agent_identity.rb +13 -0
  692. data/app/models/concerns/collavre/task/replay_loop_completion.rb +78 -0
  693. data/app/models/concerns/collavre/task/trigger_loop_completion.rb +126 -0
  694. data/app/models/concerns/collavre/task/usage_attribution_tracking.rb +28 -0
  695. data/app/models/concerns/collavre/task/workflow_completion.rb +59 -0
  696. data/app/services/collavre/agent_health/endpoint_request.rb +64 -0
  697. data/app/services/collavre/agent_health/openai_endpoint_checker.rb +77 -0
  698. data/app/services/collavre/agent_health/probe.rb +47 -0
  699. data/app/services/collavre/agent_health.rb +43 -0
  700. data/app/services/collavre/agent_provisioning/archive.rb +108 -0
  701. data/app/services/collavre/agent_session_abort.rb +2 -2
  702. data/app/services/collavre/agent_tool_permission.rb +43 -0
  703. data/app/services/collavre/ai_agent/a2a_dispatcher.rb +38 -7
  704. data/app/services/collavre/ai_agent/agent_lifecycle_manager.rb +78 -6
  705. data/app/services/collavre/ai_agent/approval_conversation.rb +60 -0
  706. data/app/services/collavre/ai_agent/approval_gate_handler.rb +37 -0
  707. data/app/services/collavre/ai_agent/approval_handler.rb +20 -5
  708. data/app/services/collavre/ai_agent/budgeted_tree_renderer.rb +80 -0
  709. data/app/services/collavre/ai_agent/chat_history_window.rb +87 -0
  710. data/app/services/collavre/ai_agent/claude_channel_adapter.rb +67 -11
  711. data/app/services/collavre/ai_agent/creative_quote_context.rb +66 -0
  712. data/app/services/collavre/ai_agent/history_notice.rb +94 -0
  713. data/app/services/collavre/ai_agent/merged_trigger_comments.rb +164 -0
  714. data/app/services/collavre/ai_agent/message_builder.rb +217 -83
  715. data/app/services/collavre/ai_agent/prompt_budget.rb +142 -0
  716. data/app/services/collavre/ai_agent/referenced_creative_renderer.rb +101 -0
  717. data/app/services/collavre/ai_agent/reply_placeholder.rb +28 -0
  718. data/app/services/collavre/ai_agent/response_finalizer.rb +15 -1
  719. data/app/services/collavre/ai_agent/review_handler.rb +17 -17
  720. data/app/services/collavre/ai_agent/screening_approval_handler.rb +26 -0
  721. data/app/services/collavre/ai_agent/session_context_resolver.rb +6 -1
  722. data/app/services/collavre/ai_agent/session_provisioner.rb +3 -7
  723. data/app/services/collavre/ai_agent/task_claim_service.rb +84 -18
  724. data/app/services/collavre/ai_agent/task_reply_service.rb +90 -0
  725. data/app/services/collavre/ai_agent/task_workspace_user.rb +20 -0
  726. data/app/services/collavre/ai_agent/turn_screening.rb +132 -0
  727. data/app/services/collavre/ai_agent/workspace_authentication.rb +74 -0
  728. data/app/services/collavre/ai_agent_service.rb +113 -50
  729. data/app/services/collavre/ai_approval_summary.rb +51 -0
  730. data/app/services/collavre/ai_client/approval_gate.rb +90 -0
  731. data/app/services/collavre/ai_client/cli_tool_events.rb +100 -0
  732. data/app/services/collavre/ai_client/decision.rb +101 -0
  733. data/app/services/collavre/ai_client/error_handling.rb +67 -0
  734. data/app/services/collavre/ai_client/provider_context.rb +69 -0
  735. data/app/services/collavre/ai_client.rb +175 -136
  736. data/app/services/collavre/ai_usage_tracking.rb +93 -0
  737. data/app/services/collavre/auto_theme_generator.rb +5 -8
  738. data/app/services/collavre/blob_access.rb +166 -0
  739. data/app/services/collavre/cdn_invalidation.rb +67 -0
  740. data/app/services/collavre/claude_approval_handoff.rb +28 -0
  741. data/app/services/collavre/cli_proxy/adapter_engine.rb +27 -0
  742. data/app/services/collavre/cli_proxy/client.rb +190 -0
  743. data/app/services/collavre/cli_proxy/endpoint_policy.rb +81 -0
  744. data/app/services/collavre/cli_proxy/engine_unauthenticated_error.rb +31 -0
  745. data/app/services/collavre/cli_proxy/health_probe.rb +137 -0
  746. data/app/services/collavre/cli_proxy/identity.rb +47 -0
  747. data/app/services/collavre/cli_proxy/inline_login.rb +239 -0
  748. data/app/services/collavre/cli_proxy/inline_replay_admission.rb +57 -0
  749. data/app/services/collavre/cli_proxy/replay_claims.rb +48 -0
  750. data/app/services/collavre/cli_proxy/replay_routing.rb +43 -0
  751. data/app/services/collavre/cli_proxy/replay_workspace.rb +53 -0
  752. data/app/services/collavre/cli_proxy/run_options.rb +90 -0
  753. data/app/services/collavre/cli_proxy/safe_net_http_adapter.rb +19 -0
  754. data/app/services/collavre/command_menu_service.rb +18 -14
  755. data/app/services/collavre/comment_move_service.rb +100 -7
  756. data/app/services/collavre/comment_resend_service/cleanup.rb +20 -0
  757. data/app/services/collavre/comment_resend_service.rb +125 -0
  758. data/app/services/collavre/comment_snapshot_restore_service.rb +27 -15
  759. data/app/services/collavre/comments/action_executor.rb +45 -27
  760. data/app/services/collavre/comments/approval_gate_decision.rb +54 -0
  761. data/app/services/collavre/comments/approved_tool_invocation.rb +37 -0
  762. data/app/services/collavre/comments/async_approval_decision.rb +41 -0
  763. data/app/services/collavre/comments/command_processor.rb +14 -1
  764. data/app/services/collavre/comments/creative_quote_rejection_notice.rb +37 -0
  765. data/app/services/collavre/comments/creative_quote_review.rb +54 -0
  766. data/app/services/collavre/comments/keep_command.rb +80 -0
  767. data/app/services/collavre/comments/list_response.rb +161 -0
  768. data/app/services/collavre/comments/read_pointer_writer.rb +210 -0
  769. data/app/services/collavre/comments/read_receipt_broadcaster.rb +157 -0
  770. data/app/services/collavre/comments/read_receipt_index.rb +152 -0
  771. data/app/services/collavre/comments/topic_command.rb +68 -18
  772. data/app/services/collavre/comments/topic_mutation.rb +20 -0
  773. data/app/services/collavre/creatives/agent_turn_history.rb +15 -0
  774. data/app/services/collavre/creatives/ai_write_policy.rb +36 -0
  775. data/app/services/collavre/creatives/breadcrumb_resolver.rb +1 -1
  776. data/app/services/collavre/creatives/change_set_apply_service.rb +309 -0
  777. data/app/services/collavre/creatives/change_set_diff.rb +216 -0
  778. data/app/services/collavre/creatives/change_set_restore_service.rb +20 -0
  779. data/app/services/collavre/creatives/change_set_revert_service.rb +21 -0
  780. data/app/services/collavre/creatives/change_set_visibility.rb +108 -0
  781. data/app/services/collavre/creatives/children_index.rb +19 -8
  782. data/app/services/collavre/creatives/comment_badge_index.rb +299 -27
  783. data/app/services/collavre/creatives/create_service.rb +3 -1
  784. data/app/services/collavre/creatives/creation_revert_policy.rb +35 -0
  785. data/app/services/collavre/creatives/creative_quote_turn.rb +96 -0
  786. data/app/services/collavre/creatives/description_image_dimensions.rb +50 -0
  787. data/app/services/collavre/creatives/destroy_service.rb +18 -2
  788. data/app/services/collavre/creatives/draft_change_set_applicator.rb +121 -0
  789. data/app/services/collavre/creatives/draft_change_set_capture.rb +206 -0
  790. data/app/services/collavre/creatives/draft_change_set_reject_service.rb +45 -0
  791. data/app/services/collavre/creatives/draft_conflict_dependency_pruner.rb +110 -0
  792. data/app/services/collavre/creatives/draft_link_authorization.rb +61 -0
  793. data/app/services/collavre/creatives/draft_link_progress_reconciliation.rb +36 -0
  794. data/app/services/collavre/creatives/drop_trigger_missing_agent_notifier.rb +31 -0
  795. data/app/services/collavre/creatives/expansion_save_order.rb +70 -0
  796. data/app/services/collavre/creatives/file_drop_service.rb +49 -0
  797. data/app/services/collavre/creatives/filter_pipeline.rb +7 -4
  798. data/app/services/collavre/creatives/filter_state.rb +25 -0
  799. data/app/services/collavre/creatives/filters/base_filter.rb +3 -2
  800. data/app/services/collavre/creatives/filters/cron_filter.rb +19 -0
  801. data/app/services/collavre/creatives/filters/reaction_filter.rb +17 -0
  802. data/app/services/collavre/creatives/historical_snapshot_authorization.rb +108 -0
  803. data/app/services/collavre/creatives/history.rb +302 -0
  804. data/app/services/collavre/creatives/history_page.rb +61 -0
  805. data/app/services/collavre/creatives/importer.rb +19 -5
  806. data/app/services/collavre/creatives/index_query.rb +6 -12
  807. data/app/services/collavre/creatives/keep_agent_scope.rb +29 -0
  808. data/app/services/collavre/creatives/origin_chain_preloader.rb +23 -0
  809. data/app/services/collavre/creatives/permission_cache_builder.rb +72 -42
  810. data/app/services/collavre/creatives/permission_checker.rb +51 -4
  811. data/app/services/collavre/creatives/permission_filter.rb +14 -1
  812. data/app/services/collavre/creatives/progress_propagation_targets.rb +36 -0
  813. data/app/services/collavre/creatives/propagated_change_authorization.rb +142 -0
  814. data/app/services/collavre/creatives/reorderer.rb +140 -49
  815. data/app/services/collavre/creatives/snapshot_assignment.rb +25 -0
  816. data/app/services/collavre/creatives/snapshot_comparison.rb +14 -0
  817. data/app/services/collavre/creatives/tree_builder.rb +41 -14
  818. data/app/services/collavre/creatives/tree_formatter.rb +6 -7
  819. data/app/services/collavre/creatives/trigger_action_command.rb +222 -0
  820. data/app/services/collavre/creatives/type_transition.rb +58 -0
  821. data/app/services/collavre/creatives/workspace_expansion_candidates.rb +24 -0
  822. data/app/services/collavre/creatives/workspace_expansion_order.rb +58 -0
  823. data/app/services/collavre/creatives/workspace_expansion_presence.rb +38 -0
  824. data/app/services/collavre/creatives/workspace_path_resolver.rb +50 -0
  825. data/app/services/collavre/creatives/workspace_tree_builder.rb +100 -0
  826. data/app/services/collavre/crons/change_broadcaster.rb +35 -0
  827. data/app/services/collavre/crons/recurring_task_arguments.rb +10 -2
  828. data/app/services/collavre/crons/recurring_task_index.rb +78 -0
  829. data/app/services/collavre/crons/recurring_topic_tasks.rb +23 -0
  830. data/app/services/collavre/decision_questions.rb +125 -0
  831. data/app/services/collavre/home_page_path.rb +55 -0
  832. data/app/services/collavre/html_text.rb +64 -0
  833. data/app/services/collavre/http_client.rb +52 -7
  834. data/app/services/collavre/inbox_reply_service.rb +2 -1
  835. data/app/services/collavre/keep_loop.rb +84 -0
  836. data/app/services/collavre/kollavy/access_scope.rb +84 -0
  837. data/app/services/collavre/kollavy/identity.rb +25 -0
  838. data/app/services/collavre/kollavy.rb +153 -0
  839. data/app/services/collavre/llm_usage/attribution.rb +99 -0
  840. data/app/services/collavre/llm_usage/history_omission.rb +30 -0
  841. data/app/services/collavre/llm_usage/recorder.rb +59 -0
  842. data/app/services/collavre/llm_usage/report.rb +116 -0
  843. data/app/services/collavre/llm_usage/token_normalizer.rb +54 -0
  844. data/app/services/collavre/markdown_converter.rb +45 -29
  845. data/app/services/collavre/mcp_service.rb +61 -35
  846. data/app/services/collavre/mcp_tool_access.rb +40 -0
  847. data/app/services/collavre/mcp_tool_categories.rb +57 -0
  848. data/app/services/collavre/mcp_tool_registrar.rb +217 -0
  849. data/app/services/collavre/mcp_tool_registry.rb +38 -0
  850. data/app/services/collavre/mention_parser.rb +48 -14
  851. data/app/services/collavre/notices/feed.rb +127 -0
  852. data/app/services/collavre/notices/onboarding_replay.rb +17 -0
  853. data/app/services/collavre/notices/refresh_deadline.rb +15 -0
  854. data/app/services/collavre/notices/tracker.rb +68 -0
  855. data/app/services/collavre/openai_endpoint.rb +24 -0
  856. data/app/services/collavre/orchestration/agent_context_builder.rb +3 -1
  857. data/app/services/collavre/orchestration/agent_orchestrator.rb +488 -144
  858. data/app/services/collavre/orchestration/agent_recovery_trigger.rb +16 -0
  859. data/app/services/collavre/orchestration/arbiter.rb +57 -7
  860. data/app/services/collavre/orchestration/deferred_trigger_scope.rb +64 -0
  861. data/app/services/collavre/orchestration/delivery_record.rb +740 -0
  862. data/app/services/collavre/orchestration/dispatch_records.rb +52 -0
  863. data/app/services/collavre/orchestration/execution_fence.rb +97 -0
  864. data/app/services/collavre/orchestration/job_enqueue.rb +150 -0
  865. data/app/services/collavre/orchestration/keep_dispatch_admission.rb +76 -0
  866. data/app/services/collavre/orchestration/keep_dispatch_restoration.rb +57 -0
  867. data/app/services/collavre/orchestration/keep_loop_ownership.rb +152 -0
  868. data/app/services/collavre/orchestration/keep_queued_dispatches.rb +73 -0
  869. data/app/services/collavre/orchestration/loop_breaker.rb +20 -9
  870. data/app/services/collavre/orchestration/matcher.rb +232 -44
  871. data/app/services/collavre/orchestration/offline_task_grace.rb +50 -0
  872. data/app/services/collavre/orchestration/policy_resolver.rb +110 -11
  873. data/app/services/collavre/orchestration/resource_tracker.rb +4 -1
  874. data/app/services/collavre/orchestration/restored_dispatch_admission.rb +103 -0
  875. data/app/services/collavre/orchestration/restored_dispatch_context.rb +15 -0
  876. data/app/services/collavre/orchestration/resume_context.rb +90 -0
  877. data/app/services/collavre/orchestration/scheduler.rb +19 -6
  878. data/app/services/collavre/orchestration/scheduling_hooks.rb +10 -0
  879. data/app/services/collavre/orchestration/selection.rb +76 -0
  880. data/app/services/collavre/orchestration/solid_queue_retry_recovery.rb +54 -0
  881. data/app/services/collavre/orchestration/stuck_detector.rb +25 -112
  882. data/app/services/collavre/orchestration/task_coalescer.rb +385 -0
  883. data/app/services/collavre/orchestration/task_resumer.rb +408 -0
  884. data/app/services/collavre/orchestration/topic_slot.rb +73 -0
  885. data/app/services/collavre/orchestration/waiting_notice_manager.rb +289 -0
  886. data/app/services/collavre/orchestration/workflow_dispatch.rb +47 -0
  887. data/app/services/collavre/orchestration/workflow_routing.rb +96 -0
  888. data/app/services/collavre/ppt_archive.rb +123 -0
  889. data/app/services/collavre/ppt_backgrounds.rb +97 -0
  890. data/app/services/collavre/ppt_colors.rb +104 -0
  891. data/app/services/collavre/ppt_connectors.rb +33 -0
  892. data/app/services/collavre/ppt_diagrams.rb +50 -0
  893. data/app/services/collavre/ppt_formatting.rb +134 -0
  894. data/app/services/collavre/ppt_geometry.rb +92 -0
  895. data/app/services/collavre/ppt_importer.rb +45 -64
  896. data/app/services/collavre/ppt_inheritance.rb +122 -0
  897. data/app/services/collavre/ppt_inline_media.rb +19 -0
  898. data/app/services/collavre/ppt_media.rb +49 -0
  899. data/app/services/collavre/ppt_numbering.rb +63 -0
  900. data/app/services/collavre/ppt_paragraphs.rb +52 -0
  901. data/app/services/collavre/ppt_preview.rb +12 -0
  902. data/app/services/collavre/ppt_renderer.rb +259 -0
  903. data/app/services/collavre/ppt_shape_fills.rb +35 -0
  904. data/app/services/collavre/ppt_shape_styles.rb +81 -0
  905. data/app/services/collavre/ppt_tables.rb +35 -0
  906. data/app/services/collavre/public_asset_allowlist.rb +41 -0
  907. data/app/services/collavre/quota/agent_execution.rb +31 -0
  908. data/app/services/collavre/quota/exceeded_error.rb +48 -0
  909. data/app/services/collavre/quota/notice.rb +15 -0
  910. data/app/services/collavre/quota/pending_dispatch.rb +35 -0
  911. data/app/services/collavre/quota/probe.rb +44 -0
  912. data/app/services/collavre/quota/recovery.rb +97 -0
  913. data/app/services/collavre/quota/retry_time.rb +65 -0
  914. data/app/services/collavre/ruby_llm_interaction_logger.rb +17 -7
  915. data/app/services/collavre/screening/gate.rb +47 -0
  916. data/app/services/collavre/screening/input.rb +30 -0
  917. data/app/services/collavre/screening/scope.rb +34 -0
  918. data/app/services/collavre/screening/screener.rb +57 -0
  919. data/app/services/collavre/screening/screener_resolver.rb +23 -0
  920. data/app/services/collavre/screening/turn_guard.rb +196 -0
  921. data/app/services/collavre/screening/verdict.rb +30 -0
  922. data/app/services/collavre/screening.rb +65 -0
  923. data/app/services/collavre/source_browser.rb +186 -0
  924. data/app/services/collavre/system_events/context_builder.rb +105 -15
  925. data/app/services/collavre/system_events/dispatcher.rb +67 -12
  926. data/app/services/collavre/system_events/envelope.rb +73 -0
  927. data/app/services/collavre/system_events/vocabulary.rb +48 -0
  928. data/app/services/collavre/task_execution_time.rb +33 -0
  929. data/app/services/collavre/tool_approval_policy.rb +42 -0
  930. data/app/services/collavre/tool_description.rb +35 -0
  931. data/app/services/collavre/tool_usage/approved_invocation.rb +28 -0
  932. data/app/services/collavre/tool_usage/cli_proxy_recorder.rb +100 -0
  933. data/app/services/collavre/tool_usage/mcp_call.rb +52 -0
  934. data/app/services/collavre/tool_usage/recorder.rb +34 -0
  935. data/app/services/collavre/tool_usage/report.rb +38 -0
  936. data/app/services/collavre/tools/approval_request_service.rb +54 -0
  937. data/app/services/collavre/tools/async_approval_request.rb +58 -0
  938. data/app/services/collavre/tools/creative_attach_files_service.rb +10 -2
  939. data/app/services/collavre/tools/creative_batch_service.rb +90 -10
  940. data/app/services/collavre/tools/creative_create_service.rb +33 -4
  941. data/app/services/collavre/tools/creative_import_service.rb +26 -3
  942. data/app/services/collavre/tools/creative_link_service.rb +75 -0
  943. data/app/services/collavre/tools/creative_list_attachments_service.rb +2 -2
  944. data/app/services/collavre/tools/creative_remove_attachment_service.rb +30 -5
  945. data/app/services/collavre/tools/creative_reorder_service.rb +111 -0
  946. data/app/services/collavre/tools/creative_retrieval_service.rb +27 -21
  947. data/app/services/collavre/tools/creative_unlink_service.rb +60 -0
  948. data/app/services/collavre/tools/creative_update_service.rb +88 -81
  949. data/app/services/collavre/tools/cron_cancel_service.rb +3 -17
  950. data/app/services/collavre/tools/cron_create_service.rb +101 -32
  951. data/app/services/collavre/tools/cron_list_service.rb +2 -2
  952. data/app/services/collavre/tools/cron_update_service.rb +5 -19
  953. data/app/services/collavre/tools/id_list.rb +38 -0
  954. data/app/services/collavre/tools/keep_service.rb +42 -0
  955. data/app/services/collavre/tools/source_list_service.rb +25 -0
  956. data/app/services/collavre/tools/source_read_service.rb +26 -0
  957. data/app/services/collavre/tools/source_search_service.rb +25 -0
  958. data/app/services/collavre/tools/source_tool_support.rb +39 -0
  959. data/app/services/collavre/tools/task_descendants.rb +32 -0
  960. data/app/services/collavre/tools/task_lineage.rb +46 -0
  961. data/app/services/collavre/tools/task_status_service.rb +61 -0
  962. data/app/services/collavre/tools/task_tracking.rb +67 -0
  963. data/app/services/collavre/tools/topic_authorizer.rb +62 -8
  964. data/app/services/collavre/tools/topic_branch_service.rb +85 -0
  965. data/app/services/collavre/tools/topic_create_service.rb +117 -0
  966. data/app/services/collavre/tools/topic_list_service.rb +101 -0
  967. data/app/services/collavre/tools/topic_message_create_service.rb +210 -0
  968. data/app/services/collavre/tools/topic_messages_service.rb +346 -0
  969. data/app/services/collavre/tools/topic_move_service.rb +107 -0
  970. data/app/services/collavre/tools/topic_selection.rb +59 -0
  971. data/app/services/collavre/tools/topic_tasks_service.rb +42 -0
  972. data/app/services/collavre/tools/topic_update_service.rb +165 -0
  973. data/app/services/collavre/topic_branch_service.rb +40 -10
  974. data/app/services/collavre/topics/active_topic_snapshot.rb +30 -0
  975. data/app/services/collavre/topics/agent_resolver.rb +93 -0
  976. data/app/services/collavre/topics/char_budget.rb +70 -0
  977. data/app/services/collavre/topics/cron_badge_decorator.rb +32 -0
  978. data/app/services/collavre/topics/last_topic_preference_payload.rb +19 -0
  979. data/app/services/collavre/topics/message_page.rb +380 -0
  980. data/app/services/collavre/topics/message_page_markdown.rb +102 -0
  981. data/app/services/collavre/topics/message_scope.rb +61 -0
  982. data/app/services/collavre/topics/message_stats.rb +92 -0
  983. data/app/services/collavre/topics/move_blocker.rb +47 -0
  984. data/app/services/collavre/topics/next_name.rb +35 -0
  985. data/app/services/collavre/topics/orphaned_cron_notifier.rb +33 -14
  986. data/app/services/collavre/topics/pin_rejection.rb +39 -0
  987. data/app/services/collavre/topics/read_pointer_relocator.rb +71 -0
  988. data/app/services/collavre/topics/reserved_name.rb +24 -0
  989. data/app/services/collavre/topics/serializer.rb +99 -0
  990. data/app/services/collavre/topics/topic_destroy.rb +30 -0
  991. data/app/services/collavre/topics/topic_move.rb +99 -0
  992. data/app/services/collavre/topics/topic_move_effects.rb +35 -0
  993. data/app/services/collavre/topics/topic_mutation.rb +27 -0
  994. data/app/services/collavre/trigger_loop_config.rb +15 -0
  995. data/app/services/collavre/workflow/admission.rb +109 -0
  996. data/app/services/collavre/workflow/child_context.rb +35 -0
  997. data/app/services/collavre/workflow/conditions.rb +79 -0
  998. data/app/services/collavre/workflow/context_preloader.rb +48 -0
  999. data/app/services/collavre/workflow/continuation.rb +16 -0
  1000. data/app/services/collavre/workflow/dispatch_identity.rb +25 -0
  1001. data/app/services/collavre/workflow/dispatch_outcome.rb +9 -0
  1002. data/app/services/collavre/workflow/editor.rb +79 -0
  1003. data/app/services/collavre/workflow/envelope_validation.rb +18 -0
  1004. data/app/services/collavre/workflow/fallback_delivery.rb +59 -0
  1005. data/app/services/collavre/workflow/fixed_anchor.rb +32 -0
  1006. data/app/services/collavre/workflow/human_handoff.rb +39 -0
  1007. data/app/services/collavre/workflow/inbox_notice.rb +56 -0
  1008. data/app/services/collavre/workflow/invocation.rb +60 -0
  1009. data/app/services/collavre/workflow/materialization.rb +41 -0
  1010. data/app/services/collavre/workflow/publication.rb +55 -0
  1011. data/app/services/collavre/workflow/push_delivery.rb +97 -0
  1012. data/app/services/collavre/workflow/recovery.rb +62 -0
  1013. data/app/services/collavre/workflow/resolver.rb +83 -0
  1014. data/app/services/collavre/workflow/rule.rb +189 -0
  1015. data/app/services/collavre/workflow/safety.rb +61 -0
  1016. data/app/services/collavre/workflow/settlement.rb +60 -0
  1017. data/app/services/collavre/workflow/source_message.rb +39 -0
  1018. data/app/services/collavre/workflow/task_admission.rb +114 -0
  1019. data/app/views/collavre/admin/integrations/_setting_row.html.erb +5 -8
  1020. data/app/views/collavre/admin/settings/_system_tab.html.erb +56 -11
  1021. data/app/views/collavre/agent_connections/show.html.erb +84 -0
  1022. data/app/views/collavre/agent_gateways/_form.html.erb +85 -0
  1023. data/app/views/collavre/agent_gateways/edit.html.erb +4 -0
  1024. data/app/views/collavre/agent_gateways/index.html.erb +51 -0
  1025. data/app/views/collavre/agent_gateways/new.html.erb +4 -0
  1026. data/app/views/collavre/agent_models/_editor.html.erb +20 -0
  1027. data/app/views/collavre/comments/_activity_log_details.html.erb +10 -4
  1028. data/app/views/collavre/comments/_agent_run_options.html.erb +12 -0
  1029. data/app/views/collavre/comments/_approval_gate.html.erb +8 -0
  1030. data/app/views/collavre/comments/_comment.html.erb +45 -8
  1031. data/app/views/collavre/comments/_comments_popup.html.erb +105 -29
  1032. data/app/views/collavre/comments/_creative_quote_review.html.erb +29 -0
  1033. data/app/views/collavre/comments/_empty_state.html.erb +33 -0
  1034. data/app/views/collavre/comments/_empty_state_minimal.html.erb +7 -0
  1035. data/app/views/collavre/comments/_feature_card.html.erb +35 -0
  1036. data/app/views/collavre/comments/_list.html.erb +3 -2
  1037. data/app/views/collavre/comments/_loading.html.erb +7 -0
  1038. data/app/views/collavre/comments/_no_search_results.html.erb +3 -0
  1039. data/app/views/collavre/comments/_reaction_buttons.html.erb +7 -0
  1040. data/app/views/collavre/comments/_reaction_picker.html.erb +1 -8
  1041. data/app/views/collavre/comments/_run_options.html.erb +4 -0
  1042. data/app/views/collavre/comments/_thinking_icon.html.erb +7 -0
  1043. data/app/views/collavre/creative_change_sets/_detail.html.erb +88 -0
  1044. data/app/views/collavre/creative_change_sets/_list.html.erb +40 -0
  1045. data/app/views/collavre/creative_change_sets/_undo_toast.html.erb +22 -0
  1046. data/app/views/collavre/creatives/_add_button.html.erb +17 -19
  1047. data/app/views/collavre/creatives/_empty_state.html.erb +109 -0
  1048. data/app/views/collavre/creatives/_import_upload_zone.html.erb +1 -1
  1049. data/app/views/collavre/creatives/_inline_edit_form.html.erb +18 -6
  1050. data/app/views/collavre/creatives/_public_meta.html.erb +16 -0
  1051. data/app/views/collavre/creatives/_share_modal.html.erb +9 -0
  1052. data/app/views/collavre/creatives/_tree_loading_placeholder.html.erb +16 -0
  1053. data/app/views/collavre/creatives/_type_selector.html.erb +15 -0
  1054. data/app/views/collavre/creatives/_workflow_panel.html.erb +71 -0
  1055. data/app/views/collavre/creatives/_workspace_tree.html.erb +36 -0
  1056. data/app/views/collavre/creatives/edit.html.erb +7 -4
  1057. data/app/views/collavre/creatives/index.html.erb +149 -25
  1058. data/app/views/collavre/creatives/ppt_previews/_markdown_document.html.erb +17 -0
  1059. data/app/views/collavre/creatives/ppt_previews/show.html.erb +38 -0
  1060. data/app/views/collavre/creatives/show.html.erb +1 -1
  1061. data/app/views/collavre/desktop_setup/show.html.erb +114 -0
  1062. data/app/views/collavre/features/index.html.erb +42 -0
  1063. data/app/views/collavre/features/show.html.erb +52 -0
  1064. data/app/views/collavre/inline_agent_logins/show.html.erb +31 -0
  1065. data/app/views/collavre/invitation_mailer/invite.html.erb +1 -1
  1066. data/app/views/collavre/invitation_mailer/invite.text.erb +1 -1
  1067. data/app/views/collavre/invites/show.html.erb +14 -1
  1068. data/app/views/collavre/landing/show.html.erb +5 -1
  1069. data/app/views/collavre/llm_usages/_metrics.html.erb +13 -0
  1070. data/app/views/collavre/llm_usages/index.html.erb +88 -0
  1071. data/app/views/collavre/notices/_payload.html.erb +5 -0
  1072. data/app/views/collavre/notices/_zone.html.erb +20 -0
  1073. data/app/views/collavre/seo/sitemap.xml.builder +8 -0
  1074. data/app/views/collavre/seo/sitemap_index.xml.builder +8 -0
  1075. data/app/views/collavre/shared/_creative_move_modal.html.erb +59 -0
  1076. data/app/views/collavre/shared/_link_creative_modal.html.erb +6 -1
  1077. data/app/views/collavre/shared/navigation/_help_button.html.erb +22 -1
  1078. data/app/views/collavre/shared/navigation/_panels.html.erb +1 -8
  1079. data/app/views/collavre/shared/navigation/_search_form.html.erb +27 -3
  1080. data/app/views/collavre/user_themes/index.html.erb +1 -1
  1081. data/app/views/collavre/users/_llm_fields.html.erb +60 -0
  1082. data/app/views/collavre/users/_model_picker.html.erb +36 -0
  1083. data/app/views/collavre/users/_org_chart_node.html.erb +1 -1
  1084. data/app/views/collavre/users/_tool_details.html.erb +7 -0
  1085. data/app/views/collavre/users/_tool_selection.html.erb +51 -0
  1086. data/app/views/collavre/users/edit_ai.html.erb +60 -53
  1087. data/app/views/collavre/users/index.html.erb +96 -80
  1088. data/app/views/collavre/users/new.html.erb +4 -2
  1089. data/app/views/collavre/users/new_ai.html.erb +17 -53
  1090. data/app/views/collavre/users/show.html.erb +19 -24
  1091. data/app/views/layouts/collavre/landing.html.erb +23 -4
  1092. data/app/views/layouts/collavre/slide.html.erb +4 -1
  1093. data/config/initializers/active_storage_access.rb +34 -0
  1094. data/config/initializers/agent_health.rb +7 -0
  1095. data/config/initializers/kollavy_feature_card.rb +11 -0
  1096. data/config/initializers/mcp_discovery_access.rb +17 -0
  1097. data/config/initializers/mcp_tool_usage.rb +17 -0
  1098. data/config/initializers/meta_tool_access.rb +35 -0
  1099. data/config/initializers/rate_limits.rb +4 -0
  1100. data/config/initializers/ruby_llm_openai_cli_events.rb +43 -0
  1101. data/config/initializers/ruby_llm_openai_reasoning_content.rb +78 -0
  1102. data/config/initializers/screening_integration_settings.rb +5 -0
  1103. data/config/initializers/task_recovery.rb +30 -0
  1104. data/config/locales/admin.en.yml +21 -3
  1105. data/config/locales/admin.ko.yml +21 -3
  1106. data/config/locales/agent_gateway.en.yml +221 -0
  1107. data/config/locales/agent_gateway.ko.yml +221 -0
  1108. data/config/locales/ai_agent.en.yml +11 -1
  1109. data/config/locales/ai_agent.ko.yml +11 -1
  1110. data/config/locales/approval_gate.en.yml +11 -0
  1111. data/config/locales/approval_gate.ko.yml +11 -0
  1112. data/config/locales/claude_channel.en.yml +1 -0
  1113. data/config/locales/claude_channel.ko.yml +1 -0
  1114. data/config/locales/comments.en.yml +146 -48
  1115. data/config/locales/comments.ko.yml +146 -48
  1116. data/config/locales/contacts.en.yml +0 -5
  1117. data/config/locales/contacts.ko.yml +0 -5
  1118. data/config/locales/contexts.en.yml +6 -0
  1119. data/config/locales/contexts.ko.yml +6 -0
  1120. data/config/locales/creative_history.en.yml +62 -0
  1121. data/config/locales/creative_history.ko.yml +56 -0
  1122. data/config/locales/creative_types.en.yml +19 -0
  1123. data/config/locales/creative_types.ko.yml +19 -0
  1124. data/config/locales/creatives.en.yml +51 -52
  1125. data/config/locales/creatives.ko.yml +49 -45
  1126. data/config/locales/crons.en.yml +16 -0
  1127. data/config/locales/crons.ko.yml +16 -0
  1128. data/config/locales/dnd.en.yml +26 -0
  1129. data/config/locales/dnd.ko.yml +26 -0
  1130. data/config/locales/drop_trigger.en.yml +5 -16
  1131. data/config/locales/drop_trigger.ko.yml +5 -16
  1132. data/config/locales/features.en.yml +155 -0
  1133. data/config/locales/features.ko.yml +155 -0
  1134. data/config/locales/file_drop.en.yml +5 -0
  1135. data/config/locales/file_drop.ko.yml +5 -0
  1136. data/config/locales/inline_agent_login.en.yml +20 -0
  1137. data/config/locales/inline_agent_login.ko.yml +16 -0
  1138. data/config/locales/integrations.en.yml +0 -1
  1139. data/config/locales/integrations.ko.yml +0 -1
  1140. data/config/locales/invites.en.yml +3 -0
  1141. data/config/locales/invites.ko.yml +3 -0
  1142. data/config/locales/keep.en.yml +18 -0
  1143. data/config/locales/keep.ko.yml +18 -0
  1144. data/config/locales/kollavy.en.yml +4 -0
  1145. data/config/locales/kollavy.ko.yml +4 -0
  1146. data/config/locales/landing.en.yml +4 -7
  1147. data/config/locales/landing.ko.yml +4 -7
  1148. data/config/locales/llm_usages.en.yml +45 -0
  1149. data/config/locales/llm_usages.ko.yml +45 -0
  1150. data/config/locales/mcp_tools.en.yml +6 -0
  1151. data/config/locales/mcp_tools.ko.yml +6 -0
  1152. data/config/locales/notices.en.yml +52 -0
  1153. data/config/locales/notices.ko.yml +52 -0
  1154. data/config/locales/orchestration.en.yml +34 -2
  1155. data/config/locales/orchestration.ko.yml +34 -2
  1156. data/config/locales/ppt_viewer.en.yml +18 -0
  1157. data/config/locales/ppt_viewer.ko.yml +18 -0
  1158. data/config/locales/public_creatives.en.yml +6 -0
  1159. data/config/locales/public_creatives.ko.yml +6 -0
  1160. data/config/locales/quota.en.yml +5 -0
  1161. data/config/locales/quota.ko.yml +5 -0
  1162. data/config/locales/screening.en.yml +22 -0
  1163. data/config/locales/screening.ko.yml +22 -0
  1164. data/config/locales/search_popup.en.yml +2 -3
  1165. data/config/locales/search_popup.ko.yml +2 -3
  1166. data/config/locales/task_tracking.en.yml +13 -0
  1167. data/config/locales/task_tracking.ko.yml +13 -0
  1168. data/config/locales/tool_categories.en.yml +14 -0
  1169. data/config/locales/tool_categories.ko.yml +14 -0
  1170. data/config/locales/tool_descriptions.en.yml +163 -0
  1171. data/config/locales/tool_descriptions.ko.yml +163 -0
  1172. data/config/locales/tools.en.yml +46 -0
  1173. data/config/locales/tools.ko.yml +46 -0
  1174. data/config/locales/users.en.yml +33 -36
  1175. data/config/locales/users.ko.yml +32 -35
  1176. data/config/locales/workflow_editor.en.yml +62 -0
  1177. data/config/locales/workflow_editor.ko.yml +62 -0
  1178. data/config/locales/workflow_runtime.en.yml +19 -0
  1179. data/config/locales/workflow_runtime.ko.yml +19 -0
  1180. data/config/routes/account_settings.rb +4 -0
  1181. data/config/routes/agent_api.rb +6 -0
  1182. data/config/routes/agent_connections.rb +24 -0
  1183. data/config/routes/attachments.rb +2 -0
  1184. data/config/routes/comment_actions.rb +10 -0
  1185. data/config/routes/creative_attachments.rb +2 -0
  1186. data/config/routes/creative_contexts.rb +8 -0
  1187. data/config/routes/creative_history.rb +4 -0
  1188. data/config/routes/creative_preferences.rb +3 -0
  1189. data/config/routes/notices.rb +16 -0
  1190. data/config/routes/public_creatives.rb +12 -0
  1191. data/config/routes.rb +35 -38
  1192. data/db/migrate/20250911084338_backfill_creative_in_comment_inbox_items.rb +9 -1
  1193. data/db/migrate/20251204161133_set_default_routing_expression_for_ai_agents.rb +10 -3
  1194. data/db/migrate/20260724000000_add_creative_id_index_to_comments.rb +34 -0
  1195. data/db/migrate/20260724000001_add_creative_private_id_index_to_comments.rb +50 -0
  1196. data/db/migrate/20260724090000_add_async_comment_notification_state.rb +64 -0
  1197. data/db/migrate/20260727000000_add_waiting_notice_scope_to_comments.rb +30 -0
  1198. data/db/migrate/20260727010000_add_waiting_notice_scope_to_tasks.rb +26 -0
  1199. data/db/migrate/20260805000000_add_creative_workspace_enabled_to_users.rb +5 -0
  1200. data/db/migrate/20260807050000_add_dismissed_notices_to_users.rb +5 -0
  1201. data/db/migrate/20260809000000_change_creative_workspace_enabled_default_to_true.rb +18 -0
  1202. data/db/migrate/20260809000001_create_llm_models.rb +64 -0
  1203. data/db/migrate/20260809000002_create_agent_gateways_and_workspaces.rb +35 -0
  1204. data/db/migrate/20260809000003_hash_agent_workspace_callback_tokens.rb +44 -0
  1205. data/db/migrate/20260809000004_encrypt_agent_workspace_manifest_tokens.rb +59 -0
  1206. data/db/migrate/20260810000000_split_agent_workspace_identity_axes.rb +58 -0
  1207. data/db/migrate/20260810000001_seed_codex_custom_proxy_llm_models.rb +28 -0
  1208. data/db/migrate/20260810010000_add_last_visited_creative_to_users.rb +8 -0
  1209. data/db/migrate/20260810020000_add_last_visited_creative_at_to_users.rb +5 -0
  1210. data/db/migrate/20260810030000_add_last_visited_creative_navigation_order_to_users.rb +6 -0
  1211. data/db/migrate/20260810060000_add_last_visited_creative_issued_sequence_to_users.rb +5 -0
  1212. data/db/migrate/20260810100000_add_desktop_managed_to_agent_gateways.rb +40 -0
  1213. data/db/migrate/20260810100001_add_desktop_preset_adapter_to_users.rb +38 -0
  1214. data/db/migrate/20260811000000_make_agent_gateway_completion_key_nullable.rb +7 -0
  1215. data/db/migrate/20260812000000_remove_workflow_columns_from_tasks.rb +101 -0
  1216. data/db/migrate/20260812000001_remove_android_devices.rb +24 -0
  1217. data/db/migrate/20260812010000_drop_inbox_items.rb +22 -0
  1218. data/db/migrate/20260813000000_clear_claude_channel_presence_routing_expressions.rb +16 -0
  1219. data/db/migrate/20260813000001_add_last_topic_revision_to_user_creative_preferences.rb +5 -0
  1220. data/db/migrate/20260813000002_add_last_topic_save_order_to_user_creative_preferences.rb +6 -0
  1221. data/db/migrate/20260813000003_add_last_topic_save_sequences_to_user_creative_preferences.rb +5 -0
  1222. data/db/migrate/20260813000004_add_last_topic_save_fences_to_user_creative_preferences.rb +6 -0
  1223. data/db/migrate/20260814000000_add_topic_to_comment_read_pointers.rb +79 -0
  1224. data/db/migrate/20260814000001_add_creative_topic_private_id_index_to_comments.rb +37 -0
  1225. data/db/migrate/20260816000000_add_watermark_index_to_comment_read_pointers.rb +27 -0
  1226. data/db/migrate/20260816000001_add_private_recipient_topic_index_to_comments.rb +48 -0
  1227. data/db/migrate/20260820000000_add_topic_assigned_at_to_comments.rb +13 -0
  1228. data/db/migrate/20260903070800_add_joined_at_order_index_to_users.rb +23 -0
  1229. data/db/migrate/20260903180000_create_creative_change_history.rb +47 -0
  1230. data/db/migrate/20260903190000_add_system_kind_to_topics.rb +8 -0
  1231. data/db/migrate/20260908000000_add_last_topic_all_messages_to_user_creative_preferences.rb +5 -0
  1232. data/db/migrate/20260910000000_add_health_to_agent_gateways.rb +10 -0
  1233. data/db/migrate/20260911000000_add_endpoint_health_to_users.rb +9 -0
  1234. data/db/migrate/20260911020000_normalize_user_names_to_single_line.rb +32 -0
  1235. data/db/migrate/20260913000000_create_workflow_executions.rb +64 -0
  1236. data/db/migrate/20260913000002_add_ordinary_delivery_to_workflow_outboxes.rb +7 -0
  1237. data/db/migrate/20260913000100_add_reserved_to_workflow_executions.rb +7 -0
  1238. data/db/migrate/20260914063000_add_justify_creative_descriptions_to_users.rb +5 -0
  1239. data/db/migrate/20260922000000_create_llm_usages.rb +44 -0
  1240. data/db/migrate/20260922000001_add_expansion_save_sequences_to_users.rb +5 -0
  1241. data/db/migrate/20260922000002_deduplicate_root_creative_preferences.rb +37 -0
  1242. data/db/migrate/20260922000003_add_agent_quota_recovery.rb +7 -0
  1243. data/db/migrate/20260922000004_add_agent_quota_probe.rb +6 -0
  1244. data/db/migrate/20260922000005_add_suspension_to_tasks.rb +12 -0
  1245. data/db/migrate/20260922010000_create_retired_task_executions.rb +11 -0
  1246. data/db/migrate/20260922113000_add_emoji_comment_index_to_comment_reactions.rb +17 -0
  1247. data/db/migrate/20260922120000_create_tool_usages.rb +37 -0
  1248. data/db/migrate/20260923000000_link_tool_usages_to_agent_workspaces.rb +44 -0
  1249. data/db/migrate/20260924000000_add_agent_run_options.rb +7 -0
  1250. data/db/migrate/20260924010000_add_run_options_to_comment_versions.rb +5 -0
  1251. data/db/migrate/20260924060000_add_async_approval_recovery_to_comments.rb +24 -0
  1252. data/db/migrate/20260924070000_add_async_approval_task_to_comments.rb +22 -0
  1253. data/db/migrate/20260929000000_create_user_notices.rb +14 -0
  1254. data/db/migrate/20260929010000_add_system_agent_to_users.rb +5 -0
  1255. data/db/migrate/20260929120000_add_actor_lookup_index_to_creative_change_sets.rb +19 -0
  1256. data/db/migrate/20261008000000_add_public_id_to_creatives.rb +6 -0
  1257. data/db/migrate/20261008010000_backfill_public_creative_ids.rb +26 -0
  1258. data/db/migrate/20261012000000_create_blob_access_flags.rb +17 -0
  1259. data/db/migrate/20261012000001_publish_landing_public_assets.rb +16 -0
  1260. data/db/migrate/20261014000000_backfill_implicit_main_cron_topics.rb +38 -0
  1261. data/db/migrate/20261016000000_add_trigger_comment_id_to_tasks.rb +21 -0
  1262. data/db/migrate/20261016000001_index_task_event_causation.rb +20 -0
  1263. data/db/migrate/20261016000002_index_task_merged_instructions.rb +25 -0
  1264. data/db/migrate/20261019000000_add_quoted_creative_to_comments.rb +10 -0
  1265. data/db/migrate/20261028000000_add_deleting_at_to_comments.rb +5 -0
  1266. data/db/seeds.rb +4 -70
  1267. data/lib/collavre/bulk_job_enqueue.rb +145 -0
  1268. data/lib/collavre/engine.rb +119 -7
  1269. data/lib/collavre/feature_card_registry.rb +174 -0
  1270. data/lib/collavre/hashed_access_token_lookup.rb +22 -0
  1271. data/lib/collavre/notice_registry.rb +179 -0
  1272. data/lib/collavre/onboarding_notices.rb +107 -0
  1273. data/lib/collavre/profile_preferences.rb +17 -0
  1274. data/lib/collavre/sensitive_request_silencer.rb +23 -0
  1275. data/lib/collavre/stylesheets_helper.rb +72 -0
  1276. data/lib/collavre/user_extensions.rb +0 -2
  1277. data/lib/collavre/version.rb +1 -1
  1278. data/lib/collavre.rb +13 -0
  1279. data/lib/generators/collavre/install/install_generator.rb +50 -8
  1280. data/lib/generators/collavre/install/templates/build.cjs.tt +1 -0
  1281. data/lib/tasks/public_assets.rake +24 -0
  1282. data/skills/collavre/SKILL.md +207 -0
  1283. data/skills/collavre/package.json +8 -0
  1284. data/skills/collavre/references/tool-authoring.md +121 -0
  1285. data/skills/collavre/references/tool-reference.md +445 -0
  1286. data/skills/collavre/scripts/collavre +653 -0
  1287. data/skills/collavre/scripts/html_entities.js +24 -0
  1288. metadata +995 -36
  1289. data/app/controllers/collavre/api/v1/mobile/agent_events_controller.rb +0 -224
  1290. data/app/controllers/collavre/api/v1/mobile/base_controller.rb +0 -95
  1291. data/app/controllers/collavre/api/v1/mobile/devices_controller.rb +0 -31
  1292. data/app/controllers/collavre/api/v1/mobile/voice_commands_controller.rb +0 -25
  1293. data/app/controllers/collavre/inbox_items_controller.rb +0 -70
  1294. data/app/controllers/collavre/typo_corrections_controller.rb +0 -39
  1295. data/app/javascript/lib/__tests__/typo_correction.test.js +0 -192
  1296. data/app/javascript/lib/typo_correction.js +0 -146
  1297. data/app/javascript/modules/__tests__/typo_corrector.test.js +0 -365
  1298. data/app/javascript/modules/creative_guide.js +0 -67
  1299. data/app/javascript/modules/typo_corrector.js +0 -534
  1300. data/app/jobs/collavre/inbox_summary_job.rb +0 -24
  1301. data/app/mailers/collavre/inbox_mailer.rb +0 -19
  1302. data/app/models/collavre/inbox_item.rb +0 -89
  1303. data/app/services/collavre/comments/concerns/workflow_support.rb +0 -115
  1304. data/app/services/collavre/comments/work_command.rb +0 -161
  1305. data/app/services/collavre/comments/workflow_executor.rb +0 -276
  1306. data/app/services/collavre/gemini_parent_recommender.rb +0 -77
  1307. data/app/services/collavre/mobile/event_summarizer.rb +0 -40
  1308. data/app/services/collavre/typo_corrector.rb +0 -188
  1309. data/app/views/collavre/inbox_items/_item.html.erb +0 -18
  1310. data/app/views/collavre/inbox_items/_items.html.erb +0 -3
  1311. data/app/views/collavre/inbox_items/_list.html.erb +0 -7
  1312. data/app/views/collavre/inbox_items/index.html.erb +0 -1
  1313. data/app/views/collavre/inbox_mailer/daily_summary.html.erb +0 -11
  1314. data/app/views/collavre/inbox_mailer/daily_summary.text.erb +0 -8
  1315. data/app/views/collavre/users/typo_correction.html.erb +0 -50
  1316. data/config/locales/mobile.en.yml +0 -16
  1317. data/config/locales/mobile.ko.yml +0 -16
  1318. data/config/locales/notifications.en.yml +0 -8
  1319. data/config/locales/notifications.ko.yml +0 -8
  1320. /data/app/javascript/{utils/drag_bundle_image.js → lib/dnd/bundle_image.js} +0 -0
@@ -1,39 +1,135 @@
1
+ import { reloadDeletedReservedTopic, archivedTopicControls } from './topics/reserved_topic_deletion'
2
+ import { createDragDropRegistry } from '../../lib/dnd/registry'
3
+ import { getDragKind, readDragData, writeDragData } from '../../lib/dnd/envelope'
4
+ import { previewDrop, horizontalHit } from '../../lib/dnd/preview'
1
5
  import { Controller } from "@hotwired/stimulus"
2
6
  import { createSubscription } from "../../services/cable"
3
7
  import { fetchNextTopicName, createTopicWithComments, saveLastTopic } from "../../lib/api/topics"
4
8
  import { alertDialog, confirmDialog } from "../../lib/utils/dialog"
9
+ import { invalidateCreativeTree } from '../../lib/creative_tree_invalidation'
10
+ import PopupToggleGuard from '../../lib/popup_toggle_guard'
11
+ import TopicSelectionRestoreState from './topics/selection_restore_state'
12
+ import LastTopicSave from './topics/last_topic_save'
13
+ import LastTopicSaveOrderState, { LAST_TOPIC_SAVE_WINDOW_NAME_PREFIX } from './topics/save_order_state'
14
+ import LastTopicSelfEchoState from './topics/self_echo_state'
5
15
 
6
16
  const ICON_ARCHIVE = `<svg width="12" height="12" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2" stroke-linecap="round" stroke-linejoin="round"><rect x="2" y="3" width="20" height="5" rx="1"/><path d="M4 8v11a2 2 0 0 0 2 2h12a2 2 0 0 0 2-2V8"/><path d="M10 12h4"/></svg>`
7
17
  const ICON_RESTORE = `<svg width="12" height="12" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2" stroke-linecap="round" stroke-linejoin="round"><path d="M3 7v6h6"/><path d="M21 17a9 9 0 0 0-9-9 9 9 0 0 0-6.69 3L3 13"/></svg>`
18
+ const AMBIGUOUS_SAVE_CLAIM_TIMEOUT = 5_000
19
+ const SAVE_REQUEST_TIMEOUT = 5_000
20
+ const UNREAD_COUNT_REFRESH_DELAY = 250
21
+ const TOPIC_SCROLL_DURATION = 250
8
22
 
9
23
  export default class extends Controller {
10
- static targets = ["list", "creationContainer"]
24
+ static targets = ["list", "creationContainer", "topicListButton"]
25
+
26
+ get selectionState() {
27
+ return this._selectionState || (this._selectionState = new TopicSelectionRestoreState())
28
+ }
29
+
30
+ get saveOrderState() {
31
+ return this._saveOrderState || (this._saveOrderState = new LastTopicSaveOrderState())
32
+ }
33
+
34
+ get lastTopicSave() {
35
+ return this._lastTopicSave || (this._lastTopicSave = new LastTopicSave(this))
36
+ }
37
+
38
+ get selfEchoState() {
39
+ return this._selfEchoState || (this._selfEchoState = new LastTopicSelfEchoState())
40
+ }
41
+
42
+ // Keep the controller's existing internal surface while the state itself is
43
+ // owned by focused collaborators. Existing lifecycle paths intentionally
44
+ // inspect these values while a request is in flight.
45
+ get _explicitAllMessagesSelection() {
46
+ return this.selectionState.explicitAllMessagesSelection
47
+ }
48
+
49
+ set _explicitAllMessagesSelection(value) {
50
+ this.selectionState.explicitAllMessagesSelection = value
51
+ }
52
+
53
+ get _pendingPick() {
54
+ return this.selectionState.pendingPick
55
+ }
56
+
57
+ set _pendingPick(value) {
58
+ this.selectionState.pendingPick = value
59
+ }
60
+
61
+ get _pickCreativeId() {
62
+ return this.selectionState.pickCreativeId
63
+ }
64
+
65
+ set _pickCreativeId(value) {
66
+ this.selectionState.pickCreativeId = value
67
+ }
68
+
69
+ get _pickTopicId() {
70
+ return this.selectionState.pickTopicId
71
+ }
72
+
73
+ set _pickTopicId(value) {
74
+ this.selectionState.pickTopicId = value
75
+ }
76
+
77
+ get _saveLastTopicTimer() {
78
+ return this.saveOrderState.timer
79
+ }
80
+
81
+ set _saveLastTopicTimer(value) {
82
+ this.saveOrderState.timer = value
83
+ }
11
84
 
12
85
  connect() {
86
+ this._registerDragDrop()
13
87
  this.topics = []
14
88
  this.canManageTopics = false
15
89
  this.canCreateTopic = false
90
+ this.canSetPrimaryAgent = false
16
91
  this.subscribedCreativeId = null
17
92
  this.topicsSubscription = null
18
- this._loadTopicsVersion = 0
93
+ this._loadTopicsVersion ||= 0
94
+ this._unreadCountsOverlay = null
95
+ this._topicScrollFrame = null
96
+ this._topicScrollInterrupted = false
97
+ this._topicScrollInterruptionVersion ||= 0
98
+ this._explicitAllMessagesSelection ??= false
19
99
  // Initial load if creativeId is available (e.g. from dataset if set server-side)
20
- if (this.creativeId) {
100
+ if (this.creativeId && this.element.dataset.docked !== 'true') {
21
101
  this.loadTopics()
22
102
  this.subscribe()
23
103
  }
24
104
  this.handleNewMessage = this.handleNewMessage.bind(this)
25
105
  this.handleTopicMoved = this.handleTopicMoved.bind(this)
106
+ this.handleTopicListClose = this.handleTopicListClose.bind(this)
107
+ this.handleTopicScrollInput = this.handleTopicScrollInput.bind(this)
26
108
  window.addEventListener('comments--topics:new-message', this.handleNewMessage)
27
109
  window.addEventListener('collavre:topic-moved', this.handleTopicMoved)
110
+ this.element.addEventListener('topic-list:close', this.handleTopicListClose)
111
+ this.listTarget.addEventListener('wheel', this.handleTopicScrollInput, { passive: true })
112
+ this.listTarget.addEventListener('touchstart', this.handleTopicScrollInput, { passive: true })
28
113
  }
29
114
 
30
115
  disconnect() {
116
+ this.dnd?.destroy()
117
+ this.cancelProgrammaticScroll()
31
118
  window.removeEventListener('comments--topics:new-message', this.handleNewMessage)
32
119
  window.removeEventListener('collavre:topic-moved', this.handleTopicMoved)
120
+ this.element.removeEventListener('topic-list:close', this.handleTopicListClose)
121
+ this.listTarget.removeEventListener('wheel', this.handleTopicScrollInput)
122
+ this.listTarget.removeEventListener('touchstart', this.handleTopicScrollInput)
123
+ this._loadTopicsVersion += 1
124
+ this.cancelUnreadCountRefresh()
33
125
  this.unsubscribe()
34
126
  }
35
127
 
36
128
  onPopupOpened({ creativeId }) {
129
+ this.cancelProgrammaticScroll()
130
+ this._topicScrollInterrupted = false
131
+ this._popupClosed = false
132
+ const previousCreativeId = this.creativeIdValue
37
133
  this.creativeIdValue = creativeId
38
134
  // Clear stale cached state from the previous creative — otherwise
39
135
  // chat-context autofill (command_menu) reads stale values during the
@@ -44,13 +140,107 @@ export default class extends Controller {
44
140
  // effective_creative_id. loadTopics() repopulates both.
45
141
  delete this.element.dataset.effectiveCreativeId
46
142
  this.mainTopicId = null
47
- this.subscribe()
143
+ // Switching creatives reuses this instance without an onPopupClosed
144
+ // (popup_controller._navigateToEntry calls open()/openForCreative()
145
+ // again), so unread marks from the previous creative would badge the new
146
+ // creative's archived toggle — and never clear, since those ids are not
147
+ // among its topics. Only on an actual switch, though: a docked chat
148
+ // re-opens the *same* creative when a workspace-sync event carries a
149
+ // highlightId (popup_controller.handleCreativeClick), and these marks are
150
+ // transient — loadTopics() cannot rebuild them.
151
+ if (String(previousCreativeId || '') !== String(creativeId || '')) {
152
+ this.archivedWithNewMessages.clear()
153
+ this._explicitAllMessagesSelection = false
154
+ // Scoped to the creative it was archived in; a topic id from another
155
+ // creative must not veto this one's restored selection.
156
+ this.archivedAwayTopicId = null
157
+ }
158
+ // Do not prune retained claims until loadTopics() has resolved this
159
+ // requested creative to its effective stream id. A linked shell and
160
+ // its origin use the same TopicsChannel stream, but only the response
161
+ // tells us that after this cached value has been cleared.
162
+ // Direct history navigation replaces the subscription without firing
163
+ // onPopupClosed(). Keep claims until loadTopics() can resolve whether
164
+ // this requested creative shares the previous effective stream.
165
+ this.subscribe({ preservePendingSelfEchoes: true })
48
166
  return this.loadTopics()
49
167
  }
50
168
 
51
169
  onPopupClosed() {
52
- this.unsubscribe()
170
+ this.cancelProgrammaticScroll()
171
+ this._popupClosed = true
172
+ this.releaseAcknowledgedPendingSelfEchoes()
173
+ this.markPendingSelfEchoesAsPossiblyMissed()
174
+ this._loadTopicsVersion += 1
175
+ this.cancelUnreadCountRefresh()
176
+ // The same creative can reopen before an in-flight save broadcasts.
177
+ // Keep that save's claim so its delayed echo remains recognisable on
178
+ // the replacement subscription; a different creative clears it when
179
+ // it opens.
180
+ this.unsubscribe({ preservePendingSelfEchoes: true })
53
181
  this.creativeIdValue = null
182
+ this.topics = []
183
+ this.mainTopicId = null
184
+ this._explicitAllMessagesSelection = false
185
+ this.archivedWithNewMessages.clear()
186
+ this.archivedAwayTopicId = null
187
+ delete this.element.dataset.effectiveCreativeId
188
+ }
189
+
190
+ // Archived topics still accept messages, but their chips only exist in the
191
+ // DOM while the archived section is expanded. Remember which ones have
192
+ // unread traffic so the badge can live on the collapsed toggle and survive
193
+ // re-renders. Created lazily: a docked controller can receive popup
194
+ // lifecycle callbacks before connect() has run.
195
+ get archivedWithNewMessages() {
196
+ if (!this._archivedWithNewMessages) this._archivedWithNewMessages = new Set()
197
+ return this._archivedWithNewMessages
198
+ }
199
+
200
+ // list_controller asks this before appending a live message to All Messages:
201
+ // CommentsController#index leaves archived-topic comments out of that view,
202
+ // so a stream must not put one there either.
203
+ isArchivedTopic(id) {
204
+ if (!id) return false
205
+ return (this.archivedTopics || []).some(t => String(t.id) === String(id))
206
+ }
207
+
208
+ // Move a topic between the live and archived caches without waiting for the
209
+ // reload. Every caller follows with loadTopics(), which clears this.topics
210
+ // synchronously and refills both lists when its fetch lands — so this only
211
+ // has to be right for the window in between, which is exactly the window
212
+ // isArchivedTopic is consulted in.
213
+ applyArchiveTransition(action, topic) {
214
+ const id = topic && topic.id
215
+ if (!id) return
216
+
217
+ const key = String(id)
218
+ const known = [ ...(this.topics || []), ...(this.archivedTopics || []) ]
219
+ .find(t => String(t.id) === key)
220
+ const entry = { ...(known || {}), ...topic }
221
+
222
+ this.topics = (this.topics || []).filter(t => String(t.id) !== key)
223
+ this.archivedTopics = (this.archivedTopics || []).filter(t => String(t.id) !== key)
224
+
225
+ if (action === "archived") {
226
+ this.archivedTopics = [ ...this.archivedTopics, entry ]
227
+ } else {
228
+ this.topics = [ ...this.topics, entry ]
229
+ // Nothing archived is left to clear the badge from, so drop it here
230
+ // rather than leaving the toggle lit until the reload lands.
231
+ this.pruneArchivedBadges()
232
+ }
233
+ }
234
+
235
+ // The toggle badge is derived from set size, so an id that is no longer
236
+ // archived — unarchived, deleted, or left behind by a creative switch —
237
+ // would keep it lit with no chip to click and clear it.
238
+ pruneArchivedBadges() {
239
+ if (this.archivedWithNewMessages.size === 0) return
240
+ const archivedIds = new Set((this.archivedTopics || []).map(t => String(t.id)))
241
+ this.archivedWithNewMessages.forEach(id => {
242
+ if (!archivedIds.has(id)) this.archivedWithNewMessages.delete(id)
243
+ })
54
244
  }
55
245
 
56
246
  get creativeId() {
@@ -69,16 +259,42 @@ export default class extends Controller {
69
259
  return match ? match[1] : null
70
260
  }
71
261
 
262
+ // TopicsChannel and update_last_topic both resolve linked shells through
263
+ // effective_origin. Before a response provides that id, the requested id
264
+ // is the best available stream key. A shell that has already loaded keeps
265
+ // its resolved stream across a close/reopen, so an acknowledgement arriving
266
+ // before the replacement load can still tell that its echo is receivable.
267
+ get effectiveCreativeId() {
268
+ return this.element.dataset.effectiveCreativeId || this.effectiveCreativeIdFor(this.creativeId)
269
+ }
270
+
271
+ // A pending pick records the shell rendered in the popup, while channel
272
+ // claims are keyed by the origin stream. Resolve both through the cached
273
+ // mapping before comparing them so a linked-shell replacement keeps a newer
274
+ // pick ahead of an orphaned echo from the previous controller.
275
+ effectiveCreativeIdFor(creativeId) {
276
+ return this.knownEffectiveCreativeIds.get(String(creativeId)) || creativeId
277
+ }
278
+
72
279
  async loadTopics() {
73
280
  if (!this.creativeId) return
74
281
 
75
282
  const version = ++this._loadTopicsVersion
283
+ this._unreadCountsOverlay = null
284
+ const selectionEpoch = this.selectionEpoch
285
+ // A response can carry a snapshot produced before a save, while that
286
+ // save's HTTP response reaches us before the snapshot is processed.
287
+ // Remember which local saves had been acknowledged when this load
288
+ // started so their retained claims can still outrank that older view.
289
+ const acknowledgedSaveVersion = this.saveAcknowledgementVersion
290
+ this.activeLoadAcknowledgementVersions.set(version, acknowledgedSaveVersion)
291
+ const creativeId = this.creativeId
76
292
  // Clear stale topics from previous creative to prevent name-based
77
293
  // dedupe in handleTopicMessage from blocking valid broadcasts
78
294
  this.topics = []
79
295
 
80
296
  try {
81
- const response = await fetch(`/creatives/${this.creativeId}/topics`)
297
+ const response = await fetch(`/creatives/${creativeId}/topics`)
82
298
  // Discard stale response if a newer loadTopics() call was made
83
299
  if (version !== this._loadTopicsVersion) return
84
300
 
@@ -87,59 +303,237 @@ export default class extends Controller {
87
303
  }
88
304
  if (response.ok) {
89
305
  const data = await response.json()
90
- const topics = Array.isArray(data) ? data : data.topics
306
+ // A removal or newer load can arrive while a large response is
307
+ // being decoded, after the pre-parse version check above.
308
+ if (version !== this._loadTopicsVersion) return
309
+ const unreadCounts = this._unreadCountsOverlay?.loadVersion === version
310
+ ? this._unreadCountsOverlay.counts
311
+ : null
312
+ const topics = this.applyUnreadCounts(Array.isArray(data) ? data : data.topics, unreadCounts)
91
313
  const canManage = Array.isArray(data) ? false : data.can_manage
92
314
  const canCreateTopic = Array.isArray(data) ? false : (data.can_create_topic ?? canManage)
315
+ // Assigning an agent is authorized at :write, not :admin, so the
316
+ // release control must follow the same capability — otherwise a
317
+ // write collaborator can pin an agent by drag-and-drop and then
318
+ // has no way to undo it. Falls back to canManage for a server
319
+ // that predates the field.
320
+ const canSetPrimaryAgent = Array.isArray(data) ? false : (data.can_set_primary_agent ?? canManage)
93
321
  this.topics = topics
94
322
  this.canManageTopics = canManage
95
323
  this.canCreateTopic = canCreateTopic
96
- this.archivedTopics = data.archived_topics || []
97
- this.serverLastTopicId = data.last_topic_id ? String(data.last_topic_id) : ""
324
+ this.canSetPrimaryAgent = canSetPrimaryAgent
325
+ this.archivedTopics = this.applyUnreadCounts(data.archived_topics || [], unreadCounts)
326
+ this.pruneArchivedBadges()
327
+ const effectiveCreativeId = data.effective_creative_id
328
+ ? String(data.effective_creative_id)
329
+ : String(this.creativeId)
330
+ this.knownEffectiveCreativeIds.set(String(creativeId), effectiveCreativeId)
331
+ const snapshotTopicId = data.last_topic_id ? String(data.last_topic_id) : ""
332
+ const snapshotAllMessages = data.last_topic_all_messages === true
333
+ const snapshotTopicRevision = this.normalizeLastTopicRevision(data.last_topic_revision)
334
+ this.element.dataset.effectiveCreativeId = effectiveCreativeId
335
+ this.remapPendingSelfEchoesForCreative(creativeId, effectiveCreativeId)
336
+ this.releaseAcknowledgedPendingSelfEchoesOutside(effectiveCreativeId)
337
+ const staleLastTopicSnapshot = !this.observeLastTopicRevision(
338
+ effectiveCreativeId,
339
+ snapshotTopicRevision
340
+ )
341
+ const deferLastTopicReconciliation = this.hasUnacknowledgedRevisionedSaveFor(
342
+ effectiveCreativeId,
343
+ snapshotTopicRevision
344
+ )
345
+ if (deferLastTopicReconciliation) {
346
+ this.deferredLastTopicReconciliations.add(effectiveCreativeId)
347
+ }
348
+ // Claims are keyed by their effective creative stream. Keep claims
349
+ // for a stream we have temporarily left: a save can still be in
350
+ // flight while the popup visits another creative, and returning before
351
+ // its echo arrives must still recognise that echo as our own.
352
+ // A topic picked while this fetch was in flight is newer intent
353
+ // than the answer coming back: last_topic_id still names the
354
+ // topic the user left, because the save for the pick is
355
+ // debounced and has not landed. Overwriting it here — and then
356
+ // restoring from it below — throws the click away, snapping the
357
+ // strip and the message list back to the previous topic.
358
+ // _loadTopicsVersion does not cover this: it only discards a
359
+ // response outrun by another loadTopics(), not by a selection.
360
+ //
361
+ // Only a pick about this creative, though. Switching creatives
362
+ // leaves the previous creative's chips on screen until this
363
+ // fetch lands, and a click on one of those is intent about the
364
+ // creative being left. Its id would survive as the preference,
365
+ // fail the lookup in restoreSelection(), drop the user on Main
366
+ // and then persist Main as the new creative's saved topic.
367
+ const skipLastTopicReconciliation = staleLastTopicSnapshot || deferLastTopicReconciliation
368
+ const pickWon = !skipLastTopicReconciliation && !this.pendingPickWasSupersededWhileClosed(
369
+ effectiveCreativeId,
370
+ snapshotTopicId,
371
+ snapshotTopicRevision
372
+ ) && this.pickOutranks(selectionEpoch, creativeId, topics, this.archivedTopics)
373
+ let keepEmptySelection = false
374
+ if (skipLastTopicReconciliation) {
375
+ // The GET has a server ordering token, but this save has neither
376
+ // its response revision nor its echo yet. Its predecessor topic is
377
+ // not an ordering token (an ABA write can repeat it), so preserve
378
+ // the current selection until the request settles and retry below.
379
+ // A snapshot older than an already observed revision is likewise
380
+ // display data only; it must not restore an older preference.
381
+ } else if (pickWon) {
382
+ // An interim restore can run while this fetch has the strip
383
+ // empty and replace serverLastTopicId with Main. The epoch
384
+ // belongs to the actual pick, so restore that picked value
385
+ // rather than treating the derived fallback as its value.
386
+ this.serverLastTopicId = this._pickTopicId
387
+ keepEmptySelection = !this._pickTopicId
388
+ // The picked value has not necessarily reached the server yet.
389
+ // Keep the snapshot as the first known remote baseline so a
390
+ // claim created after this load records what its pending save
391
+ // actually supersedes. Never replace a newer Action Cable or
392
+ // acknowledged-save baseline with this older response.
393
+ if (this.lastKnownRemoteTopicIdFor(effectiveCreativeId) === undefined) {
394
+ this.setLastKnownRemoteTopicId(effectiveCreativeId, snapshotTopicId)
395
+ }
396
+ } else {
397
+ const pendingTopicId = this.latestPendingSelfEchoTopicIdFor(
398
+ effectiveCreativeId,
399
+ snapshotTopicId,
400
+ acknowledgedSaveVersion,
401
+ snapshotTopicRevision
402
+ )
403
+ if (pendingTopicId === undefined) {
404
+ this.serverLastTopicId = snapshotTopicId
405
+ // An empty id is also written when a selected topic is
406
+ // deleted or moved. Only the explicit server flag can
407
+ // distinguish that tombstone from All Messages.
408
+ keepEmptySelection = this.isPersistedAllMessagesSelection(
409
+ snapshotTopicId,
410
+ snapshotAllMessages
411
+ )
412
+ // A retained claim proves this response was an older view of
413
+ // the preference. Do not let that stale snapshot roll back
414
+ // the baseline used by the next save's closed-reopen check.
415
+ this.setLastKnownRemoteTopicId(effectiveCreativeId, snapshotTopicId)
416
+ } else {
417
+ this.serverLastTopicId = pendingTopicId
418
+ keepEmptySelection = !pendingTopicId
419
+ }
420
+ }
421
+ if (!skipLastTopicReconciliation) {
422
+ this._explicitAllMessagesSelection = keepEmptySelection
423
+ }
424
+ // The archive guard only has to outlive the sources that still
425
+ // name the topic. Test the effective selection, not just the
426
+ // preference: an unchanged ?topic_id= outranks it in the getter,
427
+ // so keying on serverLastTopicId would drop the guard while the
428
+ // URL was still pointing at the archived topic. Once nothing
429
+ // names it, a later reselection is honoured normally.
430
+ if (this.archivedAwayTopicId && String(this.currentTopicId) !== this.archivedAwayTopicId) {
431
+ this.archivedAwayTopicId = null
432
+ }
98
433
  this.isInbox = !!data.is_inbox
99
434
  this.systemTopicId = data.system_topic_id ? String(data.system_topic_id) : null
100
435
  this.mainTopicId = data.main_topic_id ? String(data.main_topic_id) : null
101
436
  // Expose effective origin id so chat-context autofill (slash commands)
102
437
  // and any other consumer can target the same creative the server uses
103
438
  // (linked creatives resolve params[:creative_id] through effective_origin).
104
- if (data.effective_creative_id) {
105
- this.element.dataset.effectiveCreativeId = String(data.effective_creative_id)
439
+ // Migrate localStorage to server if server has no value. An
440
+ // unresolved revisioned save must not turn its retained local
441
+ // selection into another PATCH while reconciliation is deferred.
442
+ if (!skipLastTopicReconciliation) {
443
+ this.migrateLocalStorage({ keepEmptySelection })
106
444
  }
107
445
 
108
- // Migrate localStorage to server if server has no value
109
- this.migrateLocalStorage()
110
-
111
- this.renderTopics(this.topics, this.canManageTopics, this.canCreateTopic)
112
- this.restoreSelection()
446
+ this.renderTopics(this.topics, this.canManageTopics, this.canCreateTopic, this.canSetPrimaryAgent, creativeId)
447
+ if (this.currentTopicId) this.clearNewMessageBadge(this.currentTopicId)
448
+ if (!skipLastTopicReconciliation) {
449
+ this.restoreSelection({ keepEmptySelection })
450
+ }
451
+ this.refreshOpenTopicListPopup()
113
452
  }
114
453
  } catch (e) {
115
454
  console.error("Failed to load topics", e)
116
455
  throw e
456
+ } finally {
457
+ this.activeLoadAcknowledgementVersions.delete(version)
458
+ this.discardSettledSelfEchoesNoLongerNeeded()
117
459
  }
118
460
  }
119
461
 
120
- restoreSelection() {
462
+ // keepEmptySelection: the caller established that All Messages is an
463
+ // intentional selection, either from a pick that outran this load or from
464
+ // the explicit All Messages server preference. It names no topic,
465
+ // so it cannot be restored from a topic list and must be reapplied. Without
466
+ // this the Main fallback below treats it as "nothing selected", navigates
467
+ // away from it and persists Main. A prior interim restore may also have
468
+ // dispatched Main, so reapplying sends the authoritative empty selection
469
+ // to downstream controllers again.
470
+ restoreSelection({ keepEmptySelection = this._explicitAllMessagesSelection } = {}) {
121
471
  const lastTopicId = this.currentTopicId
122
- if (lastTopicId) {
123
- // Validate it exists in list
124
- const exists = this.listTarget.querySelector(`[data-id="${lastTopicId}"]`)
125
- if (exists) {
126
- this.selectTopic(lastTopicId)
472
+ // A deep link controls this popup's view, but it is not a replacement
473
+ // for the saved preference. Replaying the linked selection after a
474
+ // preference broadcast must therefore update the UI without writing the
475
+ // link back over that newer server value.
476
+ const preservePreference = this.hasDeepLinkSelection
477
+ // archiveTopic() switched away from this topic on purpose. The server
478
+ // preference still names it until the debounced save lands, so accept
479
+ // the local intent over the stale server answer for that window.
480
+ if (lastTopicId && String(lastTopicId) !== this.archivedAwayTopicId) {
481
+ // Validate against the topic data, not the rendered DOM. An archived
482
+ // topic is still readable and writable — archiving hides it from the
483
+ // strip, it does not close the conversation. A DOM lookup would bounce
484
+ // the user back to Main every time the archived section is collapsed,
485
+ // because collapsed chips are never rendered. selectTopic expands the
486
+ // section when the selection lands inside it.
487
+ const known = [ ...(this.topics || []), ...(this.archivedTopics || []) ]
488
+ if (known.some(t => String(t.id) === String(lastTopicId))) {
489
+ // Restoring is not a navigation, so it must not undo a collapse
490
+ // the user chose while sitting in this very topic. Only
491
+ // restoreSelection is suppressed; every other selectTopic caller
492
+ // is the user going somewhere, and reveals normally.
493
+ const reveal = this.archivedCollapsedTopicId !== String(lastTopicId)
494
+ this.selectTopic(lastTopicId, { reveal, pick: false, persist: !preservePreference })
127
495
  return
128
496
  }
129
497
  }
130
498
 
131
- this.selectTopic(this.mainTopicId || "")
499
+ if (keepEmptySelection && !lastTopicId) {
500
+ this.selectTopic("", { pick: false, persist: !preservePreference })
501
+ return
502
+ }
503
+
504
+ if (preservePreference && !lastTopicId) {
505
+ this.selectTopic("", { pick: false, persist: false })
506
+ return
507
+ }
508
+
509
+ // Not a pick: this fallback is what the current state resolves to, and
510
+ // loadTopics() empties the strip for the length of its fetch, so any
511
+ // re-render landing in that window resolves to Main whatever the user
512
+ // has selected. Counting it as intent would let it outrank the answer
513
+ // it was derived from — and drop the deep link on the way.
514
+ // Before the first topic response there is no Main id yet. The empty
515
+ // placeholder is not an All Messages choice, so it must not be saved as
516
+ // the explicit empty preference introduced for that user action.
517
+ const persistFallback = Boolean(this.mainTopicId) && !preservePreference
518
+ this.selectTopic(this.mainTopicId || "", { pick: false, persist: persistFallback })
132
519
  }
133
520
 
134
- renderTopics(topics, canManage = false, canCreateTopic = canManage) {
135
- const dragActions = canManage
136
- ? 'dragstart->comments--topics#handleTopicDragStart dragend->comments--topics#handleTopicDragEnd'
137
- : ''
138
- const dropActions = 'dragover->comments--topics#handleDragOver dragleave->comments--topics#handleDragLeave drop->comments--topics#handleDrop'
139
- const topicDropActions = canManage
140
- ? 'dragover->comments--topics#handleTopicReorderDragOver dragleave->comments--topics#handleTopicReorderDragLeave drop->comments--topics#handleTopicReorderDrop'
141
- : ''
521
+ // An archived topic can be opened from the topic strip, the topic-list popup,
522
+ // a deep link, or a restored last-topic. Expand the archived section from this
523
+ // one choke point so the strip always shows which topic is open.
524
+ revealArchivedTopic(id) {
525
+ if (!id || this.showingArchived) return
526
+ if (!this.isArchivedTopic(id)) return
527
+
528
+ // Reaching here is a deliberate navigation into the section, so an
529
+ // earlier collapse no longer describes what the user wants.
530
+ this.archivedCollapsedTopicId = null
531
+ this.showingArchived = true
532
+ this.renderTopics(this.topics, this.canManageTopics, this.canCreateTopic, this.canSetPrimaryAgent)
533
+ }
142
534
 
535
+ renderTopics(topics, canManage = false, canCreateTopic = canManage, canSetPrimaryAgent = canManage, sourceCreativeId = this._topicsCreativeId || this.creativeId) {
536
+ const cronMessageDrafts = this.captureCronMessageDrafts()
143
537
  const allMessagesLabel = this.element.dataset.topicMainText || 'All Messages'
144
538
 
145
539
  const mainTopic = this.mainTopicId ? topics.find(t => String(t.id) === String(this.mainTopicId)) : null
@@ -149,53 +543,116 @@ export default class extends Controller {
149
543
 
150
544
  const renderTopic = (topic) => {
151
545
  const isActive = String(this.currentTopicId) === String(topic.id) ? 'active' : ''
152
- const draggable = canManage ? 'draggable="true"' : ''
546
+ const draggable = canManage && !topic.read_only ? 'draggable="true"' : ''
547
+ // agent_locked marks a live agent session topic, whose primary agent is
548
+ // session identity rather than a routing pin — the server refuses to
549
+ // change it, so the avatar must not offer to release it.
550
+ const releasableTopicId = canSetPrimaryAgent && !topic.agent_locked ? topic.id : null
153
551
  const agentAvatar = topic.primary_agent
154
- ? this.renderAgentAvatar(topic.primary_agent)
552
+ ? this.renderAgentAvatar(topic.primary_agent, releasableTopicId)
155
553
  : ''
156
554
  const branchIcon = topic.source_topic_id ? '<span class="topic-branch-icon" title="Branched">↗</span>' : ''
555
+ const unreadBadge = topic.unread_count > 0
556
+ ? `<span class="topic-unread-badge">${topic.unread_count}</span>`
557
+ : ''
558
+ const cronBadge = topic.cron_badge_html || ''
157
559
  const isMainTopic = this.mainTopicId && String(topic.id) === String(this.mainTopicId)
158
560
  let s = `<span class="topic-tag topic-drop-target ${isActive}" ${draggable}
159
- data-action="click->comments--topics#select ${dropActions} ${dragActions} ${topicDropActions}"
561
+ data-action="click->comments--topics#select" data-dnd-read-only="${!!topic.read_only}"
160
562
  data-id="${topic.id}"${topic.source_topic_id ? ` data-source-topic-id="${topic.source_topic_id}"` : ''}>
161
- ${agentAvatar}${branchIcon}#${topic.name}`
162
- if (canManage && !isMainTopic) {
163
- s += `<button class="archive-topic-btn" data-action="click->comments--topics#archiveTopic" data-id="${topic.id}" title="Archive">${ICON_ARCHIVE}</button>`
164
- s += `<button class="delete-topic-btn" data-action="click->comments--topics#deleteTopic" data-id="${topic.id}">&times;</button>`
563
+ ${agentAvatar}${branchIcon}#${topic.display_name || topic.name}${cronBadge}${unreadBadge}`
564
+ if (canManage && !topic.read_only) {
565
+ if (!isMainTopic) s += `<button class="archive-topic-btn" data-action="click->comments--topics#archiveTopic" data-id="${topic.id}" title="Archive">${ICON_ARCHIVE}</button>`
566
+ s += `<button class="delete-topic-btn" data-action="click->comments--topics#deleteTopic" data-id="${topic.id}">&times;</button>`
165
567
  }
166
- s += `</span>`
167
- return s
568
+ return s + `</span>`
168
569
  }
169
570
 
170
571
  if (mainTopic) html += renderTopic(mainTopic)
171
572
  otherTopics.forEach(topic => { html += renderTopic(topic) })
172
573
 
173
574
  html += `<span class="topic-tag topic-drop-target topic-all-messages ${this.currentTopicId ? '' : 'active'}"
174
- data-action="click->comments--topics#select ${dropActions}"
575
+ data-action="click->comments--topics#select"
175
576
  data-id="">📋 ${allMessagesLabel}</span>`
176
577
 
177
578
  // Archived topics section
178
579
  if (this.archivedTopics && this.archivedTopics.length > 0) {
179
- html += `<span class="topic-archived-toggle" data-action="click->comments--topics#toggleArchivedTopics">
580
+ // Badges are re-applied from state on every render because innerHTML
581
+ // below wipes the classes set by handleNewMessage.
582
+ const toggleBadge = this.archivedWithNewMessages.size > 0 ? ' has-new-messages' : ''
583
+ html += `<span class="topic-archived-toggle${toggleBadge}" data-action="click->comments--topics#toggleArchivedTopics">
180
584
  ${ICON_ARCHIVE} ${this.archivedTopics.length}
181
585
  </span>`
182
586
  if (this.showingArchived) {
183
587
  this.archivedTopics.forEach(topic => {
184
- html += `<span class="topic-tag topic-archived" data-id="${topic.id}">
185
- #${topic.name}
186
- ${canManage ? `<button class="unarchive-topic-btn" data-action="click->comments--topics#unarchiveTopic" data-id="${topic.id}" title="Restore">${ICON_RESTORE}</button>` : ''}
588
+ const isActive = String(this.currentTopicId) === String(topic.id) ? ' active' : ''
589
+ const hasNew = this.archivedWithNewMessages.has(String(topic.id)) ? ' has-new-messages' : ''
590
+ const unreadBadge = topic.unread_count > 0
591
+ ? `<span class="topic-unread-badge">${topic.unread_count}</span>`
592
+ : ''
593
+ const cronBadge = topic.cron_badge_html || ''
594
+ html += `<span class="topic-tag topic-archived${isActive}${hasNew}"
595
+ data-action="click->comments--topics#select"
596
+ data-id="${topic.id}">
597
+ #${topic.name}${cronBadge}${unreadBadge}
598
+ ${archivedTopicControls(this, topic, canManage, ICON_RESTORE)}
187
599
  </span>`
188
600
  })
189
601
  }
190
602
  }
191
603
 
192
604
  this.listTarget.innerHTML = html
605
+ this.restoreCronMessageDrafts(cronMessageDrafts)
606
+ // Which creative the chips now on screen belong to. A click can only
607
+ // ever be about this one, whatever this.creativeId has since become.
608
+ this._renderedCreativeId = sourceCreativeId
609
+ this._topicsCreativeId = sourceCreativeId
193
610
 
194
611
  // The create button lives outside the scrolling strip so it stays reachable
195
612
  // without horizontal scrolling, no matter how many topics there are.
196
613
  this.renderCreationContainer(canCreateTopic)
197
614
  }
198
615
 
616
+ captureCronMessageDrafts() {
617
+ const drafts = new Map()
618
+ this.listTarget.querySelectorAll('[data-cron-key]').forEach(task => {
619
+ const input = task.querySelector('[data-cron-badge-target="messageInput"]')
620
+ const saveOperationId = task.dataset.cronSaveOperation
621
+ const deleteOperationId = task.dataset.cronDeleteOperation
622
+ const dirty = input && input.value !== input.dataset.cronSavedMessage
623
+ if (!input || (!dirty && !saveOperationId && !deleteOperationId)) return
624
+
625
+ drafts.set(task.dataset.cronKey, {
626
+ message: input.value,
627
+ dirty,
628
+ saveOperationId,
629
+ deleteOperationId,
630
+ })
631
+ })
632
+ return drafts
633
+ }
634
+
635
+ restoreCronMessageDrafts(drafts) {
636
+ this.listTarget.querySelectorAll('[data-cron-key]').forEach(task => {
637
+ if (!drafts.has(task.dataset.cronKey)) return
638
+
639
+ const input = task.querySelector('[data-cron-badge-target="messageInput"]')
640
+ if (!input) return
641
+
642
+ const draft = drafts.get(task.dataset.cronKey)
643
+ if (draft.dirty || draft.saveOperationId) input.value = draft.message
644
+ if (draft.saveOperationId) {
645
+ task.dataset.cronSaveOperation = draft.saveOperationId
646
+ input.disabled = true
647
+ task.querySelector('[data-action~="click->cron-badge#saveMessage"]').disabled = true
648
+ }
649
+ if (draft.deleteOperationId) {
650
+ task.dataset.cronDeleteOperation = draft.deleteOperationId
651
+ task.querySelector('[data-action~="click->cron-badge#destroy"]').disabled = true
652
+ }
653
+ })
654
+ }
655
+
199
656
  // Write permission is sufficient for topic creation.
200
657
  renderCreationContainer(canCreateTopic) {
201
658
  if (!this.hasCreationContainerTarget) return
@@ -222,57 +679,36 @@ export default class extends Controller {
222
679
  `<button class="add-topic-btn" data-action="click->comments--topics#showInput">+</button>`
223
680
  }
224
681
 
225
- handleDragOver(event) {
226
- // Accept comment drops or agent drops
227
- const isComment = event.dataTransfer.types.includes('application/x-comment-ids')
228
- const isAgent = event.dataTransfer.types.includes('application/x-agent-drop')
229
- if (!isComment && !isAgent) return
230
-
231
- event.preventDefault()
232
- event.dataTransfer.dropEffect = isAgent ? 'copy' : 'move'
233
- event.currentTarget.classList.add('drag-over')
234
- }
235
-
236
- handleDragLeave(event) {
237
- event.currentTarget.classList.remove('drag-over')
238
- }
239
-
240
- async handleDrop(event) {
241
- event.preventDefault()
242
- event.currentTarget.classList.remove('drag-over')
243
-
244
- // Handle agent drop
245
- const agentJson = event.dataTransfer.getData('application/x-agent-drop')
246
- if (agentJson) {
247
- const agent = JSON.parse(agentJson)
248
- const targetTopicId = event.currentTarget.dataset.id || this.mainTopicId
249
- if (targetTopicId) {
250
- await this.setTopicPrimaryAgent(targetTopicId, agent)
251
- }
252
- return
682
+ _registerDragDrop() {
683
+ this.dnd = createDragDropRegistry({ root: this.element, getKind: getDragKind, readData: readDragData })
684
+ this.dnd.registerDragSource({ selector: '.topic-tag[draggable="true"]',
685
+ onDragStart: this.handleTopicDragStart.bind(this),
686
+ onDragEnd: ({ el }) => { this.draggingTopicId = null; el.classList.remove('topic-dragging') } })
687
+ const selector = '.topic-drop-target:not([data-dnd-read-only="true"]), [data-comments--topics-target="creationContainer"]'
688
+ for (const kind of ['comments', 'agent']) {
689
+ this.dnd.registerDropZone({ selector, accepts: [kind], dropEffect: kind === 'agent' ? 'copy' : 'move',
690
+ preview: previewDrop,
691
+ onDrop: async ({ el, ids, payload }) => {
692
+ const agent = { ...payload, id: ids[0] }
693
+ if (el === this.creationContainerTarget) {
694
+ if (kind === 'comments') await this.createTopicAndMoveComments(ids)
695
+ else await this.createTopicWithAgent(agent)
696
+ } else {
697
+ const targetTopicId = el.dataset.id || this.mainTopicId
698
+ if (kind === 'agent') {
699
+ if (targetTopicId) await this.setTopicPrimaryAgent(targetTopicId, agent)
700
+ } else this.dispatch('move-to-topic', { detail: { commentIds: ids, targetTopicId } })
701
+ }
702
+ } })
253
703
  }
254
-
255
- // Handle comment drop
256
- const commentIdsJson = event.dataTransfer.getData('application/x-comment-ids')
257
- if (!commentIdsJson) return
258
-
259
- const commentIds = JSON.parse(commentIdsJson)
260
- if (!commentIds || commentIds.length === 0) return
261
-
262
- const targetTopicId = event.currentTarget.dataset.id || this.mainTopicId
263
-
264
- // Dispatch event for list_controller to handle the move
265
- this.dispatch('move-to-topic', {
266
- detail: {
267
- commentIds,
268
- targetTopicId
269
- }
270
- })
704
+ this.dnd.registerDropZone({ selector: '.topic-tag[draggable="true"]', accepts: ['topic'],
705
+ hitTest: ({ el, event }) => this.draggingTopicId && el.dataset.id !== this.draggingTopicId
706
+ ? horizontalHit({ el, event }) : null,
707
+ preview: previewDrop, onDrop: this.handleTopicReorderDrop.bind(this) })
271
708
  }
272
709
 
273
710
  // Topic reorder drag & drop handlers
274
- handleTopicDragStart(event) {
275
- const topicEl = event.currentTarget
711
+ handleTopicDragStart({ event, el: topicEl }) {
276
712
  const topicId = topicEl.dataset.id
277
713
  if (!topicId) {
278
714
  event.preventDefault()
@@ -280,69 +716,19 @@ export default class extends Controller {
280
716
  }
281
717
 
282
718
  this.draggingTopicId = topicId
283
- event.dataTransfer.setData('application/x-topic-id', topicId)
284
- // Include topic move data so creative tree rows can accept this drop
285
- event.dataTransfer.setData('application/x-topic-move', JSON.stringify({
286
- topicId,
287
- sourceCreativeId: this.creativeId
288
- }))
719
+ writeDragData(event.dataTransfer, { kind: 'topic', ids: [topicId], payload: { sourceCreativeId: this.creativeId } })
289
720
  event.dataTransfer.effectAllowed = 'move'
290
721
 
291
722
  requestAnimationFrame(() => {
292
- topicEl.classList.add('topic-dragging')
723
+ if (this.draggingTopicId === topicId) topicEl.classList.add('topic-dragging')
293
724
  })
294
725
  }
295
726
 
296
- handleTopicDragEnd(event) {
297
- this.draggingTopicId = null
298
- event.currentTarget.classList.remove('topic-dragging')
299
- this.listTarget.querySelectorAll('.topic-tag').forEach(el => {
300
- el.classList.remove('topic-drag-over-left', 'topic-drag-over-right')
301
- })
302
- }
303
-
304
- handleTopicReorderDragOver(event) {
305
- // Only accept topic reorder drops
306
- if (!event.dataTransfer.types.includes('application/x-topic-id')) return
307
- if (!this.draggingTopicId) return
308
-
309
- const targetEl = event.currentTarget
310
- const targetId = targetEl.dataset.id
311
-
312
- // Don't allow drop on self or Main
313
- if (!targetId || targetId === this.draggingTopicId) return
314
-
315
- event.preventDefault()
316
- event.dataTransfer.dropEffect = 'move'
317
-
318
- // Determine drop position (left or right) based on mouse position
319
- const rect = targetEl.getBoundingClientRect()
320
- const midpoint = rect.left + rect.width / 2
321
- const isLeft = event.clientX < midpoint
322
-
323
- targetEl.classList.toggle('topic-drag-over-left', isLeft)
324
- targetEl.classList.toggle('topic-drag-over-right', !isLeft)
325
- }
326
-
327
- handleTopicReorderDragLeave(event) {
328
- event.currentTarget.classList.remove('topic-drag-over-left', 'topic-drag-over-right')
329
- }
330
-
331
- async handleTopicReorderDrop(event) {
332
- event.preventDefault()
333
-
334
- const targetEl = event.currentTarget
335
- targetEl.classList.remove('topic-drag-over-left', 'topic-drag-over-right')
336
-
337
- const draggedTopicId = event.dataTransfer.getData('application/x-topic-id')
338
- const targetTopicId = targetEl.dataset.id
339
-
340
- if (!draggedTopicId || !targetTopicId || draggedTopicId === targetTopicId) return
341
-
342
- // Determine drop position
343
- const rect = targetEl.getBoundingClientRect()
344
- const midpoint = rect.left + rect.width / 2
345
- const insertBefore = event.clientX < midpoint
727
+ async handleTopicReorderDrop({ el, ids, hit }) {
728
+ const draggedTopicId = ids[0]
729
+ const targetTopicId = el.dataset.id
730
+ if (!draggedTopicId || !targetTopicId || String(draggedTopicId) === targetTopicId) return
731
+ const insertBefore = hit === 'left'
346
732
 
347
733
  // Reorder topics array
348
734
  const topics = [...this.topics]
@@ -367,7 +753,7 @@ export default class extends Controller {
367
753
 
368
754
  // Update local state and UI immediately
369
755
  this.topics = topics
370
- this.renderTopics(topics, this.canManageTopics, this.canCreateTopic)
756
+ this.renderTopics(topics, this.canManageTopics, this.canCreateTopic, this.canSetPrimaryAgent)
371
757
  this.restoreSelection()
372
758
 
373
759
  // Send to server
@@ -411,6 +797,9 @@ export default class extends Controller {
411
797
 
412
798
  if (!topicId) return
413
799
 
800
+ const deletingSelectedTopic = String(this.currentTopicId) === String(topicId)
801
+ const scrollInterruptionVersion = this._topicScrollInterruptionVersion
802
+
414
803
  try {
415
804
  const response = await fetch(`/creatives/${this.creativeId}/topics/${topicId}`, {
416
805
  method: 'DELETE',
@@ -420,8 +809,16 @@ export default class extends Controller {
420
809
  })
421
810
 
422
811
  if (response.ok) {
812
+ // The server can broadcast "deleted" before this response. In
813
+ // that case removeTopic() has already cleared currentTopicId,
814
+ // but this local removal should still reveal All Messages.
815
+ // A newer wheel/touch gesture always wins, though.
816
+ if (deletingSelectedTopic
817
+ && this._topicScrollInterruptionVersion === scrollInterruptionVersion) this._topicScrollInterrupted = false
818
+ if (reloadDeletedReservedTopic(this, topicId)) return
423
819
  if (String(this.currentTopicId) === String(topicId)) {
424
- this.currentTopicId = "" // Switch to Main
820
+ // Release deep links before loadTopics restores selection.
821
+ this.fallbackFromRemovedTopic(topicId)
425
822
  this.dispatch("change", { detail: { topicId: "", mainTopicId: this.mainTopicId } })
426
823
  }
427
824
  this.loadTopics()
@@ -448,9 +845,28 @@ export default class extends Controller {
448
845
 
449
846
  if (response.ok) {
450
847
  if (String(this.currentTopicId) === String(topicId)) {
848
+ this._topicScrollInterrupted = false
849
+ // Archiving the topic in view switches to All Messages, but
850
+ // the preference save is debounced 500ms and both this
851
+ // reload and the "archived" broadcast's own reload can beat
852
+ // it. restoreSelection() accepts archived ids now, so the
853
+ // stale last_topic_id would drop the user straight back into
854
+ // the topic they just archived out of. Flag it instead of
855
+ // flushing the save: the broadcast reload cannot be ordered
856
+ // behind the flush, only ignored.
857
+ this.archivedAwayTopicId = String(topicId)
858
+ // Both sources that outrank serverLastTopicId in the
859
+ // currentTopicId getter have to go too, or the archived
860
+ // topic stays the effective selection no matter what the
861
+ // preference says: overrideTopicId (deep link) and the
862
+ // ?topic_id= query parameter.
863
+ this.releaseDeepLinkSelection(topicId)
451
864
  this.currentTopicId = ""
452
865
  this.dispatch("change", { detail: { topicId: "", mainTopicId: this.mainTopicId } })
453
866
  }
867
+ // The actor has the same stale-membership window as everyone
868
+ // receiving the broadcast, so close it on this side too.
869
+ this.applyArchiveTransition("archived", { id: topicId })
454
870
  this.loadTopics()
455
871
  } else {
456
872
  alertDialog(this._i18n("archive_error"))
@@ -474,6 +890,7 @@ export default class extends Controller {
474
890
  })
475
891
 
476
892
  if (response.ok) {
893
+ this.applyArchiveTransition("unarchived", { id: topicId })
477
894
  this.loadTopics()
478
895
  } else {
479
896
  alertDialog(this._i18n("restore_error"))
@@ -486,31 +903,44 @@ export default class extends Controller {
486
903
  toggleArchivedTopics(event) {
487
904
  event.stopPropagation()
488
905
  this.showingArchived = !this.showingArchived
489
- this.renderTopics(this.topics, this.canManageTopics, this.canCreateTopic)
490
- this.restoreSelection()
906
+ // Collapsing while the open topic lives in this section is a deliberate
907
+ // choice to hide it, so record it. Every re-render runs restoreSelection
908
+ // → selectTopic → revealArchivedTopic, which would otherwise reopen the
909
+ // section on any unrelated rename, reorder, or topic broadcast.
910
+ this.archivedCollapsedTopicId = !this.showingArchived && this.isArchivedTopic(this.currentTopicId)
911
+ ? String(this.currentTopicId)
912
+ : null
913
+ // No restoreSelection() here: toggling cannot invalidate the selection, and
914
+ // renderTopics already re-applies the active class. Re-selecting would
915
+ // re-expand the section the user just collapsed (selectTopic reveals an
916
+ // archived selection) and pointlessly reload the message list.
917
+ this.renderTopics(this.topics, this.canManageTopics, this.canCreateTopic, this.canSetPrimaryAgent)
491
918
  }
492
919
 
493
920
  openTopicListPopup(event) {
921
+ if (this.topicListToggleGuard.consume()) return
922
+
494
923
  const btnRect = event.currentTarget.getBoundingClientRect()
495
924
 
496
925
  const openWith = (popup) => {
497
926
  popup.openForTopics(
498
- {
499
- topics: this.topics || [],
500
- archivedTopics: this.archivedTopics || [],
501
- mainTopicId: this.mainTopicId,
502
- allMessagesLabel: this.element.dataset.topicMainText || 'All Messages'
503
- },
927
+ this.topicListData(),
504
928
  btnRect,
505
- (item) => this.selectTopic(item.id),
929
+ (item) => this.selectTopic(item.id, { userInitiated: true }),
506
930
  this.element
507
931
  )
932
+ this.setTopicListButtonExpanded(true)
508
933
  }
509
934
 
510
935
  let modal = document.getElementById('topic-list-modal')
511
936
  if (modal) {
512
937
  const popup = this.application.getControllerForElementAndIdentifier(modal, 'topic-list')
513
- if (popup) openWith(popup)
938
+ if (popup?.popup?.isOpen()) {
939
+ popup?.close()
940
+ this.setTopicListButtonExpanded(false)
941
+ } else if (popup) {
942
+ openWith(popup)
943
+ }
514
944
  return
515
945
  }
516
946
 
@@ -537,6 +967,138 @@ export default class extends Controller {
537
967
  })
538
968
  }
539
969
 
970
+ topicListData() {
971
+ return {
972
+ topics: this.topics || [],
973
+ archivedTopics: this.archivedTopics || [],
974
+ mainTopicId: this.mainTopicId,
975
+ allMessagesLabel: this.element.dataset.topicMainText || 'All Messages'
976
+ }
977
+ }
978
+
979
+ refreshOpenTopicListPopup() {
980
+ const modal = this.element.querySelector('#topic-list-modal')
981
+ const popup = modal && this.application.getControllerForElementAndIdentifier(modal, 'topic-list')
982
+ if (popup?.popup?.isOpen()) popup.updateTopics(this.topicListData())
983
+ }
984
+
985
+ scheduleUnreadCountRefresh() {
986
+ if (this._unreadCountRefreshInFlight) {
987
+ this._unreadCountRefreshQueued = true
988
+ return
989
+ }
990
+ if (this._unreadCountRefreshTimer) return
991
+
992
+ this._unreadCountRefreshTimer = setTimeout(() => {
993
+ this._unreadCountRefreshTimer = null
994
+ this._unreadCountRefreshInFlight = true
995
+ this.refreshUnreadCounts()
996
+ .catch(error => console.error("Failed to refresh topic unread counts", error))
997
+ .finally(() => {
998
+ this._unreadCountRefreshInFlight = false
999
+ if (!this._unreadCountRefreshQueued) return
1000
+
1001
+ this._unreadCountRefreshQueued = false
1002
+ this.scheduleUnreadCountRefresh()
1003
+ })
1004
+ }, UNREAD_COUNT_REFRESH_DELAY)
1005
+ }
1006
+
1007
+ cancelUnreadCountRefresh() {
1008
+ clearTimeout(this._unreadCountRefreshTimer)
1009
+ this._unreadCountRefreshTimer = null
1010
+ this._unreadCountRefreshQueued = false
1011
+ }
1012
+
1013
+ async refreshUnreadCounts() {
1014
+ if (!this.creativeId) return
1015
+
1016
+ const creativeId = String(this.creativeId)
1017
+ const loadVersion = this._loadTopicsVersion
1018
+ const response = await fetch(`/creatives/${creativeId}/topics`)
1019
+ if (!response.ok) return
1020
+
1021
+ const data = await response.json()
1022
+ if (String(this.creativeId) !== creativeId || this._loadTopicsVersion !== loadVersion) return
1023
+
1024
+ const activeTopics = Array.isArray(data) ? data : data.topics
1025
+ const counts = new Map(
1026
+ [...(activeTopics || []), ...(data.archived_topics || [])]
1027
+ .map(topic => [String(topic.id), Number(topic.unread_count) || 0])
1028
+ )
1029
+ this._unreadCountsOverlay = { loadVersion, counts }
1030
+ this.topics = this.applyUnreadCounts(this.topics, counts)
1031
+ this.archivedTopics = this.applyUnreadCounts(this.archivedTopics, counts)
1032
+ if (this.currentTopicId) this.clearNewMessageBadge(this.currentTopicId)
1033
+ this.refreshRenderedUnreadCounts()
1034
+ this.refreshOpenTopicListPopup()
1035
+ }
1036
+
1037
+ applyUnreadCounts(topics = [], counts = null) {
1038
+ if (!counts) return topics
1039
+
1040
+ return topics.map(topic => counts.has(String(topic.id))
1041
+ ? { ...topic, unread_count: counts.get(String(topic.id)) }
1042
+ : topic)
1043
+ }
1044
+
1045
+ refreshRenderedUnreadCounts() {
1046
+ const topicsById = new Map(
1047
+ [...(this.topics || []), ...(this.archivedTopics || [])]
1048
+ .map(topic => [String(topic.id), topic])
1049
+ )
1050
+
1051
+ this.listTarget.querySelectorAll('.topic-tag[data-id]').forEach(topicEl => {
1052
+ const topic = topicsById.get(String(topicEl.dataset.id))
1053
+ if (!topic || topicEl.querySelector('.topic-edit-input')) return
1054
+
1055
+ const count = Number(topic.unread_count) || 0
1056
+ const badge = topicEl.querySelector('.topic-unread-badge')
1057
+ if (count <= 0) {
1058
+ badge?.remove()
1059
+ return
1060
+ }
1061
+ if (badge) {
1062
+ badge.textContent = String(count)
1063
+ return
1064
+ }
1065
+
1066
+ const newBadge = document.createElement('span')
1067
+ newBadge.className = 'topic-unread-badge'
1068
+ newBadge.textContent = String(count)
1069
+ topicEl.insertBefore(newBadge, topicEl.querySelector('button'))
1070
+ })
1071
+ }
1072
+
1073
+ get topicListToggleGuard() {
1074
+ this._topicListToggleGuard ||= new PopupToggleGuard()
1075
+ return this._topicListToggleGuard
1076
+ }
1077
+
1078
+ prepareTopicListToggle(event) {
1079
+ const modal = document.getElementById('topic-list-modal')
1080
+ const popup = modal && this.application.getControllerForElementAndIdentifier(modal, 'topic-list')
1081
+ this.topicListToggleGuard.prepare(event, Boolean(popup?.popup?.isOpen()))
1082
+ }
1083
+
1084
+ finishTopicListToggle(event) {
1085
+ this.topicListToggleGuard.finish(event)
1086
+ }
1087
+
1088
+ cancelTopicListToggle(event = {}) {
1089
+ this.topicListToggleGuard.cancel(event)
1090
+ }
1091
+
1092
+ handleTopicListClose() {
1093
+ this.setTopicListButtonExpanded(false)
1094
+ }
1095
+
1096
+ setTopicListButtonExpanded(expanded) {
1097
+ if (this.hasTopicListButtonTarget) {
1098
+ this.topicListButtonTarget.setAttribute('aria-expanded', String(expanded))
1099
+ }
1100
+ }
1101
+
540
1102
  showInput(event) {
541
1103
  event.preventDefault()
542
1104
  if (!this.hasCreationContainerTarget) return
@@ -578,6 +1140,7 @@ export default class extends Controller {
578
1140
  select(event) {
579
1141
  // Ignore if clicking on delete button (though stopPropagation should handle it)
580
1142
  if (event.target.closest('.delete-topic-btn')) return
1143
+ if (event.target.closest('.cron-badge-wrapper')) return
581
1144
  // Ignore if clicking on edit input
582
1145
  if (event.target.closest('.topic-edit-input')) return
583
1146
 
@@ -585,7 +1148,7 @@ export default class extends Controller {
585
1148
  if (event.target.closest('.topic-branch-icon')) {
586
1149
  const sourceTopicId = event.currentTarget.dataset.sourceTopicId
587
1150
  if (sourceTopicId) {
588
- this.selectTopic(sourceTopicId)
1151
+ this.selectTopic(sourceTopicId, { userInitiated: true })
589
1152
  return
590
1153
  }
591
1154
  }
@@ -593,21 +1156,41 @@ export default class extends Controller {
593
1156
  const id = event.currentTarget.dataset.id
594
1157
 
595
1158
  // If clicking on already active topic (not Main), show edit mode
596
- if (id && String(this.currentTopicId) === String(id) && this.canManageTopics) {
1159
+ const selectedTopic = [ ...(this.topics || []), ...(this.archivedTopics || []) ]
1160
+ .find(topic => String(topic.id) === String(id))
1161
+ if (id && String(this.currentTopicId) === String(id) && this.canManageTopics && !selectedTopic?.read_only) {
597
1162
  this.showEditInput(event.currentTarget, id)
598
1163
  return
599
1164
  }
600
1165
 
601
- this.selectTopic(id)
1166
+ this.selectTopic(id, { userInitiated: true })
602
1167
  }
603
1168
 
604
- selectTopic(id) {
605
- this.updateSelectionUI(id)
1169
+ selectTopic(id, { reveal = true, pick = true, persist = true, userInitiated = false } = {}) {
1170
+ // Only restoreSelection() is guarded, so reaching selectTopic with this
1171
+ // id means the user deliberately went back into the archived topic.
1172
+ // The transition is over.
1173
+ if (this.archivedAwayTopicId && String(id) === this.archivedAwayTopicId) {
1174
+ this.archivedAwayTopicId = null
1175
+ }
1176
+ if (reveal) this.revealArchivedTopic(id)
1177
+ this.updateSelectionUI(id, { pick, persist, pending: pick, userInitiated })
606
1178
  if (id) {
607
1179
  this.clearNewMessageBadge(id)
608
1180
  }
609
- // Dispatch event
610
- this.dispatch("change", { detail: { topicId: id, isInbox: this.isInbox, systemTopicId: this.systemTopicId, mainTopicId: this.mainTopicId } })
1181
+ this.dispatch("change", { detail: this.changeDetail(id) })
1182
+ }
1183
+
1184
+ changeDetail(id) {
1185
+ const topic = [ ...(this.topics || []), ...(this.archivedTopics || []) ]
1186
+ .find(candidate => String(candidate.id) === String(id))
1187
+ return {
1188
+ topicId: id,
1189
+ isInbox: this.isInbox,
1190
+ systemTopicId: this.systemTopicId,
1191
+ mainTopicId: this.mainTopicId,
1192
+ readOnly: topic?.read_only || false,
1193
+ }
611
1194
  }
612
1195
 
613
1196
  showEditInput(topicEl, topicId) {
@@ -656,6 +1239,7 @@ export default class extends Controller {
656
1239
  if (topicEl && topicEl.dataset.originalHtml) {
657
1240
  topicEl.innerHTML = topicEl.dataset.originalHtml
658
1241
  delete topicEl.dataset.originalHtml
1242
+ this.refreshRenderedUnreadCounts()
659
1243
  }
660
1244
 
661
1245
  setTimeout(() => { this.editCancelling = false }, 100)
@@ -680,7 +1264,7 @@ export default class extends Controller {
680
1264
  if (index !== -1) {
681
1265
  this.topics[index] = { ...this.topics[index], ...updatedTopic }
682
1266
  }
683
- this.renderTopics(this.topics, this.canManageTopics, this.canCreateTopic)
1267
+ this.renderTopics(this.topics, this.canManageTopics, this.canCreateTopic, this.canSetPrimaryAgent)
684
1268
  this.restoreSelection()
685
1269
  } else {
686
1270
  alertDialog(this._i18n("update_error"))
@@ -692,8 +1276,9 @@ export default class extends Controller {
692
1276
  }
693
1277
  }
694
1278
 
695
- updateSelectionUI(id) {
696
- this.currentTopicId = id
1279
+ updateSelectionUI(id, { pick = true, persist = true, pending = false, userInitiated = false } = {}) {
1280
+ if (userInitiated) this._topicScrollInterrupted = false
1281
+ this.applySelection(id, { pick, persist, pending })
697
1282
  // Update UI
698
1283
  let activeEl = null
699
1284
  this.listTarget.querySelectorAll('.topic-tag').forEach(el => {
@@ -704,17 +1289,56 @@ export default class extends Controller {
704
1289
  activeEl = el
705
1290
  }
706
1291
  })
707
- // Scroll active topic into view
708
- if (activeEl) {
709
- activeEl.scrollIntoView({ behavior: 'smooth', block: 'nearest', inline: 'center' })
710
- }
1292
+ if (activeEl) this.scrollTopicIntoView(activeEl)
711
1293
  }
712
1294
 
713
1295
  scrollToActiveTopic() {
714
1296
  const activeEl = this.listTarget.querySelector('.topic-tag.active')
715
- if (activeEl) {
716
- activeEl.scrollIntoView({ behavior: 'smooth', block: 'nearest', inline: 'center' })
1297
+ if (activeEl) this.scrollTopicIntoView(activeEl)
1298
+ }
1299
+
1300
+ scrollTopicIntoView(topic) {
1301
+ if (this._popupClosed || this._topicScrollInterrupted) return
1302
+
1303
+ this.cancelProgrammaticScroll()
1304
+ const list = this.listTarget
1305
+ const listRect = list.getBoundingClientRect()
1306
+ const topicRect = topic.getBoundingClientRect()
1307
+ const maxLeft = Math.max(0, list.scrollWidth - list.clientWidth)
1308
+ const targetLeft = Math.max(0, Math.min(
1309
+ maxLeft,
1310
+ list.scrollLeft + topicRect.left + (topicRect.width / 2)
1311
+ - listRect.left - (listRect.width / 2),
1312
+ ))
1313
+ const startLeft = list.scrollLeft
1314
+ const distance = targetLeft - startLeft
1315
+ if (Math.abs(distance) < 1) return
1316
+
1317
+ const startedAt = performance.now()
1318
+ const step = now => {
1319
+ const progress = Math.min((now - startedAt) / TOPIC_SCROLL_DURATION, 1)
1320
+ const easedProgress = 1 - ((1 - progress) ** 3)
1321
+ list.scrollLeft = startLeft + (distance * easedProgress)
1322
+ if (progress < 1) {
1323
+ this._topicScrollFrame = requestAnimationFrame(step)
1324
+ } else {
1325
+ this._topicScrollFrame = null
1326
+ }
717
1327
  }
1328
+ this._topicScrollFrame = requestAnimationFrame(step)
1329
+ }
1330
+
1331
+ cancelProgrammaticScroll() {
1332
+ if (this._topicScrollFrame === null) return
1333
+
1334
+ cancelAnimationFrame(this._topicScrollFrame)
1335
+ this._topicScrollFrame = null
1336
+ }
1337
+
1338
+ handleTopicScrollInput() {
1339
+ this._topicScrollInterruptionVersion += 1
1340
+ this._topicScrollInterrupted = true
1341
+ this.cancelProgrammaticScroll()
718
1342
  }
719
1343
 
720
1344
  handleTopicMoved(event) {
@@ -723,7 +1347,8 @@ export default class extends Controller {
723
1347
  if (String(sourceCreativeId) === String(this.creativeId)) {
724
1348
  // If we were viewing the moved topic, switch to Main
725
1349
  if (String(this.currentTopicId) === String(topicId)) {
726
- this.currentTopicId = ""
1350
+ this._topicScrollInterrupted = false
1351
+ this.fallbackFromRemovedTopic(topicId)
727
1352
  this.dispatch("change", { detail: { topicId: "", mainTopicId: this.mainTopicId } })
728
1353
  }
729
1354
  this.loadTopics()
@@ -737,9 +1362,18 @@ export default class extends Controller {
737
1362
  // Don't show badge if we are currently in this topic (shouldn't happen due to list_controller logic, but safety check)
738
1363
  if (String(this.currentTopicId) === String(topicId)) return
739
1364
 
1365
+ const isArchived = this.isArchivedTopic(topicId)
1366
+ if (isArchived) this.archivedWithNewMessages.add(String(topicId))
1367
+
740
1368
  const topicEl = this.listTarget.querySelector(`.topic-tag[data-id="${topicId}"]`)
741
- if (topicEl) {
742
- topicEl.classList.add('has-new-messages')
1369
+ if (topicEl) topicEl.classList.add('has-new-messages')
1370
+
1371
+ this.scheduleUnreadCountRefresh()
1372
+
1373
+ // A collapsed archived section has no chip to badge, so the toggle carries
1374
+ // the notice — otherwise a message in an archived topic is invisible.
1375
+ if (isArchived) {
1376
+ this.listTarget.querySelector('.topic-archived-toggle')?.classList.add('has-new-messages')
743
1377
  }
744
1378
  }
745
1379
 
@@ -747,6 +1381,17 @@ export default class extends Controller {
747
1381
  const topicEl = this.listTarget.querySelector(`.topic-tag[data-id="${topicId}"]`)
748
1382
  if (topicEl) {
749
1383
  topicEl.classList.remove('has-new-messages')
1384
+ topicEl.querySelector('.topic-unread-badge')?.remove()
1385
+ }
1386
+
1387
+ const topic = [...(this.topics || []), ...(this.archivedTopics || [])]
1388
+ .find(candidate => String(candidate.id) === String(topicId))
1389
+ if (topic) topic.unread_count = 0
1390
+
1391
+ // The toggle aggregates every archived topic, so it only clears once none
1392
+ // of them is left unread.
1393
+ if (this.archivedWithNewMessages.delete(String(topicId)) && this.archivedWithNewMessages.size === 0) {
1394
+ this.listTarget.querySelector('.topic-archived-toggle')?.classList.remove('has-new-messages')
750
1395
  }
751
1396
  }
752
1397
 
@@ -767,6 +1412,7 @@ export default class extends Controller {
767
1412
 
768
1413
  if (response.ok) {
769
1414
  const topic = await response.json()
1415
+ this._topicScrollInterrupted = false
770
1416
  this.currentTopicId = topic.id
771
1417
  // Flush save immediately so loadTopics gets the correct value from server
772
1418
  await this.flushSaveLastTopic(topic.id)
@@ -798,6 +1444,56 @@ export default class extends Controller {
798
1444
  return this.serverLastTopicId || ""
799
1445
  }
800
1446
 
1447
+ // Is one of the two sources above the preference still set? Not the same
1448
+ // question as "is the getter's answer nonempty" — an override of "" outranks
1449
+ // the preference just as a named one does.
1450
+ get hasDeepLinkSelection() {
1451
+ if (this.overrideTopicId !== undefined && this.overrideTopicId !== null) return true
1452
+
1453
+ return Boolean(new URLSearchParams(window.location.search).get('topic_id'))
1454
+ }
1455
+
1456
+ // A topic leaving the strip — archived or deleted — has to leave both
1457
+ // sources that outrank serverLastTopicId in the currentTopicId getter.
1458
+ // Assigning "" only touches the preference, so on its own the getter goes
1459
+ // on naming the gone topic and every later restoreSelection() finds it
1460
+ // unknown and resets to Main, discarding whatever the user picked instead.
1461
+ releaseDeepLinkSelection(topicId) {
1462
+ this.clearOverrideTopicId()
1463
+ this.clearUrlTopicId(topicId)
1464
+ }
1465
+
1466
+ // Deletion and move tombstones mean "fall back to Main", not that the user
1467
+ // picked All Messages. Do not queue a blank preference save while the topic
1468
+ // reload is still pending, because the server records blank saves as an
1469
+ // explicit All Messages choice.
1470
+ fallbackFromRemovedTopic(topicId) {
1471
+ this.cancelPendingSaveLastTopic()
1472
+ if (String(this._pendingPick?.topicId) === String(topicId)) this._pendingPick = null
1473
+ // A link only protects a distinct saved preference behind it. If both
1474
+ // sources name the removed topic, releasing the link would otherwise
1475
+ // expose that same dead preference and select it again.
1476
+ const preservePreference = this.hasDeepLinkSelection &&
1477
+ String(this.serverLastTopicId) !== String(topicId)
1478
+ this.releaseDeepLinkSelection(topicId)
1479
+ if (!preservePreference) {
1480
+ this.serverLastTopicId = ""
1481
+ this._explicitAllMessagesSelection = false
1482
+ }
1483
+ }
1484
+
1485
+ // Drop ?topic_id= when it names the topic being archived. It is a selection
1486
+ // source in its own right and survives every reload, so leaving it would
1487
+ // re-select the topic the user just archived out of. replaceState, not a
1488
+ // navigation: the chat state around it must stay put.
1489
+ clearUrlTopicId(topicId) {
1490
+ const url = new URL(window.location.href)
1491
+ if (url.searchParams.get('topic_id') !== String(topicId)) return
1492
+
1493
+ url.searchParams.delete('topic_id')
1494
+ window.history.replaceState(window.history.state, '', url.toString())
1495
+ }
1496
+
801
1497
  setOverrideTopicId(id) {
802
1498
  this.overrideTopicId = id ? String(id) : ""
803
1499
  }
@@ -807,60 +1503,723 @@ export default class extends Controller {
807
1503
  }
808
1504
 
809
1505
  set currentTopicId(id) {
810
- this.serverLastTopicId = id ? String(id) : ""
811
- this.debounceSaveLastTopic(id)
1506
+ this.applySelection(id)
1507
+ }
1508
+
1509
+ // pick: this selection is new intent — the user picked it, or the server
1510
+ // told us their preference moved. A restore is not: it re-derives the
1511
+ // selection from state already held, so it is never newer than anything and
1512
+ // must leave the sources that outrank the preference alone. Recording the
1513
+ // preference and saving it happen either way; only the two consequences of
1514
+ // *intent* are gated.
1515
+ applySelection(id, { pick = true, persist = true, pending = false } = {}) {
1516
+ if (persist) this.serverLastTopicId = id ? String(id) : ""
1517
+ if (pick) {
1518
+ // selectTopic marks picks as pending; a blank direct setter is a
1519
+ // programmatic fallback after deletion/archive and should retain
1520
+ // the established Main fallback instead of becoming All Messages.
1521
+ if (id || pending) this._explicitAllMessagesSelection = !id
1522
+ // Writing only the preference leaves the two sources that outrank it
1523
+ // in the getter still naming the topic being left, so the getter
1524
+ // keeps answering with it: the next renderTopics() lights the old
1525
+ // chip and the next restoreSelection() navigates back to it. Both
1526
+ // are one-shot pointers at a topic to open, and this selection has
1527
+ // moved off it. Dropped only when they disagree — a deep link that
1528
+ // resolved to the topic now being selected must keep outranking the
1529
+ // stale server last_topic_id for the rest of the popup session.
1530
+ this.releaseSelectionSourcesOtherThan(this.serverLastTopicId)
1531
+ this.selectionState.recordPick(
1532
+ this._renderedCreativeId,
1533
+ this.serverLastTopicId,
1534
+ { pending }
1535
+ )
1536
+ }
1537
+ if (persist) this.debounceSaveLastTopic(id)
1538
+ }
1539
+
1540
+ // Bumped on every selection so an in-flight loadTopics() can tell whether
1541
+ // its answer predates a pick the user has since made.
1542
+ get selectionEpoch() {
1543
+ return this.selectionState.epoch
1544
+ }
1545
+
1546
+ set selectionEpoch(value) {
1547
+ this.selectionState.epoch = value
1548
+ }
1549
+
1550
+ // Did a pick land after the load at `epoch` started, or is there still an
1551
+ // unsaved pick about the creative that load describes? A later load can
1552
+ // begin before the pick's debounce lands, so request age alone cannot tell
1553
+ // whether its answer predates the pick. The strip the click landed on,
1554
+ // not by this.creativeId — onPopupOpened assigns that synchronously before
1555
+ // the fetch, so a click on the outgoing creative's chips already carries the
1556
+ // incoming id. The rendered strip is what the user was actually looking at.
1557
+ //
1558
+ // An empty pick (All Messages) names no topic to match against the response,
1559
+ // and its provenance is the only thing that distinguishes it from a click on
1560
+ // a stale strip — so it rests on that test alone. A named pick is checked
1561
+ // against the topics too: one whose topic the response does not list was
1562
+ // made against a strip that predates a delete, and keeping it would fail the
1563
+ // lookup in restoreSelection() and persist Main in its place.
1564
+ pickOutranks(epoch, creativeId, topics, archivedTopics) {
1565
+ return this.selectionState.outranks(epoch, creativeId, topics, archivedTopics)
1566
+ }
1567
+
1568
+ releaseSelectionSourcesOtherThan(id) {
1569
+ if (this.overrideTopicId !== undefined && this.overrideTopicId !== null &&
1570
+ String(this.overrideTopicId) !== String(id)) {
1571
+ this.clearOverrideTopicId()
1572
+ }
1573
+
1574
+ const urlTopicId = new URLSearchParams(window.location.search).get('topic_id')
1575
+ if (urlTopicId && urlTopicId !== String(id)) {
1576
+ this.clearUrlTopicId(urlTopicId)
1577
+ }
812
1578
  }
813
1579
 
814
1580
  debounceSaveLastTopic(id) {
815
- if (this._saveLastTopicTimer) clearTimeout(this._saveLastTopicTimer)
1581
+ this.cancelPendingSaveLastTopic()
1582
+ // A linked shell can close before this debounce fires. Closing clears
1583
+ // the cached effective origin, and reopening another shell before the
1584
+ // callback runs would otherwise claim that shell's raw id even though
1585
+ // the save belongs to the stream selected here. Capture the requested
1586
+ // creative too: it is the PATCH endpoint, not the effective stream.
1587
+ const effectiveCreativeId = this.effectiveCreativeId
1588
+ const creativeId = this.creativeId
816
1589
  this._saveLastTopicTimer = setTimeout(() => {
817
- this.flushSaveLastTopic(id)
1590
+ this.flushSaveLastTopic(id, effectiveCreativeId, creativeId)
818
1591
  }, 500)
819
1592
  }
820
1593
 
821
- async flushSaveLastTopic(id) {
822
- if (this._saveLastTopicTimer) {
1594
+ // Drop a queued save without sending it. The timer closes over the id it
1595
+ // was scheduled with, so a save that is no longer wanted cannot be talked
1596
+ // out of its value — only cancelled.
1597
+ cancelPendingSaveLastTopic() {
1598
+ if (this._saveLastTopicTimer !== undefined && this._saveLastTopicTimer !== null) {
823
1599
  clearTimeout(this._saveLastTopicTimer)
824
1600
  this._saveLastTopicTimer = null
825
1601
  }
826
- if (this.creativeId) {
827
- await saveLastTopic(this.creativeId, id || null)
1602
+ }
1603
+
1604
+ async flushSaveLastTopic(
1605
+ id,
1606
+ claimedEffectiveCreativeId = this.effectiveCreativeId,
1607
+ requestedCreativeId = this.creativeId
1608
+ ) {
1609
+ this.cancelPendingSaveLastTopic()
1610
+ if (!requestedCreativeId) return
1611
+
1612
+ const creativeId = requestedCreativeId
1613
+ const effectiveCreativeId = claimedEffectiveCreativeId
1614
+ const clientId = this.newLastTopicSaveClientId()
1615
+ const pendingPick = this._pendingPick
1616
+ // The subscription the echo of this save would arrive on. The claim is
1617
+ // taken inside the callback below, which runs whenever the save ahead
1618
+ // of it finishes — by then the stream may already be a different one,
1619
+ // and a claim taken against a stream we have left is owed a message
1620
+ // that cannot arrive.
1621
+ const generation = this.subscriptionGenerationFor(effectiveCreativeId)
1622
+ // One save at a time. Two PATCHes in flight together are persisted in
1623
+ // whatever order the server finishes them, so the preference that
1624
+ // sticks need not be the last one picked. Waiting for the one in
1625
+ // flight is what makes the order they were picked in the order they
1626
+ // are written.
1627
+ const context = {
1628
+ id, creativeId, effectiveCreativeId, clientId, pendingPick, generation,
1629
+ }
1630
+ return this.lastTopicSave.enqueue(context)
1631
+ }
1632
+
1633
+ // A timed-out fetch can still be running on Rails. Prefix each echo id with
1634
+ // a controller-local session and monotonically increasing sequence so Rails
1635
+ // can reject an older request if a later one from this controller commits
1636
+ // first. The trailing nonce keeps the Action Cable echo identifier unique.
1637
+ newLastTopicSaveClientId() {
1638
+ return this.saveOrderState.nextClientId()
1639
+ }
1640
+
1641
+ // A request that never settles must not hold every later pick behind it.
1642
+ // Its server outcome remains ambiguous, so the caller still retains a short
1643
+ // lived echo claim just as it does for a rejected fetch.
1644
+ saveLastTopicWithTimeout(creativeId, topicId, clientId) {
1645
+ const abortController = new AbortController()
1646
+ const request = Promise.resolve(
1647
+ saveLastTopic(creativeId, topicId, clientId, abortController.signal)
1648
+ ).catch(() => null)
1649
+ let timeoutId
1650
+ const timedOutRequest = new Promise(resolve => {
1651
+ timeoutId = setTimeout(() => {
1652
+ // Do not advance the serialized queue while this request can still
1653
+ // reach Rails. An abort makes fetch settle before the next save starts.
1654
+ abortController.abort()
1655
+ request.then(resolve)
1656
+ }, SAVE_REQUEST_TIMEOUT)
1657
+ })
1658
+
1659
+ return Promise.race([request, timedOutRequest]).finally(() => clearTimeout(timeoutId))
1660
+ }
1661
+
1662
+ // The echo names the save it came from, so this is identity, not a guess.
1663
+ // Matching on the topic id instead would let a sibling session that picked
1664
+ // the same topic settle one of our claims, leaving our own echo to arrive
1665
+ // later looking like news and revert whatever the user picked meanwhile.
1666
+ consumeSelfEcho(clientId, lastTopicRevision) {
1667
+ if (!clientId) return false
1668
+
1669
+ const index = this.pendingSelfEchoes.indexOf(clientId)
1670
+ if (index === -1) return false
1671
+
1672
+ // An echo proves the save committed even when it wins the race with its
1673
+ // HTTP response. Keep its ordering data only while an older GET can still
1674
+ // arrive; otherwise that GET could restore the pre-save preference after
1675
+ // the response has cleared _pendingPick.
1676
+ this.saveAcknowledgementVersion += 1
1677
+ this.pendingSelfEchoAcknowledgementVersions.set(
1678
+ clientId,
1679
+ this.saveAcknowledgementVersion
1680
+ )
1681
+ const normalizedRevision = this.normalizeLastTopicRevision(lastTopicRevision)
1682
+ if (normalizedRevision) {
1683
+ this.pendingSelfEchoRemoteRevisions.set(clientId, normalizedRevision)
1684
+ }
1685
+ this.acknowledgedPendingSelfEchoes.add(clientId)
1686
+ this.pendingSelfEchoes.splice(index, 1)
1687
+ // Keep the closed-gap marker with the tombstone. A reopened GET can be
1688
+ // newer than this committed save even when its response races ahead of
1689
+ // the PATCH response; releasing this marker here would make that newer
1690
+ // sibling-session snapshot look stale and replay our old pick over it.
1691
+ this.settledSelfEchoes.add(clientId)
1692
+ this.discardSettledSelfEchoesNoLongerNeeded()
1693
+ return true
1694
+ }
1695
+
1696
+ releasePendingSelfEcho(clientId) {
1697
+ const index = this.pendingSelfEchoes.indexOf(clientId)
1698
+ if (index === -1) return false
1699
+
1700
+ this.pendingSelfEchoes.splice(index, 1)
1701
+ this.discardSelfEchoMetadata(clientId)
1702
+ return true
1703
+ }
1704
+
1705
+ // A Turbo replacement clears controller-local claims while an earlier PATCH
1706
+ // can still commit. The save-session prefix belongs to this top-level tab,
1707
+ // so its orphaned echo remains ours and must not be applied as a sibling
1708
+ // update over the replacement controller's newer pick.
1709
+ isLastTopicSaveFromThisTab(clientId) {
1710
+ const match = String(clientId || "").match(/^([A-Za-z0-9-]+)\.([1-9]\d*)\.[A-Za-z0-9-]+$/)
1711
+ const currentName = window.name || ""
1712
+ if (!currentName.startsWith(LAST_TOPIC_SAVE_WINDOW_NAME_PREFIX)) return false
1713
+
1714
+ const sessionId = currentName.slice(LAST_TOPIC_SAVE_WINDOW_NAME_PREFIX.length)
1715
+ return Boolean(match) && /^[A-Za-z0-9-]+$/.test(sessionId) && match[1] === sessionId
1716
+ }
1717
+
1718
+ // A retired ambiguous request can still have committed after its connection
1719
+ // failed. Its sequence is monotonic within a tab session, so one high-water
1720
+ // mark per session keeps all older late echoes non-actionable without retaining
1721
+ // one tombstone per failed save.
1722
+ retirePendingSelfEcho(clientId) {
1723
+ const released = this.releasePendingSelfEcho(clientId)
1724
+ if (released) this.observeRetiredSelfEcho(clientId)
1725
+ return released
1726
+ }
1727
+
1728
+ lastTopicSaveClientIdParts(clientId) {
1729
+ const match = String(clientId || "").match(/^([A-Za-z0-9-]+)\.([1-9]\d*)\.[A-Za-z0-9-]+$/)
1730
+ if (!match) return null
1731
+
1732
+ return { sessionId: match[1], sequence: Number(match[2]) }
1733
+ }
1734
+
1735
+ observeRetiredSelfEcho(clientId) {
1736
+ const parts = this.lastTopicSaveClientIdParts(clientId)
1737
+ if (!parts) return
1738
+
1739
+ const previous = this.retiredSelfEchoSequenceHighWaters.get(parts.sessionId) || 0
1740
+ if (parts.sequence > previous) {
1741
+ this.retiredSelfEchoSequenceHighWaters.set(parts.sessionId, parts.sequence)
1742
+ }
1743
+ }
1744
+
1745
+ isRetiredSelfEcho(clientId) {
1746
+ const parts = this.lastTopicSaveClientIdParts(clientId)
1747
+ if (!parts) return false
1748
+
1749
+ return parts.sequence <= (this.retiredSelfEchoSequenceHighWaters.get(parts.sessionId) || 0)
1750
+ }
1751
+
1752
+ discardSelfEchoMetadata(clientId) {
1753
+ this.cancelAmbiguousPendingSelfEchoRetirement(clientId)
1754
+ this.pendingSelfEchoCreativeIds.delete(clientId)
1755
+ this.pendingSelfEchoTopicIds.delete(clientId)
1756
+ this.pendingSelfEchoPreviousTopicIds.delete(clientId)
1757
+ this.pendingSelfEchoAcknowledgementVersions.delete(clientId)
1758
+ this.pendingSelfEchoRemoteRevisions.delete(clientId)
1759
+ this.possiblyMissedPendingSelfEchoes.delete(clientId)
1760
+ this.possiblyMissedPendingSelfEchoesDuringDisconnect.delete(clientId)
1761
+ this.acknowledgedPendingSelfEchoes.delete(clientId)
1762
+ this.settledSelfEchoes.delete(clientId)
1763
+ }
1764
+
1765
+ // A rejected fetch has an ambiguous server outcome, so retain its claim long
1766
+ // enough for a delayed self-echo. It cannot remain forever, though: a request
1767
+ // that never reached Rails has no echo or revision to resolve it, and would
1768
+ // otherwise defer every later revisioned snapshot on this stream.
1769
+ scheduleAmbiguousPendingSelfEchoRetirement(clientId) {
1770
+ if (!this.pendingSelfEchoes.includes(clientId)) return
1771
+
1772
+ this.cancelAmbiguousPendingSelfEchoRetirement(clientId)
1773
+ const timeout = setTimeout(() => {
1774
+ this.ambiguousPendingSelfEchoRetirements.delete(clientId)
1775
+ const creativeId = this.pendingSelfEchoCreativeIds.get(clientId)
1776
+ if (creativeId === undefined ||
1777
+ this.acknowledgedPendingSelfEchoes.has(clientId) ||
1778
+ this.pendingSelfEchoRemoteRevisions.has(clientId)) return
1779
+
1780
+ this.retirePendingSelfEcho(clientId)
1781
+ this.retryDeferredLastTopicReconciliation(creativeId)
1782
+ }, AMBIGUOUS_SAVE_CLAIM_TIMEOUT)
1783
+ this.ambiguousPendingSelfEchoRetirements.set(clientId, timeout)
1784
+ }
1785
+
1786
+ cancelAmbiguousPendingSelfEchoRetirement(clientId) {
1787
+ const timeout = this.ambiguousPendingSelfEchoRetirements.get(clientId)
1788
+ if (timeout !== undefined) clearTimeout(timeout)
1789
+ this.ambiguousPendingSelfEchoRetirements.delete(clientId)
1790
+ }
1791
+
1792
+ get ambiguousPendingSelfEchoRetirements() {
1793
+ return this.selfEchoState.ambiguousRetirementTimers
1794
+ }
1795
+
1796
+ get retiredSelfEchoSequenceHighWaters() {
1797
+ return this.selfEchoState.retiredSequenceHighWaters
1798
+ }
1799
+
1800
+ // An early echo can be the only proof that an in-flight GET predates a
1801
+ // committed save. Once every GET that started before it has finished, the
1802
+ // tombstone has no ordering work left and must not accumulate in a long-lived
1803
+ // popup controller. Compare the save version captured by each active load,
1804
+ // not its unrelated request sequence number.
1805
+ discardSettledSelfEchoesNoLongerNeeded() {
1806
+ for (const clientId of [...this.settledSelfEchoes]) {
1807
+ const acknowledgementVersion = this.pendingSelfEchoAcknowledgementVersions.get(clientId)
1808
+ const hasOlderLoad = [...this.activeLoadAcknowledgementVersions.values()].some(
1809
+ loadAcknowledgementVersion => loadAcknowledgementVersion < acknowledgementVersion
1810
+ )
1811
+ if (!hasOlderLoad) this.discardSelfEchoMetadata(clientId)
828
1812
  }
829
1813
  }
830
1814
 
831
- migrateLocalStorage() {
1815
+ // Ids of saves this client has made and not yet seen come back. The echo of
1816
+ // our own save is not news: it names what we already asked for, and by the
1817
+ // time it arrives the user may have picked something else — applying it
1818
+ // then reverts the newer pick and persists the older topic over it.
1819
+ get pendingSelfEchoes() {
1820
+ return this.selfEchoState.pendingIds
1821
+ }
1822
+
1823
+ get pendingSelfEchoCreativeIds() {
1824
+ return this.selfEchoState.creativeIds
1825
+ }
1826
+
1827
+ get pendingSelfEchoTopicIds() {
1828
+ return this.selfEchoState.topicIds
1829
+ }
1830
+
1831
+ // The last preference observed from the server is the baseline for a save.
1832
+ // It belongs to an effective creative stream: a controller can move between
1833
+ // creatives before the next fetch resolves, and one stream's preference is
1834
+ // never evidence about another stream.
1835
+ get lastKnownRemoteTopicId() {
1836
+ return this.lastKnownRemoteTopicIdFor(this.effectiveCreativeId)
1837
+ }
1838
+
1839
+ set lastKnownRemoteTopicId(value) {
1840
+ this.setLastKnownRemoteTopicId(this.effectiveCreativeId, value)
1841
+ }
1842
+
1843
+ lastKnownRemoteTopicIdFor(creativeId) {
1844
+ return this.saveOrderState.lastKnownTopicIdFor(creativeId)
1845
+ }
1846
+
1847
+ setLastKnownRemoteTopicId(creativeId, value) {
1848
+ this.saveOrderState.setLastKnownTopicId(creativeId, value)
1849
+ }
1850
+
1851
+ get lastKnownRemoteTopicIds() {
1852
+ return this.saveOrderState.lastKnownRemoteTopicIds
1853
+ }
1854
+
1855
+ // Action Cable is ordered only within a connection. A delayed older message
1856
+ // can therefore arrive after a newer GET, response, or broadcast. Keep the
1857
+ // server-issued revision per effective stream and never apply it backward.
1858
+ observeLastTopicRevision(creativeId, revision) {
1859
+ return this.saveOrderState.observeRevision(creativeId, revision)
1860
+ }
1861
+
1862
+ get highestLastTopicRevisions() {
1863
+ return this.saveOrderState.highestRevisions
1864
+ }
1865
+
1866
+ // The server resolves TopicsChannel subscriptions for linked shells to their
1867
+ // origin stream. Keep that result separately from the popup-scoped dataset:
1868
+ // the latter is deliberately cleared while a replacement load is pending.
1869
+ get knownEffectiveCreativeIds() {
1870
+ return this.saveOrderState.knownEffectiveCreativeIds
1871
+ }
1872
+
1873
+ get pendingSelfEchoPreviousTopicIds() {
1874
+ return this.selfEchoState.previousTopicIds
1875
+ }
1876
+
1877
+ get pendingSelfEchoAcknowledgementVersions() {
1878
+ return this.selfEchoState.acknowledgementVersions
1879
+ }
1880
+
1881
+ // The preference row id distinguishes a record recreated after clearing the
1882
+ // selection; the per-row revision orders saves made while it exists. Together
1883
+ // they are a server-issued ordering token, rather than an inference from a
1884
+ // topic id that can repeat in an ABA change (Main -> Alpha -> Main).
1885
+ normalizeLastTopicRevision(value) {
1886
+ return this.saveOrderState.normalizeRevision(value)
1887
+ }
1888
+
1889
+ isPersistedAllMessagesSelection(topicId, allMessages) {
1890
+ return !topicId && allMessages === true
1891
+ }
1892
+
1893
+ compareLastTopicRevisions(left, right) {
1894
+ return this.saveOrderState.compareRevisions(left, right)
1895
+ }
1896
+
1897
+ get pendingSelfEchoRemoteRevisions() {
1898
+ return this.selfEchoState.remoteRevisions
1899
+ }
1900
+
1901
+ // Echoes normally remove their claims. A short-lived tombstone retains the
1902
+ // save order for GETs already in progress when the echo arrived.
1903
+ get settledSelfEchoes() {
1904
+ return this.selfEchoState.settledIds
1905
+ }
1906
+
1907
+ get activeLoadAcknowledgementVersions() {
1908
+ return this.saveOrderState.activeLoadAcknowledgementVersions
1909
+ }
1910
+
1911
+ get saveAcknowledgementVersion() {
1912
+ return this.saveOrderState.acknowledgementVersion
1913
+ }
1914
+
1915
+ set saveAcknowledgementVersion(value) {
1916
+ this.saveOrderState.acknowledgementVersion = value
1917
+ }
1918
+
1919
+ // These claims were already in flight when the popup unsubscribed. If their
1920
+ // response arrives while the popup remains closed, the broadcast necessarily
1921
+ // went into that gap. A replacement subscription can receive an echo when it
1922
+ // reopens before the response arrives, though.
1923
+ get possiblyMissedPendingSelfEchoes() {
1924
+ return this.selfEchoState.possiblyMissedIds
1925
+ }
1926
+
1927
+ // A broadcast sent after Action Cable disconnects is not replayed after the
1928
+ // connection returns. Keep unresolved saves until their HTTP outcome tells us
1929
+ // whether one could have been sent in that gap; acknowledged saves can be
1930
+ // retired immediately because their broadcast has already been sent.
1931
+ get possiblyMissedPendingSelfEchoesDuringDisconnect() {
1932
+ return this.selfEchoState.possiblyMissedDuringDisconnectIds
1933
+ }
1934
+
1935
+ handleTopicsSubscriptionDisconnected() {
1936
+ const deferredCreativeIds = new Set()
1937
+ for (const clientId of [...this.pendingSelfEchoes]) {
1938
+ const creativeId = this.pendingSelfEchoCreativeIds.get(clientId)
1939
+ if (creativeId === undefined) continue
1940
+
1941
+ if (!this.acknowledgedPendingSelfEchoes.has(clientId)) {
1942
+ this.possiblyMissedPendingSelfEchoesDuringDisconnect.add(clientId)
1943
+ continue
1944
+ }
1945
+
1946
+ this.setLastKnownRemoteTopicId(creativeId, this.pendingSelfEchoTopicIds.get(clientId))
1947
+ this.retirePendingSelfEcho(clientId)
1948
+ deferredCreativeIds.add(creativeId)
1949
+ }
1950
+ for (const creativeId of deferredCreativeIds) {
1951
+ this.retryDeferredLastTopicReconciliation(creativeId)
1952
+ }
1953
+ }
1954
+
1955
+ markPendingSelfEchoesAsPossiblyMissed() {
1956
+ for (const clientId of this.pendingSelfEchoes) {
1957
+ if (!this.acknowledgedPendingSelfEchoes.has(clientId)) {
1958
+ this.possiblyMissedPendingSelfEchoes.add(clientId)
1959
+ }
1960
+ }
1961
+ }
1962
+
1963
+ // A successful response means the broadcast was already sent. Once this
1964
+ // popup unsubscribes, that echo cannot be replayed to settle its claim, so
1965
+ // retaining the acknowledgement metadata would leak it indefinitely.
1966
+ releaseAcknowledgedPendingSelfEchoes() {
1967
+ for (const clientId of [...this.pendingSelfEchoes]) {
1968
+ if (this.acknowledgedPendingSelfEchoes.has(clientId)) {
1969
+ this.releasePendingSelfEcho(clientId)
1970
+ }
1971
+ }
1972
+ }
1973
+
1974
+ // A new requested creative initially has no client-side effective stream
1975
+ // entry. Its subscription may still resolve server-side to the stream of a
1976
+ // pending save, so do not release that claim until this GET supplies the
1977
+ // effective id. Once it does, an acknowledged claim on another stream can
1978
+ // no longer receive an echo on this subscription and must not be retained.
1979
+ releaseAcknowledgedPendingSelfEchoesOutside(effectiveCreativeId) {
1980
+ const streamCreativeId = String(effectiveCreativeId)
1981
+ for (const clientId of [...this.pendingSelfEchoes]) {
1982
+ if (this.pendingSelfEchoCreativeIds.get(clientId) !== streamCreativeId &&
1983
+ this.acknowledgedPendingSelfEchoes.has(clientId)) {
1984
+ this.releasePendingSelfEcho(clientId)
1985
+ }
1986
+ }
1987
+ }
1988
+
1989
+ // A successful response proves the request committed. A close before the
1990
+ // response means the matching broadcast was missed and can be retired; an
1991
+ // open popup keeps its id long enough to consume an echo still in flight,
1992
+ // without allowing it to override a later reopen snapshot.
1993
+ get acknowledgedPendingSelfEchoes() {
1994
+ return this.selfEchoState.acknowledgedIds
1995
+ }
1996
+
1997
+ acknowledgePendingSelfEcho(clientId) {
1998
+ if (this.pendingSelfEchoes.includes(clientId)) {
1999
+ this.possiblyMissedPendingSelfEchoes.delete(clientId)
2000
+ this.acknowledgedPendingSelfEchoes.add(clientId)
2001
+ }
2002
+ }
2003
+
2004
+ latestPendingSelfEchoTopicIdFor(creativeId, snapshotTopicId, acknowledgedSaveVersion, snapshotTopicRevision) {
2005
+ const streamCreativeId = String(creativeId)
2006
+ let topicId = snapshotTopicId
2007
+ let found = false
2008
+ const orderingClaimIds = [ ...this.pendingSelfEchoes, ...this.settledSelfEchoes ]
2009
+ const remainingClaimIds = new Set(orderingClaimIds)
2010
+
2011
+ // Saves are serialized, so each claim records the topic written by the
2012
+ // previous claim. A stale response can predate more than one completed
2013
+ // save; follow that chain instead of restoring only its first successor.
2014
+ // A claim acknowledged before this load began describes an older snapshot
2015
+ // and cannot advance it.
2016
+ for (;;) {
2017
+ const clientId = orderingClaimIds.find(id => {
2018
+ if (!remainingClaimIds.has(id)) return false
2019
+ const acknowledgedAfterLoadStarted =
2020
+ this.acknowledgedPendingSelfEchoes.has(id) &&
2021
+ this.pendingSelfEchoAcknowledgementVersions.get(id) > acknowledgedSaveVersion
2022
+ const revisionComparison = this.compareLastTopicRevisions(
2023
+ this.pendingSelfEchoRemoteRevisions.get(id),
2024
+ snapshotTopicRevision
2025
+ )
2026
+ return this.pendingSelfEchoCreativeIds.get(id) === streamCreativeId &&
2027
+ (!this.acknowledgedPendingSelfEchoes.has(id) || acknowledgedAfterLoadStarted) &&
2028
+ (revisionComparison === null
2029
+ ? this.pendingSelfEchoPreviousTopicIds.get(id) === topicId
2030
+ : revisionComparison > 0)
2031
+ })
2032
+ if (!clientId) return found ? topicId : undefined
2033
+
2034
+ found = true
2035
+ remainingClaimIds.delete(clientId)
2036
+ topicId = this.pendingSelfEchoTopicIds.get(clientId)
2037
+ }
2038
+ }
2039
+
2040
+ // A pick made before this replacement load normally outranks its answer: the
2041
+ // answer may simply predate the save. A claim that was in flight across a
2042
+ // close is the exception. When the snapshot has advanced from that save's
2043
+ // known baseline, the closed stream missed a newer cross-session write, so
2044
+ // replaying the local pick would immediately write the old topic back.
2045
+ pendingPickWasSupersededWhileClosed(creativeId, snapshotTopicId, snapshotTopicRevision) {
2046
+ if (!this._pendingPick) return false
2047
+
2048
+ const streamCreativeId = String(creativeId)
2049
+ return [ ...this.pendingSelfEchoes, ...this.settledSelfEchoes ].some(clientId => {
2050
+ if (!this.possiblyMissedPendingSelfEchoes.has(clientId) ||
2051
+ this.pendingSelfEchoCreativeIds.get(clientId) !== streamCreativeId ||
2052
+ this.pendingSelfEchoTopicIds.get(clientId) !== this._pendingPick.topicId) return false
2053
+
2054
+ const revisionComparison = this.compareLastTopicRevisions(
2055
+ snapshotTopicRevision,
2056
+ this.pendingSelfEchoRemoteRevisions.get(clientId)
2057
+ )
2058
+ return revisionComparison === null
2059
+ ? this.pendingSelfEchoPreviousTopicIds.get(clientId) !== snapshotTopicId
2060
+ : revisionComparison > 0
2061
+ })
2062
+ }
2063
+
2064
+ // A revisioned snapshot can only be compared safely once every local save
2065
+ // involved in that comparison has supplied its revision. Until then an ABA
2066
+ // snapshot can look like the predecessor of an in-flight save by topic id.
2067
+ hasUnacknowledgedRevisionedSaveFor(creativeId, snapshotTopicRevision) {
2068
+ if (!snapshotTopicRevision) return false
2069
+
2070
+ const streamCreativeId = String(creativeId)
2071
+ return this.pendingSelfEchoes.some(clientId =>
2072
+ this.pendingSelfEchoCreativeIds.get(clientId) === streamCreativeId &&
2073
+ !this.acknowledgedPendingSelfEchoes.has(clientId) &&
2074
+ !this.pendingSelfEchoRemoteRevisions.has(clientId)
2075
+ )
2076
+ }
2077
+
2078
+ get deferredLastTopicReconciliations() {
2079
+ return this.saveOrderState.deferredReconciliations
2080
+ }
2081
+
2082
+ retryDeferredLastTopicReconciliation(creativeId) {
2083
+ const streamCreativeId = String(creativeId)
2084
+ if (!this.deferredLastTopicReconciliations.has(streamCreativeId) ||
2085
+ String(this.effectiveCreativeId) !== streamCreativeId) return
2086
+
2087
+ this.deferredLastTopicReconciliations.delete(streamCreativeId)
2088
+ this.loadTopics()
2089
+ }
2090
+
2091
+ // Bumped for an individual stream when that stream is permanently gone. A
2092
+ // popup can temporarily subscribe to another creative, so invalidating that
2093
+ // subscription must not prevent a queued save for the original stream from
2094
+ // claiming its own echo when the user returns to it.
2095
+ subscriptionGenerationFor(creativeId) {
2096
+ return this.saveOrderState.subscriptionGenerationFor(creativeId)
2097
+ }
2098
+
2099
+ bumpSubscriptionGenerationFor(creativeId) {
2100
+ this.saveOrderState.bumpSubscriptionGeneration(creativeId)
2101
+ }
2102
+
2103
+ get subscriptionGenerations() {
2104
+ return this.saveOrderState.subscriptionGenerations
2105
+ }
2106
+
2107
+ // The legacy key is adopted only as a stand-in for a preference the server
2108
+ // does not hold yet. A winning empty pick or a revisioned cleared preference
2109
+ // is an All Messages selection — it just names no topic, so adopting the
2110
+ // legacy value would hand the user back a topic they did not ask for and
2111
+ // persist it. The caller knows whether the empty value is intentional.
2112
+ //
2113
+ // The key still goes either way: an intentional empty selection supersedes
2114
+ // it, so leaving it behind would only re-apply a value the user moved off.
2115
+ migrateLocalStorage({ keepEmptySelection = false } = {}) {
832
2116
  const key = `collavre_creative_${this.creativeId}_last_topic`
833
2117
  const localValue = localStorage.getItem(key)
834
- if (localValue && !this.serverLastTopicId) {
2118
+ if (localValue && !this.serverLastTopicId && !keepEmptySelection) {
835
2119
  this.serverLastTopicId = localValue
836
- saveLastTopic(this.creativeId, localValue)
2120
+ // The migration is a save like any other. Giving it a client id
2121
+ // prevents its broadcast from being mistaken for another session's
2122
+ // update if the user chooses a topic before that echo arrives.
2123
+ this.flushSaveLastTopic(localValue)
837
2124
  }
838
2125
  localStorage.removeItem(key)
839
2126
  }
840
2127
 
841
- subscribe() {
2128
+ subscribe({ preservePendingSelfEchoes = false } = {}) {
842
2129
  const creativeId = this.creativeId
843
2130
  if (!creativeId) return
844
2131
 
845
2132
  if (this.topicsSubscription && this.subscribedCreativeId === String(creativeId)) return
846
2133
 
847
- this.unsubscribe()
2134
+ if (this.topicsSubscription) this.unsubscribe({ preservePendingSelfEchoes })
848
2135
 
849
2136
  this.subscribedCreativeId = String(creativeId)
850
2137
  this.topicsSubscription = createSubscription(
851
2138
  { channel: 'TopicsChannel', creative_id: this.creativeId },
852
2139
  {
853
- received: (data) => this.handleTopicMessage(data)
2140
+ received: (data) => this.handleTopicMessage(data),
2141
+ disconnected: () => this.handleTopicsSubscriptionDisconnected(),
2142
+ // A refused subscription is different: it is not retried, so
2143
+ // nothing outstanding or queued on this stream can ever settle.
2144
+ // Claims for another creative may still settle if the popup returns.
2145
+ rejected: () => this.dropPendingSelfEchoesForCreative(creativeId),
854
2146
  }
855
2147
  )
856
2148
  }
857
2149
 
858
- unsubscribe() {
2150
+ dropPendingSelfEchoes() {
2151
+ const streamCreativeIds = new Set([
2152
+ ...this.pendingSelfEchoCreativeIds.values(),
2153
+ ...this.subscriptionGenerations.keys(),
2154
+ ])
2155
+ this.pendingSelfEchoes.length = 0
2156
+ this.pendingSelfEchoCreativeIds.clear()
2157
+ this.pendingSelfEchoTopicIds.clear()
2158
+ this.pendingSelfEchoPreviousTopicIds.clear()
2159
+ this.pendingSelfEchoAcknowledgementVersions.clear()
2160
+ this.pendingSelfEchoRemoteRevisions.clear()
2161
+ this.possiblyMissedPendingSelfEchoes.clear()
2162
+ this.possiblyMissedPendingSelfEchoesDuringDisconnect.clear()
2163
+ this.acknowledgedPendingSelfEchoes.clear()
2164
+ this.settledSelfEchoes.clear()
2165
+ this.retiredSelfEchoSequenceHighWaters.clear()
2166
+ // Emptying the array cannot reach a claim that has not been taken yet.
2167
+ // A save waiting its turn on the chain takes one when it runs, and by
2168
+ // then every stream has gone; its stream generation tells it so.
2169
+ for (const creativeId of streamCreativeIds) {
2170
+ this.bumpSubscriptionGenerationFor(creativeId)
2171
+ }
2172
+ }
2173
+
2174
+ dropPendingSelfEchoesForCreative(creativeId) {
2175
+ const streamCreativeId = String(creativeId)
2176
+ const clientIds = new Set([
2177
+ ...this.pendingSelfEchoes,
2178
+ ...this.settledSelfEchoes,
2179
+ ].filter(clientId => this.pendingSelfEchoCreativeIds.get(clientId) === streamCreativeId))
2180
+
2181
+ this.selfEchoState.pendingIds = this.pendingSelfEchoes.filter(clientId => !clientIds.has(clientId))
2182
+ for (const clientId of clientIds) this.discardSelfEchoMetadata(clientId)
2183
+ this.bumpSubscriptionGenerationFor(streamCreativeId)
2184
+ }
2185
+
2186
+ // A save can begin before a linked shell's topics response reveals that it
2187
+ // shares its origin's preference stream. Re-key that claim before pruning
2188
+ // so its identified echo remains recognisable on the resolved stream.
2189
+ remapPendingSelfEchoesForCreative(requestedCreativeId, effectiveCreativeId) {
2190
+ const requestedId = String(requestedCreativeId)
2191
+ const resolvedId = String(effectiveCreativeId)
2192
+ if (requestedId === resolvedId) return
2193
+ const requestedBaseline = this.lastKnownRemoteTopicIds.get(requestedId)
2194
+ if (requestedBaseline !== undefined) {
2195
+ if (!this.lastKnownRemoteTopicIds.has(resolvedId)) {
2196
+ this.lastKnownRemoteTopicIds.set(resolvedId, requestedBaseline)
2197
+ }
2198
+ this.lastKnownRemoteTopicIds.delete(requestedId)
2199
+ }
2200
+ const requestedRevision = this.highestLastTopicRevisions.get(requestedId)
2201
+ if (requestedRevision) {
2202
+ this.observeLastTopicRevision(resolvedId, requestedRevision)
2203
+ this.highestLastTopicRevisions.delete(requestedId)
2204
+ }
2205
+
2206
+ for (const clientId of [ ...this.pendingSelfEchoes, ...this.settledSelfEchoes ]) {
2207
+ if (this.pendingSelfEchoCreativeIds.get(clientId) === requestedId) {
2208
+ this.pendingSelfEchoCreativeIds.set(clientId, resolvedId)
2209
+ }
2210
+ }
2211
+ }
2212
+
2213
+ unsubscribe({ preservePendingSelfEchoes = false } = {}) {
859
2214
  if (this.topicsSubscription) {
860
2215
  this.topicsSubscription.unsubscribe()
861
2216
  this.topicsSubscription = null
862
2217
  }
863
2218
  this.subscribedCreativeId = null
2219
+ // The stream is per creative, so echoes still owed to us on the one we
2220
+ // are leaving are not coming and nothing can settle their claims.
2221
+ // Unlike a dropped connection, there is no reconnect to wait for.
2222
+ if (!preservePendingSelfEchoes) this.dropPendingSelfEchoes()
864
2223
  }
865
2224
 
866
2225
  handleTopicMessage(data) {
@@ -868,12 +2227,80 @@ export default class extends Controller {
868
2227
 
869
2228
  const action = data.action || "created"
870
2229
 
2230
+ if (action === "cron_changed" || data.cron_changed) {
2231
+ invalidateCreativeTree()
2232
+ this.loadTopics()
2233
+ return
2234
+ }
2235
+
871
2236
  if (action === "last_topic_changed") {
872
2237
  // Broadcast is already scoped to the current user via user-specific channel
873
2238
  const newTopicId = data.last_topic_id ? String(data.last_topic_id) : ""
874
- if (newTopicId !== this.serverLastTopicId) {
2239
+ const allMessages = data.last_topic_all_messages === true
2240
+ const lastTopicRevision = this.normalizeLastTopicRevision(data.last_topic_revision)
2241
+ // A retired ambiguous save remains non-actionable, but it can still have
2242
+ // committed after the request failed. Its revision must advance this
2243
+ // stream's high-water mark so an older in-flight GET cannot restore the
2244
+ // preference from before that save.
2245
+ if (!this.pendingSelfEchoes.includes(data.client_id) && this.isRetiredSelfEcho(data.client_id)) {
2246
+ this.observeLastTopicRevision(this.effectiveCreativeId, lastTopicRevision)
2247
+ return
2248
+ }
2249
+ // A linked shell can receive an echo before its load resolves the origin.
2250
+ // The claim already knows that effective stream, while effectiveCreativeId
2251
+ // still names the shell; advance the baseline on the claimed stream.
2252
+ const claimedEffectiveCreativeId = this.pendingSelfEchoCreativeIds.get(data.client_id) || this.effectiveCreativeId
2253
+ const isCurrentRevision = this.observeLastTopicRevision(
2254
+ claimedEffectiveCreativeId,
2255
+ lastTopicRevision
2256
+ )
2257
+ const consumedSelfEcho = this.consumeSelfEcho(data.client_id, lastTopicRevision)
2258
+ const orphanedSelfEcho = !consumedSelfEcho && this.isLastTopicSaveFromThisTab(data.client_id)
2259
+ const hasNewerPendingPick = this._pendingPick &&
2260
+ String(this.effectiveCreativeIdFor(this._pendingPick.creativeId)) === String(claimedEffectiveCreativeId)
2261
+ if (consumedSelfEcho || (orphanedSelfEcho && hasNewerPendingPick)) {
2262
+ if (isCurrentRevision) {
2263
+ this.setLastKnownRemoteTopicId(claimedEffectiveCreativeId, newTopicId)
2264
+ }
2265
+ this.retryDeferredLastTopicReconciliation(claimedEffectiveCreativeId)
2266
+ return
2267
+ }
2268
+ if (!isCurrentRevision) return
2269
+ this.setLastKnownRemoteTopicId(this.effectiveCreativeId, newTopicId)
2270
+ // A deep-link restore may have queued a write even when this broadcast
2271
+ // repeats the preference already in serverLastTopicId. The sibling
2272
+ // session still established that preference, so the queued one-shot link
2273
+ // must not write itself back over it.
2274
+ if (this.hasDeepLinkSelection) this.cancelPendingSaveLastTopic()
2275
+ const explicitSelectionChanged = allMessages !== this._explicitAllMessagesSelection
2276
+ this._explicitAllMessagesSelection = allMessages
2277
+ if (newTopicId !== this.serverLastTopicId || explicitSelectionChanged) {
875
2278
  this.serverLastTopicId = newTopicId
876
- this.selectTopic(newTopicId)
2279
+ // Another session moved the preference; nobody clicked in this
2280
+ // popup. A deep link outranks the preference in the getter, so
2281
+ // following the broadcast would light a chip the getter does not
2282
+ // name — and selectTopic() writes through the setter, which
2283
+ // releases that link on the way. It is a one-shot pointer with
2284
+ // nowhere to be recovered from: ?topic_id= is dropped from the
2285
+ // URL, so not even a reload gets the linked conversation back.
2286
+ // Record the preference, leave the view where the link put it.
2287
+ //
2288
+ // Every selection queues a save, restores included, so landing
2289
+ // on the link 500ms ago left one holding the linked topic. It
2290
+ // describes a selection this popup has just conceded is not the
2291
+ // preference; letting it land would write the link back over
2292
+ // what the other session set. Following the broadcast re-arms
2293
+ // the debounce with the broadcast's own value, so only the path
2294
+ // that does not follow has anything to cancel.
2295
+ if (!this.hasDeepLinkSelection) {
2296
+ // The save belonged to the controller Turbo replaced, not to a
2297
+ // new pick in this one. Reflect its committed preference without
2298
+ // creating another pending pick or writing it back to the server.
2299
+ this.selectTopic(
2300
+ newTopicId,
2301
+ orphanedSelfEcho ? { pick: false, persist: false } : undefined
2302
+ )
2303
+ }
877
2304
  }
878
2305
  return
879
2306
  }
@@ -889,6 +2316,12 @@ export default class extends Controller {
889
2316
  }
890
2317
 
891
2318
  if (action === "archived" || action === "unarchived") {
2319
+ // loadTopics() only refreshes archivedTopics when its fetch resolves,
2320
+ // and list_controller routes every incoming stream through
2321
+ // isArchivedTopic in the meantime. The broadcast already carries the
2322
+ // membership change, so apply it now rather than letting that window
2323
+ // route on the old answer.
2324
+ this.applyArchiveTransition(action, data.topic || { id: data.topic_id })
892
2325
  this.loadTopics()
893
2326
  return
894
2327
  }
@@ -909,7 +2342,16 @@ export default class extends Controller {
909
2342
  if (existsByName) return
910
2343
 
911
2344
  this.topics = [...topics, data.topic]
912
- this.renderTopics(this.topics, this.canManageTopics, this.canCreateTopic)
2345
+ // This arrived on the subscription for the creative currently open.
2346
+ // Unlike a local re-render of cached topics, it is not about the
2347
+ // outgoing creative whose strip may still be on screen during a switch.
2348
+ this.renderTopics(
2349
+ this.topics,
2350
+ this.canManageTopics,
2351
+ this.canCreateTopic,
2352
+ this.canSetPrimaryAgent,
2353
+ this.creativeId
2354
+ )
913
2355
 
914
2356
  // Auto-select the new topic if created by the current user
915
2357
  const currentUserId = document.body.dataset.currentUserId
@@ -937,7 +2379,7 @@ export default class extends Controller {
937
2379
  })
938
2380
 
939
2381
  this.topics = reorderedTopics
940
- this.renderTopics(this.topics, this.canManageTopics, this.canCreateTopic)
2382
+ this.renderTopics(this.topics, this.canManageTopics, this.canCreateTopic, this.canSetPrimaryAgent)
941
2383
  this.restoreSelection()
942
2384
  }
943
2385
 
@@ -947,58 +2389,55 @@ export default class extends Controller {
947
2389
  if (index === -1) return
948
2390
 
949
2391
  this.topics[index] = { ...this.topics[index], ...updatedTopic }
950
- this.renderTopics(this.topics, this.canManageTopics, this.canCreateTopic)
2392
+ this.renderTopics(this.topics, this.canManageTopics, this.canCreateTopic, this.canSetPrimaryAgent)
951
2393
  this.restoreSelection()
952
2394
  }
953
2395
 
954
2396
  removeTopic(topicId) {
955
- if (!topicId) return
2397
+ if (!topicId || reloadDeletedReservedTopic(this, topicId)) return
956
2398
 
2399
+ // loadTopics clears its cache before awaiting the response. If a
2400
+ // deletion arrives in that window, the local filter has nothing to
2401
+ // retain and the old response must not rebuild the deleted chip. A
2402
+ // replacement load both invalidates that response and refills the strip.
2403
+ const topicLoadInFlight = this.activeLoadAcknowledgementVersions.has(this._loadTopicsVersion)
957
2404
  const topics = this.topics || []
2405
+ const archivedTopics = this.archivedTopics || []
2406
+ const removedCurrentSelection = String(this.currentTopicId) === String(topicId)
2407
+ if (topicLoadInFlight) {
2408
+ if (removedCurrentSelection) {
2409
+ this.fallbackFromRemovedTopic(topicId)
2410
+ this.dispatch("change", { detail: { topicId: "", mainTopicId: this.mainTopicId } })
2411
+ }
2412
+ // The cache is intentionally incomplete while loadTopics awaits.
2413
+ // Restoring against it can replace a distinct preference hidden
2414
+ // behind the removed deep link with Main. Let the replacement
2415
+ // response provide the authoritative list before restoring.
2416
+ this.loadTopics()
2417
+ return
2418
+ }
958
2419
  const nextTopics = topics.filter((topic) => String(topic.id) !== String(topicId))
959
- if (nextTopics.length === topics.length) return
2420
+ // An archived topic is deletable and now selectable, so the "deleted"
2421
+ // broadcast has to reach this cache too — nothing else does. It is the
2422
+ // only removal path that runs without a loadTopics(), so a topic dropped
2423
+ // from here would keep an openable chip and, through pruneArchivedBadges
2424
+ // never running, a lit toggle for a conversation that no longer exists.
2425
+ const nextArchivedTopics = archivedTopics.filter((topic) => String(topic.id) !== String(topicId))
2426
+ if (nextTopics.length === topics.length && nextArchivedTopics.length === archivedTopics.length &&
2427
+ !removedCurrentSelection) return
960
2428
 
961
2429
  this.topics = nextTopics
962
- if (String(this.currentTopicId) === String(topicId)) {
963
- this.currentTopicId = ""
2430
+ this.archivedTopics = nextArchivedTopics
2431
+ this.pruneArchivedBadges()
2432
+ if (removedCurrentSelection) {
2433
+ this.fallbackFromRemovedTopic(topicId)
964
2434
  this.dispatch("change", { detail: { topicId: "", mainTopicId: this.mainTopicId } })
965
2435
  }
966
2436
 
967
- this.renderTopics(this.topics, this.canManageTopics, this.canCreateTopic)
2437
+ this.renderTopics(this.topics, this.canManageTopics, this.canCreateTopic, this.canSetPrimaryAgent)
968
2438
  this.restoreSelection()
969
2439
  }
970
2440
 
971
- handleAddButtonDragOver(event) {
972
- const isAgent = event.dataTransfer.types.includes('application/x-agent-drop')
973
- const isComment = event.dataTransfer.types.includes('application/x-comment-ids')
974
- if (!isAgent && !isComment) return
975
- event.preventDefault()
976
- event.dataTransfer.dropEffect = isAgent ? 'copy' : 'move'
977
- event.currentTarget.classList.add('drag-over')
978
- }
979
-
980
- async handleAddButtonDrop(event) {
981
- event.preventDefault()
982
- event.currentTarget.classList.remove('drag-over')
983
-
984
- // Handle comment drop → create new topic + move
985
- const commentIdsJson = event.dataTransfer.getData('application/x-comment-ids')
986
- if (commentIdsJson) {
987
- const commentIds = JSON.parse(commentIdsJson)
988
- if (commentIds && commentIds.length > 0) {
989
- await this.createTopicAndMoveComments(commentIds)
990
- }
991
- return
992
- }
993
-
994
- // Handle agent drop (existing logic)
995
- const agentJson = event.dataTransfer.getData('application/x-agent-drop')
996
- if (!agentJson) return
997
-
998
- const agent = JSON.parse(agentJson)
999
- await this.createTopicWithAgent(agent)
1000
- }
1001
-
1002
2441
  async createTopicAndMoveComments(commentIds, topicName = null) {
1003
2442
  if (!this.creativeId) return
1004
2443
 
@@ -1007,6 +2446,7 @@ export default class extends Controller {
1007
2446
 
1008
2447
  const result = await createTopicWithComments(this.creativeId, name, commentIds)
1009
2448
  if (result.ok) {
2449
+ this._topicScrollInterrupted = false
1010
2450
  this.currentTopicId = result.topic.id
1011
2451
  await this.flushSaveLastTopic(result.topic.id)
1012
2452
  await this.loadTopics()
@@ -1028,6 +2468,8 @@ export default class extends Controller {
1028
2468
  _i18n(key) {
1029
2469
  const translations = {
1030
2470
  set_agent_error: this.element.dataset.topicSetAgentError || 'Unable to assign the agent to this topic.',
2471
+ agent_assigned_title: this.element.dataset.topicAgentAssignedTitle || '%{name} is assigned to this topic — click to release',
2472
+ clear_agent_confirm: this.element.dataset.topicClearAgentConfirm || 'Release %{name} from this topic? Every agent will be able to respond here again.',
1031
2473
  create_error: this.element.dataset.topicCreateError || 'Unable to create the topic.',
1032
2474
  update_error: this.element.dataset.topicUpdateError || 'Unable to update the topic.',
1033
2475
  delete_error: this.element.dataset.topicDeleteError || 'Unable to delete the topic.',
@@ -1037,6 +2479,28 @@ export default class extends Controller {
1037
2479
  return translations[key] || key
1038
2480
  }
1039
2481
 
2482
+ // Clicking the avatar of an assigned agent releases the assignment. The avatar
2483
+ // sits inside the topic tag, so the click must not also fall through to
2484
+ // selecting that topic.
2485
+ async clearTopicPrimaryAgent(event) {
2486
+ event.preventDefault()
2487
+ event.stopPropagation()
2488
+
2489
+ const topicId = event.currentTarget.dataset.id
2490
+ if (!topicId) return
2491
+
2492
+ const topic = (this.topics || []).find(t => String(t.id) === String(topicId))
2493
+ const agentName = topic?.primary_agent?.name || ''
2494
+
2495
+ const confirmed = await confirmDialog(
2496
+ this._i18n('clear_agent_confirm').replace('%{name}', agentName)
2497
+ )
2498
+ if (!confirmed) return
2499
+
2500
+ await this.setTopicPrimaryAgent(topicId, null)
2501
+ }
2502
+
2503
+ // Pass agent === null to release the topic's assignment.
1040
2504
  async setTopicPrimaryAgent(topicId, agent) {
1041
2505
  if (!this.creativeId) return
1042
2506
 
@@ -1047,7 +2511,7 @@ export default class extends Controller {
1047
2511
  'Content-Type': 'application/json',
1048
2512
  'X-CSRF-Token': document.querySelector('meta[name="csrf-token"]').content
1049
2513
  },
1050
- body: JSON.stringify({ agent_id: agent.id })
2514
+ body: JSON.stringify({ agent_id: agent ? agent.id : null })
1051
2515
  })
1052
2516
 
1053
2517
  const data = await response.json().catch(() => ({}))
@@ -1087,21 +2551,40 @@ export default class extends Controller {
1087
2551
 
1088
2552
  if (response.ok) {
1089
2553
  const topic = await response.json()
2554
+ this._topicScrollInterrupted = false
1090
2555
  this.currentTopicId = topic.id
1091
2556
  await this.flushSaveLastTopic(topic.id)
1092
2557
  await this.loadTopics()
1093
2558
  this.dispatch("change", { detail: { topicId: topic.id, mainTopicId: this.mainTopicId } })
1094
2559
  } else {
1095
- console.error('Failed to create topic with agent')
2560
+ // Dropping an agent that has no feedback access here is now
2561
+ // refused (it would mute the topic), and that is a user mistake
2562
+ // with a fix — sharing the creative. A console line would leave
2563
+ // the drop looking like it silently did nothing.
2564
+ const data = await response.json().catch(() => ({}))
2565
+ const message = data.errors?.[0] || data.error
2566
+ console.error('Failed to create topic with agent', message)
2567
+ alertDialog(message || this._i18n('create_error'))
1096
2568
  }
1097
2569
  } catch (e) {
1098
2570
  console.error('Error creating topic with agent', e)
2571
+ alertDialog(this._i18n('create_error'))
1099
2572
  }
1100
2573
  }
1101
2574
 
1102
- renderAgentAvatar(agent) {
2575
+ // When topicId is given the avatar doubles as the release control: clicking it
2576
+ // unassigns the agent from the topic. Pass null to render it as a plain badge
2577
+ // (viewers who cannot manage topics).
2578
+ renderAgentAvatar(agent, topicId = null) {
1103
2579
  const size = 16
1104
- let html = `<span class="avatar-wrapper topic-agent-avatar-wrapper" style="width:${size}px;height:${size}px;" title="${this.escapeAttr(agent.name)}">`
2580
+ const releasable = topicId !== null && topicId !== undefined
2581
+ const title = releasable
2582
+ ? this._i18n('agent_assigned_title').replace('%{name}', agent.name)
2583
+ : agent.name
2584
+ const releaseAttrs = releasable
2585
+ ? ` data-action="click->comments--topics#clearTopicPrimaryAgent" data-id="${this.escapeAttr(String(topicId))}" role="button"`
2586
+ : ''
2587
+ let html = `<span class="avatar-wrapper topic-agent-avatar-wrapper${releasable ? ' topic-agent-avatar-releasable' : ''}"${releaseAttrs} style="width:${size}px;height:${size}px;" title="${this.escapeAttr(title)}">`
1105
2588
  html += `<img src="${this.escapeAttr(agent.avatar_url)}" alt="" width="${size}" height="${size}" class="topic-agent-avatar" style="border-radius:50%;vertical-align:middle;">`
1106
2589
  if (agent.default_avatar) {
1107
2590
  html += `<span class="avatar-initial">${this.escapeAttr(agent.initial)}</span>`