Compare commits
29 Commits
v8.6.1
..
f21075eddd
| Author | SHA1 | Date | |
|---|---|---|---|
| f21075eddd | |||
| b637fcc370 | |||
| 68f3845929 | |||
| 39fee34d89 | |||
| c8f54d0cef | |||
| 78b9a15cbd | |||
| 90c122cc74 | |||
| 0a05816b68 | |||
| 9db62bf94a | |||
| 324e7cd491 | |||
| 3ef57653c9 | |||
| ad84f665bc | |||
| bfd9cad899 | |||
| 81a17921e9 | |||
| fac0a79644 | |||
| 56baaaf038 | |||
| acd92f81cb | |||
| 2a92267bf4 | |||
| e0bf428799 | |||
| dcd014291e | |||
| 9e214a423c | |||
| 07ba653b65 | |||
| 0bfa791d79 | |||
| 83b9d6c347 | |||
| 18d87d8604 | |||
| b40b221896 | |||
| f028a30d6c | |||
| f61b0ba508 | |||
| 99979d6f9d |
@@ -0,0 +1,526 @@
|
|||||||
|
# RC-Plugin Funktionsbereichs-Zerlegung
|
||||||
|
|
||||||
|
Repo: /home/bernd/projekte/Hermes_rocket.chat_Plugin
|
||||||
|
HEAD: 83b9d6c ("fix(plugin.yaml): name rocketchat-platform → rocketchat (Pitfall 4)")
|
||||||
|
Analyse: Rainer (Architektur-Reviewer)
|
||||||
|
Datum: 2026-07-24
|
||||||
|
Zweck: Systematische Aufteilung des RC-Plugins in unabhängig prüfbare Funktionsbereiche, gegen die jeweils das Zielbild (Vorgaben, Designentscheidungen, Restriktionen) referenziert werden kann.
|
||||||
|
|
||||||
|
================================================================
|
||||||
|
METRIKEN-BASIS
|
||||||
|
================================================================
|
||||||
|
- adapter.py: 6921 LOC (Gateway, DDP, REST, Dispatch, Onboarding-Wiring)
|
||||||
|
- install.sh: 1611 LOC (Deployment, Verifikation, 11 Pitfalls dokumentiert)
|
||||||
|
- archivar/ gesamt: ~15.000 LOC, 24 Module
|
||||||
|
- Tests: ~70 Dateien, davon 16 v8_4_x (Vektor-Routing) + 8 v8_3_x (P0-Round) + 9 v8_2/8_3 + onboarding/room_map/router/presence/...
|
||||||
|
- Plugin-Dateien (Top-Level): adapter.py, tools.py, plugin.yaml
|
||||||
|
- Konfiguration: templates/config.yaml + room-map.json + .env (RUNTIME)
|
||||||
|
|
||||||
|
================================================================
|
||||||
|
ZERLEGUNGSKRITERIEN
|
||||||
|
================================================================
|
||||||
|
1. Kohärenz: Ein Bereich hat EINE Hauptverantwortung. Module mit gemeinsamer
|
||||||
|
Verantwortung (z.B. DDP-Layer, Routing-Decision) werden zusammengefasst.
|
||||||
|
2. Unabhängige Prüfbarkeit: Jeder Bereich hat definierte Eingaben (Triggers),
|
||||||
|
Ausgaben (Effekte) und kann gegen eine Teilmenge der Vorgaben geprüft werden,
|
||||||
|
ohne andere Bereiche zu laden.
|
||||||
|
3. Vollständigkeit: Adapter-Lifecycle, Persistenz, Deployment und Konfiguration
|
||||||
|
sind explizite Bereiche — nicht "alles andere".
|
||||||
|
|
||||||
|
================================================================
|
||||||
|
FUNKTIONSBEREICHE (sortiert nach Onboarding → Verarbeitung → Output → Persistenz → Infrastruktur)
|
||||||
|
================================================================
|
||||||
|
|
||||||
|
────────────────────────────────────────────────────────────────────
|
||||||
|
FB-01 Onboarding & Review ✅ BEREITS REVIEWED
|
||||||
|
────────────────────────────────────────────────────────────────────
|
||||||
|
Verantwortung:
|
||||||
|
Steuerung des Erstgesprächs mit neuen Nutzern/Räumen: Greeting-Flow,
|
||||||
|
Interview-State-Machine, Review-Subphasen, Lock-Mechanismus, Fact-Store-Pfad.
|
||||||
|
Endet in persistierter room-map.json.
|
||||||
|
|
||||||
|
Hauptdateien:
|
||||||
|
- plugin/archivar/onboarding.py (492 LOC — Greeting, Lazy-Check, Lock)
|
||||||
|
- plugin/archivar/onboarding_state.py (592 LOC — StateMachine, OnboardingData)
|
||||||
|
- plugin/archivar/onboarding_review.py (1146 LOC — Review-Subphasen-Dispatcher)
|
||||||
|
- plugin/adapter.py (_send_onboarding_message, _complete_onboarding)
|
||||||
|
- room-map.json / _persist_room_map_changes (Output)
|
||||||
|
|
||||||
|
Schlüsselfeatures:
|
||||||
|
- F-OB1 Lazy Onboarding (check_room_map_completeness_delta)
|
||||||
|
- F-OB2 Onboarding-Greeting-Flow (build_greeting_message, run_onboarding_greeting_flow)
|
||||||
|
- F-OB3 State-Machine (GREETING → AWAITING_NAME → ... → COMPLETE)
|
||||||
|
- F-OB4 Review-Subphasen (Room-Step, Edit, Keywords-Edit, Theme-Edit, Catch-All-Toggle, Remove, Add-New)
|
||||||
|
- F-OB5 Fact-Store-Pfad-Validierung
|
||||||
|
- F-OB6 Onboarding-Lock (acquire/release/cleanup_stale)
|
||||||
|
|
||||||
|
Bekannte Probleme:
|
||||||
|
- F6 R18 P1: adapter.py Z.4270-4271/5815-5816 rufen self._presence_engine.x OHNE
|
||||||
|
hasattr/None-Guard — bei Init-Exception (Z.822-827) wirft Onboarding AttributeError
|
||||||
|
(widerspricht R-4 Graceful Degradation).
|
||||||
|
- Onboarding-Test-Lock-Datei-Problematik in CI (siehe test_onboarding_lock).
|
||||||
|
- Verteilung: 1146 LOC in onboarding_review.py → Refactoring-Kandidat
|
||||||
|
(render_review_room_* sehr ähnlich, Template-Pattern).
|
||||||
|
|
||||||
|
Review-Status: ARCHITEKTUR-REVIEW ABGESCHLOSSEN (Onboarding-Teil).
|
||||||
|
Vorgaben geprüft: State-Machine-Korrektheit ✅, Review-Buttons-Korrektheit ✅,
|
||||||
|
Fact-Store-Pfad ✅. Noch offen: Interaction mit FB-04 (Keyword-Lernen) und
|
||||||
|
FB-09 (Error-Recovery).
|
||||||
|
|
||||||
|
────────────────────────────────────────────────────────────────────
|
||||||
|
FB-02 DDP-Client & Verbindungs-Lifecycle ⏳ ANSTEHEND
|
||||||
|
────────────────────────────────────────────────────────────────────
|
||||||
|
Verantwortung:
|
||||||
|
Aufbau, Aufrechterhaltung und Wiederherstellung der WebSocket-Verbindung zum
|
||||||
|
Rocket.Chat-Server via DDP-Protokoll. Login, Subscription, Reader-Loop,
|
||||||
|
Future-Store für await-Semantik, Reconnect-Logik.
|
||||||
|
|
||||||
|
Hauptdateien:
|
||||||
|
- plugin/adapter.py Z.274-889 (DDPTimeout, DDPServerError, DDPNotConnected, DDPClient)
|
||||||
|
- plugin/adapter.py Z.292+ (class DDPClient, _recv_loop, Future-Store, result-Handler)
|
||||||
|
|
||||||
|
Schlüsselfeatures:
|
||||||
|
- F-DDP1 Login (auth-Tokens, self.user-Extraktion aus Login-Response — P0-Fix f61b0ba)
|
||||||
|
- F-DDP2 Subscribe (stream-room-messages, notify-on-room)
|
||||||
|
- F-DDP3 Reader-Loop (Blocking, Thread-Trennung, Heartbeat)
|
||||||
|
- F-DDP4 Future-Store + result-Handler (async-await via run_coroutine_threadsafe, P1-2-O2)
|
||||||
|
- F-DDP5 Reconnect-Backoff
|
||||||
|
- F-DDP6 Own-Message-Filter (P0-Fix f61b0ba: self.user aus DDP, nicht Env)
|
||||||
|
|
||||||
|
Bekannte Probleme:
|
||||||
|
- F19 R19 P0-1 (archiviert, aber referenced): PulseController in presence_engine
|
||||||
|
erstellt self._pulse_controller/_detection_timer NIE → 348 Zeilen Dead-Code.
|
||||||
|
NICHT in diesem Bereich, aber DDP-Layer muss fehlende Pulse-Calls
|
||||||
|
kompensieren (DDP set_status als kostenloser Fallback).
|
||||||
|
- Eigene DDP-Reader-Thread vs. asyncio.loop-Thread: Synchronisation
|
||||||
|
prüfen (run_coroutine_threadsafe-Pfad).
|
||||||
|
|
||||||
|
────────────────────────────────────────────────────────────────────
|
||||||
|
FB-03 REST-Client & API-Wrapper ⏳ ANSTEHEND
|
||||||
|
────────────────────────────────────────────────────────────────────
|
||||||
|
Verantwortung:
|
||||||
|
Kapselt die Rocket.Chat-REST-API für Out-of-Band-Operationen:
|
||||||
|
Posten von Nachrichten, Senden von Buttons, Datei-Upload/Download,
|
||||||
|
Room-Info-Lookup. Trennt synchronen HTTP-Pfad von asynchronem DDP-Pfad.
|
||||||
|
|
||||||
|
Hauptdateien:
|
||||||
|
- plugin/adapter.py Z.138-273 (class RocketChatREST)
|
||||||
|
- plugin/adapter.py Z.31-38 (RocketChatRateLimitError)
|
||||||
|
- plugin/adapter.py Z.40-130 (Helper: _MULTIROOM, _get_config_str)
|
||||||
|
|
||||||
|
Schlüsselfeatures:
|
||||||
|
- F-REST1 Message-POST (chat.postMessage)
|
||||||
|
- F-REST2 Button-Attachments (send mit attachments-Array)
|
||||||
|
- F-REST3 Rate-Limit-Handling
|
||||||
|
- F-REST4 Datei-Upload (rooms.upload)
|
||||||
|
- F-REST5 Datei-Download (für Inlining)
|
||||||
|
- F-REST6 Room-Info-Lookup (rooms.info, users.info)
|
||||||
|
|
||||||
|
Bekannte Probleme:
|
||||||
|
- Trennung REST/DDP-Nachrichten: Race-Conditions möglich wenn REST-Post
|
||||||
|
und DDP-Event dieselbe Nachricht betreffen (z.B. Echo-Filter).
|
||||||
|
- Token-Refresh: Wenn auth_token abläuft, kein automatischer Re-Login
|
||||||
|
im REST-Pfad (nur DDP reconnectet).
|
||||||
|
|
||||||
|
────────────────────────────────────────────────────────────────────
|
||||||
|
FB-04 Archivar-Routing & Klassifikation ⏳ ANSTEHEND
|
||||||
|
────────────────────────────────────────────────────────────────────
|
||||||
|
Verantwortung:
|
||||||
|
Kernlogik: Eingehende Nachricht → Klassifikation (FAKT/FRAGE/ALARM/etc.)
|
||||||
|
→ Routing-Decision → Ziel-Raum. Hybrid aus Keyword-Matcher (Stufe 0),
|
||||||
|
Sentence-Marker-Erkennung, FAISS-Vektor-Routing (Stufe 1) und
|
||||||
|
LLM-Fallback (Stufe 2).
|
||||||
|
|
||||||
|
Hauptdateien:
|
||||||
|
- plugin/archivar/router.py (2261 LOC — BidirectionalRouter)
|
||||||
|
- plugin/archivar/classifier.py (716 LOC — IntentClassifier, EmbeddingClient, LLMClient)
|
||||||
|
- plugin/archivar/keyword_matcher.py (481 LOC — Stemmer, Levenshtein, Word-Boundary)
|
||||||
|
- plugin/archivar/sentence_markers.py (307 LOC — MarkerClass, detect_sentence_marker)
|
||||||
|
- plugin/archivar/booster.py (277 LOC — KeywordBooster)
|
||||||
|
- plugin/archivar/multiroom_context.py (205 LOC — Cross-Room-Entry, MultiRoomContextRing)
|
||||||
|
- plugin/archivar/feedback_detector.py (232 LOC — RoutingWiderspruchDetector)
|
||||||
|
- plugin/archivar/archivar_state.py (1173 LOC — RoomState, ArchivarState)
|
||||||
|
|
||||||
|
Schlüsselfeatures:
|
||||||
|
- F-RT1 BidirectionalRouter (RoutingDecision, Red-Flag-Erkennung)
|
||||||
|
- F-RT2 2-Stufen-Klassifikator (Keyword → FAISS → LLM)
|
||||||
|
- F-RT3 Sentence-Marker-Pattern (FRAGE/ALARM/FAKT/...)
|
||||||
|
- F-RT4 KeywordBooster (Hybrid mit FAISS)
|
||||||
|
- F-RT5 Cross-Room-Context-Ring
|
||||||
|
- F-RT6 Routing-Konflikt-Detektor (Widerspruchs-Erkennung)
|
||||||
|
- F-RT7 Recursive Routing (v7_4)
|
||||||
|
- F-RT8 Sticky Sessions (test_sticky_session)
|
||||||
|
- F-RT9 V8.4 FAISS-Routing-Tests (8 Test-Dateien: v8_4_2 ... v8_4_6)
|
||||||
|
|
||||||
|
Bekannte Probleme:
|
||||||
|
- 2261 LOC in router.py — höchste Komplexität im Plugin. Refactoring-Druck.
|
||||||
|
- FAISS-Performance bei wachsendem Index (siehe faiss_performance_test*.py im Root).
|
||||||
|
- Hybrid-Booster mit FAISS: User-Präferenz aus Memory dokumentiert
|
||||||
|
("Hybridansatz mit KeywordBooster"), aber Integration-Drift-Risiko
|
||||||
|
(R18-Anm.: _update_dst dupliziert deploy_plugin-Logik).
|
||||||
|
- Sentence-Marker-Validierung: validate_sentence_marker ist async und
|
||||||
|
wird aus synchronem Routing-Pfad aufgerufen — Race-Risk.
|
||||||
|
|
||||||
|
────────────────────────────────────────────────────────────────────
|
||||||
|
FB-05 Presence-Engine & Status-Pulse ⏳ ANSTEHEND (KRITISCH)
|
||||||
|
────────────────────────────────────────────────────────────────────
|
||||||
|
Verantwortung:
|
||||||
|
Visuelle Präsenz des Butlers: "online"/"away"-Status, Pulse-Intervall,
|
||||||
|
Detection-Timer (Gateway-Heartbeat-Erkennung). P0-Status: Implementierung
|
||||||
|
hat dokumentierte Lücken aus F19 R19 Review.
|
||||||
|
|
||||||
|
Hauptdateien:
|
||||||
|
- plugin/archivar/presence_engine.py (1119 LOC — PresenceEngine, PulseController, DetectionTimer)
|
||||||
|
- plugin/adapter.py (DDP set_status, on_agent_busy, on_message_received)
|
||||||
|
|
||||||
|
Schlüsselfeatures:
|
||||||
|
- F-PR1 PresenceEngine (idle/active/dnd-Modi)
|
||||||
|
- F-PR2 PulseController (Async-Pulse via run_coroutine_threadsafe)
|
||||||
|
- F-PR3 DetectionTimer (pgrep-Heuristik, gateway_state-Signal)
|
||||||
|
- F-PR4 ROCKETCHAT_PRESENCE_PULSE_INTERVAL (5-30s Clamp)
|
||||||
|
- F-PR5 Honeymoon-Timer (b40b221: Status busy minimum 1s sichtbar)
|
||||||
|
- F-PR6 Status-Farben (d964d7d: grün/gelb/rot, Flughafen-Prinzip)
|
||||||
|
|
||||||
|
Bekannte Probleme (F19 R19 dokumentiert, CHANGES NEEDED):
|
||||||
|
- P0-1 ARCHITEKTUR-BRUCH: presence_engine erstellt _pulse_controller/
|
||||||
|
_detection_timer NIE, adapter instanziiert sie auch nicht → 348 Z.
|
||||||
|
Dead-Code, alle hasattr-Guards (presence_engine Z.476/488, adapter
|
||||||
|
Z.871-876) No-Ops.
|
||||||
|
- P0-2 PulseController.cancel_pending() = pass (Z.604-613) — EC-5
|
||||||
|
NICHT implementiert.
|
||||||
|
- P1-1 on_agent_busy/on_message_received (Z.479/491) in adapter.py
|
||||||
|
0 Aufrufer.
|
||||||
|
- P1-2 K3: ::setstatus on/off ruft enable/disable, nicht PulseController.
|
||||||
|
- P1-3 ROCKETCHAT_PRESENCE_PULSE_INTERVAL geht an PresenceEngine
|
||||||
|
(clamp 5-30s), PulseController-Default 1.5s.
|
||||||
|
- P1-4 DetectionTimer pgrep 'len > 1' — 0 Prozesse = False, kein
|
||||||
|
Heuristik-Unterschied.
|
||||||
|
- P1-5 heartbeat_pulse/detection ungelockt.
|
||||||
|
- P1-6 _pulse_loop Pause-Check nur in Sleep (0.1s Latenz).
|
||||||
|
- P2-1 pgrep 6/min unkritisch.
|
||||||
|
- P2-2 REST-Fallback auth_token+user_id ungebunden.
|
||||||
|
|
||||||
|
Review-Status: REVIEW CHANGES NEEDED — keine Freigabe möglich bis P0-1, P0-2,
|
||||||
|
P1-2 behoben sind. DDP set_status (adapter Z.544-549) ist kostenloser
|
||||||
|
Workaround bis dahin.
|
||||||
|
|
||||||
|
────────────────────────────────────────────────────────────────────
|
||||||
|
FB-06 Inline-Commands (::-Präfix) ⏳ ANSTEHEND
|
||||||
|
────────────────────────────────────────────────────────────────────
|
||||||
|
Verantwortung:
|
||||||
|
Verarbeitung von `::hilfe`, `::status`, `::multiroom`, etc. — direkte
|
||||||
|
Nutzer-Befehle, die vor dem Routing abgefangen werden.
|
||||||
|
|
||||||
|
Hauptdateien:
|
||||||
|
- plugin/archivar/inline_commands.py (431 LOC — InlineCommandRegistry, parse_inline_command)
|
||||||
|
- plugin/archivar/adapter_integration.py (1270 LOC — Routing-Integration)
|
||||||
|
|
||||||
|
Schlüsselfeatures:
|
||||||
|
- F-IC1 ::hilfe (build_help_text)
|
||||||
|
- F-IC2 ::status (build_status_text)
|
||||||
|
- F-IC3 ::multiroom (Kontext an/aus)
|
||||||
|
- F-IC4 ::setstatus (on/off, siehe FB-05 P1-2)
|
||||||
|
- F-IC5 Natural Help Request Detection (is_natural_help_request)
|
||||||
|
- F-IC6 Command-Question-Extraction (extract_command_question)
|
||||||
|
- F-IC7 Build-Command-Help (pro Command)
|
||||||
|
|
||||||
|
Bekannte Probleme:
|
||||||
|
- ::setstatus nutzt enable/disable statt PulseController (siehe FB-05).
|
||||||
|
- Hilfe-Text-Wartung: Bei neuen Commands muss build_help_text manuell
|
||||||
|
erweitert werden — kein Auto-Discovery aus Registry.
|
||||||
|
|
||||||
|
────────────────────────────────────────────────────────────────────
|
||||||
|
FB-07 Button-System (Rendering, Dispatch, Templates) ⏳ ANSTEHEND
|
||||||
|
────────────────────────────────────────────────────────────────────
|
||||||
|
Verantwortung:
|
||||||
|
Rendering von interaktiven Button-Attachments (Room-Auswahl, Review-Aktionen,
|
||||||
|
Move-Requests), Dispatch eingehender Button-Klicks, Template-System.
|
||||||
|
|
||||||
|
Hauptdateien:
|
||||||
|
- plugin/archivar/onboarding_review.py (build_button_attachments, dispatch_review_button)
|
||||||
|
- plugin/archivar/inline_commands.py (Button-Hilfe)
|
||||||
|
- plugin/archivar/archivar_state.py (Button-Action-IDs?)
|
||||||
|
- plugin/adapter.py (Button-Click-Handler im DDP-Reader-Pfad)
|
||||||
|
- tests/test_f6_adapter_dispatch.py (F6-Dispatch-Tests)
|
||||||
|
- tests/test_p1_button_click_fix.py (P1-Button-Klick-Fix)
|
||||||
|
- docs/BUTTON_GUIDE.md
|
||||||
|
- docs/move-request-button-ux.md
|
||||||
|
|
||||||
|
Schlüsselfeatures:
|
||||||
|
- F-BT1 Review-Buttons (room-step, edit, keywords, theme, catch-all, remove, add-new)
|
||||||
|
- F-BT2 Move-Request-Buttons (Butler Klärungsflow)
|
||||||
|
- F-BT3 Button-Action-ID-Schema
|
||||||
|
- F-BT4 Template-Rendering
|
||||||
|
- F-BT5 F6-Adapter-Dispatch-Pfad (Test existiert, deckt Pfad ab)
|
||||||
|
|
||||||
|
Bekannte Probleme:
|
||||||
|
- Button-Click-Parsing sitzt in adapter.py — Suchpfad muss verifiziert
|
||||||
|
werden (P1-Button-Click-Fix deutet auf Historie).
|
||||||
|
- docs/move-request-button-ux.md deutet auf eigenen Sub-Flow mit
|
||||||
|
noch nicht vollständig implementierter UX.
|
||||||
|
|
||||||
|
────────────────────────────────────────────────────────────────────
|
||||||
|
FB-08 File-Handling (Upload, Download, Inlining, [FILE]-Stripping) ⏳ ANSTEHEND
|
||||||
|
────────────────────────────────────────────────────────────────────
|
||||||
|
Verantwortung:
|
||||||
|
Behandlung von Datei-Anhängen: Upload via REST, Download für Inline-Vorschau,
|
||||||
|
[FILE:...]-Block-Stripping bei fehlgeschlagenen Downloads, MIME-Type-Behandlung.
|
||||||
|
|
||||||
|
Hauptdateien:
|
||||||
|
- plugin/adapter.py (_download_and_inline_files, _upload_file, [FILE]-Stripping)
|
||||||
|
- plugin/adapter.py (342a1cd: P2-1-Fix — Block-Stripping nach fehlgeschlagenen Downloads)
|
||||||
|
|
||||||
|
Schlüsselfeatures:
|
||||||
|
- F-FH1 Datei-Upload (rooms.upload via REST)
|
||||||
|
- F-FH2 Datei-Download (für Inlining)
|
||||||
|
- F-FH3 [FILE:pfad]-Block-Parsing
|
||||||
|
- F-FH4 [FILE]-Stripping nach fehlgeschlagenen Downloads (P2-1)
|
||||||
|
- F-FH5 MIME-Type-Erkennung
|
||||||
|
|
||||||
|
Bekannte Probleme:
|
||||||
|
- Datei-Pfad-Injektion: [FILE:...]-Parsing muss gegen Traversal gesichert sein.
|
||||||
|
- Download-Fehler-Handling: 342a1cd behebt Block-Stripping, aber Upload-
|
||||||
|
Fehler-Fallbacks noch nicht verifiziert.
|
||||||
|
- Größen-Limits: Kein expliziter Check in adapter.py sichtbar — Regressionsrisiko
|
||||||
|
bei sehr großen Dateien.
|
||||||
|
|
||||||
|
────────────────────────────────────────────────────────────────────
|
||||||
|
FB-09 Butler (Move-Requests, Clarification, 2. Stufe) ⏳ ANSTEHEND
|
||||||
|
────────────────────────────────────────────────────────────────────
|
||||||
|
Verantwortung:
|
||||||
|
Wenn Routing unsicher ist: Klärungs-Anfrage an Butler (Nutzer) senden,
|
||||||
|
Antwort verarbeiten, ggf. Move-Request initiieren. "Gelber Status" (away)
|
||||||
|
signalisiert Klärungsbedarf.
|
||||||
|
|
||||||
|
Hauptdateien:
|
||||||
|
- plugin/archivar/router.py (_parse_red_flag_response, validate_sentence_marker)
|
||||||
|
- plugin/archivar/onboarding.py (Lazy-Onboarding-Check)
|
||||||
|
- plugin/archivar/inline_commands.py (::multiroom-Kontext)
|
||||||
|
- plugin/adapter.py (Move-Request-Versand)
|
||||||
|
- docs/move-request-button-ux.md
|
||||||
|
- docs/rocketchat_send_clarify_architecture.md (im Root-Repo)
|
||||||
|
- tests/test_butler_mode.py
|
||||||
|
- tests/test_d_pending_resolver.py
|
||||||
|
|
||||||
|
Schlüsselfeatures:
|
||||||
|
- F-BU1 Red-Flag-Erkennung (LLM-Antwort unsicher)
|
||||||
|
- F-BU2 Clarification-Request (Nachfrage an Nutzer)
|
||||||
|
- F-BU3 Move-Request (Routing-Vorschlag als Button)
|
||||||
|
- F-BU4 Pending-Resolver (d_pending_resolver)
|
||||||
|
- F-BU5 Away-Status (573335c: gelb bei Klärungsflow)
|
||||||
|
- F-BU6 Stufe-2-Klärung (DM-Routing in unsicheren Fällen)
|
||||||
|
|
||||||
|
Bekannte Probleme:
|
||||||
|
- d_pending_resolver-Tests deutet auf komplexen State-Resolver — Refactoring-Druck.
|
||||||
|
- Butler-Status-Kopplung an Presence (FB-05): away-Status-Logik muss mit
|
||||||
|
PulseController-Implementierung harmonieren.
|
||||||
|
|
||||||
|
────────────────────────────────────────────────────────────────────
|
||||||
|
FB-10 Room-Map (Verwaltung, Onboarding, Keywords) ⏳ ANSTEHEND
|
||||||
|
────────────────────────────────────────────────────────────────────
|
||||||
|
Verantwortung:
|
||||||
|
Persistente Datenstruktur für Raum-Metadaten: Raum → Keywords, Theme,
|
||||||
|
Catch-All-Status, Owner, Excluded-Liste. CRUD-API für Onboarding-Review
|
||||||
|
und Auto-Learning.
|
||||||
|
|
||||||
|
Hauptdateien:
|
||||||
|
- plugin/archivar/room_map.py (1043 LOC — RoomEntry, RoomMap, _migrate_from_env_vars)
|
||||||
|
- plugin/archivar/room_index.py (664 LOC — RoomIndexManager, RoomIndexError)
|
||||||
|
- room-map.json (Runtime-Output)
|
||||||
|
|
||||||
|
Schlüsselfeatures:
|
||||||
|
- F-RM1 RoomEntry (name, id, keywords, theme, catch_all, owner)
|
||||||
|
- F-RM2 RoomMap CRUD (load, save, add_room, remove_room, update_room)
|
||||||
|
- F-RM3 Two-Stage Keyword Evidence
|
||||||
|
- F-RM4 Room-Exclusion (excluded_ids)
|
||||||
|
- F-RM5 Room-Validation (RoomMapValidationError)
|
||||||
|
- F-RM6 Migration from Env-Vars (_migrate_from_env_vars)
|
||||||
|
- F-RM7 Write-API (test_room_map_write_api)
|
||||||
|
- F-RM8 Weighted-Keywords (test_room_map_weighted)
|
||||||
|
- F-RM9 Room-Index (FAISS-Index für schnelles Lookup)
|
||||||
|
|
||||||
|
Bekannte Probleme:
|
||||||
|
- Room-Map-Datei ist Single-Source-of-Truth, aber kein Locking-Mechanismus
|
||||||
|
sichtbar — Concurrency-Risk bei parallelem Onboarding mehrerer Räume.
|
||||||
|
- Migration-Path von Env-Vars deprecated aber noch vorhanden.
|
||||||
|
|
||||||
|
────────────────────────────────────────────────────────────────────
|
||||||
|
FB-11 Adapter-Dispatch & ArchivarMessageHandler ⏳ ANSTEHEND
|
||||||
|
────────────────────────────────────────────────────────────────────
|
||||||
|
Verantwortung:
|
||||||
|
Glue-Code zwischen DDP-Inbox und Archivar-Subsystem: Message-Sanitizing,
|
||||||
|
Reply-Quote-Stripping, Auftrags-Erkennung, Decision-Logging, Adapter-Tests
|
||||||
|
(F6-Dispatch-Pfad).
|
||||||
|
|
||||||
|
Hauptdateien:
|
||||||
|
- plugin/archivar/adapter_integration.py (1270 LOC — ArchivarMessageHandler)
|
||||||
|
- plugin/archivar/reply_quote_stripper.py (196 LOC — strip_reply_quote)
|
||||||
|
- plugin/archivar/sentence_markers.py (Sentence-Marker → Routing-Decision)
|
||||||
|
- plugin/archivar/routing_telemetry.py (137 LOC — RoutingTelemetry)
|
||||||
|
- plugin/archivar/routing_counter.py (57 LOC — RoutingCounter)
|
||||||
|
- plugin/adapter.py (_is_auftrag, _build_announcement, ArchivarMessageHandler-Aufruf)
|
||||||
|
- tests/test_f6_adapter_dispatch.py
|
||||||
|
- tests/test_reply_quote_stripper.py
|
||||||
|
- tests/test_r5_inline_commands.py
|
||||||
|
- tests/test_a1b_integration.py
|
||||||
|
- tests/test_r1_integration.py
|
||||||
|
|
||||||
|
Schlüsselfefeatures:
|
||||||
|
- F-AD1 ArchivarMessageHandler (Hauptentry-Point für DDP-Nachrichten)
|
||||||
|
- F-AD2 Reply-Quote-Stripping (RC-spezifisch: [ ](per-Channel))
|
||||||
|
- F-AD3 Auftrags-Erkennung (_is_auftrag)
|
||||||
|
- F-AD4 Routing-Telemetry (Entscheidungsprotokollierung)
|
||||||
|
- F-AD5 Routing-Counter (Häufigkeits-Statistik)
|
||||||
|
- F-AD6 Adapter-Dispatch-Pfad (F6)
|
||||||
|
|
||||||
|
Bekannte Probleme:
|
||||||
|
- 1270 LOC in adapter_integration.py — Kandidat für Aufteilung in
|
||||||
|
Pre-Processing / Decision / Post-Processing.
|
||||||
|
- Reply-Quote-Stripping: 4 Strip-Funktionen (attachments, rc-reply-link,
|
||||||
|
blockquotes, quote-blocks) — Reihenfolge-Risiko.
|
||||||
|
|
||||||
|
────────────────────────────────────────────────────────────────────
|
||||||
|
FB-12 Config & Persistenz ⏳ ANSTEHEND
|
||||||
|
────────────────────────────────────────────────────────────────────
|
||||||
|
Verantwortung:
|
||||||
|
Konfigurations-Management: plugin.yaml (Manifest), templates/config.yaml
|
||||||
|
(Default), .env (Runtime-Secrets), room-map.json (Runtime-State),
|
||||||
|
Fact-Store-Pfad-Validierung, Conversation-History.
|
||||||
|
|
||||||
|
Hauptdateien:
|
||||||
|
- plugin/plugin.yaml (12 LOC — name: rocketchat, kind: platform)
|
||||||
|
- templates/config.yaml (88 LOC — Default-Config)
|
||||||
|
- .env (Runtime — nicht in Git)
|
||||||
|
- plugin/archivar/config.py (338 LOC — _resolve_room_mapping)
|
||||||
|
- plugin/archivar/doc_store.py (144 LOC — DocumentationStore)
|
||||||
|
- plugin/archivar/conversation_history.py (237 LOC — ConversationHistory, MessageEntry)
|
||||||
|
- plugin/archivar/seed_data.py (134 LOC — Seed-Data)
|
||||||
|
- room-map.json (Runtime-Output)
|
||||||
|
|
||||||
|
Schlüsselfeatures:
|
||||||
|
- F-CF1 plugin.yaml-Manifest (Pitfall 4: name muss "rocketchat" sein)
|
||||||
|
- F-CF2 templates/config.yaml (Default-Config-Template)
|
||||||
|
- F-CF3 .env-Loading (via _get_config_str mit env_var-Fallback)
|
||||||
|
- F-CF4 Fact-Store-Pfad (validate_fact_store_path, create_and_verify_fact_store)
|
||||||
|
- F-CF5 DocumentationStore (FAKT-Routing-Output)
|
||||||
|
- F-CF6 ConversationHistory (gespeicherte Konversations-Snapshots)
|
||||||
|
- F-CF7 Seed-Data (Erstausstattung Room-Map, Keywords)
|
||||||
|
|
||||||
|
Bekannte Probleme:
|
||||||
|
- .env nicht versioniert — Drift zwischen Test- und Prod-Config.
|
||||||
|
- Migration _migrate_from_env_vars deprecated, aber noch im Code.
|
||||||
|
- plugin.yaml-Name "rocketchat" (P1-2-O2-Fix 83b9d6c) — Hinweis auf
|
||||||
|
subtile Pitfall-Klassen (Plugin-Loader-Strict-Matching).
|
||||||
|
|
||||||
|
────────────────────────────────────────────────────────────────────
|
||||||
|
FB-13 install.sh & Deployment ⏳ ANSTEHEND
|
||||||
|
────────────────────────────────────────────────────────────────────
|
||||||
|
Verantwortung:
|
||||||
|
Deployment-Skript: Plugin-Pfad-Validierung, venv-Setup, systemd-Service-
|
||||||
|
Konfiguration, Verifikations-Loop, Restart-Logik. 11 dokumentierte
|
||||||
|
Susi-Deployment-Pitfalls.
|
||||||
|
|
||||||
|
Hauptdateien:
|
||||||
|
- install.sh (1611 LOC — Deployment, 99979d6 dokumentiert 9 Pitfalls)
|
||||||
|
- bootstrap.sh (2325 Bytes — Wrapper?)
|
||||||
|
- scripts/rebuild_index.py (FAISS-Index-Rebuild)
|
||||||
|
- scripts/smoke_test_booster.py (Booster-Smoke-Test)
|
||||||
|
- scripts/smoke_test_faiss.py (FAISS-Smoke-Test)
|
||||||
|
- docs/INSTALL.md
|
||||||
|
- docs/deployment-runbook.md
|
||||||
|
- tests/test_install_update_only.py
|
||||||
|
|
||||||
|
Schlüsselfeatures:
|
||||||
|
- F-IN1 Plugin-Pfad-Validierung (Core-Plugin-Pfad vs. Custom)
|
||||||
|
- F-IN2 venv-Setup (numpy2-Installations-Pitfall)
|
||||||
|
- F-IN3 systemd-Service-Config
|
||||||
|
- F-IN4 Verifikations-Loop (is-active-Check, 30s-Timeout)
|
||||||
|
- F-IN5 Update-Only-Pfad (test_install_update_only)
|
||||||
|
- F-IN6 bootstrap.sh (Schnell-Setup)
|
||||||
|
- F-IN7 Index-Rebuild-Skript
|
||||||
|
- F-IN8 Smoke-Tests (Booster, FAISS)
|
||||||
|
|
||||||
|
Bekannte Probleme:
|
||||||
|
- F6 R18 dokumentiert: 11 Pitfalls, install.sh 5 Schritte sauber,
|
||||||
|
30s is-active-Loop robust, journalctl --since '1 minute ago' akzeptiert
|
||||||
|
(systemd 257 getestet), --no-restart + --dry-run korrekt.
|
||||||
|
- F6 R18: bash -n OK.
|
||||||
|
- F18 (18d87d8): local outside function — replace with plain assignment
|
||||||
|
(kleiner Cleanup, P0-charakter).
|
||||||
|
|
||||||
|
Review-Status: F6 R18 APPROVED mit 1 P1 (adapter.py Guard-Issue, NICHT
|
||||||
|
install.sh selbst). Verifikation: 1288 passed, 37 failed pre-existing.
|
||||||
|
|
||||||
|
────────────────────────────────────────────────────────────────────
|
||||||
|
FB-14 Telemetrie, Tests & Diagnostics ⏳ ANSTEHEND
|
||||||
|
────────────────────────────────────────────────────────────────────
|
||||||
|
Verantwortung:
|
||||||
|
Routing-Telemetry, Routing-Counter, Test-Infrastruktur (pytest + 70 Test-Dateien),
|
||||||
|
Diagnostics-Endpoints, Performance-Tests.
|
||||||
|
|
||||||
|
Hauptdateien:
|
||||||
|
- plugin/archivar/routing_telemetry.py (137 LOC)
|
||||||
|
- plugin/archivar/routing_counter.py (57 LOC)
|
||||||
|
- plugin/archivar/tests/ (Test-Suite archivar-intern)
|
||||||
|
- tests/ (Top-level-Tests: test_adapter, test_booster, test_ddp_await, test_install_update_only, test_onboarding, test_room_index)
|
||||||
|
- scripts/smoke_test_*.py
|
||||||
|
- faiss_performance_test*.py (im Root-Repo, nicht im Plugin)
|
||||||
|
|
||||||
|
Schlüsselfeatures:
|
||||||
|
- F-TM1 Routing-Telemetry (Entscheidungs-Logging)
|
||||||
|
- F-TM2 Routing-Counter (Statistik)
|
||||||
|
- F-TM3 Test-Suite (70+ Dateien, F6-F19-Generationen)
|
||||||
|
- F-TM4 Smoke-Tests (Booster, FAISS)
|
||||||
|
- F-TM5 Performance-Tests (FAISS, Index-Größe)
|
||||||
|
|
||||||
|
Bekannte Probleme:
|
||||||
|
- Test-Suite-Wartung: 16 v8_4_x-Dateien deuten auf hohe Iterationsfrequenz
|
||||||
|
— Refactoring-Signale.
|
||||||
|
- 37 pre-existing failed Tests (laut F6 R18) — müssen auf "broken-by-design"
|
||||||
|
oder "fixable" klassifiziert werden.
|
||||||
|
|
||||||
|
================================================================
|
||||||
|
ZUSAMMENFASSUNG
|
||||||
|
================================================================
|
||||||
|
|
||||||
|
14 Funktionsbereiche identifiziert, alle Plugin-Aspekte abgedeckt:
|
||||||
|
|
||||||
|
✅ FB-01 Onboarding & Review REVIEWED (F6 R18)
|
||||||
|
⏳ FB-02 DDP-Client ANSTEHEND
|
||||||
|
⏳ FB-03 REST-Client ANSTEHEND
|
||||||
|
⏳ FB-04 Archivar-Routing & Klassifikation ANSTEHEND (komplex, 2261 LOC)
|
||||||
|
⏳ FB-05 Presence-Engine & Pulse ANSTEHEND, CHANGES NEEDED
|
||||||
|
⏳ FB-06 Inline-Commands ANSTEHEND
|
||||||
|
⏳ FB-07 Button-System ANSTEHEND
|
||||||
|
⏳ FB-08 File-Handling ANSTEHEND
|
||||||
|
⏳ FB-09 Butler (Move/Clarify) ANSTEHEND
|
||||||
|
⏳ FB-10 Room-Map ANSTEHEND
|
||||||
|
⏳ FB-11 Adapter-Dispatch ANSTEHEND
|
||||||
|
⏳ FB-12 Config & Persistenz ANSTEHEND
|
||||||
|
⏳ FB-13 install.sh & Deployment ANSTEHEND (F6 R18 APPROVED)
|
||||||
|
⏳ FB-14 Telemetrie & Tests ANSTEHEND
|
||||||
|
|
||||||
|
Review-Reihenfolge-Empfehlung (nach Abhängigkeit + Risiko):
|
||||||
|
1. FB-05 Presence (P0-Blocker für 8+ andere Bereiche)
|
||||||
|
2. FB-13 install.sh (F6 R18 APPROVED → Re-Verifikation der P1)
|
||||||
|
3. FB-02 DDP-Client (Grundlage für alle Inbox-Pfade)
|
||||||
|
4. FB-04 Archivar-Routing (komplex, zentral, FAISS-Tests vorhanden)
|
||||||
|
5. FB-10 Room-Map (Datenquelle für FB-04)
|
||||||
|
6. FB-11 Adapter-Dispatch (Glue zwischen DDP und Archivar)
|
||||||
|
7. FB-09 Butler (koppelt zurück an FB-05)
|
||||||
|
8. FB-06 Inline-Commands (kleiner, isoliert)
|
||||||
|
9. FB-07 Button-System (UX-kritisch, dokumentiert in BUTTON_GUIDE.md)
|
||||||
|
10. FB-08 File-Handling (Sicherheits-Relevanz)
|
||||||
|
11. FB-12 Config & Persistenz (Grundlage, niedrig-Risiko)
|
||||||
|
12. FB-03 REST-Client (einfach, von DDP abgekoppelt)
|
||||||
|
13. FB-14 Telemetrie & Tests (Wartbarkeit, Querschnitt)
|
||||||
|
|
||||||
|
Lücken-/Überlappungs-Check:
|
||||||
|
- ABGEDECKT: DDP, REST, Routing, Onboarding, Presence, Inline-Commands,
|
||||||
|
Buttons, Files, Butler, Room-Map, Config, Deployment, Tests.
|
||||||
|
- NICHT als eigener Bereich: Logging (Querschnitt, in jedem FB prüfen),
|
||||||
|
Error-Handling (Querschnitt), Security (Querschnitt — siehe FB-08,
|
||||||
|
FB-12, FB-10 für Pfad-/Lock-Aspekte).
|
||||||
|
- EXPLIZIT AUSGELAGERT: room-map.json sowohl in FB-10 (Schema) als auch
|
||||||
|
FB-12 (Persistenz) — bei Review Klarstellung welcher Bereich
|
||||||
|
Schema-Validierung vs. I/O-Verantwortung trägt.
|
||||||
+54
@@ -0,0 +1,54 @@
|
|||||||
|
# P2 Backlog — FB-02 DDP-Client Review (Rainer)
|
||||||
|
|
||||||
|
Erstellt: 2026-07-24
|
||||||
|
Status: Offen (nicht in diesem Durchgang)
|
||||||
|
|
||||||
|
---
|
||||||
|
|
||||||
|
## B4 (P2): [Platzhalter — Details fehlen]
|
||||||
|
|
||||||
|
**Problem:** [TBD]
|
||||||
|
|
||||||
|
**Lösung:** [TBD]
|
||||||
|
|
||||||
|
**Commit:** `fix(B4): [TBD]`
|
||||||
|
|
||||||
|
---
|
||||||
|
|
||||||
|
## B5 (P2): [Platzhalter — Details fehlen]
|
||||||
|
|
||||||
|
**Problem:** [TBD]
|
||||||
|
|
||||||
|
**Lösung:** [TBD]
|
||||||
|
|
||||||
|
**Commit:** `fix(B5): [TBD]`
|
||||||
|
|
||||||
|
---
|
||||||
|
|
||||||
|
## B6 (P2): [Platzhalter — Details fehlen]
|
||||||
|
|
||||||
|
**Problem:** [TBD]
|
||||||
|
|
||||||
|
**Lösung:** [TBD]
|
||||||
|
|
||||||
|
**Commit:** `fix(B6): [TBD]`
|
||||||
|
|
||||||
|
---
|
||||||
|
|
||||||
|
## B7 (P2): [Platzhalter — Details fehlen]
|
||||||
|
|
||||||
|
**Problem:** [TBD]
|
||||||
|
|
||||||
|
**Lösung:** [TBD]
|
||||||
|
|
||||||
|
**Commit:** `fix(B7): [TBD]`
|
||||||
|
|
||||||
|
---
|
||||||
|
|
||||||
|
## Erledigt (dieser Durchgang)
|
||||||
|
|
||||||
|
| Bug | Prio | Commit | Beschreibung |
|
||||||
|
|-----|------|--------|-------------|
|
||||||
|
| B1 | P0 | `90c122c` | Future-Cleanup bei Disconnect |
|
||||||
|
| B2 | P1 | `78b9a15` | Exponential Backoff bei Reconnect |
|
||||||
|
| B3 | P1 | `c8f54d0` | Doc-String _on_ddp_connected set_status sync |
|
||||||
+191
-31
@@ -193,6 +193,15 @@ find_pipx_venv() {
|
|||||||
echo "$hermes_venv"
|
echo "$hermes_venv"
|
||||||
return 0
|
return 0
|
||||||
fi
|
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
|
return 1
|
||||||
}
|
}
|
||||||
|
|
||||||
@@ -207,6 +216,25 @@ print(sp)
|
|||||||
PY
|
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
|
# 1. System-Dependencies installieren
|
||||||
# ──────────────────────────────────────────────────────────────────────────
|
# ──────────────────────────────────────────────────────────────────────────
|
||||||
@@ -375,11 +403,18 @@ deploy_plugin() {
|
|||||||
local src="$script_dir/plugin"
|
local src="$script_dir/plugin"
|
||||||
[ -d "$src" ] || die "plugin/-Verzeichnis fehlt in $script_dir"
|
[ -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
|
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/
|
# Eigener venv (kein pipx): Plugin direkt unter ~/.hermes/hermes-agent/plugins/
|
||||||
dst="$HOME/.hermes/hermes-agent/plugins/platforms/rocketchat"
|
dst="$HOME/.hermes/hermes-agent/plugins/platforms/rocketchat"
|
||||||
|
log "Eigener venv-Pfad: $dst"
|
||||||
else
|
else
|
||||||
# pipx-venv: Plugin unter site-packages/plugins/platforms/rocketchat/
|
# pipx-venv: Plugin unter site-packages/plugins/platforms/rocketchat/
|
||||||
local site_packages
|
local site_packages
|
||||||
@@ -390,9 +425,22 @@ deploy_plugin() {
|
|||||||
site_packages="<PIPX_VENV>/lib/python3.13/site-packages"
|
site_packages="<PIPX_VENV>/lib/python3.13/site-packages"
|
||||||
fi
|
fi
|
||||||
dst="$site_packages/plugins/platforms/rocketchat"
|
dst="$site_packages/plugins/platforms/rocketchat"
|
||||||
|
log "site-packages-Pfad (Fallback): $dst"
|
||||||
fi
|
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
|
if ! $DRY_RUN; then
|
||||||
mkdir -p "$dst"
|
mkdir -p "$dst"
|
||||||
|
|
||||||
@@ -424,6 +472,20 @@ deploy_plugin() {
|
|||||||
local count
|
local count
|
||||||
count=$(find "$dst" -type f ! -path '*/__pycache__/*' | wc -l)
|
count=$(find "$dst" -type f ! -path '*/__pycache__/*' | wc -l)
|
||||||
ok "$count Plugin-Dateien deployed"
|
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
|
else
|
||||||
printf '%s[dry]%s cp -r %s/* -> %s/\\n' "$C_YELLOW" "$C_RESET" "$src" "$dst"
|
printf '%s[dry]%s cp -r %s/* -> %s/\\n' "$C_YELLOW" "$C_RESET" "$src" "$dst"
|
||||||
fi
|
fi
|
||||||
@@ -633,6 +695,17 @@ write_env_file() {
|
|||||||
echo "OLLAMA_KEEP_ALIVE=${OLLAMA_KEEP_ALIVE}"
|
echo "OLLAMA_KEEP_ALIVE=${OLLAMA_KEEP_ALIVE}"
|
||||||
} > "$envfile"
|
} > "$envfile"
|
||||||
chmod 600 "$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)"
|
ok ".env geschrieben: $envfile (chmod 600)"
|
||||||
else
|
else
|
||||||
printf '%s[dry]%s schreibe %s\n' "$C_YELLOW" "$C_RESET" "$envfile"
|
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!)
|
# 8. Gateway Service (systemd user service mit enable!)
|
||||||
# P5: Gateway braucht systemctl enable für Autostart
|
# 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() {
|
install_gateway_service() {
|
||||||
banner "8. Gateway Service"
|
banner "8. Gateway Service"
|
||||||
|
|
||||||
@@ -801,29 +943,29 @@ EOF
|
|||||||
ok "Ollama neugestartet (OLLAMA_KEEP_ALIVE=$OLLAMA_KEEP_ALIVE aktiv)"
|
ok "Ollama neugestartet (OLLAMA_KEEP_ALIVE=$OLLAMA_KEEP_ALIVE aktiv)"
|
||||||
fi
|
fi
|
||||||
|
|
||||||
systemctl --user daemon-reload
|
gateway_daemon_reload
|
||||||
|
|
||||||
# State-Cleanup (Discovery-Bug + Auto-Resume-Loop)
|
# State-Cleanup (Discovery-Bug + Auto-Resume-Loop)
|
||||||
rm -f "$HOME/.hermes/gateway_state.json" \
|
rm -f "$HOME/.hermes/gateway_state.json" \
|
||||||
"$HOME/.hermes/gateway.lock" \
|
"$HOME/.hermes/gateway.lock" \
|
||||||
"$HOME/.hermes/.gateway_state_"*.tmp 2>/dev/null || true
|
"$HOME/.hermes/.gateway_state_"*.tmp 2>/dev/null || true
|
||||||
rm -f "$HOME/.hermes/state.db" 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
|
# P5: ENABLE! Sonst kein Autostart nach Reboot
|
||||||
systemctl --user enable hermes-gateway
|
gateway_systemctl enable
|
||||||
ok "hermes-gateway enabled (P5: Autostart nach Reboot)"
|
ok "hermes-gateway enabled (P5: Autostart nach Reboot)"
|
||||||
|
|
||||||
# Starten
|
# Starten
|
||||||
systemctl --user stop hermes-gateway 2>/dev/null || true
|
gateway_systemctl stop 2>/dev/null || true
|
||||||
local wait=0
|
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))
|
sleep 1; wait=$((wait + 1))
|
||||||
done
|
done
|
||||||
systemctl --user start hermes-gateway 2>/dev/null || true
|
gateway_systemctl start 2>/dev/null || true
|
||||||
ok "Gateway gestartet"
|
ok "Gateway gestartet"
|
||||||
else
|
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
|
fi
|
||||||
}
|
}
|
||||||
|
|
||||||
@@ -853,12 +995,20 @@ verify_installation() {
|
|||||||
if "$VENV_PY" -c 'import snowballstemmer' 2>/dev/null; then
|
if "$VENV_PY" -c 'import snowballstemmer' 2>/dev/null; then
|
||||||
ok "snowballstemmer in pipx-venv importierbar (P1)"
|
ok "snowballstemmer in pipx-venv importierbar (P1)"
|
||||||
else
|
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
|
fi
|
||||||
|
|
||||||
# Plugin-Dateien
|
# Plugin-Dateien
|
||||||
local plugin_dir
|
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"
|
plugin_dir="$HOME/.hermes/hermes-agent/plugins/platforms/rocketchat"
|
||||||
else
|
else
|
||||||
local sp
|
local sp
|
||||||
@@ -912,7 +1062,7 @@ verify_installation() {
|
|||||||
[ $env_ok -eq 1 ] && ok ".env vollständig"
|
[ $env_ok -eq 1 ] && ok ".env vollständig"
|
||||||
|
|
||||||
# Gateway service enabled (P5)
|
# 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)"
|
ok "hermes-gateway enabled (P5: Autostart)"
|
||||||
else
|
else
|
||||||
err "FAIL: hermes-gateway nicht enabled (P5)"; fail=1
|
err "FAIL: hermes-gateway nicht enabled (P5)"; fail=1
|
||||||
@@ -937,7 +1087,7 @@ verify_installation() {
|
|||||||
# journalctl ist die zuverlässige Quelle.
|
# journalctl ist die zuverlässige Quelle.
|
||||||
if command -v journalctl >/dev/null 2>&1; then
|
if command -v journalctl >/dev/null 2>&1; then
|
||||||
local no_adapter
|
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
|
if [ "${no_adapter:-0}" -gt 0 ]; then
|
||||||
err "FAIL: Gateway-Log zeigt 'No adapter' — Plugin nicht geladen (Erkenntnis 5)"
|
err "FAIL: Gateway-Log zeigt 'No adapter' — Plugin nicht geladen (Erkenntnis 5)"
|
||||||
fail=1
|
fail=1
|
||||||
@@ -1135,7 +1285,14 @@ check_gitea_ssh_key() {
|
|||||||
}
|
}
|
||||||
|
|
||||||
# SSH-Key-Check VOR Repo-Bootstrap (P11)
|
# 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)
|
# Repo-Bootstrap (falls install.sh standalone aufgerufen wurde)
|
||||||
bootstrap_repo "$@"
|
bootstrap_repo "$@"
|
||||||
@@ -1184,10 +1341,10 @@ if $CHECK_ONLY; then
|
|||||||
banner "P13: Erweiterte Checks"
|
banner "P13: Erweiterte Checks"
|
||||||
|
|
||||||
# 1. Gateway-Status
|
# 1. Gateway-Status
|
||||||
if systemctl --user is-active hermes-gateway >/dev/null 2>&1; then
|
if gateway_is_active; then
|
||||||
ok "hermes-gateway: active"
|
ok "hermes-gateway: active"
|
||||||
else
|
else
|
||||||
warn "hermes-gateway: nicht aktiv (systemctl --user is-active hermes-gateway)"
|
warn "hermes-gateway: nicht aktiv"
|
||||||
fi
|
fi
|
||||||
|
|
||||||
# 2. REST-Login-Ping gegen ROCKETCHAT_BASE_URL (falls Credentials vorhanden)
|
# 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"
|
|| die "pipx-venv nicht gefunden — vorher Normal-Install ausführen"
|
||||||
VENV_PY="$PIPX_VENV/bin/python"
|
VENV_PY="$PIPX_VENV/bin/python"
|
||||||
|
|
||||||
# Ziel-Pfad ermitteln
|
# Ziel-Pfad ermitteln (gleiche Logik wie deploy_plugin)
|
||||||
if [ "$PIPX_VENV" = "$HOME/.hermes/hermes-agent/venv" ]; then
|
_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"
|
_update_dst="$HOME/.hermes/hermes-agent/plugins/platforms/rocketchat"
|
||||||
else
|
else
|
||||||
_update_site_packages="$(find_site_packages "$PIPX_VENV")"
|
_update_site_packages="$(find_site_packages "$PIPX_VENV")"
|
||||||
@@ -1292,30 +1452,30 @@ if $UPDATE_ONLY; then
|
|||||||
|
|
||||||
# ── Schritt 4: Gateway-Dienst neu starten ──
|
# ── Schritt 4: Gateway-Dienst neu starten ──
|
||||||
if ! $DRY_RUN; then
|
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
|
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
|
if $NO_RESTART; then
|
||||||
ok "Gateway-Neustart übersprungen (--no-restart)"
|
ok "Gateway-Neustart übersprungen (--no-restart)"
|
||||||
else
|
else
|
||||||
log "Starte Gateway neu..."
|
log "Starte Gateway neu..."
|
||||||
systemctl --user restart hermes-gateway 2>/dev/null || true
|
restart_gateway 2>/dev/null || true
|
||||||
|
|
||||||
# Warte bis active (max 30s)
|
# Warte bis active (max 30s)
|
||||||
_update_wait=0
|
_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
|
sleep 1
|
||||||
_update_wait=$((_update_wait + 1))
|
_update_wait=$((_update_wait + 1))
|
||||||
done
|
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)"
|
ok "Gateway neugestartet und aktiv (nach ${_update_wait}s)"
|
||||||
else
|
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
|
||||||
fi
|
fi
|
||||||
else
|
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
|
fi
|
||||||
|
|
||||||
# ── Schritt 5: Post-Deployment-Verifikation ──
|
# ── Schritt 5: Post-Deployment-Verifikation ──
|
||||||
@@ -1334,7 +1494,7 @@ if $UPDATE_ONLY; then
|
|||||||
_all_ok=true
|
_all_ok=true
|
||||||
|
|
||||||
# Prüfe auf PresenceEngine/presence
|
# 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
|
if [ "${_update_presence_hits:-0}" -gt 0 ]; then
|
||||||
ok "PresenceEngine im Log gefunden ($_update_presence_hits Treffer)"
|
ok "PresenceEngine im Log gefunden ($_update_presence_hits Treffer)"
|
||||||
else
|
else
|
||||||
@@ -1343,7 +1503,7 @@ if $UPDATE_ONLY; then
|
|||||||
fi
|
fi
|
||||||
|
|
||||||
# Prüfe auf 'Archivar initialisiert'
|
# 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
|
if [ "${_update_archivar_hits:-0}" -gt 0 ]; then
|
||||||
ok "'Archivar initialisiert' im Log gefunden ($_update_archivar_hits Treffer)"
|
ok "'Archivar initialisiert' im Log gefunden ($_update_archivar_hits Treffer)"
|
||||||
else
|
else
|
||||||
@@ -1352,7 +1512,7 @@ if $UPDATE_ONLY; then
|
|||||||
fi
|
fi
|
||||||
|
|
||||||
# Prüfe auf 'Connected to'
|
# 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
|
if [ "${_update_connected_hits:-0}" -gt 0 ]; then
|
||||||
ok "'Connected to' im Log gefunden ($_update_connected_hits Treffer)"
|
ok "'Connected to' im Log gefunden ($_update_connected_hits Treffer)"
|
||||||
else
|
else
|
||||||
@@ -1447,6 +1607,6 @@ verify_installation
|
|||||||
if ! $DRY_RUN; then
|
if ! $DRY_RUN; then
|
||||||
echo ""
|
echo ""
|
||||||
ok "Fertig. Bot sollte laufen — prüfe mit:"
|
ok "Fertig. Bot sollte laufen — prüfe mit:"
|
||||||
echo " systemctl --user status hermes-gateway"
|
echo " gateway_systemctl status"
|
||||||
echo " journalctl --user -u hermes-gateway -f"
|
echo " gateway_journalctl -f"
|
||||||
fi
|
fi
|
||||||
+899
-1016
File diff suppressed because it is too large
Load Diff
@@ -0,0 +1,108 @@
|
|||||||
|
"""
|
||||||
|
Gemeinsamer Button-Builder für Onboarding und Review-Flow.
|
||||||
|
|
||||||
|
Extrahiert aus onboarding_review.py (P0-1), damit adapter.py und
|
||||||
|
onboarding_review.py die GLEICHE Button-Konstruktion nutzen — kein Drift.
|
||||||
|
|
||||||
|
Regeln:
|
||||||
|
- Nummerierte Buttons: max 3 pro Attachment, mit 1️⃣ 2️⃣ 3️⃣...
|
||||||
|
- Sonderschaltflächen (↩️ Zurück, ⏭️ Skip, ➕ Neu): KEINE Nummer,
|
||||||
|
IMMER in separatem (letztem) Attachment
|
||||||
|
- Jedes Attachment hat max 3 actions
|
||||||
|
"""
|
||||||
|
|
||||||
|
from typing import Any, List, Tuple
|
||||||
|
|
||||||
|
# Emoji-Nummern für bis zu 10 Buttons
|
||||||
|
EMOJI_NUMBERS = ["1️⃣", "2️⃣", "3️⃣", "4️⃣", "5️⃣", "6️⃣", "7️⃣", "8️⃣", "9️⃣", "🔟"]
|
||||||
|
|
||||||
|
|
||||||
|
def build_button_attachments(
|
||||||
|
num_buttons: List[Tuple[Any, ...]],
|
||||||
|
special_buttons: List[Tuple[Any, ...]],
|
||||||
|
color: str = "#1d74f5",
|
||||||
|
title: str = "",
|
||||||
|
number_buttons: bool = True,
|
||||||
|
button_style: str = "primary",
|
||||||
|
) -> List[dict]:
|
||||||
|
"""Baut Attachments nach Andreas' 2-Reihen-Button-Pattern.
|
||||||
|
|
||||||
|
Regeln:
|
||||||
|
- Nummerierte Buttons: max 3 pro Attachment, mit 1️⃣ 2️⃣ 3️⃣...
|
||||||
|
(Nummerierung kann via number_buttons=False deaktiviert werden)
|
||||||
|
- Sonderschaltflächen (↩️ Zurück, ⏭️ Skip, ➕ Neu): KEINE Nummer,
|
||||||
|
IMMER in separatem (letztem) Attachment
|
||||||
|
- Jedes Attachment hat max 3 actions
|
||||||
|
|
||||||
|
P0-Fix: msg-Payload mit '::' Suffix für Button-Klick-Erkennung.
|
||||||
|
num_buttons: (label, prefix) oder (label, prefix, suffix)
|
||||||
|
special_buttons: (label, prefix, style) oder (label, prefix, suffix, style)
|
||||||
|
Wenn suffix vorhanden: msg = f'{prefix}::{suffix}'
|
||||||
|
Sonst (backward-compat): msg = prefix
|
||||||
|
|
||||||
|
Args:
|
||||||
|
num_buttons: Liste von (label, prefix[, suffix]) Tuples
|
||||||
|
special_buttons: Liste von (label, prefix, style[, suffix]) Tuples
|
||||||
|
color: Attachment-Farbe (default: "#1d74f5")
|
||||||
|
title: Attachment-Titel (nur für erstes Attachment)
|
||||||
|
number_buttons: Wenn False, werden Buttons NICHT nummeriert
|
||||||
|
(z.B. für X-Buttons in Keywords-Edit)
|
||||||
|
button_style: Rocket.Chat button style für num_buttons (default: "primary")
|
||||||
|
|
||||||
|
Returns:
|
||||||
|
Liste von Attachment-Dicts (jedes mit max 3 actions)
|
||||||
|
"""
|
||||||
|
attachments: List[dict] = []
|
||||||
|
|
||||||
|
# Nummerierte Buttons in 3er-Blöcke aufteilen
|
||||||
|
for i in range(0, len(num_buttons), 3):
|
||||||
|
chunk = num_buttons[i:i + 3]
|
||||||
|
actions = []
|
||||||
|
for j, tup in enumerate(chunk):
|
||||||
|
label = tup[0]
|
||||||
|
prefix = tup[1]
|
||||||
|
suffix = tup[2] if len(tup) >= 3 else None
|
||||||
|
msg_payload = f"{prefix}::{suffix}" if suffix else prefix
|
||||||
|
if number_buttons:
|
||||||
|
num_idx = i + j
|
||||||
|
emoji = EMOJI_NUMBERS[num_idx] if num_idx < len(EMOJI_NUMBERS) else str(num_idx + 1)
|
||||||
|
text = f"{emoji} {label}"
|
||||||
|
else:
|
||||||
|
text = label
|
||||||
|
actions.append({
|
||||||
|
"type": "button",
|
||||||
|
"text": text,
|
||||||
|
"msg": msg_payload,
|
||||||
|
"msg_in_chat_window": True,
|
||||||
|
"style": button_style,
|
||||||
|
})
|
||||||
|
att = {
|
||||||
|
"color": color,
|
||||||
|
"actions": actions,
|
||||||
|
}
|
||||||
|
if i == 0 and title:
|
||||||
|
att["title"] = title
|
||||||
|
attachments.append(att)
|
||||||
|
|
||||||
|
# Sonderschaltflächen in separatem Attachment
|
||||||
|
if special_buttons:
|
||||||
|
special_actions = []
|
||||||
|
for tup in special_buttons:
|
||||||
|
label = tup[0]
|
||||||
|
prefix = tup[1]
|
||||||
|
style = tup[2]
|
||||||
|
suffix = tup[3] if len(tup) >= 4 else None
|
||||||
|
msg_payload = f"{prefix}::{suffix}" if suffix else prefix
|
||||||
|
special_actions.append({
|
||||||
|
"type": "button",
|
||||||
|
"text": label,
|
||||||
|
"msg": msg_payload,
|
||||||
|
"msg_in_chat_window": True,
|
||||||
|
"style": style,
|
||||||
|
})
|
||||||
|
attachments.append({
|
||||||
|
"color": color,
|
||||||
|
"actions": special_actions,
|
||||||
|
})
|
||||||
|
|
||||||
|
return attachments
|
||||||
@@ -154,85 +154,10 @@ def _persist_room_map_changes(
|
|||||||
|
|
||||||
|
|
||||||
# ── UX REFACTOR: build_button_attachments() Helper ──────────────────────────
|
# ── UX REFACTOR: build_button_attachments() Helper ──────────────────────────
|
||||||
|
# P0-1: In gemeinsames Modul button_builder.py extrahiert,
|
||||||
|
# damit adapter.py und onboarding_review.py die GLEICHE Button-Konstruktion nutzen.
|
||||||
|
|
||||||
# Emoji-Nummern für bis zu 10 Buttons
|
from archivar.button_builder import build_button_attachments, EMOJI_NUMBERS
|
||||||
_EMOJI_NUMBERS = ["1️⃣", "2️⃣", "3️⃣", "4️⃣", "5️⃣", "6️⃣", "7️⃣", "8️⃣", "9️⃣", "🔟"]
|
|
||||||
|
|
||||||
|
|
||||||
def build_button_attachments(
|
|
||||||
num_buttons: List[Tuple[str, str]],
|
|
||||||
special_buttons: List[Tuple[str, str, str]],
|
|
||||||
color: str = "#1d74f5",
|
|
||||||
title: str = "",
|
|
||||||
number_buttons: bool = True,
|
|
||||||
button_style: str = "primary",
|
|
||||||
) -> List[dict]:
|
|
||||||
"""Baut Attachments nach Andreas' 2-Reihen-Button-Pattern.
|
|
||||||
|
|
||||||
Regeln:
|
|
||||||
- Nummerierte Buttons: max 3 pro Attachment, mit 1️⃣ 2️⃣ 3️⃣...
|
|
||||||
(Nummerierung kann via number_buttons=False deaktiviert werden)
|
|
||||||
- Sonderschaltflächen (↩️ Zurück, ⏭️ Skip, ➕ Neu): KEINE Nummer,
|
|
||||||
IMMER in separatem (letztem) Attachment
|
|
||||||
- Jedes Attachment hat max 3 actions
|
|
||||||
|
|
||||||
Args:
|
|
||||||
num_buttons: Liste von (label, prefix) Tuples für nummerierte Buttons
|
|
||||||
special_buttons: Liste von (label, prefix, style) Tuples für Sonderschaltflächen
|
|
||||||
color: Attachment-Farbe (default: "#1d74f5")
|
|
||||||
title: Attachment-Titel (nur für erstes Attachment)
|
|
||||||
number_buttons: Wenn False, werden Buttons NICHT nummeriert
|
|
||||||
(z.B. für X-Buttons in Keywords-Edit)
|
|
||||||
button_style: Rocket.Chat button style für num_buttons (default: "primary")
|
|
||||||
|
|
||||||
Returns:
|
|
||||||
Liste von Attachment-Dicts (jedes mit max 3 actions)
|
|
||||||
"""
|
|
||||||
attachments: List[dict] = []
|
|
||||||
|
|
||||||
# Nummerierte Buttons in 3er-Blöcke aufteilen
|
|
||||||
for i in range(0, len(num_buttons), 3):
|
|
||||||
chunk = num_buttons[i:i + 3]
|
|
||||||
actions = []
|
|
||||||
for j, (label, prefix) in enumerate(chunk):
|
|
||||||
if number_buttons:
|
|
||||||
num_idx = i + j
|
|
||||||
emoji = _EMOJI_NUMBERS[num_idx] if num_idx < len(_EMOJI_NUMBERS) else str(num_idx + 1)
|
|
||||||
text = f"{emoji} {label}"
|
|
||||||
else:
|
|
||||||
text = label
|
|
||||||
actions.append({
|
|
||||||
"type": "button",
|
|
||||||
"text": text,
|
|
||||||
"msg": prefix,
|
|
||||||
"msg_in_chat_window": True,
|
|
||||||
"style": button_style,
|
|
||||||
})
|
|
||||||
att = {
|
|
||||||
"color": color,
|
|
||||||
"actions": actions,
|
|
||||||
}
|
|
||||||
if i == 0 and title:
|
|
||||||
att["title"] = title
|
|
||||||
attachments.append(att)
|
|
||||||
|
|
||||||
# Sonderschaltflächen in separatem Attachment
|
|
||||||
if special_buttons:
|
|
||||||
special_actions = []
|
|
||||||
for label, prefix, style in special_buttons:
|
|
||||||
special_actions.append({
|
|
||||||
"type": "button",
|
|
||||||
"text": label,
|
|
||||||
"msg": prefix,
|
|
||||||
"msg_in_chat_window": True,
|
|
||||||
"style": style,
|
|
||||||
})
|
|
||||||
attachments.append({
|
|
||||||
"color": color,
|
|
||||||
"actions": special_actions,
|
|
||||||
})
|
|
||||||
|
|
||||||
return attachments
|
|
||||||
|
|
||||||
|
|
||||||
# ── Schritt 1: review_room Top-Level Renderer ─────────────────────────────
|
# ── Schritt 1: review_room Top-Level Renderer ─────────────────────────────
|
||||||
@@ -297,7 +222,7 @@ def render_review_room_step(
|
|||||||
# Nummerierte Optionen im Text
|
# Nummerierte Optionen im Text
|
||||||
lines.append("👉 Klicke auf einen Raum zum Anpassen:")
|
lines.append("👉 Klicke auf einen Raum zum Anpassen:")
|
||||||
for i, (label, _) in enumerate(num_buttons):
|
for i, (label, _) in enumerate(num_buttons):
|
||||||
emoji = _EMOJI_NUMBERS[i] if i < len(_EMOJI_NUMBERS) else str(i + 1)
|
emoji = EMOJI_NUMBERS[i] if i < len(EMOJI_NUMBERS) else str(i + 1)
|
||||||
lines.append(f" {emoji} {label}")
|
lines.append(f" {emoji} {label}")
|
||||||
|
|
||||||
# Sonderschaltflächen
|
# Sonderschaltflächen
|
||||||
@@ -672,10 +597,21 @@ def render_review_room_add_new(
|
|||||||
(text, attachments) Tuple
|
(text, attachments) Tuple
|
||||||
"""
|
"""
|
||||||
if not available_rooms:
|
if not available_rooms:
|
||||||
|
# P0-4: Auch bei leerer Liste einen Zurück-Button rendern,
|
||||||
|
# damit der User nicht in einer UX-Sackgasse steckt.
|
||||||
|
special_buttons: List[Tuple[str, str, str]] = [
|
||||||
|
("↩️ Zurück", REVIEW_ROOM_BACK, "default"),
|
||||||
|
]
|
||||||
|
attachments = build_button_attachments(
|
||||||
|
[],
|
||||||
|
special_buttons,
|
||||||
|
color="#1d74f5",
|
||||||
|
title="Neuen Raum hinzufügen",
|
||||||
|
)
|
||||||
return (
|
return (
|
||||||
"📋 **Neuer Raum** — Keine weiteren Räume verfügbar.\n"
|
"📋 **Neuer Raum** — Keine weiteren Räume verfügbar.\n"
|
||||||
"Alle Rocket.Chat-Räume sind bereits in der Room-Map.",
|
"Alle Rocket.Chat-Räume sind bereits in der Room-Map.",
|
||||||
[],
|
attachments,
|
||||||
)
|
)
|
||||||
|
|
||||||
lines = [
|
lines = [
|
||||||
@@ -691,7 +627,7 @@ def render_review_room_add_new(
|
|||||||
name = room.get("name", rid)
|
name = room.get("name", rid)
|
||||||
rtype = room.get("type", "c")
|
rtype = room.get("type", "c")
|
||||||
type_label = "💬" if rtype == "d" else "#"
|
type_label = "💬" if rtype == "d" else "#"
|
||||||
emoji = _EMOJI_NUMBERS[i] if i < len(_EMOJI_NUMBERS) else str(i + 1)
|
emoji = EMOJI_NUMBERS[i] if i < len(EMOJI_NUMBERS) else str(i + 1)
|
||||||
lines.append(f" {emoji} {type_label} {name}")
|
lines.append(f" {emoji} {type_label} {name}")
|
||||||
# Kurzer Button-Name (max 9 Zeichen)
|
# Kurzer Button-Name (max 9 Zeichen)
|
||||||
short_name = name[:9] if len(name) > 9 else name
|
short_name = name[:9] if len(name) > 9 else name
|
||||||
|
|||||||
@@ -80,8 +80,14 @@ class PresenceEngine:
|
|||||||
Thread-safe: uses threading.Lock for all counter operations.
|
Thread-safe: uses threading.Lock for all counter operations.
|
||||||
Coalesce-Timer: prevents flickering by delaying status updates by 2s.
|
Coalesce-Timer: prevents flickering by delaying status updates by 2s.
|
||||||
Heartbeat: pulses online↔away when background_tasks > 0 and agent is idle.
|
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__(
|
def __init__(
|
||||||
self,
|
self,
|
||||||
rest=None,
|
rest=None,
|
||||||
@@ -137,6 +143,12 @@ class PresenceEngine:
|
|||||||
self._background_tasks: int = 0
|
self._background_tasks: int = 0
|
||||||
self._background_tasks_lock = threading.Lock()
|
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)
|
# P0-1: PulseController — DDP-basierte Heartbeat-Pulsierung (1.5s)
|
||||||
self._pulse_controller = PulseController(
|
self._pulse_controller = PulseController(
|
||||||
pulse_interval=pulse_interval,
|
pulse_interval=pulse_interval,
|
||||||
@@ -150,9 +162,10 @@ class PresenceEngine:
|
|||||||
on_change=self._on_detection_change,
|
on_change=self._on_detection_change,
|
||||||
)
|
)
|
||||||
|
|
||||||
# Start detection if enabled
|
# P1b: DetectionTimer NICHT im Init starten — erst nach on_connected_cb.
|
||||||
if self._enabled:
|
# Der Adapter ruft _detection_timer.start() explizit auf, sobald die
|
||||||
self._detection_timer.start()
|
# DDP-Verbindung steht. Das verhindert eine Race-Condition bei der
|
||||||
|
# ersten gateway_state.json-Auswertung (Datei existiert ggf. noch nicht).
|
||||||
|
|
||||||
# ── Public API ───────────────────────────────────────────────────────
|
# ── Public API ───────────────────────────────────────────────────────
|
||||||
|
|
||||||
@@ -160,10 +173,20 @@ class PresenceEngine:
|
|||||||
"""Check if presence updates are enabled."""
|
"""Check if presence updates are enabled."""
|
||||||
return self._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:
|
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._enabled = True
|
||||||
self._detection_timer.start()
|
|
||||||
logger.info("[presence] PresenceEngine enabled")
|
logger.info("[presence] PresenceEngine enabled")
|
||||||
|
|
||||||
def disable(self) -> None:
|
def disable(self) -> None:
|
||||||
@@ -194,13 +217,142 @@ class PresenceEngine:
|
|||||||
self._active_tasks -= 1
|
self._active_tasks -= 1
|
||||||
count = self._active_tasks
|
count = self._active_tasks
|
||||||
# FIX: Resume pulse when all active tasks complete.
|
# FIX: Resume pulse when all active tasks complete.
|
||||||
# on_agent_busy() pauses the pulse, but resume() was never called
|
# mark_busy_started() pauses the pulse via adapter, but resume()
|
||||||
# in production — the pulse stayed paused forever.
|
# was never called in production — the pulse stayed paused forever.
|
||||||
if count == 0:
|
if count == 0:
|
||||||
self._pulse_controller.resume()
|
self._pulse_controller.resume()
|
||||||
logger.info("[presence] active_tasks=0 → pulse resumed")
|
logger.info("[presence] active_tasks=0 → pulse resumed")
|
||||||
return count
|
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:
|
||||||
|
# B2: _busy_started_at nur beim ERSTEN busy-Start setzen.
|
||||||
|
# Wenn der Honeymoon-Timer bereits abgelaufen ist (Timer=None)
|
||||||
|
# aber _busy_started_at noch existiert (weil active > 0),
|
||||||
|
# dann NICHT neu setzen — sonst künstliche Verlängerung um 1s.
|
||||||
|
if self._busy_started_at == 0.0:
|
||||||
|
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, started_at=%.3f",
|
||||||
|
self.MIN_BUSY_VISIBLE_S, self._busy_counter, self._busy_started_at,
|
||||||
|
)
|
||||||
|
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.
|
||||||
|
B3: Checks pending_status under _active_tasks_lock to prevent
|
||||||
|
race with mark_busy_started.
|
||||||
|
"""
|
||||||
|
with self._busy_honeymoon_lock:
|
||||||
|
self._busy_honeymoon_timer = None
|
||||||
|
|
||||||
|
with self._active_tasks_lock:
|
||||||
|
active = self._active_tasks
|
||||||
|
|
||||||
|
if active == 0:
|
||||||
|
# B3: Race-Schutz — prüfe ob pending_status 'busy' ist.
|
||||||
|
# mark_busy_started könnte parallel update_presence() mit
|
||||||
|
# pending='busy' aufgerufen haben. Dann NICHT überschreiben.
|
||||||
|
with self._coalesce_lock:
|
||||||
|
pending = self._pending_status
|
||||||
|
if pending == "busy":
|
||||||
|
logger.debug(
|
||||||
|
"[presence] Honeymoon-Timer abgelaufen, aber pending_status=busy — "
|
||||||
|
"nicht überschreiben (Race-Schutz)"
|
||||||
|
)
|
||||||
|
return
|
||||||
|
# B2: Reset _busy_started_at when honeymoon fully expires
|
||||||
|
# and no active tasks remain — next busy cycle starts fresh.
|
||||||
|
self._busy_started_at = 0.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:
|
def set_onboarding_active(self, active: bool) -> None:
|
||||||
"""Set the onboarding sentinel."""
|
"""Set the onboarding sentinel."""
|
||||||
self._onboarding_active = active
|
self._onboarding_active = active
|
||||||
@@ -429,6 +581,7 @@ class PresenceEngine:
|
|||||||
"""Clean shutdown: stop PulseController, DetectionTimer, cancel coalesce timer."""
|
"""Clean shutdown: stop PulseController, DetectionTimer, cancel coalesce timer."""
|
||||||
self._pulse_controller.stop()
|
self._pulse_controller.stop()
|
||||||
self._detection_timer.stop()
|
self._detection_timer.stop()
|
||||||
|
self._cancel_honeymoon_timer()
|
||||||
with self._coalesce_lock:
|
with self._coalesce_lock:
|
||||||
if self._coalesce_timer is not None:
|
if self._coalesce_timer is not None:
|
||||||
self._coalesce_timer.cancel()
|
self._coalesce_timer.cancel()
|
||||||
@@ -444,24 +597,6 @@ class PresenceEngine:
|
|||||||
"""
|
"""
|
||||||
self._pulse_controller.cancel_pending()
|
self._pulse_controller.cancel_pending()
|
||||||
|
|
||||||
def on_agent_busy(self, room_name: str = "") -> None:
|
|
||||||
"""Hook: Agent is processing a message — pause pulse, set busy.
|
|
||||||
|
|
||||||
Priority 1 (highest): busy (rot) — Nachricht wird verarbeitet.
|
|
||||||
"""
|
|
||||||
self.set_current_room(room_name)
|
|
||||||
self.increment_active_tasks()
|
|
||||||
self.update_presence()
|
|
||||||
# Pause pulse if running
|
|
||||||
self._pulse_controller.pause()
|
|
||||||
|
|
||||||
def on_message_received(self, room_name: str = "") -> None:
|
|
||||||
"""Hook: Message received — same as on_agent_busy.
|
|
||||||
|
|
||||||
Alias for on_agent_busy for semantic clarity.
|
|
||||||
"""
|
|
||||||
self.on_agent_busy(room_name=room_name)
|
|
||||||
|
|
||||||
|
|
||||||
# ═══════════════════════════════════════════════════════════════════════════
|
# ═══════════════════════════════════════════════════════════════════════════
|
||||||
# PulseController — DDP-basierte Heartbeat-Pulsierung (1.5s Intervall)
|
# PulseController — DDP-basierte Heartbeat-Pulsierung (1.5s Intervall)
|
||||||
@@ -501,7 +636,7 @@ class PulseController:
|
|||||||
self._phase: bool = False # False=online, True=away
|
self._phase: bool = False # False=online, True=away
|
||||||
self._last_sent_phase: Optional[bool] = None
|
self._last_sent_phase: Optional[bool] = None
|
||||||
self._background_count: int = 0
|
self._background_count: int = 0
|
||||||
self._cancel_pending: bool = False # P0-2: skip next tick flag
|
self._cancel_pending_event = threading.Event() # B6: thread-safe via Event statt bool
|
||||||
# P1-2 O-2: Async-await bridge
|
# P1-2 O-2: Async-await bridge
|
||||||
self._loop: Optional[asyncio.AbstractEventLoop] = None
|
self._loop: Optional[asyncio.AbstractEventLoop] = None
|
||||||
self._await_timeout: float = 2.0
|
self._await_timeout: float = 2.0
|
||||||
@@ -612,7 +747,7 @@ class PulseController:
|
|||||||
status fires while the PulseController is running.
|
status fires while the PulseController is running.
|
||||||
Sets a flag that the next tick will skip.
|
Sets a flag that the next tick will skip.
|
||||||
"""
|
"""
|
||||||
self._cancel_pending = True
|
self._cancel_pending_event.set()
|
||||||
logger.debug("[pulse] cancel_pending: next tick will be skipped")
|
logger.debug("[pulse] cancel_pending: next tick will be skipped")
|
||||||
|
|
||||||
# ── Internal: Pulse Loop ─────────────────────────────────────────────
|
# ── Internal: Pulse Loop ─────────────────────────────────────────────
|
||||||
@@ -661,13 +796,14 @@ class PulseController:
|
|||||||
self._phase,
|
self._phase,
|
||||||
self._ddp is not None,
|
self._ddp is not None,
|
||||||
self._paused.is_set(),
|
self._paused.is_set(),
|
||||||
self._cancel_pending,
|
self._cancel_pending_event.is_set(),
|
||||||
self._loop is not None,
|
self._loop is not None,
|
||||||
)
|
)
|
||||||
|
|
||||||
# P0-2: Check cancel_pending flag (set by PresenceEngine._set_presence)
|
# P0-2: Check cancel_pending flag (set by PresenceEngine._set_presence)
|
||||||
if self._cancel_pending:
|
# B6: thread-safe via threading.Event statt bool
|
||||||
self._cancel_pending = False
|
if self._cancel_pending_event.is_set():
|
||||||
|
self._cancel_pending_event.clear()
|
||||||
logger.debug("[pulse] _pulse_tick skip: cancel_pending was set")
|
logger.debug("[pulse] _pulse_tick skip: cancel_pending was set")
|
||||||
return
|
return
|
||||||
|
|
||||||
@@ -689,7 +825,17 @@ class PulseController:
|
|||||||
self._pulse_tick_async(),
|
self._pulse_tick_async(),
|
||||||
self._loop,
|
self._loop,
|
||||||
)
|
)
|
||||||
future.result(timeout=self._pulse_interval)
|
# B5: Polling mit Pause-Check — pause() wirkt in 50ms statt 1.5s.
|
||||||
|
# future.result(timeout=...) blockiert bis zu pulse_interval,
|
||||||
|
# währenddessen kann pause() nicht greifen.
|
||||||
|
while not future.done():
|
||||||
|
if self._paused.is_set():
|
||||||
|
future.cancel()
|
||||||
|
logger.debug("[pulse] _pulse_tick async cancelled by pause")
|
||||||
|
break
|
||||||
|
time.sleep(0.05)
|
||||||
|
if not future.cancelled():
|
||||||
|
future.result(timeout=0) # already done, no blocking
|
||||||
return
|
return
|
||||||
except Exception as e:
|
except Exception as e:
|
||||||
logger.info(
|
logger.info(
|
||||||
@@ -810,8 +956,12 @@ class PulseController:
|
|||||||
class DetectionTimer:
|
class DetectionTimer:
|
||||||
"""Detects whether background agents are active.
|
"""Detects whether background agents are active.
|
||||||
|
|
||||||
Checks gateway_state.json for active_agents > 1.
|
P1b: gateway_state.json is PRIMARY — active_agents > 1 means active.
|
||||||
Falls back to pgrep for 'hermes chat --profile' processes.
|
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.
|
Calls on_change callback when detection state changes.
|
||||||
"""
|
"""
|
||||||
@@ -870,53 +1020,66 @@ class DetectionTimer:
|
|||||||
def check(self) -> bool:
|
def check(self) -> bool:
|
||||||
"""Check if background agents are active.
|
"""Check if background agents are active.
|
||||||
|
|
||||||
pgrep is the PRIMARY signal — always executed, regardless of gateway_state.
|
P1b: gateway_state.json is PRIMARY — active_agents > 1 means active.
|
||||||
gateway_state is SECONDARY — read only for diagnostic logging, never for decisions.
|
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:
|
Returns:
|
||||||
True if pgrep finds other hermes chat processes (self-excluded),
|
True if background agents are detected, False otherwise.
|
||||||
False otherwise.
|
|
||||||
"""
|
"""
|
||||||
self._check_count += 1
|
self._check_count += 1
|
||||||
self._increment_telemetry()
|
self._increment_telemetry()
|
||||||
|
|
||||||
result = False
|
result = False
|
||||||
pgrep_pids = -1 # -1 = not yet run, >=0 = count, stays -1 on error
|
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_active = 0
|
||||||
|
gateway_used = False # True if gateway_state was the deciding signal
|
||||||
|
|
||||||
|
# ── PRIMARY: gateway_state.json ────────────────────────────────────
|
||||||
try:
|
try:
|
||||||
if os.path.exists(self._gateway_state_path):
|
if os.path.exists(self._gateway_state_path):
|
||||||
with open(self._gateway_state_path, 'r') as f:
|
with open(self._gateway_state_path, 'r') as f:
|
||||||
state = json.load(f)
|
state = json.load(f)
|
||||||
gateway_active = state.get("active_agents", 0)
|
gateway_active = state.get("active_agents", 0)
|
||||||
|
if gateway_active > 1:
|
||||||
|
result = True
|
||||||
|
gateway_used = True
|
||||||
except (json.JSONDecodeError, IOError, OSError) as e:
|
except (json.JSONDecodeError, IOError, OSError) as e:
|
||||||
logger.debug("[detection] gateway_state.json read failed: %s", 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 ─────────────────────────────────────
|
# ── Log: both signals, result ─────────────────────────────────────
|
||||||
pgrep_str = str(pgrep_pids) if pgrep_pids >= 0 else "error"
|
pgrep_str = str(pgrep_pids) if pgrep_pids >= 0 else "error"
|
||||||
logger.info(
|
logger.info(
|
||||||
"[detection] check #%d: pgrep=%s, gateway_state=%d, result=%s",
|
"[detection] check #%d: gateway_state=%d (primary=%s), pgrep=%s, result=%s",
|
||||||
self._check_count, pgrep_str, gateway_active,
|
self._check_count, gateway_active,
|
||||||
|
"yes" if gateway_used else "no",
|
||||||
|
pgrep_str,
|
||||||
"active" if result else "inactive",
|
"active" if result else "inactive",
|
||||||
)
|
)
|
||||||
|
|
||||||
|
|||||||
@@ -20,6 +20,47 @@ import pytest
|
|||||||
# Ensure the plugin package is importable
|
# Ensure the plugin package is importable
|
||||||
sys.path.insert(0, str(Path(__file__).resolve().parents[2]))
|
sys.path.insert(0, str(Path(__file__).resolve().parents[2]))
|
||||||
|
|
||||||
|
|
||||||
|
# ═══════════════════════════════════════════════════════════════════════════
|
||||||
|
# B4: Autouse fixture — engine.shutdown() nach jedem Test
|
||||||
|
# Verhindert dass Honeymoon-/Coalesce-/Pulse-/Detection-Timer in
|
||||||
|
# nachfolgende Tests leaken (20-30% Failure-Rate).
|
||||||
|
# ═══════════════════════════════════════════════════════════════════════════
|
||||||
|
|
||||||
|
_ENGINE_REGISTRY: list = []
|
||||||
|
|
||||||
|
|
||||||
|
@pytest.fixture(autouse=True)
|
||||||
|
def _shutdown_presence_engines():
|
||||||
|
"""Track all PresenceEngine instances and call shutdown() after each test.
|
||||||
|
|
||||||
|
Monkey-patches PresenceEngine.__init__ to register every instance.
|
||||||
|
After the test (in finally), calls engine.shutdown() on all registered
|
||||||
|
instances — stops Honeymoon, Coalesce, PulseController, DetectionTimer.
|
||||||
|
"""
|
||||||
|
from plugin.archivar.presence_engine import PresenceEngine
|
||||||
|
|
||||||
|
_original_init = PresenceEngine.__init__
|
||||||
|
|
||||||
|
def _tracking_init(self, *args, **kwargs):
|
||||||
|
_original_init(self, *args, **kwargs)
|
||||||
|
_ENGINE_REGISTRY.append(self)
|
||||||
|
|
||||||
|
PresenceEngine.__init__ = _tracking_init
|
||||||
|
_ENGINE_REGISTRY.clear()
|
||||||
|
|
||||||
|
try:
|
||||||
|
yield
|
||||||
|
finally:
|
||||||
|
PresenceEngine.__init__ = _original_init
|
||||||
|
for engine in _ENGINE_REGISTRY:
|
||||||
|
try:
|
||||||
|
engine.shutdown()
|
||||||
|
except Exception:
|
||||||
|
pass
|
||||||
|
_ENGINE_REGISTRY.clear()
|
||||||
|
|
||||||
|
|
||||||
# ═══════════════════════════════════════════════════════════════════════════
|
# ═══════════════════════════════════════════════════════════════════════════
|
||||||
# Phase 1: Basis-PresenceEngine
|
# Phase 1: Basis-PresenceEngine
|
||||||
# ═══════════════════════════════════════════════════════════════════════════
|
# ═══════════════════════════════════════════════════════════════════════════
|
||||||
@@ -880,17 +921,17 @@ class TestPulseControllerLastSentPhase:
|
|||||||
|
|
||||||
|
|
||||||
class TestDetectionTimerPgrepPrimary:
|
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):
|
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
|
from plugin.archivar.presence_engine import DetectionTimer
|
||||||
import tempfile
|
import tempfile
|
||||||
import json
|
import json
|
||||||
|
|
||||||
own_pid = os.getpid()
|
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"]}
|
state = {"active_agents": 1, "profiles": ["default"]}
|
||||||
with tempfile.NamedTemporaryFile(suffix=".json", delete=False, mode="w") as f:
|
with tempfile.NamedTemporaryFile(suffix=".json", delete=False, mode="w") as f:
|
||||||
json.dump(state, f)
|
json.dump(state, f)
|
||||||
@@ -910,50 +951,44 @@ class TestDetectionTimerPgrepPrimary:
|
|||||||
detection_interval=0.1,
|
detection_interval=0.1,
|
||||||
)
|
)
|
||||||
result = dt.check()
|
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
|
assert result is True
|
||||||
finally:
|
finally:
|
||||||
os.unlink(state_path)
|
os.unlink(state_path)
|
||||||
|
|
||||||
def test_pgrep_finds_no_other_agents(self):
|
def test_gateway_state_primary_active(self):
|
||||||
"""pgrep findet nur eigenen Prozess → result=False (gateway_state irrelevant)."""
|
"""P1b: gateway_state active_agents=3 (>1) → PRIMARY entscheidet → result=True, pgrep NICHT aufgerufen."""
|
||||||
from plugin.archivar.presence_engine import DetectionTimer
|
from plugin.archivar.presence_engine import DetectionTimer
|
||||||
import tempfile
|
import tempfile
|
||||||
import json
|
import json
|
||||||
|
|
||||||
own_pid = os.getpid()
|
# gateway_state mit active_agents=3 (>1 → PRIMARY entscheidet)
|
||||||
|
|
||||||
# gateway_state mit active_agents=3 (würde früher True liefern)
|
|
||||||
state = {"active_agents": 3, "profiles": ["default", "miguel", "anna"]}
|
state = {"active_agents": 3, "profiles": ["default", "miguel", "anna"]}
|
||||||
with tempfile.NamedTemporaryFile(suffix=".json", delete=False, mode="w") as f:
|
with tempfile.NamedTemporaryFile(suffix=".json", delete=False, mode="w") as f:
|
||||||
json.dump(state, f)
|
json.dump(state, f)
|
||||||
state_path = f.name
|
state_path = f.name
|
||||||
|
|
||||||
try:
|
try:
|
||||||
# Mock pgrep: findet nur eigenen Prozess
|
# Mock pgrep: sollte NICHT aufgerufen werden
|
||||||
with patch('plugin.archivar.presence_engine.subprocess.run') as mock_run:
|
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(
|
dt = DetectionTimer(
|
||||||
gateway_state_path=state_path,
|
gateway_state_path=state_path,
|
||||||
detection_interval=0.1,
|
detection_interval=0.1,
|
||||||
)
|
)
|
||||||
result = dt.check()
|
result = dt.check()
|
||||||
# pgrep findet nur eigenen Prozess → False (gateway_state=3 wird ignoriert)
|
# gateway_state=3 > 1 → PRIMARY entscheidet → True
|
||||||
assert result is False
|
assert result is True
|
||||||
|
# pgrep wurde NICHT aufgerufen (gateway_state hat entschieden)
|
||||||
|
mock_run.assert_not_called()
|
||||||
finally:
|
finally:
|
||||||
os.unlink(state_path)
|
os.unlink(state_path)
|
||||||
|
|
||||||
|
|
||||||
class TestDetectionTimerPgrepNoGatewayState:
|
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):
|
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
|
from plugin.archivar.presence_engine import DetectionTimer
|
||||||
|
|
||||||
own_pid = os.getpid()
|
own_pid = os.getpid()
|
||||||
@@ -997,10 +1032,10 @@ class TestDetectionTimerPgrepNoGatewayState:
|
|||||||
|
|
||||||
|
|
||||||
class TestDetectionTimerIntegration:
|
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):
|
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
|
from plugin.archivar.presence_engine import DetectionTimer
|
||||||
|
|
||||||
own_pid = os.getpid()
|
own_pid = os.getpid()
|
||||||
@@ -1009,7 +1044,7 @@ class TestDetectionTimerIntegration:
|
|||||||
def on_detection_change(is_active):
|
def on_detection_change(is_active):
|
||||||
callback_results.append(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:
|
with patch('plugin.archivar.presence_engine.subprocess.run') as mock_run:
|
||||||
mock_run.return_value = MagicMock(
|
mock_run.return_value = MagicMock(
|
||||||
stdout=f"{own_pid}\n99999\n",
|
stdout=f"{own_pid}\n99999\n",
|
||||||
@@ -1101,10 +1136,10 @@ class TestEdgeCaseReconnectRace:
|
|||||||
|
|
||||||
|
|
||||||
class TestEdgeCaseOnAgentBusy:
|
class TestEdgeCaseOnAgentBusy:
|
||||||
"""Test 31: on_agent_busy() — pausiert Pulse, setzt busy (rot)."""
|
"""Test 31: mark_busy_started() + pause() — pausiert Pulse, setzt busy (rot)."""
|
||||||
|
|
||||||
def test_on_agent_busy_pauses_pulse(self):
|
def test_on_agent_busy_pauses_pulse(self):
|
||||||
"""on_agent_busy() pausiert den PulseController und setzt busy."""
|
"""mark_busy_started() + pause() pausiert den PulseController und setzt busy."""
|
||||||
from plugin.archivar.presence_engine import PresenceEngine
|
from plugin.archivar.presence_engine import PresenceEngine
|
||||||
|
|
||||||
mock_rest = MagicMock()
|
mock_rest = MagicMock()
|
||||||
@@ -1129,8 +1164,9 @@ class TestEdgeCaseOnAgentBusy:
|
|||||||
time.sleep(0.1)
|
time.sleep(0.1)
|
||||||
assert engine._pulse_controller.is_running()
|
assert engine._pulse_controller.is_running()
|
||||||
|
|
||||||
# on_agent_busy: pausiert Pulse
|
# A3: mark_busy_started + pause ersetzt on_agent_busy (toter Code entfernt)
|
||||||
engine.on_agent_busy(room_name="#Test")
|
engine.mark_busy_started(room_name="#Test")
|
||||||
|
engine._pulse_controller.pause()
|
||||||
|
|
||||||
time.sleep(0.1)
|
time.sleep(0.1)
|
||||||
# Pulse sollte pausiert sein
|
# Pulse sollte pausiert sein
|
||||||
@@ -1163,8 +1199,9 @@ class TestEdgeCaseOnAgentBusy:
|
|||||||
engine._pulse_controller.start()
|
engine._pulse_controller.start()
|
||||||
engine._background_tasks = 3
|
engine._background_tasks = 3
|
||||||
|
|
||||||
# on_agent_busy
|
# A3: mark_busy_started + pause ersetzt on_agent_busy
|
||||||
engine.on_agent_busy(room_name="#Test")
|
engine.mark_busy_started(room_name="#Test")
|
||||||
|
engine._pulse_controller.pause()
|
||||||
time.sleep(0.1)
|
time.sleep(0.1)
|
||||||
|
|
||||||
# Task beendet → decrement + update
|
# Task beendet → decrement + update
|
||||||
@@ -1179,10 +1216,10 @@ class TestEdgeCaseOnAgentBusy:
|
|||||||
|
|
||||||
|
|
||||||
class TestEdgeCaseOnMessageReceived:
|
class TestEdgeCaseOnMessageReceived:
|
||||||
"""Test 32: on_message_received() — wie on_agent_busy, pausiert Pulse."""
|
"""Test 32: mark_busy_started() + pause() — wie on_agent_busy, pausiert Pulse."""
|
||||||
|
|
||||||
def test_on_message_received_pauses_pulse(self):
|
def test_on_message_received_pauses_pulse(self):
|
||||||
"""on_message_received() verhält sich wie on_agent_busy()."""
|
"""mark_busy_started() + pause() verhält sich wie on_agent_busy()."""
|
||||||
from plugin.archivar.presence_engine import PresenceEngine
|
from plugin.archivar.presence_engine import PresenceEngine
|
||||||
|
|
||||||
mock_rest = MagicMock()
|
mock_rest = MagicMock()
|
||||||
@@ -1203,8 +1240,9 @@ class TestEdgeCaseOnMessageReceived:
|
|||||||
time.sleep(0.1)
|
time.sleep(0.1)
|
||||||
assert engine._pulse_controller.is_running()
|
assert engine._pulse_controller.is_running()
|
||||||
|
|
||||||
# on_message_received → wie on_agent_busy
|
# A3: mark_busy_started + pause ersetzt on_message_received
|
||||||
engine.on_message_received(room_name="#Test")
|
engine.mark_busy_started(room_name="#Test")
|
||||||
|
engine._pulse_controller.pause()
|
||||||
|
|
||||||
time.sleep(0.1)
|
time.sleep(0.1)
|
||||||
assert not engine._pulse_controller.is_running() or engine._pulse_controller._paused.is_set()
|
assert not engine._pulse_controller.is_running() or engine._pulse_controller._paused.is_set()
|
||||||
@@ -1264,7 +1302,7 @@ class TestP0LiveVerdrahtung:
|
|||||||
assert not engine._pulse_controller.is_running()
|
assert not engine._pulse_controller.is_running()
|
||||||
|
|
||||||
def test_detection_timer_starts_when_enabled(self):
|
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
|
from plugin.archivar.presence_engine import PresenceEngine
|
||||||
|
|
||||||
mock_rest = MagicMock()
|
mock_rest = MagicMock()
|
||||||
@@ -1273,7 +1311,11 @@ class TestP0LiveVerdrahtung:
|
|||||||
|
|
||||||
engine = PresenceEngine(rest=mock_rest, enabled=True)
|
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()
|
assert engine._detection_timer._running.is_set()
|
||||||
|
|
||||||
def test_detection_timer_not_started_when_disabled(self):
|
def test_detection_timer_not_started_when_disabled(self):
|
||||||
@@ -1536,3 +1578,202 @@ class TestPresenceClarificationPending:
|
|||||||
f"Klärung sollte away setzen (nicht busy), bekam: {data['status']}"
|
f"Klärung sollte away setzen (nicht busy), bekam: {data['status']}"
|
||||||
)
|
)
|
||||||
assert "Klärung" in data["message"]
|
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}"
|
||||||
|
)
|
||||||
|
|||||||
@@ -327,6 +327,9 @@ class TestRenderReviewRoomAddNew:
|
|||||||
def test_renders_empty_available(self):
|
def test_renders_empty_available(self):
|
||||||
text, attachments = render_review_room_add_new([], _mock_build_buttons)
|
text, attachments = render_review_room_add_new([], _mock_build_buttons)
|
||||||
assert "Keine weiteren Räume verfügbar" in text
|
assert "Keine weiteren Räume verfügbar" in text
|
||||||
|
# P0-4: Zurück-Button muss auch bei leerer Liste gerendert werden
|
||||||
|
assert len(attachments) > 0, "Leere Liste muss Zurück-Button rendern"
|
||||||
|
assert "Zurück" in str(attachments)
|
||||||
|
|
||||||
|
|
||||||
# ── dispatch_review_button ──────────────────────────────────────────────────
|
# ── dispatch_review_button ──────────────────────────────────────────────────
|
||||||
|
|||||||
+1
-1
@@ -1,4 +1,4 @@
|
|||||||
name: rocketchat-platform
|
name: rocketchat
|
||||||
label: Rocket.Chat
|
label: Rocket.Chat
|
||||||
kind: platform
|
kind: platform
|
||||||
version: 1.0.0
|
version: 1.0.0
|
||||||
|
|||||||
+60
-2
@@ -413,7 +413,7 @@ class TestPulseControllerPauseInAsyncMode:
|
|||||||
|
|
||||||
# Setze cancel_pending
|
# Setze cancel_pending
|
||||||
pc.cancel_pending()
|
pc.cancel_pending()
|
||||||
assert pc._cancel_pending is True
|
assert pc._cancel_pending_event.is_set()
|
||||||
|
|
||||||
# _pulse_tick sollte übersprungen werden
|
# _pulse_tick sollte übersprungen werden
|
||||||
pc._pulse_tick()
|
pc._pulse_tick()
|
||||||
@@ -421,7 +421,7 @@ class TestPulseControllerPauseInAsyncMode:
|
|||||||
# set_status sollte NICHT aufgerufen worden sein
|
# set_status sollte NICHT aufgerufen worden sein
|
||||||
mock_ddp.set_status.assert_not_called()
|
mock_ddp.set_status.assert_not_called()
|
||||||
# cancel_pending sollte zurückgesetzt sein
|
# cancel_pending sollte zurückgesetzt sein
|
||||||
assert pc._cancel_pending is False
|
assert not pc._cancel_pending_event.is_set()
|
||||||
|
|
||||||
|
|
||||||
# ═══════════════════════════════════════════════════════════════════════════
|
# ═══════════════════════════════════════════════════════════════════════════
|
||||||
@@ -481,3 +481,61 @@ class TestLegacyTimerSetStatusRemainsSync:
|
|||||||
adapter.ddp.set_status("away")
|
adapter.ddp.set_status("away")
|
||||||
|
|
||||||
mock_ddp.set_status.assert_called_with("away")
|
mock_ddp.set_status.assert_called_with("away")
|
||||||
|
|
||||||
|
|
||||||
|
# ═══════════════════════════════════════════════════════════════════════════
|
||||||
|
# Test 11: B1 — disconnect clears pending Futures with DDPNotConnected
|
||||||
|
# ═══════════════════════════════════════════════════════════════════════════
|
||||||
|
|
||||||
|
class TestDisconnectClearsPendingFutures:
|
||||||
|
"""B1: disconnect() löst alle pending Futures mit DDPNotConnected auf."""
|
||||||
|
|
||||||
|
def test_disconnect_clears_pending_futures(self):
|
||||||
|
"""Engine erstellt, set_status_async aufrufen, disconnect() → DDPNotConnected."""
|
||||||
|
client = _make_ddp_client(connected=True)
|
||||||
|
client._send_json = MagicMock()
|
||||||
|
|
||||||
|
async def _run():
|
||||||
|
# Starte set_status_async — registriert einen Future
|
||||||
|
task = asyncio.create_task(client.set_status_async("online", timeout=5.0))
|
||||||
|
await asyncio.sleep(0.05)
|
||||||
|
|
||||||
|
# Verifiziere: Future ist registriert
|
||||||
|
with client._result_lock:
|
||||||
|
assert len(client._pending_results) == 1
|
||||||
|
|
||||||
|
# Disconnect — muss den Future mit DDPNotConnected auflösen
|
||||||
|
client.disconnect()
|
||||||
|
|
||||||
|
# Der Task sollte jetzt DDPNotConnected werfen
|
||||||
|
with pytest.raises(DDPNotConnected) as exc_info:
|
||||||
|
await task
|
||||||
|
assert "connection closed" in str(exc_info.value).lower()
|
||||||
|
|
||||||
|
# _pending_results muss leer sein
|
||||||
|
with client._result_lock:
|
||||||
|
assert len(client._pending_results) == 0
|
||||||
|
|
||||||
|
asyncio.run(_run())
|
||||||
|
|
||||||
|
def test_reader_loop_exit_clears_pending_futures(self):
|
||||||
|
"""Simuliere reader-loop exit: _cancel_pending_results wird aufgerufen."""
|
||||||
|
client = _make_ddp_client(connected=True)
|
||||||
|
client._send_json = MagicMock()
|
||||||
|
|
||||||
|
# Registriere einen pending Future manuell
|
||||||
|
future = concurrent.futures.Future()
|
||||||
|
with client._result_lock:
|
||||||
|
client._pending_results["st9999999999_1"] = future
|
||||||
|
|
||||||
|
# Simuliere reader-loop exit (wie in _reader_loop nach while-Schleife)
|
||||||
|
client._cancel_pending_results()
|
||||||
|
|
||||||
|
# Future muss DDPNotConnected haben
|
||||||
|
assert future.done()
|
||||||
|
with pytest.raises(DDPNotConnected):
|
||||||
|
future.result()
|
||||||
|
|
||||||
|
# Store muss leer sein
|
||||||
|
with client._result_lock:
|
||||||
|
assert len(client._pending_results) == 0
|
||||||
|
|||||||
@@ -0,0 +1,311 @@
|
|||||||
|
"""
|
||||||
|
P0 Integration-Test: Onboarding-Button-Klick setzt Raum-Theme korrekt.
|
||||||
|
|
||||||
|
ROOT CAUSE: button_builder.py setzte msg = prefix (nur 'ONBOARD:<rid>'),
|
||||||
|
ohne '::' Suffix. _process_onboarding_response erwartet '::' als Trigger
|
||||||
|
fuer Button-Klick-Handler. Ohne '::' -> Fallthrough zu Text-Antwort-Handler
|
||||||
|
-> Theme wird mit Room-ID als Literal ueberschrieben (stille Korruption).
|
||||||
|
|
||||||
|
Dieser Test verifiziert:
|
||||||
|
1. ONBOARD:<rid>::select_<rid> wird als Button-Klick erkannt
|
||||||
|
2. _handle_onboarding_button_click wird aufgerufen (nicht interview answer)
|
||||||
|
3. build_button_attachments produziert korrekte msg-Payloads
|
||||||
|
4. Backward-compat: 2-Tupel ohne suffix -> msg = prefix
|
||||||
|
"""
|
||||||
|
|
||||||
|
from __future__ import annotations
|
||||||
|
|
||||||
|
import asyncio
|
||||||
|
import sys
|
||||||
|
from pathlib import Path
|
||||||
|
from unittest.mock import AsyncMock, MagicMock, patch
|
||||||
|
|
||||||
|
import pytest
|
||||||
|
|
||||||
|
sys.path.insert(0, str(Path(__file__).resolve().parents[1]))
|
||||||
|
|
||||||
|
|
||||||
|
# ═══════════════════════════════════════════════════════════════════════════
|
||||||
|
# Helpers
|
||||||
|
# ═══════════════════════════════════════════════════════════════════════════
|
||||||
|
|
||||||
|
def _make_mock_adapter():
|
||||||
|
"""Erzeugt einen minimalen Mock-Adapter mit Onboarding-State."""
|
||||||
|
from plugin.adapter import RocketChatAdapter
|
||||||
|
|
||||||
|
adapter = RocketChatAdapter.__new__(RocketChatAdapter)
|
||||||
|
|
||||||
|
# Grundlegende Attribute
|
||||||
|
adapter._subscribed_rooms = set()
|
||||||
|
adapter._listen_task = None
|
||||||
|
adapter._status_timer = None
|
||||||
|
adapter._last_activity = 0.0
|
||||||
|
adapter._shutdown_event = MagicMock()
|
||||||
|
adapter._room_info = {}
|
||||||
|
adapter._pending_clarifies = {}
|
||||||
|
adapter._user_rooms = {}
|
||||||
|
adapter._rooms_with_pending_questions = set()
|
||||||
|
adapter._excluded_room_ids = set()
|
||||||
|
adapter._last_server_activity = 0.0
|
||||||
|
adapter._health_check_timer = None
|
||||||
|
adapter._last_ddp_ping_ok = False
|
||||||
|
adapter._running = False
|
||||||
|
adapter._pending_move_requests = {}
|
||||||
|
adapter._session_room_preferences = {}
|
||||||
|
adapter._recent_auto_routes = {}
|
||||||
|
adapter._explicit_switch_sticky = {}
|
||||||
|
adapter._clarify_state = {}
|
||||||
|
adapter._room_map_summary = ""
|
||||||
|
|
||||||
|
# Mock REST
|
||||||
|
mock_rest = MagicMock()
|
||||||
|
mock_rest.auth_token = "fake-token"
|
||||||
|
mock_rest.user_id = "fake-user-id"
|
||||||
|
mock_rest.post_message = MagicMock(return_value="msg_12345")
|
||||||
|
adapter.rest = mock_rest
|
||||||
|
|
||||||
|
# Mock Archivar
|
||||||
|
mock_archivar = MagicMock()
|
||||||
|
mock_archivar._room_map = MagicMock()
|
||||||
|
mock_archivar._stats = {"onboarding_active": True}
|
||||||
|
mock_archivar._state = MagicMock()
|
||||||
|
adapter.archivar = mock_archivar
|
||||||
|
|
||||||
|
# Mock Post-Message
|
||||||
|
adapter._post_message_with_retry = AsyncMock(return_value=True)
|
||||||
|
|
||||||
|
# Mock _ask_onboarding_question (damit kein echter Rocket.Chat-Call)
|
||||||
|
adapter._ask_onboarding_question = AsyncMock()
|
||||||
|
|
||||||
|
# Mock _onboarding_next_room
|
||||||
|
adapter._onboarding_next_room = AsyncMock()
|
||||||
|
|
||||||
|
return adapter
|
||||||
|
|
||||||
|
|
||||||
|
# ═══════════════════════════════════════════════════════════════════════════
|
||||||
|
# Tests: Dispatch-Pfad
|
||||||
|
# ═══════════════════════════════════════════════════════════════════════════
|
||||||
|
|
||||||
|
class TestOnboardingButtonClickDispatch:
|
||||||
|
"""P0: ONBOARD:<rid>::select_<rid> wird als Button-Klick erkannt."""
|
||||||
|
|
||||||
|
def test_button_click_with_suffix_starts_interview(self):
|
||||||
|
"""ONBOARD:<rid>::select_<rid> -> _handle_onboarding_button_click
|
||||||
|
-> Interview wird gestartet (current_room_index=0, current_question=1)."""
|
||||||
|
adapter = _make_mock_adapter()
|
||||||
|
|
||||||
|
test_rid = "room_test_123"
|
||||||
|
adapter._onboarding_state = {
|
||||||
|
"missing_rooms": [
|
||||||
|
{"room_id": test_rid, "name": "#Testraum"},
|
||||||
|
],
|
||||||
|
"current_room_index": -1,
|
||||||
|
"current_question": 0,
|
||||||
|
"collected_data": {},
|
||||||
|
"operator_room_id": "dm_operator",
|
||||||
|
"skipped_rooms": [],
|
||||||
|
}
|
||||||
|
|
||||||
|
# Simuliere Button-Klick mit :: Suffix (der Fix)
|
||||||
|
button_text = f"ONBOARD:{test_rid}::select_{test_rid}"
|
||||||
|
|
||||||
|
asyncio.run(adapter._process_onboarding_response(button_text, "dm_operator"))
|
||||||
|
|
||||||
|
state = adapter._onboarding_state
|
||||||
|
assert state["current_room_index"] == 0, (
|
||||||
|
f"current_room_index sollte 0 sein (Interview gestartet), "
|
||||||
|
f"ist aber {state['current_room_index']}"
|
||||||
|
)
|
||||||
|
assert state["current_question"] == 1, (
|
||||||
|
f"current_question sollte 1 sein (Frage 1: Theme), "
|
||||||
|
f"ist aber {state['current_question']}"
|
||||||
|
)
|
||||||
|
assert test_rid in state["collected_data"], (
|
||||||
|
f"collected_data sollte Eintrag fuer {test_rid} enthalten"
|
||||||
|
)
|
||||||
|
adapter._ask_onboarding_question.assert_called_once()
|
||||||
|
|
||||||
|
def test_button_click_without_suffix_is_silent_noop(self):
|
||||||
|
"""ONBOARD:<rid> ohne :: -> Fallthrough zu interview answer
|
||||||
|
-> current_q=0 -> early return (stiller No-Op, kein Interview)."""
|
||||||
|
adapter = _make_mock_adapter()
|
||||||
|
|
||||||
|
test_rid = "room_test_456"
|
||||||
|
adapter._onboarding_state = {
|
||||||
|
"missing_rooms": [
|
||||||
|
{"room_id": test_rid, "name": "#Bugraum"},
|
||||||
|
],
|
||||||
|
"current_room_index": -1,
|
||||||
|
"current_question": 0,
|
||||||
|
"collected_data": {},
|
||||||
|
"operator_room_id": "dm_operator",
|
||||||
|
"skipped_rooms": [],
|
||||||
|
}
|
||||||
|
|
||||||
|
# Simuliere Button-Klick OHNE :: Suffix (alter Bug)
|
||||||
|
button_text = f"ONBOARD:{test_rid}"
|
||||||
|
|
||||||
|
asyncio.run(adapter._process_onboarding_response(button_text, "dm_operator"))
|
||||||
|
|
||||||
|
state = adapter._onboarding_state
|
||||||
|
# Kein Interview gestartet — stiller No-Op
|
||||||
|
assert state["current_room_index"] == -1, (
|
||||||
|
f"Ohne :: sollte kein Interview gestartet werden, "
|
||||||
|
f"current_room_index ist {state['current_room_index']}"
|
||||||
|
)
|
||||||
|
assert state["current_question"] == 0
|
||||||
|
# _ask_onboarding_question wurde NICHT aufgerufen
|
||||||
|
adapter._ask_onboarding_question.assert_not_called()
|
||||||
|
|
||||||
|
def test_button_click_without_suffix_corrupts_theme_during_interview(self):
|
||||||
|
"""Der eigentliche Bug: Wenn Interview laeuft (current_q=1),
|
||||||
|
wird ONBOARD:<rid> ohne :: als Theme-Text interpretiert
|
||||||
|
-> Theme = 'ONBOARD:<rid>' (stille Korruption)."""
|
||||||
|
adapter = _make_mock_adapter()
|
||||||
|
|
||||||
|
test_rid = "room_test_789"
|
||||||
|
adapter._onboarding_state = {
|
||||||
|
"missing_rooms": [
|
||||||
|
{"room_id": test_rid, "name": "#Korrumpiert"},
|
||||||
|
],
|
||||||
|
"current_room_index": 0,
|
||||||
|
"current_question": 1, # Frage 1: Theme
|
||||||
|
"collected_data": {
|
||||||
|
test_rid: {"theme": "", "keywords_100": [], "keywords_context": [], "catch_all": False},
|
||||||
|
},
|
||||||
|
"operator_room_id": "dm_operator",
|
||||||
|
"skipped_rooms": [],
|
||||||
|
}
|
||||||
|
|
||||||
|
# Simuliere Button-Klick OHNE :: Suffix (alter Bug)
|
||||||
|
button_text = f"ONBOARD:{test_rid}"
|
||||||
|
|
||||||
|
asyncio.run(adapter._process_onboarding_response(button_text, "dm_operator"))
|
||||||
|
|
||||||
|
# BUG REPRODUZIERT: Theme wurde mit Room-ID als Literal ueberschrieben
|
||||||
|
state = adapter._onboarding_state
|
||||||
|
theme = state["collected_data"][test_rid]["theme"]
|
||||||
|
assert theme == f"ONBOARD:{test_rid}", (
|
||||||
|
f"BUG REPRODUZIERT: Theme wurde mit '{theme}' ueberschrieben "
|
||||||
|
f"(sollte NICHT die Room-ID als Literal enthalten)"
|
||||||
|
)
|
||||||
|
|
||||||
|
def test_button_click_with_suffix_does_not_corrupt_theme(self):
|
||||||
|
"""Mit :: Suffix: Button-Klick wird korrekt erkannt,
|
||||||
|
Theme bleibt unberuehrt (wird nicht mit Room-ID ueberschrieben)."""
|
||||||
|
adapter = _make_mock_adapter()
|
||||||
|
|
||||||
|
test_rid = "room_test_fixed"
|
||||||
|
adapter._onboarding_state = {
|
||||||
|
"missing_rooms": [
|
||||||
|
{"room_id": test_rid, "name": "#FixTest"},
|
||||||
|
],
|
||||||
|
"current_room_index": -1,
|
||||||
|
"current_question": 0,
|
||||||
|
"collected_data": {},
|
||||||
|
"operator_room_id": "dm_operator",
|
||||||
|
"skipped_rooms": [],
|
||||||
|
}
|
||||||
|
|
||||||
|
# Simuliere Button-Klick MIT :: Suffix (der Fix)
|
||||||
|
button_text = f"ONBOARD:{test_rid}::select_{test_rid}"
|
||||||
|
|
||||||
|
asyncio.run(adapter._process_onboarding_response(button_text, "dm_operator"))
|
||||||
|
|
||||||
|
state = adapter._onboarding_state
|
||||||
|
data = state["collected_data"].get(test_rid, {})
|
||||||
|
theme = data.get("theme", "")
|
||||||
|
assert theme == "", (
|
||||||
|
f"Theme sollte leer sein (''), ist aber '{theme}' — "
|
||||||
|
f"Room-ID wurde faelschlich als Theme gesetzt"
|
||||||
|
)
|
||||||
|
|
||||||
|
|
||||||
|
# ═══════════════════════════════════════════════════════════════════════════
|
||||||
|
# Tests: button_builder Payload
|
||||||
|
# ═══════════════════════════════════════════════════════════════════════════
|
||||||
|
|
||||||
|
class TestButtonBuilderPayload:
|
||||||
|
"""P0: build_button_attachments produziert korrekte msg-Payloads."""
|
||||||
|
|
||||||
|
def test_num_button_with_suffix_produces_double_colon(self):
|
||||||
|
"""3-Tupel (label, prefix, suffix) -> msg = 'prefix::suffix'."""
|
||||||
|
from plugin.archivar.button_builder import build_button_attachments
|
||||||
|
|
||||||
|
test_rid = "room_bb_test"
|
||||||
|
num_buttons = [
|
||||||
|
("Testraum", f"ONBOARD:{test_rid}", f"select_{test_rid}"),
|
||||||
|
]
|
||||||
|
|
||||||
|
attachments = build_button_attachments(
|
||||||
|
num_buttons, [], color="#1d74f5",
|
||||||
|
)
|
||||||
|
|
||||||
|
num_action = attachments[0]["actions"][0]
|
||||||
|
assert num_action["msg"] == f"ONBOARD:{test_rid}::select_{test_rid}", (
|
||||||
|
f"num_button msg sollte 'ONBOARD:{test_rid}::select_{test_rid}' sein, "
|
||||||
|
f"ist aber '{num_action['msg']}'"
|
||||||
|
)
|
||||||
|
|
||||||
|
def test_special_button_without_suffix_uses_prefix_only(self):
|
||||||
|
"""3-Tupel (label, prefix, style) ohne suffix -> msg = prefix (backward-compat)."""
|
||||||
|
from plugin.archivar.button_builder import build_button_attachments
|
||||||
|
|
||||||
|
special_buttons = [
|
||||||
|
("⏭️ Überspringen", "ONBOARD", "default"),
|
||||||
|
]
|
||||||
|
|
||||||
|
attachments = build_button_attachments(
|
||||||
|
[], special_buttons, color="#1d74f5",
|
||||||
|
)
|
||||||
|
|
||||||
|
special_action = attachments[0]["actions"][0]
|
||||||
|
assert special_action["msg"] == "ONBOARD", (
|
||||||
|
f"special_button msg sollte 'ONBOARD' sein (backward-compat), "
|
||||||
|
f"ist aber '{special_action['msg']}'"
|
||||||
|
)
|
||||||
|
|
||||||
|
def test_two_tuple_backward_compat(self):
|
||||||
|
"""2-Tupel (label, prefix) ohne suffix -> msg = prefix (backward-compat)."""
|
||||||
|
from plugin.archivar.button_builder import build_button_attachments
|
||||||
|
|
||||||
|
num_buttons = [
|
||||||
|
("ReviewRaum", "REVIEW_ROOM_EDIT::rid123::edit"),
|
||||||
|
]
|
||||||
|
|
||||||
|
attachments = build_button_attachments(
|
||||||
|
num_buttons, [], color="#1d74f5",
|
||||||
|
)
|
||||||
|
|
||||||
|
num_action = attachments[0]["actions"][0]
|
||||||
|
assert num_action["msg"] == "REVIEW_ROOM_EDIT::rid123::edit", (
|
||||||
|
f"2-Tupel msg sollte unveraendert 'REVIEW_ROOM_EDIT::rid123::edit' sein, "
|
||||||
|
f"ist aber '{num_action['msg']}'"
|
||||||
|
)
|
||||||
|
|
||||||
|
def test_mixed_buttons(self):
|
||||||
|
"""Gemischt: num_buttons mit suffix, special_buttons ohne suffix."""
|
||||||
|
from plugin.archivar.button_builder import build_button_attachments
|
||||||
|
|
||||||
|
test_rid = "room_mixed"
|
||||||
|
num_buttons = [
|
||||||
|
("Raum A", f"ONBOARD:{test_rid}", f"select_{test_rid}"),
|
||||||
|
("Raum B", f"ONBOARD:other_rid", f"select_other_rid"),
|
||||||
|
]
|
||||||
|
special_buttons = [
|
||||||
|
("⏭️ Skip", "ONBOARD", "default"),
|
||||||
|
("⏰ Später", "ONBOARD", "default"),
|
||||||
|
]
|
||||||
|
|
||||||
|
attachments = build_button_attachments(
|
||||||
|
num_buttons, special_buttons, color="#1d74f5",
|
||||||
|
)
|
||||||
|
|
||||||
|
# Erstes Attachment: num_buttons
|
||||||
|
assert attachments[0]["actions"][0]["msg"] == f"ONBOARD:{test_rid}::select_{test_rid}"
|
||||||
|
assert attachments[0]["actions"][1]["msg"] == "ONBOARD:other_rid::select_other_rid"
|
||||||
|
|
||||||
|
# Zweites Attachment: special_buttons
|
||||||
|
assert attachments[1]["actions"][0]["msg"] == "ONBOARD"
|
||||||
|
assert attachments[1]["actions"][1]["msg"] == "ONBOARD"
|
||||||
Reference in New Issue
Block a user