Show startup shell before background avatar admission and update reviewed capabilities

This commit is contained in:
zenord
2026-10-13 14:57:13 +08:00
parent 345e26e245
commit 40abf3a14e
41 changed files with 1113 additions and 124 deletions
+2
View File
@@ -0,0 +1,2 @@
package android.util
object Log { fun i(tag: String,message: String)=0 }
+2
View File
@@ -6,6 +6,8 @@ import android.media.MediaPlayer
import android.view.TextureView
fun main() {
startupCacheCheck()
startupViewCheck()
reportedActionClockCheck()
playbackDiagnosticCheck()
boundedRuntimeDiagnosticCheck()
+1 -1
View File
@@ -83,7 +83,7 @@ fun playbackDiagnosticCheck() {
index.packages.values.forEach { android.media.CodecFixture.timelines[it.root+it.body.path]=it.body.ptsUs }
index.edges.mapNotNull { it.mouthRuntime }.forEach { android.media.CodecFixture.timelines[it.root+it.body.path]=it.body.ptsUs }
index.actionPack?.assets?.mapNotNull { it.media }?.forEach { android.media.CodecFixture.timelines[it.root+it.path]=it.ptsUs;android.media.CodecFixture.audioPaths.add(it.root+it.path) }
val binding=AvatarMediaBinding();val view=EmotionActionAvatarView(android.content.Context(),AvatarPack(fallback="fixture.png",emotionAction=index),binding) {}
val binding=AvatarMediaBinding();val view=EmotionActionAvatarView(android.content.Context(),AvatarPack(fallback="fixture.png",emotionAction=index),binding,{})
view.render(true);TestScheduler.advanceBy(1)
val local=OfflineDancePreview(index.actionPack,binding,{TestScheduler.now})
check(local.play(id));assertions++
+2
View File
@@ -0,0 +1,2 @@
package com.gorios.lanvoice
object R { object drawable { const val startup_poster=1 } }
+68
View File
@@ -0,0 +1,68 @@
import com.gorios.lanvoice.avatar.*
import android.os.TestScheduler
import android.media.CodecFixture
import java.util.concurrent.CountDownLatch
import java.util.concurrent.TimeUnit
fun startupCacheCheck() {
fun key(version: Long=22,install: Long=1,pin: String="a".repeat(64),validator: Int=1)=StartupAssetKey(version,install,pin,"avatar/a01-expression-action-v1/",validator)
val worker=java.util.concurrent.Executors.newSingleThreadExecutor()
try {
val cache=StartupLoadCache<String>(worker);val entered=CountDownLatch(1);val release=CountDownLatch(1);val done=CountDownLatch(2)
var calls=0;var cancelledCalled=false
val cancel=cache.request(key(),{ calls++;entered.countDown();check(release.await(2,TimeUnit.SECONDS));"verified" },{ cancelledCalled=true })
check(entered.await(2,TimeUnit.SECONDS))
repeat(2) { cache.request(key(),{ error("duplicate verification") },{ check(it.getOrThrow()=="verified");done.countDown() }) }
cancel();release.countDown();check(done.await(2,TimeUnit.SECONDS));check(!cancelledCalled && calls==1)
var hits=0;cache.request(key(),{ error("repeated cached read") },{ check(it.getOrThrow()=="verified") },{hits++});check(hits==1)
val failed=CountDownLatch(1);cache.request(key(version=23),{error("invalid assets")},{check(it.isFailure);failed.countDown()});check(failed.await(2,TimeUnit.SECONDS))
val retry=CountDownLatch(1);cache.request(key(version=23),{"retryverified"},{check(it.getOrThrow()=="retryverified");retry.countDown()});check(retry.await(2,TimeUnit.SECONDS))
val folder=java.nio.file.Files.createTempDirectory("avatar-receipt-test").toFile()
try {
val receipt=BundledValidationReceipt(folder);check(!receipt.contains(key()));receipt.complete(key());check(receipt.contains(key()))
for(changed in listOf(key(version=23),key(install=2),key(pin="b".repeat(64)),key(validator=2))) check(!receipt.contains(changed))
java.io.File(folder,key().fingerprint+".complete").writeText("partial");check(!receipt.contains(key()))
receipt.complete(key());java.io.File(folder,"incomplete.tmp").writeText("complete");check(receipt.contains(key()))
receipt.complete(key(install=2));check(!receipt.contains(key()) && receipt.contains(key(install=2)))
} finally { folder.deleteRecursively() }
} finally { worker.shutdownNow() }
println("PASS: production startup shared-future concurrency/cancel/cache/failure-retry and atomic immutable APK receipt corruption/install/pin/version/validator invalidation")
}
fun startupViewCheck() {
var cases=0
fun rig(): Triple<StartupAvatarView,ContinuousAvatarPack,AvatarPack> {
TestScheduler.reset();CodecFixture.reset();CodecFixture.emitNativeSurface=true
val index=mediaFixtureIndex();val neutral=index.packages.getValue(index.fallbackId)
index.packages.values.forEach { CodecFixture.timelines[it.root+it.body.path]=it.body.ptsUs }
index.edges.mapNotNull {it.mouthRuntime}.forEach {CodecFixture.timelines[it.root+it.body.path]=it.body.ptsUs}
return Triple(StartupAvatarView(android.content.Context(),AvatarMediaBinding(),{},{}),neutral.copy(patches=emptyList(),curves=emptyMap()),AvatarPack(fallback="fixture.png",emotionAction=index))
}
var visible=0
val (unused,base,pack)=rig();unused.dispose()
val view=StartupAvatarView(android.content.Context(),AvatarMediaBinding(),{},{visible++})
view.update(base,null,true);TestScheduler.advanceBy(250);check(visible==0);cases++
view.update(base,pack,true);TestScheduler.advanceBy(250);check(visible==0);cases++ // targetready is not sufficient: source actual0 required
TestScheduler.until(6000) { visible==1 };check(CodecFixture.releases>=1);cases++
val full=view.children.last() as EmotionActionAvatarView
check(full.alpha==1f && view.children.filterIsInstance<android.view.TextureView>().single().alpha==0f);cases++
view.update(base,pack,true);TestScheduler.advanceBy(100);check(visible==1);cases++
view.update(base,pack,false);TestScheduler.advanceBy(100);view.update(base,pack,true);TestScheduler.advanceBy(100);check(visible==1);cases++
view.dispose();TestScheduler.advanceBy(300);check(visible==1);cases++
val (background,b2,p2)=rig();background.update(b2,p2,true);background.update(b2,p2,false);TestScheduler.advanceBy(200)
check((background.children.last() as EmotionActionAvatarView).alpha==0f);cases++
background.update(b2,p2,true);TestScheduler.advanceBy(4500);check((background.children.last() as EmotionActionAvatarView).alpha==1f);cases++
background.dispose();TestScheduler.advanceBy(100)
val (bad,b3,p3)=rig();val index=p3.emotionAction!!
val wrong=index.copy(packages=index.packages+ (index.fallbackId to index.packages.getValue(index.fallbackId).copy(body=index.packages.getValue(index.fallbackId).body.copy(sha256="b".repeat(64)))))
check(runCatching { bad.update(b3,p3.copy(emotionAction=wrong),true) }.isFailure);bad.dispose();cases++
val (prototype,b4,p4)=rig();prototype.dispose();var failures=0;var recovered=0
val retrying=StartupAvatarView(android.content.Context(),AvatarMediaBinding(),{},{recovered++},{failures++})
retrying.update(b4,null,true,"preparing");TestScheduler.advanceBy(100)
CodecFixture.configureFails=true;retrying.update(b4,p4,true,"preparing");TestScheduler.advanceBy(100)
check(failures==1 && recovered==0 && (retrying.children.last() as EmotionActionAvatarView).alpha==0f) { "failure_count=$failures recovered=$recovered" };cases++
retrying.update(b4,p4,true,"failed");CodecFixture.configureFails=false
retrying.update(b4,p4,true,"preparing");TestScheduler.until(6000) { recovered==1 };cases++
retrying.dispose();TestScheduler.advanceBy(100)
println("PASS: $cases production startup host renderer callback cases: held exact target0/source0, decoderrelease before capability, persistent host, lifecycle and bodySHA mismatch")
}
+3
View File
@@ -1,14 +1,17 @@
package android.widget
import android.content.Context
open class FrameLayout(val context: Context) {
var alpha=1f
class LayoutParams(w: Int,h: Int)
val children = mutableListOf<Any>()
fun removeView(view: Any) { children.remove(view) }
fun addView(view: Any, params: LayoutParams) { children.add(view) }
open fun onDetachedFromWindow() {}
}
class ImageView(context: Context) {
enum class ScaleType { FIT_CENTER }
var scaleType = ScaleType.FIT_CENTER; var alpha = 1f
fun setImageResource(id: Int) {}
fun setImageBitmap(bitmap: Any?) {}
fun setImageDrawable(drawable: Any?) {}
}
+29
View File
@@ -0,0 +1,29 @@
"""Only bootstrap's exact pinned additions may differ from frozen code18 avatar bytes."""
import hashlib,importlib.util,tempfile,unittest,zipfile
from pathlib import Path
from unittest.mock import patch
ROOT=Path(__file__).resolve().parents[2]
spec=importlib.util.spec_from_file_location('startup_package',ROOT/'scripts/package-avatar-emotion.py')
pack=importlib.util.module_from_spec(spec);spec.loader.exec_module(pack)
class StartupPackageTests(unittest.TestCase):
def test_bootstrap_additions_and_no_old_asset_drift(self):
with tempfile.TemporaryDirectory() as folder:
old=Path(folder)/'old.apk';new=Path(folder)/'new.apk'
files={'assets/'+pack.ASSET_ROOT+'manifest.json':(ROOT/'app/src/main/assets'/pack.ASSET_ROOT/'manifest.json').read_bytes(),
'assets/'+pack.ASSET_ROOT+'fixture.png':b'old-immutable-patch'}
additions={'assets/avatar/startup-white-01/'+name:(ROOT/'app/src/main/assets/avatar/startup-white-01'/name).read_bytes() for name in ('manifest.json','poster.png')}
def write(path,rows):
with zipfile.ZipFile(path,'w') as z:
for name,data in rows.items():z.writestr(name,data)
write(old,files)
with patch.object(pack,'CODE18',old),patch.object(pack,'CODE18_SHA',hashlib.sha256(old.read_bytes()).hexdigest()):
write(new,{**files,**additions});self.assertEqual(pack.verify_runtime_fix_assets(new,pack.RUNTIME_FIX_PIN,True),2)
for change in ({'assets/avatar/unapproved.png':b'newportrait'},
{next(n for n in files if n.endswith('.png')):b'changed-mouth'},
{'assets/avatar/startup-white-01/poster.png':b'changed-poster'}):
with self.subTest(change=list(change)):
write(new,{**files,**additions,**change})
with self.assertRaises(ValueError):pack.verify_runtime_fix_assets(new,pack.RUNTIME_FIX_PIN,True)
write(new,{**files,**additions})
with self.assertRaises(ValueError):pack.verify_runtime_fix_assets(new,pack.RUNTIME_FIX_PIN,False)
+4
View File
@@ -1,6 +1,10 @@
import com.gorios.lanvoice.net.DialogueProtocol
fun main() {
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))
check("client.capabilities.ready" in update && "dance" in update)
// Partial expression packs provide no reviewed action pack; no dance in HELLO.
for (pin in listOf(null,"","unknown","a".repeat(63))) {
val hello=DialogueProtocol.hello(pin)
+1
View File
@@ -1,5 +1,6 @@
package android.util
object Log {
@JvmStatic fun i(tag: String,message: String)=0
@JvmStatic fun getStackTraceString(error: Throwable) = error.stackTraceToString()
@JvmStatic fun w(tag: String, message: String) = 0
@JvmStatic fun w(tag: String, message: String, error: Throwable) = 0
+1
View File
@@ -490,6 +490,7 @@ fun runChecks() {
}
fun main() {
startupCapabilityCheck()
checkCallControls()
checkFaceTransmission()
run {
+7 -3
View File
@@ -3,19 +3,20 @@ package com.gorios.lanvoice.net
// Event doubles isolate DialogueClient callback ordering from the unchanged JSON parser.
// Production DialogueProtocol/JSONObject were compiled separately with actual dependencies.
class Payload(private val ok: Boolean = true, private val turn: Long? = null, private val state: String = "", private val reason: String = "", private val fields: Map<String, Any> = emptyMap()) {
fun optBoolean(key: String, fallback: Boolean) = if (key == "ok") ok else fallback
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 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, SPEECH }
enum class EventKind { AUTH, HELLO, ERROR, HISTORY, UNKNOWN, LISTEN, VAD, STT, LLM, TTS, ABORT, REPLY_EMOTION, EXPRESSION_PREPARE, ACTION, CAPABILITIES, 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(actionPackSha: String? = null) = "hello"
fun hello(actionPackSha: String? = null,pendingPackSha: String?=null) = "hello"
fun capabilitiesReady(pin: String) = "capabilities_ready"
fun listen(start: Boolean) = "listen"
fun abort(turn: Long) = "abort"
fun playbackDrained(turn: Long) = "drained"
@@ -24,6 +25,9 @@ object DialogueProtocol {
fun parseEvent(text: String) = when (text) {
"auth" -> ServerEvent("auth", EventKind.AUTH, Payload())
"auth failed" -> ServerEvent("auth", EventKind.AUTH, Payload(false))
"hello pending" -> ServerEvent("hello",EventKind.HELLO,Payload(fields=mapOf("action_available" to false,"action_pending" to true)))
"cap accepted" -> ServerEvent("client.capabilities",EventKind.CAPABILITIES,Payload(fields=mapOf("action_available" to true,"action_pack_sha256" to "a".repeat(64))))
"cap wrong" -> ServerEvent("client.capabilities",EventKind.CAPABILITIES,Payload(fields=mapOf("action_available" to true,"action_pack_sha256" to "b".repeat(64))))
"hello available" -> ServerEvent("hello", EventKind.HELLO, Payload(fields=mapOf("action_available" to true)))
"hello unavailable" -> ServerEvent("hello", EventKind.HELLO, Payload(fields=mapOf("action_available" to false)))
"hello" -> ServerEvent("hello", EventKind.HELLO, Payload())
+27
View File
@@ -0,0 +1,27 @@
import android.os.Handler
import com.gorios.lanvoice.net.*
fun startupCapabilityCheck() {
var installed: String?=null
val client=DialogueClient("localhost",5011,{},actionPackSha={installed},pendingActionPackSha={"a".repeat(64)})
val socket=FakeSocket();client.setField("socket",socket);val listener=client.callbacks(0)
fun event(value: String) { listener.onMessage(socket,value);Handler.drain() }
event("auth");event("hello pending")
check(client.actionNegotiation=="pending_pack" && !client.capabilitiesReady())
installed="a".repeat(64);check(client.capabilitiesReady());check(!client.capabilitiesReady())
check(socket.sent.count { it=="capabilities_ready" }==1)
event("cap wrong");check(client.actionNegotiation=="pending_pack")
event("cap accepted");check(client.actionNegotiation=="accepted")
client.disconnect();event("cap accepted");check(client.actionNegotiation=="disconnected")
client.release();Handler.drain()
val legacy=DialogueClient("localhost",5011,{},actionPackSha={"a".repeat(64)})
val old=FakeSocket();legacy.setField("socket",old)
val callbacks=legacy.callbacks(0);callbacks.onMessage(old,"auth");Handler.drain();callbacks.onMessage(old,"hello unavailable");Handler.drain()
check(!legacy.capabilitiesReady());legacy.release();Handler.drain()
val failing=DialogueClient("localhost",5011,{},actionPackSha={installed},pendingActionPackSha={"a".repeat(64)})
installed=null;val broken=FakeSocket();failing.setField("socket",broken);val cb=failing.callbacks(0)
cb.onMessage(broken,"auth");Handler.drain();cb.onMessage(broken,"hello pending");Handler.drain()
installed="a".repeat(64);broken.acceptSend=false;check(!failing.capabilitiesReady())
check(failing.actionNegotiation=="disconnected" && broken.cancelled);failing.release();Handler.drain()
println("PASS: production DialogueClient pending/ready capability callback, exactpin, once, stale socket and legacy gates; no turn reset/reconnect")
}