feat: remote debug log upload to gateway for LAN diagnosis

- DebugLogUpload: isolated OkHttp pool, 3s timeout, bounded queue, silent drop
- POST /debug/log on gateway: LAN-only, JSON ringbuffer (200 entries), GET to read
- Logs: app_launch, connect phases, ws events, errors (no token/audio/chat content)
- UI shows debug logging active indicator
- network_security_config: cleartext HTTP allowed for gateway host (LAN debug only)
- Gateway v0.7.1 + debug log endpoint deployed on SPARK-2

Version 0.2.5-m5-fix6
This commit is contained in:
zenord
2026-10-11 12:51:51 +08:00
parent 87f1324a68
commit 198fe51cec
6 changed files with 142 additions and 38 deletions
+2 -2
View File
@@ -45,8 +45,8 @@ android {
applicationId 'com.gorios.lanvoice'
minSdk 26
targetSdk 34
versionCode 1
versionName '0.2.0-m5'
versionCode 2
versionName '0.2.5'
ndk { abiFilters 'arm64-v8a' }
}
compileOptions { sourceCompatibility JavaVersion.VERSION_17; targetCompatibility JavaVersion.VERSION_17 }
@@ -34,6 +34,7 @@ import com.gorios.lanvoice.audio.VoicePhase
import com.gorios.lanvoice.audio.VoiceSession
import com.gorios.lanvoice.audio.VoiceUiState
import com.gorios.lanvoice.net.ConnectionStatus
import com.gorios.lanvoice.net.DebugLogUpload
import com.gorios.lanvoice.expression.ExpressionController
import com.gorios.lanvoice.expression.ExpressionControls
import com.gorios.lanvoice.expression.ExpressionStatus
@@ -63,6 +64,7 @@ class MainActivity : ComponentActivity() {
override fun onCreate(savedInstanceState: Bundle?) {
super.onCreate(savedInstanceState)
DebugLogUpload.appLaunch(packageManager.getPackageInfo(packageName, 0).versionName ?: "unknown")
session = VoiceSession(
getString(R.string.voice_server_host), resources.getInteger(R.integer.voice_server_port),
onState = { state = it },
@@ -152,6 +154,7 @@ fun Home(
modifier = Modifier.background(Color(0xFF242433), RoundedCornerShape(50))
.padding(horizontal = 20.dp, vertical = 10.dp)
)
Text("调试日志已开启", color = muted, fontSize = 12.sp, modifier = Modifier.padding(top = 4.dp))
if (connectionLogs.isNotEmpty()) {
Text(
text = connectionLogs.takeLast(3).joinToString("\n"),
@@ -5,6 +5,7 @@ import android.os.Looper
import android.util.Log
import com.gorios.lanvoice.net.ConnectionStatus
import com.gorios.lanvoice.net.DialogueClient
import com.gorios.lanvoice.net.DebugLogUpload
import com.gorios.lanvoice.net.DownlinkFrame
import com.gorios.lanvoice.net.EventKind
import com.gorios.lanvoice.net.ServerEvent
@@ -238,6 +239,7 @@ class VoiceSession(
}
private fun failAudio(message: String, error: Exception) {
DebugLogUpload.log("audio", "audio failed: ${error.javaClass.simpleName}")
Log.w(TAG, message, error)
stopVoice()
update(state.copy(guidance = message))
@@ -0,0 +1,76 @@
package com.gorios.lanvoice.net
import okhttp3.Call
import okhttp3.Callback
import okhttp3.ConnectionPool
import okhttp3.ConnectionSpec
import okhttp3.Dispatcher
import okhttp3.MediaType.Companion.toMediaType
import okhttp3.OkHttpClient
import okhttp3.Request
import okhttp3.RequestBody.Companion.toRequestBody
import okhttp3.Response
import org.json.JSONObject
import java.io.IOException
import java.util.concurrent.TimeUnit
import java.util.concurrent.atomic.AtomicBoolean
import java.util.concurrent.atomic.AtomicInteger
/** Process-wide, memory-only LAN diagnostics. Callers supply metadata, never payloads. */
object DebugLogUpload {
private const val ENDPOINT = "http://192.168.31.61:5011/debug/log"
private const val MAX_PENDING = 16
private val tags = setOf("connect", "ws", "auth", "audio", "error")
private val pending = AtomicInteger()
private val launchSent = AtomicBoolean()
private val json = "application/json; charset=utf-8".toMediaType()
// Build independently, never newBuilder() from the voice client. HTTP-only avoids
// initializing TLS for the diagnostic channel whose purpose includes TLS failures.
private val client by lazy {
OkHttpClient.Builder()
.connectionSpecs(listOf(ConnectionSpec.CLEARTEXT))
.connectionPool(ConnectionPool(2, 30, TimeUnit.SECONDS))
.dispatcher(Dispatcher().apply { maxRequests = 2; maxRequestsPerHost = 2 })
.connectTimeout(3, TimeUnit.SECONDS)
.readTimeout(3, TimeUnit.SECONDS)
.writeTimeout(3, TimeUnit.SECONDS)
.callTimeout(3, TimeUnit.SECONDS)
.followRedirects(false)
.followSslRedirects(false)
.retryOnConnectionFailure(false)
.build()
}
fun appLaunch(version: String) {
if (launchSent.compareAndSet(false, true)) log("connect", "app_launch version=$version")
}
fun log(tag: String, message: String) {
if (tag !in tags) return
if (pending.incrementAndGet() > MAX_PENDING) {
pending.decrementAndGet()
return
}
try {
val bounded = message.replace('\r', ' ').replace('\n', ' ').take(500)
.let { if (it.lastOrNull()?.isHighSurrogate() == true) it.dropLast(1) else it }
val body = JSONObject()
.put("timestamp_ms", System.currentTimeMillis())
.put("tag", tag)
.put("message", bounded)
.toString().toRequestBody(json)
client.newCall(Request.Builder().url(ENDPOINT).post(body).build()).enqueue(object : Callback {
override fun onFailure(call: Call, error: IOException) {
pending.decrementAndGet() // No retries, recursive logs or UI updates.
}
override fun onResponse(call: Call, response: Response) {
try { response.close() } catch (_: Exception) { }
finally { pending.decrementAndGet() }
}
})
} catch (_: Exception) {
pending.decrementAndGet() // Setup/enqueue errors must also be silent.
}
}
}
@@ -62,6 +62,7 @@ class DialogueClient(
.readTimeout(10, TimeUnit.SECONDS)
.callTimeout(15, TimeUnit.SECONDS)
.build()
private var status = ConnectionStatus.DISCONNECTED
private var generation = 0L
private var socket: WebSocket? = null
private var healthCall: Call? = null
@@ -77,6 +78,7 @@ class DialogueClient(
checkMainThread()
check(!released) { "DialogueClient has been released" }
generation++
connectionLog("connect_start #$generation", "connect")
cancelHandshakeTimeout()
ready = false
wsOpened = false
@@ -87,8 +89,8 @@ class DialogueClient(
socket?.cancel()
socket = null
val attempt = generation
onStatus(ConnectionStatus.CONNECTING)
onConnectionLog("health checking #$attempt")
updateStatus(ConnectionStatus.CONNECTING)
connectionLog("health checking #$attempt", "connect")
// Arm before submitting the request; synchronous setup failures are terminal too.
handshakeTimeout = Runnable {
if (generation == attempt && !released && !ready) {
@@ -98,7 +100,7 @@ class DialogueClient(
wsOpened -> "等待 auth"
else -> "等待 WS(TCP/TLS/HTTP)"
}
onConnectionLog("连接超时,请检查网络 · $phase")
connectionLog("连接超时,请检查网络 · $phase", "error")
finish(socket, ConnectionStatus.DISCONNECTED)
}
}.also { main.postDelayed(it, 15_000L) }
@@ -117,7 +119,7 @@ class DialogueClient(
.eventListener(object : EventListener() {
private fun stage(call: Call, phase: String) = dispatchHealth(attempt, call) {
healthPhase = phase
onConnectionLog(phase)
connectionLog(phase, "connect")
}
override fun dnsStart(call: Call, domainName: String) = stage(call, "health DNS")
@@ -130,7 +132,7 @@ class DialogueClient(
healthCall = current
current.enqueue(object : Callback {
override fun onFailure(call: Call, error: IOException) = dispatchHealth(attempt, call) {
onConnectionLog("health failed: ${failureSummary(error)}")
connectionLog("health failed: ${failureSummary(error)}", "error")
finish(socket, ConnectionStatus.DISCONNECTED)
}
@@ -140,26 +142,27 @@ class DialogueClient(
healthCall = null
// Even 404/403/503 establishes HTTPS reachability. /health may be
// absent or protected; only the actual WS handshake decides busy.
onConnectionLog("health HTTP $code · HTTPS 可达")
connectionLog("health HTTP $code · HTTPS 可达", "connect")
openWebSocket(attempt)
}
}
})
connectionLog("health submitted #$attempt", "connect")
} catch (error: Exception) {
onConnectionLog("health setup failed: ${failureSummary(error)}")
connectionLog("health setup failed: ${failureSummary(error)}", "error")
finish(socket, ConnectionStatus.DISCONNECTED)
}
}
private fun openWebSocket(attempt: Long) {
onConnectionLog("ws connecting #$attempt")
connectionLog("ws connecting #$attempt")
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 submitted #$attempt")
connectionLog("ws submitted #$attempt")
} catch (error: Exception) {
onConnectionLog("ws setup failed: ${failureSummary(error)}")
connectionLog("ws setup failed: ${failureSummary(error)}", "error")
finish(socket, ConnectionStatus.DISCONNECTED)
}
}
@@ -175,9 +178,9 @@ class DialogueClient(
val previous = socket
socket = null
previous?.cancel()
if (previous != null) onConnectionLog("ws disconnected")
else if (previousHealth != null) onConnectionLog("health cancelled")
onStatus(ConnectionStatus.DISCONNECTED)
if (previous != null) connectionLog("ws disconnected")
else if (previousHealth != null) connectionLog("health cancelled", "connect")
updateStatus(ConnectionStatus.DISCONNECTED)
}
fun release() {
@@ -202,7 +205,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")
connectionLog("ws audio send failed", "audio")
finish(current, ConnectionStatus.DISCONNECTED)
return false
}
@@ -214,7 +217,7 @@ class DialogueClient(
val current = socket ?: return false
if (!ready || released) return false
if (current.send(text)) return true
onConnectionLog("ws send failed")
connectionLog("ws send failed", "error")
finish(current, ConnectionStatus.DISCONNECTED)
return false
}
@@ -222,55 +225,59 @@ class DialogueClient(
private fun listener(attempt: Long) = object : WebSocketListener() {
override fun onOpen(webSocket: WebSocket, response: Response) = dispatch(attempt, webSocket) {
wsOpened = true
onConnectionLog("ws open")
connectionLog("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")
connectionLog("WS JSON 事件无效", "error")
onProtocolError("Invalid JSON event")
return@dispatch
}
// Only finite event kinds; do not log raw type/payload (including text or tokens).
DebugLogUpload.log(when (event.kind) {
EventKind.AUTH -> "auth"
EventKind.ERROR -> "error"
else -> "ws"
}, "ws event=${event.kind.name.lowercase()}")
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")
connectionLog("ws received: unknown event")
}
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")
connectionLog("auth failed", "error")
finish(webSocket, ConnectionStatus.DISCONNECTED)
return@dispatch
}
if (authReceived) return@dispatch
authReceived = true
onConnectionLog("auth ok")
connectionLog("auth ok", "auth")
if (webSocket.send(DialogueProtocol.hello())) {
helloSent = true
onConnectionLog("hello sent")
connectionLog("hello sent", "auth")
} else {
onConnectionLog("hello send failed")
connectionLog("hello send failed", "error")
finish(webSocket, ConnectionStatus.DISCONNECTED)
}
return@dispatch
}
if (event.kind == EventKind.HELLO && !ready) {
if (!authReceived || !helloSent) {
onConnectionLog("hello received before auth")
connectionLog("hello received before auth", "auth")
return@dispatch
}
ready = true
cancelHandshakeTimeout()
onConnectionLog("hello received")
onStatus(ConnectionStatus.CONNECTED)
connectionLog("hello received", "auth")
updateStatus(ConnectionStatus.CONNECTED)
}
if (event.kind == EventKind.ERROR && !ready) {
onConnectionLog("握手收到 error")
connectionLog("握手收到 error", "error")
finish(webSocket, ConnectionStatus.DISCONNECTED)
}
onEvent(event)
@@ -280,32 +287,47 @@ class DialogueClient(
val frame = try {
DialogueProtocol.parseDownlink(bytes.toByteArray())
} catch (error: IllegalArgumentException) {
onProtocolError(error.message ?: "Invalid binary frame")
connectionLog("WS binary frame invalid", "error")
onProtocolError("Invalid binary frame")
return@dispatch
}
DebugLogUpload.log("audio", "downlink frame turn=${frame.turnId} seq=${frame.sequence} bytes=${frame.pcm16.size}")
onFrame(frame)
}
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")
connectionLog("ws closed: $code")
finish(webSocket, statusFor(code))
}
override fun onClosed(webSocket: WebSocket, code: Int, reason: String) = dispatch(attempt, webSocket) {
onConnectionLog("ws closed: $code")
connectionLog("ws closed: $code")
finish(webSocket, statusFor(code))
}
override fun onFailure(webSocket: WebSocket, t: Throwable, response: Response?) = dispatch(attempt, webSocket) {
onConnectionLog(when {
connectionLog(when {
response != null -> "ws failure: HTTP ${response.code}"
else -> "ws failure: ${failureSummary(t)}"
})
}, "error")
finish(webSocket, if (response?.code == 403) ConnectionStatus.BUSY else ConnectionStatus.DISCONNECTED)
}
}
private fun connectionLog(message: String, tag: String = "ws") {
DebugLogUpload.log(tag, message)
onConnectionLog(message)
}
private fun updateStatus(next: ConnectionStatus) {
if (status != next) {
status = next
DebugLogUpload.log("connect", "state=${next.name.lowercase()}")
}
onStatus(next)
}
private fun dispatch(attempt: Long, webSocket: WebSocket, action: () -> Unit) {
main.post {
if (generation == attempt && socket === webSocket && !released) action()
@@ -327,7 +349,7 @@ class DialogueClient(
socket = null
ready = false
webSocket?.cancel()
onStatus(status)
updateStatus(status)
}
private fun cancelHandshakeTimeout() {
+2 -1
View File
@@ -7,7 +7,8 @@
<certificates src="@raw/gateway_cert" />
</trust-anchors>
</base-config>
<domain-config cleartextTrafficPermitted="false">
<!-- LAN debug POST is permitted only for this gateway; TLS still uses its certificate. -->
<domain-config cleartextTrafficPermitted="true">
<domain includeSubdomains="false">@VOICE_SERVER_HOST@</domain>
<trust-anchors>
<certificates src="@raw/gateway_cert" />