fix: fence voice turns and playback; add opt-in face context

This commit is contained in:
zenord
2026-10-11 20:50:11 +08:00
parent 885bb3f2db
commit 9b428fb76f
46 changed files with 2306 additions and 32 deletions
+9
View File
@@ -0,0 +1,9 @@
package android.media.audiofx
class AcousticEchoCanceler {
companion object {
fun isAvailable() = false
fun create(id: Int): AcousticEchoCanceler? = null
}
fun setEnabled(enabled: Boolean) {}
fun release() {}
}
+60
View File
@@ -0,0 +1,60 @@
import android.media.AudioRecord
import com.gorios.lanvoice.audio.AudioCapture
import java.util.concurrent.CountDownLatch
import java.util.concurrent.TimeUnit
import java.util.concurrent.CopyOnWriteArrayList
fun main() {
for ((mode, phase) in listOf("init" to "initialization", "start" to "startRecording", "read" to "read")) {
AudioRecord.scenario = mode
val messages = CopyOnWriteArrayList<String>()
val failed = CountDownLatch(1)
val capture = AudioCapture()
capture.start(onFrame = { error("no PCM expected") }, onError = { failed.countDown() }, onDiagnostic = messages::add)
check(failed.await(2, TimeUnit.SECONDS))
check(messages.first() == "AudioRecord initialization started")
check(messages.last().startsWith("AudioRecord $phase failed:"))
check(messages.contains("AudioRecord initialization ok") == (mode != "init"))
check(messages.contains("AudioRecord startRecording ok") == (mode == "read"))
check(messages.none { "synthetic mic revocation" in it }) // exception type only
capture.stop()
capture.release()
val limit = System.nanoTime() + 2_000_000_000L
while (AudioRecord.activeDevices.get() != 0) { check(System.nanoTime() < limit); Thread.sleep(1) }
}
val capture = AudioCapture()
for ((mode, expectedCount) in listOf("partial" to 2, "fresh" to 1)) {
AudioRecord.scenario = mode
AudioRecord.partialReady = CountDownLatch(1)
AudioRecord.released = CountDownLatch(1)
val frames = CopyOnWriteArrayList<ByteArray>()
val errors = CopyOnWriteArrayList<Exception>()
capture.start(onFrame = frames::add, onError = errors::add)
check(AudioRecord.partialReady.await(2, TimeUnit.SECONDS))
capture.stop()
check(AudioRecord.released.await(2, TimeUnit.SECONDS))
check(errors.isEmpty())
check(frames.size == expectedCount) // 100B unfinished tail must not be sent
frames.forEachIndexed { index, bytes ->
check(bytes.size == 640)
check(bytes.contentEquals(ByteArray(640) { ((index * 640 + it) % 251).toByte() }))
}
if (frames.size > 1) check(frames[0] !== frames[1])
}
// Turn switch starts immediately while the previous recorder releases slowly.
AudioRecord.scenario = "fresh"
AudioRecord.partialReady = CountDownLatch(1)
AudioRecord.released = CountDownLatch(1)
capture.start({}, { throw it })
check(AudioRecord.partialReady.await(2, TimeUnit.SECONDS))
capture.stop()
AudioRecord.partialReady = CountDownLatch(1)
capture.start({}, { throw it })
check(AudioRecord.partialReady.await(2, TimeUnit.SECONDS))
capture.release()
check(AudioRecord.released.await(2, TimeUnit.SECONDS))
check(AudioRecord.overlaps.get() == 0) { "replacement AudioRecord must await old device release" }
check(AudioCapture.FRAME_BYTES == 640)
println("PASS: short/zero reads accumulated into exact independent 640B frames; stop discards trailing partial; restart starts fresh")
println("PASS: actual AudioCapture with Android media doubles: initialization/start/read success markers and failure stage, no raw exception content")
}
+50
View File
@@ -0,0 +1,50 @@
package android.media
object AudioFormat {
const val CHANNEL_IN_MONO = 16
const val ENCODING_PCM_16BIT = 2
}
class MediaRecorder { object AudioSource { const val VOICE_COMMUNICATION = 7 } }
class AudioRecord(source: Int, rate: Int, channel: Int, encoding: Int, buffer: Int) {
companion object {
const val STATE_INITIALIZED = 1
const val RECORDSTATE_RECORDING = 3
const val READ_BLOCKING = 0
val activeDevices = java.util.concurrent.atomic.AtomicInteger()
val overlaps = java.util.concurrent.atomic.AtomicInteger()
@Volatile var scenario = "init"
@Volatile var partialReady = java.util.concurrent.CountDownLatch(1)
@Volatile var released = java.util.concurrent.CountDownLatch(1)
fun getMinBufferSize(rate: Int, channel: Int, encoding: Int) = 640
}
init { if (activeDevices.incrementAndGet() > 1) overlaps.incrementAndGet() }
private val mode = scenario
val state = if (mode == "init") 0 else STATE_INITIALIZED
val recordingState = RECORDSTATE_RECORDING
val audioSessionId = 1
fun startRecording() { if (mode == "start") throw SecurityException("synthetic mic revocation") }
private val stopped = java.util.concurrent.CountDownLatch(1)
private val ready = partialReady
private val done = released
private val chunks = when (mode) {
"partial" -> listOf(2, 0, 126, 200, 312, 638, 2, 100)
"fresh" -> listOf(640, 100)
else -> emptyList()
}
private var chunk = 0
private var streamOffset = 0
fun read(frame: ByteArray, offset: Int, size: Int, mode: Int): Int {
if (chunks.isEmpty()) return -3
if (chunk == chunks.size) {
ready.countDown()
check(stopped.await(2, java.util.concurrent.TimeUnit.SECONDS))
return -3
}
val count = chunks[chunk++]
check(count <= size && offset + count <= frame.size)
repeat(count) { frame[offset + it] = ((streamOffset + it) % 251).toByte() }
streamOffset += count
return count
}
fun stop() { stopped.countDown() }
fun release() { Thread.sleep(20); activeDevices.decrementAndGet(); done.countDown() }
}
+5
View File
@@ -0,0 +1,5 @@
package android.os
object Process {
const val THREAD_PRIORITY_AUDIO = -16
fun setThreadPriority(priority: Int) {}
}
+29
View File
@@ -0,0 +1,29 @@
import com.gorios.lanvoice.expression.*
fun main() {
fun face(smile: Float = .9f, brow: Float = .1f) = FaceObservation(mapOf(
"mouthSmileLeft" to smile, "mouthSmileRight" to smile,
"browDownLeft" to brow, "browDownRight" to brow), HeadPose(0f, 0f, 0f))
val rules = FaceCueRules()
fun checkUnknown(count: Int = 1, quality: Boolean = true, obs: FaceObservation? = face(), t: Long = 1000) {
check(rules.evaluate(obs, count, quality, t).cue == FaceCue.UNKNOWN)
}
for (t in 0L..700L step 100) checkUnknown(t=t)
check(rules.evaluate(face(),1,true,800).cue == FaceCue.SMILING)
check(rules.evaluate(face(.65f),1,true,900).cue == FaceCue.SMILING) // hysteresis
checkUnknown(count=2)
checkUnknown(t=1100) // must sustain again after a multi-face frame
checkUnknown(obs=face(.9f,.9f),t=1200)
checkUnknown(obs=null,count=0,t=1300)
checkUnknown(quality=false,t=1400)
checkUnknown(obs=face(Float.NaN),t=1500)
checkUnknown(obs=face(1.01f),t=1600)
checkUnknown(obs=face(),t=3000) // long analysis gap restarts stability
rules.reset()
for (t in 0L..800L step 100) {
val result=rules.evaluate(face(.1f,.8f),1,true,t)
check(result.cue == if(t==800L) FaceCue.BROW_FURROWED else FaceCue.UNKNOWN)
}
checkUnknown(obs=face(.1f,.4f),t=900)
println("PASS: sustained bilateral cues, hysteresis, conflict/multiple/no face/poor quality/invalid score/stale reset; no gaze/eye emotion inference")
}
+45
View File
@@ -0,0 +1,45 @@
package android.media
class AudioAttributes {
class Builder { fun setUsage(x: Int) = this; fun setContentType(x: Int) = this; fun build() = AudioAttributes() }
companion object { const val USAGE_MEDIA = 1; const val CONTENT_TYPE_SPEECH = 1 }
}
class AudioFormat {
class Builder { fun setSampleRate(x: Int) = this; fun setChannelMask(x: Int) = this; fun setEncoding(x: Int) = this; fun build() = AudioFormat() }
companion object { const val CHANNEL_OUT_MONO = 1; const val ENCODING_PCM_16BIT = 2 }
}
class AudioTrack {
companion object {
const val STATE_INITIALIZED = 1; const val PLAYSTATE_PLAYING = 3; const val MODE_STREAM = 1; const val WRITE_NON_BLOCKING = 1
@Volatile var latest: AudioTrack? = null
@Volatile var advanceHead = true
@Volatile var rejectWrites = false
fun getMinBufferSize(a: Int, b: Int, c: Int) = 320
}
class Builder {
fun setAudioAttributes(x: AudioAttributes) = this; fun setAudioFormat(x: AudioFormat) = this
fun setTransferMode(x: Int) = this; fun setBufferSizeInBytes(x: Int) = this
fun build() = AudioTrack().also { latest = it }
}
val state = STATE_INITIALIZED
@Volatile var playState = 0
val bufferSizeInFrames = 320
@Volatile var samples = 0
@Volatile var flushes = 0
@Volatile var released = false
@Volatile var attempts = 0
val underrunCount get() = attempts / 4
val playbackHeadPosition get() = if (advanceHead && samples >= bufferSizeInFrames) samples else 0
fun play() { playState = PLAYSTATE_PLAYING }
fun pause() { playState = 0 }
fun flush() { samples = 0; flushes++ }
fun release() { released = true }
fun write(bytes: ByteArray, offset: Int, size: Int, mode: Int): Int {
attempts++
if (rejectWrites) return -3
if (attempts % 4 == 0) return 0 // native buffer temporarily full
val written = minOf(128, size) // partial nonblocking writes
samples += written / 2
return written
}
}
+6
View File
@@ -0,0 +1,6 @@
package android.os
object Process { const val THREAD_PRIORITY_AUDIO = -16; fun setThreadPriority(x: Int) {} }
object SystemClock {
@Volatile var extra = 0L
fun elapsedRealtime() = System.nanoTime() / 1_000_000 + extra
}
+2
View File
@@ -0,0 +1,2 @@
package com.gorios.lanvoice.net
data class DownlinkFrame(val turnId: Long, val sequence: Long, val pcm16: ByteArray)
+55
View File
@@ -0,0 +1,55 @@
import android.media.AudioTrack
import android.os.SystemClock
import com.gorios.lanvoice.audio.AudioPlayback
import com.gorios.lanvoice.net.DownlinkFrame
import java.util.concurrent.CopyOnWriteArrayList
fun awaitCheck(test: () -> Boolean) {
val deadline = System.nanoTime() + 3_000_000_000L
while (!test()) { check(System.nanoTime() < deadline) { "playback test timed out" }; Thread.sleep(2) }
}
fun main() {
val drains = CopyOnWriteArrayList<Long>()
val failures = CopyOnWriteArrayList<Exception>()
val progress = CopyOnWriteArrayList<String>()
val player = AudioPlayback({ turn, _ -> drains.add(turn) }, { _, e -> failures.add(e) }, { _, _, msg -> progress.add(msg) })
try {
player.beginTurn(1)
check(player.enqueue(DownlinkFrame(1, 1, ByteArray(1920))))
awaitCheck { (AudioTrack.latest?.samples ?: 0) == 960 }
check(drains.isEmpty()) // temporary empty software queue is not completion
player.endTurn(1)
awaitCheck { drains == listOf(1L) }
check(progress.last().contains("written=960 head=960"))
check(!player.enqueue(DownlinkFrame(1, 2, ByteArray(10))))
player.beginTurn(2)
check(player.enqueue(DownlinkFrame(2, 1, ByteArray(20)))) // below native startup threshold
player.endTurn(2)
awaitCheck { drains == listOf(1L, 2L) }
check(checkNotNull(AudioTrack.latest).samples == 320) // padded tail counted, partial writes handled
AudioTrack.advanceHead = false
player.beginTurn(3)
check(player.enqueue(DownlinkFrame(3, 1, ByteArray(1920))))
player.endTurn(3)
awaitCheck { checkNotNull(AudioTrack.latest).samples == 960 }
player.interrupt()
AudioTrack.advanceHead = true
Thread.sleep(30)
check(3L !in drains) // interrupted epoch cannot claim drained
AudioTrack.rejectWrites = true
player.beginTurn(4)
check(player.enqueue(DownlinkFrame(4, 1, ByteArray(1920))))
awaitCheck { failures.size == 1 }
check(4L !in drains)
AudioTrack.rejectWrites = false
AudioTrack.advanceHead = false
player.beginTurn(5)
check(player.enqueue(DownlinkFrame(5, 1, ByteArray(1920))))
player.endTurn(5)
awaitCheck { (AudioTrack.latest?.samples ?: 0) == 960 }
SystemClock.extra = 11_000
awaitCheck { failures.size == 2 }
check(5L !in drains)
println("PASS: real AudioPlayback partial/zero writes, explicit end + native head drain, short tail, interruption fence, write failure, stalled head watchdog; device doubles, no real speaker")
} finally { player.release() }
}
+11
View File
@@ -0,0 +1,11 @@
package org.json
// Serialization-only JVM double; actual Android JSONObject API compiled in normal build.
class JSONObject() {
constructor(text: String) : this() { error("Parser is outside this double's scope") }
private val fields = linkedMapOf<String, Any>()
fun put(key: String, value: Any): JSONObject { fields[key] = value; return this }
fun opt(key: String): Any? = fields[key]
override fun toString(): String = fields.entries.joinToString(",", "{", "}") { (key, value) ->
"\"$key\":" + if (value is String) "\"$value\"" else value.toString()
}
}
+46
View File
@@ -0,0 +1,46 @@
import com.gorios.lanvoice.net.DialogueProtocol
fun main() {
val pcm = ByteArray(640) { (it % 256).toByte() }
val uplink = DialogueProtocol.uplink(pcm, 0x81234567L, 0xffffffffL)
val golden = byteArrayOf(0x4c, 0x56, 0x01, 0x01, 0x81.toByte(), 0x23, 0x45, 0x67,
0xff.toByte(), 0xff.toByte(), 0xff.toByte(), 0xff.toByte())
check(uplink.size == 652)
check(uplink.copyOfRange(0, 12).contentEquals(golden))
check(uplink.copyOfRange(12, 652).contentEquals(pcm))
val downlink = golden.copyOf(1932).also {
it[3] = 2
it[12] = 0
it[13] = 0x80.toByte()
}
val decoded = DialogueProtocol.parseDownlink(downlink)
check(decoded.turnId == 0x81234567L && decoded.sequence == 0xffffffffL)
check(decoded.pcm16.size == 1920 && decoded.sampleRate == 48000)
check(decoded.pcm16[1] == 0x80.toByte())
check(DialogueProtocol.parseDownlink(downlink.copyOf(14)).pcm16.size == 2)
val invalid = listOf(byteArrayOf(), downlink.copyOf(12), downlink.copyOf(13), downlink.copyOf(1934),
downlink.copyOf().also { it[0] = 0 }, downlink.copyOf().also { it[2] = 2 },
downlink.copyOf().also { it[3] = 1 })
invalid.forEach {
check(runCatching { DialogueProtocol.parseDownlink(it) }.exceptionOrNull() is IllegalArgumentException)
}
listOf(-1L, 0x100000000L).forEach {
check(runCatching { DialogueProtocol.uplink(pcm, it, 0) }.exceptionOrNull() is IllegalArgumentException)
check(runCatching { DialogueProtocol.uplink(pcm, 0, it) }.exceptionOrNull() is IllegalArgumentException)
}
check(runCatching { DialogueProtocol.uplink(ByteArray(638), 0, 0) }.exceptionOrNull() is IllegalArgumentException)
val observation = com.gorios.lanvoice.expression.FaceCueObservation(
com.gorios.lanvoice.expression.FaceCue.SMILING, .8f, 900, 100)
val valid = DialogueProtocol.faceCue(7, observation, 100)
check(valid.toByteArray().size <= 512 && "\"cue\":\"smiling\"" in valid && "\"valid\":true" in valid)
for (age in listOf(-1L, 3001L)) {
val expired = DialogueProtocol.faceCue(7, observation, age)
check("\"cue\":\"unknown\"" in expired && "\"valid\":false" in expired)
check("\"intensity\":0.0" in expired && "\"duration_ms\":0" in expired)
}
check("\"valid\":false" in DialogueProtocol.faceCue(7, observation.copy(intensity=Float.NaN), 0))
check(runCatching { DialogueProtocol.faceCue(-1, observation, 0) }.exceptionOrNull() is IllegalArgumentException)
check(listOf("landmarks", "blendshape", "image", "text").none { "\"$it\":" in valid })
println("PASS: typed enum-only face serialization, stale/invalid clear, bounded control, no images/landmarks/arbitrary text")
println("PASS: v0.8 directions 1/2, golden uint32 header, 640B uplink, 1920B/short downlink, PCM preservation, invalid frames/IDs")
}
+6
View File
@@ -0,0 +1,6 @@
package android.util
object Log {
@JvmStatic fun getStackTraceString(error: Throwable) = error.stackTraceToString()
@JvmStatic fun w(tag: String, message: String) = 0
@JvmStatic fun w(tag: String, message: String, error: Throwable) = 0
}
+22
View File
@@ -0,0 +1,22 @@
package android.os
class Looper {
companion object {
private val main = Looper()
@JvmStatic fun getMainLooper() = main
@JvmStatic fun myLooper() = main
}
}
// Deterministic FIFO main-thread queue; no Android device/real sockets in this test.
class Handler(val looper: Looper) {
companion object {
val queue = java.util.concurrent.ConcurrentLinkedQueue<Runnable>()
val delayed = mutableListOf<Runnable>()
fun drain() { while (true) (queue.poll() ?: return).run() }
}
fun post(action: Runnable): Boolean { queue.add(action); return true }
fun postDelayed(action: Runnable, delay: Long): Boolean { delayed.add(action); return true }
fun removeCallbacks(action: Runnable) { delayed.remove(action); queue.remove(action) }
}
object SystemClock { fun elapsedRealtime() = System.nanoTime() / 1_000_000 }
+23
View File
@@ -0,0 +1,23 @@
package com.gorios.lanvoice.audio
import com.gorios.lanvoice.net.DownlinkFrame
enum class AecAvailability { AVAILABLE, UNAVAILABLE, UNKNOWN }
// No audio devices in callback propagation tests.
class AudioCapture {
companion object { var lastFrame: ((ByteArray) -> Unit)? = null; var lastError: ((Exception) -> Unit)? = null }
fun aecAvailability() = AecAvailability.UNKNOWN
fun start(onFrame: (ByteArray) -> Unit, onError: (Exception) -> Unit, onDiagnostic: (String) -> Unit = {}) { lastFrame = onFrame; lastError = onError; onDiagnostic("AudioRecord initialization ok") }
fun stop() {}
fun release() {}
}
class AudioPlayback(onDrained: (Long, Long) -> Unit, onError: (Long, Exception) -> Unit, onProgress: (Long, Long, String) -> Unit = { _, _, _ -> }) {
companion object { var interrupts = 0; var enqueued = 0 }
fun beginTurn(turn: Long) {}
fun endTurn(turn: Long) {}
fun enqueue(frame: DownlinkFrame): Boolean { enqueued++; return true }
fun isCurrent(turn: Long, epoch: Long) = true
fun isCurrent(epoch: Long) = true
fun interrupt() { interrupts++ }
fun release() {}
}
+451
View File
@@ -0,0 +1,451 @@
import android.os.Handler
import com.gorios.lanvoice.net.*
import okhttp3.*
import okio.ByteString
import okhttp3.ResponseBody.Companion.toResponseBody
class FakeSocket : WebSocket {
val sent = mutableListOf<String>()
var acceptSend = true
var cancelled = false
override fun request() = Request.Builder().url("https://localhost/ws/dialogue").build()
override fun queueSize() = 0L
override fun send(text: String): Boolean { if (acceptSend) sent.add(text); return acceptSend }
override fun send(bytes: ByteString) = acceptSend
override fun close(code: Int, reason: String?) = true
override fun cancel() { cancelled = true }
}
fun DialogueClient.setField(name: String, value: Any?) {
javaClass.getDeclaredField(name).apply { isAccessible = true }.set(this, value)
}
fun DialogueClient.callbacks(generation: Long): WebSocketListener =
javaClass.getDeclaredMethod("listener", Long::class.javaPrimitiveType).apply { isAccessible = true }
.invoke(this, generation) as WebSocketListener
class Fixture {
val statuses = mutableListOf<ConnectionStatus>()
val logs = mutableListOf<String>()
val events = mutableListOf<EventKind>()
val client = DialogueClient("localhost", 5011, statuses::add, onEvent = { events.add(it.kind) }, onConnectionLog = logs::add)
val socket = FakeSocket()
val listener = client.callbacks(0)
init { client.setField("socket", socket) }
fun event(text: String) { listener.onMessage(socket, text); Handler.drain() }
fun handshake() { event("auth"); event("hello") }
fun close() { client.release(); Handler.drain() }
}
fun awaitMain(condition: () -> Boolean) {
val limit = System.nanoTime() + java.util.concurrent.TimeUnit.SECONDS.toNanos(3)
while (!condition()) {
Handler.drain()
check(System.nanoTime() < limit) { "main callback did not arrive" }
Thread.sleep(1)
}
Handler.drain()
}
fun healthResponse(request: Request, code: Int) = Response.Builder().request(request)
.protocol(Protocol.HTTP_1_1).code(code).message("test").body("".toResponseBody()).build()
fun response(code: Int) = Response.Builder().request(Request.Builder().url("https://localhost/").build())
.protocol(Protocol.HTTP_1_1).code(code).message("test").build()
// Real OkHttp request creation with an interceptor that never opens a socket.
// The barrier keeps its failure callback out of deterministic handshake simulations.
class StartingFixture(val healthCode: Int = 200, val healthError: java.io.IOException? = null, val holdHealth: Boolean = false) {
val statuses = mutableListOf<ConnectionStatus>()
val logs = mutableListOf<String>()
private val barrier = java.util.concurrent.CountDownLatch(1)
val client = DialogueClient("localhost", 5011, statuses::add, onConnectionLog = logs::add)
init {
val controlled = OkHttpClient.Builder().addInterceptor {
if (it.request().url.encodedPath == "/health") {
if (holdHealth) barrier.await(30, java.util.concurrent.TimeUnit.SECONDS)
healthError?.let { error -> throw error }
healthResponse(it.request(), healthCode)
} else {
barrier.await(30, java.util.concurrent.TimeUnit.SECONDS)
throw java.io.IOException("simulated transport failure")
}
}.build()
client.setField("client", controlled)
}
fun peekSocket() = client.javaClass.getDeclaredField("socket").apply { isAccessible = true }.get(client) as? WebSocket
fun socket(): WebSocket { awaitMain { peekSocket() != null }; return checkNotNull(peekSocket()) }
fun timeout() = client.javaClass.getDeclaredField("handshakeTimeout").apply { isAccessible = true }.get(client) as Runnable
fun close() { client.release(); barrier.countDown(); Handler.drain() }
}
fun runChecks() {
Fixture().apply {
listener.onOpen(socket, response(101)); Handler.drain()
check(!client.listen(true))
event("auth")
check(socket.sent == listOf("hello") && statuses.isEmpty())
check(!client.listen(true)) // sending hello never enables control/audio
event("auth"); check(socket.sent.size == 1)
event("hello")
check(statuses == listOf(ConnectionStatus.CONNECTED))
check(logs.filterNot { it.startsWith("listen ") || it.startsWith("ws control skipped") } == listOf("ws open", "auth ok", "hello sent", "hello received"))
check(client.listen(true))
event("hello"); check(statuses.count { it == ConnectionStatus.CONNECTED } == 1)
event("history"); check(events.last() == EventKind.HISTORY)
close()
}
Fixture().apply {
// AUTH queued ahead of onOpen must still send hello, and onOpen must not reset readiness.
listener.onMessage(socket, "auth")
listener.onOpen(socket, response(101))
listener.onMessage(socket, "hello")
Handler.drain()
check(socket.sent == listOf("hello"))
check(statuses == listOf(ConnectionStatus.CONNECTED))
check(logs == listOf("auth ok", "hello sent", "ws open", "hello received"))
close()
}
Fixture().apply {
event("hello"); check(statuses.isEmpty() && !client.listen(true))
handshake(); check(statuses.last() == ConnectionStatus.CONNECTED)
close()
}
Fixture().apply {
socket.acceptSend = false
event("auth"); check(socket.cancelled && statuses.last() == ConnectionStatus.DISCONNECTED)
event("hello"); check(ConnectionStatus.CONNECTED !in statuses)
check("hello send failed" in logs)
close()
}
Fixture().apply {
event("auth failed"); check(socket.sent.isEmpty() && socket.cancelled && "auth failed" in logs)
close()
}
Fixture().apply {
event("auth"); event("error")
check(statuses.last() == ConnectionStatus.DISCONNECTED && socket.cancelled)
check("握手收到 error" in logs)
close()
}
for (code in listOf(1008, 1013)) Fixture().apply {
handshake()
listener.onClosing(socket, code, "test"); Handler.drain()
val expected = if (code == 1013) ConnectionStatus.BUSY else ConnectionStatus.DISCONNECTED
check(statuses.last() == expected && "ws closed: $code" in logs)
val count = statuses.size; val logCount = logs.size
listener.onClosed(socket, code, "test")
listener.onFailure(socket, IllegalStateException(), null); Handler.drain()
check(statuses.size == count && logs.size == logCount)
close()
}
Fixture().apply {
listener.onFailure(socket, IllegalStateException(), response(403)); Handler.drain()
check(statuses.last() == ConnectionStatus.BUSY && "ws failure: HTTP 403" in logs)
close()
}
Fixture().apply {
listener.onMessage(socket, "auth") // queued old callback
val replacement = FakeSocket()
client.setField("generation", 1L); client.setField("socket", replacement)
Handler.drain()
check(socket.sent.isEmpty() && replacement.sent.isEmpty() && logs.isEmpty())
// Matching generation with the wrong socket also cannot change status/logs.
client.callbacks(1).onOpen(socket, response(101)); Handler.drain()
check(logs.isEmpty())
client.callbacks(1).onMessage(replacement, "auth")
client.callbacks(1).onMessage(replacement, "hello"); Handler.drain()
check(replacement.sent == listOf("hello") && statuses == listOf(ConnectionStatus.CONNECTED))
close()
}
Fixture().apply {
val delayed = Runnable { error("cancelled timeout must never run") }
Handler.delayed.add(delayed); client.setField("handshakeTimeout", delayed)
handshake(); check(delayed !in Handler.delayed)
close()
}
StartingFixture().apply {
client.connect()
check(statuses == listOf(ConnectionStatus.CONNECTING))
check(logs.first() == "connect_start #1")
val current = socket()
check(logs.takeLast(3) == listOf("health HTTP 200 · HTTPS 可达", "ws connecting #1", "ws submitted #1"))
val cb = client.callbacks(1)
cb.onOpen(current, response(101)); Handler.drain()
cb.onMessage(current, "auth"); Handler.drain()
check(statuses.last() == ConnectionStatus.CONNECTING && !client.listen(true))
cb.onMessage(current, "hello"); Handler.drain()
check(statuses == listOf(ConnectionStatus.CONNECTING, ConnectionStatus.CONNECTED))
check(Handler.delayed.isEmpty())
close()
}
for (phase in listOf("WS", "auth", "hello")) StartingFixture().apply {
client.connect()
val current = socket()
val cb = client.callbacks(1)
if (phase != "WS") cb.onOpen(current, response(101))
if (phase == "hello") cb.onMessage(current, "auth")
Handler.drain()
timeout().run()
check(statuses.last() == ConnectionStatus.DISCONNECTED)
check(logs.any { it.startsWith("连接超时,请检查网络 · 等待 $phase") })
cb.onMessage(current, "auth"); cb.onMessage(current, "hello"); Handler.drain()
check(ConnectionStatus.CONNECTED !in statuses)
check(Handler.delayed.isEmpty())
close()
}
StartingFixture().apply {
client.connect()
val previous = socket(); val previousTimeout = timeout()
client.disconnect()
client.connect()
socket()
val size = logs.size
previousTimeout.run()
client.callbacks(1).onOpen(previous, response(101)); Handler.drain()
check(logs.size == size && statuses.last() == ConnectionStatus.CONNECTING)
close()
}
for ((error, expected) in listOf(
javax.net.ssl.SSLHandshakeException("test").apply { initCause(java.security.cert.CertificateException("test")) } to "TLS 证书验证失败",
javax.net.ssl.SSLPeerUnverifiedException("test") to "TLS 主机名/证书验证失败",
java.net.ConnectException("test") to "TCP 连接失败",
java.net.SocketTimeoutException("test") to "连接超时",
java.io.InterruptedIOException("timeout") to "连接超时",
java.net.UnknownHostException("test") to "主机解析失败",
)) Fixture().apply {
listener.onFailure(socket, error, null); Handler.drain()
check("ws failure: $expected" in logs)
check(statuses.last() == ConnectionStatus.DISCONNECTED)
close()
}
Fixture().apply {
event("unknown")
check(logs.last() == "ws received: unknown event")
close()
}
run {
val states = mutableListOf<com.gorios.lanvoice.audio.VoiceUiState>()
val logs = mutableListOf<String>()
val barrier = java.util.concurrent.CountDownLatch(1)
val session = com.gorios.lanvoice.audio.VoiceSession("localhost", 5011, states::add, logs::add)
val dialogue = session.javaClass.getDeclaredField("dialogue").apply { isAccessible = true }
.get(session) as DialogueClient
val controlled = OkHttpClient.Builder().addInterceptor {
if (it.request().url.encodedPath == "/health") {
healthResponse(it.request(), 200)
} else {
barrier.await(30, java.util.concurrent.TimeUnit.SECONDS)
throw java.io.IOException("simulated transport failure")
}
}.build()
dialogue.setField("client", controlled)
session.foreground()
check(states.last().connection == ConnectionStatus.CONNECTING)
val socketField = dialogue.javaClass.getDeclaredField("socket").apply { isAccessible = true }
awaitMain { socketField.get(dialogue) != null }
val current = socketField.get(dialogue) as WebSocket
val cb = dialogue.callbacks(1)
cb.onOpen(current, response(101)); cb.onMessage(current, "auth"); Handler.drain()
check(states.last().connection == ConnectionStatus.CONNECTING)
cb.onMessage(current, "hello"); Handler.drain()
check(states.last().connection == ConnectionStatus.CONNECTED)
check(listOf("auth ok", "hello sent", "hello received").all { it in logs })
session.startVoice()
session.background(showDisconnectReason = true)
check(states.last().connection == ConnectionStatus.DISCONNECTED && !states.last().voiceActive)
check(states.last().guidance == "App 退到后台,连接已断开")
check(logs.contains("App 退到后台,连接已断开"))
session.foreground()
check(states.last().connection == ConnectionStatus.CONNECTING)
check(states.last().guidance == "App 退到后台,连接已断开")
awaitMain { socketField.get(dialogue) != null }
val nextSocket = socketField.get(dialogue) as WebSocket
val nextCb = dialogue.callbacks(3)
nextCb.onOpen(nextSocket, response(101))
nextCb.onMessage(nextSocket, "auth"); nextCb.onMessage(nextSocket, "hello"); Handler.drain()
check(states.last().connection == ConnectionStatus.CONNECTED)
check(states.last().guidance == "App 退到后台,连接已断开")
session.startVoice()
check(states.last().voiceActive && states.last().guidance == null)
nextCb.onClosing(nextSocket, 1008, "test"); Handler.drain()
check(states.last().connection == ConnectionStatus.DISCONNECTED && !states.last().voiceActive)
session.release(); barrier.countDown(); Handler.drain()
}
for (code in listOf(200, 404, 403, 503)) StartingFixture(healthCode = code).apply {
client.connect()
socket()
check(logs.contains("health HTTP $code · HTTPS 可达"))
check(statuses == listOf(ConnectionStatus.CONNECTING))
close()
}
for ((failure, diagnostic) in listOf(
java.net.ConnectException("test") to "TCP 连接失败",
java.net.SocketTimeoutException("test") to "连接超时",
javax.net.ssl.SSLHandshakeException("test") to "TLS 握手失败",
)) StartingFixture(healthError = failure).apply {
client.connect()
awaitMain { statuses.last() == ConnectionStatus.DISCONNECTED }
check(peekSocket() == null && "health failed: $diagnostic" in logs)
check(Handler.delayed.isEmpty())
close()
}
StartingFixture(holdHealth = true).apply {
client.connect()
val health = client.javaClass.getDeclaredField("healthCall").apply { isAccessible = true }.get(client) as Call
check(health.request().url.toString() == "https://localhost:5011/health")
check(health.request().header("Origin") == "https://localhost:5011")
timeout().run()
check(statuses.last() == ConnectionStatus.DISCONNECTED && health.isCanceled())
check("连接超时,请检查网络 · health request" in logs)
check(peekSocket() == null)
close()
}
StartingFixture(holdHealth = true).apply {
client.connect()
val oldHealth = client.javaClass.getDeclaredField("healthCall").apply { isAccessible = true }.get(client) as Call
val gate = client.javaClass.getDeclaredMethod("dispatchHealth", Long::class.javaPrimitiveType, Call::class.java, kotlin.jvm.functions.Function0::class.java)
.apply { isAccessible = true }
val forbidden = { error("old health callback must be ignored") }
gate.invoke(client, 1L, oldHealth, forbidden)
client.disconnect()
client.connect()
Handler.drain()
check(oldHealth.isCanceled() && statuses.last() == ConnectionStatus.CONNECTING && peekSocket() == null)
close()
}
StartingFixture(holdHealth = true).apply {
client.connect()
val field = client.javaClass.getDeclaredField("healthCall").apply { isAccessible = true }
val first = field.get(client) as Call
client.connect()
check(field.get(client) === first && !first.isCanceled())
check(logs.count { it.startsWith("connect_start") } == 1)
close()
}
for (sendFails in listOf(false, true)) run {
val states = mutableListOf<com.gorios.lanvoice.audio.VoiceUiState>()
val session = com.gorios.lanvoice.audio.VoiceSession("localhost", 5011, states::add)
val dialogue = session.javaClass.getDeclaredField("dialogue").apply { isAccessible = true }
.get(session) as DialogueClient
val barrier = java.util.concurrent.CountDownLatch(1)
val controlled = OkHttpClient.Builder().addInterceptor {
barrier.await(2, java.util.concurrent.TimeUnit.SECONDS)
throw java.io.IOException("held probe")
}.build()
dialogue.setField("client", controlled)
session.foreground()
val callField = dialogue.javaClass.getDeclaredField("healthCall").apply { isAccessible = true }
val oldProbe = callField.get(dialogue) as Call
callField.set(dialogue, null); oldProbe.cancel()
val fake = FakeSocket()
dialogue.setField("socket", fake)
val cb = dialogue.callbacks(1)
cb.onMessage(fake, "auth"); cb.onMessage(fake, "hello"); Handler.drain()
val epoch = dialogue.javaClass.getDeclaredField("generation").apply { isAccessible = true }
session.foreground(); dialogue.connect()
check(epoch.get(dialogue) == 1L && !fake.cancelled)
session.background(keepConnectionForPermission = true)
check(!fake.cancelled && states.last().guidance == null)
val grace = session.javaClass.getDeclaredField("backgroundTimeout").apply { isAccessible = true }
.get(session) as Runnable
session.foreground()
check(grace !in Handler.delayed && epoch.get(dialogue) == 1L && !fake.cancelled)
fake.acceptSend = !sendFails
session.startVoice(); session.startVoice()
check(epoch.get(dialogue) == 1L) // listen/startCapture never invokes connect
if (sendFails) {
check(states.last().connection == ConnectionStatus.DISCONNECTED && fake.cancelled)
check(!states.last().voiceActive)
} else {
check(fake.sent == listOf("hello", "listen"))
check(states.last().voiceActive)
val eventMethod = session.javaClass.getDeclaredMethod("onEvent", ServerEvent::class.java).apply { isAccessible = true }
fun event(kind: EventKind, turn: Long, state: String = "", reason: String = "") {
eventMethod.invoke(session, ServerEvent(kind.name.lowercase(), kind, Payload(turn=turn, state=state, reason=reason)))
}
event(EventKind.UNKNOWN, 0)
event(EventKind.ABORT, 1, reason="listen_start")
event(EventKind.LISTEN, 1, state="start")
val blockedField = session.javaClass.getDeclaredField("blockedTurn").apply { isAccessible = true }
check(blockedField.get(session) == null)
check(states.last().connection == ConnectionStatus.CONNECTED && states.last().voiceActive)
val beforeFrames = com.gorios.lanvoice.audio.AudioPlayback.enqueued
val frameMethod = session.javaClass.getDeclaredMethod("onFrame", DownlinkFrame::class.java).apply { isAccessible = true }
frameMethod.invoke(session, DownlinkFrame(turnId=1))
check(com.gorios.lanvoice.audio.AudioPlayback.enqueued == beforeFrames + 1)
event(EventKind.UNKNOWN, 0) // retired old turn must be rejected
check(DebugLogUpload.records.any { (_, msg) -> "id=0" in msg && "accepted=false" in msg })
event(EventKind.STT, 1, state="done")
check(states.last().phase == com.gorios.lanvoice.audio.VoicePhase.THINKING)
val oldCapture = checkNotNull(com.gorios.lanvoice.audio.AudioCapture.lastFrame)
oldCapture(ByteArray(640)) // queued before a new-turn event reaches main
val beforeUplinks = DialogueProtocol.uplinks.size
event(EventKind.UNKNOWN, 2) // replacement already announced by another event
event(EventKind.ABORT, 2, reason="voice_barge_in")
Handler.drain()
check(DialogueProtocol.uplinks.size == beforeUplinks) { "queued old capture must not be relabeled" }
checkNotNull(com.gorios.lanvoice.audio.AudioCapture.lastFrame)(ByteArray(640))
Handler.drain()
check(DialogueProtocol.uplinks.last() == Triple(2L, 1L, 640))
check(blockedField.get(session) == null) { "replacement turn must remain unblocked" }
event(EventKind.LLM, 2)
check(states.last().phase == com.gorios.lanvoice.audio.VoicePhase.THINKING)
event(EventKind.TTS, 2, state="start")
check(states.last().phase == com.gorios.lanvoice.audio.VoicePhase.THINKING)
event(EventKind.TTS, 2, state="metrics")
check(states.last().phase == com.gorios.lanvoice.audio.VoicePhase.THINKING)
frameMethod.invoke(session, DownlinkFrame(turnId=2))
check(com.gorios.lanvoice.audio.AudioPlayback.enqueued == beforeFrames + 2)
frameMethod.invoke(session, DownlinkFrame(turnId=1)) // old interrupted audio remains retired
check(com.gorios.lanvoice.audio.AudioPlayback.enqueued == beforeFrames + 2)
event(EventKind.ABORT, 1, reason="voice_barge_in") // stale abort must not affect new turn
check(blockedField.get(session) == null)
frameMethod.invoke(session, DownlinkFrame(turnId=2))
check(com.gorios.lanvoice.audio.AudioPlayback.enqueued == beforeFrames + 3)
event(EventKind.ABORT, 2, reason="user_interrupt") // same-turn abort still blocks that turn
check(blockedField.get(session) == 2L)
frameMethod.invoke(session, DownlinkFrame(turnId=2))
check(com.gorios.lanvoice.audio.AudioPlayback.enqueued == beforeFrames + 3)
event(EventKind.ABORT, 3, reason="listen_start") // a reset clears the previous block
event(EventKind.LISTEN, 3, state="start")
check(blockedField.get(session) == null)
event(EventKind.TTS, 3, state="start")
frameMethod.invoke(session, DownlinkFrame(turnId=3))
check(com.gorios.lanvoice.audio.AudioPlayback.enqueued == beforeFrames + 4)
check(states.last().phase == com.gorios.lanvoice.audio.VoicePhase.ANSWERING)
event(EventKind.TTS, 3, state="stop")
check(states.last().phase == com.gorios.lanvoice.audio.VoicePhase.ANSWERING)
event(EventKind.UNKNOWN, 4)
event(EventKind.ABORT, 4, reason="new_turn")
check(blockedField.get(session) == null)
event(EventKind.STT, 4, state="final")
event(EventKind.TTS, 4, state="start")
check(states.last().phase == com.gorios.lanvoice.audio.VoicePhase.THINKING)
event(EventKind.TTS, 4, state="stop") // no PCM produces guidance instead of eternal THINKING
check(states.last().guidance?.contains("未收到") == true)
session.startVoice()
com.gorios.lanvoice.audio.AudioCapture.lastError?.invoke(SecurityException("revoked mic"))
Handler.drain()
check(states.last().connection == ConnectionStatus.CONNECTED && !states.last().voiceActive)
check(epoch.get(dialogue) == 1L && !fake.cancelled) // capture error stops audio, no reconnect
val beforeIdleAbort = com.gorios.lanvoice.audio.AudioPlayback.interrupts
event(EventKind.ABORT, 2)
check(com.gorios.lanvoice.audio.AudioPlayback.interrupts == beforeIdleAbort)
dialogue.disconnect("test_disconnect")
val beforeDisconnectedAbort = com.gorios.lanvoice.audio.AudioPlayback.interrupts
event(EventKind.ABORT, 3)
check(com.gorios.lanvoice.audio.AudioPlayback.interrupts == beforeDisconnectedAbort)
check(DebugLogUpload.records.any { (_, msg) -> "CONNECTED -> DISCONNECTED reason=test_disconnect" in msg })
}
session.release(); barrier.countDown(); Handler.drain()
}
check(DebugLogUpload.records.any { it.first == "connect" && it.second.startsWith("state=connected reason=") })
check(DebugLogUpload.records.any { it == "auth" to "hello received" })
check(DebugLogUpload.records.any { it == "ws" to "ws event=history" })
check(DebugLogUpload.records.none { (_, message) -> "auth_ready" in message })
check(DebugLogUpload.records.any { (_, message) -> "finish reason=control_send_failure stack=" in message })
check(DebugLogUpload.records.any { (_, message) -> "ABORT blockedTurn=null active=true listenReset=true" in message })
check(DebugLogUpload.records.any { (_, message) -> "LISTEN action=start active=true" in message })
println("PASS: actual DialogueClient with event/main-thread/transport doubles: server HELLO readiness, early AUTH, duplicate AUTH/HELLO, send/auth/error failure, close 1008/1013, HTTP 403, generation/socket fencing, timeout cancellation, real request submission with CONNECTING→CONNECTED, WS/auth/hello timeouts, stale timer fencing, TLS/TCP diagnostics, real VoiceSession state/log propagation, health-before-WS HTTP 200/404/403/503, probe network failures, overall timeout, health cancellation/generation fence, duplicate-connect guard, permission-return reuse, listen send failure and capture permission error without reconnect, listen_start abort allows new turn, voice_barge_in blocks prior turn and allows replacement TTS/audio, stale frames/abort rejected, same-turn abort still blocked, listen_start clears previous block, inactive/disconnected abort has no side effects, event/turn/reason/finish traces")
}
fun main() {
try { runChecks() } catch (error: Throwable) {
error.printStackTrace()
kotlin.system.exitProcess(1)
}
}
+6
View File
@@ -0,0 +1,6 @@
package com.gorios.lanvoice.net
// This test records uploads without network access; the uploader has separate checks.
object DebugLogUpload {
val records = mutableListOf<Pair<String, String>>()
fun log(tag: String, message: String) { records.add(tag to message) }
}
+32
View File
@@ -0,0 +1,32 @@
package com.gorios.lanvoice.net
// Event doubles isolate DialogueClient callback ordering from the unchanged JSON parser.
// Production DialogueProtocol/JSONObject were compiled separately with actual dependencies.
class Payload(private val ok: Boolean = true, private val turn: Long? = null, private val state: String = "", private val reason: String = "") {
fun optBoolean(key: String, fallback: Boolean) = if (key == "ok") ok else fallback
fun optString(key: String, fallback: String = "") = when (key) { "state" -> state; "reason" -> reason; else -> fallback }
fun optInt(key: String, fallback: Int) = if (key == "context_face_cue_version") 1 else fallback
fun opt(key: String): Any? = if (key == "turn_id") turn else null
}
enum class EventKind { AUTH, HELLO, ERROR, HISTORY, UNKNOWN, LISTEN, VAD, STT, LLM, TTS, ABORT }
data class ServerEvent(val type: String, val kind: EventKind, val payload: Payload)
class DownlinkFrame(val turnId: Long = 0, val sequence: Long = 0, val pcm16: ByteArray = ByteArray(2))
object DialogueProtocol {
val uplinks = mutableListOf<Triple<Long, Long, Int>>()
fun faceCue(turn: Long, observation: com.gorios.lanvoice.expression.FaceCueObservation, age: Long) = "face_cue"
fun hello() = "hello"
fun listen(start: Boolean) = "listen"
fun abort(turn: Long) = "abort"
fun playbackDrained(turn: Long) = "drained"
fun uplink(pcm: ByteArray, turn: Long, seq: Long): ByteArray { uplinks.add(Triple(turn, seq, pcm.size)); return pcm }
fun parseDownlink(bytes: ByteArray) = DownlinkFrame()
fun parseEvent(text: String) = when (text) {
"auth" -> ServerEvent("auth", EventKind.AUTH, Payload())
"auth failed" -> ServerEvent("auth", EventKind.AUTH, Payload(false))
"hello" -> ServerEvent("hello", EventKind.HELLO, Payload())
"error" -> ServerEvent("error", EventKind.ERROR, Payload())
"unknown" -> ServerEvent("auth_ready", EventKind.UNKNOWN, Payload())
"history" -> ServerEvent("history", EventKind.HISTORY, Payload())
else -> error("malformed")
}
}