fix(android): retain action layer and idle rotation across turns
This commit is contained in:
+3
-1
@@ -18,6 +18,7 @@ def avatarNatural = providers.gradleProperty('avatarNatural').orNull == 'true'
|
|||||||
def avatarUiCandidate = providers.gradleProperty('avatarUiCandidate').orNull == 'true'
|
def avatarUiCandidate = providers.gradleProperty('avatarUiCandidate').orNull == 'true'
|
||||||
def avatarMouthCandidate = providers.gradleProperty('avatarMouthCandidate').orNull == 'true'
|
def avatarMouthCandidate = providers.gradleProperty('avatarMouthCandidate').orNull == 'true'
|
||||||
def avatarActionCandidate = providers.gradleProperty('avatarActionCandidate').orNull == 'true'
|
def avatarActionCandidate = providers.gradleProperty('avatarActionCandidate').orNull == 'true'
|
||||||
|
def avatarRuntimeFix = providers.gradleProperty('avatarRuntimeFix').orNull == 'true'
|
||||||
def avatarFullActionCandidate = providers.gradleProperty('avatarFullActionCandidate').orNull == 'true'
|
def avatarFullActionCandidate = providers.gradleProperty('avatarFullActionCandidate').orNull == 'true'
|
||||||
def actionVersionCode = (providers.gradleProperty('actionVersionCode').orNull ?: '16').toInteger()
|
def actionVersionCode = (providers.gradleProperty('actionVersionCode').orNull ?: '16').toInteger()
|
||||||
if (avatarActionCandidate && (!avatarMouthCandidate || actionVersionCode < 16)) {
|
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 && !(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 (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 (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}/)) {
|
if (avatarNatural && !(naturalManifestSha ==~ /[0-9a-f]{64}/)) {
|
||||||
throw new GradleException('Natural debug candidate requires exact runtime manifest SHA')
|
throw new GradleException('Natural debug candidate requires exact runtime manifest SHA')
|
||||||
}
|
}
|
||||||
@@ -82,7 +84,7 @@ android {
|
|||||||
targetSdk 34
|
targetSdk 34
|
||||||
testInstrumentationRunner 'com.gorios.lanvoice.AvatarCleanUiInstrumentation'
|
testInstrumentationRunner 'com.gorios.lanvoice.AvatarCleanUiInstrumentation'
|
||||||
versionCode avatarActionCandidate ? actionVersionCode : (avatarMouthCandidate ? 15 : (avatarUiCandidate ? 14 : (avatarNatural ? 13 : 12)))
|
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' }
|
ndk { abiFilters 'arm64-v8a' }
|
||||||
}
|
}
|
||||||
compileOptions { sourceCompatibility JavaVersion.VERSION_17; targetCompatibility JavaVersion.VERSION_17 }
|
compileOptions { sourceCompatibility JavaVersion.VERSION_17; targetCompatibility JavaVersion.VERSION_17 }
|
||||||
|
|||||||
@@ -215,6 +215,11 @@ class MainActivity : ComponentActivity() {
|
|||||||
DiagnosticReportInfo(
|
DiagnosticReportInfo(
|
||||||
appVersion = appVersion,
|
appVersion = appVersion,
|
||||||
versionCode = packageManager.getPackageInfo(packageName, 0).versionCode,
|
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,
|
cameraGranted = checkSelfPermission(Manifest.permission.CAMERA) == PackageManager.PERMISSION_GRANTED,
|
||||||
cameraStatus = expressionState.status,
|
cameraStatus = expressionState.status,
|
||||||
cameraPermissionPending = entry.permissionPending == EntryPermission.CAMERA,
|
cameraPermissionPending = entry.permissionPending == EntryPermission.CAMERA,
|
||||||
|
|||||||
@@ -84,8 +84,15 @@ class VoiceSession(
|
|||||||
private val actions = ActionController(reviewedActionPack, actionPlayer, SystemClock::elapsedRealtime,
|
private val actions = ActionController(reviewedActionPack, actionPlayer, SystemClock::elapsedRealtime,
|
||||||
stopCapture = { confirmed ->
|
stopCapture = { confirmed ->
|
||||||
captureEpoch++; capturing = false
|
captureEpoch++; capturing = false
|
||||||
capture.stopAndConfirm { stopped -> main.post { confirmed(stopped) } }
|
diagnostic("action_capture state=stop_pending turn=$currentTurn epoch=$captureEpoch")
|
||||||
}, status = { status -> if (state.connection == ConnectionStatus.CONNECTED) dialogue.actionStatus(status) },
|
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 ->
|
changed = { active ->
|
||||||
if (!active) { actionTimeout?.let { main.removeCallbacks(it) }; actionTimeout = null }
|
if (!active) { actionTimeout?.let { main.removeCallbacks(it) }; actionTimeout = null }
|
||||||
if (active) { playback.interrupt(); resetReply("action") }
|
if (active) { playback.interrupt(); resetReply("action") }
|
||||||
@@ -294,6 +301,7 @@ class VoiceSession(
|
|||||||
if (clearObservation) faceCue = FaceCueObservation()
|
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()
|
fun faceDiagnosticsSnapshot() = faceDiagnostics.snapshot()
|
||||||
|
|
||||||
private fun sendFaceContext() {
|
private fun sendFaceContext() {
|
||||||
@@ -398,21 +406,26 @@ class VoiceSession(
|
|||||||
diagnostic("onEvent kind=${event.kind.name} turn_id=$turn")
|
diagnostic("onEvent kind=${event.kind.name} turn_id=$turn")
|
||||||
if (event.kind == EventKind.EXPRESSION_PREPARE) {
|
if (event.kind == EventKind.EXPRESSION_PREPARE) {
|
||||||
if (isActive() && hasTurn && turn == currentTurn && blockedTurn != turn && !actions.active) {
|
if (isActive() && hasTurn && turn == currentTurn && blockedTurn != turn && !actions.active) {
|
||||||
if (event.type.endsWith(".cancel")) onPrepareExpression(null)
|
if (event.type.endsWith(".cancel")) { diagnostic("emotion_prepare state=cancelled turn=$turn");onPrepareExpression(null) }
|
||||||
else onPrepareExpression(ReplyEmotion.fromWire(turn,event.payload.opt("seq"),event.payload.opt("emotion"),
|
else {
|
||||||
event.payload.opt("intensity"),"model"))
|
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
|
return
|
||||||
}
|
}
|
||||||
if (event.kind == EventKind.ACTION) {
|
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()
|
if (event.type == "action.cancel") actions.cancel()
|
||||||
else if (event.type == "action.plan") {
|
else if (event.type == "action.plan") {
|
||||||
val id = event.payload.optString("action_id")
|
val id = event.payload.optString("action_id")
|
||||||
val ttl = (event.payload.opt("ttl_ms") as? Number)?.toLong() ?: 0L
|
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"))
|
dialogue.actionStatus(ActionStatus(id,currentTurn,"failed"))
|
||||||
else if(actions.active) {
|
} else if(actions.active) {
|
||||||
actionTimeout?.let { main.removeCallbacks(it) }
|
actionTimeout?.let { main.removeCallbacks(it) }
|
||||||
actionTimeout = Runnable { actionTimeout = null; actions.tick() }.also { main.postDelayed(it,ttl) }
|
actionTimeout = Runnable { actionTimeout = null; actions.tick() }.also { main.postDelayed(it,ttl) }
|
||||||
}
|
}
|
||||||
|
|||||||
@@ -6,6 +6,7 @@ import com.gorios.lanvoice.dialogue.ReplyEmotion
|
|||||||
class AvatarMediaBinding : ActionPlayer {
|
class AvatarMediaBinding : ActionPlayer {
|
||||||
val currentPackageId: String? get() = driver?.currentPackageId
|
val currentPackageId: String? get() = driver?.currentPackageId
|
||||||
val visualStatus: String get() = driver?.visualStatus ?: "renderer_unavailable"
|
val visualStatus: String get() = driver?.visualStatus ?: "renderer_unavailable"
|
||||||
|
val diagnosticState: String get() = driver?.diagnosticState ?: "owner=stopped renderer=unavailable"
|
||||||
val selection: RoleVisualSelection? get() = driver?.selection
|
val selection: RoleVisualSelection? get() = driver?.selection
|
||||||
private var driver: ConversationMediaDriver?=null
|
private var driver: ConversationMediaDriver?=null
|
||||||
private var prepared: ReplyEmotion?=null
|
private var prepared: ReplyEmotion?=null
|
||||||
|
|||||||
@@ -1,5 +1,6 @@
|
|||||||
package com.gorios.lanvoice.avatar
|
package com.gorios.lanvoice.avatar
|
||||||
|
|
||||||
|
import com.gorios.lanvoice.diag.DiagnosticLog
|
||||||
import android.content.Context
|
import android.content.Context
|
||||||
import org.json.JSONArray
|
import org.json.JSONArray
|
||||||
import org.json.JSONObject
|
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. */
|
/** 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,
|
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 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 {
|
companion object {
|
||||||
const val STATIC_IMAGE_SHA = "36a078ad9e1d2929612e9baa2af524bda90dafceddc4515dd448fc08121d7dd2"
|
const val STATIC_IMAGE_SHA = "36a078ad9e1d2929612e9baa2af524bda90dafceddc4515dd448fc08121d7dd2"
|
||||||
private const val STATIC_ROOT = "avatar/a01-standing-arms-reference/"
|
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? {
|
fun load(context: Context): AvatarPack? {
|
||||||
val fallback = STATIC_ROOT + "frames/reference.png"
|
val fallback = STATIC_ROOT + "frames/reference.png"
|
||||||
try { check(sha(read(context,fallback,8_000_000)) == STATIC_IMAGE_SHA) }
|
try { check(sha(read(context,fallback,8_000_000)) == STATIC_IMAGE_SHA) }
|
||||||
catch (_: Exception) { return null }
|
catch (_: Exception) { DiagnosticLog.record("avatar_loader","result=static_identity_rejected");return null }
|
||||||
val static = AvatarPack(fallback=fallback)
|
var static = AvatarPack(fallback=fallback)
|
||||||
if(BuildConfig.DEBUG && BuildConfig.EMOTION_MANIFEST_SHA.isNotEmpty()) {
|
if(BuildConfig.DEBUG && BuildConfig.EMOTION_MANIFEST_SHA.isNotEmpty()) {
|
||||||
|
var stage="index_read_or_hash"
|
||||||
val admitted=try {
|
val admitted=try {
|
||||||
val root="avatar/a01-expression-action-v1/"
|
val root="avatar/a01-expression-action-v1/"
|
||||||
val raw=read(context,root+"manifest.json",2_000_000)
|
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),
|
val index=checkNotNull(EmotionActionManifest.read(jsonMap(JSONObject(String(raw,Charsets.UTF_8))),sha(raw),
|
||||||
BuildConfig.EMOTION_MANIFEST_SHA,root) { path,hash ->
|
BuildConfig.EMOTION_MANIFEST_SHA,root) { path,hash ->
|
||||||
val runtimeRoot=root+path.substringBeforeLast('/')+"/"
|
val runtimeRoot=root+path.substringBeforeLast('/')+"/"
|
||||||
|
stage="runtime_read_or_hash"
|
||||||
val bytes=read(context,root+path,2_000_000)
|
val bytes=read(context,root+path,2_000_000)
|
||||||
check(sha(bytes)==hash)
|
check(sha(bytes)==hash)
|
||||||
|
stage="runtime_schema"
|
||||||
val runtime=checkNotNull(ContinuousAvatarManifest.read(jsonMap(JSONObject(String(bytes,Charsets.UTF_8))),hash,hash,true,runtimeRoot))
|
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
|
var total=0L
|
||||||
|
stage="edge_media_hash"
|
||||||
for(clip in index.edges.map { it.clip }) {
|
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
|
val data=read(context,root+clip.path,64_000_000);check(sha(data)==clip.sha256);total+=data.size
|
||||||
check(total<=512_000_000)
|
check(total<=512_000_000)
|
||||||
}
|
}
|
||||||
|
stage="action_media_hash"
|
||||||
for(asset in index.actionPack?.assets.orEmpty()) {
|
for(asset in index.actionPack?.assets.orEmpty()) {
|
||||||
val media=checkNotNull(asset.media);val data=read(context,media.root+media.path,128_000_000)
|
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)
|
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")
|
static.copy(continuous=index.packages.getValue(index.fallbackId),emotionAction=index,motionStatus="externally_pinned_emotion_graph",emotionAdmission="accepted")
|
||||||
} catch(_: Exception) { null }
|
} catch(_: Exception) {
|
||||||
if(admitted!=null) return admitted
|
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.
|
// Continue into independently pinned neutral admission as a whole pack.
|
||||||
}
|
}
|
||||||
if (BuildConfig.DEBUG && BuildConfig.AVATAR_NATURAL) return try {
|
if (BuildConfig.DEBUG && BuildConfig.AVATAR_NATURAL) return try {
|
||||||
|
|||||||
@@ -87,8 +87,8 @@ fun CallScreen(state: VoiceUiState,entry: EntryPhase,permissionMessage: String?,
|
|||||||
LaunchedEffect(state.voiceActive,pack) {
|
LaunchedEffect(state.voiceActive,pack) {
|
||||||
if(state.voiceActive) while(true) {
|
if(state.voiceActive) while(true) {
|
||||||
val selected=latestAvatar
|
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"}")
|
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(1_000)
|
delay(10_000)
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
CleanAvatarScaffold(avatar={
|
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("当前画面:${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)
|
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)
|
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)
|
AvatarDiagnostics(pack,video)
|
||||||
Text("AEC:${state.aec.name} · 效果待真机验证",fontSize=12.sp)
|
Text("AEC:${state.aec.name} · 效果待真机验证",fontSize=12.sp)
|
||||||
Row {
|
Row {
|
||||||
|
|||||||
@@ -66,19 +66,30 @@ class ConversationMediaDriver(private val index: EmotionActionIndex,
|
|||||||
private var returning=false
|
private var returning=false
|
||||||
private var actionFinished: ((ActionEnd)->Unit)?=null
|
private var actionFinished: ((ActionEnd)->Unit)?=null
|
||||||
private var actionFailed: (()->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 musicEpoch=0L
|
||||||
private var closing=0
|
private var closing=0
|
||||||
private val releaseWaiters=mutableListOf<()->Unit>()
|
private val releaseWaiters=mutableListOf<()->Unit>()
|
||||||
fun beginTurn(id: Long?) {
|
fun beginTurn(id: Long?) {
|
||||||
if(id==turn) return
|
if(id==turn) return
|
||||||
turn=id;seq=-1;generation++;revision=0;talk=false;selection=null;idleTarget=null;resetIdleCycles()
|
turn=id;seq=-1;generation++;revision=0;talk=false;selection=null
|
||||||
selectedId=visible?.packageId ?: index.fallbackId
|
// 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()
|
if(!inBridge && revealing==null) discardRoute()
|
||||||
applyMouth()
|
applyMouth()
|
||||||
}
|
}
|
||||||
fun start() {
|
fun start() {
|
||||||
if(active || closing!=0) return
|
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
|
val slot=prepare(index.fallbackId,0);visible=slot
|
||||||
// Ports must deliver callbacks asynchronously, like both Android ports.
|
// Ports must deliver callbacks asynchronously, like both Android ports.
|
||||||
}
|
}
|
||||||
@@ -98,10 +109,9 @@ class ConversationMediaDriver(private val index: EmotionActionIndex,
|
|||||||
seq=reply.sequence
|
seq=reply.sequence
|
||||||
selection=RoleVisualSelector.select(reply.emotion,reply.intensity,index.visuals,index.fallbackId)
|
selection=RoleVisualSelector.select(reply.emotion,reply.intensity,index.visuals,index.fallbackId)
|
||||||
selectedId=checkNotNull(selection).packageId
|
selectedId=checkNotNull(selection).packageId
|
||||||
idleTarget=null;resetIdleCycles()
|
idleTarget=null
|
||||||
}
|
}
|
||||||
talk=talking && reply?.turnId==turn
|
talk=talking && reply?.turnId==turn
|
||||||
if(talk) { idleTarget=null;idleCycles=0 }
|
|
||||||
applyMouth()
|
applyMouth()
|
||||||
if(active && !inBridge && !actionStarted) plan()
|
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 ||
|
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 }
|
!sequential || previous==null && (key.index!=entry || key.loopOrdinal!=0L)) { fail();return@prepare }
|
||||||
slot.key=key;slot.closedMouth=closedMouth
|
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) {
|
if(slot===visible) {
|
||||||
reveal(slot.number);report(if(inBridge) "bridge" else "body_${slot.packageId}",key)
|
reveal(slot.number);report(if(inBridge) "bridge" else "body_${slot.packageId}",key)
|
||||||
if(!inBridge) { chooseIdleAtLoopEnd(slot,key,previous);applyMouth();plan() }
|
if(!inBridge) { chooseIdleAtLoopEnd(slot,key,previous);applyMouth();plan() }
|
||||||
@@ -150,7 +165,7 @@ class ConversationMediaDriver(private val index: EmotionActionIndex,
|
|||||||
idleCycles++
|
idleCycles++
|
||||||
if(idleCycles<idleCycleGoal) return
|
if(idleCycles<idleCycleGoal) return
|
||||||
resetIdleCycles()
|
resetIdleCycles()
|
||||||
if(idleTarget!=null && slot.packageId==idleTarget && slot.packageId!=index.fallbackId) {
|
if(slot.packageId!=index.fallbackId) {
|
||||||
idleTarget=index.fallbackId;report("idle_variant_return_queued",key);return
|
idleTarget=index.fallbackId;report("idle_variant_return_queued",key);return
|
||||||
}
|
}
|
||||||
if(slot.packageId!=index.fallbackId || selectedId!=index.fallbackId) return
|
if(slot.packageId!=index.fallbackId || selectedId!=index.fallbackId) return
|
||||||
@@ -173,7 +188,7 @@ class ConversationMediaDriver(private val index: EmotionActionIndex,
|
|||||||
if(source.packageId==wanted) {
|
if(source.packageId==wanted) {
|
||||||
if(edge!=null && edge?.from!=edge?.to) { discardRoute();return }
|
if(edge!=null && edge?.from!=edge?.to) { discardRoute();return }
|
||||||
if(action!=null && musicReady && source.closedMouth && key.index==action?.media?.sourceFrame) {
|
if(action!=null && musicReady && source.closedMouth && key.index==action?.media?.sourceFrame) {
|
||||||
actionStarted=true;talk=false;applyMouth();report("action",key)
|
actionStarted=true;layerOwner=LayerOwner.ACTION;talk=false;applyMouth();report("action",key)
|
||||||
music.start()
|
music.start()
|
||||||
return
|
return
|
||||||
}
|
}
|
||||||
@@ -214,7 +229,7 @@ class ConversationMediaDriver(private val index: EmotionActionIndex,
|
|||||||
val current=edge ?: return fail()
|
val current=edge ?: return fail()
|
||||||
if(destination.key?.index!=current.toFrame) return fail()
|
if(destination.key?.index!=current.toFrame) return fail()
|
||||||
activate(destination) {
|
activate(destination) {
|
||||||
visible=destination;target=null;bridge=null;edge=null;inBridge=false
|
visible=destination;target=null;bridge=null;edge=null;inBridge=false;resetIdleCycles()
|
||||||
closeSlot(old);reveal(destination.number);report("body_${destination.packageId}",destination.key)
|
closeSlot(old);reveal(destination.number);report("body_${destination.packageId}",destination.key)
|
||||||
applyMouth();plan();if(!actionStarted && !holdExit(destination)) destination.port.advance()
|
applyMouth();plan();if(!actionStarted && !holdExit(destination)) destination.port.advance()
|
||||||
}
|
}
|
||||||
@@ -223,7 +238,7 @@ class ConversationMediaDriver(private val index: EmotionActionIndex,
|
|||||||
if(revealing!=null) return
|
if(revealing!=null) return
|
||||||
revealing=destination
|
revealing=destination
|
||||||
destination.port.activateMouth(talk && action==null && destination.pack.apertureMode,generation,++revision) {
|
destination.port.activateMouth(talk && action==null && destination.pack.apertureMode,generation,++revision) {
|
||||||
if(active && destination.live && revealing===destination) {
|
if(active && layerOwner==LayerOwner.CONVERSATION && destination.live && revealing===destination) {
|
||||||
revealing=null;ready()
|
revealing=null;ready()
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
@@ -238,35 +253,38 @@ class ConversationMediaDriver(private val index: EmotionActionIndex,
|
|||||||
override fun play(asset: ActionAsset,finished: (ActionEnd)->Unit,failed: ()->Unit) {
|
override fun play(asset: ActionAsset,finished: (ActionEnd)->Unit,failed: ()->Unit) {
|
||||||
val media=asset.media
|
val media=asset.media
|
||||||
if(!active || action!=null || media==null || index.actionPack?.assets?.contains(asset)!=true) { failed();return }
|
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
|
val epoch=++musicEpoch
|
||||||
music.prepare(media,{ if(active && epoch==musicEpoch && action==asset) { musicReady=true;plan() } },
|
music.prepare(media,{ if(active && epoch==musicEpoch && action===asset && !actionStarted && !returning) { musicReady=true;plan() } else ignoredCallbacks++ },
|
||||||
{ if(active && epoch==musicEpoch && actionStarted) reveal(3) },{
|
{ if(active && epoch==musicEpoch && action===asset && layerOwner==LayerOwner.ACTION && actionStarted && !returning && !musicPresented) {
|
||||||
if(active && epoch==musicEpoch && action==asset && actionStarted) {
|
musicPresented=true;reveal(3);report("action_first_frame",null)
|
||||||
|
} else ignoredCallbacks++ },{
|
||||||
|
if(active && epoch==musicEpoch && action===asset && actionStarted && !returning) {
|
||||||
returning=true;closing++
|
returning=true;closing++
|
||||||
// onCompletion alone is not audio-release evidence.
|
// onCompletion alone is not audio-release evidence.
|
||||||
music.close {
|
music.close {
|
||||||
closing--;releasedIfDone()
|
closing--;releasedIfDone()
|
||||||
if(active && epoch==musicEpoch && action==asset) {
|
if(active && epoch==musicEpoch && action==asset) {
|
||||||
visible?.let(::closeSlot);visible=null;discardRoute()
|
visible?.let(::closeSlot);visible=null;discardRoute()
|
||||||
|
musicPresented=false;report("action_audio_released",null)
|
||||||
target=prepare(media.returnPackage,media.returnFrame)
|
target=prepare(media.returnPackage,media.returnFrame)
|
||||||
// Target's first composed frame is the restored idle evidence.
|
// Target's first composed frame is the restored idle evidence.
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
}
|
} else ignoredCallbacks++
|
||||||
},{ if(active && epoch==musicEpoch) fail() })
|
},{ if(active && epoch==musicEpoch && action===asset) fail() else ignoredCallbacks++ })
|
||||||
}
|
}
|
||||||
private fun restoreAction(slot: Slot) {
|
private fun restoreAction(slot: Slot) {
|
||||||
val media=action?.media ?: return
|
val media=action?.media ?: return
|
||||||
if(!returning || slot!==target || slot.key?.index!=media.returnFrame) 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)
|
reveal(slot.number);report("body_${slot.packageId}",slot.key)
|
||||||
val completed=actionFinished;actionFinished=null;actionFailed=null
|
val completed=actionFinished;actionFinished=null;actionFailed=null
|
||||||
selectedId=slot.packageId ?: index.fallbackId;applyMouth();slot.port.advance()
|
selectedId=slot.packageId ?: index.fallbackId;applyMouth();slot.port.advance()
|
||||||
completed?.invoke(ActionEnd(true,true,true))
|
completed?.invoke(ActionEnd(true,true,true))
|
||||||
}
|
}
|
||||||
override fun stop(released: ()->Unit) {
|
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
|
actionFinished=null;actionFailed=null;talk=false;generation++;revision=0
|
||||||
reveal(null);releaseWaiters.add(released)
|
reveal(null);releaseWaiters.add(released)
|
||||||
active=false;visible=null;revealing=null;target=null;bridge=null;edge=null;inBridge=false
|
active=false;visible=null;revealing=null;target=null;bridge=null;edge=null;inBridge=false
|
||||||
|
|||||||
@@ -1,5 +1,6 @@
|
|||||||
package com.gorios.lanvoice.avatar
|
package com.gorios.lanvoice.avatar
|
||||||
|
|
||||||
|
import com.gorios.lanvoice.diag.DiagnosticLog
|
||||||
import android.content.Context
|
import android.content.Context
|
||||||
import android.graphics.BitmapFactory
|
import android.graphics.BitmapFactory
|
||||||
import android.graphics.Matrix
|
import android.graphics.Matrix
|
||||||
@@ -23,6 +24,14 @@ class EmotionActionAvatarView(context: Context,private val pack: AvatarPack,
|
|||||||
private var active=false
|
private var active=false
|
||||||
private var released=false
|
private var released=false
|
||||||
private var movie: AndroidMusicPort?=null
|
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<ContinuousBodyRenderer>(3)
|
private val renderers=arrayOfNulls<ContinuousBodyRenderer>(3)
|
||||||
init {
|
init {
|
||||||
addView(still,LayoutParams(-1,-1))
|
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() }
|
fun render(foreground: Boolean) { active=foreground;if(active) start() else suspend() }
|
||||||
private fun start() {
|
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
|
if(!active || released || driver!=null || textures.any { !it.isAvailable }) return
|
||||||
val index=checkNotNull(pack.emotionAction)
|
val index=checkNotNull(pack.emotionAction)
|
||||||
val mouthClock=ConversationMouthClock()
|
val mouthClock=ConversationMouthClock()
|
||||||
@@ -67,10 +78,16 @@ class EmotionActionAvatarView(context: Context,private val pack: AvatarPack,
|
|||||||
}
|
}
|
||||||
}
|
}
|
||||||
},music,{ slot ->
|
},music,{ slot ->
|
||||||
textures.forEachIndexed { i,v->v.alpha=if(i==slot) 1f else 0f };still.alpha=if(slot==null) 1f else 0f
|
if(visibleLayer!=slot) {
|
||||||
},{ phase,key -> report(VideoPresentation(actual=phase,reason="reviewed_media_path",
|
visibleLayer=slot
|
||||||
clipId=key?.let { "f${it.index}_loop${it.loopOrdinal}" } ?: "")) })
|
textures.forEachIndexed { i,v->v.alpha=if(i==slot) 1f else 0f };still.alpha=if(slot==null) 1f else 0f
|
||||||
driver=current;current.start();binding.attach(current) { if(active && !released) { current.start();binding.attach(current) } };fitMovie()
|
}
|
||||||
|
},{ 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() {
|
private fun fitMovie() {
|
||||||
val view=textures[3];if(view.width<=0 || view.height<=0) return
|
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) })
|
view.setTransform(Matrix().apply { setScale(fit.scaleX,fit.scaleY,view.width/2f,view.height/2f) })
|
||||||
}
|
}
|
||||||
private fun suspend() {
|
private fun suspend() {
|
||||||
|
main.removeCallbacks(summary)
|
||||||
val old=driver ?: return
|
val old=driver ?: return
|
||||||
old.stop { binding.detach(old);if(driver===old) { driver=null;movie=null };if(active) start() }
|
old.stop { binding.detach(old);if(driver===old) { driver=null;movie=null };if(active) start() }
|
||||||
}
|
}
|
||||||
|
|||||||
@@ -18,6 +18,18 @@ object DiagnosticLog {
|
|||||||
private val lock = Any()
|
private val lock = Any()
|
||||||
private val entries = ArrayDeque<Entry>()
|
private val entries = ArrayDeque<Entry>()
|
||||||
private var nextId = 0L
|
private var nextId = 0L
|
||||||
|
private val states = LinkedHashMap<String, Pair<String, Long>>()
|
||||||
|
|
||||||
|
/** 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(
|
fun record(
|
||||||
tag: String, message: String,
|
tag: String, message: String,
|
||||||
|
|||||||
@@ -30,6 +30,11 @@ data class DiagnosticReportInfo(
|
|||||||
val phase: String,
|
val phase: String,
|
||||||
val aec: String,
|
val aec: String,
|
||||||
val versionCode: Int = 0,
|
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 cameraGranted: Boolean = false,
|
||||||
val cameraStatus: ExpressionStatus = ExpressionStatus.OFF,
|
val cameraStatus: ExpressionStatus = ExpressionStatus.OFF,
|
||||||
val cameraPermissionPending: Boolean = false,
|
val cameraPermissionPending: Boolean = false,
|
||||||
@@ -93,6 +98,9 @@ object DiagnosticReportUpload {
|
|||||||
.put("phase", info.phase)
|
.put("phase", info.phase)
|
||||||
.put("aec", info.aec)
|
.put("aec", info.aec)
|
||||||
.put("version_code", info.versionCode)
|
.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("camera", JSONObject().put("granted", info.cameraGranted).put("status", info.cameraStatus.name.lowercase())
|
||||||
.put("permission_pending", info.cameraPermissionPending).put("face_sharing", info.faceSharing))
|
.put("permission_pending", info.cameraPermissionPending).put("face_sharing", info.faceSharing))
|
||||||
.put("role_playing", info.rolePlaying)
|
.put("role_playing", info.rolePlaying)
|
||||||
|
|||||||
@@ -75,6 +75,7 @@ class DialogueClient(
|
|||||||
private var ready = false
|
private var ready = false
|
||||||
private var wsOpened = false
|
private var wsOpened = false
|
||||||
private var authReceived = false
|
private var authReceived = false
|
||||||
|
var actionNegotiation: String = "disconnected";private set
|
||||||
private var helloSent = false
|
private var helloSent = false
|
||||||
private var loggedAudioTurn: Long? = null
|
private var loggedAudioTurn: Long? = null
|
||||||
private var handshakeTimeout: Runnable? = null
|
private var handshakeTimeout: Runnable? = null
|
||||||
@@ -93,6 +94,7 @@ class DialogueClient(
|
|||||||
wsOpened = false
|
wsOpened = false
|
||||||
authReceived = false
|
authReceived = false
|
||||||
helloSent = false
|
helloSent = false
|
||||||
|
actionNegotiation = "pending"
|
||||||
loggedAudioTurn = null
|
loggedAudioTurn = null
|
||||||
healthCall?.cancel()
|
healthCall?.cancel()
|
||||||
healthCall = null
|
healthCall = null
|
||||||
@@ -187,6 +189,7 @@ class DialogueClient(
|
|||||||
generation++ // Invalidate before cancellation can trigger onFailure.
|
generation++ // Invalidate before cancellation can trigger onFailure.
|
||||||
cancelHandshakeTimeout()
|
cancelHandshakeTimeout()
|
||||||
ready = false
|
ready = false
|
||||||
|
actionNegotiation = "disconnected"
|
||||||
val previousHealth = healthCall
|
val previousHealth = healthCall
|
||||||
healthCall = null
|
healthCall = null
|
||||||
previousHealth?.cancel()
|
previousHealth?.cancel()
|
||||||
@@ -290,9 +293,10 @@ class DialogueClient(
|
|||||||
if (authReceived) return@dispatch
|
if (authReceived) return@dispatch
|
||||||
authReceived = true
|
authReceived = true
|
||||||
connectionLog("auth ok", "auth")
|
connectionLog("auth ok", "auth")
|
||||||
if (webSocket.send(DialogueProtocol.hello(actionPackSha()))) {
|
val offeredPack=actionPackSha()
|
||||||
|
if (webSocket.send(DialogueProtocol.hello(offeredPack))) {
|
||||||
helloSent = true
|
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 {
|
} else {
|
||||||
connectionLog("hello send failed", "error")
|
connectionLog("hello send failed", "error")
|
||||||
finish(webSocket, ConnectionStatus.DISCONNECTED, "hello_send_failure")
|
finish(webSocket, ConnectionStatus.DISCONNECTED, "hello_send_failure")
|
||||||
@@ -306,7 +310,12 @@ class DialogueClient(
|
|||||||
}
|
}
|
||||||
ready = true
|
ready = true
|
||||||
cancelHandshakeTimeout()
|
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")
|
updateStatus(ConnectionStatus.CONNECTED, "server_hello_received")
|
||||||
}
|
}
|
||||||
if (event.kind == EventKind.ERROR && !ready) {
|
if (event.kind == EventKind.ERROR && !ready) {
|
||||||
@@ -391,6 +400,7 @@ class DialogueClient(
|
|||||||
previousHealth?.cancel()
|
previousHealth?.cancel()
|
||||||
socket = null
|
socket = null
|
||||||
ready = false
|
ready = false
|
||||||
|
actionNegotiation = "disconnected"
|
||||||
webSocket?.cancel()
|
webSocket?.cancel()
|
||||||
updateStatus(status, reason)
|
updateStatus(status, reason)
|
||||||
}
|
}
|
||||||
|
|||||||
@@ -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 <APK> --sha256 <exact APK SHA>` 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.
|
||||||
@@ -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<String,Any?>); is List<*> -> JSONArray(v); null -> JSONObject.NULL;else ->v }
|
||||||
|
class JSONObject(private val map: Map<String,Any?>) {
|
||||||
|
constructor(raw: String):this(Parser(raw).value() as Map<String,Any?>)
|
||||||
|
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<s.length && s[i].isWhitespace()) i++ }
|
||||||
|
fun value(): Any? {
|
||||||
|
space()
|
||||||
|
return when(s[i]) {
|
||||||
|
'{' -> { i++;space();val m=linkedMapOf<String,Any?>();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<Any?>();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<s.length && s[i] in "-+0123456789.eE")i++;val n=s.substring(start,i);if(n.any { it in ".eE" })n.toDouble() else n.toIntOrNull() ?: n.toLong() }
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
'''
|
||||||
|
context=r'''
|
||||||
|
package android.content
|
||||||
|
class Context { val assets = Assets() }
|
||||||
|
class Assets {
|
||||||
|
fun open(path: String): java.io.InputStream = java.io.ByteArrayInputStream(Archive.zip.getInputStream(checkNotNull(Archive.zip.getEntry("assets/"+path)) { "missing_asset" }).use { it.readBytes() })
|
||||||
|
fun openFd(path: String) = Descriptor(path)
|
||||||
|
}
|
||||||
|
object Archive { lateinit var zip: java.util.zip.ZipFile }
|
||||||
|
object AssetFixture { val paths=mutableMapOf<java.io.FileDescriptor,String>() }
|
||||||
|
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<String>) {
|
||||||
|
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<EmotionActionAvatarView,AvatarMediaBinding,MutableList<Pair<Long,VideoPresentation>>> {
|
||||||
|
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<Pair<Long,VideoPresentation>>()
|
||||||
|
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<Pair<Long,VideoPresentation>>) {
|
||||||
|
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<ActionStatus>()
|
||||||
|
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<TextureView>
|
||||||
|
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)
|
||||||
@@ -27,7 +27,7 @@ source = ROOT/'app/src/main/java/com/gorios/lanvoice'
|
|||||||
suites = [
|
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']),
|
('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']),
|
('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']),
|
('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']),
|
('protocol','ProtocolCheckKt', [source/'avatar/ActionController.kt', source/'net/DialogueProtocol.kt', source/'dialogue/ReplyEmotion.kt', source/'expression/FaceCueRules.kt', source/'expression/ExpressionRules.kt']),
|
||||||
]
|
]
|
||||||
|
|||||||
@@ -24,6 +24,9 @@ TOOLS=Path('/home/ubuntu/android-build/sdk/build-tools/34.0.0')
|
|||||||
CERT='b9608336bc1ed1de3269bb4594f9fe718daaa5439511c5187aa385d2b799dcf1'
|
CERT='b9608336bc1ed1de3269bb4594f9fe718daaa5439511c5187aa385d2b799dcf1'
|
||||||
LEGACY_PIN='0a3c4918ba746019cf1df885bec66e5858a8950997dac4f64e7d37094be64dad'
|
LEGACY_PIN='0a3c4918ba746019cf1df885bec66e5858a8950997dac4f64e7d37094be64dad'
|
||||||
ROLLBACK=ROOT/'artifacts/lan-voice-v070-stage-candidate-code16-arm64-debug.apk'
|
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'
|
ROLLBACK_SHA='687c350ec64d693dd8a0bc6e8f1e249816842631119f17a4cbdd38b0cb1e7336'
|
||||||
spec=importlib.util.spec_from_file_location('runtime_gate',ROOT/'scripts/check-avatar-runtime.py')
|
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)
|
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)
|
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']),
|
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')
|
'live emotion release needs bridge-own TALK runtimes')
|
||||||
tested_source(full);packaging_tests_current();require(file_sha(ROLLBACK)==ROLLBACK_SHA,'rollback drift')
|
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:
|
if requested is not None:
|
||||||
require(requested>=version,'version code occupied');version=requested
|
require(requested>=version,'version code occupied');version=requested
|
||||||
require(not full or version>=18,'full candidate needs code >=18')
|
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',
|
subprocess.run([str(ROOT/'scripts/build.sh'),'assembleDebug','compileDebugAndroidTestKotlin','-PavatarActionCandidate=true',
|
||||||
'-PavatarNatural=true','-PavatarMouthCandidate=true','-PnaturalManifestSha='+LEGACY_PIN,
|
'-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)
|
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'"):
|
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(text in badge,'APK metadata: '+text)
|
||||||
require(re.search(r'^native-code: (.+)$',badge,re.M)[1].strip()=="'arm64-v8a'",'APK ABI')
|
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'
|
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('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')
|
require(version>=next_version((ROOT/'artifacts').glob('*.apk')),'version became occupied during build')
|
||||||
stem='action-emotion' if full else 'emotion-candidate'
|
if runtime_fix: require(verify_runtime_fix_assets(built,report['manifest_sha256'])==len(report['files']),'runtime fix file count')
|
||||||
artifact=ROOT/f'artifacts/lan-voice-v070-{stem}-code{version}-arm64-debug.apk'
|
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)
|
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()
|
digest=file_sha(artifact);checksum=f'{digest} {artifact.name}\n'.encode()
|
||||||
with artifact.with_suffix('.apk.sha256').open('xb') as f: f.write(checksum)
|
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')
|
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,
|
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'],
|
'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')
|
(output/'delivery.json').write_text(json.dumps(delivery,indent=2)+'\n')
|
||||||
return delivery
|
return delivery
|
||||||
|
|
||||||
@@ -340,6 +357,7 @@ def main():
|
|||||||
parser.add_argument('--backup',type=Path)
|
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('--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('--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()
|
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')
|
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')
|
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')
|
require(not args.previous_pin and not args.backup,'previous import report required')
|
||||||
import_files(manifest.parent,report['files'],target)
|
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')
|
(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))
|
print(json.dumps(result,indent=2))
|
||||||
|
|
||||||
|
|
||||||
|
|||||||
@@ -6,6 +6,7 @@ import android.media.MediaPlayer
|
|||||||
import android.view.TextureView
|
import android.view.TextureView
|
||||||
|
|
||||||
fun main() {
|
fun main() {
|
||||||
|
boundedRuntimeDiagnosticCheck()
|
||||||
dynamicBodyCheck()
|
dynamicBodyCheck()
|
||||||
actionCheck()
|
actionCheck()
|
||||||
emotionActionCheck()
|
emotionActionCheck()
|
||||||
|
|||||||
@@ -1,2 +1,12 @@
|
|||||||
package com.gorios.lanvoice.diag
|
import com.gorios.lanvoice.diag.DiagnosticLog
|
||||||
object DiagnosticLog { fun record(tag: String,msg: String) {} }
|
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")
|
||||||
|
}
|
||||||
|
|||||||
@@ -138,6 +138,53 @@ fun actualMediaViewCheck() {
|
|||||||
check(statuses.size==before);cases++
|
check(statuses.size==before);cases++
|
||||||
actionView.dispose();TestScheduler.advanceBy(100)
|
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<ActionStatus>()
|
||||||
|
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<TextureView>()
|
||||||
|
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.
|
// New idle rows use the actual view/renderer/codec path and reviewed graph.
|
||||||
reset()
|
reset()
|
||||||
val idleIndex=mediaFixtureIndex().let { it.copy(actionPack=null,visuals=it.visuals.map { p->p.copy(emotion=RoleEmotion.NEUTRAL) }) }
|
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++
|
check(idleTrace.all { it.actual=="body_neutral" });cases++
|
||||||
TestScheduler.until(15_000) { idleBinding.currentPackageId in setOf("happy","sad") }
|
TestScheduler.until(15_000) { idleBinding.currentPackageId in setOf("happy","sad") }
|
||||||
val firstIdle=idleBinding.currentPackageId
|
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++
|
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=="neutral" }
|
||||||
TestScheduler.until(15_000) { idleBinding.currentPackageId in setOf("happy","sad") }
|
TestScheduler.until(15_000) { idleBinding.currentPackageId in setOf("happy","sad") }
|
||||||
check(idleBinding.currentPackageId!=firstIdle && idleTrace.none { it.actual=="media_failed" });cases++
|
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" }
|
TestScheduler.until(15_000) { idleBinding.currentPackageId=="neutral" }
|
||||||
val speechStart=idleTrace.size;TestScheduler.advanceBy(9000)
|
val speechStart=idleTrace.size;TestScheduler.advanceBy(9000)
|
||||||
check(idleTrace.drop(speechStart).all { it.actual=="body_neutral" });cases++
|
check(idleTrace.drop(speechStart).all { it.actual=="body_neutral" });cases++
|
||||||
@@ -177,5 +228,5 @@ fun actualMediaViewCheck() {
|
|||||||
renderer.close();TestScheduler.advanceBy(50)
|
renderer.close();TestScheduler.advanceBy(50)
|
||||||
check(GLFixture.deleted>=126 && CodecFixture.releases==1);cases++
|
check(GLFixture.deleted>=126 && CodecFixture.releases==1);cases++
|
||||||
CodecFixture.reset();MediaPlayer.created.clear()
|
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")
|
||||||
}
|
}
|
||||||
|
|||||||
@@ -210,6 +210,28 @@ class PackageTests(unittest.TestCase):
|
|||||||
self.assertEqual(pack.next_version(['one.apk','two.apk']),20)
|
self.assertEqual(pack.next_version(['one.apk','two.apk']),20)
|
||||||
self.assertEqual(pack.next_version([]),17)
|
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):
|
def test_cli_no_pin_no_import_no_output(self):
|
||||||
self.manifest.write_text(json.dumps(self.index));out=self.base/'no-pin-output'
|
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'),
|
result=subprocess.run([sys.executable,str(ROOT/'scripts/package-avatar-emotion.py'),
|
||||||
|
|||||||
@@ -82,7 +82,7 @@ fun runChecks() {
|
|||||||
event("auth"); check(socket.sent.size == 1)
|
event("auth"); check(socket.sent.size == 1)
|
||||||
event("hello")
|
event("hello")
|
||||||
check(statuses == listOf(ConnectionStatus.CONNECTED))
|
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))
|
check(client.listen(true))
|
||||||
event("hello"); check(statuses.count { it == ConnectionStatus.CONNECTED } == 1)
|
event("hello"); check(statuses.count { it == ConnectionStatus.CONNECTED } == 1)
|
||||||
event("history"); check(events.last() == EventKind.HISTORY)
|
event("history"); check(events.last() == EventKind.HISTORY)
|
||||||
@@ -96,9 +96,18 @@ fun runChecks() {
|
|||||||
Handler.drain()
|
Handler.drain()
|
||||||
check(socket.sent == listOf("hello"))
|
check(socket.sent == listOf("hello"))
|
||||||
check(statuses == listOf(ConnectionStatus.CONNECTED))
|
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()
|
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 {
|
Fixture().apply {
|
||||||
event("hello"); check(statuses.isEmpty() && !client.listen(true))
|
event("hello"); check(statuses.isEmpty() && !client.listen(true))
|
||||||
handshake(); check(statuses.last() == ConnectionStatus.CONNECTED)
|
handshake(); check(statuses.last() == ConnectionStatus.CONNECTED)
|
||||||
@@ -243,7 +252,7 @@ fun runChecks() {
|
|||||||
check(states.last().connection == ConnectionStatus.CONNECTING)
|
check(states.last().connection == ConnectionStatus.CONNECTING)
|
||||||
cb.onMessage(current, "hello"); Handler.drain()
|
cb.onMessage(current, "hello"); Handler.drain()
|
||||||
check(states.last().connection == ConnectionStatus.CONNECTED)
|
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.startVoice()
|
||||||
session.background(showDisconnectReason = true)
|
session.background(showDisconnectReason = true)
|
||||||
check(states.last().connection == ConnectionStatus.DISCONNECTED && !states.last().voiceActive)
|
check(states.last().connection == ConnectionStatus.DISCONNECTED && !states.last().voiceActive)
|
||||||
@@ -471,7 +480,7 @@ fun runChecks() {
|
|||||||
session.release(); barrier.countDown(); Handler.drain()
|
session.release(); barrier.countDown(); Handler.drain()
|
||||||
}
|
}
|
||||||
check(DebugLogUpload.records.any { it.first == "connect" && it.second.startsWith("state=connected reason=") })
|
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.any { it == "ws" to "ws event=history" })
|
||||||
check(DebugLogUpload.records.none { (_, message) -> "auth_ready" in message })
|
check(DebugLogUpload.records.none { (_, message) -> "auth_ready" in message })
|
||||||
check(DebugLogUpload.records.any { (_, message) -> "finish reason=control_send_failure stack=" in message })
|
check(DebugLogUpload.records.any { (_, message) -> "finish reason=control_send_failure stack=" in message })
|
||||||
|
|||||||
@@ -24,6 +24,8 @@ object DialogueProtocol {
|
|||||||
fun parseEvent(text: String) = when (text) {
|
fun parseEvent(text: String) = when (text) {
|
||||||
"auth" -> ServerEvent("auth", EventKind.AUTH, Payload())
|
"auth" -> ServerEvent("auth", EventKind.AUTH, Payload())
|
||||||
"auth failed" -> ServerEvent("auth", EventKind.AUTH, Payload(false))
|
"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())
|
"hello" -> ServerEvent("hello", EventKind.HELLO, Payload())
|
||||||
"error" -> ServerEvent("error", EventKind.ERROR, Payload())
|
"error" -> ServerEvent("error", EventKind.ERROR, Payload())
|
||||||
"unknown" -> ServerEvent("auth_ready", EventKind.UNKNOWN, Payload())
|
"unknown" -> ServerEvent("auth_ready", EventKind.UNKNOWN, Payload())
|
||||||
|
|||||||
Reference in New Issue
Block a user