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
+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"