Add opt-in face presence departure and return speech

This commit is contained in:
zenord
2026-10-13 16:38:08 +08:00
parent 40abf3a14e
commit d0c1d7eb3d
21 changed files with 913 additions and 89 deletions
+3 -1
View File
@@ -19,6 +19,7 @@ def avatarUiCandidate = providers.gradleProperty('avatarUiCandidate').orNull ==
def avatarMouthCandidate = providers.gradleProperty('avatarMouthCandidate').orNull == 'true'
def avatarActionCandidate = providers.gradleProperty('avatarActionCandidate').orNull == 'true'
def avatarStartupFix = providers.gradleProperty('avatarStartupFix').orNull == 'true'
def presenceCandidate = providers.gradleProperty('presenceCandidate').orNull == 'true'
def avatarPlaybackClockFix = providers.gradleProperty('avatarPlaybackClockFix').orNull == 'true'
def avatarPlaybackDiagnostic = providers.gradleProperty('avatarPlaybackDiagnostic').orNull == 'true'
def avatarRuntimeFix = providers.gradleProperty('avatarRuntimeFix').orNull == 'true'
@@ -38,6 +39,7 @@ def emotionManifestSha = providers.gradleProperty('emotionManifestSha').orNull ?
if (emotionManifestSha && !(emotionManifestSha ==~ /[0-9a-f]{64}/)) throw new GradleException('Emotion graph requires exact external manifest SHA')
if (emotionManifestSha && (!avatarActionCandidate || !avatarMouthCandidate || !avatarNatural || actionVersionCode < 17)) throw new GradleException('Emotion candidate requires own-mouth runtime and a fresh code >=17')
if (avatarFullActionCandidate && (!emotionManifestSha || !avatarActionCandidate || actionVersionCode < 18)) throw new GradleException('Full candidate requires pinned emotion/action graph and fresh code >=18')
if (presenceCandidate && (!avatarStartupFix || actionVersionCode < 23)) throw new GradleException('Presence candidate requires startup fix and fresh code >=23')
if (avatarStartupFix && (!avatarPlaybackClockFix || actionVersionCode < 22)) throw new GradleException('Startup fix requires repaired playback and fresh code >=22')
if (avatarPlaybackClockFix && (!avatarFullActionCandidate || actionVersionCode < 21 || emotionManifestSha != '987e125a7d7a2cde99121b5f5246c82f4dbe36c4899d3d49eaffd1a68bafb887')) throw new GradleException('Playback clock fix requires frozen full graph and fresh code >=21')
if (avatarPlaybackDiagnostic && (!avatarFullActionCandidate || actionVersionCode < 20 || emotionManifestSha != '987e125a7d7a2cde99121b5f5246c82f4dbe36c4899d3d49eaffd1a68bafb887')) throw new GradleException('Playback diagnostic requires frozen full graph and fresh code >=20')
@@ -91,7 +93,7 @@ android {
targetSdk 34
testInstrumentationRunner 'com.gorios.lanvoice.AvatarCleanUiInstrumentation'
versionCode avatarActionCandidate ? actionVersionCode : (avatarMouthCandidate ? 15 : (avatarUiCandidate ? 14 : (avatarNatural ? 13 : 12)))
versionName = avatarStartupFix ? '0.7.4' : avatarPlaybackClockFix ? '0.7.3' : avatarPlaybackDiagnostic ? '0.7.2' : avatarRuntimeFix ? '0.7.1' : (avatarActionCandidate ? '0.7.0' : ((avatarUiCandidate || avatarMouthCandidate) ? '0.6.2' : '0.6.1'))
versionName = presenceCandidate ? '0.7.5' : avatarStartupFix ? '0.7.4' : avatarPlaybackClockFix ? '0.7.3' : avatarPlaybackDiagnostic ? '0.7.2' : avatarRuntimeFix ? '0.7.1' : (avatarActionCandidate ? '0.7.0' : ((avatarUiCandidate || avatarMouthCandidate) ? '0.6.2' : '0.6.1'))
ndk { abiFilters 'arm64-v8a' }
}
compileOptions { sourceCompatibility JavaVersion.VERSION_17; targetCompatibility JavaVersion.VERSION_17 }
@@ -43,6 +43,7 @@ class MainActivity : ComponentActivity() {
private lateinit var session: VoiceSession
private lateinit var audioOutput: AudioOutputGate
private var shareFace by mutableStateOf(false)
private var presenceEnabled by mutableStateOf(false)
private lateinit var entry: AutoConversation
private var entryPhase by mutableStateOf(EntryPhase.CONNECTING)
private var permissionMessage by mutableStateOf<String?>(null)
@@ -194,6 +195,10 @@ class MainActivity : ComponentActivity() {
}
}
},
presenceEnabled = presenceEnabled,onPresenceEnabled = { enabled ->
presenceEnabled=enabled;preferences().edit().putBoolean("presenceEnabled",enabled).apply()
if(::session.isInitialized) session.setPresence(enabled,expressionState.status==ExpressionStatus.ACTIVE)
},
)
}
if(BuildConfig.AVATAR_STARTUP_FIX) startShell()
@@ -232,7 +237,15 @@ class MainActivity : ComponentActivity() {
onState = {
if (expressionState.status != it.status) DebugLogUpload.log("audio", "camera state=${it.status.name.lowercase()}")
expressionState = it
}, onFaceCue = session::observeFace)
session.setPresence(presenceEnabled,it.status==ExpressionStatus.ACTIVE)
}, onFaceCue = session::observeFace,onPresence = { present,at ->
val interactive=(getSystemService(POWER_SERVICE) as android.os.PowerManager).isInteractive
val unlocked=!(getSystemService(KEYGUARD_SERVICE) as android.app.KeyguardManager).isKeyguardLocked
session.setPresence(presenceEnabled,inForeground && interactive && unlocked && expressionState.status==ExpressionStatus.ACTIVE)
session.observePresence(present,at)
})
presenceEnabled=preferences().getBoolean("presenceEnabled",false)
session.setPresence(presenceEnabled,false)
if(inForeground) session.foreground(connectAutomatically=false)
if(mediaReady) avatarPack?.emotionAction?.actionPack?.let(session::installReviewedActions)
scheduleEntry()
@@ -324,6 +337,7 @@ class MainActivity : ComponentActivity() {
private fun closeCamera() {
if(!::expressions.isInitialized) return
expressions.stop()
session.setPresence(presenceEnabled,false)
shareFace = false
session.setFaceSharing(false)
}
@@ -74,6 +74,16 @@ class VoiceSession(
private var faceCue = FaceCueObservation()
private var faceSent = false
private val faceDiagnostics = FaceTransmissionDiagnostics()
private val presenceRules=com.gorios.lanvoice.expression.PresenceRules()
private var presenceEnabled=false
private var presenceCamera=false
private var presenceSupported=false
private var presenceSpeech=false
private var lastSpeechAt=0L
private data class PresenceRequest(val id: Long,val kind: com.gorios.lanvoice.expression.PresenceKind,
var turn: Long?=null,var accepted: Boolean=false)
private var presenceRequest: PresenceRequest?=null
private var presenceTimeout: Runnable?=null
private val faceTick = object : Runnable {
override fun run() {
if (!faceSharing || released) return
@@ -107,6 +117,7 @@ class VoiceSession(
diagnostic("playback drained turn=$turn")
if (dialogue.playbackDrained(turn)) {
drainedTurn=turn
if(presenceRequest?.turn==turn) clearPresenceRequest()
resetReply("drained")
emotionEndedTurn = turn
update(state.copy(phase = VoicePhase.LISTENING, replyEmotion = ReplyEmotion()))
@@ -237,6 +248,7 @@ class VoiceSession(
fun stopVoice(sendControls: Boolean = true,cancelReason: String = "stop_voice") {
checkMainThread()
cancelPresence(reset=true)
cancelActionFor(cancelReason)
resetReply("stop")
val wasActive = state.voiceActive
@@ -275,7 +287,7 @@ class VoiceSession(
checkMainThread()
if (!isActive() || state.microphoneMuted == muted) return
update(state.copy(microphoneMuted = muted))
if (muted) stopCapture()
if (muted) { cancelPresence(reset=true);stopCapture() }
else if (state.phase == VoicePhase.LISTENING) startCapture()
}
@@ -326,6 +338,44 @@ class VoiceSession(
faceCue = observation
}
fun setPresence(enabled: Boolean,cameraActive: Boolean) {
checkMainThread()
presenceEnabled=enabled;presenceCamera=cameraActive
if(!enabled || !cameraActive) cancelPresence(reset=true)
}
private fun presenceEligible()=presenceEnabled && presenceCamera && presenceSupported && isActive() && !state.microphoneMuted
fun observePresence(present: Boolean?,observedAt: Long) {
checkMainThread()
if(!presenceEligible()) { presenceRules.reset();return }
val now=SystemClock.elapsedRealtime()
if(now-observedAt !in 0..350) { presenceRules.sample(null,now,currentTurn,false);return }
val idle=state.phase==VoicePhase.LISTENING && !actions.active && presenceRequest==null &&
!presenceSpeech && now-lastSpeechAt>=800 && capturing
val trigger=presenceRules.sample(present,observedAt,currentTurn,idle,
presenceRequest?.kind==com.gorios.lanvoice.expression.PresenceKind.ABSENT,appearedAllowed.get()) ?: return
val id=presenceSerial.incrementAndGet()
if(id !in 1..UINT32_MASK) return
presenceRequest=PresenceRequest(id,trigger.kind)
diagnostic("presence state=sent kind=${trigger.kind.wire} request=$id turn=$currentTurn")
if(!dialogue.presence(id,trigger.turn,trigger.kind,now-observedAt)) { clearPresenceRequest();return }
presenceTimeout=Runnable { cancelPresence(reset=false) }.also { main.postDelayed(it,5_000) }
}
private fun clearPresenceRequest() {
presenceTimeout?.let { main.removeCallbacks(it) };presenceTimeout=null;presenceRequest=null
}
private fun cancelPresence(reset: Boolean) {
val request=presenceRequest
clearPresenceRequest()
if(reset) presenceRules.reset() else presenceRules.discardPending()
if(request!=null && state.connection==ConnectionStatus.CONNECTED) {
dialogue.presenceCancel(request.id)
if(request.turn==currentTurn) {
blockedTurn=currentTurn;playback.interrupt();onPrepareExpression(null);resetReply("presence_cancelled")
}
diagnostic("presence state=cancelled request=${request.id}")
}
}
private fun clearFaceContext(clearObservation: Boolean = true) {
if (faceSent && faceSupported && state.connection == ConnectionStatus.CONNECTED && hasTurn) {
val sent = dialogue.sendFaceCue(currentTurn, FaceCueObservation(), 0)
@@ -335,7 +385,7 @@ class VoiceSession(
if (clearObservation) faceCue = FaceCueObservation()
}
val runtimeProtocolState: String get() = "hello=${dialogue.actionNegotiation} connection=${state.connection.name.lowercase()} turn=$currentTurn drained=$drainedTurn action=${actions.active} capture=$capturing capture_epoch=$captureEpoch"
val runtimeProtocolState: String get() = "hello=${dialogue.actionNegotiation} connection=${state.connection.name.lowercase()} turn=$currentTurn drained=$drainedTurn action=${actions.active} capture=$capturing capture_epoch=$captureEpoch presence=$presenceEnabled/$presenceCamera/$presenceSupported/${presenceRequest?.kind?.wire ?: "none"}"
fun faceDiagnosticsSnapshot() = faceDiagnostics.snapshot()
private fun sendFaceContext() {
@@ -368,6 +418,7 @@ class VoiceSession(
private fun onConnection(connection: ConnectionStatus, reason: String) {
diagnostic("connection ${state.connection.name} -> ${connection.name} reason=$reason", "connect")
if (connection != ConnectionStatus.CONNECTED) {
clearPresenceRequest();presenceRules.reset();presenceSupported=false;presenceSpeech=false
cancelActionFor("disconnect")
onPrepareExpression(null)
resetReply("disconnect")
@@ -438,6 +489,29 @@ class VoiceSession(
private fun onEvent(event: ServerEvent) {
val turn = (event.payload.opt("turn_id") as? Number)?.toLong()
diagnostic("onEvent kind=${event.kind.name} turn_id=$turn")
if(event.kind==EventKind.PRESENCE) {
val request=presenceRequest ?: return
if((event.payload.opt("request_id") as? Number)?.toLong()!=request.id) return
val accepted=event.payload.optString("state")=="accepted"
if(accepted && request.turn==turn && presenceEligible()) {
presenceTimeout?.let { main.removeCallbacks(it) };presenceTimeout=null
if(!request.accepted && request.kind==com.gorios.lanvoice.expression.PresenceKind.APPEARED)
appearedAllowed.set(SystemClock.elapsedRealtime()+600_000)
request.accepted=true
} else if(!accepted) clearPresenceRequest()
else cancelPresence(reset=false)
diagnostic("presence state=${if(accepted) "accepted" else "rejected_or_cancelled"} request=${request.id}")
return
}
if(event.kind==EventKind.ABORT && event.payload.optString("reason")=="presence_greeting") {
val id=(event.payload.opt("request_id") as? Number)?.toLong()
if(id==null || id!=presenceRequest?.id || !presenceEligible()) {
if(turn!=null) retiredTurns.add(turn)
if(id!=null && id in 1..UINT32_MASK) dialogue.presenceCancel(id)
return
}
presenceRequest?.turn=turn
}
if (event.kind == EventKind.EXPRESSION_PREPARE) {
if (isActive() && hasTurn && turn == currentTurn && blockedTurn != turn && !actions.active) {
if (event.type.endsWith(".cancel")) { diagnostic("emotion_prepare state=cancelled turn=$turn");onPrepareExpression(null) }
@@ -482,7 +556,10 @@ 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.HELLO -> {
faceSupported = event.payload.optInt("context_face_cue_version", 0) == 1
presenceSupported=event.payload.optInt("presence_greeting_version",0)==1
}
EventKind.LISTEN -> {
val active = isActive()
diagnostic("LISTEN action=${if (action in setOf("start", "stop")) action else "other"} active=$active blockedTurn=$blockedTurn")
@@ -503,6 +580,9 @@ class VoiceSession(
}
}
EventKind.VAD -> if (isActive()) {
val kind=event.payload.optJSONObject("event")?.optString("type") ?: ""
if(kind=="speech.start") { presenceSpeech=true;lastSpeechAt=SystemClock.elapsedRealtime();cancelPresence(reset=false) }
if(kind=="speech.end") { presenceSpeech=false;lastSpeechAt=SystemClock.elapsedRealtime() }
update(state.copy(phase = if (action in setOf("end", "stop", "speech_end"))
VoicePhase.RECOGNIZING else VoicePhase.LISTENING))
}
@@ -529,8 +609,9 @@ class VoiceSession(
// 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 reason = event.payload.optString("reason")
if(reason=="voice_barge_in") presenceSpeech=true
val listenReset = reason == "listen_start"
val announcesNewTurn = reason in setOf("listen_start", "new_turn", "voice_barge_in", "client_abort", "action_followup", "action_cancelled", "action_timeout")
val announcesNewTurn = reason in setOf("listen_start", "new_turn", "voice_barge_in", "client_abort", "action_followup", "action_cancelled", "action_timeout", "presence_greeting", "presence_cancelled")
blockedTurn = if (announcesNewTurn) null else oldTurn
diagnostic("ABORT blockedTurn=$blockedTurn active=${isActive()} listenReset=$listenReset oldTurn=$oldTurn currentTurn=$currentTurn")
playback.interrupt()
@@ -572,6 +653,8 @@ class VoiceSession(
}
// IDs identify turns; do not assume the server allocates them in numeric order.
if (!hasTurn || id != currentTurn) {
presenceRules.discardPending();presenceSpeech=false;lastSpeechAt=SystemClock.elapsedRealtime()
if(presenceRequest!=null && presenceRequest?.turn!=id) cancelPresence(reset=false)
cancelActionFor("new_turn")
onPrepareExpression(null)
resetReply("new_turn")
@@ -652,6 +735,8 @@ class VoiceSession(
}
companion object {
private val presenceSerial=java.util.concurrent.atomic.AtomicLong()
private val appearedAllowed=java.util.concurrent.atomic.AtomicLong()
private const val BACKGROUND_DISCONNECT_GUIDANCE = "App 退到后台,连接已断开"
private const val TAG = "LanVoice"
private const val UINT32_MASK = 0xffff_ffffL
@@ -96,6 +96,7 @@ fun CallScreen(state: VoiceUiState,entry: EntryPhase,permissionMessage: String?,
onOfflinePreview: ()->Unit=NoUiAction,
startupBase: ContinuousAvatarPack?=null,startupStage: String="ready",
onStartupVisible: ()->Unit=NoUiAction,onRetryAssets: ()->Unit=NoUiAction,onStartupFailed: ()->Unit=NoUiAction,
presenceEnabled: Boolean=false,onPresenceEnabled: (Boolean)->Unit={},
) {
val avatar=remember { AvatarController() }.select(state.voiceActive,state.replyEmotion,state.playbackActivity.takeUnless { state.actionActive })
val latestAvatar by rememberUpdatedState(avatar)
@@ -125,6 +126,11 @@ fun CallScreen(state: VoiceUiState,entry: EntryPhase,permissionMessage: String?,
}
}
Text(status,style=MaterialTheme.typography.titleMedium)
Row(verticalAlignment=Alignment.CenterVertically) {
Text("人脸出现/离开时主动说话",fontSize=13.sp,modifier=Modifier.weight(1f))
Switch(checked=presenceEnabled,onCheckedChange=onPresenceEnabled)
}
Text("需开启相机;仅发送有人出现/离开事件,不上传照片",fontSize=12.sp)
if(startupStage=="failed") {
Text("角色准备未完成,基础角色仍可使用",fontSize=12.sp)
TextButton(onClick=onRetryAssets) { Text("重试准备角色") }
@@ -29,6 +29,7 @@ class ExpressionController(
private val lifecycleOwner: LifecycleOwner,
private val onState: (ExpressionUiState) -> Unit,
private val onFaceCue: (FaceCueObservation) -> Unit = {},
private val onPresence: (Boolean?,Long) -> Unit = { _,_-> },
) {
private class Run {
@Volatile var active = true
@@ -181,6 +182,7 @@ class ExpressionController(
mpImage.close()
} ?: kotlin.run {
run.diagnostics.failed(CameraFailure.NO_RESULT)
main.post { if(isCurrent(run)) onPresence(null,now) }
return
}
if (!run.active) return
@@ -204,6 +206,7 @@ class ExpressionController(
main.post { if (isCurrent(run)) onFaceCue(faceCue) }
// UI receives only <=2 enum labels; 52 coefficients, pose and images stay transient.
val presence = if (result.faceLandmarks().isEmpty()) FacePresence.ABSENT else FacePresence.PRESENT
main.post { if(isCurrent(run)) onPresence(presence==FacePresence.PRESENT,now) }
if (run.lastPublished != visible || run.lastStableCue != faceCue.cue || run.lastPresence != presence) {
run.lastPresence = presence
run.lastStableCue = faceCue.cue
@@ -0,0 +1,56 @@
package com.gorios.lanvoice.expression
enum class PresenceKind(val wire: String) { ABSENT("absent"), APPEARED("appeared") }
data class PresenceTrigger(val kind: PresenceKind,val turn: Long,val ageMs: Long)
/** Local booleans only; called on main with monotonic successful sample times. */
class PresenceRules(private val absentMs: Long=20_000,private val confirmMs: Long=1_000) {
init { require(absentMs in 5_000..600_000 && confirmMs==1_000L) }
private var last: Long?=null
private var absentSince: Long?=null
private var presentSince: Long?=null
private var absentAttempted=false
private var returnArmed=false
private data class Pending(val kind: PresenceKind,val turn: Long,val until: Long)
private var pending: Pending?=null
fun discardPending() { pending=null }
fun reset() { breakContinuity();absentAttempted=false }
private fun breakContinuity() { last=null;absentSince=null;presentSince=null;returnArmed=false;pending=null }
fun sample(present: Boolean?,now: Long,turn: Long,idle: Boolean,
absentInFlight: Boolean=false,appearedAllowedAt: Long=0): PresenceTrigger? {
val old=last
if(present==null || old!=null && now<=old) { breakContinuity();return null }
if(old!=null && now-old>350) breakContinuity()
last=now
if(!present) {
presentSince=null
if(pending?.kind==PresenceKind.APPEARED) pending=null
val since=absentSince ?: now.also { absentSince=it }
if(now-since>=absentMs) {
returnArmed=true
if(!absentAttempted) {
absentAttempted=true
if(pending==null) pending=Pending(PresenceKind.ABSENT,turn,now+5_000)
}
}
} else {
absentSince=null
if(pending?.kind==PresenceKind.ABSENT) pending=null
val since=presentSince ?: now.also { presentSince=it }
if(now-since>=confirmMs) {
absentAttempted=false
if(returnArmed) {
returnArmed=false
// Returning during own departure speech must not queue a second speech.
if(!absentInFlight && now>=appearedAllowedAt && pending==null)
pending=Pending(PresenceKind.APPEARED,turn,now+5_000)
}
}
}
val candidate=pending ?: return null
if(now>=candidate.until || candidate.turn!=turn) { pending=null;return null }
if(!idle) return null
pending=null
return PresenceTrigger(candidate.kind,turn,0)
}
}
@@ -90,6 +90,9 @@ class DialogueClient(
readyUpdateSent=send(DialogueProtocol.capabilitiesReady(pin))
return readyUpdateSent
}
fun presence(id: Long,turn: Long,kind: com.gorios.lanvoice.expression.PresenceKind,age: Long)=
send(DialogueProtocol.presence(id,turn,kind,age))
fun presenceCancel(id: Long)=send(DialogueProtocol.presenceCancel(id))
fun connect() {
checkMainThread()
@@ -10,7 +10,7 @@ import com.gorios.lanvoice.expression.FaceCueObservation
data class ServerEvent(val type: String, val kind: EventKind, val payload: JSONObject)
enum class EventKind {
AUTH, HELLO, CAPABILITIES, HISTORY, LISTEN, VAD, STT, LLM, TTS, REPLY_EMOTION, EXPRESSION_PREPARE, ACTION, SPEECH, ERROR, ABORT, METRICS, PING, PONG, UNKNOWN
AUTH, HELLO, CAPABILITIES, PRESENCE, HISTORY, LISTEN, VAD, STT, LLM, TTS, REPLY_EMOTION, EXPRESSION_PREPARE, ACTION, SPEECH, ERROR, ABORT, METRICS, PING, PONG, UNKNOWN
}
/** Header integers are unsigned, network byte order; PCM samples are signed little endian. */
@@ -32,6 +32,7 @@ object DialogueProtocol {
.put("sample_rate", 16_000)
.put("frame_duration", 20)
.put("persona", "default")
.put("presence_greeting_version",1)
.put("voice_mode", "continuous_voice")
.apply { if (actionPackSha?.matches(Regex("[0-9a-f]{64}")) == true) {
put("action_protocol", 1); put("action_pack_sha256", actionPackSha)
@@ -64,6 +65,16 @@ object DialogueProtocol {
fun playbackDrained(turnId: Long): String = JSONObject()
.put("type", "playback.drained").put("turn_id", turnId).toString()
fun presence(id: Long,turn: Long,kind: com.gorios.lanvoice.expression.PresenceKind,age: Long): String {
require(id in 1..0xffff_ffffL && turn in 0..0xffff_ffffL && age in 0..1500)
return JSONObject().put("type","presence."+kind.wire).put("version",1).put("request_id",id)
.put("turn_id",turn).put("present",kind==com.gorios.lanvoice.expression.PresenceKind.APPEARED).put("age_ms",age).toString()
}
fun presenceCancel(id: Long): String {
require(id in 1..0xffff_ffffL)
return JSONObject().put("type","presence.cancel").put("version",1).put("request_id",id).toString()
}
fun actionStatus(value: com.gorios.lanvoice.avatar.ActionStatus): String = JSONObject()
.put("type", "action.status").put("turn_id", value.turn).put("action_id", value.id)
.put("status", value.status).put("asset_id", value.asset ?: "")
@@ -108,6 +119,7 @@ object DialogueProtocol {
"tts" -> EventKind.TTS
"action" -> EventKind.ACTION
"speech" -> EventKind.SPEECH
"presence" -> EventKind.PRESENCE
"error" -> EventKind.ERROR
"abort" -> EventKind.ABORT
"metrics" -> EventKind.METRICS
+117
View File
@@ -0,0 +1,117 @@
# 人脸存在驱动的主动发言:最终设计 / 0.7.5
2026-10-13:用户已批准施工,并将缺人默认阈值改为20s、新增离开询问。此版本覆盖先前180s/仅回来招呼评估。Android目标0.7.5/code23,gateway0.8.1。0.7.4及旧角色pin不变:987e125a7d7a2cde99121b5f5246c82f4dbe36c4899d3d49eaffd1a68bafb887。Coord已验证0.7.4首屏0.996s、idle1.424s、full2.910s;保留其启动与播放修复。
## 审核要点
- 默认连续缺人20s(内部配置5–600s)触发一次`presence.absent`;持续缺人不能反复询问。初始/重连/相机重启从UNKNOWN计20s;再次询问须先连续PRESENT确认1000ms。
- 满足过20s缺人后,重新连续PRESENT1000ms触发`presence.appeared`,接受后冷却600s。两类候选/请求/主动轮互斥;离开询问正在播放时回来,丢弃招呼,不因回来取消已开始的询问。
- 两类事件共用默认关闭的「人脸出现/离开时主动说话」开关,放现有settings。相机权限/实际ACTIVE/前台/亮屏/正常通话及协议支持都是必要条件;表情共享开关独立。
- 本地采样防抖→一次布尔/枚举WS事件→gateway空闲/VAD裁决→新轮0ASR/1LLM/1完整文本TTS。保留persona、单system时间注入、emotion schema,主动轮action/after必须null。
- 忙时候选最多5s,同socket/原turn且新鲜采样才尝试;过期/跨轮不补播。用户讲话优先,撤销候选并以普通barge-in打断已开始主动轮。后台/熄屏/关相机/关开关/离线清状态与本请求;不误取消用户/动作轮。
- 不上传/保存原图、landmarks/脸系数/身份;不写lorebook、不伪造用户气泡。只有真实playback.drained后保存assistant发言,不保存presence事件。
## 已核实的检测管线
`ExpressionController.kt:87,166,276`:Android CameraX ImageAnalysis 640×480 RGBA/KEEP_ONLY_LATEST,CPU FaceLandmarker VIDEO模式,最多2脸,内部检测/presence/tracking阈值0.5,独立executor约100ms处理一次。图片只短暂在内存,finally关闭ImageProxy和回收Bitmap;gateway不做人脸检测。
目前landmarks非空表示PRESENT,空表示ABSENT;失败/无结果/相机关闭必须为UNKNOWN,不能算缺人。未输出可校准的逐脸置信度;blendshape intensity不是人脸概率。UI仅在状态变化时回调,不能用旧UI标签+timer证明持续出现。因此补逐次本地`present:Boolean? + elapsedMs`观测,UNKNOWN清连续计时;每个相机Run既有generation过滤晚回调。
复用既有推理结果,不另开CameraX/模型或提高采样率。存在检测不依赖表情quality/smile/brow阈值;多人算有人但只泛化招呼、不认人。复用不等于降低FaceLandmarker耗电;轻量FaceDetector替换暂不做,真机性能证据后再评。
M5 `context.face_cue`是用户轮的可选弱上下文,不会启动LLM。存在事件是启动器,两者可共存;共享表情关闭不会关闭独立启用的主动功能,也不会把人的表情直接映射成角色emotion。
## 状态机
用elapsedRealtime/monotonic,不改变服务器日历时间功能,不比较两端绝对时间。相邻有效样本间隔≤350ms;UNKNOWN/间隔超限/时钟倒退清连续计时和未发送候选,不能把后台几分钟当缺人。
每个连续离开周期最多一次absent尝试(发送前消耗,拒绝/超时不自动重试)。持续PRESENT1000ms完成周期重置,可再次20s缺人询问;达到过20s才武装appeared。出现确认通常约11个100ms样本,不能用首末两帧冒充。两类共用一个pending槽和一个active请求;appeared冷却单独记录,进程内不因Activity/重连清零,服务器按认证owner补有界冷却,防重连绕过。
```text
onSample(present?, now, cameraEligible):
if !cameraEligible: resetEpisode; return
if UNKNOWN or gap>350ms: resetContinuityAndCandidate; preserveConsumedAbsence; return
if ABSENT:
cancel unsent appeared candidate; clear presentSince
start/continue absentSince
if absentDuration>=20s:
armReturn=true
if !absentAttempted:
absentAttempted=true
queueOne(absent, ttl=5s, socket/turn)
if PRESENT:
cancel unsent absent candidate; clear absentSince
start/continue presentSince
if presentDuration>=1s:
rearmAbsentForNextAbsence()
if armReturn:
armReturn=false
if ownAbsentInFlight: dropAppeared
else if appearedCooldownElapsed: queueOne(appeared, ttl=5s, socket/turn)
pollCandidateOnlyWhenIdleAndFresh()
onUserSpeech/newTurn: discard candidate; retire only this request
onBackground/screenOff/cameraOff/disabled/disconnect/offline:
reset episode; cancel only own pending/active request
gateway.onEvent:
validate negotiatedVersion/exactFields/owner/socket/turn/id/age
deduplicate; no automatic retry
require auto listening, recent uplink, VAD quiet, no task/drain/action/after/activePresence
reserve before await; allocate new turn and ack; 1LLM+1TTS without ASR
```
缺人计时不受TTS/LLM忙态本身影响,但发起必须空闲。仅VoicePhase.LISTENING不够:现有speech.start也可显示LISTENING。客户端消费嵌套VAD event.type维护speechActive;服务端检查vad.active/positive/candidate及安静至少800ms、任务/playback_waiting/action_holding/action票据/after待办。无麦权限/语音会话未启动/主动静音/手动模式不触发。起音探测有延迟,不能保证最后一个窗口后用户不会讲话;正常barge-in是最终保护,不能减弱VAD或缓存PCM补播。
## 协议及主动轮
HELLO双端可选`presence_greeting_version:1`;旧端缺字段不发送新事件,动作capability/assetpin不替代presence协商。
```json
{"type":"presence.absent","version":1,"request_id":7,"turn_id":25,"present":false,"age_ms":100}
{"type":"presence.appeared","version":1,"request_id":8,"turn_id":26,"present":true,"age_ms":100}
{"type":"presence.cancel","version":1,"request_id":7}
```
字段严格,uint32 request_id/原turn,age≤1500ms。只发确认事件,不逐帧上传bool;不传自由文本/提示词/脸计数/照片。服务端只能信任客户端检测声明,不能用它做身份认证。返回`presence.status`固定state/reason/同request_id,accepted关联新turn;reject不可意外acceptTurn。有限结果表防重复,cancel只能作用同socket本请求,未知/重复cancel不能打断无关轮。
新增小`run_presence`入口,不能把空PCM塞进submit/run的ASR路径。复用generate/synthesize、timeout/取消、emotion.prepare与最终一致schema、已有captureEpoch/turn/播放head/drain。新增presence起轮/取消原因白名单,使用speech.start(origin=presence),不复用上个turn。
服务器意图:
- absent:本地检测提示用户离开画面约20s,可能误判;按当前persona自然简短问一句去哪了/还聊吗,不断言身份/心情。
- appeared:本地检测提示有人重新出现在画面,可能误判;按persona自然简短打招呼,不断言身份/心情/离开时长。
意图是受控输入,不是固定输出台词。追加到既有单system及内部一次请求,沿用server-clock,不新增第二system;不改provider/max_tokens160/voice/TTS参数。主动轮动作不可用、action/after=null,普通轮舞蹈能力原样保留。失败不生成固定回退/再次LLM。每次接受0ASR/1LLM/1TTS,无新素材生成费用。
不调用history.begin插入合成user;独立pending-spoken槽在真实drain后调用history.spoken,只有assistant气泡。取消/未drain不成为确认历史,presence意图/事件不持久。保留现有context合并assistant及过滤开头无user规则。主动轮禁音频debug capture,普通轮原配置不变。TTS.stop不是播放完成;无舞蹈式mic-stop新窗口,录音/AEC/barge-in仍按普通对话。after_action和renderer owner不动。
## 风险与测试
照片/多人/弱光不是活体身份检测;泛化措辞及防抖只能减误触。持续UNKNOWN/性能掉帧可能延迟或永不武装,应诊断为fixed reason,不能降级当缺人。网络慢/跨轮/晚ack不得复活旧主动轮;控制事件也不能无限发模型调用。只记录500ring内enum/id/epoch/时间、最多10s摘要,禁聊天/音脸/原提示词与异常内容。
- JVM:19999/20000、999/1000、600s/5s/350ms边界;持续缺人一次、完整PRESENT后重武装;忙时TTL/跨轮;absent播放中回来丢appeared;双事件顺序互斥;speech、UNKNOWN、相机generation、后台/锁屏/权限撤销、离线、静音、开关默认off。
- 生产客户端回调:HELLO新旧、ack新turn→prepare/final/TTS/head/drain;旧PCM/epoch拒绝;取消只本请求,用户讲话优先,after/动作和code22交接不回归。
- gateway/WS:auth/strictfield/重复id/错误age/turn、冷却、两类竞争、VAD起音/任务/drain/action/after裁决、cancel幂等、0ASR/1LLM/1TTS、单system原time/persona/action:null、drain后assistant-only、无presence持久化/音频debug。
- 回归继承9 JVM/UI、32包装、200GLES、100gateway passed+1既有Silero模型排除skip,新增数量实报;Instrumentation编译/执行分开,host doubles不等于手机。
- Coord真机:开关/权限实际门禁,缺人20s一次询问、回来1s自然招呼、一直有人/缺人不重复;讲话/TTS/动作不抢、能打断;关相机/熄屏/重连无幽灵轮;耗电/温升/启动/真实口层音轨;不由代码owner开USB/无线或替用户采录。
## 实施/交付记录
用户已授权按此设计直接施工,不再逐步等审批。目标Android0.7.5/code23(发布前核占用)、gateway0.8.1;只gateway执行hash/busy/backup部署与重启,不动模型/ASR/TTS/VAD服务。旧APK/素材和成功时间/TTS设置保留,新形象另一任务不导入。实际交付记录如下;commit 在最终交付回复及 Git main 中核对。
### 已完成的交付(2026-10-13)
- APK:`http://192.168.31.124:8080/lan-voice-v075-presence-code23-arm64-debug.apk`,Android0.7.5/code23,包名`com.gorios.lanvoice`,arm64、min26/target34。SHA256:`3f36df30c8831b154f874c63710d2049092e16ddcf9fd98c812107f56f1b0851`;`.apk.sha256`同路径可取,HTTP实际字节已核。
- 同debug证书SHA256:`b9608336bc1ed1de3269bb4594f9fe718daaa5439511c5187aa385d2b799dcf1`。精确旧pin保持不变;3222运行引用及包括启动小包在内3818个avatar文件均与code22逐字节相同。code22/旧APK保留,无新形象导入、无资产生成。
- 设置内新增「人脸出现/离开时主动说话」,默认关闭;开启后仍需实际相机开启、权限授权、正常前台亮屏连接和语音空闲。缺人20s每周期一次,回来连续1s确认、招呼600s冷却。仅本地复用检测布尔结果;主动轮action/after_action强制null。
- gateway0.8.1已部署;部署前/后canonical文件SHA匹配、busy检查通过、私有环境和unit配置不变,健康返回ok。仅重启`lan-voice-gateway.service`。服务端备份:`/home/gorios-spark-2/lan-voice/.runtime/backups/voice-gateway-20261013-162856`。模型/ASR/TTS/VAD服务未重启,provider、成功时间逻辑、TTS音色/参数未改。健康检查不代表真人推理验收。
- 最终回归:9组JVM入口及UI源码契约通过;1407个presence采样/边界/状态断言及生产VoiceSession取消/turn/drain回调回放;33包装测试;gateway110 passed、1既有Silero源归档排除模型skip。真实ASGI WS路由测试2连接,后端为MockTransport,验证每主动轮0ASR/1LLM/1TTS;未调用真实模型,不把模拟调用称为真实推理。
- 沿用并核对未变化shader/harness的五包200项离线GLES结果;实际新APK生产loader/媒体回放通过,ACTION层保持、idle合法返回、后台cold/receipt加载均0主线程资产读取,冷路径3185patch读、可信receipt路径0patch读。Android媒体/Surface/录音确认使用宿主doubles,非手机GPU测试。
- Gradle assemble及Android instrumentation Kotlin编译通过;instrumentation执行、code23真机安装/20s离开问候/1s回来招呼、相机采样稳定性、耗电/温升、用户打断及新版本启动耗时均notrun。0.7.4已验证的0.996/1.424/2.910s属于旧版,不能当code23实测。APK交coord USB安装,代码owner未安装、未开启用户mic/cam。
- 忽略目录中的机器证据:`logs/action-emotion/presence-075/`、`logs/action-emotion/presence-075-release/`及`logs/avatar-safe-061/client-tests.json`;不提交日志/报告/媒体/密钥。此施工实际模型/素材生成调用0,无新增生成费用;用户使用主动功能会产生正常单次LLM/TTS推理。
### Coord安装后的有限验证
正常启动后在现有settings开启相机及默认关闭的主动开关;同意原权限状态下正常通话会采集麦克风/相机,不保存或上传人脸原图。保持空闲离开画面20s,应只问一次;持续缺人不重复;返回并连续被检测1s,应自然招呼(600s冷却内不重复)。另测离开询问正在播放时回来不补招呼、用户讲话能优先打断、关相机/关开关/后台/锁屏/重连无旧轮补播。误检和持续UNKNOWN仍可能影响触发时间,不能由宿主回放断言真人效果已达标。
+79 -63
View File
@@ -1,7 +1,7 @@
{
"baseline_android_commit": "9b428fb76ffa1468aa46124b33d9c598cf3740d8",
"source": "SPARK-2 deployed lan-voice gateway",
"code_version": "0.8.0",
"code_version": "0.8.1",
"python": "3.12.3",
"machine": "aarch64",
"scope": "whitelisted source only; no runtime/models/credentials",
@@ -34,8 +34,8 @@
},
"gateway.py": {
"source": "workspace:gateway/gateway.py",
"sha256": "0d57875ec480b2fe3990754fbef75d72e7a92cbfc1ec291b27461a983227bdbb",
"bytes": 46738,
"sha256": "ac92c48ddd903b74be21c8a12953e0f5b65a67818b9a236892ee38c14919be0e",
"bytes": 54850,
"upstream_sha256": "d088bedcf5c0accd4712e06202f6ced8ab155aad57a5b05683724efa346326ce"
},
"guest_sessions.py": {
@@ -365,6 +365,16 @@
"source": "workspace:gateway/tests/test_capabilities_ready.py",
"sha256": "49b9cf64e6d30e389588014a3a1de04d1a7b98f20fbea036ace4dcf8debfe857",
"bytes": 3494
},
"presence.py": {
"source": "workspace:gateway/presence.py",
"sha256": "56f20feb977da82e56c106d4a6862bbcbe92cf626391f8688ff9be8683c46f70",
"bytes": 2778
},
"tests/test_presence.py": {
"source": "workspace:gateway/tests/test_presence.py",
"sha256": "c8e804680d99f05174d3feea32a4a7ecac7d49143fed897a107ff3d5dbacad86",
"bytes": 14050
}
},
"archive_baseline_commit": "19a7adccd9322986eb0646b165b9ce1cf2650cf2",
@@ -398,6 +408,72 @@
},
"release_baseline_commit": "d43c7d4e809a5a6b18ca9f28c8163a2f9ad34c7f",
"deployment_baseline": {
"source": "presence absent/appeared gateway 0.8.1; gateway-only hash/busy/backup deployment",
"files": {
"action_protocol.py": "04c65ce27140da7757e0164983efe33800dddcff0139d16e8fe4c8a99a3b50ee",
"action_reply.py": "4d66164a6668a571dc861282a5c80e408b51dfcfd67f45141e8c6701f6b81364",
"app.py": "d6520894dfbe035f64b1984aae15976db4df0e7e720195c81d3bf483b240056f",
"face_context.py": "d032ff8033a49219595d6edff2950856937e024782143621d37d02b56b024315",
"gateway.py": "ac92c48ddd903b74be21c8a12953e0f5b65a67818b9a236892ee38c14919be0e",
"guest_sessions.py": "cc082fdb6c2ff7f5a41361ffe9ea2a53ebb944ee37354f65119405ad7a521c82",
"history.py": "0015b3143268f3e22a8a8a53b65ef4e3522f1f881dfca213c93142899c02631e",
"llm_provider.py": "b3cf6ab5e4c953ef13dc00802f4594055164c89b10b875dda44f071ad1ede082",
"persona_resolver.py": "deb33b4f4c17792fa5a6837362d5b29173e60a57bb993b61363bd4882d66d5de",
"personas/lvbu.lorebook.json": "1f144b431bdd5d9cda0ce593438fa88e717c0671d496105883a3d4db7bd635ea",
"personas/yangmi.lorebook.json": "73badae3fd8582555caa338e50fb6193e64e6a43025dd469672aa903c1c4b71b",
"presence.py": "56f20feb977da82e56c106d4a6862bbcbe92cf626391f8688ff9be8683c46f70",
"protocol.py": "d9f522d958935200002e56024949a12b71eb89b3f3241635c5c307b798ee71c5",
"reply_emotion.py": "080f04e368c5a7d26254f2b870803238941aa481d457227ba15a870fd4a4e3c0",
"reviewed_action_packs.json": "830334cacf04bc488e7f07809a6defdcec481410b6bedb7b78cfa78f8ecf334e",
"segmentation.py": "562ffc6e06f5b9f9072860b588feae3a5d7cd6eaa8577ac928d770071b06978d",
"server_clock.py": "dc46d79fd43c8b94f52acfdea0564058c47f3a3b8b43aa53fe6868a1821f3a0e",
"tests/test_action_protocol.py": "f1340c6c68674fc5d077003ca6be51746b31462ccc26acc0c092fbad01f629dc",
"tests/test_action_reply.py": "0c40a937be4c6545e04ed2268df1714c34dce982058f6b19daabf06b0fa30932",
"tests/test_capabilities_ready.py": "49b9cf64e6d30e389588014a3a1de04d1a7b98f20fbea036ace4dcf8debfe857",
"tests/test_continuity.py": "d8390238f390463a98f12b9909bb5846be65f5b6dc1b21b94338b4cd75aaafae",
"tests/test_debug.py": "7d1d7876c4106f3df0b84cf8f7e479afb4a30ca51264fb94fa288fdd8155883e",
"tests/test_face_context.py": "c297866117fa7406b5fda95250b67ca7ebd7476486ddd5455935c140d31c9f6f",
"tests/test_gateway.py": "f22aa98f3d6f62a2949a9047ec97e6dd686cac807d989a314a95deca718a3104",
"tests/test_gateway_emotion.py": "b4123066d3b50220825bf83aa3e96950a02d091d522f08085fb293d29f9706cf",
"tests/test_gateway_reply_face.py": "393c95b7e97981b46445cd699890bb7b732d1c479310daf09bdf2c8349e47f4c",
"tests/test_guests.py": "6bc531f1bff85b8ea550bc88c634726531a1ef241ba5c861dbb8c963adf31c35",
"tests/test_history.py": "fc13a69811cfc4f4acf265ea9e0cdd67d566358ebe9b9b53cae76197db8bce78",
"tests/test_llm_provider.py": "9395b0f1da36a09aebcc9c2d7c151328526449c1bcedbb5f97a190d0fc5573df",
"tests/test_personas.py": "013b18e7b7f0e582d8d7e04f5b1fb78009e993f96357be67a5367e70444b43e1",
"tests/test_presence.py": "c8e804680d99f05174d3feea32a4a7ecac7d49143fed897a107ff3d5dbacad86",
"tests/test_reply_emotion.py": "4ff2774187df8220ddbc8ef5b79910ae5047af3bacdb9476b0d2a8f55929d3be",
"tests/test_segmentation.py": "cf80a74958a715a81180a7932efb84f1d0974b434cf4fc3354b68c604ccbf463",
"tests/test_server_clock.py": "b7e91ff717fbdcb76984829bd7b184b4633f80dc01637cff33cc0d90363a9518",
"tests/test_v08.py": "f993d4162576494e814786f26376ba80ab8a77af98ba70de4379055bb9525082",
"tests/test_vad.py": "bff64c0aafa05c085af7c1c9418244609129d405320fe1080b4ba05a8e304228",
"tests_fake.py": "9a40f1948352f69f1dd20f8514baef58ae3d11eec240e1d2324d8990bad915d8",
"tts_debug.py": "d7b31b98a7f8ab688981873ef81decdf0b2f0167113c9103df039b7b24c9ccf2",
"vad.py": "3718ff9b296b2bba447100af520a631f221dcbfa322dd564cdc5809fb3675f23"
},
"backup": "/home/gorios-spark-2/lan-voice/.runtime/backups/voice-gateway-20261013-162856"
},
"server_capabilities": {
"structured_output_env": "LAN_LLM_STRUCTURED_OUTPUT",
"modes": [
"prompt",
"json_schema"
],
"verified_default": {
"base_url": "http://127.0.0.1:8888/v1",
"model": "qwen3.8-27b",
"chat_template_kwargs": {
"enable_thinking": false
}
},
"doubao_schema_verified": false,
"time_zone": "Asia/Shanghai",
"action_protocol": 1,
"ordered_expression": "strict schema prefix preload only; final authoritative",
"action_default": "unavailable until exact independently reviewed pack negotiation",
"reviewed_action_pack": "987e125a7d7a2cde99121b5f5246c82f4dbe36c4899d3d49eaffd1a68bafb887",
"presence_greeting_version": 1
},
"previous_deployment_baseline": {
"source": "startup capabilities update; live gateway-only hash-fenced deployment",
"files": {
"action_protocol.py": "04c65ce27140da7757e0164983efe33800dddcff0139d16e8fe4c8a99a3b50ee",
@@ -438,65 +514,5 @@
"tts_debug.py": "d7b31b98a7f8ab688981873ef81decdf0b2f0167113c9103df039b7b24c9ccf2",
"vad.py": "3718ff9b296b2bba447100af520a631f221dcbfa322dd564cdc5809fb3675f23"
}
},
"server_capabilities": {
"structured_output_env": "LAN_LLM_STRUCTURED_OUTPUT",
"modes": [
"prompt",
"json_schema"
],
"verified_default": {
"base_url": "http://127.0.0.1:8888/v1",
"model": "qwen3.8-27b",
"chat_template_kwargs": {
"enable_thinking": false
}
},
"doubao_schema_verified": false,
"time_zone": "Asia/Shanghai",
"action_protocol": 1,
"ordered_expression": "strict schema prefix preload only; final authoritative",
"action_default": "unavailable until exact independently reviewed pack negotiation",
"reviewed_action_pack": "987e125a7d7a2cde99121b5f5246c82f4dbe36c4899d3d49eaffd1a68bafb887"
},
"previous_deployment_baseline": {
"release": "gateway-0.8.0 / Android-0.7.0-stage-dev-code16",
"files": {
"action_protocol.py": "6e312aaa3736b99c24215512187a16689d4a5af8635b29bbc13c7cc1e002bace",
"action_reply.py": "4d66164a6668a571dc861282a5c80e408b51dfcfd67f45141e8c6701f6b81364",
"app.py": "d6520894dfbe035f64b1984aae15976db4df0e7e720195c81d3bf483b240056f",
"face_context.py": "d032ff8033a49219595d6edff2950856937e024782143621d37d02b56b024315",
"gateway.py": "fc4f53494ff253e5016c4e951ece462ae63b0b8567f0633654bce0eb74042b07",
"guest_sessions.py": "cc082fdb6c2ff7f5a41361ffe9ea2a53ebb944ee37354f65119405ad7a521c82",
"history.py": "0015b3143268f3e22a8a8a53b65ef4e3522f1f881dfca213c93142899c02631e",
"llm_provider.py": "b3cf6ab5e4c953ef13dc00802f4594055164c89b10b875dda44f071ad1ede082",
"persona_resolver.py": "deb33b4f4c17792fa5a6837362d5b29173e60a57bb993b61363bd4882d66d5de",
"personas/lvbu.lorebook.json": "1f144b431bdd5d9cda0ce593438fa88e717c0671d496105883a3d4db7bd635ea",
"personas/yangmi.lorebook.json": "73badae3fd8582555caa338e50fb6193e64e6a43025dd469672aa903c1c4b71b",
"protocol.py": "d9f522d958935200002e56024949a12b71eb89b3f3241635c5c307b798ee71c5",
"reply_emotion.py": "080f04e368c5a7d26254f2b870803238941aa481d457227ba15a870fd4a4e3c0",
"segmentation.py": "562ffc6e06f5b9f9072860b588feae3a5d7cd6eaa8577ac928d770071b06978d",
"server_clock.py": "dc46d79fd43c8b94f52acfdea0564058c47f3a3b8b43aa53fe6868a1821f3a0e",
"tests/test_action_protocol.py": "2e19bb1471a2bab67bfb7adca1630151d466e50d9ebc103e54c2f92566f63b63",
"tests/test_action_reply.py": "0c40a937be4c6545e04ed2268df1714c34dce982058f6b19daabf06b0fa30932",
"tests/test_continuity.py": "d8390238f390463a98f12b9909bb5846be65f5b6dc1b21b94338b4cd75aaafae",
"tests/test_debug.py": "7d1d7876c4106f3df0b84cf8f7e479afb4a30ca51264fb94fa288fdd8155883e",
"tests/test_face_context.py": "c297866117fa7406b5fda95250b67ca7ebd7476486ddd5455935c140d31c9f6f",
"tests/test_gateway.py": "f22aa98f3d6f62a2949a9047ec97e6dd686cac807d989a314a95deca718a3104",
"tests/test_gateway_emotion.py": "b4123066d3b50220825bf83aa3e96950a02d091d522f08085fb293d29f9706cf",
"tests/test_gateway_reply_face.py": "393c95b7e97981b46445cd699890bb7b732d1c479310daf09bdf2c8349e47f4c",
"tests/test_guests.py": "6bc531f1bff85b8ea550bc88c634726531a1ef241ba5c861dbb8c963adf31c35",
"tests/test_history.py": "fc13a69811cfc4f4acf265ea9e0cdd67d566358ebe9b9b53cae76197db8bce78",
"tests/test_llm_provider.py": "9395b0f1da36a09aebcc9c2d7c151328526449c1bcedbb5f97a190d0fc5573df",
"tests/test_personas.py": "013b18e7b7f0e582d8d7e04f5b1fb78009e993f96357be67a5367e70444b43e1",
"tests/test_reply_emotion.py": "4ff2774187df8220ddbc8ef5b79910ae5047af3bacdb9476b0d2a8f55929d3be",
"tests/test_segmentation.py": "cf80a74958a715a81180a7932efb84f1d0974b434cf4fc3354b68c604ccbf463",
"tests/test_server_clock.py": "b7e91ff717fbdcb76984829bd7b184b4633f80dc01637cff33cc0d90363a9518",
"tests/test_v08.py": "f993d4162576494e814786f26376ba80ab8a77af98ba70de4379055bb9525082",
"tests/test_vad.py": "bff64c0aafa05c085af7c1c9418244609129d405320fe1080b4ba05a8e304228",
"tests_fake.py": "9a40f1948352f69f1dd20f8514baef58ae3d11eec240e1d2324d8990bad915d8",
"tts_debug.py": "d7b31b98a7f8ab688981873ef81decdf0b2f0167113c9103df039b7b24c9ccf2",
"vad.py": "3718ff9b296b2bba447100af520a631f221dcbfa322dd564cdc5809fb3675f23"
}
}
}
+140 -8
View File
@@ -20,8 +20,9 @@ import uuid
from history import History
from face_context import FaceContext
from reply_emotion import SYSTEM_FRAGMENT, parse_reply
from action_reply import ACTION_FRAGMENT, ExpressionPrefix, parse_action_reply
from action_reply import ACTION_FRAGMENT, ExpressionPrefix, parse_action_reply, ActionReply, unique_object
from action_protocol import ActionPlans, negotiate, configured_packs, pending_pin
from presence import PresenceRequests, COOLDOWNS, INTENTS, restrict_action_schema
from guest_sessions import GuestSessions, COOKIE
from tts_debug import DebugStore
from persona_resolver import resolve_persona
@@ -32,7 +33,7 @@ from protocol import WavStream, pack, unpack
from vad import Config, Silero, VadSession
ROOT = Path(__file__).resolve().parent
VERSION = '0.8.0'
VERSION = '0.8.1'
DEFAULT_VOICE_ID = '9a97272c-3919-5606-9c8f-9552ab602528'
ORIGINS = {'https://192.168.31.61:5011', 'https://localhost:5011', 'https://127.0.0.1:5011'}
@@ -240,6 +241,10 @@ class Dialogue:
self.action_expiry_task = None
self.action_holding = False
self.followup_pending = None
self.presence = PresenceRequests()
self.presence_spoken = None
self.last_input_at = 0.0
self.last_voice_at = time.monotonic()
self.capture_offset = 0
self.received_samples = 0
self.vad = VadSession(model, Config(max_session_seconds=600))
@@ -275,8 +280,10 @@ class Dialogue:
self.down_seq += 1
await asyncio.wait_for(self.ws.send_bytes(pack(2, turn, self.down_seq, pcm)), 5)
async def invalidate(self, reason, preserve_vad=False):
async def invalidate(self, reason, preserve_vad=False, presence_request_id=None):
old_turn = self.turn
self.presence.retire()
self.presence_spoken = None
self.action_plans.clear()
self.action_holding = False
self.followup_pending = None
@@ -309,7 +316,8 @@ class Dialogue:
self.playback_waiting = False
self.up_seq = 0
self.down_seq = 0
await self.event('abort', reason=reason, accepted_input_samples=self.received_samples)
await self.event('abort', reason=reason, accepted_input_samples=self.received_samples,
**({'request_id': presence_request_id} if presence_request_id is not None else {}))
async def listen(self, mode, enabled=True, barge=True, start_windows=3):
if mode not in ('auto', 'manual'): raise ValueError('listen mode')
@@ -336,6 +344,7 @@ class Dialogue:
if seq != self.up_seq + 1: raise ValueError('sequence gap')
self.up_seq = seq
self.received_samples += len(pcm) // 2
self.last_input_at = time.monotonic()
responding = (self.task is not None and not self.task.done()) or self.playback_waiting
if responding and not self.barge:
return
@@ -346,7 +355,10 @@ class Dialogue:
self.listening = False
await self.submit(bytes(self.capture[:960000]), 480000)
return
was_voice = self.vad.active or bool(self.vad.positive)
events = await asyncio.to_thread(self.vad.feed, pcm)
if was_voice or self.vad.active or self.vad.positive or self.vad.candidate is not None:
self.last_voice_at = time.monotonic()
for ev in events:
if ev['type'] == 'speech.start':
if responding:
@@ -413,6 +425,11 @@ class Dialogue:
async def drained(self):
self.pending_drained = None
self.playback_waiting = False
if self.presence_spoken and self.presence_spoken[0] == self.turn:
_, rid, text = self.presence_spoken
self.presence_spoken = None
if self.history: await self.history.spoken(self.conversation_id, rid, text)
self.presence.retire('completed')
if self.followup_pending and self.followup_pending[0] == self.turn:
_, rid, text = self.followup_pending
self.followup_pending = None
@@ -503,15 +520,20 @@ class Dialogue:
if turn == self.turn and not self.closed and self.pending_drained == turn:
await self.drained()
async def generate(self, turn, text, queue, metrics, began):
async def generate(self, turn, text, queue, metrics, began, presence_kind=None):
request_start = time.perf_counter()
capability = self.action_capability # Request snapshot: readiness never changes an in-flight answer.
capability = None if presence_kind else self.action_capability # Frozen for this request.
metrics.update(voice_mode=self.voice_mode, voice_id=self.voice_id, tts_request_count=0)
# Exactly one initial system: Qwen's deployed template rejects a second system.
system = '以下角色设定只约束reply字段的可朗读正文。\n' + self.persona_rules + ''.join(
'\n\n' + item['content'] for item in self.face_messages.get(turn, [])) + '\n\n' + SYSTEM_FRAGMENT + '\n' + ACTION_FRAGMENT + '\n网关实际可用动作:' + ('dance' if capability else '无')
if presence_kind:
system = system.replace(ACTION_FRAGMENT, '外层字段按emotion、intensity、reply、action、after_action顺序输出;reply简短,action=null,after_action=null。')
messages = [{'role': 'system', 'content': system}] + self.contexts.get(turn, []) + [{'role': 'user', 'content': text}]
if presence_kind:
messages[0]['content'] += '\n本轮是本地布尔事件触发,不是用户发言;只自然简短回应此意图,不要求动作,action和after_action必须null。'
url, headers, body = self.llm_provider.request(messages, max_tokens=160, action_plan=True)
if presence_kind: restrict_action_schema(body)
metrics['llm_request_count'] = 1
raw_body = ''
prefix = ExpressionPrefix(turn)
@@ -550,7 +572,16 @@ class Dialogue:
if turn != self.turn: return
if not raw_body.strip(): raise ValueError('empty LLM body')
parse_start = time.perf_counter()
plan = parse_action_reply(raw_body, finish_reason, bool(capability))
if presence_kind:
data = json.loads(raw_body, object_pairs_hook=unique_object)
if (not isinstance(data, dict) or set(data) != {'reply', 'emotion', 'intensity', 'action', 'after_action'} or
data['action'] is not None or data['after_action'] is not None or finish_reason == 'length'):
raise ValueError('presence_envelope')
speech = parse_reply(json.dumps({k: data[k] for k in ('reply', 'emotion', 'intensity')}), finish_reason)
if speech.source != 'model': raise ValueError('presence_expression')
plan = ActionReply(speech, action_reason='presence_none')
else:
plan = parse_action_reply(raw_body, finish_reason, bool(capability))
result = plan.speech
metrics['action_reason'] = plan.action_reason
metrics['expression_prepare_mode'] = 'schema_prefix_preload' if prepare_enabled else 'full_reply'
@@ -647,6 +678,101 @@ class Dialogue:
if turn == self.turn and not self.closed and self.pending_drained == turn:
await self.drained()
async def presence_event(self, data):
parsed = PresenceRequests.parse(data)
request = data.get('request_id', 0)
request = request if type(request) is int and 1 <= request <= 0xffffffff else 0
async def status(state, reason):
await self.event('presence.status', version=1, request_id=request, state=state, reason=reason)
if parsed is None:
await status('rejected', 'invalid_fields'); return
request, kind = parsed
if request in self.presence.seen:
await status(*self.presence.seen[request]); return
if request <= self.presence.highest:
await status('rejected', 'old_id'); return
self.presence.highest = request
now = time.monotonic()
reason = None
if not self.presence.supported: reason = 'unsupported'
elif data['turn_id'] != self.turn: reason = 'old_turn'
elif self.closed or not self.listening or self.mode != 'auto' or not self.barge: reason = 'not_listening'
elif (self.presence.active or self.presence.reserving or self.playback_waiting or self.action_holding or
self.action_plans.ticket is not None or self.followup_pending or
self.task is not None and not self.task.done()): reason = 'busy'
elif (now-self.last_input_at > 1.5 or now-self.last_voice_at < .8 or
self.vad.active or self.vad.positive or self.vad.candidate is not None or self.start is not None): reason = 'voice_or_stale_input'
elif not COOLDOWNS.allowed(self.owner, kind, now): reason = 'cooldown'
if reason:
self.presence.record(request, 'rejected', reason)
await status('rejected', reason); return
# Reserve before any socket/history await; both trigger types share one slot.
self.presence.reserving = True
self.presence.record(request, 'accepted', 'accepted')
COOLDOWNS.accept(self.owner, kind, now)
try:
await self.invalidate('presence_greeting', presence_request_id=request)
if self.closed: return
if self.presence.seen.get(request, ('', ''))[0] == 'cancelled':
await self.event('listen', state='resumed', mode=self.mode); return
turn = self.turn
self.presence.active = (request, turn, kind)
self.run_id = str(uuid.uuid4())
await status('accepted', 'accepted')
if self.closed or self.presence.active != (request, turn, kind): return
await self.event('speech.start', origin='presence', presence_kind=kind)
if self.closed or self.presence.active != (request, turn, kind): return
self.task = asyncio.create_task(self.run_presence(turn, kind))
finally:
self.presence.reserving = False
async def presence_cancel(self, data):
parsed = PresenceRequests.parse(data, cancel=True)
if parsed is None: return
request, _ = parsed
active = self.presence.active
if active and active[0] == request and active[1] == self.turn:
await self.invalidate('presence_cancelled')
await self.event('listen', state='resumed', mode=self.mode)
elif self.presence.reserving and self.presence.seen.get(request) == ('accepted', 'accepted'):
self.presence.record(request, 'cancelled', 'cancelled')
previous = self.presence.seen.get(request, ('rejected', 'unknown_request'))
await self.event('presence.status', version=1, request_id=request, state=previous[0], reason=previous[1])
async def run_presence(self, turn, kind):
began = time.perf_counter(); rid = self.run_id
metrics = {'origin': 'presence', 'presence_kind': kind, 'asr_request_count': 0,
'debug_enabled_for_turn': False}
self.answers[turn] = ''
completed = False
try:
async with asyncio.timeout(90):
if self.history: self.contexts[turn] = await self.history.context(self.conversation_id, rid)
if turn != self.turn: return
self.playback_waiting = True
await self.event('tts', turn, state='start', sample_rate=48000, codec='pcm16', frame_duration=20)
queue = asyncio.Queue(2)
async with asyncio.TaskGroup() as group:
group.create_task(self.generate(turn, INTENTS[kind], queue, metrics, began, presence_kind=kind))
group.create_task(self.synthesize(turn, queue, metrics, began))
if turn != self.turn: return
self.presence_spoken = (turn, rid, self.answers[turn])
await self.event('metrics', turn, values=metrics)
await self.event('tts', turn, state='stop')
completed = True
except asyncio.CancelledError:
raise
except Exception:
if turn == self.turn:
await self.event('error', turn, code='presence_failed', message='Proactive speech failed')
await self.event('tts', turn, state='stop')
finally:
self.answers.pop(turn, None); self.contexts.pop(turn, None)
if turn == self.turn:
if not completed:
self.presence_spoken = None; self.presence.retire('failed')
if not self.closed and self.pending_drained == turn: await self.drained()
async def synthesize(self, turn, queue, metrics, began):
sentence = 0
previous_end = None
@@ -715,6 +841,7 @@ class Dialogue:
async def close(self):
self.closed = True
self.presence.retire(); self.presence_spoken = None
self.action_plans.clear()
self.followup_pending = None
self.action_holding = False
@@ -768,6 +895,7 @@ async def dialogue(ws: WebSocket):
session.owner = owner or 'admin'
session.action_plans = ActionPlans(session.owner, session.connection_generation)
session.action_capability = negotiate(hello, configured_packs())
session.presence.supported = type(hello.get('presence_greeting_version')) is int and hello.get('presence_greeting_version') == 1
session.pending_action_pin = pending_pin(hello, configured_packs())
if owner: session.auth_check = lambda: bool(app.state.guests.get(owner))
voice_mode = hello.get('voice_mode', 'continuous_voice')
@@ -783,7 +911,7 @@ async def dialogue(ws: WebSocket):
session.voice_id = voice_id
session.debug_store = app.state.debug
session.debug_enabled = hello.get('tts_debug', True) is True
await session.event('hello', action_protocol=1, action_available=bool(session.action_capability), action_pending=bool(session.pending_action_pin), context_face_cue_version=1, reply_emotion_version=1, llm_structured_output=session.llm_provider.structured_output, 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', presence_greeting_version=1, action_protocol=1, action_available=bool(session.action_capability), action_pending=bool(session.pending_action_pin), context_face_cue_version=1, reply_emotion_version=1, llm_structured_output=session.llm_provider.structured_output, 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.send_history()
started = time.monotonic()
while time.monotonic() - started < 600:
@@ -803,6 +931,10 @@ async def dialogue(ws: WebSocket):
session.face_context.clear('input_limit')
else:
session.face_context.update(data, session.turn)
elif data.get('type') in ('presence.absent', 'presence.appeared'):
await session.presence_event(data)
elif data.get('type') == 'presence.cancel':
await session.presence_cancel(data)
elif data.get('type') == 'debug':
action = data.get('action', 'list')
if action == 'set': session.debug_enabled = data.get('enabled') is True
+53
View File
@@ -0,0 +1,53 @@
"""Typed local-camera triggers. No images, identity, text or durable presence records."""
from collections import OrderedDict
INTENTS = {
'absent': '本地检测提示用户离开画面约20s,可能误判;按当前persona自然简短地问一句去哪了/还聊吗,不断言身份/心情。',
'appeared': '本地检测提示有人重新出现在画面,可能误判;按当前persona自然简短打招呼,不断言身份/心情/离开时长。',
}
class PresenceCooldowns:
def __init__(self): self.values = OrderedDict()
def allowed(self, owner, kind, now): return now >= self.values.get((owner, kind), 0)
def accept(self, owner, kind, now):
key = (owner, kind)
self.values[key] = now + (600 if kind == 'appeared' else 20)
self.values.move_to_end(key)
while len(self.values) > 128: self.values.popitem(last=False)
COOLDOWNS = PresenceCooldowns()
def restrict_action_schema(body):
"""Only this request's provider-generated schema; model/time/voice params unchanged."""
if 'response_format' in body:
props = body['response_format']['json_schema']['schema']['properties']
props['action'] = {'type': 'null'}
props['after_action'] = {'type': 'null'}
class PresenceRequests:
def __init__(self):
self.supported = False
self.seen = OrderedDict()
self.highest = 0
self.active = None # (request_id, new_turn, kind); one authenticated socket.
self.reserving = False
@staticmethod
def parse(data, cancel=False):
fields = {'type', 'version', 'request_id'}
if not cancel: fields |= {'turn_id', 'present', 'age_ms'}
if not isinstance(data, dict) or set(data) != fields: return None
if type(data['version']) is not int or data['version'] != 1: return None
if type(data['request_id']) is not int or not 1 <= data['request_id'] <= 0xffffffff: return None
if cancel: return (data['request_id'], None) if data['type'] == 'presence.cancel' else None
kind = {'presence.absent': 'absent', 'presence.appeared': 'appeared'}.get(data['type'])
if kind is None or type(data['present']) is not bool or data['present'] != (kind == 'appeared'): return None
if type(data['turn_id']) is not int or not 0 <= data['turn_id'] <= 0xffffffff: return None
if type(data['age_ms']) is not int or not 0 <= data['age_ms'] <= 1500: return None
return data['request_id'], kind
def record(self, request, state, reason):
self.seen[request] = (state, reason)
while len(self.seen) > 32: self.seen.popitem(last=False)
def retire(self, state='cancelled'):
if self.active:
self.record(self.active[0], state, state)
self.active = None
+193
View File
@@ -0,0 +1,193 @@
import asyncio
import contextlib
import io
import json
import tempfile
import time
import unittest
import wave
from pathlib import Path
from unittest.mock import patch
import httpx
from fastapi.testclient import TestClient
from gateway import Dialogue, app
from guest_sessions import GuestSessions
from history import History
from presence import PresenceRequests, PresenceCooldowns, INTENTS, COOLDOWNS
from protocol import pack
from tests_fake import FakeModel
from test_gateway import Socket
def trigger(kind='absent', request=1, turn=0):
return dict(type='presence.'+kind,version=1,request_id=request,turn_id=turn,present=kind=='appeared',age_ms=100)
def backend(calls, raw=None):
def respond(request):
calls.append(request)
if request.url.port == 8888:
text = raw or json.dumps(dict(emotion='happy',intensity=1,reply='公开合成问候。',action=None,after_action=None))
return httpx.Response(200,text='data: '+json.dumps({'choices':[{'delta':{'content':text},'finish_reason':'stop'}]})+'\n\ndata: [DONE]\n\n')
if request.url.port == 5002:
out=io.BytesIO()
with wave.open(out,'wb') as w:
w.setnchannels(1);w.setsampwidth(2);w.setframerate(48000);w.writeframes(bytes(3840))
return httpx.Response(200,content=out.getvalue())
raise AssertionError('ASR/other request forbidden')
return respond
def eligible(d):
d.presence.supported=True;d.listening=True
d.last_input_at=time.monotonic();d.last_voice_at=time.monotonic()-1
class PresenceTests(unittest.IsolatedAsyncioTestCase):
def setUp(self): COOLDOWNS.values.clear()
def test_strict_fields_and_nulls(self):
for kind in ('absent','appeared'):
good=trigger(kind);self.assertIsNotNone(PresenceRequests.parse(good))
for bad in ({**good,'present':not good['present']},{**good,'age_ms':1501},{**good,'age_ms':True},
{**good,'version':True},{**good,'request_id':0},{**good,'turn_id':-1},{**good,'text':'ignored'}):
self.assertIsNone(PresenceRequests.parse(bad))
self.assertIsNone(PresenceRequests.parse(dict(type='presence.cancel',version=1,request_id=1,turn_id=0),True))
def test_cooldowns_independent_and_bounded(self):
c=PresenceCooldowns();c.accept('same','appeared',10)
self.assertFalse(c.allowed('same','appeared',609.999));self.assertTrue(c.allowed('same','appeared',610))
self.assertTrue(c.allowed('same','absent',11));c.accept('same','absent',11)
self.assertFalse(c.allowed('same','absent',30.999));self.assertTrue(c.allowed('same','absent',31))
for i in range(200):c.accept(str(i),'absent',100)
self.assertLessEqual(len(c.values),128)
async def test_both_kinds_one_llm_one_tts_no_asr_null_schema_assistant_only_after_real_drain(self):
for kind in ('absent','appeared'):
with self.subTest(kind=kind),tempfile.TemporaryDirectory() as folder:
calls=[];history=History(Path(folder)/'public.sqlite3');await history.initialize();cid=await history.conversation()
async with httpx.AsyncClient(transport=httpx.MockTransport(backend(calls))) as client:
d=Dialogue(Socket(),FakeModel(),client,history,cid);eligible(d);d.persona_rules='公开测试角色设定';d.debug_enabled=True
await d.presence_event(trigger(kind));await d.task
self.assertEqual([r.url.port for r in calls],[8888,5002]);self.assertEqual(await history.rows(cid),[])
body=json.loads(calls[0].content);props=body['response_format']['json_schema']['schema']['properties']
self.assertEqual(props['action'],{'type':'null'});self.assertEqual(props['after_action'],{'type':'null'})
self.assertEqual(sum(m['role']=='system' for m in body['messages']),1)
self.assertIn('公开测试角色设定',body['messages'][0]['content']);self.assertEqual(body['messages'][-1]['content'],INTENTS[kind])
self.assertEqual(body['max_tokens'],160);self.assertIsNone(d.action_plans.ticket);self.assertEqual(d.debug_captures,{})
metrics=[e['values'] for e in d.ws.events if e['type']=='metrics'][-1]
self.assertEqual((metrics['asr_request_count'],metrics['llm_request_count'],metrics['tts_request_count']),(0,1,1))
turn=d.turn;await d.request_drained(turn)
rows=await history.rows(cid);self.assertEqual([r['role'] for r in rows],['assistant']);self.assertEqual(rows[0]['playback'],'confirmed')
await d.request_drained(turn);self.assertEqual(len(await history.rows(cid)),1)
await d.presence_event(trigger(kind));self.assertEqual(len(calls),2)
self.assertIsNone(d.presence.active);await d.close()
async def test_active_departure_drops_return_and_reverse_order(self):
for first,second in (('absent','appeared'),('appeared','absent')):
calls=[]
async with httpx.AsyncClient(transport=httpx.MockTransport(backend(calls))) as client:
d=Dialogue(Socket(),FakeModel(),client);eligible(d)
await d.presence_event(trigger(first));await d.task
await d.presence_event(trigger(second,2,d.turn))
self.assertEqual(d.ws.events[-1]['reason'],'busy');self.assertEqual(len(calls),2)
await d.close()
async def test_busy_vad_modes_old_turn_invalid_never_generate(self):
variants=[('active',lambda d:setattr(d.vad,'active',True)),('positive',lambda d:setattr(d.vad,'positive',1)),
('candidate',lambda d:setattr(d.vad,'candidate',0)),('voice',lambda d:setattr(d,'last_voice_at',time.monotonic())),
('input',lambda d:setattr(d,'last_input_at',0)),('manual',lambda d:setattr(d,'mode','manual')),
('drain',lambda d:setattr(d,'playback_waiting',True)),('after',lambda d:setattr(d,'followup_pending',(0,'id','public'))),
('music',lambda d:setattr(d,'action_holding',True)),('off',lambda d:setattr(d.presence,'supported',False))]
for _,alter in variants:
d=Dialogue(Socket(),FakeModel(),None);eligible(d);alter(d)
await d.presence_event(trigger());self.assertIsNone(d.task);self.assertEqual(d.turn,0);await d.close()
d=Dialogue(Socket(),FakeModel(),None);eligible(d)
await d.presence_event(trigger(turn=1));self.assertEqual(d.ws.events[-1]['reason'],'old_turn')
await d.presence_event({**trigger(request=2),'private':'forbidden'});self.assertEqual(d.ws.events[-1]['reason'],'invalid_fields');await d.close()
async def test_cancel_and_user_turn_no_speech_revive_or_history(self):
entered=asyncio.Event();release=asyncio.Event();calls=[]
async def waiting(request):
calls.append(request.url.port);entered.set();await release.wait()
return backend([])(request)
async with httpx.AsyncClient(transport=httpx.MockTransport(waiting)) as client:
d=Dialogue(Socket(),FakeModel(),client);eligible(d)
await d.presence_event(trigger());await asyncio.wait_for(entered.wait(),2)
await d.presence_cancel(dict(type='presence.cancel',version=1,request_id=9));self.assertEqual(d.turn,1)
await d.presence_cancel(dict(type='presence.cancel',version=1,request_id=1));turn=d.turn
await d.presence_cancel(dict(type='presence.cancel',version=1,request_id=1));self.assertEqual(d.turn,turn)
release.set();await asyncio.sleep(0);self.assertIsNone(d.presence_spoken);self.assertFalse(d.ws.frames)
self.assertEqual(calls,[8888]);await d.close()
async def test_concurrent_reservation_and_duplicate_id(self):
d=Dialogue(Socket(),FakeModel(),None);eligible(d)
async def simulated_run(*args): await asyncio.sleep(.01)
with patch.object(d,'run_presence',new=simulated_run):
await asyncio.gather(d.presence_event(trigger()),d.presence_event(trigger('appeared',2)))
await d.task
self.assertEqual(d.turn,1);self.assertEqual(len([e for e in d.ws.events if e['type']=='speech.start']),1)
await d.presence_event(trigger());self.assertEqual(d.turn,1)
await d.close()
async def test_bad_action_is_rejected_without_fixed_fallback_or_tts(self):
calls=[];raw=json.dumps(dict(emotion='happy',intensity=1,reply='公开正文',action='dance',after_action=None))
async with httpx.AsyncClient(transport=httpx.MockTransport(backend(calls,raw))) as client:
d=Dialogue(Socket(),FakeModel(),client);eligible(d);await d.presence_event(trigger());await d.task
self.assertEqual([r.url.port for r in calls],[8888]);self.assertIsNone(d.presence_spoken);self.assertFalse(d.ws.frames)
self.assertTrue(any(e['type']=='error' for e in d.ws.events));await d.close()
async def test_voice_barge_prioritizes_new_capture_and_retires_request(self):
calls=[]
class SpeechModel(FakeModel):
def infer(self,pcm,state): return (.9 if pcm[0] else 0.0),state
async with httpx.AsyncClient(transport=httpx.MockTransport(backend(calls))) as client:
d=Dialogue(Socket(),SpeechModel(),client);eligible(d);await d.presence_event(trigger());await d.task
old=d.turn
for seq in range(1,9):await d.input(pack(1,old,seq,bytes([255,127])*320))
self.assertGreater(d.turn,old);self.assertIsNone(d.presence.active);self.assertIsNone(d.presence_spoken)
self.assertTrue(any(e.get('reason')=='voice_barge_in' for e in d.ws.events));await d.close()
class PresenceWsTests(unittest.TestCase):
def test_real_ws_routes_negotiation_two_kinds_and_cancel(self):
COOLDOWNS.values.clear()
calls=[]
# Real ASGI WS route, public synthetic inputs, model/TTS HTTP doubles only.
async_client=httpx.AsyncClient(transport=httpx.MockTransport(backend(calls)))
with tempfile.TemporaryDirectory() as folder:
history=History(Path(folder)/'public.sqlite3');asyncio.run(history.initialize())
state=app.state
state.busy=False;state.token='synthetic-presence-auth-'+('x'*24);state.model=FakeModel();state.client=async_client
state.history=history;state.guests=GuestSessions();state.guest_enabled=False;state.lan_open=False;state.debug=None
import gateway
state.voices=[dict(id=gateway.DEFAULT_VOICE_ID,source='registered_reference',default=True)]
client=TestClient(app) # No app lifespan: no model load or live services.
original=Dialogue.presence_event
async def clock_fixture(d,data):
d.last_voice_at=time.monotonic()-1 # Explicit quiet-window clock fixture.
await original(d,data)
with patch('gateway.load_active_profile',return_value=None),patch.object(Dialogue,'presence_event',clock_fixture):
def receive(ws,kind):
for _ in range(100):
message=ws.receive()
if message.get('text'):
event=json.loads(message['text'])
if event['type']==kind:return event
raise AssertionError('bounded route event not received')
with client.websocket_connect('/ws/dialogue',headers={'Origin':'https://192.168.31.61:5011'}) as ws:
ws.send_json(dict(type='auth',token=state.token));self.assertEqual(receive(ws,'auth')['state'],'ok')
ws.send_json(dict(type='hello',codec='pcm16',sample_rate=16000,frame_duration=20,persona='default',tts_debug=False,presence_greeting_version=1))
self.assertEqual(receive(ws,'hello')['presence_greeting_version'],1)
ws.send_json(dict(type='listen',state='start',mode='auto',barge_in=True))
turn=receive(ws,'listen')['turn_id']
for seq in range(1,10):ws.send_bytes(pack(1,turn,seq,bytes(640)))
ws.send_json(trigger('absent',1,turn));ack=receive(ws,'presence.status');self.assertEqual(ack['state'],'accepted')
turn=ack['turn_id'];receive(ws,'tts')
while True:
e=receive(ws,'tts')
if e.get('state')=='stop':break
ws.send_json(dict(type='playback.drained',turn_id=turn));receive(ws,'listen')
# New turn epoch has independent uplink sequence.
ws.send_bytes(pack(1,turn,1,bytes(640)))
ws.send_json(trigger('appeared',2,turn));ack=receive(ws,'presence.status');self.assertEqual(ack['state'],'accepted')
turn=ack['turn_id']
while True:
e=receive(ws,'tts')
if e.get('state')=='stop':break
ws.send_json(dict(type='presence.cancel',version=1,request_id=2));ack=receive(ws,'presence.status');self.assertEqual(ack['state'],'cancelled')
cancelled_turn=ack['turn_id']
ws.send_json(dict(type='presence.cancel',version=1,request_id=2));self.assertEqual(receive(ws,'presence.status')['turn_id'],cancelled_turn)
self.assertEqual([r.url.port for r in calls],[8888,5002,8888,5002])
with client.websocket_connect('/ws/dialogue',headers={'Origin':'https://192.168.31.61:5011'}) as ws:
ws.send_json(dict(type='auth',token=state.token));receive(ws,'auth')
ws.send_json(dict(type='hello',codec='pcm16',sample_rate=16000,frame_duration=20,persona='default',tts_debug=False));receive(ws,'hello')
ws.send_json(trigger());self.assertEqual(receive(ws,'presence.status')['reason'],'unsupported')
asyncio.run(async_client.aclose())
+9 -1
View File
@@ -13,7 +13,15 @@ clean=re.sub(pattern,lambda m:' '*len(m[0]),source)
def block(marker,within=None):
start,end=within or (0,len(source))
at=clean.index(marker,start,end)
left=clean.index('{',at+len(marker),end)
body_at=at+len(marker)
if marker.startswith('fun '):
# Default callback lambdas belong to the parameter list, not the body.
params=clean.index('(',body_at,end)
depth=1;body_at=params+1
while depth:
assert body_at<end,'Unclosed Kotlin parameters'
depth+=(clean[body_at]=='(')-(clean[body_at]==')');body_at+=1
left=clean.index('{',body_at,end)
depth=1;right=left+1
while depth:
assert right<end,'Unclosed Kotlin block'
+1
View File
@@ -46,6 +46,7 @@ for name, main, real in suites:
with tempfile.TemporaryDirectory(prefix=f'lan-voice-{name}-') as out:
files = list((ROOT/'tests'/name).glob('*.kt')) + real
if name in ('session','avatar'): files.append(source/'diag/StartupTrace.kt')
if name in ('session','protocol'): files.append(source/'expression/PresenceRules.kt')
if name=='avatar': files += [source/'avatar/StartupAvatarView.kt',source/'avatar/StartupLoadCache.kt']
if name == 'avatar' and (args.runtime_manifest or args.index_manifest):
definitions=[]
+10 -8
View File
@@ -302,7 +302,7 @@ def verify_runtime_fix_assets(built,pin,startup_fix=False):
return len([p for p in paths(new) if p.startswith('assets/'+ASSET_ROOT)])
def publish(report,output,requested,full=False,runtime_fix=False,playback_diagnostic=False,playback_clock_fix=False,startup_fix=False):
def publish(report,output,requested,full=False,runtime_fix=False,playback_diagnostic=False,playback_clock_fix=False,startup_fix=False,presence_candidate=False):
require(all(edge.get('nativeLoop') is True or 'mouthRuntimeManifest' in edge for edge in read_json(ROOT/'app/src/main/assets'/ASSET_ROOT/'manifest.json')['edges']),
'live emotion release needs bridge-own TALK runtimes')
tested_source(full);packaging_tests_current();require(file_sha(ROLLBACK)==ROLLBACK_SHA,'rollback drift')
@@ -310,6 +310,7 @@ def publish(report,output,requested,full=False,runtime_fix=False,playback_diagno
if requested is not None:
require(requested>=version,'version code occupied');version=requested
require(not full or version>=18,'full candidate needs code >=18')
require(not presence_candidate or startup_fix and version>=23,'presence candidate needs startup and fresh code >=23')
require(not startup_fix or full and version>=22 and report['manifest_sha256']==RUNTIME_FIX_PIN,'startup fix release shape')
if startup_fix:
subprocess.run(['python3',str(ROOT/'scripts/prepare-startup-assets.py'),'--verify-only'],check=True)
@@ -318,9 +319,9 @@ def publish(report,output,requested,full=False,runtime_fix=False,playback_diagno
require(not runtime_fix or full and version>=19 and report['manifest_sha256']==RUNTIME_FIX_PIN,'runtime fix release shape')
subprocess.run([str(ROOT/'scripts/build.sh'),'assembleDebug','compileDebugAndroidTestKotlin','-PavatarActionCandidate=true',
'-PavatarNatural=true','-PavatarMouthCandidate=true','-PnaturalManifestSha='+LEGACY_PIN,
'-PemotionManifestSha='+report['manifest_sha256'],'-PactionVersionCode='+str(version),'-PavatarFullActionCandidate='+str(full).lower(),'-PavatarRuntimeFix='+str(runtime_fix).lower(),'-PavatarPlaybackDiagnostic='+str(playback_diagnostic).lower(),'-PavatarPlaybackClockFix='+str(playback_clock_fix or startup_fix).lower(),'-PavatarStartupFix='+str(startup_fix).lower()],check=True,cwd=ROOT)
'-PemotionManifestSha='+report['manifest_sha256'],'-PactionVersionCode='+str(version),'-PavatarFullActionCandidate='+str(full).lower(),'-PavatarRuntimeFix='+str(runtime_fix).lower(),'-PavatarPlaybackDiagnostic='+str(playback_diagnostic).lower(),'-PavatarPlaybackClockFix='+str(playback_clock_fix or startup_fix).lower(),'-PavatarStartupFix='+str(startup_fix).lower(),'-PpresenceCandidate='+str(presence_candidate).lower()],check=True,cwd=ROOT)
built=ROOT/'app/build/outputs/apk/debug/app-debug.apk';badge=badging(built)
version_name='0.7.4' if startup_fix else '0.7.3' if playback_clock_fix else '0.7.2' if playback_diagnostic else '0.7.1' if runtime_fix else ('0.7.0' if full else '0.7.0-emotion-dev')
version_name='0.7.5' if presence_candidate else '0.7.4' if startup_fix else '0.7.3' if playback_clock_fix else '0.7.2' if playback_diagnostic else '0.7.1' if runtime_fix else ('0.7.0' if full else '0.7.0-emotion-dev')
for text in ("name='com.gorios.lanvoice'",f"versionCode='{version}'",f"versionName='{version_name}'","sdkVersion:'26'","targetSdkVersion:'34'"):
require(text in badge,'APK metadata: '+text)
require(re.search(r'^native-code: (.+)$',badge,re.M)[1].strip()=="'arm64-v8a'",'APK ABI')
@@ -340,8 +341,8 @@ def publish(report,output,requested,full=False,runtime_fix=False,playback_diagno
if startup_fix: require('AVATAR_STARTUP_FIX = true' in config.read_text(),'compiled startup flag mismatch')
require(version>=next_version((ROOT/'artifacts').glob('*.apk')),'version became occupied during build')
if startup_fix or runtime_fix or playback_diagnostic or playback_clock_fix: require(verify_runtime_fix_assets(built,report['manifest_sha256'],startup_fix)==len(report['files']),'runtime fix file count')
stem='startup-fix' if startup_fix else 'playback-clock-fix' if playback_clock_fix else 'playback-diagnostic' if playback_diagnostic else 'runtime-fix' if runtime_fix else ('action-emotion' if full else 'emotion-candidate')
release='v074' if startup_fix else 'v073' if playback_clock_fix else 'v072' if playback_diagnostic else 'v071' if runtime_fix else 'v070'
stem='presence' if presence_candidate else 'startup-fix' if startup_fix else 'playback-clock-fix' if playback_clock_fix else 'playback-diagnostic' if playback_diagnostic else 'runtime-fix' if runtime_fix else ('action-emotion' if full else 'emotion-candidate')
release='v075' if presence_candidate else 'v074' if startup_fix else 'v073' if playback_clock_fix else 'v072' if playback_diagnostic else 'v071' if runtime_fix else 'v070'
artifact=ROOT/f'artifacts/lan-voice-{release}-{stem}-code{version}-arm64-debug.apk'
with artifact.open('xb') as f,built.open('rb') as source: shutil.copyfileobj(source,f)
digest=file_sha(artifact);checksum=f'{digest} {artifact.name}\n'.encode()
@@ -355,7 +356,7 @@ def publish(report,output,requested,full=False,runtime_fix=False,playback_diagno
'certificate_sha256':CERT,'manifest_sha256':report['manifest_sha256'],'dance_available':full,'action_count':report['action_count'],
'http_bytes_verified':True,'device':'not_run','naturalness':'not_certified','paid_calls':0,
'gateway_deployed':bool(full and read_json(ROOT/'logs/action-emotion/full-release/checks.json').get('gateway_deployed',False)),
'gateway_deployed_by_packager':False,'runtime_fix':runtime_fix,'diagnostic_only':playback_diagnostic,'playback_clock_fix':playback_clock_fix or startup_fix,'startup_fix':startup_fix,'runtime_files_unchanged_from_code18':len(report['files']) if startup_fix or runtime_fix or playback_diagnostic or playback_clock_fix else None}
'gateway_deployed_by_packager':False,'runtime_fix':runtime_fix,'diagnostic_only':playback_diagnostic,'playback_clock_fix':playback_clock_fix or startup_fix,'startup_fix':startup_fix,'presence_candidate':presence_candidate,'runtime_files_unchanged_from_code18':len(report['files']) if startup_fix or runtime_fix or playback_diagnostic or playback_clock_fix else None}
(output/'delivery.json').write_text(json.dumps(delivery,indent=2)+'\n')
return delivery
@@ -375,8 +376,9 @@ def main():
parser.add_argument('--playback-diagnostic',action='store_true',help='0.7.2 diagnostic-only Android build, frozen code18 avatar bytes')
parser.add_argument('--playback-clock-fix',action='store_true',help='0.7.3 Android MediaPlayer-output clock fix; exact frozen avatar bytes')
parser.add_argument('--startup-fix',action='store_true',help='0.7.4 immediate shell/background strict admission, exact frozen runtime plus tiny derived bootstrap')
parser.add_argument('--presence-candidate',action='store_true',help='0.7.5 presence-triggered assistant turns, frozen runtime and startup assets')
args=parser.parse_args();
require(sum((args.runtime_fix,args.playback_diagnostic,args.playback_clock_fix,args.startup_fix))<=1,'choose one build purpose')
require(sum((args.runtime_fix,args.playback_diagnostic,args.playback_clock_fix,args.startup_fix,args.presence_candidate))<=1,'choose one build purpose')
manifest=args.manifest.resolve(strict=True);output=args.output.resolve()
require(not output.exists() and not output.is_relative_to(manifest.parent),'new evidence outside owner root required')
if args.import_only or args.publish: require(args.pi_pin==args.sha256 and re.fullmatch('[0-9a-f]{64}',args.pi_pin or ''),'external Pi pin required')
@@ -393,7 +395,7 @@ def main():
require(not args.previous_pin and not args.backup,'previous import report required')
import_files(manifest.parent,report['files'],target)
(output/'import.json').write_text(json.dumps({'externally_pinned_sha256':args.pi_pin,'files':len(report['files']),'naturalness':'not_certified'})+'\n')
result=publish(report,output,args.version_code,bool(report['action_count']),args.runtime_fix,args.playback_diagnostic,args.playback_clock_fix,args.startup_fix) if args.publish else {k:v for k,v in report.items() if k!='files'}
result=publish(report,output,args.version_code,bool(report['action_count']),args.runtime_fix,args.playback_diagnostic,args.playback_clock_fix,args.startup_fix or args.presence_candidate,args.presence_candidate) if args.publish else {k:v for k,v in report.items() if k!='files'}
print(json.dumps(result,indent=2))
+21
View File
@@ -0,0 +1,21 @@
import importlib.util
from pathlib import Path
import unittest
from unittest.mock import patch
ROOT=Path(__file__).resolve().parents[2]
spec=importlib.util.spec_from_file_location('presence_package',ROOT/'scripts/package-avatar-emotion.py')
pack=importlib.util.module_from_spec(spec);spec.loader.exec_module(pack)
class PresencePackageTests(unittest.TestCase):
def test_fresh_presence_version_requires_startup_and_frozen_pack(self):
report={'manifest_sha256':pack.RUNTIME_FIX_PIN}
def stop_build(command,**kwargs):
if command[0]=='python3': return
self.assertIn('-PpresenceCandidate=true',command)
self.assertIn('-PavatarStartupFix=true',command)
self.assertIn('-PactionVersionCode=23',command)
raise RuntimeError('build_sentinel')
with patch.object(pack,'tested_source'),patch.object(pack,'packaging_tests_current'),patch.object(pack,'read_json',return_value={'edges':[{'nativeLoop':True}]}),patch.object(pack,'next_version',return_value=23),patch.object(pack.subprocess,'run',side_effect=stop_build):
with self.assertRaises(ValueError):pack.publish(report,None,23,full=True,presence_candidate=True)
with self.assertRaises(ValueError):pack.publish({**report,'manifest_sha256':'a'*64},None,23,full=True,startup_fix=True,presence_candidate=True)
with self.assertRaisesRegex(RuntimeError,'build_sentinel'):pack.publish(report,None,23,full=True,startup_fix=True,presence_candidate=True)
+9
View File
@@ -1,6 +1,15 @@
import com.gorios.lanvoice.net.DialogueProtocol
fun main() {
check("\"presence_greeting_version\":1" in DialogueProtocol.hello())
for(kind in com.gorios.lanvoice.expression.PresenceKind.entries) {
val wire=DialogueProtocol.presence(7,25,kind,100)
check("\"type\":\"presence.${kind.wire}\"" in wire)
check("\"present\":${kind==com.gorios.lanvoice.expression.PresenceKind.APPEARED}" in wire)
check("\"turn_id\":25" in wire && "\"age_ms\":100" in wire && wire.length<200)
}
for(id in listOf(0L,0x100000000L)) check(runCatching { DialogueProtocol.presenceCancel(id) }.isFailure)
check(runCatching { DialogueProtocol.presence(1,0,com.gorios.lanvoice.expression.PresenceKind.ABSENT,1501) }.isFailure)
val pending=DialogueProtocol.hello(null,"a".repeat(64))
check("action_pending_pack_sha256" in pending && "dance" !in pending)
val update=DialogueProtocol.capabilitiesReady("a".repeat(64))
+1
View File
@@ -491,6 +491,7 @@ fun runChecks() {
fun main() {
startupCapabilityCheck()
presenceCheck()
checkCallControls()
checkFaceTransmission()
run {
+87
View File
@@ -0,0 +1,87 @@
import com.gorios.lanvoice.expression.*
import com.gorios.lanvoice.audio.*
import com.gorios.lanvoice.net.*
import android.os.Handler
fun presenceCheck() {
var checks=0
fun expect(value: Boolean) { check(value) { "presence assertion $checks" };checks++ }
val rules=PresenceRules()
for(t in 0L..19_900L step 100) expect(rules.sample(false,t,1,true)==null)
expect(rules.sample(false,19_999,1,true)==null)
expect(rules.sample(false,20_000,1,true)?.kind==PresenceKind.ABSENT)
for(t in 20_100L..45_000L step 100) expect(rules.sample(false,t,1,true)==null)
expect(rules.sample(true,45_100,1,true)==null)
for(t in 45_200L..46_000L step 100) expect(rules.sample(true,t,1,true)==null)
expect(rules.sample(true,46_099,1,true)==null)
expect(rules.sample(true,46_100,1,true)?.kind==PresenceKind.APPEARED)
for(t in 46_200L..47_000L step 100) expect(rules.sample(true,t,1,true)==null)
for(t in 47_100L..67_000L step 100) expect(rules.sample(false,t,1,true)==null)
expect(rules.sample(false,67_100,1,true)?.kind==PresenceKind.ABSENT)
for(t in 67_200L..68_200L step 100) expect(rules.sample(true,t,1,false,absentInFlight=true)==null)
expect(rules.sample(true,68_300,1,true)==null) // No late return greeting after departure speech.
for(turnChanged in listOf(false,true)) {
val r=PresenceRules()
for(t in 0L..20_000L step 100) expect(r.sample(false,t,1,false)==null)
for(t in 20_100L..25_000L step 100) expect(r.sample(false,t,if(turnChanged) 2 else 1,false)==null)
expect(r.sample(false,25_100,if(turnChanged) 2 else 1,true)==null)
}
val gap=PresenceRules()
for(t in 0L..19_900L step 100) expect(gap.sample(false,t,1,true)==null)
expect(gap.sample(false,20_400,1,true)==null)
expect(gap.sample(null,20_500,1,true)==null)
expect(gap.sample(false,20_600,1,true)==null)
expect(gap.sample(false,20_600,1,true)==null)
gap.reset();expect(gap.sample(false,25_000,1,true)==null)
val cool=PresenceRules()
for(t in 0L..20_000L step 100) cool.sample(false,t,1,true)
for(t in 20_100L..21_100L step 100) expect(cool.sample(true,t,1,true,appearedAllowedAt=600_000)==null)
expect(cool.sample(true,21_200,1,true)==null)
checkPresenceSessionCallbacks()
println("PASS: $checks presence sample-boundary/episode/rearm/TTL/cooldown/UNKNOWN/gap/order assertions; production client callback/turn/cancel replay, device not_run")
}
private fun checkPresenceSessionCallbacks() {
val states=mutableListOf<VoiceUiState>();val session=VoiceSession("localhost",5011,states::add)
fun field(name: String,value: Any?) { session.javaClass.getDeclaredField(name).apply { isAccessible=true }.set(session,value) }
fun get(name: String)=session.javaClass.getDeclaredField(name).apply { isAccessible=true }.get(session)
val dialogue=get("dialogue") as DialogueClient
val socket=FakeSocket();dialogue.setField("socket",socket);dialogue.setField("ready",true)
field("foreground",true);field("state",VoiceUiState(connection=ConnectionStatus.CONNECTED))
val eventMethod=session.javaClass.getDeclaredMethod("onEvent",ServerEvent::class.java).apply { isAccessible=true }
fun event(kind: EventKind,turn: Long,fields: Map<String,Any> = emptyMap(),reason: String="",state: String="") {
eventMethod.invoke(session,ServerEvent(if(kind==EventKind.PRESENCE) "presence.status" else kind.name.lowercase(),kind,Payload(turn=turn,reason=reason,state=state,fields=fields)))
}
session.startVoice();event(EventKind.HELLO,1,mapOf("presence_greeting_version" to 1))
session.setPresence(true,true)
fun primeAndSend(): Long {
val now=android.os.SystemClock.elapsedRealtime()
val rules=get("presenceRules") as PresenceRules
rules.reset()
rules.javaClass.getDeclaredField("absentSince").apply { isAccessible=true }.set(rules,now-20_000)
field("lastSpeechAt",now-1_000)
session.observePresence(false,now)
val sent=socket.sent.last();check(sent.startsWith("presence_absent/"))
return sent.split('/')[1].toLong()
}
val id=primeAndSend()
event(EventKind.ABORT,2,mapOf("request_id" to id),reason="presence_greeting")
event(EventKind.PRESENCE,2,mapOf("request_id" to id),state="accepted")
check(states.last().turnId==2L && get("presenceRequest")!=null)
event(EventKind.TTS,2,state="start")
val frames=session.javaClass.getDeclaredMethod("onFrame",DownlinkFrame::class.java).apply { isAccessible=true }
frames.invoke(session,DownlinkFrame(2))
check(states.last().phase==VoicePhase.ANSWERING)
checkNotNull(AudioPlayback.lastDrained)(2,0);Handler.drain();check(get("presenceRequest")==null)
val id2=primeAndSend();session.setPresence(false,true)
check(socket.sent.count { it=="presence_cancel/$id2" }==1)
val before=AudioPlayback.enqueued
event(EventKind.ABORT,3,mapOf("request_id" to id2),reason="presence_greeting")
frames.invoke(session,DownlinkFrame(3));check(AudioPlayback.enqueued==before)
event(EventKind.ABORT,4,reason="presence_cancelled")
check(states.last().turnId==4L)
session.setPresence(true,true);val id3=primeAndSend()
event(EventKind.VAD,4,mapOf("event" to Payload(fields=mapOf("type" to "speech.start"))))
check(get("presenceRequest")==null && socket.sent.any { it=="presence_cancel/$id3" })
session.background();session.release();Handler.drain()
}
+5 -2
View File
@@ -5,10 +5,11 @@ package com.gorios.lanvoice.net
class Payload(private val ok: Boolean = true, private val turn: Long? = null, private val state: String = "", private val reason: String = "", private val fields: Map<String, Any> = emptyMap()) {
fun optBoolean(key: String, fallback: Boolean) = if (key == "ok") ok else fields[key] as? Boolean ?: fallback
fun optString(key: String, fallback: String = "") = when (key) { "state" -> state; "reason" -> reason; else -> fields[key] as? String ?: fallback }
fun optInt(key: String, fallback: Int) = if (key == "context_face_cue_version") 1 else fallback
fun optInt(key: String, fallback: Int) = if (key == "context_face_cue_version") 1 else fields[key] as? Int ?: fallback
fun optJSONObject(key: String): Payload? = fields[key] as? Payload
fun opt(key: String): Any? = if (key == "turn_id") turn else fields[key]
}
enum class EventKind { AUTH, HELLO, ERROR, HISTORY, UNKNOWN, LISTEN, VAD, STT, LLM, TTS, ABORT, REPLY_EMOTION, EXPRESSION_PREPARE, ACTION, CAPABILITIES, SPEECH }
enum class EventKind { AUTH, HELLO, ERROR, HISTORY, UNKNOWN, LISTEN, VAD, STT, LLM, TTS, ABORT, REPLY_EMOTION, EXPRESSION_PREPARE, ACTION, CAPABILITIES, SPEECH, PRESENCE }
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 {
@@ -17,6 +18,8 @@ object DialogueProtocol {
fun faceCue(turn: Long, observation: com.gorios.lanvoice.expression.FaceCueObservation, age: Long) = "face_cue"
fun hello(actionPackSha: String? = null,pendingPackSha: String?=null) = "hello"
fun capabilitiesReady(pin: String) = "capabilities_ready"
fun presence(id: Long,turn: Long,kind: com.gorios.lanvoice.expression.PresenceKind,age: Long) = "presence_${kind.wire}/$id/$turn"
fun presenceCancel(id: Long) = "presence_cancel/$id"
fun listen(start: Boolean) = "listen"
fun abort(turn: Long) = "abort"
fun playbackDrained(turn: Long) = "drained"