feat(android): add isolated lvbu persona build and pinned asset selection

This commit is contained in:
zenord
2026-10-14 16:41:36 +08:00
parent 3371997252
commit 5a7be557d0
23 changed files with 1507 additions and 31 deletions
+55
View File
@@ -0,0 +1,55 @@
import android.os.Handler
import com.gorios.lanvoice.net.*
import okhttp3.*
private class Socket: WebSocket {
val sent=mutableListOf<String>()
var cancelled=false
override fun request()=Request.Builder().url("https://localhost/ws/dialogue").build()
override fun queueSize()=0L
override fun send(text: String): Boolean {sent.add(text);return true}
override fun send(bytes: okio.ByteString)=true
override fun close(code: Int,reason: String?)=true
override fun cancel() {cancelled=true}
}
private fun DialogueClient.field(name: String,value: Any?) {
javaClass.getDeclaredField(name).apply {isAccessible=true}.set(this,value)
}
private fun DialogueClient.listener(epoch: Long)=javaClass.getDeclaredMethod("listener",Long::class.javaPrimitiveType)
.apply {isAccessible=true}.invoke(this,epoch) as WebSocketListener
fun main() {
val wires=mutableListOf<String>()
val pin="208f703ed92bf795bfeb78a1cef89b67bed2e45da80038a56157fd1ecd4cfa93"
for(persona in listOf("default","lvbu")) for(pending in listOf(false,true)) {
var readyPin: String?=if(pending) null else pin
val statuses=mutableListOf<ConnectionStatus>()
val client=DialogueClient("localhost",5011,statuses::add,persona=persona,
actionPackSha={readyPin},pendingActionPackSha={pin})
val socket=Socket();client.field("socket",socket);val old=client.listener(0)
fun receive(text: String) {old.onMessage(socket,text);Handler.drain()}
receive("""{"type":"auth","state":"ok"}""")
check(socket.sent.size==1 && "\"persona\":\"$persona\"" in socket.sent[0])
check("voice_id" !in socket.sent[0] && "conversation_id" !in socket.sent[0])
check(statuses.isEmpty());wires.add(socket.sent.single())
receive("""{"type":"auth","state":"ok"}""");check(socket.sent.size==1)
receive(if(pending) """{"type":"hello","action_pending":true,"action_available":false}"""
else """{"type":"hello","action_available":true}""")
check(statuses==listOf(ConnectionStatus.CONNECTED))
if(pending) {
check(client.actionNegotiation=="pending_pack")
readyPin=pin;check(client.capabilitiesReady())
check(socket.sent.last()==DialogueProtocol.capabilitiesReady(pin))
} else check(client.actionNegotiation=="accepted")
client.disconnect()
old.onMessage(socket,"""{"type":"auth","state":"ok"}""")
old.onMessage(socket,"""{"type":"hello","action_available":true}""");Handler.drain()
check(socket.cancelled && statuses.last()==ConnectionStatus.DISCONNECTED)
val count=socket.sent.size
old.onMessage(Socket(),"""{"type":"auth","state":"ok"}""");Handler.drain()
check(socket.sent.size==count)
client.release();Handler.drain()
}
java.io.File(checkNotNull(System.getProperty("character.helloFile"))).writeText(wires.joinToString("\n")+"\n")
println("PASS: four actual DialogueClient AUTH→production HELLO persona/media offers, pending readiness, duplicate AUTH and retired socket fences; transport/main/JSON adapters, device not_run")
}
+28
View File
@@ -0,0 +1,28 @@
package org.json
// Bounded flat AUTH/HELLO response adapter. Outbound JSON uses production protocol.
// This does not exercise Android's JSON parser, which the APK build compiles.
class JSONObject() {
private val fields=linkedMapOf<String,Any>()
constructor(text: String):this() {
check(text.length<2048 && text.startsWith("{") && text.endsWith("}"))
val entries=Regex("\"([a-z_]+)\":(\"[a-z_]+\"|true|false|[0-9]+)").findAll(text)
entries.forEach {
val raw=it.groupValues[2]
fields[it.groupValues[1]]=when {
raw.startsWith("\"") -> raw.removeSurrounding("\"")
raw=="true" -> true
raw=="false" -> false
else -> raw.toLong()
}
}
}
fun put(key: String,value: Any): JSONObject {fields[key]=value;return this}
fun opt(key: String): Any?=fields[key]
fun optString(key: String,fallback: String=""): String=fields[key] as? String ?: fallback
fun optBoolean(key: String,fallback: Boolean=false): Boolean=fields[key] as? Boolean ?: fallback
fun optLong(key: String,fallback: Long=0): Long=(fields[key] as? Number)?.toLong() ?: fallback
override fun toString()=fields.entries.joinToString(",","{","}") { (k,v) ->
"\"$k\":"+if(v is String) "\"$v\"" else v.toString()
}
}
+108
View File
@@ -0,0 +1,108 @@
"""Trusted selection uses actual frozen assets; no generation, device or gateway."""
import importlib.util
import json
from pathlib import Path
import tempfile
import unittest
from unittest.mock import patch
import zipfile
ROOT = Path(__file__).resolve().parents[2]
spec = importlib.util.spec_from_file_location('character_assets', ROOT/'scripts/select-character-assets.py')
select = importlib.util.module_from_spec(spec)
spec.loader.exec_module(select)
ASSETS = ROOT/'app/src/main/assets'
class CharacterProfilesTests(unittest.TestCase):
def full(self, profile='main', **changes):
flags = dict(emotion_sha=select.catalog()['mediaBundles']['black-correct03']['indexSha256'],
user_assets=True, mouth=True, startup=True)
flags.update(changes)
return select.selection(ASSETS, profile, **flags)
def test_identities_are_distinct_media_is_identical(self):
main, lvbu = self.full(), self.full('lvbu-test')
self.assertEqual(main['files'], lvbu['files'])
self.assertEqual(lvbu['file_count'], 4051)
self.assertEqual((main['persona'], lvbu['persona']), ('default', 'lvbu'))
self.assertNotEqual(main['application_id'], lvbu['application_id'])
self.assertEqual((main['media_identity'], lvbu['media_identity']), ('a01', 'a01'))
self.assertNotIn('voice_id', json.dumps(select.catalog()))
def test_complete_inventory_is_exact_code33(self):
selected = self.full()['files']
with zipfile.ZipFile(ROOT/'artifacts/lan-voice-v0714-black-tulle-correct03-code33-arm64-debug.apk') as z:
actual = {n[7:]: {'sha256': select.digest(z.read(n)), 'bytes': z.getinfo(n).file_size}
for n in z.namelist() if n.startswith('assets/') and not n.endswith('/')}
self.assertEqual(selected, actual)
self.assertEqual(sum(n.startswith('avatar/a01-neutral-graph-v1/') for n in selected), 593)
self.assertNotIn('avatar/a01-expression-action-v1/manifest.json', selected)
def test_default_legacy_flags_preserve_108_files(self):
selected = select.selection(ASSETS)
self.assertEqual(selected['file_count'], 108)
self.assertFalse(any('runtime-04/' in n for n in selected['files']))
self.assertFalse(any('startup-' in n or 'black-tulle' in n for n in selected['files']))
def test_unlisted_source_files_do_not_enter_selection(self):
import shutil
with tempfile.TemporaryDirectory() as folder:
copied = Path(folder)/'assets'
shutil.copytree(ASSETS, copied)
(copied/'unapproved').mkdir()
(copied/'unapproved/wrong-character.png').write_bytes(b'not media')
self.assertEqual(select.selection(copied)['files'], select.selection(ASSETS)['files'])
def test_wrong_persona_flags_or_pin_are_rejected(self):
for profile, changes in [('unknown', {}), ('lvbu-test', {'startup': False}),
('lvbu-test', {'mouth': False}), ('lvbu-test', {'user_assets': False}),
('main', {'emotion_sha': '0'*64})]:
with self.subTest(profile=profile, changes=changes), self.assertRaises(ValueError):
self.full(profile, **changes)
def test_index_bootstrap_and_poster_corruption_rejected(self):
media = select.catalog()['mediaBundles']['black-correct03']
targets = [ASSETS/media['assetRoot']/'manifest.json',
ASSETS/media['bootstrapRoot']/'manifest.json',
ROOT/'app/src/main/res/drawable-nodpi'/ (media['posterResource']+'.png')]
original = Path.read_bytes
for target in targets:
def corrupted(p):
return b'corrupted' if p == target else original(p)
with self.subTest(target=target.name), patch.object(Path, 'read_bytes', corrupted), self.assertRaises(ValueError):
self.full()
def test_selected_symlink_and_escape_rejected(self):
original = Path.is_symlink
target = ASSETS/'face_landmarker.task'
with patch.object(Path, 'is_symlink', lambda p: p == target or original(p)), self.assertRaises(ValueError):
self.full()
for name in ('../x', '/x', 'x/../y', 'x//y', 'x\\y'):
with self.subTest(name=name), self.assertRaises(ValueError):
select.relative(name)
def test_staging_cannot_overwrite_other_profile_or_build_root(self):
result = self.full('lvbu-test')
for dest in (ROOT/'app/build', ROOT/'app/build/generated/packagedAssets', ASSETS):
with self.subTest(dest=dest), self.assertRaises(ValueError):
select.stage(ASSETS, dest, result)
def test_backup_lifecycle_component_contracts(self):
profiles = select.catalog()['profiles']
self.assertTrue(profiles['main']['allowBackup'])
self.assertTrue(profiles['main']['permissionConnectionRetention'])
self.assertFalse(profiles['lvbu-test']['allowBackup'])
self.assertFalse(profiles['lvbu-test']['permissionConnectionRetention'])
text = (ROOT/'app/src/main/AndroidManifest.xml').read_text()
self.assertIn('android:allowBackup="${characterAllowBackup}"', text)
self.assertIn('android:name="com.gorios.lanvoice.MainActivity"', text)
self.assertIn('android:name="com.gorios.lanvoice.CameraDiagnosticsActivity"', text)
self.assertNotIn('android:name=".MainActivity"', text)
build = (ROOT/'app/build.gradle').read_text()
self.assertIn("build/characters/", build)
self.assertIn("applicationId characterProfile.applicationId", build)
activity=(ROOT/'app/src/main/java/com/gorios/lanvoice/MainActivity.kt').read_text()
pause=activity[activity.index("override fun onPause()"):activity.index("override fun onStop()")]
self.assertLess(pause.index("if(releaseSessionFirst"),pause.index("closeCamera()"))
self.assertIn("if(!releaseSessionFirst",pause)
+6 -1
View File
@@ -14,7 +14,12 @@ class UserAssetPackageTests(unittest.TestCase):
s=(ROOT/'app/build.gradle').read_text()
self.assertIn("emotionManifestSha != '"+pack.PIN+"'",s)
self.assertIn("if (!avatarUserAssetCandidate && avatarPlaybackClockFix",s)
for root in ('avatar/a01-expression-action-v1/**','avatar/startup-white-01/**','avatar/a01-black-tulle-roomy720-correct03/**'):self.assertIn(root,s)
self.assertIn("sourceSets.main.assets.setSrcDirs([packagedAssets])",s)
self.assertIn("scripts/select-character-assets.py",s)
catalog=json.loads((ROOT/'manifests/character-build-profiles.json').read_bytes())['mediaBundles']
self.assertEqual(catalog['black-correct03']['indexSha256'],pack.PIN)
self.assertEqual(catalog['black-correct03']['assetRoot'],pack.startup.ASSET_ROOT)
self.assertEqual(catalog['white-full04']['assetRoot'],pack.pack.ASSET_ROOT)
activity=(ROOT/'app/src/main/java/com/gorios/lanvoice/MainActivity.kt').read_text()
self.assertIn('reviewedActionPack = avatarPack?.emotionAction?.actionPack?.takeIf { BuildConfig.AVATAR_NETWORK_ACTIONS_ALLOWED',activity)
self.assertIn('if(BuildConfig.AVATAR_STARTUP_FIX && BuildConfig.AVATAR_NETWORK_ACTIONS_ALLOWED) BuildConfig.EMOTION_MANIFEST_SHA else null',activity)
+10
View File
@@ -1,6 +1,16 @@
import com.gorios.lanvoice.net.DialogueProtocol
fun main() {
for(persona in listOf("default","lvbu")) {
for((ready,pending) in listOf(null to null,"a".repeat(64) to null,null to "a".repeat(64))) {
val hello=DialogueProtocol.hello(ready,pending,persona)
check("\"persona\":\"$persona\"" in hello)
check("voice_id" !in hello && "conversation_id" !in hello)
}
}
check("\"persona\":\"default\"" in DialogueProtocol.hello())
check(runCatching { DialogueProtocol.hello(persona="unknown") }.isFailure)
println("PASS: production HELLO default/lvbu for no, ready and pending media; no client voice/CID; unknown persona rejected")
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)
+21
View File
@@ -60,5 +60,26 @@ fun checkCallControls() {
session.resetConnection()
check(states.last().connection == ConnectionStatus.DISCONNECTED)
session.release(); AudioPlayback.activityFence = null
// Actual session/client background path: the independent profile never retains
// mic/playback/socket, including when a permission Activity pauses this Activity.
val independentStates=mutableListOf<VoiceUiState>()
val independent=VoiceSession("localhost",5011,independentStates::add,persona="lvbu",keepPermissionConnection=false)
val connection=independent.javaClass.getDeclaredField("dialogue").apply { isAccessible=true }.get(independent) as DialogueClient
val oldSocket=FakeSocket();connection.setField("socket",oldSocket);connection.setField("ready",true)
independent.javaClass.getDeclaredField("foreground").apply { isAccessible=true }.set(independent,true)
independent.javaClass.getDeclaredField("state").apply { isAccessible=true }.set(independent,VoiceUiState(connection=ConnectionStatus.CONNECTED))
independent.startVoice()
val lateCapture=checkNotNull(AudioCapture.lastFrame);val latePlayback=checkNotNull(AudioPlayback.lastActivity)
val sent=DialogueProtocol.uplinks.size
independent.background(keepConnectionForPermission=true)
check(oldSocket.cancelled && independentStates.last().connection==ConnectionStatus.DISCONNECTED)
check(!independentStates.last().voiceActive && independentStates.last().playbackActivity==null)
check(independent.javaClass.getDeclaredField("backgroundTimeout").apply { isAccessible=true }.get(independent)==null)
lateCapture(ByteArray(640));latePlayback(PlaybackActivity(999,7,true,960,1920));Handler.drain()
check(DialogueProtocol.uplinks.size==sent && independentStates.last().playbackActivity==null)
connection.callbacks(0).onMessage(oldSocket,"hello");Handler.drain()
check(independentStates.last().connection==ConnectionStatus.DISCONNECTED)
independent.release()
println("PASS: lvbu background/permission pause disconnects actual session/client; late capture/playback/HELLO cannot revive it; default retention covered separately")
println("PASS: real VoiceSession explicit start/duplicate dial, mute discards queued capture/keeps seq/no restart while answering, audio turn/generation/abort/hangup/late-frame fences")
}
+11 -2
View File
@@ -21,11 +21,11 @@ fun DialogueClient.setField(name: String, value: Any?) {
fun DialogueClient.callbacks(generation: Long): WebSocketListener =
javaClass.getDeclaredMethod("listener", Long::class.javaPrimitiveType).apply { isAccessible = true }
.invoke(this, generation) as WebSocketListener
class Fixture {
class Fixture(persona: String = "default") {
val statuses = mutableListOf<ConnectionStatus>()
val logs = mutableListOf<String>()
val events = mutableListOf<EventKind>()
val client = DialogueClient("localhost", 5011, statuses::add, onEvent = { events.add(it.kind) }, onConnectionLog = logs::add)
val client = DialogueClient("localhost", 5011, statuses::add, onEvent = { events.add(it.kind) }, onConnectionLog = logs::add, persona=persona)
val socket = FakeSocket()
val listener = client.callbacks(0)
init { client.setField("socket", socket) }
@@ -73,6 +73,15 @@ class StartingFixture(val healthCode: Int = 200, val healthError: java.io.IOExce
fun close() { client.release(); barrier.countDown(); Handler.drain() }
}
fun runChecks() {
Fixture("lvbu").apply {
event("auth");check(socket.sent==listOf("hello persona=lvbu"))
event("auth");check(socket.sent.size==1)
event("hello");check(statuses==listOf(ConnectionStatus.CONNECTED))
client.disconnect()
listener.onMessage(socket,"auth");listener.onMessage(socket,"hello");Handler.drain()
check(socket.sent.size==1 && statuses.last()==ConnectionStatus.DISCONNECTED)
close()
}
Fixture().apply {
listener.onOpen(socket, response(101)); Handler.drain()
check(!client.listen(true))
+1 -1
View File
@@ -16,7 +16,7 @@ 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,pendingPackSha: String?=null) = "hello"
fun hello(actionPackSha: String? = null,pendingPackSha: String?=null,persona: String="default") = if(persona=="default") "hello" else "hello persona=$persona"
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"