Skip to content

fix(twilio): save the hang-up and transfer lines the caller hears the dialogs - #1523

Open
yileicn wants to merge 1 commit into
SciSharp:masterfrom
yileicn:fix/twilio-save-spoken-hangup-transfer-lines
Open

yileicn wants to merge 1 commit into
SciSharp:masterfrom
yileicn:fix/twilio-save-spoken-hangup-transfer-lines

Conversation

@yileicn

@yileicn yileicn commented Dec 1, 2026

Copy link
Copy Markdown
Member

The hang-up response_content and the transfer transition_message are played as audio files by the redirect endpoints, not spoken in the realtime stream, so they never reached the conversation dialogs. Append them as an assistant message before the redirect, which closes the stream and disposes the scope, and only when the audio file exists.

…the dialogs

The hang-up response_content and the transfer transition_message are played
as audio files by the redirect endpoints, not spoken in the realtime stream,
so they never reached the conversation dialogs. Append them as an assistant
message before the redirect, which closes the stream and disposes the scope,
and only when the audio file exists.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
@qodo-code-review

qodo-code-review Bot commented Dec 1, 2026 •

Copy link
Copy Markdown
Contributor

PR Summary by Qodo

fix(twilio): save hang-up and transfer lines to conversation dialogs

🐞 Bug fix 🕐 Less than 10 minutes

Grey Divider

AI Description

• Hang-up and transfer lines are played as audio by redirect endpoints, so they were never saved to
 dialogs.
• Both functions now append the spoken line as an assistant message before the redirect.
• The save runs only when the audio file is actually generated, so dialogs match what the caller
 hears.
Merge Risk 🟡 Medium

Blast radius 🟢 Low 💥 0 capabilities

  • Fault-specific containment limits risk to the originating changed behavior.
Behavioral complexity 🟡 Medium 🧩 Coordinated invariants

  • Before, generated ending audio was followed directly by redirect.
  • After, persistent dialog append precedes redirect.
  • New correctness condition: storage and call termination must remain ordered without making hang-up unavailable when persistence fails.
  • The semaphore and repository persistence are existing infrastructure; the changed interaction is their placement in the call-control sequence.
Potential damage 🟡 Medium 🩹 Temporary loss

  • Conservative damage bound for the originating changed behavior; downstream capabilities remain contained.
  • A storage exception can prevent the hang-up redirect, so the call may remain active until another control path or manual action ends it.
  • Reverting removes this new prerequisite, but an already active call needs recovery.
  • The code change can be reverted to stop new occurrences; an affected active call still requires a later hang-up action, so recovery is not automatic.
Assessed commit 1281e12
Diagram

sequenceDiagram
    participant LLM as Agent LLM
    participant Fn as Hangup/Transfer Fn
    participant TS as TwilioService
    participant CS as ConversationStorage
    participant TW as Twilio Redirect
    LLM->>Fn: Call function with response line
    Fn->>TS: SaveSpeechAsync (audio file)
    TS-->>Fn: init-audio-file path
    Fn->>CS: Append assistant message
    Fn->>TW: TryRedirectCallAsync with audio URL
    TW-->>Fn: Stream closed, scope disposed
Loading
High-Level Assessment

The following are alternative approaches to this PR:

1. Persist inside TwilioService or the redirect helper
  • ➕ Single place handles audio generation and dialog persistence for both functions
  • ➕ Removes duplicated save blocks in each function
  • ➖ Mixes persistence into a transport service
  • ➖ Needs the message role and agent id passed in, which widens the helper's signature
2. Save from the redirect endpoint when it plays the init audio
  • ➕ Records only what was actually played, including the case where the redirect fails
  • ➕ Covers any future caller of init-audio-file
  • ➖ Redirect endpoints run in a new request scope, so the agent id and conversation context must be reconstructed
  • ➖ Harder to test than a function-level change

Recommendation: The PR's approach is reasonable and minimal: it saves before the scope is disposed, and only when audio exists. Two review points: the transfer path saves the line even if TryRedirectCallAsync returns false (call already ended), and the hang-up path saves even when the call has already ended. Consider saving after a successful redirect, or moving the duplicated block into a shared helper.

Files changed (2) +16 / -0

Bug fix (2) +16 / -0
HangupPhoneCallFn.csPersist hang-up response line as assistant message before redirect +8/-0

Persist hang-up response line as assistant message before redirect

• After generating the ending audio file, appends the response content as an assistant dialog message using IConversationStorage. The save happens before TryRedirectCallAsync because the redirect closes the stream and disposes the scope.

src/Plugins/BotSharp.Plugin.Twilio/OutboundPhoneCallHandler/Functions/HangupPhoneCallFn.cs

TransferPhoneCallFn.csPersist transfer transition message as assistant message before redirect +8/-0

Persist transfer transition message as assistant message before redirect

• After generating the transfer audio file, appends the transition message as an assistant dialog message. The save is guarded by the audio file existing and runs before the transfer redirect.

src/Plugins/BotSharp.Plugin.Twilio/OutboundPhoneCallHandler/Functions/TransferPhoneCallFn.cs

@qodo-code-review

Copy link
Copy Markdown
Contributor

Code Review by Qodo

🐞 Bugs (3) 📘 Rule violations (0) 📜 Skill insights (0)

Grey Divider


Action required

1. Storage failures block live call redirects 🐞 Bug ☼ Reliability
Description
Both phone-call functions await the new IConversationStorage.Append before calling
TryRedirectCallAsync, without handling persistence errors. If the repository write fails after
audio generation, the exception prevents a live call from reaching its hang-up or transfer redirect.
Code

src/Plugins/BotSharp.Plugin.Twilio/OutboundPhoneCallHandler/Functions/HangupPhoneCallFn.cs[R58-59]

+                var storage = _services.GetRequiredService<IConversationStorage>();
+                await storage.Append(conversationId, new RoleDialogModel(AgentRole.Assistant, args.ResponseContent)
Evidence
Both newly added appends precede their redirects. ConversationStorage lets repository exceptions
propagate, so a failed write exits the function before Twilio receives the redirect.

src/Plugins/BotSharp.Plugin.Twilio/OutboundPhoneCallHandler/Functions/HangupPhoneCallFn.cs[58-67]
src/Plugins/BotSharp.Plugin.Twilio/OutboundPhoneCallHandler/Functions/TransferPhoneCallFn.cs[63-70]
src/Infrastructure/BotSharp.Core/Conversations/Services/ConversationStorage.cs[21-50]

Agent prompt
The issue below was found during a code review. Follow the provided context and guidance below and implement a solution

## Issue description
A failed dialog write prevents either phone-call function from redirecting the live call.
## Fix Focus Areas
- src/Plugins/BotSharp.Plugin.Twilio/OutboundPhoneCallHandler/Functions/HangupPhoneCallFn.cs[58-67]
- src/Plugins/BotSharp.Plugin.Twilio/OutboundPhoneCallHandler/Functions/TransferPhoneCallFn.cs[63-70]
## Recommended Fix
Make dialog persistence best-effort in both functions: catch and log append failures with their exception, then attempt the redirect regardless. Preserve the intended dialog write when storage is available.

ⓘ Copy this prompt and use it to remediate the issue with your preferred AI generation tools

Dismiss ↗ | View ↗



Remediation recommended

2. Ended calls gain lines they never heard 🐞 Bug ≡ Correctness
Description
The new assistant dialog is appended before TryRedirectCallAsync determines whether the call can
be redirected. When Twilio reports that a call has already ended, the service returns false
without delivering the audio, but both functions have already stored the line as spoken.
Code

src/Plugins/BotSharp.Plugin.Twilio/OutboundPhoneCallHandler/Functions/TransferPhoneCallFn.cs[R63-64]

+                var storage = _services.GetRequiredService<IConversationStorage>();
+                await storage.Append(conversationId, new RoleDialogModel(AgentRole.Assistant, args.TransitionMessage)
Evidence
The appends run before the redirect. The redirect service explicitly returns false for a call that
is no longer in progress; only the redirected endpoints add the audio file to the Twilio response.

src/Plugins/BotSharp.Plugin.Twilio/OutboundPhoneCallHandler/Functions/TransferPhoneCallFn.cs[63-75]
src/Plugins/BotSharp.Plugin.Twilio/OutboundPhoneCallHandler/Functions/HangupPhoneCallFn.cs[58-67]
src/Plugins/BotSharp.Plugin.Twilio/Services/TwilioService.cs[511-525]
src/Plugins/BotSharp.Plugin.Twilio/Controllers/TwilioVoiceController.cs[309-347]

Agent prompt
The issue below was found during a code review. Follow the provided context and guidance below and implement a solution

## Issue description
Hang-up and transfer record audio lines even when Twilio says the call was already over and no audio could be delivered.
## Fix Focus Areas
- src/Plugins/BotSharp.Plugin.Twilio/OutboundPhoneCallHandler/Functions/HangupPhoneCallFn.cs[58-67]
- src/Plugins/BotSharp.Plugin.Twilio/OutboundPhoneCallHandler/Functions/TransferPhoneCallFn.cs[63-75]
## Recommended Fix
Account for the redirect result before recording a line as delivered in both functions. Preserve the required storage lifetime when arranging the redirect and write, and do not persist a spoken-line dialog when the redirect returns false.

ⓘ Copy this prompt and use it to remediate the issue with your preferred AI generation tools

Dismiss ↗ | View ↗


3. Reused audio gets the wrong transcript 🐞 Bug ≡ Correctness
Description
Both functions append the current text whenever SaveSpeechAsync returns a filename, although that
filename can refer to an existing recording of different text. On a repeated hang-up or transfer in
a realtime conversation without a synthesis model, the fixed-name audio file is reused while the new
dialog records the latest argument instead.
Code

src/Plugins/BotSharp.Plugin.Twilio/OutboundPhoneCallHandler/Functions/HangupPhoneCallFn.cs[59]

+                await storage.Append(conversationId, new RoleDialogModel(AgentRole.Assistant, args.ResponseContent)
Evidence
SaveSpeechAsync uses fixed filenames and returns an existing MP3 without examining the new text when
realtime audio synthesis is unavailable. The changed appends store the new arguments, while the
redirect endpoints play the returned file.

src/Plugins/BotSharp.Plugin.Twilio/Services/TwilioService.cs[470-486]
src/Plugins/BotSharp.Plugin.Twilio/OutboundPhoneCallHandler/Functions/HangupPhoneCallFn.cs[47-59]
src/Plugins/BotSharp.Plugin.Twilio/OutboundPhoneCallHandler/Functions/TransferPhoneCallFn.cs[53-64]
src/Plugins/BotSharp.Plugin.Twilio/Controllers/TwilioVoiceController.cs[309-347]

Agent prompt
The issue below was found during a code review. Follow the provided context and guidance below and implement a solution

## Issue description
A returned audio filename does not always mean the file contains the current hang-up or transfer text.
## Fix Focus Areas
- src/Plugins/BotSharp.Plugin.Twilio/OutboundPhoneCallHandler/Functions/HangupPhoneCallFn.cs[47-62]
- src/Plugins/BotSharp.Plugin.Twilio/OutboundPhoneCallHandler/Functions/TransferPhoneCallFn.cs[53-67]
- src/Plugins/BotSharp.Plugin.Twilio/Services/TwilioService.cs[470-486]
## Recommended Fix
When speech generation reuses an existing file, obtain and store the text associated with that file rather than the latest argument. Alternatively, generate a distinct audio file for each distinct line before appending its text.

ⓘ Copy this prompt and use it to remediate the issue with your preferred AI generation tools

Dismiss ↗ | View ↗


Grey Divider

Context sources
Review mode: Auto: ⚖️ Balanced: Runtime persistence changes affect conversation history and redirect lifecycle.

Grey Divider

Tip of the day
💡 Did you know, you can pick a display mode instead of tweaking every Display option by hand

More tips ↗ | Customize Qodo ↗ | Qodo docs ↗

Grey Divider

Qodo Logo

Comment on lines +58 to +59
var storage = _services.GetRequiredService<IConversationStorage>();
await storage.Append(conversationId, new RoleDialogModel(AgentRole.Assistant, args.ResponseContent)

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.

Action required

1. Storage failures block live call redirects 🐞 Bug ☼ Reliability

Both phone-call functions await the new IConversationStorage.Append before calling
TryRedirectCallAsync, without handling persistence errors. If the repository write fails after
audio generation, the exception prevents a live call from reaching its hang-up or transfer redirect.
Agent Prompt
## Issue description
A failed dialog write prevents either phone-call function from redirecting the live call.
## Fix Focus Areas
- src/Plugins/BotSharp.Plugin.Twilio/OutboundPhoneCallHandler/Functions/HangupPhoneCallFn.cs[58-67]
- src/Plugins/BotSharp.Plugin.Twilio/OutboundPhoneCallHandler/Functions/TransferPhoneCallFn.cs[63-70]
## Recommended Fix
Make dialog persistence best-effort in both functions: catch and log append failures with their exception, then attempt the redirect regardless. Preserve the intended dialog write when storage is available.

ⓘ Copy this prompt and use it to remediate the issue with your preferred AI generation tools

Dismiss ↗ | View ↗

Comment on lines +63 to +64
var storage = _services.GetRequiredService<IConversationStorage>();
await storage.Append(conversationId, new RoleDialogModel(AgentRole.Assistant, args.TransitionMessage)

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.

Remediation recommended

2. Ended calls gain lines they never heard 🐞 Bug ≡ Correctness

The new assistant dialog is appended before TryRedirectCallAsync determines whether the call can
be redirected. When Twilio reports that a call has already ended, the service returns false
without delivering the audio, but both functions have already stored the line as spoken.
Agent Prompt
## Issue description
Hang-up and transfer record audio lines even when Twilio says the call was already over and no audio could be delivered.
## Fix Focus Areas
- src/Plugins/BotSharp.Plugin.Twilio/OutboundPhoneCallHandler/Functions/HangupPhoneCallFn.cs[58-67]
- src/Plugins/BotSharp.Plugin.Twilio/OutboundPhoneCallHandler/Functions/TransferPhoneCallFn.cs[63-75]
## Recommended Fix
Account for the redirect result before recording a line as delivered in both functions. Preserve the required storage lifetime when arranging the redirect and write, and do not persist a spoken-line dialog when the redirect returns false.

ⓘ Copy this prompt and use it to remediate the issue with your preferred AI generation tools

Dismiss ↗ | View ↗

// The caller hears this as audio, so keep it in the dialogs too. Save it before the redirect,
// which closes the stream and disposes this scope.
var storage = _services.GetRequiredService<IConversationStorage>();
await storage.Append(conversationId, new RoleDialogModel(AgentRole.Assistant, args.ResponseContent)

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.

Remediation recommended

3. Reused audio gets the wrong transcript 🐞 Bug ≡ Correctness

Both functions append the current text whenever SaveSpeechAsync returns a filename, although that
filename can refer to an existing recording of different text. On a repeated hang-up or transfer in
a realtime conversation without a synthesis model, the fixed-name audio file is reused while the new
dialog records the latest argument instead.
Agent Prompt
## Issue description
A returned audio filename does not always mean the file contains the current hang-up or transfer text.
## Fix Focus Areas
- src/Plugins/BotSharp.Plugin.Twilio/OutboundPhoneCallHandler/Functions/HangupPhoneCallFn.cs[47-62]
- src/Plugins/BotSharp.Plugin.Twilio/OutboundPhoneCallHandler/Functions/TransferPhoneCallFn.cs[53-67]
- src/Plugins/BotSharp.Plugin.Twilio/Services/TwilioService.cs[470-486]
## Recommended Fix
When speech generation reuses an existing file, obtain and store the text associated with that file rather than the latest argument. Alternatively, generate a distinct audio file for each distinct line before appending its text.

ⓘ Copy this prompt and use it to remediate the issue with your preferred AI generation tools

Dismiss ↗ | View ↗

@yuyixg

yuyixg commented Dec 1, 2026

Copy link
Copy Markdown
Contributor

reviewed

@yileicn

yileicn commented Dec 1, 2026

Copy link
Copy Markdown
Member Author

✅ AegisCode Code Review Report: Pass

No counted findings.
Full report · review 12167 · commit 1281e120

Unit Tests: not run (No unit tests were found)

Test Coverage: Failed

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