Repository navigation
PR #76 review fix: ack webhook 200 before running the agent (LINE + WhatsApp) - #78
Conversation
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
There was a problem hiding this comment.
💡 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".
| inherited Create(False); { CreateSuspended=False — start immediately } | ||
| FreeOnTerminate := True; | ||
| FBot := Bot; | ||
| FEventJSON := EventJSON; |
There was a problem hiding this comment.
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 👍 / 👎.
| inherited Create(False); { CreateSuspended=False — start immediately } | ||
| FreeOnTerminate := True; | ||
| FBot := Bot; | ||
| FFromNumber := FromNumber; | ||
| FText := Text; |
There was a problem hiding this comment.
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
…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
PR #76 review fix (P2): ack webhook 200 before running the agent
Codex's review on PR #76 flagged that
TLineBot.HandleWebhookcallsProcessEventinline —RunToolLoopis 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 thoughResponseNo := 200was 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
TThreadper event.HandleWebhookspawns the worker(s) and returns; Indy flushes the 200 within milliseconds; the worker runsRunToolLoopand sends the reply on the background thread.TLineEventWorkerTLineBot.ProcessEvent(EventJSON)TWhatsAppMessageWorkerTWhatsAppBot.ProcessMessage(From, Text)messages[].text.bodyparse site so each text message gets its own workerBoth constructors take their bot reference + the captured data, set
FreeOnTerminate := True, and start viainherited Create(False).Executewraps the bot call intry/exceptso 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.ProcessMessagethrough Pascal's unit-private visibility — no public surface change.Thread safety
FBotfields (Token, Secret, Cfg, Provider, Registry, internalTLinePush/TWhatsAppPush) are all set once at construction and never written after, so worker threads read them without locking.PostJSONcall creates its ownTIdHTTPper the existingPasClaw.Providers.HTTPpattern, so no shared HTTP client state.LogInfo/LogWarnwriteWriteLn-to-stderr without locking, which is the same behaviour the existingTTelegramChannel.Runloop already relies on — log lines may interleave under heavy parallel load but won't crash.Verification
makebuilds 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