fix(chat): delete needs the person's own yes; chat action ids never repeat
- chatChannels delete with confirm=true now runs only in the person's very next turn and only when their own message of that turn agrees, checked by a small fail-closed YES/NO call on the router model chain (the message fenced as data). A refusal, question, other topic or error cancels the request; an unconfirmed request lapses after one turn. The reply model's confirm flag alone can no longer delete. - chat_action ids carry a per-run nonce and the session, so a late answer meant for an earlier connection (or worker run) never completes a newer action. - Tests: agree, refuse, other topic, lapse, classifier failure, late answer across reconnects. Eval test_chat_delete_consent: 12 of 12 on qwen2.5:7b, 3 runs. Spec and llm_contexts updated. Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
This commit is contained in:
@@ -457,3 +457,46 @@ def test_a_chat_action_the_app_never_answers_fails(store):
|
||||
|
||||
asyncio.run(run())
|
||||
assert results and results[0]["ok"] is False and results[0]["error"]
|
||||
|
||||
|
||||
@pytest.mark.unit
|
||||
def test_a_late_answer_from_an_earlier_connection_is_not_taken_for_a_new_action(store):
|
||||
results = []
|
||||
brain = FakeBrain(lambda u, t: results.append(brain.chat.act("send", "c1", text="x")) or "done")
|
||||
worker = VoiceWorker(TOKEN, LevelTranscriber(), AmplitudeVad, None, history=store, brain=brain,
|
||||
chat_timeout_s=0.5)
|
||||
|
||||
async def ask(url):
|
||||
async with connect(url) as ws:
|
||||
await hello(ws)
|
||||
await ws.send(json.dumps(CHANNELS))
|
||||
await send(ws, type="reply", id="r1", user="100", text="q", via="chat", speak=False)
|
||||
seen = await recv_until(ws, lambda m: isinstance(m, dict) and m.get("type") == "chat_action")
|
||||
return ws, seen[-1]["id"]
|
||||
|
||||
async def run():
|
||||
server = await worker.serve("127.0.0.1", 0)
|
||||
url = f"ws://127.0.0.1:{server.sockets[0].getsockname()[1]}"
|
||||
try:
|
||||
async with connect(url) as ws: # first connection: asked, never answered, then gone
|
||||
await hello(ws)
|
||||
await ws.send(json.dumps(CHANNELS))
|
||||
await send(ws, type="reply", id="r1", user="100", text="q", via="chat", speak=False)
|
||||
old = (await recv_until(ws, lambda m: isinstance(m, dict) and m.get("type") == "chat_action"))[-1]["id"]
|
||||
async with connect(url) as ws: # second connection: the old answer arrives late
|
||||
await hello(ws)
|
||||
await ws.send(json.dumps(CHANNELS))
|
||||
await send(ws, type="reply", id="r2", user="100", text="q", via="chat", speak=False)
|
||||
new = (await recv_until(ws, lambda m: isinstance(m, dict) and m.get("type") == "chat_action"))[-1]["id"]
|
||||
await send(ws, type="chat_action_result", id=old, ok=True, message_ids=["stale"])
|
||||
await recv_until(ws, lambda m: isinstance(m, dict) and m.get("id") == "r2")
|
||||
return old, new
|
||||
finally:
|
||||
server.close()
|
||||
await server.wait_closed()
|
||||
await worker.stop()
|
||||
|
||||
old, new = asyncio.run(asyncio.wait_for(run(), 15))
|
||||
assert old != new
|
||||
assert all(r.get("message_ids") != ["stale"] for r in results), results
|
||||
assert results[-1]["ok"] is False
|
||||
|
||||
@@ -1,5 +1,7 @@
|
||||
"""chatChannels tool (src/jarvis/tools/builtin/chat_channels.spec.md) with a fake chat backend."""
|
||||
|
||||
from unittest.mock import patch
|
||||
|
||||
import pytest
|
||||
|
||||
from jarvis.reply import turn_state
|
||||
@@ -41,16 +43,29 @@ class FakeChat:
|
||||
return {"ok": True, "message_ids": ["99"]}
|
||||
|
||||
|
||||
def call(args, chat):
|
||||
class Cfg:
|
||||
ollama_base_url = "http://x"
|
||||
ollama_chat_model = "m"
|
||||
|
||||
|
||||
def call(args, chat, said=""):
|
||||
"""``said`` is the person's own message this turn (what the consent check reads)."""
|
||||
turn_state.reset()
|
||||
turn_state.set_chat(chat)
|
||||
try:
|
||||
return ChatChannelsTool().execute(db=None, cfg=None, tool_args=args, system_prompt="", original_prompt="",
|
||||
redacted_text="", max_retries=0, user_print=lambda m: None)
|
||||
return ChatChannelsTool().execute(db=None, cfg=Cfg(), tool_args=args, system_prompt="", original_prompt=said,
|
||||
redacted_text=said, max_retries=0, user_print=lambda m: None)
|
||||
finally:
|
||||
turn_state.reset()
|
||||
|
||||
|
||||
def consent(answers):
|
||||
"""The consent classifier answers by what the person said."""
|
||||
def fake(base_url, model, system_prompt, user_content, **kw):
|
||||
return next((a for said, a in answers.items() if said in user_content), "NO")
|
||||
return patch("jarvis.tools.builtin.chat_channels.call_llm_direct", side_effect=fake)
|
||||
|
||||
|
||||
@pytest.fixture
|
||||
def chat():
|
||||
return FakeChat([chan("1", "일정", "모임과 약속"), chan("2", "잡담", "아무 얘기", send=False, delete=True)])
|
||||
@@ -112,23 +127,58 @@ def test_edit_react_and_pin_pass_their_arguments(chat):
|
||||
("unpin", "1", {"message_id": "12"})]
|
||||
|
||||
|
||||
def test_delete_needs_the_users_yes_in_a_later_turn(chat):
|
||||
ask = {"action": "delete", "channel": "잡담", "message_id": "21"}
|
||||
first = call(ask, chat)
|
||||
assert first.success and chat.acts == [] and "confirm" in first.reply_text.lower()
|
||||
# The same turn cannot confirm its own request.
|
||||
assert not call({**ask, "confirm": True}, chat).success and chat.acts == []
|
||||
chat.turn = 2
|
||||
assert call({**ask, "confirm": True}, chat).success
|
||||
ASK = {"action": "delete", "channel": "잡담", "message_id": "21"}
|
||||
|
||||
|
||||
def test_delete_happens_only_when_the_next_message_agrees(chat):
|
||||
with consent({"응 지워": "YES"}):
|
||||
first = call(ASK, chat, said="21번 지워 줘")
|
||||
assert first.success and chat.acts == [] and "confirm" in first.reply_text.lower()
|
||||
# The same turn cannot confirm its own request, whatever the model passes.
|
||||
assert not call({**ASK, "confirm": True}, chat, said="21번 지워 줘").success and chat.acts == []
|
||||
chat.turn = 2
|
||||
assert call({**ASK, "confirm": True}, chat, said="응 지워").success
|
||||
assert chat.acts == [("delete", "2", {"message_id": "21"})]
|
||||
# Used up: a second confirm deletes nothing more.
|
||||
# Used up: a later confirm deletes nothing more.
|
||||
chat.turn = 3
|
||||
assert not call({**ask, "confirm": True}, chat).success and len(chat.acts) == 1
|
||||
with consent({"응 지워": "YES"}):
|
||||
assert not call({**ASK, "confirm": True}, chat, said="응 지워").success
|
||||
assert len(chat.acts) == 1
|
||||
|
||||
|
||||
@pytest.mark.parametrize("said", ["아니, 지우지 마. 취소해", "오늘 날씨 어때?"])
|
||||
def test_a_refusal_or_another_topic_cancels_the_request(chat, said):
|
||||
with consent({"응 지워": "YES"}):
|
||||
call(ASK, chat, said="21번 지워 줘")
|
||||
chat.turn = 2
|
||||
res = call({**ASK, "confirm": True}, chat, said=said)
|
||||
assert not res.success and chat.acts == []
|
||||
# Cancelled: agreeing afterwards does not bring the old request back.
|
||||
chat.turn = 3
|
||||
assert not call({**ASK, "confirm": True}, chat, said="응 지워").success
|
||||
assert chat.acts == [] and not chat.pending_deletes
|
||||
|
||||
|
||||
def test_the_yes_must_come_in_the_very_next_message(chat):
|
||||
with consent({"응 지워": "YES"}):
|
||||
call(ASK, chat, said="21번 지워 줘")
|
||||
chat.turn = 3 # something else was said in between
|
||||
assert not call({**ASK, "confirm": True}, chat, said="응 지워").success
|
||||
assert chat.acts == []
|
||||
|
||||
|
||||
def test_the_consent_check_failing_means_no(chat):
|
||||
call(ASK, chat, said="21번 지워 줘")
|
||||
chat.turn = 2
|
||||
with patch("jarvis.tools.builtin.chat_channels.call_llm_direct", return_value=None):
|
||||
assert not call({**ASK, "confirm": True}, chat, said="응 지워").success
|
||||
assert chat.acts == []
|
||||
|
||||
|
||||
def test_confirm_without_a_request_is_refused(chat):
|
||||
chat.turn = 5
|
||||
assert not call({"action": "delete", "channel": "잡담", "message_id": "21", "confirm": True}, chat).success
|
||||
with consent({"응": "YES"}):
|
||||
assert not call({**ASK, "confirm": True}, chat, said="응").success
|
||||
assert chat.acts == []
|
||||
|
||||
|
||||
|
||||
Reference in New Issue
Block a user