Skip to content

fix(whatsapp): persist attempt IDs and lock tail - #1399

Merged
khaira777 merged 3 commits into
mainfrom
fm/flocafe-fix-whatsapp-attempt-ids-and-locks
Oct 29, 2026
Merged

khaira777 merged 3 commits into
mainfrom
fm/flocafe-fix-whatsapp-attempt-ids-and-locks

Conversation

@khaira777

Copy link
Copy Markdown
Contributor

Intent

Fix the three WhatsApp service release-review defects (F2: persist every submitted WhatsApp attempt external ID in whatsapp_message_attempts with migration 121 so late ACKs resolve across retries and restarts; F3: enforce RATE_LIMIT_MIN_GAP_MS on retries in isOverRateLimit while still excluding excludeMessageId from the 1-hour message count; F4: keep per-recipient sendLocks queue tail chained onto previous when a waiting send cancels or aborts) and clarify Google Drive retention_pending status/toast/docs so a successful backup upload with pending retention cleanup does not show an alarming red error line or error toast.

What Changed

  • Persist submitted outbound WhatsApp attempt external IDs in whatsapp_message_attempts (added in migration 121 and backfilled during migrations, data-only restores, and JSON database imports) so findMessageByExternalId() and advanceStatus() resolve late ACKs across retries and restarts.
  • Enforce RATE_LIMIT_MIN_GAP_MS on message retries in isOverRateLimit() against in-memory and persisted sent_at/typing_at timestamps while still excluding excludeMessageId from the 1-hour message count, and keep the per-recipient sendLocks queue tail chained onto previous in sendMessageWithLock() when a waiting send cancels or aborts.
  • Display Google Drive retention_pending status as an amber notice in DatabaseSettingsTab instead of a red last_error line, show a neutral toast when a manual backup finishes in retention_pending in SettingsPage, and document the two-step backup/retention flow and WhatsApp retry/lock behavior in docs/architecture/cloud-integrations.md.

Risk Assessment

✅ Low: All Round 1 findings (schema migration 121 isolation and restore/import backfill, attempt external_message_id COALESCE ordering, and synchronous sendLocks cleanup after previous settles) have been cleanly resolved and verified against the full diff and user intent.

Testing

Ran focused schema, upgrade-path, backup/restore, database-tools, WhatsApp service, and Google Drive suites, then stood up the live Express server and statically exported frontend in an isolated environment and drove all four scenarios end-to-end with Playwright Chromium, capturing SQLite/API state and screenshots of both the WhatsApp Sent table and the Settings Backup & Data Google Drive retention_pending UI and toast.

  • Live validation: ✅ go - 4 of 4 scenarios driven live against the product
Scenario Result Live Evidence
F2: Outbound WhatsApp send (Attempt 1) that times out and is retried (Attempt 2) persists both external attempt IDs in whatsapp_message_attempts (with v121 migration and import/restore backfill), and… ✅ pass live ~/.no-mistakes/evidence/01M62KE6W1BYN7XSMCXBWTP3TA/whatsapp-late-ack-resolved.png; ~/.no-mistakes/evidence/01M62KE6W1BYN7XSMCXBWTP3TA/whatsapp-scenarios-live-ev…
F3: Retrying a failed outbound WhatsApp message within RATE_LIMIT_MIN_GAP_MS (30s) is rejected with HTTP 400 rate_limited, while retrying after the 30s gap succeeds (HTTP 200) and excludes its own mes… ✅ pass live ~/.no-mistakes/evidence/01M62KE6W1BYN7XSMCXBWTP3TA/whatsapp-scenarios-live-evidence.json; npm run test:whatsapp-service
F4: When Send A is in flight to a recipient, waiting Send B aborts/cancels while queued on sendLocks, and Send C is requested for the same recipient, Send C remains chained behind Send A and does not… ✅ pass live ~/.no-mistakes/evidence/01M62KE6W1BYN7XSMCXBWTP3TA/whatsapp-scenarios-live-evidence.json; npm run test:whatsapp-service
Google Drive retention_pending status and manual backup completion render an amber informational notice and neutral toast while keeping Last backed up status green, without rendering a red text-red-60… ✅ pass live ~/.no-mistakes/evidence/01M62KE6W1BYN7XSMCXBWTP3TA/google-drive-retention-pending-ui.png; ~/.no-mistakes/evidence/01M62KE6W1BYN7XSMCXBWTP3TA/whatsapp-scenarios-…

Live WhatsApp Sent UI showing Attempt 1 late delivered/read ACK resolved after Attempt 2 retry and service restart, plus F3 retry and F4 serialized sends
Live Settings Backup & Data UI showing Google Drive retention_pending amber status notice, green Last backed up status, and non-error toast

Evidence: Live HTTP API, SQLite state, rate-limit, lock-ordering, and browser DOM evidence across all 4 scenarios
{
  "scenario1_f2_attempt_persistence": {
    "messageId": 1,
    "persistedAttempts": [
      {
        "message_id": 1,
        "external_message_id": "ext-live-attempt-1"
      },
      {
        "message_id": 1,
        "external_message_id": "ext-live-attempt-2"
      }
    ],
    "statusAfterTimeout": {
      "status": "failed",
      "error": "ack_timeout",
      "external_message_id": "ext-live-attempt-1"
    },
    "statusAfterLateAttempt1DeliveredAck": {
      "status": "delivered",
      "error": null,
      "failed_at": null,
      "delivered_at": "2026-10-29 02:29:47"
    },
    "statusAfterLateAttempt1ReadAck": {
      "status": "read",
      "error": null,
      "delivered_at": "2026-10-29 02:29:47",
      "read_at": "2026-10-29 02:29:47"
    },
    "importedBackfillRow": {
      "message_id": 9901,
      "external_message_id": "ext-imported-attempt-9901",
      "created_at": "2026-10-28 10:00:05"
    }
  },
  "scenario2_f3_retry_rate_limit": {
    "rateCheckWithinMinGap": {
      "limited": true,
      "retryAfterMs": 24963
    },
    "retryHttpWithinMinGap": {
      "status": 400,
      "body": {
        "error": "Rate limit reached for this number.",
        "reason": "rate_limited",
        "messageId": 9905
      }
    },
    "rateCheckAfterGapWithExcludeMessageId": {
      "limited": false
    },
    "rateCheckAfterGapWithoutExcludeMessageId": {
      "limited": true
    },
    "retryHttpAfterMinGap": {
      "status": 200,
      "body": {
        "ok": true,
        "messageId": 9905
      }
    }
  },
  "scenario3_f4_send_locks_abort_serialization": {
    "cancelledWaiterResult": {
      "ok": false,
      "error": "WhatsApp is shutting down.",
      "reason": "send_failed"
    },
    "eventsWhileSendAInFlightAfterSendBAborted": [
      "presence_subscribe",
      "start:Live-F4-Send-A"
    ],
    "finalOrderedEvents": [
      "presence_subscribe",
      "start:Live-F4-Send-A",
      "end:Live-F4-Send-A",
      "presence_subscribe",
      "start:Live-F4-Send-C",
      "end:Live-F4-Send-C"
    ],
    "sendAStatus": 200,
    "sendCStatus": 200
  },
  "scenario4_google_drive_retention_pending_ui": {
    "redErrorLinesForRetentionPending": 0,
    "amberPendingLinesCount": 1,
    "toastVisible": true,
    "toastText": "Backup uploaded, but automatic retention cleanup is pending and will retry automatically.",
    "driveStatusFromApi": {
      "configured": true,
      "secure_storage_available": true,
      "connected": true,
      "auth_state": "connected",
      "account_email": "[email protected]",
      "frequency": "daily",
      "retention_count": 7,
      "destination_folder_id": "folder-live",
      "destination_folder_name": "flocafe_backups",
      "last_backup_at": "2026-10-29T02:29:50.251Z",
      "last_backup_status": "success",
      "last_error": "retention_pending",
      "last_attempt_at": "2026-10-29T02:29:50.211Z",
      "last_success_at": "2026-10-29T02:29:50.251Z",
      "last_success_kind": "manual",
      "next_retry_at": "2026-10-29T02:34:50.252Z",
      "retention_status": "pending",
      "revoke_status": null,
      "warning_acknowledged": true,
      "warning_required": false,
      "job": {
        "id": "adc419b2-3920-41b9-82ba-4c970808acc7",
        "operation": "backup",
        "kind": "manual",
        "state": "retention_pending",
        "remote_id": "remote-live-backup-1",
        "bytes_sent": 991232,
        "total_bytes": 991232,
        "updated_at": "2026-10-29 02:29:50"
      }
    }
  }
}
- Outcome: 🔧 2 issues found → no changes applied ✅ across 2 runs (51m9s)

Pipeline

Updates from git push no-mistakes

✅ **intent** - passed

✅ No issues found.

✅ **Rebase** - passed

✅ No issues found.

🔧 **Review** - 3 issues found → auto-fixed ✅
  • 🚨 main/db.ts:8556 - Adding whatsapp_message_attempts and idx_whatsapp_message_attempts_message_id inside createWhatsAppSchema() (main/db.ts:8556-8564) retroactively modifies migration v29 (main/db.ts:5106). When isHealthyDatabaseFile() (main/db.ts:1099) validates any real pre-v121 database or backup (29 <= schemaVersion <= 120) via getRecoverySchemaReference(schemaVersion) -> buildIdealSchemaDb(schemaVersion) (main/db.ts:1030-1051), the reference schema for v29..v120 now requires whatsapp_message_attempts (and for 96 <= schemaVersion <= 120, migration v96's ALTER TABLE whatsapp_messages RENAME TO whatsapp_messages_v95 rewrites whatsapp_message_attempts's foreign key in SQLite to REFERENCES "whatsapp_messages_v95"(id) without running migration 121), causing isHealthyDatabaseFile() to reject valid pre-v121 databases and backups. Remove whatsapp_message_attempts and idx_whatsapp_message_attempts_message_id from createWhatsAppSchema() (main/db.ts:8556-8564) so migration 121 (main/db.ts:7790-7838) is the sole creator of the table and index, and remove the now-unreachable whatsapp_messages_v95 repair branch in main/db.ts:7793-7815. Also fix the sibling sites for this migration: (1) main/db.ts:7826 - select TRIM(external_message_id) in the migration 121 backfill so whitespace-padded IDs match findMessageByExternalId()'s trimmed lookup (main/services/whatsapp.ts:993, 1005); (2) main/db.ts:4339 (dataOnlyRestore) and main/routes/database.ts:456 (POST /api/db/import replace mode) - when whatsapp_messages is replaced from a pre-v121 backup or export that does not include whatsapp_message_attempts while foreign_keys = OFF, clear whatsapp_message_attempts (and backfill from restored whatsapp_messages.external_message_id) so pre-existing rows in whatsapp_message_attempts do not become orphaned and fail getForeignKeyViolationKeys(currentDb) (main/db.ts:4373) or PRAGMA foreign_key_check (main/routes/database.ts:575); (3) tests/backup-restore-production.test.ts:976 and frontend/e2e/database-export-import.spec.ts:214 - update the hardcoded schema version 120 assertion/fixture metadata to 121.
  • ⚠️ main/services/whatsapp.ts:907 - In recordMessageAttemptExternalId (main/services/whatsapp.ts:893-910), trimmed is guaranteed non-empty (if (!trimmed) return; at line 898), so SET external_message_id = COALESCE(?, external_message_id) with .run(trimmed, messageId) always overwrites whatsapp_messages.external_message_id with trimmed. If an earlier send attempt aborts while socket.sendMessage is in flight (main/services/whatsapp.ts:2447-2459), a subsequent retry completes and sets whatsapp_messages.external_message_id = 'ext-2' (main/services/whatsapp.ts:2470), and the aborted attempt's socket.sendMessage promise later resolves in the background, its .then(...) callback at main/services/whatsapp.ts:2453 calls recordMessageAttemptExternalId(messageId, 'ext-1') and overwrites whatsapp_messages.external_message_id back to 'ext-1'. Use COALESCE(external_message_id, ?) in main/services/whatsapp.ts:907 (normal non-aborted completion already updates whatsapp_messages.external_message_id via updateMessageRow at main/services/whatsapp.ts:2470), and remove the duplicate recordMessageAttemptExternalId call at main/services/whatsapp.ts:2463-2465 (already invoked in .then(...) at main/services/whatsapp.ts:2453).
  • ⚠️ main/services/whatsapp.ts:2122 - In sendMessageWithLock (main/services/whatsapp.ts:2050-2126), current is previous.catch(() => {}).then(() => ownDone) and map cleanup is deferred to void current.finally(...) (main/services/whatsapp.ts:2122-2126). Even when previous has already settled before finally runs, current.finally(...) executes on a later microtask tick after await sendMessage(...) / await retryMessage(...) resolves to its caller, leaving sendLocks.size > 0 synchronously after completion. If initFromDb() (main/services/whatsapp.ts:3577) runs immediately after a send completes and disconnects, sendLocks.size === 0 evaluates to false and skips includeAllUnfinished in sweepAckTimeouts(). Track whether previous has settled (let previousSettled = false; set via previous.then(() => { previousSettled = true; }, () => { previousSettled = true; })): in finally, after releaseOwn(), delete req.phoneE164 from sendLocks synchronously when previousSettled && sendLocks.get(req.phoneE164) === current, and only defer cleanup to current.finally(...) when the waiter exited before previous settled.

🔧 Fix applied.
✅ Re-checked - no issues remain.

🔧 **Test** - 2 issues found → no changes applied ✅
  • ⚠️ The Test agent did not finish within its invocation budget. Reported: agent run tests timed out after 30m0s: agent last produced output 693ms ago (288 observed); agent reported: antigravity parse events: context deadline exceeded. This is a budget or provider-slowness cut, not a code failure. Re-running the same request costs another full budget, so no further attempt is made automatically. If this repository's targeted tests or evidence gathering routinely approach the default 30m0s, raise test_agent_timeout in global config. Respond with fix to spend another budget: a repair turn runs only for selected findings other than this budget cut, then validation re-runs. Or abort and retry after raising the budget.
  • 🚨 Approval is refused: the run worktree at ~/.no-mistakes/worktrees/de2296f2e6f8/01M62KE6W1BYN7XSMCXBWTP3TA holds work no Test turn validated, and the steps after Test would commit and publish it. It holds uncommitted changes to main/db.ts (inspect with git -C ~/.no-mistakes/worktrees/de2296f2e6f8/01M62KE6W1BYN7XSMCXBWTP3TA status and git -C ~/.no-mistakes/worktrees/de2296f2e6f8/01M62KE6W1BYN7XSMCXBWTP3TA diff). Respond with fix to validate it, or abort.

🔧 No changes applied.
✅ Re-checked - no issues remain.

  • Live validation: ✅ go - 4 of 4 scenarios driven live against the product
Scenario Result Live Evidence
F2: Outbound WhatsApp send (Attempt 1) that times out and is retried (Attempt 2) persists both external attempt IDs in whatsapp_message_attempts (with v121 migration and import/restore backfill), and… ✅ pass live ~/.no-mistakes/evidence/01M62KE6W1BYN7XSMCXBWTP3TA/whatsapp-late-ack-resolved.png; ~/.no-mistakes/evidence/01M62KE6W1BYN7XSMCXBWTP3TA/whatsapp-scenarios-live-ev…
F3: Retrying a failed outbound WhatsApp message within RATE_LIMIT_MIN_GAP_MS (30s) is rejected with HTTP 400 rate_limited, while retrying after the 30s gap succeeds (HTTP 200) and excludes its own mes… ✅ pass live ~/.no-mistakes/evidence/01M62KE6W1BYN7XSMCXBWTP3TA/whatsapp-scenarios-live-evidence.json; npm run test:whatsapp-service
F4: When Send A is in flight to a recipient, waiting Send B aborts/cancels while queued on sendLocks, and Send C is requested for the same recipient, Send C remains chained behind Send A and does not… ✅ pass live ~/.no-mistakes/evidence/01M62KE6W1BYN7XSMCXBWTP3TA/whatsapp-scenarios-live-evidence.json; npm run test:whatsapp-service
Google Drive retention_pending status and manual backup completion render an amber informational notice and neutral toast while keeping Last backed up status green, without rendering a red text-red-60… ✅ pass live ~/.no-mistakes/evidence/01M62KE6W1BYN7XSMCXBWTP3TA/google-drive-retention-pending-ui.png; ~/.no-mistakes/evidence/01M62KE6W1BYN7XSMCXBWTP3TA/whatsapp-scenarios-…
  • npm run test:whatsapp-schema
  • npm run test:whatsapp-service
  • npm run test:upgrade-path
  • npm run test:schema-health
  • npm run test:migration-registry
  • node tests/run-electron-node-test.cjs tests/backup-restore-production.test.ts
  • npm run test:database-tools-api
  • npm run test:google-drive
  • Live Express (:3001) + Playwright Chromium verification driving /api/whatsapp/send, /api/whatsapp/messages/:id/retry, /whatsapp Sent UI, and /settings?tab=data Google Drive retention_pending backup flow
✅ **Document** - passed

✅ No issues found.

✅ **Lint** - passed

✅ No issues found.

✅ **Push** - passed

✅ No issues found.

@coderabbitai

coderabbitai Bot commented Oct 29, 2026

Copy link
Copy Markdown
Contributor

Important

Review skipped

Auto reviews are disabled on this repository. Please check the settings in the CodeRabbit UI or the .coderabbit.yaml file in this repository. To trigger a single review, invoke the @coderabbitai review command.

Run configuration

You can disable this status message by setting the reviews.review_status to false in the CodeRabbit configuration file.

Use the checkbox below for a quick retry:

  • 🔍 Trigger review
  • Autofix · Keep fixing CodeRabbit findings and required CI, and resolving merge conflicts

Thanks for using CodeRabbit! It's free for OSS, and your support helps us grow. If you like it, consider giving us a shout-out.

❤️ Share

Comment @coderabbitai help to get the list of available commands.

@khaira777 khaira777 changed the title fix(whatsapp): persist attempt IDs, harden send locks, and clarify Drive retention status fix(whatsapp): persist attempt IDs and lock tail Oct 29, 2026
@qodo-code-review

Copy link
Copy Markdown

PR Summary by Qodo

Persist WhatsApp attempt IDs and harden retries and send locks

🐞 Bug fix 🧪 Tests 📝 Documentation 🕐 40+ Minutes

Grey Divider

AI Description

• Persist WhatsApp attempt IDs so late ACKs resolve after retries, restores, and restarts.
• Enforce retry spacing and preserve per-recipient send order when waiting requests abort.
• Show pending Drive retention as a notice, with regression tests and updated documentation.
Diagram

sequenceDiagram
    actor Sender
    participant Queue as Send queue
    participant Limit as Rate limiter
    participant Socket as WA socket
    participant Store as SQLite attempts
    participant Ack as ACK handler
    Sender->>Queue: Submit or retry
    Queue->>Limit: Check spacing and cap
    Limit-->>Queue: Allow send
    Queue->>Socket: Send in order
    Socket-->>Queue: Return attempt ID
    Queue->>Store: Persist attempt ID
    Socket-->>Ack: Deliver late ACK
    Ack->>Store: Look up attempt ID
    Store-->>Ack: Return message row
    Ack->>Store: Advance status
Loading
High-Level Assessment

Keep the existing message row for retries and store each external attempt ID in a linked table. This supports indexed late-ACK lookup without changing message identity or the established retry workflow; storing IDs only in memory cannot survive restarts.

Files changed (11) +632 / -67

Bug fix (5) +201 / -30
page.tsxUse a neutral toast for pending retention +1/-1

Use a neutral toast for pending retention

• A manual backup that uploaded successfully but awaits retention cleanup now shows a neutral toast rather than an error toast.

frontend/src/app/(dashboard)/settings/page.tsx

DatabaseSettingsTab.tsxPresent pending retention as an amber notice +13/-7

Present pending retention as an amber notice

• Suppresses the red last-error line for retention_pending and shows one amber notice when the job, error code, or retention status indicates pending cleanup.

frontend/src/components/settings/DatabaseSettingsTab.tsx

db.tsAdd and backfill WhatsApp attempt IDs in schema v121 +63/-0

Add and backfill WhatsApp attempt IDs in schema v121

• Adds the indexed attempt table with a cascading message reference and backfills existing outbound external IDs. Also backfills attempts during data-only restores and handles an existing table with incompatible foreign keys.

main/db.ts

database.tsBackfill attempts after JSON database imports +21/-0

Backfill attempts after JSON database imports

• Tracks imported or cleared WhatsApp messages and backfills their attempt IDs within the import transaction. Resets attempts when overwritten messages have no corresponding imported attempt data.

main/routes/database.ts

whatsapp.tsPersist send attempts and preserve retry ordering +103/-22

Persist send attempts and preserve retry ordering

• Records outbound attempt IDs and resolves late ACKs through persisted attempts. Applies minimum-gap checks to retries using memory and database timestamps, while chaining send locks across aborted waiters.

main/services/whatsapp.ts

Tests (5) +404 / -25
database-export-import.spec.tsUse schema version 121 in import fixture +1/-1

Use schema version 121 in import fixture

• Advances the contaminated JSON import fixture to the new schema version.

frontend/e2e/database-export-import.spec.ts

backup-restore-production.test.tsExpect schema v121 after recovery +2/-2

Expect schema v121 after recovery

• Updates the backup-recovery upgrade assertion to expect the new schema version.

tests/backup-restore-production.test.ts

upgrade-path.test.tsVerify v121 attempt-table migration +78/-0

Verify v121 attempt-table migration

• Tests creation and outbound backfill of attempt records from a v120 database, including trimmed IDs, timestamp selection, and a clean health check.

tests/upgrade-path.test.ts

whatsapp-schema.test.tsTest attempt-table constraints and cascade +115/-22

Test attempt-table constraints and cascade

• Checks the new table's columns and index, external-ID uniqueness, and deletion of attempts when a parent message is deleted.

tests/whatsapp-schema.test.ts

whatsapp-service.test.tsCover late ACKs, retry spacing, and aborted waiters +208/-0

Cover late ACKs, retry spacing, and aborted waiters

• Adds regressions for ACK resolution after a retry and service restart, retry minimum-gap enforcement with hourly-count exclusion, and send ordering after a waiting request aborts.

tests/whatsapp-service.test.ts

Documentation (1) +27 / -12
cloud-integrations.mdDocument retention and WhatsApp retry behavior +27/-12

Document retention and WhatsApp retry behavior

• Explains why a completed Drive upload remains successful when retention cleanup is pending. Documents persisted WhatsApp attempt IDs, retry spacing, and send-lock ordering.

docs/architecture/cloud-integrations.md

@qodo-code-review

qodo-code-review Bot commented Oct 29, 2026 •

Copy link
Copy Markdown

Code Review by Qodo

🐞 Bugs (0) 📘 Rule violations (0) 🔗 Cross-repo conflicts (0) 📜 Skill insights (0)

Grey Divider


Remediation recommended

1. Retrying a send that just failed is wrongly rate-limited ✗ Dismissed
Description
isOverRateLimit uses MAX(COALESCE(sent_at, typing_at)) across every outbound row for a phone,
including failed attempts and excludeMessageId, even though sendMessageInternal writes
typing_at before socket submission and retains it on failure. When a send is canceled during
typing, blocked mid-typing, or rejected by the socket, an immediate retry of that row or a new
manual send reaches the minimum-gap check and is rejected as rate_limited for up to 30 seconds.
Code

main/services/whatsapp.ts[R689-697]

+    const lastRow = db
+      .prepare(`
+        SELECT MAX(COALESCE(sent_at, typing_at)) AS last_ts
+        FROM whatsapp_messages
+        WHERE phone_e164 = ?
+          AND direction = 'outbound'
+          AND (sent_at IS NOT NULL OR typing_at IS NOT NULL)
+      `)
+      .get(phoneE164) as { last_ts: string | null } | undefined;
Relevance

●● Moderate

Intent and tests enforce retry min-gap, but failed typing attempts may be incorrectly treated as
sends.

PR-#1384

ⓘ Recommendations generated based on similar findings in past PRs

Evidence
The send path writes typing_at before abortableDelay and socket.sendMessage, and failure
leaves that timestamp on the row. The next request runs the rate check before resetting a retry row;
its persisted lookup counts that row’s typing_at even if the attempt never reached the socket,
whereas the existing lastSendByPhone timestamp is set only after successful submission.

main/services/whatsapp.ts[686-710]
main/services/whatsapp.ts[2262-2275]
main/services/whatsapp.ts[2436-2461]
main/services/whatsapp.ts[2502-2510]
main/services/whatsapp.ts[688-709]
main/services/whatsapp.ts[2412-2427]
main/services/whatsapp.ts[2439-2462]
main/services/whatsapp.ts[2262-2279]

Agent prompt
The issue below was found during a code review. Follow the provided context and guidance below and implement a solution

## Issue description
The persisted minimum-gap lookup treats pre-submission typing on failed outbound rows as a completed send and can count the row being retried. This blocks retries and new manual sends after attempts that never reached the socket.

## Fix Focus Areas
- main/services/whatsapp.ts[686-710]
- main/services/whatsapp.ts[2439-2462]

## Recommended Fix
Make the persisted minimum-gap lookup use only attempts that were actually submitted, rather than pre-submission `typing_at` alone. Record or identify an actual-submission timestamp; possible filters include `sent_at IS NOT NULL` or `external_message_id IS NOT NULL OR status IN ('sent','delivered','read')`. Exclude failed rows without an external message ID, and apply `AND id != ?` for `excludeMessageId` when a retried row never reached the socket. Keep the in-memory `lastSendByPhone` check and the existing exclusion of the retried row from the hourly count.

ⓘ Copy this prompt and use it to remediate the issue with your preferred AI generation tools



Informational

2. Failures to save attempt IDs are silently swallowed ✗ Dismissed
Description
The socket.sendMessage continuation swallows errors from recordMessageAttemptExternalId in an
empty catch, leaving a failed attempt write without a diagnostic or retry. If the caller aborts
before the socket resolves, the parent-row update is also skipped; after a disconnect or restart
clears the in-memory external-ID map, a late ACK has no durable ID to resolve and the row can remain
failed.
Code

main/services/whatsapp.ts[R2466-2470]

+          if (extId) {
+            try {
+              recordMessageAttemptExternalId(messageId, extId);
+            } catch {}
+          }
Relevance

●●● Strong

Persistence failures undermine the PR’s explicit late-ACK durability goal; similar attempt-ID fixes
were accepted.

PR-#1384

ⓘ Recommendations generated based on similar findings in past PRs

Evidence
The empty catch suppresses failures from the attempt-table persistence path, which provides the
durable link between a retry’s external ID and its message row. abortable can finish before the
underlying socket operation, so an aborted signal can bypass the post-await parent-row update; once
the in-memory external-ID map is cleared on disconnect, neither that update nor a failed attempt
write is available for a late ACK lookup.

main/services/whatsapp.ts[2462-2474]
main/services/whatsapp.ts[893-910]
main/services/whatsapp.ts[2462-2483]
main/services/whatsapp.ts[301-350]
main/services/whatsapp.ts[893-909]
main/services/whatsapp.ts[992-1011]
main/services/whatsapp.ts[1653-1658]

Agent prompt
The issue below was found during a code review. Follow the provided context and guidance below and implement a solution

## Issue description
Errors from `recordMessageAttemptExternalId` after `socket.sendMessage` are silently discarded. If the caller has already aborted, the parent-row update may also be skipped, leaving a submitted external ID without a durable lookup or a diagnostic when the attempt write fails.

## Fix Focus Areas
- main/services/whatsapp.ts[2462-2475]
- main/services/whatsapp.ts[893-910]

## Recommended Fix
Replace the empty catch with non-fatal logging that includes the message ID and error, for example `console.warn('[WhatsApp] Failed to persist attempt external ID', { messageId, err });`. Retain failed attempt writes for a bounded retry, including when the caller has aborted, and ensure the active send path does not report durable attempt tracking when persistence has failed.

ⓘ Copy this prompt and use it to remediate the issue with your preferred AI generation tools


Grey Divider

Context sources
✅ Linked PRs:
  🌐 PR #39
  🌐 PR #34
✅ Compliance rules (platform): 5 rules
✅ Cross-repo context — repo relationships
Review mode: Auto: 🧠 Deep: Dense cross-cutting changes span migrations, retries, concurrency, restore paths, and UI behavior.

Grey Divider

Tip of the day
💡 Did you know, you can add REVIEW.md to your repo root and Qodo follows it on every PR

More tips ↗ | Customize Qodo ↗ | Qodo docs ↗

Grey Divider

Qodo Logo

Comment thread main/services/whatsapp.ts Resolved
Comment thread main/services/whatsapp.ts Resolved
@khaira777
khaira777 merged commit ab4b4c7 into main Oct 29, 2026
23 checks passed
@khaira777
khaira777 deleted the fm/flocafe-fix-whatsapp-attempt-ids-and-locks branch October 29, 2026 02:48
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

None yet

Projects

None yet

Development

Successfully merging this pull request may close these issues.

1 participant