Skip to content

The agent that grows with you

fix(context): re-derive model.context_length on model/provider change

finn76336b6efc29750
diff --git a/agent/agent_init.py b/agent/agent_init.py
index 6d85e6eda2c..5b5542bb8e3 100644
--- a/agent/agent_init.py
+++ b/agent/agent_init.py
@@ -1689,6 +1689,55 @@ def _scope_context_length_to_default_runtime(
return _config_context_length
+def set_config_context_length(agent, value: Optional[int]) -> None:
+ """Store the durable ``model.context_length`` pin on EVERY cached copy of it.
+
+ The pin is read from config exactly once, at construction, then cached twice: on
+ ``agent._config_context_length`` (switch/fallback resolution plus every display and ``/usage``
+ surface) and on ``context_compressor._config_context_length`` (the compressor's own
+ re-resolution). Live paths that updated only one copy left the other stale, so a session could
+ report a pinned ceiling while compressing against a different window (#116467).
+ """
+ agent._config_context_length = value
+ _compressor = getattr(agent, "context_compressor", None)
+ if _compressor is not None:
+ _compressor._config_context_length = value
+
+
+def config_context_length_for_runtime(agent, config=None) -> Optional[int]:
+ """Re-read the durable ``model.context_length`` pin for ``agent``'s CURRENT runtime, or ``None``.
+
+ Single re-derivation point for the cached pin: construction resolves it once, and every live path
+ that re-resolves a runtime used to clear the cached copy without re-reading the config — so a
+ model/provider switch or a Desktop config round-trip silently dropped a ceiling the user still had
+ on disk, and resolution fell through to probing / catalog metadata / the 256K fallback (#116467).
+
+ Reuses construction's own scoping (``_scope_context_length_to_default_runtime``): the pin describes
+ the configured default route, so an unrelated runtime never inherits it.
+ """
+ try:
+ from hermes_cli.config import get_compatible_custom_providers, load_config
+ _agent_cfg = config if isinstance(config, dict) else load_config()
+ if not isinstance(_agent_cfg, dict):
+ return None
+ _model_section = _agent_cfg.get("model", {})
+ if not isinstance(_model_section, dict):
+ return None
+ _pin = _model_section.get("context_length")
+ if _pin is None or isinstance(_pin, bool):
+ return None
+ _pin = int(_pin)
+ if _pin <= 0:
+ return None
+ return _scope_context_length_to_default_runtime(
+ agent, _agent_cfg, _model_section, get_compatible_custom_providers(_agent_cfg),
+ _pin, str(getattr(agent, "base_url", "") or ""),
+ )
+ except Exception:
+ logger.debug("Could not re-read model.context_length for the current runtime", exc_info=True)
+ return None
+
+
_CTX_LEN_REQUIREMENT = "must be a positive integer (e.g. 256000, not '256K')"
diff --git a/agent/agent_runtime_helpers.py b/agent/agent_runtime_helpers.py
index 5d0cd93c348..d780c4c19dd 100644
--- a/agent/agent_runtime_helpers.py
+++ b/agent/agent_runtime_helpers.py
@@ -2130,13 +2130,22 @@ def _resolve_switch_context_length(agent, snapshot):
from hermes_cli.config import (
get_compatible_custom_providers, get_custom_provider_context_length, load_config
)
- custom_providers = get_compatible_custom_providers(load_config())
- intent = get_custom_provider_context_length(
- model=agent.model, base_url=agent.base_url, custom_providers=custom_providers
- )
+ from agent.agent_init import config_context_length_for_runtime
+ switch_cfg = load_config()
+ custom_providers = get_compatible_custom_providers(switch_cfg)
+ # The durable ``model.context_length`` pin is re-read from live config (never carried over
+ # blindly, never simply dropped): the destination IS the configured default route -> keep the
+ # ceiling; it is some other route -> the scoping inside returns None. Same precedence as
+ # construction, where the pin outranks custom_providers metadata (#116467).
+ intent = config_context_length_for_runtime(agent, switch_cfg)
+ if intent is None:
+ intent = get_custom_provider_context_length(
+ model=agent.model, base_url=agent.base_url, custom_providers=custom_providers
+ )
except Exception:
intent = None
- agent._config_context_length = intent
+ from agent.agent_init import set_config_context_length
+ set_config_context_length(agent, intent)
runtime_len = None
if hasattr(agent, "_ensure_lmstudio_runtime_loaded"):
try:
diff --git a/tests/agent/test_switch_model_reapplies_config_context_pin.py b/tests/agent/test_switch_model_reapplies_config_context_pin.py
new file mode 100644
index 00000000000..60b05c7a41c
--- /dev/null
+++ b/tests/agent/test_switch_model_reapplies_config_context_pin.py
@@ -0,0 +1,105 @@
+"""A live model/provider switch must re-derive the durable ``model.context_length`` pin.
+
+``model.context_length`` is the user's profile-wide ceiling. It is read from config.yaml exactly once,
+at agent construction (``agent_init._resolve_context_length``), then cached on
+``agent._config_context_length``. Every live path that re-resolves a runtime cleared that cached copy
+instead of re-reading the config, so a long-running Desktop/CLI session silently lost the ceiling and
+fell through to provider probing / catalog metadata / the 256K fallback — while the ceiling was still
+on disk and still shown by other surfaces.
+"""
+
+from unittest.mock import MagicMock, patch
+
+from agent.context_compressor import ContextCompressor
+from run_agent import AIAgent
+
+PIN = 249_000
+ROUTE = "http://127.0.0.1:8123/v1"
+OTHER_ROUTE = "https://openrouter.ai/api/v1"
+
+
+def _cfg_with_pin():
+ return {
+ "model": {
+ "default": "model-b",
+ "provider": "custom:acme",
+ "base_url": ROUTE,
+ "context_length": PIN,
+ },
+ "custom_providers": [{"name": "acme", "base_url": ROUTE, "models": {}}],
+ }
+
+
+def _make_agent(config_context_length=None):
+ agent = AIAgent.__new__(AIAgent)
+ agent.model = "model-a"
+ agent.provider = "openrouter"
+ agent.base_url = OTHER_ROUTE
+ agent.api_key = "sk-primary"
+ agent.api_mode = "chat_completions"
+ agent.client = MagicMock()
+ agent.quiet_mode = True
+ agent._config_context_length = config_context_length
+ agent._custom_providers = []
+ agent._primary_runtime = {}
+ agent._create_openai_client = lambda *_args, **_kwargs: MagicMock()
+ agent.context_compressor = ContextCompressor(
+ model="model-a", threshold_percent=0.50, base_url=OTHER_ROUTE,
+ api_key="sk-primary", provider="openrouter", quiet_mode=True,
+ )
+ return agent
+
+
+def _switch(agent, model, provider, base_url):
+ """Switch and return the ``config_context_length`` the compressor resolution ran with."""
+ with patch("agent.model_metadata.get_model_context_length", return_value=200_000) as ctx_len:
+ agent.switch_model(model, provider, api_key="sk-new", base_url=base_url)
+ return ctx_len.call_args.kwargs.get("config_context_length")
+
+
+def test_switch_to_configured_default_route_reapplies_context_pin():
+ """Switching onto the route ``model.context_length`` describes keeps the ceiling."""
+ cfg = _cfg_with_pin()
+ agent = _make_agent(config_context_length=None)
+
+ with (
+ patch("hermes_cli.config.load_config", return_value=cfg),
+ patch("hermes_cli.config.load_config_readonly", return_value=cfg),
+ ):
+ applied = _switch(agent, "model-b", "custom:acme", ROUTE)
+
+ assert applied == PIN
+ assert agent._config_context_length == PIN
+
+
+def test_switch_back_to_configured_default_route_restores_context_pin():
+ """A round-trip away from and back onto the configured route restores the ceiling."""
+ cfg = _cfg_with_pin()
+ agent = _make_agent(config_context_length=PIN)
+
+ with (
+ patch("hermes_cli.config.load_config", return_value=cfg),
+ patch("hermes_cli.config.load_config_readonly", return_value=cfg),
+ patch("agent.model_metadata.get_model_context_length", return_value=1_000_000),
+ ):
+ agent.switch_model("other-model", "openrouter", api_key="sk-new", base_url=OTHER_ROUTE)
+ assert agent._config_context_length is None # pin does not describe the other route
+ applied = _switch(agent, "model-b", "custom:acme", ROUTE)
+
+ assert applied == PIN
+ assert agent._config_context_length == PIN
+
+
+def test_switch_to_other_route_does_not_inherit_context_pin():
+ """The pin stays scoped to its own route (no leak onto an unrelated model)."""
+ cfg = _cfg_with_pin()
+ agent = _make_agent(config_context_length=PIN)
+
+ with (
+ patch("hermes_cli.config.load_config", return_value=cfg),
+ patch("hermes_cli.config.load_config_readonly", return_value=cfg),
+ ):
+ applied = _switch(agent, "unrelated-model", "openrouter", OTHER_ROUTE)
+
+ assert applied is None
+ assert agent._config_context_length is None
diff --git a/tests/tui_gateway/test_live_config_context_pin_mirror.py b/tests/tui_gateway/test_live_config_context_pin_mirror.py
new file mode 100644
index 00000000000..d12bd77851c
--- /dev/null
+++ b/tests/tui_gateway/test_live_config_context_pin_mirror.py
@@ -0,0 +1,62 @@
+"""Desktop/TUI config hot-reload must keep the agent's cached context pin in step with the compressor's.
+
+``model.context_length`` is cached twice: on ``agent._config_context_length`` (read by the switch path,
+fallback resolution and every display/`/usage` surface) and on
+``context_compressor._config_context_length`` (read by the compressor's own re-resolution). The live
+hot-reload updated only the compressor's copy, so an already-running Desktop session showed a pinned
+ceiling while the compressor had already fallen back to provider metadata / the 256K fallback.
+"""
+
+from types import SimpleNamespace
+
+import agent.context_compressor as cc_mod
+from agent.context_compressor import ContextCompressor
+from tui_gateway import server
+
+PIN = 249_000
+
+
+def _session(config_context_length=PIN):
+ compressor = ContextCompressor(
+ model="model-a", threshold_percent=0.50, config_context_length=config_context_length,
+ quiet_mode=True,
+ )
+ agent = SimpleNamespace(
+ model="model-a",
+ provider="custom:acme",
+ _config_context_length=config_context_length,
+ context_compressor=compressor,
+ compression_enabled=True,
+ compression_idle_compact_after_seconds=0,
+ codex_responses_native_compaction=False,
+ codex_responses_compact_threshold=200_000,
+ )
+ return {"agent": agent, "session_key": "session-pin"}, compressor
+
+
+def _sync(monkeypatch, session, cfg):
+ monkeypatch.setattr(server, "_load_cfg", lambda: cfg)
+ server._sync_agent_compression_with_config("sid-pin", session)
+
+
+def test_removed_context_length_clears_the_agent_pin_too(monkeypatch):
+ """Dropping ``model.context_length`` on disk must stop the agent claiming the pin."""
+ session, compressor = _session()
+ monkeypatch.setattr(cc_mod, "get_model_context_length", lambda *a, **k: 256_000)
+
+ _sync(monkeypatch, session, {"model": {}, "compression": {}})
+
+ assert compressor._config_context_length is None
+ assert compressor.context_length == 256_000
+ assert session["agent"]._config_context_length is None
+
+
+def test_changed_context_length_refreshes_the_agent_pin_too(monkeypatch):
+ """A new ``model.context_length`` must land on both cached copies."""
+ session, compressor = _session()
+
+ _sync(monkeypatch, session, {"model": {"context_length": 400_000}, "compression": {}})
+
+ assert compressor._config_context_length == 400_000
+ assert compressor.context_length == 400_000
+ assert session["agent"]._config_context_length == 400_000
diff --git a/tui_gateway/session_compression.py b/tui_gateway/session_compression.py
index 38c1070e646..6e7c8c7541e 100644
--- a/tui_gateway/session_compression.py
+++ b/tui_gateway/session_compression.py
@@ -85,6 +85,7 @@ def _apply_live_compression_config(agent: Any, cfg: dict | None) -> None:
cfg = cfg if isinstance(cfg, dict) else {}
compression = cfg.get("compression") if isinstance(cfg.get("compression"), dict) else {}
model_cfg = cfg.get("model") if isinstance(cfg.get("model"), dict) else {}
+ from agent.agent_init import set_config_context_length
enabled_raw = compression.get("enabled", True)
agent.compression_enabled = enabled_raw if isinstance(enabled_raw, bool) else str(enabled_raw).lower() in {"true", "1", "yes"}
agent.codex_responses_native_compaction = is_truthy_value(compression.get("codex_responses_native", False))
@@ -140,13 +141,17 @@ def _apply_live_compression_config(agent: Any, cfg: dict | None) -> None:
if raw_ctx is not None:
with contextlib.suppress(TypeError, ValueError):
if (new_ctx := int(raw_ctx)) > 0:
- cc._config_context_length = new_ctx
+ # Both cached copies: the compressor's (its own re-resolution) and the agent's
+ # (switch/fallback + every display surface). Writing one left the other stale, so the
+ # session showed a pinned ceiling while compressing against a different window (#116467).
+ set_config_context_length(agent, new_ctx)
with contextlib.suppress(Exception):
cc.context_length = new_ctx
elif getattr(cc, "_config_context_length", None) is not None:
# model.context_length removed: drop the override and force re-inference from model metadata on
# next access (construction's deferred resolution); re-applies the small-context floor too.
- cc._config_context_length = cc._resolved_context_length = None
+ set_config_context_length(agent, None)
+ cc._resolved_context_length = None
cc.threshold_tokens_cap = cc._coerce_threshold_tokens_cap(compression.get("threshold_tokens"))
# Invalidate the cached trigger so the next preflight re-derives from percent/window, then the cap.
cc._threshold_tokens = cc._tail_token_budget = None