Skip to content

The agent that grows with you

fix(cli): validate every /queue index before int()

unsupportedpastelsd5d7f2c38717
diff --git a/hermes_cli/cli_loops_mixin.py b/hermes_cli/cli_loops_mixin.py
index 7b7a6838b77..7f536ad3e2f 100644
--- a/hermes_cli/cli_loops_mixin.py
+++ b/hermes_cli/cli_loops_mixin.py
@@ -26,8 +26,25 @@ def _queue_usage() -> str:
return t("cli.queue.usage")
+def _parse_queue_index(token: str) -> int | None:
+ """1-based queue index from one whitespace-free token, or None when it isn't one.
+
+ ``str.isdigit()`` alone is not enough: it accepts characters ``int()`` rejects
+ (``²``, ``②``), and ``int()`` also refuses digit strings past Python's
+ conversion limit. A ValueError here would escape the slash handler and take
+ down the prompt_toolkit app, so every queue index goes through this.
+ """
+ if not token.isdigit():
+ return None
+ try:
+ return int(token)
+ except ValueError:
+ return None
+
+
# management verb -> (handler, takes a leading item index). Verbs without an index are
-# only management when they stand alone; index verbs only when a number follows.
+# only management when they stand alone; index verbs when a number follows or when the
+# verb stands alone (the handler then prints its usage line).
_QUEUE_VERBS: dict[str, tuple[str, bool]] = {
"list": ("_queue_list", False), "ls": ("_queue_list", False), "show": ("_queue_list", False),
"clear": ("_queue_clear", False),
@@ -349,16 +366,11 @@ class CLILoopsMixin:
def _queue_remove(self, rest: str) -> None:
from cli import _cprint
- # ``_cmd_queue`` routes a bare ``/queue rm`` here as management (its
- # ``not rest`` fallback), and an index verb with trailing words
- # (``rm 2 extra``) as management too, so ``rest`` is not always a bare
- # integer. Parse the leading token instead of trusting the whole string,
- # or int() raises out of the slash handler and kills the TUI.
bits = rest.split()
- if len(bits) != 1 or not bits[0].isdigit():
+ idx = _parse_queue_index(bits[0]) if len(bits) == 1 else None
+ if idx is None:
_cprint(f" {t('cli.queue.usage_remove')}")
return
- idx = int(bits[0])
removed: list = []
before, _ = self._mutate_pending_input(
lambda items: (removed.append(items.pop(idx - 1)) or items) if 1 <= idx <= len(items) else items)
@@ -369,11 +381,14 @@ class CLILoopsMixin:
def _queue_edit(self, rest: str) -> None:
from cli import _VoiceInputMessage, _cprint
- idx_text, _, new_prompt = rest.partition(" ")
- if not new_prompt.strip():
+ # Split on any whitespace, like ``_cmd_queue``'s routing check, so
+ # ``edit 1<TAB>text`` doesn't leave "1\ttext" as the index token.
+ bits = rest.split(None, 1)
+ idx = _parse_queue_index(bits[0]) if len(bits) == 2 else None
+ if idx is None:
_cprint(f" {t('cli.queue.usage_edit')}")
return
- idx = int(idx_text)
+ new_prompt = bits[1]
new_text = self._expand_paste_references(new_prompt.strip())
def _edit(items: list) -> list:
@@ -393,10 +408,10 @@ class CLILoopsMixin:
def _queue_move(self, rest: str) -> None:
from cli import _cprint
bits = rest.split()
- if len(bits) != 2 or not bits[1].isdigit():
+ src, dst = (_parse_queue_index(b) for b in bits) if len(bits) == 2 else (None, None)
+ if src is None or dst is None:
_cprint(f" {t('cli.queue.usage_move')}")
return
- src, dst = int(bits[0]), int(bits[1])
def _move(items: list) -> list:
if 1 <= src <= len(items) and 1 <= dst <= len(items):
diff --git a/locales/es.yaml b/locales/es.yaml
index 8d5ca9268d0..7e6af331028 100644
--- a/locales/es.yaml
+++ b/locales/es.yaml
@@ -2355,7 +2355,7 @@ cli:
removed: "Se eliminó el elemento {index} de la cola: {preview}"
item_not_found: "No se encontró el elemento {index} de la cola. Tamaño actual: {size}"
usage_edit: "Uso: /queue edit <número> <nuevo prompt>"
- usage_remove: "Uso: /queue rm <number>"
+ usage_remove: "Uso: /queue rm <número>"
updated: "Se actualizó el elemento {index} de la cola: {preview}"
usage_move: "Uso: /queue move <desde> <hasta>"
move_out_of_range: "Movimiento fuera de rango en la cola. Tamaño actual: {size}"
diff --git a/locales/pt.yaml b/locales/pt.yaml
index 8cef4f434d3..e3558d7232f 100644
--- a/locales/pt.yaml
+++ b/locales/pt.yaml
@@ -2355,7 +2355,7 @@ cli:
removed: "Item {index} removido da fila: {preview}"
item_not_found: "Item {index} da fila não encontrado. Tamanho atual: {size}"
usage_edit: "Uso: /queue edit <número> <novo prompt>"
- usage_remove: "Uso: /queue rm <number>"
+ usage_remove: "Uso: /queue rm <número>"
updated: "Item {index} da fila atualizado: {preview}"
usage_move: "Uso: /queue move <origem> <destino>"
move_out_of_range: "Movimento na fila fora do intervalo. Tamanho atual: {size}"
diff --git a/locales/ru.yaml b/locales/ru.yaml
index bf680543477..60923900e63 100644
--- a/locales/ru.yaml
+++ b/locales/ru.yaml
@@ -2355,7 +2355,7 @@ cli:
removed: "Удалён элемент очереди {index}: {preview}"
item_not_found: "Элемент очереди {index} не найден. Текущий размер: {size}"
usage_edit: "Использование: /queue edit <номер> <новый промпт>"
- usage_remove: "Использование: /queue rm <number>"
+ usage_remove: "Использование: /queue rm <номер>"
updated: "Обновлён элемент очереди {index}: {preview}"
usage_move: "Использование: /queue move <откуда> <куда>"
move_out_of_range: "Перемещение выходит за границы очереди. Текущий размер: {size}"
diff --git a/tests/hermes_cli/test_cli_init.py b/tests/hermes_cli/test_cli_init.py
index b2bb3cb58ad..96eb002d983 100644
--- a/tests/hermes_cli/test_cli_init.py
+++ b/tests/hermes_cli/test_cli_init.py
@@ -168,22 +168,33 @@ class TestBusyInputMode:
cli.process_command("/queue move 1 9")
assert cli._pending_input_items() == ["only item"]
- def test_queue_rm_without_index_prints_usage_instead_of_raising(self):
- """``/queue rm`` with no index reaches _queue_remove with rest="" and used to
- raise ValueError out of the prompt_toolkit key handler, killing the TUI."""
+ @pytest.mark.parametrize("command, usage_key", [
+ ("/queue rm", "cli.queue.usage_remove"),
+ ("/queue rm 1 extra", "cli.queue.usage_remove"),
+ ("/queue rm \u2461", "cli.queue.usage_remove"), # ② : isdigit() but not int()
+ ("/queue rm " + "9" * 5000, "cli.queue.usage_remove"), # past int()'s digit limit
+ ("/queue edit \u00b2 new text", "cli.queue.usage_edit"), # ²
+ ("/queue move \u2466 1", "cli.queue.usage_move"), # ⑦
+ ("/queue move 1 \u2466", "cli.queue.usage_move"),
+ ], ids=["rm-bare", "rm-trailing-words", "rm-circled-digit", "rm-over-int-limit",
+ "edit-superscript", "move-src-circled", "move-dst-circled"])
+ def test_queue_malformed_index_prints_usage_instead_of_raising(self, command, usage_key):
+ """A bad index used to raise ValueError out of the slash handler, which
+ escapes the prompt_toolkit key handler and kills the TUI."""
cli = _make_cli()
- cli.process_command("/queue first prompt")
- cli.process_command("/queue rm")
+ import cli as _cli_mod
+ printed = []
+ with patch.object(_cli_mod, "_cprint", side_effect=lambda s, *a, **k: printed.append(s)):
+ cli.process_command("/queue first prompt")
+ cli.process_command(command)
assert cli._pending_input_items() == ["first prompt"]
+ assert printed[-1].strip() == t(usage_key)
- def test_queue_rm_with_trailing_words_prints_usage_instead_of_raising(self):
- """``rest`` is only known to start with a digit, so "2 extra" reached int()."""
+ def test_queue_edit_accepts_tab_after_index(self):
cli = _make_cli()
cli.process_command("/queue first prompt")
- cli.process_command("/queue rm 1 extra")
- assert cli._pending_input_items() == ["first prompt"]
-
-
+ cli.process_command("/queue edit 1\treplacement")
+ assert cli._pending_input_items() == ["replacement"]
def test_interrupt_mode_routes_busy_enter_to_interrupt(self):