Skip to content

Commit 8252a86

Browse files
committed
Show the active agent in the status bar and /agent list
Switching with /agent gave no visible confirmation of the new profile. - Status bar renders @<agent> after the mode tag, @default for the built-in prompt; the name is sanitized, whitespace-flattened and cell-budgeted so it cannot break the pinned bar layout. - /agent marks the active profile with "← active" (right after the name, so a long prompt path cannot separate the two) and warns when the active profile's file is no longer on disk. - The switch now reports "agent-switched" so the render loop wakes up without replacing the idle status with a bare " running". - Numeric selections require ASCII digits: "²".isdigit() is True but int("²") raises ValueError, which crashed /agent and /model.
1 parent 82b2c08 commit 8252a86

8 files changed

Lines changed: 209 additions & 11 deletions

File tree

‎README.md‎

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -106,7 +106,7 @@ Agent files are markdown (`.md`) in `prompts/agents/`. Each becomes a switchable
106106
- `name:` — override the agent name (defaults to file stem)
107107
- `exclude_tools:` — list of tool names to hide. Matches by exact name, glob (`mcp__git__*`), or `__`-delimited prefix (`mcp__git` hides `mcp__git__list_repos` but `Write` does NOT hide `TodoWrite`).
108108
109-
**Commands vs Agents:** Commands (`/review`) are one-shot with a hardcoded kickoff and reset after run. Agents (`/agent reviewer`) persist until the next `/agent`, let the user type their own prompt, and stay active after `Ctrl-C`.
109+
**Commands vs Agents:** Commands (`/review`) are one-shot with a hardcoded kickoff and reset after run. Agents (`/agent reviewer`) persist until the next `/agent`, let the user type their own prompt, and stay active after `Ctrl-C`. The active agent is always shown in the status bar (`[BUILD] @reviewer ...`, `@default` for the built-in), and `/agent` marks the current profile with `← active` in its list.
110110
111111
## Configuration
112112

‎python_agent_harness/tui/commands.py‎

Lines changed: 21 additions & 7 deletions
Original file line numberDiff line numberDiff line change
@@ -481,7 +481,7 @@ def _run_model_command(self, arg: str) -> None:
481481
return
482482

483483
# Check if selection is a number
484-
if selection.isdigit():
484+
if selection.isascii() and selection.isdigit():
485485
idx = int(selection) - 1
486486
if 0 <= idx < len(all_names):
487487
selected = all_names[idx]
@@ -503,7 +503,7 @@ def _run_model_command(self, arg: str) -> None:
503503
return
504504

505505
# Check if arg is a number
506-
if arg.strip().isdigit():
506+
if arg.strip().isascii() and arg.strip().isdigit():
507507
all_names = self._model_list_names()
508508
idx = int(arg.strip()) - 1
509509
if 0 <= idx < len(all_names):
@@ -569,7 +569,7 @@ def _agent_switch_by_name(self, name: str) -> None:
569569
success, msg = self._controller.switch_agent(name)
570570
if success:
571571
self.console.print(f"[green]{safe_markup(msg)}[/green]")
572-
self._data_event.set()
572+
self._on_notify("agent-switched")
573573
else:
574574
self.console.print(f"[red]{safe_markup(msg)}[/red]")
575575

@@ -583,14 +583,28 @@ def _run_agent_command(self, arg: str) -> None:
583583
self.console.print(
584584
"[yellow] (none found — add .md files to the prompts/agents/ directory to use /agent)[/yellow]"
585585
)
586+
# Which agent is currently active: the store records None for
587+
# the built-in default, so "no agent" means "default" here too.
588+
# The marker sits right after the name (not at the end of the
589+
# row) so a long prompt path wrapping the line cannot separate
590+
# the marker from the profile it belongs to.
591+
active_name = getattr(self._controller.session.store, "agent", None)
592+
active = active_name or RESERVED_AGENT_NAME
586593
for idx, name in enumerate(all_names, 1):
594+
marker = " [green]← active[/green]" if name == active else ""
587595
if name == RESERVED_AGENT_NAME:
588-
self.console.print(f" [cyan]{idx})[/cyan] default — agent.md")
596+
self.console.print(f" [cyan]{idx})[/cyan] default{marker} — agent.md")
589597
else:
590598
prompt_file = self._discovered_agents[name]
591599
self.console.print(
592-
f" [cyan]{idx})[/cyan] {safe_markup(name)} — {safe_markup(prompt_file)}"
600+
f" [cyan]{idx})[/cyan] {safe_markup(name)}{marker} — {safe_markup(prompt_file)}"
593601
)
602+
if active_name and active_name not in self._discovered_agents:
603+
# The active prompt file disappeared while it was in use:
604+
# say so instead of silently listing nothing as active.
605+
self.console.print(
606+
f" [yellow](active agent {safe_markup(active_name)} no longer found on disk)[/yellow]"
607+
)
594608
total_count = len(all_names)
595609
self.console.print(
596610
f"\n[dim]Type a number (1-{total_count}) to switch, or enter an agent name directly[/dim]\n"
@@ -599,7 +613,7 @@ def _run_agent_command(self, arg: str) -> None:
599613
selection = input("Select agent: ").strip()
600614
if not selection:
601615
return
602-
if selection.isdigit():
616+
if selection.isascii() and selection.isdigit():
603617
idx = int(selection) - 1
604618
if 0 <= idx < len(all_names):
605619
self._agent_switch_by_name(all_names[idx])
@@ -614,7 +628,7 @@ def _run_agent_command(self, arg: str) -> None:
614628
except KeyboardInterrupt:
615629
self.console.print("\n[dim]cancelled[/dim]")
616630
return
617-
if arg.strip().isdigit():
631+
if arg.strip().isascii() and arg.strip().isdigit():
618632
all_names = self._agent_list_names()
619633
idx = int(arg.strip()) - 1
620634
if 0 <= idx < len(all_names):

‎python_agent_harness/tui/core.py‎

Lines changed: 7 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -236,6 +236,13 @@ def _on_notify(self, kind: str, data: Any = None) -> None:
236236
with self.lock:
237237
self.stream_text = ""
238238
self._history_dirty = True
239+
elif kind == "agent-switched":
240+
# /agent switched the profile: the status bar reads the
241+
# active agent from the session store on every frame, so
242+
# there is nothing to refresh -- but the kind must be
243+
# handled explicitly, or the else branch would replace the
244+
# idle status with a bare " running".
245+
pass
239246
else:
240247
with self.lock:
241248
self.status = " running"

‎python_agent_harness/tui/input.py‎

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -323,7 +323,7 @@ def _resolve_numbered_choice(answer: str, options: list[str]) -> str:
323323
resolved: list[str] = []
324324
for part in answer.split(","):
325325
part = part.strip()
326-
if part.isdigit():
326+
if part.isascii() and part.isdigit():
327327
idx = int(part)
328328
if 1 <= idx <= len(options):
329329
resolved.append(options[idx - 1])

‎python_agent_harness/tui/render.py‎

Lines changed: 39 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -24,7 +24,7 @@
2424
from ..core.models import ImagePart, api_safe, display_args
2525
from ..io.diffrender import render_diff
2626
from ..io.text_filter import strip_final_check, strip_reasoning
27-
from ..prompts import _is_mode_reminder_text
27+
from ..prompts import RESERVED_AGENT_NAME, _is_mode_reminder_text
2828
from ..session import config
2929

3030
if TYPE_CHECKING:
@@ -35,6 +35,13 @@
3535

3636
SPINNER_FRAMES = ["⠋", "⠙", "⠹", "⠸", "⠼", "⠴", "⠦", "⠧", "⠇", "⠏"]
3737

38+
# Cells the status bar's prefix (mode/agent/context) must leave free on
39+
# its first line. One cell is enough for the bar to stay two rows (the
40+
# status wraps next to the prefix and then onto a second full line), so
41+
# the prefix may never fill the width by itself -- which is what pushed a
42+
# narrow terminal to a third row once the agent name was added.
43+
_MIN_STATUS_CELLS = 1
44+
3845
# message-body colors - distinct from tool colors (tool calls are magenta,
3946
# tool results dim) so roles never blend into tool activity
4047
USER_STYLE = "cyan"
@@ -1062,6 +1069,24 @@ def _on_mouse_click(self, column: int, row: int) -> None:
10621069
def _status_bar(self) -> Text:
10631070
mode = self._controller.plan_mode.mode.value
10641071
mode_style = "bold yellow" if mode == "plan" else "bold green"
1072+
mode_display = f" [{mode.upper()}]"
1073+
# Active agent profile: the store holds None for the built-in
1074+
# default agent, so "default" is what the bar reports there.
1075+
# It is shown unconditionally — a switch to the default agent
1076+
# (or a restored session) must be visible too, otherwise the
1077+
# bar cannot tell the user which prompt is in effect.
1078+
agent_name = getattr(self._controller.session.store, "agent", None)
1079+
custom_agent = bool(agent_name)
1080+
display_name = str(agent_name or RESERVED_AGENT_NAME)
1081+
# The name is an agent file's frontmatter ``name:`` (or its stem)
1082+
# and is otherwise unvalidated: sanitize it like every other
1083+
# untrusted display path and flatten whitespace, or a name could
1084+
# carry escape sequences (clear the screen, spoof hyperlinks) or
1085+
# newlines that split the pinned bar into unaccounted rows.
1086+
if needs_sanitize(display_name):
1087+
display_name = sanitize_terminal(display_name)
1088+
display_name = " ".join(display_name.split())
1089+
agent_style = "bold magenta" if custom_agent else "dim"
10651090
ratio = self._controller.context_ratio
10661091
ctx = ""
10671092
if ratio is not None:
@@ -1070,8 +1095,20 @@ def _status_bar(self) -> Text:
10701095
filled = round(ratio * 10)
10711096
bar = "▓" * filled + "░" * (10 - filled)
10721097
ctx = f" [Ctx:{bar} {pct}%/{trigger}%]"
1098+
# Budget the prefix so it cannot wrap by itself: the status takes
1099+
# at least _MIN_STATUS_CELLS of line 1, and the bar is at most two
1100+
# lines. On a narrow terminal drop the context gauge first, then
1101+
# shorten the agent name (a long profile name must not push the
1102+
# bar to three rows); the mode tag is never dropped.
1103+
width = self.console.width or 80
1104+
budget = max(1, width - _MIN_STATUS_CELLS)
1105+
name_cells = budget - cell_len(mode_display) - 2 # " @" + one cell left
1106+
agent_display = f" @{_truncate_cells(display_name, name_cells)}" if name_cells > 1 else ""
1107+
if ctx and cell_len(mode_display) + cell_len(agent_display) + cell_len(ctx) > budget:
1108+
ctx = ""
10731109
t = Text()
1074-
t.append(f" [{mode.upper()}]", style=mode_style)
1110+
t.append(mode_display, style=mode_style)
1111+
t.append(agent_display, style=agent_style)
10751112
if ctx:
10761113
over = ratio is not None and ratio >= config.CONTEXT_TRIGGER
10771114
t.append(ctx, style="bold" if over else "")

‎tests/tui/test_tui_commands.py‎

Lines changed: 106 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -1079,6 +1079,34 @@ def test_agent_switch_by_name_success_and_failure(self):
10791079
tui._agent_switch_by_name("nope")
10801080
self.assertIn("no agent", buf.getvalue())
10811081

1082+
def test_agent_switch_reports_agent_switched(self):
1083+
"""A successful switch emits ``agent-switched`` (so the render
1084+
loop wakes and the bar redraws) without touching the idle status
1085+
-- the generic notify branch would turn it into " running"; a
1086+
failed switch emits nothing."""
1087+
tui, _ = make_tui()
1088+
tui._data_event.clear()
1089+
with (
1090+
mock.patch.object(tui, "_on_notify") as notify,
1091+
mock.patch.object(tui.session, "switch_agent", return_value=(True, "ok")),
1092+
):
1093+
tui._agent_switch_by_name("planner")
1094+
notify.assert_called_once_with("agent-switched")
1095+
1096+
tui2, _ = make_tui()
1097+
tui2._data_event.clear()
1098+
tui2.status = " idle"
1099+
tui2._on_notify("agent-switched")
1100+
self.assertEqual(tui2.status, " idle")
1101+
self.assertTrue(tui2._data_event.is_set())
1102+
1103+
with (
1104+
mock.patch.object(tui, "_on_notify") as notify,
1105+
mock.patch.object(tui.session, "switch_agent", return_value=(False, "nope")),
1106+
):
1107+
tui._agent_switch_by_name("planner")
1108+
notify.assert_not_called()
1109+
10821110
def test_agent_command_lists_without_agents(self):
10831111
tui, buf = make_tui()
10841112
with (
@@ -1090,6 +1118,59 @@ def test_agent_command_lists_without_agents(self):
10901118
self.assertIn("Available agent profiles", out)
10911119
self.assertIn("none found", out)
10921120

1121+
def test_agent_command_marks_active_agent(self):
1122+
"""/agent must show which profile is active, both for the
1123+
built-in default (store.agent is None) and a custom agent, and
1124+
the marker must stay on the profile's own line (a long prompt
1125+
path wraps, so an end-of-row marker could be orphaned)."""
1126+
tui, buf = make_tui()
1127+
with (
1128+
mock.patch(
1129+
"python_agent_harness.tui.commands.discover_agents",
1130+
return_value={"planner": "/p/planner.md"},
1131+
),
1132+
mock.patch("builtins.input", return_value=""),
1133+
):
1134+
tui._run_agent_command("")
1135+
lines = buf.getvalue().splitlines()
1136+
default_line = [ln for ln in lines if "default" in ln]
1137+
self.assertEqual(len(default_line), 1)
1138+
self.assertIn("default ← active — agent.md", default_line[0])
1139+
# the other row must be listed without the marker (it is the only
1140+
# other line mentioning "planner", via its own prompt path)
1141+
other = [ln for ln in lines if "planner" in ln]
1142+
self.assertEqual(len(other), 1)
1143+
self.assertIn("2) planner — /p/planner.md", other[0])
1144+
self.assertNotIn("← active", other[0])
1145+
1146+
buf.truncate(0)
1147+
tui.session.store.agent = "planner"
1148+
with (
1149+
mock.patch(
1150+
"python_agent_harness.tui.commands.discover_agents",
1151+
return_value={"planner": "/p/planner.md"},
1152+
),
1153+
mock.patch("builtins.input", return_value=""),
1154+
):
1155+
tui._run_agent_command("")
1156+
lines = buf.getvalue().splitlines()
1157+
planner_line = [ln for ln in lines if "planner" in ln]
1158+
self.assertEqual(len(planner_line), 1)
1159+
self.assertIn("planner ← active — /p/planner.md", planner_line[0])
1160+
self.assertIn("default — agent.md", buf.getvalue())
1161+
1162+
def test_agent_command_warns_when_active_file_vanished(self):
1163+
"""An active agent whose prompt file disappeared is reported
1164+
instead of silently listing nothing as active."""
1165+
tui, buf = make_tui()
1166+
tui.session.store.agent = "gone"
1167+
with (
1168+
mock.patch("python_agent_harness.tui.commands.discover_agents", return_value={}),
1169+
mock.patch("builtins.input", return_value=""),
1170+
):
1171+
tui._run_agent_command("")
1172+
self.assertIn("active agent gone no longer found on disk", buf.getvalue())
1173+
10931174
def test_agent_command_interactive_number(self):
10941175
tui, buf = make_tui()
10951176
with (
@@ -1165,6 +1246,31 @@ def test_agent_command_numeric_and_named_arg(self):
11651246
tui._run_agent_command("planner")
11661247
switch.assert_called_once_with("planner")
11671248

1249+
def test_agent_unicode_digit_selection_not_treated_as_number(self):
1250+
"""'²'.isdigit() is True but int('²') raises ValueError: a
1251+
superscript-digit argument must fall through to the name path
1252+
("unknown agent") instead of crashing the command loop."""
1253+
tui, buf = make_tui()
1254+
with mock.patch("python_agent_harness.tui.commands.discover_agents", return_value={}):
1255+
tui._run_agent_command("²")
1256+
self.assertIn("unknown agent: ²", buf.getvalue())
1257+
buf.truncate(0)
1258+
with (
1259+
mock.patch("python_agent_harness.tui.commands.discover_agents", return_value={}),
1260+
mock.patch("builtins.input", return_value="²"),
1261+
):
1262+
tui._run_agent_command("")
1263+
self.assertIn("unknown agent: ²", buf.getvalue())
1264+
1265+
def test_model_unicode_digit_selection_not_treated_as_number(self):
1266+
"""Same int()/isdigit() mismatch for /model arguments."""
1267+
tui, buf = make_tui()
1268+
with mock.patch(
1269+
"python_agent_harness.tui.commands.config.load_models_config", return_value={}
1270+
):
1271+
tui._run_model_command("²")
1272+
self.assertIn("unknown model: ²", buf.getvalue())
1273+
11681274
# ------------------------------------------------------------------
11691275
# /restore warning paths
11701276
# ------------------------------------------------------------------

‎tests/tui/test_tui_render.py‎

Lines changed: 18 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -117,6 +117,24 @@ def test_status_bar_wraps_long_error_two_lines(self):
117117
self.assertIn("current quota", out)
118118
self.assertNotIn("…", out)
119119

120+
def test_status_bar_shows_active_agent(self):
121+
"""The status bar reports which agent profile is in effect, so a
122+
/agent switch is visible without scrolling back to its message."""
123+
tui, buf = make_tui()
124+
tui.console.print(tui._status_bar())
125+
self.assertIn("@default", buf.getvalue())
126+
buf.truncate(0)
127+
ok, _ = tui._controller.switch_agent("reviewer")
128+
self.assertTrue(ok)
129+
tui.console.print(tui._status_bar())
130+
self.assertIn("@reviewer", buf.getvalue())
131+
buf.truncate(0)
132+
tui._controller.switch_agent("default")
133+
tui.console.print(tui._status_bar())
134+
out = buf.getvalue()
135+
self.assertIn("@default", out)
136+
self.assertNotIn("@reviewer", out)
137+
120138
def test_status_bar_beyond_two_lines_ellipsized(self):
121139
"""Content wider than two lines ends with an ellipsis on line 2."""
122140
tui, buf = make_tui()

‎tests/tui/test_tui_sanitize.py‎

Lines changed: 16 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -255,6 +255,22 @@ def test_status_bar_strips_escapes_from_error_notification(self):
255255
self.assertNotIn("PWNED-TITLE", out)
256256
self.assertIn("Error: 500", out)
257257

258+
def test_status_bar_sanitizes_active_agent_name(self):
259+
"""The active agent name comes from an agent file's frontmatter
260+
(``name:``), which is taken verbatim: it reaches the status bar,
261+
so escapes must be stripped and newlines flattened -- otherwise a
262+
crafted agent file could clear the screen, spoof a hyperlink or
263+
split the pinned bar into rows the layout never reserved."""
264+
tui, _ = make_tui()
265+
tui.session.store.agent = "evil" + HOSTILE + "\nsecond-line"
266+
out = self._status_out(tui)
267+
self.assertNotIn(ESC, out)
268+
self.assertNotIn("\x9b", out)
269+
self.assertNotIn("\r", out)
270+
self.assertNotIn("PWNED-TITLE", out)
271+
self.assertEqual(len(out.rstrip("\n").split("\n")), 1)
272+
self.assertIn("evilbeforeafter second-line", out)
273+
258274

259275
if __name__ == "__main__":
260276
unittest.main()

0 commit comments

Comments
 (0)