Skip to content

Dodaios is an open-source agent OS for your desktop: it runs your coding agents, browser and apps by voice or chat, on your own machine. Formerly Personal Jarvis.

fix(chat): rank Add picker by name prefix

rubenluetke10-beepf9990272cf09
diff --git a/jarvis/agent_chat/tool_catalog.py b/jarvis/agent_chat/tool_catalog.py
index 24ceb0da1e..61e03e0b9b 100644
--- a/jarvis/agent_chat/tool_catalog.py
+++ b/jarvis/agent_chat/tool_catalog.py
@@ -1,7 +1,10 @@
-"""Read-only composer inventory and tool-free semantic discovery.
+"""Read-only composer inventory and keyword discovery for the Add menu.
Selections name existing runtime tools; they never grant permissions or install
anything. Catalog descriptions and search queries are data, never instructions.
+The Add picker matches names, not meaning: a letter like ``g`` lists Gmail
+ahead of later alphabet hits. Semantic ranking stays available for callers that
+pass a ranker; the Add route never does.
"""
from __future__ import annotations
@@ -18,7 +21,6 @@ from pydantic import BaseModel, ConfigDict
from jarvis.core.protocols import BrainMessage, BrainRequest, Tool
log = logging.getLogger(__name__)
-_ranking_busy: set[tuple[str, str]] = set()
Category = Literal[
"plugins", "skills", "mcp", "memory", "web", "files", "automation", "system", "cli"
]
@@ -210,31 +212,14 @@ def live_catalog(brain: Any, *, cwd: str = "", stance: str = "ask") -> list[Tool
async def discover(
*, provider: str, model: str, query: str, category: str, cwd: str, stance: str
) -> dict[str, Any]:
- from jarvis.agent_chat.runner_brain import _default_model, brain_manager
- from jarvis.core.config import get_jarvis_agent_secret, override_provider_secrets
+ from jarvis.agent_chat.runner_brain import brain_manager
+ del provider, model # Add search is keyword-only; the model is not consulted.
manager = brain_manager()
- if not model and manager is not None:
- model = _default_model(manager, provider) or ""
rows = await asyncio.to_thread(live_catalog, manager, cwd=cwd, stance=stance)
if category:
rows = [row for row in rows if row.category == category]
- ranker = None
- rank_key = (provider, model)
- if query.strip() and manager is not None and provider and rank_key not in _ranking_busy:
- _ranking_busy.add(rank_key)
- try:
- secret = get_jarvis_agent_secret(provider)
- with override_provider_secrets({provider: secret} if secret else {}):
- ranker = manager._get_brain(provider, model or None, scope="composer-search")
- found, mode = await search_catalog(rows, query, ranker)
- except Exception: # noqa: BLE001 — missing provider still allows ordinary search
- log.warning("Composer search provider unavailable", exc_info=True)
- found, mode = await search_catalog(rows, query)
- finally:
- _ranking_busy.discard(rank_key)
- else:
- found, mode = await search_catalog(rows, query)
+ found, mode = await search_catalog(rows, query)
return {"items": [r.model_dump(mode="json") for r in found], "mode": mode, "total": len(rows)}
@@ -284,18 +269,38 @@ def lexical_score(query: str, row: ToolChoice) -> float:
return (3.0 if q in name else 0.0) + sum(w in text for w in words) / max(1, len(words))
+def keyword_rank(query: str, row: ToolChoice) -> tuple[int, str, str] | None:
+ """Prefix of a name first, then other name hits, then A–Z.
+
+ Category buckets like ``skills`` are not search keys. A single letter only
+ matches the start of a name, so ``g`` lists Gmail and GitHub, not Telegram.
+ """
+ q = query.casefold().strip()
+ if not q:
+ return None
+ label = row.label.casefold()
+ brand = (row.brand or "").casefold()
+ tokens = re.findall(r"[a-z0-9]+", f"{label} {brand}")
+ if label.startswith(q) or brand.startswith(q) or any(token.startswith(q) for token in tokens):
+ return (0, label, row.id)
+ if len(q) >= 2 and (q in label or q in brand):
+ return (1, label, row.id)
+ return None
+
+
async def search_catalog(
rows: list[ToolChoice], query: str, ranker: Any = None
) -> tuple[list[ToolChoice], str]:
- """Rank every candidate by meaning, including queries without lexical overlap.
+ """Name search for Add. Optional ranker keeps meaning-based ranking for tests.
- A provider sees metadata only through Brain.complete with NO tools/history.
- Invalid output and timeouts return explicitly labelled text search.
+ Add never passes a ranker. A provider that does sees metadata only through
+ Brain.complete with NO tools/history. Invalid output and timeouts return
+ explicitly labelled text search.
"""
if not query.strip():
return rows, "browse"
- lexical = {r.id: lexical_score(query, r) for r in rows}
if ranker is not None and rows:
+ lexical = {r.id: lexical_score(query, r) for r in rows}
try:
scores: dict[str, float] = {}
# Bound individual requests, not inventory coverage. A timeout falls
@@ -361,6 +366,7 @@ async def search_catalog(
return found, "semantic"
except Exception: # noqa: BLE001 — no model is required to browse or select tools
log.warning("Composer semantic search unavailable; using text search", exc_info=True)
- found = [r for r in rows if lexical[r.id] > 0]
- found.sort(key=lambda r: (-lexical[r.id], r.label.casefold()))
- return found, "text"
+ ranked = [(keyword_rank(query, r), r) for r in rows]
+ hits = [(rank, row) for rank, row in ranked if rank is not None]
+ hits.sort(key=lambda item: item[0])
+ return [row for _, row in hits], "text"
diff --git a/jarvis/ui/web/frontend/src/components/agentchat/ComposerAddMenu.test.tsx b/jarvis/ui/web/frontend/src/components/agentchat/ComposerAddMenu.test.tsx
index e0ba3285ad..5304370601 100644
--- a/jarvis/ui/web/frontend/src/components/agentchat/ComposerAddMenu.test.tsx
+++ b/jarvis/ui/web/frontend/src/components/agentchat/ComposerAddMenu.test.tsx
@@ -120,7 +120,7 @@ describe("Add menu", () => {
expect(screen.queryByText("plugin-gmail")).toBeNull();
});
- it("forwards category and natural-language query to the server", async () => {
+ it("forwards category and name query to the server", async () => {
setup();
await screen.findByRole("button", { name: /Gmail Read your inbox/ });
fireEvent.click(screen.getByLabelText("chat_tools.filter"));
@@ -128,16 +128,16 @@ describe("Add menu", () => {
fireEvent.pointerDown(memoryOption);
fireEvent.click(memoryOption);
fireEvent.change(screen.getByLabelText("chat_tools.search"), {
- target: { value: "what did I decide" },
+ target: { value: "g" },
});
await waitFor(
() => {
const calls = vi.mocked(fetch).mock.calls;
const url = String(calls[calls.length - 1][0]);
expect(url).toContain("category=memory");
- expect(url).toContain("q=what+did+I+decide");
+ expect(url).toContain("q=g");
},
- { timeout: 1500 },
+ { timeout: 500 },
);
});
diff --git a/jarvis/ui/web/frontend/src/components/agentchat/ComposerAddMenu.tsx b/jarvis/ui/web/frontend/src/components/agentchat/ComposerAddMenu.tsx
index 6b211db71d..eee4bb5065 100644
--- a/jarvis/ui/web/frontend/src/components/agentchat/ComposerAddMenu.tsx
+++ b/jarvis/ui/web/frontend/src/components/agentchat/ComposerAddMenu.tsx
@@ -121,7 +121,7 @@ export function ComposerAddMenu({
if (!controller.signal.aborted) setLoading(false);
});
},
- query ? 600 : 0,
+ query ? 80 : 0,
);
return () => {
clearTimeout(timer);
diff --git a/jarvis/ui/web/frontend/src/i18n/locales/de.json b/jarvis/ui/web/frontend/src/i18n/locales/de.json
index c073d5dceb..bbe1880e51 100644
--- a/jarvis/ui/web/frontend/src/i18n/locales/de.json
+++ b/jarvis/ui/web/frontend/src/i18n/locales/de.json
@@ -5464,7 +5464,7 @@
},
"chat_tools": {
"add": "Hinzufügen",
- "search": "Tools suchen oder beschreiben, was du tun möchtest…",
+ "search": "Nach Namen suchen…",
"remove": "Entfernen",
"close": "Schließen",
"filter": "Tools filtern",
@@ -5480,13 +5480,13 @@
"cli": "CLIs",
"browse": "Alle Funktionen",
"semantic": "Semantische Suche",
- "text": "Textsuche (semantische Suche nicht verfügbar)",
+ "text": "Namenssuche",
"loading": "Suche läuft…",
"attach": "Dateien hinzufügen",
"folder": "Arbeitsordner auswählen",
"error": "Die Toolsuche ist nicht verfügbar.",
"retry": "Erneut versuchen",
- "empty": "Keine passenden Tools. Versuche eine andere Beschreibung oder Kategorie.",
+ "empty": "Keine passenden Tools. Versuche einen anderen Namen oder eine Kategorie.",
"connect": "Einrichten",
"next_message": "Für die nächste Nachricht ausgewählt",
"hint": "Wähle Tools für die nächste Nachricht. Berechtigungen gelten weiterhin.",
diff --git a/jarvis/ui/web/frontend/src/i18n/locales/en.json b/jarvis/ui/web/frontend/src/i18n/locales/en.json
index 1b8d062162..ebf762fd25 100644
--- a/jarvis/ui/web/frontend/src/i18n/locales/en.json
+++ b/jarvis/ui/web/frontend/src/i18n/locales/en.json
@@ -5497,7 +5497,7 @@
},
"chat_tools": {
"add": "Add",
- "search": "Search tools or describe what you want to do…",
+ "search": "Search by name…",
"remove": "Remove",
"close": "Close",
"filter": "Filter tools",
@@ -5513,13 +5513,13 @@
"cli": "CLIs",
"browse": "All capabilities",
"semantic": "Semantic search",
- "text": "Text search (semantic search unavailable)",
+ "text": "Name search",
"loading": "Searching…",
"attach": "Add files",
"folder": "Choose working folder",
"error": "Tool search is unavailable.",
"retry": "Try again",
- "empty": "No matching tools. Try another description or category.",
+ "empty": "No matching tools. Try another name or category.",
"connect": "Set up",
"next_message": "Selected for the next message",
"hint": "Pick tools for your next message. Permissions still apply.",
diff --git a/jarvis/ui/web/frontend/src/i18n/locales/es.json b/jarvis/ui/web/frontend/src/i18n/locales/es.json
index 3bb7b25536..a18d66dfd1 100644
--- a/jarvis/ui/web/frontend/src/i18n/locales/es.json
+++ b/jarvis/ui/web/frontend/src/i18n/locales/es.json
@@ -5464,7 +5464,7 @@
},
"chat_tools": {
"add": "Añadir",
- "search": "Busca herramientas o describe lo que quieres hacer…",
+ "search": "Buscar por nombre…",
"remove": "Quitar",
"close": "Cerrar",
"filter": "Filtrar herramientas",
@@ -5480,13 +5480,13 @@
"cli": "CLI",
"browse": "Todas las funciones",
"semantic": "Búsqueda semántica",
- "text": "Búsqueda de texto (búsqueda semántica no disponible)",
+ "text": "Búsqueda por nombre",
"loading": "Buscando…",
"attach": "Añadir archivos",
"folder": "Elegir carpeta de trabajo",
"error": "La búsqueda no está disponible.",
"retry": "Reintentar",
- "empty": "No hay herramientas coincidentes. Prueba otra descripción o categoría.",
+ "empty": "No hay herramientas coincidentes. Prueba otro nombre o categoría.",
"connect": "Configurar",
"next_message": "Seleccionadas para el próximo mensaje",
"hint": "Elige herramientas para el próximo mensaje. Se siguen aplicando los permisos.",
diff --git a/tests/contract/test_chat_tool_choices.py b/tests/contract/test_chat_tool_choices.py
index 9ff15587e4..e235340e3a 100644
--- a/tests/contract/test_chat_tool_choices.py
+++ b/tests/contract/test_chat_tool_choices.py
@@ -21,6 +21,7 @@ from jarvis.agent_chat.tool_catalog import (
Category,
ToolChoice,
build_catalog,
+ keyword_rank,
resolve_choices,
search_catalog,
)
@@ -212,27 +213,66 @@ def test_wire_category_and_fields_match_typescript():
assert set(get_args(Category)) <= data["chat_tools"].keys()
-async def test_discovery_uses_chat_default_model_and_own_client_scope(monkeypatch):
- ranker = Ranker('{"plugin:gmail": 0.95}')
+def _choice(**kwargs: object) -> ToolChoice:
+ row = dict(
+ id="plugin:gmail",
+ label="Gmail",
+ description="Email",
+ category="plugins",
+ group="Gmail",
+ brand="gmail",
+ )
+ row.update(kwargs)
+ return ToolChoice(**row)
+
+
+async def test_keyword_search_lists_prefix_hits_alphabetically():
+ rows = [
+ _choice(id="plugin:telegram", label="Telegram", group="Telegram", brand="telegram"),
+ _choice(id="plugin:gmail", label="Gmail", group="Gmail", brand="gmail"),
+ _choice(id="plugin:github", label="GitHub", group="GitHub", brand="github"),
+ _choice(
+ id="tool:grep",
+ label="grep",
+ description="Search files",
+ category="files",
+ group="files",
+ brand="",
+ ),
+ _choice(
+ id="skill:daily-brief",
+ label="Daily brief",
+ category="skills",
+ group="skills",
+ brand="",
+ ),
+ ]
+ found, mode = await search_catalog(rows, "g")
+ assert mode == "text"
+ assert [row.id for row in found] == ["plugin:github", "plugin:gmail", "tool:grep"]
+ assert keyword_rank("g", rows[0]) is None
+ mail, mail_mode = await search_catalog(rows, "mail")
+ assert mail_mode == "text"
+ assert [row.id for row in mail] == ["plugin:gmail"]
+
+
+async def test_discovery_is_keyword_search_without_a_model(monkeypatch):
calls = []
- def get_brain(provider, model, *, scope):
- calls.append((provider, model, scope))
- return ranker
+ def get_brain(*args, **kwargs):
+ calls.append((args, kwargs))
+ raise AssertionError("Add search must not open a brain")
fake = SimpleNamespace(_get_brain=get_brain, _fast_model=lambda _provider: "chosen-model")
monkeypatch.setattr(runner_brain, "brain_manager", lambda: fake)
monkeypatch.setattr(tool_catalog, "live_catalog", lambda *_a, **_k: inventory()[1])
- from jarvis.core import config
-
- monkeypatch.setattr(config, "get_jarvis_agent_secret", lambda _provider: None)
result = await tool_catalog.discover(
- provider="openai", model="", query="Inbox", category="plugins", cwd="", stance="ask"
+ provider="openai", model="", query="g", category="plugins", cwd="", stance="ask"
)
- assert result["mode"] == "semantic"
- assert calls == [("openai", "chosen-model", "composer-search")]
+ assert result["mode"] == "text"
+ assert calls == []
+ assert [row["id"] for row in result["items"]] == ["plugin:gmail"]
assert all(r["category"] == "plugins" for r in result["items"])
- assert not tool_catalog._ranking_busy
def test_discovery_route_serves_catalog_and_openapi_metadata(tmp_path, monkeypatch):