From df14b4b931a5a72a966469ed77584589d5edd9c1 Mon Sep 17 00:00:00 2001 From: "Bernd (Hermes)" Date: Sun, 2 Aug 2026 20:07:43 +0200 Subject: [PATCH] fix(presence): Busy-Done-Debounce verhindert vorzeitiges mark_busy_done (V8.9 P1) MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit PROBLEM: mark_busy_done im finally-Block von _process_incoming feuert 25ms nach mark_busy_started — der Status geht auf Grün, während der Agent noch 30-90s arbeitet. Ursache: handle_message() dispatched den Agent asynchron und kehrt sofort zurück, aber der finally-Block wartet nicht auf die tatsächliche Agent-Fertigstellung. LÖSUNG: Busy-Done-Debounce: Statt sofort mark_busy_done zu rufen, startet der finally-Block einen 3s-Timer. Jeder send()-Call resettet den Timer. Erst wenn 3s lang keine Nachricht mehr gesendet wurde, ist der Agent wirklich fertig und mark_busy_done wird aufgerufen. ÄNDERUNGEN (adapter.py): - __init__: _agent_dispatched_this_turn, _busy_done_debounce_task, _busy_done_debounce_lock - _process_incoming: Flag-Reset vor mark_busy_started; finally-Block startet _start_busy_done_debounce() statt sofort mark_busy_done - _dispatch_agent + main dispatch path: Flag auf True setzen - send(): _reset_busy_done_debounce() nach erfolgreichem Post - _send_split(): _reset_busy_done_debounce() pro Chunk - disconnect(): _cancel_busy_done_debounce() - Neue Methoden: _start_busy_done_debounce, _busy_done_debounce_timer, _reset_busy_done_debounce, _cancel_busy_done_debounce EDGE CASES: - Kein Agent dispatched (Inline-Command, Onboarding-Guard): mark_busy_done sofort - Agent sendet mehrere Nachrichten: Timer wird jedes Mal reset - Agent sendet Split-Nachrichten: Timer wird pro Chunk reset - disconnect(): Timer wird gecancelled ZUSÄTZLICH (presence_engine.py): pgrep-Block von pid_used/gateway_used/plugin_used entkoppelt — pgrep läuft jetzt immer (bereits deployed von Bernd). --- plugin/adapter.py | 116 ++++++++++++++++++++++++++--- plugin/archivar/presence_engine.py | 13 ++-- 2 files changed, 111 insertions(+), 18 deletions(-) diff --git a/plugin/adapter.py b/plugin/adapter.py index 7234d84..3a3ccdc 100644 --- a/plugin/adapter.py +++ b/plugin/adapter.py @@ -1251,6 +1251,14 @@ class RocketChatAdapter(BasePlatformAdapter): ) self._presence_engine = None # Graceful degradation -> alter Idle-Timer greift + # V8.9 P1: Busy-Done-Debounce — verhindert dass mark_busy_done feuert + # während der Agent noch arbeitet. Der finally-Block von _process_incoming + # startet einen 3s-Timer; jeder send()-Call resettet ihn. Erst wenn 3s + # lang keine Nachricht mehr gesendet wurde, ist der Agent wirklich fertig. + self._agent_dispatched_this_turn: bool = False + self._busy_done_debounce_task: Optional[asyncio.Task] = None + self._busy_done_debounce_lock = asyncio.Lock() + # Phase 5: SubagentTracker — Subagent-Status für PresenceEngine try: from archivar.subagent_tracker import get_tracker @@ -2235,6 +2243,8 @@ class RocketChatAdapter(BasePlatformAdapter): # B12: Background-Tasks zählen — Heartbeat-Message aktivieren self._presence_engine.increment_background_tasks() logger.info("[presence] mark_busy_started (room=%s)", room_name) + # V8.9 P1: Reset dispatch flag — wird in _dispatch_agent auf True gesetzt + self._agent_dispatched_this_turn = False try: # ── R5: Inline-Command-Erkennung (VOR Onboarding + Hermes-Dispatch) ── @@ -3527,6 +3537,8 @@ class RocketChatAdapter(BasePlatformAdapter): # P0-3: Agent-Dispatch-Task speichern für Cancel bei ::onboarding abort. # handle_message() erzeugt intern asyncio.create_task (Drain-Task). # Ohne Referenz kann ::onboarding abort den laufenden Agent-Task nicht killen. + # V8.9 P1: Flag setzen — der Agent wurde dispatched + self._agent_dispatched_this_turn = True self._agent_dispatch_task = asyncio.create_task( ctx.run(self.handle_message, event) ) @@ -3567,19 +3579,19 @@ class RocketChatAdapter(BasePlatformAdapter): except Exception as e2: logger.error("[rocketchat] COMMAND text fallback also failed: %s", e2) finally: - # ── V8.6 P1a: PresenceEngine — mark_busy_done (Honeymoon-Timer) ── - # try/finally garantiert decrement auch bei Exceptions/Errors. - # Phase 5: Reihenfolge getauscht — decrement_background_tasks VOR - # mark_busy_done, damit mark_busy_done den aktuellen background_tasks - # Stand sieht und entscheiden kann ob Subagent-Pulse nötig ist. + # ── V8.9 P1: PresenceEngine — Busy-Done-Debounce statt sofortigem mark_busy_done ── + # Der finally-Block von _process_incoming feuert, sobald handle_message() + # zurückkehrt — aber handle_message() dispatched den Agent nur asynchron + # und kehrt sofort zurück. Der Agent arbeitet dann noch 30-90s weiter. + # Statt sofort mark_busy_done zu rufen, starten wir einen 3s-Debounce-Timer. + # Jeder send()-Call resettet den Timer. Erst wenn 3s lang keine Nachricht + # mehr gesendet wurde, ist der Agent wirklich fertig. if _has_presence: - # B12: Background-Tasks decrement — Heartbeat-Message aktualisieren - self._presence_engine.decrement_background_tasks() - # P1a: mark_busy_done prüft jetzt intern background_tasks > 0 - self._presence_engine.mark_busy_done() - # P1-2: current_room zurücksetzen nach Verarbeitung - self._presence_engine.set_current_room("") - logger.info("[presence] mark_busy_done (turn complete)") + # _start_busy_done_debounce() ruft decrement_background_tasks + + # mark_busy_done entweder sofort (kein Agent dispatched) oder + # nach 3s Debounce (Agent wurde dispatched und ist jetzt still). + asyncio.create_task(self._start_busy_done_debounce()) + logger.info("[presence] Busy-Done-Debounce gestartet (turn complete)") # Phase 5: SubagentTracker — complete() NICHT im finally! # Der Background-Prozess läuft noch wenn der Turn endet. @@ -4661,6 +4673,75 @@ class RocketChatAdapter(BasePlatformAdapter): """ return MessageType.COMMAND if is_button_response else MessageType.TEXT + # ── V8.9 P1: Busy-Done-Debounce ───────────────────────────────────── + + async def _start_busy_done_debounce(self) -> None: + """Start a 3s debounce timer that calls mark_busy_done when it fires. + + Called from _process_incoming's finally block. If the agent was + dispatched this turn, we start a debounce instead of calling + mark_busy_done immediately. Every send() call resets the timer. + When the timer fires (3s of silence), the agent is truly done. + """ + async with self._busy_done_debounce_lock: + # Cancel any existing debounce + if self._busy_done_debounce_task is not None: + self._busy_done_debounce_task.cancel() + self._busy_done_debounce_task = None + + if not self._agent_dispatched_this_turn: + # No agent was dispatched — mark done immediately + if hasattr(self, '_presence_engine') and self._presence_engine is not None: + self._presence_engine.decrement_background_tasks() + self._presence_engine.mark_busy_done() + self._presence_engine.set_current_room("") + logger.info("[presence] mark_busy_done (no agent dispatched)") + return + + # Agent was dispatched — start debounce + self._busy_done_debounce_task = asyncio.create_task( + self._busy_done_debounce_timer() + ) + logger.debug("[presence] Busy-Done-Debounce gestartet (3s)") + + async def _busy_done_debounce_timer(self) -> None: + """Wait 3s, then call mark_busy_done if not reset.""" + try: + await asyncio.sleep(3.0) + async with self._busy_done_debounce_lock: + if self._busy_done_debounce_task is not None: + if hasattr(self, '_presence_engine') and self._presence_engine is not None: + self._presence_engine.decrement_background_tasks() + self._presence_engine.mark_busy_done() + self._presence_engine.set_current_room("") + logger.info("[presence] mark_busy_done (debounce fired — agent silent 3s)") + self._busy_done_debounce_task = None + except asyncio.CancelledError: + logger.debug("[presence] Busy-Done-Debounce gecancelled (send() reset)") + raise + + async def _reset_busy_done_debounce(self) -> None: + """Reset the debounce timer — called from send() when agent sends a message. + + If no debounce is running, this is a no-op (agent wasn't dispatched + this turn, or mark_busy_done already fired). + """ + async with self._busy_done_debounce_lock: + if self._busy_done_debounce_task is not None: + self._busy_done_debounce_task.cancel() + self._busy_done_debounce_task = asyncio.create_task( + self._busy_done_debounce_timer() + ) + logger.debug("[presence] Busy-Done-Debounce reset (agent sent message)") + + async def _cancel_busy_done_debounce(self) -> None: + """Cancel the debounce timer — called from disconnect().""" + async with self._busy_done_debounce_lock: + if self._busy_done_debounce_task is not None: + self._busy_done_debounce_task.cancel() + self._busy_done_debounce_task = None + logger.debug("[presence] Busy-Done-Debounce gecancelled (disconnect)") + async def _dispatch_agent( self, text: str, @@ -4750,6 +4831,9 @@ class RocketChatAdapter(BasePlatformAdapter): _target[:8] if _target else "", ) # P0-3: Agent-Dispatch-Task speichern für Cancel bei ::onboarding abort. + # V8.9 P1: Flag setzen — der Agent wurde dispatched, Busy-Done-Debounce + # wird im finally-Block von _process_incoming gestartet. + self._agent_dispatched_this_turn = True self._agent_dispatch_task = asyncio.create_task( ctx.run(self.handle_message, event) ) @@ -6550,6 +6634,8 @@ class RocketChatAdapter(BasePlatformAdapter): return text async def disconnect(self) -> None: + # ── V8.9 P1: Busy-Done-Debounce canceln ── + await self._cancel_busy_done_debounce() # ── P1b: Gate-Sweep-Task sauber beenden ── if hasattr(self, '_gate_sweep_task') and self._gate_sweep_task is not None: self._gate_sweep_task.cancel() @@ -6966,6 +7052,10 @@ class RocketChatAdapter(BasePlatformAdapter): # dekrementiert (line 2794). send() kann mehrfach pro Turn # aufgerufen werden (Multi-Message, Split) — ein decrement hier # würde den Agenten vorzeitig auf "online" setzen. + # ── V8.9 P1: Busy-Done-Debounce reset — Agent sendet noch ── + # Jeder erfolgreiche send()-Call resettet den 3s-Debounce-Timer. + # Solange der Agent Nachrichten sendet, bleibt der Status busy. + asyncio.create_task(self._reset_busy_done_debounce()) return SendResult(success=True, message_id=str(int(time.time() * 1000))) finally: @@ -7038,6 +7128,8 @@ class RocketChatAdapter(BasePlatformAdapter): success = await self._post_message_with_retry(room_id, chunk_text) if success: last_msg_id = str(int(time.time() * 1000)) + # V8.9 P1: Busy-Done-Debounce reset pro Chunk + asyncio.create_task(self._reset_busy_done_debounce()) # Small delay between chunks to preserve order if i < total: await asyncio.sleep(0.5) diff --git a/plugin/archivar/presence_engine.py b/plugin/archivar/presence_engine.py index 607a89f..1cfff0c 100644 --- a/plugin/archivar/presence_engine.py +++ b/plugin/archivar/presence_engine.py @@ -1542,12 +1542,13 @@ class DetectionTimer: # ── V8.7: pgrep /proc scan — hermes chat --profile Prozesse ── # Ersetzt subagent_status.json als vierte Quelle. # Direkt /proc lesen, kein subprocess. - pgrep_count = 0 - if not pid_used and not gateway_used and not plugin_used: - pgrep_count = self._pgrep_hermes_subagents() - if pgrep_count > 0: - result = True - detection_source = "pgrep" + # V8.9: pgrep ALWAYS runs — not gated behind pid_sentinel/gateway_state. + # PID-Sentinel says "Gateway alive" (always true), pgrep says "Subagent active". + # Different semantics — pgrep must run independently. + pgrep_count = self._pgrep_hermes_subagents() + if pgrep_count > 0: + result = True + detection_source = "pgrep" # ── Log: all signals, result, source ─────────────────────────────── plugin_str = str(plugin_bg_tasks) if plugin_bg_tasks >= 0 else "n/a"