From f101a24571b05abef4fe068d81b392615089f2c2 Mon Sep 17 00:00:00 2001 From: chengyongru <61816729+chengyongru@users.noreply.github.com> Date: Fri, 16 Oct 2026 15:34:49 +0800 Subject: [PATCH] refactor(cli): use Questionary for onboarding selection (#6251) * fix(cli): require compatible terminal prompt dependencies Require prompt-toolkit 3.0.52 for Windows VT100 input flushing and Questionary 2.1.1 for compatibility with its prompt layout. Keep the existing major-version bounds and Python minimum. * refactor(cli): use Questionary for onboarding selection Delegate menu navigation, selection and scrolling to questionary.select. Retain the existing back/cancel contract, palette and position feedback through a thin adapter and exercise real prompt keyboard behavior instead of viewport arithmetic. --- nanobot/cli/onboard.py | 137 +++++++++--------------------- pyproject.toml | 4 +- tests/agent/test_onboard_logic.py | 84 +++++++++++++----- 3 files changed, 104 insertions(+), 121 deletions(-) diff --git a/nanobot/cli/onboard.py b/nanobot/cli/onboard.py index 1f9ae263b..07aa7fada 100644 --- a/nanobot/cli/onboard.py +++ b/nanobot/cli/onboard.py @@ -153,120 +153,61 @@ def _select_with_back( The selected choice string if user confirmed None if user cancelled (Ctrl+C) """ - import shutil - - from prompt_toolkit.application import Application - from prompt_toolkit.keys import Keys - from prompt_toolkit.layout import Layout - from prompt_toolkit.layout.containers import HSplit, Window + from prompt_toolkit.key_binding import merge_key_bindings + from prompt_toolkit.layout.containers import Window from prompt_toolkit.layout.controls import FormattedTextControl - from prompt_toolkit.styles import Style - # Validate choices if not choices: logger.warning("Empty choices list provided to _select_with_back") return None - # Find default index - selected_index = 0 - if default and default in choices: - selected_index = choices.index(default) + bindings = _input_back_key_bindings() - # State holder for the result - state: dict[str, str | None | object] = {"result": None} - terminal_lines = shutil.get_terminal_size((80, 24)).lines - visible_count = min(len(choices), max(1, terminal_lines - 3)) - - # Build menu items (uses closure over selected_index) - def get_menu_text() -> list[tuple[str, str]]: - items: list[tuple[str, str]] = [] - start, end = _choice_viewport(selected_index, len(choices), visible_count) - for i in range(start, end): - choice = choices[i] - if i == selected_index: - items.append(("class:selected", f"> {choice}\n")) - else: - items.append(("", f" {choice}\n")) - return items - - # Create layout - menu_control = FormattedTextControl(cast(Any, get_menu_text), show_cursor=False) - menu_window = Window(content=menu_control, height=visible_count, always_hide_cursor=True) - - def get_prompt_text() -> list[tuple[str, str]]: - suffix = f" ({selected_index + 1}/{len(choices)})" if len(choices) > visible_count else "" - return [("class:question", f"{prompt}{suffix}")] - - prompt_control = FormattedTextControl(cast(Any, get_prompt_text), show_cursor=False) - prompt_window = Window(content=prompt_control, height=1, always_hide_cursor=True) - - layout = Layout(HSplit([prompt_window, menu_window])) - - # Key bindings - bindings = KeyBindings() - - # KeyBindings consumes these handlers through decorator registration. - @bindings.add(Keys.Up) - def _up(event: KeyPressEvent) -> None: # pyright: ignore[reportUnusedFunction] - nonlocal selected_index - selected_index = (selected_index - 1) % len(choices) - event.app.invalidate() - - @bindings.add(Keys.Down) - def _down(event: KeyPressEvent) -> None: # pyright: ignore[reportUnusedFunction] - nonlocal selected_index - selected_index = (selected_index + 1) % len(choices) - event.app.invalidate() - - @bindings.add(Keys.Enter) - def _enter(event: KeyPressEvent) -> None: # pyright: ignore[reportUnusedFunction] - state["result"] = choices[selected_index] - event.app.exit() - - @bindings.add("escape") - def _escape(event: KeyPressEvent) -> None: # pyright: ignore[reportUnusedFunction] - state["result"] = _BACK_PRESSED - event.app.exit() - - @bindings.add(Keys.Left) + @bindings.add("left") def _left(event: KeyPressEvent) -> None: # pyright: ignore[reportUnusedFunction] - state["result"] = _BACK_PRESSED - event.app.exit() + event.app.exit(result=_BACK_PRESSED) - @bindings.add(Keys.ControlC) - def _ctrl_c(event: KeyPressEvent) -> None: # pyright: ignore[reportUnusedFunction] - state["result"] = None - event.app.exit() + @bindings.add("c-c", eager=True) + def _cancel(event: KeyPressEvent) -> None: # pyright: ignore[reportUnusedFunction] + event.app.exit(result=None) - # Style - style = Style.from_dict({ - "selected": f"fg:{_UI_ACCENT} bold", - "question": f"fg:{_UI_TEXT}", - }) + q = _get_questionary() + from questionary.prompts.common import InquirerControl - app = Application[object](layout=layout, key_bindings=bindings, style=style) - app.ttimeoutlen = 0.05 - app.timeoutlen = 0.05 + question = q.select( + prompt, + choices=choices, + default=default if default in choices else choices[0], + qmark="", + pointer=">", + instruction=" ", + use_jk_keys=False, + use_emacs_keys=False, + style=q.Style([ + ("question", f"fg:{_UI_TEXT} nobold"), + ("pointer", f"fg:{_UI_ACCENT} bold"), + ("highlighted", f"fg:{_UI_ACCENT} bold noreverse"), + ("selected", f"fg:{_UI_ACCENT} bold noreverse"), + ("answer", f"fg:{_UI_ACCENT} bold"), + ]), + ) + control = next( + c for c in question.application.layout.find_all_controls() if isinstance(c, InquirerControl) + ) + question.application.layout.container.children.insert(1, Window( + FormattedTextControl(lambda: f"({control.pointed_at + 1}/{len(choices)})"), + height=1, + style=f"fg:{_UI_TEXT}", + )) + question.application.key_bindings = merge_key_bindings([ + question.application.key_bindings, bindings, + ]) try: - app.run() + return _ask_prompt(question) except Exception: logger.exception("Error in select prompt") return None - return state["result"] - - -def _choice_viewport(selected_index: int, total: int, visible_count: int) -> tuple[int, int]: - """Return the visible slice for a long terminal menu.""" - if total <= 0: - return 0, 0 - visible_count = max(1, min(visible_count, total)) - selected_index = max(0, min(selected_index, total - 1)) - half = visible_count // 2 - start = selected_index - half - start = max(0, min(start, total - visible_count)) - return start, start + visible_count - # --- Type Introspection --- diff --git a/pyproject.toml b/pyproject.toml index 1e11fd46a..2019e43a8 100644 --- a/pyproject.toml +++ b/pyproject.toml @@ -42,9 +42,9 @@ dependencies = [ "qrcode[pil]>=8.0", "pillow>=11.0,<13.0", "croniter>=6.0.0,<7.0.0", - "prompt-toolkit>=3.0.50,<4.0.0", + "prompt-toolkit>=3.0.52,<4.0.0", "setproctitle>=1.3.7,<2.0.0; sys_platform != 'win32'", - "questionary>=2.0.0,<3.0.0", + "questionary>=2.1.1,<3.0.0", "mcp>=1.26.0,<2.0.0", "json-repair>=0.57.0,<1.0.0", "chardet>=3.0.2,<6.0.0", diff --git a/tests/agent/test_onboard_logic.py b/tests/agent/test_onboard_logic.py index 7a027158e..cd7d71052 100644 --- a/tests/agent/test_onboard_logic.py +++ b/tests/agent/test_onboard_logic.py @@ -1,14 +1,13 @@ -"""Unit tests for onboard core logic functions. - -These tests focus on the business logic behind the onboard wizard, -without testing the interactive UI components. -""" +"""Tests for onboard logic and prompt keyboard behavior.""" from pathlib import Path from types import SimpleNamespace from typing import Any, cast import pytest +from prompt_toolkit.application import create_app_session +from prompt_toolkit.input import create_pipe_input +from prompt_toolkit.output import DummyOutput from pydantic import BaseModel, Field from nanobot.cli import onboard as onboard_wizard @@ -850,25 +849,68 @@ class TestApiServerRegistration: assert config.api.api_key == "secret" +@pytest.fixture +def prompt_input(): + with create_pipe_input() as pipe: + with create_app_session(input=pipe, output=DummyOutput()): + yield pipe + + +class TestSelectWithBack: + def test_empty_choices_cancel(self): + assert onboard_wizard._select_with_back("Choose", []) is None + + @pytest.mark.parametrize( + "default, keys, expected", + [ + pytest.param(None, "\r", "one", id="first-by-default"), + pytest.param("two", "\r", "two", id="confirm-default"), + pytest.param("missing", "\r", "one", id="invalid-default"), + pytest.param("one", "\x1b[A\r", "three", id="up-wraps"), + pytest.param("three", "\x1b[B\r", "one", id="down-wraps"), + pytest.param(None, "\x1b", _BACK_PRESSED, id="escape-goes-back"), + pytest.param(None, "\x1b[D", _BACK_PRESSED, id="left-goes-back"), + pytest.param(None, "\x03", None, id="ctrl-c-cancels"), + ], + ) + def test_keyboard_navigation(self, prompt_input, default, keys, expected): + prompt_input.send_text(keys) + + result = onboard_wizard._select_with_back("Choose", ["one", "two", "three"], default) + + assert result == expected + + @pytest.mark.parametrize("index", range(40)) + def test_every_long_menu_choice_is_reachable(self, prompt_input, index): + choices = [f"Provider {i}" for i in range(40)] + prompt_input.send_text("\x1b[B" * index + "\r") + + assert onboard_wizard._select_with_back("Provider", choices) == f"Provider {index}" + + @pytest.mark.parametrize("exit_key", ["\x1b", "\x1b[D", "\x03"]) + def test_section_keyboard_exit_preserves_back_vs_cancel(self, monkeypatch, prompt_input, exit_key): + model = _SimpleDraftModel() + answers = iter(["\r", "draft-key\r", exit_key]) + ask_prompt = onboard_wizard._ask_prompt + + def ask_with_input(prompt): + prompt_input.send_text(next(answers)) + return ask_prompt(prompt) + + monkeypatch.setattr(onboard_wizard, "_ask_prompt", ask_with_input) + + updated = _configure_pydantic_model(model, "Draft") + + if exit_key == "\x03": + assert updated is None + else: + assert updated.api_key == "draft-key" + assert model.api_key == "" + + class TestMainMenuInteraction: """Main menu navigation, save actions, and terminal input behavior.""" - def test_choice_viewport_keeps_long_menus_within_terminal_height(self): - """Long provider menus should render as a bounded scrolling slice.""" - assert onboard_wizard._choice_viewport(selected_index=0, total=20, visible_count=5) == (0, 5) - assert onboard_wizard._choice_viewport(selected_index=10, total=20, visible_count=5) == ( - 8, - 13, - ) - assert onboard_wizard._choice_viewport(selected_index=19, total=20, visible_count=5) == ( - 15, - 20, - ) - - def test_choice_viewport_handles_tiny_terminals(self): - """A one-row menu is still usable instead of failing as window-too-small.""" - assert onboard_wizard._choice_viewport(selected_index=3, total=5, visible_count=0) == (3, 4) - def test_main_menu_hides_save_actions_until_needed(self): """The first screen should not show save or summary actions before edits.""" from nanobot.cli.onboard import _get_main_menu_choices