feat: add single-call action protocol and Android stage interfaces

This commit is contained in:
zenord
2026-10-13 00:41:55 +08:00
parent dfd1372ba2
commit e91354c9e8
41 changed files with 1438 additions and 70 deletions
+49
View File
@@ -0,0 +1,49 @@
import com.gorios.lanvoice.avatar.*
import com.gorios.lanvoice.dialogue.RoleEmotion
fun actionCheck() {
val sha="a".repeat(64)
val statuses=mutableListOf<ActionStatus>()
var now=100L; var confirm: ((Boolean)->Unit)?=null
var playing=false;var finish: ((ActionEnd)->Unit)?=null
var release: (()->Unit)?=null
val picked=mutableListOf<String>()
val player=object: ActionPlayer {
override fun play(asset: ActionAsset, finished: (ActionEnd)->Unit, failed: ()->Unit) {
check(!playing);playing=true;picked.add(asset.id);finish=finished
}
override fun stop(released: ()->Unit) { release={ playing=false;released() } }
}
val pack=ReviewedActionPack(sha,listOf(ActionAsset("asset_01",1000),ActionAsset("asset_02",1200)))
val controller=ActionController(pack,player,{now},{confirm=it},{statuses.add(it)},choose={0})
fun plan(turn: Long)=ActionPlan("id".repeat(12)+turn,turn,sha,10000)
check(controller.offer(plan(1)))
check(controller.active && !playing && statuses.isEmpty()) // Intent is not recording-stop evidence.
confirm!!(true);check(playing && statuses.single().status=="started")
now+=1000;playing=false;finish!!(ActionEnd(true,true,true))
check(!controller.active && statuses.last().status=="completed")
check(controller.offer(plan(2)));confirm!!(true)
check(picked==listOf("asset_01","asset_02"))
val stale=finish!!
controller.cancel();check(controller.active) // No recording resume before music release fence.
check(statuses.last().status=="started")
release!!();check(!controller.active && statuses.last().status=="cancelled")
stale(ActionEnd(true,true,true));check(statuses.last().status=="cancelled")
check(controller.offer(plan(3)));confirm!!(false);release!!()
check(statuses.last().status=="failed" && picked.size==2)
check(controller.offer(plan(4)));confirm!!(true)
now+=10001;controller.tick();release!!();check(statuses.last().status=="failed")
val missing=ActionController(null,player,{now},{confirm=it},{statuses.add(it)})
check(missing.capability==null && !missing.offer(plan(5)))
val pts=List(97) { it*1_000_000L/24 }
val neutral=TalkPackage("neutral",RoleEmotion.NEUTRAL,sha,sha,pts,pts,true)
val happy=TalkPackage("happy",RoleEmotion.HAPPY,"b".repeat(64),"b".repeat(64),pts,pts,true)
val slight=RoleVisualSelector.select(RoleEmotion.HAPPY,2,listOf(neutral,happy),"neutral")
check(slight.selectedIntensity==2 && slight.visualIntensity==1 && slight.reason=="slight_only")
val mismatch=RoleVisualSelector.select(RoleEmotion.HAPPY,1,listOf(neutral,happy.copy(mouthBodySha=sha)),"neutral")
check(mismatch.selectedEmotion==RoleEmotion.HAPPY && mismatch.visualEmotion==RoleEmotion.NEUTRAL && mismatch.degraded)
val shifted=RoleVisualSelector.select(RoleEmotion.HAPPY,1,listOf(neutral,happy.copy(mouthPtsUs=pts.map { it+1 })),"neutral")
check(shifted.packageId=="neutral")
println("PASS: action fixture record-stop/music-release/return-A/TTL/cancel/stale/no-repeat and expression own-body/PTS/slight-only selection; no device/naturalness claim")
}
+2
View File
@@ -6,6 +6,8 @@ import android.media.MediaPlayer
import android.view.TextureView
fun main() {
actionCheck()
emotionActionCheck()
checkContinuous()
checkEngineering()
checkSafeDriver()
+36
View File
@@ -0,0 +1,36 @@
import com.gorios.lanvoice.avatar.*
fun emotionActionCheck() {
val sha="b".repeat(64)
val runtime=continuousPack().let { old -> old.copy(apertureMode=true,patches=old.patches.map { patch ->
patch.copy(levels=List(5) { MouthPatchLevel(it,it/4f,"patches/${patch.frameIndex}-$it.png",sha) })
}) }
fun clip(audio: Boolean)=mapOf<String,Any?>("path" to "clips/bridge.mp4","sha256" to sha,"hasAudio" to audio,
"frameCount" to 48,"ptsUs" to List(48) { it*1_000_000L/24 },"durationUs" to 2_000_000L)
fun edge(id: String,from: String,to: String)=mapOf<String,Any?>("id" to id,"from" to from,"to" to to,
"fromAnchor" to "A","toAnchor" to "A","fromFrame" to 96,"toFrame" to 0,"clip" to clip(false))
fun conversation(id: String)=mapOf<String,Any?>("id" to id,"emotion" to if(id=="neutral") "neutral" else "happy",
"visualIntensity" to if(id=="neutral") 0 else 1,"mouthBodySha256" to sha,
"runtimeManifest" to mapOf("path" to "$id/manifest.json","sha256" to sha),"entryAnchor" to "A","exitAnchor" to "A",
"legalExitFrames" to listOf(96),"loopEdge" to "$id-loop")
val edges=listOf(edge("neutral-loop","neutral","neutral"),edge("happy-loop","happy","happy"),
edge("in","neutral","happy"),edge("out","happy","neutral"))
val actions=listOf("asset_01","asset_02").map { mapOf<String,Any?>("id" to it,"kind" to "dance",
"mouthAllowed" to false,"disallowTALK" to true,"entryAnchor" to "A","returnAnchor" to "A",
"clip" to clip(true),"audioEndUs" to 1_900_000L) }
val root=mapOf<String,Any?>("schemaVersion" to 2,"identityId" to "a01","packId" to "a01-expression-action-v1",
"fallbackPackageId" to "neutral","conversationPackages" to listOf(conversation("neutral"),conversation("happy")),
"edges" to edges,"actions" to actions)
fun read(data: Map<String,Any?>,pin: String=sha)=EmotionActionManifest.read(data,sha,pin) { _,hash -> if(hash==sha) runtime else null }
check(read(root)?.actionPack?.assets?.size==2)
check(read(root+("actions" to emptyList<Any>()))?.actionPack==null)
check(read(root,"a".repeat(64))==null)
check(read(root+("approved" to true),"")==null)
check(read(root+("conversationPackages" to listOf(conversation("neutral"),conversation("happy")+("mouthBodySha256" to "a".repeat(64)))))==null)
check(read(root+("edges" to edges.dropLast(1)))==null)
for(change in listOf(mapOf("mouthAllowed" to true),mapOf("disallowTALK" to false),mapOf("returnAnchor" to "B"),
mapOf("audioEndUs" to 2_000_001L),mapOf("clip" to clip(false)),mapOf("clip" to clip(true)+("path" to "../escape.mp4")))) {
check(read(root+("actions" to listOf(actions[0]+change,actions[1])))==null)
}
println("PASS: production v2 index exact external pin/own body-mouth SHA/runtime04/complete bridges/music bounds/no TALK, synthetic metadata only")
}
+6 -1
View File
@@ -31,7 +31,12 @@ fun main() {
val errors = CopyOnWriteArrayList<Exception>()
capture.start(onFrame = frames::add, onError = errors::add)
check(AudioRecord.partialReady.await(2, TimeUnit.SECONDS))
capture.stop()
val confirmed = CountDownLatch(1)
capture.stopAndConfirm { stopped ->
check(stopped && AudioRecord.activeDevices.get()==0)
confirmed.countDown()
}
check(confirmed.await(2, TimeUnit.SECONDS))
check(AudioRecord.released.await(2, TimeUnit.SECONDS))
check(errors.isEmpty())
check(frames.size == expectedCount) // 100B unfinished tail must not be sent
+3 -3
View File
@@ -19,9 +19,9 @@ class AudioRecord(source: Int, rate: Int, channel: Int, encoding: Int, buffer: I
init { if (activeDevices.incrementAndGet() > 1) overlaps.incrementAndGet() }
private val mode = scenario
val state = if (mode == "init") 0 else STATE_INITIALIZED
val recordingState = RECORDSTATE_RECORDING
var recordingState = 1
val audioSessionId = 1
fun startRecording() { if (mode == "start") throw SecurityException("synthetic mic revocation") }
fun startRecording() { if (mode == "start") throw SecurityException("synthetic mic revocation"); recordingState = RECORDSTATE_RECORDING }
private val stopped = java.util.concurrent.CountDownLatch(1)
private val ready = partialReady
private val done = released
@@ -45,6 +45,6 @@ class AudioRecord(source: Int, rate: Int, channel: Int, encoding: Int, buffer: I
streamOffset += count
return count
}
fun stop() { stopped.countDown() }
fun stop() { recordingState = 1; stopped.countDown() }
fun release() { Thread.sleep(20); activeDevices.decrementAndGet(); done.countDown() }
}
+6
View File
@@ -0,0 +1,6 @@
package org.json
class JSONArray {
private val values = mutableListOf<String>()
fun put(value: String): JSONArray { values.add(value); return this }
override fun toString() = values.joinToString(",", "[", "]") { "\"$it\"" }
}
+50
View File
@@ -0,0 +1,50 @@
import android.os.Handler
import com.gorios.lanvoice.audio.*
import com.gorios.lanvoice.avatar.*
import com.gorios.lanvoice.net.*
fun checkActionSession() {
val sha="a".repeat(64);val states=mutableListOf<VoiceUiState>()
val prepared=mutableListOf<com.gorios.lanvoice.dialogue.ReplyEmotion?>()
var plays=0;var stopped=0;var ended: ((ActionEnd)->Unit)?=null
val player=object: ActionPlayer {
override fun play(asset: ActionAsset,finished: (ActionEnd)->Unit,failed: ()->Unit) { plays++;ended=finished }
override fun stop(released: ()->Unit) { stopped++;released() }
}
val session=VoiceSession("localhost",5011,states::add,
reviewedActionPack=ReviewedActionPack(sha,listOf(ActionAsset("asset_01",1000),ActionAsset("asset_02",1000))),
actionPlayer=player,onPrepareExpression=prepared::add)
fun set(name: String,value: Any) { session.javaClass.getDeclaredField(name).apply { isAccessible=true }.set(session,value) }
val dialogue=session.javaClass.getDeclaredField("dialogue").apply { isAccessible=true }.get(session) as DialogueClient
val socket=FakeSocket();dialogue.setField("socket",socket);dialogue.setField("ready",true)
set("foreground",true);set("state",VoiceUiState(connection=ConnectionStatus.CONNECTED))
val onEvent=session.javaClass.getDeclaredMethod("onEvent",ServerEvent::class.java).apply { isAccessible=true }
fun event(type: String,kind: EventKind,turn: Long,fields: Map<String,Any> = emptyMap()) {
onEvent.invoke(session,ServerEvent(type,kind,Payload(turn=turn,fields=fields)))
}
session.startVoice();event("listen",EventKind.LISTEN,7,mapOf("state" to "start"))
event("reply.emotion.prepare",EventKind.EXPRESSION_PREPARE,7,mapOf("seq" to 1L,"emotion" to "happy","intensity" to 1))
check(prepared.last()?.emotion==com.gorios.lanvoice.dialogue.RoleEmotion.HAPPY)
check(states.last().replyEmotion.turnId==null) // Preload never becomes displayed emotion.
event("reply.emotion.prepare",EventKind.EXPRESSION_PREPARE,6,mapOf("seq" to 2L,"emotion" to "sad","intensity" to 1))
check(prepared.last()?.emotion==com.gorios.lanvoice.dialogue.RoleEmotion.HAPPY)
AudioCapture.confirmStopsAutomatically=false
val oldFrame=checkNotNull(AudioCapture.lastFrame)
event("action.plan",EventKind.ACTION,7,mapOf("action_id" to "x".repeat(24),"pack_sha256" to sha,"ttl_ms" to 10000L))
check(states.last().actionActive && plays==0)
val before=DialogueProtocol.uplinks.size
oldFrame(ByteArray(640));Handler.drain();check(DialogueProtocol.uplinks.size==before)
checkNotNull(AudioCapture.lastStopped)(true);Handler.drain();check(plays==1)
val starts=AudioCapture.starts
session.setMicrophoneMuted(true);session.setMicrophoneMuted(false);session.interrupt()
check(AudioCapture.starts==starts)
val enqueued=AudioPlayback.enqueued
session.javaClass.getDeclaredMethod("onFrame",DownlinkFrame::class.java).apply { isAccessible=true }.invoke(session,DownlinkFrame(7))
check(enqueued==AudioPlayback.enqueued)
val stale=checkNotNull(ended)
session.background();Handler.drain()
check(stopped==1 && !states.last().actionActive && !states.last().voiceActive)
stale(ActionEnd(true,true,true));Handler.drain();check(plays==1)
session.release();AudioCapture.confirmStopsAutomatically=true
println("PASS: actual VoiceSession action plan→capture cleanup fence→player, queued mic/downlink dropped, prepare-only/old-turn, no voice barge, background cancel; doubles only")
}
+3 -1
View File
@@ -5,9 +5,11 @@ import com.gorios.lanvoice.net.DownlinkFrame
enum class AecAvailability { AVAILABLE, UNAVAILABLE, UNKNOWN }
// No audio devices in callback propagation tests.
class AudioCapture {
companion object { var lastFrame: ((ByteArray) -> Unit)? = null; var lastError: ((Exception) -> Unit)? = null; var starts = 0 }
companion object { var lastFrame: ((ByteArray) -> Unit)? = null; var lastError: ((Exception) -> Unit)? = null; var starts = 0
var confirmStopsAutomatically = true; var lastStopped: ((Boolean)->Unit)? = null }
fun aecAvailability() = AecAvailability.UNKNOWN
fun start(onFrame: (ByteArray) -> Unit, onError: (Exception) -> Unit, onDiagnostic: (String) -> Unit = {}) { starts++; lastFrame = onFrame; lastError = onError; onDiagnostic("AudioRecord initialization ok") }
fun stopAndConfirm(confirmed: (Boolean) -> Unit) { lastStopped = confirmed; if(confirmStopsAutomatically) confirmed(true) }
fun stop() {}
fun release() {}
}
+1
View File
@@ -3,6 +3,7 @@ import com.gorios.lanvoice.audio.*
import com.gorios.lanvoice.net.*
fun checkCallControls() {
checkActionSession()
val states = mutableListOf<VoiceUiState>()
val session = VoiceSession("localhost",5011,states::add)
fun set(name: String,value: Any) { session.javaClass.getDeclaredField(name).apply { isAccessible=true }.set(session,value) }
+3 -2
View File
@@ -8,13 +8,14 @@ class Payload(private val ok: Boolean = true, private val turn: Long? = null, pr
fun optInt(key: String, fallback: Int) = if (key == "context_face_cue_version") 1 else fallback
fun opt(key: String): Any? = if (key == "turn_id") turn else fields[key]
}
enum class EventKind { AUTH, HELLO, ERROR, HISTORY, UNKNOWN, LISTEN, VAD, STT, LLM, TTS, ABORT, REPLY_EMOTION }
enum class EventKind { AUTH, HELLO, ERROR, HISTORY, UNKNOWN, LISTEN, VAD, STT, LLM, TTS, ABORT, REPLY_EMOTION, EXPRESSION_PREPARE, ACTION, SPEECH }
data class ServerEvent(val type: String, val kind: EventKind, val payload: Payload)
class DownlinkFrame(val turnId: Long = 0, val sequence: Long = 0, val pcm16: ByteArray = ByteArray(2))
object DialogueProtocol {
val uplinks = mutableListOf<Triple<Long, Long, Int>>()
fun actionStatus(value: com.gorios.lanvoice.avatar.ActionStatus) = "action_status"
fun faceCue(turn: Long, observation: com.gorios.lanvoice.expression.FaceCueObservation, age: Long) = "face_cue"
fun hello() = "hello"
fun hello(actionPackSha: String? = null) = "hello"
fun listen(start: Boolean) = "listen"
fun abort(turn: Long) = "abort"
fun playbackDrained(turn: Long) = "drained"