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 = when (state.connection) {
ConnectionStatus.CONNECTING -> "连接中"
ConnectionStatus.DISCONNECTED -> "已断开"
ConnectionStatus.BUSY -> "被占用 · 另一设备正在使用"
ConnectionStatus.CONNECTED -> when (state.phase) {
@@ -9,10 +9,16 @@ import okhttp3.Response
import okhttp3.WebSocket
import okhttp3.WebSocketListener
import okio.ByteString
import java.io.InterruptedIOException
import java.net.ConnectException
import java.net.SocketTimeoutException
import java.net.UnknownHostException
import java.security.cert.CertificateException
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,
@@ -42,12 +48,16 @@ class DialogueClient(
.followSslRedirects(false)
.pingInterval(20, 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()
private var generation = 0L
private var socket: WebSocket? = null
private var released = false
private var ready = false
private var wsOpened = false
private var authReceived = false
private var helloSent = false
private var handshakeTimeout: Runnable? = null
@@ -58,23 +68,35 @@ class DialogueClient(
generation++
cancelHandshakeTimeout()
ready = false
wsOpened = false
authReceived = false
helloSent = false
socket?.cancel()
socket = null
onStatus(ConnectionStatus.DISCONNECTED)
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.
onStatus(ConnectionStatus.CONNECTING)
onConnectionLog("ws connecting #$attempt")
// Arm before submitting the request; synchronous setup failures are terminal too.
handshakeTimeout = Runnable {
if (generation == attempt && socket === current && !released && !ready) {
onConnectionLog("连接超时:" + if (helloSent) "等待 hello" else "等待 auth / WS")
finish(current, ConnectionStatus.DISCONNECTED)
if (generation == attempt && !released && !ready) {
val phase = when {
helloSent -> "等待 hello"
wsOpened -> "等待 auth"
else -> "等待 WS(TCP/TLS/HTTP)"
}
onConnectionLog("连接超时:$phase")
finish(socket, ConnectionStatus.DISCONNECTED)
}
}.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() {
@@ -130,6 +152,7 @@ class DialogueClient(
private fun listener(attempt: Long) = object : WebSocketListener() {
override fun onOpen(webSocket: WebSocket, response: Response) = dispatch(attempt, webSocket) {
wsOpened = true
onConnectionLog("ws open")
}
@@ -141,6 +164,11 @@ class DialogueClient(
onProtocolError(error.message ?: "Invalid JSON event")
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.payload.optBoolean("ok", true) ||
!event.payload.optBoolean("success", true) ||
@@ -203,8 +231,7 @@ class DialogueClient(
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}"
else -> "ws failure: ${failureSummary(t)}"
})
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.
cancelHandshakeTimeout()
socket = null
ready = false
webSocket.cancel()
webSocket?.cancel()
onStatus(status)
}
@@ -230,6 +257,20 @@ class DialogueClient(
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) =
if (code == 1013) ConnectionStatus.BUSY else ConnectionStatus.DISCONNECTED