Files
Hermes_rocket.chat_Plugin/tests/live_rc/test_08_clarify.py
T
Bernd (Hermes) 7857bc1aea fix(tests): replace clarify trigger texts with genuinely ambiguous scenarios
The old trigger texts asked the model to 'ask me a question with multiple
choices' — which caused deepseek-v4-flash (.45) to answer the question
directly as text instead of calling the clarify tool. glm-5.2 (.101) only
worked because it knew to call clarify proactively.

New approach: genuinely ambiguous decision scenarios where the model lacks
context to answer directly (e.g. 'short-term results vs long-term
architecture improvements'). The model MUST use the clarify tool because
it genuinely needs more information — not because the text asks for it.

Changes:
- test_clarify_buttons_rendered: 2-option decision without context
- test_clarify_button_click: same 2-option decision
- test_clarify_chunking: 3-option decision (workaround/refactoring/migration)
- test_clarify_modal_status: same 2-option decision

All trigger texts verified against room-map keywords_100 — no false routing.
No changes to test logic, assertions, or button extraction.
2026-08-14 06:05:26 +02:00

702 lines
26 KiB
Python

"""
Test 08 — Clarify: Button-Rendering, Button-Klick, Chunking, Modal-Status.
Verifiziert den vollständigen Clarify-Flow des Rocket.Chat-Plugins:
1. Clarify-Buttons werden korrekt gerendert (attachments, action_id, Emoji-Nummern)
2. Button-Klick via CLARIFY-Payload wird verarbeitet (kein pending_questions-Leak)
3. Chunking: max 3 Buttons/Reihe bei 4+ Optionen
4. Modal-Status: Bot-Status wechselt während Clarify auf busy/offline
TECHNISCHE DETAILS:
- CLARIFY-Payload-Format: CLARIFY:<clarify_id>::<choice_idx> (1-basiert)
- Button-Labels: Emoji-Nummern (1️⃣ 2️⃣ 3️⃣ ...)
- action_id: clarify_{clarify_id}_{i} (P-051 Fix)
- Chunking: MAX_BUTTONS_PER_ROW = 3 (adapter.py:7659)
- P6: Keine keywords_100 in Test-Messages
- P3: Polling 3s→8s→12s→20s, Timeout 120s
- 429: RateLimitSkip → pytest.skip
"""
from __future__ import annotations
import logging
import time
from typing import Optional
import pytest
from tests.live_rc.conftest import (
assert_bot_message,
post_test_message,
)
from tests.live_rc.helpers.polling import (
wait_for_bot_message,
get_latest_timestamp,
PollTimeout,
RateLimitSkip,
)
logger = logging.getLogger(__name__)
# ═══════════════════════════════════════════════════════════════════════════
# Helpers
# ═══════════════════════════════════════════════════════════════════════════
def _has_clarify_buttons(msg: dict) -> bool:
"""Check if a message contains clarify button attachments."""
attachments = msg.get("attachments", [])
for att in attachments:
for action in att.get("actions", []):
if (action.get("msg", "") or "").startswith("CLARIFY:"):
return True
return False
def _extract_clarify_id(msg: dict) -> Optional[str]:
"""Extract clarify_id from a bot message with clarify buttons.
Handles both formats:
- New: CLARIFY:<clarify_id>::<choice> (double colon)
- Old: CLARIFY:<clarify_id>:other (single colon, Other button)
"""
attachments = msg.get("attachments", [])
for att in attachments:
for action in att.get("actions", []):
msg_payload = (action.get("msg", "") or "")
if not msg_payload.startswith("CLARIFY:"):
continue
if "::" in msg_payload:
# New format: CLARIFY:<id>::<choice>
return msg_payload.split("::")[0].split(":", 1)[1]
# Old format: CLARIFY:<id>:<token>
parts = msg_payload.split(":", 2)
if len(parts) >= 2:
return parts[1]
return None
def _get_clarify_actions(msg: dict) -> list:
"""Get all clarify action dicts from a message's attachments."""
result = []
attachments = msg.get("attachments", [])
for att in attachments:
for action in att.get("actions", []):
if (action.get("msg", "") or "").startswith("CLARIFY:"):
result.append(action)
return result
# ═══════════════════════════════════════════════════════════════════════════
# Test 1: Clarify-Buttons werden korrekt gerendert
# ═══════════════════════════════════════════════════════════════════════════
@pytest.mark.live_rc
def test_clarify_buttons_rendered(
rc_client,
test_room_id: str,
bot_username: str,
bot_user_id: str,
cursor: str,
posted_message_ids: list,
rate_limiter,
cleanup_messages,
bot_status_check,
):
"""Verifiziere: Clarify-Buttons haben action_id, Emoji-Nummern, korrekte Struktur.
Steps:
1. Sende mehrdeutige Nachricht, die eine Clarify-Rückfrage auslöst
2. Warte auf Bot-Antwort mit attachments[].actions[]
3. Verifiziere: actions-Array existiert und ist nicht leer
4. Verifiziere: Jedes action-Dict hat ein action_id-Feld (P-051)
5. Verifiziere: Button-Labels enthalten Emoji-Nummern (1️⃣ 2️⃣ 3️⃣)
"""
# Step 1: Post ambiguous message to trigger clarify
# P6: Keine keywords_100 — generische Formulierung ohne Fachbegriffe
# Genuinely ambiguous: model lacks context to decide between two valid
# directions — must use clarify tool to ask which the user prefers.
trigger_text = (
"Wir muessen uns zwischen zwei wichtigen Richtungen entscheiden. "
"Sollen wir den Fokus auf kurzfristige Ergebnisse oder auf "
"langfristige Architekturverbesserungen legen?"
)
msg_id, _ = post_test_message(
rc_client, test_room_id, trigger_text,
posted_message_ids, rate_limiter,
)
logger.info(
"Test 08.1: posted clarify trigger '%s' → msg %s",
trigger_text[:60], msg_id[:12],
)
# Step 2: Wait for bot response with clarify buttons
try:
response = wait_for_bot_message(
client=rc_client,
room_id=test_room_id,
bot_username=bot_username,
cursor=cursor,
timeout=120.0,
rate_limiter=rate_limiter,
initial_interval=3.0,
)
except RateLimitSkip as e:
pytest.skip(f"Rate limit triggered: {e}")
except PollTimeout as e:
pytest.fail(
f"Bot did not send clarify buttons within 120s. "
f"Check that the agent uses the clarify tool for ambiguous questions. "
f"Trigger: '{trigger_text[:80]}'. Error: {e}"
)
# Track bot response for cleanup
response_id = response.get("_id", "")
if response_id:
posted_message_ids.append(response_id)
# Step 3: Verify attachments with actions exist
attachments = response.get("attachments", [])
assert attachments, (
f"Bot response has no attachments. "
f"Expected clarify buttons. Got text: '{response.get('msg', '')[:200]}'"
)
all_actions = _get_clarify_actions(response)
assert len(all_actions) > 0, (
f"Bot response attachments have no clarify actions. "
f"Attachments: {attachments}"
)
logger.info(
"Test 08.1: found %d clarify actions in %d attachment(s)",
len(all_actions), len(attachments),
)
# Step 4: Verify each action has action_id (P-051 Fix)
for i, action in enumerate(all_actions):
action_id = action.get("action_id", "")
assert action_id, (
f"Clarify action {i} missing action_id field (P-051 regression). "
f"Action: {action}"
)
# Verify action_id follows expected pattern
assert action_id.startswith("clarify_"), (
f"Clarify action {i} action_id='{action_id}' does not start with 'clarify_'. "
f"Expected pattern: clarify_{{clarify_id}}_{{index}}"
)
# Step 5: Verify button labels contain emoji numbers
emoji_numbers = ["1️⃣", "2️⃣", "3️⃣", "4️⃣", "5️⃣", "6️⃣", "7️⃣", "8️⃣", "9️⃣", "🔟"]
# The "Other" button has label "✏️ Other" — skip it for emoji check
choice_actions = [
a for a in all_actions
if (a.get("msg", "") or "").startswith("CLARIFY:")
and "::" in (a.get("msg", "") or "")
]
for i, action in enumerate(choice_actions):
label = action.get("text", "")
expected_emoji = emoji_numbers[i] if i < len(emoji_numbers) else str(i + 1)
assert expected_emoji in label, (
f"Clarify button {i} label='{label}' does not contain "
f"expected emoji '{expected_emoji}'"
)
# Verify message ownership
assert_bot_message(
response,
expected_username=bot_username,
context="test_clarify_buttons_rendered",
)
logger.info("Test 08.1 PASSED: clarify buttons rendered correctly")
# ═══════════════════════════════════════════════════════════════════════════
# Test 2: Button-Klick via CLARIFY-Payload
# ═══════════════════════════════════════════════════════════════════════════
@pytest.mark.live_rc
def test_clarify_button_click(
rc_client,
test_room_id: str,
bot_username: str,
bot_user_id: str,
cursor: str,
posted_message_ids: list,
rate_limiter,
cleanup_messages,
bot_status_check,
):
"""Verifiziere: CLARIFY-Payload als Textnachricht wird als Button-Klick verarbeitet.
Steps:
1. Löse eine Clarify aus (mehrdeutige Nachricht)
2. Extrahiere clarify_id aus den Button-Attachments
3. Sende CLARIFY:<clarify_id>::1 als Textnachricht (Button-Klick-Simulation)
4. Warte auf Bot-Antwort (verarbeitet die Clarify-Auflösung)
5. Verifiziere: Bot antwortet mit der gewählten Option (kein pending_questions-Leak)
"""
# Step 1: Trigger clarify
# Genuinely ambiguous: model lacks context to decide between two valid
# directions — must use clarify tool to ask which the user prefers.
trigger_text = (
"Wir muessen uns zwischen zwei wichtigen Richtungen entscheiden. "
"Sollen wir den Fokus auf kurzfristige Ergebnisse oder auf "
"langfristige Architekturverbesserungen legen?"
)
msg_id, _ = post_test_message(
rc_client, test_room_id, trigger_text,
posted_message_ids, rate_limiter,
)
logger.info(
"Test 08.2: posted clarify trigger '%s' → msg %s",
trigger_text[:60], msg_id[:12],
)
# Step 2: Wait for clarify response
try:
clarify_msg = wait_for_bot_message(
client=rc_client,
room_id=test_room_id,
bot_username=bot_username,
cursor=cursor,
timeout=120.0,
rate_limiter=rate_limiter,
initial_interval=3.0,
)
except RateLimitSkip as e:
pytest.skip(f"Rate limit triggered: {e}")
except PollTimeout as e:
pytest.fail(
f"Bot did not send clarify buttons within 120s. Error: {e}"
)
clarify_msg_id = clarify_msg.get("_id", "")
if clarify_msg_id:
posted_message_ids.append(clarify_msg_id)
# Extract clarify_id from the first choice button
clarify_id = _extract_clarify_id(clarify_msg)
assert clarify_id, (
f"Could not extract clarify_id from bot response. "
f"Attachments: {clarify_msg.get('attachments', [])}"
)
logger.info("Test 08.2: extracted clarify_id=%s", clarify_id)
# Get the text of the first choice for later verification
clarify_text = clarify_msg.get("msg", "")
# Extract first option text from the message body (format: "1. Option text")
first_option = ""
for line in clarify_text.split("\n"):
line = line.strip()
if line.startswith("1. "):
first_option = line[3:].strip()
break
logger.info("Test 08.2: first option text='%s'", first_option[:80])
# Step 3: Send CLARIFY payload as button-click simulation
# Format: CLARIFY:<clarify_id>::<choice_idx> (1-basiert, adapter.py:7638)
button_payload = f"CLARIFY:{clarify_id}::1"
button_msg_id, button_cursor = post_test_message(
rc_client, test_room_id, button_payload,
posted_message_ids, rate_limiter,
)
logger.info(
"Test 08.2: posted CLARIFY payload '%s' → msg %s",
button_payload, button_msg_id[:12],
)
# Step 4: Wait for bot's response to the clarify answer
try:
response = wait_for_bot_message(
client=rc_client,
room_id=test_room_id,
bot_username=bot_username,
cursor=button_cursor,
timeout=120.0,
rate_limiter=rate_limiter,
initial_interval=3.0,
)
except RateLimitSkip as e:
pytest.skip(f"Rate limit triggered: {e}")
except PollTimeout as e:
pytest.fail(
f"Bot did not respond to CLARIFY payload within 120s. "
f"Clarify may be stuck in pending_questions. "
f"Payload: '{button_payload}'. Error: {e}"
)
response_id = response.get("_id", "")
if response_id:
posted_message_ids.append(response_id)
# Step 5: Verify bot processed the clarify answer
response_text = response.get("msg", "")
assert response_text, (
f"Bot response to clarify answer has no text. "
f"Full message: {response}"
)
logger.info(
"Test 08.2: bot responded to clarify answer with %d chars: '%s'",
len(response_text), response_text[:200],
)
# Verify message ownership
assert_bot_message(
response,
expected_username=bot_username,
context="test_clarify_button_click",
)
# Verify the response is NOT another clarify (no pending_questions leak)
assert not _has_clarify_buttons(response), (
f"Bot sent another clarify instead of processing the answer. "
f"Possible pending_questions leak (P-045). "
f"Response text: '{response_text[:200]}'"
)
logger.info("Test 08.2 PASSED: clarify button click processed correctly")
# ═══════════════════════════════════════════════════════════════════════════
# Test 3: Clarify-Chunking (max 3 Buttons/Reihe)
# ═══════════════════════════════════════════════════════════════════════════
@pytest.mark.live_rc
def test_clarify_chunking(
rc_client,
test_room_id: str,
bot_username: str,
bot_user_id: str,
cursor: str,
posted_message_ids: list,
rate_limiter,
cleanup_messages,
bot_status_check,
):
"""Verifiziere: Clarify mit 4+ Optionen wird in mehrere Attachment-Blöcke gechunkt.
Chunking-Regel (adapter.py:7658-7679):
- MAX_BUTTONS_PER_ROW = 3
- Bei >3 Buttons: Aufteilung in Attachment-Blöcke à max 3 actions
- Erster Block bekommt den title "Please choose an option:"
Steps:
1. Löse eine Clarify mit 4+ Optionen aus
2. Warte auf Bot-Antwort
3. Verifiziere: Mehrere Attachment-Blöcke (>=2)
4. Verifiziere: Erster Block hat max 3 actions
5. Verifiziere: Zweiter Block enthält die restlichen Buttons
"""
# Step 1: Trigger clarify with request for 4+ options
# P6: Keine keywords_100
# Genuinely ambiguous: model lacks context to decide between multiple
# valid approaches — must use clarify tool to ask which the user prefers.
trigger_text = (
"Wir haben mehrere Moeglichkeiten das Problem anzugehen. "
"Sollen wir es pragmatisch mit einem schnellen Workaround loesen, "
"gruendlich mit einem kompletten Refactoring, "
"oder inkrementell mit einer schrittweisen Migration?"
)
msg_id, _ = post_test_message(
rc_client, test_room_id, trigger_text,
posted_message_ids, rate_limiter,
)
logger.info(
"Test 08.3: posted chunking trigger '%s' → msg %s",
trigger_text[:60], msg_id[:12],
)
# Step 2: Wait for clarify response
try:
response = wait_for_bot_message(
client=rc_client,
room_id=test_room_id,
bot_username=bot_username,
cursor=cursor,
timeout=120.0,
rate_limiter=rate_limiter,
initial_interval=3.0,
)
except RateLimitSkip as e:
pytest.skip(f"Rate limit triggered: {e}")
except PollTimeout as e:
pytest.fail(
f"Bot did not send clarify buttons within 120s. Error: {e}"
)
response_id = response.get("_id", "")
if response_id:
posted_message_ids.append(response_id)
# Step 3: Verify multiple attachment blocks
attachments = response.get("attachments", [])
# Filter to only attachments that contain clarify actions
clarify_attachments = [
att for att in attachments
if any(
(a.get("msg", "") or "").startswith("CLARIFY:")
for a in att.get("actions", [])
)
]
assert len(clarify_attachments) >= 2, (
f"Expected >=2 clarify attachment blocks for 4+ options, "
f"got {len(clarify_attachments)}. "
f"Total attachments: {len(attachments)}. "
f"Clarify text: '{response.get('msg', '')[:200]}'"
)
logger.info(
"Test 08.3: found %d clarify attachment blocks (total attachments: %d)",
len(clarify_attachments), len(attachments),
)
# Step 4: Verify first block has max 3 actions
first_block_actions = clarify_attachments[0].get("actions", [])
assert len(first_block_actions) <= 3, (
f"First attachment block has {len(first_block_actions)} actions, "
f"expected max 3 (Chunking-Regel). Actions: {first_block_actions}"
)
# First block should have exactly 3 (max per row)
assert len(first_block_actions) == 3, (
f"First attachment block has {len(first_block_actions)} actions, "
f"expected exactly 3 (max per row). The chunking may not be working correctly."
)
# Step 5: Verify second block has remaining buttons
second_block_actions = clarify_attachments[1].get("actions", [])
assert len(second_block_actions) > 0, (
f"Second attachment block has 0 actions, expected remaining buttons."
)
# Total clarify actions should be: 4 choices + 1 "Other" = 5
all_actions = _get_clarify_actions(response)
logger.info(
"Test 08.3: total clarify actions=%d (block1=%d, block2=%d)",
len(all_actions), len(first_block_actions), len(second_block_actions),
)
# Verify all actions have action_id (P-051)
for i, action in enumerate(all_actions):
assert action.get("action_id"), (
f"Clarify action {i} in chunked response missing action_id (P-051)"
)
# Verify message ownership
assert_bot_message(
response,
expected_username=bot_username,
context="test_clarify_chunking",
)
logger.info("Test 08.3 PASSED: clarify chunking works correctly")
# ═══════════════════════════════════════════════════════════════════════════
# Test 4: Clarify-Modal-Status (Bot-Status während/nach Clarify)
# ═══════════════════════════════════════════════════════════════════════════
@pytest.mark.live_rc
def test_clarify_modal_status(
rc_client,
test_room_id: str,
bot_username: str,
bot_user_id: str,
cursor: str,
posted_message_ids: list,
rate_limiter,
cleanup_messages,
bot_status_check,
):
"""Verifiziere: Bot-Status wechselt während Clarify auf busy/offline und zurück.
P-049: Clarify-Modal setzt Bot-Status via Presence-Engine auf busy/offline
(Modal-Override im Mediator Schicht 2). Nach Auflösung kehrt Status zurück.
Steps:
1. Löse eine Clarify aus
2. Prüfe via REST users.info: Bot-Status ist busy oder offline (nicht online)
3. Verifiziere: Status-Text enthält 'wartet auf Antwort' oder ähnlich
4. Löse Clarify auf (Button-Klick)
5. Warte auf Bot-Antwort
6. Verifiziere: Status kehrt zurück auf normal (online)
"""
# Step 1: Trigger clarify
# Genuinely ambiguous: model lacks context to decide between two valid
# directions — must use clarify tool to ask which the user prefers.
trigger_text = (
"Wir muessen uns zwischen zwei wichtigen Richtungen entscheiden. "
"Sollen wir den Fokus auf kurzfristige Ergebnisse oder auf "
"langfristige Architekturverbesserungen legen?"
)
msg_id, _ = post_test_message(
rc_client, test_room_id, trigger_text,
posted_message_ids, rate_limiter,
)
logger.info(
"Test 08.4: posted clarify trigger '%s' → msg %s",
trigger_text[:60], msg_id[:12],
)
# Step 2: Wait for clarify response
try:
clarify_msg = wait_for_bot_message(
client=rc_client,
room_id=test_room_id,
bot_username=bot_username,
cursor=cursor,
timeout=120.0,
rate_limiter=rate_limiter,
initial_interval=3.0,
)
except RateLimitSkip as e:
pytest.skip(f"Rate limit triggered: {e}")
except PollTimeout as e:
pytest.fail(
f"Bot did not send clarify buttons within 120s. Error: {e}"
)
clarify_msg_id = clarify_msg.get("_id", "")
if clarify_msg_id:
posted_message_ids.append(clarify_msg_id)
# Extract clarify_id for later resolution
clarify_id = _extract_clarify_id(clarify_msg)
assert clarify_id, (
f"Could not extract clarify_id from bot response. "
f"Attachments: {clarify_msg.get('attachments', [])}"
)
logger.info("Test 08.4: extracted clarify_id=%s", clarify_id)
# Small delay to let the Presence-Engine update the status
# P-049: Modal-Puls toggled alle 1.5s, warte 3s für sichere Erfassung
time.sleep(3.0)
# Step 3: Check bot status during clarify
try:
user_info = rc_client.get_user_info(bot_username)
except Exception as e:
pytest.fail(
f"Failed to get bot user info via REST API: {e}"
)
status = (user_info.get("status") or "").lower()
status_text = (user_info.get("statusText") or "").lower()
logger.info(
"Test 08.4: bot status during clarify: status='%s', statusText='%s'",
status, user_info.get("statusText", ""),
)
# Verify status is NOT online (should be busy or offline during clarify)
assert status != "online", (
f"Bot status is 'online' during active clarify — "
f"Modal-Override (P-049) may not be active. "
f"status='{status}', statusText='{user_info.get('statusText', '')}'"
)
# Verify statusText indicates waiting for answer
# P-049: Modal setzt Custom-Message mit "wartet auf Antwort"-Text
waiting_indicators = ["wartet", "rückfrage", "clarify", "modal", "antwort"]
has_waiting_indicator = any(ind in status_text for ind in waiting_indicators)
if not has_waiting_indicator:
# Not a hard failure — statusText might use different wording
logger.warning(
"Test 08.4: statusText='%s' does not contain expected waiting indicators %s. "
"This may be a localization difference.",
user_info.get("statusText", ""), waiting_indicators,
)
# Step 4: Resolve clarify via button-click simulation
button_payload = f"CLARIFY:{clarify_id}::1"
button_msg_id, button_cursor = post_test_message(
rc_client, test_room_id, button_payload,
posted_message_ids, rate_limiter,
)
logger.info(
"Test 08.4: posted CLARIFY resolution '%s' → msg %s",
button_payload, button_msg_id[:12],
)
# Step 5: Wait for bot's response to the clarify answer
try:
response = wait_for_bot_message(
client=rc_client,
room_id=test_room_id,
bot_username=bot_username,
cursor=button_cursor,
timeout=120.0,
rate_limiter=rate_limiter,
initial_interval=3.0,
)
except RateLimitSkip as e:
pytest.skip(f"Rate limit triggered: {e}")
except PollTimeout as e:
pytest.fail(
f"Bot did not respond to CLARIFY resolution within 120s. Error: {e}"
)
response_id = response.get("_id", "")
if response_id:
posted_message_ids.append(response_id)
logger.info(
"Test 08.4: bot responded to clarify resolution: '%s'",
response.get("msg", "")[:200],
)
# Small delay for Presence-Engine to update status back to normal
time.sleep(3.0)
# Step 6: Verify status returns to normal
try:
user_info_after = rc_client.get_user_info(bot_username)
except Exception as e:
pytest.fail(
f"Failed to get bot user info after clarify resolution: {e}"
)
status_after = (user_info_after.get("status") or "").lower()
status_text_after = (user_info_after.get("statusText") or "").lower()
logger.info(
"Test 08.4: bot status after clarify: status='%s', statusText='%s'",
status_after, user_info_after.get("statusText", ""),
)
# Verify status is back to a normal state (online, away, or busy are all valid)
assert status_after in ("online", "away", "busy"), (
f"Bot status after clarify resolution is '{status_after}', "
f"expected 'online', 'away', or 'busy'. "
f"statusText='{user_info_after.get('statusText', '')}'"
)
# Verify the waiting indicator is gone
waiting_indicators = ["wartet", "rückfrage", "clarify", "modal"]
still_waiting = any(ind in status_text_after for ind in waiting_indicators)
assert not still_waiting, (
f"Bot statusText still contains waiting indicator after clarify resolution: "
f"'{user_info_after.get('statusText', '')}'. "
f"Modal may not have been cleared (P-049 clear_clarify_modal)."
)
# Verify message ownership
assert_bot_message(
clarify_msg,
expected_username=bot_username,
context="test_clarify_modal_status_clarify",
)
assert_bot_message(
response,
expected_username=bot_username,
context="test_clarify_modal_status_response",
)
logger.info("Test 08.4 PASSED: clarify modal status transitions correctly")