From 40abf3a14eb489bf03e327c61144795a764420c1 Mon Sep 17 00:00:00 2001 From: zenord Date: Tue, 13 Oct 2026 14:57:13 +0800 Subject: [PATCH] Show startup shell before background avatar admission and update reviewed capabilities --- .gitignore | 1 + app/build.gradle | 7 +- .../lanvoice/AvatarCleanUiInstrumentation.kt | 25 ++-- .../java/com/gorios/lanvoice/MainActivity.kt | 135 ++++++++++++------ .../com/gorios/lanvoice/audio/VoiceSession.kt | 7 + .../lanvoice/avatar/ActionController.kt | 8 +- .../com/gorios/lanvoice/avatar/AvatarPack.kt | 42 ++++-- .../com/gorios/lanvoice/avatar/CallScreen.kt | 68 +++++++-- .../avatar/ConversationMediaDriver.kt | 18 ++- .../avatar/EmotionActionAvatarView.kt | 16 ++- .../avatar/StartupAvatarRepository.kt | 74 ++++++++++ .../lanvoice/avatar/StartupAvatarView.kt | 115 +++++++++++++++ .../lanvoice/avatar/StartupLoadCache.kt | 79 ++++++++++ .../com/gorios/lanvoice/diag/StartupTrace.kt | 26 ++++ .../expression/ExpressionController.kt | 6 + .../com/gorios/lanvoice/net/DialogueClient.kt | 30 +++- .../gorios/lanvoice/net/DialogueProtocol.kt | 14 +- docs/COLD_START_FIX_074.md | 72 ++++++++++ gateway/SOURCE_MANIFEST.json | 21 ++- gateway/action_protocol.py | 11 ++ gateway/gateway.py | 26 +++- gateway/tests/test_capabilities_ready.py | 57 ++++++++ manifests/startup-white-01.json | 1 + scripts/check-avatar-apk-runtime.py | 62 ++++++-- scripts/check-avatar-ui.py | 11 +- scripts/check-reply-regressions.py | 2 + scripts/package-avatar-emotion.py | 37 +++-- scripts/prepare-startup-assets.py | 39 +++++ scripts/probe-startup-capabilities.py | 76 ++++++++++ tests/avatar/AndroidLog.kt | 2 + tests/avatar/AvatarCheck.kt | 2 + tests/avatar/PlaybackDiagnosticCheck.kt | 2 +- tests/avatar/Resources.kt | 2 + tests/avatar/StartupCheck.kt | 68 +++++++++ tests/avatar/Widget.kt | 3 + tests/packaging/test_startup_package.py | 29 ++++ tests/protocol/ProtocolCheck.kt | 4 + tests/session/AndroidLog.kt | 1 + tests/session/ConnectionCheck.kt | 1 + tests/session/ProtocolEvents.kt | 10 +- tests/session/StartupCapabilityCheck.kt | 27 ++++ 41 files changed, 1113 insertions(+), 124 deletions(-) create mode 100644 app/src/main/java/com/gorios/lanvoice/avatar/StartupAvatarRepository.kt create mode 100644 app/src/main/java/com/gorios/lanvoice/avatar/StartupAvatarView.kt create mode 100644 app/src/main/java/com/gorios/lanvoice/avatar/StartupLoadCache.kt create mode 100644 app/src/main/java/com/gorios/lanvoice/diag/StartupTrace.kt create mode 100644 docs/COLD_START_FIX_074.md create mode 100644 gateway/tests/test_capabilities_ready.py create mode 100644 manifests/startup-white-01.json create mode 100644 scripts/prepare-startup-assets.py create mode 100644 scripts/probe-startup-capabilities.py create mode 100644 tests/avatar/AndroidLog.kt create mode 100644 tests/avatar/Resources.kt create mode 100644 tests/avatar/StartupCheck.kt create mode 100644 tests/packaging/test_startup_package.py create mode 100644 tests/session/StartupCapabilityCheck.kt diff --git a/.gitignore b/.gitignore index 4f10131..0a582d4 100644 --- a/.gitignore +++ b/.gitignore @@ -11,3 +11,4 @@ __pycache__/ *.py[cod] .runtime/ app/src/main/assets/avatar/ +app/src/main/res/drawable-nodpi/startup_poster.png diff --git a/app/build.gradle b/app/build.gradle index 3a23de4..36203a7 100644 --- a/app/build.gradle +++ b/app/build.gradle @@ -18,6 +18,7 @@ def avatarNatural = providers.gradleProperty('avatarNatural').orNull == 'true' def avatarUiCandidate = providers.gradleProperty('avatarUiCandidate').orNull == 'true' def avatarMouthCandidate = providers.gradleProperty('avatarMouthCandidate').orNull == 'true' def avatarActionCandidate = providers.gradleProperty('avatarActionCandidate').orNull == 'true' +def avatarStartupFix = providers.gradleProperty('avatarStartupFix').orNull == 'true' def avatarPlaybackClockFix = providers.gradleProperty('avatarPlaybackClockFix').orNull == 'true' def avatarPlaybackDiagnostic = providers.gradleProperty('avatarPlaybackDiagnostic').orNull == 'true' def avatarRuntimeFix = providers.gradleProperty('avatarRuntimeFix').orNull == 'true' @@ -37,6 +38,7 @@ def emotionManifestSha = providers.gradleProperty('emotionManifestSha').orNull ? if (emotionManifestSha && !(emotionManifestSha ==~ /[0-9a-f]{64}/)) throw new GradleException('Emotion graph requires exact external manifest SHA') if (emotionManifestSha && (!avatarActionCandidate || !avatarMouthCandidate || !avatarNatural || actionVersionCode < 17)) throw new GradleException('Emotion candidate requires own-mouth runtime and a fresh code >=17') if (avatarFullActionCandidate && (!emotionManifestSha || !avatarActionCandidate || actionVersionCode < 18)) throw new GradleException('Full candidate requires pinned emotion/action graph and fresh code >=18') +if (avatarStartupFix && (!avatarPlaybackClockFix || actionVersionCode < 22)) throw new GradleException('Startup fix requires repaired playback and fresh code >=22') if (avatarPlaybackClockFix && (!avatarFullActionCandidate || actionVersionCode < 21 || emotionManifestSha != '987e125a7d7a2cde99121b5f5246c82f4dbe36c4899d3d49eaffd1a68bafb887')) throw new GradleException('Playback clock fix requires frozen full graph and fresh code >=21') if (avatarPlaybackDiagnostic && (!avatarFullActionCandidate || actionVersionCode < 20 || emotionManifestSha != '987e125a7d7a2cde99121b5f5246c82f4dbe36c4899d3d49eaffd1a68bafb887')) throw new GradleException('Playback diagnostic requires frozen full graph and fresh code >=20') if (avatarRuntimeFix && (!avatarFullActionCandidate || actionVersionCode < 19)) throw new GradleException('Runtime fix requires full pinned graph and fresh code >=19') @@ -75,6 +77,7 @@ def stagePackagedAssets = tasks.register('stagePackagedAssets', Sync) { from('src/main/assets') exclude 'avatar/a01-v1/**', 'avatar/a01-standing-v2/**' if (!avatarMouthCandidate) exclude 'avatar/a01-neutral-graph-v1/runtime-04/**' + if (!avatarStartupFix) exclude 'avatar/startup-white-01/**' if (!emotionManifestSha) exclude 'avatar/a01-expression-action-v1/**' into(packagedAssets) } @@ -88,7 +91,7 @@ android { targetSdk 34 testInstrumentationRunner 'com.gorios.lanvoice.AvatarCleanUiInstrumentation' versionCode avatarActionCandidate ? actionVersionCode : (avatarMouthCandidate ? 15 : (avatarUiCandidate ? 14 : (avatarNatural ? 13 : 12))) - versionName = avatarPlaybackClockFix ? '0.7.3' : avatarPlaybackDiagnostic ? '0.7.2' : avatarRuntimeFix ? '0.7.1' : (avatarActionCandidate ? '0.7.0' : ((avatarUiCandidate || avatarMouthCandidate) ? '0.6.2' : '0.6.1')) + versionName = avatarStartupFix ? '0.7.4' : avatarPlaybackClockFix ? '0.7.3' : avatarPlaybackDiagnostic ? '0.7.2' : avatarRuntimeFix ? '0.7.1' : (avatarActionCandidate ? '0.7.0' : ((avatarUiCandidate || avatarMouthCandidate) ? '0.6.2' : '0.6.1')) ndk { abiFilters 'arm64-v8a' } } compileOptions { sourceCompatibility JavaVersion.VERSION_17; targetCompatibility JavaVersion.VERSION_17 } @@ -103,6 +106,7 @@ android { else if (avatarUiCandidate) versionNameSuffix '-ui-dev' else if (avatarNatural) versionNameSuffix '-natural-dev' else if (avatarEngineering) versionNameSuffix '-dev' + buildConfigField 'boolean', 'AVATAR_STARTUP_FIX', avatarStartupFix ? 'true' : 'false' buildConfigField 'boolean', 'AVATAR_ENGINEERING', (avatarEngineering || avatarNatural) ? 'true' : 'false' buildConfigField 'boolean', 'AVATAR_NATURAL', avatarNatural ? 'true' : 'false' buildConfigField 'boolean', 'AVATAR_MOUTH_CANDIDATE', avatarMouthCandidate ? 'true' : 'false' @@ -110,6 +114,7 @@ android { buildConfigField 'String', 'EMOTION_MANIFEST_SHA', '"' + emotionManifestSha + '"' } release { + buildConfigField 'boolean', 'AVATAR_STARTUP_FIX', 'false' buildConfigField 'boolean', 'AVATAR_ENGINEERING', 'false' buildConfigField 'boolean', 'AVATAR_NATURAL', 'false' buildConfigField 'boolean', 'AVATAR_MOUTH_CANDIDATE', 'false' diff --git a/app/src/androidTest/java/com/gorios/lanvoice/AvatarCleanUiInstrumentation.kt b/app/src/androidTest/java/com/gorios/lanvoice/AvatarCleanUiInstrumentation.kt index 9b5a56c..7435214 100644 --- a/app/src/androidTest/java/com/gorios/lanvoice/AvatarCleanUiInstrumentation.kt +++ b/app/src/androidTest/java/com/gorios/lanvoice/AvatarCleanUiInstrumentation.kt @@ -9,6 +9,8 @@ import android.view.View import android.view.ViewGroup import android.view.accessibility.AccessibilityNodeInfo import com.gorios.lanvoice.avatar.ContinuousAvatarView +import com.gorios.lanvoice.avatar.EmotionActionAvatarView +import com.gorios.lanvoice.avatar.StartupAvatarView /** Optional on-device regression, only launches the explicit sensor-free preview. * Uses platform instrumentation/accessibility, no external test dependencies. @@ -25,11 +27,16 @@ class AvatarCleanUiInstrumentation : Instrumentation() { screen=activity; waitForIdleSync() fun field(instance: Any,name: String): Any? = instance.javaClass.getDeclaredField(name).apply { isAccessible=true }.get(instance) check(field(activity,"session")==null && field(activity,"expressions")==null) { "Offline probe created sensors/session" } - var avatar: ContinuousAvatarView?=null + var avatar: View?=null runOnMainSync { avatar=findAvatar(activity.window.decorView) } val view=checkNotNull(avatar) { "Continuous avatar missing" } - await { field(view,"renderer")!=null } - val renderer=checkNotNull(field(view,"renderer")) + fun currentRenderer(): Any? = when(view) { + is StartupAvatarView -> (field(view,"full") as? EmotionActionAvatarView)?.let { field(it,"driver") } + is EmotionActionAvatarView -> field(view,"driver") + else -> field(view,"renderer") + } + await { currentRenderer()!=null && (!BuildConfig.AVATAR_STARTUP_FIX || field(activity,"mediaReady")==true) } + val renderer=checkNotNull(currentRenderer()) await { gear()!=null } assertClean() val gear=checkNotNull(gear()); val bounds=android.graphics.Rect();gear.getBoundsInScreen(bounds) @@ -40,17 +47,17 @@ class AvatarCleanUiInstrumentation : Instrumentation() { await { nodes().any { it.text?.toString()=="关闭" } } check(nodes().any { it.text?.toString()?.contains("离线 avatar")==true }) val version=targetContext.packageManager.getPackageInfo(targetContext.packageName,0).versionName - val candidate=if(version=="0.6.2-mouth-dev") "嘴部工程候选" else "嘴层沿用 runtime03" + val candidate=if(BuildConfig.EMOTION_MANIFEST_SHA.isNotEmpty()) "整合候选" else if(version=="0.6.2-mouth-dev") "嘴部工程候选" else "嘴层沿用 runtime03" check(nodes().any { it.text?.toString()?.contains(candidate)==true }) check(nodes().first { it.text?.toString()=="关闭" }.performAction(AccessibilityNodeInfo.ACTION_CLICK)) await { nodes().none { it.text?.toString()=="关闭" } && gear()!=null } assertClean() runOnMainSync { check(findAvatar(activity.window.decorView)===view) } - check(field(view,"renderer")===renderer) { "Settings restarted body renderer" } + check(currentRenderer()===renderer) { "Settings restarted body renderer" } check(field(activity,"session")==null && field(activity,"expressions")==null) } runOnMainSync { activity.moveTaskToBack(true) } - await { field(view,"renderer")==null } + await { currentRenderer()==null } result.putString("result","PASS: clean accessibility home / 48dp gear / 3 settings cycles preserve renderer / offline no sensors / background releases renderer") success=true } catch(t: Throwable) { @@ -58,8 +65,8 @@ class AvatarCleanUiInstrumentation : Instrumentation() { } finally { screen?.let { runOnMainSync { it.finish() } } } finish(if(success) Activity.RESULT_OK else Activity.RESULT_CANCELED,result) } - private fun findAvatar(view: View): ContinuousAvatarView? { - if(view is ContinuousAvatarView) return view + private fun findAvatar(view: View): View? { + if(view is StartupAvatarView || view is EmotionActionAvatarView || view is ContinuousAvatarView) return view if(view is ViewGroup) for(i in 0 until view.childCount) findAvatar(view.getChildAt(i))?.let { return it } return null } @@ -79,7 +86,7 @@ class AvatarCleanUiInstrumentation : Instrumentation() { check(app.count { it.isClickable }==1 && gear()!=null) { "Home has controls besides gear" } } private fun await(condition: ()->Boolean) { - val deadline=SystemClock.uptimeMillis()+8_000 + val deadline=SystemClock.uptimeMillis()+90_000 while(!condition()) { check(SystemClock.uptimeMillis()(null) + private var startupBase by mutableStateOf(null) + private var startupStage by mutableStateOf(if(BuildConfig.AVATAR_STARTUP_FIX) "preparing" else "ready") + private var loaderCancel: (()->Unit)?=null + private var loaderGeneration=0L + private var firstDrawReady=false + private var mediaReady=false private val avatarMedia=com.gorios.lanvoice.avatar.AvatarMediaBinding() private var expressionState by mutableStateOf(ExpressionUiState()) private lateinit var expressions: ExpressionController @@ -75,8 +81,8 @@ class MainActivity : ComponentActivity() { entry.permissionResult(permission, granted) if (permission == EntryPermission.CAMERA && !granted) preferences().edit().putBoolean("cameraWanted", false).apply() if (!granted && !offlineAvatarPreview) { - if (permission == EntryPermission.MICROPHONE) session.permissionDenied() - else expressions.permissionDenied() + if (permission == EntryPermission.MICROPHONE) { if(::session.isInitialized) session.permissionDenied() } + else if(::expressions.isInitialized) expressions.permissionDenied() } scheduleEntry() } @@ -86,6 +92,7 @@ class MainActivity : ComponentActivity() { } private fun advanceEntry() { if (!::entry.isInitialized || isDestroyed) return + if(BuildConfig.AVATAR_STARTUP_FIX && (!firstDrawReady || !offlineAvatarPreview && !::session.isInitialized)) return // First consent is after the foreground Compose host has a stable layout, // independent of health/WS/HELLO. No request originates from recomposition. if(inForeground && (!window.decorView.isAttachedToWindow || !window.decorView.isLaidOut)) { @@ -136,7 +143,7 @@ class MainActivity : ComponentActivity() { else if(entry.requestPermission(EntryPermission.CAMERA,false)) scheduleEntry() } private fun retryConnection() { - if (entry.retry(android.os.SystemClock.elapsedRealtime())) { + if (::session.isInitialized && entry.retry(android.os.SystemClock.elapsedRealtime())) { session.resetConnection() scheduleEntry() } @@ -144,6 +151,7 @@ class MainActivity : ComponentActivity() { override fun onCreate(savedInstanceState: Bundle?) { super.onCreate(savedInstanceState) + if(BuildConfig.AVATAR_STARTUP_FIX) com.gorios.lanvoice.diag.StartupTrace.begin() enableEdgeToEdge( statusBarStyle = SystemBarStyle.light(android.graphics.Color.WHITE, android.graphics.Color.WHITE), navigationBarStyle = SystemBarStyle.light(android.graphics.Color.WHITE, android.graphics.Color.WHITE), @@ -151,22 +159,54 @@ class MainActivity : ComponentActivity() { appVersion = packageManager.getPackageInfo(packageName, 0).versionName ?: "unknown" volumeControlStream = AudioManager.STREAM_MUSIC offlineAvatarPreview = BuildConfig.DEBUG && BuildConfig.AVATAR_ENGINEERING && intent.getBooleanExtra(OfflineAvatarTrace.EXTRA,false) + if(!BuildConfig.AVATAR_STARTUP_FIX) avatarPack = AvatarPack.load(this) + entry=AutoConversation(preferences().getBoolean("micAsked",false),preferences().getBoolean("camAsked",false), + preferences().getBoolean("cameraWanted",true),conversationEnabled=!offlineAvatarPreview,automaticPermissions=!offlineAvatarPreview) if (offlineAvatarPreview) { - avatarPack = AvatarPack.load(this) entry=AutoConversation(preferences().getBoolean("micAsked",false),preferences().getBoolean("camAsked",false), conversationEnabled=false,automaticPermissions=false) setContent { EngineeringPreviewScreen(avatarPack,micGranted,cameraGranted,micSettings,cameraSettings, - permissionPending,::authorizeMicrophone,::authorizeCamera,avatarMedia,::sendDiagnosticReport,reportSending,reportResult) } + permissionPending,::authorizeMicrophone,::authorizeCamera,avatarMedia,::sendDiagnosticReport,reportSending,reportResult, + startupBase,startupStage,::startupVisible,::startAssetLoad,{startupStage="failed"}) } + if(BuildConfig.AVATAR_STARTUP_FIX) startShell() return // No VoiceSession/audio focus/camera controller; manual permission consent only. } + if(!BuildConfig.AVATAR_STARTUP_FIX) initializeNormal() + setContent { + CallScreen( + state, entryPhase, permissionMessage, micSettings, cameraSettings, avatarPack, ::retryConnection, ::authorizeMicrophone, + { val muted = !state.microphoneMuted + preferences().edit().putBoolean("microphoneMuted", muted).apply() + if(::session.isInitialized) session.setMicrophoneMuted(muted) }, ::toggleExpressions, + expressionState, shareFace, { enabled -> shareFace = enabled; if(::session.isInitialized) session.setFaceSharing(enabled) }, + connectionLogs, ::sendDiagnosticReport, reportSending, reportResult, { if(::session.isInitialized) session.interrupt() }, + micGranted,cameraGranted,permissionPending,::authorizeCamera, + onCancelAction = { if(::session.isInitialized) session.cancelAction() }, + mediaBinding = avatarMedia, + startupBase = startupBase,startupStage = startupStage,onStartupVisible = ::startupVisible,onRetryAssets = ::startAssetLoad,onStartupFailed = { startupStage="failed" }, + onOfflinePreview = { + if(!openingOffline && ::session.isInitialized) { + openingOffline=true;closeCamera() + session.suspendForLocalPreview { safe -> + openingOffline=false + if(safe && inForeground && !isDestroyed) startActivity(android.content.Intent(this,MainActivity::class.java).putExtra(OfflineAvatarTrace.EXTRA,true)) + else reportResult="录音停止未确认,暂不进入离线播放检查" + } + } + }, + ) + } + if(BuildConfig.AVATAR_STARTUP_FIX) startShell() + } + + private fun initializeNormal() { + if(::session.isInitialized || offlineAvatarPreview || isDestroyed) return audioOutput = AudioOutputGate(this) { session.outputUnavailable("播放被系统音频占用打断,请重新开始") } DebugLogUpload.appLaunch( appVersion, NetworkSecurityPolicy.getInstance().isCleartextTrafficPermitted("192.168.31.61"), ) // User approved the original crossed-arms reference. Motion approval is separate. - avatarPack = AvatarPack.load(this) - entry = AutoConversation(preferences().getBoolean("micAsked", false), preferences().getBoolean("camAsked", false), preferences().getBoolean("cameraWanted", true)) session = VoiceSession( getString(R.string.voice_server_host), resources.getInteger(R.integer.voice_server_port), onState = { @@ -183,7 +223,8 @@ class MainActivity : ComponentActivity() { onConnectionLog = { connectionLogs = (connectionLogs + it).takeLast(10) }, onPreparePlayback = audioOutput::prepare, onVoiceStopped = audioOutput::release, - reviewedActionPack = avatarPack?.emotionAction?.actionPack, + reviewedActionPack = avatarPack?.emotionAction?.actionPack?.takeIf { !BuildConfig.AVATAR_STARTUP_FIX || mediaReady }, + pendingActionPackSha = { if(BuildConfig.AVATAR_STARTUP_FIX) BuildConfig.EMOTION_MANIFEST_SHA else null }, actionPlayer = avatarMedia, onPrepareExpression = avatarMedia::prepare, ) @@ -192,29 +233,40 @@ class MainActivity : ComponentActivity() { if (expressionState.status != it.status) DebugLogUpload.log("audio", "camera state=${it.status.name.lowercase()}") expressionState = it }, onFaceCue = session::observeFace) - setContent { - CallScreen( - state, entryPhase, permissionMessage, micSettings, cameraSettings, avatarPack, ::retryConnection, ::authorizeMicrophone, - { val muted = !state.microphoneMuted - preferences().edit().putBoolean("microphoneMuted", muted).apply() - session.setMicrophoneMuted(muted) }, ::toggleExpressions, - expressionState, shareFace, { enabled -> shareFace = enabled; session.setFaceSharing(enabled) }, - connectionLogs, ::sendDiagnosticReport, reportSending, reportResult, session::interrupt, - micGranted,cameraGranted,permissionPending,::authorizeCamera, - onCancelAction = session::cancelAction, - mediaBinding = avatarMedia, - onOfflinePreview = { - if(!openingOffline) { - openingOffline=true;closeCamera() - session.suspendForLocalPreview { safe -> - openingOffline=false - if(safe && inForeground && !isDestroyed) startActivity(android.content.Intent(this,MainActivity::class.java).putExtra(OfflineAvatarTrace.EXTRA,true)) - else reportResult="录音停止未确认,暂不进入离线播放检查" - } - } - }, - ) + if(inForeground) session.foreground(connectAutomatically=false) + if(mediaReady) avatarPack?.emotionAction?.actionPack?.let(session::installReviewedActions) + scheduleEntry() + } + private fun startShell() { + com.gorios.lanvoice.diag.StartupTrace.mark(com.gorios.lanvoice.diag.StartupTrace.Phase.SHELL_SET_CONTENT) + val view=window.decorView + val listener=object: android.view.ViewTreeObserver.OnDrawListener { + override fun onDraw() { + if(firstDrawReady) return + firstDrawReady=true + com.gorios.lanvoice.diag.StartupTrace.mark(com.gorios.lanvoice.diag.StartupTrace.Phase.FIRST_DRAW) + view.post { + if(view.viewTreeObserver.isAlive) view.viewTreeObserver.removeOnDrawListener(this) + if(!isDestroyed && inForeground) { initializeNormal();scheduleEntry() } + } + } } + view.viewTreeObserver.addOnDrawListener(listener) + startAssetLoad() + } + private fun startAssetLoad() { + if(!BuildConfig.AVATAR_STARTUP_FIX || isDestroyed) return + loaderCancel?.invoke();val token=++loaderGeneration;startupStage="preparing";avatarPack=null + loaderCancel=com.gorios.lanvoice.avatar.StartupAvatarRepository.request(this, + { base->if(token==loaderGeneration && !isDestroyed) startupBase=base }, + { result->if(token==loaderGeneration && !isDestroyed) { + result.fold({ pack->avatarPack=pack },{ startupStage="failed" }) + } }) + } + private fun startupVisible() { + mediaReady=true;startupStage="ready" + if(!offlineAvatarPreview && ::session.isInitialized) + avatarPack?.emotionAction?.actionPack?.let(session::installReviewedActions) } private fun sendDiagnosticReport() { @@ -228,15 +280,15 @@ class MainActivity : ComponentActivity() { versionCode = packageManager.getPackageInfo(packageName, 0).versionCode, avatarMode = if(offlineAvatarPreview) "offline_preview" else "normal", avatarPin = BuildConfig.EMOTION_MANIFEST_SHA, - avatarAdmission = avatarPack?.emotionAdmission ?: "static_identity_rejected", + avatarAdmission = avatarPack?.emotionAdmission ?: if(BuildConfig.AVATAR_STARTUP_FIX) "startup_$startupStage" else "static_identity_rejected", avatarRuntime = avatarMedia.diagnosticState, - actionProtocolState = if(offlineAvatarPreview) "offline_no_session" else session.runtimeProtocolState, + actionProtocolState = if(offlineAvatarPreview) "offline_no_session" else if(::session.isInitialized) session.runtimeProtocolState else "startup_no_session", cameraGranted = checkSelfPermission(Manifest.permission.CAMERA) == PackageManager.PERMISSION_GRANTED, cameraStatus = expressionState.status, cameraPermissionPending = entry.permissionPending == EntryPermission.CAMERA, faceSharing = shareFace, - cameraAnalysis = if(offlineAvatarPreview) com.gorios.lanvoice.expression.CameraAnalysisSnapshot() else expressions.diagnosticsSnapshot(), - faceTransmission = if(offlineAvatarPreview) com.gorios.lanvoice.expression.FaceTransmissionSnapshot() else session.faceDiagnosticsSnapshot(), + cameraAnalysis = if(offlineAvatarPreview) com.gorios.lanvoice.expression.CameraAnalysisSnapshot() else if(::expressions.isInitialized) expressions.diagnosticsSnapshot() else com.gorios.lanvoice.expression.CameraAnalysisSnapshot(), + faceTransmission = if(offlineAvatarPreview) com.gorios.lanvoice.expression.FaceTransmissionSnapshot() else if(::session.isInitialized) session.faceDiagnosticsSnapshot() else com.gorios.lanvoice.expression.FaceTransmissionSnapshot(), rolePlaying = state.phase == VoicePhase.ANSWERING, role = state.replyEmotion.takeIf { it.turnId != null }, previousRole = state.previousReplyEmotion, @@ -270,6 +322,7 @@ class MainActivity : ComponentActivity() { else if (entry.requestPermission(EntryPermission.CAMERA, false)) { preferences().edit().putBoolean("cameraWanted", true).apply(); scheduleEntry() } } private fun closeCamera() { + if(!::expressions.isInitialized) return expressions.stop() shareFace = false session.setFaceSharing(false) @@ -279,7 +332,8 @@ class MainActivity : ComponentActivity() { inForeground = true entry.enter() // The pure coordinator owns bounded connection attempts. No automatic listen here. - if(!offlineAvatarPreview) session.foreground(connectAutomatically = false) + if(!offlineAvatarPreview && ::session.isInitialized) session.foreground(connectAutomatically = false) + if(BuildConfig.AVATAR_STARTUP_FIX && firstDrawReady && !offlineAvatarPreview) initializeNormal() scheduleEntry() } override fun onPause() { @@ -290,24 +344,25 @@ class MainActivity : ComponentActivity() { closeCamera() // Permission windows can pause/stop the Activity. No sensors survive this pause; // retain only the fenced connection continuation, bounded by VoiceSession's timeout. - session.background(keepConnectionForPermission = true) + if(::session.isInitialized) session.background(keepConnectionForPermission = true) super.onPause() } override fun onStop() { if (offlineAvatarPreview) { super.onStop(); return } val pending = entry.permissionPending != null DebugLogUpload.log("connect", "activity onStop permission=$pending changingConfig=$isChangingConfigurations") - if (!pending) session.background(showDisconnectReason = true) + if (!pending && ::session.isInitialized) session.background(showDisconnectReason = true) super.onStop() } override fun onDestroy() { main.removeCallbacks(pump); main.removeCallbacks(retryTimer) + loaderGeneration++;loaderCancel?.invoke();loaderCancel=null if (offlineAvatarPreview) { super.onDestroy(); return } DebugLogUpload.log("audio", "camera stop reason=release") - expressions.release() + if(::expressions.isInitialized) expressions.release() DebugLogUpload.log("connect", "activity onDestroy changingConfig=$isChangingConfigurations") - session.release() + if(::session.isInitialized) session.release() super.onDestroy() } } diff --git a/app/src/main/java/com/gorios/lanvoice/audio/VoiceSession.kt b/app/src/main/java/com/gorios/lanvoice/audio/VoiceSession.kt index ef5adcf..b99d1cf 100644 --- a/app/src/main/java/com/gorios/lanvoice/audio/VoiceSession.kt +++ b/app/src/main/java/com/gorios/lanvoice/audio/VoiceSession.kt @@ -51,6 +51,7 @@ class VoiceSession( private val actionPlayer: ActionPlayer = UnavailableActionPlayer, private val onPrepareExpression: (ReplyEmotion?) -> Unit = {}, private val emotionObserver: ReplyEmotionObserver = ReplyEmotionObserver {}, + private val pendingActionPackSha: ()->String? = { null }, ) { private val main = Handler(Looper.getMainLooper()) private var state = VoiceUiState() @@ -146,6 +147,7 @@ class VoiceSession( onStatus = {}, onStatusReason = ::onConnection, actionPackSha = { actions.capability?.manifestSha }, + pendingActionPackSha = pendingActionPackSha, onEvent = ::onEvent, onFrame = ::onFrame, onProtocolError = { Log.w(TAG, it) }, @@ -227,6 +229,11 @@ class VoiceSession( update(state.copy(voiceActive = true, phase = VoicePhase.LISTENING, guidance = null, microphoneMuted = microphoneMuted)) startCapture() } + fun installReviewedActions(pack: ReviewedActionPack) { + checkMainThread() + if(released || !actions.install(pack)) return + dialogue.capabilitiesReady() + } fun stopVoice(sendControls: Boolean = true,cancelReason: String = "stop_voice") { checkMainThread() diff --git a/app/src/main/java/com/gorios/lanvoice/avatar/ActionController.kt b/app/src/main/java/com/gorios/lanvoice/avatar/ActionController.kt index 432527b..ee7fb0a 100644 --- a/app/src/main/java/com/gorios/lanvoice/avatar/ActionController.kt +++ b/app/src/main/java/com/gorios/lanvoice/avatar/ActionController.kt @@ -22,7 +22,7 @@ interface ActionPlayer { /** Main-thread state machine. No pack is installed until an external exact-SHA review. * No microphone data is stored here, and no model URL can reach the player. */ class ActionController( - private val pack: ReviewedActionPack?, private val player: ActionPlayer, + private var pack: ReviewedActionPack?, private val player: ActionPlayer, private val clock: () -> Long, private val stopCapture: ((Boolean) -> Unit) -> Unit, private val status: (ActionStatus) -> Unit, private val changed: (Boolean) -> Unit = {}, private val choose: (Int) -> Int = { kotlin.random.Random.nextInt(it) }, @@ -36,6 +36,12 @@ class ActionController( private var mediaReleased=false private var cancellation: Pair?=null val active get() = plan != null || stopping + fun install(value: ReviewedActionPack): Boolean { + if(active || pack!=null && pack?.manifestSha!=value.manifestSha) return false + val old=pack;pack=value + if(capability==null) { pack=old;return false } + return true + } private var deadline = 0L private var started = 0L val capability: ReviewedActionPack? get() = pack?.takeIf { diff --git a/app/src/main/java/com/gorios/lanvoice/avatar/AvatarPack.kt b/app/src/main/java/com/gorios/lanvoice/avatar/AvatarPack.kt index 085e37e..071d90e 100644 --- a/app/src/main/java/com/gorios/lanvoice/avatar/AvatarPack.kt +++ b/app/src/main/java/com/gorios/lanvoice/avatar/AvatarPack.kt @@ -1,6 +1,8 @@ package com.gorios.lanvoice.avatar import com.gorios.lanvoice.diag.DiagnosticLog +import com.gorios.lanvoice.diag.StartupTrace +import android.os.SystemClock import android.content.Context import org.json.JSONArray import org.json.JSONObject @@ -18,7 +20,7 @@ data class AvatarPack(val idle: String = "", val talk: String = "", val fallback private const val MOTION_ROOT = "avatar/a01-neutral-graph-v1/" // Add an exact manifest hash only after coordinator preview/edge review. Empty now. private val APPROVED_MOTION_HASHES = emptySet() - fun load(context: Context): AvatarPack? { + fun load(context: Context,immutableReceipt: Boolean=false): AvatarPack? { val fallback = STATIC_ROOT + "frames/reference.png" try { check(sha(read(context,fallback,8_000_000)) == STATIC_IMAGE_SHA) } catch (_: Exception) { DiagnosticLog.record("avatar_loader","result=static_identity_rejected");return null } @@ -27,10 +29,15 @@ data class AvatarPack(val idle: String = "", val talk: String = "", val fallback var stage="index_read_or_hash" val admitted=try { val root="avatar/a01-expression-action-v1/" + val parsedAt=SystemClock.elapsedRealtime() 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 metadata=jsonMap(JSONObject(String(raw,Charsets.UTF_8))) + StartupTrace.mark(StartupTrace.Phase.INDEX_PARSE,parsedAt) + val verified=mutableMapOf() + val runtimesAt=SystemClock.elapsedRealtime() + val index=checkNotNull(EmotionActionManifest.read(metadata,sha(raw), BuildConfig.EMOTION_MANIFEST_SHA,root) { path,hash -> val runtimeRoot=root+path.substringBeforeLast('/')+"/" stage="runtime_read_or_hash" @@ -39,19 +46,29 @@ data class AvatarPack(val idle: String = "", val talk: String = "", val fallback stage="runtime_schema" val runtime=checkNotNull(ContinuousAvatarManifest.read(jsonMap(JSONObject(String(bytes,Charsets.UTF_8))),hash,hash,true,runtimeRoot)) stage="runtime_body_patch_hash_or_shape" - verifyRuntime(context,runtime);stage="index_schema_or_binding";runtime + if(!immutableReceipt) verifyRuntime(context,runtime,verified) + stage="index_schema_or_binding";runtime }) + StartupTrace.mark(StartupTrace.Phase.RUNTIMES_VERIFY,runtimesAt) var total=0L + val mediaAt=SystemClock.elapsedRealtime() stage="edge_media_hash" for(clip in index.edges.map { it.clip }) { - val data=read(context,root+clip.path,64_000_000);check(sha(data)==clip.sha256);total+=data.size + if(!immutableReceipt && root+clip.path !in verified) { + val data=read(context,root+clip.path,64_000_000);check(sha(data)==clip.sha256);total+=data.size + verified[root+clip.path]=clip.sha256 + } else if(!immutableReceipt) check(verified[root+clip.path]==clip.sha256) check(total<=512_000_000) } stage="action_media_hash" for(asset in index.actionPack?.assets.orEmpty()) { - val media=checkNotNull(asset.media);val data=read(context,media.root+media.path,128_000_000) - check(sha(data)==media.sha256);total+=data.size;check(total<=512_000_000) + val media=checkNotNull(asset.media) + if(!immutableReceipt) { + val data=read(context,media.root+media.path,128_000_000) + check(sha(data)==media.sha256);total+=data.size;check(total<=512_000_000) + } } + StartupTrace.mark(StartupTrace.Phase.MEDIA_VERIFY,mediaAt) static.copy(continuous=index.packages.getValue(index.fallbackId),emotionAction=index,motionStatus="externally_pinned_emotion_graph",emotionAdmission="accepted") } catch(_: Exception) { static=static.copy(emotionAdmission=stage) @@ -125,13 +142,15 @@ data class AvatarPack(val idle: String = "", val talk: String = "", val fallback safeGraph=graph,pathRoot=MOTION_ROOT,motionStatus="approved") } catch (_: Exception) { static.copy(motionStatus="pack_unavailable") } } - private fun verifyRuntime(context: Context,runtime: ContinuousAvatarPack) { + private fun verifyRuntime(context: Context,runtime: ContinuousAvatarPack,verified: MutableMap) { check(sha(read(context,runtime.root+runtime.body.path,64_000_000))==runtime.body.sha256) + verified[runtime.root+runtime.body.path]=runtime.body.sha256 runtime.textureImages.forEachIndexed { i,image -> val bytes=read(context,runtime.root+image.path,256_000);check(sha(bytes)==image.sha256) val options=android.graphics.BitmapFactory.Options().apply { inJustDecodeBounds=true } android.graphics.BitmapFactory.decodeByteArray(bytes,0,bytes.size,options) val patch=runtime.patches[i/5];check(options.outWidth==patch.width && options.outHeight==patch.height) + verified[runtime.root+image.path]=image.sha256 } } private fun read(context: Context,path: String,maximum: Int): ByteArray = context.assets.open(path).use { @@ -150,6 +169,13 @@ data class AvatarPack(val idle: String = "", val talk: String = "", val fallback is JSONArray -> (0 until value.length()).map { convert(value.get(it)) } else -> value } - private fun sha(bytes: ByteArray) = MessageDigest.getInstance("SHA-256").digest(bytes).joinToString("") { "%02x".format(it) } + private fun sha(bytes: ByteArray): String { + val digest=MessageDigest.getInstance("SHA-256").digest(bytes) + val hex="0123456789abcdef" + return String(CharArray(digest.size*2) { i -> + val value=digest[i/2].toInt() and 255 + hex[if(i%2==0) value ushr 4 else value and 15] + }) + } } } diff --git a/app/src/main/java/com/gorios/lanvoice/avatar/CallScreen.kt b/app/src/main/java/com/gorios/lanvoice/avatar/CallScreen.kt index 5c54299..0e7370a 100644 --- a/app/src/main/java/com/gorios/lanvoice/avatar/CallScreen.kt +++ b/app/src/main/java/com/gorios/lanvoice/avatar/CallScreen.kt @@ -40,10 +40,13 @@ private val NoUiAction: ()->Unit = {} * only changes chrome, never a lifecycle/voice/decoder key or renderer instance. */ @OptIn(ExperimentalMaterial3Api::class) @Composable -private fun CleanAvatarScaffold(avatar: @Composable ()->Unit,settings: @Composable ()->Unit) { +private fun CleanAvatarScaffold(avatar: @Composable ()->Unit,settings: @Composable ()->Unit, + startupStage: String="ready",connecting: Boolean=false) { var settingsOpen by rememberSaveable { mutableStateOf(false) } Box(Modifier.fillMaxSize().background(Color.White).testTag("avatar_home")) { avatar() + StartupStatus(startupStage,connecting,Modifier.align(Alignment.BottomStart) + .windowInsetsPadding(WindowInsets.safeDrawing).padding(start=16.dp,end=88.dp,bottom=16.dp)) IconButton(onClick={settingsOpen=true},modifier=Modifier.align(Alignment.BottomEnd) .windowInsetsPadding(WindowInsets.safeDrawing).padding(12.dp).size(48.dp) .background(Color.White.copy(alpha=.72f),CircleShape).testTag("avatar_settings") @@ -73,6 +76,15 @@ private fun CleanAvatarScaffold(avatar: @Composable ()->Unit,settings: @Composab } } +@Composable +private fun StartupStatus(stage: String,connecting: Boolean,modifier: Modifier) { + if(stage!="preparing" && !connecting) return + Column(modifier) { + if(stage=="preparing") Text("准备角色",fontSize=12.sp,color=Color(0xFF59675F)) + if(connecting) Text("正在连接",fontSize=12.sp,color=Color(0xFF59675F)) + } +} + @Composable fun CallScreen(state: VoiceUiState,entry: EntryPhase,permissionMessage: String?,micSettings: Boolean,cameraSettings: Boolean, pack: AvatarPack?,onRetry: ()->Unit,onAuthorizeMic: ()->Unit,onMute: ()->Unit,onCamera: ()->Unit, @@ -82,6 +94,8 @@ fun CallScreen(state: VoiceUiState,entry: EntryPhase,permissionMessage: String?, onCancelAction: ()->Unit, mediaBinding: AvatarMediaBinding?=null, onOfflinePreview: ()->Unit=NoUiAction, + startupBase: ContinuousAvatarPack?=null,startupStage: String="ready", + onStartupVisible: ()->Unit=NoUiAction,onRetryAssets: ()->Unit=NoUiAction,onStartupFailed: ()->Unit=NoUiAction, ) { val avatar=remember { AvatarController() }.select(state.voiceActive,state.replyEmotion,state.playbackActivity.takeUnless { state.actionActive }) val latestAvatar by rememberUpdatedState(avatar) @@ -95,7 +109,8 @@ fun CallScreen(state: VoiceUiState,entry: EntryPhase,permissionMessage: String?, } } CleanAvatarScaffold(avatar={ - AvatarPortrait(pack,avatar.desiredMode,state.replyEmotion.turnId,state.playbackActivity?.generation,Modifier.fillMaxSize(),mediaBinding) { video=it } + AvatarPortrait(pack,avatar.desiredMode,state.replyEmotion.turnId,state.playbackActivity?.generation,Modifier.fillMaxSize(),mediaBinding, + startupBase,onStartupVisible,onStartupFailed,startupStage) { video=it } },settings={ val status=when(entry) { EntryPhase.CONNECTING -> "正在连接" @@ -110,6 +125,10 @@ fun CallScreen(state: VoiceUiState,entry: EntryPhase,permissionMessage: String?, } } Text(status,style=MaterialTheme.typography.titleMedium) + if(startupStage=="failed") { + Text("角色准备未完成,基础角色仍可使用",fontSize=12.sp) + TextButton(onClick=onRetryAssets) { Text("重试准备角色") } + } Text("麦克风:${if(state.voiceActive && !state.microphoneMuted && !state.actionActive && state.phase==VoicePhase.LISTENING) "正在收音" else "未收音"} · 相机:${when(expression.status) { ExpressionStatus.ACTIVE -> "开启";ExpressionStatus.STARTING -> "启动中";ExpressionStatus.UNAVAILABLE -> "不可用";else -> "关闭" }}",fontSize=13.sp) if(state.actionActive) Button(onClick=onCancelAction) { Text("结束表演") } TextButton(onClick=onRetry) { Text("重试连接") } @@ -147,7 +166,7 @@ fun CallScreen(state: VoiceUiState,entry: EntryPhase,permissionMessage: String?, TextButton(onClick=onOfflinePreview) { Text("离线播放检查(停止当前会话)") } reportResult?.let { Text(it,fontSize=12.sp) } Text(logs.takeLast(10).joinToString("\n"),fontSize=11.sp) - }) + },startupStage=startupStage,connecting=BuildConfig.AVATAR_STARTUP_FIX && entry==EntryPhase.CONNECTING) } @Composable @@ -180,7 +199,9 @@ private fun AvatarDiagnostics(pack: AvatarPack?,video: VideoPresentation) { @Composable fun EngineeringPreviewScreen(pack: AvatarPack?,micGranted: Boolean,cameraGranted: Boolean,micSettings: Boolean,cameraSettings: Boolean, permissionPending: EntryPermission?,onAuthorizeMic: ()->Unit,onAuthorizeCamera: ()->Unit, - mediaBinding: AvatarMediaBinding?=null,onReport: ()->Unit=NoUiAction,reportSending: Boolean=false,reportResult: String?=null) { + mediaBinding: AvatarMediaBinding?=null,onReport: ()->Unit=NoUiAction,reportSending: Boolean=false,reportResult: String?=null, + startupBase: ContinuousAvatarPack?=null,startupStage: String="ready", + onStartupVisible: ()->Unit=NoUiAction,onRetryAssets: ()->Unit=NoUiAction,onStartupFailed: ()->Unit=NoUiAction) { val activity=LocalContext.current as ComponentActivity var resumed by remember { mutableStateOf(activity.lifecycle.currentState.isAtLeast(Lifecycle.State.RESUMED)) } var trace by remember { mutableStateOf(OfflineAvatarTrace.at(0)) } @@ -191,10 +212,10 @@ fun EngineeringPreviewScreen(pack: AvatarPack?,micGranted: Boolean,cameraGranted var danceActive by remember { mutableStateOf(false) } var danceStatus by remember { mutableStateOf("idle") } var nativeState by remember { mutableStateOf("renderer_unavailable") } - val dance=remember(pack,offlineBinding) { OfflineDancePreview(pack?.emotionAction?.actionPack,offlineBinding, + val dance=remember(pack,offlineBinding,startupStage) { OfflineDancePreview(pack?.emotionAction?.actionPack?.takeIf { !BuildConfig.AVATAR_STARTUP_FIX || startupStage=="ready" },offlineBinding, { android.os.SystemClock.elapsedRealtime() }) { active,status -> danceActive=active;danceStatus=status } } var emotionLabel by remember { mutableStateOf("") } - DisposableEffect(activity) { + DisposableEffect(activity,dance) { val observer=LifecycleEventObserver { _,event -> if(event==Lifecycle.Event.ON_RESUME) resumed=true if(event==Lifecycle.Event.ON_PAUSE) { resumed=false;dance.cancel("background") } @@ -203,7 +224,7 @@ fun EngineeringPreviewScreen(pack: AvatarPack?,micGranted: Boolean,cameraGranted onDispose { activity.lifecycle.removeObserver(observer);dance.cancel("disposed") } } LaunchedEffect(resumed) { while(resumed) { nativeState=offlineBinding.diagnosticState;delay(500) } } - LaunchedEffect(resumed,restart,override,danceActive) { + LaunchedEffect(resumed,restart,override,danceActive,pack) { if(resumed && !danceActive) { val start=android.os.SystemClock.elapsedRealtime() val emotionSequence=OfflineEmotionSequence(1000+restart) @@ -223,17 +244,19 @@ fun EngineeringPreviewScreen(pack: AvatarPack?,micGranted: Boolean,cameraGranted } } CleanAvatarScaffold(avatar={ - AvatarPortrait(pack,override ?: trace.mode,trace.turn+restart*100,trace.generation+restart*100,Modifier.fillMaxSize(),if(pack?.emotionAction!=null) offlineBinding else null) { video=it } + AvatarPortrait(pack,override ?: trace.mode,trace.turn+restart*100,trace.generation+restart*100,Modifier.fillMaxSize(), + if(BuildConfig.AVATAR_STARTUP_FIX || pack?.emotionAction!=null) offlineBinding else null,startupBase,onStartupVisible,onStartupFailed,startupStage) { video=it } },settings={ Text("离线 avatar · 无连接 / 不录音 / 不采集相机",fontSize=13.sp) Text("可手动申请权限;授权后仍不启动采集",fontSize=12.sp) + if(startupStage=="failed") TextButton(onClick=onRetryAssets) { Text("重试准备角色") } PermissionSettings(micGranted,cameraGranted,micSettings,cameraSettings,permissionPending,onAuthorizeMic,onAuthorizeCamera) Text("合成意图:${override?.name ?: if(pack?.emotionAction!=null) emotionLabel else trace.label}",fontSize=12.sp) if(pack?.emotionAction!=null) Text("整合候选 · 动态自然度、音乐听审及真机未测;表达可能等待 2–4 秒出口和约 1 秒过渡",fontSize=12.sp) Text("版本 ${BuildConfig.VERSION_NAME} · code ${BuildConfig.VERSION_CODE} · pin ${BuildConfig.EMOTION_MANIFEST_SHA.take(12)}",fontSize=12.sp) Text("离线媒体:$danceStatus · $nativeState",fontSize=11.sp) AvatarDiagnostics(pack,video) - if(pack?.emotionAction?.actionPack!=null) { + if(pack?.emotionAction?.actionPack!=null && (!BuildConfig.AVATAR_STARTUP_FIX || startupStage=="ready")) { Row { TextButton(onClick={offlineBinding.intent(null,false);dance.play("asset_01")},enabled=resumed && !danceActive) { Text("舞蹈 01") } TextButton(onClick={offlineBinding.intent(null,false);dance.play("asset_02")},enabled=resumed && !danceActive) { Text("舞蹈 02") } @@ -248,16 +271,37 @@ fun EngineeringPreviewScreen(pack: AvatarPack?,micGranted: Boolean,cameraGranted TextButton(onClick={dance.cancel();override=AvatarMode.IDLE;restart++}) { Text("Abort") } TextButton(onClick={override=null;restart++}) { Text("Trace") } } - }) + },startupStage=startupStage) } @Composable private fun AvatarPortrait(pack: AvatarPack?, mode: AvatarMode, turn: Long?, audioEpoch: Long?, modifier: Modifier, - mediaBinding: AvatarMediaBinding?=null,onPresentation: (VideoPresentation) -> Unit) { + mediaBinding: AvatarMediaBinding?=null,startupBase: ContinuousAvatarPack?=null, + onStartupVisible: ()->Unit=NoUiAction,onStartupFailed: ()->Unit=NoUiAction,startupStage: String="ready",onPresentation: (VideoPresentation) -> Unit) { + if(BuildConfig.AVATAR_STARTUP_FIX && mediaBinding!=null) { + val activity=LocalContext.current as ComponentActivity + val latest by rememberUpdatedState(onPresentation) + val ready by rememberUpdatedState(onStartupVisible) + val failed by rememberUpdatedState(onStartupFailed) + val stage by rememberUpdatedState(startupStage) + val base by rememberUpdatedState(startupBase) + val admitted by rememberUpdatedState(pack) + val view=remember(mediaBinding) { StartupAvatarView(activity,mediaBinding,{ latest(it) },{ ready() },{failed()}) } + SideEffect { view.update(base,admitted,activity.lifecycle.currentState.isAtLeast(Lifecycle.State.RESUMED),stage) } + DisposableEffect(view) { + val observer=LifecycleEventObserver { _,event-> + if(event==Lifecycle.Event.ON_PAUSE) view.update(base,admitted,false,stage) + if(event==Lifecycle.Event.ON_RESUME) view.update(base,admitted,true,stage) + } + activity.lifecycle.addObserver(observer) + onDispose { activity.lifecycle.removeObserver(observer);view.dispose() } + } + AndroidView(factory={view},modifier=modifier);return + } if(pack?.emotionAction!=null && mediaBinding!=null) { val activity=LocalContext.current as ComponentActivity val latest by rememberUpdatedState(onPresentation) - val view=remember(pack,mediaBinding) { EmotionActionAvatarView(activity,pack,mediaBinding) { latest(it) } } + val view=remember(pack,mediaBinding) { EmotionActionAvatarView(activity,pack,mediaBinding,{ latest(it) }) } SideEffect { view.render(activity.lifecycle.currentState.isAtLeast(Lifecycle.State.RESUMED)) } DisposableEffect(view) { val observer=LifecycleEventObserver { _,event-> diff --git a/app/src/main/java/com/gorios/lanvoice/avatar/ConversationMediaDriver.kt b/app/src/main/java/com/gorios/lanvoice/avatar/ConversationMediaDriver.kt index 05f9017..b65ceda 100644 --- a/app/src/main/java/com/gorios/lanvoice/avatar/ConversationMediaDriver.kt +++ b/app/src/main/java/com/gorios/lanvoice/avatar/ConversationMediaDriver.kt @@ -27,7 +27,15 @@ class ConversationMediaDriver(private val index: EmotionActionIndex, private val reveal: (Int?)->Unit,private val report: (String,BodyFrameKey?)->Unit = { _,_-> }, private val allowSilentEdges: Boolean=false, private val chooseIdle: (Int)->Int = { kotlin.random.Random.nextInt(it) }, - private val chooseIdleCycles: ()->Int = { kotlin.random.Random.nextInt(2,4) }) : ActionPlayer { + private val chooseIdleCycles: ()->Int = { kotlin.random.Random.nextInt(2,4) }, + private val holdInitial: Boolean=false) : ActionPlayer { + private var initialHeld=holdInitial + fun releaseInitial() { + if(!active || !initialHeld) return + initialHeld=false + plan() + visible?.takeIf { !holdExit(it) }?.port?.advance() + } private data class Slot(val number: Int,val port: CompositeMediaPort,val pack: ContinuousAvatarPack, val entry: Int,val packageId: String?,var key: BodyFrameKey?=null,var live: Boolean=true,var closedMouth: Boolean=false) private val slots=mutableListOf() @@ -89,7 +97,7 @@ class ConversationMediaDriver(private val index: EmotionActionIndex, } fun start() { if(active || closing!=0) return - active=true;layerOwner=LayerOwner.CONVERSATION;generation++;revision=0;resetIdleCycles() + active=true;initialHeld=holdInitial;layerOwner=LayerOwner.CONVERSATION;generation++;revision=0;resetIdleCycles() val slot=prepare(index.fallbackId,0);visible=slot // Ports must deliver callbacks asynchronously, like both Android ports. } @@ -141,8 +149,8 @@ class ConversationMediaDriver(private val index: EmotionActionIndex, } if(slot===visible) { reveal(slot.number);report(if(inBridge) "bridge" else "body_${slot.packageId}",key) - if(!inBridge) { chooseIdleAtLoopEnd(slot,key,previous);applyMouth();plan() } - if(slot===visible && !actionStarted && !holdExit(slot)) slot.port.advance() + if(!inBridge && !initialHeld) { chooseIdleAtLoopEnd(slot,key,previous);applyMouth();plan() } + if(slot===visible && !initialHeld && !actionStarted && !holdExit(slot)) slot.port.advance() } else if(returning) restoreAction(slot) else plan() } },{ @@ -182,7 +190,7 @@ class ConversationMediaDriver(private val index: EmotionActionIndex, private fun plan() { val source=visible ?: return val key=source.key ?: return - if(inBridge || revealing!=null || !active || returning || actionStarted) return + if(initialHeld || inBridge || revealing!=null || !active || returning || actionStarted) return val wanted=if(action!=null) checkNotNull(action?.media).sourcePackage else idleTarget ?: selectedId var reviewedLoop: ConversationEdge?=null if(source.packageId==wanted) { diff --git a/app/src/main/java/com/gorios/lanvoice/avatar/EmotionActionAvatarView.kt b/app/src/main/java/com/gorios/lanvoice/avatar/EmotionActionAvatarView.kt index 073161e..b95a1cb 100644 --- a/app/src/main/java/com/gorios/lanvoice/avatar/EmotionActionAvatarView.kt +++ b/app/src/main/java/com/gorios/lanvoice/avatar/EmotionActionAvatarView.kt @@ -15,7 +15,9 @@ import android.widget.ImageView /** All views remain in one stable settings-independent composition slot. */ class EmotionActionAvatarView(context: Context,private val pack: AvatarPack, - private val binding: AvatarMediaBinding,private val report: (VideoPresentation)->Unit): FrameLayout(context) { + private val binding: AvatarMediaBinding,private val report: (VideoPresentation)->Unit, + private val startupHold: Boolean=false): FrameLayout(context) { + fun releaseStartup() { driver?.releaseInitial() } private val main=Handler(Looper.getMainLooper()) private val textures=List(4) { TextureView(context).apply { isOpaque=false;alpha=0f } } private val still=ImageView(context).apply { scaleType=ImageView.ScaleType.FIT_CENTER } @@ -34,7 +36,7 @@ class EmotionActionAvatarView(context: Context,private val pack: AvatarPack, private val renderers=arrayOfNulls(3) init { addView(still,LayoutParams(-1,-1)) - try { still.setImageBitmap(context.assets.open(pack.fallback).use(BitmapFactory::decodeStream)) } catch(_: Exception) { } + if(!startupHold) try { still.setImageBitmap(context.assets.open(pack.fallback).use(BitmapFactory::decodeStream)) } catch(_: Exception) { } textures.forEachIndexed { i,view -> addView(view,LayoutParams(-1,-1)) view.surfaceTextureListener=object: TextureView.SurfaceTextureListener { @@ -86,19 +88,19 @@ class EmotionActionAvatarView(context: Context,private val pack: AvatarPack, 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}" } ?: "")) }) + clipId=key?.let { "f${it.index}_loop${it.loopOrdinal}" } ?: "")) },holdInitial=startupHold) driver=current;main.removeCallbacks(summary);main.postDelayed(summary,10_000);current.start();binding.attach(current) { if(active && !released) { current.start();binding.attach(current) } };fitMovie() } private fun fitMovie() { val view=textures[3];if(view.width<=0 || view.height<=0) return movie?.resize(view.width,view.height) } - private fun suspend() { + private fun suspend(done: ()->Unit={}) { main.removeCallbacks(summary) - val old=driver ?: return - old.stop { binding.detach(old);if(driver===old) { driver=null;movie=null };if(active) start() } + val old=driver ?: run { done();return } + old.stop { binding.detach(old);if(driver===old) { driver=null;movie=null };if(active) start();done() } } - fun dispose() { active=false;released=true;suspend() } + fun dispose(done: ()->Unit={}) { active=false;released=true;suspend(done) } override fun onDetachedFromWindow() { dispose();super.onDetachedFromWindow() } } diff --git a/app/src/main/java/com/gorios/lanvoice/avatar/StartupAvatarRepository.kt b/app/src/main/java/com/gorios/lanvoice/avatar/StartupAvatarRepository.kt new file mode 100644 index 0000000..0898568 --- /dev/null +++ b/app/src/main/java/com/gorios/lanvoice/avatar/StartupAvatarRepository.kt @@ -0,0 +1,74 @@ +package com.gorios.lanvoice.avatar + +import android.content.Context +import android.os.Handler +import android.os.Looper +import android.os.SystemClock +import com.gorios.lanvoice.BuildConfig +import com.gorios.lanvoice.diag.StartupTrace +import org.json.JSONObject +import java.io.File +import java.io.InputStream +import java.security.MessageDigest +import java.util.concurrent.Executors + +/** Immutable APK cache; no Activity, Surface, GL texture or camera retained. */ +object StartupAvatarRepository { + const val BASIC_SHA="461f5cfc10036de5f10ca3ce765fb8d9998697d3fd035aa9b1862d2ccfc3eaa2" + private const val ROOT="avatar/startup-white-01/" + private val worker=Executors.newSingleThreadExecutor { Thread(it,"avatar-validation").apply { isDaemon=true } } + private val main=Handler(Looper.getMainLooper()) + private val full=StartupLoadCache(worker) + private val basic=StartupLoadCache(worker) + private fun sha(bytes: ByteArray)=MessageDigest.getInstance("SHA-256").digest(bytes) + .joinToString("") { "%02x".format(it) } + private fun readBounded(stream: InputStream,limit: Int): ByteArray = stream.use { + val out=java.io.ByteArrayOutputStream();val buffer=ByteArray(8192) + while(true) { val n=it.read(buffer);if(n<0) break;check(out.size()+n<=limit);out.write(buffer,0,n) };out.toByteArray() + } + fun request(context: Context,onBasic: (ContinuousAvatarPack)->Unit,onFull: (Result)->Unit): ()->Unit { + val app=context.applicationContext + val info=app.packageManager.getPackageInfo(app.packageName,0) + val key=StartupAssetKey(info.versionCode.toLong(),info.lastUpdateTime,BuildConfig.EMOTION_MANIFEST_SHA, + "avatar/a01-expression-action-v1/",1) + var cancelled=false + var basicFailed=false + // Both requests use one serial IO worker: the tiny baseline is prioritized. + val cancelBasic=basic.request(key,{ + check(Looper.myLooper()!=Looper.getMainLooper()) + val start=SystemClock.elapsedRealtime() + val raw=readBounded(app.assets.open(ROOT+"manifest.json"),8192);check(raw.size<=8192 && sha(raw)==BASIC_SHA) + val json=JSONObject(String(raw,Charsets.UTF_8)) + check(json.getString("sourceIndexSha256")==BuildConfig.EMOTION_MANIFEST_SHA) + val b=json.getJSONObject("body") + val path=b.getString("path");check(path=="avatar/a01-expression-action-v1/runtime/neutral/body/idle.mp4") + val bytes=readBounded(app.assets.open(path),64_000_000);check(bytes.size<=64_000_000 && sha(bytes)==b.getString("sha256")) + val poster=readBounded(app.assets.open(ROOT+"poster.png"),100_000);check(poster.size<=100_000 && sha(poster)==json.getString("posterSha256")) + val pts=b.getJSONArray("ptsUs");val timeline=List(pts.length()) { pts.getLong(it) } + check(b.getInt("width")==480 && b.getInt("height")==848 && + BodyTimeline.valid(timeline,b.getInt("frameCount"),b.getLong("durationUs"),b.getInt("fpsNumerator"),b.getInt("fpsDenominator"))) + val body=ContinuousBodyAsset(path,b.getString("sha256"),480,848,timeline.size,b.getLong("durationUs"), + timeline,b.getInt("fpsNumerator"),b.getInt("fpsDenominator")) + StartupTrace.mark(StartupTrace.Phase.BASIC_VERIFY,start) + ContinuousAvatarPack(body,emptyList(),emptyMap(),"",BASIC_SHA) + },{ result->main.post { if(!cancelled) result.fold(onBasic,{ basicFailed=true;StartupTrace.mark(StartupTrace.Phase.FULL_FAILED);onFull(Result.failure(it)) }) } }) + val cancelFull=full.request(key,{ + check(Looper.myLooper()!=Looper.getMainLooper()) + StartupTrace.mark(StartupTrace.Phase.CACHE_MISS) + val receipt=BundledValidationReceipt(File(app.filesDir,"bundled-avatar-validation")) + val trusted=receipt.contains(key) + StartupTrace.mark(if(trusted) StartupTrace.Phase.RECEIPT_HIT else StartupTrace.Phase.RECEIPT_MISS) + val pack=checkNotNull(AvatarPack.load(app,trusted)) + check(pack.emotionAdmission=="accepted" && pack.emotionAction?.actionPack?.manifestSha==key.pin) + if(!trusted) { + // A failed receipt write cannot invalidate a fully verified current pack. + try { receipt.complete(key);StartupTrace.mark(StartupTrace.Phase.RECEIPT_WRITE) } catch(_: Exception) { } + } + pack + },{ result->main.post { if(!cancelled) { + StartupTrace.mark(if(result.isSuccess) StartupTrace.Phase.FULL_READY else StartupTrace.Phase.FULL_FAILED) + if(!basicFailed) onFull(result) + } } },onHit={ StartupTrace.mark(StartupTrace.Phase.CACHE_HIT) }) + return { cancelled=true;cancelBasic();cancelFull() } + } +} diff --git a/app/src/main/java/com/gorios/lanvoice/avatar/StartupAvatarView.kt b/app/src/main/java/com/gorios/lanvoice/avatar/StartupAvatarView.kt new file mode 100644 index 0000000..2a4e842 --- /dev/null +++ b/app/src/main/java/com/gorios/lanvoice/avatar/StartupAvatarView.kt @@ -0,0 +1,115 @@ +package com.gorios.lanvoice.avatar + +import android.content.Context +import android.graphics.SurfaceTexture +import android.view.Surface +import android.view.TextureView +import android.widget.FrameLayout +import android.widget.ImageView +import com.gorios.lanvoice.R +import com.gorios.lanvoice.diag.StartupTrace + +/** One stable host. Only real matching neutral sourceframe0 can hand off the base loop. + * Full renderer is prepared/held hidden; no TextureView output-clock inference. */ +class StartupAvatarView(context: Context,private val binding: AvatarMediaBinding, + private val report: (VideoPresentation)->Unit,private val fullVisible: ()->Unit,private val failed: ()->Unit={}): FrameLayout(context) { + private val poster=ImageView(context).apply { + scaleType=ImageView.ScaleType.FIT_CENTER + setImageResource(R.drawable.startup_poster) + } + private val surface=TextureView(context).apply { isOpaque=false;alpha=0f } + private var basic: ContinuousAvatarPack?=null + private var fullPack: AvatarPack?=null + private var renderer: ContinuousBodyRenderer?=null + private var full: EmotionActionAvatarView?=null + private var key: BodyFrameKey?=null + private var fullReady=false + private var switched=false + private var active=false + private var disposed=false + private var epoch=0L + private var basicEpoch=0L + private var baseReleased=false + private var notified=false + private var firstIdle=false + private var startupFailed=false + private var lastStage="preparing" + private var retiring=false + init { + addView(poster,LayoutParams(-1,-1));addView(surface,LayoutParams(-1,-1)) + StartupTrace.mark(StartupTrace.Phase.POSTER_READY) + surface.surfaceTextureListener=object: TextureView.SurfaceTextureListener { + override fun onSurfaceTextureAvailable(s: SurfaceTexture,w: Int,h: Int) { startBasic() } + override fun onSurfaceTextureSizeChanged(s: SurfaceTexture,w: Int,h: Int) { renderer?.resize(w,h) } + override fun onSurfaceTextureUpdated(s: SurfaceTexture) { } + override fun onSurfaceTextureDestroyed(s: SurfaceTexture): Boolean { closeBasic();return true } + } + } + fun update(base: ContinuousAvatarPack?,pack: AvatarPack?,foreground: Boolean,stage: String="ready") { + active=foreground + if(disposed) return + if(base!=null) basic=base + fullPack=pack + val previousStage=lastStage;lastStage=stage + if(startupFailed && (pack==null || stage=="preparing" && previousStage=="failed")) { + startupFailed=false;val token=++epoch;val old=full;full=null;fullReady=false + retiring=old!=null + old?.dispose { + removeView(old) + if(!disposed && token==epoch) { retiring=false;update(basic,fullPack,active,lastStage) } + } + } + if(!retiring && !startupFailed && pack?.emotionAction!=null && full==null && basic!=null) { + check(pack.emotionAction.packages.getValue(pack.emotionAction.fallbackId).body.sha256==basic!!.body.sha256) + fullPack=pack + val token=epoch + full=EmotionActionAvatarView(context,pack,binding,{ value -> + if(!disposed && token==epoch && active) { + report(value) + if(!switched && !startupFailed && (value.actual=="media_failed" || value.reason !in setOf("reviewed_media_path",""))) { + startupFailed=true;fullReady=false;StartupTrace.mark(StartupTrace.Phase.FULL_FAILED);failed() + } + if(!startupFailed && !fullReady && value.actual=="body_"+pack.emotionAction.fallbackId && value.clipId=="f0_loop0") { + fullReady=true;StartupTrace.mark(StartupTrace.Phase.FULL_FIRST_GL);handoff() + } + if(switched && value.clipId=="f0_loop0") finishHandoff() + } + },startupHold=true).also { it.alpha=0f;addView(it,LayoutParams(-1,-1)) } + } + if(active) { startBasic();full?.render(!startupFailed);if(switched) finishHandoff() } + else { if(!switched) fullReady=false;closeBasic();full?.render(false) } + } + private fun startBasic() { + val pack=basic ?: return + if(!active || disposed || switched || renderer!=null || !surface.isAvailable) return + val token=basicEpoch + renderer=ContinuousBodyRenderer(context,pack,Surface(checkNotNull(surface.surfaceTexture)),surface.width,surface.height, + { frame,_ -> if(token==basicEpoch && active && !disposed && !switched) { + key=frame.key;surface.alpha=1f;poster.alpha=0f + if(!firstIdle) { firstIdle=true;StartupTrace.mark(StartupTrace.Phase.FIRST_IDLE_FRAME) } + if(frame.key.index==0 && fullReady) handoff() else renderer?.advance() + } },{ _ -> if(token==basicEpoch && !switched) { closeBasic();surface.alpha=0f;poster.alpha=1f } }, + automatic=false,mouthEnabled=false) + } + private fun handoff() { + if(startupFailed || !active || disposed || switched || !fullReady || key?.index!=0) return + switched=true + // Both source and target are actual composed frame0 of the exact same body. + full?.alpha=1f;surface.alpha=0f;poster.alpha=0f + StartupTrace.mark(StartupTrace.Phase.HANDOFF) + // The bootstrap decoder must actually release before action capability opens. + val old=renderer;renderer=null + old?.close { if(!disposed) { baseReleased=true;finishHandoff() } } + } + private fun finishHandoff() { + if(!active || disposed || !switched || !baseReleased) return + full?.releaseStartup() + if(!notified) { notified=true;fullVisible() } + } + private fun closeBasic() { basicEpoch++;val old=renderer;renderer=null;key=null;old?.close() } + fun dispose() { + if(disposed) return + disposed=true;active=false;epoch++;closeBasic();full?.dispose();full=null + } + override fun onDetachedFromWindow() { dispose();super.onDetachedFromWindow() } +} diff --git a/app/src/main/java/com/gorios/lanvoice/avatar/StartupLoadCache.kt b/app/src/main/java/com/gorios/lanvoice/avatar/StartupLoadCache.kt new file mode 100644 index 0000000..e6de73b --- /dev/null +++ b/app/src/main/java/com/gorios/lanvoice/avatar/StartupLoadCache.kt @@ -0,0 +1,79 @@ +package com.gorios.lanvoice.avatar + +import java.io.File +import java.nio.file.Files +import java.nio.file.StandardCopyOption +import java.security.MessageDigest +import java.util.concurrent.Executor + +/** Only immutable packaged assets. This receipt NEVER applies to downloaded/runtime files. + * Reconstruct objects through strict parsers on every process; receipt only avoids repeated + * media/PNG byte verification previously completed for this exact installed APK. */ +data class StartupAssetKey(val versionCode: Long,val installedAt: Long,val pin: String, + val root: String,val validator: Int) { + init { require(versionCode>0 && installedAt>0 && pin.matches(Regex("[0-9a-f]{64}")) && + root=="avatar/a01-expression-action-v1/" && validator>0) } + val fingerprint: String get() = digest("$versionCode/$installedAt/$pin/$root/$validator") +} +private fun digest(value: String): String = MessageDigest.getInstance("SHA-256").digest(value.toByteArray()) + .joinToString("") { "%02x".format(it) } + +class BundledValidationReceipt(private val directory: File) { + fun contains(key: StartupAssetKey): Boolean = try { + val file=File(directory,key.fingerprint+".complete") + if(!file.isFile || file.length()>512) false else { + val text="bundled-complete-v1\n"+key.fingerprint+"\n" + file.readText()==text+digest(text)+"\n" + } + } catch(_: Exception) { false } + fun complete(key: StartupAssetKey) { + check(directory.isDirectory || directory.mkdirs()) + val text="bundled-complete-v1\n"+key.fingerprint+"\n" + val temp=File.createTempFile("validation-",".tmp",directory) + try { + java.io.FileOutputStream(temp).use { it.write((text+digest(text)+"\n").toByteArray());it.flush();it.fd.sync() } + Files.move(temp.toPath(),File(directory,key.fingerprint+".complete").toPath(), + StandardCopyOption.ATOMIC_MOVE,StandardCopyOption.REPLACE_EXISTING) + // Keep a bounded history; no old key can satisfy a new install/pin/validator. + directory.listFiles()?.filter { it.name.endsWith(".complete") && it.name!=key.fingerprint+".complete" } + ?.forEach { it.delete() } + } finally { temp.delete() } + } +} + +/** Shared one-key future. Cancellation removes the Activity listener, not a useful shared + * immutable validation. Failure is not a cached success; retry can start fresh work. */ +class StartupLoadCache(private val worker: Executor) { + private class Flight(val key: StartupAssetKey) { + val listeners=linkedMapOf)->Unit>() + var result: T?=null + } + private val lock=Any() + private var serial=0L + private val flights=linkedMapOf>() + fun request(key: StartupAssetKey,load: ()->T,callback: (Result)->Unit,onHit: ()->Unit={}): ()->Unit { + val id: Long + val current: Flight + var start=false + var cached: T?=null + synchronized(lock) { + id=++serial + current=flights[key] ?: Flight(key).also { flights[key]=it;start=true } + cached=current.result + if(cached==null) current.listeners[id]=callback + } + if(!start) onHit() + cached?.let { callback(Result.success(it)) } + if(start) worker.execute { + val result=runCatching(load) + val callbacks=synchronized(lock) { + if(result.isSuccess) current.result=result.getOrNull() + else if(flights[key]===current) flights.remove(key) + flights.entries.filter { it.key!=key && it.value.result!=null }.dropLast(1).forEach { flights.remove(it.key) } + current.listeners.values.toList().also { current.listeners.clear() } + } + callbacks.forEach { callback->runCatching { callback(result) } } + } + return { synchronized(lock) { current.listeners.remove(id) };Unit } + } +} diff --git a/app/src/main/java/com/gorios/lanvoice/diag/StartupTrace.kt b/app/src/main/java/com/gorios/lanvoice/diag/StartupTrace.kt new file mode 100644 index 0000000..2584d17 --- /dev/null +++ b/app/src/main/java/com/gorios/lanvoice/diag/StartupTrace.kt @@ -0,0 +1,26 @@ +package com.gorios.lanvoice.diag + +import android.os.SystemClock +import android.util.Log +import java.util.concurrent.atomic.AtomicLong + +/** Fixed stages and monotonic numbers only. No exceptions, paths, payloads or frames per tick. */ +object StartupTrace { + enum class Phase { + ON_CREATE, SHELL_SET_CONTENT, FIRST_DRAW, POSTER_READY, BASIC_VERIFY, FIRST_IDLE_FRAME, + INDEX_PARSE, RUNTIMES_VERIFY, MEDIA_VERIFY, CACHE_MISS, CACHE_HIT, RECEIPT_HIT, + RECEIPT_MISS, RECEIPT_INVALID, RECEIPT_WRITE, FULL_READY, FULL_FAILED, FULL_FIRST_GL, + HANDOFF, HEALTH_START, HEALTH_HTTP, WS_OPEN, AUTH, HELLO, CAP_READY, + CAMERA_MODEL, CAMERA_BIND, CAMERA_READY + } + private val sequence=AtomicLong() + @Volatile private var origin=SystemClock.elapsedRealtime() + fun begin() { sequence.incrementAndGet();origin=SystemClock.elapsedRealtime();mark(Phase.ON_CREATE) } + fun mark(phase: Phase,started: Long?=null) { + val now=SystemClock.elapsedRealtime() + val line="run="+sequence.get()+" phase="+phase.name.lowercase()+" mono_ms="+now+ + " elapsed_ms="+(now-origin).coerceAtLeast(0)+" duration_ms="+(started?.let { (now-it).coerceAtLeast(0) } ?: -1) + DiagnosticLog.record("startup",line) + Log.i("LanVoiceStartup",line) + } +} diff --git a/app/src/main/java/com/gorios/lanvoice/expression/ExpressionController.kt b/app/src/main/java/com/gorios/lanvoice/expression/ExpressionController.kt index a33861a..cc1e2fc 100644 --- a/app/src/main/java/com/gorios/lanvoice/expression/ExpressionController.kt +++ b/app/src/main/java/com/gorios/lanvoice/expression/ExpressionController.kt @@ -41,6 +41,7 @@ class ExpressionController( var landmarker: FaceLandmarker? = null // Accessed only on this run's executor. var analysis: ImageAnalysis? = null // Accessed only on main. var provider: ProcessCameraProvider? = null // Accessed only on main. + var firstReady=false var lastSampleMs = Long.MIN_VALUE var lastPublished: List? = null var lastStableCue = FaceCue.UNKNOWN @@ -90,7 +91,9 @@ class ExpressionController( .setOutputFaceBlendshapes(true) .setOutputFacialTransformationMatrixes(true) .build() + val modelStart=android.os.SystemClock.elapsedRealtime() run.landmarker = FaceLandmarker.createFromOptions(appContext, options) + com.gorios.lanvoice.diag.StartupTrace.mark(com.gorios.lanvoice.diag.StartupTrace.Phase.CAMERA_MODEL,modelStart) main.post { if (isCurrent(run)) bind(run) } } catch (_: Exception) { fail(run, "表情分析暂不可用,请检查模型和设备支持;语音功能不受影响。", "model_load") @@ -147,7 +150,9 @@ class ExpressionController( run.analysis = analysis analysis.setAnalyzer(run.executor) { image -> analyze(run, image) } // ImageAnalysis only: no Preview, capture, video recording or image persistence. + val bindStart=android.os.SystemClock.elapsedRealtime() provider.bindToLifecycle(lifecycleOwner, CameraSelector.DEFAULT_FRONT_CAMERA, analysis) + com.gorios.lanvoice.diag.StartupTrace.mark(com.gorios.lanvoice.diag.StartupTrace.Phase.CAMERA_BIND,bindStart) onState(ExpressionUiState(ExpressionStatus.ACTIVE)) } catch (_: Exception) { fail(run, "摄像头暂不可用,请稍后重试;语音功能不受影响。", "camera_bind") @@ -163,6 +168,7 @@ class ExpressionController( try { if (!run.active) return run.diagnostics.received() + if(!run.firstReady) { run.firstReady=true;com.gorios.lanvoice.diag.StartupTrace.mark(com.gorios.lanvoice.diag.StartupTrace.Phase.CAMERA_READY) } val now = SystemClock.elapsedRealtime() if (run.lastSampleMs != Long.MIN_VALUE && now - run.lastSampleMs < SAMPLE_INTERVAL_MS) return run.lastSampleMs = now diff --git a/app/src/main/java/com/gorios/lanvoice/net/DialogueClient.kt b/app/src/main/java/com/gorios/lanvoice/net/DialogueClient.kt index d5c3aa6..92112ed 100644 --- a/app/src/main/java/com/gorios/lanvoice/net/DialogueClient.kt +++ b/app/src/main/java/com/gorios/lanvoice/net/DialogueClient.kt @@ -3,6 +3,7 @@ package com.gorios.lanvoice.net import android.os.Handler import android.os.Looper import android.util.Log +import com.gorios.lanvoice.diag.StartupTrace import okhttp3.Call import okhttp3.Callback import okhttp3.EventListener @@ -43,6 +44,7 @@ class DialogueClient( private val onProtocolError: (String) -> Unit = {}, private val onConnectionLog: (String) -> Unit = {}, private val actionPackSha: () -> String? = { null }, + private val pendingActionPackSha: () -> String? = { null }, private val onStatusReason: (ConnectionStatus, String) -> Unit = { _, _ -> }, ) { private val main = Handler(Looper.getMainLooper()) @@ -79,6 +81,15 @@ class DialogueClient( private var helloSent = false private var loggedAudioTurn: Long? = null private var handshakeTimeout: Runnable? = null + private var pendingOffered: String?=null + private var readyUpdateSent=false + fun capabilitiesReady(): Boolean { + checkMainThread() + val pin=actionPackSha() ?: return false + if(!ready || readyUpdateSent || pendingOffered!=pin || actionNegotiation!="pending_pack") return false + readyUpdateSent=send(DialogueProtocol.capabilitiesReady(pin)) + return readyUpdateSent + } fun connect() { checkMainThread() @@ -95,6 +106,7 @@ class DialogueClient( authReceived = false helloSent = false actionNegotiation = "pending" + pendingOffered=null;readyUpdateSent=false loggedAudioTurn = null healthCall?.cancel() healthCall = null @@ -102,6 +114,7 @@ class DialogueClient( socket = null val attempt = generation updateStatus(ConnectionStatus.CONNECTING, "connect_start") + StartupTrace.mark(StartupTrace.Phase.HEALTH_START) connectionLog("health checking #$attempt", "connect") // Arm before submitting the request; synchronous setup failures are terminal too. handshakeTimeout = Runnable { @@ -159,6 +172,7 @@ class DialogueClient( healthCall = null // Even 404/403/503 establishes HTTPS reachability. /health may be // absent or protected; only the actual WS handshake decides busy. + StartupTrace.mark(StartupTrace.Phase.HEALTH_HTTP) connectionLog("health HTTP $code · HTTPS 可达", "connect") openWebSocket(attempt) } @@ -261,6 +275,7 @@ class DialogueClient( private fun listener(attempt: Long) = object : WebSocketListener() { override fun onOpen(webSocket: WebSocket, response: Response) = dispatch(attempt, webSocket) { wsOpened = true + StartupTrace.mark(StartupTrace.Phase.WS_OPEN) connectionLog("ws open") } @@ -292,9 +307,11 @@ class DialogueClient( } if (authReceived) return@dispatch authReceived = true + StartupTrace.mark(StartupTrace.Phase.AUTH) connectionLog("auth ok", "auth") val offeredPack=actionPackSha() - if (webSocket.send(DialogueProtocol.hello(offeredPack))) { + pendingOffered=if(offeredPack==null) pendingActionPackSha() else null + if (webSocket.send(DialogueProtocol.hello(offeredPack,pendingOffered))) { helloSent = true connectionLog("hello sent action_offer=${offeredPack?.takeIf { it.matches(Regex("[0-9a-f]{64}")) }?.take(12) ?: "none"} generation=$attempt", "auth") } else { @@ -309,14 +326,25 @@ class DialogueClient( return@dispatch } ready = true + StartupTrace.mark(StartupTrace.Phase.HELLO) cancelHandshakeTimeout() actionNegotiation=when { + event.payload.optBoolean("action_pending",false) && pendingOffered!=null -> "pending_pack" 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") + capabilitiesReady() + } + if(event.kind==EventKind.CAPABILITIES && ready && readyUpdateSent) { + val pin=event.payload.optString("action_pack_sha256") + if(pin==pendingOffered && pin==actionPackSha()) { + actionNegotiation=if(event.payload.optBoolean("action_available",false)) "accepted" else "unavailable" + com.gorios.lanvoice.diag.StartupTrace.mark(com.gorios.lanvoice.diag.StartupTrace.Phase.CAP_READY) + connectionLog("capabilities ready action_pack=$actionNegotiation generation=$attempt","auth") + } } if (event.kind == EventKind.ERROR && !ready) { connectionLog("握手收到 error", "error") diff --git a/app/src/main/java/com/gorios/lanvoice/net/DialogueProtocol.kt b/app/src/main/java/com/gorios/lanvoice/net/DialogueProtocol.kt index f5b1c23..4131bfb 100644 --- a/app/src/main/java/com/gorios/lanvoice/net/DialogueProtocol.kt +++ b/app/src/main/java/com/gorios/lanvoice/net/DialogueProtocol.kt @@ -10,7 +10,7 @@ import com.gorios.lanvoice.expression.FaceCueObservation data class ServerEvent(val type: String, val kind: EventKind, val payload: JSONObject) enum class EventKind { - AUTH, HELLO, HISTORY, LISTEN, VAD, STT, LLM, TTS, REPLY_EMOTION, EXPRESSION_PREPARE, ACTION, SPEECH, ERROR, ABORT, METRICS, PING, PONG, UNKNOWN + AUTH, HELLO, CAPABILITIES, HISTORY, LISTEN, VAD, STT, LLM, TTS, REPLY_EMOTION, EXPRESSION_PREPARE, ACTION, SPEECH, ERROR, ABORT, METRICS, PING, PONG, UNKNOWN } /** Header integers are unsigned, network byte order; PCM samples are signed little endian. */ @@ -26,7 +26,7 @@ object DialogueProtocol { const val UPLINK_PCM_BYTES = 640 const val DOWNLINK_PCM_BYTES = 1_920 - fun hello(actionPackSha: String? = null): String = JSONObject() + fun hello(actionPackSha: String? = null,pendingPackSha: String?=null): String = JSONObject() .put("type", "hello") .put("codec", "pcm16") .put("sample_rate", 16_000) @@ -36,9 +36,18 @@ object DialogueProtocol { .apply { if (actionPackSha?.matches(Regex("[0-9a-f]{64}")) == true) { put("action_protocol", 1); put("action_pack_sha256", actionPackSha) put("action_kinds", org.json.JSONArray().put("dance")) + } else if(pendingPackSha?.matches(Regex("[0-9a-f]{64}"))==true) { + put("action_protocol",1);put("action_pending_pack_sha256",pendingPackSha) + put("action_kinds",org.json.JSONArray()) } } .toString() + fun capabilitiesReady(pin: String): String { + require(pin.matches(Regex("[0-9a-f]{64}"))) + return JSONObject().put("type","client.capabilities.ready").put("action_protocol",1) + .put("action_pack_sha256",pin).put("action_kinds",org.json.JSONArray().put("dance")).toString() + } + fun listen(start: Boolean): String = JSONObject() .put("type", "listen") .put("state", if (start) "start" else "stop") @@ -90,6 +99,7 @@ object DialogueProtocol { val kind = if (type.startsWith("reply.emotion.prepare")) EventKind.EXPRESSION_PREPARE else if (type == "reply.emotion") EventKind.REPLY_EMOTION else when (type.substringBefore('.')) { "auth" -> EventKind.AUTH "hello" -> EventKind.HELLO + "client.capabilities" -> EventKind.CAPABILITIES "history" -> EventKind.HISTORY "listen" -> EventKind.LISTEN "vad" -> EventKind.VAD diff --git a/docs/COLD_START_FIX_074.md b/docs/COLD_START_FIX_074.md new file mode 100644 index 0000000..f70b84d --- /dev/null +++ b/docs/COLD_START_FIX_074.md @@ -0,0 +1,72 @@ +# 0.7.4 / code22 cold-start candidate + +Coord's real code21 WindowsUSB normal cold-start observation was `Displayed +31s949ms`, observed 32.086s, with 1823 + 38 = 1861 skipped frames. `am start -W` returned timeout around 10.385s; the process remained foreground/running and no fatal/ANR was captured. There were no precise app phase markers, so this does **not** measure how much of 31.949s belongs to one function. Source audit confirmed the full synchronous `AvatarPack.load()` ran before `setContent`: index/runtime parsing, SHA checks and 3185 PNG dimension checks. HELLO was asynchronous and did not gate composition. + +## Implementation + +`MainActivity` immediately composes a stable white-role shell with a 240×424 sourceframe0 poster and 48dp safe-inset gear. System splash has no fixed delay or required intro. Role preparation and connection status are independent, small bottom lines; each disappears on its own readiness and the ready home contains only the character and gear. Offline/error does not display endless connecting. Settings retains diagnostics and preparation retry. + +The serial `avatar-validation` worker first verifies an exact tiny bootstrap manifest, poster and existing silent neutral body. This body-only loop has no TALK patches, expression or dance capability. It then strictly admits the complete frozen pack on that worker: index/runtime SHA/schema, own-frame/PTS/body bindings, 3185 PNG hashes/dimensions and body/edge/action bytes. Duplicate edge media already verified through its own runtime is reused; digest hex encoding avoids per-byte Formatter overhead. GL/codec decoding remains on renderer workers and only current/next graph resources are decoded, within the existing 8MB per-runtime / 32MB aggregate limits. No array of all 13 runtimes' bitmaps is created on main. + +One `StartupAvatarView` prepares the full renderer hidden/held at actual neutral frame0. Handoff requires the bootstrap's actual frame0 and the full renderer's composed frame0 of the **same body SHA**. The bootstrap decoder releases before capability activation; late callbacks cannot reclaim its layer. Full playback retains code21's decoded source-PTS clock and code19's ACTION display owner. Background/disposal fences both renderers; settings does not key/recreate the host. A preparation failure keeps the basic role/poster and allows an explicit settings retry. + +`StartupLoadCache` shares inflight/successful metadata by APK versionCode + lastUpdateTime + exact index SHA + asset root + validator version. It holds no Activity, bitmap, Surface, camera or GL object. Destroy removes listeners; failed work is not success-cached. Different lifecycle instances reconstruct their own render resources. + +A private atomic, fsynced, bounded complete receipt applies **only to immutable APK assets** for that exact key. A new process still reads/hashes/parses all index/runtime metadata through strict production parsers; only previously completed media/PNG byte checks are reused. Version/pin/install/validator change, missing/corrupt/partial records revalidate. It never deserializes a trusted AvatarPack, applies to downloaded paths, or trusts a filename. Receipt-write failure leaves current verified admission valid and means a future process verifies again. First install remains a full verification; process cache and cross-process receipt are distinct. + +## Capability update + +Before full verification **and actual renderer handoff**, HELLO sends protocol1 + the exact pending reviewed SHA + empty action kinds. It does not advertise dance. Gateway authorizes pending readiness only against its independent exact reviewed registry on that authenticated socket. `client.capabilities.ready` can activate only the same authorized pin; legacy/unknown/different pins cannot upgrade, repeats are idempotent and old sockets are fenced. It changes neither turn, history, AudioRecord, drain nor after_action. Each LLM generation snapshots availability at request start, so readiness affects later requests rather than reinterpreting an in-flight answer. Offline dance controls also wait for the real handoff. + +Gateway-only hash/busy/backup deployment succeeded; unit/environment relationships were verified unchanged. Backup: `/home/gorios-spark-2/lan-voice/.runtime/backups/voice-gateway-20261013-142340`. Version remains 0.8.0; Qwen/provider/server clock/TTS parameters and model/ASR/TTS/VAD services were not changed or restarted. Existing exact action registry/durations remain unchanged. + +## Assets and reproducibility + +Frozen index: `987e125a7d7a2cde99121b5f5246c82f4dbe36c4899d3d49eaffd1a68bafb887`, 3222 runtime references, 5 bodies + 8 own-mouth bridges + 13 edges + 2 dances. White outfit and mouth1.1 bytes stay identical to code18/21. No new black-tulle assets enter this candidate. Bootstrap adds only a tiny manifest and poster under `avatar/startup-white-01/`, plus the same ignored PNG as an Android resource. No new body/video is generated. + +After restoring the externally pinned private import, run `python3 scripts/prepare-startup-assets.py`; it validates the full pin and source body hash and reproduces the exact archived manifest/poster SHA from existing neutral sourceframe0 with ffmpeg/Pillow. `--verify-only` checks existing output without changing it. `manifests/startup-white-01.json` and the script are versioned; portrait PNGs/videos stay ignored. No paid/model/generation call was made for this stage. Coord subsequently superseded the SVG launch-art candidate: this version uses existing icon/system resources. New Pi PNG icon/Splash and any new visual short-loop file are not yet delivered and will be adapted separately; no raster image is vectorized and no unavailable loop blocks startup. The preparation loop here is the existing verified white neutral body, with no fixed waiting timer. + +## Evidence and limits + +Nine JVM entry points/UI contracts, existing 757 reported-clock and 103 native callback assertions, production renderer/capture/action regression cases, 200 offline GLES pixel cases, 32 packaging tests, and strict complete-pack parser/media gate pass. Gateway archive ran 101 tests: **100 passed, 1 existing Silero artifact-exclusion skip**. A finite canonical-source isolated WS route probe used 3 connections, with 0 LLM/ASR/TTS calls: pending exactpin upgrades, legacy/unknown remain unavailable, duplicate update preserves the turn. This is not a live phone conversation or inference benchmark. + +Production background repository replay over actual APK bytes reports **0 main-thread asset reads**, cold 3185 patch reads, cross-process receipt 0 patch reads, same-process reload 0 reads. Concurrency/cancel/failure-retry/key/receipt corruption and actual host source0/target0/decoderrelease/lifecycle/failure-retry callbacks are tested with Android/codec/GL doubles. Host time is not phone performance. Instrumentation compiles but has not run on a device. Code21 phone playback success is inherited evidence, not code22 GPU handoff or performance certification. Music listening/full dynamic naturalness remain unmeasured. + +## Coord device measurement + +Normal launcher with already granted MIC/CAM can automatically connect and start capture in foreground after the first draw. Offline preview never constructs VoiceSession/camera or captures either sensor. This agent does not install or launch the phone. + +On the existing authorized WindowsADB serial `0123456789ABCDEF`, measure the **same normal launcher conditions** as code21, without clearing app data or changing networking: + +```text +adb -s 0123456789ABCDEF shell am force-stop com.gorios.lanvoice +adb -s 0123456789ABCDEF shell am start -W -n com.gorios.lanvoice/.MainActivity -a android.intent.action.MAIN -c android.intent.category.LAUNCHER +``` + +Sensor-free control entry: + +```text +adb -s 0123456789ABCDEF shell am start -W -n com.gorios.lanvoice/.MainActivity --ez avatar_offline_preview true +``` + +Capture only fixed startup markers via `adb ... logcat -v monotonic -s LanVoiceStartup:I *:S`, plus separately filtered System `Displayed com.gorios.lanvoice` / Choreographer skip metadata. Do not save general chat, camera/audio or raw protocol logs. Compare first post-update process (receipt_miss), a force-stopped second process (receipt_hit), and settings open/close in one process (stable host). Do not clear receipt/data to manufacture repeated cold misses; version/install-key changes already revalidate. + +Marker fields: `run`, finite `phase`, `mono_ms`, `elapsed_ms`, `duration_ms` (-1 means an event endpoint; subtract matching monotonic endpoints). Phases include on_create, shell_set_content, first_draw, poster_ready, basic_verify, first_idle_frame, index_parse, runtimes_verify, media_verify, cache_hit/miss, receipt_hit/miss/write, full_ready/failed, full_first_gl, handoff, health_start/http, ws_open, auth, hello, cap_ready, camera_model/bind/ready. `camera_ready` is the first analysis image arrival; it is not proof of a recognized face. These metadata enter the bounded500 diagnostic ring without frame-level churn. + +Suggested coord JSON: versionCode/pinPrefix/mode, amStartStatus/waitMs, displayedMs, skippedFrames, cacheClass, startupPhases[{run,phase,monoMs,elapsedMs,durationMs}], roleReady/connectionReady/actionNegotiation, errors as fixed enums, devicePerformance=`measured` or `not_run`. Report missing markers as missing, not as zero-duration/unexecuted phases. Actual performance improvement must be stated only after this same-phone comparison. + +## Published candidate + +Published `0.7.4 / code22`, package `com.gorios.lanvoice`, arm64, min26 / target34, using the existing icon (no SVG import, no pending PNG artwork). + +- APK: http://192.168.31.124:8080/lan-voice-v074-startup-fix-code22-arm64-debug.apk +- SHA256: `c39457c2ff0799779b6bcaecb713c13a6d52bbd90dea4634c7216ed8929e1131`; HTTP APK and `.apk.sha256` bytes independently matched. +- Debug certificate SHA256: `b9608336bc1ed1de3269bb4594f9fe718daaa5439511c5187aa385d2b799dcf1`. +- Compiled pin remains `987e125a7d7a2cde99121b5f5246c82f4dbe36c4899d3d49eaffd1a68bafb887`; startup and repaired source-PTS clock flags are true. +- Final APK comparison: all 3816 existing `assets/avatar/` files equal code21 byte-for-byte, including all 3222 frozen runtime references. Only two tiny bootstrap asset files were added. Code18/21 and older published packages remain available. + +Fresh final-source regression passed all nine JVM/UI entries and 32 package tests. Final Gradle assembled the APK and compiled Android instrumentation; instrumentation was not run. Actual final APK production loader/media callback replay passed (including legal idle returns after new turns, independent happy/sad mouths, full action layer/audio release/return). The real repository over final APK bytes passed two isolated JVM processes: cold 3185 patch reads, receipt reload zero patch reads, both zero main-thread asset reads; same-process full reload zero asset reads. These use Android/codec/GL doubles and do not prove phone rendering or elapsed startup time. + +The deployed canonical gateway was read-only rechecked after build: all 37 archived source/registry hashes match. Only the previously described gateway capability change was deployed/restarted once in this stage; the APK publisher does not deploy a server. Gateway remains 0.8.0 with unchanged environment, provider/time/TTS parameters and other services. 100 gateway tests passed, with the one explicit pre-existing excluded-Silero-model skip. The isolated finite WS probe used three connections and no inference. + +No code22 phone install, launch, capture, screenshot, GPU test or performance measurement was performed here. Coord can now compare normal first-draw/system Displayed and the monotonic startup stages to the code21 31.949s baseline on the same phone. Normal startup with already granted MIC/CAM can auto-start foreground capture; use the documented offline extra for a sensor-free control. Preparation is a verified existing neutral loop, not a fixed-duration intro. The next PNG icon/Splash remains a separate integration after actual transfer, with a fresh artifact version if code22 has already shipped. diff --git a/gateway/SOURCE_MANIFEST.json b/gateway/SOURCE_MANIFEST.json index bf3d69a..7c6d3ac 100644 --- a/gateway/SOURCE_MANIFEST.json +++ b/gateway/SOURCE_MANIFEST.json @@ -34,8 +34,8 @@ }, "gateway.py": { "source": "workspace:gateway/gateway.py", - "sha256": "de94825b2005c5e4eedd1beb10360b477dc40d7e1bd6dc5c7d95b50bbc46cbef", - "bytes": 45724, + "sha256": "0d57875ec480b2fe3990754fbef75d72e7a92cbfc1ec291b27461a983227bdbb", + "bytes": 46738, "upstream_sha256": "d088bedcf5c0accd4712e06202f6ced8ab155aad57a5b05683724efa346326ce" }, "guest_sessions.py": { @@ -326,8 +326,9 @@ }, "action_protocol.py": { "source": "workspace:gateway/action_protocol.py", - "sha256": "ca98055f9ddba361d36607791522cee15ce254b3d40395cd45c508e96c42a2f8", - "bytes": 4166 + "sha256": "04c65ce27140da7757e0164983efe33800dddcff0139d16e8fe4c8a99a3b50ee", + "bytes": 4697, + "upstream_sha256": "ca98055f9ddba361d36607791522cee15ce254b3d40395cd45c508e96c42a2f8" }, "action_reply.py": { "source": "workspace:gateway/action_reply.py", @@ -359,6 +360,11 @@ "source": "workspace:gateway/reviewed_action_packs.json", "sha256": "830334cacf04bc488e7f07809a6defdcec481410b6bedb7b78cfa78f8ecf334e", "bytes": 125 + }, + "tests/test_capabilities_ready.py": { + "source": "workspace:gateway/tests/test_capabilities_ready.py", + "sha256": "49b9cf64e6d30e389588014a3a1de04d1a7b98f20fbea036ace4dcf8debfe857", + "bytes": 3494 } }, "archive_baseline_commit": "19a7adccd9322986eb0646b165b9ce1cf2650cf2", @@ -392,13 +398,13 @@ }, "release_baseline_commit": "d43c7d4e809a5a6b18ca9f28c8163a2f9ad34c7f", "deployment_baseline": { - "release": "gateway-0.8.0 / reviewed full action/emotion candidate", + "source": "startup capabilities update; live gateway-only hash-fenced deployment", "files": { - "action_protocol.py": "ca98055f9ddba361d36607791522cee15ce254b3d40395cd45c508e96c42a2f8", + "action_protocol.py": "04c65ce27140da7757e0164983efe33800dddcff0139d16e8fe4c8a99a3b50ee", "action_reply.py": "4d66164a6668a571dc861282a5c80e408b51dfcfd67f45141e8c6701f6b81364", "app.py": "d6520894dfbe035f64b1984aae15976db4df0e7e720195c81d3bf483b240056f", "face_context.py": "d032ff8033a49219595d6edff2950856937e024782143621d37d02b56b024315", - "gateway.py": "de94825b2005c5e4eedd1beb10360b477dc40d7e1bd6dc5c7d95b50bbc46cbef", + "gateway.py": "0d57875ec480b2fe3990754fbef75d72e7a92cbfc1ec291b27461a983227bdbb", "guest_sessions.py": "cc082fdb6c2ff7f5a41361ffe9ea2a53ebb944ee37354f65119405ad7a521c82", "history.py": "0015b3143268f3e22a8a8a53b65ef4e3522f1f881dfca213c93142899c02631e", "llm_provider.py": "b3cf6ab5e4c953ef13dc00802f4594055164c89b10b875dda44f071ad1ede082", @@ -412,6 +418,7 @@ "server_clock.py": "dc46d79fd43c8b94f52acfdea0564058c47f3a3b8b43aa53fe6868a1821f3a0e", "tests/test_action_protocol.py": "f1340c6c68674fc5d077003ca6be51746b31462ccc26acc0c092fbad01f629dc", "tests/test_action_reply.py": "0c40a937be4c6545e04ed2268df1714c34dce982058f6b19daabf06b0fa30932", + "tests/test_capabilities_ready.py": "49b9cf64e6d30e389588014a3a1de04d1a7b98f20fbea036ace4dcf8debfe857", "tests/test_continuity.py": "d8390238f390463a98f12b9909bb5846be65f5b6dc1b21b94338b4cd75aaafae", "tests/test_debug.py": "7d1d7876c4106f3df0b84cf8f7e479afb4a30ca51264fb94fa288fdd8155883e", "tests/test_face_context.py": "c297866117fa7406b5fda95250b67ca7ebd7476486ddd5455935c140d31c9f6f", diff --git a/gateway/action_protocol.py b/gateway/action_protocol.py index f213da4..7b3fb3a 100644 --- a/gateway/action_protocol.py +++ b/gateway/action_protocol.py @@ -36,6 +36,17 @@ def negotiate(hello, configured): return sha, dict(pack) +def pending_pin(hello, configured): + """Authorize only a future SAME reviewed pin on this authenticated connection. + No action available until the client's complete immutable admission and handoff. + """ + if hello.get('action_protocol') != 1 or hello.get('action_kinds') != [] or 'action_pack_sha256' in hello: + return None + sha=hello.get('action_pending_pack_sha256') + offer={'action_protocol':1,'action_kinds':['dance'],'action_pack_sha256':sha} + return sha if negotiate(offer, configured) else None + + @dataclass class ActionTicket: id: str diff --git a/gateway/gateway.py b/gateway/gateway.py index 7427736..89d3e66 100644 --- a/gateway/gateway.py +++ b/gateway/gateway.py @@ -21,7 +21,7 @@ from history import History from face_context import FaceContext from reply_emotion import SYSTEM_FRAGMENT, parse_reply from action_reply import ACTION_FRAGMENT, ExpressionPrefix, parse_action_reply -from action_protocol import ActionPlans, negotiate, configured_packs +from action_protocol import ActionPlans, negotiate, configured_packs, pending_pin from guest_sessions import GuestSessions, COOKIE from tts_debug import DebugStore from persona_resolver import resolve_persona @@ -236,6 +236,7 @@ class Dialogue: self.owner = secrets.token_hex(16) self.action_plans = ActionPlans(self.owner, self.connection_generation) self.action_capability = None + self.pending_action_pin = None self.action_expiry_task = None self.action_holding = False self.followup_pending = None @@ -504,10 +505,11 @@ class Dialogue: async def generate(self, turn, text, queue, metrics, began): request_start = time.perf_counter() + capability = self.action_capability # Request snapshot: readiness never changes an in-flight answer. metrics.update(voice_mode=self.voice_mode, voice_id=self.voice_id, tts_request_count=0) # Exactly one initial system: Qwen's deployed template rejects a second system. system = '以下角色设定只约束reply字段的可朗读正文。\n' + self.persona_rules + ''.join( - '\n\n' + item['content'] for item in self.face_messages.get(turn, [])) + '\n\n' + SYSTEM_FRAGMENT + '\n' + ACTION_FRAGMENT + '\n网关实际可用动作:' + ('dance' if self.action_capability else '无') + '\n\n' + item['content'] for item in self.face_messages.get(turn, [])) + '\n\n' + SYSTEM_FRAGMENT + '\n' + ACTION_FRAGMENT + '\n网关实际可用动作:' + ('dance' if capability else '无') messages = [{'role': 'system', 'content': system}] + self.contexts.get(turn, []) + [{'role': 'user', 'content': text}] url, headers, body = self.llm_provider.request(messages, max_tokens=160, action_plan=True) metrics['llm_request_count'] = 1 @@ -548,14 +550,14 @@ class Dialogue: if turn != self.turn: return if not raw_body.strip(): raise ValueError('empty LLM body') parse_start = time.perf_counter() - plan = parse_action_reply(raw_body, finish_reason, bool(self.action_capability)) + plan = parse_action_reply(raw_body, finish_reason, bool(capability)) result = plan.speech metrics['action_reason'] = plan.action_reason metrics['expression_prepare_mode'] = 'schema_prefix_preload' if prepare_enabled else 'full_reply' if prepare_enabled and prefix.candidate and not prefix.consistent(plan, self.turn): await self.event('reply.emotion.prepare.cancel', turn, reason='final_invalid') if plan.action == 'dance': - ticket = self.action_plans.create(turn, plan.after, self.action_capability) + ticket = self.action_plans.create(turn, plan.after, capability) self.action_expiry_task = asyncio.create_task(self.expire_action(ticket.id, turn)) metrics.update(reply_emotion_reason=result.reason, reply_parse_branch=result.parse_branch, reply_emotion=result.emotion, reply_intensity=result.intensity, @@ -592,6 +594,17 @@ class Dialogue: except asyncio.CancelledError: pass + async def capabilities_ready(self, data): + # This Dialogue belongs to the authenticated socket/owner generation. The + # HELLO authorization cannot be manufactured or changed by a later event. + pin=self.pending_action_pin + offered=negotiate(data, configured_packs()) + accepted=bool(pin and offered and offered[0]==pin and + (self.action_capability is None or self.action_capability==offered)) + if accepted: self.action_capability=offered + await self.event('client.capabilities', action_available=accepted, + action_pack_sha256=pin or '') + async def action_status(self, data): status, after = self.action_plans.status(data, self.turn, self.owner, self.connection_generation) if status in ('cancelled', 'failed'): @@ -755,6 +768,7 @@ async def dialogue(ws: WebSocket): session.owner = owner or 'admin' session.action_plans = ActionPlans(session.owner, session.connection_generation) session.action_capability = negotiate(hello, configured_packs()) + session.pending_action_pin = pending_pin(hello, configured_packs()) if owner: session.auth_check = lambda: bool(app.state.guests.get(owner)) voice_mode = hello.get('voice_mode', 'continuous_voice') if voice_mode not in ('continuous_voice', 'fragment'): raise ValueError('voice mode') @@ -769,7 +783,7 @@ async def dialogue(ws: WebSocket): session.voice_id = voice_id session.debug_store = app.state.debug session.debug_enabled = hello.get('tts_debug', True) is True - await session.event('hello', action_protocol=1, action_available=bool(session.action_capability), context_face_cue_version=1, reply_emotion_version=1, llm_structured_output=session.llm_provider.structured_output, version=VERSION, codec='pcm16', sample_rate=16000, output_sample_rate=48000, channels=1, frame_duration=20, header_version=1, conversation_id=cid, duplex_default=True, voice_mode=voice_mode, voice_id=voice_id, voices=app.state.voices) + await session.event('hello', action_protocol=1, action_available=bool(session.action_capability), action_pending=bool(session.pending_action_pin), context_face_cue_version=1, reply_emotion_version=1, llm_structured_output=session.llm_provider.structured_output, version=VERSION, codec='pcm16', sample_rate=16000, output_sample_rate=48000, channels=1, frame_duration=20, header_version=1, conversation_id=cid, duplex_default=True, voice_mode=voice_mode, voice_id=voice_id, voices=app.state.voices) await session.send_history() started = time.monotonic() while time.monotonic() - started < 600: @@ -817,6 +831,8 @@ async def dialogue(ws: WebSocket): else: raise ValueError('history action') elif data.get('type') == 'playback.drained': await session.request_drained(data.get('turn_id')) + elif data.get('type') == 'client.capabilities.ready': + await session.capabilities_ready(data) elif data.get('type') == 'action.status': await session.action_status(data) elif data.get('type') == 'ping': await session.event('pong') diff --git a/gateway/tests/test_capabilities_ready.py b/gateway/tests/test_capabilities_ready.py new file mode 100644 index 0000000..6ebadd0 --- /dev/null +++ b/gateway/tests/test_capabilities_ready.py @@ -0,0 +1,57 @@ +import asyncio +import json +import time +import unittest +from unittest.mock import patch +import httpx +from action_protocol import pending_pin +from gateway import Dialogue +from test_gateway import Socket +from tests_fake import FakeModel + +PIN='a'*64 +PACK={PIN:{'asset_01':1000,'asset_02':2000}} +READY={'type':'client.capabilities.ready','action_protocol':1,'action_kinds':['dance'],'action_pack_sha256':PIN} + +class CapabilitiesTests(unittest.IsolatedAsyncioTestCase): + def test_pending_pin_exact_reviewed_empty_only(self): + valid={'action_protocol':1,'action_kinds':[],'action_pending_pack_sha256':PIN} + self.assertEqual(pending_pin(valid,PACK),PIN) + for hello in ({}, {**valid,'action_protocol':2},{**valid,'action_kinds':['dance']}, + {**valid,'action_pack_sha256':PIN},{**valid,'action_pending_pack_sha256':'b'*64}): + self.assertIsNone(pending_pin(hello,PACK)) + + async def test_update_same_socket_pin_once_no_turn_ticket_or_generator_change(self): + d=Dialogue(Socket(),FakeModel(),None) + with patch('gateway.configured_packs',return_value=PACK): + await d.capabilities_ready(READY);self.assertIsNone(d.action_capability) + d.pending_action_pin=PIN + for bad in ({**READY,'action_pack_sha256':'b'*64},{**READY,'action_kinds':[]},{**READY,'action_protocol':2}): + await d.capabilities_ready(bad);self.assertIsNone(d.action_capability) + await d.capabilities_ready(READY);cap=d.action_capability + ticket=d.action_plans.create(0,'after',cap) + await d.capabilities_ready(READY) + self.assertEqual(d.action_capability,cap);self.assertIs(d.action_plans.ticket,ticket) + self.assertEqual(d.turn,0);self.assertIsNone(d.task) + await d.capabilities_ready({**READY,'action_pack_sha256':'b'*64});self.assertEqual(d.action_capability,cap) + other=Dialogue(Socket(),FakeModel(),None) + with patch('gateway.configured_packs',return_value=PACK):await other.capabilities_ready(READY) + self.assertIsNone(other.action_capability) + await other.close();await d.close() + + async def test_inflight_reply_freezes_capability_and_next_request_can_dance(self): + entered=asyncio.Event();release=asyncio.Event();calls=[] + raw=json.dumps(dict(emotion='happy',intensity=1,reply='公开合成正文',action='dance',after_action=dict(reply='公开后续',emotion='sad',intensity=1))) + async def backend(request): + calls.append(request) + if len(calls)==1:entered.set();await release.wait() + return httpx.Response(200,text='data: '+json.dumps({'choices':[{'delta':{'content':raw},'finish_reason':'stop'}]})+'\n\ndata: [DONE]\n\n') + async with httpx.AsyncClient(transport=httpx.MockTransport(backend)) as client: + d=Dialogue(Socket(),FakeModel(),client);d.pending_action_pin=PIN + with patch('gateway.configured_packs',return_value=PACK): + task=asyncio.create_task(d.generate(0,'公开合成请求',asyncio.Queue(),{},time.perf_counter())) + await asyncio.wait_for(entered.wait(),2);await d.capabilities_ready(READY);release.set();await task + self.assertIsNone(d.action_plans.ticket) + await d.generate(0,'公开合成请求',asyncio.Queue(),{},time.perf_counter()) + self.assertIsNotNone(d.action_plans.ticket);self.assertEqual(len(calls),2) + await d.close() diff --git a/manifests/startup-white-01.json b/manifests/startup-white-01.json new file mode 100644 index 0000000..b008db4 --- /dev/null +++ b/manifests/startup-white-01.json @@ -0,0 +1 @@ +{"schemaVersion":1,"sourceIndexSha256":"987e125a7d7a2cde99121b5f5246c82f4dbe36c4899d3d49eaffd1a68bafb887","posterSha256":"e4c0090fb5f374cf582daba202cff934e28018fd57cddfbc5af8f9d54590164d","body":{"path":"avatar/a01-expression-action-v1/runtime/neutral/body/idle.mp4","sha256":"177dbc0ab809e3c9c684899ffbd9cf3a2c357973c7037134f5d79e4e6cdfc762","frameCount":97,"width":480,"height":848,"fpsNumerator":24,"fpsDenominator":1,"frameDurationUsNumerator":1000000,"frameDurationUsDenominator":24,"durationUs":4041667,"hasAudio":false,"loopSeamReview":"pending_device_visual_review","sourceMasterSHA256":"4d6cc09a2ba53286ad0f713708b37b6fbc4231ad4b63cff83c66274bb618df30","ptsUs":[0,41667,83333,125000,166667,208333,250000,291667,333333,375000,416667,458333,500000,541667,583333,625000,666667,708333,750000,791667,833333,875000,916667,958333,1000000,1041667,1083333,1125000,1166667,1208333,1250000,1291667,1333333,1375000,1416667,1458333,1500000,1541667,1583333,1625000,1666667,1708333,1750000,1791667,1833333,1875000,1916667,1958333,2000000,2041667,2083333,2125000,2166667,2208333,2250000,2291667,2333333,2375000,2416667,2458333,2500000,2541667,2583333,2625000,2666667,2708333,2750000,2791667,2833333,2875000,2916667,2958333,3000000,3041667,3083333,3125000,3166667,3208333,3250000,3291667,3333333,3375000,3416667,3458333,3500000,3541667,3583333,3625000,3666667,3708333,3750000,3791667,3833333,3875000,3916667,3958333,4000000]}} diff --git a/scripts/check-avatar-apk-runtime.py b/scripts/check-avatar-apk-runtime.py index e26b9ff..9b067cc 100644 --- a/scripts/check-avatar-apk-runtime.py +++ b/scripts/check-avatar-apk-runtime.py @@ -8,6 +8,7 @@ import argparse parser=argparse.ArgumentParser(description=__doc__) parser.add_argument('--apk',type=Path,required=True) parser.add_argument('--sha256',required=True) +parser.add_argument('--startup-loader',action='store_true',help='Production background repository over actual APK bytes, isolated private receipt, no rendering/connection') 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' @@ -25,6 +26,8 @@ class JSONObject(private val map: Map) { fun keys()=map.keys.iterator() fun get(k: String): Any? = wrap(map.getValue(k)) fun getString(k: String)=map.getValue(k) as String + fun getJSONObject(k: String)=JSONObject(map.getValue(k) as Map) + fun getLong(k: String)=(map.getValue(k) as Number).toLong() 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<*>) @@ -34,6 +37,7 @@ 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 + fun getLong(i: Int)=(values[i] as Number).toLong() } private class Parser(val s: String) { var i=0 @@ -54,12 +58,21 @@ private class Parser(val s: String) { ''' context=r''' package android.content -class Context { val assets = Assets() } +class Context { + val assets = Assets();val applicationContext get()=this;val packageName="com.gorios.lanvoice" + val packageManager=PackageManager();val filesDir get()=Archive.privateDir +} +class PackageManager { fun getPackageInfo(name: String,flags: Int)=PackageInfo() } +class PackageInfo { val versionCode=22;val lastUpdateTime=123456L } 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 open(path: String): java.io.InputStream { + if(Archive.requireWorker) check(Thread.currentThread()!==Archive.owner) { "asset_read_on_main" } + synchronized(Archive.reads) {Archive.reads.add(path)} + return 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 Archive { lateinit var zip: java.util.zip.ZipFile;lateinit var privateDir: java.io.File;var requireWorker=false;val owner=Thread.currentThread();val reads=mutableListOf() } object AssetFixture { val paths=mutableMapOf() } class Descriptor(path: String="") : java.io.Closeable { val fileDescriptor=java.io.FileDescriptor();val startOffset=0L;val length=20L @@ -76,7 +89,7 @@ graphics=(ROOT/'tests/avatar/Graphics.kt').read_text();graphics=graphics.replace } ''') 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 +object BuildConfig { const val AVATAR_STARTUP_FIX=false;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" }''' @@ -100,7 +113,7 @@ fun main(args: Array) { index.actionPack?.assets?.mapNotNull { it.media }?.forEach { CodecFixture.timelines[it.root+it.path]=it.ptsUs;CodecFixture.audioPaths.add(it.root+it.path) } val binding=AvatarMediaBinding();binding.beginTurn(7) val trace=mutableListOf>() - val view=EmotionActionAvatarView(context,pack,binding) { trace.add(TestScheduler.now to it) } + 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>) { @@ -174,12 +187,43 @@ fun main(args: Array) { 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") } ''' +startup_main=r''' +import com.gorios.lanvoice.avatar.* +import android.os.TestScheduler +fun main(args: Array) { + android.content.Archive.zip=java.util.zip.ZipFile(args[0]);android.content.Archive.privateDir=java.io.File(args[1]) + android.os.Looper.getMainLooper();android.content.Archive.requireWorker=true + val context=android.content.Context();var base: ContinuousAvatarPack?=null;var pack: AvatarPack?=null + fun waitReady() { + val deadline=System.nanoTime()+40_000_000_000L + while(pack==null || base==null) { TestScheduler.advanceBy(0);check(System.nanoTime()=27,'full release regression evidence') + require(evidence['gateway_passed']>=97 and evidence['gateway_skipped']==1 and evidence['offline_gles_goldens']==200 and evidence['packaging_passed']>=27,'full release regression evidence') for name,digest in evidence['hashes'].items(): require(file_sha(ROOT/name)==digest,'full release evidence drift: '+name) return evidence=json.loads((ROOT/'logs/action-emotion/bridge-talk/delivery.json').read_text()) @@ -286,18 +286,23 @@ def packaging_tests_current(): for name,digest in evidence['hashes'].items(): require(file_sha(ROOT/name)==digest,'untested packaging source: '+name) -def verify_runtime_fix_assets(built,pin): +def verify_runtime_fix_assets(built,pin,startup_fix=False): 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') + extra={'assets/avatar/startup-white-01/manifest.json','assets/avatar/startup-white-01/poster.png'} if startup_fix else set() + require(paths(new)==paths(old)|extra,'runtime fix avatar inventory changed') + if startup_fix: + basic=read_json(ROOT/'manifests/startup-white-01.json') + require(sha(new.read('assets/avatar/startup-white-01/manifest.json'))=='461f5cfc10036de5f10ca3ce765fb8d9998697d3fd035aa9b1862d2ccfc3eaa2','bootstrap exact manifest') + require(sha(new.read('assets/avatar/startup-white-01/poster.png'))==basic['posterSha256'],'bootstrap poster SHA') 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,playback_diagnostic=False,playback_clock_fix=False): +def publish(report,output,requested,full=False,runtime_fix=False,playback_diagnostic=False,playback_clock_fix=False,startup_fix=False): require(all(edge.get('nativeLoop') is True or 'mouthRuntimeManifest' in edge for edge in read_json(ROOT/'app/src/main/assets'/ASSET_ROOT/'manifest.json')['edges']), 'live emotion release needs bridge-own TALK runtimes') tested_source(full);packaging_tests_current();require(file_sha(ROLLBACK)==ROLLBACK_SHA,'rollback drift') @@ -305,14 +310,17 @@ def publish(report,output,requested,full=False,runtime_fix=False,playback_diagno if requested is not None: require(requested>=version,'version code occupied');version=requested require(not full or version>=18,'full candidate needs code >=18') + require(not startup_fix or full and version>=22 and report['manifest_sha256']==RUNTIME_FIX_PIN,'startup fix release shape') + if startup_fix: + subprocess.run(['python3',str(ROOT/'scripts/prepare-startup-assets.py'),'--verify-only'],check=True) require(not playback_clock_fix or full and version>=21 and report['manifest_sha256']==RUNTIME_FIX_PIN,'playback clock fix release shape') require(not playback_diagnostic or full and version>=20 and report['manifest_sha256']==RUNTIME_FIX_PIN,'playback diagnostic release shape') require(not runtime_fix or full and version>=19 and report['manifest_sha256']==RUNTIME_FIX_PIN,'runtime fix release shape') subprocess.run([str(ROOT/'scripts/build.sh'),'assembleDebug','compileDebugAndroidTestKotlin','-PavatarActionCandidate=true', '-PavatarNatural=true','-PavatarMouthCandidate=true','-PnaturalManifestSha='+LEGACY_PIN, - '-PemotionManifestSha='+report['manifest_sha256'],'-PactionVersionCode='+str(version),'-PavatarFullActionCandidate='+str(full).lower(),'-PavatarRuntimeFix='+str(runtime_fix).lower(),'-PavatarPlaybackDiagnostic='+str(playback_diagnostic).lower(),'-PavatarPlaybackClockFix='+str(playback_clock_fix).lower()],check=True,cwd=ROOT) + '-PemotionManifestSha='+report['manifest_sha256'],'-PactionVersionCode='+str(version),'-PavatarFullActionCandidate='+str(full).lower(),'-PavatarRuntimeFix='+str(runtime_fix).lower(),'-PavatarPlaybackDiagnostic='+str(playback_diagnostic).lower(),'-PavatarPlaybackClockFix='+str(playback_clock_fix or startup_fix).lower(),'-PavatarStartupFix='+str(startup_fix).lower()],check=True,cwd=ROOT) built=ROOT/'app/build/outputs/apk/debug/app-debug.apk';badge=badging(built) - version_name='0.7.3' if playback_clock_fix else '0.7.2' if playback_diagnostic else '0.7.1' if runtime_fix else ('0.7.0' if full else '0.7.0-emotion-dev') + version_name='0.7.4' if startup_fix else '0.7.3' if playback_clock_fix else '0.7.2' if playback_diagnostic else '0.7.1' if runtime_fix else ('0.7.0' if full else '0.7.0-emotion-dev') for text in ("name='com.gorios.lanvoice'",f"versionCode='{version}'",f"versionName='{version_name}'","sdkVersion:'26'","targetSdkVersion:'34'"): require(text in badge,'APK metadata: '+text) require(re.search(r'^native-code: (.+)$',badge,re.M)[1].strip()=="'arm64-v8a'",'APK ABI') @@ -321,6 +329,7 @@ def publish(report,output,requested,full=False,runtime_fix=False,playback_diagno with zipfile.ZipFile(ROLLBACK) 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('/')} extra={'assets/'+ASSET_ROOT+n for n in report['files']} + if startup_fix: extra|={'assets/avatar/startup-white-01/manifest.json','assets/avatar/startup-white-01/poster.png'} require(paths(new)==paths(old)|extra,'APK unreferenced/missing avatar assets') for name in paths(old): require(new.read(name)==old.read(name),'rollback asset changed') for name,row in report['files'].items(): require(sha(new.read('assets/'+ASSET_ROOT+name))==row['sha256'],'APK pack hash') @@ -328,10 +337,11 @@ def publish(report,output,requested,full=False,runtime_fix=False,playback_diagno if name.endswith('.mp4'): require(new.getinfo(name).compress_type==zipfile.ZIP_STORED,'compressed media') 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') + if startup_fix: require('AVATAR_STARTUP_FIX = true' in config.read_text(),'compiled startup flag mismatch') require(version>=next_version((ROOT/'artifacts').glob('*.apk')),'version became occupied during build') - if runtime_fix or playback_diagnostic or playback_clock_fix: require(verify_runtime_fix_assets(built,report['manifest_sha256'])==len(report['files']),'runtime fix file count') - stem='playback-clock-fix' if playback_clock_fix else 'playback-diagnostic' if playback_diagnostic else 'runtime-fix' if runtime_fix else ('action-emotion' if full else 'emotion-candidate') - release='v073' if playback_clock_fix else 'v072' if playback_diagnostic else 'v071' if runtime_fix else 'v070' + if startup_fix or runtime_fix or playback_diagnostic or playback_clock_fix: require(verify_runtime_fix_assets(built,report['manifest_sha256'],startup_fix)==len(report['files']),'runtime fix file count') + stem='startup-fix' if startup_fix else 'playback-clock-fix' if playback_clock_fix else 'playback-diagnostic' if playback_diagnostic else 'runtime-fix' if runtime_fix else ('action-emotion' if full else 'emotion-candidate') + release='v074' if startup_fix else 'v073' if playback_clock_fix else 'v072' if playback_diagnostic else 'v071' if runtime_fix else 'v070' artifact=ROOT/f'artifacts/lan-voice-{release}-{stem}-code{version}-arm64-debug.apk' with artifact.open('xb') as f,built.open('rb') as source: shutil.copyfileobj(source,f) digest=file_sha(artifact);checksum=f'{digest} {artifact.name}\n'.encode() @@ -343,7 +353,9 @@ def publish(report,output,requested,full=False,runtime_fix=False,playback_diagno require(file_sha(ROLLBACK)==ROLLBACK_SHA,'rollback modified') delivery={'status':'full_action_emotion_candidate' if full else 'partial_emotion_candidate','version_name':version_name,'version_code':version,'url':url,'sha256':digest, 'certificate_sha256':CERT,'manifest_sha256':report['manifest_sha256'],'dance_available':full,'action_count':report['action_count'], - 'http_bytes_verified':True,'device':'not_run','naturalness':'not_certified','paid_calls':0,'gateway_deployed':False,'runtime_fix':runtime_fix,'diagnostic_only':playback_diagnostic,'playback_clock_fix':playback_clock_fix,'runtime_files_unchanged_from_code18':len(report['files']) if runtime_fix or playback_diagnostic or playback_clock_fix else None} + 'http_bytes_verified':True,'device':'not_run','naturalness':'not_certified','paid_calls':0, + 'gateway_deployed':bool(full and read_json(ROOT/'logs/action-emotion/full-release/checks.json').get('gateway_deployed',False)), + 'gateway_deployed_by_packager':False,'runtime_fix':runtime_fix,'diagnostic_only':playback_diagnostic,'playback_clock_fix':playback_clock_fix or startup_fix,'startup_fix':startup_fix,'runtime_files_unchanged_from_code18':len(report['files']) if startup_fix or runtime_fix or playback_diagnostic or playback_clock_fix else None} (output/'delivery.json').write_text(json.dumps(delivery,indent=2)+'\n') return delivery @@ -362,8 +374,9 @@ def main(): parser.add_argument('--runtime-fix',action='store_true',help='0.7.1 Android-only repair; all avatar bytes must equal frozen code18') parser.add_argument('--playback-diagnostic',action='store_true',help='0.7.2 diagnostic-only Android build, frozen code18 avatar bytes') parser.add_argument('--playback-clock-fix',action='store_true',help='0.7.3 Android MediaPlayer-output clock fix; exact frozen avatar bytes') + parser.add_argument('--startup-fix',action='store_true',help='0.7.4 immediate shell/background strict admission, exact frozen runtime plus tiny derived bootstrap') args=parser.parse_args(); - require(sum((args.runtime_fix,args.playback_diagnostic,args.playback_clock_fix))<=1,'choose one build purpose') + require(sum((args.runtime_fix,args.playback_diagnostic,args.playback_clock_fix,args.startup_fix))<=1,'choose one build purpose') manifest=args.manifest.resolve(strict=True);output=args.output.resolve() require(not output.exists() and not output.is_relative_to(manifest.parent),'new evidence outside owner root required') if args.import_only or args.publish: require(args.pi_pin==args.sha256 and re.fullmatch('[0-9a-f]{64}',args.pi_pin or ''),'external Pi pin required') @@ -380,7 +393,7 @@ def main(): require(not args.previous_pin and not args.backup,'previous import report required') import_files(manifest.parent,report['files'],target) (output/'import.json').write_text(json.dumps({'externally_pinned_sha256':args.pi_pin,'files':len(report['files']),'naturalness':'not_certified'})+'\n') - result=publish(report,output,args.version_code,bool(report['action_count']),args.runtime_fix,args.playback_diagnostic,args.playback_clock_fix) 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,args.playback_diagnostic,args.playback_clock_fix,args.startup_fix) if args.publish else {k:v for k,v in report.items() if k!='files'} print(json.dumps(result,indent=2)) diff --git a/scripts/prepare-startup-assets.py b/scripts/prepare-startup-assets.py new file mode 100644 index 0000000..b55b538 --- /dev/null +++ b/scripts/prepare-startup-assets.py @@ -0,0 +1,39 @@ +#!/usr/bin/env python3 +"""Recreate tiny bootstrap from frozen neutral sourceframe0. Free CPU only, no new media. +Portrait outputs are ignored; never commit generated PNG/video. Requires existing ffmpeg/Pillow. +""" +import argparse,hashlib,io,json,subprocess +from pathlib import Path +from PIL import Image +ROOT=Path(__file__).resolve().parents[1] +PIN='987e125a7d7a2cde99121b5f5246c82f4dbe36c4899d3d49eaffd1a68bafb887' +BASIC_SHA='461f5cfc10036de5f10ca3ce765fb8d9998697d3fd035aa9b1862d2ccfc3eaa2' +sha=lambda b:hashlib.sha256(b).hexdigest() + +def prepare(verify_only=False): + archive=ROOT/'manifests/startup-white-01.json';raw=archive.read_bytes();assert sha(raw)==BASIC_SHA + meta=json.loads(raw);assert meta['sourceIndexSha256']==PIN + assets=ROOT/'app/src/main/assets';index=assets/'avatar/a01-expression-action-v1/manifest.json' + assert sha(index.read_bytes())==PIN + body=assets/meta['body']['path'];assert sha(body.read_bytes())==meta['body']['sha256'] + outputs={assets/'avatar/startup-white-01/manifest.json':raw} + poster=assets/'avatar/startup-white-01/poster.png';resource=ROOT/'app/src/main/res/drawable-nodpi/startup_poster.png' + if verify_only: + data=poster.read_bytes();assert sha(data)==meta['posterSha256'];assert resource.read_bytes()==data + else: + native=subprocess.check_output(['/home/ubuntu/gori-bin/ffmpeg','-v','error','-i',str(body),'-frames:v','1','-f','image2pipe','-vcodec','png','-'],timeout=30) + image=Image.open(io.BytesIO(native)).convert('RGB').resize((240,424),Image.Resampling.LANCZOS) + out=io.BytesIO();image.save(out,format='PNG',optimize=True);data=out.getvalue() + assert sha(data)==meta['posterSha256'],'Deterministic poster changed; do not invent a new pin' + outputs[poster]=data;outputs[resource]=data + poster_bytes=len(data) + for path,data in outputs.items(): + if verify_only: assert path.read_bytes()==data + else: + path.parent.mkdir(parents=True,exist_ok=True) + if path.exists():assert path.read_bytes()==data,'Refuse unknown bootstrap overwrite' + else:path.write_bytes(data) + return {'status':'passed','index_sha256':PIN,'bootstrap_sha256':BASIC_SHA,'new_avatar_files':2,'poster_bytes':poster_bytes,'width':240,'height':424,'paid_calls':0} +if __name__=='__main__': + parser=argparse.ArgumentParser(description=__doc__);parser.add_argument('--verify-only',action='store_true') + print(json.dumps(prepare(parser.parse_args().verify_only),indent=2)) diff --git a/scripts/probe-startup-capabilities.py b/scripts/probe-startup-capabilities.py new file mode 100644 index 0000000..a29afad --- /dev/null +++ b/scripts/probe-startup-capabilities.py @@ -0,0 +1,76 @@ +#!/usr/bin/env python3 +"""Finite model-free WS route replay of canonical deployed source in isolated localhost. +No live phone/session/history, no inference, no fake pack approvals or live configuration. +""" +import json,subprocess +from pathlib import Path +ROOT=Path(__file__).resolve().parents[1] +REMOTE=r''' +import asyncio,contextlib,inspect,json,secrets,socket,tempfile,hashlib,sys +from pathlib import Path +root=Path('/home/gorios-spark-2/lan-voice') +for name,digest in expected.items():assert hashlib.sha256((root/name).read_bytes()).hexdigest()==digest +import shutil +stage_dir=tempfile.TemporaryDirectory(prefix='startup-canonical-source-') +stage=Path(stage_dir.name) +for path in root.glob('*.py'):shutil.copy2(path,stage/path.name) +shutil.copy2(root/'reviewed_action_packs.json',stage/'reviewed_action_packs.json') +(stage/'web').mkdir();sys.path.insert(0,str(stage)) +import gateway as g +import uvicorn,websockets,httpx +from history import History +from guest_sessions import GuestSessions +from tests_fake import FakeModel +from action_protocol import configured_packs +pin='987e125a7d7a2cde99121b5f5246c82f4dbe36c4899d3d49eaffd1a68bafb887' +assert configured_packs()[pin]=={'asset_01':10042,'asset_02':10042} +async def main(): + with tempfile.TemporaryDirectory(prefix='startup-capabilities-probe-') as directory: + history=History(Path(directory)/'public-empty.sqlite3');await history.initialize() + token=secrets.token_urlsafe(32) + async with httpx.AsyncClient(transport=httpx.MockTransport(lambda req: (_ for _ in ()).throw(AssertionError('no_inference_allowed')))) as client: + state=g.app.state + state.busy=False;state.model=FakeModel();state.client=client;state.history=history + state.token=token;state.guest_enabled=False;state.lan_open=False;state.guests=GuestSessions();state.debug=None + state.voices=[{'id':g.DEFAULT_VOICE_ID,'source':'registered_reference','default':True}] + server=uvicorn.Server(uvicorn.Config(g.app,host='127.0.0.1',port=0,lifespan='off',log_level='critical',access_log=False)) + sock=socket.socket();sock.bind(('127.0.0.1',0));sock.listen();sock.setblocking(False);port=sock.getsockname()[1] + task=asyncio.create_task(server.serve(sockets=[sock]));rows=[] + try: + async with asyncio.timeout(5): + while not server.started:await asyncio.sleep(.01) + kwargs={'origin':'https://192.168.31.61:5011','open_timeout':3,'close_timeout':1} + if 'proxy' in inspect.signature(websockets.connect).parameters:kwargs['proxy']=None + for kind,offer in [('pending',{'action_protocol':1,'action_kinds':[],'action_pending_pack_sha256':pin}),('legacy',{}),('unknown',{'action_protocol':1,'action_kinds':[],'action_pending_pack_sha256':'b'*64})]: + async with websockets.connect(f'ws://127.0.0.1:{port}/ws/dialogue',**kwargs) as ws: + await ws.send(json.dumps({'type':'auth','token':token}));assert json.loads(await ws.recv())['type']=='auth' + await ws.send(json.dumps({'type':'hello','codec':'pcm16','sample_rate':16000,'frame_duration':20,'persona':'default','tts_debug':False,**offer})) + hello=json.loads(await ws.recv());assert hello['type']=='hello' and not hello['action_available'] + assert hello['action_pending']==(kind=='pending') + async def update(value): + await ws.send(json.dumps({'type':'client.capabilities.ready','action_protocol':1,'action_kinds':['dance'],'action_pack_sha256':value})) + async with asyncio.timeout(3): + while True: + event=json.loads(await ws.recv()) + if event['type']=='client.capabilities':return event['action_available'],event['turn_id'] + assert event['type']=='history' # Isolated empty history; never saved or printed. + denied=await update('b'*64);accepted=await update(pin);duplicate=await update(pin) + assert not denied[0] and accepted[0]==(kind=='pending') and duplicate==accepted + rows.append({'offer':kind,'hello_available':False,'pending':hello['action_pending'],'ready_available':accepted[0],'duplicate_turn_unchanged':duplicate[1]==hello['turn_id']}) + async with asyncio.timeout(3): + while state.busy:await asyncio.sleep(.01) + finally: + server.should_exit=True;await task + return {'status':'passed','scope':'canonical source isolated actual WS routes; no live session','rows':rows,'connections':3,'model_calls':0,'asr_calls':0,'tts_calls':0,'device':'not_run'} +print(json.dumps(asyncio.run(main()))) +stage_dir.cleanup() +''' +def main(): + expected=json.loads((ROOT/'gateway/SOURCE_MANIFEST.json').read_text())['deployment_baseline']['files'] + payload='expected='+repr(expected)+'\n'+REMOTE + result=subprocess.run(['ssh','-o','BatchMode=yes','-o','ConnectTimeout=5','gorios-spark-2@192.168.31.61','cd /home/gorios-spark-2/lan-voice && exec .venv/bin/python -'],input=payload.encode(),capture_output=True,timeout=25) + if result.returncode: + print('FAIL: isolated capability probe; remote exception suppressed, no live changes');raise SystemExit(1) + report=json.loads(result.stdout);output=ROOT/'logs/action-emotion/startup-074/capability-ws.json' + output.parent.mkdir(parents=True,exist_ok=True);output.write_text(json.dumps(report,indent=2)+'\n');print(json.dumps(report,indent=2)) +if __name__=='__main__':main() diff --git a/tests/avatar/AndroidLog.kt b/tests/avatar/AndroidLog.kt new file mode 100644 index 0000000..17fa5b4 --- /dev/null +++ b/tests/avatar/AndroidLog.kt @@ -0,0 +1,2 @@ +package android.util +object Log { fun i(tag: String,message: String)=0 } diff --git a/tests/avatar/AvatarCheck.kt b/tests/avatar/AvatarCheck.kt index efb3fa2..4c15417 100644 --- a/tests/avatar/AvatarCheck.kt +++ b/tests/avatar/AvatarCheck.kt @@ -6,6 +6,8 @@ import android.media.MediaPlayer import android.view.TextureView fun main() { + startupCacheCheck() + startupViewCheck() reportedActionClockCheck() playbackDiagnosticCheck() boundedRuntimeDiagnosticCheck() diff --git a/tests/avatar/PlaybackDiagnosticCheck.kt b/tests/avatar/PlaybackDiagnosticCheck.kt index 0521b61..8e8da1f 100644 --- a/tests/avatar/PlaybackDiagnosticCheck.kt +++ b/tests/avatar/PlaybackDiagnosticCheck.kt @@ -83,7 +83,7 @@ fun playbackDiagnosticCheck() { index.packages.values.forEach { android.media.CodecFixture.timelines[it.root+it.body.path]=it.body.ptsUs } index.edges.mapNotNull { it.mouthRuntime }.forEach { android.media.CodecFixture.timelines[it.root+it.body.path]=it.body.ptsUs } index.actionPack?.assets?.mapNotNull { it.media }?.forEach { android.media.CodecFixture.timelines[it.root+it.path]=it.ptsUs;android.media.CodecFixture.audioPaths.add(it.root+it.path) } - val binding=AvatarMediaBinding();val view=EmotionActionAvatarView(android.content.Context(),AvatarPack(fallback="fixture.png",emotionAction=index),binding) {} + val binding=AvatarMediaBinding();val view=EmotionActionAvatarView(android.content.Context(),AvatarPack(fallback="fixture.png",emotionAction=index),binding,{}) view.render(true);TestScheduler.advanceBy(1) val local=OfflineDancePreview(index.actionPack,binding,{TestScheduler.now}) check(local.play(id));assertions++ diff --git a/tests/avatar/Resources.kt b/tests/avatar/Resources.kt new file mode 100644 index 0000000..6a9d922 --- /dev/null +++ b/tests/avatar/Resources.kt @@ -0,0 +1,2 @@ +package com.gorios.lanvoice +object R { object drawable { const val startup_poster=1 } } diff --git a/tests/avatar/StartupCheck.kt b/tests/avatar/StartupCheck.kt new file mode 100644 index 0000000..e8817c4 --- /dev/null +++ b/tests/avatar/StartupCheck.kt @@ -0,0 +1,68 @@ +import com.gorios.lanvoice.avatar.* +import android.os.TestScheduler +import android.media.CodecFixture +import java.util.concurrent.CountDownLatch +import java.util.concurrent.TimeUnit + +fun startupCacheCheck() { + fun key(version: Long=22,install: Long=1,pin: String="a".repeat(64),validator: Int=1)=StartupAssetKey(version,install,pin,"avatar/a01-expression-action-v1/",validator) + val worker=java.util.concurrent.Executors.newSingleThreadExecutor() + try { + val cache=StartupLoadCache(worker);val entered=CountDownLatch(1);val release=CountDownLatch(1);val done=CountDownLatch(2) + var calls=0;var cancelledCalled=false + val cancel=cache.request(key(),{ calls++;entered.countDown();check(release.await(2,TimeUnit.SECONDS));"verified" },{ cancelledCalled=true }) + check(entered.await(2,TimeUnit.SECONDS)) + repeat(2) { cache.request(key(),{ error("duplicate verification") },{ check(it.getOrThrow()=="verified");done.countDown() }) } + cancel();release.countDown();check(done.await(2,TimeUnit.SECONDS));check(!cancelledCalled && calls==1) + var hits=0;cache.request(key(),{ error("repeated cached read") },{ check(it.getOrThrow()=="verified") },{hits++});check(hits==1) + val failed=CountDownLatch(1);cache.request(key(version=23),{error("invalid assets")},{check(it.isFailure);failed.countDown()});check(failed.await(2,TimeUnit.SECONDS)) + val retry=CountDownLatch(1);cache.request(key(version=23),{"retryverified"},{check(it.getOrThrow()=="retryverified");retry.countDown()});check(retry.await(2,TimeUnit.SECONDS)) + val folder=java.nio.file.Files.createTempDirectory("avatar-receipt-test").toFile() + try { + val receipt=BundledValidationReceipt(folder);check(!receipt.contains(key()));receipt.complete(key());check(receipt.contains(key())) + for(changed in listOf(key(version=23),key(install=2),key(pin="b".repeat(64)),key(validator=2))) check(!receipt.contains(changed)) + java.io.File(folder,key().fingerprint+".complete").writeText("partial");check(!receipt.contains(key())) + receipt.complete(key());java.io.File(folder,"incomplete.tmp").writeText("complete");check(receipt.contains(key())) + receipt.complete(key(install=2));check(!receipt.contains(key()) && receipt.contains(key(install=2))) + } finally { folder.deleteRecursively() } + } finally { worker.shutdownNow() } + println("PASS: production startup shared-future concurrency/cancel/cache/failure-retry and atomic immutable APK receipt corruption/install/pin/version/validator invalidation") +} + +fun startupViewCheck() { + var cases=0 + fun rig(): Triple { + TestScheduler.reset();CodecFixture.reset();CodecFixture.emitNativeSurface=true + val index=mediaFixtureIndex();val neutral=index.packages.getValue(index.fallbackId) + index.packages.values.forEach { CodecFixture.timelines[it.root+it.body.path]=it.body.ptsUs } + index.edges.mapNotNull {it.mouthRuntime}.forEach {CodecFixture.timelines[it.root+it.body.path]=it.body.ptsUs} + return Triple(StartupAvatarView(android.content.Context(),AvatarMediaBinding(),{},{}),neutral.copy(patches=emptyList(),curves=emptyMap()),AvatarPack(fallback="fixture.png",emotionAction=index)) + } + var visible=0 + val (unused,base,pack)=rig();unused.dispose() + val view=StartupAvatarView(android.content.Context(),AvatarMediaBinding(),{},{visible++}) + view.update(base,null,true);TestScheduler.advanceBy(250);check(visible==0);cases++ + view.update(base,pack,true);TestScheduler.advanceBy(250);check(visible==0);cases++ // targetready is not sufficient: source actual0 required + TestScheduler.until(6000) { visible==1 };check(CodecFixture.releases>=1);cases++ + val full=view.children.last() as EmotionActionAvatarView + check(full.alpha==1f && view.children.filterIsInstance().single().alpha==0f);cases++ + view.update(base,pack,true);TestScheduler.advanceBy(100);check(visible==1);cases++ + view.update(base,pack,false);TestScheduler.advanceBy(100);view.update(base,pack,true);TestScheduler.advanceBy(100);check(visible==1);cases++ + view.dispose();TestScheduler.advanceBy(300);check(visible==1);cases++ + val (background,b2,p2)=rig();background.update(b2,p2,true);background.update(b2,p2,false);TestScheduler.advanceBy(200) + check((background.children.last() as EmotionActionAvatarView).alpha==0f);cases++ + background.update(b2,p2,true);TestScheduler.advanceBy(4500);check((background.children.last() as EmotionActionAvatarView).alpha==1f);cases++ + background.dispose();TestScheduler.advanceBy(100) + val (bad,b3,p3)=rig();val index=p3.emotionAction!! + val wrong=index.copy(packages=index.packages+ (index.fallbackId to index.packages.getValue(index.fallbackId).copy(body=index.packages.getValue(index.fallbackId).body.copy(sha256="b".repeat(64))))) + check(runCatching { bad.update(b3,p3.copy(emotionAction=wrong),true) }.isFailure);bad.dispose();cases++ + val (prototype,b4,p4)=rig();prototype.dispose();var failures=0;var recovered=0 + val retrying=StartupAvatarView(android.content.Context(),AvatarMediaBinding(),{},{recovered++},{failures++}) + retrying.update(b4,null,true,"preparing");TestScheduler.advanceBy(100) + CodecFixture.configureFails=true;retrying.update(b4,p4,true,"preparing");TestScheduler.advanceBy(100) + check(failures==1 && recovered==0 && (retrying.children.last() as EmotionActionAvatarView).alpha==0f) { "failure_count=$failures recovered=$recovered" };cases++ + retrying.update(b4,p4,true,"failed");CodecFixture.configureFails=false + retrying.update(b4,p4,true,"preparing");TestScheduler.until(6000) { recovered==1 };cases++ + retrying.dispose();TestScheduler.advanceBy(100) + println("PASS: $cases production startup host renderer callback cases: held exact target0/source0, decoderrelease before capability, persistent host, lifecycle and bodySHA mismatch") +} diff --git a/tests/avatar/Widget.kt b/tests/avatar/Widget.kt index 3488968..b8e1999 100644 --- a/tests/avatar/Widget.kt +++ b/tests/avatar/Widget.kt @@ -1,14 +1,17 @@ package android.widget import android.content.Context open class FrameLayout(val context: Context) { + var alpha=1f class LayoutParams(w: Int,h: Int) val children = mutableListOf() + fun removeView(view: Any) { children.remove(view) } fun addView(view: Any, params: LayoutParams) { children.add(view) } open fun onDetachedFromWindow() {} } class ImageView(context: Context) { enum class ScaleType { FIT_CENTER } var scaleType = ScaleType.FIT_CENTER; var alpha = 1f + fun setImageResource(id: Int) {} fun setImageBitmap(bitmap: Any?) {} fun setImageDrawable(drawable: Any?) {} } diff --git a/tests/packaging/test_startup_package.py b/tests/packaging/test_startup_package.py new file mode 100644 index 0000000..e73b8dd --- /dev/null +++ b/tests/packaging/test_startup_package.py @@ -0,0 +1,29 @@ +"""Only bootstrap's exact pinned additions may differ from frozen code18 avatar bytes.""" +import hashlib,importlib.util,tempfile,unittest,zipfile +from pathlib import Path +from unittest.mock import patch +ROOT=Path(__file__).resolve().parents[2] +spec=importlib.util.spec_from_file_location('startup_package',ROOT/'scripts/package-avatar-emotion.py') +pack=importlib.util.module_from_spec(spec);spec.loader.exec_module(pack) + +class StartupPackageTests(unittest.TestCase): + def test_bootstrap_additions_and_no_old_asset_drift(self): + with tempfile.TemporaryDirectory() as folder: + old=Path(folder)/'old.apk';new=Path(folder)/'new.apk' + files={'assets/'+pack.ASSET_ROOT+'manifest.json':(ROOT/'app/src/main/assets'/pack.ASSET_ROOT/'manifest.json').read_bytes(), + 'assets/'+pack.ASSET_ROOT+'fixture.png':b'old-immutable-patch'} + additions={'assets/avatar/startup-white-01/'+name:(ROOT/'app/src/main/assets/avatar/startup-white-01'/name).read_bytes() for name in ('manifest.json','poster.png')} + def write(path,rows): + with zipfile.ZipFile(path,'w') as z: + for name,data in rows.items():z.writestr(name,data) + write(old,files) + with patch.object(pack,'CODE18',old),patch.object(pack,'CODE18_SHA',hashlib.sha256(old.read_bytes()).hexdigest()): + write(new,{**files,**additions});self.assertEqual(pack.verify_runtime_fix_assets(new,pack.RUNTIME_FIX_PIN,True),2) + for change in ({'assets/avatar/unapproved.png':b'newportrait'}, + {next(n for n in files if n.endswith('.png')):b'changed-mouth'}, + {'assets/avatar/startup-white-01/poster.png':b'changed-poster'}): + with self.subTest(change=list(change)): + write(new,{**files,**additions,**change}) + with self.assertRaises(ValueError):pack.verify_runtime_fix_assets(new,pack.RUNTIME_FIX_PIN,True) + write(new,{**files,**additions}) + with self.assertRaises(ValueError):pack.verify_runtime_fix_assets(new,pack.RUNTIME_FIX_PIN,False) diff --git a/tests/protocol/ProtocolCheck.kt b/tests/protocol/ProtocolCheck.kt index 2f2d52d..6644b0e 100644 --- a/tests/protocol/ProtocolCheck.kt +++ b/tests/protocol/ProtocolCheck.kt @@ -1,6 +1,10 @@ import com.gorios.lanvoice.net.DialogueProtocol fun main() { + val pending=DialogueProtocol.hello(null,"a".repeat(64)) + check("action_pending_pack_sha256" in pending && "dance" !in pending) + val update=DialogueProtocol.capabilitiesReady("a".repeat(64)) + check("client.capabilities.ready" in update && "dance" in update) // Partial expression packs provide no reviewed action pack; no dance in HELLO. for (pin in listOf(null,"","unknown","a".repeat(63))) { val hello=DialogueProtocol.hello(pin) diff --git a/tests/session/AndroidLog.kt b/tests/session/AndroidLog.kt index 80b58a5..12ee01b 100644 --- a/tests/session/AndroidLog.kt +++ b/tests/session/AndroidLog.kt @@ -1,5 +1,6 @@ package android.util object Log { + @JvmStatic fun i(tag: String,message: String)=0 @JvmStatic fun getStackTraceString(error: Throwable) = error.stackTraceToString() @JvmStatic fun w(tag: String, message: String) = 0 @JvmStatic fun w(tag: String, message: String, error: Throwable) = 0 diff --git a/tests/session/ConnectionCheck.kt b/tests/session/ConnectionCheck.kt index de3ac15..3389338 100644 --- a/tests/session/ConnectionCheck.kt +++ b/tests/session/ConnectionCheck.kt @@ -490,6 +490,7 @@ fun runChecks() { } fun main() { + startupCapabilityCheck() checkCallControls() checkFaceTransmission() run { diff --git a/tests/session/ProtocolEvents.kt b/tests/session/ProtocolEvents.kt index 95d7710..289fd3c 100644 --- a/tests/session/ProtocolEvents.kt +++ b/tests/session/ProtocolEvents.kt @@ -3,19 +3,20 @@ package com.gorios.lanvoice.net // Event doubles isolate DialogueClient callback ordering from the unchanged JSON parser. // Production DialogueProtocol/JSONObject were compiled separately with actual dependencies. class Payload(private val ok: Boolean = true, private val turn: Long? = null, private val state: String = "", private val reason: String = "", private val fields: Map = emptyMap()) { - fun optBoolean(key: String, fallback: Boolean) = if (key == "ok") ok else fallback + fun optBoolean(key: String, fallback: Boolean) = if (key == "ok") ok else fields[key] as? Boolean ?: fallback fun optString(key: String, fallback: String = "") = when (key) { "state" -> state; "reason" -> reason; else -> fields[key] as? String ?: fallback } fun optInt(key: String, fallback: Int) = if (key == "context_face_cue_version") 1 else fallback fun opt(key: String): Any? = if (key == "turn_id") turn else fields[key] } -enum class EventKind { AUTH, HELLO, ERROR, HISTORY, UNKNOWN, LISTEN, VAD, STT, LLM, TTS, ABORT, REPLY_EMOTION, EXPRESSION_PREPARE, ACTION, SPEECH } +enum class EventKind { AUTH, HELLO, ERROR, HISTORY, UNKNOWN, LISTEN, VAD, STT, LLM, TTS, ABORT, REPLY_EMOTION, EXPRESSION_PREPARE, ACTION, CAPABILITIES, SPEECH } data class ServerEvent(val type: String, val kind: EventKind, val payload: Payload) class DownlinkFrame(val turnId: Long = 0, val sequence: Long = 0, val pcm16: ByteArray = ByteArray(2)) object DialogueProtocol { val uplinks = mutableListOf>() fun actionStatus(value: com.gorios.lanvoice.avatar.ActionStatus) = "action_status" fun faceCue(turn: Long, observation: com.gorios.lanvoice.expression.FaceCueObservation, age: Long) = "face_cue" - fun hello(actionPackSha: String? = null) = "hello" + fun hello(actionPackSha: String? = null,pendingPackSha: String?=null) = "hello" + fun capabilitiesReady(pin: String) = "capabilities_ready" fun listen(start: Boolean) = "listen" fun abort(turn: Long) = "abort" fun playbackDrained(turn: Long) = "drained" @@ -24,6 +25,9 @@ object DialogueProtocol { fun parseEvent(text: String) = when (text) { "auth" -> ServerEvent("auth", EventKind.AUTH, Payload()) "auth failed" -> ServerEvent("auth", EventKind.AUTH, Payload(false)) + "hello pending" -> ServerEvent("hello",EventKind.HELLO,Payload(fields=mapOf("action_available" to false,"action_pending" to true))) + "cap accepted" -> ServerEvent("client.capabilities",EventKind.CAPABILITIES,Payload(fields=mapOf("action_available" to true,"action_pack_sha256" to "a".repeat(64)))) + "cap wrong" -> ServerEvent("client.capabilities",EventKind.CAPABILITIES,Payload(fields=mapOf("action_available" to true,"action_pack_sha256" to "b".repeat(64)))) "hello available" -> ServerEvent("hello", EventKind.HELLO, Payload(fields=mapOf("action_available" to true))) "hello unavailable" -> ServerEvent("hello", EventKind.HELLO, Payload(fields=mapOf("action_available" to false))) "hello" -> ServerEvent("hello", EventKind.HELLO, Payload()) diff --git a/tests/session/StartupCapabilityCheck.kt b/tests/session/StartupCapabilityCheck.kt new file mode 100644 index 0000000..3b73ba6 --- /dev/null +++ b/tests/session/StartupCapabilityCheck.kt @@ -0,0 +1,27 @@ +import android.os.Handler +import com.gorios.lanvoice.net.* + +fun startupCapabilityCheck() { + var installed: String?=null + val client=DialogueClient("localhost",5011,{},actionPackSha={installed},pendingActionPackSha={"a".repeat(64)}) + val socket=FakeSocket();client.setField("socket",socket);val listener=client.callbacks(0) + fun event(value: String) { listener.onMessage(socket,value);Handler.drain() } + event("auth");event("hello pending") + check(client.actionNegotiation=="pending_pack" && !client.capabilitiesReady()) + installed="a".repeat(64);check(client.capabilitiesReady());check(!client.capabilitiesReady()) + check(socket.sent.count { it=="capabilities_ready" }==1) + event("cap wrong");check(client.actionNegotiation=="pending_pack") + event("cap accepted");check(client.actionNegotiation=="accepted") + client.disconnect();event("cap accepted");check(client.actionNegotiation=="disconnected") + client.release();Handler.drain() + val legacy=DialogueClient("localhost",5011,{},actionPackSha={"a".repeat(64)}) + val old=FakeSocket();legacy.setField("socket",old) + val callbacks=legacy.callbacks(0);callbacks.onMessage(old,"auth");Handler.drain();callbacks.onMessage(old,"hello unavailable");Handler.drain() + check(!legacy.capabilitiesReady());legacy.release();Handler.drain() + val failing=DialogueClient("localhost",5011,{},actionPackSha={installed},pendingActionPackSha={"a".repeat(64)}) + installed=null;val broken=FakeSocket();failing.setField("socket",broken);val cb=failing.callbacks(0) + cb.onMessage(broken,"auth");Handler.drain();cb.onMessage(broken,"hello pending");Handler.drain() + installed="a".repeat(64);broken.acceptSend=false;check(!failing.capabilitiesReady()) + check(failing.actionNegotiation=="disconnected" && broken.cancelled);failing.release();Handler.drain() + println("PASS: production DialogueClient pending/ready capability callback, exactpin, once, stale socket and legacy gates; no turn reset/reconnect") +}