From b521d368a5a5bab77599c860f651dce04b0de67e Mon Sep 17 00:00:00 2001 From: zenord Date: Mon, 12 Oct 2026 11:33:36 +0800 Subject: [PATCH] fix: preserve camera permission intent and distinguish unknown reply expression --- app/build.gradle | 4 +- .../java/com/gorios/lanvoice/MainActivity.kt | 66 ++++++++++++++----- .../com/gorios/lanvoice/audio/VoiceSession.kt | 54 +++++++++++++-- .../lanvoice/diag/DiagnosticReportUpload.kt | 22 +++++++ .../gorios/lanvoice/dialogue/ReplyEmotion.kt | 25 ++++++- .../expression/CameraPermissionGate.kt | 46 +++++++++++++ .../expression/ExpressionController.kt | 19 +++--- docs/CAMERA_EMOTION_051.md | 58 ++++++++++++++++ docs/PLAN.md | 9 +++ gateway/README.md | 3 + gateway/SOURCE_MANIFEST.json | 63 ++++++++++++++---- gateway/gateway.py | 20 +++++- gateway/reply_emotion.py | 48 +++++++++----- gateway/tests/test_debug.py | 11 ++++ gateway/tests/test_gateway_emotion.py | 45 +++++++++++++ gateway/tests/test_reply_emotion.py | 31 +++++++++ scripts/check-expression-rules.sh | 5 +- scripts/deploy-gateway-source.py | 8 +-- scripts/finalize-emotion-release.sh | 17 ++--- scripts/package-emotion-release.sh | 9 +-- scripts/probe-reply-emotion.py | 10 ++- scripts/update-gateway-manifest.py | 2 +- tests/expression/CameraPermissionCheck.kt | 31 +++++++++ tests/protocol/ProtocolCheck.kt | 6 +- tests/session/ConnectionCheck.kt | 31 +++++++-- tests/session/ProtocolEvents.kt | 2 +- 26 files changed, 544 insertions(+), 101 deletions(-) create mode 100644 app/src/main/java/com/gorios/lanvoice/expression/CameraPermissionGate.kt create mode 100644 docs/CAMERA_EMOTION_051.md create mode 100644 tests/expression/CameraPermissionCheck.kt diff --git a/app/build.gradle b/app/build.gradle index 2e72b58..45a5d2f 100644 --- a/app/build.gradle +++ b/app/build.gradle @@ -45,8 +45,8 @@ android { applicationId 'com.gorios.lanvoice' minSdk 26 targetSdk 34 - versionCode 8 - versionName '0.5.0' + versionCode 9 + versionName '0.5.1' ndk { abiFilters 'arm64-v8a' } } compileOptions { sourceCompatibility JavaVersion.VERSION_17; targetCompatibility JavaVersion.VERSION_17 } diff --git a/app/src/main/java/com/gorios/lanvoice/MainActivity.kt b/app/src/main/java/com/gorios/lanvoice/MainActivity.kt index 1da7b08..44fcbbb 100644 --- a/app/src/main/java/com/gorios/lanvoice/MainActivity.kt +++ b/app/src/main/java/com/gorios/lanvoice/MainActivity.kt @@ -47,6 +47,7 @@ import com.gorios.lanvoice.diag.DiagnosticReportInfo import com.gorios.lanvoice.diag.DiagnosticReportUpload import com.gorios.lanvoice.net.ConnectionStatus import com.gorios.lanvoice.net.DebugLogUpload +import com.gorios.lanvoice.expression.CameraPermissionGate import com.gorios.lanvoice.expression.ExpressionController import com.gorios.lanvoice.expression.ExpressionControls import com.gorios.lanvoice.expression.ExpressionStatus @@ -65,13 +66,11 @@ class MainActivity : ComponentActivity() { private var pendingStart = false private var expressionState by mutableStateOf(ExpressionUiState()) private lateinit var expressions: ExpressionController - private var pendingCamera = false + private val cameraGate = CameraPermissionGate() private var inForeground = false private val cameraPermission = registerForActivityResult(ActivityResultContracts.RequestPermission()) { granted -> - val shouldStart = pendingCamera && inForeground - pendingCamera = false - if (granted && shouldStart) expressions.start() - else if (!granted) expressions.permissionDenied() + DebugLogUpload.log("audio", "camera permission_result granted=$granted foreground=$inForeground") + cameraAction(cameraGate.permissionResult(granted)) } private val microphonePermission = registerForActivityResult(ActivityResultContracts.RequestPermission()) { granted -> DebugLogUpload.log("audio", "microphone permission granted=$granted foreground=$inForeground") @@ -99,7 +98,10 @@ class MainActivity : ComponentActivity() { onVoiceStopped = audioOutput::release, ) expressions = ExpressionController(this, this, - onState = { expressionState = it }, onFaceCue = session::observeFace) + onState = { + if (expressionState.status != it.status) DebugLogUpload.log("audio", "camera state=${it.status.name.lowercase()}") + expressionState = it + }, onFaceCue = session::observeFace) setContent { Home( state, ::toggleVoice, session::interrupt, expressionState, ::toggleExpressions, @@ -117,6 +119,14 @@ class MainActivity : ComponentActivity() { DiagnosticReportUpload.send( DiagnosticReportInfo( appVersion = appVersion, + versionCode = packageManager.getPackageInfo(packageName, 0).versionCode, + cameraGranted = checkSelfPermission(Manifest.permission.CAMERA) == PackageManager.PERMISSION_GRANTED, + cameraStatus = expressionState.status, + cameraPermissionPending = cameraGate.permissionPending, + faceSharing = shareFace, + rolePlaying = state.phase == VoicePhase.ANSWERING, + role = state.replyEmotion.takeIf { it.turnId != null }, + previousRole = state.previousReplyEmotion, device = "${Build.MANUFACTURER} ${Build.MODEL}", androidApi = Build.VERSION.SDK_INT, connection = state.connection.name, @@ -135,15 +145,30 @@ class MainActivity : ComponentActivity() { } private fun toggleExpressions() { - if (!inForeground) return - if (expressionState.status == ExpressionStatus.STARTING || expressionState.status == ExpressionStatus.ACTIVE) { - pendingCamera = false - expressions.stop() - } else if (checkSelfPermission(Manifest.permission.CAMERA) == PackageManager.PERMISSION_GRANTED) { - expressions.start() - } else if (!pendingCamera) { - pendingCamera = true - cameraPermission.launch(Manifest.permission.CAMERA) + val granted = checkSelfPermission(Manifest.permission.CAMERA) == PackageManager.PERMISSION_GRANTED + val running = expressionState.status in setOf(ExpressionStatus.STARTING, ExpressionStatus.ACTIVE) + DebugLogUpload.log("audio", "camera click foreground=$inForeground granted=$granted running=$running pending=${cameraGate.permissionPending}") + cameraAction(cameraGate.click(running, granted)) + } + + private fun cameraAction(action: CameraPermissionGate.Action) { + when (action) { + CameraPermissionGate.Action.REQUEST_PERMISSION -> { + DebugLogUpload.log("audio", "camera permission_request") + cameraPermission.launch(Manifest.permission.CAMERA) + } + CameraPermissionGate.Action.START -> { + if (inForeground) { + DebugLogUpload.log("audio", "camera start_attempt") + expressions.start() + } + } + CameraPermissionGate.Action.STOP -> { + DebugLogUpload.log("audio", "camera stop reason=user") + expressions.stop() + } + CameraPermissionGate.Action.DENIED -> expressions.permissionDenied() + CameraPermissionGate.Action.NONE -> Unit } } @@ -174,14 +199,16 @@ class MainActivity : ComponentActivity() { inForeground = true DebugLogUpload.log("connect", "activity onStart") session.foreground() + cameraAction(cameraGate.onForeground()) startPendingVoice() } override fun onStop() { inForeground = false - val permissionInFlight = pendingStart || pendingCamera + val permissionInFlight = pendingStart || cameraGate.permissionPending DebugLogUpload.log("connect", "activity onStop permission=$permissionInFlight changingConfig=$isChangingConfigurations") - pendingCamera = false + cameraGate.onBackground() + DebugLogUpload.log("audio", "camera stop reason=background") expressions.stop() if (!permissionInFlight) pendingStart = false session.background( @@ -192,6 +219,8 @@ class MainActivity : ComponentActivity() { } override fun onDestroy() { + cameraGate.release() + DebugLogUpload.log("audio", "camera stop reason=release") expressions.release() DebugLogUpload.log("connect", "activity onDestroy changingConfig=$isChangingConfigurations") session.release() @@ -255,7 +284,8 @@ fun Home( ) } ExpressionControls(expressionState, onToggleExpressions, shareFace, onShareFace) - Text("角色:${state.replyEmotion.label}(角色表达)", color = gold, fontSize = 13.sp) + Text("角色:${state.roleLabel}(角色表达)", color = gold, fontSize = 13.sp) + state.previousReplyEmotion?.let { Text("上一轮:${it.label}", color = muted, fontSize = 12.sp) } } Column( modifier = Modifier.padding(top = 24.dp, bottom = 12.dp), 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 de3330d..2c83b8b 100644 --- a/app/src/main/java/com/gorios/lanvoice/audio/VoiceSession.kt +++ b/app/src/main/java/com/gorios/lanvoice/audio/VoiceSession.kt @@ -24,7 +24,14 @@ data class VoiceUiState( val aec: AecAvailability = AecAvailability.UNKNOWN, val guidance: String? = null, val replyEmotion: ReplyEmotion = ReplyEmotion(), -) + val previousReplyEmotion: ReplyEmotion? = null, +) { + val roleLabel: String get() = when { + phase == VoicePhase.ANSWERING && replyEmotion.turnId != null -> replyEmotion.label + voiceActive && phase in setOf(VoicePhase.RECOGNIZING, VoicePhase.THINKING, VoicePhase.ANSWERING) -> "等待回复" + else -> "当前未播放" + } +} /** Main-thread coordinator; both audio workers add their own epochs to the socket's fence. */ class VoiceSession( @@ -71,6 +78,7 @@ class VoiceSession( if (isActive() && playbackIsCurrent(turn, epoch) && blockedTurn != turn) { diagnostic("playback drained turn=$turn") if (dialogue.playbackDrained(turn)) { + resetReply("drained") emotionEndedTurn = turn update(state.copy(phase = VoicePhase.LISTENING, replyEmotion = ReplyEmotion())) startCapture() @@ -162,6 +170,7 @@ class VoiceSession( fun stopVoice(sendControls: Boolean = true) { checkMainThread() + resetReply("stop") val wasActive = state.voiceActive stopCapture() playback.interrupt() @@ -179,6 +188,7 @@ class VoiceSession( fun interrupt() { checkMainThread() if (!isActive()) return + resetReply("interrupt") blockedTurn = currentTurn playback.interrupt() // Silence locally before waiting for the server's abort event. if (dialogue.abort(currentTurn)) { @@ -225,6 +235,7 @@ class VoiceSession( private fun onConnection(connection: ConnectionStatus, reason: String) { diagnostic("connection ${state.connection.name} -> ${connection.name} reason=$reason", "connect") if (connection != ConnectionStatus.CONNECTED) { + resetReply("disconnect") faceSupported = false faceSent = false faceCue = FaceCueObservation() @@ -291,6 +302,7 @@ class VoiceSession( private fun onEvent(event: ServerEvent) { val turn = (event.payload.opt("turn_id") as? Number)?.toLong() diagnostic("onEvent kind=${event.kind.name} turn_id=$turn") + if (event.kind == EventKind.REPLY_EMOTION) { receiveReply(event, turn); return } if (released || state.connection != ConnectionStatus.CONNECTED) { diagnostic("event ignored: connection=${state.connection.name} released=$released") return @@ -302,7 +314,6 @@ class VoiceSession( // An ABORT can announce the replacement turn. Remember the interrupted // turn before acceptTurn updates currentTurn and retires the old one. // An expression cannot announce/switch a turn. Other protocol events establish it first. - if (event.kind == EventKind.REPLY_EMOTION && (!hasTurn || turn != currentTurn)) return val oldTurn = if (hasTurn) currentTurn else null if (turn != null && !acceptTurn(turn)) return val action = event.payload.optString("state", "").ifBlank { event.type.substringAfter('.', "") } @@ -338,11 +349,6 @@ class VoiceSession( EventKind.LLM -> if (isActive() && state.phase != VoicePhase.ANSWERING) { update(state.copy(phase = VoicePhase.THINKING)) } - EventKind.REPLY_EMOTION -> if (isActive() && blockedTurn != currentTurn && emotionEndedTurn != currentTurn) { - val emotion = ReplyEmotion.fromWire(event.payload.opt("turn_id"), event.payload.opt("seq"), - event.payload.opt("emotion"), event.payload.opt("intensity"), event.payload.opt("source")) ?: return - if (emotion.sequence > state.replyEmotion.sequence) update(state.copy(replyEmotion = emotion)) - } EventKind.TTS -> if (isActive() && blockedTurn != currentTurn) { // The gateway sends start BEFORE LLM generation and also tts.metrics. // Only received PCM means there is an answer to play. @@ -355,6 +361,7 @@ class VoiceSession( } } EventKind.ABORT -> { + resetReply("abort") // listen_start aborts the previous reply while announcing the NEW turn. // The server's following LISTEN start and TTS belong to that new turn. val reason = event.payload.optString("reason") @@ -399,6 +406,7 @@ class VoiceSession( } // IDs identify turns; do not assume the server allocates them in numeric order. if (!hasTurn || id != currentTurn) { + resetReply("new_turn") val resumeCapture = capturing if (resumeCapture) stopCapture() // Invalidate already queued PCM before resetting seq. if (hasTurn) retiredTurns.add(currentTurn) @@ -416,6 +424,38 @@ class VoiceSession( return true } + private fun receiveReply(event: ServerEvent, turn: Long?) { + val reason = when { + released -> "released" + state.connection != ConnectionStatus.CONNECTED -> "disconnected" + !hasTurn -> "no_turn" + turn in retiredTurns -> "old_turn" + turn != currentTurn -> "unannounced_turn" + !isActive() -> "inactive" + blockedTurn == currentTurn -> "blocked_turn" + emotionEndedTurn == currentTurn -> "drained" + else -> null + } + if (reason != null) { diagnostic("role ignore reason=$reason turn=$turn"); return } + val expression = ReplyEmotion.fromWire(event.payload.opt("turn_id"), event.payload.opt("seq"), + event.payload.opt("emotion"), event.payload.opt("intensity"), event.payload.opt("source"), + event.payload.opt("reason"), event.payload.opt("parse_branch"), event.payload.opt("finish_reason")) + if (expression == null) { diagnostic("role ignore reason=invalid_identity turn=$turn"); return } + if (expression.sequence <= state.replyEmotion.sequence) { + diagnostic("role ignore reason=old_seq turn=$turn seq=${expression.sequence}"); return + } + update(state.copy(replyEmotion = expression)) + diagnostic("role apply turn=$turn seq=${expression.sequence} emotion=${expression.emotion.wire} intensity=${expression.intensity} source=${expression.source.name.lowercase()} reason=${expression.reason.wire} branch=${expression.parseBranch.wire} finish=${expression.finishReason.wire}") + } + + private fun resetReply(reason: String) { + val expression = state.replyEmotion + val played = preparedPlaybackTurn == currentTurn && expression.turnId == currentTurn + if (expression.turnId != null) diagnostic("role reset reason=$reason turn=${expression.turnId} played=$played") + update(state.copy(replyEmotion = ReplyEmotion(), + previousReplyEmotion = if (played) expression else state.previousReplyEmotion)) + } + private fun failAudio(message: String, error: Exception) { diagnostic("audio failed: ${error.javaClass.simpleName} connection=${state.connection.name}", "error") Log.w(TAG, message, error) 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 79f3512..9a06509 100644 --- a/app/src/main/java/com/gorios/lanvoice/diag/DiagnosticReportUpload.kt +++ b/app/src/main/java/com/gorios/lanvoice/diag/DiagnosticReportUpload.kt @@ -1,5 +1,7 @@ package com.gorios.lanvoice.diag +import com.gorios.lanvoice.dialogue.ReplyEmotion +import com.gorios.lanvoice.expression.ExpressionStatus import okhttp3.Call import okhttp3.Callback import okhttp3.ConnectionPool @@ -25,6 +27,14 @@ data class DiagnosticReportInfo( val voiceActive: Boolean, val phase: String, val aec: String, + val versionCode: Int = 0, + val cameraGranted: Boolean = false, + val cameraStatus: ExpressionStatus = ExpressionStatus.OFF, + val cameraPermissionPending: Boolean = false, + val faceSharing: Boolean = false, + val rolePlaying: Boolean = false, + val role: ReplyEmotion? = null, + val previousRole: ReplyEmotion? = null, ) /** Explicit user submission, isolated from both voice traffic and per-entry debug uploads. */ @@ -48,6 +58,12 @@ object DiagnosticReportUpload { .build() } + private fun roleMetadata(role: ReplyEmotion?): Any = role?.let { + JSONObject().put("turn_id", it.turnId).put("seq", it.sequence).put("emotion", it.emotion.wire) + .put("intensity", it.intensity).put("source", it.source.name.lowercase()).put("reason", it.reason.wire) + .put("parse_branch", it.parseBranch.wire).put("finish_reason", it.finishReason.wire) + } ?: JSONObject.NULL + /** Result arrives on an OkHttp worker (or immediately if setup fails). */ fun send(info: DiagnosticReportInfo, onResult: (Boolean) -> Unit) { if (!sending.compareAndSet(false, true)) { @@ -72,6 +88,12 @@ object DiagnosticReportUpload { .put("voice_active", info.voiceActive) .put("phase", info.phase) .put("aec", info.aec) + .put("version_code", info.versionCode) + .put("camera", JSONObject().put("granted", info.cameraGranted).put("status", info.cameraStatus.name.lowercase()) + .put("permission_pending", info.cameraPermissionPending).put("face_sharing", info.faceSharing)) + .put("role_playing", info.rolePlaying) + .put("role_active", roleMetadata(info.role)) + .put("role_previous", roleMetadata(info.previousRole)) .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/dialogue/ReplyEmotion.kt b/app/src/main/java/com/gorios/lanvoice/dialogue/ReplyEmotion.kt index b335363..26d8672 100644 --- a/app/src/main/java/com/gorios/lanvoice/dialogue/ReplyEmotion.kt +++ b/app/src/main/java/com/gorios/lanvoice/dialogue/ReplyEmotion.kt @@ -5,16 +5,32 @@ enum class RoleEmotion(val wire: String, val label: String) { NEUTRAL("neutral", "中立"), HAPPY("happy", "高兴"), ANGRY("angry", "生气"), SAD("sad", "难过") } enum class EmotionSource { MODEL, FALLBACK } +enum class EmotionReason(val wire: String) { + NONE("none"), MISSING_FIELDS("missing_fields"), UNEXPECTED_FIELDS("unexpected_fields"), + INVALID_EMOTION("invalid_emotion"), INVALID_INTENSITY("invalid_intensity"), INVALID_REPLY("invalid_reply"), + NON_JSON("non_json"), INVALID_JSON("invalid_json"), TRUNCATED("truncated"), INPUT_LIMIT("input_limit"), UNKNOWN("unknown") +} +enum class ParseBranch(val wire: String) { + STRICT_JSON("strict_json"), FENCED_JSON("fenced_json"), JSON_REPLY("json_reply"), ALTERNATE_FIELD("alternate_field"), + QUOTED_REPLY("quoted_reply"), REPAIRED_STRING("repaired_string"), PLAIN_TEXT("plain_text"), SAFE_REPLY("safe_reply"), UNKNOWN("unknown") +} +enum class FinishReason(val wire: String) { + STOP("stop"), LENGTH("length"), CONTENT_FILTER("content_filter"), TOOL_CALLS("tool_calls"), FUNCTION_CALL("function_call"), + NOT_PROVIDED("not_provided"), UNKNOWN("unknown") +} data class ReplyEmotion( val emotion: RoleEmotion = RoleEmotion.NEUTRAL, val intensity: Int = 0, val source: EmotionSource = EmotionSource.FALLBACK, val turnId: Long? = null, val sequence: Long = -1, + val reason: EmotionReason = EmotionReason.UNKNOWN, + val parseBranch: ParseBranch = ParseBranch.UNKNOWN, + val finishReason: FinishReason = FinishReason.NOT_PROVIDED, ) { - val label: String get() = emotion.label + when (intensity) { 1 -> "·轻度"; 2 -> "·明显"; else -> "" } + val label: String get() = if (source == EmotionSource.FALLBACK) "表达未判定(格式回退)" else emotion.label + when (intensity) { 1 -> "·轻度"; 2 -> "·明显"; else -> "" } companion object { - fun fromWire(turn: Any?, seq: Any?, emotion: Any?, intensity: Any?, source: Any?): ReplyEmotion? { + fun fromWire(turn: Any?, seq: Any?, emotion: Any?, intensity: Any?, source: Any?, reason: Any? = null, branch: Any? = null, finish: Any? = null): ReplyEmotion? { fun integer(value: Any?): Long? = when (value) { is Int -> value.toLong(); is Long -> value; else -> null } val id = integer(turn)?.takeIf { it in 0..0xffff_ffffL } ?: return null val sequence = integer(seq)?.takeIf { it >= 0 } ?: return null @@ -26,7 +42,10 @@ data class ReplyEmotion( origin == EmotionSource.FALLBACK && kind != RoleEmotion.NEUTRAL) { return ReplyEmotion(turnId = id, sequence = sequence) } - return ReplyEmotion(kind, strength!!.toInt(), origin, id, sequence) + return ReplyEmotion(kind, strength!!.toInt(), origin, id, sequence, + EmotionReason.entries.firstOrNull { it.wire == reason } ?: if (origin == EmotionSource.MODEL) EmotionReason.NONE else EmotionReason.UNKNOWN, + ParseBranch.entries.firstOrNull { it.wire == branch } ?: ParseBranch.UNKNOWN, + FinishReason.entries.firstOrNull { it.wire == finish } ?: FinishReason.NOT_PROVIDED) } } } diff --git a/app/src/main/java/com/gorios/lanvoice/expression/CameraPermissionGate.kt b/app/src/main/java/com/gorios/lanvoice/expression/CameraPermissionGate.kt new file mode 100644 index 0000000..cf412c1 --- /dev/null +++ b/app/src/main/java/com/gorios/lanvoice/expression/CameraPermissionGate.kt @@ -0,0 +1,46 @@ +package com.gorios.lanvoice.expression + +/** Explicit, one-shot camera intent. A permission result may arrive before or after onStart. */ +class CameraPermissionGate { + enum class Action { NONE, REQUEST_PERMISSION, START, STOP, DENIED } + var permissionPending = false + private set + private var foreground = false + private var requested = false + private var approved = false + private var released = false + + fun onForeground(): Action { foreground = true; return consumeStart() } + fun onBackground() { + foreground = false + // Retain only a user-requested authorization continuation, never an active camera. + if (!permissionPending && !approved) requested = false + } + fun click(running: Boolean, granted: Boolean): Action { + if (released || !foreground) return Action.NONE + if (running || requested) { + requested = false; approved = false + return Action.STOP + } + if (permissionPending) return Action.NONE + requested = true + if (granted) { approved = true; return consumeStart() } + permissionPending = true + return Action.REQUEST_PERMISSION + } + fun permissionResult(granted: Boolean): Action { + if (released || !permissionPending) return Action.NONE + permissionPending = false + if (!granted) { requested = false; approved = false; return Action.DENIED } + if (requested) approved = true + return consumeStart() + } + fun release() { released = true; requested = false; approved = false; permissionPending = false } + private fun consumeStart(): Action { + if (!released && foreground && requested && approved) { + requested = false; approved = false + return Action.START + } + return Action.NONE + } +} 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 3f3fa68..078265e 100644 --- a/app/src/main/java/com/gorios/lanvoice/expression/ExpressionController.kt +++ b/app/src/main/java/com/gorios/lanvoice/expression/ExpressionController.kt @@ -10,6 +10,7 @@ import android.os.Looper import android.os.SystemClock import android.util.Size import android.view.WindowManager +import com.gorios.lanvoice.net.DebugLogUpload import androidx.camera.core.CameraSelector import androidx.camera.core.ImageAnalysis import androidx.camera.core.ImageProxy @@ -78,9 +79,9 @@ class ExpressionController( run.landmarker = FaceLandmarker.createFromOptions(appContext, options) main.post { if (isCurrent(run)) bind(run) } } catch (_: Exception) { - fail(run, "表情分析暂不可用,请检查模型和设备支持;语音功能不受影响。") + fail(run, "表情分析暂不可用,请检查模型和设备支持;语音功能不受影响。", "model_load") } catch (_: LinkageError) { - fail(run, "设备暂不支持表情分析,语音功能仍可使用。") + fail(run, "设备暂不支持表情分析,语音功能仍可使用。", "device_support") } } } @@ -94,6 +95,7 @@ class ExpressionController( fun permissionDenied() { checkMainThread() + DebugLogUpload.log("audio", "camera denied") stopCurrent() onFaceCue(FaceCueObservation()) if (!released) onState(ExpressionUiState(guidance = @@ -117,7 +119,7 @@ class ExpressionController( try { val provider = future.get() if (!provider.hasCamera(CameraSelector.DEFAULT_FRONT_CAMERA)) { - fail(run, "未找到前置摄像头,语音功能仍可使用。") + fail(run, "未找到前置摄像头,语音功能仍可使用。", "no_front_camera") return@addListener } val analysis = ImageAnalysis.Builder() @@ -134,11 +136,11 @@ class ExpressionController( provider.bindToLifecycle(lifecycleOwner, CameraSelector.DEFAULT_FRONT_CAMERA, analysis) onState(ExpressionUiState(ExpressionStatus.ACTIVE)) } catch (_: Exception) { - fail(run, "摄像头暂不可用,请稍后重试;语音功能不受影响。") + fail(run, "摄像头暂不可用,请稍后重试;语音功能不受影响。", "camera_bind") } }, { action -> main.post(action) }) } catch (_: Exception) { - fail(run, "摄像头暂不可用,请稍后重试;语音功能不受影响。") + fail(run, "摄像头暂不可用,请稍后重试;语音功能不受影响。", "camera_bind") } } @@ -185,20 +187,21 @@ class ExpressionController( } } catch (_: Exception) { // Never log exceptions from inference, frames, coefficients or head pose. - fail(run, "表情分析已停止,请重新开启;语音功能不受影响。") + fail(run, "表情分析已停止,请重新开启;语音功能不受影响。", "analysis") } catch (_: LinkageError) { - fail(run, "设备暂不支持表情分析,语音功能仍可使用。") + fail(run, "设备暂不支持表情分析,语音功能仍可使用。", "device_support") } finally { bitmap?.recycle() image.close() // Includes throttle/stop/error paths, so CameraX never retains the proxy. } } - private fun fail(run: Run, guidance: String) { + private fun fail(run: Run, guidance: String, reason: String) { // Prevent another scheduled frame from running before main unbinds the camera. run.active = false main.post { if (!released && current === run) { + DebugLogUpload.log("error", "camera failure=$reason") stopCurrent() onFaceCue(FaceCueObservation()) onState(ExpressionUiState(ExpressionStatus.UNAVAILABLE, guidance = guidance)) diff --git a/docs/CAMERA_EMOTION_051.md b/docs/CAMERA_EMOTION_051.md new file mode 100644 index 0000000..a737e89 --- /dev/null +++ b/docs/CAMERA_EMOTION_051.md @@ -0,0 +1,58 @@ +# 0.5.1 相机授权与角色表达诊断 + +基线是已发布0.5.0/code8,Git d43c7d4e809a5a6b18ca9f28c8163a2f9ad34c7f。此次在同一专属session核对干净工作区、远端代码hash与main后备份源代码;不换provider、不增模型、不改prompt/160-token预算、不修改TTS音色或参数。完整canonical gateway/同仓维护,manifest保留provider来源及实际0.5.0部署hash。 + +## 已确认与未知 + +2026-10-12北京时间11:02:07收到的0.5.0报告确认为Xiaomi MI MAX 3/API29。轮2 source=model但未记录标签;轮3/4 source=fallback,按原代码neutral/0。三轮均收到情绪事件、正常drained;提交时已停止语音。报告没有相机点击/权限结果/分析状态、具体fallback分支或finish_reason,不能追溯两轮fallback的原因,也不能断言用户没点击相机。没有读取用户聊天正文或额外调用付费模型来猜原因。 + +相机代码存在确定生命周期风险:原onStop无条件清pendingCamera,部分ROM的权限界面若导致onStop,授权回调便无法启动。该报告未记录这一生命周期路径,所以这是修复已发现风险,不是宣称已证明此次没弹窗的根因。没有发现可据此确定的合法七状态parser错误;原严格字段集合与整数强度验证继续保留,不盲目放宽或增加重试。 + +## 相机 + +CameraPermissionGate保留一次明确点击产生的授权意图,授权结果在onStart之前或之后到达都只在前台启动一次。拒绝、取消、释放后不启动;普通退后台停止相机、不自动恢复;默认off。未授权点击“开启表情线索”才请求CAMERA;已有授权直接启动。与“将表情线索用于对话”明确分开,后者仍只控制共享。申请结果回调丢失或Activity重建不会自行猜测开启相机。 + +记录固定camera click、permission_request、permission_result、start_attempt、状态off/starting/active/unavailable、stop(user/background/release)、denied与failure(model_load/device_support/no_front_camera/camera_bind/analysis)。不记录图像、landmarks、系数、异常内容或原始face数据。报告增加version_code及camera的granted/status/permission_pending/face_sharing。原相机权限与hardware feature required=false不变,拒绝时仍引导用户在系统应用权限开启。 + +## 角色表达 + +协议仍有neutral/0、happy/angry/sad各1/2七状态;fallback在传输上安全返回neutral/0。0.5.1显示区分: + +- 有PCM进入回答/播放阶段且source=model:显示“中立”“高兴·轻度”等模型验证结果。 +- 同阶段source=fallback:显示“表达未判定(格式回退)”,不冒充模型中立。 +- 思考/等待首PCM:显示“等待回复”;其它无活动播放状态:显示“当前未播放”。 +- drained/stop/abort/断线/新轮清活动表达,将已进入播放阶段的表达保留为“上一轮:…”;未播放的新轮或迟到/旧turn事件不覆盖上一轮。上一轮不是长期情绪或用户情绪诊断。 + +仅接收已建立当前turn的事件,拒绝旧轮/未声明轮/非活动/阻断/drained/无效身份/旧seq。有限role apply日志记录turn/seq/emotion/intensity/source/reason/parse_branch/finish;ignore与reset记录固定原因。报告包含有限role_active/role_previous和role_playing,无正文。 + +## 服务端诊断与兼容 + +reply.emotion新增可选reason、parse_branch、finish_reason和usage;老客户端忽略附加字段并按原七状态处理,旧诊断报告继续接受。metrics/服务器metadata记录相同有限结果、实际max_tokens和可选prompt_tokens/completion_tokens/total_tokens。接口不提供usage或finish_reason时分别记录空对象/not_provided,绝不编造。 + +reason固定为none、missing_fields、unexpected_fields、invalid_emotion、invalid_intensity、invalid_reply、non_json、invalid_json、truncated、input_limit。恢复分支固定为strict_json、fenced_json、json_reply、alternate_field、quoted_reply、repaired_string、plain_text、safe_reply。损坏结构本身不等于截断:只有失败解析且接口确切finish_reason=length才标truncated;边界上完整合法JSON仍可source=model,同时保留length证据。恢复正文后仍只把正文送入原单个TTS generator,不保存原始LLM包/prompt或进行第二次请求。 + +新增诊断没有聊天正文、原始LLM包/prompt、凭据或face原始数据。既有TTS诊断metadata也从input正文改为input_chars;原会话历史、reply-only TTS输入与原授权PCM诊断功能继续其原有用途。旧诊断文件不改写,不以旧文件缺新字段猜测原因。 + +## 验证与交付 + +本地生产coordinator/protocol/播放/采集与设备transport doubles回归、face规则、camera授权状态机及parser6项通过;覆盖七状态、缺/非法类型/损坏/长度证据、未播放/model neutral/fallback、seq/turn/drained与上一轮隔离。69项gateway全量测试在SPARK既有venv临时源码树通过,包括读取并核对既有Silero artifact;无线上模型请求或容器控制。旧/新report兼容与诊断metadata不存正文均有回归。真实Android Kotlin/Compose编译与APK结果在完成后追加。 + +部署继续核对源码/环境关系hash、备份完整代码/权限及仅服务器保存的私有unit/env;busy或并发修改拒绝操作,仅必要restartgateway,失败精确回退。模型/证书/token不动。有限公开短音频只验证协议、单TTS与非空PCM,不代表真人可听或相机真机授权已验收。旧两轮fallback根因仍未知;新诊断用于之后的实际报告,不调整中立默认或强制情绪分布。 + +版本递增0.5.1/code9,APK归档v051,保留v050/v040,沿用build.sh/JDK17/toolchain。回退为python3 scripts/rollback-gateway-source.py(当前部署hash、unit/env关系与busy必须匹配),仅恢复此次备份并restartgateway。 + + +## 本 session 实际部署与协议结果 + +真实Android Kotlin/Compose编译通过。部署再次运行69项gateway全量测试(0.982秒,含Silero),备份路径 `/home/gorios-spark-2/lan-voice/.runtime/backups/voice-v051-20261012-112944`。只restartgateway,源码hash、unit/env加载关系精确匹配;health ok。当前仍为http://127.0.0.1:8888/v1、qwen3.8-27b、enable_thinking=false;provider模块本次未改。 + +一次公开短音频ASR→Qwen→原TTS协议核验通过:happy/1/source=model/reason=none/parse_branch=strict_json/finish_reason=stop,实际预算160。此接口本轮未提供stream token usage,记录空对象而非推算。208帧399360B非静音PCM,独立情绪事件在首PCM前,单TTS、drained确认与合成face快照通过;未使用手机摄像头。 + +capture→首PCM2212.28ms,结构等待1756.43ms,parse0.24ms;backend总时长6238.68ms。仅一轮有限样本,不能证明稳定性、七状态语义准确率或零延迟。它没有复现fallback,旧报告轮3/4的具体原因仍未知。也未把token预算改大或对同一请求自动重试。 + + +## APK结果 + +既有build.sh/JDK17 assembleDebug成功;aapt确认versionName0.5.1/code9、minSdk26、arm64。apksigner验签通过,签名证书与原0.4.0/0.5.0一致;两个旧APK原hash均核对保留。新APK 31449676字节,SHA256 `7d089517cde3241d79c971d6260ed8f71af86851e2623fdc66e51fb1583ae77f`,下载 `http://192.168.31.124:8080/lan-voice-v051-arm64-debug.apk` 返回HTTP200、下载字节数与SHA256和本地一致。 + +此为debug APK,尚未安装到MI MAX3测试权限弹窗/相机分析、真实标签渲染或出声。诊断按钮保留;新的公开短音频/设备doubles不代替上述真机验收。 diff --git a/docs/PLAN.md b/docs/PLAN.md index e7140f1..8441277 100644 --- a/docs/PLAN.md +++ b/docs/PLAN.md @@ -216,3 +216,12 @@ APK 侧实现、编译及依赖校验元数据固化已完成。用户在外部 - 64项gateway全量回归通过(包括读取既有Silero artifact测试);客户端生产coordinator/播放/采集/protocol与Android doubles、表情规则和parser通过。当前Qwen和保存的Doubao各两个公开问题结构接口HTTP200;参数隔离、header-only key、无schema/自动fallback均验证,alias非真实权重证明。 - 本session受控部署完整Python源码/tests,源码hash/busy/env关系多次检查,完整代码/权限/私有unit/env只在服务器备份,仅restartgateway,health ok。一次公开短音频链路:14字STT/23字reply/单TTS/216帧414720B非静音PCM/情绪先于PCM/drained与face快照通过;capture→首PCM2426.19ms,结构等待1750.91ms,非零开销。 - 实际APK/签名/HTTP交付信息在 [REPLY_EMOTION_050.md](REPLY_EMOTION_050.md);真机可听、真人对话与原1011根因仍未验收,不以PCM/drained替代。所有开发/测试/部署/构建/Git在此独立session执行,无新agent/pane,运行模型/密钥/证书未改。 + + +## 15. 0.5.1 相机授权与角色表达诊断(2026-10-12) + +- 基于同session的MI MAX3/API29/0.5.0实际报告,已确认三轮情绪事件到达、两轮fallback及正常drained;没有旧输出/finish_reason可用于追溯fallback,根因不猜测。相机onStop清待启动标志是确定代码风险,此报告是否触发未知。 +- 修复一次相机授权意图在onStop/onStart之间的安全续接,只在前台启动,拒绝/取消/释放不启动、普通后台停相机/defaultoff。补有限相机与角色apply/ignore/reset日志及报告versionCode/状态字段,不记录图像/正文/原始face。 +- 播放中的模型neutral才显示中立;fallback显示表达未判定(格式回退);无播放显示等待回复/当前未播放,并保留上一轮已进入播放阶段的表达,旧turn不得覆盖。保持用户表情不是心理诊断、摄像头与分享独立。 +- 服务端记录固定reason/恢复分支/真实finish_reason/可选usage及有限最终表达,诊断metadata仅保留TTS input_chars。长度截断仅依实际length;原prompt/160预算/provider/TTS音色参数未改,单system/单请求/单generator。 +- 69项gateway全量测试、本地production coordinator与device doubles、parser、face规则与camera生命周期通过,真实Kotlin/Compose编译通过。受控网关部署后一次公开协议happy/1/model/strict_json/stop,208帧399360B PCM、单TTS/情绪先于PCM/drained通过;真实手机相机与播放仍需用户验收。版本0.5.1/code9,完整结果见 [CAMERA_EMOTION_051.md](CAMERA_EMOTION_051.md)。 diff --git a/gateway/README.md b/gateway/README.md index cb1bd96..5042860 100644 --- a/gateway/README.md +++ b/gateway/README.md @@ -25,3 +25,6 @@ The 0.5.0 canonical source adds `reply_emotion.py`: one-system structured provid `SOURCE_MANIFEST.json.provider_baseline` records the latest observed SPARK2 hashes before this merge, including gateway `d088bedcf5c0accd4712e06202f6ced8ab155aad57a5b05683724efa346326ce`. Deployment fences against these hashes, not the superseded historical patch. Historical `scripts/deploy-gateway.py` is disabled. The existing unit and private environment loading relationships are backed up only on the server and checked unchanged. All Python sources/tests and original modes are backed up; only gateway is restarted after isolated tests and repeated source/busy checks. Use `scripts/rollback-gateway-source.py` for this exact deployment. Portable archive checks skip only the omitted Silero artifact. On the existing server, run `python scripts/check-archive.py --vad-model /absolute/path/to/models/silero_vad.onnx` for the full suite, with checksum verification and an isolated read-only artifact link. This never downloads or changes a model or online service. + + +Release 0.5.1 adds finite parser reason/recovery branch, finish_reason and optional token usage diagnostics without changing provider, prompt, 160-token dialogue budget, TTS voice or request count. Damaged structure is called truncated only when the provider explicitly reported length. Existing 0.5.0 clients continue to receive neutral/0 for fallback; the new UI labels it undetermined, shows model neutral only during playback and retains the previous played reply separately. New TTS diagnostic metadata keeps input_chars instead of the speech body; existing conversation history and the actual reply-only TTS request retain their original function. Old diagnostic reports remain accepted. See ../docs/CAMERA_EMOTION_051.md. diff --git a/gateway/SOURCE_MANIFEST.json b/gateway/SOURCE_MANIFEST.json index c873c81..08d0a16 100644 --- a/gateway/SOURCE_MANIFEST.json +++ b/gateway/SOURCE_MANIFEST.json @@ -33,8 +33,8 @@ }, "gateway.py": { "source": "workspace:gateway/gateway.py", - "sha256": "d9215f99339de0667e830fbd4d3bff80ac5a61c85630cc4ecadcb52a4c33a0e5", - "bytes": 37391, + "sha256": "b8e64e9387fca05808fac61bd097ae179e996a2c7ccd33f23bb729a61693dd0d", + "bytes": 38559, "upstream_sha256": "d088bedcf5c0accd4712e06202f6ced8ab155aad57a5b05683724efa346326ce" }, "guest_sessions.py": { @@ -124,9 +124,10 @@ "upstream_sha256": "6dd818484a064dc3fc9efe5ca71cc11ffcd3a0dcc45ea4185065732dab0289cc" }, "tests/test_debug.py": { - "source": "tests/test_debug.py", - "sha256": "26f9e374354b714ab1a03b56af90bcbf32135711dc4f26e2c53eaa90c7f02ddd", - "bytes": 2837 + "source": "workspace:gateway/tests/test_debug.py", + "sha256": "7d1d7876c4106f3df0b84cf8f7e479afb4a30ca51264fb94fa288fdd8155883e", + "bytes": 3665, + "upstream_sha256": "26f9e374354b714ab1a03b56af90bcbf32135711dc4f26e2c53eaa90c7f02ddd" }, "tests/test_gateway.py": { "source": "tests/test_gateway.py", @@ -245,8 +246,8 @@ }, "README.md": { "source": "workspace:gateway/README.md", - "sha256": "808a77916a8ba477cd6d95ae255cc661239c97031760d83fe38ea43c571deb6d", - "bytes": 6666, + "sha256": "cc32a5d3cd21975ece637f467c5c2f4ca2bc6c90b3fd450a3da909a116b11d5e", + "bytes": 7397, "upstream_sha256": "799bc84308eb17d58987c5bee8ce3cf7617b4c52169d9307d344ac7d9996b6c5" }, "config/active_profile.json.example": { @@ -282,8 +283,9 @@ }, "reply_emotion.py": { "source": "workspace:gateway/reply_emotion.py", - "sha256": "488fbd24ff1ce7d3d4ab92257c8ccabafe24fc857e11c8486f54fa689276a565", - "bytes": 3114 + "sha256": "a2b6a1a51639d77368c200f2a6db8bb66fff1eebb4f60219d49da69ae402a8a2", + "bytes": 4005, + "upstream_sha256": "488fbd24ff1ce7d3d4ab92257c8ccabafe24fc857e11c8486f54fa689276a565" }, "scripts/check-archive.py": { "source": "workspace:gateway/scripts/check-archive.py", @@ -293,14 +295,14 @@ }, "tests/test_gateway_emotion.py": { "source": "workspace:gateway/tests/test_gateway_emotion.py", - "sha256": "fc01e9319263b93adb1cc93904d23a13a25965ddb0fcfbd9c3e14e39f4cf52a5", - "bytes": 4589, + "sha256": "e4da9a092e6ee19ef421a43a04cd2b6d12cb65f1b210946092dcad016c8816bb", + "bytes": 7923, "upstream_sha256": "86f22211e753e4b5ebfa11266e2e33eb2ea6b85707fbe8a988be6b8ff05f3f75" }, "tests/test_reply_emotion.py": { "source": "workspace:gateway/tests/test_reply_emotion.py", - "sha256": "324fdaf55b501a31af129d41e9cf459f741ff0636818a6c628657dfde3fa6344", - "bytes": 2701, + "sha256": "2bd1ee33f11e2d23ccf9a30603f0db3b9f20c6d5fce8001f37f9ca76167974dd", + "bytes": 4678, "upstream_sha256": "e45ccda640ef758fcb925d53804071349bdc8fb9f43ee1f63d1afb2ee3f238f5" }, "llm_provider.py": { @@ -317,7 +319,7 @@ } }, "archive_baseline_commit": "19a7adccd9322986eb0646b165b9ce1cf2650cf2", - "workspace_release": "0.5.0", + "workspace_release": "0.5.1", "provider_baseline": { "source": "SPARK2 whitelist observed 2026-10-12", "files": { @@ -344,5 +346,38 @@ "tests/test_llm_provider.py": "6a8bd33679d68899c2a978bf4de672578517494c613b8e77d275c6207de3285b", "tests/test_v08.py": "f993d4162576494e814786f26376ba80ab8a77af98ba70de4379055bb9525082" } + }, + "release_baseline_commit": "d43c7d4e809a5a6b18ca9f28c8163a2f9ad34c7f", + "deployment_baseline": { + "release": "0.5.0", + "files": { + "app.py": "d6520894dfbe035f64b1984aae15976db4df0e7e720195c81d3bf483b240056f", + "face_context.py": "01abfc214ebb4e979faf9430166eccae9af37df911d36da5435f907769e7e31a", + "gateway.py": "d9215f99339de0667e830fbd4d3bff80ac5a61c85630cc4ecadcb52a4c33a0e5", + "guest_sessions.py": "cc082fdb6c2ff7f5a41361ffe9ea2a53ebb944ee37354f65119405ad7a521c82", + "history.py": "2cf8b006bf486a03e038a69daa860ebb71a86989161cf6a7ea610114177a249f", + "llm_provider.py": "56ce6c1a4a647dea6ef86a83615f03db3a4397ebb3fa800b7fa655147d4f9978", + "persona_resolver.py": "deb33b4f4c17792fa5a6837362d5b29173e60a57bb993b61363bd4882d66d5de", + "protocol.py": "d9f522d958935200002e56024949a12b71eb89b3f3241635c5c307b798ee71c5", + "reply_emotion.py": "488fbd24ff1ce7d3d4ab92257c8ccabafe24fc857e11c8486f54fa689276a565", + "segmentation.py": "562ffc6e06f5b9f9072860b588feae3a5d7cd6eaa8577ac928d770071b06978d", + "tests/test_continuity.py": "d8390238f390463a98f12b9909bb5846be65f5b6dc1b21b94338b4cd75aaafae", + "tests/test_debug.py": "26f9e374354b714ab1a03b56af90bcbf32135711dc4f26e2c53eaa90c7f02ddd", + "tests/test_face_context.py": "50ca57adee1d07a194ebaa95b15e09d3e836b97b19490e99e3e045c72a89682c", + "tests/test_gateway.py": "f22aa98f3d6f62a2949a9047ec97e6dd686cac807d989a314a95deca718a3104", + "tests/test_gateway_emotion.py": "fc01e9319263b93adb1cc93904d23a13a25965ddb0fcfbd9c3e14e39f4cf52a5", + "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": "324fdaf55b501a31af129d41e9cf459f741ff0636818a6c628657dfde3fa6344", + "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" + } } } diff --git a/gateway/gateway.py b/gateway/gateway.py index 833aa73..78d9876 100644 --- a/gateway/gateway.py +++ b/gateway/gateway.py @@ -472,6 +472,8 @@ class Dialogue: messages = [{'role': 'system', 'content': system}] + self.contexts.get(turn, []) + [{'role': 'user', 'content': text}] url, headers, body = self.llm_provider.request(messages, max_tokens=160) raw_body = '' + finish_reason = 'not_provided' + usage = {} async with asyncio.timeout(30): async with self.client.stream('POST', url, headers=headers, json=body) as response: response.raise_for_status() @@ -483,7 +485,15 @@ class Dialogue: raw = '\n'.join(event_data); event_data = [] if raw == '[DONE]': break data = json.loads(raw) + reported_usage = data.get('usage') + if isinstance(reported_usage, dict): + for key in ('prompt_tokens', 'completion_tokens', 'total_tokens'): + value = reported_usage.get(key) + if type(value) is int and 0 <= value <= 10_000_000: usage[key] = value for choice in data.get('choices', []): + reported_finish = choice.get('finish_reason') + if reported_finish is not None: + finish_reason = reported_finish if reported_finish in ('stop', 'length', 'content_filter', 'tool_calls', 'function_call') else 'unknown' delta = choice.get('delta', {}).get('content') or '' if not delta: continue metrics.setdefault('llm_first_token_ms', round((time.perf_counter() - request_start) * 1000, 2)) @@ -492,7 +502,10 @@ class Dialogue: if turn != self.turn: return if not raw_body.strip(): raise ValueError('empty LLM body') parse_start = time.perf_counter() - result = parse_reply(raw_body) + result = parse_reply(raw_body, finish_reason=finish_reason) + metrics.update(reply_emotion_reason=result.reason, reply_parse_branch=result.parse_branch, + reply_emotion=result.emotion, reply_intensity=result.intensity, + llm_finish_reason=finish_reason, llm_usage=usage, llm_max_tokens=body['max_tokens']) metrics['reply_parse_ms'] = round((time.perf_counter() - parse_start) * 1000, 2) metrics['reply_emotion_source'] = result.source metrics['llm_first_body_ms'] = round((time.perf_counter() - request_start) * 1000, 2) @@ -501,7 +514,8 @@ class Dialogue: # Only the extracted reply enters events, persistent history and the single TTS generator. self.answers[turn] = result.reply await self.event('llm', turn, text=result.reply) - await self.event('reply.emotion', turn, emotion=result.emotion, intensity=result.intensity, source=result.source) + await self.event('reply.emotion', turn, emotion=result.emotion, intensity=result.intensity, source=result.source, reason=result.reason, parse_branch=result.parse_branch, + finish_reason=finish_reason, usage=usage) await self.event('llm.finished', turn, voice_mode=self.voice_mode, llm_finished_ms=metrics['llm_finished_ms']) async def enqueue(fragment): if fragment: @@ -536,7 +550,7 @@ class Dialogue: self.debug_captures[turn] = await asyncio.to_thread(self.debug_store.create, {'run_id':self.run_id,'conversation_id':self.conversation_id,'turn_id':turn,'voice_id':self.voice_id,'voice_mode':self.voice_mode,'persona':self.persona,'tts_requests':[]}) capture = self.debug_captures.get(turn) if capture: - capture.meta['tts_requests'].append({'input':text,'parameters':{'model':'openbmb/VoxCPM2','voice':self.voice_id,'stream':True},'request_number':sentence}) + capture.meta['tts_requests'].append({'input_chars':len(text),'parameters':{'model':'openbmb/VoxCPM2','voice':self.voice_id,'stream':True},'request_number':sentence}) async with asyncio.timeout(30): async with self.client.stream('POST', 'http://192.168.31.61:5002/v1/audio/speech', json={'model': 'openbmb/VoxCPM2', 'input': text, 'voice': self.voice_id, 'stream': True}) as response: response.raise_for_status() diff --git a/gateway/reply_emotion.py b/gateway/reply_emotion.py index 9c74a94..f51ecbc 100644 --- a/gateway/reply_emotion.py +++ b/gateway/reply_emotion.py @@ -12,6 +12,8 @@ class ReplyEmotion: emotion: str = 'neutral' intensity: int = 0 source: str = 'fallback' + reason: str = 'invalid_json' + parse_branch: str = 'safe_reply' def clean_reply(value): @@ -23,37 +25,51 @@ def clean_reply(value): return value -def parse_reply(raw): - if not isinstance(raw, str) or len(raw) > 8192: return ReplyEmotion(SAFE_REPLY) +def parse_reply(raw, finish_reason=None): + # A damaged envelope alone is not evidence of a token cutoff. + def fallback(reply, reason, branch): + return ReplyEmotion(reply, reason='truncated' if finish_reason == 'length' else reason, parse_branch=branch) + if not isinstance(raw, str) or len(raw) > 8192: + return fallback(SAFE_REPLY, 'input_limit', 'safe_reply') body = raw.strip() - if body.startswith('```'): + fenced = body.startswith('```') + if fenced: body = re.sub(r'^```(?:json)?\s*', '', body, count=1).removesuffix('```').strip() try: data = json.loads(body) except (ValueError, RecursionError): data = None + reason = 'invalid_json' if isinstance(data, dict): reply = clean_reply(data.get('reply')) - if reply: - emotion, intensity = data.get('emotion'), data.get('intensity') - if (set(data) == {'reply', 'emotion', 'intensity'} and type(intensity) is int and - ((emotion == 'neutral' and intensity == 0) or - (emotion in ('happy', 'angry', 'sad') and intensity in (1, 2)))): - return ReplyEmotion(reply, emotion, intensity, 'model') - return ReplyEmotion(reply) + required = {'reply', 'emotion', 'intensity'} + if not required.issubset(data): reason = 'missing_fields' + elif set(data) != required: reason = 'unexpected_fields' + elif not reply: reason = 'invalid_reply' + elif not isinstance(data['emotion'], str) or data['emotion'] not in ('neutral', 'happy', 'angry', 'sad'): + reason = 'invalid_emotion' + elif type(data['intensity']) is not int or not ( + data['emotion'] == 'neutral' and data['intensity'] == 0 or + data['emotion'] != 'neutral' and data['intensity'] in (1, 2)): + reason = 'invalid_intensity' + else: + return ReplyEmotion(reply, data['emotion'], data['intensity'], 'model', 'none', + 'fenced_json' if fenced else 'strict_json') + if reply: return fallback(reply, reason, 'json_reply') for key in ('text', 'answer'): reply = clean_reply(data.get(key)) - if reply: return ReplyEmotion(reply) - # Recover a usable quoted reply from a damaged/truncated envelope without another model call. + if reply: return fallback(reply, reason, 'alternate_field') + # Recover only the reply string, never speak the envelope or make another model request. match = re.search(r'"reply"\s*:\s*(")', body) if match: literal = body[match.start(1):] + branch = 'quoted_reply' try: value, _ = json.JSONDecoder().raw_decode(literal) except ValueError: - # Only a truncated string, never arbitrary suffix/JSON syntax recovery. + branch = 'repaired_string' try: value = json.loads(literal.rstrip('\\') + '"') except ValueError: value = None reply = clean_reply(value) - if reply: return ReplyEmotion(reply) + if reply: return fallback(reply, reason, branch) if not any(c in body for c in '{}[]') and not re.search(r'\b(?:reply|emotion|intensity)\s*[:=]', body): reply = clean_reply(body) - if reply: return ReplyEmotion(reply) - return ReplyEmotion(SAFE_REPLY) + if reply: return fallback(reply, 'non_json', 'plain_text') + return fallback(SAFE_REPLY, reason, 'safe_reply') diff --git a/gateway/tests/test_debug.py b/gateway/tests/test_debug.py index 0c07375..029efaa 100644 --- a/gateway/tests/test_debug.py +++ b/gateway/tests/test_debug.py @@ -41,6 +41,17 @@ class DebugTests(unittest.TestCase): payload['debug_id']='../bad' self.assertEqual(client.post('/debug/download',json=payload,headers=headers).status_code,404) + def test_report_accepts_old_and_finite_new_diagnostics(self): + from unittest.mock import patch + app.state.lan_open=True;app.state.remote_reports=[] + old={'type':'diagnostic_report','app_version':'0.5.0','logs':[]} + new={**old,'app_version':'0.5.1','version_code':9,'camera':{'granted':False,'status':'off','permission_pending':False,'face_sharing':False}, + 'role_playing':False,'role_active':None,'role_previous':{'turn_id':2,'seq':7,'emotion':'neutral','intensity':0,'source':'fallback','reason':'non_json'}} + with patch('gateway.GuestSessions.lan',return_value=True): + client=TestClient(app) + for payload in (old,new):self.assertEqual(client.post('/debug/report',json=payload).status_code,200) + self.assertEqual(len(app.state.remote_reports),2) + def test_lore_constraints_bounded(self): d=json.loads(Path('personas/lvbu.lorebook.json').read_text());text=d['rules']+'\n'+'\n'.join(e['text'] for e in d['entries']) self.assertLess(len(text),1400) diff --git a/gateway/tests/test_gateway_emotion.py b/gateway/tests/test_gateway_emotion.py index df098e3..68a5571 100644 --- a/gateway/tests/test_gateway_emotion.py +++ b/gateway/tests/test_gateway_emotion.py @@ -49,6 +49,51 @@ class EmotionPipelineTests(unittest.IsolatedAsyncioTestCase): self.assertGreater(events[0]['seq'],0);self.assertLess(order.index('reply.emotion'),order.index('pcm')) self.assertTrue(socket.frames) + async def test_finish_usage_and_metadata_never_store_model_envelope(self): + for finish,expected in [('length','truncated'),('stop','invalid_json'),(None,'invalid_json')]: + socket=Socket() + content='{"reply":"公开正文","emotion":' + records=[{'choices':[{'delta':{'content':content},'finish_reason':None}]}, + {'choices':[{'delta':{},'finish_reason':finish}]}, + {'choices':[],'usage':{'prompt_tokens':20,'completion_tokens':160,'total_tokens':180,'private':'never-log','bad':True}}] + stream=''.join('data: '+json.dumps(row)+'\n\n' for row in records)+'data: [DONE]\n\n' + async with httpx.AsyncClient(transport=httpx.MockTransport(lambda req:httpx.Response(200,text=stream))) as client: + d=Dialogue(socket,FakeModel(),client);queue=asyncio.Queue(2);metrics={} + await d.generate(0,'公开问题',queue,metrics,time.perf_counter()) + self.assertEqual(await queue.get(),'公开正文');self.assertIsNone(await queue.get()) + event=next(e for e in socket.events if e['type']=='reply.emotion') + self.assertEqual(event['reason'],expected) + self.assertEqual(event['finish_reason'],finish or 'not_provided') + self.assertEqual(event['usage'],{'prompt_tokens':20,'completion_tokens':160,'total_tokens':180}) + 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) + + async def test_debug_metadata_contains_counts_not_reply_text(self): + import tempfile + from pathlib import Path + from tts_debug import DebugStore + spoken='公开诊断正文不应落入metadata' + def backend(request): + if 'transcriptions' in request.url.path:return httpx.Response(200,json={'text':'公开问题'}) + if 'chat' in request.url.path: + content=json.dumps({'reply':spoken,'emotion':'happy','intensity':1}) + return httpx.Response(200,text='data: '+json.dumps({'choices':[{'delta':{'content':content},'finish_reason':'stop'}]})+'\n\ndata: [DONE]\n\n') + out=io.BytesIO() + with wave.open(out,'wb') as w: + w.setnchannels(1);w.setsampwidth(2);w.setframerate(48000);w.writeframes(b'\x11\x01'*960) + return httpx.Response(200,content=out.getvalue()) + with tempfile.TemporaryDirectory() as folder: + async with httpx.AsyncClient(transport=httpx.MockTransport(backend)) as client: + d=Dialogue(Socket(),FakeModel(),client);d.debug_store=DebugStore(folder);d.run_id='synthetic' + await d.run(0,bytes(640)) + metadata=json.loads(next(Path(folder).glob('*/metadata.json')).read_text()) + self.assertEqual(metadata['tts_requests'][0]['input_chars'],len(spoken)) + self.assertNotIn('input',metadata['tts_requests'][0]) + self.assertNotIn(spoken,json.dumps(metadata,ensure_ascii=False)) + self.assertEqual(metadata['metrics']['reply_emotion'],'happy') + self.assertEqual(metadata['metrics']['reply_emotion_reason'],'none') + async def test_stale_generation_cannot_publish_emotion_or_speak(self): entered=asyncio.Event();resume=asyncio.Event();socket=Socket() class Slow(httpx.AsyncByteStream): diff --git a/gateway/tests/test_reply_emotion.py b/gateway/tests/test_reply_emotion.py index 52ebc62..eef7339 100644 --- a/gateway/tests/test_reply_emotion.py +++ b/gateway/tests/test_reply_emotion.py @@ -35,6 +35,37 @@ class ReplyEmotionTests(unittest.TestCase): self.assertEqual(result.reply,expected) self.assertEqual((result.emotion,result.intensity,result.source),('neutral',0,'fallback')) + def test_fixed_reasons_and_recovery_branches(self): + cases = [ + ({'reply':'正文'}, 'missing_fields'), + ({'reply':'正文','emotion':'fear','intensity':1}, 'invalid_emotion'), + ({'reply':'正文','emotion':'happy','intensity':True}, 'invalid_intensity'), + ({'reply':'正文','emotion':'happy','intensity':1.0}, 'invalid_intensity'), + ({'reply':'正文','emotion':'happy','intensity':1,'extra':1}, 'unexpected_fields'), + ] + for data,reason in cases: + parsed=parse_reply(json.dumps(data)) + self.assertEqual((parsed.reason,parsed.parse_branch,parsed.reply),(reason,'json_reply','正文')) + self.assertEqual(parsed.source,'fallback') + for raw,reason,branch in [('普通正文','non_json','plain_text'), + ('{"reply":"正文","emotion":','invalid_json','quoted_reply'), + ('{"reply":"正文','invalid_json','repaired_string'), + ('{"answer":"正文"}','missing_fields','alternate_field')]: + result=parse_reply(raw) + self.assertEqual((result.reason,result.parse_branch),(reason,branch)) + self.assertEqual(result.reply,'普通正文' if branch=='plain_text' else '正文') + + def test_length_is_evidence_not_a_guess(self): + broken='{"reply":"正文' + self.assertEqual(parse_reply(broken).reason,'invalid_json') + self.assertEqual(parse_reply(broken,'stop').reason,'invalid_json') + result=parse_reply(broken,'length') + self.assertEqual((result.reason,result.source,result.reply),('truncated','fallback','正文')) + # A complete validated object can remain valid even at the token budget boundary. + valid='{"reply":"正文","emotion":"neutral","intensity":0}' + self.assertEqual(parse_reply(valid,'length').source,'model') + self.assertEqual(parse_reply(valid).reason,'none') + def test_no_model_retry_or_schema_contract(self): from pathlib import Path source=(Path(__file__).resolve().parents[1]/'gateway.py').read_text() diff --git a/scripts/check-expression-rules.sh b/scripts/check-expression-rules.sh index dea67f5..e2e1f44 100755 --- a/scripts/check-expression-rules.sh +++ b/scripts/check-expression-rules.sh @@ -28,8 +28,11 @@ with tempfile.TemporaryDirectory(prefix='lan-voice-expression-check-') as output '-no-stdlib', '-no-reflect', '-jvm-target', '17', '-classpath', stdlib, '-d', 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', 'tests/expression/ExpressionRulesCheck.kt', - 'tests/expression/FaceCueRulesCheck.kt'], check=True) + 'tests/expression/FaceCueRulesCheck.kt', + 'tests/expression/CameraPermissionCheck.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) PY diff --git a/scripts/deploy-gateway-source.py b/scripts/deploy-gateway-source.py index a86a84f..e94be44 100644 --- a/scripts/deploy-gateway-source.py +++ b/scripts/deploy-gateway-source.py @@ -13,7 +13,7 @@ def health(): with opener.open('https://192.168.31.61:5011/health',timeout=3) as r:return json.load(r) def atomic(path,content,mode): path.parent.mkdir(parents=True,exist_ok=True) - tmp=path.with_name(path.name+'.v050.tmp');tmp.write_bytes(content);tmp.chmod(mode);tmp.replace(path) + tmp=path.with_name(path.name+'.v051.tmp');tmp.write_bytes(content);tmp.chmod(mode);tmp.replace(path) def live_hashes():return {name:digest(root/name) for name in deploy_files} original=live_hashes() if original!=expected: @@ -30,7 +30,7 @@ private_hashes={str(p):digest(p) for p in private_files} def relation_unchanged(): return subprocess.check_output(['systemctl','--user','cat',unit])==unit_text and all(digest(Path(p))==h for p,h in private_hashes.items()) if apply and health().get('busy'): raise RuntimeError('gateway_busy_no_restart') -with tempfile.TemporaryDirectory(prefix='voice-v050-stage-') as folder: +with tempfile.TemporaryDirectory(prefix='voice-v051-stage-') as folder: stage=Path(folder) for name,content in bundle.items(): path=stage/name;path.parent.mkdir(parents=True,exist_ok=True);path.write_bytes(base64.b64decode(content)) @@ -42,7 +42,7 @@ with tempfile.TemporaryDirectory(prefix='voice-v050-stage-') as folder: if live_hashes()!=original:raise RuntimeError('source_changed_during_tests') if not relation_unchanged():raise RuntimeError('environment_or_unit_changed_during_tests') if health().get('busy'):raise RuntimeError('gateway_busy_after_tests_no_restart') - backup=root/'.runtime/backups'/time.strftime('voice-v050-%Y%m%d-%H%M%S');backup.mkdir(parents=True,mode=0o700) + backup=root/'.runtime/backups'/time.strftime('voice-v051-%Y%m%d-%H%M%S');backup.mkdir(parents=True,mode=0o700) # Save all actual runtime Python sources/tests, modes, plus unit/env privately. No logs/history/audio copied. for path in list(root.glob('*.py'))+list((root/'tests').glob('*.py')): dst=backup/path.relative_to(root);dst.parent.mkdir(parents=True,exist_ok=True);shutil.copy2(path,dst) @@ -84,7 +84,7 @@ def main(): root=Path(__file__).resolve().parents[1] parser=argparse.ArgumentParser(description=__doc__);parser.add_argument('--apply',action='store_true');args=parser.parse_args() source=root/'gateway';manifest=json.loads((source/'SOURCE_MANIFEST.json').read_text()) - baseline=manifest['provider_baseline']['files'] + baseline=manifest.get('deployment_baseline',manifest['provider_baseline'])['files'] files=sorted(set(baseline)|{p.relative_to(source).as_posix() for p in source.glob('*.py')}|{p.relative_to(source).as_posix() for p in (source/'tests').glob('*.py')}) assert all(n.endswith('.py') and not Path(n).is_absolute() and '..' not in Path(n).parts for n in files) expected={name:baseline.get(name) for name in files} diff --git a/scripts/finalize-emotion-release.sh b/scripts/finalize-emotion-release.sh index be591d0..963b32b 100755 --- a/scripts/finalize-emotion-release.sh +++ b/scripts/finalize-emotion-release.sh @@ -15,10 +15,11 @@ import hashlib,json,runpy root=Path.cwd();directory=root/'logs/voice-investigation' load=lambda name:json.loads((directory/name).read_text()) release=load('release-emotion.json');probe=load('probe-emotion.json');deploy=load('gateway-emotion-deploy.json');client=load('client-emotion-tests.json') -assert release['version_name']=='0.5.0' and release['version_code']==8 and release['signature']=='apksigner_verified' +assert release['version_name']=='0.5.1' and release['version_code']==9 and release['signature']=='apksigner_verified' assert release['download_http_status']==200 and release['download_bytes']==release['bytes'] assert hashlib.sha256((root/release['apk']).read_bytes()).hexdigest()==release['sha256'] 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 probe['status']=='passed' and probe['downlink_bytes']>0 and probe['llm_chars']>0 and probe['drained_ack'] assert probe['emotion_count']==1 and probe['emotion_before_pcm'] and probe['tts_input_matches_body'] and probe['tts_requests']==1 assert deploy['status']=='deployed' and deploy['applied'] and deploy['health']=='ok' and client['status']=='passed' @@ -38,18 +39,18 @@ PY git diff --check git add -- app/build.gradle app/src/main/java/com/gorios/lanvoice/MainActivity.kt \ app/src/main/java/com/gorios/lanvoice/audio/VoiceSession.kt \ - app/src/main/java/com/gorios/lanvoice/dialogue/ReplyEmotion.kt \ - app/src/main/java/com/gorios/lanvoice/expression/ExpressionController.kt \ + app/src/main/java/com/gorios/lanvoice/dialogue/ReplyEmotion.kt app/src/main/java/com/gorios/lanvoice/diag/DiagnosticReportUpload.kt \ + app/src/main/java/com/gorios/lanvoice/expression/ExpressionController.kt app/src/main/java/com/gorios/lanvoice/expression/CameraPermissionGate.kt \ app/src/main/java/com/gorios/lanvoice/expression/ExpressionState.kt \ app/src/main/java/com/gorios/lanvoice/expression/ExpressionUi.kt \ app/src/main/java/com/gorios/lanvoice/net/DialogueProtocol.kt \ gateway/gateway.py gateway/llm_provider.py gateway/reply_emotion.py gateway/SOURCE_MANIFEST.json gateway/README.md gateway/env.example gateway/scripts/check-archive.py \ - gateway/tests/test_continuity.py gateway/tests/test_reply_emotion.py gateway/tests/test_gateway_emotion.py gateway/tests/test_llm_provider.py \ + gateway/tests/test_debug.py gateway/tests/test_continuity.py gateway/tests/test_reply_emotion.py gateway/tests/test_gateway_emotion.py gateway/tests/test_llm_provider.py \ tests/session/AudioDoubles.kt tests/session/ProtocolEvents.kt tests/session/ConnectionCheck.kt tests/protocol/ProtocolCheck.kt \ - scripts/check-reply-regressions.py scripts/check-reply-structure.py scripts/check-emotion-regressions.sh \ + scripts/check-expression-rules.sh tests/expression/CameraPermissionCheck.kt scripts/check-reply-regressions.py scripts/check-reply-structure.py scripts/check-emotion-regressions.sh \ scripts/deploy-gateway-source.py scripts/rollback-gateway-source.py scripts/update-gateway-manifest.py scripts/deploy-gateway.py scripts/archive-gateway.py \ scripts/probe-reply-emotion.py scripts/package-emotion-release.sh scripts/finalize-emotion-release.sh \ - docs/REPLY_EMOTION_050.md docs/PLAN.md + docs/CAMERA_EMOTION_051.md docs/REPLY_EMOTION_050.md docs/PLAN.md git diff --cached --check python3 - <<'PY' import subprocess @@ -57,7 +58,7 @@ names=subprocess.check_output(['git','diff','--cached','--name-only'],text=True) assert names and all(n.startswith(('app/','gateway/','tests/','scripts/','docs/')) for n in names) assert not any(any(x in n.split('/') for x in ('logs','artifacts','.runtime','__pycache__','models')) or n.endswith(('.pem','.key','.apk','.wav','.pcm','.pyc')) for n in names) PY -git -c user.name=zenord -c user.email=zenord@email.com commit -m 'feat: merge reply emotions while preserving configurable Qwen/Doubao provider' +git -c user.name=zenord -c user.email=zenord@email.com commit -m 'fix: preserve camera permission intent and distinguish unknown reply expression' git push origin main python3 - <<'PY' import json,subprocess @@ -65,7 +66,7 @@ from pathlib import Path commit=subprocess.check_output(['git','rev-parse','HEAD'],text=True).strip() remote=subprocess.check_output(['git','ls-remote','origin','refs/heads/main'],text=True).split()[0] assert commit==remote -result={'commit':commit,'branch':'main','push':'verified','archive':'gateway/','version':'0.5.0','archive_baseline':'19a7adccd9322986eb0646b165b9ce1cf2650cf2'} +result={'commit':commit,'branch':'main','push':'verified','archive':'gateway/','version':'0.5.1','archive_baseline':'19a7adccd9322986eb0646b165b9ce1cf2650cf2'} Path('logs/voice-investigation/git-emotion-release.json').write_text(json.dumps(result,indent=2)+'\n') print(json.dumps(result,indent=2)) PY diff --git a/scripts/package-emotion-release.sh b/scripts/package-emotion-release.sh index 74c7499..f2b0339 100755 --- a/scripts/package-emotion-release.sh +++ b/scripts/package-emotion-release.sh @@ -13,7 +13,7 @@ assert probe['status']=='passed' and probe['downlink_bytes']>0 and probe['emotio assert compat['status']=='passed' 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-v050-arm64-debug.apk').exists(), 'release artifact exists: refusing overwrite' +assert not (root/'artifacts/lan-voice-v051-arm64-debug.apk').exists(), 'release artifact exists: refusing overwrite' print('Verified tested client/provider source and successful deployed pipeline before APK build') PY ./scripts/build.sh @@ -29,7 +29,7 @@ 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='8'" in badging and "versionName='0.5.0'" in badging +assert "versionCode='9'" in badging and "versionName='0.5.1'" 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' @@ -39,9 +39,10 @@ if previous.exists(): 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-v050-arm64-debug.apk' +artifact=root/'artifacts/lan-voice-v051-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' shutil.copy2(source,artifact) digest=hashlib.sha256(artifact.read_bytes()).hexdigest() artifact.with_suffix('.apk.sha256').write_text(f'{digest} {artifact.name}\n') @@ -59,7 +60,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.0',version_code=8,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.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') (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-reply-emotion.py b/scripts/probe-reply-emotion.py index 60da5d1..6ebd923 100644 --- a/scripts/probe-reply-emotion.py +++ b/scripts/probe-reply-emotion.py @@ -83,10 +83,14 @@ async def probe(): if kind=='reply.emotion': assert event['turn_id']==turn and isinstance(event.get('seq'),int) and event['seq']>0 assert (event.get('emotion'),event.get('intensity')) in [('neutral',0)]+[(e,i) for e in ('happy','angry','sad') for i in (1,2)] - assert event.get('source')=='model', 'real structured output fell back' + assert event.get('source') in ('model','fallback') + assert event.get('reason') in ('none','missing_fields','unexpected_fields','invalid_emotion','invalid_intensity','invalid_reply','non_json','invalid_json','truncated','input_limit') + if event['source']=='fallback':assert (event['emotion'],event['intensity'])==('neutral',0) and event['reason']!='none' + if event['reason']=='truncated':assert event.get('finish_reason')=='length' + summary['structured_model_output']=event['source']=='model' assert summary['downlink_frames']==0 and emotion is None and reply_body, 'emotion event order/duplicate' emotion=event;summary['emotion_count']+=1 - summary['reply_emotion']={key:event[key] for key in ('turn_id','seq','emotion','intensity','source')} + summary['reply_emotion']={key:event[key] for key in ('turn_id','seq','emotion','intensity','source','reason','parse_branch','finish_reason','usage')} if kind=='tts' and event.get('state')=='sentence_start': assert event.get('text')==reply_body, 'TTS text differs from parsed body' summary['tts_input_matches_body']=True @@ -94,7 +98,7 @@ async def probe(): if kind=='voice.metrics': summary['tts_requests']=event.get('tts_request_count') if kind=='metrics': values=event.get('values',{}) - summary['backend_metrics']={key:values.get(key) for key in ('stt_ms','llm_first_token_ms','llm_first_body_ms','structured_wait_ms','reply_parse_ms','llm_finished_ms','tts_first_pcm_ms','capture_to_first_pcm_ms','total_ms','tts_request_count','face_cue_used')} + summary['backend_metrics']={key:values.get(key) for key in ('stt_ms','llm_first_token_ms','llm_first_body_ms','structured_wait_ms','reply_parse_ms','llm_finished_ms','tts_first_pcm_ms','capture_to_first_pcm_ms','total_ms','tts_request_count','face_cue_used','reply_emotion_reason','reply_parse_branch','reply_emotion','reply_intensity','llm_finish_reason','llm_usage','llm_max_tokens')} summary['segments']=[{key:s.get(key) for key in ('audio_seconds','total_ms','rtf','max_chunk_interarrival_ms')} for s in values.get('tts_segments',[])] if kind=='error': raise RuntimeError('gateway_backend_error') if kind=='tts' and event.get('state')=='stop': diff --git a/scripts/update-gateway-manifest.py b/scripts/update-gateway-manifest.py index 289f638..e6964e4 100644 --- a/scripts/update-gateway-manifest.py +++ b/scripts/update-gateway-manifest.py @@ -5,7 +5,7 @@ import hashlib,json root=Path(__file__).resolve().parents[1]/'gateway' manifest=json.loads((root/'SOURCE_MANIFEST.json').read_text()) manifest['archive_baseline_commit']='19a7adccd9322986eb0646b165b9ce1cf2650cf2' -manifest['workspace_release']='0.5.0' +manifest['workspace_release']='0.5.1' manifest['code_version']='0.7.1 (legacy health version; reply.emotion version 1 capability)' for path in sorted(root.rglob('*')): if not path.is_file():continue diff --git a/tests/expression/CameraPermissionCheck.kt b/tests/expression/CameraPermissionCheck.kt new file mode 100644 index 0000000..eb680c5 --- /dev/null +++ b/tests/expression/CameraPermissionCheck.kt @@ -0,0 +1,31 @@ +import com.gorios.lanvoice.expression.CameraPermissionGate +import com.gorios.lanvoice.expression.CameraPermissionGate.Action + +fun main() { + fun gate() = CameraPermissionGate().apply { check(onForeground() == Action.NONE) } + check(CameraPermissionGate().click(false, false) == Action.NONE) + for (resultBeforeForeground in listOf(true, false)) { + val g=gate();check(g.click(false,false)==Action.REQUEST_PERMISSION) + g.onBackground();check(g.permissionPending) + if (resultBeforeForeground) { + check(g.permissionResult(true)==Action.NONE) + check(g.onForeground()==Action.START) + } else { + check(g.onForeground()==Action.NONE) + check(g.permissionResult(true)==Action.START) + } + check(g.onForeground()==Action.NONE) // one-shot continuation + g.onBackground();check(g.onForeground()==Action.NONE) // no auto-resume of active camera + } + val denied=gate();check(denied.click(false,false)==Action.REQUEST_PERMISSION) + denied.onBackground();check(denied.permissionResult(false)==Action.DENIED) + check(denied.onForeground()==Action.NONE) + val cancel=gate();check(cancel.click(false,false)==Action.REQUEST_PERMISSION) + check(cancel.click(false,false)==Action.STOP);check(cancel.permissionResult(true)==Action.NONE) + val released=gate();released.click(false,false);released.release() + check(released.permissionResult(true)==Action.NONE);check(released.onForeground()==Action.NONE) + val granted=gate();check(granted.click(false,true)==Action.START) + check(granted.click(true,true)==Action.STOP) + check(granted.permissionResult(true)==Action.NONE) // duplicate/stale result + println("PASS: camera authorization survives onStop in both callback orders; foreground-only, denial/cancel/release, default off, no automatic resume") +} diff --git a/tests/protocol/ProtocolCheck.kt b/tests/protocol/ProtocolCheck.kt index 5995584..81bf2ce 100644 --- a/tests/protocol/ProtocolCheck.kt +++ b/tests/protocol/ProtocolCheck.kt @@ -8,11 +8,11 @@ fun main() { } listOf("other" to 1, "neutral" to 2, "happy" to 0, "sad" to 3).forEach { (kind, strength) -> val parsed = checkNotNull(com.gorios.lanvoice.dialogue.ReplyEmotion.fromWire(7L, 10L, kind, strength, "model")) - check(parsed.label == "中立" && parsed.source == com.gorios.lanvoice.dialogue.EmotionSource.FALLBACK) + check(parsed.label == "表达未判定(格式回退)" && parsed.source == com.gorios.lanvoice.dialogue.EmotionSource.FALLBACK) } check(com.gorios.lanvoice.dialogue.ReplyEmotion.fromWire(null, 1, "happy", 2, "model") == null) - check(com.gorios.lanvoice.dialogue.ReplyEmotion.fromWire(1, 1, "happy", true, "model")?.label == "中立") - check(com.gorios.lanvoice.dialogue.ReplyEmotion.fromWire(1, 1, "happy", 2.0, "model")?.label == "中立") + check(com.gorios.lanvoice.dialogue.ReplyEmotion.fromWire(1, 1, "happy", true, "model")?.label == "表达未判定(格式回退)") + check(com.gorios.lanvoice.dialogue.ReplyEmotion.fromWire(1, 1, "happy", 2.0, "model")?.label == "表达未判定(格式回退)") val pcm = ByteArray(640) { (it % 256).toByte() } val uplink = DialogueProtocol.uplink(pcm, 0x81234567L, 0xffffffffL) diff --git a/tests/session/ConnectionCheck.kt b/tests/session/ConnectionCheck.kt index 8ddf429..f66fa4c 100644 --- a/tests/session/ConnectionCheck.kt +++ b/tests/session/ConnectionCheck.kt @@ -412,13 +412,17 @@ fun runChecks() { Payload(turn=turn, fields=mapOf("seq" to seq, "emotion" to kind, "intensity" to strength, "source" to "model")))) } emotion(3, 100) + check(states.last().roleLabel == "高兴·明显") check(states.last().replyEmotion.label == "高兴·明显") emotion(3, 99, "angry") // out-of-order same-turn event emotion(2, 101, "angry") // retired turn emotion(99, 102, "angry") // unannounced turn must not advance current turn + for (reason in listOf("old_seq", "old_turn", "unannounced_turn")) { + check(DebugLogUpload.records.any { it.second.startsWith("role ignore reason=$reason ") }) + } check(states.last().replyEmotion.label == "高兴·明显") emotion(3, 103, "invalid") - check(states.last().replyEmotion.label == "中立") + check(states.last().replyEmotion.label == "表达未判定(格式回退)") emotion(3, 104, "sad", 1) check(states.last().replyEmotion.label == "难过·轻度") event(EventKind.TTS, 3, state="stop") @@ -426,16 +430,22 @@ fun runChecks() { check(states.last().replyEmotion.label == "难过·轻度") // tts.stop does not mean native drain checkNotNull(com.gorios.lanvoice.audio.AudioPlayback.lastDrained)(3, 0) Handler.drain() - check(states.last().replyEmotion.label == "中立") + check(states.last().replyEmotion.turnId == null) + check(states.last().roleLabel == "当前未播放") + check(states.last().previousReplyEmotion?.label == "难过·轻度") emotion(3, 105) // a late event after drained cannot reanimate the expression - check(states.last().replyEmotion.label == "中立") + check(DebugLogUpload.records.any { it.second.startsWith("role ignore reason=drained ") }) + check(states.last().previousReplyEmotion?.label == "难过·轻度") + check(states.last().replyEmotion.turnId == null) event(EventKind.ABORT, 4, reason="new_turn") + check(states.last().previousReplyEmotion?.label == "难过·轻度") emotion(4, 106) + check(states.last().roleLabel == "当前未播放") // accepted expression before PCM is not displayed as playing check(states.last().replyEmotion.label == "高兴·明显") session.interrupt() - check(states.last().replyEmotion.label == "中立") + check(states.last().replyEmotion.turnId == null) event(EventKind.ABORT, 4, reason="client_abort") - check(states.last().replyEmotion.label == "中立") + check(states.last().replyEmotion.turnId == null) event(EventKind.UNKNOWN, 4) event(EventKind.ABORT, 4, reason="new_turn") check(blockedField.get(session) == null) @@ -471,6 +481,17 @@ fun runChecks() { } fun main() { + 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")!! + val empty = com.gorios.lanvoice.audio.VoiceUiState() + check(empty.roleLabel == "当前未播放") + check(empty.copy(voiceActive=true, phase=com.gorios.lanvoice.audio.VoicePhase.THINKING, replyEmotion=normal).roleLabel == "等待回复") + check(empty.copy(phase=com.gorios.lanvoice.audio.VoicePhase.ANSWERING, replyEmotion=normal).roleLabel == "中立") + check(empty.copy(phase=com.gorios.lanvoice.audio.VoicePhase.ANSWERING, replyEmotion=fallback).roleLabel == "表达未判定(格式回退)") + check(fallback.reason.wire == "invalid_intensity") + } + try { runChecks() } catch (error: Throwable) { error.printStackTrace() kotlin.system.exitProcess(1) diff --git a/tests/session/ProtocolEvents.kt b/tests/session/ProtocolEvents.kt index 4a4cb45..f440beb 100644 --- a/tests/session/ProtocolEvents.kt +++ b/tests/session/ProtocolEvents.kt @@ -4,7 +4,7 @@ package com.gorios.lanvoice.net // 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 optString(key: String, fallback: String = "") = when (key) { "state" -> state; "reason" -> reason; else -> 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] }