Skip to content

The agent that grows with you

fix(gateway): tolerate an unreadable tools pin in the agentless breakdown

unsupportedpastelscec18a97370b
diff --git a/gateway/session_tui_reads.py b/gateway/session_tui_reads.py
index dddf5c514ae..c779cad6332 100644
--- a/gateway/session_tui_reads.py
+++ b/gateway/session_tui_reads.py
@@ -182,13 +182,17 @@ async def context_breakdown(connection, ref, params) -> dict:
def _stored_breakdown(row, conversation, usage) -> dict:
"""``stored_context_breakdown`` over the session row's frozen system prompt and tools[] pin, beside its
- stored usage. A legacy name-only pin has no schemas to measure."""
+ stored usage. Tools are measured as the next agent restores them (``pinned_tool_defs``)."""
from agent.context_breakdown import stored_context_breakdown
+ from tools.mcp_tool_agent import pinned_tool_defs
breakdown = {'categories': [], 'estimated_total': 0}
# No prompt until an agent first built one: nothing to measure yet, the contract's pre-build shape.
if prompt := row.get('system_prompt'):
- pin = json.loads(row.get('tool_names') or 'null')
- breakdown = stored_context_breakdown(prompt, pin['tools'] if isinstance(pin, dict) else [], conversation)
+ try:
+ pin = json.loads(row.get('tool_names') or 'null')
+ except (TypeError, ValueError):
+ pin = None # a pin hash whose row was swept resolves to itself
+ breakdown = stored_context_breakdown(prompt, pinned_tool_defs(pin), conversation)
return {**breakdown, 'context_max': int(usage.get('context_max') or 0),
'context_percent': int(usage.get('context_percent') or 0), 'context_used': int(usage.get('context_used') or 0),
'context_estimated': bool(usage.get('context_estimated', False)),
diff --git a/tests/gateway/test_tui_context_breakdown_scope.py b/tests/gateway/test_tui_context_breakdown_scope.py
index 78e235265a0..1c49287ef67 100644
--- a/tests/gateway/test_tui_context_breakdown_scope.py
+++ b/tests/gateway/test_tui_context_breakdown_scope.py
@@ -58,6 +58,38 @@ async def test_agentless_breakdown_refreshes_when_the_stored_prompt_or_tools_cha
assert 'tool_definitions' in {c['id'] for c in tooled['categories']}, tooled
+async def _agentless_session(owner, request_id, pin):
+ from gateway.session_tui_reads import _stored_id
+
+ sid = (await owner.call('session.create', request_id=request_id, source='tui', cwd=str(owner.workdir)))['session_id']
+ stored = _stored_id(owner.authority, SimpleNamespace(session_id=sid))
+ owner.authority.db.update_system_prompt(stored, 'You are Hermes. ' * 50)
+ owner.authority.db.update_session_tool_names(stored, pin)
+ owner.authority.db.append_message(stored, 'user', 'hello')
+ return sid, stored
+
+
+async def test_agentless_breakdown_measures_a_legacy_name_only_pin(owner):
+ """A legacy name-only pin measures each tool's registry schema, as the next agent restores it."""
+ import tools.terminal_tool # registers ``terminal``
+
+ sid, _ = await _agentless_session(owner, 'legacy', ['terminal'])
+ actual = await owner.call('session.context_breakdown', session_id=sid)
+ assert 'tool_definitions' in {c['id'] for c in actual['categories']}, actual
+
+
+async def test_agentless_breakdown_survives_a_swept_tools_pin(owner):
+ """A pin hash whose ``system_prompts`` row was swept resolves to the bare hash: no tools, no error."""
+ sid, stored = await _agentless_session(owner, 'swept', {'version': 'v', 'tools': [
+ {'type': 'function', 'function': {'name': 'terminal', 'parameters': {'type': 'object'}}}]})
+ owner.authority.db._execute_write(lambda conn: conn.execute(
+ 'DELETE FROM system_prompts WHERE hash = (SELECT tool_names FROM sessions WHERE id = ?)', (stored,)))
+ actual = await owner.call('session.context_breakdown', session_id=sid)
+ assert {c['id'] for c in actual['categories']} == {'system_prompt', 'conversation'}, actual
+
+
@pytest.mark.asyncio
async def test_context_breakdown_measures_only_the_compression_tips_model_history(owner, monkeypatch):
"""The runtime id still names the compressed parent; neither its superseded segment nor the tip's