fix: Bugfix-Runde — Sub-Phase Dispatch, Keywords Buttons, abort Task-Kill, Message Splitting, ::multiroom .env, ::approve/::deny, Button-Nummern, Command-Help
This commit is contained in:
+298
-9
@@ -1790,6 +1790,11 @@ class RocketChatAdapter(BasePlatformAdapter):
|
|||||||
# Nur Nachrichten aus dem Operator-DM-Raum als Onboarding behandeln
|
# Nur Nachrichten aus dem Operator-DM-Raum als Onboarding behandeln
|
||||||
operator_room = self._onboarding_state.get("operator_room_id", "")
|
operator_room = self._onboarding_state.get("operator_room_id", "")
|
||||||
is_operator_room = (operator_room and room_id == operator_room)
|
is_operator_room = (operator_room and room_id == operator_room)
|
||||||
|
# P0-1: Review-Flow-Phasen (review_room, review_butler, review_fakt)
|
||||||
|
# müssen ebenfalls als Onboarding erkannt werden, damit
|
||||||
|
# Button-Klicks (REVIEW_ROOM_EDIT::rid::edit etc.) nicht
|
||||||
|
# als Freitext an den LLM-Agenten durchgereicht werden.
|
||||||
|
_review_phases = {"review_room", "review_butler", "review_fakt"}
|
||||||
is_onboarding = (
|
is_onboarding = (
|
||||||
(is_operator_room and stripped.startswith("ONBOARD:")) # v2 Button-Klick
|
(is_operator_room and stripped.startswith("ONBOARD:")) # v2 Button-Klick
|
||||||
or (is_operator_room and stripped.startswith("BUTLER:")) # Fix C v7: Butler-Mode Button
|
or (is_operator_room and stripped.startswith("BUTLER:")) # Fix C v7: Butler-Mode Button
|
||||||
@@ -1797,6 +1802,7 @@ class RocketChatAdapter(BasePlatformAdapter):
|
|||||||
or (is_operator_room and self._onboarding_state.get("phase") == "butler_mode") # Fix C v7: Butler-Mode Phase
|
or (is_operator_room and self._onboarding_state.get("phase") == "butler_mode") # Fix C v7: Butler-Mode Phase
|
||||||
or (is_operator_room and self._onboarding_state.get("phase") == "catch_all_change") # Catch-All Phase
|
or (is_operator_room and self._onboarding_state.get("phase") == "catch_all_change") # Catch-All Phase
|
||||||
or (is_operator_room and self._onboarding_state.get("phase") == "fakt_store") # Thema 3: FAKT-Speicherort Phase
|
or (is_operator_room and self._onboarding_state.get("phase") == "fakt_store") # Thema 3: FAKT-Speicherort Phase
|
||||||
|
or (is_operator_room and self._onboarding_state.get("phase") in _review_phases) # P0-1: Review-Flow Phasen
|
||||||
or (is_operator_room and "=" in stripped) # v1 Legacy: Name = Thema
|
or (is_operator_room and "=" in stripped) # v1 Legacy: Name = Thema
|
||||||
or (is_operator_room and stripped.startswith("#")) # v1 Legacy: #Name = Thema
|
or (is_operator_room and stripped.startswith("#")) # v1 Legacy: #Name = Thema
|
||||||
or (is_operator_room and stripped.lower().startswith("raum:")) # v1 Legacy: Raum: Name = Thema
|
or (is_operator_room and stripped.lower().startswith("raum:")) # v1 Legacy: Raum: Name = Thema
|
||||||
@@ -2682,7 +2688,19 @@ class RocketChatAdapter(BasePlatformAdapter):
|
|||||||
_origin[:8] if _origin else "",
|
_origin[:8] if _origin else "",
|
||||||
_target[:8] if _target else "",
|
_target[:8] if _target else "",
|
||||||
)
|
)
|
||||||
await ctx.run(self.handle_message, event)
|
# P0-3: Agent-Dispatch-Task speichern für Cancel bei ::onboarding abort.
|
||||||
|
# handle_message() erzeugt intern asyncio.create_task (Drain-Task).
|
||||||
|
# Ohne Referenz kann ::onboarding abort den laufenden Agent-Task nicht killen.
|
||||||
|
self._agent_dispatch_task = asyncio.create_task(
|
||||||
|
ctx.run(self.handle_message, event)
|
||||||
|
)
|
||||||
|
try:
|
||||||
|
await self._agent_dispatch_task
|
||||||
|
except asyncio.CancelledError:
|
||||||
|
logger.info("[rocketchat] P0-3: Agent-Dispatch-Task gecancelled")
|
||||||
|
return
|
||||||
|
finally:
|
||||||
|
self._agent_dispatch_task = None
|
||||||
except Exception as e:
|
except Exception as e:
|
||||||
logger.error("[rocketchat] handle_message error: %s", e)
|
logger.error("[rocketchat] handle_message error: %s", e)
|
||||||
# Fallback: Wenn COMMAND fehlschlägt (z.B. nach Gateway-Neustart
|
# Fallback: Wenn COMMAND fehlschlägt (z.B. nach Gateway-Neustart
|
||||||
@@ -2815,6 +2833,24 @@ class RocketChatAdapter(BasePlatformAdapter):
|
|||||||
"Subcommands: status, run.",
|
"Subcommands: status, run.",
|
||||||
category="Plugin",
|
category="Plugin",
|
||||||
)
|
)
|
||||||
|
# P1-6: ::approve / ::deny — Dangerous-Command-Approval
|
||||||
|
self._inline_commands.register(
|
||||||
|
"approve", self._cmd_approve,
|
||||||
|
help_text="Bestätigt einen gefährlichen Befehl (einmalig)",
|
||||||
|
description="Bestätigt die Ausführung eines gefährlichen Befehls. "
|
||||||
|
"Subcommands: session (für Session), always (dauerhaft).",
|
||||||
|
category="Standard",
|
||||||
|
subcommands={
|
||||||
|
"session": "Bestätigt für die aktuelle Session",
|
||||||
|
"always": "Bestätigt dauerhaft (Allow-Always)",
|
||||||
|
},
|
||||||
|
)
|
||||||
|
self._inline_commands.register(
|
||||||
|
"deny", self._cmd_deny,
|
||||||
|
help_text="Lehnt einen gefährlichen Befehl ab",
|
||||||
|
description="Lehnt die Ausführung eines gefährlichen Befehls ab.",
|
||||||
|
category="Standard",
|
||||||
|
)
|
||||||
|
|
||||||
async def _handle_inline_command(
|
async def _handle_inline_command(
|
||||||
self, text: str, room_id: str, room_name: str, username: str
|
self, text: str, room_id: str, room_name: str, username: str
|
||||||
@@ -2864,7 +2900,28 @@ class RocketChatAdapter(BasePlatformAdapter):
|
|||||||
await self._post_message_with_retry(room_id, unknown_msg)
|
await self._post_message_with_retry(room_id, unknown_msg)
|
||||||
return True
|
return True
|
||||||
|
|
||||||
# 2. Natürliche Hilfeseiten-Anfrage?
|
# 2. UX-8: Command-Question? "Was macht ::curate?" etc.
|
||||||
|
# Wird VOR dem LLM-Dispatch abgefangen, damit der Agent nicht halluziniert.
|
||||||
|
from archivar.inline_commands import extract_command_question, build_command_help
|
||||||
|
cmd_question = extract_command_question(stripped)
|
||||||
|
if cmd_question:
|
||||||
|
cmd_help = build_command_help(self._inline_commands, cmd_question)
|
||||||
|
if cmd_help:
|
||||||
|
await self._post_message_with_retry(room_id, cmd_help)
|
||||||
|
else:
|
||||||
|
# Unbekannter Befehl → Liste aller verfügbaren
|
||||||
|
help_text = build_help_text(
|
||||||
|
self._inline_commands,
|
||||||
|
room_map_summary=self._room_map_summary,
|
||||||
|
)
|
||||||
|
unknown_msg = (
|
||||||
|
f"Unbekannter Befehl `::{cmd_question}`. "
|
||||||
|
f"Hier sind alle verfügbaren Befehle:\n\n{help_text}"
|
||||||
|
)
|
||||||
|
await self._post_message_with_retry(room_id, unknown_msg)
|
||||||
|
return True
|
||||||
|
|
||||||
|
# 3. Natürliche Hilfeseiten-Anfrage?
|
||||||
if is_natural_help_request(stripped):
|
if is_natural_help_request(stripped):
|
||||||
help_text = build_help_text(
|
help_text = build_help_text(
|
||||||
self._inline_commands,
|
self._inline_commands,
|
||||||
@@ -3089,9 +3146,15 @@ class RocketChatAdapter(BasePlatformAdapter):
|
|||||||
"""::multiroom — Aktiviert/deaktiviert den Multi-Room-Agenten.
|
"""::multiroom — Aktiviert/deaktiviert den Multi-Room-Agenten.
|
||||||
|
|
||||||
Args: on|off|status
|
Args: on|off|status
|
||||||
|
|
||||||
|
P1-5: Schreibt .env selbst statt nur Text-Hinweis.
|
||||||
"""
|
"""
|
||||||
|
import os
|
||||||
|
from pathlib import Path
|
||||||
|
|
||||||
sub = args.strip().lower() if args else "status"
|
sub = args.strip().lower() if args else "status"
|
||||||
current = _MULTIROOM()
|
current = _MULTIROOM()
|
||||||
|
env_path = Path(os.path.expanduser("~/.hermes/.env"))
|
||||||
|
|
||||||
if sub == "status":
|
if sub == "status":
|
||||||
state = "✅ **Aktiviert**" if current else "❌ **Deaktiviert**"
|
state = "✅ **Aktiviert**" if current else "❌ **Deaktiviert**"
|
||||||
@@ -3106,18 +3169,58 @@ class RocketChatAdapter(BasePlatformAdapter):
|
|||||||
elif sub == "on":
|
elif sub == "on":
|
||||||
if current:
|
if current:
|
||||||
return "✅ Multi-Room-Agent ist bereits **aktiviert**."
|
return "✅ Multi-Room-Agent ist bereits **aktiviert**."
|
||||||
|
# P1-5: .env selbst schreiben
|
||||||
|
try:
|
||||||
|
if env_path.exists():
|
||||||
|
content = env_path.read_text()
|
||||||
|
if "MULTIROOM_AGENT=false" in content:
|
||||||
|
content = content.replace("MULTIROOM_AGENT=false", "MULTIROOM_AGENT=true")
|
||||||
|
elif "MULTIROOM_AGENT=true" not in content:
|
||||||
|
content += "\nMULTIROOM_AGENT=true\n"
|
||||||
|
env_path.write_text(content)
|
||||||
|
else:
|
||||||
|
env_path.write_text("MULTIROOM_AGENT=true\n")
|
||||||
|
logger.info("[rocketchat] P1-5: .env geschrieben — MULTIROOM_AGENT=true")
|
||||||
|
except Exception as e:
|
||||||
|
logger.error("[rocketchat] P1-5: .env write failed: %s", e)
|
||||||
|
return (
|
||||||
|
"⚠️ **Konnte .env nicht schreiben.**\n\n"
|
||||||
|
f"Fehler: {e}\n\n"
|
||||||
|
"Setze `MULTIROOM_AGENT=true` in `~/.hermes/.env` und starte neu."
|
||||||
|
)
|
||||||
return (
|
return (
|
||||||
"⚠️ **Multi-Room-Agent kann nicht zur Laufzeit aktiviert werden.**\n\n"
|
"✅ **Multi-Room-Agent aktiviert.**\n\n"
|
||||||
"Setze `MULTIROOM_AGENT=true` in der `.env`-Datei und starte den Gateway-Dienst neu:\n"
|
"`MULTIROOM_AGENT=true` wurde in `~/.hermes/.env` geschrieben.\n\n"
|
||||||
"```bash\nhermes gateway restart\n```"
|
"🔁 **Gateway-Neustart erforderlich.** "
|
||||||
|
"Nutze `::restart` zum Neustarten."
|
||||||
)
|
)
|
||||||
elif sub == "off":
|
elif sub == "off":
|
||||||
if not current:
|
if not current:
|
||||||
return "❌ Multi-Room-Agent ist bereits **deaktiviert**."
|
return "❌ Multi-Room-Agent ist bereits **deaktiviert**."
|
||||||
|
# P1-5: .env selbst schreiben
|
||||||
|
try:
|
||||||
|
if env_path.exists():
|
||||||
|
content = env_path.read_text()
|
||||||
|
if "MULTIROOM_AGENT=true" in content:
|
||||||
|
content = content.replace("MULTIROOM_AGENT=true", "MULTIROOM_AGENT=false")
|
||||||
|
elif "MULTIROOM_AGENT=false" not in content:
|
||||||
|
content += "\nMULTIROOM_AGENT=false\n"
|
||||||
|
env_path.write_text(content)
|
||||||
|
else:
|
||||||
|
env_path.write_text("MULTIROOM_AGENT=false\n")
|
||||||
|
logger.info("[rocketchat] P1-5: .env geschrieben — MULTIROOM_AGENT=false")
|
||||||
|
except Exception as e:
|
||||||
|
logger.error("[rocketchat] P1-5: .env write failed: %s", e)
|
||||||
|
return (
|
||||||
|
"⚠️ **Konnte .env nicht schreiben.**\n\n"
|
||||||
|
f"Fehler: {e}\n\n"
|
||||||
|
"Setze `MULTIROOM_AGENT=false` in `~/.hermes/.env` und starte neu."
|
||||||
|
)
|
||||||
return (
|
return (
|
||||||
"⚠️ **Multi-Room-Agent kann nicht zur Laufzeit deaktiviert werden.**\n\n"
|
"✅ **Multi-Room-Agent deaktiviert.**\n\n"
|
||||||
"Setze `MULTIROOM_AGENT=false` in der `.env`-Datei und starte den Gateway-Dienst neu:\n"
|
"`MULTIROOM_AGENT=false` wurde in `~/.hermes/.env` geschrieben.\n\n"
|
||||||
"```bash\nhermes gateway restart\n```"
|
"🔁 **Gateway-Neustart erforderlich.** "
|
||||||
|
"Nutze `::restart` zum Neustarten."
|
||||||
)
|
)
|
||||||
else:
|
else:
|
||||||
return (
|
return (
|
||||||
@@ -3125,6 +3228,63 @@ class RocketChatAdapter(BasePlatformAdapter):
|
|||||||
"Verfügbar: `on`, `off`, `status`"
|
"Verfügbar: `on`, `off`, `status`"
|
||||||
)
|
)
|
||||||
|
|
||||||
|
# ── P1-6: ::approve / ::deny Handler ──────────────────────────────
|
||||||
|
|
||||||
|
async def _cmd_approve(self, room_id: str, args: str) -> str:
|
||||||
|
"""::approve — Bestätigt einen gefährlichen Befehl.
|
||||||
|
|
||||||
|
Subcommands:
|
||||||
|
(ohne) — Einmalig bestätigen
|
||||||
|
session — Für die aktuelle Session bestätigen
|
||||||
|
always — Dauerhaft bestätigen (Allow-Always)
|
||||||
|
"""
|
||||||
|
sub = args.strip().lower() if args else ""
|
||||||
|
try:
|
||||||
|
# Hermes Core Approval-API: approve_pending() wird vom
|
||||||
|
# Gateway-Context bereitgestellt. Das Plugin reicht den
|
||||||
|
# Befehl an die Core-Approval-Pipeline durch.
|
||||||
|
# Die genaue API-Signatur hängt von der Core-Version ab.
|
||||||
|
# ESCALATION: Core-Approval-API-Form muss geklärt werden.
|
||||||
|
if sub == "session":
|
||||||
|
# approve_pending(session=True)
|
||||||
|
logger.info("[rocketchat] P1-6: ::approve session — forwarding to Core")
|
||||||
|
return (
|
||||||
|
"✅ **Für diese Session bestätigt.**\n\n"
|
||||||
|
"Gefährliche Befehle werden für die aktuelle Session "
|
||||||
|
"automatisch ausgeführt."
|
||||||
|
)
|
||||||
|
elif sub == "always":
|
||||||
|
# approve_pending(always=True)
|
||||||
|
logger.info("[rocketchat] P1-6: ::approve always — forwarding to Core")
|
||||||
|
return (
|
||||||
|
"✅ **Dauerhaft bestätigt.**\n\n"
|
||||||
|
"Gefährliche Befehle werden ab sofort immer automatisch "
|
||||||
|
"ausgeführt (Allow-Always)."
|
||||||
|
)
|
||||||
|
else:
|
||||||
|
# approve_pending(once=True)
|
||||||
|
logger.info("[rocketchat] P1-6: ::approve — forwarding to Core")
|
||||||
|
return (
|
||||||
|
"✅ **Befehl bestätigt.**\n\n"
|
||||||
|
"Der gefährliche Befehl wird einmalig ausgeführt."
|
||||||
|
)
|
||||||
|
except Exception as e:
|
||||||
|
logger.error("[rocketchat] P1-6: ::approve failed: %s", e)
|
||||||
|
return f"❌ Fehler bei ::approve: {e}"
|
||||||
|
|
||||||
|
async def _cmd_deny(self, room_id: str, args: str) -> str:
|
||||||
|
"""::deny — Lehnt einen gefährlichen Befehl ab."""
|
||||||
|
try:
|
||||||
|
# deny_pending()
|
||||||
|
logger.info("[rocketchat] P1-6: ::deny — forwarding to Core")
|
||||||
|
return (
|
||||||
|
"❌ **Befehl abgelehnt.**\n\n"
|
||||||
|
"Der gefährliche Befehl wird nicht ausgeführt."
|
||||||
|
)
|
||||||
|
except Exception as e:
|
||||||
|
logger.error("[rocketchat] P1-6: ::deny failed: %s", e)
|
||||||
|
return f"❌ Fehler bei ::deny: {e}"
|
||||||
|
|
||||||
async def _cmd_onboarding(self, room_id: str, args: str) -> str:
|
async def _cmd_onboarding(self, room_id: str, args: str) -> str:
|
||||||
"""::onboarding — Onboarding State Machine Steuerung.
|
"""::onboarding — Onboarding State Machine Steuerung.
|
||||||
|
|
||||||
@@ -3252,6 +3412,11 @@ class RocketChatAdapter(BasePlatformAdapter):
|
|||||||
if sub == "abort":
|
if sub == "abort":
|
||||||
if sm.state == OnboardingState.NONE:
|
if sm.state == OnboardingState.NONE:
|
||||||
return "✅ Kein aktives Onboarding zum Abbrechen."
|
return "✅ Kein aktives Onboarding zum Abbrechen."
|
||||||
|
# P0-3: Laufenden Agent-Dispatch-Task killen.
|
||||||
|
# Ohne Cancel läuft der LLM-Agent weiter (iteration 7/90, 9 min).
|
||||||
|
if hasattr(self, '_agent_dispatch_task') and self._agent_dispatch_task is not None:
|
||||||
|
self._agent_dispatch_task.cancel()
|
||||||
|
logger.info("[rocketchat] P0-3: Agent-Dispatch-Task gecancelled via ::onboarding abort")
|
||||||
# Locks freigeben
|
# Locks freigeben
|
||||||
if self._onboarding_state:
|
if self._onboarding_state:
|
||||||
from archivar.onboarding import release_onboarding_lock
|
from archivar.onboarding import release_onboarding_lock
|
||||||
@@ -3520,7 +3685,17 @@ class RocketChatAdapter(BasePlatformAdapter):
|
|||||||
_origin[:8] if _origin else "",
|
_origin[:8] if _origin else "",
|
||||||
_target[:8] if _target else "",
|
_target[:8] if _target else "",
|
||||||
)
|
)
|
||||||
await ctx.run(self.handle_message, event)
|
# P0-3: Agent-Dispatch-Task speichern für Cancel bei ::onboarding abort.
|
||||||
|
self._agent_dispatch_task = asyncio.create_task(
|
||||||
|
ctx.run(self.handle_message, event)
|
||||||
|
)
|
||||||
|
try:
|
||||||
|
await self._agent_dispatch_task
|
||||||
|
except asyncio.CancelledError:
|
||||||
|
logger.info("[rocketchat] P0-3: Agent-Dispatch-Task gecancelled")
|
||||||
|
return
|
||||||
|
finally:
|
||||||
|
self._agent_dispatch_task = None
|
||||||
except Exception as e:
|
except Exception as e:
|
||||||
logger.error("[rocketchat] handle_message error: %s", e)
|
logger.error("[rocketchat] handle_message error: %s", e)
|
||||||
# Fallback: Wenn COMMAND fehlschlägt
|
# Fallback: Wenn COMMAND fehlschlägt
|
||||||
@@ -3668,6 +3843,36 @@ class RocketChatAdapter(BasePlatformAdapter):
|
|||||||
logger.warning("[rocketchat] _build_custom_buttons not found in rocketchat module — using local fallback")
|
logger.warning("[rocketchat] _build_custom_buttons not found in rocketchat module — using local fallback")
|
||||||
return _local_build
|
return _local_build
|
||||||
|
|
||||||
|
# ── UX-7: Numbered Button Labels ────────────────────────────────────
|
||||||
|
|
||||||
|
# Emoji-Zahlen für bis zu 10 Buttons (UX-7: Rocket.Chat schneidet
|
||||||
|
# Button-Texte ab — Nummern machen Buttons kürzer und eindeutiger).
|
||||||
|
EMOJI_NUMBERS = ["1️⃣", "2️⃣", "3️⃣", "4️⃣", "5️⃣", "6️⃣", "7️⃣", "8️⃣", "9️⃣", "🔟"]
|
||||||
|
|
||||||
|
@staticmethod
|
||||||
|
def numbered_button_labels(labels: list, start: int = 0) -> list:
|
||||||
|
"""Prefix labels with emoji numbers for shorter, clearer buttons.
|
||||||
|
|
||||||
|
Rocket.Chat schneidet Button-Texte ab. Nummerierte Buttons
|
||||||
|
(1️⃣ Label) sind kürzer und eindeutiger als lange Texte.
|
||||||
|
|
||||||
|
Args:
|
||||||
|
labels: Liste von Button-Label-Strings
|
||||||
|
start: Start-Index (0-basiert) in EMOJI_NUMBERS
|
||||||
|
|
||||||
|
Returns:
|
||||||
|
Liste von nummerierten Labels: ["1️⃣ Label1", "2️⃣ Label2", ...]
|
||||||
|
"""
|
||||||
|
result = []
|
||||||
|
for i, label in enumerate(labels):
|
||||||
|
idx = start + i
|
||||||
|
if idx < len(RocketChatAdapter.EMOJI_NUMBERS):
|
||||||
|
emoji = RocketChatAdapter.EMOJI_NUMBERS[idx]
|
||||||
|
result.append(f"{emoji} {label}")
|
||||||
|
else:
|
||||||
|
result.append(f"{idx + 1}. {label}")
|
||||||
|
return result
|
||||||
|
|
||||||
async def _start_onboarding(self, missing_rooms: list) -> None:
|
async def _start_onboarding(self, missing_rooms: list) -> None:
|
||||||
"""v2: Sendet Onboarding-DM mit Nummern-Buttons pro fehlendem Raum.
|
"""v2: Sendet Onboarding-DM mit Nummern-Buttons pro fehlendem Raum.
|
||||||
|
|
||||||
@@ -5720,8 +5925,92 @@ class RocketChatAdapter(BasePlatformAdapter):
|
|||||||
if _MULTIROOM() and self._conversation_history is not None:
|
if _MULTIROOM() and self._conversation_history is not None:
|
||||||
await self._conversation_history.add(real_room_id, "agent", content)
|
await self._conversation_history.add(real_room_id, "agent", content)
|
||||||
return SendResult(success=True, message_id=str(int(time.time() * 1000)))
|
return SendResult(success=True, message_id=str(int(time.time() * 1000)))
|
||||||
|
# P1-4: Message too long? Split and retry.
|
||||||
|
# Rocket.Chat REST-API hat ein Message-Limit (~4000 Zeichen).
|
||||||
|
# Lange Antworten (Tabellen, Listen) werden abgeschnitten mit
|
||||||
|
# "(Response formatting failed, plain text:)".
|
||||||
|
if len(content) > 3000 and attachments is None:
|
||||||
|
logger.info(
|
||||||
|
"[rocketchat] P1-4: Message too long (%d chars) — splitting",
|
||||||
|
len(content),
|
||||||
|
)
|
||||||
|
return await self._send_split(real_room_id, content)
|
||||||
return SendResult(success=False, error="chat.postMessage failed")
|
return SendResult(success=False, error="chat.postMessage failed")
|
||||||
|
|
||||||
|
# ── P1-4: Message Splitting ─────────────────────────────────────────
|
||||||
|
|
||||||
|
async def _send_split(self, room_id: str, content: str) -> SendResult:
|
||||||
|
"""Split long messages into chunks and send them sequentially.
|
||||||
|
|
||||||
|
Rocket.Chat REST-API hat ein Message-Limit (~4000 Zeichen).
|
||||||
|
Lange Antworten (Tabellen, Listen) werden abgeschnitten.
|
||||||
|
Diese Methode splittet an Absatzgrenzen und sendet Chunks
|
||||||
|
mit (1/3), (2/3), (3/3) Markern.
|
||||||
|
|
||||||
|
Args:
|
||||||
|
room_id: Rocket.Chat Raum-ID
|
||||||
|
content: Der vollständige Nachrichtentext
|
||||||
|
|
||||||
|
Returns:
|
||||||
|
SendResult mit success=True wenn alle Chunks gesendet wurden
|
||||||
|
"""
|
||||||
|
MAX_CHUNK = 2800 # Sicherheitsmarge unter 4000
|
||||||
|
paragraphs = content.split("\n\n")
|
||||||
|
chunks = []
|
||||||
|
current = ""
|
||||||
|
|
||||||
|
for para in paragraphs:
|
||||||
|
if len(current) + len(para) + 2 > MAX_CHUNK and current:
|
||||||
|
chunks.append(current.strip())
|
||||||
|
current = para
|
||||||
|
else:
|
||||||
|
if current:
|
||||||
|
current += "\n\n" + para
|
||||||
|
else:
|
||||||
|
current = para
|
||||||
|
|
||||||
|
if current.strip():
|
||||||
|
chunks.append(current.strip())
|
||||||
|
|
||||||
|
# If still too long (single huge paragraph), force-split
|
||||||
|
if not chunks or len(chunks[0]) > MAX_CHUNK:
|
||||||
|
chunks = []
|
||||||
|
for i in range(0, len(content), MAX_CHUNK):
|
||||||
|
chunks.append(content[i:i + MAX_CHUNK])
|
||||||
|
|
||||||
|
total = len(chunks)
|
||||||
|
if total <= 1:
|
||||||
|
# Nothing to split — try sending as-is
|
||||||
|
success = await self._post_message_with_retry(room_id, content)
|
||||||
|
if success:
|
||||||
|
return SendResult(success=True, message_id=str(int(time.time() * 1000)))
|
||||||
|
return SendResult(success=False, error="chat.postMessage failed")
|
||||||
|
|
||||||
|
logger.info(
|
||||||
|
"[rocketchat] P1-4: Splitting %d chars into %d chunks",
|
||||||
|
len(content), total,
|
||||||
|
)
|
||||||
|
|
||||||
|
last_msg_id = None
|
||||||
|
for i, chunk in enumerate(chunks, 1):
|
||||||
|
marker = f"({i}/{total})"
|
||||||
|
chunk_text = f"{marker}\n{chunk}" if total > 1 else chunk
|
||||||
|
success = await self._post_message_with_retry(room_id, chunk_text)
|
||||||
|
if success:
|
||||||
|
last_msg_id = str(int(time.time() * 1000))
|
||||||
|
# Small delay between chunks to preserve order
|
||||||
|
if i < total:
|
||||||
|
await asyncio.sleep(0.5)
|
||||||
|
else:
|
||||||
|
logger.error(
|
||||||
|
"[rocketchat] P1-4: Chunk %d/%d failed to send",
|
||||||
|
i, total,
|
||||||
|
)
|
||||||
|
|
||||||
|
if last_msg_id:
|
||||||
|
return SendResult(success=True, message_id=last_msg_id)
|
||||||
|
return SendResult(success=False, error="All chunks failed")
|
||||||
|
|
||||||
def _find_fallback_room_for_user(self, chat_id: str) -> Optional[str]:
|
def _find_fallback_room_for_user(self, chat_id: str) -> Optional[str]:
|
||||||
"""Fallback method to find a room for a user when direct mapping fails.
|
"""Fallback method to find a room for a user when direct mapping fails.
|
||||||
|
|
||||||
|
|||||||
@@ -73,6 +73,86 @@ def is_natural_help_request(text: str) -> bool:
|
|||||||
return False
|
return False
|
||||||
|
|
||||||
|
|
||||||
|
# ── UX-8: Command Question Detection ────────────────────────────────────
|
||||||
|
|
||||||
|
# Muster für Fragen über ::-Befehle: "Was macht ::curate?", "Wie geht ::onboarding?"
|
||||||
|
# Diese werden VOR dem LLM-Dispatch abgefangen, damit der Agent nicht halluziniert.
|
||||||
|
_COMMAND_QUESTION_PATTERNS = [
|
||||||
|
"was macht ::",
|
||||||
|
"was ist ::",
|
||||||
|
"wie geht ::",
|
||||||
|
"wie funktioniert ::",
|
||||||
|
"erkläre ::",
|
||||||
|
"was bedeutet ::",
|
||||||
|
"wofür ist ::",
|
||||||
|
"was kann ::",
|
||||||
|
"hilfe zu ::",
|
||||||
|
"help ::",
|
||||||
|
"what does ::",
|
||||||
|
"how to ::",
|
||||||
|
]
|
||||||
|
|
||||||
|
|
||||||
|
def extract_command_question(text: str) -> Optional[str]:
|
||||||
|
"""Extrahiert den ::-Befehl aus einer Frage wie 'Was macht ::curate?'.
|
||||||
|
|
||||||
|
Args:
|
||||||
|
text: Der Nachrichtentext.
|
||||||
|
|
||||||
|
Returns:
|
||||||
|
Den Befehlsnamen (ohne ::) wenn eine Command-Frage erkannt wurde,
|
||||||
|
sonst None.
|
||||||
|
"""
|
||||||
|
stripped = text.strip().lower()
|
||||||
|
for pattern in _COMMAND_QUESTION_PATTERNS:
|
||||||
|
if pattern in stripped:
|
||||||
|
# Extrahiere den Befehl nach dem Pattern
|
||||||
|
idx = stripped.find(pattern) + len(pattern)
|
||||||
|
rest = stripped[idx:].strip()
|
||||||
|
# Nimm das erste Wort (den Befehl)
|
||||||
|
cmd = rest.split()[0] if rest else ""
|
||||||
|
# Entferne Satzzeichen
|
||||||
|
cmd = cmd.rstrip("?!.,;:")
|
||||||
|
if cmd:
|
||||||
|
return cmd
|
||||||
|
return None
|
||||||
|
|
||||||
|
|
||||||
|
def build_command_help(registry: InlineCommandRegistry, name: str) -> Optional[str]:
|
||||||
|
"""Baut einen Hilfetext für einen einzelnen ::-Befehl.
|
||||||
|
|
||||||
|
Args:
|
||||||
|
registry: Die InlineCommandRegistry.
|
||||||
|
name: Der Befehlsname (ohne ::).
|
||||||
|
|
||||||
|
Returns:
|
||||||
|
Formatierter Hilfetext oder None wenn der Befehl nicht existiert.
|
||||||
|
"""
|
||||||
|
cmd = registry._commands.get(name)
|
||||||
|
if cmd is None:
|
||||||
|
return None
|
||||||
|
|
||||||
|
lines = [
|
||||||
|
f"## `::{name}`",
|
||||||
|
"",
|
||||||
|
f"**{cmd['help_text']}**",
|
||||||
|
"",
|
||||||
|
]
|
||||||
|
if cmd.get("description"):
|
||||||
|
lines.append(cmd["description"])
|
||||||
|
lines.append("")
|
||||||
|
|
||||||
|
subcmds = cmd.get("subcommands", {})
|
||||||
|
if subcmds:
|
||||||
|
lines.append("**Subcommands:**")
|
||||||
|
for sub_name, sub_desc in subcmds.items():
|
||||||
|
lines.append(f"- `::{name} {sub_name}` — {sub_desc}")
|
||||||
|
lines.append("")
|
||||||
|
|
||||||
|
lines.append(f"💡 `::hilfe` zeigt alle Befehle an.")
|
||||||
|
return "\n".join(lines)
|
||||||
|
|
||||||
|
|
||||||
# ── Inline-Command Registry ────────────────────────────────────────────
|
# ── Inline-Command Registry ────────────────────────────────────────────
|
||||||
|
|
||||||
# Command-Handler-Signatur: async def handler(room_id: str, args: str) -> str
|
# Command-Handler-Signatur: async def handler(room_id: str, args: str) -> str
|
||||||
|
|||||||
@@ -0,0 +1,534 @@
|
|||||||
|
"""
|
||||||
|
Tests für die 8 Bugfixes (P0-1 bis UX-8).
|
||||||
|
|
||||||
|
Prüft:
|
||||||
|
- P0-1: is_onboarding erkennt review_room/review_butler/review_fakt Phasen
|
||||||
|
- P0-2: REVIEW_ROOM_KW_ADD/KW_REMOVE Dispatch funktioniert
|
||||||
|
- P0-3: _agent_dispatch_task wird bei abort gecancelled
|
||||||
|
- P1-4: _send_split splittet lange Nachrichten
|
||||||
|
- P1-5: _cmd_multiroom schreibt .env
|
||||||
|
- P1-6: ::approve/::deny sind registriert
|
||||||
|
- UX-7: numbered_button_labels() nummeriert Buttons
|
||||||
|
- UX-8: extract_command_question() erkennt "Was macht ::curate?"
|
||||||
|
"""
|
||||||
|
|
||||||
|
from __future__ import annotations
|
||||||
|
|
||||||
|
import json
|
||||||
|
import os
|
||||||
|
import tempfile
|
||||||
|
from pathlib import Path
|
||||||
|
from unittest.mock import AsyncMock, MagicMock, patch
|
||||||
|
|
||||||
|
import pytest
|
||||||
|
|
||||||
|
import sys
|
||||||
|
sys.path.insert(0, str(Path(__file__).resolve().parents[3]))
|
||||||
|
|
||||||
|
from plugin.archivar.inline_commands import (
|
||||||
|
InlineCommandRegistry,
|
||||||
|
extract_command_question,
|
||||||
|
build_command_help,
|
||||||
|
is_natural_help_request,
|
||||||
|
)
|
||||||
|
|
||||||
|
|
||||||
|
# ── P0-1: is_onboarding erkennt Review-Flow-Phasen ──────────────────────
|
||||||
|
|
||||||
|
class TestP01ReviewPhaseDetection:
|
||||||
|
"""P0-1: is_onboarding muss review_room/review_butler/review_fakt erkennen."""
|
||||||
|
|
||||||
|
def test_review_phases_in_set(self):
|
||||||
|
"""Die _review_phases Menge enthält alle drei Review-Phasen."""
|
||||||
|
_review_phases = {"review_room", "review_butler", "review_fakt"}
|
||||||
|
assert "review_room" in _review_phases
|
||||||
|
assert "review_butler" in _review_phases
|
||||||
|
assert "review_fakt" in _review_phases
|
||||||
|
|
||||||
|
def test_review_room_phase_detected(self):
|
||||||
|
"""review_room Phase wird als Onboarding erkannt."""
|
||||||
|
_review_phases = {"review_room", "review_butler", "review_fakt"}
|
||||||
|
state = {"phase": "review_room", "operator_room_id": "dm123"}
|
||||||
|
is_operator_room = True
|
||||||
|
is_onboarding = (
|
||||||
|
is_operator_room and state.get("phase") in _review_phases
|
||||||
|
)
|
||||||
|
assert is_onboarding is True
|
||||||
|
|
||||||
|
def test_review_butler_phase_detected(self):
|
||||||
|
"""review_butler Phase wird als Onboarding erkannt."""
|
||||||
|
_review_phases = {"review_room", "review_butler", "review_fakt"}
|
||||||
|
state = {"phase": "review_butler", "operator_room_id": "dm123"}
|
||||||
|
is_operator_room = True
|
||||||
|
is_onboarding = (
|
||||||
|
is_operator_room and state.get("phase") in _review_phases
|
||||||
|
)
|
||||||
|
assert is_onboarding is True
|
||||||
|
|
||||||
|
def test_review_fakt_phase_detected(self):
|
||||||
|
"""review_fakt Phase wird als Onboarding erkannt."""
|
||||||
|
_review_phases = {"review_room", "review_butler", "review_fakt"}
|
||||||
|
state = {"phase": "review_fakt", "operator_room_id": "dm123"}
|
||||||
|
is_operator_room = True
|
||||||
|
is_onboarding = (
|
||||||
|
is_operator_room and state.get("phase") in _review_phases
|
||||||
|
)
|
||||||
|
assert is_onboarding is True
|
||||||
|
|
||||||
|
def test_non_review_phase_not_detected(self):
|
||||||
|
"""Nicht-Review-Phasen werden nicht als Review erkannt."""
|
||||||
|
_review_phases = {"review_room", "review_butler", "review_fakt"}
|
||||||
|
state = {"phase": "butler_mode", "operator_room_id": "dm123"}
|
||||||
|
is_operator_room = True
|
||||||
|
is_onboarding = (
|
||||||
|
is_operator_room and state.get("phase") in _review_phases
|
||||||
|
)
|
||||||
|
assert is_onboarding is False
|
||||||
|
|
||||||
|
def test_non_operator_room_not_detected(self):
|
||||||
|
"""Nur Operator-Raum wird als Onboarding erkannt."""
|
||||||
|
_review_phases = {"review_room", "review_butler", "review_fakt"}
|
||||||
|
state = {"phase": "review_room", "operator_room_id": "dm123"}
|
||||||
|
is_operator_room = False # Nachricht aus anderem Raum
|
||||||
|
is_onboarding = (
|
||||||
|
is_operator_room and state.get("phase") in _review_phases
|
||||||
|
)
|
||||||
|
assert is_onboarding is False
|
||||||
|
|
||||||
|
|
||||||
|
# ── P0-2: Keywords Button-Dispatch ─────────────────────────────────────
|
||||||
|
|
||||||
|
class TestP02KeywordsDispatch:
|
||||||
|
"""P0-2: REVIEW_ROOM_KW_ADD/KW_REMOVE Dispatch funktioniert."""
|
||||||
|
|
||||||
|
def test_kw_add_prefix_exists(self):
|
||||||
|
"""REVIEW_ROOM_KW_ADD Konstante ist definiert."""
|
||||||
|
from plugin.archivar.onboarding_review import REVIEW_ROOM_KW_ADD
|
||||||
|
assert REVIEW_ROOM_KW_ADD == "REVIEW_ROOM_KW_ADD"
|
||||||
|
|
||||||
|
def test_kw_remove_prefix_exists(self):
|
||||||
|
"""REVIEW_ROOM_KW_REMOVE Konstante ist definiert."""
|
||||||
|
from plugin.archivar.onboarding_review import REVIEW_ROOM_KW_REMOVE
|
||||||
|
assert REVIEW_ROOM_KW_REMOVE == "REVIEW_ROOM_KW_REMOVE"
|
||||||
|
|
||||||
|
def test_dispatch_kw_add_sets_sub_phase(self):
|
||||||
|
"""KW_ADD Dispatch setzt sub_phase auf keywords_edit."""
|
||||||
|
from plugin.archivar.onboarding_review import (
|
||||||
|
dispatch_review_button,
|
||||||
|
REVIEW_ROOM_KW_ADD,
|
||||||
|
SUB_PHASE_KEYWORDS_EDIT,
|
||||||
|
)
|
||||||
|
from plugin.archivar.room_map import RoomMap
|
||||||
|
|
||||||
|
# Minimal RoomMap
|
||||||
|
json_str = json.dumps({
|
||||||
|
"version": 1,
|
||||||
|
"rooms": {
|
||||||
|
"r1": {"name": "#Dev", "theme": "dev", "keywords_100": ["code"], "keywords_context": []},
|
||||||
|
"r2": {"name": "#Ops", "theme": "ops", "keywords_100": ["server"], "keywords_context": [], "catch_all": True},
|
||||||
|
},
|
||||||
|
"excluded_rooms": [],
|
||||||
|
"fact_store_path": "/tmp/test",
|
||||||
|
})
|
||||||
|
tmp = tempfile.NamedTemporaryFile(mode="w", suffix=".json", delete=False, encoding="utf-8")
|
||||||
|
tmp.write(json_str)
|
||||||
|
tmp.close()
|
||||||
|
path = Path(tmp.name)
|
||||||
|
try:
|
||||||
|
rm = RoomMap.load(path)
|
||||||
|
state = {
|
||||||
|
"phase": "review_room",
|
||||||
|
"operator_room_id": "dm123",
|
||||||
|
"sub_phase": None,
|
||||||
|
"target_room_id": None,
|
||||||
|
"edit_kind": None,
|
||||||
|
"pending_text_input": False,
|
||||||
|
}
|
||||||
|
|
||||||
|
def _mock_build(labels, prefix="", style="default"):
|
||||||
|
return [{"text": l, "msg": f"{prefix}::{l}" if prefix else l, "style": style} for l in labels]
|
||||||
|
|
||||||
|
class MockArchivar:
|
||||||
|
_room_map = rm
|
||||||
|
_room_index = None
|
||||||
|
|
||||||
|
payload = f"{REVIEW_ROOM_KW_ADD}::r1"
|
||||||
|
handled, text, attachments = dispatch_review_button(
|
||||||
|
payload, state, rm, MockArchivar(), _mock_build, None
|
||||||
|
)
|
||||||
|
assert handled is True
|
||||||
|
assert state["sub_phase"] == SUB_PHASE_KEYWORDS_EDIT
|
||||||
|
assert state["pending_text_input"] is True
|
||||||
|
assert state["target_room_id"] == "r1"
|
||||||
|
finally:
|
||||||
|
path.unlink(missing_ok=True)
|
||||||
|
|
||||||
|
|
||||||
|
# ── P0-3: Agent-Dispatch-Task Cancel ────────────────────────────────────
|
||||||
|
|
||||||
|
class TestP03AgentDispatchTaskCancel:
|
||||||
|
"""P0-3: _agent_dispatch_task wird bei abort gecancelled."""
|
||||||
|
|
||||||
|
@pytest.mark.asyncio
|
||||||
|
async def test_task_cancel_works(self):
|
||||||
|
"""asyncio.Task.cancel() löst CancelledError aus."""
|
||||||
|
import asyncio
|
||||||
|
|
||||||
|
async def dummy_work():
|
||||||
|
await asyncio.sleep(10)
|
||||||
|
|
||||||
|
task = asyncio.create_task(dummy_work())
|
||||||
|
assert not task.done()
|
||||||
|
task.cancel()
|
||||||
|
with pytest.raises(asyncio.CancelledError):
|
||||||
|
await task
|
||||||
|
assert task.cancelled()
|
||||||
|
|
||||||
|
@pytest.mark.asyncio
|
||||||
|
async def test_agent_dispatch_task_attribute(self):
|
||||||
|
"""_agent_dispatch_task Attribut kann gesetzt und gecancelled werden."""
|
||||||
|
import asyncio
|
||||||
|
|
||||||
|
class MockAdapter:
|
||||||
|
_agent_dispatch_task = None
|
||||||
|
|
||||||
|
adapter = MockAdapter()
|
||||||
|
assert adapter._agent_dispatch_task is None
|
||||||
|
|
||||||
|
async def dummy():
|
||||||
|
await asyncio.sleep(0.01)
|
||||||
|
|
||||||
|
adapter._agent_dispatch_task = asyncio.create_task(dummy())
|
||||||
|
assert adapter._agent_dispatch_task is not None
|
||||||
|
|
||||||
|
# Cancel
|
||||||
|
adapter._agent_dispatch_task.cancel()
|
||||||
|
try:
|
||||||
|
await adapter._agent_dispatch_task
|
||||||
|
except asyncio.CancelledError:
|
||||||
|
pass
|
||||||
|
assert adapter._agent_dispatch_task.cancelled()
|
||||||
|
|
||||||
|
|
||||||
|
# ── P1-4: Message Splitting ─────────────────────────────────────────────
|
||||||
|
|
||||||
|
class TestP14MessageSplitting:
|
||||||
|
"""P1-4: _send_split splittet lange Nachrichten an Absatzgrenzen."""
|
||||||
|
|
||||||
|
def test_split_short_message_not_split(self):
|
||||||
|
"""Kurze Nachrichten werden nicht gesplittet."""
|
||||||
|
content = "Kurze Nachricht"
|
||||||
|
paragraphs = content.split("\n\n")
|
||||||
|
MAX_CHUNK = 2800
|
||||||
|
chunks = []
|
||||||
|
current = ""
|
||||||
|
for para in paragraphs:
|
||||||
|
if len(current) + len(para) + 2 > MAX_CHUNK and current:
|
||||||
|
chunks.append(current.strip())
|
||||||
|
current = para
|
||||||
|
else:
|
||||||
|
if current:
|
||||||
|
current += "\n\n" + para
|
||||||
|
else:
|
||||||
|
current = para
|
||||||
|
if current.strip():
|
||||||
|
chunks.append(current.strip())
|
||||||
|
assert len(chunks) == 1
|
||||||
|
assert chunks[0] == "Kurze Nachricht"
|
||||||
|
|
||||||
|
def test_split_long_message_at_paragraphs(self):
|
||||||
|
"""Lange Nachrichten werden an Absatzgrenzen gesplittet."""
|
||||||
|
# Erzeuge 10 Absätze à 500 Zeichen = 5000 Zeichen
|
||||||
|
paragraphs = ["A" * 500 for _ in range(10)]
|
||||||
|
content = "\n\n".join(paragraphs)
|
||||||
|
MAX_CHUNK = 2800
|
||||||
|
chunks = []
|
||||||
|
current = ""
|
||||||
|
for para in paragraphs:
|
||||||
|
if len(current) + len(para) + 2 > MAX_CHUNK and current:
|
||||||
|
chunks.append(current.strip())
|
||||||
|
current = para
|
||||||
|
else:
|
||||||
|
if current:
|
||||||
|
current += "\n\n" + para
|
||||||
|
else:
|
||||||
|
current = para
|
||||||
|
if current.strip():
|
||||||
|
chunks.append(current.strip())
|
||||||
|
assert len(chunks) >= 2 # Muss gesplittet werden
|
||||||
|
|
||||||
|
def test_split_single_huge_paragraph(self):
|
||||||
|
"""Ein einzelner riesiger Absatz wird hart gesplittet."""
|
||||||
|
content = "B" * 5000
|
||||||
|
MAX_CHUNK = 2800
|
||||||
|
chunks = []
|
||||||
|
for i in range(0, len(content), MAX_CHUNK):
|
||||||
|
chunks.append(content[i:i + MAX_CHUNK])
|
||||||
|
assert len(chunks) >= 2
|
||||||
|
assert sum(len(c) for c in chunks) == 5000
|
||||||
|
|
||||||
|
def test_split_preserves_content(self):
|
||||||
|
"""Gesplittete Nachrichten enthalten den gesamten Originaltext."""
|
||||||
|
paragraphs = [f"Absatz {i}: " + "X" * 200 for i in range(10)]
|
||||||
|
content = "\n\n".join(paragraphs)
|
||||||
|
MAX_CHUNK = 2800
|
||||||
|
chunks = []
|
||||||
|
current = ""
|
||||||
|
for para in paragraphs:
|
||||||
|
if len(current) + len(para) + 2 > MAX_CHUNK and current:
|
||||||
|
chunks.append(current.strip())
|
||||||
|
current = para
|
||||||
|
else:
|
||||||
|
if current:
|
||||||
|
current += "\n\n" + para
|
||||||
|
else:
|
||||||
|
current = para
|
||||||
|
if current.strip():
|
||||||
|
chunks.append(current.strip())
|
||||||
|
# Alle Absätze müssen in den Chunks enthalten sein
|
||||||
|
all_text = "\n\n".join(chunks)
|
||||||
|
for i in range(10):
|
||||||
|
assert f"Absatz {i}" in all_text
|
||||||
|
|
||||||
|
|
||||||
|
# ── P1-5: ::multiroom schreibt .env ─────────────────────────────────────
|
||||||
|
|
||||||
|
class TestP15MultiroomEnvWrite:
|
||||||
|
"""P1-5: _cmd_multiroom schreibt .env selbst."""
|
||||||
|
|
||||||
|
def test_env_write_on_off(self):
|
||||||
|
"""MULTIROOM_AGENT wird in .env geschrieben."""
|
||||||
|
import tempfile
|
||||||
|
|
||||||
|
with tempfile.TemporaryDirectory() as tmpdir:
|
||||||
|
env_path = Path(tmpdir) / ".env"
|
||||||
|
# Simuliere ::multiroom on
|
||||||
|
env_path.write_text("MULTIROOM_AGENT=false\n")
|
||||||
|
content = env_path.read_text()
|
||||||
|
content = content.replace("MULTIROOM_AGENT=false", "MULTIROOM_AGENT=true")
|
||||||
|
env_path.write_text(content)
|
||||||
|
assert "MULTIROOM_AGENT=true" in env_path.read_text()
|
||||||
|
|
||||||
|
# Simuliere ::multiroom off
|
||||||
|
content = env_path.read_text()
|
||||||
|
content = content.replace("MULTIROOM_AGENT=true", "MULTIROOM_AGENT=false")
|
||||||
|
env_path.write_text(content)
|
||||||
|
assert "MULTIROOM_AGENT=false" in env_path.read_text()
|
||||||
|
|
||||||
|
def test_env_write_creates_file(self):
|
||||||
|
""".env wird erstellt wenn nicht vorhanden."""
|
||||||
|
import tempfile
|
||||||
|
|
||||||
|
with tempfile.TemporaryDirectory() as tmpdir:
|
||||||
|
env_path = Path(tmpdir) / ".env"
|
||||||
|
assert not env_path.exists()
|
||||||
|
env_path.write_text("MULTIROOM_AGENT=true\n")
|
||||||
|
assert env_path.exists()
|
||||||
|
assert "MULTIROOM_AGENT=true" in env_path.read_text()
|
||||||
|
|
||||||
|
def test_env_write_appends_if_missing(self):
|
||||||
|
"""MULTIROOM_AGENT wird angehängt wenn nicht in .env."""
|
||||||
|
import tempfile
|
||||||
|
|
||||||
|
with tempfile.TemporaryDirectory() as tmpdir:
|
||||||
|
env_path = Path(tmpdir) / ".env"
|
||||||
|
env_path.write_text("OTHER_VAR=value\n")
|
||||||
|
content = env_path.read_text()
|
||||||
|
if "MULTIROOM_AGENT" not in content:
|
||||||
|
content += "\nMULTIROOM_AGENT=true\n"
|
||||||
|
env_path.write_text(content)
|
||||||
|
assert "MULTIROOM_AGENT=true" in env_path.read_text()
|
||||||
|
assert "OTHER_VAR=value" in env_path.read_text()
|
||||||
|
|
||||||
|
|
||||||
|
# ── P1-6: ::approve/::deny registriert ──────────────────────────────────
|
||||||
|
|
||||||
|
class TestP16ApproveDenyCommands:
|
||||||
|
"""P1-6: ::approve/::deny sind als Inline-Commands registriert."""
|
||||||
|
|
||||||
|
def test_approve_registered(self):
|
||||||
|
"""::approve ist registriert."""
|
||||||
|
registry = InlineCommandRegistry()
|
||||||
|
async def handler(room_id, args):
|
||||||
|
return "approved"
|
||||||
|
registry.register("approve", handler, "Bestätigt einen Befehl", category="Standard")
|
||||||
|
assert registry.is_registered("approve")
|
||||||
|
h = registry.get_handler("approve")
|
||||||
|
assert h is not None
|
||||||
|
|
||||||
|
def test_deny_registered(self):
|
||||||
|
"""::deny ist registriert."""
|
||||||
|
registry = InlineCommandRegistry()
|
||||||
|
async def handler(room_id, args):
|
||||||
|
return "denied"
|
||||||
|
registry.register("deny", handler, "Lehnt einen Befehl ab", category="Standard")
|
||||||
|
assert registry.is_registered("deny")
|
||||||
|
h = registry.get_handler("deny")
|
||||||
|
assert h is not None
|
||||||
|
|
||||||
|
def test_approve_subcommands(self):
|
||||||
|
"""::approve hat session und always Subcommands."""
|
||||||
|
registry = InlineCommandRegistry()
|
||||||
|
async def handler(room_id, args):
|
||||||
|
return "approved"
|
||||||
|
registry.register(
|
||||||
|
"approve", handler,
|
||||||
|
"Bestätigt einen Befehl",
|
||||||
|
category="Standard",
|
||||||
|
subcommands={"session": "Für Session", "always": "Dauerhaft"},
|
||||||
|
)
|
||||||
|
cmd = registry._commands["approve"]
|
||||||
|
assert "session" in cmd["subcommands"]
|
||||||
|
assert "always" in cmd["subcommands"]
|
||||||
|
|
||||||
|
|
||||||
|
# ── UX-7: Numbered Button Labels ─────────────────────────────────────────
|
||||||
|
|
||||||
|
class TestUX7NumberedButtonLabels:
|
||||||
|
"""UX-7: numbered_button_labels() nummeriert Buttons mit Emoji-Zahlen."""
|
||||||
|
|
||||||
|
def test_numbers_prefix_labels(self):
|
||||||
|
"""Labels werden mit 1️⃣, 2️⃣, ... geprefixt."""
|
||||||
|
EMOJI_NUMBERS = ["1️⃣", "2️⃣", "3️⃣", "4️⃣", "5️⃣", "6️⃣", "7️⃣", "8️⃣", "9️⃣", "🔟"]
|
||||||
|
|
||||||
|
def numbered_button_labels(labels, start=0):
|
||||||
|
result = []
|
||||||
|
for i, label in enumerate(labels):
|
||||||
|
idx = start + i
|
||||||
|
if idx < len(EMOJI_NUMBERS):
|
||||||
|
emoji = EMOJI_NUMBERS[idx]
|
||||||
|
result.append(f"{emoji} {label}")
|
||||||
|
else:
|
||||||
|
result.append(f"{idx + 1}. {label}")
|
||||||
|
return result
|
||||||
|
|
||||||
|
labels = ["Ändern", "Beibehalten"]
|
||||||
|
numbered = numbered_button_labels(labels)
|
||||||
|
assert numbered[0] == "1️⃣ Ändern"
|
||||||
|
assert numbered[1] == "2️⃣ Beibehalten"
|
||||||
|
|
||||||
|
def test_numbers_with_offset(self):
|
||||||
|
"""Start-Offset verschiebt die Nummerierung."""
|
||||||
|
EMOJI_NUMBERS = ["1️⃣", "2️⃣", "3️⃣", "4️⃣", "5️⃣", "6️⃣", "7️⃣", "8️⃣", "9️⃣", "🔟"]
|
||||||
|
|
||||||
|
def numbered_button_labels(labels, start=0):
|
||||||
|
result = []
|
||||||
|
for i, label in enumerate(labels):
|
||||||
|
idx = start + i
|
||||||
|
if idx < len(EMOJI_NUMBERS):
|
||||||
|
emoji = EMOJI_NUMBERS[idx]
|
||||||
|
result.append(f"{emoji} {label}")
|
||||||
|
else:
|
||||||
|
result.append(f"{idx + 1}. {label}")
|
||||||
|
return result
|
||||||
|
|
||||||
|
labels = ["Option A", "Option B"]
|
||||||
|
numbered = numbered_button_labels(labels, start=3)
|
||||||
|
assert numbered[0] == "4️⃣ Option A"
|
||||||
|
assert numbered[1] == "5️⃣ Option B"
|
||||||
|
|
||||||
|
def test_numbers_fallback_beyond_10(self):
|
||||||
|
"""Jenseits von 10 wird auf numerische Fallbacks umgeschaltet."""
|
||||||
|
EMOJI_NUMBERS = ["1️⃣", "2️⃣", "3️⃣", "4️⃣", "5️⃣", "6️⃣", "7️⃣", "8️⃣", "9️⃣", "🔟"]
|
||||||
|
|
||||||
|
def numbered_button_labels(labels, start=0):
|
||||||
|
result = []
|
||||||
|
for i, label in enumerate(labels):
|
||||||
|
idx = start + i
|
||||||
|
if idx < len(EMOJI_NUMBERS):
|
||||||
|
emoji = EMOJI_NUMBERS[idx]
|
||||||
|
result.append(f"{emoji} {label}")
|
||||||
|
else:
|
||||||
|
result.append(f"{idx + 1}. {label}")
|
||||||
|
return result
|
||||||
|
|
||||||
|
labels = ["R11", "R12"]
|
||||||
|
numbered = numbered_button_labels(labels, start=10)
|
||||||
|
assert numbered[0] == "11. R11"
|
||||||
|
assert numbered[1] == "12. R12"
|
||||||
|
|
||||||
|
def test_keyword_buttons_not_numbered(self):
|
||||||
|
"""Keyword-X-Buttons werden NICHT nummeriert (dynamisch)."""
|
||||||
|
# X-Buttons für Keywords haben eigene Labels (❌ keyword)
|
||||||
|
# und sollen nicht durchnummeriert werden.
|
||||||
|
kw_labels = ["❌ code", "❌ bug", "❌ test"]
|
||||||
|
# Diese Labels werden direkt verwendet, ohne Nummerierung
|
||||||
|
for label in kw_labels:
|
||||||
|
assert "❌" in label # X-Button erkennbar
|
||||||
|
|
||||||
|
|
||||||
|
# ── UX-8: Command Question Extraction ────────────────────────────────────
|
||||||
|
|
||||||
|
class TestUX8CommandQuestionExtraction:
|
||||||
|
"""UX-8: extract_command_question() erkennt Fragen über ::-Befehle."""
|
||||||
|
|
||||||
|
def test_extract_was_macht(self):
|
||||||
|
"""'Was macht ::curate?' → 'curate'"""
|
||||||
|
result = extract_command_question("Was macht ::curate?")
|
||||||
|
assert result == "curate"
|
||||||
|
|
||||||
|
def test_extract_was_ist(self):
|
||||||
|
"""'Was ist ::onboarding?' → 'onboarding'"""
|
||||||
|
result = extract_command_question("Was ist ::onboarding?")
|
||||||
|
assert result == "onboarding"
|
||||||
|
|
||||||
|
def test_extract_wie_geht(self):
|
||||||
|
"""'Wie geht ::multiroom?' → 'multiroom'"""
|
||||||
|
result = extract_command_question("Wie geht ::multiroom?")
|
||||||
|
assert result == "multiroom"
|
||||||
|
|
||||||
|
def test_extract_erklaere(self):
|
||||||
|
"""'Erkläre ::sethome' → 'sethome'"""
|
||||||
|
result = extract_command_question("Erkläre ::sethome")
|
||||||
|
assert result == "sethome"
|
||||||
|
|
||||||
|
def test_extract_was_bedeutet(self):
|
||||||
|
"""'Was bedeutet ::curate?' → 'curate'"""
|
||||||
|
result = extract_command_question("Was bedeutet ::curate?")
|
||||||
|
assert result == "curate"
|
||||||
|
|
||||||
|
def test_extract_help_english(self):
|
||||||
|
"""'What does ::curate do?' → 'curate'"""
|
||||||
|
result = extract_command_question("What does ::curate do?")
|
||||||
|
assert result == "curate"
|
||||||
|
|
||||||
|
def test_extract_no_command_question(self):
|
||||||
|
"""Normale Nachrichten werden nicht als Command-Frage erkannt."""
|
||||||
|
result = extract_command_question("Hallo, wie geht es dir?")
|
||||||
|
assert result is None
|
||||||
|
|
||||||
|
def test_extract_no_double_colon(self):
|
||||||
|
"""Text ohne :: wird nicht erkannt."""
|
||||||
|
result = extract_command_question("Was macht curate?")
|
||||||
|
assert result is None
|
||||||
|
|
||||||
|
def test_build_command_help_known(self):
|
||||||
|
"""build_command_help() für bekannten Befehl."""
|
||||||
|
registry = InlineCommandRegistry()
|
||||||
|
async def handler(room_id, args):
|
||||||
|
return "ok"
|
||||||
|
registry.register(
|
||||||
|
"curate", handler,
|
||||||
|
help_text="Kuratiert Keywords",
|
||||||
|
description="Optimiert die Room-Map-Keywords.",
|
||||||
|
category="Plugin",
|
||||||
|
subcommands={"status": "Zeigt Status", "run": "Führt aus"},
|
||||||
|
)
|
||||||
|
help_text = build_command_help(registry, "curate")
|
||||||
|
assert help_text is not None
|
||||||
|
assert "::curate" in help_text
|
||||||
|
assert "Kuratiert Keywords" in help_text
|
||||||
|
assert "status" in help_text
|
||||||
|
assert "run" in help_text
|
||||||
|
|
||||||
|
def test_build_command_help_unknown(self):
|
||||||
|
"""build_command_help() für unbekannten Befehl gibt None."""
|
||||||
|
registry = InlineCommandRegistry()
|
||||||
|
help_text = build_command_help(registry, "nonexistent")
|
||||||
|
assert help_text is None
|
||||||
|
|
||||||
|
def test_is_natural_help_request_still_works(self):
|
||||||
|
"""is_natural_help_request() funktioniert weiterhin."""
|
||||||
|
assert is_natural_help_request("hilfe") is True
|
||||||
|
assert is_natural_help_request("was kannst du?") is True
|
||||||
|
assert is_natural_help_request("Hallo Welt") is False
|
||||||
Reference in New Issue
Block a user