fix(P1a): Status busy minimum 1s sichtbar — Honeymoon-Timer gegen Coalesce-Überschreibung
This commit is contained in:
@@ -80,8 +80,14 @@ class PresenceEngine:
|
||||
Thread-safe: uses threading.Lock for all counter operations.
|
||||
Coalesce-Timer: prevents flickering by delaying status updates by 2s.
|
||||
Heartbeat: pulses online↔away when background_tasks > 0 and agent is idle.
|
||||
|
||||
P1a: Honeymoon-Timer ensures busy status is visible for at least
|
||||
MIN_BUSY_VISIBLE_S (1.0s) before transitioning to online.
|
||||
"""
|
||||
|
||||
# P1a: Minimum time busy status must be visible (prevents coalesce race)
|
||||
MIN_BUSY_VISIBLE_S = 1.0
|
||||
|
||||
def __init__(
|
||||
self,
|
||||
rest=None,
|
||||
@@ -137,6 +143,12 @@ class PresenceEngine:
|
||||
self._background_tasks: int = 0
|
||||
self._background_tasks_lock = threading.Lock()
|
||||
|
||||
# P1a: Honeymoon-Timer — busy status minimum 1s sichtbar
|
||||
self._busy_started_at: float = 0.0 # time.monotonic() when busy started
|
||||
self._busy_honeymoon_timer: Optional[threading.Timer] = None
|
||||
self._busy_honeymoon_lock = threading.Lock()
|
||||
self._busy_counter: int = 0 # multi-turn: count concurrent busy starts
|
||||
|
||||
# P0-1: PulseController — DDP-basierte Heartbeat-Pulsierung (1.5s)
|
||||
self._pulse_controller = PulseController(
|
||||
pulse_interval=pulse_interval,
|
||||
@@ -212,6 +224,115 @@ class PresenceEngine:
|
||||
logger.info("[presence] active_tasks=0 → pulse resumed")
|
||||
return count
|
||||
|
||||
# ── P1a: Honeymoon-Timer — busy minimum 1s sichtbar ──────────────────
|
||||
|
||||
def mark_busy_started(self, room_name: str = "") -> None:
|
||||
"""P1a: Mark the start of a busy period with honeymoon protection.
|
||||
|
||||
Sets the room, increments active_tasks, and schedules a busy status.
|
||||
If a honeymoon timer is already running (multi-turn), only increments
|
||||
the counter — no duplicate timer.
|
||||
|
||||
Args:
|
||||
room_name: Room name for the busy status message.
|
||||
"""
|
||||
self.set_current_room(room_name)
|
||||
self.increment_active_tasks()
|
||||
self.update_presence() # sets pending_status="busy"
|
||||
# P1a: Busy sofort flushen — nicht auf 2s Coalesce warten.
|
||||
# Der Honeymoon-Timer (1s) würde sonst vor dem Coalesce feuern.
|
||||
self._flush_presence()
|
||||
|
||||
with self._busy_honeymoon_lock:
|
||||
self._busy_counter += 1
|
||||
if self._busy_honeymoon_timer is None:
|
||||
# First busy start — record time and start honeymoon timer
|
||||
self._busy_started_at = time.monotonic()
|
||||
self._busy_honeymoon_timer = threading.Timer(
|
||||
self.MIN_BUSY_VISIBLE_S,
|
||||
self._honeymoon_expired,
|
||||
)
|
||||
self._busy_honeymoon_timer.daemon = True
|
||||
self._busy_honeymoon_timer.start()
|
||||
logger.debug(
|
||||
"[presence] Honeymoon-Timer gestartet (%.1fs), counter=%d",
|
||||
self.MIN_BUSY_VISIBLE_S, self._busy_counter,
|
||||
)
|
||||
else:
|
||||
logger.debug(
|
||||
"[presence] Honeymoon-Timer läuft bereits, counter=%d",
|
||||
self._busy_counter,
|
||||
)
|
||||
|
||||
def mark_busy_done(self) -> None:
|
||||
"""P1a: Mark the end of a busy period.
|
||||
|
||||
Decrements the busy counter. If the counter reaches 0 and the
|
||||
honeymoon has elapsed, transitions to online immediately.
|
||||
If the honeymoon hasn't elapsed yet, the timer callback will
|
||||
handle the transition when it fires.
|
||||
|
||||
Must be called in a finally block to ensure counter balance
|
||||
even on exceptions.
|
||||
"""
|
||||
with self._busy_honeymoon_lock:
|
||||
if self._busy_counter > 0:
|
||||
self._busy_counter -= 1
|
||||
counter = self._busy_counter
|
||||
|
||||
# Decrement the underlying active_tasks counter
|
||||
self.decrement_active_tasks()
|
||||
|
||||
if counter == 0:
|
||||
elapsed = time.monotonic() - self._busy_started_at
|
||||
if elapsed >= self.MIN_BUSY_VISIBLE_S:
|
||||
# Honeymoon already elapsed — transition to online now
|
||||
self._cancel_honeymoon_timer()
|
||||
self.update_presence()
|
||||
logger.debug(
|
||||
"[presence] Honeymoon abgelaufen (%.2fs) → online", elapsed,
|
||||
)
|
||||
else:
|
||||
# Honeymoon still running — timer callback will handle it
|
||||
logger.debug(
|
||||
"[presence] Honeymoon läuft noch (%.2fs/%.1fs) — Timer übernimmt",
|
||||
elapsed, self.MIN_BUSY_VISIBLE_S,
|
||||
)
|
||||
else:
|
||||
logger.debug(
|
||||
"[presence] mark_busy_done: counter=%d (weitere Tasks aktiv)", counter,
|
||||
)
|
||||
|
||||
def _honeymoon_expired(self) -> None:
|
||||
"""P1a: Honeymoon timer callback — transition to online if idle.
|
||||
|
||||
Called by threading.Timer after MIN_BUSY_VISIBLE_S.
|
||||
If no active tasks remain, sets status to online.
|
||||
"""
|
||||
with self._busy_honeymoon_lock:
|
||||
self._busy_honeymoon_timer = None
|
||||
|
||||
with self._active_tasks_lock:
|
||||
active = self._active_tasks
|
||||
|
||||
if active == 0:
|
||||
logger.info(
|
||||
"[presence] Honeymoon-Timer abgelaufen, active_tasks=0 → online"
|
||||
)
|
||||
self.update_presence()
|
||||
else:
|
||||
logger.debug(
|
||||
"[presence] Honeymoon-Timer abgelaufen, aber active_tasks=%d — kein Wechsel",
|
||||
active,
|
||||
)
|
||||
|
||||
def _cancel_honeymoon_timer(self) -> None:
|
||||
"""P1a: Cancel the honeymoon timer if running."""
|
||||
with self._busy_honeymoon_lock:
|
||||
if self._busy_honeymoon_timer is not None:
|
||||
self._busy_honeymoon_timer.cancel()
|
||||
self._busy_honeymoon_timer = None
|
||||
|
||||
def set_onboarding_active(self, active: bool) -> None:
|
||||
"""Set the onboarding sentinel."""
|
||||
self._onboarding_active = active
|
||||
@@ -440,6 +561,7 @@ class PresenceEngine:
|
||||
"""Clean shutdown: stop PulseController, DetectionTimer, cancel coalesce timer."""
|
||||
self._pulse_controller.stop()
|
||||
self._detection_timer.stop()
|
||||
self._cancel_honeymoon_timer()
|
||||
with self._coalesce_lock:
|
||||
if self._coalesce_timer is not None:
|
||||
self._coalesce_timer.cancel()
|
||||
|
||||
@@ -1534,3 +1534,202 @@ class TestPresenceClarificationPending:
|
||||
f"Klärung sollte away setzen (nicht busy), bekam: {data['status']}"
|
||||
)
|
||||
assert "Klärung" in data["message"]
|
||||
|
||||
|
||||
# ═══════════════════════════════════════════════════════════════════════════
|
||||
# P1a: Honeymoon-Timer — busy minimum 1s sichtbar
|
||||
# ═══════════════════════════════════════════════════════════════════════════
|
||||
|
||||
|
||||
class TestHoneymoonBusyMinVisible:
|
||||
"""P1a: Honeymoon-Timer — busy Status mindestens 1s sichtbar."""
|
||||
|
||||
def test_busy_min_visible_duration(self):
|
||||
"""mark_busy_started → mark_busy_done innerhalb 50ms → pending_status bleibt busy bis Timer feuert."""
|
||||
from plugin.archivar.presence_engine import PresenceEngine
|
||||
|
||||
mock_rest = MagicMock()
|
||||
mock_rest.auth_token = "token"
|
||||
mock_rest.user_id = "user123"
|
||||
mock_rest._request = MagicMock(return_value={"success": True})
|
||||
|
||||
engine = PresenceEngine(rest=mock_rest, enabled=True)
|
||||
|
||||
# Start busy
|
||||
engine.mark_busy_started(room_name="#Test")
|
||||
assert engine._active_tasks == 1
|
||||
assert engine._busy_counter == 1
|
||||
assert engine._busy_honeymoon_timer is not None
|
||||
|
||||
# Done sofort (50ms später — Honeymoon noch nicht abgelaufen)
|
||||
time.sleep(0.05)
|
||||
engine.mark_busy_done()
|
||||
assert engine._active_tasks == 0
|
||||
assert engine._busy_counter == 0
|
||||
|
||||
# Honeymoon-Timer läuft noch → pending_status sollte busy sein
|
||||
# (update_presence wurde NICHT aufgerufen, weil Honeymoon noch läuft)
|
||||
# Warte auf Honeymoon-Expiry
|
||||
time.sleep(1.1) # MIN_BUSY_VISIBLE_S + margin
|
||||
|
||||
# Jetzt sollte der Timer gefeuert haben → online
|
||||
# Flush um sicherzustellen
|
||||
engine._flush_presence()
|
||||
|
||||
# Prüfe: REST-Calls in Reihenfolge: erst busy, dann online
|
||||
calls = mock_rest._request.call_args_list
|
||||
assert len(calls) >= 2, f"Erwarte mind. 2 REST-Calls (busy + online), bekam {len(calls)}"
|
||||
# Erster Call: busy
|
||||
assert calls[0][1]["data"]["status"] == "busy"
|
||||
# Letzter Call: online
|
||||
assert calls[-1][1]["data"]["status"] == "online"
|
||||
|
||||
def test_busy_done_after_honeymoon(self):
|
||||
"""Nach 1.05s ist Honeymoon abgelaufen → mark_busy_done setzt sofort online."""
|
||||
from plugin.archivar.presence_engine import PresenceEngine
|
||||
|
||||
mock_rest = MagicMock()
|
||||
mock_rest.auth_token = "token"
|
||||
mock_rest.user_id = "user123"
|
||||
mock_rest._request = MagicMock(return_value={"success": True})
|
||||
|
||||
engine = PresenceEngine(rest=mock_rest, enabled=True)
|
||||
|
||||
engine.mark_busy_started(room_name="#Test")
|
||||
assert engine._active_tasks == 1
|
||||
|
||||
# Warte bis Honeymoon abgelaufen ist
|
||||
time.sleep(1.1)
|
||||
|
||||
engine.mark_busy_done()
|
||||
# Honeymoon bereits abgelaufen → update_presence wurde aufgerufen
|
||||
engine._flush_presence()
|
||||
|
||||
calls = mock_rest._request.call_args_list
|
||||
assert len(calls) >= 2
|
||||
assert calls[0][1]["data"]["status"] == "busy"
|
||||
assert calls[-1][1]["data"]["status"] == "online"
|
||||
|
||||
def test_double_busy_no_double_honeymoon(self):
|
||||
"""Zweiter mark_busy_started während Honeymoon läuft → nur EIN Timer aktiv."""
|
||||
from plugin.archivar.presence_engine import PresenceEngine
|
||||
|
||||
mock_rest = MagicMock()
|
||||
mock_rest.auth_token = "token"
|
||||
mock_rest.user_id = "user123"
|
||||
mock_rest._request = MagicMock(return_value={"success": True})
|
||||
|
||||
engine = PresenceEngine(rest=mock_rest, enabled=True)
|
||||
|
||||
# Erster busy
|
||||
engine.mark_busy_started(room_name="#Test")
|
||||
first_timer = engine._busy_honeymoon_timer
|
||||
assert first_timer is not None
|
||||
assert engine._busy_counter == 1
|
||||
|
||||
# Zweiter busy (multi-turn) — kein neuer Timer
|
||||
engine.mark_busy_started(room_name="#Test2")
|
||||
assert engine._busy_honeymoon_timer is first_timer # gleicher Timer
|
||||
assert engine._busy_counter == 2
|
||||
|
||||
# Erster done → counter=1, Timer läuft weiter
|
||||
engine.mark_busy_done()
|
||||
assert engine._busy_counter == 1
|
||||
assert engine._active_tasks == 1
|
||||
|
||||
# Zweiter done → counter=0, Honeymoon noch nicht abgelaufen
|
||||
engine.mark_busy_done()
|
||||
assert engine._busy_counter == 0
|
||||
assert engine._active_tasks == 0
|
||||
|
||||
# Warte auf Honeymoon
|
||||
time.sleep(1.1)
|
||||
engine._flush_presence()
|
||||
|
||||
calls = mock_rest._request.call_args_list
|
||||
assert len(calls) >= 2
|
||||
assert calls[0][1]["data"]["status"] == "busy"
|
||||
assert calls[-1][1]["data"]["status"] == "online"
|
||||
|
||||
def test_active_tasks_balanced(self):
|
||||
"""100x mark_busy_started/mark_busy_done → _active_tasks == 0, _busy_counter == 0."""
|
||||
from plugin.archivar.presence_engine import PresenceEngine
|
||||
|
||||
mock_rest = MagicMock()
|
||||
mock_rest.auth_token = "token"
|
||||
mock_rest.user_id = "user123"
|
||||
mock_rest._request = MagicMock(return_value={"success": True})
|
||||
|
||||
engine = PresenceEngine(rest=mock_rest, enabled=True)
|
||||
|
||||
for _ in range(100):
|
||||
engine.mark_busy_started(room_name="#Test")
|
||||
assert engine._active_tasks == 100
|
||||
assert engine._busy_counter == 100
|
||||
|
||||
for _ in range(100):
|
||||
engine.mark_busy_done()
|
||||
assert engine._active_tasks == 0
|
||||
assert engine._busy_counter == 0
|
||||
|
||||
def test_exception_during_dispatch_releases_busy(self):
|
||||
"""Exception während Dispatch → mark_busy_done balanced Counter, Honeymoon läuft."""
|
||||
from plugin.archivar.presence_engine import PresenceEngine
|
||||
|
||||
mock_rest = MagicMock()
|
||||
mock_rest.auth_token = "token"
|
||||
mock_rest.user_id = "user123"
|
||||
mock_rest._request = MagicMock(return_value={"success": True})
|
||||
|
||||
engine = PresenceEngine(rest=mock_rest, enabled=True)
|
||||
|
||||
try:
|
||||
engine.mark_busy_started(room_name="#Test")
|
||||
raise RuntimeError("simulated dispatch failure")
|
||||
except RuntimeError:
|
||||
engine.mark_busy_done()
|
||||
|
||||
# Counter balanced
|
||||
assert engine._active_tasks == 0
|
||||
assert engine._busy_counter == 0
|
||||
|
||||
# Honeymoon-Timer läuft noch (oder ist schon abgelaufen)
|
||||
# Wichtig: kein Crash, kein hängender Counter
|
||||
time.sleep(1.1)
|
||||
engine._flush_presence()
|
||||
|
||||
calls = mock_rest._request.call_args_list
|
||||
assert len(calls) >= 2
|
||||
assert calls[0][1]["data"]["status"] == "busy"
|
||||
assert calls[-1][1]["data"]["status"] == "online"
|
||||
|
||||
def test_status_send_order_busy_then_online(self):
|
||||
"""Reihenfolge der REST-Calls: erst busy, dann online."""
|
||||
from plugin.archivar.presence_engine import PresenceEngine
|
||||
|
||||
mock_rest = MagicMock()
|
||||
mock_rest.auth_token = "token"
|
||||
mock_rest.user_id = "user123"
|
||||
mock_rest._request = MagicMock(return_value={"success": True})
|
||||
|
||||
engine = PresenceEngine(rest=mock_rest, enabled=True)
|
||||
|
||||
engine.mark_busy_started(room_name="#Test")
|
||||
time.sleep(0.05)
|
||||
engine.mark_busy_done()
|
||||
|
||||
# Warte auf Honeymoon
|
||||
time.sleep(1.1)
|
||||
engine._flush_presence()
|
||||
|
||||
calls = mock_rest._request.call_args_list
|
||||
statuses = [c[1]["data"]["status"] for c in calls]
|
||||
# Erster Status muss busy sein
|
||||
assert "busy" in statuses, f"Status-Sequenz: {statuses}"
|
||||
# busy kommt vor online
|
||||
busy_idx = statuses.index("busy")
|
||||
online_idx = statuses.index("online") if "online" in statuses else -1
|
||||
if online_idx >= 0:
|
||||
assert busy_idx < online_idx, (
|
||||
f"busy (idx={busy_idx}) muss vor online (idx={online_idx}) kommen: {statuses}"
|
||||
)
|
||||
|
||||
Reference in New Issue
Block a user