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.

feat(agentic-ide): spoken instructions reach the addressed terminal

Ruben Lütke9d6097a94e12
diff --git a/jarvis/agentic_ide/folders.py b/jarvis/agentic_ide/folders.py
index b25a34579f..b3cf212dcd 100644
--- a/jarvis/agentic_ide/folders.py
+++ b/jarvis/agentic_ide/folders.py
@@ -106,6 +106,8 @@ class ProjectProfile:
instruction_files: list[str] = field(default_factory=list)
top_level_dirs: list[str] = field(default_factory=list)
skills: list[str] = field(default_factory=list)
+ subagents: list[str] = field(default_factory=list)
+ commands: list[str] = field(default_factory=list)
note: str = ""
def to_dict(self) -> dict:
@@ -125,10 +127,21 @@ class ProjectProfile:
out.append("Agent instructions present: " + ", ".join(self.instruction_files))
if self.top_level_dirs:
out.append("Top-level folders: " + ", ".join(self.top_level_dirs))
- if self.skills:
- shown = ", ".join(self.skills[:20])
- more = "" if len(self.skills) <= 20 else f" (+{len(self.skills) - 20} more)"
- out.append(f"Skills defined here ({len(self.skills)}): {shown}{more}")
+ # What the agents in this repo can be ASKED for. Knowing that a repo
+ # defines a `publish-new-version` skill or a `code-reviewer` subagent is
+ # the difference between "write a release script" and "run the release
+ # skill" — the second is what the user meant and what the agent in the
+ # pane is actually equipped to do.
+ for label, items in (
+ ("Skills defined here", self.skills),
+ ("Subagents defined here", self.subagents),
+ ("Slash commands defined here", self.commands),
+ ):
+ if not items:
+ continue
+ shown = ", ".join(items[:20])
+ more = "" if len(items) <= 20 else f" (+{len(items) - 20} more)"
+ out.append(f"{label} ({len(items)}): {shown}{more}")
return out
@@ -339,10 +352,18 @@ def _git_branch(root: Path) -> str | None:
return text[:12] or None # detached HEAD
-def _collect_skills(root: Path) -> list[str]:
- """Skill names defined in this repo (``.claude/skills`` / ``.agents/skills``)."""
+def _collect_named(root: Path, kind: str, *, files: bool = False) -> list[str]:
+ """Names defined under ``.claude/<kind>`` / ``.agents/<kind>``.
+
+ Both trees are read because the repo convention is that they mirror each
+ other (``.claude`` canonical, ``.agents`` the tool-neutral twin), and a
+ contributor may have only one of them checked out. Duplicates collapse.
+
+ Skills and subagents are directories; slash commands are Markdown files, so
+ ``files`` switches which entries count and strips the ``.md`` suffix.
+ """
found: list[str] = []
- for base in (root / ".claude" / "skills", root / ".agents" / "skills"):
+ for base in (root / ".claude" / kind, root / ".agents" / kind):
if not base.is_dir():
continue
try:
@@ -350,14 +371,31 @@ def _collect_skills(root: Path) -> list[str]:
for item in it:
if len(found) >= _MAX_SKILLS:
break
- if item.is_dir(follow_symlinks=False) and not _is_hidden(item.name):
- if item.name not in found:
- found.append(item.name)
+ if _is_hidden(item.name):
+ continue
+ try:
+ is_file = item.is_file(follow_symlinks=False)
+ is_dir = item.is_dir(follow_symlinks=False)
+ except OSError:
+ continue
+ if files and is_file and item.name.endswith(".md"):
+ name = item.name[:-3]
+ elif not files and is_dir:
+ name = item.name
+ else:
+ continue
+ if name not in found:
+ found.append(name)
except OSError:
continue
return found
+def _collect_skills(root: Path) -> list[str]:
+ """Skill names defined in this repo (``.claude/skills`` / ``.agents/skills``)."""
+ return _collect_named(root, "skills")
+
+
def probe_project(path: str | Path) -> ProjectProfile:
"""Shallow profile of a folder — one scandir plus a few existence checks."""
root = Path(path).expanduser()
@@ -408,6 +446,12 @@ def probe_project(path: str | Path) -> ProjectProfile:
profile.instruction_files = [f for f in _INSTRUCTION_FILES if f in names]
profile.top_level_dirs = sorted(dirs, key=str.lower)
profile.skills = _collect_skills(root)
+ # Subagents and slash commands are both single Markdown files (one per
+ # definition); skills are directories with a SKILL.md inside.
+ profile.subagents = [
+ name for name in _collect_named(root, "agents", files=True) if name != "INDEX"
+ ]
+ profile.commands = _collect_named(root, "commands", files=True)
return profile
diff --git a/jarvis/brain/manager.py b/jarvis/brain/manager.py
index 4575cd527d..a754397bf0 100644
--- a/jarvis/brain/manager.py
+++ b/jarvis/brain/manager.py
@@ -1080,6 +1080,36 @@ def _is_spawn_feature_reference(user_text: str) -> bool:
return bool(_SPAWN_FEATURE_RE.search(user_text or ""))
+def _prompt_sent_line(terminal: str, files: list[str], lang: str) -> str:
+ """Spoken confirmation that an Agentic-IDE terminal received the prompt.
+
+ Deliberately short and pane-named: in a four-pane workspace the only thing
+ the user needs to hear is WHICH agent got it. Naming the attached file when
+ there is exactly one is worth the extra second — it is also the fastest way
+ for the user to catch a wrong file before the agent acts on it.
+ """
+ from jarvis.voice.action_phrases import action_phrase
+
+ if len(files) == 1:
+ return action_phrase(
+ "ide_prompt_sent_one_file", lang, terminal=terminal, file=files[0]
+ )
+ if files:
+ return action_phrase(
+ "ide_prompt_sent_files", lang, terminal=terminal, count=len(files)
+ )
+ return action_phrase("ide_prompt_sent", lang, terminal=terminal)
+
+
+def _terminal_not_running_line(terminal: str, status: str, lang: str) -> str:
+ """Honest readback when the addressed pane is not accepting input."""
+ from jarvis.voice.action_phrases import action_phrase
+
+ return action_phrase(
+ "ide_terminal_not_running", lang, terminal=terminal, status=status
+ )
+
+
# Conversational coaching: "help me [get better at a soft / cognitive /
# conversational skill]" — asking, thinking, phrasing, deciding, understanding,
# expressing, communicating. This is CONVERSATION (Jarvis answers inline and
@@ -5569,6 +5599,113 @@ class BrainManager:
)
return f"Öffne {label}." if is_de else f"Opening {label}." # i18n-allow
+ async def _run_agentic_ide_fast_path(
+ self,
+ user_text: str,
+ *,
+ trace_id: UUID | None = None,
+ ) -> str | None:
+ """Deliver a spoken instruction to the addressed Agentic-IDE terminal.
+
+ The Agentic IDE's promise is that talking to a named pane makes that pane
+ work. Leaving that to the LLM's tool choice made it unreliable in exactly
+ the situation it matters most: on 2026-07-25 (voice session 15:47) "let
+ Kai do a deep dive" was swallowed by the force-spawn heuristic and became
+ an invisible background mission, and even without that collision a router
+ that is busy deciding between a dozen tools sometimes just answers in
+ prose. So the delivery is deterministic here, ahead of force-spawn — the
+ same shape as the navigation and local-action fast-paths.
+
+ What is NOT deterministic is the prompt itself: the composer
+ (``agentic_ide.prompt_composer``) rewrites the spoken sentence into a
+ briefed task with ``@file`` references. That is one bounded provider call
+ with a regex fallback, so the instruction is delivered either way.
+
+ Returns ``None`` whenever this turn is not an addressed terminal, so the
+ normal path runs untouched.
+ """
+ try:
+ from jarvis.agentic_ide import intent as ide_intent
+ from jarvis.agentic_ide.session import (
+ AGENT_DISPLAY,
+ SessionError,
+ get_registry,
+ )
+ except Exception: # noqa: BLE001 - optional surface
+ return None
+
+ try:
+ registry = get_registry()
+ session = registry.session
+ if session is None:
+ return None
+ found = ide_intent.detect(
+ user_text, names=[t.name for t in session.terminals]
+ )
+ except Exception: # noqa: BLE001 - detection must never break a turn
+ return None
+ if found is None:
+ return None
+ # Naming the spawn vehicle outranks the workspace: "spawn an agent that
+ # helps Kai" is a genuine background-worker request even with a
+ # workspace open. Same test the spawn gate and ``intent.owns_turn`` use,
+ # so the three cannot drift into disagreeing about one utterance.
+ from jarvis.brain.spawn_gate import names_spawn_vehicle
+
+ if names_spawn_vehicle(user_text):
+ return None
+
+ out_lang = resolve_output_language(
+ self._reply_language,
+ "unknown",
+ user_text,
+ default=DEFAULT_LOCALE,
+ conversation_language=self._conversation_language,
+ )
+
+ # A question about a pane is read-only: answer it from what that pane
+ # printed, and let the normal brain path phrase the answer with the
+ # focus-context block (which already carries the transcript tail).
+ if found.kind == ide_intent.KIND_REPORT:
+ return None
+
+ term = session.find(found.terminal)
+ if term is None:
+ return None
+ if term.status != "live" or not term.pty_id:
+ log.info(
+ "Agentic IDE fast-path: %s is %s — nothing sent",
+ term.name, term.status,
+ )
+ return _terminal_not_running_line(term.name, term.status, out_lang)
+
+ from jarvis.agentic_ide.prompt_composer import compose
+
+ composed = await compose(
+ user_text,
+ session=session,
+ terminal_name=term.name,
+ agent_display=AGENT_DISPLAY.get(term.agent, term.agent),
+ instruction=found.instruction,
+ )
+ if not composed.text:
+ return None
+
+ try:
+ await registry.send_prompt(term.name, composed.text)
+ except SessionError as exc:
+ log.info("Agentic IDE fast-path could not send to %s: %s", term.name, exc)
+ return str(exc)
+ except Exception: # noqa: BLE001 - never crash the turn over a pane
+ log.warning("Agentic IDE fast-path failed", exc_info=True)
+ return None
+
+ log.info(
+ "Agentic IDE fast-path -> %s (composed_by=%s, files=%d)",
+ term.name, composed.composed_by, len(composed.files),
+ )
+ return _prompt_sent_line(term.name, composed.files, out_lang)
+
def _is_explicit_heavy_request(self, user_text: str) -> bool:
"""Return whether the user semantically requested a heavy worker."""
text = (user_text or "").strip()
@@ -5689,6 +5826,28 @@ class BrainManager:
"force-spawn skipped: auto-spawn feature named, not commanded — inline"
)
return False
+ # An open Agentic-IDE terminal that is being ADDRESSED owns the turn.
+ # Checked BEFORE the explicit-trigger hoist for the same reason the two
+ # guards above are: the hoist matches a DEPTH marker, and "let Kai do a
+ # deep dive" carries one while meaning the exact opposite of a background
+ # mission. Live bug 2026-07-25 (voice session 15:47): that sentence
+ # dispatched a Codex worker into a fresh worktree while the terminal
+ # called Kai sat idle and the user saw nothing happen.
+ #
+ # ``owns_turn`` stands down when the user NAMES the spawn vehicle, so an
+ # explicit "spawn an agent that helps Kai" still force-spawns — the
+ # workspace claims ambiguous turns, never explicit delegation.
+ try:
+ from jarvis.agentic_ide.intent import owns_turn as _ide_owns_turn
+
+ if _ide_owns_turn(t):
+ log.info(
+ "force-spawn skipped: an open Agentic-IDE terminal is "
+ "addressed — the workspace handles this turn"
+ )
+ return False
+ except Exception: # noqa: BLE001 — optional surface, never breaks routing
+ pass
# User mandate (2026-06-15, "when I say subagent it MUST spawn"): an
# EXPLICIT heavy-work trigger that NAMES the execution vehicle
# ("subagent", "spawn", "openclaw", "delegate") is an UNAMBIGUOUS request
@@ -7987,6 +8146,26 @@ class BrainManager:
)
return nav_reply
+ # Agentic-IDE fast-path: an instruction aimed at a named terminal of the
+ # open coding workspace is DELIVERED to that terminal, deterministically.
+ # Placed before force-spawn — whose depth-marker hoist used to swallow
+ # exactly these turns (live bug 2026-07-25: "let Kai do a deep dive"
+ # dispatched a background mission while Kai sat idle) — and before the
+ # capability gate. Placed AFTER navigation so a section command still
+ # moves the UI even when a pane happens to share that word. Returns None
+ # on every turn that does not address a terminal.
+ ide_reply = await self._run_agentic_ide_fast_path(
+ user_text, trace_id=turn_trace_id,
+ )
+ if ide_reply is not None:
+ await self._record_response_side_effects(
+ user_text=user_text,
+ response_text=ide_reply,
+ use_history=use_history,
+ trace_id=turn_trace_id,
+ )
+ return ide_reply
+
# Agent-C (capability-coupling): pre-generation capability gate.
# If the utterance looks like an action request but no registered
# capability covers it, return a deterministic "not supported" reply
diff --git a/jarvis/brain/spawn_gate.py b/jarvis/brain/spawn_gate.py
index b6cae083e4..ccb54ecfc9 100644
--- a/jarvis/brain/spawn_gate.py
+++ b/jarvis/brain/spawn_gate.py
@@ -174,6 +174,34 @@ class DelegationOfferWindow:
OFFER_WINDOW = DelegationOfferWindow()
+def names_spawn_vehicle(user_text: str) -> bool:
+ """True when the utterance names the background-agent vehicle explicitly.
+
+ Public because the Agentic-IDE turn detector needs the SAME answer this gate
+ uses: a workspace terminal may claim a turn only when the user did *not* ask
+ for a background agent. Sharing the one pattern keeps "spawn an agent that
+ helps Kai" a spawn while "let Kai do it" reaches Kai.
+ """
+ return bool(_DELEGATION_MARKER_RE.search((user_text or "").strip()))
+
+
+def _agentic_ide_claims_turn(text: str) -> bool:
+ """True when an open Agentic-IDE terminal is being addressed instead.
+
+ An agent already runs in a pane the user can see and named; typing the work
+ into it is what they asked for, and dispatching an invisible background
+ worker instead is the live 2026-07-25 defect this guard closes. Import is
+ local and failure-tolerant: the workspace is an optional surface and must
+ never be able to break spawn routing.
+ """
+ try:
+ from jarvis.agentic_ide.intent import owns_turn
+
+ return owns_turn(text)
+ except Exception: # noqa: BLE001 - optional surface, never fatal to routing
+ return False
+
+
def llm_spawn_allowed(user_text: str) -> bool:
"""Gate an LLM-chosen spawn tool call against the user's ACTUAL turn.
@@ -189,6 +217,17 @@ def llm_spawn_allowed(user_text: str) -> bool:
if _is_decline_or_feature_talk(text):
log.info("spawn gate: decline / feature talk — spawn blocked")
return False
+ # An addressed Agentic-IDE terminal outranks a spawn. Checked before the
+ # delegation marker so a depth word inside a terminal instruction ("let Kai
+ # do a deep dive") cannot dispatch a background mission — but AFTER the
+ # decline guard, and ``owns_turn`` itself stands down when the user named the
+ # vehicle, so an explicit "spawn an agent" still spawns.
+ if _agentic_ide_claims_turn(text):
+ log.info(
+ "spawn gate: an open Agentic-IDE terminal is addressed — "
+ "the workspace handles this turn, no background agent"
+ )
+ return False
if _DELEGATION_MARKER_RE.search(text):
OFFER_WINDOW.disarm()
return True
@@ -230,4 +269,5 @@ __all__ = [
"SPAWN_VEHICLE_TOOL_NAMES",
"DelegationOfferWindow",
"llm_spawn_allowed",
+ "names_spawn_vehicle",
]
diff --git a/jarvis/ui/web/frontend/package-lock.json b/jarvis/ui/web/frontend/package-lock.json
index fbbe2cd226..e555483bc1 100644
--- a/jarvis/ui/web/frontend/package-lock.json
+++ b/jarvis/ui/web/frontend/package-lock.json
@@ -18,6 +18,7 @@
"@xterm/addon-canvas": "^0.7.0",
"@xterm/addon-fit": "^0.10.0",
"@xterm/addon-search": "^0.16.0",
+ "@xterm/addon-unicode11": "^0.9.0",
"@xterm/addon-web-links": "^0.11.0",
"@xterm/xterm": "^5.5.0",
"@xyflow/react": "^12.10.2",
@@ -2682,6 +2683,12 @@
"integrity": "sha512-9OeuBFu0/uZJPu+9AHKY6g/w0Czyb/Ut0A5t79I4ULoU4IfU5BEpPFVGQxP4zTTMdfZEYkVIRYbHBX1xWwjeSA==",
"license": "MIT"
},
+ "node_modules/@xterm/addon-unicode11": {
+ "version": "0.9.0",
+ "resolved": "https://registry.npmjs.org/@xterm/addon-unicode11/-/addon-unicode11-0.9.0.tgz",
+ "integrity": "sha512-FxDnYcyuXhNl+XSqGZL/t0U9eiNb/q3EWT5rYkQT/zuig8Gz/VagnQANKHdDWFM2lTMk9ly0EFQxxxtZUoRetw==",
+ "license": "MIT"
+ },
"node_modules/@xterm/addon-web-links": {
"version": "0.11.0",
"resolved": "https://registry.npmjs.org/@xterm/addon-web-links/-/addon-web-links-0.11.0.tgz",
diff --git a/jarvis/ui/web/frontend/package.json b/jarvis/ui/web/frontend/package.json
index a4f1c5f61c..2d580f2b20 100644
--- a/jarvis/ui/web/frontend/package.json
+++ b/jarvis/ui/web/frontend/package.json
@@ -20,6 +20,7 @@
"@xterm/addon-canvas": "^0.7.0",
"@xterm/addon-fit": "^0.10.0",
"@xterm/addon-search": "^0.16.0",
+ "@xterm/addon-unicode11": "^0.9.0",
"@xterm/addon-web-links": "^0.11.0",
"@xterm/xterm": "^5.5.0",
"@xyflow/react": "^12.10.2",
diff --git a/jarvis/ui/web/frontend/src/components/agentic/AgenticGrid.test.tsx b/jarvis/ui/web/frontend/src/components/agentic/AgenticGrid.test.tsx
index 4a89000e33..6a6a473d0a 100644
--- a/jarvis/ui/web/frontend/src/components/agentic/AgenticGrid.test.tsx
+++ b/jarvis/ui/web/frontend/src/components/agentic/AgenticGrid.test.tsx
@@ -101,6 +101,8 @@ function sessionWith(panes: Array<[string, number]>): SessionState {
instruction_files: [],
top_level_dirs: [],
skills: [],
+ subagents: [],
+ commands: [],
note: "",
},
created_at: 0,
diff --git a/jarvis/ui/web/frontend/src/views/AgenticIdeView.test.tsx b/jarvis/ui/web/frontend/src/views/AgenticIdeView.test.tsx
index e3be21a8c3..697f82b2a2 100644
--- a/jarvis/ui/web/frontend/src/views/AgenticIdeView.test.tsx
+++ b/jarvis/ui/web/frontend/src/views/AgenticIdeView.test.tsx
@@ -79,6 +79,8 @@ function sessionWith(names: string[], focus = false): api.SessionState {
instruction_files: ["CLAUDE.md"],
top_level_dirs: ["src"],
skills: [],
+ subagents: [],
+ commands: [],
note: "",
},
created_at: 0,
diff --git a/jarvis/voice/action_phrases.py b/jarvis/voice/action_phrases.py
index a708311b44..58da6cdff2 100644
--- a/jarvis/voice/action_phrases.py
+++ b/jarvis/voice/action_phrases.py
@@ -302,6 +302,30 @@ _PHRASES: dict[str, dict[str, str]] = {
"en": "I am not sure what to write to the wiki. Please say it again with the content.",
"es": "No tengo claro qué escribir en la wiki; dímelo otra vez con el contenido.",
},
+ # Agentic-IDE terminal delivery (deterministic fast path). Naming the pane
+ # back is the whole confirmation the user gets that the right agent was
+ # addressed — a spoken "sent" without the call-sign would be useless in a
+ # four-pane workspace.
+ "ide_prompt_sent": {
+ "de": "Ist bei {terminal}.", # i18n-allow
+ "en": "Sent to {terminal}.",
+ "es": "Enviado a {terminal}.",
+ },
+ "ide_prompt_sent_files": {
+ "de": "Ist bei {terminal}, mit {count} Dateien dazu.", # i18n-allow
+ "en": "Sent to {terminal}, with {count} files attached.",
+ "es": "Enviado a {terminal}, con {count} archivos adjuntos.",
+ },
+ "ide_prompt_sent_one_file": {
+ "de": "Ist bei {terminal}, samt {file}.", # i18n-allow
+ "en": "Sent to {terminal}, along with {file}.",
+ "es": "Enviado a {terminal}, junto con {file}.",
+ },
+ "ide_terminal_not_running": {
+ "de": "{terminal} läuft gerade nicht ({status}) — ich habe nichts geschickt.", # i18n-allow
+ "en": "{terminal} is not running right now ({status}) — I sent nothing.",
+ "es": "{terminal} no está en marcha ahora ({status}) — no envié nada.",
+ },
}
diff --git a/tests/unit/agentic_ide/test_prompt_composer.py b/tests/unit/agentic_ide/test_prompt_composer.py
new file mode 100644
index 0000000000..6a7187f373
--- /dev/null
+++ b/tests/unit/agentic_ide/test_prompt_composer.py
@@ -0,0 +1,176 @@
+"""Guards for the spoken-instruction → agent-prompt composer.
+
+The composer's contract is that the instruction ALWAYS gets delivered. A user
+with no API key at all, a depleted provider, or a slow one must still see their
+words reach the terminal — just phrased less well. So the tests here are mostly
+about the unhappy paths: they are the ones that decide whether the feature works
+for an arbitrary downloader (§3) or only on a machine like the maintainer's.
+"""
+from __future__ import annotations
+
+from dataclasses import dataclass, field
+from pathlib import Path
+
+import pytest
+
+from jarvis.agentic_ide import file_index, prompt_composer
+
+
+@dataclass
+class _Profile:
+ """Minimal stand-in for ProjectProfile — only what the composer reads."""
+
+ lines: list[str] = field(default_factory=lambda: ["Folder: /work/project"])
+
+ def summary_lines(self) -> list[str]:
+ return self.lines
+
+
+@dataclass
+class _Session:
+ folder: str
+ profile: _Profile = field(default_factory=_Profile)
+
+
+def workspace(tmp_path: Path) -> _Session:
+ (tmp_path / "jarvis" / "plugins" / "wake").mkdir(parents=True)
+ (tmp_path / "jarvis" / "plugins" / "wake" / "vosk_kws_provider.py").write_text("x")
+ file_index.reset_cache()
+ return _Session(folder=str(tmp_path))
+
+
+def _prime(session: _Session) -> None:
+ """Build the index synchronously so the test does not race the thread."""
+ file_index._CACHE[str(Path(session.folder))] = file_index.build_index( # noqa: SLF001
+ session.folder
+ )
+
+
+async def test_no_provider_still_delivers_a_cleaned_instruction(
+ workspace: _Session, monkeypatch: pytest.MonkeyPatch
+) -> None:
+ """With every provider dead the words still reach the agent."""
+ _prime(workspace)
+
+ async def _boom(**_kwargs: object) -> str:
+ raise RuntimeError("no provider configured")
+
+ monkeypatch.setattr(prompt_composer, "_llm_compose", _boom)
+
+ result = await prompt_composer.compose(
+ "kannst du mal ähm bitte den vosk wake provider angucken", # i18n-allow: German speech input under test
+ session=workspace,
+ terminal_name="Kai",
+ )
+ assert result.composed_by == "fallback"
+ assert result.text, "the instruction must never be dropped"
+ # Speech filler is gone, the task survives.
+ assert "ähm" not in result.text # i18n-allow: the German filler under test
+ assert "vosk" in result.text.lower()
+ # And the file it pointed at came along.
+ assert "@jarvis/plugins/wake/vosk_kws_provider.py" in result.text
+
+
+async def test_a_timeout_falls_back_rather_than_hanging(
+ workspace: _Session, monkeypatch: pytest.MonkeyPatch
+) -> None:
+ _prime(workspace)
+
+ async def _slow(**_kwargs: object) -> str:
+ import asyncio
+
+ await asyncio.sleep(60)
+ return "never"
+
+ monkeypatch.setattr(prompt_composer, "_llm_compose", _slow)
+ monkeypatch.setattr(prompt_composer, "COMPOSE_TIMEOUT_S", 0.05)
+
+ result = await prompt_composer.compose(
+ "schau dir den vosk provider an", session=workspace, terminal_name="Kai"
+ )
+ assert result.composed_by == "fallback"
+ assert "timed out" in result.note
+
+
+async def test_invented_file_references_are_stripped(
+ workspace: _Session, monkeypatch: pytest.MonkeyPatch
+) -> None:
+ """A hallucinated @path costs the agent a wasted turn — it must not ship."""
+ _prime(workspace)
+
+ async def _hallucinate(**_kwargs: object) -> str:
+ return (
+ "Review the wake word detection. "
+ "@jarvis/plugins/wake/vosk_kws_provider.py @jarvis/does/not/exist.py"
+ )
+
+ monkeypatch.setattr(prompt_composer, "_llm_compose", _hallucinate)
+
+ result = await prompt_composer.compose(
+ "review the wake word detection", session=workspace, terminal_name="Kai"
+ )
+ assert result.composed_by == "llm"
+ assert result.files == ["jarvis/plugins/wake/vosk_kws_provider.py"]
+ assert "@jarvis/does/not/exist.py" not in result.text
+ # The name survives as plain text — the agent can still read the intent.
+ assert "jarvis/does/not/exist.py" in result.text
+
+
+async def test_a_path_escaping_the_workspace_is_refused(
+ workspace: _Session, monkeypatch: pytest.MonkeyPatch
+) -> None:
+ _prime(workspace)
+
+ async def _escape(**_kwargs: object) -> str:
+ return "Look at @../../../etc/passwd and @/etc/shadow"
+
+ monkeypatch.setattr(prompt_composer, "_llm_compose", _escape)
+
+ result = await prompt_composer.compose(
+ "look at the config", session=workspace, terminal_name="Kai"
+ )
+ assert result.files == []
+
+
+async def test_a_fenced_or_quoted_answer_is_unwrapped(
+ workspace: _Session, monkeypatch: pytest.MonkeyPatch
+) -> None:
+ _prime(workspace)
+
+ async def _fenced(**_kwargs: object) -> str:
+ return "```\nReview the wake word detection.\n```"
+
+ monkeypatch.setattr(prompt_composer, "_llm_compose", _fenced)
+
+ result = await prompt_composer.compose(
+ "review the wake word detection", session=workspace, terminal_name="Kai"
+ )
+ assert result.text == "Review the wake word detection."
+
+
+async def test_use_llm_false_sends_the_text_through(workspace: _Session) -> None:
+ """The typed prompt bar must not have its wording rewritten behind the user."""
+ _prime(workspace)
+ result = await prompt_composer.compose(
+ "run the tests", session=workspace, terminal_name="Kai", use_llm=False
+ )
+ assert result.composed_by == "raw"
+ assert result.text.startswith("run the tests")
+
+
+async def test_an_index_that_is_not_ready_yet_does_not_block(
+ workspace: _Session, monkeypatch: pytest.MonkeyPatch
+) -> None:
+ """A workspace whose walk is still running ships without references."""
+ file_index.reset_cache()
+
+ async def _echo(**kwargs: object) -> str:
+ assert kwargs["candidates"] == []
+ return "Review the wake word detection."
+
+ monkeypatch.setattr(prompt_composer, "_llm_compose", _echo)
+ result = await prompt_composer.compose(
+ "review the vosk wake provider", session=workspace, terminal_name="Kai"
+ )
+ assert result.text == "Review the wake word detection."