Skip to content

fix: flush debounced messages before closing WhatsApp socket - #63038

Closed
mmcc9988 wants to merge 2 commits into
openclaw:mainfrom
mmcc9988:fix/whatsapp-debounce-flush-on-close
Closed

mmcc9988 wants to merge 2 commits into
openclaw:mainfrom
mmcc9988:fix/whatsapp-debounce-flush-on-close

Conversation

@mmcc9988

@mmcc9988 mmcc9988 commented Apr 8, 2026

Copy link
Copy Markdown

Problem

When the WhatsApp connection closes (disconnect, watchdog timeout, or graceful shutdown), messages sitting in the inbound debounce window are silently dropped. This happens because:

  1. The socket is closed immediately in the close() handler
  2. Pending debounce timers fire after the socket is already dead
  3. Reply callbacks (msg.reply, msg.sendMedia) fail silently on the closed socket

This affects deployments with messages.inbound.debounceMs > 0 configured — rapid consecutive messages from the same sender may be lost during connection transitions.

Fix

src/auto-reply/inbound-debounce.ts: Add a flushAll() method that iterates all buffered keys and flushes them using the existing flushKey() logic (which properly clears timers, releases keyed execution slots, and calls onFlush).

extensions/whatsapp/src/inbound/monitor.ts: Call debouncer.flushAll() in the close() handler, sequenced between:

  • detachMessagesUpsert() — stop accepting new messages
  • debouncer.flushAll() — process buffered messages while socket is still alive
  • closeInboundMonitorSocket(sock) — close the socket

This ordering ensures buffered messages are processed and replies sent before the socket is torn down.

Testing

  • Existing debouncer tests (1019 lines in inbound.test.ts) cover flushKey behavior
  • flushAll delegates to flushKey per-key, inheriting the same guarantees

@openclaw-barnacle openclaw-barnacle Bot added channel: whatsapp-web Channel integration: whatsapp-web size: XS labels Apr 8, 2026
@greptile-apps

greptile-apps Bot commented Apr 8, 2026 •

Copy link
Copy Markdown
Contributor

Greptile Summary

This PR fixes silent message loss on WhatsApp socket close by calling debouncer.flushAll() in the close() handler after detaching the message listener but before tearing down the socket, ensuring debounce-buffered messages are dispatched while the socket is still alive. A new flushAll() method is added to createInboundDebouncer, delegating to the existing flushKey() per buffered key.

Confidence Score: 5/5

Safe to merge; the fix is correct and both remaining findings are P2 style suggestions.

No P0/P1 issues found. The flush ordering and sequencing logic are correct. The two P2 comments are optional improvements: parallel key flushing to reduce close-path latency, and moving detachConnectionUpdate before the flush for a cleaner shutdown boundary.

No files require special attention.

Vulnerabilities

No security concerns identified.

Comments Outside Diff (1)

  1. extensions/whatsapp/src/inbound/monitor.ts, line 559-568 (link)

    P2 detachConnectionUpdate still attached during flush

    detachConnectionUpdate() is called after the await debouncer.flushAll() point, so handleConnectionUpdate remains active for the duration of the flush. If the underlying socket signals a close event during that window, resolveClose fires and callers see onClose settle while close() is still executing. Moving detachConnectionUpdate() before the flush aligns it with detachMessagesUpsert() and makes the shutdown boundary cleaner.

    Prompt To Fix With AI
    This is a comment left during a code review.
    Path: extensions/whatsapp/src/inbound/monitor.ts
    Line: 559-568
    
    Comment:
    **`detachConnectionUpdate` still attached during flush**
    
    `detachConnectionUpdate()` is called after the `await debouncer.flushAll()` point, so `handleConnectionUpdate` remains active for the duration of the flush. If the underlying socket signals a close event during that window, `resolveClose` fires and callers see `onClose` settle while `close()` is still executing. Moving `detachConnectionUpdate()` before the flush aligns it with `detachMessagesUpsert()` and makes the shutdown boundary cleaner.
    
    
    
    How can I resolve this? If you propose a fix, please make it concise.
Prompt To Fix All With AI
This is a comment left during a code review.
Path: src/auto-reply/inbound-debounce.ts
Line: 234-239

Comment:
**Sequential flush adds close-path latency**

`flushAll` awaits each key one at a time, so total close time is the sum of all `onFlush` durations. Since each key maps to a different conversation/sender, the per-key flushes are independent and can run in parallel without ordering concerns between them (per-key ordering is already guaranteed by `keyChains`).

```suggestion
  const flushAll = async () => {
    const keys = Array.from(buffers.keys());
    await Promise.all(keys.map((key) => flushKey(key)));
  };
```

How can I resolve this? If you propose a fix, please make it concise.

---

This is a comment left during a code review.
Path: extensions/whatsapp/src/inbound/monitor.ts
Line: 559-568

Comment:
**`detachConnectionUpdate` still attached during flush**

`detachConnectionUpdate()` is called after the `await debouncer.flushAll()` point, so `handleConnectionUpdate` remains active for the duration of the flush. If the underlying socket signals a close event during that window, `resolveClose` fires and callers see `onClose` settle while `close()` is still executing. Moving `detachConnectionUpdate()` before the flush aligns it with `detachMessagesUpsert()` and makes the shutdown boundary cleaner.

```suggestion
    close: async () => {
      try {
        detachMessagesUpsert();
        detachConnectionUpdate();
        await debouncer.flushAll();
        closeInboundMonitorSocket(sock);
      } catch (err) {
        logVerbose(`Socket close failed: ${String(err)}`);
      }
    },
```

How can I resolve this? If you propose a fix, please make it concise.

Reviews (1): Last reviewed commit: "fix: flush debounced messages before clo..." | Re-trigger Greptile

Comment on lines +234 to +239
const flushAll = async () => {
const keys = Array.from(buffers.keys());
for (const key of keys) {
await flushKey(key);
}
};

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

P2 Sequential flush adds close-path latency

flushAll awaits each key one at a time, so total close time is the sum of all onFlush durations. Since each key maps to a different conversation/sender, the per-key flushes are independent and can run in parallel without ordering concerns between them (per-key ordering is already guaranteed by keyChains).

Suggested change
const flushAll = async () => {
const keys = Array.from(buffers.keys());
for (const key of keys) {
await flushKey(key);
}
};
const flushAll = async () => {
const keys = Array.from(buffers.keys());
await Promise.all(keys.map((key) => flushKey(key)));
};
Prompt To Fix With AI
This is a comment left during a code review.
Path: src/auto-reply/inbound-debounce.ts
Line: 234-239

Comment:
**Sequential flush adds close-path latency**

`flushAll` awaits each key one at a time, so total close time is the sum of all `onFlush` durations. Since each key maps to a different conversation/sender, the per-key flushes are independent and can run in parallel without ordering concerns between them (per-key ordering is already guaranteed by `keyChains`).

```suggestion
  const flushAll = async () => {
    const keys = Array.from(buffers.keys());
    await Promise.all(keys.map((key) => flushKey(key)));
  };
```

How can I resolve this? If you propose a fix, please make it concise.

@chatgpt-codex-connector chatgpt-codex-connector Bot left a comment

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

💡 Codex Review

Here are some automated review suggestions for this pull request.

Reviewed commit: c4fa24ed78

ℹ️ About Codex in GitHub

Codex has been enabled to automatically review pull requests in this repo. Reviews are triggered when you

  • Open a pull request for review
  • Mark a draft as ready
  • Comment "@codex review".

If Codex has suggestions, it will comment; otherwise it will react with 👍.

When you sign up for Codex through ChatGPT, Codex can also answer questions or update the PR, like "@codex address that feedback".

Comment thread src/auto-reply/inbound-debounce.ts Outdated
Comment on lines +235 to +237
const keys = Array.from(buffers.keys());
for (const key of keys) {
await flushKey(key);

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

P1 Badge Keep flushing until buffer map is empty

flushAll snapshots buffers.keys() once and never re-checks the map, so entries enqueued during the flush window are skipped. In this flow, monitorWebInbox.close() calls flushAll() and then closes the socket, and detachMessagesUpsert() does not cancel an already-running async handleMessagesUpsert callback; that callback can still enqueue additional items after the snapshot. Those late items remain buffered and are dropped when the socket closes, so the new shutdown path can still lose debounced inbound messages.

Useful? React with 👍 / 👎.

@openclaw-barnacle openclaw-barnacle Bot added channel: bluebubbles Channel integration: bluebubbles channel: slack Channel integration: slack channel: feishu Channel integration: feishu labels Apr 8, 2026

@chatgpt-codex-connector chatgpt-codex-connector Bot left a comment

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

💡 Codex Review

Here are some automated review suggestions for this pull request.

Reviewed commit: 81be021f5c

ℹ️ About Codex in GitHub

Codex has been enabled to automatically review pull requests in this repo. Reviews are triggered when you

  • Open a pull request for review
  • Mark a draft as ready
  • Comment "@codex review".

If Codex has suggestions, it will comment; otherwise it will react with 👍.

When you sign up for Codex through ChatGPT, Codex can also answer questions or update the PR, like "@codex address that feedback".

Comment on lines +235 to +236
const keys = Array.from(buffers.keys());
await Promise.all(keys.map((key) => flushKey(key)));

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

P1 Badge Drain active keyed tasks before returning from flushAll

flushAll only awaits keys that are still present in buffers, but a debounce timer callback removes the buffer before awaiting buffer.task (tracked in keyChains). If close() runs during that window, flushAll can resolve even though a debounced onFlush is still executing, and monitorWebInbox.close() will then close the WhatsApp socket immediately after, causing in-flight reply/sendMedia calls to fail and drop those messages.

Useful? React with 👍 / 👎.

When the WhatsApp connection closes (disconnect, watchdog, or shutdown),
messages sitting in the inbound debounce window are silently dropped
because the socket is closed before pending timers fire.

Add a flushAll() method to the inbound debouncer and call it during the
close sequence — after detaching the message listener (preventing new
arrivals) but before closing the socket (so replies can still be sent).

This ensures debounced messages are processed and replied to even during
connection transitions.
- Use Promise.all for parallel flush (keys are independent conversations)
- Move detachConnectionUpdate before flushAll for cleaner shutdown boundary
- Add flushAll to mock debouncers in feishu, slack, bluebubbles, and
  plugin-runtime-mock to fix TS2322 type errors
- Add flushAll to BlueBubblesDebouncer type definition
@mmcc9988
mmcc9988 force-pushed the fix/whatsapp-debounce-flush-on-close branch from 81be021 to 48a45ba Compare April 8, 2026 16:56

@chatgpt-codex-connector chatgpt-codex-connector Bot left a comment

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

💡 Codex Review

Here are some automated review suggestions for this pull request.

Reviewed commit: 48a45bad6d

ℹ️ About Codex in GitHub

Codex has been enabled to automatically review pull requests in this repo. Reviews are triggered when you

  • Open a pull request for review
  • Mark a draft as ready
  • Comment "@codex review".

If Codex has suggestions, it will comment; otherwise it will react with 👍.

When you sign up for Codex through ChatGPT, Codex can also answer questions or update the PR, like "@codex address that feedback".

Comment on lines +235 to +236
const keys = Array.from(buffers.keys());
await Promise.all(keys.map((key) => flushKey(key)));

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

P1 Badge Wait for debouncer to fully quiesce before returning flushAll

flushAll only snapshots buffers.keys() once and awaits flushKey for that snapshot, so it can return while debounce work is still being created or still running. In the new WhatsApp shutdown flow, detachMessagesUpsert() does not cancel already-running handleMessagesUpsert callbacks, so they can enqueue new buffered items after this snapshot; additionally, timer flushes remove a buffer before awaiting its keyed task, so in-flight onFlush work can exist with no buffer entry. Because close() now closes the socket immediately after flushAll, those late/in-flight flushes can still execute against a closed socket and drop messages.

Useful? React with 👍 / 👎.

@clawsweeper

clawsweeper Bot commented Apr 27, 2026 •

Copy link
Copy Markdown
Contributor

Codex review: needs real behavior proof before merge.

Summary
Adds flushAll() to the shared inbound debouncer, calls it during WhatsApp Web close before socket teardown, and updates affected channel/test mocks for the new debouncer API.

Reproducibility: yes. source-reproducible: configure messages.inbound.debounceMs > 0, emit WhatsApp messages.upsert, then close while handler or timer work is pending and assert reply or sendMedia finishes before closeInboundMonitorSocket. I did not run a live WhatsApp session.

Real behavior proof
Needs real behavior proof before merge: The PR body and comments include no after-fix real WhatsApp proof; the contributor should add redacted terminal/log output, screenshot, recording, or linked artifact and update the PR body for re-review.

Next step before merge
Needs contributor real-behavior proof plus a corrected quiescence drain; automation cannot supply proof from the contributor’s WhatsApp setup.

Security
Cleared: The diff only changes in-process debounce shutdown sequencing and test mocks; it does not change dependencies, workflows, secrets, or package resolution.

Review findings

  • [P1] Wait for debounce work to fully quiesce — src/auto-reply/inbound-debounce.ts:235-237
Review details

Best possible solution:

Implement a debouncer drain that waits until there are no buffered keys and no active keyed chains before closing WhatsApp, with a focused regression proving reply or sendMedia completes before socket teardown.

Do we have a high-confidence way to reproduce the issue?

Yes, source-reproducible: configure messages.inbound.debounceMs > 0, emit WhatsApp messages.upsert, then close while handler or timer work is pending and assert reply or sendMedia finishes before closeInboundMonitorSocket. I did not run a live WhatsApp session.

Is this the best way to solve the issue?

No. A close-path drain is the right direction, but the proposed one-shot buffer snapshot can miss late enqueues and active keyChains work; a quiescence drain is the safer fix.

Full review comments:

  • [P1] Wait for debounce work to fully quiesce — src/auto-reply/inbound-debounce.ts:235-237
    flushAll() snapshots buffers.keys() once and awaits only that snapshot. In the WhatsApp close path, an already-running handleMessagesUpsert can enqueue after the snapshot, and timer-driven flushes can leave active keyChains work after the buffer is deleted, so close() can still tear down the socket before reply or sendMedia finishes.
    Confidence: 0.9

Overall correctness: patch is incorrect
Overall confidence: 0.9

Acceptance criteria:

  • pnpm test src/auto-reply/inbound.test.ts extensions/whatsapp/src/monitor-inbox.behavior.test.ts

What I checked:

Likely related people:

  • @steipete: Recent history includes shared inbound debounce ordering/key-accounting work and several WhatsApp inbound monitor changes near this shutdown path. (role: recent area contributor; confidence: high; commits: 323ae73b3028, 1b69d9ee1a51, 47083460eacc; files: src/auto-reply/inbound-debounce.ts, extensions/whatsapp/src/inbound/monitor.ts)
  • @vincentkoc: Recent commits touched inbound debounce cleanup, key limits, no-debounce concurrency, and WhatsApp inbound retry behavior adjacent to this failure mode. (role: recent adjacent contributor; confidence: high; commits: df27091f5f69, 9b7cfd0bea88, 3de42e946a2b; files: src/auto-reply/inbound-debounce.ts, extensions/whatsapp/src/inbound/monitor.ts)
  • @juanpablodlc: Authored the original WhatsApp debounce batching work that introduced the shared inbound debouncer and channel debounce configuration. (role: introduced behavior; confidence: medium; commits: 4a99b9b65118; files: src/auto-reply/inbound-debounce.ts)
  • @mcaxtr: Recent WhatsApp monitor lifecycle and reply-mode work is adjacent to socket-close reply preservation. (role: recent adjacent contributor; confidence: medium; commits: f5f0235bb18a, 458a52610a4d, aa023e428306; files: extensions/whatsapp/src/inbound/monitor.ts)

Remaining risk / open question:

  • No after-fix real WhatsApp run proof is attached, so live socket behavior remains unverified.
  • I did not run tests in this read-only sweep; validation should happen after a revised branch adds the regression.

Codex review notes: model gpt-5.5, reasoning high; reviewed against a5668efb7aca.

@mcaxtr

mcaxtr commented May 13, 2026

Copy link
Copy Markdown
Member

Thanks for the PR and for working on this. We checked the current main branch, and this fix is already in main via #81246, which landed in commit 81a3de1.

Handling already-received debounced WhatsApp inbound messages before closing the socket, so replies and media sends from that batch run first, is already covered on main, so the behavior this PR changes is already handled there.

Because that has landed, I’m closing this PR as superseded by #81246.

Thanks again for the work here. If you think this closure is mistaken and your PR still fixes something meaningfully different on current main, feel free to open a new PR with that explanation.

@mcaxtr mcaxtr closed this May 13, 2026
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

channel: bluebubbles Channel integration: bluebubbles channel: feishu Channel integration: feishu channel: slack Channel integration: slack channel: whatsapp-web Channel integration: whatsapp-web size: XS

Projects

None yet

Development

Successfully merging this pull request may close these issues.

3 participants