feat(F423): ::getcontext Inline-Command — Context-Auslastung anzeigen
@implements: [F423] Neuer Inline-Command ::getcontext zeigt die aktuelle Context-Auslastung an (Weg B, von Rainer evaluiert). Liest Token-Daten über GatewayRunner aus dem Agent-Objekt im Gateway-Speicher: - agent.session_input_tokens — aktuelle Context-Größe - compressor.context_length — maximales Context-Fenster - agent.max_tokens — reserviertes Output-Budget (~ markiert) - compressor.threshold_tokens — Compression-Schwelle - compressor.threshold_percent — Compression-Schwelle in Prozent Auflösung: laufender Agent (mid-turn) → gecachter Agent (zwischen Turns) via runner._resident_agent_for(session_key). Graceful degradation: ohne Runner/Agent/Context-Fenster → 'Keine aktive Session gefunden'. Reine Textanzeige, kein Button. Registriert in _register_inline_commands (Kategorie 'Hilfe'), erscheint automatisch in ::hilfe. 7 Unit-Tests.
This commit is contained in:
@@ -5221,6 +5221,15 @@ class RocketChatAdapter(BasePlatformAdapter):
|
||||
category="Standard",
|
||||
)
|
||||
|
||||
# F423: ::getcontext — aktuelle Context-Auslastung anzeigen
|
||||
self._inline_commands.register(
|
||||
"getcontext", self._cmd_getcontext,
|
||||
help_text="Zeigt die aktuelle Context-Auslastung an",
|
||||
description="Zeigt aktuelle Token-Nutzung, Compression-Threshold und "
|
||||
"verfügbares Budget an.",
|
||||
category="Hilfe",
|
||||
)
|
||||
|
||||
# F169: ::reset-timeout — adaptiven LLM-Timeout auf Baseline zurücksetzen
|
||||
self._inline_commands.register(
|
||||
"reset-timeout", self._cmd_reset_timeout,
|
||||
@@ -6419,6 +6428,145 @@ class RocketChatAdapter(BasePlatformAdapter):
|
||||
|
||||
return "✅ **Kontext komprimiert.**"
|
||||
|
||||
async def _cmd_getcontext(self, room_id: str, args: str) -> str:
|
||||
"""::getcontext — Zeigt die aktuelle Context-Auslastung an (F423).
|
||||
|
||||
@implements: [F423]
|
||||
|
||||
Liest die Token-Daten über den GatewayRunner aus dem Agent-Objekt im
|
||||
Gateway-Speicher (Weg B, von Rainer evaluiert):
|
||||
|
||||
- agent.session_input_tokens — aktuelle Context-Größe in Tokens
|
||||
- compressor.context_length — maximales Context-Fenster
|
||||
- agent.max_tokens — reserviertes Output-Budget
|
||||
- compressor.threshold_tokens — Compression-Schwelle
|
||||
- compressor.threshold_percent — Compression-Schwelle in Prozent
|
||||
|
||||
Auflösung: laufender Agent (mid-turn) → gecachter Agent (zwischen Turns)
|
||||
via ``runner._resident_agent_for(session_key)``. Ist kein Agent verfügbar
|
||||
(keine aktive Session), wird eine klare deutsche Meldung geliefert.
|
||||
|
||||
Reine Textanzeige — kein Button, kein interaktives Element. Der User
|
||||
tippt danach manuell ``::compress`` wenn nötig.
|
||||
"""
|
||||
runner = getattr(self, "gateway_runner", None)
|
||||
if runner is None:
|
||||
logger.warning(
|
||||
"[rocketchat] ::getcontext ohne gateway_runner — "
|
||||
"kein Zugriff auf Agent-Daten möglich"
|
||||
)
|
||||
return "⚠️ **Keine aktive Session gefunden.**\n\n" \
|
||||
"Der Gateway-Runner ist nicht verdrahtet (Standalone/Test)."
|
||||
|
||||
# ── Session-Key ableiten (Muster aus ::compress / ::reasoning) ──
|
||||
username = getattr(self, "_last_inline_username", "") or ""
|
||||
room_name = getattr(self, "_last_inline_room_name", "") or "DM"
|
||||
try:
|
||||
source = SessionSource(
|
||||
platform=Platform("rocketchat"),
|
||||
chat_id=f"user:{username}",
|
||||
chat_name=f"{room_name} (via @{username})",
|
||||
user_id=username,
|
||||
user_name=username,
|
||||
chat_type="dm",
|
||||
)
|
||||
except Exception as e:
|
||||
logger.warning("[rocketchat] ::getcontext SessionSource build failed: %s", e)
|
||||
return "⚠️ **Keine aktive Session gefunden.**\n\n" \
|
||||
f"Session-Kontext konnte nicht aufgebaut werden: {e}"
|
||||
|
||||
# ── Agent auflösen (running → cached → None) ──
|
||||
agent = None
|
||||
try:
|
||||
if hasattr(runner, "_session_key_for_source"):
|
||||
session_key = runner._session_key_for_source(source)
|
||||
else:
|
||||
session_key = f"rocketchat:user:{username}"
|
||||
if session_key and hasattr(runner, "_resident_agent_for"):
|
||||
agent = runner._resident_agent_for(session_key)
|
||||
except Exception as e:
|
||||
logger.warning("[rocketchat] ::getcontext agent lookup failed: %s", e)
|
||||
agent = None
|
||||
|
||||
if agent is None:
|
||||
return "⚠️ **Keine aktive Session gefunden.**\n\n" \
|
||||
"Es läuft gerade kein Agent-Turn und es ist kein gecachter " \
|
||||
"Agent für diese Session vorhanden. Sende eine Nachricht, " \
|
||||
"damit eine Session entsteht, und versuche es erneut."
|
||||
|
||||
# ── Token-Daten auslesen (defensiv, graceful degradation) ──
|
||||
def _int(v):
|
||||
try:
|
||||
return int(v)
|
||||
except (TypeError, ValueError):
|
||||
return 0
|
||||
|
||||
used = _int(getattr(agent, "session_input_tokens", 0))
|
||||
max_tokens = _int(getattr(agent, "max_tokens", 0))
|
||||
|
||||
ctx = getattr(agent, "context_compressor", None)
|
||||
context_length = 0
|
||||
threshold = 0
|
||||
threshold_pct = 0.0
|
||||
if ctx is not None:
|
||||
context_length = _int(getattr(ctx, "context_length", 0))
|
||||
threshold = _int(getattr(ctx, "threshold_tokens", 0))
|
||||
threshold_pct = float(getattr(ctx, "threshold_percent", 0.0) or 0.0)
|
||||
|
||||
# Fallback: wenn session_input_tokens noch 0 ist (frische Session ohne
|
||||
# abgeschlossenen Turn), nutze die letzte reale Prompt-Größe.
|
||||
if used == 0 and ctx is not None:
|
||||
used = _int(getattr(ctx, "last_prompt_tokens", 0))
|
||||
|
||||
# ── Formatierung (K = Tausender) ──
|
||||
def _k(n: int) -> str:
|
||||
if n >= 1000:
|
||||
return f"{n / 1000:.0f}K"
|
||||
return str(n)
|
||||
|
||||
if context_length <= 0:
|
||||
# Kein Context-Fenster bekannt → nur die verfügbaren Werte zeigen.
|
||||
lines = ["📊 **Context-Auslastung**", ""]
|
||||
if used > 0:
|
||||
lines.append(f"- **Context:** {_k(used)} Tokens")
|
||||
if max_tokens > 0:
|
||||
lines.append(f"- **Output-Budget:** ~{_k(max_tokens)} (max_tokens)")
|
||||
if threshold > 0:
|
||||
lines.append(
|
||||
f"- **Compression-Threshold:** {_k(threshold)} "
|
||||
f"({threshold_pct * 100:.0f}%)"
|
||||
)
|
||||
if not lines[1:]:
|
||||
return "⚠️ **Keine aktive Session gefunden.**\n\n" \
|
||||
"Es sind keine Token-Daten verfügbar."
|
||||
return "\n".join(lines)
|
||||
|
||||
pct = min(100, round(used / context_length * 100)) if context_length else 0
|
||||
available = max(0, threshold - used) if threshold > 0 else max(0, context_length - used)
|
||||
|
||||
lines = [
|
||||
f"📊 Context: {_k(used)} / {_k(context_length)} ({pct}%)",
|
||||
]
|
||||
if threshold > 0:
|
||||
lines.append(
|
||||
f"Compression-Threshold: {_k(threshold)} "
|
||||
f"({threshold_pct * 100:.0f}%) — wird bei ~{_k(threshold)} aktiv"
|
||||
)
|
||||
if max_tokens > 0:
|
||||
lines.append(f"Output-Budget: ~{_k(max_tokens)} (max_tokens)")
|
||||
if threshold > 0:
|
||||
if used >= threshold:
|
||||
lines.append(
|
||||
f"Verfuegbar: Compression-Schwelle bereits erreicht "
|
||||
f"(~{_k(used - threshold)} darüber)"
|
||||
)
|
||||
else:
|
||||
lines.append(f"Verfuegbar: ~{_k(available)} bis zur Compression")
|
||||
else:
|
||||
lines.append(f"Verfuegbar: ~{_k(available)} bis zum Context-Limit")
|
||||
|
||||
return "\n".join(lines)
|
||||
|
||||
async def _cmd_onboarding(self, room_id: str, args: str) -> str:
|
||||
"""::onboarding — Onboarding State Machine Steuerung.
|
||||
|
||||
|
||||
@@ -0,0 +1,159 @@
|
||||
"""Tests für F423 — ::getcontext zeigt die aktuelle Context-Auslastung an.
|
||||
|
||||
Der Handler ``_cmd_getcontext`` liest die Token-Daten über den GatewayRunner
|
||||
aus dem Agent-Objekt (Weg B). Diese Tests decken die Formatierung und die
|
||||
Graceful-Degradation-Pfade ab — ohne echten Gateway-Runner, damit sie
|
||||
standalone laufen.
|
||||
|
||||
Abgedeckte Szenarien:
|
||||
- Vollständige Daten (used/context/threshold/max_tokens) → 4-Zeilen-Format
|
||||
- Kein gateway_runner → "Keine aktive Session gefunden"
|
||||
- Kein Agent (running/cached) → "Keine aktive Session gefunden"
|
||||
- Kein context_length → reduzierte Anzeige
|
||||
- used >= threshold → "Schwelle bereits erreicht"
|
||||
- Output-Budget mit '~' markiert
|
||||
"""
|
||||
|
||||
from __future__ import annotations
|
||||
|
||||
import asyncio
|
||||
import sys
|
||||
from pathlib import Path
|
||||
from unittest.mock import MagicMock
|
||||
|
||||
import pytest
|
||||
|
||||
sys.path.insert(0, str(Path(__file__).resolve().parents[1]))
|
||||
|
||||
from plugin.adapter import RocketChatAdapter
|
||||
import plugin.adapter as adapter_mod
|
||||
|
||||
|
||||
def _make_adapter():
|
||||
"""Erzeuge eine Adapter-Instanz OHNE echten __init__ (braucht PlatformConfig)."""
|
||||
return RocketChatAdapter.__new__(RocketChatAdapter)
|
||||
|
||||
|
||||
class _FakeSessionSource:
|
||||
"""Ersetzt gateway.session.SessionSource im Standalone-Test (Import-Fallback = object)."""
|
||||
|
||||
def __init__(self, **kwargs):
|
||||
self.__dict__.update(kwargs)
|
||||
|
||||
|
||||
@pytest.fixture(autouse=True)
|
||||
def _patch_gateway_types(monkeypatch):
|
||||
"""Simuliert den Gateway-Kontext: SessionSource + Platform sind echte Klassen."""
|
||||
monkeypatch.setattr(adapter_mod, "SessionSource", _FakeSessionSource)
|
||||
monkeypatch.setattr(adapter_mod, "Platform", lambda name: name)
|
||||
|
||||
|
||||
class _FakeCompressor:
|
||||
def __init__(self, context_length=0, threshold=0, threshold_pct=0.0, last_prompt=0):
|
||||
self.context_length = context_length
|
||||
self.threshold_tokens = threshold
|
||||
self.threshold_percent = threshold_pct
|
||||
self.last_prompt_tokens = last_prompt
|
||||
|
||||
|
||||
class _FakeAgent:
|
||||
def __init__(self, input_tokens=0, max_tokens=0, compressor=None):
|
||||
self.session_input_tokens = input_tokens
|
||||
self.max_tokens = max_tokens
|
||||
self.context_compressor = compressor
|
||||
|
||||
|
||||
def _make_runner(agent=None):
|
||||
"""Baut einen Fake-GatewayRunner mit _session_key_for_source + _resident_agent_for."""
|
||||
runner = MagicMock()
|
||||
runner._session_key_for_source.return_value = "rocketchat:user:testuser"
|
||||
runner._resident_agent_for.return_value = agent
|
||||
return runner
|
||||
|
||||
|
||||
def _run(adapter, runner):
|
||||
adapter.gateway_runner = runner
|
||||
adapter._last_inline_username = "testuser"
|
||||
adapter._last_inline_room_name = "Testraum"
|
||||
return asyncio.run(adapter._cmd_getcontext("room_id", ""))
|
||||
|
||||
|
||||
def test_full_data_four_line_format():
|
||||
adapter = _make_adapter()
|
||||
ctx = _FakeCompressor(context_length=262000, threshold=170000, threshold_pct=0.65)
|
||||
agent = _FakeAgent(input_tokens=120000, max_tokens=32000, compressor=ctx)
|
||||
runner = _make_runner(agent)
|
||||
|
||||
out = _run(adapter, runner)
|
||||
|
||||
assert "📊 Context: 120K / 262K (46%)" in out
|
||||
assert "Compression-Threshold: 170K (65%)" in out
|
||||
assert "Output-Budget: ~32K (max_tokens)" in out
|
||||
assert "Verfuegbar: ~50K bis zur Compression" in out
|
||||
|
||||
|
||||
def test_output_budget_marked_with_tilde():
|
||||
adapter = _make_adapter()
|
||||
ctx = _FakeCompressor(context_length=262000, threshold=170000, threshold_pct=0.65)
|
||||
agent = _FakeAgent(input_tokens=120000, max_tokens=32000, compressor=ctx)
|
||||
runner = _make_runner(agent)
|
||||
|
||||
out = _run(adapter, runner)
|
||||
|
||||
assert "Output-Budget: ~32K" in out
|
||||
assert "Output-Budget: 32K" not in out
|
||||
|
||||
|
||||
def test_no_runner_returns_no_session():
|
||||
adapter = _make_adapter()
|
||||
adapter.gateway_runner = None
|
||||
adapter._last_inline_username = "testuser"
|
||||
adapter._last_inline_room_name = "Testraum"
|
||||
|
||||
out = asyncio.run(adapter._cmd_getcontext("room_id", ""))
|
||||
|
||||
assert "Keine aktive Session gefunden" in out
|
||||
|
||||
|
||||
def test_no_agent_returns_no_session():
|
||||
adapter = _make_adapter()
|
||||
runner = _make_runner(None) # _resident_agent_for → None
|
||||
|
||||
out = _run(adapter, runner)
|
||||
|
||||
assert "Keine aktive Session gefunden" in out
|
||||
|
||||
|
||||
def test_no_context_length_reduced_display():
|
||||
adapter = _make_adapter()
|
||||
agent = _FakeAgent(input_tokens=5000, max_tokens=32000, compressor=None)
|
||||
runner = _make_runner(agent)
|
||||
|
||||
out = _run(adapter, runner)
|
||||
|
||||
assert "Context:** 5K Tokens" in out
|
||||
assert "Output-Budget:** ~32K" in out
|
||||
|
||||
|
||||
def test_threshold_already_reached():
|
||||
adapter = _make_adapter()
|
||||
ctx = _FakeCompressor(context_length=262000, threshold=170000, threshold_pct=0.65)
|
||||
agent = _FakeAgent(input_tokens=180000, max_tokens=32000, compressor=ctx)
|
||||
runner = _make_runner(agent)
|
||||
|
||||
out = _run(adapter, runner)
|
||||
|
||||
assert "Schwelle bereits erreicht" in out
|
||||
|
||||
|
||||
def test_fallback_to_last_prompt_tokens_when_input_zero():
|
||||
adapter = _make_adapter()
|
||||
ctx = _FakeCompressor(
|
||||
context_length=262000, threshold=170000, threshold_pct=0.65, last_prompt=90000
|
||||
)
|
||||
agent = _FakeAgent(input_tokens=0, max_tokens=32000, compressor=ctx)
|
||||
runner = _make_runner(agent)
|
||||
|
||||
out = _run(adapter, runner)
|
||||
|
||||
assert "90K / 262K" in out
|
||||
Reference in New Issue
Block a user