Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
8 changes: 8 additions & 0 deletions agent/conversation_loop.py
Original file line number Diff line number Diff line change
Expand Up @@ -1101,6 +1101,14 @@ def run_conversation(
approx_request_tokens = estimate_request_tokens_rough(
api_messages, tools=agent.tools or None
)
# Some local/OpenAI-compatible lanes do not return usage on streamed
# responses. Keep a rough request-pressure estimate available for the
# TUI status bar so context does not stay pinned at 0 until a provider
# supplies real token usage.
try:
agent._last_request_context_tokens = approx_request_tokens
except Exception:
pass

_runtime_context_error = _ollama_context_limit_error(
agent, approx_request_tokens
Expand Down
22 changes: 17 additions & 5 deletions agent/stall_retry.py
Original file line number Diff line number Diff line change
Expand Up @@ -101,17 +101,29 @@ def _as_bool(value: Any, default: bool) -> bool:


def _stall_retry_config(agent: Any | None = None) -> Mapping[str, Any]:
cfg = getattr(agent, "_stall_retry_config", None)
if isinstance(cfg, Mapping):
return cfg
loaded_cfg: Mapping[str, Any] = {}
try:
from hermes_cli.config import load_config

loaded = load_config()
except Exception:
return {}
loaded = {}
cfg = loaded.get("stall_retry") if isinstance(loaded, Mapping) else None
return cfg if isinstance(cfg, Mapping) else {}
if isinstance(cfg, Mapping):
loaded_cfg = cfg

agent_cfg = getattr(agent, "_stall_retry_config", None)
if not isinstance(agent_cfg, Mapping):
return loaded_cfg
if not agent_cfg:
return loaded_cfg

merged = dict(loaded_cfg)
for key, value in agent_cfg.items():
if value is None or value == "":
continue
merged[str(key)] = value
return merged


def get_stall_retry_model(agent: Any | None = None) -> str:
Expand Down
29 changes: 28 additions & 1 deletion tests/agent/test_stall_retry.py
Original file line number Diff line number Diff line change
Expand Up @@ -319,6 +319,33 @@ def interruptible_api_call(kwargs: dict[str, object]) -> object:
assert captured["kwargs"]["stream"] is False


def test_stall_retry_empty_agent_config_falls_back_to_loaded_config(monkeypatch) -> None:
import hermes_cli.config as config_mod

monkeypatch.delenv("HERMES_STALL_RETRY_MODEL", raising=False)
monkeypatch.delenv("HERMES_STALL_RETRY_PROVIDER", raising=False)
monkeypatch.delenv("HERMES_STALL_RETRY_MAX_PER_TURN", raising=False)
monkeypatch.setattr(
config_mod,
"load_config",
lambda: {
"stall_retry": {
"max_per_turn": 3,
"model": "qwen3.6-27b-256k",
"provider": "taro",
}
},
)

empty_agent = SimpleNamespace(_stall_retry_config={})
provider_only_agent = SimpleNamespace(_stall_retry_config={"provider": "ko-mac"})

assert get_stall_retry_model(empty_agent) == "qwen3.6-27b-256k"
assert get_stall_retry_max_per_turn(empty_agent) == 3
assert get_stall_retry_model(provider_only_agent) == "qwen3.6-27b-256k"
assert get_stall_retry_max_per_turn(provider_only_agent) == 3


def test_retry_on_stall_uses_configured_retry_provider(monkeypatch) -> None:
captured: dict[str, object] = {}
tool_call = SimpleNamespace(
Expand Down Expand Up @@ -496,7 +523,7 @@ def test_conversation_loop_retries_empty_post_tool_before_tool_branch() -> None:

assert empty_retry_idx < generic_stall_idx
assert empty_retry_idx < tool_branch_idx
assert "and not _empty_after_tool_result" in source
assert "not _empty_after_tool_result" in source
assert "EMPTY_AFTER_TOOL_RETRY_NUDGE" in source
assert "accept_content=True" in source

Expand Down
75 changes: 75 additions & 0 deletions tests/test_tui_gateway_server.py
Original file line number Diff line number Diff line change
Expand Up @@ -671,6 +671,81 @@ def test_status_callback_accepts_single_message_argument():
)


def test_status_callbacks_include_live_usage_when_session_is_active(monkeypatch):
usage = {"context_used": 20900, "context_max": 262000, "context_percent": 8}
monkeypatch.setitem(server._sessions, "sid", {"agent": object()})
monkeypatch.setattr(server, "_get_usage", lambda _agent: usage)

with patch("tui_gateway.server._emit") as emit:
callbacks = server._agent_cbs("sid")
callbacks["thinking_callback"]("thinking...")
callbacks["status_callback"]("process", "running tool")

assert emit.call_args_list[0].args == (
"thinking.delta",
"sid",
{"text": "thinking...", "usage": usage},
)
assert emit.call_args_list[1].args == (
"status.update",
"sid",
{"kind": "process", "text": "running tool", "usage": usage},
)


def test_get_usage_uses_rough_context_when_provider_usage_is_missing():
agent = types.SimpleNamespace(
_last_request_context_tokens=20900,
context_compressor=types.SimpleNamespace(
compression_count=0,
context_length=262000,
last_prompt_tokens=0,
),
model="dflash",
)

usage = server._get_usage(agent)

assert usage["context_used"] == 20900
assert usage["context_max"] == 262000
assert usage["context_percent"] == 8
assert usage["context_estimated"] is True


def test_get_usage_estimates_initial_context_from_system_and_tools(monkeypatch):
from agent import model_metadata

captured = {}

def fake_estimate(messages, system_prompt="", tools=None):
captured["messages"] = messages
captured["system_prompt"] = system_prompt
captured["tools"] = tools
return 12000

monkeypatch.setattr(model_metadata, "estimate_request_tokens_rough", fake_estimate)

tools = [{"function": {"name": "read_file", "parameters": {}}}]
agent = types.SimpleNamespace(
_cached_system_prompt="system",
context_compressor=types.SimpleNamespace(
compression_count=0,
context_length=262000,
last_prompt_tokens=0,
),
model="dflash",
tools=tools,
)

usage = server._get_usage(agent)

assert captured == {"messages": [], "system_prompt": "system", "tools": tools}
assert usage["context_used"] == 12000
assert usage["context_percent"] == 5
assert usage["context_estimated"] is True
assert agent._last_usage_context_estimate == 12000


def test_resolve_model_uses_inference_model_env(monkeypatch):
monkeypatch.delenv("HERMES_MODEL", raising=False)
monkeypatch.setenv("HERMES_INFERENCE_MODEL", " anthropic/claude-sonnet-4.6\n")
Expand Down
65 changes: 62 additions & 3 deletions tui_gateway/server.py
Original file line number Diff line number Diff line change
Expand Up @@ -391,14 +391,62 @@ def _emit(event: str, sid: str, payload: dict | None = None):
write_json({"jsonrpc": "2.0", "method": "event", "params": params})


def _usage_for_sid(sid: str) -> dict | None:
try:
agent = (_sessions.get(sid) or {}).get("agent")
if agent is None:
return None
return _get_usage(agent)
except Exception:
return None


def _rough_context_estimate(agent) -> int:
for attr in ("_last_request_context_tokens", "_last_request_tokens_estimate"):
try:
value = int(getattr(agent, attr, 0) or 0)
except Exception:
value = 0
if value > 0:
return value

try:
cached = int(getattr(agent, "_last_usage_context_estimate", 0) or 0)
except Exception:
cached = 0
if cached > 0:
return cached

try:
from agent.model_metadata import estimate_request_tokens_rough

estimate = estimate_request_tokens_rough(
[],
system_prompt=getattr(agent, "_cached_system_prompt", "") or "",
tools=getattr(agent, "tools", None) or None,
)
except Exception:
estimate = 0
if estimate > 0:
try:
agent._last_usage_context_estimate = estimate
except Exception:
pass
return estimate


def _status_update(sid: str, kind: str, text: str | None = None):
body = (text if text is not None else kind).strip()
if not body:
return
payload = {"kind": kind if text is not None else "status", "text": body}
usage = _usage_for_sid(sid)
if usage is not None:
payload["usage"] = usage
_emit(
"status.update",
sid,
{"kind": kind if text is not None else "status", "text": body},
payload,
)


Expand Down Expand Up @@ -1328,6 +1376,7 @@ def _sync_session_key_after_compress(

def _get_usage(agent) -> dict:
g = lambda k, fb=None: getattr(agent, k, 0) or (getattr(agent, fb, 0) if fb else 0)
rough_context = _rough_context_estimate(agent)
usage = {
"model": getattr(agent, "model", "") or "",
"input": g("session_input_tokens", "session_prompt_tokens"),
Expand All @@ -1342,12 +1391,15 @@ def _get_usage(agent) -> dict:
}
comp = getattr(agent, "context_compressor", None)
if comp:
ctx_used = getattr(comp, "last_prompt_tokens", 0) or usage["total"] or 0
ctx_real = getattr(comp, "last_prompt_tokens", 0) or 0
ctx_used = ctx_real if ctx_real > 0 else rough_context or usage["total"] or 0
ctx_estimated = ctx_real <= 0 and rough_context > 0
ctx_max = getattr(comp, "context_length", 0) or 0
if ctx_max:
usage["context_used"] = ctx_used
usage["context_max"] = ctx_max
usage["context_percent"] = max(0, min(100, round(ctx_used / ctx_max * 100)))
usage["context_estimated"] = ctx_estimated
usage["compressions"] = getattr(comp, "compression_count", 0) or 0
try:
from agent.usage_pricing import CanonicalUsage, estimate_usage_cost
Expand Down Expand Up @@ -1768,6 +1820,13 @@ def _on_tool_progress(


def _agent_cbs(sid: str) -> dict:
def _thinking_delta(text):
payload = {"text": text}
usage = _usage_for_sid(sid)
if usage is not None:
payload["usage"] = usage
_emit("thinking.delta", sid, payload)

return {
"tool_start_callback": lambda tc_id, name, args: _on_tool_start(
sid, tc_id, name, args
Expand All @@ -1780,7 +1839,7 @@ def _agent_cbs(sid: str) -> dict:
),
"tool_gen_callback": lambda name: _tool_progress_enabled(sid)
and _emit("tool.generating", sid, {"name": name}),
"thinking_callback": lambda text: _emit("thinking.delta", sid, {"text": text}),
"thinking_callback": _thinking_delta,
"reasoning_callback": lambda text: _emit(
"reasoning.delta",
sid,
Expand Down
42 changes: 41 additions & 1 deletion ui-tui/src/__tests__/appChromeStatusRule.test.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -110,9 +110,49 @@ describe('StatusRule compact phone layout', () => {

const content = textContent(element)

expect(content).toContain('model dflash')
expect(content).toContain('dflash')
expect(content).toContain('ctx 20.9k/262k 8%')
expect(content).toContain('1 session')
expect(content).toContain('~/Workspaces')
})

it('does not spill compact busy status words across phone lines', () => {
const now = new Date('2026-05-31T22:30:00Z').getTime()
vi.useFakeTimers()
vi.setSystemTime(now)

try {
const element = StatusRule({
bgCount: 0,
busy: true,
cols: 58,
cwdLabel: '~/Workspaces',
liveSessionCount: 1,
model: 'dflash',
sessionStartedAt: now - 90_000,
showCost: false,
status: 'deliberating...',
statusColor: DEFAULT_THEME.color.ok,
t: DEFAULT_THEME,
turnStartedAt: now - 45_000,
usage: {
context_estimated: true,
context_max: 262000,
context_percent: 8,
context_used: 20900,
total: 20900
},
voiceLabel: 'voice off'
})

const content = textContent(element)

expect(content).toContain('- busy 45s | dflash | ctx ~20.9k/262k 8%')
expect(content).toContain('dur 1m 30s | voice off | 1 session | ~/Workspaces')
expect(content).not.toContain('deliberating')
expect(content).not.toContain('model dfla')
} finally {
vi.useRealTimers()
}
})
})
45 changes: 45 additions & 0 deletions ui-tui/src/__tests__/createGatewayEventHandler.test.ts
Original file line number Diff line number Diff line change
Expand Up @@ -319,6 +319,51 @@ describe('createGatewayEventHandler', () => {
}
})

it('updates status-bar usage from live thinking and status events', () => {
const onEvent = createGatewayEventHandler(buildCtx([]))

onEvent({ payload: {}, type: 'message.start' } as any)
onEvent({
payload: {
text: 'thinking...',
usage: {
calls: 1,
context_estimated: true,
context_max: 262000,
context_percent: 8,
context_used: 20900,
input: 0,
output: 0,
total: 0
}
},
type: 'thinking.delta'
} as any)

expect(getUiState().usage.context_used).toBe(20900)
expect(getUiState().usage.context_estimated).toBe(true)

onEvent({
payload: {
kind: 'process',
text: 'running tool',
usage: {
calls: 1,
context_max: 262000,
context_percent: 9,
context_used: 24000,
input: 0,
output: 0,
total: 0
}
},
type: 'status.update'
} as any)

expect(getUiState().usage.context_used).toBe(24000)
expect(getUiState().usage.context_percent).toBe(9)
})

it('ignores late thinking.delta after the turn has already completed', () => {
vi.useFakeTimers()
const appended: Msg[] = []
Expand Down
Loading
Loading