522 lines
30 KiB
Kotlin
522 lines
30 KiB
Kotlin
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(persona: String = "default") {
|
|
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, persona=persona)
|
|
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() {
|
|
for(persona in listOf("lvbu","liam")) Fixture(persona).apply {
|
|
event("auth");check(socket.sent==listOf("hello persona=$persona"))
|
|
event("auth");check(socket.sent.size==1)
|
|
event("hello");check(statuses==listOf(ConnectionStatus.CONNECTED))
|
|
client.disconnect()
|
|
listener.onMessage(socket,"auth");listener.onMessage(socket,"hello");Handler.drain()
|
|
check(socket.sent.size==1 && statuses.last()==ConnectionStatus.DISCONNECTED)
|
|
close()
|
|
}
|
|
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 action_offer=none generation=0", "hello received action_pack=unknown generation=0"))
|
|
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 action_offer=none generation=0", "ws open", "hello received action_pack=unknown generation=0"))
|
|
close()
|
|
}
|
|
for((hello,expected) in listOf("hello" to "unknown","hello available" to "accepted","hello unavailable" to "unavailable")) {
|
|
Fixture().apply {
|
|
event("auth");event(hello);check(client.actionNegotiation==expected)
|
|
// Old-generation HELLO cannot overwrite the negotiated connection.
|
|
client.callbacks(-1).onMessage(socket,"hello unavailable");Handler.drain()
|
|
check(client.actionNegotiation==expected)
|
|
close();check(client.actionNegotiation=="disconnected")
|
|
}
|
|
}
|
|
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 action_offer=none generation=1", "hello received action_pack=unknown generation=1").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)
|
|
fun emotion(turn: Long, seq: Long, kind: String = "happy", strength: Int = 2) {
|
|
eventMethod.invoke(session, ServerEvent("reply.emotion", EventKind.REPLY_EMOTION,
|
|
Payload(turn=turn, fields=mapOf("seq" to seq, "emotion" to kind, "intensity" to strength, "source" to "model"))))
|
|
}
|
|
emotion(3, 100)
|
|
check(states.last().roleLabel == "高兴·明显")
|
|
check(states.last().replyEmotion.label == "高兴·明显")
|
|
emotion(3, 99, "angry") // out-of-order same-turn event
|
|
emotion(2, 101, "angry") // retired turn
|
|
emotion(99, 102, "angry") // unannounced turn must not advance current turn
|
|
for (reason in listOf("old_seq", "old_turn", "unannounced_turn")) {
|
|
check(DebugLogUpload.records.any { it.second.startsWith("role ignore reason=$reason ") })
|
|
}
|
|
check(states.last().replyEmotion.label == "高兴·明显")
|
|
emotion(3, 103, "invalid")
|
|
check(states.last().replyEmotion.label == "表达未判定(格式回退)")
|
|
emotion(3, 104, "sad", 1)
|
|
check(states.last().replyEmotion.label == "难过·轻度")
|
|
event(EventKind.TTS, 3, state="stop")
|
|
check(states.last().phase == com.gorios.lanvoice.audio.VoicePhase.ANSWERING)
|
|
check(states.last().replyEmotion.label == "难过·轻度") // tts.stop does not mean native drain
|
|
checkNotNull(com.gorios.lanvoice.audio.AudioPlayback.lastDrained)(3, 0)
|
|
Handler.drain()
|
|
check(states.last().replyEmotion.turnId == null)
|
|
check(states.last().roleLabel == "当前未播放")
|
|
check(states.last().previousReplyEmotion?.label == "难过·轻度")
|
|
emotion(3, 105) // a late event after drained cannot reanimate the expression
|
|
check(DebugLogUpload.records.any { it.second.startsWith("role ignore reason=drained ") })
|
|
check(states.last().previousReplyEmotion?.label == "难过·轻度")
|
|
check(states.last().replyEmotion.turnId == null)
|
|
event(EventKind.ABORT, 4, reason="new_turn")
|
|
check(states.last().previousReplyEmotion?.label == "难过·轻度")
|
|
emotion(4, 106)
|
|
check(states.last().roleLabel == "当前未播放") // accepted expression before PCM is not displayed as playing
|
|
check(states.last().replyEmotion.label == "高兴·明显")
|
|
session.interrupt()
|
|
check(states.last().replyEmotion.turnId == null)
|
|
event(EventKind.ABORT, 4, reason="client_abort")
|
|
check(states.last().replyEmotion.turnId == null)
|
|
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 action_pack=unknown generation=0" })
|
|
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() {
|
|
startupCapabilityCheck()
|
|
presenceCheck()
|
|
checkCallControls()
|
|
checkFaceTransmission()
|
|
run {
|
|
val normal = com.gorios.lanvoice.dialogue.ReplyEmotion.fromWire(2L, 1L, "neutral", 0, "model")!!
|
|
val fallback = com.gorios.lanvoice.dialogue.ReplyEmotion.fromWire(2L, 1L, "neutral", 0, "fallback", "invalid_intensity")!!
|
|
val empty = com.gorios.lanvoice.audio.VoiceUiState()
|
|
check(empty.roleLabel == "当前未播放")
|
|
check(empty.copy(voiceActive=true, phase=com.gorios.lanvoice.audio.VoicePhase.THINKING, replyEmotion=normal).roleLabel == "等待回复")
|
|
check(empty.copy(phase=com.gorios.lanvoice.audio.VoicePhase.ANSWERING, replyEmotion=normal).roleLabel == "中立")
|
|
check(empty.copy(phase=com.gorios.lanvoice.audio.VoicePhase.ANSWERING, replyEmotion=fallback).roleLabel == "表达未判定(格式回退)")
|
|
check(fallback.reason.wire == "invalid_intensity")
|
|
}
|
|
|
|
try { runChecks() } catch (error: Throwable) {
|
|
error.printStackTrace()
|
|
kotlin.system.exitProcess(1)
|
|
}
|
|
}
|