Skip to content

Framework for orchestrating role-playing, autonomous AI agents. By fostering collaborative intelligence, CrewAI empowers agents to work together seamlessly, tackling complex tasks.

Filter platform actions while selecting them (#7991)

Vidit Ostwal3da2d4e9932b
diff --git a/lib/cli/src/crewai_cli/create_json_crew.py b/lib/cli/src/crewai_cli/create_json_crew.py
index 8346a9928..13503454b 100644
--- a/lib/cli/src/crewai_cli/create_json_crew.py
+++ b/lib/cli/src/crewai_cli/create_json_crew.py
@@ -549,6 +549,7 @@ def _select_platform_actions(selected_tools: list[str]) -> list[str]:
action_indices = pick_many(
f"{PLATFORM_APP_DISPLAY_NAMES[app]} actions for this agent (space to toggle):",
[f"{item.display_name} ({item.slug})" for item in app_tools],
+ searchable=True,
preselected={
index
for index, item in enumerate(app_tools)
diff --git a/lib/cli/src/crewai_cli/tui_picker.py b/lib/cli/src/crewai_cli/tui_picker.py
index a06fd18bd..9ac7d4f86 100644
--- a/lib/cli/src/crewai_cli/tui_picker.py
+++ b/lib/cli/src/crewai_cli/tui_picker.py
@@ -15,6 +15,7 @@ _CORAL = "\033[38;2;255;90;80m" # #FF5A50
_TEAL = "\033[38;2;31;121;130m" # #1F7982
_BOLD = "\033[1m"
_DIM = "\033[2m"
+_GREEN = "\033[1;32m"
_RESET = "\033[0m"
_HIDE_CURSOR = "\033[?25l"
_SHOW_CURSOR = "\033[?25h"
@@ -98,20 +99,45 @@ def _draw_multi(
separator_indices: set[int] | None = None,
clear: bool = False,
previous_line_count: int | None = None,
+ row_indices: list[int] | None = None,
+ query: str = "",
+ searchable: bool = False,
) -> int:
action_indices = action_indices or set()
separator_indices = separator_indices or set()
- start, end = _visible_row_range(len(labels), cursor)
+ rows = row_indices if row_indices is not None else list(range(len(labels)))
+ try:
+ cursor_pos = rows.index(cursor)
+ except ValueError:
+ cursor_pos = 0
+ start, end = _visible_row_range(len(rows), cursor_pos)
hint_text = "↑↓ navigate, space toggle, enter confirm"
if action_indices:
hint_text = "↑↓ navigate, space toggle, enter confirm, ▸ rows expand/collapse"
- if end - start < len(labels):
- hint_text += f" · showing {start + 1}-{end} of {len(labels)}"
+ if searchable:
+ hint_text += " · type to filter"
+ if end - start < len(rows):
+ hint_text += f" · showing {start + 1}-{end} of {len(rows)}"
hint = f" {_DIM}{hint_text}{_RESET}"
if clear:
- sys.stdout.write(f"\033[{previous_line_count or 1}A")
+ # Erase the previous block first. A shorter search result would
+ # otherwise leave the old rows visible underneath the matches.
+ _clear_lines(previous_line_count or 1)
+ extra_lines = 0
sys.stdout.write(f"\033[2K{hint}\n")
- for i in range(start, end):
+ if searchable:
+ match_count = ""
+ if query:
+ count = len(rows)
+ noun = "match" if count == 1 else "matches"
+ match_count = f" · {count} {noun}"
+ sys.stdout.write(f"\033[2K {_GREEN}Search: {query}{match_count}{_RESET}\n")
+ extra_lines += 1
+ if searchable and query and not rows:
+ sys.stdout.write(f"\033[2K {_DIM}No matching actions{_RESET}\n")
+ extra_lines += 1
+ for pos in range(start, end):
+ i = rows[pos]
label = labels[i]
if i in separator_indices:
sys.stdout.write(f"\033[2K {_TEAL}{label}{_RESET}\n")
@@ -126,7 +152,7 @@ def _draw_multi(
bold = f"{_BOLD}{label}{_RESET}" if i == cursor else label
sys.stdout.write(f"\033[2K {arrow}{check} {bold}\n")
sys.stdout.flush()
- return end - start + 1
+ return end - start + 1 + extra_lines
def _visible_row_range(total: int, cursor: int) -> tuple[int, int]:
@@ -165,6 +191,64 @@ def _arrow_select_one(labels: list[str]) -> int:
sys.stdout.flush()
+def _is_search_character(key: str) -> bool:
+ return len(key) == 1 and key.isprintable() and key != " "
+
+
+def _visible_label_indices(
+ labels: list[str],
+ query: str,
+ separator_indices: set[int],
+ *,
+ searchable: bool,
+) -> list[int]:
+ if not searchable or not query:
+ return list(range(len(labels)))
+ return [
+ index
+ for index in matching_label_indices(labels, query)
+ if index not in separator_indices
+ ]
+
+
+def _cursor_on_visible(
+ cursor: int,
+ labels: list[str],
+ query: str,
+ separator_indices: set[int],
+ searchable: bool,
+) -> int:
+ visible = _visible_label_indices(
+ labels, query, separator_indices, searchable=searchable
+ )
+ if cursor in visible or not visible:
+ return cursor
+ return visible[0]
+
+
+def _move_visible_cursor(
+ cursor: int,
+ direction: int,
+ labels: list[str],
+ query: str,
+ separator_indices: set[int],
+ searchable: bool,
+) -> int:
+ visible = [
+ index
+ for index in _visible_label_indices(
+ labels, query, separator_indices, searchable=searchable
+ )
+ if index not in separator_indices
+ ]
+ if cursor not in visible:
+ return visible[0] if visible else cursor
+ position = visible.index(cursor) + direction
+ if 0 <= position < len(visible):
+ return visible[position]
+ return cursor
+
+
def _arrow_select_multi(
labels: list[str],
*,
@@ -172,71 +256,82 @@ def _arrow_select_multi(
separator_indices: set[int] | None = None,
preselected: set[int] | None = None,
initial_cursor: int | None = None,
+ searchable: bool = False,
) -> tuple[list[int], int | None]:
total = len(labels)
selected: set[int] = set(preselected or ())
action_indices = action_indices or set()
separator_indices = separator_indices or set()
+ query = ""
if initial_cursor is not None and 0 <= initial_cursor < total:
cursor = initial_cursor
else:
cursor = _first_selectable_index(total, separator_indices)
sys.stdout.write(_HIDE_CURSOR)
sys.stdout.flush()
- try:
- rendered_lines = _draw_multi(
+
+ def redraw(clear: bool) -> int:
+ return _draw_multi(
labels,
cursor,
selected,
action_indices=action_indices,
separator_indices=separator_indices,
+ clear=clear,
+ previous_line_count=rendered_lines if clear else None,
+ row_indices=_visible_label_indices(
+ labels, query, separator_indices, searchable=searchable
+ ),
+ query=query,
+ searchable=searchable,
)
+
+ try:
+ rendered_lines = redraw(False)
while True:
key = _read_key()
if key == "up":
- cursor = _next_selectable_index(cursor, -1, total, separator_indices)
- rendered_lines = _draw_multi(
- labels,
- cursor,
- selected,
- action_indices=action_indices,
- separator_indices=separator_indices,
- clear=True,
- previous_line_count=rendered_lines,
+ cursor = _move_visible_cursor(
+ cursor, -1, labels, query, separator_indices, searchable
)
elif key == "down":
- cursor = _next_selectable_index(cursor, 1, total, separator_indices)
- rendered_lines = _draw_multi(
- labels,
- cursor,
- selected,
- action_indices=action_indices,
- separator_indices=separator_indices,
- clear=True,
- previous_line_count=rendered_lines,
+ cursor = _move_visible_cursor(
+ cursor, 1, labels, query, separator_indices, searchable
)
elif key == "space":
if cursor in action_indices:
_clear_lines(rendered_lines)
return sorted(selected), cursor
- selected ^= {cursor}
- rendered_lines = _draw_multi(
- labels,
- cursor,
- selected,
- action_indices=action_indices,
- separator_indices=separator_indices,
- clear=True,
- previous_line_count=rendered_lines,
- )
+ if cursor in _visible_label_indices(
+ labels, query, separator_indices, searchable=searchable
+ ):
+ selected ^= {cursor}
elif key == "enter":
_clear_lines(rendered_lines)
if cursor in action_indices:
return sorted(selected), cursor
return sorted(selected), None
+ elif searchable and key in ("\x7f", "\b") and query:
+ query = query[:-1]
+ cursor = _cursor_on_visible(
+ cursor, labels, query, separator_indices, searchable
+ )
+ elif searchable and key == "esc" and query:
+ query = ""
+ cursor = _cursor_on_visible(
+ cursor, labels, query, separator_indices, searchable
+ )
+ elif searchable and _is_search_character(key):
+ query += key
+ cursor = _cursor_on_visible(
+ cursor, labels, query, separator_indices, searchable
+ )
elif key in ("esc", "q"):
_clear_lines(rendered_lines)
return sorted(selected), None
+ else:
+ continue
+ rendered_lines = redraw(True)
finally:
sys.stdout.write(_SHOW_CURSOR)
sys.stdout.flush()
@@ -266,11 +361,21 @@ def _numbered_select_multi(
action_indices: set[int] | None = None,
separator_indices: set[int] | None = None,
preselected: set[int] | None = None,
+ searchable: bool = False,
) -> tuple[list[int], int | None]:
action_indices = action_indices or set()
separator_indices = separator_indices or set()
+ query = ""
+ if searchable:
+ query = str(click.prompt(" Filter", default="", show_default=False)).strip()
+ visible = _visible_label_indices(
+ labels, query, separator_indices, searchable=searchable
+ )
numbered_indices: list[int] = []
- for idx, label in enumerate(labels):
+ if searchable and query and not visible:
+ click.echo(" No matching actions")
+ for idx in visible:
+ label = labels[idx]
if idx in separator_indices:
click.secho(f" {label}", fg="cyan")
continue
@@ -317,6 +422,18 @@ def _next_selectable_index(
return cursor
+def matching_label_indices(labels: list[str], query: str) -> list[int]:
+ """Original indexes whose label contains ``query``, ignoring case.
+
+ An empty query matches every label. The returned indexes stay in label
+ order so a filtered view can keep the selection tied to the full list.
+ """
+ needle = query.casefold()
+ if not needle:
+ return list(range(len(labels)))
+ return [index for index, label in enumerate(labels) if needle in label.casefold()]
+
+
# ── Public API ──────────────────────────────────────────────────
@@ -377,6 +494,7 @@ def pick_many(
separator_indices: set[int] | None = None,
preselected: set[int] | None = None,
initial_cursor: int | None = None,
+ searchable: bool = False,
) -> list[int]: ...
@@ -389,6 +507,7 @@ def pick_many(
separator_indices: set[int] | None = None,
preselected: set[int] | None = None,
initial_cursor: int | None = None,
+ searchable: bool = False,
) -> tuple[list[int], int | None]: ...
@@ -400,9 +519,13 @@ def pick_many(
separator_indices: set[int] | None = None,
preselected: set[int] | None = None,
initial_cursor: int | None = None,
+ searchable: bool = False,
) -> list[int] | tuple[list[int], int | None]:
"""Arrow-key multi-select with checkboxes.
+ ``searchable`` lets the user type a query. Matching rows stay tied to
+ their original indexes, and checked rows stay checked when filtered out.
+
Returns:
Sorted list of selected indices, or ``(indices, action_index)`` when
``action_indices`` is provided.
@@ -419,6 +542,7 @@ def pick_many(
separator_indices=separator_indices,
preselected=preselected,
initial_cursor=initial_cursor,
+ searchable=searchable,
)
except Exception:
selected, action = _numbered_select_multi(
@@ -426,6 +550,7 @@ def pick_many(
action_indices=action_indices,
separator_indices=separator_indices,
preselected=preselected,
+ searchable=searchable,
)
else:
selected, action = _numbered_select_multi(
@@ -433,6 +558,7 @@ def pick_many(
action_indices=action_indices,
separator_indices=separator_indices,
preselected=preselected,
+ searchable=searchable,
)
if action_indices is None:
return selected
diff --git a/lib/cli/tests/test_create_crew.py b/lib/cli/tests/test_create_crew.py
index e26d7ef63..8e419a2e6 100644
--- a/lib/cli/tests/test_create_crew.py
+++ b/lib/cli/tests/test_create_crew.py
@@ -488,6 +488,19 @@ def test_json_wizard_tool_picker_prioritizes_common_tools(monkeypatch):
assert "More tools" not in labels
+def test_platform_action_picker_is_searchable(monkeypatch):
+ picker_calls: list[dict[str, object]] = []
+
+ def pick_many(title: str, labels: list[str], **kwargs):
+ picker_calls.append(kwargs)
+ return []
+
+ monkeypatch.setattr(json_crew, "pick_many", pick_many)
+
+ assert json_crew._select_platform_actions(["platform:github"]) == []
+ assert picker_calls[0]["searchable"] is True
+
+
def test_json_wizard_tool_picker_collapses_categories_by_default(monkeypatch):
picker_calls: list[tuple[str, list[str], dict[str, object]]] = []
diff --git a/lib/cli/tests/test_tui_picker.py b/lib/cli/tests/test_tui_picker.py
index fea21a53d..a381ec771 100644
--- a/lib/cli/tests/test_tui_picker.py
+++ b/lib/cli/tests/test_tui_picker.py
@@ -48,3 +48,107 @@ def test_draw_multi_renders_only_the_visible_window(monkeypatch) -> None:
assert "Tool 65" in rendered
assert "Tool 0" not in rendered
assert "Tool 124" not in rendered
+
+
+def test_search_redraw_shows_only_matching_rows(monkeypatch) -> None:
+ output = StringIO()
+ monkeypatch.setattr(tui_picker.sys, "stdout", output)
+
+ tui_picker._draw_multi(
+ ["Send an email (send-email)", "Create email draft (create_draft)"],
+ cursor=1,
+ selected=set(),
+ row_indices=[1],
+ query="draft",
+ searchable=True,
+ clear=True,
+ previous_line_count=6,
+ )
+
+ rendered = output.getvalue()
+ assert "Create email draft" in rendered
+ assert "1 match" in rendered
+ assert "Send an email" not in rendered
+ assert rendered.count("\033[2K") >= 6
+
+
+def test_searchable_draw_shows_the_query_and_an_empty_match(monkeypatch) -> None:
+ output = StringIO()
+ monkeypatch.setattr(tui_picker.sys, "stdout", output)
+
+ tui_picker._draw_multi(
+ ["Send an email (send-email)"],
+ cursor=0,
+ selected={0},
+ row_indices=[],
+ query="missing",
+ searchable=True,
+ )
+
+ rendered = output.getvalue()
+ assert "Search:" in rendered
+ assert "missing" in rendered
+ assert "type to filter" in rendered
+ assert "No matching actions" in rendered
+ assert "0 matches" in rendered
+ assert "Send an email" not in rendered
+
+
+def test_numbered_search_keeps_original_indexes(monkeypatch) -> None:
+ prompts = iter(["draft", "1"])
+ monkeypatch.setattr(
+ tui_picker.click, "prompt", lambda *_args, **_kwargs: next(prompts)
+ )
+
+ selected, action = tui_picker._numbered_select_multi(
+ [
+ "Send an email (send-email)",
+ "Create email draft (create_draft)",
+ "Search emails (search-emails)",
+ ],
+ preselected={0},
+ searchable=True,
+ )
+
+ assert selected == [0, 1]
+ assert action is None
+
+
+def test_searchable_picker_keeps_preselected_rows_while_filtering(monkeypatch) -> None:
+ keys = iter(["d", "r", "a", "f", "t", "space", "enter"])
+ monkeypatch.setattr(tui_picker, "_read_key", lambda: next(keys))
+ monkeypatch.setattr(tui_picker, "_clear_lines", lambda *_args, **_kwargs: None)
+ labels = [
+ "Send an email (send-email)",
+ "Create email draft (create_draft)",
+ "Search emails (search-emails)",
+ ]
+
+ assert tui_picker._arrow_select_multi(
+ labels, preselected={0}, searchable=True
+ ) == ([0, 1], None)
+
+
+def test_searchable_picker_clears_the_query_on_escape(monkeypatch) -> None:
+ keys = iter(["f", "esc", "up", "space", "enter"])
+ monkeypatch.setattr(tui_picker, "_read_key", lambda: next(keys))
+ monkeypatch.setattr(tui_picker, "_clear_lines", lambda *_args, **_kwargs: None)
+
+ assert tui_picker._arrow_select_multi(
+ ["Send an email (send-email)", "Create email draft (create_draft)"],
+ searchable=True,
+ ) == ([0], None)
+
+
+def test_matching_label_indices_keeps_original_positions() -> None:
+ labels = [
+ "Send an email (send-email)",
+ "Create email draft (create_draft)",
+ "Search emails (search-emails)",
+ ]
+
+ assert tui_picker.matching_label_indices(labels, "") == [0, 1, 2]
+ assert tui_picker.matching_label_indices(labels, "EMAIL") == [0, 1, 2]
+ assert tui_picker.matching_label_indices(labels, "draft") == [1]
+ assert tui_picker.matching_label_indices(labels, "search-emails") == [2]
+ assert tui_picker.matching_label_indices(labels, "missing") == []