collavre 0.24.0 → 0.25.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 (440) hide show
  1. checksums.yaml +4 -4
  2. data/README.md +0 -1
  3. data/app/assets/stylesheets/collavre/comments_popup.css +165 -99
  4. data/app/assets/stylesheets/collavre/creatives.css +346 -37
  5. data/app/assets/stylesheets/collavre/desktop_setup.css +246 -0
  6. data/app/assets/stylesheets/collavre/gnb.css +64 -3
  7. data/app/assets/stylesheets/collavre/landing.css +108 -3
  8. data/app/assets/stylesheets/collavre/mention_menu.css +32 -0
  9. data/app/assets/stylesheets/collavre/popup.css +14 -0
  10. data/app/assets/stylesheets/collavre/print.css +0 -1
  11. data/app/assets/stylesheets/collavre/search_popup.css +1 -1
  12. data/app/assets/stylesheets/collavre/secret_fields.css +3 -0
  13. data/app/assets/stylesheets/collavre/workspace.css +307 -0
  14. data/app/channels/collavre/agent_channel.rb +14 -21
  15. data/app/channels/collavre/comments_presence_channel.rb +181 -21
  16. data/app/channels/collavre/inbox_badge_channel.rb +7 -1
  17. data/app/components/collavre/inbox/badge_component.rb +6 -13
  18. data/app/components/collavre/progress_filter_component.html.erb +2 -2
  19. data/app/components/collavre/progress_filter_component.rb +20 -0
  20. data/app/controllers/collavre/admin/settings_controller.rb +4 -1
  21. data/app/controllers/collavre/agent_connections_controller.rb +165 -0
  22. data/app/controllers/collavre/agent_gateways_controller.rb +132 -0
  23. data/app/controllers/collavre/agent_provisioning_controller.rb +79 -0
  24. data/app/controllers/collavre/api/v1/agents_controller.rb +45 -97
  25. data/app/controllers/collavre/application_controller.rb +13 -2
  26. data/app/controllers/collavre/comment_read_pointers_controller.rb +69 -40
  27. data/app/controllers/collavre/comments_controller.rb +45 -131
  28. data/app/controllers/collavre/concerns/shareable.rb +9 -3
  29. data/app/controllers/collavre/creatives_controller.rb +144 -11
  30. data/app/controllers/collavre/desktop_gateway_registrations_controller.rb +173 -0
  31. data/app/controllers/collavre/desktop_setup_controller.rb +119 -0
  32. data/app/controllers/collavre/desktop_sidecar_health_controller.rb +35 -0
  33. data/app/controllers/collavre/features_controller.rb +57 -0
  34. data/app/controllers/collavre/invites_controller.rb +12 -1
  35. data/app/controllers/collavre/llm_models_controller.rb +8 -0
  36. data/app/controllers/collavre/notices_controller.rb +20 -0
  37. data/app/controllers/collavre/tasks_controller.rb +40 -6
  38. data/app/controllers/collavre/topics_controller.rb +130 -53
  39. data/app/controllers/collavre/user_creative_preferences_controller.rb +214 -30
  40. data/app/controllers/concerns/collavre/comments/batch_operations.rb +15 -3
  41. data/app/controllers/concerns/collavre/comments/conversion.rb +1 -1
  42. data/app/controllers/concerns/collavre/users_controller/ai_user_management.rb +118 -8
  43. data/app/controllers/concerns/collavre/users_controller/profile_and_settings.rb +1 -15
  44. data/app/controllers/concerns/collavre/users_controller/registration.rb +2 -2
  45. data/app/errors/collavre/turn_deadline_error.rb +20 -0
  46. data/app/helpers/collavre/application_helper.rb +38 -0
  47. data/app/helpers/collavre/creatives_helper.rb +56 -22
  48. data/app/helpers/collavre/navigation_helper.rb +12 -0
  49. data/app/javascript/collavre.js +1 -2
  50. data/app/javascript/components/InlineLexicalEditor.jsx +30 -21
  51. data/app/javascript/components/__tests__/creative_tree_row_parent_id.test.js +32 -2
  52. data/app/javascript/components/__tests__/creative_tree_row_progress_toggle.test.js +185 -0
  53. data/app/javascript/components/creative_tree_row.js +62 -22
  54. data/app/javascript/controllers/__tests__/agent_connection_controller.test.js +195 -0
  55. data/app/javascript/controllers/__tests__/desktop_proxy_setup_controller.test.js +96 -0
  56. data/app/javascript/controllers/__tests__/index.test.js +42 -0
  57. data/app/javascript/controllers/__tests__/last_visited_creative_controller.test.js +103 -0
  58. data/app/javascript/controllers/__tests__/link_creative_controller.test.js +253 -2
  59. data/app/javascript/controllers/__tests__/progress_filter_controller.test.js +134 -0
  60. data/app/javascript/controllers/__tests__/search_popup_controller.test.js +310 -0
  61. data/app/javascript/controllers/__tests__/topic_list_controller.test.js +111 -0
  62. data/app/javascript/controllers/__tests__/workspace_tree_controller.test.js +1011 -0
  63. data/app/javascript/controllers/agent_connection_controller.js +357 -0
  64. data/app/javascript/controllers/agent_vendor_controller.js +23 -0
  65. data/app/javascript/controllers/comment_controller.js +3 -1
  66. data/app/javascript/controllers/comments/__tests__/feature_cards_controller.test.js +223 -0
  67. data/app/javascript/controllers/comments/__tests__/form_controller_default_placeholder.test.js +83 -0
  68. data/app/javascript/controllers/comments/__tests__/form_controller_draft.test.js +2069 -0
  69. data/app/javascript/controllers/comments/__tests__/form_controller_ime_send.test.js +324 -0
  70. data/app/javascript/controllers/comments/__tests__/form_controller_review.test.js +28 -2
  71. data/app/javascript/controllers/comments/__tests__/form_controller_search_submit.test.js +106 -0
  72. data/app/javascript/controllers/comments/__tests__/form_controller_stashed_draft.test.js +134 -0
  73. data/app/javascript/controllers/comments/__tests__/form_controller_stashed_draft_creative_switch.test.js +166 -0
  74. data/app/javascript/controllers/comments/__tests__/form_controller_stashed_draft_failure.test.js +183 -0
  75. data/app/javascript/controllers/comments/__tests__/list_controller_deep_link_topic.test.js +467 -0
  76. data/app/javascript/controllers/comments/__tests__/list_controller_docked.test.js +115 -0
  77. data/app/javascript/controllers/comments/__tests__/list_controller_prev_message.test.js +245 -0
  78. data/app/javascript/controllers/comments/__tests__/list_controller_read_pointer.test.js +276 -0
  79. data/app/javascript/controllers/comments/__tests__/list_controller_stream_archived.test.js +221 -0
  80. data/app/javascript/controllers/comments/__tests__/list_controller_stream_search.test.js +104 -0
  81. data/app/javascript/controllers/comments/__tests__/placeholder_controller.test.js +79 -0
  82. data/app/javascript/controllers/comments/__tests__/popup_controller.test.js +754 -1
  83. data/app/javascript/controllers/comments/__tests__/presence_controller.test.js +717 -15
  84. data/app/javascript/controllers/comments/__tests__/prev_message_navigator.test.js +129 -0
  85. data/app/javascript/controllers/comments/__tests__/topics_controller_action_errors.test.js +184 -0
  86. data/app/javascript/controllers/comments/__tests__/topics_controller_archived.test.js +879 -0
  87. data/app/javascript/controllers/comments/__tests__/topics_controller_creation_container.test.js +154 -0
  88. data/app/javascript/controllers/comments/__tests__/topics_controller_creation_scroll.test.js +92 -0
  89. data/app/javascript/controllers/comments/__tests__/topics_controller_delete.test.js +130 -0
  90. data/app/javascript/controllers/comments/__tests__/topics_controller_docked.test.js +32 -0
  91. data/app/javascript/controllers/comments/__tests__/topics_controller_last_topic_echo.test.js +1938 -0
  92. data/app/javascript/controllers/comments/__tests__/topics_controller_primary_agent.test.js +256 -0
  93. data/app/javascript/controllers/comments/__tests__/topics_controller_scroll.test.js +182 -0
  94. data/app/javascript/controllers/comments/__tests__/topics_controller_selection_race.test.js +981 -0
  95. data/app/javascript/controllers/comments/__tests__/topics_controller_topic_list.test.js +313 -0
  96. data/app/javascript/controllers/comments/feature_cards_controller.js +83 -0
  97. data/app/javascript/controllers/comments/form_controller.js +795 -14
  98. data/app/javascript/controllers/comments/list_controller.js +338 -52
  99. data/app/javascript/controllers/comments/placeholder_controller.js +30 -0
  100. data/app/javascript/controllers/comments/popup_controller.js +425 -83
  101. data/app/javascript/controllers/comments/presence_controller.js +317 -55
  102. data/app/javascript/controllers/comments/prev_message_navigator.js +94 -0
  103. data/app/javascript/controllers/comments/topics_controller.js +1772 -100
  104. data/app/javascript/controllers/common_popup_controller.js +2 -2
  105. data/app/javascript/controllers/creatives/__tests__/select_mode_controller.test.js +139 -0
  106. data/app/javascript/controllers/creatives/__tests__/tree_controller.test.js +605 -0
  107. data/app/javascript/controllers/creatives/__tests__/write_access_request_controller.test.js +125 -0
  108. data/app/javascript/controllers/creatives/select_mode_controller.js +7 -2
  109. data/app/javascript/controllers/creatives/tree_controller.js +140 -31
  110. data/app/javascript/controllers/creatives/write_access_request_controller.js +58 -0
  111. data/app/javascript/controllers/desktop_proxy_setup_controller.js +51 -0
  112. data/app/javascript/controllers/gateway_check_controller.js +36 -0
  113. data/app/javascript/controllers/index.js +25 -1
  114. data/app/javascript/controllers/last_visited_creative_controller.js +58 -0
  115. data/app/javascript/controllers/link_creative_controller.js +89 -18
  116. data/app/javascript/controllers/progress_filter_controller.js +12 -22
  117. data/app/javascript/controllers/search_popup_controller.js +64 -46
  118. data/app/javascript/controllers/share_user_search_controller.js +2 -2
  119. data/app/javascript/controllers/topic_list_controller.js +44 -7
  120. data/app/javascript/controllers/workspace_tree_controller.js +662 -0
  121. data/app/javascript/creatives/__tests__/tree_renderer.test.js +80 -0
  122. data/app/javascript/creatives/drag_drop/__tests__/drop_completion_empty_state.test.js +98 -0
  123. data/app/javascript/creatives/drag_drop/__tests__/topic_move_released_agent.test.js +125 -0
  124. data/app/javascript/creatives/drag_drop/event_handlers.js +12 -0
  125. data/app/javascript/creatives/tree_renderer.js +65 -22
  126. data/app/javascript/lib/__tests__/chat_drafts.test.js +1458 -0
  127. data/app/javascript/lib/__tests__/common_popup_bounds.test.js +8 -3
  128. data/app/javascript/lib/__tests__/common_popup_placement.test.js +374 -0
  129. data/app/javascript/lib/__tests__/common_popup_reshow.test.js +131 -0
  130. data/app/javascript/lib/__tests__/creative_link_prefetch.test.js +46 -0
  131. data/app/javascript/lib/__tests__/last_visited_creative.test.js +87 -0
  132. data/app/javascript/lib/__tests__/skill_html_entities.test.js +23 -0
  133. data/app/javascript/lib/__tests__/turbo_stream_actions.test.js +190 -0
  134. data/app/javascript/lib/api/__tests__/creatives.test.js +68 -0
  135. data/app/javascript/lib/api/__tests__/csrf_fetch.test.js +27 -0
  136. data/app/javascript/lib/api/__tests__/topics_save_last_topic.test.js +112 -0
  137. data/app/javascript/lib/api/creatives.js +32 -13
  138. data/app/javascript/lib/api/csrf_fetch.js +6 -4
  139. data/app/javascript/lib/api/topics.js +63 -5
  140. data/app/javascript/lib/chat_drafts.js +786 -0
  141. data/app/javascript/lib/common_popup.js +164 -25
  142. data/app/javascript/lib/creative_link_prefetch.js +27 -0
  143. data/app/javascript/lib/last_visited_creative.js +97 -0
  144. data/app/javascript/lib/lexical/__tests__/creative_link_node.test.js +162 -0
  145. data/app/javascript/lib/lexical/__tests__/creative_link_trigger.test.js +133 -0
  146. data/app/javascript/lib/lexical/__tests__/link_toolbar.test.js +62 -0
  147. data/app/javascript/lib/lexical/creative_link_node.js +101 -0
  148. data/app/javascript/lib/lexical/creative_link_trigger.js +98 -0
  149. data/app/javascript/lib/lexical/link_toolbar.js +23 -0
  150. data/app/javascript/lib/turbo_stream_actions.js +23 -16
  151. data/app/javascript/lib/utils/__tests__/filter_navigation.test.js +210 -0
  152. data/app/javascript/lib/utils/__tests__/markdown.test.js +44 -0
  153. data/app/javascript/lib/utils/filter_navigation.js +100 -0
  154. data/app/javascript/modules/__tests__/command_menu_creative_picker.test.js +62 -0
  155. data/app/javascript/modules/__tests__/command_menu_typeahead.test.js +267 -0
  156. data/app/javascript/modules/__tests__/creative_link_picker.test.js +85 -0
  157. data/app/javascript/modules/__tests__/creative_row_editor_archive.test.js +391 -0
  158. data/app/javascript/modules/__tests__/creative_row_editor_delegated_clicks.test.js +158 -0
  159. data/app/javascript/modules/__tests__/creative_row_editor_empty_state_recovery.test.js +519 -0
  160. data/app/javascript/modules/__tests__/creative_row_editor_empty_state_removal.test.js +346 -0
  161. data/app/javascript/modules/__tests__/creative_row_editor_session.test.js +144 -0
  162. data/app/javascript/modules/__tests__/creative_tree_dom.test.js +30 -0
  163. data/app/javascript/modules/__tests__/creative_tree_empty_state.test.js +186 -0
  164. data/app/javascript/modules/__tests__/dom_listener_registry.test.js +67 -0
  165. data/app/javascript/modules/__tests__/support/inline_editor_dom.js +159 -0
  166. data/app/javascript/modules/command_args_form.js +0 -12
  167. data/app/javascript/modules/command_menu.js +80 -38
  168. data/app/javascript/modules/creative_link_picker.js +56 -0
  169. data/app/javascript/modules/creative_row_editor.js +446 -243
  170. data/app/javascript/modules/creative_row_editor_delegated_clicks.js +87 -0
  171. data/app/javascript/modules/creative_tree_dom.js +4 -0
  172. data/app/javascript/modules/creative_tree_empty_state.js +80 -0
  173. data/app/javascript/modules/dom_listener_registry.js +23 -0
  174. data/app/javascript/modules/mention_menu.js +2 -3
  175. data/app/javascript/utils/__tests__/caret_anchor.test.js +75 -0
  176. data/app/javascript/utils/__tests__/chevron_icons.test.js +15 -0
  177. data/app/javascript/utils/caret_position.js +10 -0
  178. data/app/javascript/utils/chevron_icons.js +7 -0
  179. data/app/jobs/collavre/ai_agent_job.rb +262 -72
  180. data/app/jobs/collavre/cancel_offline_delegated_tasks_job.rb +11 -36
  181. data/app/jobs/collavre/comment_badges_broadcast_job.rb +28 -0
  182. data/app/jobs/collavre/comment_link_preview_job.rb +33 -0
  183. data/app/jobs/collavre/comment_notification_job.rb +14 -0
  184. data/app/jobs/collavre/comment_push_delivery_sweep_job.rb +17 -0
  185. data/app/jobs/collavre/compress_job.rb +33 -22
  186. data/app/jobs/collavre/creative_broadcast_job.rb +161 -48
  187. data/app/jobs/collavre/cron_action_job.rb +36 -18
  188. data/app/jobs/collavre/drop_trigger_job.rb +23 -9
  189. data/app/jobs/collavre/merge_comments_job.rb +33 -16
  190. data/app/jobs/collavre/push_notification_job.rb +62 -18
  191. data/app/jobs/collavre/restore_dropped_dispatches_job.rb +17 -0
  192. data/app/jobs/collavre/stuck_detector_job.rb +1 -1
  193. data/app/jobs/collavre/touch_creative_subtree_job.rb +14 -0
  194. data/app/models/collavre/agent_gateway.rb +200 -0
  195. data/app/models/collavre/agent_subscription.rb +4 -4
  196. data/app/models/collavre/agent_workspace.rb +210 -0
  197. data/app/models/collavre/comment/broadcastable.rb +22 -52
  198. data/app/models/collavre/comment/notifiable.rb +154 -77
  199. data/app/models/collavre/comment/topic_membership.rb +41 -0
  200. data/app/models/collavre/comment.rb +336 -31
  201. data/app/models/collavre/comment_notification_delivery.rb +61 -0
  202. data/app/models/collavre/comment_presence_store/cache_batches.rb +64 -0
  203. data/app/models/collavre/comment_presence_store.rb +272 -12
  204. data/app/models/collavre/comment_read_pointer.rb +9 -15
  205. data/app/models/collavre/creative/describable.rb +8 -2
  206. data/app/models/collavre/creative/permissible.rb +11 -0
  207. data/app/models/collavre/creative.rb +29 -4
  208. data/app/models/collavre/creative_share.rb +109 -4
  209. data/app/models/collavre/current.rb +1 -0
  210. data/app/models/collavre/llm_model.rb +62 -0
  211. data/app/models/collavre/system_setting.rb +12 -1
  212. data/app/models/collavre/task.rb +121 -2
  213. data/app/models/collavre/topic.rb +51 -0
  214. data/app/models/collavre/user.rb +101 -41
  215. data/app/models/collavre/user_creative_preference.rb +3 -1
  216. data/app/services/collavre/agent_provisioning/archive.rb +108 -0
  217. data/app/services/collavre/ai_agent/a2a_dispatcher.rb +16 -3
  218. data/app/services/collavre/ai_agent/agent_lifecycle_manager.rb +63 -6
  219. data/app/services/collavre/ai_agent/approval_handler.rb +12 -4
  220. data/app/services/collavre/ai_agent/claude_channel_adapter.rb +10 -5
  221. data/app/services/collavre/ai_agent/merged_trigger_comments.rb +164 -0
  222. data/app/services/collavre/ai_agent/message_builder.rb +103 -16
  223. data/app/services/collavre/ai_agent/session_provisioner.rb +3 -7
  224. data/app/services/collavre/ai_agent/task_claim_service.rb +29 -15
  225. data/app/services/collavre/ai_agent/task_reply_service.rb +67 -0
  226. data/app/services/collavre/ai_agent_service.rb +108 -20
  227. data/app/services/collavre/ai_client.rb +211 -21
  228. data/app/services/collavre/cli_proxy/client.rb +147 -0
  229. data/app/services/collavre/cli_proxy/endpoint_policy.rb +81 -0
  230. data/app/services/collavre/cli_proxy/identity.rb +47 -0
  231. data/app/services/collavre/cli_proxy/safe_net_http_adapter.rb +19 -0
  232. data/app/services/collavre/command_menu_service.rb +0 -10
  233. data/app/services/collavre/comment_move_service.rb +96 -7
  234. data/app/services/collavre/comment_snapshot_restore_service.rb +11 -5
  235. data/app/services/collavre/comments/action_executor.rb +48 -20
  236. data/app/services/collavre/comments/command_processor.rb +0 -1
  237. data/app/services/collavre/comments/list_response.rb +133 -0
  238. data/app/services/collavre/comments/read_pointer_writer.rb +210 -0
  239. data/app/services/collavre/comments/read_receipt_broadcaster.rb +157 -0
  240. data/app/services/collavre/comments/read_receipt_index.rb +152 -0
  241. data/app/services/collavre/comments/topic_command.rb +72 -1
  242. data/app/services/collavre/comments/topic_mutation.rb +20 -0
  243. data/app/services/collavre/creatives/breadcrumb_resolver.rb +1 -1
  244. data/app/services/collavre/creatives/comment_badge_index.rb +299 -27
  245. data/app/services/collavre/creatives/reorderer.rb +15 -3
  246. data/app/services/collavre/creatives/tree_builder.rb +1 -1
  247. data/app/services/collavre/creatives/tree_formatter.rb +5 -6
  248. data/app/services/collavre/creatives/workspace_path_resolver.rb +50 -0
  249. data/app/services/collavre/creatives/workspace_tree_builder.rb +92 -0
  250. data/app/services/collavre/crons/recurring_topic_tasks.rb +23 -0
  251. data/app/services/collavre/home_page_path.rb +55 -0
  252. data/app/services/collavre/html_text.rb +64 -0
  253. data/app/services/collavre/http_client.rb +11 -2
  254. data/app/services/collavre/inbox_reply_service.rb +1 -1
  255. data/app/services/collavre/markdown_converter.rb +13 -1
  256. data/app/services/collavre/orchestration/agent_orchestrator.rb +776 -81
  257. data/app/services/collavre/orchestration/arbiter.rb +48 -5
  258. data/app/services/collavre/orchestration/deferred_trigger_scope.rb +53 -0
  259. data/app/services/collavre/orchestration/delivery_record.rb +792 -0
  260. data/app/services/collavre/orchestration/loop_breaker.rb +10 -4
  261. data/app/services/collavre/orchestration/matcher.rb +132 -17
  262. data/app/services/collavre/orchestration/policy_resolver.rb +58 -10
  263. data/app/services/collavre/orchestration/scheduler.rb +10 -4
  264. data/app/services/collavre/orchestration/scheduling_hooks.rb +10 -0
  265. data/app/services/collavre/orchestration/selection.rb +43 -0
  266. data/app/services/collavre/orchestration/stuck_detector.rb +25 -112
  267. data/app/services/collavre/orchestration/task_coalescer.rb +355 -0
  268. data/app/services/collavre/orchestration/topic_slot.rb +73 -0
  269. data/app/services/collavre/system_events/context_builder.rb +60 -11
  270. data/app/services/collavre/system_events/dispatcher.rb +58 -12
  271. data/app/services/collavre/system_events/envelope.rb +73 -0
  272. data/app/services/collavre/system_events/vocabulary.rb +45 -0
  273. data/app/services/collavre/tools/creative_retrieval_service.rb +1 -1
  274. data/app/services/collavre/tools/cron_create_service.rb +32 -18
  275. data/app/services/collavre/tools/id_list.rb +38 -0
  276. data/app/services/collavre/tools/topic_authorizer.rb +61 -7
  277. data/app/services/collavre/tools/topic_branch_service.rb +85 -0
  278. data/app/services/collavre/tools/topic_create_service.rb +117 -0
  279. data/app/services/collavre/tools/topic_list_service.rb +101 -0
  280. data/app/services/collavre/tools/topic_message_create_service.rb +192 -0
  281. data/app/services/collavre/tools/topic_messages_service.rb +346 -0
  282. data/app/services/collavre/tools/topic_move_service.rb +108 -0
  283. data/app/services/collavre/tools/topic_selection.rb +59 -0
  284. data/app/services/collavre/tools/topic_update_service.rb +165 -0
  285. data/app/services/collavre/topic_branch_service.rb +39 -10
  286. data/app/services/collavre/topics/agent_resolver.rb +87 -0
  287. data/app/services/collavre/topics/char_budget.rb +70 -0
  288. data/app/services/collavre/topics/last_topic_preference_payload.rb +18 -0
  289. data/app/services/collavre/topics/message_page.rb +380 -0
  290. data/app/services/collavre/topics/message_page_markdown.rb +102 -0
  291. data/app/services/collavre/topics/message_scope.rb +61 -0
  292. data/app/services/collavre/topics/message_stats.rb +92 -0
  293. data/app/services/collavre/topics/move_blocker.rb +47 -0
  294. data/app/services/collavre/topics/next_name.rb +35 -0
  295. data/app/services/collavre/topics/pin_rejection.rb +25 -0
  296. data/app/services/collavre/topics/read_pointer_relocator.rb +71 -0
  297. data/app/services/collavre/topics/reserved_name.rb +18 -0
  298. data/app/services/collavre/topics/serializer.rb +92 -0
  299. data/app/services/collavre/topics/topic_destroy.rb +30 -0
  300. data/app/services/collavre/topics/topic_move.rb +80 -0
  301. data/app/services/collavre/topics/topic_move_effects.rb +35 -0
  302. data/app/services/collavre/topics/topic_mutation.rb +27 -0
  303. data/app/views/collavre/admin/integrations/_setting_row.html.erb +5 -8
  304. data/app/views/collavre/admin/settings/_system_tab.html.erb +7 -0
  305. data/app/views/collavre/agent_connections/show.html.erb +77 -0
  306. data/app/views/collavre/agent_gateways/_form.html.erb +71 -0
  307. data/app/views/collavre/agent_gateways/edit.html.erb +2 -0
  308. data/app/views/collavre/agent_gateways/index.html.erb +54 -0
  309. data/app/views/collavre/agent_gateways/new.html.erb +2 -0
  310. data/app/views/collavre/comments/_comments_popup.html.erb +32 -17
  311. data/app/views/collavre/comments/_empty_state.html.erb +33 -0
  312. data/app/views/collavre/comments/_empty_state_minimal.html.erb +7 -0
  313. data/app/views/collavre/comments/_feature_card.html.erb +35 -0
  314. data/app/views/collavre/comments/_list.html.erb +3 -2
  315. data/app/views/collavre/comments/_no_search_results.html.erb +3 -0
  316. data/app/views/collavre/creatives/_add_button.html.erb +17 -19
  317. data/app/views/collavre/creatives/_empty_state.html.erb +109 -0
  318. data/app/views/collavre/creatives/_inline_edit_form.html.erb +5 -5
  319. data/app/views/collavre/creatives/_tree_loading_placeholder.html.erb +16 -0
  320. data/app/views/collavre/creatives/_workspace_tree.html.erb +33 -0
  321. data/app/views/collavre/creatives/index.html.erb +79 -18
  322. data/app/views/collavre/desktop_setup/show.html.erb +114 -0
  323. data/app/views/collavre/features/index.html.erb +42 -0
  324. data/app/views/collavre/features/show.html.erb +52 -0
  325. data/app/views/collavre/invitation_mailer/invite.html.erb +1 -1
  326. data/app/views/collavre/invitation_mailer/invite.text.erb +1 -1
  327. data/app/views/collavre/invites/show.html.erb +14 -1
  328. data/app/views/collavre/landing/show.html.erb +5 -1
  329. data/app/views/collavre/shared/_link_creative_modal.html.erb +4 -1
  330. data/app/views/collavre/shared/navigation/_help_button.html.erb +3 -1
  331. data/app/views/collavre/shared/navigation/_panels.html.erb +1 -8
  332. data/app/views/collavre/shared/navigation/_search_form.html.erb +13 -2
  333. data/app/views/collavre/user_themes/index.html.erb +1 -1
  334. data/app/views/collavre/users/_llm_fields.html.erb +65 -0
  335. data/app/views/collavre/users/_org_chart_node.html.erb +1 -1
  336. data/app/views/collavre/users/edit_ai.html.erb +33 -31
  337. data/app/views/collavre/users/new.html.erb +4 -2
  338. data/app/views/collavre/users/new_ai.html.erb +14 -32
  339. data/app/views/collavre/users/show.html.erb +13 -1
  340. data/app/views/layouts/collavre/landing.html.erb +9 -4
  341. data/config/initializers/ruby_llm_openai_reasoning_content.rb +77 -0
  342. data/config/locales/admin.en.yml +3 -1
  343. data/config/locales/admin.ko.yml +3 -1
  344. data/config/locales/agent_gateway.en.yml +217 -0
  345. data/config/locales/agent_gateway.ko.yml +217 -0
  346. data/config/locales/ai_agent.en.yml +0 -1
  347. data/config/locales/ai_agent.ko.yml +0 -1
  348. data/config/locales/comments.en.yml +72 -30
  349. data/config/locales/comments.ko.yml +72 -30
  350. data/config/locales/creatives.en.yml +32 -1
  351. data/config/locales/creatives.ko.yml +32 -1
  352. data/config/locales/features.en.yml +140 -0
  353. data/config/locales/features.ko.yml +140 -0
  354. data/config/locales/invites.en.yml +3 -0
  355. data/config/locales/invites.ko.yml +3 -0
  356. data/config/locales/landing.en.yml +2 -1
  357. data/config/locales/landing.ko.yml +2 -1
  358. data/config/locales/tools.en.yml +20 -0
  359. data/config/locales/tools.ko.yml +20 -0
  360. data/config/locales/users.en.yml +15 -14
  361. data/config/locales/users.ko.yml +14 -14
  362. data/config/routes.rb +45 -19
  363. data/db/migrate/20250911084338_backfill_creative_in_comment_inbox_items.rb +9 -1
  364. data/db/migrate/20260724000000_add_creative_id_index_to_comments.rb +34 -0
  365. data/db/migrate/20260724000001_add_creative_private_id_index_to_comments.rb +50 -0
  366. data/db/migrate/20260724090000_add_async_comment_notification_state.rb +64 -0
  367. data/db/migrate/20260727000000_add_waiting_notice_scope_to_comments.rb +30 -0
  368. data/db/migrate/20260727010000_add_waiting_notice_scope_to_tasks.rb +26 -0
  369. data/db/migrate/20260805000000_add_creative_workspace_enabled_to_users.rb +5 -0
  370. data/db/migrate/20260807050000_add_dismissed_notices_to_users.rb +5 -0
  371. data/db/migrate/20260809000000_change_creative_workspace_enabled_default_to_true.rb +18 -0
  372. data/db/migrate/20260809000001_create_llm_models.rb +64 -0
  373. data/db/migrate/20260809000002_create_agent_gateways_and_workspaces.rb +35 -0
  374. data/db/migrate/20260809000003_hash_agent_workspace_callback_tokens.rb +44 -0
  375. data/db/migrate/20260809000004_encrypt_agent_workspace_manifest_tokens.rb +59 -0
  376. data/db/migrate/20260810000000_split_agent_workspace_identity_axes.rb +58 -0
  377. data/db/migrate/20260810000001_seed_codex_custom_proxy_llm_models.rb +28 -0
  378. data/db/migrate/20260810010000_add_last_visited_creative_to_users.rb +8 -0
  379. data/db/migrate/20260810020000_add_last_visited_creative_at_to_users.rb +5 -0
  380. data/db/migrate/20260810030000_add_last_visited_creative_navigation_order_to_users.rb +6 -0
  381. data/db/migrate/20260810060000_add_last_visited_creative_issued_sequence_to_users.rb +5 -0
  382. data/db/migrate/20260810100000_add_desktop_managed_to_agent_gateways.rb +40 -0
  383. data/db/migrate/20260810100001_add_desktop_preset_adapter_to_users.rb +38 -0
  384. data/db/migrate/20260811000000_make_agent_gateway_completion_key_nullable.rb +7 -0
  385. data/db/migrate/20260812000000_remove_workflow_columns_from_tasks.rb +101 -0
  386. data/db/migrate/20260812000001_remove_android_devices.rb +24 -0
  387. data/db/migrate/20260812010000_drop_inbox_items.rb +22 -0
  388. data/db/migrate/20260813000000_clear_claude_channel_presence_routing_expressions.rb +16 -0
  389. data/db/migrate/20260813000001_add_last_topic_revision_to_user_creative_preferences.rb +5 -0
  390. data/db/migrate/20260813000002_add_last_topic_save_order_to_user_creative_preferences.rb +6 -0
  391. data/db/migrate/20260813000003_add_last_topic_save_sequences_to_user_creative_preferences.rb +5 -0
  392. data/db/migrate/20260813000004_add_last_topic_save_fences_to_user_creative_preferences.rb +6 -0
  393. data/db/migrate/20260814000000_add_topic_to_comment_read_pointers.rb +79 -0
  394. data/db/migrate/20260814000001_add_creative_topic_private_id_index_to_comments.rb +37 -0
  395. data/db/migrate/20260816000000_add_watermark_index_to_comment_read_pointers.rb +27 -0
  396. data/db/migrate/20260816000001_add_private_recipient_topic_index_to_comments.rb +48 -0
  397. data/db/migrate/20260820000000_add_topic_assigned_at_to_comments.rb +13 -0
  398. data/db/seeds.rb +1 -51
  399. data/lib/collavre/engine.rb +108 -1
  400. data/lib/collavre/feature_card_registry.rb +168 -0
  401. data/lib/collavre/hashed_access_token_lookup.rb +22 -0
  402. data/lib/collavre/sensitive_request_silencer.rb +23 -0
  403. data/lib/collavre/user_extensions.rb +0 -2
  404. data/lib/collavre/version.rb +1 -1
  405. data/lib/collavre.rb +1 -0
  406. data/skills/collavre/SKILL.md +165 -0
  407. data/skills/collavre/package.json +8 -0
  408. data/skills/collavre/references/tool-reference.md +347 -0
  409. data/skills/collavre/scripts/collavre +634 -0
  410. data/skills/collavre/scripts/html_entities.js +24 -0
  411. metadata +228 -30
  412. data/app/controllers/collavre/api/v1/mobile/agent_events_controller.rb +0 -224
  413. data/app/controllers/collavre/api/v1/mobile/base_controller.rb +0 -95
  414. data/app/controllers/collavre/api/v1/mobile/devices_controller.rb +0 -31
  415. data/app/controllers/collavre/api/v1/mobile/voice_commands_controller.rb +0 -25
  416. data/app/controllers/collavre/inbox_items_controller.rb +0 -70
  417. data/app/controllers/collavre/typo_corrections_controller.rb +0 -39
  418. data/app/javascript/lib/__tests__/typo_correction.test.js +0 -192
  419. data/app/javascript/lib/typo_correction.js +0 -146
  420. data/app/javascript/modules/__tests__/typo_corrector.test.js +0 -365
  421. data/app/javascript/modules/creative_guide.js +0 -67
  422. data/app/javascript/modules/typo_corrector.js +0 -534
  423. data/app/jobs/collavre/inbox_summary_job.rb +0 -24
  424. data/app/mailers/collavre/inbox_mailer.rb +0 -19
  425. data/app/models/collavre/inbox_item.rb +0 -89
  426. data/app/services/collavre/comments/concerns/workflow_support.rb +0 -115
  427. data/app/services/collavre/comments/work_command.rb +0 -161
  428. data/app/services/collavre/comments/workflow_executor.rb +0 -276
  429. data/app/services/collavre/gemini_parent_recommender.rb +0 -77
  430. data/app/services/collavre/mobile/event_summarizer.rb +0 -40
  431. data/app/services/collavre/typo_corrector.rb +0 -188
  432. data/app/views/collavre/inbox_items/_item.html.erb +0 -18
  433. data/app/views/collavre/inbox_items/_items.html.erb +0 -3
  434. data/app/views/collavre/inbox_items/_list.html.erb +0 -7
  435. data/app/views/collavre/inbox_items/index.html.erb +0 -1
  436. data/app/views/collavre/inbox_mailer/daily_summary.html.erb +0 -11
  437. data/app/views/collavre/inbox_mailer/daily_summary.text.erb +0 -8
  438. data/app/views/collavre/users/typo_correction.html.erb +0 -50
  439. data/config/locales/mobile.en.yml +0 -16
  440. data/config/locales/mobile.ko.yml +0 -16
@@ -3,12 +3,15 @@ import apiQueue from '../lib/api/queue_manager'
3
3
  import { $getSelection } from 'lexical'
4
4
  import { isSelectionAtDocumentStart, isSelectionAtDocumentEnd } from '../lib/lexical/selection_boundary'
5
5
  import { createInlineEditor } from './lexical_inline_editor'
6
+ import { markdownCreativeCommandRange, openCreativeLinkPicker } from './creative_link_picker'
6
7
  import { renderCreativeTree, dispatchCreativeTreeUpdated } from '../creatives/tree_renderer'
7
8
  import { isProgressComplete, progressBaselineValueFrom, progressValueChangedFrom } from './creative_progress'
8
9
  import { renderMarkdown } from '../lib/utils/markdown'
9
10
  import { reconcileMarkdownSource } from './markdown_source_reconcile'
10
11
  import { isHtmlEmpty } from './html_content_empty'
11
12
  import { CreativeSaveQueue } from './creative_save_queue'
13
+ import { createListenerRegistry } from './dom_listener_registry'
14
+ import { createDelegatedClickHandler } from './creative_row_editor_delegated_clicks'
12
15
  import { confirmDialog, alertDialog } from '../lib/utils/dialog'
13
16
  import { serverErrorMessage } from '../lib/api/api_error'
14
17
  import yaml from 'js-yaml'
@@ -42,12 +45,42 @@ import {
42
45
  updateRowFromData,
43
46
  inlinePayloadFromTree,
44
47
  } from './creative_inline_payload'
48
+ import { hideTreeEmptyState } from './creative_tree_empty_state'
45
49
  // Import Stimulus application from the global window (set by host app)
46
50
  const application = window.Stimulus
47
51
 
48
52
  let initialized = false;
49
- let creativeEditClickHandler = null;
50
- let addCreativeShortcutHandler = null;
53
+ // The template node the current editor session was built against. Workspace
54
+ // frame swaps replace the template without firing turbo:load, so the session
55
+ // must be rebuilt whenever a different template node is in the document.
56
+ let activeTemplate = null;
57
+ let destroyActiveEditor = null;
58
+ // Frame-only swaps rebuild the session (see initializeCreativeRowEditor)
59
+ // without the outgoing session ever calling hideCurrent()/move(), so the
60
+ // editing ping interval it may have started has no other path to stop.
61
+ let stopActiveEditingPing = null;
62
+ const globalListeners = createListenerRegistry();
63
+
64
+ function teardownEditorSession() {
65
+ globalListeners.releaseAll();
66
+ if (stopActiveEditingPing) {
67
+ try {
68
+ stopActiveEditingPing();
69
+ } catch (e) {
70
+ console.error('CreativeRowEditor: Failed to stop editing ping', e);
71
+ }
72
+ stopActiveEditingPing = null;
73
+ }
74
+ if (destroyActiveEditor) {
75
+ try {
76
+ destroyActiveEditor();
77
+ } catch (e) {
78
+ console.error('CreativeRowEditor: Failed to destroy inline editor', e);
79
+ }
80
+ destroyActiveEditor = null;
81
+ }
82
+ activeTemplate = null;
83
+ }
51
84
 
52
85
  function deleteAttachment(signedId) {
53
86
  if (!signedId) return;
@@ -61,17 +94,27 @@ function deleteAttachment(signedId) {
61
94
  }
62
95
 
63
96
  export function initializeCreativeRowEditor() {
97
+ // Rebuild the session on every call: the Stimulus wrapper controller
98
+ // reconnects whenever the workspace center frame swaps its content, which
99
+ // is the only lifecycle signal for non-promoted frame navigations.
100
+ setupEditorSession();
64
101
  if (initialized) return;
65
102
  initialized = true;
66
103
 
67
- document.addEventListener('turbo:load', function () {
104
+ document.addEventListener('turbo:load', setupEditorSession);
105
+ }
106
+
107
+ function setupEditorSession() {
68
108
  const template = document.getElementById('inline-edit-form');
109
+ if (template && template === activeTemplate) return;
110
+ teardownEditorSession();
69
111
  if (!template) return;
112
+ activeTemplate = template;
70
113
 
71
114
  initializeEventListeners();
72
115
 
73
116
  // Listen for attachment deletions from queue manager
74
- window.addEventListener('api-queue-attachments-deleted', (event) => {
117
+ globalListeners.add(window, 'api-queue-attachments-deleted', (event) => {
75
118
  const attachmentIds = event.detail?.attachmentIds;
76
119
  if (attachmentIds && attachmentIds.length > 0) {
77
120
  attachmentIds.forEach(deleteAttachment);
@@ -79,7 +122,7 @@ export function initializeCreativeRowEditor() {
79
122
  });
80
123
 
81
124
  // Listen for failed requests to prevent silent data loss
82
- window.addEventListener('api-queue-request-failed', (event) => {
125
+ globalListeners.add(window, 'api-queue-request-failed', (event) => {
83
126
  const { item, error } = event.detail;
84
127
  console.error('Queue request failed permanently:', item, error);
85
128
 
@@ -147,8 +190,6 @@ export function initializeCreativeRowEditor() {
147
190
  const unlinkBtn = document.getElementById('inline-unlink');
148
191
  const unconvertBtn = document.getElementById('inline-unconvert');
149
192
  const closeBtn = document.getElementById('inline-close');
150
- const parentSuggestions = document.getElementById('parent-suggestions');
151
- const parentSuggestBtn = document.getElementById('inline-recommend-parent');
152
193
  const methodInput = document.getElementById('inline-method');
153
194
  const parentInput = document.getElementById('inline-parent-id');
154
195
  const beforeInput = document.getElementById('inline-before-id');
@@ -181,6 +222,9 @@ export function initializeCreativeRowEditor() {
181
222
  onEnterKey: handleEditorEnterKey,
182
223
  onUploadStateChange: handleUploadStateChange
183
224
  });
225
+ destroyActiveEditor = () => {
226
+ if (lexicalEditor && typeof lexicalEditor.destroy === 'function') lexicalEditor.destroy();
227
+ };
184
228
  } catch (e) {
185
229
  console.error('CreativeRowEditor: Failed to create inline editor', e);
186
230
  }
@@ -211,6 +255,11 @@ export function initializeCreativeRowEditor() {
211
255
  let uploadCompletionPromise = null;
212
256
  let resolveUploadCompletion = null;
213
257
  let addNewInProgress = false;
258
+ // hideCurrent() clears currentTree and hides the shared form before its
259
+ // close save settles. Without a separate transition guard, that temporary
260
+ // "no editor" state lets another row or Add reuse the form while the old
261
+ // save still owns its completion and recovery callbacks.
262
+ let closeSaveInProgress = false;
214
263
  let originalContent = '';
215
264
  let originalProgress = 0;
216
265
  let originalOriginId = '';
@@ -225,8 +274,38 @@ export function initializeCreativeRowEditor() {
225
274
  }
226
275
  }
227
276
 
277
+ // Announces that a creative is being edited and keeps re-announcing it: the
278
+ // sync controller expires the lock when the pings stop, so a single event
279
+ // is not enough. Every path that puts the editor on a persisted row must go
280
+ // through this.
281
+ function startEditingPresence(creativeId) {
282
+ const parsedId = parseInt(creativeId, 10);
283
+ if (Number.isNaN(parsedId)) return;
284
+ const announce = () => document.dispatchEvent(new CustomEvent('creative-editing:start', {
285
+ detail: { creativeId: parsedId }
286
+ }));
287
+ announce();
288
+ stopEditingPing();
289
+ editingPingInterval = setInterval(announce, 3000);
290
+ }
291
+
228
292
  // Clean up editing ping on Turbo navigation to prevent interval leak
229
- document.addEventListener('turbo:before-cache', () => stopEditingPing());
293
+ globalListeners.add(document, 'turbo:before-cache', () => stopEditingPing());
294
+
295
+ // Registered with the module-level teardown so a workspace frame swap —
296
+ // which rebuilds the session without ever calling hideCurrent()/move() on
297
+ // the outgoing one — still stops this session's ping and reports the
298
+ // creative it was pinging for as no longer being edited.
299
+ stopActiveEditingPing = () => {
300
+ if (!editingPingInterval) return;
301
+ const editCreativeId = form.dataset.creativeId;
302
+ stopEditingPing();
303
+ if (editCreativeId) {
304
+ document.dispatchEvent(new CustomEvent('creative-editing:stop', {
305
+ detail: { creativeId: parseInt(editCreativeId, 10) }
306
+ }));
307
+ }
308
+ };
230
309
 
231
310
  const destroyedCreativeIds = new Set();
232
311
 
@@ -265,10 +344,16 @@ export function initializeCreativeRowEditor() {
265
344
  }
266
345
  }
267
346
 
347
+ // The server's answer, carried on the row by TreeBuilder's `has_children`. It is
348
+ // set whether or not the children have been fetched, so it is the only reliable
349
+ // source for a collapsed node — its children container is rendered empty with
350
+ // `data-loaded="false"` until the user expands it.
351
+ function rowFlagHasChildren(row) {
352
+ return !!(row && (row.hasChildren || row.getAttribute?.('has-children')));
353
+ }
354
+
268
355
  function currentRowHasChildren() {
269
- const row = currentRowElement || (currentTree ? treeRowElement(currentTree) : null);
270
- if (!row) return false;
271
- return !!(row.hasChildren || row.getAttribute?.('has-children'));
356
+ return rowFlagHasChildren(currentRowElement || (currentTree ? treeRowElement(currentTree) : null));
272
357
  }
273
358
 
274
359
  function activateMarkdownMode(source) {
@@ -540,13 +625,20 @@ export function initializeCreativeRowEditor() {
540
625
 
541
626
  async function handleEditButtonClick(tree) {
542
627
  if (!tree) return;
628
+ // Do not let a second session take over the shared form while an earlier
629
+ // close still owns it. The initiating switch continues below after its
630
+ // own hideCurrent() resolves; only later, competing clicks are ignored.
631
+ if (closeSaveInProgress) return;
543
632
 
544
633
  if (currentTree === tree) {
545
634
  await hideCurrent();
546
635
  return;
547
636
  }
548
637
  if (currentTree) {
549
- await hideCurrent(false);
638
+ // A failed save keeps the editor on the outgoing row with the draft the
639
+ // server rejected; loadCreative() below would replace the shared form
640
+ // buffer and destroy it, so the switch is abandoned instead.
641
+ if (await hideCurrent(false, { switching: true }) === SAVE_FAILED) return;
550
642
  }
551
643
  currentTree = tree;
552
644
  currentRowElement = treeRowElement(tree);
@@ -559,128 +651,36 @@ export function initializeCreativeRowEditor() {
559
651
  updateActionButtonStates();
560
652
 
561
653
  // Notify sync controller that editing started + periodic ping
562
- const editCreativeId = form.dataset.creativeId || currentRowElement?.getAttribute('creative-id');
563
- if (editCreativeId) {
564
- const parsedId = parseInt(editCreativeId, 10);
565
- document.dispatchEvent(new CustomEvent('creative-editing:start', {
566
- detail: { creativeId: parsedId }
567
- }));
568
- if (editingPingInterval) clearInterval(editingPingInterval);
569
- editingPingInterval = setInterval(() => {
570
- document.dispatchEvent(new CustomEvent('creative-editing:start', {
571
- detail: { creativeId: parsedId }
572
- }));
573
- }, 3000);
574
- }
654
+ startEditingPresence(form.dataset.creativeId || currentRowElement?.getAttribute('creative-id'));
575
655
  }
576
656
 
577
657
  function initializeEventListeners() {
578
- if (!creativeEditClickHandler) {
579
- creativeEditClickHandler = function (e) {
580
- const tree = e.detail?.treeElement || e.detail?.button?.closest('.creative-tree');
581
- if (!tree) return;
582
- e.preventDefault();
583
- handleEditButtonClick(tree);
584
- };
585
- document.addEventListener('creative-edit-click', creativeEditClickHandler);
586
- }
587
-
588
- if (!addCreativeShortcutHandler) {
589
- addCreativeShortcutHandler = function (event) {
590
- if (event.defaultPrevented || event.isComposing) return;
591
- if (event.key !== 'Enter' || event.altKey || event.ctrlKey || event.metaKey || event.shiftKey) return;
592
- const target = event.target;
593
- const interactiveSelector = 'input, textarea, select, button, a, [contenteditable="true"], [data-lexical-editor-root]';
594
- if (target && target.closest && target.closest(interactiveSelector)) return;
595
- if (target && target.isContentEditable) return;
596
- const addButton = document.querySelector('.creative-actions-row .add-creative-btn, .creative-actions-row .new-root-creative-btn');
597
- if (!addButton) return;
598
- event.preventDefault();
599
- addButton.click();
600
- };
601
- document.addEventListener('keydown', addCreativeShortcutHandler);
602
- }
603
-
604
- document.body.addEventListener('click', function (e) {
605
- // Delegated event for .edit-inline-btn
606
- const editBtn = e.target.closest('.edit-inline-btn');
607
- if (editBtn) {
608
- e.preventDefault();
609
- const tree = editBtn.closest('.creative-tree');
610
- if (!tree) return;
611
- handleEditButtonClick(tree);
612
- return; // Event handled
613
- }
614
-
615
- // Delegated event for .add-creative-btn
616
- const addBtn = e.target.closest('.add-creative-btn:not(#inline-add):not(#inline-level-down):not(#inline-level-up)');
617
- if (addBtn) {
618
- e.preventDefault();
619
- if (template.style.display === 'block') {
620
- hideCurrent();
621
- return;
622
- }
623
- const tree = addBtn.closest('.creative-tree');
624
- let parentId, container, insertBefore, beforeId = '';
625
- if (tree) {
626
- parentId = tree.dataset.id;
627
- container = tree.querySelector('.creative-children');
628
- if (!container) {
629
- container = document.createElement('div');
630
- container.className = 'creative-children';
631
- container.id = 'creative-children-' + parentId;
632
- tree.appendChild(container);
633
- }
634
- insertBefore = container.firstElementChild;
635
- beforeId = insertBefore ? creativeIdFrom(insertBefore) : '';
636
- } else {
637
- parentId = addBtn.dataset.parentId || '';
638
- const rootContainer = document.getElementById('creatives');
639
- container = rootContainer;
640
- insertBefore = rootContainer.firstElementChild;
641
- beforeId = insertBefore ? creativeIdFrom(insertBefore) : '';
642
- }
643
- startNew(parentId, container, insertBefore, beforeId);
644
- return; // Event handled
645
- }
646
-
647
-
648
- // Delegated event for .new-root-creative-btn
649
- const newRootBtn = e.target.closest('.new-root-creative-btn');
650
- if (newRootBtn) {
651
- e.preventDefault();
652
- const container = document.getElementById('creatives');
653
- if (!container) return;
654
-
655
- if (template.style.display === 'block') {
656
- hideCurrent();
657
- return;
658
- }
659
- const insertBefore = container.firstElementChild;
660
- const beforeId = insertBefore ? creativeIdFrom(insertBefore) : '';
661
- startNew('', container, insertBefore, beforeId);
662
- return; // Event handled
663
- }
658
+ globalListeners.add(document, 'creative-edit-click', function (event) {
659
+ const tree = event.detail?.treeElement || event.detail?.button?.closest('.creative-tree');
660
+ if (!tree) return;
661
+ event.preventDefault();
662
+ handleEditButtonClick(tree);
663
+ });
664
664
 
665
- // Delegated event for .append-parent-btn
666
- const appendParentBtn = e.target.closest('.append-parent-btn');
667
- if (appendParentBtn) {
668
- e.preventDefault();
669
- const targetId = appendParentBtn.dataset.childId;
670
- const target = document.getElementById('creative-' + targetId);
671
- if (!target) return;
672
- const container = target.parentNode;
673
- startNew(
674
- container.id.startsWith('creative-children-') ? container.id.replace('creative-children-', '') : '',
675
- container,
676
- target,
677
- targetId,
678
- '',
679
- targetId
680
- );
681
- return; // Event handled
682
- }
665
+ globalListeners.add(document, 'keydown', function (event) {
666
+ if (event.defaultPrevented || event.isComposing) return;
667
+ if (event.key !== 'Enter' || event.altKey || event.ctrlKey || event.metaKey || event.shiftKey) return;
668
+ const target = event.target;
669
+ const interactiveSelector = 'input, textarea, select, button, a, [contenteditable="true"], [data-lexical-editor-root]';
670
+ if (target && target.closest && target.closest(interactiveSelector)) return;
671
+ if (target && target.isContentEditable) return;
672
+ const addButton = document.querySelector('.creative-actions-row .add-creative-btn, .creative-actions-row .new-root-creative-btn');
673
+ if (!addButton) return;
674
+ event.preventDefault();
675
+ addButton.click();
683
676
  });
677
+
678
+ globalListeners.add(document.body, 'click', createDelegatedClickHandler({
679
+ template,
680
+ startNew,
681
+ hideCurrent,
682
+ handleEditButtonClick,
683
+ }));
684
684
  }
685
685
 
686
686
  function hideRow(tree) {
@@ -912,7 +912,28 @@ export function initializeCreativeRowEditor() {
912
912
  });
913
913
  }
914
914
 
915
- function hideCurrent(event) {
915
+ // The save request resolves with the raw Response (see creativesApi.save),
916
+ // so an HTTP error arrives on the *fulfilled* path with `ok === false` — it
917
+ // is just as much a failure as a rejection. Everything else that reaches
918
+ // here is a success: performSave returns null for empty content and
919
+ // finalizeHide substitutes Promise.resolve() when no save was needed, both
920
+ // of which settle as undefined.
921
+ function isFailedSaveResult(result) {
922
+ return !!result && typeof result === 'object' && result.ok === false;
923
+ }
924
+
925
+ // Resolved by hideCurrent() when the flush-on-close save failed and the
926
+ // editor was left open on the outgoing row with the user's draft.
927
+ const SAVE_FAILED = 'save-failed';
928
+
929
+ // `switching` marks the calls that immediately open another row: the caller
930
+ // reassigns currentTree and moves the shared template as soon as the
931
+ // returned promise settles. It is deliberately a separate option rather
932
+ // than another meaning for the `event === false` argument, which only
933
+ // suppresses preventDefault(). Those callers MUST abort when hideCurrent
934
+ // resolves with SAVE_FAILED — the editor is still bound to the outgoing row
935
+ // holding the unsaved draft, and switching anyway would overwrite it.
936
+ function hideCurrent(event, { switching = false } = {}) {
916
937
  if (event?.preventDefault) {
917
938
  event.preventDefault();
918
939
  }
@@ -920,24 +941,87 @@ export function initializeCreativeRowEditor() {
920
941
  const tree = currentTree;
921
942
  const parentId = parentInput.value;
922
943
  const wasNew = !form.dataset.creativeId;
944
+ closeSaveInProgress = true;
923
945
 
924
- // Notify sync controller that editing stopped
925
- stopEditingPing();
926
946
  const editCreativeId = form.dataset.creativeId;
927
- document.dispatchEvent(new CustomEvent('creative-editing:stop', {
928
- detail: { creativeId: editCreativeId ? parseInt(editCreativeId, 10) : null }
929
- }));
947
+
948
+ // Announcing "editing stopped" is what releases the row to everything
949
+ // that defers work while it is being edited — the sync controller's lock,
950
+ // and the tree controller, which holds a pending reload and drains it into
951
+ // a 300ms debounce on this event. So it must not be said until the row is
952
+ // genuinely released, which is only once the flush below has succeeded.
953
+ // Saying it up front (as this used to) handed out the all-clear while the
954
+ // editor still held the user's text: a save slower than that debounce let
955
+ // the deferred reload replace the whole container, taking the row and the
956
+ // editor attached inside it out of the document, and
957
+ // recoverFromFailedSave() then re-attached the editor to a detached row.
958
+ // On failure it is never announced at all — the editor stays open on the
959
+ // row, so presence was never interrupted and there is nothing to restore.
960
+ const releaseEditingPresence = function () {
961
+ stopEditingPing();
962
+ document.dispatchEvent(new CustomEvent('creative-editing:stop', {
963
+ detail: { creativeId: editCreativeId ? parseInt(editCreativeId, 10) : null }
964
+ }));
965
+ };
930
966
 
931
967
  currentTree = null;
932
968
  currentRowElement = null;
933
969
  tree.draggable = true;
934
970
  updateActionButtonStates();
935
971
 
972
+ // A failed save leaves the editor hidden and currentTree cleared, so the
973
+ // DOM has to be reconciled here. The buffer in the editor is the user's
974
+ // only copy of what they typed — the server rejected it, and for an
975
+ // existing row loadCreative() would overwrite the buffer with the stored
976
+ // copy the moment another row is opened. Losing it would also be silent,
977
+ // because saveForm's own 'error' status is gated on `tree === currentTree`
978
+ // (already null by now) and creativesApi.save calls csrfFetch directly,
979
+ // bypassing the api queue whose 'api-queue-request-failed' listener is
980
+ // what normally alerts the user. So the draft is always kept: the editor
981
+ // is re-bound to the row it was typed in, whether or not that row was ever
982
+ // persisted, and the save is re-armed so the next close retries it.
983
+ const recoverFromFailedSave = function () {
984
+ currentTree = tree;
985
+ currentRowElement = treeRowElement(tree) || currentRowElement;
986
+ tree.draggable = false;
987
+ attachTemplate(tree);
988
+ template.style.display = 'block';
989
+ // The rendered row stays hidden underneath, as it is while editing —
990
+ // the editor is visible on top of it, so nothing is blank. The
991
+ // empty-state card likewise stays hidden: the row still exists.
992
+ hideRow(tree);
993
+ isDirty = true;
994
+ pendingSave = true;
995
+ setSaveStatus('error');
996
+ updateActionButtonStates();
997
+ // Nothing to do about presence here: releaseEditingPresence() is only
998
+ // called on the success path, so the ping never stopped and the row was
999
+ // never announced as free. That also covers a never-persisted draft,
1000
+ // which has no id to re-announce with.
1001
+
1002
+ if (switching) {
1003
+ // The caller was about to open another row; it aborts on this result,
1004
+ // so the editor keeps the draft. Without an alert that click would
1005
+ // look like it did nothing, so say why out loud. The localized string
1006
+ // is carried on the form's data-* attribute (set in the ERB) because
1007
+ // plain JS can't call the i18n `t()` helper.
1008
+ const message = form.dataset.saveFailedMessage;
1009
+ if (message) alertDialog(message);
1010
+ }
1011
+ };
1012
+
936
1013
  const finalizeHide = function () {
937
1014
  template.style.display = 'none';
938
1015
  const p = (pendingSave || saveQueue.saving) ? saveForm(tree, parentId) : Promise.resolve();
939
- return p.then(() => {
1016
+ return p.then((result) => {
1017
+ if (isFailedSaveResult(result)) {
1018
+ recoverFromFailedSave();
1019
+ return SAVE_FAILED;
1020
+ }
1021
+ releaseEditingPresence();
940
1022
  if (wasNew && !form.dataset.creativeId) {
1023
+ // removeTreeElement() restores the placeholder when this leaves the
1024
+ // tree empty — see creative_tree_dom.js.
941
1025
  removeTreeElement(tree);
942
1026
  } else if (!tree.querySelector('.creative-row')) {
943
1027
  const parentTree = parentId ? document.getElementById(`creative-${parentId}`) : null;
@@ -948,14 +1032,39 @@ export function initializeCreativeRowEditor() {
948
1032
  showRow(tree);
949
1033
  refreshRow(tree);
950
1034
  }
1035
+ }, () => {
1036
+ // Rethrowing here would only strand an unhandled rejection: the
1037
+ // callers that must react to a failed save read the resolved value
1038
+ // instead, and the rest are fire-and-forget.
1039
+ recoverFromFailedSave();
1040
+ return SAVE_FAILED;
951
1041
  });
952
1042
  };
953
1043
 
954
- if (uploadsPending) {
955
- return waitForUploads().then(finalizeHide);
956
- }
1044
+ const closePromise = uploadsPending ? waitForUploads().then(finalizeHide) : finalizeHide();
1045
+ return Promise.resolve(closePromise).finally(() => { closeSaveInProgress = false; });
1046
+ }
957
1047
 
958
- return finalizeHide();
1048
+ // Tears the session down for a row that is already gone from the DOM, so
1049
+ // hideCurrent() is not usable: its flush would try to save — and then
1050
+ // re-show and refresh — a detached row. The archive handler has always
1051
+ // called this, but it was never defined anywhere in the module, so
1052
+ // archiving threw a ReferenceError inside its .then() and silently left the
1053
+ // editor bound to the removed row.
1054
+ function closeEditor() {
1055
+ isDirty = false;
1056
+ pendingSave = null;
1057
+ stopEditingPing();
1058
+ const editCreativeId = form.dataset.creativeId;
1059
+ if (editCreativeId) {
1060
+ document.dispatchEvent(new CustomEvent('creative-editing:stop', {
1061
+ detail: { creativeId: parseInt(editCreativeId, 10) }
1062
+ }));
1063
+ }
1064
+ currentTree = null;
1065
+ currentRowElement = null;
1066
+ template.style.display = 'none';
1067
+ updateActionButtonStates();
959
1068
  }
960
1069
 
961
1070
  function loadCreative(tree) {
@@ -1254,19 +1363,7 @@ export function initializeCreativeRowEditor() {
1254
1363
  loadCreative(target);
1255
1364
  focusAfterMove();
1256
1365
  // Notify editing started on new creative + start ping
1257
- const newCreativeId = target.dataset?.id || currentRowElement?.getAttribute('creative-id');
1258
- if (newCreativeId) {
1259
- const parsedNewId = parseInt(newCreativeId, 10);
1260
- document.dispatchEvent(new CustomEvent('creative-editing:start', {
1261
- detail: { creativeId: parsedNewId }
1262
- }));
1263
- stopEditingPing();
1264
- editingPingInterval = setInterval(() => {
1265
- document.dispatchEvent(new CustomEvent('creative-editing:start', {
1266
- detail: { creativeId: parsedNewId }
1267
- }));
1268
- }, 3000);
1269
- }
1366
+ startEditingPresence(target.dataset?.id || currentRowElement?.getAttribute('creative-id'));
1270
1367
  });
1271
1368
  } else {
1272
1369
  // For existing creatives, show the row and refresh if needed
@@ -1276,19 +1373,7 @@ export function initializeCreativeRowEditor() {
1276
1373
  loadCreative(target);
1277
1374
  focusAfterMove();
1278
1375
  // Notify editing started on new creative + start ping
1279
- const newCreativeId = target.dataset?.id || currentRowElement?.getAttribute('creative-id');
1280
- if (newCreativeId) {
1281
- const parsedNewId = parseInt(newCreativeId, 10);
1282
- document.dispatchEvent(new CustomEvent('creative-editing:start', {
1283
- detail: { creativeId: parsedNewId }
1284
- }));
1285
- stopEditingPing();
1286
- editingPingInterval = setInterval(() => {
1287
- document.dispatchEvent(new CustomEvent('creative-editing:start', {
1288
- detail: { creativeId: parsedNewId }
1289
- }));
1290
- }, 3000);
1291
- }
1376
+ startEditingPresence(target.dataset?.id || currentRowElement?.getAttribute('creative-id'));
1292
1377
  }
1293
1378
  updateActionButtonStates();
1294
1379
  }
@@ -1317,14 +1402,14 @@ export function initializeCreativeRowEditor() {
1317
1402
  }
1318
1403
  }
1319
1404
 
1320
- // Notify editing stopped on previous creative
1321
- stopEditingPing();
1322
- const prevEditId = prev.dataset?.id || form.dataset?.creativeId;
1323
- if (prevEditId) {
1324
- document.dispatchEvent(new CustomEvent('creative-editing:stop', {
1325
- detail: { creativeId: parseInt(prevEditId, 10) }
1326
- }));
1327
- }
1405
+ // Editing is NOT announced as stopped here. Both branches below end in
1406
+ // startNew(), which flushes the previous row through hideCurrent() and
1407
+ // announces the stop itself once that flush succeeds. Doing it here as
1408
+ // well released the row while the flush was still in flight — the same
1409
+ // window that let a deferred tree reload delete the open editor — and,
1410
+ // for a row that had never been persisted, said nothing at all because
1411
+ // there was no id to report. addChild() has always relied on hideCurrent()
1412
+ // for this.
1328
1413
 
1329
1414
  const handleAddNew = () => {
1330
1415
  const prevCreativeId = prev.dataset.id;
@@ -1486,6 +1571,52 @@ export function initializeCreativeRowEditor() {
1486
1571
  updateActionButtonStates();
1487
1572
  }
1488
1573
 
1574
+ // Mirrors move(1)'s own lookup, so "would move(1) actually move?" is answered
1575
+ // by the same question move() asks rather than by a list captured earlier.
1576
+ function hasNextTree(tree) {
1577
+ const trees = Array.from(document.querySelectorAll('.creative-tree'));
1578
+ const index = trees.indexOf(tree);
1579
+ return index !== -1 && !!trees[index + 1];
1580
+ }
1581
+
1582
+ // Root-level equivalent of refreshChildren(parentTree): the server is the only
1583
+ // place that knows what the root tree looks like now, so ask the tree controller
1584
+ // to refetch it. Returns false when the controller is not reachable, leaving the
1585
+ // caller's DOM as-is.
1586
+ //
1587
+ // Looks `window.Stimulus` up on each call rather than using the module-level
1588
+ // `application`, which is captured at import time and so is undefined whenever
1589
+ // this module is loaded before the host app starts Stimulus. The archive handler
1590
+ // resolves its controller the same way.
1591
+ //
1592
+ // requestReload(), not load(): a reload replaces the whole container, so it
1593
+ // detaches whichever row the editor is currently sitting on together with the
1594
+ // unsaved draft in it. The controller knows whether a row is being edited and
1595
+ // holds the refetch until it is not.
1596
+ function creativeTreeController() {
1597
+ const container = document.getElementById('creatives');
1598
+ if (!container) return null;
1599
+ return window.Stimulus?.getControllerForElementAndIdentifier?.(container, 'creatives--tree') || null;
1600
+ }
1601
+
1602
+ function reloadCreativeTree() {
1603
+ const controller = creativeTreeController();
1604
+ if (typeof controller?.requestReload !== 'function') return false;
1605
+ controller.requestReload();
1606
+ return true;
1607
+ }
1608
+
1609
+ // A successful close releases any pending tree reload, but archive still has
1610
+ // to land before that reload is safe: otherwise it can render the pre-archive
1611
+ // server state and replace the row reference the response handler later removes.
1612
+ function holdCreativeTreeReload() {
1613
+ const controller = creativeTreeController();
1614
+ if (typeof controller?.beginReloadHold !== 'function' ||
1615
+ typeof controller?.endReloadHold !== 'function') return function () {};
1616
+ controller.beginReloadHold();
1617
+ return function () { controller.endReloadHold(); };
1618
+ }
1619
+
1489
1620
  function deleteCurrent(withChildren) {
1490
1621
  if (!currentTree || !form.dataset.creativeId) return;
1491
1622
  const id = form.dataset.creativeId;
@@ -1520,6 +1651,25 @@ export function initializeCreativeRowEditor() {
1520
1651
  }));
1521
1652
  const parentTree = parentId ? document.getElementById(`creative-${parentId}`) : null;
1522
1653
  const childrenTree = document.getElementById("creative-children-" + id)
1654
+ // "Delete only this" does not delete the children: DestroyService#reparent_children
1655
+ // promotes them to the deleted creative's parent. When there is a parent row we
1656
+ // refetch it below and the promoted children come back under it. When there is
1657
+ // not — a top-level creative — they are promoted to the root, and the only copy
1658
+ // of them in the DOM is inside the children container we are about to drop. That
1659
+ // would leave the tree looking empty, and hand restoreTreeEmptyState() an empty
1660
+ // container to put the "no creatives yet" card into, while the server still holds
1661
+ // the promoted rows. Refetch the root tree instead.
1662
+ //
1663
+ // Whether there are children to promote is the server's answer, carried on
1664
+ // the row's `has-children` flag — not "does the DOM hold a child row". A
1665
+ // collapsed node gets a children container that TreeBuilder marks
1666
+ // `loaded: false` and leaves empty until the user expands it, so asking the
1667
+ // container would say "no children" for every tree the user never opened.
1668
+ // The container is still consulted as well, because a child inserted
1669
+ // client-side is in the DOM before any flag round-trips.
1670
+ const promotesChildrenToRoot = !withChildren && !parentTree &&
1671
+ (rowFlagHasChildren(treeRowElement(tree)) ||
1672
+ !!childrenTree?.querySelector('creative-tree-row'));
1523
1673
  if (!withChildren && childrenTree && parentTree) {
1524
1674
  refreshChildren(parentTree).then(() => {
1525
1675
  if (parentTree) refreshRow(parentTree);
@@ -1530,8 +1680,22 @@ export function initializeCreativeRowEditor() {
1530
1680
  // Clear dirty state so move() doesn't try to save the just-deleted creative
1531
1681
  isDirty = false;
1532
1682
  pendingSave = null;
1533
- move(1);
1683
+ // move(1) is a no-op when the deleted row was the last one: it bails on the
1684
+ // missing target and leaves currentTree pointing at the row we are about to
1685
+ // detach, with the inline template still attached to it and still displayed.
1686
+ // The next Add click would then see display === 'block', read it as "close the
1687
+ // open editor" and flush a save/refresh for a creative that no longer exists —
1688
+ // so the restored CTA would need two clicks to create anything. Close the
1689
+ // editor outright, as the archive path already does.
1690
+ if (hasNextTree(tree)) {
1691
+ move(1);
1692
+ } else {
1693
+ closeEditor();
1694
+ }
1695
+ // removeTreeElement() restores the empty-state placeholder if this leaves the
1696
+ // tree with no rows (creative_tree_dom.js).
1534
1697
  removeTreeElement(tree);
1698
+ if (promotesChildrenToRoot) reloadCreativeTree();
1535
1699
  });
1536
1700
  }
1537
1701
 
@@ -1557,6 +1721,10 @@ export function initializeCreativeRowEditor() {
1557
1721
  }
1558
1722
 
1559
1723
  function startNew(parentId, container, insertBefore, beforeId = '', afterId = '', childId = '') {
1724
+ // The close save still owns the shared form and may need to recover it on
1725
+ // failure. Starting a new row here would replace that buffer and let the
1726
+ // stale completion mutate the newer session.
1727
+ if (closeSaveInProgress) return;
1560
1728
  resetOriginTracking();
1561
1729
  const performStart = () => {
1562
1730
  let targetContainer = container || document.getElementById('creatives');
@@ -1613,6 +1781,8 @@ export function initializeCreativeRowEditor() {
1613
1781
  } else {
1614
1782
  targetContainer.appendChild(rowComponent);
1615
1783
  }
1784
+ // A row now occupies the tree — the "no sub-creatives" placeholder must go.
1785
+ hideTreeEmptyState();
1616
1786
 
1617
1787
  const finalizeSetup = () => {
1618
1788
  const newTree = rowComponent.querySelector('.creative-tree');
@@ -1658,10 +1828,6 @@ export function initializeCreativeRowEditor() {
1658
1828
  document.dispatchEvent(new CustomEvent('creative-editing:start', {
1659
1829
  detail: { creativeId: null }
1660
1830
  }));
1661
- if (parentSuggestions) {
1662
- parentSuggestions.style.display = 'none';
1663
- parentSuggestions.innerHTML = '';
1664
- }
1665
1831
  };
1666
1832
 
1667
1833
  if (rowComponent.updateComplete) {
@@ -1672,7 +1838,10 @@ export function initializeCreativeRowEditor() {
1672
1838
  };
1673
1839
 
1674
1840
  if (currentTree) {
1675
- return Promise.resolve(hideCurrent(false)).then(performStart);
1841
+ // Same as handleEditButtonClick: don't strand the rejected draft by
1842
+ // moving the editor onto a brand-new row.
1843
+ return Promise.resolve(hideCurrent(false, { switching: true }))
1844
+ .then((result) => (result === SAVE_FAILED ? undefined : performStart()));
1676
1845
  }
1677
1846
 
1678
1847
  return performStart();
@@ -1721,6 +1890,9 @@ export function initializeCreativeRowEditor() {
1721
1890
  markdownPreviewTimer = setTimeout(() => {
1722
1891
  if (markdownPreview) markdownPreview.innerHTML = renderMarkdown(md);
1723
1892
  }, 300);
1893
+
1894
+ const triggerRange = markdownCreativeCommandRange(md, markdownTextarea.selectionStart);
1895
+ if (triggerRange) openCreativeLinkPicker(markdownTextarea, { triggerRange });
1724
1896
  }
1725
1897
 
1726
1898
  // Intercepts Shift+Enter via capture-phase keydown on Lexical's root element.
@@ -1814,54 +1986,6 @@ export function initializeCreativeRowEditor() {
1814
1986
  });
1815
1987
  }
1816
1988
 
1817
- if (parentSuggestBtn && parentSuggestions) {
1818
- parentSuggestBtn.addEventListener('click', function () {
1819
- const originalLabel = parentSuggestBtn.textContent;
1820
- parentSuggestBtn.disabled = true;
1821
- parentSuggestBtn.textContent = `${originalLabel}...`;
1822
- parentSuggestions.innerHTML = '<option>...</option>';
1823
- parentSuggestions.style.display = 'block';
1824
-
1825
- saveForm()
1826
- .then(function () {
1827
- const id = form.dataset.creativeId;
1828
- if (!id) {
1829
- parentSuggestions.style.display = 'none';
1830
- return;
1831
- }
1832
- return creativesApi.parentSuggestions(id).then(function (data) {
1833
- parentSuggestions.innerHTML = '';
1834
- if (data && data.length) {
1835
- data.forEach(function (s) {
1836
- const opt = document.createElement('option');
1837
- opt.value = s.id;
1838
- opt.textContent = s.path;
1839
- parentSuggestions.appendChild(opt);
1840
- });
1841
- parentSuggestions.style.display = 'block';
1842
- } else {
1843
- parentSuggestions.style.display = 'none';
1844
- }
1845
- });
1846
- })
1847
- .finally(function () {
1848
- parentSuggestBtn.textContent = originalLabel;
1849
- parentSuggestBtn.disabled = false;
1850
- });
1851
- });
1852
- }
1853
-
1854
- if (parentSuggestions) {
1855
- parentSuggestions.addEventListener('change', function () {
1856
- if (!this.value) return;
1857
- parentInput.value = this.value;
1858
- const targetId = this.value;
1859
- saveForm().then(function () {
1860
- window.location.href = `/creatives/${targetId}`;
1861
- });
1862
- });
1863
- }
1864
-
1865
1989
  if (closeBtn) {
1866
1990
  closeBtn.addEventListener('click', hideCurrent);
1867
1991
  }
@@ -1896,27 +2020,107 @@ export function initializeCreativeRowEditor() {
1896
2020
  const confirmMsg = isArchived ? archiveBtn.dataset.restoreConfirm : archiveBtn.dataset.confirm;
1897
2021
 
1898
2022
  if (await confirmDialog(confirmMsg)) {
2023
+ const releaseTreeReload = holdCreativeTreeReload();
2024
+ // Flush the editor BEFORE the archive request goes out, not after it has
2025
+ // landed. The row is about to be removed (or the tree re-rendered), so a
2026
+ // failed flush has nowhere safe to leave the draft once the server-side
2027
+ // change is done — the previous ordering had to choose between stranding
2028
+ // the archived row on screen and discarding the user's unsaved edits.
2029
+ // Flushing first makes the failure recoverable: nothing has changed on the
2030
+ // server yet, so the whole action is simply abandoned.
2031
+ //
2032
+ // `switching: true` because the editor cannot just stay quietly open here:
2033
+ // the user asked for something that is now not happening, so they get the
2034
+ // alert. recoverFromFailedSave() keeps the draft in the editor on this row,
2035
+ // which is what that alert promises — and, because we abort, stays true.
2036
+ const flushed = await hideCurrent(undefined, { switching: true }).catch(err => {
2037
+ console.error('CreativeRowEditor: Failed to flush the editor before archiving', err);
2038
+ return SAVE_FAILED;
2039
+ });
2040
+ if (flushed === SAVE_FAILED) {
2041
+ releaseTreeReload();
2042
+ return;
2043
+ }
2044
+
2045
+ // The flush above already closed the editor, so a failed request has to
2046
+ // say so: the row is still there unarchived, the editor is unexpectedly
2047
+ // gone, and nothing else reports it — creativesApi goes straight to
2048
+ // csrfFetch, bypassing the api queue whose failure listener would
2049
+ // otherwise alert. The draft is not at risk (the flush persisted it), so
2050
+ // this reports rather than recovers. Reopening the editor was considered
2051
+ // and rejected: the request is in flight for an unbounded time, and the
2052
+ // user may well have opened another row by the time it fails — stealing
2053
+ // the shared editor back would then discard a newer draft to undo a
2054
+ // cosmetic surprise.
2055
+ const reportFailure = function (err) {
2056
+ if (err) console.error('CreativeRowEditor: archive request failed', err);
2057
+ // Localized in the ERB and carried on the button, like data-confirm.
2058
+ // No literal fallback here, deliberately: an English string baked into
2059
+ // the module is exactly what this project's i18n rule forbids.
2060
+ const message = isArchived
2061
+ ? archiveBtn.dataset.restoreFailureMessage
2062
+ : archiveBtn.dataset.failureMessage;
2063
+ if (message) alertDialog(message);
2064
+ };
2065
+
1899
2066
  const apiCall = isArchived ? creativesApi.unarchive(creativeId) : creativesApi.archive(creativeId);
1900
2067
  apiCall.then(res => {
1901
- if (res.ok) {
2068
+ // csrfFetch resolves for any HTTP status, so a non-OK response is a
2069
+ // failure that arrives on the fulfilled path.
2070
+ if (!res || !res.ok) return reportFailure();
2071
+ // The pre-flush closed the editor before the request went out, but it
2072
+ // left the row on screen and clickable, and the request is in flight
2073
+ // for an unbounded time. So the user can reopen that row — or one of
2074
+ // its children — and start typing again before this lands. The editor
2075
+ // template is attached *inside* the row it is bound to, so dropping
2076
+ // this subtree would take that newer draft out of the document with
2077
+ // no flush and no feedback, which is the same silent loss the
2078
+ // pre-flush was introduced to stop.
2079
+ const editorIsInsideArchivedSubtree = function () {
2080
+ if (!currentTree) return false;
2081
+ const editedRow = treeRowElement(currentTree) || currentTree;
2082
+ if (row && (row === editedRow || row.contains(editedRow))) return true;
2083
+ const childrenContainer = document.getElementById(`creative-children-${creativeId}`);
2084
+ return !!childrenContainer?.contains(editedRow);
2085
+ };
2086
+
2087
+ const applyToView = function () {
1902
2088
  if (!isArchived) {
1903
- // Archiving: remove from view
2089
+ // Archiving: remove from view. Creative#archive! is an update_all,
2090
+ // so it fires no destroy broadcast — this is the only chance to
2091
+ // bring the empty-state placeholder back when the last row goes.
2092
+ if (editorIsInsideArchivedSubtree()) {
2093
+ // Hand the timing to the tree controller instead of removing
2094
+ // anything here: it holds the refetch until editing stops, so
2095
+ // the draft stays in the editor and the archived row goes away
2096
+ // once the user is done with it. If there is no controller to
2097
+ // ask, the row is deliberately left in place anyway — a stale
2098
+ // row that the next reload corrects is a far smaller failure
2099
+ // than deleting what the user is typing.
2100
+ reloadCreativeTree();
2101
+ return;
2102
+ }
1904
2103
  const childrenContainer = document.getElementById(`creative-children-${creativeId}`);
1905
2104
  if (childrenContainer) childrenContainer.remove();
1906
- if (row) row.remove();
2105
+ removeTreeElement(row);
1907
2106
  } else {
1908
- // Restoring: reload tree to show updated state
1909
- const treeEl = document.querySelector('[data-controller="creatives--tree"]');
1910
- if (treeEl) {
1911
- treeEl.innerHTML = '';
1912
- delete treeEl.dataset.loaded;
1913
- const ctrl = window.Stimulus?.getControllerForElementAndIdentifier(treeEl, 'creatives--tree');
1914
- if (ctrl) ctrl.load();
1915
- }
2107
+ // Restoring: only the server knows where the row belongs in the
2108
+ // tree now, so refetch. Nothing is cleared here on the way: this
2109
+ // request has been in flight for an unbounded time and the user
2110
+ // may well have opened another row and started typing, and wiping
2111
+ // the container would take that row — and the editor attached
2112
+ // inside it — out of the document, discarding the newer draft.
2113
+ // reloadCreativeTree() hands the timing to the tree controller,
2114
+ // which defers the re-render until editing stops; load() then
2115
+ // replaces the container itself, so clearing it first was only
2116
+ // ever a blank flash.
2117
+ reloadCreativeTree();
1916
2118
  }
1917
- closeEditor();
1918
- }
1919
- });
2119
+ };
2120
+ // The pending edit was already flushed and the editor closed above, so
2121
+ // the view can just follow the server.
2122
+ applyToView();
2123
+ }, reportFailure).finally(releaseTreeReload);
1920
2124
  }
1921
2125
  });
1922
2126
  }
@@ -2144,5 +2348,4 @@ export function initializeCreativeRowEditor() {
2144
2348
  }
2145
2349
  });
2146
2350
  }
2147
- });
2148
2351
  }