diff --git a/app/build.gradle b/app/build.gradle index 45a5d2f..6dd2b8e 100644 --- a/app/build.gradle +++ b/app/build.gradle @@ -45,8 +45,8 @@ android { applicationId 'com.gorios.lanvoice' minSdk 26 targetSdk 34 - versionCode 9 - versionName '0.5.1' + versionCode 10 + versionName '0.5.2' ndk { abiFilters 'arm64-v8a' } } compileOptions { sourceCompatibility JavaVersion.VERSION_17; targetCompatibility JavaVersion.VERSION_17 } diff --git a/app/src/main/java/com/gorios/lanvoice/MainActivity.kt b/app/src/main/java/com/gorios/lanvoice/MainActivity.kt index 44fcbbb..62a14b7 100644 --- a/app/src/main/java/com/gorios/lanvoice/MainActivity.kt +++ b/app/src/main/java/com/gorios/lanvoice/MainActivity.kt @@ -124,6 +124,8 @@ class MainActivity : ComponentActivity() { cameraStatus = expressionState.status, cameraPermissionPending = cameraGate.permissionPending, faceSharing = shareFace, + cameraAnalysis = expressions.diagnosticsSnapshot(), + faceTransmission = session.faceDiagnosticsSnapshot(), rolePlaying = state.phase == VoicePhase.ANSWERING, role = state.replyEmotion.takeIf { it.turnId != null }, previousRole = state.previousReplyEmotion, 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 2c83b8b..9fde2b9 100644 --- a/app/src/main/java/com/gorios/lanvoice/audio/VoiceSession.kt +++ b/app/src/main/java/com/gorios/lanvoice/audio/VoiceSession.kt @@ -14,6 +14,9 @@ import com.gorios.lanvoice.net.EventKind import com.gorios.lanvoice.net.ServerEvent import com.gorios.lanvoice.expression.FaceCue import com.gorios.lanvoice.expression.FaceCueObservation +import com.gorios.lanvoice.expression.FaceCueReason +import com.gorios.lanvoice.expression.FaceSendReason +import com.gorios.lanvoice.expression.FaceTransmissionDiagnostics enum class VoicePhase { IDLE, LISTENING, RECOGNIZING, THINKING, ANSWERING } @@ -59,15 +62,11 @@ class VoiceSession( private var faceSupported = false private var faceCue = FaceCueObservation() private var faceSent = false + private val faceDiagnostics = FaceTransmissionDiagnostics() private val faceTick = object : Runnable { override fun run() { if (!faceSharing || released) return - if (isActive() && faceSupported && hasTurn) { - val age = SystemClock.elapsedRealtime() - faceCue.observedAtMs - if (dialogue.sendFaceCue(currentTurn, faceCue, age)) { - faceSent = faceCue.cue != FaceCue.UNKNOWN && age in 0..3_000 - } - } + sendFaceContext() main.postDelayed(this, 1_000L) } } @@ -215,6 +214,8 @@ class VoiceSession( main.removeCallbacks(faceTick) if (!enabled) clearFaceContext() faceSharing = enabled + diagnostic("face sharing enabled=$enabled") + if (!enabled) faceDiagnostics.record(FaceSendReason.SHARING_OFF) if (enabled && !released) main.post(faceTick) } @@ -224,12 +225,42 @@ class VoiceSession( faceCue = observation } - private fun clearFaceContext() { + private fun clearFaceContext(clearObservation: Boolean = true) { if (faceSent && faceSupported && state.connection == ConnectionStatus.CONNECTED && hasTurn) { - dialogue.sendFaceCue(currentTurn, FaceCueObservation(), 0) + val sent = dialogue.sendFaceCue(currentTurn, FaceCueObservation(), 0) + faceDiagnostics.record(if (sent) FaceSendReason.CLEARED else FaceSendReason.CLEAR_FAILED) } faceSent = false - faceCue = FaceCueObservation() + if (clearObservation) faceCue = FaceCueObservation() + } + + fun faceDiagnosticsSnapshot() = faceDiagnostics.snapshot() + + private fun sendFaceContext() { + val now = SystemClock.elapsedRealtime() + val age = now - faceCue.observedAtMs + val reason = when { + !faceSharing -> FaceSendReason.SHARING_OFF + !foreground -> FaceSendReason.BACKGROUND + state.connection != ConnectionStatus.CONNECTED -> FaceSendReason.NOT_CONNECTED + !state.voiceActive -> FaceSendReason.VOICE_INACTIVE + !faceSupported -> FaceSendReason.UNSUPPORTED + !hasTurn -> FaceSendReason.NO_TURN + faceCue.cue == FaceCue.UNKNOWN -> if (faceCue.reason == FaceCueReason.NO_FACE) FaceSendReason.NO_FACE else FaceSendReason.NO_STABLE_CUE + age !in 0..3_000 -> FaceSendReason.STALE + !faceCue.intensity.isFinite() || faceCue.intensity !in .5f..1f || faceCue.durationMs !in 800..10_000 -> FaceSendReason.INVALID_CUE + else -> null + } + if (reason != null) { + // Send a one-shot clear for a previously published observation; no repeated unknown controls. + if (reason in setOf(FaceSendReason.STALE, FaceSendReason.INVALID_CUE, FaceSendReason.NO_FACE, FaceSendReason.NO_STABLE_CUE)) clearFaceContext(clearObservation = false) + faceDiagnostics.record(reason) + } else { + val sent = dialogue.sendFaceCue(currentTurn, faceCue, age) + if (sent) faceSent = true + faceDiagnostics.record(if (sent) FaceSendReason.SENT else FaceSendReason.SEND_FAILED, faceCue.cue) + } + faceDiagnostics.summary(now)?.let { diagnostic(it) } } private fun onConnection(connection: ConnectionStatus, reason: String) { diff --git a/app/src/main/java/com/gorios/lanvoice/diag/DiagnosticReportUpload.kt b/app/src/main/java/com/gorios/lanvoice/diag/DiagnosticReportUpload.kt index 9a06509..fd158da 100644 --- a/app/src/main/java/com/gorios/lanvoice/diag/DiagnosticReportUpload.kt +++ b/app/src/main/java/com/gorios/lanvoice/diag/DiagnosticReportUpload.kt @@ -2,6 +2,8 @@ package com.gorios.lanvoice.diag import com.gorios.lanvoice.dialogue.ReplyEmotion import com.gorios.lanvoice.expression.ExpressionStatus +import com.gorios.lanvoice.expression.CameraAnalysisSnapshot +import com.gorios.lanvoice.expression.FaceTransmissionSnapshot import okhttp3.Call import okhttp3.Callback import okhttp3.ConnectionPool @@ -35,6 +37,8 @@ data class DiagnosticReportInfo( val rolePlaying: Boolean = false, val role: ReplyEmotion? = null, val previousRole: ReplyEmotion? = null, + val cameraAnalysis: CameraAnalysisSnapshot = CameraAnalysisSnapshot(), + val faceTransmission: FaceTransmissionSnapshot = FaceTransmissionSnapshot(), ) /** Explicit user submission, isolated from both voice traffic and per-entry debug uploads. */ @@ -94,6 +98,15 @@ object DiagnosticReportUpload { .put("role_playing", info.rolePlaying) .put("role_active", roleMetadata(info.role)) .put("role_previous", roleMetadata(info.previousRole)) + .put("camera_analysis", JSONObject().put("received", info.cameraAnalysis.received) + .put("processed", info.cameraAnalysis.processed).put("failures", info.cameraAnalysis.failures) + .put("faces", info.cameraAnalysis.faceCount).put("cue", info.cameraAnalysis.cue.wire) + .put("reason", info.cameraAnalysis.reason.name.lowercase()).put("failure", info.cameraAnalysis.failure.name.lowercase()) + .put("last_process_ms", info.cameraAnalysis.lastProcessMs)) + .put("face_transmission", JSONObject().put("attempts", info.faceTransmission.attempts) + .put("sent", info.faceTransmission.sent).put("clears", info.faceTransmission.clears) + .put("failures", info.faceTransmission.failures).put("reason", info.faceTransmission.reason.name.lowercase()) + .put("cue", info.faceTransmission.cue.wire)) .put("logs", logs) .toString().toRequestBody(json) client.newCall(Request.Builder().url(ENDPOINT).post(body).build()).enqueue(object : Callback { 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 078265e..b49ee73 100644 --- a/app/src/main/java/com/gorios/lanvoice/expression/ExpressionController.kt +++ b/app/src/main/java/com/gorios/lanvoice/expression/ExpressionController.kt @@ -37,6 +37,7 @@ class ExpressionController( } val rules = ExpressionRules() val faceRules = FaceCueRules() + val diagnostics = CameraAnalysisDiagnostics() 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. @@ -49,6 +50,16 @@ class ExpressionController( private val main = Handler(Looper.getMainLooper()) private var current: Run? = null private var released = false + private var lastDiagnostics = CameraAnalysisDiagnostics() + private val diagnosticTick = object : Runnable { + override fun run() { + val run = current ?: return + run.diagnostics.summary(SystemClock.elapsedRealtime())?.let { DebugLogUpload.log("audio", it) } + main.postDelayed(this, 10_000) + } + } + + fun diagnosticsSnapshot(): CameraAnalysisSnapshot = lastDiagnostics.snapshot() /** Called only after an explicit user toggle and CAMERA permission approval. */ fun start() { @@ -60,6 +71,8 @@ class ExpressionController( } val run = Run() current = run + lastDiagnostics = run.diagnostics + main.post(diagnosticTick) onState(ExpressionUiState(ExpressionStatus.STARTING)) // Model loading and all synchronous VIDEO inference stay off the UI/audio threads. run.executor.execute { @@ -148,6 +161,7 @@ class ExpressionController( var bitmap: Bitmap? = null try { if (!run.active) return + run.diagnostics.received() val now = SystemClock.elapsedRealtime() if (run.lastSampleMs != Long.MIN_VALUE && now - run.lastSampleMs < SAMPLE_INTERVAL_MS) return run.lastSampleMs = now @@ -158,7 +172,10 @@ class ExpressionController( run.landmarker?.detectForVideo(mpImage, now) } finally { mpImage.close() - } ?: return + } ?: kotlin.run { + run.diagnostics.failed(CameraFailure.NO_RESULT) + return + } if (!run.active) return val observation = if (result.faceLandmarks().isEmpty()) null else { val categories = result.faceBlendshapes().orElse(emptyList()).firstOrNull().orEmpty() @@ -176,6 +193,7 @@ class ExpressionController( (landmarks.maxOf { it.x() } - landmarks.minOf { it.x() }) * (landmarks.maxOf { it.y() } - landmarks.minOf { it.y() }) >= .06f val faceCue = run.faceRules.evaluate(observation, result.faceLandmarks().size, quality, now) + run.diagnostics.processed(result.faceLandmarks().size, faceCue, SystemClock.elapsedRealtime() - now) main.post { if (isCurrent(run)) onFaceCue(faceCue) } // UI receives only <=2 enum labels; 52 coefficients, pose and images stay transient. if (run.lastPublished != visible || run.lastStableCue != faceCue.cue) { @@ -197,6 +215,7 @@ class ExpressionController( } private fun fail(run: Run, guidance: String, reason: String) { + run.diagnostics.failed(CameraFailure.entries.firstOrNull { it.name.lowercase() == reason } ?: CameraFailure.ANALYSIS) // Prevent another scheduled frame from running before main unbinds the camera. run.active = false main.post { @@ -212,6 +231,7 @@ class ExpressionController( private fun stopCurrent() { val run = current ?: return current = null // Invalidate every pending model/provider/result callback before unbinding. + main.removeCallbacks(diagnosticTick) run.active = false try { run.analysis?.clearAnalyzer() @@ -232,6 +252,7 @@ class ExpressionController( run.rules.reset() run.faceRules.reset() run.lastPublished = null + run.diagnostics.summary(SystemClock.elapsedRealtime(), force = true)?.let { DebugLogUpload.log("audio", it) } } } run.executor.shutdown() diff --git a/app/src/main/java/com/gorios/lanvoice/expression/FaceCueRules.kt b/app/src/main/java/com/gorios/lanvoice/expression/FaceCueRules.kt index 2dc0e04..3599166 100644 --- a/app/src/main/java/com/gorios/lanvoice/expression/FaceCueRules.kt +++ b/app/src/main/java/com/gorios/lanvoice/expression/FaceCueRules.kt @@ -1,6 +1,10 @@ package com.gorios.lanvoice.expression enum class FaceCue(val wire: String) { UNKNOWN("unknown"), SMILING("smiling"), BROW_FURROWED("brow_furrowed") } +enum class FaceCueReason { + NO_FRAME, NO_FACE, MULTIPLE_FACES, POOR_QUALITY, MISSING_COEFFICIENTS, + INVALID_COEFFICIENTS, CONFLICT, NO_CLEAR_CUE, STABILIZING, STABLE, +} /** Rule intensity is an uncalibrated coefficient, never a probability or emotional state. */ data class FaceCueObservation( @@ -8,6 +12,7 @@ data class FaceCueObservation( val intensity: Float = 0f, val durationMs: Long = 0, val observedAtMs: Long = 0, + val reason: FaceCueReason = FaceCueReason.NO_FRAME, ) class FaceCueRules { @@ -22,24 +27,26 @@ class FaceCueRules { val last = previous if (last != null && (nowMs <= last || nowMs - last > 500)) reset() previous = nowMs - fun unknown(): FaceCueObservation { + fun unknown(reason: FaceCueReason): FaceCueObservation { candidate = FaceCue.UNKNOWN; active = false; since = nowMs - return FaceCueObservation(observedAtMs = nowMs) + return FaceCueObservation(observedAtMs = nowMs, reason = reason) } - if (faceCount != 1 || !quality || observation == null) return unknown() + if (faceCount == 0 || observation == null) return unknown(FaceCueReason.NO_FACE) + if (faceCount != 1) return unknown(FaceCueReason.MULTIPLE_FACES) + if (!quality) return unknown(FaceCueReason.POOR_QUALITY) val names = listOf("mouthSmileLeft", "mouthSmileRight", "browDownLeft", "browDownRight") - val scores = names.map { observation.blendshapes[it] ?: return unknown() } - if (scores.any { !it.isFinite() || it !in 0f..1f }) return unknown() + val scores = names.map { observation.blendshapes[it] ?: return unknown(FaceCueReason.MISSING_COEFFICIENTS) } + if (scores.any { !it.isFinite() || it !in 0f..1f }) return unknown(FaceCueReason.INVALID_COEFFICIENTS) val smile = minOf(scores[0], scores[1]) val brow = minOf(scores[2], scores[3]) val smiling = smile >= if (active && candidate == FaceCue.SMILING) .60f else .75f val furrowed = brow >= if (active && candidate == FaceCue.BROW_FURROWED) .50f else .65f - if (smiling == furrowed) return unknown() // Conflict or no clear cue. + if (smiling == furrowed) return unknown(if (smiling) FaceCueReason.CONFLICT else FaceCueReason.NO_CLEAR_CUE) val next = if (smiling) FaceCue.SMILING else FaceCue.BROW_FURROWED if (candidate != next) { candidate = next; since = nowMs; active = false } val duration = (nowMs - since).coerceIn(0, 10_000) - if (duration < 800) return FaceCueObservation(observedAtMs = nowMs) + if (duration < 800) return FaceCueObservation(observedAtMs = nowMs, reason = FaceCueReason.STABILIZING) active = true - return FaceCueObservation(next, if (smiling) smile else brow, duration, nowMs) + return FaceCueObservation(next, if (smiling) smile else brow, duration, nowMs, FaceCueReason.STABLE) } } diff --git a/app/src/main/java/com/gorios/lanvoice/expression/FaceDiagnostics.kt b/app/src/main/java/com/gorios/lanvoice/expression/FaceDiagnostics.kt new file mode 100644 index 0000000..d0df870 --- /dev/null +++ b/app/src/main/java/com/gorios/lanvoice/expression/FaceDiagnostics.kt @@ -0,0 +1,55 @@ +package com.gorios.lanvoice.expression + +/** Fixed fields only. No image, coefficient, pose, free text, or user speech. */ +enum class CameraFailure { NONE, MODEL_LOAD, DEVICE_SUPPORT, NO_FRONT_CAMERA, CAMERA_BIND, ANALYSIS, NO_RESULT } +data class CameraAnalysisSnapshot( + val received: Int = 0, val processed: Int = 0, val failures: Int = 0, + val faceCount: Int = 0, val cue: FaceCue = FaceCue.UNKNOWN, + val reason: FaceCueReason = FaceCueReason.NO_FRAME, val failure: CameraFailure = CameraFailure.NONE, + val lastProcessMs: Long = 0, +) + +class CameraAnalysisDiagnostics { + private var state = CameraAnalysisSnapshot() + private var lastLogMs: Long? = null + @Synchronized fun received() { state = state.copy(received = (state.received + 1).coerceAtMost(1_000_000)) } + @Synchronized fun processed(count: Int, cue: FaceCueObservation, elapsedMs: Long) { + state = state.copy(processed = (state.processed + 1).coerceAtMost(1_000_000), + faceCount = count.coerceIn(0, 2), cue = cue.cue, reason = cue.reason, + lastProcessMs = elapsedMs.coerceIn(0, 60_000)) + } + @Synchronized fun failed(failure: CameraFailure) { + state = state.copy(failures = (state.failures + 1).coerceAtMost(1_000_000), failure = failure) + } + @Synchronized fun snapshot() = state + @Synchronized fun summary(nowMs: Long, force: Boolean = false): String? { + val last = lastLogMs + if (!force && last != null && nowMs - last < 10_000) return null + lastLogMs = nowMs + return "camera analysis received=${state.received} processed=${state.processed} failures=${state.failures} faces=${state.faceCount} cue=${state.cue.wire} reason=${state.reason.name.lowercase()} failure=${state.failure.name.lowercase()} process_ms=${state.lastProcessMs}" + } +} + +enum class FaceSendReason { SHARING_OFF, BACKGROUND, NOT_CONNECTED, VOICE_INACTIVE, UNSUPPORTED, NO_TURN, + NO_FACE, NO_STABLE_CUE, STALE, INVALID_CUE, SENT, SEND_FAILED, CLEARED, CLEAR_FAILED } +data class FaceTransmissionSnapshot(val attempts: Int = 0, val sent: Int = 0, val clears: Int = 0, + val failures: Int = 0, val reason: FaceSendReason = FaceSendReason.SHARING_OFF, val cue: FaceCue = FaceCue.UNKNOWN) +class FaceTransmissionDiagnostics { + private var state = FaceTransmissionSnapshot() + private var lastLogMs: Long? = null + fun record(reason: FaceSendReason, cue: FaceCue = FaceCue.UNKNOWN) { + val attempt = reason in setOf(FaceSendReason.SENT, FaceSendReason.SEND_FAILED, FaceSendReason.CLEARED, FaceSendReason.CLEAR_FAILED) + state = state.copy(reason = reason, cue = cue, + attempts = (state.attempts + if (attempt) 1 else 0).coerceAtMost(1_000_000), + sent = (state.sent + if (reason == FaceSendReason.SENT) 1 else 0).coerceAtMost(1_000_000), + clears = (state.clears + if (reason == FaceSendReason.CLEARED) 1 else 0).coerceAtMost(1_000_000), + failures = (state.failures + if (reason in setOf(FaceSendReason.SEND_FAILED, FaceSendReason.CLEAR_FAILED)) 1 else 0).coerceAtMost(1_000_000)) + } + fun snapshot() = state + fun summary(nowMs: Long): String? { + val last = lastLogMs + if (last != null && nowMs - last < 10_000) return null + lastLogMs = nowMs + return "face transmission attempts=${state.attempts} sent=${state.sent} clears=${state.clears} failures=${state.failures} reason=${state.reason.name.lowercase()} cue=${state.cue.wire}" + } +} diff --git a/docs/EMOTION_CAMERA_052.md b/docs/EMOTION_CAMERA_052.md new file mode 100644 index 0000000..3ccde3e --- /dev/null +++ b/docs/EMOTION_CAMERA_052.md @@ -0,0 +1,33 @@ +# Android 0.5.2 / gateway 0.7.3 + +The report received on 2026-10-12 at 13:41:02 +08:00 came from an alps/API31 device running 0.5.1/code9. Five retained rounds were model-selected neutral0/strict_json/stop, with no fallback or discarded nonneutral event. The camera reached ACTIVE and later stopped on background; none of those rounds used face context. That establishes the symptom in those retained rounds, not that neutral was semantically incorrect or that the camera hardware failed. User speech, model envelopes and raw face data were not read for this investigation. + +## Role expression + +The single system now explains seven reply intents and strengths: objective facts neutral0, warm congratulations/relaxed joy happy1, strong joy happy2, restrained disapproval angry1, strong anger angry2, gentle regret/empathy sad1, deep sadness sad2. Classification follows the character's actual reply intent, not a user's emotional word, negation, quotation, another person's emotion or face. It no longer says ordinary questions default to neutral regardless of a warm reply. Objective answers remain neutral; no emotion quota or probability is introduced. Persona style/content/safety rules remain intact. + +The exact verified Qwen endpoint still uses json_schema, thinking=false, max_tokens160, one system and one request. The simple schema and parser cross-field checks are unchanged; neutral0 fallback with finite reasons, reply-only history/TTS and one streaming generator remain. Doubao provider switching and private Authorization/template settings are retained; unverified providers remain prompt-only unless explicitly configured after verification. ASR/TTS voice/parameters/models are unchanged. + +## Camera diagnostics + +Frame arrival and successful processing counts, failures, bounded face count (0/1/2), latest stable cue, last processing duration and fixed reasons are recorded for each local camera run. `camera_analysis` in an explicit diagnostic report is the current or last run snapshot; the existing camera status distinguishes a running camera from a stopped run. Reasons distinguish no frame, no face, multiple faces, poor quality, missing/invalid coefficients, conflicting cues, no clear cue, stabilizing and stable. Failures use fixed stage enums (model_load/device_support/no_front_camera/camera_bind/analysis/no_result), never raw exception strings. + +Camera summaries and transmission summaries each emit at most once per10s, with one final camera summary during stop; there are no per-frame logs or cue-transition bursts. Frame analysis stays on its existing executor and the10Hz limit is unchanged. Counts are capped at1,000,000, durations at60,000ms. Camera permissions retain the foreground-only gate and explicit pending permission handling. Camera/share remain off by default; thresholds, pose/framing and800ms stability requirements are unchanged. No camera failure was established, so no threshold or model change is claimed. + +`face_transmission` records activity-lifetime attempts, valid sends, clear sends, failures, last cue and fixed gating reason: sharing_off/background/not_connected/voice_inactive/unsupported/no_turn/no_face/no_stable_cue/stale/invalid_cue/sent/send_failed/cleared/clear_failed. Sharing toggle is explicit. Controls retain the existing1s send interval. Unknown observations no longer produce redundant periodic clear messages; a previously sent cue still receives a one-shot clear on loss/staleness/disable, with existing server TTL protection if a clear cannot send. This is bounded control cleanup, not a proven repair of the user's camera detection. Protocol fields are unchanged; the local diagnostic reason is not inserted in face control payloads. + +Gateway metrics snapshot finite `face_context` counters since that socket began, with receive/use reasons and used cue for the current reply turn. Receive rejection distinguishes malformed fields/version/turn/age/duration/intensity/cue/clear. Snapshot use distinguishes no cue/clear/new turn/consumed/wrong turn/stale/used. No extra model request or wait for a camera is introduced. Old clients/reports remain accepted. All images, video, coefficients, landmarks, pose, speech and raw model output remain excluded from these new logs/reports; only enums/counts/times are added. + +## Validation and release + +Candidate prompt: six fixed public cases were run once each under the active Yangmi persona, with no resampling or conversation history. Results: fact neutral0; congratulations happy1; sympathy sad1; restrained disapproval angry1; objective emotion-word definition neutral0; negated emotional phrase followed by arithmetic neutral0. All HTTP200/SSE[DONE]/model/strict_json/stop at160-token budget, reply lengths4/33/38/33/21/8. These are finite-case intent checks, not an accuracy estimate or proof about the user's prior five dialogues. Strong intensity2 is covered by model-free7-state/cross-field tests, not claimed as real-model acceptance in this six-case run. First content257.77–439.19ms; full structure1258.83–3287.67ms; waiting after first content819.64–2975.24ms. Usage absent does not mean zero tokens. + +The full isolated gateway suite and eight JVM suite entry points cover parser states/types/finish reasons/provider isolation, single system/LLM/TTS, cancellation/turn/seq/current-vs-previous labels, face stability/TTL/clear, camera permission lifecycle, no-face/stable/failure/send gating and10s summary rate/privacy. Android builds through scripts/build.sh with the existing JDK17 environment. APK is0.5.2/code10, arm64-v8a/minSdk26, verified against retained0.5.1 signature and HTTP bytes. Only0.5.1 and0.5.2 artifacts are retained for this release; no old APK is regenerated or deleted. No automatic USB install or device permission control occurs. + +Deployment remains canonical gateway/, hash/busy/unit/environment fenced with source/mode/private-loading backup on the server, restarting only gateway. Rollback: python3 scripts/rollback-gateway-source.py for the exact deployment record; checks remain mandatory. APK rollback file is artifacts/lan-voice-v051-arm64-debug.apk. Android generally rejects a lower versionCode over an installed higher version; retaining the file does not promise a data-preserving downgrade. User data/device changes are not performed here. + +Actual numeric release/full-chain artifacts are ignored under logs/emotion-052/ and logs/voice-investigation/. Real camera capture/frames/face recognition, alps and MI MAX phone behavior, phone audio audibility, long-session latency/semantic quality and the original user's conversations remain untested. New camera diagnostics become available only after installing0.5.2 and explicitly sending a report. + +Completed release:74 gateway tests passed in0.975s during deployment; all eight JVM entry points passed. One public audio round after deployment was happy1/model/strict_json/stop, one LLM and one TTS request, emotion before PCM,476160 PCM bytes and drained acknowledged. Synthetic smiling context was received1/accepted1/rejected0 and use_reason=used; it does not validate a real camera. LLM first content338.90ms, full structure2903.96ms, structure wait2565.06ms, TTS first PCM199.08ms, capture end to first PCM3153.46ms. Nonzero structure waiting remains significant. + +APK: http://192.168.31.124:8080/lan-voice-v052-arm64-debug.apk (31510181bytes), SHA256 `b0618f7e6befdd4403287ccaddae353f8180fd3e461e0b09bc357d89501eb6a4`. Signature verified and certificate matches retained0.5.1. APK and .apk.sha256 HTTP200/download bytes verified. Backup for gateway rollback: `/home/gorios-spark-2/lan-voice/.runtime/backups/voice-gateway-20261012-135835`. Qwen3.8-27b/thinkingfalse/json_schema and private unit/environment were reverified unchanged. No USB installation was attempted. diff --git a/gateway/README.md b/gateway/README.md index b812ecf..0101abf 100644 --- a/gateway/README.md +++ b/gateway/README.md @@ -34,3 +34,5 @@ Gateway 0.7.2 repairs the observed 0.5.1 `non_json/plain_text/stop` fallback by Persona format rules now explicitly bind only spoken `reply`, preserving style/content/safety while removing the competing outer JSON prohibition. One system and the 160-token budget remain. JSON/labels still never enter speech or history, and each parsed reply uses one streaming TTS generator. Health/hello and numeric metrics expose the format mode; optional diagnostics remain compatible with the 0.5.1 APK. No Android update is needed. See ../docs/STRUCTURED_REPLY_072.md for compatibility evidence, rollout and limitations. Deployment uses `deployment_baseline` in SOURCE_MANIFEST as the reviewed live hash fence, including the two whitelisted public persona lore JSON files. Ignored records no longer override the expected baseline. Backups retain all Python sources/tests, public persona lore, permissions and private unit/environment relationships on the server. The rollback script restores exactly the deployment whitelist and refuses busy/source/environment conflicts. + +Gateway0.7.3 / Android0.5.2 refines reply-intent rules with seven semantic examples and adds bounded camera/frame/transmission diagnostics. FaceContext emits finite receive/use reason/counters in per-turn metrics; counters are cumulative for the current socket, cue/use reason describes the current snapshot. Camera criteria and models remain unchanged. New diagnostic reports add camera_analysis (current/last run) and face_transmission (activity lifetime) snapshots; old reports are accepted. Each camera and transmission summary is limited to one per10s plus final camera stop summary. See ../docs/EMOTION_CAMERA_052.md for actual public-case results and test limits. Retained0.5.1 APK needs an update to0.5.2/code10 to supply the new camera fields. diff --git a/gateway/SOURCE_MANIFEST.json b/gateway/SOURCE_MANIFEST.json index 6c93467..0386cf5 100644 --- a/gateway/SOURCE_MANIFEST.json +++ b/gateway/SOURCE_MANIFEST.json @@ -1,7 +1,7 @@ { "baseline_android_commit": "9b428fb76ffa1468aa46124b33d9c598cf3740d8", "source": "SPARK-2 deployed lan-voice gateway", - "code_version": "0.7.2 (streaming json_schema for verified local provider; reply.emotion version 1)", + "code_version": "0.7.3 (role reply intent rules; bounded face pipeline diagnostics; schema)", "python": "3.12.3", "machine": "aarch64", "scope": "whitelisted source only; no runtime/models/credentials", @@ -27,14 +27,15 @@ "bytes": 554 }, "face_context.py": { - "source": "face_context.py", - "sha256": "01abfc214ebb4e979faf9430166eccae9af37df911d36da5435f907769e7e31a", - "bytes": 2997 + "source": "workspace:gateway/face_context.py", + "sha256": "d032ff8033a49219595d6edff2950856937e024782143621d37d02b56b024315", + "bytes": 4561, + "upstream_sha256": "01abfc214ebb4e979faf9430166eccae9af37df911d36da5435f907769e7e31a" }, "gateway.py": { "source": "workspace:gateway/gateway.py", - "sha256": "06797c4d327977eef755f72db70ef91ff6925ca20cc5ae8a6cefb5ffa1890534", - "bytes": 38786, + "sha256": "ea268a5abf36f79483427a78991d9ab2bab814ea3042ffcc08025de8c4af6b6d", + "bytes": 38914, "upstream_sha256": "d088bedcf5c0accd4712e06202f6ced8ab155aad57a5b05683724efa346326ce" }, "guest_sessions.py": { @@ -228,14 +229,16 @@ "bytes": 2216 }, "tests/test_face_context.py": { - "source": "workspace:backend/test_face_context.py", - "sha256": "50ca57adee1d07a194ebaa95b15e09d3e836b97b19490e99e3e045c72a89682c", - "bytes": 1851 + "source": "workspace:gateway/tests/test_face_context.py", + "sha256": "c297866117fa7406b5fda95250b67ca7ebd7476486ddd5455935c140d31c9f6f", + "bytes": 3230, + "upstream_sha256": "50ca57adee1d07a194ebaa95b15e09d3e836b97b19490e99e3e045c72a89682c" }, "tests/test_gateway_reply_face.py": { - "source": "workspace:backend/test_gateway_reply_face.py", - "sha256": "4a4a8fd997941c0d92356c2ebab2c336abbcf84954735a6955d8fa7e3700ec3f", - "bytes": 5320 + "source": "workspace:gateway/tests/test_gateway_reply_face.py", + "sha256": "393c95b7e97981b46445cd699890bb7b732d1c479310daf09bdf2c8349e47f4c", + "bytes": 5802, + "upstream_sha256": "4a4a8fd997941c0d92356c2ebab2c336abbcf84954735a6955d8fa7e3700ec3f" }, "requirements.lock": { "source": "deployed interpreter distribution metadata", @@ -249,8 +252,8 @@ }, "README.md": { "source": "workspace:gateway/README.md", - "sha256": "8e13b5532e5af921b411d5fa8185e9e8efbef42859f47ec3615099bb87304c10", - "bytes": 9220, + "sha256": "a558871dd83dd5c764c9cc3ba9b769c180bf8865adfc52ffed7fbbc93a5ca29a", + "bytes": 9974, "upstream_sha256": "799bc84308eb17d58987c5bee8ce3cf7617b4c52169d9307d344ac7d9996b6c5" }, "config/active_profile.json.example": { @@ -275,8 +278,8 @@ }, "env.example": { "source": "workspace:gateway/env.example", - "sha256": "ccc97d0e357d8120303cedf7947e1ba302070980a14cc8801f2424344fcab820", - "bytes": 1115, + "sha256": "b0c591d5e253ea4ea3ca1b177f4670a8939cfdba5c662cdaedbff7a95418ee85", + "bytes": 1266, "upstream_sha256": "d92e60812f49b02f3b0582d8b3dee03eb51cfca6dba77d9468a3ffddfce32499" }, "pytest.ini": { @@ -286,8 +289,8 @@ }, "reply_emotion.py": { "source": "workspace:gateway/reply_emotion.py", - "sha256": "a32b9dedc135cac1ed6f25f33123946152a6bd3dc8d0d816a897c00b9e444ead", - "bytes": 4343, + "sha256": "080f04e368c5a7d26254f2b870803238941aa481d457227ba15a870fd4a4e3c0", + "bytes": 5455, "upstream_sha256": "488fbd24ff1ce7d3d4ab92257c8ccabafe24fc857e11c8486f54fa689276a565" }, "scripts/check-archive.py": { @@ -298,8 +301,8 @@ }, "tests/test_gateway_emotion.py": { "source": "workspace:gateway/tests/test_gateway_emotion.py", - "sha256": "51a8f751d14345fe2ccf3afd9250b0962f0ab260a97023afcee4a7b9b0f535d0", - "bytes": 8535, + "sha256": "234310a9f44e3ece56482f4e2080e4f0882d1ea8b7dcd85795c816a8c1ebed78", + "bytes": 8596, "upstream_sha256": "86f22211e753e4b5ebfa11266e2e33eb2ea6b85707fbe8a988be6b8ff05f3f75" }, "tests/test_reply_emotion.py": { @@ -322,7 +325,7 @@ } }, "archive_baseline_commit": "19a7adccd9322986eb0646b165b9ce1cf2650cf2", - "workspace_release": "0.5.1", + "workspace_release": "0.5.2", "provider_baseline": { "source": "SPARK2 whitelist observed 2026-10-12", "files": { @@ -352,6 +355,55 @@ }, "release_baseline_commit": "d43c7d4e809a5a6b18ca9f28c8163a2f9ad34c7f", "deployment_baseline": { + "release": "gateway-0.7.3 / Android-0.5.2", + "files": { + "app.py": "d6520894dfbe035f64b1984aae15976db4df0e7e720195c81d3bf483b240056f", + "face_context.py": "d032ff8033a49219595d6edff2950856937e024782143621d37d02b56b024315", + "gateway.py": "ea268a5abf36f79483427a78991d9ab2bab814ea3042ffcc08025de8c4af6b6d", + "guest_sessions.py": "cc082fdb6c2ff7f5a41361ffe9ea2a53ebb944ee37354f65119405ad7a521c82", + "history.py": "2cf8b006bf486a03e038a69daa860ebb71a86989161cf6a7ea610114177a249f", + "llm_provider.py": "21aa2885c24f3240e891fd5325b09446ae1d8a95497d07a53082410d9fac2b10", + "persona_resolver.py": "deb33b4f4c17792fa5a6837362d5b29173e60a57bb993b61363bd4882d66d5de", + "personas/lvbu.lorebook.json": "1f144b431bdd5d9cda0ce593438fa88e717c0671d496105883a3d4db7bd635ea", + "personas/yangmi.lorebook.json": "73badae3fd8582555caa338e50fb6193e64e6a43025dd469672aa903c1c4b71b", + "protocol.py": "d9f522d958935200002e56024949a12b71eb89b3f3241635c5c307b798ee71c5", + "reply_emotion.py": "080f04e368c5a7d26254f2b870803238941aa481d457227ba15a870fd4a4e3c0", + "segmentation.py": "562ffc6e06f5b9f9072860b588feae3a5d7cd6eaa8577ac928d770071b06978d", + "tests/test_continuity.py": "d8390238f390463a98f12b9909bb5846be65f5b6dc1b21b94338b4cd75aaafae", + "tests/test_debug.py": "7d1d7876c4106f3df0b84cf8f7e479afb4a30ca51264fb94fa288fdd8155883e", + "tests/test_face_context.py": "c297866117fa7406b5fda95250b67ca7ebd7476486ddd5455935c140d31c9f6f", + "tests/test_gateway.py": "f22aa98f3d6f62a2949a9047ec97e6dd686cac807d989a314a95deca718a3104", + "tests/test_gateway_emotion.py": "234310a9f44e3ece56482f4e2080e4f0882d1ea8b7dcd85795c816a8c1ebed78", + "tests/test_gateway_reply_face.py": "393c95b7e97981b46445cd699890bb7b732d1c479310daf09bdf2c8349e47f4c", + "tests/test_guests.py": "6bc531f1bff85b8ea550bc88c634726531a1ef241ba5c861dbb8c963adf31c35", + "tests/test_history.py": "fc13a69811cfc4f4acf265ea9e0cdd67d566358ebe9b9b53cae76197db8bce78", + "tests/test_llm_provider.py": "43669d1fd7e61452b96f314a7f161fbcec843e463c74208d0f892fb58b839785", + "tests/test_personas.py": "013b18e7b7f0e582d8d7e04f5b1fb78009e993f96357be67a5367e70444b43e1", + "tests/test_reply_emotion.py": "4ff2774187df8220ddbc8ef5b79910ae5047af3bacdb9476b0d2a8f55929d3be", + "tests/test_segmentation.py": "cf80a74958a715a81180a7932efb84f1d0974b434cf4fc3354b68c604ccbf463", + "tests/test_v08.py": "f993d4162576494e814786f26376ba80ab8a77af98ba70de4379055bb9525082", + "tests/test_vad.py": "bff64c0aafa05c085af7c1c9418244609129d405320fe1080b4ba05a8e304228", + "tests_fake.py": "9a40f1948352f69f1dd20f8514baef58ae3d11eec240e1d2324d8990bad915d8", + "tts_debug.py": "d7b31b98a7f8ab688981873ef81decdf0b2f0167113c9103df039b7b24c9ccf2", + "vad.py": "3718ff9b296b2bba447100af520a631f221dcbfa322dd564cdc5809fb3675f23" + } + }, + "server_capabilities": { + "structured_output_env": "LAN_LLM_STRUCTURED_OUTPUT", + "modes": [ + "prompt", + "json_schema" + ], + "verified_default": { + "base_url": "http://127.0.0.1:8888/v1", + "model": "qwen3.8-27b", + "chat_template_kwargs": { + "enable_thinking": false + } + }, + "doubao_schema_verified": false + }, + "previous_deployment_baseline": { "release": "gateway-0.7.2 / Android-0.5.1", "files": { "app.py": "d6520894dfbe035f64b1984aae15976db4df0e7e720195c81d3bf483b240056f", @@ -384,55 +436,5 @@ "tts_debug.py": "d7b31b98a7f8ab688981873ef81decdf0b2f0167113c9103df039b7b24c9ccf2", "vad.py": "3718ff9b296b2bba447100af520a631f221dcbfa322dd564cdc5809fb3675f23" } - }, - "server_capabilities": { - "structured_output_env": "LAN_LLM_STRUCTURED_OUTPUT", - "modes": [ - "prompt", - "json_schema" - ], - "verified_default": { - "base_url": "http://127.0.0.1:8888/v1", - "model": "qwen3.8-27b", - "chat_template_kwargs": { - "enable_thinking": false - } - }, - "doubao_schema_verified": false - }, - "previous_deployment_baseline": { - "release": "0.5.1", - "commit": "b521d368a5a5bab77599c860f651dce04b0de67e", - "files": { - "app.py": "d6520894dfbe035f64b1984aae15976db4df0e7e720195c81d3bf483b240056f", - "face_context.py": "01abfc214ebb4e979faf9430166eccae9af37df911d36da5435f907769e7e31a", - "gateway.py": "b8e64e9387fca05808fac61bd097ae179e996a2c7ccd33f23bb729a61693dd0d", - "guest_sessions.py": "cc082fdb6c2ff7f5a41361ffe9ea2a53ebb944ee37354f65119405ad7a521c82", - "history.py": "2cf8b006bf486a03e038a69daa860ebb71a86989161cf6a7ea610114177a249f", - "llm_provider.py": "56ce6c1a4a647dea6ef86a83615f03db3a4397ebb3fa800b7fa655147d4f9978", - "persona_resolver.py": "deb33b4f4c17792fa5a6837362d5b29173e60a57bb993b61363bd4882d66d5de", - "protocol.py": "d9f522d958935200002e56024949a12b71eb89b3f3241635c5c307b798ee71c5", - "reply_emotion.py": "a2b6a1a51639d77368c200f2a6db8bb66fff1eebb4f60219d49da69ae402a8a2", - "segmentation.py": "562ffc6e06f5b9f9072860b588feae3a5d7cd6eaa8577ac928d770071b06978d", - "tests/test_continuity.py": "d8390238f390463a98f12b9909bb5846be65f5b6dc1b21b94338b4cd75aaafae", - "tests/test_debug.py": "7d1d7876c4106f3df0b84cf8f7e479afb4a30ca51264fb94fa288fdd8155883e", - "tests/test_face_context.py": "50ca57adee1d07a194ebaa95b15e09d3e836b97b19490e99e3e045c72a89682c", - "tests/test_gateway.py": "f22aa98f3d6f62a2949a9047ec97e6dd686cac807d989a314a95deca718a3104", - "tests/test_gateway_emotion.py": "e4da9a092e6ee19ef421a43a04cd2b6d12cb65f1b210946092dcad016c8816bb", - "tests/test_gateway_reply_face.py": "4a4a8fd997941c0d92356c2ebab2c336abbcf84954735a6955d8fa7e3700ec3f", - "tests/test_guests.py": "6bc531f1bff85b8ea550bc88c634726531a1ef241ba5c861dbb8c963adf31c35", - "tests/test_history.py": "fc13a69811cfc4f4acf265ea9e0cdd67d566358ebe9b9b53cae76197db8bce78", - "tests/test_llm_provider.py": "45404653daa71a006a90852b2f07f00cac608bd7311dd5ea850da0c1a3e52940", - "tests/test_personas.py": "2576f2be903c69270cb1dec1e12448154554798bd7fca866d78e66e31594cbcb", - "tests/test_reply_emotion.py": "2bd1ee33f11e2d23ccf9a30603f0db3b9f20c6d5fce8001f37f9ca76167974dd", - "tests/test_segmentation.py": "cf80a74958a715a81180a7932efb84f1d0974b434cf4fc3354b68c604ccbf463", - "tests/test_v08.py": "f993d4162576494e814786f26376ba80ab8a77af98ba70de4379055bb9525082", - "tests/test_vad.py": "bff64c0aafa05c085af7c1c9418244609129d405320fe1080b4ba05a8e304228", - "tests_fake.py": "9a40f1948352f69f1dd20f8514baef58ae3d11eec240e1d2324d8990bad915d8", - "tts_debug.py": "d7b31b98a7f8ab688981873ef81decdf0b2f0167113c9103df039b7b24c9ccf2", - "vad.py": "3718ff9b296b2bba447100af520a631f221dcbfa322dd564cdc5809fb3675f23", - "personas/lvbu.lorebook.json": "266078a2aed07dcbcf3283ae102a8215cef6c181bb240ac5e53ee240414721e4", - "personas/yangmi.lorebook.json": "d3b0201dff992b1bd0258d4aa06f8e7688322c9904c0b885aa6cf7be7046717d" - } } } diff --git a/gateway/env.example b/gateway/env.example index 584d443..9c2e88b 100644 --- a/gateway/env.example +++ b/gateway/env.example @@ -17,3 +17,5 @@ LAN_LLM_CHAT_TEMPLATE_KWARGS={"enable_thinking":false} # model alias doubao-seed-2-1-pro, kwargs {}, LAN_LLM_STRUCTURED_OUTPUT=prompt. # Reset this mode when switching providers; Doubao schema support is unverified. # Alias does not identify actual weights. +# Gateway0.7.3 keeps this provider/schema contract and the160-token dialogue budget; +# camera/frame diagnostics do not add a model or inference retry. diff --git a/gateway/face_context.py b/gateway/face_context.py index 6ec5bc9..70fc30e 100644 --- a/gateway/face_context.py +++ b/gateway/face_context.py @@ -13,30 +13,51 @@ TEMPLATE = ( class FaceContext: def __init__(self): self.value = None + self.received = self.accepted = self.rejected = self.clears = 0 + self.receive_reason = 'not_received' + self.use_reason = 'not_taken' + self.state_reason = 'no_cue' + self.used_cue = 'unknown' - def clear(self): + def clear(self, reason='cleared'): self.value = None + self.state_reason = reason + + def diagnostics(self): + return {'received': self.received, 'accepted': self.accepted, 'rejected': self.rejected, + 'clears': self.clears, 'receive_reason': self.receive_reason, + 'use_reason': self.use_reason, 'cue': self.used_cue} def update(self, data, turn, now=None): self.clear() # Invalid observations must never leave an older cue latched. + self.received = min(self.received + 1, 1_000_000) + def reject(reason): + self.rejected = min(self.rejected + 1, 1_000_000) + self.receive_reason = self.state_reason = reason + return False allowed = {'type', 'version', 'turn_id', 'valid', 'cue', 'intensity', 'duration_ms', 'age_ms'} if not isinstance(data, dict) or set(data) != allowed: - return False + return reject('invalid_fields') if data['type'] != 'context.face_cue' or type(data['version']) is not int or data['version'] != 1: - return False + return reject('invalid_version') if type(data['turn_id']) is not int or not 0 <= data['turn_id'] <= 0xffffffff or data['turn_id'] != turn: - return False + return reject('wrong_turn') if type(data['valid']) is not bool: - return False + return reject('invalid_valid') age, duration, intensity = data['age_ms'], data['duration_ms'], data['intensity'] if type(age) is not int or not 0 <= age <= 3000 or type(duration) is not int or not 0 <= duration <= 10000: - return False + return reject('invalid_age_duration') if type(intensity) not in (int, float) or not math.isfinite(intensity) or not 0 <= intensity <= 1: - return False + return reject('invalid_intensity') if not data['valid']: - return data['cue'] == 'unknown' and intensity == 0 and duration == 0 + if data['cue'] != 'unknown' or intensity != 0 or duration != 0: return reject('invalid_clear') + self.clears = min(self.clears + 1, 1_000_000) + self.receive_reason = self.state_reason = 'explicit_clear' + return True if data['cue'] not in ('smiling', 'brow_furrowed') or duration < 800 or intensity < .5: - return False + return reject('invalid_cue') + self.accepted = min(self.accepted + 1, 1_000_000) + self.receive_reason = self.state_reason = 'accepted' self.value = (turn, data['cue'], intensity, duration, age, time.monotonic() if now is None else now) return True @@ -45,15 +66,24 @@ class FaceContext: if self.value and self.value[0] == old_turn: self.value = (new_turn, *self.value[1:]) else: - self.clear() + self.clear('new_turn') def take(self, turn, now=None): value, self.value = self.value, None - if value is None or value[0] != turn: + self.used_cue = 'unknown' + if value is None: + self.use_reason = self.state_reason + return None + if value[0] != turn: + self.use_reason = self.state_reason = 'wrong_turn' return None _, cue, intensity, duration, age, received = value elapsed = ((time.monotonic() if now is None else now) - received) * 1000 if elapsed < 0 or age + round(elapsed, 6) > 3000: + self.use_reason = self.state_reason = 'stale' return None + self.use_reason = 'used' + self.state_reason = 'consumed' + self.used_cue = cue label = {'smiling': '明显、持续的嘴角上扬', 'brow_furrowed': '明显、持续的双侧眉头收紧'}[cue] return {'role': 'system', 'content': TEMPLATE.format(cue=label, intensity=round(intensity, 2), duration=duration)} diff --git a/gateway/gateway.py b/gateway/gateway.py index 31aa0b4..27abc96 100644 --- a/gateway/gateway.py +++ b/gateway/gateway.py @@ -30,7 +30,7 @@ from protocol import WavStream, pack, unpack from vad import Config, Silero, VadSession ROOT = Path(__file__).resolve().parent -VERSION = '0.7.2' +VERSION = '0.7.3' DEFAULT_VOICE_ID = '9a97272c-3919-5606-9c8f-9552ab602528' ORIGINS = {'https://192.168.31.61:5011', 'https://localhost:5011', 'https://127.0.0.1:5011'} @@ -425,6 +425,7 @@ class Dialogue: face_message = self.face_context.take(turn) if face_message is not None: self.face_messages[turn] = [face_message] metrics['face_cue_used'] = face_message is not None + metrics['face_context'] = self.face_context.diagnostics() text = text[:2000] if self.history: recorded = True @@ -472,6 +473,7 @@ class Dialogue: '\n\n' + item['content'] for item in self.face_messages.get(turn, [])) + '\n\n' + SYSTEM_FRAGMENT messages = [{'role': 'system', 'content': system}] + self.contexts.get(turn, []) + [{'role': 'user', 'content': text}] url, headers, body = self.llm_provider.request(messages, max_tokens=160) + metrics['llm_request_count'] = 1 raw_body = '' finish_reason = 'not_provided' usage = {} @@ -671,7 +673,7 @@ async def dialogue(ws: WebSocket): if not isinstance(data, dict): raise ValueError('control object') if data.get('type') == 'context.face_cue': if len(raw.encode('utf-8')) > 512: - session.face_context.clear() + session.face_context.clear('input_limit') else: session.face_context.update(data, session.turn) elif data.get('type') == 'debug': diff --git a/gateway/reply_emotion.py b/gateway/reply_emotion.py index 8436fbe..b926ae7 100644 --- a/gateway/reply_emotion.py +++ b/gateway/reply_emotion.py @@ -14,7 +14,11 @@ REPLY_SCHEMA = { 'additionalProperties': False, } -SYSTEM_FRAGMENT = '''本轮只输出一个JSON对象,格式为{"reply":"简短中文回答","emotion":"neutral","intensity":0},不加代码围栏或额外文字。reply直接回答用户,最多两小句,不含情绪标签、动作旁白或思考过程。emotion是角色本轮表达意图,不是用户心理判断;只允许neutral(intensity=0)、happy/angry/sad(intensity=1轻度或2明显)。普通问答默认neutral;帮助性和用户台词优先,不为表演牺牲回答,不根据摄像头皱眉强行生气或攻击。每轮仅一个主情绪,无混合或长期状态。''' +SYSTEM_FRAGMENT = '''本轮只输出一个JSON对象,字段reply为简短中文回答,emotion为neutral/happy/angry/sad,intensity为整数。无围栏或额外文字。reply直接回答用户,最多两小句,不含情绪标签、动作旁白或思考过程,保持角色风格与实际帮助。 +emotion描述角色这句reply自身传达的态度和感受,不识别用户心理,不直接复制用户、人脸或第三方情绪。先按回复语义和表达意图选择,再给强度:neutral只配0,happy/angry/sad只配1轻度或2明显。温暖祝贺、欣慰和轻松欣喜可用happy1;惋惜、遗憾和共情可用sad1,不必因回复也是回答问题就中立。仅事实、操作说明或没有明显情感态度时neutral0。强度由reply实际措辞与意图决定,不能由用户使用“非常”等词决定。 +七种意图示例(说明分类,不是固定台词):客观说明“水通常在一百度沸腾”→neutral0;温暖祝贺“做得好,替你开心”→happy1;明确强烈欢喜“太棒了,我真是开心极了”→happy2;克制不满“这处理确实不妥,我不赞同”→angry1;明确强烈愤怒“这太过分了,我非常气愤”→angry2;温和惋惜共情“真遗憾,这一定很不好受”→sad1;明确深切悲伤“听到这消息我非常难过”→sad2。 +引用、否定、情绪词解释、讲述别人情绪不自动变成角色情绪;如客观解释愤怒仍可neutral。摄像头只供弱辅助,微笑不必高兴、皱眉不必生气。每轮只选一个主情绪,不混合,不强迫非中立,不输出概率。不为表演牺牲准确性或安全,不因愤怒辱骂攻击,不虚构亲历。''' + SAFE_REPLY = '抱歉,这次回答格式有误,请再说一次。' @dataclass(frozen=True) diff --git a/gateway/tests/test_face_context.py b/gateway/tests/test_face_context.py index 6aeaa30..33a2fe7 100644 --- a/gateway/tests/test_face_context.py +++ b/gateway/tests/test_face_context.py @@ -8,6 +8,31 @@ def cue(**changes): class FaceContextTests(unittest.TestCase): + def test_diagnostics_use_clear_stale_and_rejected_without_raw_fields(self): + state=FaceContext() + self.assertIsNone(state.take(1)) + self.assertEqual(state.diagnostics()['use_reason'],'no_cue') + state.update(cue(),1,now=100) + state.take(1,now=100) + self.assertEqual(state.diagnostics(),{'received':1,'accepted':1,'rejected':0,'clears':0, + 'receive_reason':'accepted','use_reason':'used','cue':'smiling'}) + state.update(cue(),1,now=100) + self.assertIsNone(state.take(1,now=103)) + self.assertEqual(state.diagnostics()['use_reason'],'stale') + state.update(cue(turn_id=2),1,now=100) + state.take(1,now=100) + self.assertEqual(state.diagnostics()['use_reason'],'wrong_turn') + state.update(cue(valid=False,cue='unknown',intensity=0,duration_ms=0),1) + state.take(1) + self.assertEqual(state.diagnostics()['use_reason'],'explicit_clear') + state.update(cue(text='never-store-this',landmarks=[1]),1) + self.assertNotIn('never-store-this',str(state.diagnostics())) + self.assertEqual(state.diagnostics()['receive_reason'],'invalid_fields') + state.received=state.accepted=1_000_000 + state.update(cue(),1) + self.assertEqual(state.diagnostics()['received'],1_000_000) + self.assertEqual(state.diagnostics()['accepted'],1_000_000) + def test_ttl_and_one_shot(self): state = FaceContext() self.assertTrue(state.update(cue(), 1, now=100)) diff --git a/gateway/tests/test_gateway_emotion.py b/gateway/tests/test_gateway_emotion.py index 8415d5c..b2288a9 100644 --- a/gateway/tests/test_gateway_emotion.py +++ b/gateway/tests/test_gateway_emotion.py @@ -77,6 +77,7 @@ class EmotionPipelineTests(unittest.IsolatedAsyncioTestCase): self.assertEqual((event['emotion'],event['intensity'],event['source']),('neutral',0,'fallback')) self.assertNotIn('reply',event);self.assertNotIn('公开正文',json.dumps(metrics,ensure_ascii=False)) self.assertEqual(metrics['llm_max_tokens'],160) + self.assertEqual(metrics['llm_request_count'],1) async def test_debug_metadata_contains_counts_not_reply_text(self): import tempfile diff --git a/gateway/tests/test_gateway_reply_face.py b/gateway/tests/test_gateway_reply_face.py index 208385f..0015574 100644 --- a/gateway/tests/test_gateway_reply_face.py +++ b/gateway/tests/test_gateway_reply_face.py @@ -48,9 +48,16 @@ class ReplyFaceTests(unittest.IsolatedAsyncioTestCase): self.assertEqual(d.face_messages, {}) self.assertIsNone(d.face_context.value) self.assertTrue(socket.frames) + metrics=next(e['values'] for e in socket.events if e['type']=='metrics') + self.assertEqual(metrics['face_context']['use_reason'],'used') + self.assertEqual(metrics['face_context']['cue'],'smiling') + self.assertEqual(metrics['face_context']['accepted'],1) d, socket, messages = await self.round(observation=False) self.assertEqual([m['role'] for m in messages[0]], ['system','user']) self.assertNotIn('摄像头观察', messages[0][0]['content']) + metrics=next(e['values'] for e in socket.events if e['type']=='metrics') + self.assertFalse(metrics['face_cue_used']) + self.assertEqual(metrics['face_context']['cue'],'unknown') async def test_expired_and_barge_clear(self): d = Dialogue(Socket(), FakeModel(), None) diff --git a/scripts/check-expression-rules.sh b/scripts/check-expression-rules.sh index e2e1f44..d9e7619 100755 --- a/scripts/check-expression-rules.sh +++ b/scripts/check-expression-rules.sh @@ -29,10 +29,13 @@ with tempfile.TemporaryDirectory(prefix='lan-voice-expression-check-') as output 'app/src/main/java/com/gorios/lanvoice/expression/ExpressionRules.kt', 'app/src/main/java/com/gorios/lanvoice/expression/FaceCueRules.kt', 'app/src/main/java/com/gorios/lanvoice/expression/CameraPermissionGate.kt', + 'app/src/main/java/com/gorios/lanvoice/expression/FaceDiagnostics.kt', 'tests/expression/ExpressionRulesCheck.kt', 'tests/expression/FaceCueRulesCheck.kt', - 'tests/expression/CameraPermissionCheck.kt'], check=True) + 'tests/expression/CameraPermissionCheck.kt', + 'tests/expression/FaceDiagnosticsCheck.kt'], check=True) subprocess.run([java, '-cp', output + ':' + stdlib, 'ExpressionRulesCheckKt'], check=True) subprocess.run([java, '-cp', output + ':' + stdlib, 'FaceCueRulesCheckKt'], check=True) subprocess.run([java, '-cp', output + ':' + stdlib, 'CameraPermissionCheckKt'], check=True) + subprocess.run([java, '-cp', output + ':' + stdlib, 'FaceDiagnosticsCheckKt'], check=True) PY diff --git a/scripts/check-reply-regressions.py b/scripts/check-reply-regressions.py index 30a3e20..aca0050 100644 --- a/scripts/check-reply-regressions.py +++ b/scripts/check-reply-regressions.py @@ -23,7 +23,7 @@ compiler = ':'.join([jar('org.jetbrains.kotlin','kotlin-compiler-embeddable','2. cp = ':'.join([stdlib, jar('com.squareup.okhttp3','okhttp','4.12.0'), jar('com.squareup.okio','okio-jvm','3.6.0')]) source = ROOT/'app/src/main/java/com/gorios/lanvoice' suites = [ - ('session','ConnectionCheckKt', [source/'audio/VoiceSession.kt', source/'dialogue/ReplyEmotion.kt', source/'net/DialogueClient.kt', source/'expression/FaceCueRules.kt', source/'expression/ExpressionRules.kt']), + ('session','ConnectionCheckKt', [source/'audio/VoiceSession.kt', source/'dialogue/ReplyEmotion.kt', source/'net/DialogueClient.kt', source/'expression/FaceCueRules.kt', source/'expression/ExpressionRules.kt', source/'expression/FaceDiagnostics.kt']), ('playback','PlaybackCheckKt', [source/'audio/AudioPlayback.kt']), ('capture','CaptureCheckKt', [source/'audio/AudioCapture.kt']), ('protocol','ProtocolCheckKt', [source/'net/DialogueProtocol.kt', source/'dialogue/ReplyEmotion.kt', source/'expression/FaceCueRules.kt', source/'expression/ExpressionRules.kt']), diff --git a/scripts/package-emotion-release.sh b/scripts/package-emotion-release.sh index f2b0339..8cd8a1c 100755 --- a/scripts/package-emotion-release.sh +++ b/scripts/package-emotion-release.sh @@ -7,13 +7,16 @@ from pathlib import Path import hashlib,json root=Path.cwd();directory=root/'logs/voice-investigation' load=lambda name:json.loads((directory/name).read_text()) -deploy=load('gateway-emotion-deploy.json');probe=load('probe-emotion.json');client=load('client-emotion-tests.json');compat=load('reply-structure.json') +deploy=load('gateway-emotion-deploy.json');probe=load('probe-emotion.json');client=load('client-emotion-tests.json') +compat=json.loads((root/'logs/emotion-052/semantic-candidate.json').read_text()) assert deploy['applied'] and deploy['health']=='ok' and deploy['environment_unchanged'] assert probe['status']=='passed' and probe['downlink_bytes']>0 and probe['emotion_before_pcm'] and probe['drained_ack'] and probe['tts_requests']==1 -assert compat['status']=='passed' and client['status']=='passed' +assert compat['status']=='passed' and compat['semantic_status']=='matched_fixed_cases' and client['status']=='passed' for name,digest in deploy['hashes'].items():assert hashlib.sha256((root/'gateway'/name).read_bytes()).hexdigest()==digest,name for name,digest in client['hashes'].items():assert hashlib.sha256((root/name).read_bytes()).hexdigest()==digest,name -assert not (root/'artifacts/lan-voice-v051-arm64-debug.apk').exists(), 'release artifact exists: refusing overwrite' +assert not (root/'artifacts/lan-voice-v052-arm64-debug.apk').exists(), 'release artifact exists: refusing overwrite' +assert (root/'artifacts/lan-voice-v051-arm64-debug.apk').is_file(), 'previous release required for signature comparison/rollback' +assert hashlib.sha256((root/'gateway/reply_emotion.py').read_bytes()).hexdigest()==compat['candidate_source_sha256'], 'semantic probe does not match candidate prompt source' print('Verified tested client/provider source and successful deployed pipeline before APK build') PY ./scripts/build.sh @@ -29,20 +32,19 @@ from pathlib import Path root=Path.cwd() badging=(root/'logs/voice-investigation/release-emotion-badging.txt').read_text() assert "name='com.gorios.lanvoice'" in badging -assert "versionCode='9'" in badging and "versionName='0.5.1'" in badging +assert "versionCode='10'" in badging and "versionName='0.5.2'" in badging native=re.search(r'^native-code: (.+)$',badging,re.M) assert native and native[1].strip()=="'arm64-v8a'", 'unexpected ABI' source=root/'app/build/outputs/apk/debug/app-debug.apk' -previous=root/'artifacts/lan-voice-v040-arm64-debug.apk' +previous=root/'artifacts/lan-voice-v051-arm64-debug.apk' if previous.exists(): old=subprocess.check_output(['/home/ubuntu/android-build/sdk/build-tools/34.0.0/apksigner','verify','--print-certs',str(previous)],text=True) new=(root/'logs/voice-investigation/release-emotion-signature.txt').read_text() pattern=r'Signer #1 certificate SHA-256 digest: (\w+)' assert re.search(pattern,old)[1]==re.search(pattern,new)[1], 'signing certificate changed: update install would fail' -artifact=root/'artifacts/lan-voice-v051-arm64-debug.apk' +artifact=root/'artifacts/lan-voice-v052-arm64-debug.apk' assert not artifact.exists(), 'release artifact exists: refusing overwrite' -assert hashlib.sha256((root/'artifacts/lan-voice-v040-arm64-debug.apk').read_bytes()).hexdigest()=='5a6f88cb2f825dbcd5c7b8c1f212b369534bc53c49533e196fb5e9287902e934' -assert hashlib.sha256((root/'artifacts/lan-voice-v050-arm64-debug.apk').read_bytes()).hexdigest()=='da47f7a08f63a68fbb6dbe7fb3d803ee58b402de393112a32f92a63ad50c1f33' +assert hashlib.sha256(previous.read_bytes()).hexdigest()=='7d089517cde3241d79c971d6260ed8f71af86851e2623fdc66e51fb1583ae77f' shutil.copy2(source,artifact) digest=hashlib.sha256(artifact.read_bytes()).hexdigest() artifact.with_suffix('.apk.sha256').write_text(f'{digest} {artifact.name}\n') @@ -60,7 +62,7 @@ for path in ('artifacts/'+artifact.name, artifact.name): if downloaded==digest: url=base+path;break except Exception: pass assert url is not None, 'APK built, but existing HTTP server did not serve matching bytes' -result=dict(version_name='0.5.1',version_code=9,apk=str(artifact.relative_to(root)),bytes=artifact.stat().st_size,sha256=digest,url=url,download_http_status=200,download_bytes=len(content),signature='apksigner_verified',real_phone_playback='not_tested') +result=dict(version_name='0.5.2',version_code=10,apk=str(artifact.relative_to(root)),bytes=artifact.stat().st_size,sha256=digest,url=url,download_http_status=200,download_bytes=len(content),signature='apksigner_verified',same_signing_certificate_as='0.5.1',real_phone_playback='not_tested') (root/'logs/voice-investigation/release-emotion.json').write_text(json.dumps(result,indent=2)+'\n') print(json.dumps(result,indent=2)) PY diff --git a/scripts/probe-llm-schema.py b/scripts/probe-llm-schema.py index 9e033f1..26840e0 100644 --- a/scripts/probe-llm-schema.py +++ b/scripts/probe-llm-schema.py @@ -3,12 +3,13 @@ import argparse import json import subprocess +import hashlib from pathlib import Path import sys ROOT = Path(__file__).resolve().parents[1] sys.path.insert(0, str(ROOT / 'gateway')) -from reply_emotion import REPLY_SCHEMA +from reply_emotion import REPLY_SCHEMA, SYSTEM_FRAGMENT REMOTE = r''' import asyncio, json, pathlib, ssl, subprocess, time, urllib.request @@ -17,6 +18,7 @@ from llm_provider import LLMProvider from reply_emotion import SYSTEM_FRAGMENT, parse_reply from persona_resolver import resolve_persona root=pathlib.Path('/home/gorios-spark-2/lan-voice') +if candidate_prompt is not None: SYSTEM_FRAGMENT=candidate_prompt result={'status':'failed','public_samples':samples,'rows':[],'real_phone_playback':'not_tested'} async def probe(): ctx=ssl.create_default_context(cafile=str(root/'.runtime/gateway-cert.pem')) @@ -33,9 +35,8 @@ async def probe(): rules=resolve_persona(root,persona,voice_ids)['rules'] if preflight:system='以下角色设定只约束reply字段的口述内容;其中旧有不输出JSON等格式约定不约束本轮外层结构。\n'+rules+'\n\n'+SYSTEM_FRAGMENT else:system='以下角色设定只约束reply字段的可朗读正文。\n'+rules+'\n\n'+SYSTEM_FRAGMENT - public=['请简短说一声你好。','公开合成测试:朋友考试通过了,表达轻度高兴,简短祝贺。'] async with httpx.AsyncClient(trust_env=False,timeout=30) as client: - for index,text in enumerate(public[:samples]): + for index,(name,text,expected) in enumerate(cases): url,headers,body=p.request([{'role':'system','content':system},{'role':'user','content':text}],max_tokens=160) if preflight:body['response_format']={'type':'json_schema','json_schema':{'name':'role_reply','strict':True,'schema':schema}} else:assert body.get('response_format')=={'type':'json_schema','json_schema':{'name':'role_reply','strict':True,'schema':schema}}, 'schema_not_enabled' @@ -59,9 +60,13 @@ async def probe(): elapsed=round((time.perf_counter()-start)*1000,2) parsed=parse_reply(raw,finish_reason=finish) row={'sample':index+1,'http_status':response.status_code,'sse_done':done,'chunks':chunks,'envelope_chars':len(raw),'reply_chars':len(parsed.reply),'emotion':parsed.emotion,'intensity':parsed.intensity,'source':parsed.source,'reason':parsed.reason,'parse_branch':parsed.parse_branch,'finish_reason':finish,'usage':usage,'max_tokens':160,'first_content_ms':first,'complete_ms':elapsed,'structured_wait_ms':round(elapsed-(first or elapsed),2)} + row['case']=name + if expected is not None:row.update(expected_emotion=expected,expected_emotion_match=parsed.emotion==expected) result['rows'].append(row) assert done and finish=='stop' and parsed.source=='model' and parsed.parse_branch=='strict_json' and 0327, 'no voiced PCM amplitude' summary['pcm_rms']=round(math.sqrt(summary.pop('pcm_square')/(summary['downlink_bytes']//2)),2) summary['status']='passed' diff --git a/tests/expression/FaceCueRulesCheck.kt b/tests/expression/FaceCueRulesCheck.kt index ff65cf5..a862c77 100644 --- a/tests/expression/FaceCueRulesCheck.kt +++ b/tests/expression/FaceCueRulesCheck.kt @@ -25,5 +25,13 @@ fun main() { check(result.cue == if(t==800L) FaceCue.BROW_FURROWED else FaceCue.UNKNOWN) } checkUnknown(obs=face(.1f,.4f),t=900) + check(rules.evaluate(null,0,false,1000).reason == FaceCueReason.NO_FACE) + check(rules.evaluate(face(),2,true,1100).reason == FaceCueReason.MULTIPLE_FACES) + check(rules.evaluate(face(),1,false,1200).reason == FaceCueReason.POOR_QUALITY) + check(rules.evaluate(face(.1f,.1f),1,true,1300).reason == FaceCueReason.NO_CLEAR_CUE) + check(rules.evaluate(face(.9f,.9f),1,true,1400).reason == FaceCueReason.CONFLICT) + check(rules.evaluate(face(),1,true,1500).reason == FaceCueReason.STABILIZING) + check(rules.evaluate(face(Float.NaN),1,true,1600).reason == FaceCueReason.INVALID_COEFFICIENTS) + check(rules.evaluate(FaceObservation(emptyMap(),null),1,true,1700).reason == FaceCueReason.MISSING_COEFFICIENTS) println("PASS: sustained bilateral cues, hysteresis, conflict/multiple/no face/poor quality/invalid score/stale reset; no gaze/eye emotion inference") } diff --git a/tests/expression/FaceDiagnosticsCheck.kt b/tests/expression/FaceDiagnosticsCheck.kt new file mode 100644 index 0000000..9259ae9 --- /dev/null +++ b/tests/expression/FaceDiagnosticsCheck.kt @@ -0,0 +1,33 @@ +import com.gorios.lanvoice.expression.* + +fun main() { + val camera = CameraAnalysisDiagnostics() + check(camera.snapshot().reason == FaceCueReason.NO_FRAME) + var summaries = 0 + for (time in 0L..600_000L step 100) { + camera.received() + camera.processed(0, FaceCueObservation(reason = FaceCueReason.NO_FACE), 8) + if (camera.summary(time) != null) summaries++ + } + check(summaries == 61) // 10Hz samples, <=1 summary/10s including first. + check(camera.snapshot().received == 6001 && camera.snapshot().processed == 6001) + check(camera.snapshot().faceCount == 0 && camera.snapshot().reason == FaceCueReason.NO_FACE) + camera.processed(1, FaceCueObservation(FaceCue.SMILING, .9f, 900, 0, FaceCueReason.STABLE), 12) + camera.failed(CameraFailure.ANALYSIS) + check(camera.snapshot().cue == FaceCue.SMILING && camera.snapshot().failures == 1) + check(camera.summary(600_001) == null) + val final = checkNotNull(camera.summary(600_001, force = true)) + check("failure=analysis" in final && "cue=smiling" in final) + check(listOf("landmark", "blendshape", "image", "prompt", "reply").none { it in final }) + val send = FaceTransmissionDiagnostics() + check(send.snapshot().reason == FaceSendReason.SHARING_OFF) + send.record(FaceSendReason.NO_STABLE_CUE) + check(send.snapshot().attempts == 0) + send.record(FaceSendReason.SENT, FaceCue.SMILING) + send.record(FaceSendReason.CLEARED) + send.record(FaceSendReason.SEND_FAILED) + send.record(FaceSendReason.STALE) + check(send.snapshot().attempts == 3 && send.snapshot().sent == 1 && send.snapshot().clears == 1 && send.snapshot().failures == 1) + check(send.summary(0) != null && send.summary(9999) == null && send.summary(10000) != null) + println("PASS: enum-only camera/frame/send snapshots, failure counters, 10s rate bound, no-face/stable/stale/clear accounting") +} diff --git a/tests/session/ConnectionCheck.kt b/tests/session/ConnectionCheck.kt index f66fa4c..5408a5b 100644 --- a/tests/session/ConnectionCheck.kt +++ b/tests/session/ConnectionCheck.kt @@ -481,6 +481,7 @@ fun runChecks() { } fun main() { + checkFaceTransmission() run { val normal = com.gorios.lanvoice.dialogue.ReplyEmotion.fromWire(2L, 1L, "neutral", 0, "model")!! val fallback = com.gorios.lanvoice.dialogue.ReplyEmotion.fromWire(2L, 1L, "neutral", 0, "fallback", "invalid_intensity")!! diff --git a/tests/session/FaceSendCheck.kt b/tests/session/FaceSendCheck.kt new file mode 100644 index 0000000..ecdfac3 --- /dev/null +++ b/tests/session/FaceSendCheck.kt @@ -0,0 +1,37 @@ +import android.os.SystemClock +import com.gorios.lanvoice.audio.* +import com.gorios.lanvoice.expression.* +import com.gorios.lanvoice.net.* + +fun checkFaceTransmission() { + val session=VoiceSession("localhost",5011,{}) + fun set(name: String, value: Any) { session.javaClass.getDeclaredField(name).apply { isAccessible=true }.set(session,value) } + val dialogue=session.javaClass.getDeclaredField("dialogue").apply { isAccessible=true }.get(session) as DialogueClient + val socket=FakeSocket() + dialogue.setField("socket",socket);dialogue.setField("ready",true) + fun tick() { session.javaClass.getDeclaredMethod("sendFaceContext").apply { isAccessible=true }.invoke(session) } + set("foreground",true);set("faceSupported",true);set("hasTurn",true);set("currentTurn",7L) + set("state",VoiceUiState(connection=ConnectionStatus.CONNECTED,voiceActive=true,phase=VoicePhase.LISTENING)) + session.setFaceSharing(true) + tick() + check(session.faceDiagnosticsSnapshot().reason == FaceSendReason.NO_STABLE_CUE && socket.sent.isEmpty()) + session.observeFace(FaceCueObservation(reason=FaceCueReason.NO_FACE));tick() + check(session.faceDiagnosticsSnapshot().reason == FaceSendReason.NO_FACE) + val stable=FaceCueObservation(FaceCue.SMILING,.9f,900,SystemClock.elapsedRealtime(),FaceCueReason.STABLE) + session.observeFace(stable);tick() + check(session.faceDiagnosticsSnapshot().sent==1) + session.observeFace(stable.copy(observedAtMs=SystemClock.elapsedRealtime()-4000));tick() + check(session.faceDiagnosticsSnapshot().reason==FaceSendReason.STALE && session.faceDiagnosticsSnapshot().clears==1) + val count=socket.sent.size;tick();check(socket.sent.size==count) // clear only once, retain stale reason. + session.observeFace(stable.copy(observedAtMs=SystemClock.elapsedRealtime()));socket.acceptSend=false;tick() + check(session.faceDiagnosticsSnapshot().reason==FaceSendReason.SEND_FAILED) + socket.acceptSend=true;tick();session.setFaceSharing(false) + check(session.faceDiagnosticsSnapshot().reason==FaceSendReason.SHARING_OFF) + check(session.faceDiagnosticsSnapshot().clears==2) + session.setFaceSharing(true) + set("foreground",false);tick();check(session.faceDiagnosticsSnapshot().reason==FaceSendReason.BACKGROUND) + set("foreground",true);set("state",VoiceUiState(connection=ConnectionStatus.DISCONNECTED));tick() + check(session.faceDiagnosticsSnapshot().reason==FaceSendReason.NOT_CONNECTED) + session.setFaceSharing(false);dialogue.release() + println("PASS: real coordinator face sharing/no-face/stable-send/failure/TTL one-shot clear/background/disconnect; transport doubles") +}