Dodaios is an open-source agent OS for your desktop: it runs your coding agents, browser and apps by voice or chat, on your own machine. Formerly Personal Jarvis.
Python agent-orchestrationai-agentai-coding-assistantclaude-codecoding-agentcomputer-usedesktop-applocal-firstmcppersonal-jarvisvoice-assistantvoice-coding
feat!: retire the assistant modes — one persona, no shelf of characters
rubenluetke10-beep5fd860ca623c
diff --git a/docs/adr/0011-router-pure-dispatcher.md b/docs/adr/0011-router-pure-dispatcher.mdindex 6954016b62..04894318b8 100644--- a/docs/adr/0011-router-pure-dispatcher.md+++ b/docs/adr/0011-router-pure-dispatcher.md@@ -1096,6 +1096,18 @@ the process.- `tests/integration/test_modes_routes.py`- `tests/unit/brain/test_routing.py` (ROUTER_TOOLS exact set)+### Retired (2026-08-23)++The assistant-modes feature was removed on the maintainer's decision: the+shelf of characters, `jarvis/brain/modes.py`, the `/api/modes` routes, the+`jarvis modes` CLI group, the Modes section and the three router tools above+are gone, and `ROUTER_TOOLS` no longer lists them. `load_effective_persona_prompt`+is back to "custom override, else default" with no mode layer, and the Agentic+IDE's focused coding mode no longer swaps the persona's character — it still+adds the workspace facts to the prompt and gates spawns as before. This+section stays as history; the reasoning above is what to re-read if a+character layer is ever wanted again.+## Amendment: `create-skill` router tool (2026-08-18)`create-skill` joins `ROUTER_TOOLS`: the brain can now WRITE a new skill fromdiff --git a/docs/architecture-overview.md b/docs/architecture-overview.mdindex 4ac781fc49..09db325fbe 100644--- a/docs/architecture-overview.md+++ b/docs/architecture-overview.md@@ -120,8 +120,6 @@ Ack-Brain (`jarvis/brain/ack_brain/`) emits a sub-second butler-style preamble b**Persona / custom system prompt:** the live persona comes from `jarvis/brain/persona_loader.py`. `base_persona_prompt()` returns an editable override (`data/custom_system_prompt.md`, written atomically via the Settings UI / `settings_routes.py`) when present, else the packaged `JARVIS_PERSONA.md`. `load_effective_persona_prompt()` is what the brains call: the base **plus the active mode's character block**. Edits apply on the **next turn** (no restart); `invalidate_cache()` clears the in-process cache. Never hardcode the persona string elsewhere.-**Assistant modes (`jarvis/brain/modes.py`):** the character the assistant answers in — five built-ins (`jarvis/brain/modes/*.md`, packaged) plus the user's own under `DATA_DIR/modes/`. A mode is **layered onto** the base persona, never substituted for it, so no mode can drop the standing honesty rules; the default `assistant` mode contributes an empty block, making the feature invisible until it is used. Because `load_effective_persona_prompt()` is the single chokepoint both the typing brain (`BrainManager._build_system_prompt`) and the speaking brain (`jarvis/realtime/session.py`) read fresh each turn, one switch reaches voice and chat together with no restart. Which mode is active has two layers: `[persona] active_mode` in `jarvis.toml` (the user's sticky choice, written only via `config_writer.set_active_mode`) and an **in-memory section override** the Agentic IDE sets while it is on screen — never persisted, so a mode a screen turned on cannot outlive the process. Surfaces: `/api/modes`, `jarvis modes …`, the Modes section, and the `list_modes` / `switch_mode` / `save_mode` router tools (ADR-0011 amendment "Assistant-Mode Tools").-### Risk-Tier systemFour levels: `safe` / `monitor` / `ask` / `block`. Priority is **blacklist > whitelist > tool default** (`jarvis/safety/risk_tier.py`). Whitelist downgrades a tier to `safe` with `approved_by="whitelist"` — this is the anti-confirmation-fatigue contract. **Direct calls to `Tool.execute()` are a bug**; only `ToolExecutor.execute()` is authorized.diff --git a/docs/jarvis-cli-reference.md b/docs/jarvis-cli-reference.mdindex 832e4d27d1..ed93d49067 100644--- a/docs/jarvis-cli-reference.md+++ b/docs/jarvis-cli-reference.md@@ -137,15 +137,6 @@ _Generated from the curated command tree by `scripts/ci/gen_cli_reference.py`- `jarvis missions show <mission_id>` — Show one mission with its events + verdicts.- `jarvis missions tool-approvals <mission_id>` — List supervisor tool calls waiting for approval in a mission.-## modes--- `jarvis modes create <name> --character --slug --emoji --description --voice --verbosity --proactivity` — Create or replace a mode. Does NOT switch to it — use `modes use` for that.-- `jarvis modes delete <slug>` — Delete a mode you created. Built-ins are refused; a copy of one is not.-- `jarvis modes list` — List every mode and show which one is active.-- `jarvis modes restore <slug>` — Throw away your edits to a built-in mode and bring the shipped one back.-- `jarvis modes show <slug>` — Show one mode in full, including its character text.-- `jarvis modes use <slug>` — Switch the active mode. Applies on the next turn — no restart.-## outputs- `jarvis outputs files <slug>` — List the artifacts a mission produced.diff --git a/jarvis/agentic_ide/session.py b/jarvis/agentic_ide/session.pyindex 64208556a9..02acb96f8c 100644--- a/jarvis/agentic_ide/session.py+++ b/jarvis/agentic_ide/session.py@@ -1906,10 +1906,6 @@ class Registry:"""Bring ``session`` to the front. Caller holds the lock."""self._active = session.idsession.last_active_at = time.time()- # A different workspace at the front can mean a different answer to- # "is coding mode on" — the flag is per workspace — so the persona- # follows the front, not only the toggle.- self._sync_coding_character()async def _open_locked(self,@@ -2230,9 +2226,6 @@ class Registry:async with self._lock:if workspace_id is None:self._active = None- # No workspace on screen is no coding mode, whatever the flags- # on the workspaces behind the wizard say.- self._sync_coding_character()return Nonesession = self._sessions.get(workspace_id)if session is None:@@ -2441,12 +2434,6 @@ class Registry:self._active = survivor.id if survivor else Noneif survivor is not None:self._focus_locked(survivor)- else:- # The last workspace is gone; the coding character must go- # with it. This is the second life of the bug this override was- # built against — coding mode stuck on for the whole session- # after the workspace it belonged to had been closed.- self._sync_coding_character()# Deliberately NOT re-written here. The restore point is refreshed by# activity — opening a workspace, adding a pane, connecting one — and# closing is not activity. Rewriting on close made the offer shrink one@@ -2460,48 +2447,19 @@ class Registry:def set_focus_mode(self, enabled: bool) -> bool:"""Turn the focused coding mode on/off. Returns the resulting state.- Also swaps the assistant's *character* to the built-in ``coding`` mode,- because "focused coding mode" was only ever half a mode: it added the- workspace facts to the prompt but left the tone alone. It is applied as- a SECTION OVERRIDE, which is in-memory and never persisted — so this- cannot overwrite the mode the user actually chose, and cannot survive a- restart the way the old sticky focus flag did.+ The flag is per workspace and in-memory: it adds the workspace facts+ to the assistant's prompt while the workspace is at the front, and it+ does not survive a restart."""session = self.sessionif session is None:if enabled:raise SessionError("No Agentic-IDE session is running — open one first.")- self._sync_coding_character()return Falsesession.focus_mode = bool(enabled)logger.info("Agentic IDE focus mode {}", "on" if enabled else "off")- self._sync_coding_character()return session.focus_mode- def _sync_coding_character(self) -> None:- """Point the persona layer at the ``coding`` mode exactly while coding- mode is in effect — and at nothing the moment it is not.-- Derived from the registry's own state (the workspace at the front AND- its focus flag, the same two halves ``coding_mode_active`` reads) rather- than passed in by the caller, so no transition can leave the persona- saying "coding" while the predicate says "no workspace". Called from- every place that state changes: the toggle, a workspace coming to the- front, the front being cleared, and the last workspace closing.-- Best-effort by design: the workspace context block is the part users- depend on, so a missing or renamed ``coding`` mode costs the tone and- nothing else.- """- session = self.session- enabled = session is not None and bool(session.focus_mode)- try:- from jarvis.brain import modes-- modes.set_section_override(modes.MODE_CODING if enabled else None)- except Exception as exc: # noqa: BLE001 - never fail a toggle on the tone- logger.debug("Coding-mode character not applied: {}", exc)-def set_surface_context(self,*,diff --git a/jarvis/brain/factory.py b/jarvis/brain/factory.pyindex c46ca3ca8f..a6a7906e1e 100644--- a/jarvis/brain/factory.py+++ b/jarvis/brain/factory.py@@ -97,14 +97,6 @@ ROUTER_TOOLS = frozenset({# (two-turn voice confirm). Direct gated action, never a spawn — never in# a worker set (AP-5/AP-14). See ADR-0011 amendment "app-command tool"."app-command",- # Assistant modes (2026-08-13): the assistant's own character. Reading the- # list is a property read; switching changes tone and is visible on screen- # the moment it happens; saving is ask-tier because it writes a file every- # future turn will read. All three are direct gated actions, never a spawn- # — never in a worker set (AP-5/AP-14).- "list-modes",- "switch-mode",- "save-mode",# Phase A1: synchronous state read on the AwarenessManager (Plan §5).# NO brain call, NO IO — property read only."awareness-snapshot",diff --git a/jarvis/brain/modes.py b/jarvis/brain/modes.pydeleted file mode 100644index d3237379d7..0000000000--- a/jarvis/brain/modes.py+++ /dev/null@@ -1,749 +0,0 @@-"""Assistant modes: a shelf of named characters, one of them active.--A *mode* is how the assistant behaves — the difference between a butler who-answers in one line and a friend who asks how your day went. Until now there-was exactly one character (``JARVIS_PERSONA.md``) plus a single-slot override-(``data/custom_system_prompt.md``). This module turns that one slot into a-library.--Why a mode is a LAYER, never a replacement--------------------------------------------The packaged persona carries the rules that keep the assistant honest — never-claim an action that did not happen, never read a path aloud, never invent a-result. A mode that replaced the whole prompt would drop those rules the moment-the user picked "Friend", and the failure would look like a personality quirk-rather than the safety regression it is (the BUG-136 class: a spoken claim that-ran ahead of reality).--So a mode contributes only a *character block*, appended to the base persona by-``persona_loader.load_effective_persona_prompt``. The base always wins on-honesty; the mode decides tone, length, and how much the assistant volunteers.-The ``assistant`` built-in contributes an EMPTY block on purpose: the default-mode reproduces today's behaviour byte for byte, so shipping this feature-changes nothing until the user chooses otherwise.--Where a mode lives--------------------Built-ins are packaged Markdown next to this file (``jarvis/brain/modes/``) —-readable, forkable, and never written to at runtime. User modes are sidecar-files under ``DATA_DIR/modes/``, exactly the arrangement-``persona_loader.custom_prompt_path`` already uses, so "reset" is a delete and-the packaged set is always recoverable.--Which mode is active----------------------Two layers, and the split is the whole point:--* ``[persona] active_mode`` in ``jarvis.toml`` — the user's deliberate choice.- Sticky, survives a restart, written only through ``config_writer``.-* An in-memory *section override* — what the Agentic IDE section sets while it- is on screen. Deliberately NOT persisted: a mode that a screen switched on- must not outlive the process. That is precisely how coding mode became- permanently stuck (``AgenticIdeView`` switched it on and nothing ever switched- it off), and a non-persisted override makes that class of bug structurally- impossible — the worst case is one session, not forever.--Five-layer enum discipline (``docs/anti-drift-three-layer.md``): ``VERBOSITIES``-and ``PROACTIVITIES`` are the single source of truth here; the Pydantic Literals-in ``jarvis/ui/web/modes_routes.py`` assert against these tuples at import time,-and the TypeScript union mirrors them.-"""--from __future__ import annotations--import logging-import os-import re-import tempfile-import threading-from dataclasses import dataclass, replace-from pathlib import Path--log = logging.getLogger(__name__)--# ----------------------------------------------------------------------------# Layer 0 — the single source of truth for every enum-like value below.-# -----------------------------------------------------------------------------VERBOSITY_BRIEF = "brief"-VERBOSITY_NORMAL = "normal"-VERBOSITY_RICH = "rich"-VERBOSITIES: tuple[str, ...] = (VERBOSITY_BRIEF, VERBOSITY_NORMAL, VERBOSITY_RICH)--PROACTIVITY_REACTIVE = "reactive"-PROACTIVITY_NORMAL = "normal"-PROACTIVITY_FORWARD = "forward"-PROACTIVITIES: tuple[str, ...] = (- PROACTIVITY_REACTIVE,- PROACTIVITY_NORMAL,- PROACTIVITY_FORWARD,-)--# Built-in slugs. Symbolic so a typo is an AttributeError at import, not a-# silently missing mode weeks later (defence D1 of the anti-drift doc).-MODE_ASSISTANT = "assistant"-MODE_FRIEND = "friend"-MODE_COACH = "coach"-MODE_FOCUS = "focus"-MODE_CODING = "coding"-BUILTIN_SLUGS: tuple[str, ...] = (- MODE_ASSISTANT,- MODE_FRIEND,- MODE_COACH,- MODE_FOCUS,- MODE_CODING,-)--#: The mode in force when the user has never chosen one. Reproduces the-#: pre-modes behaviour exactly (empty character block).-DEFAULT_MODE = MODE_ASSISTANT--#: Slug grammar. Restrictive on purpose: the slug becomes a FILE NAME written-#: by an HTTP route and by a tool the realtime model can call, so anything that-#: could escape ``modes_dir()`` — separators, dots, absolute paths, NTFS-#: alternate data streams — must not survive validation.-_SLUG_RE = re.compile(r"^[a-z0-9][a-z0-9-]{0,47}$")--#: Reserved on Windows regardless of extension; a mode called "con" would create-#: a file nobody can delete afterwards.-_WINDOWS_RESERVED = frozenset(- {"con", "prn", "aux", "nul"}- | {f"com{i}" for i in range(1, 10)}- | {f"lpt{i}" for i in range(1, 10)}-)--_MODE_FILE_SUFFIX = ".md"-_PACKAGED_DIR_NAME = "modes"--# Guards the in-memory section override. Voice turns, HTTP handlers and the UI-# poll read it from different threads.-_override_lock = threading.Lock()-_section_override: str | None = None---class ModeError(ValueError):- """A mode could not be resolved, validated, or written."""---@dataclass(frozen=True)-class Mode:- """One selectable character.-- ``character`` is the block appended to the base persona — NOT a complete- system prompt. Empty means "add nothing", which is what ``assistant`` does.- """-- slug: str- name: str- emoji: str- description: str- character: str- built_in: bool = False- #: TTS voice id this mode prefers. Empty keeps the configured voice — a- #: mode that named a voice the active provider does not have would- #: otherwise mute the assistant rather than merely sounding wrong.- voice: str = ""- verbosity: str = VERBOSITY_NORMAL- proactivity: str = PROACTIVITY_NORMAL- #: True when a built-in has been overlaid by the user's own file. Only then- #: does "restore the original" do anything, so a UI can offer it exactly- #: when it means something and label the card as edited.- edited: bool = False-- def to_payload(self) -> dict[str, object]:- """JSON-ready shape shared by the REST routes and the CLI."""- return {- "slug": self.slug,- "name": self.name,- "emoji": self.emoji,- "description": self.description,- "character": self.character,- "built_in": self.built_in,- "edited": self.edited,- "voice": self.voice,- "verbosity": self.verbosity,- "proactivity": self.proactivity,- }---# ----------------------------------------------------------------------------# Paths-# ------------------------------------------------------------------------------def packaged_modes_dir() -> Path:- """Directory holding the shipped built-in mode files (read-only)."""- return Path(__file__).resolve().parent / _PACKAGED_DIR_NAME---def modes_dir() -> Path:- """Directory holding the user's own modes.-- Resolved at call time from ``jarvis.core.config.DATA_DIR`` — the same- convention ``persona_loader.custom_prompt_path`` follows — so tests can- redirect it and a headless install can relocate the whole data directory.- """- from jarvis.core import config as core_config-- return core_config.DATA_DIR / _PACKAGED_DIR_NAME---def _mode_path(slug: str) -> Path:- return modes_dir() / f"{slug}{_MODE_FILE_SUFFIX}"---# ----------------------------------------------------------------------------# Validation-# ------------------------------------------------------------------------------def normalize_slug(raw: str) -> str:- """Turn a human name into a safe slug, or raise ``ModeError``.-- Accepts what a person types ("My Friend Mode") and returns ``my-friend-mode``.- Rejects anything that would not round-trip as a plain file name.- """- text = (raw or "").strip().lower()- # Path-shaped input is refused rather than repaired. Stripping the illegal- # characters below would already make traversal impossible (the grammar has- # no dots and no separators, so the result cannot leave ``modes_dir()``),- # but it would turn "/etc/passwd" into a mode cheerfully named "etcpasswd".- # This slug can arrive from a tool the realtime model calls; a caller that- # hands over a path has made a mistake and should hear about it.- if any(sep in text for sep in ("/", "\\", ":")) or ".." in text:- raise ModeError(f"{raw!r} looks like a path, not a mode name.")- text = text.replace("_", "-").replace(" ", "-")- # Drop everything outside the grammar rather than escaping it: a slug is a- # label, and a silently escaped one is unreadable in the UI and the CLI.- text = re.sub(r"[^a-z0-9-]", "", text)- text = re.sub(r"-{2,}", "-", text).strip("-")- if not text or not _SLUG_RE.match(text):- raise ModeError(- f"{raw!r} does not produce a usable mode id. Use letters, digits and "- "hyphens (1-48 characters)."- )- if text in _WINDOWS_RESERVED:- raise ModeError(f"{text!r} is a reserved device name on Windows. Pick another name.")- return text---def _validate_choice(value: str, allowed: tuple[str, ...], field: str) -> str:- candidate = (value or "").strip().lower()- if not candidate:- return allowed[allowed.index("normal")] if "normal" in allowed else allowed[0]- if candidate not in allowed:- raise ModeError(f"{field} must be one of {', '.join(allowed)} — got {value!r}.")- return candidate---# ----------------------------------------------------------------------------# Reading-# ------------------------------------------------------------------------------def _parse_mode_file(path: Path, *, built_in: bool) -> Mode | None:- """Read one ``<slug>.md`` into a :class:`Mode`, or ``None`` when unusable.-- A corrupt mode file degrades to "this mode does not exist" instead of- raising: the file sits in a user-writable directory, and one bad hand-edit- must not take down the mode list (or, through the persona layer, every turn).- """- try:- text = path.read_text(encoding="utf-8-sig")- except OSError as exc:- log.warning("Mode %s unreadable (%s) — skipped.", path.name, exc)- return None-- from jarvis.memory.frontmatter import parse_frontmatter-- meta, body = parse_frontmatter(text)- if not isinstance(meta, dict):- meta = {}- slug = path.stem.lower()- try:- slug = normalize_slug(slug)- except ModeError:- log.warning("Mode file %s has an unusable name — skipped.", path.name)- return None-- def _str(key: str, default: str = "") -> str:- value = meta.get(key, default)- return value.strip() if isinstance(value, str) else default-- try:- verbosity = _validate_choice(_str("verbosity"), VERBOSITIES, "verbosity")- proactivity = _validate_choice(_str("proactivity"), PROACTIVITIES, "proactivity")- except ModeError as exc:- # A hand-edited typo costs the knob, not the mode.- log.warning("Mode %s: %s — falling back to the normal setting.", slug, exc)- verbosity, proactivity = VERBOSITY_NORMAL, PROACTIVITY_NORMAL-- return Mode(- slug=slug,- name=_str("name") or slug.replace("-", " ").title(),- emoji=_str("emoji"),- description=_str("description"),- character=body.strip(),- built_in=built_in,- voice=_str("voice"),- verbosity=verbosity,- proactivity=proactivity,- )---def _read_dir(directory: Path, *, built_in: bool) -> dict[str, Mode]:- found: dict[str, Mode] = {}- try:- entries = sorted(directory.glob(f"*{_MODE_FILE_SUFFIX}"))- except OSError as exc:- # An unreadable modes directory contributes nothing; the built-in- # (or user) side still applies, so this is a debug note, not a failure.- log.debug("modes: cannot list %s (%s) — skipping that directory", directory, exc)- return found- for path in entries:- mode = _parse_mode_file(path, built_in=built_in)- if mode is not None:- found[mode.slug] = mode- return found---def list_modes() -> tuple[Mode, ...]:- """Every available mode: built-ins first, then the user's own, A-Z.-- A user file whose name collides with a built-in slug WINS — that is how- "copy a built-in and tweak it" works — but it keeps the ``built_in`` flag- so the UI can still offer "restore the original" rather than pretending the- packaged version is gone.- """- builtins = _read_dir(packaged_modes_dir(), built_in=True)- overrides = _read_dir(modes_dir(), built_in=False)-- merged: dict[str, Mode] = dict(builtins)- for slug, mode in overrides.items():- is_builtin = slug in builtins- merged[slug] = replace(mode, built_in=is_builtin, edited=is_builtin)-- ordered = [merged[s] for s in BUILTIN_SLUGS if s in merged]- ordered.extend(- sorted(- (m for s, m in merged.items() if s not in BUILTIN_SLUGS),- key=lambda m: m.name.lower(),- )- )- return tuple(ordered)---def get_mode(slug: str) -> Mode | None:- """One mode by slug, or ``None`` when there is no such mode."""- try:- wanted = normalize_slug(slug)- except ModeError:- return None # an invalid slug names no mode — the docstring promises None- for mode in list_modes():- if mode.slug == wanted:- return mode- return None---def has_user_copy(slug: str) -> bool:- """True when the user has their own file for this slug (built-in or not)."""- try:- return _mode_path(normalize_slug(slug)).is_file()- except (ModeError, OSError):- return False # no valid slug or no readable file: either way, no user copy---# ----------------------------------------------------------------------------# Which mode is active-# ------------------------------------------------------------------------------def _configured_slug() -> str:- """The user's sticky choice from ``[persona] active_mode``.-- Read through ``load_config()`` — the one accessor the config layer has —- which is cached on the file's identity and invalidated by ``config_writer``- on every write, so a switch is visible on the very next read without a- restart. The first version imported a ``get_config`` that never existed and- swallowed the ``ImportError`` in a blanket ``except``: every read came back- as the default, the check mark on the modes screen never moved, and the- assistant never ran the mode the user had picked. Only failures of the READ- itself are tolerated here (a half-written file mid-reload); a broken import- is a bug and must surface as one.- """- from jarvis.core.config import load_config-- try:- raw = getattr(getattr(load_config(), "persona", None), "active_mode", "")- except (OSError, ValueError) as exc: # a config that cannot be parsed right now- log.warning("Could not read [persona] active_mode (%s) — using %s.", exc, DEFAULT_MODE)- return DEFAULT_MODE- slug = (raw or "").strip().lower()- return slug or DEFAULT_MODE---def chosen_slug() -> str:- """The user's own, sticky choice — what ``[persona] active_mode`` names.-- Distinct from :func:`active_slug` on purpose: while a section override is- in force the two differ, and a UI that can only show the one in force has no- way to confirm that a switch was stored ("you picked Friend; Coding is on- until you leave the IDE"). Falls back to the default when the stored slug- names a mode that no longer exists, for the same reason ``active_slug`` does.- """- candidate = _configured_slug()- if get_mode(candidate) is not None:- return candidate- return DEFAULT_MODE---def active_slug() -> str:- """The slug in force for this turn — section override first, then config.-- Falls back to :data:`DEFAULT_MODE` when the stored slug names a mode that no- longer exists (deleted by hand, or a config carried to another machine).- Silence here would be wrong in the other direction: the user would keep- seeing a mode name the assistant is not actually running.- """- with _override_lock:- override = _section_override- candidate = override or _configured_slug()- if get_mode(candidate) is not None:- return candidate- if override is not None:- log.warning("Section override %r names no known mode — ignoring it.", override)- elif candidate != DEFAULT_MODE:- log.warning(- "Active mode %r no longer exists — falling back to %s.", candidate, DEFAULT_MODE- )- return DEFAULT_MODE---def active_mode() -> Mode:- """The mode in force for this turn. Never ``None``."""- mode = get_mode(active_slug())- if mode is not None:- return mode- # Neither the chosen mode nor the packaged default could be read — a broken- # install. An empty character block is the honest answer: base persona only.- return Mode(- slug=DEFAULT_MODE,- name="Assistant",- emoji="",- description="",- character="",- built_in=True,- )---def set_active(slug: str) -> Mode:- """Persist the user's mode choice. Applies on the next turn, no restart.-- Raises ``ModeError`` when the slug names no known mode — writing a pointer- to a mode that does not exist would show a name in the UI that the assistant- is not running.- """- mode = get_mode(slug)- if mode is None:- raise ModeError(f"No mode called {slug!r}.")-- from jarvis.core import config_writer-- config_writer.set_active_mode(mode.slug)- log.info("Active mode set to %s.", mode.slug)- return mode---def set_section_override(slug: str | None) -> str | None:- """Set (or clear with ``None``) the screen-scoped mode.-- In-memory only, by design — see the module docstring. Returns the slug now- in force, so the caller can report what actually happened rather than what- it asked for.- """- global _section_override- if slug is None:- with _override_lock:- _section_override = None- return active_slug()- if get_mode(slug) is None:- raise ModeError(f"No mode called {slug!r}.")- with _override_lock:- _section_override = normalize_slug(slug)- return active_slug()---def section_override() -> str | None:- """The screen-scoped mode currently in force, if any."""- with _override_lock:- return _section_override---# ----------------------------------------------------------------------------# Writing-# ------------------------------------------------------------------------------def _atomic_write(path: Path, text: str) -> None:- """Write UTF-8 without a BOM via tempfile + ``os.replace`` (AP-7)."""- path.parent.mkdir(parents=True, exist_ok=True)- fd, tmp_name = tempfile.mkstemp(dir=str(path.parent), prefix=f".{path.stem}.", suffix=".tmp")- try:- with os.fdopen(fd, "w", encoding="utf-8", newline="\n") as fh:- fh.write(text)- os.replace(tmp_name, path)- except BaseException:- try:- os.unlink(tmp_name)- except OSError:- pass # best-effort temp cleanup — the original error re-raised below matters- raise---def save_mode(- *,- slug: str,- name: str,- character: str,- emoji: str = "",- description: str = "",- voice: str = "",- verbosity: str = VERBOSITY_NORMAL,- proactivity: str = PROACTIVITY_NORMAL,-) -> Mode:- """Create or replace a user mode. Returns the mode as it was stored.-- Editing a built-in is allowed and writes a user copy alongside the packaged- file; the packaged one is never touched, so ``restore_builtin`` is a delete.- """- safe_slug = normalize_slug(slug)- display = (name or "").strip() or safe_slug.replace("-", " ").title()- body = (character or "").strip()- if not body:- raise ModeError("A mode needs a character description — an empty one changes nothing.")-- mode = Mode(- slug=safe_slug,- name=display,- emoji=(emoji or "").strip(),- description=(description or "").strip(),- character=body,- built_in=safe_slug in BUILTIN_SLUGS,- voice=(voice or "").strip(),- verbosity=_validate_choice(verbosity, VERBOSITIES, "verbosity"),- proactivity=_validate_choice(proactivity, PROACTIVITIES, "proactivity"),- )-- from jarvis.memory.frontmatter import write_frontmatter-- meta: dict[str, object] = {- "name": mode.name,- "emoji": mode.emoji,- "description": mode.description,- "voice": mode.voice,- "verbosity": mode.verbosity,- "proactivity": mode.proactivity,- }- _atomic_write(_mode_path(safe_slug), write_frontmatter(meta, mode.character))- log.info("Mode %s saved.", safe_slug)- return mode---def delete_mode(slug: str) -> bool:- """Remove a user mode (or a user copy of a built-in). Idempotent.-- Deleting the mode that is currently active resets the pointer to- :data:`DEFAULT_MODE` rather than leaving a dangling name on screen.- """- safe_slug = normalize_slug(slug)- if safe_slug in BUILTIN_SLUGS and not has_user_copy(safe_slug):- raise ModeError(f"{safe_slug!r} is a built-in mode and cannot be deleted.")-- try:- _mode_path(safe_slug).unlink()- removed = True- except FileNotFoundError:- removed = False # idempotent: nothing to delete is a "no", not an error- except OSError as exc:- raise ModeError(f"Could not delete {safe_slug!r}: {exc}") from exc-- if removed and _configured_slug() == safe_slug and get_mode(safe_slug) is None:- try:- from jarvis.core import config_writer-- config_writer.set_active_mode(DEFAULT_MODE)- except Exception as exc: # noqa: BLE001 - the delete already happened- log.warning("Deleted the active mode but could not reset the pointer: %s", exc)- with _override_lock:- stale_override = _section_override == safe_slug- if stale_override:- set_section_override(None)- return removed---def restore_builtin(slug: str) -> bool:- """Drop the user's copy of a built-in so the packaged version applies again."""- safe_slug = normalize_slug(slug)- if safe_slug not in BUILTIN_SLUGS:- raise ModeError(f"{safe_slug!r} is not a built-in mode.")- try:- _mode_path(safe_slug).unlink()- return True- except FileNotFoundError:- return False # no user copy to drop — the packaged version already applies- except OSError as exc:- raise ModeError(f"Could not restore {safe_slug!r}: {exc}") from exc---# ----------------------------------------------------------------------------# Migration from the single-slot custom prompt-# -----------------------------------------------------------------------------MIGRATED_SLUG = "my-mode"---def migrate_legacy_custom_prompt() -> str | None:- """Adopt an existing ``custom_system_prompt.md`` as a normal mode.-- Runs at most once: the legacy file is left in place (so a downgrade still- works and nothing the user wrote is destroyed) and the copy is only made- when no mode with that slug exists yet. Returns the slug it created, or- ``None`` when there was nothing to migrate.-- The migrated mode is NOT activated. The legacy file is still honoured by- ``persona_loader`` for exactly that reason — the user's words keep applying- either way, and the migration only makes them switchable.- """- from jarvis.brain import persona_loader-- legacy = persona_loader.read_custom_prompt()- if not legacy:- return None- if _mode_path(MIGRATED_SLUG).is_file():- return None- try:- save_mode(- slug=MIGRATED_SLUG,- name="My Mode",- emoji="✍️",- description="The custom system prompt you wrote before modes existed.",- character=legacy,- )- except (ModeError, OSError) as exc:- log.warning("Could not migrate the custom system prompt into a mode: %s", exc)- return None- log.info("Migrated the custom system prompt into the %r mode.", MIGRATED_SLUG)- return MIGRATED_SLUG---# ----------------------------------------------------------------------------# Compiling a mode into prompt text-# -----------------------------------------------------------------------------_VERBOSITY_LINES = {- VERBOSITY_BRIEF: (- "Answer in as few words as carry the meaning — usually one or two "- "sentences. Do not summarise what you just did unless asked."- ),- VERBOSITY_NORMAL: "",- VERBOSITY_RICH: (- "Give the reasoning as well as the answer: what you considered, what you "- "ruled out, and why. Detail is welcome as long as every sentence earns "- "its place."- ),-}--_PROACTIVITY_LINES = {- PROACTIVITY_REACTIVE: (- "Answer what was asked and stop. Do not suggest next steps, do not offer "- "related work, and do not raise topics the user did not open."- ),- PROACTIVITY_NORMAL: "",- PROACTIVITY_FORWARD: (- "Think a step ahead: name the thing the user has not thought of yet, "- "flag what is about to become a problem, and offer the obvious next move."- ),-}--_BLOCK_HEADER = "ACTIVE MODE"---def mode_prompt_block(mode: Mode) -> str:- """The text a mode contributes to the system prompt. ``""`` adds nothing.-- Deliberately closes with a precedence line. Without it, a mode that says- "be casual and just go for it" reads as permission to skip the honesty rules- in the base persona, and the model has no way to know which instruction is- the standing one.- """- parts = [line for line in (mode.character.strip(),) if line]- for line in (- _VERBOSITY_LINES.get(mode.verbosity, ""),- _PROACTIVITY_LINES.get(mode.proactivity, ""),- ):- if line:- parts.append(line)- if not parts:- return ""-- label = f"{mode.emoji} {mode.name}".strip() if mode.emoji else mode.name- body = "\n\n".join(parts)- return (- f"{_BLOCK_HEADER}: {label}\n"- "This is how you behave right now. It changes your tone, your length "- "and what you volunteer — it never overrides the rules above about "- "honesty, about only claiming actions you actually took, or about what "- "is safe to say out loud. Where this section and those rules disagree, "- f"those rules win.\n\n{body}"- )---def active_prompt_block() -> str:- """The prompt contribution of whichever mode is active. Never raises."""- try:- return mode_prompt_block(active_mode())- except Exception as exc: # noqa: BLE001 - a mode must never break a turn- log.warning("Mode block unavailable (%s) — running the base persona.", exc)- return ""---def active_voice() -> str:- """TTS voice the active mode prefers, or ``""`` to keep the configured one."""- try:- return active_mode().voice- except Exception: # noqa: BLE001 - never let a mode mute the assistant- return ""---__all__ = [- "BUILTIN_SLUGS",- "DEFAULT_MODE",- "MODE_ASSISTANT",- "MODE_CODING",- "MODE_COACH",- "MODE_FOCUS",- "MODE_FRIEND",- "PROACTIVITIES",- "VERBOSITIES",- "Mode",- "ModeError",- "active_mode",- "active_prompt_block",- "active_slug",- "active_voice",- "chosen_slug",- "delete_mode",- "get_mode",- "has_user_copy",- "list_modes",- "migrate_legacy_custom_prompt",- "mode_prompt_block",- "modes_dir",- "normalize_slug",- "packaged_modes_dir",- "restore_builtin",- "save_mode",- "section_override",- "set_active",- "set_section_override",-]diff --git a/jarvis/brain/modes/assistant.md b/jarvis/brain/modes/assistant.mddeleted file mode 100644index 5e7ddf9e79..0000000000--- a/jarvis/brain/modes/assistant.md+++ /dev/null@@ -1,8 +0,0 @@-----name: Assistant-emoji: 🎩-description: Precise and quiet. Does the task, says what happened, stops.-voice: ""-verbosity: normal-proactivity: normal----diff --git a/jarvis/brain/modes/coach.md b/jarvis/brain/modes/coach.mddeleted file mode 100644index 60da7faed5..0000000000--- a/jarvis/brain/modes/coach.md+++ /dev/null@@ -1,29 +0,0 @@-----name: Coach-emoji: 🎯-description: Holds you to what you said you would do. Checks in, no excuses.-voice: ""-verbosity: normal-proactivity: forward------Your job is to keep the user moving toward what they said they wanted, not to-make them comfortable.--Hold the thread. When they told you a goal, a deadline, or a habit, bring it up-again — at the start of a session, when they drift, and when they quietly drop-it. "You said you would finish this by Friday. Where is it?" is a normal thing-for you to say.--Push on vagueness. "Soon", "I'll look into it", and "kind of" are not answers.-Ask for the specific next action, who does it, and by when. If they cannot name-one, help them cut the task down until they can.--Do not accept an excuse at face value, and do not moralise about it either.-Name what actually blocked them, ask what would remove that block, and move on.-One question is worth more than a paragraph of encouragement.--Give credit only when it is earned, and be specific about what earned it.-Constant praise is noise; rare praise is information.--Keep it short. A coach who lectures is being ignored.diff --git a/jarvis/brain/modes/coding.md b/jarvis/brain/modes/coding.mddeleted file mode 100644index e9342405be..0000000000--- a/jarvis/brain/modes/coding.md+++ /dev/null@@ -1,29 +0,0 @@-----name: Coding-emoji: 🖥️-description: Terminal-aware. Talks about your open agents and what they are doing.-voice: ""-verbosity: normal-proactivity: normal------The user is working in the Agentic IDE with terminals open, and you can see-what is in them.--Talk about the panes the way a colleague sitting next to them would: by-call-sign, in the present tense, and about what is actually on screen. "Kai is-still on the wake path, Nova finished and is waiting" beats any summary of what-you assume is happening.--When they hand work to a named agent, that is where it goes. Do not quietly-start a background worker instead, and do not answer as though you had done the-work yourself.--Never report a pane as finished, started, or briefed unless the terminal-content in front of you shows it. A pane with a brief still being composed is-not a pane that has been briefed. When you do not know the state of something,-say you will check rather than guessing — a wrong status here sends the user-looking in the wrong place.--Use their vocabulary: panes, terminals, call-signs, briefs. Keep answers short-while work is running; they are reading output, not you.diff --git a/jarvis/brain/modes/focus.md b/jarvis/brain/modes/focus.mddeleted file mode 100644index f20e9bd7ad..0000000000--- a/jarvis/brain/modes/focus.md+++ /dev/null@@ -1,27 +0,0 @@-----name: Focus-emoji: 🔇-description: One-line answers. Nothing volunteered. Get out of the way.-voice: ""-verbosity: brief-proactivity: reactive------The user is concentrating on something that is not you. Cost them as little-attention as possible.--Answer in one line where one line is true. Two if it is not. Never three.--No preamble, no restating the question, no summary at the end, no offer of-further help. If the answer is a single word or a single number, that is the-whole message.--Volunteer nothing. No suggestions, no related information, no "you might also-want to". If something genuinely urgent comes up — something breaking, or a-mistake about to be made — say it in one sentence and stop.--When a task takes a while, say nothing until it is done, then report the result-in one line.--If the honest answer is long, say the short version first and offer the rest in-four words: "Want the full version?"diff --git a/jarvis/brain/modes/friend.md b/jarvis/brain/modes/friend.mddeleted file mode 100644index 6e6bf114e1..0000000000--- a/jarvis/brain/modes/friend.md+++ /dev/null@@ -1,31 +0,0 @@-----name: Friend-emoji: 🫂-description: Warm and casual. Has opinions, pushes back, asks how you are.-voice: ""-verbosity: normal-proactivity: normal------You are talking to a friend, not serving a client. Drop the deference.--Talk the way someone does who knows the user and likes them: contractions,-short sentences, the occasional joke, no formal openings and no "certainly" or-"of course". Never call them sir.--Have actual opinions and say them first, before the caveats. When you think an-idea is weak, say so plainly and say why — a friend who agrees with everything-is no use to anyone. When you think it is good, say that too, without hedging-it into mush.--Notice the person, not just the task. If they sound tired, frustrated, or-pleased with something, respond to that before the work. If they mention-something from their life, remember it and come back to it later. Ask a real-question now and then instead of only answering them.--Small talk is allowed. Silence is allowed. You do not have to end every message-with an offer to help.--What does not change: when they ask you to do something, you do it properly and-you tell them honestly how it went. Being warm never means softening bad news-or pretending something worked.diff --git a/jarvis/brain/persona_loader.py b/jarvis/brain/persona_loader.pyindex d2d6887265..560ad42392 100644--- a/jarvis/brain/persona_loader.py+++ b/jarvis/brain/persona_loader.py@@ -175,17 +175,17 @@ def default_persona_prompt() -> str:return load_persona_prompt()-def base_persona_prompt(*, compact: bool = False) -> str:- """The persona WITHOUT the active mode layered on: custom override, else default.+def load_effective_persona_prompt(*, compact: bool = False) -> str:+ """The persona block the brain should use: custom override if set, else default.The custom override wins EVEN in compact mode — the user chose thoseexact words for their assistant, and user autonomy outranks the latencyoptimization (the trade-off is documented on the settings surface).- Callers that build the brain's prompt want- :func:`load_effective_persona_prompt` instead; this one exists for the- settings surface, which edits the base text and must not show the user a- mode block they cannot edit there.+ This is the ONE place the assistant's character is assembled: the typing+ brain (``BrainManager._build_system_prompt``) and the speaking brain+ (``jarvis.realtime.session``) both read it fresh on every turn, so an edit+ reaches both without a restart."""custom = read_custom_prompt()if custom is not None:@@ -195,35 +195,6 @@ def base_persona_prompt(*, compact: bool = False) -> str:return default_persona_prompt()-def load_effective_persona_prompt(*, compact: bool = False) -> str:- """The full persona the brain should use: the base plus the active mode.-- This is the ONE place the assistant's character is assembled, which is why- a mode switch reaches the typing brain (``BrainManager._build_system_prompt``)- and the speaking brain (``jarvis.realtime.session``) at the same moment and- without a restart — both read this function fresh on every turn.-- The mode is appended, never substituted. The base carries the standing rules- about honesty and about what is safe to say aloud; a mode that replaced it- would drop those rules the moment somebody picked a chattier character, and- the regression would read as a personality quirk rather than a safety bug.-- The default ``assistant`` mode contributes an empty block, so an install- that never touches modes produces byte-identical prompts to before.- """- base = base_persona_prompt(compact=compact)- try:- from .modes import active_prompt_block-- block = active_prompt_block()- except Exception as exc: # noqa: BLE001 - a mode must never break a turn- log.warning("Mode layer unavailable (%s) — base persona only.", exc)- return base- if not block:- return base- return f"{base}\n\n{block}" if base else block--def save_custom_prompt(text: str) -> None:"""Persist a custom system prompt atomically (tempfile + ``os.replace``).diff --git a/jarvis/cli_ctl/__main__.py b/jarvis/cli_ctl/__main__.pyindex 6532725963..79c2043320 100644--- a/jarvis/cli_ctl/__main__.py+++ b/jarvis/cli_ctl/__main__.py@@ -34,7 +34,6 @@ from jarvis.cli_ctl.commands import ide as ide_cmdfrom jarvis.cli_ctl.commands import marketplace as marketplace_cmdfrom jarvis.cli_ctl.commands import mcps as mcps_cmdfrom jarvis.cli_ctl.commands import missions as missions_cmd-from jarvis.cli_ctl.commands import modes as modes_cmdfrom jarvis.cli_ctl.commands import outputs as outputs_cmdfrom jarvis.cli_ctl.commands import permissions as permissions_cmdfrom jarvis.cli_ctl.commands import sessions as sessions_cmd@@ -115,7 +114,6 @@ app.add_typer(commands_cmd.app, name="commands")app.add_typer(computer_use_cmd.app, name="computer-use")app.add_typer(config_cmd.app, name="config")app.add_typer(missions_cmd.app, name="missions")-app.add_typer(modes_cmd.app, name="modes")app.add_typer(wiki_cmd.app, name="wiki")app.add_typer(sessions_cmd.app, name="sessions")app.add_typer(skills_cmd.app, name="skills")diff --git a/jarvis/cli_ctl/command_index.py b/jarvis/cli_ctl/command_index.pyindex 710534477b..896db94eba 100644--- a/jarvis/cli_ctl/command_index.py+++ b/jarvis/cli_ctl/command_index.py@@ -7,7 +7,7 @@ three tool rounds — `jarvisctl --help`, `jarvisctl skills --help`,deadline ended the turn. The CLI catalog gives the tool six example commands;everything else the model had to discover at the user's expense, one slowprovider round per `--help`. That is not a skills problem: it is the same for-workflows, modes, tasks, wiki, board, contacts, missions — every group the CLI+workflows, tasks, wiki, board, contacts, missions — every group the CLIhas and the model cannot see.So the tool description carries the whole tree: one line per group, the@@ -85,7 +85,6 @@ COMMAND_INDEX: dict[str, tuple[str, ...]] = {"kill <id>",),"tasks": ("list", "get <id>", "create", "cancel <id>", "delete <id>"),- "modes": ("list", "show <slug>", "use <slug>", "create", "delete <slug>", "restore"),"workflows": ("list", "show <id>", "create", "run <id>", "delete <id>", "run-history"),"sessions": ("list",diff --git a/jarvis/cli_ctl/commands/modes.py b/jarvis/cli_ctl/commands/modes.pydeleted file mode 100644index 89c6036b87..0000000000--- a/jarvis/cli_ctl/commands/modes.py+++ /dev/null@@ -1,84 +0,0 @@-"""modes: switch how the assistant behaves (/api/modes).--A mode is the assistant's character — Assistant, Friend, Coach, Focus, Coding,-or one you wrote yourself. Switching applies on the next turn, in voice and in-chat, with no restart.-"""--from __future__ import annotations--import typer--from jarvis.cli_ctl import invoke--app = typer.Typer(- no_args_is_help=True,- help="Assistant modes: list, show, use, create, delete, restore.",-)--[email protected]("list")-def list_modes() -> None:- """List every mode and show which one is active."""- invoke.run("GET", "/api/modes")---def show(slug: str = typer.Argument(..., help="Mode id, e.g. friend")) -> None:- """Show one mode in full, including its character text."""- invoke.run("GET", f"/api/modes/{slug}")---def use(slug: str = typer.Argument(..., help="Mode id to switch to")) -> None:- """Switch the active mode. Applies on the next turn — no restart."""- invoke.run("PUT", "/api/modes/active", body={"slug": slug})---def create(- name: str = typer.Argument(..., help="Display name, e.g. 'Night Owl'"),- character: str = typer.Option(..., "--character", "-c", help="How it should behave"),- slug: str = typer.Option("", "--slug", help="Mode id (derived from the name if omitted)"),- emoji: str = typer.Option("", "--emoji", help="Shown on the mode card"),- description: str = typer.Option("", "--description", "-d", help="One line for the card"),- voice: str = typer.Option("", "--voice", help="TTS voice id this mode speaks in"),- verbosity: str = typer.Option("normal", "--verbosity", help="brief | normal | rich"),- proactivity: str = typer.Option("normal", "--proactivity", help="reactive | normal | forward"),-) -> None:- """Create or replace a mode. Does NOT switch to it — use `modes use` for that."""- invoke.run(- "POST",- "/api/modes",- body={- "slug": slug,- "name": name,- "character": character,- "emoji": emoji,- "description": description,- "voice": voice,- "verbosity": verbosity,- "proactivity": proactivity,- },- )---def delete(slug: str = typer.Argument(..., help="Mode id to delete")) -> None:- """Delete a mode you created. Built-ins are refused; a copy of one is not.-- Destructive and not undoable — the mode's character text is gone with it.- Deleting the active mode falls back to the default rather than leaving the- assistant pointing at something that is not there.- """- invoke.run("DELETE", f"/api/modes/{slug}", dangerous=True)---def restore(slug: str = typer.Argument(..., help="Built-in mode id to restore")) -> None:- """Throw away your edits to a built-in mode and bring the shipped one back.-- Destructive in one direction only: your edited copy is deleted, and the- packaged mode is always recoverable because it was never touched.- """- invoke.run("POST", f"/api/modes/{slug}/restore", dangerous=True)diff --git a/jarvis/cli_ctl/reserved.py b/jarvis/cli_ctl/reserved.pyindex 343f50884f..69dfe56200 100644--- a/jarvis/cli_ctl/reserved.py+++ b/jarvis/cli_ctl/reserved.py@@ -47,7 +47,6 @@ RESERVED_CONTROL_NAMES: frozenset[str] = frozenset("docs","frontier","ide",- "modes",})diff --git a/jarvis/core/config.py b/jarvis/core/config.pyindex 4328bd8d9c..cee0ce981e 100644--- a/jarvis/core/config.py+++ b/jarvis/core/config.py@@ -272,17 +272,6 @@ class PersonaConfig(BaseModel):# silently broken by a future base-class / project-wide model_config change.model_config = ConfigDict(extra="ignore")- # Which assistant mode is active — the user's deliberate, sticky choice- # (``jarvis.brain.modes``). Deliberately a free string rather than a- # Literal: user-created modes are the point of the feature, so the closed- # set lives in ``modes.BUILTIN_SLUGS`` and an unknown value degrades to the- # default at read time instead of failing config validation at boot.- #- # NOT the whole story on purpose: the Agentic IDE's screen-scoped override- # is in-memory only and never reaches this file, so a mode a screen turned- # on can never outlive the process.- active_mode: str = "assistant"-class WakeWordConfig(BaseModel):"""User-editable ``[trigger.wake_word]`` — the custom-wake-word config.diff --git a/jarvis/core/config_writer.py b/jarvis/core/config_writer.pyindex 18b3609dc5..09fe0f0c89 100644--- a/jarvis/core/config_writer.py+++ b/jarvis/core/config_writer.py@@ -1203,22 +1203,6 @@ def set_overlay_style(style: str, *, path: Path = DEFAULT_CONFIG_FILE) -> None:_patch_table(path, "ui", "orb_style", style)-def set_active_mode(slug: str, *, path: Path = DEFAULT_CONFIG_FILE) -> None:- """Persist the active assistant mode to ``[persona] active_mode``.-- ``slug`` is a mode id from ``jarvis.brain.modes`` — a built-in or one the- user created. Validation belongs to ``modes.set_active`` (it is the layer- that knows which modes exist); this function only writes.-- TOML-only by design, same rationale as :func:`set_overlay_style`:- ``persona.active_mode`` is not in the drift-guard's reference snapshot, so- it is never reverted, and no ENV override reads it — a second layer would- be a lie about where the value lives. No restart is needed either way,- because the persona layer re-reads the pointer on every turn.- """- _patch_table(path, "persona", "active_mode", slug)--def set_computer_use_engine(engine: str, *, path: Path = DEFAULT_CONFIG_FILE) -> None:"""Persist the active Computer-Use engine to ``[computer_use] engine``.diff --git a/jarvis/plugins/tool/assistant_mode.py b/jarvis/plugins/tool/assistant_mode.pydeleted file mode 100644index 97798f5b79..0000000000--- a/jarvis/plugins/tool/assistant_mode.py+++ /dev/null@@ -1,231 +0,0 @@-"""``switch_mode`` / ``save_mode`` — the assistant changes its own character.--Two tools, one feature. ``switch_mode`` is how "be my friend for a bit" or-"back to normal" works by voice. ``save_mode`` is the end of the mode-builder-interview: the assistant has asked what kind of company the user wants, and-this is where it writes the answer down.--They live here rather than as bespoke realtime declarations because the-realtime bridge builds its tool list from this same registry-(``jarvis/realtime/tools.py``). One tool file therefore reaches the speaking-brain, the typing brain and the CLI at once — a mode built by voice is-immediately visible on the modes screen, with no second code path to keep in-step.--Risk tiers, and why they differ:--* ``switch_mode`` is ``monitor``. It changes tone, nothing else, it is visible- on screen the moment it happens, and undoing it is one sentence. Making the- user confirm a change of voice they just asked for out loud would be- paperwork.-* ``save_mode`` is ``ask``. It writes a file the assistant will read on every- future turn, and the name is one the model chose from a conversation. The- confirmation is not friction here — it is the natural last beat of the- interview ("shall I save this as Night Owl?"), and it is what stops a- half-heard sentence from becoming a permanent character.--Neither tool is a spawn vehicle and neither belongs in a worker set-(AP-5/AP-14): both are direct, gated, in-process actions.-"""--from __future__ import annotations--from typing import Any--from jarvis.core.protocols import ExecutionContext, ToolResult---class SwitchModeTool:- """Switch the active assistant mode. Applies from the next turn."""-- name: str = "switch_mode"- risk_tier: str = "monitor"- description: str = (- "Switch how you behave by selecting one of the user's assistant modes "- "(for example assistant, friend, coach, focus, coding, or one they "- "created). Use this when the user asks you to be different — warmer, "- "shorter, tougher, back to normal. Call list_modes first if you are "- "not sure which modes exist. The change applies from the next turn."- )- schema: dict[str, Any] = {- "type": "object",- "properties": {- "slug": {- "type": "string",- "description": (- "The mode id to switch to, e.g. 'friend'. Must be one that already exists."- ),- },- },- "required": ["slug"],- }-- async def execute(self, args: dict[str, Any], ctx: ExecutionContext) -> ToolResult:- del ctx- from jarvis.brain import modes-- slug = str(args.get("slug", "")).strip()- if not slug:- return ToolResult(success=False, output=None, error="No mode id given.")- try:- mode = modes.set_active(slug)- except modes.ModeError as exc:- # Reported through the tool result: the model hears the exact reason.- available = ", ".join(m.slug for m in modes.list_modes())- return ToolResult(- success=False,- output=None,- # The model gets the real list back rather than a bare refusal,- # so a near-miss ("friendly") is recoverable in the same turn- # instead of becoming an apology to the user.- error=f"{exc} Available modes: {available}.",- )-- override = modes.section_override()- if override and override != mode.slug:- # Honest rather than convenient: the switch was stored, but it is- # not what the user will hear until they leave the section that is- # holding the override.- return ToolResult(- success=True,- output=(- f"Saved {mode.name} as the chosen mode, but the {override} mode "- "is in force while that section is open."- ),- error=None,- )- return ToolResult(success=True, output=f"Now in {mode.name} mode.", error=None)---class SaveModeTool:- """Write a new assistant mode from what the user described."""-- name: str = "save_mode"- risk_tier: str = "ask"- description: str = (- "Save a new assistant mode the user has described, or replace one they "- "already have. Use this at the end of a conversation about how they "- "want you to behave. Write 'character' in the second person, addressed "- "to yourself ('You are talking to a friend, not serving a client'), and "- "make it concrete: how to greet them, whether to have opinions, how "- "long answers should be, what to never do. Do not restate rules about "- "honesty or safety — those always apply and are not part of a mode."- )- schema: dict[str, Any] = {- "type": "object",- "properties": {- "name": {- "type": "string",- "description": "Short display name, e.g. 'Night Owl'.",- },- "character": {- "type": "string",- "description": (- "How you should behave in this mode, in the second person. "- "A few short paragraphs."- ),- },- "description": {- "type": "string",- "description": "One line describing the mode, shown on its card.",- },- "emoji": {"type": "string", "description": "A single emoji for the card."},- "verbosity": {- "type": "string",- "enum": ["brief", "normal", "rich"],- "description": "How long the answers should be.",- },- "proactivity": {- "type": "string",- "enum": ["reactive", "normal", "forward"],- "description": (- "How much to volunteer: 'reactive' answers only what was "- "asked, 'forward' thinks a step ahead."- ),- },- "activate": {- "type": "boolean",- "description": "Switch to the mode straight after saving it.",- },- },- "required": ["name", "character"],- }-- async def execute(self, args: dict[str, Any], ctx: ExecutionContext) -> ToolResult:- del ctx- from jarvis.brain import modes-- name = str(args.get("name", "")).strip()- character = str(args.get("character", "")).strip()- if not name or not character:- return ToolResult(- success=False,- output=None,- error="A mode needs both a name and a description of how to behave.",- )-- try:- mode = modes.save_mode(- slug=modes.normalize_slug(name),- name=name,- character=character,- emoji=str(args.get("emoji", "") or ""),- description=str(args.get("description", "") or ""),- verbosity=str(args.get("verbosity") or modes.VERBOSITY_NORMAL),- proactivity=str(args.get("proactivity") or modes.PROACTIVITY_NORMAL),- )- except modes.ModeError as exc:- # Both failures travel back to the model as the tool error — that is- # the report; the model turns it into words for the user.- return ToolResult(success=False, output=None, error=str(exc))- except OSError as exc:- # Same as above: the disk problem is spelled out in the tool error.- return ToolResult(success=False, output=None, error=f"Could not save the mode: {exc}")-- if not bool(args.get("activate")):- return ToolResult(success=True, output=f"Saved the {mode.name} mode.", error=None)- try:- modes.set_active(mode.slug)- except modes.ModeError as exc:- # The mode IS saved; only the switch failed. Reporting success- # here would promise a character the user is not going to get.- return ToolResult(- success=True,- output=f"Saved the {mode.name} mode, but could not switch to it: {exc}",- error=None,- )- return ToolResult(- success=True, output=f"Saved the {mode.name} mode and switched to it.", error=None- )---class ListModesTool:- """Read-only: which modes exist and which one is active."""-- name: str = "list_modes"- risk_tier: str = "safe"- description: str = (- "List the user's assistant modes and which one is currently active. "- "Use it before switching modes, or when the user asks what modes they "- "have."- )- schema: dict[str, Any] = {"type": "object", "properties": {}, "required": []}-- async def execute(self, args: dict[str, Any], ctx: ExecutionContext) -> ToolResult:- del args, ctx- from jarvis.brain import modes-- active = modes.active_slug()- listing = [- {- "slug": m.slug,- "name": m.name,- "description": m.description,- "active": m.slug == active,- }- for m in modes.list_modes()- ]- return ToolResult(success=True, output={"modes": listing, "active": active}, error=None)---__all__ = ["ListModesTool", "SaveModeTool", "SwitchModeTool"]diff --git a/jarvis/plugins/tool/navigate.py b/jarvis/plugins/tool/navigate.pyindex 9f32de40ad..220d33e556 100644--- a/jarvis/plugins/tool/navigate.py+++ b/jarvis/plugins/tool/navigate.py@@ -61,10 +61,6 @@ KNOWN: frozenset[str] = frozenset(# grid" an unknown section to the brain."agentic-ide-classic","chat-workspace",- # The assistant's character screen. It was a valid SECTION_IDS entry- # from the day it shipped but never landed here, which left the parity- # guard red and made "open the modes" an unknown section.- "modes",# The marketplace, in the app: community plugins, skills and wallpapers# in one storefront."marketplace",@@ -203,12 +199,6 @@ _ALIASES: dict[str, str] = {"marktplatz": "marketplace", # i18n-allow: input vocab"mercado": "marketplace", # i18n-allow: input vocab"tienda": "marketplace", # i18n-allow: input vocab- # The character screen, spoken. The bare id already resolves; these are the- # singular and localised forms.- "mode": "modes",- "modus": "modes", # i18n-allow: input vocab- "modi": "modes", # i18n-allow: input vocab- "modos": "modes", # i18n-allow: input vocab}diff --git a/jarvis/plugins/tts/__init__.py b/jarvis/plugins/tts/__init__.pyindex 698ba813b8..22451fe2ae 100644--- a/jarvis/plugins/tts/__init__.py+++ b/jarvis/plugins/tts/__init__.py@@ -360,17 +360,7 @@ def build_realtime_surface_tts(providers.get(provider_id) if isinstance(providers, dict) else None)config_voice = str(getattr(provider_cfg, "voice", "") or "").strip()- mode_voice = ""- try:- from jarvis.brain.modes import active_voice-- mode_voice = str(active_voice() or "").strip()- except Exception as exc: # noqa: BLE001 — a mode voice never blocks the fallback- log.debug("Mode voice not applied to the realtime surface TTS: %s", exc)- mode_voice = ""- session_voice = (- str(session_voice or "").strip() or mode_voice or config_voice- )+ session_voice = str(session_voice or "").strip() or config_voicetts_cfg = getattr(cfg, "tts", None)if family in {"gemini-flash-tts", "vertex-tts"}:diff --git a/jarvis/realtime/session.py b/jarvis/realtime/session.pyindex 351adf10f7..17b5563bd1 100644--- a/jarvis/realtime/session.py+++ b/jarvis/realtime/session.py@@ -3520,19 +3520,6 @@ class RealtimeVoiceSession:if provider_config is not Noneelse "")- # The active mode may ask for its own voice — a friend should not sound- # like a butler. Unlike the classic pipeline, which picks a voice per- # utterance, a realtime provider pins the voice when the session opens:- # switching modes mid-call therefore changes the voice on the NEXT call,- # not this sentence. Documented rather than worked around, because- # tearing down a live conversation to change its timbre would cost the- # user their turn.- try:- from jarvis.brain.modes import active_voice-- voice = active_voice() or voice- except Exception as exc: # noqa: BLE001 - a voice preference never costs a session- log.debug("Mode voice not applied to the realtime session: %s", exc)# An empty pin used to leave ``_active_voice`` blank. Surface TTS then# fell through to Charon while the live socket used Google's# undocumented default — a second, often different-gender speakerdiff --git a/jarvis/speech/pipeline.py b/jarvis/speech/pipeline.pyindex 7857bf3c99..9fd1590ebe 100644--- a/jarvis/speech/pipeline.py+++ b/jarvis/speech/pipeline.py@@ -292,23 +292,6 @@ _DELEGATION_COMPOSITION_RE = re.compile()-def _active_mode_voice() -> str | None:- """TTS voice the active assistant mode asks for, or ``None`` to keep the- configured one.-- Never raises and never blocks: this sits on the speak path, and a mode is a- cosmetic preference. A missing mode layer, an unreadable mode file or a- voice the provider does not have all degrade to the configured voice —- sounding wrong is recoverable, going silent is not.- """- try:- from jarvis.brain.modes import active_voice-- return active_voice() or None- except Exception: # noqa: BLE001 - a voice preference must never cost speech- return None--def _looks_like_delegation_composition(partial: str | None) -> bool:"""True if the live partial transcript shows a delegation being composed."""return bool(partial) and _DELEGATION_COMPOSITION_RE.search(partial) is not None@@ -4995,16 +4978,8 @@ class SpeechPipeline:# symptom; forensic 2026-06-23).lang_code = self._bcp47(ann_lang)self._register_assistant_speech(scrubbed.cleaned)- # A mode may name the voice it speaks in — a friend should not sound- # like a butler. Resolved per utterance rather than bound when the- # provider is built, so switching modes changes the voice on the- # next sentence instead of at the next restart. None means "keep the- # configured voice", which is every mode that names none.- mode_voice = _active_mode_voice()try:- chunks = self._tts.synthesize(- scrubbed.cleaned, voice=mode_voice, language_code=lang_code- )+ chunks = self._tts.synthesize(scrubbed.cleaned, language_code=lang_code)except TypeError:chunks = self._tts.synthesize(scrubbed.cleaned)if is_preamble:diff --git a/jarvis/ui/web/frontend/src/components/layout/MainView.tsx b/jarvis/ui/web/frontend/src/components/layout/MainView.tsxindex 2fb876c821..0936924c70 100644--- a/jarvis/ui/web/frontend/src/components/layout/MainView.tsx+++ b/jarvis/ui/web/frontend/src/components/layout/MainView.tsx@@ -82,9 +82,6 @@ const JarvisAgentsView = lazyView(() =>const WikiView = lazyView(() =>import("@/views/WikiView").then((m) => ({ default: m.WikiView })),);-const ModesView = lazyView(() =>- import("@/views/ModesView").then((m) => ({ default: m.ModesView })),-);const ApiKeysView = lazyView(() =>import("@/views/ApiKeysView").then((m) => ({ default: m.ApiKeysView })),);@@ -496,10 +493,6 @@ function SwitchOnActiveSection({ active }: { active: string }) {// AROUND it looks like (see App.tsx).case "visualization":return <VisualizationView />;- // The assistant's character: which mode is active, and the workshop for- // building another one by talking to it.- case "modes":- return <ModesView />;// The marketplace storefront: everything the community published, in one// place, installable without leaving the app.case "marketplace":diff --git a/jarvis/ui/web/frontend/src/components/layout/navGroups.ts b/jarvis/ui/web/frontend/src/components/layout/navGroups.tsindex bf16e6ebb5..6d1d5b85fe 100644--- a/jarvis/ui/web/frontend/src/components/layout/navGroups.ts+++ b/jarvis/ui/web/frontend/src/components/layout/navGroups.ts@@ -1,207 +1,198 @@-/**- * The app's section list — the ONE source of truth for what sections exist.- *- * Extracted from `Sidebar.tsx` so the mission deck can show every section at- * once without pulling the sidebar's own dependency tree (voice hooks, the- * realtime control, provider health) into the entry chunk with it. The deck- * ships in that chunk, and `MainView` keeps it deliberately small.- *- * A second hand-written list anywhere would be the classic drift trap (AP-4):- * a section added here would silently never appear on the deck.- */-import {- BookOpen,- Boxes,- Contact,- Drama,- FolderOpen,- Frame,- Gauge,- KeyRound,- ListTodo,- MessageSquare,- MessageSquareWarning,- MessagesSquare,- Mic,- Notebook,- ScrollText,- Settings,- Share2,- Sparkles,- Store,- Terminal,- UserCircle2,- Users,- Image as ImageIcon,- type LucideIcon,-} from "lucide-react";-import type { SectionId } from "@/store/events";--// Resolve a nav row's label, preferring the active-locale translation and-// falling back to the English `fallbackLabel` when the key is not yet present-// (the i18n resolver returns the key itself on a miss).-export function resolveNavLabel(t: (key: string) => string, item: NavItem): string {- const resolved = t(item.labelKey);- return resolved === item.labelKey && item.fallbackLabel ? item.fallbackLabel : resolved;-}--export interface NavItem {- id: SectionId;- labelKey: string;- icon: LucideIcon;- // When set, the row is highlighted while the active section is any of these- // ids — used by the merged section entries ("Skills & Tools" fronting- // skills/plugins/mcps, "CLIs" fronting clis/cli-test-hub); the active id- // doubles as the tab state.- matchIds?: SectionId[];- // English fallback shown when `labelKey` has no translation yet in the active- // locale (the i18n resolver returns the key itself on a miss).- fallbackLabel?: string;- // Draws a small "Beta" pill after the label — the Agentic IDE runs real- // coding-agent CLIs against the user's own filesystem, which is a step- // riskier than the rest of the app, so the row says so up front.- beta?: boolean;-}---// Sidebar nav, clustered into logical groups separated by a thin divider:-// 1) daily tools 2) content & data 3) configuration 4) social links.-// The render walks the groups in order and draws a separator between them, so-// the order below IS the on-screen order.-//-// Exported because the mission deck shows every section at once and jumps to-// them. A second hand-written list there would be the classic drift trap-// (AP-4): a section added here would silently never appear on the deck.-export const NAV_GROUPS: NavItem[][] = [- // 1) Daily tools — what the user reaches for most often.- [- { id: "chats", labelKey: "nav.chats", icon: MessageSquare },- { id: "agents", labelKey: "nav.agents", icon: Users },- // Skills & Tools — Skills + Plugins + MCPs behind one tab switch. The id- // "skills" is the default landing (Skills tab); matchIds keeps the row- // highlighted for any of the fronted sections.- {- id: "skills",- labelKey: "nav.extensions",- icon: Boxes,- matchIds: ["skills", "plugins", "mcps"],- },- // CLIs — the CLIs list + the CLI Test Hub behind one tab switch (CLIs first).- { id: "clis", labelKey: "nav.clis_hub", icon: Terminal, matchIds: ["clis", "cli-test-hub"] },- // The marketplace. Sits right under Skills & Tools because that is what- // fills those lists: a plugin, a skill or a wallpaper published there ends- // up in one of them once installed. Same Store icon as the badge that- // marks an installed entry, so the mark and its origin read as one thing.- {- id: "marketplace",- labelKey: "nav.marketplace",- icon: Store,- fallbackLabel: "Marketplace",- },- ],- // 2) Content & data — things the user reads, edits, or browses.- [- { id: "tasks", labelKey: "nav.tasks", icon: ListTodo },- { id: "sessions", labelKey: "nav.sessions", icon: Mic },- { id: "run_inspector", labelKey: "nav.run_inspector", icon: Gauge },- // The visual stage. Sits with the content group next to Outputs on- // purpose: it reads the same run archive, it just shows the pictures in it- // instead of listing the files.- {- id: "visualization",- labelKey: "nav.visualization",- icon: Frame,- fallbackLabel: "Visualization",- },- { id: "board", labelKey: "nav.board", icon: Sparkles },- { id: "memory", labelKey: "nav.wiki", icon: Notebook },- { id: "contacts", labelKey: "nav.contacts", icon: Contact },- { id: "profile", labelKey: "nav.profile", icon: UserCircle2 },- {- id: "agent-instructions",- labelKey: "nav.agent_instructions",- icon: ScrollText,- fallbackLabel: "Instructions",- },- { id: "docs", labelKey: "nav.docs", icon: BookOpen },- ],- // 3) Configuration. API Keys now also fronts the former "Telephony" screen —- // the telephony status/credentials/scripts/calls live as a section inside the- // API-Keys view, so matchIds keeps this row highlighted when a "geh zur- // Telefonie" voice command lands on the "telephony" id. Settings likewise- // fronts the former "Taskbar" + "Languages" sections (overlay/dictation- // controls live in OverlayTaskbarGroup, language selectors in LanguagesGroup).- [- {- id: "apikeys",- labelKey: "nav.apikeys",- icon: KeyRound,- matchIds: ["apikeys", "telephony", "telephony-setup"],- },- {- id: "settings",- labelKey: "nav.settings",- icon: Settings,- matchIds: ["settings", "taskbar", "languages"],- },- // The voice section — dictation, the custom vocabulary, the keys that start- // it, the dictation language and the speech-to-text providers — behind one- // tab switch. "dictation" is the default landing; matchIds keeps the row- // highlighted for any of the fronted tabs. The label carries the {name}- // token, so the row reads as the user's own wake-word brand.- {- id: "dictation",- labelKey: "nav.voice",- icon: Mic,- matchIds: [- "dictation",- "dictionary",- "voice-shortcuts",- "voice-language",- "voice-api-keys",- ],- // Name-FREE on purpose: the fallback is rendered verbatim when the key is- // missing from a locale, and it is NOT interpolated.- fallbackLabel: "Voice",- },- { id: "outputs", labelKey: "nav.outputs", icon: FolderOpen },- // The assistant's character. Sits with the configuration group because it- // changes how the assistant behaves everywhere, not what any one page holds.- {- id: "modes",- labelKey: "nav.modes",- icon: Drama,- fallbackLabel: "Modes",- },- // Appearance. Sits with the configuration group rather than with the- // content views: it changes how the app looks, not what it holds.- {- id: "wallpaper",- labelKey: "nav.wallpaper",- icon: ImageIcon,- fallbackLabel: "Wallpaper",- },- ],- // 4) Social links + in-app feedback.- [- { id: "socials", labelKey: "nav.socials", icon: Share2 },- { id: "feedback", labelKey: "nav.feedback", icon: MessageSquareWarning },- ],- // 5) The 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: MessagesSquare,- fallbackLabel: "Agentic IDE",- // The classic grid is the same destination as far as the row is- // concerned: someone who stepped back into it should still see where- // they are in the navigation.- matchIds: ["agentic-ide", "chat-workspace", "agentic-ide-classic"],- beta: true,- },- ],-];+/**+ * The app's section list — the ONE source of truth for what sections exist.+ *+ * Extracted from `Sidebar.tsx` so the mission deck can show every section at+ * once without pulling the sidebar's own dependency tree (voice hooks, the+ * realtime control, provider health) into the entry chunk with it. The deck+ * ships in that chunk, and `MainView` keeps it deliberately small.+ *+ * A second hand-written list anywhere would be the classic drift trap (AP-4):+ * a section added here would silently never appear on the deck.+ */+import {+ BookOpen,+ Boxes,+ Contact,+ FolderOpen,+ Frame,+ Gauge,+ KeyRound,+ ListTodo,+ MessageSquare,+ MessageSquareWarning,+ MessagesSquare,+ Mic,+ Notebook,+ ScrollText,+ Settings,+ Share2,+ Sparkles,+ Store,+ Terminal,+ UserCircle2,+ Users,+ Image as ImageIcon,+ type LucideIcon,+} from "lucide-react";+import type { SectionId } from "@/store/events";++// Resolve a nav row's label, preferring the active-locale translation and+// falling back to the English `fallbackLabel` when the key is not yet present+// (the i18n resolver returns the key itself on a miss).+export function resolveNavLabel(t: (key: string) => string, item: NavItem): string {+ const resolved = t(item.labelKey);+ return resolved === item.labelKey && item.fallbackLabel ? item.fallbackLabel : resolved;+}++export interface NavItem {+ id: SectionId;+ labelKey: string;+ icon: LucideIcon;+ // When set, the row is highlighted while the active section is any of these+ // ids — used by the merged section entries ("Skills & Tools" fronting+ // skills/plugins/mcps, "CLIs" fronting clis/cli-test-hub); the active id+ // doubles as the tab state.+ matchIds?: SectionId[];+ // English fallback shown when `labelKey` has no translation yet in the active+ // locale (the i18n resolver returns the key itself on a miss).+ fallbackLabel?: string;+ // Draws a small "Beta" pill after the label — the Agentic IDE runs real+ // coding-agent CLIs against the user's own filesystem, which is a step+ // riskier than the rest of the app, so the row says so up front.+ beta?: boolean;+}+++// Sidebar nav, clustered into logical groups separated by a thin divider:+// 1) daily tools 2) content & data 3) configuration 4) social links.+// The render walks the groups in order and draws a separator between them, so+// the order below IS the on-screen order.+//+// Exported because the mission deck shows every section at once and jumps to+// them. A second hand-written list there would be the classic drift trap+// (AP-4): a section added here would silently never appear on the deck.+export const NAV_GROUPS: NavItem[][] = [+ // 1) Daily tools — what the user reaches for most often.+ [+ { id: "chats", labelKey: "nav.chats", icon: MessageSquare },+ { id: "agents", labelKey: "nav.agents", icon: Users },+ // Skills & Tools — Skills + Plugins + MCPs behind one tab switch. The id+ // "skills" is the default landing (Skills tab); matchIds keeps the row+ // highlighted for any of the fronted sections.+ {+ id: "skills",+ labelKey: "nav.extensions",+ icon: Boxes,+ matchIds: ["skills", "plugins", "mcps"],+ },+ // CLIs — the CLIs list + the CLI Test Hub behind one tab switch (CLIs first).+ { id: "clis", labelKey: "nav.clis_hub", icon: Terminal, matchIds: ["clis", "cli-test-hub"] },+ // The marketplace. Sits right under Skills & Tools because that is what+ // fills those lists: a plugin, a skill or a wallpaper published there ends+ // up in one of them once installed. Same Store icon as the badge that+ // marks an installed entry, so the mark and its origin read as one thing.+ {+ id: "marketplace",+ labelKey: "nav.marketplace",+ icon: Store,+ fallbackLabel: "Marketplace",+ },+ ],+ // 2) Content & data — things the user reads, edits, or browses.+ [+ { id: "tasks", labelKey: "nav.tasks", icon: ListTodo },+ { id: "sessions", labelKey: "nav.sessions", icon: Mic },+ { id: "run_inspector", labelKey: "nav.run_inspector", icon: Gauge },+ // The visual stage. Sits with the content group next to Outputs on+ // purpose: it reads the same run archive, it just shows the pictures in it+ // instead of listing the files.+ {+ id: "visualization",+ labelKey: "nav.visualization",+ icon: Frame,+ fallbackLabel: "Visualization",+ },+ { id: "board", labelKey: "nav.board", icon: Sparkles },+ { id: "memory", labelKey: "nav.wiki", icon: Notebook },+ { id: "contacts", labelKey: "nav.contacts", icon: Contact },+ { id: "profile", labelKey: "nav.profile", icon: UserCircle2 },+ {+ id: "agent-instructions",+ labelKey: "nav.agent_instructions",+ icon: ScrollText,+ fallbackLabel: "Instructions",+ },+ { id: "docs", labelKey: "nav.docs", icon: BookOpen },+ ],+ // 3) Configuration. API Keys now also fronts the former "Telephony" screen —+ // the telephony status/credentials/scripts/calls live as a section inside the+ // API-Keys view, so matchIds keeps this row highlighted when a "geh zur+ // Telefonie" voice command lands on the "telephony" id. Settings likewise+ // fronts the former "Taskbar" + "Languages" sections (overlay/dictation+ // controls live in OverlayTaskbarGroup, language selectors in LanguagesGroup).+ [+ {+ id: "apikeys",+ labelKey: "nav.apikeys",+ icon: KeyRound,+ matchIds: ["apikeys", "telephony", "telephony-setup"],+ },+ {+ id: "settings",+ labelKey: "nav.settings",+ icon: Settings,+ matchIds: ["settings", "taskbar", "languages"],+ },+ // The voice section — dictation, the custom vocabulary, the keys that start+ // it, the dictation language and the speech-to-text providers — behind one+ // tab switch. "dictation" is the default landing; matchIds keeps the row+ // highlighted for any of the fronted tabs. The label carries the {name}+ // token, so the row reads as the user's own wake-word brand.+ {+ id: "dictation",+ labelKey: "nav.voice",+ icon: Mic,+ matchIds: [+ "dictation",+ "dictionary",+ "voice-shortcuts",+ "voice-language",+ "voice-api-keys",+ ],+ // Name-FREE on purpose: the fallback is rendered verbatim when the key is+ // missing from a locale, and it is NOT interpolated.+ fallbackLabel: "Voice",+ },+ { id: "outputs", labelKey: "nav.outputs", icon: FolderOpen },+ // Appearance. Sits with the configuration group rather than with the+ // content views: it changes how the app looks, not what it holds.+ {+ id: "wallpaper",+ labelKey: "nav.wallpaper",+ icon: ImageIcon,+ fallbackLabel: "Wallpaper",+ },+ ],+ // 4) Social links + in-app feedback.+ [+ { id: "socials", labelKey: "nav.socials", icon: Share2 },+ { id: "feedback", labelKey: "nav.feedback", icon: MessageSquareWarning },+ ],+ // 5) The 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: MessagesSquare,+ fallbackLabel: "Agentic IDE",+ // The classic grid is the same destination as far as the row is+ // concerned: someone who stepped back into it should still see where+ // they are in the navigation.+ matchIds: ["agentic-ide", "chat-workspace", "agentic-ide-classic"],+ beta: true,+ },+ ],+];diff --git a/jarvis/ui/web/frontend/src/i18n/locales/de.json b/jarvis/ui/web/frontend/src/i18n/locales/de.jsonindex 911ab0e965..41967deab4 100644--- a/jarvis/ui/web/frontend/src/i18n/locales/de.json+++ b/jarvis/ui/web/frontend/src/i18n/locales/de.json@@ -101,7 +101,6 @@"feedback": "Feedback","agent_instructions": "{name}.md","wallpaper": "Hintergrund",- "modes": "Modi","marketplace": "Marketplace","agentic_ide": "Agentic IDE","agentic_ide_beta": "Beta",@@ -4738,70 +4737,6 @@"standby_since": "seit {0}","open_board": "Board öffnen"},- "modes_view": {- "title": "Modi",- "subtitle": "Wie sich der Assistent verhält. Gilt für Sprache und Chat ab der nächsten Antwort.",- "override_banner": "{0} ist gerade in Kraft, weil im Agentic IDE der fokussierte Coding-Modus an ist. Deine eigene Wahl, {1}, übernimmt, sobald der Coding-Modus aus ist oder der Workspace geschlossen wird.",- "shelf_title": "Deine Modi",- "shelf_hint": "Klicke auf eine Karte, um alles zu lesen, was der Modus macht. „Verwenden“ schaltet um — für Sprache und Chat, ab der nächsten Antwort.",- "in_use": "In Benutzung",- "in_use_now": "Gerade in Benutzung",- "use": "Verwenden",- "use_named": "{0} verwenden",- "use_this_mode": "Diesen Modus verwenden",- "your_choice": "Deine Wahl",- "switched_waiting": "{0} ist als deine Wahl gespeichert. {1} bleibt in Kraft, bis der Coding-Modus endet.",- "detail_waiting": "Das ist deine Wahl. Sie übernimmt, sobald {0} loslässt — wenn der Coding-Modus aus ist oder der Workspace geschlossen wird.",- "badge_builtin": "Eingebaut",- "badge_builtin_edited": "Eingebaut · von dir bearbeitet",- "badge_yours": "Von dir",- "detail_behaviour": "So verhält er sich",- "detail_empty_character": "Fügt der Basis-Persona nichts hinzu — das ist der Assistent genau so, wie er ausgeliefert wird.",- "detail_voice": "Stimme",- "detail_voice_default": "Die eingestellte Stimme",- "detail_id": "Id",- "length_label": "Antwortlänge",- "volunteers_label": "Wie viel er von sich aus sagt",- "verbosity_brief": "Kurze Antworten",- "verbosity_normal": "Normale Länge",- "verbosity_rich": "Erklärt die Gründe",- "proactivity_reactive": "Beantwortet nur, was gefragt wurde",- "proactivity_normal": "Ausgewogen",- "proactivity_forward": "Denkt einen Schritt voraus",- "edit": "Bearbeiten",- "restore_original": "Original wiederherstellen",- "restore_named": "{0} wiederherstellen",- "delete": "Löschen",- "delete_named": "{0} löschen",- "restored": "{0} wiederhergestellt.",- "deleted": "{0} gelöscht.",- "saved": "{0} gespeichert.",- "needs_name": "Ein Modus braucht einen Namen und eine Beschreibung, wie er sich verhält.",- "build_title": "Modus bauen",- "build_subtitle": "Beschreibe den Assistenten, den du willst, und lass ihn den Modus schreiben — oder füll ihn selbst aus.",- "interview_toast": "Sag, was für einen Assistenten du willst. Den Rest frage ich.",- "interview_start": "Im Gespräch klären",- "interview_end": "Gespräch beenden",- "interview_idle": "Öffnet ein Sprachgespräch. Er interviewt dich und schreibt den Modus dann selbst.",- "interview_live": "Ich höre zu. Beschreibe den Assistenten, den du willst — er fragt den Rest und speichert den Modus, wenn du zustimmst.",- "rather_type": "Lieber tippen?",- "written_placeholder": "Eine Version von dir, die direkt ist und schlechte Nachrichten nie beschönigt…",- "ask_in_chat": "Im Chat fragen",- "chat_not_up": "Die Chat-Verbindung steht noch nicht.",- "editing_title": "{0} bearbeiten",- "editing_hint": "Speichern schreibt deine Änderungen in diesen Modus zurück.",- "editing_hint_builtin": "Speichern legt deine Version auf diese Karte. „Original wiederherstellen“ holt den eingebauten Modus jederzeit zurück.",- "cancel_edit": "Bearbeiten abbrechen",- "emoji_label": "Emoji",- "name_label": "Name des Modus",- "name_placeholder": "Nachteule",- "description_label": "Beschreibung in einer Zeile",- "description_placeholder": "Ruhig und kurz. Fängt spät nichts Neues mehr an.",- "character_label": "So verhält er sich",- "character_placeholder": "Sprich leise. Es ist spät und ich fahre runter…",- "save_mode": "Modus speichern",- "save_changes": "Änderungen speichern"- },"marketplace": {"title": "Marketplace","loading": "Der Marketplace wird geladen…",diff --git a/jarvis/ui/web/frontend/src/i18n/locales/en.json b/jarvis/ui/web/frontend/src/i18n/locales/en.jsonindex 1970c2c7f5..2c00c9556f 100644--- a/jarvis/ui/web/frontend/src/i18n/locales/en.json+++ b/jarvis/ui/web/frontend/src/i18n/locales/en.json@@ -101,7 +101,6 @@"feedback": "Feedback","agent_instructions": "{name}.md","wallpaper": "Wallpaper",- "modes": "Modes","marketplace": "Marketplace","agentic_ide": "Agentic IDE","agentic_ide_beta": "Beta",@@ -4738,70 +4737,6 @@"standby_since": "since {0}","open_board": "Open the board"},- "modes_view": {- "title": "Modes",- "subtitle": "How the assistant behaves. Applies to voice and chat from the next turn.",- "override_banner": "{0} is in force right now because focused coding mode is on in the Agentic IDE. Your own choice, {1}, takes over as soon as coding mode is turned off or the workspace closes.",- "shelf_title": "Your modes",- "shelf_hint": "Click a card to read everything a mode does. “Use” switches to it — in voice and chat, from the next turn.",- "in_use": "In use",- "in_use_now": "In use now",- "use": "Use",- "use_named": "Use {0}",- "use_this_mode": "Use this mode",- "your_choice": "Your choice",- "switched_waiting": "{0} is saved as your choice. {1} stays in force until coding mode ends.",- "detail_waiting": "This is your choice. It takes over as soon as {0} lets go — when coding mode is turned off or the workspace closes.",- "badge_builtin": "Built in",- "badge_builtin_edited": "Built in · edited by you",- "badge_yours": "Yours",- "detail_behaviour": "How it behaves",- "detail_empty_character": "Adds nothing on top of the base persona — this is the assistant exactly as it ships.",- "detail_voice": "Voice",- "detail_voice_default": "The configured voice",- "detail_id": "Id",- "length_label": "Answer length",- "volunteers_label": "How much it volunteers",- "verbosity_brief": "Short answers",- "verbosity_normal": "Normal length",- "verbosity_rich": "Explains the reasoning",- "proactivity_reactive": "Answers only what was asked",- "proactivity_normal": "Balanced",- "proactivity_forward": "Thinks a step ahead",- "edit": "Edit",- "restore_original": "Restore original",- "restore_named": "Restore {0}",- "delete": "Delete",- "delete_named": "Delete {0}",- "restored": "{0} restored.",- "deleted": "{0} deleted.",- "saved": "{0} saved.",- "needs_name": "A mode needs a name and a description of how it behaves.",- "build_title": "Build a mode",- "build_subtitle": "Describe the assistant you want and let it write the mode, or fill it in yourself.",- "interview_toast": "Say what kind of assistant you want. I'll ask the rest.",- "interview_start": "Talk it through",- "interview_end": "End the conversation",- "interview_idle": "Opens a voice conversation. It interviews you, then writes the mode itself.",- "interview_live": "Listening. Describe the assistant you want — it will ask the rest and save the mode when you agree.",- "rather_type": "Rather type it?",- "written_placeholder": "A version of you that is blunt and never softens bad news…",- "ask_in_chat": "Ask in chat",- "chat_not_up": "The chat connection is not up yet.",- "editing_title": "Editing {0}",- "editing_hint": "Saving writes your changes back to this mode.",- "editing_hint_builtin": "Saving keeps your version on this card. “Restore original” brings the built-in back at any time.",- "cancel_edit": "Stop editing",- "emoji_label": "Emoji",- "name_label": "Mode name",- "name_placeholder": "Night Owl",- "description_label": "One-line description",- "description_placeholder": "Quiet and short. Refuses to start new work late.",- "character_label": "How it behaves",- "character_placeholder": "Speak quietly. It is late and I am winding down…",- "save_mode": "Save mode",- "save_changes": "Save changes"- },"marketplace": {"title": "Marketplace","loading": "Loading the marketplace index…",diff --git a/jarvis/ui/web/frontend/src/i18n/locales/es.json b/jarvis/ui/web/frontend/src/i18n/locales/es.jsonindex e09d1cfa3f..99203de95b 100644--- a/jarvis/ui/web/frontend/src/i18n/locales/es.json+++ b/jarvis/ui/web/frontend/src/i18n/locales/es.json@@ -101,7 +101,6 @@"feedback": "Comentarios","agent_instructions": "{name}.md","wallpaper": "Fondo de pantalla",- "modes": "Modos","marketplace": "Marketplace","agentic_ide": "IDE agéntico","agentic_ide_beta": "Beta",@@ -4738,70 +4737,6 @@"standby_since": "desde {0}","open_board": "Abrir el tablero"},- "modes_view": {- "title": "Modos",- "subtitle": "Cómo se comporta el asistente. Se aplica a voz y chat desde la próxima respuesta.",- "override_banner": "{0} está en vigor ahora porque el modo de programación enfocada está activo en el Agentic IDE. Tu propia elección, {1}, tomará el relevo en cuanto se apague el modo de programación o se cierre el espacio de trabajo.",- "shelf_title": "Tus modos",- "shelf_hint": "Haz clic en una tarjeta para leer todo lo que hace un modo. “Usar” cambia a él — en voz y chat, desde la próxima respuesta.",- "in_use": "En uso",- "in_use_now": "En uso ahora",- "use": "Usar",- "use_named": "Usar {0}",- "use_this_mode": "Usar este modo",- "your_choice": "Tu elección",- "switched_waiting": "{0} queda guardado como tu elección. {1} sigue en vigor hasta que termine el modo de programación.",- "detail_waiting": "Esta es tu elección. Tomará el relevo en cuanto {0} lo suelte — cuando se apague el modo de programación o se cierre el espacio de trabajo.",- "badge_builtin": "Integrado",- "badge_builtin_edited": "Integrado · editado por ti",- "badge_yours": "Tuyo",- "detail_behaviour": "Cómo se comporta",- "detail_empty_character": "No añade nada a la persona base — es el asistente exactamente como viene.",- "detail_voice": "Voz",- "detail_voice_default": "La voz configurada",- "detail_id": "Id",- "length_label": "Longitud de las respuestas",- "volunteers_label": "Cuánto aporta por iniciativa propia",- "verbosity_brief": "Respuestas cortas",- "verbosity_normal": "Longitud normal",- "verbosity_rich": "Explica el razonamiento",- "proactivity_reactive": "Responde solo lo que se preguntó",- "proactivity_normal": "Equilibrado",- "proactivity_forward": "Piensa un paso por delante",- "edit": "Editar",- "restore_original": "Restaurar el original",- "restore_named": "Restaurar {0}",- "delete": "Eliminar",- "delete_named": "Eliminar {0}",- "restored": "{0} restaurado.",- "deleted": "{0} eliminado.",- "saved": "{0} guardado.",- "needs_name": "Un modo necesita un nombre y una descripción de cómo se comporta.",- "build_title": "Crear un modo",- "build_subtitle": "Describe el asistente que quieres y deja que él escriba el modo, o rellénalo tú mismo.",- "interview_toast": "Di qué tipo de asistente quieres. Yo pregunto el resto.",- "interview_start": "Hablarlo",- "interview_end": "Terminar la conversación",- "interview_idle": "Abre una conversación de voz. Te entrevista y luego escribe el modo por sí mismo.",- "interview_live": "Escuchando. Describe el asistente que quieres — preguntará el resto y guardará el modo cuando estés de acuerdo.",- "rather_type": "¿Prefieres escribirlo?",- "written_placeholder": "Una versión tuya que es directa y nunca suaviza las malas noticias…",- "ask_in_chat": "Preguntar en el chat",- "chat_not_up": "La conexión del chat aún no está lista.",- "editing_title": "Editando {0}",- "editing_hint": "Guardar escribe tus cambios de vuelta en este modo.",- "editing_hint_builtin": "Guardar deja tu versión en esta tarjeta. “Restaurar el original” recupera el modo integrado en cualquier momento.",- "cancel_edit": "Dejar de editar",- "emoji_label": "Emoji",- "name_label": "Nombre del modo",- "name_placeholder": "Búho nocturno",- "description_label": "Descripción en una línea",- "description_placeholder": "Tranquilo y breve. Se niega a empezar trabajo nuevo tarde.",- "character_label": "Cómo se comporta",- "character_placeholder": "Habla bajo. Es tarde y estoy desconectando…",- "save_mode": "Guardar modo",- "save_changes": "Guardar cambios"- },"marketplace": {"title": "Marketplace","loading": "Cargando el índice del marketplace…",diff --git a/jarvis/ui/web/frontend/src/lib/modesApi.ts b/jarvis/ui/web/frontend/src/lib/modesApi.tsdeleted file mode 100644index 06d51cd3c0..0000000000--- a/jarvis/ui/web/frontend/src/lib/modesApi.ts+++ /dev/null@@ -1,113 +0,0 @@-/**- * Client for /api/modes — the assistant's shelf of characters.- *- * A mode changes how Jarvis behaves in voice AND in chat from the next turn on,- * with no restart, because both brains read the persona through one function on- * the backend. Nothing here needs to know that; it matters only in that a- * switch is a single call and the UI never has to tell the user to restart.- */--/** Layer 4 of the five-layer enum pattern — mirrors `modes.VERBOSITIES`. */-export type Verbosity = "brief" | "normal" | "rich";-/** Mirrors `modes.PROACTIVITIES`. */-export type Proactivity = "reactive" | "normal" | "forward";--export interface AssistantMode {- slug: string;- name: string;- emoji: string;- description: string;- /** How the assistant behaves — appended to the base persona, never replacing it. */- character: string;- built_in: boolean;- /** A built-in the user has overlaid with their own file — "restore" is real. */- edited: boolean;- voice: string;- verbosity: Verbosity;- proactivity: Proactivity;-}--export interface ModesState {- modes: AssistantMode[];- /** The mode IN FORCE for the next turn — a section override wins here. */- active: string;- /**- * The user's own, stored choice. Equal to `active` unless a section override- * is in force; then it is the only proof the shelf has that a switch was- * saved rather than swallowed.- */- chosen: string;- /**- * A mode a SCREEN switched on (today: the Agentic IDE), which outranks the- * user's own choice while it lasts. Surfaced so the UI can say why the active- * card is not the one the user picked — an unexplained mode is exactly what- * this feature was built to replace.- */- section_override: string;- verbosities: Verbosity[];- proactivities: Proactivity[];-}--async function readJson<T>(res: Response): Promise<T> {- if (!res.ok) {- // FastAPI puts the human-readable reason in `detail`; surfacing it beats a- // bare status code, because every failure here has a specific cause the- // user can act on ("that is a built-in mode", "that looks like a path").- let detail = `${res.status} ${res.statusText}`;- try {- const body = (await res.json()) as { detail?: string };- if (body?.detail) detail = body.detail;- } catch {- /* a non-JSON error body leaves the status line as the message */- }- throw new Error(detail);- }- return (await res.json()) as T;-}--export async function fetchModes(): Promise<ModesState> {- return readJson<ModesState>(await fetch("/api/modes"));-}--export async function activateMode(slug: string): Promise<ModesState> {- return readJson<ModesState>(- await fetch("/api/modes/active", {- method: "PUT",- headers: { "Content-Type": "application/json" },- body: JSON.stringify({ slug }),- }),- );-}--export interface ModeDraft {- slug?: string;- name: string;- character: string;- emoji?: string;- description?: string;- voice?: string;- verbosity?: Verbosity;- proactivity?: Proactivity;-}--export async function saveMode(draft: ModeDraft): Promise<ModesState> {- return readJson<ModesState>(- await fetch("/api/modes", {- method: "POST",- headers: { "Content-Type": "application/json" },- body: JSON.stringify(draft),- }),- );-}--export async function deleteMode(slug: string): Promise<ModesState> {- return readJson<ModesState>(- await fetch(`/api/modes/${encodeURIComponent(slug)}`, { method: "DELETE" }),- );-}--export async function restoreBuiltin(slug: string): Promise<ModesState> {- return readJson<ModesState>(- await fetch(`/api/modes/${encodeURIComponent(slug)}/restore`, { method: "POST" }),- );-}diff --git a/jarvis/ui/web/frontend/src/store/events.ts b/jarvis/ui/web/frontend/src/store/events.tsindex cd55053e95..bba0bd8bdc 100644--- a/jarvis/ui/web/frontend/src/store/events.ts+++ b/jarvis/ui/web/frontend/src/store/events.ts@@ -88,8 +88,6 @@ export type SectionId =// so the grid needs an id of its own — it still holds live panes and must// stay reachable while the new surface grows into full parity.| "agentic-ide-classic"- // The assistant's character: pick a mode, or build one by talking to it.- | "modes"// The Jarvis Marketplace, in the app: everything the community published —// plugins, skills and wallpapers — browsable and installable in one place// instead of scattered across three unrelated sections.@@ -134,7 +132,6 @@ export const SECTION_IDS = ["agentic-ide","chat-workspace","agentic-ide-classic",- "modes","marketplace",] as const satisfies readonly SectionId[];@@ -202,7 +199,6 @@ export const SECTION_LABELS: Record<SectionId, string> = {"agentic-ide": "Agentic IDE","chat-workspace": "Chat","agentic-ide-classic": "Terminal grid",- modes: "Modes",marketplace: "Marketplace",};diff --git a/jarvis/ui/web/frontend/src/views/ModesView.test.tsx b/jarvis/ui/web/frontend/src/views/ModesView.test.tsxdeleted file mode 100644index 0ad160e2db..0000000000--- a/jarvis/ui/web/frontend/src/views/ModesView.test.tsx+++ /dev/null@@ -1,282 +0,0 @@-/**- * Component tests for ModesView — the shelf of characters.- *- * Pinned here is what a user noticed was missing: a card can be OPENED to read- * everything the mode does (the full character text, not the one-liner), a mode- * can be switched with one explicit click, and while the Agentic IDE holds the- * persona the screen tells the truth — the click was stored (chosen) even though- * something else is in force (active) — instead of looking broken.- *- * Driven through a stateful fetch fake, so a switch and the re-read that- * follows agree with each other. No jest-dom in this repo — assertions use- * toBeTruthy()/toBeNull().- */-import { afterEach, beforeEach, describe, expect, it, vi } from "vitest";-import { cleanup, fireEvent, render, screen, waitFor, within } from "@testing-library/react";--// ViewHeader lives in ChatsView, which drags in the whole chat surface; the-// view only needs its shape.-vi.mock("@/views/ChatsView", () => ({- ViewHeader: ({ title }: { title: string }) => <header>{title}</header>,-}));--// The voice interview button needs a call controller; none of these tests-// start a call, so a quiet stub keeps the realtime stack out of the render.-vi.mock("@/components/agentic/useVoiceCall", () => ({- useVoiceCall: () => ({- active: false,- busy: false,- connecting: false,- toggleCall: vi.fn(async () => undefined),- voiceState: "idle",- }),-}));--import { ModesView } from "@/views/ModesView";-import { setUiLanguage } from "@/i18n";-import { useEventStore } from "@/store/events";-import type { AssistantMode } from "@/lib/modesApi";--const MODES: AssistantMode[] = [- {- slug: "assistant",- name: "Assistant",- emoji: "🎩",- description: "Precise and quiet.",- character: "",- built_in: true,- edited: false,- voice: "",- verbosity: "normal",- proactivity: "normal",- },- {- slug: "friend",- name: "Friend",- emoji: "🫂",- description: "Warm and casual.",- character: "You are talking to a friend, not serving a client.\n\nDrop the deference.",- built_in: true,- edited: false,- voice: "",- verbosity: "normal",- proactivity: "normal",- },- {- slug: "coding",- name: "Coding",- emoji: "💻",- description: "Terminal-aware.",- character: "The user is working in the Agentic IDE.",- built_in: true,- edited: false,- voice: "",- verbosity: "normal",- proactivity: "normal",- },- {- slug: "night-owl",- name: "Night Owl",- emoji: "🦉",- description: "Quiet and short.",- character: "Speak quietly. It is late.",- built_in: false,- edited: false,- voice: "nova",- verbosity: "brief",- proactivity: "reactive",- },-];--interface Call {- url: string;- method: string;- body: unknown;-}--/**- * A stand-in for /api/modes that keeps the one bit of state that matters: the- * user's stored choice, and — optionally — a section override that outranks it,- * exactly the way the backend's `active_slug()` composes the two.- */-function stubServer(opts: { chosen?: string; override?: string } = {}) {- const state = { chosen: opts.chosen ?? "assistant", override: opts.override ?? "" };- const calls: Call[] = [];- const payload = () => ({- modes: MODES,- active: state.override || state.chosen,- chosen: state.chosen,- section_override: state.override,- verbosities: ["brief", "normal", "rich"],- proactivities: ["reactive", "normal", "forward"],- });- const json = (body: unknown, status = 200) => ({- ok: status >= 200 && status < 300,- status,- statusText: "OK",- json: async () => body,- });-- vi.stubGlobal(- "fetch",- vi.fn(async (input: RequestInfo | URL, init?: RequestInit) => {- const url = String(input);- const method = (init?.method ?? "GET").toUpperCase();- const body = init?.body ? JSON.parse(init.body as string) : null;- calls.push({ url, method, body });- if (url === "/api/modes" && method === "GET") return json(payload());- if (url === "/api/modes/active" && method === "PUT") {- state.chosen = (body as { slug: string }).slug;- return json({ ok: true, ...payload(), chosen: state.chosen, restart_required: false });- }- if (url === "/api/modes" && method === "POST") return json({ ok: true, ...payload() });- return json({ detail: `unexpected ${method} ${url}` }, 404);- }),- );- return { calls, state };-}--beforeEach(() => {- setUiLanguage("en");- useEventStore.setState({ toasts: [] });-});--afterEach(() => {- cleanup();- vi.unstubAllGlobals();-});--async function renderView() {- render(<ModesView />);- await waitFor(() => expect(screen.getByTestId("mode-card-friend")).toBeTruthy());-}--describe("ModesView — reading a mode", () => {- it("opens with the mode in force and shows its full character text", async () => {- stubServer({ chosen: "friend" });- await renderView();-- const detail = screen.getByTestId("mode-detail");- expect(within(detail).getByText("Friend")).toBeTruthy();- // The full text, verbatim — not the one-line description.- expect(screen.getByTestId("mode-detail-character").textContent).toContain(- "You are talking to a friend, not serving a client.",- );- expect(within(detail).getByText("In use now")).toBeTruthy();- });-- it("clicking a card opens it without switching to it", async () => {- const server = stubServer({ chosen: "assistant" });- await renderView();-- fireEvent.click(screen.getByTestId("mode-card-night-owl"));-- const detail = screen.getByTestId("mode-detail");- expect(within(detail).getByText("Night Owl")).toBeTruthy();- expect(screen.getByTestId("mode-detail-character").textContent).toContain(- "Speak quietly. It is late.",- );- // The knobs and the voice are spelled out, not just the description.- expect(within(detail).getByText("Short answers")).toBeTruthy();- expect(within(detail).getByText("Answers only what was asked")).toBeTruthy();- expect(within(detail).getByText("nova")).toBeTruthy();- expect(within(detail).getByText("Yours")).toBeTruthy();- // Reading is not choosing: nothing was written.- expect(server.calls.filter((c) => c.method === "PUT")).toHaveLength(0);- expect(server.state.chosen).toBe("assistant");- });-- it("states that the default mode adds nothing rather than showing a blank box", async () => {- stubServer({ chosen: "assistant" });- await renderView();- expect(screen.getByTestId("mode-detail-character").textContent).toContain(- "Adds nothing on top of the base persona",- );- });-});--describe("ModesView — switching", () => {- it("the card's Use switches with one click and the shelf follows", async () => {- const server = stubServer({ chosen: "assistant" });- await renderView();-- fireEvent.click(screen.getByTestId("mode-use-friend"));-- await waitFor(() => expect(server.state.chosen).toBe("friend"));- const put = server.calls.find((c) => c.method === "PUT");- expect(put?.url).toBe("/api/modes/active");- expect(put?.body).toEqual({ slug: "friend" });- await waitFor(() =>- expect(screen.getByTestId("mode-card-friend").getAttribute("data-active")).toBe("true"),- );- expect(screen.getByTestId("mode-card-assistant").getAttribute("data-active")).toBeNull();- // The card in use offers no second "Use".- expect(screen.queryByTestId("mode-use-friend")).toBeNull();- expect(screen.getByTestId("mode-use-assistant")).toBeTruthy();- });-- it("the open panel's Use switches too", async () => {- const server = stubServer({ chosen: "assistant" });- await renderView();-- fireEvent.click(screen.getByTestId("mode-card-night-owl"));- fireEvent.click(screen.getByTestId("mode-detail-use"));-- await waitFor(() => expect(server.state.chosen).toBe("night-owl"));- await waitFor(() =>- expect(within(screen.getByTestId("mode-detail")).getByText("In use now")).toBeTruthy(),- );- });-});--describe("ModesView — while the Agentic IDE holds the persona", () => {- it("says which mode is in force, and that the click was stored", async () => {- const server = stubServer({ chosen: "assistant", override: "coding" });- await renderView();-- const banner = screen.getByTestId("mode-override-banner");- expect(banner.textContent).toContain("Coding is in force");- expect(banner.textContent).toContain("Your own choice, Assistant");- expect(screen.getByTestId("mode-card-coding").getAttribute("data-active")).toBe("true");-- fireEvent.click(screen.getByTestId("mode-use-friend"));- await waitFor(() => expect(server.state.chosen).toBe("friend"));-- // Coding stays in force — but the shelf now shows Friend as the stored- // choice, and a toast says so, instead of the click vanishing.- await waitFor(() =>- expect(within(screen.getByTestId("mode-card-friend")).getByText("Your choice")).toBeTruthy(),- );- expect(screen.getByTestId("mode-card-coding").getAttribute("data-active")).toBe("true");- expect(screen.getByTestId("mode-override-banner").textContent).toContain(- "Your own choice, Friend",- );- const toasts = useEventStore.getState().toasts;- expect(toasts.some((t) => t.message.includes("Friend is saved as your choice"))).toBe(true);- });-});--describe("ModesView — editing", () => {- it("Edit loads the mode into the form and saves it back under the same id", async () => {- const server = stubServer({ chosen: "assistant" });- await renderView();-- fireEvent.click(screen.getByTestId("mode-card-night-owl"));- fireEvent.click(screen.getByTestId("mode-detail-edit"));-- const form = screen.getByTestId("mode-form");- expect(within(form).getByText("Editing Night Owl")).toBeTruthy();- const character = within(form).getByLabelText("How it behaves") as HTMLTextAreaElement;- expect(character.value).toBe("Speak quietly. It is late.");-- fireEvent.change(character, { target: { value: "Speak quietly. It is very late." } });- fireEvent.click(screen.getByTestId("mode-save-button"));-- await waitFor(() => expect(server.calls.some((c) => c.method === "POST")).toBe(true));- const post = server.calls.find((c) => c.method === "POST")?.body as Record<string, unknown>;- expect(post.slug).toBe("night-owl");- expect(post.name).toBe("Night Owl");- expect(post.character).toBe("Speak quietly. It is very late.");- expect(post.voice).toBe("nova");- });-});diff --git a/jarvis/ui/web/frontend/src/views/ModesView.tsx b/jarvis/ui/web/frontend/src/views/ModesView.tsxdeleted file mode 100644index a0a570f3a8..0000000000--- a/jarvis/ui/web/frontend/src/views/ModesView.tsx+++ /dev/null@@ -1,757 +0,0 @@-/**- * Modes — pick the character the assistant answers in, or build a new one.- *- * Three parts, in the order the decision actually gets made: the shelf you- * choose from, the open card that shows EVERYTHING a mode does, and the- * workshop where you make (or change) one. Switching applies from the next turn- * in voice AND in chat, with no restart, because both brains read the persona- * through one function on the backend.- *- * Reading and choosing are two different clicks, on purpose. Clicking a card- * opens it below the shelf — the full character text, the knobs, the voice —- * without touching what the assistant is running, so you can read Coach without- * becoming Coach. Every card and the open panel carry an explicit "Use" so the- * switch is still one click and never a hidden gesture; the first version hid- * "restore" behind a hover and nobody found it.- *- * Two facts, shown apart: what is IN FORCE and what the user CHOSE. They differ- * while the Agentic IDE's coding mode overrides the persona, and a screen that- * only knows the first cannot even confirm that a click did anything.- *- * The workshop offers two ways in, because describing a personality out loud- * and typing one are genuinely different tasks. "Talk it through" opens a real- * voice conversation: the assistant interviews you and writes the mode itself- * with its `save_mode` tool. The written path hands the same job to the chat.- * The form is also the editor: "Edit" on any card loads it there, and saving- * writes it back under the same id (a built-in keeps its "restore original").- *- * Colours come from theme tokens only, so the view is correct in light and dark- * without a second palette to keep in step.- */-import { useCallback, useEffect, useMemo, useRef, useState } from "react";-import {- Check,- Loader2,- Mic,- MicOff,- Pencil,- Plus,- RotateCcw,- Sparkles,- Trash2,- X,-} from "lucide-react";--import { ViewHeader } from "@/views/ChatsView";-import { useEventStore } from "@/store/events";-import { useVoiceCall } from "@/components/agentic/useVoiceCall";-import { BrandedSelect } from "@/components/ui/select";-import { useT } from "@/i18n";-import { sendChatMessage } from "@/lib/chat";-import { cn } from "@/lib/utils";-import {- activateMode,- deleteMode,- fetchModes,- restoreBuiltin,- saveMode,- type AssistantMode,- type ModeDraft,- type ModesState,- type Proactivity,- type Verbosity,-} from "@/lib/modesApi";--/**- * What the assistant is told when the user asks for an interview.- *- * Deliberately an instruction to ASK rather than to produce: handed "build me a- * friendly mode", a model writes one immediately and the user gets whatever it- * guessed. The point of the interview is that the questions surface the things- * people do not think to say — whether they want to be disagreed with, what the- * assistant should never do, how it should open a conversation.- */-const INTERVIEW_BRIEF =- "I want to create a new assistant mode — a character for you to answer in. " +- "Interview me first: ask me one question at a time about how you should " +- "behave. How should you greet me? Should you have opinions and disagree with " +- "me? How long should your answers be? Should you ask about my day, or stay " +- "on the task? What should you never do? When you have enough, read the mode " +- "back to me in a sentence and save it with the save_mode tool.";--/** i18n keys for the two knobs — layer 4 of the five-layer enum pattern. */-const VERBOSITY_KEYS: Record<Verbosity, string> = {- brief: "modes_view.verbosity_brief",- normal: "modes_view.verbosity_normal",- rich: "modes_view.verbosity_rich",-};--const PROACTIVITY_KEYS: Record<Proactivity, string> = {- reactive: "modes_view.proactivity_reactive",- normal: "modes_view.proactivity_normal",- forward: "modes_view.proactivity_forward",-};--interface Draft extends ModeDraft {- name: string;- emoji: string;- description: string;- character: string;- verbosity: Verbosity;- proactivity: Proactivity;-}--const EMPTY_DRAFT: Draft = {- name: "",- emoji: "",- description: "",- character: "",- verbosity: "normal",- proactivity: "normal",-};--function fill(template: string, ...values: string[]): string {- return values.reduce((text, value, i) => text.replace(`{${i}}`, value), template);-}--export function ModesView() {- const t = useT();- const pushToast = useEventStore((s) => s.pushToast);- const setActiveSection = useEventStore((s) => s.setActiveSection);- const { active: voiceLive, busy: voiceBusy, connecting, toggleCall } = useVoiceCall();-- const [state, setState] = useState<ModesState | null>(null);- const [loading, setLoading] = useState(true);- const [switching, setSwitching] = useState("");- const [viewing, setViewing] = useState<string | null>(null);- const [draft, setDraft] = useState<Draft>(EMPTY_DRAFT);- const [saving, setSaving] = useState(false);- const [written, setWritten] = useState("");- const formRef = useRef<HTMLElement>(null);-- const refresh = useCallback(async () => {- try {- setState(await fetchModes());- } catch {- // Backend still warming, or headless. Keep whatever we had: blanking the- // shelf on a hiccup would claim the user has no modes, which is a claim- // about their setup rather than about this one failed read.- } finally {- setLoading(false);- }- }, []);-- useEffect(() => {- void refresh();- }, [refresh]);-- /*- * While a voice interview is running, watch for the mode it creates.- *- * The assistant saves through its own tool, not through this screen, so there- * is no response here to react to. Polling is confined to exactly that window- * — a call in progress — rather than running for the whole session, which is- * how a background refresh quietly becomes a per-second request forever.- */- useEffect(() => {- if (!voiceLive) return;- const timer = setInterval(() => void refresh(), 4000);- return () => clearInterval(timer);- }, [voiceLive, refresh]);-- const modes = useMemo(() => state?.modes ?? [], [state]);- const active = state?.active ?? "";- const chosen = state?.chosen ?? active;- const override = state?.section_override ?? "";- const nameOf = (slug: string) => modes.find((m) => m.slug === slug)?.name ?? slug;-- // The open card: what the user clicked, else the mode in force. Never a mode- // that has since been deleted — that panel would describe a ghost.- const shown = useMemo(() => {- const wanted = viewing && modes.some((m) => m.slug === viewing) ? viewing : active;- return modes.find((m) => m.slug === wanted) ?? null;- }, [modes, viewing, active]);-- const choose = async (mode: AssistantMode) => {- setSwitching(mode.slug);- try {- const next = await activateMode(mode.slug);- setState(next);- if (next.section_override && next.active !== mode.slug) {- // The click DID something — it is stored — but nothing on the shelf- // moves. Say so, or the user learns that the screen is broken.- pushToast("info", fill(t("modes_view.switched_waiting"), mode.name, nameOf(next.active)));- }- } catch (e) {- pushToast("error", (e as Error).message);- } finally {- setSwitching("");- }- };-- const remove = async (mode: AssistantMode) => {- try {- setState(mode.built_in ? await restoreBuiltin(mode.slug) : await deleteMode(mode.slug));- pushToast(- "success",- fill(t(mode.built_in ? "modes_view.restored" : "modes_view.deleted"), mode.name),- );- if (draft.slug === mode.slug) setDraft(EMPTY_DRAFT);- } catch (e) {- pushToast("error", (e as Error).message);- }- };-- const startEditing = (mode: AssistantMode) => {- setDraft({- slug: mode.slug,- name: mode.name,- emoji: mode.emoji,- description: mode.description,- character: mode.character,- voice: mode.voice,- verbosity: mode.verbosity,- proactivity: mode.proactivity,- });- // The form is below the fold on most screens; an "Edit" that visibly does- // nothing reads as broken.- formRef.current?.scrollIntoView?.({ behavior: "smooth", block: "start" });- };-- const editing = draft.slug ? modes.find((m) => m.slug === draft.slug) ?? null : null;-- const create = async () => {- if (!draft.name.trim() || !draft.character.trim()) {- pushToast("warning", t("modes_view.needs_name"));- return;- }- setSaving(true);- try {- setState(await saveMode(draft));- pushToast("success", fill(t("modes_view.saved"), draft.name));- if (draft.slug) setViewing(draft.slug);- setDraft(EMPTY_DRAFT);- } catch (e) {- pushToast("error", (e as Error).message);- } finally {- setSaving(false);- }- };-- const startInterview = async () => {- // Ending a call needs no brief — only the opening of one does.- if (!voiceLive) pushToast("info", t("modes_view.interview_toast"));- await toggleCall();- };-- const describeInWriting = async () => {- const text = written.trim();- if (!text) return;- const sent = await sendChatMessage(`${INTERVIEW_BRIEF}\n\nTo start: ${text}`);- if (!sent) {- pushToast("error", t("modes_view.chat_not_up"));- return;- }- setWritten("");- // The conversation happens in Chats, so go where the answer will appear- // rather than leaving the user watching a screen that will not change.- setActiveSection("chats");- };-- const fieldClass =- "rounded-lg border border-border bg-background px-3 py-2 text-sm outline-none focus:border-primary";-- return (- <div className="flex h-full flex-col overflow-y-auto">- <ViewHeader- icon={<Sparkles className="h-4 w-4 text-muted-foreground" />}- title={t("modes_view.title")}- subtitle={t("modes_view.subtitle")}- />-- {loading ? (- <div className="flex flex-1 items-center justify-center">- <Loader2 className="h-5 w-5 animate-spin text-muted-foreground" />- </div>- ) : (- <div className="flex flex-col gap-8 px-6 py-6">- {override && (- <p- data-testid="mode-override-banner"- className="rounded-lg border border-border bg-secondary/40 px-4 py-3 text-sm text-muted-foreground"- >- {fill(t("modes_view.override_banner"), nameOf(override), nameOf(chosen))}- </p>- )}-- <section className="flex flex-col gap-3">- <div>- <h3 className="font-display text-sm font-semibold tracking-tight">- {t("modes_view.shelf_title")}- </h3>- <p className="mt-1 text-sm text-muted-foreground">{t("modes_view.shelf_hint")}</p>- </div>- <div className="grid gap-3 sm:grid-cols-2 lg:grid-cols-3">- {modes.map((mode) => {- const isActive = mode.slug === active;- const isChosen = mode.slug === chosen && !isActive;- const isShown = shown?.slug === mode.slug;- return (- <button- key={mode.slug}- type="button"- onClick={() => setViewing(mode.slug)}- aria-pressed={isShown}- data-testid={`mode-card-${mode.slug}`}- data-active={isActive || undefined}- className={cn(- "group relative flex flex-col gap-2 rounded-xl border p-4 text-left transition-colors",- isActive- ? "border-primary bg-primary/10"- : isChosen- ? "border-dashed border-primary/60 bg-secondary/30 hover:bg-secondary/60"- : "border-border bg-secondary/30 hover:bg-secondary/60",- isShown && "ring-2 ring-primary/50",- )}- >- <div className="flex items-center gap-2 pr-6">- <span className="text-lg leading-none">{mode.emoji || "•"}</span>- <span className="font-medium">{mode.name}</span>- </div>- <p className="text-sm text-muted-foreground">{mode.description}</p>- <div className="mt-1 flex items-center gap-2 text-xs text-muted-foreground">- <span>{t(VERBOSITY_KEYS[mode.verbosity])}</span>- <span aria-hidden>·</span>- <span>{t(PROACTIVITY_KEYS[mode.proactivity])}</span>- <span className="ml-auto">- {isActive ? (- <span className="flex items-center gap-1 font-medium text-primary">- <Check className="h-3.5 w-3.5" />- {t("modes_view.in_use")}- </span>- ) : switching === mode.slug ? (- <Loader2 className="h-3.5 w-3.5 animate-spin" />- ) : (- <span- role="button"- tabIndex={0}- data-testid={`mode-use-${mode.slug}`}- aria-label={fill(t("modes_view.use_named"), mode.name)}- onClick={(e) => {- e.stopPropagation();- if (!switching) void choose(mode);- }}- onKeyDown={(e) => {- if (e.key !== "Enter" && e.key !== " ") return;- e.stopPropagation();- e.preventDefault();- if (!switching) void choose(mode);- }}- className={cn(- "rounded-md border px-2 py-0.5 font-medium transition-colors",- isChosen- ? "border-primary/60 text-primary"- : "border-border text-foreground hover:border-primary hover:bg-primary hover:text-primary-foreground",- )}- >- {isChosen ? t("modes_view.your_choice") : t("modes_view.use")}- </span>- )}- </span>- </div>- {/*- Built-ins offer "restore", user modes offer "delete" — the- same button position, because to the user both mean "undo- what I did to this card". Hidden until hover here; the open- panel below shows the same action in plain sight.- */}- {(mode.built_in ? mode.edited : true) && (- <span- role="button"- tabIndex={0}- aria-label={fill(- t(mode.built_in ? "modes_view.restore_named" : "modes_view.delete_named"),- mode.name,- )}- onClick={(e) => {- e.stopPropagation();- void remove(mode);- }}- onKeyDown={(e) => {- if (e.key !== "Enter" && e.key !== " ") return;- e.stopPropagation();- e.preventDefault();- void remove(mode);- }}- className="absolute right-3 top-3 hidden rounded p-1 text-muted-foreground hover:bg-destructive/20 hover:text-destructive group-hover:block"- >- {mode.built_in ? (- <RotateCcw className="h-3.5 w-3.5" />- ) : (- <Trash2 className="h-3.5 w-3.5" />- )}- </span>- )}- </button>- );- })}- </div>-- {shown && (- <ModeDetail- mode={shown}- isActive={shown.slug === active}- isChosen={shown.slug === chosen}- overrideName={override ? nameOf(override) : ""}- switching={switching === shown.slug}- onUse={() => void choose(shown)}- onEdit={() => startEditing(shown)}- onRemove={() => void remove(shown)}- />- )}- </section>-- <section className="flex flex-col gap-4" ref={formRef}>- <div>- <h3 className="font-display text-sm font-semibold tracking-tight">- {t("modes_view.build_title")}- </h3>- <p className="mt-1 text-sm text-muted-foreground">{t("modes_view.build_subtitle")}</p>- </div>-- <div className="grid gap-4 lg:grid-cols-2">- <div className="flex flex-col gap-3 rounded-xl border border-border bg-secondary/30 p-4">- <button- type="button"- onClick={() => void startInterview()}- disabled={voiceBusy || connecting}- data-testid="mode-interview-button"- className={cn(- "flex items-center justify-center gap-2 rounded-lg px-4 py-3 font-medium transition-colors",- voiceLive- ? "bg-destructive/15 text-destructive hover:bg-destructive/25"- : "bg-primary text-primary-foreground hover:opacity-90",- (voiceBusy || connecting) && "opacity-60",- )}- >- {connecting ? (- <Loader2 className="h-4 w-4 animate-spin" />- ) : voiceLive ? (- <MicOff className="h-4 w-4" />- ) : (- <Mic className="h-4 w-4" />- )}- {voiceLive ? t("modes_view.interview_end") : t("modes_view.interview_start")}- </button>- <p className="text-sm text-muted-foreground">- {voiceLive ? t("modes_view.interview_live") : t("modes_view.interview_idle")}- </p>-- <div className="mt-2 flex flex-col gap-2 border-t border-border pt-3">- <label className="text-xs font-medium text-muted-foreground" htmlFor="mode-written">- {t("modes_view.rather_type")}- </label>- <textarea- id="mode-written"- value={written}- onChange={(e) => setWritten(e.target.value)}- rows={3}- placeholder={t("modes_view.written_placeholder")}- className={cn(fieldClass, "resize-none")}- />- <button- type="button"- onClick={() => void describeInWriting()}- disabled={!written.trim()}- className="self-start rounded-lg border border-border px-3 py-1.5 text-sm hover:bg-secondary/60 disabled:opacity-50"- >- {t("modes_view.ask_in_chat")}- </button>- </div>- </div>-- <div- className={cn(- "flex flex-col gap-3 rounded-xl border bg-secondary/30 p-4",- editing ? "border-primary/60" : "border-border",- )}- data-testid="mode-form"- >- {editing && (- <div className="flex items-start justify-between gap-3 rounded-lg bg-primary/10 px-3 py-2 text-sm">- <div>- <div className="font-medium">- {fill(t("modes_view.editing_title"), editing.name)}- </div>- <div className="text-xs text-muted-foreground">- {t(- editing.built_in- ? "modes_view.editing_hint_builtin"- : "modes_view.editing_hint",- )}- </div>- </div>- <button- type="button"- onClick={() => setDraft(EMPTY_DRAFT)}- aria-label={t("modes_view.cancel_edit")}- title={t("modes_view.cancel_edit")}- className="rounded p-1 text-muted-foreground hover:bg-secondary hover:text-foreground"- >- <X className="h-4 w-4" />- </button>- </div>- )}- <div className="flex gap-2">- <input- aria-label={t("modes_view.emoji_label")}- value={draft.emoji}- onChange={(e) => setDraft({ ...draft, emoji: e.target.value })}- placeholder="🦉"- className={cn(fieldClass, "w-16 text-center")}- />- <input- aria-label={t("modes_view.name_label")}- value={draft.name}- onChange={(e) => setDraft({ ...draft, name: e.target.value })}- placeholder={t("modes_view.name_placeholder")}- className={cn(fieldClass, "flex-1")}- />- </div>- <input- aria-label={t("modes_view.description_label")}- value={draft.description}- onChange={(e) => setDraft({ ...draft, description: e.target.value })}- placeholder={t("modes_view.description_placeholder")}- className={fieldClass}- />- <textarea- aria-label={t("modes_view.character_label")}- value={draft.character}- onChange={(e) => setDraft({ ...draft, character: e.target.value })}- rows={editing ? 12 : 5}- placeholder={t("modes_view.character_placeholder")}- className={cn(fieldClass, "resize-y")}- />- <div className="flex flex-wrap gap-2">- <BrandedSelect- ariaLabel={t("modes_view.length_label")}- value={draft.verbosity}- onValueChange={(v) => setDraft({ ...draft, verbosity: v as Verbosity })}- className="min-w-[180px]"- options={(state?.verbosities ?? []).map((v) => ({- value: v,- label: t(VERBOSITY_KEYS[v]),- }))}- />- <BrandedSelect- ariaLabel={t("modes_view.volunteers_label")}- value={draft.proactivity}- onValueChange={(p) => setDraft({ ...draft, proactivity: p as Proactivity })}- className="min-w-[220px]"- options={(state?.proactivities ?? []).map((p) => ({- value: p,- label: t(PROACTIVITY_KEYS[p]),- }))}- />- </div>- <button- type="button"- onClick={() => void create()}- disabled={saving}- data-testid="mode-save-button"- className="flex items-center justify-center gap-2 self-start rounded-lg bg-primary px-4 py-2 text-sm font-medium text-primary-foreground hover:opacity-90 disabled:opacity-60"- >- {saving ? (- <Loader2 className="h-4 w-4 animate-spin" />- ) : editing ? (- <Pencil className="h-4 w-4" />- ) : (- <Plus className="h-4 w-4" />- )}- {editing ? t("modes_view.save_changes") : t("modes_view.save_mode")}- </button>- </div>- </div>- </section>- </div>- )}- </div>- );-}--interface ModeDetailProps {- mode: AssistantMode;- isActive: boolean;- isChosen: boolean;- /** Name of the mode a section is holding in force, or "" when none is. */- overrideName: string;- switching: boolean;- onUse: () => void;- onEdit: () => void;- onRemove: () => void;-}--/**- * The open card: everything a mode does, in plain sight.- *- * The full character text is the point — it is what the assistant actually- * reads — so it gets the room, verbatim and unabridged. The empty character of- * the default mode is stated as such rather than shown as a blank box, because- * "adds nothing" is a fact about that mode, not a missing value.- */-function ModeDetail({- mode,- isActive,- isChosen,- overrideName,- switching,- onUse,- onEdit,- onRemove,-}: ModeDetailProps) {- const t = useT();- const buttonClass =- "flex items-center gap-1.5 rounded-lg border px-3 py-1.5 text-sm transition-colors disabled:opacity-60";- return (- <div- data-testid="mode-detail"- className="mt-2 flex flex-col gap-4 rounded-xl border border-border bg-secondary/20 p-5"- >- <div className="flex flex-wrap items-start justify-between gap-3">- <div className="flex min-w-0 items-start gap-3">- <span className="text-2xl leading-none">{mode.emoji || "•"}</span>- <div className="min-w-0">- <div className="flex flex-wrap items-center gap-2">- <h4 className="font-display text-base font-semibold tracking-tight">{mode.name}</h4>- <span className="rounded-md border border-border px-1.5 py-0.5 text-[11px] text-muted-foreground">- {mode.built_in- ? mode.edited- ? t("modes_view.badge_builtin_edited")- : t("modes_view.badge_builtin")- : t("modes_view.badge_yours")}- </span>- {isActive && (- <span className="flex items-center gap-1 rounded-md bg-primary/15 px-1.5 py-0.5 text-[11px] font-medium text-primary">- <Check className="h-3 w-3" />- {t("modes_view.in_use")}- </span>- )}- {!isActive && isChosen && (- <span className="rounded-md border border-primary/60 px-1.5 py-0.5 text-[11px] font-medium text-primary">- {t("modes_view.your_choice")}- </span>- )}- </div>- {mode.description && (- <p className="mt-1 text-sm text-muted-foreground">{mode.description}</p>- )}- </div>- </div>- <div className="flex flex-wrap items-center gap-2">- <button- type="button"- onClick={onUse}- disabled={isActive || switching}- data-testid="mode-detail-use"- className={cn(- buttonClass,- isActive- ? "border-primary/40 text-primary"- : "border-primary bg-primary text-primary-foreground hover:opacity-90",- )}- >- {switching ? (- <Loader2 className="h-4 w-4 animate-spin" />- ) : (- <Check className="h-4 w-4" />- )}- {isActive ? t("modes_view.in_use_now") : t("modes_view.use_this_mode")}- </button>- <button- type="button"- onClick={onEdit}- data-testid="mode-detail-edit"- className={cn(buttonClass, "border-border hover:bg-secondary/60")}- >- <Pencil className="h-4 w-4" />- {t("modes_view.edit")}- </button>- {(mode.built_in ? mode.edited : true) && (- <button- type="button"- onClick={onRemove}- data-testid="mode-detail-remove"- className={cn(- buttonClass,- "border-border text-muted-foreground hover:border-destructive/40 hover:bg-destructive/10 hover:text-destructive",- )}- >- {mode.built_in ? (- <RotateCcw className="h-4 w-4" />- ) : (- <Trash2 className="h-4 w-4" />- )}- {mode.built_in ? t("modes_view.restore_original") : t("modes_view.delete")}- </button>- )}- </div>- </div>-- {!isActive && isChosen && overrideName && (- <p className="text-sm text-muted-foreground">- {fill(t("modes_view.detail_waiting"), overrideName)}- </p>- )}-- <div className="grid gap-4 lg:grid-cols-[minmax(0,2fr)_minmax(0,1fr)]">- <div className="flex flex-col gap-2">- <h5 className="text-xs font-medium uppercase tracking-wider text-muted-foreground">- {t("modes_view.detail_behaviour")}- </h5>- {mode.character ? (- <pre- data-testid="mode-detail-character"- className="max-h-[28rem] overflow-y-auto whitespace-pre-wrap break-words rounded-lg border border-border bg-background/60 p-4 font-sans text-sm leading-relaxed text-foreground"- >- {mode.character}- </pre>- ) : (- <p- data-testid="mode-detail-character"- className="rounded-lg border border-dashed border-border p-4 text-sm text-muted-foreground"- >- {t("modes_view.detail_empty_character")}- </p>- )}- </div>- <dl className="flex flex-col gap-3 text-sm">- <div>- <dt className="text-xs font-medium uppercase tracking-wider text-muted-foreground">- {t("modes_view.length_label")}- </dt>- <dd className="mt-0.5">{t(VERBOSITY_KEYS[mode.verbosity])}</dd>- </div>- <div>- <dt className="text-xs font-medium uppercase tracking-wider text-muted-foreground">- {t("modes_view.volunteers_label")}- </dt>- <dd className="mt-0.5">{t(PROACTIVITY_KEYS[mode.proactivity])}</dd>- </div>- <div>- <dt className="text-xs font-medium uppercase tracking-wider text-muted-foreground">- {t("modes_view.detail_voice")}- </dt>- <dd className="mt-0.5">{mode.voice || t("modes_view.detail_voice_default")}</dd>- </div>- <div>- <dt className="text-xs font-medium uppercase tracking-wider text-muted-foreground">- {t("modes_view.detail_id")}- </dt>- <dd className="mt-0.5 font-mono text-xs text-muted-foreground">{mode.slug}</dd>- </div>- </dl>- </div>- </div>- );-}diff --git a/jarvis/ui/web/modes_routes.py b/jarvis/ui/web/modes_routes.pydeleted file mode 100644index dbab12c57b..0000000000--- a/jarvis/ui/web/modes_routes.py+++ /dev/null@@ -1,166 +0,0 @@-"""REST API for assistant modes — the shelf of characters the user picks from.--Every action is an endpoint (the CLI-first contract): the modes screen, the-voice interviewer and the ``jarvis modes`` commands all drive these same-routes, so what the UI can do and what a spoken command can do never drift-apart.--Endpoints (prefix ``/api/modes``):--* ``GET /`` → every mode + which one is active-* ``GET /{slug}`` → one mode in full-* ``PUT /active`` → switch the active mode (applies next turn)-* ``POST /`` → create or replace a mode-* ``DELETE /{slug}`` → delete a user mode (or a user copy of a built-in)-* ``POST /{slug}/restore`` → drop the user copy, bring the built-in back--Anti-drift (``docs/anti-drift-three-layer.md``): the ``Verbosity`` and-``Proactivity`` Literals below are asserted against ``modes.VERBOSITIES`` /-``modes.PROACTIVITIES`` at import time, so adding a value in one place and-forgetting the other fails at startup rather than on the one request that-happens to carry the new string.-"""--from __future__ import annotations--import logging-from typing import Literal, get_args--from fastapi import APIRouter, HTTPException-from pydantic import BaseModel, Field--from jarvis.brain import modes--log = logging.getLogger(__name__)--router = APIRouter(prefix="/api/modes", tags=["modes"])--Verbosity = Literal["brief", "normal", "rich"]-Proactivity = Literal["reactive", "normal", "forward"]--# D2 of the anti-drift doc: an import-time assertion, not a test somebody has to-# remember to run.-assert set(get_args(Verbosity)) == set(modes.VERBOSITIES), (- "Verbosity Literal drifted from modes.VERBOSITIES"-)-assert set(get_args(Proactivity)) == set(modes.PROACTIVITIES), (- "Proactivity Literal drifted from modes.PROACTIVITIES"-)---class ActiveModeBody(BaseModel):- slug: str = Field(..., min_length=1, max_length=64)---class ModeBody(BaseModel):- """One mode as the UI and the voice interviewer submit it."""-- # Optional: a mode created by voice has a NAME the user said out loud and no- # slug at all, so the server derives one rather than making the caller- # guess the grammar.- slug: str = Field("", max_length=64)- name: str = Field(..., min_length=1, max_length=80)- character: str = Field(..., min_length=1, max_length=20_000)- emoji: str = Field("", max_length=16)- description: str = Field("", max_length=280)- voice: str = Field("", max_length=80)- verbosity: Verbosity = "normal"- proactivity: Proactivity = "normal"---def _payload() -> dict[str, object]:- active = modes.active_slug()- return {- "modes": [m.to_payload() for m in modes.list_modes()],- "active": active,- # The user's own choice, which is what a switch on this screen writes.- # Equal to ``active`` except while a section override is in force —- # and then it is the only way the UI can confirm the switch was- # stored rather than silently swallowed.- "chosen": modes.chosen_slug(),- # What the section override is doing, if anything. The UI needs to be- # able to say "coding mode is on because you are in the Agentic IDE"- # rather than showing a switch the user did not touch and cannot- # explain — an unexplained mode is exactly what this feature replaced.- "section_override": modes.section_override() or "",- "verbosities": list(modes.VERBOSITIES),- "proactivities": list(modes.PROACTIVITIES),- }--[email protected]("", summary="Every mode and which one is active")-async def list_modes() -> dict[str, object]:- """The full shelf, built-ins first, plus the active slug."""- return _payload()--[email protected]("/{slug}", summary="One mode in full")-async def get_mode(slug: str) -> dict[str, object]:- mode = modes.get_mode(slug)- if mode is None:- raise HTTPException(status_code=404, detail=f"No mode called {slug!r}.")- return mode.to_payload()--[email protected]("/active", summary="Switch the active mode")-async def set_active(body: ActiveModeBody) -> dict[str, object]:- """Switch modes. Applies on the next turn — voice and chat alike, no restart.-- A section override (the Agentic IDE) still wins while it is in force, so the- response reports the slug ACTUALLY in effect, not the one that was asked- for. Reporting the request back would be a small lie the UI would then show.- """- try:- mode = modes.set_active(body.slug)- except modes.ModeError as exc:- raise HTTPException(status_code=404, detail=str(exc)) from exc- # ``chosen`` after the payload on purpose: this handler KNOWS what was just- # written, and must not be second-guessed by a config read that could lag.- return {"ok": True, **_payload(), "chosen": mode.slug, "restart_required": False}--[email protected]("", summary="Create or replace a mode")-async def save_mode(body: ModeBody) -> dict[str, object]:- """Write a mode. Creating one does not switch to it — that is a separate act."""- try:- slug = modes.normalize_slug(body.slug or body.name)- except modes.ModeError as exc:- raise HTTPException(status_code=400, detail=str(exc)) from exc-- try:- mode = modes.save_mode(- slug=slug,- name=body.name,- character=body.character,- emoji=body.emoji,- description=body.description,- voice=body.voice,- verbosity=body.verbosity,- proactivity=body.proactivity,- )- except modes.ModeError as exc:- raise HTTPException(status_code=400, detail=str(exc)) from exc- except OSError as exc:- raise HTTPException(status_code=500, detail=f"Could not save: {exc}") from exc-- return {"ok": True, "mode": mode.to_payload(), **_payload()}--[email protected]("/{slug}", summary="Delete a user mode")-async def delete_mode(slug: str) -> dict[str, object]:- """Remove a user mode. Built-ins are refused; a user COPY of one is allowed."""- try:- removed = modes.delete_mode(slug)- except modes.ModeError as exc:- raise HTTPException(status_code=400, detail=str(exc)) from exc- return {"ok": True, "removed": removed, **_payload()}--[email protected]("/{slug}/restore", summary="Restore a built-in mode")-async def restore_builtin(slug: str) -> dict[str, object]:- """Throw away the user's edits to a built-in and bring the packaged one back."""- try:- restored = modes.restore_builtin(slug)- except modes.ModeError as exc:- raise HTTPException(status_code=400, detail=str(exc)) from exc- return {"ok": True, "restored": restored, **_payload()}diff --git a/jarvis/ui/web/server.py b/jarvis/ui/web/server.pyindex cf08329329..76c8d0bb15 100644--- a/jarvis/ui/web/server.py+++ b/jarvis/ui/web/server.py@@ -372,7 +372,6 @@ class WebServer:from .missions_ws_routes import (router as missions_ws_router,)- from .modes_routes import router as modes_routerfrom .onboarding_routes import router as onboarding_routerfrom .outputs_routes import router as outputs_routerfrom .permissions_routes import router as permissions_router@@ -429,7 +428,6 @@ class WebServer:app.include_router(desktop_router)app.include_router(profile_router)app.include_router(settings_router)- app.include_router(modes_router)app.include_router(permissions_router)# In-app updater (GET status / POST apply). Managed-install only — see# jarvis/ui/web/update_routes.py; refuses to self-reset a dev checkout.diff --git a/jarvis/ui/web/settings_routes.py b/jarvis/ui/web/settings_routes.pyindex f1e9743117..aa6a81ff20 100644--- a/jarvis/ui/web/settings_routes.py+++ b/jarvis/ui/web/settings_routes.py@@ -2184,10 +2184,7 @@ class SystemPromptBody(BaseModel):def _system_prompt_payload() -> dict[str, object]:from jarvis.brain import persona_loader- # The BASE persona, not the effective one: this editor writes the base text- # back, so showing the active mode's block here would let the user "edit" a- # block that the mode owns and then silently lose it on save.- content = persona_loader.base_persona_prompt()+ content = persona_loader.load_effective_persona_prompt()return {"content": content,"is_custom": persona_loader.has_custom_prompt(),diff --git a/pyproject.toml b/pyproject.tomlindex 3c789dbc61..5a538b34da 100644--- a/pyproject.toml+++ b/pyproject.toml@@ -693,13 +693,6 @@ click-element = "jarvis.plugins.tool.click_element:ClickElementTool"scroll = "jarvis.plugins.tool.scroll:ScrollTool"wait-for-element = "jarvis.plugins.tool.wait_for_element:WaitForElementTool"remember = "jarvis.plugins.tool.remember:RememberTool"-# Assistant modes (2026-08-13): the assistant's own character, switchable by-# voice and buildable through an interview. Direct gated actions, never a spawn-# (AP-5/AP-14). save_mode is ask-tier because it writes a file every future-# turn reads.-list-modes = "jarvis.plugins.tool.assistant_mode:ListModesTool"-switch-mode = "jarvis.plugins.tool.assistant_mode:SwitchModeTool"-save-mode = "jarvis.plugins.tool.assistant_mode:SaveModeTool"dispatch-to-harness = "jarvis.plugins.tool.dispatch_to_harness:DispatchToHarnessTool"# Computer-Use (Wave 1, 2026-05-29) — first-class router tool to drive the live# desktop via the in-process computer-use harness. Router-tier only (in@@ -851,10 +844,6 @@ jarvis = [# allowlist (skills/authoring/draft_writer.py), Jarvis-Agent critic# verdict JSON-schema (core/review/spawns.py)."brain/JARVIS_PERSONA.md",- # Built-in assistant modes (brain/modes.py::packaged_modes_dir). Missing- # here, a wheel install would show an empty mode list and silently fall- # back to the base persona — the same class of bug as the note above.- "brain/modes/*.md","skills/safe_imports.txt","core/review/verdict_schema.json",# Seed catalogs (CLI tools / skills / marketplace plugins) — nameddiff --git a/tests/integration/test_modes_routes.py b/tests/integration/test_modes_routes.pydeleted file mode 100644index 484ee4125b..0000000000--- a/tests/integration/test_modes_routes.py+++ /dev/null@@ -1,129 +0,0 @@-"""Integration tests for /api/modes — the assistant's shelf of characters.--These go through the real WebServer, so they also prove the router is actually-mounted: a modes screen talking to a route nobody registered fails as a blank-page, which is the least diagnosable failure this feature has.-"""-from __future__ import annotations--from collections.abc import Iterator--import pytest-from fastapi.testclient import TestClient--import jarvis.core.config as core_config-from jarvis.brain import modes-from jarvis.core.bus import EventBus-from jarvis.core.config import JarvisConfig-from jarvis.ui.web.server import WebServer--[email protected](autouse=True)-def _isolate(tmp_path, monkeypatch: pytest.MonkeyPatch) -> None:- """User modes go to a throwaway dir; the pointer never reaches jarvis.toml."""- monkeypatch.setattr(core_config, "DATA_DIR", tmp_path)- stored: dict[str, str] = {}- monkeypatch.setattr(modes, "_configured_slug", lambda: stored.get("slug", modes.DEFAULT_MODE))- monkeypatch.setattr(- "jarvis.core.config_writer.set_active_mode",- lambda slug, **_kw: stored.__setitem__("slug", slug),- )- modes.set_section_override(None)---def client() -> Iterator[TestClient]:- cfg = JarvisConfig()- cfg.ui.dev_mode = True- bus = EventBus()- server = WebServer(cfg, bus=bus)- server.app.state.config = cfg- server.app.state.bus = bus- with TestClient(server.app) as c:- yield c---def test_router_is_mounted_and_lists_the_builtins(client: TestClient) -> None:- resp = client.get("/api/modes")- assert resp.status_code == 200- body = resp.json()- assert [m["slug"] for m in body["modes"]][:5] == list(modes.BUILTIN_SLUGS)- assert body["active"] == modes.DEFAULT_MODE---def test_switching_the_active_mode_round_trips(client: TestClient) -> None:- resp = client.put("/api/modes/active", json={"slug": "friend"})- assert resp.status_code == 200- assert resp.json()["active"] == "friend"- assert resp.json()["restart_required"] is False- assert client.get("/api/modes").json()["active"] == "friend"---def test_switching_to_an_unknown_mode_is_a_404(client: TestClient) -> None:- assert client.put("/api/modes/active", json={"slug": "nope"}).status_code == 404---def test_a_mode_created_by_name_alone_gets_a_slug(client: TestClient) -> None:- """The voice interviewer submits a spoken NAME and no slug — the server derives one."""- resp = client.post(- "/api/modes",- json={"name": "Night Owl", "character": "Speak quietly. It is late."},- )- assert resp.status_code == 200- assert resp.json()["mode"]["slug"] == "night-owl"---def test_creating_a_mode_does_not_switch_to_it(client: TestClient) -> None:- """Two separate acts — building a character is not the same as becoming it."""- client.post("/api/modes", json={"name": "Night Owl", "character": "Quietly."})- assert client.get("/api/modes").json()["active"] == modes.DEFAULT_MODE---def test_an_unknown_knob_value_is_rejected(client: TestClient) -> None:- """The Literal guard: a value the backend does not know never reaches disk."""- resp = client.post(- "/api/modes",- json={"name": "Loud", "character": "Shout.", "verbosity": "very-loud"},- )- assert resp.status_code == 422---def test_a_path_shaped_name_is_refused(client: TestClient) -> None:- resp = client.post("/api/modes", json={"name": "../escape", "character": "x"})- assert resp.status_code == 400---def test_builtins_cannot_be_deleted_but_a_copy_can(client: TestClient) -> None:- assert client.delete("/api/modes/friend").status_code == 400-- client.post("/api/modes", json={"name": "Friend", "character": "My own words."})- assert client.get("/api/modes/friend").json()["character"] == "My own words."-- assert client.post("/api/modes/friend/restore").json()["restored"] is True- assert "not serving a client" in client.get("/api/modes/friend").json()["character"]---def test_the_response_reports_the_mode_actually_in_force(client: TestClient) -> None:- """A section override wins; echoing the request back would be a small lie."""- modes.set_section_override(modes.MODE_CODING)- try:- body = client.put("/api/modes/active", json={"slug": "friend"}).json()- assert body["chosen"] == "friend"- assert body["active"] == modes.MODE_CODING- assert body["section_override"] == modes.MODE_CODING- # And a plain read afterwards still tells the two apart: the switch was- # STORED (chosen) even though something else is in force (active). A- # payload that only carried ``active`` left the modes screen unable to- # confirm a click had done anything at all.- listing = client.get("/api/modes").json()- assert listing["chosen"] == "friend"- assert listing["active"] == modes.MODE_CODING- finally:- modes.set_section_override(None)---def test_chosen_equals_active_when_nothing_overrides(client: TestClient) -> None:- client.put("/api/modes/active", json={"slug": "coach"})- body = client.get("/api/modes").json()- assert body["chosen"] == body["active"] == "coach"- assert body["section_override"] == ""diff --git a/tests/unit/agentic_ide/test_coding_mode.py b/tests/unit/agentic_ide/test_coding_mode.pyindex 489b00f788..4717daa15d 100644--- a/tests/unit/agentic_ide/test_coding_mode.py+++ b/tests/unit/agentic_ide/test_coding_mode.py@@ -116,89 +116,3 @@ async def test_event_reaches_the_ui_as_a_ws_envelope(assert envelope["event_name"] == "AgenticIdeCodingModeChanged"assert envelope["payload"]["enabled"] is True---# --------------------------------------------------- the persona follows the mode-#-# Coding mode also swaps the assistant's CHARACTER (the ``coding`` mode) through-# an in-memory section override on the persona layer. That override must agree-# with ``coding_mode_active`` after EVERY transition, not only after the toggle:-# left behind by a closed or switched-away workspace it kept the assistant in-# coding character for the rest of the process, and — because the override-# outranks the user's choice — made the modes screen look as if switching modes-# did nothing at all.---def _persona_override() -> str | None:- from jarvis.brain import modes-- return modes.section_override()--[email protected](autouse=True)-def _clear_persona_override():- from jarvis.brain import modes-- modes.set_section_override(None)- yield- modes.set_section_override(None)---async def test_the_persona_override_tracks_the_toggle(- wired: Registry, tmp_path: Path-) -> None:- await wired.start(str(tmp_path), [{"agent": "claude"}])- assert _persona_override() is None- wired.set_focus_mode(True)- assert _persona_override() == "coding"- wired.set_focus_mode(False)- assert _persona_override() is None---async def test_closing_the_last_workspace_drops_the_persona_override(- wired: Registry, tmp_path: Path-) -> None:- """The exact bug: coding character stuck on after the workspace was closed."""- await wired.start(str(tmp_path), [{"agent": "claude"}])- wired.set_focus_mode(True)- await wired.end()- assert coding_mode_active() is False- assert _persona_override() is None---async def test_clearing_the_front_drops_the_persona_override(- wired: Registry, tmp_path: Path-) -> None:- """The wizard for another workspace takes the front away — and the mode."""- await wired.start(str(tmp_path), [{"agent": "claude"}])- wired.set_focus_mode(True)- await wired.activate(None)- assert coding_mode_active() is False- assert _persona_override() is None---async def test_switching_workspaces_moves_the_persona_override_with_the_flag(- wired: Registry, tmp_path: Path-) -> None:- """The flag is per workspace, so the persona follows whichever is in front."""- (tmp_path / "a").mkdir()- (tmp_path / "b").mkdir()- first = await wired.start(str(tmp_path / "a"), [{"agent": "claude"}])- wired.set_focus_mode(True)- second = await wired.start(str(tmp_path / "b"), [{"agent": "claude"}])- # A freshly opened workspace is at the front with the mode OFF.- assert wired.session is second- assert coding_mode_active() is False- assert _persona_override() is None-- await wired.activate(first.id)- assert coding_mode_active() is True- assert _persona_override() == "coding"-- # Closing the front workspace hands the front to the survivor, whose flag- # is off — the override must not linger from the one that just closed.- await wired.end(first.id)- assert wired.session is second- assert coding_mode_active() is False- assert _persona_override() is None-diff --git a/tests/unit/brain/test_custom_system_prompt.py b/tests/unit/brain/test_custom_system_prompt.pyindex 61ec1483c8..344fcb050e 100644--- a/tests/unit/brain/test_custom_system_prompt.py+++ b/tests/unit/brain/test_custom_system_prompt.py@@ -18,14 +18,6 @@ from jarvis.brain import persona_loaderdef _isolate_data_dir(tmp_path, monkeypatch: pytest.MonkeyPatch):"""Point the override file at a throwaway dir so tests never touch real data."""monkeypatch.setattr(core_config, "DATA_DIR", tmp_path)- # Neutralise the active MODE too. ``load_effective_persona_prompt``- # appends the mode block, and the mode is real user state that lives- # outside DATA_DIR — so on any machine with a mode switched on these- # comparisons failed against the bare default while CI, which has no- # user state, stayed green. A test must not read the developer.- monkeypatch.setattr(- "jarvis.brain.modes.active_prompt_block", lambda: ""- )return tmp_pathdiff --git a/tests/unit/brain/test_modes.py b/tests/unit/brain/test_modes.pydeleted file mode 100644index 325fd4869b..0000000000--- a/tests/unit/brain/test_modes.py+++ /dev/null@@ -1,322 +0,0 @@-"""Assistant modes: a shelf of named characters, one of them active.--Feature 2026-08-13. These lock the four contracts everything else depends on:--1. The default mode changes NOTHING — an install that never opens the modes- screen produces the same system prompt as before the feature existed.-2. A mode is layered on the base persona, never substituted for it, so the- honesty rules survive picking a chattier character.-3. A slug becomes a file name, and it can arrive from a tool the realtime model- calls — so anything path-shaped is refused, not quietly repaired.-4. The screen-scoped override is in-memory only. That is the structural reason- coding mode can no longer get permanently stuck (the pre-2026-08-13 bug:- ``AgenticIdeView`` switched it on and nothing ever switched it off).-"""-from __future__ import annotations--import functools--import pytest--import jarvis.core.config as core_config-from jarvis.brain import modes, persona_loader--[email protected](autouse=True)-def _isolate(tmp_path, monkeypatch: pytest.MonkeyPatch):- """User modes go to a throwaway dir; the active pointer never hits jarvis.toml."""- monkeypatch.setattr(core_config, "DATA_DIR", tmp_path)- stored: dict[str, str] = {}- monkeypatch.setattr(modes, "_configured_slug", lambda: stored.get("slug", modes.DEFAULT_MODE))- monkeypatch.setattr(- "jarvis.core.config_writer.set_active_mode",- lambda slug, **_kw: stored.__setitem__("slug", slug),- )- modes.set_section_override(None)- yield tmp_path- modes.set_section_override(None)---# ----------------------------------------------------------------------------# The five built-ins-# ------------------------------------------------------------------------------def test_all_five_builtins_ship_and_are_marked_built_in() -> None:- by_slug = {m.slug: m for m in modes.list_modes()}- assert set(modes.BUILTIN_SLUGS) <= by_slug.keys()- assert all(by_slug[s].built_in for s in modes.BUILTIN_SLUGS)---def test_builtins_lead_the_list_in_declared_order() -> None:- """The switcher shows a stable shelf, not whatever the filesystem returned."""- listed = [m.slug for m in modes.list_modes()]- assert listed[: len(modes.BUILTIN_SLUGS)] == list(modes.BUILTIN_SLUGS)---def test_every_builtin_carries_a_name_and_a_description() -> None:- """The switcher renders these; a blank card is indistinguishable from a bug."""- for mode in modes.list_modes():- assert mode.name.strip(), f"{mode.slug} has no name"- assert mode.description.strip(), f"{mode.slug} has no description"---# ----------------------------------------------------------------------------# Contract 1: the default mode is a no-op-# ------------------------------------------------------------------------------def test_default_mode_contributes_nothing() -> None:- assert modes.active_slug() == modes.MODE_ASSISTANT- assert modes.mode_prompt_block(modes.active_mode()) == ""---def test_effective_persona_is_byte_identical_to_the_base_by_default() -> None:- """The whole feature must be invisible until the user chooses otherwise."""- assert persona_loader.load_effective_persona_prompt() == persona_loader.base_persona_prompt()---# ----------------------------------------------------------------------------# Contract 2: layered, never substituted-# ------------------------------------------------------------------------------def test_active_mode_is_appended_to_the_base_persona() -> None:- modes.set_active(modes.MODE_FRIEND)- base = persona_loader.base_persona_prompt()- effective = persona_loader.load_effective_persona_prompt()-- assert effective.startswith(base), "the base persona must survive a mode switch"- assert len(effective) > len(base)- assert "Friend" in effective---def test_mode_block_states_that_the_base_rules_win() -> None:- """Without this, 'be casual' reads as permission to skip the honesty rules."""- block = modes.mode_prompt_block(modes.get_mode(modes.MODE_FRIEND))- assert "those rules win" in block- assert "honesty" in block---def test_custom_system_prompt_and_a_mode_compose() -> None:- """The legacy single-slot override is a BASE; a mode still layers on top."""- persona_loader.save_custom_prompt("You are MAX.")- modes.set_active(modes.MODE_COACH)- effective = persona_loader.load_effective_persona_prompt()- assert effective.startswith("You are MAX.")- assert "Coach" in effective---def test_verbosity_and_proactivity_are_compiled_into_the_block() -> None:- block = modes.mode_prompt_block(modes.get_mode(modes.MODE_FOCUS))- assert "as few words" in block # verbosity: brief- assert "Answer what was asked and stop" in block # proactivity: reactive---def test_normal_knobs_add_no_text() -> None:- """'Normal' means 'say nothing extra', not 'say the word normal'."""- mode = modes.Mode(slug="x", name="X", emoji="", description="", character="Be nice.")- block = modes.mode_prompt_block(mode)- assert block.rstrip().endswith("Be nice.")---# ----------------------------------------------------------------------------# Contract 3: a slug is a file name-# ------------------------------------------------------------------------------ "hostile",- ["../escape", "/etc/passwd", "..\\windows", "a:b", "..", "", "!!!", "con", "LPT1"],-)-def test_hostile_slugs_are_refused(hostile: str) -> None:- with pytest.raises(modes.ModeError):- modes.normalize_slug(hostile)--- ("typed", "expected"),- [("Friend Mode", "friend-mode"), (" My Coach ", "my-coach"), ("a_b", "a-b")],-)-def test_human_names_become_readable_slugs(typed: str, expected: str) -> None:- assert modes.normalize_slug(typed) == expected---def test_saved_mode_stays_inside_the_modes_directory(tmp_path) -> None:- modes.save_mode(slug="Pirate", name="Pirate", character="Speak like a pirate.")- written = list((tmp_path / "modes").glob("*.md"))- assert [p.name for p in written] == ["pirate.md"]---def test_a_mode_needs_a_character() -> None:- with pytest.raises(modes.ModeError):- modes.save_mode(slug="empty", name="Empty", character=" ")---# ----------------------------------------------------------------------------# Round trip, activation, deletion-# ------------------------------------------------------------------------------def test_save_then_read_back_preserves_every_field() -> None:- modes.save_mode(- slug="pirate",- name="Pirate",- character="Speak like a pirate.",- emoji="🏴",- description="Arr.",- voice="alloy",- verbosity=modes.VERBOSITY_BRIEF,- proactivity=modes.PROACTIVITY_FORWARD,- )- back = modes.get_mode("pirate")- assert back is not None- assert (back.name, back.emoji, back.description) == ("Pirate", "🏴", "Arr.")- assert (back.voice, back.verbosity, back.proactivity) == (- "alloy",- modes.VERBOSITY_BRIEF,- modes.PROACTIVITY_FORWARD,- )- assert back.character == "Speak like a pirate."- assert back.built_in is False---def test_activating_an_unknown_mode_raises() -> None:- with pytest.raises(modes.ModeError):- modes.set_active("no-such-mode")---def test_builtins_cannot_be_deleted() -> None:- with pytest.raises(modes.ModeError):- modes.delete_mode(modes.MODE_FRIEND)---def test_deleting_the_active_mode_falls_back_to_the_default() -> None:- modes.save_mode(slug="pirate", name="Pirate", character="Arr.")- modes.set_active("pirate")- assert modes.active_slug() == "pirate"- modes.delete_mode("pirate")- assert modes.active_slug() == modes.DEFAULT_MODE---def test_a_user_copy_shadows_a_builtin_but_stays_restorable() -> None:- modes.save_mode(slug=modes.MODE_FRIEND, name="My Friend", character="Totally different.")- edited = modes.get_mode(modes.MODE_FRIEND)- assert edited is not None and edited.character == "Totally different."- assert edited.built_in is True, "still offers 'restore the original'"- # ``edited`` is what tells a UI that "restore" would actually do something.- assert edited.edited is True- assert edited.to_payload()["edited"] is True-- assert modes.restore_builtin(modes.MODE_FRIEND) is True- restored = modes.get_mode(modes.MODE_FRIEND)- assert restored is not None and "not serving a client" in restored.character- assert restored.edited is False-- # A mode of the user's own is not "edited": there is no original under it.- modes.save_mode(slug="pirate", name="Pirate", character="Arr.")- own = modes.get_mode("pirate")- assert own is not None and own.built_in is False and own.edited is False---def test_a_stored_pointer_to_a_vanished_mode_degrades_to_the_default() -> None:- """A config carried to another machine must not name a mode that is not there."""- modes.save_mode(slug="pirate", name="Pirate", character="Arr.")- modes.set_active("pirate")- (core_config.DATA_DIR / "modes" / "pirate.md").unlink()- assert modes.active_slug() == modes.DEFAULT_MODE---def test_a_corrupt_mode_file_is_skipped_not_fatal(tmp_path) -> None:- """One bad hand-edit must not take down the mode list, and through it every turn."""- (tmp_path / "modes").mkdir(parents=True, exist_ok=True)- (tmp_path / "modes" / "broken.md").write_text("---\nname: [unclosed\n", encoding="utf-8")- slugs = [m.slug for m in modes.list_modes()]- assert set(modes.BUILTIN_SLUGS) <= set(slugs)- assert persona_loader.load_effective_persona_prompt()---# ----------------------------------------------------------------------------# Contract 4: the screen-scoped override never persists-# ------------------------------------------------------------------------------def test_section_override_wins_over_the_stored_choice() -> None:- modes.set_active(modes.MODE_FRIEND)- modes.set_section_override(modes.MODE_CODING)- assert modes.active_slug() == modes.MODE_CODING---def test_clearing_the_override_restores_the_users_own_choice() -> None:- """Leaving the Agentic IDE must not leave you in a mode you never picked."""- modes.set_active(modes.MODE_FRIEND)- modes.set_section_override(modes.MODE_CODING)- modes.set_section_override(None)- assert modes.active_slug() == modes.MODE_FRIEND---def test_override_is_never_written_to_config(monkeypatch: pytest.MonkeyPatch) -> None:- """The structural fix: a mode a screen turned on cannot outlive the process.-- Guards the exact regression path — if someone ever "helpfully" persists the- section override, coding mode becomes sticky again and this test fails.- """- written: list[str] = []- monkeypatch.setattr(- "jarvis.core.config_writer.set_active_mode",- lambda slug, **_kw: written.append(slug),- )- modes.set_section_override(modes.MODE_CODING)- assert modes.section_override() == modes.MODE_CODING- assert written == [], "the section override must never reach jarvis.toml"---def test_override_naming_an_unknown_mode_raises() -> None:- with pytest.raises(modes.ModeError):- modes.set_section_override("no-such-mode")---# ----------------------------------------------------------------------------# The real round trip through jarvis.toml-# ----------------------------------------------------------------------------#-# Every test above stubs ``_configured_slug`` — which is exactly how a broken-# reader shipped: it imported an accessor the config layer does not have,-# swallowed the ImportError, and returned the default forever. The switch was-# written to disk on every click and never read back; the check mark on the-# modes screen never moved. This test goes through the actual file.---def test_the_stored_choice_is_read_back_from_the_real_config(- tmp_path, monkeypatch: pytest.MonkeyPatch-) -> None:- from jarvis.core import config_writer-- monkeypatch.undo() # drop the stubs from ``_isolate``; the file is the point- monkeypatch.setattr(core_config, "DATA_DIR", tmp_path)- target = tmp_path / "jarvis.toml"- target.write_text('[persona]\nactive_mode = "coach"\n', encoding="utf-8")- monkeypatch.setenv("JARVIS_CONFIG", str(target))- core_config.clear_config_cache()-- assert modes._configured_slug() == "coach"- assert modes.active_slug() == "coach"-- # A write through the real writer is visible on the very next read. Only- # the target path is redirected; the writer itself is the real one.- monkeypatch.setattr(- config_writer,- "set_active_mode",- functools.partial(config_writer.set_active_mode, path=target),- )- modes.set_active("friend")- assert modes._configured_slug() == "friend"- assert modes.chosen_slug() == "friend"- assert modes.active_slug() == "friend"-- # A stored slug that no longer names a mode degrades to the default — the- # config could have come from another machine.- target.write_text('[persona]\nactive_mode = "pirate"\n', encoding="utf-8")- core_config.clear_config_cache()- assert modes._configured_slug() == "pirate"- assert modes.active_slug() == modes.DEFAULT_MODEdiff --git a/tests/unit/brain/test_persona_loader.py b/tests/unit/brain/test_persona_loader.pyindex c6119e7616..ef20f03463 100644--- a/tests/unit/brain/test_persona_loader.py+++ b/tests/unit/brain/test_persona_loader.py@@ -145,11 +145,6 @@ def test_custom_override_wins_even_in_compact_mode(monkeypatch, tmp_path) -> Non"""User autonomy outranks the latency optimization: their exact wordsstay, whatever profile the provider asked for."""invalidate_cache()- # The active MODE is appended by the loader and is real user state, so on a- # machine with a mode switched on this compared "My own words." against- # "My own words." plus the mode block. CI has no user state and stayed- # green; the developer's own box failed. Isolate what is not under test.- monkeypatch.setattr("jarvis.brain.modes.active_prompt_block", lambda: "")monkeypatch.setattr(pl, "read_custom_prompt", lambda: "My own words.")try:assert pl.load_effective_persona_prompt(compact=True) == "My own words."diff --git a/tests/unit/brain/test_routing.py b/tests/unit/brain/test_routing.pyindex a19d58140c..a7af8baf92 100644--- a/tests/unit/brain/test_routing.py+++ b/tests/unit/brain/test_routing.py@@ -1999,18 +1999,6 @@ def test_router_tools_is_pure_dispatcher_set() -> None:# jarvis/brain/artifact_gate.py), because the mandate is that an# artifact is asked for, never volunteered."create-artifact",- # Assistant modes (2026-08-13, maintainer mandate): the assistant's- # own character. list-modes (safe, property read), switch-mode- # (monitor, changes tone only and is visible on screen the moment it- # happens), save-mode (ask, echo-confirm — it writes a file every- # future turn reads). Deterministic, in-process, touching no- # external system: the same shape as switch-provider, which is the- # standing precedent for the assistant reconfiguring itself by- # voice. Direct gated actions, never spawns (AP-5/AP-14). See- # ADR-0011 amendment "Assistant-Mode Tools".- "list-modes",- "switch-mode",- "save-mode",})assert ROUTER_TOOLS == expected, (diff --git a/tests/unit/plugins/test_assistant_mode_tool.py b/tests/unit/plugins/test_assistant_mode_tool.pydeleted file mode 100644index d027e0b228..0000000000--- a/tests/unit/plugins/test_assistant_mode_tool.py+++ /dev/null@@ -1,108 +0,0 @@-"""The three mode tools the assistant can call itself.--``switch_mode`` is how "be my friend for a bit" works by voice; ``save_mode``-is the last beat of the mode-builder interview. They live in the normal tool-registry rather than as bespoke realtime declarations, so the speaking brain-and the typing brain get the same behaviour from one file — these tests lock-that they are registered, gated at the right tiers, and honest when they fail.-"""-from __future__ import annotations--from importlib.metadata import entry_points--import pytest--import jarvis.core.config as core_config-from jarvis.brain import modes, persona_loader-from jarvis.plugins.tool.assistant_mode import ListModesTool, SaveModeTool, SwitchModeTool--[email protected](autouse=True)-def _isolate(tmp_path, monkeypatch: pytest.MonkeyPatch):- """Never touch the real data dir or the real jarvis.toml."""- monkeypatch.setattr(core_config, "DATA_DIR", tmp_path)- stored: dict[str, str] = {}- monkeypatch.setattr(modes, "_configured_slug", lambda: stored.get("slug", modes.DEFAULT_MODE))- monkeypatch.setattr(- "jarvis.core.config_writer.set_active_mode",- lambda slug, **_kw: stored.__setitem__("slug", slug),- )- modes.set_section_override(None)- yield- modes.set_section_override(None)---def test_all_three_tools_are_registered_entry_points() -> None:- """Unregistered, they exist but the model can never reach them."""- names = {e.name for e in entry_points(group="jarvis.tool")}- assert {"list-modes", "switch-mode", "save-mode"} <= names---def test_risk_tiers_match_what_each_tool_actually_does() -> None:- assert ListModesTool.risk_tier == "safe" # a property read- assert SwitchModeTool.risk_tier == "monitor" # visible, reversible in one sentence- assert SaveModeTool.risk_tier == "ask" # writes a file every future turn reads---async def test_list_modes_reports_the_shelf_and_the_active_one() -> None:- result = await ListModesTool().execute({}, None)- assert result.success- assert [m["slug"] for m in result.output["modes"]][:5] == list(modes.BUILTIN_SLUGS)- assert result.output["active"] == modes.DEFAULT_MODE---async def test_switching_reaches_the_persona_layer() -> None:- """The point of the whole feature: one call changes what the brain is told."""- base = persona_loader.base_persona_prompt()- result = await SwitchModeTool().execute({"slug": "friend"}, None)- assert result.success- assert "Friend" in persona_loader.load_effective_persona_prompt()[len(base) :]---async def test_an_unknown_mode_comes_back_with_the_real_list() -> None:- """A near-miss must be recoverable in the same turn, not an apology."""- result = await SwitchModeTool().execute({"slug": "friendly"}, None)- assert not result.success- assert "friend" in result.error- assert "coach" in result.error---async def test_switching_under_a_section_override_says_so() -> None:- """Reporting a mode the user will not actually hear is the lie to avoid."""- modes.set_section_override(modes.MODE_CODING)- result = await SwitchModeTool().execute({"slug": "friend"}, None)- assert result.success- assert "coding" in result.output- assert modes.active_slug() == modes.MODE_CODING---async def test_save_mode_writes_and_can_activate() -> None:- result = await SaveModeTool().execute(- {- "name": "Night Owl",- "character": "Speak quietly. It is late.",- "emoji": "🦉",- "verbosity": "brief",- "activate": True,- },- None,- )- assert result.success- saved = modes.get_mode("night-owl")- assert saved is not None and saved.verbosity == modes.VERBOSITY_BRIEF- assert modes.active_slug() == "night-owl"---async def test_save_mode_does_not_activate_unless_asked() -> None:- await SaveModeTool().execute({"name": "Night Owl", "character": "Quietly."}, None)- assert modes.active_slug() == modes.DEFAULT_MODE---async def test_save_mode_needs_both_a_name_and_a_character() -> None:- result = await SaveModeTool().execute({"name": "Half", "character": " "}, None)- assert not result.success---async def test_save_mode_refuses_a_path_shaped_name() -> None:- result = await SaveModeTool().execute({"name": "../escape", "character": "x"}, None)- assert not result.successdiff --git a/tests/unit/realtime/test_session.py b/tests/unit/realtime/test_session.pyindex 645472d181..bab9281c73 100644--- a/tests/unit/realtime/test_session.py+++ b/tests/unit/realtime/test_session.py@@ -6839,14 +6839,11 @@ async def test_scrub_cancel_fallback_carries_the_active_voice_hint():await sess.end(reason="test")-def test_active_provider_selection_falls_back_to_adapter_default_voice(- monkeypatch: pytest.MonkeyPatch,-):+def test_active_provider_selection_falls_back_to_adapter_default_voice():"""BUG-155: an empty card pin must still resolve a named live voice sosurface TTS cannot fall through to Charon while the socket speaks Kore."""from types import SimpleNamespace- monkeypatch.setattr("jarvis.brain.modes.active_voice", lambda: "")sess = RealtimeVoiceSession(session_id="voice-default",send_binary=lambda _data: asyncio.sleep(0),