Skip to content

The agent that grows with you

fix(tui_gateway): answer /context in-process and run /refine on local sessions

Brooklyn Nicholsoncb97982de766
diff --git a/tests/tui_gateway/test_context_local_slash.py b/tests/tui_gateway/test_context_local_slash.py
new file mode 100644
index 00000000000..378d46049db
--- /dev/null
+++ b/tests/tui_gateway/test_context_local_slash.py
@@ -0,0 +1,140 @@
+"""``/context`` must be answered IN-PROCESS for a local (non-compute-host) session.
+
+The slash worker is a CLI subprocess whose ``self.agent`` is built lazily by the
+first chat prompt and never by a slash command, so its /context answers
+"(._.) No active agent -- send a message first." for ANY local session — active
+or idle (#93280). The gateway already renders the view from the live session
+(``_format_live_context_output``), with the desktop gauge's breakdown engine when
+a live agent exists; this pins that routing so the command never falls through
+to the worker for a local session.
+
+Supersedes the narrower #81266, which only served the agentless case and pinned
+the live-agent fallthrough (the bug) as intended behaviour.
+"""
+
+from __future__ import annotations
+
+import contextlib
+import threading
+from types import SimpleNamespace
+from unittest.mock import patch
+
+from tui_gateway import server
+
+
+def _live_session(agent, messages=2):
+ return {
+ "agent": agent,
+ "session_key": "sk-1",
+ "session_id": "sid-1",
+ "history": [
+ {"role": "user", "content": "hello"},
+ {"role": "assistant", "content": "hi"},
+ ][:messages],
+ "history_lock": threading.Lock(),
+ "running": False,
+ }
+
+
+def _no_db():
+ """Render from in-memory history: no state.db needed in the test."""
+ return contextlib.nullcontext()
+
+
+def test_context_local_session_with_live_agent(monkeypatch):
+ """THE bug: a live local session's /context fell through to the worker CLI
+ (lazy agent, always None) and answered 'No active agent'."""
+ monkeypatch.setattr(server, "_session_uses_compute_host", lambda *a, **k: False)
+ monkeypatch.setattr(server, "_session_db", _no_db)
+
+ out = server._live_slash_command_output("sid-1", _live_session(object()), "context", "")
+
+ assert out is not None, "/context fell through to the CLI worker for a local session"
+ assert "No active agent" not in out
+ assert "Conversation:" in out
+
+
+def test_context_local_session_agentless(monkeypatch):
+ """Agentless (idle/resumed) local session: same in-process path (#81266 case)."""
+ monkeypatch.setattr(server, "_session_uses_compute_host", lambda *a, **k: False)
+ monkeypatch.setattr(server, "_session_db", _no_db)
+
+ out = server._live_slash_command_output("sid-1", _live_session(None), "context", "")
+
+ assert out is not None
+ assert "No active agent" not in out
+ assert "Conversation:" in out
+
+
+def test_context_compute_host_route_unchanged(monkeypatch):
+ """Guard: the isolated/compute-host route the gate was built for still works."""
+ monkeypatch.setattr(server, "_session_uses_compute_host", lambda *a, **k: True)
+ monkeypatch.setattr(server, "_session_db", _no_db)
+
+ out = server._live_slash_command_output("sid-1", _live_session(object()), "context", "")
+
+ assert out is not None
+ assert "Conversation:" in out
+
+
+def test_tools_local_still_falls_through(monkeypatch):
+ """Scope guard: /tools consults the agent, so it keeps the old routing."""
+ monkeypatch.setattr(server, "_session_uses_compute_host", lambda *a, **k: False)
+
+ out = server._live_slash_command_output("sid-1", _live_session(None), "tools", "")
+
+ assert out is None # worker path, unchanged
+
+
+def test_context_breakdown_engine_used_with_live_agent(monkeypatch):
+ """With a live agent, the output carries the gauge engine's 'Context window'
+ line (same compute_session_context_breakdown the popover RPC uses)."""
+ monkeypatch.setattr(server, "_session_uses_compute_host", lambda *a, **k: False)
+ monkeypatch.setattr(server, "_session_db", _no_db)
+
+ payload = {
+ "categories": [
+ {"id": "system_prompt", "label": "System prompt", "tokens": 8000, "color": "dim"},
+ {"id": "conversation", "label": "Conversation", "tokens": 82000, "color": "normal"},
+ ],
+ "context_max": 131072,
+ "context_percent": 68,
+ "context_used": 90000,
+ "context_source": "provider_usage",
+ "context_estimated": False,
+ "estimated_total": 90000,
+ "model": "test-model",
+ }
+ with patch("agent.context_breakdown.compute_session_context_breakdown", return_value=payload):
+ out = server._live_slash_command_output("sid-1", _live_session(object()), "context", "")
+
+ assert out is not None
+ assert "Context window:" in out
+ assert "90,000" in out # rendered from the breakdown payload, not the usage mirror
+
+
+def test_context_all_arg_reaches_details(monkeypatch):
+ """``/context all`` expands per-skill / per-toolset costs (compute_context_details)."""
+ monkeypatch.setattr(server, "_session_uses_compute_host", lambda *a, **k: False)
+ monkeypatch.setattr(server, "_session_db", _no_db)
+
+ payload = {
+ "categories": [{"id": "conversation", "label": "Conversation", "tokens": 1000, "color": "normal"}],
+ "context_max": 10000,
+ "context_percent": 10,
+ "context_used": 1000,
+ "context_source": "provider_usage",
+ "context_estimated": False,
+ "estimated_total": 1000,
+ "model": "test-model",
+ }
+ details = {"skills": [], "toolsets": []}
+ with (
+ patch("agent.context_breakdown.compute_session_context_breakdown", return_value=payload) as m_breakdown,
+ patch("agent.context_breakdown.compute_context_details", return_value=details) as m_details,
+ ):
+ out = server._live_slash_command_output("sid-1", _live_session(object()), "context", "all")
+
+ assert out is not None
+ m_breakdown.assert_called_once()
+ m_details.assert_called_once()
diff --git a/tests/tui_gateway/test_slash_refine_live.py b/tests/tui_gateway/test_slash_refine_live.py
new file mode 100644
index 00000000000..735a4ef7eb8
--- /dev/null
+++ b/tests/tui_gateway/test_slash_refine_live.py
@@ -0,0 +1,125 @@
+"""/refine from a completed Desktop/TUI session. The in-memory agent cache may be absent
+(or its history empty) on a session that was reattached from disk — refine must replay the
+PERSISTED transcript and spawn the background review on the live agent, instead of falling
+back to the isolated slash worker and answering "Nothing to refine yet" (#93918, #83455).
+
+Covers tui_gateway/methods_slash.py `_format_live_refine_output`.
+"""
+
+from __future__ import annotations
+
+import contextlib
+import threading
+from unittest.mock import patch
+
+from tui_gateway import server
+from tui_gateway.transport import StdioTransport
+
+
+def _live_session(agent, *, session_key: str, history: list):
+ return {
+ "agent": agent, "session_key": session_key, "history": list(history),
+ "history_lock": threading.Lock(), "running": False,
+ "transport": StdioTransport(lambda: None, threading.Lock()),
+ "cwd": "", "source": "desktop",
+ }
+
+
+class _Agent:
+ valid_tool_names = {"memory", "skill_manage"}
+
+ def __init__(self):
+ self.spawned: list[dict] = []
+
+ def _spawn_background_review(self, **kwargs):
+ self.spawned.append(kwargs)
+
+
+class _DB:
+ def get_messages_as_conversation(self, key, include_ancestors=True, **_kwargs):
+ assert key == "refine-key"
+ assert include_ancestors is True
+ return [
+ {"role": "user", "content": "persisted question"},
+ {"role": "assistant", "content": "persisted answer"},
+ ]
+
+
+def _fake_session_db(_session):
+ yield _DB()
+
+
+def test_refine_spawns_review_from_persisted_transcript():
+ """A reattached session with an empty in-memory history still refines, from state.db."""
+ sid = "refine-sid"
+ agent = _Agent()
+ session = _live_session(agent, session_key="refine-key", history=[])
+ server._sessions[sid] = session
+
+ try:
+ with (
+ patch.object(server, "_session_uses_compute_host", return_value=False),
+ patch.object(server, "_session_db", _fake_session_db),
+ ):
+ out = server._live_slash_command_output(sid, session, "refine", "save the workflow")
+ finally:
+ server._sessions.pop(sid, None)
+
+ assert "Reviewing this conversation" in out
+ assert agent.spawned == [{
+ "messages_snapshot": [
+ {"role": "user", "content": "persisted question"},
+ {"role": "assistant", "content": "persisted answer"},
+ ],
+ "review_memory": True,
+ "review_skills": True,
+ "focus": "save the workflow",
+ # /refine is explicit: it must not be swallowed by the unattended-review gates.
+ "explicit": True,
+ }]
+
+
+class _DBEmpty:
+ def get_messages_as_conversation(self, key, include_ancestors=True, **_kwargs):
+ return []
+
+
+def _fake_session_db_empty(_session):
+ yield _DBEmpty()
+
+
+def test_refine_spawns_review_from_in_memory_history_mid_conversation():
+ """A live mid-conversation session with no persisted rows yet falls back to the
+ locked in-memory history (covers the fallback branch, not just the reattach path)."""
+ sid = "refine-mid"
+ agent = _Agent()
+ history = [
+ {"role": "user", "content": "in-flight question"},
+ {"role": "assistant", "content": "in-flight answer"},
+ ]
+ session = _live_session(agent, session_key="mid-key", history=history)
+ server._sessions[sid] = session
+
+ try:
+ with (
+ patch.object(server, "_session_uses_compute_host", return_value=False),
+ patch.object(server, "_session_db", _fake_session_db_empty),
+ ):
+ out = server._live_slash_command_output(sid, session, "refine", "")
+ finally:
+ server._sessions.pop(sid, None)
+
+ assert "Reviewing this conversation" in out
+ assert agent.spawned == [{
+ "messages_snapshot": [
+ {"role": "user", "content": "in-flight question"},
+ {"role": "assistant", "content": "in-flight answer"},
+ ],
+ "review_memory": True,
+ "review_skills": True,
+ "focus": None,
+ # /refine is explicit: it must not be swallowed by the unattended-review gates.
+ "explicit": True,
+ }]
diff --git a/tests/tui_gateway/test_tui_gateway_server.py b/tests/tui_gateway/test_tui_gateway_server.py
index 13dceef8aa5..60dd57adbf4 100644
--- a/tests/tui_gateway/test_tui_gateway_server.py
+++ b/tests/tui_gateway/test_tui_gateway_server.py
@@ -19910,7 +19910,12 @@ def test_restart_slash_worker_noop_without_worker(monkeypatch):
def test_slash_exec_concurrent_first_use_spawns_single_worker(monkeypatch):
"""With eager pre-warm removed, slash.exec is the only spawn path — two
concurrent worker-routed commands on a fresh session must not each fork a
- full MCP-fleet worker. The per-session spawn lock serializes first use."""
+ full MCP-fleet worker. The per-session spawn lock serializes first use.
+
+ The probe is an unregistered command so it is not answered live, pending-input,
+ bundle, skill, or plugin — it falls through to the worker spawn (the path under
+ test). ``/context`` was the original probe but is now answered in-process for a
+ local session (the #93280 fix), so it no longer reaches the worker."""
import time as _time
spawned = []
@@ -19940,7 +19945,7 @@ def test_slash_exec_concurrent_first_use_spawns_single_worker(monkeypatch):
{
"id": str(n),
"method": "slash.exec",
- "params": {"command": "/context", "session_id": "race-spawn"},
+ "params": {"command": "/frobnicate-probe", "session_id": "race-spawn"},
}
)
results.append(resp)
diff --git a/tui_gateway/compute_host.py b/tui_gateway/compute_host.py
index f3326839b28..50042bb3897 100644
--- a/tui_gateway/compute_host.py
+++ b/tui_gateway/compute_host.py
@@ -475,7 +475,12 @@ class ComputeHost:
with session["history_lock"]:
ack.update(_history_meta(session))
else:
- output = server._mirror_slash_side_effects(sid, session, command) if command else ""
+ if route_name == "slash.refine":
+ parts = command.lstrip("/").split(maxsplit=1)
+ focus = parts[1] if len(parts) > 1 else ""
+ output = server._live_slash_command_output(sid, session, "refine", focus) or ""
+ else:
+ output = server._mirror_slash_side_effects(sid, session, command) if command else ""
with session["history_lock"]:
messages = server._history_to_messages(list(session.get("history") or []), profile_home=session.get("profile_home"))
ack = {"output": output, **_history_meta(session), "messages": messages}
diff --git a/tui_gateway/host_supervisor.py b/tui_gateway/host_supervisor.py
index a3077af3e38..8afd6edb376 100644
--- a/tui_gateway/host_supervisor.py
+++ b/tui_gateway/host_supervisor.py
@@ -29,6 +29,7 @@ MUTATOR_ROUTE_TABLE: dict[str, str] = {
"session.save": "run-concurrent", "session.compress": "idle-gated",
"prompt.submit.truncate": "idle-gated", "slash.model": "idle-gated",
"slash.personality": "idle-gated", "slash.prompt": "idle-gated", "slash.compress": "idle-gated",
+ "slash.refine": "idle-gated",
"session.reset": "idle-gated", "session.history.reload": "idle-gated",
"slash.retry": "idle-gated"}
diff --git a/tui_gateway/methods_slash.py b/tui_gateway/methods_slash.py
index db81dc231aa..9e4f6b92c94 100644
--- a/tui_gateway/methods_slash.py
+++ b/tui_gateway/methods_slash.py
@@ -18,6 +18,16 @@ _registry = HandlerRegistry()
# Answered from the live session ONLY when the agent lives on a compute host.
_ISOLATED_SESSION_READ_COMMANDS = frozenset({"context", "tools", "help"})
+# /context on a LOCAL session is answered in-process: the slash worker is a CLI
+# subprocess whose ``self.agent`` is built lazily by the first chat prompt and
+# never by a slash command, so its /context answers "(._.) No active agent" for
+# any local session, active or idle (#81251 / #93280). With a live agent we render
+# the full Cursor-style breakdown (the desktop gauge's engine); without one we
+# fall back to the persisted-state view. ``tools``/``help`` keep the old routing:
+# ``_format_live_tools_output`` reads ``session["agent"]``, so serving it here
+# for an agentless session would answer worse, not better.
+_CONTEXT_LOCAL_IN_PROCESS = frozenset({"context"})
+
_NO_AGENT_USAGE = "(._.) No active agent -- send a message first."
_NO_AGENT = "No active agent -- send a message first."
@@ -60,6 +70,67 @@ def _format_live_review_output(sid: str, session: Optional[dict], arg: str) -> s
return format_dispatch_note(result, arg or "")
+def _format_live_refine_output(sid: str, session: Optional[dict], arg: str) -> str:
+ """Dispatch /refine against the live session's agent: spawn the background
+ memory/skills review directly instead of forking the isolated slash worker."""
+ if session is None:
+ return "Refine unavailable (no session)."
+ if session.get("running"):
+ return "Agent is running — wait for the turn to finish, then /refine."
+ if _session_uses_compute_host(session):
+ command = "/refine" + (f" {arg}" if arg.strip() else "")
+ try:
+ ack = _send_compute_host_control(
+ sid,
+ route_name="slash.refine",
+ command=command,
+ wait=True,
+ )
+ except Exception as exc:
+ return f"compute-host slash.refine failed: {exc}"
+ if ack.get("type") in {"control.error", "error"}:
+ return str(ack.get("message") or "compute-host slash.refine failed")
+ _apply_compute_host_metadata_mirror(session, ack)
+ return str(ack.get("output") or "")
+ agent = session.get("agent")
+ if agent is None:
+ return "Nothing to refine yet — send a message first."
+
+ snapshot = []
+ transcript_ref = str(session.get("session_key") or "")
+ if transcript_ref:
+ try:
+ with _session_db(session) as db:
+ if db is not None:
+ snapshot = db.get_messages_as_conversation(
+ transcript_ref, include_ancestors=True
+ )
+ except Exception:
+ logger.debug("failed to load persisted /refine transcript", exc_info=True)
+ if not snapshot:
+ with session["history_lock"]:
+ snapshot = list(session.get("history", []))
+ if not snapshot:
+ return "Nothing to refine yet — the conversation is empty."
+
+ review_skills = "skill_manage" in getattr(agent, "valid_tool_names", set())
+ try:
+ agent._spawn_background_review(
+ messages_snapshot=list(snapshot),
+ review_memory=True,
+ review_skills=review_skills,
+ focus=arg.strip() or None,
+ explicit=True,
+ )
+ except Exception as exc:
+ return f"/refine failed to start: {exc}"
+ tail = f" (focus: {arg.strip()})" if arg.strip() else ""
+ return (
+ f"⚗ Reviewing this conversation in the background{tail} — "
+ "any memory/skill updates will be reported when done."
+ )
+
+
def _format_live_usage_output(sid: str, session: dict, arg: str) -> str:
agent = session.get("agent")
usage = _session_usage_snapshot(session)
@@ -126,6 +197,34 @@ def _format_live_context_output(sid: str, session: dict, arg: str) -> str:
if not messages:
with session["history_lock"]:
messages = _history_to_messages(list(session.get("history", [])), profile_home=session.get("profile_home"))
+
+ breakdown_lines: list[str] = []
+ if (agent := session.get("agent")) is not None:
+ # Live agent: the desktop gauge's engine (agent.context_breakdown) —
+ # full Cursor-style breakdown, provider-anchored, no provider calls.
+ # `all` expands per-skill / per-toolset costs, matching the CLI.
+ with session["history_lock"]:
+ live_messages = list(session.get("history", []))
+ try:
+ # Bind the session context: on the RPC thread the session cwd is unset, so the
+ # prompt build inside would key its workspace pin on the backend's cwd.
+ tokens = _set_session_context(session["session_key"], cwd=_session_cwd(session))
+ try:
+ from agent.context_breakdown import (
+ compute_context_details,
+ compute_session_context_breakdown,
+ render_context_breakdown_lines)
+ payload = compute_session_context_breakdown(agent, live_messages)
+ details = None
+ if (arg or "").strip().lower() in {"all", "full", "details"}:
+ with contextlib.suppress(Exception):
+ details = compute_context_details(agent)
+ breakdown_lines = render_context_breakdown_lines(payload, details=details, grid=False)
+ finally:
+ _clear_session_context(tokens)
+ except Exception:
+ breakdown_lines = [] # fall back to the persisted-state view below
+
usage = _session_usage_snapshot(session)
mirror = _metadata_mirror(session)
lines = [f"Conversation: {len(messages)} messages" if messages else "Conversation is empty (no messages yet)."]
@@ -134,6 +233,9 @@ def _format_live_context_output(sid: str, session: dict, arg: str) -> str:
if model := mirror.get("model") or usage.get("model") or "":
lines.append(f"Model: {model}")
lines.append(f"Provider: {mirror.get('provider') or 'auto'}")
+ if breakdown_lines:
+ lines.extend(["", *breakdown_lines])
+ return "\n".join(lines)
context_used = int(usage.get("context_used") or 0)
mark = "~" if usage.get("context_estimated") else ""
context_max = int(usage.get("context_max") or 0)
@@ -204,6 +306,7 @@ _LIVE_SLASH_OUTPUT = {
"usage": (_NO_AGENT_USAGE, _format_live_usage_output),
"review": (None, _format_live_review_output),
"history": ("No conversation history yet.", _format_live_history_output),
+ "refine": (None, _format_live_refine_output),
"status": (None, _format_live_status_output),
"context": ("Conversation is empty (no messages yet).", _format_live_context_output),
"tools": ("No tools available.", _format_live_tools_output),
@@ -220,6 +323,12 @@ def _live_slash_command_output(sid: str, session: Optional[dict], name: str, arg
arg = arg or ""
if name == "model" and not arg.strip():
return _format_live_model_output(session or {})
+ if (
+ name in _CONTEXT_LOCAL_IN_PROCESS
+ and session is not None
+ and not _session_uses_compute_host(session)
+ ):
+ return _format_live_context_output(sid, session, arg)
if name in _ISOLATED_SESSION_READ_COMMANDS and not (session is not None and _session_uses_compute_host(session)):
return None
entry = _LIVE_SLASH_OUTPUT.get(name)