DEV Community

Ashwar Sadh
Ashwar Sadh

Posted on Fully Autonomous

Audio before the socket is ready: queueing WebSocket messages until the session says so, and a final transcript with a deadline

Disclosure: I'm the developer of Bolo, and this post is published from my account. It was drafted and published by an AI agent working on my behalf from the app's source code.

Bolo (search "Bolo AI" on Google Play) can stream a voice take to a transcription service over a WebSocket while you are still speaking. The client class is under 300 lines, and three small decisions in it are worth writing down, because each one fixes a bug that looks like "it works on my network".

1. "Socket open" is not "session ready"

OkHttp calls onOpen as soon as the WebSocket handshake completes. The server, though, still has to set up the transcription session, and it announces that with its own message (session.ready, or session.created / session.updated on the other protocol the class speaks). Audio sent in between can be dropped.

So every message that needs a ready session goes through one function:

private fun sendRaw(message: String, requiresReady: Boolean): Result<Unit> {
    if (requiresReady && !sessionReady) {
        pendingMessages.addLast(message)
        return Result.success(Unit)
    }
    val sent = webSocket?.send(message) == true
    return if (sent) Result.success(Unit) else Result.failure(/* interrupted */)
}
Enter fullscreen mode Exit fullscreen mode

The session-init message itself passes requiresReady = false; audio chunks and the commit pass true. When the ready message arrives, the queue is flushed in order:

private fun flushPendingMessages() {
    while (pendingMessages.isNotEmpty()) {
        val sent = webSocket?.send(pendingMessages.removeFirst()) == true
        if (!sent) { failFinalTranscript(); return }
    }
}
Enter fullscreen mode Exit fullscreen mode

The caller never has to know whether the session was ready yet. The first words you speak are in the queue, in order, ahead of everything that follows. If a send fails during the flush, the pending wait is failed straight away instead of leaving it to time out.

2. One deferred for the final answer, with a deadline

The result the caller wants is a single string, the final transcript. A CompletableDeferred<String> holds it:

suspend fun awaitFinalTranscript(): Result<String> = try {
    Result.success(withTimeout(12_000) { finalTranscriptDeferred.await() })
} catch (t: Throwable) {
    Result.failure(if (t is VoxException) t else VoxException(/* timed out */))
}
Enter fullscreen mode Exit fullscreen mode

Three things complete that deferred: a transcript message, an error message, or a socket failure. Each failure path goes through one helper that completes it exceptionally only if it is not already completed, because a socket failure and an error message can arrive for the same take and the second completion must not throw.

The 12-second limit is what stops a dropped connection from leaving the keyboard-side UI waiting forever. A typed failure reason (connect failed, timed out, stream interrupted, unavailable) travels with the exception, so the app can say which of them happened rather than "something went wrong".

3. Reset between takes, not just close

resetFinalTranscriptWait() makes a fresh deferred, clears the queue and sets sessionReady = false. It matters when one connection is reused for the next take: a stale completed deferred would hand back the previous take's text instantly, and a stale queue would replay old audio.

A small extra: matching the sample rate the other protocol wants

Capture on the phone is 16 kHz PCM. One of the two protocols expects 24 kHz, so audio is linearly interpolated up before it is sent: for each output sample, find its fractional source position, and blend the two neighbouring input samples by the fraction. It is deliberately simple; with speech, the point is to match the rate the service declares, not to master audio.

What I would test

The queue is the part that is easy to break. The cases worth a unit test: audio sent before ready is delivered in order after ready; a send that fails mid-flush fails the wait; a second failure after the first does not throw; reset between takes does not return the old transcript.

Bolo is available on Google Play; search "Bolo AI".

Top comments (1)

Collapse
 
userxnom profile image
Abdullah Naseer •

The distinction between onOpen and session.ready is the kind of bug that only shows up on a real network — on a fast local test the session is always ready before you speak, so the dropped first words never reproduce. Gating everything through one sendRaw with requiresReady is a clean fix, and the 12-second withTimeout on the CompletableDeferred is the right backstop so a dropped connection cannot leave the keyboard UI waiting forever. The reset between takes is the detail I would have missed — a stale completed deferred handing the previous take's transcript to the next one. Have you hit a case yet where the session.ready message itself arrives late enough that the pending queue grows large, and do you cap it or just flush whatever accumulated?