fix: abort listen_start no longer blocks new turn, debug log HTTPS fix

- ABORT with reason=listen_start no longer marks new turn as blocked
- ABORT ignored when connection lost or voice not active
- finish() logs stack trace to Logcat, truncated summary to screen/remote
- DebugLogUpload endpoint fixed to HTTPS (was cleartext HTTP to HTTPS port)
- Granular logging: onEvent entry, acceptTurn details, ABORT/LISTEN decisions,
  startCapture result, onConnection transitions, finish() caller

Version 0.2.7-m5-fix8
This commit is contained in:
zenord
2026-10-11 18:40:55 +08:00
parent c3e5481d19
commit 8652659e68
5 changed files with 122 additions and 59 deletions
+2 -2
View File
@@ -45,8 +45,8 @@ android {
applicationId 'com.gorios.lanvoice'
minSdk 26
targetSdk 34
versionCode 2
versionName '0.2.5'
versionCode 3
versionName '0.2.7'
ndk { abiFilters 'arm64-v8a' }
}
compileOptions { sourceCompatibility JavaVersion.VERSION_17; targetCompatibility JavaVersion.VERSION_17 }
@@ -25,11 +25,14 @@ class AudioCapture {
}
/** The caller must obtain RECORD_AUDIO permission before starting. Callbacks run off main. */
fun start(onFrame: (ByteArray) -> Unit, onError: (Exception) -> Unit) {
fun start(
onFrame: (ByteArray) -> Unit, onError: (Exception) -> Unit,
onDiagnostic: (String) -> Unit = {},
) {
stop()
val run = Run()
synchronized(lock) { current = run }
Thread({ record(run, onFrame, onError) }, "lan-voice-capture").apply {
Thread({ record(run, onFrame, onError, onDiagnostic) }, "lan-voice-capture").apply {
isDaemon = true
start()
}
@@ -45,10 +48,15 @@ class AudioCapture {
}
}
private fun record(run: Run, onFrame: (ByteArray) -> Unit, onError: (Exception) -> Unit) {
private fun record(
run: Run, onFrame: (ByteArray) -> Unit, onError: (Exception) -> Unit,
onDiagnostic: (String) -> Unit,
) {
var recorder: AudioRecord? = null
var aec: AcousticEchoCanceler? = null
var stage = "initialization"
try {
onDiagnostic("AudioRecord initialization started")
Process.setThreadPriority(Process.THREAD_PRIORITY_AUDIO)
val minimum = AudioRecord.getMinBufferSize(
16_000, AudioFormat.CHANNEL_IN_MONO, AudioFormat.ENCODING_PCM_16BIT
@@ -61,6 +69,7 @@ class AudioCapture {
)
recorder = device
check(device.state == AudioRecord.STATE_INITIALIZED) { "AudioRecord initialization failed" }
onDiagnostic("AudioRecord initialization ok")
// Availability is reported separately; creating/enabling an effect is best effort.
if (aecAvailability() == AecAvailability.AVAILABLE) {
try {
@@ -71,9 +80,12 @@ class AudioCapture {
synchronized(lock) {
if (!run.active || current !== run) return
run.recorder = device
stage = "startRecording"
device.startRecording()
check(device.recordingState == AudioRecord.RECORDSTATE_RECORDING) { "Recording did not start" }
}
onDiagnostic("AudioRecord startRecording ok")
stage = "read"
val frame = ByteArray(FRAME_BYTES)
var filled = 0
while (run.active) {
@@ -91,7 +103,10 @@ class AudioCapture {
}
}
} catch (error: Exception) {
if (run.active) onError(error)
if (run.active) {
onDiagnostic("AudioRecord $stage failed: ${error.javaClass.simpleName}")
onError(error)
}
} finally {
synchronized(lock) {
run.active = false
@@ -23,7 +23,7 @@ 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,
onConnectionLog: (String) -> Unit = {},
private val onConnectionLog: (String) -> Unit = {},
) {
private val main = Handler(Looper.getMainLooper())
private var state = VoiceUiState()
@@ -57,7 +57,8 @@ class VoiceSession(
)
private val dialogue: DialogueClient = DialogueClient(
host, port,
onStatus = ::onConnection,
onStatus = {},
onStatusReason = ::onConnection,
onEvent = ::onEvent,
onFrame = ::onFrame,
onProtocolError = { Log.w(TAG, it) },
@@ -92,9 +93,9 @@ class VoiceSession(
// but reuse the authorized WS when it returns. Bound retention if the user leaves.
backgroundTimeout = Runnable {
backgroundTimeout = null
if (!foreground && !released) dialogue.disconnect()
if (!foreground && !released) dialogue.disconnect("permission_background_timeout")
}.also { main.postDelayed(it, 30_000L) }
} else dialogue.disconnect()
} else dialogue.disconnect("session_background")
}
fun release() {
@@ -145,7 +146,8 @@ class VoiceSession(
update(state.copy(guidance = "麦克风权限未授予,请允许录音;若不再弹出申请,可在系统应用权限中开启。"))
}
private fun onConnection(connection: ConnectionStatus) {
private fun onConnection(connection: ConnectionStatus, reason: String) {
diagnostic("connection ${state.connection.name} -> ${connection.name} reason=$reason", "connect")
if (connection != ConnectionStatus.CONNECTED) {
stopCapture()
playback.interrupt()
@@ -159,26 +161,37 @@ class VoiceSession(
}
private fun startCapture() {
if (!isActive() || capturing) return
val active = isActive()
diagnostic("startCapture active=$active capturing=$capturing")
if (!active || capturing) return
capturing = true
val epoch = ++captureEpoch
DebugLogUpload.log("audio", "capture start")
capture.start(
onFrame = { pcm ->
main.post {
if (epoch == captureEpoch && capturing && isActive()) {
if (dialogue.sendAudio(pcm, currentTurn, sequence)) {
sequence = (sequence + 1) and UINT32_MASK
diagnostic("capture start epoch=$epoch")
try {
capture.start(
onFrame = { pcm ->
main.post {
if (epoch == captureEpoch && capturing && isActive()) {
if (dialogue.sendAudio(pcm, currentTurn, sequence)) {
sequence = (sequence + 1) and UINT32_MASK
}
}
}
}
},
onError = { error ->
main.post {
if (epoch == captureEpoch && isActive()) failAudio("无法录音,请检查麦克风权限后重新开始", error)
}
},
)
},
onError = { error ->
main.post {
if (epoch == captureEpoch && isActive()) failAudio("无法录音,请检查麦克风权限后重新开始", error)
}
},
onDiagnostic = { message ->
main.post {
if (epoch == captureEpoch && capturing && !released) diagnostic(message)
}
},
)
} catch (error: Exception) {
failAudio("无法启动录音,请检查麦克风权限后重新开始", error)
}
}
private fun stopCapture() {
@@ -189,10 +202,22 @@ class VoiceSession(
private fun onEvent(event: ServerEvent) {
val turn = (event.payload.opt("turn_id") as? Number)?.toLong()
diagnostic("onEvent kind=${event.kind.name} turn_id=$turn")
if (released || state.connection != ConnectionStatus.CONNECTED) {
diagnostic("event ignored: connection=${state.connection.name} released=$released")
return
}
if (event.kind == EventKind.ABORT && !isActive()) {
diagnostic("ABORT ignored active=false blockedTurn=$blockedTurn")
return
}
if (turn != null && !acceptTurn(turn)) return
val action = event.payload.optString("state", "").ifBlank { event.type.substringAfter('.', "") }
when (event.kind) {
EventKind.LISTEN -> if (isActive()) {
EventKind.LISTEN -> {
val active = isActive()
diagnostic("LISTEN action=${if (action in setOf("start", "stop")) action else "other"} active=$active blockedTurn=$blockedTurn")
if (!active) return
when (action) {
"start" -> {
update(state.copy(phase = VoicePhase.LISTENING))
@@ -221,7 +246,11 @@ class VoiceSession(
if (action in setOf("stop", "done", "end")) playback.endTurn(currentTurn)
}
EventKind.ABORT -> {
blockedTurn = currentTurn
// listen_start aborts the previous reply while announcing the NEW turn.
// The server's following LISTEN start and TTS belong to that new turn.
val listenReset = event.payload.optString("reason") == "listen_start"
blockedTurn = if (listenReset) null else currentTurn
diagnostic("ABORT blockedTurn=$blockedTurn active=${isActive()} listenReset=$listenReset")
playback.interrupt()
if (isActive()) {
update(state.copy(phase = VoicePhase.LISTENING))
@@ -237,17 +266,22 @@ class VoiceSession(
}
private fun onFrame(frame: DownlinkFrame) {
if (!isActive() || !acceptTurn(frame.turnId) || blockedTurn == frame.turnId) return
// Avoid uploading the same acceptTurn decision for every 20 ms PCM frame.
if (!isActive() || !acceptTurn(frame.turnId, logDecision = !hasTurn || frame.turnId != currentTurn) ||
blockedTurn == frame.turnId) return
update(state.copy(phase = VoicePhase.ANSWERING))
if (!playback.enqueue(frame)) {
failAudio("播放中断,请重新开始语音对话", IllegalStateException("Playback queue rejected frame"))
}
}
private fun acceptTurn(id: Long): Boolean {
if (id !in 0..UINT32_MASK) return false
private fun acceptTurn(id: Long, logDecision: Boolean = true): Boolean {
val before = "id=$id hasTurn=$hasTurn currentTurn=$currentTurn blockedTurn=$blockedTurn retired=${retiredTurns.size}"
if (id !in 0..UINT32_MASK || id in retiredTurns) {
if (logDecision) diagnostic("acceptTurn $before accepted=false")
return false
}
// IDs identify turns; do not assume the server allocates them in numeric order.
if (id in retiredTurns) return false
if (!hasTurn || id != currentTurn) {
if (hasTurn) retiredTurns.add(currentTurn)
playback.interrupt()
@@ -256,17 +290,22 @@ class VoiceSession(
sequence = 0
if (blockedTurn != id) blockedTurn = null
}
if (logDecision) diagnostic("acceptTurn $before accepted=true nextTurn=$currentTurn nextBlocked=$blockedTurn retiredNow=${retiredTurns.size}")
return true
}
private fun failAudio(message: String, error: Exception) {
DebugLogUpload.log("audio", "audio failed: ${error.javaClass.simpleName}")
diagnostic("audio failed: ${error.javaClass.simpleName} connection=${state.connection.name}", "error")
Log.w(TAG, message, error)
stopVoice()
update(state.copy(guidance = message))
}
private fun playbackIsCurrent(turn: Long, epoch: Long): Boolean = playback.isCurrent(turn, epoch)
private fun diagnostic(message: String, tag: String = "audio") {
DebugLogUpload.log(tag, message)
onConnectionLog(message)
}
private fun playbackIsCurrent(epoch: Long): Boolean = playback.isCurrent(epoch)
private fun isActive() = !released && foreground && state.voiceActive && state.connection == ConnectionStatus.CONNECTED
private fun update(next: VoiceUiState) { state = next; onState(next) }
@@ -22,7 +22,7 @@ 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 ENDPOINT = "https://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()
@@ -30,11 +30,11 @@ object DebugLogUpload {
@Volatile var lastResult: String = "等待发送"
private set
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.
// Build independently from voice. This gateway endpoint uses HTTPS; Android applies
// the same packaged certificate trust policy, with normal hostname verification.
private val client by lazy {
OkHttpClient.Builder()
.connectionSpecs(listOf(ConnectionSpec.CLEARTEXT))
.connectionSpecs(listOf(ConnectionSpec.MODERN_TLS))
.proxy(Proxy.NO_PROXY) // Direct LAN request, independent of any system HTTP proxy.
.connectionPool(ConnectionPool(2, 30, TimeUnit.SECONDS))
.dispatcher(Dispatcher().apply { maxRequests = 2; maxRequestsPerHost = 2 })
@@ -2,6 +2,7 @@ package com.gorios.lanvoice.net
import android.os.Handler
import android.os.Looper
import android.util.Log
import okhttp3.Call
import okhttp3.Callback
import okhttp3.EventListener
@@ -40,6 +41,7 @@ class DialogueClient(
private val onFrame: (DownlinkFrame) -> Unit = {},
private val onProtocolError: (String) -> Unit = {},
private val onConnectionLog: (String) -> Unit = {},
private val onStatusReason: (ConnectionStatus, String) -> Unit = { _, _ -> },
) {
private val main = Handler(Looper.getMainLooper())
private val endpoint = HttpUrl.Builder()
@@ -95,7 +97,7 @@ class DialogueClient(
socket?.cancel()
socket = null
val attempt = generation
updateStatus(ConnectionStatus.CONNECTING)
updateStatus(ConnectionStatus.CONNECTING, "connect_start")
connectionLog("health checking #$attempt", "connect")
// Arm before submitting the request; synchronous setup failures are terminal too.
handshakeTimeout = Runnable {
@@ -107,7 +109,7 @@ class DialogueClient(
else -> "等待 WS(TCP/TLS/HTTP)"
}
connectionLog("连接超时,请检查网络 · $phase", "error")
finish(socket, ConnectionStatus.DISCONNECTED)
finish(socket, ConnectionStatus.DISCONNECTED, "handshake_timeout")
}
}.also { main.postDelayed(it, 15_000L) }
startHealthProbe(attempt)
@@ -144,7 +146,7 @@ class DialogueClient(
current.enqueue(object : Callback {
override fun onFailure(call: Call, error: IOException) = dispatchHealth(attempt, call) {
connectionLog("health failed: ${failureSummary(error)}", "error")
finish(socket, ConnectionStatus.DISCONNECTED)
finish(socket, ConnectionStatus.DISCONNECTED, "health_failure:${failureSummary(error)}")
}
override fun onResponse(call: Call, response: Response) {
@@ -161,7 +163,7 @@ class DialogueClient(
connectionLog("health submitted #$attempt", "connect")
} catch (error: Exception) {
connectionLog("health setup failed: ${failureSummary(error)}", "error")
finish(socket, ConnectionStatus.DISCONNECTED)
finish(socket, ConnectionStatus.DISCONNECTED, "health_setup_failure:${failureSummary(error)}")
}
}
@@ -174,11 +176,11 @@ class DialogueClient(
connectionLog("ws submitted #$attempt")
} catch (error: Exception) {
connectionLog("ws setup failed: ${failureSummary(error)}", "error")
finish(socket, ConnectionStatus.DISCONNECTED)
finish(socket, ConnectionStatus.DISCONNECTED, "ws_setup_failure:${failureSummary(error)}")
}
}
fun disconnect() {
fun disconnect(reason: String = "client_disconnect") {
checkMainThread()
generation++ // Invalidate before cancellation can trigger onFailure.
cancelHandshakeTimeout()
@@ -191,13 +193,13 @@ class DialogueClient(
previous?.cancel()
if (previous != null) connectionLog("ws disconnected")
else if (previousHealth != null) connectionLog("health cancelled", "connect")
updateStatus(ConnectionStatus.DISCONNECTED)
updateStatus(ConnectionStatus.DISCONNECTED, reason)
}
fun release() {
checkMainThread()
if (released) return
disconnect()
disconnect("client_release")
released = true
client.dispatcher.executorService.shutdown()
client.connectionPool.evictAll()
@@ -221,7 +223,7 @@ class DialogueClient(
if (current.queueSize() > 64 * 1024 ||
!current.send(ByteString.of(*DialogueProtocol.uplink(pcm16, turnId, sequence)))) {
connectionLog("ws audio send failed", "audio")
finish(current, ConnectionStatus.DISCONNECTED)
finish(current, ConnectionStatus.DISCONNECTED, "audio_send_failure_or_backpressure")
return false
}
return true
@@ -236,7 +238,7 @@ class DialogueClient(
}
if (current.send(text)) return true
connectionLog("ws send failed", "error")
finish(current, ConnectionStatus.DISCONNECTED)
finish(current, ConnectionStatus.DISCONNECTED, "control_send_failure")
return false
}
@@ -269,7 +271,7 @@ class DialogueClient(
event.type in setOf("auth.error", "auth.failed") ||
event.payload.optString("status") in setOf("error", "failed", "denied")) {
connectionLog("auth failed", "error")
finish(webSocket, ConnectionStatus.DISCONNECTED)
finish(webSocket, ConnectionStatus.DISCONNECTED, "auth_rejected")
return@dispatch
}
if (authReceived) return@dispatch
@@ -280,7 +282,7 @@ class DialogueClient(
connectionLog("hello sent", "auth")
} else {
connectionLog("hello send failed", "error")
finish(webSocket, ConnectionStatus.DISCONNECTED)
finish(webSocket, ConnectionStatus.DISCONNECTED, "hello_send_failure")
}
return@dispatch
}
@@ -292,11 +294,11 @@ class DialogueClient(
ready = true
cancelHandshakeTimeout()
connectionLog("hello received", "auth")
updateStatus(ConnectionStatus.CONNECTED)
updateStatus(ConnectionStatus.CONNECTED, "server_hello_received")
}
if (event.kind == EventKind.ERROR && !ready) {
connectionLog("握手收到 error", "error")
finish(webSocket, ConnectionStatus.DISCONNECTED)
finish(webSocket, ConnectionStatus.DISCONNECTED, "server_error_during_handshake")
}
onEvent(event)
}
@@ -319,12 +321,12 @@ 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.
connectionLog("ws closed: $code")
finish(webSocket, statusFor(code))
finish(webSocket, statusFor(code), "ws_closing:$code")
}
override fun onClosed(webSocket: WebSocket, code: Int, reason: String) = dispatch(attempt, webSocket) {
connectionLog("ws closed: $code")
finish(webSocket, statusFor(code))
finish(webSocket, statusFor(code), "ws_closed:$code")
}
override fun onFailure(webSocket: WebSocket, t: Throwable, response: Response?) = dispatch(attempt, webSocket) {
@@ -332,7 +334,8 @@ class DialogueClient(
response != null -> "ws failure: HTTP ${response.code}"
else -> "ws failure: ${failureSummary(t)}"
}, "error")
finish(webSocket, if (response?.code == 403) ConnectionStatus.BUSY else ConnectionStatus.DISCONNECTED)
finish(webSocket, if (response?.code == 403) ConnectionStatus.BUSY else ConnectionStatus.DISCONNECTED,
if (response != null) "ws_failure_http:${response.code}" else "ws_failure:${failureSummary(t)}")
}
}
@@ -341,11 +344,12 @@ class DialogueClient(
onConnectionLog(message)
}
private fun updateStatus(next: ConnectionStatus) {
private fun updateStatus(next: ConnectionStatus, reason: String) {
if (status != next) {
status = next
DebugLogUpload.log("connect", "state=${next.name.lowercase()}")
DebugLogUpload.log("connect", "state=${next.name.lowercase()} reason=$reason")
}
onStatusReason(next, reason)
onStatus(next)
}
@@ -361,7 +365,12 @@ class DialogueClient(
}
}
private fun finish(webSocket: WebSocket?, status: ConnectionStatus) {
private fun finish(webSocket: WebSocket?, status: ConnectionStatus, reason: String) {
// Synthetic exception contains only our fixed reason and code locations, no server
// payload/Throwable messages. Full trace stays in logcat; LAN/UI get a bounded trace.
val stack = Log.getStackTraceString(Throwable("DialogueClient.finish reason=$reason"))
Log.w("LanVoice", stack)
connectionLog("finish reason=$reason stack=${stack.replace('\n', '|').replace('\t', ' ').take(360)}", "error")
// Invalidate terminal callbacks so a later failure cannot overwrite a 1013 busy status.
cancelHandshakeTimeout()
val previousHealth = healthCall
@@ -370,7 +379,7 @@ class DialogueClient(
socket = null
ready = false
webSocket?.cancel()
updateStatus(status)
updateStatus(status, reason)
}
private fun cancelHandshakeTimeout() {