@in-the-loop-labs/pair-review 5.3.6 → 5.4.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 (41) hide show
  1. package/README.md +8 -0
  2. package/package.json +3 -3
  3. package/plugin/.claude-plugin/plugin.json +1 -1
  4. package/plugin-code-critic/.claude-plugin/plugin.json +1 -1
  5. package/plugin-pair-loop/.claude-plugin/plugin.json +1 -1
  6. package/public/css/pr.css +407 -13
  7. package/public/js/components/AIPanel.js +323 -104
  8. package/public/js/components/ReviewHistoryModal.js +294 -0
  9. package/public/js/components/ReviewModal.js +131 -14
  10. package/public/js/components/SplitButton.js +14 -0
  11. package/public/js/local.js +4 -8
  12. package/public/js/modules/comment-manager.js +6 -12
  13. package/public/js/modules/comment-minimizer.js +4 -1
  14. package/public/js/modules/file-comment-manager.js +38 -74
  15. package/public/js/modules/pierre-bridge.js +36 -0
  16. package/public/js/modules/suggestion-manager.js +4 -1
  17. package/public/js/pr.js +337 -191
  18. package/public/js/utils/posted-comment.js +326 -0
  19. package/public/js/vendor/pierre-diffs-worker.js +41 -13485
  20. package/public/js/vendor/pierre-diffs.js +131 -1364
  21. package/public/local.html +1 -0
  22. package/public/pr.html +2 -0
  23. package/src/chat/api-reference.js +22 -2
  24. package/src/config.js +28 -4
  25. package/src/database.js +177 -35
  26. package/src/github/client.js +95 -16
  27. package/src/github/impl/graphql/pending-review-comments.js +118 -14
  28. package/src/github/impl/graphql/pending-review.js +8 -2
  29. package/src/github/impl/graphql/review-comment-edit.js +89 -0
  30. package/src/github/impl/host/pending-review-comments.js +41 -10
  31. package/src/github/impl/host/review-comment-edit.js +36 -0
  32. package/src/github/impl/rest/pending-review.js +6 -2
  33. package/src/github/impl/rest/review-comment-edit.js +44 -0
  34. package/src/github/impl/review-comment-edit-utils.js +45 -0
  35. package/src/github/operations/pending-review.js +4 -3
  36. package/src/github/operations/review-comment-edit.js +35 -0
  37. package/src/github/record-submission.js +78 -0
  38. package/src/github/update-posted-comment.js +115 -0
  39. package/src/main.js +24 -38
  40. package/src/routes/mcp.js +1 -0
  41. package/src/routes/pr.js +152 -100
package/src/main.js CHANGED
@@ -8,6 +8,8 @@ const { initializeDatabase, run, queryOne, query, migrateExistingWorktrees, Work
8
8
  const { PRArgumentParser } = require('./github/parser');
9
9
  const { GitHubClient } = require('./github/client');
10
10
  const { buildSubmitPrContext } = require('./github/submit-pr-context');
11
+ const { recordReviewSubmission, recordRetainedSubmission } = require('./github/record-submission');
12
+ const { broadcastReviewEvent } = require('./events/review-events');
11
13
  const { GitWorktreeManager } = require('./git/worktree');
12
14
  const { fetchNoTags } = require('./git/fetch-helpers');
13
15
  const { cleanupOrphanedKeepFiles } = require('./git/pack-cleanup');
@@ -1374,7 +1376,7 @@ async function loadHeadlessSuggestions(db, reviewId) {
1374
1376
  type,
1375
1377
  is_file_level
1376
1378
  FROM comments
1377
- WHERE review_id = ? AND source = 'ai' AND ai_level IS NULL AND (is_raw = 0 OR is_raw IS NULL) AND status = 'active'
1379
+ WHERE review_id = ? AND source = 'ai' AND ai_level IS NULL AND (is_raw = 0 OR is_raw IS NULL) AND ${CommentRepository.pendingCommentSql('comments')}
1378
1380
  ORDER BY file, line_start
1379
1381
  `, [reviewId]);
1380
1382
 
@@ -1400,7 +1402,6 @@ async function loadHeadlessSuggestions(db, reviewId) {
1400
1402
  * @param {Object} options - Mode-specific options
1401
1403
  * @param {string} options.mode - 'draft' or 'review'
1402
1404
  * @param {string} options.reviewEvent - 'DRAFT' or 'COMMENT'
1403
- * @param {string} options.commentStatus - 'draft' or 'submitted'
1404
1405
  * @param {string} options.modeLabel - Display label for log messages (e.g., 'draft mode', 'action review mode')
1405
1406
  * @param {import('../git/worktree-pool-lifecycle').WorktreePoolLifecycle} [externalPoolLifecycle] - Shared pool lifecycle instance (avoids creating a fresh singleton)
1406
1407
  */
@@ -1783,14 +1784,22 @@ Found ${aiSuggestions.length} suggestion${aiSuggestions.length === 1 ? '' : 's'}
1783
1784
  });
1784
1785
 
1785
1786
  let githubReview;
1786
- if (options.reviewEvent === 'DRAFT') {
1787
- githubReview = await githubClient.createDraftReviewGraphQL(
1788
- prNodeId, reviewBody, githubComments, existingDraft?.id, submitPrContext
1789
- );
1790
- } else {
1791
- githubReview = await githubClient.createReviewGraphQL(
1792
- prNodeId, options.reviewEvent, reviewBody, githubComments, existingDraft?.id, submitPrContext
1793
- );
1787
+ try {
1788
+ if (options.reviewEvent === 'DRAFT') {
1789
+ githubReview = await githubClient.createDraftReviewGraphQL(
1790
+ prNodeId, reviewBody, githubComments, existingDraft?.id, submitPrContext
1791
+ );
1792
+ } else {
1793
+ githubReview = await githubClient.createReviewGraphQL(
1794
+ prNodeId, options.reviewEvent, reviewBody, githubComments, existingDraft?.id, submitPrContext
1795
+ );
1796
+ }
1797
+ } catch (error) {
1798
+ await recordRetainedSubmission(db, error, {
1799
+ reviewId: review.id, body: reviewBody, existingDraft,
1800
+ sourceRows: aiSuggestions, sentComments: githubComments
1801
+ }, () => broadcastReviewEvent(review.id, { type: 'review:comments_changed' }));
1802
+ throw error;
1794
1803
  }
1795
1804
 
1796
1805
  // When adding to an existing draft, use the existing URL and include prior comments in total count
@@ -1804,12 +1813,6 @@ Found ${aiSuggestions.length} suggestion${aiSuggestions.length === 1 ? '' : 's'}
1804
1813
  // - github_reviews.github_node_id -> GraphQL node ID (e.g., "PRR_kwDOM...")
1805
1814
  // - reviewData JSON -> uses 'github_node_id' key for the GraphQL node ID
1806
1815
  const githubNodeId = String(githubReview.id); // GraphQL methods return node IDs
1807
- const githubDatabaseId = githubReview.databaseId
1808
- ? String(githubReview.databaseId)
1809
- : existingDraft ? String(existingDraft.databaseId) : null;
1810
-
1811
- const githubReviewState = options.reviewEvent === 'DRAFT' ? 'pending' : 'submitted';
1812
-
1813
1816
  // Update database to track the review
1814
1817
  await run(db, 'BEGIN TRANSACTION');
1815
1818
 
@@ -1831,29 +1834,14 @@ Found ${aiSuggestions.length} suggestion${aiSuggestions.length === 1 ? '' : 's'}
1831
1834
  reviewData: reviewData
1832
1835
  });
1833
1836
 
1834
- // Create a github_reviews record to track this submission (matches pr.js)
1835
- const githubReviewRepo = new GitHubReviewRepository(db);
1836
- await githubReviewRepo.create(review.id, {
1837
- github_review_id: githubDatabaseId,
1838
- github_node_id: githubNodeId,
1839
- state: githubReviewState,
1840
- body: reviewBody || '',
1841
- github_url: githubReview.html_url
1837
+ await recordReviewSubmission(db, {
1838
+ reviewId: review.id, event: options.reviewEvent, body: reviewBody,
1839
+ githubReview, existingDraft, sourceRows: aiSuggestions,
1840
+ sentComments: githubComments, postedComments: githubReview.postedComments
1842
1841
  });
1843
1842
 
1844
- // Update AI suggestions to appropriate status (batch update for performance)
1845
- // Only the submitted suggestions (loadHeadlessSuggestions skipped the rest)
1846
- if (aiSuggestions.length > 0) {
1847
- const suggestionIds = aiSuggestions.map(s => s.id);
1848
- const placeholders = suggestionIds.map(() => '?').join(',');
1849
- await run(db, `
1850
- UPDATE comments
1851
- SET status = ?, updated_at = ?
1852
- WHERE id IN (${placeholders})
1853
- `, [options.commentStatus, now, ...suggestionIds]);
1854
- }
1855
-
1856
1843
  await run(db, 'COMMIT');
1844
+ broadcastReviewEvent(review.id, { type: 'review:comments_changed' });
1857
1845
 
1858
1846
  const successLabel = options.reviewEvent === 'DRAFT' ? 'Draft review created' : 'Review submitted';
1859
1847
  console.log(`\n✅ ${successLabel} successfully!`);
@@ -2695,7 +2683,6 @@ async function handleDraftModeReview(args, config, db, flags = {}, poolLifecycle
2695
2683
  await performHeadlessReview(args, config, db, flags, {
2696
2684
  mode: 'draft',
2697
2685
  reviewEvent: 'DRAFT',
2698
- commentStatus: 'draft',
2699
2686
  modeLabel: 'draft mode'
2700
2687
  }, poolLifecycle);
2701
2688
  }
@@ -2714,7 +2701,6 @@ async function handleActionReview(args, config, db, flags = {}, poolLifecycle =
2714
2701
  await performHeadlessReview(args, config, db, flags, {
2715
2702
  mode: 'review',
2716
2703
  reviewEvent: 'COMMENT',
2717
- commentStatus: 'submitted',
2718
2704
  modeLabel: 'action review mode'
2719
2705
  }, poolLifecycle);
2720
2706
  }
package/src/routes/mcp.js CHANGED
@@ -271,6 +271,7 @@ function createMCPServer(db, options = {}) {
271
271
  type: c.type,
272
272
  title: c.title,
273
273
  status: c.status,
274
+ posted: c.publication?.state || null,
274
275
  created_at: c.created_at,
275
276
  });
276
277
  }
package/src/routes/pr.js CHANGED
@@ -40,6 +40,8 @@ const simpleGit = require('simple-git');
40
40
  const { GIT_DIFF_FLAGS_ARRAY, SIMPLE_GIT_PATH_OPTIONS } = require('../git/diff-flags');
41
41
  const { walkPRStack, DEFAULT_TRUNK_BRANCHES } = require('../github/stack-walker');
42
42
  const { buildSubmitPrContext } = require('../github/submit-pr-context');
43
+ const { recordReviewSubmission, recordRetainedSubmission } = require('../github/record-submission');
44
+ const { updatePostedComment, listSubmissions } = require('../github/update-posted-comment');
43
45
  const summaryGenerator = require('../ai/summary-generator');
44
46
  const tourGenerator = require('../ai/tour-generator');
45
47
  const {
@@ -204,6 +206,66 @@ async function resolveBindingForRequest(req, repository) {
204
206
  return null;
205
207
  }
206
208
 
209
+ /**
210
+ * Resolve stale drafts before opening a short local transaction. Errors are
211
+ * retried on the next load; a confirmed missing review is treated as dismissed,
212
+ * never requeued. Postings stay intact and derive their state from these rows.
213
+ * @returns {Promise<boolean>} Whether any pending record changed state
214
+ */
215
+ async function reconcileStalePendingRecords(githubReviewRepo, records, githubClient, prContext,
216
+ { keepPendingOnError = true } = {}) {
217
+ const updates = [];
218
+ const lookups = new Map();
219
+ for (const record of records) {
220
+ let actualState = 'dismissed';
221
+ let data = null;
222
+ const lookupId = record.github_node_id || record.github_review_id;
223
+ if (githubClient && lookupId) {
224
+ const key = record.github_review_id || lookupId;
225
+ try {
226
+ if (!lookups.has(key)) {
227
+ const context = prContext ? { ...prContext, reviewId: record.github_review_id } : null;
228
+ lookups.set(key, githubClient.getReviewById(lookupId, context, { strict: true }));
229
+ }
230
+ data = await lookups.get(key);
231
+ if (data) {
232
+ actualState = data.state === 'PENDING' ? 'pending'
233
+ : data.state === 'DISMISSED' ? 'dismissed' : 'submitted';
234
+ }
235
+ } catch (error) {
236
+ logger.warn(`Error querying GitHub for old review ${lookupId}: ${error.message}`);
237
+ if (keepPendingOnError) continue;
238
+ }
239
+ } else if (keepPendingOnError) {
240
+ // Without a usable client/identity absence cannot be confirmed.
241
+ continue;
242
+ }
243
+ if (actualState === 'pending') continue;
244
+ const update = { state: actualState };
245
+ if (actualState === 'submitted' && data?.submittedAt) update.submitted_at = data.submittedAt;
246
+ updates.push({ record, update });
247
+ }
248
+ if (!updates.length) return false;
249
+
250
+ const changedReviews = new Set();
251
+ let changed = false;
252
+ await withTransaction(githubReviewRepo.db, async () => {
253
+ for (const { record, update } of updates) {
254
+ // A submit may have completed while the network lookups were in flight.
255
+ const current = await githubReviewRepo.getById(record.id);
256
+ if (current?.state !== 'pending') continue;
257
+ await githubReviewRepo.update(record.id, update);
258
+ changed = true;
259
+ if (record.review_id != null) changedReviews.add(record.review_id);
260
+ }
261
+ });
262
+ // Include the requesting tab: its initial comments fetch may have raced us.
263
+ for (const reviewId of changedReviews) {
264
+ broadcastReviewEvent(reviewId, { type: 'review:comments_changed' });
265
+ }
266
+ return changed;
267
+ }
268
+
207
269
  /**
208
270
  * Sync pending draft review from GitHub with local database
209
271
  *
@@ -234,10 +296,15 @@ async function syncPendingDraftFromGitHub(githubReviewRepo, reviewId, githubPend
234
296
  const githubDbIdStr = (githubPendingReview.databaseId !== undefined && githubPendingReview.databaseId !== null)
235
297
  ? String(githubPendingReview.databaseId)
236
298
  : null;
237
- const matchingRecord = existingPendingRecords.find(r =>
299
+ const matchesCurrentDraft = r =>
238
300
  (r.github_node_id && r.github_node_id === githubPendingReview.id) ||
239
- (githubDbIdStr !== null && r.github_review_id === githubDbIdStr)
240
- );
301
+ (githubDbIdStr !== null && r.github_review_id === githubDbIdStr);
302
+ const matchingRecord = existingPendingRecords.find(matchesCurrentDraft);
303
+ // Older drafts can remain stale even when we already know the current one.
304
+ // Exclude every duplicate of the current identity, not just the chosen row.
305
+ await reconcileStalePendingRecords(githubReviewRepo,
306
+ existingPendingRecords.filter(r => !matchesCurrentDraft(r)), githubClient, prContext,
307
+ { keepPendingOnError: false });
241
308
 
242
309
  let pendingDraft;
243
310
  if (matchingRecord) {
@@ -251,60 +318,6 @@ async function syncPendingDraftFromGitHub(githubReviewRepo, reviewId, githubPend
251
318
  pendingDraft = await githubReviewRepo.getById(matchingRecord.id);
252
319
  } else {
253
320
  // New draft from GitHub - create new record
254
- // Query GitHub for the actual state of old pending records
255
- for (const oldRecord of existingPendingRecords) {
256
- let actualState = 'dismissed'; // Default if we can't determine
257
- let githubReviewData = null;
258
-
259
- // On the GraphQL path the node id is the canonical identifier; on
260
- // the REST path the numeric id (`github_review_id`) is the only
261
- // value we may have. Run the lookup whenever we have either —
262
- // otherwise mark the record as dismissed without querying.
263
- const oldLookupId = oldRecord.github_node_id || oldRecord.github_review_id;
264
- if (githubClient && (oldRecord.github_node_id || oldRecord.github_review_id)) {
265
- try {
266
- // prContext carries the REST review id when available. The
267
- // GraphQL path ignores it. The github_review_id column holds
268
- // the numeric REST id we received when the draft was created.
269
- const reviewPrContext = prContext
270
- ? { ...prContext, reviewId: oldRecord.github_review_id }
271
- : null;
272
- githubReviewData = await githubClient.getReviewById(oldLookupId, reviewPrContext);
273
-
274
- if (githubReviewData) {
275
- // Map GitHub state to our local state
276
- // GitHub states: PENDING, APPROVED, CHANGES_REQUESTED, COMMENTED, DISMISSED
277
- // Our states: local, pending, submitted, dismissed
278
- if (githubReviewData.state === 'PENDING') {
279
- // This shouldn't happen (we have a different pending review now), but handle it
280
- actualState = 'pending';
281
- } else if (githubReviewData.state === 'DISMISSED') {
282
- actualState = 'dismissed';
283
- } else {
284
- // APPROVED, CHANGES_REQUESTED, COMMENTED all mean it was submitted
285
- actualState = 'submitted';
286
- }
287
- logger.debug(`Old review ${oldLookupId} actual state from GitHub: ${githubReviewData.state} -> ${actualState}`);
288
- } else {
289
- // Review not found on GitHub - treat as dismissed
290
- logger.debug(`Old review ${oldLookupId} not found on GitHub, marking as dismissed`);
291
- actualState = 'dismissed';
292
- }
293
- } catch (error) {
294
- // On error, default to dismissed (most likely scenario)
295
- logger.warn(`Error querying GitHub for old review ${oldLookupId}: ${error.message}, marking as dismissed`);
296
- actualState = 'dismissed';
297
- }
298
- }
299
-
300
- // Update the old record with the actual state and submitted_at if available
301
- const updateData = { state: actualState };
302
- if (actualState === 'submitted' && githubReviewData?.submittedAt) {
303
- updateData.submitted_at = githubReviewData.submittedAt;
304
- }
305
- await githubReviewRepo.update(oldRecord.id, updateData);
306
- }
307
-
308
321
  pendingDraft = await githubReviewRepo.create(reviewId, {
309
322
  github_review_id: String(githubPendingReview.databaseId),
310
323
  github_node_id: githubPendingReview.id,
@@ -403,6 +416,10 @@ router.get('/api/pr/:owner/:repo/:number', async (req, res) => {
403
416
  githubClient,
404
417
  { owner: repoOwner, repo: repoName, prNumber }
405
418
  );
419
+ } else {
420
+ await reconcileStalePendingRecords(githubReviewRepo,
421
+ await githubReviewRepo.findPendingByReviewId(review.id), githubClient,
422
+ { owner: repoOwner, repo: repoName, prNumber });
406
423
  }
407
424
  } catch (githubError) {
408
425
  // Log the error but don't fail the request - draft info is supplementary
@@ -1051,6 +1068,10 @@ router.get('/api/pr/:owner/:repo/:number/github-drafts', async (req, res) => {
1051
1068
  githubClient,
1052
1069
  { owner, repo, prNumber }
1053
1070
  );
1071
+ } else {
1072
+ await reconcileStalePendingRecords(githubReviewRepo,
1073
+ await githubReviewRepo.findPendingByReviewId(review.id), githubClient,
1074
+ { owner, repo, prNumber });
1054
1075
  }
1055
1076
  } catch (githubError) {
1056
1077
  // Log the error but don't fail the request - return local data only
@@ -1460,6 +1481,48 @@ router.get('/api/file-content-original/:fileName(*)', async (req, res) => {
1460
1481
  }
1461
1482
  });
1462
1483
 
1484
+ // Publication actions are PR-only. Local reviews have no host identity.
1485
+ router.get('/api/reviews/:id/submissions', async (req, res) => {
1486
+ try {
1487
+ const db = req.app.get('db');
1488
+ const review = await new ReviewRepository(db).getReview(Number(req.params.id));
1489
+ if (!review) return res.status(404).json({ error: 'Review not found' });
1490
+ if (!review.pr_number || !review.repository) return res.status(400).json({ error: 'Review history is only available in PR mode' });
1491
+ res.json({ submissions: await listSubmissions(db, review.id) });
1492
+ } catch (error) {
1493
+ logger.error('Error loading review history:', error);
1494
+ res.status(500).json({ error: 'Failed to load review history' });
1495
+ }
1496
+ });
1497
+
1498
+ router.post('/api/reviews/:id/comments/:commentId/update-on-github', async (req, res) => {
1499
+ try {
1500
+ const db = req.app.get('db');
1501
+ const comment = await new CommentRepository(db).getComment(Number(req.params.commentId), 'user');
1502
+ if (!comment || comment.review_id !== Number(req.params.id)) return res.status(404).json({ error: 'Comment not found' });
1503
+ const review = await new ReviewRepository(db).getReview(comment.review_id);
1504
+ if (!review?.pr_number || !review.repository) return res.status(400).json({ error: 'Updating on GitHub is only available in PR mode' });
1505
+ const [owner, repo] = review.repository.split('/');
1506
+ // Reuse the PR-aware resolver, including recorded alt-host evidence.
1507
+ const resolved = await resolveBindingForRequest({ app: req.app, params: { number: String(review.pr_number) } }, review.repository);
1508
+ if (!resolved) return res.status(401).json({ error: 'GitHub token not configured' });
1509
+ const updated = await updatePostedComment(db, { commentId: comment.id, owner, repo,
1510
+ pull_number: review.pr_number, githubClient: new GitHubClient(resolved.binding) },
1511
+ reviewId => broadcastReviewEvent(reviewId, { type: 'review:comments_changed' }, { sourceClientId: req.get('X-Client-Id') }));
1512
+ res.json({ success: true, comment: updated });
1513
+ } catch (error) {
1514
+ logger.error('Error updating posted comment:', error);
1515
+ const code = error.code === 'unresolved_identity' ? 'unresolved_identity'
1516
+ : error.status === 404 || error.code === 'not_found' ? 'not_found_on_github'
1517
+ : [403, 422].includes(error.status) || error.code === 'forbidden' ? 'forbidden' : 'update_failed';
1518
+ const status = error.status || (code === 'unresolved_identity' ? 409 : code === 'not_found_on_github' ? 404 : code === 'forbidden' ? 403 : 500);
1519
+ const message = code === 'not_found_on_github' ? 'The host could not find this comment. Nothing was posted.'
1520
+ : code === 'forbidden' ? 'The host refused this update. Check your permissions or whether the conversation is locked. Nothing was posted.'
1521
+ : error.message;
1522
+ res.status(status).json({ error: message, code, review_url: error.review_url });
1523
+ }
1524
+ });
1525
+
1463
1526
  /**
1464
1527
  * Submit review to GitHub
1465
1528
  */
@@ -1533,7 +1596,7 @@ router.post('/api/pr/:owner/:repo/:number/submit-review', async (req, res) => {
1533
1596
  commit_sha,
1534
1597
  is_file_level
1535
1598
  FROM comments
1536
- WHERE review_id = ? AND source = 'user' AND status = 'active'
1599
+ WHERE review_id = ? AND source = 'user' AND ${CommentRepository.pendingCommentSql('comments')}
1537
1600
  ORDER BY file, line_start
1538
1601
  `, [review.id]);
1539
1602
 
@@ -1606,21 +1669,28 @@ router.post('/api/pr/:owner/:repo/:number/submit-review', async (req, res) => {
1606
1669
  prMetadata
1607
1670
  });
1608
1671
 
1609
- if (event === 'DRAFT') {
1610
- // Delegate to createDraftReviewGraphQL (handles both new and existing drafts)
1611
- githubReview = await githubClient.createDraftReviewGraphQL(
1612
- prNodeId, body || '', graphqlComments, existingDraft?.id, submitPrContext
1613
- );
1614
- // When adding to an existing draft, use the existing URL and include prior comments in total count
1615
- if (existingDraft) {
1616
- githubReview.html_url = githubReview.html_url || existingDraft.url;
1617
- githubReview.comments_count = existingDraft.comments.totalCount + githubReview.comments_count;
1672
+ try {
1673
+ if (event === 'DRAFT') {
1674
+ // Delegate to createDraftReviewGraphQL (handles both new and existing drafts)
1675
+ githubReview = await githubClient.createDraftReviewGraphQL(
1676
+ prNodeId, body || '', graphqlComments, existingDraft?.id, submitPrContext
1677
+ );
1678
+ // When adding to an existing draft, use the existing URL and include prior comments in total count
1679
+ if (existingDraft) {
1680
+ githubReview.html_url = githubReview.html_url || existingDraft.url;
1681
+ githubReview.comments_count = existingDraft.comments.totalCount + githubReview.comments_count;
1682
+ }
1683
+ } else {
1684
+ // For non-drafts, create/use review, add comments, and submit
1685
+ githubReview = await githubClient.createReviewGraphQL(
1686
+ prNodeId, event, body || '', graphqlComments, existingDraft?.id, submitPrContext
1687
+ );
1618
1688
  }
1619
- } else {
1620
- // For non-drafts, create/use review, add comments, and submit
1621
- githubReview = await githubClient.createReviewGraphQL(
1622
- prNodeId, event, body || '', graphqlComments, existingDraft?.id, submitPrContext
1623
- );
1689
+ } catch (error) {
1690
+ await recordRetainedSubmission(db, error, {
1691
+ reviewId: review.id, body, existingDraft, sourceRows: comments, sentComments: graphqlComments
1692
+ }, () => broadcastReviewEvent(review.id, { type: 'review:comments_changed' }));
1693
+ throw error;
1624
1694
  }
1625
1695
 
1626
1696
  // ID storage strategy:
@@ -1629,11 +1699,6 @@ router.post('/api/pr/:owner/:repo/:number/submit-review', async (req, res) => {
1629
1699
  // - reviewData JSON -> uses 'github_node_id' key for the GraphQL node ID
1630
1700
  // - reviews.review_id -> legacy column, no longer written (github_reviews table has taken over)
1631
1701
  const githubNodeId = String(githubReview.id); // GraphQL methods return node IDs
1632
- // Use databaseId from the mutation response, or fall back to existingDraft's databaseId
1633
- const githubDatabaseId = githubReview.databaseId
1634
- ? String(githubReview.databaseId)
1635
- : existingDraft ? String(existingDraft.databaseId) : null;
1636
-
1637
1702
  // Build review metadata for database storage
1638
1703
  const reviewData = {
1639
1704
  github_node_id: githubNodeId,
@@ -1665,34 +1730,20 @@ router.post('/api/pr/:owner/:repo/:number/submit-review', async (req, res) => {
1665
1730
  reviewData: reviewData
1666
1731
  });
1667
1732
 
1668
- // Create a github_reviews record to track this submission
1669
- const githubReviewRepo = new GitHubReviewRepository(db);
1670
- await githubReviewRepo.create(review.id, {
1671
- github_review_id: githubDatabaseId,
1672
- github_node_id: githubNodeId,
1673
- state: event === 'DRAFT' ? 'pending' : 'submitted',
1674
- event: event === 'DRAFT' ? null : event,
1675
- body: body || '',
1676
- submitted_at: event === 'DRAFT' ? null : new Date().toISOString(),
1677
- github_url: githubReview.html_url
1733
+ await recordReviewSubmission(db, {
1734
+ reviewId: review.id, event, body, githubReview, existingDraft,
1735
+ sourceRows: comments, sentComments: graphqlComments,
1736
+ postedComments: githubReview.postedComments
1678
1737
  });
1679
1738
 
1680
- console.log(`${event === 'DRAFT' ? 'Draft review created' : 'Review submitted'} successfully: ${githubReview.html_url}${event === 'DRAFT' ? ' (Review ID: ' + githubReview.id + ')' : ''}`);
1681
-
1682
- // Update comments table to mark submitted comments
1683
- const commentStatus = event === 'DRAFT' ? 'draft' : 'submitted';
1684
- const commentUpdateTime = new Date().toISOString();
1685
- for (const comment of comments) {
1686
- await run(db, `
1687
- UPDATE comments
1688
- SET status = ?, updated_at = ?
1689
- WHERE id = ?
1690
- `, [commentStatus, commentUpdateTime, comment.id]);
1691
- }
1692
-
1693
1739
  // Commit transaction
1694
1740
  await run(db, 'COMMIT');
1695
1741
 
1742
+ // Comment statuses changed (active -> submitted/draft): tell other open
1743
+ // tabs to reload. Only after COMMIT, so they never reload rolled-back
1744
+ // state. The submitting tab refetches itself and skips its own echo.
1745
+ broadcastReviewEvent(review.id, { type: 'review:comments_changed' }, { sourceClientId: req.get('X-Client-Id') });
1746
+
1696
1747
  // Send success response after all database operations complete.
1697
1748
  // Use the configured remote-host display name (e.g. "Meteorite")
1698
1749
  // instead of the literal "GitHub". Resolve via the binding repository
@@ -2886,5 +2937,6 @@ module.exports = router;
2886
2937
  // absent) can be exercised directly without spinning up the route.
2887
2938
  module.exports._internals = {
2888
2939
  syncPendingDraftFromGitHub,
2940
+ reconcileStalePendingRecords,
2889
2941
  resolveBindingForRequest
2890
2942
  };