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(dictation): outcome vocabulary, lifetime stats and recovery audio
Ruben Lütkefe2b1e83f1cc
diff --git a/jarvis/dictation/audio.py b/jarvis/dictation/audio.pynew file mode 100644index 0000000000..38acbd809b--- /dev/null+++ b/jarvis/dictation/audio.py@@ -0,0 +1,272 @@+"""Local audio sidecars for dictations that produced nothing usable.++Why keep audio at all+---------------------+A dictation that fails — a provider 401, a wedged engine, a transcript that+came back empty — currently costs the user everything they just said. Keeping+the raw audio for those cases (and only those cases) is what makes a later+"Restore" more than a button that shakes its head.++Why this is written carefully+-----------------------------+Raw microphone audio is the most sensitive thing this application would ever+store. It is a voiceprint, it contains whatever was said in the room before+the key was released, and it cannot be redacted after the fact. So:++* **Only recoverable outcomes.** The success path never writes a file. That+ decision lives in the caller, but nothing here makes the success path easy.+* **Local only.** Files land under ``<user data>/data/dictation_audio/`` and+ are never uploaded, synced, or referenced by an absolute path in any API+ response.+* **Capped hard.** ``prune_audio`` keeps at most a handful of recent files and+ ages the rest out, so "keep failed audio" can never grow into an archive.+* **Purgeable in one call.** ``purge_dictation_audio`` is what the "delete my+ dictation history" action calls, so the user's mental model ("I deleted it")+ matches reality.+* **Opt-out is a real switch.** ``[dictation].keep_failed_audio = false``+ means nothing here is ever called.++Format: plain uncompressed WAV via the stdlib :mod:`wave` module — 16 kHz,+mono, signed 16-bit, which is exactly the PCM the capture path already holds.+No codec, no third-party dependency, and readable by every STT provider we+hand it back to. At the 300 s capture ceiling one file is ~9.6 MB.++The :mod:`wave` import is deliberately made inside the functions: this module+sits on no hot path and must not cost anything at import time (AP-26).+"""++from __future__ import annotations++import logging+import os+import re+import tempfile+from pathlib import Path++log = logging.getLogger(__name__)++#: The capture format. These are not tunables — they describe the PCM the+#: dictation buffer already contains.+SAMPLE_RATE: int = 16_000+CHANNELS: int = 1+SAMPLE_WIDTH: int = 2 # bytes per sample (signed 16-bit)++#: Longest audio written to one file. Mirrors the 300 s capture ceiling; a+#: longer buffer is stored truncated rather than refused, because a partial+#: recovery still beats none.+MAX_AUDIO_SECONDS: int = 300+MAX_AUDIO_BYTES: int = MAX_AUDIO_SECONDS * SAMPLE_RATE * CHANNELS * SAMPLE_WIDTH++#: Entry ids are generated as ``uuid4().hex``, but a file name is built from+#: them and untrusted input must never be able to escape the directory.+_SAFE_ID_RE = re.compile(r"[^A-Za-z0-9_-]")+_MAX_ID_LEN = 64+++def default_audio_dir() -> Path:+ """``<user data>/data/dictation_audio``. Does not create the directory."""+ from jarvis.core.paths import user_data_dir++ return Path(user_data_dir()) / "data" / "dictation_audio"+++def _safe_stem(entry_id: str) -> str:+ """A file-name-safe stem, or ``""`` when nothing usable is left."""+ cleaned = _SAFE_ID_RE.sub("", str(entry_id or ""))+ return cleaned[:_MAX_ID_LEN]+++def audio_path_for(entry_id: str, *, directory: Path | str | None = None) -> Path | None:+ """Where the sidecar for ``entry_id`` lives. ``None`` for an unusable id.++ Deterministic, so a caller can find the file again without having stored+ the path — but the path IS stored on the history entry as well, because+ that is what lets a prune know which files are still spoken for.+ """+ stem = _safe_stem(entry_id)+ if not stem:+ return None+ base = Path(directory) if directory is not None else default_audio_dir()+ return base / f"{stem}.wav"+++def save_dictation_audio(+ entry_id: str,+ pcm: bytes,+ *,+ directory: Path | str | None = None,+ sample_rate: int = SAMPLE_RATE,+) -> Path | None:+ """Write ``pcm`` as a WAV sidecar. ``None`` when nothing was written.++ Never raises: a failed sidecar is a lost recovery option, which must never+ turn into a lost dictation. Blocking — call it from a worker thread.+ """+ import wave # lazy: nothing at import time (AP-26)++ path = audio_path_for(entry_id, directory=directory)+ if path is None:+ log.debug("dictation audio not saved: unusable entry id")+ return None+ data = bytes(pcm or b"")+ if not data:+ return None+ if len(data) > MAX_AUDIO_BYTES:+ # Truncate rather than refuse — the first five minutes are still the+ # part the user is most likely to want back.+ data = data[:MAX_AUDIO_BYTES]+ # Whole samples only; a trailing half-sample makes an unreadable frame.+ frame_bytes = CHANNELS * SAMPLE_WIDTH+ if len(data) % frame_bytes:+ data = data[: len(data) - (len(data) % frame_bytes)]+ if not data:+ return None++ tmp_name = ""+ try:+ path.parent.mkdir(parents=True, exist_ok=True)+ # Atomic tempfile + os.replace, same discipline as the history sidecar:+ # a crash mid-write never leaves a torn WAV that a later read chokes on.+ fd, tmp_name = tempfile.mkstemp(+ dir=str(path.parent), prefix=".dictation_audio_", suffix=".tmp"+ )+ os.close(fd)+ with wave.open(str(tmp_name), "wb") as handle:+ handle.setnchannels(CHANNELS)+ handle.setsampwidth(SAMPLE_WIDTH)+ handle.setframerate(int(sample_rate or SAMPLE_RATE))+ handle.writeframes(data)+ os.replace(tmp_name, path)+ except Exception: # noqa: BLE001 — a sidecar is never worth a failure+ log.warning("could not store the dictation audio sidecar", exc_info=True)+ if tmp_name:+ try:+ os.unlink(tmp_name)+ except OSError:+ pass+ return None+ return path+++def load_dictation_audio(path: Path | str | None) -> bytes:+ """Read a sidecar back as raw PCM frames. ``b""`` when unreadable.++ Returns the frames, not the WAV container, because that is what an STT+ provider's ``transcribe_pcm`` expects. Blocking — call it from a worker+ thread.+ """+ import wave # lazy (AP-26)++ if not path:+ return b""+ try:+ with wave.open(str(path), "rb") as handle:+ return handle.readframes(handle.getnframes())+ except Exception: # noqa: BLE001+ log.debug("dictation audio sidecar unreadable: %s", path, exc_info=True)+ return b""+++def audio_exists(path: Path | str | None) -> bool:+ """``True`` when the sidecar is still on disk. Never raises."""+ if not path:+ return False+ try:+ return Path(path).is_file()+ except OSError:+ return False+++def delete_dictation_audio(path: Path | str | None) -> bool:+ """Remove one sidecar. ``False`` when there was nothing to remove."""+ if not path:+ return False+ try:+ Path(path).unlink()+ return True+ except FileNotFoundError:+ return False+ except OSError as exc:+ log.warning("could not delete a dictation audio sidecar: %s", exc)+ return False+++def purge_dictation_audio(*, directory: Path | str | None = None) -> int:+ """Delete every sidecar. Returns how many files went away.++ This is what "delete my dictation history" calls. It must leave nothing+ behind, so the user's mental model matches the disk.+ """+ base = Path(directory) if directory is not None else default_audio_dir()+ removed = 0+ try:+ candidates = sorted(base.glob("*.wav"))+ except OSError:+ return 0+ for item in candidates:+ if delete_dictation_audio(item):+ removed += 1+ return removed+++def prune_audio(+ *,+ max_files: int = 20,+ retention_days: int = 7,+ directory: Path | str | None = None,+) -> int:+ """Enforce the retention caps. Returns how many files were deleted.++ Two independent caps, both applied: anything older than ``retention_days``+ goes, and only the ``max_files`` newest survive. ``0`` for either value+ disables that cap; ``max_files = 0`` therefore means "age-based only", not+ "delete everything" — use :func:`purge_dictation_audio` for that.+ """+ import time++ base = Path(directory) if directory is not None else default_audio_dir()+ try:+ files = [p for p in base.glob("*.wav") if p.is_file()]+ except OSError:+ return 0+ if not files:+ return 0++ stamped: list[tuple[float, Path]] = []+ for item in files:+ try:+ stamped.append((item.stat().st_mtime, item))+ except OSError:+ continue+ # Newest first — the survivors of a count cap are the recent ones.+ stamped.sort(key=lambda pair: pair[0], reverse=True)++ doomed: list[Path] = []+ if retention_days and retention_days > 0:+ cutoff = time.time() - (float(retention_days) * 86_400.0)+ doomed.extend(item for mtime, item in stamped if mtime < cutoff)+ if max_files and max_files > 0:+ doomed.extend(item for _, item in stamped[int(max_files) :])++ removed = 0+ for item in dict.fromkeys(doomed): # de-duplicate, keep order+ if delete_dictation_audio(item):+ removed += 1+ return removed+++__all__ = [+ "CHANNELS",+ "MAX_AUDIO_BYTES",+ "MAX_AUDIO_SECONDS",+ "SAMPLE_RATE",+ "SAMPLE_WIDTH",+ "audio_exists",+ "audio_path_for",+ "default_audio_dir",+ "delete_dictation_audio",+ "load_dictation_audio",+ "prune_audio",+ "purge_dictation_audio",+ "save_dictation_audio",+]diff --git a/jarvis/dictation/cleanup.py b/jarvis/dictation/cleanup.pyindex 69de4c7c7f..7aa378d551 100644--- a/jarvis/dictation/cleanup.py+++ b/jarvis/dictation/cleanup.py@@ -141,8 +141,15 @@ def normalize_language(language: str | None) -> str | None:return code if code in SUPPORTED_LANGUAGES else None-def _count_words(text: str) -> int:- return len(_WORD_RE.findall(text))+def count_words(text: str) -> int:+ """How many words a transcript contains.++ Public because the history and the statistics sidecar need the SAME answer+ the destruction ceiling uses. A second word regex living somewhere else+ would drift from this one the first time either is touched, and then+ "words dictated" and "words removed" would stop being comparable numbers.+ """+ return len(_WORD_RE.findall(text or ""))def _compile_patterns(language: str) -> list[re.Pattern[str]]:@@ -214,7 +221,7 @@ def clean_transcript()if not remove_fillers:return CleanupResult(- text=raw, raw=raw, removed_words=0, total_words=_count_words(raw),+ text=raw, raw=raw, removed_words=0, total_words=count_words(raw),applied=False, reason="disabled",)@@ -223,11 +230,11 @@ def clean_transcript(# Honest no-op: we would rather leave a filler in than damage a# sentence in a language whose rules we do not have.return CleanupResult(- text=raw, raw=raw, removed_words=0, total_words=_count_words(raw),+ text=raw, raw=raw, removed_words=0, total_words=count_words(raw),applied=False, reason="no_rules",)- total = _count_words(raw)+ total = count_words(raw)cleaned = rawtry:for pattern in _PATTERN_CACHE[lang]:@@ -239,7 +246,7 @@ def clean_transcript(applied=False, reason="error",)- remaining = _count_words(cleaned)+ remaining = count_words(cleaned)removed = max(0, total - remaining)# Nothing survived — always a defect in the rules, never a valid result.@@ -274,5 +281,6 @@ __all__ = ["SUPPORTED_LANGUAGES","CleanupResult","clean_transcript",+ "count_words","normalize_language",]diff --git a/jarvis/dictation/history.py b/jarvis/dictation/history.pyindex c2720d284b..5d2f6aeee5 100644--- a/jarvis/dictation/history.py+++ b/jarvis/dictation/history.py@@ -17,6 +17,19 @@ purgeable with one call. It can be switched off entirelyStorage pattern mirrors ``jarvis.speech.stt_dictionary.DictionaryStore``:atomic tempfile + ``os.replace`` so a crash mid-write never leaves a torn file.++Two companion sidecars sit next to this one, both derived from ITS path so a+history pointed somewhere else takes them along:++* ``dictation_stats.json`` (:mod:`jarvis.dictation.stats`) — per-day counts and+ durations, no text, never pruned. It exists because totals derived from a+ 30-day rolling window would silently stop growing.+* ``dictation_audio/`` (:mod:`jarvis.dictation.audio`) — WAV files kept ONLY for+ dictations that produced nothing usable, and only when the user allows it.+ It is what makes Restore more than a button that shakes its head.++Deleting the history deletes all three. Anything less would be a quiet lie+about what the application still knows."""from __future__ import annotations@@ -27,10 +40,14 @@ import osimport tempfileimport threadingimport uuid-from dataclasses import asdict, dataclass, field+from dataclasses import asdict, dataclass, field, replace+from dataclasses import fields as fields_offrom datetime import UTC, datetime, timedeltafrom pathlib import Path-from typing import Any+from typing import TYPE_CHECKING, Any++if TYPE_CHECKING: # import-time cost stays zero on the dictation hot path+ from jarvis.dictation.stats import DictationStatslog = logging.getLogger(__name__)@@ -54,7 +71,7 @@ class DictationEntry:language: str = ""#: Seconds of audio.duration_s: float = 0.0- #: ``inserted`` | ``clipboard_only`` | ``unavailable`` | ``chat``.+ #: One of ``jarvis.dictation.outcomes.DICTATION_OUTCOMES``.outcome: str = ""#: How it got there, e.g. ``clipboard+ctrl_v``.method: str = ""@@ -62,11 +79,58 @@ class DictationEntry:removed_words: int = 0#: Why a cleanup did not apply — ``""`` when it did.cleanup_reason: str = ""+ #: Words in the inserted text. Stored rather than recomputed so the+ #: statistics sidecar and the UI can never disagree about one entry.+ word_count: int = 0+ #: The user hid this entry. Separate from ``outcome`` on purpose: an entry+ #: can be both ``inserted`` and discarded, and folding the two into one+ #: string would make that state unrepresentable (AD-6).+ discarded: bool = False+ #: Local path of the kept audio sidecar, or ``None``. NEVER serialised to+ #: an API response — the wire shape exposes ``audio_available`` instead,+ #: because a filesystem path in a JSON body is an information leak that+ #: buys the client nothing.+ audio_path: str | None = None+ #: Why transcription failed, when it did. ``None`` on every other path.+ error: str | None = Nonemetadata: dict[str, Any] = field(default_factory=dict)- def to_dict(self) -> dict[str, Any]:+ def to_storage_dict(self) -> dict[str, Any]:+ """The full on-disk shape, including ``audio_path``. Sidecar only."""return asdict(self)+ def to_dict(self) -> dict[str, Any]:+ """The API shape: no ``audio_path``, plus a resolved availability flag.++ The SAFE shape is the default one on purpose. A serialiser that leaks+ by default and has to be opted out of is a leak waiting for the one+ call site that forgets — so the on-disk shape is the one that needs an+ explicit name (:meth:`to_storage_dict`), not the other way round.++ ``audio_available`` is a live filesystem check rather than a stored+ boolean, because the retention prune deletes sidecars behind the+ history's back — a cached flag would offer the user a Restore button+ for audio that is no longer there.+ """+ from jarvis.dictation.audio import audio_exists++ return {+ "id": self.id,+ "created_at": self.created_at,+ "raw_text": self.raw_text,+ "text": self.text,+ "language": self.language,+ "duration_s": self.duration_s,+ "outcome": self.outcome,+ "method": self.method,+ "removed_words": self.removed_words,+ "cleanup_reason": self.cleanup_reason,+ "word_count": self.word_count,+ "discarded": self.discarded,+ "audio_available": audio_exists(self.audio_path),+ "error": self.error,+ }+def default_history_path() -> Path:"""``<user data>/data/dictation_history.json``."""@@ -83,17 +147,51 @@ class DictationHistory:"no history", which is a cosmetic loss."""- def __init__(self, path: Path | str | None = None) -> None:+ def __init__(+ self,+ path: Path | str | None = None,+ *,+ stats_path: Path | str | None = None,+ ) -> None:self._path = Path(path) if path is not None else default_history_path()+ # The statistics sidecar lives NEXT TO the history file rather than at+ # a globally resolved location, so pointing the history at a temporary+ # directory (a test, a second profile) moves both together instead of+ # leaking counters into the real user data directory.+ self._stats_path = (+ Path(stats_path)+ if stats_path is not None+ else self._path.parent / "dictation_stats.json"+ )self._lock = threading.Lock()@propertydef path(self) -> Path:return self._path+ @property+ def stats_path(self) -> Path:+ return self._stats_path++ @property+ def audio_dir(self) -> Path:+ """Where this history's audio sidecars live — beside the JSON file.++ Derived rather than resolved globally for the same reason as+ ``stats_path``: a history pointed at a temporary directory must not+ be able to purge the real user's audio.+ """+ return self._path.parent / "dictation_audio"++ def stats(self) -> DictationStats:+ """The lifetime-counter sidecar bound to this history."""+ from jarvis.dictation.stats import DictationStats++ return DictationStats(self._stats_path)+# -- reading ---------------------------------------------------------- def list_all(self) -> list[DictationEntry]:+ def list_all(self, *, include_discarded: bool = True) -> list[DictationEntry]:"""Newest first. An unreadable file reads as an empty history."""try:raw = self._path.read_text(encoding="utf-8")@@ -124,13 +222,31 @@ class DictationHistory:method=str(item.get("method") or ""),removed_words=int(item.get("removed_words") or 0),cleanup_reason=str(item.get("cleanup_reason") or ""),+ # Fields added after the first release. The reader has+ # always built field-by-field with .get(), so a file+ # written by an older install reads as these defaults+ # instead of failing — verified, not assumed+ # (test_history_written_before_the_new_fields_reads_as_defaults).+ word_count=int(item.get("word_count") or 0),+ discarded=bool(item.get("discarded") or False),+ audio_path=(str(item["audio_path"]) if item.get("audio_path") else None),+ error=(str(item["error"]) if item.get("error") else None),metadata=dict(item.get("metadata") or {}),))except (TypeError, ValueError):continue # one bad row never invalidates the rest+ if not include_discarded:+ entries = [e for e in entries if not e.discarded]return entries+ def get(self, entry_id: str) -> DictationEntry | None:+ """One entry by id, or ``None``."""+ for entry in self.list_all():+ if entry.id == entry_id:+ return entry+ return None+# -- writing ---------------------------------------------------------def add(@@ -144,12 +260,24 @@ class DictationHistory:method: str = "",removed_words: int = 0,cleanup_reason: str = "",+ word_count: int | None = None,+ error: str | None = None,max_entries: int = 200,retention_days: int = 30,) -> DictationEntry | None:- """Record one dictation and prune. ``None`` when nothing was stored."""- if not (raw_text or text):+ """Record one dictation and prune. ``None`` when nothing was stored.++ A dictation with no text at all is still recorded when its outcome says+ the user lost something (``failed`` / ``cancelled`` / ``empty``) — that+ row is the only place a later Restore can start from. Without it, the+ worst failure this feature has is also its most invisible one.+ """+ from jarvis.dictation.outcomes import is_recoverable++ if not (raw_text or text) and not is_recoverable(outcome):return None+ from jarvis.dictation.cleanup import count_words+entry = DictationEntry(id=uuid.uuid4().hex,created_at=datetime.now(UTC).isoformat(),@@ -161,9 +289,19 @@ class DictationHistory:method=str(method or ""),removed_words=max(0, int(removed_words or 0)),cleanup_reason=str(cleanup_reason or ""),+ word_count=(+ max(0, int(word_count))+ if word_count is not None+ else count_words(text or raw_text)+ ),+ error=(str(error) if error else None),)try:with self._lock:+ # Counted BEFORE the prune, so a dictation that immediately+ # ages out of the rolling window still shows up in the lifetime+ # totals. That ordering is the whole point of a second sidecar.+ self._record_stats(entry)entries = [entry, *self.list_all()]entries = _prune(entries,@@ -176,31 +314,110 @@ class DictationHistory:return Nonereturn entry+ def update(self, entry_id: str, **fields: Any) -> DictationEntry | None:+ """Replace named fields on one entry. ``None`` when the id is unknown.++ Used by the audio hand-off (``audio_path`` is only known after the+ entry exists, because the file name is built from its id) and by a+ Restore that re-transcribed. Unknown field names are ignored rather+ than raised, so an older caller can never break a write.+ """+ allowed = {f.name for f in fields_of(DictationEntry)} - {"id", "created_at"}+ changes = {k: v for k, v in fields.items() if k in allowed}+ if not changes:+ return None+ if "raw_text" in changes:+ changes["raw_text"] = _clip(str(changes["raw_text"] or ""))+ if "text" in changes:+ changes["text"] = _clip(str(changes["text"] or ""))+ if "audio_path" in changes and changes["audio_path"] is not None:+ changes["audio_path"] = str(changes["audio_path"])+ try:+ with self._lock:+ entries = self.list_all()+ updated: DictationEntry | None = None+ out: list[DictationEntry] = []+ for entry in entries:+ if entry.id == entry_id and updated is None:+ updated = replace(entry, **changes)+ out.append(updated)+ else:+ out.append(entry)+ if updated is None:+ return None+ self._write(out)+ return updated+ except Exception: # noqa: BLE001+ log.warning("could not update a dictation history entry", exc_info=True)+ return None++ def set_discarded(self, entry_id: str, value: bool = True) -> DictationEntry | None:+ """Hide or un-hide one entry. The soft counterpart to :meth:`delete`.++ Soft on purpose: the trash icon in the UI calls this, so a mis-click+ stays recoverable. ``DELETE /history/{id}`` keeps hard-delete semantics+ for anyone scripting the CLI (AD-8).+ """+ return self.update(entry_id, discarded=bool(value))+def delete(self, entry_id: str) -> bool:+ """Hard-delete one entry AND its audio sidecar. Irreversible."""try:with self._lock:entries = self.list_all()kept = [e for e in entries if e.id != entry_id]if len(kept) == len(entries):return False+ doomed = [e for e in entries if e.id == entry_id]self._write(kept)- return Trueexcept Exception: # noqa: BLE001log.warning("could not delete a dictation history entry", exc_info=True)return False+ # Outside the lock: the sidecar is a separate file and a slow unlink+ # must not hold up another dictation being recorded.+ for entry in doomed:+ if entry.audio_path:+ from jarvis.dictation.audio import delete_dictation_audio++ delete_dictation_audio(entry.audio_path)+ return Truedef clear(self) -> bool:- """Purge everything. The user-facing "delete my dictation history"."""+ """Purge everything. The user-facing "delete my dictation history".++ Deliberately total: the entries, the kept audio and the lifetime+ counters all go. Leaving the streak standing after someone asked for+ their dictation history to be deleted would be a quiet lie about what+ the app still knows.+ """try:with self._lock:self._write([])- return Trueexcept Exception: # noqa: BLE001log.warning("could not clear the dictation history", exc_info=True)return False+ try:+ from jarvis.dictation.audio import purge_dictation_audio++ purge_dictation_audio(directory=self.audio_dir)+ self.stats().reset()+ except Exception: # noqa: BLE001+ log.warning("could not purge the dictation sidecars", exc_info=True)+ return True++ def _record_stats(self, entry: DictationEntry) -> None:+ """Feed one entry to the lifetime counters. Never raises."""+ try:+ self.stats().record(+ created_at=entry.created_at,+ word_count=entry.word_count,+ duration_s=entry.duration_s,+ )+ except Exception: # noqa: BLE001 — a counter never costs a dictation+ log.debug("dictation statistics write failed", exc_info=True)def _write(self, entries: list[DictationEntry]) -> None:- payload = {"version": 1, "entries": [e.to_dict() for e in entries]}+ payload = {"version": 1, "entries": [e.to_storage_dict() for e in entries]}self._path.parent.mkdir(parents=True, exist_ok=True)# Atomic tempfile + os.replace: a crash mid-write never leaves a torn# sidecar (same discipline as the config writer, AP-7).@@ -226,6 +443,31 @@ def _clip(text: str) -> str:return value[:MAX_TEXT_LEN] + " […truncated]"+def _holds_pending_recovery(entry: DictationEntry) -> bool:+ """``True`` when dropping this entry would strand a Restore.++ An entry the user can still recover from — one that ended badly or was+ discarded, and whose audio is still on disk — is the ONLY thing that makes+ the Restore button do anything. Letting the ordinary count cap evict it+ would delete the row while leaving the audio file behind: the user sees the+ entry vanish, the disk keeps the recording, and nobody can get either back.+ So these are exempt from the count cap.++ They are NOT exempt from the retention window: the audio itself ages out on+ its own schedule, and an entry whose sidecar is already gone is not a+ pending recovery any more.+ """+ from jarvis.dictation.outcomes import is_recoverable++ if not entry.audio_path:+ return False+ if not (entry.discarded or is_recoverable(entry.outcome)):+ return False+ from jarvis.dictation.audio import audio_exists++ return audio_exists(entry.audio_path)++def _prune(entries: list[DictationEntry],*,@@ -235,9 +477,12 @@ def _prune("""Drop entries past the count cap or the retention window.``retention_days = 0`` means "keep until the count cap"; an unparseable- timestamp is kept rather than silently discarded.+ timestamp is kept rather than silently discarded. ``max_entries = 0`` is an+ explicit "keep nothing" and overrides every exemption."""cap = max(0, min(int(max_entries or 0), MAX_ENTRIES_CEILING))+ if not cap:+ return []kept = entriesif retention_days and retention_days > 0:cutoff = datetime.now(UTC) - timedelta(days=int(retention_days))@@ -253,7 +498,19 @@ def _prune(if created >= cutoff:fresh.append(entry)kept = fresh- return kept[:cap] if cap else []++ result: list[DictationEntry] = []+ budget = cap+ for entry in kept: # newest first — the survivors of the cap are recent+ if _holds_pending_recovery(entry):+ result.append(entry)+ continue+ if budget > 0:+ result.append(entry)+ budget -= 1+ # The exemption is bounded too: the audio retention caps how many sidecars+ # can exist, and the absolute ceiling backstops a pathological file.+ return result[:MAX_ENTRIES_CEILING]__all__ = [diff --git a/jarvis/dictation/outcomes.py b/jarvis/dictation/outcomes.pynew file mode 100644index 0000000000..51d92bf502--- /dev/null+++ b/jarvis/dictation/outcomes.py@@ -0,0 +1,83 @@+"""The single vocabulary for "how did this dictation end".++Why this file exists at all+---------------------------+The outcome string is a value that crosses five layers — the speech pipeline+writes it, ``DictationCompleted`` carries it, the history sidecar stores it,+the REST layer serialises it and the UI renders a label for it. That is exactly+the shape of drift that has bitten this repo four times (BUG-008, AP-4): one+site learns a new value, the others keep an older list, and the UI ends up+rendering a raw identifier or nothing at all.++So the vocabulary is declared **once**, here, and every other layer imports it.+A cross-layer parity test pins the TypeScript mirror against this tuple.++What each value means+---------------------+``inserted``+ The text was typed or pasted into the focused window. The happy path.+``clipboard_only``+ Insertion was not possible, so the text was left on the clipboard. The+ user still has their words; they just have to paste them.+``unavailable``+ Neither insertion nor the clipboard worked (no desktop session, no+ clipboard backend). The transcript exists only in the history.+``chat``+ The dictation was routed into the chat instead of the desktop.+``empty``+ Transcription succeeded but returned nothing — silence, or speech too+ quiet to resolve. Not an error, but nothing to show for it either.+``cancelled``+ The user aborted before a transcript existed.+``failed``+ Transcription itself failed — a provider error, a missing key, a wedged+ engine. This is the value that used to be invisible: the pipeline+ swallowed the error and the dictation looked like plain silence.++``discarded`` is deliberately **not** in this list. It is a separate boolean+on the history entry, because an entry can be both ``inserted`` and discarded+by the user afterwards; folding the two into one string would make that state+unrepresentable.+"""++from __future__ import annotations++from typing import Final++#: Every outcome the pipeline may report, in rough order of desirability.+#: Mirrored in TypeScript as ``DICTATION_OUTCOMES`` and pinned by a parity test.+DICTATION_OUTCOMES: Final[tuple[str, ...]] = (+ "inserted",+ "clipboard_only",+ "unavailable",+ "chat",+ "empty",+ "cancelled",+ "failed",+)++#: Outcomes for which there is nothing usable to show the user, so keeping the+#: audio (when the user allows it) is what makes a later Restore possible.+#: The success outcomes are excluded on purpose: audio is the most sensitive+#: thing this application ever stores, so it is only ever kept when it buys+#: back something the user actually lost.+RECOVERABLE_OUTCOMES: Final[frozenset[str]] = frozenset(+ {"empty", "cancelled", "failed"}+)+++def is_recoverable(outcome: str | None) -> bool:+ """``True`` when this outcome left the user with nothing to show for it.++ Tolerant by design: an unknown value from an older install reads as "not+ recoverable" rather than raising, because a vocabulary mismatch must never+ cost someone their dictation.+ """+ return str(outcome or "") in RECOVERABLE_OUTCOMES+++__all__ = [+ "DICTATION_OUTCOMES",+ "RECOVERABLE_OUTCOMES",+ "is_recoverable",+]diff --git a/jarvis/dictation/stats.py b/jarvis/dictation/stats.pynew file mode 100644index 0000000000..f19c6de410--- /dev/null+++ b/jarvis/dictation/stats.py@@ -0,0 +1,421 @@+"""Lifetime dictation totals — a never-pruned sidecar next to the history.++Why a second file instead of counting the history+-------------------------------------------------+The history is a deliberately small rolling window (200 entries / 30 days by+default) so that the most sensitive text this application holds ages out on+its own. Deriving "words dictated" or a "day streak" from that window would+quietly lie: the totals would stop growing once the window filled, and a+streak could never exceed the retention setting no matter how long someone had+been using the feature.++So the counters live in their own sidecar, ``dictation_stats.json``, written+next to the history file. It stores **no text at all** — only per-day counts+and durations — which is why it can be kept forever without becoming the+privacy problem the history window exists to avoid.++Two details that are easy to get wrong+--------------------------------------+1. **Days are LOCAL days.** Entries are timestamped in UTC, but "did I dictate+ today" is a question about the user's wall clock. Bucketing by UTC date+ shreds the streak for everyone east of UTC — their evening work lands on+ tomorrow — and for everyone west of it their morning lands on yesterday.+2. **Today gets grace.** Before the first dictation of the day the streak+ counts back from *yesterday*, so the badge reads "6 days" over breakfast+ instead of a demoralising and simply wrong 0. It only reaches 0 once+ yesterday was quiet too. Same semantics as the board's activity streak.++This is an information badge, nothing else: no popup, no notification, no+"you lost your streak". A number that can punish you is a different product.++Storage pattern mirrors the history sidecar: atomic tempfile + ``os.replace``,+so a crash mid-write never leaves a torn file, and every public method+degrades to "no stats" instead of raising.+"""++from __future__ import annotations++import json+import logging+import os+import tempfile+import threading+from collections.abc import Iterable, Sequence+from dataclasses import dataclass+from datetime import date as _date+from datetime import datetime, timedelta+from pathlib import Path+from typing import Any++log = logging.getLogger(__name__)++#: How many days the API hands to the UI. Enough for a year-ish of sparkline+#: without shipping a decade of JSON on every poll.+DEFAULT_BY_DAY_LIMIT = 90++#: Upper bound on the retained day buckets. At ~40 bytes a day this is a few+#: hundred kilobytes after ten years; the cap exists so the file cannot grow+#: without any bound at all, not because the data is expensive.+MAX_DAYS_RETAINED = 3_650+++@dataclass(frozen=True, slots=True)+class DayStat:+ """One local calendar day of dictation activity."""++ date: str+ dictations: int = 0+ words: int = 0+ seconds: float = 0.0++ def to_dict(self) -> dict[str, Any]:+ return {+ "date": self.date,+ "dictations": self.dictations,+ "words": self.words,+ "seconds": round(self.seconds, 2),+ }+++# ----------------------------------------------------------------------+# Day bucketing+# ----------------------------------------------------------------------+++def today_key() -> str:+ """Today's LOCAL calendar date as ``YYYY-MM-DD``."""+ return datetime.now().astimezone().date().isoformat()+++def local_day(created_at: str | None) -> str | None:+ """ISO timestamp -> the LOCAL calendar day it belongs to.++ A naive timestamp is read as UTC (that is what the history writes), then+ converted to the local zone before the date is taken. Anything unparseable+ returns ``None`` so the caller can skip it rather than mis-bucket it.+ """+ if not created_at:+ return None+ try:+ moment = datetime.fromisoformat(str(created_at))+ except (TypeError, ValueError):+ return None+ if moment.tzinfo is None:+ from datetime import UTC++ moment = moment.replace(tzinfo=UTC)+ try:+ return moment.astimezone().date().isoformat()+ except (OSError, OverflowError, ValueError):+ return None+++def _parse_day(value: str) -> _date | None:+ try:+ return _date.fromisoformat(str(value))+ except (TypeError, ValueError):+ return None+++def current_streak(active_days: Iterable[str]) -> int:+ """Consecutive local days up to today with at least one dictation.++ Grace rule: a quiet *today* does not break the run — the count starts from+ yesterday instead. The streak only reads 0 once yesterday was quiet too.+ """+ days = {d for d in active_days if d}+ if not days:+ return 0+ cursor = datetime.now().astimezone().date()+ if cursor.isoformat() not in days:+ cursor -= timedelta(days=1)+ streak = 0+ while cursor.isoformat() in days:+ streak += 1+ cursor -= timedelta(days=1)+ return streak+++def longest_streak(active_days: Iterable[str]) -> int:+ """The best run of consecutive active days ever recorded."""+ parsed = sorted({d for d in (_parse_day(v) for v in active_days) if d is not None})+ longest = 0+ run = 0+ previous: _date | None = None+ for day in parsed:+ run = run + 1 if previous is not None and (day - previous).days == 1 else 1+ longest = max(longest, run)+ previous = day+ return longest+++def _wpm(words: int, seconds: float) -> float:+ """Words per minute, or ``0.0`` when there is no time to divide by."""+ if seconds <= 0.0:+ return 0.0+ return round(float(words) / (float(seconds) / 60.0), 1)+++def _summary_payload(+ *,+ source: str,+ totals: dict[str, Any],+ days: dict[str, DayStat],+ by_day_limit: int,+) -> dict[str, Any]:+ key = today_key()+ today = days.get(key, DayStat(date=key))+ ordered = sorted(days.values(), key=lambda d: d.date, reverse=True)+ active = [d.date for d in days.values() if d.dictations > 0]+ limit = max(0, int(by_day_limit))+ return {+ "source": source,+ "totals": {+ "dictations": int(totals.get("dictations", 0)),+ "words": int(totals.get("words", 0)),+ "seconds": round(float(totals.get("seconds", 0.0)), 2),+ "wpm": _wpm(+ int(totals.get("words", 0)), float(totals.get("seconds", 0.0))+ ),+ },+ "today": {"dictations": today.dictations, "words": today.words},+ "streak": {+ "current_days": current_streak(active),+ "longest_days": longest_streak(active),+ },+ "by_day": [d.to_dict() for d in ordered[:limit]],+ }+++# ----------------------------------------------------------------------+# The sidecar+# ----------------------------------------------------------------------+++def default_stats_path() -> Path:+ """``<user data>/data/dictation_stats.json``."""+ from jarvis.core.paths import user_data_dir++ return Path(user_data_dir()) / "data" / "dictation_stats.json"+++class DictationStats:+ """Per-day and lifetime counters. Never raises to the caller.++ Every method degrades to "no stats" on a broken or unreadable file — a+ counter is never worth costing someone their dictation.+ """++ def __init__(self, path: Path | str | None = None) -> None:+ self._path = Path(path) if path is not None else default_stats_path()+ self._lock = threading.Lock()++ @property+ def path(self) -> Path:+ return self._path++ @property+ def exists(self) -> bool:+ try:+ return self._path.is_file()+ except OSError:+ return False++ # -- reading ---------------------------------------------------------++ def load(self) -> tuple[dict[str, Any], dict[str, DayStat]]:+ """``(totals, days)``. An unreadable or corrupt file reads as empty."""+ totals: dict[str, Any] = {"dictations": 0, "words": 0, "seconds": 0.0}+ days: dict[str, DayStat] = {}+ try:+ raw = self._path.read_text(encoding="utf-8")+ except FileNotFoundError:+ return totals, days+ except OSError as exc:+ log.warning("dictation stats unreadable: %s", exc)+ return totals, days+ try:+ payload = json.loads(raw)+ except (ValueError, TypeError) as exc:+ log.warning("dictation stats are corrupt, ignoring them: %s", exc)+ return totals, days+ if not isinstance(payload, dict):+ return totals, days++ stored_totals = payload.get("totals")+ if isinstance(stored_totals, dict):+ totals = {+ "dictations": _as_int(stored_totals.get("dictations")),+ "words": _as_int(stored_totals.get("words")),+ "seconds": _as_float(stored_totals.get("seconds")),+ }+ stored_days = payload.get("days")+ if isinstance(stored_days, dict):+ for key, value in stored_days.items():+ if not isinstance(value, dict) or _parse_day(key) is None:+ continue # one bad bucket never invalidates the rest+ days[str(key)] = DayStat(+ date=str(key),+ dictations=_as_int(value.get("dictations")),+ words=_as_int(value.get("words")),+ seconds=_as_float(value.get("seconds")),+ )+ return totals, days++ def summary(self, *, by_day_limit: int = DEFAULT_BY_DAY_LIMIT) -> dict[str, Any]:+ """The lifetime view: totals, today, streak and the recent days."""+ totals, days = self.load()+ return _summary_payload(+ source="lifetime", totals=totals, days=days, by_day_limit=by_day_limit+ )++ # -- writing ---------------------------------------------------------++ def record(+ self,+ *,+ created_at: str | None = None,+ word_count: int = 0,+ duration_s: float = 0.0,+ ) -> bool:+ """Count one dictation. ``False`` when nothing was recorded.++ Only dictations that produced words are counted. A failed or empty one+ still belongs in the history (that is how a Restore finds it), but+ counting it would drag the words-per-minute figure toward zero for a+ reason that has nothing to do with how fast the user speaks.+ """+ words = _as_int(word_count)+ if words <= 0:+ return False+ day = local_day(created_at) or today_key()+ seconds = max(0.0, _as_float(duration_s))+ try:+ with self._lock:+ totals, days = self.load()+ previous = days.get(day, DayStat(date=day))+ days[day] = DayStat(+ date=day,+ dictations=previous.dictations + 1,+ words=previous.words + words,+ seconds=previous.seconds + seconds,+ )+ totals = {+ "dictations": _as_int(totals.get("dictations")) + 1,+ "words": _as_int(totals.get("words")) + words,+ "seconds": _as_float(totals.get("seconds")) + seconds,+ }+ self._write(totals, days)+ except Exception: # noqa: BLE001 — a counter never costs a dictation+ log.warning("could not record the dictation statistics", exc_info=True)+ return False+ return True++ def reset(self) -> bool:+ """Zero everything. What "delete my dictation history" also calls.++ The streak resets with it — the UI copy has to say so, because a+ silently reset streak reads as a bug rather than a consequence.+ """+ try:+ with self._lock:+ self._write({"dictations": 0, "words": 0, "seconds": 0.0}, {})+ return True+ except Exception: # noqa: BLE001+ log.warning("could not reset the dictation statistics", exc_info=True)+ return False++ def _write(self, totals: dict[str, Any], days: dict[str, DayStat]) -> None:+ ordered = sorted(days.values(), key=lambda d: d.date, reverse=True)+ kept = ordered[:MAX_DAYS_RETAINED]+ payload = {+ "version": 1,+ "totals": {+ "dictations": _as_int(totals.get("dictations")),+ "words": _as_int(totals.get("words")),+ "seconds": round(_as_float(totals.get("seconds")), 2),+ },+ "days": {d.date: d.to_dict() for d in kept},+ }+ self._path.parent.mkdir(parents=True, exist_ok=True)+ fd, tmp_name = tempfile.mkstemp(+ dir=str(self._path.parent), prefix=".dictation_stats_", suffix=".tmp"+ )+ try:+ with os.fdopen(fd, "w", encoding="utf-8") as fh:+ json.dump(payload, fh, ensure_ascii=False, indent=2)+ os.replace(tmp_name, self._path)+ except Exception:+ try:+ os.unlink(tmp_name)+ except OSError:+ pass+ raise+++# ----------------------------------------------------------------------+# Fallback: derive a summary from the history window+# ----------------------------------------------------------------------+++def summarize_entries(+ entries: Sequence[Any],+ *,+ by_day_limit: int = DEFAULT_BY_DAY_LIMIT,+) -> dict[str, Any]:+ """Build the same summary shape out of history entries alone.++ This is the honest fallback for an install that predates the sidecar: the+ numbers are real, they are just bounded by the history window. The caller+ surfaces that as ``source: "window"`` so the UI can label the panel+ truthfully instead of presenting a 30-day count as a lifetime total.+ """+ totals = {"dictations": 0, "words": 0, "seconds": 0.0}+ days: dict[str, DayStat] = {}+ for entry in entries or ():+ words = _as_int(getattr(entry, "word_count", 0))+ if words <= 0:+ continue+ day = local_day(getattr(entry, "created_at", "")) or today_key()+ seconds = max(0.0, _as_float(getattr(entry, "duration_s", 0.0)))+ previous = days.get(day, DayStat(date=day))+ days[day] = DayStat(+ date=day,+ dictations=previous.dictations + 1,+ words=previous.words + words,+ seconds=previous.seconds + seconds,+ )+ totals["dictations"] = _as_int(totals["dictations"]) + 1+ totals["words"] = _as_int(totals["words"]) + words+ totals["seconds"] = _as_float(totals["seconds"]) + seconds+ return _summary_payload(+ source="window", totals=totals, days=days, by_day_limit=by_day_limit+ )+++def _as_int(value: Any) -> int:+ try:+ return max(0, int(value or 0))+ except (TypeError, ValueError):+ return 0+++def _as_float(value: Any) -> float:+ try:+ return max(0.0, float(value or 0.0))+ except (TypeError, ValueError):+ return 0.0+++__all__ = [+ "DEFAULT_BY_DAY_LIMIT",+ "MAX_DAYS_RETAINED",+ "DayStat",+ "DictationStats",+ "current_streak",+ "default_stats_path",+ "local_day",+ "longest_streak",+ "summarize_entries",+ "today_key",+]diff --git a/jarvis/ui/web/frontend/src/components/ApiKeyForm.tsx b/jarvis/ui/web/frontend/src/components/ApiKeyForm.tsxindex 84a5b2aa19..6916945e31 100644--- a/jarvis/ui/web/frontend/src/components/ApiKeyForm.tsx+++ b/jarvis/ui/web/frontend/src/components/ApiKeyForm.tsx@@ -39,6 +39,25 @@ interface ApiKeyFormProps {onSavedActivate?: () => void;}+/**+ * Tell every mounted surface that this credential slot changed.+ *+ * The parent card's `onChanged` only refreshes the card the form sits on. The+ * same key is shown by other screens (the API-Keys view and the voice+ * section's "API Keys" tab render the same provider block), and the section+ * health rollup has to re-check too. `useProviders` and `useSectionHealth`+ * already listen for this event, so one dispatch keeps them all honest without+ * waiting for a backend broadcast to arrive over the WebSocket. Established+ * in-repo pattern (TelephonyView). Only the key NAME travels — never a value.+ */+function announceSecretChange(secretKey: string, action: "set" | "delete") {+ window.dispatchEvent(+ new CustomEvent("jarvis:secret-configured", {+ detail: { key: secretKey, action },+ }),+ );+}+/*** Single-key input form: password input + "Save" + delete action for an* existing value. Writes directly to POST /api/secrets/{key}; the value@@ -70,6 +89,7 @@ export function ApiKeyForm({ secretKey, dashboardUrl, configured, credentialHelpsetEditing(false);onChanged?.();onSavedActivate?.();+ announceSecretChange(secretKey, "set");} catch (e) {pushToast("error", `${t("common.save_failed")}: ${(e as Error).message}`);} finally {@@ -92,6 +112,7 @@ export function ApiKeyForm({ secretKey, dashboardUrl, configured, credentialHelppushToast("info", `${secretKey} removed`);setEditing(true);onChanged?.();+ announceSecretChange(secretKey, "delete");} catch (e) {pushToast("error", `${t("common.delete_failed")}: ${(e as Error).message}`);} finally {diff --git a/jarvis/ui/web/frontend/src/components/providers/ProviderTierSection.tsx b/jarvis/ui/web/frontend/src/components/providers/ProviderTierSection.tsxnew file mode 100644index 0000000000..ed6a4ce80c--- /dev/null+++ b/jarvis/ui/web/frontend/src/components/providers/ProviderTierSection.tsx@@ -0,0 +1,1660 @@+import { useEffect, useMemo, useRef, useState } from "react";+import { AlertCircle, Bot, Brain, Check, Copy, Loader2, LogIn, LogOut, Mic, PlugZap, Radio, Sparkles, Terminal, Volume2, Waypoints, XCircle } from "lucide-react";+import { AltCredentialNote } from "@/components/AltCredentialNote";+import { ApiKeyForm } from "@/components/ApiKeyForm";+import { BrainModelSelector } from "@/components/BrainModelSelector";+import { OpenRouterTtsControls } from "@/components/OpenRouterTtsVoicePicker";+import { CuModelSelector } from "@/components/CuModelSelector";+import { RealtimeOptionsControl } from "@/components/RealtimeOptionsControl";+import { ProviderBillingBadge } from "@/components/ProviderBillingBadge";+import { Button } from "@/components/ui/button";+import {+ codexLogout,+ loginAntigravity,+ logoutAntigravity,+ type ProviderDescriptor,+ type ProviderTestResult,+ type ProviderTestStatus,+ type ProviderTier,+ type SectionHealth,+ saveProviderBaseUrl,+ sectionHealthForSubject,+ startCodexLogin,+ switchBrainProvider,+ switchComputerUseProvider,+ switchRealtimeProvider,+ switchSttProvider,+ switchTtsProvider,+ testProvider,+ useSectionHealth,+} from "@/hooks/useProviders";+import { useEventStore } from "@/store/events";+import { agentBrand, agentsBrand } from "@/lib/agentBrand";+import { robustCopy } from "@/lib/clipboard";+import { cn } from "@/lib/utils";+import { useT } from "@/i18n";++/**+ * The provider-tier building blocks shared by every screen that lets a user+ * configure a provider: the API-Keys view (all tiers) and the voice section's+ * "API Keys" tab (the `stt` tier only).+ *+ * This module is a VERBATIM extraction out of `views/ApiKeysView.tsx` — the+ * pieces below were module-private there and are unchanged apart from being+ * exported. `ApiKeysView` imports them back, so its pinned test suites keep+ * describing the exact same rendered output.+ */++export type { ProviderTier } from "@/hooks/useProviders";++export type LucideIcon = typeof Brain;++export interface CategoryMeta {+ /** Short label for the segmented tab. */+ tab: string;+ /** Full heading shown in the category hero band. */+ title: string;+ /** One-line plain-language description under the heading. */+ description: string;+ icon: LucideIcon;+}++// The top-level engine mode. Feature A supersedes design D1 ("view-only"):+// the switch now decides which tab set is shown AND persists `[voice].mode`+// via `useVoiceMode().setMode` — Pipeline always (it's always reachable),+// Realtime only when a realtime provider actually has a key+// (`realtimeAvailable`), so the switch can never pin the boot default to an+// unreachable engine. See `EngineModeSwitch` below for the exact rule.+export type VoiceEngineMode = "pipeline" | "realtime";++// The three provider slots the maintainer's setup recommendation speaks about+// (RecommendedSetupPanel). All three are ordinary CategoryKeys; "realtime"+// additionally requires the Realtime tab set, so opening it switches the VIEW+// mode (never the persisted `[voice].mode`).+export type RecommendationTab = "realtime" | "computer-use" | "subagents";++// Meta for the three provider tiers (brain/tts/stt). Subagents and Advanced are+// composed separately because they own their own data sources / sub-sections.+export function makeProviderCategories(+ t: (k: string) => string,+): Record<ProviderTier, CategoryMeta> {+ return {+ brain: {+ tab: t("apikeys_view.tab_brain"),+ title: t("apikeys_view.tier_brain"),+ description: t("apikeys_view.cat_brain_desc"),+ icon: Brain,+ },+ tts: {+ tab: t("apikeys_view.tab_tts"),+ title: t("apikeys_view.tier_tts"),+ description: t("apikeys_view.cat_tts_desc"),+ icon: Volume2,+ },+ stt: {+ tab: t("apikeys_view.tab_stt"),+ title: t("apikeys_view.tier_stt"),+ description: t("apikeys_view.cat_stt_desc"),+ icon: Mic,+ },+ realtime: {+ tab: t("apikeys_view.tab_realtime"),+ title: t("apikeys_view.tier_realtime"),+ description: t("apikeys_view.cat_realtime_desc"),+ icon: Radio,+ },+ "computer-use": {+ tab: t("apikeys_view.tab_computer_use"),+ title: t("apikeys_view.tier_computer_use"),+ description: t("apikeys_view.cat_computer_use_desc"),+ icon: Terminal,+ },+ };+}++/**+ * Per-tab health (amber = the active provider isn't set up, red = it's set up+ * but failing a live check), re-bound to the provider that is ACTUALLY active+ * right now. Best-effort and off the render-blocking path.+ *+ * The re-bind is load-bearing, not cosmetic: the backend rollup carries the+ * `subject_id` it tested, and a stale entry (e.g. a NVIDIA timeout recorded+ * before the user switched to OpenRouter) must be DROPPED rather than+ * attributed to whoever is active now. Handing raw rollup entries to the tabs+ * re-opens exactly that bug.+ */+export function useTierHealth(+ providers: ProviderDescriptor[],+): Record<string, SectionHealth> {+ const { health: rawHealth } = useSectionHealth();+ return useMemo(() => {+ const visible = { ...rawHealth };+ const activeSubjects: Record<string, string | undefined> = {+ brain: providers.find((provider) => provider.tier === "brain" && provider.active)?.id,+ tts: providers.find((provider) => provider.tier === "tts" && provider.active)?.id,+ stt: providers.find((provider) => provider.tier === "stt" && provider.active)?.id,+ realtime: providers.find(+ (provider) => provider.tier === "realtime" && provider.active,+ )?.id,+ "computer-use": providers.find(+ (provider) => provider.tier === "brain" && provider.computer_use_active,+ )?.id,+ };+ for (const [section, subjectId] of Object.entries(activeSubjects)) {+ const matching = sectionHealthForSubject(rawHealth[section], subjectId);+ if (matching) visible[section] = matching;+ else delete visible[section];+ }+ return visible;+ }, [providers, rawHealth]);+}++/**+ * The Pipeline|Realtime segmented switch. Feature A (supersedes D1): clicking+ * a segment still switches the local view (`onSelect`), and ALSO persists+ * `[voice].mode` — Pipeline unconditionally (always reachable), Realtime only+ * when `realtimeAvailable` (a key is present for some realtime family);+ * otherwise the click just switches the view so the user can add a key from+ * the Realtime tab without silently pinning the boot default to a dead+ * engine.+ *+ * Visual system (one system, two legible states):+ * - A sliding gold thumb sits under the segment matching the LIVE+ * `[voice].mode` — unmistakably "this engine is on". `useVoiceMode` updates+ * its cache optimistically, so the thumb follows the click INSTANTLY and+ * only rolls back if the persist fails.+ * - The segment currently being VIEWED but not live gets a subtle outline+ * only (no fill) — it's a transient look, not "on".+ * - Realtime with no key configured anywhere (`!realtimeAvailable`) reads+ * muted; it stays clickable (opens the Realtime tab so the user can add one)+ * but never gets the fill.+ * - The explanatory copy lives in `VoiceEngineContext` inside the provider+ * scroller, keeping this always-visible header control one compact row.+ */+export function EngineModeSwitch({+ mode,+ liveMode,+ realtimeAvailable,+ onSelect,+ onSetVoiceMode,+}: {+ mode: VoiceEngineMode;+ /** The live `[voice].mode` value — determines the filled/active segment. */+ liveMode: string;+ /** Whether SOME realtime family (OpenAI/Gemini) has a key configured. */+ realtimeAvailable: boolean;+ onSelect: (mode: VoiceEngineMode) => void;+ /** Persists `[voice].mode` — gated per the rule above. */+ onSetVoiceMode: (mode: string) => void;+}) {+ const t = useT();+ // Realtime leads as the recommended default. Pipeline follows with an+ // explicit Not recommended badge so the product guidance is unambiguous.+ const segments: { key: VoiceEngineMode; label: string; icon: LucideIcon }[] = [+ { key: "realtime", label: t("apikeys_view.mode_realtime"), icon: Radio },+ { key: "pipeline", label: t("apikeys_view.mode_pipeline"), icon: Waypoints },+ ];+ const liveIndex = liveMode === "realtime" ? 0 : 1;+ const liveModeAvailable = liveMode !== "realtime" || realtimeAvailable;++ function handleSelect(seg: VoiceEngineMode) {+ onSelect(seg);+ if (seg === "pipeline" || realtimeAvailable) {+ onSetVoiceMode(seg);+ }+ }++ return (+ <div+ data-testid="voice-engine-header-control"+ role="group"+ aria-label={t("apikeys_view.voice_engine_label")}+ className="shrink-0"+ >+ <div className="relative grid min-w-56 grid-cols-2 rounded-lg border border-border bg-card/40 p-0.5">+ {liveModeAvailable && (+ <span+ data-testid="voice-engine-live-thumb"+ aria-hidden="true"+ className="absolute inset-y-0.5 left-0.5 w-[calc(50%-0.125rem)] rounded-md bg-primary shadow-[0_0_14px_rgba(255,214,10,0.22)] transition-transform duration-200 ease-out"+ style={{ transform: `translateX(${liveIndex * 100}%)` }}+ />+ )}+ {segments.map((seg) => {+ const isLive = liveModeAvailable && liveMode === seg.key;+ const isViewedOnly = mode === seg.key && !isLive;+ const needsKey = seg.key === "realtime" && !realtimeAvailable;+ const isRecommended = seg.key === "realtime";+ const Icon = seg.icon;+ return (+ <button+ key={seg.key}+ type="button"+ onClick={() => handleSelect(seg.key)}+ aria-pressed={mode === seg.key}+ className={cn(+ "relative z-10 inline-flex items-center justify-center gap-1 rounded-md px-2 py-1 text-xs font-medium transition-colors",+ "focus-visible:outline-none focus-visible:ring-2 focus-visible:ring-ring",+ isLive+ ? "text-primary-foreground"+ : isViewedOnly+ ? "text-foreground ring-1 ring-border"+ : needsKey+ ? "text-muted-foreground/60 hover:text-muted-foreground"+ : "text-muted-foreground hover:text-foreground",+ )}+ >+ <Icon aria-hidden="true" className="h-3 w-3" />+ <span className="whitespace-nowrap">{seg.label}</span>+ <span+ className={cn(+ "whitespace-nowrap rounded-full px-1 py-px text-[8px] font-semibold uppercase tracking-wide",+ isRecommended+ ? isLive+ ? "bg-primary-foreground/20 text-primary-foreground"+ : "bg-primary/15 text-primary"+ : isLive+ ? "border border-primary-foreground/30 bg-primary-foreground/10 text-primary-foreground"+ : "border border-amber-500/30 bg-amber-500/10 text-amber-600 dark:text-amber-400",+ )}+ >+ {t(+ isRecommended+ ? "apikeys_view.mode_recommended"+ : "apikeys_view.not_recommended",+ )}+ </span>+ {isLive && (+ <span className="sr-only">{t("apikeys_view.mode_active_badge")}</span>+ )}+ </button>+ );+ })}+ </div>+ {/* One discreet reminder right where the choice is made: you configure+ exactly one engine, never both. The per-mode key details live in the+ VoiceEngineContext copy below, so this stays a single short line. */}+ <p+ data-testid="voice-engine-pick-one-hint"+ className="mt-1 text-right text-[10px] leading-tight text-muted-foreground/70"+ >+ {t("apikeys_view.mode_pick_one_hint")}+ </p>+ </div>+ );+}++/**+ * Compact, scrollable context for the header-level engine control. Keeping+ * explanatory copy and recommendations inside the provider scroller gives the+ * fixed viewport back to provider cards on laptop-height windows, while the+ * switch itself remains immediately reachable in the main header.+ */+export function VoiceEngineContext({+ mode,+ realtimeAvailable,+ statusKnown,+ sessionActive,+ activeSessionMode,+ activeSessionProvider,+ activeSessionModel,+ transitioning,+ liveMode,+ onOpenRecommendedTab,+}: {+ mode: VoiceEngineMode;+ realtimeAvailable: boolean;+ statusKnown: boolean;+ sessionActive: boolean;+ activeSessionMode: "pipeline" | "realtime" | null;+ activeSessionProvider: string;+ activeSessionModel: string;+ transitioning: boolean;+ liveMode: string;+ onOpenRecommendedTab: (tab: RecommendationTab) => void;+}) {+ const t = useT();+ const runtimeDetail = [activeSessionProvider, activeSessionModel]+ .filter(Boolean)+ .join(" · ");+ const runtimeText = transitioning+ ? t("apikeys_view.runtime_switching")+ : sessionActive && activeSessionMode === "realtime"+ ? `${t("apikeys_view.runtime_realtime")}${runtimeDetail ? ` · ${runtimeDetail}` : ""}`+ : sessionActive && activeSessionMode === "pipeline" && liveMode === "realtime"+ ? t("apikeys_view.runtime_fallback_pipeline")+ : sessionActive && activeSessionMode === "pipeline"+ ? t("apikeys_view.runtime_pipeline")+ : t("apikeys_view.runtime_idle");+ const runtimeMatchesSelection =+ !sessionActive || activeSessionMode === null || activeSessionMode === liveMode;+ const modeDescription =+ mode === "realtime" && !realtimeAvailable+ ? t(+ statusKnown+ ? "apikeys_view.mode_needs_key"+ : "apikeys_view.mode_status_unknown",+ )+ : mode === "realtime"+ ? t("apikeys_view.mode_desc_realtime")+ : t("apikeys_view.mode_desc_pipeline");++ return (+ <section+ data-testid="voice-engine-context"+ className="mx-auto mb-4 w-full max-w-4xl rounded-xl border border-border bg-card/25 px-3 py-2"+ aria-label={t("apikeys_view.voice_engine_label")}+ >+ <div className="flex min-w-0 flex-wrap items-center gap-x-4 gap-y-1.5">+ <div+ className="flex min-w-64 flex-1 items-center gap-2 overflow-hidden text-xs"+ title={`${t("apikeys_view.voice_engine_desc")} ${modeDescription}`}+ >+ <Volume2 aria-hidden="true" className="h-3.5 w-3.5 shrink-0 text-primary" />+ <span className="shrink-0 font-medium text-foreground">+ {t("apikeys_view.voice_engine_label")}+ </span>+ <span aria-hidden="true" className="text-border">·</span>+ <span className="min-w-0 truncate text-muted-foreground">+ {modeDescription}+ {mode === "realtime" && (+ <span className="text-amber-500/90">+ {` · ${t("apikeys_view.mode_realtime_preview")}`}+ </span>+ )}+ </span>+ </div>+ <div+ className="flex shrink-0 items-center gap-1.5 text-[11px] leading-snug"+ aria-live="polite"+ data-testid="voice-engine-runtime-status"+ >+ <span+ aria-hidden="true"+ className={cn(+ "h-1.5 w-1.5 shrink-0 rounded-full",+ transitioning+ ? "animate-pulse bg-amber-400 motion-reduce:animate-none"+ : runtimeMatchesSelection+ ? "bg-emerald-400"+ : "bg-amber-400",+ )}+ />+ <span+ className={cn(+ runtimeMatchesSelection && !transitioning+ ? "text-muted-foreground"+ : "text-amber-300",+ )}+ >+ {runtimeText}+ </span>+ </div>+ </div>++ <p+ data-testid="voice-engine-keys-hint"+ className="mt-1 text-[11px] leading-snug text-muted-foreground/80"+ >+ {t("apikeys_view.mode_keys_hint")}+ </p>++ {mode === "realtime" && (+ <RecommendedSetupPanel onOpenTab={onOpenRecommendedTab} />+ )}+ </section>+ );+}++/**+ * The maintainer's personal pick for the three provider slots of the REALTIME+ * tab set, shown in the scrollable engine context only while that tab set is+ * being viewed — the picks name Realtime-mode tabs, so surfacing them next to+ * the Pipeline tabs would point at tabs that are not even on screen+ * (maintainer feedback 2026-07-17). Same contract as the per-card+ * "Recommended" badges fed by provider_spec.py: a presentation hint only — it+ * never gates behavior and never branches a code path on a provider name+ * (AP-21). Each row is a button that jumps straight to the tab it names, so+ * the guidance sits one click from the place it applies. The rows carry an+ * explicit aria-label starting with the panel title so their accessible names+ * never collide with the Pipeline|Realtime segment buttons (tests match those+ * via /^realtime/i).+ */+function RecommendedSetupPanel({+ onOpenTab,+}: {+ onOpenTab: (tab: RecommendationTab) => void;+}) {+ const t = useT();+ const rows: {+ tab: RecommendationTab;+ icon: LucideIcon;+ label: string;+ pick: string;+ why: string;+ }[] = [+ {+ tab: "realtime",+ icon: Radio,+ label: t("apikeys_view.tab_realtime"),+ pick: t("apikeys_view.reco_realtime_pick"),+ why: t("apikeys_view.reco_realtime_why"),+ },+ {+ tab: "computer-use",+ icon: Terminal,+ label: t("apikeys_view.tab_computer_use"),+ pick: t("apikeys_view.reco_computer_use_pick"),+ why: t("apikeys_view.reco_computer_use_why"),+ },+ {+ tab: "subagents",+ icon: Bot,+ label: t("apikeys_view.tab_subagents"),+ pick: t("apikeys_view.reco_subagents_pick"),+ why: t("apikeys_view.reco_subagents_why"),+ },+ ];+ return (+ <div+ data-testid="recommended-setup-panel"+ className="mt-2 flex min-w-0 items-center gap-2 border-t border-primary/20 pt-2"+ >+ <p className="flex shrink-0 items-center gap-1.5 text-[11px] font-medium text-foreground">+ <Sparkles aria-hidden="true" className="h-3.5 w-3.5 shrink-0 text-primary" />+ {t("apikeys_view.reco_title")}+ </p>+ <ul className="flex min-w-0 flex-1 items-center gap-1 overflow-x-auto scrollbar-jarvis">+ {rows.map((row) => {+ const Icon = row.icon;+ return (+ <li key={row.tab} className="shrink-0">+ <button+ type="button"+ onClick={() => onOpenTab(row.tab)}+ data-testid={`reco-row-${row.tab}`}+ aria-label={`${t("apikeys_view.reco_title")}: ${row.label} — ${row.pick}. ${row.why}`}+ title={row.why}+ className="inline-flex items-center gap-1.5 whitespace-nowrap rounded-md border border-primary/15 bg-primary/[0.04] px-2 py-1 text-[11px] leading-none transition-colors hover:bg-primary/10 focus-visible:outline-none focus-visible:ring-2 focus-visible:ring-ring"+ >+ <Icon+ aria-hidden="true"+ className="h-3 w-3 shrink-0 text-primary/80"+ />+ <span className="text-muted-foreground">{row.label}:</span>+ <span className="font-medium text-foreground">{row.pick}</span>+ </button>+ </li>+ );+ })}+ </ul>+ </div>+ );+}++/**+ * The header band atop each category panel: an icon chip, the full category+ * title (display font), and a one-line plain-language description. Mirrors the+ * app's `ViewHeader` icon treatment so the screen reads as one system.+ */+export function CategoryHero({+ icon: Icon,+ title,+ description,+}: {+ icon: LucideIcon;+ title: string;+ description: string;+}) {+ return (+ <div className="mb-4 flex items-start gap-2.5">+ <div className="flex h-8 w-8 shrink-0 items-center justify-center rounded-lg border border-border bg-secondary/40 text-primary">+ <Icon className="h-4 w-4" />+ </div>+ <div className="min-w-0">+ <h3 className="font-display text-base font-semibold tracking-tight">+ {title}+ </h3>+ <p className="mt-0.5 text-xs text-muted-foreground">{description}</p>+ </div>+ </div>+ );+}++/**+ * A soft, gold-tinted "which one should I pick?" band — the one place a+ * category speaks up with an opinion. Used by the Realtime and Computer-Use+ * tabs, where the model choice genuinely confuses people; the calmer tiers+ * carry their guidance on the cards themselves (Recommended badges).+ */+export function GuidancePanel({ title, body }: { title: string; body: string }) {+ return (+ <div className="mb-3 flex items-start gap-2.5 rounded-xl border border-primary/25 bg-primary/[0.05] px-3 py-2">+ <Sparkles aria-hidden="true" className="mt-0.5 h-4 w-4 shrink-0 text-primary" />+ <p className="min-w-0 text-xs leading-relaxed">+ <span className="font-medium text-foreground">{title}</span>+ <span className="text-muted-foreground"> · {body}</span>+ </p>+ </div>+ );+}++/**+ * One of the three provider tiers (brain/tts/stt): the hero band plus the+ * loading / error / empty / card states. The card list itself is `TierSection`,+ * reused unchanged from the original layout.+ */+export function ProviderCategory({+ meta,+ tier,+ providers,+ loading,+ error,+ onChanged,+ onActivateOptimistic,+ health,+ intro,+}: {+ meta: CategoryMeta;+ tier: ProviderTier;+ providers: ProviderDescriptor[];+ loading: boolean;+ error: string | null;+ onChanged: () => void;+ onActivateOptimistic: (tier: ProviderTier, id: string) => void;+ /** Live health of this tier's ACTIVE provider — drills the tab's red dot down+ * onto the exact card that is failing so the user sees WHICH provider broke. */+ health?: SectionHealth;+ /** Optional guidance band rendered between the hero and the card list. */+ intro?: React.ReactNode;+}) {+ const t = useT();+ const tierProviders = providers.filter(+ (p) => p.tier === tier && p.brain_switchable !== false,+ );++ return (+ <div role="tabpanel">+ <CategoryHero icon={meta.icon} title={meta.title} description={meta.description} />++ {intro}++ {loading && (+ <div className="flex items-center gap-2 text-sm text-muted-foreground">+ <Loader2 className="h-4 w-4 animate-spin" /> {t("apikeys_view.loading_providers")}+ </div>+ )}++ {error && (+ <div className="flex items-start gap-2 rounded-md border border-destructive/30 bg-destructive/5 p-4 text-sm text-destructive">+ <AlertCircle className="mt-0.5 h-4 w-4" />+ <div>+ {t("apikeys_view.load_error")} ({error}).+ <button onClick={() => onChanged()} className="ml-2 underline">+ {t("apikeys_view.retry")}+ </button>+ </div>+ </div>+ )}++ {!loading && !error && tierProviders.length === 0 && (+ <p className="text-sm text-muted-foreground">+ {t("apikeys_view.no_providers_in_tier")}+ </p>+ )}++ {!loading && !error && tierProviders.length > 0 && (+ <TierSection+ providers={tierProviders}+ onChanged={onChanged}+ onActivateOptimistic={onActivateOptimistic}+ health={health}+ />+ )}+ </div>+ );+}++// The card list for a single provider tier. The category label now lives in the+// tab bar + the `CategoryHero` above, so this renders only the cards. If nobody+// in the tier is active yet, a freshly saved key auto-activates itself — the+// first configured provider wins automatically (`autoActivateOnSave`).+export function TierSection({+ providers,+ onChanged,+ onActivateOptimistic,+ health,+}: {+ providers: ProviderDescriptor[];+ onChanged: () => void;+ onActivateOptimistic: (tier: ProviderTier, id: string) => void;+ /** Tier health — handed only to the ACTIVE card, since section-health tests+ * exactly the one provider powering this tier. */+ health?: SectionHealth;+}) {+ const tierHasActive = providers.some((p) => p.active);+ // Configured (or active) providers first — the wall of empty key forms used+ // to bury the one or two cards the user actually set up. `active` counts so+ // an active-but-keyless anomaly (e.g. a free-tier provider) can never hide+ // below untouched cards; among configured cards nothing reorders on a switch+ // (both stay rank 0), so a card never jumps under the pointer mid-click.+ // Stable within each group (Array.sort is stable).+ const sorted = [...providers].sort(+ (a, b) =>+ Number(b.configured || b.active) - Number(a.configured || a.active),+ );+ return (+ <ul className="space-y-3">+ {sorted.map((p) => (+ <li key={p.id}>+ <ProviderCard+ descriptor={p}+ onChanged={onChanged}+ onActivateOptimistic={onActivateOptimistic}+ autoActivateOnSave={!tierHasActive}+ health={p.active ? sectionHealthForSubject(health, p.id) : undefined}+ />+ </li>+ ))}+ </ul>+ );+}++export function ProviderCard({+ descriptor,+ onChanged,+ onActivateOptimistic,+ autoActivateOnSave,+ health,+}: {+ descriptor: ProviderDescriptor;+ onChanged: () => void;+ onActivateOptimistic: (tier: ProviderTier, id: string) => void;+ autoActivateOnSave: boolean;+ /** Live section-health for THIS card (set only on the active provider). A+ * status of "error" turns the card red and surfaces the cause inline — the+ * tab dot says "something here is broken", this says exactly WHAT/WHERE. */+ health?: SectionHealth;+}) {+ const t = useT();+ const [activating, setActivating] = useState(false);+ const pushToast = useEventStore((s) => s.pushToast);+ const assistantName = useEventStore((s) => s.assistantName);+ // The card only escalates to red for a real "set up but failing" error — the+ // amber "needs setup" case stays on the tab + the open/ready badge so a fresh,+ // half-configured screen doesn't paint cards red.+ const cardError = descriptor.active && health?.status === "error";+ // The backend one-liner (e.g. "OpenRouter: rate limited") already names the+ // provider + cause, so it answers "what is wrong" without a second lookup.+ const cardErrorDetail = health?.detail?.trim() || "";++ // Codex is filtered out of the Brain tier (`brain_switchable=false`) and is+ // selected from the Subagent section. This branch stays for older payloads or+ // tests that still mount a Codex descriptor directly.+ const isCodex = descriptor.auth_mode === "codex";+ const isBrainSwitchable =+ descriptor.tier !== "brain" || descriptor.brain_switchable !== false;++ async function activate(assumeConfigured = false) {+ if (descriptor.active) return;+ if (!isBrainSwitchable) {+ pushToast(+ "warning",+ `${descriptor.label} is only available for ${agentsBrand(assistantName)}.`,+ );+ return;+ }+ if (isCodex && !descriptor.codex_brain_ready) {+ // The card is "connected" via OAuth, but a chat brain needs an OpenAI key.+ // Guide honestly instead of switching and failing on the first turn.+ pushToast("warning", t("apikeys_codex.brain_needs_openai_key"));+ return;+ }+ if (!assumeConfigured && !descriptor.configured) {+ pushToast(+ "warning",+ descriptor.auth_mode === "codex"+ ? t("apikeys_codex.needs_codex_full").replace("{0}", descriptor.label)+ : descriptor.auth_mode === "antigravity"+ ? t("apikeys_antigravity.needs_login_full").replace("{0}", descriptor.label)+ : t("apikeys_codex.needs_key_full").replace("{0}", descriptor.label),+ );+ return;+ }+ // Flip the highlight immediately so the switch feels instant — the backend+ // call below can take a few seconds (a TTS switch rebuilds the provider and+ // injects it into the live pipeline). The refetch on success / failure then+ // reconciles with server truth.+ onActivateOptimistic(descriptor.tier, descriptor.id);+ setActivating(true);+ try {+ if (descriptor.tier === "brain") {+ await switchBrainProvider(descriptor.id);+ pushToast("success", `Brain → ${descriptor.label}`);+ window.dispatchEvent(new CustomEvent("jarvis:brain-switched"));+ } else if (descriptor.tier === "tts") {+ const result = await switchTtsProvider(descriptor.id);+ const note = result.restart_required+ ? " (active from next voice start)"+ : "";+ pushToast("success", `Voice output → ${descriptor.label}${note}`);+ window.dispatchEvent(new CustomEvent("jarvis:tts-switched"));+ } else if (descriptor.tier === "stt") {+ const result = await switchSttProvider(descriptor.id);+ const note = result.restart_required+ ? " (active from next voice start)"+ : "";+ pushToast("success", `Voice input → ${descriptor.label}${note}`);+ window.dispatchEvent(new CustomEvent("jarvis:stt-switched"));+ } else if (descriptor.tier === "computer-use") {+ await switchComputerUseProvider(descriptor.id);+ pushToast("success", `Computer-Use → ${descriptor.label}`);+ window.dispatchEvent(new CustomEvent("jarvis:computer-use-switched"));+ } else {+ const result = await switchRealtimeProvider(descriptor.id);+ const note = result.restart_required+ ? " (active from next voice start)"+ : "";+ pushToast("success", `Realtime → ${descriptor.label}${note}`);+ window.dispatchEvent(new CustomEvent("jarvis:realtime-switched"));+ }+ onChanged();+ } catch (e) {+ pushToast("error", (e as Error).message);+ // Roll the optimistic highlight back to the true active provider.+ onChanged();+ window.dispatchEvent(+ new CustomEvent("jarvis:provider-switch-failed", {+ detail: { section: descriptor.tier, provider: descriptor.id },+ }),+ );+ } finally {+ setActivating(false);+ }+ }++ // A single click AND a double click on the card both activate the provider.+ // We explicitly filter clicks on interactive sub-elements (inputs, buttons,+ // links) so that a click into the password field or on the+ // "Replace"/trash icon does NOT accidentally trigger a switch. The radio+ // also has its own stopPropagation for historical reasons+ // (belt and suspenders).+ function handleCardActivate(e: React.MouseEvent<HTMLDivElement>) {+ // Codex is connection-only — a card click must never trigger a brain switch.+ if (isCodex) return;+ if (!isBrainSwitchable) return;+ const target = e.target as HTMLElement | null;+ if (+ target &&+ (target.closest("input") ||+ target.closest("button") ||+ target.closest("a") ||+ target.closest("label"))+ ) {+ return;+ }+ void activate();+ }++ // Called by ApiKeyForm as soon as a key has been saved for a previously+ // unconfigured provider. If no one else is active in this tier, the+ // freshly configured provider takes over automatically — otherwise the+ // user has to click the now-visible "Activate" button.+ async function handleSavedActivate() {+ if (!autoActivateOnSave) return;+ if (descriptor.active) return;+ await activate(true);+ }++ return (+ <div+ onClick={handleCardActivate}+ onDoubleClick={handleCardActivate}+ title={+ descriptor.active+ ? t("apikeys_view.active_tooltip")+ : !isBrainSwitchable+ ? `Available for ${agentsBrand(assistantName)} only`+ : descriptor.configured+ ? t("apikeys_view.click_to_activate")+ : descriptor.auth_mode === "codex"+ ? t("apikeys_view.needs_codex")+ : descriptor.auth_mode === "antigravity"+ ? t("apikeys_view.needs_login")+ : t("apikeys_view.needs_key")+ }+ className={cn(+ "card-outline space-y-3 p-4 transition-colors",+ // A broken active provider wins the card's frame — red outline + faint+ // red wash — so the eye lands on the exact card behind the tab's red dot.+ cardError+ ? "border-destructive/70 bg-destructive/[0.05] ring-1 ring-destructive/30"+ : descriptor.active+ ? "border-primary bg-primary/[0.06] ring-1 ring-primary/30"+ : descriptor.configured+ ? isBrainSwitchable+ ? "cursor-pointer hover:border-primary/40 hover:bg-primary/[0.02]"+ : ""+ : "opacity-95",+ )}+ >+ <div className="flex items-start justify-between gap-3">+ <div className="min-w-0 flex-1">+ <div className="flex flex-wrap items-center gap-2">+ <span className="font-display text-sm font-semibold tracking-tight">+ {descriptor.label}+ </span>+ <StatusBadge descriptor={descriptor} />+ {descriptor.recommended && (+ <span+ className="inline-flex items-center gap-1 rounded-full border border-primary/40 bg-primary/10 px-2 py-0.5 text-[10px] font-medium text-primary"+ title={+ descriptor.recommended_model+ ? t("apikeys_view.recommended_tooltip").replace(+ "{0}",+ descriptor.recommended_model,+ )+ : undefined+ }+ >+ <Sparkles aria-hidden="true" className="h-2.5 w-2.5" />+ {t("apikeys_view.recommended")}+ </span>+ )}+ {descriptor.caution && (+ <span+ className="rounded-full border border-amber-500/40 bg-amber-500/10 px-2 py-0.5 text-[10px] font-medium text-amber-600 dark:text-amber-400"+ title={descriptor.caution}+ >+ {t("apikeys_view.not_recommended")}+ </span>+ )}+ </div>+ <p className="mt-0.5 text-[11px] text-muted-foreground">+ <code className="font-mono">{descriptor.id}</code>+ {" · "}+ <span>+ {descriptor.auth_mode === "api_key" && "API key auth"}+ {descriptor.auth_mode === "codex" && "ChatGPT / Codex login"}+ {descriptor.auth_mode === "antigravity" && "Google subscription login"}+ {descriptor.auth_mode === "none" && "Local — no auth"}+ </span>+ </p>+ </div>++ <ActiveControl+ descriptor={+ isCodex+ ? { ...descriptor, configured: Boolean(descriptor.codex_brain_ready) }+ : descriptor+ }+ activating={activating}+ onActivate={activate}+ disabled={!isBrainSwitchable || (isCodex && !descriptor.codex_brain_ready)}+ disabledReason={+ !isBrainSwitchable+ ? `Available for ${agentsBrand(assistantName)} only`+ : isCodex && !descriptor.codex_brain_ready+ ? t("apikeys_codex.brain_needs_openai_key")+ : undefined+ }+ />+ </div>++ {/* The precise "this card is the problem" banner: only on the active card,+ only when the live check actually failed. Names the cause in plain+ words instead of leaving the user to guess behind the tab's red dot. */}+ {cardError && (+ <div+ data-testid={`provider-health-error-${descriptor.id}`}+ role="status"+ className="flex items-start gap-2 rounded-md border border-destructive/40 bg-destructive/[0.07] px-3 py-2 text-[11px] leading-relaxed text-destructive"+ >+ <XCircle className="mt-0.5 h-3.5 w-3.5 shrink-0" />+ <span className="min-w-0 break-words">+ <span className="font-medium">{t("apikeys_view.health_error")}</span>+ {cardErrorDetail ? ` — ${cardErrorDetail}` : ""}+ </span>+ </div>+ )}++ <AuthWidget+ descriptor={descriptor}+ onChanged={onChanged}+ onSavedActivate={handleSavedActivate}+ />++ {!isBrainSwitchable && (+ <p className="rounded-md border border-amber-500/25 bg-amber-500/10 px-3 py-2 text-[11px] leading-relaxed text-amber-700">+ {agentBrand(assistantName)} only. This provider cannot be used as the main Brain or+ Computer-Use planner because it does not receive screenshots.+ </p>+ )}++ {/* Model / voice picker. Every switchable brain provider shows its model+ picker — even before a key is set — because the catalog falls back to+ the provider's curated family without a key (no network, no error), so+ a model can be pre-picked. TTS/STT share a single global [tts]/[stt]+ block, so the picker only WRITES from the ACTIVE provider and sets the+ voice (Grok/Gemini/OpenAI/Google) or model (Cartesia/STT). */}+ {((descriptor.tier === "brain" && isBrainSwitchable) ||+ ((descriptor.tier === "tts" || descriptor.tier === "stt") &&+ descriptor.active &&+ descriptor.configured)) &&+ // OpenRouter TTS is the one provider where the user also picks a VOICE+ // (per model, language-tagged, with an audio preview) — render the+ // combined model + voice controls; every other tier keeps the plain+ // model/voice picker.+ (descriptor.id === "openrouter-tts" ? (+ <OpenRouterTtsControls+ providerId={descriptor.id}+ recommendedModel={descriptor.recommended_model}+ healthActive={descriptor.active}+ />+ ) : (+ <BrainModelSelector+ providerId={descriptor.id}+ recommendedModel={descriptor.recommended_model}+ healthSection={descriptor.tier}+ healthActive={descriptor.active}+ />+ ))}++ {/* TTS/STT model/voice is a single global value, so a configured-but-+ inactive provider can't own it — make the capability discoverable with+ a hint instead of silently hiding the picker. */}+ {(descriptor.tier === "tts" || descriptor.tier === "stt") &&+ descriptor.configured &&+ !descriptor.active && (+ <p className="text-[11px] text-muted-foreground">+ {t("apikeys_view.model_picker_activate_hint")}+ </p>+ )}++ {/* Phase 3: a dedicated Computer-Use model, selectable per brain provider+ (defaults to the provider's main model — no automatic escalation).+ Also shown under the Computer-Use tab (synthetic "computer-use"+ tier, same underlying brain id) — but never the plain+ BrainModelSelector above, which stays Brain-tab-only. */}+ {(descriptor.tier === "brain" || descriptor.tier === "computer-use") &&+ descriptor.configured &&+ isBrainSwitchable && (+ <CuModelSelector+ providerId={descriptor.id}+ recommendedModel={descriptor.recommended_model}+ healthActive={+ descriptor.tier === "computer-use"+ ? descriptor.active+ : Boolean(descriptor.computer_use_active)+ }+ />+ )}++ {/* Realtime needs BOTH a model AND a voice pinned per provider — a+ dedicated compact control (two dropdowns), gated on the card+ already having a stored credential like the other tiers' pickers+ above. */}+ {descriptor.tier === "realtime" && descriptor.configured && (+ <RealtimeOptionsControl+ providerId={descriptor.id}+ healthActive={descriptor.active}+ />+ )}++ {/* Footer: the live connectivity test, visually separated from the+ configuration body so "set up" and "verify" read as two steps. */}+ <div className="border-t border-border/60 pt-2.5">+ <ProviderTestControl+ providerId={descriptor.id}+ providerLabel={descriptor.label}+ section={descriptor.tier}+ active={descriptor.active}+ />+ </div>+ </div>+ );+}++// Tone per status: green = works; amber = reached but key/account/model blocks+// (integration is fine); red = couldn't reach / integration bug.+const TEST_STATUS_TONE: Record<ProviderTestStatus, string> = {+ ok: "border-emerald-500/30 bg-emerald-500/10 text-emerald-600",+ not_configured: "border-border bg-muted text-muted-foreground",+ bad_key: "border-amber-500/30 bg-amber-500/10 text-amber-600",+ no_credits: "border-amber-500/30 bg-amber-500/10 text-amber-600",+ rate_limited: "border-amber-500/30 bg-amber-500/10 text-amber-600",+ model_unavailable: "border-amber-500/30 bg-amber-500/10 text-amber-600",+ unreachable: "border-destructive/30 bg-destructive/10 text-destructive",+ error: "border-destructive/30 bg-destructive/10 text-destructive",+};++/**+ * "Test" button + honest result chip. Calls POST /api/providers/{id}/test which+ * makes a REAL minimal call — distinguishing a working provider from an invalid+ * key, an out-of-credits account, or an unreachable endpoint. This is the piece+ * the API-Keys view was missing: the green "configured" badge only ever meant a+ * key STRING was stored, never that the provider answers.+ */+export function ProviderTestControl({+ providerId,+ providerLabel,+ section,+ active,+}: {+ providerId: string;+ providerLabel: string;+ section: ProviderTier;+ active: boolean;+}) {+ const t = useT();+ const [running, setRunning] = useState(false);+ const [result, setResult] = useState<ProviderTestResult | null>(null);+ const activeRef = useRef(active);+ activeRef.current = active;++ function publish(next: ProviderTestResult) {+ window.dispatchEvent(+ new CustomEvent("jarvis:provider-tested", {+ detail: {+ section,+ provider: providerId,+ provider_label: providerLabel,+ active: activeRef.current,+ result: next,+ },+ }),+ );+ }++ async function run() {+ setRunning(true);+ setResult(null);+ try {+ const next = await testProvider(providerId);+ setResult(next);+ publish(next);+ } catch (e) {+ const next: ProviderTestResult = {+ provider: providerId,+ status: "error",+ detail: (e as Error).message,+ latency_ms: 0,+ integration_ok: false,+ };+ setResult(next);+ publish(next);+ } finally {+ setRunning(false);+ }+ }++ const tone = result ? TEST_STATUS_TONE[result.status] : "";+ const note = result+ ? (result.integration_ok+ ? t("apikeys_test.integration_ok_note")+ : t("apikeys_test.integration_bad_note"))+ : "";++ return (+ <div className="flex flex-wrap items-center gap-2 pt-0.5">+ <Button+ size="sm"+ variant="outline"+ onClick={(e) => {+ e.stopPropagation();+ void run();+ }}+ disabled={running}+ className="h-7 gap-1.5 text-xs"+ >+ {running ? (+ <Loader2 className="h-3.5 w-3.5 animate-spin" />+ ) : (+ <PlugZap className="h-3.5 w-3.5" />+ )}+ {running ? t("apikeys_test.running") : t("apikeys_test.button")}+ </Button>++ {result && (+ <span+ data-testid={`provider-test-result-${providerId}`}+ className={cn(+ "inline-flex items-center gap-1 rounded-full border px-2 py-0.5 text-[11px]",+ tone,+ )}+ title={[note, result.detail, result.latency_ms ? `${Math.round(result.latency_ms)} ms` : ""]+ .filter(Boolean)+ .join("\n")}+ >+ {result.status === "ok" ? (+ <Check className="h-3 w-3" />+ ) : result.integration_ok ? (+ <AlertCircle className="h-3 w-3" />+ ) : (+ <XCircle className="h-3 w-3" />+ )}+ {t(`apikeys_test.status_${result.status}`)}+ {result.status === "ok" && result.latency_ms+ ? ` · ${Math.round(result.latency_ms)} ms`+ : ""}+ </span>+ )}+ </div>+ );+}++/**+ * Radio-button-based active toggle. The source of truth stays+ * `descriptor.active` from `/api/providers` — the radio mirrors server+ * state, it is not held locally. `name="active-{tier}"` gives us browser-+ * native exclusivity per tier (Brain/TTS/STT).+ *+ * `disabled` would suppress onChange; that's why the radio is NOT disabled+ * when a key is missing — instead it routes through `activate()` to raise a+ * warning toast. This way the user gets a reaction to every click, instead+ * of bumping into a silent element.+ */+export function ActiveControl({+ descriptor,+ activating,+ onActivate,+ disabled = false,+ disabledReason,+}: {+ descriptor: ProviderDescriptor;+ activating: boolean;+ onActivate: () => void;+ /**+ * Truly disable the radio (no click, no toast). Used for Codex when it cannot+ * be a brain yet (no OpenAI key) — a click there would be a dead end, so we+ * disable instead of firing a warning toast. Other providers stay clickable+ * (warn-on-click) because their key field is right on the card.+ */+ disabled?: boolean;+ disabledReason?: string;+}) {+ const labelTitle = descriptor.active+ ? "This provider is active"+ : disabled+ ? disabledReason ?? "Provider cannot be activated"+ : descriptor.configured+ ? "Activate this provider"+ : "Set an API key first";++ return (+ <label+ onClick={(e) => e.stopPropagation()}+ onDoubleClick={(e) => {+ // A double click on the radio label must NOT also trigger the+ // card's onDoubleClick — otherwise activate() would fire twice+ // (idempotent, but sends two API calls).+ e.stopPropagation();+ }}+ className={cn(+ "inline-flex shrink-0 select-none items-center gap-1.5 text-xs",+ disabled ? "cursor-not-allowed" : "cursor-pointer",+ descriptor.active+ ? "font-medium text-primary"+ : descriptor.configured+ ? "text-muted-foreground hover:text-foreground"+ : "text-muted-foreground/70",+ )}+ title={labelTitle}+ >+ <input+ type="radio"+ name={`active-${descriptor.tier}`}+ checked={descriptor.active}+ onChange={() => onActivate()}+ disabled={activating || disabled}+ className="accent-primary"+ />+ {activating ? "Activating…" : descriptor.active ? "Active" : "Set active"}+ </label>+ );+}++export function BaseUrlField({+ descriptor,+ onChanged,+}: {+ descriptor: ProviderDescriptor;+ onChanged: () => void;+}) {+ const t = useT();+ const pushToast = useEventStore((s) => s.pushToast);+ const [value, setValue] = useState(descriptor.base_url ?? "");+ const [saving, setSaving] = useState(false);++ // Follow refetches (e.g. after another card action) without clobbering an+ // in-flight edit: only resync while the user is not mid-save.+ useEffect(() => {+ setValue(descriptor.base_url ?? "");+ // eslint-disable-next-line react-hooks/exhaustive-deps+ }, [descriptor.base_url]);++ const dirty = value.trim() !== (descriptor.base_url ?? "");++ async function save() {+ setSaving(true);+ try {+ const stored = await saveProviderBaseUrl(descriptor.id, value.trim() || null);+ setValue(stored ?? "");+ pushToast(+ "success",+ stored ? t("apikeys_base_url.saved") : t("apikeys_base_url.cleared"),+ );+ onChanged();+ } catch (e) {+ pushToast("error", e instanceof Error ? e.message : String(e));+ } finally {+ setSaving(false);+ }+ }++ return (+ <div className="space-y-1">+ <label className="text-[10px] uppercase tracking-wider text-muted-foreground">+ {t("apikeys_base_url.label")}+ </label>+ <div className="flex gap-2">+ <input+ type="url"+ value={value}+ onChange={(e) => setValue(e.target.value)}+ placeholder={+ descriptor.default_base_url ?? t("apikeys_base_url.placeholder_required")+ }+ className="h-8 w-full rounded-md border border-border bg-background px-2 text-xs"+ />+ <Button+ size="sm"+ variant="secondary"+ onClick={save}+ disabled={saving || !dirty}+ >+ {saving ? t("apikeys_base_url.saving") : t("apikeys_base_url.save")}+ </Button>+ </div>+ <p className="text-[11px] leading-relaxed text-muted-foreground">+ {descriptor.default_base_url+ ? t("apikeys_base_url.hint_default")+ : t("apikeys_base_url.hint_required")}+ </p>+ </div>+ );+}++export function AuthWidget({+ descriptor,+ onChanged,+ onSavedActivate,+}: {+ descriptor: ProviderDescriptor;+ onChanged: () => void;+ onSavedActivate?: () => void;+}) {+ return (+ <div className="space-y-2">+ <ProviderBillingBadge billing={descriptor.billing} />+ {descriptor.supports_base_url && (+ <BaseUrlField descriptor={descriptor} onChanged={onChanged} />+ )}+ {descriptor.auth_mode === "none" && (+ <>+ <p className="text-xs text-muted-foreground">+ {descriptor.secret_keys.length > 0+ ? "Local provider — runs without credentials. The key below is optional, only for servers that enforce one (e.g. vLLM --api-key)."+ : "Local provider — no credentials needed."}+ </p>+ {descriptor.secret_keys.map((k) => (+ <ApiKeyForm+ key={k}+ secretKey={k}+ dashboardUrl={descriptor.dashboard_url}+ configured={Boolean(descriptor.secrets_set[k])}+ effectiveConfigured={Boolean(descriptor.secrets_effective?.[k])}+ sharedWith={descriptor.secret_shared_with?.[k] ?? []}+ credentialHelp={descriptor.credential_help}+ onChanged={onChanged}+ onSavedActivate={onSavedActivate}+ />+ ))}+ </>+ )}+ {descriptor.auth_mode === "codex" && (+ <CodexAuthWidget descriptor={descriptor} onChanged={onChanged} />+ )}+ {descriptor.auth_mode === "antigravity" && (+ <AntigravityAuthWidget descriptor={descriptor} onChanged={onChanged} />+ )}+ {descriptor.auth_mode === "api_key" && (+ <>+ {descriptor.secret_keys.map((k) => (+ <ApiKeyForm+ key={k}+ secretKey={k}+ dashboardUrl={descriptor.dashboard_url}+ configured={Boolean(descriptor.secrets_set[k])}+ effectiveConfigured={Boolean(descriptor.secrets_effective?.[k])}+ sharedWith={descriptor.secret_shared_with?.[k] ?? []}+ credentialHelp={descriptor.credential_help}+ onChanged={onChanged}+ onSavedActivate={onSavedActivate}+ />+ ))}+ {descriptor.alt_credential && (+ <AltCredentialNote alt={descriptor.alt_credential} />+ )}+ </>+ )}+ </div>+ );+}++function CodexAuthWidget({+ descriptor,+ onChanged,+}: {+ descriptor: ProviderDescriptor;+ onChanged: () => void;+}) {+ const t = useT();+ const [pending, setPending] = useState<"login" | "logout" | "copy" | null>(null);+ const pushToast = useEventStore((s) => s.pushToast);+ const status = descriptor.codex_status;+ const installCommand = descriptor.install_hint ?? "npm i -g @openai/codex";++ async function handleCopy() {+ setPending("copy");+ try {+ const copied = await robustCopy(installCommand);+ pushToast(copied ? "success" : "warning", copied ? "Install command copied" : installCommand);+ } finally {+ setPending(null);+ }+ }++ async function handleLogin() {+ setPending("login");+ try {+ await startCodexLogin();+ pushToast("info", t("apikeys_codex.login_started"));+ // `codex login` opens the browser OAuth flow; it only completes once the+ // user clicks through (seconds later). Poll a few times so the card flips+ // to the compact "connected" state on its own once auth.json appears —+ // no manual refresh needed.+ [1500, 4000, 8000, 15000, 25000].forEach((ms) =>+ window.setTimeout(onChanged, ms),+ );+ } catch (e) {+ pushToast("error", (e as Error).message);+ } finally {+ setPending(null);+ }+ }++ async function handleLogout() {+ setPending("logout");+ try {+ await codexLogout();+ pushToast("info", t("apikeys_codex.disconnected"));+ onChanged();+ } catch (e) {+ pushToast("error", (e as Error).message);+ } finally {+ setPending(null);+ }+ }++ // Connected: collapse to a small "logged in" badge instead of the full card.+ // No connect button (no second invitation), no API-key field (the key lives on+ // the separate "OpenAI" provider). Activation as the worker happens in the+ // Subagent list below.+ if (status?.connected) {+ return (+ <div className="space-y-3">+ <div+ data-testid="codex-connected"+ className="flex flex-wrap items-center gap-2 rounded-md border border-emerald-500/30 bg-emerald-500/[0.06] px-3 py-2 text-xs"+ >+ <Check className="h-3.5 w-3.5 shrink-0 text-emerald-500" />+ <span className="min-w-0 break-words text-foreground">+ {status.message ?? "Connected via ChatGPT."}+ </span>+ {status.version && (+ <code className="rounded bg-muted px-1.5 py-0.5 font-mono">{status.version}</code>+ )}+ {status.mode === "chatgpt" && <span className="chip-yellow">CHATGPT-LOGIN</span>}+ <Button+ size="sm"+ variant="ghost"+ onClick={handleLogout}+ disabled={pending !== null}+ className="ml-auto"+ >+ <LogOut className="h-3.5 w-3.5" />+ Disconnect+ </Button>+ </div>+ </div>+ );+ }++ // Not connected: status + (install hint) + the single "connect" action.+ return (+ <div className="space-y-3">+ <div className="rounded-md border border-border bg-background/40 p-3 text-xs text-muted-foreground">+ <div className="flex flex-wrap items-center gap-2">+ <span>{status?.message ?? t("apikeys_codex.status_loading")}</span>+ {status?.version && (+ <code className="rounded bg-muted px-1.5 py-0.5 font-mono">{status.version}</code>+ )}+ </div>+ </div>++ {!status?.installed && (+ <div className="flex flex-wrap items-center gap-2">+ <code className="min-w-[220px] flex-1 rounded-md border border-border bg-muted/30 px-3 py-1.5 font-mono text-xs">+ {installCommand}+ </code>+ <Button size="sm" variant="outline" onClick={handleCopy} disabled={pending === "copy"}>+ {pending === "copy" ? <Check className="h-3.5 w-3.5" /> : <Copy className="h-3.5 w-3.5" />}+ Copy command+ </Button>+ </div>+ )}++ <div className="flex flex-wrap gap-2">+ <Button size="sm" onClick={handleLogin} disabled={pending !== null || !status?.installed}>+ <LogIn className="h-3.5 w-3.5" />+ Connect with ChatGPT+ </Button>+ <Button size="sm" variant="outline" asChild>+ <a href="https://help.openai.com/en/articles/11381614" target="_blank" rel="noreferrer">+ <Terminal className="h-3.5 w-3.5" />+ Install Codex+ </a>+ </Button>+ </div>++ </div>+ );+}++function AntigravityAuthWidget({+ descriptor,+ onChanged,+}: {+ descriptor: ProviderDescriptor;+ onChanged: () => void;+}) {+ const t = useT();+ const [pending, setPending] = useState<"login" | "logout" | "copy" | null>(null);+ const pushToast = useEventStore((s) => s.pushToast);+ const status = descriptor.antigravity_status;+ const installCommand =+ descriptor.install_hint ?? "curl -fsSL https://antigravity.google/cli/install.sh | bash";++ async function handleCopy() {+ setPending("copy");+ try {+ const copied = await robustCopy(installCommand);+ pushToast(copied ? "success" : "warning", copied ? "Install command copied" : installCommand);+ } finally {+ setPending(null);+ }+ }++ async function handleLogin() {+ setPending("login");+ try {+ await loginAntigravity();+ pushToast("info", t("apikeys_antigravity.login_started"));+ // The Google CLI opens the browser "Sign in with Google" flow; it only+ // completes once the user clicks through (seconds later). Poll a few times+ // so the card flips to the compact "connected" state on its own once the+ // on-disk creds appear — no manual refresh needed (mirror of Codex).+ [1500, 4000, 8000, 15000, 25000].forEach((ms) =>+ window.setTimeout(onChanged, ms),+ );+ } catch (e) {+ pushToast("error", (e as Error).message);+ } finally {+ setPending(null);+ }+ }++ async function handleLogout() {+ setPending("logout");+ try {+ await logoutAntigravity();+ pushToast("info", t("apikeys_antigravity.disconnected"));+ onChanged();+ } catch (e) {+ pushToast("error", (e as Error).message);+ } finally {+ setPending(null);+ }+ }++ // Connected: collapse to a small "logged in" badge instead of the full card.+ // The Google subscription bills the brain/subagent; no key field (OAuth-only).+ if (status?.connected) {+ return (+ <div className="space-y-3">+ <div+ data-testid="antigravity-connected"+ className="flex flex-wrap items-center gap-2 rounded-md border border-emerald-500/30 bg-emerald-500/[0.06] px-3 py-2 text-xs"+ >+ <Check className="h-3.5 w-3.5 shrink-0 text-emerald-500" />+ <span className="min-w-0 break-words text-foreground">+ {status.user_email+ ? t("apikeys_antigravity.connected_as").replace("{0}", status.user_email)+ : status.message || t("apikeys_antigravity.connected")}+ </span>+ {status.version && (+ <code className="rounded bg-muted px-1.5 py-0.5 font-mono">{status.version}</code>+ )}+ <span className="chip-yellow">GOOGLE-LOGIN</span>+ <Button+ size="sm"+ variant="ghost"+ onClick={handleLogout}+ disabled={pending !== null}+ className="ml-auto"+ >+ <LogOut className="h-3.5 w-3.5" />+ Disconnect+ </Button>+ </div>+ </div>+ );+ }++ // Not connected: status + (install hint) + the single "connect" action.+ return (+ <div className="space-y-3">+ <div className="rounded-md border border-border bg-background/40 p-3 text-xs text-muted-foreground">+ <div className="flex flex-wrap items-center gap-2">+ <span>{status?.message ?? t("apikeys_antigravity.status_loading")}</span>+ {status?.version && (+ <code className="rounded bg-muted px-1.5 py-0.5 font-mono">{status.version}</code>+ )}+ </div>+ </div>++ {!status?.installed && (+ <div className="flex flex-wrap items-center gap-2">+ <code className="min-w-[220px] flex-1 rounded-md border border-border bg-muted/30 px-3 py-1.5 font-mono text-xs">+ {installCommand}+ </code>+ <Button size="sm" variant="outline" onClick={handleCopy} disabled={pending === "copy"}>+ {pending === "copy" ? <Check className="h-3.5 w-3.5" /> : <Copy className="h-3.5 w-3.5" />}+ Copy command+ </Button>+ </div>+ )}++ <div className="flex flex-wrap gap-2">+ <Button size="sm" onClick={handleLogin} disabled={pending !== null || !status?.installed}>+ <LogIn className="h-3.5 w-3.5" />+ Connect with Google+ </Button>+ <Button size="sm" variant="outline" asChild>+ <a href="https://antigravity.google" target="_blank" rel="noreferrer">+ <Terminal className="h-3.5 w-3.5" />+ Install Antigravity+ </a>+ </Button>+ </div>+ </div>+ );+}++// One calm chip vocabulary for every card state. Sentence-case, small, and+// tonally consistent (gold = on, green = ready, neutral = untouched, red =+// broken) — replaces the earlier mix of shouting uppercase badges.+const STATE_CHIP_TONE = {+ active: "border-primary/40 bg-primary/15 text-primary font-semibold",+ ready: "border-emerald-500/30 bg-emerald-500/10 text-emerald-600",+ missing: "border-destructive/30 bg-destructive/10 text-destructive",+ neutral: "border-border bg-muted text-muted-foreground",+} as const;++export function StateChip({+ tone,+ children,+}: {+ tone: keyof typeof STATE_CHIP_TONE;+ children: React.ReactNode;+}) {+ return (+ <span+ className={cn(+ "inline-flex items-center rounded-full border px-2 py-0.5 text-[10px] font-medium",+ STATE_CHIP_TONE[tone],+ )}+ >+ {children}+ </span>+ );+}++export function StatusBadge({ descriptor }: { descriptor: ProviderDescriptor }) {+ if (descriptor.active) return <StateChip tone="active">active</StateChip>;+ if (descriptor.auth_mode === "codex") {+ const status = descriptor.codex_status;+ if (!status?.installed) return <StateChip tone="missing">missing</StateChip>;+ if (descriptor.configured) return <StateChip tone="ready">ready</StateChip>;+ return <StateChip tone="neutral">not connected</StateChip>;+ }+ if (descriptor.auth_mode === "antigravity") {+ const status = descriptor.antigravity_status;+ if (!status?.installed) return <StateChip tone="missing">missing</StateChip>;+ if (status.connected) return <StateChip tone="ready">ready</StateChip>;+ return <StateChip tone="neutral">not connected</StateChip>;+ }+ if (descriptor.configured) return <StateChip tone="ready">ready</StateChip>;+ return <StateChip tone="neutral">open</StateChip>;+}diff --git a/jarvis/ui/web/frontend/src/views/ApiKeysView.tsx b/jarvis/ui/web/frontend/src/views/ApiKeysView.tsxindex 919a489387..03694895bd 100644--- a/jarvis/ui/web/frontend/src/views/ApiKeysView.tsx+++ b/jarvis/ui/web/frontend/src/views/ApiKeysView.tsx@@ -1,45 +1,34 @@-import { useEffect, useRef, useState } from "react";-import { useMemo } from "react";-import { AlertCircle, Bot, Brain, Check, Copy, KeyRound, Loader2, LogIn, LogOut, Mic, Phone, PlugZap, Radio, SlidersHorizontal, Sparkles, Terminal, Volume2, Waypoints, XCircle } from "lucide-react";+import { useEffect, useRef, useState } from "react";+import { Bot, Brain, KeyRound, Mic, Phone, Radio, SlidersHorizontal, Terminal, Volume2 } from "lucide-react";import { ViewHeader } from "@/views/ChatsView";-import { AltCredentialNote } from "@/components/AltCredentialNote";-import { ApiKeyForm } from "@/components/ApiKeyForm";-import { BrainModelSelector } from "@/components/BrainModelSelector";-import { OpenRouterTtsControls } from "@/components/OpenRouterTtsVoicePicker";-import { CuModelSelector } from "@/components/CuModelSelector";-import { RealtimeOptionsControl } from "@/components/RealtimeOptionsControl";-import { ProviderBillingBadge } from "@/components/ProviderBillingBadge";import { JarvisAgentSection } from "@/components/JarvisAgentSection";import { TelephonyPanel } from "@/views/TelephonyView";import { WikiProviderCard } from "@/views/settings/WikiProviderCard";import { JarvisApiGroup } from "@/views/settings/JarvisApiGroup";import { TeamProxyGroup } from "@/views/settings/TeamProxyGroup";-import { Button } from "@/components/ui/button";+// The provider-card machinery lives in its own module so the voice section's+// "API Keys" tab renders the very same subtree (scoped to the `stt` tier)+// instead of forking a second implementation.+import {+ CategoryHero,+ EngineModeSwitch,+ GuidancePanel,+ makeProviderCategories,+ ProviderCategory,+ useTierHealth,+ VoiceEngineContext,+ type CategoryMeta,+ type LucideIcon,+ type RecommendationTab,+ type VoiceEngineMode,+} from "@/components/providers/ProviderTierSection";import {- codexLogout,- loginAntigravity,- logoutAntigravity,type ProviderDescriptor,- type ProviderTestResult,- type ProviderTestStatus,type ProviderTier,type SectionHealth,- saveProviderBaseUrl,- sectionHealthForSubject,- startCodexLogin,- switchBrainProvider,- switchComputerUseProvider,- switchRealtimeProvider,- switchSttProvider,- switchTtsProvider,- testProvider,useProviders,- useSectionHealth,} from "@/hooks/useProviders";-import { useEventStore } from "@/store/events";import { useVoiceMode } from "@/hooks/useVoiceMode";-import { agentBrand, agentsBrand } from "@/lib/agentBrand";-import { robustCopy } from "@/lib/clipboard";import { cn } from "@/lib/utils";import { useT } from "@/i18n";@@ -52,20 +41,6 @@ import { useT } from "@/i18n";// lives in the "Advanced" tab so it never competes with the core categories.type CategoryKey = ProviderTier | "subagents" | "jarvis-key" | "advanced";-// The top-level engine mode. Feature A supersedes design D1 ("view-only"):-// the switch now decides which tab set is shown AND persists `[voice].mode`-// via `useVoiceMode().setMode` — Pipeline always (it's always reachable),-// Realtime only when a realtime provider actually has a key-// (`realtimeAvailable`), so the switch can never pin the boot default to an-// unreachable engine. See `EngineModeSwitch` below for the exact rule.-type VoiceEngineMode = "pipeline" | "realtime";--// The three provider slots the maintainer's setup recommendation speaks about-// (RecommendedSetupPanel). All three are ordinary CategoryKeys; "realtime"-// additionally requires the Realtime tab set, so opening it switches the VIEW-// mode (never the persisted `[voice].mode`).-type RecommendationTab = "realtime" | "computer-use" | "subagents";-// Realtime replaces STT+Brain+TTS with one full-duplex model, so those three// tiers don't apply in Realtime mode — that's the whole reason for the split.// "computer-use" is GLOBAL (not mode-specific — Computer-Use is one engine for@@ -88,89 +63,18 @@ const REALTIME_TABS: CategoryKey[] = ["advanced",];-type LucideIcon = typeof Brain;--interface CategoryMeta {- /** Short label for the segmented tab. */- tab: string;- /** Full heading shown in the category hero band. */- title: string;- /** One-line plain-language description under the heading. */- description: string;- icon: LucideIcon;-}--// Meta for the three provider tiers (brain/tts/stt). Subagents and Advanced are-// composed separately because they own their own data sources / sub-sections.-function makeProviderCategories(- t: (k: string) => string,-): Record<ProviderTier, CategoryMeta> {- return {- brain: {- tab: t("apikeys_view.tab_brain"),- title: t("apikeys_view.tier_brain"),- description: t("apikeys_view.cat_brain_desc"),- icon: Brain,- },- tts: {- tab: t("apikeys_view.tab_tts"),- title: t("apikeys_view.tier_tts"),- description: t("apikeys_view.cat_tts_desc"),- icon: Volume2,- },- stt: {- tab: t("apikeys_view.tab_stt"),- title: t("apikeys_view.tier_stt"),- description: t("apikeys_view.cat_stt_desc"),- icon: Mic,- },- realtime: {- tab: t("apikeys_view.tab_realtime"),- title: t("apikeys_view.tier_realtime"),- description: t("apikeys_view.cat_realtime_desc"),- icon: Radio,- },- "computer-use": {- tab: t("apikeys_view.tab_computer_use"),- title: t("apikeys_view.tier_computer_use"),- description: t("apikeys_view.cat_computer_use_desc"),- icon: Terminal,- },- };-}-export function ApiKeysView() {const t = useT();const { providers, loading, error, refetch, setActiveOptimistic } = useProviders();// Per-tab health (amber = the active provider isn't set up, red = it's set up// but failing a live check). Best-effort and off the render-blocking path.- const { health: rawHealth } = useSectionHealth();- const health = useMemo(() => {- const visible = { ...rawHealth };- const activeSubjects: Record<string, string | undefined> = {- brain: providers.find((provider) => provider.tier === "brain" && provider.active)?.id,- tts: providers.find((provider) => provider.tier === "tts" && provider.active)?.id,- stt: providers.find((provider) => provider.tier === "stt" && provider.active)?.id,- realtime: providers.find(- (provider) => provider.tier === "realtime" && provider.active,- )?.id,- "computer-use": providers.find(- (provider) => provider.tier === "brain" && provider.computer_use_active,- )?.id,- };- for (const [section, subjectId] of Object.entries(activeSubjects)) {- const matching = sectionHealthForSubject(rawHealth[section], subjectId);- if (matching) visible[section] = matching;- else delete visible[section];- }- return visible;- }, [providers, rawHealth]);+ const health = useTierHealth(providers);const categories = makeProviderCategories(t);const [active, setActive] = useState<CategoryKey>("brain");const [engineMode, setEngineMode] = useState<VoiceEngineMode>("pipeline");// The LIVE `[voice].mode` (+ cross-family availability) for the "Active"// badge AND for gating the segment's own persistence (Feature A). See- // VoiceEngineMode / EngineModeSwitch above.+ // VoiceEngineMode / EngineModeSwitch in the provider module.const {mode: liveMode,realtimeAvailable,@@ -294,349 +198,6 @@ export function ApiKeysView() {);}-/**- * The Pipeline|Realtime segmented switch. Feature A (supersedes D1): clicking- * a segment still switches the local view (`onSelect`), and ALSO persists- * `[voice].mode` — Pipeline unconditionally (always reachable), Realtime only- * when `realtimeAvailable` (a key is present for some realtime family);- * otherwise the click just switches the view so the user can add a key from- * the Realtime tab without silently pinning the boot default to a dead- * engine.- *- * Visual system (one system, two legible states):- * - A sliding gold thumb sits under the segment matching the LIVE- * `[voice].mode` — unmistakably "this engine is on". `useVoiceMode` updates- * its cache optimistically, so the thumb follows the click INSTANTLY and- * only rolls back if the persist fails.- * - The segment currently being VIEWED but not live gets a subtle outline- * only (no fill) — it's a transient look, not "on".- * - Realtime with no key configured anywhere (`!realtimeAvailable`) reads- * muted; it stays clickable (opens the Realtime tab so the user can add one)- * but never gets the fill.- * - The explanatory copy lives in `VoiceEngineContext` inside the provider- * scroller, keeping this always-visible header control one compact row.- */-function EngineModeSwitch({- mode,- liveMode,- realtimeAvailable,- onSelect,- onSetVoiceMode,-}: {- mode: VoiceEngineMode;- /** The live `[voice].mode` value — determines the filled/active segment. */- liveMode: string;- /** Whether SOME realtime family (OpenAI/Gemini) has a key configured. */- realtimeAvailable: boolean;- onSelect: (mode: VoiceEngineMode) => void;- /** Persists `[voice].mode` — gated per the rule above. */- onSetVoiceMode: (mode: string) => void;-}) {- const t = useT();- // Realtime leads as the recommended default. Pipeline follows with an- // explicit Not recommended badge so the product guidance is unambiguous.- const segments: { key: VoiceEngineMode; label: string; icon: LucideIcon }[] = [- { key: "realtime", label: t("apikeys_view.mode_realtime"), icon: Radio },- { key: "pipeline", label: t("apikeys_view.mode_pipeline"), icon: Waypoints },- ];- const liveIndex = liveMode === "realtime" ? 0 : 1;- const liveModeAvailable = liveMode !== "realtime" || realtimeAvailable;-- function handleSelect(seg: VoiceEngineMode) {- onSelect(seg);- if (seg === "pipeline" || realtimeAvailable) {- onSetVoiceMode(seg);- }- }-- return (- <div- data-testid="voice-engine-header-control"- role="group"- aria-label={t("apikeys_view.voice_engine_label")}- className="shrink-0"- >- <div className="relative grid min-w-56 grid-cols-2 rounded-lg border border-border bg-card/40 p-0.5">- {liveModeAvailable && (- <span- data-testid="voice-engine-live-thumb"- aria-hidden="true"- className="absolute inset-y-0.5 left-0.5 w-[calc(50%-0.125rem)] rounded-md bg-primary shadow-[0_0_14px_rgba(255,214,10,0.22)] transition-transform duration-200 ease-out"- style={{ transform: `translateX(${liveIndex * 100}%)` }}- />- )}- {segments.map((seg) => {- const isLive = liveModeAvailable && liveMode === seg.key;- const isViewedOnly = mode === seg.key && !isLive;- const needsKey = seg.key === "realtime" && !realtimeAvailable;- const isRecommended = seg.key === "realtime";- const Icon = seg.icon;- return (- <button- key={seg.key}- type="button"- onClick={() => handleSelect(seg.key)}- aria-pressed={mode === seg.key}- className={cn(- "relative z-10 inline-flex items-center justify-center gap-1 rounded-md px-2 py-1 text-xs font-medium transition-colors",- "focus-visible:outline-none focus-visible:ring-2 focus-visible:ring-ring",- isLive- ? "text-primary-foreground"- : isViewedOnly- ? "text-foreground ring-1 ring-border"- : needsKey- ? "text-muted-foreground/60 hover:text-muted-foreground"- : "text-muted-foreground hover:text-foreground",- )}- >- <Icon aria-hidden="true" className="h-3 w-3" />- <span className="whitespace-nowrap">{seg.label}</span>- <span- className={cn(- "whitespace-nowrap rounded-full px-1 py-px text-[8px] font-semibold uppercase tracking-wide",- isRecommended- ? isLive- ? "bg-primary-foreground/20 text-primary-foreground"- : "bg-primary/15 text-primary"- : isLive- ? "border border-primary-foreground/30 bg-primary-foreground/10 text-primary-foreground"- : "border border-amber-500/30 bg-amber-500/10 text-amber-600 dark:text-amber-400",- )}- >- {t(- isRecommended- ? "apikeys_view.mode_recommended"- : "apikeys_view.not_recommended",- )}- </span>- {isLive && (- <span className="sr-only">{t("apikeys_view.mode_active_badge")}</span>- )}- </button>- );- })}- </div>- {/* One discreet reminder right where the choice is made: you configure- exactly one engine, never both. The per-mode key details live in the- VoiceEngineContext copy below, so this stays a single short line. */}- <p- data-testid="voice-engine-pick-one-hint"- className="mt-1 text-right text-[10px] leading-tight text-muted-foreground/70"- >- {t("apikeys_view.mode_pick_one_hint")}- </p>- </div>- );-}--/**- * Compact, scrollable context for the header-level engine control. Keeping- * explanatory copy and recommendations inside the provider scroller gives the- * fixed viewport back to provider cards on laptop-height windows, while the- * switch itself remains immediately reachable in the main header.- */-function VoiceEngineContext({- mode,- realtimeAvailable,- statusKnown,- sessionActive,- activeSessionMode,- activeSessionProvider,- activeSessionModel,- transitioning,- liveMode,- onOpenRecommendedTab,-}: {- mode: VoiceEngineMode;- realtimeAvailable: boolean;- statusKnown: boolean;- sessionActive: boolean;- activeSessionMode: "pipeline" | "realtime" | null;- activeSessionProvider: string;- activeSessionModel: string;- transitioning: boolean;- liveMode: string;- onOpenRecommendedTab: (tab: RecommendationTab) => void;-}) {- const t = useT();- const runtimeDetail = [activeSessionProvider, activeSessionModel]- .filter(Boolean)- .join(" · ");- const runtimeText = transitioning- ? t("apikeys_view.runtime_switching")- : sessionActive && activeSessionMode === "realtime"- ? `${t("apikeys_view.runtime_realtime")}${runtimeDetail ? ` · ${runtimeDetail}` : ""}`- : sessionActive && activeSessionMode === "pipeline" && liveMode === "realtime"- ? t("apikeys_view.runtime_fallback_pipeline")- : sessionActive && activeSessionMode === "pipeline"- ? t("apikeys_view.runtime_pipeline")- : t("apikeys_view.runtime_idle");- const runtimeMatchesSelection =- !sessionActive || activeSessionMode === null || activeSessionMode === liveMode;- const modeDescription =- mode === "realtime" && !realtimeAvailable- ? t(- statusKnown- ? "apikeys_view.mode_needs_key"- : "apikeys_view.mode_status_unknown",- )- : mode === "realtime"- ? t("apikeys_view.mode_desc_realtime")- : t("apikeys_view.mode_desc_pipeline");-- return (- <section- data-testid="voice-engine-context"- className="mx-auto mb-4 w-full max-w-4xl rounded-xl border border-border bg-card/25 px-3 py-2"- aria-label={t("apikeys_view.voice_engine_label")}- >- <div className="flex min-w-0 flex-wrap items-center gap-x-4 gap-y-1.5">- <div- className="flex min-w-64 flex-1 items-center gap-2 overflow-hidden text-xs"- title={`${t("apikeys_view.voice_engine_desc")} ${modeDescription}`}- >- <Volume2 aria-hidden="true" className="h-3.5 w-3.5 shrink-0 text-primary" />- <span className="shrink-0 font-medium text-foreground">- {t("apikeys_view.voice_engine_label")}- </span>- <span aria-hidden="true" className="text-border">·</span>- <span className="min-w-0 truncate text-muted-foreground">- {modeDescription}- {mode === "realtime" && (- <span className="text-amber-500/90">- {` · ${t("apikeys_view.mode_realtime_preview")}`}- </span>- )}- </span>- </div>- <div- className="flex shrink-0 items-center gap-1.5 text-[11px] leading-snug"- aria-live="polite"- data-testid="voice-engine-runtime-status"- >- <span- aria-hidden="true"- className={cn(- "h-1.5 w-1.5 shrink-0 rounded-full",- transitioning- ? "animate-pulse bg-amber-400 motion-reduce:animate-none"- : runtimeMatchesSelection- ? "bg-emerald-400"- : "bg-amber-400",- )}- />- <span- className={cn(- runtimeMatchesSelection && !transitioning- ? "text-muted-foreground"- : "text-amber-300",- )}- >- {runtimeText}- </span>- </div>- </div>-- <p- data-testid="voice-engine-keys-hint"- className="mt-1 text-[11px] leading-snug text-muted-foreground/80"- >- {t("apikeys_view.mode_keys_hint")}- </p>-- {mode === "realtime" && (- <RecommendedSetupPanel onOpenTab={onOpenRecommendedTab} />- )}- </section>- );-}--/**- * The maintainer's personal pick for the three provider slots of the REALTIME- * tab set, shown in the scrollable engine context only while that tab set is- * being viewed — the picks name Realtime-mode tabs, so surfacing them next to- * the Pipeline tabs would point at tabs that are not even on screen- * (maintainer feedback 2026-07-17). Same contract as the per-card- * "Recommended" badges fed by provider_spec.py: a presentation hint only — it- * never gates behavior and never branches a code path on a provider name- * (AP-21). Each row is a button that jumps straight to the tab it names, so- * the guidance sits one click from the place it applies. The rows carry an- * explicit aria-label starting with the panel title so their accessible names- * never collide with the Pipeline|Realtime segment buttons (tests match those- * via /^realtime/i).- */-function RecommendedSetupPanel({- onOpenTab,-}: {- onOpenTab: (tab: RecommendationTab) => void;-}) {- const t = useT();- const rows: {- tab: RecommendationTab;- icon: LucideIcon;- label: string;- pick: string;- why: string;- }[] = [- {- tab: "realtime",- icon: Radio,- label: t("apikeys_view.tab_realtime"),- pick: t("apikeys_view.reco_realtime_pick"),- why: t("apikeys_view.reco_realtime_why"),- },- {- tab: "computer-use",- icon: Terminal,- label: t("apikeys_view.tab_computer_use"),- pick: t("apikeys_view.reco_computer_use_pick"),- why: t("apikeys_view.reco_computer_use_why"),- },- {- tab: "subagents",- icon: Bot,- label: t("apikeys_view.tab_subagents"),- pick: t("apikeys_view.reco_subagents_pick"),- why: t("apikeys_view.reco_subagents_why"),- },- ];- return (- <div- data-testid="recommended-setup-panel"- className="mt-2 flex min-w-0 items-center gap-2 border-t border-primary/20 pt-2"- >- <p className="flex shrink-0 items-center gap-1.5 text-[11px] font-medium text-foreground">- <Sparkles aria-hidden="true" className="h-3.5 w-3.5 shrink-0 text-primary" />- {t("apikeys_view.reco_title")}- </p>- <ul className="flex min-w-0 flex-1 items-center gap-1 overflow-x-auto scrollbar-jarvis">- {rows.map((row) => {- const Icon = row.icon;- return (- <li key={row.tab} className="shrink-0">- <button- type="button"- onClick={() => onOpenTab(row.tab)}- data-testid={`reco-row-${row.tab}`}- aria-label={`${t("apikeys_view.reco_title")}: ${row.label} — ${row.pick}. ${row.why}`}- title={row.why}- className="inline-flex items-center gap-1.5 whitespace-nowrap rounded-md border border-primary/15 bg-primary/[0.04] px-2 py-1 text-[11px] leading-none transition-colors hover:bg-primary/10 focus-visible:outline-none focus-visible:ring-2 focus-visible:ring-ring"- >- <Icon- aria-hidden="true"- className="h-3 w-3 shrink-0 text-primary/80"- />- <span className="text-muted-foreground">{row.label}:</span>- <span className="font-medium text-foreground">{row.pick}</span>- </button>- </li>- );- })}- </ul>- </div>- );-}-/*** The segmented category navigation. The four core categories are grouped in one* pill container; the de-emphasized "Advanced" tab is set apart by a divider and@@ -799,129 +360,6 @@ function TabButton({);}-/**- * The header band atop each category panel: an icon chip, the full category- * title (display font), and a one-line plain-language description. Mirrors the- * app's `ViewHeader` icon treatment so the screen reads as one system.- */-function CategoryHero({- icon: Icon,- title,- description,-}: {- icon: LucideIcon;- title: string;- description: string;-}) {- return (- <div className="mb-4 flex items-start gap-2.5">- <div className="flex h-8 w-8 shrink-0 items-center justify-center rounded-lg border border-border bg-secondary/40 text-primary">- <Icon className="h-4 w-4" />- </div>- <div className="min-w-0">- <h3 className="font-display text-base font-semibold tracking-tight">- {title}- </h3>- <p className="mt-0.5 text-xs text-muted-foreground">{description}</p>- </div>- </div>- );-}--/**- * A soft, gold-tinted "which one should I pick?" band — the one place a- * category speaks up with an opinion. Used by the Realtime and Computer-Use- * tabs, where the model choice genuinely confuses people; the calmer tiers- * carry their guidance on the cards themselves (Recommended badges).- */-function GuidancePanel({ title, body }: { title: string; body: string }) {- return (- <div className="mb-3 flex items-start gap-2.5 rounded-xl border border-primary/25 bg-primary/[0.05] px-3 py-2">- <Sparkles aria-hidden="true" className="mt-0.5 h-4 w-4 shrink-0 text-primary" />- <p className="min-w-0 text-xs leading-relaxed">- <span className="font-medium text-foreground">{title}</span>- <span className="text-muted-foreground"> · {body}</span>- </p>- </div>- );-}--/**- * One of the three provider tiers (brain/tts/stt): the hero band plus the- * loading / error / empty / card states. The card list itself is `TierSection`,- * reused unchanged from the original layout.- */-function ProviderCategory({- meta,- tier,- providers,- loading,- error,- onChanged,- onActivateOptimistic,- health,- intro,-}: {- meta: CategoryMeta;- tier: ProviderTier;- providers: ProviderDescriptor[];- loading: boolean;- error: string | null;- onChanged: () => void;- onActivateOptimistic: (tier: ProviderTier, id: string) => void;- /** Live health of this tier's ACTIVE provider — drills the tab's red dot down- * onto the exact card that is failing so the user sees WHICH provider broke. */- health?: SectionHealth;- /** Optional guidance band rendered between the hero and the card list. */- intro?: React.ReactNode;-}) {- const t = useT();- const tierProviders = providers.filter(- (p) => p.tier === tier && p.brain_switchable !== false,- );-- return (- <div role="tabpanel">- <CategoryHero icon={meta.icon} title={meta.title} description={meta.description} />-- {intro}-- {loading && (- <div className="flex items-center gap-2 text-sm text-muted-foreground">- <Loader2 className="h-4 w-4 animate-spin" /> {t("apikeys_view.loading_providers")}- </div>- )}-- {error && (- <div className="flex items-start gap-2 rounded-md border border-destructive/30 bg-destructive/5 p-4 text-sm text-destructive">- <AlertCircle className="mt-0.5 h-4 w-4" />- <div>- {t("apikeys_view.load_error")} ({error}).- <button onClick={() => onChanged()} className="ml-2 underline">- {t("apikeys_view.retry")}- </button>- </div>- </div>- )}-- {!loading && !error && tierProviders.length === 0 && (- <p className="text-sm text-muted-foreground">- {t("apikeys_view.no_providers_in_tier")}- </p>- )}-- {!loading && !error && tierProviders.length > 0 && (- <TierSection- providers={tierProviders}- onChanged={onChanged}- onActivateOptimistic={onActivateOptimistic}- health={health}- />- )}- </div>- );-}-/*** The Realtime category (Feature B): the two realtime provider cards, via the* SAME `ProviderCategory` used for brain/tts/stt (unchanged). Realtime@@ -1128,1047 +566,3 @@ function TelephonySection() {</section>);}--// The card list for a single provider tier. The category label now lives in the-// tab bar + the `CategoryHero` above, so this renders only the cards. If nobody-// in the tier is active yet, a freshly saved key auto-activates itself — the-// first configured provider wins automatically (`autoActivateOnSave`).-function TierSection({- providers,- onChanged,- onActivateOptimistic,- health,-}: {- providers: ProviderDescriptor[];- onChanged: () => void;- onActivateOptimistic: (tier: ProviderTier, id: string) => void;- /** Tier health — handed only to the ACTIVE card, since section-health tests- * exactly the one provider powering this tier. */- health?: SectionHealth;-}) {- const tierHasActive = providers.some((p) => p.active);- // Configured (or active) providers first — the wall of empty key forms used- // to bury the one or two cards the user actually set up. `active` counts so- // an active-but-keyless anomaly (e.g. a free-tier provider) can never hide- // below untouched cards; among configured cards nothing reorders on a switch- // (both stay rank 0), so a card never jumps under the pointer mid-click.- // Stable within each group (Array.sort is stable).- const sorted = [...providers].sort(- (a, b) =>- Number(b.configured || b.active) - Number(a.configured || a.active),- );- return (- <ul className="space-y-3">- {sorted.map((p) => (- <li key={p.id}>- <ProviderCard- descriptor={p}- onChanged={onChanged}- onActivateOptimistic={onActivateOptimistic}- autoActivateOnSave={!tierHasActive}- health={p.active ? sectionHealthForSubject(health, p.id) : undefined}- />- </li>- ))}- </ul>- );-}--function ProviderCard({- descriptor,- onChanged,- onActivateOptimistic,- autoActivateOnSave,- health,-}: {- descriptor: ProviderDescriptor;- onChanged: () => void;- onActivateOptimistic: (tier: ProviderTier, id: string) => void;- autoActivateOnSave: boolean;- /** Live section-health for THIS card (set only on the active provider). A- * status of "error" turns the card red and surfaces the cause inline — the- * tab dot says "something here is broken", this says exactly WHAT/WHERE. */- health?: SectionHealth;-}) {- const t = useT();- const [activating, setActivating] = useState(false);- const pushToast = useEventStore((s) => s.pushToast);- const assistantName = useEventStore((s) => s.assistantName);- // The card only escalates to red for a real "set up but failing" error — the- // amber "needs setup" case stays on the tab + the open/ready badge so a fresh,- // half-configured screen doesn't paint cards red.- const cardError = descriptor.active && health?.status === "error";- // The backend one-liner (e.g. "OpenRouter: rate limited") already names the- // provider + cause, so it answers "what is wrong" without a second lookup.- const cardErrorDetail = health?.detail?.trim() || "";-- // Codex is filtered out of the Brain tier (`brain_switchable=false`) and is- // selected from the Subagent section. This branch stays for older payloads or- // tests that still mount a Codex descriptor directly.- const isCodex = descriptor.auth_mode === "codex";- const isBrainSwitchable =- descriptor.tier !== "brain" || descriptor.brain_switchable !== false;-- async function activate(assumeConfigured = false) {- if (descriptor.active) return;- if (!isBrainSwitchable) {- pushToast(- "warning",- `${descriptor.label} is only available for ${agentsBrand(assistantName)}.`,- );- return;- }- if (isCodex && !descriptor.codex_brain_ready) {- // The card is "connected" via OAuth, but a chat brain needs an OpenAI key.- // Guide honestly instead of switching and failing on the first turn.- pushToast("warning", t("apikeys_codex.brain_needs_openai_key"));- return;- }- if (!assumeConfigured && !descriptor.configured) {- pushToast(- "warning",- descriptor.auth_mode === "codex"- ? t("apikeys_codex.needs_codex_full").replace("{0}", descriptor.label)- : descriptor.auth_mode === "antigravity"- ? t("apikeys_antigravity.needs_login_full").replace("{0}", descriptor.label)- : t("apikeys_codex.needs_key_full").replace("{0}", descriptor.label),- );- return;- }- // Flip the highlight immediately so the switch feels instant — the backend- // call below can take a few seconds (a TTS switch rebuilds the provider and- // injects it into the live pipeline). The refetch on success / failure then- // reconciles with server truth.- onActivateOptimistic(descriptor.tier, descriptor.id);- setActivating(true);- try {- if (descriptor.tier === "brain") {- await switchBrainProvider(descriptor.id);- pushToast("success", `Brain → ${descriptor.label}`);- window.dispatchEvent(new CustomEvent("jarvis:brain-switched"));- } else if (descriptor.tier === "tts") {- const result = await switchTtsProvider(descriptor.id);- const note = result.restart_required- ? " (active from next voice start)"- : "";- pushToast("success", `Voice output → ${descriptor.label}${note}`);- window.dispatchEvent(new CustomEvent("jarvis:tts-switched"));- } else if (descriptor.tier === "stt") {- const result = await switchSttProvider(descriptor.id);- const note = result.restart_required- ? " (active from next voice start)"- : "";- pushToast("success", `Voice input → ${descriptor.label}${note}`);- window.dispatchEvent(new CustomEvent("jarvis:stt-switched"));- } else if (descriptor.tier === "computer-use") {- await switchComputerUseProvider(descriptor.id);- pushToast("success", `Computer-Use → ${descriptor.label}`);- window.dispatchEvent(new CustomEvent("jarvis:computer-use-switched"));- } else {- const result = await switchRealtimeProvider(descriptor.id);- const note = result.restart_required- ? " (active from next voice start)"- : "";- pushToast("success", `Realtime → ${descriptor.label}${note}`);- window.dispatchEvent(new CustomEvent("jarvis:realtime-switched"));- }- onChanged();- } catch (e) {- pushToast("error", (e as Error).message);- // Roll the optimistic highlight back to the true active provider.- onChanged();- window.dispatchEvent(- new CustomEvent("jarvis:provider-switch-failed", {- detail: { section: descriptor.tier, provider: descriptor.id },- }),- );- } finally {- setActivating(false);- }- }-- // A single click AND a double click on the card both activate the provider.- // We explicitly filter clicks on interactive sub-elements (inputs, buttons,- // links) so that a click into the password field or on the- // "Replace"/trash icon does NOT accidentally trigger a switch. The radio- // also has its own stopPropagation for historical reasons- // (belt and suspenders).- function handleCardActivate(e: React.MouseEvent<HTMLDivElement>) {- // Codex is connection-only — a card click must never trigger a brain switch.- if (isCodex) return;- if (!isBrainSwitchable) return;- const target = e.target as HTMLElement | null;- if (- target &&- (target.closest("input") ||- target.closest("button") ||- target.closest("a") ||- target.closest("label"))- ) {- return;- }- void activate();- }-- // Called by ApiKeyForm as soon as a key has been saved for a previously- // unconfigured provider. If no one else is active in this tier, the- // freshly configured provider takes over automatically — otherwise the- // user has to click the now-visible "Activate" button.- async function handleSavedActivate() {- if (!autoActivateOnSave) return;- if (descriptor.active) return;- await activate(true);- }-- return (- <div- onClick={handleCardActivate}- onDoubleClick={handleCardActivate}- title={- descriptor.active- ? t("apikeys_view.active_tooltip")- : !isBrainSwitchable- ? `Available for ${agentsBrand(assistantName)} only`- : descriptor.configured- ? t("apikeys_view.click_to_activate")- : descriptor.auth_mode === "codex"- ? t("apikeys_view.needs_codex")- : descriptor.auth_mode === "antigravity"- ? t("apikeys_view.needs_login")- : t("apikeys_view.needs_key")- }- className={cn(- "card-outline space-y-3 p-4 transition-colors",- // A broken active provider wins the card's frame — red outline + faint- // red wash — so the eye lands on the exact card behind the tab's red dot.- cardError- ? "border-destructive/70 bg-destructive/[0.05] ring-1 ring-destructive/30"- : descriptor.active- ? "border-primary bg-primary/[0.06] ring-1 ring-primary/30"- : descriptor.configured- ? isBrainSwitchable- ? "cursor-pointer hover:border-primary/40 hover:bg-primary/[0.02]"- : ""- : "opacity-95",- )}- >- <div className="flex items-start justify-between gap-3">- <div className="min-w-0 flex-1">- <div className="flex flex-wrap items-center gap-2">- <span className="font-display text-sm font-semibold tracking-tight">- {descriptor.label}- </span>- <StatusBadge descriptor={descriptor} />- {descriptor.recommended && (- <span- className="inline-flex items-center gap-1 rounded-full border border-primary/40 bg-primary/10 px-2 py-0.5 text-[10px] font-medium text-primary"- title={- descriptor.recommended_model- ? t("apikeys_view.recommended_tooltip").replace(- "{0}",- descriptor.recommended_model,- )- : undefined- }- >- <Sparkles aria-hidden="true" className="h-2.5 w-2.5" />- {t("apikeys_view.recommended")}- </span>- )}- {descriptor.caution && (- <span- className="rounded-full border border-amber-500/40 bg-amber-500/10 px-2 py-0.5 text-[10px] font-medium text-amber-600 dark:text-amber-400"- title={descriptor.caution}- >- {t("apikeys_view.not_recommended")}- </span>- )}- </div>- <p className="mt-0.5 text-[11px] text-muted-foreground">- <code className="font-mono">{descriptor.id}</code>- {" · "}- <span>- {descriptor.auth_mode === "api_key" && "API key auth"}- {descriptor.auth_mode === "codex" && "ChatGPT / Codex login"}- {descriptor.auth_mode === "antigravity" && "Google subscription login"}- {descriptor.auth_mode === "none" && "Local — no auth"}- </span>- </p>- </div>-- <ActiveControl- descriptor={- isCodex- ? { ...descriptor, configured: Boolean(descriptor.codex_brain_ready) }- : descriptor- }- activating={activating}- onActivate={activate}- disabled={!isBrainSwitchable || (isCodex && !descriptor.codex_brain_ready)}- disabledReason={- !isBrainSwitchable- ? `Available for ${agentsBrand(assistantName)} only`- : isCodex && !descriptor.codex_brain_ready- ? t("apikeys_codex.brain_needs_openai_key")- : undefined- }- />- </div>-- {/* The precise "this card is the problem" banner: only on the active card,- only when the live check actually failed. Names the cause in plain- words instead of leaving the user to guess behind the tab's red dot. */}- {cardError && (- <div- data-testid={`provider-health-error-${descriptor.id}`}- role="status"- className="flex items-start gap-2 rounded-md border border-destructive/40 bg-destructive/[0.07] px-3 py-2 text-[11px] leading-relaxed text-destructive"- >- <XCircle className="mt-0.5 h-3.5 w-3.5 shrink-0" />- <span className="min-w-0 break-words">- <span className="font-medium">{t("apikeys_view.health_error")}</span>- {cardErrorDetail ? ` — ${cardErrorDetail}` : ""}- </span>- </div>- )}-- <AuthWidget- descriptor={descriptor}- onChanged={onChanged}- onSavedActivate={handleSavedActivate}- />-- {!isBrainSwitchable && (- <p className="rounded-md border border-amber-500/25 bg-amber-500/10 px-3 py-2 text-[11px] leading-relaxed text-amber-700">- {agentBrand(assistantName)} only. This provider cannot be used as the main Brain or- Computer-Use planner because it does not receive screenshots.- </p>- )}-- {/* Model / voice picker. Every switchable brain provider shows its model- picker — even before a key is set — because the catalog falls back to- the provider's curated family without a key (no network, no error), so- a model can be pre-picked. TTS/STT share a single global [tts]/[stt]- block, so the picker only WRITES from the ACTIVE provider and sets the- voice (Grok/Gemini/OpenAI/Google) or model (Cartesia/STT). */}- {((descriptor.tier === "brain" && isBrainSwitchable) ||- ((descriptor.tier === "tts" || descriptor.tier === "stt") &&- descriptor.active &&- descriptor.configured)) &&- // OpenRouter TTS is the one provider where the user also picks a VOICE- // (per model, language-tagged, with an audio preview) — render the- // combined model + voice controls; every other tier keeps the plain- // model/voice picker.- (descriptor.id === "openrouter-tts" ? (- <OpenRouterTtsControls- providerId={descriptor.id}- recommendedModel={descriptor.recommended_model}- healthActive={descriptor.active}- />- ) : (- <BrainModelSelector- providerId={descriptor.id}- recommendedModel={descriptor.recommended_model}- healthSection={descriptor.tier}- healthActive={descriptor.active}- />- ))}-- {/* TTS/STT model/voice is a single global value, so a configured-but-- inactive provider can't own it — make the capability discoverable with- a hint instead of silently hiding the picker. */}- {(descriptor.tier === "tts" || descriptor.tier === "stt") &&- descriptor.configured &&- !descriptor.active && (- <p className="text-[11px] text-muted-foreground">- {t("apikeys_view.model_picker_activate_hint")}- </p>- )}-- {/* Phase 3: a dedicated Computer-Use model, selectable per brain provider- (defaults to the provider's main model — no automatic escalation).- Also shown under the Computer-Use tab (synthetic "computer-use"- tier, same underlying brain id) — but never the plain- BrainModelSelector above, which stays Brain-tab-only. */}- {(descriptor.tier === "brain" || descriptor.tier === "computer-use") &&- descriptor.configured &&- isBrainSwitchable && (- <CuModelSelector- providerId={descriptor.id}- recommendedModel={descriptor.recommended_model}- healthActive={- descriptor.tier === "computer-use"- ? descriptor.active- : Boolean(descriptor.computer_use_active)- }- />- )}-- {/* Realtime needs BOTH a model AND a voice pinned per provider — a- dedicated compact control (two dropdowns), gated on the card- already having a stored credential like the other tiers' pickers- above. */}- {descriptor.tier === "realtime" && descriptor.configured && (- <RealtimeOptionsControl- providerId={descriptor.id}- healthActive={descriptor.active}- />- )}-- {/* Footer: the live connectivity test, visually separated from the- configuration body so "set up" and "verify" read as two steps. */}- <div className="border-t border-border/60 pt-2.5">- <ProviderTestControl- providerId={descriptor.id}- providerLabel={descriptor.label}- section={descriptor.tier}- active={descriptor.active}- />- </div>- </div>- );-}--// Tone per status: green = works; amber = reached but key/account/model blocks-// (integration is fine); red = couldn't reach / integration bug.-const TEST_STATUS_TONE: Record<ProviderTestStatus, string> = {- ok: "border-emerald-500/30 bg-emerald-500/10 text-emerald-600",- not_configured: "border-border bg-muted text-muted-foreground",- bad_key: "border-amber-500/30 bg-amber-500/10 text-amber-600",- no_credits: "border-amber-500/30 bg-amber-500/10 text-amber-600",- rate_limited: "border-amber-500/30 bg-amber-500/10 text-amber-600",- model_unavailable: "border-amber-500/30 bg-amber-500/10 text-amber-600",- unreachable: "border-destructive/30 bg-destructive/10 text-destructive",- error: "border-destructive/30 bg-destructive/10 text-destructive",-};--/**- * "Test" button + honest result chip. Calls POST /api/providers/{id}/test which- * makes a REAL minimal call — distinguishing a working provider from an invalid- * key, an out-of-credits account, or an unreachable endpoint. This is the piece- * the API-Keys view was missing: the green "configured" badge only ever meant a- * key STRING was stored, never that the provider answers.- */-function ProviderTestControl({- providerId,- providerLabel,- section,- active,-}: {- providerId: string;- providerLabel: string;- section: ProviderTier;- active: boolean;-}) {- const t = useT();- const [running, setRunning] = useState(false);- const [result, setResult] = useState<ProviderTestResult | null>(null);- const activeRef = useRef(active);- activeRef.current = active;-- function publish(next: ProviderTestResult) {- window.dispatchEvent(- new CustomEvent("jarvis:provider-tested", {- detail: {- section,- provider: providerId,- provider_label: providerLabel,- active: activeRef.current,- result: next,- },- }),- );- }-- async function run() {- setRunning(true);- setResult(null);- try {- const next = await testProvider(providerId);- setResult(next);- publish(next);- } catch (e) {- const next: ProviderTestResult = {- provider: providerId,- status: "error",- detail: (e as Error).message,- latency_ms: 0,- integration_ok: false,- };- setResult(next);- publish(next);- } finally {- setRunning(false);- }- }-- const tone = result ? TEST_STATUS_TONE[result.status] : "";- const note = result- ? (result.integration_ok- ? t("apikeys_test.integration_ok_note")- : t("apikeys_test.integration_bad_note"))- : "";-- return (- <div className="flex flex-wrap items-center gap-2 pt-0.5">- <Button- size="sm"- variant="outline"- onClick={(e) => {- e.stopPropagation();- void run();- }}- disabled={running}- className="h-7 gap-1.5 text-xs"- >- {running ? (- <Loader2 className="h-3.5 w-3.5 animate-spin" />- ) : (- <PlugZap className="h-3.5 w-3.5" />- )}- {running ? t("apikeys_test.running") : t("apikeys_test.button")}- </Button>-- {result && (- <span- data-testid={`provider-test-result-${providerId}`}- className={cn(- "inline-flex items-center gap-1 rounded-full border px-2 py-0.5 text-[11px]",- tone,- )}- title={[note, result.detail, result.latency_ms ? `${Math.round(result.latency_ms)} ms` : ""]- .filter(Boolean)- .join("\n")}- >- {result.status === "ok" ? (- <Check className="h-3 w-3" />- ) : result.integration_ok ? (- <AlertCircle className="h-3 w-3" />- ) : (- <XCircle className="h-3 w-3" />- )}- {t(`apikeys_test.status_${result.status}`)}- {result.status === "ok" && result.latency_ms- ? ` · ${Math.round(result.latency_ms)} ms`- : ""}- </span>- )}- </div>- );-}--/**- * Radio-button-based active toggle. The source of truth stays- * `descriptor.active` from `/api/providers` — the radio mirrors server- * state, it is not held locally. `name="active-{tier}"` gives us browser-- * native exclusivity per tier (Brain/TTS/STT).- *- * `disabled` would suppress onChange; that's why the radio is NOT disabled- * when a key is missing — instead it routes through `activate()` to raise a- * warning toast. This way the user gets a reaction to every click, instead- * of bumping into a silent element.- */-function ActiveControl({- descriptor,- activating,- onActivate,- disabled = false,- disabledReason,-}: {- descriptor: ProviderDescriptor;- activating: boolean;- onActivate: () => void;- /**- * Truly disable the radio (no click, no toast). Used for Codex when it cannot- * be a brain yet (no OpenAI key) — a click there would be a dead end, so we- * disable instead of firing a warning toast. Other providers stay clickable- * (warn-on-click) because their key field is right on the card.- */- disabled?: boolean;- disabledReason?: string;-}) {- const labelTitle = descriptor.active- ? "This provider is active"- : disabled- ? disabledReason ?? "Provider cannot be activated"- : descriptor.configured- ? "Activate this provider"- : "Set an API key first";-- return (- <label- onClick={(e) => e.stopPropagation()}- onDoubleClick={(e) => {- // A double click on the radio label must NOT also trigger the- // card's onDoubleClick — otherwise activate() would fire twice- // (idempotent, but sends two API calls).- e.stopPropagation();- }}- className={cn(- "inline-flex shrink-0 select-none items-center gap-1.5 text-xs",- disabled ? "cursor-not-allowed" : "cursor-pointer",- descriptor.active- ? "font-medium text-primary"- : descriptor.configured- ? "text-muted-foreground hover:text-foreground"- : "text-muted-foreground/70",- )}- title={labelTitle}- >- <input- type="radio"- name={`active-${descriptor.tier}`}- checked={descriptor.active}- onChange={() => onActivate()}- disabled={activating || disabled}- className="accent-primary"- />- {activating ? "Activating…" : descriptor.active ? "Active" : "Set active"}- </label>- );-}--function BaseUrlField({- descriptor,- onChanged,-}: {- descriptor: ProviderDescriptor;- onChanged: () => void;-}) {- const t = useT();- const pushToast = useEventStore((s) => s.pushToast);- const [value, setValue] = useState(descriptor.base_url ?? "");- const [saving, setSaving] = useState(false);-- // Follow refetches (e.g. after another card action) without clobbering an- // in-flight edit: only resync while the user is not mid-save.- useEffect(() => {- setValue(descriptor.base_url ?? "");- // eslint-disable-next-line react-hooks/exhaustive-deps- }, [descriptor.base_url]);-- const dirty = value.trim() !== (descriptor.base_url ?? "");-- async function save() {- setSaving(true);- try {- const stored = await saveProviderBaseUrl(descriptor.id, value.trim() || null);- setValue(stored ?? "");- pushToast(- "success",- stored ? t("apikeys_base_url.saved") : t("apikeys_base_url.cleared"),- );- onChanged();- } catch (e) {- pushToast("error", e instanceof Error ? e.message : String(e));- } finally {- setSaving(false);- }- }-- return (- <div className="space-y-1">- <label className="text-[10px] uppercase tracking-wider text-muted-foreground">- {t("apikeys_base_url.label")}- </label>- <div className="flex gap-2">- <input- type="url"- value={value}- onChange={(e) => setValue(e.target.value)}- placeholder={- descriptor.default_base_url ?? t("apikeys_base_url.placeholder_required")- }- className="h-8 w-full rounded-md border border-border bg-background px-2 text-xs"- />- <Button- size="sm"- variant="secondary"- onClick={save}- disabled={saving || !dirty}- >- {saving ? t("apikeys_base_url.saving") : t("apikeys_base_url.save")}- </Button>- </div>- <p className="text-[11px] leading-relaxed text-muted-foreground">- {descriptor.default_base_url- ? t("apikeys_base_url.hint_default")- : t("apikeys_base_url.hint_required")}- </p>- </div>- );-}--function AuthWidget({- descriptor,- onChanged,- onSavedActivate,-}: {- descriptor: ProviderDescriptor;- onChanged: () => void;- onSavedActivate?: () => void;-}) {- return (- <div className="space-y-2">- <ProviderBillingBadge billing={descriptor.billing} />- {descriptor.supports_base_url && (- <BaseUrlField descriptor={descriptor} onChanged={onChanged} />- )}- {descriptor.auth_mode === "none" && (- <>- <p className="text-xs text-muted-foreground">- {descriptor.secret_keys.length > 0- ? "Local provider — runs without credentials. The key below is optional, only for servers that enforce one (e.g. vLLM --api-key)."- : "Local provider — no credentials needed."}- </p>- {descriptor.secret_keys.map((k) => (- <ApiKeyForm- key={k}- secretKey={k}- dashboardUrl={descriptor.dashboard_url}- configured={Boolean(descriptor.secrets_set[k])}- effectiveConfigured={Boolean(descriptor.secrets_effective?.[k])}- sharedWith={descriptor.secret_shared_with?.[k] ?? []}- credentialHelp={descriptor.credential_help}- onChanged={onChanged}- onSavedActivate={onSavedActivate}- />- ))}- </>- )}- {descriptor.auth_mode === "codex" && (- <CodexAuthWidget descriptor={descriptor} onChanged={onChanged} />- )}- {descriptor.auth_mode === "antigravity" && (- <AntigravityAuthWidget descriptor={descriptor} onChanged={onChanged} />- )}- {descriptor.auth_mode === "api_key" && (- <>- {descriptor.secret_keys.map((k) => (- <ApiKeyForm- key={k}- secretKey={k}- dashboardUrl={descriptor.dashboard_url}- configured={Boolean(descriptor.secrets_set[k])}- effectiveConfigured={Boolean(descriptor.secrets_effective?.[k])}- sharedWith={descriptor.secret_shared_with?.[k] ?? []}- credentialHelp={descriptor.credential_help}- onChanged={onChanged}- onSavedActivate={onSavedActivate}- />- ))}- {descriptor.alt_credential && (- <AltCredentialNote alt={descriptor.alt_credential} />- )}- </>- )}- </div>- );-}--function CodexAuthWidget({- descriptor,- onChanged,-}: {- descriptor: ProviderDescriptor;- onChanged: () => void;-}) {- const t = useT();- const [pending, setPending] = useState<"login" | "logout" | "copy" | null>(null);- const pushToast = useEventStore((s) => s.pushToast);- const status = descriptor.codex_status;- const installCommand = descriptor.install_hint ?? "npm i -g @openai/codex";-- async function handleCopy() {- setPending("copy");- try {- const copied = await robustCopy(installCommand);- pushToast(copied ? "success" : "warning", copied ? "Install command copied" : installCommand);- } finally {- setPending(null);- }- }-- async function handleLogin() {- setPending("login");- try {- await startCodexLogin();- pushToast("info", t("apikeys_codex.login_started"));- // `codex login` opens the browser OAuth flow; it only completes once the- // user clicks through (seconds later). Poll a few times so the card flips- // to the compact "connected" state on its own once auth.json appears —- // no manual refresh needed.- [1500, 4000, 8000, 15000, 25000].forEach((ms) =>- window.setTimeout(onChanged, ms),- );- } catch (e) {- pushToast("error", (e as Error).message);- } finally {- setPending(null);- }- }-- async function handleLogout() {- setPending("logout");- try {- await codexLogout();- pushToast("info", t("apikeys_codex.disconnected"));- onChanged();- } catch (e) {- pushToast("error", (e as Error).message);- } finally {- setPending(null);- }- }-- // Connected: collapse to a small "logged in" badge instead of the full card.- // No connect button (no second invitation), no API-key field (the key lives on- // the separate "OpenAI" provider). Activation as the worker happens in the- // Subagent list below.- if (status?.connected) {- return (- <div className="space-y-3">- <div- data-testid="codex-connected"- className="flex flex-wrap items-center gap-2 rounded-md border border-emerald-500/30 bg-emerald-500/[0.06] px-3 py-2 text-xs"- >- <Check className="h-3.5 w-3.5 shrink-0 text-emerald-500" />- <span className="min-w-0 break-words text-foreground">- {status.message ?? "Connected via ChatGPT."}- </span>- {status.version && (- <code className="rounded bg-muted px-1.5 py-0.5 font-mono">{status.version}</code>- )}- {status.mode === "chatgpt" && <span className="chip-yellow">CHATGPT-LOGIN</span>}- <Button- size="sm"- variant="ghost"- onClick={handleLogout}- disabled={pending !== null}- className="ml-auto"- >- <LogOut className="h-3.5 w-3.5" />- Disconnect- </Button>- </div>- </div>- );- }-- // Not connected: status + (install hint) + the single "connect" action.- return (- <div className="space-y-3">- <div className="rounded-md border border-border bg-background/40 p-3 text-xs text-muted-foreground">- <div className="flex flex-wrap items-center gap-2">- <span>{status?.message ?? t("apikeys_codex.status_loading")}</span>- {status?.version && (- <code className="rounded bg-muted px-1.5 py-0.5 font-mono">{status.version}</code>- )}- </div>- </div>-- {!status?.installed && (- <div className="flex flex-wrap items-center gap-2">- <code className="min-w-[220px] flex-1 rounded-md border border-border bg-muted/30 px-3 py-1.5 font-mono text-xs">- {installCommand}- </code>- <Button size="sm" variant="outline" onClick={handleCopy} disabled={pending === "copy"}>- {pending === "copy" ? <Check className="h-3.5 w-3.5" /> : <Copy className="h-3.5 w-3.5" />}- Copy command- </Button>- </div>- )}-- <div className="flex flex-wrap gap-2">- <Button size="sm" onClick={handleLogin} disabled={pending !== null || !status?.installed}>- <LogIn className="h-3.5 w-3.5" />- Connect with ChatGPT- </Button>- <Button size="sm" variant="outline" asChild>- <a href="https://help.openai.com/en/articles/11381614" target="_blank" rel="noreferrer">- <Terminal className="h-3.5 w-3.5" />- Install Codex- </a>- </Button>- </div>-- </div>- );-}--function AntigravityAuthWidget({- descriptor,- onChanged,-}: {- descriptor: ProviderDescriptor;- onChanged: () => void;-}) {- const t = useT();- const [pending, setPending] = useState<"login" | "logout" | "copy" | null>(null);- const pushToast = useEventStore((s) => s.pushToast);- const status = descriptor.antigravity_status;- const installCommand =- descriptor.install_hint ?? "curl -fsSL https://antigravity.google/cli/install.sh | bash";-- async function handleCopy() {- setPending("copy");- try {- const copied = await robustCopy(installCommand);- pushToast(copied ? "success" : "warning", copied ? "Install command copied" : installCommand);- } finally {- setPending(null);- }- }-- async function handleLogin() {- setPending("login");- try {- await loginAntigravity();- pushToast("info", t("apikeys_antigravity.login_started"));- // The Google CLI opens the browser "Sign in with Google" flow; it only- // completes once the user clicks through (seconds later). Poll a few times- // so the card flips to the compact "connected" state on its own once the- // on-disk creds appear — no manual refresh needed (mirror of Codex).- [1500, 4000, 8000, 15000, 25000].forEach((ms) =>- window.setTimeout(onChanged, ms),- );- } catch (e) {- pushToast("error", (e as Error).message);- } finally {- setPending(null);- }- }-- async function handleLogout() {- setPending("logout");- try {- await logoutAntigravity();- pushToast("info", t("apikeys_antigravity.disconnected"));- onChanged();- } catch (e) {- pushToast("error", (e as Error).message);- } finally {- setPending(null);- }- }-- // Connected: collapse to a small "logged in" badge instead of the full card.- // The Google subscription bills the brain/subagent; no key field (OAuth-only).- if (status?.connected) {- return (- <div className="space-y-3">- <div- data-testid="antigravity-connected"- className="flex flex-wrap items-center gap-2 rounded-md border border-emerald-500/30 bg-emerald-500/[0.06] px-3 py-2 text-xs"- >- <Check className="h-3.5 w-3.5 shrink-0 text-emerald-500" />- <span className="min-w-0 break-words text-foreground">- {status.user_email- ? t("apikeys_antigravity.connected_as").replace("{0}", status.user_email)- : status.message || t("apikeys_antigravity.connected")}- </span>- {status.version && (- <code className="rounded bg-muted px-1.5 py-0.5 font-mono">{status.version}</code>- )}- <span className="chip-yellow">GOOGLE-LOGIN</span>- <Button- size="sm"- variant="ghost"- onClick={handleLogout}- disabled={pending !== null}- className="ml-auto"- >- <LogOut className="h-3.5 w-3.5" />- Disconnect- </Button>- </div>- </div>- );- }-- // Not connected: status + (install hint) + the single "connect" action.- return (- <div className="space-y-3">- <div className="rounded-md border border-border bg-background/40 p-3 text-xs text-muted-foreground">- <div className="flex flex-wrap items-center gap-2">- <span>{status?.message ?? t("apikeys_antigravity.status_loading")}</span>- {status?.version && (- <code className="rounded bg-muted px-1.5 py-0.5 font-mono">{status.version}</code>- )}- </div>- </div>-- {!status?.installed && (- <div className="flex flex-wrap items-center gap-2">- <code className="min-w-[220px] flex-1 rounded-md border border-border bg-muted/30 px-3 py-1.5 font-mono text-xs">- {installCommand}- </code>- <Button size="sm" variant="outline" onClick={handleCopy} disabled={pending === "copy"}>- {pending === "copy" ? <Check className="h-3.5 w-3.5" /> : <Copy className="h-3.5 w-3.5" />}- Copy command- </Button>- </div>- )}-- <div className="flex flex-wrap gap-2">- <Button size="sm" onClick={handleLogin} disabled={pending !== null || !status?.installed}>- <LogIn className="h-3.5 w-3.5" />- Connect with Google- </Button>- <Button size="sm" variant="outline" asChild>- <a href="https://antigravity.google" target="_blank" rel="noreferrer">- <Terminal className="h-3.5 w-3.5" />- Install Antigravity- </a>- </Button>- </div>- </div>- );-}--// One calm chip vocabulary for every card state. Sentence-case, small, and-// tonally consistent (gold = on, green = ready, neutral = untouched, red =-// broken) — replaces the earlier mix of shouting uppercase badges.-const STATE_CHIP_TONE = {- active: "border-primary/40 bg-primary/15 text-primary font-semibold",- ready: "border-emerald-500/30 bg-emerald-500/10 text-emerald-600",- missing: "border-destructive/30 bg-destructive/10 text-destructive",- neutral: "border-border bg-muted text-muted-foreground",-} as const;--function StateChip({- tone,- children,-}: {- tone: keyof typeof STATE_CHIP_TONE;- children: React.ReactNode;-}) {- return (- <span- className={cn(- "inline-flex items-center rounded-full border px-2 py-0.5 text-[10px] font-medium",- STATE_CHIP_TONE[tone],- )}- >- {children}- </span>- );-}--function StatusBadge({ descriptor }: { descriptor: ProviderDescriptor }) {- if (descriptor.active) return <StateChip tone="active">active</StateChip>;- if (descriptor.auth_mode === "codex") {- const status = descriptor.codex_status;- if (!status?.installed) return <StateChip tone="missing">missing</StateChip>;- if (descriptor.configured) return <StateChip tone="ready">ready</StateChip>;- return <StateChip tone="neutral">not connected</StateChip>;- }- if (descriptor.auth_mode === "antigravity") {- const status = descriptor.antigravity_status;- if (!status?.installed) return <StateChip tone="missing">missing</StateChip>;- if (status.connected) return <StateChip tone="ready">ready</StateChip>;- return <StateChip tone="neutral">not connected</StateChip>;- }- if (descriptor.configured) return <StateChip tone="ready">ready</StateChip>;- return <StateChip tone="neutral">open</StateChip>;-}diff --git a/jarvis/ui/web/frontend/src/views/voice/VoiceApiKeysTab.test.tsx b/jarvis/ui/web/frontend/src/views/voice/VoiceApiKeysTab.test.tsxnew file mode 100644index 0000000000..a74cd5ec25--- /dev/null+++ b/jarvis/ui/web/frontend/src/views/voice/VoiceApiKeysTab.test.tsx@@ -0,0 +1,119 @@+/**+ * Component tests for the voice section's "API Keys" tab.+ *+ * The tab is deliberately NOT a second implementation: it renders the same+ * extracted provider block the API-Keys view uses, scoped to the `stt` tier.+ * These tests pin the two things that would silently break that contract —+ * that a speech-to-text provider card actually renders here, and that none of+ * the API-Keys view's own category tabs come along for the ride (this screen+ * shows one tier, so a tab strip would be a rendering fault).+ */+import { afterEach, describe, expect, it, vi } from "vitest";+import { cleanup, render, screen } from "@testing-library/react";++import type { ProviderDescriptor } from "@/hooks/useProviders";++// Deterministic data: no network round-trip, no react-query provider needed.+const STT_PROVIDER: ProviderDescriptor = {+ id: "test-speech",+ label: "Test Speech Service",+ tier: "stt",+ auth_mode: "api_key",+ secret_keys: ["TEST_SPEECH_API_KEY"],+ secrets_set: { TEST_SPEECH_API_KEY: false },+ dashboard_url: null,+ login_cli: null,+ install_hint: null,+ credential_path_hint: null,+ configured: false,+ active: false,+ cli_installed: null,+ credential_help: null,+ signup_url: null,+ billing: "api",+ alt_credential: null,+};++const BRAIN_PROVIDER: ProviderDescriptor = {+ ...STT_PROVIDER,+ id: "test-brain",+ label: "Test Brain Service",+ tier: "brain",+ secret_keys: ["TEST_BRAIN_API_KEY"],+ secrets_set: { TEST_BRAIN_API_KEY: false },+};++vi.mock("@/hooks/useProviders", () => ({+ sectionHealthForSubject: (+ health: { subject_id?: string } | undefined,+ subjectId?: string,+ ) => (subjectId && health?.subject_id === subjectId ? health : undefined),+ useProviders: () => ({+ providers: [STT_PROVIDER, BRAIN_PROVIDER],+ loading: false,+ error: null,+ refetch: vi.fn(),+ setActiveOptimistic: vi.fn(),+ }),+ useSectionHealth: () => ({ health: {} }),+}));++vi.mock("@/hooks/useVoiceMode", () => ({+ useVoiceMode: () => ({+ mode: "pipeline",+ realtimeAvailable: false,+ statusKnown: true,+ sessionActive: false,+ activeSessionMode: null,+ activeSessionProvider: "",+ activeSessionModel: "",+ transitioning: false,+ setMode: vi.fn(),+ isLoading: false,+ isSaving: false,+ }),+}));++import { VoiceApiKeysTab } from "@/views/voice/VoiceApiKeysTab";++afterEach(() => {+ cleanup();+ vi.clearAllMocks();+});++describe("VoiceApiKeysTab", () => {+ it("renders the speech-to-text provider card", () => {+ render(<VoiceApiKeysTab />);++ expect(screen.getByTestId("voice-api-keys-tab")).toBeTruthy();+ expect(screen.getByText("Test Speech Service")).toBeTruthy();+ expect(screen.getByLabelText("Enter TEST_SPEECH_API_KEY")).toBeTruthy();+ });++ it("shows only the speech-to-text tier, never other tiers' providers", () => {+ render(<VoiceApiKeysTab />);++ expect(screen.queryByText("Test Brain Service")).toBeNull();+ });++ it("brings none of the API-Keys view's category tabs along", () => {+ render(<VoiceApiKeysTab />);++ expect(screen.queryByTestId("api-keys-category-tabs")).toBeNull();+ expect(screen.queryAllByRole("tab")).toHaveLength(0);+ });++ it("keeps the engine switch, so the tier's relevance stays visible", () => {+ render(<VoiceApiKeysTab />);++ expect(screen.getByTestId("voice-engine-header-control")).toBeTruthy();+ });++ it("stands its own header down when the merged section owns it", () => {+ const { rerender } = render(<VoiceApiKeysTab />);+ const withHeader = screen.getAllByRole("heading").length;++ rerender(<VoiceApiKeysTab hideHeader />);+ expect(screen.getAllByRole("heading").length).toBe(withHeader - 1);+ });+});diff --git a/jarvis/ui/web/frontend/src/views/voice/VoiceApiKeysTab.tsx b/jarvis/ui/web/frontend/src/views/voice/VoiceApiKeysTab.tsxindex 2f450c58cc..3da6465466 100644--- a/jarvis/ui/web/frontend/src/views/voice/VoiceApiKeysTab.tsx+++ b/jarvis/ui/web/frontend/src/views/voice/VoiceApiKeysTab.tsx@@ -1,6 +1,16 @@+import { useEffect, useRef, useState } from "react";import { KeyRound } from "lucide-react";import { ViewHeader } from "@/views/ChatsView";+import {+ EngineModeSwitch,+ makeProviderCategories,+ ProviderCategory,+ useTierHealth,+ type VoiceEngineMode,+} from "@/components/providers/ProviderTierSection";+import { useProviders } from "@/hooks/useProviders";+import { useVoiceMode } from "@/hooks/useVoiceMode";import { useT } from "@/i18n";export interface VoiceApiKeysTabProps {@@ -18,16 +28,44 @@ export interface VoiceApiKeysTabProps {* "API Keys" tab of the merged voice section — the providers and keys that turn* speech into text.*- * Placeholder shell: the shell, its section id and its i18n keys ship first so- * the rest of the section can be built against a stable surface. The speech-to-- * text provider block (the same subtree the API-Keys view renders, scoped to- * the `stt` tier) lands here next.+ * This is the SAME provider block the API-Keys view renders, scoped to the+ * `stt` tier: one shared `ProviderCategory`, not a second implementation. A key+ * saved here is therefore the same stored credential the API-Keys view shows,+ * and vice versa — the two screens are never mounted at the same time+ * (`MainView.SwitchOnActiveSection` renders exactly one section), and+ * `ApiKeyForm` announces every save/delete on the window event bus that+ * `useProviders` / `useSectionHealth` already listen to, so whichever screen is+ * opened next reads the current truth.+ *+ * The engine switch rides along because it decides whether this tier is used at+ * all: speech-to-text is a Pipeline-mode stage, and a realtime model replaces+ * it entirely. Hiding that would let someone add a key here that their voice+ * never touches.*/export function VoiceApiKeysTab({ hideHeader = false }: VoiceApiKeysTabProps = {}) {const t = useT();+ const { providers, loading, error, refetch, setActiveOptimistic } = useProviders();+ const health = useTierHealth(providers);+ const categories = makeProviderCategories(t);+ const {+ mode: liveMode,+ realtimeAvailable,+ setMode: setVoiceMode,+ isLoading: liveModeLoading,+ } = useVoiceMode();++ // Mirror the API-Keys view: open on the engine that is actually LIVE, once,+ // when the mode query resolves. Later live-mode changes never yank the view.+ const [engineMode, setEngineMode] = useState<VoiceEngineMode>("pipeline");+ const viewSyncedToLive = useRef(false);+ useEffect(() => {+ if (viewSyncedToLive.current || liveModeLoading) return;+ viewSyncedToLive.current = true;+ setEngineMode(liveMode === "realtime" ? "realtime" : "pipeline");+ }, [liveMode, liveModeLoading]);return (- <div className="flex h-full flex-col">+ <div className="flex h-full min-h-0 flex-col">{!hideHeader && (<ViewHeadericon={<KeyRound className="h-4 w-4 text-primary" />}@@ -36,10 +74,34 @@ export function VoiceApiKeysTab({ hideHeader = false }: VoiceApiKeysTabProps = {/>)}<div- className="flex-1 overflow-y-auto scrollbar-jarvis p-6"+ className="min-h-0 flex-1 overflow-y-auto scrollbar-jarvis px-4 py-4"data-testid="voice-api-keys-tab">- <div className="mx-auto flex max-w-3xl flex-col gap-4" />+ <div className="mx-auto flex w-full max-w-4xl flex-col gap-4">+ <div className="flex flex-wrap items-start justify-between gap-3 rounded-xl border border-border bg-card/25 px-3 py-2">+ <p className="min-w-64 flex-1 text-[11px] leading-snug text-muted-foreground/80">+ {t("apikeys_view.mode_keys_hint")}+ </p>+ <EngineModeSwitch+ mode={engineMode}+ liveMode={liveMode}+ realtimeAvailable={realtimeAvailable}+ onSelect={setEngineMode}+ onSetVoiceMode={setVoiceMode}+ />+ </div>++ <ProviderCategory+ meta={categories.stt}+ tier="stt"+ providers={providers}+ loading={loading}+ error={error}+ onChanged={refetch}+ onActivateOptimistic={setActiveOptimistic}+ health={health.stt}+ />+ </div></div></div>);diff --git a/tests/unit/dictation/test_dictation_audio.py b/tests/unit/dictation/test_dictation_audio.pynew file mode 100644index 0000000000..3d1f295cdd--- /dev/null+++ b/tests/unit/dictation/test_dictation_audio.py@@ -0,0 +1,225 @@+"""The audio sidecars kept for dictations that produced nothing usable.++Raw microphone audio is the most sensitive thing this application would ever+store, so the tests that matter most here are the ones about it going away+again: the retention caps, the purge, and the fact that an entry id can never+be used to write outside the audio directory.+"""++from __future__ import annotations++import os+import time+import wave+from pathlib import Path++import pytest++from jarvis.dictation.audio import (+ CHANNELS,+ MAX_AUDIO_BYTES,+ SAMPLE_RATE,+ SAMPLE_WIDTH,+ audio_exists,+ audio_path_for,+ default_audio_dir,+ delete_dictation_audio,+ load_dictation_audio,+ prune_audio,+ purge_dictation_audio,+ save_dictation_audio,+)+++def audio_dir(tmp_path: Path) -> Path:+ return tmp_path / "dictation_audio"+++def _pcm(seconds: float) -> bytes:+ return b"\x01\x02" * int(seconds * SAMPLE_RATE)+++# --------------------------------------------------------------------------+# Writing+# --------------------------------------------------------------------------+++def test_saved_file_is_16k_mono_int16_wav(audio_dir: Path) -> None:+ path = save_dictation_audio("abc123", _pcm(0.5), directory=audio_dir)+ assert path is not None+ with wave.open(str(path), "rb") as handle:+ assert handle.getframerate() == SAMPLE_RATE+ assert handle.getnchannels() == CHANNELS+ assert handle.getsampwidth() == SAMPLE_WIDTH+ assert handle.getnframes() == int(0.5 * SAMPLE_RATE)+++def test_round_trip_returns_the_same_pcm(audio_dir: Path) -> None:+ pcm = _pcm(0.25)+ path = save_dictation_audio("roundtrip", pcm, directory=audio_dir)+ assert path is not None+ assert load_dictation_audio(path) == pcm+++def test_empty_pcm_writes_nothing(audio_dir: Path) -> None:+ assert save_dictation_audio("empty", b"", directory=audio_dir) is None+ assert audio_dir.exists() is False+++def test_a_half_sample_tail_is_trimmed_instead_of_corrupting_the_frame(+ audio_dir: Path,+) -> None:+ path = save_dictation_audio("odd", b"\x01\x02\x03", directory=audio_dir)+ assert path is not None+ with wave.open(str(path), "rb") as handle:+ assert handle.getnframes() == 1+++def test_audio_longer_than_the_ceiling_is_truncated_not_refused(+ audio_dir: Path,+) -> None:+ oversized = b"\x00\x01" * ((MAX_AUDIO_BYTES // 2) + 1000)+ path = save_dictation_audio("long", oversized, directory=audio_dir)+ assert path is not None+ assert len(load_dictation_audio(path)) == MAX_AUDIO_BYTES+++def test_no_temporary_file_is_left_behind(audio_dir: Path) -> None:+ save_dictation_audio("clean", _pcm(0.1), directory=audio_dir)+ assert [p.name for p in audio_dir.iterdir()] == ["clean.wav"]+++# --------------------------------------------------------------------------+# The id is untrusted input+# --------------------------------------------------------------------------+++ "entry_id",+ ["../escape", "..\\escape", "a/b", "a\\b", "с:\\x"],+)+def test_a_hostile_entry_id_can_never_escape_the_audio_directory(+ entry_id: str, audio_dir: Path+) -> None:+ path = save_dictation_audio(entry_id, _pcm(0.1), directory=audio_dir)+ assert path is not None+ assert path.parent.resolve() == audio_dir.resolve()++[email protected]("entry_id", ["", " ", "..", "/", "///"])+def test_an_entry_id_with_nothing_usable_left_writes_nothing(+ entry_id: str, audio_dir: Path+) -> None:+ assert audio_path_for(entry_id, directory=audio_dir) is None+ assert save_dictation_audio(entry_id, _pcm(0.1), directory=audio_dir) is None+++def test_the_path_is_deterministic(audio_dir: Path) -> None:+ first = audio_path_for("abc", directory=audio_dir)+ second = save_dictation_audio("abc", _pcm(0.1), directory=audio_dir)+ assert first == second+++# --------------------------------------------------------------------------+# Reading a broken or absent file+# --------------------------------------------------------------------------+++def test_a_missing_file_reads_as_empty_bytes(audio_dir: Path) -> None:+ assert load_dictation_audio(audio_dir / "nope.wav") == b""+ assert load_dictation_audio(None) == b""+ assert load_dictation_audio("") == b""+++def test_a_file_that_is_not_a_wav_reads_as_empty_bytes(tmp_path: Path) -> None:+ broken = tmp_path / "broken.wav"+ broken.write_bytes(b"this is not a wav file at all")+ assert load_dictation_audio(broken) == b""+++def test_audio_exists_is_tolerant(audio_dir: Path) -> None:+ assert audio_exists(None) is False+ assert audio_exists("") is False+ assert audio_exists(audio_dir / "nope.wav") is False+ path = save_dictation_audio("here", _pcm(0.1), directory=audio_dir)+ assert audio_exists(path) is True+++# --------------------------------------------------------------------------+# Deleting — the part that matters+# --------------------------------------------------------------------------+++def test_delete_is_idempotent(audio_dir: Path) -> None:+ path = save_dictation_audio("gone", _pcm(0.1), directory=audio_dir)+ assert path is not None+ assert delete_dictation_audio(path) is True+ assert delete_dictation_audio(path) is False+ assert delete_dictation_audio(None) is False+++def test_purge_removes_every_sidecar(audio_dir: Path) -> None:+ for name in ("a", "b", "c"):+ save_dictation_audio(name, _pcm(0.1), directory=audio_dir)+ assert purge_dictation_audio(directory=audio_dir) == 3+ assert list(audio_dir.glob("*.wav")) == []+++def test_purge_on_a_missing_directory_is_a_quiet_zero(tmp_path: Path) -> None:+ assert purge_dictation_audio(directory=tmp_path / "never-created") == 0+++def test_prune_keeps_only_the_newest_files(audio_dir: Path) -> None:+ for index in range(5):+ path = save_dictation_audio(f"f{index}", _pcm(0.05), directory=audio_dir)+ assert path is not None+ os.utime(path, (time.time() - (5 - index) * 60, time.time() - (5 - index) * 60))+ assert prune_audio(max_files=2, retention_days=0, directory=audio_dir) == 3+ assert sorted(p.stem for p in audio_dir.glob("*.wav")) == ["f3", "f4"]+++def test_prune_ages_files_out_regardless_of_the_count(audio_dir: Path) -> None:+ fresh = save_dictation_audio("fresh", _pcm(0.05), directory=audio_dir)+ stale = save_dictation_audio("stale", _pcm(0.05), directory=audio_dir)+ assert fresh is not None and stale is not None+ old = time.time() - (10 * 86_400)+ os.utime(stale, (old, old))+ assert prune_audio(max_files=100, retention_days=7, directory=audio_dir) == 1+ assert fresh.exists() is True+ assert stale.exists() is False+++def test_prune_counts_each_file_once_when_both_caps_hit(audio_dir: Path) -> None:+ """A file past BOTH caps must not be counted as two deletions."""+ path = save_dictation_audio("both", _pcm(0.05), directory=audio_dir)+ assert path is not None+ old = time.time() - (10 * 86_400)+ os.utime(path, (old, old))+ assert prune_audio(max_files=0, retention_days=7, directory=audio_dir) == 1+++def test_prune_with_both_caps_disabled_deletes_nothing(audio_dir: Path) -> None:+ save_dictation_audio("keep", _pcm(0.05), directory=audio_dir)+ assert prune_audio(max_files=0, retention_days=0, directory=audio_dir) == 0+ assert len(list(audio_dir.glob("*.wav"))) == 1+++def test_prune_on_a_missing_directory_is_a_quiet_zero(tmp_path: Path) -> None:+ assert prune_audio(directory=tmp_path / "never-created") == 0+++# --------------------------------------------------------------------------+# Location+# --------------------------------------------------------------------------+++def test_default_directory_lives_under_the_user_data_dir(+ tmp_path: Path, monkeypatch: pytest.MonkeyPatch+) -> None:+ """Local only, never a synced folder, and resolved with pathlib."""+ monkeypatch.setenv("LOCALAPPDATA", str(tmp_path))+ monkeypatch.setattr(Path, "home", classmethod(lambda cls: tmp_path))+ directory = default_audio_dir()+ assert directory.name == "dictation_audio"+ assert directory.parent.name == "data"diff --git a/tests/unit/dictation/test_dictation_stats.py b/tests/unit/dictation/test_dictation_stats.pynew file mode 100644index 0000000000..59df9ae27f--- /dev/null+++ b/tests/unit/dictation/test_dictation_stats.py@@ -0,0 +1,238 @@+"""The lifetime dictation counters.++Two things here are easy to get subtly wrong and impossible to notice once+shipped, so they get the most tests: days are bucketed by the user's LOCAL+calendar date (UTC bucketing moves an evening dictation to tomorrow for+everyone east of UTC), and the streak gives today grace (so the badge reads+the real run over breakfast instead of a demoralising and wrong 0).+"""++from __future__ import annotations++import json+from datetime import UTC, datetime, timedelta, timezone+from pathlib import Path++import pytest++from jarvis.dictation.stats import (+ DictationStats,+ current_streak,+ local_day,+ longest_streak,+ summarize_entries,+ today_key,+)+++def stats(tmp_path: Path) -> DictationStats:+ return DictationStats(tmp_path / "dictation_stats.json")+++def _day(offset: int) -> str:+ return (datetime.now().astimezone().date() + timedelta(days=offset)).isoformat()+++# --------------------------------------------------------------------------+# Local-day bucketing+# --------------------------------------------------------------------------+++def test_a_naive_timestamp_is_read_as_utc() -> None:+ assert local_day("2026-07-28T12:00:00") is not None+++def test_bucketing_uses_the_local_calendar_day_not_the_utc_one() -> None:+ """23:30 in UTC+2 is still *today* locally, and yesterday in UTC."""+ moment = datetime(2026, 7, 28, 23, 30, tzinfo=timezone(timedelta(hours=2)))+ assert moment.astimezone(UTC).date().isoformat() == "2026-07-28"+ # Whatever the runner's zone is, the answer must be that instant's LOCAL+ # date — never a hardcoded UTC date.+ assert local_day(moment.isoformat()) == moment.astimezone().date().isoformat()+++def test_an_unparseable_timestamp_buckets_to_nothing() -> None:+ assert local_day("not-a-date") is None+ assert local_day("") is None+ assert local_day(None) is None+++# --------------------------------------------------------------------------+# Streaks+# --------------------------------------------------------------------------+++def test_streak_counts_back_from_today() -> None:+ assert current_streak([_day(0), _day(-1), _day(-2)]) == 3+++def test_a_quiet_today_gets_grace_instead_of_reading_zero() -> None:+ """Before the first dictation of the day the run ending yesterday shows."""+ assert current_streak([_day(-1), _day(-2)]) == 2+++def test_the_streak_only_reaches_zero_once_yesterday_was_quiet_too() -> None:+ assert current_streak([_day(-2), _day(-3)]) == 0+++def test_a_gap_ends_the_current_streak() -> None:+ assert current_streak([_day(0), _day(-2), _day(-3)]) == 1+++def test_no_days_is_a_zero_streak() -> None:+ assert current_streak([]) == 0+++def test_longest_streak_scans_the_whole_history() -> None:+ days = ["2026-01-01", "2026-01-02", "2026-01-03", "2026-02-01", "2026-02-02"]+ assert longest_streak(days) == 3+++def test_longest_streak_ignores_unparseable_days() -> None:+ assert longest_streak(["nope", "2026-01-01", "2026-01-02"]) == 2+++# --------------------------------------------------------------------------+# The sidecar+# --------------------------------------------------------------------------+++def test_a_missing_file_reads_as_empty(stats: DictationStats) -> None:+ summary = stats.summary()+ assert summary["totals"] == {+ "dictations": 0,+ "words": 0,+ "seconds": 0.0,+ "wpm": 0.0,+ }+ assert summary["by_day"] == []+ assert stats.exists is False+++def test_record_accumulates_totals_and_days(stats: DictationStats) -> None:+ now = datetime.now(UTC).isoformat()+ assert stats.record(created_at=now, word_count=10, duration_s=30.0) is True+ assert stats.record(created_at=now, word_count=20, duration_s=30.0) is True+ summary = stats.summary()+ assert summary["source"] == "lifetime"+ assert summary["totals"]["dictations"] == 2+ assert summary["totals"]["words"] == 30+ assert summary["totals"]["seconds"] == 60.0+ assert summary["totals"]["wpm"] == 30.0+ assert summary["today"] == {"dictations": 2, "words": 30}+ assert summary["by_day"][0]["date"] == today_key()+++def test_a_wordless_dictation_is_not_counted(stats: DictationStats) -> None:+ """A failure still belongs in the history — it does not belong in the WPM."""+ assert stats.record(created_at=None, word_count=0, duration_s=45.0) is False+ assert stats.summary()["totals"]["dictations"] == 0+++def test_words_per_minute_is_zero_without_a_duration(stats: DictationStats) -> None:+ stats.record(created_at=None, word_count=10, duration_s=0.0)+ assert stats.summary()["totals"]["wpm"] == 0.0+++def test_counters_survive_a_reload(tmp_path: Path) -> None:+ path = tmp_path / "s.json"+ DictationStats(path).record(created_at=None, word_count=7, duration_s=10.0)+ assert DictationStats(path).summary()["totals"]["words"] == 7+++def test_reset_zeroes_everything_including_the_streak(stats: DictationStats) -> None:+ stats.record(created_at=None, word_count=7, duration_s=10.0)+ assert stats.reset() is True+ summary = stats.summary()+ assert summary["totals"]["words"] == 0+ assert summary["streak"]["current_days"] == 0+ assert summary["by_day"] == []+++def test_a_corrupt_file_reads_as_empty_instead_of_raising(tmp_path: Path) -> None:+ path = tmp_path / "broken.json"+ path.write_text("{not json", encoding="utf-8")+ assert DictationStats(path).summary()["totals"]["words"] == 0+++def test_one_bad_day_bucket_does_not_invalidate_the_rest(tmp_path: Path) -> None:+ path = tmp_path / "mixed.json"+ path.write_text(+ json.dumps(+ {+ "version": 1,+ "totals": {"dictations": 1, "words": 5, "seconds": 10.0},+ "days": {+ "not-a-date": {"dictations": 1, "words": 5},+ "2026-01-01": {"dictations": 1, "words": 5, "seconds": 10.0},+ },+ }+ ),+ encoding="utf-8",+ )+ summary = DictationStats(path).summary()+ assert [d["date"] for d in summary["by_day"]] == ["2026-01-01"]+++def test_by_day_is_newest_first_and_capped(stats: DictationStats) -> None:+ base = datetime.now(UTC)+ for offset in range(5):+ stats.record(+ created_at=(base - timedelta(days=offset)).isoformat(),+ word_count=1,+ duration_s=1.0,+ )+ dates = [d["date"] for d in stats.summary(by_day_limit=3)["by_day"]]+ assert len(dates) == 3+ assert dates == sorted(dates, reverse=True)+++def test_the_streak_is_built_from_the_recorded_days(stats: DictationStats) -> None:+ base = datetime.now(UTC)+ for offset in range(3):+ stats.record(+ created_at=(base - timedelta(days=offset)).isoformat(),+ word_count=4,+ duration_s=2.0,+ )+ assert stats.summary()["streak"]["current_days"] == 3+ assert stats.summary()["streak"]["longest_days"] == 3+++# --------------------------------------------------------------------------+# The history-window fallback+# --------------------------------------------------------------------------+++def test_summarize_entries_labels_itself_as_a_window() -> None:+ """An install without the sidecar must not present 30 days as a lifetime."""+ from jarvis.dictation.history import DictationEntry++ now = datetime.now(UTC).isoformat()+ entries = [+ DictationEntry(+ id=str(i), created_at=now, raw_text="a b", text="a b",+ word_count=2, duration_s=6.0,+ )+ for i in range(3)+ ]+ summary = summarize_entries(entries)+ assert summary["source"] == "window"+ assert summary["totals"]["dictations"] == 3+ assert summary["totals"]["words"] == 6+ assert summary["today"]["words"] == 6+++def test_summarize_entries_skips_wordless_rows() -> None:+ from jarvis.dictation.history import DictationEntry++ entry = DictationEntry(+ id="a", created_at=datetime.now(UTC).isoformat(), raw_text="", text="",+ outcome="failed", word_count=0, duration_s=9.0,+ )+ assert summarize_entries([entry])["totals"]["dictations"] == 0+++def test_summarize_entries_tolerates_an_empty_sequence() -> None:+ assert summarize_entries([])["totals"]["words"] == 0diff --git a/tests/unit/dictation/test_segment_and_history.py b/tests/unit/dictation/test_segment_and_history.pyindex dd8f3c95d2..84aa7a54dc 100644--- a/tests/unit/dictation/test_segment_and_history.py+++ b/tests/unit/dictation/test_segment_and_history.py@@ -75,6 +75,11 @@ def history(tmp_path: Path) -> DictationHistory:return DictationHistory(tmp_path / "dictation_history.json")+def _missing_wav() -> Path:+ """A path that is guaranteed not to exist, for the availability check."""+ return Path("definitely") / "not" / "here.wav"++def test_empty_history_reads_as_empty_list(history: DictationHistory) -> None:assert history.list_all() == []@@ -136,6 +141,205 @@ def test_empty_add_is_a_no_op(history: DictationHistory) -> None:assert history.list_all() == []+# --------------------------------------------------------------------------+# The fields added for restore/statistics+# --------------------------------------------------------------------------+++def test_word_count_is_derived_from_the_inserted_text(+ history: DictationHistory,+) -> None:+ entry = history.add(raw_text="uh send the report", text="send the report")+ assert entry is not None+ assert entry.word_count == 3+++def test_an_explicit_word_count_wins_over_the_derived_one(+ history: DictationHistory,+) -> None:+ entry = history.add(raw_text="a b c", text="a b c", word_count=99)+ assert entry is not None+ assert entry.word_count == 99+++def test_a_failed_dictation_with_no_text_is_still_recorded(+ history: DictationHistory,+) -> None:+ """The worst failure must stop being the most invisible one."""+ entry = history.add(raw_text="", text="", outcome="failed", error="provider 401")+ assert entry is not None+ stored = history.list_all()+ assert [e.outcome for e in stored] == ["failed"]+ assert stored[0].error == "provider 401"+ assert stored[0].word_count == 0+++def test_an_unrecoverable_outcome_with_no_text_stays_a_no_op(+ history: DictationHistory,+) -> None:+ assert history.add(raw_text="", text="", outcome="inserted") is None+++def test_get_returns_one_entry_or_none(history: DictationHistory) -> None:+ entry = history.add(raw_text="a", text="a")+ assert entry is not None+ assert history.get(entry.id) is not None+ assert history.get("no-such-id") is None+++def test_set_discarded_hides_the_entry_without_deleting_it(+ history: DictationHistory,+) -> None:+ entry = history.add(raw_text="a", text="a")+ assert entry is not None+ assert history.set_discarded(entry.id) is not None+ assert history.list_all(include_discarded=False) == []+ assert len(history.list_all()) == 1+ # ...and it comes back, which is the whole point of a soft delete.+ history.set_discarded(entry.id, False)+ assert len(history.list_all(include_discarded=False)) == 1+++def test_set_discarded_on_an_unknown_id_is_none(history: DictationHistory) -> None:+ assert history.set_discarded("nope") is None+++def test_update_ignores_unknown_fields_instead_of_raising(+ history: DictationHistory, tmp_path: Path+) -> None:+ sidecar = str(tmp_path / "x.wav")+ entry = history.add(raw_text="a", text="a")+ assert entry is not None+ assert history.update(entry.id, not_a_field="x") is None+ updated = history.update(entry.id, audio_path=sidecar, error="boom")+ assert updated is not None+ assert updated.audio_path == sidecar+ assert updated.error == "boom"+++def test_update_never_rewrites_the_id_or_timestamp(history: DictationHistory) -> None:+ entry = history.add(raw_text="a", text="a")+ assert entry is not None+ assert history.update(entry.id, id="hijacked", created_at="1999") is None+ assert history.get(entry.id) is not None+++def test_history_written_before_the_new_fields_reads_as_defaults(+ tmp_path: Path,+) -> None:+ """An install that predates word_count/discarded/audio/error still loads."""+ path = tmp_path / "old.json"+ path.write_text(+ '{"version": 1, "entries": ['+ '{"id": "a", "created_at": "2026-07-28T00:00:00+00:00",'+ ' "raw_text": "hi", "text": "hi", "outcome": "inserted"}'+ "]}",+ encoding="utf-8",+ )+ entry = DictationHistory(path).list_all()[0]+ assert entry.word_count == 0+ assert entry.discarded is False+ assert entry.audio_path is None+ assert entry.error is None+++def test_public_dict_never_leaks_the_audio_path(history: DictationHistory) -> None:+ entry = history.add(raw_text="a", text="a")+ assert entry is not None+ history.update(entry.id, audio_path=str(_missing_wav()))+ stored = history.get(entry.id)+ assert stored is not None+ payload = stored.to_dict()+ assert "audio_path" not in payload+ assert payload["audio_available"] is False+ assert set(payload) == {+ "id", "created_at", "raw_text", "text", "language", "duration_s",+ "outcome", "method", "removed_words", "cleanup_reason", "word_count",+ "discarded", "audio_available", "error",+ }+++def test_public_dict_reports_audio_that_is_actually_on_disk(+ history: DictationHistory, tmp_path: Path+) -> None:+ from jarvis.dictation.audio import save_dictation_audio++ entry = history.add(raw_text="", text="", outcome="failed")+ assert entry is not None+ path = save_dictation_audio(entry.id, b"\x00\x01" * 800, directory=tmp_path / "a")+ assert path is not None+ history.update(entry.id, audio_path=str(path))+ stored = history.get(entry.id)+ assert stored is not None+ assert stored.to_dict()["audio_available"] is True+++def test_delete_also_removes_the_audio_sidecar(+ history: DictationHistory, tmp_path: Path+) -> None:+ from jarvis.dictation.audio import save_dictation_audio++ entry = history.add(raw_text="", text="", outcome="failed")+ assert entry is not None+ path = save_dictation_audio(entry.id, b"\x00\x01" * 800, directory=tmp_path / "a")+ assert path is not None+ history.update(entry.id, audio_path=str(path))+ assert history.delete(entry.id) is True+ assert path.exists() is False+++def test_clear_purges_history_audio_and_statistics(+ history: DictationHistory, tmp_path: Path+) -> None:+ from jarvis.dictation.audio import save_dictation_audio++ history.add(raw_text="a b c", text="a b c")+ failed = history.add(raw_text="", text="", outcome="failed")+ assert failed is not None+ path = save_dictation_audio(+ failed.id, b"\x00\x01" * 800, directory=history.audio_dir+ )+ assert path is not None+ history.update(failed.id, audio_path=str(path))+ assert history.stats().summary()["totals"]["words"] == 3++ assert history.clear() is True+ assert history.list_all() == []+ assert path.exists() is False+ assert history.stats().summary()["totals"]["words"] == 0+ assert history.stats().summary()["streak"]["current_days"] == 0+++def test_statistics_sidecar_sits_next_to_the_history_file(+ history: DictationHistory,+) -> None:+ """A history in a temp directory must not write into the real user data."""+ assert history.stats_path.parent == history.path.parent+ assert history.stats_path.name == "dictation_stats.json"+ assert history.audio_dir.parent == history.path.parent+++def test_add_feeds_the_lifetime_counters(history: DictationHistory) -> None:+ history.add(raw_text="one two three", text="one two three", duration_s=6.0)+ history.add(raw_text="four five", text="four five", duration_s=3.0)+ summary = history.stats().summary()+ assert summary["source"] == "lifetime"+ assert summary["totals"]["dictations"] == 2+ assert summary["totals"]["words"] == 5+ assert summary["today"]["words"] == 5+ assert summary["streak"]["current_days"] == 1+++def test_a_failed_dictation_does_not_move_the_words_per_minute(+ history: DictationHistory,+) -> None:+ history.add(raw_text="one two three", text="one two three", duration_s=60.0)+ history.add(raw_text="", text="", outcome="failed", duration_s=60.0)+ totals = history.stats().summary()["totals"]+ assert totals["dictations"] == 1+ assert totals["wpm"] == 3.0++# --------------------------------------------------------------------------# Pruning# --------------------------------------------------------------------------@@ -174,3 +378,96 @@ def test_unparseable_timestamp_is_kept_not_silently_discarded() -> None:def test_zero_cap_keeps_nothing() -> None:assert _prune([_entry(1)], max_entries=0, retention_days=0) == []+++# --------------------------------------------------------------------------+# Pruning must not strand a pending Restore+# --------------------------------------------------------------------------+++def _recoverable(tmp_path: Path, name: str, *, discarded: bool = False):+ """An entry that ended badly and whose audio is really on disk."""+ from jarvis.dictation.audio import save_dictation_audio+ from jarvis.dictation.history import DictationEntry++ path = save_dictation_audio(name, b"\x00\x01" * 800, directory=tmp_path)+ assert path is not None+ return DictationEntry(+ id=name,+ created_at=datetime.now(UTC).isoformat(),+ raw_text="",+ text="",+ outcome="failed",+ discarded=discarded,+ audio_path=str(path),+ )+++def test_count_cap_never_evicts_an_entry_whose_audio_a_restore_still_needs(+ tmp_path: Path,+) -> None:+ """Otherwise the row vanishes while the recording stays on disk."""+ pending = _recoverable(tmp_path, "pending")+ ordinary = [_entry(0.1, f"x{i}") for i in range(5)]+ kept = _prune([*ordinary, pending], max_entries=2, retention_days=0)+ assert pending in kept+ assert len([e for e in kept if e.audio_path is None]) == 2+++def test_a_discarded_entry_with_audio_survives_the_cap_too(tmp_path: Path) -> None:+ pending = _recoverable(tmp_path, "discarded-one", discarded=True)+ kept = _prune([_entry(0.1, "a"), pending], max_entries=1, retention_days=0)+ assert pending in kept+++def test_the_exemption_needs_the_audio_to_actually_exist(tmp_path: Path) -> None:+ """A stored path whose file is gone is not a pending recovery."""+ from jarvis.dictation.history import DictationEntry++ ghost = DictationEntry(+ id="ghost",+ created_at=datetime.now(UTC).isoformat(),+ raw_text="",+ text="",+ outcome="failed",+ audio_path=str(tmp_path / "never-written.wav"),+ )+ kept = _prune([_entry(0.1, "a"), ghost], max_entries=1, retention_days=0)+ assert ghost not in kept+++def test_a_successful_entry_with_audio_is_not_exempt(tmp_path: Path) -> None:+ """Only outcomes the user lost something to hold a Restore open."""+ from jarvis.dictation.audio import save_dictation_audio+ from jarvis.dictation.history import DictationEntry++ path = save_dictation_audio("ok", b"\x00\x01" * 800, directory=tmp_path)+ assert path is not None+ fine = DictationEntry(+ id="ok",+ created_at=datetime.now(UTC).isoformat(),+ raw_text="hi",+ text="hi",+ outcome="inserted",+ audio_path=str(path),+ )+ kept = _prune([_entry(0.1, "a"), fine], max_entries=1, retention_days=0)+ assert fine not in kept+++def test_the_exemption_does_not_survive_the_retention_window(tmp_path: Path) -> None:+ """Audio ages out on its own schedule; a stale row is not held open."""+ from jarvis.dictation.audio import save_dictation_audio+ from jarvis.dictation.history import DictationEntry++ path = save_dictation_audio("old", b"\x00\x01" * 800, directory=tmp_path)+ assert path is not None+ stale = DictationEntry(+ id="old",+ created_at=(datetime.now(UTC) - timedelta(days=40)).isoformat(),+ raw_text="",+ text="",+ outcome="failed",+ audio_path=str(path),+ )+ assert _prune([stale], max_entries=100, retention_days=30) == []