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): per-pane maximize, split right/down, and a guarded close

Ruben Lütke727954681190
diff --git a/jarvis/agentic_ide/context.py b/jarvis/agentic_ide/context.py
index 8affb62d74..a1d2c34597 100644
--- a/jarvis/agentic_ide/context.py
+++ b/jarvis/agentic_ide/context.py
@@ -7,14 +7,24 @@ running in which pane, and what each of them last printed. Without that, "is
Mika stuck?" is unanswerable and the assistant guesses — the failure mode this
block exists to prevent.
+Two things live here, and the distinction matters:
+
+* **A role directive.** Focus mode is not a hint, it is a different assistant:
+ an agentic-coding partner for this one repository. It plans work with the
+ user, decides which pane should do what, and hands the work over — it does not
+ do the coding itself and does not start invisible background agents. Stating
+ that explicitly is what stopped the live 2026-07-25 failure, where "let Kai do
+ a deep dive" dispatched a background mission while Kai sat idle. The
+ deterministic guards (``intent.owns_turn``, consulted by the router's
+ force-spawn check and the spawn gate) are the enforcement; this text is what
+ makes the model *want* the right thing in the first place, so a phrasing the
+ regex misses still lands correctly.
+* **The facts.** Folder, stack, branch, panes, and what each pane last printed.
+
Cost discipline (AP-9 / AP-26): building the block touches nothing but
in-memory state — the session's cached project profile and each terminal's ring
buffer. No disk read, no subprocess, no network. The project profile was
computed ONCE when the session started, precisely so this path stays free.
-
-The block is written the way the wiki-context block is: it states what it is and
-what it is for, so the model treats it as situational awareness rather than as
-an instruction to narrate the terminals unprompted.
"""
from __future__ import annotations
@@ -23,16 +33,38 @@ import time
# Per-terminal output shown in the block. Enough to say what an agent is doing,
# small enough that ten panes do not crowd out the conversation.
_LINES_PER_TERMINAL = 6
-_MAX_CHARS = 4000
+_MAX_CHARS = 4500
_HEADER = (
"[AGENTIC IDE — focused coding mode is ON]\n"
- "You are assisting inside a live coding workspace that the user has open in "
- "the app. The facts below are the current state of that workspace: the "
- "folder, what kind of project it is, and the coding agents running in named "
- "terminals. Use it to answer questions about the workspace and its agents "
- "concretely (by name), and to decide what to send to which terminal. It is "
- "context, not a script — do not recite it back unprompted."
+ "You are the user's agentic-coding partner for the one repository below. "
+ "Coding agents are already running in named terminals in front of the user; "
+ "your job is to think WITH them about this codebase and to drive those "
+ "agents — not to write the code yourself, and not to start background "
+ "workers.\n"
+ "\n"
+ "How to behave while this mode is on:\n"
+ "- When the user tells a named terminal to do something (\"tell Kai to …\", "
+ "\"Mika soll …\", \"let Nova refactor …\"), send it to THAT terminal with "
+ "the agentic-ide-prompt function. That is the whole point of this mode. "
+ "NEVER spawn a background agent for work aimed at a terminal, and never "
+ "answer with what you WOULD have sent — send it.\n"
+ "- Turn what the user said into a prompt worth running: state the task "
+ "precisely, keep every constraint they gave, invent none, and point at the "
+ "relevant files with @path references from this repository. A vague spoken "
+ "sentence becomes a briefed task; that is the value you add here.\n"
+ "- When the user asks what an agent is doing, read it with "
+ "agentic-ide-terminal-report and answer from what that terminal actually "
+ "printed. Never guess, never take a screenshot — the terminals are readable "
+ "directly.\n"
+ "- Brainstorming, architecture, and 'what should we do next' are answered "
+ "inline, against this codebase, and you may propose which terminal should "
+ "take which part.\n"
+ "- Say the terminal's name out loud in your answers, so the user always "
+ "knows who is doing what.\n"
+ "\n"
+ "The facts below are the live state of that workspace. It is context, not a "
+ "script — do not recite it back unprompted."
)
diff --git a/jarvis/agentic_ide/file_index.py b/jarvis/agentic_ide/file_index.py
new file mode 100644
index 0000000000..ebc3d47da9
--- /dev/null
+++ b/jarvis/agentic_ide/file_index.py
@@ -0,0 +1,318 @@
+"""A bounded map of the open workspace's files, so spoken words become paths.
+
+The point of the Agentic IDE is that you never type at the agent. But a coding
+agent works far better when the prompt *points* at files — Claude Code's ``@``
+reference and Codex's file mentions both pull a file into context immediately,
+which is the difference between "find the wake word code" (three tool calls of
+searching) and "here it is" (zero). A person speaking cannot dictate
+``jarvis/plugins/wake/vosk_kws_provider.py``; they say "the Vosk wake thing".
+This module closes that gap.
+
+Design constraints that shaped it:
+
+* **Off the hot path (AP-26 / AP-9).** The index is built once per workspace, in
+ a worker thread, and cached. Nothing here runs at boot, and a voice turn never
+ waits for a directory walk — if the index is not ready yet, the composer
+ simply gets no file suggestions and the prompt still goes out.
+* **Bounded, always.** A user can open ANY folder, including a home directory or
+ a network share. The walk carries a hard file budget, a depth limit, and the
+ shared skip list, so the worst case is a truncated index, never a hang.
+* **Lexical, not semantic.** Matching is token overlap against path segments and
+ file stems. No embedding, no model call — it must work on a machine with no
+ API key at all, and a wrong suggestion costs the agent one glance.
+
+The ranking encodes what someone actually means when they name a file out loud:
+an exact stem hit beats a partial one, a hit in the file NAME beats one in a
+parent directory, and tests rank below implementation unless the request is
+about tests.
+"""
+from __future__ import annotations
+
+import os
+import re
+import threading
+from dataclasses import dataclass, field
+from pathlib import Path
+
+from .folders import _SKIP_DIRS
+
+# Hard bounds. 30k files covers a large monorepo; past that the tail is noise
+# for this purpose (nobody dictates the name of the 30001st file).
+_MAX_FILES = 30_000
+_MAX_DEPTH = 12
+
+# Extensions worth indexing: source, config, and docs. Binaries and media are
+# never what someone points a coding agent at.
+_INTERESTING_SUFFIXES = frozenset(
+ {
+ ".py", ".pyi", ".ts", ".tsx", ".js", ".jsx", ".mjs", ".cjs", ".vue", ".svelte",
+ ".rs", ".go", ".java", ".kt", ".swift", ".c", ".h", ".cc", ".cpp", ".hpp",
+ ".cs", ".rb", ".php", ".sh", ".ps1", ".bat", ".sql", ".graphql", ".proto",
+ ".toml", ".yaml", ".yml", ".json", ".ini", ".cfg", ".env.example",
+ ".md", ".mdx", ".rst", ".txt", ".css", ".scss", ".html",
+ }
+)
+
+# Files whose bare name matters even without an interesting suffix.
+_ALWAYS_INDEX = frozenset(
+ {"Dockerfile", "Makefile", "Procfile", "LICENSE", "CODEOWNERS", ".gitignore"}
+)
+
+# Directory names that hold a COPY of the repository. Indexing them means every
+# query returns the same file four times over from stale checkouts — measured on
+# this repo: `.claude/worktrees` pushed the real hit out of the top results for
+# nearly every query. The working copy is the only one anyone means.
+_COPY_DIRS = frozenset({"worktrees", ".worktrees", "worktree", "jarvis-agent-outputs"})
+
+# Hidden directories worth indexing anyway: a coding request routinely points at
+# the agent instruction trees ("the wake skill", "the review workflow"), and they
+# are hidden only by convention.
+_KEEP_HIDDEN = frozenset({".claude", ".agents", ".github"})
+
+# Words that carry no addressing power — they appear in every request and would
+# match half the tree. The question words and auxiliaries earn their place the
+# hard way: without them, "was ist mit dem audio capture" scored two stopword
+# hits against a voice-session transcript named `...-was-ist.md` and buried
+# `jarvis/audio/capture.py`.
+_STOPWORDS = frozenset(
+ {
+ # structural / generic
+ "the", "a", "an", "and", "or", "of", "in", "on", "at", "to", "for", "with",
+ "der", "die", "das", "den", "dem", "des", "und", "oder", "von", "im",
+ "auf", "für", "fuer", "mit", "bei", "zum", "zur", "el", "la", "los", "las",
+ "de", "del", "y", "o", "con", "para", "por",
+ # question words / auxiliaries — pure conversational scaffolding
+ "was", "wer", "wie", "wo", "wann", "warum", "welche", "welcher", "welches",
+ "ist", "sind", "war", "waren", "hat", "haben", "wird", "werden", "kann",
+ "soll", "sollte", "muss", "gibt", "gib", "dass", "wenn", "aber", "auch",
+ "noch", "schon", "nur", "sich", "sein", "seine", "ihre", "einen", "eine",
+ "einer", "eines", "etwas", "irgendwas", "irgendwie", "dann", "denn",
+ "what", "who", "how", "where", "when", "why", "which", "is", "are",
+ "were", "has", "have", "will", "would", "should", "must", "can", "does",
+ "this", "that", "these", "those", "there", "here", "some", "any", "about",
+ "qué", "que", "quien", "cómo", "como", "donde", "cuando", "cual", "está",
+ "estan", "tiene", "puede", "debe", "esto", "eso", "aqui", "algo",
+ # request verbs (they say what to DO, not which file)
+ "mach", "mache", "machen", "bau", "baue", "schreib", "schreibe", "fix",
+ "fixe", "behebe", "prüf", "pruef", "prüfe", "check", "checke", "teste",
+ "test", "starte", "start", "build", "write", "make", "run", "change",
+ "create", "add", "remove", "delete", "look", "read", "find", "search",
+ "review", "analyse", "analyze", "analysiere", "untersuche", "schau",
+ "haz", "escribe", "crea", "revisa", "arregla",
+ # meta words about the code itself
+ "code", "datei", "dateien", "file", "files", "funktion", "function",
+ "klasse", "class", "modul", "module", "bug", "fehler", "error", "problem",
+ "sache", "thing", "stuff", "part", "teil", "mal", "bitte", "kurz", "nochmal",
+ }
+)
+
+_TOKEN_RE = re.compile(r"[A-Za-zÄÖÜäöüß0-9_]+")
+# Split identifiers the way they are spoken: camelCase, snake_case, kebab-case.
+_CAMEL_RE = re.compile(r"(?<=[a-z0-9])(?=[A-Z])")
+
+
+@dataclass(slots=True)
+class _Entry:
+ """One indexed file: its repo-relative path plus its searchable tokens."""
+
+ rel: str
+ stem_tokens: frozenset[str]
+ path_tokens: frozenset[str]
+ is_test: bool
+
+
+@dataclass(slots=True)
+class FileIndex:
+ """Searchable, bounded view of one workspace folder."""
+
+ root: str
+ entries: list[_Entry] = field(default_factory=list)
+ truncated: bool = False
+
+ def __len__(self) -> int: # pragma: no cover - trivial
+ return len(self.entries)
+
+ def suggest(self, text: str, *, limit: int = 6) -> list[str]:
+ """Repo-relative paths the words in ``text`` most plausibly point at."""
+ wanted = tokenize(text)
+ if not wanted or not self.entries:
+ return []
+ wants_tests = bool(wanted & {"test", "tests", "spec", "specs"})
+ scored: list[tuple[float, int, str]] = []
+ for entry in self.entries:
+ score = _score(entry, wanted, wants_tests=wants_tests)
+ if score > 0:
+ # Shorter paths win ties: the top-level `config.py` is far more
+ # likely meant than a same-named file nested six levels deep.
+ scored.append((score, -entry.rel.count("/"), entry.rel))
+ if not scored:
+ return []
+ scored.sort(key=lambda item: (-item[0], -item[1], item[2]))
+ return [rel for _s, _d, rel in scored[: max(1, limit)]]
+
+
+def _singular(token: str) -> str:
+ """Fold a trailing plural ``s`` so speech matches file names.
+
+ People say "the terminal theme"; the file is ``terminalThemes.ts``. Only a
+ trailing ``s`` on a word long enough for it to be a plural — nothing that
+ would collapse two genuinely different identifiers.
+ """
+ if len(token) > 4 and token.endswith("s") and not token.endswith("ss"):
+ return token[:-1]
+ return token
+
+
+def tokenize(text: str) -> set[str]:
+ """Meaningful lowercase tokens of ``text``, identifiers split apart."""
+ out: set[str] = set()
+ for raw in _TOKEN_RE.findall(text or ""):
+ for piece in _CAMEL_RE.split(raw):
+ for chunk in re.split(r"[_\-]+", piece):
+ token = chunk.lower()
+ if len(token) < 3 or token in _STOPWORDS or token.isdigit():
+ continue
+ out.add(_singular(token))
+ return out
+
+
+def _score(entry: _Entry, wanted: set[str], *, wants_tests: bool) -> float:
+ """How strongly this file answers to the words the user used."""
+ stem_hits = entry.stem_tokens & wanted
+ path_hits = (entry.path_tokens - entry.stem_tokens) & wanted
+ if not stem_hits and not path_hits:
+ return 0.0
+ # A hit in the file's own name is what someone means when they name a file;
+ # a hit in a parent directory only narrows the area.
+ score = 3.0 * len(stem_hits) + 1.0 * len(path_hits)
+ # Every token of the file's name being named is near-certainty.
+ if stem_hits and stem_hits == entry.stem_tokens:
+ score += 2.0
+ if entry.is_test and not wants_tests:
+ score *= 0.35
+ return score
+
+
+def _is_interesting(name: str) -> bool:
+ if name in _ALWAYS_INDEX:
+ return True
+ suffix = os.path.splitext(name)[1].lower()
+ return suffix in _INTERESTING_SUFFIXES
+
+
+def build_index(root: str | Path) -> FileIndex:
+ """Walk ``root`` once and return its bounded file index.
+
+ Blocking by design — callers run it in a worker thread (see ``index_for``).
+ """
+ base = Path(root).expanduser()
+ index = FileIndex(root=str(base))
+ try:
+ if not base.is_dir():
+ return index
+ except OSError:
+ return index
+
+ stack: list[tuple[Path, int]] = [(base, 0)]
+ while stack:
+ current, depth = stack.pop()
+ if len(index.entries) >= _MAX_FILES:
+ index.truncated = True
+ break
+ try:
+ with os.scandir(current) as it:
+ for item in it:
+ if len(index.entries) >= _MAX_FILES:
+ index.truncated = True
+ break
+ name = item.name
+ if name in _SKIP_DIRS or name in _COPY_DIRS:
+ continue
+ try:
+ if item.is_dir(follow_symlinks=False):
+ # Hidden directories are skipped except the agent
+ # instruction trees, which are exactly what a coding
+ # request refers to ("the wake skill", ".claude").
+ if name.startswith(".") and name not in _KEEP_HIDDEN:
+ continue
+ if depth < _MAX_DEPTH:
+ stack.append((Path(item.path), depth + 1))
+ continue
+ if not _is_interesting(name):
+ continue
+ except OSError:
+ continue
+ rel = os.path.relpath(item.path, base).replace(os.sep, "/")
+ stem = os.path.splitext(name)[0]
+ parent = rel.rsplit("/", 1)[0] if "/" in rel else ""
+ index.entries.append(
+ _Entry(
+ rel=rel,
+ stem_tokens=frozenset(tokenize(stem)),
+ path_tokens=frozenset(tokenize(parent)) | frozenset(tokenize(stem)),
+ is_test=(
+ "test" in rel.lower().split("/")[0]
+ or stem.lower().startswith("test_")
+ or stem.lower().endswith(("_test", ".test", ".spec"))
+ ),
+ )
+ )
+ except (PermissionError, OSError):
+ continue
+ return index
+
+
+# One cached index per folder. Small on purpose: a session opens one workspace,
+# and holding a stale index for every folder ever browsed would be a slow leak.
+_CACHE: dict[str, FileIndex] = {}
+_BUILDING: set[str] = set()
+_LOCK = threading.Lock()
+
+
+def cached_index(root: str | Path) -> FileIndex | None:
+ """The index for ``root`` if it is already built, else ``None``."""
+ with _LOCK:
+ return _CACHE.get(str(Path(root).expanduser()))
+
+
+def prime_index(root: str | Path) -> None:
+ """Build the index for ``root`` in the background, once.
+
+ Called when a workspace opens so the first spoken instruction already has
+ file suggestions available. Never raises and never blocks the caller — a
+ failed or slow build degrades to "no suggestions", which costs the agent one
+ extra search and nothing else.
+ """
+ key = str(Path(root).expanduser())
+ with _LOCK:
+ if key in _CACHE or key in _BUILDING:
+ return
+ _BUILDING.add(key)
+
+ def _run() -> None:
+ try:
+ built = build_index(key)
+ except Exception: # noqa: BLE001 - an index is a convenience, never fatal
+ built = FileIndex(root=key)
+ with _LOCK:
+ _CACHE[key] = built
+ _BUILDING.discard(key)
+
+ threading.Thread(target=_run, name="agentic-ide-file-index", daemon=True).start()
+
+
+def reset_cache() -> None:
+ """Drop every cached index — tests, and when a workspace closes."""
+ with _LOCK:
+ _CACHE.clear()
+ _BUILDING.clear()
+
+
+__all__ = [
+ "FileIndex",
+ "build_index",
+ "cached_index",
+ "prime_index",
+ "reset_cache",
+ "tokenize",
+]
diff --git a/jarvis/agentic_ide/intent.py b/jarvis/agentic_ide/intent.py
new file mode 100644
index 0000000000..2e96f262c0
--- /dev/null
+++ b/jarvis/agentic_ide/intent.py
@@ -0,0 +1,285 @@
+"""Does this utterance address a terminal of the open workspace?
+
+The Agentic IDE's whole promise is that you *talk* to the agents instead of
+typing at them. That only works if "tell Kai to review the wake path" reaches
+Kai. Live failure 2026-07-25 (voice session 15:47): it did not — the utterance
+contained the depth marker "deep dive", the router's deterministic force-spawn
+heuristic recognised it as heavy work, and a background mission worker was
+dispatched into a fresh git worktree while Kai's terminal sat idle. The user
+saw nothing happen.
+
+The root cause is a routing-precedence bug, not a missing feature: two
+deterministic paths claimed the same turn and the older one ran first. This
+module is the tie-breaker, and it is deliberately a *detector*, not a policy —
+it answers one question ("which open terminal is this turn about, and does the
+user want it to DO something or REPORT something?") and lets the callers decide.
+
+Precedence, as implemented by the callers:
+
+1. The user naming the spawn vehicle ("spawn an agent", "im Hintergrund") still
+ wins — asking for a background worker *while* a workspace is open is a
+ legitimate, unambiguous request, and the workspace must not swallow it.
+2. Otherwise, an addressed terminal wins over force-spawn: "let Kai do a deep
+ dive" means *Kai* does it, not a new invisible worker.
+3. An utterance that names no terminal is none of this module's business.
+
+Why matching is conservative: a false positive here silently withholds a
+background mission the user wanted, so a bare mention of a name is not enough.
+The utterance must both name a running terminal AND carry an addressing shape
+(an imperative aimed at it, a "tell X to …" construction, or a question about
+what it is doing). Everything is derived from the *configured* call-signs, never
+from a fixed word list — a workspace whose panes are called "Bruno" and "Vega"
+behaves exactly like one with the defaults.
+
+Cost: pure regex + an in-memory registry read, no IO, no LLM (AP-9 / AP-11), so
+it is safe on the voice hot path.
+"""
+from __future__ import annotations
+
+import re
+from dataclasses import dataclass
+
+from .names import resolve
+
+# Kinds of turn this module recognises.
+KIND_PROMPT = "prompt" # the user wants the agent to do something
+KIND_REPORT = "report" # the user asks what the agent is up to
+
+# Addressing shapes, per supported locale. These match *input vocabulary* — the
+# words a person actually says to hand work to a named agent — not prose.
+# ``{name}`` is substituted with the live call-signs at match time.
+_DIRECTIVE_TEMPLATES: tuple[str, ...] = (
+ # "sag Mika, sie soll …" / "sage Kai …" / "tell Nova to …" / "dile a Aria …"
+ r"\b(?:sag|sage|sagst)\b[^.!?]{{0,40}}?\b{name}\b",
+ r"\btell\b[^.!?]{{0,40}}?\b{name}\b",
+ r"\b(?:dile|d[ií]gale|dile\s+a)\b[^.!?]{{0,40}}?\b{name}\b",
+ # "Mika soll …" / "lass Kai …" / "Nova should …" / "let Aria …"
+ r"\b{name}\b[^.!?]{{0,20}}?\b(?:soll|sollte|kann|k[oö]nnte)\b",
+ r"\b{name}\b[^.!?]{{0,20}}?\b(?:should|can|could|please)\b",
+ r"\b{name}\b[^.!?]{{0,20}}?\b(?:deber[ií]a|puede|podr[ií]a)\b",
+ r"\b(?:lass|l[aä]sst)\b[^.!?]{{0,20}}?\b{name}\b",
+ r"\blet\b[^.!?]{{0,20}}?\b{name}\b",
+ # "schick(e) das an Kai" / "gib Mika …" / "frag Nova …" / "beauftrage Kai …"
+ r"\b(?:schick|schicke|gib|gibt|frag|frage|beauftrag|beauftrage|"
+ r"[uü]bergib|[uü]bergebe|weiterleit\w*)\b[^.!?]{{0,40}}?\b{name}\b",
+ r"\b(?:send|give|ask|hand|forward|assign)\b[^.!?]{{0,40}}?\b{name}\b",
+ r"\b(?:env[ií]a|manda|preg[uú]nta|pasa|asigna)\b[^.!?]{{0,40}}?\b{name}\b",
+ # "an Kai:" / "in Mika:" / "bei Nova" / "über Kai" — a routing preposition
+ # immediately in front of the call-sign.
+ r"\b(?:an|in|bei|[uü]ber|via|to|into|en|a)\s+{name}\b",
+ # Vocative: the name opens the utterance ("Kai, mach mal …").
+ r"^{name}\b\s*[,:]",
+)
+
+# "what is Mika doing?" — a read, never a spawn either. Both word orders are
+# covered per language: German and Spanish put the verb before the name ("was
+# macht Mika"), English after it ("what is Mika doing").
+_REPORT_TEMPLATES: tuple[str, ...] = (
+ r"\bwas\b[^.!?]{{0,30}}?\b{name}\b[^.!?]{{0,30}}?\b(?:macht|tut|treibt|arbeitet)\b",
+ r"\bwas\b[^.!?]{{0,20}}?\b(?:macht|tut|treibt|arbeitet)\b[^.!?]{{0,20}}?\b{name}\b",
+ r"\b(?:what|how)\b[^.!?]{{0,30}}?\b{name}\b[^.!?]{{0,30}}?\b(?:doing|up\s+to|going|at)\b",
+ r"\b(?:qu[eé]|c[oó]mo)\b[^.!?]{{0,30}}?\b{name}\b[^.!?]{{0,30}}?\b(?:hace|haciendo|va)\b",
+ r"\b(?:qu[eé]|c[oó]mo)\b[^.!?]{{0,20}}?\b(?:hace|haciendo|va)\b[^.!?]{{0,20}}?\b{name}\b",
+ r"\b{name}\b[^.!?]{{0,20}}?\b(?:status|fortschritt|progress|estado)\b",
+ r"\b(?:status|fortschritt|progress|estado)\b[^.!?]{{0,20}}?\b{name}\b",
+ # "ist Kai fertig / stuck / hängt Mika?"
+ r"\b(?:ist|is|est[aá])\b\s+{name}\b",
+ r"\b(?:h[aä]ngt|steckt|stuck|fertig|done|listo)\b[^.!?]{{0,20}}?\b{name}\b",
+)
+
+# Leading conversational filler that carries no instruction for the agent
+# ("kannst du mal bitte kurz …"). Stripped from the extracted instruction so the
+# composer sees the work, not the politeness.
+_FILLER_PREFIX_RE = re.compile(
+ r"^(?:"
+ r"(?:hey|hallo|hi|ok|okay|also|so|und|na)\b[\s,]*"
+ r"|(?:kannst|k[oö]nntest|w[uü]rdest|willst|magst)\s+du\b\s*"
+ r"|(?:could|can|would|will)\s+you\b\s*"
+ r"|(?:puedes|podr[ií]as)\b\s*"
+ r"|(?:mal|bitte|kurz|schnell|eben|just|please|quickly|por\s+favor)\b[\s,]*"
+ r")+",
+ re.IGNORECASE,
+)
+
+
+@dataclass(frozen=True, slots=True)
+class TerminalIntent:
+ """A turn that belongs to one named terminal of the open workspace."""
+
+ terminal: str
+ """The resolved call-sign as the session spells it ("Kai")."""
+
+ kind: str
+ """``prompt`` (make it do something) or ``report`` (say what it is doing)."""
+
+ instruction: str
+ """The user's words minus the addressing preamble — what the agent should do.
+
+ Best-effort and only a *fallback*: the prompt composer receives the whole
+ utterance as well, because a deterministic split cannot reliably tell an
+ addressing clause from the work in a long spoken sentence.
+ """
+
+ utterance: str
+ """The original utterance, unmodified."""
+
+
+def _running_names() -> list[str]:
+ """Call-signs of the open workspace, or ``[]`` when none is open."""
+ try:
+ from .session import get_registry
+
+ session = get_registry().session
+ except Exception: # noqa: BLE001 - the detector must never break a turn
+ return []
+ if session is None:
+ return []
+ return [term.name for term in session.terminals]
+
+
+def _name_alternatives(name: str) -> str:
+ """Regex alternation matching ``name`` and its common transcript garble.
+
+ A call-sign arrives through speech recognition, so "Kai" also shows up as
+ "Kay" and "Mika" as "Micah". The phonetic folding in ``names.resolve`` covers
+ that for *word* matching; here we only need a pattern loose enough to locate
+ the name inside a sentence, and ``resolve`` re-checks the hit afterwards.
+ """
+ escaped = re.escape(name)
+ return escaped
+
+
+def _compile(templates: tuple[str, ...], names: list[str]) -> list[tuple[str, re.Pattern[str]]]:
+ out: list[tuple[str, re.Pattern[str]]] = []
+ for name in names:
+ token = _name_alternatives(name)
+ for template in templates:
+ try:
+ out.append((name, re.compile(template.format(name=token), re.IGNORECASE)))
+ except re.error: # pragma: no cover - a call-sign that breaks regex
+ continue
+ return out
+
+
+def _strip_addressing(text: str, name: str) -> str:
+ """The utterance with the addressing preamble and the call-sign removed."""
+ cleaned = re.sub(
+ r"\b(?:sag|sage|sagst|tell|dile|d[ií]gale|schick|schicke|send|gib|give|"
+ r"frag|frage|ask|lass|let|beauftrage?|assign|env[ií]a|manda)\b\s*",
+ " ",
+ text,
+ flags=re.IGNORECASE,
+ )
+ cleaned = re.sub(
+ rf"\b(?:an|to|a|bei|in|[uü]ber|via)?\s*{re.escape(name)}\b\s*[,:]?\s*",
+ " ",
+ cleaned,
+ flags=re.IGNORECASE,
+ )
+ # "…, dass er/sie …" / "…, that it should …" — the subordinating conjunction
+ # left over once the addressee is gone.
+ cleaned = re.sub(
+ r"^\s*(?:und\s+zwar\s+)?(?:dass|damit|that|que)\s+(?:er|sie|es|it|he|she|they)?\s*",
+ "",
+ cleaned.strip(),
+ flags=re.IGNORECASE,
+ )
+ cleaned = _FILLER_PREFIX_RE.sub("", cleaned.strip())
+ return " ".join(cleaned.split())
+
+
+def detect(user_text: str, *, names: list[str] | None = None) -> TerminalIntent | None:
+ """The terminal this turn is about, or ``None``.
+
+ ``names`` is injectable so tests (and callers that already hold the session)
+ do not need the process-wide registry.
+ """
+ text = (user_text or "").strip()
+ if len(text) < 3:
+ return None
+ candidates = _running_names() if names is None else list(names)
+ if not candidates:
+ return None
+
+ # A report question is checked first: "what is Kai doing?" also matches the
+ # looser "ist Kai …" directive shape, and answering it as a prompt would type
+ # the question into the agent.
+ for name, pattern in _compile(_REPORT_TEMPLATES, candidates):
+ if pattern.search(text):
+ return TerminalIntent(
+ terminal=name, kind=KIND_REPORT, instruction="", utterance=text
+ )
+
+ for name, pattern in _compile(_DIRECTIVE_TEMPLATES, candidates):
+ if pattern.search(text):
+ return TerminalIntent(
+ terminal=name,
+ kind=KIND_PROMPT,
+ instruction=_useful_instruction(text, name),
+ utterance=text,
+ )
+
+ # Last resort: the utterance names a terminal (possibly garbled) and reads as
+ # an instruction. ``names.resolve`` does the phonetic work; requiring a verb
+ # keeps a passing mention ("Kai is a nice name") from being addressed.
+ matched = resolve(text, candidates)
+ if matched is not None and _looks_like_instruction(text):
+ return TerminalIntent(
+ terminal=matched,
+ kind=KIND_PROMPT,
+ instruction=_useful_instruction(text, matched),
+ utterance=text,
+ )
+ return None
+
+
+# Below this, stripping has eaten the task rather than the addressing — "schick
+# das an Kai" reduces to "das". The full utterance is then the honest input; the
+# composer reads both and can tell them apart.
+_MIN_INSTRUCTION_CHARS = 12
+
+
+def _useful_instruction(text: str, name: str) -> str:
+ """The stripped instruction, or the whole utterance when stripping over-ate."""
+ stripped = _strip_addressing(text, name)
+ return stripped if len(stripped) >= _MIN_INSTRUCTION_CHARS else text
+
+
+_INSTRUCTION_VERB_RE = re.compile(
+ r"\b(?:mach|machen|bau|baue|schreib|schreibe|fix|fixe|behebe|pr[uü]f|pr[uü]fe|"
+ r"check|checke|analysier\w*|review\w*|refactor\w*|teste?|starte?|implementier\w*|"
+ r"[aä]nder\w*|erstell\w*|f[uü]g\w*|entfern\w*|l[oö]sch\w*|untersuch\w*|"
+ r"build|write|make|run|test|start|implement|change|create|add|remove|delete|"
+ r"investigate|look|read|find|search|explain|document|"
+ r"haz|escribe|crea|revisa|arregla|ejecuta|implementa|analiza)\b",
+ re.IGNORECASE,
+)
+
+
+def _looks_like_instruction(text: str) -> bool:
+ return bool(_INSTRUCTION_VERB_RE.search(text))
+
+
+def owns_turn(user_text: str, *, names: list[str] | None = None) -> bool:
+ """True when the open workspace should handle this turn instead of a spawn.
+
+ Used by the router's force-spawn guard. An utterance that explicitly names
+ the spawn vehicle is NOT owned here — asking for a background agent while a
+ workspace happens to be open is a real request, and stealing it would be the
+ mirror image of the bug this module fixes.
+ """
+ from jarvis.brain.spawn_gate import names_spawn_vehicle
+
+ text = (user_text or "").strip()
+ if not text or names_spawn_vehicle(text):
+ return False
+ return detect(text, names=names) is not None
+
+
+__all__ = [
+ "KIND_PROMPT",
+ "KIND_REPORT",
+ "TerminalIntent",
+ "detect",
+ "owns_turn",
+]
diff --git a/jarvis/agentic_ide/prompt_composer.py b/jarvis/agentic_ide/prompt_composer.py
new file mode 100644
index 0000000000..476098d522
--- /dev/null
+++ b/jarvis/agentic_ide/prompt_composer.py
@@ -0,0 +1,336 @@
+"""Turn a spoken instruction into a prompt a coding agent can actually work on.
+
+This is the part that makes the Agentic IDE worth having. Speaking at an agent
+and speaking at a *transcript relay* are very different products: dictated
+words arrive as one unpunctuated run of filler, pronouns and self-corrections
+("kannst du mal schnell, also ähm, das Wake-Ding angucken ob da was kaputt
+ist"), and pasting that into Claude Code produces a confused agent that starts
+by asking what you meant. What the user asked for is that *Jarvis* does the
+prompt engineering: it knows the repo, so it turns that sentence into a briefed
+task with the relevant files already attached.
+
+What the composed prompt contains, and why each part earns its place:
+
+* **The task, as an imperative.** Fillers, the addressing clause ("tell Kai
+ to …") and speech artefacts are gone; what remains is what to do.
+* **File references in the agent's own syntax** (``@path``). Both supported
+ CLIs read ``@`` as "pull this file into context", which removes the agent's
+ entire opening round of blind searching. Paths come from the workspace file
+ index — never invented, and every one is verified to exist before it ships.
+* **A short workspace line** (stack, branch) when it is not obvious, so the
+ agent does not re-derive it.
+
+Two-layer construction, because the product must work for a downloader with no
+API key at all (§3):
+
+1. **Composed** — one bounded call to the frontier chain
+ (``resolve_frontier_brain``: key-aware, crosses provider families, AP-22).
+ It gets the utterance, the project profile and the candidate files, and
+ returns the prompt.
+2. **Deterministic fallback** — regex cleanup plus the same file references,
+ used when no provider is reachable, the call fails, times out, or comes back
+ empty. It is *always* better than the raw transcript, so the feature never
+ depends on a model being available.
+
+The composer is honest about which layer produced the result (``composed_by``),
+because the readback the user hears should not claim more than happened.
+"""
+from __future__ import annotations
+
+import asyncio
+import re
+from dataclasses import dataclass, field
+from pathlib import Path
+
+from loguru import logger
+
+from .file_index import cached_index
+from .session import MAX_PROMPT_CHARS, sanitize_prompt
+
+# The composer is not on the voice hot path the way an ack is, but the user is
+# waiting to hear "sent to Kai" — past a few seconds it feels broken. On timeout
+# the deterministic prompt ships, so this bound costs quality, never delivery.
+COMPOSE_TIMEOUT_S = 8.0
+
+# How many files may be attached. Enough to point the agent at a feature's
+# surface; few enough that the agent's context is not flooded with guesses.
+MAX_FILE_REFERENCES = 5
+
+_SYSTEM_PROMPT = """\
+You turn a spoken instruction into a precise prompt for a coding agent (Claude \
+Code / Codex) that is already running inside the user's repository.
+
+Rules:
+- Output ONLY the prompt text. No preamble, no explanation, no quotes, no \
+markdown fences.
+- Write it as a direct instruction to the coding agent, in the imperative.
+- Preserve every constraint, file, symbol and intent the user expressed. Do not \
+invent requirements, scope, or acceptance criteria they did not state.
+- Remove speech artefacts: filler words, false starts, self-corrections, and \
+the clause that addressed the agent by name ("tell Kai to ...").
+- If the user was vague, keep it vague — state the goal and let the agent \
+investigate. Never fabricate specifics to make the prompt look complete.
+- Reference relevant files with @path syntax on their own line at the end, \
+using ONLY paths from the candidate list you are given. Omit the line entirely \
+if no candidate is clearly relevant.
+- Write the prompt in the same language the user spoke.
+- Keep it under 1200 characters.
+"""
+
+# Speech artefacts the deterministic layer removes. Matching *input vocabulary*
+# in the supported locales — these are the words people actually say while
+# thinking, not prose.
+_FILLER_RE = re.compile(
+ r"\b(?:"
+ r"ähm|ähmm|äh|ehm|hmm|halt|eben|einfach\s+mal|also|ne|gell|weißt\s+du|"
+ r"verstehst\s+du|sozusagen|quasi|irgendwie|jetzt\s+mal|mal\s+eben|"
+ r"um|uh|erm|like|you\s+know|i\s+mean|sort\s+of|kind\s+of|basically|"
+ r"este|o\s+sea|pues|bueno"
+ r")\b[\s,]*",
+ re.IGNORECASE,
+)
+
+_POLITENESS_PREFIX_RE = re.compile(
+ r"^(?:"
+ r"(?:kannst|k[oö]nntest|w[uü]rdest|willst|magst|k[oö]nnen)\s+(?:du|sie)\b\s*"
+ r"|(?:could|can|would|will)\s+you\b\s*"
+ r"|(?:puedes|podr[ií]as)\b\s*"
+ r"|(?:bitte|please|por\s+favor|mal|kurz|schnell|eben|just|quickly)\b[\s,]*"
+ r")+",
+ re.IGNORECASE,
+)
+
+
+@dataclass(slots=True)
+class ComposedPrompt:
+ """The prompt that will be typed, plus how it came to be."""
+
+ text: str
+ """What gets sent to the agent."""
+
+ files: list[str] = field(default_factory=list)
+ """Repo-relative paths referenced with ``@`` in ``text``."""
+
+ composed_by: str = "fallback"
+ """``llm`` when a provider wrote it, ``fallback`` when the regex layer did,
+ ``raw`` when composition was switched off by the caller."""
+
+ note: str = ""
+ """Why the fallback was used, when it was. Empty on the happy path."""
+
+
+def _clean_speech(text: str) -> str:
+ """The instruction with speech artefacts and politeness scaffolding gone."""
+ cleaned = _FILLER_RE.sub(" ", text or "")
+ cleaned = _POLITENESS_PREFIX_RE.sub("", cleaned.strip())
+ # Collapse the "und zwar dass er ..." construction into a plain imperative
+ # opening; it is a spoken connector, never part of the task.
+ cleaned = re.sub(
+ r"^\s*(?:und\s+zwar\s+)?(?:dass|damit|that|que)\s+(?:er|sie|es|it|he|she|they)\s+",
+ "",
+ cleaned,
+ flags=re.IGNORECASE,
+ )
+ return " ".join(cleaned.split())
+
+
+def _existing(root: str, candidates: list[str]) -> list[str]:
+ """Candidate paths that really exist under ``root``, in the given order.
+
+ A hallucinated ``@path`` is worse than none: the agent opens it, fails, and
+ spends a turn recovering. The index can also be stale (a file was renamed
+ after the walk), so existence is re-checked here rather than assumed.
+ """
+ base = Path(root)
+ out: list[str] = []
+ for rel in candidates:
+ # Reject anything trying to leave the workspace — a composed path is
+ # model output on the happy path, and it only ever legitimately points
+ # inside the folder the user opened.
+ if rel.startswith(("/", "\\")) or ".." in rel.split("/") or ":" in rel[:3]:
+ continue
+ try:
+ if (base / rel).is_file():
+ out.append(rel)
+ except OSError:
+ continue
+ return out
+
+
+def _file_candidates(session, instruction: str, limit: int) -> list[str]: # noqa: ANN001
+ """Repo-relative files the instruction plausibly points at."""
+ index = cached_index(session.folder)
+ if index is None:
+ # Still building (or never primed): ship without references rather than
+ # make the user wait for a directory walk.
+ return []
+ return _existing(session.folder, index.suggest(instruction, limit=limit))
+
+
+def _render_fallback(instruction: str, files: list[str]) -> str:
+ body = _clean_speech(instruction)
+ if not body:
+ body = " ".join((instruction or "").split())
+ if files:
+ body = f"{body}\n\n{' '.join('@' + f for f in files)}"
+ return body
+
+
+def _extract_referenced(text: str) -> list[str]:
+ """``@path`` tokens in a composed prompt, in order of appearance."""
+ seen: list[str] = []
+ for match in re.finditer(r"@([\w./\\-]+)", text or ""):
+ rel = match.group(1).replace("\\", "/")
+ if rel not in seen:
+ seen.append(rel)
+ return seen
+
+
+async def _llm_compose(
+ *,
+ utterance: str,
+ instruction: str,
+ session, # noqa: ANN001 - Session, avoid an import cycle
+ terminal_name: str,
+ agent_display: str,
+ candidates: list[str],
+) -> str:
+ """One bounded frontier-chain call that writes the prompt.
+
+ Uses ``resolve_frontier_brain`` rather than a pinned provider so the call
+ follows whatever the user actually has configured and keyed, crossing
+ provider families when the primary is dead (AP-21 / AP-22).
+ """
+ from jarvis.brain.resolver import resolve_frontier_brain
+ from jarvis.core.config import load_config
+ from jarvis.core.protocols import BrainMessage, BrainRequest
+
+ brain = resolve_frontier_brain(load_config())
+
+ profile_lines = "\n".join(session.profile.summary_lines())
+ candidate_block = (
+ "\n".join(f"- {c}" for c in candidates)
+ if candidates
+ else "(no candidate files matched — omit the @ line)"
+ )
+ user_block = (
+ f"The user is talking to the coding agent {agent_display} running in a "
+ f"terminal they call {terminal_name}.\n\n"
+ f"WORKSPACE\n{profile_lines}\n\n"
+ f"CANDIDATE FILES (repo-relative; use only these in @ references)\n"
+ f"{candidate_block}\n\n"
+ f"WHAT THE USER SAID (verbatim speech transcript)\n{utterance}\n\n"
+ f"THE INSTRUCTION PART, WITH THE ADDRESSING REMOVED\n{instruction}\n\n"
+ f"Write the prompt now."
+ )
+
+ request = BrainRequest(
+ messages=(BrainMessage(role="user", content=user_block),),
+ system=_SYSTEM_PROMPT,
+ # Deterministic rewriting, not creative writing: the prompt must carry
+ # the user's intent, so temperature stays low.
+ temperature=0.2,
+ max_tokens=800,
+ stream=True,
+ # A prompt rewrite needs no internal reasoning budget, and on
+ # thinking-heavy models it would eat max_tokens and truncate the answer.
+ reasoning_effort="none",
+ )
+ chunks: list[str] = []
+ async for delta in brain.complete(request):
+ if delta.content:
+ chunks.append(delta.content)
+ return "".join(chunks).strip()
+
+
+def _strip_wrapper(text: str) -> str:
+ """Remove a fenced block or surrounding quotes a model may have added."""
+ stripped = text.strip()
+ fence = re.match(r"^```[a-zA-Z]*\s*\n(.*?)\n?```$", stripped, re.DOTALL)
+ if fence:
+ stripped = fence.group(1).strip()
+ if len(stripped) > 1 and stripped[0] == stripped[-1] and stripped[0] in "\"'":
+ stripped = stripped[1:-1].strip()
+ return stripped
+
+
+async def compose(
+ utterance: str,
+ *,
+ session, # noqa: ANN001 - Session, avoid an import cycle
+ terminal_name: str,
+ agent_display: str = "the coding agent",
+ instruction: str | None = None,
+ use_llm: bool = True,
+ max_files: int = MAX_FILE_REFERENCES,
+) -> ComposedPrompt:
+ """Build the prompt for ``terminal_name`` out of what the user said.
+
+ Never raises: every failure path lands on the deterministic prompt, because
+ "the agent got a slightly rougher prompt" is a far better outcome than "your
+ instruction vanished".
+ """
+ said = (utterance or "").strip()
+ base_instruction = (instruction or said).strip()
+ if not said:
+ return ComposedPrompt(text="", composed_by="raw", note="empty instruction")
+
+ candidates = _file_candidates(session, base_instruction or said, max_files * 2)
+
+ if not use_llm:
+ text = _render_fallback(base_instruction, candidates[:max_files])
+ return ComposedPrompt(
+ text=sanitize_prompt(text)[:MAX_PROMPT_CHARS],
+ files=candidates[:max_files],
+ composed_by="raw",
+ )
+
+ note = ""
+ try:
+ composed = await asyncio.wait_for(
+ _llm_compose(
+ utterance=said,
+ instruction=base_instruction,
+ session=session,
+ terminal_name=terminal_name,
+ agent_display=agent_display,
+ candidates=candidates,
+ ),
+ timeout=COMPOSE_TIMEOUT_S,
+ )
+ composed = _strip_wrapper(composed)
+ except TimeoutError:
+ composed, note = "", f"composer timed out after {COMPOSE_TIMEOUT_S:g}s"
+ except Exception as exc: # noqa: BLE001 - any provider failure degrades
+ composed, note = "", f"composer unavailable ({type(exc).__name__})"
+ logger.info("Agentic IDE prompt composer fell back: {}", exc)
+
+ if composed:
+ # Keep only the references that survive an existence check — the model
+ # may echo a candidate that was renamed, or invent one outright.
+ referenced = _existing(session.folder, _extract_referenced(composed))
+ dropped = [r for r in _extract_referenced(composed) if r not in referenced]
+ for bad in dropped:
+ composed = composed.replace(f"@{bad}", bad)
+ final = sanitize_prompt(composed)[:MAX_PROMPT_CHARS]
+ if final:
+ return ComposedPrompt(
+ text=final, files=referenced, composed_by="llm", note=note
+ )
+ note = note or "composer returned nothing usable"
+
+ chosen = candidates[:max_files]
+ return ComposedPrompt(
+ text=sanitize_prompt(_render_fallback(base_instruction, chosen))[:MAX_PROMPT_CHARS],
+ files=chosen,
+ composed_by="fallback",
+ note=note or "no provider reachable",
+ )
+
+
+__all__ = [
+ "COMPOSE_TIMEOUT_S",
+ "MAX_FILE_REFERENCES",
+ "ComposedPrompt",
+ "compose",
+]
diff --git a/jarvis/agentic_ide/session.py b/jarvis/agentic_ide/session.py
index ada18cf861..8484bcc8df 100644
--- a/jarvis/agentic_ide/session.py
+++ b/jarvis/agentic_ide/session.py
@@ -126,6 +126,11 @@ class Terminal:
agent: str # "claude" | "codex"
display_name: str # "Claude Code"
index: int
+ # Grid row this pane sits in. Panes sharing a row render side by side, which
+ # is what "split right" produces; "split down" opens a new row. A full split
+ # TREE (arbitrary nesting, draggable separators) is deliberately NOT modelled
+ # — rows express both buttons the UI offers and stay readable.
+ row: int = 0
status: Status = "pending"
pty_id: str | None = None
exit_code: int | None = None
@@ -143,6 +148,7 @@ class Terminal:
"agent": self.agent,
"display_name": self.display_name,
"index": self.index,
+ "row": self.row,
"status": self.status,
"exit_code": self.exit_code,
"error": self.error,
@@ -323,6 +329,17 @@ class Registry:
created_at=time.time(),
)
self._session = session
+ # Start indexing the codebase NOW, in a background thread, so the
+ # first spoken instruction can already point the agent at real files
+ # (@path). Deliberately fire-and-forget: nothing waits for it, and a
+ # workspace whose walk is still running just gets a prompt without
+ # file references (AP-26 — no heavy work on an interactive path).
+ try:
+ from . import file_index
+
+ file_index.prime_index(str(root))
+ except Exception as exc: # noqa: BLE001 - the index is a convenience
+ logger.warning("Agentic IDE: file index not primed: {}", exc)
# Remember the workspace so the next visit is one click, replaying
# the same terminal count and agent split (see recents.py).
split: dict[str, int] = {}
@@ -365,6 +382,14 @@ class Registry:
manager.close(term.pty_id)
except Exception: # noqa: BLE001, S110 - best-effort teardown
pass
+ # Drop the codebase index with the workspace: keeping it would hand the
+ # next session a snapshot of a folder that may have changed since.
+ try:
+ from . import file_index
+
+ file_index.reset_cache()
+ except Exception: # noqa: BLE001, S110 - best-effort teardown
+ pass
logger.info("Agentic IDE session ended: {}", session.id)
def set_focus_mode(self, enabled: bool) -> bool:
@@ -481,6 +506,133 @@ class Registry:
if term.status == "live":
term.status = "exited"
+ # ------------------------------------------------------------- panes
+ async def add_terminal(
+ self,
+ *,
+ agent: str | None = None,
+ name: str | None = None,
+ anchor: str | None = None,
+ direction: str = "right",
+ ) -> Terminal:
+ """Open one more terminal in the running workspace.
+
+ ``direction`` decides where it lands relative to ``anchor``:
+ ``"right"`` joins the anchor's row (side by side), ``"down"`` opens a new
+ row directly beneath it and pushes the rows below down. Without an anchor
+ the new pane goes after the last one.
+
+ The agent defaults to the anchor's, because splitting a Claude Code pane
+ almost always means "another one of these".
+ """
+ async with self._lock:
+ session = self._session
+ if session is None:
+ raise SessionError("No Agentic-IDE session is running.")
+ if len(session.terminals) >= MAX_TERMINALS:
+ raise SessionError(
+ f"This workspace already has the maximum of {MAX_TERMINALS} terminals."
+ )
+ if direction not in ("right", "down"):
+ raise SessionError("Direction must be 'right' or 'down'.")
+
+ base = session.find(anchor) if anchor else None
+ if anchor and base is None:
+ raise SessionError(f"No terminal called {anchor!r}.")
+ if base is None:
+ base = session.terminals[-1] if session.terminals else None
+
+ chosen = agent or (base.agent if base else "claude")
+ if chosen not in AGENT_BINARIES:
+ raise SessionError(f"Unknown agent: {chosen}")
+ if agent_argv(chosen) is None:
+ pretty = AGENT_DISPLAY.get(chosen, chosen)
+ raise SessionError(f"{pretty} is not installed or not on this machine's PATH.")
+
+ used = {normalize(t.name) for t in session.terminals}
+ wanted = (name or "").strip()
+ if not wanted:
+ # Next unused call-sign from the pool, so names stay speakable
+ # however many times the user splits.
+ pool = default_names(MAX_TERMINALS * 2)
+ wanted = next(
+ (n for n in pool if normalize(n) not in used),
+ f"T{len(session.terminals) + 1}",
+ )
+ final = wanted
+ suffix = 2
+ while normalize(final) in used:
+ final = f"{wanted} {suffix}"
+ suffix += 1
+
+ if base is None:
+ row = 0
+ position = len(session.terminals)
+ elif direction == "right":
+ row = base.row
+ position = session.terminals.index(base) + 1
+ else:
+ row = base.row + 1
+ for other in session.terminals:
+ if other.row >= row:
+ other.row += 1
+ position = session.terminals.index(base) + 1
+
+ term = Terminal(
+ key=normalize(final) or f"t{len(session.terminals)}",
+ name=final,
+ agent=chosen,
+ display_name=AGENT_DISPLAY.get(chosen, chosen),
+ index=len(session.terminals),
+ row=row,
+ )
+ session.terminals.insert(position, term)
+ self._renumber(session)
+ logger.info(
+ "Agentic IDE: added terminal {} ({}) {} of {}",
+ term.name,
+ term.agent,
+ direction,
+ base.name if base else "the grid",
+ )
+ return term
+
+ async def close_terminal(self, wanted: str) -> Terminal:
+ """Stop one terminal's agent and remove its pane from the workspace."""
+ async with self._lock:
+ session = self._session
+ if session is None:
+ raise SessionError("No Agentic-IDE session is running.")
+ term = session.find(wanted)
+ if term is None:
+ known = ", ".join(t.name for t in session.terminals) or "none"
+ raise SessionError(f"No terminal called {wanted!r}. Running: {known}.")
+
+ if term.pty_id and self._pty is not None:
+ try:
+ self._pty.close(term.pty_id)
+ except Exception: # noqa: BLE001, S110 - best-effort teardown
+ pass
+ term.pty_id = None
+ term.status = "exited"
+ session.terminals.remove(term)
+ self._renumber(session)
+ logger.info("Agentic IDE: closed terminal {}", term.name)
+ return term
+
+ @staticmethod
+ def _renumber(session: Session) -> None:
+ """Re-pack indexes and rows after an insert or a removal.
+
+ Removing the only pane of a row would otherwise leave a gap in the row
+ numbers and the grid would render an empty band.
+ """
+ rows = sorted({t.row for t in session.terminals})
+ remap = {old: new for new, old in enumerate(rows)}
+ for position, term in enumerate(session.terminals):
+ term.index = position
+ term.row = remap.get(term.row, 0)
+
# --------------------------------------------------------------- prompt
async def send_prompt(self, wanted: str, text: str) -> Terminal:
"""Type ``text`` into a terminal and press Enter.
diff --git a/jarvis/commands/registry.py b/jarvis/commands/registry.py
index ea6840f137..00ea3579a6 100644
--- a/jarvis/commands/registry.py
+++ b/jarvis/commands/registry.py
@@ -661,8 +661,13 @@ def _build_registry() -> tuple[AppCommand, ...]:
id="agentic-ide-prompt",
title="Prompt an Agentic-IDE terminal",
description=(
- "Type a prompt into the named terminal's coding agent and press "
- "Enter. Use the user's own instruction as the prompt text."
+ "Send an instruction to the coding agent in a named terminal. "
+ "Use this whenever the user tells a terminal to do something "
+ "('tell Kai to ...', 'Mika soll ...', 'let Nova refactor ...') "
+ "— that work belongs to that agent, never to a background "
+ "worker. Pass the user's instruction as the prompt; with "
+ "compose=true it is rewritten into a briefed task with the "
+ "relevant files of this workspace attached."
),
method="POST",
path="/api/agentic-ide/terminals/{name}/prompt",
@@ -678,6 +683,15 @@ def _build_registry() -> tuple[AppCommand, ...]:
min_length=1,
max_length=4000,
),
+ "compose": {
+ "type": "boolean",
+ "default": True,
+ "description": (
+ "Rewrite a spoken/rough instruction into a precise "
+ "prompt and attach @file references before sending. "
+ "Set false only to send text through verbatim."
+ ),
+ },
},
"required": ["name", "prompt"],
},
diff --git a/jarvis/ui/web/agentic_ide_routes.py b/jarvis/ui/web/agentic_ide_routes.py
index 11bfc7cf6d..5ecc17665a 100644
--- a/jarvis/ui/web/agentic_ide_routes.py
+++ b/jarvis/ui/web/agentic_ide_routes.py
@@ -68,6 +68,25 @@ class StartSessionRequest(BaseModel):
)
+class AddTerminalRequest(BaseModel):
+ agent: str | None = Field(
+ default=None,
+ description="Coding agent to run; defaults to the anchor terminal's.",
+ )
+ name: str | None = Field(
+ default=None,
+ description="Call-sign for the new terminal; auto-assigned when omitted.",
+ )
+ anchor: str | None = Field(
+ default=None,
+ description="Call-sign of the terminal to split; defaults to the last one.",
+ )
+ direction: str = Field(
+ default="right",
+ description="'right' places it beside the anchor, 'down' below it.",
+ )
+
+
class ModeRequest(BaseModel):
enabled: bool = Field(
description="True narrows Jarvis to this workspace; False returns to normal."
@@ -79,6 +98,18 @@ class PromptRequest(BaseModel):
max_length=MAX_PROMPT_CHARS,
description="Text to type into the terminal, followed by Enter.",
)
+ compose: bool = Field(
+ default=False,
+ description=(
+ "Rewrite the text into a briefed prompt for the coding agent and "
+ "attach @file references from this workspace before sending. Meant "
+ "for spoken/rough instructions; the typed prompt bar sends as-is."
+ ),
+ )
+ dry_run: bool = Field(
+ default=False,
+ description="Compose and return the prompt WITHOUT sending it.",
+ )
class AgentStatus(BaseModel):
@@ -359,6 +390,40 @@ async def set_mode(req: ModeRequest) -> dict:
return {"ok": True, "focus_mode": enabled}
[email protected]("/terminals", summary="Open one more terminal")
+async def add_terminal(req: AddTerminalRequest) -> dict:
+ """Add a terminal to the running workspace, beside or below another one.
+
+ ``direction="right"`` puts it in the same grid row as ``anchor`` (side by
+ side); ``"down"`` opens a new row underneath. The agent defaults to the
+ anchor's, since splitting a pane usually means "another one of these".
+ """
+ try:
+ term = await get_registry().add_terminal(
+ agent=req.agent,
+ name=req.name,
+ anchor=req.anchor,
+ direction=req.direction,
+ )
+ except SessionError as exc:
+ raise HTTPException(status_code=409, detail=str(exc)) from exc
+ return {"ok": True, "terminal": term.to_dict(), "state": get_registry().state()}
+
+
+ "/terminals/{name}",
+ summary="Close one terminal",
+ openapi_extra={"x-jarvis-dangerous": True},
+)
+async def close_terminal(name: str) -> dict:
+ """Stop the agent in the terminal called ``name`` and remove its pane."""
+ try:
+ term = await get_registry().close_terminal(name)
+ except SessionError as exc:
+ raise HTTPException(status_code=404, detail=str(exc)) from exc
+ return {"ok": True, "closed": term.name, "state": get_registry().state()}
+
+
@router.get("/terminals/{name}/report", summary="What one terminal is doing")
async def terminal_report(name: str, lines: int = 40) -> dict:
"""Status plus the recent readable output of the terminal called ``name``."""
@@ -370,9 +435,64 @@ async def terminal_report(name: str, lines: int = 40) -> dict:
@router.post("/terminals/{name}/prompt", summary="Send a prompt to one terminal")
async def terminal_prompt(name: str, req: PromptRequest) -> dict:
- """Type ``prompt`` into the terminal called ``name`` and press Enter."""
+ """Type ``prompt`` into the terminal called ``name`` and press Enter.
+
+ With ``compose=true`` the text is first rewritten into a prompt worth
+ running — speech artefacts removed, the task stated as an imperative, and
+ the relevant files of this workspace attached as ``@path`` references. That
+ is the path a spoken instruction takes; the UI's prompt bar sends verbatim,
+ because someone who typed it already wrote what they meant.
+
+ ``dry_run=true`` returns the composed prompt without sending it, so a caller
+ can show it for approval first.
+ """
+ registry = get_registry()
+ session = registry.session
+ if session is None:
+ raise HTTPException(
+ status_code=409, detail="No Agentic-IDE session is running."
+ )
+
+ text = req.prompt
+ composed_by = "raw"
+ files: list[str] = []
+ if req.compose:
+ from jarvis.agentic_ide.prompt_composer import compose as compose_prompt
+
+ term_for_compose = session.find(name)
+ if term_for_compose is None:
+ known = ", ".join(t.name for t in session.terminals) or "none"
+ raise HTTPException(
+ status_code=404,
+ detail=f"No terminal called {name!r}. Running: {known}.",
+ )
+ result = await compose_prompt(
+ req.prompt,
+ session=session,
+ terminal_name=term_for_compose.name,
+ agent_display=AGENT_DISPLAY.get(
+ term_for_compose.agent, term_for_compose.agent
+ ),
+ )
+ text, composed_by, files = result.text, result.composed_by, result.files
+ if not text:
+ raise HTTPException(
+ status_code=422, detail="The prompt was empty after composition."
+ )
+
+ if req.dry_run:
+ return {
+ "ok": True,
+ "terminal": name,
+ "sent": "",
+ "composed": text,
+ "composed_by": composed_by,
+ "files": files,
+ "dry_run": True,
+ }
+
try:
- term = await get_registry().send_prompt(name, req.prompt)
+ term = await registry.send_prompt(name, text)
except SessionError as exc:
raise HTTPException(status_code=409, detail=str(exc)) from exc
return {
@@ -380,6 +500,8 @@ async def terminal_prompt(name: str, req: PromptRequest) -> dict:
"terminal": term.name,
"agent": AGENT_DISPLAY.get(term.agent, term.agent),
"sent": term.last_prompt,
+ "composed_by": composed_by,
+ "files": files,
"prompts_sent": term.prompts_sent,
}
diff --git a/jarvis/ui/web/frontend/src/components/agentic/AgenticGrid.test.tsx b/jarvis/ui/web/frontend/src/components/agentic/AgenticGrid.test.tsx
new file mode 100644
index 0000000000..4a89000e33
--- /dev/null
+++ b/jarvis/ui/web/frontend/src/components/agentic/AgenticGrid.test.tsx
@@ -0,0 +1,296 @@
+import { cleanup, fireEvent, render, screen, waitFor } from "@testing-library/react";
+import { afterEach, beforeEach, describe, expect, it, vi } from "vitest";
+
+const pushToast = vi.fn();
+vi.mock("@/store/events", () => ({
+ useEventStore: (selector: (s: Record<string, unknown>) => unknown) =>
+ selector({ pushToast }),
+}));
+
+vi.mock("@/lib/agenticIdeApi", () => ({
+ addTerminal: vi.fn(),
+ closeTerminal: vi.fn(),
+ promptTerminal: vi.fn(),
+}));
+
+/**
+ * xterm needs a real canvas, so the pane is stubbed — but the stub exposes the
+ * same action buttons, because what these tests check is the WIRING: which call
+ * a button makes and what the grid does with the answer.
+ */
+vi.mock("./AgenticTerminal", () => ({
+ AgenticTerminal: ({
+ name,
+ maximized,
+ splitDisabled,
+ onToggleMaximize,
+ onSplitRight,
+ onSplitDown,
+ onClose,
+ }: {
+ name: string;
+ maximized?: boolean;
+ splitDisabled?: boolean;
+ onToggleMaximize?: () => void;
+ onSplitRight?: () => void;
+ onSplitDown?: () => void;
+ onClose?: () => void;
+ }) => (
+ <div data-testid={`pane-${name}`} data-maximized={maximized ? "yes" : "no"}>
+ {name}
+ <button data-testid={`pane-maximize-${name}`} onClick={onToggleMaximize}>
+ max
+ </button>
+ <button
+ data-testid={`pane-split-right-${name}`}
+ disabled={splitDisabled}
+ onClick={onSplitRight}
+ >
+ right
+ </button>
+ <button
+ data-testid={`pane-split-down-${name}`}
+ disabled={splitDisabled}
+ onClick={onSplitDown}
+ >
+ down
+ </button>
+ <button data-testid={`pane-close-${name}`} onClick={onClose}>
+ close
+ </button>
+ </div>
+ ),
+ PaneStatusPill: () => <span>live</span>,
+}));
+
+import { AgenticGrid } from "./AgenticGrid";
+import * as api from "@/lib/agenticIdeApi";
+import type { SessionState, TerminalState } from "@/lib/agenticIdeApi";
+
+function pane(name: string, row: number, index: number): TerminalState {
+ return {
+ key: name.toLowerCase(),
+ name,
+ agent: "claude",
+ display_name: "Claude Code",
+ index,
+ row,
+ status: "live",
+ exit_code: null,
+ error: "",
+ started_at: 0,
+ last_output_at: 0,
+ idle_seconds: 0,
+ prompts_sent: 0,
+ last_prompt: "",
+ lines_captured: 0,
+ };
+}
+
+function sessionWith(panes: Array<[string, number]>): SessionState {
+ return {
+ id: "ide_test",
+ folder: "/work/project",
+ project: {
+ path: "/work/project",
+ name: "project",
+ exists: true,
+ is_repo: true,
+ branch: "main",
+ stacks: [],
+ instruction_files: [],
+ top_level_dirs: [],
+ skills: [],
+ note: "",
+ },
+ created_at: 0,
+ focus_mode: false,
+ terminals: panes.map(([name, row], i) => pane(name, row, i)),
+ };
+}
+
+const BASE = sessionWith([
+ ["Mika", 0],
+ ["Nova", 0],
+]);
+
+beforeEach(() => {
+ vi.mocked(api.addTerminal).mockResolvedValue(
+ sessionWith([
+ ["Mika", 0],
+ ["Aria", 0],
+ ["Nova", 0],
+ ]),
+ );
+ vi.mocked(api.closeTerminal).mockResolvedValue(sessionWith([["Nova", 0]]));
+});
+
+afterEach(() => {
+ cleanup();
+ vi.clearAllMocks();
+});
+
+function renderGrid(session = BASE, extra: Record<string, unknown> = {}) {
+ const onSessionChanged = vi.fn();
+ render(
+ <AgenticGrid
+ session={session}
+ focusMode={false}
+ onToggleFocus={vi.fn()}
+ onClose={vi.fn()}
+ onSessionChanged={onSessionChanged}
+ {...extra}
+ />,
+ );
+ return { onSessionChanged };
+}
+
+describe("pane actions", () => {
+ it("splitting right asks for a pane in the same row", async () => {
+ const { onSessionChanged } = renderGrid();
+ fireEvent.click(screen.getByTestId("pane-split-right-Mika"));
+ await waitFor(() =>
+ expect(api.addTerminal).toHaveBeenCalledWith({
+ anchor: "Mika",
+ direction: "right",
+ }),
+ );
+ await waitFor(() => expect(onSessionChanged).toHaveBeenCalled());
+ });
+
+ it("splitting down asks for a new row", async () => {
+ renderGrid();
+ fireEvent.click(screen.getByTestId("pane-split-down-Nova"));
+ await waitFor(() =>
+ expect(api.addTerminal).toHaveBeenCalledWith({
+ anchor: "Nova",
+ direction: "down",
+ }),
+ );
+ });
+
+ it("a new pane becomes the prompt target", async () => {
+ renderGrid();
+ fireEvent.click(screen.getByTestId("pane-split-right-Mika"));
+ // The freshly added pane is the one the user just asked for, so the prompt
+ // bar should already point at it.
+ await waitFor(() =>
+ expect(screen.getByPlaceholderText(/instruction for Aria/i)).toBeTruthy(),
+ );
+ });
+
+ it("reports a refused split instead of pretending it worked", async () => {
+ vi.mocked(api.addTerminal).mockRejectedValue(
+ new Error("This workspace already has the maximum of 12 terminals."),
+ );
+ renderGrid();
+ fireEvent.click(screen.getByTestId("pane-split-right-Mika"));
+ await waitFor(() =>
+ expect(pushToast).toHaveBeenCalledWith(
+ "error",
+ "This workspace already has the maximum of 12 terminals.",
+ ),
+ );
+ });
+
+ it("disables the split buttons at the terminal limit", () => {
+ renderGrid(BASE, { maxTerminals: 2 });
+ expect((screen.getByTestId("pane-split-right-Mika") as HTMLButtonElement).disabled).toBe(
+ true,
+ );
+ expect((screen.getByTestId("pane-split-down-Mika") as HTMLButtonElement).disabled).toBe(
+ true,
+ );
+ });
+});
+
+describe("maximize", () => {
+ it("hides the other panes without unmounting them", () => {
+ // Unmounting would tear down the WebSocket and kill the agent, so the other
+ // panes must still be in the DOM — only hidden.
+ renderGrid();
+ fireEvent.click(screen.getByTestId("pane-maximize-Mika"));
+
+ const mika = screen.getByTestId("pane-Mika");
+ const nova = screen.getByTestId("pane-Nova");
+ expect(mika.getAttribute("data-maximized")).toBe("yes");
+ expect(nova).toBeTruthy();
+ expect(nova.parentElement?.className).toContain("hidden");
+ expect(mika.parentElement?.className).not.toContain("hidden");
+ });
+
+ it("clicking again restores the grid", () => {
+ renderGrid();
+ fireEvent.click(screen.getByTestId("pane-maximize-Mika"));
+ fireEvent.click(screen.getByTestId("pane-maximize-Mika"));
+ expect(screen.getByTestId("pane-Nova").parentElement?.className).not.toContain(
+ "hidden",
+ );
+ });
+
+ it("hides a whole row that holds no maximized pane", () => {
+ renderGrid(
+ sessionWith([
+ ["Mika", 0],
+ ["Nova", 1],
+ ]),
+ );
+ fireEvent.click(screen.getByTestId("pane-maximize-Mika"));
+ // Nova's entire row is hidden, not just the pane.
+ expect(screen.getByTestId("pane-Nova")).toBeTruthy();
+ });
+});
+
+describe("closing a pane", () => {
+ it("asks before killing the agent", () => {
+ renderGrid();
+ fireEvent.click(screen.getByTestId("pane-close-Mika"));
+ expect(screen.getByTestId("confirm-close-terminal")).toBeTruthy();
+ expect(screen.getByText(/Close Mika\?/)).toBeTruthy();
+ // Nothing has happened yet.
+ expect(api.closeTerminal).not.toHaveBeenCalled();
+ });
+
+ it("cancelling leaves the terminal alone", () => {
+ renderGrid();
+ fireEvent.click(screen.getByTestId("pane-close-Mika"));
+ fireEvent.click(screen.getByRole("button", { name: /keep it open/i }));
+ expect(screen.queryByTestId("confirm-close-terminal")).toBeNull();
+ expect(api.closeTerminal).not.toHaveBeenCalled();
+ });
+
+ it("confirming closes it and updates the workspace", async () => {
+ const { onSessionChanged } = renderGrid();
+ fireEvent.click(screen.getByTestId("pane-close-Mika"));
+ fireEvent.click(screen.getByTestId("confirm-close-terminal-confirm"));
+
+ await waitFor(() => expect(api.closeTerminal).toHaveBeenCalledWith("Mika"));
+ await waitFor(() => expect(onSessionChanged).toHaveBeenCalled());
+ await waitFor(() =>
+ expect(screen.queryByTestId("confirm-close-terminal")).toBeNull(),
+ );
+ });
+
+ it("escape cancels the dialog", () => {
+ renderGrid();
+ fireEvent.click(screen.getByTestId("pane-close-Mika"));
+ fireEvent.keyDown(screen.getByTestId("confirm-close-terminal"), { key: "Escape" });
+ expect(screen.queryByTestId("confirm-close-terminal")).toBeNull();
+ });
+
+ it("reports a refused close honestly", async () => {
+ vi.mocked(api.closeTerminal).mockRejectedValue(new Error("No terminal called 'Mika'."));
+ renderGrid();
+ fireEvent.click(screen.getByTestId("pane-close-Mika"));
+ fireEvent.click(screen.getByTestId("confirm-close-terminal-confirm"));
+ await waitFor(() =>
+ expect(pushToast).toHaveBeenCalledWith("error", "No terminal called 'Mika'."),
+ );
+ });
+
+ it("offers to open a terminal once the workspace is empty", () => {
+ renderGrid(sessionWith([]));
+ expect(screen.getByText(/Every terminal in this workspace is closed/i)).toBeTruthy();
+ expect(screen.getByRole("button", { name: /open a terminal/i })).toBeTruthy();
+ });
+});
diff --git a/jarvis/ui/web/frontend/src/components/agentic/AgenticGrid.tsx b/jarvis/ui/web/frontend/src/components/agentic/AgenticGrid.tsx
index 2b82cf9bc2..c4fbbf0132 100644
--- a/jarvis/ui/web/frontend/src/components/agentic/AgenticGrid.tsx
+++ b/jarvis/ui/web/frontend/src/components/agentic/AgenticGrid.tsx
@@ -29,7 +29,13 @@ import {
type PaneStatus,
} from "./AgenticTerminal";
import type { TerminalAppearance } from "./terminalThemes";
-import { promptTerminal, type SessionState } from "@/lib/agenticIdeApi";
+import {
+ addTerminal,
+ closeTerminal,
+ promptTerminal,
+ type SessionState,
+ type TerminalState,
+} from "@/lib/agenticIdeApi";
interface AgenticGridProps {
session: SessionState;
@@ -37,13 +43,10 @@ interface AgenticGridProps {
onToggleFocus: (enabled: boolean) => void;
onClose: () => void;
busy?: boolean;
-}
-
-function gridColumns(count: number): number {
- if (count <= 1) return 1;
- if (count <= 2) return 2;
- if (count <= 6) return Math.min(3, Math.ceil(count / 2));
- return 4;
+ /** Hard cap on panes, so the split buttons can disable themselves. */
+ maxTerminals?: number;
+ /** Adding or closing a pane changes the workspace — the owner re-reads it. */
+ onSessionChanged?: (session: SessionState) => void;
}
const FONT_MIN = 10;
@@ -55,6 +58,8 @@ export function AgenticGrid({
onToggleFocus,
onClose,
busy = false,
+ maxTerminals = 12,
+ onSessionChanged,
}: AgenticGridProps) {
const pushToast = useEventStore((s) => s.pushToast);
const [appearance, setAppearance] = useState<TerminalAppearance>("light");
@@ -64,7 +69,53 @@ export function AgenticGrid({
const [prompt, setPrompt] = useState("");
const [sending, setSending] = useState(false);
- const columns = gridColumns(session.terminals.length);
+ const [maximized, setMaximized] = useState<string | null>(null);
+ const [pendingClose, setPendingClose] = useState<string | null>(null);
+ const [working, setWorking] = useState(false);
+
+ // Group panes into their rows. The backend keeps `row` packed and the list in
+ // render order, so this is a straight fold rather than a sort.
+ const rows = useMemo(() => {
+ const grouped: TerminalState[][] = [];
+ for (const term of session.terminals) {
+ while (grouped.length <= term.row) grouped.push([]);
+ grouped[term.row].push(term);
+ }
+ return grouped.filter((row) => row.length > 0);
+ }, [session.terminals]);
+
+ const atLimit = session.terminals.length >= maxTerminals;
+
+ const split = async (anchor: string | null, direction: "right" | "down") => {
+ setWorking(true);
+ try {
+ const next = await addTerminal({ anchor: anchor ?? undefined, direction });
+ onSessionChanged?.(next);
+ // A fresh pane should receive the next prompt — that is why it was opened.
+ const known = new Set(session.terminals.map((t) => t.name));
+ const added = next.terminals.find((t) => !known.has(t.name));
+ if (added) setTarget(added.name);
+ } catch (e) {
+ pushToast("error", (e as Error).message);
+ } finally {
+ setWorking(false);
+ }
+ };
+
+ const closeOne = async (name: string) => {
+ setWorking(true);
+ try {
+ const next = await closeTerminal(name);
+ setPendingClose(null);
+ if (maximized === name) setMaximized(null);
+ onSessionChanged?.(next);
+ if (target === name) setTarget(next.terminals[0]?.name ?? "");
+ } catch (e) {
+ pushToast("error", (e as Error).message);
+ } finally {
+ setWorking(false);
+ }
+ };
const setStatus = useCallback((name: string, status: PaneStatus, detail?: string) => {
setStatuses((prev) => ({ ...prev, [name]: { status, detail } }));
@@ -91,7 +142,7 @@ export function AgenticGrid({
);
return (
- <div className="flex h-full flex-col">
+ <div className="relative flex h-full flex-col">
{/* ---------------------------------------------------------- toolbar */}
<div className="flex flex-wrap items-center gap-x-3 gap-y-2 border-b border-border px-4 py-2.5">
<div className="flex min-w-0 flex-1 items-center gap-2">
@@ -189,27 +240,78 @@ export function AgenticGrid({
</div>
{/* ------------------------------------------------------------- grid */}
- <div
- className="grid flex-1 gap-3 overflow-hidden p-3"
- style={{
- gridTemplateColumns: `repeat(${columns}, minmax(0, 1fr))`,
- gridAutoRows: "1fr",
- }}
- >
- {session.terminals.map((term) => (
- <AgenticTerminal
- key={term.key}
- name={term.name}
- displayName={term.display_name}
- appearance={appearance}
- fontSize={fontSize}
- focused={target === term.name}
- onFocus={() => setTarget(term.name)}
- onStatus={(status, detail) => setStatus(term.name, status, detail)}
- />
- ))}
+ {/*
+ Rows, not one uniform grid: "split right" adds a pane to an existing row
+ and "split down" opens a new one, so rows can differ in width. Every pane
+ stays MOUNTED at all times — including while another one is maximized —
+ because unmounting it would tear down its WebSocket and kill the agent
+ behind it. Maximizing therefore hides the others with CSS instead.
+ */}
+ <div className="flex flex-1 flex-col gap-3 overflow-hidden p-3">
+ {rows.map((rowTerminals, rowIndex) => {
+ const rowHidden =
+ maximized !== null && !rowTerminals.some((t) => t.name === maximized);
+ return (
+ <div
+ key={rowIndex}
+ className={cn("flex min-h-0 flex-1 gap-3", rowHidden && "hidden")}
+ >
+ {rowTerminals.map((term) => (
+ <div
+ key={term.key}
+ className={cn(
+ "min-w-0 flex-1",
+ maximized !== null && maximized !== term.name && "hidden",
+ )}
+ >
+ <AgenticTerminal
+ name={term.name}
+ displayName={term.display_name}
+ appearance={appearance}
+ fontSize={fontSize}
+ focused={target === term.name}
+ maximized={maximized === term.name}
+ splitDisabled={atLimit || busy || working}
+ onFocus={() => setTarget(term.name)}
+ onStatus={(status, detail) => setStatus(term.name, status, detail)}
+ onToggleMaximize={() =>
+ setMaximized((current) => (current === term.name ? null : term.name))
+ }
+ onSplitRight={() => void split(term.name, "right")}
+ onSplitDown={() => void split(term.name, "down")}
+ onClose={() => setPendingClose(term.name)}
+ />
+ </div>
+ ))}
+ </div>
+ );
+ })}
+ {session.terminals.length === 0 && (
+ <div className="flex flex-1 flex-col items-center justify-center gap-3 text-sm text-muted-foreground">
+ <span>Every terminal in this workspace is closed.</span>
+ <button
+ type="button"
+ className="btn-primary"
+ disabled={busy || working}
+ onClick={() => void split(null, "right")}
+ >
+ <Plus className="h-4 w-4" />
+ Open a terminal
+ </button>
+ </div>
+ )}
</div>
+ {/* Closing a terminal kills a working agent, so it always asks first. */}
+ {pendingClose && (
+ <ConfirmClose
+ name={pendingClose}
+ busy={busy || working}
+ onCancel={() => setPendingClose(null)}
+ onConfirm={() => void closeOne(pendingClose)}
+ />
+ )}
+
{/* -------------------------------------------------------- prompt bar */}
<div className="border-t border-border px-4 py-3">
<div className="mb-2 flex flex-wrap items-center gap-2">
@@ -274,3 +376,63 @@ export function AgenticGrid({
</div>
);
}
+
+/**
+ * Confirmation before a pane is closed.
+ *
+ * Closing a terminal terminates a coding agent that may be mid-task, and there
+ * is no undo — so it always asks, and the dialog says what is actually lost.
+ * Escape cancels and the destructive button is not the default focus.
+ */
+function ConfirmClose({
+ name,
+ busy,
+ onCancel,
+ onConfirm,
+}: {
+ name: string;
+ busy: boolean;
+ onCancel: () => void;
+ onConfirm: () => void;
+}) {
+ return (
+ <div
+ role="dialog"
+ aria-modal="true"
+ aria-label={`Close ${name}`}
+ data-testid="confirm-close-terminal"
+ className="absolute inset-0 z-30 flex items-center justify-center bg-background/70 p-6 backdrop-blur-sm"
+ onKeyDown={(e) => {
+ if (e.key === "Escape") onCancel();
+ }}
+ >
+ <div className="w-full max-w-sm rounded-xl border border-border bg-card p-5 shadow-xl">
+ <h3 className="font-display text-base font-semibold">Close {name}?</h3>
+ <p className="mt-2 text-sm text-muted-foreground">
+ The coding agent running in this terminal is stopped and its session is
+ gone. Anything it already wrote to disk stays.
+ </p>
+ <div className="mt-5 flex items-center justify-end gap-2">
+ <button
+ type="button"
+ className="btn-ghost"
+ autoFocus
+ disabled={busy}
+ onClick={onCancel}
+ >
+ Keep it open
+ </button>
+ <button
+ type="button"
+ data-testid="confirm-close-terminal-confirm"
+ className="rounded-lg bg-destructive px-3 py-2 text-sm font-medium text-destructive-foreground transition-opacity hover:opacity-90 disabled:opacity-50"
+ disabled={busy}
+ onClick={onConfirm}
+ >
+ Close {name}
+ </button>
+ </div>
+ </div>
+ </div>
+ );
+}
diff --git a/jarvis/ui/web/frontend/src/components/agentic/AgenticTerminal.tsx b/jarvis/ui/web/frontend/src/components/agentic/AgenticTerminal.tsx
index b711eaeb9b..d01d1f944b 100644
--- a/jarvis/ui/web/frontend/src/components/agentic/AgenticTerminal.tsx
+++ b/jarvis/ui/web/frontend/src/components/agentic/AgenticTerminal.tsx
@@ -11,13 +11,50 @@
* tear down the WebSocket, which kills the agent running behind it and
* loses the whole session. So the connect effect depends on the pane key
* alone.
+ *
+ * ## Why this pane is configured the way it is
+ *
+ * A coding agent's TUI is the hardest thing you can ask a web terminal to
+ * draw: box-drawing frames, emoji status markers, live-rewritten spinner lines,
+ * and a prompt box that redraws on every keystroke. Rendered with xterm's
+ * defaults it came out visibly broken (reported 2026-07-25): text wrapped in
+ * the wrong places, the frame characters drifted out of their columns, and
+ * typing left artefacts behind. Four causes, all fixed here:
+ *
+ * * **Character width.** Without the Unicode 11 provider, xterm measures emoji
+ * and many box/symbol characters as one cell when the terminal on the other
+ * side counts them as two. Every such glyph then shifts the rest of the line
+ * by a column — which is exactly what "the frames look wrong" means.
+ * * **ConPTY line semantics.** On Windows the agent runs behind ConPTY, which
+ * re-wraps and re-emits lines differently from a POSIX pty. xterm has a
+ * dedicated compatibility mode for it; without `windowsPty` the re-emitted
+ * lines stack up as duplicated, half-overwritten rows.
+ * * **Measuring before the font is ready.** FitAddon derives the column count
+ * from one measured character. Run before the web font loads, it measures
+ * the fallback font, computes the wrong column count, and the agent then
+ * formats for a width the pane does not have. Hence the re-fit once
+ * `document.fonts.ready` resolves.
+ * * **Renderer.** The DOM renderer draws each cell as an element; with a TUI
+ * redrawing on every keystroke that is both slow and subtly misaligned. The
+ * canvas renderer draws on a grid, which is what a terminal actually is.
*/
import { useEffect, useRef } from "react";
import { Terminal } from "@xterm/xterm";
import { FitAddon } from "@xterm/addon-fit";
import { WebLinksAddon } from "@xterm/addon-web-links";
+import { CanvasAddon } from "@xterm/addon-canvas";
+import { Unicode11Addon } from "@xterm/addon-unicode11";
import "@xterm/xterm/css/xterm.css";
-import { AlertCircle, Circle, Loader2 } from "lucide-react";
+import {
+ AlertCircle,
+ Circle,
+ Columns2,
+ Loader2,
+ Maximize2,
+ Minimize2,
+ Rows2,
+ X,
+} from "lucide-react";
import { cn } from "@/lib/utils";
import {
PANE_CHROME,
@@ -38,6 +75,17 @@ interface AgenticTerminalProps {
focused?: boolean;
onFocus?: () => void;
onStatus?: (status: PaneStatus, detail?: string) => void;
+ /** True while this pane fills the whole grid. */
+ maximized?: boolean;
+ onToggleMaximize?: () => void;
+ /** Open another terminal beside this one. */
+ onSplitRight?: () => void;
+ /** Open another terminal below this one. */
+ onSplitDown?: () => void;
+ /** Close this pane (the caller asks for confirmation first). */
+ onClose?: () => void;
+ /** Disable the split buttons — the workspace is at its terminal limit. */
+ splitDisabled?: boolean;
}
function socketUrl(name: string, cols: number, rows: number): string {
@@ -56,10 +104,19 @@ export function AgenticTerminal({
focused = false,
onFocus,
onStatus,
+ maximized = false,
+ onToggleMaximize,
+ onSplitRight,
+ onSplitDown,
+ onClose,
+ splitDisabled = false,
}: AgenticTerminalProps) {
const containerRef = useRef<HTMLDivElement | null>(null);
const termRef = useRef<Terminal | null>(null);
const fitRef = useRef<FitAddon | null>(null);
+ // Lets the font-size effect trigger a REAL resize (xterm + the terminal
+ // process together) without reaching into the connect effect's socket.
+ const resizeRef = useRef<(() => void) | null>(null);
const statusRef = useRef<PaneStatus>("connecting");
// Latest callbacks/appearance without re-running the connect effect.
const onStatusRef = useRef(onStatus);
@@ -77,17 +134,56 @@ export function AgenticTerminal({
fontSize: initialRef.current.fontSize,
// Roomier than a console default — the single biggest readability win for
// an agent that prints prose, diffs and file trees rather than log lines.
- lineHeight: 1.35,
- letterSpacing: 0.2,
+ // Kept integral-friendly: fractional cell heights round differently per
+ // row and make a redrawn TUI box look ragged.
+ lineHeight: 1.3,
+ // Zero, not 0.2: extra tracking is added per cell, so a box-drawing frame
+ // and the text under it accumulate different sub-pixel offsets and the
+ // frame visibly bends. Monospace legibility comes from the line height.
+ letterSpacing: 0,
cursorBlink: true,
cursorStyle: "bar",
scrollback: 10000,
+ // Required by the Unicode 11 width provider below.
+ allowProposedApi: true,
+ // Instant scrolling: an agent that redraws a live status line while
+ // animating a scroll leaves visible tearing.
+ smoothScrollDuration: 0,
+ // Windows only. ConPTY re-emits and re-wraps lines in a way a POSIX pty
+ // never does; without telling xterm which backend it is talking to, those
+ // re-emitted lines pile up as duplicated, half-overwritten rows. Harmless
+ // to declare on other platforms — the pty there simply never triggers it,
+ // and the value is derived from the browser rather than assumed.
+ windowsPty: /windows/i.test(navigator.userAgent)
+ ? { backend: "conpty" as const }
+ : undefined,
theme: themeFor(initialRef.current.appearance),
});
const fit = new FitAddon();
term.loadAddon(fit);
term.loadAddon(new WebLinksAddon());
+ // Character WIDTH, not appearance: without this xterm measures emoji and
+ // many box/symbol glyphs as one cell while the agent on the other side
+ // counted two, and every such glyph shifts the rest of the line one column
+ // left. That is the "the frames are broken" symptom.
+ try {
+ const unicode = new Unicode11Addon();
+ term.loadAddon(unicode);
+ term.unicode.activeVersion = "11";
+ } catch {
+ /* proposed API unavailable in this build — widths stay at Unicode 6 */
+ }
term.open(container);
+ // Canvas rather than the DOM renderer: a coding agent's TUI redraws its
+ // prompt box on every keystroke, and per-cell DOM elements both lag and
+ // land on fractional pixel offsets. Loaded AFTER open() because it needs
+ // the mounted element. A failure here is not fatal — xterm falls back to
+ // the DOM renderer, which draws correctly, just less crisply.
+ try {
+ term.loadAddon(new CanvasAddon());
+ } catch {
+ /* no canvas in this environment — the DOM renderer still works */
+ }
termRef.current = term;
fitRef.current = fit;
try {
@@ -106,15 +202,22 @@ export function AgenticTerminal({
let everLive = false;
const sendResize = () => {
+ // A hidden pane measures 0x0 (maximizing another one hides this one), and
+ // fitting to that would resize the PTY to zero columns — which permanently
+ // wrecks the agent's full-screen drawing. Skip while not measurable; the
+ // ResizeObserver fires again when the pane comes back.
+ if (container.clientWidth < 8 || container.clientHeight < 8) return;
try {
fit.fit();
} catch {
return;
}
+ if (term.cols < 2 || term.rows < 2) return;
if (ws && ws.readyState === WebSocket.OPEN) {
ws.send(JSON.stringify({ t: "r", cols: term.cols, rows: term.rows }));
}
};
+ resizeRef.current = sendResize;
ws = new WebSocket(socketUrl(name, term.cols || 80, term.rows || 24));
ws.onopen = () => {
@@ -169,13 +272,45 @@ export function AgenticTerminal({
}
});
- window.addEventListener("resize", sendResize);
- const ro = new ResizeObserver(() => sendResize());
+ // The mount-time fit measured whatever font was loaded at that moment. If
+ // the display font arrives afterwards the cell width changes underneath the
+ // already-computed column count, and the agent then formats its output for a
+ // width the pane does not have — text wrapping in the wrong places, which is
+ // exactly the reported symptom. Re-fit once fonts settle.
+ let fontsSettled = false;
+ const refitOnFonts = () => {
+ if (disposed || fontsSettled) return;
+ fontsSettled = true;
+ term.clearTextureAtlas?.();
+ sendResize();
+ };
+ if (typeof document !== "undefined" && document.fonts?.ready) {
+ void document.fonts.ready.then(refitOnFonts).catch(() => undefined);
+ } else {
+ refitOnFonts();
+ }
+
+ // Resizes are coalesced: dragging a split or the window fires the observer
+ // dozens of times a second, and every fit both reflows xterm's buffer and
+ // sends a PTY resize the agent redraws for. Unthrottled that is the visible
+ // flicker while resizing.
+ let resizeTimer: number | undefined;
+ const scheduleResize = () => {
+ if (resizeTimer !== undefined) window.clearTimeout(resizeTimer);
+ resizeTimer = window.setTimeout(() => {
+ resizeTimer = undefined;
+ sendResize();
+ }, 80);
+ };
+
+ window.addEventListener("resize", scheduleResize);
+ const ro = new ResizeObserver(scheduleResize);
ro.observe(container);
return () => {
disposed = true;
- window.removeEventListener("resize", sendResize);
+ if (resizeTimer !== undefined) window.clearTimeout(resizeTimer);
+ window.removeEventListener("resize", scheduleResize);
ro.disconnect();
try {
ws?.close();
@@ -185,27 +320,33 @@ export function AgenticTerminal({
term.dispose();
termRef.current = null;
fitRef.current = null;
+ resizeRef.current = null;
};
// eslint-disable-next-line react-hooks/exhaustive-deps -- see file header:
// appearance/fontSize must NOT rebuild the pane (it would kill the agent).
}, [name]);
- // Live restyle — no reconnect, so the running agent is untouched.
+ // Live restyle — no reconnect, so the running agent is untouched. The canvas
+ // renderer caches rendered glyphs per colour in a texture atlas, so a theme
+ // change has to invalidate it or the old palette keeps being painted.
useEffect(() => {
const term = termRef.current;
if (!term) return;
term.options.theme = themeFor(appearance);
+ term.clearTextureAtlas?.();
}, [appearance]);
useEffect(() => {
const term = termRef.current;
if (!term) return;
term.options.fontSize = fontSize;
- try {
- fitRef.current?.fit();
- } catch {
- /* ignore */
- }
+ term.clearTextureAtlas?.();
+ // Changing the font size changes the COLUMN COUNT. Fitting locally without
+ // telling the terminal process leaves the agent formatting for the old
+ // width — it keeps wrapping at 100 columns in a pane that now holds 80, and
+ // every line breaks in the wrong place. The two must move together, so this
+ // goes through the same resize path the observer uses.
+ resizeRef.current?.();
}, [fontSize]);
const chrome = PANE_CHROME[appearance];
@@ -230,6 +371,12 @@ export function AgenticTerminal({
displayName={displayName}
appearance={appearance}
focused={focused}
+ maximized={maximized}
+ onToggleMaximize={onToggleMaximize}
+ onSplitRight={onSplitRight}
+ onSplitDown={onSplitDown}
+ onClose={onClose}
+ splitDisabled={splitDisabled}
/>
<div ref={containerRef} className="flex-1 overflow-hidden px-2 pb-1 pt-1" />
</div>
@@ -241,16 +388,28 @@ function PaneHeader({
displayName,
appearance,
focused,
+ maximized,
+ onToggleMaximize,
+ onSplitRight,
+ onSplitDown,
+ onClose,
+ splitDisabled,
}: {
name: string;
displayName: string;
appearance: TerminalAppearance;
focused: boolean;
+ maximized: boolean;
+ onToggleMaximize?: () => void;
+ onSplitRight?: () => void;
+ onSplitDown?: () => void;
+ onClose?: () => void;
+ splitDisabled: boolean;
}) {
const light = appearance === "light";
return (
<header
- className="flex items-center justify-between gap-2 border-b px-3 py-2"
+ className="group/header flex items-center justify-between gap-2 border-b px-3 py-2"
style={{
borderColor: PANE_CHROME[appearance].border,
background: light ? "rgba(0,0,0,0.025)" : "rgba(255,255,255,0.03)",
@@ -277,10 +436,104 @@ function PaneHeader({
{displayName}
</span>
</div>
+
+ {/* Pane actions. Kept quiet until the pane is hovered or focused, so a
+ grid of eight terminals is not a wall of icons — but always reachable
+ by keyboard, and always visible on the pane you are working in. */}
+ <div
+ className={cn(
+ "flex shrink-0 items-center gap-0.5 transition-opacity",
+ focused || maximized
+ ? "opacity-100"
+ : "opacity-0 focus-within:opacity-100 group-hover/header:opacity-100",
+ )}
+ >
+ <PaneAction
+ label={maximized ? `Restore ${name}` : `Maximize ${name}`}
+ testId={`pane-maximize-${name}`}
+ light={light}
+ onClick={onToggleMaximize}
+ >
+ {maximized ? <Minimize2 className="h-3.5 w-3.5" /> : <Maximize2 className="h-3.5 w-3.5" />}
+ </PaneAction>
+ <PaneAction
+ label={`Open another terminal beside ${name}`}
+ testId={`pane-split-right-${name}`}
+ light={light}
+ disabled={splitDisabled}
+ onClick={onSplitRight}
+ >
+ <Columns2 className="h-3.5 w-3.5" />
+ </PaneAction>
+ <PaneAction
+ label={`Open another terminal below ${name}`}
+ testId={`pane-split-down-${name}`}
+ light={light}
+ disabled={splitDisabled}
+ onClick={onSplitDown}
+ >
+ <Rows2 className="h-3.5 w-3.5" />
+ </PaneAction>
+ <PaneAction
+ label={`Close ${name}`}
+ testId={`pane-close-${name}`}
+ light={light}
+ danger
+ onClick={onClose}
+ >
+ <X className="h-3.5 w-3.5" />
+ </PaneAction>
+ </div>
</header>
);
}
+function PaneAction({
+ label,
+ testId,
+ light,
+ danger = false,
+ disabled = false,
+ onClick,
+ children,
+}: {
+ label: string;
+ testId: string;
+ light: boolean;
+ danger?: boolean;
+ disabled?: boolean;
+ onClick?: () => void;
+ children: React.ReactNode;
+}) {
+ return (
+ <button
+ type="button"
+ aria-label={label}
+ title={label}
+ data-testid={testId}
+ disabled={disabled || !onClick}
+ onClick={(e) => {
+ // The pane's own mousedown selects it as the prompt target; an action
+ // click must not also count as "typing here".
+ e.stopPropagation();
+ onClick?.();
+ }}
+ onMouseDown={(e) => e.stopPropagation()}
+ className={cn(
+ "flex h-6 w-6 items-center justify-center rounded transition-colors disabled:cursor-not-allowed disabled:opacity-30",
+ danger
+ ? "hover:bg-destructive/20 hover:text-destructive"
+ : light
+ ? "hover:bg-black/10"
+ : "hover:bg-white/10",
+ )}
+ style={{ color: light ? "#55555e" : "#a8a8b2" }}
+ >
+ {children}
+ </button>
+ );
+}
+
/** Small status pill reused by the grid toolbar. */
export function PaneStatusPill({ status, detail }: { status: PaneStatus; detail?: string }) {
if (status === "live") {
diff --git a/jarvis/ui/web/frontend/src/lib/agenticIdeApi.ts b/jarvis/ui/web/frontend/src/lib/agenticIdeApi.ts
index 1bc55e90f0..5fdf230b94 100644
--- a/jarvis/ui/web/frontend/src/lib/agenticIdeApi.ts
+++ b/jarvis/ui/web/frontend/src/lib/agenticIdeApi.ts
@@ -69,6 +69,10 @@ export interface ProjectProfile {
instruction_files: string[];
top_level_dirs: string[];
skills: string[];
+ /** Subagents this repo defines (`.claude/agents` / `.agents/agents`). */
+ subagents: string[];
+ /** Slash commands this repo defines (`.claude/commands`). */
+ commands: string[];
note: string;
}
@@ -78,6 +82,8 @@ export interface TerminalState {
agent: string;
display_name: string;
index: number;
+ /** Grid row: panes sharing a row render side by side. */
+ row: number;
status: "pending" | "live" | "exited" | "error";
exit_code: number | null;
error: string;
@@ -195,6 +201,41 @@ export async function endIdeSession(): Promise<void> {
if (!res.ok) throw new Error(await detail(res));
}
+/**
+ * Open one more terminal in the running workspace.
+ *
+ * `direction` decides where it lands relative to `anchor`: "right" joins that
+ * pane's row, "down" opens a new row beneath it. Returns the updated workspace.
+ */
+export async function addTerminal(payload: {
+ anchor?: string;
+ direction?: "right" | "down";
+ agent?: string;
+ name?: string;
+}): Promise<SessionState> {
+ const res = await fetch("/api/agentic-ide/terminals", {
+ method: "POST",
+ headers: { "Content-Type": "application/json" },
+ body: JSON.stringify(payload),
+ });
+ if (!res.ok) throw new Error(await detail(res));
+ const body = (await res.json()) as { state: IdeState };
+ if (!body.state.session) throw new Error("The workspace closed while adding a terminal.");
+ return body.state.session;
+}
+
+/** Stop one terminal's agent and remove its pane. Returns the updated workspace. */
+export async function closeTerminal(name: string): Promise<SessionState> {
+ const res = await fetch(
+ `/api/agentic-ide/terminals/${encodeURIComponent(name)}`,
+ { method: "DELETE" },
+ );
+ if (!res.ok) throw new Error(await detail(res));
+ const body = (await res.json()) as { state: IdeState };
+ if (!body.state.session) throw new Error("The workspace is no longer open.");
+ return body.state.session;
+}
+
export async function setFocusMode(enabled: boolean): Promise<boolean> {
const res = await fetch("/api/agentic-ide/mode", {
method: "PUT",
@@ -206,14 +247,38 @@ export async function setFocusMode(enabled: boolean): Promise<boolean> {
return body.focus_mode;
}
-export async function promptTerminal(name: string, prompt: string): Promise<void> {
+export interface PromptResult {
+ terminal: string;
+ /** What was actually typed into the agent. */
+ sent: string;
+ /** `llm` when a model wrote the prompt, `fallback` after cleanup, `raw` as typed. */
+ composed_by: "llm" | "fallback" | "raw";
+ /** Repo-relative files referenced with `@` in the sent prompt. */
+ files: string[];
+}
+
+/**
+ * Send an instruction to one terminal.
+ *
+ * `compose` asks the backend to rewrite a rough instruction into a briefed
+ * prompt with `@file` references attached. The typed prompt bar leaves it off —
+ * someone who typed a prompt already wrote what they meant, and silently
+ * rewriting it would be the wrong kind of helpful. Spoken instructions take the
+ * composed path.
+ */
+export async function promptTerminal(
+ name: string,
+ prompt: string,
+ options: { compose?: boolean } = {},
+): Promise<PromptResult> {
const res = await fetch(
`/api/agentic-ide/terminals/${encodeURIComponent(name)}/prompt`,
{
method: "POST",
headers: { "Content-Type": "application/json" },
- body: JSON.stringify({ prompt }),
+ body: JSON.stringify({ prompt, compose: Boolean(options.compose) }),
},
);
if (!res.ok) throw new Error(await detail(res));
+ return (await res.json()) as PromptResult;
}
diff --git a/jarvis/ui/web/frontend/src/views/AgenticIdeView.test.tsx b/jarvis/ui/web/frontend/src/views/AgenticIdeView.test.tsx
index a1c352ba53..e3be21a8c3 100644
--- a/jarvis/ui/web/frontend/src/views/AgenticIdeView.test.tsx
+++ b/jarvis/ui/web/frontend/src/views/AgenticIdeView.test.tsx
@@ -89,6 +89,7 @@ function sessionWith(names: string[], focus = false): api.SessionState {
agent: "claude",
display_name: "Claude Code",
index,
+ row: index,
status: "live" as const,
exit_code: null,
error: "",
@@ -212,11 +213,18 @@ describe("Agentic IDE running workspace", () => {
render(<AgenticIdeView />);
const toggle = await screen.findByTestId("agentic-focus-toggle");
- expect(toggle.getAttribute("aria-pressed")).toBe("false");
- fireEvent.click(toggle);
+ // The view turns coding mode on by itself when a workspace opens, so the
+ // starting state is not asserted here — what matters is that the switch goes
+ // through the API rather than only flipping local state.
+ await waitFor(() => expect(api.setFocusMode).toHaveBeenCalled());
+ const before = toggle.getAttribute("aria-pressed") === "true";
+ vi.mocked(api.setFocusMode).mockResolvedValue(!before);
- await waitFor(() => expect(api.setFocusMode).toHaveBeenCalledWith(true));
- await waitFor(() => expect(toggle.getAttribute("aria-pressed")).toBe("true"));
+ fireEvent.click(toggle);
+ await waitFor(() => expect(api.setFocusMode).toHaveBeenLastCalledWith(!before));
+ await waitFor(() =>
+ expect(toggle.getAttribute("aria-pressed")).toBe(String(!before)),
+ );
});
it("sends a prompt to the selected terminal through the same endpoint voice uses", async () => {
@@ -225,7 +233,12 @@ describe("Agentic IDE running workspace", () => {
session: sessionWith(["Mika", "Nova"]),
max_terminals: 12,
});
- vi.mocked(api.promptTerminal).mockResolvedValue(undefined);
+ vi.mocked(api.promptTerminal).mockResolvedValue({
+ terminal: "Mika",
+ sent: "run the tests",
+ composed_by: "raw",
+ files: [],
+ });
render(<AgenticIdeView />);
await screen.findByTestId("pane-Mika");
diff --git a/jarvis/ui/web/frontend/src/views/AgenticIdeView.tsx b/jarvis/ui/web/frontend/src/views/AgenticIdeView.tsx
index b9500b1dea..c0012079b3 100644
--- a/jarvis/ui/web/frontend/src/views/AgenticIdeView.tsx
+++ b/jarvis/ui/web/frontend/src/views/AgenticIdeView.tsx
@@ -15,15 +15,17 @@
* i18n note: the section label and view header go through the locale files; the
* panel copy inside is still English-only source awaiting its i18n keys.
*/
-import { useCallback, useEffect, useMemo, useState } from "react";
+import { useCallback, useEffect, useMemo, useRef, useState } from "react";
import {
AlertCircle,
ArrowLeft,
ArrowRight,
+ Brain,
Check,
Download,
FolderOpen,
Loader2,
+ Mic,
Rocket,
Sparkles,
Terminal,
@@ -112,6 +114,43 @@ export function AgenticIdeView() {
void refresh();
}, [refresh]);
+ /*
+ * Being in this section IS the coding mode.
+ *
+ * Focus mode started as a switch you had to remember to flip, and the result
+ * was predictable: the workspace was open, agents were running, and Jarvis
+ * still answered as the general-purpose assistant because nobody had pressed
+ * the button. Standing in a room full of running coding agents and having to
+ * announce that you are now coding is not a mode, it is paperwork. So opening
+ * a workspace turns it on.
+ *
+ * The switch stays, and it stays honest: turning it OFF here is respected for
+ * as long as this workspace is open (`optedOutRef`), so "I want the normal
+ * assistant for a minute" works and does not get overridden a second later.
+ */
+ const optedOutRef = useRef(false);
+ const [modeIntroFor, setModeIntroFor] = useState<string | null>(null);
+
+ useEffect(() => {
+ if (!session || session.focus_mode || optedOutRef.current) return;
+ let cancelled = false;
+ void (async () => {
+ try {
+ const on = await setFocusMode(true);
+ if (cancelled) return;
+ setFocus(on);
+ // First workspace on this machine: say once what just changed. A mode
+ // that switches silently is indistinguishable from a bug.
+ if (on && !hasSeenModeIntro()) setModeIntroFor(session.id);
+ } catch {
+ /* the workspace still works; the mode toggle stays available */
+ }
+ })();
+ return () => {
+ cancelled = true;
+ };
+ }, [session]);
+
// Memoised so these arrays keep a stable identity across renders — see the
// note on buildPlan for what an unstable one costs.
const agents = useMemo(() => meta?.agents ?? [], [meta]);
@@ -193,6 +232,9 @@ export function AgenticIdeView() {
};
const toggleFocus = async (enabled: boolean) => {
+ // Remember a deliberate opt-out, or the auto-enable effect above would turn
+ // the mode straight back on and the switch would look broken.
+ optedOutRef.current = !enabled;
try {
setFocus(await setFocusMode(enabled));
} catch (e) {
@@ -203,13 +245,27 @@ export function AgenticIdeView() {
// ------------------------------------------------------------ running mode
if (session) {
return (
- <AgenticGrid
- session={session}
- focusMode={focusMode}
- onToggleFocus={(v) => void toggleFocus(v)}
- onClose={() => void close()}
- busy={busy}
- />
+ <>
+ <AgenticGrid
+ session={session}
+ focusMode={focusMode}
+ onToggleFocus={(v) => void toggleFocus(v)}
+ onClose={() => void close()}
+ busy={busy}
+ maxTerminals={meta?.max_terminals ?? 12}
+ onSessionChanged={setSession}
+ />
+ {modeIntroFor === session.id && (
+ <CodingModeIntro
+ terminals={session.terminals.map((x) => x.name)}
+ project={session.project.name}
+ onDismiss={() => {
+ rememberModeIntro();
+ setModeIntroFor(null);
+ }}
+ />
+ )}
+ </>
);
}
@@ -429,6 +485,114 @@ export function AgenticIdeView() {
);
}
+/*
+ * One-time explanation of what entering a workspace changes.
+ *
+ * Shown once per machine, not once per session: after the first time the user
+ * knows, and a modal that reappears every time is the thing people learn to
+ * dismiss without reading. Stored in localStorage rather than in config —
+ * "has this person seen a UI hint" is a property of this browser profile, not
+ * something worth a round-trip and a config write.
+ */
+const MODE_INTRO_KEY = "jarvis.agenticIde.codingModeIntroSeen";
+
+function hasSeenModeIntro(): boolean {
+ try {
+ return window.localStorage.getItem(MODE_INTRO_KEY) === "1";
+ } catch {
+ // Private mode / storage disabled: showing the hint again is a far smaller
+ // problem than crashing the view.
+ return false;
+ }
+}
+
+function rememberModeIntro(): void {
+ try {
+ window.localStorage.setItem(MODE_INTRO_KEY, "1");
+ } catch {
+ /* nothing to do — the hint will simply appear again */
+ }
+}
+
+function CodingModeIntro({
+ terminals,
+ project,
+ onDismiss,
+}: {
+ terminals: string[];
+ project: string;
+ onDismiss: () => void;
+}) {
+ const first = terminals[0] ?? "Mika";
+ const second = terminals[1] ?? "Nova";
+ return (
+ <div className="fixed inset-0 z-50 flex items-center justify-center bg-background/70 p-6 backdrop-blur-sm">
+ <div className="w-full max-w-lg rounded-2xl border border-primary/30 bg-card p-6 shadow-2xl">
+ <div className="mb-4 flex items-center gap-3">
+ <span className="flex h-10 w-10 items-center justify-center rounded-xl bg-primary/15">
+ <Brain className="h-5 w-5 text-primary" />
+ </span>
+ <div>
+ <h3 className="font-display text-lg font-semibold">Coding mode is on</h3>
+ <p className="text-xs text-muted-foreground">
+ While this workspace is open, Jarvis works inside {project}.
+ </p>
+ </div>
+ </div>
+
+ <ul className="space-y-3 text-sm">
+ <li className="flex gap-3">
+ <Mic className="mt-0.5 h-4 w-4 shrink-0 text-primary" />
+ <span>
+ <strong className="font-medium">Talk to the agents by name.</strong>{" "}
+ Say “tell {first} to look at the wake word code” and it goes
+ straight into {first}’s terminal — you never type the prompt
+ yourself.
+ </span>
+ </li>
+ <li className="flex gap-3">
+ <Sparkles className="mt-0.5 h-4 w-4 shrink-0 text-primary" />
+ <span>
+ <strong className="font-medium">Jarvis writes the prompt.</strong>{" "}
+ What you say gets turned into a proper instruction, with the
+ relevant files of this repository attached as <code>@</code>{" "}
+ references.
+ </span>
+ </li>
+ <li className="flex gap-3">
+ <Terminal className="mt-0.5 h-4 w-4 shrink-0 text-primary" />
+ <span>
+ <strong className="font-medium">Ask what they are doing.</strong>{" "}
+ “What is {second} up to?” is answered from what that terminal
+ actually printed.
+ </span>
+ </li>
+ <li className="flex gap-3">
+ <Brain className="mt-0.5 h-4 w-4 shrink-0 text-primary" />
+ <span>
+ <strong className="font-medium">Think out loud with Jarvis.</strong>{" "}
+ It knows this codebase — the stack, the branch, the instruction
+ files — so planning happens here instead of in a chat window.
+ </span>
+ </li>
+ </ul>
+
+ <p className="mt-4 text-xs text-muted-foreground">
+ No background agents are started while you are in here: work you give
+ a terminal stays with that terminal. Turn the mode off any time with
+ the button in the toolbar.
+ </p>
+
+ <div className="mt-5 flex justify-end">
+ <button type="button" className="btn-primary" onClick={onDismiss}>
+ Got it
+ </button>
+ </div>
+ </div>
+ </div>
+ );
+}
+
function StepRail({ step }: { step: Step }) {
const labels = ["Folder", "Terminals", "Agents", "Start"];
return (
diff --git a/tests/unit/agentic_ide/test_file_index.py b/tests/unit/agentic_ide/test_file_index.py
new file mode 100644
index 0000000000..b33016ca34
--- /dev/null
+++ b/tests/unit/agentic_ide/test_file_index.py
@@ -0,0 +1,100 @@
+"""Guards for the workspace file index — spoken words must reach real paths.
+
+The index exists so a dictated instruction can carry ``@file`` references, and
+its failure modes are all quiet ones: a ranking that puts a stale copy of the
+repo first, a plural that never matches, or a walk that never terminates. Each
+gets a test here because none of them would show up as an error — just as an
+agent that starts by searching for the file you already named.
+"""
+from __future__ import annotations
+
+from pathlib import Path
+
+import pytest
+
+from jarvis.agentic_ide import file_index
+
+
+def repo(tmp_path: Path) -> Path:
+ """A miniature project with the shapes that actually cause trouble."""
+ (tmp_path / "jarvis" / "plugins" / "wake").mkdir(parents=True)
+ (tmp_path / "jarvis" / "plugins" / "wake" / "vosk_kws_provider.py").write_text("x")
+ (tmp_path / "jarvis" / "core").mkdir(parents=True)
+ (tmp_path / "jarvis" / "core" / "turn_language.py").write_text("x")
+ (tmp_path / "frontend" / "src").mkdir(parents=True)
+ (tmp_path / "frontend" / "src" / "terminalThemes.ts").write_text("x")
+ (tmp_path / "tests" / "unit").mkdir(parents=True)
+ (tmp_path / "tests" / "unit" / "test_turn_language.py").write_text("x")
+ # Noise that must never be indexed.
+ (tmp_path / "node_modules" / "pkg").mkdir(parents=True)
+ (tmp_path / "node_modules" / "pkg" / "turn_language.py").write_text("x")
+ (tmp_path / ".claude" / "worktrees" / "old" / "jarvis" / "core").mkdir(parents=True)
+ (tmp_path / ".claude" / "worktrees" / "old" / "jarvis" / "core" / "turn_language.py").write_text("x")
+ (tmp_path / "logo.png").write_bytes(b"\x89PNG")
+ return tmp_path
+
+
+def test_spoken_words_resolve_to_the_real_file(repo: Path) -> None:
+ index = file_index.build_index(repo)
+ hits = index.suggest("schau dir den vosk wake provider an", limit=3)
+ assert hits[0] == "jarvis/plugins/wake/vosk_kws_provider.py"
+
+
+def test_a_plural_still_matches_its_file(repo: Path) -> None:
+ """People say "the terminal theme"; the file is `terminalThemes.ts`."""
+ index = file_index.build_index(repo)
+ hits = index.suggest("das terminal theme", limit=3)
+ assert "frontend/src/terminalThemes.ts" in hits
+
+
+def test_stale_repo_copies_are_never_indexed(repo: Path) -> None:
+ """A worktree holds a copy of every file; indexing it buries the real one."""
+ index = file_index.build_index(repo)
+ paths = [entry.rel for entry in index.entries]
+ assert not any("worktrees" in p for p in paths)
+ assert not any("node_modules" in p for p in paths)
+ assert "jarvis/core/turn_language.py" in paths
+
+
+def test_binaries_are_skipped(repo: Path) -> None:
+ index = file_index.build_index(repo)
+ assert not any(p.endswith(".png") for p in (e.rel for e in index.entries))
+
+
+def test_implementation_outranks_its_test_unless_tests_are_asked_for(
+ repo: Path,
+) -> None:
+ index = file_index.build_index(repo)
+ code_first = index.suggest("fix the turn language resolver", limit=2)
+ assert code_first[0] == "jarvis/core/turn_language.py"
+
+ asked = index.suggest("fix the turn language test", limit=2)
+ assert "tests/unit/test_turn_language.py" in asked
+
+
+def test_conversational_scaffolding_matches_nothing(repo: Path) -> None:
+ """"was ist das" carries no addressing power and must not rank a file."""
+ assert index_suggest(repo, "was ist das denn") == []
+
+
+def index_suggest(root: Path, text: str) -> list[str]:
+ return file_index.build_index(root).suggest(text, limit=3)
+
+
+def test_a_missing_folder_yields_an_empty_index_rather_than_raising(
+ tmp_path: Path,
+) -> None:
+ index = file_index.build_index(tmp_path / "does-not-exist")
+ assert len(index) == 0
+ assert index.suggest("anything") == []
+
+
+def test_cache_is_per_folder_and_clearable(repo: Path) -> None:
+ file_index.reset_cache()
+ assert file_index.cached_index(repo) is None
+ file_index.prime_index(repo)
+ # prime_index is asynchronous; the contract under test is only that priming
+ # never blocks or raises, and that the cache is resettable.
+ file_index.reset_cache()
+ assert file_index.cached_index(repo) is None
diff --git a/tests/unit/agentic_ide/test_intent.py b/tests/unit/agentic_ide/test_intent.py
new file mode 100644
index 0000000000..1b8bb0d908
--- /dev/null
+++ b/tests/unit/agentic_ide/test_intent.py
@@ -0,0 +1,141 @@
+"""Guards for the Agentic-IDE turn detector.
+
+The regression this file exists for (voice session 2026-07-25 15:47): the user
+said "Kannst du mal bitte schnell ein zu Kai ein Review schicken und zwar dass
+er ein Deep Dive machen soll ..." and Jarvis dispatched a background Codex
+worker into a fresh git worktree while the terminal called Kai sat idle. The
+utterance carried the depth marker "Deep Dive", the router's force-spawn hoist
+matched it, and the workspace never got a look in.
+
+Two properties are pinned here, and they pull against each other on purpose:
+
+* an addressed terminal claims the turn even when the sentence is full of
+ delegation-flavoured words, and
+* naming the spawn vehicle outright still reaches the spawn path — otherwise
+ the fix would simply have broken background agents whenever a workspace
+ happens to be open.
+"""
+from __future__ import annotations
+
+import pytest
+
+from jarvis.agentic_ide import intent
+
+NAMES = ["Mika", "Nova", "Aria", "Kai"]
+
+# The verbatim transcript from the live failure, truncated the way the log
+# recorded it.
+LIVE_FAILURE = (
+ "Kannst du mal bitte schnell ein zu Kai ein Review schicken und zwar dass "
+ "er ein Deep Dive machen soll und dann kompletten Deep Dive machen und "
+ "gucken ob irgendwo Fehler sind"
+)
+
+
+def test_live_failure_reaches_the_terminal_not_a_background_worker() -> None:
+ """The exact 2026-07-25 utterance must belong to Kai."""
+ found = intent.detect(LIVE_FAILURE, names=NAMES)
+ assert found is not None
+ assert found.terminal == "Kai"
+ assert found.kind == intent.KIND_PROMPT
+ # And the router's guard must agree, or force-spawn wins again.
+ assert intent.owns_turn(LIVE_FAILURE, names=NAMES) is True
+
+
+ ("utterance", "terminal"),
+ [
+ ("Sag Mika, sie soll die Tests laufen lassen", "Mika"),
+ ("Tell Nova to refactor the wake word provider", "Nova"),
+ ("Nova should look at the vosk provider", "Nova"),
+ ("Aria, mach mal einen Review vom Audio-Code", "Aria"),
+ ("Schick das an Kai", "Kai"),
+ ("Dile a Kai que revise el codigo", "Kai"),
+ ("Lass Mika den Bug im Wake-Pfad untersuchen", "Mika"),
+ ],
+)
+def test_addressing_shapes_across_locales(utterance: str, terminal: str) -> None:
+ found = intent.detect(utterance, names=NAMES)
+ assert found is not None, utterance
+ assert found.terminal == terminal
+ assert found.kind == intent.KIND_PROMPT
+
+
+ ("utterance", "terminal"),
+ [
+ ("Was macht Mika gerade?", "Mika"),
+ ("What is Kai doing?", "Kai"),
+ ("Ist Nova fertig?", "Nova"),
+ ("Wie ist der Status von Aria?", "Aria"),
+ ],
+)
+def test_questions_about_a_pane_are_reads_not_prompts(
+ utterance: str, terminal: str
+) -> None:
+ """Asking what an agent is doing must never type the question into it."""
+ found = intent.detect(utterance, names=NAMES)
+ assert found is not None, utterance
+ assert found.terminal == terminal
+ assert found.kind == intent.KIND_REPORT
+
+
+ "utterance",
+ [
+ "Spawne einen Subagenten der Kai hilft",
+ "Start a background agent to review this",
+ "Mach das im Hintergrund, Mika braucht das nicht",
+ "Delegiere das an einen Worker",
+ ],
+)
+def test_naming_the_spawn_vehicle_still_wins(utterance: str) -> None:
+ """A workspace being open must not swallow an explicit delegation request."""
+ assert intent.owns_turn(utterance, names=NAMES) is False
+
+
+ "utterance",
+ [
+ "Wie ist das Wetter heute?",
+ "Mach einen Deep Dive in meine Google Cloud Kosten",
+ "Kai ist ein schoener Name fuer ein Kind",
+ "Erklaer mir bitte wie Vosk funktioniert",
+ ],
+)
+def test_unrelated_turns_are_left_alone(utterance: str) -> None:
+ """A passing mention or an unrelated request is none of the detector's business."""
+ assert intent.detect(utterance, names=NAMES) is None
+ assert intent.owns_turn(utterance, names=NAMES) is False
+
+
+def test_no_open_workspace_means_no_claim() -> None:
+ """With no terminals running, nothing can be addressed."""
+ assert intent.detect("Sag Mika, sie soll die Tests starten", names=[]) is None
+
+
+def test_call_signs_are_read_from_the_session_not_a_fixed_list() -> None:
+ """A workspace with custom names behaves exactly like one with defaults."""
+ custom = ["Bruno", "Vega"]
+ found = intent.detect("Sag Bruno, er soll die Tests starten", names=custom)
+ assert found is not None
+ assert found.terminal == "Bruno"
+ # A default-pool name that is NOT in this workspace must not match.
+ assert intent.detect("Sag Mika, sie soll die Tests starten", names=custom) is None
+
+
+def test_instruction_keeps_the_work_when_stripping_would_eat_it() -> None:
+ """A short utterance falls back to the full text rather than a stub."""
+ found = intent.detect("Schick das an Kai", names=NAMES)
+ assert found is not None
+ # "das" alone would be useless to the composer; the whole sentence is honest.
+ assert len(found.instruction) >= len("Schick das an Kai")
+
+
+def test_instruction_drops_the_addressing_when_there_is_real_work_left() -> None:
+ found = intent.detect(
+ "Sag Mika, sie soll die Wake-Word-Erkennung reparieren", names=NAMES
+ )
+ assert found is not None
+ assert "Mika" not in found.instruction
+ assert "Wake-Word-Erkennung" in found.instruction
diff --git a/tests/unit/agentic_ide/test_panes.py b/tests/unit/agentic_ide/test_panes.py
new file mode 100644
index 0000000000..74711821d1
--- /dev/null
+++ b/tests/unit/agentic_ide/test_panes.py
@@ -0,0 +1,230 @@
+"""Adding and closing panes in a running workspace.
+
+The row model is what makes the two split buttons mean something: "right" joins
+the anchor's row so the panes render side by side, "down" opens a new row
+beneath it. These tests pin that arithmetic, because an off-by-one in the row
+numbers renders as an empty band in the grid or as two panes stacked where one
+was expected.
+"""
+from __future__ import annotations
+
+from pathlib import Path
+
+import pytest
+
+from jarvis.agentic_ide import session as session_mod
+from jarvis.agentic_ide.session import MAX_TERMINALS, Registry, SessionError
+from tests.fakes.fake_pty_manager import FakePtyManager
+
+
+def fake_pty() -> FakePtyManager:
+ return FakePtyManager()
+
+
+def registry(fake_pty: FakePtyManager, monkeypatch: pytest.MonkeyPatch) -> Registry:
+ monkeypatch.setattr(session_mod, "agent_argv", lambda name: (f"/usr/bin/{name}",))
+ return Registry(pty_manager=fake_pty)
+
+
+async def _open(registry: Registry, folder: Path, count: int = 2):
+ return await registry.start(
+ str(folder), [{"agent": "claude"} for _ in range(count)]
+ )
+
+
+def _layout(registry: Registry) -> list[tuple[str, int]]:
+ """(name, row) in render order — the shape the grid draws."""
+ return [(t.name, t.row) for t in registry.session.terminals]
+
+
+async def _noop(_text: str) -> None:
+ return None
+
+
+async def _noop_exit(_code: int) -> None:
+ return None
+
+
+# --------------------------------------------------------------- initial rows
+async def test_a_fresh_workspace_puts_every_pane_in_row_zero(
+ registry: Registry, tmp_path: Path
+) -> None:
+ """The wizard's grid is one row; splitting is what creates more."""
+ await _open(registry, tmp_path, 3)
+ assert _layout(registry) == [("Mika", 0), ("Nova", 0), ("Aria", 0)]
+
+
+# ---------------------------------------------------------------- split right
+async def test_split_right_joins_the_anchor_row(registry: Registry, tmp_path: Path) -> None:
+ await _open(registry, tmp_path, 2)
+ term = await registry.add_terminal(anchor="Mika", direction="right")
+ assert term.row == 0
+ # Inserted directly after its anchor, not appended at the end.
+ assert _layout(registry) == [("Mika", 0), (term.name, 0), ("Nova", 0)]
+
+
+async def test_split_right_inherits_the_anchor_agent(
+ registry: Registry, tmp_path: Path
+) -> None:
+ """Splitting a Codex pane means "another Codex", not the default agent."""
+ await registry.start(str(tmp_path), [{"agent": "codex", "name": "Cody"}])
+ term = await registry.add_terminal(anchor="Cody", direction="right")
+ assert term.agent == "codex"
+
+
+async def test_an_explicit_agent_wins_over_the_anchor(
+ registry: Registry, tmp_path: Path
+) -> None:
+ await _open(registry, tmp_path, 1)
+ term = await registry.add_terminal(anchor="Mika", direction="right", agent="codex")
+ assert term.agent == "codex"
+
+
+# ----------------------------------------------------------------- split down
+async def test_split_down_opens_a_new_row_below_the_anchor(
+ registry: Registry, tmp_path: Path
+) -> None:
+ await _open(registry, tmp_path, 2)
+ term = await registry.add_terminal(anchor="Mika", direction="down")
+ assert term.row == 1
+ assert _layout(registry) == [("Mika", 0), (term.name, 1), ("Nova", 0)]
+
+
+async def test_split_down_pushes_existing_lower_rows_down(
+ registry: Registry, tmp_path: Path
+) -> None:
+ """Inserting between rows must not collide with the row already there."""
+ await _open(registry, tmp_path, 1)
+ bottom = await registry.add_terminal(anchor="Mika", direction="down")
+ middle = await registry.add_terminal(anchor="Mika", direction="down")
+ rows = {name: row for name, row in _layout(registry)}
+ assert rows["Mika"] == 0
+ assert rows[middle.name] == 1, "the newest pane sits directly under its anchor"
+ assert rows[bottom.name] == 2, "the older row moved down"
+
+
+# --------------------------------------------------------------------- naming
+async def test_new_panes_take_the_next_free_call_sign(
+ registry: Registry, tmp_path: Path
+) -> None:
+ await _open(registry, tmp_path, 2) # Mika, Nova
+ term = await registry.add_terminal(direction="right")
+ assert term.name == "Aria"
+
+
+async def test_an_explicit_name_is_deduplicated(registry: Registry, tmp_path: Path) -> None:
+ await _open(registry, tmp_path, 1)
+ term = await registry.add_terminal(name="Mika", direction="right")
+ assert term.name == "Mika 2"
+
+
+async def test_the_new_pane_starts_pending_and_addressable(
+ registry: Registry, tmp_path: Path
+) -> None:
+ await _open(registry, tmp_path, 1)
+ term = await registry.add_terminal(direction="down")
+ assert term.status == "pending"
+ assert registry.session.find(term.name) is term
+ assert registry.session.find(term.name.lower()) is term
+
+
+# --------------------------------------------------------------------- limits
+async def test_adding_past_the_limit_is_refused(registry: Registry, tmp_path: Path) -> None:
+ await _open(registry, tmp_path, MAX_TERMINALS)
+ with pytest.raises(SessionError, match="maximum"):
+ await registry.add_terminal(direction="right")
+
+
+async def test_an_unknown_anchor_is_refused(registry: Registry, tmp_path: Path) -> None:
+ await _open(registry, tmp_path, 1)
+ with pytest.raises(SessionError, match="Gandalf"):
+ await registry.add_terminal(anchor="Gandalf", direction="right")
+
+
+async def test_a_bad_direction_is_refused(registry: Registry, tmp_path: Path) -> None:
+ await _open(registry, tmp_path, 1)
+ with pytest.raises(SessionError, match="right.*down"):
+ await registry.add_terminal(anchor="Mika", direction="sideways")
+
+
+async def test_adding_without_a_workspace_is_refused(registry: Registry) -> None:
+ with pytest.raises(SessionError, match="No Agentic-IDE session"):
+ await registry.add_terminal(direction="right")
+
+
+async def test_a_missing_agent_binary_is_reported(
+ fake_pty: FakePtyManager, tmp_path: Path, monkeypatch: pytest.MonkeyPatch
+) -> None:
+ registry = Registry(pty_manager=fake_pty)
+ monkeypatch.setattr(session_mod, "agent_argv", lambda name: (f"/usr/bin/{name}",))
+ await registry.start(str(tmp_path), [{"agent": "claude"}])
+ monkeypatch.setattr(session_mod, "agent_argv", lambda name: None)
+ with pytest.raises(SessionError, match="not installed"):
+ await registry.add_terminal(direction="right")
+
+
+# ---------------------------------------------------------------------- close
+async def test_closing_a_pane_stops_its_agent(
+ registry: Registry, fake_pty: FakePtyManager, tmp_path: Path
+) -> None:
+ await _open(registry, tmp_path, 2)
+ await registry.attach("Mika", 80, 24, _noop, _noop_exit)
+ pty_id = registry.session.terminals[0].pty_id
+ closed = await registry.close_terminal("Mika")
+ assert closed.name == "Mika"
+ assert pty_id in fake_pty.closed
+ assert [t.name for t in registry.session.terminals] == ["Nova"]
+
+
+async def test_closing_repacks_the_rows(registry: Registry, tmp_path: Path) -> None:
+ """A row left empty would render as a blank band, so rows are re-packed."""
+ await _open(registry, tmp_path, 1)
+ middle = await registry.add_terminal(anchor="Mika", direction="down")
+ bottom = await registry.add_terminal(anchor=middle.name, direction="down")
+ assert [row for _n, row in _layout(registry)] == [0, 1, 2]
+
+ await registry.close_terminal(middle.name)
+ assert _layout(registry) == [("Mika", 0), (bottom.name, 1)]
+
+
+async def test_closing_the_last_pane_leaves_an_empty_workspace(
+ registry: Registry, tmp_path: Path
+) -> None:
+ """Allowed on purpose: the grid then offers to open a fresh terminal."""
+ await _open(registry, tmp_path, 1)
+ await registry.close_terminal("Mika")
+ assert registry.session is not None
+ assert registry.session.terminals == []
+
+
+async def test_closing_an_unknown_pane_names_the_real_ones(
+ registry: Registry, tmp_path: Path
+) -> None:
+ await _open(registry, tmp_path, 1)
+ with pytest.raises(SessionError, match="Mika"):
+ await registry.close_terminal("Gandalf")
+
+
+async def test_a_closed_pane_refuses_further_prompts(
+ registry: Registry, tmp_path: Path
+) -> None:
+ await _open(registry, tmp_path, 2)
+ await registry.attach("Mika", 80, 24, _noop, _noop_exit)
+ await registry.close_terminal("Mika")
+ with pytest.raises(SessionError, match="No terminal called"):
+ await registry.send_prompt("Mika", "still there?")
+
+
+async def test_a_reopened_call_sign_is_a_fresh_pane(
+ registry: Registry, tmp_path: Path
+) -> None:
+ """Closing Mika and splitting again must not resurrect the old transcript."""
+ await _open(registry, tmp_path, 1)
+ await registry.attach("Mika", 80, 24, _noop, _noop_exit)
+ registry.session.terminals[0].transcript.feed("old work\r\n")
+ await registry.close_terminal("Mika")
+ fresh = await registry.add_terminal(name="Mika", direction="right")
+ assert fresh.transcript.tail() == []
+ assert fresh.prompts_sent == 0