The agent that grows with you
Python aiai-agentai-agentsanthropicchatgptclaudeclaude-codecodexhermeshermes-agentllmnous-researchopenai
fix(agent): name the running Bot Screen in the model context
Brooklyn Nicholson94a57ead919d
diff --git a/agent/prompt_builder.py b/agent/prompt_builder.pyindex 4dec6655283..e53105f5f6c 100644--- a/agent/prompt_builder.py+++ b/agent/prompt_builder.py@@ -1038,6 +1038,42 @@ def _local_host_hints() -> list[str]:return ["\n".join(host_lines), _WINDOWS_BASH_SHELL_HINT]+def bot_screen_note(running: bool, display: "str | None", holder: str) -> str:+ """The one-line Bot Screen status the model sees — the prompt's ``_bot_screen_hint`` body,+ parameterised so the display watcher can stage the same sentence as a per-turn note when a+ screen starts or stops mid-session (#125830; the byte-stable prompt only converges at+ compaction). ``holder`` is ``lease.AGENT``/``lease.HUMAN``; "" when there is nothing to say+ (a stop with no display known, or an unknown holder on a running screen)."""+ if running:+ if not display:+ return ""+ held = ("a human holds it — do not drive the screen; ask them or wait" if holder == "human"+ else "you hold it" if holder == "agent" else "")+ if not held:+ return ""+ return (f"Bot Screen: this profile's own headless desktop is RUNNING on display {display} "+ f"({held}). 'screen N' / ':N' / 'the bot screen' / 'your screen' means THIS screen: "+ f"GUI apps you launch from the terminal already open there (their DISPLAY is routed "+ f"to it), and display introspection (xrandr/xdotool/wmctrl) targets it. It is NOT "+ f"the user's own display.")+ return ("Bot Screen: this profile's own headless desktop is no longer running. Do not refer to "+ "'the bot screen' or route GUI launches at it; GUI apps from the terminal open on the "+ "user's own display again.")+++def _bot_screen_hint() -> str:+ """One line naming this profile's running Bot Screen (#125830): the display, and who holds it.++ Pure reads (``published_env`` + the lease file); never raises — a missing/unimportable+ bot_desktop module or an unreadable lease must not break prompt construction. ``""`` when+ no screen is running, so the block simply drops out of the environment hints."""+ try:+ from tools.bot_desktop import lease as _bd_lease, runtime as _bd_runtime+ return bot_screen_note(True, _bd_runtime.published_env().get("DISPLAY"), _bd_lease.get().holder)+ except Exception:+ return ""++def _remote_backend_hint(backend: str) -> str:"""Backend-only block for remote/sandbox backends (host info deliberately suppressed)."""lead = (f"Terminal backend: {backend}. Your `terminal`, `read_file`, `write_file`, `patch`, and "@@ -1086,6 +1122,10 @@ def build_environment_hints() -> str:backend = (_tenv_read("TERMINAL_ENV") or "local").strip().lower()is_remote_backend = backend in _REMOTE_TERMINAL_BACKENDS or _plugin_backend_is_remote(backend)hints = [_remote_backend_hint(backend)] if is_remote_backend else _local_host_hints()+ # A host-placed Bot Screen is only reachable from a local backend (a sandboxed terminal cannot+ # open windows on the gateway host), and a sandbox-placed one is the sandbox probe's business.+ if not is_remote_backend:+ hints.append(_bot_screen_hint())hints += [WSL_ENVIRONMENT_HINT] if is_wsl() else []return "\n\n".join(h for h in (*hints, _embedder_environment_hint()) if h)diff --git a/tests/agent/test_prompt_builder.py b/tests/agent/test_prompt_builder.pyindex b9cb66e24de..fe11bb1902a 100644--- a/tests/agent/test_prompt_builder.py+++ b/tests/agent/test_prompt_builder.py@@ -5,6 +5,7 @@ import osimport sysimport timefrom pathlib import Path+from types import SimpleNamespaceimport pytest@@ -699,6 +700,48 @@ class TestEnvironmentHints:_pb._BACKEND_PROBE_CACHE.clear()assert f"Current working directory: {tmp_path}" in _pb.build_environment_hints()+ def test_running_bot_screen_rides_the_environment_hints(self, monkeypatch):+ """#125830: with this profile's Bot Screen up, the local-backend hints must NAME it —+ display number and lease holder — so 'open chrome in screen 20' resolves to the bot's own+ screen instead of launching on the user's display via a confused terminal call."""+ import agent.prompt_builder as _pb+ monkeypatch.setattr(_pb, "is_wsl", lambda: False)+ monkeypatch.delenv("TERMINAL_ENV", raising=False)+ monkeypatch.setattr("tools.bot_desktop.runtime.published_env",+ lambda: {"DISPLAY": ":20", "XAUTHORITY": "/run/x"})+ monkeypatch.setattr("tools.bot_desktop.lease.get", lambda: SimpleNamespace(holder="agent"))+ hints = _pb.build_environment_hints()+ assert "Bot Screen" in hints and "display :20" in hints and "you hold it" in hints++ def test_human_held_bot_screen_says_so(self, monkeypatch):+ import agent.prompt_builder as _pb+ monkeypatch.setattr(_pb, "is_wsl", lambda: False)+ monkeypatch.delenv("TERMINAL_ENV", raising=False)+ monkeypatch.setattr("tools.bot_desktop.runtime.published_env", lambda: {"DISPLAY": ":20"})+ monkeypatch.setattr("tools.bot_desktop.lease.get", lambda: SimpleNamespace(holder="human"))+ hints = _pb.build_environment_hints()+ assert "a human holds it" in hints and "do not drive the screen" in hints++ def test_stopped_bot_screen_leaves_no_hint(self, monkeypatch):+ """No screen running → nothing added; the block must drop out entirely, not say 'None'."""+ import agent.prompt_builder as _pb+ monkeypatch.setattr(_pb, "is_wsl", lambda: False)+ monkeypatch.delenv("TERMINAL_ENV", raising=False)+ monkeypatch.setattr("tools.bot_desktop.runtime.published_env", lambda: {})+ _pb._BACKEND_PROBE_CACHE.clear()+ assert "Bot Screen" not in _pb.build_environment_hints()++ def test_remote_backend_never_sees_a_host_bot_screen(self, monkeypatch):+ """A sandboxed terminal cannot open windows on the gateway host, so the hint is local-only."""+ import agent.prompt_builder as _pb+ monkeypatch.setattr(_pb, "is_wsl", lambda: False)+ monkeypatch.setenv("TERMINAL_ENV", "docker")+ monkeypatch.setattr(_pb, "_probe_remote_backend", lambda _t: None)+ monkeypatch.setattr("tools.bot_desktop.runtime.published_env",+ lambda: {"DISPLAY": ":20"})+ _pb._BACKEND_PROBE_CACHE.clear()+ assert "Bot Screen" not in _pb.build_environment_hints()+def test_remote_backend_probe_carries_no_user_home_cwd(self, monkeypatch):diff --git a/tests/tui_gateway/test_display_watch.py b/tests/tui_gateway/test_display_watch.pyindex 85c152eff74..845f35afd1b 100644--- a/tests/tui_gateway/test_display_watch.py+++ b/tests/tui_gateway/test_display_watch.py@@ -132,3 +132,51 @@ def test_launcher_dying_without_touching_its_files_is_broadcast_as_stopped(tmp_pif launcher.poll() is None:launcher.kill()launcher.wait(5)+++def test_screen_start_and_stop_reach_the_models_turn_notes(tmp_path, monkeypatch):+ """#125830: a screen started/stopped mid-session must reach the model without waiting for a+ prompt rebuild — the watcher stages the Bot Screen line as a one-shot per-turn note on every+ live session of THAT profile. The staged note is consumed on the next turn+ (``agent/turn_context.py``), so only its presence here is asserted."""+ import psutil+ import tui_gateway.server as server++ home = tmp_path / "home"+ (home / "bot-desktop").mkdir(parents=True)+ events = _watching(server, home, monkeypatch)++ class _Agent: # a plain object: MagicMock would auto-create the note attribute+ _gateway_turn_context_notes = ""++ agent, other = _Agent(), _Agent()+ server._sessions["ws-a"] = {"agent": agent, "profile_home": str(home), "transport": server._detached_ws_transport}+ other_home = tmp_path / "other"+ other_home.mkdir()+ server._sessions["ws-b"] = {"agent": other, "profile_home": str(other_home), "transport": server._detached_ws_transport}+ # the stub "launcher": a real live process with matching create_time, like runtime.start() records+ launcher = subprocess.Popen([sys.executable, "-c", "import time; time.sleep(30)"], stdin=subprocess.DEVNULL) # noqa: S603+ try:+ server._poll_runtime_files() # seed: stopped+ assert not getattr(agent, "_gateway_turn_context_notes", "")++ born = psutil.Process(launcher.pid).create_time()+ (home / "bot-desktop" / "launcher.pid").write_text(f"{launcher.pid} {born!r}", encoding="utf-8")+ (home / "bot-desktop" / "env").write_text("DISPLAY=:77\n", encoding="utf-8")+ server._poll_runtime_files()+ note = getattr(agent, "_gateway_turn_context_notes", "")+ assert "Bot Screen" in note and "display :77" in note and "RUNNING" in note, note+ assert not getattr(other, "_gateway_turn_context_notes", ""), "another profile's session was told"++ (home / "bot-desktop" / "env").unlink() # stop() from another process+ server._poll_runtime_files()+ note = getattr(agent, "_gateway_turn_context_notes", "")+ assert "no longer running" in note, note+ assert [e for e in events if e[0] == "display.status"] # the broadcast still happened+ finally:+ with server._sessions_lock:+ server._sessions.pop("ws-a", None)+ server._sessions.pop("ws-b", None)+ if launcher.poll() is None:+ launcher.kill()+ launcher.wait(5)diff --git a/tui_gateway/methods_display_watch.py b/tui_gateway/methods_display_watch.pyindex 9e0ce28c982..89a349c488f 100644--- a/tui_gateway/methods_display_watch.py+++ b/tui_gateway/methods_display_watch.py@@ -46,6 +46,38 @@ def _mtime(path: Path):return None+def _notify_agents_of_screen_change(profile_key: str, payload: dict) -> None:+ """Stage the Bot Screen line as a per-turn note on that profile's live agents (#125830).++ The system prompt is byte-stable and only rebuilt at compaction, so a screen started or+ stopped mid-session would otherwise stay unknown to the model until then. The note rides+ the one-shot user-message channel (``_gateway_turn_context_notes``, consumed by+ ``agent/turn_context.py``), landing behind the cached prefix. Sessions may hold a fresh+ agent per turn, so the note is staged on every live session of the profile, not just one.+ ``payload`` is the just-broadcast display.status snapshot (``running``/``display`` and the+ lease's public view), already read under the profile's home override."""+ from hermes_constants import hermes_home_key+ try:+ from agent.prompt_builder import bot_screen_note+ lease_view = payload.get("lease") if isinstance(payload.get("lease"), dict) else {}+ line = bot_screen_note(bool(payload.get("running")), payload.get("display"),+ str(lease_view.get("holder") or ""))+ except Exception:+ return+ if not line:+ return+ with _sessions_lock:+ sids = [sid for sid, sess in _sessions.items() if isinstance(sess, dict) and sess.get("agent") is not None+ and hermes_home_key(sess.get("profile_home") or get_process_hermes_home()) == profile_key]+ for sid in sids:+ agent = _sessions[sid]["agent"]+ try:+ prior = getattr(agent, "_gateway_turn_context_notes", "") or ""+ agent._gateway_turn_context_notes = f"{prior}\n\n{line}" if prior else line+ except Exception:+ logger.debug("could not stage Bot Screen note on session %s", sid, exc_info=True)++def _poll_runtime_files() -> None:"""Broadcast ``display.status`` when a home's screen started/stopped outside this process — afile move (start/stop by the CLI or gateway) or the launcher dying without touching its files@@ -68,6 +100,7 @@ def _poll_runtime_files() -> None:finally:reset_hermes_home_override(token)_broadcast_global_event("display.status", payload)+ _notify_agents_of_screen_change(key, payload)_IDLE_CHECK_S = 30.0