fix: preserve camera permission intent and distinguish unknown reply expression

This commit is contained in:
zenord
2026-10-12 11:33:36 +08:00
parent d43c7d4e80
commit b521d368a5
26 changed files with 544 additions and 101 deletions
+3
View File
@@ -25,3 +25,6 @@ The 0.5.0 canonical source adds `reply_emotion.py`: one-system structured provid
`SOURCE_MANIFEST.json.provider_baseline` records the latest observed SPARK2 hashes before this merge, including gateway `d088bedcf5c0accd4712e06202f6ced8ab155aad57a5b05683724efa346326ce`. Deployment fences against these hashes, not the superseded historical patch. Historical `scripts/deploy-gateway.py` is disabled. The existing unit and private environment loading relationships are backed up only on the server and checked unchanged. All Python sources/tests and original modes are backed up; only gateway is restarted after isolated tests and repeated source/busy checks. Use `scripts/rollback-gateway-source.py` for this exact deployment.
Portable archive checks skip only the omitted Silero artifact. On the existing server, run `python scripts/check-archive.py --vad-model /absolute/path/to/models/silero_vad.onnx` for the full suite, with checksum verification and an isolated read-only artifact link. This never downloads or changes a model or online service.
Release 0.5.1 adds finite parser reason/recovery branch, finish_reason and optional token usage diagnostics without changing provider, prompt, 160-token dialogue budget, TTS voice or request count. Damaged structure is called truncated only when the provider explicitly reported length. Existing 0.5.0 clients continue to receive neutral/0 for fallback; the new UI labels it undetermined, shows model neutral only during playback and retains the previous played reply separately. New TTS diagnostic metadata keeps input_chars instead of the speech body; existing conversation history and the actual reply-only TTS request retain their original function. Old diagnostic reports remain accepted. See ../docs/CAMERA_EMOTION_051.md.
+49 -14
View File
@@ -33,8 +33,8 @@
},
"gateway.py": {
"source": "workspace:gateway/gateway.py",
"sha256": "d9215f99339de0667e830fbd4d3bff80ac5a61c85630cc4ecadcb52a4c33a0e5",
"bytes": 37391,
"sha256": "b8e64e9387fca05808fac61bd097ae179e996a2c7ccd33f23bb729a61693dd0d",
"bytes": 38559,
"upstream_sha256": "d088bedcf5c0accd4712e06202f6ced8ab155aad57a5b05683724efa346326ce"
},
"guest_sessions.py": {
@@ -124,9 +124,10 @@
"upstream_sha256": "6dd818484a064dc3fc9efe5ca71cc11ffcd3a0dcc45ea4185065732dab0289cc"
},
"tests/test_debug.py": {
"source": "tests/test_debug.py",
"sha256": "26f9e374354b714ab1a03b56af90bcbf32135711dc4f26e2c53eaa90c7f02ddd",
"bytes": 2837
"source": "workspace:gateway/tests/test_debug.py",
"sha256": "7d1d7876c4106f3df0b84cf8f7e479afb4a30ca51264fb94fa288fdd8155883e",
"bytes": 3665,
"upstream_sha256": "26f9e374354b714ab1a03b56af90bcbf32135711dc4f26e2c53eaa90c7f02ddd"
},
"tests/test_gateway.py": {
"source": "tests/test_gateway.py",
@@ -245,8 +246,8 @@
},
"README.md": {
"source": "workspace:gateway/README.md",
"sha256": "808a77916a8ba477cd6d95ae255cc661239c97031760d83fe38ea43c571deb6d",
"bytes": 6666,
"sha256": "cc32a5d3cd21975ece637f467c5c2f4ca2bc6c90b3fd450a3da909a116b11d5e",
"bytes": 7397,
"upstream_sha256": "799bc84308eb17d58987c5bee8ce3cf7617b4c52169d9307d344ac7d9996b6c5"
},
"config/active_profile.json.example": {
@@ -282,8 +283,9 @@
},
"reply_emotion.py": {
"source": "workspace:gateway/reply_emotion.py",
"sha256": "488fbd24ff1ce7d3d4ab92257c8ccabafe24fc857e11c8486f54fa689276a565",
"bytes": 3114
"sha256": "a2b6a1a51639d77368c200f2a6db8bb66fff1eebb4f60219d49da69ae402a8a2",
"bytes": 4005,
"upstream_sha256": "488fbd24ff1ce7d3d4ab92257c8ccabafe24fc857e11c8486f54fa689276a565"
},
"scripts/check-archive.py": {
"source": "workspace:gateway/scripts/check-archive.py",
@@ -293,14 +295,14 @@
},
"tests/test_gateway_emotion.py": {
"source": "workspace:gateway/tests/test_gateway_emotion.py",
"sha256": "fc01e9319263b93adb1cc93904d23a13a25965ddb0fcfbd9c3e14e39f4cf52a5",
"bytes": 4589,
"sha256": "e4da9a092e6ee19ef421a43a04cd2b6d12cb65f1b210946092dcad016c8816bb",
"bytes": 7923,
"upstream_sha256": "86f22211e753e4b5ebfa11266e2e33eb2ea6b85707fbe8a988be6b8ff05f3f75"
},
"tests/test_reply_emotion.py": {
"source": "workspace:gateway/tests/test_reply_emotion.py",
"sha256": "324fdaf55b501a31af129d41e9cf459f741ff0636818a6c628657dfde3fa6344",
"bytes": 2701,
"sha256": "2bd1ee33f11e2d23ccf9a30603f0db3b9f20c6d5fce8001f37f9ca76167974dd",
"bytes": 4678,
"upstream_sha256": "e45ccda640ef758fcb925d53804071349bdc8fb9f43ee1f63d1afb2ee3f238f5"
},
"llm_provider.py": {
@@ -317,7 +319,7 @@
}
},
"archive_baseline_commit": "19a7adccd9322986eb0646b165b9ce1cf2650cf2",
"workspace_release": "0.5.0",
"workspace_release": "0.5.1",
"provider_baseline": {
"source": "SPARK2 whitelist observed 2026-10-12",
"files": {
@@ -344,5 +346,38 @@
"tests/test_llm_provider.py": "6a8bd33679d68899c2a978bf4de672578517494c613b8e77d275c6207de3285b",
"tests/test_v08.py": "f993d4162576494e814786f26376ba80ab8a77af98ba70de4379055bb9525082"
}
},
"release_baseline_commit": "d43c7d4e809a5a6b18ca9f28c8163a2f9ad34c7f",
"deployment_baseline": {
"release": "0.5.0",
"files": {
"app.py": "d6520894dfbe035f64b1984aae15976db4df0e7e720195c81d3bf483b240056f",
"face_context.py": "01abfc214ebb4e979faf9430166eccae9af37df911d36da5435f907769e7e31a",
"gateway.py": "d9215f99339de0667e830fbd4d3bff80ac5a61c85630cc4ecadcb52a4c33a0e5",
"guest_sessions.py": "cc082fdb6c2ff7f5a41361ffe9ea2a53ebb944ee37354f65119405ad7a521c82",
"history.py": "2cf8b006bf486a03e038a69daa860ebb71a86989161cf6a7ea610114177a249f",
"llm_provider.py": "56ce6c1a4a647dea6ef86a83615f03db3a4397ebb3fa800b7fa655147d4f9978",
"persona_resolver.py": "deb33b4f4c17792fa5a6837362d5b29173e60a57bb993b61363bd4882d66d5de",
"protocol.py": "d9f522d958935200002e56024949a12b71eb89b3f3241635c5c307b798ee71c5",
"reply_emotion.py": "488fbd24ff1ce7d3d4ab92257c8ccabafe24fc857e11c8486f54fa689276a565",
"segmentation.py": "562ffc6e06f5b9f9072860b588feae3a5d7cd6eaa8577ac928d770071b06978d",
"tests/test_continuity.py": "d8390238f390463a98f12b9909bb5846be65f5b6dc1b21b94338b4cd75aaafae",
"tests/test_debug.py": "26f9e374354b714ab1a03b56af90bcbf32135711dc4f26e2c53eaa90c7f02ddd",
"tests/test_face_context.py": "50ca57adee1d07a194ebaa95b15e09d3e836b97b19490e99e3e045c72a89682c",
"tests/test_gateway.py": "f22aa98f3d6f62a2949a9047ec97e6dd686cac807d989a314a95deca718a3104",
"tests/test_gateway_emotion.py": "fc01e9319263b93adb1cc93904d23a13a25965ddb0fcfbd9c3e14e39f4cf52a5",
"tests/test_gateway_reply_face.py": "4a4a8fd997941c0d92356c2ebab2c336abbcf84954735a6955d8fa7e3700ec3f",
"tests/test_guests.py": "6bc531f1bff85b8ea550bc88c634726531a1ef241ba5c861dbb8c963adf31c35",
"tests/test_history.py": "fc13a69811cfc4f4acf265ea9e0cdd67d566358ebe9b9b53cae76197db8bce78",
"tests/test_llm_provider.py": "45404653daa71a006a90852b2f07f00cac608bd7311dd5ea850da0c1a3e52940",
"tests/test_personas.py": "2576f2be903c69270cb1dec1e12448154554798bd7fca866d78e66e31594cbcb",
"tests/test_reply_emotion.py": "324fdaf55b501a31af129d41e9cf459f741ff0636818a6c628657dfde3fa6344",
"tests/test_segmentation.py": "cf80a74958a715a81180a7932efb84f1d0974b434cf4fc3354b68c604ccbf463",
"tests/test_v08.py": "f993d4162576494e814786f26376ba80ab8a77af98ba70de4379055bb9525082",
"tests/test_vad.py": "bff64c0aafa05c085af7c1c9418244609129d405320fe1080b4ba05a8e304228",
"tests_fake.py": "9a40f1948352f69f1dd20f8514baef58ae3d11eec240e1d2324d8990bad915d8",
"tts_debug.py": "d7b31b98a7f8ab688981873ef81decdf0b2f0167113c9103df039b7b24c9ccf2",
"vad.py": "3718ff9b296b2bba447100af520a631f221dcbfa322dd564cdc5809fb3675f23"
}
}
}
+17 -3
View File
@@ -472,6 +472,8 @@ class Dialogue:
messages = [{'role': 'system', 'content': system}] + self.contexts.get(turn, []) + [{'role': 'user', 'content': text}]
url, headers, body = self.llm_provider.request(messages, max_tokens=160)
raw_body = ''
finish_reason = 'not_provided'
usage = {}
async with asyncio.timeout(30):
async with self.client.stream('POST', url, headers=headers, json=body) as response:
response.raise_for_status()
@@ -483,7 +485,15 @@ class Dialogue:
raw = '\n'.join(event_data); event_data = []
if raw == '[DONE]': break
data = json.loads(raw)
reported_usage = data.get('usage')
if isinstance(reported_usage, dict):
for key in ('prompt_tokens', 'completion_tokens', 'total_tokens'):
value = reported_usage.get(key)
if type(value) is int and 0 <= value <= 10_000_000: usage[key] = value
for choice in data.get('choices', []):
reported_finish = choice.get('finish_reason')
if reported_finish is not None:
finish_reason = reported_finish if reported_finish in ('stop', 'length', 'content_filter', 'tool_calls', 'function_call') else 'unknown'
delta = choice.get('delta', {}).get('content') or ''
if not delta: continue
metrics.setdefault('llm_first_token_ms', round((time.perf_counter() - request_start) * 1000, 2))
@@ -492,7 +502,10 @@ class Dialogue:
if turn != self.turn: return
if not raw_body.strip(): raise ValueError('empty LLM body')
parse_start = time.perf_counter()
result = parse_reply(raw_body)
result = parse_reply(raw_body, finish_reason=finish_reason)
metrics.update(reply_emotion_reason=result.reason, reply_parse_branch=result.parse_branch,
reply_emotion=result.emotion, reply_intensity=result.intensity,
llm_finish_reason=finish_reason, llm_usage=usage, llm_max_tokens=body['max_tokens'])
metrics['reply_parse_ms'] = round((time.perf_counter() - parse_start) * 1000, 2)
metrics['reply_emotion_source'] = result.source
metrics['llm_first_body_ms'] = round((time.perf_counter() - request_start) * 1000, 2)
@@ -501,7 +514,8 @@ class Dialogue:
# Only the extracted reply enters events, persistent history and the single TTS generator.
self.answers[turn] = result.reply
await self.event('llm', turn, text=result.reply)
await self.event('reply.emotion', turn, emotion=result.emotion, intensity=result.intensity, source=result.source)
await self.event('reply.emotion', turn, emotion=result.emotion, intensity=result.intensity, source=result.source, reason=result.reason, parse_branch=result.parse_branch,
finish_reason=finish_reason, usage=usage)
await self.event('llm.finished', turn, voice_mode=self.voice_mode, llm_finished_ms=metrics['llm_finished_ms'])
async def enqueue(fragment):
if fragment:
@@ -536,7 +550,7 @@ class Dialogue:
self.debug_captures[turn] = await asyncio.to_thread(self.debug_store.create, {'run_id':self.run_id,'conversation_id':self.conversation_id,'turn_id':turn,'voice_id':self.voice_id,'voice_mode':self.voice_mode,'persona':self.persona,'tts_requests':[]})
capture = self.debug_captures.get(turn)
if capture:
capture.meta['tts_requests'].append({'input':text,'parameters':{'model':'openbmb/VoxCPM2','voice':self.voice_id,'stream':True},'request_number':sentence})
capture.meta['tts_requests'].append({'input_chars':len(text),'parameters':{'model':'openbmb/VoxCPM2','voice':self.voice_id,'stream':True},'request_number':sentence})
async with asyncio.timeout(30):
async with self.client.stream('POST', 'http://192.168.31.61:5002/v1/audio/speech', json={'model': 'openbmb/VoxCPM2', 'input': text, 'voice': self.voice_id, 'stream': True}) as response:
response.raise_for_status()
+32 -16
View File
@@ -12,6 +12,8 @@ class ReplyEmotion:
emotion: str = 'neutral'
intensity: int = 0
source: str = 'fallback'
reason: str = 'invalid_json'
parse_branch: str = 'safe_reply'
def clean_reply(value):
@@ -23,37 +25,51 @@ def clean_reply(value):
return value
def parse_reply(raw):
if not isinstance(raw, str) or len(raw) > 8192: return ReplyEmotion(SAFE_REPLY)
def parse_reply(raw, finish_reason=None):
# A damaged envelope alone is not evidence of a token cutoff.
def fallback(reply, reason, branch):
return ReplyEmotion(reply, reason='truncated' if finish_reason == 'length' else reason, parse_branch=branch)
if not isinstance(raw, str) or len(raw) > 8192:
return fallback(SAFE_REPLY, 'input_limit', 'safe_reply')
body = raw.strip()
if body.startswith('```'):
fenced = body.startswith('```')
if fenced:
body = re.sub(r'^```(?:json)?\s*', '', body, count=1).removesuffix('```').strip()
try: data = json.loads(body)
except (ValueError, RecursionError): data = None
reason = 'invalid_json'
if isinstance(data, dict):
reply = clean_reply(data.get('reply'))
if reply:
emotion, intensity = data.get('emotion'), data.get('intensity')
if (set(data) == {'reply', 'emotion', 'intensity'} and type(intensity) is int and
((emotion == 'neutral' and intensity == 0) or
(emotion in ('happy', 'angry', 'sad') and intensity in (1, 2)))):
return ReplyEmotion(reply, emotion, intensity, 'model')
return ReplyEmotion(reply)
required = {'reply', 'emotion', 'intensity'}
if not required.issubset(data): reason = 'missing_fields'
elif set(data) != required: reason = 'unexpected_fields'
elif not reply: reason = 'invalid_reply'
elif not isinstance(data['emotion'], str) or data['emotion'] not in ('neutral', 'happy', 'angry', 'sad'):
reason = 'invalid_emotion'
elif type(data['intensity']) is not int or not (
data['emotion'] == 'neutral' and data['intensity'] == 0 or
data['emotion'] != 'neutral' and data['intensity'] in (1, 2)):
reason = 'invalid_intensity'
else:
return ReplyEmotion(reply, data['emotion'], data['intensity'], 'model', 'none',
'fenced_json' if fenced else 'strict_json')
if reply: return fallback(reply, reason, 'json_reply')
for key in ('text', 'answer'):
reply = clean_reply(data.get(key))
if reply: return ReplyEmotion(reply)
# Recover a usable quoted reply from a damaged/truncated envelope without another model call.
if reply: return fallback(reply, reason, 'alternate_field')
# Recover only the reply string, never speak the envelope or make another model request.
match = re.search(r'"reply"\s*:\s*(")', body)
if match:
literal = body[match.start(1):]
branch = 'quoted_reply'
try: value, _ = json.JSONDecoder().raw_decode(literal)
except ValueError:
# Only a truncated string, never arbitrary suffix/JSON syntax recovery.
branch = 'repaired_string'
try: value = json.loads(literal.rstrip('\\') + '"')
except ValueError: value = None
reply = clean_reply(value)
if reply: return ReplyEmotion(reply)
if reply: return fallback(reply, reason, branch)
if not any(c in body for c in '{}[]') and not re.search(r'\b(?:reply|emotion|intensity)\s*[:=]', body):
reply = clean_reply(body)
if reply: return ReplyEmotion(reply)
return ReplyEmotion(SAFE_REPLY)
if reply: return fallback(reply, 'non_json', 'plain_text')
return fallback(SAFE_REPLY, reason, 'safe_reply')
+11
View File
@@ -41,6 +41,17 @@ class DebugTests(unittest.TestCase):
payload['debug_id']='../bad'
self.assertEqual(client.post('/debug/download',json=payload,headers=headers).status_code,404)
def test_report_accepts_old_and_finite_new_diagnostics(self):
from unittest.mock import patch
app.state.lan_open=True;app.state.remote_reports=[]
old={'type':'diagnostic_report','app_version':'0.5.0','logs':[]}
new={**old,'app_version':'0.5.1','version_code':9,'camera':{'granted':False,'status':'off','permission_pending':False,'face_sharing':False},
'role_playing':False,'role_active':None,'role_previous':{'turn_id':2,'seq':7,'emotion':'neutral','intensity':0,'source':'fallback','reason':'non_json'}}
with patch('gateway.GuestSessions.lan',return_value=True):
client=TestClient(app)
for payload in (old,new):self.assertEqual(client.post('/debug/report',json=payload).status_code,200)
self.assertEqual(len(app.state.remote_reports),2)
def test_lore_constraints_bounded(self):
d=json.loads(Path('personas/lvbu.lorebook.json').read_text());text=d['rules']+'\n'+'\n'.join(e['text'] for e in d['entries'])
self.assertLess(len(text),1400)
+45
View File
@@ -49,6 +49,51 @@ class EmotionPipelineTests(unittest.IsolatedAsyncioTestCase):
self.assertGreater(events[0]['seq'],0);self.assertLess(order.index('reply.emotion'),order.index('pcm'))
self.assertTrue(socket.frames)
async def test_finish_usage_and_metadata_never_store_model_envelope(self):
for finish,expected in [('length','truncated'),('stop','invalid_json'),(None,'invalid_json')]:
socket=Socket()
content='{"reply":"公开正文","emotion":'
records=[{'choices':[{'delta':{'content':content},'finish_reason':None}]},
{'choices':[{'delta':{},'finish_reason':finish}]},
{'choices':[],'usage':{'prompt_tokens':20,'completion_tokens':160,'total_tokens':180,'private':'never-log','bad':True}}]
stream=''.join('data: '+json.dumps(row)+'\n\n' for row in records)+'data: [DONE]\n\n'
async with httpx.AsyncClient(transport=httpx.MockTransport(lambda req:httpx.Response(200,text=stream))) as client:
d=Dialogue(socket,FakeModel(),client);queue=asyncio.Queue(2);metrics={}
await d.generate(0,'公开问题',queue,metrics,time.perf_counter())
self.assertEqual(await queue.get(),'公开正文');self.assertIsNone(await queue.get())
event=next(e for e in socket.events if e['type']=='reply.emotion')
self.assertEqual(event['reason'],expected)
self.assertEqual(event['finish_reason'],finish or 'not_provided')
self.assertEqual(event['usage'],{'prompt_tokens':20,'completion_tokens':160,'total_tokens':180})
self.assertEqual((event['emotion'],event['intensity'],event['source']),('neutral',0,'fallback'))
self.assertNotIn('reply',event);self.assertNotIn('公开正文',json.dumps(metrics,ensure_ascii=False))
self.assertEqual(metrics['llm_max_tokens'],160)
async def test_debug_metadata_contains_counts_not_reply_text(self):
import tempfile
from pathlib import Path
from tts_debug import DebugStore
spoken='公开诊断正文不应落入metadata'
def backend(request):
if 'transcriptions' in request.url.path:return httpx.Response(200,json={'text':'公开问题'})
if 'chat' in request.url.path:
content=json.dumps({'reply':spoken,'emotion':'happy','intensity':1})
return httpx.Response(200,text='data: '+json.dumps({'choices':[{'delta':{'content':content},'finish_reason':'stop'}]})+'\n\ndata: [DONE]\n\n')
out=io.BytesIO()
with wave.open(out,'wb') as w:
w.setnchannels(1);w.setsampwidth(2);w.setframerate(48000);w.writeframes(b'\x11\x01'*960)
return httpx.Response(200,content=out.getvalue())
with tempfile.TemporaryDirectory() as folder:
async with httpx.AsyncClient(transport=httpx.MockTransport(backend)) as client:
d=Dialogue(Socket(),FakeModel(),client);d.debug_store=DebugStore(folder);d.run_id='synthetic'
await d.run(0,bytes(640))
metadata=json.loads(next(Path(folder).glob('*/metadata.json')).read_text())
self.assertEqual(metadata['tts_requests'][0]['input_chars'],len(spoken))
self.assertNotIn('input',metadata['tts_requests'][0])
self.assertNotIn(spoken,json.dumps(metadata,ensure_ascii=False))
self.assertEqual(metadata['metrics']['reply_emotion'],'happy')
self.assertEqual(metadata['metrics']['reply_emotion_reason'],'none')
async def test_stale_generation_cannot_publish_emotion_or_speak(self):
entered=asyncio.Event();resume=asyncio.Event();socket=Socket()
class Slow(httpx.AsyncByteStream):
+31
View File
@@ -35,6 +35,37 @@ class ReplyEmotionTests(unittest.TestCase):
self.assertEqual(result.reply,expected)
self.assertEqual((result.emotion,result.intensity,result.source),('neutral',0,'fallback'))
def test_fixed_reasons_and_recovery_branches(self):
cases = [
({'reply':'正文'}, 'missing_fields'),
({'reply':'正文','emotion':'fear','intensity':1}, 'invalid_emotion'),
({'reply':'正文','emotion':'happy','intensity':True}, 'invalid_intensity'),
({'reply':'正文','emotion':'happy','intensity':1.0}, 'invalid_intensity'),
({'reply':'正文','emotion':'happy','intensity':1,'extra':1}, 'unexpected_fields'),
]
for data,reason in cases:
parsed=parse_reply(json.dumps(data))
self.assertEqual((parsed.reason,parsed.parse_branch,parsed.reply),(reason,'json_reply','正文'))
self.assertEqual(parsed.source,'fallback')
for raw,reason,branch in [('普通正文','non_json','plain_text'),
('{"reply":"正文","emotion":','invalid_json','quoted_reply'),
('{"reply":"正文','invalid_json','repaired_string'),
('{"answer":"正文"}','missing_fields','alternate_field')]:
result=parse_reply(raw)
self.assertEqual((result.reason,result.parse_branch),(reason,branch))
self.assertEqual(result.reply,'普通正文' if branch=='plain_text' else '正文')
def test_length_is_evidence_not_a_guess(self):
broken='{"reply":"正文'
self.assertEqual(parse_reply(broken).reason,'invalid_json')
self.assertEqual(parse_reply(broken,'stop').reason,'invalid_json')
result=parse_reply(broken,'length')
self.assertEqual((result.reason,result.source,result.reply),('truncated','fallback','正文'))
# A complete validated object can remain valid even at the token budget boundary.
valid='{"reply":"正文","emotion":"neutral","intensity":0}'
self.assertEqual(parse_reply(valid,'length').source,'model')
self.assertEqual(parse_reply(valid).reason,'none')
def test_no_model_retry_or_schema_contract(self):
from pathlib import Path
source=(Path(__file__).resolve().parents[1]/'gateway.py').read_text()