From a68988e0bacd1a82d5f1812544504a148f625e8c Mon Sep 17 00:00:00 2001 From: zenord Date: Tue, 13 Oct 2026 09:36:29 +0800 Subject: [PATCH] fix(android): retain action layer and idle rotation across turns --- app/build.gradle | 4 +- .../java/com/gorios/lanvoice/MainActivity.kt | 5 + .../com/gorios/lanvoice/audio/VoiceSession.kt | 29 ++- .../lanvoice/avatar/AvatarMediaBinding.kt | 1 + .../com/gorios/lanvoice/avatar/AvatarPack.kt | 31 ++- .../com/gorios/lanvoice/avatar/CallScreen.kt | 6 +- .../avatar/ConversationMediaDriver.kt | 52 +++-- .../avatar/EmotionActionAvatarView.kt | 26 ++- .../com/gorios/lanvoice/diag/DiagnosticLog.kt | 12 ++ .../lanvoice/diag/DiagnosticReportUpload.kt | 8 + .../com/gorios/lanvoice/net/DialogueClient.kt | 16 +- docs/RUNTIME_TRIGGER_FIX_071.md | 95 +++++++++ scripts/check-avatar-apk-runtime.py | 182 ++++++++++++++++++ scripts/check-reply-regressions.py | 2 +- scripts/package-avatar-emotion.py | 32 ++- tests/avatar/AvatarCheck.kt | 1 + tests/avatar/Diagnostic.kt | 14 +- tests/avatar/MediaWiringCheck.kt | 55 +++++- tests/packaging/test_emotion_package.py | 22 +++ tests/session/ConnectionCheck.kt | 17 +- tests/session/ProtocolEvents.kt | 2 + 21 files changed, 554 insertions(+), 58 deletions(-) create mode 100644 docs/RUNTIME_TRIGGER_FIX_071.md create mode 100644 scripts/check-avatar-apk-runtime.py diff --git a/app/build.gradle b/app/build.gradle index 2797ae8..4e7aabb 100644 --- a/app/build.gradle +++ b/app/build.gradle @@ -18,6 +18,7 @@ def avatarNatural = providers.gradleProperty('avatarNatural').orNull == 'true' def avatarUiCandidate = providers.gradleProperty('avatarUiCandidate').orNull == 'true' def avatarMouthCandidate = providers.gradleProperty('avatarMouthCandidate').orNull == 'true' def avatarActionCandidate = providers.gradleProperty('avatarActionCandidate').orNull == 'true' +def avatarRuntimeFix = providers.gradleProperty('avatarRuntimeFix').orNull == 'true' def avatarFullActionCandidate = providers.gradleProperty('avatarFullActionCandidate').orNull == 'true' def actionVersionCode = (providers.gradleProperty('actionVersionCode').orNull ?: '16').toInteger() if (avatarActionCandidate && (!avatarMouthCandidate || actionVersionCode < 16)) { @@ -34,6 +35,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 (avatarRuntimeFix && (!avatarFullActionCandidate || actionVersionCode < 19)) throw new GradleException('Runtime fix requires full pinned graph and fresh code >=19') if (avatarNatural && !(naturalManifestSha ==~ /[0-9a-f]{64}/)) { throw new GradleException('Natural debug candidate requires exact runtime manifest SHA') } @@ -82,7 +84,7 @@ android { targetSdk 34 testInstrumentationRunner 'com.gorios.lanvoice.AvatarCleanUiInstrumentation' versionCode avatarActionCandidate ? actionVersionCode : (avatarMouthCandidate ? 15 : (avatarUiCandidate ? 14 : (avatarNatural ? 13 : 12))) - versionName = avatarActionCandidate ? '0.7.0' : ((avatarUiCandidate || avatarMouthCandidate) ? '0.6.2' : '0.6.1') + versionName = 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 } diff --git a/app/src/main/java/com/gorios/lanvoice/MainActivity.kt b/app/src/main/java/com/gorios/lanvoice/MainActivity.kt index b02144a..864d474 100644 --- a/app/src/main/java/com/gorios/lanvoice/MainActivity.kt +++ b/app/src/main/java/com/gorios/lanvoice/MainActivity.kt @@ -215,6 +215,11 @@ class MainActivity : ComponentActivity() { DiagnosticReportInfo( appVersion = appVersion, versionCode = packageManager.getPackageInfo(packageName, 0).versionCode, + avatarMode = if(offlineAvatarPreview) "offline_preview" else "normal", + avatarPin = BuildConfig.EMOTION_MANIFEST_SHA, + avatarAdmission = avatarPack?.emotionAdmission ?: "static_identity_rejected", + avatarRuntime = avatarMedia.diagnosticState, + actionProtocolState = if(offlineAvatarPreview) "offline_no_session" else session.runtimeProtocolState, cameraGranted = checkSelfPermission(Manifest.permission.CAMERA) == PackageManager.PERMISSION_GRANTED, cameraStatus = expressionState.status, cameraPermissionPending = entry.permissionPending == EntryPermission.CAMERA, diff --git a/app/src/main/java/com/gorios/lanvoice/audio/VoiceSession.kt b/app/src/main/java/com/gorios/lanvoice/audio/VoiceSession.kt index 1fff8af..4aed88a 100644 --- a/app/src/main/java/com/gorios/lanvoice/audio/VoiceSession.kt +++ b/app/src/main/java/com/gorios/lanvoice/audio/VoiceSession.kt @@ -84,8 +84,15 @@ class VoiceSession( private val actions = ActionController(reviewedActionPack, actionPlayer, SystemClock::elapsedRealtime, stopCapture = { confirmed -> captureEpoch++; capturing = false - capture.stopAndConfirm { stopped -> main.post { confirmed(stopped) } } - }, status = { status -> if (state.connection == ConnectionStatus.CONNECTED) dialogue.actionStatus(status) }, + diagnostic("action_capture state=stop_pending turn=$currentTurn epoch=$captureEpoch") + capture.stopAndConfirm { stopped -> main.post { + diagnostic("action_capture state=${if(stopped) "stop_confirmed" else "stop_failed"} turn=$currentTurn epoch=$captureEpoch") + confirmed(stopped) + } } + }, status = { status -> + diagnostic("action_status state=${status.status} turn=${status.turn} mic_stopped=${status.micStopped} video_ended=${status.videoEnded} audio_stopped=${status.audioStopped} restored_a=${status.idleRestored}") + if (state.connection == ConnectionStatus.CONNECTED) dialogue.actionStatus(status) + }, changed = { active -> if (!active) { actionTimeout?.let { main.removeCallbacks(it) }; actionTimeout = null } if (active) { playback.interrupt(); resetReply("action") } @@ -294,6 +301,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" fun faceDiagnosticsSnapshot() = faceDiagnostics.snapshot() private fun sendFaceContext() { @@ -398,21 +406,26 @@ class VoiceSession( diagnostic("onEvent kind=${event.kind.name} turn_id=$turn") if (event.kind == EventKind.EXPRESSION_PREPARE) { if (isActive() && hasTurn && turn == currentTurn && blockedTurn != turn && !actions.active) { - if (event.type.endsWith(".cancel")) onPrepareExpression(null) - else onPrepareExpression(ReplyEmotion.fromWire(turn,event.payload.opt("seq"),event.payload.opt("emotion"), - event.payload.opt("intensity"),"model")) + if (event.type.endsWith(".cancel")) { diagnostic("emotion_prepare state=cancelled turn=$turn");onPrepareExpression(null) } + else { + val header=ReplyEmotion.fromWire(turn,event.payload.opt("seq"),event.payload.opt("emotion"),event.payload.opt("intensity"),"model") + diagnostic("emotion_prepare state=${if(header==null) "invalid" else "received"} turn=$turn seq=${header?.sequence} emotion=${header?.emotion?.wire ?: "unset"} intensity=${header?.intensity}") + onPrepareExpression(header) + } } return } if (event.kind == EventKind.ACTION) { - if (!isActive() || !hasTurn || turn != currentTurn) return + if (!isActive() || !hasTurn || turn != currentTurn) { diagnostic("action_plan state=ignored_turn_or_inactive turn=$turn");return } if (event.type == "action.cancel") actions.cancel() else if (event.type == "action.plan") { val id = event.payload.optString("action_id") val ttl = (event.payload.opt("ttl_ms") as? Number)?.toLong() ?: 0L - if (drainedTurn!=currentTurn || !actions.offer(ActionPlan(id,currentTurn,event.payload.optString("pack_sha256"),ttl))) + diagnostic("action_plan state=received turn=$turn pre_tts_drained=${drainedTurn==currentTurn}") + if (drainedTurn!=currentTurn || !actions.offer(ActionPlan(id,currentTurn,event.payload.optString("pack_sha256"),ttl))) { + diagnostic("action_plan state=rejected_drain_or_capability turn=$turn") dialogue.actionStatus(ActionStatus(id,currentTurn,"failed")) - else if(actions.active) { + } else if(actions.active) { actionTimeout?.let { main.removeCallbacks(it) } actionTimeout = Runnable { actionTimeout = null; actions.tick() }.also { main.postDelayed(it,ttl) } } diff --git a/app/src/main/java/com/gorios/lanvoice/avatar/AvatarMediaBinding.kt b/app/src/main/java/com/gorios/lanvoice/avatar/AvatarMediaBinding.kt index 272bc60..c46c9a2 100644 --- a/app/src/main/java/com/gorios/lanvoice/avatar/AvatarMediaBinding.kt +++ b/app/src/main/java/com/gorios/lanvoice/avatar/AvatarMediaBinding.kt @@ -6,6 +6,7 @@ import com.gorios.lanvoice.dialogue.ReplyEmotion class AvatarMediaBinding : ActionPlayer { val currentPackageId: String? get() = driver?.currentPackageId val visualStatus: String get() = driver?.visualStatus ?: "renderer_unavailable" + val diagnosticState: String get() = driver?.diagnosticState ?: "owner=stopped renderer=unavailable" val selection: RoleVisualSelection? get() = driver?.selection private var driver: ConversationMediaDriver?=null private var prepared: ReplyEmotion?=null diff --git a/app/src/main/java/com/gorios/lanvoice/avatar/AvatarPack.kt b/app/src/main/java/com/gorios/lanvoice/avatar/AvatarPack.kt index 82f3974..085e37e 100644 --- a/app/src/main/java/com/gorios/lanvoice/avatar/AvatarPack.kt +++ b/app/src/main/java/com/gorios/lanvoice/avatar/AvatarPack.kt @@ -1,5 +1,6 @@ package com.gorios.lanvoice.avatar +import com.gorios.lanvoice.diag.DiagnosticLog import android.content.Context import org.json.JSONArray import org.json.JSONObject @@ -9,7 +10,8 @@ import com.gorios.lanvoice.BuildConfig /** Static identity approval and motion approval are independent. No metadata self-approval. */ data class AvatarPack(val idle: String = "", val talk: String = "", val fallback: String, val waiting: String = fallback, val safeGraph: SafeAvatarGraph? = null, val pathRoot: String = "", val motionStatus: String = "anchor_review_pending", - val continuous: ContinuousAvatarPack? = null,val emotionAction: EmotionActionIndex?=null) { + val continuous: ContinuousAvatarPack? = null,val emotionAction: EmotionActionIndex?=null, + val emotionAdmission: String="not_requested") { companion object { const val STATIC_IMAGE_SHA = "36a078ad9e1d2929612e9baa2af524bda90dafceddc4515dd448fc08121d7dd2" private const val STATIC_ROOT = "avatar/a01-standing-arms-reference/" @@ -19,32 +21,47 @@ data class AvatarPack(val idle: String = "", val talk: String = "", val fallback fun load(context: Context): AvatarPack? { val fallback = STATIC_ROOT + "frames/reference.png" try { check(sha(read(context,fallback,8_000_000)) == STATIC_IMAGE_SHA) } - catch (_: Exception) { return null } - val static = AvatarPack(fallback=fallback) + catch (_: Exception) { DiagnosticLog.record("avatar_loader","result=static_identity_rejected");return null } + var static = AvatarPack(fallback=fallback) if(BuildConfig.DEBUG && BuildConfig.EMOTION_MANIFEST_SHA.isNotEmpty()) { + var stage="index_read_or_hash" val admitted=try { val root="avatar/a01-expression-action-v1/" val raw=read(context,root+"manifest.json",2_000_000) + check(sha(raw)==BuildConfig.EMOTION_MANIFEST_SHA) + stage="index_schema_or_binding" val index=checkNotNull(EmotionActionManifest.read(jsonMap(JSONObject(String(raw,Charsets.UTF_8))),sha(raw), BuildConfig.EMOTION_MANIFEST_SHA,root) { path,hash -> val runtimeRoot=root+path.substringBeforeLast('/')+"/" + stage="runtime_read_or_hash" val bytes=read(context,root+path,2_000_000) check(sha(bytes)==hash) + stage="runtime_schema" val runtime=checkNotNull(ContinuousAvatarManifest.read(jsonMap(JSONObject(String(bytes,Charsets.UTF_8))),hash,hash,true,runtimeRoot)) - verifyRuntime(context,runtime);runtime + stage="runtime_body_patch_hash_or_shape" + verifyRuntime(context,runtime);stage="index_schema_or_binding";runtime }) var total=0L + stage="edge_media_hash" for(clip in index.edges.map { it.clip }) { val data=read(context,root+clip.path,64_000_000);check(sha(data)==clip.sha256);total+=data.size check(total<=512_000_000) } + stage="action_media_hash" for(asset in index.actionPack?.assets.orEmpty()) { val media=checkNotNull(asset.media);val data=read(context,media.root+media.path,128_000_000) check(sha(data)==media.sha256);total+=data.size;check(total<=512_000_000) } - static.copy(continuous=index.packages.getValue(index.fallbackId),emotionAction=index,motionStatus="externally_pinned_emotion_graph") - } catch(_: Exception) { null } - if(admitted!=null) return admitted + static.copy(continuous=index.packages.getValue(index.fallbackId),emotionAction=index,motionStatus="externally_pinned_emotion_graph",emotionAdmission="accepted") + } catch(_: Exception) { + static=static.copy(emotionAdmission=stage) + DiagnosticLog.record("avatar_loader","result=rejected reason=$stage pin=${BuildConfig.EMOTION_MANIFEST_SHA.take(12)}") + null + } + if(admitted!=null) { + DiagnosticLog.record("avatar_loader","result=accepted pin=${BuildConfig.EMOTION_MANIFEST_SHA.take(12)} packages=${admitted.emotionAction?.packages?.size} actions=${admitted.emotionAction?.actionPack?.assets?.size ?: 0}") + return admitted + } // Continue into independently pinned neutral admission as a whole pack. } if (BuildConfig.DEBUG && BuildConfig.AVATAR_NATURAL) return try { diff --git a/app/src/main/java/com/gorios/lanvoice/avatar/CallScreen.kt b/app/src/main/java/com/gorios/lanvoice/avatar/CallScreen.kt index 6b43305..3aabf0a 100644 --- a/app/src/main/java/com/gorios/lanvoice/avatar/CallScreen.kt +++ b/app/src/main/java/com/gorios/lanvoice/avatar/CallScreen.kt @@ -87,8 +87,8 @@ fun CallScreen(state: VoiceUiState,entry: EntryPhase,permissionMessage: String?, LaunchedEffect(state.voiceActive,pack) { if(state.voiceActive) while(true) { val selected=latestAvatar - DiagnosticLog.record("avatar","desired=${selected.desiredMode.name.lowercase()} actual=${latestVideo.actual} reason=${latestVideo.reason} requested=${selected.requestedEmotion.emotion.wire}/${selected.requestedEmotion.intensity} current_visual=${mediaBinding?.currentPackageId ?: "unavailable"} visual_status=${mediaBinding?.visualStatus ?: "legacy_neutral"}") - delay(1_000) + DiagnosticLog.state("avatar", "${selected.desiredMode}/${selected.requestedEmotion.emotion}/${selected.requestedEmotion.intensity}/${mediaBinding?.visualStatus}/${mediaBinding?.currentPackageId}","desired=${selected.desiredMode.name.lowercase()} actual=${latestVideo.actual} reason=${latestVideo.reason} requested=${selected.requestedEmotion.emotion.wire}/${selected.requestedEmotion.intensity} current_visual=${mediaBinding?.currentPackageId ?: "unavailable"} visual_status=${mediaBinding?.visualStatus ?: "legacy_neutral"}") + delay(10_000) } } CleanAvatarScaffold(avatar={ @@ -132,6 +132,8 @@ fun CallScreen(state: VoiceUiState,entry: EntryPhase,permissionMessage: String?, Text("当前画面:${visualEmotion?.label ?: if(pack?.emotionAction!=null) "过渡或未呈现" else "中立"} · ${video.actual}",fontSize=12.sp) Text("视觉选择:${mediaBinding?.selection?.let { "${it.visualEmotion.wire}/${it.visualIntensity}" } ?: "未选择"} · ${mediaBinding?.visualStatus ?: "旧中立素材"}",fontSize=12.sp) if(pack?.emotionAction!=null) Text("整合候选 · 动态自然度、音乐听审及真机未测;表达可能等待 2–4 秒出口和约 1 秒过渡",fontSize=12.sp) + Text("版本 ${com.gorios.lanvoice.BuildConfig.VERSION_NAME} · code ${com.gorios.lanvoice.BuildConfig.VERSION_CODE} · pin ${com.gorios.lanvoice.BuildConfig.EMOTION_MANIFEST_SHA.take(12)}",fontSize=12.sp) + Text("素材准入:${pack?.emotionAdmission ?: "unavailable"} · ${mediaBinding?.diagnosticState ?: "legacy_neutral"}",fontSize=11.sp) AvatarDiagnostics(pack,video) Text("AEC:${state.aec.name} · 效果待真机验证",fontSize=12.sp) Row { diff --git a/app/src/main/java/com/gorios/lanvoice/avatar/ConversationMediaDriver.kt b/app/src/main/java/com/gorios/lanvoice/avatar/ConversationMediaDriver.kt index 5c41f2b..05f9017 100644 --- a/app/src/main/java/com/gorios/lanvoice/avatar/ConversationMediaDriver.kt +++ b/app/src/main/java/com/gorios/lanvoice/avatar/ConversationMediaDriver.kt @@ -66,19 +66,30 @@ class ConversationMediaDriver(private val index: EmotionActionIndex, private var returning=false private var actionFinished: ((ActionEnd)->Unit)?=null private var actionFailed: (()->Unit)?=null + enum class LayerOwner { STOPPED, CONVERSATION, ACTION } + var layerOwner=LayerOwner.STOPPED;private set + private var musicPresented=false + private var ignoredCallbacks=0L + /** Fixed metadata only; frames are sampled in reports, never logged per callback. */ + val diagnosticState: String get() = "owner=${layerOwner.name.lowercase()} turn=$turn seq=$seq gen=$generation epoch=$musicEpoch requested=${selection?.selectedEmotion?.wire ?: "unset"} selected=$selectedId visual=${currentPackageId ?: "none"} edge=${edge?.id ?: "none"} idle_goal=${idleTarget ?: "none"} cycles=$idleCycles/$idleCycleGoal talk=$talk action=${when { returning -> "returning";musicPresented -> "presented";actionStarted -> "await_frame";action!=null -> "routing";else -> "none" }} ignored=$ignoredCallbacks frame=${visible?.key?.index ?: -1} loop=${visible?.key?.loopOrdinal ?: -1} pts=${visible?.key?.ptsUs ?: -1}" + val diagnosticSignature: String get() = "$layerOwner/$turn/$seq/$generation/$selectedId/${visible?.packageId}/${edge?.id}/$idleTarget/$talk/$actionStarted/$returning/$musicPresented/$active" private var musicEpoch=0L private var closing=0 private val releaseWaiters=mutableListOf<()->Unit>() fun beginTurn(id: Long?) { if(id==turn) return - turn=id;seq=-1;generation++;revision=0;talk=false;selection=null;idleTarget=null;resetIdleCycles() - selectedId=visible?.packageId ?: index.fallbackId + turn=id;seq=-1;generation++;revision=0;talk=false;selection=null + // A neutral idle variant is a displayed body, never the model's retained goal. + // Preserve its rotation and completed cycles across new user turns. + val current=visible?.packageId + selectedId=if(index.visuals.any { it.id==current && it.emotion==com.gorios.lanvoice.dialogue.RoleEmotion.NEUTRAL }) + index.fallbackId else current ?: index.fallbackId if(!inBridge && revealing==null) discardRoute() applyMouth() } fun start() { if(active || closing!=0) return - active=true;generation++;revision=0;resetIdleCycles() + active=true;layerOwner=LayerOwner.CONVERSATION;generation++;revision=0;resetIdleCycles() val slot=prepare(index.fallbackId,0);visible=slot // Ports must deliver callbacks asynchronously, like both Android ports. } @@ -98,10 +109,9 @@ class ConversationMediaDriver(private val index: EmotionActionIndex, seq=reply.sequence selection=RoleVisualSelector.select(reply.emotion,reply.intensity,index.visuals,index.fallbackId) selectedId=checkNotNull(selection).packageId - idleTarget=null;resetIdleCycles() + idleTarget=null } talk=talking && reply?.turnId==turn - if(talk) { idleTarget=null;idleCycles=0 } applyMouth() if(active && !inBridge && !actionStarted) plan() } @@ -124,6 +134,11 @@ class ConversationMediaDriver(private val index: EmotionActionIndex, if(key.index !in pack.body.ptsUs.indices || kotlin.math.abs(key.ptsUs-pack.body.ptsUs[key.index])>2 || !sequential || previous==null && (key.index!=entry || key.loopOrdinal!=0L)) { fail();return@prepare } slot.key=key;slot.closedMouth=closedMouth + if(slot===visible && layerOwner==LayerOwner.ACTION) { + // Held compositors still tick every20ms. They cannot steal the + // movie's layer, relabel it, advance or plan during ACTION/return. + ignoredCallbacks++;return@prepare + } if(slot===visible) { reveal(slot.number);report(if(inBridge) "bridge" else "body_${slot.packageId}",key) if(!inBridge) { chooseIdleAtLoopEnd(slot,key,previous);applyMouth();plan() } @@ -150,7 +165,7 @@ class ConversationMediaDriver(private val index: EmotionActionIndex, idleCycles++ if(idleCyclesUnit,failed: ()->Unit) { val media=asset.media if(!active || action!=null || media==null || index.actionPack?.assets?.contains(asset)!=true) { failed();return } - action=asset;actionFinished=finished;actionFailed=failed;musicReady=false;talk=false;idleTarget=null;resetIdleCycles();applyMouth() + action=asset;actionFinished=finished;actionFailed=failed;musicReady=false;musicPresented=false;talk=false;idleTarget=null;resetIdleCycles();applyMouth() val epoch=++musicEpoch - music.prepare(media,{ if(active && epoch==musicEpoch && action==asset) { musicReady=true;plan() } }, - { if(active && epoch==musicEpoch && actionStarted) reveal(3) },{ - if(active && epoch==musicEpoch && action==asset && actionStarted) { + music.prepare(media,{ if(active && epoch==musicEpoch && action===asset && !actionStarted && !returning) { musicReady=true;plan() } else ignoredCallbacks++ }, + { if(active && epoch==musicEpoch && action===asset && layerOwner==LayerOwner.ACTION && actionStarted && !returning && !musicPresented) { + musicPresented=true;reveal(3);report("action_first_frame",null) + } else ignoredCallbacks++ },{ + if(active && epoch==musicEpoch && action===asset && actionStarted && !returning) { returning=true;closing++ // onCompletion alone is not audio-release evidence. music.close { closing--;releasedIfDone() if(active && epoch==musicEpoch && action==asset) { visible?.let(::closeSlot);visible=null;discardRoute() + musicPresented=false;report("action_audio_released",null) target=prepare(media.returnPackage,media.returnFrame) // Target's first composed frame is the restored idle evidence. } } - } - },{ if(active && epoch==musicEpoch) fail() }) + } else ignoredCallbacks++ + },{ if(active && epoch==musicEpoch && action===asset) fail() else ignoredCallbacks++ }) } private fun restoreAction(slot: Slot) { val media=action?.media ?: return if(!returning || slot!==target || slot.key?.index!=media.returnFrame) return - visible=slot;target=null;returning=false;actionStarted=false;action=null + visible=slot;target=null;returning=false;actionStarted=false;action=null;layerOwner=LayerOwner.CONVERSATION reveal(slot.number);report("body_${slot.packageId}",slot.key) val completed=actionFinished;actionFinished=null;actionFailed=null selectedId=slot.packageId ?: index.fallbackId;applyMouth();slot.port.advance() completed?.invoke(ActionEnd(true,true,true)) } override fun stop(released: ()->Unit) { - musicEpoch++;action=null;actionStarted=false;returning=false;musicReady=false;idleTarget=null + musicEpoch++;layerOwner=LayerOwner.STOPPED;musicPresented=false;action=null;actionStarted=false;returning=false;musicReady=false;idleTarget=null actionFinished=null;actionFailed=null;talk=false;generation++;revision=0 reveal(null);releaseWaiters.add(released) active=false;visible=null;revealing=null;target=null;bridge=null;edge=null;inBridge=false diff --git a/app/src/main/java/com/gorios/lanvoice/avatar/EmotionActionAvatarView.kt b/app/src/main/java/com/gorios/lanvoice/avatar/EmotionActionAvatarView.kt index 88ccbfa..373a879 100644 --- a/app/src/main/java/com/gorios/lanvoice/avatar/EmotionActionAvatarView.kt +++ b/app/src/main/java/com/gorios/lanvoice/avatar/EmotionActionAvatarView.kt @@ -1,5 +1,6 @@ package com.gorios.lanvoice.avatar +import com.gorios.lanvoice.diag.DiagnosticLog import android.content.Context import android.graphics.BitmapFactory import android.graphics.Matrix @@ -23,6 +24,14 @@ class EmotionActionAvatarView(context: Context,private val pack: AvatarPack, private var active=false private var released=false private var movie: AndroidMusicPort?=null + private val summary=object: Runnable { + override fun run() { + val current=driver ?: return + DiagnosticLog.state("avatar_media",current.diagnosticSignature,"layer=${visibleLayer ?: -1} ${current.diagnosticState}") + if(active && !released) main.postDelayed(this,10_000) + } + } + private var visibleLayer: Int?=null private val renderers=arrayOfNulls(3) init { addView(still,LayoutParams(-1,-1)) @@ -41,6 +50,8 @@ class EmotionActionAvatarView(context: Context,private val pack: AvatarPack, } fun render(foreground: Boolean) { active=foreground;if(active) start() else suspend() } private fun start() { + DiagnosticLog.state("avatar_surface", "$active/$released/${textures.map { it.isAvailable }}", + "foreground=$active disposed=$released ready_mask=${textures.joinToString("") { if(it.isAvailable) "1" else "0" }}") if(!active || released || driver!=null || textures.any { !it.isAvailable }) return val index=checkNotNull(pack.emotionAction) val mouthClock=ConversationMouthClock() @@ -67,10 +78,16 @@ class EmotionActionAvatarView(context: Context,private val pack: AvatarPack, } } },music,{ slot -> - textures.forEachIndexed { i,v->v.alpha=if(i==slot) 1f else 0f };still.alpha=if(slot==null) 1f else 0f - },{ phase,key -> report(VideoPresentation(actual=phase,reason="reviewed_media_path", - clipId=key?.let { "f${it.index}_loop${it.loopOrdinal}" } ?: "")) }) - driver=current;current.start();binding.attach(current) { if(active && !released) { current.start();binding.attach(current) } };fitMovie() + if(visibleLayer!=slot) { + visibleLayer=slot + textures.forEachIndexed { i,v->v.alpha=if(i==slot) 1f else 0f };still.alpha=if(slot==null) 1f else 0f + } + },{ phase,key -> + driver?.let { value -> DiagnosticLog.state("avatar_media", value.diagnosticSignature, + "event=$phase layer=${visibleLayer ?: -1} ${value.diagnosticState}") } + report(VideoPresentation(actual=phase,reason="reviewed_media_path", + clipId=key?.let { "f${it.index}_loop${it.loopOrdinal}" } ?: "")) }) + driver=current;main.removeCallbacks(summary);main.postDelayed(summary,10_000);current.start();binding.attach(current) { if(active && !released) { current.start();binding.attach(current) } };fitMovie() } private fun fitMovie() { val view=textures[3];if(view.width<=0 || view.height<=0) return @@ -78,6 +95,7 @@ class EmotionActionAvatarView(context: Context,private val pack: AvatarPack, view.setTransform(Matrix().apply { setScale(fit.scaleX,fit.scaleY,view.width/2f,view.height/2f) }) } private fun suspend() { + main.removeCallbacks(summary) val old=driver ?: return old.stop { binding.detach(old);if(driver===old) { driver=null;movie=null };if(active) start() } } diff --git a/app/src/main/java/com/gorios/lanvoice/diag/DiagnosticLog.kt b/app/src/main/java/com/gorios/lanvoice/diag/DiagnosticLog.kt index 066dc93..31260cc 100644 --- a/app/src/main/java/com/gorios/lanvoice/diag/DiagnosticLog.kt +++ b/app/src/main/java/com/gorios/lanvoice/diag/DiagnosticLog.kt @@ -18,6 +18,18 @@ object DiagnosticLog { private val lock = Any() private val entries = ArrayDeque() private var nextId = 0L + private val states = LinkedHashMap>() + + /** State changes + one monotonic ten-second summary. Frame/PTS/counters belong + * in the sampled message, never the signature, so held ticks cannot flood500. */ + fun state(tag: String, signature: String, message: String, nowMs: Long = System.nanoTime()/1_000_000) = synchronized(lock) { + val previous=states[tag] + if(previous==null || previous.first!=signature || nowMs-previous.second>=10_000) { + if(tag !in states && states.size>=32) states.remove(states.keys.first()) + states[tag]=signature.take(500) to nowMs + record(tag,message) + } + } fun record( tag: String, message: String, diff --git a/app/src/main/java/com/gorios/lanvoice/diag/DiagnosticReportUpload.kt b/app/src/main/java/com/gorios/lanvoice/diag/DiagnosticReportUpload.kt index fd158da..6edb150 100644 --- a/app/src/main/java/com/gorios/lanvoice/diag/DiagnosticReportUpload.kt +++ b/app/src/main/java/com/gorios/lanvoice/diag/DiagnosticReportUpload.kt @@ -30,6 +30,11 @@ data class DiagnosticReportInfo( val phase: String, val aec: String, val versionCode: Int = 0, + val avatarMode: String = "unknown", + val avatarPin: String = "", + val avatarAdmission: String = "unknown", + val avatarRuntime: String = "unavailable", + val actionProtocolState: String = "unknown", val cameraGranted: Boolean = false, val cameraStatus: ExpressionStatus = ExpressionStatus.OFF, val cameraPermissionPending: Boolean = false, @@ -93,6 +98,9 @@ object DiagnosticReportUpload { .put("phase", info.phase) .put("aec", info.aec) .put("version_code", info.versionCode) + .put("avatar_runtime", JSONObject().put("mode",info.avatarMode).put("expected_pin",info.avatarPin) + .put("admission",info.avatarAdmission).put("state",info.avatarRuntime.take(1000)) + .put("action_protocol",info.actionProtocolState.take(500))) .put("camera", JSONObject().put("granted", info.cameraGranted).put("status", info.cameraStatus.name.lowercase()) .put("permission_pending", info.cameraPermissionPending).put("face_sharing", info.faceSharing)) .put("role_playing", info.rolePlaying) diff --git a/app/src/main/java/com/gorios/lanvoice/net/DialogueClient.kt b/app/src/main/java/com/gorios/lanvoice/net/DialogueClient.kt index 4dc92c4..d5c3aa6 100644 --- a/app/src/main/java/com/gorios/lanvoice/net/DialogueClient.kt +++ b/app/src/main/java/com/gorios/lanvoice/net/DialogueClient.kt @@ -75,6 +75,7 @@ class DialogueClient( private var ready = false private var wsOpened = false private var authReceived = false + var actionNegotiation: String = "disconnected";private set private var helloSent = false private var loggedAudioTurn: Long? = null private var handshakeTimeout: Runnable? = null @@ -93,6 +94,7 @@ class DialogueClient( wsOpened = false authReceived = false helloSent = false + actionNegotiation = "pending" loggedAudioTurn = null healthCall?.cancel() healthCall = null @@ -187,6 +189,7 @@ class DialogueClient( generation++ // Invalidate before cancellation can trigger onFailure. cancelHandshakeTimeout() ready = false + actionNegotiation = "disconnected" val previousHealth = healthCall healthCall = null previousHealth?.cancel() @@ -290,9 +293,10 @@ class DialogueClient( if (authReceived) return@dispatch authReceived = true connectionLog("auth ok", "auth") - if (webSocket.send(DialogueProtocol.hello(actionPackSha()))) { + val offeredPack=actionPackSha() + if (webSocket.send(DialogueProtocol.hello(offeredPack))) { helloSent = true - connectionLog("hello sent", "auth") + connectionLog("hello sent action_offer=${offeredPack?.takeIf { it.matches(Regex("[0-9a-f]{64}")) }?.take(12) ?: "none"} generation=$attempt", "auth") } else { connectionLog("hello send failed", "error") finish(webSocket, ConnectionStatus.DISCONNECTED, "hello_send_failure") @@ -306,7 +310,12 @@ class DialogueClient( } ready = true cancelHandshakeTimeout() - connectionLog("hello received", "auth") + actionNegotiation=when { + event.payload.opt("action_available") !is Boolean -> "unknown" + event.payload.opt("action_available")==true -> "accepted" + else -> "unavailable" + } + connectionLog("hello received action_pack=$actionNegotiation generation=$attempt", "auth") updateStatus(ConnectionStatus.CONNECTED, "server_hello_received") } if (event.kind == EventKind.ERROR && !ready) { @@ -391,6 +400,7 @@ class DialogueClient( previousHealth?.cancel() socket = null ready = false + actionNegotiation = "disconnected" webSocket?.cancel() updateStatus(status, reason) } diff --git a/docs/RUNTIME_TRIGGER_FIX_071.md b/docs/RUNTIME_TRIGGER_FIX_071.md new file mode 100644 index 0000000..60c68e2 --- /dev/null +++ b/docs/RUNTIME_TRIGGER_FIX_071.md @@ -0,0 +1,95 @@ +# Android 0.7.1 runtime trigger repair + +This Android-only repair starts from clean/pushed +`24ec3ab0449f198408239a8ed9830c0ff70da776`. It fixes two defects reproduced +with production Kotlin callbacks over the published code18 assets. It does not +establish which build/mode the user's phone ran or explain every reported symptom. +The last audit report query returned zero entries at 2026-10-13 09:12:48 Shanghai. + +## Confirmed defects and changes + +- In code18, `ConversationMediaDriver.prepare` unconditionally revealed the held + conversation body. The continuous compositor posts held presentations every20ms. + After the music's first-frame reveal, a body callback hid music within21ms even + though the player remained started. ACTION now owns the layer from music start + through actual end/release and presentation of the reviewed return frame. Held + body callbacks cannot reveal, relabel, advance or schedule conversation. Music + ready/first-frame/end/error callbacks check their epoch and instance; duplicate + completion cannot initiate another return. Delayed activation checks ownership. + The stable View changes alpha only when the selected layer changes. +- `beginTurn` previously cleared the idle rotation target/cycle count and retained + the displayed neutral variant as the selected model goal. That variant then + remained stranded for30s. Model goal and displayed neutral variant are now + separate: new turns retain the rotation target and completed cycle count; + a neutral variant can always schedule its reviewed return. New reply expression + takes priority, and cycle cadence resets at actual bridge-to-body transitions, + rather than on every new turn/TALK update. No body seek/hardcut was added. + +`emotion.prepare` still only preloads. Final happy/sad tags and selected slight +visuals remain separate; intensity2 never enlarges the expression or mouth. +The emotion path passed production loader/request/bridge/render callback replay; +actual user labels, human visibility and phone GPU remain unmeasured. + +## Frozen media and backend + +The reviewed index remains exactly +`987e125a7d7a2cde99121b5f5246c82f4dbe36c4899d3d49eaffd1a68bafb887`. +All3222 referenced runtime files must match code18 byte-for-byte. Five bodies, +eight own-mouth transitions, thirteen edges and two music dances are unchanged; +mouth gap remains1.1 source pixels. `--runtime-fix` packaging rejects any changed, +missing or extra avatar file, changed index pin or code18 rollback hash. +Code18/17/16 artifacts remain available. Build0.7.1/code19 uses the existing debug +certificate, `com.gorios.lanvoice`, arm64, min26/target34. + +No gateway deployment/restart or server-clock/provider/TTS/model setting change. +Gateway0.8 and its exact action allowlist remain the code18 configuration. Gateway +regression runs in a temporary remote source stage, with `applied=false`. +This repair makes no LLM/ASR/TTS/paid asset calls and performs no device install. +Asset ledger is unchanged:21 submitted, known video$4.16; image/rate fees unknown. + +## Verification and evidence boundaries + +- Nine existing JVM/UI entry suites passed. Production View/renderer/music callback + checks now contain1288 assertions, including five10-second/241-frame scenarios + with interleaved held compositor ticks, delayed first frame, duplicate readiness, + cancellation/error/background/new turn, return A and retired callbacks. +- Existing289 bridge TALK assertions,27 idle assertions,17 full graph assertions, + and2367 dynamic frame/level/parser checks pass. New actual-APK replay exercises + both neutral idle variants through repeated new turns, preload/final mismatch, + short TALK/end, legal return and another rotation over30s. +- Production APK loader and own happy/sad routes pass with the actual frozen file + bytes, PNG dimensions, N/PTS and own patch bindings. Both dances retain music + alpha1/body alpha0 at21ms and all241 sampled frames; code18 was alpha0/body1 at21ms. +- Packaging safety has29 passing tests; five body shader runs total200 offline + software EGL/GLES goldens. Gateway98 total:97 pass and1 existing skip + (`Silero artifact excluded from source archive`). The skip is not a pass. +- Android app and instrumentation compile. Instrumentation execution, real codec/ + GPU/surface visibility, AudioRecord state, actual music tail, human listening, + naturalness and perceptual latency remain **not_run**. Host replay doubles those + Android/device boundaries and recording confirmation; elapsed time alone never + causes action completion. + +Reproduce source regression with `scripts/check-avatar-regressions.sh`; use +`scripts/check-avatar-apk-runtime.py --apk --sha256 ` for finite +production loader/View callback replay. Ignored evidence lives under +`logs/action-emotion/runtime-fix-071/`; audit evidence remains untouched under +`logs/action-emotion/runtime-trigger-audit-01/`. No evidence logs/media enter Git. + +## Next user diagnostic + +The main screen remains fullscreen avatar plus the settings gear. Settings show +versionName, **versionCode**, pin prefix, admission and current runtime state. +Sending a diagnostic explicitly includes normal/offline mode, expected pin, +loader admission/reject stage, owner/epoch/turn/seq, model request versus displayed +package/queued edge, source frame/PTS/loop, idle rotation/cycles and ignored +callbacks. HELLO reports offered pin and negotiated accepted/unavailable/unknown; +a missing plan is not asserted to be model `action:none`. Fixed events identify +prepare/receive, plan/pre-TTS-drain, actual capture-stop confirmation, first music +frame, audio release and restored A/completion. Render state changes and monotonic +10s summaries use the existing500-entry ring, without per-frame log churn. +No raw reply/prompt, credentials, audio, images or user face values are added. + +A later normal-mode report can distinguish capability rejection, absent model +request, queued exit and rendering failure. Offline preview has no VoiceSession +and cannot trigger a server dance. Expression exits may still wait2–4s plus an +approximately1s bridge; this repair does not claim expression arrival within1s. diff --git a/scripts/check-avatar-apk-runtime.py b/scripts/check-avatar-apk-runtime.py new file mode 100644 index 0000000..7880119 --- /dev/null +++ b/scripts/check-avatar-apk-runtime.py @@ -0,0 +1,182 @@ +#!/usr/bin/env python3 +"""Finite replay of production loader/View/renderer callbacks over exact APK bytes. +Android EGL/codec/music/record confirmations are doubles; no device or sockets. +""" +from pathlib import Path +import ast,subprocess,tempfile,json,hashlib +import argparse +parser=argparse.ArgumentParser(description=__doc__) +parser.add_argument('--apk',type=Path,required=True) +parser.add_argument('--sha256',required=True) +args=parser.parse_args() +assert hashlib.sha256(args.apk.read_bytes()).hexdigest()==args.sha256, 'APK hash drift' +ROOT=Path(__file__).resolve().parents[1];script=ROOT/'scripts/check-reply-regressions.py' +tree=ast.parse(script.read_text());nodes=[] +for node in tree.body: + if isinstance(node,ast.Assign) and any(isinstance(t,ast.Name) and t.id=='parser' for t in node.targets):break + nodes.append(node) +ns={'__file__':str(script)};exec(compile(ast.Module(body=nodes,type_ignores=[]),str(script),'exec'),ns) +java,compiler,cp=ns['JAVA'],ns['compiler'],ns['cp'];real=next(x[2] for x in ns['suites'] if x[0]=='avatar') +json_adapter=r''' +package org.json +private fun wrap(v: Any?): Any? = when(v) { is Map<*,*> -> JSONObject(v as Map); is List<*> -> JSONArray(v); null -> JSONObject.NULL;else ->v } +class JSONObject(private val map: Map) { + constructor(raw: String):this(Parser(raw).value() as Map) + fun keys()=map.keys.iterator() + fun get(k: String): Any? = wrap(map.getValue(k)) + fun getString(k: String)=map.getValue(k) as String + fun getInt(k: String)=(map.getValue(k) as Number).toInt() + fun getBoolean(k: String)=map.getValue(k) as Boolean + fun getJSONArray(k: String)=JSONArray(map.getValue(k) as List<*>) + companion object { val NULL=Any() } +} +class JSONArray(private val values: List<*>) { + fun length()=values.size + fun get(i: Int): Any? =wrap(values[i]) + fun getJSONObject(i: Int)=get(i) as JSONObject +} +private class Parser(val s: String) { + var i=0 + fun space() { while(i { i++;space();val m=linkedMapOf();if(s[i]!='}') while(true) { val k=value() as String;space();check(s[i++]==':');m[k]=value();space();if(s[i]!=',')break;i++ };check(s[i++]=='}');m } + '[' -> { i++;space();val a=mutableListOf();if(s[i]!=']')while(true) { a.add(value());space();if(s[i]!=',')break;i++ };check(s[i++]==']');a } + '"' -> { i++;val b=StringBuilder();while(s[i]!='"') { var c=s[i++];if(c=='\\') { c=s[i++];c=when(c) { 'n'->'\n';'r'->'\r';'t'->'\t';'b'->'\b';'f'->'\u000c';'u'->{ val x=s.substring(i,i+4).toInt(16).toChar();i+=4;x };else->c } };b.append(c) };i++;b.toString() } + 't' -> {check(s.substring(i,i+4)=="true");i+=4;true} + 'f' -> {check(s.substring(i,i+5)=="false");i+=5;false} + 'n' -> {check(s.substring(i,i+4)=="null");i+=4;null} + else -> { val start=i;while(i() } +class Descriptor(path: String="") : java.io.Closeable { + val fileDescriptor=java.io.FileDescriptor();val startOffset=0L;val length=20L + init { AssetFixture.paths[fileDescriptor]=path };override fun close() {} +} +''' +graphics=(ROOT/'tests/avatar/Graphics.kt').read_text();graphics=graphics.replace(' fun decodeStream(input: java.io.InputStream): Bitmap = Bitmap(if(wrongSize) 41 else 40,22)',r''' + class Options { var inJustDecodeBounds=false;var outWidth=0;var outHeight=0 } + fun decodeStream(input: java.io.InputStream): Bitmap { val image=javax.imageio.ImageIO.read(input);return Bitmap(image.width,image.height) } + fun decodeByteArray(bytes: ByteArray,offset: Int,length: Int,options: Options): Bitmap? { + val input=java.io.ByteArrayInputStream(bytes,offset,length);val image=javax.imageio.ImageIO.read(input) + options.outWidth=image.width;options.outHeight=image.height + return if(options.inJustDecodeBounds) null else Bitmap(image.width,image.height) + } +''') +build='''package com.gorios.lanvoice +object BuildConfig { const val DEBUG=true;const val AVATAR_NATURAL=true;const val AVATAR_ENGINEERING=true;const val AVATAR_MOUTH_CANDIDATE=true +const val EMOTION_MANIFEST_SHA="987e125a7d7a2cde99121b5f5246c82f4dbe36c4899d3d49eaffd1a68bafb887" +const val NATURAL_MANIFEST_SHA="0a3c4918ba746019cf1df885bec66e5858a8950997dac4f64e7d37094be64dad" +}''' +main=r''' +import com.gorios.lanvoice.avatar.* +import com.gorios.lanvoice.dialogue.* +import android.os.TestScheduler +import android.media.CodecFixture +import android.media.MediaPlayer +import android.graphics.SurfaceTexture +import android.view.TextureView +fun main(args: Array) { + android.content.Archive.zip=java.util.zip.ZipFile(args.single()) + val context=android.content.Context();val pack=checkNotNull(AvatarPack.load(context)) + println("LOADER|status=${pack.motionStatus}|full=${pack.emotionAction!=null}|actions=${pack.emotionAction?.actionPack?.assets?.size}") + val index=checkNotNull(pack.emotionAction) + fun rig(): Triple>> { + TestScheduler.reset();CodecFixture.reset();MediaPlayer.created.clear();CodecFixture.emitNativeSurface=true + 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 } + val binding=AvatarMediaBinding();binding.beginTurn(7) + val trace=mutableListOf>() + val view=EmotionActionAvatarView(context,pack,binding) { trace.add(TestScheduler.now to it) } + view.render(true);TestScheduler.advanceBy(1);return Triple(view,binding,trace) + } + fun printTrace(case: String,trace: List>) { + var old="";for((ms,v) in trace)if(v.actual!=old) { println("FRAME|case=$case|ms=$ms|actual=${v.actual}|cursor=${v.clipId}|reason=${v.reason}");old=v.actual } + } + run { + val(view,binding,trace)=rig();TestScheduler.advanceBy(30_000) + printTrace("idle30s",trace);println("IDLE|current=${binding.currentPackageId}|visual=${binding.visualStatus}") + check(trace.none { it.second.actual=="media_failed" });check(trace.any { it.second.actual.startsWith("body_idle-") }) + TestScheduler.until(15_000) { binding.currentPackageId?.startsWith("idle-")==true } + val parked=checkNotNull(binding.currentPackageId);val startRows=trace.size + binding.beginTurn(8);binding.intent(null,false);TestScheduler.advanceBy(30_000) + val changed=trace.drop(startRows).any { it.second.actual=="bridge" || it.second.actual.startsWith("idle_variant_") } + println("IDLE_NEWTURN|parked=$parked|after30s=${binding.currentPackageId}|routed=$changed|status=${binding.visualStatus}") + check(changed) + check(trace.drop(startRows).any { it.second.actual=="body_neutral-01" }) + for(wanted in listOf("idle-breathe-01","idle-microshift-01")) { + TestScheduler.until(50_000) { binding.currentPackageId==wanted } + val start=trace.size + repeat(5) { i -> binding.beginTurn(10L+i);binding.intent(null,false);TestScheduler.advanceBy(100) } + binding.prepare(mediaReply(RoleEmotion.HAPPY,turn=14,seq=1)) + binding.intent(mediaReply(RoleEmotion.NEUTRAL,turn=14,seq=2),true) + TestScheduler.advanceBy(200);check(binding.currentPackageId==wanted) + binding.intent(null,false) + TestScheduler.advanceBy(30_000) + val returned=trace.drop(start).any { it.second.actual=="body_neutral-01" } + check(returned && trace.drop(start).any { it.second.actual=="bridge" }) + println("IDLE_NEWTURN|parked=$wanted|turns=5|legal_return=$returned|after30s=${binding.currentPackageId}") + } + view.dispose();TestScheduler.advanceBy(100) + } + run { + val(view,binding,trace)=rig() + binding.prepare(mediaReply(RoleEmotion.HAPPY,seq=1));TestScheduler.advanceBy(500) + println("EMOTION|prepare_only|current=${binding.currentPackageId}|visual=${binding.visualStatus}") + binding.intent(mediaReply(RoleEmotion.HAPPY,seq=2),true);TestScheduler.advanceBy(1000) + binding.intent(null,false) // Same MainActivity path when short reply drained. + TestScheduler.advanceBy(6000) + println("EMOTION|requested=happy1|current=${binding.currentPackageId}|visual=${binding.visualStatus}") + binding.intent(mediaReply(RoleEmotion.SAD,seq=3),true);TestScheduler.advanceBy(1500);binding.intent(null,false);TestScheduler.advanceBy(7000) + println("EMOTION|requested=sad1|current=${binding.currentPackageId}|visual=${binding.visualStatus}") + printTrace("happy_sad",trace);check(trace.none { it.second.actual=="media_failed" });check(binding.currentPackageId=="sad-01");view.dispose();TestScheduler.advanceBy(100) + } + for(initial in listOf(RoleEmotion.NEUTRAL,RoleEmotion.HAPPY)) { + val(view,binding,trace)=rig();binding.intent(mediaReply(initial),false);TestScheduler.advanceBy(6000) + var stop: ((Boolean)->Unit)?=null;val statuses=mutableListOf() + val controller=ActionController(index.actionPack,binding,{TestScheduler.now},{stop=it},statuses::add,choose={0}) + check(controller.offer(ActionPlan("public_fixture_action_id_001",7,index.actionPack!!.manifestSha,120000))) + println("DANCE|initial=${initial.wire}|offered=true|before_stop_players=${MediaPlayer.created.size}") + stop!!(true);MediaPlayer.created.single().let { it.prepared!!(it) };TestScheduler.until(15000) { MediaPlayer.created.any { it.started } || trace.any { it.second.actual=="media_failed" } } + val movie=MediaPlayer.created.single();println("DANCE|started=${movie.started}|current=${binding.currentPackageId}|status=${statuses.last().status}") + val field=view.javaClass.getDeclaredField("textures").apply { isAccessible=true };val textures=field.get(view) as List + val listener=textures[3].surfaceTextureListener!!;val surface=textures[3].surfaceTexture!! + index.actionPack.assets.first().media!!.ptsUs.forEachIndexed { i,pts -> + if(i>0) TestScheduler.advanceBy(42);surface.timestamp=pts*1000;listener.onSurfaceTextureUpdated(surface) + if(i==0) { + println("DANCE_LAYER|initial=${initial.wire}|first_frame_alpha=${textures[3].alpha}|body_alpha=${textures.take(3).map { it.alpha }}") + TestScheduler.advanceBy(21) + println("DANCE_LAYER|initial=${initial.wire}|after_21ms_alpha=${textures[3].alpha}|body_alpha=${textures.take(3).map { it.alpha }}|movie_started=${movie.started}|phase=${binding.visualStatus}") + check(movie.started && textures[3].alpha==1f && textures.take(3).all { it.alpha==0f }) + } + check(textures[3].alpha==1f && textures.take(3).all { it.alpha==0f }) + } + println("DANCE_OWNER|initial=${initial.wire}|frames=241|music_visible=241|conversation_visible=0|state=${binding.diagnosticState}") + TestScheduler.advanceBy(50);movie.completion!!(movie);TestScheduler.until(15000) { statuses.last().status!="started" } + println("DANCE|ended=${statuses.last().status}|released=${movie.released}|return=${binding.currentPackageId}") + printTrace("dance_${initial.wire}",trace);check(statuses.last().status=="completed");check(binding.currentPackageId=="neutral-01");view.dispose();TestScheduler.advanceBy(100) + } + println("HOST_REPLAY|fix_verified=true|dance_layer_retained=true|idle_newturn_legal_return=true|native_device=false|surface_availability_mock=true|record_stop_mock=true|json_adapter=host") +} +''' +with tempfile.TemporaryDirectory(prefix='baji-runtime-audit-') as td: + tmp=Path(td);files=[] + for path in (ROOT/'tests/avatar').glob('*.kt'): + if path.name not in ('Pack.kt','Context.kt','Graphics.kt'):files.append(path) + for name,txt in [('Json.kt',json_adapter),('Context.kt',context),('Graphics.kt',graphics),('BuildConfig.kt',build),('Audit.kt',main)]: + p=tmp/name;p.write_text(txt);files.append(p) + files+=real+[ROOT/'app/src/main/java/com/gorios/lanvoice/avatar/AvatarPack.kt'] + subprocess.run([java,'-cp',compiler,'org.jetbrains.kotlin.cli.jvm.K2JVMCompiler','-no-stdlib','-no-reflect','-jvm-target','17','-nowarn','-classpath',cp,'-d',str(tmp),*map(str,files)],check=True) + subprocess.run([java,'-cp',str(tmp)+':'+cp,'AuditKt',str(args.apk.resolve())],check=True,timeout=45) diff --git a/scripts/check-reply-regressions.py b/scripts/check-reply-regressions.py index c6b018a..a2ab187 100644 --- a/scripts/check-reply-regressions.py +++ b/scripts/check-reply-regressions.py @@ -27,7 +27,7 @@ source = ROOT/'app/src/main/java/com/gorios/lanvoice' suites = [ ('session','ConnectionCheckKt', [source/'audio/PlaybackActivity.kt', source/'audio/VoiceSession.kt', source/'avatar/ActionController.kt', source/'dialogue/ReplyEmotion.kt', source/'net/DialogueClient.kt', source/'expression/FaceCueRules.kt', source/'expression/ExpressionRules.kt', source/'expression/FaceDiagnostics.kt']), ('playback','PlaybackCheckKt', [source/'audio/AudioPlayback.kt', source/'audio/PlaybackActivity.kt']), - ('avatar','AvatarCheckKt', [source/'avatar/ConversationMediaDriver.kt',source/'avatar/AvatarMediaBinding.kt',source/'avatar/EmotionActionAvatarView.kt',source/'avatar/ContinuousAvatarView.kt',source/'avatar/ConversationPackagePlanner.kt', source/'avatar/EmotionActionManifest.kt', source/'avatar/ActionController.kt', source/'avatar/RoleVisualSelection.kt', source/'avatar/ContinuousAvatarManifest.kt', source/'avatar/ContinuousMouth.kt', source/'avatar/ContinuousFramePresenter.kt', source/'avatar/ContinuousBodyRenderer.kt', source/'avatar/EngineeringGraphAdmission.kt', source/'avatar/OfflineAvatarTrace.kt', source/'avatar/NeutralGraphContract.kt', source/'avatar/SafeVideoDriver.kt', source/'avatar/CodecAnchorVideoPort.kt', source/'avatar/AutoConversation.kt', source/'avatar/SafeAvatarGraph.kt', source/'avatar/SafeTransitionPlanner.kt', source/'avatar/SafeAvatarManifest.kt', source/'avatar/TransitionDiagnostics.kt', source/'avatar/AvatarController.kt', source/'avatar/CallIntent.kt', source/'avatar/AvatarVideoView.kt', source/'audio/PlaybackActivity.kt', source/'dialogue/ReplyEmotion.kt']), + ('avatar','AvatarCheckKt', [source/'diag/DiagnosticLog.kt',source/'avatar/ConversationMediaDriver.kt',source/'avatar/AvatarMediaBinding.kt',source/'avatar/EmotionActionAvatarView.kt',source/'avatar/ContinuousAvatarView.kt',source/'avatar/ConversationPackagePlanner.kt', source/'avatar/EmotionActionManifest.kt', source/'avatar/ActionController.kt', source/'avatar/RoleVisualSelection.kt', source/'avatar/ContinuousAvatarManifest.kt', source/'avatar/ContinuousMouth.kt', source/'avatar/ContinuousFramePresenter.kt', source/'avatar/ContinuousBodyRenderer.kt', source/'avatar/EngineeringGraphAdmission.kt', source/'avatar/OfflineAvatarTrace.kt', source/'avatar/NeutralGraphContract.kt', source/'avatar/SafeVideoDriver.kt', source/'avatar/CodecAnchorVideoPort.kt', source/'avatar/AutoConversation.kt', source/'avatar/SafeAvatarGraph.kt', source/'avatar/SafeTransitionPlanner.kt', source/'avatar/SafeAvatarManifest.kt', source/'avatar/TransitionDiagnostics.kt', source/'avatar/AvatarController.kt', source/'avatar/CallIntent.kt', source/'avatar/AvatarVideoView.kt', source/'audio/PlaybackActivity.kt', source/'dialogue/ReplyEmotion.kt']), ('capture','CaptureCheckKt', [source/'audio/AudioCapture.kt']), ('protocol','ProtocolCheckKt', [source/'avatar/ActionController.kt', source/'net/DialogueProtocol.kt', source/'dialogue/ReplyEmotion.kt', source/'expression/FaceCueRules.kt', source/'expression/ExpressionRules.kt']), ] diff --git a/scripts/package-avatar-emotion.py b/scripts/package-avatar-emotion.py index 9afcda2..131d839 100644 --- a/scripts/package-avatar-emotion.py +++ b/scripts/package-avatar-emotion.py @@ -24,6 +24,9 @@ TOOLS=Path('/home/ubuntu/android-build/sdk/build-tools/34.0.0') CERT='b9608336bc1ed1de3269bb4594f9fe718daaa5439511c5187aa385d2b799dcf1' LEGACY_PIN='0a3c4918ba746019cf1df885bec66e5858a8950997dac4f64e7d37094be64dad' ROLLBACK=ROOT/'artifacts/lan-voice-v070-stage-candidate-code16-arm64-debug.apk' +RUNTIME_FIX_PIN='987e125a7d7a2cde99121b5f5246c82f4dbe36c4899d3d49eaffd1a68bafb887' +CODE18=ROOT/'artifacts/lan-voice-v070-action-emotion-code18-arm64-debug.apk' +CODE18_SHA='ea6ca77c2e4cc995c3ca2c097e71beef092cfcba1f452b18f255bd341e5f8723' ROLLBACK_SHA='687c350ec64d693dd8a0bc6e8f1e249816842631119f17a4cbdd38b0cb1e7336' spec=importlib.util.spec_from_file_location('runtime_gate',ROOT/'scripts/check-avatar-runtime.py') runtime_gate=importlib.util.module_from_spec(spec);spec.loader.exec_module(runtime_gate) @@ -283,7 +286,18 @@ def packaging_tests_current(): for name,digest in evidence['hashes'].items(): require(file_sha(ROOT/name)==digest,'untested packaging source: '+name) -def publish(report,output,requested,full=False): +def verify_runtime_fix_assets(built,pin): + require(pin==RUNTIME_FIX_PIN,'runtime fix must preserve reviewed pin') + require(file_sha(CODE18)==CODE18_SHA,'code18 rollback drift') + with zipfile.ZipFile(CODE18) as old,zipfile.ZipFile(built) as new: + paths=lambda z:{n for n in z.namelist() if n.startswith('assets/avatar/') and not n.endswith('/')} + require(paths(new)==paths(old),'runtime fix avatar inventory changed') + for name in paths(old): require(new.read(name)==old.read(name),'runtime fix asset changed: '+name) + require(sha(new.read('assets/'+ASSET_ROOT+'manifest.json'))==pin,'runtime fix packaged pin') + return len([p for p in paths(new) if p.startswith('assets/'+ASSET_ROOT)]) + + +def publish(report,output,requested,full=False,runtime_fix=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') @@ -291,11 +305,12 @@ def publish(report,output,requested,full=False): 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 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()],check=True,cwd=ROOT) + '-PemotionManifestSha='+report['manifest_sha256'],'-PactionVersionCode='+str(version),'-PavatarFullActionCandidate='+str(full).lower(),'-PavatarRuntimeFix='+str(runtime_fix).lower()],check=True,cwd=ROOT) built=ROOT/'app/build/outputs/apk/debug/app-debug.apk';badge=badging(built) - version_name='0.7.0' if full else '0.7.0-emotion-dev' + version_name='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') @@ -312,8 +327,10 @@ def publish(report,output,requested,full=False): config=ROOT/'app/build/generated/source/buildConfig/debug/com/gorios/lanvoice/BuildConfig.java' require('EMOTION_MANIFEST_SHA = "'+report['manifest_sha256']+'"' in config.read_text(),'compiled index pin mismatch') require(version>=next_version((ROOT/'artifacts').glob('*.apk')),'version became occupied during build') - stem='action-emotion' if full else 'emotion-candidate' - artifact=ROOT/f'artifacts/lan-voice-v070-{stem}-code{version}-arm64-debug.apk' + if runtime_fix: require(verify_runtime_fix_assets(built,report['manifest_sha256'])==len(report['files']),'runtime fix file count') + stem='runtime-fix' if runtime_fix else ('action-emotion' if full else 'emotion-candidate') + release='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() with artifact.with_suffix('.apk.sha256').open('xb') as f: f.write(checksum) @@ -324,7 +341,7 @@ def publish(report,output,requested,full=False): require(file_sha(ROLLBACK)==ROLLBACK_SHA,'rollback modified') delivery={'status':'full_action_emotion_candidate' if full else 'partial_emotion_candidate','version_name':version_name,'version_code':version,'url':url,'sha256':digest, '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':False} + 'http_bytes_verified':True,'device':'not_run','naturalness':'not_certified','paid_calls':0,'gateway_deployed':False,'runtime_fix':runtime_fix,'runtime_files_unchanged_from_code18':len(report['files']) if runtime_fix else None} (output/'delivery.json').write_text(json.dumps(delivery,indent=2)+'\n') return delivery @@ -340,6 +357,7 @@ def main(): parser.add_argument('--backup',type=Path) parser.add_argument('--action-registry',type=Path,help='Reviewed public gateway registry required for full dance release') parser.add_argument('--version-code',type=int,help='Default max existing APK code+1, minimum17') + parser.add_argument('--runtime-fix',action='store_true',help='0.7.1 Android-only repair; all avatar bytes must equal frozen code18') args=parser.parse_args();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') @@ -356,7 +374,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'])) 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) if args.publish else {k:v for k,v in report.items() if k!='files'} print(json.dumps(result,indent=2)) diff --git a/tests/avatar/AvatarCheck.kt b/tests/avatar/AvatarCheck.kt index acf87ae..4d1469b 100644 --- a/tests/avatar/AvatarCheck.kt +++ b/tests/avatar/AvatarCheck.kt @@ -6,6 +6,7 @@ import android.media.MediaPlayer import android.view.TextureView fun main() { + boundedRuntimeDiagnosticCheck() dynamicBodyCheck() actionCheck() emotionActionCheck() diff --git a/tests/avatar/Diagnostic.kt b/tests/avatar/Diagnostic.kt index c4ddeb1..cf79a5e 100644 --- a/tests/avatar/Diagnostic.kt +++ b/tests/avatar/Diagnostic.kt @@ -1,2 +1,12 @@ -package com.gorios.lanvoice.diag -object DiagnosticLog { fun record(tag: String,msg: String) {} } +import com.gorios.lanvoice.diag.DiagnosticLog +fun boundedRuntimeDiagnosticCheck() { + val before=DiagnosticLog.snapshot().size + repeat(501) { DiagnosticLog.state("bounded_test","action","owner=action frame=$it",it.toLong()) } + check(DiagnosticLog.snapshot().size==before+1) + DiagnosticLog.state("bounded_test","action","owner=action frame=240",10_000) + DiagnosticLog.state("bounded_test","conversation","owner=conversation frame=96",10_001) + check(DiagnosticLog.snapshot().size==before+3) + repeat(600) { DiagnosticLog.record("bounded_ring","fixed_enum=sample") } + check(DiagnosticLog.snapshot().size==500) + println("PASS: bounded runtime diagnostics: state changes +10s monotonic summaries, no per-frame churn,500-entry ring") +} diff --git a/tests/avatar/MediaWiringCheck.kt b/tests/avatar/MediaWiringCheck.kt index ee19ce7..5cbf402 100644 --- a/tests/avatar/MediaWiringCheck.kt +++ b/tests/avatar/MediaWiringCheck.kt @@ -138,6 +138,53 @@ fun actualMediaViewCheck() { check(statuses.size==before);cases++ actionView.dispose();TestScheduler.advanceBy(100) } + // Ten seconds of real production held-renderer callbacks must never steal + // the movie TextureView. Native/codec/record ports remain deterministic doubles. + for(mode in listOf("complete", "cancel", "failed", "background", "newturn")) { + reset() + val base=mediaFixtureIndex() + val original=base.actionPack!!.assets.first() + val media=original.media!!.copy(ptsUs=List(241) { it*1_000_000L/24 },durationUs=10_041_667, + sourceFrame=0,returnFrame=96) + val asset=original.copy(durationMs=10_042,media=media) + val index=base.copy(actionPack=base.actionPack.copy(assets=listOf(asset,asset.copy(id="asset_02")))) + val (v,b,trace)=rig(index) + var confirmation: ((Boolean)->Unit)?=null + val statuses=mutableListOf() + val controller=ActionController(index.actionPack,b,{TestScheduler.now},{confirmation=it},statuses::add) + check(controller.offer(ActionPlan("z".repeat(24),7,"a".repeat(64),25000))) + confirmation!!(true);val player=MediaPlayer.created.single();val prepared=player.prepared!! + prepared(player);TestScheduler.until { player.started } + val textures=v.children.filterIsInstance() + fun latch(pts: Long) { val t=textures[3].surfaceTexture!!;t.timestamp=pts*1000;textures[3].surfaceTextureListener!!.onSurfaceTextureUpdated(t) } + val owner=driverField.get(v) as ConversationMediaDriver + // Delayed first frame leaves the last valid body visible, with ACTION owning it. + TestScheduler.advanceBy(80);check(owner.layerOwner==ConversationMediaDriver.LayerOwner.ACTION && textures[3].alpha==0f);cases++ + latch(0);TestScheduler.advanceBy(21) + check(textures[3].alpha==1f && textures.take(3).all { it.alpha==0f } && player.started);cases++ + prepared(player) // Duplicated ready cannot start/reclaim again. + for(i in 1..240) { + TestScheduler.advanceBy(42);latch(media.ptsUs[i]) + check(textures[3].alpha==1f && textures.take(3).all { it.alpha==0f } && owner.layerOwner==ConversationMediaDriver.LayerOwner.ACTION);cases++ + if(i==120) { v.render(true);check(driverField.get(v)===owner);cases++ } // Settings continuity. + } + check(statuses.none { it.status=="completed" });cases++ // Time alone is insufficient. + when(mode) { + "complete" -> { player.completion!!(player);player.completion!!(player) + TestScheduler.until { statuses.last().status=="completed" } + check(player.released && owner.layerOwner==ConversationMediaDriver.LayerOwner.CONVERSATION && trace.last().clipId.startsWith("f96_"));cases++ } + "failed" -> { player.error!!(player,1,2);TestScheduler.until { !controller.active } } + "background" -> { controller.cancel();v.render(false);TestScheduler.until { !controller.active } } + "newturn" -> { b.beginTurn(8);controller.cancel();TestScheduler.until { !controller.active } } + else -> { controller.cancel();TestScheduler.until { !controller.active } } + } + val before=statuses.size;val alphas=textures.map { it.alpha } + prepared(player);player.completion!!(player);player.error!!(player,1,2) + check(statuses.size==before && textures.map { it.alpha }==alphas && player.released);cases++ + v.dispose();TestScheduler.advanceBy(100) + check(owner.layerOwner==ConversationMediaDriver.LayerOwner.STOPPED);cases++ + } + // New idle rows use the actual view/renderer/codec path and reviewed graph. reset() val idleIndex=mediaFixtureIndex().let { it.copy(actionPack=null,visuals=it.visuals.map { p->p.copy(emotion=RoleEmotion.NEUTRAL) }) } @@ -146,11 +193,15 @@ fun actualMediaViewCheck() { check(idleTrace.all { it.actual=="body_neutral" });cases++ TestScheduler.until(15_000) { idleBinding.currentPackageId in setOf("happy","sad") } val firstIdle=idleBinding.currentPackageId + // New turns on the actual displayed variant must retain its legal rotation. + val turnBefore=idleTrace.size + repeat(4) { i -> idleBinding.beginTurn(8L+i);idleBinding.intent(null,false);TestScheduler.advanceBy(200) } + check(idleBinding.currentPackageId==firstIdle && idleTrace.drop(turnBefore).none { it.actual=="body_neutral" });cases++ check(idleTrace.any { it.actual=="bridge" } && idleBinding.visualStatus=="neutral_idle_variant");cases++ TestScheduler.until(15_000) { idleBinding.currentPackageId=="neutral" } TestScheduler.until(15_000) { idleBinding.currentPackageId in setOf("happy","sad") } check(idleBinding.currentPackageId!=firstIdle && idleTrace.none { it.actual=="media_failed" });cases++ - idleBinding.intent(mediaReply(RoleEmotion.NEUTRAL),true) + idleBinding.intent(mediaReply(RoleEmotion.NEUTRAL,turn=11),true) TestScheduler.until(15_000) { idleBinding.currentPackageId=="neutral" } val speechStart=idleTrace.size;TestScheduler.advanceBy(9000) check(idleTrace.drop(speechStart).all { it.actual=="body_neutral" });cases++ @@ -177,5 +228,5 @@ fun actualMediaViewCheck() { renderer.close();TestScheduler.advanceBy(50) check(GLFixture.deleted>=126 && CodecFixture.releases==1);cases++ CodecFixture.reset();MediaPlayer.created.clear() - println("PASS: $cases actual EmotionActionAvatarView/binding/held GLES renderer/MediaPlayer callback cases: hidden header/final mismatch, final slight,97→49→121 and24→30fps/native loops, real bridge frames/latest turn, settings continuity, mic-confirm/cancel-pending/failure gate, safe exit/music first+last PTS/native end/release/idle-A, completion order, cancel/error/background/stale callbacks; deterministic Android doubles, device/naturalness not_run") + println("PASS: $cases actual EmotionActionAvatarView/binding/held GLES renderer/MediaPlayer callback assertions: hidden header/final mismatch, final slight,97→49→121 and24→30fps/native loops, real bridge frames/latest turn, settings continuity, mic-confirm/cancel-pending/failure gate, safe exit/music first+last PTS/native end/release/idle-A, completion order, cancel/error/background/stale callbacks; deterministic Android doubles, device/naturalness not_run") } diff --git a/tests/packaging/test_emotion_package.py b/tests/packaging/test_emotion_package.py index 9566f24..4d6e94f 100644 --- a/tests/packaging/test_emotion_package.py +++ b/tests/packaging/test_emotion_package.py @@ -210,6 +210,28 @@ class PackageTests(unittest.TestCase): self.assertEqual(pack.next_version(['one.apk','two.apk']),20) self.assertEqual(pack.next_version([]),17) + def test_runtime_fix_preserves_all_frozen_avatar_bytes(self): + import zipfile + old=self.base/'frozen18.apk';new=self.base/'runtime19.apk' + payload={'assets/'+pack.ASSET_ROOT+'manifest.json':b'exact index', + 'assets/'+pack.ASSET_ROOT+'own.png':b'own frame patch', + 'assets/avatar/legacy/body.mp4':b'rollback media'} + def write(path,data): + with zipfile.ZipFile(path,'w') as z: + for name,value in data.items(): z.writestr(name,value) + write(old,payload);write(new,payload) + pin=pack.sha(b'exact index') + with patch.object(pack,'CODE18',old),patch.object(pack,'CODE18_SHA',pack.file_sha(old)),patch.object(pack,'RUNTIME_FIX_PIN',pin): + self.assertEqual(pack.verify_runtime_fix_assets(new,pin),2) + for kind in ('bytes','missing','extra','pin'): + changed=dict(payload) + if kind=='bytes': changed['assets/'+pack.ASSET_ROOT+'own.png']=b'changed' + if kind=='missing': del changed['assets/avatar/legacy/body.mp4'] + if kind=='extra': changed['assets/'+pack.ASSET_ROOT+'review.png']=b'not runtime' + write(new,changed) + with self.subTest(kind=kind),self.assertRaises(ValueError): + pack.verify_runtime_fix_assets(new,'0'*64 if kind=='pin' else pin) + def test_cli_no_pin_no_import_no_output(self): self.manifest.write_text(json.dumps(self.index));out=self.base/'no-pin-output' result=subprocess.run([sys.executable,str(ROOT/'scripts/package-avatar-emotion.py'), diff --git a/tests/session/ConnectionCheck.kt b/tests/session/ConnectionCheck.kt index 0afb025..de3ac15 100644 --- a/tests/session/ConnectionCheck.kt +++ b/tests/session/ConnectionCheck.kt @@ -82,7 +82,7 @@ fun runChecks() { event("auth"); check(socket.sent.size == 1) event("hello") check(statuses == listOf(ConnectionStatus.CONNECTED)) - check(logs.filterNot { it.startsWith("listen ") || it.startsWith("ws control skipped") } == listOf("ws open", "auth ok", "hello sent", "hello received")) + check(logs.filterNot { it.startsWith("listen ") || it.startsWith("ws control skipped") } == listOf("ws open", "auth ok", "hello sent action_offer=none generation=0", "hello received action_pack=unknown generation=0")) check(client.listen(true)) event("hello"); check(statuses.count { it == ConnectionStatus.CONNECTED } == 1) event("history"); check(events.last() == EventKind.HISTORY) @@ -96,9 +96,18 @@ fun runChecks() { Handler.drain() check(socket.sent == listOf("hello")) check(statuses == listOf(ConnectionStatus.CONNECTED)) - check(logs == listOf("auth ok", "hello sent", "ws open", "hello received")) + check(logs == listOf("auth ok", "hello sent action_offer=none generation=0", "ws open", "hello received action_pack=unknown generation=0")) close() } + for((hello,expected) in listOf("hello" to "unknown","hello available" to "accepted","hello unavailable" to "unavailable")) { + Fixture().apply { + event("auth");event(hello);check(client.actionNegotiation==expected) + // Old-generation HELLO cannot overwrite the negotiated connection. + client.callbacks(-1).onMessage(socket,"hello unavailable");Handler.drain() + check(client.actionNegotiation==expected) + close();check(client.actionNegotiation=="disconnected") + } + } Fixture().apply { event("hello"); check(statuses.isEmpty() && !client.listen(true)) handshake(); check(statuses.last() == ConnectionStatus.CONNECTED) @@ -243,7 +252,7 @@ fun runChecks() { check(states.last().connection == ConnectionStatus.CONNECTING) cb.onMessage(current, "hello"); Handler.drain() check(states.last().connection == ConnectionStatus.CONNECTED) - check(listOf("auth ok", "hello sent", "hello received").all { it in logs }) + check(listOf("auth ok", "hello sent action_offer=none generation=1", "hello received action_pack=unknown generation=1").all { it in logs }) session.startVoice() session.background(showDisconnectReason = true) check(states.last().connection == ConnectionStatus.DISCONNECTED && !states.last().voiceActive) @@ -471,7 +480,7 @@ fun runChecks() { session.release(); barrier.countDown(); Handler.drain() } check(DebugLogUpload.records.any { it.first == "connect" && it.second.startsWith("state=connected reason=") }) - check(DebugLogUpload.records.any { it == "auth" to "hello received" }) + check(DebugLogUpload.records.any { it == "auth" to "hello received action_pack=unknown generation=0" }) check(DebugLogUpload.records.any { it == "ws" to "ws event=history" }) check(DebugLogUpload.records.none { (_, message) -> "auth_ready" in message }) check(DebugLogUpload.records.any { (_, message) -> "finish reason=control_send_failure stack=" in message }) diff --git a/tests/session/ProtocolEvents.kt b/tests/session/ProtocolEvents.kt index f3862ea..95d7710 100644 --- a/tests/session/ProtocolEvents.kt +++ b/tests/session/ProtocolEvents.kt @@ -24,6 +24,8 @@ object DialogueProtocol { fun parseEvent(text: String) = when (text) { "auth" -> ServerEvent("auth", EventKind.AUTH, Payload()) "auth failed" -> ServerEvent("auth", EventKind.AUTH, Payload(false)) + "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()) "error" -> ServerEvent("error", EventKind.ERROR, Payload()) "unknown" -> ServerEvent("auth_ready", EventKind.UNKNOWN, Payload())