From d43c7d4e809a5a6b18ca9f28c8163a2f9ad34c7f Mon Sep 17 00:00:00 2001 From: zenord Date: Mon, 12 Oct 2026 10:57:14 +0800 Subject: [PATCH] feat: merge reply emotions while preserving configurable Qwen/Doubao provider --- app/build.gradle | 4 +- .../java/com/gorios/lanvoice/MainActivity.kt | 1 + .../com/gorios/lanvoice/audio/VoiceSession.kt | 33 +++- .../gorios/lanvoice/dialogue/ReplyEmotion.kt | 35 ++++ .../expression/ExpressionController.kt | 6 +- .../lanvoice/expression/ExpressionState.kt | 1 + .../lanvoice/expression/ExpressionUi.kt | 19 ++- .../gorios/lanvoice/net/DialogueProtocol.kt | 4 +- docs/PLAN.md | 16 ++ docs/REPLY_EMOTION_050.md | 84 ++++++++++ gateway/README.md | 9 + gateway/SOURCE_MANIFEST.json | 122 +++++++++++++- gateway/env.example | 8 + gateway/gateway.py | 105 +++++------- gateway/llm_provider.py | 27 +++ gateway/reply_emotion.py | 59 +++++++ gateway/scripts/check-archive.py | 14 +- gateway/tests/test_continuity.py | 4 +- gateway/tests/test_gateway_emotion.py | 66 ++++++++ gateway/tests/test_llm_provider.py | 94 +++++++++++ gateway/tests/test_reply_emotion.py | 46 ++++++ scripts/archive-gateway.py | 2 + scripts/check-emotion-regressions.sh | 18 ++ scripts/check-reply-regressions.py | 4 +- scripts/check-reply-structure.py | 66 ++++++++ scripts/deploy-gateway-source.py | 109 ++++++++++++ scripts/deploy-gateway.py | 3 +- scripts/finalize-emotion-release.sh | 71 ++++++++ scripts/package-emotion-release.sh | 65 ++++++++ scripts/probe-reply-emotion.py | 156 ++++++++++++++++++ scripts/rollback-gateway-source.py | 41 +++++ scripts/update-gateway-manifest.py | 21 +++ tests/protocol/ProtocolCheck.kt | 13 ++ tests/session/AudioDoubles.kt | 3 +- tests/session/ConnectionCheck.kt | 27 +++ tests/session/ProtocolEvents.kt | 6 +- 36 files changed, 1264 insertions(+), 98 deletions(-) create mode 100644 app/src/main/java/com/gorios/lanvoice/dialogue/ReplyEmotion.kt create mode 100644 docs/REPLY_EMOTION_050.md create mode 100644 gateway/llm_provider.py create mode 100644 gateway/reply_emotion.py create mode 100644 gateway/tests/test_gateway_emotion.py create mode 100644 gateway/tests/test_llm_provider.py create mode 100644 gateway/tests/test_reply_emotion.py create mode 100755 scripts/check-emotion-regressions.sh create mode 100644 scripts/check-reply-structure.py create mode 100644 scripts/deploy-gateway-source.py create mode 100755 scripts/finalize-emotion-release.sh create mode 100755 scripts/package-emotion-release.sh create mode 100644 scripts/probe-reply-emotion.py create mode 100644 scripts/rollback-gateway-source.py create mode 100644 scripts/update-gateway-manifest.py diff --git a/app/build.gradle b/app/build.gradle index 4d640eb..2e72b58 100644 --- a/app/build.gradle +++ b/app/build.gradle @@ -45,8 +45,8 @@ android { applicationId 'com.gorios.lanvoice' minSdk 26 targetSdk 34 - versionCode 7 - versionName '0.4.0' + versionCode 8 + versionName '0.5.0' 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 429bed3..1da7b08 100644 --- a/app/src/main/java/com/gorios/lanvoice/MainActivity.kt +++ b/app/src/main/java/com/gorios/lanvoice/MainActivity.kt @@ -255,6 +255,7 @@ fun Home( ) } ExpressionControls(expressionState, onToggleExpressions, shareFace, onShareFace) + Text("角色:${state.replyEmotion.label}(角色表达)", color = gold, fontSize = 13.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 0b39567..de3330d 100644 --- a/app/src/main/java/com/gorios/lanvoice/audio/VoiceSession.kt +++ b/app/src/main/java/com/gorios/lanvoice/audio/VoiceSession.kt @@ -4,6 +4,8 @@ import android.os.Handler import android.os.Looper import android.os.SystemClock import android.util.Log +import com.gorios.lanvoice.dialogue.ReplyEmotion +import com.gorios.lanvoice.dialogue.ReplyEmotionObserver import com.gorios.lanvoice.net.ConnectionStatus import com.gorios.lanvoice.net.DialogueClient import com.gorios.lanvoice.net.DebugLogUpload @@ -21,6 +23,7 @@ data class VoiceUiState( val voiceActive: Boolean = false, val aec: AecAvailability = AecAvailability.UNKNOWN, val guidance: String? = null, + val replyEmotion: ReplyEmotion = ReplyEmotion(), ) /** Main-thread coordinator; both audio workers add their own epochs to the socket's fence. */ @@ -29,6 +32,7 @@ class VoiceSession( private val onConnectionLog: (String) -> Unit = {}, private val onPreparePlayback: () -> String? = { null }, private val onVoiceStopped: () -> Unit = {}, + private val emotionObserver: ReplyEmotionObserver = ReplyEmotionObserver {}, ) { private val main = Handler(Looper.getMainLooper()) private var state = VoiceUiState() @@ -43,6 +47,7 @@ class VoiceSession( private var blockedTurn: Long? = null private var sequence = 1L private var preparedPlaybackTurn: Long? = null + private var emotionEndedTurn: Long? = null private var faceSharing = false private var faceSupported = false private var faceCue = FaceCueObservation() @@ -66,7 +71,8 @@ class VoiceSession( if (isActive() && playbackIsCurrent(turn, epoch) && blockedTurn != turn) { diagnostic("playback drained turn=$turn") if (dialogue.playbackDrained(turn)) { - update(state.copy(phase = VoicePhase.LISTENING)) + emotionEndedTurn = turn + update(state.copy(phase = VoicePhase.LISTENING, replyEmotion = ReplyEmotion())) startCapture() } } @@ -163,7 +169,7 @@ class VoiceSession( clearFaceContext() onVoiceStopped() blockedTurn = currentTurn - update(state.copy(voiceActive = false, phase = VoicePhase.IDLE)) + update(state.copy(voiceActive = false, phase = VoicePhase.IDLE, replyEmotion = ReplyEmotion())) if (sendControls && wasActive && state.connection == ConnectionStatus.CONNECTED) { dialogue.listen(false) dialogue.abort(currentTurn) @@ -176,7 +182,7 @@ class VoiceSession( blockedTurn = currentTurn playback.interrupt() // Silence locally before waiting for the server's abort event. if (dialogue.abort(currentTurn)) { - update(state.copy(phase = VoicePhase.LISTENING)) + update(state.copy(phase = VoicePhase.LISTENING, replyEmotion = ReplyEmotion())) startCapture() } } @@ -223,6 +229,7 @@ class VoiceSession( faceSent = false faceCue = FaceCueObservation() preparedPlaybackTurn = null + emotionEndedTurn = null onVoiceStopped() stopCapture() playback.interrupt() @@ -231,7 +238,7 @@ class VoiceSession( retiredTurns.clear() blockedTurn = null sequence = 1 - update(state.copy(connection = connection, voiceActive = false, phase = VoicePhase.IDLE)) + update(state.copy(connection = connection, voiceActive = false, phase = VoicePhase.IDLE, replyEmotion = ReplyEmotion())) } else update(state.copy( connection = connection, // onStop runs while the screen is hidden. Keep the reason visible on @@ -294,6 +301,8 @@ 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('.', "") } @@ -329,6 +338,11 @@ 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. @@ -350,7 +364,7 @@ class VoiceSession( diagnostic("ABORT blockedTurn=$blockedTurn active=${isActive()} listenReset=$listenReset oldTurn=$oldTurn currentTurn=$currentTurn") playback.interrupt() if (isActive()) { - update(state.copy(phase = VoicePhase.LISTENING)) + update(state.copy(phase = VoicePhase.LISTENING, replyEmotion = ReplyEmotion())) startCapture() } } @@ -391,6 +405,8 @@ class VoiceSession( playback.interrupt() preparedPlaybackTurn = null currentTurn = id + emotionEndedTurn = null + update(state.copy(replyEmotion = ReplyEmotion())) hasTurn = true sequence = 1 if (blockedTurn != id) blockedTurn = null @@ -414,7 +430,12 @@ class VoiceSession( } private fun playbackIsCurrent(epoch: Long): Boolean = playback.isCurrent(epoch) private fun isActive() = !released && foreground && state.voiceActive && state.connection == ConnectionStatus.CONNECTED - private fun update(next: VoiceUiState) { state = next; onState(next) } + private fun update(next: VoiceUiState) { + val changed = state.replyEmotion != next.replyEmotion + state = next + onState(next) + if (changed) emotionObserver.onReplyEmotion(next.replyEmotion) + } private fun checkMainThread() { check(Looper.myLooper() === main.looper) { "VoiceSession must be used on main" } } diff --git a/app/src/main/java/com/gorios/lanvoice/dialogue/ReplyEmotion.kt b/app/src/main/java/com/gorios/lanvoice/dialogue/ReplyEmotion.kt new file mode 100644 index 0000000..b335363 --- /dev/null +++ b/app/src/main/java/com/gorios/lanvoice/dialogue/ReplyEmotion.kt @@ -0,0 +1,35 @@ +package com.gorios.lanvoice.dialogue + +/** Role expression for one reply, never a classification of the user's feelings. */ +enum class RoleEmotion(val wire: String, val label: String) { + NEUTRAL("neutral", "中立"), HAPPY("happy", "高兴"), ANGRY("angry", "生气"), SAD("sad", "难过") +} +enum class EmotionSource { MODEL, FALLBACK } +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 label: String get() = emotion.label + when (intensity) { 1 -> "·轻度"; 2 -> "·明显"; else -> "" } + companion object { + fun fromWire(turn: Any?, seq: Any?, emotion: Any?, intensity: Any?, source: Any?): 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 + val kind = RoleEmotion.entries.firstOrNull { it.wire == emotion } + val strength = integer(intensity) + val origin = when (source) { "model" -> EmotionSource.MODEL; "fallback" -> EmotionSource.FALLBACK; else -> null } + if (kind == null || origin == null || !(kind == RoleEmotion.NEUTRAL && strength == 0L || + kind != RoleEmotion.NEUTRAL && strength in 1L..2L) || + origin == EmotionSource.FALLBACK && kind != RoleEmotion.NEUTRAL) { + return ReplyEmotion(turnId = id, sequence = sequence) + } + return ReplyEmotion(kind, strength!!.toInt(), origin, id, sequence) + } + } +} + +/** Main-thread observation point reserved for future visuals; no renderer/service dependency. */ +fun interface ReplyEmotionObserver { fun onReplyEmotion(emotion: ReplyEmotion) } 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 7b19c5f..3f3fa68 100644 --- a/app/src/main/java/com/gorios/lanvoice/expression/ExpressionController.kt +++ b/app/src/main/java/com/gorios/lanvoice/expression/ExpressionController.kt @@ -41,6 +41,7 @@ class ExpressionController( var provider: ProcessCameraProvider? = null // Accessed only on main. var lastSampleMs = Long.MIN_VALUE var lastPublished: List? = null + var lastStableCue = FaceCue.UNKNOWN } private val appContext = context.applicationContext @@ -175,10 +176,11 @@ class ExpressionController( val faceCue = run.faceRules.evaluate(observation, result.faceLandmarks().size, quality, 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) { + if (run.lastPublished != visible || run.lastStableCue != faceCue.cue) { + run.lastStableCue = faceCue.cue run.lastPublished = visible main.post { - if (isCurrent(run)) onState(ExpressionUiState(ExpressionStatus.ACTIVE, visible)) + if (isCurrent(run)) onState(ExpressionUiState(ExpressionStatus.ACTIVE, visible, stableCue = faceCue.cue)) } } } catch (_: Exception) { diff --git a/app/src/main/java/com/gorios/lanvoice/expression/ExpressionState.kt b/app/src/main/java/com/gorios/lanvoice/expression/ExpressionState.kt index 7a334a0..0585712 100644 --- a/app/src/main/java/com/gorios/lanvoice/expression/ExpressionState.kt +++ b/app/src/main/java/com/gorios/lanvoice/expression/ExpressionState.kt @@ -6,4 +6,5 @@ data class ExpressionUiState( val status: ExpressionStatus = ExpressionStatus.OFF, val cues: List = emptyList(), val guidance: String? = null, + val stableCue: FaceCue = FaceCue.UNKNOWN, ) diff --git a/app/src/main/java/com/gorios/lanvoice/expression/ExpressionUi.kt b/app/src/main/java/com/gorios/lanvoice/expression/ExpressionUi.kt index 3a3e32e..077b6f0 100644 --- a/app/src/main/java/com/gorios/lanvoice/expression/ExpressionUi.kt +++ b/app/src/main/java/com/gorios/lanvoice/expression/ExpressionUi.kt @@ -25,13 +25,16 @@ fun ExpressionControls( val enabled = state.status == ExpressionStatus.STARTING || state.status == ExpressionStatus.ACTIVE Column(horizontalAlignment = Alignment.CenterHorizontally) { Row(horizontalArrangement = Arrangement.spacedBy(8.dp), verticalAlignment = Alignment.CenterVertically) { - state.cues.take(2).forEach { cue -> - Text( - cue.label, fontSize = 12.sp, color = Color(0xFFE8C884), - modifier = Modifier.background(Color(0xFF242433), RoundedCornerShape(50)) - .padding(horizontal = 10.dp, vertical = 5.dp), - ) - } + Text( + "你:" + when { + !enabled -> "摄像头已关闭" + state.status == ExpressionStatus.STARTING -> "检测中" + ExpressionCue.FACE_LOST in state.cues -> "无脸" + state.stableCue == FaceCue.SMILING -> "明显微笑" + state.stableCue == FaceCue.BROW_FURROWED -> "明显皱眉" + else -> "未见明显线索" + }, fontSize = 12.sp, color = Color(0xFFE8C884), + ) TextButton(onClick = onToggle) { Text(when { state.status == ExpressionStatus.STARTING -> "取消开启" @@ -47,7 +50,7 @@ fun ExpressionControls( Text(it, fontSize = 12.sp, color = Color(0xFF9CA3AF), textAlign = TextAlign.Center) } Text( - "表情线索仅供参考,不代表真实情绪", + "表情不等于情绪;线索仅供参考,不代表真实情绪", fontSize = 11.sp, color = Color(0xFF9CA3AF), textAlign = TextAlign.Center, ) Row(verticalAlignment = Alignment.CenterVertically) { diff --git a/app/src/main/java/com/gorios/lanvoice/net/DialogueProtocol.kt b/app/src/main/java/com/gorios/lanvoice/net/DialogueProtocol.kt index 6b2f4be..b06a63d 100644 --- a/app/src/main/java/com/gorios/lanvoice/net/DialogueProtocol.kt +++ b/app/src/main/java/com/gorios/lanvoice/net/DialogueProtocol.kt @@ -10,7 +10,7 @@ import com.gorios.lanvoice.expression.FaceCueObservation data class ServerEvent(val type: String, val kind: EventKind, val payload: JSONObject) enum class EventKind { - AUTH, HELLO, HISTORY, LISTEN, VAD, STT, LLM, TTS, ERROR, ABORT, METRICS, PING, PONG, UNKNOWN + AUTH, HELLO, HISTORY, LISTEN, VAD, STT, LLM, TTS, REPLY_EMOTION, ERROR, ABORT, METRICS, PING, PONG, UNKNOWN } /** Header integers are unsigned, network byte order; PCM samples are signed little endian. */ @@ -77,7 +77,7 @@ object DialogueProtocol { val payload = JSONObject(text) val type = payload.opt("type") as? String require(!type.isNullOrBlank()) { "Event is missing a string type" } - val kind = when (type.substringBefore('.')) { + val kind = if (type == "reply.emotion") EventKind.REPLY_EMOTION else when (type.substringBefore('.')) { "auth" -> EventKind.AUTH "hello" -> EventKind.HELLO "history" -> EventKind.HISTORY diff --git a/docs/PLAN.md b/docs/PLAN.md index 6182340..e7140f1 100644 --- a/docs/PLAN.md +++ b/docs/PLAN.md @@ -200,3 +200,19 @@ APK 侧实现、编译及依赖校验元数据固化已完成。用户在外部 - 首次表情接入产生双 system 模板 HTTP400 回归;实际对比单 system HTTP200 后修复并复验通过。此回归与旧手机报告 1011 分开记录,原1011未复现/未归因,不能宣称根治;未做真机出声或真人有效回答验收。 - 普通 workspace shell 使用 ./scripts/build.sh 构建成功;真实版本 0.4.0/code7,arm64,签名与上一版一致。APK artifacts/lan-voice-v040-arm64-debug.apk,31,433,233B,SHA256 5a6f88cb2f825dbcd5c7b8c1f212b369534bc53c49533e196fb5e9287902e934;现有 HTTP 下载校验一致。 - agent 沙箱 socket/只读 Gradle 缓存限制未解除;受控部署、实链路与构建由本 workspace 普通 shell 执行。只重启网关以加载代码,未重启模型/其他服务,备份与回滚脚本已提供。 + +## 13. 0.5.0 角色回复七状态实施记录 + +- 可恢复服务端完整源码先独立提交并推送为 `19a7adccd9322986eb0646b165b9ce1cf2650cf2`(gateway/,58 文件);Android/语音基线 `9b428fb` 已推送。之后功能直接修改并部署同仓 gateway/,不以历史 backend patch 代替完整源码。 +- 新增 reply_emotion.py 结构解析/回退、独立 reply.emotion 事件;原单次Qwen调用与单system合并persona/本轮表情片段,只有提取正文进入历史与连续语音单TTS generator。neutral/0及happy/angry/sad各1/2,是角色表达意图,不是用户心理分类,不新增模型/推理服务/依赖。 +- Android 新增 ReplyEmotion 数据结构/观察接口,白名单校验、当前turn/seq隔离、播放期间保持,abort/断线/新轮/正常drained清除;分别显示用户稳定表情线索和角色表达。摄像头与表情共享仍默认关闭,原3秒TTL与禁用清除策略不变。 +- 真实Qwen两个固定问题兼容通过:单system prompt-only JSON,HTTP200 neutral/0及happy/2;仅为有限接口兼容,不代表稳定性或首音增量。客户端/表达规则/纯parser设备doubles回归及全量Kotlin/Compose源码编译通过;完整gateway暂存/部署/实链路与APK仍须普通shell执行,不能把源码检查当APK或真机播放验收。 +- 实际版本已递增为0.5.0/code8,新APK计划独立归档v050,保留v040。完整协议、回退、哈希备份测试busy部署/回滚、验证边界见 [REPLY_EMOTION_050.md](REPLY_EMOTION_050.md),完成外部验收后追加数值证据。 + + +## 14. 独立provider + emotion合并交付(2026-10-12) + +- 本session先备份原30个未提交功能文件,白名单同步SPARK最新provider源与tests,以实际 `d088bedc…` gateway为基底保留Qwen/Doubao接口,再合入单system结构解析/七状态;不使用已过期patch覆盖provider。配置/凭据不归档、不改变在线Qwen。 +- 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,运行模型/密钥/证书未改。 diff --git a/docs/REPLY_EMOTION_050.md b/docs/REPLY_EMOTION_050.md new file mode 100644 index 0000000..a26a2b8 --- /dev/null +++ b/docs/REPLY_EMOTION_050.md @@ -0,0 +1,84 @@ +# 0.5.0 角色回复表达 + +完整服务端源码基线已先提交并推送:`19a7adccd9322986eb0646b165b9ce1cf2650cf2`(`gateway/`,58 文件);Android/语音修复基线为 `9b428fb76ffa1468aa46124b33d9c598cf3740d8`。`backend/gateway.patch` 仅为历史 0.4.0 补丁,0.5.0 部署直接使用同仓 `gateway/` 完整源码。`SOURCE_MANIFEST.json` 记录源码 SHA256、原始来源及修改前哈希;运行数据、模型、音频参考、凭据和诊断报告不归档。 + +## 一轮协议与回退 + +沿用同一个可配置 provider 的单次 LLM 调用、单条 system(固定结构约束 + 原 persona/lore + 本轮可选白名单摄像头辅助片段),prompt-only JSON,不依赖 `json_schema` 或增加模型。最多 160 token,30 秒超时、8192 字符结构缓冲上限。结果为 `{"reply":"正文","emotion":"neutral","intensity":0}`。完整解析之后只发布提取的 `reply` 为 `llm` 正文、历史及 TTS 输入;所有已接受 voice_mode 均只将完整 reply 送入一个 generator,TTS 音色、参考和参数不变。 + +| emotion | intensity | 显示 | +|---|---:|---| +| neutral | 0 | 中立 | +| happy | 1 / 2 | 高兴·轻度 / 明显 | +| angry | 1 / 2 | 生气·轻度 / 明显 | +| sad | 1 / 2 | 难过·轻度 / 明显 | + +情绪是角色本轮表达意图,不是用户心理诊断;普通问答默认中立,内容和帮助性优先,不根据皱眉强行生气或攻击。每轮一个主表达,无混合、逐句或长期状态。 + +提取正文后、入 TTS 队列前发独立事件: + +```json +{"type":"reply.emotion","turn_id":2,"seq":19,"emotion":"happy","intensity":1,"source":"model"} +``` + +`turn_id` 是当轮 uint32,`seq` 使用已有服务端事件序列;hello 广告 `reply_emotion_version=1`。非法/缺失情绪或强度(包括 bool/float 类型)、多余结构字段回退 `neutral/0/source=fallback`,保留可用 reply。损坏 JSON 可通过 JSONDecoder 提取完整 quoted reply;截断字符串仅做字符串终止修复;兼容 text/answer 正文、普通非 JSON 文本,均 fallback。无可用正文使用固定简短重说提示,绝不把结构包或嵌套 JSON 原样读出,不进行第二次模型请求。空模型输出仍显式 backend_failed,不冒充有效回答。 + +Android `dialogue/ReplyEmotion.kt` 提供有限枚举及 `ReplyEmotionObserver`;turn/seq 必须整型有效,表达字段非法则中立 fallback。表达事件不得自行建立/切换轮次;仅接收已声明当前 turn,同轮 seq 更旧/重复、退休轮、未声明轮及已 drained 轮忽略。播放期间保留,tts.stop 不是播放结束;原生播放头 drained 后归中立,abort/本地打断/断线/新轮/停止归中立。界面没有回复气泡,本次不增加。 + +## UI 与摄像头独立性 + +顶部分别显示“你:明显微笑 / 明显皱眉 / 无脸 / 未见明显线索 / 摄像头已关闭”以及“角色:中立 / 高兴·明显”等。用户线索使用已有持续阈值与迟滞,未把眼动、头部姿态或闭眼分类为情绪,不显示概率。摄像头和“将表情线索用于对话”开关仍默认关闭,无持久化;摄像头按钮授予权限后启动,分享开关才允许白名单控制发送。界面明确“表情不等于情绪;线索仅供参考”。 + +分享仅含 smiling/brow_furrowed、规则强度/持续时间/age,无图像、landmarks、完整 blendshape 或任意文本。最多 1Hz;关闭分享/摄像头、无脸、离开前台或停止语音清除。网关以 client age + server 接收后单调耗时 <=3秒 TTL,在 ASR 完成、LLM 开始前单次快照;不阻塞等待摄像头、不保留到历史或未来轮次。已提交的本轮 LLM 快照不被关闭开关追溯取消。 + +## 验证及边界 + +2026-10-12 本 session 有限兼容检查:当前 Qwen 与保存的 Doubao 各两个固定公开问题,单 system prompt-only JSON 均 HTTP200、source=model、finish_reason=stop;普通问答 neutral/0、祝贺 happy/2。Qwen 耗时 845.84/1606.58 ms,完整结构等待 675.43/1348.62 ms;Doubao 耗时 1074.11/1311.60 ms,完整结构等待 21.87/234.58 ms。Doubao 只在测试子进程加载已有 key 文件与 provider 文件,在线配置未改变;首次未加载独立 key 文件的检查返回401,补充正确加载关系后通过,未修改凭据。alias `doubao-seed-2-1-pro` 不代表真实权重,既有 LiteLLM 审计记录实际 model 为 `doubao-seed-2-0-mini-260428`,本次未重新证明真实权重。这是接口兼容证据,不是稳定性、七情绪语义准确率或首音延迟增量保证。 + +本地纯 parser 覆盖全部七状态、缺字段/非法枚举/强度/bool/float、截断/损坏/围栏/嵌套包、可用正文回收和安全提示。完整 gateway 回归以 HTTP doubles 验证七状态及坏结构/坏标签的正文/历史/TTS隔离、单system/单generator、首PCM前情绪、旧轮抑制及取消;默认无脸与单轮摄像头上下文仍有回归。客户端使用真实生产 coordinator/parser/model 和 Android/transport doubles,验证七状态、旧轮/未声明轮/乱序、drained及abort清除;播放/录音回归保留。 + +本 session 客户端 coordinator/播放/采集/协议、表达规则和纯 parser 回归通过。完整 gateway 在 SPARK2 现有 venv 的临时目录运行,64项全部通过,包括校验并读取既有 Silero artifact 的测试,不触碰在线模型服务。provider 默认Qwen、显式Doubao kwargs隔离、Authorization只进header、单请求无fallback、结构正文/历史/TTS隔离、七状态、取消与TTL均有回归。日志只记录测试输出、数值、枚举、哈希,不提交。 + +结构化输出需等完整解析再生成首音。记录 `llm_first_token_ms`、`llm_first_body_ms`、`structured_wait_ms`(完整结构等待减首token)、`reply_parse_ms`、`capture_to_first_pcm_ms` 和 TTS 首PCM时延。单轮比较不能归因出纯结构化开销;不声称零延迟。 + +原始手机 1011 没有足够因果堆栈、未复现;0.4.0 双system模板 HTTP400 是另一次引入且已修复的回归,不能混为一谈。原诊断中部分轮次已有PCM,缺少真机播放头/路由/音量证据,真人播放仍未验证。公开样本非空LLM/PCM及协议drained确认不等于真机可听或真人有效回答。 + +## 受控操作 + +本次独立 session 在用户设置 Full Access 后完成网络、测试、部署、构建和 Git 交付;不新开 pane/agent,不重启模型/ASR/TTS 或其它项目服务。 + +```sh +python3 scripts/deploy-gateway-source.py # 仅暂存测试 +python3 scripts/deploy-gateway-source.py --apply # 哈希/备份/测试/busy检查后,仅重启网关 +python3 scripts/probe-reply-emotion.py # 一次公开短样本,非空LLM/PCM、情绪顺序、单TTS、drained及表情快照 +./scripts/package-emotion-release.sh # build.sh + 真版本/签名/ABI/HTTP字节校验 +``` + +部署前核对归档的所有运行 Python 源码及原测试文件哈希,测试后再核对,拒绝并发修改和忙会话;不覆盖运行配置/音色/persona/数据库。原文件受控备份,健康检查失败自动恢复并仅重启网关;手工恢复当前这次部署为 `python3 scripts/rollback-gateway-source.py`,也核对精确部署哈希和busy,绝不恢复旧历史补丁。新增模块与回归一并部署,源码在同仓可恢复,测试模块独立临时根目录。 + +实际 Android versionName=0.5.0/code8。新产物 `artifacts/lan-voice-v050-arm64-debug.apk`,打包拒绝覆盖已存在版本;0.4.0 产物哈希核对保留。验签与0.4.0同签名、aapt badging arm64/版本、下载的HTTP字节SHA256一致才发布。 + + +## Provider 合并基线 + +本次先受控备份原30个功能修改文件,再白名单取回服务器最新Python源/tests并核对hash。当前 `gateway.py` 基线为 `d088bedcf5c0accd4712e06202f6ced8ab155aad57a5b05683724efa346326ce`,provider基线为 `7d853adbe79f5f861a36894a9dfa28aa553d3eabea4db4c87a5fb4c319818ef1`;完整来源在 `gateway/SOURCE_MANIFEST.json.provider_baseline`。以实际provider gateway为基底替换generate结构解析并保留其余代码。`request(messages, max_tokens=160)`是情绪轮次显式预算,原provider默认64不变。 + +缺省使用Qwen `http://127.0.0.1:8888/v1` / `qwen3.8-27b` / `enable_thinking=false`。切换接口为四个 `LAN_LLM_*` 环境变量;Doubao走既有LiteLLM `http://192.168.31.53:4000/v1`,精确alias `doubao-seed-2-1-pro`,kwargs `{}`,key仅Authorization。后台persona/default和音色继续原配置。部署不覆盖.env、私钥、证书、token或persona;服务器备份包括完整Python代码/测试、权限和私有unit/env加载关系,只重启gateway。历史backend patch不再允许由旧deploy脚本重新覆盖provider。 + + +## 本 session 部署与整链路结果(2026-10-12) + +在测试前、测试后及备份后核对源码/私有环境关系与busy,64项全量gateway测试再次通过(测试本身0.938秒,暂存检查1555.16 ms)。已部署canonical source,健康ok,unit/env加载关系未改;仅restart `lan-voice-gateway.service`。服务器备份为 `/home/gorios-spark-2/lan-voice/.runtime/backups/voice-v050-20261012-105306`,包含完整Python代码/tests、文件权限以及只留在服务器的unit/env备份。模型/ASR/TTS/证书/token/音色均未改。 + +一次3.36秒公开音频经过ASR→当前Qwen→TTS:STT14字,reply23字,happy/1/source=model;独立情绪事件1个,在首PCM前;只有正文进入LLM事件与一次TTS请求。216帧/414720B/4.32秒PCM,peak7961、RMS1161.75,序号连续且从1开始;协议drained ack,合成表情cue的ASR后快照使用成功、非法face控制未关连接。总backend时间6698.10 ms,capture→首PCM2426.19 ms;首LLM token379.72 ms,完整结构2130.63 ms,结构等待1750.91 ms,parse0.27 ms,TTS首PCM197.89 ms。单轮不能推导稳定性、延迟分布或结构化纯增量;不声称零开销。 + +重启后重新读取实际进程环境并按provider默认规则解析,仍为 `http://127.0.0.1:8888/v1` / `qwen3.8-27b` / `enable_thinking=false`,无API key要求。Doubao仅完成公开问题接口检查和synthetic SSE回归,没有在线切换或Doubao整音频链路验收。7状态是规则/协议覆盖,不是7状态真人语义准确率。手机播放、摄像头真机采集、连续真人轮次及原1011根因未验收;保留诊断按钮供用户试听后调查。 + + +## APK交付结果 + +`./scripts/package-emotion-release.sh` 先校验client/deploy/probe/兼容记录与源码hash,再调用既有 `./scripts/build.sh`(加载 `/home/ubuntu/android-build/env.sh` 的JDK17,沿用既有Gradle缓存,不覆盖工具链)。Gradle assembleDebug成功(17秒)。aapt确认 `com.gorios.lanvoice`、versionName0.5.0/code8、minSdk26、唯一ABI arm64-v8a;apksigner验签通过且签名证书与0.4.0一致,可覆盖安装。0.4.0原APK及其hash保持。 + +新APK 31,433,292字节,SHA256 `da47f7a08f63a68fbb6dbe7fb3d803ee58b402de393112a32f92a63ad50c1f33`。现有下载服务 `http://192.168.31.124:8080/lan-voice-v050-arm64-debug.apk` 返回HTTP200,下载内容SHA256与本地一致。此为debug APK,尚未安装/试听MI MAX3;真实播放和摄像头仍由用户验收。源码/tests/docs提交,APK与日志不进Git。 + +回退:在同workspace运行 `python3 scripts/rollback-gateway-source.py`,仅在当前代码hash精确匹配此次部署、unit/env未变且gateway不busy时,按原权限恢复此次服务器备份并仅restartgateway;遇并发修改拒绝回退。自动失败回退也先核对文件仍是本次原始/部署版本,不覆盖并发编辑。手机若需降级0.4.0,Android versionCode7低于8,普通覆盖安装会拒绝;卸载后安装会清除应用数据,请按实际手机需要选择,不自动操作手机。 diff --git a/gateway/README.md b/gateway/README.md index e967667..cb1bd96 100644 --- a/gateway/README.md +++ b/gateway/README.md @@ -16,3 +16,12 @@ This directory contains the actual deployed SPARK-2 source, not just an Android- 8. Verify HTTPS health and authorized Origin/auth/hello/history, then run one bounded public-sample protocol check. Real Android speaker playback still needs a real phone; nonempty backend PCM does not prove audible output. The v0.4.0 repair/context protocol and evidence boundaries are documented in `../docs/VOICE_REPAIR_040.md`. Archive and future deployments use this workspace's scripts with hash, backup, tests and busy checks. Archiving itself does not deploy or restart anything. + +The 0.5.0 canonical source adds `reply_emotion.py`: one-system structured provider reply, validated one-turn role expression and reply-only speech/history. See `../docs/REPLY_EMOTION_050.md`. `scripts/deploy-gateway-source.py` in the repository root tests this complete source tree, hash-fences deployed modules, backs up and restarts only the gateway. Use that script for current releases; historical `backend/gateway.patch` is not the current restore source. `SOURCE_MANIFEST.json` includes current hashes and retained original provenance; a legacy 0.7.1 health version does not advertise feature completeness, so inspect hello capabilities. + + +`llm_provider.py` preserves the configurable OpenAI-compatible provider interface: `LAN_LLM_BASE_URL`, `LAN_LLM_MODEL`, private `LAN_LLM_API_KEY` (Authorization header only), and optional JSON-object `LAN_LLM_CHAT_TEMPLATE_KWARGS`. Missing configuration defaults to local `http://127.0.0.1:8888/v1`, `qwen3.8-27b`, thinking disabled. Non-Qwen model defaults omit Qwen kwargs; explicit kwargs stay local to that provider. The provider's original default budget is 64; the structured dialogue explicitly requests 160. There is no automatic failover or retry. Doubao's `doubao-seed-2-1-pro` is a LiteLLM alias, not evidence of actual model weights. + +`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. diff --git a/gateway/SOURCE_MANIFEST.json b/gateway/SOURCE_MANIFEST.json index cfc1b08..c873c81 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.1", + "code_version": "0.7.1 (legacy health version; reply.emotion version 1 capability)", "python": "3.12.3", "machine": "aarch64", "scope": "whitelisted source only; no runtime/models/credentials", @@ -32,9 +32,10 @@ "bytes": 2997 }, "gateway.py": { - "source": "gateway.py", - "sha256": "725577a378b688c24519ab2a0a9dfdb48723f365309e7ccccc9fc1de26c2894f", - "bytes": 38598 + "source": "workspace:gateway/gateway.py", + "sha256": "d9215f99339de0667e830fbd4d3bff80ac5a61c85630cc4ecadcb52a4c33a0e5", + "bytes": 37391, + "upstream_sha256": "d088bedcf5c0accd4712e06202f6ced8ab155aad57a5b05683724efa346326ce" }, "guest_sessions.py": { "source": "guest_sessions.py", @@ -117,9 +118,10 @@ "bytes": 2206 }, "tests/test_continuity.py": { - "source": "tests/test_continuity.py", - "sha256": "6dd818484a064dc3fc9efe5ca71cc11ffcd3a0dcc45ea4185065732dab0289cc", - "bytes": 2769 + "source": "workspace:gateway/tests/test_continuity.py", + "sha256": "d8390238f390463a98f12b9909bb5846be65f5b6dc1b21b94338b4cd75aaafae", + "bytes": 2786, + "upstream_sha256": "6dd818484a064dc3fc9efe5ca71cc11ffcd3a0dcc45ea4185065732dab0289cc" }, "tests/test_debug.py": { "source": "tests/test_debug.py", @@ -235,6 +237,112 @@ "source": "deployed interpreter distribution metadata", "sha256": "26fec2a2814c6b52cc50015e3b838a4c42c257b495db66482f65e33c7207f90c", "bytes": 5539 + }, + ".gitignore": { + "source": "workspace:gateway/.gitignore", + "sha256": "7e416b444fb60e87e974827b31a18a16e9a519a3a5bd38e972b6e3c079784b37", + "bytes": 115 + }, + "README.md": { + "source": "workspace:gateway/README.md", + "sha256": "808a77916a8ba477cd6d95ae255cc661239c97031760d83fe38ea43c571deb6d", + "bytes": 6666, + "upstream_sha256": "799bc84308eb17d58987c5bee8ce3cf7617b4c52169d9307d344ac7d9996b6c5" + }, + "config/active_profile.json.example": { + "source": "workspace:gateway/config/active_profile.json.example", + "sha256": "459f6ecbb0b431614eba68d19af0c792eaedc27aadd67d44a547900e78d78006", + "bytes": 82 + }, + "config/personas/lvbu.json.example": { + "source": "workspace:gateway/config/personas/lvbu.json.example", + "sha256": "8215a424addcc03a108c130fe91892ce1de78a122565ac9fdde0d986661c3c83", + "bytes": 53 + }, + "config/personas/yangmi_fiction.json.example": { + "source": "workspace:gateway/config/personas/yangmi_fiction.json.example", + "sha256": "0a959b34bb824b93314db01e722d6d4d445ad9dacd047a2f468706bcff2f0fe9", + "bytes": 55 + }, + "deploy/gateway.service.example": { + "source": "workspace:gateway/deploy/gateway.service.example", + "sha256": "9cbb5fcbf3f5df5c51d8b5d5020764e101903bc71d3d95ea10f6d1e006e7fe4f", + "bytes": 570 + }, + "env.example": { + "source": "workspace:gateway/env.example", + "sha256": "ec703e599d66f6848f7a4415da851a87c8446dd92805a8ce83e46bd690502367", + "bytes": 796, + "upstream_sha256": "d92e60812f49b02f3b0582d8b3dee03eb51cfca6dba77d9468a3ffddfce32499" + }, + "pytest.ini": { + "source": "workspace:gateway/pytest.ini", + "sha256": "bc43448d7cfda3a84a240f9f4d6799b27ad0f2c6d4525dcfed577d14fccb1253", + "bytes": 144 + }, + "reply_emotion.py": { + "source": "workspace:gateway/reply_emotion.py", + "sha256": "488fbd24ff1ce7d3d4ab92257c8ccabafe24fc857e11c8486f54fa689276a565", + "bytes": 3114 + }, + "scripts/check-archive.py": { + "source": "workspace:gateway/scripts/check-archive.py", + "sha256": "6b5463e16b2cc68e4ef6e0c5cf8582fe18cc58df9d2ab63122153a428677af45", + "bytes": 2878, + "upstream_sha256": "e86ad90244932543fd653ed07e158cf96dba7c61e7945685c9c98bd044c41e5a" + }, + "tests/test_gateway_emotion.py": { + "source": "workspace:gateway/tests/test_gateway_emotion.py", + "sha256": "fc01e9319263b93adb1cc93904d23a13a25965ddb0fcfbd9c3e14e39f4cf52a5", + "bytes": 4589, + "upstream_sha256": "86f22211e753e4b5ebfa11266e2e33eb2ea6b85707fbe8a988be6b8ff05f3f75" + }, + "tests/test_reply_emotion.py": { + "source": "workspace:gateway/tests/test_reply_emotion.py", + "sha256": "324fdaf55b501a31af129d41e9cf459f741ff0636818a6c628657dfde3fa6344", + "bytes": 2701, + "upstream_sha256": "e45ccda640ef758fcb925d53804071349bdc8fb9f43ee1f63d1afb2ee3f238f5" + }, + "llm_provider.py": { + "source": "workspace:gateway/llm_provider.py", + "sha256": "56ce6c1a4a647dea6ef86a83615f03db3a4397ebb3fa800b7fa655147d4f9978", + "bytes": 1471, + "upstream_sha256": "7d853adbe79f5f861a36894a9dfa28aa553d3eabea4db4c87a5fb4c319818ef1" + }, + "tests/test_llm_provider.py": { + "source": "workspace:gateway/tests/test_llm_provider.py", + "sha256": "45404653daa71a006a90852b2f07f00cac608bd7311dd5ea850da0c1a3e52940", + "bytes": 5601, + "upstream_sha256": "6a8bd33679d68899c2a978bf4de672578517494c613b8e77d275c6207de3285b" + } + }, + "archive_baseline_commit": "19a7adccd9322986eb0646b165b9ce1cf2650cf2", + "workspace_release": "0.5.0", + "provider_baseline": { + "source": "SPARK2 whitelist observed 2026-10-12", + "files": { + "app.py": "d6520894dfbe035f64b1984aae15976db4df0e7e720195c81d3bf483b240056f", + "protocol.py": "d9f522d958935200002e56024949a12b71eb89b3f3241635c5c307b798ee71c5", + "gateway.py": "d088bedcf5c0accd4712e06202f6ced8ab155aad57a5b05683724efa346326ce", + "tests_fake.py": "9a40f1948352f69f1dd20f8514baef58ae3d11eec240e1d2324d8990bad915d8", + "history.py": "2cf8b006bf486a03e038a69daa860ebb71a86989161cf6a7ea610114177a249f", + "vad.py": "3718ff9b296b2bba447100af520a631f221dcbfa322dd564cdc5809fb3675f23", + "persona_resolver.py": "deb33b4f4c17792fa5a6837362d5b29173e60a57bb993b61363bd4882d66d5de", + "tts_debug.py": "d7b31b98a7f8ab688981873ef81decdf0b2f0167113c9103df039b7b24c9ccf2", + "guest_sessions.py": "cc082fdb6c2ff7f5a41361ffe9ea2a53ebb944ee37354f65119405ad7a521c82", + "llm_provider.py": "7d853adbe79f5f861a36894a9dfa28aa553d3eabea4db4c87a5fb4c319818ef1", + "face_context.py": "01abfc214ebb4e979faf9430166eccae9af37df911d36da5435f907769e7e31a", + "segmentation.py": "562ffc6e06f5b9f9072860b588feae3a5d7cd6eaa8577ac928d770071b06978d", + "tests/test_debug.py": "26f9e374354b714ab1a03b56af90bcbf32135711dc4f26e2c53eaa90c7f02ddd", + "tests/test_gateway.py": "f22aa98f3d6f62a2949a9047ec97e6dd686cac807d989a314a95deca718a3104", + "tests/test_history.py": "fc13a69811cfc4f4acf265ea9e0cdd67d566358ebe9b9b53cae76197db8bce78", + "tests/test_guests.py": "6bc531f1bff85b8ea550bc88c634726531a1ef241ba5c861dbb8c963adf31c35", + "tests/test_vad.py": "bff64c0aafa05c085af7c1c9418244609129d405320fe1080b4ba05a8e304228", + "tests/test_continuity.py": "6dd818484a064dc3fc9efe5ca71cc11ffcd3a0dcc45ea4185065732dab0289cc", + "tests/test_personas.py": "2576f2be903c69270cb1dec1e12448154554798bd7fca866d78e66e31594cbcb", + "tests/test_segmentation.py": "cf80a74958a715a81180a7932efb84f1d0974b434cf4fc3354b68c604ccbf463", + "tests/test_llm_provider.py": "6a8bd33679d68899c2a978bf4de672578517494c613b8e77d275c6207de3285b", + "tests/test_v08.py": "f993d4162576494e814786f26376ba80ab8a77af98ba70de4379055bb9525082" } } } diff --git a/gateway/env.example b/gateway/env.example index fcc5a01..ef0d997 100644 --- a/gateway/env.example +++ b/gateway/env.example @@ -4,3 +4,11 @@ LAN_OPEN_MODE=1 LAN_GUEST_ENABLED=1 # The optional independent VAD service also needs its own secret. LAN_VAD_TOKEN=REPLACE_WITH_A_DIFFERENT_RANDOM_SECRET_AT_LEAST_32_CHARS +# Optional provider settings; absence keeps the existing local Qwen defaults. +LAN_LLM_BASE_URL=http://127.0.0.1:8888/v1 +LAN_LLM_MODEL=qwen3.8-27b +LAN_LLM_CHAT_TEMPLATE_KWARGS={"enable_thinking":false} +# Set API keys only in a private environment file. Do not commit them. +# LAN_LLM_API_KEY=REPLACE_WITH_PRIVATE_PROVIDER_KEY +# Doubao through existing LiteLLM: base http://192.168.31.53:4000/v1, +# model alias doubao-seed-2-1-pro, kwargs {}. Alias does not identify actual weights. diff --git a/gateway/gateway.py b/gateway/gateway.py index 51daaea..833aa73 100644 --- a/gateway/gateway.py +++ b/gateway/gateway.py @@ -19,10 +19,12 @@ from fastapi.staticfiles import StaticFiles import uuid from history import History from face_context import FaceContext +from reply_emotion import SYSTEM_FRAGMENT, parse_reply from guest_sessions import GuestSessions, COOKIE from tts_debug import DebugStore from persona_resolver import resolve_persona from segmentation import Segmenter +from llm_provider import LLMProvider from app import EXPECTED_HASH from protocol import WavStream, pack, unpack from vad import Config, Silero, VadSession @@ -202,6 +204,7 @@ async def debug_download(request: Request): class Dialogue: def __init__(self, ws, model, client, history=None, conversation_id=None): self.ws, self.client = ws, client + self.llm_provider = LLMProvider() self.history = history self.conversation_id = conversation_id self.run_id = None @@ -461,71 +464,51 @@ class Dialogue: await self.drained() async def generate(self, turn, text, queue, metrics, began): - segmenter = Segmenter(getattr(self, 'synthesis_mode', 'balanced')) request_start = time.perf_counter() - continuous = self.voice_mode == 'continuous_voice' - full_text = '' metrics.update(voice_mode=self.voice_mode, voice_id=self.voice_id, tts_request_count=0) + # Exactly one initial system: Qwen's deployed template rejects a second system. + system = '以下角色设定只约束reply字段的口述内容;其中旧有不输出JSON等格式约定不约束本轮外层结构。\n' + self.persona_rules + ''.join( + '\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) + raw_body = '' + async with asyncio.timeout(30): + async with self.client.stream('POST', url, headers=headers, json=body) as response: + response.raise_for_status() + event_data = [] + async for line in response.aiter_lines(): + if turn != self.turn: return + if line.startswith('data:'): event_data.append(line[5:].lstrip()) + if line != '' or not event_data: continue + raw = '\n'.join(event_data); event_data = [] + if raw == '[DONE]': break + data = json.loads(raw) + for choice in data.get('choices', []): + 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)) + raw_body += delta + if len(raw_body) > 8192: raise ValueError('structured reply limit') + 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) + 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) + metrics['structured_wait_ms'] = round(metrics['llm_first_body_ms'] - metrics.get('llm_first_token_ms', 0), 2) + metrics['llm_finished_ms'] = round((time.perf_counter() - began) * 1000, 2) + # 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('llm.finished', turn, voice_mode=self.voice_mode, llm_finished_ms=metrics['llm_finished_ms']) async def enqueue(fragment): if fragment: - if 'first_fragment_ms' not in metrics: metrics['first_fragment_ms'] = round((time.perf_counter() - began) * 1000, 2) - metrics['segment_hardcuts'] = segmenter.hardcuts - metrics['segment_last_cut'] = segmenter.last_cut + metrics.setdefault('first_fragment_ms', round((time.perf_counter() - began) * 1000, 2)) await queue.put(fragment) - async with asyncio.timeout(30): - async with self.client.stream('POST', 'http://127.0.0.1:8888/v1/chat/completions', json={'model': 'qwen3.8-27b', 'messages': [{'role': 'system', 'content': '用简短中文直接回答,不输出思考过程、动作旁白、Markdown或JSON。最多两小句。' + self.persona_rules + ''.join('\n\n' + item['content'] for item in self.face_messages.get(turn, []))}] + self.contexts.get(turn, []) + [{'role': 'user', 'content': text}], 'max_tokens': 64, 'temperature': 0.3, 'stream': True, 'chat_template_kwargs': {'enable_thinking': False}}) as response: - response.raise_for_status() - lines = response.aiter_lines().__aiter__() - pending = asyncio.create_task(anext(lines)) - event_data = [] - try: - while True: - timeout = None if continuous else segmenter.timeout(time.perf_counter()) - done, _ = await asyncio.wait({pending}, timeout=timeout) - if not done: - await enqueue(segmenter.take(time.perf_counter())); continue - try: line = pending.result() - except StopAsyncIteration: break - pending = asyncio.create_task(anext(lines)) - if line.startswith('data:'): event_data.append(line[5:].lstrip()) - if line != '' or not event_data: continue - raw = '\n'.join(event_data); event_data = [] - if raw == '[DONE]': break - data = json.loads(raw) - for choice in data.get('choices', []): - delta = choice.get('delta', {}).get('content') or '' - if not delta: continue - if 'llm_first_body_ms' not in metrics: - metrics['llm_first_body_ms'] = round((time.perf_counter() - request_start) * 1000, 2) - if turn != self.turn: return - self.answers[turn] = (self.answers.get(turn, '') + delta)[:2000] - await self.event('llm', turn, text=delta) - full_text += delta - if len(full_text) > 1000: raise ValueError('TTS full text limit') - if not continuous: - await enqueue(segmenter.add(delta, time.perf_counter())) - while True: - fragment = segmenter.take(time.perf_counter()) - if not fragment: break - await enqueue(fragment) - if turn != self.turn: return - if not full_text.strip(): raise ValueError('empty LLM body') - metrics['llm_finished_ms'] = round((time.perf_counter() - began) * 1000, 2) - await self.event('llm.finished', turn, voice_mode=self.voice_mode, llm_finished_ms=metrics['llm_finished_ms']) - if continuous: - await enqueue(full_text.strip()) - else: - remainder = segmenter.take(time.perf_counter(), final=True) - queued = [] - while not queue.empty(): - queued.append(queue.get_nowait()) - combined = ''.join(queued) + (remainder or '') - if combined: - metrics['final_queued_merge_chars'] = len(combined) - await enqueue(combined) - finally: - pending.cancel() - with contextlib.suppress(asyncio.CancelledError, StopAsyncIteration): await pending + # A validated reply is a single synthesis input in every voice mode. + await enqueue(result.reply) await queue.put(None) async def synthesize(self, turn, queue, metrics, began): @@ -655,7 +638,7 @@ async def dialogue(ws: WebSocket): session.voice_id = voice_id session.debug_store = app.state.debug session.debug_enabled = hello.get('tts_debug', True) is True - await session.event('hello', context_face_cue_version=1, version=VERSION, codec='pcm16', sample_rate=16000, output_sample_rate=48000, channels=1, frame_duration=20, header_version=1, conversation_id=cid, duplex_default=True, voice_mode=voice_mode, voice_id=voice_id, voices=app.state.voices) + await session.event('hello', context_face_cue_version=1, reply_emotion_version=1, version=VERSION, codec='pcm16', sample_rate=16000, output_sample_rate=48000, channels=1, frame_duration=20, header_version=1, conversation_id=cid, duplex_default=True, voice_mode=voice_mode, voice_id=voice_id, voices=app.state.voices) await session.send_history() started = time.monotonic() while time.monotonic() - started < 600: diff --git a/gateway/llm_provider.py b/gateway/llm_provider.py new file mode 100644 index 0000000..a27783b --- /dev/null +++ b/gateway/llm_provider.py @@ -0,0 +1,27 @@ +import json +import os +from urllib.parse import urlsplit + + +class LLMProvider: + def __init__(self, environ=None): + env = os.environ if environ is None else environ + self.base_url = env.get('LAN_LLM_BASE_URL', 'http://127.0.0.1:8888/v1').rstrip('/') + self.model = env.get('LAN_LLM_MODEL', 'qwen3.8-27b') + self.api_key = env.get('LAN_LLM_API_KEY', '') + url = urlsplit(self.base_url) + if url.scheme not in ('http', 'https') or not url.hostname or url.username or url.password or url.query or url.fragment: + raise ValueError('invalid LLM base URL') + if not self.model or any(c in self.api_key for c in '\r\n'): + raise ValueError('invalid LLM configuration') + raw = env.get('LAN_LLM_CHAT_TEMPLATE_KWARGS') + self.template_kwargs = json.loads(raw) if raw is not None else ({'enable_thinking': False} if self.model.lower().startswith('qwen') else {}) + if not isinstance(self.template_kwargs, dict): + raise ValueError('invalid LLM chat template kwargs') + + def request(self, messages, *, max_tokens=64): + body = {'model': self.model, 'messages': messages, 'max_tokens': max_tokens, 'temperature': 0.3, 'stream': True} + if self.template_kwargs: + body['chat_template_kwargs'] = self.template_kwargs + headers = {'Authorization': 'Bearer ' + self.api_key} if self.api_key else {} + return self.base_url + '/chat/completions', headers, body diff --git a/gateway/reply_emotion.py b/gateway/reply_emotion.py new file mode 100644 index 0000000..9c74a94 --- /dev/null +++ b/gateway/reply_emotion.py @@ -0,0 +1,59 @@ +"""Bounded structured role expression; never return the raw model envelope as speech.""" +from dataclasses import dataclass +import json +import re + +SYSTEM_FRAGMENT = '''本轮只输出一个JSON对象,格式为{"reply":"简短中文回答","emotion":"neutral","intensity":0},不加代码围栏或额外文字。reply直接回答用户,最多两小句,不含情绪标签、动作旁白或思考过程。emotion是角色本轮表达意图,不是用户心理判断;只允许neutral(intensity=0)、happy/angry/sad(intensity=1轻度或2明显)。普通问答默认neutral;帮助性和用户台词优先,不为表演牺牲回答,不根据摄像头皱眉强行生气或攻击。每轮仅一个主情绪,无混合或长期状态。''' +SAFE_REPLY = '抱歉,这次回答格式有误,请再说一次。' + +@dataclass(frozen=True) +class ReplyEmotion: + reply: str + emotion: str = 'neutral' + intensity: int = 0 + source: str = 'fallback' + + +def clean_reply(value): + if not isinstance(value, str): return None + value = value.strip() + # Structured envelopes/code must never become TTS input, including nested replies. + if not value or len(value) > 1000 or value.startswith(('{', '[', '```')): return None + if re.search(r'"(?:reply|emotion|intensity)"\s*:', value): return None + return value + + +def parse_reply(raw): + if not isinstance(raw, str) or len(raw) > 8192: return ReplyEmotion(SAFE_REPLY) + body = raw.strip() + if body.startswith('```'): + body = re.sub(r'^```(?:json)?\s*', '', body, count=1).removesuffix('```').strip() + try: data = json.loads(body) + except (ValueError, RecursionError): data = None + 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) + 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. + match = re.search(r'"reply"\s*:\s*(")', body) + if match: + literal = body[match.start(1):] + try: value, _ = json.JSONDecoder().raw_decode(literal) + except ValueError: + # Only a truncated string, never arbitrary suffix/JSON syntax recovery. + try: value = json.loads(literal.rstrip('\\') + '"') + except ValueError: value = None + reply = clean_reply(value) + if reply: return ReplyEmotion(reply) + 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) diff --git a/gateway/scripts/check-archive.py b/gateway/scripts/check-archive.py index 2b12abe..69d3be3 100644 --- a/gateway/scripts/check-archive.py +++ b/gateway/scripts/check-archive.py @@ -1,5 +1,6 @@ #!/usr/bin/env python3 """Portable model-free archive regression: isolated temp root + synthetic persona manifests.""" +import argparse import json import os from pathlib import Path @@ -9,11 +10,22 @@ import sys import tempfile root = Path(__file__).resolve().parents[1] +parser=argparse.ArgumentParser(description=__doc__) +parser.add_argument('--vad-model', type=Path, help='Existing authorized Silero artifact; read only, never downloaded') +args=parser.parse_args() with tempfile.TemporaryDirectory(prefix='lan-voice-archive-check-') as folder: stage = Path(folder) for source in root.glob('*.py'): shutil.copy2(source, stage/source.name) for name in ('tests','personas','web'): shutil.copytree(root/name, stage/name, ignore=shutil.ignore_patterns('__pycache__')) + if args.vad_model: + import hashlib + model=args.vad_model.resolve(strict=True) + sys.path.insert(0,str(root)) + from importlib.util import spec_from_file_location, module_from_spec + spec=spec_from_file_location('vad_app',root/'app.py');module=module_from_spec(spec);spec.loader.exec_module(module) + assert hashlib.sha256(model.read_bytes()).hexdigest()==module.EXPECTED_HASH, 'Silero artifact checksum' + (stage/'models').mkdir();(stage/'models/silero_vad.onnx').symlink_to(model) target=stage/'.runtime/personas'; target.mkdir(parents=True) for name in ('lvbu','yangmi_fiction'): # Public dummy IDs only; no production profile/reference audio/runtime copied. @@ -29,7 +41,7 @@ def safe(suite): result=unittest.TestSuite() for item in suite: if isinstance(item,unittest.TestSuite): result.addTest(safe(item)) - elif item.id().endswith('.test_silero_silence_and_state'): + elif item.id().endswith('.test_silero_silence_and_state') and not Path('models/silero_vad.onnx').exists(): # Model artifacts are intentionally absent; never download/load a model in archive checks. item.setUp=lambda: (_ for _ in ()).throw(unittest.SkipTest('Silero artifact excluded from source archive')) result.addTest(item) diff --git a/gateway/tests/test_continuity.py b/gateway/tests/test_continuity.py index 2939f75..de3cc4c 100644 --- a/gateway/tests/test_continuity.py +++ b/gateway/tests/test_continuity.py @@ -13,7 +13,7 @@ from test_gateway import Socket class ContinuityTests(unittest.IsolatedAsyncioTestCase): - async def test_multidelta_one_tts_and_realtime_text(self): + async def test_multidelta_one_tts_and_parsed_text(self): socket=Socket();tts=[] wav=io.BytesIO() with wave.open(wav,'wb') as w: @@ -25,7 +25,7 @@ class ContinuityTests(unittest.IsolatedAsyncioTestCase): stream=''.join('data: '+json.dumps({'choices':[{'delta':{'content':x}}]},ensure_ascii=False)+'\n\n' for x in parts)+'data: [DONE]\n\n' return httpx.Response(200,text=stream) tts.append(json.loads(request.content)) - self.assertEqual(len([e for e in socket.events if e['type']=='llm']),3) + self.assertEqual([e['text'] for e in socket.events if e['type']=='llm'], [''.join(parts)]) return httpx.Response(200,content=wav.getvalue()) async with httpx.AsyncClient(transport=httpx.MockTransport(backend)) as client: d=Dialogue(socket,FakeModel(),client) diff --git a/gateway/tests/test_gateway_emotion.py b/gateway/tests/test_gateway_emotion.py new file mode 100644 index 0000000..df098e3 --- /dev/null +++ b/gateway/tests/test_gateway_emotion.py @@ -0,0 +1,66 @@ +"""Actual pipeline: one system, parsed body/history/TTS, emotion before any PCM, turn fencing.""" +import asyncio +import io +import json +import time +import unittest +import wave +import httpx +from gateway import Dialogue +from tests_fake import FakeModel +from test_gateway import Socket + +class EmotionPipelineTests(unittest.IsolatedAsyncioTestCase): + async def test_seven_states_no_envelope_in_body_history_or_tts(self): + for emotion,intensity in [('neutral',0)]+[(e,i) for e in ('happy','angry','sad') for i in (1,2)]+[('invalid',2),('damaged',0)]: + socket=Socket();tts=[];history=[];order=[] + class OrderedSocket(Socket): + async def send_json(self,event): order.append(event['type']);await super().send_json(event) + async def send_bytes(self,frame): order.append('pcm');await super().send_bytes(frame) + class History: + async def begin(self,*args): pass + async def context(self,*args): return [] + async def rows(self,*args): return [] + async def finish(self,rid,answer,status): history.append((answer,status)) + body=json.dumps(dict(reply='测试回答。',emotion=emotion,intensity=intensity),ensure_ascii=False) + if emotion=='damaged':body='{"reply":"测试回答。","emotion":' + expected=(emotion,intensity,'model') if emotion not in ('invalid','damaged') else ('neutral',0,'fallback') + def backend(request): + if 'transcriptions' in request.url.path:return httpx.Response(200,json={'text':'公开测试'}) + if 'chat' in request.url.path: + data=json.loads(request.content);self.assertEqual([m['role'] for m in data['messages']],['system','user']) + self.assertNotIn('摄像头观察',data['messages'][0]['content']) + # Even a JSON envelope split inside a key must never leak as text. + return httpx.Response(200,text=''.join('data: '+json.dumps({'choices':[{'delta':{'content':part}}]})+'\n\n' for part in (body[:5],body[5:]))+'data: [DONE]\n\n') + tts.append(json.loads(request.content)['input']);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()) + socket=OrderedSocket() + async with httpx.AsyncClient(transport=httpx.MockTransport(backend)) as client: + d=Dialogue(socket,FakeModel(),client,History(),'synthetic');d.run_id='synthetic' + # Exercise both accepted voice modes; both synthesize just the parsed reply once. + d.voice_mode='fragment' if intensity==1 else 'continuous_voice' + await d.run(0,bytes(640)) + self.assertEqual(tts,['测试回答。']);self.assertEqual(history,[('测试回答。','completed')]) + self.assertEqual([e['text'] for e in socket.events if e['type']=='llm'],['测试回答。']) + events=[e for e in socket.events if e['type']=='reply.emotion'];self.assertEqual(len(events),1) + self.assertEqual((events[0]['emotion'],events[0]['intensity'],events[0]['source'],events[0]['turn_id']),(*expected,0)) + self.assertGreater(events[0]['seq'],0);self.assertLess(order.index('reply.emotion'),order.index('pcm')) + self.assertTrue(socket.frames) + + async def test_stale_generation_cannot_publish_emotion_or_speak(self): + entered=asyncio.Event();resume=asyncio.Event();socket=Socket() + class Slow(httpx.AsyncByteStream): + async def __aiter__(self): + yield b'data: {"choices":[{"delta":{"content":"{\\\"reply\\\":\\\"hello\\\""}}]}\n\n' + entered.set();await resume.wait() + yield b'data: [DONE]\n\n' + async with httpx.AsyncClient(transport=httpx.MockTransport(lambda req:httpx.Response(200,stream=Slow()))) as client: + d=Dialogue(socket,FakeModel(),client);queue=asyncio.Queue(2) + task=asyncio.create_task(d.generate(0,'test',queue,{},time.perf_counter())) + await entered.wait();await d.invalidate('new_turn');resume.set();await task + self.assertTrue(queue.empty()) + self.assertFalse(any(e['type'] in ('llm','reply.emotion') for e in socket.events)) + await d.event('reply.emotion',0,emotion='angry',intensity=2,source='model') + self.assertEqual([e['type'] for e in socket.events],['abort']) diff --git a/gateway/tests/test_llm_provider.py b/gateway/tests/test_llm_provider.py new file mode 100644 index 0000000..adc31dc --- /dev/null +++ b/gateway/tests/test_llm_provider.py @@ -0,0 +1,94 @@ +import asyncio +import json +import time +import unittest +from unittest.mock import patch + +import httpx + +from gateway import Dialogue +from llm_provider import LLMProvider +from test_gateway import Socket +from tests_fake import FakeModel + + +class ProviderTests(unittest.TestCase): + def test_qwen_default_and_manual_return(self): + provider = LLMProvider({}) + url, headers, body = provider.request([{'role': 'user', 'content': '公开问题'}]) + self.assertEqual(url, 'http://127.0.0.1:8888/v1/chat/completions') + self.assertEqual(headers, {}) + self.assertEqual(body['model'], 'qwen3.8-27b') + self.assertEqual(body['chat_template_kwargs'], {'enable_thinking': False}) + + def test_doubao_key_only_in_header_and_no_schema_requirement(self): + provider = LLMProvider({'LAN_LLM_BASE_URL': 'http://192.168.31.53:4000/v1/', 'LAN_LLM_MODEL': 'doubao-seed-2-1-pro', 'LAN_LLM_API_KEY': 'unit-key'}) + messages = [{'role': 'system', 'content': '简短中文'}, {'role': 'user', 'content': '公开问题'}] + url, headers, body = provider.request(messages) + self.assertEqual(url, 'http://192.168.31.53:4000/v1/chat/completions') + self.assertEqual(headers['Authorization'], 'Bearer unit-key') + self.assertEqual(body['messages'], messages) + self.assertEqual(body['max_tokens'], 64) + self.assertTrue(body['stream']) + self.assertNotIn('chat_template_kwargs', body) + self.assertNotIn('response_format', body) + self.assertNotIn(provider.api_key, json.dumps(body) + url) + self.assertEqual(provider.request(messages, max_tokens=160)[2]['max_tokens'], 160) + + def test_custom_kwargs_are_provider_local(self): + custom = LLMProvider({'LAN_LLM_MODEL': 'doubao-seed-2-1-pro', 'LAN_LLM_CHAT_TEMPLATE_KWARGS': '{"custom":true}'}) + self.assertEqual(custom.request([])[2]['chat_template_kwargs'], {'custom': True}) + self.assertEqual(LLMProvider({}).request([])[2]['chat_template_kwargs'], {'enable_thinking': False}) + self.assertNotIn('chat_template_kwargs', LLMProvider({'LAN_LLM_MODEL': 'doubao-seed-2-1-pro'}).request([])[2]) + + def test_explicit_template_kwargs_and_invalid_configuration(self): + self.assertEqual(LLMProvider({'LAN_LLM_CHAT_TEMPLATE_KWARGS': '{}'}).template_kwargs, {}) + for env in ({'LAN_LLM_BASE_URL': 'http://user:password@example.com/v1'}, {'LAN_LLM_BASE_URL': 'http://example.com/v1?key=secret'}, {'LAN_LLM_CHAT_TEMPLATE_KWARGS': '[]'}, {'LAN_LLM_API_KEY': 'bad\nheader'}): + with self.assertRaises(ValueError): + LLMProvider(env) + + +class ProviderStreamTests(unittest.IsolatedAsyncioTestCase): + async def test_doubao_sse_history_face_and_no_fallback(self): + calls = [] + def backend(request): + calls.append(request) + self.assertEqual(str(request.url), 'http://192.168.31.53:4000/v1/chat/completions') + self.assertEqual(request.headers['authorization'], 'Bearer unit-key') + body = json.loads(request.content) + self.assertNotIn('chat_template_kwargs', body) + self.assertEqual(body['max_tokens'], 160) + self.assertEqual(sum(m['role']=='system' for m in body['messages']), 1) + self.assertIn('face-summary', body['messages'][0]['content']) + self.assertEqual(body['messages'][1]['content'], '历史问题') + content=json.dumps({'reply':'公开回答。','emotion':'happy','intensity':1}) + return httpx.Response(200, text='data: '+json.dumps({'choices':[{'delta':{'content':content}}]})+'\n\ndata: [DONE]\n\n') + env = {'LAN_LLM_BASE_URL': 'http://192.168.31.53:4000/v1', 'LAN_LLM_MODEL': 'doubao-seed-2-1-pro', 'LAN_LLM_API_KEY': 'unit-key'} + with patch.dict('os.environ', env, clear=True): + async with httpx.AsyncClient(transport=httpx.MockTransport(backend)) as client: + socket = Socket() + dialogue = Dialogue(socket, FakeModel(), client) + dialogue.contexts[0] = [{'role': 'user', 'content': '历史问题'}] + dialogue.face_messages[0] = [{'content': 'face-summary'}] + queue = asyncio.Queue(2) + await dialogue.generate(0, '公开问题', queue, {}, time.perf_counter()) + self.assertEqual(await queue.get(), '公开回答。') + self.assertIsNone(await queue.get()) + self.assertEqual(len(calls), 1) + self.assertEqual(dialogue.answers[0], '公开回答。') + self.assertTrue(any(e['type'] == 'llm.finished' for e in socket.events)) + emotion=next(e for e in socket.events if e['type']=='reply.emotion') + self.assertEqual((emotion['emotion'],emotion['intensity'],emotion['source']),('happy',1,'model')) + + async def test_auth_failure_never_calls_second_provider(self): + calls = [] + def backend(request): + calls.append(request) + return httpx.Response(401) + with patch.dict('os.environ', {'LAN_LLM_BASE_URL': 'http://192.168.31.53:4000/v1', 'LAN_LLM_MODEL': 'doubao-seed-2-1-pro'}, clear=True): + async with httpx.AsyncClient(transport=httpx.MockTransport(backend)) as client: + dialogue = Dialogue(Socket(), FakeModel(), client) + with self.assertRaises(httpx.HTTPStatusError): + await dialogue.generate(0, '公开问题', asyncio.Queue(2), {}, time.perf_counter()) + self.assertEqual(len(calls), 1) + self.assertEqual(calls[0].url.host, '192.168.31.53') diff --git a/gateway/tests/test_reply_emotion.py b/gateway/tests/test_reply_emotion.py new file mode 100644 index 0000000..52ebc62 --- /dev/null +++ b/gateway/tests/test_reply_emotion.py @@ -0,0 +1,46 @@ +import json +import unittest +from reply_emotion import parse_reply, SAFE_REPLY + +class ReplyEmotionTests(unittest.TestCase): + def test_all_seven_states(self): + for emotion, intensity in [('neutral',0)]+[(e,i) for e in ('happy','angry','sad') for i in (1,2)]: + with self.subTest(emotion=emotion,intensity=intensity): + result=parse_reply(json.dumps(dict(reply='公开回答。',emotion=emotion,intensity=intensity))) + self.assertEqual((result.reply,result.emotion,result.intensity,result.source),('公开回答。',emotion,intensity,'model')) + + def test_invalid_missing_and_wrong_types_keep_reply_fallback(self): + for fields in [dict(),dict(emotion='fear',intensity=2),dict(emotion='happy',intensity=0), + dict(emotion='neutral',intensity=2),dict(emotion='sad',intensity=True), + dict(emotion='happy',intensity=1.0),dict(emotion=[],intensity=1), + dict(emotion='sad',intensity=1,extra='ignored')]: + result=parse_reply(json.dumps(dict(reply='可用正文',**fields))) + self.assertEqual((result.reply,result.emotion,result.intensity,result.source),('可用正文','neutral',0,'fallback')) + + def test_damaged_formats_recover_without_reading_envelope(self): + for raw, expected in [ + ('{"reply":"正文","emotion":','正文'), + ('{"reply":"被截断的正文','被截断的正文'), + ('{"reply":"转义\\n正文","intensity":???}', '转义\n正文'), + ('普通的非JSON回答。','普通的非JSON回答。'), + ('{"answer":"兼容正文"}', '兼容正文'), + ('```json\n{"reply":"正文"}\n```','正文'), + ('{"emotion":"happy"}',SAFE_REPLY), + ('{"reply": {"evil":true}}',SAFE_REPLY), + ('{"reply":"{\\"emotion\\":\\"happy\\"}"}',SAFE_REPLY), + ('',SAFE_REPLY), ('x'*8193, SAFE_REPLY), + ]: + with self.subTest(raw=raw): + result=parse_reply(raw) + self.assertEqual(result.reply,expected) + self.assertEqual((result.emotion,result.intensity,result.source),('neutral',0,'fallback')) + + def test_no_model_retry_or_schema_contract(self): + from pathlib import Path + source=(Path(__file__).resolve().parents[1]/'gateway.py').read_text() + generate=source.split(' async def generate(')[1].split(' async def synthesize(')[0] + self.assertEqual(generate.count("self.client.stream('POST'"),1) + self.assertEqual(generate.count('self.llm_provider.request('),1) + self.assertNotIn('response_format', generate) + +if __name__=='__main__': unittest.main() diff --git a/scripts/archive-gateway.py b/scripts/archive-gateway.py index c98ca47..e719684 100644 --- a/scripts/archive-gateway.py +++ b/scripts/archive-gateway.py @@ -64,6 +64,8 @@ def scan(name, data): for pattern in patterns: for match in re.finditer(pattern,text): if match.lastindex and match.group(1).startswith('REPLACE_'): continue + # A fixed reserved-domain negative fixture tests rejecting URL credentials. + if name.endswith('tests/test_llm_provider.py') and match.group(0)=='http://user:password@' and text[match.end():].startswith('example.com/v1'): continue raise RuntimeError(f'Possible embedded secret in {name}; inspect locally before any Git add') diff --git a/scripts/check-emotion-regressions.sh b/scripts/check-emotion-regressions.sh new file mode 100755 index 0000000..73fa63f --- /dev/null +++ b/scripts/check-emotion-regressions.sh @@ -0,0 +1,18 @@ +#!/bin/bash +# Model-free local JVM/rule/parser regressions; persistent numeric result for release checks. +set -euo pipefail +cd "$(dirname "$0")/.." +mkdir -p logs/voice-investigation +python3 scripts/check-reply-regressions.py > logs/voice-investigation/client-emotion-tests.txt 2>&1 +./scripts/check-expression-rules.sh > logs/voice-investigation/expression-emotion-tests.txt 2>&1 +(cd gateway && python3 -m unittest discover -s tests -p test_reply_emotion.py -v) > logs/voice-investigation/parser-emotion-tests.txt 2>&1 +python3 - <<'PY' +import hashlib,json +from pathlib import Path +root=Path.cwd() +files=list((root/'app/src/main/java').rglob('*.kt')) + list((root/'tests').rglob('*.kt')) +files += [root/'gateway/reply_emotion.py',root/'scripts/check-reply-regressions.py'] +result={'status':'passed','scope':'production Kotlin coordinator/playback/capture/protocol with device/transport doubles; pure face rules and structured parser','real_phone_playback':'not_tested','hashes':{str(p.relative_to(root)):hashlib.sha256(p.read_bytes()).hexdigest() for p in sorted(files)}} +(root/'logs/voice-investigation/client-emotion-tests.json').write_text(json.dumps(result,indent=2)+'\n') +print('Client/expression/parser emotion regressions passed (no real speaker)') +PY diff --git a/scripts/check-reply-regressions.py b/scripts/check-reply-regressions.py index f689185..30a3e20 100644 --- a/scripts/check-reply-regressions.py +++ b/scripts/check-reply-regressions.py @@ -23,10 +23,10 @@ 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/'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']), ('playback','PlaybackCheckKt', [source/'audio/AudioPlayback.kt']), ('capture','CaptureCheckKt', [source/'audio/AudioCapture.kt']), - ('protocol','ProtocolCheckKt', [source/'net/DialogueProtocol.kt', source/'expression/FaceCueRules.kt', source/'expression/ExpressionRules.kt']), + ('protocol','ProtocolCheckKt', [source/'net/DialogueProtocol.kt', source/'dialogue/ReplyEmotion.kt', source/'expression/FaceCueRules.kt', source/'expression/ExpressionRules.kt']), ] for name, main, real in suites: with tempfile.TemporaryDirectory(prefix=f'lan-voice-{name}-') as out: diff --git a/scripts/check-reply-structure.py b/scripts/check-reply-structure.py new file mode 100644 index 0000000..d90249d --- /dev/null +++ b/scripts/check-reply-structure.py @@ -0,0 +1,66 @@ +#!/usr/bin/env python3 +"""Four bounded public compatibility calls; current Qwen and saved Doubao, no live config changes.""" +from pathlib import Path +import base64,json,subprocess +root=Path(__file__).resolve().parents[1] +CORE=r''' +import json,time,httpx +from llm_provider import LLMProvider +from reply_emotion import SYSTEM_FRAGMENT,parse_reply +provider=LLMProvider();rows=[] +with httpx.Client(timeout=30,trust_env=False) as client: + for name,prompt in [('ordinary','一加一等于几?'),('happy','请用明显高兴的语气祝贺我完成公开练习。')]: + start=time.perf_counter();first=None;raw='';finish=None + messages=[{'role':'system','content':'以下角色设定只约束reply口述内容,旧有不输出JSON约定不约束外层结构。用简短中文直接回答。\n'+SYSTEM_FRAGMENT},{'role':'user','content':prompt}] + url,headers,body=provider.request(messages,max_tokens=160) + row={'case':name} + try: + with client.stream('POST',url,headers=headers,json=body) as r: + row['http_status']=r.status_code;r.raise_for_status() + for line in r.iter_lines(): + if not line.startswith('data:'):continue + data=line[5:].strip() + if data=='[DONE]':break + for choice in json.loads(data).get('choices',[]): + delta=choice.get('delta',{}).get('content') or '' + if delta and first is None:first=round((time.perf_counter()-start)*1000,2) + raw+=delta;finish=choice.get('finish_reason') or finish + if len(raw)>8192:raise ValueError('reply bound') + parsed=parse_reply(raw) + row.update(source=parsed.source,emotion=parsed.emotion,intensity=parsed.intensity,reply_chars=len(parsed.reply),finish_reason=finish,first_token_ms=first) + except Exception as error:row['error_type']=type(error).__name__ + row['elapsed_ms']=round((time.perf_counter()-start)*1000,2) + if first is not None:row['structured_wait_ms']=round(row['elapsed_ms']-first,2) + rows.append(row) +passed=all(x.get('source')=='model' and x.get('finish_reason')=='stop' for x in rows) +print(json.dumps({'status':'passed' if passed else 'failed','base_url':provider.base_url,'model_alias':provider.model,'chat_template_kwargs':provider.template_kwargs,'key_present':bool(provider.api_key),'strategy':'prompt_only_json_single_system_single_request','results':rows})) +raise SystemExit(0 if passed else 1) +''' +REMOTE=r''' +import tempfile,pathlib,sys,base64,os,subprocess,json +root=pathlib.Path('/home/gorios-spark-2/lan-voice') +pid=subprocess.check_output(['systemctl','--user','show','lan-voice-gateway.service','-p','MainPID','--value'],text=True).strip() +running=dict(x.split('=',1) for x in pathlib.Path('/proc/'+pid+'/environ').read_bytes().decode().split('\0') if '=' in x) +with tempfile.TemporaryDirectory(prefix='reply-structure-') as d: + for name,content in bundle.items():pathlib.Path(d,name).write_bytes(base64.b64decode(content)) + code='import sys\nsys.path.insert(0,'+repr(d)+')\n'+core + qwen=subprocess.run([sys.executable,'-'],input=code,text=True,capture_output=True,timeout=70,env={**os.environ,**running}) + # Existing private provider file is loaded only into a subprocess; never copied or logged. + doubao=subprocess.run(['bash','-c','set -a; source .runtime/gori-baji-llm.env; source .runtime/gori-baji-provider.env; exec .venv/bin/python -'],cwd=root,input=code,text=True,capture_output=True,timeout=70) + rows={} + for name,result in [('qwen_current',qwen),('doubao_saved',doubao)]: + try:rows[name]=json.loads(result.stdout) + except ValueError:rows[name]={'status':'failed','returncode':result.returncode,'stderr_present':bool(result.stderr)} + passed=all(r.get('status')=='passed' for r in rows.values()) + print(json.dumps({'status':'passed' if passed else 'failed','results':rows,'live_configuration_changed':False,'real_weights_verified':False})) + raise SystemExit(0 if passed else 1) +''' +bundle={name:base64.b64encode((root/'gateway'/name).read_bytes()).decode() for name in ('llm_provider.py','reply_emotion.py')} +payload='bundle='+repr(bundle)+'\ncore='+repr(CORE)+'\n'+REMOTE +r=subprocess.run(['ssh','-o','BatchMode=yes','-o','ConnectTimeout=5','gorios-spark-2@192.168.31.61','cd /home/gorios-spark-2/lan-voice && exec .venv/bin/python -'],input=payload.encode(),capture_output=True,timeout=150) +if r.stdout: + data=json.loads(r.stdout);out=root/'logs/voice-investigation/reply-structure.json';out.parent.mkdir(parents=True,exist_ok=True) + if out.exists():out.with_name('reply-structure-previous.json').write_bytes(out.read_bytes()) + out.write_text(json.dumps(data,indent=2)+'\n');print(json.dumps(data)) +if r.stderr:print('Remote stderr present (content suppressed).') +raise SystemExit(r.returncode) diff --git a/scripts/deploy-gateway-source.py b/scripts/deploy-gateway-source.py new file mode 100644 index 0000000..a86a84f --- /dev/null +++ b/scripts/deploy-gateway-source.py @@ -0,0 +1,109 @@ +#!/usr/bin/env python3 +"""Canonical gateway/ deployment fenced to observed provider source. Default: isolated tests only.""" +import argparse, base64, hashlib, json, subprocess +from pathlib import Path +REMOTE=r''' +import base64,hashlib,json,os,shutil,ssl,stat,subprocess,sys,tempfile,time,urllib.request,re +from pathlib import Path +root=Path('/home/gorios-spark-2/lan-voice');unit='lan-voice-gateway.service' +def digest(path): return hashlib.sha256(path.read_bytes()).hexdigest() if path.exists() else None +def health(): + ctx=ssl.create_default_context(cafile=str(root/'.runtime/gateway-cert.pem')) + opener=urllib.request.build_opener(urllib.request.ProxyHandler({}),urllib.request.HTTPSHandler(context=ctx)) + 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) +def live_hashes():return {name:digest(root/name) for name in deploy_files} +original=live_hashes() +if original!=expected: + print(json.dumps({'status':'source_changed','mismatches':{name:{'expected':expected[name],'actual':original[name]} for name in expected if expected[name]!=original[name]},'applied':False}));raise SystemExit(1) +# Preserve complete unit and private environment loading relationships on server only. +unit_text=subprocess.check_output(['systemctl','--user','cat',unit]) +fragment=subprocess.check_output(['systemctl','--user','show',unit,'-p','FragmentPath','--value'],text=True).strip() +dropins=subprocess.check_output(['systemctl','--user','show',unit,'-p','DropInPaths','--value'],text=True).split() +private_files=[Path(fragment)]+[Path(p) for p in dropins]+list((root/'.runtime').glob('*.env')) +for name in re.findall(r'^EnvironmentFile=-?(.+)$',unit_text.decode(),re.M): + p=Path(name.strip().strip('"'));assert p.is_absolute();private_files.append(p) +private_files=sorted(set(p for p in private_files if p.is_file())) +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: + 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)) + test_start=time.perf_counter() + result=subprocess.run([sys.executable,str(stage/'scripts/check-archive.py'),'--vad-model',str(root/'models/silero_vad.onnx')],cwd=stage,stdout=subprocess.PIPE,stderr=subprocess.STDOUT,timeout=120,env={**os.environ,'PYTHONDONTWRITEBYTECODE':'1'}) + summary={'status':'tests_passed' if result.returncode==0 else 'tests_failed','test_output':result.stdout.decode(errors='replace'),'test_elapsed_ms':round((time.perf_counter()-test_start)*1000,2),'applied':False,'expected_hashes':original} + if result.returncode: print(json.dumps(summary));raise SystemExit(1) + if apply: + 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) + # 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) + for i,path in enumerate(private_files): + dst=backup/'private'/str(i);dst.parent.mkdir(parents=True,exist_ok=True,mode=0o700);shutil.copy2(path,dst) + (backup/'unit.txt').write_bytes(unit_text);(backup/'unit.txt').chmod(0o600) + existed={name:(root/name).exists() for name in deploy_files} + modes={name:stat.S_IMODE((root/name).stat().st_mode) if existed[name] else 0o644 for name in deploy_files} + (backup/'manifest.json').write_text(json.dumps(existed));(backup/'manifest.json').chmod(0o600) + (backup/'metadata.json').write_text(json.dumps({'modes':modes,'private_files':{str(p):{'backup':'private/'+str(i),'sha256':private_hashes[str(p)],'mode':stat.S_IMODE(p.stat().st_mode)} for i,p in enumerate(private_files)},'unit_sha256':hashlib.sha256(unit_text).hexdigest()}));(backup/'metadata.json').chmod(0o600) + if live_hashes()!=original or not relation_unchanged():raise RuntimeError('source_or_environment_changed_before_apply') + if health().get('busy'):raise RuntimeError('gateway_busy_before_apply_no_restart') + try: + for name in deploy_files:atomic(root/name,(stage/name).read_bytes(),modes[name]) + subprocess.run(['systemctl','--user','restart',unit],check=True,timeout=30,stdout=subprocess.PIPE,stderr=subprocess.PIPE) + for attempt in range(15): + try: + if health().get('status')=='ok':break + except Exception:pass + time.sleep(1) + else:raise RuntimeError('gateway_health_failed') + assert relation_unchanged(),'environment_loading_changed' + deployed=live_hashes() + assert deployed=={name:hashlib.sha256((stage/name).read_bytes()).hexdigest() for name in deploy_files} + except BaseException: + # Never overwrite an edit made by another operator, even while rolling back a failed restart. + staged_hashes={name:hashlib.sha256((stage/name).read_bytes()).hexdigest() for name in deploy_files} + if any(value not in (original[name],staged_hashes[name]) for name,value in live_hashes().items()): + raise RuntimeError('concurrent_source_change_refusing_automatic_rollback') + for name,present in existed.items(): + if present:atomic(root/name,(backup/name).read_bytes(),modes[name]) + elif (root/name).exists():(root/name).unlink() + subprocess.run(['systemctl','--user','restart',unit],timeout=30,stdout=subprocess.PIPE,stderr=subprocess.PIPE) + raise + summary.update(status='deployed',applied=True,backup=str(backup),hashes=deployed,modes=modes,environment_unchanged=True,unit_sha256=hashlib.sha256(unit_text).hexdigest(),health='ok',restart_unit=unit) + print(json.dumps(summary)) +''' +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'] + 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} + record=root/'logs/voice-investigation/gateway-emotion-deploy.json' + if record.exists(): + previous=json.loads(record.read_text()) + if previous.get('applied'):expected=previous['hashes'];assert set(expected)==set(files) + bundle={} + for path in source.rglob('*'): + name=path.relative_to(source).as_posix() + if not path.is_file() or any(x.startswith('.') or x in ('__pycache__','models','logs') for x in path.relative_to(source).parts):continue + if path.suffix in ('.py','.json','.js','.html','.css'):bundle[name]=base64.b64encode(path.read_bytes()).decode() + payload='import json\nbundle='+repr(bundle)+'\ndeploy_files='+repr(files)+'\nexpected='+repr(expected)+'\napply='+repr(args.apply)+'\ntry:\n exec('+repr(REMOTE)+')\nexcept Exception as error:\n print(json.dumps({"status":"blocked","error_type":type(error).__name__,"reason":str(error) if isinstance(error,RuntimeError) else "remote_execution_error","applied":False}))\n raise SystemExit(1)\n' + command='cd /home/gorios-spark-2/lan-voice && exec .venv/bin/python -' + r=subprocess.run(['ssh','-o','BatchMode=yes','-o','ConnectTimeout=5','gorios-spark-2@192.168.31.61',command],input=payload.encode(),capture_output=True,timeout=210) + if r.stdout: + data=json.loads(r.stdout);out=record if data.get('applied') else record.with_name('gateway-emotion-staged.json');out.parent.mkdir(parents=True,exist_ok=True) + if out.exists() and data.get('applied'):out.with_name('gateway-emotion-deploy-previous.json').write_bytes(out.read_bytes()) + out.write_text(json.dumps(data,indent=2)+'\n');print('Gateway '+data['status']) + if r.stderr:print('Remote stderr present (content suppressed); no concurrent hash check bypassed.') + raise SystemExit(r.returncode) +if __name__=='__main__':main() diff --git a/scripts/deploy-gateway.py b/scripts/deploy-gateway.py index 54b29d8..e3781d2 100644 --- a/scripts/deploy-gateway.py +++ b/scripts/deploy-gateway.py @@ -127,4 +127,5 @@ def main(): raise SystemExit(result.returncode) -if __name__=='__main__': main() +if __name__=='__main__': + raise SystemExit('Historical v040 patch deployment disabled; use scripts/deploy-gateway-source.py for canonical provider + emotion source.') diff --git a/scripts/finalize-emotion-release.sh b/scripts/finalize-emotion-release.sh new file mode 100755 index 0000000..be591d0 --- /dev/null +++ b/scripts/finalize-emotion-release.sh @@ -0,0 +1,71 @@ +#!/bin/bash +# Explicit source-only release commit/push; no runtime, diagnostics or binary staging. +set -euo pipefail +cd "$(dirname "$0")/.." +[ "$(git branch --show-current)" = main ] +[ "$(git remote get-url origin)" = 'git@git.oops.school:heihei/baji-vc.git' ] +git merge-base --is-ancestor 19a7adccd9322986eb0646b165b9ce1cf2650cf2 HEAD +if [ -n "$(git diff --cached --name-only)" ]; then + echo 'Existing staged changes preserved; refusing mixed release commit.' >&2 + exit 1 +fi +python3 - <<'PY' +from pathlib import Path +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['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 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' +assert deploy['environment_unchanged'] and load('reply-structure.json')['status']=='passed' +verification=load('provider-release-verified.json') +assert verification['status']=='passed' and verification['live_source_hashes_match'] and verification['private_environment_and_unit_unchanged'] +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 +manifest=load('gateway-baseline-git.json');assert manifest['commit']=='19a7adccd9322986eb0646b165b9ce1cf2650cf2' +source=json.loads((root/'gateway/SOURCE_MANIFEST.json').read_text()) +for name,row in source['files'].items():assert hashlib.sha256((root/'gateway'/name).read_bytes()).hexdigest()==row['sha256'],name +scan=runpy.run_path('scripts/archive-gateway.py',run_name='archive_library')['scan'] +for p in (root/'gateway').rglob('*'): + if p.is_file() and '__pycache__' not in p.parts:scan(str(p.relative_to(root/'gateway')),p.read_bytes()) +print('Verified APK, bounded live pipeline, full gateway/client tests, canonical deployed source hashes; real phone remains untested') +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/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 \ + 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/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 +git diff --cached --check +python3 - <<'PY' +import subprocess +names=subprocess.check_output(['git','diff','--cached','--name-only'],text=True).splitlines() +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 push origin main +python3 - <<'PY' +import json,subprocess +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'} +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 new file mode 100755 index 0000000..74c7499 --- /dev/null +++ b/scripts/package-emotion-release.sh @@ -0,0 +1,65 @@ +#!/bin/bash +# Ordinary workspace shell: normal build entry, true package/signature checks, archive + HTTP check. +set -euo pipefail +cd "$(dirname "$0")/.." +python3 - <<'PY' +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') +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' +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' +print('Verified tested client/provider source and successful deployed pipeline before APK build') +PY +./scripts/build.sh +source /home/ubuntu/android-build/env.sh +TOOLS=/home/ubuntu/android-build/sdk/build-tools/34.0.0 +APK=app/build/outputs/apk/debug/app-debug.apk +mkdir -p logs/voice-investigation artifacts +"$TOOLS/aapt" dump badging "$APK" > logs/voice-investigation/release-emotion-badging.txt +"$TOOLS/apksigner" verify --verbose --print-certs "$APK" > logs/voice-investigation/release-emotion-signature.txt +python3 - <<'PY' +import hashlib,json,re,shutil,urllib.request,subprocess +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 +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' +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-v050-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' +shutil.copy2(source,artifact) +digest=hashlib.sha256(artifact.read_bytes()).hexdigest() +artifact.with_suffix('.apk.sha256').write_text(f'{digest} {artifact.name}\n') +# Existing HTTP server root can be the workspace or artifacts; check the actual bytes. +base='http://192.168.31.124:8080/' +opener=urllib.request.build_opener(urllib.request.ProxyHandler({})) +url=None +for path in ('artifacts/'+artifact.name, artifact.name): + try: + with opener.open(base+path,timeout=15) as response: + assert response.status==200 + content=response.read() + assert len(content)==artifact.stat().st_size + downloaded=hashlib.sha256(content).hexdigest() + 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') +(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 new file mode 100644 index 0000000..60da5d1 --- /dev/null +++ b/scripts/probe-reply-emotion.py @@ -0,0 +1,156 @@ +#!/usr/bin/env python3 +"""One bounded public-sample round against live gateway. Run only in the workspace ordinary shell.""" +import json +import subprocess +from pathlib import Path + +PROBE = r''' +import asyncio, contextlib, io, json, math, re, ssl, struct, sys, time, urllib.request, wave +from pathlib import Path +ROOT = Path('/home/gorios-spark-2/lan-voice') +sys.path.insert(0, str(ROOT)) +summary = {'test': 'one_public_sample_round', 'real_phone_playback': 'not_tested'} +async def probe(): + import websockets + from protocol import pack, unpack + ctx=ssl.create_default_context(cafile=str(ROOT/'.runtime/gateway-cert.pem')) + opener=urllib.request.build_opener(urllib.request.ProxyHandler({}),urllib.request.HTTPSHandler(context=ctx)) + with opener.open('https://192.168.31.61:5011/health',timeout=5) as response: health=json.load(response) + if health.get('busy'): raise RuntimeError('gateway_busy_probe_not_started') + sample=ROOT/'tmp/public_tts_16k.wav' + with wave.open(str(sample),'rb') as audio: + assert (audio.getframerate(),audio.getnchannels(),audio.getsampwidth())==(16000,1,2) + assert audio.getnframes() <= 16000*15, 'public sample exceeds 15s bound' + pcm=audio.readframes(audio.getnframes()) + summary['input_samples']=len(pcm)//2 + started=time.perf_counter() + summary.update(emotion_count=0,emotion_before_pcm=False,json_free_body=True,events={},llm_chars=0,llm_deltas=0,downlink_frames=0,downlink_bytes=0,pcm_peak=0,pcm_square=0,drained_ack=False) + def stamp(name): summary.setdefault(name,round((time.perf_counter()-started)*1000,2)) + kwargs=dict(ssl=ctx,origin='https://192.168.31.61:5011',open_timeout=5,close_timeout=2) + # The deployed websockets version accepts proxy=None; avoid any system proxy. + if 'proxy' in __import__('inspect').signature(websockets.connect).parameters: kwargs['proxy']=None + async with websockets.connect('wss://192.168.31.61:5011/ws/dialogue',**kwargs) as ws: + auth=json.loads(await asyncio.wait_for(ws.recv(),5)); assert auth['type']=='auth' and auth.get('state')=='ok' + await ws.send(json.dumps({'type':'hello','codec':'pcm16','sample_rate':16000,'frame_duration':20,'persona':'default','voice_mode':'continuous_voice','tts_debug':False})) + while True: + event=json.loads(await asyncio.wait_for(ws.recv(),5)) + if event['type']=='hello': break + summary['face_context_supported']=event.get('context_face_cue_version') + summary['reply_emotion_supported']=event.get('reply_emotion_version') + assert summary['reply_emotion_supported']==1 + if after: assert summary['face_context_supported']==1, 'face protocol not advertised' + await ws.send(json.dumps({'type':'listen','mode':'manual','state':'start','barge_in':False})) + while True: + event=json.loads(await asyncio.wait_for(ws.recv(),5)) + if event['type']=='listen' and event.get('state')=='start': turn=event['turn_id']; break + for offset in range(0,len(pcm),640): + chunk=pcm[offset:offset+640] + if len(chunk)<640: chunk += bytes(640-len(chunk)) + await ws.send(pack(1,turn,offset//640+1,chunk)) + await asyncio.sleep(.02) + if after: + cue={'type':'context.face_cue','version':1,'turn_id':turn,'valid':True,'cue':'smiling','intensity':.8,'duration_ms':900,'age_ms':0} + # Explicit synthetic observation: never represents the user's face. + await ws.send(json.dumps(cue)) + summary['synthetic_face_context_sent']=True + await ws.send(json.dumps({'type':'listen','mode':'manual','state':'stop'})) + stamp('input_end_ms') + last_seq=0; stopped=False;reply_body='';emotion=None + async with asyncio.timeout(60): + while True: + raw=await ws.recv() + if isinstance(raw,bytes): + actual,seq,audio=unpack(raw,2) + assert emotion is not None and emotion['turn_id']==actual, 'PCM before parsed emotion' + summary['emotion_before_pcm']=True + assert actual==turn and seq==last_seq+1 and 00 + 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 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')} + 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 + if kind=='llm.finished': stamp('llm_finished_ms') + 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['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': + stopped=True; stamp('tts_stop_ms') + assert summary.get('stt_chars',0)>0 and summary['llm_chars']>0 and summary['downlink_frames']>0 + # Model native drain is tested separately; this probe only confirms protocol ack. + await ws.send(json.dumps({'type':'playback.drained','turn_id':turn})) + if stopped and kind=='listen' and event.get('state')=='resumed': + summary['drained_ack']=True;stamp('drained_ack_ms');break + if after: + assert summary['backend_metrics'].get('face_cue_used') is True, 'ASR-time face snapshot missing' + await ws.send(json.dumps({'type':'context.face_cue','version':1,'turn_id':turn,'valid':False,'cue':'unknown','intensity':0,'duration_ms':0,'age_ms':0})) + await ws.send(json.dumps({'type':'context.face_cue','version':1,'turn_id':turn,'valid':True,'cue':'gaze_left','intensity':.8,'duration_ms':900,'age_ms':0})) + # A whitelisted control with invalid fields clears context; it must not close 1008. + await ws.send(json.dumps({'type':'ping'})) + while json.loads(await asyncio.wait_for(ws.recv(),5)).get('type')!='pong': pass + summary['invalid_face_control_survived']=True + assert summary['emotion_count']==1 and summary.get('tts_input_matches_body') and summary.get('tts_requests')==1 + assert summary['pcm_peak']>327, 'no voiced PCM amplitude' + summary['pcm_rms']=round(math.sqrt(summary.pop('pcm_square')/(summary['downlink_bytes']//2)),2) + summary['status']='passed' +try: + asyncio.run(probe()) +except Exception as error: + summary['status']='failed'; summary['error_type']=type(error).__name__ + summary['close_code']=getattr(error,'code',None) + summary.pop('pcm_square',None) +print(json.dumps(summary,ensure_ascii=False,indent=2)) +raise SystemExit(0 if summary['status']=='passed' else 1) +''' + + +def main(): + root = Path(__file__).resolve().parents[1] + payload = 'after=True\n'+PROBE + # Use the existing gateway venv if present; never install packages or load a new model. + remote = ('cd /home/gorios-spark-2/lan-voice && ' + 'if [ -x .venv/bin/python ]; then exec .venv/bin/python -; ' + 'elif [ -x venv/bin/python ]; then exec venv/bin/python -; else exec python3 -; fi') + result = subprocess.run(['ssh', '-o', 'BatchMode=yes', '-o', 'ConnectTimeout=5', + 'gorios-spark-2@192.168.31.61', remote], + input=payload.encode(), capture_output=True, timeout=100) + output = root / 'logs/voice-investigation' + output.mkdir(parents=True, exist_ok=True) + if result.stdout: + data = json.loads(result.stdout) + target = output / 'probe-emotion.json' + if target.exists(): + (output/'probe-emotion-previous.json').write_bytes(target.read_bytes()) + target.write_text(json.dumps(data, ensure_ascii=False, indent=2) + '\n') + print(f'Saved redacted numeric probe results: {target.relative_to(root)}; status={data.get("status")}') + if result.stderr: + # Remote script emits no payloads. Avoid printing unexpected tracebacks/raw server errors. + print('Remote stderr present; inspect script/environment (no content printed).') + raise SystemExit(result.returncode) + + +if __name__ == '__main__': + main() diff --git a/scripts/rollback-gateway-source.py b/scripts/rollback-gateway-source.py new file mode 100644 index 0000000..a7dba49 --- /dev/null +++ b/scripts/rollback-gateway-source.py @@ -0,0 +1,41 @@ +#!/usr/bin/env python3 +"""Restore only exact v050-deployed files, from its own backup; no model/container actions.""" +import json,subprocess +from pathlib import Path +REMOTE=r''' +import hashlib,json,ssl,subprocess,time,urllib.request,shutil +from pathlib import Path +root=Path('/home/gorios-spark-2/lan-voice');backup=Path(record['backup']).resolve() +assert backup.is_relative_to((root/'.runtime/backups').resolve()) +for name,expected in record['hashes'].items(): + assert name.endswith('.py') and not Path(name).is_absolute() and '..' not in Path(name).parts + assert hashlib.sha256((root/name).read_bytes()).hexdigest()==expected, 'concurrent source change: refusing rollback' +ctx=ssl.create_default_context(cafile=str(root/'.runtime/gateway-cert.pem')) +opener=urllib.request.build_opener(urllib.request.ProxyHandler({}),urllib.request.HTTPSHandler(context=ctx)) +def health(): + with opener.open('https://192.168.31.61:5011/health',timeout=3) as r:return json.load(r) +assert not health().get('busy'), 'busy: refusing restart' +manifest=json.loads((backup/'manifest.json').read_text());assert set(manifest)==set(record['hashes']) +metadata=json.loads((backup/'metadata.json').read_text()) +assert hashlib.sha256(subprocess.check_output(['systemctl','--user','cat','lan-voice-gateway.service'])).hexdigest()==metadata['unit_sha256'], 'unit changed: refusing rollback' +for name,row in metadata['private_files'].items(): + assert hashlib.sha256(Path(name).read_bytes()).hexdigest()==row['sha256'], 'private environment changed: refusing rollback' +for name,present in manifest.items(): + path=root/name + if present: + tmp=path.with_name(path.name+'.rollback.tmp');shutil.copy2(backup/name,tmp);tmp.replace(path) + elif path.exists():path.unlink() +subprocess.run(['systemctl','--user','restart','lan-voice-gateway.service'],check=True,timeout=30,stdout=subprocess.PIPE,stderr=subprocess.PIPE) +for attempt in range(15): + try: + if health().get('status')=='ok':print(json.dumps({'status':'rolled_back','backup':str(backup),'health':'ok'}));break + except Exception:pass + time.sleep(1) +else:raise RuntimeError('rollback health failed') +''' +root=Path(__file__).resolve().parents[1];record=json.loads((root/'logs/voice-investigation/gateway-emotion-deploy.json').read_text()) +r=subprocess.run(['ssh','-o','BatchMode=yes','-o','ConnectTimeout=5','gorios-spark-2@192.168.31.61','python3 -'],input=('record='+repr(record)+'\n'+REMOTE).encode(),capture_output=True,timeout=90) +if r.stdout: + data=json.loads(r.stdout);(root/'logs/voice-investigation/gateway-emotion-rollback.json').write_text(json.dumps(data,indent=2)+'\n');print(json.dumps(data)) +if r.stderr:print('Remote rollback stderr present (suppressed).') +raise SystemExit(r.returncode) diff --git a/scripts/update-gateway-manifest.py b/scripts/update-gateway-manifest.py new file mode 100644 index 0000000..289f638 --- /dev/null +++ b/scripts/update-gateway-manifest.py @@ -0,0 +1,21 @@ +#!/usr/bin/env python3 +"""Refresh recoverable source hashes while preserving observed upstream provenance.""" +from pathlib import Path +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['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 + name=path.relative_to(root).as_posix() + if name=='SOURCE_MANIFEST.json' or any(x in path.relative_to(root).parts for x in ('__pycache__','.runtime','models','logs')):continue + raw=path.read_bytes();digest=hashlib.sha256(raw).hexdigest();old=manifest['files'].get(name) + row={'source':old['source'] if old else 'workspace:gateway/'+name,'sha256':digest,'bytes':len(raw)} + if old and old['sha256']!=digest: + row['upstream_sha256']=old.get('upstream_sha256',old['sha256']);row['source']='workspace:gateway/'+name + elif old and 'upstream_sha256' in old:row['upstream_sha256']=old['upstream_sha256'] + manifest['files'][name]=row +(root/'SOURCE_MANIFEST.json').write_text(json.dumps(manifest,indent=2,ensure_ascii=False)+'\n') +print('Updated canonical gateway source manifest') diff --git a/tests/protocol/ProtocolCheck.kt b/tests/protocol/ProtocolCheck.kt index 5554fb5..5995584 100644 --- a/tests/protocol/ProtocolCheck.kt +++ b/tests/protocol/ProtocolCheck.kt @@ -1,6 +1,19 @@ import com.gorios.lanvoice.net.DialogueProtocol fun main() { + val states = listOf("neutral" to 0) + listOf("happy", "angry", "sad").flatMap { kind -> listOf(kind to 1, kind to 2) } + states.forEach { (kind, strength) -> + val parsed = checkNotNull(com.gorios.lanvoice.dialogue.ReplyEmotion.fromWire(7L, 10L, kind, strength, "model")) + check(parsed.emotion.wire == kind && parsed.intensity == strength && parsed.turnId == 7L) + } + 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(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 == "中立") + val pcm = ByteArray(640) { (it % 256).toByte() } val uplink = DialogueProtocol.uplink(pcm, 0x81234567L, 0xffffffffL) val golden = byteArrayOf(0x4c, 0x56, 0x01, 0x01, 0x81.toByte(), 0x23, 0x45, 0x67, diff --git a/tests/session/AudioDoubles.kt b/tests/session/AudioDoubles.kt index bd1e8ff..cd98283 100644 --- a/tests/session/AudioDoubles.kt +++ b/tests/session/AudioDoubles.kt @@ -12,7 +12,8 @@ class AudioCapture { fun release() {} } class AudioPlayback(onDrained: (Long, Long) -> Unit, onError: (Long, Exception) -> Unit, onProgress: (Long, Long, String) -> Unit = { _, _, _ -> }) { - companion object { var interrupts = 0; var enqueued = 0 } + companion object { var interrupts = 0; var enqueued = 0; var lastDrained: ((Long, Long) -> Unit)? = null } + init { lastDrained = onDrained } fun beginTurn(turn: Long) {} fun endTurn(turn: Long) {} fun enqueue(frame: DownlinkFrame): Boolean { enqueued++; return true } diff --git a/tests/session/ConnectionCheck.kt b/tests/session/ConnectionCheck.kt index 8ac96d5..8ddf429 100644 --- a/tests/session/ConnectionCheck.kt +++ b/tests/session/ConnectionCheck.kt @@ -407,8 +407,35 @@ fun runChecks() { frameMethod.invoke(session, DownlinkFrame(turnId=3)) check(com.gorios.lanvoice.audio.AudioPlayback.enqueued == beforeFrames + 4) check(states.last().phase == com.gorios.lanvoice.audio.VoicePhase.ANSWERING) + fun emotion(turn: Long, seq: Long, kind: String = "happy", strength: Int = 2) { + eventMethod.invoke(session, ServerEvent("reply.emotion", EventKind.REPLY_EMOTION, + Payload(turn=turn, fields=mapOf("seq" to seq, "emotion" to kind, "intensity" to strength, "source" to "model")))) + } + emotion(3, 100) + 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 + check(states.last().replyEmotion.label == "高兴·明显") + emotion(3, 103, "invalid") + check(states.last().replyEmotion.label == "中立") + emotion(3, 104, "sad", 1) + check(states.last().replyEmotion.label == "难过·轻度") event(EventKind.TTS, 3, state="stop") check(states.last().phase == com.gorios.lanvoice.audio.VoicePhase.ANSWERING) + 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 == "中立") + emotion(3, 105) // a late event after drained cannot reanimate the expression + check(states.last().replyEmotion.label == "中立") + event(EventKind.ABORT, 4, reason="new_turn") + emotion(4, 106) + check(states.last().replyEmotion.label == "高兴·明显") + session.interrupt() + check(states.last().replyEmotion.label == "中立") + event(EventKind.ABORT, 4, reason="client_abort") + check(states.last().replyEmotion.label == "中立") event(EventKind.UNKNOWN, 4) event(EventKind.ABORT, 4, reason="new_turn") check(blockedField.get(session) == null) diff --git a/tests/session/ProtocolEvents.kt b/tests/session/ProtocolEvents.kt index 89da0ba..4a4cb45 100644 --- a/tests/session/ProtocolEvents.kt +++ b/tests/session/ProtocolEvents.kt @@ -2,13 +2,13 @@ package com.gorios.lanvoice.net // Event doubles isolate DialogueClient callback ordering from the unchanged JSON parser. // Production DialogueProtocol/JSONObject were compiled separately with actual dependencies. -class Payload(private val ok: Boolean = true, private val turn: Long? = null, private val state: String = "", private val reason: String = "") { +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 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 null + fun opt(key: String): Any? = if (key == "turn_id") turn else fields[key] } -enum class EventKind { AUTH, HELLO, ERROR, HISTORY, UNKNOWN, LISTEN, VAD, STT, LLM, TTS, ABORT } +enum class EventKind { AUTH, HELLO, ERROR, HISTORY, UNKNOWN, LISTEN, VAD, STT, LLM, TTS, ABORT, REPLY_EMOTION } data class ServerEvent(val type: String, val kind: EventKind, val payload: Payload) class DownlinkFrame(val turnId: Long = 0, val sequence: Long = 0, val pcm16: ByteArray = ByteArray(2)) object DialogueProtocol {