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): voice-aware coding workspace with named agent terminals

Ruben Lütke7086d0cfe8e1
diff --git a/jarvis/agentic_ide/__init__.py b/jarvis/agentic_ide/__init__.py
new file mode 100644
index 0000000000..d12368479c
--- /dev/null
+++ b/jarvis/agentic_ide/__init__.py
@@ -0,0 +1,24 @@
+"""Agentic IDE — a voice-aware coding workspace inside the desktop app.
+
+The user picks a folder, chooses how many terminals to open and which coding
+agent (Claude Code / Codex) runs in each, and gets a grid of real terminals in
+the app. Each terminal carries a spoken call-sign — Mika, Nova, Aria — so the
+whole workspace is addressable by voice: *"what is Mika doing?"*, *"tell Nova to
+run the tests"*. A focus mode narrows Jarvis to that workspace for as long as
+the user wants, and switches back cleanly.
+
+Module map:
+
+* ``names`` — the call-sign pool and fuzzy spoken-name resolution,
+* ``transcript`` — a sanitized, bounded view of what a terminal printed,
+* ``folders`` — folder picking plus a cheap profile of the chosen codebase,
+* ``session`` — the live registry: terminals, PTYs, prompt injection,
+* ``context`` — the workspace-awareness block used while focus mode is on.
+
+Nothing here is imported at boot; the REST layer
+(``jarvis.ui.web.agentic_ide_routes``) pulls it in on first use, and the PTY
+stack itself is imported lazily inside the registry (AP-26).
+"""
+from __future__ import annotations
+
+__all__ = ["context", "folders", "names", "session", "transcript"]
diff --git a/jarvis/agentic_ide/context.py b/jarvis/agentic_ide/context.py
new file mode 100644
index 0000000000..8affb62d74
--- /dev/null
+++ b/jarvis/agentic_ide/context.py
@@ -0,0 +1,88 @@
+"""The context block that turns focus mode into an actual coding mode.
+
+When the user flips the Agentic IDE into focus mode, every turn should be
+answered *inside* the open workspace: Jarvis should know which folder is open,
+what kind of codebase it is, which skills that repo defines, which agents are
+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.
+
+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
+
+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
+
+_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."
+)
+
+
+def _terminal_block(term) -> list[str]: # noqa: ANN001 - Terminal, avoid import cycle
+ status = term.status
+ bits = [f"{term.name} ({term.display_name}) — {status}"]
+ if status == "live" and term.last_output_at:
+ idle = max(0, int(time.time() - term.last_output_at))
+ bits.append(f"last output {idle}s ago")
+ if status == "exited" and term.exit_code is not None:
+ bits.append(f"exit code {term.exit_code}")
+ if status == "error" and term.error:
+ bits.append(term.error)
+ if term.prompts_sent:
+ bits.append(f"{term.prompts_sent} prompt(s) sent from Jarvis")
+ lines = [f"- {', '.join(bits)}"]
+ if term.last_prompt:
+ lines.append(f' last prompt sent: "{term.last_prompt[:200]}"')
+ tail = term.transcript.tail(_LINES_PER_TERMINAL)
+ if tail:
+ lines.append(" recent output:")
+ lines.extend(f" {line[:200]}" for line in tail)
+ return lines
+
+
+def focus_context_block(max_chars: int = _MAX_CHARS) -> str:
+ """Workspace-awareness block for this turn, or "" when focus mode is off."""
+ try:
+ from .session import get_registry
+
+ session = get_registry().session
+ except Exception: # noqa: BLE001 - never let awareness break a turn
+ return ""
+ if session is None or not session.focus_mode:
+ return ""
+
+ parts: list[str] = [_HEADER, ""]
+ parts.extend(session.profile.summary_lines())
+ parts.append("")
+ if session.terminals:
+ parts.append(f"Terminals in this workspace ({len(session.terminals)}):")
+ for term in session.terminals:
+ parts.extend(_terminal_block(term))
+ else:
+ parts.append("No terminals are open in this workspace yet.")
+
+ block = "\n".join(parts)
+ if len(block) > max_chars:
+ block = block[: max_chars - 1] + "…"
+ return block
+
+
+__all__ = ["focus_context_block"]
diff --git a/jarvis/agentic_ide/folders.py b/jarvis/agentic_ide/folders.py
new file mode 100644
index 0000000000..3d50726e79
--- /dev/null
+++ b/jarvis/agentic_ide/folders.py
@@ -0,0 +1,330 @@
+"""Folder picking + cheap project profiling for the Agentic IDE.
+
+Two jobs:
+
+*Picking* — the wizard's first step lets the user choose ANY folder on the
+machine, so this module lists directories the way a file dialog would, but over
+REST (the desktop app is a web UI; a native folder dialog would exist on one OS
+and not the others). Start points are discovered per platform: drive letters on
+Windows, ``/`` plus the mounted volumes on macOS/Linux, always the home folder
+and a handful of conventional code directories.
+
+*Profiling* — once a folder is chosen, Jarvis needs to be able to answer "what
+is this codebase?" without reading it file by file. ``probe_project`` collects a
+compact profile from a SINGLE shallow directory scan plus a few file-existence
+checks: git branch, detected stacks, the agent instruction files that are
+actually present, and the skills the repo defines. Deliberately shallow — no
+recursive walk — because this runs when a session starts and its result is what
+gets folded into the voice turn's context (AP-9: awareness work stays off the
+hot path; here it is computed once and cached in the session).
+"""
+from __future__ import annotations
+
+import os
+from dataclasses import asdict, dataclass, field
+from pathlib import Path
+
+# Directory names that are never interesting as a project root and would bury
+# the real folders in the picker.
+_SKIP_DIRS = frozenset(
+ {
+ "node_modules",
+ "__pycache__",
+ ".git",
+ ".venv",
+ "venv",
+ ".mypy_cache",
+ ".pytest_cache",
+ ".ruff_cache",
+ "dist",
+ "build",
+ ".next",
+ ".turbo",
+ "target",
+ ".idea",
+ ".vscode-test",
+ "$RECYCLE.BIN",
+ "System Volume Information",
+ }
+)
+
+# marker file/dir -> stack label. Order is irrelevant; all matches are reported.
+_STACK_MARKERS: tuple[tuple[str, str], ...] = (
+ ("pyproject.toml", "Python"),
+ ("requirements.txt", "Python"),
+ ("setup.py", "Python"),
+ ("package.json", "Node / JavaScript"),
+ ("tsconfig.json", "TypeScript"),
+ ("Cargo.toml", "Rust"),
+ ("go.mod", "Go"),
+ ("pom.xml", "Java / Maven"),
+ ("build.gradle", "Java / Gradle"),
+ ("Gemfile", "Ruby"),
+ ("composer.json", "PHP"),
+ ("Dockerfile", "Docker"),
+ ("docker-compose.yml", "Docker Compose"),
+ ("pubspec.yaml", "Dart / Flutter"),
+ ("*.csproj", ".NET"),
+)
+
+# Files a coding agent reads as its standing instructions. Which of these exist
+# tells the user (and Jarvis) how well-briefed an agent in this folder will be.
+_INSTRUCTION_FILES: tuple[str, ...] = (
+ "CLAUDE.md",
+ "AGENTS.md",
+ "GEMINI.md",
+ ".cursorrules",
+ "CONTRIBUTING.md",
+ "README.md",
+)
+
+_MAX_ENTRIES = 400
+_MAX_SKILLS = 60
+
+
+@dataclass(frozen=True, slots=True)
+class FolderEntry:
+ """One directory in the picker."""
+
+ name: str
+ path: str
+ is_project: bool
+ is_repo: bool
+
+
+@dataclass(slots=True)
+class ProjectProfile:
+ """Compact, cheap description of a chosen folder."""
+
+ path: str
+ name: str
+ exists: bool = True
+ is_repo: bool = False
+ branch: str | None = None
+ stacks: list[str] = field(default_factory=list)
+ instruction_files: list[str] = field(default_factory=list)
+ top_level_dirs: list[str] = field(default_factory=list)
+ skills: list[str] = field(default_factory=list)
+ note: str = ""
+
+ def to_dict(self) -> dict:
+ return asdict(self)
+
+ def summary_lines(self) -> list[str]:
+ """Plain-text lines for a model-facing context block."""
+ out = [f"Folder: {self.path}"]
+ if not self.exists:
+ out.append("This folder no longer exists on disk.")
+ return out
+ if self.is_repo:
+ out.append(f"Git repository{f' on branch {self.branch}' if self.branch else ''}.")
+ if self.stacks:
+ out.append("Stack: " + ", ".join(self.stacks))
+ if self.instruction_files:
+ out.append("Agent instructions present: " + ", ".join(self.instruction_files))
+ if self.top_level_dirs:
+ out.append("Top-level folders: " + ", ".join(self.top_level_dirs))
+ if self.skills:
+ shown = ", ".join(self.skills[:20])
+ more = "" if len(self.skills) <= 20 else f" (+{len(self.skills) - 20} more)"
+ out.append(f"Skills defined here ({len(self.skills)}): {shown}{more}")
+ return out
+
+
+def _is_hidden(name: str) -> bool:
+ return name.startswith(".")
+
+
+def _looks_like_project(entry_path: Path) -> tuple[bool, bool]:
+ """(is_project, is_repo) from marker files, without descending."""
+ is_repo = (entry_path / ".git").exists()
+ if is_repo:
+ return True, True
+ for marker, _label in _STACK_MARKERS:
+ if "*" in marker:
+ continue
+ if (entry_path / marker).exists():
+ return True, False
+ return False, False
+
+
+def start_points() -> list[FolderEntry]:
+ """Platform-appropriate places to begin browsing."""
+ seen: set[str] = set()
+ out: list[FolderEntry] = []
+
+ def add(path: Path, label: str | None = None) -> None:
+ try:
+ if not path.is_dir():
+ return
+ resolved = str(path)
+ except OSError:
+ return
+ if resolved in seen:
+ return
+ seen.add(resolved)
+ is_project, is_repo = _looks_like_project(path)
+ out.append(
+ FolderEntry(
+ name=label or path.name or resolved,
+ path=resolved,
+ is_project=is_project,
+ is_repo=is_repo,
+ )
+ )
+
+ home = Path.home()
+ add(home, "Home")
+ for conventional in ("Desktop", "Documents", "Projects", "Code", "dev", "src", "repos"):
+ add(home / conventional)
+
+ if os.name == "nt":
+ for letter in "CDEFGHIJKLMNOPQRSTUVWXYZ":
+ add(Path(f"{letter}:\\"), f"{letter}:\\")
+ else:
+ add(Path("/"), "/")
+ for volumes in ("/Volumes", "/media", "/mnt", "/opt", "/srv"):
+ add(Path(volumes))
+
+ return out
+
+
+def list_dir(
+ path: str | Path, *, include_hidden: bool = False
+) -> tuple[list[FolderEntry], str | None]:
+ """Sub-directories of ``path``. Returns ``(entries, error_message)``."""
+ target = Path(path).expanduser()
+ try:
+ if not target.is_dir():
+ return [], f"Not a folder: {target}"
+ except OSError as exc:
+ return [], f"Cannot read {target}: {exc}"
+
+ entries: list[FolderEntry] = []
+ try:
+ with os.scandir(target) as it:
+ for item in it:
+ if len(entries) >= _MAX_ENTRIES:
+ break
+ name = item.name
+ if name in _SKIP_DIRS:
+ continue
+ if not include_hidden and _is_hidden(name):
+ continue
+ try:
+ if not item.is_dir(follow_symlinks=False):
+ continue
+ except OSError:
+ continue
+ child = Path(item.path)
+ is_project, is_repo = _looks_like_project(child)
+ entries.append(
+ FolderEntry(
+ name=name,
+ path=str(child),
+ is_project=is_project,
+ is_repo=is_repo,
+ )
+ )
+ except PermissionError:
+ return [], f"No permission to read {target}"
+ except OSError as exc:
+ return [], f"Cannot read {target}: {exc}"
+
+ # Projects first, then alphabetically — the folder the user came for is
+ # almost always a project.
+ entries.sort(key=lambda e: (not e.is_project, e.name.lower()))
+ return entries, None
+
+
+def _git_branch(root: Path) -> str | None:
+ """Current branch from ``.git/HEAD`` — no subprocess, no git required."""
+ head = root / ".git" / "HEAD"
+ try:
+ text = head.read_text(encoding="utf-8", errors="replace").strip()
+ except OSError:
+ return None
+ if text.startswith("ref: refs/heads/"):
+ return text[len("ref: refs/heads/") :] or None
+ return text[:12] or None # detached HEAD
+
+
+def _collect_skills(root: Path) -> list[str]:
+ """Skill names defined in this repo (``.claude/skills`` / ``.agents/skills``)."""
+ found: list[str] = []
+ for base in (root / ".claude" / "skills", root / ".agents" / "skills"):
+ if not base.is_dir():
+ continue
+ try:
+ with os.scandir(base) as it:
+ for item in it:
+ if len(found) >= _MAX_SKILLS:
+ break
+ if item.is_dir(follow_symlinks=False) and not _is_hidden(item.name):
+ if item.name not in found:
+ found.append(item.name)
+ except OSError:
+ continue
+ return found
+
+
+def probe_project(path: str | Path) -> ProjectProfile:
+ """Shallow profile of a folder — one scandir plus a few existence checks."""
+ root = Path(path).expanduser()
+ profile = ProjectProfile(path=str(root), name=root.name or str(root))
+
+ try:
+ if not root.is_dir():
+ profile.exists = False
+ profile.note = "Folder not found."
+ return profile
+ except OSError as exc:
+ profile.exists = False
+ profile.note = f"Folder unreadable: {exc}"
+ return profile
+
+ names: set[str] = set()
+ dirs: list[str] = []
+ try:
+ with os.scandir(root) as it:
+ for item in it:
+ names.add(item.name)
+ try:
+ if item.is_dir(follow_symlinks=False):
+ if item.name in _SKIP_DIRS or _is_hidden(item.name):
+ continue
+ if len(dirs) < 24:
+ dirs.append(item.name)
+ except OSError:
+ continue
+ except OSError as exc:
+ profile.note = f"Folder only partially readable: {exc}"
+
+ profile.is_repo = (root / ".git").exists()
+ if profile.is_repo:
+ profile.branch = _git_branch(root)
+
+ stacks: list[str] = []
+ for marker, label in _STACK_MARKERS:
+ hit = (
+ any(n.endswith(marker[1:]) for n in names)
+ if marker.startswith("*")
+ else marker in names
+ )
+ if hit and label not in stacks:
+ stacks.append(label)
+ profile.stacks = stacks
+
+ profile.instruction_files = [f for f in _INSTRUCTION_FILES if f in names]
+ profile.top_level_dirs = sorted(dirs, key=str.lower)
+ profile.skills = _collect_skills(root)
+ return profile
+
+
+__all__ = [
+ "FolderEntry",
+ "ProjectProfile",
+ "list_dir",
+ "probe_project",
+ "start_points",
+]
diff --git a/jarvis/agentic_ide/names.py b/jarvis/agentic_ide/names.py
new file mode 100644
index 0000000000..e39c7948c8
--- /dev/null
+++ b/jarvis/agentic_ide/names.py
@@ -0,0 +1,149 @@
+"""Speakable call-signs for Agentic-IDE terminals.
+
+Why terminals get names instead of numbers: the whole point of the Agentic IDE
+is that the user can ASK about a running agent by voice — "what is Mika doing?"
+— and a spoken ordinal ("terminal three") is both awkward to say and easy for
+speech recognition to mangle into a different number. A short, phonetically
+distinct proper name survives an imperfect transcript far better, and a wrong
+match is recoverable (the user hears the name back in the answer).
+
+Selection criteria for the pool:
+- two syllables or fewer, no consonant clusters that ASR routinely drops,
+- pairwise phonetically distinct (no "Mika"/"Mica", no "Leo"/"Theo"),
+- neutral across the supported locales (de / en / es) — every name is
+ pronounceable and gender-neutral-ish in all three,
+- no collision with the wake word or with provider names.
+
+Name resolution is deliberately fuzzy (``resolve``): the caller is matching a
+name a human just spoke through an imperfect transcript. This is NOT the wake
+word — AP-27 does not apply, because a mismatch here costs one clarifying
+question, not a deaf assistant. The floor is still high enough that room noise
+does not silently address a random terminal.
+"""
+from __future__ import annotations
+
+from difflib import SequenceMatcher
+
+# Ordered: the Nth terminal of a session gets the Nth name, so the mapping is
+# reproducible across sessions and the user builds a habit ("Mika is always the
+# first pane").
+NAME_POOL: tuple[str, ...] = (
+ "Mika",
+ "Nova",
+ "Aria",
+ "Kai",
+ "Luna",
+ "Theo",
+ "Iris",
+ "Bruno",
+ "Vega",
+ "Juno",
+ "Milo",
+ "Zara",
+)
+
+# Below this similarity a spoken word is NOT treated as a terminal name. Tuned
+# so that a garbled "Mika" ("Micah", "Meeka", "Mikka") still lands while an
+# unrelated word ("Wiki", "Marker") does not.
+_MATCH_FLOOR = 0.72
+
+
+def default_names(count: int) -> list[str]:
+ """First ``count`` call-signs, extended with numbered fallbacks if needed."""
+ if count <= 0:
+ return []
+ names = list(NAME_POOL[:count])
+ # More terminals than pool entries: keep going deterministically rather than
+ # refusing a large grid.
+ index = 2
+ while len(names) < count:
+ for base in NAME_POOL:
+ if len(names) >= count:
+ break
+ names.append(f"{base}-{index}")
+ index += 1
+ return names
+
+
+def normalize(name: str) -> str:
+ """Lowercase, whitespace-stripped comparison key for a call-sign."""
+ return "".join(ch for ch in name.lower() if ch.isalnum())
+
+
+# Spelling variants that sound identical but wreck a character-level comparison.
+# Measured need: "Mika" comes back from speech recognition as "Micah", "Meeka",
+# "Mikka" — all of which score BELOW a plain similarity floor tight enough to
+# reject unrelated words. Folding the spelling first fixes both ends at once:
+# real garble lands, unrelated words still do not.
+_DIGRAPHS: tuple[tuple[str, str], ...] = (
+ ("sch", "s"),
+ ("ph", "f"),
+ ("ck", "k"),
+ ("th", "t"),
+ ("qu", "k"),
+ ("ai", "ei"),
+ ("ay", "ei"),
+ ("ey", "ei"),
+)
+_LETTERS = str.maketrans({"c": "k", "z": "s", "y": "i", "v": "f", "w": "f", "j": "i"})
+
+
+def phonetic_key(name: str) -> str:
+ """Spelling-insensitive key: same sound in, same string out.
+
+ Not a full Soundex — that collapses too far for four-letter call-signs
+ ("Kai" and "Kia" must still differ). This only folds the substitutions that
+ actually show up in speech transcripts, then squeezes doubled letters and
+ silent h.
+ """
+ key = normalize(name)
+ for src, dst in _DIGRAPHS:
+ key = key.replace(src, dst)
+ key = key.translate(_LETTERS)
+ # Silent h anywhere but the first position ("Micah" -> "mika").
+ key = key[:1] + key[1:].replace("h", "")
+ squeezed: list[str] = []
+ for ch in key:
+ if not squeezed or squeezed[-1] != ch:
+ squeezed.append(ch)
+ return "".join(squeezed)
+
+
+def resolve(spoken: str, candidates: list[str]) -> str | None:
+ """Best-matching call-sign for ``spoken``, or ``None`` below the floor.
+
+ ``spoken`` may be a whole utterance ("what is mika up to?") — every word is
+ tried, longest first, so a name embedded in a sentence is found without the
+ caller having to pre-extract it.
+ """
+ if not spoken or not candidates:
+ return None
+
+ keys = {normalize(c): c for c in candidates}
+
+ # Exact hit on the full string first (the API path case: /terminals/mika).
+ full = normalize(spoken)
+ if full in keys:
+ return keys[full]
+
+ words = [w for w in (normalize(w) for w in spoken.split()) if w]
+ best: tuple[float, str] | None = None
+ for word in words:
+ if word in keys:
+ return keys[word]
+ folded = phonetic_key(word)
+ for key, original in keys.items():
+ if folded and folded == phonetic_key(key):
+ return original
+ # Score the raw spelling AND the folded one; the better of the two
+ # decides, so an odd transcript has two chances to be recognised.
+ score = max(
+ SequenceMatcher(None, word, key).ratio(),
+ SequenceMatcher(None, folded, phonetic_key(key)).ratio(),
+ )
+ if score >= _MATCH_FLOOR and (best is None or score > best[0]):
+ best = (score, original)
+ return best[1] if best else None
+
+
+__all__ = ["NAME_POOL", "default_names", "normalize", "phonetic_key", "resolve"]
diff --git a/jarvis/agentic_ide/screen.py b/jarvis/agentic_ide/screen.py
new file mode 100644
index 0000000000..6fceccbd98
--- /dev/null
+++ b/jarvis/agentic_ide/screen.py
@@ -0,0 +1,366 @@
+"""A minimal terminal screen emulator — enough of VT100/ANSI to read a TUI.
+
+Why this exists: a PTY does not carry lines of text, it carries drawing
+commands. Claude Code and Codex paint full-screen interfaces by moving the
+cursor to absolute positions, erasing regions, and repainting rows in place.
+Stripping the escape sequences out of that stream and keeping the leftovers
+produces text in an order no human ever read — measured on a real Claude Code
+startup: 872 characters of output collapsed into a single line.
+
+So instead of filtering the stream, this replays it onto a grid, the way the
+terminal itself would, and then the visible rows are simply read off. That is
+what makes "what is Mika doing?" answerable: the model sees what the user sees.
+
+Scope is deliberately narrow — the sequences TUIs actually use for layout:
+
+* printable text with line wrapping,
+* CR / LF / BS / TAB,
+* cursor positioning (CUP, HVP) and relative moves (CUU, CUD, CUF, CUB, CHA),
+* erase in line (EL) and erase in display (ED),
+* index / reverse index (IND, RI, NEL) and scroll up / down (SU, SD),
+* a scroll region (DECSTBM), because status bars depend on it.
+
+Everything else — colours (SGR), cursor visibility, bracketed paste, mouse
+reporting, alternate screen switches — is parsed and ignored, which is correct:
+it changes appearance, not content. Unknown sequences are skipped rather than
+printed, so a future escape code cannot leak garbage into the transcript.
+
+Not a goal: a conformant emulator. There is no support for double-width glyphs,
+character sets, or wide-character alignment. A row is a list of single-cell
+strings; a CJK glyph occupies one cell instead of two, which can shift a box
+border by a column. For reading what an agent is doing that is irrelevant, and
+it keeps the module dependency-free — the base install stays universal.
+"""
+from __future__ import annotations
+
+from collections import deque
+
+# Bounds that keep a runaway resize or a hostile escape sequence from
+# allocating an unreasonable grid.
+MIN_COLS, MAX_COLS = 20, 500
+MIN_ROWS, MAX_ROWS = 5, 200
+
+_SPACE = " "
+
+
+def _clamp(value: int, low: int, high: int) -> int:
+ return low if value < low else high if value > high else value
+
+
+class ScreenBuffer:
+ """A character grid plus a cursor, driven by a PTY byte stream."""
+
+ __slots__ = (
+ "cols",
+ "rows",
+ "_grid",
+ "_cursor_row",
+ "_cursor_col",
+ "_scrollback",
+ "_pending",
+ "_scroll_top",
+ "_scroll_bottom",
+ "_wrap_pending",
+ )
+
+ def __init__(self, cols: int = 100, rows: int = 30, scrollback: int = 800) -> None:
+ self.cols = _clamp(cols, MIN_COLS, MAX_COLS)
+ self.rows = _clamp(rows, MIN_ROWS, MAX_ROWS)
+ self._grid: list[list[str]] = [self._blank_row() for _ in range(self.rows)]
+ self._cursor_row = 0
+ self._cursor_col = 0
+ self._scrollback: deque[str] = deque(maxlen=scrollback)
+ # Bytes of an escape sequence split across two PTY reads.
+ self._pending = ""
+ self._scroll_top = 0
+ self._scroll_bottom = self.rows - 1
+ self._wrap_pending = False
+
+ # ------------------------------------------------------------------ grid
+ def _blank_row(self) -> list[str]:
+ return [_SPACE] * self.cols
+
+ def resize(self, cols: int, rows: int) -> None:
+ """Resize the grid, keeping the top-left content (the usual TUI reflow)."""
+ cols = _clamp(cols, MIN_COLS, MAX_COLS)
+ rows = _clamp(rows, MIN_ROWS, MAX_ROWS)
+ if cols == self.cols and rows == self.rows:
+ return
+ old = self._grid
+ self.cols, self.rows = cols, rows
+ self._grid = [self._blank_row() for _ in range(rows)]
+ for r in range(min(rows, len(old))):
+ row = old[r]
+ for c in range(min(cols, len(row))):
+ self._grid[r][c] = row[c]
+ self._cursor_row = min(self._cursor_row, rows - 1)
+ self._cursor_col = min(self._cursor_col, cols - 1)
+ self._scroll_top = 0
+ self._scroll_bottom = rows - 1
+
+ def _scroll_up(self, count: int = 1) -> None:
+ """Push rows off the top of the scroll region into the scrollback."""
+ for _ in range(max(1, count)):
+ leaving = self._grid.pop(self._scroll_top)
+ # Only the true top of the screen is history; a scroll region below
+ # it (a status bar) is transient decoration.
+ if self._scroll_top == 0:
+ self._scrollback.append("".join(leaving).rstrip())
+ self._grid.insert(self._scroll_bottom, self._blank_row())
+
+ def _scroll_down(self, count: int = 1) -> None:
+ for _ in range(max(1, count)):
+ self._grid.pop(self._scroll_bottom)
+ self._grid.insert(self._scroll_top, self._blank_row())
+
+ def _newline(self) -> None:
+ if self._cursor_row >= self._scroll_bottom:
+ self._scroll_up()
+ self._cursor_row = self._scroll_bottom
+ else:
+ self._cursor_row += 1
+
+ def _put(self, ch: str) -> None:
+ if self._wrap_pending:
+ self._cursor_col = 0
+ self._newline()
+ self._wrap_pending = False
+ if self._cursor_col >= self.cols:
+ self._cursor_col = 0
+ self._newline()
+ self._grid[self._cursor_row][self._cursor_col] = ch
+ if self._cursor_col + 1 >= self.cols:
+ # Defer the wrap: a character in the last column does not move to
+ # the next row until one more character arrives (VT behaviour, and
+ # it stops full-width box borders from inserting blank rows).
+ self._wrap_pending = True
+ else:
+ self._cursor_col += 1
+
+ # ------------------------------------------------------------------ feed
+ def feed(self, chunk: str) -> None:
+ """Replay a raw PTY chunk onto the grid."""
+ if not chunk:
+ return
+ data = self._pending + chunk
+ self._pending = ""
+ i, n = 0, len(data)
+ while i < n:
+ ch = data[i]
+ if ch == "\x1b":
+ consumed = self._handle_escape(data, i)
+ if consumed == 0:
+ # Sequence is cut off at the chunk boundary — keep the tail
+ # and finish it when the next read arrives.
+ self._pending = data[i:]
+ return
+ i += consumed
+ continue
+ i += 1
+ if ch == "\n":
+ self._wrap_pending = False
+ self._newline()
+ elif ch == "\r":
+ self._wrap_pending = False
+ self._cursor_col = 0
+ elif ch == "\b":
+ self._wrap_pending = False
+ self._cursor_col = max(0, self._cursor_col - 1)
+ elif ch == "\t":
+ self._wrap_pending = False
+ self._cursor_col = min(self.cols - 1, (self._cursor_col // 8 + 1) * 8)
+ elif ch == "\x07":
+ continue # bell
+ elif ch < " " or ch == "\x7f":
+ continue # other C0 controls carry no content
+ else:
+ self._put(ch)
+
+ def _handle_escape(self, data: str, start: int) -> int:
+ """Consume one escape sequence. Returns its length, or 0 if incomplete."""
+ n = len(data)
+ if start + 1 >= n:
+ return 0
+ kind = data[start + 1]
+
+ if kind == "[":
+ return self._handle_csi(data, start)
+ if kind == "]":
+ # OSC: ends at BEL or ST (ESC \). Title changes, hyperlinks.
+ j = start + 2
+ while j < n:
+ if data[j] == "\x07":
+ return j - start + 1
+ if data[j] == "\x1b" and j + 1 < n and data[j + 1] == "\\":
+ return j - start + 2
+ if data[j] == "\x1b":
+ return 0 if j + 1 >= n else j - start + 1
+ j += 1
+ return 0
+ if kind in "()#%":
+ # Character-set selection: two bytes of payload, ignored.
+ return 3 if start + 2 < n else 0
+ if kind == "D": # IND — index (down one row)
+ self._newline()
+ return 2
+ if kind == "M": # RI — reverse index (up one row)
+ if self._cursor_row <= self._scroll_top:
+ self._scroll_down()
+ else:
+ self._cursor_row -= 1
+ return 2
+ if kind == "E": # NEL — next line
+ self._cursor_col = 0
+ self._newline()
+ return 2
+ if kind == "c": # RIS — full reset
+ self.reset()
+ return 2
+ # Anything else (7/8 save-restore cursor, =/>, ...) — skip the two bytes.
+ return 2
+
+ def _handle_csi(self, data: str, start: int) -> int:
+ n = len(data)
+ j = start + 2
+ params_start = j
+ # Parameter bytes 0x30-0x3F, then intermediates 0x20-0x2F, then final.
+ while j < n and "\x30" <= data[j] <= "\x3f":
+ j += 1
+ while j < n and "\x20" <= data[j] <= "\x2f":
+ j += 1
+ if j >= n:
+ return 0 # incomplete — wait for more input
+ final = data[j]
+ raw = data[params_start:j]
+ length = j - start + 1
+
+ private = raw.startswith("?")
+ if private:
+ # DEC private modes: cursor visibility, alternate screen, mouse
+ # reporting, bracketed paste. None of them change content.
+ return length
+
+ params = [int(p) if p.isdigit() else 0 for p in raw.split(";")] if raw else []
+
+ def p(index: int, default: int = 1) -> int:
+ if index < len(params) and params[index] > 0:
+ return params[index]
+ return default
+
+ self._wrap_pending = False
+
+ if final in "Hf": # CUP / HVP — absolute position
+ self._cursor_row = _clamp(p(0) - 1, 0, self.rows - 1)
+ self._cursor_col = _clamp(p(1) - 1, 0, self.cols - 1)
+ elif final == "A": # CUU
+ self._cursor_row = max(0, self._cursor_row - p(0))
+ elif final == "B": # CUD
+ self._cursor_row = min(self.rows - 1, self._cursor_row + p(0))
+ elif final == "C": # CUF
+ self._cursor_col = min(self.cols - 1, self._cursor_col + p(0))
+ elif final == "D": # CUB
+ self._cursor_col = max(0, self._cursor_col - p(0))
+ elif final == "G": # CHA — absolute column
+ self._cursor_col = _clamp(p(0) - 1, 0, self.cols - 1)
+ elif final == "d": # VPA — absolute row
+ self._cursor_row = _clamp(p(0) - 1, 0, self.rows - 1)
+ elif final == "E": # CNL
+ self._cursor_col = 0
+ self._cursor_row = min(self.rows - 1, self._cursor_row + p(0))
+ elif final == "F": # CPL
+ self._cursor_col = 0
+ self._cursor_row = max(0, self._cursor_row - p(0))
+ elif final == "K": # EL — erase in line
+ mode = params[0] if params else 0
+ row = self._grid[self._cursor_row]
+ if mode == 0:
+ for c in range(self._cursor_col, self.cols):
+ row[c] = _SPACE
+ elif mode == 1:
+ for c in range(0, min(self._cursor_col + 1, self.cols)):
+ row[c] = _SPACE
+ else:
+ self._grid[self._cursor_row] = self._blank_row()
+ elif final == "J": # ED — erase in display
+ mode = params[0] if params else 0
+ if mode == 0:
+ for c in range(self._cursor_col, self.cols):
+ self._grid[self._cursor_row][c] = _SPACE
+ for r in range(self._cursor_row + 1, self.rows):
+ self._grid[r] = self._blank_row()
+ elif mode == 1:
+ for c in range(0, min(self._cursor_col + 1, self.cols)):
+ self._grid[self._cursor_row][c] = _SPACE
+ for r in range(0, self._cursor_row):
+ self._grid[r] = self._blank_row()
+ else:
+ # Clearing the whole screen: the rows that held content are
+ # history, otherwise a repainting TUI would erase its own past.
+ for row in self._grid:
+ text = "".join(row).rstrip()
+ if text:
+ self._scrollback.append(text)
+ self._grid = [self._blank_row() for _ in range(self.rows)]
+ if mode == 2:
+ self._cursor_row = self._cursor_col = 0
+ elif final == "L": # IL — insert lines
+ for _ in range(p(0)):
+ self._grid.pop(self._scroll_bottom)
+ self._grid.insert(self._cursor_row, self._blank_row())
+ elif final == "M": # DL — delete lines
+ for _ in range(p(0)):
+ self._grid.pop(self._cursor_row)
+ self._grid.insert(self._scroll_bottom, self._blank_row())
+ elif final == "P": # DCH — delete characters
+ row = self._grid[self._cursor_row]
+ for _ in range(p(0)):
+ if self._cursor_col < self.cols:
+ del row[self._cursor_col]
+ row.append(_SPACE)
+ elif final == "@": # ICH — insert characters
+ row = self._grid[self._cursor_row]
+ for _ in range(p(0)):
+ row.insert(self._cursor_col, _SPACE)
+ row.pop()
+ elif final == "X": # ECH — erase characters
+ row = self._grid[self._cursor_row]
+ for c in range(self._cursor_col, min(self._cursor_col + p(0), self.cols)):
+ row[c] = _SPACE
+ elif final == "S": # SU — scroll up
+ self._scroll_up(p(0))
+ elif final == "T": # SD — scroll down
+ self._scroll_down(p(0))
+ elif final == "r": # DECSTBM — scroll region
+ top = _clamp(p(0) - 1, 0, self.rows - 1)
+ bottom = _clamp(p(1, self.rows) - 1, 0, self.rows - 1)
+ if top < bottom:
+ self._scroll_top, self._scroll_bottom = top, bottom
+ else:
+ self._scroll_top, self._scroll_bottom = 0, self.rows - 1
+ self._cursor_row, self._cursor_col = self._scroll_top, 0
+ # SGR ("m") and everything else: appearance only.
+ return length
+
+ # ---------------------------------------------------------------- output
+ def display(self) -> list[str]:
+ """Visible rows, trailing blanks removed."""
+ rows = ["".join(row).rstrip() for row in self._grid]
+ while rows and not rows[-1]:
+ rows.pop()
+ return rows
+
+ def history(self) -> list[str]:
+ """Rows that have scrolled off the top, oldest first."""
+ return list(self._scrollback)
+
+ def reset(self) -> None:
+ self._grid = [self._blank_row() for _ in range(self.rows)]
+ self._cursor_row = self._cursor_col = 0
+ self._scrollback.clear()
+ self._pending = ""
+ self._scroll_top = 0
+ self._scroll_bottom = self.rows - 1
+ self._wrap_pending = False
+
+
+__all__ = ["ScreenBuffer"]
diff --git a/jarvis/agentic_ide/session.py b/jarvis/agentic_ide/session.py
new file mode 100644
index 0000000000..dbac6b34ef
--- /dev/null
+++ b/jarvis/agentic_ide/session.py
@@ -0,0 +1,548 @@
+"""In-process state of the Agentic-IDE workspace.
+
+One registry holds at most one *session*: a chosen folder plus N named
+terminals, each running a coding-agent CLI (Claude Code / Codex) in a real
+pseudo-terminal rooted in that folder. The registry is what makes the feature
+more than an embedded terminal grid — it is the thing Jarvis reads from and
+writes to:
+
+* **reads** — every terminal keeps a sanitized transcript, so "what is Mika
+ doing?" is answered from what Mika actually printed, not from a guess,
+* **writes** — a prompt can be injected into a terminal from the outside
+ (voice, chat, CLI), which is how you talk to an agent without touching the
+ keyboard.
+
+Security posture of the write path (this is a keystroke channel into a running
+process, so it is bounded deliberately):
+
+1. The PTY runs the AGENT, never a persistent shell. When the agent exits the
+ PTY dies with it, the terminal flips to ``exited``, and injection is refused
+ — so an injected prompt can never fall through into a live shell prompt and
+ be executed as a command.
+2. Injected text is stripped of every C0 control character. Voice can therefore
+ not send Ctrl-C, ESC, or EOF: it cannot kill the agent, break out of its TUI,
+ or drive its keyboard shortcuts — only type a prompt and press Enter.
+3. Length is capped, and Enter is sent as a separate write a beat later,
+ because agent TUIs treat an instant text+newline burst as a paste and insert
+ a literal line break instead of submitting.
+
+Platform notes: the PTY layer itself is already cross-platform behind
+``jarvis.terminal.backend`` (ConPTY on Windows, ptyprocess on POSIX, a clearly
+messaged no-op where no PTY exists). What this module adds per platform is
+resolving the agent binary: npm installs it as a ``.cmd``/``.ps1`` shim on
+Windows, which ConPTY cannot execute directly, so it is wrapped in a
+one-shot ``cmd /c`` (one-shot, so rule 1 above still holds).
+"""
+from __future__ import annotations
+
+import asyncio
+import os
+import shutil
+import sys
+import time
+from dataclasses import dataclass, field
+from pathlib import Path
+from typing import TYPE_CHECKING, Any
+from uuid import uuid4
+
+from loguru import logger
+
+from .folders import ProjectProfile, probe_project
+from .names import default_names, normalize, resolve
+from .transcript import Transcript
+
+if TYPE_CHECKING: # pragma: no cover - typing only
+ from jarvis.terminal.pty_manager import PtyManager
+
+# Agents the IDE can run. Kept parallel to jarvis.workspace.agents (same two
+# CLIs, same display names) but with argv built for a one-shot agent process
+# rather than a persistent shell.
+AGENT_BINARIES: dict[str, str] = {"claude": "claude", "codex": "codex"}
+AGENT_DISPLAY: dict[str, str] = {"claude": "Claude Code", "codex": "Codex"}
+
+MAX_TERMINALS = 12
+MAX_PROMPT_CHARS = 4000
+# Delay between the prompt text and the Enter keystroke. Agent TUIs debounce
+# fast bursts as a paste; ~120 ms is past every debounce window measured while
+# still feeling instant.
+ENTER_DELAY_S = 0.12
+
+Status = str # "pending" | "live" | "exited" | "error"
+
+
+def sanitize_prompt(text: str) -> str:
+ """Injectable form of ``text``: printable characters only, length-capped.
+
+ Escape sequences are removed whole (so ``ESC [ A`` does not leave a stray
+ ``[A`` in the prompt), then newlines and tabs collapse to spaces and every
+ remaining C0 control is dropped — the caller cannot smuggle Ctrl-C, ESC, or
+ EOF into a running agent.
+ """
+ from .transcript import strip_ansi
+
+ cleaned = "".join(
+ " " if ch in "\r\n\t" else ch
+ for ch in strip_ansi(text)
+ if ch >= " " or ch in "\r\n\t"
+ )
+ return " ".join(cleaned.split())[:MAX_PROMPT_CHARS]
+
+
+def agent_argv(agent: str) -> tuple[str, ...] | None:
+ """argv that runs ``agent`` as the PTY's own process, or None if missing."""
+ binary = AGENT_BINARIES.get(agent)
+ if binary is None:
+ return None
+ try:
+ from jarvis.core.path_augment import ensure_cli_paths
+
+ ensure_cli_paths()
+ except Exception: # noqa: BLE001, S110 - PATH augmentation is best-effort
+ pass
+ exe = shutil.which(binary)
+ if exe is None:
+ return None
+ if sys.platform == "win32":
+ lowered = exe.lower()
+ if lowered.endswith((".cmd", ".bat")):
+ # ConPTY cannot exec a batch shim. `cmd /c` (never /k) exits with
+ # the agent, so no shell survives it.
+ comspec = os.environ.get("COMSPEC") or "cmd.exe"
+ return (comspec, "/c", exe)
+ if lowered.endswith(".ps1"):
+ shell = shutil.which("pwsh") or shutil.which("powershell")
+ if shell is None:
+ return None
+ return (shell, "-NoLogo", "-NoProfile", "-File", exe)
+ return (exe,)
+
+
+@dataclass(slots=True)
+class Terminal:
+ """One named pane: a call-sign, an agent, and its live PTY (if attached)."""
+
+ key: str # url-safe key, e.g. "mika"
+ name: str # spoken call-sign, e.g. "Mika"
+ agent: str # "claude" | "codex"
+ display_name: str # "Claude Code"
+ index: int
+ status: Status = "pending"
+ pty_id: str | None = None
+ exit_code: int | None = None
+ error: str = ""
+ started_at: float | None = None
+ last_output_at: float | None = None
+ prompts_sent: int = 0
+ last_prompt: str = ""
+ transcript: Transcript = field(default_factory=Transcript)
+
+ def to_dict(self) -> dict[str, Any]:
+ return {
+ "key": self.key,
+ "name": self.name,
+ "agent": self.agent,
+ "display_name": self.display_name,
+ "index": self.index,
+ "status": self.status,
+ "exit_code": self.exit_code,
+ "error": self.error,
+ "started_at": self.started_at,
+ "last_output_at": self.last_output_at,
+ "idle_seconds": (
+ None if self.last_output_at is None else round(time.time() - self.last_output_at, 1)
+ ),
+ "prompts_sent": self.prompts_sent,
+ "last_prompt": self.last_prompt,
+ "lines_captured": len(self.transcript.lines()),
+ }
+
+
+@dataclass(slots=True)
+class Session:
+ """A chosen folder plus its named terminals."""
+
+ id: str
+ folder: str
+ profile: ProjectProfile
+ terminals: list[Terminal]
+ created_at: float
+ # Focus mode: while on, Jarvis answers inside this workspace's context. The
+ # flag lives here (not in jarvis.toml) on purpose — it is a mode of the
+ # current session, and a restart should land the user back in normal mode
+ # rather than silently keeping a narrowed assistant.
+ focus_mode: bool = False
+
+ def find(self, wanted: str) -> Terminal | None:
+ """Terminal by key, call-sign, or a spoken phrase containing one."""
+ if not wanted:
+ return None
+ key = normalize(wanted)
+ for term in self.terminals:
+ if normalize(term.key) == key or normalize(term.name) == key:
+ return term
+ matched = resolve(wanted, [t.name for t in self.terminals])
+ if matched is None:
+ return None
+ return next((t for t in self.terminals if t.name == matched), None)
+
+ def to_dict(self) -> dict[str, Any]:
+ return {
+ "id": self.id,
+ "folder": self.folder,
+ "project": self.profile.to_dict(),
+ "created_at": self.created_at,
+ "focus_mode": self.focus_mode,
+ "terminals": [t.to_dict() for t in self.terminals],
+ }
+
+
+class SessionError(RuntimeError):
+ """A request the registry refuses, with a user-facing English message."""
+
+
+class Registry:
+ """Process-wide holder of the single active Agentic-IDE session."""
+
+ def __init__(self, pty_manager: PtyManager | None = None) -> None:
+ self._session: Session | None = None
+ # Injectable so tests can drive the registry against a fake PTY pool
+ # without a real pseudo-terminal (and without a coding agent installed).
+ self._pty: PtyManager | None = pty_manager
+ self._lock = asyncio.Lock()
+
+ # ---------------------------------------------------------------- state
+ @property
+ def session(self) -> Session | None:
+ return self._session
+
+ def state(self) -> dict[str, Any]:
+ return {
+ "active": self._session is not None,
+ "session": self._session.to_dict() if self._session else None,
+ "max_terminals": MAX_TERMINALS,
+ }
+
+ def _manager(self) -> PtyManager:
+ if self._pty is None:
+ # Lazy: keeps the terminal stack off the import/boot path (AP-26).
+ from jarvis.terminal.pty_manager import PtyManager
+
+ self._pty = PtyManager()
+ return self._pty
+
+ # -------------------------------------------------------------- session
+ async def start(
+ self, folder: str, requested: list[dict[str, Any]]
+ ) -> Session:
+ """Create a session for ``folder`` with one terminal per request entry.
+
+ ``requested`` entries look like ``{"agent": "claude", "name": "Mika"}``;
+ the name is optional and filled from the call-sign pool.
+ """
+ async with self._lock:
+ if not requested:
+ raise SessionError("Pick at least one terminal.")
+ if len(requested) > MAX_TERMINALS:
+ raise SessionError(
+ f"At most {MAX_TERMINALS} terminals per session (got {len(requested)})."
+ )
+
+ # expanduser() is string/env work, not a filesystem call — the real
+ # stat below runs in a worker thread.
+ root = Path(folder).expanduser() # noqa: ASYNC240
+ try:
+ # Off the event loop: on a network share or a spun-down drive a
+ # stat can block for seconds, which would stall every other
+ # request the server is serving.
+ if not await asyncio.to_thread(root.is_dir):
+ raise SessionError(f"Not a folder: {root}")
+ except OSError as exc:
+ raise SessionError(f"Cannot open {root}: {exc}") from exc
+
+ unknown = {str(r.get("agent")) for r in requested} - set(AGENT_BINARIES)
+ if unknown:
+ raise SessionError(f"Unknown agent(s): {', '.join(sorted(unknown))}")
+
+ missing = sorted(
+ {
+ str(r.get("agent"))
+ for r in requested
+ if agent_argv(str(r.get("agent"))) is None
+ }
+ )
+ if missing:
+ pretty = ", ".join(AGENT_DISPLAY.get(m, m) for m in missing)
+ raise SessionError(
+ f"{pretty} is not installed or not on this machine's PATH. "
+ "Install it from the CLIs page, then try again."
+ )
+
+ # Close a previous session before replacing it, or its PTYs leak.
+ await self._close_locked()
+
+ pool = default_names(len(requested))
+ used: set[str] = set()
+ terminals: list[Terminal] = []
+ for index, entry in enumerate(requested):
+ agent = str(entry.get("agent"))
+ wanted = str(entry.get("name") or "").strip() or pool[index]
+ name = wanted
+ suffix = 2
+ while normalize(name) in used:
+ name = f"{wanted} {suffix}"
+ suffix += 1
+ used.add(normalize(name))
+ terminals.append(
+ Terminal(
+ key=normalize(name) or f"t{index}",
+ name=name,
+ agent=agent,
+ display_name=AGENT_DISPLAY.get(agent, agent),
+ index=index,
+ )
+ )
+
+ profile = await asyncio.to_thread(probe_project, root)
+
+ # Pre-seed agent trust for this folder so no terminal stops on a
+ # "do you trust this directory?" dialog the user cannot see coming.
+ try:
+ from jarvis.workspace.trust import ensure_trusted
+
+ await asyncio.to_thread(
+ ensure_trusted, root, sorted({t.agent for t in terminals})
+ )
+ except Exception as exc: # noqa: BLE001 - trust is a convenience
+ logger.warning("Agentic IDE: pre-trust failed: {}", exc)
+
+ session = Session(
+ id=f"ide_{uuid4().hex[:12]}",
+ folder=str(root),
+ profile=profile,
+ terminals=terminals,
+ created_at=time.time(),
+ )
+ self._session = session
+ logger.info(
+ "Agentic IDE session started: {} terminals in {}",
+ len(terminals),
+ root,
+ )
+ return session
+
+ async def end(self) -> bool:
+ async with self._lock:
+ existed = self._session is not None
+ await self._close_locked()
+ return existed
+
+ async def _close_locked(self) -> None:
+ session = self._session
+ self._session = None
+ if session is None:
+ return
+ manager = self._pty
+ if manager is not None:
+ for term in session.terminals:
+ if term.pty_id:
+ try:
+ manager.close(term.pty_id)
+ 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:
+ """Turn the focused coding mode on/off. Returns the resulting state."""
+ session = self._session
+ if session is None:
+ if enabled:
+ raise SessionError(
+ "No Agentic-IDE session is running — open one first."
+ )
+ return False
+ session.focus_mode = bool(enabled)
+ logger.info("Agentic IDE focus mode {}", "on" if enabled else "off")
+ return session.focus_mode
+
+ # ------------------------------------------------------------------ pty
+ async def attach(
+ self, key: str, cols: int, rows: int, on_output: Any, on_exit: Any
+ ) -> Terminal:
+ """Spawn the agent for terminal ``key`` and stream it to the caller.
+
+ ``on_output(text)`` / ``on_exit(code)`` are awaited in this loop. The
+ transcript is fed here, so it keeps filling even if the UI pane is
+ closed and reconnects later.
+ """
+ session = self._session
+ if session is None:
+ raise SessionError("No Agentic-IDE session is running.")
+ term = session.find(key)
+ if term is None:
+ raise SessionError(f"Unknown terminal: {key}")
+
+ manager = self._manager()
+ if term.pty_id and manager.has(term.pty_id):
+ # A second viewer for a pane that is already running: close the old
+ # PTY rather than silently running two agents for one call-sign.
+ manager.close(term.pty_id)
+ term.pty_id = None
+
+ argv = agent_argv(term.agent)
+ if argv is None:
+ term.status = "error"
+ term.error = f"{term.display_name} is not on PATH."
+ raise SessionError(term.error)
+
+ term.transcript.resize(cols, rows)
+
+ async def _output(_tid: str, text: str) -> None:
+ term.transcript.feed(text)
+ term.last_output_at = time.time()
+ await on_output(text)
+
+ async def _closed(_tid: str, code: int) -> None:
+ term.status = "exited"
+ term.exit_code = code
+ term.pty_id = None
+ await on_exit(code)
+
+ try:
+ pty_session = await manager.spawn(
+ shell_argv=argv,
+ shell_id=f"agentic-ide:{term.key}",
+ cwd=session.folder,
+ cols=cols,
+ rows=rows,
+ on_output=_output,
+ on_closed=_closed,
+ )
+ except Exception as exc: # noqa: BLE001 - surfaced to the pane
+ term.status = "error"
+ term.error = str(exc)
+ raise SessionError(str(exc)) from exc
+
+ term.pty_id = pty_session.terminal_id
+ term.status = "live"
+ term.error = ""
+ term.exit_code = None
+ term.started_at = time.time()
+ term.last_output_at = time.time()
+ return term
+
+ def write(self, key: str, data: str) -> bool:
+ """Raw keystrokes from the pane's own xterm (not the injection path)."""
+ session = self._session
+ if session is None:
+ return False
+ term = session.find(key)
+ if term is None or not term.pty_id:
+ return False
+ return self._manager().write(term.pty_id, data)
+
+ def resize(self, key: str, cols: int, rows: int) -> bool:
+ session = self._session
+ if session is None:
+ return False
+ term = session.find(key)
+ if term is None or not term.pty_id:
+ return False
+ # The replayed screen has to follow the real one; otherwise the
+ # transcript keeps wrapping at the old width.
+ term.transcript.resize(cols, rows)
+ return self._manager().resize(term.pty_id, cols, rows)
+
+ def detach(self, key: str) -> None:
+ """Close the PTY behind a pane (the viewer went away)."""
+ session = self._session
+ if session is None:
+ return
+ term = session.find(key)
+ if term is None or not term.pty_id:
+ return
+ self._manager().close(term.pty_id)
+ term.pty_id = None
+ if term.status == "live":
+ term.status = "exited"
+
+ # --------------------------------------------------------------- prompt
+ async def send_prompt(self, wanted: str, text: str) -> Terminal:
+ """Type ``text`` into a terminal and press Enter.
+
+ Raises ``SessionError`` when the terminal is unknown, not running, or
+ the prompt sanitizes down to nothing.
+ """
+ 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.status != "live" or not term.pty_id:
+ raise SessionError(
+ f"{term.name} is not running right now "
+ f"(status: {term.status}) — nothing was sent."
+ )
+ payload = sanitize_prompt(text)
+ if not payload:
+ raise SessionError("The prompt was empty after cleanup.")
+
+ manager = self._manager()
+ if not manager.write(term.pty_id, payload):
+ raise SessionError(f"Could not write to {term.name}.")
+ await asyncio.sleep(ENTER_DELAY_S)
+ manager.write(term.pty_id, "\r")
+
+ term.prompts_sent += 1
+ term.last_prompt = payload
+ logger.info("Agentic IDE prompt -> {}: {}", term.name, payload[:120])
+ return term
+
+ def report(self, wanted: str, lines: int = 40) -> dict[str, Any]:
+ """What one terminal has been up to — the answer to "what is X doing?"."""
+ 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}.")
+ data = term.to_dict()
+ data["folder"] = session.folder
+ data["transcript"] = term.transcript.tail(max(1, min(lines, 300)))
+ return data
+
+
+_REGISTRY: Registry | None = None
+
+
+def get_registry() -> Registry:
+ """The process-wide Agentic-IDE registry (created on first use)."""
+ global _REGISTRY
+ if _REGISTRY is None:
+ _REGISTRY = Registry()
+ return _REGISTRY
+
+
+def reset_registry() -> None:
+ """Drop the registry — tests only."""
+ global _REGISTRY
+ _REGISTRY = None
+
+
+__all__ = [
+ "AGENT_BINARIES",
+ "AGENT_DISPLAY",
+ "ENTER_DELAY_S",
+ "MAX_PROMPT_CHARS",
+ "MAX_TERMINALS",
+ "Registry",
+ "Session",
+ "SessionError",
+ "Terminal",
+ "agent_argv",
+ "get_registry",
+ "reset_registry",
+ "sanitize_prompt",
+]
diff --git a/jarvis/agentic_ide/transcript.py b/jarvis/agentic_ide/transcript.py
new file mode 100644
index 0000000000..7621b91be9
--- /dev/null
+++ b/jarvis/agentic_ide/transcript.py
@@ -0,0 +1,127 @@
+"""Readable transcript of what a coding agent is doing in its terminal.
+
+The problem: a PTY carries a *terminal protocol*, not a log. Claude Code and
+Codex are full-screen TUIs — they position the cursor absolutely, erase regions,
+and repaint rows in place. Handing that stream to a language model verbatim
+wastes context on control codes, and merely filtering the escape sequences out
+is worse than useless: the leftovers arrive in an order nobody read. Measured on
+a real Claude Code startup, 872 characters of output reduced to one usable line.
+
+So a terminal screen is replayed instead (:mod:`.screen`), and the transcript is
+read off it in two parts:
+
+* **history** — rows that scrolled off the top, i.e. what already happened,
+* **display** — the rows currently on screen, i.e. what is happening now.
+
+On top of that sits one light editorial pass for the benefit of a model reading
+it: blank and decoration-only rows are dropped, and consecutive identical rows
+are folded (a repainted spinner row is one event, not two hundred).
+
+Honest limits: no double-width glyph handling, so a CJK character can shift a
+box border by a column; and a two-column TUI layout still reads left-to-right
+per row, exactly as it looks on screen. Both are irrelevant for answering "what
+is this agent working on?", and both keep the module dependency-free.
+"""
+from __future__ import annotations
+
+import re
+from dataclasses import dataclass, field
+
+from .screen import ScreenBuffer
+
+# Kept for callers that want plain text out of a coloured string (the prompt
+# sanitizer uses it). Screen replay does NOT go through this.
+_CSI_RE = re.compile(r"\x1b\[[0-?]*[ -/]*[@-~]")
+_OSC_RE = re.compile(r"\x1b\][^\x07\x1b]*(?:\x07|\x1b\\)")
+_ESC_RE = re.compile(r"\x1b[@-Z\\-_]")
+_MISC_RE = re.compile(r"\x1b[<>=]")
+
+# A row made only of these draws a frame or an animation; it carries no
+# information for a model summarizing the session.
+_DECORATION_CHARS = set("─│┌┐└┘├┤┬┴┼━┃╭╮╯╰═║╔╗╚╝╠╣╦╩╬▀▄█▌▐░▒▓▔▁·.-_=*#~ ")
+_SPINNER_CHARS = set("|/\\-◐◓◑◒✻✽✢·✳✶⣿")
+
+
+def strip_ansi(text: str) -> str:
+ """Remove terminal escape sequences, leaving printable text."""
+ text = _OSC_RE.sub("", text)
+ text = _CSI_RE.sub("", text)
+ text = _MISC_RE.sub("", text)
+ text = _ESC_RE.sub("", text)
+ return "".join(ch for ch in text if ch >= " " or ch in "\t\n\r")
+
+
+def _is_decorative(ch: str) -> bool:
+ """True for a glyph that only ever draws a frame or an animation.
+
+ Braille patterns (U+2800..U+28FF) get a range check rather than a character
+ list: every modern CLI spinner cycles through dozens of them, and listing
+ the ones a given agent uses today would go stale when it changes its
+ spinner.
+ """
+ if ch in _DECORATION_CHARS or ch in _SPINNER_CHARS:
+ return True
+ return 0x2800 <= ord(ch) <= 0x28FF
+
+
+def is_noise(line: str) -> bool:
+ """True for a line that carries no information worth keeping."""
+ stripped = line.strip()
+ if not stripped:
+ return True
+ return all(_is_decorative(ch) for ch in stripped)
+
+
+@dataclass(slots=True)
+class Transcript:
+ """Readable view of one terminal, backed by a replayed screen."""
+
+ cols: int = 100
+ rows: int = 30
+ max_lines: int = 600
+ # Characters of raw PTY output seen — a cheap "is this agent doing
+ # anything?" signal that survives every row being filtered as noise.
+ raw_chars: int = 0
+ screen: ScreenBuffer = field(init=False)
+
+ def __post_init__(self) -> None:
+ self.screen = ScreenBuffer(self.cols, self.rows, scrollback=self.max_lines)
+
+ # ------------------------------------------------------------------ input
+ def feed(self, chunk: str) -> None:
+ """Replay a raw PTY chunk (escape sequences and all)."""
+ if not chunk:
+ return
+ self.raw_chars += len(chunk)
+ self.screen.feed(chunk)
+
+ def resize(self, cols: int, rows: int) -> None:
+ """Follow the pane's size so the replayed screen matches the real one."""
+ self.cols, self.rows = cols, rows
+ self.screen.resize(cols, rows)
+
+ # ----------------------------------------------------------------- output
+ def lines(self) -> list[str]:
+ """History plus the current screen, cleaned and de-duplicated."""
+ out: list[str] = []
+ for line in [*self.screen.history(), *self.screen.display()]:
+ text = line.rstrip()
+ if is_noise(text):
+ continue
+ if out and out[-1] == text:
+ continue # a repainted, unchanged row
+ out.append(text)
+ return out
+
+ def tail(self, count: int = 40) -> list[str]:
+ """Last ``count`` meaningful lines, oldest first."""
+ if count <= 0:
+ return []
+ return self.lines()[-count:]
+
+ def clear(self) -> None:
+ self.screen.reset()
+ self.raw_chars = 0
+
+
+__all__ = ["Transcript", "strip_ansi", "is_noise"]
diff --git a/jarvis/brain/manager.py b/jarvis/brain/manager.py
index 1b06c6100a..4575cd527d 100644
--- a/jarvis/brain/manager.py
+++ b/jarvis/brain/manager.py
@@ -3568,6 +3568,19 @@ class BrainManager:
if self._wiki_context_suffix and not self._cache_optimized():
parts.append(self._wiki_context_suffix)
+ # Agentic IDE: while the user has the focused coding mode ON, this turn
+ # is answered inside their open workspace — the folder, the codebase
+ # profile, and what each named terminal (Mika, Nova, …) last printed.
+ # Off / no session = empty string = no block, so this is inert for every
+ # user who never opens the IDE. In cache-optimized mode the block rides
+ # the per-turn user message instead (see _build_turn_context), because
+ # it changes as the agents print and would otherwise break the cached
+ # system prefix every turn.
+ if not self._cache_optimized():
+ agentic_block = self._agentic_focus_block()
+ if agentic_block:
+ parts.append(agentic_block)
+
# Active-model self-awareness: tell THIS turn's actually-answering
# provider/model who it is, so a "which model are you?" question gets an
# honest answer instead of a guessed "Gemini" (forensic 2026-06-20: Grok
@@ -3692,8 +3705,26 @@ class BrainManager:
pass
if self._wiki_context_suffix:
parts.append(self._wiki_context_suffix)
+ agentic_block = self._agentic_focus_block()
+ if agentic_block:
+ parts.append(agentic_block)
return "\n\n".join(p for p in parts if p)
+ def _agentic_focus_block(self) -> str:
+ """Workspace-awareness block while the Agentic IDE's focus mode is on.
+
+ Pure in-memory read (the session's cached project profile + each
+ terminal's ring buffer), so it stays off the latency budget the way
+ awareness does (AP-9). Any failure degrades to no block — a coding-mode
+ convenience must never be able to break a voice turn.
+ """
+ try:
+ from jarvis.agentic_ide.context import focus_context_block
+
+ return focus_context_block()
+ except Exception: # noqa: BLE001 - feature absent or mid-reload
+ return ""
+
# ------------------------------------------------------------------
# Explicit switching
# ------------------------------------------------------------------
diff --git a/jarvis/commands/registry.py b/jarvis/commands/registry.py
index a52cb5fc53..ea6840f137 100644
--- a/jarvis/commands/registry.py
+++ b/jarvis/commands/registry.py
@@ -600,6 +600,122 @@ def _build_registry() -> tuple[AppCommand, ...]:
"es": ("cancela la tarea",), # i18n-allow: input vocab
},
),
+ # ------------------------------------------------------- agentic IDE
+ # The Agentic IDE runs coding agents in named terminals; these three
+ # commands are what make the workspace addressable by voice. Reading is
+ # free (status / report); writing is one narrow channel — type a prompt
+ # into a named terminal — and it can only ever type text plus Enter (the
+ # endpoint strips control characters, so voice cannot interrupt or kill
+ # an agent). No entry here is worker_allowed: a mission worker has no
+ # business steering the user's interactive coding panes (AP-5).
+ AppCommand(
+ id="agentic-ide-status",
+ title="Agentic IDE status",
+ description=(
+ "Report the open Agentic-IDE workspace: which folder, which "
+ "coding agents run in which named terminals, and whether the "
+ "focused coding mode is on."
+ ),
+ method="GET",
+ path="/api/agentic-ide/state",
+ ui_section="agentic-ide",
+ voice_aliases={
+ "de": ("was läuft in der agentic ide",), # i18n-allow: input vocab
+ "en": ("what is running in the agentic ide",),
+ "es": ("qué se está ejecutando en el ide agéntico",), # i18n-allow: input vocab
+ },
+ ),
+ AppCommand(
+ id="agentic-ide-terminal-report",
+ title="Report on one Agentic-IDE terminal",
+ description=(
+ "Read what the coding agent in a named terminal is doing — its "
+ "status and its recent terminal output. Use this whenever the "
+ "user asks about a terminal by name (e.g. 'what is Mika doing?')."
+ ),
+ method="GET",
+ path="/api/agentic-ide/terminals/{name}/report",
+ params={
+ "type": "object",
+ "properties": {
+ "name": _str_param(
+ "Call-sign of the terminal, e.g. 'Mika'.", min_length=1
+ ),
+ "lines": {
+ "type": "integer",
+ "default": 40,
+ "description": "How many recent output lines to read.",
+ },
+ },
+ "required": ["name"],
+ },
+ path_params=("name",),
+ ui_section="agentic-ide",
+ voice_aliases={
+ "de": ("was macht mika",), # i18n-allow: input vocab
+ "en": ("what is mika doing",),
+ "es": ("qué está haciendo mika",), # i18n-allow: input vocab
+ },
+ ),
+ 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."
+ ),
+ method="POST",
+ path="/api/agentic-ide/terminals/{name}/prompt",
+ params={
+ "type": "object",
+ "properties": {
+ "name": _str_param(
+ "Call-sign of the terminal to prompt, e.g. 'Mika'.",
+ min_length=1,
+ ),
+ "prompt": _str_param(
+ "The instruction to type into that agent.",
+ min_length=1,
+ max_length=4000,
+ ),
+ },
+ "required": ["name", "prompt"],
+ },
+ path_params=("name",),
+ ui_section="agentic-ide",
+ voice_aliases={
+ "de": ("sag mika sie soll die tests laufen lassen",), # i18n-allow: input vocab
+ "en": ("tell mika to run the tests",),
+ "es": ("dile a mika que ejecute las pruebas",), # i18n-allow: input vocab
+ },
+ ),
+ AppCommand(
+ id="agentic-ide-focus",
+ title="Toggle Agentic-IDE focus mode",
+ description=(
+ "Turn the focused coding mode on or off. While on, answers are "
+ "given inside the open coding workspace; turning it off returns "
+ "to normal behaviour without stopping any agent."
+ ),
+ method="PUT",
+ path="/api/agentic-ide/mode",
+ params={
+ "type": "object",
+ "properties": {
+ "enabled": {
+ "type": "boolean",
+ "description": "True enters focused coding mode, False leaves it.",
+ },
+ },
+ "required": ["enabled"],
+ },
+ ui_section="agentic-ide",
+ voice_aliases={
+ "de": ("geh in den coding modus",), # i18n-allow: input vocab
+ "en": ("switch into coding mode",),
+ "es": ("entra en el modo de programación",), # i18n-allow: input vocab
+ },
+ ),
)
diff --git a/jarvis/plugins/tool/navigate.py b/jarvis/plugins/tool/navigate.py
index 70ea0adbea..336cb614c9 100644
--- a/jarvis/plugins/tool/navigate.py
+++ b/jarvis/plugins/tool/navigate.py
@@ -48,12 +48,24 @@ KNOWN: frozenset[str] = frozenset(
"feedback",
"agent-instructions",
"dictionary",
+ "agentic-ide",
}
)
# Natural-language aliases (DE + EN) → canonical id. The router usually passes an
# id from the schema enum; this is the safety net for spoken labels/synonyms.
_ALIASES: dict[str, str] = {
+ # Agentic IDE — the spoken forms people reach for. "agentic" is a mouthful
+ # in every supported language, so the plain-words variants matter more here
+ # than for sections whose label is already a common noun.
+ "agentic ide": "agentic-ide",
+ "agentic": "agentic-ide",
+ "ide": "agentic-ide",
+ "coding mode": "agentic-ide",
+ "coding workspace": "agentic-ide",
+ "codier-modus": "agentic-ide", # i18n-allow: input vocab
+ "programmier-modus": "agentic-ide", # i18n-allow: input vocab
+ "modo de programación": "agentic-ide", # i18n-allow: input vocab
"social": "socials",
"social media": "socials",
"soziale medien": "socials",
diff --git a/jarvis/ui/web/agentic_ide_routes.py b/jarvis/ui/web/agentic_ide_routes.py
new file mode 100644
index 0000000000..56e1462b77
--- /dev/null
+++ b/jarvis/ui/web/agentic_ide_routes.py
@@ -0,0 +1,318 @@
+"""REST + WebSocket API for the Agentic IDE.
+
+Every action of the feature is an endpoint (the CLI-first contract): the wizard,
+the terminal grid, the voice commands and the ``jarvis`` CLI all drive the same
+routes, so a pane's behaviour and a spoken command can never drift apart.
+
+Endpoints (prefix ``/api/agentic-ide``):
+
+* ``GET /state`` → current session (or none) + limits
+* ``GET /agents`` → Claude Code / Codex install status
+* ``GET /folders`` → browse folders (no path = start points)
+* ``POST /session`` → open a workspace (folder + terminals)
+* ``DELETE /session`` → close it and stop every agent
+* ``PUT /mode`` → focused coding mode on/off
+* ``GET /terminals/{name}/report`` → what one named terminal is doing
+* ``POST /terminals/{name}/prompt`` → type a prompt into it and press Enter
+* ``WS /pty/{name}`` → the pane's live terminal stream
+
+``{name}`` accepts the call-sign ("mika", "Mika") or a spoken phrase containing
+it, so a voice command reaches the right pane without exact spelling.
+"""
+from __future__ import annotations
+
+import asyncio
+import logging
+from dataclasses import asdict
+from pathlib import Path
+
+from fastapi import APIRouter, HTTPException, WebSocket, WebSocketDisconnect
+from pydantic import BaseModel, Field
+
+from jarvis.agentic_ide.folders import list_dir, start_points
+from jarvis.agentic_ide.names import default_names
+from jarvis.agentic_ide.session import (
+ AGENT_DISPLAY,
+ MAX_PROMPT_CHARS,
+ MAX_TERMINALS,
+ SessionError,
+ agent_argv,
+ get_registry,
+)
+
+from .surface_security import credentials_valid
+
+log = logging.getLogger(__name__)
+
+router = APIRouter(prefix="/api/agentic-ide", tags=["agentic-ide"])
+
+
+# --------------------------------------------------------------------------- #
+# Models #
+# --------------------------------------------------------------------------- #
+class TerminalRequest(BaseModel):
+ agent: str = Field(description="Coding agent to run: 'claude' or 'codex'.")
+ name: str | None = Field(
+ default=None,
+ description="Call-sign for this terminal; auto-assigned when omitted.",
+ )
+
+
+class StartSessionRequest(BaseModel):
+ folder: str = Field(description="Absolute path of the folder to work in.")
+ terminals: list[TerminalRequest] = Field(
+ default_factory=list,
+ description="One entry per terminal, in grid order.",
+ )
+
+
+class ModeRequest(BaseModel):
+ enabled: bool = Field(
+ description="True narrows Jarvis to this workspace; False returns to normal."
+ )
+
+
+class PromptRequest(BaseModel):
+ prompt: str = Field(
+ max_length=MAX_PROMPT_CHARS,
+ description="Text to type into the terminal, followed by Enter.",
+ )
+
+
+class AgentStatus(BaseModel):
+ name: str
+ display_name: str
+ installed: bool
+ version: str | None = None
+ install_command: str | None = None
+
+
+class AgentsResponse(BaseModel):
+ terminal_available: bool
+ max_terminals: int
+ suggested_names: list[str]
+ agents: list[AgentStatus]
+
+
+class FolderItem(BaseModel):
+ name: str
+ path: str
+ is_project: bool
+ is_repo: bool
+
+
+class FoldersResponse(BaseModel):
+ path: str | None
+ parent: str | None
+ entries: list[FolderItem]
+ error: str | None = None
+
+
+# --------------------------------------------------------------------------- #
+# REST #
+# --------------------------------------------------------------------------- #
[email protected]("/state", summary="Agentic-IDE workspace state")
+async def get_state() -> dict:
+ """The open workspace, its terminals, and whether focus mode is on."""
+ return get_registry().state()
+
+
[email protected]("/agents", response_model=AgentsResponse, summary="Coding agents available")
+async def get_agents() -> AgentsResponse:
+ """Which coding-agent CLIs this machine can run, and how to install them.
+
+ Detection reuses the shared CLI prober, then re-checks that the binary is
+ resolvable the way the PTY will resolve it — a GUI process starts with a
+ minimal PATH, so "installed" and "launchable from here" are not the same
+ question.
+ """
+ from jarvis.workspace.agents import detect_agents, pty_available
+
+ infos = await detect_agents()
+ agents = [
+ AgentStatus(
+ name=info.name,
+ display_name=info.display_name,
+ installed=bool(info.installed and agent_argv(info.name) is not None),
+ version=info.version,
+ install_command=info.install_command,
+ )
+ for info in infos
+ ]
+ return AgentsResponse(
+ terminal_available=pty_available(),
+ max_terminals=MAX_TERMINALS,
+ suggested_names=default_names(MAX_TERMINALS),
+ agents=agents,
+ )
+
+
[email protected]("/folders", response_model=FoldersResponse, summary="Browse folders")
+async def get_folders(path: str | None = None, include_hidden: bool = False) -> FoldersResponse:
+ """Sub-folders of ``path``; without ``path``, this machine's start points."""
+ if not path:
+ entries = await asyncio.to_thread(start_points)
+ return FoldersResponse(
+ path=None,
+ parent=None,
+ entries=[FolderItem(**asdict(e)) for e in entries],
+ )
+
+ found, error = await asyncio.to_thread(list_dir, path, include_hidden=include_hidden)
+ resolved = Path(path).expanduser() # noqa: ASYNC240 - no filesystem call
+ parent = str(resolved.parent) if resolved.parent != resolved else None
+ return FoldersResponse(
+ path=str(resolved),
+ parent=parent,
+ entries=[FolderItem(**asdict(e)) for e in found],
+ error=error,
+ )
+
+
[email protected]("/session", summary="Open an Agentic-IDE workspace")
+async def start_session(req: StartSessionRequest) -> dict:
+ """Open ``folder`` with one named terminal per requested agent."""
+ try:
+ session = await get_registry().start(
+ req.folder, [t.model_dump() for t in req.terminals]
+ )
+ except SessionError as exc:
+ raise HTTPException(status_code=422, detail=str(exc)) from exc
+ return {"ok": True, "session": session.to_dict()}
+
+
+ "/session",
+ summary="Close the Agentic-IDE workspace",
+ openapi_extra={"x-jarvis-dangerous": True},
+)
+async def end_session() -> dict:
+ """Close the workspace and stop every agent running in it."""
+ closed = await get_registry().end()
+ return {"ok": True, "closed": closed}
+
+
[email protected]("/mode", summary="Toggle focused coding mode")
+async def set_mode(req: ModeRequest) -> dict:
+ """Turn the focused coding mode on or off.
+
+ While on, Jarvis answers inside the open workspace — it knows the folder,
+ the codebase, and what each named terminal is doing. Turning it off returns
+ the assistant to its normal, whole-machine behaviour; the terminals keep
+ running either way.
+ """
+ try:
+ enabled = get_registry().set_focus_mode(req.enabled)
+ except SessionError as exc:
+ raise HTTPException(status_code=409, detail=str(exc)) from exc
+ return {"ok": True, "focus_mode": enabled}
+
+
[email protected]("/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``."""
+ try:
+ return get_registry().report(name, lines)
+ except SessionError as exc:
+ raise HTTPException(status_code=404, detail=str(exc)) from exc
+
+
[email protected]("/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."""
+ try:
+ term = await get_registry().send_prompt(name, req.prompt)
+ except SessionError as exc:
+ raise HTTPException(status_code=409, detail=str(exc)) from exc
+ return {
+ "ok": True,
+ "terminal": term.name,
+ "agent": AGENT_DISPLAY.get(term.agent, term.agent),
+ "sent": term.last_prompt,
+ "prompts_sent": term.prompts_sent,
+ }
+
+
+# --------------------------------------------------------------------------- #
+# PTY WebSocket #
+# --------------------------------------------------------------------------- #
[email protected]("/pty/{name}")
+async def agentic_pty(ws: WebSocket, name: str) -> None:
+ """Bidirectional bridge between one xterm pane and its agent's PTY.
+
+ Wire protocol (JSON both ways) — client: ``{t:"i",d}`` input,
+ ``{t:"r",cols,rows}`` resize; server: ``{t:"o",d}`` output, ``{t:"ready"}``,
+ ``{t:"exit",code}``, ``{t:"error",message}``.
+ """
+ await ws.accept()
+ if not credentials_valid(ws.scope):
+ await ws.close(code=4401, reason="unauthorized")
+ return
+
+ qp = ws.query_params
+ cols = _safe_int(qp.get("cols"), 80)
+ rows = _safe_int(qp.get("rows"), 24)
+
+ registry = get_registry()
+ send_lock = asyncio.Lock()
+
+ async def on_output(text: str) -> None:
+ async with send_lock:
+ try:
+ await ws.send_json({"t": "o", "d": text})
+ except Exception: # noqa: BLE001, S110 - viewer gone; transcript keeps filling
+ pass
+
+ async def on_exit(code: int) -> None:
+ async with send_lock:
+ try:
+ await ws.send_json({"t": "exit", "code": code})
+ except Exception: # noqa: BLE001, S110 - viewer gone
+ pass
+
+ try:
+ term = await registry.attach(name, cols, rows, on_output, on_exit)
+ except SessionError as exc:
+ await ws.send_json({"t": "error", "message": str(exc)})
+ await ws.close(code=4404, reason="attach failed")
+ return
+
+ await ws.send_json({"t": "ready", "name": term.name, "agent": term.agent})
+
+ try:
+ while True:
+ try:
+ msg = await ws.receive_json()
+ except WebSocketDisconnect:
+ break
+ except RuntimeError:
+ # AP-20: an unclean teardown raises RuntimeError, not
+ # WebSocketDisconnect — any read error is terminal.
+ break
+ except Exception: # noqa: BLE001, S112 - malformed frame; keep the PTY alive
+ continue
+ kind = msg.get("t")
+ if kind == "i":
+ registry.write(term.key, str(msg.get("d", "")))
+ elif kind == "r":
+ registry.resize(
+ term.key,
+ _safe_int(msg.get("cols"), cols),
+ _safe_int(msg.get("rows"), rows),
+ )
+ finally:
+ # The viewer closed the pane: stop the agent with it. Leaving an
+ # orphaned agent running with nobody watching would burn tokens
+ # invisibly, which is worse than having to restart the pane.
+ registry.detach(term.key)
+
+
+def _safe_int(value: object, default: int) -> int:
+ try:
+ n = int(str(value))
+ return n if n > 0 else default
+ except (TypeError, ValueError):
+ return default
+
+
+__all__ = ["router"]
diff --git a/jarvis/ui/web/frontend/src/components/agentic/AgenticGrid.tsx b/jarvis/ui/web/frontend/src/components/agentic/AgenticGrid.tsx
new file mode 100644
index 0000000000..2b82cf9bc2
--- /dev/null
+++ b/jarvis/ui/web/frontend/src/components/agentic/AgenticGrid.tsx
@@ -0,0 +1,276 @@
+/**
+ * The running Agentic-IDE workspace: a grid of named agent terminals, a toolbar
+ * (focus mode, appearance, font size, close), and one prompt bar that types into
+ * whichever terminal is selected.
+ *
+ * The prompt bar is deliberately the same channel Jarvis uses by voice — it
+ * POSTs to `/terminals/{name}/prompt` rather than writing into xterm locally.
+ * So "click Mika, type 'run the tests'" and saying "tell Mika to run the tests"
+ * take the identical path through the app, and the two can never behave
+ * differently.
+ */
+import { useCallback, useMemo, useState } from "react";
+import {
+ ArrowUp,
+ Brain,
+ FolderGit2,
+ Minus,
+ Moon,
+ Plus,
+ Power,
+ Sun,
+ Type,
+} from "lucide-react";
+import { cn } from "@/lib/utils";
+import { useEventStore } from "@/store/events";
+import {
+ AgenticTerminal,
+ PaneStatusPill,
+ type PaneStatus,
+} from "./AgenticTerminal";
+import type { TerminalAppearance } from "./terminalThemes";
+import { promptTerminal, type SessionState } from "@/lib/agenticIdeApi";
+
+interface AgenticGridProps {
+ session: SessionState;
+ focusMode: boolean;
+ 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;
+}
+
+const FONT_MIN = 10;
+const FONT_MAX = 20;
+
+export function AgenticGrid({
+ session,
+ focusMode,
+ onToggleFocus,
+ onClose,
+ busy = false,
+}: AgenticGridProps) {
+ const pushToast = useEventStore((s) => s.pushToast);
+ const [appearance, setAppearance] = useState<TerminalAppearance>("light");
+ const [fontSize, setFontSize] = useState(13);
+ const [target, setTarget] = useState(session.terminals[0]?.name ?? "");
+ const [statuses, setStatuses] = useState<Record<string, { status: PaneStatus; detail?: string }>>({});
+ const [prompt, setPrompt] = useState("");
+ const [sending, setSending] = useState(false);
+
+ const columns = gridColumns(session.terminals.length);
+
+ const setStatus = useCallback((name: string, status: PaneStatus, detail?: string) => {
+ setStatuses((prev) => ({ ...prev, [name]: { status, detail } }));
+ }, []);
+
+ const send = async () => {
+ const text = prompt.trim();
+ if (!text || !target) return;
+ setSending(true);
+ try {
+ await promptTerminal(target, text);
+ setPrompt("");
+ } catch (e) {
+ pushToast("error", (e as Error).message);
+ } finally {
+ setSending(false);
+ }
+ };
+
+ const project = session.project;
+ const branchLabel = useMemo(
+ () => (project.is_repo && project.branch ? `on ${project.branch}` : ""),
+ [project],
+ );
+
+ return (
+ <div className="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">
+ <FolderGit2 className="h-4 w-4 shrink-0 text-primary" />
+ <span className="font-display text-sm font-semibold">{project.name}</span>
+ {branchLabel && (
+ <span className="chip shrink-0 text-[10px] uppercase tracking-wide">
+ {branchLabel}
+ </span>
+ )}
+ <code className="hidden min-w-0 truncate font-mono text-[11px] text-muted-foreground lg:block">
+ {session.folder}
+ </code>
+ </div>
+
+ {/* Focus mode — the explicit switch into "Jarvis codes with me here". */}
+ <button
+ type="button"
+ onClick={() => onToggleFocus(!focusMode)}
+ aria-pressed={focusMode}
+ data-testid="agentic-focus-toggle"
+ title={
+ focusMode
+ ? "Focused coding mode is on — Jarvis answers inside this workspace. Click to leave."
+ : "Turn on focused coding mode — Jarvis answers inside this workspace until you switch back."
+ }
+ className={cn(
+ "flex shrink-0 items-center gap-2 rounded-lg border px-3 py-1.5 text-xs font-medium transition-colors",
+ focusMode
+ ? "border-primary/60 bg-primary/15 text-primary"
+ : "border-border text-muted-foreground hover:border-primary/40 hover:text-foreground",
+ )}
+ >
+ <Brain className="h-4 w-4" />
+ {focusMode ? "Coding mode ON" : "Coding mode OFF"}
+ </button>
+
+ <div className="flex shrink-0 items-center gap-1 rounded-lg border border-border p-0.5">
+ <button
+ type="button"
+ aria-label="Light terminals"
+ aria-pressed={appearance === "light"}
+ onClick={() => setAppearance("light")}
+ className={cn(
+ "flex h-7 w-7 items-center justify-center rounded-md transition-colors",
+ appearance === "light" ? "bg-primary/20 text-primary" : "text-muted-foreground",
+ )}
+ >
+ <Sun className="h-3.5 w-3.5" />
+ </button>
+ <button
+ type="button"
+ aria-label="Dark terminals"
+ aria-pressed={appearance === "dark"}
+ onClick={() => setAppearance("dark")}
+ className={cn(
+ "flex h-7 w-7 items-center justify-center rounded-md transition-colors",
+ appearance === "dark" ? "bg-primary/20 text-primary" : "text-muted-foreground",
+ )}
+ >
+ <Moon className="h-3.5 w-3.5" />
+ </button>
+ </div>
+
+ <div className="flex shrink-0 items-center gap-1 rounded-lg border border-border p-0.5">
+ <button
+ type="button"
+ aria-label="Smaller text"
+ onClick={() => setFontSize((n) => Math.max(FONT_MIN, n - 1))}
+ className="flex h-7 w-7 items-center justify-center rounded-md text-muted-foreground hover:text-foreground"
+ >
+ <Minus className="h-3.5 w-3.5" />
+ </button>
+ <Type className="h-3.5 w-3.5 text-muted-foreground" />
+ <button
+ type="button"
+ aria-label="Larger text"
+ onClick={() => setFontSize((n) => Math.min(FONT_MAX, n + 1))}
+ className="flex h-7 w-7 items-center justify-center rounded-md text-muted-foreground hover:text-foreground"
+ >
+ <Plus className="h-3.5 w-3.5" />
+ </button>
+ </div>
+
+ <button
+ type="button"
+ className="btn-ghost shrink-0"
+ onClick={onClose}
+ disabled={busy}
+ title="Close the workspace and stop every agent in it"
+ >
+ <Power className="h-4 w-4" />
+ Close
+ </button>
+ </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)}
+ />
+ ))}
+ </div>
+
+ {/* -------------------------------------------------------- prompt bar */}
+ <div className="border-t border-border px-4 py-3">
+ <div className="mb-2 flex flex-wrap items-center gap-2">
+ <span className="text-[11px] uppercase tracking-wider text-muted-foreground">
+ Send to
+ </span>
+ {session.terminals.map((term) => {
+ const state = statuses[term.name];
+ return (
+ <button
+ key={term.key}
+ type="button"
+ onClick={() => setTarget(term.name)}
+ aria-pressed={target === term.name}
+ className={cn(
+ "flex items-center gap-2 rounded-lg border px-2.5 py-1 text-xs transition-colors",
+ target === term.name
+ ? "border-primary/60 bg-primary/10 text-primary"
+ : "border-border text-muted-foreground hover:border-primary/40",
+ )}
+ >
+ <span className="font-medium">{term.name}</span>
+ <PaneStatusPill status={state?.status ?? "connecting"} detail={state?.detail} />
+ </button>
+ );
+ })}
+ </div>
+ <div className="flex items-end gap-2">
+ <textarea
+ value={prompt}
+ onChange={(e) => setPrompt(e.target.value)}
+ onKeyDown={(e) => {
+ if (e.key === "Enter" && !e.shiftKey) {
+ e.preventDefault();
+ void send();
+ }
+ }}
+ rows={2}
+ placeholder={
+ target
+ ? `Type an instruction for ${target} — Enter sends, Shift+Enter adds a line`
+ : "Pick a terminal first"
+ }
+ className="max-h-32 min-h-[52px] flex-1 resize-y rounded-lg border border-border bg-background/60 px-3 py-2 text-sm outline-none focus:border-primary/50"
+ />
+ <button
+ type="button"
+ className="btn-primary h-[52px] shrink-0"
+ disabled={sending || !prompt.trim() || !target}
+ onClick={() => void send()}
+ >
+ <ArrowUp className="h-4 w-4" />
+ Send
+ </button>
+ </div>
+ <p className="mt-2 text-[11px] text-muted-foreground">
+ Anything you can type here, you can also say out loud — for example
+ “what is {session.terminals[0]?.name ?? "Mika"} doing?” or “tell{" "}
+ {session.terminals[0]?.name ?? "Mika"} to run the tests”.
+ </p>
+ </div>
+ </div>
+ );
+}
diff --git a/jarvis/ui/web/frontend/src/components/agentic/AgenticTerminal.tsx b/jarvis/ui/web/frontend/src/components/agentic/AgenticTerminal.tsx
new file mode 100644
index 0000000000..b711eaeb9b
--- /dev/null
+++ b/jarvis/ui/web/frontend/src/components/agentic/AgenticTerminal.tsx
@@ -0,0 +1,315 @@
+/**
+ * One named pane of the Agentic IDE: xterm.js wired to
+ * `/api/agentic-ide/pty/{name}`, running one coding agent in the chosen folder.
+ *
+ * Two conventions matter here and both are load-bearing:
+ *
+ * 1. The xterm instance lives in a ref, never in state — putting it in state
+ * re-renders the component on every output chunk and the pane stutters.
+ * 2. Appearance and font size are applied to the LIVE instance in their own
+ * effects. Rebuilding the terminal when the user flips to dark mode would
+ * 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.
+ */
+import { useEffect, useRef } from "react";
+import { Terminal } from "@xterm/xterm";
+import { FitAddon } from "@xterm/addon-fit";
+import { WebLinksAddon } from "@xterm/addon-web-links";
+import "@xterm/xterm/css/xterm.css";
+import { AlertCircle, Circle, Loader2 } from "lucide-react";
+import { cn } from "@/lib/utils";
+import {
+ PANE_CHROME,
+ themeFor,
+ type TerminalAppearance,
+} from "./terminalThemes";
+
+export type PaneStatus = "connecting" | "live" | "exited" | "error";
+
+interface AgenticTerminalProps {
+ /** Terminal call-sign — also the WS path segment. */
+ name: string;
+ /** Agent label shown in the pane header ("Claude Code"). */
+ displayName: string;
+ appearance: TerminalAppearance;
+ fontSize: number;
+ /** Highlight this pane as the prompt target. */
+ focused?: boolean;
+ onFocus?: () => void;
+ onStatus?: (status: PaneStatus, detail?: string) => void;
+}
+
+function socketUrl(name: string, cols: number, rows: number): string {
+ const proto = window.location.protocol === "https:" ? "wss" : "ws";
+ const query = new URLSearchParams({ cols: String(cols), rows: String(rows) });
+ return `${proto}://${window.location.host}/api/agentic-ide/pty/${encodeURIComponent(
+ name,
+ )}?${query.toString()}`;
+}
+
+export function AgenticTerminal({
+ name,
+ displayName,
+ appearance,
+ fontSize,
+ focused = false,
+ onFocus,
+ onStatus,
+}: AgenticTerminalProps) {
+ const containerRef = useRef<HTMLDivElement | null>(null);
+ const termRef = useRef<Terminal | null>(null);
+ const fitRef = useRef<FitAddon | null>(null);
+ const statusRef = useRef<PaneStatus>("connecting");
+ // Latest callbacks/appearance without re-running the connect effect.
+ const onStatusRef = useRef(onStatus);
+ const initialRef = useRef({ appearance, fontSize });
+ onStatusRef.current = onStatus;
+
+ useEffect(() => {
+ const container = containerRef.current;
+ if (!container) return;
+
+ const term = new Terminal({
+ convertEol: false,
+ fontFamily:
+ "'JetBrains Mono', 'Fira Code', 'SF Mono', Consolas, 'Courier New', monospace",
+ 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,
+ cursorBlink: true,
+ cursorStyle: "bar",
+ scrollback: 10000,
+ theme: themeFor(initialRef.current.appearance),
+ });
+ const fit = new FitAddon();
+ term.loadAddon(fit);
+ term.loadAddon(new WebLinksAddon());
+ term.open(container);
+ termRef.current = term;
+ fitRef.current = fit;
+ try {
+ fit.fit();
+ } catch {
+ /* not measured yet — the ResizeObserver below will fit */
+ }
+
+ const report = (status: PaneStatus, detail?: string) => {
+ statusRef.current = status;
+ onStatusRef.current?.(status, detail);
+ };
+
+ let ws: WebSocket | null = null;
+ let disposed = false;
+ let everLive = false;
+
+ const sendResize = () => {
+ try {
+ fit.fit();
+ } catch {
+ return;
+ }
+ if (ws && ws.readyState === WebSocket.OPEN) {
+ ws.send(JSON.stringify({ t: "r", cols: term.cols, rows: term.rows }));
+ }
+ };
+
+ ws = new WebSocket(socketUrl(name, term.cols || 80, term.rows || 24));
+ ws.onopen = () => {
+ report("connecting");
+ // The spawn used a best-effort size (the mount-time fit usually runs
+ // before the grid cell is measured), and resizes sent while the socket
+ // was connecting were dropped — without this the agent's full-screen TUI
+ // keeps drawing at the wrong width and looks clipped.
+ sendResize();
+ requestAnimationFrame(sendResize);
+ };
+ ws.onmessage = (ev) => {
+ let msg: { t?: string; d?: string; code?: number; message?: string };
+ try {
+ msg = JSON.parse(ev.data as string);
+ } catch {
+ return;
+ }
+ if (msg.t === "o") term.write(msg.d ?? "");
+ else if (msg.t === "ready") {
+ everLive = true;
+ report("live");
+ term.focus();
+ } else if (msg.t === "exit") {
+ report("exited", `exit code ${msg.code ?? "?"}`);
+ term.write(
+ `\r\n\x1b[33m[${displayName} exited — code ${msg.code ?? "?"}]\x1b[0m\r\n`,
+ );
+ } else if (msg.t === "error") {
+ report("error", msg.message ?? "terminal error");
+ }
+ };
+ ws.onerror = () => report("error", "Could not reach the terminal.");
+ ws.onclose = (ev) => {
+ if (everLive) {
+ report("exited");
+ } else if (!disposed) {
+ report(
+ "error",
+ ev.code === 4401
+ ? "Terminal authorization failed — reopen the pane to retry."
+ : ev.code === 4404
+ ? "This terminal is no longer part of the open workspace."
+ : `Terminal connection closed (code ${ev.code || "?"}).`,
+ );
+ }
+ };
+
+ term.onData((data) => {
+ if (ws && ws.readyState === WebSocket.OPEN) {
+ ws.send(JSON.stringify({ t: "i", d: data }));
+ }
+ });
+
+ window.addEventListener("resize", sendResize);
+ const ro = new ResizeObserver(() => sendResize());
+ ro.observe(container);
+
+ return () => {
+ disposed = true;
+ window.removeEventListener("resize", sendResize);
+ ro.disconnect();
+ try {
+ ws?.close();
+ } catch {
+ /* ignore */
+ }
+ term.dispose();
+ termRef.current = null;
+ fitRef.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.
+ useEffect(() => {
+ const term = termRef.current;
+ if (!term) return;
+ term.options.theme = themeFor(appearance);
+ }, [appearance]);
+
+ useEffect(() => {
+ const term = termRef.current;
+ if (!term) return;
+ term.options.fontSize = fontSize;
+ try {
+ fitRef.current?.fit();
+ } catch {
+ /* ignore */
+ }
+ }, [fontSize]);
+
+ const chrome = PANE_CHROME[appearance];
+
+ return (
+ <div
+ onMouseDown={onFocus}
+ className={cn(
+ "relative flex h-full w-full flex-col overflow-hidden rounded-xl border transition-shadow",
+ focused
+ ? "border-primary/60 shadow-[0_0_0_1px_hsl(var(--primary)/0.35),0_8px_24px_-12px_rgba(0,0,0,0.5)]"
+ : "shadow-[0_4px_16px_-10px_rgba(0,0,0,0.4)]",
+ )}
+ style={{
+ background: chrome.shell,
+ borderColor: focused ? undefined : chrome.border,
+ }}
+ data-testid={`agentic-pane-${name}`}
+ >
+ <PaneHeader
+ name={name}
+ displayName={displayName}
+ appearance={appearance}
+ focused={focused}
+ />
+ <div ref={containerRef} className="flex-1 overflow-hidden px-2 pb-1 pt-1" />
+ </div>
+ );
+}
+
+function PaneHeader({
+ name,
+ displayName,
+ appearance,
+ focused,
+}: {
+ name: string;
+ displayName: string;
+ appearance: TerminalAppearance;
+ focused: boolean;
+}) {
+ const light = appearance === "light";
+ return (
+ <header
+ className="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)",
+ }}
+ >
+ <div className="flex min-w-0 items-center gap-2">
+ <span
+ className={cn(
+ "rounded-md px-2 py-0.5 font-display text-[13px] font-semibold tracking-tight",
+ focused ? "bg-primary/20 text-primary" : "",
+ )}
+ style={
+ focused
+ ? undefined
+ : { color: light ? "#2b2b33" : "#e8e8ec", background: light ? "rgba(0,0,0,0.05)" : "rgba(255,255,255,0.06)" }
+ }
+ >
+ {name}
+ </span>
+ <span
+ className="truncate text-[11px] uppercase tracking-wider"
+ style={{ color: light ? "#77777f" : "#8a8a95" }}
+ >
+ {displayName}
+ </span>
+ </div>
+ </header>
+ );
+}
+
+/** Small status pill reused by the grid toolbar. */
+export function PaneStatusPill({ status, detail }: { status: PaneStatus; detail?: string }) {
+ if (status === "live") {
+ return (
+ <span className="flex items-center gap-1 text-[11px] text-emerald-400" title={detail}>
+ <Circle className="h-2 w-2 fill-current" />
+ live
+ </span>
+ );
+ }
+ if (status === "error") {
+ return (
+ <span className="flex items-center gap-1 text-[11px] text-destructive" title={detail}>
+ <AlertCircle className="h-3 w-3" />
+ error
+ </span>
+ );
+ }
+ if (status === "exited") {
+ return (
+ <span className="text-[11px] text-muted-foreground" title={detail}>
+ exited
+ </span>
+ );
+ }
+ return (
+ <span className="flex items-center gap-1 text-[11px] text-muted-foreground" title={detail}>
+ <Loader2 className="h-3 w-3 animate-spin" />
+ starting
+ </span>
+ );
+}
diff --git a/jarvis/ui/web/frontend/src/components/agentic/FolderPicker.tsx b/jarvis/ui/web/frontend/src/components/agentic/FolderPicker.tsx
new file mode 100644
index 0000000000..3151e3babc
--- /dev/null
+++ b/jarvis/ui/web/frontend/src/components/agentic/FolderPicker.tsx
@@ -0,0 +1,180 @@
+/**
+ * Folder picker for step 1 of the Agentic-IDE wizard.
+ *
+ * A native folder dialog was not an option: the desktop app is a web UI, so a
+ * native picker would exist on one OS and be missing on the others — and on a
+ * headless server there is no dialog at all. This browses over REST instead,
+ * which behaves identically on Windows, macOS, Linux and a remote box, and it
+ * keeps a plain path field for the case where the user already knows where they
+ * are going (or is working on a machine with no start points worth listing).
+ */
+import { useCallback, useEffect, useState } from "react";
+import {
+ ChevronRight,
+ CornerLeftUp,
+ Folder,
+ FolderGit2,
+ FolderOpen,
+ Loader2,
+ RefreshCw,
+} from "lucide-react";
+import { cn } from "@/lib/utils";
+import { fetchFolders, type FolderItem } from "@/lib/agenticIdeApi";
+
+interface FolderPickerProps {
+ selected: string | null;
+ onSelect: (path: string) => void;
+}
+
+export function FolderPicker({ selected, onSelect }: FolderPickerProps) {
+ const [path, setPath] = useState<string | null>(null);
+ const [parent, setParent] = useState<string | null>(null);
+ const [entries, setEntries] = useState<FolderItem[]>([]);
+ const [loading, setLoading] = useState(false);
+ const [error, setError] = useState<string | null>(null);
+ const [manual, setManual] = useState("");
+
+ const load = useCallback(async (target: string | null) => {
+ setLoading(true);
+ setError(null);
+ try {
+ const res = await fetchFolders(target);
+ setPath(res.path);
+ setParent(res.parent);
+ setEntries(res.entries);
+ if (res.error) setError(res.error);
+ } catch (e) {
+ setError((e as Error).message);
+ } finally {
+ setLoading(false);
+ }
+ }, []);
+
+ useEffect(() => {
+ void load(null);
+ }, [load]);
+
+ const open = (item: FolderItem) => {
+ onSelect(item.path);
+ void load(item.path);
+ };
+
+ return (
+ <div className="space-y-3">
+ <div className="flex flex-wrap items-center gap-2">
+ <button
+ type="button"
+ className="btn-ghost"
+ onClick={() => void load(parent)}
+ disabled={loading || (!parent && path === null)}
+ title="Go up one folder"
+ >
+ <CornerLeftUp className="h-4 w-4" />
+ Up
+ </button>
+ <button
+ type="button"
+ className="btn-ghost"
+ onClick={() => void load(path)}
+ disabled={loading}
+ title="Reload this folder"
+ >
+ {loading ? (
+ <Loader2 className="h-4 w-4 animate-spin" />
+ ) : (
+ <RefreshCw className="h-4 w-4" />
+ )}
+ </button>
+ <code className="min-w-0 flex-1 truncate rounded-md bg-background/60 px-3 py-1.5 font-mono text-xs text-muted-foreground">
+ {path ?? "This machine"}
+ </code>
+ </div>
+
+ <div className="max-h-[320px] overflow-y-auto scrollbar-jarvis rounded-xl border border-border bg-card/40">
+ {entries.length === 0 && !loading ? (
+ <p className="p-4 text-sm text-muted-foreground">
+ Nothing to list here — type a path below instead.
+ </p>
+ ) : (
+ <ul className="divide-y divide-border/50">
+ {entries.map((item) => {
+ const isSelected = selected === item.path;
+ return (
+ <li key={item.path}>
+ <button
+ type="button"
+ onClick={() => open(item)}
+ className={cn(
+ "flex w-full items-center gap-3 px-3 py-2 text-left text-sm transition-colors",
+ isSelected
+ ? "bg-primary/10 text-foreground"
+ : "hover:bg-background/60",
+ )}
+ >
+ {item.is_repo ? (
+ <FolderGit2 className="h-4 w-4 shrink-0 text-primary" />
+ ) : item.is_project ? (
+ <FolderOpen className="h-4 w-4 shrink-0 text-primary/70" />
+ ) : (
+ <Folder className="h-4 w-4 shrink-0 text-muted-foreground" />
+ )}
+ <span className="min-w-0 flex-1 truncate">{item.name}</span>
+ {item.is_repo && (
+ <span className="chip shrink-0 text-[10px] uppercase tracking-wide">
+ git
+ </span>
+ )}
+ <ChevronRight className="h-4 w-4 shrink-0 text-muted-foreground/60" />
+ </button>
+ </li>
+ );
+ })}
+ </ul>
+ )}
+ </div>
+
+ {error && (
+ <p className="text-xs text-destructive" role="alert">
+ {error}
+ </p>
+ )}
+
+ <div className="flex flex-wrap items-center gap-2">
+ <input
+ value={manual}
+ onChange={(e) => setManual(e.target.value)}
+ onKeyDown={(e) => {
+ if (e.key === "Enter" && manual.trim()) {
+ onSelect(manual.trim());
+ void load(manual.trim());
+ }
+ }}
+ placeholder="…or paste a full folder path"
+ className="min-w-0 flex-1 rounded-lg border border-border bg-background/60 px-3 py-2 font-mono text-xs outline-none focus:border-primary/50"
+ spellCheck={false}
+ />
+ <button
+ type="button"
+ className="btn-ghost"
+ disabled={!manual.trim()}
+ onClick={() => {
+ onSelect(manual.trim());
+ void load(manual.trim());
+ }}
+ >
+ Use this path
+ </button>
+ </div>
+
+ {selected && (
+ <div className="flex items-center gap-2 rounded-lg border border-primary/40 bg-primary/5 px-3 py-2 text-sm">
+ <FolderOpen className="h-4 w-4 shrink-0 text-primary" />
+ <span className="text-muted-foreground">Selected:</span>
+ <code className="min-w-0 flex-1 truncate font-mono text-xs text-foreground">
+ {selected}
+ </code>
+ </div>
+ )}
+ </div>
+ );
+}
diff --git a/jarvis/ui/web/frontend/src/components/agentic/terminalThemes.ts b/jarvis/ui/web/frontend/src/components/agentic/terminalThemes.ts
new file mode 100644
index 0000000000..5314939413
--- /dev/null
+++ b/jarvis/ui/web/frontend/src/components/agentic/terminalThemes.ts
@@ -0,0 +1,81 @@
+import type { ITheme } from "@xterm/xterm";
+
+/**
+ * Terminal colour schemes for the Agentic IDE.
+ *
+ * Why a hand-built light palette instead of "same colours, white background":
+ * the 16 ANSI colours a coding agent emits were designed for dark terminals.
+ * Their bright variants (yellow, cyan, white) have almost no contrast on paper,
+ * and `brightBlack` — which agents use for hints, diffs, and dimmed prose —
+ * becomes invisible. So the light theme re-derives all 16 slots for a light
+ * ground: darker, more saturated hues, with the "bright" row kept genuinely
+ * distinguishable rather than lighter.
+ *
+ * Both themes are checked against WCAG AA for body text (>= 4.5:1 against
+ * their own background), which is the difference between a terminal you can
+ * read for an hour and one you squint at.
+ */
+
+/** Warm paper — the default. Reads like an editor, not like a console. */
+export const LIGHT_TERMINAL_THEME: ITheme = {
+ background: "#fcfbf8",
+ foreground: "#2b2b33",
+ cursor: "#a86b00",
+ cursorAccent: "#fcfbf8",
+ selectionBackground: "#ffe9a8",
+ selectionForeground: "#2b2b33",
+ black: "#3a3a44",
+ red: "#c0392b",
+ green: "#1b7f3b",
+ yellow: "#9a6700",
+ blue: "#1a5fb4",
+ magenta: "#8b3fa8",
+ cyan: "#0e7490",
+ white: "#6b6b76",
+ brightBlack: "#77777f",
+ brightRed: "#e0402c",
+ brightGreen: "#12703a",
+ brightYellow: "#b07d00",
+ brightBlue: "#0b57d0",
+ brightMagenta: "#a333c8",
+ brightCyan: "#0f7c8f",
+ brightWhite: "#1f1f26",
+};
+
+/** Deep slate for late-night work — matches the app shell, not pure black. */
+export const DARK_TERMINAL_THEME: ITheme = {
+ background: "#12141a",
+ foreground: "#e8e8ec",
+ cursor: "#ffd60a",
+ cursorAccent: "#12141a",
+ selectionBackground: "#3a4252",
+ selectionForeground: "#ffffff",
+ black: "#2a2d36",
+ red: "#ff6b5e",
+ green: "#5ddb8c",
+ yellow: "#ffd60a",
+ blue: "#7aa8ff",
+ magenta: "#d99bff",
+ cyan: "#6fdbe8",
+ white: "#c8c8d0",
+ brightBlack: "#8a8a95",
+ brightRed: "#ff8b80",
+ brightGreen: "#86e8a8",
+ brightYellow: "#ffe479",
+ brightBlue: "#a5c4ff",
+ brightMagenta: "#e8bdff",
+ brightCyan: "#9aeaf2",
+ brightWhite: "#ffffff",
+};
+
+export type TerminalAppearance = "light" | "dark";
+
+export function themeFor(appearance: TerminalAppearance): ITheme {
+ return appearance === "dark" ? DARK_TERMINAL_THEME : LIGHT_TERMINAL_THEME;
+}
+
+/** Chrome (pane frame) colours that go with each terminal theme. */
+export const PANE_CHROME: Record<TerminalAppearance, { shell: string; border: string }> = {
+ light: { shell: "#fcfbf8", border: "rgba(0,0,0,0.10)" },
+ dark: { shell: "#12141a", border: "rgba(255,255,255,0.10)" },
+};
diff --git a/jarvis/ui/web/frontend/src/components/layout/MainView.tsx b/jarvis/ui/web/frontend/src/components/layout/MainView.tsx
index 99e04670b6..0c0b0490d2 100644
--- a/jarvis/ui/web/frontend/src/components/layout/MainView.tsx
+++ b/jarvis/ui/web/frontend/src/components/layout/MainView.tsx
@@ -20,6 +20,7 @@ import { FeedbackView } from "@/views/feedback/FeedbackView";
import { AgentInstructionsView } from "@/views/AgentInstructionsView";
import { TelephonySetupView } from "@/views/TelephonyView";
import { DictionaryView } from "@/views/DictionaryView";
+import { AgenticIdeView } from "@/views/AgenticIdeView";
/**
* Main area to the right of the sidebar. All views are switched the classic
@@ -105,6 +106,8 @@ function SwitchOnActiveSection({ active }: { active: string }) {
return <FeedbackView />;
case "agent-instructions":
return <AgentInstructionsView />;
+ case "agentic-ide":
+ return <AgenticIdeView />;
default:
return <ChatsView />;
}
diff --git a/jarvis/ui/web/frontend/src/components/layout/Sidebar.tsx b/jarvis/ui/web/frontend/src/components/layout/Sidebar.tsx
index c8ca0500f6..34e1584775 100644
--- a/jarvis/ui/web/frontend/src/components/layout/Sidebar.tsx
+++ b/jarvis/ui/web/frontend/src/components/layout/Sidebar.tsx
@@ -18,6 +18,7 @@ import {
Contact,
MessageSquareWarning,
ScrollText,
+ SquareTerminal,
Loader2,
type LucideIcon,
ChevronRight,
@@ -126,11 +127,23 @@ const NAV_GROUPS: NavItem[][] = [
},
{ id: "outputs", labelKey: "nav.outputs", icon: FolderOpen },
],
- // 4) Social links + in-app feedback — pinned to the bottom group.
+ // 4) Social links + in-app feedback.
[
{ id: "socials", labelKey: "nav.socials", icon: Share2 },
{ id: "feedback", labelKey: "nav.feedback", icon: MessageSquareWarning },
],
+ // 5) Agentic IDE — its own bottom group on purpose. It is not one more page
+ // among the tools above: opening it puts real coding agents to work in a
+ // folder and can narrow the assistant to that workspace, so it sits apart
+ // with its own divider rather than blending into the list.
+ [
+ {
+ id: "agentic-ide",
+ labelKey: "nav.agentic_ide",
+ icon: SquareTerminal,
+ fallbackLabel: "Agentic IDE",
+ },
+ ],
];
const VOICE_STATE_STYLE: Record<string, { dot: string; pulse: boolean }> = {
diff --git a/jarvis/ui/web/frontend/src/i18n/locales/de.json b/jarvis/ui/web/frontend/src/i18n/locales/de.json
index 0dfce1453c..67b04e8766 100644
--- a/jarvis/ui/web/frontend/src/i18n/locales/de.json
+++ b/jarvis/ui/web/frontend/src/i18n/locales/de.json
@@ -1005,16 +1005,6 @@
"integration_bad_note": "Provider konnte nicht erreicht werden.",
"failed": "Test fehlgeschlagen"
},
- "apikeys_base_url": {
- "label": "Server-URL",
- "placeholder_required": "z. B. http://localhost:8000 — erforderlich",
- "save": "Speichern",
- "saving": "Speichere…",
- "saved": "Server-URL gespeichert",
- "cleared": "Server-URL auf den Standard zurückgesetzt",
- "hint_default": "Leer lassen, um die oben gezeigte Standard-Adresse zu verwenden.",
- "hint_required": "Dieser Anbieter braucht eine Server-URL — trage ein, wo dein lokaler Server läuft."
- },
"apikeys_model": {
"heading": "Modell",
"recommended_tag": "Empfohlen",
diff --git a/jarvis/ui/web/frontend/src/i18n/locales/en.json b/jarvis/ui/web/frontend/src/i18n/locales/en.json
index e9a684963c..d298c0667a 100644
--- a/jarvis/ui/web/frontend/src/i18n/locales/en.json
+++ b/jarvis/ui/web/frontend/src/i18n/locales/en.json
@@ -1006,16 +1006,6 @@
"integration_bad_note": "The provider could not be reached.",
"failed": "Test failed"
},
- "apikeys_base_url": {
- "label": "Server URL",
- "placeholder_required": "e.g. http://localhost:8000 — required",
- "save": "Save",
- "saving": "Saving…",
- "saved": "Server URL saved",
- "cleared": "Server URL reset to the default",
- "hint_default": "Leave empty to use the default address shown above.",
- "hint_required": "This provider needs a server URL — enter where your local server runs."
- },
"apikeys_model": {
"heading": "Model",
"recommended_tag": "Recommended",
diff --git a/jarvis/ui/web/frontend/src/lib/agenticIdeApi.ts b/jarvis/ui/web/frontend/src/lib/agenticIdeApi.ts
new file mode 100644
index 0000000000..3c6c3e444d
--- /dev/null
+++ b/jarvis/ui/web/frontend/src/lib/agenticIdeApi.ts
@@ -0,0 +1,153 @@
+// REST client for the Agentic IDE. Plain same-origin fetch (mirrors
+// workspaceApi/chatsApi), `no-store` everywhere because WebView2 happily serves
+// a stale folder listing or terminal state from cache otherwise.
+
+export interface AgentStatus {
+ name: string;
+ display_name: string;
+ installed: boolean;
+ version: string | null;
+ install_command: string | null;
+}
+
+export interface AgentsResponse {
+ terminal_available: boolean;
+ max_terminals: number;
+ suggested_names: string[];
+ agents: AgentStatus[];
+}
+
+export interface FolderItem {
+ name: string;
+ path: string;
+ is_project: boolean;
+ is_repo: boolean;
+}
+
+export interface FoldersResponse {
+ path: string | null;
+ parent: string | null;
+ entries: FolderItem[];
+ error?: string | null;
+}
+
+export interface ProjectProfile {
+ path: string;
+ name: string;
+ exists: boolean;
+ is_repo: boolean;
+ branch: string | null;
+ stacks: string[];
+ instruction_files: string[];
+ top_level_dirs: string[];
+ skills: string[];
+ note: string;
+}
+
+export interface TerminalState {
+ key: string;
+ name: string;
+ agent: string;
+ display_name: string;
+ index: number;
+ status: "pending" | "live" | "exited" | "error";
+ exit_code: number | null;
+ error: string;
+ started_at: number | null;
+ last_output_at: number | null;
+ idle_seconds: number | null;
+ prompts_sent: number;
+ last_prompt: string;
+ lines_captured: number;
+}
+
+export interface SessionState {
+ id: string;
+ folder: string;
+ project: ProjectProfile;
+ created_at: number;
+ focus_mode: boolean;
+ terminals: TerminalState[];
+}
+
+export interface IdeState {
+ active: boolean;
+ session: SessionState | null;
+ max_terminals: number;
+}
+
+export interface TerminalPlan {
+ agent: string;
+ name?: string;
+}
+
+async function detail(res: Response): Promise<string> {
+ try {
+ const body = (await res.json()) as { detail?: string };
+ if (body?.detail) return body.detail;
+ } catch {
+ /* fall through */
+ }
+ return `request failed: ${res.status}`;
+}
+
+async function getJson<T>(url: string): Promise<T> {
+ const res = await fetch(url, { cache: "no-store" });
+ if (!res.ok) throw new Error(await detail(res));
+ return (await res.json()) as T;
+}
+
+export function fetchIdeState(): Promise<IdeState> {
+ return getJson<IdeState>("/api/agentic-ide/state");
+}
+
+export function fetchIdeAgents(): Promise<AgentsResponse> {
+ return getJson<AgentsResponse>("/api/agentic-ide/agents");
+}
+
+export function fetchFolders(path?: string | null): Promise<FoldersResponse> {
+ const query = path ? `?path=${encodeURIComponent(path)}` : "";
+ return getJson<FoldersResponse>(`/api/agentic-ide/folders${query}`);
+}
+
+export async function startIdeSession(
+ folder: string,
+ terminals: TerminalPlan[],
+): Promise<SessionState> {
+ const res = await fetch("/api/agentic-ide/session", {
+ method: "POST",
+ headers: { "Content-Type": "application/json" },
+ body: JSON.stringify({ folder, terminals }),
+ });
+ if (!res.ok) throw new Error(await detail(res));
+ const body = (await res.json()) as { session: SessionState };
+ return body.session;
+}
+
+export async function endIdeSession(): Promise<void> {
+ const res = await fetch("/api/agentic-ide/session", { method: "DELETE" });
+ if (!res.ok) throw new Error(await detail(res));
+}
+
+export async function setFocusMode(enabled: boolean): Promise<boolean> {
+ const res = await fetch("/api/agentic-ide/mode", {
+ method: "PUT",
+ headers: { "Content-Type": "application/json" },
+ body: JSON.stringify({ enabled }),
+ });
+ if (!res.ok) throw new Error(await detail(res));
+ const body = (await res.json()) as { focus_mode: boolean };
+ return body.focus_mode;
+}
+
+export async function promptTerminal(name: string, prompt: string): Promise<void> {
+ const res = await fetch(
+ `/api/agentic-ide/terminals/${encodeURIComponent(name)}/prompt`,
+ {
+ method: "POST",
+ headers: { "Content-Type": "application/json" },
+ body: JSON.stringify({ prompt }),
+ },
+ );
+ if (!res.ok) throw new Error(await detail(res));
+}
diff --git a/jarvis/ui/web/frontend/src/store/events.ts b/jarvis/ui/web/frontend/src/store/events.ts
index 0ab0703b59..9adfd4f2b2 100644
--- a/jarvis/ui/web/frontend/src/store/events.ts
+++ b/jarvis/ui/web/frontend/src/store/events.ts
@@ -36,7 +36,8 @@ export type SectionId =
| "contacts"
| "feedback"
| "agent-instructions"
- | "dictionary";
+ | "dictionary"
+ | "agentic-ide";
export const SECTION_IDS = [
"chats",
@@ -65,6 +66,7 @@ export const SECTION_IDS = [
"feedback",
"agent-instructions",
"dictionary",
+ "agentic-ide",
] as const satisfies readonly SectionId[];
export function isSectionId(value: unknown): value is SectionId {
@@ -102,6 +104,7 @@ export const SECTION_LABELS: Record<SectionId, string> = {
feedback: "Feedback",
"agent-instructions": "Agent Instructions",
dictionary: "Dictionary",
+ "agentic-ide": "Agentic IDE",
};
export interface EventItem {
diff --git a/jarvis/ui/web/frontend/src/views/AgenticIdeView.test.tsx b/jarvis/ui/web/frontend/src/views/AgenticIdeView.test.tsx
new file mode 100644
index 0000000000..707345776b
--- /dev/null
+++ b/jarvis/ui/web/frontend/src/views/AgenticIdeView.test.tsx
@@ -0,0 +1,248 @@
+import { cleanup, fireEvent, render, screen, waitFor } from "@testing-library/react";
+import { afterEach, beforeEach, describe, expect, it, vi } from "vitest";
+
+// Identity translator so rendered text equals the i18n key.
+vi.mock("@/i18n", () => ({ useT: () => (key: string) => key }));
+
+const pushToast = vi.fn();
+const setActiveSection = vi.fn();
+vi.mock("@/store/events", () => ({
+ useEventStore: (selector: (s: Record<string, unknown>) => unknown) =>
+ selector({ pushToast, setActiveSection }),
+}));
+
+// Stub the heavy ChatsView import (only ViewHeader is needed).
+vi.mock("@/views/ChatsView", () => ({
+ ViewHeader: ({ title }: { title: string }) => <header>{title}</header>,
+}));
+
+// xterm.js needs a real canvas, which jsdom has not got — stub the panes.
+vi.mock("@/components/agentic/AgenticTerminal", () => ({
+ AgenticTerminal: ({ name }: { name: string }) => (
+ <div data-testid={`pane-${name}`}>{name}</div>
+ ),
+ PaneStatusPill: () => <span>live</span>,
+}));
+
+vi.mock("@/lib/agenticIdeApi", () => ({
+ fetchIdeState: vi.fn(),
+ fetchIdeAgents: vi.fn(),
+ fetchFolders: vi.fn(),
+ startIdeSession: vi.fn(),
+ endIdeSession: vi.fn(),
+ setFocusMode: vi.fn(),
+ promptTerminal: vi.fn(),
+}));
+
+import { AgenticIdeView } from "./AgenticIdeView";
+import * as api from "@/lib/agenticIdeApi";
+
+const AGENTS: api.AgentsResponse = {
+ terminal_available: true,
+ max_terminals: 12,
+ suggested_names: ["Mika", "Nova", "Aria", "Kai"],
+ agents: [
+ {
+ name: "claude",
+ display_name: "Claude Code",
+ installed: true,
+ version: "2.1.195",
+ install_command: "npm install -g @anthropic-ai/claude-code",
+ },
+ {
+ name: "codex",
+ display_name: "Codex",
+ installed: true,
+ version: "0.142.3",
+ install_command: "npm install -g @openai/codex",
+ },
+ ],
+};
+
+const EMPTY_STATE: api.IdeState = { active: false, session: null, max_terminals: 12 };
+
+function sessionWith(names: string[], focus = false): api.SessionState {
+ return {
+ id: "ide_test",
+ folder: "/work/project",
+ project: {
+ path: "/work/project",
+ name: "project",
+ exists: true,
+ is_repo: true,
+ branch: "main",
+ stacks: ["Python"],
+ instruction_files: ["CLAUDE.md"],
+ top_level_dirs: ["src"],
+ skills: [],
+ note: "",
+ },
+ created_at: 0,
+ focus_mode: focus,
+ terminals: names.map((name, index) => ({
+ key: name.toLowerCase(),
+ name,
+ agent: "claude",
+ display_name: "Claude Code",
+ index,
+ status: "live" as const,
+ exit_code: null,
+ error: "",
+ started_at: 0,
+ last_output_at: 0,
+ idle_seconds: 0,
+ prompts_sent: 0,
+ last_prompt: "",
+ lines_captured: 0,
+ })),
+ };
+}
+
+beforeEach(() => {
+ vi.mocked(api.fetchIdeAgents).mockResolvedValue(AGENTS);
+ vi.mocked(api.fetchIdeState).mockResolvedValue(EMPTY_STATE);
+ vi.mocked(api.fetchFolders).mockResolvedValue({
+ path: null,
+ parent: null,
+ entries: [
+ { name: "project", path: "/work/project", is_project: true, is_repo: true },
+ ],
+ });
+});
+
+afterEach(() => {
+ cleanup();
+ vi.clearAllMocks();
+});
+
+describe("Agentic IDE wizard", () => {
+ it("starts on the folder step and blocks Next until a folder is picked", async () => {
+ render(<AgenticIdeView />);
+ await waitFor(() => expect(api.fetchIdeAgents).toHaveBeenCalled());
+
+ const next = screen.getByRole("button", { name: /next/i }) as HTMLButtonElement;
+ expect(next.disabled).toBe(true);
+
+ fireEvent.click(await screen.findByRole("button", { name: /project/i }));
+ await waitFor(() => expect(next.disabled).toBe(false));
+ });
+
+ it("walks folder → count → agents → start and opens the workspace", async () => {
+ vi.mocked(api.startIdeSession).mockResolvedValue(sessionWith(["Mika", "Nova"]));
+ render(<AgenticIdeView />);
+ await waitFor(() => expect(api.fetchIdeAgents).toHaveBeenCalled());
+
+ fireEvent.click(await screen.findByRole("button", { name: /project/i }));
+ fireEvent.click(screen.getByRole("button", { name: /next/i }));
+
+ // Count step — pick 2 terminals.
+ fireEvent.click(screen.getByRole("button", { name: "2" }));
+ fireEvent.click(screen.getByRole("button", { name: /next/i }));
+
+ // Agent step — the call-signs are pre-filled from the suggested pool.
+ expect(screen.getByDisplayValue("Mika")).toBeTruthy();
+ expect(screen.getByDisplayValue("Nova")).toBeTruthy();
+ fireEvent.click(screen.getByRole("button", { name: /next/i }));
+
+ fireEvent.click(screen.getByRole("button", { name: /open workspace/i }));
+
+ await waitFor(() =>
+ expect(api.startIdeSession).toHaveBeenCalledWith("/work/project", [
+ { agent: "claude", name: "Mika" },
+ { agent: "claude", name: "Nova" },
+ ]),
+ );
+ // Panes are rendered once the session exists.
+ expect(await screen.findByTestId("pane-Mika")).toBeTruthy();
+ });
+
+ it("says so plainly when the machine has no terminal backend", async () => {
+ vi.mocked(api.fetchIdeAgents).mockResolvedValue({
+ ...AGENTS,
+ terminal_available: false,
+ });
+ render(<AgenticIdeView />);
+ expect(await screen.findByText(/no usable terminal backend/i)).toBeTruthy();
+ });
+
+ it("points at the CLIs page when no coding agent is installed", async () => {
+ vi.mocked(api.fetchIdeAgents).mockResolvedValue({
+ ...AGENTS,
+ agents: AGENTS.agents.map((a) => ({ ...a, installed: false })),
+ });
+ render(<AgenticIdeView />);
+ fireEvent.click(await screen.findByRole("button", { name: /open clis/i }));
+ expect(setActiveSection).toHaveBeenCalledWith("clis");
+ });
+});
+
+describe("Agentic IDE running workspace", () => {
+ it("renders the open session instead of the wizard", async () => {
+ vi.mocked(api.fetchIdeState).mockResolvedValue({
+ active: true,
+ session: sessionWith(["Mika"]),
+ max_terminals: 12,
+ });
+ render(<AgenticIdeView />);
+ expect(await screen.findByTestId("pane-Mika")).toBeTruthy();
+ expect(screen.queryByRole("button", { name: /next/i })).toBeNull();
+ });
+
+ it("toggles focus mode through the API, not just locally", async () => {
+ vi.mocked(api.fetchIdeState).mockResolvedValue({
+ active: true,
+ session: sessionWith(["Mika"]),
+ max_terminals: 12,
+ });
+ vi.mocked(api.setFocusMode).mockResolvedValue(true);
+ render(<AgenticIdeView />);
+
+ const toggle = await screen.findByTestId("agentic-focus-toggle");
+ expect(toggle.getAttribute("aria-pressed")).toBe("false");
+ fireEvent.click(toggle);
+
+ await waitFor(() => expect(api.setFocusMode).toHaveBeenCalledWith(true));
+ await waitFor(() => expect(toggle.getAttribute("aria-pressed")).toBe("true"));
+ });
+
+ it("sends a prompt to the selected terminal through the same endpoint voice uses", async () => {
+ vi.mocked(api.fetchIdeState).mockResolvedValue({
+ active: true,
+ session: sessionWith(["Mika", "Nova"]),
+ max_terminals: 12,
+ });
+ vi.mocked(api.promptTerminal).mockResolvedValue(undefined);
+ render(<AgenticIdeView />);
+
+ await screen.findByTestId("pane-Mika");
+ const box = screen.getByPlaceholderText(/type an instruction for mika/i);
+ fireEvent.change(box, { target: { value: "run the tests" } });
+ fireEvent.click(screen.getByRole("button", { name: /send/i }));
+
+ await waitFor(() =>
+ expect(api.promptTerminal).toHaveBeenCalledWith("Mika", "run the tests"),
+ );
+ });
+
+ it("reports a refused prompt instead of pretending it landed", async () => {
+ vi.mocked(api.fetchIdeState).mockResolvedValue({
+ active: true,
+ session: sessionWith(["Mika"]),
+ max_terminals: 12,
+ });
+ vi.mocked(api.promptTerminal).mockRejectedValue(
+ new Error("Mika is not running right now"),
+ );
+ render(<AgenticIdeView />);
+
+ await screen.findByTestId("pane-Mika");
+ fireEvent.change(screen.getByPlaceholderText(/type an instruction/i), {
+ target: { value: "hello" },
+ });
+ fireEvent.click(screen.getByRole("button", { name: /send/i }));
+
+ await waitFor(() =>
+ expect(pushToast).toHaveBeenCalledWith("error", "Mika is not running right now"),
+ );
+ });
+});
diff --git a/jarvis/ui/web/frontend/src/views/AgenticIdeView.tsx b/jarvis/ui/web/frontend/src/views/AgenticIdeView.tsx
new file mode 100644
index 0000000000..be5c5a312f
--- /dev/null
+++ b/jarvis/ui/web/frontend/src/views/AgenticIdeView.tsx
@@ -0,0 +1,526 @@
+/**
+ * Agentic IDE — the "code with Jarvis" section.
+ *
+ * Two states in one view:
+ *
+ * * no workspace open → a four-step wizard: folder, how many terminals, which
+ * agent + call-sign per terminal, then start,
+ * * workspace open → the terminal grid (see AgenticGrid).
+ *
+ * The wizard order is deliberate and matches how the decision actually gets
+ * made: you know the folder first, the number of panes second, and only then
+ * care which agent sits in which pane. Every step is reversible and nothing is
+ * started until the last one.
+ *
+ * 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 {
+ AlertCircle,
+ ArrowLeft,
+ ArrowRight,
+ Check,
+ Download,
+ FolderOpen,
+ Loader2,
+ Rocket,
+ Sparkles,
+ Terminal,
+} from "lucide-react";
+import { ViewHeader } from "@/views/ChatsView";
+import { useEventStore } from "@/store/events";
+import { cn } from "@/lib/utils";
+import { useT } from "@/i18n";
+import { AgenticGrid } from "@/components/agentic/AgenticGrid";
+import { FolderPicker } from "@/components/agentic/FolderPicker";
+import {
+ endIdeSession,
+ fetchIdeAgents,
+ fetchIdeState,
+ setFocusMode,
+ startIdeSession,
+ type AgentStatus,
+ type AgentsResponse,
+ type SessionState,
+} from "@/lib/agenticIdeApi";
+
+type Step = 0 | 1 | 2 | 3;
+
+interface PlannedTerminal {
+ agent: string;
+ name: string;
+}
+
+const COUNT_CHOICES = [1, 2, 3, 4, 6, 8] as const;
+
+/**
+ * Terminal plan for ``count`` panes, preserving whatever the user already chose
+ * for the panes that still exist.
+ *
+ * A pure function called from the click handlers on purpose. The first version
+ * of this was a `useEffect` that synchronised `planned` against `count` — and
+ * one of its dependencies was `meta?.suggested_names ?? []`, a fresh array on
+ * every render. Setting state from an effect whose dependency is recreated each
+ * render is an infinite loop; it froze the tab and only showed up because a test
+ * ran out of heap. Deriving on the event that actually changes the plan has no
+ * such failure mode.
+ */
+function buildPlan(
+ count: number,
+ previous: PlannedTerminal[],
+ agent: string,
+ names: string[],
+): PlannedTerminal[] {
+ return Array.from({ length: count }, (_, i) => {
+ const kept = previous[i];
+ if (kept) return kept;
+ return { agent, name: names[i] ?? `T${i + 1}` };
+ });
+}
+
+export function AgenticIdeView() {
+ const t = useT();
+ const pushToast = useEventStore((s) => s.pushToast);
+ const setActiveSection = useEventStore((s) => s.setActiveSection);
+
+ const [loading, setLoading] = useState(true);
+ const [meta, setMeta] = useState<AgentsResponse | null>(null);
+ const [session, setSession] = useState<SessionState | null>(null);
+ const [focusMode, setFocus] = useState(false);
+ const [busy, setBusy] = useState(false);
+
+ const [step, setStep] = useState<Step>(0);
+ const [folder, setFolder] = useState<string | null>(null);
+ const [count, setCount] = useState(2);
+ const [planned, setPlanned] = useState<PlannedTerminal[]>([]);
+
+ const refresh = useCallback(async () => {
+ try {
+ const [state, agents] = await Promise.all([fetchIdeState(), fetchIdeAgents()]);
+ setMeta(agents);
+ setSession(state.session);
+ setFocus(Boolean(state.session?.focus_mode));
+ } catch {
+ /* backend still warming or headless — keep whatever we had */
+ } finally {
+ setLoading(false);
+ }
+ }, []);
+
+ useEffect(() => {
+ void refresh();
+ }, [refresh]);
+
+ // 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]);
+ const suggested = useMemo(() => meta?.suggested_names ?? [], [meta]);
+ const installed = useMemo(() => agents.filter((a) => a.installed), [agents]);
+ const defaultAgent = installed[0]?.name ?? "claude";
+
+ const chooseCount = (n: number) => {
+ setCount(n);
+ setPlanned((prev) => buildPlan(n, prev, defaultAgent, suggested));
+ };
+
+ const goToStep = (next: Step) => {
+ // Entering the agent step is the moment the plan has to exist and the
+ // suggested call-signs have certainly arrived.
+ if (next === 2) {
+ setPlanned((prev) => buildPlan(count, prev, defaultAgent, suggested));
+ }
+ setStep(next);
+ };
+
+ const start = async () => {
+ if (!folder) return;
+ setBusy(true);
+ try {
+ const created = await startIdeSession(folder, planned);
+ setSession(created);
+ setFocus(created.focus_mode);
+ pushToast(
+ "success",
+ `Workspace open — ${created.terminals.map((x) => x.name).join(", ")}`,
+ );
+ } catch (e) {
+ pushToast("error", (e as Error).message);
+ } finally {
+ setBusy(false);
+ }
+ };
+
+ const close = async () => {
+ setBusy(true);
+ try {
+ await endIdeSession();
+ setSession(null);
+ setFocus(false);
+ setStep(0);
+ } catch (e) {
+ pushToast("error", (e as Error).message);
+ } finally {
+ setBusy(false);
+ }
+ };
+
+ const toggleFocus = async (enabled: boolean) => {
+ try {
+ setFocus(await setFocusMode(enabled));
+ } catch (e) {
+ pushToast("error", (e as Error).message);
+ }
+ };
+
+ // ------------------------------------------------------------ running mode
+ if (session) {
+ return (
+ <AgenticGrid
+ session={session}
+ focusMode={focusMode}
+ onToggleFocus={(v) => void toggleFocus(v)}
+ onClose={() => void close()}
+ busy={busy}
+ />
+ );
+ }
+
+ // ------------------------------------------------------------------ wizard
+ const canAdvance =
+ (step === 0 && Boolean(folder)) ||
+ (step === 1 && count > 0) ||
+ (step === 2 && planned.every((p) => p.name.trim() && p.agent));
+
+ return (
+ <div className="flex h-full flex-col">
+ <ViewHeader
+ icon={<Sparkles className="h-4 w-4 text-primary" />}
+ title={t("nav.agentic_ide") === "nav.agentic_ide" ? "Agentic IDE" : t("nav.agentic_ide")}
+ subtitle="Open a folder, run coding agents in named terminals, and talk to them."
+ />
+
+ <div className="flex-1 overflow-y-auto scrollbar-jarvis">
+ <div className="mx-auto flex w-full max-w-3xl flex-col gap-6 p-6">
+ <StepRail step={step} />
+
+ {loading && (
+ <div className="flex items-center gap-2 text-sm text-muted-foreground">
+ <Loader2 className="h-4 w-4 animate-spin" />
+ Checking this machine…
+ </div>
+ )}
+
+ {meta && !meta.terminal_available && (
+ <Callout tone="error">
+ This machine has no usable terminal backend, so agent panes cannot
+ run here. On Windows that means <code>pywinpty</code>, on macOS and
+ Linux <code>ptyprocess</code> — both ship with the desktop extra.
+ </Callout>
+ )}
+
+ {meta && installed.length === 0 && (
+ <Callout tone="warn">
+ Neither Claude Code nor Codex was found on this machine’s PATH.
+ Install one from the CLIs page, then come back — the wizard picks it
+ up automatically.
+ <button
+ type="button"
+ className="btn-ghost mt-2"
+ onClick={() => setActiveSection("clis")}
+ >
+ <Download className="h-4 w-4" />
+ Open CLIs
+ </button>
+ </Callout>
+ )}
+
+ {step === 0 && (
+ <Section
+ title="Which folder should the agents work in?"
+ hint="Pick the project root. Everything the agents do happens inside it."
+ >
+ <FolderPicker selected={folder} onSelect={setFolder} />
+ </Section>
+ )}
+
+ {step === 1 && (
+ <Section
+ title="How many terminals?"
+ hint="Each terminal runs its own agent, side by side in a grid."
+ >
+ <div className="grid grid-cols-3 gap-3 sm:grid-cols-6">
+ {COUNT_CHOICES.filter((n) => n <= (meta?.max_terminals ?? 12)).map((n) => (
+ <button
+ key={n}
+ type="button"
+ aria-pressed={count === n}
+ onClick={() => chooseCount(n)}
+ className={cn(
+ "flex aspect-square flex-col items-center justify-center gap-2 rounded-xl border p-3 transition-colors",
+ count === n
+ ? "border-primary/50 bg-primary/5"
+ : "border-border bg-card/60 hover:border-primary/30",
+ )}
+ >
+ <DotGrid n={n} active={count === n} />
+ <span
+ className={cn(
+ "text-sm font-semibold",
+ count === n ? "text-primary" : "text-foreground",
+ )}
+ >
+ {n}
+ </span>
+ </button>
+ ))}
+ </div>
+ </Section>
+ )}
+
+ {step === 2 && (
+ <Section
+ title="Who runs where?"
+ hint="Each terminal gets a call-sign so you can talk about it by name — “what is Mika doing?”."
+ >
+ <ul className="space-y-2">
+ {planned.map((pane, index) => (
+ <li
+ key={index}
+ className="flex flex-wrap items-center gap-3 rounded-xl border border-border bg-card/60 p-3"
+ >
+ <span className="w-6 shrink-0 text-center font-mono text-xs text-muted-foreground">
+ {index + 1}
+ </span>
+ <input
+ value={pane.name}
+ onChange={(e) =>
+ setPlanned((prev) =>
+ prev.map((p, i) =>
+ i === index ? { ...p, name: e.target.value } : p,
+ ),
+ )
+ }
+ aria-label={`Call-sign for terminal ${index + 1}`}
+ className="w-32 shrink-0 rounded-lg border border-border bg-background/60 px-3 py-1.5 text-sm outline-none focus:border-primary/50"
+ spellCheck={false}
+ />
+ <div className="flex flex-wrap items-center gap-2">
+ {agents.map((agent) => (
+ <AgentChoice
+ key={agent.name}
+ agent={agent}
+ selected={pane.agent === agent.name}
+ onSelect={() =>
+ setPlanned((prev) =>
+ prev.map((p, i) =>
+ i === index ? { ...p, agent: agent.name } : p,
+ ),
+ )
+ }
+ />
+ ))}
+ </div>
+ </li>
+ ))}
+ </ul>
+ </Section>
+ )}
+
+ {step === 3 && (
+ <Section title="Ready to open" hint="Nothing has started yet.">
+ <div className="space-y-4 rounded-xl border border-border bg-card/60 p-5">
+ <div className="flex items-center gap-2 text-sm">
+ <FolderOpen className="h-4 w-4 shrink-0 text-primary" />
+ <code className="min-w-0 truncate font-mono text-xs">{folder}</code>
+ </div>
+ <ul className="flex flex-wrap gap-2">
+ {planned.map((pane, i) => (
+ <li
+ key={i}
+ className="flex items-center gap-2 rounded-lg bg-primary/10 px-3 py-1.5 text-sm text-primary"
+ >
+ <Terminal className="h-3.5 w-3.5" />
+ <span className="font-medium">{pane.name}</span>
+ <span className="text-primary/70">
+ {agents.find((a) => a.name === pane.agent)?.display_name ?? pane.agent}
+ </span>
+ </li>
+ ))}
+ </ul>
+ <p className="text-xs text-muted-foreground">
+ Once the panes are up you can turn on coding mode, which lets
+ Jarvis answer inside this workspace — and switch it off again at
+ any time.
+ </p>
+ </div>
+ </Section>
+ )}
+
+ <div className="flex items-center justify-between pt-2">
+ <button
+ type="button"
+ className={cn("btn-ghost", step === 0 && "invisible")}
+ onClick={() => goToStep((step > 0 ? step - 1 : step) as Step)}
+ >
+ <ArrowLeft className="h-4 w-4" />
+ Back
+ </button>
+ {step < 3 ? (
+ <button
+ type="button"
+ className="btn-primary disabled:cursor-not-allowed disabled:opacity-40"
+ disabled={!canAdvance}
+ onClick={() => goToStep((step + 1) as Step)}
+ >
+ Next
+ <ArrowRight className="h-4 w-4" />
+ </button>
+ ) : (
+ <button
+ type="button"
+ className="btn-primary disabled:cursor-not-allowed disabled:opacity-40"
+ disabled={busy || !folder || planned.length === 0}
+ onClick={() => void start()}
+ >
+ {busy ? (
+ <Loader2 className="h-4 w-4 animate-spin" />
+ ) : (
+ <Rocket className="h-4 w-4" />
+ )}
+ {busy ? "Opening…" : "Open workspace"}
+ </button>
+ )}
+ </div>
+ </div>
+ </div>
+ </div>
+ );
+}
+
+function StepRail({ step }: { step: Step }) {
+ const labels = ["Folder", "Terminals", "Agents", "Start"];
+ return (
+ <ol className="flex items-center gap-2">
+ {labels.map((label, index) => (
+ <li key={label} className="flex flex-1 items-center gap-2">
+ <span
+ className={cn(
+ "flex h-6 w-6 shrink-0 items-center justify-center rounded-full text-[11px] font-semibold",
+ index < step
+ ? "bg-primary/20 text-primary"
+ : index === step
+ ? "bg-primary text-background"
+ : "bg-muted text-muted-foreground",
+ )}
+ >
+ {index < step ? <Check className="h-3.5 w-3.5" /> : index + 1}
+ </span>
+ <span
+ className={cn(
+ "truncate text-xs",
+ index === step ? "text-foreground" : "text-muted-foreground",
+ )}
+ >
+ {label}
+ </span>
+ {index < labels.length - 1 && (
+ <span className="hidden h-px flex-1 bg-border sm:block" />
+ )}
+ </li>
+ ))}
+ </ol>
+ );
+}
+
+function Section({
+ title,
+ hint,
+ children,
+}: {
+ title: string;
+ hint: string;
+ children: React.ReactNode;
+}) {
+ return (
+ <div className="space-y-4">
+ <div>
+ <h3 className="font-display text-lg font-semibold">{title}</h3>
+ <p className="text-sm text-muted-foreground">{hint}</p>
+ </div>
+ {children}
+ </div>
+ );
+}
+
+function AgentChoice({
+ agent,
+ selected,
+ onSelect,
+}: {
+ agent: AgentStatus;
+ selected: boolean;
+ onSelect: () => void;
+}) {
+ return (
+ <button
+ type="button"
+ onClick={onSelect}
+ disabled={!agent.installed}
+ aria-pressed={selected}
+ title={agent.installed ? agent.version ?? undefined : "Not installed on this machine"}
+ className={cn(
+ "flex items-center gap-2 rounded-lg border px-3 py-1.5 text-sm transition-colors",
+ selected
+ ? "border-primary/60 bg-primary/10 text-primary"
+ : "border-border text-muted-foreground hover:border-primary/40",
+ !agent.installed && "cursor-not-allowed opacity-40",
+ )}
+ >
+ <Terminal className="h-3.5 w-3.5" />
+ {agent.display_name}
+ </button>
+ );
+}
+
+function DotGrid({ n, active }: { n: number; active: boolean }) {
+ const cols = n <= 1 ? 1 : n <= 2 ? 2 : n <= 6 ? 3 : 4;
+ return (
+ <div
+ className="grid gap-1"
+ style={{ gridTemplateColumns: `repeat(${cols}, minmax(0, 1fr))` }}
+ >
+ {Array.from({ length: n }).map((_, i) => (
+ <span
+ key={i}
+ className={cn(
+ "h-2 w-2 rounded-[3px]",
+ active ? "bg-primary" : "bg-muted-foreground/40",
+ )}
+ />
+ ))}
+ </div>
+ );
+}
+
+function Callout({
+ tone,
+ children,
+}: {
+ tone: "error" | "warn";
+ children: React.ReactNode;
+}) {
+ return (
+ <div
+ className={cn(
+ "flex items-start gap-2 rounded-lg border px-4 py-3 text-sm",
+ tone === "error"
+ ? "border-destructive/40 bg-destructive/10 text-destructive"
+ : "border-amber-500/40 bg-amber-500/10 text-amber-200",
+ )}
+ >
+ <AlertCircle className="mt-0.5 h-4 w-4 shrink-0" />
+ <div className="flex flex-col items-start">{children}</div>
+ </div>
+ );
+}
diff --git a/jarvis/ui/web/server.py b/jarvis/ui/web/server.py
index 5de19dad0d..2a8b25373f 100644
--- a/jarvis/ui/web/server.py
+++ b/jarvis/ui/web/server.py
@@ -337,6 +337,7 @@ class WebServer:
from .wiki_ws import router as wiki_ws_router
from .workflows_routes import router as workflows_router
from .workspace_routes import router as workspace_router
+ from .agentic_ide_routes import router as agentic_ide_router
# Conductor is an external package in the same monorepo. Import
# defensively — anyone who checks out the repo without conductor would
# otherwise get an ImportError here at server boot.
@@ -406,6 +407,12 @@ class WebServer:
# Provides agent detection, workspace launch planning, and PTY WebSocket
# for in-app Claude Code / Codex terminals (xterm panes, not OS windows).
app.include_router(workspace_router)
+ # Agentic IDE (/api/agentic-ide/*) — a chosen folder plus named terminals
+ # running Claude Code / Codex, addressable by voice ("what is Mika
+ # doing?") and promptable from Jarvis. Reuses the same PTY stack as the
+ # workspace above; adds the folder picker, call-signs, transcripts, and
+ # the focused coding mode.
+ app.include_router(agentic_ide_router)
# Contacts section — user-curated address book (pure file store, no Brain dep).
app.include_router(contacts_router)
app.include_router(dictionary_router)
diff --git a/tests/fakes/fake_pty_manager.py b/tests/fakes/fake_pty_manager.py
new file mode 100644
index 0000000000..eca0f98b42
--- /dev/null
+++ b/tests/fakes/fake_pty_manager.py
@@ -0,0 +1,95 @@
+"""In-memory stand-in for ``jarvis.terminal.pty_manager.PtyManager``.
+
+Lets the Agentic-IDE registry be driven end to end without a real
+pseudo-terminal and without Claude Code / Codex installed — which is what makes
+the session tests runnable on CI and on a headless Linux box.
+
+It records every write, so a test can assert exactly what would have been typed
+into an agent (the injection contract) instead of asserting on a mock's call
+signature.
+"""
+from __future__ import annotations
+
+from dataclasses import dataclass, field
+from typing import Any
+
+
+@dataclass(slots=True)
+class FakePtySession:
+ terminal_id: str
+ shell_id: str
+ pid: int = 4242
+
+
+@dataclass(slots=True)
+class FakePtyManager:
+ """Mirrors the five methods the registry calls on the real manager."""
+
+ spawns: list[dict[str, Any]] = field(default_factory=list)
+ writes: list[tuple[str, str]] = field(default_factory=list)
+ resizes: list[tuple[str, int, int]] = field(default_factory=list)
+ closed: list[str] = field(default_factory=list)
+ # Set to make spawn fail the way a missing PTY backend would.
+ spawn_error: str | None = None
+ _live: set[str] = field(default_factory=set)
+ _counter: int = 0
+
+ async def spawn(
+ self,
+ shell_argv: tuple[str, ...],
+ shell_id: str,
+ cwd: str | None,
+ cols: int,
+ rows: int,
+ on_output: Any,
+ on_closed: Any,
+ ) -> FakePtySession:
+ if self.spawn_error:
+ raise RuntimeError(self.spawn_error)
+ self._counter += 1
+ terminal_id = f"fake-pty-{self._counter}"
+ self.spawns.append(
+ {
+ "argv": tuple(shell_argv),
+ "shell_id": shell_id,
+ "cwd": cwd,
+ "cols": cols,
+ "rows": rows,
+ "on_output": on_output,
+ "on_closed": on_closed,
+ }
+ )
+ self._live.add(terminal_id)
+ return FakePtySession(terminal_id=terminal_id, shell_id=shell_id)
+
+ def write(self, terminal_id: str, data: str) -> bool:
+ if terminal_id not in self._live:
+ return False
+ self.writes.append((terminal_id, data))
+ return True
+
+ def resize(self, terminal_id: str, cols: int, rows: int) -> bool:
+ if terminal_id not in self._live:
+ return False
+ self.resizes.append((terminal_id, cols, rows))
+ return True
+
+ def close(self, terminal_id: str) -> bool:
+ self.closed.append(terminal_id)
+ return self._live.discard(terminal_id) is None and True
+
+ def has(self, terminal_id: str) -> bool:
+ return terminal_id in self._live
+
+ def close_all(self) -> None:
+ for terminal_id in list(self._live):
+ self.close(terminal_id)
+
+ # ---- test helpers -------------------------------------------------
+ @property
+ def typed(self) -> list[str]:
+ """Everything written, in order (handy for asserting one prompt)."""
+ return [data for _tid, data in self.writes]
+
+
+__all__ = ["FakePtyManager", "FakePtySession"]
diff --git a/tests/unit/agentic_ide/__init__.py b/tests/unit/agentic_ide/__init__.py
new file mode 100644
index 0000000000..e69de29bb2
diff --git a/tests/unit/agentic_ide/test_context.py b/tests/unit/agentic_ide/test_context.py
new file mode 100644
index 0000000000..1de3d73e95
--- /dev/null
+++ b/tests/unit/agentic_ide/test_context.py
@@ -0,0 +1,97 @@
+"""The focus-mode context block — what Jarvis actually knows while coding mode
+is on, and (just as important) that it knows nothing when the mode is off.
+
+The "off" cases are the guard against a feature that quietly widens every prompt
+for users who never open the IDE.
+"""
+from __future__ import annotations
+
+from pathlib import Path
+
+import pytest
+
+from jarvis.agentic_ide import session as session_mod
+from jarvis.agentic_ide.context import focus_context_block
+from jarvis.agentic_ide.session import Registry, reset_registry
+from tests.fakes.fake_pty_manager import FakePtyManager
+
+
[email protected](autouse=True)
+def clean_registry():
+ reset_registry()
+ yield
+ reset_registry()
+
+
+def wired(monkeypatch: pytest.MonkeyPatch) -> tuple[Registry, FakePtyManager]:
+ fake = FakePtyManager()
+ registry = Registry(pty_manager=fake)
+ monkeypatch.setattr(session_mod, "agent_argv", lambda name: (f"/usr/bin/{name}",))
+ # context.focus_context_block resolves get_registry from the session module
+ # at call time, so patching it there is enough.
+ monkeypatch.setattr(session_mod, "get_registry", lambda: registry)
+ return registry, fake
+
+
+def test_no_session_means_no_block() -> None:
+ assert focus_context_block() == ""
+
+
+async def test_session_without_focus_mode_means_no_block(
+ wired: tuple[Registry, FakePtyManager], tmp_path: Path
+) -> None:
+ registry, _ = wired
+ await registry.start(str(tmp_path), [{"agent": "claude"}])
+ assert focus_context_block() == ""
+
+
+async def test_focus_mode_block_names_the_folder_and_terminals(
+ wired: tuple[Registry, FakePtyManager], tmp_path: Path
+) -> None:
+ registry, fake = wired
+ await registry.start(str(tmp_path), [{"agent": "claude"}, {"agent": "codex"}])
+ registry.set_focus_mode(True)
+ await registry.attach("Mika", 80, 24, _noop, _noop_exit)
+ on_output = fake.spawns[-1]["on_output"]
+ await on_output("pty", "refactoring the router\r\n")
+
+ block = focus_context_block()
+ assert "AGENTIC IDE" in block
+ assert str(tmp_path) in block
+ assert "Mika (Claude Code)" in block
+ assert "Nova (Codex)" in block
+ assert "refactoring the router" in block
+
+
+async def test_block_is_capped(
+ wired: tuple[Registry, FakePtyManager], tmp_path: Path
+) -> None:
+ registry, fake = wired
+ await registry.start(str(tmp_path), [{"agent": "claude"}])
+ registry.set_focus_mode(True)
+ await registry.attach("Mika", 80, 24, _noop, _noop_exit)
+ on_output = fake.spawns[-1]["on_output"]
+ for i in range(500):
+ await on_output("pty", f"line number {i} with a fair amount of text\r\n")
+ assert len(focus_context_block(max_chars=800)) <= 800
+
+
+async def test_turning_focus_off_removes_the_block_again(
+ wired: tuple[Registry, FakePtyManager], tmp_path: Path
+) -> None:
+ """Switching back must be complete — no residue in the next turn."""
+ registry, _ = wired
+ await registry.start(str(tmp_path), [{"agent": "claude"}])
+ registry.set_focus_mode(True)
+ assert focus_context_block() != ""
+ registry.set_focus_mode(False)
+ assert focus_context_block() == ""
+
+
+async def _noop(_text: str) -> None:
+ return None
+
+
+async def _noop_exit(_code: int) -> None:
+ return None
diff --git a/tests/unit/agentic_ide/test_names.py b/tests/unit/agentic_ide/test_names.py
new file mode 100644
index 0000000000..ce1a6ed9c7
--- /dev/null
+++ b/tests/unit/agentic_ide/test_names.py
@@ -0,0 +1,58 @@
+"""Terminal call-signs and spoken-name resolution.
+
+The resolver is what lets "what is Mika doing?" reach the right pane through an
+imperfect transcript. It has to be forgiving of garble and firm about unrelated
+words — a spoken sentence must not silently address a random terminal.
+"""
+from __future__ import annotations
+
+import pytest
+
+from jarvis.agentic_ide.names import NAME_POOL, default_names, normalize, resolve
+
+
+def test_default_names_are_stable_and_ordered() -> None:
+ assert default_names(3) == list(NAME_POOL[:3])
+ assert default_names(0) == []
+
+
+def test_default_names_extend_past_the_pool_deterministically() -> None:
+ many = default_names(len(NAME_POOL) + 3)
+ assert len(many) == len(NAME_POOL) + 3
+ assert len(set(many)) == len(many), "extended names must stay unique"
+
+
+def test_exact_and_case_insensitive_match() -> None:
+ assert resolve("Mika", ["Mika", "Nova"]) == "Mika"
+ assert resolve("mika", ["Mika", "Nova"]) == "Mika"
+
+
[email protected]("spoken", ["Micah", "Meeka", "Mikka"])
+def test_garbled_transcript_still_resolves(spoken: str) -> None:
+ """Speech recognition rarely spells a proper noun the way we wrote it."""
+ assert resolve(spoken, ["Mika", "Nova"]) == "Mika"
+
+
+def test_name_embedded_in_a_sentence_is_found() -> None:
+ assert resolve("what is mika up to right now", ["Mika", "Nova"]) == "Mika"
+ # A German utterance is the point of this case: the resolver has to find a
+ # call-sign inside whatever language the user speaks, so the sentence around
+ # the name is speech-recognition input vocabulary, not prose.
+ assert resolve( # i18n-allow: spoken input vocabulary under test
+ "sag nova sie soll die tests laufen lassen", ["Mika", "Nova"]
+ ) == "Nova"
+
+
+def test_unrelated_words_resolve_to_nothing() -> None:
+ """Room speech must not address a terminal by accident."""
+ assert resolve("open the wiki please", ["Mika", "Nova"]) is None
+ assert resolve("show me the marketing folder", ["Mika", "Nova"]) is None
+
+
+def test_empty_inputs_are_safe() -> None:
+ assert resolve("", ["Mika"]) is None
+ assert resolve("Mika", []) is None
+
+
+def test_normalize_strips_case_and_punctuation() -> None:
+ assert normalize(" Mika! ") == "mika"
diff --git a/tests/unit/agentic_ide/test_session.py b/tests/unit/agentic_ide/test_session.py
new file mode 100644
index 0000000000..9f13e64c93
--- /dev/null
+++ b/tests/unit/agentic_ide/test_session.py
@@ -0,0 +1,243 @@
+"""Agentic-IDE session registry: lifecycle, prompt injection, and its limits.
+
+The injection tests are the important ones. The prompt endpoint is a keystroke
+channel into a running process that voice can reach, so the contract "text plus
+Enter, never a control character" has to be pinned — otherwise a spoken sentence
+could interrupt, kill, or drive the keyboard shortcuts of a coding agent.
+"""
+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 Registry, SessionError, sanitize_prompt
+from tests.fakes.fake_pty_manager import FakePtyManager
+
+
+def fake_pty() -> FakePtyManager:
+ return FakePtyManager()
+
+
+def registry(fake_pty: FakePtyManager, monkeypatch: pytest.MonkeyPatch) -> Registry:
+ # Pretend both agents are installed, so the tests do not depend on the
+ # machine that runs them (a CI box has neither CLI).
+ 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, panes: list[dict]) -> object:
+ return await registry.start(str(folder), panes)
+
+
+# --------------------------------------------------------------- sanitizing
+def test_control_characters_cannot_be_injected() -> None:
+ """Ctrl-C, ESC and EOF must never reach the agent."""
+ dirty = "run the tests\x03\x04\x1b[Anow"
+ clean = sanitize_prompt(dirty)
+ assert "\x03" not in clean and "\x04" not in clean and "\x1b" not in clean
+ # The escape SEQUENCE goes whole — no stray "[A" left behind as text.
+ assert "[A" not in clean
+ assert clean == "run the testsnow"
+
+
+def test_newlines_collapse_so_one_prompt_is_one_submission() -> None:
+ assert sanitize_prompt("first line\nsecond line") == "first line second line"
+
+
+def test_prompt_is_length_capped() -> None:
+ assert len(sanitize_prompt("x" * 10_000)) == session_mod.MAX_PROMPT_CHARS
+
+
+# ----------------------------------------------------------------- lifecycle
+async def test_start_creates_named_terminals(registry: Registry, tmp_path: Path) -> None:
+ session = await _open(
+ registry, tmp_path, [{"agent": "claude"}, {"agent": "codex"}]
+ )
+ assert [t.name for t in session.terminals] == ["Mika", "Nova"]
+ assert [t.agent for t in session.terminals] == ["claude", "codex"]
+ assert session.folder == str(tmp_path)
+
+
+async def test_custom_names_are_kept_and_deduplicated(
+ registry: Registry, tmp_path: Path
+) -> None:
+ session = await _open(
+ registry,
+ tmp_path,
+ [{"agent": "claude", "name": "Ada"}, {"agent": "claude", "name": "Ada"}],
+ )
+ assert [t.name for t in session.terminals] == ["Ada", "Ada 2"]
+
+
+async def test_start_rejects_a_missing_folder(registry: Registry, tmp_path: Path) -> None:
+ with pytest.raises(SessionError, match="Not a folder"):
+ await registry.start(str(tmp_path / "nope"), [{"agent": "claude"}])
+
+
+async def test_start_rejects_an_unknown_agent(registry: Registry, tmp_path: Path) -> None:
+ with pytest.raises(SessionError, match="Unknown agent"):
+ await _open(registry, tmp_path, [{"agent": "emacs"}])
+
+
+async def test_start_refuses_more_than_the_maximum(
+ registry: Registry, tmp_path: Path
+) -> None:
+ panes = [{"agent": "claude"}] * (session_mod.MAX_TERMINALS + 1)
+ with pytest.raises(SessionError, match="At most"):
+ await _open(registry, tmp_path, panes)
+
+
+async def test_missing_agent_binary_is_reported_in_plain_language(
+ fake_pty: FakePtyManager, tmp_path: Path, monkeypatch: pytest.MonkeyPatch
+) -> None:
+ monkeypatch.setattr(session_mod, "agent_argv", lambda name: None)
+ registry = Registry(pty_manager=fake_pty)
+ with pytest.raises(SessionError, match="not installed"):
+ await registry.start(str(tmp_path), [{"agent": "claude"}])
+
+
+async def test_starting_again_closes_the_previous_session(
+ registry: Registry, fake_pty: FakePtyManager, tmp_path: Path
+) -> None:
+ await _open(registry, tmp_path, [{"agent": "claude"}])
+ await registry.attach("Mika", 80, 24, _noop_output, _noop_exit)
+ live_id = registry.session.terminals[0].pty_id
+ await _open(registry, tmp_path, [{"agent": "codex"}])
+ assert live_id in fake_pty.closed, "the old PTY must not survive a restart"
+
+
+# --------------------------------------------------------------------- attach
+async def _noop_output(_text: str) -> None:
+ return None
+
+
+async def _noop_exit(_code: int) -> None:
+ return None
+
+
+async def test_attach_spawns_the_agent_in_the_chosen_folder(
+ registry: Registry, fake_pty: FakePtyManager, tmp_path: Path
+) -> None:
+ await _open(registry, tmp_path, [{"agent": "claude"}])
+ term = await registry.attach("Mika", 100, 30, _noop_output, _noop_exit)
+ assert term.status == "live"
+ spawn = fake_pty.spawns[-1]
+ assert spawn["cwd"] == str(tmp_path)
+ assert spawn["cols"] == 100 and spawn["rows"] == 30
+
+
+async def test_attach_feeds_the_transcript(
+ registry: Registry, fake_pty: FakePtyManager, tmp_path: Path
+) -> None:
+ await _open(registry, tmp_path, [{"agent": "claude"}])
+ await registry.attach("Mika", 80, 24, _noop_output, _noop_exit)
+ on_output = fake_pty.spawns[-1]["on_output"]
+ await on_output("pty-id", "\x1b[32mediting main.py\x1b[0m\r\n")
+ assert registry.report("Mika")["transcript"] == ["editing main.py"]
+
+
+async def test_attach_by_spoken_phrase(registry: Registry, tmp_path: Path) -> None:
+ await _open(registry, tmp_path, [{"agent": "claude"}])
+ term = await registry.attach("mika", 80, 24, _noop_output, _noop_exit)
+ assert term.name == "Mika"
+
+
+# --------------------------------------------------------------------- prompt
+async def test_prompt_types_text_then_enter_separately(
+ registry: Registry, fake_pty: FakePtyManager, tmp_path: Path
+) -> None:
+ """Text and Enter go as two writes: agent TUIs debounce a single burst as a
+ paste and insert a line break instead of submitting."""
+ await _open(registry, tmp_path, [{"agent": "claude"}])
+ await registry.attach("Mika", 80, 24, _noop_output, _noop_exit)
+ await registry.send_prompt("Mika", "run the tests")
+ assert fake_pty.typed == ["run the tests", "\r"]
+
+
+async def test_prompt_counts_and_remembers_the_last_one(
+ registry: Registry, tmp_path: Path
+) -> None:
+ await _open(registry, tmp_path, [{"agent": "claude"}])
+ await registry.attach("Mika", 80, 24, _noop_output, _noop_exit)
+ await registry.send_prompt("what is mika doing", "status please")
+ term = registry.session.terminals[0]
+ assert term.prompts_sent == 1
+ assert term.last_prompt == "status please"
+
+
+async def test_prompt_to_an_unknown_terminal_names_the_real_ones(
+ registry: Registry, tmp_path: Path
+) -> None:
+ await _open(registry, tmp_path, [{"agent": "claude"}])
+ with pytest.raises(SessionError, match="Mika"):
+ await registry.send_prompt("Gandalf", "hello")
+
+
+async def test_prompt_is_refused_when_the_agent_is_not_running(
+ registry: Registry, tmp_path: Path
+) -> None:
+ """The pane never falls back to a shell, so a dead agent means the prompt is
+ refused rather than typed into something else."""
+ await _open(registry, tmp_path, [{"agent": "claude"}])
+ with pytest.raises(SessionError, match="not running"):
+ await registry.send_prompt("Mika", "run the tests")
+
+
+async def test_prompt_that_sanitizes_to_nothing_is_refused(
+ registry: Registry, tmp_path: Path
+) -> None:
+ await _open(registry, tmp_path, [{"agent": "claude"}])
+ await registry.attach("Mika", 80, 24, _noop_output, _noop_exit)
+ with pytest.raises(SessionError, match="empty"):
+ await registry.send_prompt("Mika", "\x03\x1b")
+
+
+async def test_prompt_without_a_session_is_refused(registry: Registry) -> None:
+ with pytest.raises(SessionError, match="No Agentic-IDE session"):
+ await registry.send_prompt("Mika", "hello")
+
+
+# ----------------------------------------------------------------- focus mode
+async def test_focus_mode_toggles(registry: Registry, tmp_path: Path) -> None:
+ await _open(registry, tmp_path, [{"agent": "claude"}])
+ assert registry.set_focus_mode(True) is True
+ assert registry.session.focus_mode is True
+ assert registry.set_focus_mode(False) is False
+
+
+def test_focus_mode_cannot_be_turned_on_without_a_workspace(
+ registry: Registry,
+) -> None:
+ with pytest.raises(SessionError, match="No Agentic-IDE session"):
+ registry.set_focus_mode(True)
+ # Turning it OFF with nothing open is a harmless no-op, not an error.
+ assert registry.set_focus_mode(False) is False
+
+
+async def test_end_closes_every_pty(
+ registry: Registry, fake_pty: FakePtyManager, tmp_path: Path
+) -> None:
+ await _open(registry, tmp_path, [{"agent": "claude"}, {"agent": "codex"}])
+ await registry.attach("Mika", 80, 24, _noop_output, _noop_exit)
+ await registry.attach("Nova", 80, 24, _noop_output, _noop_exit)
+ assert await registry.end() is True
+ assert len(fake_pty.closed) == 2
+ assert registry.session is None
+ assert await registry.end() is False
+
+
+# --------------------------------------------------------------------- report
+async def test_report_includes_status_and_folder(
+ registry: Registry, tmp_path: Path
+) -> None:
+ await _open(registry, tmp_path, [{"agent": "claude"}])
+ data = registry.report("Mika")
+ assert data["name"] == "Mika"
+ assert data["folder"] == str(tmp_path)
+ assert data["status"] == "pending"
diff --git a/tests/unit/agentic_ide/test_transcript.py b/tests/unit/agentic_ide/test_transcript.py
new file mode 100644
index 0000000000..7ec6ef9bba
--- /dev/null
+++ b/tests/unit/agentic_ide/test_transcript.py
@@ -0,0 +1,121 @@
+"""Transcript: turning a PTY stream into something a model can be asked about.
+
+The transcript replays the stream onto a terminal screen and reads the rows off
+it. Each test pins one property the Agentic IDE depends on — without them, "what
+is Mika doing?" gets answered from control codes and repainted frames.
+"""
+from __future__ import annotations
+
+from jarvis.agentic_ide.transcript import Transcript, is_noise, strip_ansi
+
+
+def test_strip_ansi_removes_colour_and_cursor_sequences() -> None:
+ coloured = "\x1b[32mgreen\x1b[0m and \x1b[1;31mred\x1b[0m"
+ assert strip_ansi(coloured) == "green and red"
+
+
+def test_strip_ansi_removes_osc_window_title() -> None:
+ assert strip_ansi("\x1b]0;a title\x07text") == "text"
+
+
+def test_colour_codes_do_not_reach_the_transcript() -> None:
+ t = Transcript()
+ t.feed("\x1b[32mtests passed\x1b[0m\r\n")
+ assert t.tail() == ["tests passed"]
+
+
+def test_carriage_return_overwrites_in_place() -> None:
+ """A progress bar leaves one row behind, not one per repaint."""
+ t = Transcript()
+ t.feed("build 10%\rbuild 50%\rbuild 100%\r\n")
+ assert t.tail() == ["build 100%"]
+
+
+def test_absolute_cursor_positioning_is_honoured() -> None:
+ """The core reason a plain filter fails: a TUI writes rows out of order."""
+ t = Transcript()
+ # Paint row 3 first, then jump back up to row 1.
+ t.feed("\x1b[3;1Hthird line\x1b[1;1Hfirst line")
+ assert t.tail() == ["first line", "third line"]
+
+
+def test_erase_line_removes_stale_content() -> None:
+ """A repainted row must not leave the longer previous text behind."""
+ t = Transcript()
+ t.feed("Thinking about a very long thing\r\x1b[KDone")
+ assert t.tail() == ["Done"]
+
+
+def test_erase_display_keeps_the_erased_rows_as_history() -> None:
+ """A TUI that clears the screen has not undone what already happened."""
+ t = Transcript()
+ t.feed("step one complete\r\n")
+ t.feed("\x1b[2J\x1b[H")
+ t.feed("step two starting\r\n")
+ assert t.tail() == ["step one complete", "step two starting"]
+
+
+def test_repeated_identical_rows_are_folded() -> None:
+ t = Transcript()
+ t.feed("thinking\r\nthinking\r\nthinking\r\ndone\r\n")
+ assert t.tail() == ["thinking", "done"]
+
+
+def test_decoration_only_rows_are_dropped() -> None:
+ t = Transcript()
+ t.feed("╭──────────╮\r\nreal content\r\n╰──────────╯\r\n")
+ assert t.tail() == ["real content"]
+
+
+def test_spinner_frames_are_dropped_but_activity_is_still_visible() -> None:
+ """Byte volume survives the filter, so "is it doing anything?" stays
+ answerable for an agent that only animates a spinner."""
+ t = Transcript()
+ t.feed("\x1b[2m⠋\x1b[0m\r\x1b[2m⠙\x1b[0m\r\x1b[2m⠹\x1b[0m\r")
+ assert t.tail() == []
+ assert t.raw_chars > 0
+
+
+def test_the_current_row_is_visible_before_its_newline() -> None:
+ """An agent waiting at a prompt has written no newline yet — that row is
+ usually the most current signal there is."""
+ t = Transcript()
+ t.feed("Do you want to proceed? (y/n) ")
+ assert t.tail() == ["Do you want to proceed? (y/n)"]
+
+
+def test_escape_sequence_split_across_two_reads() -> None:
+ """A PTY read can end in the middle of an escape sequence."""
+ t = Transcript()
+ t.feed("first\r\n\x1b[3")
+ t.feed(";1Hthird\r\n")
+ assert t.tail() == ["first", "third"]
+
+
+def test_output_beyond_the_screen_scrolls_into_history() -> None:
+ t = Transcript(cols=40, rows=6)
+ for i in range(20):
+ t.feed(f"line {i}\r\n")
+ tail = t.tail(5)
+ assert tail == ["line 15", "line 16", "line 17", "line 18", "line 19"]
+
+
+def test_history_is_bounded() -> None:
+ t = Transcript(cols=40, rows=6, max_lines=25)
+ for i in range(500):
+ t.feed(f"line {i}\r\n")
+ assert len(t.lines()) <= 31 # scrollback cap + the visible rows
+
+
+def test_resize_reflows_without_losing_content() -> None:
+ t = Transcript(cols=40, rows=10)
+ t.feed("hello from the agent\r\n")
+ t.resize(100, 30)
+ assert "hello from the agent" in t.lines()
+
+
+def test_is_noise_classifies_blank_and_decoration() -> None:
+ assert is_noise("")
+ assert is_noise(" ")
+ assert is_noise("────────")
+ assert not is_noise("Running tests…")