collavre_github 0.6.3 → 0.8.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 (38) hide show
  1. checksums.yaml +4 -4
  2. data/app/controllers/collavre_github/creatives/integrations_controller.rb +253 -36
  3. data/app/controllers/collavre_github/webhooks_controller.rb +563 -44
  4. data/app/javascript/collavre_github.js +32 -123
  5. data/app/jobs/collavre_github/initial_markdown_sync_job.rb +6 -4
  6. data/app/jobs/collavre_github/markdown_sync_job.rb +6 -4
  7. data/app/jobs/collavre_github/pr_blocker_sweep_job.rb +18 -0
  8. data/app/jobs/collavre_github/webhook_delivery_prune_job.rb +14 -0
  9. data/app/models/collavre_github/github_pr_channel.rb +124 -28
  10. data/app/models/collavre_github/repository_link.rb +63 -2
  11. data/app/models/collavre_github/webhook_delivery.rb +159 -0
  12. data/app/services/collavre_github/client.rb +37 -0
  13. data/app/services/collavre_github/markdown_sync/content_creative.rb +56 -0
  14. data/app/services/collavre_github/markdown_sync/content_processor.rb +16 -1
  15. data/app/services/collavre_github/markdown_sync/incremental_sync_service.rb +12 -34
  16. data/app/services/collavre_github/markdown_sync/initial_import_service.rb +6 -19
  17. data/app/services/collavre_github/pr_blocker_monitor.rb +93 -0
  18. data/app/services/collavre_github/pr_channel_state_updater.rb +83 -0
  19. data/app/services/collavre_github/pr_discussion_event.rb +25 -0
  20. data/app/services/collavre_github/repository_identity_synchronizer.rb +145 -0
  21. data/app/services/collavre_github/repository_provisioning_lock.rb +95 -0
  22. data/app/services/collavre_github/tools/concerns/pr_channel_locator.rb +50 -0
  23. data/app/services/collavre_github/tools/pr_monitor_service.rb +82 -62
  24. data/app/services/collavre_github/tools/pr_state_set_service.rb +170 -0
  25. data/app/services/collavre_github/webhook_provisioner.rb +601 -42
  26. data/app/services/collavre_github/webhook_reprovisioner.rb +118 -0
  27. data/config/locales/en.yml +4 -0
  28. data/config/locales/ko.yml +4 -0
  29. data/config/locales/tool_descriptions.en.yml +20 -0
  30. data/config/locales/tool_descriptions.ko.yml +20 -0
  31. data/config/routes.rb +13 -3
  32. data/db/migrate/20260727000001_add_webhook_hook_id_to_github_repository_links.rb +17 -0
  33. data/db/migrate/20260727000002_create_github_webhook_deliveries.rb +30 -0
  34. data/db/migrate/20260729000000_add_repository_id_index_to_github_repository_links.rb +13 -0
  35. data/db/seeds.rb +2 -1
  36. data/lib/collavre_github/engine.rb +9 -0
  37. data/lib/collavre_github/version.rb +1 -1
  38. metadata +19 -2
@@ -1,4 +1,4 @@
1
- import { csrfToken, showError, clearError, updateStepVisibility, openOAuthPopup, fetchWithCsrf, setupModalClose } from 'collavre/modules/integration_wizard';
1
+ import { csrfToken, showError, clearError, updateStepVisibility, requireCreativeId, resetConnectView, sendJson, appendLabeledInput } from 'collavre/modules/integration_wizard';
2
2
  import { alertDialog, confirmDialog } from 'collavre/lib/utils/dialog';
3
3
  import { deriveConnectState, shouldShowConnectNext } from './github_wizard_state.js';
4
4
 
@@ -72,23 +72,11 @@ if (!githubIntegrationInitialized) {
72
72
  userConnected = false;
73
73
  selectedReposForDeletion = new Set();
74
74
  statusEl.textContent = '';
75
- errorEl.style.display = 'none';
76
- errorEl.textContent = '';
75
+ clearError(errorEl);
77
76
  if (summaryInstructions) summaryInstructions.style.display = 'none';
78
-
79
- if (existingContainer) {
80
- existingContainer.style.display = 'none';
81
- }
82
- if (existingList) {
83
- existingList.innerHTML = '';
84
- }
85
- if (connectMessage) {
86
- connectMessage.style.display = '';
87
- }
88
- if (deleteBtn) deleteBtn.style.display = 'none';
77
+ resetConnectView({ existingContainer, existingList, connectMessage, deleteBtn, loginBtn });
89
78
  if (resyncBtn) resyncBtn.style.display = 'none';
90
79
  updateDeleteButtonState();
91
- if (loginBtn) loginBtn.style.display = 'inline-block';
92
80
  updateStep();
93
81
  }
94
82
 
@@ -98,12 +86,7 @@ if (!githubIntegrationInitialized) {
98
86
  }
99
87
 
100
88
  function updateStep() {
101
- ['connect', 'organization', 'repositories', 'markdown-sync', 'summary']
102
- .forEach(function (step) {
103
- const el = document.getElementById(`github-step-${step}`);
104
- if (!el) return;
105
- el.style.display = (step === currentStep) ? 'block' : 'none';
106
- });
89
+ updateStepVisibility(currentStep, ['connect', 'organization', 'repositories', 'markdown-sync', 'summary'], 'github-step');
107
90
 
108
91
  if (currentStep === 'connect') {
109
92
  prevBtn.style.display = 'none';
@@ -149,13 +132,6 @@ if (!githubIntegrationInitialized) {
149
132
  return;
150
133
  }
151
134
  repos.forEach(function (fullName) {
152
- const label = document.createElement('label');
153
- label.style.display = 'flex';
154
- label.style.alignItems = 'center';
155
- label.style.gap = '0.5em';
156
- label.style.marginBottom = '0.5em';
157
- label.style.cursor = 'pointer';
158
-
159
135
  const input = document.createElement('input');
160
136
  input.type = 'checkbox';
161
137
  input.value = fullName;
@@ -168,12 +144,7 @@ if (!githubIntegrationInitialized) {
168
144
  }
169
145
  });
170
146
 
171
- const span = document.createElement('span');
172
- span.textContent = fullName + ' — Markdown Sync';
173
-
174
- label.appendChild(input);
175
- label.appendChild(span);
176
- markdownSyncList.appendChild(label);
147
+ appendLabeledInput(markdownSyncList, input, fullName + ' — Markdown Sync');
177
148
  });
178
149
  }
179
150
 
@@ -187,23 +158,12 @@ if (!githubIntegrationInitialized) {
187
158
  document.body.classList.remove('no-scroll');
188
159
  }
189
160
 
190
- function showError(message) {
191
- if (!message) return;
192
- errorEl.textContent = message;
193
- errorEl.style.display = 'block';
194
- }
195
-
196
- function clearError() {
197
- errorEl.textContent = '';
198
- errorEl.style.display = 'none';
199
- }
200
-
201
161
  function fetchStatus() {
202
162
  if (!creativeId) {
203
- showError(modal.dataset.noCreative);
163
+ showError(errorEl, modal.dataset.noCreative);
204
164
  return;
205
165
  }
206
- clearError();
166
+ clearError(errorEl);
207
167
  fetch(`/github/creatives/${creativeId}/integration`, { headers: { Accept: 'application/json' } })
208
168
  .then(function (response) { return response.json(); })
209
169
  .then(function (data) {
@@ -261,7 +221,7 @@ if (!githubIntegrationInitialized) {
261
221
  }
262
222
  })
263
223
  .catch(function () {
264
- showError('Github 연동 정보를 불러오지 못했습니다.');
224
+ showError(errorEl, 'Github 연동 정보를 불러오지 못했습니다.');
265
225
  });
266
226
  }
267
227
 
@@ -338,7 +298,7 @@ if (!githubIntegrationInitialized) {
338
298
  renderOrganizations();
339
299
  })
340
300
  .catch(function () {
341
- showError('Organization 목록을 불러오지 못했습니다.');
301
+ showError(errorEl, 'Organization 목록을 불러오지 못했습니다.');
342
302
  });
343
303
  }
344
304
 
@@ -352,13 +312,6 @@ if (!githubIntegrationInitialized) {
352
312
  return;
353
313
  }
354
314
  organizations.forEach(function (org) {
355
- const label = document.createElement('label');
356
- label.style.display = 'flex';
357
- label.style.alignItems = 'center';
358
- label.style.gap = '0.5em';
359
- label.style.marginBottom = '0.5em';
360
- label.style.cursor = 'pointer';
361
-
362
315
  const input = document.createElement('input');
363
316
  input.type = 'radio';
364
317
  input.name = 'github-organization';
@@ -371,19 +324,14 @@ if (!githubIntegrationInitialized) {
371
324
  nextBtn.disabled = false;
372
325
  });
373
326
 
374
- const span = document.createElement('span');
375
- span.textContent = org.name || org.login;
376
-
377
- label.appendChild(input);
378
- label.appendChild(span);
379
- orgList.appendChild(label);
327
+ appendLabeledInput(orgList, input, org.name || org.login);
380
328
  });
381
329
  nextBtn.disabled = !selectedOrg;
382
330
  }
383
331
 
384
332
  function loadRepositories() {
385
333
  if (!selectedOrg) return;
386
- clearError();
334
+ clearError(errorEl);
387
335
  if (repoList) {
388
336
  repoList.textContent = '...';
389
337
  }
@@ -396,7 +344,7 @@ if (!githubIntegrationInitialized) {
396
344
  })
397
345
  .catch(function () {
398
346
  if (repoList) repoList.textContent = '';
399
- showError('Repository 목록을 불러오지 못했습니다.');
347
+ showError(errorEl, 'Repository 목록을 불러오지 못했습니다.');
400
348
  });
401
349
  }
402
350
 
@@ -410,13 +358,6 @@ if (!githubIntegrationInitialized) {
410
358
  return;
411
359
  }
412
360
  repositories.forEach(function (repo) {
413
- const label = document.createElement('label');
414
- label.style.display = 'flex';
415
- label.style.alignItems = 'center';
416
- label.style.gap = '0.5em';
417
- label.style.marginBottom = '0.5em';
418
- label.style.cursor = 'pointer';
419
-
420
361
  const input = document.createElement('input');
421
362
  input.type = 'checkbox';
422
363
  input.value = repo.full_name;
@@ -429,12 +370,7 @@ if (!githubIntegrationInitialized) {
429
370
  }
430
371
  });
431
372
 
432
- const span = document.createElement('span');
433
- span.textContent = repo.full_name;
434
-
435
- label.appendChild(input);
436
- label.appendChild(span);
437
- repoList.appendChild(label);
373
+ appendLabeledInput(repoList, input, repo.full_name);
438
374
  });
439
375
  }
440
376
 
@@ -497,25 +433,17 @@ if (!githubIntegrationInitialized) {
497
433
  }
498
434
 
499
435
  function saveSelection() {
500
- clearError();
436
+ clearError(errorEl);
501
437
  const markdownSync = {};
502
438
  Array.from(selectedRepos).forEach(function (repo) {
503
439
  markdownSync[repo] = markdownSyncRepos.has(repo);
504
440
  });
505
441
  const payload = { repositories: Array.from(selectedRepos), markdown_sync: markdownSync };
506
-
507
- fetch(`/github/creatives/${creativeId}/integration`, {
508
- method: 'PATCH',
509
- headers: {
510
- 'Content-Type': 'application/json',
511
- 'X-CSRF-Token': csrfToken()
512
- },
513
- body: JSON.stringify(payload)
514
- })
515
- .then(function (response) { return response.json().then(function (body) { return { ok: response.ok, body: body }; }); })
442
+
443
+ sendJson(`/github/creatives/${creativeId}/integration`, 'PATCH', payload)
516
444
  .then(function (result) {
517
445
  if (!result.ok) {
518
- showError(result.body.error || '연동 저장 중 오류가 발생했습니다.');
446
+ showError(errorEl, result.body.error || '연동 저장 중 오류가 발생했습니다.');
519
447
  return;
520
448
  }
521
449
  selectedRepos = new Set(result.body.selected_repositories || []);
@@ -526,16 +454,13 @@ if (!githubIntegrationInitialized) {
526
454
  alertDialog(modal.dataset.successMessage);
527
455
  })
528
456
  .catch(function () {
529
- showError('연동 정보를 저장하지 못했습니다.');
457
+ showError(errorEl, '연동 정보를 저장하지 못했습니다.');
530
458
  });
531
459
  }
532
460
 
533
461
  openBtn.addEventListener('click', function () {
534
- creativeId = openBtn.dataset.creativeId;
535
- if (!creativeId) {
536
- alertDialog(modal.dataset.noCreative);
537
- return;
538
- }
462
+ creativeId = requireCreativeId(openBtn, modal);
463
+ if (!creativeId) return;
539
464
  resetWizard();
540
465
  showModal();
541
466
  fetchStatus();
@@ -547,7 +472,7 @@ if (!githubIntegrationInitialized) {
547
472
  });
548
473
 
549
474
  prevBtn.addEventListener('click', function () {
550
- clearError();
475
+ clearError(errorEl);
551
476
  if (currentStep === 'organization') {
552
477
  currentStep = 'connect';
553
478
  } else if (currentStep === 'repositories') {
@@ -563,7 +488,7 @@ if (!githubIntegrationInitialized) {
563
488
  });
564
489
 
565
490
  nextBtn.addEventListener('click', function () {
566
- clearError();
491
+ clearError(errorEl);
567
492
  if (currentStep === 'connect') {
568
493
  currentStep = 'organization';
569
494
  updateStep();
@@ -613,26 +538,18 @@ if (!githubIntegrationInitialized) {
613
538
  alertDialog(modal.dataset.noCreative);
614
539
  return;
615
540
  }
616
- clearError();
541
+ clearError(errorEl);
617
542
  const selectedToDelete = Array.from(selectedReposForDeletion);
618
543
  if (!selectedToDelete.length) {
619
- showError(deleteSelectWarning);
544
+ showError(errorEl, deleteSelectWarning);
620
545
  return;
621
546
  }
622
547
  if (!(await confirmDialog(deleteConfirm, { danger: true }))) return;
623
548
 
624
- fetch(`/github/creatives/${creativeId}/integration`, {
625
- method: 'DELETE',
626
- headers: {
627
- 'Content-Type': 'application/json',
628
- 'X-CSRF-Token': csrfToken()
629
- },
630
- body: JSON.stringify({ repositories: selectedToDelete })
631
- })
632
- .then(function (response) { return response.json().then(function (body) { return { ok: response.ok, body: body }; }); })
549
+ sendJson(`/github/creatives/${creativeId}/integration`, 'DELETE', { repositories: selectedToDelete })
633
550
  .then(function (result) {
634
551
  if (!result.ok) {
635
- showError(result.body.error || deleteError);
552
+ showError(errorEl, result.body.error || deleteError);
636
553
  return;
637
554
  }
638
555
 
@@ -654,17 +571,17 @@ if (!githubIntegrationInitialized) {
654
571
  }
655
572
  })
656
573
  .catch(function () {
657
- showError(deleteError);
574
+ showError(errorEl, deleteError);
658
575
  });
659
576
  });
660
577
 
661
578
  resyncBtn?.addEventListener('click', async function () {
662
579
  if (!creativeId) return;
663
- clearError();
580
+ clearError(errorEl);
664
581
  const checkboxes = existingList ? existingList.querySelectorAll('.github-existing-repo-checkbox:checked') : [];
665
582
  const selectedToResync = Array.from(checkboxes).map(cb => cb.value);
666
583
  if (!selectedToResync.length) {
667
- showError(resyncSelectWarning);
584
+ showError(errorEl, resyncSelectWarning);
668
585
  return;
669
586
  }
670
587
  if (!(await confirmDialog(resyncConfirm))) return;
@@ -674,21 +591,13 @@ if (!githubIntegrationInitialized) {
674
591
  let failed = 0;
675
592
 
676
593
  selectedToResync.forEach(function (repo) {
677
- fetch(`/github/creatives/${creativeId}/integration/resync`, {
678
- method: 'POST',
679
- headers: {
680
- 'Content-Type': 'application/json',
681
- 'X-CSRF-Token': csrfToken()
682
- },
683
- body: JSON.stringify({ repository: repo })
684
- })
685
- .then(function (response) { return response.json().then(function (body) { return { ok: response.ok, body: body }; }); })
594
+ sendJson(`/github/creatives/${creativeId}/integration/resync`, 'POST', { repository: repo })
686
595
  .then(function (result) {
687
596
  completed++;
688
597
  if (!result.ok) failed++;
689
598
  if (completed === selectedToResync.length) {
690
599
  if (failed > 0) {
691
- showError(resyncError);
600
+ showError(errorEl, resyncError);
692
601
  } else {
693
602
  statusEl.textContent = resyncSuccess;
694
603
  }
@@ -699,7 +608,7 @@ if (!githubIntegrationInitialized) {
699
608
  completed++;
700
609
  failed++;
701
610
  if (completed === selectedToResync.length) {
702
- showError(resyncError);
611
+ showError(errorEl, resyncError);
703
612
  resyncBtn.disabled = false;
704
613
  }
705
614
  });
@@ -10,10 +10,12 @@ module CollavreGithub
10
10
  user = link.creative.user
11
11
  return unless user
12
12
 
13
- CollavreGithub::MarkdownSync::InitialImportService.new(
14
- repository_link: link,
15
- user: user
16
- ).call
13
+ Collavre::Creatives::History.track(actor: nil, origin: :sync) do
14
+ CollavreGithub::MarkdownSync::InitialImportService.new(
15
+ repository_link: link,
16
+ user: user
17
+ ).call
18
+ end
17
19
  end
18
20
  end
19
21
  end
@@ -7,10 +7,12 @@ module CollavreGithub
7
7
  link = CollavreGithub::RepositoryLink.find_by(id: repository_link_id)
8
8
  return unless link&.markdown_sync_enabled?
9
9
 
10
- CollavreGithub::MarkdownSync::IncrementalSyncService.new(
11
- repository_link: link,
12
- push_payload: push_payload
13
- ).call
10
+ Collavre::Creatives::History.track(actor: nil, origin: :sync) do
11
+ CollavreGithub::MarkdownSync::IncrementalSyncService.new(
12
+ repository_link: link,
13
+ push_payload: push_payload
14
+ ).call
15
+ end
14
16
  end
15
17
  end
16
18
  end
@@ -0,0 +1,18 @@
1
+ module CollavreGithub
2
+ class PrBlockerSweepJob < ApplicationJob
3
+ queue_as :default
4
+
5
+ limits_concurrency to: 1,
6
+ key: -> { "github-pr-blocker-sweep" },
7
+ duration: 1.hour,
8
+ on_conflict: :discard
9
+
10
+ def perform
11
+ GithubPrChannel.active.not_dismissed.find_each do |channel|
12
+ PrBlockerMonitor.new(channel).call
13
+ rescue StandardError => e
14
+ Rails.logger.warn("[CollavreGithub] PR blocker check failed for channel #{channel.id}: #{e.class}")
15
+ end
16
+ end
17
+ end
18
+ end
@@ -0,0 +1,14 @@
1
+ # frozen_string_literal: true
2
+
3
+ module CollavreGithub
4
+ # Trims the webhook idempotency ledger. Rows are only useful for as long as
5
+ # GitHub could still redeliver the same GUID; past that they are dead weight.
6
+ class WebhookDeliveryPruneJob < ApplicationJob
7
+ queue_as :default
8
+
9
+ def perform
10
+ deleted = CollavreGithub::WebhookDelivery.prune!
11
+ Rails.logger.info("[CollavreGithub::WebhookDeliveryPruneJob] pruned #{deleted} rows") if deleted.positive?
12
+ end
13
+ end
14
+ end
@@ -2,6 +2,9 @@ module CollavreGithub
2
2
  class GithubPrChannel < Collavre::Channel
3
3
  self.table_name = "channels"
4
4
 
5
+ before_create :initialize_discussion_tracking
6
+ after_destroy_commit :broadcast_chips_changed
7
+
5
8
  def repo_full_name
6
9
  config["repo_full_name"]
7
10
  end
@@ -58,6 +61,39 @@ module CollavreGithub
58
61
  self.config = config.merge("pr_state" => value)
59
62
  end
60
63
 
64
+ # Keep a single monitor when identity repair meets a channel that a user
65
+ # already attached under the canonical repository name. The explicit
66
+ # canonical channel survives; topic comments are not owned by channels, so
67
+ # removing the obsolete routing row loses no timeline content.
68
+ def synchronize_repository_name!(canonical_full_name)
69
+ return self if repo_full_name == canonical_full_name
70
+
71
+ survivor = self.class
72
+ .where(topic_id: topic_id, pr_number: pr_number)
73
+ .where("LOWER(repo_full_name) = ?", canonical_full_name.to_s.downcase)
74
+ .where.not(id: id)
75
+ .first
76
+
77
+ if survivor
78
+ if preferred_over?(survivor)
79
+ self.class.transaction do
80
+ survivor.destroy!
81
+ update!(config: config.merge("repo_full_name" => canonical_full_name))
82
+ end
83
+ return self
84
+ end
85
+
86
+ survivor.update!(
87
+ config: survivor.config.merge("repo_full_name" => canonical_full_name)
88
+ )
89
+ destroy!
90
+ survivor
91
+ else
92
+ update!(config: config.merge("repo_full_name" => canonical_full_name))
93
+ self
94
+ end
95
+ end
96
+
61
97
  def attached_message
62
98
  Collavre::Channel::InjectedMessage.new(
63
99
  speaker: channel_bot_user,
@@ -67,6 +103,31 @@ module CollavreGithub
67
103
  )
68
104
  end
69
105
 
106
+ # Shown when GitHub's delivery could not be authenticated. Renders this
107
+ # channel's OWN stored repo name, never the rejected payload's — the
108
+ # payload is unverified by definition at the point this is built.
109
+ def auth_failure_message
110
+ Collavre::Channel::InjectedMessage.new(
111
+ speaker: channel_bot_user,
112
+ message: t("auth_failure_message", repo: repo_full_name, label: label, url: pr_url),
113
+ label: label,
114
+ link: pr_url
115
+ )
116
+ end
117
+
118
+ # Closing message for `state` (merged / closed_without_merge). Public so
119
+ # the out-of-band corrector (PrChannelStateUpdater) posts the exact same
120
+ # text the webhook would have, instead of maintaining a second copy.
121
+ def closed_message(state = pr_state)
122
+ verb = state.to_s == "merged" ? t("state_merged") : t("state_closed")
123
+ Collavre::Channel::InjectedMessage.new(
124
+ speaker: channel_bot_user,
125
+ message: t("closed_message", label: label, verb: verb),
126
+ label: label,
127
+ link: pr_url
128
+ )
129
+ end
130
+
70
131
  def reopened_message
71
132
  Collavre::Channel::InjectedMessage.new(
72
133
  speaker: channel_bot_user,
@@ -76,26 +137,74 @@ module CollavreGithub
76
137
  )
77
138
  end
78
139
 
140
+ def blocker_message(key, **options)
141
+ Collavre::Channel::InjectedMessage.new(
142
+ speaker: channel_bot_user,
143
+ message: t(key, label: label, url: pr_url, **options),
144
+ label: label,
145
+ link: pr_url
146
+ )
147
+ end
148
+
149
+ def discussion_poll_since
150
+ config["discussion_poll_since"]&.to_time || last_event_at || created_at
151
+ end
152
+
153
+ def start_discussion_tracking!(since = discussion_poll_since)
154
+ return if config.key?("discussion_poll_since")
155
+
156
+ update!(config: config.merge("discussion_poll_since" => since.iso8601(6)))
157
+ end
158
+
159
+ # Both callers hold the channel lock so the message and its GitHub ID commit together.
160
+ def deliver_event!(event:, payload:)
161
+ definition = PrDiscussionEvent::EVENTS[event]
162
+ external_id = payload.dig(definition.resource, "id") if definition
163
+ key = "#{event}:#{external_id}" if external_id.present?
164
+ delivered = config.fetch("discussion_event_ids", [])
165
+ return if key && delivered.include?(key)
166
+
167
+ injected = handle(event: event, payload: payload)
168
+ return unless injected
169
+
170
+ start_discussion_tracking! if definition
171
+ inject_into_topic!(injected)
172
+ update!(config: config.merge("discussion_event_ids" => delivered + [ key ])) if key
173
+ detach! if event == "pull_request" && payload["action"] == "closed"
174
+ end
175
+
79
176
  def handle(event:, payload:)
80
- case event
81
- when "issue_comment"
82
- handle_issue_comment(payload)
83
- when "pull_request_review_comment"
84
- handle_review_comment(payload)
85
- when "pull_request_review"
86
- handle_review_submitted(payload)
87
- when "pull_request"
88
- handle_pull_request(payload)
89
- end
177
+ return handle_pull_request(payload) if event == "pull_request"
178
+
179
+ definition = PrDiscussionEvent::EVENTS[event]
180
+ return unless definition && payload["action"] == definition.action
181
+ return if event == "issue_comment" && !payload.dig("issue", "pull_request")
182
+
183
+ send(definition.handler, payload.fetch(definition.resource))
90
184
  end
91
185
 
92
186
  private
93
187
 
188
+ def initialize_discussion_tracking
189
+ # GitHub event timestamps have second precision.
190
+ self.config = config.reverse_merge("discussion_poll_since" => (created_at || Time.current).iso8601)
191
+ end
192
+
193
+ def preferred_over?(other)
194
+ (lifecycle_priority(self) <=> lifecycle_priority(other)) == 1
195
+ end
196
+
197
+ def lifecycle_priority(channel)
198
+ [
199
+ channel.active? ? 1 : 0,
200
+ channel.dismissed? ? 0 : 1
201
+ ]
202
+ end
203
+
94
204
  def handle_pull_request(payload)
95
205
  return nil unless payload["action"] == "closed"
96
206
  pr = payload["pull_request"]
97
207
  new_state = pr["merged"] ? "merged" : "closed_without_merge"
98
- verb = pr["merged"] ? t("state_merged") : t("state_closed")
99
208
 
100
209
  # pr_state is updated atomically with the closing comment: the dispatch
101
210
  # path wraps both `handle` and `inject_into_topic!` in a single with_lock
@@ -105,19 +214,12 @@ module CollavreGithub
105
214
  self.pr_state = new_state
106
215
  save!
107
216
 
108
- Collavre::Channel::InjectedMessage.new(
109
- speaker: channel_bot_user,
110
- message: t("closed_message", label: label, verb: verb),
111
- label: label,
112
- link: pr_url
113
- )
217
+ closed_message(new_state)
114
218
  # Detach is performed by the webhook controller AFTER injecting this
115
219
  # message, so the chip stays visible until the closing comment lands.
116
220
  end
117
221
 
118
- def handle_review_submitted(payload)
119
- return nil unless payload["action"] == "submitted"
120
- review = payload["review"]
222
+ def handle_review_submitted(review)
121
223
  body = review["body"].to_s
122
224
  return nil if body.strip.empty?
123
225
 
@@ -132,9 +234,7 @@ module CollavreGithub
132
234
  )
133
235
  end
134
236
 
135
- def handle_review_comment(payload)
136
- return nil unless payload["action"] == "created"
137
- comment = payload["comment"]
237
+ def handle_review_comment(comment)
138
238
  author = comment.dig("user", "login")
139
239
  return nil if ignored_actor?(author)
140
240
  path = comment["path"]
@@ -157,11 +257,7 @@ module CollavreGithub
157
257
  )
158
258
  end
159
259
 
160
- def handle_issue_comment(payload)
161
- return nil unless payload["action"] == "created"
162
- return nil unless payload.dig("issue", "pull_request") # PR comments only
163
-
164
- comment = payload["comment"]
260
+ def handle_issue_comment(comment)
165
261
  author = comment.dig("user", "login")
166
262
  return nil if ignored_actor?(author)
167
263
  body = comment["body"].to_s