Compare commits
4 Commits
v8.6.1
...
b40b221896
| Author | SHA1 | Date | |
|---|---|---|---|
| b40b221896 | |||
| f028a30d6c | |||
| f61b0ba508 | |||
| 99979d6f9d |
+191
-31
@@ -193,6 +193,15 @@ find_pipx_venv() {
|
||||
echo "$hermes_venv"
|
||||
return 0
|
||||
fi
|
||||
# Fallback 2: Systemweite Installation (root, /usr/local, /opt)
|
||||
# Bei root-Installationen liegt der venv unter /usr/local/lib/hermes-agent/venv/
|
||||
# oder /opt/hermes-agent/venv/ — nicht unter $HOME.
|
||||
for sys_venv in /usr/local/lib/hermes-agent/venv /opt/hermes-agent/venv; do
|
||||
if [ -d "$sys_venv" ] && [ -x "$sys_venv/bin/python" ]; then
|
||||
echo "$sys_venv"
|
||||
return 0
|
||||
fi
|
||||
done
|
||||
return 1
|
||||
}
|
||||
|
||||
@@ -207,6 +216,25 @@ print(sp)
|
||||
PY
|
||||
}
|
||||
|
||||
# Core-Plugin-Pfad finden: dort wo gateway/config.py liegt,
|
||||
# zwei Ebenen hoch, dann plugins/platforms/.
|
||||
# Der Gateway scannt Path(__file__).parent.parent / "plugins" / "platforms"
|
||||
# in gateway/config.py — das ist der MAßGEBLICHE Pfad, nicht site-packages.
|
||||
find_core_plugin_path() {
|
||||
local venv="$1"
|
||||
local core_path
|
||||
core_path=$("$venv/bin/python" -c "
|
||||
import gateway.config
|
||||
from pathlib import Path
|
||||
print(Path(gateway.config.__file__).parent.parent / 'plugins' / 'platforms')
|
||||
" 2>/dev/null)
|
||||
if [ -n "$core_path" ] && [ -d "$core_path" ]; then
|
||||
echo "$core_path"
|
||||
return 0
|
||||
fi
|
||||
return 1
|
||||
}
|
||||
|
||||
# ──────────────────────────────────────────────────────────────────────────
|
||||
# 1. System-Dependencies installieren
|
||||
# ──────────────────────────────────────────────────────────────────────────
|
||||
@@ -375,11 +403,18 @@ deploy_plugin() {
|
||||
local src="$script_dir/plugin"
|
||||
[ -d "$src" ] || die "plugin/-Verzeichnis fehlt in $script_dir"
|
||||
|
||||
# Ziel-Pfad ermitteln: pipx-venv → site-packages, eigener venv → ~/.hermes/hermes-agent/plugins/
|
||||
# Ziel-Pfad ermitteln: Core-Plugin-Pfad (gateway/config.py) hat Vorrang.
|
||||
# Der Gateway scannt Path(__file__).parent.parent / "plugins" / "platforms"
|
||||
# in gateway/config.py — das ist der MAßGEBLICHE Pfad, nicht site-packages.
|
||||
local dst
|
||||
if [ "$PIPX_VENV" = "$HOME/.hermes/hermes-agent/venv" ]; then
|
||||
local core_path
|
||||
if core_path="$(find_core_plugin_path "$PIPX_VENV" 2>/dev/null)" && [ -n "$core_path" ]; then
|
||||
dst="$core_path/rocketchat"
|
||||
log "Core-Plugin-Pfad (gateway/config.py): $dst"
|
||||
elif [ "$PIPX_VENV" = "$HOME/.hermes/hermes-agent/venv" ]; then
|
||||
# Eigener venv (kein pipx): Plugin direkt unter ~/.hermes/hermes-agent/plugins/
|
||||
dst="$HOME/.hermes/hermes-agent/plugins/platforms/rocketchat"
|
||||
log "Eigener venv-Pfad: $dst"
|
||||
else
|
||||
# pipx-venv: Plugin unter site-packages/plugins/platforms/rocketchat/
|
||||
local site_packages
|
||||
@@ -390,9 +425,22 @@ deploy_plugin() {
|
||||
site_packages="<PIPX_VENV>/lib/python3.13/site-packages"
|
||||
fi
|
||||
dst="$site_packages/plugins/platforms/rocketchat"
|
||||
log "site-packages-Pfad (Fallback): $dst"
|
||||
fi
|
||||
|
||||
log "Plugin-Ziel (P3): $dst"
|
||||
# Pitfall 8: Alte Plugin-Ordner-Namen vor Deployment bereinigen
|
||||
for old_name in rocketchat-platform; do
|
||||
local old_dir
|
||||
old_dir="$(dirname "$dst")/$old_name"
|
||||
if [ -d "$old_dir" ]; then
|
||||
log "Entferne alten Plugin-Ordner: $old_dir"
|
||||
if ! $DRY_RUN; then
|
||||
rm -rf "$old_dir"
|
||||
fi
|
||||
fi
|
||||
done
|
||||
|
||||
log "Plugin-Ziel: $dst"
|
||||
if ! $DRY_RUN; then
|
||||
mkdir -p "$dst"
|
||||
|
||||
@@ -424,6 +472,20 @@ deploy_plugin() {
|
||||
local count
|
||||
count=$(find "$dst" -type f ! -path '*/__pycache__/*' | wc -l)
|
||||
ok "$count Plugin-Dateien deployed"
|
||||
|
||||
# Pitfall 4: plugin.yaml name-Feld MUSS 'rocketchat' sein
|
||||
if [ -f "$dst/plugin.yaml" ]; then
|
||||
if grep '^name:' "$dst/plugin.yaml" | grep -q 'rocketchat$'; then
|
||||
ok "plugin.yaml name='rocketchat' (korrekt)"
|
||||
else
|
||||
local actual_name
|
||||
actual_name="$(grep '^name:' "$dst/plugin.yaml" | head -1)"
|
||||
err "FAIL: plugin.yaml name-Feld ist '$actual_name' — muss 'rocketchat' sein! Plugin wird nicht geladen."
|
||||
die "plugin.yaml name-Feld falsch — Abbruch"
|
||||
fi
|
||||
else
|
||||
warn "plugin.yaml nicht gefunden in $dst"
|
||||
fi
|
||||
else
|
||||
printf '%s[dry]%s cp -r %s/* -> %s/\\n' "$C_YELLOW" "$C_RESET" "$src" "$dst"
|
||||
fi
|
||||
@@ -633,6 +695,17 @@ write_env_file() {
|
||||
echo "OLLAMA_KEEP_ALIVE=${OLLAMA_KEEP_ALIVE}"
|
||||
} > "$envfile"
|
||||
chmod 600 "$envfile"
|
||||
|
||||
# Pitfall 6: ARCHIVAR_CATCHALL_ROOM auto-setzen wenn ROCKETCHAT_HOME_CHANNEL definiert
|
||||
# Bei Single-Room-Mode (MULTIROOM_AGENT=false) reicht ARCHIVAR_CATCHALL_ROOM in .env.
|
||||
# Ohne diesen Eintrag crasht der Archivar mit "No room map found".
|
||||
if [ -n "${ROCKETCHAT_HOME_CHANNEL:-}" ]; then
|
||||
if ! grep -q '^ARCHIVAR_CATCHALL_ROOM=' "$envfile" 2>/dev/null; then
|
||||
echo "ARCHIVAR_CATCHALL_ROOM=${ROCKETCHAT_HOME_CHANNEL}" >> "$envfile"
|
||||
ok "ARCHIVAR_CATCHALL_ROOM=${ROCKETCHAT_HOME_CHANNEL} auto-gesetzt (Pitfall 6)"
|
||||
fi
|
||||
fi
|
||||
|
||||
ok ".env geschrieben: $envfile (chmod 600)"
|
||||
else
|
||||
printf '%s[dry]%s schreibe %s\n' "$C_YELLOW" "$C_RESET" "$envfile"
|
||||
@@ -738,7 +811,76 @@ MD
|
||||
# ──────────────────────────────────────────────────────────────────────────
|
||||
# 8. Gateway Service (systemd user service mit enable!)
|
||||
# P5: Gateway braucht systemctl enable für Autostart
|
||||
# Pitfall 7: Unterstützt sowohl systemctl --user (pipx) als auch
|
||||
# sudo systemctl (system-service, root-Installationen).
|
||||
# ──────────────────────────────────────────────────────────────────────────
|
||||
|
||||
# restart_gateway() — erkennt automatisch ob Gateway als user- oder system-service läuft
|
||||
restart_gateway() {
|
||||
if systemctl --user is-active hermes-gateway &>/dev/null; then
|
||||
systemctl --user restart hermes-gateway
|
||||
elif sudo systemctl is-active hermes-gateway &>/dev/null; then
|
||||
sudo systemctl restart hermes-gateway
|
||||
else
|
||||
# Weder user noch system — versuche user (Default)
|
||||
systemctl --user restart hermes-gateway 2>/dev/null || true
|
||||
fi
|
||||
}
|
||||
|
||||
# gateway_journalctl() — journalctl-Aufruf für user- ODER system-service
|
||||
gateway_journalctl() {
|
||||
local args="$*"
|
||||
if systemctl --user is-active hermes-gateway &>/dev/null 2>&1; then
|
||||
journalctl --user -u hermes-gateway $args
|
||||
elif systemctl is-active hermes-gateway &>/dev/null 2>&1; then
|
||||
journalctl -u hermes-gateway $args
|
||||
else
|
||||
# Fallback: user journalctl
|
||||
journalctl --user -u hermes-gateway $args 2>/dev/null || true
|
||||
fi
|
||||
}
|
||||
|
||||
# gateway_is_enabled() — prüft enable-Status für user- ODER system-service
|
||||
gateway_is_enabled() {
|
||||
if systemctl --user is-enabled hermes-gateway &>/dev/null 2>&1; then
|
||||
systemctl --user is-enabled hermes-gateway 2>/dev/null
|
||||
elif systemctl is-enabled hermes-gateway &>/dev/null 2>&1; then
|
||||
systemctl is-enabled hermes-gateway 2>/dev/null
|
||||
else
|
||||
return 1
|
||||
fi
|
||||
}
|
||||
|
||||
# gateway_is_active() — prüft active-Status für user- ODER system-service
|
||||
gateway_is_active() {
|
||||
systemctl --user is-active hermes-gateway &>/dev/null 2>&1 \
|
||||
|| systemctl is-active hermes-gateway &>/dev/null 2>&1
|
||||
}
|
||||
|
||||
# gateway_systemctl() — generischer systemctl-Aufruf, auto-detektiert user vs. system
|
||||
gateway_systemctl() {
|
||||
local cmd="$1"; shift
|
||||
if systemctl --user is-active hermes-gateway &>/dev/null 2>&1; then
|
||||
systemctl --user "$cmd" hermes-gateway "$@"
|
||||
elif systemctl is-active hermes-gateway &>/dev/null 2>&1; then
|
||||
sudo systemctl "$cmd" hermes-gateway "$@"
|
||||
else
|
||||
# Weder user noch system — versuche user (Default)
|
||||
systemctl --user "$cmd" hermes-gateway "$@" 2>/dev/null || true
|
||||
fi
|
||||
}
|
||||
|
||||
# gateway_daemon_reload() — daemon-reload für user- ODER system-service
|
||||
gateway_daemon_reload() {
|
||||
if systemctl --user is-active hermes-gateway &>/dev/null 2>&1; then
|
||||
systemctl --user daemon-reload
|
||||
elif systemctl is-active hermes-gateway &>/dev/null 2>&1; then
|
||||
sudo systemctl daemon-reload
|
||||
else
|
||||
systemctl --user daemon-reload 2>/dev/null || true
|
||||
fi
|
||||
}
|
||||
|
||||
install_gateway_service() {
|
||||
banner "8. Gateway Service"
|
||||
|
||||
@@ -801,29 +943,29 @@ EOF
|
||||
ok "Ollama neugestartet (OLLAMA_KEEP_ALIVE=$OLLAMA_KEEP_ALIVE aktiv)"
|
||||
fi
|
||||
|
||||
systemctl --user daemon-reload
|
||||
gateway_daemon_reload
|
||||
|
||||
# State-Cleanup (Discovery-Bug + Auto-Resume-Loop)
|
||||
rm -f "$HOME/.hermes/gateway_state.json" \
|
||||
"$HOME/.hermes/gateway.lock" \
|
||||
"$HOME/.hermes/.gateway_state_"*.tmp 2>/dev/null || true
|
||||
rm -f "$HOME/.hermes/state.db" 2>/dev/null || true
|
||||
systemctl --user reset-failed hermes-gateway 2>/dev/null || true
|
||||
gateway_systemctl reset-failed 2>/dev/null || true
|
||||
|
||||
# P5: ENABLE! Sonst kein Autostart nach Reboot
|
||||
systemctl --user enable hermes-gateway
|
||||
gateway_systemctl enable
|
||||
ok "hermes-gateway enabled (P5: Autostart nach Reboot)"
|
||||
|
||||
# Starten
|
||||
systemctl --user stop hermes-gateway 2>/dev/null || true
|
||||
gateway_systemctl stop 2>/dev/null || true
|
||||
local wait=0
|
||||
while systemctl --user is-active hermes-gateway >/dev/null 2>&1 && [ $wait -lt 30 ]; do
|
||||
while gateway_is_active && [ $wait -lt 30 ]; do
|
||||
sleep 1; wait=$((wait + 1))
|
||||
done
|
||||
systemctl --user start hermes-gateway 2>/dev/null || true
|
||||
gateway_systemctl start 2>/dev/null || true
|
||||
ok "Gateway gestartet"
|
||||
else
|
||||
printf '%s[dry]%s systemctl --user enable + start hermes-gateway\n' "$C_YELLOW" "$C_RESET"
|
||||
printf '%s[dry]%s gateway_systemctl enable + start hermes-gateway\n' "$C_YELLOW" "$C_RESET"
|
||||
fi
|
||||
}
|
||||
|
||||
@@ -853,12 +995,20 @@ verify_installation() {
|
||||
if "$VENV_PY" -c 'import snowballstemmer' 2>/dev/null; then
|
||||
ok "snowballstemmer in pipx-venv importierbar (P1)"
|
||||
else
|
||||
err "FAIL: snowballstemmer fehlt in pipx-venv (P1)"; fail=1
|
||||
warn "snowballstemmer fehlt — installiere nach..."
|
||||
if "$VENV_PY" -m pip install --quiet snowballstemmer>=3.0.0 2>/dev/null; then
|
||||
ok "snowballstemmer nachinstalliert (P1)"
|
||||
else
|
||||
err "FAIL: snowballstemmer fehlt und Installation fehlgeschlagen (P1)"; fail=1
|
||||
fi
|
||||
fi
|
||||
|
||||
# Plugin-Dateien
|
||||
local plugin_dir
|
||||
if [ "$PIPX_VENV" = "$HOME/.hermes/hermes-agent/venv" ]; then
|
||||
local core_path
|
||||
if core_path="$(find_core_plugin_path "$PIPX_VENV" 2>/dev/null)" && [ -n "$core_path" ]; then
|
||||
plugin_dir="$core_path/rocketchat"
|
||||
elif [ "$PIPX_VENV" = "$HOME/.hermes/hermes-agent/venv" ]; then
|
||||
plugin_dir="$HOME/.hermes/hermes-agent/plugins/platforms/rocketchat"
|
||||
else
|
||||
local sp
|
||||
@@ -912,7 +1062,7 @@ verify_installation() {
|
||||
[ $env_ok -eq 1 ] && ok ".env vollständig"
|
||||
|
||||
# Gateway service enabled (P5)
|
||||
if systemctl --user is-enabled hermes-gateway 2>/dev/null | grep -q enabled; then
|
||||
if gateway_is_enabled | grep -q enabled; then
|
||||
ok "hermes-gateway enabled (P5: Autostart)"
|
||||
else
|
||||
err "FAIL: hermes-gateway nicht enabled (P5)"; fail=1
|
||||
@@ -937,7 +1087,7 @@ verify_installation() {
|
||||
# journalctl ist die zuverlässige Quelle.
|
||||
if command -v journalctl >/dev/null 2>&1; then
|
||||
local no_adapter
|
||||
no_adapter="$(journalctl --user -u hermes-gateway --since '2 minutes ago' 2>/dev/null | grep -c 'No adapter' || echo "0")"
|
||||
no_adapter="$(gateway_journalctl --since '2 minutes ago' 2>/dev/null | grep -c 'No adapter' || echo "0")"
|
||||
if [ "${no_adapter:-0}" -gt 0 ]; then
|
||||
err "FAIL: Gateway-Log zeigt 'No adapter' — Plugin nicht geladen (Erkenntnis 5)"
|
||||
fail=1
|
||||
@@ -1135,7 +1285,14 @@ check_gitea_ssh_key() {
|
||||
}
|
||||
|
||||
# SSH-Key-Check VOR Repo-Bootstrap (P11)
|
||||
check_gitea_ssh_key
|
||||
# P11-Fix: Bei --update-only ist das Repo bereits lokal — kein Gitea-Clone nötig.
|
||||
# Externe Maschinen (Hetzner VPS) können Gitea nur per HTTPS erreichen,
|
||||
# SSH-Port 222 ist nicht nach außen freigegeben.
|
||||
if [ "$UPDATE_ONLY" = "true" ] && [ -d "$(cd "$(dirname "$0")" && pwd)/.git" ] && [ -d "$(cd "$(dirname "$0")" && pwd)/plugin" ]; then
|
||||
log "[+] --update-only: P11 Gitea SSH-Check übersprungen (Repo bereits lokal)"
|
||||
else
|
||||
check_gitea_ssh_key
|
||||
fi
|
||||
|
||||
# Repo-Bootstrap (falls install.sh standalone aufgerufen wurde)
|
||||
bootstrap_repo "$@"
|
||||
@@ -1184,10 +1341,10 @@ if $CHECK_ONLY; then
|
||||
banner "P13: Erweiterte Checks"
|
||||
|
||||
# 1. Gateway-Status
|
||||
if systemctl --user is-active hermes-gateway >/dev/null 2>&1; then
|
||||
if gateway_is_active; then
|
||||
ok "hermes-gateway: active"
|
||||
else
|
||||
warn "hermes-gateway: nicht aktiv (systemctl --user is-active hermes-gateway)"
|
||||
warn "hermes-gateway: nicht aktiv"
|
||||
fi
|
||||
|
||||
# 2. REST-Login-Ping gegen ROCKETCHAT_BASE_URL (falls Credentials vorhanden)
|
||||
@@ -1258,8 +1415,11 @@ if $UPDATE_ONLY; then
|
||||
|| die "pipx-venv nicht gefunden — vorher Normal-Install ausführen"
|
||||
VENV_PY="$PIPX_VENV/bin/python"
|
||||
|
||||
# Ziel-Pfad ermitteln
|
||||
if [ "$PIPX_VENV" = "$HOME/.hermes/hermes-agent/venv" ]; then
|
||||
# Ziel-Pfad ermitteln (gleiche Logik wie deploy_plugin)
|
||||
local _update_core_path
|
||||
if _update_core_path="$(find_core_plugin_path "$PIPX_VENV" 2>/dev/null)" && [ -n "$_update_core_path" ]; then
|
||||
_update_dst="$_update_core_path/rocketchat"
|
||||
elif [ "$PIPX_VENV" = "$HOME/.hermes/hermes-agent/venv" ]; then
|
||||
_update_dst="$HOME/.hermes/hermes-agent/plugins/platforms/rocketchat"
|
||||
else
|
||||
_update_site_packages="$(find_site_packages "$PIPX_VENV")"
|
||||
@@ -1292,30 +1452,30 @@ if $UPDATE_ONLY; then
|
||||
|
||||
# ── Schritt 4: Gateway-Dienst neu starten ──
|
||||
if ! $DRY_RUN; then
|
||||
systemctl --user daemon-reload 2>/dev/null || true
|
||||
gateway_daemon_reload 2>/dev/null || true
|
||||
rm -f "$HOME/.hermes/gateway_state.json" "$HOME/.hermes/gateway.lock" 2>/dev/null || true
|
||||
systemctl --user reset-failed hermes-gateway 2>/dev/null || true
|
||||
gateway_systemctl reset-failed 2>/dev/null || true
|
||||
|
||||
if $NO_RESTART; then
|
||||
ok "Gateway-Neustart übersprungen (--no-restart)"
|
||||
else
|
||||
log "Starte Gateway neu..."
|
||||
systemctl --user restart hermes-gateway 2>/dev/null || true
|
||||
restart_gateway 2>/dev/null || true
|
||||
|
||||
# Warte bis active (max 30s)
|
||||
_update_wait=0
|
||||
while ! systemctl --user is-active hermes-gateway >/dev/null 2>&1 && [ $_update_wait -lt 30 ]; do
|
||||
while ! gateway_is_active && [ $_update_wait -lt 30 ]; do
|
||||
sleep 1
|
||||
_update_wait=$((_update_wait + 1))
|
||||
done
|
||||
if systemctl --user is-active hermes-gateway >/dev/null 2>&1; then
|
||||
if gateway_is_active; then
|
||||
ok "Gateway neugestartet und aktiv (nach ${_update_wait}s)"
|
||||
else
|
||||
err "Gateway nach 30s nicht aktiv — prüfe: journalctl --user -u hermes-gateway -n 20"
|
||||
err "Gateway nach 30s nicht aktiv — prüfe: gateway_journalctl -n 20"
|
||||
fi
|
||||
fi
|
||||
else
|
||||
printf '%s[dry]%s systemctl --user restart hermes-gateway\n' "$C_YELLOW" "$C_RESET"
|
||||
printf '%s[dry]%s restart_gateway\\n' "$C_YELLOW" "$C_RESET"
|
||||
fi
|
||||
|
||||
# ── Schritt 5: Post-Deployment-Verifikation ──
|
||||
@@ -1334,7 +1494,7 @@ if $UPDATE_ONLY; then
|
||||
_all_ok=true
|
||||
|
||||
# Prüfe auf PresenceEngine/presence
|
||||
_update_presence_hits="$(journalctl --user -u hermes-gateway --since "$_verify_since" --no-pager 2>/dev/null | grep -c -i 'PresenceEngine\|presence' || true)"
|
||||
_update_presence_hits="$(gateway_journalctl --since "$_verify_since" --no-pager 2>/dev/null | grep -c -i 'PresenceEngine\\|presence' || true)"
|
||||
if [ "${_update_presence_hits:-0}" -gt 0 ]; then
|
||||
ok "PresenceEngine im Log gefunden ($_update_presence_hits Treffer)"
|
||||
else
|
||||
@@ -1343,7 +1503,7 @@ if $UPDATE_ONLY; then
|
||||
fi
|
||||
|
||||
# Prüfe auf 'Archivar initialisiert'
|
||||
_update_archivar_hits="$(journalctl --user -u hermes-gateway --since "$_verify_since" --no-pager 2>/dev/null | grep -c 'Archivar initialisiert' || true)"
|
||||
_update_archivar_hits="$(gateway_journalctl --since "$_verify_since" --no-pager 2>/dev/null | grep -c 'Archivar initialisiert' || true)"
|
||||
if [ "${_update_archivar_hits:-0}" -gt 0 ]; then
|
||||
ok "'Archivar initialisiert' im Log gefunden ($_update_archivar_hits Treffer)"
|
||||
else
|
||||
@@ -1352,7 +1512,7 @@ if $UPDATE_ONLY; then
|
||||
fi
|
||||
|
||||
# Prüfe auf 'Connected to'
|
||||
_update_connected_hits="$(journalctl --user -u hermes-gateway --since "$_verify_since" --no-pager 2>/dev/null | grep -c 'Connected to' || true)"
|
||||
_update_connected_hits="$(gateway_journalctl --since "$_verify_since" --no-pager 2>/dev/null | grep -c 'Connected to' || true)"
|
||||
if [ "${_update_connected_hits:-0}" -gt 0 ]; then
|
||||
ok "'Connected to' im Log gefunden ($_update_connected_hits Treffer)"
|
||||
else
|
||||
@@ -1447,6 +1607,6 @@ verify_installation
|
||||
if ! $DRY_RUN; then
|
||||
echo ""
|
||||
ok "Fertig. Bot sollte laufen — prüfe mit:"
|
||||
echo " systemctl --user status hermes-gateway"
|
||||
echo " journalctl --user -u hermes-gateway -f"
|
||||
echo " gateway_systemctl status"
|
||||
echo " gateway_journalctl -f"
|
||||
fi
|
||||
+63
-12
@@ -314,6 +314,8 @@ class DDPClient:
|
||||
self._loop: Optional[asyncio.AbstractEventLoop] = None
|
||||
self._result_lock = threading.Lock()
|
||||
self._msg_seq: int = 0
|
||||
# P0: Resolved RC username from DDP login response (not from env)
|
||||
self._rc_username: Optional[str] = None
|
||||
|
||||
def _create_socket(self) -> socket.socket:
|
||||
ctx = ssl.create_default_context()
|
||||
@@ -608,7 +610,29 @@ class DDPClient:
|
||||
if "error" in data:
|
||||
future.set_exception(DDPServerError(data["error"]))
|
||||
else:
|
||||
future.set_result(data.get("result", True))
|
||||
result = data.get("result", True)
|
||||
future.set_result(result)
|
||||
|
||||
# P0: Extract RC username from DDP login response
|
||||
# The login result contains {"id": <userId>, "username": <rcUsername>, ...}
|
||||
# We need the real RC username (not the env email) for the own-message filter.
|
||||
if msg_id == "ddplogin" and isinstance(result, dict):
|
||||
resolved = result.get("username")
|
||||
if resolved:
|
||||
self._rc_username = resolved
|
||||
logger.info("[ddp] Resolved RC username from login: %s", resolved)
|
||||
|
||||
def get_logged_in_username(self) -> Optional[str]:
|
||||
"""Return the RC username resolved from the DDP login response.
|
||||
|
||||
Returns None if the login response has not been processed yet
|
||||
(e.g., during reconnect with resume token, or before the first
|
||||
result message arrives).
|
||||
|
||||
Returns:
|
||||
The resolved RC username string, or None.
|
||||
"""
|
||||
return self._rc_username
|
||||
|
||||
def set_status(self, status: str) -> bool:
|
||||
"""Set the user presence status via DDP (fire-and-forget, no await).
|
||||
@@ -1068,6 +1092,9 @@ class RocketChatAdapter(BasePlatformAdapter):
|
||||
|
||||
Sets initial online status and binds DDP to PulseController
|
||||
if PresenceEngine is active (EC-1: on_connected_cb race).
|
||||
|
||||
P1b: Starts DetectionTimer after DDP connection is established
|
||||
to prevent race condition with gateway_state.json.
|
||||
"""
|
||||
if self.ddp:
|
||||
self.ddp.set_status("online")
|
||||
@@ -1078,6 +1105,12 @@ class RocketChatAdapter(BasePlatformAdapter):
|
||||
logger.debug("[rocketchat] V8.6: PulseController DDP gebunden (on_connected_cb)")
|
||||
except Exception as e:
|
||||
logger.debug("[rocketchat] V8.6: PulseController bind_ddp failed: %s", e)
|
||||
# P1b: DetectionTimer erst nach DDP-Connect starten
|
||||
try:
|
||||
self._presence_engine.start_detection()
|
||||
logger.debug("[rocketchat] P1b: DetectionTimer gestartet (on_connected_cb)")
|
||||
except Exception as e:
|
||||
logger.debug("[rocketchat] P1b: DetectionTimer start failed: %s", e)
|
||||
|
||||
def _on_ddp_room_event(self, event: dict) -> None:
|
||||
"""A1b: Callback für DDP rooms-changed Events.
|
||||
@@ -1443,6 +1476,21 @@ class RocketChatAdapter(BasePlatformAdapter):
|
||||
if not self.ddp.connect_and_login(self._auth_token):
|
||||
logger.error("[rocketchat] DDP connect/login failed")
|
||||
return False
|
||||
|
||||
# P0: Resolve self.user from DDP login response (not blind from env).
|
||||
# connect_and_login() returns before the async result message arrives,
|
||||
# so we retry briefly until the DDP reader thread processes it.
|
||||
for _retry in range(10):
|
||||
resolved = self.ddp.get_logged_in_username()
|
||||
if resolved:
|
||||
self.user = resolved.lower()
|
||||
logger.info("[rocketchat] Resolved self.user from login: %s", self.user)
|
||||
break
|
||||
time.sleep(0.1)
|
||||
else:
|
||||
# Fallback: keep the env value (ROCKETCHAT_USER)
|
||||
logger.info("[rocketchat] Login username not resolved — keeping env value: %s", self.user)
|
||||
|
||||
self._rooms = self.rest.get_rooms()
|
||||
logger.info("[rocketchat] REST get_rooms returned %d rooms", len(self._rooms))
|
||||
|
||||
@@ -1695,6 +1743,14 @@ class RocketChatAdapter(BasePlatformAdapter):
|
||||
logger.error("[rocketchat] _reconnect_ddp: DDP connect/login failed")
|
||||
return False
|
||||
|
||||
# P0: On reconnect, only update self.user if a new username was resolved.
|
||||
# Resume-token reconnects don't produce a new result message, so
|
||||
# get_logged_in_username() returns None — keep the existing self.user.
|
||||
resolved = self.ddp.get_logged_in_username()
|
||||
if resolved:
|
||||
self.user = resolved.lower()
|
||||
logger.info("[rocketchat] Resolved self.user from login (reconnect): %s", self.user)
|
||||
|
||||
# P1-2 O-2: Re-bind asyncio loop to new DDPClient and PulseController
|
||||
try:
|
||||
loop = asyncio.get_running_loop()
|
||||
@@ -1903,16 +1959,13 @@ class RocketChatAdapter(BasePlatformAdapter):
|
||||
room_type = self._room_info.get(room_id, {}).get("type", "unknown")
|
||||
logger.info("[rocketchat] Message from %s in %s [%s]: %s", username, room_name, room_type, text[:80])
|
||||
|
||||
# ── V8.6: PresenceEngine — active_tasks++ und busy setzen ──
|
||||
# ── V8.6 P1a: PresenceEngine — mark_busy_started (Honeymoon-Timer) ──
|
||||
# Graceful degradation: wenn _presence_engine nicht existiert
|
||||
# (z.B. in Tests die __new__ statt __init__ verwenden), skip.
|
||||
_has_presence = hasattr(self, '_presence_engine') and self._presence_engine is not None
|
||||
if _has_presence:
|
||||
self._presence_engine.set_current_room(room_name)
|
||||
self._presence_engine.increment_active_tasks()
|
||||
self._presence_engine.update_presence()
|
||||
logger.info("[presence] active_tasks++ → %d (room=%s)",
|
||||
self._presence_engine._active_tasks, room_name)
|
||||
self._presence_engine.mark_busy_started(room_name=room_name)
|
||||
logger.info("[presence] mark_busy_started (room=%s)", room_name)
|
||||
|
||||
try:
|
||||
# ── R5: Inline-Command-Erkennung (VOR Onboarding + Hermes-Dispatch) ──
|
||||
@@ -3097,15 +3150,13 @@ class RocketChatAdapter(BasePlatformAdapter):
|
||||
except Exception as e2:
|
||||
logger.error("[rocketchat] COMMAND text fallback also failed: %s", e2)
|
||||
finally:
|
||||
# ── V8.6 P1-3: PresenceEngine — active_tasks-- immer ausführen ──
|
||||
# ── V8.6 P1a: PresenceEngine — mark_busy_done (Honeymoon-Timer) ──
|
||||
# try/finally garantiert decrement auch bei Exceptions/Errors.
|
||||
if _has_presence:
|
||||
self._presence_engine.decrement_active_tasks()
|
||||
self._presence_engine.update_presence()
|
||||
self._presence_engine.mark_busy_done()
|
||||
# P1-2: current_room zurücksetzen nach Verarbeitung
|
||||
self._presence_engine.set_current_room("")
|
||||
logger.info("[presence] active_tasks-- → %d (turn complete)",
|
||||
self._presence_engine._active_tasks)
|
||||
logger.info("[presence] mark_busy_done (turn complete)")
|
||||
|
||||
# ── R5: Inline-Command-Handler ────────────────────────────────────────
|
||||
|
||||
|
||||
@@ -80,8 +80,14 @@ class PresenceEngine:
|
||||
Thread-safe: uses threading.Lock for all counter operations.
|
||||
Coalesce-Timer: prevents flickering by delaying status updates by 2s.
|
||||
Heartbeat: pulses online↔away when background_tasks > 0 and agent is idle.
|
||||
|
||||
P1a: Honeymoon-Timer ensures busy status is visible for at least
|
||||
MIN_BUSY_VISIBLE_S (1.0s) before transitioning to online.
|
||||
"""
|
||||
|
||||
# P1a: Minimum time busy status must be visible (prevents coalesce race)
|
||||
MIN_BUSY_VISIBLE_S = 1.0
|
||||
|
||||
def __init__(
|
||||
self,
|
||||
rest=None,
|
||||
@@ -137,6 +143,12 @@ class PresenceEngine:
|
||||
self._background_tasks: int = 0
|
||||
self._background_tasks_lock = threading.Lock()
|
||||
|
||||
# P1a: Honeymoon-Timer — busy status minimum 1s sichtbar
|
||||
self._busy_started_at: float = 0.0 # time.monotonic() when busy started
|
||||
self._busy_honeymoon_timer: Optional[threading.Timer] = None
|
||||
self._busy_honeymoon_lock = threading.Lock()
|
||||
self._busy_counter: int = 0 # multi-turn: count concurrent busy starts
|
||||
|
||||
# P0-1: PulseController — DDP-basierte Heartbeat-Pulsierung (1.5s)
|
||||
self._pulse_controller = PulseController(
|
||||
pulse_interval=pulse_interval,
|
||||
@@ -150,9 +162,10 @@ class PresenceEngine:
|
||||
on_change=self._on_detection_change,
|
||||
)
|
||||
|
||||
# Start detection if enabled
|
||||
if self._enabled:
|
||||
self._detection_timer.start()
|
||||
# P1b: DetectionTimer NICHT im Init starten — erst nach on_connected_cb.
|
||||
# Der Adapter ruft _detection_timer.start() explizit auf, sobald die
|
||||
# DDP-Verbindung steht. Das verhindert eine Race-Condition bei der
|
||||
# ersten gateway_state.json-Auswertung (Datei existiert ggf. noch nicht).
|
||||
|
||||
# ── Public API ───────────────────────────────────────────────────────
|
||||
|
||||
@@ -160,10 +173,20 @@ class PresenceEngine:
|
||||
"""Check if presence updates are enabled."""
|
||||
return self._enabled
|
||||
|
||||
def start_detection(self) -> None:
|
||||
"""P1b: Start DetectionTimer — called after DDP connection is established.
|
||||
|
||||
Must be called explicitly by the adapter in on_connected_cb.
|
||||
Prevents race condition where gateway_state.json doesn't exist yet
|
||||
at PresenceEngine init time.
|
||||
"""
|
||||
if self._enabled:
|
||||
self._detection_timer.start()
|
||||
|
||||
def enable(self) -> None:
|
||||
"""Enable presence updates. Starts DetectionTimer."""
|
||||
"""Enable presence updates. DetectionTimer must be started externally
|
||||
via start_detection() after DDP connection is established."""
|
||||
self._enabled = True
|
||||
self._detection_timer.start()
|
||||
logger.info("[presence] PresenceEngine enabled")
|
||||
|
||||
def disable(self) -> None:
|
||||
@@ -201,6 +224,115 @@ class PresenceEngine:
|
||||
logger.info("[presence] active_tasks=0 → pulse resumed")
|
||||
return count
|
||||
|
||||
# ── P1a: Honeymoon-Timer — busy minimum 1s sichtbar ──────────────────
|
||||
|
||||
def mark_busy_started(self, room_name: str = "") -> None:
|
||||
"""P1a: Mark the start of a busy period with honeymoon protection.
|
||||
|
||||
Sets the room, increments active_tasks, and schedules a busy status.
|
||||
If a honeymoon timer is already running (multi-turn), only increments
|
||||
the counter — no duplicate timer.
|
||||
|
||||
Args:
|
||||
room_name: Room name for the busy status message.
|
||||
"""
|
||||
self.set_current_room(room_name)
|
||||
self.increment_active_tasks()
|
||||
self.update_presence() # sets pending_status="busy"
|
||||
# P1a: Busy sofort flushen — nicht auf 2s Coalesce warten.
|
||||
# Der Honeymoon-Timer (1s) würde sonst vor dem Coalesce feuern.
|
||||
self._flush_presence()
|
||||
|
||||
with self._busy_honeymoon_lock:
|
||||
self._busy_counter += 1
|
||||
if self._busy_honeymoon_timer is None:
|
||||
# First busy start — record time and start honeymoon timer
|
||||
self._busy_started_at = time.monotonic()
|
||||
self._busy_honeymoon_timer = threading.Timer(
|
||||
self.MIN_BUSY_VISIBLE_S,
|
||||
self._honeymoon_expired,
|
||||
)
|
||||
self._busy_honeymoon_timer.daemon = True
|
||||
self._busy_honeymoon_timer.start()
|
||||
logger.debug(
|
||||
"[presence] Honeymoon-Timer gestartet (%.1fs), counter=%d",
|
||||
self.MIN_BUSY_VISIBLE_S, self._busy_counter,
|
||||
)
|
||||
else:
|
||||
logger.debug(
|
||||
"[presence] Honeymoon-Timer läuft bereits, counter=%d",
|
||||
self._busy_counter,
|
||||
)
|
||||
|
||||
def mark_busy_done(self) -> None:
|
||||
"""P1a: Mark the end of a busy period.
|
||||
|
||||
Decrements the busy counter. If the counter reaches 0 and the
|
||||
honeymoon has elapsed, transitions to online immediately.
|
||||
If the honeymoon hasn't elapsed yet, the timer callback will
|
||||
handle the transition when it fires.
|
||||
|
||||
Must be called in a finally block to ensure counter balance
|
||||
even on exceptions.
|
||||
"""
|
||||
with self._busy_honeymoon_lock:
|
||||
if self._busy_counter > 0:
|
||||
self._busy_counter -= 1
|
||||
counter = self._busy_counter
|
||||
|
||||
# Decrement the underlying active_tasks counter
|
||||
self.decrement_active_tasks()
|
||||
|
||||
if counter == 0:
|
||||
elapsed = time.monotonic() - self._busy_started_at
|
||||
if elapsed >= self.MIN_BUSY_VISIBLE_S:
|
||||
# Honeymoon already elapsed — transition to online now
|
||||
self._cancel_honeymoon_timer()
|
||||
self.update_presence()
|
||||
logger.debug(
|
||||
"[presence] Honeymoon abgelaufen (%.2fs) → online", elapsed,
|
||||
)
|
||||
else:
|
||||
# Honeymoon still running — timer callback will handle it
|
||||
logger.debug(
|
||||
"[presence] Honeymoon läuft noch (%.2fs/%.1fs) — Timer übernimmt",
|
||||
elapsed, self.MIN_BUSY_VISIBLE_S,
|
||||
)
|
||||
else:
|
||||
logger.debug(
|
||||
"[presence] mark_busy_done: counter=%d (weitere Tasks aktiv)", counter,
|
||||
)
|
||||
|
||||
def _honeymoon_expired(self) -> None:
|
||||
"""P1a: Honeymoon timer callback — transition to online if idle.
|
||||
|
||||
Called by threading.Timer after MIN_BUSY_VISIBLE_S.
|
||||
If no active tasks remain, sets status to online.
|
||||
"""
|
||||
with self._busy_honeymoon_lock:
|
||||
self._busy_honeymoon_timer = None
|
||||
|
||||
with self._active_tasks_lock:
|
||||
active = self._active_tasks
|
||||
|
||||
if active == 0:
|
||||
logger.info(
|
||||
"[presence] Honeymoon-Timer abgelaufen, active_tasks=0 → online"
|
||||
)
|
||||
self.update_presence()
|
||||
else:
|
||||
logger.debug(
|
||||
"[presence] Honeymoon-Timer abgelaufen, aber active_tasks=%d — kein Wechsel",
|
||||
active,
|
||||
)
|
||||
|
||||
def _cancel_honeymoon_timer(self) -> None:
|
||||
"""P1a: Cancel the honeymoon timer if running."""
|
||||
with self._busy_honeymoon_lock:
|
||||
if self._busy_honeymoon_timer is not None:
|
||||
self._busy_honeymoon_timer.cancel()
|
||||
self._busy_honeymoon_timer = None
|
||||
|
||||
def set_onboarding_active(self, active: bool) -> None:
|
||||
"""Set the onboarding sentinel."""
|
||||
self._onboarding_active = active
|
||||
@@ -429,6 +561,7 @@ class PresenceEngine:
|
||||
"""Clean shutdown: stop PulseController, DetectionTimer, cancel coalesce timer."""
|
||||
self._pulse_controller.stop()
|
||||
self._detection_timer.stop()
|
||||
self._cancel_honeymoon_timer()
|
||||
with self._coalesce_lock:
|
||||
if self._coalesce_timer is not None:
|
||||
self._coalesce_timer.cancel()
|
||||
@@ -810,8 +943,12 @@ class PulseController:
|
||||
class DetectionTimer:
|
||||
"""Detects whether background agents are active.
|
||||
|
||||
Checks gateway_state.json for active_agents > 1.
|
||||
Falls back to pgrep for 'hermes chat --profile' processes.
|
||||
P1b: gateway_state.json is PRIMARY — active_agents > 1 means active.
|
||||
pgrep is SECONDARY/CONFIRM — used as fallback when gateway_state is
|
||||
unavailable or returns 0/1 (ambiguous).
|
||||
|
||||
pgrep pattern: 'hermes_cli|hermes chat' (catches subagents AND gateway
|
||||
subprocesses). Self-pid exclude is preserved.
|
||||
|
||||
Calls on_change callback when detection state changes.
|
||||
"""
|
||||
@@ -870,53 +1007,66 @@ class DetectionTimer:
|
||||
def check(self) -> bool:
|
||||
"""Check if background agents are active.
|
||||
|
||||
pgrep is the PRIMARY signal — always executed, regardless of gateway_state.
|
||||
gateway_state is SECONDARY — read only for diagnostic logging, never for decisions.
|
||||
P1b: gateway_state.json is PRIMARY — active_agents > 1 means active.
|
||||
pgrep is SECONDARY/CONFIRM — used as fallback when gateway_state is
|
||||
unavailable or returns 0/1 (ambiguous).
|
||||
|
||||
pgrep pattern expanded from 'hermes chat --profile' to
|
||||
'hermes_cli|hermes chat' to catch subagents AND gateway subprocesses.
|
||||
Self-pid exclude is preserved.
|
||||
|
||||
Returns:
|
||||
True if pgrep finds other hermes chat processes (self-excluded),
|
||||
False otherwise.
|
||||
True if background agents are detected, False otherwise.
|
||||
"""
|
||||
self._check_count += 1
|
||||
self._increment_telemetry()
|
||||
|
||||
result = False
|
||||
pgrep_pids = -1 # -1 = not yet run, >=0 = count, stays -1 on error
|
||||
|
||||
# ── PRIMARY: pgrep — ALWAYS run ──────────────────────────────────
|
||||
try:
|
||||
own_pid = os.getpid()
|
||||
proc = subprocess.run(
|
||||
["pgrep", "-f", "hermes chat --profile"],
|
||||
capture_output=True,
|
||||
text=True,
|
||||
timeout=5,
|
||||
)
|
||||
# Parse PIDs and self-exclude
|
||||
raw_lines = [l.strip() for l in proc.stdout.strip().split("\n") if l.strip()]
|
||||
all_pids = [int(l) for l in raw_lines if l.isdigit()]
|
||||
pids = [p for p in all_pids if p != own_pid]
|
||||
pgrep_pids = len(pids)
|
||||
result = pgrep_pids > 0
|
||||
except (subprocess.TimeoutExpired, FileNotFoundError, OSError, ValueError) as e:
|
||||
logger.debug("[detection] pgrep failed: %s", e)
|
||||
# pgrep_pids stays -1 (error sentinel)
|
||||
|
||||
# ── SECONDARY: gateway_state — diagnostic only ────────────────────
|
||||
gateway_active = 0
|
||||
gateway_used = False # True if gateway_state was the deciding signal
|
||||
|
||||
# ── PRIMARY: gateway_state.json ────────────────────────────────────
|
||||
try:
|
||||
if os.path.exists(self._gateway_state_path):
|
||||
with open(self._gateway_state_path, 'r') as f:
|
||||
state = json.load(f)
|
||||
gateway_active = state.get("active_agents", 0)
|
||||
if gateway_active > 1:
|
||||
result = True
|
||||
gateway_used = True
|
||||
except (json.JSONDecodeError, IOError, OSError) as e:
|
||||
logger.debug("[detection] gateway_state.json read failed: %s", e)
|
||||
# Fall through to pgrep
|
||||
|
||||
# ── SECONDARY: pgrep — run when gateway_state didn't decide ───────
|
||||
if not gateway_used:
|
||||
try:
|
||||
own_pid = os.getpid()
|
||||
# P1b: Expanded pattern catches subagents AND gateway subprocesses
|
||||
proc = subprocess.run(
|
||||
["pgrep", "-f", "hermes_cli|hermes chat"],
|
||||
capture_output=True,
|
||||
text=True,
|
||||
timeout=5,
|
||||
)
|
||||
# Parse PIDs and self-exclude
|
||||
raw_lines = [l.strip() for l in proc.stdout.strip().split("\n") if l.strip()]
|
||||
all_pids = [int(l) for l in raw_lines if l.isdigit()]
|
||||
pids = [p for p in all_pids if p != own_pid]
|
||||
pgrep_pids = len(pids)
|
||||
result = pgrep_pids > 0
|
||||
except (subprocess.TimeoutExpired, FileNotFoundError, OSError, ValueError) as e:
|
||||
logger.debug("[detection] pgrep failed: %s", e)
|
||||
# pgrep_pids stays -1 (error sentinel)
|
||||
|
||||
# ── Log: both signals, result ─────────────────────────────────────
|
||||
pgrep_str = str(pgrep_pids) if pgrep_pids >= 0 else "error"
|
||||
logger.info(
|
||||
"[detection] check #%d: pgrep=%s, gateway_state=%d, result=%s",
|
||||
self._check_count, pgrep_str, gateway_active,
|
||||
"[detection] check #%d: gateway_state=%d (primary=%s), pgrep=%s, result=%s",
|
||||
self._check_count, gateway_active,
|
||||
"yes" if gateway_used else "no",
|
||||
pgrep_str,
|
||||
"active" if result else "inactive",
|
||||
)
|
||||
|
||||
|
||||
@@ -880,17 +880,17 @@ class TestPulseControllerLastSentPhase:
|
||||
|
||||
|
||||
class TestDetectionTimerPgrepPrimary:
|
||||
"""Test 20: DetectionTimer — pgrep als Primärsignal, gateway_state nur diagnostisch."""
|
||||
"""Test 20: DetectionTimer — gateway_state PRIMARY, pgrep SECONDARY (P1b)."""
|
||||
|
||||
def test_pgrep_finds_other_agents(self):
|
||||
"""pgrep findet andere hermes-Prozesse → result=True (gateway_state irrelevant)."""
|
||||
"""gateway_state=1 (nicht >1) → pgrep-Fallback findet anderen Prozess → result=True."""
|
||||
from plugin.archivar.presence_engine import DetectionTimer
|
||||
import tempfile
|
||||
import json
|
||||
|
||||
own_pid = os.getpid()
|
||||
|
||||
# gateway_state mit active_agents=1 (würde früher False liefern)
|
||||
# gateway_state mit active_agents=1 (nicht >1 → fällt auf pgrep zurück)
|
||||
state = {"active_agents": 1, "profiles": ["default"]}
|
||||
with tempfile.NamedTemporaryFile(suffix=".json", delete=False, mode="w") as f:
|
||||
json.dump(state, f)
|
||||
@@ -910,50 +910,44 @@ class TestDetectionTimerPgrepPrimary:
|
||||
detection_interval=0.1,
|
||||
)
|
||||
result = dt.check()
|
||||
# pgrep findet anderen Prozess → True (gateway_state=1 wird ignoriert)
|
||||
# gateway_state=1 → pgrep-Fallback findet anderen Prozess → True
|
||||
assert result is True
|
||||
finally:
|
||||
os.unlink(state_path)
|
||||
|
||||
def test_pgrep_finds_no_other_agents(self):
|
||||
"""pgrep findet nur eigenen Prozess → result=False (gateway_state irrelevant)."""
|
||||
def test_gateway_state_primary_active(self):
|
||||
"""P1b: gateway_state active_agents=3 (>1) → PRIMARY entscheidet → result=True, pgrep NICHT aufgerufen."""
|
||||
from plugin.archivar.presence_engine import DetectionTimer
|
||||
import tempfile
|
||||
import json
|
||||
|
||||
own_pid = os.getpid()
|
||||
|
||||
# gateway_state mit active_agents=3 (würde früher True liefern)
|
||||
# gateway_state mit active_agents=3 (>1 → PRIMARY entscheidet)
|
||||
state = {"active_agents": 3, "profiles": ["default", "miguel", "anna"]}
|
||||
with tempfile.NamedTemporaryFile(suffix=".json", delete=False, mode="w") as f:
|
||||
json.dump(state, f)
|
||||
state_path = f.name
|
||||
|
||||
try:
|
||||
# Mock pgrep: findet nur eigenen Prozess
|
||||
# Mock pgrep: sollte NICHT aufgerufen werden
|
||||
with patch('plugin.archivar.presence_engine.subprocess.run') as mock_run:
|
||||
mock_run.return_value = MagicMock(
|
||||
stdout=f"{own_pid}\n",
|
||||
stderr="",
|
||||
returncode=0,
|
||||
)
|
||||
|
||||
dt = DetectionTimer(
|
||||
gateway_state_path=state_path,
|
||||
detection_interval=0.1,
|
||||
)
|
||||
result = dt.check()
|
||||
# pgrep findet nur eigenen Prozess → False (gateway_state=3 wird ignoriert)
|
||||
assert result is False
|
||||
# gateway_state=3 > 1 → PRIMARY entscheidet → True
|
||||
assert result is True
|
||||
# pgrep wurde NICHT aufgerufen (gateway_state hat entschieden)
|
||||
mock_run.assert_not_called()
|
||||
finally:
|
||||
os.unlink(state_path)
|
||||
|
||||
|
||||
class TestDetectionTimerPgrepNoGatewayState:
|
||||
"""Test 21: DetectionTimer pgrep funktioniert auch ohne gateway_state.json."""
|
||||
"""Test 21: DetectionTimer pgrep-Fallback funktioniert auch ohne gateway_state.json (P1b)."""
|
||||
|
||||
def test_pgrep_works_without_gateway_state(self):
|
||||
"""Wenn gateway_state.json nicht existiert, pgrep ist trotzdem Primärsignal."""
|
||||
"""Wenn gateway_state.json nicht existiert, pgrep-Fallback greift."""
|
||||
from plugin.archivar.presence_engine import DetectionTimer
|
||||
|
||||
own_pid = os.getpid()
|
||||
@@ -997,10 +991,10 @@ class TestDetectionTimerPgrepNoGatewayState:
|
||||
|
||||
|
||||
class TestDetectionTimerIntegration:
|
||||
"""Test 22: DetectionTimer start/stop + Callback (pgrep als Primärsignal)."""
|
||||
"""Test 22: DetectionTimer start/stop + Callback (P1b: gateway_state PRIMARY, pgrep SECONDARY)."""
|
||||
|
||||
def test_detection_timer_start_stop(self):
|
||||
"""DetectionTimer startet und stoppt korrekt, pgrep als Primärsignal."""
|
||||
"""DetectionTimer startet und stoppt korrekt, pgrep-Fallback bei fehlendem gateway_state."""
|
||||
from plugin.archivar.presence_engine import DetectionTimer
|
||||
|
||||
own_pid = os.getpid()
|
||||
@@ -1009,7 +1003,7 @@ class TestDetectionTimerIntegration:
|
||||
def on_detection_change(is_active):
|
||||
callback_results.append(is_active)
|
||||
|
||||
# Mock pgrep: findet anderen Prozess → True
|
||||
# Mock pgrep: findet anderen Prozess → True (gateway_state fehlt → Fallback)
|
||||
with patch('plugin.archivar.presence_engine.subprocess.run') as mock_run:
|
||||
mock_run.return_value = MagicMock(
|
||||
stdout=f"{own_pid}\n99999\n",
|
||||
@@ -1264,7 +1258,7 @@ class TestP0LiveVerdrahtung:
|
||||
assert not engine._pulse_controller.is_running()
|
||||
|
||||
def test_detection_timer_starts_when_enabled(self):
|
||||
"""P0-5: DetectionTimer startet automatisch wenn enabled=True."""
|
||||
"""P1b: DetectionTimer startet NICHT automatisch — muss via start_detection() gestartet werden."""
|
||||
from plugin.archivar.presence_engine import PresenceEngine
|
||||
|
||||
mock_rest = MagicMock()
|
||||
@@ -1273,7 +1267,11 @@ class TestP0LiveVerdrahtung:
|
||||
|
||||
engine = PresenceEngine(rest=mock_rest, enabled=True)
|
||||
|
||||
# DetectionTimer läuft (wurde in __init__ gestartet)
|
||||
# P1b: DetectionTimer läuft NICHT nach __init__ (startet erst via start_detection())
|
||||
assert not engine._detection_timer._running.is_set()
|
||||
|
||||
# start_detection() startet ihn
|
||||
engine.start_detection()
|
||||
assert engine._detection_timer._running.is_set()
|
||||
|
||||
def test_detection_timer_not_started_when_disabled(self):
|
||||
@@ -1536,3 +1534,202 @@ class TestPresenceClarificationPending:
|
||||
f"Klärung sollte away setzen (nicht busy), bekam: {data['status']}"
|
||||
)
|
||||
assert "Klärung" in data["message"]
|
||||
|
||||
|
||||
# ═══════════════════════════════════════════════════════════════════════════
|
||||
# P1a: Honeymoon-Timer — busy minimum 1s sichtbar
|
||||
# ═══════════════════════════════════════════════════════════════════════════
|
||||
|
||||
|
||||
class TestHoneymoonBusyMinVisible:
|
||||
"""P1a: Honeymoon-Timer — busy Status mindestens 1s sichtbar."""
|
||||
|
||||
def test_busy_min_visible_duration(self):
|
||||
"""mark_busy_started → mark_busy_done innerhalb 50ms → pending_status bleibt busy bis Timer feuert."""
|
||||
from plugin.archivar.presence_engine import PresenceEngine
|
||||
|
||||
mock_rest = MagicMock()
|
||||
mock_rest.auth_token = "token"
|
||||
mock_rest.user_id = "user123"
|
||||
mock_rest._request = MagicMock(return_value={"success": True})
|
||||
|
||||
engine = PresenceEngine(rest=mock_rest, enabled=True)
|
||||
|
||||
# Start busy
|
||||
engine.mark_busy_started(room_name="#Test")
|
||||
assert engine._active_tasks == 1
|
||||
assert engine._busy_counter == 1
|
||||
assert engine._busy_honeymoon_timer is not None
|
||||
|
||||
# Done sofort (50ms später — Honeymoon noch nicht abgelaufen)
|
||||
time.sleep(0.05)
|
||||
engine.mark_busy_done()
|
||||
assert engine._active_tasks == 0
|
||||
assert engine._busy_counter == 0
|
||||
|
||||
# Honeymoon-Timer läuft noch → pending_status sollte busy sein
|
||||
# (update_presence wurde NICHT aufgerufen, weil Honeymoon noch läuft)
|
||||
# Warte auf Honeymoon-Expiry
|
||||
time.sleep(1.1) # MIN_BUSY_VISIBLE_S + margin
|
||||
|
||||
# Jetzt sollte der Timer gefeuert haben → online
|
||||
# Flush um sicherzustellen
|
||||
engine._flush_presence()
|
||||
|
||||
# Prüfe: REST-Calls in Reihenfolge: erst busy, dann online
|
||||
calls = mock_rest._request.call_args_list
|
||||
assert len(calls) >= 2, f"Erwarte mind. 2 REST-Calls (busy + online), bekam {len(calls)}"
|
||||
# Erster Call: busy
|
||||
assert calls[0][1]["data"]["status"] == "busy"
|
||||
# Letzter Call: online
|
||||
assert calls[-1][1]["data"]["status"] == "online"
|
||||
|
||||
def test_busy_done_after_honeymoon(self):
|
||||
"""Nach 1.05s ist Honeymoon abgelaufen → mark_busy_done setzt sofort online."""
|
||||
from plugin.archivar.presence_engine import PresenceEngine
|
||||
|
||||
mock_rest = MagicMock()
|
||||
mock_rest.auth_token = "token"
|
||||
mock_rest.user_id = "user123"
|
||||
mock_rest._request = MagicMock(return_value={"success": True})
|
||||
|
||||
engine = PresenceEngine(rest=mock_rest, enabled=True)
|
||||
|
||||
engine.mark_busy_started(room_name="#Test")
|
||||
assert engine._active_tasks == 1
|
||||
|
||||
# Warte bis Honeymoon abgelaufen ist
|
||||
time.sleep(1.1)
|
||||
|
||||
engine.mark_busy_done()
|
||||
# Honeymoon bereits abgelaufen → update_presence wurde aufgerufen
|
||||
engine._flush_presence()
|
||||
|
||||
calls = mock_rest._request.call_args_list
|
||||
assert len(calls) >= 2
|
||||
assert calls[0][1]["data"]["status"] == "busy"
|
||||
assert calls[-1][1]["data"]["status"] == "online"
|
||||
|
||||
def test_double_busy_no_double_honeymoon(self):
|
||||
"""Zweiter mark_busy_started während Honeymoon läuft → nur EIN Timer aktiv."""
|
||||
from plugin.archivar.presence_engine import PresenceEngine
|
||||
|
||||
mock_rest = MagicMock()
|
||||
mock_rest.auth_token = "token"
|
||||
mock_rest.user_id = "user123"
|
||||
mock_rest._request = MagicMock(return_value={"success": True})
|
||||
|
||||
engine = PresenceEngine(rest=mock_rest, enabled=True)
|
||||
|
||||
# Erster busy
|
||||
engine.mark_busy_started(room_name="#Test")
|
||||
first_timer = engine._busy_honeymoon_timer
|
||||
assert first_timer is not None
|
||||
assert engine._busy_counter == 1
|
||||
|
||||
# Zweiter busy (multi-turn) — kein neuer Timer
|
||||
engine.mark_busy_started(room_name="#Test2")
|
||||
assert engine._busy_honeymoon_timer is first_timer # gleicher Timer
|
||||
assert engine._busy_counter == 2
|
||||
|
||||
# Erster done → counter=1, Timer läuft weiter
|
||||
engine.mark_busy_done()
|
||||
assert engine._busy_counter == 1
|
||||
assert engine._active_tasks == 1
|
||||
|
||||
# Zweiter done → counter=0, Honeymoon noch nicht abgelaufen
|
||||
engine.mark_busy_done()
|
||||
assert engine._busy_counter == 0
|
||||
assert engine._active_tasks == 0
|
||||
|
||||
# Warte auf Honeymoon
|
||||
time.sleep(1.1)
|
||||
engine._flush_presence()
|
||||
|
||||
calls = mock_rest._request.call_args_list
|
||||
assert len(calls) >= 2
|
||||
assert calls[0][1]["data"]["status"] == "busy"
|
||||
assert calls[-1][1]["data"]["status"] == "online"
|
||||
|
||||
def test_active_tasks_balanced(self):
|
||||
"""100x mark_busy_started/mark_busy_done → _active_tasks == 0, _busy_counter == 0."""
|
||||
from plugin.archivar.presence_engine import PresenceEngine
|
||||
|
||||
mock_rest = MagicMock()
|
||||
mock_rest.auth_token = "token"
|
||||
mock_rest.user_id = "user123"
|
||||
mock_rest._request = MagicMock(return_value={"success": True})
|
||||
|
||||
engine = PresenceEngine(rest=mock_rest, enabled=True)
|
||||
|
||||
for _ in range(100):
|
||||
engine.mark_busy_started(room_name="#Test")
|
||||
assert engine._active_tasks == 100
|
||||
assert engine._busy_counter == 100
|
||||
|
||||
for _ in range(100):
|
||||
engine.mark_busy_done()
|
||||
assert engine._active_tasks == 0
|
||||
assert engine._busy_counter == 0
|
||||
|
||||
def test_exception_during_dispatch_releases_busy(self):
|
||||
"""Exception während Dispatch → mark_busy_done balanced Counter, Honeymoon läuft."""
|
||||
from plugin.archivar.presence_engine import PresenceEngine
|
||||
|
||||
mock_rest = MagicMock()
|
||||
mock_rest.auth_token = "token"
|
||||
mock_rest.user_id = "user123"
|
||||
mock_rest._request = MagicMock(return_value={"success": True})
|
||||
|
||||
engine = PresenceEngine(rest=mock_rest, enabled=True)
|
||||
|
||||
try:
|
||||
engine.mark_busy_started(room_name="#Test")
|
||||
raise RuntimeError("simulated dispatch failure")
|
||||
except RuntimeError:
|
||||
engine.mark_busy_done()
|
||||
|
||||
# Counter balanced
|
||||
assert engine._active_tasks == 0
|
||||
assert engine._busy_counter == 0
|
||||
|
||||
# Honeymoon-Timer läuft noch (oder ist schon abgelaufen)
|
||||
# Wichtig: kein Crash, kein hängender Counter
|
||||
time.sleep(1.1)
|
||||
engine._flush_presence()
|
||||
|
||||
calls = mock_rest._request.call_args_list
|
||||
assert len(calls) >= 2
|
||||
assert calls[0][1]["data"]["status"] == "busy"
|
||||
assert calls[-1][1]["data"]["status"] == "online"
|
||||
|
||||
def test_status_send_order_busy_then_online(self):
|
||||
"""Reihenfolge der REST-Calls: erst busy, dann online."""
|
||||
from plugin.archivar.presence_engine import PresenceEngine
|
||||
|
||||
mock_rest = MagicMock()
|
||||
mock_rest.auth_token = "token"
|
||||
mock_rest.user_id = "user123"
|
||||
mock_rest._request = MagicMock(return_value={"success": True})
|
||||
|
||||
engine = PresenceEngine(rest=mock_rest, enabled=True)
|
||||
|
||||
engine.mark_busy_started(room_name="#Test")
|
||||
time.sleep(0.05)
|
||||
engine.mark_busy_done()
|
||||
|
||||
# Warte auf Honeymoon
|
||||
time.sleep(1.1)
|
||||
engine._flush_presence()
|
||||
|
||||
calls = mock_rest._request.call_args_list
|
||||
statuses = [c[1]["data"]["status"] for c in calls]
|
||||
# Erster Status muss busy sein
|
||||
assert "busy" in statuses, f"Status-Sequenz: {statuses}"
|
||||
# busy kommt vor online
|
||||
busy_idx = statuses.index("busy")
|
||||
online_idx = statuses.index("online") if "online" in statuses else -1
|
||||
if online_idx >= 0:
|
||||
assert busy_idx < online_idx, (
|
||||
f"busy (idx={busy_idx}) muss vor online (idx={online_idx}) kommen: {statuses}"
|
||||
)
|
||||
|
||||
Reference in New Issue
Block a user