fix(voice_worker): keep history and the brain's output scoped to who was there
- A final is stored under the channel, speaker name and time fixed when its end was decided. Decoding takes a while; a move, rename or late joiner meanwhile used to change where and when it was said, and who heard it. - At start the worker closes presence a killed run left open (HistoryStore.close_open_presence), so a person who is gone no longer hears new speech after a restart. - run_reply_engine(legacy_memory=False) skips v1's single-user memory (warm profile, extractor, diary, graph, digest); the v2 brain uses it so another user's profile or diary never reaches the prompt. - While a brain reply runs, stdout and stderr are muted (also helper threads such as the web fetch pool); the worker logs through voice_worker/log.py to the original stderr. - Live check: Ollama's /v1 fixes the context at 2,048 tokens and cut the prompt in earlier runs; with an 8k tag the chat-record question was answered 4 of 4 and nothing reached the output. Noted in llm_contexts and the eval. Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
This commit is contained in:
@@ -49,3 +49,26 @@ def test_history_lines_reach_the_system_prompt():
|
||||
@pytest.mark.parametrize("history", [None, HistoryContext()])
|
||||
def test_no_history_adds_nothing(history):
|
||||
assert "<conversation_records>" not in _system_prompt(history)
|
||||
|
||||
|
||||
def _system_prompt_with(legacy_memory, profile):
|
||||
with patch("src.jarvis.reply.engine.plan_query", return_value=[]), \
|
||||
patch("src.jarvis.reply.engine.extract_search_params_for_memory", return_value={}), \
|
||||
patch("src.jarvis.reply.engine.extract_text_from_response", return_value="Hello."), \
|
||||
patch("src.jarvis.memory.graph.GraphMemoryStore"), \
|
||||
patch("src.jarvis.memory.graph_ops.build_warm_profile", return_value={"user": profile, "directives": ""}), \
|
||||
patch("src.jarvis.memory.graph_ops.format_warm_profile_block", return_value=profile), \
|
||||
patch("src.jarvis.reply.engine.chat_with_messages") as mock_chat:
|
||||
mock_chat.return_value = {"message": {"content": "Hello."}}
|
||||
run_reply_engine(db=Mock(), cfg=_mock_cfg(512), tts=None, text="hi", dialogue_memory=DialogueMemory(),
|
||||
history=HistoryContext(), legacy_memory=legacy_memory)
|
||||
messages = mock_chat.call_args.kwargs.get("messages") or mock_chat.call_args.args[2]
|
||||
return messages[0]["content"]
|
||||
|
||||
|
||||
@pytest.mark.unit
|
||||
def test_v2_turns_off_the_single_user_profile():
|
||||
"""v1's profile, diary and graph belong to one user; in a shared v2 channel they would leak."""
|
||||
profile = "PROFILE: Alice is allergic to peanuts"
|
||||
assert profile in _system_prompt_with(True, profile)
|
||||
assert profile not in _system_prompt_with(False, profile)
|
||||
|
||||
@@ -225,3 +225,122 @@ def test_malformed_history_messages_are_rejected(store):
|
||||
|
||||
seen = asyncio.run(with_worker(body, store=store, brain=FakeBrain()))
|
||||
assert [s[-1]["code"] for s in seen] == ["bad_message", "bad_message"]
|
||||
|
||||
|
||||
class SlowTranscriber(LevelTranscriber):
|
||||
def __init__(self, delay):
|
||||
super().__init__()
|
||||
self.delay = delay
|
||||
|
||||
def transcribe(self, clips, opts):
|
||||
import time as _t
|
||||
_t.sleep(self.delay)
|
||||
return super().transcribe(clips, opts)
|
||||
|
||||
|
||||
@pytest.mark.unit
|
||||
def test_a_slow_final_keeps_the_channel_time_and_name_of_when_it_was_said(store):
|
||||
async def body(url):
|
||||
async with connect(url) as ws:
|
||||
await hello(ws, stt={"partials": False})
|
||||
await send(ws, type="voice_join", channel="vc1")
|
||||
await send(ws, type="member_join", user="100", name="Alice")
|
||||
await stream(ws, "100", 0.9, 600)
|
||||
await send(ws, type="speaking_end", speaker="100")
|
||||
# While the model is still decoding: a late joiner arrives, then Jarvis moves.
|
||||
await asyncio.sleep(0.15)
|
||||
await send(ws, type="member_join", user="300", name="Late")
|
||||
await send(ws, type="member_join", user="100", name="Renamed")
|
||||
await send(ws, type="voice_join", channel="vc2")
|
||||
await recv_until(ws, lambda m: isinstance(m, dict) and m.get("type") == "final")
|
||||
|
||||
worker = VoiceWorker(TOKEN, SlowTranscriber(0.6), AmplitudeVad, None, history=store)
|
||||
|
||||
async def run():
|
||||
server = await worker.serve("127.0.0.1", 0)
|
||||
port = server.sockets[0].getsockname()[1]
|
||||
try:
|
||||
await asyncio.wait_for(body(f"ws://127.0.0.1:{port}"), 15)
|
||||
finally:
|
||||
server.close()
|
||||
await server.wait_closed()
|
||||
await worker.stop()
|
||||
|
||||
asyncio.run(run())
|
||||
recs = store.records_of("100")
|
||||
assert [(r.channel_id, r.author_name, r.text) for r in recs] == [("vc1", "Alice", "level 0.9")]
|
||||
# The late joiner was not there when it was said.
|
||||
assert store.recent("300", now=4_000_000_000, scope=Scope(), minutes=10 ** 9) == []
|
||||
|
||||
|
||||
@pytest.mark.unit
|
||||
def test_presence_left_open_by_a_previous_run_is_closed_at_start(store):
|
||||
store.presence_join("old", "vc1", 1_000.0) # the worker was killed with "old" still present
|
||||
|
||||
async def body(url):
|
||||
async with connect(url) as ws:
|
||||
await hello(ws, stt={"partials": False})
|
||||
await send(ws, type="voice_join", channel="vc1")
|
||||
await send(ws, type="member_join", user="100", name="Alice")
|
||||
await say(ws, "100", 0.9)
|
||||
|
||||
asyncio.run(with_worker(body, store=store))
|
||||
assert texts(store.recent("100", now=4_000_000_000, scope=Scope(), minutes=10 ** 9)) == ["level 0.9"]
|
||||
assert store.recent("old", now=4_000_000_000, scope=Scope(), minutes=10 ** 9) == []
|
||||
|
||||
|
||||
@pytest.mark.unit
|
||||
def test_the_brain_prints_no_text_from_its_thread(tmp_path, monkeypatch, capfd):
|
||||
pytest.importorskip("mcp") # the real brain needs the jarvis dependencies (--brain)
|
||||
import sys
|
||||
import threading
|
||||
|
||||
from jarvis.memory.history import HistoryContext
|
||||
from voice_worker import brain as brain_mod
|
||||
|
||||
cfg = tmp_path / "config.json"
|
||||
cfg.write_text(json.dumps({"db_path": str(tmp_path / "jarvis.db")}))
|
||||
monkeypatch.setenv("JARVIS_CONFIG_PATH", str(cfg))
|
||||
|
||||
def fake_engine(db, cfg, tts, text, mem, language=None, history=None, legacy_memory=True):
|
||||
print(f"answer text {text}")
|
||||
print(f"debug {text}", file=sys.stderr)
|
||||
# Tools print from helper threads too (the web fetch pool).
|
||||
helper = threading.Thread(target=lambda: print(f"helper {text}", file=sys.stderr))
|
||||
helper.start()
|
||||
helper.join()
|
||||
return f"answer to {text}"
|
||||
|
||||
import jarvis.reply.engine as engine
|
||||
monkeypatch.setattr(engine, "run_reply_engine", fake_engine)
|
||||
b = brain_mod.JarvisBrain()
|
||||
out = []
|
||||
t = threading.Thread(target=lambda: out.append(b.reply("100", "secret question", HistoryContext())))
|
||||
t.start()
|
||||
t.join()
|
||||
print("other output stays")
|
||||
captured = capfd.readouterr()
|
||||
assert out == ["answer to secret question"]
|
||||
assert "secret question" not in captured.out + captured.err
|
||||
assert "other output stays" in captured.out
|
||||
|
||||
|
||||
@pytest.mark.unit
|
||||
def test_the_brain_turns_off_the_single_user_memory(tmp_path, monkeypatch):
|
||||
pytest.importorskip("mcp") # the real brain needs the jarvis dependencies (--brain)
|
||||
from jarvis.memory.history import HistoryContext
|
||||
from voice_worker import brain as brain_mod
|
||||
|
||||
cfg = tmp_path / "config.json"
|
||||
cfg.write_text(json.dumps({"db_path": str(tmp_path / "jarvis.db")}))
|
||||
monkeypatch.setenv("JARVIS_CONFIG_PATH", str(cfg))
|
||||
seen = {}
|
||||
|
||||
def fake_engine(db, cfg, tts, text, mem, language=None, history=None, legacy_memory=True):
|
||||
seen["legacy_memory"] = legacy_memory
|
||||
return "ok"
|
||||
|
||||
import jarvis.reply.engine as engine
|
||||
monkeypatch.setattr(engine, "run_reply_engine", fake_engine)
|
||||
brain_mod.JarvisBrain().reply("100", "q", HistoryContext())
|
||||
assert seen["legacy_memory"] is False
|
||||
|
||||
Reference in New Issue
Block a user