Skip to content

refactor(realtime): share audio duration calculation - #125612

Merged
steipete merged 1 commit into
mainfrom
steipete/realtime-audio-duration-clamp
Aug 18, 2026
Merged

steipete merged 1 commit into
mainfrom
steipete/realtime-audio-duration-clamp

Conversation

@steipete

Copy link
Copy Markdown
Contributor

Historical context: #79980, reported by @rparikh1019.

What Problem This Solves

Fixes an issue where xAI realtime voice users interrupting assistant audio could send an audio_end_ms later than the audio the provider had actually produced. In the captured regression, both manual G.711 interruption and server-VAD PCM16 interruption reported 3760 ms even though only 3700 ms of decoded audio existed. That can make provider conversation history retain an invalid playback boundary.

Why This Change Was Made

The xAI owner now tracks the active assistant item as its item ID, decoded byte count, and relay start timestamp. Manual and server-VAD interruption clamp the truncation point to the smaller of produced audio duration and elapsed relay playback, while xAI lifecycle, playback-mark, cancellation, and error semantics remain local to that provider.

The exact byte/format duration primitive now lives beside RealtimeVoiceAudioFormat and is exported through the existing openclaw/plugin-sdk/realtime-voice seam. It returns fractional milliseconds without rounding. OpenAI and xAI apply caller-owned Math.floor truncation for provider-safe upper bounds; Google applies caller-owned Math.round for silence accumulation. This public helper pays rent immediately across three current providers and removes duplicated codec arithmetic without adding a new SDK subpath.

External contract checks support this boundary: xAI and OpenAI define audio_end_ms as milliseconds actually played and accept conversation.item.truncate; output deltas carry base64 codec bytes, while completion events carry no duration. Google uses the same byte/format duration primitive for input-silence accounting but retains server-owned interruption behavior.

This does not change voice-call disconnect grace, generalize provider interruption state, or move Google/GPT-Live interruption ownership into the shared helper.

Provenance: the xAI clock-only truncation was introduced/carried by #106267 (6c5084f1adb39088c19788b8fbe200b9c3c382d9), authored and merged by @steipete on 2026-07-13 with Vitor Cepeda Lopes as co-author. The equivalent OpenAI invariant was repaired in #125502; this change reuses that invariant and removes duplicated duration math. Current PR author: @steipete.

Production LOC: +57/-46 (net +11). Tests: +47/-9 (net +38). Roughly +4 production lines are the xAI owner repair; the remaining growth establishes and adopts the shared three-consumer SDK contract. No generated tracked file or changelog changed.

User Impact

xAI realtime voice interruptions now truncate provider history only to audio that could actually have played, avoiding the 3700/3760 mismatch. OpenAI retains its existing safe truncation behavior, and Google retains its existing silence and interruption behavior while all three providers share one exact duration calculation.

Evidence

  • Pre-fix owner regression: 2 failed, 71 passed. Manual G.711 and server-VAD PCM16 both emitted 3760 ms instead of the expected 3700 ms.
  • Post-fix lead focused proof: 244 tests passed across Plugin SDK, OpenAI, xAI, and Google. After rebasing onto current origin/main, the same seven-file suite passed 245 tests; one routed test was added by intervening main history.
  • node scripts/check-changed.mjs: passed for core, coreTests, extensions, and extensionTests.
  • pnpm plugin-sdk:surface:check: passed; 146 public Plugin SDK subpaths verified.
  • pnpm build: passed; 146 Plugin SDK subpaths verified and no ineffective dynamic imports reported. Only existing dependency EVAL warnings appeared.
  • Formatting and git diff --check passed before publication; git diff --check origin/main...HEAD passed after rebase.
  • Authenticated live proof: temporary OpenAI and xAI mid-response probes advanced the transport clock 60 ms beyond decoded G.711 duration and each received conversation.item.truncated (2/2 passed). Temporary files were removed and no secret was printed.
  • Final integrated Codex-backed autoreview of the eight-file diff: clean, with no accepted/actionable findings. A fresh pre-commit staged-diff autoreview also passed cleanly.
  • Rebase was conflict-free and patch-equivalent: stable patch ID remained 7afa5a8be9dae380dd6149eb164436179487f5c8.

AI-assisted: yes. The author reviewed the implementation, understands the provider ownership boundaries, and verified the change with deterministic and authenticated live evidence.

Fix xAI barge-in truncation that reported 3760 ms after only 3700 ms of decoded audio.

Share exact audio-duration math across OpenAI, xAI, and Google while keeping provider-specific rounding at each caller.
@clawsweeper

clawsweeper Bot commented Aug 18, 2026

Copy link
Copy Markdown
Contributor

🦞👀
ClawSweeper picked this up.

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

@steipete
steipete marked this pull request as ready for review August 18, 2026 05:00
@openclaw-barnacle openclaw-barnacle Bot added size: S maintainer Maintainer-authored PR labels Aug 18, 2026
@clawsweeper clawsweeper Bot added P2 Normal backlog priority with limited blast radius. rating: 🐚 platinum hermit Good normal PR readiness with ordinary maintainer review expected. status: 👀 ready for maintainer look ClawSweeper has no concrete contributor-facing blocker left for this PR. labels Aug 18, 2026
@clawsweeper

clawsweeper Bot commented Aug 18, 2026

Copy link
Copy Markdown
Contributor

Codex review: needs maintainer review before merge. Reviewed August 18, 2026, 1:11 AM ET / 05:11 UTC.

ClawSweeper review

What this changes

This PR clamps xAI realtime interruption truncation to decoded audio actually produced and shares byte-to-duration arithmetic across xAI, OpenAI, and Google voice providers.

Regression provenance

Possible regression — probable (reproduction; reviewed change). No predecessor PR is attributed.

Merge readiness

⚠️ Ready for maintainer review - 3 items remain

Keep this maintainer-authored PR open for normal exact-head CI and maintainer handling. Source review found no correctness finding: it records the produced-audio fact at the xAI owner and preserves each provider’s existing rounding policy.

Priority: P2
Reviewed head: 10b0557480f3d717e869bfc55faf97a94614e07f

Review scores

Measure Result What it means
Overall readiness 🐚 platinum hermit (4/6) A focused owner-boundary repair with meaningful regression coverage and documented authenticated provider probes; no actionable correctness finding was found.
Proof confidence 🐚 platinum hermit (4/6) Not applicable: The real-behavior-proof gate is not required for this member-authored PR; its body nevertheless records authenticated OpenAI and xAI after-fix truncation acknowledgements.
Patch quality 🐚 platinum hermit (4/6) No actionable review findings were identified.

Verification

Check Result Evidence
Real behavior Not applicable Not applicable: The real-behavior-proof gate is not required for this member-authored PR; its body nevertheless records authenticated OpenAI and xAI after-fix truncation acknowledgements.
Evidence reviewed 6 items Current-main defect path: The current-main tree calculates xAI truncation only from elapsed relay time, so a relay clock beyond produced audio can send an overlong boundary.
Owner-boundary repair: The PR records decoded bytes for the active xAI item at audio ingress and clamps truncation to the smaller of produced duration and relay elapsed time.
Regression coverage: The provider-boundary cases exercise G.711 manual interruption and PCM16 server-VAD interruption with a 3760-ms clock and require the 3700-ms produced-audio boundary.
Findings None None.
Security None None.

How this fits together

Realtime voice providers stream assistant audio through a relay and truncate provider history when a caller interrupts playback. The shared private Plugin SDK runtime helper converts decoded audio bytes to duration while each provider retains its own interruption and rounding rules.

flowchart LR
  Audio[Decoded provider audio] --> Format[Negotiated audio format]
  Format --> Duration[Shared duration helper]
  Audio --> Duration
  Duration --> XAI[xAI interruption clamp]
  Duration --> OpenAI[OpenAI interruption clamp]
  Duration --> Google[Google silence accounting]
  XAI --> Truncate[Provider history truncation]
Loading

Before merge

  • Resolve merge risk (P1) - The bug fix adds 11 net production lines; the three-consumer helper and the xAI-produced-audio record justify the growth, but the shared helper should stay limited to this closed format contract.
  • Resolve merge risk (P1) - Official xAI and OpenAI protocol documentation could not be independently fetched because DNS is unavailable in this review environment; the PR’s documented authenticated probes are therefore the available contract proof.
  • Complete next step (P2) - No repair lane is needed: this is a coherent member-authored patch with no actionable review finding.
Agent review details

Security

None.

PR surface

Source +11, Tests +38. Total +49 across 8 files.

View PR surface stats
Area Files Added Removed Net
Source 6 57 46 +11
Tests 2 47 9 +38
Docs 0 0 0 0
Config 0 0 0 0
Generated 0 0 0 0
Other 0 0 0 0
Total 8 104 55 +49

Review metrics

Metric Value Why it matters
Production versus tests production +57/-46 (net +11); tests +47/-9 (net +38) The production growth is limited to the xAI owner record and one shared three-consumer duration primitive; the added tests cover format and interruption boundaries.

Root-cause cluster

Relationship: canonical
Canonical: #125612
Summary: This PR is the canonical xAI repair for the produced-audio truncation invariant; the earlier OpenAI repair shares the invariant but not the xAI owner path.

Members:

Proposal only: this assessment does not dispatch repair, suppress jobs, mutate sibling items, close, or merge anything.

Merge-risk options

Maintainer options:

  1. Decide the mitigation before merge
    Keep the xAI item record at its audio producer and the generic duration calculation in the existing private runtime seam, then validate the external protocol references when network access is available before merge.
  2. Pause or close
    Do not merge this PR until maintainers decide whether the risk is worth taking.

Technical review

Best possible solution:

Keep the xAI item record at its audio producer and the generic duration calculation in the existing private runtime seam, then validate the external protocol references when network access is available before merge.

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

Yes, source-reproducible: current main uses elapsed relay time alone, while the focused regression fixtures make the relay clock exceed 3700 ms of decoded G.711 or PCM16 audio.

Is this the best way to solve the issue?

Yes. Recording decoded-byte duration at the xAI audio producer and sharing only stateless duration math is the narrow owner-boundary repair; OpenAI and Google retain their different rounding semantics.

AGENTS.md: found and applied where relevant.

Codex review notes: model internal, reasoning high; reviewed against e6a427c493da.

Labels

Label changes:

  • add P2: This is a bounded realtime voice interruption defect that can preserve an invalid provider conversation boundary.
  • add rating: 🐚 platinum hermit: Overall readiness is 🐚 platinum hermit; proof is 🐚 platinum hermit and patch quality is 🐚 platinum hermit.
  • add status: 👀 ready for maintainer look: ClawSweeper has no concrete contributor-facing blocker left for this PR. Not applicable: The real-behavior-proof gate is not required for this member-authored PR; its body nevertheless records authenticated OpenAI and xAI after-fix truncation acknowledgements.

Label justifications:

  • P2: This is a bounded realtime voice interruption defect that can preserve an invalid provider conversation boundary.
  • rating: 🐚 platinum hermit: Overall readiness is 🐚 platinum hermit; proof is 🐚 platinum hermit and patch quality is 🐚 platinum hermit.
  • status: 👀 ready for maintainer look: ClawSweeper has no concrete contributor-facing blocker left for this PR. Not applicable: The real-behavior-proof gate is not required for this member-authored PR; its body nevertheless records authenticated OpenAI and xAI after-fix truncation acknowledgements.

Evidence

What I checked:

Likely related people:

  • steipete: Authored the current repair, the original merged xAI realtime provider, and the recent Talk realtime ownership work. (role: feature owner and current change author; confidence: high; commits: 10b0557480f3, 6c5084f1adb3, df4e6666c6ba; files: extensions/xai/realtime-voice-protocol.ts, extensions/xai/realtime-voice-events.ts, src/talk/provider-types.ts)
  • Vincent Koc: Recent history includes xAI playback-mark and lifecycle repairs in the exact protocol and event area. (role: recent xAI realtime contributor; confidence: high; commits: 73544a73afca, b4ec765e00cc, fd16d9ad8ed4; files: extensions/xai/realtime-voice-protocol.ts, extensions/xai/realtime-voice-events.ts, extensions/xai/realtime-voice-provider.test.ts)

Rating scale

Score Internal tier Crab rank Meaning
6/6 S 🦀 challenger crab Exceptional readiness
5/6 A 🦞 diamond lobster Very strong readiness
4/6 B 🐚 platinum hermit Good normal PR; ordinary maintainer review
3/6 C 🦐 gold shrimp Useful, but confidence is limited
2/6 D 🦪 silver shellfish Proof or implementation needs work
1/6 F 🧂 unranked krab Not merge-ready
N/A NA 🌊 off-meta tidepool Rating does not apply

Overall follows the weaker of proof and patch quality.
Shiny media proof means a screenshot, video, or linked artifact directly shows the changed behavior. Runtime, network, CSP, and security claims still need visible diagnostics.

Workflow

  • ClawSweeper keeps one durable marker-backed review comment per issue or PR.
  • Re-runs edit this comment so the latest verdict, findings, and automation markers stay together instead of adding duplicate bot comments.
  • A fresh review can be triggered by eligible @clawsweeper re-review comments, exact-item GitHub events, scheduled/background review runs, or manual workflow dispatch.
  • PR/issue authors and users with repository write access can comment @clawsweeper re-review or @clawsweeper re-run on an open PR or issue to request a fresh review only.
  • Maintainers can also comment @clawsweeper review to request a fresh review only.
  • Fresh-review commands do not start repair, autofix, rebase, CI repair, or automerge.
  • Maintainer-only repair and merge flows require explicit commands such as @clawsweeper autofix, @clawsweeper automerge, @clawsweeper fix ci, or @clawsweeper address review.
  • Maintainers can comment @clawsweeper explain to ask for more context, or @clawsweeper stop to stop active automation.

@steipete

Copy link
Copy Markdown
Contributor Author

Land-ready verification for exact head 10b0557480f3d717e869bfc55faf97a94614e07f:

  • Current-main defect reproduced before repair: manual G.711 and server-VAD PCM16 xAI interruption both emitted audio_end_ms: 3760 with only 3,700 ms of decoded audio; 2 tests failed and 71 passed.
  • Owner repair: xAI records item ID, decoded bytes, and relay start time at the audio producer, then both interruption paths clamp elapsed playback to produced duration.
  • Shared refactor: realtimeVoiceAudioDurationMs returns exact fractional milliseconds through the existing realtime voice SDK seam. OpenAI and xAI retain caller-owned Math.floor; Google retains caller-owned Math.round. Provider interruption state remains local.
  • Lead focused proof passed 244 tests before publication. The conflict-free, patch-equivalent rebase passed the same routed suite with 245 tests after one new main test joined the selection.
  • Full changed-path gate passed for core, core tests, extensions, and extension tests.
  • pnpm plugin-sdk:surface:check passed; pnpm build passed and verified all 146 Plugin SDK subpaths with no ineffective dynamic imports.
  • Authenticated live proof passed after the shared refactor: OpenAI and xAI mid-response probes each advanced the transport clock 60 ms past decoded G.711 duration and received conversation.item.truncated (2/2 passed). Temporary probes were removed and no secret was printed.
  • Exact-head CI is green: https://github.com/openclaw/openclaw/actions/runs/32101203017
  • Final integrated Codex-backed branch autoreview is clean with no accepted/actionable findings.
  • Latest ClawSweeper review is 4/6 with no correctness or security findings.

Maintainer decisions:

  • I accept production +57/-46 (net +11) and tests +47/-9 (net +38). Roughly four production lines record the missing xAI provider-owned decoded-duration fact. The remaining growth establishes one narrow helper/export used immediately by OpenAI, xAI, and Google; the three consumer migrations remove their duplicate codec arithmetic while retaining provider-specific policy.
  • ClawSweeper's documentation-network limitation is resolved: the official xAI Realtime reference and speech-to-speech format documentation were inspected directly, as was the OpenAI truncation contract. The authenticated provider probes independently confirm both services accept the clamped event.
  • Historical issue Feature request: native xAI Grok Voice Agent API support in voice-call realtime #79980 remains closed feature context; this PR neither reopens nor claims to close it.

Known proof gap: the exact head was not redeployed for another full Twilio phone call. The provider contracts were exercised live, and the Twilio clock-overrun shape plus both xAI interruption modes have deterministic owner-boundary coverage.

@steipete

Copy link
Copy Markdown
Contributor Author

@clawsweeper re-review

@clawsweeper

clawsweeper Bot commented Aug 18, 2026 •

Copy link
Copy Markdown
Contributor

🦞🧹
ClawSweeper re-review requested.

I asked ClawSweeper to review this item again.
Action: item re-review queued (workflow sweep.yml, event exact_review_queue).
Result: when the review finishes, ClawSweeper will create the durable review comment if needed or update the existing comment in place.

Re-review progress:

@steipete
steipete merged commit 31afd52 into main Aug 18, 2026
285 checks passed
@steipete
steipete deleted the steipete/realtime-audio-duration-clamp branch August 18, 2026 05:25
@steipete

Copy link
Copy Markdown
Contributor Author

Merged via squash.

@steipete

Copy link
Copy Markdown
Contributor Author

@clawsweeper re-review

@clawsweeper

clawsweeper Bot commented Aug 18, 2026 •

Copy link
Copy Markdown
Contributor

🦞🧹
ClawSweeper could not start a re-review for this item.

Reason: re-review requires an open issue or PR.

@steipete

Copy link
Copy Markdown
Contributor Author

@clawsweeper re-review

github-actions Bot pushed a commit to Desicool/openclaw that referenced this pull request Aug 20, 2026
Fix xAI barge-in truncation that reported 3760 ms after only 3700 ms of decoded audio.

Share exact audio-duration math across OpenAI, xAI, and Google while keeping provider-specific rounding at each caller.
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

extensions: google extensions: openai extensions: xai maintainer Maintainer-authored PR P2 Normal backlog priority with limited blast radius. rating: 🐚 platinum hermit Good normal PR readiness with ordinary maintainer review expected. size: S status: 👀 ready for maintainer look ClawSweeper has no concrete contributor-facing blocker left for this PR.

Projects

None yet

Development

Successfully merging this pull request may close these issues.

1 participant