fix: explicit CONNECTING state, handshake timeout, granular connection log

- New ConnectionStatus.CONNECTING shown as 连接中 in status pill
- Connection log distinguishes: TCP connecting / WS open / auth received / hello sent / hello received
- Failure categories: TCP unreachable / TLS cert / handshake timeout / server closed
- 15s total handshake timeout with reason display
- On-screen log shows last 3 events for user diagnosis

Version 0.2.3-m5-fix4
This commit is contained in:
zenord
2026-10-11 12:03:49 +08:00
parent 7766f9d3eb
commit b2388931f1
2 changed files with 57 additions and 15 deletions
@@ -136,6 +136,7 @@ fun Home(
) { ) {
Text( Text(
text = when (state.connection) { text = when (state.connection) {
ConnectionStatus.CONNECTING -> "连接中"
ConnectionStatus.DISCONNECTED -> "已断开" ConnectionStatus.DISCONNECTED -> "已断开"
ConnectionStatus.BUSY -> "被占用 · 另一设备正在使用" ConnectionStatus.BUSY -> "被占用 · 另一设备正在使用"
ConnectionStatus.CONNECTED -> when (state.phase) { ConnectionStatus.CONNECTED -> when (state.phase) {
@@ -9,10 +9,16 @@ import okhttp3.Response
import okhttp3.WebSocket import okhttp3.WebSocket
import okhttp3.WebSocketListener import okhttp3.WebSocketListener
import okio.ByteString import okio.ByteString
import java.io.InterruptedIOException
import java.net.ConnectException
import java.net.SocketTimeoutException import java.net.SocketTimeoutException
import java.net.UnknownHostException
import java.security.cert.CertificateException
import java.util.concurrent.TimeUnit import java.util.concurrent.TimeUnit
import javax.net.ssl.SSLException
import javax.net.ssl.SSLPeerUnverifiedException
enum class ConnectionStatus { CONNECTED, DISCONNECTED, BUSY } enum class ConnectionStatus { CONNECTING, CONNECTED, DISCONNECTED, BUSY }
/** /**
* Owned by the main thread. All socket callbacks cross the same main-thread generation gate, * Owned by the main thread. All socket callbacks cross the same main-thread generation gate,
@@ -42,12 +48,16 @@ class DialogueClient(
.followSslRedirects(false) .followSslRedirects(false)
.pingInterval(20, TimeUnit.SECONDS) .pingInterval(20, TimeUnit.SECONDS)
.connectTimeout(10, TimeUnit.SECONDS) .connectTimeout(10, TimeUnit.SECONDS)
.readTimeout(0, TimeUnit.MILLISECONDS) // Bound TLS and HTTP Upgrade reads too. OkHttp clears the socket read timeout
// when it upgrades to WebSocket; idle conversations still use ping/pong.
.readTimeout(10, TimeUnit.SECONDS)
.callTimeout(15, TimeUnit.SECONDS)
.build() .build()
private var generation = 0L private var generation = 0L
private var socket: WebSocket? = null private var socket: WebSocket? = null
private var released = false private var released = false
private var ready = false private var ready = false
private var wsOpened = false
private var authReceived = false private var authReceived = false
private var helloSent = false private var helloSent = false
private var handshakeTimeout: Runnable? = null private var handshakeTimeout: Runnable? = null
@@ -58,23 +68,35 @@ class DialogueClient(
generation++ generation++
cancelHandshakeTimeout() cancelHandshakeTimeout()
ready = false ready = false
wsOpened = false
authReceived = false authReceived = false
helloSent = false helloSent = false
socket?.cancel() socket?.cancel()
socket = null socket = null
onStatus(ConnectionStatus.DISCONNECTED)
onConnectionLog("ws connecting")
val attempt = generation val attempt = generation
val current = client.newWebSocket(request, listener(attempt)) onStatus(ConnectionStatus.CONNECTING)
socket = current onConnectionLog("ws connecting #$attempt")
// onOpen is not a prerequisite for AUTH handling. All callbacks are queued on main, // Arm before submitting the request; synchronous setup failures are terminal too.
// so even an early AUTH sees the assigned socket and can send hello exactly once.
handshakeTimeout = Runnable { handshakeTimeout = Runnable {
if (generation == attempt && socket === current && !released && !ready) { if (generation == attempt && !released && !ready) {
onConnectionLog("连接超时:" + if (helloSent) "等待 hello" else "等待 auth / WS") val phase = when {
finish(current, ConnectionStatus.DISCONNECTED) helloSent -> "等待 hello"
wsOpened -> "等待 auth"
else -> "等待 WS(TCP/TLS/HTTP)"
}
onConnectionLog("连接超时:$phase")
finish(socket, ConnectionStatus.DISCONNECTED)
} }
}.also { main.postDelayed(it, 15_000L) } }.also { main.postDelayed(it, 15_000L) }
try {
// Callbacks always post to main, including AUTH arriving before onOpen.
// They run after this assignment and do not depend on wsOpened.
socket = client.newWebSocket(request, listener(attempt))
onConnectionLog("ws request queued #$attempt")
} catch (error: Exception) {
onConnectionLog("ws setup failed: ${failureSummary(error)}")
finish(socket, ConnectionStatus.DISCONNECTED)
}
} }
fun disconnect() { fun disconnect() {
@@ -130,6 +152,7 @@ class DialogueClient(
private fun listener(attempt: Long) = object : WebSocketListener() { private fun listener(attempt: Long) = object : WebSocketListener() {
override fun onOpen(webSocket: WebSocket, response: Response) = dispatch(attempt, webSocket) { override fun onOpen(webSocket: WebSocket, response: Response) = dispatch(attempt, webSocket) {
wsOpened = true
onConnectionLog("ws open") onConnectionLog("ws open")
} }
@@ -141,6 +164,11 @@ class DialogueClient(
onProtocolError(error.message ?: "Invalid JSON event") onProtocolError(error.message ?: "Invalid JSON event")
return@dispatch return@dispatch
} }
if (!ready && event.kind == EventKind.UNKNOWN) {
// Only the event name is shown, never auth payloads/history/token contents.
val type = event.type.replace(Regex("[\\r\\n\\t]"), " ").take(48)
onConnectionLog("ws received: $type")
}
if (event.kind == EventKind.AUTH) { if (event.kind == EventKind.AUTH) {
if (!event.payload.optBoolean("ok", true) || if (!event.payload.optBoolean("ok", true) ||
!event.payload.optBoolean("success", true) || !event.payload.optBoolean("success", true) ||
@@ -203,8 +231,7 @@ class DialogueClient(
override fun onFailure(webSocket: WebSocket, t: Throwable, response: Response?) = dispatch(attempt, webSocket) { override fun onFailure(webSocket: WebSocket, t: Throwable, response: Response?) = dispatch(attempt, webSocket) {
onConnectionLog(when { onConnectionLog(when {
response != null -> "ws failure: HTTP ${response.code}" response != null -> "ws failure: HTTP ${response.code}"
t is SocketTimeoutException -> "连接超时" else -> "ws failure: ${failureSummary(t)}"
else -> "ws failure: ${t.javaClass.simpleName}"
}) })
finish(webSocket, if (response?.code == 403) ConnectionStatus.BUSY else ConnectionStatus.DISCONNECTED) finish(webSocket, if (response?.code == 403) ConnectionStatus.BUSY else ConnectionStatus.DISCONNECTED)
} }
@@ -216,12 +243,12 @@ class DialogueClient(
} }
} }
private fun finish(webSocket: WebSocket, status: ConnectionStatus) { private fun finish(webSocket: WebSocket?, status: ConnectionStatus) {
// Invalidate terminal callbacks so a later failure cannot overwrite a 1013 busy status. // Invalidate terminal callbacks so a later failure cannot overwrite a 1013 busy status.
cancelHandshakeTimeout() cancelHandshakeTimeout()
socket = null socket = null
ready = false ready = false
webSocket.cancel() webSocket?.cancel()
onStatus(status) onStatus(status)
} }
@@ -230,6 +257,20 @@ class DialogueClient(
handshakeTimeout = null handshakeTimeout = null
} }
private fun failureSummary(error: Throwable): String {
val causes = generateSequence(error) { it.cause }.take(8).toList()
return when {
causes.any { it is CertificateException } -> "TLS 证书验证失败"
causes.any { it is SSLPeerUnverifiedException } -> "TLS 主机名/证书验证失败"
causes.any { it is SSLException } -> "TLS 握手失败"
causes.any { it is SocketTimeoutException ||
(it is InterruptedIOException && it.message == "timeout") } -> "连接超时"
causes.any { it is ConnectException } -> "TCP 连接失败"
causes.any { it is UnknownHostException } -> "主机解析失败"
else -> error.javaClass.simpleName
}
}
private fun statusFor(code: Int) = private fun statusFor(code: Int) =
if (code == 1013) ConnectionStatus.BUSY else ConnectionStatus.DISCONNECTED if (code == 1013) ConnectionStatus.BUSY else ConnectionStatus.DISCONNECTED