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.
Python agent-orchestrationai-agentai-coding-assistantclaude-codecoding-agentcomputer-usedesktop-applocal-firstmcppersonal-jarvisvoice-assistantvoice-coding
feat(agent-chat): the composer lists skills, commands, plugins, agents and files after "/", "@" and "$"
rubenluetke10-beepbfb8df27e43a
diff --git a/jarvis/agent_chat/runner_brain.py b/jarvis/agent_chat/runner_brain.pyindex 3163f5b032..482ac4403c 100644--- a/jarvis/agent_chat/runner_brain.py+++ b/jarvis/agent_chat/runner_brain.py@@ -26,6 +26,7 @@ from __future__ import annotationsimport asyncioimport logging+import reimport timeimport uuidfrom collections.abc import Callable, Mapping@@ -544,10 +545,29 @@ def _agent_secret(resolver: Callable[[str], str | None], provider: str) -> str |return None+#: A leading ``/slug`` — the composer's slash pick — and whatever follows it.+_EXPLICIT_SKILL_RE = re.compile(r"^\s*/([A-Za-z0-9][\w.:-]*)(?:\s+|$)(.*)$", re.DOTALL)+++def explicit_skill(text: str) -> tuple[str, str] | None:+ """``("slug", "the rest")`` when the message opens with ``/slug``, else None.++ The composer's ``/`` typeahead lists the registry's active skills by+ slug; picking one puts ``/slug`` at the head of the sentence. That pick+ is an order, not a hint, so it is honoured before any trigger-phrase+ matching — the same precedence a CLI gives its slash commands.+ """+ m = _EXPLICIT_SKILL_RE.match(text or "")+ if m is None:+ return None+ return m.group(1), m.group(2).strip()++def _note_skill_trigger(brain: Any, text: str) -> None:"""The desktop text path's pre-brain hook, verbatim in effect: a skillwhose trigger matches is noted on the brain, which injects its- instructions into this turn (desktop_app._on_user_message)."""+ instructions into this turn (desktop_app._on_user_message). A leading+ ``/slug`` names the skill outright and wins over the trigger matcher."""try:from jarvis.skills.skill_context import try_get_skill_contextfrom jarvis.skills.trigger_matcher import TriggerMatcher@@ -556,6 +576,16 @@ def _note_skill_trigger(brain: Any, text: str) -> None:note = getattr(brain, "note_skill_trigger", None)if skill_ctx is None or not callable(note):return+ explicit = explicit_skill(text)+ if explicit is not None:+ slug, rest = explicit+ try:+ skill = skill_ctx.registry.resolve(slug)+ except KeyError: # not a skill's name: the trigger matcher gets its turn+ log.debug("brain runner: /%s names no active skill", slug)+ else:+ note(skill.name, content=rest, source="chat")+ returnmatch_result = TriggerMatcher(skill_ctx.registry).match_voice_with_match(text, lang="auto")if match_result is None:returndiff --git a/jarvis/agent_chat/typeahead.py b/jarvis/agent_chat/typeahead.pynew file mode 100644index 0000000000..23ee1cef3f--- /dev/null+++ b/jarvis/agent_chat/typeahead.py@@ -0,0 +1,753 @@+"""What the composer offers when a person types ``/``, ``@`` or ``$``.++Every coding CLI has a typeahead: ``/`` lists the slash commands and skills,+``@`` the files of the folder (and, in Claude Code, the subagents), and Codex+spells an explicit skill ``$name``. The chat composer wears the same three+gestures — but the seat behind a chat decides what each one means, and the+list must be what THAT seat will honour when the sentence arrives. Nothing+here is a catalogue typed by hand: every row is read from the disk the+runner reads.++ runner "/" "@" "$"+ claude-cli skills, commands, plugins files, agents —+ codex-cli — files skills+ agy-cli — files —+ grok-cli — files —+ api — files —+ brain Jarvis' own skills — —++A Claude Code seat reads its user-level definitions from the account's+config dir (``CLAUDE_CONFIG_DIR``, the same seat the turn is spawned on —+never the maintainer's ``~/.claude``); a Codex seat from ``CODEX_HOME``.+Project-level definitions come from the chat's folder, and both the+``.claude`` tree and its tool-neutral twin ``.agents`` are read because a+checkout may carry only one of them.++The Jarvis surface's ``/`` is its own skill registry; the brain runner turns+a leading ``/slug`` into a noted trigger (``runner_brain._note_skill_trigger``),+so the pick here is honoured the same way a spoken trigger phrase is.++Cross-platform: ``os.scandir`` + ``pathlib`` only, paths reported POSIX-style+relative to the folder, nothing OS-specific. The file walk is bounded (depth,+entry count, wall time) and cached for a few seconds per folder, so a+keystroke never re-reads a large checkout.+"""++from __future__ import annotations++import json+import logging+import os+import re+import shutil+import subprocess+import time+from collections import deque+from dataclasses import asdict, dataclass+from pathlib import Path, PurePosixPath+from typing import Any, Final++log = logging.getLogger(__name__)++SLASH: Final[str] = "/"+MENTION: Final[str] = "@"+SKILL_REF: Final[str] = "$"++#: runner id -> the trigger characters that seat honours (see module doc).+TRIGGERS_BY_RUNNER: Final[dict[str, tuple[str, ...]]] = {+ "claude-cli": (SLASH, MENTION),+ "codex-cli": (MENTION, SKILL_REF),+ "agy-cli": (MENTION,),+ "grok-cli": (MENTION,),+ "api": (MENTION,),+ "brain": (SLASH,),+}++#: Group ids the composer turns into headings (i18n keys ``agent_chat.typeahead_group_*``).+GROUP_PROJECT: Final[str] = "project"+GROUP_ACCOUNT: Final[str] = "account"+GROUP_PLUGINS: Final[str] = "plugins"+GROUP_JARVIS: Final[str] = "jarvis"+GROUP_AGENTS: Final[str] = "agents"+GROUP_FILES: Final[str] = "files"++#: Hidden directories that still hold things worth offering under ``@``.+_VISIBLE_DOT_DIRS: Final[frozenset[str]] = frozenset({".claude", ".agents", ".codex", ".github"})+_MAX_WALK_ENTRIES: Final[int] = 25000+_MAX_WALK_DEPTH: Final[int] = 12+_MAX_WALK_SECONDS: Final[float] = 2.5+_WALK_TTL_S: Final[float] = 20.0+_GIT_TIMEOUT_S: Final[float] = 5.0+#: Inside a visible dot dir, the sub-trees that are caches or other checkouts,+#: never something to mention (``.claude/worktrees`` holds whole repos).+_SKIP_UNDER_DOT_DIRS: Final[frozenset[str]] = frozenset(+ {"worktrees", "cache", "projects", "plugins", "shell-snapshots", "sessions"}+)+_MAX_CACHED_FOLDERS: Final[int] = 8+_MAX_DEFINITIONS: Final[int] = 400+_DESCRIPTION_CHARS: Final[int] = 160+_FRONTMATTER_BYTES: Final[int] = 8192+++@dataclass(frozen=True, slots=True)+class Suggestion:+ """One row of the list.++ ``value`` is what lands in the text box after the trigger character —+ ``commit``, ``github:issue``, ``src/app.py`` — never the character itself.+ """++ value: str+ label: str+ hint: str = ""+ #: skill | command | agent | file | folder+ kind: str = ""+ group: str = ""++ def to_dict(self) -> dict[str, Any]:+ return asdict(self)+++def triggers_for(runner: str) -> tuple[str, ...]:+ """The trigger characters a seat honours; unknown runners get none."""+ return TRIGGERS_BY_RUNNER.get(runner, ())+++def suggest(+ *,+ runner: str,+ cwd: str | Path | None,+ trigger: str,+ query: str = "",+ limit: int = 40,+) -> dict[str, Any]:+ """The list for one trigger on one seat, filtered by ``query``.++ Returns ``{"trigger", "items", "truncated"}``; a trigger the seat does not+ honour yields an empty list rather than an error, so a stale picker on a+ changed seat degrades to "nothing here".+ """+ if trigger not in triggers_for(runner):+ return {"trigger": trigger, "items": [], "truncated": False}+ folder = Path(cwd).expanduser() if cwd else None+ q = (query or "").strip()+ rows: list[Suggestion]+ if trigger == SLASH:+ rows = jarvis_skills() if runner == "brain" else claude_slash(folder)+ rows = _filter_definitions(rows, q)+ elif trigger == SKILL_REF:+ rows = _filter_definitions(codex_skills(folder), q)+ else:+ rows = claude_agents(folder) if runner == "claude-cli" else []+ rows = _filter_definitions(rows, q) if q else rows+ rows = rows + file_suggestions(folder, q, limit=limit)+ truncated = len(rows) > limit+ return {+ "trigger": trigger,+ "items": [r.to_dict() for r in rows[:limit]],+ "truncated": truncated,+ }+++# ------------------------------------------------------------- definitions+++def _frontmatter(path: Path) -> dict[str, str]:+ """``name`` and ``description`` from a Markdown file's YAML frontmatter.++ A deliberately small reader — the two scalar keys, quoted or bare, plus+ the folded/literal block forms (``>`` / ``|``) collapsed to one line — so+ no YAML dependency sits on this path and a malformed file costs nothing+ but its description.+ """+ try:+ with path.open("rb") as fh:+ head = fh.read(_FRONTMATTER_BYTES).decode("utf-8", errors="replace")+ except OSError: # unreadable file: the row keeps its name and loses its description+ return {}+ if not head.startswith("---"):+ return {}+ end = head.find("\n---", 3)+ block = head[3:end] if end != -1 else head[3:]+ out: dict[str, str] = {}+ lines = block.splitlines()+ i = 0+ while i < len(lines):+ m = re.match(r"^(name|description)\s*:\s*(.*)$", lines[i])+ i += 1+ if not m:+ continue+ key, raw = m.group(1), m.group(2).strip()+ if raw in (">", "|", ">-", "|-"):+ parts: list[str] = []+ while i < len(lines) and (lines[i].startswith((" ", "\t")) or not lines[i].strip()):+ if lines[i].strip():+ parts.append(lines[i].strip())+ i += 1+ raw = " ".join(parts)+ if len(raw) >= 2 and raw[0] == raw[-1] and raw[0] in "\"'":+ raw = raw[1:-1]+ out[key] = raw.strip()+ return out+++def _short(text: str) -> str:+ text = " ".join((text or "").split())+ if len(text) <= _DESCRIPTION_CHARS:+ return text+ return text[: _DESCRIPTION_CHARS - 1].rstrip() + "…"+++def _hidden(name: str) -> bool:+ return name.startswith(".") or name.startswith("_")+++def _skill_dirs(base: Path, *, depth: int = 2) -> list[tuple[str, Path]]:+ """``(name, SKILL.md)`` for every skill folder under ``base``, up to ``depth`` levels.++ A skill is a folder holding a ``SKILL.md``; both Claude Code and Codex+ also accept them one level deeper (a category folder), which is what the+ second level covers.+ """+ found: list[tuple[str, Path]] = []+ if not base.is_dir():+ return found+ queue: deque[tuple[Path, int]] = deque([(base, 0)])+ while queue and len(found) < _MAX_DEFINITIONS:+ current, level = queue.popleft()+ try:+ with os.scandir(current) as it:+ entries = sorted(it, key=lambda e: e.name.lower())+ except OSError: # a folder that cannot be listed contributes no skills+ continue+ for entry in entries:+ if _hidden(entry.name):+ continue+ try:+ # follow_symlinks on purpose: account dirs symlink their skills.+ if not entry.is_dir(follow_symlinks=True):+ continue+ except OSError: # an entry that vanished mid-scan is not a skill+ continue+ skill_md = Path(entry.path) / "SKILL.md"+ if skill_md.is_file():+ found.append((entry.name, skill_md))+ elif level + 1 < depth:+ queue.append((Path(entry.path), level + 1))+ return found+++def _command_files(base: Path) -> list[tuple[str, Path]]:+ """``(name, file)`` for every ``*.md`` under ``base`` — nested ones keep their stem."""+ found: list[tuple[str, Path]] = []+ if not base.is_dir():+ return found+ queue: deque[tuple[Path, int]] = deque([(base, 0)])+ while queue and len(found) < _MAX_DEFINITIONS:+ current, level = queue.popleft()+ try:+ with os.scandir(current) as it:+ entries = sorted(it, key=lambda e: e.name.lower())+ except OSError: # a folder that cannot be listed contributes no commands+ continue+ for entry in entries:+ if _hidden(entry.name):+ continue+ try:+ if entry.is_dir(follow_symlinks=True):+ if level < 2:+ queue.append((Path(entry.path), level + 1))+ continue+ if not entry.is_file(follow_symlinks=True):+ continue+ except OSError: # an entry that vanished mid-scan is not a command+ continue+ if entry.name.lower().endswith(".md") and entry.name.upper() != "README.MD":+ found.append((entry.name[:-3], Path(entry.path)))+ return found+++def _definition_rows(+ pairs: list[tuple[str, Path]],+ *,+ kind: str,+ group: str,+ prefix: str = "",+ seen: set[str],+) -> list[Suggestion]:+ rows: list[Suggestion] = []+ for name, path in pairs:+ value = f"{prefix}{name}"+ if value in seen:+ continue+ seen.add(value)+ meta = _frontmatter(path)+ rows.append(+ Suggestion(+ value=value,+ label=value,+ hint=_short(meta.get("description", "")),+ kind=kind,+ group=group,+ )+ )+ return rows+++def _project_roots(folder: Path | None) -> list[Path]:+ """The ``.claude`` tree and its ``.agents`` twin inside the chat's folder."""+ if folder is None:+ return []+ return [folder / ".claude", folder / ".agents"]+++def claude_config_dir() -> Path:+ """The Claude Code seat's config dir — the account the chat spawns on."""+ try:+ from jarvis.agent_chat.runner_cli import _account_env++ raw = _account_env("claude").get("CLAUDE_CONFIG_DIR", "").strip()+ except Exception: # noqa: BLE001 — no account layer: the CLI's own default+ log.debug("typeahead: claude account env unavailable", exc_info=True)+ raw = os.environ.get("CLAUDE_CONFIG_DIR", "").strip()+ return Path(raw).expanduser() if raw else Path.home() / ".claude"+++def codex_home() -> Path:+ """The Codex seat's home — ``CODEX_HOME`` of the account, else ``~/.codex``."""+ try:+ from jarvis.agent_chat.runner_cli import _account_env++ raw = _account_env("codex").get("CODEX_HOME", "").strip()+ except Exception: # noqa: BLE001 — no account layer: the CLI's own default+ log.debug("typeahead: codex account env unavailable", exc_info=True)+ raw = os.environ.get("CODEX_HOME", "").strip()+ return Path(raw).expanduser() if raw else Path.home() / ".codex"+++def _installed_plugins(config_dir: Path) -> list[tuple[str, Path]]:+ """``(plugin, install_path)`` for every plugin Claude Code has installed AND enabled.++ ``plugins/installed_plugins.json`` (v2) maps ``name@marketplace`` to its+ install records; the user-scoped record wins, else the first whose path+ still exists. ``settings.json``'s ``enabledPlugins`` may switch one off.+ """+ manifest = config_dir / "plugins" / "installed_plugins.json"+ try:+ data = json.loads(manifest.read_text(encoding="utf-8"))+ except (OSError, ValueError): # no manifest, or a broken one: no plugins — not an error+ return []+ enabled: dict[str, Any] = {}+ try:+ settings = json.loads((config_dir / "settings.json").read_text(encoding="utf-8"))+ if isinstance(settings, dict) and isinstance(settings.get("enabledPlugins"), dict):+ enabled = settings["enabledPlugins"]+ except (OSError, ValueError): # no settings file: every installed plugin counts as enabled+ pass+ plugins = data.get("plugins") if isinstance(data, dict) else None+ if not isinstance(plugins, dict):+ return []+ out: list[tuple[str, Path]] = []+ for key, records in sorted(plugins.items()):+ if enabled.get(key) is False:+ continue+ name = str(key).split("@", 1)[0]+ if not name:+ continue+ candidates = records if isinstance(records, list) else [records]+ chosen: Path | None = None+ for rec in sorted(+ (r for r in candidates if isinstance(r, dict)),+ key=lambda r: 0 if r.get("scope") == "user" else 1,+ ):+ path = Path(str(rec.get("installPath") or "")).expanduser()+ if rec.get("installPath") and path.is_dir():+ chosen = path+ break+ if chosen is not None:+ out.append((name, chosen))+ return out+++def claude_slash(folder: Path | None) -> list[Suggestion]:+ """Claude Code's ``/`` list for this folder and this seat.++ Project skills and commands first (they shadow the account's), then the+ account's own, then every enabled plugin's as ``plugin:name`` — the+ spelling Claude Code itself lists them under.+ """+ seen: set[str] = set()+ rows: list[Suggestion] = []+ for root in _project_roots(folder):+ rows += _definition_rows(+ _skill_dirs(root / "skills"), kind="skill", group=GROUP_PROJECT, seen=seen+ )+ rows += _definition_rows(+ _command_files(root / "commands"), kind="command", group=GROUP_PROJECT, seen=seen+ )+ account = claude_config_dir()+ rows += _definition_rows(+ _skill_dirs(account / "skills"), kind="skill", group=GROUP_ACCOUNT, seen=seen+ )+ rows += _definition_rows(+ _command_files(account / "commands"), kind="command", group=GROUP_ACCOUNT, seen=seen+ )+ for plugin, install in _installed_plugins(account):+ rows += _definition_rows(+ _skill_dirs(install / "skills"),+ kind="skill",+ group=GROUP_PLUGINS,+ prefix=f"{plugin}:",+ seen=seen,+ )+ rows += _definition_rows(+ _command_files(install / "commands"),+ kind="command",+ group=GROUP_PLUGINS,+ prefix=f"{plugin}:",+ seen=seen,+ )+ return rows+++def claude_agents(folder: Path | None) -> list[Suggestion]:+ """Claude Code's subagents — project, account, plugins — for ``@name``."""+ seen: set[str] = set()+ rows: list[Suggestion] = []+ for root in _project_roots(folder):+ rows += _definition_rows(+ [(n, p) for n, p in _command_files(root / "agents") if n != "INDEX"],+ kind="agent",+ group=GROUP_AGENTS,+ seen=seen,+ )+ account = claude_config_dir()+ rows += _definition_rows(+ [(n, p) for n, p in _command_files(account / "agents") if n != "INDEX"],+ kind="agent",+ group=GROUP_AGENTS,+ seen=seen,+ )+ for plugin, install in _installed_plugins(account):+ rows += _definition_rows(+ _command_files(install / "agents"),+ kind="agent",+ group=GROUP_AGENTS,+ prefix=f"{plugin}:",+ seen=seen,+ )+ return rows+++def codex_skills(folder: Path | None) -> list[Suggestion]:+ """Codex's ``$`` list.++ The folder's ``.agents/skills`` (and its ``.claude`` twin) first, then the+ account's ``CODEX_HOME/skills``.+ """+ seen: set[str] = set()+ rows: list[Suggestion] = []+ if folder is not None:+ for root in (folder / ".agents", folder / ".claude"):+ rows += _definition_rows(+ _skill_dirs(root / "skills"), kind="skill", group=GROUP_PROJECT, seen=seen+ )+ rows += _definition_rows(+ _skill_dirs(codex_home() / "skills"), kind="skill", group=GROUP_ACCOUNT, seen=seen+ )+ return rows+++def jarvis_skills() -> list[Suggestion]:+ """The Jarvis surface's ``/`` list: every active skill of the registry, by slug."""+ try:+ from jarvis.skills.skill_context import try_get_skill_context++ ctx = try_get_skill_context()+ except Exception: # noqa: BLE001 — the skill layer is optional at boot+ log.debug("typeahead: skill context unavailable", exc_info=True)+ return []+ if ctx is None:+ return []+ rows: list[Suggestion] = []+ seen: set[str] = set()+ active: list[Any] = list(ctx.registry.list_active())+ for skill in sorted(active, key=lambda s: str(s.name).lower()):+ try:+ slug = str(skill.path.parent.name) or str(skill.name)+ except Exception: # noqa: BLE001 — a pathless skill keeps its name+ slug = str(skill.name)+ if not slug or slug in seen:+ continue+ seen.add(slug)+ fm = skill.frontmatter+ description = str(getattr(fm, "description", "") or "") if fm is not None else ""+ rows.append(+ Suggestion(+ value=slug,+ label=str(skill.name) or slug,+ hint=_short(description),+ kind="skill",+ group=GROUP_JARVIS,+ )+ )+ return rows+++def _filter_definitions(rows: list[Suggestion], query: str) -> list[Suggestion]:+ """Prefix matches first, then substring — on the value, the label, or the hint."""+ if not query:+ return rows+ q = query.lower()+ ranked: list[tuple[int, int, Suggestion]] = []+ for idx, row in enumerate(rows):+ value = row.value.lower()+ label = row.label.lower()+ if value.startswith(q) or label.startswith(q):+ score = 0+ elif q in value or q in label:+ score = 1+ elif q in row.hint.lower():+ score = 2+ else:+ continue+ ranked.append((score, idx, row))+ ranked.sort(key=lambda t: (t[0], t[1]))+ return [row for _, _, row in ranked]+++# ------------------------------------------------------------------- files+++@dataclass(frozen=True, slots=True)+class _FileEntry:+ path: str # POSIX, relative to the folder; folders end in "/"+ name: str+ is_dir: bool+ depth: int+++#: folder -> (walked_at, entries, truncated)+_walk_cache: dict[str, tuple[float, list[_FileEntry], bool]] = {}+++def _skip_dir(name: str) -> bool:+ from jarvis.agentic_ide.folders import SKIP_DIRS++ if name in SKIP_DIRS:+ return True+ return name.startswith(".") and name not in _VISIBLE_DOT_DIRS+++def _git_entries(folder: Path) -> tuple[list[_FileEntry], bool] | None:+ """What git would show: tracked files plus untracked ones ``.gitignore`` lets through.++ The list a coding CLI's own ``@`` shows is exactly this — no build+ output, no virtualenv, no ``node_modules`` — and git answers it in a+ fraction of the time a walk needs (9 500 paths in 0.1 s on the+ maintainer's checkout). ``None`` when the folder is no checkout or git+ cannot answer; the walk then stands in.+ """+ try:+ if not (folder / ".git").exists():+ return None+ except OSError: # an unreadable folder is no checkout; the walk decides+ return None+ git = shutil.which("git")+ if not git:+ return None+ from jarvis.core.process_utils import NO_WINDOW_CREATIONFLAGS++ try:+ proc = subprocess.run(+ [+ git,+ "-C",+ str(folder),+ "ls-files",+ "-z",+ "--cached",+ "--others",+ "--exclude-standard",+ ], # noqa: E501+ capture_output=True,+ timeout=_GIT_TIMEOUT_S,+ creationflags=NO_WINDOW_CREATIONFLAGS,+ check=False,+ )+ except (OSError, subprocess.SubprocessError):+ log.debug("typeahead: git ls-files failed in %s", folder, exc_info=True)+ return None+ if proc.returncode != 0:+ return None+ paths = [p for p in proc.stdout.decode("utf-8", errors="replace").split("\0") if p]+ truncated = len(paths) > _MAX_WALK_ENTRIES+ files: list[_FileEntry] = []+ folders: dict[str, _FileEntry] = {}+ for rel in paths[:_MAX_WALK_ENTRIES]:+ rel = rel.replace("\\", "/")+ if rel.endswith("/"):+ # An untracked nested checkout shows as its directory alone.+ rel = rel[:-1]+ entry = _FileEntry(rel + "/", rel.rsplit("/", 1)[-1], True, rel.count("/"))+ folders.setdefault(entry.path, entry)+ continue+ parts = rel.split("/")+ files.append(_FileEntry(rel, parts[-1], False, len(parts) - 1))+ for i in range(1, len(parts)):+ key = "/".join(parts[:i]) + "/"+ if key not in folders:+ folders[key] = _FileEntry(key, parts[i - 1], True, i - 1)+ entries = list(folders.values()) + files+ entries.sort(key=lambda e: (e.depth, not e.is_dir, e.path.lower()))+ return entries, truncated+++def _walk(folder: Path) -> tuple[list[_FileEntry], bool]:+ """Breadth-first, bounded listing of ``folder``: near things first (the no-git fallback)."""+ entries: list[_FileEntry] = []+ truncated = False+ started = time.monotonic()+ queue: deque[tuple[Path, str, int]] = deque([(folder, "", 0)])+ while queue:+ current, rel, depth = queue.popleft()+ if time.monotonic() - started > _MAX_WALK_SECONDS:+ truncated = True+ break+ try:+ with os.scandir(current) as it:+ listed = sorted(it, key=lambda e: (not _safe_is_dir(e), e.name.lower()))+ except OSError: # a folder that cannot be listed is skipped; the rest still lists+ continue+ for entry in listed:+ if len(entries) >= _MAX_WALK_ENTRIES:+ truncated = True+ queue.clear()+ break+ is_dir = _safe_is_dir(entry)+ if is_dir and _skip_dir(entry.name):+ continue+ if is_dir and rel.startswith(".") and entry.name in _SKIP_UNDER_DOT_DIRS:+ continue+ if not is_dir and entry.name.startswith("."):+ continue+ child_rel = f"{rel}{entry.name}"+ if is_dir:+ entries.append(_FileEntry(child_rel + "/", entry.name, True, depth))+ if depth + 1 < _MAX_WALK_DEPTH:+ queue.append((Path(entry.path), child_rel + "/", depth + 1))+ else:+ entries.append(_FileEntry(child_rel, entry.name, False, depth))+ return entries, truncated+++def _safe_is_dir(entry: os.DirEntry[str]) -> bool:+ try:+ return entry.is_dir(follow_symlinks=False)+ except OSError: # an entry that vanished mid-scan is treated as a file and drops out+ return False+++def _entries_for(folder: Path) -> tuple[list[_FileEntry], bool]:+ key = str(folder)+ now = time.monotonic()+ cached = _walk_cache.get(key)+ if cached and now - cached[0] < _WALK_TTL_S:+ return cached[1], cached[2]+ listed = _git_entries(folder)+ entries, truncated = listed if listed is not None else _walk(folder)+ if len(_walk_cache) >= _MAX_CACHED_FOLDERS:+ oldest = min(_walk_cache, key=lambda k: _walk_cache[k][0])+ _walk_cache.pop(oldest, None)+ _walk_cache[key] = (now, entries, truncated)+ return entries, truncated+++def forget_folder(folder: str | Path | None = None) -> None:+ """Drop the cached walk (all folders when none is named) — tests and file changes."""+ if folder is None:+ _walk_cache.clear()+ else:+ _walk_cache.pop(str(Path(folder).expanduser()), None)+++def _subsequence(needle: str, haystack: str) -> bool:+ it = iter(haystack)+ return all(ch in it for ch in needle)+++def file_suggestions(folder: Path | None, query: str, *, limit: int = 40) -> list[Suggestion]:+ """Files and folders under ``folder`` matching ``query``, nearest and best first.++ Empty query: the top of the tree in walk order. Otherwise ranked — a name+ that starts with the query, a name that contains it, a path that+ contains it, a path where its letters appear in order — and within a+ rank the shallower path wins, so ``src/app.py`` beats ``vendor/x/app.py``.+ The letters-in-order match is on the name alone and from three letters+ up: on a whole path almost any word matches, which is noise, not help.+ """+ if folder is None:+ return []+ try:+ if not folder.is_dir():+ return []+ except OSError: # an unreadable folder has no files to offer+ return []+ entries, _ = _entries_for(folder)+ q = query.strip().lower().replace("\\", "/")+ picked: list[_FileEntry]+ if not q:+ picked = entries[:limit]+ else:+ ranked: list[tuple[int, int, str, _FileEntry]] = []+ for e in entries:+ name = e.name.lower()+ path = e.path.lower()+ if name.startswith(q):+ score = 0+ elif q in name:+ score = 1+ elif q in path:+ score = 2+ elif len(q) >= 3 and _subsequence(q, name):+ score = 3+ else:+ continue+ ranked.append((score, e.depth, path, e))+ ranked.sort(key=lambda t: (t[0], t[1], t[2]))+ picked = [e for _, _, _, e in ranked[:limit]]+ return [+ Suggestion(+ value=e.path,+ label=e.name + ("/" if e.is_dir else ""),+ hint=str(PurePosixPath(e.path).parent) if e.depth > 0 else "",+ kind="folder" if e.is_dir else "file",+ group=GROUP_FILES,+ )+ for e in picked+ ]+++__all__ = [+ "GROUP_ACCOUNT",+ "GROUP_AGENTS",+ "GROUP_FILES",+ "GROUP_JARVIS",+ "GROUP_PLUGINS",+ "GROUP_PROJECT",+ "MENTION",+ "SKILL_REF",+ "SLASH",+ "TRIGGERS_BY_RUNNER",+ "Suggestion",+ "claude_agents",+ "claude_config_dir",+ "claude_slash",+ "codex_home",+ "codex_skills",+ "file_suggestions",+ "forget_folder",+ "jarvis_skills",+ "suggest",+ "triggers_for",+]diff --git a/jarvis/agentic_ide/folders.py b/jarvis/agentic_ide/folders.pyindex b7abeffdbc..67b7a8ebc9 100644--- a/jarvis/agentic_ide/folders.py+++ b/jarvis/agentic_ide/folders.py@@ -49,6 +49,9 @@ _SKIP_DIRS = frozenset("System Volume Information",})+#: The same set for other listers (the chat composer's ``@`` typeahead), so+#: "what a folder walk skips" is decided once.+SKIP_DIRS = _SKIP_DIRS# marker file/dir -> stack label. Order is irrelevant; all matches are reported._STACK_MARKERS: tuple[tuple[str, str], ...] = (@@ -628,6 +631,7 @@ def probe_project(path: str | Path) -> ProjectProfile:__all__ = [+ "SKIP_DIRS","FolderEntry","ProjectProfile","WorkspaceEntry",diff --git a/jarvis/ui/web/agent_chat_routes.py b/jarvis/ui/web/agent_chat_routes.pyindex 79012ae365..18d8b2fde3 100644--- a/jarvis/ui/web/agent_chat_routes.py+++ b/jarvis/ui/web/agent_chat_routes.py@@ -19,6 +19,8 @@ Prefix ``/api/agent-chat``:GET /check-folder?path= does the folder exist / is it a directoryGET /typeahead?trigger=&surface=&provider=&cwd=&q=what the composer lists after "/", "@" or "$"+ GET /typeahead?trigger=&surface=&provider=&cwd=&q=+ what the composer lists after "/", "@" or "$"The service lives on ``app.state.agent_chat`` (built in ``server.py``); amissing service answers 503 like every other optional subsystem.diff --git a/jarvis/ui/web/frontend/src/components/agentchat/AgentComposer.tsx b/jarvis/ui/web/frontend/src/components/agentchat/AgentComposer.tsxindex 6988e25db4..48c5951796 100644--- a/jarvis/ui/web/frontend/src/components/agentchat/AgentComposer.tsx+++ b/jarvis/ui/web/frontend/src/components/agentchat/AgentComposer.tsx@@ -15,6 +15,7 @@ import {} from "lucide-react";import { Combobox, type ComboboxGroup, type ComboboxOption } from "@/components/ui/combobox";+import { AgentMark } from "@/components/agentic/AgentMark";import { ProviderLogo } from "@/components/providers/ProviderLogo";import { useAgentChat, useAgentChatApi } from "@/components/agentchat/AgentChatStoreContext";import type { ProviderOption } from "@/store/agentChat";@@ -26,6 +27,8 @@ import { permissionModeIcon } from "@/components/agentchat/permissionIcons";import { useComposerDictation } from "@/components/agentchat/useComposerDictation";import { useChatAttachments } from "@/components/agentchat/useChatAttachments";import { usePasteRescue } from "@/components/agentchat/usePasteRescue";+import { useComposerTypeahead } from "@/components/agentchat/useComposerTypeahead";+import { ComposerTypeahead } from "@/components/agentchat/ComposerTypeahead";import { ChatAttachmentStrip } from "@/components/agentchat/ChatAttachmentStrip";import { useAutoGrowTextarea } from "@/hooks/useAutoGrowTextarea";import { fill, useT } from "@/i18n";@@ -145,6 +148,18 @@ export function AgentComposer({ autoFocus = false }: { autoFocus?: boolean }) {const fileInputRef = useRef<HTMLInputElement | null>(null);const pasteRescue = usePasteRescue();+ // The list over the box after "/", "@" or "$" — which of the three this+ // seat honours is the catalog row's word (`typeahead`), read from the+ // runner, so a seat that would take the slash as text never gets a list.+ const cardRef = useRef<HTMLDivElement | null>(null);+ const triggers = useMemo(() => provider?.typeahead ?? [], [provider]);+ const typeahead = useComposerTypeahead(textareaRef, value, setValueState, {+ surface,+ provider: draft.provider,+ cwd: draft.cwd,+ triggers,+ });+const running = runningTurn(timeline) !== null;async function onSend() {@@ -166,6 +181,8 @@ export function AgentComposer({ autoFocus = false }: { autoFocus?: boolean }) {// Watches for a Ctrl+V the embedded browser may never answer; does nothing// in a real browser, where the box pastes on its own.pasteRescue.onKeyDown(ev);+ // An open list owns the arrows, Enter, Tab and Escape.+ if (typeahead.onKeyDown(ev)) return;if (ev.key === "Enter" && !ev.shiftKey) {ev.preventDefault();void onSend();@@ -239,7 +256,21 @@ export function AgentComposer({ autoFocus = false }: { autoFocus?: boolean }) {disabled: !p.connected,icon: (<span className="relative inline-flex shrink-0">- <ProviderLogo providerId={p.id} label={p.label} size="sm" />+ {/* A coding CLI installed on this machine wears its own mark; a+ catalog row wears its provider family's. Both are real brand+ files — the fallback either would otherwise take is a letter+ in a box, and a letter is not a logo. */}+ {p.agentMark ? (+ <AgentMark+ agent={p.agentMark}+ label={p.label}+ logoUrl={p.logoUrl}+ variant="plain"+ size="sm"+ />+ ) : (+ <ProviderLogo providerId={p.id} label={p.label} size="sm" />+ )}{(broken || working) && (<spandata-testid={`provider-health-${p.id}`}@@ -376,6 +407,7 @@ export function AgentComposer({ autoFocus = false }: { autoFocus?: boolean }) {return (<div+ ref={cardRef}data-testid="agent-composer"data-dragging={files.dragging ? "true" : undefined}// The whole card is the drop target, not just the text box: someone@@ -415,6 +447,16 @@ export function AgentComposer({ autoFocus = false }: { autoFocus?: boolean }) {analyzing={files.analyzing}onRemove={files.remove}/>+ <ComposerTypeahead+ anchorRef={cardRef}+ open={typeahead.open}+ trigger={typeahead.token?.trigger ?? null}+ items={typeahead.items}+ loading={typeahead.loading}+ activeIndex={typeahead.activeIndex}+ onHover={typeahead.setActiveIndex}+ onPick={typeahead.pick}+ /><textarearef={textareaRef}data-jarvis-chat-input=""@@ -422,6 +464,11 @@ export function AgentComposer({ autoFocus = false }: { autoFocus?: boolean }) {value={value}onChange={(e) => setValueState(e.target.value)}onKeyDown={onKeyDown}+ onSelect={typeahead.refresh}+ onClick={typeahead.refresh}+ onBlur={typeahead.blur}+ aria-expanded={typeahead.open || undefined}+ aria-autocomplete={triggers.length ? "list" : undefined}onPaste={(e) => {pasteRescue.onPaste();files.onPaste(e);diff --git a/jarvis/ui/web/frontend/src/components/agentchat/ComposerTypeahead.tsx b/jarvis/ui/web/frontend/src/components/agentchat/ComposerTypeahead.tsxnew file mode 100644index 0000000000..25777327b1--- /dev/null+++ b/jarvis/ui/web/frontend/src/components/agentchat/ComposerTypeahead.tsx@@ -0,0 +1,184 @@+import { useEffect, useId, useLayoutEffect, useRef, useState, type RefObject } from "react";+import { createPortal } from "react-dom";+import { Bot, FileText, Folder, Sparkles, TerminalSquare } from "lucide-react";++import { groupRuns, type TypeaheadItem } from "@/components/agentchat/typeahead";+import { useT } from "@/i18n";+import { cn } from "@/lib/utils";++const PANEL_MAX_HEIGHT = 320;+const VIEWPORT_MARGIN = 8;++/**+ * The list over the composer — what `/`, `@` or `$` offers, one row per+ * item, grouped by where it came from (this folder, the account, a plugin,+ * Jarvis' registry, the subagents, the files).+ *+ * Drawn above the card, portalled and fixed like the Combobox panel, so the+ * page's scroll columns cannot clip it. The highlighted row follows the+ * arrow keys the text box receives (`useComposerTypeahead`); the mouse+ * hovers to move it and clicks to pick. `onMouseDown` prevents default so a+ * click never takes focus from the text box — the caret is the whole state.+ */+export function ComposerTypeahead({+ anchorRef,+ open,+ trigger,+ items,+ loading,+ activeIndex,+ onHover,+ onPick,+}: {+ anchorRef: RefObject<HTMLElement | null>;+ open: boolean;+ trigger: string | null;+ items: TypeaheadItem[];+ loading: boolean;+ activeIndex: number;+ onHover: (index: number) => void;+ onPick: (item: TypeaheadItem) => void;+}) {+ const t = useT();+ const listId = useId();+ const listRef = useRef<HTMLDivElement | null>(null);+ const [position, setPosition] = useState<{+ left: number;+ bottom: number;+ width: number;+ maxHeight: number;+ } | null>(null);++ useLayoutEffect(() => {+ if (!open) return;+ const measure = () => {+ const anchor = anchorRef.current;+ if (!anchor) return;+ const rect = anchor.getBoundingClientRect();+ setPosition({+ left: rect.left,+ bottom: window.innerHeight - rect.top + 6,+ width: rect.width,+ maxHeight: Math.max(120, Math.min(PANEL_MAX_HEIGHT, rect.top - VIEWPORT_MARGIN - 6)),+ });+ };+ measure();+ window.addEventListener("scroll", measure, true);+ window.addEventListener("resize", measure);+ return () => {+ window.removeEventListener("scroll", measure, true);+ window.removeEventListener("resize", measure);+ };+ }, [open, anchorRef, items.length]);++ // The highlighted row stays in view as the arrows move it.+ useEffect(() => {+ if (!open) return;+ const row = listRef.current?.querySelector<HTMLElement>(`[data-index="${activeIndex}"]`);+ // jsdom draws no layout and has no scrollIntoView; the browser does.+ if (row && typeof row.scrollIntoView === "function") row.scrollIntoView({ block: "nearest" });+ }, [open, activeIndex]);++ if (!open || !position || !trigger) return null;++ const runs = groupRuns(items);+ let runningIndex = 0;++ return createPortal(+ <div+ data-testid="composer-typeahead"+ data-trigger={trigger}+ role="listbox"+ id={listId}+ aria-label={t("agent_chat.typeahead_label")}+ ref={listRef}+ style={{+ left: position.left,+ bottom: position.bottom,+ width: position.width,+ maxHeight: position.maxHeight,+ }}+ onMouseDown={(ev) => ev.preventDefault()}+ className="fixed z-[70] flex flex-col overflow-y-auto rounded-xl border border-primary/25 bg-popover/95 p-1 text-sm shadow-[0_22px_55px_-16px_rgb(var(--scrim-rgb)/0.7),inset_0_1px_0_hsl(var(--foreground)/0.05)] backdrop-blur-xl"+ >+ {items.length === 0 ? (+ <div className="px-3 py-2 text-xs text-muted-foreground" data-testid="composer-typeahead-empty">+ {loading ? t("agent_chat.typeahead_loading") : t("agent_chat.typeahead_empty")}+ </div>+ ) : (+ runs.map((run) => (+ <div key={`${run.group}-${runningIndex}`} role="group" aria-label={groupLabel(run.group, t)}>+ <div className="px-2 pb-0.5 pt-1.5 text-[10px] font-semibold uppercase tracking-wider text-muted-foreground">+ {groupLabel(run.group, t)}+ </div>+ {run.items.map((item) => {+ const index = runningIndex;+ runningIndex += 1;+ const active = index === activeIndex;+ const Icon = kindIcon(item.kind);+ return (+ <div+ key={`${item.group}:${item.value}`}+ role="option"+ aria-selected={active}+ data-index={index}+ data-testid="composer-typeahead-item"+ onMouseEnter={() => onHover(index)}+ onClick={() => onPick(item)}+ className={cn(+ "flex cursor-pointer items-center gap-2 rounded-lg px-2 py-1.5",+ active ? "bg-primary/15 text-foreground" : "text-foreground/90",+ )}+ >+ <Icon className="h-3.5 w-3.5 shrink-0 text-muted-foreground" aria-hidden />+ <span className="shrink-0 font-mono text-[13px]">+ <span className="text-muted-foreground">{trigger}</span>+ {item.value}+ </span>+ {item.hint && (+ <span className="min-w-0 flex-1 truncate text-xs text-muted-foreground">{item.hint}</span>+ )}+ </div>+ );+ })}+ </div>+ ))+ )}+ </div>,+ document.body,+ );+}++function groupLabel(group: string, t: (key: string) => string): string {+ switch (group) {+ case "project":+ return t("agent_chat.typeahead_group_project");+ case "account":+ return t("agent_chat.typeahead_group_account");+ case "plugins":+ return t("agent_chat.typeahead_group_plugins");+ case "jarvis":+ return t("agent_chat.typeahead_group_jarvis");+ case "agents":+ return t("agent_chat.typeahead_group_agents");+ case "files":+ return t("agent_chat.typeahead_group_files");+ default:+ return group;+ }+}++function kindIcon(kind: string) {+ switch (kind) {+ case "skill":+ return Sparkles;+ case "command":+ return TerminalSquare;+ case "agent":+ return Bot;+ case "folder":+ return Folder;+ default:+ return FileText;+ }+}diff --git a/jarvis/ui/web/frontend/src/components/agentchat/composerTypeahead.test.tsx b/jarvis/ui/web/frontend/src/components/agentchat/composerTypeahead.test.tsxnew file mode 100644index 0000000000..1f856f0999--- /dev/null+++ b/jarvis/ui/web/frontend/src/components/agentchat/composerTypeahead.test.tsx@@ -0,0 +1,222 @@+import { act, cleanup, fireEvent, render, screen, waitFor } from "@testing-library/react";+import { afterEach, beforeEach, describe, expect, it, vi } from "vitest";++import { AgentComposer } from "@/components/agentchat/AgentComposer";+import { AgentChatStoreProvider } from "@/components/agentchat/AgentChatStoreContext";+import { EMPTY_TIMELINE } from "@/components/agentchat/reduce";+import { useAgentChatStore } from "@/store/agentChat";+import { useEventStore } from "@/store/events";+import type { AgentChatCatalog } from "@/lib/agentChatApi";++/**+ * The list over the composer after "/", "@" or "$" — the gesture every+ * coding CLI has, on the chat's own text box.+ *+ * What is under test: the list opens only for the triggers the catalog row+ * names, it shows what the backend read, the arrows and Enter pick without+ * sending, Escape dismisses for that token, and a seat with no triggers gets+ * no list at all.+ */++function catalog(typeahead?: string[]): AgentChatCatalog {+ return {+ default_cwd: "C:\\work",+ shell: "pwsh",+ providers: [+ {+ id: "claude-api",+ label: "Anthropic Claude",+ family: "claude",+ runner: "claude-cli",+ models_source: "curated",+ curated_models: [{ id: "claude-opus-5", label: "Claude Opus 5" }],+ default_model: "",+ keyless: false,+ native_resume: true,+ effort_levels: ["low", "high"],+ default_effort: "high",+ permission_modes: [{ id: "default", label: "Ask before acting", description: "" }],+ default_permission_mode: "default",+ cli_installed: true,+ ...(typeahead ? { typeahead } : {}),+ },+ ],+ };+}++function seed(cat: AgentChatCatalog, overrides: Record<string, unknown> = {}) {+ useAgentChatStore.setState({+ catalog: cat,+ connections: [{ jarvis: "claude-api", key_set: true, is_active_brain: true }],+ catalogError: null,+ backendOutdated: false,+ liveModels: {},+ sessions: [],+ activeSessionId: "s-1",+ activeSession: null,+ timeline: EMPTY_TIMELINE,+ draft: {+ provider: "claude-api",+ model: "",+ effort: "high",+ permissionMode: "default",+ buildMode: "default",+ cwd: "C:\\work",+ },+ busy: false,+ lastError: null,+ loadCatalog: async () => {},+ loadSessions: async () => {},+ loadModels: async () => {},+ ...overrides,+ });+}++function composer() {+ return render(+ <AgentChatStoreProvider store={useAgentChatStore}>+ <AgentComposer />+ </AgentChatStoreProvider>,+ );+}++function box(): HTMLTextAreaElement {+ return document.querySelector("textarea[data-jarvis-chat-input]") as HTMLTextAreaElement;+}++/** Type into the box the way a person does: the value lands, the caret sits at its end. */+function type(text: string) {+ const el = box();+ fireEvent.change(el, { target: { value: text } });+ el.setSelectionRange(text.length, text.length);+ fireEvent.select(el);+}++const SLASH_ITEMS = [+ { value: "commit", label: "commit", hint: "Commit the work", kind: "skill", group: "project" },+ { value: "review", label: "review", hint: "Review the diff", kind: "command", group: "project" },+ { value: "github:issue", label: "github:issue", hint: "Open an issue", kind: "skill", group: "plugins" },+];+const FILE_ITEMS = [+ { value: "src/", label: "src/", hint: "", kind: "folder", group: "files" },+ { value: "src/app.py", label: "app.py", hint: "src", kind: "file", group: "files" },+];++describe("composer typeahead", () => {+ let fetchMock: ReturnType<typeof vi.fn>;+ let sent: string[];++ beforeEach(() => {+ window.localStorage.clear();+ useEventStore.setState({ connected: true, wsWarming: false, assistantName: "Jarvis" });+ sent = [];+ fetchMock = vi.fn(async (url: string) => {+ const u = String(url);+ if (u.includes("/api/agent-chat/typeahead")) {+ const params = new URL(u, "http://x").searchParams;+ const trigger = params.get("trigger");+ return {+ ok: true,+ status: 200,+ json: async () => ({+ trigger,+ items: trigger === "/" ? SLASH_ITEMS : FILE_ITEMS,+ truncated: false,+ }),+ } as Response;+ }+ if (u.includes("/messages")) sent.push(u);+ return { ok: true, status: 200, json: async () => ({ turn_id: "t-1" }) } as Response;+ });+ vi.stubGlobal("fetch", fetchMock);+ });++ afterEach(() => {+ cleanup();+ vi.unstubAllGlobals();+ vi.restoreAllMocks();+ });++ it("opens the slash list with what the backend read, grouped, and picks with Enter without sending", async () => {+ seed(catalog(["/", "@"]));+ composer();+ type("/");++ await waitFor(() => expect(screen.getByTestId("composer-typeahead")).toBeTruthy());+ const rows = screen.getAllByTestId("composer-typeahead-item");+ expect(rows.map((r) => r.textContent)).toEqual([+ "/commitCommit the work",+ "/reviewReview the diff",+ "/github:issueOpen an issue",+ ]);+ expect(screen.getByTestId("composer-typeahead").textContent).toContain("Plugins");+ const asked = new URL(String(fetchMock.mock.calls[0][0]), "http://x").searchParams;+ // The default store speaks for the front page; the IDE's store would say "agent".+ expect(asked.get("surface")).toBe("jarvis");+ expect(asked.get("provider")).toBe("claude-api");+ expect(asked.get("cwd")).toBe("C:\\work");++ // Narrow, then arrow down to the second match and take it.+ type("/re");+ await waitFor(() =>+ expect(screen.getAllByTestId("composer-typeahead-item").map((r) => r.getAttribute("data-index"))).toEqual([+ "0",+ ]),+ );+ expect(screen.getByTestId("composer-typeahead-item").textContent).toContain("/review");+ fireEvent.keyDown(box(), { key: "Enter" });+ await waitFor(() => expect(box().value).toBe("/review "));+ expect(sent).toEqual([]);+ expect(screen.queryByTestId("composer-typeahead")).toBeNull();+ });++ it("asks the backend per keystroke for @ and keeps a folder pick open on its contents", async () => {+ seed(catalog(["/", "@"]));+ composer();+ type("look at @sr");++ // The list opens at once ("Looking…"); the request follows the debounce.+ await waitFor(() => expect(screen.getByTestId("composer-typeahead")).toBeTruthy());+ const asked = () =>+ fetchMock.mock.calls+ .map((c) => new URL(String(c[0]), "http://x").searchParams)+ .filter((p) => p.get("trigger") === "@");+ await waitFor(() => expect(asked().at(-1)?.get("q")).toBe("sr"));+ await waitFor(() => expect(screen.getAllByTestId("composer-typeahead-item")).toHaveLength(2));++ fireEvent.keyDown(box(), { key: "ArrowDown" });+ fireEvent.keyDown(box(), { key: "ArrowUp" });+ fireEvent.keyDown(box(), { key: "Tab" });+ await waitFor(() => expect(box().value).toBe("look at @src/"));+ expect(sent).toEqual([]);+ });++ it("dismisses on Escape for that token only, and Enter then sends", async () => {+ seed(catalog(["/", "@"]));+ composer();+ type("/");+ await waitFor(() => expect(screen.getByTestId("composer-typeahead")).toBeTruthy());++ fireEvent.keyDown(box(), { key: "Escape" });+ expect(screen.queryByTestId("composer-typeahead")).toBeNull();+ type("/c");+ await act(async () => {+ await new Promise((r) => setTimeout(r, 30));+ });+ expect(screen.queryByTestId("composer-typeahead")).toBeNull();++ fireEvent.keyDown(box(), { key: "Enter" });+ await waitFor(() => expect(sent.length).toBe(1));+ });++ it("gives a seat with no triggers no list at all", async () => {+ seed(catalog());+ composer();+ type("/");+ await act(async () => {+ await new Promise((r) => setTimeout(r, 30));+ });+ expect(screen.queryByTestId("composer-typeahead")).toBeNull();+ expect(fetchMock.mock.calls.some((c) => String(c[0]).includes("/typeahead"))).toBe(false);+ });+});diff --git a/jarvis/ui/web/frontend/src/components/agentchat/typeahead.test.ts b/jarvis/ui/web/frontend/src/components/agentchat/typeahead.test.tsnew file mode 100644index 0000000000..490ec711c6--- /dev/null+++ b/jarvis/ui/web/frontend/src/components/agentchat/typeahead.test.ts@@ -0,0 +1,104 @@+import { describe, expect, it } from "vitest";++import {+ activeToken,+ applyPick,+ filterItems,+ groupRuns,+ isStaticTrigger,+ type TypeaheadItem,+} from "@/components/agentchat/typeahead";++const ALL = ["/", "@", "$"] as const;++function item(value: string, kind = "skill", group = "project", hint = ""): TypeaheadItem {+ return { value, label: value, hint, kind, group };+}++describe("activeToken", () => {+ it("opens on a trigger at the caret's token", () => {+ expect(activeToken("/", 1, ALL)).toEqual({ trigger: "/", query: "", start: 0, end: 1 });+ expect(activeToken("/com", 4, ALL)).toEqual({ trigger: "/", query: "com", start: 0, end: 4 });+ expect(activeToken("look at @src/ap", 15, ALL)).toEqual({+ trigger: "@",+ query: "src/ap",+ start: 8,+ end: 15,+ });+ expect(activeToken("use $grill", 10, ALL)).toEqual({ trigger: "$", query: "grill", start: 4, end: 10 });+ });++ it("opens the slash list only at the very start of the message", () => {+ expect(activeToken("see /etc/hosts", 14, ALL)).toBeNull();+ expect(activeToken(" /commit", 9, ALL)).toEqual({ trigger: "/", query: "commit", start: 2, end: 9 });+ expect(activeToken("https://x", 9, ALL)).toBeNull();+ });++ it("never opens inside an address or after the token ended", () => {+ expect(activeToken("mail [email protected]", 10, ALL)).toBeNull();+ expect(activeToken("@src/app.py next", 16, ALL)).toBeNull();+ expect(activeToken("@src ", 5, ALL)).toBeNull();+ });++ it("only opens the triggers the seat honours", () => {+ expect(activeToken("/x", 2, ["@"])).toBeNull();+ expect(activeToken("$x", 2, ["@", "$"])).not.toBeNull();+ expect(activeToken("/x", 2, [])).toBeNull();+ });++ it("follows the caret, not the end of the text", () => {+ const text = "@src tail";+ expect(activeToken(text, 4, ALL)?.query).toBe("src");+ expect(activeToken(text, 9, ALL)).toBeNull();+ });+});++describe("applyPick", () => {+ it("writes the pick over the token and adds a space after a name", () => {+ const token = activeToken("fix /com please", 8, ["/"]);+ expect(token).toBeNull(); // not at the start — but a start token works:+ const start = activeToken("/com please", 4, ["/"])!;+ expect(applyPick("/com please", start, item("commit"))).toEqual({+ text: "/commit please",+ caret: 8,+ });+ });++ it("keeps the caret inside a folder pick so the list narrows into it", () => {+ const token = activeToken("read @sr", 8, ["@"])!;+ expect(applyPick("read @sr", token, item("src/", "folder", "files"))).toEqual({+ text: "read @src/",+ caret: 10,+ });+ });+});++describe("filterItems", () => {+ it("ranks a prefix over a substring over a hint hit and keeps arrival order within a rank", () => {+ const items = [+ item("release", "skill", "project", "Tag and commit"),+ item("autocommit"),+ item("commit"),+ item("deploy"),+ ];+ expect(filterItems(items, "commit").map((i) => i.value)).toEqual(["commit", "autocommit", "release"]);+ expect(filterItems(items, "").map((i) => i.value)).toEqual(["release", "autocommit", "commit", "deploy"]);+ });+});++describe("groupRuns / isStaticTrigger", () => {+ it("cuts the arrival order into runs of one group", () => {+ const runs = groupRuns([item("a"), item("b"), item("c", "skill", "account"), item("d")]);+ expect(runs.map((r) => [r.group, r.items.length])).toEqual([+ ["project", 2],+ ["account", 1],+ ["project", 1],+ ]);+ });++ it("reads / and $ once and asks per keystroke for @", () => {+ expect(isStaticTrigger("/")).toBe(true);+ expect(isStaticTrigger("$")).toBe(true);+ expect(isStaticTrigger("@")).toBe(false);+ });+});diff --git a/jarvis/ui/web/frontend/src/components/agentchat/typeahead.ts b/jarvis/ui/web/frontend/src/components/agentchat/typeahead.tsnew file mode 100644index 0000000000..395e675775--- /dev/null+++ b/jarvis/ui/web/frontend/src/components/agentchat/typeahead.ts@@ -0,0 +1,114 @@+/**+ * The composer's typeahead, the pure part: which token under the caret opens+ * a list, and how a pick lands back in the text.+ *+ * Three gestures, the ones every coding CLI has: `/` for skills and commands,+ * `@` for files (and Claude Code's subagents), `$` for Codex's explicit skill+ * mention. Which of them a chat honours is the backend's word — the catalog+ * row's `typeahead` list, decided from the seat's runner — so the box never+ * opens a `/` list for a seat that would read the slash as plain text.+ */++export interface TypeaheadItem {+ /** What lands after the trigger character — `commit`, `github:issue`, `src/app.py`. */+ value: string;+ label: string;+ hint: string;+ /** skill | command | agent | file | folder */+ kind: string;+ /** project | account | plugins | jarvis | agents | files */+ group: string;+}++export interface TypeaheadResponse {+ trigger: string;+ items: TypeaheadItem[];+ truncated: boolean;+}++export interface ActiveToken {+ trigger: string;+ /** The text typed after the trigger, up to the caret. */+ query: string;+ /** Index of the trigger character. */+ start: number;+ /** The caret. */+ end: number;+}++/**+ * The token the caret sits in, when a trigger character opens it.+ *+ * A token runs from the last whitespace before the caret to the caret. `@`+ * and `$` open anywhere a word starts; `/` only at the very start of the+ * message, because that is the only place a CLI reads a slash command — a+ * `/` inside a path or a URL must not throw a list over the sentence. An+ * address like `a@b` never opens: the token's first character is `a`.+ */+export function activeToken(+ text: string,+ caret: number,+ triggers: readonly string[],+): ActiveToken | null {+ if (!triggers.length) return null;+ const at = Math.max(0, Math.min(caret, text.length));+ let start = at;+ while (start > 0 && !/\s/.test(text[start - 1])) start -= 1;+ const trigger = text[start];+ if (!trigger || !triggers.includes(trigger)) return null;+ if (trigger === "/" && text.slice(0, start).trim() !== "") return null;+ return { trigger, query: text.slice(start + 1, at), start, end: at };+}++/**+ * The text with `item` written over the token, and where the caret goes.+ *+ * A file or a name is followed by one space so typing continues past it. A+ * folder is not: it ends in `/`, and the next keystroke should narrow the+ * list to what is inside it, the way a shell completes a path.+ */+export function applyPick(+ text: string,+ token: ActiveToken,+ item: TypeaheadItem,+): { text: string; caret: number } {+ const trailing = item.kind === "folder" ? "" : " ";+ const inserted = `${token.trigger}${item.value}${trailing}`;+ const next = text.slice(0, token.start) + inserted + text.slice(token.end);+ return { text: next, caret: token.start + inserted.length };+}++/** A prefix match on the value or the label first, then a substring, then the hint. */+export function filterItems(items: readonly TypeaheadItem[], query: string): TypeaheadItem[] {+ const q = query.trim().toLowerCase();+ if (!q) return [...items];+ const ranked: { score: number; index: number; item: TypeaheadItem }[] = [];+ items.forEach((item, index) => {+ const value = item.value.toLowerCase();+ const label = item.label.toLowerCase();+ let score: number;+ if (value.startsWith(q) || label.startsWith(q)) score = 0;+ else if (value.includes(q) || label.includes(q)) score = 1;+ else if (item.hint.toLowerCase().includes(q)) score = 2;+ else return;+ ranked.push({ score, index, item });+ });+ ranked.sort((a, b) => a.score - b.score || a.index - b.index);+ return ranked.map((r) => r.item);+}++/** Triggers whose list is read once and filtered here; `@` asks the backend per keystroke. */+export function isStaticTrigger(trigger: string): boolean {+ return trigger === "/" || trigger === "$";+}++/** Items in the order they arrived, cut into runs of one group for headings. */+export function groupRuns(items: readonly TypeaheadItem[]): { group: string; items: TypeaheadItem[] }[] {+ const runs: { group: string; items: TypeaheadItem[] }[] = [];+ for (const item of items) {+ const last = runs[runs.length - 1];+ if (last && last.group === item.group) last.items.push(item);+ else runs.push({ group: item.group, items: [item] });+ }+ return runs;+}diff --git a/jarvis/ui/web/frontend/src/components/agentchat/useComposerTypeahead.ts b/jarvis/ui/web/frontend/src/components/agentchat/useComposerTypeahead.tsnew file mode 100644index 0000000000..7d45eb3609--- /dev/null+++ b/jarvis/ui/web/frontend/src/components/agentchat/useComposerTypeahead.ts@@ -0,0 +1,244 @@+import { useCallback, useEffect, useMemo, useRef, useState, type KeyboardEvent, type RefObject } from "react";++import { fetchTypeahead, type AgentChatSurface } from "@/lib/agentChatApi";+import {+ activeToken,+ applyPick,+ filterItems,+ isStaticTrigger,+ type ActiveToken,+ type TypeaheadItem,+} from "@/components/agentchat/typeahead";++/** How long the box waits after a keystroke before asking for `@` matches. */+const MENTION_DEBOUNCE_MS = 120;+/** One fetched `/` or `$` list stands this long before it is read again. */+const STATIC_LIST_TTL_MS = 15_000;++export interface ComposerTypeahead {+ open: boolean;+ token: ActiveToken | null;+ items: TypeaheadItem[];+ loading: boolean;+ activeIndex: number;+ setActiveIndex: (index: number) => void;+ /** Re-read the caret; call after any change, click or arrow key in the box. */+ refresh: () => void;+ /** Returns true when the key was the list's — the caller must then stop. */+ onKeyDown: (ev: KeyboardEvent<HTMLTextAreaElement>) => boolean;+ pick: (item: TypeaheadItem) => void;+ /** Escape: hide the list for this token until the token changes. */+ close: () => void;+ /** Focus left the box: hide the list; it comes back with the next caret move. */+ blur: () => void;+}++interface Seat {+ surface: AgentChatSurface;+ provider: string;+ cwd: string;+ triggers: readonly string[];+}++/**+ * The typeahead's state machine for one text box.+ *+ * The caret decides everything: whenever it sits in a token a trigger opens+ * (`typeahead.ts`), the list for that trigger is shown, filtered by what was+ * typed after it. `/` and `$` lists are read once per seat and folder and+ * filtered here; `@` asks the backend per keystroke, because the folder's+ * file list is too large to ship. Escape dismisses the list for THIS token+ * only — a `/` typed on purpose as text must not keep re-opening, and the+ * next token opens as usual.+ */+export function useComposerTypeahead(+ textareaRef: RefObject<HTMLTextAreaElement | null>,+ value: string,+ setValue: (next: string) => void,+ seat: Seat,+): ComposerTypeahead {+ const [token, setToken] = useState<ActiveToken | null>(null);+ const [rawItems, setRawItems] = useState<TypeaheadItem[]>([]);+ const [loading, setLoading] = useState(false);+ const [activeIndex, setActiveIndex] = useState(0);+ const dismissedStart = useRef<number | null>(null);+ const staticCache = useRef(new Map<string, { at: number; items: TypeaheadItem[] }>());+ const abortRef = useRef<AbortController | null>(null);+ const seatRef = useRef(seat);+ seatRef.current = seat;++ const refresh = useCallback(() => {+ const box = textareaRef.current;+ if (!box) {+ setToken(null);+ return;+ }+ const next = activeToken(box.value, box.selectionStart ?? box.value.length, seatRef.current.triggers);+ if (next && dismissedStart.current === next.start) {+ setToken(null);+ return;+ }+ if (next === null) dismissedStart.current = null;+ setToken((prev) =>+ prev && next && prev.trigger === next.trigger && prev.start === next.start && prev.query === next.query+ ? prev+ : next,+ );+ }, [textareaRef]);++ // The value can change under the box without a key (dictation, a paste+ // rescue, a pick); the caret is read afterwards so the token follows.+ useEffect(() => {+ refresh();+ }, [value, refresh]);++ const seatKey = `${seat.surface}|${seat.provider}|${seat.cwd}`;+ const trigger = token?.trigger ?? null;+ const query = token?.query ?? "";++ useEffect(() => {+ if (!trigger) {+ abortRef.current?.abort();+ setLoading(false);+ return;+ }+ const wanted = seatRef.current;+ const key = `${trigger}|${seatKey}`;+ if (isStaticTrigger(trigger)) {+ const cached = staticCache.current.get(key);+ if (cached && Date.now() - cached.at < STATIC_LIST_TTL_MS) {+ setRawItems(cached.items);+ setLoading(false);+ return;+ }+ }+ const controller = new AbortController();+ abortRef.current?.abort();+ abortRef.current = controller;+ setLoading(true);+ const timer = window.setTimeout(+ () => {+ fetchTypeahead(+ {+ surface: wanted.surface,+ provider: wanted.provider,+ cwd: wanted.cwd,+ trigger,+ q: isStaticTrigger(trigger) ? "" : query,+ },+ controller.signal,+ )+ .then((res) => {+ if (controller.signal.aborted) return;+ if (isStaticTrigger(trigger)) staticCache.current.set(key, { at: Date.now(), items: res.items });+ setRawItems(res.items);+ setLoading(false);+ })+ .catch(() => {+ // An aborted request is the caller's doing; anything else leaves+ // the list empty — the box still works, only the list is gone.+ if (controller.signal.aborted) return;+ setRawItems([]);+ setLoading(false);+ });+ },+ isStaticTrigger(trigger) ? 0 : MENTION_DEBOUNCE_MS,+ );+ return () => {+ window.clearTimeout(timer);+ controller.abort();+ };+ }, [trigger, query, seatKey]);++ const items = useMemo(+ () => (trigger && isStaticTrigger(trigger) ? filterItems(rawItems, query) : rawItems),+ [trigger, rawItems, query],+ );++ // A new query starts at the top; a longer list never leaves the highlight past its end.+ useEffect(() => {+ setActiveIndex(0);+ }, [trigger, query]);+ useEffect(() => {+ if (activeIndex >= items.length) setActiveIndex(Math.max(0, items.length - 1));+ }, [items.length, activeIndex]);++ const close = useCallback(() => {+ if (token) dismissedStart.current = token.start;+ setToken(null);+ }, [token]);++ const blur = useCallback(() => setToken(null), []);++ const pick = useCallback(+ (item: TypeaheadItem) => {+ const box = textareaRef.current;+ if (!token) return;+ const applied = applyPick(box ? box.value : value, token, item);+ setValue(applied.text);+ dismissedStart.current = null;+ setToken(null);+ // The caret lands after what was inserted, once React has painted the new value.+ window.requestAnimationFrame(() => {+ const el = textareaRef.current;+ if (!el) return;+ el.focus();+ el.setSelectionRange(applied.caret, applied.caret);+ // A folder keeps the list open on its contents; refresh reads the caret.+ if (item.kind === "folder") refresh();+ });+ },+ [token, textareaRef, value, setValue, refresh],+ );++ const open = Boolean(token) && (loading || items.length > 0 || query.length > 0);++ const onKeyDown = useCallback(+ (ev: KeyboardEvent<HTMLTextAreaElement>): boolean => {+ if (!token || !open) return false;+ switch (ev.key) {+ case "ArrowDown":+ ev.preventDefault();+ if (items.length) setActiveIndex((i) => (i + 1) % items.length);+ return true;+ case "ArrowUp":+ ev.preventDefault();+ if (items.length) setActiveIndex((i) => (i - 1 + items.length) % items.length);+ return true;+ case "Enter":+ case "Tab": {+ if (ev.shiftKey && ev.key === "Enter") return false;+ const item = items[activeIndex];+ if (!item) {+ // Nothing to pick: Tab does nothing, Enter falls through to send.+ return ev.key === "Tab";+ }+ ev.preventDefault();+ pick(item);+ return true;+ }+ case "Escape":+ ev.preventDefault();+ close();+ return true;+ default:+ return false;+ }+ },+ [token, open, items, activeIndex, pick, close],+ );++ return {+ open,+ token,+ items,+ loading,+ activeIndex,+ setActiveIndex,+ refresh,+ onKeyDown,+ pick,+ close,+ blur,+ };+}diff --git a/jarvis/ui/web/frontend/src/i18n/locales/de.json b/jarvis/ui/web/frontend/src/i18n/locales/de.jsonindex b1d07682ff..49ae385f34 100644--- a/jarvis/ui/web/frontend/src/i18n/locales/de.json+++ b/jarvis/ui/web/frontend/src/i18n/locales/de.json@@ -626,6 +626,15 @@"attach_text_read": "Text gelesen","attach_not_described": "nicht beschrieben","attach_nothing": "Darin war nichts, was dieser Chat verwenden kann.",+ "typeahead_label": "Vorschläge",+ "typeahead_loading": "Suche…",+ "typeahead_empty": "Nichts passt",+ "typeahead_group_project": "In diesem Ordner",+ "typeahead_group_account": "Dein Konto",+ "typeahead_group_plugins": "Plugins",+ "typeahead_group_jarvis": "Jarvis-Skills",+ "typeahead_group_agents": "Subagenten",+ "typeahead_group_files": "Dateien und Ordner","send": "Senden","stop": "Durchgang stoppen","hint_connect": "{provider} ist noch nicht verbunden.",diff --git a/jarvis/ui/web/frontend/src/i18n/locales/en.json b/jarvis/ui/web/frontend/src/i18n/locales/en.jsonindex f06ce65da7..0b35b672e3 100644--- a/jarvis/ui/web/frontend/src/i18n/locales/en.json+++ b/jarvis/ui/web/frontend/src/i18n/locales/en.json@@ -626,6 +626,15 @@"attach_text_read": "text read","attach_not_described": "not described","attach_nothing": "That drop carried nothing this chat could use.",+ "typeahead_label": "Suggestions",+ "typeahead_loading": "Looking…",+ "typeahead_empty": "Nothing matches",+ "typeahead_group_project": "In this folder",+ "typeahead_group_account": "Your account",+ "typeahead_group_plugins": "Plugins",+ "typeahead_group_jarvis": "Jarvis skills",+ "typeahead_group_agents": "Subagents",+ "typeahead_group_files": "Files and folders","send": "Send","stop": "Stop the turn","hint_connect": "{provider} is not connected yet.",diff --git a/jarvis/ui/web/frontend/src/i18n/locales/es.json b/jarvis/ui/web/frontend/src/i18n/locales/es.jsonindex 02b441a811..978d02736d 100644--- a/jarvis/ui/web/frontend/src/i18n/locales/es.json+++ b/jarvis/ui/web/frontend/src/i18n/locales/es.json@@ -626,6 +626,15 @@"attach_text_read": "texto leído","attach_not_described": "sin descripción","attach_nothing": "Lo que soltaste no contenía nada que este chat pueda usar.",+ "typeahead_label": "Sugerencias",+ "typeahead_loading": "Buscando…",+ "typeahead_empty": "Nada coincide",+ "typeahead_group_project": "En esta carpeta",+ "typeahead_group_account": "Tu cuenta",+ "typeahead_group_plugins": "Plugins",+ "typeahead_group_jarvis": "Skills de Jarvis",+ "typeahead_group_agents": "Subagentes",+ "typeahead_group_files": "Archivos y carpetas","send": "Enviar","stop": "Detener el turno","hint_connect": "{provider} aún no está conectado.",diff --git a/tests/unit/agent_chat/test_typeahead.py b/tests/unit/agent_chat/test_typeahead.pynew file mode 100644index 0000000000..7ab71a1d0b--- /dev/null+++ b/tests/unit/agent_chat/test_typeahead.py@@ -0,0 +1,354 @@+"""The composer's typeahead — what "/", "@" and "$" list on each seat.++Every row must come from the disk the seat's runner reads: the folder's own+``.claude`` / ``.agents`` trees, the account's config dir, the installed+plugins, the file list git would show. Nothing typed by hand, nothing from a+seat that would not honour the gesture.+"""++from __future__ import annotations++import json+import shutil+import subprocess+from pathlib import Path++import pytest+from fastapi import FastAPI+from fastapi.testclient import TestClient++from jarvis.agent_chat import typeahead+from jarvis.agent_chat.runner_brain import explicit_skill+from jarvis.agent_chat.service import AgentChatService+from jarvis.agent_chat.store import AgentChatStore+from jarvis.ui.web.agent_chat_routes import router+++def _skill(root: Path, name: str, description: str) -> None:+ d = root / name+ d.mkdir(parents=True)+ (d / "SKILL.md").write_text(+ f"---\nname: {name}\ndescription: {description}\n---\n# {name}\n", encoding="utf-8"+ )+++def _md(path: Path, description: str = "") -> None:+ path.parent.mkdir(parents=True, exist_ok=True)+ body = f"---\ndescription: {description}\n---\nbody\n" if description else "body\n"+ path.write_text(body, encoding="utf-8")+++def account(tmp_path: Path, monkeypatch: pytest.MonkeyPatch) -> Path:+ """A Claude Code config dir standing in for the seat's account."""+ home = tmp_path / "account"+ home.mkdir()+ monkeypatch.setattr(typeahead, "claude_config_dir", lambda: home)+ return home+++def folder(tmp_path: Path) -> Path:+ cwd = tmp_path / "repo"+ cwd.mkdir()+ return cwd++[email protected](autouse=True)+def _fresh_walk_cache():+ typeahead.forget_folder()+ yield+ typeahead.forget_folder()+++# ------------------------------------------------------------- triggers+++def test_every_runner_the_catalog_can_resolve_has_a_trigger_row():+ """The route derives the composer's triggers from the runner; an unlisted+ runner would silently get no list at all."""+ for runner in ("claude-cli", "codex-cli", "agy-cli", "grok-cli", "api", "brain"):+ assert runner in typeahead.TRIGGERS_BY_RUNNER, runner+ assert typeahead.triggers_for("claude-cli") == ("/", "@")+ assert typeahead.triggers_for("codex-cli") == ("@", "$")+ assert typeahead.triggers_for("brain") == ("/",)+ assert typeahead.triggers_for("nope") == ()+++def test_a_trigger_the_seat_does_not_honour_answers_empty(folder: Path):+ assert typeahead.suggest(runner="api", cwd=folder, trigger="/") == {+ "trigger": "/",+ "items": [],+ "truncated": False,+ }+ assert typeahead.suggest(runner="claude-cli", cwd=folder, trigger="$")["items"] == []+++# --------------------------------------------------------- claude slash+++def test_claude_slash_lists_project_then_account_then_plugins(account: Path, folder: Path):+ _skill(folder / ".claude" / "skills", "deploy", "Ship it")+ _skill(folder / ".agents" / "skills", "deploy", "the mirrored twin — one row, not two")+ _md(folder / ".claude" / "commands" / "review.md", "Review the diff")+ _md(folder / ".claude" / "commands" / "README.md") # never a command+ _skill(account / "skills", "notes", "Write notes")+ _md(account / "commands" / "standup.md")++ install = account / "plugins" / "cache" / "market" / "github" / "abc"+ _skill(install / "skills", "issue", "Open an issue")+ _md(install / "commands" / "pr.md", "Open a PR")+ off = account / "plugins" / "cache" / "market" / "dark" / "abc"+ _skill(off / "skills", "hidden", "switched off")+ (account / "plugins").mkdir(exist_ok=True)+ (account / "plugins" / "installed_plugins.json").write_text(+ json.dumps(+ {+ "version": 2,+ "plugins": {+ "github@market": [{"scope": "user", "installPath": str(install)}],+ "dark@market": [{"scope": "user", "installPath": str(off)}],+ "gone@market": [{"scope": "user", "installPath": str(account / "nope")}],+ },+ }+ ),+ encoding="utf-8",+ )+ (account / "settings.json").write_text(+ json.dumps({"enabledPlugins": {"github@market": True, "dark@market": False}}),+ encoding="utf-8",+ )++ rows = typeahead.claude_slash(folder)+ assert [(r.value, r.group, r.kind) for r in rows] == [+ ("deploy", "project", "skill"),+ ("review", "project", "command"),+ ("notes", "account", "skill"),+ ("standup", "account", "command"),+ ("github:issue", "plugins", "skill"),+ ("github:pr", "plugins", "command"),+ ]+ by_value = {r.value: r for r in rows}+ assert by_value["deploy"].hint == "Ship it" # the project's own, not the twin's+ assert by_value["github:pr"].hint == "Open a PR"+++def test_frontmatter_reads_quoted_and_folded_descriptions(tmp_path: Path):+ quoted = tmp_path / "q.md"+ quoted.write_text('---\nname: "x"\ndescription: "Use when: things"\n---\n', encoding="utf-8")+ folded = tmp_path / "f.md"+ folded.write_text(+ "---\ndescription: >\n Line one\n line two.\nname: y\n---\n", encoding="utf-8"+ )+ plain = tmp_path / "p.md"+ plain.write_text("# no frontmatter\n", encoding="utf-8")+ assert typeahead._frontmatter(quoted) == {"name": "x", "description": "Use when: things"}+ assert typeahead._frontmatter(folded) == {"description": "Line one line two.", "name": "y"}+ assert typeahead._frontmatter(plain) == {}+++def test_slash_query_ranks_prefix_before_substring_before_hint(account: Path, folder: Path):+ _skill(folder / ".claude" / "skills", "commit", "Commit the work")+ _skill(folder / ".claude" / "skills", "autocommit", "Commit on a timer")+ _skill(folder / ".claude" / "skills", "release", "Tag and commit a version")+ _skill(folder / ".claude" / "skills", "deploy", "Ship it")+ items = typeahead.suggest(runner="claude-cli", cwd=folder, trigger="/", query="commit")["items"]+ assert [i["value"] for i in items] == ["commit", "autocommit", "release"]+++# ------------------------------------------------------------- agents+++def test_mention_on_claude_lists_agents_before_files(account: Path, folder: Path):+ _md(folder / ".claude" / "agents" / "reviewer.md", "Reviews code")+ _md(folder / ".claude" / "agents" / "INDEX.md")+ _md(account / "agents" / "planner.md")+ (folder / "reviewer_notes.txt").write_text("x", encoding="utf-8")++ rows = typeahead.suggest(runner="claude-cli", cwd=folder, trigger="@", query="review")["items"]+ assert rows[0] == {+ "value": "reviewer",+ "label": "reviewer",+ "hint": "Reviews code",+ "kind": "agent",+ "group": "agents",+ }+ # The definition file itself is a file of the folder too — nearer names first.+ assert [r["value"] for r in rows[1:]] == ["reviewer_notes.txt", ".claude/agents/reviewer.md"]+ everything = typeahead.suggest(runner="claude-cli", cwd=folder, trigger="@")["items"]+ assert [r["value"] for r in everything if r["kind"] == "agent"] == ["reviewer", "planner"]+++# -------------------------------------------------------------- codex $+++def test_codex_skill_refs_read_the_folder_then_codex_home(+ folder: Path, tmp_path: Path, monkeypatch: pytest.MonkeyPatch+):+ home = tmp_path / "codex-home"+ monkeypatch.setattr(typeahead, "codex_home", lambda: home)+ _skill(folder / ".agents" / "skills", "grill-me", "Interview me")+ _skill(home / "skills", "design-md", "Design doc")+ _skill(home / "skills" / "cloud", "run-basics", "One level down is fine too")+ rows = typeahead.suggest(runner="codex-cli", cwd=folder, trigger="$")["items"]+ assert [(r["value"], r["group"]) for r in rows] == [+ ("grill-me", "project"),+ ("design-md", "account"),+ ("run-basics", "account"),+ ]+++# --------------------------------------------------------------- files+++def test_file_walk_skips_build_trees_and_ranks_names_first(folder: Path):+ (folder / "src").mkdir()+ (folder / "src" / "app.py").write_text("x", encoding="utf-8")+ (folder / "src" / "happy.py").write_text("x", encoding="utf-8")+ (folder / "vendor" / "x").mkdir(parents=True)+ (folder / "vendor" / "x" / "app.py").write_text("x", encoding="utf-8")+ (folder / "node_modules" / "m").mkdir(parents=True)+ (folder / "node_modules" / "m" / "app.py").write_text("x", encoding="utf-8")+ (folder / ".secret").write_text("x", encoding="utf-8")+ (folder / "README.md").write_text("x", encoding="utf-8")++ top = [i.value for i in typeahead.file_suggestions(folder, "")]+ assert top[:3] == ["src/", "vendor/", "README.md"] # folders first, then files, near first+ assert not any("node_modules" in v or ".secret" in v for v in top)++ ranked = [i.value for i in typeahead.file_suggestions(folder, "app")]+ assert ranked == ["src/app.py", "vendor/x/app.py", "src/happy.py"]++ row = typeahead.file_suggestions(folder, "happy")[0]+ assert (row.label, row.hint, row.kind, row.group) == ("happy.py", "src", "file", "files")+ assert typeahead.file_suggestions(folder, "src")[0].kind == "folder"++[email protected](shutil.which("git") is None, reason="git is not installed")+def test_a_checkout_lists_what_git_would_show(folder: Path):+ """Tracked plus untracked-but-not-ignored: build output never appears."""+ subprocess.run(["git", "init", "-q"], cwd=folder, check=True)+ (folder / ".gitignore").write_text("build/\n", encoding="utf-8")+ (folder / "src").mkdir()+ (folder / "src" / "main.py").write_text("x", encoding="utf-8")+ (folder / "build").mkdir()+ (folder / "build" / "out.js").write_text("x", encoding="utf-8")+ (folder / "untracked.txt").write_text("x", encoding="utf-8")+ subprocess.run(["git", "add", "src"], cwd=folder, check=True)++ listed = typeahead._git_entries(folder)+ assert listed is not None+ entries, truncated = listed+ assert truncated is False+ paths = [e.path for e in entries]+ assert "src/" in paths and "src/main.py" in paths and "untracked.txt" in paths+ assert not any(p.startswith("build") for p in paths)+ assert paths.index("src/") < paths.index("src/main.py")+++def test_the_walk_is_cached_per_folder(folder: Path, monkeypatch: pytest.MonkeyPatch):+ (folder / "a.txt").write_text("x", encoding="utf-8")+ assert [i.value for i in typeahead.file_suggestions(folder, "")] == ["a.txt"]+ (folder / "b.txt").write_text("x", encoding="utf-8")+ assert [i.value for i in typeahead.file_suggestions(folder, "")] == ["a.txt"] # still cached+ typeahead.forget_folder(folder)+ assert [i.value for i in typeahead.file_suggestions(folder, "")] == ["a.txt", "b.txt"]+++# -------------------------------------------------------------- jarvis /+++def test_jarvis_surface_lists_the_registry_by_slug(tmp_path: Path, monkeypatch: pytest.MonkeyPatch):+ class _FM:+ description = "Morning briefing"++ class _Skill:+ name = "Morning Routine"+ path = tmp_path / "morning-routine" / "SKILL.md"+ frontmatter = _FM()++ class _Registry:+ def list_active(self):+ return [_Skill()]++ class _Ctx:+ registry = _Registry()++ import jarvis.skills.skill_context as skill_context++ monkeypatch.setattr(skill_context, "try_get_skill_context", lambda: _Ctx())+ rows = typeahead.suggest(runner="brain", cwd=None, trigger="/")["items"]+ assert rows == [+ {+ "value": "morning-routine",+ "label": "Morning Routine",+ "hint": "Morning briefing",+ "kind": "skill",+ "group": "jarvis",+ }+ ]+++ ("text", "expected"),+ [+ ("/morning-routine", ("morning-routine", "")),+ ("/deploy now please", ("deploy", "now please")),+ (" /a:b.c-d\nmore", ("a:b.c-d", "more")),+ ("hello /deploy", None),+ ("/", None),+ ("", None),+ ("/ deploy", None),+ ],+)+def test_explicit_skill_reads_a_leading_slash_only(text, expected):+ assert explicit_skill(text) == expected+++# ---------------------------------------------------------------- route+++def _app(tmp_path: Path) -> FastAPI:+ app = FastAPI()+ app.include_router(router)+ app.state.agent_chat = None+ app.state.agent_chat_factory = lambda: AgentChatService(+ AgentChatStore(tmp_path / "db.sqlite"), default_cwd=lambda: str(tmp_path)+ )+ return app+++def test_typeahead_route_resolves_the_seat_and_reads_the_folder(+ tmp_path: Path, account: Path, folder: Path, monkeypatch: pytest.MonkeyPatch+):+ import jarvis.ui.web.agent_chat_routes as routes++ seen: list[tuple[str, str]] = []++ def _resolve(provider: str, *, surface: str = "agent") -> str:+ seen.append((provider, surface))+ return "claude-cli"++ monkeypatch.setattr(routes, "resolve_runner", _resolve)+ _skill(folder / ".claude" / "skills", "deploy", "Ship it")++ with TestClient(_app(tmp_path)) as client:+ body = client.get(+ "/api/agent-chat/typeahead",+ params={+ "trigger": "/",+ "surface": "agent",+ "provider": "claude-api",+ "cwd": str(folder),+ },+ ).json()+ assert seen == [("claude-api", "agent")]+ assert body["trigger"] == "/"+ assert [i["value"] for i in body["items"]] == ["deploy"]++ # A folder that does not exist is a 400, not a walk of nothing.+ res = client.get(+ "/api/agent-chat/typeahead",+ params={"trigger": "@", "provider": "claude-api", "cwd": str(folder / "missing")},+ )+ assert res.status_code == 400