You signed in with another tab or window. Reload to refresh your session.You signed out in another tab or window. Reload to refresh your session.You switched accounts on another tab or window. Reload to refresh your session.Dismiss alert
{{ message }}
Repository navigation
fix(whatsapp): persist attempt IDs and lock tail - #1399
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…
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…
🚨 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…
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…
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
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.
Comment @coderabbitai help to get the list of available commands.
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
Persist WhatsApp attempt IDs and harden retries and send locks
🐞 Bug fix🧪 Tests📝 Documentation🕐 40+ Minutes
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.
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.
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.
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.
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.
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.
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.
+ 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.
ⓘ 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.
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
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.
ⓘ 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.
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
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Add this suggestion to a batch that can be applied as a single commit.This suggestion is invalid because no changes were made to the code.Suggestions cannot be applied while the pull request is closed.Suggestions cannot be applied while viewing a subset of changes.Only one suggestion per line can be applied in a batch.Add this suggestion to a batch that can be applied as a single commit.Applying suggestions on deleted lines is not supported.You must change the existing code in this line in order to create a valid suggestion.Outdated suggestions cannot be applied.This suggestion has been applied or marked resolved.Suggestions cannot be applied from pending reviews.Suggestions cannot be applied on multi-line comments.Suggestions cannot be applied while the pull request is queued to merge.Suggestion cannot be applied right now. Please check back later.
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
whatsapp_message_attempts(added in migration 121 and backfilled during migrations, data-only restores, and JSON database imports) sofindMessageByExternalId()andadvanceStatus()resolve late ACKs across retries and restarts.RATE_LIMIT_MIN_GAP_MSon message retries inisOverRateLimit()against in-memory and persistedsent_at/typing_attimestamps while still excludingexcludeMessageIdfrom the 1-hour message count, and keep the per-recipientsendLocksqueue tail chained ontopreviousinsendMessageWithLock()when a waiting send cancels or aborts.retention_pendingstatus as an amber notice inDatabaseSettingsTabinstead of a redlast_errorline, show a neutral toast when a manual backup finishes inretention_pendinginSettingsPage, and document the two-step backup/retention flow and WhatsApp retry/lock behavior indocs/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.
Evidence: Live HTTP API, SQLite state, rate-limit, lock-ordering, and browser DOM evidence across all 4 scenarios
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- Addingwhatsapp_message_attemptsandidx_whatsapp_message_attempts_message_idinsidecreateWhatsAppSchema()(main/db.ts:8556-8564) retroactively modifies migration v29 (main/db.ts:5106). WhenisHealthyDatabaseFile()(main/db.ts:1099) validates any real pre-v121 database or backup (29 <= schemaVersion <= 120) viagetRecoverySchemaReference(schemaVersion)->buildIdealSchemaDb(schemaVersion)(main/db.ts:1030-1051), the reference schema for v29..v120 now requireswhatsapp_message_attempts(and for96 <= schemaVersion <= 120, migration v96'sALTER TABLE whatsapp_messages RENAME TO whatsapp_messages_v95rewriteswhatsapp_message_attempts's foreign key in SQLite toREFERENCES "whatsapp_messages_v95"(id)without running migration 121), causingisHealthyDatabaseFile()to reject valid pre-v121 databases and backups. Removewhatsapp_message_attemptsandidx_whatsapp_message_attempts_message_idfromcreateWhatsAppSchema()(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-unreachablewhatsapp_messages_v95repair branch inmain/db.ts:7793-7815. Also fix the sibling sites for this migration: (1)main/db.ts:7826- selectTRIM(external_message_id)in the migration 121 backfill so whitespace-padded IDs matchfindMessageByExternalId()'s trimmed lookup (main/services/whatsapp.ts:993, 1005); (2)main/db.ts:4339(dataOnlyRestore) andmain/routes/database.ts:456(POST /api/db/importreplace mode) - whenwhatsapp_messagesis replaced from a pre-v121 backup or export that does not includewhatsapp_message_attemptswhileforeign_keys = OFF, clearwhatsapp_message_attempts(and backfill from restoredwhatsapp_messages.external_message_id) so pre-existing rows inwhatsapp_message_attemptsdo not become orphaned and failgetForeignKeyViolationKeys(currentDb)(main/db.ts:4373) orPRAGMA foreign_key_check(main/routes/database.ts:575); (3)tests/backup-restore-production.test.ts:976andfrontend/e2e/database-export-import.spec.ts:214- update the hardcoded schema version120assertion/fixture metadata to121.main/services/whatsapp.ts:907- InrecordMessageAttemptExternalId(main/services/whatsapp.ts:893-910),trimmedis guaranteed non-empty (if (!trimmed) return;at line 898), soSET external_message_id = COALESCE(?, external_message_id)with.run(trimmed, messageId)always overwriteswhatsapp_messages.external_message_idwithtrimmed. If an earlier send attempt aborts whilesocket.sendMessageis in flight (main/services/whatsapp.ts:2447-2459), a subsequent retry completes and setswhatsapp_messages.external_message_id = 'ext-2'(main/services/whatsapp.ts:2470), and the aborted attempt'ssocket.sendMessagepromise later resolves in the background, its.then(...)callback atmain/services/whatsapp.ts:2453callsrecordMessageAttemptExternalId(messageId, 'ext-1')and overwriteswhatsapp_messages.external_message_idback to'ext-1'. UseCOALESCE(external_message_id, ?)inmain/services/whatsapp.ts:907(normal non-aborted completion already updateswhatsapp_messages.external_message_idviaupdateMessageRowatmain/services/whatsapp.ts:2470), and remove the duplicaterecordMessageAttemptExternalIdcall atmain/services/whatsapp.ts:2463-2465(already invoked in.then(...)atmain/services/whatsapp.ts:2453).main/services/whatsapp.ts:2122- InsendMessageWithLock(main/services/whatsapp.ts:2050-2126),currentisprevious.catch(() => {}).then(() => ownDone)and map cleanup is deferred tovoid current.finally(...)(main/services/whatsapp.ts:2122-2126). Even whenprevioushas already settled beforefinallyruns,current.finally(...)executes on a later microtask tick afterawait sendMessage(...)/await retryMessage(...)resolves to its caller, leavingsendLocks.size > 0synchronously after completion. IfinitFromDb()(main/services/whatsapp.ts:3577) runs immediately after a send completes and disconnects,sendLocks.size === 0evaluates tofalseand skipsincludeAllUnfinishedinsweepAckTimeouts(). Track whetherprevioushas settled (let previousSettled = false;set viaprevious.then(() => { previousSettled = true; }, () => { previousSettled = true; })): infinally, afterreleaseOwn(), deletereq.phoneE164fromsendLockssynchronously whenpreviousSettled && sendLocks.get(req.phoneE164) === current, and only defer cleanup tocurrent.finally(...)when the waiter exited beforeprevioussettled.🔧 Fix applied.
✅ Re-checked - no issues remain.
🔧 **Test** - 2 issues found → no changes applied ✅
git -C ~/.no-mistakes/worktrees/de2296f2e6f8/01M62KE6W1BYN7XSMCXBWTP3TA statusandgit -C ~/.no-mistakes/worktrees/de2296f2e6f8/01M62KE6W1BYN7XSMCXBWTP3TA diff). Respond with fix to validate it, or abort.🔧 No changes applied.
✅ Re-checked - no issues remain.
npm run test:whatsapp-schemanpm run test:whatsapp-servicenpm run test:upgrade-pathnpm run test:schema-healthnpm run test:migration-registrynode tests/run-electron-node-test.cjs tests/backup-restore-production.test.tsnpm run test:database-tools-apinpm run test:google-driveLive 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.