Skip to content

PR #76 review fix: ack webhook 200 before running the agent (LINE + WhatsApp) - #78

Merged
FMXExpress merged 2 commits into
mainfrom
claude/pr76-async-events
May 29, 2026
Merged

FMXExpress merged 2 commits into
mainfrom
claude/pr76-async-events

Conversation

@FMXExpress

Copy link
Copy Markdown
Owner

PR #76 review fix (P2): ack webhook 200 before running the agent

Codex's review on PR #76 flagged that TLineBot.HandleWebhook calls ProcessEvent inline — RunToolLoop is synchronous and can take 30+ seconds when the model uses tools, but the 200 ack only flushes after the Indy handler returns. LINE's webhook timeout is 1s; past that they retry the same event up to 3 times, generating 4× duplicate replies even though ResponseNo := 200 was set on the response object early.

PR #77's WhatsApp bot shipped with the identical bug (Meta's webhook ingestion times out around 20s and backs off exponentially on retry), so this PR fixes both.

Approach

A tiny self-freeing TThread per event. HandleWebhook spawns the worker(s) and returns; Indy flushes the 200 within milliseconds; the worker runs RunToolLoop and sends the reply on the background thread.

Worker Calls Captures
TLineEventWorker TLineBot.ProcessEvent(EventJSON) the raw event JSON
TWhatsAppMessageWorker TWhatsAppBot.ProcessMessage(From, Text) extracted at the messages[].text.body parse site so each text message gets its own worker

Both constructors take their bot reference + the captured data, set FreeOnTerminate := True, and start via inherited Create(False). Execute wraps the bot call in try/except so a handler crash logs and dies cleanly instead of propagating up into Indy's dispatcher.

Worker classes live in the implementation section of their respective units so they can reach Bot.ProcessEvent / Bot.ProcessMessage through Pascal's unit-private visibility — no public surface change.

Thread safety

  • FBot fields (Token, Secret, Cfg, Provider, Registry, internal TLinePush / TWhatsAppPush) are all set once at construction and never written after, so worker threads read them without locking.
  • Each PostJSON call creates its own TIdHTTP per the existing PasClaw.Providers.HTTP pattern, so no shared HTTP client state.
  • LogInfo/LogWarn write WriteLn-to-stderr without locking, which is the same behaviour the existing TTelegramChannel.Run loop already relies on — log lines may interleave under heavy parallel load but won't crash.

Verification

make builds clean under FPC 3.2.2; both bots compile with the new worker types resolving correctly through unit-private visibility. The fix is localized to the two bot units — 91 lines added across both, no signature or API surface change.

https://claude.ai/code/session_01TBcLtmpj7dqA5tyFbGnQon


Generated by Claude Code

PR #76's Codex review (P2) flagged that TLineBot.HandleWebhook calls
ProcessEvent inline — RunToolLoop is synchronous and can take 30+
seconds when the model uses tools, but the 200 ack only flushes after
the Indy handler returns. LINE's webhook timeout is 1s; past that
they retry the same event up to 3 times, generating 4× duplicate
replies even though ResponseNo := 200 was set on the response
object early. PR #77's WhatsApp bot shipped with the identical bug
(Meta's timeout is ~20s and they back off exponentially on retry),
so fix both here.

Approach: a tiny self-freeing worker thread per event. HandleWebhook
spawns the worker(s) and returns; Indy flushes the 200 within
milliseconds; the worker runs RunToolLoop and sends the reply on the
background thread.

  TLineEventWorker     — thread that calls TLineBot.ProcessEvent
                          with a captured copy of the event JSON.
                          Constructor takes (Bot, EventJSON), sets
                          FreeOnTerminate := True, starts via
                          inherited Create(False). Execute wraps the
                          ProcessEvent call in try/except so a
                          handler crash logs and dies cleanly
                          instead of propagating up into Indy's
                          dispatcher.
  TWhatsAppMessageWorker — same shape, calls
                          TWhatsAppBot.ProcessMessage(From, Text).
                          Extracted at the messages[].text.body
                          parse site so each text message gets its
                          own worker — multiple messages in one
                          webhook delivery process in parallel.

Both bots' loops in HandleWebhook / HandleEvents now construct the
worker instead of calling ProcessEvent/ProcessMessage directly. The
worker classes live in the implementation section of their
respective units so they can reach Bot.ProcessEvent /
Bot.ProcessMessage through Pascal's unit-private visibility — no
public surface change.

Thread safety: FBot fields (Token, Secret, Cfg, Provider, Registry,
internal TLinePush / TWhatsAppPush) are all set once at construction
and never written after, so worker threads read them without
locking. Each PostJSON call creates its own TIdHTTP per the existing
PasClaw.Providers.HTTP pattern, so no shared HTTP client state. The
Logger writes WriteLn-to-stderr without locking, which is the same
behaviour the existing TTelegramChannel.Run loop relies on — log
lines may interleave under heavy parallel load but won't crash.

Verified locally: make builds clean, both bots compile with the new
worker types resolving correctly through their unit's private
visibility.

https://claude.ai/code/session_01TBcLtmpj7dqA5tyFbGnQon

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

Copy link
Copy Markdown

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: 120c468e2e

ℹ️ About Codex in GitHub

Your team has set up Codex to 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 👍.

Codex can also answer questions or update the PR. Try commenting "@codex address that feedback".

Comment on lines +106 to +109
inherited Create(False); { CreateSuspended=False — start immediately }
FreeOnTerminate := True;
FBot := Bot;
FEventJSON := EventJSON;

Copy link
Copy Markdown

Choose a reason for hiding this comment

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

P2 Badge Initialize LINE worker before starting it

With CreateSuspended=False, Execute may be scheduled immediately, before FBot and FEventJSON are assigned here. In that race, a LINE webhook worker can call ProcessEvent on a nil bot or with an empty event, log/drop the message after the handler already acknowledged 200, and sometimes miss FreeOnTerminate; create the thread suspended, assign its fields, then start it.

Useful? React with 👍 / 👎.

Comment on lines +127 to +131
inherited Create(False); { CreateSuspended=False — start immediately }
FreeOnTerminate := True;
FBot := Bot;
FFromNumber := FromNumber;
FText := Text;

Copy link
Copy Markdown

Choose a reason for hiding this comment

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

P2 Badge Initialize WhatsApp worker before starting it

Because inherited Create(False) starts the thread before the constructor stores FBot, FFromNumber, and FText, the worker can run on another scheduler tick with default fields. For an inbound WhatsApp message this can turn the new async path into a nil-bot exception or an empty send after the webhook has already returned 200; construct suspended, populate state/FreeOnTerminate, then start the thread.

Useful? React with 👍 / 👎.

Codex flagged both worker constructors (TLineEventWorker and
TWhatsAppMessageWorker) for the same P2 race: inherited Create(False)
starts the thread immediately, before the constructor's own field
assignments finish. The scheduler can run Execute on FBot=nil and an
empty FEventJSON / FFromNumber / FText — the new async path turns
into a nil-pointer crash or a silent drop after the handler has
already acknowledged 200.

Switch both workers to the suspended-then-start idiom the cron
scheduler's TCronThread already uses:

  inherited Create(True);   // suspended — Execute won't run yet
  FreeOnTerminate := True;  // set before any thread-side observer
  FBot       := Bot;        // assign payload while we own it alone
  FEventJSON := EventJSON;
  Start;                    // green-light Execute

After Start returns, every field Execute reads is guaranteed
visible; FreeOnTerminate is in place so the worker still cleans
itself up after running.

No behavior change beyond closing the race — the public Create
signatures and the spawning sites in HandleWebhook / HandleEvents
stay byte-identical. The comment block in each constructor names the
exact race so a future maintainer doesn't "optimize" back to
Create(False).

Verified: make builds clean, both bot units compile.

https://claude.ai/code/session_01TBcLtmpj7dqA5tyFbGnQon
@FMXExpress
FMXExpress merged commit 4c91c9d into main May 29, 2026
FMXExpress pushed a commit that referenced this pull request May 30, 2026
…worker thread

Three Codex reviews against the Matrix + IRC bots — all legit and
material.

PR #86 P1: Matrix /whoami failure caused an echo loop. Start used to
warn-and-continue if /account/whoami failed transiently, leaving
FUserId empty. ProcessEvent's "if Sender = FUserId" then matched
Sender='' instead of the bot's actual user_id, so every outbound
reply re-entered the loop as a fresh prompt — the bot would spam-
reply to itself until the server kicked it or the API quota ran
out.

Fix:
  WhoAmIWithRetry(out UserId; Attempts) — calls WhoAmI in a loop
  with exponential-ish backoff (1s, 2s, 4s) between attempts, and
  watches FStopEvt so an in-flight RequestStop doesn't sit through
  the backoff. If all attempts fail, Start logs a hard error
  pointing at the token/homeserver and REFUSES to launch the sync
  thread.

PR #86 P1: Initial /sync without a since= parameter replays history
through the model. Per spec, the first sync returns whatever
recent timeline the homeserver has cached for each joined room.
Every restart would produce a duplicate run through the most
recent few messages — the bot would re-answer them and look like
it had time-travelled.

Fix:
  InitialSyncToken — one-shot call to
    GET /sync?timeout=0&filter={"room":{"timeline":{"limit":0}}}
  to fetch the next_batch anchor with zero timeline events.
  Start runs it after /whoami passes, sets FNextBatch, then
  launches TMatrixSyncThread; the long-poll loop's first GetSync
  uses that token so the first delivered events are strictly NEW.
  Bails out the same way as WhoAmI if the token fetch fails.

PR #86 P2: IRC RunToolLoop blocked Indy's TIdCmdTCPClient listener.
OnPrivateMessage ran the agent inline. A slow turn (model + tool
loop chasing fs_read / shell_exec / web_fetch) kept the listener
from servicing server PINGs, the server killed the connection
after its ping-timeout, and the bot disconnected from IRC.

Fix:
  TIRCMessageWorker — self-freeing TThread per inbound message,
  same suspended-then-Start pattern from PR #78's LINE/WhatsApp
  worker fix. HandlePrivMessage now spawns one and returns
  immediately. The listener keeps PONGing on schedule; the worker
  runs RunToolLoop and FClient.Say asynchronously. Worker exception
  swallowed with a warn so a bug in the agent path doesn't bring
  down the IRC connection.

Build: clean under FPC 3.2.2; both channel units compile with the
new worker types and retry helpers resolving correctly through
unit-private visibility.

https://claude.ai/code/session_01TBcLtmpj7dqA5tyFbGnQon
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.

2 participants