Skip to content

fix(voice-call): let Twilio notify messages finish before hangup - #191264

Open
GoatInAHat wants to merge 4 commits into
openclaw:mainfrom
GoatInAHat:voice-call-notify-inline-hangup
Open

GoatInAHat wants to merge 4 commits into
openclaw:mainfrom
GoatInAHat:voice-call-notify-inline-hangup

Conversation

@GoatInAHat

@GoatInAHat GoatInAHat commented Nov 2, 2026 •

Copy link
Copy Markdown
Contributor

Closes #191214

What Problem This Solves

Twilio notify calls restart their message on answer and cut it off after about three seconds when voicemail detection is disabled. The original patch also prematurely recorded speech for calls that were rejected, busy, or never answered; this revision also fixes terminal playback records that otherwise remain marked playing after local termination or restart recovery.

User Impact

Recipients can hear the complete inline notification before Twilio hangs up. Undelivered notifications are no longer recorded as assistant speech. Call setup, conversation flow, voicemail detection, and providers that ignore inline TwiML keep their existing behavior. Terminal notification and voicemail reports now settle playback instead of displaying playing forever. No configuration changes are required.

Why This Change Was Made

Twilio already receives <Say>…</Say><Hangup/> as its create-call instructions. Before dialing, the manager moves the pending initial message into a private inline-ownership metadata marker, so no answer/stream trigger can replay it, including an answer callback arriving before the create-call response. This is pending ownership, not evidence of speech: the transcript stays empty and notifyStatus is unset.

Only the carrier's answered event consumes that marker, sets notifyStatus: "playing", and appends the bot transcript entry in the existing persisted event mutation, before answer effects run. Repeated answered callbacks cannot record the message twice. The shared markCallEnded owner now settles playback and terminal timestamps/state before persistence. finalizeCall uses it for local endings (including max-duration/notification timers and initiation failure) and carrier call.ended/fatal call.error; restart recovery uses it for both terminal-provider and expired-record branches. Newly rejected inbound records also use it. Runtime stop only drains accepted work and clears timers; it does not create terminal records.

Provider-confirmed completed playback becomes left; other provider endings become failed with an error naming the status (or preserving the carrier error). Local notification endings remain failed with their existing reason-specific errors. Expired recovery without provider confirmation becomes failed with an explicit unconfirmed-after-restart error. The same mapping closes the voicemail gap, while preserving left for successful realtime voicemail and the existing carrier-completed voicemail end reason. Already-settled statuses are untouched. Rejected creation and unanswered calls still have no bot speech or playing status; non-inline provider fallback timing is unchanged.

Evidence

  • Restart regressions failed on ce1bec49022 before production edits: 6 failed, 11 skipped, 32.65s Vitest / 41.36s runner. Completed, busy, and expired recovery each persisted playing for notifications and voicemail. The repaired initial restore suite passed 17 tests, 34.60s Vitest / 42.64s runner, including late-carrier-callback checks; the final expanded suite is included below.
  • pnpm test extensions/voice-call/src/manager.notify.test.ts extensions/voice-call/src/manager/outbound.test.ts extensions/voice-call/src/manager/events.test.ts extensions/voice-call/src/providers/twilio.test.ts extensions/voice-call/src/manager.restore.test.ts --maxWorkers=1: 157 passed in five files, 229.62s runner (104 database-worker tests/207.60s; 53 voice-call tests/12.96s), including cold worker preparation. The changed restore suite passes all 23 cases, including 12 new cases.
  • Affected persistence consumers: 11 passed, 10 skipped, 34.03s Vitest / 40.39s runner. The selected cases cover three asynchronous restore durability paths and all eight outbound-persistence cases, including terminal identity and delayed playback. Unrelated call-scope tests were excluded.
  • All earlier pre-dial replay, answer-only transcript/status, rejected/unanswered calls, local endCall/max-duration, repeated/early answer, carrier completion, Plivo/Telnyx, AMD, successful realtime voicemail and first-provider-terminal-facts regressions pass unchanged. Six additional persisted carrier-busy/fatal-error/local-timeout cases cover both playback fields. These use real manager/queue/persistence owners with a fake external provider; they do not prove live carrier/audio behavior.
  • Narrow strict source-backed typecheck passed for all five production files, three regression files and their dependency closure (214.20s). Source-backed type-aware lint passed all eight TypeScript files (27.67s wall / 26.37s lint), reusing root source aliases instead of generated SDK declarations; artifact preparation was skipped for that config. Formatting passed (0.21s), the test-line ratchet passed (7.09s), and git diff --check passed (0.17s).
  • pnpm check:changed was deliberately not rerun: the previous 900s run timed out in the repository-wide SQLite worker scan and is not claimed passing. Hosted CI on ce1bec49022 finished with no failed checks; current-revision CI seconds are not yet available. Fresh hosted Codex review is requested after publication; no local autoreview is claimed.
  • The allocation is 219 net regression-test lines (83 in this follow-up); production growth is 32 lines (12 in this follow-up). The change removes duplicated local/carrier settlement and the separate restore-only finalization helper. Shared terminal settlement is necessary to prevent another finalization route from retaining playing; no new runtime manager, public contract, schema or dependency.
  • Full extension suite not rerun; the earlier broader attempt had unrelated call-scope failures and consult timeouts. Only the scopes above are claimed passing.

Production before trace

The following sanitized trace is from a real production call on released voice-call plugin 2026.10.10-beta.5, with voicemail detection off. IDs are placeholders and times are relative to dialing:

+0.000s [voice-call] Using inline TwiML for notify mode (voice: <voice>)
+0.023s [voice-call] Sending direct Twilio initial TwiML for call <call-id> (kind=notify)
+0.259s [voice-call] Outbound call initiated: callId=<call-id> providerCallId=<call-sid> mode=notify preConnectDtmf=no initialMessage=yes
+20.304s [voice-call] Starting max duration timer (1800s) for call <call-id>
+20.305s [voice-call] Speaking initial message for call <call-id> (mode: notify)
+20.317s [voice-call] Using TwiML <Say> fallback - telephony TTS not configured or media stream not active
+20.477s [voice-call] Notify mode: auto-hangup in 3s for call <call-id>
+23.477s [voice-call] Notify mode: hanging up call <call-id>
+23.637s [voice-call] Call finalized callId=<call-id> providerCallId=<call-sid> endReason=hangup-bot

The message was about 45 words (roughly 15 seconds of speech). The call record shows answer at +20.5 seconds and termination 3.3 seconds later with endReason: hangup-bot.

Open proof item

The before trace is production evidence; the after behavior is currently covered by local manager/provider regression tests, not a live Gateway-plus-Twilio trace. An after trace requires the unmerged build running on a live Twilio deployment. We cannot run that against the production install because local production patches are not permitted, and no live calls, plugin installs/reloads, or Gateway changes were made for this revision. Could a maintainer verify with an isolated Twilio setup, or specify the minimal trace they would accept? This live proof item remains open; the local tests are not a claim of carrier/audio verification.

@openclaw-barnacle openclaw-barnacle Bot added channel: voice-call Channel integration: voice-call size: S labels Nov 2, 2026
@clawsweeper

clawsweeper Bot commented Nov 2, 2026 •

Copy link
Copy Markdown
Contributor

🦞👀
ClawSweeper picked this up.

Pull request received. I will update this pull request when review starts.

ClawSweeper review complete

ClawSweeper finished reviewing this revision. The review result is being finalized.

View the workflow run.

@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: f98765732c

ℹ️ 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".

@chatgpt-codex-connector

chatgpt-codex-connector Bot commented Nov 2, 2026 •

Copy link
Copy Markdown
Contributor

Codex Review Summary

This comment shows the latest Codex review activity on this pull request.

Review Status Commit Review trigger
📝 Code Review ✅ Completed 2026-11-02T19:11:18.137095Z 15a5ac3 Manual request
ℹ️ 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" or "@codex security review".

Codex reacts with 👀 while any review is running, comments if it has suggestions, and reacts with 👍 once all reviews finish with no findings.

@clawsweeper clawsweeper Bot added clawsweeper:intake:bug Preliminary submission classification; full source review pending. clawsweeper:intake:needs-environment Preliminary submission classification; full source review pending. clawsweeper:intake:needs-repro Preliminary submission classification; full source review pending. P2 Normal backlog priority with limited blast radius. rating: 🧂 unranked krab Not merge-ready due to missing proof or serious correctness/safety concerns. status: 📣 needs proof The PR needs real behavior proof before ClawSweeper can clear the contributor ask. and removed clawsweeper:intake:bug Preliminary submission classification; full source review pending. clawsweeper:intake:needs-environment Preliminary submission classification; full source review pending. clawsweeper:intake:needs-repro Preliminary submission classification; full source review pending. labels Nov 2, 2026
@clawsweeper

clawsweeper Bot commented Nov 2, 2026

Copy link
Copy Markdown
Contributor

Codex review: needs real behavior proof before merge.

What this changes

The PR prevents Twilio inline notifications from replaying on answer and triggering the manager’s three-second hangup timer.

Example: A Twilio notify call speaks a ten-second message with voicemail detection disabled.

  • Before: Answering restarts the message and schedules hangup after three seconds.
  • After: Twilio retains its original Say/Hangup instructions and can finish the message.

Review scores

Measure Result What it means
Overall readiness 🧂 unranked krab (1/6) A useful focused repair with meaningful ordering regressions, one confirmed history defect, and only mocked carrier proof; existing record schemas and storage formats remain unchanged.
Proof confidence 🧂 unranked krab (1/6) Real behavior proof is necessary before merge. See Before merge.
Patch quality 🦪 silver shellfish (2/6) 1 actionable review finding remain.

Product

Kind: Bug fix · Worth it: Yes · Fix scope: Complete
User problem: Recipients hear a restarted notification that is cut off after about three seconds.
Reason: Restoring uninterrupted one-shot notifications follows the existing carrier contract and needs no new configuration or public API.

Merge readiness

⛔ Blocked before merge - 2 items remain

Keep this PR open: it addresses a current notification-delivery bug, but records speech before a call is accepted or answered.

Priority: P2
Reviewed head: f98765732cde2cb7989362188657e590cd39fd38

Before merge

  • Add real behavior proof - The supplied regressions exercise the manager with FakeProvider, not a shipped Gateway and Twilio call; the body explicitly reports no live calls. Supply redacted logs, terminal captures, or a recording of uninterrupted single playback through carrier completion, removing phone numbers, IPs, keys, and non-public endpoints. After adding proof, update the PR body, then request a new review with @clawsweeper re-review. The PR author or someone with repository write access can request it.
  • Defer recorded speech until the carrier confirms answer (P2) - This runs before provider.initiateCall and persists a final bot utterance immediately. If Twilio rejects creation, or the recipient is busy or never answers, finalizeCall retains that utterance and call-delivery-runtime renders it as Assistant speech in transcripts and reports; creation failures also retain notifyStatus="playing". Preserve the pre-dial replay guard, but defer active-playback status and transcript recording until answer or playback confirmation, with rejected and unanswered regressions.

Findings

  • [P2] Defer recorded speech until the carrier confirms answer — extensions/voice-call/src/manager/outbound.ts:164-166

Tests

  • Missing end-to-end proof: Provide an isolated Gateway/Twilio trace showing a notification longer than three seconds playing once through carrier hangup, including accurate history for rejected or unanswered calls.
Agent review details

How this fits together

The voice-call manager prepares outbound carrier instructions, processes answer callbacks, and persists call history consumed by transcripts and reports.

flowchart LR
  A[Notification request] --> B[Outbound call manager]
  B --> C[Twilio Say and Hangup]
  C --> D[Carrier callbacks]
  D --> B
  B --> E[Persisted call history]
  E --> F[Transcripts and reports]
Loading

Technical review

Best possible solution:

Keep inline playback ownership in the existing manager, suppress replay before dialing, and record speech only after carrier answer or playback confirmation.

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

Current main retains initialMessage after preparing inline TwiML; answer handling dispatches fallback speech and arms the three-second timer, establishing the failure path without executing target code.

Is this the best way to solve the issue?

Reusing manager playback ownership is the smallest complete approach, but the replay guard must be separated from claims that speech has already occurred.

Full review comments:

  • [P2] Defer recorded speech until the carrier confirms answer — extensions/voice-call/src/manager/outbound.ts:164-166
    This runs before provider.initiateCall and persists a final bot utterance immediately. If Twilio rejects creation, or the recipient is busy or never answers, finalizeCall retains that utterance and call-delivery-runtime renders it as Assistant speech in transcripts and reports; creation failures also retain notifyStatus="playing". Preserve the pre-dial replay guard, but defer active-playback status and transcript recording until answer or playback confirmation, with rejected and unanswered regressions.
    Confidence: 0.99

Overall correctness: patch is incorrect
Overall confidence: 0.97

AGENTS.md: found and applied where relevant.

Codex review notes: model internal, reasoning medium; reviewed against e8f91361abfe.

Provenance checked

  • Manager persistence and lifecycle keeps the original intent (ce7981f: Persist call mutations before publishing active state while keeping carrier waits outside the mutation queue.)
  • Carrier notify bookkeeping changes intended behavior with a stated reason (9fa2a21: Voicemail detection establishes carrier playback after classification and supplies transcripts for call reports; the PR reuses this convention to prevent inline replay.)

Testing

Proof path: in-process harness.

Security

None.

Evidence

Acceptance criteria:

  • pnpm test extensions/voice-call/src/manager.notify.test.ts extensions/voice-call/src/manager/outbound.test.ts extensions/voice-call/src/manager/events.test.ts extensions/voice-call/src/providers/twilio.test.ts --maxWorkers=1
  • pnpm check:changed
  • git diff --check
  • Verify rejected creation and busy/no-answer calls retain no unspoken final transcript entry.
  • Obtain contributor proof through an isolated Gateway and Twilio of one uninterrupted notification longer than three seconds followed by carrier hangup.

What I checked:

Likely related people:

  • Peter Steinberger: Raw commit b5f7ba5 adds extensions/voice-call/src/manager/outbound.ts:47 relative to its recorded parents. This identifies author metadata, not feature responsibility or a PR merger. (role: source-line author; confidence: high; commits: b5f7ba502de2; files: extensions/voice-call/src/manager/outbound.ts)
  • Mariano: Raw commit 9fa2a21 adds extensions/voice-call/src/manager/outbound.ts:131 relative to its recorded parents. This identifies author metadata, not feature responsibility or a PR merger. (role: source-line author; confidence: high; commits: 9fa2a214dde1; files: extensions/voice-call/src/manager/outbound.ts)

PR surface

Source +8, Tests +45, Other +2. Total +55 across 4 files. Added test files: 0.

View PR surface stats
Area Files Added Removed Net
Source 1 8 0 +8
Tests 2 46 1 +45
Docs 0 0 0 0
Config 0 0 0 0
Generated 0 0 0 0
Other 1 2 0 +2
Total 4 56 1 +55

Labels

Label changes:

  • add P2: The PR repairs truncated notifications in one optional carrier path, with limited blast radius.
  • add rating: 🧂 unranked krab: Overall readiness is 🧂 unranked krab; proof is 🧂 unranked krab and patch quality is 🦪 silver shellfish.
  • add status: 📣 needs proof: The PR needs real behavior proof before ClawSweeper can clear the contributor ask.

Label justifications:

  • P2: The PR repairs truncated notifications in one optional carrier path, with limited blast radius.
  • rating: 🧂 unranked krab: Overall readiness is 🧂 unranked krab; proof is 🧂 unranked krab and patch quality is 🦪 silver shellfish.
  • status: 📣 needs proof: The PR needs real behavior proof before ClawSweeper can clear the contributor ask.

Rating scale

6/6 🦀 challenger crab · 5/6 🦞 diamond lobster · 4/6 🐚 platinum hermit · 3/6 🦐 gold shrimp · 2/6 🦪 silver shellfish · 1/6 🧂 unranked krab. Overall follows the weaker of proof and patch quality; ✨ marks media proof (a screenshot, video, or linked artifact) that directly shows the changed behavior.

Workflow

ClawSweeper edits this one comment on every review. Comment @clawsweeper re-review for a fresh review only. Repair and merge execution lanes are retired.

Reviewed November 2, 2026, 11:41 AM ET / 16:41 UTC.

@GoatInAHat
GoatInAHat force-pushed the voice-call-notify-inline-hangup branch from f987657 to cf0c1bb Compare November 2, 2026 17:50
@GoatInAHat

Copy link
Copy Markdown
Contributor Author

Addressed the P2 finding in cf0c1bbb8a0. The pre-dial replay guard now moves the message to pendingInlineNotifyMessage; it does not claim playback. Only call.answered consumes that marker, persists notifyStatus: "playing", and appends the bot transcript before dispatching answer effects.

Regressions cover rejected create-call requests; busy, no-answer, and failed calls ending without assistant speech/status; normal and early answered callbacks; no duplicate TTS or three-second hangup; repeated answered callbacks and carrier completion; and Plivo/Telnyx still speaking on answer. All 132 tests in the four requested files passed (104.93s wall). The six strengthened failure/timing cases failed on the previous patch before repair.

git diff --check, strict source-backed typecheck, focused lint/format, and the 97-line test allocation ratchet passed. pnpm check:changed remains incomplete: the bounded 900s run timed out with SIGTERM/exit 143 in the repository-wide SQLite worker semantic scan (838.50s in that step, no violation diagnostic). The PR body records the exact aggregate-check gap and the narrow checks used instead.

The PR body now includes the sanitized production before trace and explicitly keeps live Gateway-plus-Twilio after proof open. Could a maintainer verify using an isolated Twilio setup, or specify the minimal trace they would accept? No production changes or live calls were made for this revision.

@codex review

@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: cf0c1bbb8a

ℹ️ 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".

@GoatInAHat

Copy link
Copy Markdown
Contributor Author

Local-finalization P2 fixed in ce1bec4: playing notifications interrupted by endCall or max-duration timeout now persist failed plus a reason-specific notifyError. Both cases failed on cf0c1bb and now pass, including late-callback terminal-record protection. All 134 requested tests pass (111.78s); narrow strict types, lint, format, test-line ratchet and diff checks pass. PR Evidence updated. Live Gateway/Twilio after proof remains open and no production changes or calls were made.

@codex review

@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: ce1bec4902

ℹ️ 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".

@GoatInAHat

Copy link
Copy Markdown
Contributor Author

@codex review

@chatgpt-codex-connector

Copy link
Copy Markdown
Contributor

Codex Review: Didn't find any major issues. Another round soon, please!

Reviewed commit: 15a5ac3486

ℹ️ 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".

This branch has not been deployed

No deployments
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

channel: voice-call Channel integration: voice-call P2 Normal backlog priority with limited blast radius. rating: 🧂 unranked krab Not merge-ready due to missing proof or serious correctness/safety concerns. size: M status: 📣 needs proof The PR needs real behavior proof before ClawSweeper can clear the contributor ask.

Projects

None yet

Development

Successfully merging this pull request may close these issues.

[Bug]: Twilio notify calls restart playback and hang up after three seconds

1 participant