fix: fence voice turns and playback; add opt-in face context
This commit is contained in:
@@ -6,3 +6,6 @@ local.properties
|
||||
*.keystore
|
||||
logs/
|
||||
artifacts/
|
||||
|
||||
__pycache__/
|
||||
*.py[cod]
|
||||
|
||||
+2
-2
@@ -45,8 +45,8 @@ android {
|
||||
applicationId 'com.gorios.lanvoice'
|
||||
minSdk 26
|
||||
targetSdk 34
|
||||
versionCode 6
|
||||
versionName '0.3.3'
|
||||
versionCode 7
|
||||
versionName '0.4.0'
|
||||
ndk { abiFilters 'arm64-v8a' }
|
||||
}
|
||||
compileOptions { sourceCompatibility JavaVersion.VERSION_17; targetCompatibility JavaVersion.VERSION_17 }
|
||||
|
||||
@@ -3,6 +3,7 @@ package com.gorios.lanvoice
|
||||
import android.Manifest
|
||||
import android.content.pm.PackageManager
|
||||
import android.os.Build
|
||||
import android.media.AudioManager
|
||||
import android.os.Bundle
|
||||
import android.security.NetworkSecurityPolicy
|
||||
import androidx.activity.ComponentActivity
|
||||
@@ -10,7 +11,6 @@ import androidx.activity.compose.setContent
|
||||
import androidx.activity.result.contract.ActivityResultContracts
|
||||
import androidx.compose.foundation.background
|
||||
import androidx.compose.foundation.layout.Arrangement
|
||||
import androidx.compose.foundation.layout.Box
|
||||
import androidx.compose.foundation.layout.Column
|
||||
import androidx.compose.foundation.layout.Row
|
||||
import androidx.compose.foundation.layout.fillMaxSize
|
||||
@@ -39,6 +39,7 @@ import androidx.compose.ui.text.style.TextOverflow
|
||||
import androidx.compose.ui.unit.dp
|
||||
import androidx.compose.ui.unit.sp
|
||||
import com.gorios.lanvoice.audio.AecAvailability
|
||||
import com.gorios.lanvoice.audio.AudioOutputGate
|
||||
import com.gorios.lanvoice.audio.VoicePhase
|
||||
import com.gorios.lanvoice.audio.VoiceSession
|
||||
import com.gorios.lanvoice.audio.VoiceUiState
|
||||
@@ -59,6 +60,8 @@ class MainActivity : ComponentActivity() {
|
||||
private var reportResult by mutableStateOf<String?>(null)
|
||||
private var appVersion = "unknown"
|
||||
private lateinit var session: VoiceSession
|
||||
private lateinit var audioOutput: AudioOutputGate
|
||||
private var shareFace by mutableStateOf(false)
|
||||
private var pendingStart = false
|
||||
private var expressionState by mutableStateOf(ExpressionUiState())
|
||||
private lateinit var expressions: ExpressionController
|
||||
@@ -82,6 +85,8 @@ class MainActivity : ComponentActivity() {
|
||||
override fun onCreate(savedInstanceState: Bundle?) {
|
||||
super.onCreate(savedInstanceState)
|
||||
appVersion = packageManager.getPackageInfo(packageName, 0).versionName ?: "unknown"
|
||||
volumeControlStream = AudioManager.STREAM_MUSIC
|
||||
audioOutput = AudioOutputGate(this) { session.outputUnavailable("播放被系统音频占用打断,请重新开始") }
|
||||
DebugLogUpload.appLaunch(
|
||||
appVersion,
|
||||
NetworkSecurityPolicy.getInstance().isCleartextTrafficPermitted("192.168.31.61"),
|
||||
@@ -90,12 +95,16 @@ class MainActivity : ComponentActivity() {
|
||||
getString(R.string.voice_server_host), resources.getInteger(R.integer.voice_server_port),
|
||||
onState = { state = it; startPendingVoice() },
|
||||
onConnectionLog = { connectionLogs = (connectionLogs + it).takeLast(10) },
|
||||
onPreparePlayback = audioOutput::prepare,
|
||||
onVoiceStopped = audioOutput::release,
|
||||
)
|
||||
expressions = ExpressionController(this, this) { expressionState = it }
|
||||
expressions = ExpressionController(this, this,
|
||||
onState = { expressionState = it }, onFaceCue = session::observeFace)
|
||||
setContent {
|
||||
Home(
|
||||
state, ::toggleVoice, session::interrupt, expressionState, ::toggleExpressions,
|
||||
connectionLogs, ::sendDiagnosticReport, reportSending, reportResult,
|
||||
shareFace, { enabled -> shareFace = enabled; session.setFaceSharing(enabled) },
|
||||
)
|
||||
}
|
||||
}
|
||||
@@ -196,6 +205,7 @@ fun Home(
|
||||
expressionState: ExpressionUiState, onToggleExpressions: () -> Unit,
|
||||
connectionLogs: List<String> = emptyList(),
|
||||
onSendReport: () -> Unit = {}, reportSending: Boolean = false, reportResult: String? = null,
|
||||
shareFace: Boolean = false, onShareFace: (Boolean) -> Unit = {},
|
||||
) {
|
||||
val gold = Color(0xFFE8C884)
|
||||
val muted = Color(0xFF9CA3AF)
|
||||
@@ -208,9 +218,13 @@ fun Home(
|
||||
delay(1_000L)
|
||||
}
|
||||
}
|
||||
Box(Modifier.fillMaxSize().background(Color(0xFF121220)).padding(24.dp)) {
|
||||
Column(
|
||||
modifier = Modifier.align(Alignment.TopCenter).padding(top = 24.dp),
|
||||
Modifier.fillMaxSize().background(Color(0xFF121220)).padding(24.dp).verticalScroll(rememberScrollState()),
|
||||
horizontalAlignment = Alignment.CenterHorizontally,
|
||||
verticalArrangement = Arrangement.SpaceBetween,
|
||||
) {
|
||||
Column(
|
||||
modifier = Modifier.padding(top = 12.dp),
|
||||
horizontalAlignment = Alignment.CenterHorizontally,
|
||||
) {
|
||||
Text(
|
||||
@@ -240,17 +254,10 @@ fun Home(
|
||||
modifier = Modifier.padding(top = 6.dp).heightIn(max = 54.dp).verticalScroll(logScroll),
|
||||
)
|
||||
}
|
||||
ExpressionControls(expressionState, onToggleExpressions)
|
||||
ExpressionControls(expressionState, onToggleExpressions, shareFace, onShareFace)
|
||||
}
|
||||
Column(
|
||||
modifier = Modifier.align(Alignment.Center).padding(bottom = 180.dp),
|
||||
horizontalAlignment = Alignment.CenterHorizontally,
|
||||
) {
|
||||
Text("声伴", color = gold, fontSize = 44.sp)
|
||||
Text("角色与音色由服务端决定", color = muted, modifier = Modifier.padding(top = 16.dp))
|
||||
}
|
||||
Column(
|
||||
modifier = Modifier.align(Alignment.BottomCenter).padding(bottom = 24.dp),
|
||||
modifier = Modifier.padding(top = 24.dp, bottom = 12.dp),
|
||||
horizontalAlignment = Alignment.CenterHorizontally,
|
||||
verticalArrangement = Arrangement.spacedBy(14.dp),
|
||||
) {
|
||||
|
||||
@@ -15,6 +15,11 @@ class AudioCapture {
|
||||
var recorder: AudioRecord? = null
|
||||
}
|
||||
|
||||
// A replacement run must not initialize a second microphone before the old
|
||||
// worker releases its AudioRecord/AEC (turn boundaries can arrive back-to-back).
|
||||
private val worker = java.util.concurrent.Executors.newSingleThreadExecutor { task ->
|
||||
Thread(task, "lan-voice-capture").apply { isDaemon = true }
|
||||
}
|
||||
private val lock = Any()
|
||||
private var current: Run? = null
|
||||
|
||||
@@ -32,10 +37,7 @@ class AudioCapture {
|
||||
stop()
|
||||
val run = Run()
|
||||
synchronized(lock) { current = run }
|
||||
Thread({ record(run, onFrame, onError, onDiagnostic) }, "lan-voice-capture").apply {
|
||||
isDaemon = true
|
||||
start()
|
||||
}
|
||||
worker.execute { if (run.active) record(run, onFrame, onError, onDiagnostic) }
|
||||
}
|
||||
|
||||
fun stop() {
|
||||
@@ -48,6 +50,11 @@ class AudioCapture {
|
||||
}
|
||||
}
|
||||
|
||||
fun release() {
|
||||
stop()
|
||||
worker.shutdown()
|
||||
}
|
||||
|
||||
private fun record(
|
||||
run: Run, onFrame: (ByteArray) -> Unit, onError: (Exception) -> Unit,
|
||||
onDiagnostic: (String) -> Unit,
|
||||
|
||||
@@ -0,0 +1,36 @@
|
||||
package com.gorios.lanvoice.audio
|
||||
|
||||
import android.content.Context
|
||||
import android.media.AudioAttributes
|
||||
import android.media.AudioFocusRequest
|
||||
import android.media.AudioManager
|
||||
import android.os.Handler
|
||||
import android.os.Looper
|
||||
|
||||
/** Respect system routing/volume; never silently raise volume or force a speaker during a call. */
|
||||
class AudioOutputGate(context: Context, onFocusLost: () -> Unit) {
|
||||
private val manager = context.getSystemService(AudioManager::class.java)
|
||||
private var held = false
|
||||
private val request = AudioFocusRequest.Builder(AudioManager.AUDIOFOCUS_GAIN_TRANSIENT)
|
||||
.setAudioAttributes(AudioAttributes.Builder().setUsage(AudioAttributes.USAGE_MEDIA)
|
||||
.setContentType(AudioAttributes.CONTENT_TYPE_SPEECH).build())
|
||||
.setAcceptsDelayedFocusGain(false)
|
||||
.setOnAudioFocusChangeListener({ change ->
|
||||
if (held && change in setOf(AudioManager.AUDIOFOCUS_LOSS, AudioManager.AUDIOFOCUS_LOSS_TRANSIENT)) {
|
||||
onFocusLost()
|
||||
}
|
||||
}, Handler(Looper.getMainLooper()))
|
||||
.build()
|
||||
|
||||
fun prepare(): String? {
|
||||
if (manager.getStreamVolume(AudioManager.STREAM_MUSIC) == 0 || manager.isStreamMute(AudioManager.STREAM_MUSIC)) {
|
||||
return "媒体音量为零,请调高手机媒体音量后重新开始"
|
||||
}
|
||||
if (!held) held = manager.requestAudioFocus(request) == AudioManager.AUDIOFOCUS_REQUEST_GRANTED
|
||||
return if (held) null else "系统暂未允许播放,请结束其他音频占用后重试"
|
||||
}
|
||||
|
||||
fun release() {
|
||||
if (held) { held = false; manager.abandonAudioFocusRequest(request) }
|
||||
}
|
||||
}
|
||||
@@ -4,6 +4,7 @@ import android.media.AudioAttributes
|
||||
import android.media.AudioFormat
|
||||
import android.media.AudioTrack
|
||||
import android.os.Process
|
||||
import android.os.SystemClock
|
||||
import com.gorios.lanvoice.net.DownlinkFrame
|
||||
import java.util.ArrayDeque
|
||||
|
||||
@@ -11,6 +12,7 @@ import java.util.ArrayDeque
|
||||
class AudioPlayback(
|
||||
private val onDrained: (turnId: Long, generation: Long) -> Unit,
|
||||
private val onError: (generation: Long, error: Exception) -> Unit,
|
||||
private val onProgress: (turnId: Long, generation: Long, message: String) -> Unit = { _, _, _ -> },
|
||||
) {
|
||||
private val lock = Object()
|
||||
private val queue = ArrayDeque<ByteArray>()
|
||||
@@ -20,6 +22,11 @@ class AudioPlayback(
|
||||
private var ended = false
|
||||
private var drained = false
|
||||
private var writtenSamples = 0L
|
||||
private var receivedFrames = 0L
|
||||
private var receivedBytes = 0L
|
||||
private var lastHead = 0L
|
||||
private var lastAdvanceMs = 0L
|
||||
private var lastReportMs = 0L
|
||||
private var track: AudioTrack? = null
|
||||
private var released = false
|
||||
|
||||
@@ -35,6 +42,8 @@ class AudioPlayback(
|
||||
if (released) return false
|
||||
if (turnId != frame.turnId) resetLocked(frame.turnId)
|
||||
if (ended || drained || queuedBytes + frame.pcm16.size > MAX_QUEUED_BYTES) return false
|
||||
receivedFrames++
|
||||
receivedBytes += frame.pcm16.size
|
||||
queue.addLast(frame.pcm16)
|
||||
queuedBytes += frame.pcm16.size
|
||||
lock.notifyAll()
|
||||
@@ -72,6 +81,11 @@ class AudioPlayback(
|
||||
queue.clear()
|
||||
queuedBytes = 0
|
||||
writtenSamples = 0
|
||||
receivedFrames = 0
|
||||
receivedBytes = 0
|
||||
lastHead = 0
|
||||
lastAdvanceMs = 0
|
||||
lastReportMs = 0
|
||||
track?.let {
|
||||
try { it.pause(); it.flush() } catch (_: IllegalStateException) { }
|
||||
}
|
||||
@@ -115,6 +129,19 @@ class AudioPlayback(
|
||||
}
|
||||
}
|
||||
|
||||
/** At most one numeric summary/second; a stalled native sink must not hang forever. */
|
||||
private fun progressLocked(id: Long, epoch: Long, device: AudioTrack, force: Boolean = false) {
|
||||
val now = SystemClock.elapsedRealtime()
|
||||
val head = device.playbackHeadPosition.toLong() and 0xffff_ffffL
|
||||
if (lastAdvanceMs == 0L || head != lastHead || writtenSamples <= head) lastAdvanceMs = now
|
||||
lastHead = head
|
||||
check(writtenSamples <= head || now - lastAdvanceMs < 10_000) { "AudioTrack playback head stalled" }
|
||||
if (force || now - lastReportMs >= 1_000 || lastReportMs == 0L) {
|
||||
lastReportMs = now
|
||||
onProgress(id, epoch, "frames=$receivedFrames bytes=$receivedBytes written=$writtenSamples head=$head queued=$queuedBytes underruns=${device.underrunCount} ended=$ended")
|
||||
}
|
||||
}
|
||||
|
||||
private fun play() {
|
||||
try {
|
||||
try { Process.setThreadPriority(Process.THREAD_PRIORITY_AUDIO) } catch (_: SecurityException) { }
|
||||
@@ -136,15 +163,24 @@ class AudioPlayback(
|
||||
if (chunk != null) {
|
||||
val device = acquireTrack(epoch) ?: continue
|
||||
var offset = 0
|
||||
var lastWriteMs = SystemClock.elapsedRealtime()
|
||||
while (offset < chunk.size) {
|
||||
val written = synchronized(lock) {
|
||||
if (released || generation != epoch) null else
|
||||
device.write(chunk, offset, chunk.size - offset, AudioTrack.WRITE_NON_BLOCKING)
|
||||
.also { if (it > 0) writtenSamples += it / 2 }
|
||||
.also {
|
||||
check(it <= chunk.size - offset && it % 2 == 0) { "Invalid AudioTrack write count" }
|
||||
if (it > 0) writtenSamples += it / 2
|
||||
progressLocked(id, epoch, device)
|
||||
}
|
||||
} ?: break
|
||||
check(written >= 0) { "AudioTrack write failed: $written" }
|
||||
offset += written
|
||||
if (written == 0) Thread.sleep(4)
|
||||
if (written > 0) lastWriteMs = SystemClock.elapsedRealtime()
|
||||
else {
|
||||
check(SystemClock.elapsedRealtime() - lastWriteMs < 10_000) { "AudioTrack write stalled" }
|
||||
Thread.sleep(4)
|
||||
}
|
||||
}
|
||||
} else {
|
||||
val finished = synchronized(lock) {
|
||||
@@ -161,9 +197,11 @@ class AudioPlayback(
|
||||
check(written >= 0) { "AudioTrack tail write failed: $written" }
|
||||
writtenSamples += written / 2
|
||||
}
|
||||
if (device != null) progressLocked(id, epoch, device)
|
||||
val played = device?.playbackHeadPosition?.toLong()?.and(0xffff_ffffL) ?: 0L
|
||||
val primed = device == null || writtenSamples == 0L || writtenSamples >= device.bufferSizeInFrames
|
||||
if (primed && played >= writtenSamples) {
|
||||
if (device != null) progressLocked(id, epoch, device, force = true)
|
||||
device?.pause()
|
||||
drained = true
|
||||
true
|
||||
|
||||
@@ -2,6 +2,7 @@ package com.gorios.lanvoice.audio
|
||||
|
||||
import android.os.Handler
|
||||
import android.os.Looper
|
||||
import android.os.SystemClock
|
||||
import android.util.Log
|
||||
import com.gorios.lanvoice.net.ConnectionStatus
|
||||
import com.gorios.lanvoice.net.DialogueClient
|
||||
@@ -9,6 +10,8 @@ import com.gorios.lanvoice.net.DebugLogUpload
|
||||
import com.gorios.lanvoice.net.DownlinkFrame
|
||||
import com.gorios.lanvoice.net.EventKind
|
||||
import com.gorios.lanvoice.net.ServerEvent
|
||||
import com.gorios.lanvoice.expression.FaceCue
|
||||
import com.gorios.lanvoice.expression.FaceCueObservation
|
||||
|
||||
enum class VoicePhase { IDLE, LISTENING, RECOGNIZING, THINKING, ANSWERING }
|
||||
|
||||
@@ -24,6 +27,8 @@ data class VoiceUiState(
|
||||
class VoiceSession(
|
||||
host: String, port: Int, private val onState: (VoiceUiState) -> Unit,
|
||||
private val onConnectionLog: (String) -> Unit = {},
|
||||
private val onPreparePlayback: () -> String? = { null },
|
||||
private val onVoiceStopped: () -> Unit = {},
|
||||
) {
|
||||
private val main = Handler(Looper.getMainLooper())
|
||||
private var state = VoiceUiState()
|
||||
@@ -37,11 +42,29 @@ class VoiceSession(
|
||||
private val retiredTurns = mutableSetOf<Long>()
|
||||
private var blockedTurn: Long? = null
|
||||
private var sequence = 1L
|
||||
private var preparedPlaybackTurn: Long? = null
|
||||
private var faceSharing = false
|
||||
private var faceSupported = false
|
||||
private var faceCue = FaceCueObservation()
|
||||
private var faceSent = false
|
||||
private val faceTick = object : Runnable {
|
||||
override fun run() {
|
||||
if (!faceSharing || released) return
|
||||
if (isActive() && faceSupported && hasTurn) {
|
||||
val age = SystemClock.elapsedRealtime() - faceCue.observedAtMs
|
||||
if (dialogue.sendFaceCue(currentTurn, faceCue, age)) {
|
||||
faceSent = faceCue.cue != FaceCue.UNKNOWN && age in 0..3_000
|
||||
}
|
||||
}
|
||||
main.postDelayed(this, 1_000L)
|
||||
}
|
||||
}
|
||||
private val capture = AudioCapture()
|
||||
private val playback: AudioPlayback = AudioPlayback(
|
||||
onDrained = { turn, epoch ->
|
||||
main.post {
|
||||
if (isActive() && playbackIsCurrent(turn, epoch) && blockedTurn != turn) {
|
||||
diagnostic("playback drained turn=$turn")
|
||||
if (dialogue.playbackDrained(turn)) {
|
||||
update(state.copy(phase = VoicePhase.LISTENING))
|
||||
startCapture()
|
||||
@@ -49,6 +72,11 @@ class VoiceSession(
|
||||
}
|
||||
}
|
||||
},
|
||||
onProgress = { turn, epoch, message ->
|
||||
main.post {
|
||||
if (playbackIsCurrent(turn, epoch)) diagnostic("playback turn=$turn $message")
|
||||
}
|
||||
},
|
||||
onError = { epoch, error ->
|
||||
main.post {
|
||||
if (isActive() && playbackIsCurrent(epoch)) failAudio("无法播放音频,请重新开始语音对话", error)
|
||||
@@ -83,6 +111,7 @@ class VoiceSession(
|
||||
|
||||
fun background(keepConnectionForPermission: Boolean = false, showDisconnectReason: Boolean = false) {
|
||||
checkMainThread()
|
||||
clearFaceContext()
|
||||
foreground = false
|
||||
stopVoice(sendControls = false)
|
||||
backgroundTimeout?.let { main.removeCallbacks(it) }
|
||||
@@ -109,6 +138,8 @@ class VoiceSession(
|
||||
if (released) return
|
||||
background()
|
||||
released = true
|
||||
main.removeCallbacks(faceTick)
|
||||
capture.release()
|
||||
playback.release()
|
||||
dialogue.release()
|
||||
}
|
||||
@@ -128,6 +159,9 @@ class VoiceSession(
|
||||
val wasActive = state.voiceActive
|
||||
stopCapture()
|
||||
playback.interrupt()
|
||||
preparedPlaybackTurn = null
|
||||
clearFaceContext()
|
||||
onVoiceStopped()
|
||||
blockedTurn = currentTurn
|
||||
update(state.copy(voiceActive = false, phase = VoicePhase.IDLE))
|
||||
if (sendControls && wasActive && state.connection == ConnectionStatus.CONNECTED) {
|
||||
@@ -152,9 +186,44 @@ class VoiceSession(
|
||||
update(state.copy(guidance = "麦克风权限未授予,请允许录音;若不再弹出申请,可在系统应用权限中开启。"))
|
||||
}
|
||||
|
||||
fun outputUnavailable(message: String) {
|
||||
checkMainThread()
|
||||
if (state.voiceActive) {
|
||||
stopVoice()
|
||||
update(state.copy(guidance = message))
|
||||
}
|
||||
}
|
||||
|
||||
fun setFaceSharing(enabled: Boolean) {
|
||||
checkMainThread()
|
||||
main.removeCallbacks(faceTick)
|
||||
if (!enabled) clearFaceContext()
|
||||
faceSharing = enabled
|
||||
if (enabled && !released) main.post(faceTick)
|
||||
}
|
||||
|
||||
fun observeFace(observation: FaceCueObservation) {
|
||||
checkMainThread()
|
||||
if (observation.cue == FaceCue.UNKNOWN) clearFaceContext()
|
||||
faceCue = observation
|
||||
}
|
||||
|
||||
private fun clearFaceContext() {
|
||||
if (faceSent && faceSupported && state.connection == ConnectionStatus.CONNECTED && hasTurn) {
|
||||
dialogue.sendFaceCue(currentTurn, FaceCueObservation(), 0)
|
||||
}
|
||||
faceSent = false
|
||||
faceCue = FaceCueObservation()
|
||||
}
|
||||
|
||||
private fun onConnection(connection: ConnectionStatus, reason: String) {
|
||||
diagnostic("connection ${state.connection.name} -> ${connection.name} reason=$reason", "connect")
|
||||
if (connection != ConnectionStatus.CONNECTED) {
|
||||
faceSupported = false
|
||||
faceSent = false
|
||||
faceCue = FaceCueObservation()
|
||||
preparedPlaybackTurn = null
|
||||
onVoiceStopped()
|
||||
stopCapture()
|
||||
playback.interrupt()
|
||||
currentTurn = 0
|
||||
@@ -177,13 +246,14 @@ class VoiceSession(
|
||||
if (!active || capturing) return
|
||||
capturing = true
|
||||
val epoch = ++captureEpoch
|
||||
val captureTurn = currentTurn
|
||||
diagnostic("capture start epoch=$epoch")
|
||||
try {
|
||||
capture.start(
|
||||
onFrame = { pcm ->
|
||||
main.post {
|
||||
if (epoch == captureEpoch && capturing && isActive()) {
|
||||
if (dialogue.sendAudio(pcm, currentTurn, sequence)) {
|
||||
if (epoch == captureEpoch && captureTurn == currentTurn && capturing && isActive()) {
|
||||
if (dialogue.sendAudio(pcm, captureTurn, sequence)) {
|
||||
sequence = (sequence + 1) and UINT32_MASK
|
||||
}
|
||||
}
|
||||
@@ -228,6 +298,7 @@ class VoiceSession(
|
||||
if (turn != null && !acceptTurn(turn)) return
|
||||
val action = event.payload.optString("state", "").ifBlank { event.type.substringAfter('.', "") }
|
||||
when (event.kind) {
|
||||
EventKind.HELLO -> faceSupported = event.payload.optInt("context_face_cue_version", 0) == 1
|
||||
EventKind.LISTEN -> {
|
||||
val active = isActive()
|
||||
diagnostic("LISTEN action=${if (action in setOf("start", "stop")) action else "other"} active=$active blockedTurn=$blockedTurn")
|
||||
@@ -241,6 +312,10 @@ class VoiceSession(
|
||||
stopCapture()
|
||||
update(state.copy(phase = VoicePhase.RECOGNIZING))
|
||||
}
|
||||
"resumed" -> {
|
||||
update(state.copy(phase = VoicePhase.LISTENING))
|
||||
startCapture()
|
||||
}
|
||||
}
|
||||
}
|
||||
EventKind.VAD -> if (isActive()) {
|
||||
@@ -255,15 +330,23 @@ class VoiceSession(
|
||||
update(state.copy(phase = VoicePhase.THINKING))
|
||||
}
|
||||
EventKind.TTS -> if (isActive() && blockedTurn != currentTurn) {
|
||||
playback.beginTurn(currentTurn)
|
||||
update(state.copy(phase = VoicePhase.ANSWERING))
|
||||
if (action in setOf("stop", "done", "end")) playback.endTurn(currentTurn)
|
||||
// The gateway sends start BEFORE LLM generation and also tts.metrics.
|
||||
// Only received PCM means there is an answer to play.
|
||||
when (action) {
|
||||
"start" -> playback.beginTurn(currentTurn)
|
||||
"stop", "done", "end" -> {
|
||||
if (preparedPlaybackTurn == currentTurn) playback.endTurn(currentTurn)
|
||||
else failAudio("本轮未收到可播放音频,请重新开始", IllegalStateException("TTS ended without accepted PCM"))
|
||||
}
|
||||
}
|
||||
}
|
||||
EventKind.ABORT -> {
|
||||
// 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 oldTurn
|
||||
val reason = event.payload.optString("reason")
|
||||
val listenReset = reason == "listen_start"
|
||||
val announcesNewTurn = reason in setOf("listen_start", "new_turn", "voice_barge_in", "client_abort")
|
||||
blockedTurn = if (announcesNewTurn) null else oldTurn
|
||||
diagnostic("ABORT blockedTurn=$blockedTurn active=${isActive()} listenReset=$listenReset oldTurn=$oldTurn currentTurn=$currentTurn")
|
||||
playback.interrupt()
|
||||
if (isActive()) {
|
||||
@@ -283,6 +366,11 @@ class VoiceSession(
|
||||
// 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
|
||||
if (preparedPlaybackTurn != frame.turnId) {
|
||||
val failure = onPreparePlayback()
|
||||
if (failure != null) { outputUnavailable(failure); return }
|
||||
preparedPlaybackTurn = frame.turnId
|
||||
}
|
||||
update(state.copy(phase = VoicePhase.ANSWERING))
|
||||
if (!playback.enqueue(frame)) {
|
||||
failAudio("播放中断,请重新开始语音对话", IllegalStateException("Playback queue rejected frame"))
|
||||
@@ -297,12 +385,16 @@ class VoiceSession(
|
||||
}
|
||||
// IDs identify turns; do not assume the server allocates them in numeric order.
|
||||
if (!hasTurn || id != currentTurn) {
|
||||
val resumeCapture = capturing
|
||||
if (resumeCapture) stopCapture() // Invalidate already queued PCM before resetting seq.
|
||||
if (hasTurn) retiredTurns.add(currentTurn)
|
||||
playback.interrupt()
|
||||
preparedPlaybackTurn = null
|
||||
currentTurn = id
|
||||
hasTurn = true
|
||||
sequence = 1
|
||||
if (blockedTurn != id) blockedTurn = null
|
||||
if (resumeCapture) startCapture()
|
||||
}
|
||||
if (logDecision) diagnostic("acceptTurn $before accepted=true nextTurn=$currentTurn nextBlocked=$blockedTurn retiredNow=${retiredTurns.size}")
|
||||
return true
|
||||
|
||||
@@ -22,11 +22,12 @@ import com.google.mediapipe.tasks.vision.facelandmarker.FaceLandmarker
|
||||
import java.util.concurrent.ExecutorService
|
||||
import java.util.concurrent.Executors
|
||||
|
||||
/** Independent local feature. It never references net/audio, writes user data or opens a network. */
|
||||
/** Local analyzer. Only enum observations leave this feature; images/coefficients never do. */
|
||||
class ExpressionController(
|
||||
context: Context,
|
||||
private val lifecycleOwner: LifecycleOwner,
|
||||
private val onState: (ExpressionUiState) -> Unit,
|
||||
private val onFaceCue: (FaceCueObservation) -> Unit = {},
|
||||
) {
|
||||
private class Run {
|
||||
@Volatile var active = true
|
||||
@@ -34,6 +35,7 @@ class ExpressionController(
|
||||
Thread(task, "lan-voice-expression").apply { isDaemon = true }
|
||||
}
|
||||
val rules = ExpressionRules()
|
||||
val faceRules = FaceCueRules()
|
||||
var landmarker: FaceLandmarker? = null // Accessed only on this run's executor.
|
||||
var analysis: ImageAnalysis? = null // Accessed only on main.
|
||||
var provider: ProcessCameraProvider? = null // Accessed only on main.
|
||||
@@ -65,7 +67,7 @@ class ExpressionController(
|
||||
val options = FaceLandmarker.FaceLandmarkerOptions.builder()
|
||||
.setBaseOptions(base) // Default delegate is CPU; no GPU/context requirements.
|
||||
.setRunningMode(RunningMode.VIDEO)
|
||||
.setNumFaces(1)
|
||||
.setNumFaces(2) // Multiple faces must produce unknown for dialogue context.
|
||||
.setMinFaceDetectionConfidence(.5f)
|
||||
.setMinFacePresenceConfidence(.5f)
|
||||
.setMinTrackingConfidence(.5f)
|
||||
@@ -85,12 +87,14 @@ class ExpressionController(
|
||||
fun stop() {
|
||||
checkMainThread()
|
||||
stopCurrent()
|
||||
onFaceCue(FaceCueObservation())
|
||||
if (!released) onState(ExpressionUiState())
|
||||
}
|
||||
|
||||
fun permissionDenied() {
|
||||
checkMainThread()
|
||||
stopCurrent()
|
||||
onFaceCue(FaceCueObservation())
|
||||
if (!released) onState(ExpressionUiState(guidance =
|
||||
"摄像头权限未授予。可在系统应用权限中开启,语音功能仍可使用。"))
|
||||
}
|
||||
@@ -98,6 +102,7 @@ class ExpressionController(
|
||||
fun release() {
|
||||
checkMainThread()
|
||||
if (released) return
|
||||
onFaceCue(FaceCueObservation())
|
||||
released = true
|
||||
stopCurrent()
|
||||
}
|
||||
@@ -159,6 +164,16 @@ class ExpressionController(
|
||||
FaceObservation(blendshapes, transform?.let(HeadPose::fromMatrix))
|
||||
}
|
||||
val visible = ExpressionRules.visible(run.rules.evaluate(observation, now))
|
||||
val landmarks = result.faceLandmarks().singleOrNull()
|
||||
val pose = observation?.pose
|
||||
// Conservative framing/pose checks, not a calibrated quality/confidence score.
|
||||
val quality = landmarks != null && landmarks.isNotEmpty() && pose != null &&
|
||||
kotlin.math.abs(pose.yaw) <= 30 && kotlin.math.abs(pose.pitch) <= 25 && kotlin.math.abs(pose.roll) <= 25 &&
|
||||
landmarks.all { it.x().isFinite() && it.y().isFinite() && it.x() in 0f..1f && it.y() in 0f..1f } &&
|
||||
(landmarks.maxOf { it.x() } - landmarks.minOf { it.x() }) *
|
||||
(landmarks.maxOf { it.y() } - landmarks.minOf { it.y() }) >= .06f
|
||||
val faceCue = run.faceRules.evaluate(observation, result.faceLandmarks().size, quality, now)
|
||||
main.post { if (isCurrent(run)) onFaceCue(faceCue) }
|
||||
// UI receives only <=2 enum labels; 52 coefficients, pose and images stay transient.
|
||||
if (run.lastPublished != visible) {
|
||||
run.lastPublished = visible
|
||||
@@ -183,6 +198,7 @@ class ExpressionController(
|
||||
main.post {
|
||||
if (!released && current === run) {
|
||||
stopCurrent()
|
||||
onFaceCue(FaceCueObservation())
|
||||
onState(ExpressionUiState(ExpressionStatus.UNAVAILABLE, guidance = guidance))
|
||||
}
|
||||
}
|
||||
@@ -209,6 +225,7 @@ class ExpressionController(
|
||||
} finally {
|
||||
run.landmarker = null
|
||||
run.rules.reset()
|
||||
run.faceRules.reset()
|
||||
run.lastPublished = null
|
||||
}
|
||||
}
|
||||
|
||||
@@ -8,6 +8,7 @@ import androidx.compose.foundation.layout.padding
|
||||
import androidx.compose.foundation.shape.RoundedCornerShape
|
||||
import androidx.compose.material3.Text
|
||||
import androidx.compose.material3.TextButton
|
||||
import androidx.compose.material3.Switch
|
||||
import androidx.compose.runtime.Composable
|
||||
import androidx.compose.ui.Alignment
|
||||
import androidx.compose.ui.Modifier
|
||||
@@ -17,7 +18,10 @@ import androidx.compose.ui.unit.dp
|
||||
import androidx.compose.ui.unit.sp
|
||||
|
||||
@Composable
|
||||
fun ExpressionControls(state: ExpressionUiState, onToggle: () -> Unit) {
|
||||
fun ExpressionControls(
|
||||
state: ExpressionUiState, onToggle: () -> Unit,
|
||||
shareFace: Boolean = false, onShareFace: (Boolean) -> Unit = {},
|
||||
) {
|
||||
val enabled = state.status == ExpressionStatus.STARTING || state.status == ExpressionStatus.ACTIVE
|
||||
Column(horizontalAlignment = Alignment.CenterHorizontally) {
|
||||
Row(horizontalArrangement = Arrangement.spacedBy(8.dp), verticalAlignment = Alignment.CenterVertically) {
|
||||
@@ -46,5 +50,12 @@ fun ExpressionControls(state: ExpressionUiState, onToggle: () -> Unit) {
|
||||
"表情线索仅供参考,不代表真实情绪",
|
||||
fontSize = 11.sp, color = Color(0xFF9CA3AF), textAlign = TextAlign.Center,
|
||||
)
|
||||
Row(verticalAlignment = Alignment.CenterVertically) {
|
||||
Text("将表情线索用于对话", color = Color(0xFF9CA3AF), fontSize = 12.sp)
|
||||
Switch(checked = shareFace, onCheckedChange = onShareFace)
|
||||
}
|
||||
if (shareFace && state.status != ExpressionStatus.ACTIVE) {
|
||||
Text("摄像头关闭时不发送线索", color = Color(0xFF9CA3AF), fontSize = 11.sp)
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
@@ -0,0 +1,45 @@
|
||||
package com.gorios.lanvoice.expression
|
||||
|
||||
enum class FaceCue(val wire: String) { UNKNOWN("unknown"), SMILING("smiling"), BROW_FURROWED("brow_furrowed") }
|
||||
|
||||
/** Rule intensity is an uncalibrated coefficient, never a probability or emotional state. */
|
||||
data class FaceCueObservation(
|
||||
val cue: FaceCue = FaceCue.UNKNOWN,
|
||||
val intensity: Float = 0f,
|
||||
val durationMs: Long = 0,
|
||||
val observedAtMs: Long = 0,
|
||||
)
|
||||
|
||||
class FaceCueRules {
|
||||
private var previous: Long? = null
|
||||
private var candidate = FaceCue.UNKNOWN
|
||||
private var since = 0L
|
||||
private var active = false
|
||||
|
||||
fun reset() { previous = null; candidate = FaceCue.UNKNOWN; active = false; since = 0 }
|
||||
|
||||
fun evaluate(observation: FaceObservation?, faceCount: Int, quality: Boolean, nowMs: Long): FaceCueObservation {
|
||||
val last = previous
|
||||
if (last != null && (nowMs <= last || nowMs - last > 500)) reset()
|
||||
previous = nowMs
|
||||
fun unknown(): FaceCueObservation {
|
||||
candidate = FaceCue.UNKNOWN; active = false; since = nowMs
|
||||
return FaceCueObservation(observedAtMs = nowMs)
|
||||
}
|
||||
if (faceCount != 1 || !quality || observation == null) return unknown()
|
||||
val names = listOf("mouthSmileLeft", "mouthSmileRight", "browDownLeft", "browDownRight")
|
||||
val scores = names.map { observation.blendshapes[it] ?: return unknown() }
|
||||
if (scores.any { !it.isFinite() || it !in 0f..1f }) return unknown()
|
||||
val smile = minOf(scores[0], scores[1])
|
||||
val brow = minOf(scores[2], scores[3])
|
||||
val smiling = smile >= if (active && candidate == FaceCue.SMILING) .60f else .75f
|
||||
val furrowed = brow >= if (active && candidate == FaceCue.BROW_FURROWED) .50f else .65f
|
||||
if (smiling == furrowed) return unknown() // Conflict or no clear cue.
|
||||
val next = if (smiling) FaceCue.SMILING else FaceCue.BROW_FURROWED
|
||||
if (candidate != next) { candidate = next; since = nowMs; active = false }
|
||||
val duration = (nowMs - since).coerceIn(0, 10_000)
|
||||
if (duration < 800) return FaceCueObservation(observedAtMs = nowMs)
|
||||
active = true
|
||||
return FaceCueObservation(next, if (smiling) smile else brow, duration, nowMs)
|
||||
}
|
||||
}
|
||||
@@ -25,6 +25,7 @@ import java.security.cert.CertificateException
|
||||
import java.util.concurrent.TimeUnit
|
||||
import javax.net.ssl.SSLException
|
||||
import javax.net.ssl.SSLPeerUnverifiedException
|
||||
import com.gorios.lanvoice.expression.FaceCueObservation
|
||||
|
||||
enum class ConnectionStatus { CONNECTING, CONNECTED, DISCONNECTED, BUSY }
|
||||
|
||||
@@ -215,6 +216,15 @@ class DialogueClient(
|
||||
|
||||
fun playbackDrained(turnId: Long): Boolean = send(DialogueProtocol.playbackDrained(turnId))
|
||||
|
||||
/** Optional context is best effort and never tears down the audio connection. */
|
||||
fun sendFaceCue(turnId: Long, observation: FaceCueObservation, ageMs: Long): Boolean {
|
||||
checkMainThread()
|
||||
val current = socket ?: return false
|
||||
if (!ready || released || current.queueSize() > 64 * 1024) return false
|
||||
return try { current.send(DialogueProtocol.faceCue(turnId, observation, ageMs)) }
|
||||
catch (_: Exception) { false }
|
||||
}
|
||||
|
||||
fun sendAudio(pcm16: ByteArray, turnId: Long, sequence: Long): Boolean {
|
||||
checkMainThread()
|
||||
val current = socket ?: return false
|
||||
|
||||
@@ -3,6 +3,8 @@ package com.gorios.lanvoice.net
|
||||
import org.json.JSONObject
|
||||
import java.nio.ByteBuffer
|
||||
import java.nio.ByteOrder
|
||||
import com.gorios.lanvoice.expression.FaceCue
|
||||
import com.gorios.lanvoice.expression.FaceCueObservation
|
||||
|
||||
/** Wire payloads stay intact: event-specific fields are consumed by later milestones. */
|
||||
data class ServerEvent(val type: String, val kind: EventKind, val payload: JSONObject)
|
||||
@@ -49,6 +51,17 @@ object DialogueProtocol {
|
||||
fun playbackDrained(turnId: Long): String = JSONObject()
|
||||
.put("type", "playback.drained").put("turn_id", turnId).toString()
|
||||
|
||||
fun faceCue(turnId: Long, observation: FaceCueObservation, ageMs: Long): String {
|
||||
require(turnId in 0..0xffff_ffffL)
|
||||
val valid = observation.cue != FaceCue.UNKNOWN && ageMs in 0..3_000 &&
|
||||
observation.intensity.isFinite() && observation.intensity in .5f..1f && observation.durationMs in 800..10_000
|
||||
return JSONObject().put("type", "context.face_cue").put("version", 1).put("turn_id", turnId)
|
||||
.put("valid", valid).put("cue", if (valid) observation.cue.wire else "unknown")
|
||||
.put("intensity", if (valid) observation.intensity.toDouble() else 0.0)
|
||||
.put("duration_ms", if (valid) observation.durationMs else 0)
|
||||
.put("age_ms", if (valid) ageMs else 0).toString()
|
||||
}
|
||||
|
||||
fun uplink(pcm16: ByteArray, turnId: Long, sequence: Long): ByteArray {
|
||||
require(pcm16.size == UPLINK_PCM_BYTES) { "Expected 20 ms of PCM16@16k" }
|
||||
require(turnId in 0..0xffff_ffffL && sequence in 0..0xffff_ffffL) {
|
||||
|
||||
@@ -0,0 +1,59 @@
|
||||
"""Versioned enum-only camera observations, scoped to a live socket/utterance. No images or text."""
|
||||
import math
|
||||
import time
|
||||
|
||||
TEMPLATE = (
|
||||
'本轮可选摄像头观察(可能误判,不是情绪识别):{cue},规则强度{intensity},持续约{duration}毫秒。'
|
||||
'只作为弱辅助信息,用户台词和聊天内容优先;冲突时忽略观察。'
|
||||
'微笑可能是礼貌或苦笑,皱眉可能是困惑,不能断言内心情绪、健康状况或危险等级。'
|
||||
'不做身份识别,不从闭眼推断疲劳或疾病,不必每句评论表情。'
|
||||
)
|
||||
|
||||
|
||||
class FaceContext:
|
||||
def __init__(self):
|
||||
self.value = None
|
||||
|
||||
def clear(self):
|
||||
self.value = None
|
||||
|
||||
def update(self, data, turn, now=None):
|
||||
self.clear() # Invalid observations must never leave an older cue latched.
|
||||
allowed = {'type', 'version', 'turn_id', 'valid', 'cue', 'intensity', 'duration_ms', 'age_ms'}
|
||||
if not isinstance(data, dict) or set(data) != allowed:
|
||||
return False
|
||||
if data['type'] != 'context.face_cue' or type(data['version']) is not int or data['version'] != 1:
|
||||
return False
|
||||
if type(data['turn_id']) is not int or not 0 <= data['turn_id'] <= 0xffffffff or data['turn_id'] != turn:
|
||||
return False
|
||||
if type(data['valid']) is not bool:
|
||||
return False
|
||||
age, duration, intensity = data['age_ms'], data['duration_ms'], data['intensity']
|
||||
if type(age) is not int or not 0 <= age <= 3000 or type(duration) is not int or not 0 <= duration <= 10000:
|
||||
return False
|
||||
if type(intensity) not in (int, float) or not math.isfinite(intensity) or not 0 <= intensity <= 1:
|
||||
return False
|
||||
if not data['valid']:
|
||||
return data['cue'] == 'unknown' and intensity == 0 and duration == 0
|
||||
if data['cue'] not in ('smiling', 'brow_furrowed') or duration < 800 or intensity < .5:
|
||||
return False
|
||||
self.value = (turn, data['cue'], intensity, duration, age, time.monotonic() if now is None else now)
|
||||
return True
|
||||
|
||||
def advance_capture(self, old_turn, new_turn):
|
||||
# new_turn names the response to the just-finished capture, not another utterance.
|
||||
if self.value and self.value[0] == old_turn:
|
||||
self.value = (new_turn, *self.value[1:])
|
||||
else:
|
||||
self.clear()
|
||||
|
||||
def take(self, turn, now=None):
|
||||
value, self.value = self.value, None
|
||||
if value is None or value[0] != turn:
|
||||
return None
|
||||
_, cue, intensity, duration, age, received = value
|
||||
elapsed = ((time.monotonic() if now is None else now) - received) * 1000
|
||||
if elapsed < 0 or age + round(elapsed, 6) > 3000:
|
||||
return None
|
||||
label = {'smiling': '明显、持续的嘴角上扬', 'brow_furrowed': '明显、持续的双侧眉头收紧'}[cue]
|
||||
return {'role': 'system', 'content': TEMPLATE.format(cue=label, intensity=round(intensity, 2), duration=duration)}
|
||||
@@ -0,0 +1 @@
|
||||
68a5c44661d44726456469d63d35ef245f51b0003894a02265f05db084659796
|
||||
@@ -0,0 +1,71 @@
|
||||
--- gateway.py
|
||||
+++ gateway.py
|
||||
@@ -20,0 +21 @@
|
||||
+from face_context import FaceContext
|
||||
@@ -166 +167 @@
|
||||
- if len(raw) > 65536: raise HTTPException(413)
|
||||
+ if len(raw) > 2097152: raise HTTPException(413)
|
||||
@@ -216,0 +218,3 @@
|
||||
+ self.face_context = FaceContext()
|
||||
+ self.face_messages = {}
|
||||
+ self.pending_drained = None
|
||||
@@ -252,0 +257 @@
|
||||
+ old_turn = self.turn
|
||||
@@ -253,0 +259,6 @@
|
||||
+ if reason == 'new_turn':
|
||||
+ self.face_context.advance_capture(old_turn, self.turn)
|
||||
+ else:
|
||||
+ self.face_context.clear()
|
||||
+ self.face_messages.clear()
|
||||
+ self.pending_drained = None
|
||||
@@ -364,0 +376,8 @@
|
||||
+ async def request_drained(self, turn):
|
||||
+ if turn != self.turn or not self.playback_waiting: return
|
||||
+ if self.task is not None and not self.task.done():
|
||||
+ # tts.stop may reach Android before history/debug finalization completes.
|
||||
+ self.pending_drained = turn
|
||||
+ else:
|
||||
+ await self.drained()
|
||||
+
|
||||
@@ -365,0 +385 @@
|
||||
+ self.pending_drained = None
|
||||
@@ -396 +416,8 @@
|
||||
- if not text: return
|
||||
+ if not text:
|
||||
+ self.face_context.clear()
|
||||
+ await self.event('listen', turn, state='resumed', mode=self.mode)
|
||||
+ return
|
||||
+ # Snapshot after ASR: no camera wait, no persistent/history context.
|
||||
+ face_message = self.face_context.take(turn)
|
||||
+ if face_message is not None: self.face_messages[turn] = [face_message]
|
||||
+ metrics['face_cue_used'] = face_message is not None
|
||||
@@ -422,0 +450 @@
|
||||
+ self.face_messages.pop(turn, None)
|
||||
@@ -431,0 +460,2 @@
|
||||
+ if turn == self.turn and not self.closed and self.pending_drained == turn:
|
||||
+ await self.drained()
|
||||
@@ -446 +476 @@
|
||||
- async with self.client.stream('POST', 'http://127.0.0.1:8888/v1/chat/completions', json={'model': 'qwen3.8-27b', 'messages': [{'role': 'system', 'content': '用简短中文直接回答,不输出思考过程、动作旁白、Markdown或JSON。最多两小句。' + self.persona_rules}] + self.contexts.get(turn, []) + [{'role': 'user', 'content': text}], 'max_tokens': 64, 'temperature': 0.3, 'stream': True, 'chat_template_kwargs': {'enable_thinking': False}}) as response:
|
||||
+ async with self.client.stream('POST', 'http://127.0.0.1:8888/v1/chat/completions', json={'model': 'qwen3.8-27b', 'messages': [{'role': 'system', 'content': '用简短中文直接回答,不输出思考过程、动作旁白、Markdown或JSON。最多两小句。' + self.persona_rules + ''.join('\n\n' + item['content'] for item in self.face_messages.get(turn, []))}] + self.contexts.get(turn, []) + [{'role': 'user', 'content': text}], 'max_tokens': 64, 'temperature': 0.3, 'stream': True, 'chat_template_kwargs': {'enable_thinking': False}}) as response:
|
||||
@@ -481,0 +512 @@
|
||||
+ if not full_text.strip(): raise ValueError('empty LLM body')
|
||||
@@ -557,0 +589 @@
|
||||
+ if not audio_bytes: raise ValueError('empty TTS PCM')
|
||||
@@ -573,0 +606 @@
|
||||
+ self.face_context.clear(); self.face_messages.clear()
|
||||
@@ -625 +658 @@
|
||||
- await session.event('hello', version=VERSION, codec='pcm16', sample_rate=16000, output_sample_rate=48000, channels=1, frame_duration=20, header_version=1, conversation_id=cid, duplex_default=True, voice_mode=voice_mode, voice_id=voice_id, voices=app.state.voices)
|
||||
+ await session.event('hello', context_face_cue_version=1, version=VERSION, codec='pcm16', sample_rate=16000, output_sample_rate=48000, channels=1, frame_duration=20, header_version=1, conversation_id=cid, duplex_default=True, voice_mode=voice_mode, voice_id=voice_id, voices=app.state.voices)
|
||||
@@ -639 +672,7 @@
|
||||
- if data.get('type') == 'debug':
|
||||
+ if not isinstance(data, dict): raise ValueError('control object')
|
||||
+ if data.get('type') == 'context.face_cue':
|
||||
+ if len(raw.encode('utf-8')) > 512:
|
||||
+ session.face_context.clear()
|
||||
+ else:
|
||||
+ session.face_context.update(data, session.turn)
|
||||
+ elif data.get('type') == 'debug':
|
||||
@@ -666,2 +705 @@
|
||||
- if data.get('turn_id') == session.turn and (session.task is None or session.task.done()):
|
||||
- await session.drained()
|
||||
+ await session.request_drained(data.get('turn_id'))
|
||||
@@ -0,0 +1,46 @@
|
||||
import unittest
|
||||
from face_context import FaceContext
|
||||
|
||||
|
||||
def cue(**changes):
|
||||
return dict({'type': 'context.face_cue', 'version': 1, 'turn_id': 1, 'valid': True,
|
||||
'cue': 'smiling', 'intensity': .8, 'duration_ms': 900, 'age_ms': 100}, **changes)
|
||||
|
||||
|
||||
class FaceContextTests(unittest.TestCase):
|
||||
def test_ttl_and_one_shot(self):
|
||||
state = FaceContext()
|
||||
self.assertTrue(state.update(cue(), 1, now=100))
|
||||
state.advance_capture(1, 2)
|
||||
self.assertEqual(state.take(2, now=102.9)['role'], 'system')
|
||||
self.assertIsNone(state.take(2, now=102.9))
|
||||
state.update(cue(), 1, now=100)
|
||||
self.assertIsNone(state.take(1, now=102.901))
|
||||
|
||||
def test_no_cue_is_no_message(self):
|
||||
state = FaceContext()
|
||||
self.assertIsNone(state.take(1))
|
||||
state.update(cue(), 1, now=10)
|
||||
state.clear()
|
||||
self.assertIsNone(state.take(1, now=10))
|
||||
|
||||
def test_whitelist_invalid_clears(self):
|
||||
for change in ({'cue':'angry'}, {'text':'untrusted prompt'}, {'intensity':float('nan')},
|
||||
{'intensity':True}, {'duration_ms':799}, {'age_ms':3001}, {'version':True},
|
||||
{'turn_id':2}, {'valid':'true'}, {'cue':'eyes_closed'}, {'landmarks':[]}):
|
||||
state = FaceContext()
|
||||
state.update(cue(), 1, now=1)
|
||||
self.assertFalse(state.update(cue(**change), 1, now=1))
|
||||
self.assertIsNone(state.take(1, now=1))
|
||||
|
||||
def test_unknown_clear_and_turn_scope(self):
|
||||
state = FaceContext()
|
||||
state.update(cue(), 1, now=1)
|
||||
self.assertTrue(state.update(cue(valid=False, cue='unknown', intensity=0, duration_ms=0), 1, now=1))
|
||||
self.assertIsNone(state.take(1, now=1))
|
||||
state.update(cue(), 1, now=1)
|
||||
self.assertIsNone(state.take(2, now=1))
|
||||
|
||||
|
||||
if __name__ == '__main__':
|
||||
unittest.main()
|
||||
@@ -0,0 +1,105 @@
|
||||
"""No live models/sockets: actual Dialogue + HTTP doubles, including drain/finalization race."""
|
||||
import asyncio
|
||||
import io
|
||||
import json
|
||||
import time
|
||||
import unittest
|
||||
import wave
|
||||
import httpx
|
||||
from gateway import Dialogue
|
||||
from tests_fake import FakeModel
|
||||
from test_gateway import Socket
|
||||
from test_face_context import cue
|
||||
|
||||
|
||||
def wav(pcm):
|
||||
out = io.BytesIO()
|
||||
with wave.open(out, 'wb') as file:
|
||||
file.setnchannels(1); file.setsampwidth(2); file.setframerate(48000); file.writeframes(pcm)
|
||||
return out.getvalue()
|
||||
|
||||
|
||||
class ReplyFaceTests(unittest.IsolatedAsyncioTestCase):
|
||||
async def round(self, observation=False, empty_llm=False, empty_tts=False, empty_stt=False):
|
||||
messages = []
|
||||
def backend(request):
|
||||
if 'transcriptions' in request.url.path:
|
||||
return httpx.Response(200, json={'text': '' if empty_stt else '公开合成测试'})
|
||||
if 'chat' in request.url.path:
|
||||
messages.append(json.loads(request.content)['messages'])
|
||||
# The actual deployed Qwen template accepts only one initial system.
|
||||
self.assertEqual(sum(m['role']=='system' for m in messages[-1]), 1)
|
||||
body = '' if empty_llm else '测试回答'
|
||||
return httpx.Response(200, text='data: '+json.dumps({'choices':[{'delta':{'content':body}}]})+'\n\ndata: [DONE]\n\n')
|
||||
return httpx.Response(200, content=wav(b'' if empty_tts else b'\x10\x01'*960))
|
||||
socket = Socket()
|
||||
async with httpx.AsyncClient(transport=httpx.MockTransport(backend)) as client:
|
||||
d = Dialogue(socket, FakeModel(), client)
|
||||
if observation:
|
||||
self.assertTrue(d.face_context.update(cue(turn_id=0), 0))
|
||||
await d.invalidate('new_turn')
|
||||
await d.run(d.turn, bytes(640))
|
||||
return d, socket, messages
|
||||
|
||||
async def test_optional_ephemeral_message(self):
|
||||
d, socket, messages = await self.round(observation=True)
|
||||
self.assertEqual([m['role'] for m in messages[0]], ['system','user'])
|
||||
self.assertIn('摄像头观察', messages[0][0]['content'])
|
||||
self.assertEqual(d.face_messages, {})
|
||||
self.assertIsNone(d.face_context.value)
|
||||
self.assertTrue(socket.frames)
|
||||
d, socket, messages = await self.round(observation=False)
|
||||
self.assertEqual([m['role'] for m in messages[0]], ['system','user'])
|
||||
self.assertNotIn('摄像头观察', messages[0][0]['content'])
|
||||
|
||||
async def test_expired_and_barge_clear(self):
|
||||
d = Dialogue(Socket(), FakeModel(), None)
|
||||
d.face_context.update(cue(turn_id=0),0,now=time.monotonic()-4)
|
||||
await d.invalidate('new_turn')
|
||||
self.assertIsNone(d.face_context.take(d.turn))
|
||||
for reason in ('listen_start','voice_barge_in','client_abort','history_new'):
|
||||
d.face_context.update(cue(turn_id=d.turn),d.turn)
|
||||
await d.invalidate(reason)
|
||||
self.assertIsNone(d.face_context.value)
|
||||
|
||||
async def test_empty_body_or_pcm_explicit_error(self):
|
||||
for options in ({'empty_llm':True}, {'empty_tts':True}):
|
||||
d, socket, _ = await self.round(**options)
|
||||
self.assertTrue(any(e['type']=='error' and e['code']=='backend_failed' for e in socket.events))
|
||||
self.assertFalse(socket.frames)
|
||||
|
||||
async def test_empty_stt_recovers_listening(self):
|
||||
d, socket, messages = await self.round(empty_stt=True)
|
||||
self.assertFalse(messages)
|
||||
self.assertTrue(any(e['type']=='listen' and e['state']=='resumed' for e in socket.events))
|
||||
|
||||
async def test_native_drain_during_history_finalize_not_lost(self):
|
||||
entered, finish = asyncio.Event(), asyncio.Event()
|
||||
class History:
|
||||
async def begin(self,*args): pass
|
||||
async def context(self,*args): return []
|
||||
async def rows(self,*args): return []
|
||||
async def finish(self,*args): entered.set(); await finish.wait()
|
||||
async def drained(self,*args): pass
|
||||
def backend(request):
|
||||
if 'transcriptions' in request.url.path: return httpx.Response(200,json={'text':'公开测试'})
|
||||
if 'chat' in request.url.path: return httpx.Response(200,text='data: {"choices":[{"delta":{"content":"回答"}}]}\n\ndata: [DONE]\n\n')
|
||||
return httpx.Response(200,content=wav(b'\x10\x01'*960))
|
||||
socket = Socket()
|
||||
async with httpx.AsyncClient(transport=httpx.MockTransport(backend)) as client:
|
||||
d=Dialogue(socket,FakeModel(),client,History(),'synthetic-conversation')
|
||||
d.run_id='synthetic-run'
|
||||
d.task=asyncio.create_task(d.run(0,bytes(640)))
|
||||
await asyncio.wait_for(entered.wait(),2)
|
||||
self.assertTrue(any(e['type']=='tts' and e.get('state')=='stop' for e in socket.events))
|
||||
await d.request_drained(0)
|
||||
self.assertEqual(d.pending_drained,0)
|
||||
finish.set()
|
||||
await asyncio.wait_for(d.task,2)
|
||||
self.assertFalse(d.playback_waiting)
|
||||
self.assertEqual(sum(e['type']=='listen' and e['state']=='resumed' for e in socket.events),1)
|
||||
await d.request_drained(0) # duplicate must not send another ack
|
||||
self.assertEqual(sum(e['type']=='listen' and e['state']=='resumed' for e in socket.events),1)
|
||||
|
||||
|
||||
if __name__ == '__main__': unittest.main()
|
||||
@@ -1,5 +1,7 @@
|
||||
# M5 表情线索
|
||||
|
||||
当前版本 0.4.0 已增加默认关闭的“将表情线索用于对话”开关,并以最多两脸检测排除多脸。下文保留 M5 独立阶段记录;当前对话规则、白名单协议、隐私与验收边界见 [VOICE_REPAIR_040.md](VOICE_REPAIR_040.md)。原本地标签与较严格的对话注入规则分别说明于两份文档。
|
||||
|
||||
版本:`0.2.0-m5`。这是独立的 `expression/` feature;不调用 net/ 或 audio/,不向服务端发送线索。摄像头默认关闭,只有用户点击并授予 CAMERA 权限后才加载模型、绑定前置摄像头。关闭、退后台或销毁时立即清除 analyzer 并解绑本 feature 的 ImageAnalysis;已在执行的 CPU 推理返回后丢弃结果,再安全关闭模型,避免阻塞语音/UI 线程。返回前台不自动开启。
|
||||
|
||||
CameraX 使用 `KEEP_ONLY_LATEST`、约 640×480 分辨率和最多 10Hz 分析。只绑定 ImageAnalysis,无预览、拍照或录制。MediaPipe Face Landmarker 使用 VIDEO 模式、单人脸、默认 CPU delegate,输出 52 个 blendshape 类别和脸部变换矩阵;矩阵在内存中转换为 yaw/pitch/roll。输入 RGBA 处理行/像素步长、裁剪与传感器旋转,不做自拍镜像。
|
||||
|
||||
@@ -189,3 +189,14 @@ APK 侧实现、编译及依赖校验元数据固化已完成。用户在外部
|
||||
- 改动文件:`expression/ExpressionController.kt`、`ExpressionRules.kt`、`ExpressionState.kt`、`ExpressionUi.kt`;MainActivity、Manifest、app/build.gradle;scripts/build.sh、prepare-expression.sh/.py、check-expression-rules.sh;tests/expression/ExpressionRulesCheck.kt;docs/EXPRESSION.md 及本实施记录。
|
||||
- 规则映射、采样限制、关闭行为、模型资源下载和外部构建步骤详见 `docs/EXPRESSION.md`。外部准备会生成 assets/face_landmarker.task、模型 SHA256 和具体依赖版本文件,再用 `--write-verification-metadata sha256` 固化依赖。
|
||||
- 有限验证:合成规则时间线、规则/state/Compose 控件独立编译、准备脚本合成输入和 shell/XML 检查通过;audio/ 文件 SHA256 确认不变。沙箱无法下载新依赖/模型,完整编译及真机运行仍需外部验收,不将源码检查当作 M5 APK 构建通过。
|
||||
|
||||
## 12. 0.4.0 回复链路修复与可选表情上下文(2026-10-11)
|
||||
|
||||
本次用户明确授权基于实际报告修复回复链路,并最小修改 gateway 接入表情辅助。历史已定决策与阶段记录保留;新增范围、协议、具体改动、前后数值证据及待验收边界见 [VOICE_REPAIR_040.md](VOICE_REPAIR_040.md)。
|
||||
|
||||
- Android 修复采集 turn/epoch/seq 和设备释放顺序、新 turn abort 语义、TTS/PCM/UI 阶段、输出焦点与零音量提示、AudioTrack 停滞保护与实际播放头完成;gateway 修复提前 drained 丢失及空输出。
|
||||
- 摄像头与“将表情线索用于对话”初始关闭;仅双侧明显稳定 smiling/brow_furrowed,有强度/持续/有效性、1Hz 刷新、3 秒 TTL、ASR 后单轮快照,固定片段合并原唯一 system,不上传图像或原始系数、不进历史,不新增模型/依赖。
|
||||
- 43 项 gateway 暂存测试、客户端设备 doubles 回归及完整源码编译检查通过。实际公开样本复验:STT14字、LLM24字、224帧/430080B/4.48秒非静音 PCM、drained ack;表情快照与非法枚举不关连接的断言通过。
|
||||
- 首次表情接入产生双 system 模板 HTTP400 回归;实际对比单 system HTTP200 后修复并复验通过。此回归与旧手机报告 1011 分开记录,原1011未复现/未归因,不能宣称根治;未做真机出声或真人有效回答验收。
|
||||
- 普通 workspace shell 使用 ./scripts/build.sh 构建成功;真实版本 0.4.0/code7,arm64,签名与上一版一致。APK artifacts/lan-voice-v040-arm64-debug.apk,31,433,233B,SHA256 5a6f88cb2f825dbcd5c7b8c1f212b369534bc53c49533e196fb5e9287902e934;现有 HTTP 下载校验一致。
|
||||
- agent 沙箱 socket/只读 Gradle 缓存限制未解除;受控部署、实链路与构建由本 workspace 普通 shell 执行。只重启网关以加载代码,未重启模型/其他服务,备份与回滚脚本已提供。
|
||||
|
||||
@@ -0,0 +1,99 @@
|
||||
# 0.4.0 回复链路修复与表情辅助上下文
|
||||
|
||||
2026-10-11;Android `versionName=0.4.0` / `versionCode=7`。本次用户授权修复 Android 与最小 gateway 改动,追加表情上下文。既有人格、default 音色、连续语音、config.xml 地址和证书保持原配置。没有新模型或依赖,没有重启模型容器或其他服务。
|
||||
|
||||
## 证据与归因边界
|
||||
|
||||
采证、部署、真实后端探测及构建均从本 Herdr workspace 发起,由普通 shell pane 执行指定脚本。agent 沙箱仍禁止 socket,基线 Gradle 缓存仍只读;没有绕过审批,也没有修改 `/home/ubuntu/android-build`。数值化证据保存在忽略的 `logs/voice-investigation/`,诊断报告、正文、音频和远端源码快照不提交。
|
||||
|
||||
读取的最新非空诊断来自 Xiaomi MI MAX 3 / API29 / App 0.3.3,报告时间戳 `1791719668916`。turn 11/15/16/17 有 `downlink started`;其中 15/16/17 的后端 TTS 元数据记录 completed,PCM 非零。此报告**不能支持“这些轮次均未生成/未收到 PCM”或“所有新轮均被 blockedTurn 丢弃”的结论**。旧报告没有数值化 AudioTrack 写入/播放头/路由/音量,不能据此证明手机有效出声。
|
||||
|
||||
turn 20:STT 在 `1791719664075`、LLM 在 `1791719664212` 起有事件,最后 LLM 事件 `1791719665001`,`1791719665096` 收到 1011;没有该轮下行 PCM。所读 journal/容器日志摘要没有足以归因的异常栈;本次前后短探测都未复现 1011。**1011 原因未定,不能宣称已根治,也不能将本次表情模板回归当成原 1011 的原因。**
|
||||
|
||||
通过实际协议/源码和回归可确定并已修复的缺陷:
|
||||
|
||||
| 缺陷 | 修复及验证 |
|
||||
|---|---|
|
||||
| 录音回调排到 main 后才取 currentTurn,切轮时重置 seq,但旧录音/半帧仍存活 | 每个采集 run 固定 turn + epoch;切轮作废旧回调/半帧,新轮 seq=1;单工作线程确保旧 AudioRecord/AEC 释放后再初始化下一设备。合成队列和慢释放测试覆盖。 |
|
||||
| invalidate 的 abort 携带**新** turn;若其他事件先宣布该轮,简单 oldTurn 仍可能等于新 turn | listen_start/new_turn/voice_barge_in/client_abort 均按“替换轮公告”处理,不封锁新轮;旧轮仍通过 retiredTurns 和播放代次拒绝。同轮普通 abort 仍阻止该轮。 |
|
||||
| gateway 在 LLM 前发 tts.start;客户端把 start、metrics、stop 都显示为回答开始 | 只有收到并接受 PCM 才切 ANSWERING;TTS start 只建队列,stop 只结束队列。完全没收到 PCM 的 stop 明确提示,空 STT resumed 恢复听取。 |
|
||||
| 原 gateway 仅在 task.done 时接受 drained,tts.stop 后历史/debug 收尾未完会丢确认 | 记 pending_drained,收尾完成后确认且去重;测试刻意阻塞 history.finish 并提前送 drained。 |
|
||||
| 系统媒体音量/焦点和 native sink 停滞无显式处理 | 使用媒体音量键、申请临时 speech 焦点;零音量/焦点拒绝给提示。AudioTrack 写入/播放头停滞 10 秒停止语音并提示;按秒记录帧/字节/写入样本/head/underruns,完成依据真实播放头。**这是防护与可验证性改进,未证明其为该手机原无声根因。** |
|
||||
| 空 LLM 或空 TTS 可静默走向结束 | gateway 明确 backend_failed,客户端结束当前语音并提示,不永久思考;HTTP doubles 覆盖两种空输出。 |
|
||||
|
||||
## 真实后端最小复验
|
||||
|
||||
同一现有公开短样本,16k mono PCM16,53760 samples(3.36 秒),20ms/640B 上行。未输出、保存聊天正文或样本音频;不压测,不强占 busy 会话。
|
||||
|
||||
| 指标 | 修复前(无表情) | 修复后(显式合成表情) |
|
||||
|---|---:|---:|
|
||||
| STT 字数 / STT 耗时 | 14 / 93.01ms | 14 / 73.34ms |
|
||||
| LLM 正文字数 / deltas | 30 / 16 | 24 / 13 |
|
||||
| capture→llm.finished | 2324.20ms | 1981.14ms |
|
||||
| TTS 请求数 / 首 PCM 耗时 | 1 / 197.23ms | 1 / 201.87ms |
|
||||
| 下行帧 / PCM 字节 | 280 / 537600 | 224 / 430080 |
|
||||
| PCM 秒数 / peak / RMS | 5.60 / 11601 / 1915.58 | 4.48 / 9972 / 1958.15 |
|
||||
| RTF / 最大 PCM chunk 到达间隔 | 1.0143 / 162.58ms | 1.0271 / 168.60ms |
|
||||
| drained 对应 listen.resumed | 是 | 是,结束后立即发送,不再人为等 100ms |
|
||||
| 表情快照 / 非法枚举不关闭连接 | 未启用 | face_cue_used=true / pong 返回 |
|
||||
|
||||
probe-after 的 turn=2;`llm.finished`、下行 seq 连续、非空 LLM、非静音 PCM、drained ack 都有断言。RTF 略大于 1,约实时供给,有短间隙;不能由此推出手机播放结果。**真实模型后端协议链路已通过;Android native 播放使用设备 doubles 测试;没有真机真人有效回答或听感验收。**
|
||||
|
||||
表情接入首次部署曾回归:STT 14 字,LLM/PCM 都为零,backend_failed。两次各 1-token 固定合成模板检查证明:双 system HTTP400(role/template error),合并单 system HTTP200。本次修复把固定辅助片段合并到原 system,新增单 system 回归断言;之后完整链路通过。失败数值保留于 `probe-after-previous.json`,与原手机 1011 分开记录。
|
||||
|
||||
## 表情开关与规则
|
||||
|
||||
摄像头和“将表情线索用于对话”每次启动都默认关闭、不持久化。先点“开启表情线索”并允许 CAMERA,再开启“将表情线索用于对话”,开始语音后才可能发送。仅开摄像头用于本地标签,不向网关发送;仅开分享但摄像头关闭也不发送有效线索。拒绝 CAMERA 不影响语音。UI 保留“表情线索仅供参考,不代表真实情绪”。
|
||||
|
||||
复用 CameraX/MediaPipe CPU,不上传图像/视频/landmarks/全 blendshapes,不身份识别,不记录系数。允许两脸检测以排除多脸;10Hz,KEEP_ONLY_LATEST。
|
||||
|
||||
| 对话线索 | 规则强度 | 进入 / 保持阈值 | 持续 |
|
||||
|---|---|---|---|
|
||||
| smiling | min(mouthSmileLeft, mouthSmileRight) | ≥0.75 / ≥0.60 | 连续 ≥800ms |
|
||||
| brow_furrowed | min(browDownLeft, browDownRight) | ≥0.65 / ≥0.50 | 连续 ≥800ms |
|
||||
| unknown | 不提供表情辅助 | 无脸、多脸、冲突、缺系数、非有限/越界、低质量、分析间隙 >500ms | 立即清除 |
|
||||
|
||||
保守质量门:单脸、有限且位于画面内的 landmarks、有效 pose、|yaw|≤30°、|pitch/roll|≤25°、人脸框面积≥画面 6%。这些是启发式,规则强度不是校准概率。眼动/头部/闭眼仅维持本地线索显示,**不作为情绪上下文**。没有单独情绪模型,不推断内心情绪、健康状况或危险等级。
|
||||
|
||||
## context.face_cue v1 协议
|
||||
|
||||
gateway hello 广告 `context_face_cue_version:1`;客户端仅在该能力明确存在、连接就绪、前台语音活动时发送,约每 1000ms 刷新;必要的失效变化立即清除。可选发送失败不重连、不终止语音。使用当前 socket 代次及 main 线程当前 turn;旧 camera run 回调被丢弃。
|
||||
|
||||
```json
|
||||
{"type":"context.face_cue","version":1,"turn_id":2,"valid":true,"cue":"smiling","intensity":0.8,"duration_ms":900,"age_ms":100}
|
||||
```
|
||||
|
||||
严格且完整的字段白名单;最大 512 UTF-8 字节。version=1;turn_id 是当前轮 uint32(不能 bool);valid 是 bool;cue 仅 smiling/brow_furrowed;强度有限 0..1(有效观察至少 .5);duration_ms 0..10000(有效观察至少 800);age_ms 0..3000。clear 使用 valid=false/cue=unknown/intensity=0/duration_ms=0。额外字段、非法枚举/类型/范围/过期数据清旧值,已识别的可选控制不因字段无效触发 unknown-control 1008。
|
||||
|
||||
网关保存 socket 内最近有效观察;`age_ms + 服务端 monotonic 接收后经过时间 ≤3000ms` 才有效,绝不直接相减跨机器时间。new_turn 表示刚结束采集的回答轮,观察随该次采集换号;其他 invalidation 清除。ASR 返回后、启动 LLM 前只取一次快照,不等待摄像头。模板只由白名单枚举映射固定中文片段,数值有界;合并到既有唯一 system,用户台词/历史/persona 保持原流程。片段声明观察可能误判、微笑可能礼貌/苦笑、皱眉可能困惑、内容优先且不必每句评论脸。
|
||||
|
||||
关闭分享、关闭摄像头、离开前台、停止语音、无脸/多脸/冲突/低质量时 clear;断线清本地与能力状态,服务器随 socket 销毁。失效清除尽力立即发送,网络不可用时仍受 3 秒 TTL 限制。已经提交的本轮 LLM 快照不会被追溯取消;下一轮不会复用过期观察。辅助 system 不写 history,不保存到 TTS debug,不占 4090 的额外推理。
|
||||
|
||||
## Backend 最小改动及操作
|
||||
|
||||
提交的是 `backend/gateway.patch`、原始基线 SHA256、纯 `face_context.py` 和新增测试,不是远端完整源码/配置。补丁包括:能力广告/控制白名单/TTL 快照/唯一 system 辅助片段、drained 收尾竞争、空输出错误、空 STT 恢复、诊断报告最大 body 从 64KiB 调到有界 2MiB(匹配现有最多 500×500 字符日志,不截断用户主动报告)。
|
||||
|
||||
`python3 scripts/deploy-gateway.py` 在临时目录跑 43 项 gateway/history/continuity/LAN/profile/persona/face 测试,不调用真实模型。`--apply` 先核对线上 gateway 哈希;仅接受原始基线或上一受控部署的精确哈希并验证基线备份。测试后再次核对并发修改和 busy,备份 gateway/face 文件后更新;只重启 `lan-voice-gateway.service` 并验证 health,启动失败恢复备份。模型、ASR/TTS/Qwen/4090 avatar 及其他服务不重启。
|
||||
|
||||
普通 workspace shell 操作(agent 沙箱不能代执行):
|
||||
|
||||
```bash
|
||||
python3 scripts/deploy-gateway.py --apply
|
||||
python3 scripts/probe-reply.py --after
|
||||
./scripts/package-release.sh
|
||||
```
|
||||
|
||||
必要时 `python3 scripts/rollback-gateway.py --initial` 恢复本次修改前网关;依旧核对精确线上哈希和 busy,只重启网关。回滚后能力不再广告,新 APK 自动停止发送可选上下文。原始备份 `.runtime/backups/voice-v040-20261011-203236`;最终部署前备份 `.runtime/backups/voice-v040-20261011-203752`。
|
||||
|
||||
## 验证与交付
|
||||
|
||||
- `python3 scripts/check-reply-regressions.py`:实际 DialogueClient/VoiceSession/AudioCapture/AudioPlayback/DialogueProtocol,配可控 Android/传输 doubles;没有真机。
|
||||
- `./scripts/check-expression-rules.sh`:原本地规则与新增持续/迟滞/无脸/多脸/冲突/质量测试。
|
||||
- `python3 -m unittest discover -s backend -p test_face_context.py`:纯 TTL/字段白名单/范围/一次性及清除检查。
|
||||
- gateway 暂存测试 43 项通过;真实短单轮复验通过。
|
||||
- 普通 shell `./scripts/build.sh`:BUILD SUCCESSFUL;aapt 实际 versionName0.4.0/code7、min26/target34、arm64-v8a;apksigner 验证 v2 debug 签名通过,证书与 v0.3.3 一致,可覆盖安装。没有新增依赖。
|
||||
- APK `artifacts/lan-voice-v040-arm64-debug.apk`,31,433,233 bytes。
|
||||
- SHA256 `5a6f88cb2f825dbcd5c7b8c1f212b369534bc53c49533e196fb5e9287902e934`;agent 本地重算一致。
|
||||
- 下载 <http://192.168.31.124:8080/lan-voice-v040-arm64-debug.apk>;普通 shell 下载字节哈希与归档相同。
|
||||
- 最终 gateway SHA256 `725577a378b688c24519ab2a0a9dfdb48723f365309e7ccccc9fc1de26c2894f`;face_context SHA256 `01abfc214ebb4e979faf9430166eccae9af37df911d36da5435f907769e7e31a`。
|
||||
- 尚未验收:MI MAX 3 真机实际出声/有效真人回答、音频焦点/路由/音量、真实光照及机型下表情规则、原 1011 的归因与复现。以上不以合成 PCM 或 backend 探测代替。
|
||||
@@ -0,0 +1,34 @@
|
||||
#!/usr/bin/env python3
|
||||
"""Two bounded 1-token synthetic requests isolate chat-template role compatibility. No voice/chat logs."""
|
||||
from pathlib import Path
|
||||
import json, subprocess
|
||||
REMOTE=r'''
|
||||
import json,httpx
|
||||
rows=[]
|
||||
base={'model':'qwen3.8-27b','max_tokens':1,'temperature':0,'stream':False,'chat_template_kwargs':{'enable_thinking':False}}
|
||||
with httpx.Client(timeout=15,trust_env=False) as client:
|
||||
for mode,messages in [
|
||||
('two_system',[{'role':'system','content':'简短回答。'},{'role':'system','content':'本轮可选摄像头观察可能误判,以用户台词为主。'},{'role':'user','content':'你好'}]),
|
||||
('merged_system',[{'role':'system','content':'简短回答。本轮可选摄像头观察可能误判,以用户台词为主。'},{'role':'user','content':'你好'}])]:
|
||||
response=client.post('http://127.0.0.1:8888/v1/chat/completions',json={**base,'messages':messages})
|
||||
text=response.text.lower()
|
||||
row={'mode':mode,'http_status':response.status_code,'body_chars':len(text),
|
||||
'role_or_template_error':any(x in text for x in ('system role','system message','roles must','chat template','conversation roles','only supports','alternat'))}
|
||||
# Fixed synthetic inputs only; errors are classified, never save response text.
|
||||
try:
|
||||
data=response.json()
|
||||
row['error_type']=str(data.get('error',{}).get('type',''))[:80]
|
||||
row['completion_tokens']=data.get('usage',{}).get('completion_tokens')
|
||||
except Exception: pass
|
||||
rows.append(row)
|
||||
print(json.dumps({'results':rows}))
|
||||
'''
|
||||
root=Path(__file__).resolve().parents[1]
|
||||
command=('cd /home/gorios-spark-2/lan-voice && if [ -x .venv/bin/python ]; then exec .venv/bin/python -; elif [ -x venv/bin/python ]; then exec venv/bin/python -; else exec python3 -; fi')
|
||||
r=subprocess.run(['ssh','-o','BatchMode=yes','-o','ConnectTimeout=5','gorios-spark-2@192.168.31.61',command],input=REMOTE.encode(),capture_output=True,timeout=45)
|
||||
if r.stdout:
|
||||
data=json.loads(r.stdout)
|
||||
(root/'logs/voice-investigation/backend-template.json').write_text(json.dumps(data,indent=2)+'\n')
|
||||
print(json.dumps(data))
|
||||
if r.stderr: print('Remote stderr present; no content printed.')
|
||||
raise SystemExit(r.returncode)
|
||||
@@ -27,6 +27,9 @@ with tempfile.TemporaryDirectory(prefix='lan-voice-expression-check-') as output
|
||||
subprocess.run([java, '-cp', compiler, 'org.jetbrains.kotlin.cli.jvm.K2JVMCompiler',
|
||||
'-no-stdlib', '-no-reflect', '-jvm-target', '17', '-classpath', stdlib, '-d', output,
|
||||
'app/src/main/java/com/gorios/lanvoice/expression/ExpressionRules.kt',
|
||||
'tests/expression/ExpressionRulesCheck.kt'], check=True)
|
||||
'app/src/main/java/com/gorios/lanvoice/expression/FaceCueRules.kt',
|
||||
'tests/expression/ExpressionRulesCheck.kt',
|
||||
'tests/expression/FaceCueRulesCheck.kt'], check=True)
|
||||
subprocess.run([java, '-cp', output + ':' + stdlib, 'ExpressionRulesCheckKt'], check=True)
|
||||
subprocess.run([java, '-cp', output + ':' + stdlib, 'FaceCueRulesCheckKt'], check=True)
|
||||
PY
|
||||
|
||||
@@ -0,0 +1,36 @@
|
||||
#!/usr/bin/env python3
|
||||
"""Real production coordinator/playback with deterministic device/transport doubles. No sockets."""
|
||||
from pathlib import Path
|
||||
import subprocess
|
||||
import tempfile
|
||||
|
||||
ROOT = Path(__file__).resolve().parents[1]
|
||||
CACHE = Path('/home/ubuntu/android-build/gradle-home/caches/modules-2/files-2.1')
|
||||
FALLBACK = Path('/tmp/lanvoice-gradle-home/caches/modules-2/files-2.1')
|
||||
JAVA = '/home/ubuntu/android-build/jdk/temurin-17.0.20.1/bin/java'
|
||||
|
||||
def jar(group, artifact, version):
|
||||
for base in (CACHE, FALLBACK):
|
||||
result = list((base/group/artifact/version).glob('*/*.jar'))
|
||||
if result: return str(result[0])
|
||||
raise RuntimeError(f'Missing cached {group}:{artifact}:{version}')
|
||||
|
||||
stdlib = jar('org.jetbrains.kotlin','kotlin-stdlib','2.0.20')
|
||||
compiler = ':'.join([jar('org.jetbrains.kotlin','kotlin-compiler-embeddable','2.0.20'), stdlib,
|
||||
jar('org.jetbrains.kotlin','kotlin-reflect','1.6.10'), jar('org.jetbrains.kotlin','kotlin-script-runtime','2.0.20'),
|
||||
jar('org.jetbrains.intellij.deps','trove4j','1.0.20200330'), jar('org.jetbrains','annotations','23.0.0'),
|
||||
str(next((CACHE/'org.jetbrains.kotlinx/kotlinx-coroutines-core-jvm').glob('*/*/*.jar')))])
|
||||
cp = ':'.join([stdlib, jar('com.squareup.okhttp3','okhttp','4.12.0'), jar('com.squareup.okio','okio-jvm','3.6.0')])
|
||||
source = ROOT/'app/src/main/java/com/gorios/lanvoice'
|
||||
suites = [
|
||||
('session','ConnectionCheckKt', [source/'audio/VoiceSession.kt', source/'net/DialogueClient.kt', source/'expression/FaceCueRules.kt', source/'expression/ExpressionRules.kt']),
|
||||
('playback','PlaybackCheckKt', [source/'audio/AudioPlayback.kt']),
|
||||
('capture','CaptureCheckKt', [source/'audio/AudioCapture.kt']),
|
||||
('protocol','ProtocolCheckKt', [source/'net/DialogueProtocol.kt', source/'expression/FaceCueRules.kt', source/'expression/ExpressionRules.kt']),
|
||||
]
|
||||
for name, main, real in suites:
|
||||
with tempfile.TemporaryDirectory(prefix=f'lan-voice-{name}-') as out:
|
||||
files = list((ROOT/'tests'/name).glob('*.kt')) + real
|
||||
subprocess.run([JAVA,'-cp',compiler,'org.jetbrains.kotlin.cli.jvm.K2JVMCompiler','-no-stdlib',
|
||||
'-no-reflect','-jvm-target','17','-nowarn','-classpath',cp,'-d',out, *map(str,files)],check=True,cwd=ROOT)
|
||||
subprocess.run([JAVA,'-cp',out+':'+cp,main],check=True,cwd=ROOT,timeout=30)
|
||||
@@ -0,0 +1,209 @@
|
||||
#!/usr/bin/env python3
|
||||
"""Run in this workspace's ordinary shell. Read-only remote inspection, no credentials/log bodies saved."""
|
||||
import io
|
||||
import json
|
||||
import os
|
||||
import re
|
||||
import ssl
|
||||
import subprocess
|
||||
import sys
|
||||
import tarfile
|
||||
import urllib.error
|
||||
import urllib.request
|
||||
from pathlib import Path
|
||||
|
||||
REMOTE_ROOT = Path('/home/gorios-spark-2/lan-voice')
|
||||
HOST = 'gorios-spark-2@192.168.31.61'
|
||||
SERVICE = re.compile(r'lan.?voice|gateway|stt|tts|qwen|vllm|asr|cosy', re.I)
|
||||
|
||||
|
||||
def command(args, cwd=None):
|
||||
try:
|
||||
result = subprocess.run(args, cwd=cwd, capture_output=True, timeout=20)
|
||||
return result.returncode, result.stdout.decode(errors='replace'), result.stderr.decode(errors='replace')
|
||||
except (OSError, subprocess.TimeoutExpired) as error:
|
||||
return -1, '', type(error).__name__
|
||||
|
||||
|
||||
def log_metadata(entry):
|
||||
if not isinstance(entry, dict):
|
||||
entry = {'message': str(entry)}
|
||||
msg = str(entry.get('msg', entry.get('message', entry.get('MESSAGE', ''))))
|
||||
# Do not print arbitrary messages, recognitions, prompts, completions or exception bodies.
|
||||
prefixes = ('onEvent', 'acceptTurn', 'ABORT', 'LISTEN', 'AudioRecord', 'startCapture',
|
||||
'capture start', 'connection', 'finish', 'ws', 'auth', 'hello', 'health',
|
||||
'state=', 'downlink', 'voice button', 'microphone', 'activity', 'session',
|
||||
'foreground', 'app_launch', 'send_report')
|
||||
event = next((p for p in prefixes if msg.startswith(p)), 'redacted')
|
||||
for phase in ('capture.end', 'llm.finished', 'tts.start', 'tts.stop', 'playback.drained',
|
||||
'ws open', 'hello received', 'hello sent', 'auth ok', 'ws closed', 'ws failure',
|
||||
'initialization ok', 'startRecording ok'):
|
||||
if phase in msg:
|
||||
event = phase
|
||||
break
|
||||
result = {'event': event}
|
||||
for key in ('ts', 'timestamp_ms', '__REALTIME_TIMESTAMP'):
|
||||
if str(entry.get(key, '')).isdigit():
|
||||
result[key] = int(entry[key])
|
||||
tag = entry.get('tag')
|
||||
if tag in ('connect', 'ws', 'auth', 'audio', 'error'):
|
||||
result['tag'] = tag
|
||||
numeric = r'turn_id|turn|oldTurn|currentTurn|nextTurn|blockedTurn|nextBlocked|id|seq|epoch|retired|retiredNow|frames|bytes|samples|duration_ms|elapsed_ms|latency_ms|rtf|status|code'
|
||||
for match in re.finditer(r'\b(' + numeric + r')=(-?\d+(?:\.\d+)?|null)\b', msg):
|
||||
result[match[1]] = match[2]
|
||||
for key in ('kind', 'state', 'phase', 'reason', 'active', 'capturing', 'hasTurn',
|
||||
'accepted', 'listenReset', 'released', 'permission', 'changingConfig'):
|
||||
match = re.search(r'\b' + key + r'=([A-Za-z_][A-Za-z_0-9:.-]{0,70}|true|false|null)\b', msg)
|
||||
if match:
|
||||
# Only structural identifiers; no arbitrary quoted/free-text values.
|
||||
result[key] = match[1]
|
||||
statuses = re.findall(r'\b(?:CONNECTED|DISCONNECTED|CONNECTING|BUSY)\b', msg)
|
||||
if statuses:
|
||||
result['connection_states'] = statuses
|
||||
code = re.search(r'\b(?:closed:|HTTP)\s*(\d{3,4})\b', msg)
|
||||
if code:
|
||||
result['http_or_close_code'] = int(code[1])
|
||||
result['exception_types'] = sorted(set(re.findall(r'\b[A-Z][A-Za-z]*(?:Exception|Error)\b', msg)))
|
||||
return result
|
||||
|
||||
|
||||
def items(value, keys):
|
||||
if isinstance(value, list):
|
||||
return value
|
||||
if isinstance(value, dict):
|
||||
for key in keys:
|
||||
if isinstance(value.get(key), list):
|
||||
return value[key]
|
||||
return [value] if isinstance(value, dict) else []
|
||||
|
||||
|
||||
def remote_evidence():
|
||||
ctx = ssl.create_default_context(cafile=str(REMOTE_ROOT / '.runtime/gateway-cert.pem'))
|
||||
opener = urllib.request.build_opener(urllib.request.ProxyHandler({}), urllib.request.HTTPSHandler(context=ctx))
|
||||
result = {}
|
||||
for endpoint in ('health', 'debug/report', 'debug/log'):
|
||||
try:
|
||||
with opener.open('https://192.168.31.61:5011/' + endpoint, timeout=5) as response:
|
||||
data = response.read(2_000_001)
|
||||
if len(data) > 2_000_000:
|
||||
raise ValueError('response exceeds bounded inspection size')
|
||||
data = json.loads(data)
|
||||
if endpoint == 'debug/report':
|
||||
reports = []
|
||||
for wrapped in items(data, ('reports', 'items', 'entries')):
|
||||
if not isinstance(wrapped, dict):
|
||||
continue
|
||||
report = wrapped.get('report', wrapped)
|
||||
if isinstance(report, dict) and report.get('logs'):
|
||||
reports.append(report)
|
||||
report = max(reports, key=lambda r: float(r.get('timestamp', 0)), default=None)
|
||||
if report:
|
||||
summary = {key: report.get(key) for key in ('timestamp', 'app_version', 'device',
|
||||
'android_api', 'connection', 'voice_active', 'phase', 'aec')}
|
||||
summary['logs'] = [log_metadata(e) for e in report['logs'][-500:]]
|
||||
result[endpoint] = summary
|
||||
else:
|
||||
result[endpoint] = {'nonempty_report_found': False, 'response_keys': list(data)[:20] if isinstance(data, dict) else []}
|
||||
elif endpoint == 'debug/log':
|
||||
result[endpoint] = [log_metadata(e) for e in items(data, ('logs', 'items', 'entries'))[-100:]]
|
||||
else:
|
||||
result[endpoint] = {key: data.get(key) for key in ('status', 'version', 'ok')}
|
||||
except Exception as error:
|
||||
result[endpoint] = {'error_type': type(error).__name__, 'http_status': getattr(error, 'code', None)}
|
||||
|
||||
code, status, _ = command(['docker', 'ps', '--format', '{{.Names}}\t{{.Status}}'])
|
||||
result['containers_status'] = [line for line in status.splitlines() if SERVICE.search(line)]
|
||||
result['docker_exit'] = code
|
||||
result['container_logs'] = {}
|
||||
for line in result['containers_status']:
|
||||
name = line.split('\t')[0]
|
||||
_, out, err = command(['docker', 'logs', '--since', '20m', '--tail', '150', name])
|
||||
result['container_logs'][name] = [log_metadata(s) for s in (out + err).splitlines()]
|
||||
result['systemd'] = []
|
||||
result['journal'] = {}
|
||||
for user in (False, True):
|
||||
prefix = ['systemctl'] + (['--user'] if user else [])
|
||||
_, out, _ = command(prefix + ['list-units', '--all', '--type=service', '--no-pager', '--no-legend', '--plain'])
|
||||
for line in out.splitlines():
|
||||
if not SERVICE.search(line):
|
||||
continue
|
||||
result['systemd'].append({'user': user, 'status': line.strip()})
|
||||
unit = line.strip().split()[0]
|
||||
_, journal, _ = command(['journalctl'] + (['--user'] if user else []) +
|
||||
['-u', unit, '--since', '-20min', '-n', '400', '--no-pager', '-o', 'json'])
|
||||
result['journal'][unit] = []
|
||||
for record in journal.splitlines():
|
||||
try:
|
||||
result['journal'][unit].append(log_metadata(json.loads(record)))
|
||||
except ValueError:
|
||||
pass
|
||||
print(json.dumps(result, ensure_ascii=False, indent=2))
|
||||
|
||||
|
||||
def remote_sources():
|
||||
# Deployment directories may have no tracked files. Inspect live source files,
|
||||
# with explicit exclusions, instead of assuming this is a populated Git checkout.
|
||||
paths = []
|
||||
excluded = {'models', 'data', 'assets', 'voices', 'lorebooks', 'node_modules',
|
||||
'venv', '__pycache__', 'logs', 'artifacts', 'build', 'dist'}
|
||||
for base, directories, files in os.walk(REMOTE_ROOT, followlinks=False):
|
||||
directories[:] = [d for d in directories if not d.startswith('.') and d not in excluded
|
||||
and not (Path(base) / d).is_symlink()]
|
||||
for name in files:
|
||||
if Path(name).suffix in ('.py', '.toml') or name == 'AGENTS.md':
|
||||
paths.append((Path(base) / name).relative_to(REMOTE_ROOT))
|
||||
if not paths:
|
||||
raise RuntimeError('no live gateway Python sources found')
|
||||
total = 0
|
||||
with tarfile.open(fileobj=sys.stdout.buffer, mode='w|gz') as archive:
|
||||
for relative in sorted(paths):
|
||||
path = Path(relative)
|
||||
if path.is_absolute() or '..' in path.parts or path.suffix not in ('.py', '.toml') and path.name != 'AGENTS.md':
|
||||
continue
|
||||
if any(part.startswith('.') or part in ('models', 'data', 'assets', 'voices', 'lorebooks') for part in path.parts):
|
||||
continue
|
||||
source = REMOTE_ROOT / path
|
||||
if source.is_symlink() or not source.is_file() or source.stat().st_size > 1_000_000:
|
||||
continue
|
||||
total += source.stat().st_size
|
||||
if total > 12_000_000:
|
||||
raise RuntimeError('gateway source snapshot exceeds 12MB')
|
||||
archive.add(source, arcname=relative, recursive=False)
|
||||
|
||||
|
||||
def local():
|
||||
root = Path(__file__).resolve().parents[1]
|
||||
output = root / 'logs/voice-investigation'
|
||||
output.mkdir(parents=True, exist_ok=True)
|
||||
source = Path(__file__).read_bytes()
|
||||
ssh = ['ssh', '-o', 'BatchMode=yes', '-o', 'ConnectTimeout=5', HOST, 'python3', '-']
|
||||
for mode in ('--remote-evidence', '--remote-sources'):
|
||||
result = subprocess.run(ssh + [mode], input=source, capture_output=True, timeout=180)
|
||||
if result.returncode:
|
||||
# SSH diagnostics contain no report, chat or credential bodies.
|
||||
print(result.stderr.decode(errors='replace')[-1000:], file=sys.stderr)
|
||||
raise SystemExit(result.returncode)
|
||||
if mode == '--remote-evidence':
|
||||
summary = json.loads(result.stdout)
|
||||
(output / 'evidence.json').write_text(json.dumps(summary, ensure_ascii=False, indent=2) + '\n')
|
||||
else:
|
||||
destination = output / 'backend-source'
|
||||
destination.mkdir(exist_ok=True)
|
||||
with tarfile.open(fileobj=io.BytesIO(result.stdout), mode='r:gz') as archive:
|
||||
for member in archive:
|
||||
path = Path(member.name)
|
||||
if not member.isfile() or path.is_absolute() or '..' in path.parts:
|
||||
raise RuntimeError('unsafe source archive entry')
|
||||
target = destination / path
|
||||
target.parent.mkdir(parents=True, exist_ok=True)
|
||||
target.write_bytes(archive.extractfile(member).read())
|
||||
print('Saved redacted evidence and gateway sources to logs/voice-investigation/ (git ignored).')
|
||||
|
||||
|
||||
if __name__ == '__main__':
|
||||
if '--remote-evidence' in sys.argv:
|
||||
remote_evidence()
|
||||
elif '--remote-sources' in sys.argv:
|
||||
remote_sources()
|
||||
else:
|
||||
local()
|
||||
@@ -0,0 +1,130 @@
|
||||
#!/usr/bin/env python3
|
||||
"""Controlled gateway-only deployment from this workspace; ordinary shell required for SSH.
|
||||
Default stages/tests only. --apply backs up and restarts ONLY lan-voice-gateway.service.
|
||||
"""
|
||||
import argparse
|
||||
import base64
|
||||
import hashlib
|
||||
import json
|
||||
from pathlib import Path
|
||||
import subprocess
|
||||
|
||||
REMOTE = r'''
|
||||
import base64, hashlib, io, json, os, shutil, ssl, subprocess, sys, tempfile, time, unittest, urllib.request
|
||||
from pathlib import Path
|
||||
ROOT = Path('/home/gorios-spark-2/lan-voice')
|
||||
UNIT = 'lan-voice-gateway.service'
|
||||
def health():
|
||||
ctx = ssl.create_default_context(cafile=str(ROOT/'.runtime/gateway-cert.pem'))
|
||||
opener=urllib.request.build_opener(urllib.request.ProxyHandler({}),urllib.request.HTTPSHandler(context=ctx))
|
||||
with opener.open('https://192.168.31.61:5011/health',timeout=3) as r: return json.load(r)
|
||||
def decode(name): return base64.b64decode(bundle[name])
|
||||
def atomic(path, content):
|
||||
tmp=path.with_name(path.name+'.v040.tmp')
|
||||
tmp.write_bytes(content); tmp.chmod(0o600); tmp.replace(path)
|
||||
original=(ROOT/'gateway.py').read_bytes()
|
||||
base_source = original
|
||||
if hashlib.sha256(original).hexdigest()!=base_hash:
|
||||
# A follow-up fix may replace only the exact version deployed by this script.
|
||||
if not previous or hashlib.sha256(original).hexdigest()!=previous.get('gateway_sha256'):
|
||||
raise RuntimeError('live_gateway_changed_refusing_patch')
|
||||
backup_source = Path(previous['backup']).resolve()
|
||||
if not backup_source.is_relative_to((ROOT/'.runtime/backups').resolve()):
|
||||
raise RuntimeError('invalid_backup_path')
|
||||
base_source = (backup_source/'gateway.py').read_bytes()
|
||||
if hashlib.sha256(base_source).hexdigest()!=base_hash:
|
||||
# A second follow-up backup contains a patched version. The immutable initial
|
||||
# base snapshot is saved separately by the workspace deployment record.
|
||||
initial = Path(previous.get('initial_backup', previous['backup'])).resolve()
|
||||
if not initial.is_relative_to((ROOT/'.runtime/backups').resolve()): raise RuntimeError('invalid_backup_path')
|
||||
base_source = (initial/'gateway.py').read_bytes()
|
||||
if hashlib.sha256(base_source).hexdigest()!=base_hash: raise RuntimeError('base_backup_mismatch')
|
||||
if apply and health().get('busy'): raise RuntimeError('gateway_busy_no_restart')
|
||||
with tempfile.TemporaryDirectory(prefix='voice-v040-stage-') as folder:
|
||||
stage=Path(folder)
|
||||
for path in ROOT.glob('*.py'): shutil.copy2(path,stage/path.name)
|
||||
shutil.copytree(ROOT/'tests',stage/'tests',ignore=shutil.ignore_patterns('__pycache__'))
|
||||
for name in ('web','personas'):
|
||||
if (ROOT/name).exists(): (stage/name).symlink_to(ROOT/name,target_is_directory=True)
|
||||
(stage/'.runtime').mkdir()
|
||||
if (ROOT/'.runtime/personas').exists(): (stage/'.runtime/personas').symlink_to(ROOT/'.runtime/personas',target_is_directory=True)
|
||||
# Only gateway.py is patched. The other production file is enum/TTL validation.
|
||||
(stage/'gateway.py').write_bytes(base_source)
|
||||
(stage/'gateway.patch').write_bytes(decode('gateway.patch'))
|
||||
subprocess.run(['patch','--batch','--fuzz=0','-p0','-i','gateway.patch'],cwd=stage,check=True,stdout=subprocess.PIPE,stderr=subprocess.PIPE)
|
||||
(stage/'face_context.py').write_bytes(decode('face_context.py'))
|
||||
for name in ('test_face_context.py','test_gateway_reply_face.py'): (stage/'tests'/name).write_bytes(decode(name))
|
||||
runner = """
|
||||
import sys,unittest
|
||||
sys.path[:0]=['.','tests']
|
||||
modules=['test_gateway','test_continuity','test_history','test_v08','test_debug','test_segmentation','test_guests','test_personas','test_face_context','test_gateway_reply_face']
|
||||
suite=unittest.TestSuite(unittest.defaultTestLoader.loadTestsFromName(name) for name in modules)
|
||||
result=unittest.TextTestRunner(verbosity=2).run(suite)
|
||||
raise SystemExit(not result.wasSuccessful())
|
||||
"""
|
||||
result=subprocess.run([sys.executable,'-c',runner],cwd=stage,stdout=subprocess.PIPE,stderr=subprocess.STDOUT,timeout=90)
|
||||
# Synthetic tests only. Never attach runtime reports, tokens, prompts or microphone audio.
|
||||
if result.returncode:
|
||||
print(json.dumps({'status':'tests_failed','test_output':result.stdout.decode(errors='replace')}))
|
||||
raise SystemExit(1)
|
||||
summary={'status':'tests_passed','test_output':result.stdout.decode(errors='replace'),'applied':False}
|
||||
patched=(stage/'gateway.py').read_bytes()
|
||||
if apply:
|
||||
# Recheck after staged tests: no overwriting concurrent edits or interrupting an active user.
|
||||
if (ROOT/'gateway.py').read_bytes()!=original: raise RuntimeError('gateway_changed_during_tests')
|
||||
if health().get('busy'): raise RuntimeError('gateway_busy_after_tests_no_restart')
|
||||
backup=ROOT/'.runtime/backups'/time.strftime('voice-v040-%Y%m%d-%H%M%S')
|
||||
backup.mkdir(parents=True,mode=0o700)
|
||||
existed={name:(ROOT/name).exists() for name in ('gateway.py','face_context.py')}
|
||||
for name,present in existed.items():
|
||||
if present: shutil.copy2(ROOT/name,backup/name)
|
||||
(backup/'manifest.json').write_text(json.dumps(existed)); (backup/'manifest.json').chmod(0o600)
|
||||
try:
|
||||
atomic(ROOT/'face_context.py',decode('face_context.py'))
|
||||
atomic(ROOT/'gateway.py',patched)
|
||||
subprocess.run(['systemctl','--user','restart',UNIT],check=True,timeout=30,stdout=subprocess.PIPE,stderr=subprocess.PIPE)
|
||||
healthy=False
|
||||
for attempt in range(15):
|
||||
try:
|
||||
if health().get('status')=='ok': healthy=True;break
|
||||
except Exception: pass
|
||||
time.sleep(1)
|
||||
if not healthy: raise RuntimeError('gateway_health_failed')
|
||||
except BaseException:
|
||||
for name,present in existed.items():
|
||||
if present: atomic(ROOT/name,(backup/name).read_bytes())
|
||||
elif (ROOT/name).exists(): (ROOT/name).unlink()
|
||||
subprocess.run(['systemctl','--user','restart',UNIT],timeout=30,stdout=subprocess.PIPE,stderr=subprocess.PIPE)
|
||||
raise
|
||||
summary.update(status='deployed',applied=True,initial_backup=previous.get('initial_backup', previous['backup']) if previous else str(backup),backup=str(backup),gateway_sha256=hashlib.sha256(patched).hexdigest(),face_context_sha256=hashlib.sha256(decode('face_context.py')).hexdigest(),health='ok')
|
||||
print(json.dumps(summary))
|
||||
'''
|
||||
|
||||
|
||||
def main():
|
||||
parser=argparse.ArgumentParser(description=__doc__)
|
||||
parser.add_argument('--apply',action='store_true')
|
||||
args=parser.parse_args()
|
||||
root=Path(__file__).resolve().parents[1]
|
||||
bundle={name:base64.b64encode((root/'backend'/name).read_bytes()).decode() for name in
|
||||
('gateway.patch','face_context.py','test_face_context.py','test_gateway_reply_face.py')}
|
||||
record=root/'logs/voice-investigation/gateway-deploy.json'
|
||||
previous=json.loads(record.read_text()) if record.exists() else None
|
||||
payload='previous='+repr(previous)+'\n'+'bundle='+repr(bundle)+'\nbase_hash='+repr((root/'backend/gateway-base.sha256').read_text().strip())+'\napply='+repr(args.apply)+'\n'+REMOTE
|
||||
remote=('cd /home/gorios-spark-2/lan-voice && '
|
||||
'if [ -x .venv/bin/python ]; then exec .venv/bin/python -; '
|
||||
'elif [ -x venv/bin/python ]; then exec venv/bin/python -; else exec python3 -; fi')
|
||||
result=subprocess.run(['ssh','-o','BatchMode=yes','-o','ConnectTimeout=5','gorios-spark-2@192.168.31.61',remote],input=payload.encode(),capture_output=True,timeout=180)
|
||||
directory=root/'logs/voice-investigation';directory.mkdir(parents=True,exist_ok=True)
|
||||
if result.stdout:
|
||||
data=json.loads(result.stdout)
|
||||
if args.apply and data.get('applied') and record.exists():
|
||||
(directory/'gateway-deploy-previous.json').write_bytes(record.read_bytes())
|
||||
name = ('gateway-deploy.json' if data.get('applied') else 'gateway-apply-failed.json') if args.apply else 'gateway-staged-tests.json'
|
||||
(directory/name).write_text(json.dumps(data,ensure_ascii=False,indent=2)+'\n')
|
||||
print(f'Gateway {data["status"]}; details saved under logs/voice-investigation/')
|
||||
if result.stderr: print('Remote execution stderr present; no raw payload printed.')
|
||||
raise SystemExit(result.returncode)
|
||||
|
||||
|
||||
if __name__=='__main__': main()
|
||||
Executable
+67
@@ -0,0 +1,67 @@
|
||||
#!/bin/bash
|
||||
# Approved author/remote; run in ordinary workspace shell because agent .git is read-only.
|
||||
set -euo pipefail
|
||||
cd "$(dirname "$0")/.."
|
||||
python3 - <<'PY'
|
||||
from pathlib import Path
|
||||
import hashlib,json
|
||||
root=Path.cwd(); logs=root/'logs/voice-investigation'
|
||||
release=json.loads((logs/'release.json').read_text())
|
||||
assert release['version_name']=='0.4.0' and release['version_code']==7
|
||||
assert hashlib.sha256((root/release['apk']).read_bytes()).hexdigest()==release['sha256']
|
||||
probe=json.loads((logs/'probe-after.json').read_text())
|
||||
assert probe['status']=='passed' and probe['llm_chars']>0 and probe['downlink_bytes']>0 and probe['drained_ack']
|
||||
assert probe['backend_metrics']['face_cue_used'] and probe['invalid_face_control_survived']
|
||||
deploy=json.loads((logs/'gateway-deploy.json').read_text())
|
||||
assert deploy['status']=='deployed' and 'Ran 43 tests' in deploy['test_output'] and '\nOK\n' in deploy['test_output']
|
||||
checks=(root/'logs/reply-regressions.log').read_text()
|
||||
assert 'PASS: typed enum-only face serialization' in checks and 'Traceback' not in checks and 'Exception in thread' not in checks
|
||||
PY
|
||||
if [ "$(git remote get-url origin)" != 'git@git.oops.school:heihei/baji-vc.git' ]; then
|
||||
echo 'Unexpected origin: refusing commit/push' >&2
|
||||
exit 1
|
||||
fi
|
||||
git diff --check
|
||||
git add -- .gitignore app/build.gradle \
|
||||
app/src/main/java/com/gorios/lanvoice/MainActivity.kt \
|
||||
app/src/main/java/com/gorios/lanvoice/audio/AudioCapture.kt \
|
||||
app/src/main/java/com/gorios/lanvoice/audio/AudioPlayback.kt \
|
||||
app/src/main/java/com/gorios/lanvoice/audio/AudioOutputGate.kt \
|
||||
app/src/main/java/com/gorios/lanvoice/audio/VoiceSession.kt \
|
||||
app/src/main/java/com/gorios/lanvoice/net/DialogueClient.kt \
|
||||
app/src/main/java/com/gorios/lanvoice/net/DialogueProtocol.kt \
|
||||
app/src/main/java/com/gorios/lanvoice/expression/ExpressionController.kt \
|
||||
app/src/main/java/com/gorios/lanvoice/expression/ExpressionUi.kt \
|
||||
app/src/main/java/com/gorios/lanvoice/expression/FaceCueRules.kt \
|
||||
docs/PLAN.md docs/EXPRESSION.md docs/VOICE_REPAIR_040.md \
|
||||
backend/face_context.py backend/gateway.patch backend/gateway-base.sha256 \
|
||||
backend/test_face_context.py backend/test_gateway_reply_face.py \
|
||||
scripts/collect-voice-evidence.py scripts/probe-reply.py scripts/check-backend-template.py \
|
||||
scripts/deploy-gateway.py scripts/rollback-gateway.py scripts/package-release.sh \
|
||||
scripts/check-expression-rules.sh scripts/check-reply-regressions.py scripts/finalize-release.sh \
|
||||
tests/capture tests/playback tests/session tests/protocol tests/expression/FaceCueRulesCheck.kt
|
||||
python3 - <<'PY'
|
||||
import subprocess
|
||||
paths=subprocess.check_output(['git','diff','--cached','--name-only'],text=True).splitlines()
|
||||
assert paths, 'Nothing staged'
|
||||
for path in paths:
|
||||
assert not path.startswith(('logs/','artifacts/','.runtime/','.aws/','.codex/')),path
|
||||
assert not path.endswith(('.pem','.key','.keystore','.apk','.pyc')),path
|
||||
content=subprocess.check_output(['git','diff','--cached','--no-ext-diff','--unified=0'],text=True)
|
||||
assert not any(('-----BEGIN ' + kind + '-----') in content for kind in ('PRIVATE KEY','OPENSSH PRIVATE KEY','RSA PRIVATE KEY'))
|
||||
print(f'Reviewed {len(paths)} staged source/test/doc files; no reports/APKs/keys staged')
|
||||
PY
|
||||
git diff --cached --check
|
||||
git -c user.name=zenord -c user.email=zenord@email.com commit -m 'fix: fence voice turns and playback; add opt-in face context'
|
||||
git push origin HEAD
|
||||
python3 - <<'PY'
|
||||
import json,subprocess
|
||||
from pathlib import Path
|
||||
commit=subprocess.check_output(['git','rev-parse','HEAD'],text=True).strip()
|
||||
branch=subprocess.check_output(['git','symbolic-ref','--short','HEAD'],text=True).strip()
|
||||
remote=subprocess.check_output(['git','ls-remote','origin','refs/heads/'+branch],text=True).split()[0]
|
||||
assert remote==commit, 'remote HEAD verification failed'
|
||||
result={'commit':commit,'branch':branch,'remote':'git@git.oops.school:heihei/baji-vc.git','push':'verified'}
|
||||
Path('logs/voice-investigation/git-release.json').write_text(json.dumps(result,indent=2)+'\n')
|
||||
print(json.dumps(result,indent=2))
|
||||
PY
|
||||
Executable
+46
@@ -0,0 +1,46 @@
|
||||
#!/bin/bash
|
||||
# Ordinary workspace shell: normal build entry, true package/signature checks, archive + HTTP check.
|
||||
set -euo pipefail
|
||||
cd "$(dirname "$0")/.."
|
||||
./scripts/build.sh
|
||||
source /home/ubuntu/android-build/env.sh
|
||||
TOOLS=/home/ubuntu/android-build/sdk/build-tools/34.0.0
|
||||
APK=app/build/outputs/apk/debug/app-debug.apk
|
||||
mkdir -p logs/voice-investigation artifacts
|
||||
"$TOOLS/aapt" dump badging "$APK" > logs/voice-investigation/release-badging.txt
|
||||
"$TOOLS/apksigner" verify --verbose --print-certs "$APK" > logs/voice-investigation/release-signature.txt
|
||||
python3 - <<'PY'
|
||||
import hashlib,json,re,shutil,urllib.request,subprocess
|
||||
from pathlib import Path
|
||||
root=Path.cwd()
|
||||
badging=(root/'logs/voice-investigation/release-badging.txt').read_text()
|
||||
assert "name='com.gorios.lanvoice'" in badging
|
||||
assert "versionCode='7'" in badging and "versionName='0.4.0'" in badging
|
||||
native=re.search(r'^native-code: (.+)$',badging,re.M)
|
||||
assert native and native[1].strip()=="'arm64-v8a'", 'unexpected ABI'
|
||||
source=root/'app/build/outputs/apk/debug/app-debug.apk'
|
||||
previous=root/'artifacts/lan-voice-v033-arm64-debug.apk'
|
||||
if previous.exists():
|
||||
old=subprocess.check_output(['/home/ubuntu/android-build/sdk/build-tools/34.0.0/apksigner','verify','--print-certs',str(previous)],text=True)
|
||||
new=(root/'logs/voice-investigation/release-signature.txt').read_text()
|
||||
pattern=r'Signer #1 certificate SHA-256 digest: (\w+)'
|
||||
assert re.search(pattern,old)[1]==re.search(pattern,new)[1], 'signing certificate changed: update install would fail'
|
||||
artifact=root/'artifacts/lan-voice-v040-arm64-debug.apk'
|
||||
shutil.copy2(source,artifact)
|
||||
digest=hashlib.sha256(artifact.read_bytes()).hexdigest()
|
||||
artifact.with_suffix('.apk.sha256').write_text(f'{digest} {artifact.name}\n')
|
||||
# Existing HTTP server root can be the workspace or artifacts; check the actual bytes.
|
||||
base='http://192.168.31.124:8080/'
|
||||
opener=urllib.request.build_opener(urllib.request.ProxyHandler({}))
|
||||
url=None
|
||||
for path in ('artifacts/'+artifact.name, artifact.name):
|
||||
try:
|
||||
with opener.open(base+path,timeout=15) as response:
|
||||
downloaded=hashlib.sha256(response.read()).hexdigest()
|
||||
if downloaded==digest: url=base+path;break
|
||||
except Exception: pass
|
||||
assert url is not None, 'APK built, but existing HTTP server did not serve matching bytes'
|
||||
result=dict(version_name='0.4.0',version_code=7,apk=str(artifact.relative_to(root)),bytes=artifact.stat().st_size,sha256=digest,url=url,signature='apksigner_verified',real_phone_playback='not_tested')
|
||||
(root/'logs/voice-investigation/release.json').write_text(json.dumps(result,indent=2)+'\n')
|
||||
print(json.dumps(result,indent=2))
|
||||
PY
|
||||
@@ -0,0 +1,176 @@
|
||||
#!/usr/bin/env python3
|
||||
"""One bounded public-sample round against live gateway. Run only in the workspace ordinary shell."""
|
||||
import json
|
||||
import subprocess
|
||||
from pathlib import Path
|
||||
|
||||
PROBE = r'''
|
||||
import asyncio, contextlib, io, json, math, re, ssl, struct, sys, time, urllib.request, wave
|
||||
from pathlib import Path
|
||||
ROOT = Path('/home/gorios-spark-2/lan-voice')
|
||||
sys.path.insert(0, str(ROOT))
|
||||
summary = {'test': 'one_public_sample_round', 'real_phone_playback': 'not_tested'}
|
||||
sanitize = helper['log_metadata']
|
||||
summary['tts_metadata'] = []
|
||||
for path in sorted((ROOT/'.runtime/tts-debug').glob('*/metadata.json'), key=lambda p:p.stat().st_mtime, reverse=True)[:20]:
|
||||
try:
|
||||
if path.stat().st_size > 1_000_000: continue
|
||||
data = json.loads(path.read_text())
|
||||
row = {key:data.get(key) for key in ('turn_id','created','status','samples','seconds','peak','rms','truncated','writer_error')}
|
||||
row['tts_requests'] = len(data.get('tts_requests',[]))
|
||||
row['tts_input_chars'] = [len(r.get('input','')) for r in data.get('tts_requests',[])]
|
||||
metrics = data.get('metrics',{})
|
||||
row['metrics'] = {key:metrics.get(key) for key in ('stt_ms','llm_first_body_ms','llm_finished_ms','tts_first_pcm_ms','capture_to_first_pcm_ms','total_ms','tts_request_count','face_cue_used')}
|
||||
row['segments'] = [{k:s.get(k) for k in ('audio_seconds','total_ms','rtf','pcm_chunks','first_pcm_ms','first_voiced_ms','max_chunk_interarrival_ms')} for s in metrics.get('tts_segments',[])]
|
||||
summary['tts_metadata'].append(row)
|
||||
except Exception as error:
|
||||
summary['tts_metadata'].append({'error_type':type(error).__name__})
|
||||
summary['runtime_logs'] = {}
|
||||
logpaths = list((ROOT/'.runtime').glob('*.log')) + list((ROOT/'logs').glob('*.log'))
|
||||
unit = Path.home()/'.config/systemd/user/lan-voice-gateway.service'
|
||||
if unit.exists():
|
||||
for line in unit.read_text().splitlines():
|
||||
if line.startswith(('StandardOutput=append:','StandardError=append:','StandardOutput=file:','StandardError=file:')):
|
||||
logpaths.append(Path(line.split(':',1)[1]))
|
||||
for path in dict.fromkeys(logpaths):
|
||||
if not path.is_file(): continue
|
||||
with path.open('rb') as stream:
|
||||
stream.seek(max(0,path.stat().st_size-131072))
|
||||
lines=stream.read().decode(errors='replace').splitlines()[-500:]
|
||||
rows=[]
|
||||
for line in lines:
|
||||
row=sanitize(line)
|
||||
trace=re.search(r'File "([^"\n]+)", line (\d+), in ([A-Za-z_0-9<>]+)',line)
|
||||
if trace: row['trace']={'file':trace[1], 'line':int(trace[2]), 'function':trace[3]}
|
||||
http=re.search(r'\b(POST|GET) (/v1/(?:chat/completions|audio/speech|audio/transcriptions))[^\n]*?\b([1-5]\d\d)\b',line)
|
||||
if http: row['backend_http']={'method':http[1],'path':http[2],'status':int(http[3])}
|
||||
if row.get('trace') or row.get('exception_types') or row.get('backend_http') or row['event']!='redacted': rows.append(row)
|
||||
summary['runtime_logs'][str(path)] = rows
|
||||
|
||||
async def probe():
|
||||
import websockets
|
||||
from protocol import pack, unpack
|
||||
ctx=ssl.create_default_context(cafile=str(ROOT/'.runtime/gateway-cert.pem'))
|
||||
opener=urllib.request.build_opener(urllib.request.ProxyHandler({}),urllib.request.HTTPSHandler(context=ctx))
|
||||
with opener.open('https://192.168.31.61:5011/health',timeout=5) as response: health=json.load(response)
|
||||
if health.get('busy'): raise RuntimeError('gateway_busy_probe_not_started')
|
||||
sample=ROOT/'tmp/public_tts_16k.wav'
|
||||
with wave.open(str(sample),'rb') as audio:
|
||||
assert (audio.getframerate(),audio.getnchannels(),audio.getsampwidth())==(16000,1,2)
|
||||
assert audio.getnframes() <= 16000*15, 'public sample exceeds 15s bound'
|
||||
pcm=audio.readframes(audio.getnframes())
|
||||
summary['input_samples']=len(pcm)//2
|
||||
started=time.perf_counter()
|
||||
summary.update(events={},llm_chars=0,llm_deltas=0,downlink_frames=0,downlink_bytes=0,pcm_peak=0,pcm_square=0,drained_ack=False)
|
||||
def stamp(name): summary.setdefault(name,round((time.perf_counter()-started)*1000,2))
|
||||
kwargs=dict(ssl=ctx,origin='https://192.168.31.61:5011',open_timeout=5,close_timeout=2)
|
||||
# The deployed websockets version accepts proxy=None; avoid any system proxy.
|
||||
if 'proxy' in __import__('inspect').signature(websockets.connect).parameters: kwargs['proxy']=None
|
||||
async with websockets.connect('wss://192.168.31.61:5011/ws/dialogue',**kwargs) as ws:
|
||||
auth=json.loads(await asyncio.wait_for(ws.recv(),5)); assert auth['type']=='auth' and auth.get('state')=='ok'
|
||||
await ws.send(json.dumps({'type':'hello','codec':'pcm16','sample_rate':16000,'frame_duration':20,'persona':'default','voice_mode':'continuous_voice','tts_debug':False}))
|
||||
while True:
|
||||
event=json.loads(await asyncio.wait_for(ws.recv(),5))
|
||||
if event['type']=='hello': break
|
||||
summary['face_context_supported']=event.get('context_face_cue_version')
|
||||
if after: assert summary['face_context_supported']==1, 'face protocol not advertised'
|
||||
await ws.send(json.dumps({'type':'listen','mode':'manual','state':'start','barge_in':False}))
|
||||
while True:
|
||||
event=json.loads(await asyncio.wait_for(ws.recv(),5))
|
||||
if event['type']=='listen' and event.get('state')=='start': turn=event['turn_id']; break
|
||||
for offset in range(0,len(pcm),640):
|
||||
chunk=pcm[offset:offset+640]
|
||||
if len(chunk)<640: chunk += bytes(640-len(chunk))
|
||||
await ws.send(pack(1,turn,offset//640+1,chunk))
|
||||
await asyncio.sleep(.02)
|
||||
if after:
|
||||
cue={'type':'context.face_cue','version':1,'turn_id':turn,'valid':True,'cue':'smiling','intensity':.8,'duration_ms':900,'age_ms':0}
|
||||
# Explicit synthetic observation: never represents the user's face.
|
||||
await ws.send(json.dumps(cue))
|
||||
summary['synthetic_face_context_sent']=True
|
||||
await ws.send(json.dumps({'type':'listen','mode':'manual','state':'stop'}))
|
||||
stamp('input_end_ms')
|
||||
last_seq=0; stopped=False
|
||||
async with asyncio.timeout(60):
|
||||
while True:
|
||||
raw=await ws.recv()
|
||||
if isinstance(raw,bytes):
|
||||
actual,seq,audio=unpack(raw,2)
|
||||
assert actual==turn and seq==last_seq+1 and 0<len(audio)<=1920
|
||||
last_seq=seq; summary['downlink_frames']+=1;summary['downlink_bytes']+=len(audio)
|
||||
samples=struct.unpack('<'+'h'*(len(audio)//2),audio)
|
||||
summary['pcm_peak']=max(summary['pcm_peak'],max(map(abs,samples),default=0))
|
||||
summary['pcm_square']+=sum(x*x for x in samples)
|
||||
stamp('first_pcm_ms')
|
||||
continue
|
||||
event=json.loads(raw);kind=event.get('type','unknown')
|
||||
summary['events'][kind]=summary['events'].get(kind,0)+1
|
||||
if kind=='abort': turn=event['turn_id'];last_seq=0
|
||||
if kind=='capture.end': stamp('capture_end_ms');summary['turn']=turn
|
||||
if kind=='stt': summary['stt_chars']=len(event.get('text',''));stamp('stt_ms')
|
||||
if kind=='llm':
|
||||
summary['llm_chars']+=len(event.get('text',''));summary['llm_deltas']+=1;stamp('first_llm_ms')
|
||||
if kind=='llm.finished': stamp('llm_finished_ms')
|
||||
if kind=='voice.metrics': summary['tts_requests']=event.get('tts_request_count')
|
||||
if kind=='metrics':
|
||||
values=event.get('values',{})
|
||||
summary['backend_metrics']={key:values.get(key) for key in ('stt_ms','llm_finished_ms','tts_first_pcm_ms','total_ms','tts_request_count','face_cue_used')}
|
||||
summary['segments']=[{key:s.get(key) for key in ('audio_seconds','total_ms','rtf','max_chunk_interarrival_ms')} for s in values.get('tts_segments',[])]
|
||||
if kind=='error': raise RuntimeError('gateway_backend_error')
|
||||
if kind=='tts' and event.get('state')=='stop':
|
||||
stopped=True; stamp('tts_stop_ms')
|
||||
assert summary.get('stt_chars',0)>0 and summary['llm_chars']>0 and summary['downlink_frames']>0
|
||||
# Model native drain is tested separately; this probe only confirms protocol ack.
|
||||
await ws.send(json.dumps({'type':'playback.drained','turn_id':turn}))
|
||||
if stopped and kind=='listen' and event.get('state')=='resumed':
|
||||
summary['drained_ack']=True;stamp('drained_ack_ms');break
|
||||
if after:
|
||||
assert summary['backend_metrics'].get('face_cue_used') is True, 'ASR-time face snapshot missing'
|
||||
await ws.send(json.dumps({'type':'context.face_cue','version':1,'turn_id':turn,'valid':False,'cue':'unknown','intensity':0,'duration_ms':0,'age_ms':0}))
|
||||
await ws.send(json.dumps({'type':'context.face_cue','version':1,'turn_id':turn,'valid':True,'cue':'gaze_left','intensity':.8,'duration_ms':900,'age_ms':0}))
|
||||
# A whitelisted control with invalid fields clears context; it must not close 1008.
|
||||
await ws.send(json.dumps({'type':'ping'}))
|
||||
while json.loads(await asyncio.wait_for(ws.recv(),5)).get('type')!='pong': pass
|
||||
summary['invalid_face_control_survived']=True
|
||||
assert summary['pcm_peak']>327, 'no voiced PCM amplitude'
|
||||
summary['pcm_rms']=round(math.sqrt(summary.pop('pcm_square')/(summary['downlink_bytes']//2)),2)
|
||||
summary['status']='passed'
|
||||
try:
|
||||
asyncio.run(probe())
|
||||
except Exception as error:
|
||||
summary['status']='failed'; summary['error_type']=type(error).__name__
|
||||
summary['close_code']=getattr(error,'code',None)
|
||||
summary.pop('pcm_square',None)
|
||||
print(json.dumps(summary,ensure_ascii=False,indent=2))
|
||||
raise SystemExit(0 if summary['status']=='passed' else 1)
|
||||
'''
|
||||
|
||||
|
||||
def main():
|
||||
root = Path(__file__).resolve().parents[1]
|
||||
collector = (root / 'scripts/collect-voice-evidence.py').read_text()
|
||||
payload = "after=" + repr('--after' in __import__('sys').argv) + "\nhelper={'__name__':'collector_library'}\nexec(" + repr(collector) + ",helper)\n" + PROBE
|
||||
# Use the existing gateway venv if present; never install packages or load a new model.
|
||||
remote = ('cd /home/gorios-spark-2/lan-voice && '
|
||||
'if [ -x .venv/bin/python ]; then exec .venv/bin/python -; '
|
||||
'elif [ -x venv/bin/python ]; then exec venv/bin/python -; else exec python3 -; fi')
|
||||
result = subprocess.run(['ssh', '-o', 'BatchMode=yes', '-o', 'ConnectTimeout=5',
|
||||
'gorios-spark-2@192.168.31.61', remote],
|
||||
input=payload.encode(), capture_output=True, timeout=100)
|
||||
output = root / 'logs/voice-investigation'
|
||||
output.mkdir(parents=True, exist_ok=True)
|
||||
if result.stdout:
|
||||
data = json.loads(result.stdout)
|
||||
target = output / ('probe-after.json' if '--after' in __import__('sys').argv else 'probe-before.json')
|
||||
if target.exists() and '--after' in __import__('sys').argv:
|
||||
(output/'probe-after-previous.json').write_bytes(target.read_bytes())
|
||||
target.write_text(json.dumps(data, ensure_ascii=False, indent=2) + '\n')
|
||||
print(f'Saved redacted numeric probe results: {target.relative_to(root)}; status={data.get("status")}')
|
||||
if result.stderr:
|
||||
# Remote script emits no payloads. Avoid printing unexpected tracebacks/raw server errors.
|
||||
print('Remote stderr present; inspect script/environment (no content printed).')
|
||||
raise SystemExit(result.returncode)
|
||||
|
||||
|
||||
if __name__ == '__main__':
|
||||
main()
|
||||
@@ -0,0 +1,42 @@
|
||||
#!/usr/bin/env python3
|
||||
"""Restore exact gateway files from the last controlled backup; ordinary shell required."""
|
||||
import json, subprocess, sys
|
||||
from pathlib import Path
|
||||
REMOTE=r'''
|
||||
import hashlib,json,ssl,subprocess,time,urllib.request
|
||||
from pathlib import Path
|
||||
root=Path('/home/gorios-spark-2/lan-voice')
|
||||
backup=Path(record['backup']).resolve()
|
||||
assert backup.is_relative_to((root/'.runtime/backups').resolve())
|
||||
assert hashlib.sha256((root/'gateway.py').read_bytes()).hexdigest()==record['gateway_sha256'], 'concurrent change: refusing rollback'
|
||||
ctx=ssl.create_default_context(cafile=str(root/'.runtime/gateway-cert.pem'))
|
||||
opener=urllib.request.build_opener(urllib.request.ProxyHandler({}),urllib.request.HTTPSHandler(context=ctx))
|
||||
def health():
|
||||
with opener.open('https://192.168.31.61:5011/health',timeout=3) as response: return json.load(response)
|
||||
assert not health().get('busy'), 'busy: no rollback/restart'
|
||||
manifest=json.loads((backup/'manifest.json').read_text())
|
||||
for name,existed in manifest.items():
|
||||
assert name in ('gateway.py','face_context.py')
|
||||
path=root/name
|
||||
if existed:
|
||||
tmp=path.with_name(path.name+'.rollback.tmp')
|
||||
tmp.write_bytes((backup/name).read_bytes());tmp.chmod(0o600);tmp.replace(path)
|
||||
elif path.exists(): path.unlink()
|
||||
subprocess.run(['systemctl','--user','restart','lan-voice-gateway.service'],check=True,timeout=30,stdout=subprocess.PIPE,stderr=subprocess.PIPE)
|
||||
for attempt in range(15):
|
||||
try:
|
||||
if health().get('status')=='ok': print(json.dumps({'status':'rolled_back','backup':str(backup),'health':'ok'}));break
|
||||
except Exception: pass
|
||||
time.sleep(1)
|
||||
else: raise RuntimeError('rollback health failed')
|
||||
'''
|
||||
root=Path(__file__).resolve().parents[1]
|
||||
record=json.loads((root/'logs/voice-investigation/gateway-deploy.json').read_text())
|
||||
if '--initial' in sys.argv: record['backup']=record.get('initial_backup',record['backup'])
|
||||
payload='record='+repr({k:record[k] for k in ('backup','gateway_sha256')})+'\n'+REMOTE
|
||||
r=subprocess.run(['ssh','-o','BatchMode=yes','-o','ConnectTimeout=5','gorios-spark-2@192.168.31.61','python3 -'],input=payload.encode(),capture_output=True,timeout=90)
|
||||
if r.stdout:
|
||||
result=json.loads(r.stdout);print(json.dumps(result))
|
||||
(root/'logs/voice-investigation/gateway-rollback.json').write_text(json.dumps(result,indent=2)+'\n')
|
||||
if r.stderr: print('Remote rollback error; no raw content printed.')
|
||||
raise SystemExit(r.returncode)
|
||||
@@ -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() {}
|
||||
}
|
||||
@@ -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")
|
||||
}
|
||||
@@ -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() }
|
||||
}
|
||||
@@ -0,0 +1,5 @@
|
||||
package android.os
|
||||
object Process {
|
||||
const val THREAD_PRIORITY_AUDIO = -16
|
||||
fun setThreadPriority(priority: Int) {}
|
||||
}
|
||||
@@ -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")
|
||||
}
|
||||
@@ -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
|
||||
}
|
||||
}
|
||||
@@ -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
|
||||
}
|
||||
@@ -0,0 +1,2 @@
|
||||
package com.gorios.lanvoice.net
|
||||
data class DownlinkFrame(val turnId: Long, val sequence: Long, val pcm16: ByteArray)
|
||||
@@ -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() }
|
||||
}
|
||||
@@ -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()
|
||||
}
|
||||
}
|
||||
@@ -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")
|
||||
}
|
||||
@@ -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
|
||||
}
|
||||
@@ -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 }
|
||||
@@ -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() {}
|
||||
}
|
||||
@@ -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)
|
||||
}
|
||||
}
|
||||
@@ -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) }
|
||||
}
|
||||
@@ -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")
|
||||
}
|
||||
}
|
||||
Reference in New Issue
Block a user