fix: wait for server HELLO event before CONNECTED, add on-screen connection log

- CONNECTED now requires receiving server hello event (not just sending client hello)
- 15s handshake timeout: if auth/hello never arrives, show timeout reason
- On-screen log shows last 3 connection events (ws open, auth ok, hello, closed, timeout)
- Generation guard covers early/duplicate auth and stale socket callbacks

Version 0.2.2-m5-fix3
This commit is contained in:
zenord
2026-10-11 11:51:19 +08:00
parent 218d905e63
commit 7766f9d3eb
3 changed files with 85 additions and 8 deletions
@@ -26,6 +26,7 @@ import androidx.compose.ui.Alignment
import androidx.compose.ui.Modifier
import androidx.compose.ui.graphics.Color
import androidx.compose.ui.text.style.TextAlign
import androidx.compose.ui.text.style.TextOverflow
import androidx.compose.ui.unit.dp
import androidx.compose.ui.unit.sp
import com.gorios.lanvoice.audio.AecAvailability
@@ -40,6 +41,7 @@ import com.gorios.lanvoice.expression.ExpressionUiState
class MainActivity : ComponentActivity() {
private var state by mutableStateOf(VoiceUiState())
private var connectionLogs by mutableStateOf<List<String>>(emptyList())
private lateinit var session: VoiceSession
private var pendingStart = false
private var expressionState by mutableStateOf(ExpressionUiState())
@@ -64,9 +66,10 @@ class MainActivity : ComponentActivity() {
session = VoiceSession(
getString(R.string.voice_server_host), resources.getInteger(R.integer.voice_server_port),
onState = { state = it },
onConnectionLog = { connectionLogs = (connectionLogs + it).takeLast(3) },
)
expressions = ExpressionController(this, this) { expressionState = it }
setContent { Home(state, ::toggleVoice, session::interrupt, expressionState, ::toggleExpressions) }
setContent { Home(state, ::toggleVoice, session::interrupt, expressionState, ::toggleExpressions, connectionLogs) }
}
private fun toggleExpressions() {
@@ -97,6 +100,7 @@ class MainActivity : ComponentActivity() {
override fun onStart() {
super.onStart()
inForeground = true
connectionLogs = emptyList()
session.foreground()
}
@@ -120,6 +124,7 @@ class MainActivity : ComponentActivity() {
fun Home(
state: VoiceUiState, onToggleVoice: () -> Unit, onInterrupt: () -> Unit,
expressionState: ExpressionUiState, onToggleExpressions: () -> Unit,
connectionLogs: List<String> = emptyList(),
) {
val gold = Color(0xFFE8C884)
val muted = Color(0xFF9CA3AF)
@@ -146,6 +151,14 @@ fun Home(
modifier = Modifier.background(Color(0xFF242433), RoundedCornerShape(50))
.padding(horizontal = 20.dp, vertical = 10.dp)
)
if (connectionLogs.isNotEmpty()) {
Text(
text = connectionLogs.takeLast(3).joinToString("\n"),
color = muted, fontSize = 12.sp, textAlign = TextAlign.Center,
maxLines = 3, softWrap = false, overflow = TextOverflow.Ellipsis,
modifier = Modifier.padding(top = 6.dp),
)
}
ExpressionControls(expressionState, onToggleExpressions)
}
Column(
@@ -20,7 +20,10 @@ data class VoiceUiState(
)
/** Main-thread coordinator; both audio workers add their own epochs to the socket's fence. */
class VoiceSession(host: String, port: Int, private val onState: (VoiceUiState) -> Unit) {
class VoiceSession(
host: String, port: Int, private val onState: (VoiceUiState) -> Unit,
onConnectionLog: (String) -> Unit = {},
) {
private val main = Handler(Looper.getMainLooper())
private var state = VoiceUiState()
private var foreground = false
@@ -56,6 +59,7 @@ class VoiceSession(host: String, port: Int, private val onState: (VoiceUiState)
onEvent = ::onEvent,
onFrame = ::onFrame,
onProtocolError = { Log.w(TAG, it) },
onConnectionLog = onConnectionLog,
)
fun foreground() {
@@ -9,6 +9,7 @@ import okhttp3.Response
import okhttp3.WebSocket
import okhttp3.WebSocketListener
import okio.ByteString
import java.net.SocketTimeoutException
import java.util.concurrent.TimeUnit
enum class ConnectionStatus { CONNECTED, DISCONNECTED, BUSY }
@@ -25,6 +26,7 @@ class DialogueClient(
private val onEvent: (ServerEvent) -> Unit = {},
private val onFrame: (DownlinkFrame) -> Unit = {},
private val onProtocolError: (String) -> Unit = {},
private val onConnectionLog: (String) -> Unit = {},
) {
private val main = Handler(Looper.getMainLooper())
private val endpoint = HttpUrl.Builder()
@@ -47,26 +49,43 @@ class DialogueClient(
private var released = false
private var ready = false
private var authReceived = false
private var helloSent = false
private var handshakeTimeout: Runnable? = null
fun connect() {
checkMainThread()
check(!released) { "DialogueClient has been released" }
generation++
cancelHandshakeTimeout()
ready = false
authReceived = false
helloSent = false
socket?.cancel()
socket = null
onStatus(ConnectionStatus.DISCONNECTED)
socket = client.newWebSocket(request, listener(generation))
onConnectionLog("ws connecting")
val attempt = generation
val current = client.newWebSocket(request, listener(attempt))
socket = current
// onOpen is not a prerequisite for AUTH handling. All callbacks are queued on main,
// so even an early AUTH sees the assigned socket and can send hello exactly once.
handshakeTimeout = Runnable {
if (generation == attempt && socket === current && !released && !ready) {
onConnectionLog("连接超时:" + if (helloSent) "等待 hello" else "等待 auth / WS")
finish(current, ConnectionStatus.DISCONNECTED)
}
}.also { main.postDelayed(it, 15_000L) }
}
fun disconnect() {
checkMainThread()
generation++ // Invalidate before cancellation can trigger onFailure.
cancelHandshakeTimeout()
ready = false
val previous = socket
socket = null
previous?.cancel()
if (previous != null) onConnectionLog("ws disconnected")
onStatus(ConnectionStatus.DISCONNECTED)
}
@@ -92,6 +111,7 @@ class DialogueClient(
// Bound microphone latency rather than silently buffering many seconds of stale speech.
if (current.queueSize() > 64 * 1024 ||
!current.send(ByteString.of(*DialogueProtocol.uplink(pcm16, turnId, sequence)))) {
onConnectionLog("ws audio send failed")
finish(current, ConnectionStatus.DISCONNECTED)
return false
}
@@ -103,33 +123,59 @@ class DialogueClient(
val current = socket ?: return false
if (!ready || released) return false
if (current.send(text)) return true
onConnectionLog("ws send failed")
finish(current, ConnectionStatus.DISCONNECTED)
return false
}
private fun listener(attempt: Long) = object : WebSocketListener() {
override fun onOpen(webSocket: WebSocket, response: Response) = dispatch(attempt, webSocket) {
// Server sends auth-ok first (LAN direct/guest cookie/admin bearer), then expects hello.
// Do not send hello here; wait for the auth event in onMessage.
onConnectionLog("ws open")
}
override fun onMessage(webSocket: WebSocket, text: String) = dispatch(attempt, webSocket) {
val event = try {
DialogueProtocol.parseEvent(text)
} catch (error: Exception) {
if (!ready) onConnectionLog("握手事件 JSON 无效")
onProtocolError(error.message ?: "Invalid JSON event")
return@dispatch
}
if (!authReceived && event.kind == EventKind.AUTH) {
if (event.kind == EventKind.AUTH) {
if (!event.payload.optBoolean("ok", true) ||
!event.payload.optBoolean("success", true) ||
event.type in setOf("auth.error", "auth.failed") ||
event.payload.optString("status") in setOf("error", "failed", "denied")) {
onConnectionLog("auth failed")
finish(webSocket, ConnectionStatus.DISCONNECTED)
return@dispatch
}
if (authReceived) return@dispatch
authReceived = true
onConnectionLog("auth ok")
if (webSocket.send(DialogueProtocol.hello())) {
ready = true
onStatus(ConnectionStatus.CONNECTED)
helloSent = true
onConnectionLog("hello sent")
} else {
onConnectionLog("hello send failed")
finish(webSocket, ConnectionStatus.DISCONNECTED)
}
return@dispatch
}
if (event.kind == EventKind.HELLO && !ready) {
if (!authReceived || !helloSent) {
onConnectionLog("hello received before auth")
return@dispatch
}
ready = true
cancelHandshakeTimeout()
onConnectionLog("hello received")
onStatus(ConnectionStatus.CONNECTED)
}
if (event.kind == EventKind.ERROR && !ready) {
onConnectionLog("握手收到 error")
finish(webSocket, ConnectionStatus.DISCONNECTED)
}
onEvent(event)
}
@@ -144,14 +190,22 @@ class DialogueClient(
}
override fun onClosing(webSocket: WebSocket, code: Int, reason: String) = dispatch(attempt, webSocket) {
// finish invalidates onClosed, so record the close code here as well.
onConnectionLog("ws closed: $code")
finish(webSocket, statusFor(code))
}
override fun onClosed(webSocket: WebSocket, code: Int, reason: String) = dispatch(attempt, webSocket) {
onConnectionLog("ws closed: $code")
finish(webSocket, statusFor(code))
}
override fun onFailure(webSocket: WebSocket, t: Throwable, response: Response?) = dispatch(attempt, webSocket) {
onConnectionLog(when {
response != null -> "ws failure: HTTP ${response.code}"
t is SocketTimeoutException -> "连接超时"
else -> "ws failure: ${t.javaClass.simpleName}"
})
finish(webSocket, if (response?.code == 403) ConnectionStatus.BUSY else ConnectionStatus.DISCONNECTED)
}
}
@@ -164,12 +218,18 @@ class DialogueClient(
private fun finish(webSocket: WebSocket, status: ConnectionStatus) {
// Invalidate terminal callbacks so a later failure cannot overwrite a 1013 busy status.
cancelHandshakeTimeout()
socket = null
ready = false
webSocket.cancel()
onStatus(status)
}
private fun cancelHandshakeTimeout() {
handshakeTimeout?.let { main.removeCallbacks(it) }
handshakeTimeout = null
}
private fun statusFor(code: Int) =
if (code == 1013) ConnectionStatus.BUSY else ConnectionStatus.DISCONNECTED