Skip to content

Dodaios is an open-source agent OS for your desktop: it runs your coding agents, browser and apps by voice or chat, on your own machine. Formerly Personal Jarvis.

feat(ui): consolidate in-flight desktop UI + frontend work

Ruben Lütkebc1a1ec63b33
diff --git a/jarvis/ui/desktop_app.py b/jarvis/ui/desktop_app.py
index 5f0a3c7580..582aaa28d1 100644
--- a/jarvis/ui/desktop_app.py
+++ b/jarvis/ui/desktop_app.py
@@ -20,8 +20,10 @@ import secrets
import sys
import threading
import time
+from collections.abc import Awaitable, Callable
+from contextlib import suppress
from pathlib import Path
-from typing import TYPE_CHECKING, Any, Awaitable
+from typing import TYPE_CHECKING, Any
# Windows-UTF8-Fix (analog zu jarvis.__main__)
if sys.platform == "win32":
@@ -404,26 +406,91 @@ async def _await_cancellable_chat_turn(
# ---------------------------------------------------------------------------
+def _default_lock_holder_health(port: int) -> bool:
+ """True if a Jarvis webserver answers ``/api/health`` on *port* (loopback).
+
+ Retries briefly so a still-booting fast-boot instance — which binds + answers
+ health in well under a second — is NEVER mistaken for a dead one. Returns the
+ SAFE default (``True`` → "treat as alive, do not evict") whenever it cannot
+ probe at all (no httpx), so a probing failure can never cause an eviction.
+ """
+ try:
+ import httpx
+ except Exception: # noqa: BLE001
+ return True # cannot probe → never evict on uncertainty
+ url = f"http://127.0.0.1:{int(port)}/api/health"
+ for _ in range(4):
+ with suppress(Exception):
+ r = httpx.get(url, timeout=1.0)
+ if r.status_code == 200:
+ return True
+ time.sleep(0.5)
+ return False
+
+
+def _terminate_pid(pid: int) -> bool:
+ """Terminate a confirmed lock-zombie process. Returns True once it is gone.
+
+ Graceful ``terminate()`` first, then ``kill()`` if it lingers. Returns False
+ (→ the caller keeps the lock blocked, the SAFE outcome) when psutil is
+ missing or the kill did not take, so we never falsely report a still-living
+ process as evicted.
+ """
+ try:
+ import psutil # type: ignore[import-not-found]
+ except Exception: # noqa: BLE001
+ return False
+ try:
+ proc = psutil.Process(int(pid))
+ except Exception: # noqa: BLE001
+ return True # already gone
+ # terminate may race the process self-exiting; the final _pid_alive check is
+ # the authority on whether it is really gone.
+ with suppress(Exception):
+ proc.terminate()
+ try:
+ proc.wait(timeout=5.0)
+ except Exception: # noqa: BLE001 — graceful timed out → hard kill
+ with suppress(Exception):
+ proc.kill()
+ proc.wait(timeout=5.0)
+ return not _pid_alive(pid)
+
+
def acquire_single_instance_lock(
*,
timeout: float = _LOCK_ACQUIRE_TIMEOUT,
lock_path: Path | None = None,
meta_path: Path | None = None,
+ health_probe: Callable[[int], bool] | None = None,
+ terminate: Callable[[int], bool] | None = None,
) -> FileLock:
"""Acquire exklusives Lock oder raise :class:`SingleInstanceError`.
Stale-Lock-Erkennung: wenn das Lock belegt ist, lesen wir das
PID-Sidecar und pruefen ``psutil.pid_exists(pid)``. Ist der PID tot,
- loeschen wir Lock + Sidecar und versuchen erneut (genau einmal).
+ loeschen wir Lock + Sidecar und versuchen erneut.
+
+ Lock-zombie eviction (forensic 2026-06-26): a holder PID can be ALIVE yet
+ non-functional — its webserver accept-socket died on a transient WinError 64
+ while voice/telegram kept the process running, so it holds the lock with no
+ bound port and no window and would block EVERY restart. When the holder is
+ alive but its admin port does not answer health (probed with retries so a
+ still-booting instance is never falsely accused), we terminate the zombie and
+ reclaim the lock. Never the own pid (no suicide); never a healthy holder.
Args:
timeout: Sekunden bis wir den ersten Acquire aufgeben. Default 0.0.
lock_path: Override fuer Tests.
meta_path: Override fuer Tests.
+ health_probe: Override fuer Tests — ``(port) -> bool`` health check.
+ terminate: Override fuer Tests — ``(pid) -> bool`` process kill.
"""
lp = lock_path or LOCK_FILE_PATH
mp = meta_path or META_FILE_PATH
lp.parent.mkdir(parents=True, exist_ok=True)
+ probe = health_probe or _default_lock_holder_health
+ killer = terminate or _terminate_pid
lock = FileLock(str(lp))
try:
@@ -441,25 +508,52 @@ def acquire_single_instance_lock(
meta = None
pid = int(meta["pid"]) if meta and "pid" in meta else None
+ port = (
+ int(meta["port"]) if meta and "port" in meta and meta["port"] else None
+ )
if pid is not None and _pid_alive(pid):
- raise SingleInstanceError(
- f"Jarvis laeuft bereits (pid={pid})."
- )
+ # Holder is alive. Is it actually FUNCTIONAL (serving its port)? A
+ # healthy instance, the own pid, or a holder with no recorded port is
+ # respected; only a live-but-non-serving lock-zombie is evicted.
+ if pid == os.getpid() or port is None or probe(port):
+ raise SingleInstanceError(f"Jarvis laeuft bereits (pid={pid}).")
+ with suppress(Exception):
+ from loguru import logger
- # Stale: Sidecar entfernen, Lock erneut versuchen. Das Lock-File auf
- # Filesystem-Ebene wegzuraeumen ist nicht noetig — filelock nutzt
- # fcntl/LockFileEx, d.h. sobald der Halter weg ist, ist das Lock frei.
- try:
+ logger.warning(
+ "Jarvis-Lock von einer LEBENDEN, aber nicht-reagierenden Instanz "
+ "belegt (pid={}, port={} antwortet nicht) — Lock-Zombie wird "
+ "beendet, damit dieser Start durchkommt.",
+ pid,
+ port,
+ )
+ if not killer(pid):
+ raise SingleInstanceError(
+ f"Jarvis-Lock von nicht-reagierender Instanz (pid={pid}) belegt; "
+ "konnte sie nicht beenden."
+ )
+ # fall through to the stale-reclaim path below (sidecar + retry acquire)
+
+ # Stale (toter Halter) ODER eben beendeter Zombie: Sidecar entfernen, Lock
+ # erneut versuchen. Das Lock-File auf Filesystem-Ebene wegzuraeumen ist nicht
+ # noetig — filelock nutzt fcntl/LockFileEx, d.h. sobald der Halter weg ist,
+ # ist das Lock frei. Nach einem Kill braucht Windows allerdings einen Moment,
+ # den Lock-Handle freizugeben — deshalb mehrere kurze Versuche.
+ with suppress(Exception):
mp.unlink(missing_ok=True)
- except Exception: # noqa: BLE001
- pass
- try:
- lock.acquire(timeout=max(timeout, 2.0))
- except Timeout as exc:
- raise SingleInstanceError(
- "Jarvis-Lock ist besetzt aber der Halter reagiert nicht."
- ) from exc
- return lock
+ last_exc: Timeout | None = None
+ deadline = time.monotonic() + 5.0
+ while True:
+ try:
+ lock.acquire(timeout=max(timeout, 2.0))
+ return lock
+ except Timeout as exc:
+ last_exc = exc
+ if time.monotonic() >= deadline:
+ raise SingleInstanceError(
+ "Jarvis-Lock ist besetzt aber der Halter reagiert nicht."
+ ) from last_exc
+ time.sleep(0.3)
# ---------------------------------------------------------------------------
@@ -478,9 +572,15 @@ class DesktopApp:
Event-Loop stoppen, Meta-Sidecar aufraeumen.
"""
- def __init__(self, cfg: JarvisConfig | None = None) -> None:
+ def __init__(
+ self, cfg: JarvisConfig | None = None, *, session_token: str | None = None
+ ) -> None:
self.cfg = cfg or load_config()
- self.session_token = _generate_session_token()
+ # The fast-boot launcher generates the token up front (on the main
+ # thread, before this backend-thread construction) so the same token is
+ # used for both the server's TokenAuth env (below) and the window's
+ # _inject_token. When not injected, generate our own (classic path).
+ self.session_token = session_token or _generate_session_token()
# ENV muss _vor_ dem Start des Backends gesetzt werden: uvicorn-Thread
# liest sie beim FastAPI-App-Build, um den TokenAuth-Guard zu prime.
os.environ[self.cfg.ui.auth_token_env] = self.session_token
@@ -495,6 +595,10 @@ class DesktopApp:
self._backend_thread: threading.Thread | None = None
self._backend_loop: asyncio.AbstractEventLoop | None = None
self._server: WebServer | None = None
+ # Serve-first bootstrap: binds the admin port before the heavy build so
+ # /api/health answers immediately and the window can appear (see
+ # _run_backend). The real app is delegated to it once built.
+ self._bootstrap: Any = None
self._window: Any = None
self._shutdown_done = False
self._tray: Any = None
@@ -527,9 +631,14 @@ class DesktopApp:
# ---- Backend-Thread ----------------------------------------------------
- def _run_backend(self) -> None:
+ def _run_backend(self, *, prebound: tuple[Any, Any] | None = None) -> None:
"""Eintrittspunkt des Backend-Threads.
+ ``prebound`` (fast-boot launcher path): ``(loop, bootstrap)`` already
+ created + bound BEFORE this heavy module was imported, so the port-bind
+ beat the import floor. When ``None`` (classic path), this creates the
+ loop and binds the bootstrap itself.
+
Erstellt einen dedizierten asyncio-Loop, startet den ``WebServer``
(``await server.start()``) und laesst den Loop ewig laufen bis
``stop()`` via :meth:`shutdown` durchgereicht wird.
@@ -550,20 +659,21 @@ class DesktopApp:
der Chat antwortet mit einer ehrlichen Setup-Anweisung statt mit
scripted Standard-Phrasen. User-Wunsch: kein "dummer Jarvis" ohne LLM.
"""
- from jarvis.brain.factory import build_default_brain
- from jarvis.core.events import (
- ErrorOccurred,
- MessageSent,
- ResponseGenerated,
- ShowWindowRequested,
- )
- from jarvis.mcp import state as mcp_state
- from jarvis.mcp.registry import MCPRegistry
- from jarvis.state.chat_store import ChatStore, default_chats_db_path
- from jarvis.state.supervisor import Supervisor
- from jarvis.ui.web.server import WebServer # lazy, vermeidet Circular
-
- loop = asyncio.new_event_loop()
+ # NOTE: the heavy imports (build_default_brain → the brain graph,
+ # WebServer → fastapi + every route schema, etc.) are DELIBERATELY NOT
+ # done here. They hold the GIL in long C-level blocks, which would
+ # starve the bootstrap loop and delay the UI shell. They are imported
+ # AFTER ``wait_shell_served`` below — i.e. once the window has painted —
+ # so the visible boot is never blocked by the import storm.
+ if prebound is not None:
+ # Fast-boot launcher path: the loop already exists and the bootstrap
+ # is already bound + serving (the launcher did that BEFORE importing
+ # this heavy module, so the bind beat the import floor). Reuse them.
+ loop, _prebound_bootstrap = prebound
+ self._backend_thread = threading.current_thread()
+ else:
+ loop = asyncio.new_event_loop()
+ _prebound_bootstrap = None
asyncio.set_event_loop(loop)
self._backend_loop = loop
@@ -576,6 +686,14 @@ class DesktopApp:
_bp = os.environ.get("JARVIS_BOOT_PROFILE") == "1"
_bp_t0 = time.perf_counter()
_bp_last = _bp_t0
+ # Expose the boot t0 so ``_start_speech_and_orb`` can emit an honest
+ # ``VOICE_READY_MS`` anchor (wake loop armed) on the SAME clock as
+ # ``BOOT_READY_MS`` (window appears). The gap between the two is the
+ # wake-boot cost the user actually feels ("the window is fast but
+ # talking to it takes forever"). Gated identically; production stdout
+ # unchanged.
+ self._bp_t0 = _bp_t0
+ self._bp = _bp
def _db_mark(_name: str) -> None:
nonlocal _bp_last
@@ -594,6 +712,30 @@ class DesktopApp:
flush=True,
)
+ # === Serve-first fast boot ===========================================
+ # Bind a tiny bootstrap server on the admin port NOW, before the heavy
+ # WebServer build, so ``/api/health`` answers 200 within ~150 ms. The
+ # desktop shell (``run`` -> ``_wait_for_backend``) gates the pywebview
+ # window on that health poll, so the window appears at bootstrap-bind
+ # time instead of after the full ``server.start()``. The real FastAPI
+ # app is built behind the bootstrap (below) and handed over via
+ # ``set_app``; requests that arrive while it warms are held then
+ # delegated (the "serve first, init behind" contract). Mirrors the
+ # proven headless path (commit 6379222e).
+ if _prebound_bootstrap is not None:
+ # Already bound + BOOT_READY emitted by the launcher — just adopt it.
+ bootstrap = _prebound_bootstrap
+ self._bootstrap = bootstrap
+ else:
+ from jarvis.ui.web.fast_bootstrap import FastBootstrap
+
+ bootstrap = FastBootstrap()
+ loop.run_until_complete(
+ bootstrap.serve("127.0.0.1", self.cfg.ui.admin_api_port)
+ )
+ self._bootstrap = bootstrap
+ _db_boot_ready() # /api/health is servable now → window can appear
+
# Fire the heavy OpenWakeWord/onnxruntime import NOW, in a daemon thread,
# BEFORE the WebServer + brain build + subsystem boot storm grab the
# Python import lock. The wake-critical Phase-A warm-up gates
@@ -604,8 +746,18 @@ class DesktopApp:
# finds openwakeword already in sys.modules. No-op on a headless VPS /
# JARVIS_VOICE=0; never slower than today (worst case Phase A waits on
# the same import it would have triggered itself).
- from jarvis.speech.warmup_prefetch import start_wake_import_prefetch
+ from jarvis.speech.warmup_prefetch import (
+ start_tts_import_prefetch,
+ start_wake_import_prefetch,
+ )
start_wake_import_prefetch()
+ # Same idea for the default TTS SDK (google-genai): the deferred warm-up
+ # loader gates honest readiness on the TTS client, and its dominant cost
+ # is the ``from google import genai`` import (~4-11 s when starved in the
+ # boot storm). Prefetch it now in a daemon thread (disjoint from the wake
+ # import — no torch/shield interaction) so ``_ensure_client`` later hits
+ # a warm sys.modules. No-op for non-Gemini TTS / JARVIS_VOICE=0.
+ start_tts_import_prefetch()
# Same idea for the audio-device settle: the BUG-014 guard
# (wait_for_stable_audio_devices) is a blocking ~1.5 s poll that gates
@@ -627,8 +779,39 @@ class DesktopApp:
loop.set_exception_handler(_log_unhandled_async)
+ # Let the window OPEN and PAINT (fetch /api/health, then index.html +
+ # the entry JS bundle from the bootstrap) BEFORE the GIL-heavy build
+ # starts. The WebServer ctor + its C-extension imports (fastapi, the
+ # route schemas) hold the GIL in long blocks; if they run first they
+ # starve the loop and the user stares at a blank window. Serving the
+ # shell first means the rendered UI is up before the warm-up storm.
+ # Bounded (2 s) so a headless run with no window never stalls the build.
+ if self._bootstrap is not None:
+ loop.run_until_complete(self._bootstrap.wait_shell_served(timeout=2.0))
+
+ # Heavy imports — done NOW (after the shell has painted) so their
+ # GIL-holding C-level work no longer starves the bootstrap loop while
+ # the window is still rendering. See the note at the top of _run_backend.
+ from jarvis.brain.factory import build_default_brain
+ from jarvis.core.events import (
+ ErrorOccurred,
+ MessageSent,
+ ResponseGenerated,
+ ShowWindowRequested,
+ )
+ from jarvis.mcp import state as mcp_state
+ from jarvis.mcp.registry import MCPRegistry
+ from jarvis.state.chat_store import ChatStore, default_chats_db_path
+ from jarvis.state.supervisor import Supervisor
+ from jarvis.ui.web.server import WebServer # lazy, vermeidet Circular
+
_db_mark("pre_webserver")
- server = WebServer(self.cfg)
+ # Build the FastAPI app + all routes (~1 s, CPU-bound) in a worker thread
+ # via the running loop, so the loop stays free to answer the bootstrap's
+ # /api/health while it builds — that is what lets the window appear at
+ # bind time rather than after the ~1 s ctor. WebServer.__init__ is
+ # loop-agnostic (pure construction + route mounting), so off-loop is safe.
+ server = loop.run_until_complete(asyncio.to_thread(WebServer, self.cfg))
self._server = server
_db_mark("webserver_ctor")
@@ -813,6 +996,106 @@ class DesktopApp:
pass
return brain_holder["brain"]
+ desktop_cfg = self.cfg
+
+ class _DeferredVoiceBrain:
+ """Callable brain facade that lets the wake listener boot first.
+
+ The voice pipeline only needs a callable brain once a user utterance
+ has been captured. Wake detection itself must not wait for the
+ BrainManager build. This proxy waits at turn dispatch time and
+ delegates to the real shared brain as soon as it is ready.
+ """
+
+ def __init__(self) -> None:
+ self._pending_skill_notes: list[
+ tuple[tuple[Any, ...], dict[str, Any]]
+ ] = []
+
+ @property
+ def active_provider(self) -> str:
+ brain = brain_holder["brain"]
+ return str(getattr(brain, "active_provider", "starting"))
+
+ @property
+ def reply_language(self) -> str:
+ brain = brain_holder["brain"]
+ if brain is not None:
+ return str(getattr(brain, "reply_language", "auto"))
+ return str(
+ getattr(getattr(desktop_cfg, "brain", None), "reply_language", "auto")
+ )
+
+ @property
+ def conversation_language(self) -> str:
+ brain = brain_holder["brain"]
+ return str(getattr(brain, "conversation_language", "")) if brain else ""
+
+ def _brain_unavailable_message(self) -> str:
+ detail = brain_holder["error"] or "BrainManager not initialized"
+ return f"Brain unavailable: {detail}"
+
+ def _drain_skill_notes(self, brain: Any) -> None:
+ note = getattr(brain, "note_skill_trigger", None)
+ if not callable(note) or not self._pending_skill_notes:
+ return
+ pending = list(self._pending_skill_notes)
+ self._pending_skill_notes.clear()
+ for args, kwargs in pending:
+ note(*args, **kwargs)
+
+ async def _resolve(self) -> Any | None:
+ brain = await _await_brain_ready()
+ if brain is not None:
+ self._drain_skill_notes(brain)
+ return brain
+
+ def note_skill_trigger(self, *args: Any, **kwargs: Any) -> None:
+ brain = brain_holder["brain"]
+ note = getattr(brain, "note_skill_trigger", None)
+ if callable(note):
+ note(*args, **kwargs)
+ return
+ if len(self._pending_skill_notes) < 16:
+ self._pending_skill_notes.append((args, dict(kwargs)))
+
+ async def __call__(self, text: str) -> str:
+ brain = await self._resolve()
+ if brain is None:
+ return self._brain_unavailable_message()
+ return await brain(text)
+
+ async def generate(self, text: str, *args: Any, **kwargs: Any) -> str:
+ brain = await self._resolve()
+ if brain is None:
+ return self._brain_unavailable_message()
+ generate = getattr(brain, "generate", None)
+ if callable(generate):
+ return await generate(text, *args, **kwargs)
+ return await brain(text)
+
+ async def generate_stream(self, text: str, **kwargs: Any):
+ brain = await self._resolve()
+ if brain is None:
+ yield self._brain_unavailable_message()
+ return
+ stream = getattr(brain, "generate_stream", None)
+ if not callable(stream):
+ yield await self.generate(text)
+ return
+ call_kwargs = dict(kwargs)
+ try:
+ iterator = stream(text, **call_kwargs)
+ except TypeError:
+ call_kwargs.pop("allow_voice_confirm", None)
+ try:
+ iterator = stream(text, **call_kwargs)
+ except TypeError:
+ call_kwargs.pop("on_progress", None)
+ iterator = stream(text, **call_kwargs)
+ async for chunk in iterator:
+ yield chunk
+
async def _on_user_message(evt: MessageSent) -> None:
"""Brain-Dispatcher: jedes user-turned MessageSent triggert generate.
@@ -1215,13 +1498,19 @@ class DesktopApp:
)
try:
- loop.run_until_complete(server.start())
- _db_mark("server_start")
- # Erst nach erfolgreichem start() ist der Port wirklich belegt.
- _write_meta(self.cfg.ui.admin_api_port, os.getpid())
- # The backend is now serving /api/health — the desktop shell's
- # ``_wait_for_backend`` poll can succeed and the window be created.
- _db_boot_ready()
+ # The bootstrap already owns the listening socket, so build the real
+ # app WITHOUT starting its own uvicorn, then hand it to the bootstrap
+ # which delegates held + new requests to it.
+ # Serve-WAKE-first ordering (2026-06-27): the heavy ``server.start()``
+ # _init_* chain (mission stack incl. git-worktree-prune, wiki,
+ # sessions, tasks, channels) is NO LONGER awaited here before voice
+ # starts. It is moved into ``_heavy_backend_bg`` below so it runs
+ # BEHIND the live Jarvis-Bar / wake listener. ``_start_speech_and_orb``
+ # needs only ``server.bus`` + ``server.app.state`` (skill_registry,
+ # set in the WebServer ctor — already done above) + ``supervisor`` +
+ # the deferred brain proxy — NONE of that chain. The user-perceived
+ # "ready to talk to Jarvis" gate is the wake listener, not the full
+ # backend, so it must not wait ~15-20 s for subsystems it never uses.
async def _start_overlay_bg() -> None:
try:
# Phase 9.8: Overlay-Subprocess starten wenn [overlay].enabled=true.
@@ -1245,28 +1534,87 @@ class DesktopApp:
"Overlay-Bootstrap fehlgeschlagen."
)
- loop.create_task(_start_overlay_bg(), name="overlay-bootstrap")
- loop.create_task(_build_brain_bg(), name="brain-build")
- # MCP-Autostart als Fire-and-Forget-Task — blockt Backend-Ready nicht.
- loop.create_task(_start_enabled_mcps())
- loop.create_task(_bootstrap_workflows(), name="workflow-bootstrap")
- loop.create_task(_bootstrap_conductor(), name="conductor-bootstrap")
-
- # Speech-Pipeline + Orb-Overlay: after the backend is serving. This
- # used to run synchronously before ``run_forever()``, which meant the
- # already-started uvicorn task could not answer ``/api/health`` while
- # voice/overlay imports and setup ran. The desktop shell waits on
- # that health probe before creating the window, so any slow wake/GUI
- # warm-up inflated visible app startup.
- def _start_desktop_post_ready_services() -> None:
- brain = brain_holder["brain"]
- if brain is None and not brain_ready.is_set():
- loop.call_later(0.25, _start_desktop_post_ready_services)
+ def _log_speech_and_orb_done(task: asyncio.Task) -> None:
+ if task.cancelled():
return
- self._start_speech_and_orb(loop, server.bus, supervisor, brain, server)
- self._start_virtual_cursor()
+ exc = task.exception()
+ if exc is not None:
+ from loguru import logger as _slog
+ _slog.opt(exception=exc).error(
+ "Voice/orb startup task crashed."
+ )
+
+ # Wake-model GIL-priority gate: set by ``_start_speech_and_orb`` once
+ # the (light base/cpu) wake model has finished loading. The heavy
+ # backend (the GIL-heavy brain + MCP build) waits on this so the wake
+ # model load is NOT starved by the import storm — it loads in ~3 s
+ # isolated instead of ~8.8 s racing brain/mcp. Matches the user's
+ # "window -> Jarvis-Bar -> rest" order.
+ self._wake_model_loaded = asyncio.Event()
+
+ # === 1) Jarvis-Bar / wake listener FIRST ========================
+ # The user's "Jarvis is ready to talk to" gate. Scheduled before the
+ # heavy backend so the wake word arms within ~1 s of the window
+ # appearing, not after the whole _init_* chain. Wake detection only
+ # needs a callable for later turn dispatch, so the deferred proxy
+ # waits for the real shared brain at answer time instead of keeping
+ # the wake word deaf while the app is visibly open.
+ speech_task = loop.create_task(
+ self._start_speech_and_orb(
+ loop, server.bus, supervisor, _DeferredVoiceBrain(), server
+ ),
+ name="speech-and-orb",
+ )
+ speech_task.add_done_callback(_log_speech_and_orb_done)
+ loop.create_task(_start_overlay_bg(), name="overlay-bootstrap")
- loop.call_later(0.25, _start_desktop_post_ready_services)
+ # === 2) Everything else, BEHIND the live wake listener ==========
+ # The heavy backend keeps its original internal order (server.start()
+ # before brain/mcp/workflows/conductor) so no task that depended on a
+ # fully-initialised app.state regresses — only the wake path was
+ # pulled ahead of it. set_app + _write_meta gate API delegation
+ # (serve-first), which Voice does not need.
+ async def _heavy_backend_bg() -> None:
+ # Wake-model CPU/disk priority: hold the ENTIRE heavy backend
+ # (server.start's mission/wiki/session/channel init + git-prune,
+ # then the brain + MCP build) until the wake model has loaded.
+ # Measured: the light base/cpu wake model loads ~4 s isolated but
+ # ~8 s when it races this boot storm for CPU/disk — gating the
+ # whole storm behind wake roughly halves the custom-wake hear-
+ # ready time. This matches the user's explicit "window ->
+ # Jarvis-Bar -> rest" order: the bootstrap already serves the
+ # static UI shell, so only the API DATA (chat history, missions,
+ # wiki) and background services land a few seconds later. Bounded
+ # so a stuck/absent wake load never blocks the backend forever.
+ try:
+ await asyncio.wait_for(
+ self._wake_model_loaded.wait(), timeout=12.0
+ )
+ except (TimeoutError, asyncio.TimeoutError):
+ from loguru import logger as _slog
+ _slog.info(
+ "Heavy backend: wake-model gate timed out (12 s) — "
+ "starting the backend anyway."
+ )
+ try:
+ await server.start(start_serving=False)
+ bootstrap.set_app(server.app)
+ _db_mark("server_start")
+ # Erst nach erfolgreichem start() ist der Port wirklich belegt.
+ _write_meta(self.cfg.ui.admin_api_port, os.getpid())
+ except Exception as exc: # noqa: BLE001 — never kill the backend loop
+ from loguru import logger as _slog
+ _slog.opt(exception=exc).error(
+ "Heavy backend init (server.start) failed."
+ )
+ loop.create_task(_build_brain_bg(), name="brain-build")
+ # MCP-Autostart als Fire-and-Forget-Task — blockt Backend-Ready nicht.
+ loop.create_task(_start_enabled_mcps())
+ loop.create_task(_bootstrap_workflows(), name="workflow-bootstrap")
+ loop.create_task(_bootstrap_conductor(), name="conductor-bootstrap")
+
+ loop.create_task(_heavy_backend_bg(), name="heavy-backend")
+ loop.call_soon(self._start_virtual_cursor)
loop.run_forever()
finally:
try:
@@ -1352,35 +1700,44 @@ class DesktopApp:
logger.opt(exception=exc).warning("Virtual mouse overlay not startable")
self._virtual_cursor = None
- def _build_overlay_surface(self, style: str, *, boot: bool = False):
+ def _build_overlay_surface(self, style: str, *, start_hidden: bool = False):
"""Construct (and start) the overlay surface for a display style.
Returns a ``NullOverlay`` for ``"none"`` (no Tk window, no-op surface),
- a started ``WhisperBarOverlay`` for ``"whisper_bar"``, or a started
+ a started ``JarvisBarOverlay`` for ``"jarvis_bar"``, or a started
mascot ``OrbOverlay`` for anything else. Shared by boot wiring and the
live ``swap_overlay`` path so the two never drift.
- ``boot=True`` (only the first-boot call) builds the persistent bar
- WITHDRAWN; the boot wiring then schedules its reveal on
- ``VoiceBootStatus(ready=True)``. A non-boot caller must leave ``boot``
- False so the bar maps immediately (it has no reveal task to wait on).
+ A persistent ``JarvisBarOverlay`` maps its window immediately, so the
+ bar is visible as soon as it is constructed — at boot AND on a live
+ ``swap_overlay``. Its boot visibility is deliberately decoupled from the
+ voice warm-up / wake path (the sidebar "Voice starting…" badge carries
+ readiness instead). A non-persistent bar / the mascot still starts
+ withdrawn and pops on a real session.
"""
if style == "none":
- from jarvis.ui.whisperbar import NullOverlay
+ from jarvis.ui.jarvisbar import NullOverlay
return NullOverlay()
- if style == "whisper_bar":
- from jarvis.ui.whisperbar import WhisperBarOverlay
-
- # start_hidden only at boot: a persistent bar must NOT map its window
- # before the speech pipeline can hear the user — the OrbBusBridge
- # reveals it on VoiceBootStatus(ready=True). A runtime rebuild
- # (boot=False) shows immediately; the non-persistent bar starts
- # hidden regardless (it pops on a session).
- surface = WhisperBarOverlay(
+ if style == "jarvis_bar":
+ from jarvis.ui.jarvisbar import JarvisBarOverlay
+
+ # Synchronized appearance (2026-06-29): when ``start_hidden`` is set,
+ # the persistent bar starts WITHDRAWN and is revealed only on the
+ # honest ``VoiceBootStatus(ready=True)`` (via
+ # ``reveal_bar_when_voice_ready``), so the bar appears AT THE SAME
+ # MOMENT the voice stack is genuinely ready — no more "bar shows at
+ # boot, then 'ready' a few seconds later" desync. An earlier attempt
+ # at this left the bar hidden until the first wake word because
+ # ready=True fired unreliably/too early on the fast-boot path; that
+ # root cause is fixed (ready now fires once, after the deferred
+ # loaders bring up wake+VAD+TTS), and a 30 s reveal timeout backstops
+ # it so the bar can never be stuck hidden. A non-persistent bar starts
+ # withdrawn regardless (it pops on a session).
+ surface = JarvisBarOverlay(
persistent=self.cfg.ui.bar_persistent,
accent=self.cfg.ui.bar_accent,
- start_hidden=boot,
+ start_hidden=start_hidden,
)
else: # "mascot" (and any legacy style value)
from ui.orb.overlay import OrbOverlay
@@ -1452,8 +1809,8 @@ class DesktopApp:
"""
from loguru import logger
- style = (style or "whisper_bar").strip()
- if style not in ("whisper_bar", "mascot", "none"):
+ style = (style or "jarvis_bar").strip()
+ if style not in ("jarvis_bar", "mascot", "none"):
return {"ok": False, "applied_live": False, "style": style}
bridge = getattr(self, "_bridge", None)
if bridge is None:
@@ -1468,7 +1825,7 @@ class DesktopApp:
if style == "none":
new = cache.get("none")
if new is None:
- from jarvis.ui.whisperbar import NullOverlay # no Tk root
+ from jarvis.ui.jarvisbar import NullOverlay # no Tk root
new = NullOverlay()
cache["none"] = new
@@ -1492,7 +1849,7 @@ class DesktopApp:
except Exception: # noqa: BLE001
logger.debug("old overlay hide failed", exc_info=True)
try:
- if style == "whisper_bar" and self.cfg.ui.bar_persistent:
+ if style == "jarvis_bar" and self.cfg.ui.bar_persistent:
new.show("idle")
except Exception: # noqa: BLE001
logger.debug("post-swap show failed", exc_info=True)
@@ -1584,7 +1941,7 @@ class DesktopApp:
)
return True
- def _start_speech_and_orb(
+ async def _start_speech_and_orb(
self,
loop: asyncio.AbstractEventLoop,
bus: Any,
@@ -1612,14 +1969,14 @@ class DesktopApp:
# On-screen overlay in its own Tk daemon thread — the bus bridge reacts
# to SystemStateChanged and drives whichever surface is selected.
- # Style is chosen by [ui].orb_style: "whisper_bar" (slim default),
+ # Style is chosen by [ui].orb_style: "jarvis_bar" (slim default),
# "mascot" (ghost orb), or "none". Both real surfaces share OrbBusBridge.
try:
from loguru import logger
from jarvis.platform.probes import has_overlay
- orb_style = self.cfg.ui.orb_style or "whisper_bar"
+ orb_style = self.cfg.ui.orb_style or "jarvis_bar"
overlay_ok = has_overlay()
if not overlay_ok:
@@ -1636,21 +1993,25 @@ class DesktopApp:
from ui.orb.bus_bridge import OrbBusBridge
# NullOverlay for "none" still gets a bridge, so a live switch to
- # bar/mascot works without a restart. boot=True builds the
- # persistent bar withdrawn — revealed below on voice-ready.
- surface = self._build_overlay_surface(orb_style, boot=True)
+ # bar/mascot works without a restart. Synchronized appearance:
+ # the persistent bar starts WITHDRAWN (start_hidden=True) and is
+ # revealed only on the honest VoiceBootStatus(ready=True), so it
+ # appears exactly when the voice stack is genuinely ready — no
+ # "bar at boot, ready a few seconds later" desync.
+ surface = self._build_overlay_surface(orb_style, start_hidden=True)
hide_on_idle = (
(not self.cfg.ui.bar_persistent)
- if orb_style == "whisper_bar"
+ if orb_style == "jarvis_bar"
else True
)
bridge = OrbBusBridge(bus=bus, orb=surface, hide_on_idle=hide_on_idle)
bridge.attach()
- # Reveal the (start-hidden) persistent bar only once voice is
- # ready to listen — gated on VoiceBootStatus(ready=True), with a
- # bounded fallback so a voice-offline host still gets its bar.
- # loop.create_task works before run_forever (it just schedules);
- # the boot surface starts withdrawn, so this never flickers.
+ # Visibility gate: the persistent bar started withdrawn (above),
+ # so this task is what actually SHOWS it — it waits for
+ # VoiceBootStatus(ready=True) (full stack: wake+VAD+TTS) and then
+ # maps + lifts the idle pill. Bounded by a 30 s timeout fallback
+ # so the bar can never be stuck hidden. A non-persistent bar / the
+ # mascot is left untouched (it pops on a real session).
loop.create_task(
bridge.reveal_bar_when_voice_ready(),
name="overlay-boot-reveal",
@@ -1758,7 +2119,6 @@ class DesktopApp:
# Wenn brain ein MockBrain ist (Fallback), funktioniert Voice-TTS auch,
# aber ohne echten LLM-Output → erkennbar an scripted Replies.
try:
- from jarvis.plugins.stt.fwhisper import FasterWhisperProvider
from jarvis.plugins.tts import build_tts_from_config
from jarvis.plugins.wake.openwakeword_provider import (
PRODUCTION_WAKE_THRESHOLD,
@@ -1805,6 +2165,16 @@ class DesktopApp:
# build it when the plan asks for it. See
# docs/local-wakeword/{RESEARCH-AND-DESIGN,CUSTOM-WAKE-WORD-DESIGN}.md.
stt = None
+ # Progressive wake-model state: when we build the LIGHT base/cpu wake
+ # model (fast_first), remember the phrase so a background task can
+ # hot-swap in the heavier turbo/cuda model once the pipeline is live.
+ wake_phrase = None
+ _wake_progressive_upgrade = False
+ _t_build0 = time.perf_counter()
+ # Concurrency handle for the heavy wake-model build (below). It is
+ # started in a worker thread and joined just before the pipeline ctor
+ # so the TTS + ack-brain builds overlap it instead of waiting it out.
+ wake_task: "asyncio.Task | None" = None
if self.cfg.trigger.heavy_local_whisper or wake_plan.needs_local_whisper:
# The local wake-match / live-preview Whisper — a SMALL model on
# CPU (cfg.stt.wake_*), not the heavy utterance model on the GPU.
@@ -1813,6 +2183,12 @@ class DesktopApp:
# latency-tolerant and does not need the big model.
from jarvis.plugins.stt import build_wake_whisper
+ # Tell the boot-storm housekeeping (deferred registry disk scans)
+ # that a local wake model is loading, so it yields CPU/disk to the
+ # wake-model load first (no-op for headless / voice-off).
+ from jarvis.core import runtime_refs as _rr_wake
+ _rr_wake.signal_wake_model_expected()
+
# Seed the wake Whisper's prompt with the custom phrase ONLY on
# the stt_match path (a custom name with no OWW model). The
# heavy_local_whisper backstop for "Hey Jarvis" keeps its OWW
@@ -1821,10 +2197,36 @@ class DesktopApp:
wake_phrase = (
wake_plan.phrase if wake_plan.needs_local_whisper else None
)
- stt = build_wake_whisper(
- self.cfg.stt, language=stt_language, wake_phrase=wake_phrase
+ # Build the local wake-Whisper OFF the event loop: it probes CUDA
+ # availability, whose first-call context init JIT-compiles for
+ # ~30-60 s on a Blackwell GPU (cold cache). Offloading keeps the
+ # backend responsive — a desktop app must never freeze its UI
+ # while a subsystem warms up. The persisted probe cache
+ # (jarvis.plugins.stt._wake_cuda_available) makes this near-instant
+ # on every boot after the first.
+ # Start the wake-model build in a worker thread but DON'T block
+ # on it here — the TTS + ack-brain builds below run on the loop
+ # thread WHILE it loads (the wake C-extension / CUDA load releases
+ # the GIL), overlapping their cost instead of paying it after the
+ # ~3-5 s wake build. Joined right before the pipeline ctor. The
+ # LIGHT base/cpu model is built now (hear-ready in ~3 s, no CUDA
+ # JIT); the turbo/cuda hot-swap is armed in the background after
+ # the pipeline is live (see ``_upgrade_wake_model_bg``).
+ wake_task = asyncio.create_task(
+ asyncio.to_thread(
+ build_wake_whisper,
+ self.cfg.stt,
+ language=stt_language,
+ wake_phrase=wake_phrase,
+ fast_first=True,
+ ),
+ name="voice-build-wake-model",
)
+ _wake_progressive_upgrade = True
+ # TTS + ack-brain build here, on the loop thread, overlapping the
+ # wake-model build started above.
tts = build_tts_from_config(self.cfg.tts)
+ _t_tts = time.perf_counter()
# SpeechPipeline.brain_callback braucht Callable[[str], Awaitable[str]].
# BrainManager und Echo-/Gemini-Fallback erfüllen das via __call__.
# MockBrain erfüllt es nicht (hat nur respond()) → eigener Voice-Brain.
@@ -1850,6 +2252,20 @@ class DesktopApp:
# None. Threaded into the pipeline below.
from jarvis.brain.factory import build_ack_brain as _bab
voice_ack_brain = _bab(self.cfg)
+ _t_ack = time.perf_counter()
+ # Join the wake-model build started above (it loaded in its worker
+ # thread WHILE the TTS + ack-brain were built here). On failure
+ # re-raise to the outer handler — voice degrades exactly as the
+ # previous inline ``await`` did — and cancel the task so the worker
+ # thread's result is never left orphaned.
+ if wake_task is not None:
+ try:
+ stt = await wake_task
+ except BaseException:
+ if not wake_task.done():
+ wake_task.cancel()
+ raise
+ _t_stt = time.perf_counter()
_call_hk, _ptt_hk = self.cfg.trigger.resolve_hotkeys()
pipeline = SpeechPipeline(
call_hotkeys=_call_hk,
@@ -1931,6 +2347,24 @@ class DesktopApp:
# phrase matcher for the verifier + rolling-whisper.
wake_plan=wake_plan,
)
+ _t_ctor = time.perf_counter()
+ # Targeted boot-timing breakdown so the log shows exactly which voice
+ # build step costs what (the wake-Whisper CUDA probe was the hidden
+ # ~60 s "VOICE STARTING…" stall before the persisted probe cache).
+ from loguru import logger as _vlog
+ # Stamps now reflect the OVERLAPPED build: TTS + ack-brain run on the
+ # loop thread while the wake model loads in its worker thread, so
+ # ``wake_join`` is only the wake time NOT already hidden behind them
+ # (≈0 when fully overlapped). total is wall-clock for the whole build.
+ _vlog.info(
+ "Voice setup build timings (ms): tts={:.0f} ack_brain={:.0f} "
+ "wake_join={:.0f} pipeline_ctor={:.0f} total={:.0f}",
+ (_t_tts - _t_build0) * 1000.0,
+ (_t_ack - _t_tts) * 1000.0,
+ (_t_stt - _t_ack) * 1000.0,
+ (_t_ctor - _t_stt) * 1000.0,
+ (_t_ctor - _t_build0) * 1000.0,
+ )
# Pipeline-Referenz fuer Live-Provider-Switches (TTS) auf app.state
# legen — der /api/tts/switch-Endpoint baut bei einem UI-Wechsel
# einen neuen TTS-Provider und ruft pipeline.set_tts() auf, ohne
@@ -1968,7 +2402,119 @@ class DesktopApp:
)
self._pipeline_task.add_done_callback(_on_pipeline_done)
- logger.info("Speech-Pipeline gestartet — Wake: 'Hey Jarvis'.")
+ # Log the ACTUAL configured wake word, not a hardcoded "Hey Jarvis"
+ # (the custom phrase, e.g. "Luca", or the openWakeWord keyword).
+ logger.info(
+ "Speech-Pipeline gestartet — Wake: {!r}.",
+ wake_plan.phrase or wake_plan.oww_keyword or "?",
+ )
+ if getattr(self, "_bp", False):
+ # Honest wake-armed anchor on the same clock as BOOT_READY_MS.
+ print(
+ f"VOICE_READY_MS={(time.perf_counter() - self._bp_t0) * 1000.0:.1f}",
+ flush=True,
+ )
+
+ # Wake-model GIL-priority gate: signal the heavy backend (brain/mcp)
+ # to resume as soon as the LIGHT base/cpu wake model has loaded — or
+ # immediately if there is no local wake model (e.g. the OWW path), so
+ # the backend never waits needlessly.
+ def _wake_model_is_loaded() -> bool:
+ ww = getattr(pipeline, "_whisper_wake", None)
+ base_stt = getattr(ww, "_stt", None) if ww is not None else stt
+ return (
+ base_stt is not None
+ and getattr(base_stt, "_model", None) is not None
+ )
+
+ from jarvis.core import runtime_refs as _rr_ready
+ if stt is None:
+ self._wake_model_loaded.set()
+ _rr_ready.signal_wake_model_ready()
+ else:
+ async def _signal_wake_model_loaded() -> None:
+ for _ in range(40): # ~20 s cap, then release the gate anyway
+ if _wake_model_is_loaded():
+ break
+ await asyncio.sleep(0.5)
+ self._wake_model_loaded.set()
+ # Release the boot-storm housekeeping gate too.
+ _rr_ready.signal_wake_model_ready()
+
+ loop.create_task(
+ _signal_wake_model_loaded(), name="wake-model-ready-signal"
+ )
+
+ # Progressive wake model: the pipeline is now live on the LIGHT
+ # base/cpu wake model (hear-ready fast, no CUDA JIT). Hot-swap the
+ # heavier turbo/cuda model in the BACKGROUND for faster steady-state
+ # inference, so a custom phrase comes up fast AND stays accurate. No-op
+ # on a CPU-only host (the build returns base again). Any failure leaves
+ # the working base/cpu model in place — wake never breaks.
+ if _wake_progressive_upgrade:
+ _wake_phrase_for_upgrade = wake_phrase
+ _stt_lang_for_upgrade = stt_language
+
+ async def _upgrade_wake_model_bg() -> None:
+ try:
+ from jarvis.plugins.stt import (
+ build_wake_whisper as _bww,
+ )
+
+ ww = getattr(pipeline, "_whisper_wake", None)
+ # Wait until the base/cpu wake model is loaded (the same
+ # gate the heavy backend uses) BEFORE loading turbo —
+ # loading turbo in parallel races the base load on the
+ # GIL/CUDA-init lock and doubled it (~3 s -> ~20 s,
+ # measured 2026-06-27). Wake is already live on base while
+ # we wait, so this costs nothing user-visible.
+ try:
+ await asyncio.wait_for(
+ self._wake_model_loaded.wait(), timeout=120.0
+ )
+ except (TimeoutError, asyncio.TimeoutError):
+ pass
+
+ turbo = await asyncio.to_thread(
+ _bww,
+ self.cfg.stt,
+ language=_stt_lang_for_upgrade,
+ wake_phrase=_wake_phrase_for_upgrade,
+ fast_first=False,
+ )
+ if getattr(turbo, "_model_name", "base") == "base":
+ return # no GPU upgrade available — keep base/cpu
+ # WARM-UP, not just load: ``warm_up`` runs one real
+ # inference so the turbo/cuda kernels are primed BEFORE
+ # the ref swap below makes it the live wake model. Without
+ # this the first "Hey Jarvis" after the swap hits a cold
+ # CUDA inference (kernel JIT / cuDNN search, several
+ # seconds) and is swallowed by the rolling-window wake
+ # loop — the same first-wake-missed bug the boot pre-warm
+ # fixes (forensic 2026-06-28). Falls back to a plain load
+ # for any STT without the prime hook.
+ _turbo_prime = getattr(turbo, "warm_up", None)
+ await asyncio.to_thread(
+ _turbo_prime
+ if callable(_turbo_prime)
+ else turbo._ensure_model
+ )
+ if ww is not None:
+ # Atomic ref swap (GIL); the next transcribe uses turbo.
+ ww._stt = turbo
+ logger.info(
+ "Wake-model upgraded base/cpu -> turbo/cuda "
+ "(background hot-swap; faster steady-state inference)."
+ )
+ except Exception as exc: # noqa: BLE001 — base/cpu stays; wake never breaks
+ logger.warning(
+ "Wake-model turbo upgrade failed (staying on base/cpu): %s",
+ exc,
+ )
+
+ self._wake_upgrade_task = loop.create_task(
+ _upgrade_wake_model_bg(), name="wake-model-turbo-upgrade"
+ )
except Exception as exc: # noqa: BLE001
from loguru import logger
# FAIL-LOUD (2026-05-28 "Hey Jarvis silently dead" incident): a
@@ -2024,6 +2570,8 @@ class DesktopApp:
desktop._window.restore()
desktop._window_visible = True
_bring_window_to_front_by_title(WINDOW_TITLE)
+ # Restore the persistent bar if a prior minimise cleared it.
+ desktop._restore_overlay_for_visible_window()
return {"ok": True, "focused": True}
except Exception as exc: # noqa: BLE001
return {"ok": False, "reason": f"{type(exc).__name__}: {exc}"}
@@ -2087,15 +2635,25 @@ class DesktopApp:
# ---- Main-Entry --------------------------------------------------------
def run(self) -> int:
- """Blockt bis der User das Fenster schliesst. Rueckgabe = Exit-Code."""
- import webview # type: ignore[import-not-found]
+ """Blockt bis der User das Fenster schliesst. Rueckgabe = Exit-Code.
+ Classic boot: start the backend thread here, then run the window. The
+ fast-boot launcher path starts the backend thread itself (so the
+ bootstrap binds BEFORE the heavy imports) and calls ``run_window_only``
+ directly — both share the identical window code below.
+ """
self._backend_thread = threading.Thread(
target=self._run_backend,
name="jarvis-backend",
daemon=True,
)
self._backend_thread.start()
+ return self.run_window_only()
+
+ def run_window_only(self) -> int:
+ """The main-thread pywebview window. Assumes the backend thread is
+ already running (started by :meth:`run` or the fast-boot launcher)."""
+ import webview # type: ignore[import-not-found]
if not self._wait_for_backend():
sys.stderr.write("Backend startete nicht in 45s — Abbruch.\n")
@@ -2115,17 +2673,9 @@ class DesktopApp:
# Close-Button = Minimize-to-Tray (User-Entscheidung 2026-04-20).
# `closing`-Callback gibt False zurueck → pywebview bricht Destroy ab.
- def _on_closing() -> bool:
- if self._user_requested_quit:
- return True
- try:
- self._window.hide()
- self._window_visible = False
- except Exception: # noqa: BLE001
- return True
- return False
-
- self._window.events.closing += _on_closing
+ # Extracted to a method so the tray-minimise + overlay-clear contract
+ # is unit-testable (test_desktop_minimize_to_tray_overlay.py).
+ self._window.events.closing += self._on_window_closing
# Tray + Bridge zum Main-Thread-Window starten. Daemon-Thread, damit
# er beim Hauptprogramm-Exit nicht am Leben bleibt.
@@ -2170,25 +2720,46 @@ class DesktopApp:
from jarvis.ui.icon_utils import (
project_icon_path,
set_window_icon_by_title,
+ set_window_icon_for_pid,
)
ico = project_icon_path()
if not ico.is_file():
return
+ own_pid = os.getpid()
+
def _poll() -> None:
from loguru import logger
- deadline = time.monotonic() + 5.0
+ # 30s window (was 5s): a voice-loaded boot delays the WebView2 host
+ # window past the old 5s deadline, so the icon was never set and the
+ # titlebar kept the pythonw.exe Python logo (forensic 2026-06-28).
+ # Match by title OR by our own process id (the WebView2 host title is
+ # applied late, so an exact-title FindWindowW alone is racy), and keep
+ # re-applying for a few seconds after the first success — WebView2
+ # re-assigns the process icon once its control finishes initialising,
+ # so a single WM_SETICON does not stick.
+ deadline = time.monotonic() + 30.0
+ first_set_at: float | None = None
while time.monotonic() < deadline:
- if set_window_icon_by_title(WINDOW_TITLE, ico, quiet=True):
- logger.debug("Taskbar-Icon fruehzeitig gesetzt.")
- return
- time.sleep(0.05)
- logger.warning(
- "Taskbar-Icon-Setter Timeout — Fenster '{}' nicht gefunden.",
- WINDOW_TITLE,
- )
+ ok = set_window_icon_by_title(WINDOW_TITLE, ico, quiet=True)
+ if not ok:
+ ok = set_window_icon_for_pid(own_pid, ico)
+ if ok:
+ if first_set_at is None:
+ first_set_at = time.monotonic()
+ logger.debug(
+ "Taskbar-Icon gesetzt; re-arming gegen WebView2-Override."
+ )
+ elif time.monotonic() - first_set_at > 8.0:
+ return
+ time.sleep(0.3)
+ if first_set_at is None:
+ logger.warning(
+ "Taskbar-Icon-Setter Timeout — Fenster '{}' nicht gefunden.",
+ WINDOW_TITLE,
+ )
threading.Thread(
target=_poll, name="jarvis-icon-setter", daemon=True
@@ -2257,6 +2828,8 @@ class DesktopApp:
self._window_visible = True
_bring_window_to_front_by_title(WINDOW_TITLE)
self._reload_window_if_stale()
+ # Bring the persistent bar back too (it was cleared on minimise).
+ self._restore_overlay_for_visible_window()
except Exception: # noqa: BLE001
pass
@@ -2285,6 +2858,94 @@ class DesktopApp:
except Exception: # noqa: BLE001
pass
+ # ---- Window close (X) = minimise to tray + clear overlay ---------------
+
+ def _on_window_closing(self) -> bool:
+ """pywebview ``closing`` callback: the X minimises to tray, not quit.
+
+ Returns ``True`` to allow the destroy — a genuine tray "Quit", where the
+ real :meth:`shutdown` tears everything down — and ``False`` to veto it
+ and hide the window instead. On a minimise we ALSO take the overlay bar
+ off the screen so the desktop is actually clean; it returns on the next
+ window-show or voice session.
+ """
+ if self._user_requested_quit:
+ return True
+ try:
+ self._window.hide()
+ self._window_visible = False
+ self._suppress_overlay_for_hidden_window()
+ except Exception: # noqa: BLE001
+ return True
+ return False
+
+ def _suppress_overlay_for_hidden_window(self) -> None:
+ """Take the overlay bar off the screen while the window is minimised.
+
+ The persistent bar would otherwise stay on screen after the X (the app
+ keeps running in the tray for voice), which reads as "the bar won't
+ close". Drive the bar into the non-persistent (hide-at-idle) regime and
+ hide it now, WITHOUT mutating the user's saved ``bar_persistent``
+ preference. Voice activity still surfaces it (the bridge shows it on a
+ session and hides it again at idle); reopening the window restores the
+ configured regime via :meth:`_restore_overlay_for_visible_window`.
+ """
+ bar = getattr(self, "_orb", None)
+ bridge = getattr(self, "_bridge", None)
+ if bar is None or bridge is None:
+ return
+ try:
+ if getattr(bridge, "_boot_reveal_done", True) is False:
+ # The persistent jarvis bar starts withdrawn at boot and is
+ # revealed once voice is ready. Before that first reveal there
+ # is no visible surface to suppress; flipping hide-on-idle here
+ # would turn the one-shot startup reveal into a no-op.
+ return
+ bridge._hide_on_idle = True
+ if hasattr(bar, "_persistent"):
+ bar._persistent = False
+ hide = getattr(bar, "hide", None)
+ if callable(hide):
+ hide()
+ except Exception: # noqa: BLE001
+ from loguru import logger
+
+ logger.debug(
+ "overlay suppress for hidden window failed", exc_info=True
+ )
+
+ def _restore_overlay_for_visible_window(self) -> None:
+ """Reverse of :meth:`_suppress_overlay_for_hidden_window`.
+
+ Put the bar back into the user's configured persistence regime when the
+ window is shown again (tray click / focus / overlay right-click). A
+ persistent user gets the idle pill back immediately; a non-persistent
+ user keeps the hide-at-idle behaviour (the bar pops only on a session).
+ """
+ bar = getattr(self, "_orb", None)
+ bridge = getattr(self, "_bridge", None)
+ if bar is None or bridge is None:
+ return
+ try:
+ # Mirror the boot wiring in ``_start_speech_and_orb``: bar_persistent
+ # only governs the jarvis bar; the mascot is always hide-at-idle.
+ orb_style = getattr(self.cfg.ui, "orb_style", "jarvis_bar") or "jarvis_bar"
+ persistent = bool(getattr(self.cfg.ui, "bar_persistent", True))
+ is_bar = orb_style == "jarvis_bar"
+ bridge._hide_on_idle = (not persistent) if is_bar else True
+ if hasattr(bar, "_persistent"):
+ bar._persistent = persistent
+ if is_bar and persistent:
+ show = getattr(bar, "show", None)
+ if callable(show):
+ show("idle")
+ except Exception: # noqa: BLE001
+ from loguru import logger
+
+ logger.debug(
+ "overlay restore for visible window failed", exc_info=True
+ )
+
# ---- Shutdown ----------------------------------------------------------
def shutdown(self) -> int:
@@ -2300,7 +2961,7 @@ class DesktopApp:
# oben rechts verschwindet bevor der Prozess terminiert.
if self._orb is not None:
try:
- # Prefer stop() when the surface has it (whisper bar:
+ # Prefer stop() when the surface has it (jarvis bar:
# unsubscribes its level_tap sink + destroys the window). The
# mascot orb has no stop() → fall back to hide().
stop = getattr(self._orb, "stop", None)
@@ -2363,6 +3024,25 @@ class DesktopApp:
loop.call_soon_threadsafe(self._pipeline_task.cancel)
except Exception: # noqa: BLE001
pass
+ # Wake-model background tasks + gate: cancel the turbo hot-swap task
+ # and RELEASE the wake-model-loaded gate so any task still parked in
+ # ``await self._wake_model_loaded.wait()`` (the heavy-backend gate)
+ # unblocks instead of sitting pending through shutdown. Left pending,
+ # these log "Task was destroyed but it is pending" and can stall
+ # loop.stop → the self-restart hangs and the old process keeps the
+ # port (forensic 2026-06-27: PID 51240 hung ~30 min on shutdown).
+ _wut = getattr(self, "_wake_upgrade_task", None)
+ if _wut is not None and not _wut.done():
+ try:
+ loop.call_soon_threadsafe(_wut.cancel)
+ except Exception: # noqa: BLE001
+ pass
+ _wml = getattr(self, "_wake_model_loaded", None)
+ if _wml is not None:
+ try:
+ loop.call_soon_threadsafe(_wml.set)
+ except Exception: # noqa: BLE001
+ pass
# Workflow-Scheduler + Store sauber herunterfahren — verhindert
# dass ein cron-Tick mitten im Shutdown noch einen Run triggert.
wf_scheduler = getattr(self, "_workflow_scheduler", None)
@@ -2410,6 +3090,14 @@ class DesktopApp:
asyncio.run_coroutine_threadsafe(stop_overlay(), loop).result(timeout=2.0)
except Exception: # noqa: BLE001
pass
+ # Stop the serve-first bootstrap (it owns the listening socket).
+ if self._bootstrap is not None:
+ try:
+ asyncio.run_coroutine_threadsafe(
+ self._bootstrap.stop(), loop
+ ).result(timeout=3.0)
+ except Exception: # noqa: BLE001
+ pass
try:
fut = asyncio.run_coroutine_threadsafe(server.stop(), loop)
try:
diff --git a/jarvis/ui/icon_utils.py b/jarvis/ui/icon_utils.py
index 07cf65ae26..7f44def600 100644
--- a/jarvis/ui/icon_utils.py
+++ b/jarvis/ui/icon_utils.py
@@ -341,6 +341,52 @@ def set_window_icon_by_title(
return _apply_icon_to_hwnd(int(hwnd), ico_path)
+def set_window_icon_for_pid(pid: int, ico_path: Path) -> bool:
+ """Set the icon on the largest visible top-level window owned by ``pid``.
+
+ A title-independent companion to :func:`set_window_icon_by_title`. pywebview's
+ WebView2 host window does not reliably carry ``WINDOW_TITLE`` at the moment the
+ icon-setter polls (the title is applied late, and ``FindWindowW`` only matches
+ an *exact* title), so we also locate the window by *our own* process id and pick
+ its biggest top-level window. Returns True when an icon was applied.
+ """
+ if sys.platform != "win32":
+ return False
+ if not ico_path.is_file():
+ return False
+ try:
+ import ctypes
+ from ctypes import wintypes
+ except Exception as exc: # noqa: BLE001
+ logger.opt(exception=exc).warning("ctypes nicht verfügbar")
+ return False
+
+ user32 = ctypes.windll.user32
+ user32.GetWindowThreadProcessId.argtypes = [
+ wintypes.HWND, ctypes.POINTER(wintypes.DWORD)
+ ]
+ user32.IsWindowVisible.argtypes = [wintypes.HWND]
+
+ best = [0, 0] # [hwnd, area]
+ EnumProc = ctypes.WINFUNCTYPE(ctypes.c_bool, wintypes.HWND, wintypes.LPARAM)
+
+ def _cb(hwnd, _lparam): # noqa: ANN001
+ wp = wintypes.DWORD()
+ user32.GetWindowThreadProcessId(hwnd, ctypes.byref(wp))
+ if wp.value == pid and user32.IsWindowVisible(hwnd):
+ rect = wintypes.RECT()
+ user32.GetWindowRect(hwnd, ctypes.byref(rect))
+ area = (rect.right - rect.left) * (rect.bottom - rect.top)
+ if area > best[1]:
+ best[0], best[1] = int(hwnd), area
+ return True
+
+ user32.EnumWindows(EnumProc(_cb), 0)
+ if not best[0]:
+ return False
+ return _apply_icon_to_hwnd(best[0], ico_path)
+
+
def load_ico_as_pil_image(ico_path: Path, size: int = 64) -> Any | None:
"""Lädt ``.ico`` als ``PIL.Image`` für pystray-Tray-Icon.
diff --git a/jarvis/ui/whisperbar/__init__.py b/jarvis/ui/jarvisbar/__init__.py
similarity index 54%
rename from jarvis/ui/whisperbar/__init__.py
rename to jarvis/ui/jarvisbar/__init__.py
index 612154d57f..8bc74a9710 100644
--- a/jarvis/ui/whisperbar/__init__.py
+++ b/jarvis/ui/jarvisbar/__init__.py
@@ -1,20 +1,20 @@
"""Whisper-bar overlay package — the slim default on-screen representation.
-``WhisperBarOverlay`` is imported lazily so this package stays importable on a
+``JarvisBarOverlay`` is imported lazily so this package stays importable on a
headless host (no tkinter) for capability probing and tests.
"""
from __future__ import annotations
-__all__ = ["WhisperBarOverlay", "NullOverlay"]
+__all__ = ["JarvisBarOverlay", "NullOverlay"]
def __getattr__(name: str): # lazy: avoid importing tkinter on headless import
- if name == "WhisperBarOverlay":
- from jarvis.ui.whisperbar.overlay import WhisperBarOverlay
+ if name == "JarvisBarOverlay":
+ from jarvis.ui.jarvisbar.overlay import JarvisBarOverlay
- return WhisperBarOverlay
+ return JarvisBarOverlay
if name == "NullOverlay":
- from jarvis.ui.whisperbar.null_overlay import NullOverlay
+ from jarvis.ui.jarvisbar.null_overlay import NullOverlay
return NullOverlay
raise AttributeError(f"module {__name__!r} has no attribute {name!r}")
diff --git a/jarvis/ui/whisperbar/interaction.py b/jarvis/ui/jarvisbar/interaction.py
similarity index 87%
rename from jarvis/ui/whisperbar/interaction.py
rename to jarvis/ui/jarvisbar/interaction.py
index 224d916a63..3c2f1c458a 100644
--- a/jarvis/ui/whisperbar/interaction.py
+++ b/jarvis/ui/jarvisbar/interaction.py
@@ -6,7 +6,7 @@ The pure helpers (``is_drag``, ``classify_release``, ``default_bottom_center``,
(→ start a voice session); a press that moves past it is a DRAG (→ reposition
+ persist). No duration gate is needed — moving the pointer arms a drag.
-Persistence uses a dedicated top-level ``[whisperbar]`` TOML section (absolute
+Persistence uses a dedicated top-level ``[jarvisbar]`` TOML section (absolute
x/y) so it never clobbers the orb's ``[overlay.mascot]`` pin, and serialises
through ``config_writer._WRITE_LOCK`` so it cannot race other config writes
(AP-7). The orb's own writer predates that lock; ours is stricter.
@@ -52,10 +52,10 @@ def resolve_click(
) -> str:
"""Resolve a click on the bar into an action by its horizontal zone + state.
- Returns one of ``"hangup"`` / ``"dictate"`` / ``"talk"`` / ``"none"``.
+ Returns one of ``"hangup"`` / ``"mute"`` / ``"talk"`` / ``"none"``.
- The RIGHT zone is the square (toggle endpoint-free dictation — non-
- destructive, so it keeps a generous zone). When IDLE, a click anywhere
+ The RIGHT zone is the microphone mute toggle (mic muted FOR JARVIS only —
+ non-destructive, so it keeps a generous zone). When IDLE, a click anywhere
starts a normal session.
The hang-up X is different: it ENDS the session, so its hit-box is
@@ -70,8 +70,8 @@ def resolve_click(
"""
frac = x / max(1, width)
active = mode in ("listen", "think", "speak")
- if frac >= 0.60: # right zone → the square (non-destructive)
- return "dictate"
+ if frac >= 0.60: # right zone → the mic mute toggle (non-destructive)
+ return "mute"
if not active: # idle middle/left → start a normal session
return "talk"
# Active session: the ONLY destructive bar action is the close-X hang-up,
@@ -109,10 +109,10 @@ def clamp_to_screen(
# --------------------------------------------------------------------------- #
-# Position persistence ([whisperbar] section, absolute x/y) #
+# Position persistence ([jarvisbar] section, absolute x/y) #
# --------------------------------------------------------------------------- #
-def load_whisperbar_position(path: str | Path) -> tuple[int, int] | None:
- """Read [whisperbar] pos_x/pos_y. Returns None if absent/invalid."""
+def load_jarvisbar_position(path: str | Path) -> tuple[int, int] | None:
+ """Read [jarvisbar] pos_x/pos_y. Returns None if absent/invalid."""
import tomllib
try:
@@ -123,7 +123,7 @@ def load_whisperbar_position(path: str | Path) -> tuple[int, int] | None:
data = tomllib.loads(raw.decode("utf-8-sig"))
except (UnicodeDecodeError, tomllib.TOMLDecodeError):
return None
- section = data.get("whisperbar")
+ section = data.get("jarvisbar")
if not isinstance(section, dict):
return None
x, y = section.get("pos_x"), section.get("pos_y")
@@ -132,8 +132,8 @@ def load_whisperbar_position(path: str | Path) -> tuple[int, int] | None:
return None
-def save_whisperbar_position(path: str | Path, x: int, y: int) -> None:
- """Atomically persist [whisperbar] pos_x/pos_y, comment- and BOM-safe.
+def save_jarvisbar_position(path: str | Path, x: int, y: int) -> None:
+ """Atomically persist [jarvisbar] pos_x/pos_y, comment- and BOM-safe.
Reuses ``config_writer._WRITE_LOCK`` so the write serialises with every
other jarvis.toml mutation (AP-7). No-op if the config file is missing.
@@ -155,10 +155,10 @@ def save_whisperbar_position(path: str | Path, x: int, y: int) -> None:
raw_bytes = p.read_bytes()
had_bom = raw_bytes.startswith(b"\xef\xbb\xbf")
doc = tomlkit.parse(raw_bytes.decode("utf-8-sig"))
- section = doc.get("whisperbar")
+ section = doc.get("jarvisbar")
if section is None:
section = tomlkit.table()
- doc["whisperbar"] = section
+ doc["jarvisbar"] = section
section["pos_x"] = int(x)
section["pos_y"] = int(y)
out = tomlkit.dumps(doc)
@@ -166,7 +166,7 @@ def save_whisperbar_position(path: str | Path, x: int, y: int) -> None:
out = bom + out
# Path-based temp + os.replace: the context manager guarantees the
# file handle is closed, so no descriptor can leak (unlike mkstemp).
- tmp = p.with_suffix(p.suffix + ".whisperbar.tmp")
+ tmp = p.with_suffix(p.suffix + ".jarvisbar.tmp")
try:
with open(tmp, "w", encoding="utf-8", newline="") as fh:
fh.write(out)
diff --git a/jarvis/ui/whisperbar/null_overlay.py b/jarvis/ui/jarvisbar/null_overlay.py
similarity index 100%
rename from jarvis/ui/whisperbar/null_overlay.py
rename to jarvis/ui/jarvisbar/null_overlay.py
diff --git a/jarvis/ui/whisperbar/overlay.py b/jarvis/ui/jarvisbar/overlay.py
similarity index 70%
rename from jarvis/ui/whisperbar/overlay.py
rename to jarvis/ui/jarvisbar/overlay.py
index 610d559348..f7c7be0e03 100644
--- a/jarvis/ui/whisperbar/overlay.py
+++ b/jarvis/ui/jarvisbar/overlay.py
@@ -1,4 +1,4 @@
-"""WhisperBarOverlay — the slim Tk on-screen bar.
+"""JarvisBarOverlay — the slim Tk on-screen bar.
Implements the same duck-typed surface API ``OrbBusBridge`` already drives, so
the bridge is reused unchanged. ``show(mode)`` selects the renderer state;
@@ -29,9 +29,9 @@ import time
from collections.abc import Callable
from typing import Any
-from jarvis.ui.whisperbar import interaction, renderer
+from jarvis.ui.jarvisbar import interaction, renderer
-log = logging.getLogger("jarvis.ui.whisperbar")
+log = logging.getLogger("jarvis.ui.jarvisbar")
COLOR_KEY_HEX = "#FF00FF"
DRAG_THRESHOLD_PX = 16
@@ -53,6 +53,18 @@ BAR_ALPHA = 0.6
AUDIBLE_LEVEL = 0.06
AUDIBLE_HOLD_S = 0.5
+# Frame-loop revival watchdog (anti-freeze). The animation re-arms only from its
+# own tail, so any single silent break (a swallowed after() failure, an exception
+# before the try/finally, a one-off Tk hiccup) would kill it permanently while
+# the Tk mainloop keeps running — the bar stays visible, frozen on its last
+# frame. A SECOND, independent after-chain (``_schedule_frame_watchdog``) watches
+# a per-frame heartbeat (``_last_frame_ns``) and kicks the frame loop back to life
+# when it goes stale. It renders nothing, so it is immune to the render/PIL faults
+# that kill the frame loop. The threshold is far above the 16 ms tick, so a
+# continuously-stamped heartbeat can never false-fire while the loop is ticking.
+WATCHDOG_INTERVAL_MS = 1000
+FRAME_STALL_THRESHOLD_NS = 2_000_000_000 # 2 s of silence ⇒ the loop is dead
+
def _primary_work_area() -> tuple[int, int, int, int] | None:
"""Primary-monitor work area (left, top, right, bottom) EXCLUDING the
@@ -77,7 +89,7 @@ def _primary_work_area() -> tuple[int, int, int, int] | None:
return None
-class WhisperBarOverlay:
+class JarvisBarOverlay:
def __init__(
self,
persistent: bool = True,
@@ -100,9 +112,13 @@ class WhisperBarOverlay:
# (>= AUDIBLE_LEVEL). Drives the wave↔bars choice in _schedule_frame.
# 0.0 = "long ago" → starts on the wave, not the bars.
self._last_audible_t = 0.0
+ # monotonic_ns() stamped on every frame tick (alive or dropped). The
+ # revival watchdog compares against this to tell a living loop from a
+ # silently-dead one. 0 = "no frame has run yet" → the watchdog holds off.
+ self._last_frame_ns = 0
self._root: Any = None
self._canvas: Any = None
- self._renderer: renderer.WhisperBarRenderer | None = None
+ self._renderer: renderer.JarvisBarRenderer | None = None
self._photo: Any = None
self._image_id: Any = None
self._ui_queue: queue.Queue = queue.Queue()
@@ -118,6 +134,11 @@ class WhisperBarOverlay:
self._feedback_publisher: Callable[[str, dict], None] | None = None
self._on_show_window: Callable[[], None] | None = None
self._hovered = False # mouse over the bar → reveal the close cross
+ # Local mirror of the global voice-mute state (mic muted FOR JARVIS only).
+ # Flipped optimistically on a mic-button click and reconciled by the
+ # authoritative VoiceMuteChanged via set_muted(). A bool write is atomic
+ # under the GIL, like _ext_level — read on the frame loop without a lock.
+ self._muted = False
# ------------------------------------------------------------------ #
# Surface API consumed by OrbBusBridge #
@@ -163,6 +184,15 @@ class WhisperBarOverlay:
def start_mouth_animation(self, duration_ms: int = 60000) -> None: ...
def stop_mouth_animation(self) -> None: ...
+ def set_muted(self, muted: bool) -> None:
+ """Mirror the pipeline's authoritative voice-mute state onto the bar.
+
+ Called by OrbBusBridge on every VoiceMuteChanged (from this bar, the
+ mascot, or a voice command), so the red rim + slashed-mic icon stay in
+ lock-step with reality regardless of where the toggle originated. Plain
+ atomic bool write — the frame loop reads it; no Tk marshal needed."""
+ self._muted = bool(muted)
+
def set_on_mute_toggle(self, callback: Callable[[], None] | None) -> None:
self._on_mute_toggle = callback
@@ -191,12 +221,12 @@ class WhisperBarOverlay:
try:
self.start()
except Exception: # noqa: BLE001
- log.exception("WhisperBar thread start failed")
+ log.exception("JarvisBar thread start failed")
- t = threading.Thread(target=_run, name="whisperbar-tk-mainloop", daemon=True)
+ t = threading.Thread(target=_run, name="jarvisbar-tk-mainloop", daemon=True)
t.start()
if not self._started.wait(timeout=timeout):
- log.error("WhisperBar window not initialised within %.1fs", timeout)
+ log.error("JarvisBar window not initialised within %.1fs", timeout)
def start(self) -> None:
import tkinter as tk
@@ -204,11 +234,11 @@ class WhisperBarOverlay:
from PIL import ImageTk # noqa: F401 — fail fast here if Pillow missing
self._tk_thread_id = threading.get_ident()
- self._renderer = renderer.WhisperBarRenderer(accent=self._accent)
+ self._renderer = renderer.JarvisBarRenderer(accent=self._accent)
root = tk.Tk()
self._root = root
- root.title("JarvisWhisperBar")
+ root.title("JarvisBar")
root.overrideredirect(True)
root.wm_attributes("-topmost", True)
try:
@@ -277,6 +307,7 @@ class WhisperBarOverlay:
self._started.set()
self._schedule_ui_queue()
self._schedule_frame()
+ self._schedule_frame_watchdog() # independent anti-freeze revival loop
root.mainloop()
def stop(self) -> None:
@@ -292,7 +323,7 @@ class WhisperBarOverlay:
try:
root.after(0, root.destroy)
except Exception: # noqa: BLE001
- log.debug("whisperbar destroy failed", exc_info=True)
+ log.debug("jarvisbar destroy failed", exc_info=True)
# ------------------------------------------------------------------ #
# Tk-thread internals #
@@ -307,7 +338,7 @@ class WhisperBarOverlay:
try:
from jarvis.core.config_writer import DEFAULT_CONFIG_FILE
- pos = interaction.load_whisperbar_position(DEFAULT_CONFIG_FILE)
+ pos = interaction.load_jarvisbar_position(DEFAULT_CONFIG_FILE)
except Exception: # noqa: BLE001
pos = None
if pos is not None:
@@ -336,7 +367,7 @@ class WhisperBarOverlay:
try:
self._root.deiconify()
except Exception: # noqa: BLE001
- log.debug("whisperbar deiconify failed", exc_info=True)
+ log.debug("jarvisbar deiconify failed", exc_info=True)
def _do_hide(self) -> None:
if self._root is None:
@@ -344,7 +375,7 @@ class WhisperBarOverlay:
try:
self._root.withdraw()
except Exception: # noqa: BLE001
- log.debug("whisperbar withdraw failed", exc_info=True)
+ log.debug("jarvisbar withdraw failed", exc_info=True)
def _enqueue_ui(self, fn: Callable[[], None]) -> None:
if self._root is None:
@@ -365,7 +396,7 @@ class WhisperBarOverlay:
try:
fn()
except Exception: # noqa: BLE001
- log.exception("WhisperBar UI command failed")
+ log.exception("JarvisBar UI command failed")
self._root.after(20, self._schedule_ui_queue)
def _schedule_frame(self) -> None:
@@ -404,7 +435,8 @@ class WhisperBarOverlay:
# exactly like it reacts to your mic. No synthetic floor (that made the
# bars look uniformly blocky).
img = self._renderer.render(
- t, effective_mode, self._ext_level, hovered=self._hovered
+ t, effective_mode, self._ext_level,
+ hovered=self._hovered, muted=self._muted,
)
# PhotoImage must be retained on self, else Tk GCs it before drawing.
self._photo = ImageTk.PhotoImage(img)
@@ -415,8 +447,12 @@ class WhisperBarOverlay:
else:
self._canvas.itemconfig(self._image_id, image=self._photo)
except Exception: # noqa: BLE001 — one bad frame must never freeze the bar
- log.exception("WhisperBar frame render failed — dropping one frame")
+ log.exception("JarvisBar frame render failed — dropping one frame")
finally:
+ # Heartbeat first: a dropped-but-rearmed frame is still a LIVING loop,
+ # so we stamp even on the failure path. The watchdog reads this to
+ # tell alive from silently-dead.
+ self._last_frame_ns = time.monotonic_ns()
# Re-arm unconditionally so the loop is self-healing. Guard the after()
# call itself: if the root was torn down mid-frame, swallow the
# TclError and stop re-arming (the window is gone — correct to stop).
@@ -424,7 +460,43 @@ class WhisperBarOverlay:
try:
self._root.after(16, self._schedule_frame) # ~60 FPS
except Exception: # noqa: BLE001
- log.debug("WhisperBar frame re-arm skipped", exc_info=True)
+ log.warning(
+ "JarvisBar frame re-arm skipped — watchdog will revive",
+ exc_info=True,
+ )
+
+ def _schedule_frame_watchdog(self) -> None:
+ """Independent revival loop — the second after-chain (anti-freeze). Renders
+ nothing; only checks the frame-loop heartbeat and kicks ``_schedule_frame``
+ back to life if it has gone silent past ``FRAME_STALL_THRESHOLD_NS`` (e.g.
+ a render hang or a swallowed re-arm failure froze the bar). Its own re-arm
+ is in ``finally`` so a single check error cannot kill the watchdog. A
+ deliberate ``stop()`` (``_running`` False) ends it cleanly."""
+ if not self._running or self._root is None:
+ return
+ try:
+ last = self._last_frame_ns
+ if last and (time.monotonic_ns() - last) > FRAME_STALL_THRESHOLD_NS:
+ stalled_s = (time.monotonic_ns() - last) / 1e9
+ log.warning(
+ "JarvisBar frame loop stalled %.1fs — reviving it", stalled_s
+ )
+ # Pre-stamp so a false alarm (a still-live loop) doesn't make us
+ # re-kick every tick; the revived loop immediately re-stamps.
+ self._last_frame_ns = time.monotonic_ns()
+ self._schedule_frame()
+ except Exception: # noqa: BLE001 — the watchdog must itself never die
+ log.debug("JarvisBar frame watchdog check failed", exc_info=True)
+ finally:
+ if self._running and self._root is not None:
+ try:
+ self._root.after(
+ WATCHDOG_INTERVAL_MS, self._schedule_frame_watchdog
+ )
+ except Exception: # noqa: BLE001
+ log.warning(
+ "JarvisBar frame watchdog re-arm skipped", exc_info=True
+ )
# ------------------------------------------------------------------ #
# Drag (reposition) + click (start a voice session) #
@@ -460,7 +532,7 @@ class WhisperBarOverlay:
try:
self._root.geometry(f"{renderer.WIN_W}x{renderer.WIN_H}+{self._x}+{self._y}")
except Exception: # noqa: BLE001
- log.debug("whisperbar geometry update failed", exc_info=True)
+ log.debug("jarvisbar geometry update failed", exc_info=True)
def _on_release(self, event: Any) -> None:
d = self._drag
@@ -468,6 +540,17 @@ class WhisperBarOverlay:
if d is None:
return
if interaction.classify_release(moved=bool(d["moved"])) == "click":
+ # Phantom-click guard (root cause of the request_hangup STORM): a
+ # frameless color-key topmost Tk window emits SYNTHETIC press/release
+ # events on withdraw/deiconify/turn-mode-switch under a stationary
+ # cursor. Read as a close-X click, they fired a machine-paced
+ # request_hangup storm that killed live sessions AND armed the
+ # post-hangup wake-lock, so the next "Hey Jarvis" was swallowed
+ # ("wake triggers, nothing happens"). Honor a click ONLY when the OS
+ # pointer is really over the bar right now.
+ if not self._pointer_over_bar():
+ log.debug("jarvisbar: ignoring phantom click (pointer off bar)")
+ return
# Use the PRESS-time hover (consistent with the press-time cx): a
# deliberate click that started on the bar registers even if a stray
# <Leave> flickered _hovered before release.
@@ -483,9 +566,38 @@ class WhisperBarOverlay:
self._root.geometry(f"{renderer.WIN_W}x{renderer.WIN_H}+{self._x}+{self._y}")
from jarvis.core.config_writer import DEFAULT_CONFIG_FILE
- interaction.save_whisperbar_position(DEFAULT_CONFIG_FILE, self._x, self._y)
+ interaction.save_jarvisbar_position(DEFAULT_CONFIG_FILE, self._x, self._y)
+ except Exception: # noqa: BLE001
+ log.debug("jarvisbar position persist failed", exc_info=True)
+
+ def _pointer_over_bar(self) -> bool:
+ """True when the OS pointer is really inside the bar window right now.
+
+ Guards against synthetic/phantom button events that a frameless
+ color-key topmost Tk window emits on withdraw/deiconify/turn-mode-switch
+ under a stationary cursor (tkdnd was one source, now disabled; the
+ deiconify path remains). Uses ``winfo_pointerxy`` + the window's own
+ ``winfo_rootx/rooty/width/height`` — all Tk screen-pixel measurements in
+ one coordinate space, so it stays correct under HiDPI scaling. Fails
+ CLOSED (returns False) on any error or an unmapped / zero-size window:
+ a missed real click is recoverable, a phantom hang-up is not.
+ """
+ root = self._root
+ if root is None:
+ return False
+ try:
+ if not int(root.winfo_ismapped()):
+ return False
+ bw = int(root.winfo_width())
+ bh = int(root.winfo_height())
+ if bw <= 1 or bh <= 1:
+ return False
+ px, py = root.winfo_pointerxy()
+ bx = int(root.winfo_rootx())
+ by = int(root.winfo_rooty())
+ return bx <= int(px) < bx + bw and by <= int(py) < by + bh
except Exception: # noqa: BLE001
- log.debug("whisperbar position persist failed", exc_info=True)
+ return False
def _on_enter(self, _event: Any = None) -> None:
self._hovered = True
@@ -503,12 +615,12 @@ class WhisperBarOverlay:
try:
callback()
except Exception: # noqa: BLE001
- log.debug("whisperbar show-window callback failed", exc_info=True)
+ log.debug("jarvisbar show-window callback failed", exc_info=True)
def _on_click(self, click_x: float | None = None, *, hovered: bool = False) -> None:
- # Zone-routed: LEFT X → hang up (active only), RIGHT square → toggle
- # endpoint-free dictation, MIDDLE (idle) → start a normal session. All
- # entries are thread-safe from the Tk thread.
+ # Zone-routed: LEFT X → hang up (active only), RIGHT mic → toggle voice
+ # mute (mic muted FOR JARVIS only), MIDDLE (idle) → start a normal
+ # session. All entries are thread-safe from the Tk thread.
if click_x is None:
click_x = renderer.WIN_W / 2
try:
@@ -527,19 +639,40 @@ class WhisperBarOverlay:
click_x, renderer.WIN_W, self._mode,
hovered=hovered, pill_w=pill_w,
)
- if action == "dictate":
- toggle = getattr(pipeline, "request_ptt_toggle", None)
- if callable(toggle):
- toggle()
+ if action == "mute":
+ # The mic button toggles voice mute via the bridge-wired
+ # callback (publishes VoiceMuteToggleRequested → pipeline flips
+ # _muted → broadcasts VoiceMuteChanged → set_muted reconciles).
+ # Flip the local mirror optimistically so the red rim +
+ # slashed-mic show on the very next frame — but ONLY when a
+ # callback is wired, else a boot-race click would paint a false
+ # slash with nothing muted behind it.
+ cb = self._on_mute_toggle
+ if cb is not None:
+ cb()
+ self._muted = not self._muted
elif action == "hangup":
- hangup = getattr(pipeline, "request_hangup", None)
- if callable(hangup):
- hangup()
+ # Only a LIVE session is hung up. If the bar is stuck in an
+ # active "listen/think/speak" look with NO session behind it
+ # (a wake confirmed then swallowed by the post-hangup wake-lock,
+ # or a stray event flipped the look), a close-X would be a no-op
+ # request_hangup that just traps the user. Start a session
+ # instead so a click ALWAYS escapes the stuck state. Legacy
+ # pipelines without is_session_active keep the plain hang-up.
+ active_fn = getattr(pipeline, "is_session_active", None)
+ if active_fn is not None and not active_fn():
+ start = getattr(pipeline, "request_voice_session", None)
+ if callable(start):
+ start()
+ else:
+ hangup = getattr(pipeline, "request_hangup", None)
+ if callable(hangup):
+ hangup()
elif action == "talk":
pipeline.request_voice_session()
# "none" → nothing
except Exception: # noqa: BLE001
- log.debug("whisperbar click action failed", exc_info=True)
+ log.debug("jarvisbar click action failed", exc_info=True)
def _on_reset_double_click(self, _event: Any = None) -> None:
"""Reset the bar to its default bottom-center anchor.
@@ -560,6 +693,6 @@ class WhisperBarOverlay:
self._root.geometry(f"{renderer.WIN_W}x{renderer.WIN_H}+{self._x}+{self._y}")
from jarvis.core.config_writer import DEFAULT_CONFIG_FILE
- interaction.save_whisperbar_position(DEFAULT_CONFIG_FILE, self._x, self._y)
+ interaction.save_jarvisbar_position(DEFAULT_CONFIG_FILE, self._x, self._y)
except Exception: # noqa: BLE001
- log.debug("whisperbar reset failed", exc_info=True)
+ log.debug("jarvisbar reset failed", exc_info=True)
diff --git a/jarvis/ui/whisperbar/renderer.py b/jarvis/ui/jarvisbar/renderer.py
similarity index 84%
rename from jarvis/ui/whisperbar/renderer.py
rename to jarvis/ui/jarvisbar/renderer.py
index a2f22af9eb..1fcc57b359 100644
--- a/jarvis/ui/whisperbar/renderer.py
+++ b/jarvis/ui/jarvisbar/renderer.py
@@ -1,7 +1,7 @@
"""Pure rendering math + drawing for the whisper bar.
No tkinter, no I/O — every function is deterministic given its inputs, so the
-visual behaviour is unit-testable. ``WhisperBarRenderer.render`` returns a PIL
+visual behaviour is unit-testable. ``JarvisBarRenderer.render`` returns a PIL
image with a magenta color-key background that the Tk surface keys out.
State → look:
@@ -30,6 +30,10 @@ PILL_BG = (14, 13, 12)
PILL_BORDER = (215, 182, 105)
# Hover-to-hang-up close cross (soft red = "close").
CLOSE_X = (228, 110, 96)
+# Muted-state rim + slashed-mic disc: a clear-but-soft red so the user can tell
+# at a glance they are muted (the pill border turns this colour whenever the
+# voice mic is muted FOR JARVIS, even at rest). Tune freely — purely cosmetic.
+MUTED_RED = (220, 80, 72)
# Size factors. ``_SCALE`` is the overall shrink (1.0 was the original, far too
# big). ``_W`` / ``_H`` then stretch width / height independently on top of it:
@@ -129,13 +133,19 @@ def evenly_spaced(cx: float, span: float, n: int) -> list[float]:
return [x0 + i * step for i in range(n)]
-def target_pill_size(mode: str, hovered: bool) -> tuple[int, int]:
+def target_pill_size(mode: str, hovered: bool, muted: bool = False) -> tuple[int, int]:
"""Pick the pill's target (w, h): ACTIVE while a session is live, OPEN on
hover (to show controls), COLLAPSED at rest. Only a live session is 2x —
- matching 'bigger only while in the conversation'."""
+ matching 'bigger only while in the conversation'.
+
+ Muted standby is the exception: instead of collapsing to the tiny empty
+ pill (where the red rim is a hairline and the mic glyph is hidden), the
+ muted bar stays at the OPEN size so the slashed-mic + red rim stay visible.
+ A muted user is otherwise trapped — they can't unmute by voice (Jarvis is
+ deaf while muted), so the click target must always be on screen."""
if mode in ("listen", "speak", "think"):
return ACTIVE_W, ACTIVE_H
- if hovered:
+ if hovered or muted:
return OPEN_W, OPEN_H
return COLLAPSED_W, COLLAPSED_H
@@ -384,18 +394,24 @@ class _RenderState:
ph: float = float(COLLAPSED_H) # live pill height, eased toward the target
-class WhisperBarRenderer:
+class JarvisBarRenderer:
def __init__(self, accent: str = "#e7c46e") -> None:
self._accent = _hex_to_rgb(accent)
self._st = _RenderState()
def render(
- self, t: float, mode: str, ext_level: float, hovered: bool = False
+ self,
+ t: float,
+ mode: str,
+ ext_level: float,
+ hovered: bool = False,
+ muted: bool = False,
) -> Image.Image:
active = mode in ("listen", "speak")
# Ease the pill toward its target size: ACTIVE (2x) while a session is
- # live, OPEN on hover (controls), COLLAPSED at rest.
- tw, th = target_pill_size(mode, hovered)
+ # live, OPEN on hover (controls) OR while muted (keep the mute cue +
+ # unmute target visible), COLLAPSED at rest.
+ tw, th = target_pill_size(mode, hovered, muted)
# Snappy grow/shrink: 0.5 reaches the target in ~4 frames (~70 ms) so the
# bar pops to full size almost immediately on "Hey Jarvis" instead of
# crawling there over a third of a second.
@@ -413,19 +429,23 @@ class WhisperBarRenderer:
cx = WIN_W / 2.0
cy = pill_center_y(ph) # bottom-anchored: grows upward, idle stays put
+ # The rim turns red whenever the mic is muted FOR JARVIS — drawn on
+ # EVERY frame (even idle/standby, no hover) so the muted cue is visible
+ # at a glance without having to reveal the controls.
+ outline_color = MUTED_RED if muted else PILL_BORDER
d.rounded_rectangle(
[cx - pw / 2, cy - ph / 2, cx + pw / 2, cy + ph / 2],
radius=ph / 2,
fill=PILL_BG,
- outline=PILL_BORDER,
+ outline=outline_color,
width=2,
)
# Hover splits the bar into controls: LEFT X (hang up, only while a
- # session is live) + RIGHT square (toggle endpoint-free dictation).
+ # session is live) + RIGHT mic (toggle voice mute for Jarvis).
+ x_right = cx + 0.33 * pw # pulled in so the mic glyph never clips the rim
if hovered:
x_left = cx - 0.42 * pw
- x_right = cx + 0.35 * pw # pulled left off the right edge (no clip)
active_sess = mode in ("listen", "speak", "think")
# Keep the speech indicator VISIBLE while interacting — narrow bars
# in the centre so you can see the voice is live, controls flanking.
@@ -433,13 +453,18 @@ class WhisperBarRenderer:
self._draw_bars(d, t, cx, cy, pw, ph, span=bars_span_for(pw) * 0.5, n=5)
if active_sess:
self._draw_close_x(d, x_left, cy, ph)
- self._draw_square(d, x_right, cy, ph)
+ self._draw_mic(img, x_right, cy, ph, muted)
elif mode == "think":
self._draw_thinking(img, t, cx, cy, pw, ph)
elif mode in ("listen", "speak"):
self._draw_bars(d, t, cx, cy, pw, ph)
- # idle / standby (not hovered): a clean EMPTY pill — no dots, no bars.
- # "When nothing is happening, nothing is in the bar."
+ elif muted:
+ # Muted standby (idle, not hovered): always show the slashed mic so
+ # the user sees at a glance they're muted AND where to click to
+ # unmute (they can't unmute by voice — Jarvis is deaf while muted).
+ self._draw_mic(img, x_right, cy, ph, muted=True)
+ # idle / standby (not hovered, not muted): a clean EMPTY pill — no dots,
+ # no bars. "When nothing is happening, nothing is in the bar."
return img
def _draw_dots(
@@ -464,13 +489,58 @@ class WhisperBarRenderer:
d.line([(cx - r, cy - r), (cx + r, cy + r)], fill=CLOSE_X, width=w)
d.line([(cx - r, cy + r), (cx + r, cy - r)], fill=CLOSE_X, width=w)
- def _draw_square(self, d: ImageDraw.ImageDraw, cx: float, cy: float, ph: float) -> None:
- r = max(2.5, ph * 0.21) # half-side of the dictation square
- w = max(2, _STROKE_W)
- d.rounded_rectangle(
- [cx - r, cy - r, cx + r, cy + r], radius=max(1.0, r * 0.25),
- outline=self._accent, width=w,
+ def _draw_mic(
+ self, img: Image.Image, cx: float, cy: float, ph: float, muted: bool
+ ) -> None:
+ """Right-hand control: the voice-mute toggle, drawn as a clean OUTLINE
+ microphone (capsule head + cradle bow + stand), in the spirit of the
+ reference glyph — line art, no enclosing box. Replaced the dictation
+ square (maintainer request 2026-06-28).
+
+ Supersampled (4x → LANCZOS) like the standby dots, because the thin
+ curves alias badly drawn directly at ~30 px. Gold while live; red with
+ a diagonal slash when muted (mirrors the red pill rim — the universal
+ "mic off" mark).
+ """
+ ss = 4
+ layer = Image.new("RGBA", (img.width * ss, img.height * ss), (0, 0, 0, 0))
+ ld = ImageDraw.Draw(layer)
+ color = (*(MUTED_RED if muted else self._accent), 255)
+ w = max(1, round(_STROKE_W * 0.85 * ss))
+
+ x = cx * ss
+ y = cy * ss
+ p = ph * ss
+
+ # Capsule head (outline rounded rect), sitting in the upper half.
+ hw = p * 0.115
+ head_top = y - p * 0.34
+ head_bot = y + p * 0.02
+ ld.rounded_rectangle(
+ [x - hw, head_top, x + hw, head_bot], radius=hw, outline=color, width=w
+ )
+ # Cradle bow: a U-arc cupping the capsule from below (wider than it).
+ bw = p * 0.21
+ ld.arc(
+ [x - bw, y - p * 0.16, x + bw, y + p * 0.20],
+ start=15, end=165, fill=color, width=w,
+ )
+ # Stand: short stem from the bow down to a small foot.
+ stem_bot = y + p * 0.32
+ ld.line([(x, y + p * 0.18), (x, stem_bot)], fill=color, width=w)
+ foot_hw = p * 0.12
+ ld.line(
+ [(x - foot_hw, stem_bot), (x + foot_hw, stem_bot)], fill=color, width=w
)
+ # Muted: a diagonal slash across the whole glyph ("mic off"). Kept short
+ # enough that its top-right tip stays inside the rounded pill (else the
+ # color-key shows through as a pink fleck at the rim).
+ if muted:
+ s = p * 0.28
+ ld.line([(x - s, y + s), (x + s, y - s)], fill=color, width=w)
+
+ small = layer.resize(img.size, Image.Resampling.LANCZOS)
+ img.paste(small, (0, 0), small)
def _draw_bars(
self,
diff --git a/jarvis/ui/web/antigravity_routes.py b/jarvis/ui/web/antigravity_routes.py
index d07a57b0c3..9aa321303e 100644
--- a/jarvis/ui/web/antigravity_routes.py
+++ b/jarvis/ui/web/antigravity_routes.py
@@ -15,6 +15,7 @@ other routers::
from __future__ import annotations
import logging
+import sys
from typing import Any
from fastapi import APIRouter, HTTPException
@@ -25,10 +26,21 @@ log = logging.getLogger(__name__)
router = APIRouter(prefix="/api", tags=["antigravity"])
-# Shown to the user when no official Google CLI is installed. The Gemini CLI
-# (``npm i -g @google/gemini-cli``) is the cross-platform fallback; ``agy`` is
-# the official successor (macOS/Linux installer below).
-_INSTALL_HINT = "curl -fsSL https://antigravity.google/cli/install.sh | bash"
+
+def _install_hint() -> str:
+ """OS-appropriate install command for an official Google CLI.
+
+ Windows ships ``agy`` via winget (the ``curl … | bash`` script does not run
+ in PowerShell/cmd); macOS/Linux use the install script. The cross-platform
+ Gemini-CLI npm fallback works on every OS, so it is always offered too.
+ """
+ npm_fallback = "npm i -g @google/gemini-cli"
+ if sys.platform == "win32":
+ return f"winget install Google.AntigravityCLI (or: {npm_fallback})"
+ return (
+ "curl -fsSL https://antigravity.google/cli/install.sh | bash"
+ f" (or: {npm_fallback})"
+ )
@router.get("/antigravity/status")
@@ -45,7 +57,7 @@ async def antigravity_login() -> dict[str, Any]:
if not status.installed:
raise HTTPException(
status_code=409,
- detail={"message": "No Google CLI found", "install_command": _INSTALL_HINT},
+ detail={"message": "No Google CLI found", "install_command": _install_hint()},
)
try:
proc = service.start_login()
diff --git a/jarvis/ui/web/claude_routes.py b/jarvis/ui/web/claude_routes.py
new file mode 100644
index 0000000000..6144a768ed
--- /dev/null
+++ b/jarvis/ui/web/claude_routes.py
@@ -0,0 +1,93 @@
+"""REST routes for the Claude (Anthropic) subscription connect flow.
+
+Dual billing, mirror of Codex / Antigravity: the heavy-task subagent runs over
+the **Claude Max subscription** (the ``claude`` CLI's OAuth login in
+``~/.claude/.credentials.json`` — no per-token bill) OR over an **Anthropic API
+key** (billed per token). This module surfaces an honest snapshot of which one is
+live, plus the connected account email + subscription tier, so the Subagent card
+can render "Connected as <email>" exactly like the Codex / Antigravity cards.
+
+This is the Anthropic sibling of ``/api/codex/*``
+(:mod:`jarvis.ui.web.provider_routes`) and ``/api/antigravity/*``
+(:mod:`jarvis.ui.web.antigravity_routes`). Kept in its own router module so the
+feature ships as a self-contained unit. Mount alongside the other routers::
+
+ from .claude_routes import router as claude_router
+ app.include_router(claude_router)
+
+The endpoint returns NO secret — only the display-safe account email + tier and
+connection booleans.
+"""
+from __future__ import annotations
+
+import logging
+from typing import Any
+
+from fastapi import APIRouter, HTTPException
+
+from jarvis.claude_auth import ClaudeAuthService
+
+log = logging.getLogger(__name__)
+
+router = APIRouter(prefix="/api", tags=["claude"])
+
+_INSTALL_HINT = "npm i -g @anthropic-ai/claude-code"
+
+
+def _real_api_key_present() -> bool:
+ """True when a CLASSIC Anthropic API key (sk-ant-api…) is stored.
+
+ A stored ``anthropic_api_key`` that is actually an OAuth bearer (sk-ant-oat,
+ auto-populated from a Claude Max login) is NOT an API-key billing path — that
+ is the subscription, already detected from the credentials file. Only a real
+ API key flips the service into ``api_key`` mode.
+ """
+ try:
+ from jarvis.core.config import get_secret
+
+ key = get_secret("anthropic_api_key", env_fallback="ANTHROPIC_API_KEY")
+ except Exception: # noqa: BLE001
+ return False
+ return bool(key) and not str(key).startswith("sk-ant-oat")
+
+
+def _service() -> ClaudeAuthService:
+ return ClaudeAuthService(api_key_present=_real_api_key_present())
+
+
[email protected]("/claude/status")
+async def claude_status() -> dict[str, Any]:
+ """Honest snapshot of the Claude login (installed / connected / account)."""
+ return _service().status().to_dict()
+
+
[email protected]("/claude/login")
+async def claude_login() -> dict[str, Any]:
+ """Start the interactive Claude sign-in in a terminal. 409 if no CLI is found."""
+ service = _service()
+ status = service.status()
+ if not status.installed:
+ raise HTTPException(
+ status_code=409,
+ detail={"message": "Claude CLI is not installed", "install_command": _INSTALL_HINT},
+ )
+ try:
+ proc = service.start_login()
+ except FileNotFoundError as exc:
+ raise HTTPException(status_code=409, detail=str(exc)) from exc
+ except Exception as exc: # noqa: BLE001
+ raise HTTPException(
+ status_code=500,
+ detail=f"Claude login could not be started: {type(exc).__name__}: {exc}",
+ ) from exc
+ return {"ok": True, "pid": proc.pid, "message": "Claude login was started in the terminal"}
+
+
[email protected]("/claude/logout")
+async def claude_logout() -> dict[str, Any]:
+ """Disconnect the Claude subscription login (removes the on-disk bearer)."""
+ service = _service()
+ ok, error = service.logout_blocking()
+ if not ok:
+ raise HTTPException(status_code=500, detail=error or "Claude logout failed")
+ return {"ok": True, "message": "Claude was disconnected"}
diff --git a/jarvis/ui/web/downloads_routes.py b/jarvis/ui/web/downloads_routes.py
new file mode 100644
index 0000000000..2438aee007
--- /dev/null
+++ b/jarvis/ui/web/downloads_routes.py
@@ -0,0 +1,137 @@
+"""REST routes that save a file to the user's local Downloads folder.
+
+Why this exists: the desktop shell renders the UI inside pywebview (WebView2 /
+Edge Chromium on Windows). pywebview ships with ``settings['ALLOW_DOWNLOADS']``
+defaulting to ``False`` — its EdgeChromium handler then *silently cancels* every
+browser download (blob ``<a download>``, ``Content-Disposition: attachment``).
+So the client-side download that works in a plain browser produces a "success"
+toast but no file on the desktop. To put a file where the user expects it, the
+backend writes it directly to ``~/Downloads`` (cross-platform via
+``Path.home()``) and reports the absolute path back for the toast.
+
+This mirrors the Outputs view, which already takes the native path on the
+desktop (``open_path.reveal_in_folder`` / ``open_file``) instead of a browser
+download.
+
+Endpoints:
+ GET /api/downloads/capabilities {native_file_actions, platform}
+ POST /api/downloads/save Write base64 bytes to ~/Downloads
+
+``POST /save`` is **desktop-only**: it is gated on
+``app.state.native_file_actions`` (True on a local desktop run, False on a
+headless VPS) and 404s when False — on a server the file would land on the
+*server's* disk, not the user's machine, so the frontend keeps the browser
+download there. Loopback-only (server binds 127.0.0.1) — no auth token needed.
+"""
+from __future__ import annotations
+
+import base64
+import binascii
+import logging
+import re
+from pathlib import Path
+from typing import Any
+
+from fastapi import APIRouter, HTTPException, Request
+from pydantic import BaseModel, Field
+
+from jarvis.platform import detect_platform
+
+# Reuse the proven collision-avoidance helper from the sessions save path
+# instead of duplicating it (the two save flows share the same ~/Downloads
+# semantics). Importing the module only defines a router; no side effects.
+from jarvis.ui.web.sessions_routes import _avoid_collision
+
+log = logging.getLogger(__name__)
+
+router = APIRouter(prefix="/api/downloads", tags=["downloads"])
+
+# A generous ceiling for a UI-initiated save (transcripts, a share-card PNG).
+# Guards against a runaway/abusive body even though the server is loopback-only.
+_MAX_BYTES = 25 * 1024 * 1024 # 25 MiB
+
+# Characters illegal in a Windows filename (the strictest of the three OSes);
+# replaced with '_' so one sanitizer keeps the name portable everywhere.
+_ILLEGAL_FILENAME_CHARS = re.compile(r'[<>:"/\\|?*\x00-\x1f]')
+
+
+class SaveFileRequest(BaseModel):
+ """Save-to-Downloads request — filename + base64 content (text or binary)."""
+
+ filename: str = Field(min_length=1, max_length=255)
+ content_b64: str
+
+
+class SaveFileResponse(BaseModel):
+ """Absolute saved path for the toast, plus filename and byte count."""
+
+ saved_path: str
+ filename: str
+ bytes_written: int
+
+
[email protected]("/capabilities")
+def downloads_capabilities(request: Request) -> dict[str, Any]:
+ """Report whether the backend can save straight to the local Downloads folder.
+
+ True only on a local desktop run (set by the launcher); False on a headless
+ VPS, where writing to ``~/Downloads`` would target the *server's* disk, not
+ the user's machine. The frontend uses this to decide between a backend save
+ (desktop) and a normal browser download (VPS/browser).
+ """
+ native = bool(getattr(request.app.state, "native_file_actions", False))
+ return {"native_file_actions": native, "platform": detect_platform()}
+
+
+def _safe_basename(filename: str) -> str:
+ """Reduce *filename* to a single portable basename (defense-in-depth).
+
+ Strips any directory part and traversal, replaces characters illegal on
+ Windows, and falls back to ``download`` when nothing usable remains. The
+ frontend already builds safe names; this guarantees it regardless.
+ """
+ # Drop any path component — handle both separators explicitly so a Windows
+ # path posted from a non-Windows client (or vice versa) is still flattened.
+ base = filename.replace("\\", "/").rsplit("/", 1)[-1].strip()
+ base = _ILLEGAL_FILENAME_CHARS.sub("_", base)
+ base = base.strip(" .") # no leading/trailing dots or spaces (Windows)
+ if not base or base in (".", ".."):
+ return "download"
+ return base[:255]
+
+
[email protected]("/save", response_model=SaveFileResponse)
+async def save_to_downloads(
+ request: Request, body: SaveFileRequest
+) -> SaveFileResponse:
+ """Write base64-decoded *content* to ``~/Downloads`` and return the path.
+
+ Desktop-only (gated on ``native_file_actions``). On a name collision a
+ ``-1``, ``-2`` … suffix is appended — never overwrites. Returns the absolute
+ path so the UI can show exactly where the file landed.
+ """
+ native = bool(getattr(request.app.state, "native_file_actions", False))
+ if not native:
+ # On a server this would write to the server's disk. The frontend takes
+ # the browser-download path there, so this route should not be reached.
+ raise HTTPException(status_code=404, detail="native-file-actions-disabled")
+
+ try:
+ data = base64.b64decode(body.content_b64, validate=True)
+ except (binascii.Error, ValueError) as exc:
+ raise HTTPException(status_code=400, detail="invalid-base64") from exc
+ if len(data) > _MAX_BYTES:
+ raise HTTPException(status_code=413, detail="file-too-large")
+
+ filename = _safe_basename(body.filename)
+ downloads = Path.home() / "Downloads"
+ downloads.mkdir(parents=True, exist_ok=True)
+ target = _avoid_collision(downloads / filename)
+
+ target.write_bytes(data)
+ log.info("DownloadSave: %s (%d bytes)", target, len(data))
+ return SaveFileResponse(
+ saved_path=str(target),
+ filename=target.name,
+ bytes_written=len(data),
+ )
diff --git a/jarvis/ui/web/fast_bootstrap.py b/jarvis/ui/web/fast_bootstrap.py
new file mode 100644
index 0000000000..79080660c8
--- /dev/null
+++ b/jarvis/ui/web/fast_bootstrap.py
@@ -0,0 +1,435 @@
+"""Reusable serve-first fast-boot bootstrap (the "serve first, init behind" core).
+
+A tiny ASGI holding server that binds the admin port in a few hundred ms and
+answers ``GET /api/health`` with 200 the instant it is up — so a shell that
+gates on health (the desktop ``DesktopApp._wait_for_backend`` poll, or the
+headless harness) sees the process as serving immediately. Every other request
+is HELD until the real FastAPI app is registered via :meth:`set_app`, then
+delegated to it. The first such request cleanly waits (never fails); everything
+after is full speed.
+
+Dependency-light on purpose: nothing heavy is imported at module load and
+``uvicorn`` is imported lazily inside :meth:`serve`, so a caller can construct
+and bind a :class:`FastBootstrap` *before* paying for ``import fastapi`` /
+``load_config`` / the ``jarvis.brain`` import graph — which is exactly what
+keeps those costs off the time-to-serving path.
+
+Contract: the real app delegated to runs ON THE SAME EVENT LOOP that serves the
+bootstrap. :meth:`set_app` must therefore be called from a coroutine on that
+loop (the headless and desktop backends both build the app on the bootstrap's
+own loop), so the readiness :class:`asyncio.Event` is set loop-locally.
+"""
+
+from __future__ import annotations
+
+import asyncio
+import mimetypes
+from contextlib import suppress
+from pathlib import Path
+from typing import Any
+
+# The built React frontend lives next to this module (jarvis/ui/web/dist),
+# the same directory the real FastAPI app serves it from. Resolving it here —
+# with NO config / FastAPI import — lets the bootstrap serve the UI shell from
+# disk while the heavy app warms up, so the desktop window shows the real UI
+# instead of a black screen.
+_DEFAULT_DIST_DIR = Path(__file__).resolve().parent / "dist"
+
+
+class FastBootstrap:
+ """Hold-and-delegate ASGI bootstrap server. See module docstring."""
+
+ def __init__(
+ self, *, hold_timeout: float = 120.0, dist_dir: Path | None = None
+ ) -> None:
+ self._full: dict[str, Any] = {"app": None}
+ self._ready = asyncio.Event()
+ self._hold_timeout = hold_timeout
+ self._server: Any = None
+ self._task: asyncio.Task | None = None
+ self._dist_dir = (dist_dir or _DEFAULT_DIST_DIR).resolve()
+ # Listener self-healing (see the "lifecycle" section). The bootstrap
+ # OWNS the listening socket for the whole process lifetime (it delegates
+ # to the real app via set_app but never hands off the socket), so when a
+ # transient OS error kills the accept loop and closes the socket, only
+ # the bootstrap can bring the port back. These carry the bind target +
+ # the supervisor task so it can re-bind on the same host:port.
+ self._host: str | None = None
+ self._port: int | None = None
+ self._stopping = False
+ self._supervisor_task: asyncio.Task | None = None
+ self._supervise_interval = 5.0
+ # Set once the window's critical shell assets (index.html + the entry
+ # JS bundle) have been served. The backend build waits briefly on this
+ # so the heavy, GIL-holding imports don't starve the loop while the UI
+ # is still painting — i.e. the user sees the rendered UI, not a blank
+ # window, before the warm-up storm begins.
+ self._shell_served = asyncio.Event()
+
+ # ---- the ASGI callable -------------------------------------------------
+
+ @property
+ def app(self) -> Any:
+ """The bootstrap ASGI app (handed to uvicorn / driven directly in tests)."""
+ return self._asgi
+
+ async def _asgi(self, scope: dict, receive: Any, send: Any) -> None:
+ kind = scope["type"]
+ if kind == "lifespan":
+ await self._handle_lifespan(receive, send)
+ return
+
+ # Real app already registered → delegate everything to it (incl. health).
+ if self._ready.is_set():
+ app = self._full["app"]
+ if app is None:
+ await self._warming(scope, send, unavailable=True)
+ return
+ await app(scope, receive, send)
+ return
+
+ # Warming: answer health 200 NOW so the window can appear; hold the rest.
+ if (
+ kind == "http"
+ and scope.get("method") == "GET"
+ and scope.get("path") == "/api/health"
+ ):
+ await self._ok_health(send)
+ return
+
+ # A websocket during warming must NOT hold the handshake open: a
+ # browser times out a pending WS handshake (tens of seconds) and its
+ # client then escalates its reconnect backoff, so the desktop window
+ # shows a long spurious "OFFLINE" after every restart. Accept-then-close
+ # with 1013 ("try again later") instead — the client receives a readable
+ # close code and reconnects fast once the real app is registered.
+ if kind == "websocket":
+ await receive() # consume the websocket.connect event
+ await send({"type": "websocket.accept"})
+ await send({"type": "websocket.close", "code": 1013})
+ return
+
+ # Serve the STATIC frontend (index.html + assets + SPA fallback) straight
+ # from disk while warming, so the window shows the real UI shell — not a
+ # black screen — the instant it opens. Only the dynamic surface (/api/*,
+ # /ws) is held below; the SPA's data calls then resolve once the real app
+ # is registered. This serves the genuine build (no fake splash).
+ path = scope.get("path", "/")
+ if (
+ kind == "http"
+ and scope.get("method") in ("GET", "HEAD")
+ and not path.startswith("/api")
+ and not path.startswith("/ws")
+ ):
+ served = await self._serve_static(scope, send)
+ if served:
+ return
+ # No build on disk → fall through to hold (the real app may still
+ # render a server-side placeholder once it is up).
+
+ try:
+ await asyncio.wait_for(self._ready.wait(), timeout=self._hold_timeout)
+ except TimeoutError:
+ await self._warming(scope, send)
+ return
+
+ app = self._full["app"]
+ if app is None:
+ await self._warming(scope, send, unavailable=True)
+ return
+ await app(scope, receive, send)
+
+ @staticmethod
+ async def _handle_lifespan(receive: Any, send: Any) -> None:
+ while True:
+ message = await receive()
+ if message["type"] == "lifespan.startup":
+ await send({"type": "lifespan.startup.complete"})
+ elif message["type"] == "lifespan.shutdown":
+ await send({"type": "lifespan.shutdown.complete"})
+ return
+
+ @staticmethod
+ async def _ok_health(send: Any) -> None:
+ body = b'{"ok": true, "warming": true}'
+ await send(
+ {
+ "type": "http.response.start",
+ "status": 200,
+ "headers": [(b"content-type", b"application/json")],
+ }
+ )
+ await send({"type": "http.response.body", "body": body})
+
+ @staticmethod
+ async def _warming(scope: dict, send: Any, *, unavailable: bool = False) -> None:
+ kind = scope["type"]
+ if kind == "http":
+ body = (
+ b"Jarvis backend failed to start."
+ if unavailable
+ else b"Jarvis is starting up. Please retry."
+ )
+ await send(
+ {
+ "type": "http.response.start",
+ "status": 503,
+ "headers": [
+ (b"content-type", b"text/plain; charset=utf-8"),
+ (b"retry-after", b"1"),
+ ],
+ }
+ )
+ await send({"type": "http.response.body", "body": body})
+ elif kind == "websocket":
+ # 1013 = "try again later" → clients reconnect once the app is up.
+ await send({"type": "websocket.close", "code": 1013})
+
+ # ---- static frontend (served while warming, no black screen) -----------
+
+ async def _serve_static(self, scope: dict, send: Any) -> bool:
+ """Serve the built frontend file for *scope*'s path. Returns False when
+ no build is on disk (the caller then holds the request)."""
+ target = self._resolve_static_file(scope.get("path", "/"))
+ if target is None:
+ return False
+ try:
+ data = await asyncio.to_thread(target.read_bytes)
+ except OSError:
+ return False
+ ctype = mimetypes.guess_type(target.name)[0] or "application/octet-stream"
+ headers = [
+ (b"content-type", ctype.encode("latin-1")),
+ (b"content-length", str(len(data)).encode("latin-1")),
+ ]
+ if target.name == "index.html":
+ # The shell must never be cached stale across a rebuild/restart
+ # (mirrors the real app's index response).
+ headers.append((b"cache-control", b"no-store, max-age=0"))
+ await send({"type": "http.response.start", "status": 200, "headers": headers})
+ body = b"" if scope.get("method") == "HEAD" else data
+ await send({"type": "http.response.body", "body": body})
+ # Mark the shell as served once the entry JS bundle has gone out (the
+ # SPA can render after that). index.html alone is a blank #root, so wait
+ # for a .js asset — the backend build holds off its GIL-heavy imports
+ # until this fires so the UI paints first.
+ if target.name.endswith(".js"):
+ self._shell_served.set()
+ return True
+
+ async def wait_shell_served(self, timeout: float) -> bool: # noqa: ASYNC109 — bounded readiness wait, conventional param
+ """Block until the window has fetched the shell's entry JS (so the UI
+ can paint), or *timeout* elapses. Returns True if the shell was served.
+
+ Lets the backend defer its GIL-heavy build until the visible UI is up.
+ A no-op-fast return when already set; bounded so a headless run (no
+ window, no JS request) never stalls the build.
+ """
+ if self._shell_served.is_set():
+ return True
+ try:
+ await asyncio.wait_for(self._shell_served.wait(), timeout=timeout)
+ return True
+ except TimeoutError:
+ return False
+
+ def _resolve_static_file(self, path: str) -> Path | None:
+ """Map a request path to a real file under dist, or the SPA index.html
+ fallback. Returns None when no build exists (caller holds instead).
+
+ Mirrors ``WebServer._register_static_or_spa``: a real file under dist is
+ served as-is; any other (client-side route) path falls back to
+ index.html so the SPA router can take over.
+ """
+ index = self._dist_dir / "index.html"
+ rel = path.lstrip("/")
+ if rel:
+ try:
+ target = (self._dist_dir / rel).resolve()
+ if target.is_file() and self._dist_dir in target.parents:
+ return target
+ except (OSError, ValueError):
+ pass
+ return index if index.is_file() else None
+
+ # ---- lifecycle ---------------------------------------------------------
+
+ def set_app(self, app: Any) -> None:
+ """Register the real ASGI app; held + future requests delegate to it.
+
+ Must be called on the loop that serves the bootstrap (see module
+ docstring) so the readiness event is set loop-locally.
+ """
+ self._full["app"] = app
+ self._ready.set()
+
+ async def serve(
+ self,
+ host: str,
+ port: int,
+ *,
+ supervise: bool = True,
+ supervise_interval: float = 5.0,
+ ) -> None:
+ """Bind *port* and start serving the bootstrap on the current loop.
+
+ Returns once the server is accepting connections. ``uvicorn`` is
+ imported here (lazily) so the module stays dependency-light.
+
+ When *supervise* is true (the default), a background watchdog keeps the
+ listening socket alive: if a transient OS error kills the accept loop
+ and closes the socket (the WinError-64 lock-zombie forensic), the
+ watchdog re-binds the same host:port so the port never stays dead while
+ the process lives on. *supervise_interval* is the probe period.
+ """
+ self._host = host
+ self._port = port
+ self._supervise_interval = supervise_interval
+ await self._start_server(host, port)
+ if supervise and self._supervisor_task is None:
+ self._supervisor_task = asyncio.create_task(self._supervise())
+
+ async def _start_server(self, host: str, port: int) -> None:
+ """Build + start a fresh uvicorn server on *host:port* and wait until it
+ is accepting connections. Shared by :meth:`serve` and :meth:`_rebind`."""
+ import uvicorn
+
+ # Pass a plain async function (NOT the bound method ``self._asgi``):
+ # uvicorn's ASGI-version probe mis-detects a bound method as ASGI2
+ # (``iscoroutinefunction(method.__call__)`` is False), which would call
+ # it as ``app(scope)`` and crash. A module-level-style closure is
+ # correctly detected as ASGI3.
+ _self = self
+
+ async def _asgi3(scope: dict, receive: Any, send: Any) -> None:
+ await _self._asgi(scope, receive, send)
+
+ self._server = uvicorn.Server(
+ uvicorn.Config(
+ app=_asgi3,
+ host=host,
+ port=port,
+ log_level="warning",
+ lifespan="on",
+ loop="asyncio",
+ )
+ )
+ self._task = asyncio.create_task(self._server.serve())
+ deadline = asyncio.get_running_loop().time() + 8.0
+ while not self._server.started:
+ if asyncio.get_running_loop().time() > deadline:
+ raise TimeoutError(f"bootstrap server not ready on {host}:{port}")
+ if self._task.done():
+ exc = self._task.exception()
+ if exc is not None:
+ raise exc
+ raise RuntimeError("bootstrap serve() ended before 'started'")
+ await asyncio.sleep(0.01)
+
+ async def _listener_alive(self) -> bool:
+ """True if the bound port still accepts a TCP connection.
+
+ An active loopback connect — not an inspection of uvicorn/asyncio
+ internals — so it is version-proof and tests the one thing that matters:
+ can a request still reach us. The proactor's ``sock.close()`` on
+ WinError 64 makes this connect fail with ECONNREFUSED, which is exactly
+ the dead-listener signal the watchdog acts on.
+ """
+ if self._host is None or self._port is None:
+ return True # never bound → nothing to supervise
+ try:
+ reader, writer = await asyncio.wait_for(
+ asyncio.open_connection(self._host, self._port), timeout=2.0
+ )
+ writer.close()
+ with suppress(Exception):
+ await writer.wait_closed()
+ return True
+ except (OSError, TimeoutError):
+ return False
+
+ async def _supervise(self) -> None:
+ """Watchdog: keep the listening socket alive for the process lifetime.
+
+ Probes the bound port every ``_supervise_interval`` seconds; on a
+ confirmed dead listener (two probes, to ride out a one-off transient) it
+ re-binds. Self-contained + error-swallowing so it can never crash the
+ backend loop; it simply retries on the next tick.
+ """
+ from loguru import logger
+
+ while not self._stopping:
+ try:
+ await asyncio.sleep(self._supervise_interval)
+ if self._stopping:
+ return
+ if await self._listener_alive():
+ continue
+ # Confirm with a second probe so a single transient blip does
+ # not trigger an unnecessary re-bind.
+ await asyncio.sleep(0.2)
+ if self._stopping or await self._listener_alive():
+ continue
+ logger.warning(
+ "fast-boot: listening socket on {}:{} is dead — re-binding "
+ "(transient OS socket error / WinError 64 recovery)",
+ self._host,
+ self._port,
+ )
+ await self._rebind()
+ logger.info(
+ "fast-boot: listener re-bound on {}:{} — port recovered",
+ self._host,
+ self._port,
+ )
+ except asyncio.CancelledError:
+ raise
+ except Exception as exc: # noqa: BLE001 — never let the watchdog die
+ logger.opt(exception=exc).error(
+ "fast-boot: listener watchdog tick failed (will retry next tick)"
+ )
+
+ async def _rebind(self) -> None:
+ """Tear down the dead uvicorn server and start a fresh one on the same
+ host:port. The registered real app + readiness state are untouched, so
+ delegation survives the listener swap.
+ """
+ if self._host is None or self._port is None:
+ return
+ await self._teardown_server()
+ await self._start_server(self._host, self._port)
+
+ async def _teardown_server(self) -> None:
+ """Stop the current uvicorn server + serve task (no effect on the
+ socket already closed by the OS; just reaps the dead task)."""
+ if self._server is not None:
+ self._server.should_exit = True
+ if self._task is not None:
+ try:
+ await asyncio.wait_for(asyncio.shield(self._task), timeout=3.0)
+ except (TimeoutError, asyncio.CancelledError):
+ self._task.cancel()
+ with suppress(asyncio.CancelledError, Exception):
+ await self._task
+ self._server = None
+ self._task = None
+
+ async def _kill_listener_for_test(self) -> None:
+ """Test-only: close the uvicorn listening socket exactly as the asyncio
+ proactor does on WinError 64, so a test can drive the self-heal path
+ without a real network fault."""
+ server = self._server
+ for sub in getattr(server, "servers", []) or []:
+ sub.close()
+ with suppress(Exception):
+ await sub.wait_closed()
+
+ async def stop(self) -> None:
+ """Stop the bootstrap server (it owns the listening socket)."""
+ self._stopping = True
+ if self._supervisor_task is not None:
+ self._supervisor_task.cancel()
+ with suppress(asyncio.CancelledError, Exception):
+ await self._supervisor_task
+ self._supervisor_task = None
+ await self._teardown_server()
diff --git a/jarvis/ui/web/feedback_routes.py b/jarvis/ui/web/feedback_routes.py
new file mode 100644
index 0000000000..3ddec8a46e
--- /dev/null
+++ b/jarvis/ui/web/feedback_routes.py
@@ -0,0 +1,242 @@
+"""REST API for the in-app feedback / bug-report form.
+
+Endpoint:
+
+ POST /api/feedback → {"ok": bool, "status": str, "detail": str}
+
+The endpoint validates the payload, enriches it with system context (app
+version, OS, Python, UTC timestamp), and forwards it to a Discord webhook as
+a rich embed. A screenshot may be included as a data-URL; if present it is
+sent as a multipart upload so Discord can render it as an inline image.
+
+Outcomes (``status`` field):
+ ``"sent"`` — Discord accepted the webhook (2xx).
+ ``"not_configured"`` — no webhook URL is configured; nothing was sent.
+ ``"discord_error"`` — Discord returned a non-2xx status.
+ ``"unreachable"`` — network / timeout error reaching Discord.
+
+The webhook URL is read exclusively via the secret store / ENV; it is never
+hardcoded in source. Configure it via:
+
+ Credential Manager key : discord_feedback_webhook_url
+ ENV fallback : DISCORD_FEEDBACK_WEBHOOK_URL
+"""
+from __future__ import annotations
+
+import base64
+import datetime
+import json as _json
+import logging
+import platform
+import re
+from pathlib import Path
+from typing import Literal
+
+import httpx
+from fastapi import APIRouter, HTTPException
+from pydantic import BaseModel, Field
+
+from jarvis.core.config import get_secret
+
+log = logging.getLogger(__name__)
+
+router = APIRouter(prefix="/api/feedback", tags=["feedback"])
+
+# Discord embed colour per feedback type.
+_TYPE_COLORS: dict[str, int] = {
+ "bug": 0xED4245, # red
+ "idea": 0x5865F2, # blurple
+ "question": 0xFEE75C, # yellow
+}
+
+# Discord API limits.
+_DISCORD_EMBED_DESC_MAX = 4096
+
+# Maximum decoded size for an attached screenshot (8 MB).
+_SCREENSHOT_DECODED_MAX_BYTES = 8 * 1024 * 1024
+
+_SECRET_KEY = "discord_feedback_webhook_url"
+_ENV_KEY = "DISCORD_FEEDBACK_WEBHOOK_URL"
+
+
+# ----------------------------------------------------------------------
+# Request / response models
+# ----------------------------------------------------------------------
+
+
+class FeedbackPayload(BaseModel):
+ type: Literal["bug", "idea", "question"]
+ title: str = Field(..., min_length=1, max_length=200)
+ description: str = Field(..., min_length=1, max_length=4000)
+ # Optional data-URL screenshot, e.g. "data:image/png;base64,<...>".
+ screenshot: str | None = Field(None)
+
+
+class FeedbackResult(BaseModel):
+ ok: bool
+ status: Literal["sent", "not_configured", "discord_error", "unreachable"]
+ detail: str
+
+
+# ----------------------------------------------------------------------
+# Version helper
+# ----------------------------------------------------------------------
+
+
+def _app_version() -> str:
+ """Return the running app version string, with several fallback strategies.
+
+ 1. ``jarvis.__version__`` if present (editable install with metadata).
+ 2. The ``version = "..."`` field from ``pyproject.toml`` at repo root.
+ 3. ``"unknown"`` if both fail.
+ """
+ try:
+ import jarvis # type: ignore[import]
+
+ return jarvis.__version__ # type: ignore[attr-defined]
+ except (ImportError, AttributeError):
+ pass
+
+ try:
+ pyproject = Path(__file__).resolve().parents[4] / "pyproject.toml"
+ text = pyproject.read_text(encoding="utf-8")
+ m = re.search(r'^version\s*=\s*"([^"]+)"', text, re.MULTILINE)
+ if m:
+ return m.group(1)
+ except Exception: # noqa: BLE001 — best-effort, never fatal
+ pass
+
+ return "unknown"
+
+
+# ----------------------------------------------------------------------
+# Endpoint
+# ----------------------------------------------------------------------
+
+
+async def submit_feedback(body: FeedbackPayload) -> FeedbackResult:
+ """Submit user feedback or a bug report to the configured Discord webhook.
+
+ Enriches the payload with app version, OS, Python version, and a UTC
+ timestamp before dispatching. If a screenshot data-URL is included, the
+ request is sent as a Discord multipart upload so the image is rendered
+ inline inside the embed.
+
+ Returns a structured result describing whether the submission was accepted
+ (``"sent"``), skipped because no webhook is configured
+ (``"not_configured"``), or failed (``"discord_error"`` / ``"unreachable"``).
+ The ``ok`` field is ``True`` only when Discord returned a 2xx response.
+ """
+ webhook_url = get_secret(_SECRET_KEY, env_fallback=_ENV_KEY)
+ if not webhook_url:
+ return FeedbackResult(
+ ok=False,
+ status="not_configured",
+ detail=(
+ "No Discord webhook URL is configured. "
+ f"Set the credential '{_SECRET_KEY}' or "
+ f"the environment variable {_ENV_KEY}."
+ ),
+ )
+
+ # Gather server-side context so the client does not have to send it.
+ version = _app_version()
+ os_info = platform.platform()
+ py_version = platform.python_version()
+ reported_at = datetime.datetime.now(datetime.timezone.utc).isoformat()
+
+ # Decode and size-check the screenshot if the client provided one.
+ screenshot_bytes: bytes | None = None
+ if body.screenshot:
+ try:
+ # Strip the data-URL header: "data:image/png;base64,<payload>".
+ _header, _sep, b64_data = body.screenshot.partition(",")
+ raw = base64.b64decode(b64_data)
+ if len(raw) > _SCREENSHOT_DECODED_MAX_BYTES:
+ raise HTTPException(
+ status_code=400,
+ detail=(
+ f"Screenshot exceeds the 8 MB limit "
+ f"({len(raw):,} bytes decoded)."
+ ),
+ )
+ screenshot_bytes = raw
+ except HTTPException:
+ raise
+ except Exception as exc: # noqa: BLE001 — bad b64 → skip screenshot
+ log.warning("feedback: could not decode screenshot — %s", exc)
+ screenshot_bytes = None
+
+ # Build the Discord embed.
+ color = _TYPE_COLORS.get(body.type, 0x99AAB5)
+ embed: dict = {
+ "title": body.title,
+ "description": body.description[:_DISCORD_EMBED_DESC_MAX],
+ "color": color,
+ "fields": [
+ {"name": "Type", "value": body.type.capitalize(), "inline": True},
+ {"name": "App version", "value": version, "inline": True},
+ {"name": "OS", "value": os_info, "inline": False},
+ {"name": "Python", "value": py_version, "inline": True},
+ {"name": "Reported at", "value": reported_at, "inline": True},
+ ],
+ "footer": {"text": "Personal Jarvis · in-app feedback"},
+ }
+ if screenshot_bytes is not None:
+ embed["image"] = {"url": "attachment://screenshot.png"}
+
+ payload_json: dict = {"embeds": [embed]}
+
+ # Dispatch to Discord.
+ try:
+ async with httpx.AsyncClient(timeout=10.0) as client:
+ if screenshot_bytes is not None:
+ # Multipart upload: embed JSON in `payload_json` field + image
+ # in `files[0]` so Discord renders it as the embed image.
+ resp = await client.post(
+ webhook_url,
+ data={"payload_json": _json.dumps(payload_json)},
+ files={
+ "files[0]": (
+ "screenshot.png",
+ screenshot_bytes,
+ "image/png",
+ )
+ },
+ )
+ else:
+ resp = await client.post(webhook_url, json=payload_json)
+ except httpx.TimeoutException as exc:
+ log.warning("feedback: timeout reaching Discord — %s", exc)
+ return FeedbackResult(
+ ok=False,
+ status="unreachable",
+ detail=f"Request timed out: {exc}",
+ )
+ except httpx.HTTPError as exc:
+ log.warning("feedback: network error reaching Discord — %s", exc)
+ return FeedbackResult(
+ ok=False,
+ status="unreachable",
+ detail=f"Network error: {exc}",
+ )
+
+ if resp.is_success:
+ log.info(
+ "feedback: sent to Discord (type=%s, title=%r)", body.type, body.title
+ )
+ return FeedbackResult(
+ ok=True,
+ status="sent",
+ detail="Feedback delivered to Discord.",
+ )
+
+ log.warning(
+ "feedback: Discord returned %d — %s", resp.status_code, resp.text[:200]
+ )
+ return FeedbackResult(
+ ok=False,
+ status="discord_error",
+ detail=f"Discord returned HTTP {resp.status_code}: {resp.text[:200]}",
+ )
diff --git a/jarvis/ui/web/frontend/index.html b/jarvis/ui/web/frontend/index.html
index 3367ef025e..afe50bc999 100644
--- a/jarvis/ui/web/frontend/index.html
+++ b/jarvis/ui/web/frontend/index.html
@@ -5,9 +5,45 @@
<meta name="viewport" content="width=device-width, initial-scale=1.0" />
<link rel="icon" type="image/x-icon" href="/jarvis.ico" />
<title>Jarvis</title>
+ <style>
+ /* Boot splash — painted from index.html the instant the window opens, so
+ there is NO black screen while the (large) JS bundle loads + React
+ mounts. React's createRoot clears #root on its first render, so this is
+ replaced by the real UI automatically. Background matches the pywebview
+ window color (#0a0e14) so there is never a flash. */
+ html, body { margin: 0; height: 100%; background: #0a0e14; }
+ #jarvis-boot-splash {
+ position: fixed; inset: 0; display: flex; flex-direction: column;
+ align-items: center; justify-content: center; gap: 18px;
+ background: #0a0e14;
+ font-family: ui-sans-serif, system-ui, -apple-system, Segoe UI, sans-serif;
+ color: #e7c46e;
+ }
+ #jarvis-boot-splash .ring {
+ width: 38px; height: 38px; border-radius: 50%;
+ border: 3px solid rgba(231, 196, 110, 0.2);
+ border-top-color: #e7c46e;
+ animation: jbs-spin 0.8s linear infinite;
+ }
+ #jarvis-boot-splash .name {
+ font-size: 15px; font-weight: 600; letter-spacing: 0.04em;
+ color: #e6e6e6;
+ }
+ #jarvis-boot-splash .sub {
+ font-size: 12px; color: #9aa3ad; letter-spacing: 0.06em;
+ text-transform: uppercase;
+ }
+ @keyframes jbs-spin { to { transform: rotate(360deg); } }
+ </style>
</head>
<body>
- <div id="root"></div>
+ <div id="root">
+ <div id="jarvis-boot-splash">
+ <div class="ring"></div>
+ <div class="name">Personal Jarvis</div>
+ <div class="sub">Starting…</div>
+ </div>
+ </div>
<script type="module" src="/src/main.tsx"></script>
</body>
</html>
diff --git a/jarvis/ui/web/frontend/package-lock.json b/jarvis/ui/web/frontend/package-lock.json
index 2e457805e9..fbbe2cd226 100644
--- a/jarvis/ui/web/frontend/package-lock.json
+++ b/jarvis/ui/web/frontend/package-lock.json
@@ -25,7 +25,6 @@
"clsx": "^2.1.1",
"cmdk": "^1.1.1",
"framer-motion": "^12.38.0",
- "gray-matter": "^4.0.3",
"html-to-image": "^1.11.13",
"lucide-react": "^0.445.0",
"qrcode.react": "^4.2.0",
@@ -58,8 +57,8 @@
"tailwindcss": "^3.4.13",
"tailwindcss-animate": "^1.0.7",
"typescript": "^5.6.2",
- "vite": "^5.4.8",
- "vitest": "^2.1.1"
+ "vite": "^6.4.3",
+ "vitest": "^3.2.6"
}
},
"node_modules/@alloc/quick-lru": {
@@ -97,13 +96,13 @@
"license": "ISC"
},
"node_modules/@babel/code-frame": {
- "version": "7.29.0",
- "resolved": "https://registry.npmjs.org/@babel/code-frame/-/code-frame-7.29.0.tgz",
- "integrity": "sha512-9NhCeYjq9+3uxgdtp20LSiJXJvN0FeCtNGpJxuMFZ1Kv3cWUNb6DOhJwUvcVCzKGR66cw4njwM6hrJLqgOwbcw==",
+ "version": "7.29.7",
+ "resolved": "https://registry.npmjs.org/@babel/code-frame/-/code-frame-7.29.7.tgz",
+ "integrity": "sha512-Aup7aUOfpbAUg2ROOJN6Iw5f9DMBlzu0mIkm/malLQFN/YQgO48wCj0Kxa3sEHJvPVFg7siR+qRInwXd2qhQKw==",
"dev": true,
"license": "MIT",
"dependencies": {
- "@babel/helper-validator-identifier": "^7.28.5",
+ "@babel/helper-validator-identifier": "^7.29.7",
"js-tokens": "^4.0.0",
"picocolors": "^1.1.1"
},
@@ -112,9 +111,9 @@
}
},
"node_modules/@babel/compat-data": {
- "version": "7.29.0",
- "resolved": "https://registry.npmjs.org/@babel/compat-data/-/compat-data-7.29.0.tgz",
- "integrity": "sha512-T1NCJqT/j9+cn8fvkt7jtwbLBfLC/1y1c7NtCeXFRgzGTsafi68MRv8yzkYSapBnFA6L3U2VSc02ciDzoAJhJg==",
+ "version": "7.29.7",
+ "resolved": "https://registry.npmjs.org/@babel/compat-data/-/compat-data-7.29.7.tgz",
+ "integrity": "sha512-locTkQyKvwIEgBzVrn8693ebc97F2U8ZHjbXwDXJ5Fn2TCpNwTlKcaKLkdHop5c/icOFE7qt7Q9JC5hnKNa6Gg==",
"dev": true,
"license": "MIT",
"engines": {
@@ -122,22 +121,22 @@
}
},
"node_modules/@babel/core": {
- "version": "7.29.0",
- "resolved": "https://registry.npmjs.org/@babel/core/-/core-7.29.0.tgz",
- "integrity": "sha512-CGOfOJqWjg2qW/Mb6zNsDm+u5vFQ8DxXfbM09z69p5Z6+mE1ikP2jUXw+j42Pf1XTYED2Rni5f95npYeuwMDQA==",
+ "version": "7.29.7",
+ "resolved": "https://registry.npmjs.org/@babel/core/-/core-7.29.7.tgz",
+ "integrity": "sha512-RgHBCvtjbOK2gXSNBNIkNoEc9qoVEtau3hj8gEqKQuL3HZAibKarWFEI3Lfm6EYKkLalOh8eSrj9b+ch9H/VBA==",
"dev": true,
"license": "MIT",
"peer": true,
"dependencies": {
- "@babel/code-frame": "^7.29.0",
- "@babel/generator": "^7.29.0",
- "@babel/helper-compilation-targets": "^7.28.6",
- "@babel/helper-module-transforms": "^7.28.6",
- "@babel/helpers": "^7.28.6",
- "@babel/parser": "^7.29.0",
- "@babel/template": "^7.28.6",
- "@babel/traverse": "^7.29.0",
- "@babel/types": "^7.29.0",
+ "@babel/code-frame": "^7.29.7",
+ "@babel/generator": "^7.29.7",
+ "@babel/helper-compilation-targets": "^7.29.7",
+ "@babel/helper-module-transforms": "^7.29.7",
+ "@babel/helpers": "^7.29.7",
+ "@babel/parser": "^7.29.7",
+ "@babel/template": "^7.29.7",
+ "@babel/traverse": "^7.29.7",
+ "@babel/types": "^7.29.7",
"@jridgewell/remapping": "^2.3.5",
"convert-source-map": "^2.0.0",
"debug": "^4.1.0",
@@ -154,14 +153,14 @@
}
},
"node_modules/@babel/generator": {
- "version": "7.29.1",
- "resolved": "https://registry.npmjs.org/@babel/generator/-/generator-7.29.1.tgz",
- "integrity": "sha512-qsaF+9Qcm2Qv8SRIMMscAvG4O3lJ0F1GuMo5HR/Bp02LopNgnZBC/EkbevHFeGs4ls/oPz9v+Bsmzbkbe+0dUw==",
+ "version": "7.29.7",
+ "resolved": "https://registry.npmjs.org/@babel/generator/-/generator-7.29.7.tgz",
+ "integrity": "sha512-DkXD5OJQaAQIdZ1bt3UZdEnHAn9Imd3IVBdX03UFe+ony9Ojw5pzr9YVKGDY1jt+Gcn/FnGkNf8r+Vj5NOJWtQ==",
"dev": true,
"license": "MIT",
"dependencies": {
- "@babel/parser": "^7.29.0",
- "@babel/types": "^7.29.0",
+ "@babel/parser": "^7.29.7",
+ "@babel/types": "^7.29.7",
"@jridgewell/gen-mapping": "^0.3.12",
"@jridgewell/trace-mapping": "^0.3.28",
"jsesc": "^3.0.2"
@@ -171,14 +170,14 @@
}
},
"node_modules/@babel/helper-compilation-targets": {
- "version": "7.28.6",
- "resolved": "https://registry.npmjs.org/@babel/helper-compilation-targets/-/helper-compilation-targets-7.28.6.tgz",
- "integrity": "sha512-JYtls3hqi15fcx5GaSNL7SCTJ2MNmjrkHXg4FSpOA/grxK8KwyZ5bubHsCq8FXCkua6xhuaaBit+3b7+VZRfcA==",
+ "version": "7.29.7",
+ "resolved": "https://registry.npmjs.org/@babel/helper-compilation-targets/-/helper-compilation-targets-7.29.7.tgz",
+ "integrity": "sha512-wem6WaBj4NaVYVdNhLPPVacES6ZJ+KBBfSkTMD3YZxbP3rm3Di85tJU5ljaUNhaOynt+Aj0xruhYuzQBt8n71g==",
"dev": true,
"license": "MIT",
"dependencies": {
- "@babel/compat-data": "^7.28.6",
- "@babel/helper-validator-option": "^7.27.1",
+ "@babel/compat-data": "^7.29.7",
+ "@babel/helper-validator-option": "^7.29.7",
"browserslist": "^4.24.0",
"lru-cache": "^5.1.1",
"semver": "^6.3.1"
@@ -188,9 +187,9 @@
}
},
"node_modules/@babel/helper-globals": {
- "version": "7.28.0",
- "resolved": "https://registry.npmjs.org/@babel/helper-globals/-/helper-globals-7.28.0.tgz",
- "integrity": "sha512-+W6cISkXFa1jXsDEdYA8HeevQT/FULhxzR99pxphltZcVaugps53THCeiWA8SguxxpSp3gKPiuYfSWopkLQ4hw==",
+ "version": "7.29.7",
+ "resolved": "https://registry.npmjs.org/@babel/helper-globals/-/helper-globals-7.29.7.tgz",
+ "integrity": "sha512-3nQVUAtvkKH9zahfWgw96Jc/uFOmjACE1kQz82E2lqWmHBgjzbNlsC22nuQTfahmWeQtTq5nQ/4Nnd2A1wj4zA==",
"dev": true,
"license": "MIT",
"engines": {
@@ -198,29 +197,29 @@
}
},
"node_modules/@babel/helper-module-imports": {
- "version": "7.28.6",
- "resolved": "https://registry.npmjs.org/@babel/helper-module-imports/-/helper-module-imports-7.28.6.tgz",
- "integrity": "sha512-l5XkZK7r7wa9LucGw9LwZyyCUscb4x37JWTPz7swwFE/0FMQAGpiWUZn8u9DzkSBWEcK25jmvubfpw2dnAMdbw==",
+ "version": "7.29.7",
+ "resolved": "https://registry.npmjs.org/@babel/helper-module-imports/-/helper-module-imports-7.29.7.tgz",
+ "integrity": "sha512-ejHwrQQYcm9xnTivShn2IDOlIzInN34AXskvq9QicvCtEzq1Vzclu/tKF8Jq1Cg8JG2GL6/EmjgsCT7lXepE3g==",
"dev": true,
"license": "MIT",
"dependencies": {
- "@babel/traverse": "^7.28.6",
- "@babel/types": "^7.28.6"
+ "@babel/traverse": "^7.29.7",
+ "@babel/types": "^7.29.7"
},
"engines": {
"node": ">=6.9.0"
}
},
"node_modules/@babel/helper-module-transforms": {
- "version": "7.28.6",
- "resolved": "https://registry.npmjs.org/@babel/helper-module-transforms/-/helper-module-transforms-7.28.6.tgz",
- "integrity": "sha512-67oXFAYr2cDLDVGLXTEABjdBJZ6drElUSI7WKp70NrpyISso3plG9SAGEF6y7zbha/wOzUByWWTJvEDVNIUGcA==",
+ "version": "7.29.7",
+ "resolved": "https://registry.npmjs.org/@babel/helper-module-transforms/-/helper-module-transforms-7.29.7.tgz",
+ "integrity": "sha512-UPUVSyXbOh627KiCIGQSgwWzGeBKLkaJ9PJEdrngIwMSzxLR4jS4+f1f1jb7VzBbg8nFLaYotvVPFCTqdrmTAg==",
"dev": true,
"license": "MIT",
"dependencies": {
- "@babel/helper-module-imports": "^7.28.6",
- "@babel/helper-validator-identifier": "^7.28.5",
- "@babel/traverse": "^7.28.6"
+ "@babel/helper-module-imports": "^7.29.7",
+ "@babel/helper-validator-identifier": "^7.29.7",
+ "@babel/traverse": "^7.29.7"
},
"engines": {
"node": ">=6.9.0"
@@ -240,9 +239,9 @@
}
},
"node_modules/@babel/helper-string-parser": {
- "version": "7.27.1",
- "resolved": "https://registry.npmjs.org/@babel/helper-string-parser/-/helper-string-parser-7.27.1.tgz",
- "integrity": "sha512-qMlSxKbpRlAridDExk92nSobyDdpPijUq2DW6oDnUqd0iOGxmQjyqhMIihI9+zv4LPyZdRje2cavWPbCbWm3eA==",
+ "version": "7.29.7",
+ "resolved": "https://registry.npmjs.org/@babel/helper-string-parser/-/helper-string-parser-7.29.7.tgz",
+ "integrity": "sha512-Pb5ijPrZ89GDH8223L4UP8i6QApWxs04RbPQJTeWDV0/keR2E36MeKnyr6LYmUUvqRRI+Iv87SuF1W6ErINzYw==",
"dev": true,
"license": "MIT",
"engines": {
@@ -250,9 +249,9 @@
}
},
"node_modules/@babel/helper-validator-identifier": {
- "version": "7.28.5",
- "resolved": "https://registry.npmjs.org/@babel/helper-validator-identifier/-/helper-validator-identifier-7.28.5.tgz",
- "integrity": "sha512-qSs4ifwzKJSV39ucNjsvc6WVHs6b7S03sOh2OcHF9UHfVPqWWALUsNUVzhSBiItjRZoLHx7nIarVjqKVusUZ1Q==",
+ "version": "7.29.7",
+ "resolved": "https://registry.npmjs.org/@babel/helper-validator-identifier/-/helper-validator-identifier-7.29.7.tgz",
+ "integrity": "sha512-qehxGkRj55h/ff8EMaJ+cYhyaKlHIxqYDn682wQD7RNp9UujOQsHog2uS0r2vzr4pW+sXf90NeeayjcNaX3fFg==",
"dev": true,
"license": "MIT",
"engines": {
@@ -260,9 +259,9 @@
}
},
"node_modules/@babel/helper-validator-option": {
- "version": "7.27.1",
- "resolved": "https://registry.npmjs.org/@babel/helper-validator-option/-/helper-validator-option-7.27.1.tgz",
- "integrity": "sha512-YvjJow9FxbhFFKDSuFnVCe2WxXk1zWc22fFePVNEaWJEu8IrZVlda6N0uHwzZrUM1il7NC9Mlp4MaJYbYd9JSg==",
+ "version": "7.29.7",
+ "resolved": "https://registry.npmjs.org/@babel/helper-validator-option/-/helper-validator-option-7.29.7.tgz",
+ "integrity": "sha512-N9ZErrD+yW5geCDtBqnOoxmR8+tNKiGuxKlDpuJxfsqpa2dFcexaziGAE/qoHLiDDreVNMupxGmSoNlyvsA3gw==",
"dev": true,
"license": "MIT",
"engines": {
@@ -270,27 +269,27 @@
}
},
"node_modules/@babel/helpers": {
- "version": "7.29.2",
- "resolved": "https://registry.npmjs.org/@babel/helpers/-/helpers-7.29.2.tgz",
- "integrity": "sha512-HoGuUs4sCZNezVEKdVcwqmZN8GoHirLUcLaYVNBK2J0DadGtdcqgr3BCbvH8+XUo4NGjNl3VOtSjEKNzqfFgKw==",
+ "version": "7.29.7",
+ "resolved": "https://registry.npmjs.org/@babel/helpers/-/helpers-7.29.7.tgz",
+ "integrity": "sha512-1k2lAGRMfHTcwuNYcCNUmaUffmQv8KWMfh2iJUUeRlwlwH4FdNG7mfPI10NPfLHJFThE4Tyr4mv7kTNZOiPuBg==",
"dev": true,
"license": "MIT",
"dependencies": {
- "@babel/template": "^7.28.6",
- "@babel/types": "^7.29.0"
+ "@babel/template": "^7.29.7",
+ "@babel/types": "^7.29.7"
},
"engines": {
"node": ">=6.9.0"
}
},
"node_modules/@babel/parser": {
- "version": "7.29.2",
- "resolved": "https://registry.npmjs.org/@babel/parser/-/parser-7.29.2.tgz",
- "integrity": "sha512-4GgRzy/+fsBa72/RZVJmGKPmZu9Byn8o4MoLpmNe1m8ZfYnz5emHLQz3U4gLud6Zwl0RZIcgiLD7Uq7ySFuDLA==",
+ "version": "7.29.7",
+ "resolved": "https://registry.npmjs.org/@babel/parser/-/parser-7.29.7.tgz",
+ "integrity": "sha512-hnORnjP/1P/zFEndoeX+n+t1RwWRJiJpM/jO7FW32Kn9r5+sJB2JWOdYo4L6k78j15eCwY3Gm/7364B1EMwtNg==",
"dev": true,
"license": "MIT",
"dependencies": {
- "@babel/types": "^7.29.0"
+ "@babel/types": "^7.29.7"
},
"bin": {
"parser": "bin/babel-parser.js"
@@ -341,33 +340,33 @@
}
},
"node_modules/@babel/template": {
- "version": "7.28.6",
- "resolved": "https://registry.npmjs.org/@babel/template/-/template-7.28.6.tgz",
- "integrity": "sha512-YA6Ma2KsCdGb+WC6UpBVFJGXL58MDA6oyONbjyF/+5sBgxY/dwkhLogbMT2GXXyU84/IhRw/2D1Os1B/giz+BQ==",
+ "version": "7.29.7",
+ "resolved": "https://registry.npmjs.org/@babel/template/-/template-7.29.7.tgz",
+ "integrity": "sha512-puq+Gf35oI24FeN11LkoUQFqv9uwNeWpxXZi/Ji3rRIoKAzKnxRaZ+Gkj0vKS9ZCiTESfng1N9LyOyXvo+m+Gg==",
"dev": true,
"license": "MIT",
"dependencies": {
- "@babel/code-frame": "^7.28.6",
- "@babel/parser": "^7.28.6",
- "@babel/types": "^7.28.6"
+ "@babel/code-frame": "^7.29.7",
+ "@babel/parser": "^7.29.7",
+ "@babel/types": "^7.29.7"
},
"engines": {
"node": ">=6.9.0"
}
},
"node_modules/@babel/traverse": {
- "version": "7.29.0",
- "resolved": "https://registry.npmjs.org/@babel/traverse/-/traverse-7.29.0.tgz",
- "integrity": "sha512-4HPiQr0X7+waHfyXPZpWPfWL/J7dcN1mx9gL6WdQVMbPnF3+ZhSMs8tCxN7oHddJE9fhNE7+lxdnlyemKfJRuA==",
+ "version": "7.29.7",
+ "resolved": "https://registry.npmjs.org/@babel/traverse/-/traverse-7.29.7.tgz",
+ "integrity": "sha512-EhlfNQtZ+NK22w5BM61ciuiq1m58ed33Wr1Xan//ZRTy6hgjnwyCffRYwzsGXdASJSUJ1guZILsErh1eQcl+zw==",
"dev": true,
"license": "MIT",
"dependencies": {
- "@babel/code-frame": "^7.29.0",
- "@babel/generator": "^7.29.0",
- "@babel/helper-globals": "^7.28.0",
- "@babel/parser": "^7.29.0",
- "@babel/template": "^7.28.6",
- "@babel/types": "^7.29.0",
+ "@babel/code-frame": "^7.29.7",
+ "@babel/generator": "^7.29.7",
+ "@babel/helper-globals": "^7.29.7",
+ "@babel/parser": "^7.29.7",
+ "@babel/template": "^7.29.7",
+ "@babel/types": "^7.29.7",
"debug": "^4.3.1"
},
"engines": {
@@ -375,14 +374,14 @@
}
},
"node_modules/@babel/types": {
- "version": "7.29.0",
- "resolved": "https://registry.npmjs.org/@babel/types/-/types-7.29.0.tgz",
- "integrity": "sha512-LwdZHpScM4Qz8Xw2iKSzS+cfglZzJGvofQICy7W7v4caru4EaAmyUuO6BGrbyQ2mYV11W0U8j5mBhd14dd3B0A==",
+ "version": "7.29.7",
+ "resolved": "https://registry.npmjs.org/@babel/types/-/types-7.29.7.tgz",
+ "integrity": "sha512-4zBIxpPzowiZpusoFkyGVwakdRJUyuH5PxQ/PrqghfdFWWasvnCdPfQXHrenDai+gyLARulZjZowCOj6fjT4pA==",
"dev": true,
"license": "MIT",
"dependencies": {
- "@babel/helper-string-parser": "^7.27.1",
- "@babel/helper-validator-identifier": "^7.28.5"
+ "@babel/helper-string-parser": "^7.29.7",
+ "@babel/helper-validator-identifier": "^7.29.7"
},
"engines": {
"node": ">=6.9.0"
@@ -506,9 +505,9 @@
}
},
"node_modules/@esbuild/aix-ppc64": {
- "version": "0.21.5",
- "resolved": "https://registry.npmjs.org/@esbuild/aix-ppc64/-/aix-ppc64-0.21.5.tgz",
- "integrity": "sha512-1SDgH6ZSPTlggy1yI6+Dbkiz8xzpHJEVAlF/AM1tHPLsf5STom9rwtjE4hKAF20FfXXNTFqEYXyJNWh1GiZedQ==",
+ "version": "0.25.12",
+ "resolved": "https://registry.npmjs.org/@esbuild/aix-ppc64/-/aix-ppc64-0.25.12.tgz",
+ "integrity": "sha512-Hhmwd6CInZ3dwpuGTF8fJG6yoWmsToE+vYgD4nytZVxcu1ulHpUQRAB1UJ8+N1Am3Mz4+xOByoQoSZf4D+CpkA==",
"cpu": [
"ppc64"
],
@@ -519,13 +518,13 @@
"aix"
],
"engines": {
- "node": ">=12"
+ "node": ">=18"
}
},
"node_modules/@esbuild/android-arm": {
- "version": "0.21.5",
- "resolved": "https://registry.npmjs.org/@esbuild/android-arm/-/android-arm-0.21.5.tgz",
- "integrity": "sha512-vCPvzSjpPHEi1siZdlvAlsPxXl7WbOVUBBAowWug4rJHb68Ox8KualB+1ocNvT5fjv6wpkX6o/iEpbDrf68zcg==",
+ "version": "0.25.12",
+ "resolved": "https://registry.npmjs.org/@esbuild/android-arm/-/android-arm-0.25.12.tgz",
+ "integrity": "sha512-VJ+sKvNA/GE7Ccacc9Cha7bpS8nyzVv0jdVgwNDaR4gDMC/2TTRc33Ip8qrNYUcpkOHUT5OZ0bUcNNVZQ9RLlg==",
"cpu": [
"arm"
],
@@ -536,13 +535,13 @@
"android"
],
"engines": {
- "node": ">=12"
+ "node": ">=18"
}
},
"node_modules/@esbuild/android-arm64": {
- "version": "0.21.5",
- "resolved": "https://registry.npmjs.org/@esbuild/android-arm64/-/android-arm64-0.21.5.tgz",
- "integrity": "sha512-c0uX9VAUBQ7dTDCjq+wdyGLowMdtR/GoC2U5IYk/7D1H1JYC0qseD7+11iMP2mRLN9RcCMRcjC4YMclCzGwS/A==",
+ "version": "0.25.12",
+ "resolved": "https://registry.npmjs.org/@esbuild/android-arm64/-/android-arm64-0.25.12.tgz",
+ "integrity": "sha512-6AAmLG7zwD1Z159jCKPvAxZd4y/VTO0VkprYy+3N2FtJ8+BQWFXU+OxARIwA46c5tdD9SsKGZ/1ocqBS/gAKHg==",
"cpu": [
"arm64"
],
@@ -553,13 +552,13 @@
"android"
],
"engines": {
- "node": ">=12"
+ "node": ">=18"
}
},
"node_modules/@esbuild/android-x64": {
- "version": "0.21.5",
- "resolved": "https://registry.npmjs.org/@esbuild/android-x64/-/android-x64-0.21.5.tgz",
- "integrity": "sha512-D7aPRUUNHRBwHxzxRvp856rjUHRFW1SdQATKXH2hqA0kAZb1hKmi02OpYRacl0TxIGz/ZmXWlbZgjwWYaCakTA==",
+ "version": "0.25.12",
+ "resolved": "https://registry.npmjs.org/@esbuild/android-x64/-/android-x64-0.25.12.tgz",
+ "integrity": "sha512-5jbb+2hhDHx5phYR2By8GTWEzn6I9UqR11Kwf22iKbNpYrsmRB18aX/9ivc5cabcUiAT/wM+YIZ6SG9QO6a8kg==",
"cpu": [
"x64"
],
@@ -570,13 +569,13 @@
"android"
],
"engines": {
- "node": ">=12"
+ "node": ">=18"
}
},
"node_modules/@esbuild/darwin-arm64": {
- "version": "0.21.5",
- "resolved": "https://registry.npmjs.org/@esbuild/darwin-arm64/-/darwin-arm64-0.21.5.tgz",
- "integrity": "sha512-DwqXqZyuk5AiWWf3UfLiRDJ5EDd49zg6O9wclZ7kUMv2WRFr4HKjXp/5t8JZ11QbQfUS6/cRCKGwYhtNAY88kQ==",
+ "version": "0.25.12",
+ "resolved": "https://registry.npmjs.org/@esbuild/darwin-arm64/-/darwin-arm64-0.25.12.tgz",
+ "integrity": "sha512-N3zl+lxHCifgIlcMUP5016ESkeQjLj/959RxxNYIthIg+CQHInujFuXeWbWMgnTo4cp5XVHqFPmpyu9J65C1Yg==",
"cpu": [
"arm64"
],
@@ -587,13 +586,13 @@
"darwin"
],
"engines": {
- "node": ">=12"
+ "node": ">=18"
}
},
"node_modules/@esbuild/darwin-x64": {
- "version": "0.21.5",
- "resolved": "https://registry.npmjs.org/@esbuild/darwin-x64/-/darwin-x64-0.21.5.tgz",
- "integrity": "sha512-se/JjF8NlmKVG4kNIuyWMV/22ZaerB+qaSi5MdrXtd6R08kvs2qCN4C09miupktDitvh8jRFflwGFBQcxZRjbw==",
+ "version": "0.25.12",
+ "resolved": "https://registry.npmjs.org/@esbuild/darwin-x64/-/darwin-x64-0.25.12.tgz",
+ "integrity": "sha512-HQ9ka4Kx21qHXwtlTUVbKJOAnmG1ipXhdWTmNXiPzPfWKpXqASVcWdnf2bnL73wgjNrFXAa3yYvBSd9pzfEIpA==",
"cpu": [
"x64"
],
@@ -604,13 +603,13 @@
"darwin"
],
"engines": {
- "node": ">=12"
+ "node": ">=18"
}
},
"node_modules/@esbuild/freebsd-arm64": {
- "version": "0.21.5",
- "resolved": "https://registry.npmjs.org/@esbuild/freebsd-arm64/-/freebsd-arm64-0.21.5.tgz",
- "integrity": "sha512-5JcRxxRDUJLX8JXp/wcBCy3pENnCgBR9bN6JsY4OmhfUtIHe3ZW0mawA7+RDAcMLrMIZaf03NlQiX9DGyB8h4g==",
+ "version": "0.25.12",
+ "resolved": "https://registry.npmjs.org/@esbuild/freebsd-arm64/-/freebsd-arm64-0.25.12.tgz",
+ "integrity": "sha512-gA0Bx759+7Jve03K1S0vkOu5Lg/85dou3EseOGUes8flVOGxbhDDh/iZaoek11Y8mtyKPGF3vP8XhnkDEAmzeg==",
"cpu": [
"arm64"
],
@@ -621,13 +620,13 @@
"freebsd"
],
"engines": {
- "node": ">=12"
+ "node": ">=18"
}
},
"node_modules/@esbuild/freebsd-x64": {
- "version": "0.21.5",
- "resolved": "https://registry.npmjs.org/@esbuild/freebsd-x64/-/freebsd-x64-0.21.5.tgz",
- "integrity": "sha512-J95kNBj1zkbMXtHVH29bBriQygMXqoVQOQYA+ISs0/2l3T9/kj42ow2mpqerRBxDJnmkUDCaQT/dfNXWX/ZZCQ==",
+ "version": "0.25.12",
+ "resolved": "https://registry.npmjs.org/@esbuild/freebsd-x64/-/freebsd-x64-0.25.12.tgz",
+ "integrity": "sha512-TGbO26Yw2xsHzxtbVFGEXBFH0FRAP7gtcPE7P5yP7wGy7cXK2oO7RyOhL5NLiqTlBh47XhmIUXuGciXEqYFfBQ==",
"cpu": [
"x64"
],
@@ -638,13 +637,13 @@
"freebsd"
],
"engines": {
- "node": ">=12"
+ "node": ">=18"
}
},
"node_modules/@esbuild/linux-arm": {
- "version": "0.21.5",
- "resolved": "https://registry.npmjs.org/@esbuild/linux-arm/-/linux-arm-0.21.5.tgz",
- "integrity": "sha512-bPb5AHZtbeNGjCKVZ9UGqGwo8EUu4cLq68E95A53KlxAPRmUyYv2D6F0uUI65XisGOL1hBP5mTronbgo+0bFcA==",
+ "version": "0.25.12",
+ "resolved": "https://registry.npmjs.org/@esbuild/linux-arm/-/linux-arm-0.25.12.tgz",
+ "integrity": "sha512-lPDGyC1JPDou8kGcywY0YILzWlhhnRjdof3UlcoqYmS9El818LLfJJc3PXXgZHrHCAKs/Z2SeZtDJr5MrkxtOw==",
"cpu": [
"arm"
],
@@ -655,13 +654,13 @@
"linux"
],
"engines": {
- "node": ">=12"
+ "node": ">=18"
}
},
"node_modules/@esbuild/linux-arm64": {
- "version": "0.21.5",
- "resolved": "https://registry.npmjs.org/@esbuild/linux-arm64/-/linux-arm64-0.21.5.tgz",
- "integrity": "sha512-ibKvmyYzKsBeX8d8I7MH/TMfWDXBF3db4qM6sy+7re0YXya+K1cem3on9XgdT2EQGMu4hQyZhan7TeQ8XkGp4Q==",
+ "version": "0.25.12",
+ "resolved": "https://registry.npmjs.org/@esbuild/linux-arm64/-/linux-arm64-0.25.12.tgz",
+ "integrity": "sha512-8bwX7a8FghIgrupcxb4aUmYDLp8pX06rGh5HqDT7bB+8Rdells6mHvrFHHW2JAOPZUbnjUpKTLg6ECyzvas2AQ==",
"cpu": [
"arm64"
],
@@ -672,13 +671,13 @@
"linux"
],
"engines": {
- "node": ">=12"
+ "node": ">=18"
}
},
"node_modules/@esbuild/linux-ia32": {
- "version": "0.21.5",
- "resolved": "https://registry.npmjs.org/@esbuild/linux-ia32/-/linux-ia32-0.21.5.tgz",
- "integrity": "sha512-YvjXDqLRqPDl2dvRODYmmhz4rPeVKYvppfGYKSNGdyZkA01046pLWyRKKI3ax8fbJoK5QbxblURkwK/MWY18Tg==",
+ "version": "0.25.12",
+ "resolved": "https://registry.npmjs.org/@esbuild/linux-ia32/-/linux-ia32-0.25.12.tgz",
+ "integrity": "sha512-0y9KrdVnbMM2/vG8KfU0byhUN+EFCny9+8g202gYqSSVMonbsCfLjUO+rCci7pM0WBEtz+oK/PIwHkzxkyharA==",
"cpu": [
"ia32"
],
@@ -689,13 +688,13 @@
"linux"
],
"engines": {
- "node": ">=12"
+ "node": ">=18"
}
},
"node_modules/@esbuild/linux-loong64": {
- "version": "0.21.5",
- "resolved": "https://registry.npmjs.org/@esbuild/linux-loong64/-/linux-loong64-0.21.5.tgz",
- "integrity": "sha512-uHf1BmMG8qEvzdrzAqg2SIG/02+4/DHB6a9Kbya0XDvwDEKCoC8ZRWI5JJvNdUjtciBGFQ5PuBlpEOXQj+JQSg==",
+ "version": "0.25.12",
+ "resolved": "https://registry.npmjs.org/@esbuild/linux-loong64/-/linux-loong64-0.25.12.tgz",
+ "integrity": "sha512-h///Lr5a9rib/v1GGqXVGzjL4TMvVTv+s1DPoxQdz7l/AYv6LDSxdIwzxkrPW438oUXiDtwM10o9PmwS/6Z0Ng==",
"cpu": [
"loong64"
],
@@ -706,13 +705,13 @@
"linux"
],
"engines": {
- "node": ">=12"
+ "node": ">=18"
}
},
"node_modules/@esbuild/linux-mips64el": {
- "version": "0.21.5",
- "resolved": "https://registry.npmjs.org/@esbuild/linux-mips64el/-/linux-mips64el-0.21.5.tgz",
- "integrity": "sha512-IajOmO+KJK23bj52dFSNCMsz1QP1DqM6cwLUv3W1QwyxkyIWecfafnI555fvSGqEKwjMXVLokcV5ygHW5b3Jbg==",
+ "version": "0.25.12",
+ "resolved": "https://registry.npmjs.org/@esbuild/linux-mips64el/-/linux-mips64el-0.25.12.tgz",
+ "integrity": "sha512-iyRrM1Pzy9GFMDLsXn1iHUm18nhKnNMWscjmp4+hpafcZjrr2WbT//d20xaGljXDBYHqRcl8HnxbX6uaA/eGVw==",
"cpu": [
"mips64el"
],
@@ -723,13 +722,13 @@
"linux"
],
"engines": {
- "node": ">=12"
+ "node": ">=18"
}
},
"node_modules/@esbuild/linux-ppc64": {
- "version": "0.21.5",
- "resolved": "https://registry.npmjs.org/@esbuild/linux-ppc64/-/linux-ppc64-0.21.5.tgz",
- "integrity": "sha512-1hHV/Z4OEfMwpLO8rp7CvlhBDnjsC3CttJXIhBi+5Aj5r+MBvy4egg7wCbe//hSsT+RvDAG7s81tAvpL2XAE4w==",
+ "version": "0.25.12",
+ "resolved": "https://registry.npmjs.org/@esbuild/linux-ppc64/-/linux-ppc64-0.25.12.tgz",
+ "integrity": "sha512-9meM/lRXxMi5PSUqEXRCtVjEZBGwB7P/D4yT8UG/mwIdze2aV4Vo6U5gD3+RsoHXKkHCfSxZKzmDssVlRj1QQA==",
"cpu": [
"ppc64"
],
@@ -740,13 +739,13 @@
"linux"
],
"engines": {
- "node": ">=12"
+ "node": ">=18"
}
},
"node_modules/@esbuild/linux-riscv64": {
- "version": "0.21.5",
- "resolved": "https://registry.npmjs.org/@esbuild/linux-riscv64/-/linux-riscv64-0.21.5.tgz",
- "integrity": "sha512-2HdXDMd9GMgTGrPWnJzP2ALSokE/0O5HhTUvWIbD3YdjME8JwvSCnNGBnTThKGEB91OZhzrJ4qIIxk/SBmyDDA==",
+ "version": "0.25.12",
+ "resolved": "https://registry.npmjs.org/@esbuild/linux-riscv64/-/linux-riscv64-0.25.12.tgz",
+ "integrity": "sha512-Zr7KR4hgKUpWAwb1f3o5ygT04MzqVrGEGXGLnj15YQDJErYu/BGg+wmFlIDOdJp0PmB0lLvxFIOXZgFRrdjR0w==",
"cpu": [
"riscv64"
],
@@ -757,13 +756,13 @@
"linux"
],
"engines": {
- "node": ">=12"
+ "node": ">=18"
}
},
"node_modules/@esbuild/linux-s390x": {
- "version": "0.21.5",
- "resolved": "https://registry.npmjs.org/@esbuild/linux-s390x/-/linux-s390x-0.21.5.tgz",
- "integrity": "sha512-zus5sxzqBJD3eXxwvjN1yQkRepANgxE9lgOW2qLnmr8ikMTphkjgXu1HR01K4FJg8h1kEEDAqDcZQtbrRnB41A==",
+ "version": "0.25.12",
+ "resolved": "https://registry.npmjs.org/@esbuild/linux-s390x/-/linux-s390x-0.25.12.tgz",
+ "integrity": "sha512-MsKncOcgTNvdtiISc/jZs/Zf8d0cl/t3gYWX8J9ubBnVOwlk65UIEEvgBORTiljloIWnBzLs4qhzPkJcitIzIg==",
"cpu": [
"s390x"
],
@@ -774,13 +773,13 @@
"linux"
],
"engines": {
- "node": ">=12"
+ "node": ">=18"
}
},
"node_modules/@esbuild/linux-x64": {
- "version": "0.21.5",
- "resolved": "https://registry.npmjs.org/@esbuild/linux-x64/-/linux-x64-0.21.5.tgz",
- "integrity": "sha512-1rYdTpyv03iycF1+BhzrzQJCdOuAOtaqHTWJZCWvijKD2N5Xu0TtVC8/+1faWqcP9iBCWOmjmhoH94dH82BxPQ==",
+ "version": "0.25.12",
+ "resolved": "https://registry.npmjs.org/@esbuild/linux-x64/-/linux-x64-0.25.12.tgz",
+ "integrity": "sha512-uqZMTLr/zR/ed4jIGnwSLkaHmPjOjJvnm6TVVitAa08SLS9Z0VM8wIRx7gWbJB5/J54YuIMInDquWyYvQLZkgw==",
"cpu": [
"x64"
],
@@ -791,13 +790,30 @@
"linux"
],
"engines": {
- "node": ">=12"
+ "node": ">=18"
+ }
+ },
+ "node_modules/@esbuild/netbsd-arm64": {
+ "version": "0.25.12",
+ "resolved": "https://registry.npmjs.org/@esbuild/netbsd-arm64/-/netbsd-arm64-0.25.12.tgz",
+ "integrity": "sha512-xXwcTq4GhRM7J9A8Gv5boanHhRa/Q9KLVmcyXHCTaM4wKfIpWkdXiMog/KsnxzJ0A1+nD+zoecuzqPmCRyBGjg==",
+ "cpu": [
+ "arm64"
+ ],
+ "dev": true,
+ "license": "MIT",
+ "optional": true,
+ "os": [
+ "netbsd"
+ ],
+ "engines": {
+ "node": ">=18"
}
},
"node_modules/@esbuild/netbsd-x64": {
- "version": "0.21.5",
- "resolved": "https://registry.npmjs.org/@esbuild/netbsd-x64/-/netbsd-x64-0.21.5.tgz",
- "integrity": "sha512-Woi2MXzXjMULccIwMnLciyZH4nCIMpWQAs049KEeMvOcNADVxo0UBIQPfSmxB3CWKedngg7sWZdLvLczpe0tLg==",
+ "version": "0.25.12",
+ "resolved": "https://registry.npmjs.org/@esbuild/netbsd-x64/-/netbsd-x64-0.25.12.tgz",
+ "integrity": "sha512-Ld5pTlzPy3YwGec4OuHh1aCVCRvOXdH8DgRjfDy/oumVovmuSzWfnSJg+VtakB9Cm0gxNO9BzWkj6mtO1FMXkQ==",
"cpu": [
"x64"
],
@@ -808,13 +824,30 @@
"netbsd"
],
"engines": {
- "node": ">=12"
+ "node": ">=18"
+ }
+ },
+ "node_modules/@esbuild/openbsd-arm64": {
+ "version": "0.25.12",
+ "resolved": "https://registry.npmjs.org/@esbuild/openbsd-arm64/-/openbsd-arm64-0.25.12.tgz",
+ "integrity": "sha512-fF96T6KsBo/pkQI950FARU9apGNTSlZGsv1jZBAlcLL1MLjLNIWPBkj5NlSz8aAzYKg+eNqknrUJ24QBybeR5A==",
+ "cpu": [
+ "arm64"
+ ],
+ "dev": true,
+ "license": "MIT",
+ "optional": true,
+ "os": [
+ "openbsd"
+ ],
+ "engines": {
+ "node": ">=18"
}
},
"node_modules/@esbuild/openbsd-x64": {
- "version": "0.21.5",
- "resolved": "https://registry.npmjs.org/@esbuild/openbsd-x64/-/openbsd-x64-0.21.5.tgz",
- "integrity": "sha512-HLNNw99xsvx12lFBUwoT8EVCsSvRNDVxNpjZ7bPn947b8gJPzeHWyNVhFsaerc0n3TsbOINvRP2byTZ5LKezow==",
+ "version": "0.25.12",
+ "resolved": "https://registry.npmjs.org/@esbuild/openbsd-x64/-/openbsd-x64-0.25.12.tgz",
+ "integrity": "sha512-MZyXUkZHjQxUvzK7rN8DJ3SRmrVrke8ZyRusHlP+kuwqTcfWLyqMOE3sScPPyeIXN/mDJIfGXvcMqCgYKekoQw==",
"cpu": [
"x64"
],
@@ -825,13 +858,30 @@
"openbsd"
],
"engines": {
- "node": ">=12"
+ "node": ">=18"
+ }
+ },
+ "node_modules/@esbuild/openharmony-arm64": {
+ "version": "0.25.12",
+ "resolved": "https://registry.npmjs.org/@esbuild/openharmony-arm64/-/openharmony-arm64-0.25.12.tgz",
+ "integrity": "sha512-rm0YWsqUSRrjncSXGA7Zv78Nbnw4XL6/dzr20cyrQf7ZmRcsovpcRBdhD43Nuk3y7XIoW2OxMVvwuRvk9XdASg==",
+ "cpu": [
+ "arm64"
+ ],
+ "dev": true,
+ "license": "MIT",
+ "optional": true,
+ "os": [
+ "openharmony"
+ ],
+ "engines": {
+ "node": ">=18"
}
},
"node_modules/@esbuild/sunos-x64": {
- "version": "0.21.5",
- "resolved": "https://registry.npmjs.org/@esbuild/sunos-x64/-/sunos-x64-0.21.5.tgz",
- "integrity": "sha512-6+gjmFpfy0BHU5Tpptkuh8+uw3mnrvgs+dSPQXQOv3ekbordwnzTVEb4qnIvQcYXq6gzkyTnoZ9dZG+D4garKg==",
+ "version": "0.25.12",
+ "resolved": "https://registry.npmjs.org/@esbuild/sunos-x64/-/sunos-x64-0.25.12.tgz",
+ "integrity": "sha512-3wGSCDyuTHQUzt0nV7bocDy72r2lI33QL3gkDNGkod22EsYl04sMf0qLb8luNKTOmgF/eDEDP5BFNwoBKH441w==",
"cpu": [
"x64"
],
@@ -842,13 +892,13 @@
"sunos"
],
"engines": {
- "node": ">=12"
+ "node": ">=18"
}
},
"node_modules/@esbuild/win32-arm64": {
- "version": "0.21.5",
- "resolved": "https://registry.npmjs.org/@esbuild/win32-arm64/-/win32-arm64-0.21.5.tgz",
- "integrity": "sha512-Z0gOTd75VvXqyq7nsl93zwahcTROgqvuAcYDUr+vOv8uHhNSKROyU961kgtCD1e95IqPKSQKH7tBTslnS3tA8A==",
+ "version": "0.25.12",
+ "resolved": "https://registry.npmjs.org/@esbuild/win32-arm64/-/win32-arm64-0.25.12.tgz",
+ "integrity": "sha512-rMmLrur64A7+DKlnSuwqUdRKyd3UE7oPJZmnljqEptesKM8wx9J8gx5u0+9Pq0fQQW8vqeKebwNXdfOyP+8Bsg==",
"cpu": [
"arm64"
],
@@ -859,13 +909,13 @@
"win32"
],
"engines": {
- "node": ">=12"
+ "node": ">=18"
}
},
"node_modules/@esbuild/win32-ia32": {
- "version": "0.21.5",
- "resolved": "https://registry.npmjs.org/@esbuild/win32-ia32/-/win32-ia32-0.21.5.tgz",
- "integrity": "sha512-SWXFF1CL2RVNMaVs+BBClwtfZSvDgtL//G/smwAc5oVK/UPu2Gu9tIaRgFmYFFKrmg3SyAjSrElf0TiJ1v8fYA==",
+ "version": "0.25.12",
+ "resolved": "https://registry.npmjs.org/@esbuild/win32-ia32/-/win32-ia32-0.25.12.tgz",
+ "integrity": "sha512-HkqnmmBoCbCwxUKKNPBixiWDGCpQGVsrQfJoVGYLPT41XWF8lHuE5N6WhVia2n4o5QK5M4tYr21827fNhi4byQ==",
"cpu": [
"ia32"
],
@@ -876,13 +926,13 @@
"win32"
],
"engines": {
- "node": ">=12"
+ "node": ">=18"
}
},
"node_modules/@esbuild/win32-x64": {
- "version": "0.21.5",
- "resolved": "https://registry.npmjs.org/@esbuild/win32-x64/-/win32-x64-0.21.5.tgz",
- "integrity": "sha512-tQd/1efJuzPC6rCFwEvLtci/xNFcTZknmXs98FYDfGE4wP9ClFV98nyKrzJKVPMhdDnjzLhdUyMX4PsQAPjwIw==",
+ "version": "0.25.12",
+ "resolved": "https://registry.npmjs.org/@esbuild/win32-x64/-/win32-x64-0.25.12.tgz",
+ "integrity": "sha512-alJC0uCZpTFrSL0CCDjcgleBXPnCrEAhTBILpeAp7M/OFgoqtAetfBzX0xM00MUsVVPpVjlPuMbREqnZCXaTnA==",
"cpu": [
"x64"
],
@@ -893,7 +943,7 @@
"win32"
],
"engines": {
- "node": ">=12"
+ "node": ">=18"
}
},
"node_modules/@jridgewell/gen-mapping": {
@@ -2252,6 +2302,17 @@
"@babel/types": "^7.28.2"
}
},
+ "node_modules/@types/chai": {
+ "version": "5.2.3",
+ "resolved": "https://registry.npmjs.org/@types/chai/-/chai-5.2.3.tgz",
+ "integrity": "sha512-Mw558oeA9fFbv65/y4mHtXDs9bPnFMZAL/jxdPFUpOHHIXX91mcgEHbS5Lahr+pwZFR8A7GQleRWeI6cGFC2UA==",
+ "dev": true,
+ "license": "MIT",
+ "dependencies": {
+ "@types/deep-eql": "*",
+ "assertion-error": "^2.0.1"
+ }
+ },
"node_modules/@types/d3-array": {
"version": "3.2.2",
"resolved": "https://registry.npmjs.org/@types/d3-array/-/d3-array-3.2.2.tgz",
@@ -2358,6 +2419,13 @@
"@types/ms": "*"
}
},
+ "node_modules/@types/deep-eql": {
+ "version": "4.0.2",
+ "resolved": "https://registry.npmjs.org/@types/deep-eql/-/deep-eql-4.0.2.tgz",
+ "integrity": "sha512-c9h9dVVMigMPc4bwTvC5dxqtqJZwQPePsWjPlpSOnojbor6pGqdk541lfA7AqFQr5pB1BRdq0juY9db81BwyFw==",
+ "dev": true,
+ "license": "MIT"
+ },
"node_modules/@types/estree": {
"version": "1.0.8",
"resolved": "https://registry.npmjs.org/@types/estree/-/estree-1.0.8.tgz",
@@ -2476,38 +2544,39 @@
}
},
"node_modules/@vitest/expect": {
- "version": "2.1.9",
- "resolved": "https://registry.npmjs.org/@vitest/expect/-/expect-2.1.9.tgz",
- "integrity": "sha512-UJCIkTBenHeKT1TTlKMJWy1laZewsRIzYighyYiJKZreqtdxSos/S1t+ktRMQWu2CKqaarrkeszJx1cgC5tGZw==",
+ "version": "3.2.6",
+ "resolved": "https://registry.npmjs.org/@vitest/expect/-/expect-3.2.6.tgz",
+ "integrity": "sha512-1+7q9BtaKzEmO+fmNT3kYvoNn5Y71XWAx2Q5HRim4tTVRQVRv4uJFAQ5FbK0OPUeNP/WmVCpxYxoJdvuHVjzBQ==",
"dev": true,
"license": "MIT",
"dependencies": {
- "@vitest/spy": "2.1.9",
- "@vitest/utils": "2.1.9",
- "chai": "^5.1.2",
- "tinyrainbow": "^1.2.0"
+ "@types/chai": "^5.2.2",
+ "@vitest/spy": "3.2.6",
+ "@vitest/utils": "3.2.6",
+ "chai": "^5.2.0",
+ "tinyrainbow": "^2.0.0"
},
"funding": {
"url": "https://opencollective.com/vitest"
}
},
"node_modules/@vitest/mocker": {
- "version": "2.1.9",
- "resolved": "https://registry.npmjs.org/@vitest/mocker/-/mocker-2.1.9.tgz",
- "integrity": "sha512-tVL6uJgoUdi6icpxmdrn5YNo3g3Dxv+IHJBr0GXHaEdTcw3F+cPKnsXFhli6nO+f/6SDKPHEK1UN+k+TQv0Ehg==",
+ "version": "3.2.6",
+ "resolved": "https://registry.npmjs.org/@vitest/mocker/-/mocker-3.2.6.tgz",
+ "integrity": "sha512-EZOrpDbkKotFAP7wPAQV1UIyoGOk4oX7ynWhBhLB7v+meMHbQhU16oPpIYGTTe4oFlhpryGpgpcZP/sin3hYuw==",
"dev": true,
"license": "MIT",
"dependencies": {
- "@vitest/spy": "2.1.9",
+ "@vitest/spy": "3.2.6",
"estree-walker": "^3.0.3",
- "magic-string": "^0.30.12"
+ "magic-string": "^0.30.17"
},
"funding": {
"url": "https://opencollective.com/vitest"
},
"peerDependencies": {
"msw": "^2.4.9",
- "vite": "^5.0.0"
+ "vite": "^5.0.0 || ^6.0.0 || ^7.0.0-0"
},
"peerDependenciesMeta": {
"msw": {
@@ -2519,70 +2588,71 @@
}
},
"node_modules/@vitest/pretty-format": {
- "version": "2.1.9",
- "resolved": "https://registry.npmjs.org/@vitest/pretty-format/-/pretty-format-2.1.9.tgz",
- "integrity": "sha512-KhRIdGV2U9HOUzxfiHmY8IFHTdqtOhIzCpd8WRdJiE7D/HUcZVD0EgQCVjm+Q9gkUXWgBvMmTtZgIG48wq7sOQ==",
+ "version": "3.2.6",
+ "resolved": "https://registry.npmjs.org/@vitest/pretty-format/-/pretty-format-3.2.6.tgz",
+ "integrity": "sha512-lb7XXXzmm2h2ASzFnRvQpDo6onT1NmMJA3tkGTWiBFtRJ9lxGY3d3mm/Apt36gej2bkkOVLL/yTOtufDaFa/jA==",
"dev": true,
"license": "MIT",
"dependencies": {
- "tinyrainbow": "^1.2.0"
+ "tinyrainbow": "^2.0.0"
},
"funding": {
"url": "https://opencollective.com/vitest"
}
},
"node_modules/@vitest/runner": {
- "version": "2.1.9",
- "resolved": "https://registry.npmjs.org/@vitest/runner/-/runner-2.1.9.tgz",
- "integrity": "sha512-ZXSSqTFIrzduD63btIfEyOmNcBmQvgOVsPNPe0jYtESiXkhd8u2erDLnMxmGrDCwHCCHE7hxwRDCT3pt0esT4g==",
+ "version": "3.2.6",
+ "resolved": "https://registry.npmjs.org/@vitest/runner/-/runner-3.2.6.tgz",
+ "integrity": "sha512-HYcoSj1w5tcgUnzoF0HcyaAQjpA1gj9ftUJ7iSJSuipc02jW9gKkigwZbjFldAfYHA1fa8UZVRftdMY5msWM9Q==",
"dev": true,
"license": "MIT",
"dependencies": {
- "@vitest/utils": "2.1.9",
- "pathe": "^1.1.2"
+ "@vitest/utils": "3.2.6",
+ "pathe": "^2.0.3",
+ "strip-literal": "^3.0.0"
},
"funding": {
"url": "https://opencollective.com/vitest"
}
},
"node_modules/@vitest/snapshot": {
- "version": "2.1.9",
- "resolved": "https://registry.npmjs.org/@vitest/snapshot/-/snapshot-2.1.9.tgz",
- "integrity": "sha512-oBO82rEjsxLNJincVhLhaxxZdEtV0EFHMK5Kmx5sJ6H9L183dHECjiefOAdnqpIgT5eZwT04PoggUnW88vOBNQ==",
+ "version": "3.2.6",
+ "resolved": "https://registry.npmjs.org/@vitest/snapshot/-/snapshot-3.2.6.tgz",
+ "integrity": "sha512-H+ZjNTWGpObenh0YnlBctAPnJSI20P81PL8BPzWpx54YXLLTm8hEsWawtcYLMrwvpK48hGxLLbCS+1KRXhsKhw==",
"dev": true,
"license": "MIT",
"dependencies": {
- "@vitest/pretty-format": "2.1.9",
- "magic-string": "^0.30.12",
- "pathe": "^1.1.2"
+ "@vitest/pretty-format": "3.2.6",
+ "magic-string": "^0.30.17",
+ "pathe": "^2.0.3"
},
"funding": {
"url": "https://opencollective.com/vitest"
}
},
"node_modules/@vitest/spy": {
- "version": "2.1.9",
- "resolved": "https://registry.npmjs.org/@vitest/spy/-/spy-2.1.9.tgz",
- "integrity": "sha512-E1B35FwzXXTs9FHNK6bDszs7mtydNi5MIfUWpceJ8Xbfb1gBMscAnwLbEu+B44ed6W3XjL9/ehLPHR1fkf1KLQ==",
+ "version": "3.2.6",
+ "resolved": "https://registry.npmjs.org/@vitest/spy/-/spy-3.2.6.tgz",
+ "integrity": "sha512-oq6BbH68WzcWmwtBrU9nqLeaXTR4XwJF7FSLkKEZo4i6eoXcrxjcwSuTvWBIRUTC6VC72nXYunzqgZA+IKdtxg==",
"dev": true,
"license": "MIT",
"dependencies": {
- "tinyspy": "^3.0.2"
+ "tinyspy": "^4.0.3"
},
"funding": {
"url": "https://opencollective.com/vitest"
}
},
"node_modules/@vitest/utils": {
- "version": "2.1.9",
- "resolved": "https://registry.npmjs.org/@vitest/utils/-/utils-2.1.9.tgz",
- "integrity": "sha512-v0psaMSkNJ3A2NMrUEHFRzJtDPFn+/VWZ5WxImB21T9fjucJRmS7xCS3ppEnARb9y11OAzaD+P2Ps+b+BGX5iQ==",
+ "version": "3.2.6",
+ "resolved": "https://registry.npmjs.org/@vitest/utils/-/utils-3.2.6.tgz",
+ "integrity": "sha512-lI23nIs4bnT3T8NIoh+vFaz5s2/DdP0Jgt2jxwgWljvwn82cLJtyi/If+fjFyoLMGIOz0U/fKvWE0d4jsNQEfg==",
"dev": true,
"license": "MIT",
"dependencies": {
- "@vitest/pretty-format": "2.1.9",
- "loupe": "^3.1.2",
- "tinyrainbow": "^1.2.0"
+ "@vitest/pretty-format": "3.2.6",
+ "loupe": "^3.1.4",
+ "tinyrainbow": "^2.0.0"
},
"funding": {
"url": "https://opencollective.com/vitest"
@@ -2758,15 +2828,6 @@
"dev": true,
"license": "MIT"
},
- "node_modules/argparse": {
- "version": "1.0.10",
- "resolved": "https://registry.npmjs.org/argparse/-/argparse-1.0.10.tgz",
- "integrity": "sha512-o5Roy6tNG4SL/FOkCAN6RzjiakZS25RLYFrcMttJqbdd8BWrnA+fGz57iN5Pb06pvBGvl5gQ0B48dJlslXvoTg==",
- "license": "MIT",
- "dependencies": {
- "sprintf-js": "~1.0.2"
- }
- },
"node_modules/aria-hidden": {
"version": "1.2.6",
"resolved": "https://registry.npmjs.org/aria-hidden/-/aria-hidden-1.2.6.tgz",
@@ -3734,9 +3795,9 @@
]
},
"node_modules/esbuild": {
- "version": "0.21.5",
- "resolved": "https://registry.npmjs.org/esbuild/-/esbuild-0.21.5.tgz",
- "integrity": "sha512-mg3OPMV4hXywwpoDxu3Qda5xCKQi+vCTZq8S9J/EpkhB2HzKXq4SNFZE3+NK93JYxc8VMSep+lOUSC/RVKaBqw==",
+ "version": "0.25.12",
+ "resolved": "https://registry.npmjs.org/esbuild/-/esbuild-0.25.12.tgz",
+ "integrity": "sha512-bbPBYYrtZbkt6Os6FiTLCTFxvq4tt3JKall1vRwshA3fdVztsLAatFaZobhkBC8/BrPetoa0oksYoKXoG4ryJg==",
"dev": true,
"hasInstallScript": true,
"license": "MIT",
@@ -3744,32 +3805,35 @@
"esbuild": "bin/esbuild"
},
"engines": {
- "node": ">=12"
+ "node": ">=18"
},
"optionalDependencies": {
- "@esbuild/aix-ppc64": "0.21.5",
- "@esbuild/android-arm": "0.21.5",
- "@esbuild/android-arm64": "0.21.5",
- "@esbuild/android-x64": "0.21.5",
- "@esbuild/darwin-arm64": "0.21.5",
- "@esbuild/darwin-x64": "0.21.5",
- "@esbuild/freebsd-arm64": "0.21.5",
- "@esbuild/freebsd-x64": "0.21.5",
- "@esbuild/linux-arm": "0.21.5",
- "@esbuild/linux-arm64": "0.21.5",
- "@esbuild/linux-ia32": "0.21.5",
- "@esbuild/linux-loong64": "0.21.5",
- "@esbuild/linux-mips64el": "0.21.5",
- "@esbuild/linux-ppc64": "0.21.5",
- "@esbuild/linux-riscv64": "0.21.5",
- "@esbuild/linux-s390x": "0.21.5",
- "@esbuild/linux-x64": "0.21.5",
- "@esbuild/netbsd-x64": "0.21.5",
- "@esbuild/openbsd-x64": "0.21.5",
- "@esbuild/sunos-x64": "0.21.5",
- "@esbuild/win32-arm64": "0.21.5",
- "@esbuild/win32-ia32": "0.21.5",
- "@esbuild/win32-x64": "0.21.5"
+ "@esbuild/aix-ppc64": "0.25.12",
+ "@esbuild/android-arm": "0.25.12",
+ "@esbuild/android-arm64": "0.25.12",
+ "@esbuild/android-x64": "0.25.12",
+ "@esbuild/darwin-arm64": "0.25.12",
+ "@esbuild/darwin-x64": "0.25.12",
+ "@esbuild/freebsd-arm64": "0.25.12",
+ "@esbuild/freebsd-x64": "0.25.12",
+ "@esbuild/linux-arm": "0.25.12",
+ "@esbuild/linux-arm64": "0.25.12",
+ "@esbuild/linux-ia32": "0.25.12",
+ "@esbuild/linux-loong64": "0.25.12",
+ "@esbuild/linux-mips64el": "0.25.12",
+ "@esbuild/linux-ppc64": "0.25.12",
+ "@esbuild/linux-riscv64": "0.25.12",
+ "@esbuild/linux-s390x": "0.25.12",
+ "@esbuild/linux-x64": "0.25.12",
+ "@esbuild/netbsd-arm64": "0.25.12",
+ "@esbuild/netbsd-x64": "0.25.12",
+ "@esbuild/openbsd-arm64": "0.25.12",
+ "@esbuild/openbsd-x64": "0.25.12",
+ "@esbuild/openharmony-arm64": "0.25.12",
+ "@esbuild/sunos-x64": "0.25.12",
+ "@esbuild/win32-arm64": "0.25.12",
+ "@esbuild/win32-ia32": "0.25.12",
+ "@esbuild/win32-x64": "0.25.12"
}
},
"node_modules/escalade": {
@@ -3794,19 +3858,6 @@
"url": "https://github.com/sponsors/sindresorhus"
}
},
- "node_modules/esprima": {
- "version": "4.0.1",
- "resolved": "https://registry.npmjs.org/esprima/-/esprima-4.0.1.tgz",
- "integrity": "sha512-eGuFFw7Upda+g4p+QHvnW0RyTX/SVeJBDM/gCtMARO0cLuT2HcEKnTPvhjV6aGeqrCB/sbNop0Kszm0jsaWU4A==",
- "license": "BSD-2-Clause",
- "bin": {
- "esparse": "bin/esparse.js",
- "esvalidate": "bin/esvalidate.js"
- },
- "engines": {
- "node": ">=4"
- }
- },
"node_modules/estree-util-is-identifier-name": {
"version": "3.0.0",
"resolved": "https://registry.npmjs.org/estree-util-is-identifier-name/-/estree-util-is-identifier-name-3.0.0.tgz",
@@ -3849,18 +3900,6 @@
"integrity": "sha512-fjquC59cD7CyW6urNXK0FBufkZcoiGG80wTuPujX590cB5Ttln20E2UB4S/WARVqhXffZl2LNgS+gQdPIIim/g==",
"license": "MIT"
},
- "node_modules/extend-shallow": {
- "version": "2.0.1",
- "resolved": "https://registry.npmjs.org/extend-shallow/-/extend-shallow-2.0.1.tgz",
- "integrity": "sha512-zCnTtlxNoAiDc3gqY2aYAWFx7XWWiasuF2K8Me5WbN8otHKTUKBwjPtNpRs/rbUZm7KxWAaNj7P1a/p52GbVug==",
- "license": "MIT",
- "dependencies": {
- "is-extendable": "^0.1.0"
- },
- "engines": {
- "node": ">=0.10.0"
- }
- },
"node_modules/fast-deep-equal": {
"version": "3.1.3",
"resolved": "https://registry.npmjs.org/fast-deep-equal/-/fast-deep-equal-3.1.3.tgz",
@@ -3974,17 +4013,17 @@
}
},
"node_modules/form-data": {
- "version": "4.0.5",
- "resolved": "https://registry.npmjs.org/form-data/-/form-data-4.0.5.tgz",
- "integrity": "sha512-8RipRLol37bNs2bhoV67fiTEvdTrbMUYcFTiy3+wuuOnUog2QBHCZWXDRijWQfAkhBj2Uf5UnVaiWwA5vdd82w==",
+ "version": "4.0.6",
+ "resolved": "https://registry.npmjs.org/form-data/-/form-data-4.0.6.tgz",
+ "integrity": "sha512-vKatAh4SlVfgbv+YtmhiRjhEMJsYpsG1Y2rMQtR+SVSbytsSD1YGzDIcrAJmdFec88u/+VoGmxnl+80gL1tRCQ==",
"dev": true,
"license": "MIT",
"dependencies": {
"asynckit": "^0.4.0",
"combined-stream": "^1.0.8",
"es-set-tostringtag": "^2.1.0",
- "hasown": "^2.0.2",
- "mime-types": "^2.1.12"
+ "hasown": "^2.0.4",
+ "mime-types": "^2.1.35"
},
"engines": {
"node": ">= 6"
@@ -4154,21 +4193,6 @@
"url": "https://github.com/sponsors/ljharb"
}
},
- "node_modules/gray-matter": {
- "version": "4.0.3",
- "resolved": "https://registry.npmjs.org/gray-matter/-/gray-matter-4.0.3.tgz",
- "integrity": "sha512-5v6yZd4JK3eMI3FqqCouswVqwugaA9r4dNZB1wwcmrD02QkV5H0y7XBQW8QwQqEaZY1pM9aqORSORhJRdNK44Q==",
- "license": "MIT",
- "dependencies": {
- "js-yaml": "^3.13.1",
- "kind-of": "^6.0.2",
- "section-matter": "^1.0.0",
- "strip-bom-string": "^1.0.0"
- },
- "engines": {
- "node": ">=6.0"
- }
- },
"node_modules/has-symbols": {
"version": "1.1.0",
"resolved": "https://registry.npmjs.org/has-symbols/-/has-symbols-1.1.0.tgz",
@@ -4199,9 +4223,9 @@
}
},
"node_modules/hasown": {
- "version": "2.0.3",
- "resolved": "https://registry.npmjs.org/hasown/-/hasown-2.0.3.tgz",
- "integrity": "sha512-ej4AhfhfL2Q2zpMmLo7U1Uv9+PyhIZpgQLGT1F9miIGmiCJIoCgSmczFdrc97mWT4kVY72KA+WnnhJ5pghSvSg==",
+ "version": "2.0.4",
+ "resolved": "https://registry.npmjs.org/hasown/-/hasown-2.0.4.tgz",
+ "integrity": "sha512-T2UbfbBEF32wiepXIsMlTW9+dDYC6wMh/t/vYA4tuOMKqWz/n3vr1NFSxQiyP+zk2mXsoMA/i/7qV6LKut1t1A==",
"dev": true,
"license": "MIT",
"dependencies": {
@@ -4506,15 +4530,6 @@
"url": "https://github.com/sponsors/wooorm"
}
},
- "node_modules/is-extendable": {
- "version": "0.1.1",
- "resolved": "https://registry.npmjs.org/is-extendable/-/is-extendable-0.1.1.tgz",
- "integrity": "sha512-5BMULNob1vgFX6EjQw5izWDxrecWK9AM72rugNr0TFldMOi0fj6Jk+zeKIt0xGj4cEfQIJth4w3OKWOJ4f+AFw==",
- "license": "MIT",
- "engines": {
- "node": ">=0.10.0"
- }
- },
"node_modules/is-extglob": {
"version": "2.1.1",
"resolved": "https://registry.npmjs.org/is-extglob/-/is-extglob-2.1.1.tgz",
@@ -4603,19 +4618,6 @@
"integrity": "sha512-RdJUflcE3cUzKiMqQgsCu06FPu9UdIJO0beYbPhHN4k6apgJtifcoCtT9bcxOpYBtpD2kCM6Sbzg4CausW/PKQ==",
"license": "MIT"
},
- "node_modules/js-yaml": {
- "version": "3.14.2",
- "resolved": "https://registry.npmjs.org/js-yaml/-/js-yaml-3.14.2.tgz",
- "integrity": "sha512-PMSmkqxr106Xa156c2M265Z+FTrPl+oxd/rgOQy2tijQeK5TxQ43psO1ZCwhVOSdnn+RzkzlRz/eY4BgJBYVpg==",
- "license": "MIT",
- "dependencies": {
- "argparse": "^1.0.7",
- "esprima": "^4.0.0"
- },
- "bin": {
- "js-yaml": "bin/js-yaml.js"
- }
- },
"node_modules/jsdom": {
"version": "25.0.1",
"resolved": "https://registry.npmjs.org/jsdom/-/jsdom-25.0.1.tgz",
@@ -4696,15 +4698,6 @@
"node": ">=12"
}
},
- "node_modules/kind-of": {
- "version": "6.0.3",
- "resolved": "https://registry.npmjs.org/kind-of/-/kind-of-6.0.3.tgz",
- "integrity": "sha512-dcS1ul+9tmeD95T+x28/ehLgd9mENa3LsvDTtzm3vyBEO7RPptvAD+t44WVXaUjTBRcrpFeFlC8WCruUR456hw==",
- "license": "MIT",
- "engines": {
- "node": ">=0.10.0"
- }
- },
"node_modules/lilconfig": {
"version": "3.1.3",
"resolved": "https://registry.npmjs.org/lilconfig/-/lilconfig-3.1.3.tgz",
@@ -5891,9 +5884,9 @@
"license": "MIT"
},
"node_modules/pathe": {
- "version": "1.1.2",
- "resolved": "https://registry.npmjs.org/pathe/-/pathe-1.1.2.tgz",
- "integrity": "sha512-whLdWMYL2TwI08hn8/ZqAbrVemu0LNaNNJZX73O6qaIdCTfXutsLhMkjdENX0qhsQ9uIimo4/aQOmXkoon2nDQ==",
+ "version": "2.0.3",
+ "resolved": "https://registry.npmjs.org/pathe/-/pathe-2.0.3.tgz",
+ "integrity": "sha512-WUjGcAqP1gQacoQe+OBJsFA7Ld4DyXuUIjZ5cc75cLHvJ7dtNsTugphxIADwspS+AraAUePCKrSVtPLFj/F88w==",
"dev": true,
"license": "MIT"
},
@@ -6833,19 +6826,6 @@
"loose-envify": "^1.1.0"
}
},
- "node_modules/section-matter": {
- "version": "1.0.0",
- "resolved": "https://registry.npmjs.org/section-matter/-/section-matter-1.0.0.tgz",
- "integrity": "sha512-vfD3pmTzGpufjScBh50YHKzEu2lxBWhVEHsNGoEXmCmn2hKGfeNLYMzCJpe8cD7gqX7TJluOVpBkAequ6dgMmA==",
- "license": "MIT",
- "dependencies": {
- "extend-shallow": "^2.0.1",
- "kind-of": "^6.0.0"
- },
- "engines": {
- "node": ">=4"
- }
- },
"node_modules/semver": {
"version": "6.3.1",
"resolved": "https://registry.npmjs.org/semver/-/semver-6.3.1.tgz",
@@ -6899,12 +6879,6 @@
"url": "https://github.com/sponsors/wooorm"
}
},
- "node_modules/sprintf-js": {
- "version": "1.0.3",
- "resolved": "https://registry.npmjs.org/sprintf-js/-/sprintf-js-1.0.3.tgz",
- "integrity": "sha512-D9cPgkvLlV3t3IzL0D0YLvGA9Ahk4PcvVwUbN0dSGr1aP0Nrt4AEnTUbuGvquEC0mA64Gqt1fzirlRs5ibXx8g==",
- "license": "BSD-3-Clause"
- },
"node_modules/stackback": {
"version": "0.0.2",
"resolved": "https://registry.npmjs.org/stackback/-/stackback-0.0.2.tgz",
@@ -6933,15 +6907,26 @@
"url": "https://github.com/sponsors/wooorm"
}
},
- "node_modules/strip-bom-string": {
- "version": "1.0.0",
- "resolved": "https://registry.npmjs.org/strip-bom-string/-/strip-bom-string-1.0.0.tgz",
- "integrity": "sha512-uCC2VHvQRYu+lMh4My/sFNmF2klFymLX1wHJeXnbEJERpV/ZsVuonzerjfrGpIGF7LBVa1O7i9kjiWvJiFck8g==",
+ "node_modules/strip-literal": {
+ "version": "3.1.0",
+ "resolved": "https://registry.npmjs.org/strip-literal/-/strip-literal-3.1.0.tgz",
+ "integrity": "sha512-8r3mkIM/2+PpjHoOtiAW8Rg3jJLHaV7xPwG+YRGrv6FP0wwk/toTpATxWYOW0BKdWwl82VT2tFYi5DlROa0Mxg==",
+ "dev": true,
"license": "MIT",
- "engines": {
- "node": ">=0.10.0"
+ "dependencies": {
+ "js-tokens": "^9.0.1"
+ },
+ "funding": {
+ "url": "https://github.com/sponsors/antfu"
}
},
+ "node_modules/strip-literal/node_modules/js-tokens": {
+ "version": "9.0.1",
+ "resolved": "https://registry.npmjs.org/js-tokens/-/js-tokens-9.0.1.tgz",
+ "integrity": "sha512-mxa9E9ITFOt0ban3j6L5MpjwegGz6lBQmM1IJkWeBZGcMxto50+eWdjC/52xDbS2vy0k7vIMK0Fe2wfL9OQSpQ==",
+ "dev": true,
+ "license": "MIT"
+ },
"node_modules/style-to-js": {
"version": "1.1.21",
"resolved": "https://registry.npmjs.org/style-to-js/-/style-to-js-1.1.21.tgz",
@@ -7171,9 +7156,9 @@
}
},
"node_modules/tinyrainbow": {
- "version": "1.2.0",
- "resolved": "https://registry.npmjs.org/tinyrainbow/-/tinyrainbow-1.2.0.tgz",
- "integrity": "sha512-weEDEq7Z5eTHPDh4xjX789+fHfF+P8boiFB+0vbWzpbnbsEr/GRaohi/uMKxg8RZMXnl1ItAi/IUHWMsjDV7kQ==",
+ "version": "2.0.0",
+ "resolved": "https://registry.npmjs.org/tinyrainbow/-/tinyrainbow-2.0.0.tgz",
+ "integrity": "sha512-op4nsTR47R6p0vMUUoYl/a+ljLFVtlfaXkLQmqfLR1qHma1h/ysYk4hEXZ880bf2CYgTskvTa/e196Vd5dDQXw==",
"dev": true,
"license": "MIT",
"engines": {
@@ -7181,9 +7166,9 @@
}
},
"node_modules/tinyspy": {
- "version": "3.0.2",
- "resolved": "https://registry.npmjs.org/tinyspy/-/tinyspy-3.0.2.tgz",
- "integrity": "sha512-n1cw8k1k0x4pgA2+9XrOkFydTerNcJ1zWCO5Nn9scWHTD+5tp8dghT2x1uduQePZTZgd3Tupf+x9BxJjeJi77Q==",
+ "version": "4.0.4",
+ "resolved": "https://registry.npmjs.org/tinyspy/-/tinyspy-4.0.4.tgz",
+ "integrity": "sha512-azl+t0z7pw/z958Gy9svOTuzqIk6xq+NSheJzn5MMWtWTFywIacg2wUlzKFGtt3cthx0r2SxMK0yzJOR0IES7Q==",
"dev": true,
"license": "MIT",
"engines": {
@@ -7531,22 +7516,25 @@
}
},
"node_modules/vite": {
- "version": "5.4.21",
- "resolved": "https://registry.npmjs.org/vite/-/vite-5.4.21.tgz",
- "integrity": "sha512-o5a9xKjbtuhY6Bi5S3+HvbRERmouabWbyUcpXXUA1u+GNUKoROi9byOJ8M0nHbHYHkYICiMlqxkg1KkYmm25Sw==",
+ "version": "6.4.3",
+ "resolved": "https://registry.npmjs.org/vite/-/vite-6.4.3.tgz",
+ "integrity": "sha512-NTKlcQjlAK7MlQoyb6LgaqHc8sso/pVyUJYWMws3jg21uTJw/LddqIFPcPqP6PzpgbIcZyKI85sFE4HBrQDA8A==",
"dev": true,
"license": "MIT",
"peer": true,
"dependencies": {
- "esbuild": "^0.21.3",
- "postcss": "^8.4.43",
- "rollup": "^4.20.0"
+ "esbuild": "^0.25.0",
+ "fdir": "^6.4.4",
+ "picomatch": "^4.0.2",
+ "postcss": "^8.5.3",
+ "rollup": "^4.34.9",
+ "tinyglobby": "^0.2.13"
},
"bin": {
"vite": "bin/vite.js"
},
"engines": {
- "node": "^18.0.0 || >=20.0.0"
+ "node": "^18.0.0 || ^20.0.0 || >=22.0.0"
},
"funding": {
"url": "https://github.com/vitejs/vite?sponsor=1"
@@ -7555,19 +7543,25 @@
"fsevents": "~2.3.3"
},
"peerDependencies": {
- "@types/node": "^18.0.0 || >=20.0.0",
+ "@types/node": "^18.0.0 || ^20.0.0 || >=22.0.0",
+ "jiti": ">=1.21.0",
"less": "*",
"lightningcss": "^1.21.0",
"sass": "*",
"sass-embedded": "*",
"stylus": "*",
"sugarss": "*",
- "terser": "^5.4.0"
+ "terser": "^5.16.0",
+ "tsx": "^4.8.1",
+ "yaml": "^2.4.2"
},
"peerDependenciesMeta": {
"@types/node": {
"optional": true
},
+ "jiti": {
+ "optional": true
+ },
"less": {
"optional": true
},
@@ -7588,74 +7582,116 @@
},
"terser": {
"optional": true
+ },
+ "tsx": {
+ "optional": true
+ },
+ "yaml": {
+ "optional": true
}
}
},
"node_modules/vite-node": {
- "version": "2.1.9",
- "resolved": "https://registry.npmjs.org/vite-node/-/vite-node-2.1.9.tgz",
- "integrity": "sha512-AM9aQ/IPrW/6ENLQg3AGY4K1N2TGZdR5e4gu/MmmR2xR3Ll1+dib+nook92g4TV3PXVyeyxdWwtaCAiUL0hMxA==",
+ "version": "3.2.4",
+ "resolved": "https://registry.npmjs.org/vite-node/-/vite-node-3.2.4.tgz",
+ "integrity": "sha512-EbKSKh+bh1E1IFxeO0pg1n4dvoOTt0UDiXMd/qn++r98+jPO1xtJilvXldeuQ8giIB5IkpjCgMleHMNEsGH6pg==",
"dev": true,
"license": "MIT",
"dependencies": {
"cac": "^6.7.14",
- "debug": "^4.3.7",
- "es-module-lexer": "^1.5.4",
- "pathe": "^1.1.2",
- "vite": "^5.0.0"
+ "debug": "^4.4.1",
+ "es-module-lexer": "^1.7.0",
+ "pathe": "^2.0.3",
+ "vite": "^5.0.0 || ^6.0.0 || ^7.0.0-0"
},
"bin": {
"vite-node": "vite-node.mjs"
},
"engines": {
- "node": "^18.0.0 || >=20.0.0"
+ "node": "^18.0.0 || ^20.0.0 || >=22.0.0"
},
"funding": {
"url": "https://opencollective.com/vitest"
}
},
+ "node_modules/vite/node_modules/fdir": {
+ "version": "6.5.0",
+ "resolved": "https://registry.npmjs.org/fdir/-/fdir-6.5.0.tgz",
+ "integrity": "sha512-tIbYtZbucOs0BRGqPJkshJUYdL+SDH7dVM8gjy+ERp3WAUjLEFJE+02kanyHtwjWOnwrKYBiwAmM0p4kLJAnXg==",
+ "dev": true,
+ "license": "MIT",
+ "engines": {
+ "node": ">=12.0.0"
+ },
+ "peerDependencies": {
+ "picomatch": "^3 || ^4"
+ },
+ "peerDependenciesMeta": {
+ "picomatch": {
+ "optional": true
+ }
+ }
+ },
+ "node_modules/vite/node_modules/picomatch": {
+ "version": "4.0.4",
+ "resolved": "https://registry.npmjs.org/picomatch/-/picomatch-4.0.4.tgz",
+ "integrity": "sha512-QP88BAKvMam/3NxH6vj2o21R6MjxZUAd6nlwAS/pnGvN9IVLocLHxGYIzFhg6fUQ+5th6P4dv4eW9jX3DSIj7A==",
+ "dev": true,
+ "license": "MIT",
+ "peer": true,
+ "engines": {
+ "node": ">=12"
+ },
+ "funding": {
+ "url": "https://github.com/sponsors/jonschlinkert"
+ }
+ },
"node_modules/vitest": {
- "version": "2.1.9",
- "resolved": "https://registry.npmjs.org/vitest/-/vitest-2.1.9.tgz",
- "integrity": "sha512-MSmPM9REYqDGBI8439mA4mWhV5sKmDlBKWIYbA3lRb2PTHACE0mgKwA8yQ2xq9vxDTuk4iPrECBAEW2aoFXY0Q==",
- "dev": true,
- "license": "MIT",
- "dependencies": {
- "@vitest/expect": "2.1.9",
- "@vitest/mocker": "2.1.9",
- "@vitest/pretty-format": "^2.1.9",
- "@vitest/runner": "2.1.9",
- "@vitest/snapshot": "2.1.9",
- "@vitest/spy": "2.1.9",
- "@vitest/utils": "2.1.9",
- "chai": "^5.1.2",
- "debug": "^4.3.7",
- "expect-type": "^1.1.0",
- "magic-string": "^0.30.12",
- "pathe": "^1.1.2",
- "std-env": "^3.8.0",
+ "version": "3.2.6",
+ "resolved": "https://registry.npmjs.org/vitest/-/vitest-3.2.6.tgz",
+ "integrity": "sha512-xejya+bT/j/+R/AGa1XOfRxLmNUlLtlwjRsFUILF+xHfzElmGcmFydy2gqqIrd62ptIEfwVMofd19uNWD9L7Nw==",
+ "dev": true,
+ "license": "MIT",
+ "dependencies": {
+ "@types/chai": "^5.2.2",
+ "@vitest/expect": "3.2.6",
+ "@vitest/mocker": "3.2.6",
+ "@vitest/pretty-format": "^3.2.6",
+ "@vitest/runner": "3.2.6",
+ "@vitest/snapshot": "3.2.6",
+ "@vitest/spy": "3.2.6",
+ "@vitest/utils": "3.2.6",
+ "chai": "^5.2.0",
+ "debug": "^4.4.1",
+ "expect-type": "^1.2.1",
+ "magic-string": "^0.30.17",
+ "pathe": "^2.0.3",
+ "picomatch": "^4.0.2",
+ "std-env": "^3.9.0",
"tinybench": "^2.9.0",
- "tinyexec": "^0.3.1",
- "tinypool": "^1.0.1",
- "tinyrainbow": "^1.2.0",
- "vite": "^5.0.0",
- "vite-node": "2.1.9",
+ "tinyexec": "^0.3.2",
+ "tinyglobby": "^0.2.14",
+ "tinypool": "^1.1.1",
+ "tinyrainbow": "^2.0.0",
+ "vite": "^5.0.0 || ^6.0.0 || ^7.0.0-0",
+ "vite-node": "3.2.4",
"why-is-node-running": "^2.3.0"
},
"bin": {
"vitest": "vitest.mjs"
},
"engines": {
- "node": "^18.0.0 || >=20.0.0"
+ "node": "^18.0.0 || ^20.0.0 || >=22.0.0"
},
"funding": {
"url": "https://opencollective.com/vitest"
},
"peerDependencies": {
"@edge-runtime/vm": "*",
- "@types/node": "^18.0.0 || >=20.0.0",
- "@vitest/browser": "2.1.9",
- "@vitest/ui": "2.1.9",
+ "@types/debug": "^4.1.12",
+ "@types/node": "^18.0.0 || ^20.0.0 || >=22.0.0",
+ "@vitest/browser": "3.2.6",
+ "@vitest/ui": "3.2.6",
"happy-dom": "*",
"jsdom": "*"
},
@@ -7663,6 +7699,9 @@
"@edge-runtime/vm": {
"optional": true
},
+ "@types/debug": {
+ "optional": true
+ },
"@types/node": {
"optional": true
},
@@ -7680,6 +7719,19 @@
}
}
},
+ "node_modules/vitest/node_modules/picomatch": {
+ "version": "4.0.4",
+ "resolved": "https://registry.npmjs.org/picomatch/-/picomatch-4.0.4.tgz",
+ "integrity": "sha512-QP88BAKvMam/3NxH6vj2o21R6MjxZUAd6nlwAS/pnGvN9IVLocLHxGYIzFhg6fUQ+5th6P4dv4eW9jX3DSIj7A==",
+ "dev": true,
+ "license": "MIT",
+ "engines": {
+ "node": ">=12"
+ },
+ "funding": {
+ "url": "https://github.com/sponsors/jonschlinkert"
+ }
+ },
"node_modules/w3c-xmlserializer": {
"version": "5.0.0",
"resolved": "https://registry.npmjs.org/w3c-xmlserializer/-/w3c-xmlserializer-5.0.0.tgz",
@@ -7759,9 +7811,9 @@
}
},
"node_modules/ws": {
- "version": "8.20.0",
- "resolved": "https://registry.npmjs.org/ws/-/ws-8.20.0.tgz",
- "integrity": "sha512-sAt8BhgNbzCtgGbt2OxmpuryO63ZoDk/sqaB/znQm94T4fCEsy/yV+7CdC1kJhOU9lboAEU7R3kquuycDoibVA==",
+ "version": "8.21.0",
+ "resolved": "https://registry.npmjs.org/ws/-/ws-8.21.0.tgz",
+ "integrity": "sha512-Vsp28b7DRcimFQvrqu2Wek3z1iYxDCWqHYB8Qsnk/S4RfaCQzPGPyBNuVjJV3cd6UiKtUtp6sNM77gWvzcCH+g==",
"dev": true,
"license": "MIT",
"engines": {
diff --git a/jarvis/ui/web/frontend/package.json b/jarvis/ui/web/frontend/package.json
index fbdb9a9c95..71aa10457c 100644
--- a/jarvis/ui/web/frontend/package.json
+++ b/jarvis/ui/web/frontend/package.json
@@ -27,7 +27,6 @@
"clsx": "^2.1.1",
"cmdk": "^1.1.1",
"framer-motion": "^12.38.0",
- "gray-matter": "^4.0.3",
"html-to-image": "^1.11.13",
"lucide-react": "^0.445.0",
"qrcode.react": "^4.2.0",
@@ -60,7 +59,7 @@
"tailwindcss": "^3.4.13",
"tailwindcss-animate": "^1.0.7",
"typescript": "^5.6.2",
- "vite": "^5.4.8",
- "vitest": "^2.1.1"
+ "vite": "^6.4.3",
+ "vitest": "^3.2.6"
}
}
diff --git a/jarvis/ui/web/frontend/public/jarvis-logo.png b/jarvis/ui/web/frontend/public/jarvis-logo.png
new file mode 100644
index 0000000000..454022005a
Binary files /dev/null and b/jarvis/ui/web/frontend/public/jarvis-logo.png differ
diff --git a/jarvis/ui/web/frontend/pythonw_n7xBZqO3aR.png b/jarvis/ui/web/frontend/pythonw_n7xBZqO3aR.png
new file mode 100644
index 0000000000..3aafbfd2c4
Binary files /dev/null and b/jarvis/ui/web/frontend/pythonw_n7xBZqO3aR.png differ
diff --git a/jarvis/ui/web/frontend/src/App.tsx b/jarvis/ui/web/frontend/src/App.tsx
index bb0ce63d78..1fdb7a11d7 100644
--- a/jarvis/ui/web/frontend/src/App.tsx
+++ b/jarvis/ui/web/frontend/src/App.tsx
@@ -4,6 +4,7 @@ import { useVoiceStatus } from "@/hooks/useVoiceStatus";
import { useAssistantNameSeed } from "@/hooks/useAssistantNameSeed";
import { Sidebar } from "@/components/layout/Sidebar";
import { TopBar } from "@/components/layout/TopBar";
+import { VoiceWarmingBanner } from "@/components/layout/VoiceWarmingBanner";
import { MainView } from "@/components/layout/MainView";
import { ToastLayer } from "@/components/ToastLayer";
import { JarvisDock } from "@/components/JarvisDock";
@@ -28,6 +29,7 @@ export default function App() {
<main className="relative z-10 flex min-w-0 flex-1 flex-col">
<TopBar />
+ <VoiceWarmingBanner />
<div className="min-h-0 flex-1">
<MainView />
</div>
diff --git a/jarvis/ui/web/frontend/src/__tests__/ws.test.ts b/jarvis/ui/web/frontend/src/__tests__/ws.test.ts
index 7de7da142d..c2396d165f 100644
--- a/jarvis/ui/web/frontend/src/__tests__/ws.test.ts
+++ b/jarvis/ui/web/frontend/src/__tests__/ws.test.ts
@@ -83,4 +83,30 @@ describe("WSClient", () => {
);
client.close();
});
+
+ it("passes the close code to onClose", async () => {
+ const onClose = vi.fn();
+ const client = new WSClient({ onClose });
+ client.connect();
+ await Promise.resolve();
+ MockWebSocket.last!.fire("close", { code: 1013 });
+ expect(onClose).toHaveBeenCalledWith(1013);
+ client.close();
+ });
+
+ it("retries fast (no backoff escalation) after a 1013 warming close", async () => {
+ vi.useFakeTimers();
+ try {
+ const client = new WSClient();
+ client.connect();
+ const first = MockWebSocket.last;
+ // Warming close → must reconnect at MIN_BACKOFF (500ms), not escalate.
+ first!.fire("close", { code: 1013 });
+ vi.advanceTimersByTime(500);
+ expect(MockWebSocket.last).not.toBe(first); // a new socket was opened
+ client.close();
+ } finally {
+ vi.useRealTimers();
+ }
+ });
});
diff --git a/jarvis/ui/web/frontend/src/components/BrainModelSelector.test.tsx b/jarvis/ui/web/frontend/src/components/BrainModelSelector.test.tsx
index 8939e4cb1a..80ec3e5745 100644
--- a/jarvis/ui/web/frontend/src/components/BrainModelSelector.test.tsx
+++ b/jarvis/ui/web/frontend/src/components/BrainModelSelector.test.tsx
@@ -11,7 +11,12 @@ vi.mock("@/store/events", () => ({
selector({ pushToast: vi.fn() }),
}));
+vi.mock("@/lib/openExternal", () => ({
+ openExternalUrl: vi.fn(),
+}));
+
import { BrainModelSelector } from "./BrainModelSelector";
+import { openExternalUrl } from "@/lib/openExternal";
const MODELS = {
provider: "gemini",
@@ -80,6 +85,160 @@ describe("BrainModelSelector", () => {
expect(screen.queryByText("gemini-3-flash-preview")).toBeNull();
});
+ it("matches a hyphenated id when the user types spaces (gpt 5.5)", async () => {
+ // OpenRouter ids use hyphens (openai/gpt-5.5); users naturally type
+ // "gpt 5.5". A naive substring search found nothing — the 2026-06-28 report.
+ const OR_MODELS = {
+ provider: "openrouter",
+ current_model: "",
+ models: [
+ { id: "openai/gpt-5.5", label: "OpenAI: GPT-5.5" },
+ { id: "openai/gpt-5.5-pro", label: "OpenAI: GPT-5.5 Pro" },
+ { id: "z-ai/glm-5.2", label: "Z.AI: GLM 5.2" },
+ ],
+ source: "live",
+ fetched_at: 1,
+ };
+ vi.stubGlobal(
+ "fetch",
+ vi.fn().mockImplementation(async (url: string) => {
+ if (String(url).includes("/models")) return { ok: true, json: async () => OR_MODELS };
+ return { ok: true, json: async () => ({}) };
+ }),
+ );
+ render(<BrainModelSelector providerId="openrouter" currentModel="" />);
+ await openDropdown();
+ const search = (await screen.findByLabelText(
+ "apikeys_model.search_placeholder",
+ )) as HTMLInputElement;
+ fireEvent.change(search, { target: { value: "gpt 5.5" } });
+ expect(await screen.findByText("OpenAI: GPT-5.5")).toBeTruthy();
+ // Unrelated model is filtered out.
+ expect(screen.queryByText("Z.AI: GLM 5.2")).toBeNull();
+ });
+
+ it("matches with no separators at all (gpt5.5pro)", async () => {
+ const OR_MODELS = {
+ provider: "openrouter",
+ current_model: "",
+ models: [
+ { id: "openai/gpt-5.5", label: "OpenAI: GPT-5.5" },
+ { id: "openai/gpt-5.5-pro", label: "OpenAI: GPT-5.5 Pro" },
+ ],
+ source: "live",
+ fetched_at: 1,
+ };
+ vi.stubGlobal(
+ "fetch",
+ vi.fn().mockImplementation(async (url: string) => {
+ if (String(url).includes("/models")) return { ok: true, json: async () => OR_MODELS };
+ return { ok: true, json: async () => ({}) };
+ }),
+ );
+ render(<BrainModelSelector providerId="openrouter" currentModel="" />);
+ await openDropdown();
+ const search = (await screen.findByLabelText(
+ "apikeys_model.search_placeholder",
+ )) as HTMLInputElement;
+ fireEvent.change(search, { target: { value: "gpt5.5pro" } });
+ expect(await screen.findByText("OpenAI: GPT-5.5 Pro")).toBeTruthy();
+ expect(screen.queryByText("OpenAI: GPT-5.5")).toBeNull();
+ });
+
+ it("shows ALL search hits, not just the first 80", async () => {
+ // A search must reach EVERY matching model — the old 80-row display cap hid
+ // the rest of a large OpenRouter catalog (user report: "can't search all
+ // models"). 120 models sharing a token; searching surfaces all of them.
+ const many = Array.from({ length: 120 }, (_, i) => ({
+ id: `vendor/model-${i}`,
+ label: `Vendor Model ${i}`,
+ }));
+ vi.stubGlobal(
+ "fetch",
+ vi.fn().mockImplementation(async (url: string) => {
+ if (String(url).includes("/models"))
+ return {
+ ok: true,
+ json: async () => ({
+ provider: "openrouter",
+ current_model: "",
+ models: many,
+ source: "live",
+ fetched_at: 1,
+ }),
+ };
+ return { ok: true, json: async () => ({}) };
+ }),
+ );
+ render(<BrainModelSelector providerId="openrouter" currentModel="" />);
+ await openDropdown();
+ const search = (await screen.findByLabelText(
+ "apikeys_model.search_placeholder",
+ )) as HTMLInputElement;
+ fireEvent.change(search, { target: { value: "vendor" } });
+ // The 119th match (well past the old 80-row cap) must be rendered.
+ expect(await screen.findByText("Vendor Model 119")).toBeTruthy();
+ });
+
+ it("shows the COMPLETE catalog on open, without typing (no display cap)", async () => {
+ // User mandate: the whole catalog must be visible/scrollable on open, not a
+ // truncated slice. 250 models; the 249th must render without any search.
+ const many = Array.from({ length: 250 }, (_, i) => ({
+ id: `vendor/model-${i}`,
+ label: `Vendor Model ${i}`,
+ }));
+ vi.stubGlobal(
+ "fetch",
+ vi.fn().mockImplementation(async (url: string) => {
+ if (String(url).includes("/models"))
+ return {
+ ok: true,
+ json: async () => ({
+ provider: "openrouter",
+ current_model: "",
+ models: many,
+ source: "live",
+ fetched_at: 1,
+ }),
+ };
+ return { ok: true, json: async () => ({}) };
+ }),
+ );
+ render(<BrainModelSelector providerId="openrouter" currentModel="" />);
+ await openDropdown();
+ expect(await screen.findByText("Vendor Model 249")).toBeTruthy();
+ });
+
+ it("links each OpenRouter model to its page via the external-link bridge", async () => {
+ const OR_MODELS = {
+ provider: "openrouter",
+ current_model: "",
+ models: [{ id: "openai/gpt-5.5", label: "OpenAI: GPT-5.5" }],
+ source: "live",
+ fetched_at: 1,
+ };
+ vi.stubGlobal(
+ "fetch",
+ vi.fn().mockImplementation(async (url: string) => {
+ if (String(url).includes("/models")) return { ok: true, json: async () => OR_MODELS };
+ return { ok: true, json: async () => ({}) };
+ }),
+ );
+ render(<BrainModelSelector providerId="openrouter" currentModel="" />);
+ await openDropdown();
+ const link = await screen.findByLabelText("apikeys_model.open_on_provider");
+ fireEvent.click(link);
+ expect(openExternalUrl).toHaveBeenCalledWith("https://openrouter.ai/openai/gpt-5.5");
+ });
+
+ it("shows no provider link for a direct provider (no per-model page)", async () => {
+ vi.stubGlobal("fetch", mockFetch());
+ render(<BrainModelSelector providerId="gemini" currentModel="" />);
+ await openDropdown();
+ await screen.findByText("gemini-3.1-pro-preview");
+ expect(screen.queryByLabelText("apikeys_model.open_on_provider")).toBeNull();
+ });
+
it("saves a model picked from the list via PUT", async () => {
const fetchMock = mockFetch();
vi.stubGlobal("fetch", fetchMock);
diff --git a/jarvis/ui/web/frontend/src/components/BrainModelSelector.tsx b/jarvis/ui/web/frontend/src/components/BrainModelSelector.tsx
index ac3c1f9b1f..f6af904b91 100644
--- a/jarvis/ui/web/frontend/src/components/BrainModelSelector.tsx
+++ b/jarvis/ui/web/frontend/src/components/BrainModelSelector.tsx
@@ -1,5 +1,14 @@
import { useEffect, useMemo, useRef, useState } from "react";
-import { AlertCircle, Check, ChevronDown, Loader2, RefreshCw, Search, XCircle } from "lucide-react";
+import {
+ AlertCircle,
+ Check,
+ ChevronDown,
+ ExternalLink,
+ Loader2,
+ RefreshCw,
+ Search,
+ XCircle,
+} from "lucide-react";
import {
getBrainProviderModels,
saveBrainProviderModel,
@@ -9,10 +18,24 @@ import {
type ProviderTestStatus,
} from "@/hooks/useProviders";
import { useEventStore } from "@/store/events";
+import { openExternalUrl } from "@/lib/openExternal";
import { cn } from "@/lib/utils";
import { useT } from "@/i18n";
-const MAX_VISIBLE = 80;
+/**
+ * The provider's own page for a model, so the user can see its details/pricing.
+ * Only OpenRouter exposes a stable per-model URL whose path IS the model id
+ * (`openrouter.ai/anthropic/claude-opus-4.8`). Direct providers (claude-api /
+ * openai / gemini) have no clean per-model page → no link (better than a dead
+ * or guessed one). Returns null when there is no reliable URL.
+ */
+function modelProviderUrl(providerId: string, modelId: string): string | null {
+ if (providerId === "openrouter" && modelId) {
+ return `https://openrouter.ai/${modelId}`;
+ }
+ return null;
+}
+
// Mirrors TEST_STATUS_TONE in ApiKeysView (kept local to avoid a circular import).
const STATUS_TONE: Record<ProviderTestStatus, string> = {
@@ -142,16 +165,31 @@ export function BrainModelSelector({
const matched = useMemo(() => {
const list = Array.isArray(models) ? models : [];
const q = query.trim().toLowerCase();
- return q
- ? list.filter(
- (m) => m.id.toLowerCase().includes(q) || m.label.toLowerCase().includes(q),
- )
- : list;
+ if (!q) return list;
+ // Separator-insensitive match: model ids use hyphens/slashes/dots
+ // (openai/gpt-5.5) but users type spaces ("gpt 5.5") or nothing
+ // ("gpt5.5"). Strip every non-alphanumeric char from both sides so the
+ // query matches regardless of separators, while still honouring a plain
+ // substring hit (e.g. searching a literal "/").
+ const squash = (s: string) => s.toLowerCase().replace(/[^a-z0-9]/g, "");
+ const sq = squash(query);
+ return list.filter((m) => {
+ const id = m.id.toLowerCase();
+ const label = m.label.toLowerCase();
+ return (
+ id.includes(q) ||
+ label.includes(q) ||
+ (sq.length > 0 && (squash(m.id).includes(sq) || squash(m.label).includes(sq)))
+ );
+ });
}, [models, query]);
const trimmed = query.trim();
const exactMatch = matched.some((m) => m.id === trimmed);
- const visible = matched.slice(0, MAX_VISIBLE);
+ // Show the COMPLETE catalog — every model is visible on open and every search
+ // hit is shown. The list lives in a scrollable container, so even OpenRouter's
+ // full ~340-model catalog is fully reachable without a display cap.
+ const visible = matched;
const pinnedLabel = models.find((m) => m.id === pinned)?.label ?? pinned;
async function save(value: string) {
@@ -254,30 +292,59 @@ export function BrainModelSelector({
</div>
<ul className="max-h-56 overflow-y-auto p-1 scrollbar-jarvis">
- {visible.map((m) => (
- <li key={m.id}>
- <button
- type="button"
- onClick={() => void save(m.id)}
- className={cn(
- "flex w-full items-center justify-between gap-2 rounded px-2 py-1.5 text-left hover:bg-accent",
- m.id === pinned && "bg-primary/10",
- )}
- >
- <span className="flex min-w-0 items-center gap-1.5 truncate text-xs">
- {m.label}
- {recommendedModel && m.id === recommendedModel && (
- <span className="shrink-0 rounded-full bg-primary/15 px-1.5 py-0.5 text-[9px] uppercase tracking-wide text-primary">
- {t("apikeys_model.recommended_tag")}
+ {visible.map((m) => {
+ const link = modelProviderUrl(providerId, m.id);
+ const isPinned = m.id === pinned;
+ return (
+ <li key={m.id}>
+ {/* Row is a <div> (not a button) so the external-link button can
+ sit beside the select button without nesting <button>s. The
+ hover/selected highlight lives on the row. Hover uses a soft
+ gold TINT (not the loud full-gold accent) so light text stays
+ readable — the maintainer's "too bright" complaint. */}
+ <div
+ className={cn(
+ "flex items-center rounded hover:bg-primary/10",
+ isPinned && "bg-primary/20",
+ )}
+ >
+ <button
+ type="button"
+ onClick={() => void save(m.id)}
+ className="flex min-w-0 flex-1 items-center justify-between gap-2 px-2 py-1.5 text-left"
+ >
+ <span
+ className={cn(
+ "flex min-w-0 items-center gap-1.5 truncate text-xs",
+ isPinned && "font-medium text-primary",
+ )}
+ >
+ {m.label}
+ {recommendedModel && m.id === recommendedModel && (
+ <span className="shrink-0 rounded-full bg-primary px-1.5 py-0.5 text-[9px] font-medium uppercase tracking-wide text-primary-foreground">
+ {t("apikeys_model.recommended_tag")}
+ </span>
+ )}
</span>
+ <span className="shrink-0 font-mono text-[10px] text-muted-foreground">
+ {m.id}
+ </span>
+ </button>
+ {link && (
+ <button
+ type="button"
+ onClick={() => void openExternalUrl(link)}
+ aria-label={t("apikeys_model.open_on_provider")}
+ title={t("apikeys_model.open_on_provider")}
+ className="mr-1 shrink-0 rounded p-1 text-muted-foreground transition-colors hover:text-primary"
+ >
+ <ExternalLink className="h-3 w-3" />
+ </button>
)}
- </span>
- <span className="shrink-0 font-mono text-[10px] text-muted-foreground">
- {m.id}
- </span>
- </button>
- </li>
- ))}
+ </div>
+ </li>
+ );
+ })}
{trimmed && !exactMatch && (
<li>
@@ -285,7 +352,7 @@ export function BrainModelSelector({
type="button"
data-testid="use-custom-row"
onClick={() => void save(trimmed)}
- className="flex w-full items-center gap-2 rounded px-2 py-1.5 text-left text-xs hover:bg-accent"
+ className="flex w-full items-center gap-2 rounded px-2 py-1.5 text-left text-xs hover:bg-primary/10"
>
<Check className="h-3 w-3 shrink-0 text-primary" />
{t("apikeys_model.use_custom").replace("{0}", trimmed)}
@@ -300,9 +367,9 @@ export function BrainModelSelector({
)}
</ul>
- {matched.length > MAX_VISIBLE && (
+ {matched.length > 0 && (
<div className="border-t border-border px-2.5 py-1 text-[10px] text-muted-foreground">
- {t("apikeys_model.more_hint").replace("{0}", String(matched.length - MAX_VISIBLE))}
+ {t("apikeys_model.count_hint").replace("{0}", String(matched.length))}
</div>
)}
</div>
diff --git a/jarvis/ui/web/frontend/src/components/ChatInput.test.tsx b/jarvis/ui/web/frontend/src/components/ChatInput.test.tsx
new file mode 100644
index 0000000000..e92a44f1a0
--- /dev/null
+++ b/jarvis/ui/web/frontend/src/components/ChatInput.test.tsx
@@ -0,0 +1,29 @@
+import { cleanup, render, screen } from "@testing-library/react";
+import { afterEach, beforeEach, describe, expect, test } from "vitest";
+
+import { ChatInput } from "@/components/ChatInput";
+import { useEventStore } from "@/store/events";
+
+describe("ChatInput offline/warming placeholder", () => {
+ beforeEach(() => {
+ useEventStore.setState({
+ connected: false,
+ wsWarming: true,
+ chatThinking: false,
+ dictating: false,
+ });
+ });
+ afterEach(() => cleanup());
+
+ test("shows the booting placeholder while warming", () => {
+ render(<ChatInput />);
+ const box = screen.getByPlaceholderText("Starting…") as HTMLTextAreaElement;
+ expect(box.disabled).toBe(true);
+ });
+
+ test("shows the offline placeholder when truly offline", () => {
+ useEventStore.setState({ connected: false, wsWarming: false });
+ render(<ChatInput />);
+ expect(screen.getByPlaceholderText("Offline")).toBeTruthy();
+ });
+});
diff --git a/jarvis/ui/web/frontend/src/components/ChatInput.tsx b/jarvis/ui/web/frontend/src/components/ChatInput.tsx
index 4e83b9afd6..f2dd2dc338 100644
--- a/jarvis/ui/web/frontend/src/components/ChatInput.tsx
+++ b/jarvis/ui/web/frontend/src/components/ChatInput.tsx
@@ -15,6 +15,7 @@ export function ChatInput() {
const t = useT();
const [value, setValue] = useState("");
const connected = useEventStore((s) => s.connected);
+ const wsWarming = useEventStore((s) => s.wsWarming);
const chatThinking = useEventStore((s) => s.chatThinking);
const setChatThinking = useEventStore((s) => s.setChatThinking);
// Most recent live reasoning step — the pill mirrors what the trace card
@@ -169,7 +170,13 @@ export function ChatInput() {
value={value}
onChange={(e) => setValue(e.target.value)}
onKeyDown={onKeyDown}
- placeholder={connected ? t("chats_view.input_placeholder") : t("voice_state.offline")}
+ placeholder={
+ connected
+ ? t("chats_view.input_placeholder")
+ : wsWarming
+ ? t("voice_state.booting")
+ : t("voice_state.offline")
+ }
disabled={!connected}
rows={2}
className="flex-1 resize-none rounded-md border border-input bg-background px-3 py-2 text-sm shadow-sm focus-visible:outline-none focus-visible:ring-1 focus-visible:ring-ring disabled:opacity-50"
diff --git a/jarvis/ui/web/frontend/src/components/SubagentSection.model.test.tsx b/jarvis/ui/web/frontend/src/components/JarvisAgentSection.model.test.tsx
similarity index 100%
rename from jarvis/ui/web/frontend/src/components/SubagentSection.model.test.tsx
rename to jarvis/ui/web/frontend/src/components/JarvisAgentSection.model.test.tsx
diff --git a/jarvis/ui/web/frontend/src/components/SubagentSection.tsx b/jarvis/ui/web/frontend/src/components/JarvisAgentSection.tsx
similarity index 53%
rename from jarvis/ui/web/frontend/src/components/SubagentSection.tsx
rename to jarvis/ui/web/frontend/src/components/JarvisAgentSection.tsx
index 7dc2c523df..0c32de3a30 100644
--- a/jarvis/ui/web/frontend/src/components/SubagentSection.tsx
+++ b/jarvis/ui/web/frontend/src/components/JarvisAgentSection.tsx
@@ -6,14 +6,19 @@ import { useEventStore } from "@/store/events";
import {
codexLogout,
loginAntigravity,
+ loginClaude,
logoutAntigravity,
+ logoutClaude,
saveSubagentModel,
startCodexLogin,
switchSubagentProvider,
type AntigravityStatus,
+ type Billing,
+ type ClaudeStatus,
type CodexStatus,
} from "@/hooks/useProviders";
import { BrainModelSelector } from "@/components/BrainModelSelector";
+import { ProviderBillingBadge } from "@/components/ProviderBillingBadge";
/**
* Subagent tier for the API-Keys view.
@@ -40,6 +45,10 @@ interface SubagentMappingRow {
env_fallback: string | null;
key_set: boolean;
is_active_brain: boolean;
+ /** How this subagent is billed — "api" (per token) / "subscription" /
+ * "subscription_or_api". Drives the billing badge so the API-vs-subscription
+ * distinction is visible right on the subagent cards. */
+ billing: Billing;
}
interface SubagentStatus {
@@ -76,22 +85,62 @@ const PROVIDER_LABELS: Record<string, string> = {
antigravity: "Antigravity (Google subscription)",
};
-export function SubagentSection() {
+/**
+ * Poll a CLI status endpoint after starting an external login flow, refreshing
+ * the section on each tick, until it reports `connected` or a timeout.
+ *
+ * Why: external CLI logins (Codex `codex login`, Antigravity Google sign-in)
+ * complete in a SEPARATE browser/console window AFTER the POST returns, so a
+ * single immediate refetch always reads the still-disconnected state. Without
+ * this poll the card stays "open" / locked until the user manually reloads —
+ * the exact "I connected Codex but can't select it" symptom.
+ */
+async function pollStatusUntilConnected(
+ statusUrl: string,
+ onTick: () => void | Promise<void>,
+ { maxMs = 120_000, intervalMs = 2_500 }: { maxMs?: number; intervalMs?: number } = {},
+): Promise<boolean> {
+ const deadline = Date.now() + maxMs;
+ while (Date.now() < deadline) {
+ await new Promise((r) => setTimeout(r, intervalMs));
+ await onTick();
+ try {
+ const res = await fetch(statusUrl);
+ if (res.ok) {
+ const data = await res.json();
+ if (data?.connected) return true;
+ }
+ } catch {
+ // transient (app restarting / network blip) — keep polling
+ }
+ }
+ return false;
+}
+
+export function SubagentSection({
+ hideHeader = false,
+}: {
+ /** Suppress the section header — used inside the API-Keys "Subagents" tab,
+ * whose category hero already shows the title (avoids a double label). */
+ hideHeader?: boolean;
+} = {}) {
const t = useT();
const [bridge, setBridge] = useState<SubagentStatus | null>(null);
const [codexStatus, setCodexStatus] = useState<CodexStatus | null>(null);
const [antigravityStatus, setAntigravityStatus] =
useState<AntigravityStatus | null>(null);
+ const [claudeStatus, setClaudeStatus] = useState<ClaudeStatus | null>(null);
const [error, setError] = useState<string | null>(null);
// Re-fetch on brain-switch / subagent-switch / secret-set so the active
// provider highlight + the per-provider "Key gesetzt" badges track live.
const reload = useCallback(async () => {
try {
- const [res, codexRes, antigravityRes] = await Promise.all([
+ const [res, codexRes, antigravityRes, claudeRes] = await Promise.all([
fetch("/api/openclaw/status"),
fetch("/api/codex/status").catch(() => null),
fetch("/api/antigravity/status").catch(() => null),
+ fetch("/api/claude/status").catch(() => null),
]);
if (!res.ok) throw new Error(`HTTP ${res.status}`);
const data: SubagentStatus = await res.json();
@@ -106,6 +155,11 @@ export function SubagentSection() {
} else {
setAntigravityStatus(null);
}
+ if (claudeRes?.ok) {
+ setClaudeStatus(await claudeRes.json());
+ } else {
+ setClaudeStatus(null);
+ }
setError(null);
} catch (e) {
setError((e as Error).message);
@@ -128,7 +182,7 @@ export function SubagentSection() {
if (error) {
return (
<section>
- <SectionHeader label={t("apikeys_view.tier_subagent")} />
+ {!hideHeader && <SectionHeader label={t("apikeys_view.tier_subagent")} />}
<p className="text-xs text-destructive">Status unavailable: {error}</p>
</section>
);
@@ -136,9 +190,26 @@ export function SubagentSection() {
if (!bridge) return null;
+ // Codex + Antigravity are subscription logins (OAuth) rendered as their own
+ // connection cards; their "Set active" control now lives ON those cards, so
+ // exclude them from the generic provider list to avoid a duplicate card per
+ // CLI (the confusing "no select button on the subscription" the user hit).
+ const codexRow = bridge.mapping.find((r) => r.jarvis === "openai-codex");
+ const antigravityRow = bridge.mapping.find((r) => r.jarvis === "antigravity");
+ // Claude is dual-billed (Claude Max subscription OR Anthropic API key) — it
+ // gets its own connection card showing the signed-in account, like Codex /
+ // Antigravity, so exclude it from the generic per-key provider list too.
+ const claudeRow = bridge.mapping.find((r) => r.jarvis === "claude-api");
+ const providerRows = bridge.mapping.filter(
+ (r) =>
+ r.jarvis !== "openai-codex" &&
+ r.jarvis !== "antigravity" &&
+ r.jarvis !== "claude-api",
+ );
+
return (
<section>
- <SectionHeader label={t("apikeys_view.tier_subagent")} />
+ {!hideHeader && <SectionHeader label={t("apikeys_view.tier_subagent")} />}
{/* The coupling is non-obvious: subagent providers have no key field of
their own — they reuse the Brain-provider keys set above. Spell it out
so users know where to add the key instead of looking for an input
@@ -160,20 +231,43 @@ export function SubagentSection() {
<li>
<SubagentModelCard status={bridge} onSaved={reload} />
</li>
- {bridge.mapping.some((row) => row.jarvis === "openai-codex") && (
+ {codexRow && (
<li>
- <CodexConnectionCard status={codexStatus} onChanged={reload} />
+ <CodexConnectionCard
+ status={codexStatus}
+ row={codexRow}
+ onChanged={reload}
+ />
</li>
)}
- {bridge.mapping.some((row) => row.jarvis === "antigravity") && (
+ {antigravityRow && (
<li>
<AntigravityConnectionCard
status={antigravityStatus}
+ row={antigravityRow}
+ onChanged={reload}
+ />
+ </li>
+ )}
+ {claudeRow && (
+ <li>
+ <ClaudeConnectionCard
+ status={claudeStatus}
+ row={claudeRow}
onChanged={reload}
/>
</li>
)}
- {bridge.mapping.map((row) => (
+ {claudeRow && (
+ <li>
+ <ClaudeApiCard
+ status={claudeStatus}
+ row={claudeRow}
+ onChanged={reload}
+ />
+ </li>
+ )}
+ {providerRows.map((row) => (
<li key={row.jarvis}>
<SubagentProviderCard row={row} onSwitched={reload} />
</li>
@@ -342,15 +436,19 @@ function BridgeCard({ status }: { status: SubagentStatus }) {
function CodexConnectionCard({
status,
+ row,
onChanged,
}: {
status: CodexStatus | null;
+ row: SubagentMappingRow | undefined;
onChanged: () => void | Promise<void>;
}) {
const pushToast = useEventStore((s) => s.pushToast);
const [pending, setPending] = useState(false);
+ const { activating, activate } = useSubagentActivate(row, onChanged);
const connected = Boolean(status?.connected);
const installed = status?.installed ?? false;
+ const isActive = Boolean(row?.is_active_brain);
const email =
status?.user_email ??
status?.account_label ??
@@ -366,8 +464,14 @@ function CodexConnectionCard({
setPending(true);
try {
await startCodexLogin();
- pushToast("info", "Codex login started");
+ pushToast("info", "Codex login started — finish it in the browser window");
await onChanged();
+ // The login finishes asynchronously in the spawned console/browser, so
+ // poll until the CLI reports connected; then the card flips to selectable
+ // on its own — no manual reload needed.
+ void pollStatusUntilConnected("/api/codex/status", onChanged).then((ok) => {
+ if (ok) pushToast("success", "Codex connected — now selectable as a subagent");
+ });
} catch (e) {
pushToast("error", (e as Error).message);
} finally {
@@ -389,12 +493,19 @@ function CodexConnectionCard({
}
return (
- <div className="card-outline space-y-3 p-4">
+ <div
+ className={cn(
+ "card-outline space-y-3 p-4 transition-colors",
+ isActive && "border-primary bg-primary/[0.06] ring-1 ring-primary/30",
+ )}
+ >
<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-medium">OpenAI Codex ChatGPT login</span>
- {connected ? (
+ <span className="font-medium">OpenAI Codex (Subscription)</span>
+ {isActive ? (
+ <span className="chip-yellow">active</span>
+ ) : connected ? (
<span className="rounded-full bg-emerald-500/10 px-2 py-0.5 text-[10px] uppercase tracking-wider text-emerald-600">
ready
</span>
@@ -403,6 +514,7 @@ function CodexConnectionCard({
open
</span>
)}
+ {row && <ProviderBillingBadge billing={row.billing} />}
</div>
<p className="mt-1 text-[11px] leading-relaxed text-muted-foreground">
{detail}
@@ -414,27 +526,39 @@ function CodexConnectionCard({
</p>
)}
</div>
- {connected ? (
- <button
- type="button"
- onClick={disconnect}
- disabled={pending}
- className="inline-flex shrink-0 items-center gap-1.5 rounded-md border border-border px-3 py-1.5 text-xs text-muted-foreground hover:text-foreground disabled:opacity-50"
- >
- <LogOut className="h-3.5 w-3.5" />
- Disconnect
- </button>
- ) : (
- <button
- type="button"
- onClick={connect}
- disabled={pending || !installed}
- className="inline-flex shrink-0 items-center gap-1.5 rounded-md bg-primary px-3 py-1.5 text-xs font-medium text-primary-foreground disabled:opacity-50"
- >
- <LogIn className="h-3.5 w-3.5" />
- Connect
- </button>
- )}
+ <div className="flex shrink-0 items-center gap-3">
+ {/* When connected, the same "Set active" control as the other
+ provider cards — so this subscription login is selectable right
+ here, not only via a duplicate card further down. */}
+ {connected && row && (
+ <SubagentActiveControl
+ row={row}
+ activating={activating}
+ onActivate={activate}
+ />
+ )}
+ {connected ? (
+ <button
+ type="button"
+ onClick={disconnect}
+ disabled={pending}
+ className="inline-flex shrink-0 items-center gap-1.5 rounded-md border border-border px-3 py-1.5 text-xs text-muted-foreground hover:text-foreground disabled:opacity-50"
+ >
+ <LogOut className="h-3.5 w-3.5" />
+ Disconnect
+ </button>
+ ) : (
+ <button
+ type="button"
+ onClick={connect}
+ disabled={pending || !installed}
+ className="inline-flex shrink-0 items-center gap-1.5 rounded-md bg-primary px-3 py-1.5 text-xs font-medium text-primary-foreground disabled:opacity-50"
+ >
+ <LogIn className="h-3.5 w-3.5" />
+ Connect
+ </button>
+ )}
+ </div>
</div>
</div>
);
@@ -442,15 +566,19 @@ function CodexConnectionCard({
function AntigravityConnectionCard({
status,
+ row,
onChanged,
}: {
status: AntigravityStatus | null;
+ row: SubagentMappingRow | undefined;
onChanged: () => void | Promise<void>;
}) {
const pushToast = useEventStore((s) => s.pushToast);
const [pending, setPending] = useState(false);
+ const { activating, activate } = useSubagentActivate(row, onChanged);
const connected = Boolean(status?.connected);
const installed = status?.installed ?? false;
+ const isActive = Boolean(row?.is_active_brain);
const detail = connected
? status?.user_email
? `Connected as ${status.user_email}`
@@ -461,8 +589,13 @@ function AntigravityConnectionCard({
setPending(true);
try {
await loginAntigravity();
- pushToast("info", "Google login started");
+ pushToast("info", "Google login started — finish it in the browser window");
await onChanged();
+ // Same as Codex: the Google sign-in completes asynchronously, so poll
+ // until agy reports connected and the card unlocks on its own.
+ void pollStatusUntilConnected("/api/antigravity/status", onChanged).then((ok) => {
+ if (ok) pushToast("success", "Antigravity connected — now selectable as a subagent");
+ });
} catch (e) {
pushToast("error", (e as Error).message);
} finally {
@@ -484,12 +617,19 @@ function AntigravityConnectionCard({
}
return (
- <div className="card-outline space-y-3 p-4">
+ <div
+ className={cn(
+ "card-outline space-y-3 p-4 transition-colors",
+ isActive && "border-primary bg-primary/[0.06] ring-1 ring-primary/30",
+ )}
+ >
<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-medium">Antigravity Google login</span>
- {connected ? (
+ <span className="font-medium">Antigravity (Subscription)</span>
+ {isActive ? (
+ <span className="chip-yellow">active</span>
+ ) : connected ? (
<span className="rounded-full bg-emerald-500/10 px-2 py-0.5 text-[10px] uppercase tracking-wider text-emerald-600">
ready
</span>
@@ -498,6 +638,7 @@ function AntigravityConnectionCard({
open
</span>
)}
+ {row && <ProviderBillingBadge billing={row.billing} />}
</div>
<p className="mt-1 text-[11px] leading-relaxed text-muted-foreground">
{detail}
@@ -509,60 +650,311 @@ function AntigravityConnectionCard({
</p>
)}
</div>
- {connected ? (
- <button
- type="button"
- onClick={disconnect}
- disabled={pending}
- className="inline-flex shrink-0 items-center gap-1.5 rounded-md border border-border px-3 py-1.5 text-xs text-muted-foreground hover:text-foreground disabled:opacity-50"
- >
- <LogOut className="h-3.5 w-3.5" />
- Disconnect
- </button>
- ) : (
- <button
- type="button"
- onClick={connect}
- disabled={pending || !installed}
- className="inline-flex shrink-0 items-center gap-1.5 rounded-md bg-primary px-3 py-1.5 text-xs font-medium text-primary-foreground disabled:opacity-50"
- >
- <LogIn className="h-3.5 w-3.5" />
- Connect
- </button>
- )}
+ <div className="flex shrink-0 items-center gap-3">
+ {connected && row && (
+ <SubagentActiveControl
+ row={row}
+ activating={activating}
+ onActivate={activate}
+ />
+ )}
+ {connected ? (
+ <button
+ type="button"
+ onClick={disconnect}
+ disabled={pending}
+ className="inline-flex shrink-0 items-center gap-1.5 rounded-md border border-border px-3 py-1.5 text-xs text-muted-foreground hover:text-foreground disabled:opacity-50"
+ >
+ <LogOut className="h-3.5 w-3.5" />
+ Disconnect
+ </button>
+ ) : (
+ <button
+ type="button"
+ onClick={connect}
+ disabled={pending || !installed}
+ className="inline-flex shrink-0 items-center gap-1.5 rounded-md bg-primary px-3 py-1.5 text-xs font-medium text-primary-foreground disabled:opacity-50"
+ >
+ <LogIn className="h-3.5 w-3.5" />
+ Connect
+ </button>
+ )}
+ </div>
+ </div>
+ </div>
+ );
+}
+
+function ClaudeConnectionCard({
+ status,
+ row,
+ onChanged,
+}: {
+ status: ClaudeStatus | null;
+ row: SubagentMappingRow | undefined;
+ onChanged: () => void | Promise<void>;
+}) {
+ const pushToast = useEventStore((s) => s.pushToast);
+ const [pending, setPending] = useState(false);
+ const { activating, activate } = useSubagentActivate(row, onChanged);
+ const connected = Boolean(status?.connected);
+ const installed = status?.installed ?? false;
+ // Claude has ONE subagent slug (claude-api) reached by EITHER the Claude Max
+ // OAuth login OR an Anthropic API key — split into two sibling cards (mirror
+ // of Codex/OpenAI + Antigravity/Gemini). This subscription card lights up only
+ // when claude-api is the active worker AND it is running over the OAuth login
+ // (mode != "api_key"); the API key card owns the api_key mode. So exactly one
+ // of the two ever shows "active".
+ const isActive = Boolean(row?.is_active_brain) && status?.mode !== "api_key";
+ // A subscription login shows the signed-in account + tier ("Connected as
+ // ruben@… · Claude Max"); not connected shows how to sign in. The API-key
+ // alternative now lives on its own card below, not here.
+ const detail = connected
+ ? status?.user_email
+ ? `Connected as ${status.user_email}${
+ status.account_label ? ` · ${status.account_label}` : ""
+ }`
+ : status?.message || "Connected"
+ : status?.message || "Claude login not connected";
+
+ async function connect() {
+ setPending(true);
+ try {
+ await loginClaude();
+ pushToast("info", "Claude login started — finish it in the terminal window");
+ await onChanged();
+ // The sign-in finishes asynchronously in the spawned console, so poll
+ // until the CLI reports connected; the card then unlocks on its own.
+ void pollStatusUntilConnected("/api/claude/status", onChanged).then((ok) => {
+ if (ok) pushToast("success", "Claude connected — now selectable as a subagent");
+ });
+ } catch (e) {
+ pushToast("error", (e as Error).message);
+ } finally {
+ setPending(false);
+ }
+ }
+
+ async function disconnect() {
+ setPending(true);
+ try {
+ await logoutClaude();
+ pushToast("info", "Claude subscription disconnected");
+ await onChanged();
+ } catch (e) {
+ pushToast("error", (e as Error).message);
+ } finally {
+ setPending(false);
+ }
+ }
+
+ return (
+ <div
+ className={cn(
+ "card-outline space-y-3 p-4 transition-colors",
+ isActive && "border-primary bg-primary/[0.06] ring-1 ring-primary/30",
+ )}
+ >
+ <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-medium">Anthropic Claude (Subscription)</span>
+ {isActive ? (
+ <span className="chip-yellow">active</span>
+ ) : connected ? (
+ <span className="rounded-full bg-emerald-500/10 px-2 py-0.5 text-[10px] uppercase tracking-wider text-emerald-600">
+ ready
+ </span>
+ ) : (
+ <span className="rounded-full bg-muted px-2 py-0.5 text-[10px] uppercase tracking-wider text-muted-foreground">
+ open
+ </span>
+ )}
+ {/* Split card: this one is the subscription login only. */}
+ <ProviderBillingBadge billing="subscription" />
+ </div>
+ <p className="mt-1 text-[11px] leading-relaxed text-muted-foreground">
+ {detail}
+ </p>
+ {!installed && (
+ <p className="mt-2 flex items-center gap-1.5 text-[11px] text-amber-600">
+ <Terminal className="h-3 w-3 shrink-0" />
+ <span>Install the Claude CLI before connecting.</span>
+ </p>
+ )}
+ </div>
+ <div className="flex shrink-0 items-center gap-3">
+ {connected && row && (
+ <SubagentActiveControl
+ row={row}
+ active={isActive}
+ activating={activating}
+ onActivate={activate}
+ />
+ )}
+ {connected ? (
+ <button
+ type="button"
+ onClick={disconnect}
+ disabled={pending}
+ className="inline-flex shrink-0 items-center gap-1.5 rounded-md border border-border px-3 py-1.5 text-xs text-muted-foreground hover:text-foreground disabled:opacity-50"
+ >
+ <LogOut className="h-3.5 w-3.5" />
+ Disconnect
+ </button>
+ ) : (
+ <button
+ type="button"
+ onClick={connect}
+ disabled={pending || !installed}
+ className="inline-flex shrink-0 items-center gap-1.5 rounded-md bg-primary px-3 py-1.5 text-xs font-medium text-primary-foreground disabled:opacity-50"
+ >
+ <LogIn className="h-3.5 w-3.5" />
+ Connect
+ </button>
+ )}
+ </div>
</div>
</div>
);
}
/**
- * One sub-agent-capable provider, styled to match the `ProviderCard` in
- * `ApiKeysView` (header + badge + id·auth sub-line + active highlight + the
- * "Set active" radio). Clicking the card or the radio switches the Heavy-Task
- * subagent provider via `POST /api/subagent/switch` (3-layer persist). The key
- * itself is managed by the brain-provider card above; a provider with no key
- * cannot be activated (warning toast instead of a silent no-op).
+ * The Anthropic Claude (API) card — the per-token sibling of the subscription
+ * card above, built to behave EXACTLY like the OpenAI / Google Gemini subagent
+ * cards (`SubagentProviderCard`): there is NO key field here. The Anthropic API
+ * key is entered ONCE on the "Claude (API-Key)" brain provider above, and this
+ * card just reflects whether that key is set (`row.key_set`) and lets the user
+ * pick Claude-on-the-key as the heavy-task worker — locked with a pointer to the
+ * Brain section until the key exists, exactly like OpenAI/Gemini.
+ *
+ * Claude has ONE subagent slug (claude-api) reached by either auth, so this card
+ * and the subscription card both drive `useSubagentActivate(row)`. To keep only
+ * one of the two lit, "active" here means claude-api is the active worker AND it
+ * is running over the API key (status mode === "api_key"); the subscription card
+ * owns every other mode.
*/
-function SubagentProviderCard({
+function ClaudeApiCard({
+ status,
row,
- onSwitched,
+ onChanged,
}: {
- row: SubagentMappingRow;
- onSwitched: () => void | Promise<void>;
+ status: ClaudeStatus | null;
+ row: SubagentMappingRow | undefined;
+ onChanged: () => void | Promise<void>;
}) {
- const label = PROVIDER_LABELS[row.jarvis] ?? row.jarvis;
+ const { activating, activate } = useSubagentActivate(row, onChanged);
+ // Mirror the other API cards: ready/locked tracks the stored brain key.
+ const keySet = Boolean(row?.key_set);
+ const isActive = Boolean(row?.is_active_brain) && status?.mode === "api_key";
+
+ // Click anywhere on the card activates — except the radio/label (own handler)
+ // so a single user click never fires activate() twice (mirror of the others).
+ function handleCardActivate(e: React.MouseEvent<HTMLDivElement>) {
+ const target = e.target as HTMLElement | null;
+ if (target && (target.closest("input") || target.closest("label"))) {
+ return;
+ }
+ void activate();
+ }
+
+ return (
+ <div
+ onClick={handleCardActivate}
+ onDoubleClick={handleCardActivate}
+ title={
+ isActive
+ ? "This subagent provider is active"
+ : keySet
+ ? "Activate this subagent provider"
+ : "Add the Claude API key in the Brain section first"
+ }
+ className={cn(
+ "card-outline space-y-2 p-4 transition-colors",
+ isActive
+ ? "border-primary bg-primary/[0.06] ring-1 ring-primary/30"
+ : keySet
+ ? "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-medium">Anthropic Claude (API)</span>
+ {isActive ? (
+ <span className="chip-yellow">active</span>
+ ) : keySet ? (
+ <span className="rounded-full bg-emerald-500/10 px-2 py-0.5 text-[10px] uppercase tracking-wider text-emerald-600">
+ ready
+ </span>
+ ) : (
+ <span className="rounded-full bg-muted px-2 py-0.5 text-[10px] uppercase tracking-wider text-muted-foreground">
+ open
+ </span>
+ )}
+ <ProviderBillingBadge billing="api" />
+ </div>
+ {row && (
+ <p className="mt-0.5 text-[11px] text-muted-foreground">
+ <code className="font-mono">
+ {row.jarvis} → {row.openclaw}
+ </code>
+ {" · "}
+ <span className="font-mono">
+ {row.env_var}
+ {row.env_fallback && ` / ${row.env_fallback}`}
+ </span>
+ </p>
+ )}
+ </div>
+
+ {row && (
+ <SubagentActiveControl
+ row={row}
+ active={isActive}
+ activating={activating}
+ onActivate={activate}
+ />
+ )}
+ </div>
+
+ {!keySet && (
+ <p className="flex items-center gap-1.5 text-[11px] text-amber-600">
+ <Lock className="h-3 w-3 shrink-0" />
+ <span>
+ Locked &mdash; add the <strong>Claude (API-Key)</strong> key in the
+ Brain section above to unlock it.
+ </span>
+ </p>
+ )}
+ </div>
+ );
+}
+
+/**
+ * Shared "activate this subagent provider" action (POST /api/subagent/switch,
+ * 3-layer persist). Used by the generic provider cards AND the Codex /
+ * Antigravity subscription cards, so every selectable card behaves identically
+ * — including the subscription logins, which previously had no "Set active".
+ */
+function useSubagentActivate(
+ row: SubagentMappingRow | undefined,
+ onSwitched: () => void | Promise<void>,
+) {
const [activating, setActivating] = useState(false);
const pushToast = useEventStore((s) => s.pushToast);
- async function activate() {
- if (row.is_active_brain || activating) return;
+ const activate = useCallback(async () => {
+ if (!row || row.is_active_brain || activating) return;
+ const label = PROVIDER_LABELS[row.jarvis] ?? row.jarvis;
if (!row.key_set) {
pushToast(
"warning",
row.jarvis === "openai-codex"
- ? `${label}: connect the ChatGPT login above first.`
+ ? `${label}: connect the ChatGPT login first.`
: row.jarvis === "antigravity"
- ? `${label}: connect the Google login above first.`
+ ? `${label}: connect the Google login first.`
: `${label}: set the API key on the brain provider above first.`,
);
return;
@@ -570,9 +962,7 @@ function SubagentProviderCard({
setActivating(true);
try {
const result = await switchSubagentProvider(row.jarvis);
- const note = result.restart_required
- ? " (active from next restart)"
- : "";
+ const note = result.restart_required ? " (active from next restart)" : "";
pushToast("success", `Subagent → ${label}${note}`);
window.dispatchEvent(new CustomEvent("jarvis:subagent-switched"));
await onSwitched();
@@ -581,7 +971,28 @@ function SubagentProviderCard({
} finally {
setActivating(false);
}
- }
+ }, [row, activating, pushToast, onSwitched]);
+
+ return { activating, activate };
+}
+
+/**
+ * One sub-agent-capable provider, styled to match the `ProviderCard` in
+ * `ApiKeysView` (header + badge + id·auth sub-line + active highlight + the
+ * "Set active" radio). Clicking the card or the radio switches the Heavy-Task
+ * subagent provider via `POST /api/subagent/switch` (3-layer persist). The key
+ * itself is managed by the brain-provider card above; a provider with no key
+ * cannot be activated (warning toast instead of a silent no-op).
+ */
+function SubagentProviderCard({
+ row,
+ onSwitched,
+}: {
+ row: SubagentMappingRow;
+ onSwitched: () => void | Promise<void>;
+}) {
+ const label = PROVIDER_LABELS[row.jarvis] ?? row.jarvis;
+ const { activating, activate } = useSubagentActivate(row, onSwitched);
// Click anywhere on the card activates — except on the radio/label (which
// has its own handler) so a single user click never fires activate() twice.
@@ -618,6 +1029,7 @@ function SubagentProviderCard({
<div className="flex flex-wrap items-center gap-2">
<span className="font-medium">{label}</span>
<SubagentStatusBadge row={row} />
+ <ProviderBillingBadge billing={row.billing} />
</div>
<p className="mt-0.5 text-[11px] text-muted-foreground">
<code className="font-mono">
@@ -677,12 +1089,22 @@ function SubagentActiveControl({
row,
activating,
onActivate,
+ active,
}: {
row: SubagentMappingRow;
activating: boolean;
onActivate: () => void;
+ /**
+ * Explicit active state, overriding `row.is_active_brain`. The two Claude
+ * cards share ONE slug (claude-api), so the raw row flag would light BOTH
+ * radios at once. Each Claude card passes its mode-split flag here so only the
+ * card matching the live auth (subscription vs API key) shows "Active". Other
+ * cards omit it and fall back to the row flag.
+ */
+ active?: boolean;
}) {
- const labelTitle = row.is_active_brain
+ const isActive = active ?? row.is_active_brain;
+ const labelTitle = isActive
? "This subagent provider is active"
: row.key_set
? "Activate this subagent provider"
@@ -694,7 +1116,7 @@ function SubagentActiveControl({
onDoubleClick={(e) => e.stopPropagation()}
className={cn(
"inline-flex shrink-0 cursor-pointer select-none items-center gap-1.5 text-xs",
- row.is_active_brain
+ isActive
? "font-medium text-primary"
: row.key_set
? "text-muted-foreground hover:text-foreground"
@@ -705,12 +1127,12 @@ function SubagentActiveControl({
<input
type="radio"
name="active-subagent"
- checked={row.is_active_brain}
+ checked={isActive}
onChange={() => onActivate()}
disabled={activating}
className="accent-primary"
/>
- {activating ? "Activating…" : "Set active"}
+ {activating ? "Activating…" : isActive ? "Active" : "Set active"}
</label>
);
}
diff --git a/jarvis/ui/web/frontend/src/components/JarvisDock.filedrop.test.tsx b/jarvis/ui/web/frontend/src/components/JarvisDock.filedrop.test.tsx
index 8cd1d713f0..3ec5923e49 100644
--- a/jarvis/ui/web/frontend/src/components/JarvisDock.filedrop.test.tsx
+++ b/jarvis/ui/web/frontend/src/components/JarvisDock.filedrop.test.tsx
@@ -6,7 +6,7 @@ const playDropConfirm = vi.fn();
vi.mock("@/hooks/useWebSocket", () => ({ getWSClient: () => ({ send }) }));
vi.mock("@/hooks/useOverlayStyle", () => ({
useOverlayStyle: () => ({
- config: { style: "whisper_bar", options: [] },
+ config: { style: "jarvis_bar", options: [] },
loading: false,
error: null,
refetch: vi.fn(),
diff --git a/jarvis/ui/web/frontend/src/components/JarvisDock.test.tsx b/jarvis/ui/web/frontend/src/components/JarvisDock.test.tsx
index 39806740ec..c8dee4d11b 100644
--- a/jarvis/ui/web/frontend/src/components/JarvisDock.test.tsx
+++ b/jarvis/ui/web/frontend/src/components/JarvisDock.test.tsx
@@ -6,7 +6,7 @@ const playDropConfirm = vi.fn();
vi.mock("@/hooks/useWebSocket", () => ({ getWSClient: () => ({ send }) }));
vi.mock("@/hooks/useOverlayStyle", () => ({
useOverlayStyle: () => ({
- config: { style: "whisper_bar", options: [] },
+ config: { style: "jarvis_bar", options: [] },
loading: false,
error: null,
refetch: vi.fn(),
diff --git a/jarvis/ui/web/frontend/src/components/JarvisDock.tsx b/jarvis/ui/web/frontend/src/components/JarvisDock.tsx
index 38848178a6..1bd64fdb22 100644
--- a/jarvis/ui/web/frontend/src/components/JarvisDock.tsx
+++ b/jarvis/ui/web/frontend/src/components/JarvisDock.tsx
@@ -46,7 +46,7 @@ function isDroppable(dt: DataTransfer | null): boolean {
* shows the OS "no-drop" sign and a toss *near* Jarvis still lands. A successful
* drop plays a quiet confirmation chime and an "absorb" burst.
*
- * It mirrors the chosen on-screen display style: a slim bar for `whisper_bar`,
+ * It mirrors the chosen on-screen display style: a slim bar for `jarvis_bar`,
* the ghost mascot otherwise. This in-app surface is the cloud-first drop
* target — it works in any browser, unlike the separate Tk overlay windows.
*/
@@ -59,7 +59,11 @@ export function JarvisDock() {
const [fileArmed, setFileArmed] = useState(false); // a native OS drag is in flight
const [flash, setFlash] = useState(false); // brief post-drop "absorb" burst
const flashTimer = useRef<ReturnType<typeof setTimeout> | null>(null);
- const isBar = config?.style === "whisper_bar";
+ // Mascot ONLY when explicitly selected; the slim bar for "jarvis_bar"/"none"
+ // and while the style is still loading (config === null). Defaulting the
+ // unknown/loading state to the bar (the documented default) stops a ghost
+ // mascot from flashing in for a user who picked the bar.
+ const isBar = config?.style !== "mascot";
// Clear the pending "absorb" timer on unmount so it can't setState on a gone
// component (the source of a stray act() warning and a small leak).
diff --git a/jarvis/ui/web/frontend/src/components/board/ShareDialog.tsx b/jarvis/ui/web/frontend/src/components/board/ShareDialog.tsx
index a72f21c08e..5202639697 100644
--- a/jarvis/ui/web/frontend/src/components/board/ShareDialog.tsx
+++ b/jarvis/ui/web/frontend/src/components/board/ShareDialog.tsx
@@ -11,7 +11,8 @@ import {
shareToX,
type ShareStats,
} from "@/lib/shareImage";
-import { downloadBlob } from "@/lib/clipboard";
+import { saveOrDownload } from "@/lib/clipboard";
+import { useCapabilities } from "@/hooks/useCapabilities";
import { cn } from "@/lib/utils";
import { useT } from "@/i18n";
@@ -38,6 +39,8 @@ const SCALE = PREVIEW / 1080;
*/
export function ShareDialog({ open, onOpenChange, stats }: Props) {
const t = useT();
+ const caps = useCapabilities();
+ const native = caps.data?.native_file_actions ?? false;
const cardRef = useRef<HTMLDivElement>(null);
const [handle, setHandle] = useShareHandle();
const [status, setStatus] = useState<Status>({ kind: "idle" });
@@ -108,14 +111,22 @@ export function ShareDialog({ open, onOpenChange, stats }: Props) {
if (res === "copied") {
setStatus({ kind: "ok", msgKey: "board_view.share.status_copied" });
} else {
- downloadBlob("jarvis-stats.png", await ensureBlob());
+ await saveOrDownload({
+ filename: "jarvis-stats.png",
+ blob: await ensureBlob(),
+ native,
+ });
setStatus({ kind: "ok", msgKey: "board_view.share.status_copy_unsupported" });
}
});
const onSave = () =>
run(async () => {
- downloadBlob("jarvis-stats.png", await ensureBlob());
+ await saveOrDownload({
+ filename: "jarvis-stats.png",
+ blob: await ensureBlob(),
+ native,
+ });
setStatus({ kind: "ok", msgKey: "board_view.share.status_saved" });
});
diff --git a/jarvis/ui/web/frontend/src/components/layout/MainView.tsx b/jarvis/ui/web/frontend/src/components/layout/MainView.tsx
index 892bb87db6..26b040df2a 100644
--- a/jarvis/ui/web/frontend/src/components/layout/MainView.tsx
+++ b/jarvis/ui/web/frontend/src/components/layout/MainView.tsx
@@ -16,8 +16,10 @@ import { RunInspectorView } from "@/views/RunInspectorView";
import { SessionsView } from "@/views/SessionsView";
import { SocialsView } from "@/views/socials/SocialsView";
import { ContactsView } from "@/views/contacts/ContactsView";
+import { FeedbackView } from "@/views/feedback/FeedbackView";
import { AgentInstructionsView } from "@/views/AgentInstructionsView";
import { TelephonySetupView } from "@/views/TelephonyView";
+import { MakeItYoursView } from "@/views/MakeItYoursView";
/**
* Main area to the right of the sidebar. All views are switched the classic
@@ -97,8 +99,12 @@ function SwitchOnActiveSection({ active }: { active: string }) {
return <SocialsView />;
case "contacts":
return <ContactsView />;
+ case "feedback":
+ return <FeedbackView />;
case "agent-instructions":
return <AgentInstructionsView />;
+ case "personalize":
+ return <MakeItYoursView />;
default:
return <ChatsView />;
}
diff --git a/jarvis/ui/web/frontend/src/components/layout/Sidebar.test.tsx b/jarvis/ui/web/frontend/src/components/layout/Sidebar.test.tsx
index 9a8e38c4f9..aa782795dc 100644
--- a/jarvis/ui/web/frontend/src/components/layout/Sidebar.test.tsx
+++ b/jarvis/ui/web/frontend/src/components/layout/Sidebar.test.tsx
@@ -1,9 +1,26 @@
import { act, cleanup, render, screen } from "@testing-library/react";
-import { afterEach, beforeEach, describe, expect, test } from "vitest";
+import { afterEach, beforeEach, describe, expect, test, vi } from "vitest";
import { Sidebar } from "@/components/layout/Sidebar";
import { useEventStore } from "@/store/events";
+// The sidebar header avatar must mirror the chosen on-screen display style:
+// the ghost mascot ONLY when the user explicitly picked "mascot"; the slim bar
+// for "jarvis_bar"/"none" and while the style is still loading (config null).
+// Mock the overlay-style hook so the test controls the style without a fetch.
+const overlayMock = vi.hoisted(() => ({ style: "jarvis_bar" as string | null }));
+vi.mock("@/hooks/useOverlayStyle", () => ({
+ useOverlayStyle: () => ({
+ config: overlayMock.style
+ ? { style: overlayMock.style, options: ["jarvis_bar", "mascot", "none"] }
+ : null,
+ loading: false,
+ error: null,
+ refetch: () => {},
+ saveStyle: () => {},
+ }),
+}));
+
describe("Sidebar voice header", () => {
beforeEach(() => {
useEventStore.setState({
@@ -53,6 +70,88 @@ describe("Sidebar voice header", () => {
});
});
+describe("Sidebar header avatar", () => {
+ beforeEach(() => {
+ useEventStore.setState({
+ voiceState: "idle",
+ transcription: "",
+ transcriptionFinal: true,
+ connected: true,
+ voiceReady: true,
+ assistantName: "Ruben",
+ });
+ });
+
+ afterEach(() => {
+ cleanup();
+ overlayMock.style = "jarvis_bar";
+ });
+
+ // NOTE: an earlier change had the header avatar mirror the overlay display
+ // style (bar glyph for "jarvis_bar"). A later snapshot reverted it to the
+ // canonical static brand logo (jarvis-logo.png) regardless of style. This
+ // test pins the CURRENT behavior; the bar-vs-mascot-vs-logo choice is a
+ // product/branding decision tracked separately from the boot-speed work.
+ test("renders the static brand-logo avatar (one stable header identity)", () => {
+ const { container } = render(<Sidebar />);
+ const avatar = container.querySelector('[data-testid="sidebar-style-avatar"]');
+ expect(avatar).not.toBeNull();
+ expect(avatar?.getAttribute("data-variant")).toBe("logo");
+ });
+});
+
+describe("Sidebar brain footer", () => {
+ beforeEach(() => {
+ useEventStore.setState({
+ voiceState: "idle",
+ transcription: "",
+ transcriptionFinal: true,
+ connected: true,
+ voiceReady: true,
+ brainProvider: "unknown",
+ brainModel: "",
+ });
+ });
+
+ afterEach(() => {
+ cleanup();
+ });
+
+ test("renders the active provider and its model id", () => {
+ // The footer must show WHICH model is in use, not just the provider — a
+ // user who configured e.g. opus-4-8 wants that surfaced, not a bare "—".
+ useEventStore.setState({ brainProvider: "claude-api", brainModel: "claude-opus-4-8" });
+
+ render(<Sidebar />);
+
+ expect(screen.getByText("Claude (API)")).toBeTruthy();
+ const modelLine = screen.getByTestId("sidebar-brain-model");
+ expect(modelLine.textContent).toBe("claude-opus-4-8");
+ });
+
+ test("hides the model line when no model is known (shows provider only)", () => {
+ useEventStore.setState({ brainProvider: "gemini", brainModel: "" });
+
+ render(<Sidebar />);
+
+ expect(screen.getByText("Gemini")).toBeTruthy();
+ expect(screen.queryByTestId("sidebar-brain-model")).toBeNull();
+ });
+
+ test("follows a live model change", () => {
+ useEventStore.setState({ brainProvider: "claude-api", brainModel: "claude-opus-4-8" });
+ render(<Sidebar />);
+ expect(screen.getByTestId("sidebar-brain-model").textContent).toBe("claude-opus-4-8");
+
+ act(() => {
+ useEventStore.setState({ brainProvider: "gemini", brainModel: "gemini-3.1-flash" });
+ });
+
+ expect(screen.getByTestId("sidebar-brain-model").textContent).toBe("gemini-3.1-flash");
+ expect(screen.getByText("Gemini")).toBeTruthy();
+ });
+});
+
describe("Sidebar assistant name header", () => {
beforeEach(() => {
useEventStore.setState({
@@ -132,10 +231,10 @@ describe("Sidebar voice-boot indicator", () => {
expect(container.querySelector('[data-testid="voice-starting-spinner"]')).toBeNull();
});
- test("shows 'Offline' (not the spinner) when disconnected", () => {
- // Disconnected outranks warmup: there is no live socket to even report
- // voice readiness, so the honest state is Offline.
- useEventStore.setState({ connected: false, voiceReady: false });
+ test("shows 'Offline' (not the spinner) when disconnected and NOT warming", () => {
+ // Truly offline: no live socket AND the WS is not in the fast-boot warming
+ // loop (no 1013) — the honest state is Offline.
+ useEventStore.setState({ connected: false, voiceReady: false, wsWarming: false });
const { container } = render(<Sidebar />);
@@ -143,4 +242,17 @@ describe("Sidebar voice-boot indicator", () => {
expect(screen.queryByText("Voice starting…")).toBeNull();
expect(container.querySelector('[data-testid="voice-starting-spinner"]')).toBeNull();
});
+
+ test("shows the booting label + spinner (not Offline) while warming", () => {
+ // Disconnected but the fast-boot bootstrap keeps closing the WS with 1013:
+ // the backend is still starting, so the honest state is "Starting…", not
+ // the alarming "Offline".
+ useEventStore.setState({ connected: false, voiceReady: false, wsWarming: true });
+
+ const { container } = render(<Sidebar />);
+
+ expect(screen.getByText("Starting…")).toBeTruthy();
+ expect(screen.queryByText("Offline")).toBeNull();
+ expect(container.querySelector('[data-testid="voice-starting-spinner"]')).not.toBeNull();
+ });
});
diff --git a/jarvis/ui/web/frontend/src/components/layout/Sidebar.tsx b/jarvis/ui/web/frontend/src/components/layout/Sidebar.tsx
index 412c9f2df8..5a3e9ec8ba 100644
--- a/jarvis/ui/web/frontend/src/components/layout/Sidebar.tsx
+++ b/jarvis/ui/web/frontend/src/components/layout/Sidebar.tsx
@@ -13,17 +13,19 @@ import {
Sparkles,
Mic,
Terminal,
+ Wand2,
Share2,
Contact,
+ MessageSquareWarning,
ScrollText,
Loader2,
type LucideIcon,
ChevronRight,
} from "lucide-react";
import { useEventStore, type SectionId } from "@/store/events";
+import { useVoiceReadiness } from "@/hooks/useVoiceReadiness";
import { cn } from "@/lib/utils";
import { useMemo } from "react";
-import { MascotGigi } from "@/components/MascotGigi";
import { useT } from "@/i18n";
interface NavItem {
@@ -68,6 +70,7 @@ const NAV_GROUPS: NavItem[][] = [
},
// CLIs — the CLIs list + the CLI Test Hub behind one tab switch (CLIs first).
{ id: "clis", labelKey: "nav.clis_hub", icon: Terminal, matchIds: ["clis", "cli-test-hub"] },
+ { id: "personalize", labelKey: "nav.personalize", icon: Wand2, fallbackLabel: "Make It Yours" },
],
// 2) Content & data — things the user reads, edits, or browses.
[
@@ -107,8 +110,11 @@ const NAV_GROUPS: NavItem[][] = [
},
{ id: "outputs", labelKey: "nav.outputs", icon: FolderOpen },
],
- // 4) Social links — pinned to the bottom group.
- [{ id: "socials", labelKey: "nav.socials", icon: Share2 }],
+ // 4) Social links + in-app feedback — pinned to the bottom group.
+ [
+ { id: "socials", labelKey: "nav.socials", icon: Share2 },
+ { id: "feedback", labelKey: "nav.feedback", icon: MessageSquareWarning },
+ ],
];
const VOICE_STATE_STYLE: Record<string, { dot: string; pulse: boolean }> = {
@@ -127,9 +133,10 @@ export function Sidebar() {
const assistantName = useEventStore((s) => s.assistantName);
const transcription = useEventStore((s) => s.transcription);
const transcriptionFinal = useEventStore((s) => s.transcriptionFinal);
- const connected = useEventStore((s) => s.connected);
- const voiceReady = useEventStore((s) => s.voiceReady);
+ // Shared readiness derivation (same source the banner + chat empty-state use).
+ const { connected, voiceWarming, bootWarming, warming } = useVoiceReadiness();
const brainProvider = useEventStore((s) => s.brainProvider);
+ const brainModel = useEventStore((s) => s.brainModel);
const agentsCount = useEventStore((s) =>
s.events.filter((e) => e.name === "AgentStateChange").length > 0 ? undefined : 0,
);
@@ -138,10 +145,14 @@ export function Sidebar() {
// background. During that gap show a "Voice starting…" spinner instead of the
// normal idle "Ready" dot (which would falsely imply the mic already works).
// Disconnected outranks warmup — "Offline" is the honest state with no socket.
- const voiceWarming = connected && !voiceReady;
+ // voiceWarming / bootWarming / warming come from the shared useVoiceReadiness
+ // hook so the sidebar dot, the banner and the chat empty-state never disagree.
+ const showSpinner = warming;
const vs = VOICE_STATE_STYLE[voiceState] ?? VOICE_STATE_STYLE.idle;
const voiceLabel = !connected
- ? t("voice_state.offline")
+ ? bootWarming
+ ? t("voice_state.booting")
+ : t("voice_state.offline")
: voiceWarming
? t("voice_state.starting")
: t(`voice_state.${voiceState}`);
@@ -152,13 +163,22 @@ export function Sidebar() {
<aside className="flex h-full w-[280px] shrink-0 flex-col border-r border-border bg-card/40 backdrop-blur">
<div className="border-b border-border px-4 py-4">
<div className="flex items-center gap-3">
- {/* enableComments={false}: the mascot's floating speech-bubble is
- anchored beside a free-standing mascot, but here the mascot hugs
- the window edge — the listening bubble slid off-screen and only
- its yellow border + glow bled back in (the spurious "yellow
- frame"). The sidebar already surfaces voice status + the live
- transcript in its own boxes below, so the bubble is redundant. */}
- <MascotGigi size={44} enableComments={false} />
+ {/* The original Personal Jarvis logo — the ghost mascot. A snapshot
+ had swapped the header avatar for a bar glyph / gold-spark mark;
+ this is the canonical brand identity (jarvis-gigi). */}
+ <span
+ data-testid="sidebar-style-avatar"
+ data-variant="logo"
+ className="flex h-11 w-11 shrink-0 items-center justify-center"
+ >
+ <img
+ src="/jarvis-logo.png"
+ width={40}
+ height={40}
+ alt="Personal Jarvis"
+ className="shrink-0"
+ />
+ </span>
<div className="flex min-w-0 flex-1 flex-col">
<span className="font-display text-sm font-semibold tracking-tight">
{assistantName}
@@ -167,7 +187,7 @@ export function Sidebar() {
{voiceLabel}
</span>
</div>
- {voiceWarming ? (
+ {showSpinner ? (
<Loader2
className="h-3.5 w-3.5 shrink-0 animate-spin text-muted-foreground"
data-testid="voice-starting-spinner"
@@ -232,6 +252,17 @@ export function Sidebar() {
{t("sidebar.brain_label")}
</div>
<div className="text-xs font-medium truncate">{providerLabel}</div>
+ {/* The configured model id (e.g. "claude-opus-4-8") — the user asked
+ to see WHICH model is actually in use, not just the provider. */}
+ {brainModel && (
+ <div
+ className="text-[10px] text-muted-foreground/70 truncate"
+ title={brainModel}
+ data-testid="sidebar-brain-model"
+ >
+ {brainModel}
+ </div>
+ )}
</div>
<ChevronRight className="h-4 w-4 text-muted-foreground transition-transform group-hover:translate-x-0.5 group-hover:text-primary" />
</button>
diff --git a/jarvis/ui/web/frontend/src/components/layout/VoiceWarmingBanner.tsx b/jarvis/ui/web/frontend/src/components/layout/VoiceWarmingBanner.tsx
new file mode 100644
index 0000000000..b8fa1b9688
--- /dev/null
+++ b/jarvis/ui/web/frontend/src/components/layout/VoiceWarmingBanner.tsx
@@ -0,0 +1,76 @@
+import { useEffect, useRef, useState } from "react";
+import { Loader2, Mic } from "lucide-react";
+import { useT } from "@/i18n";
+import { useVoiceReadiness } from "@/hooks/useVoiceReadiness";
+import { cn } from "@/lib/utils";
+
+/**
+ * Honest "can I speak yet?" indicator.
+ *
+ * The desktop window appears within ~1 s, but the wake word is not actually
+ * ready until the wake model has loaded (a few seconds later — longer on a cold
+ * cache). Backend made honest 2026-06-27: `voiceReady` now flips to true only
+ * once the wake model can really hear (see jarvis/speech/pipeline.py). This
+ * banner surfaces that gap PROMINENTLY (not just a sidebar dot) so users don't
+ * speak too early and think the system is broken:
+ * - while warming -> amber "Jarvis is starting up / getting ready to listen"
+ * - on becoming ready -> a brief green "Ready — you can speak now" confirmation
+ */
+export function VoiceWarmingBanner() {
+ const t = useT();
+ // Single source of truth shared with the Sidebar status line and the chat
+ // empty-state, so all three readiness surfaces agree (no more "banner says
+ // starting up while the centre says Ready for commands").
+ const { warming, ready } = useVoiceReadiness();
+
+ // Flash an explicit "you can speak now" confirmation on the warming -> ready
+ // transition, so the go-ahead is a positive signal, not the banner silently
+ // disappearing.
+ const [justReady, setJustReady] = useState(false);
+ const wasWarming = useRef(false);
+ useEffect(() => {
+ if (wasWarming.current && !warming && ready) {
+ setJustReady(true);
+ const timer = setTimeout(() => setJustReady(false), 4000);
+ wasWarming.current = warming;
+ return () => clearTimeout(timer);
+ }
+ wasWarming.current = warming;
+ return undefined;
+ }, [warming, ready]);
+
+ if (!warming && !justReady) return null;
+
+ return (
+ <div
+ data-testid="voice-warming-banner"
+ data-state={warming ? "warming" : "ready"}
+ role="status"
+ aria-live="polite"
+ className={cn(
+ "flex items-center gap-3 border-b px-4 py-2.5 text-sm transition-colors",
+ warming
+ ? "border-amber-500/30 bg-amber-500/10 text-amber-200"
+ : "border-emerald-500/30 bg-emerald-500/10 text-emerald-200",
+ )}
+ >
+ {warming ? (
+ <Loader2 className="h-4 w-4 shrink-0 animate-spin" aria-hidden />
+ ) : (
+ <Mic className="h-4 w-4 shrink-0" aria-hidden />
+ )}
+ <div className="flex min-w-0 flex-col">
+ <span className="font-medium leading-tight">
+ {warming
+ ? t("voice_state.warming_title")
+ : t("voice_state.ready_title")}
+ </span>
+ {warming && (
+ <span className="text-xs leading-tight opacity-80">
+ {t("voice_state.warming_hint")}
+ </span>
+ )}
+ </div>
+ </div>
+ );
+}
diff --git a/jarvis/ui/web/frontend/src/components/missions/OpenClawPanel.tsx b/jarvis/ui/web/frontend/src/components/missions/JarvisAgentPanel.tsx
similarity index 100%
rename from jarvis/ui/web/frontend/src/components/missions/OpenClawPanel.tsx
rename to jarvis/ui/web/frontend/src/components/missions/JarvisAgentPanel.tsx
diff --git a/jarvis/ui/web/frontend/src/components/onboarding/IntroVideoScreen.test.tsx b/jarvis/ui/web/frontend/src/components/onboarding/IntroVideoScreen.test.tsx
new file mode 100644
index 0000000000..cd914bceb7
--- /dev/null
+++ b/jarvis/ui/web/frontend/src/components/onboarding/IntroVideoScreen.test.tsx
@@ -0,0 +1,36 @@
+import { cleanup, fireEvent, render, screen } from "@testing-library/react";
+import { afterEach, expect, it, vi } from "vitest";
+
+vi.mock("@/i18n", () => ({ useT: () => (k: string) => k }));
+
+import { IntroVideoScreen } from "./IntroVideoScreen";
+
+afterEach(cleanup);
+
+it("shows a click-to-play facade and only mounts the heavy iframe on demand", () => {
+ render(<IntroVideoScreen onContinue={() => {}} />);
+ // Facade first: the heavy YouTube iframe is NOT mounted until the user plays,
+ // so the step renders instantly with no loading flash.
+ expect(screen.queryByTitle("onboarding.tutorial.title")).toBeNull();
+
+ fireEvent.click(screen.getByLabelText("onboarding.tutorial.play"));
+
+ const frame = screen.getByTitle("onboarding.tutorial.title") as HTMLIFrameElement;
+ expect(frame.tagName).toBe("IFRAME");
+ expect(frame.src).toContain("youtube-nocookie.com/embed/FXz1HclXL1g");
+ expect(frame.src).toContain("autoplay=1");
+});
+
+it("the primary button advances the flow", () => {
+ const onContinue = vi.fn();
+ render(<IntroVideoScreen onContinue={onContinue} />);
+ fireEvent.click(screen.getByText("onboarding.tutorial.continue"));
+ expect(onContinue).toHaveBeenCalledOnce();
+});
+
+it("the skip link also advances the flow", () => {
+ const onContinue = vi.fn();
+ render(<IntroVideoScreen onContinue={onContinue} />);
+ fireEvent.click(screen.getByText("onboarding.tutorial.skip"));
+ expect(onContinue).toHaveBeenCalledOnce();
+});
diff --git a/jarvis/ui/web/frontend/src/components/onboarding/IntroVideoScreen.tsx b/jarvis/ui/web/frontend/src/components/onboarding/IntroVideoScreen.tsx
new file mode 100644
index 0000000000..904e724f60
--- /dev/null
+++ b/jarvis/ui/web/frontend/src/components/onboarding/IntroVideoScreen.tsx
@@ -0,0 +1,83 @@
+import { useState } from "react";
+import { Play } from "lucide-react";
+import { Button } from "@/components/ui/button";
+import { useT } from "@/i18n";
+
+// The public onboarding walkthrough on YouTube. Embedded via the
+// privacy-enhanced youtube-nocookie domain (no cookies until playback) with
+// rel=0 so "related" videos stay within this channel.
+//
+// A lightweight click-to-play thumbnail facade is shown first: the heavy
+// YouTube player iframe is only mounted once the user presses play. This makes
+// the step render instantly — no black box and no visible "loading" flash while
+// the embed boots — and defers the player module (and any YouTube contact beyond
+// the single static thumbnail) until the user actually chooses to watch.
+const VIDEO_ID = "FXz1HclXL1g";
+const EMBED_SRC = `https://www.youtube-nocookie.com/embed/${VIDEO_ID}?rel=0&autoplay=1`;
+const THUMB_SRC = `https://i.ytimg.com/vi/${VIDEO_ID}/maxresdefault.jpg`;
+const THUMB_FALLBACK = `https://i.ytimg.com/vi/${VIDEO_ID}/hqdefault.jpg`;
+
+/**
+ * The onboarding tutorial video, shown as the second screen — right after the
+ * RiskGate acknowledgement and before the step flow. Frontend-only and gated by
+ * local state in OnboardingGate, so it never mutates onboarding/completed state
+ * and cannot reintroduce the "onboarding reappears every restart" bug. Both the
+ * primary button and the skip link simply advance to the flow, so a user who
+ * does not want to watch is never blocked.
+ *
+ * The video uses a click-to-play thumbnail facade so the step appears instantly
+ * instead of mounting (and visibly loading) the heavy YouTube iframe up front.
+ */
+export function IntroVideoScreen({ onContinue }: { onContinue: () => void }) {
+ const t = useT();
+ const [playing, setPlaying] = useState(false);
+
+ return (
+ <div className="flex w-full max-w-lg flex-col gap-5 rounded-2xl border border-border bg-card p-8 shadow-2xl">
+ <div className="text-center">
+ <h1 className="font-display text-xl font-semibold">{t("onboarding.tutorial.title")}</h1>
+ <p className="mt-1 text-sm text-muted-foreground">{t("onboarding.tutorial.body")}</p>
+ </div>
+ <div className="aspect-video w-full overflow-hidden rounded-xl border border-border bg-gradient-to-br from-background to-card">
+ {playing ? (
+ <iframe
+ className="h-full w-full"
+ src={EMBED_SRC}
+ title={t("onboarding.tutorial.title")}
+ allow="accelerometer; autoplay; clipboard-write; encrypted-media; gyroscope; picture-in-picture; web-share"
+ allowFullScreen
+ />
+ ) : (
+ <button
+ type="button"
+ onClick={() => setPlaying(true)}
+ aria-label={t("onboarding.tutorial.play")}
+ className="group relative block h-full w-full"
+ >
+ <img
+ src={THUMB_SRC}
+ alt=""
+ aria-hidden="true"
+ className="h-full w-full object-cover"
+ onError={(e) => {
+ const img = e.currentTarget;
+ if (!img.src.endsWith("hqdefault.jpg")) img.src = THUMB_FALLBACK;
+ }}
+ />
+ <span className="absolute inset-0 flex items-center justify-center bg-black/25 transition-colors group-hover:bg-black/15">
+ <span className="flex h-16 w-16 items-center justify-center rounded-full bg-primary text-primary-foreground shadow-lg transition-transform group-hover:scale-110">
+ <Play className="h-7 w-7 translate-x-0.5 fill-current" />
+ </span>
+ </span>
+ </button>
+ )}
+ </div>
+ <Button className="w-full" onClick={onContinue}>
+ {t("onboarding.tutorial.continue")}
+ </Button>
+ <button className="text-xs text-muted-foreground underline" onClick={onContinue}>
+ {t("onboarding.tutorial.skip")}
+ </button>
+ </div>
+ );
+}
diff --git a/jarvis/ui/web/frontend/src/components/onboarding/OnboardingFlow.test.tsx b/jarvis/ui/web/frontend/src/components/onboarding/OnboardingFlow.test.tsx
index 93d6d53198..b170fce025 100644
--- a/jarvis/ui/web/frontend/src/components/onboarding/OnboardingFlow.test.tsx
+++ b/jarvis/ui/web/frontend/src/components/onboarding/OnboardingFlow.test.tsx
@@ -62,8 +62,15 @@ it("advancing persists the next step and shows it", () => {
expect(screen.getByTestId("step-terms")).toBeDefined();
});
-it("resumes from current_step", () => {
- render(<OnboardingFlow onb={makeOnb({ current_step: "terms" })} />);
+it("always starts at the first step, ignoring a saved current_step", () => {
+ // Every run must walk each step in order. A current_step saved by an earlier
+ // (already completed) run must NOT auto-skip the user ahead to the end.
+ render(<OnboardingFlow onb={makeOnb({ current_step: "finish" })} />);
+ expect(screen.getByTestId("step-welcome")).toBeDefined();
+});
+
+it("honors an explicit initialStep (the terms-version-bump re-open)", () => {
+ render(<OnboardingFlow onb={makeOnb({ current_step: "finish" })} initialStep="terms" />);
expect(screen.getByTestId("step-terms")).toBeDefined();
});
diff --git a/jarvis/ui/web/frontend/src/components/onboarding/OnboardingFlow.tsx b/jarvis/ui/web/frontend/src/components/onboarding/OnboardingFlow.tsx
index aaa0b25cc5..45ac301a01 100644
--- a/jarvis/ui/web/frontend/src/components/onboarding/OnboardingFlow.tsx
+++ b/jarvis/ui/web/frontend/src/components/onboarding/OnboardingFlow.tsx
@@ -41,7 +41,11 @@ export function OnboardingFlow({
}) {
const t = useT();
const steps = onb.state?.steps ?? ["welcome", "finish"];
- const initialIdx = Math.max(0, steps.indexOf(initialStep ?? onb.state?.current_step ?? "welcome"));
+ // Always begin at the first step so every run walks each step in order. We do
+ // NOT resume to a saved current_step: a user who already finished once would
+ // otherwise be auto-jumped to the last step, which feels like the flow skipped
+ // itself. An explicit initialStep (the terms-version-bump re-open) still wins.
+ const initialIdx = initialStep ? Math.max(0, steps.indexOf(initialStep)) : 0;
const [idx, setIdx] = useState(initialIdx);
const [skipped, setSkipped] = useState<string[]>(onb.state?.skipped_steps ?? []);
diff --git a/jarvis/ui/web/frontend/src/components/onboarding/OnboardingGate.test.tsx b/jarvis/ui/web/frontend/src/components/onboarding/OnboardingGate.test.tsx
index 4d3b1eb0e9..33b52fc6ca 100644
--- a/jarvis/ui/web/frontend/src/components/onboarding/OnboardingGate.test.tsx
+++ b/jarvis/ui/web/frontend/src/components/onboarding/OnboardingGate.test.tsx
@@ -1,4 +1,4 @@
-import { cleanup, render, screen, waitFor } from "@testing-library/react";
+import { cleanup, fireEvent, render, screen, waitFor } from "@testing-library/react";
import { afterEach, expect, it, vi } from "vitest";
vi.mock("./OnboardingFlow", () => ({ OnboardingFlow: () => <div data-testid="flow" /> }));
@@ -54,3 +54,21 @@ it("fails open (renders nothing) on a fetch error", async () => {
render(<OnboardingGate />);
await waitFor(() => expect(screen.queryByRole("dialog")).toBeNull(), { timeout: 500 });
});
+
+it("shows the tutorial video after the risk gate, then the step flow", async () => {
+ stub({ ...base, completed: false });
+ render(<OnboardingGate />);
+ await waitFor(() => expect(screen.getByRole("dialog")).toBeDefined());
+
+ // Accept the risk gate (tick the box, then the proceed button).
+ fireEvent.click(screen.getByRole("checkbox"));
+ fireEvent.click(screen.getByRole("button", { name: /continue/i }));
+
+ // Second screen: the YouTube tutorial embed.
+ const frame = screen.getByTitle(/tour/i) as HTMLIFrameElement;
+ expect(frame.src).toContain("youtube-nocookie.com");
+
+ // Continue past the video → the step flow renders.
+ fireEvent.click(screen.getByRole("button", { name: /continue/i }));
+ expect(screen.getByTestId("flow")).toBeDefined();
+});
diff --git a/jarvis/ui/web/frontend/src/components/onboarding/OnboardingGate.tsx b/jarvis/ui/web/frontend/src/components/onboarding/OnboardingGate.tsx
index 185c9fc14a..42ff29d901 100644
--- a/jarvis/ui/web/frontend/src/components/onboarding/OnboardingGate.tsx
+++ b/jarvis/ui/web/frontend/src/components/onboarding/OnboardingGate.tsx
@@ -2,6 +2,7 @@ import { useEffect, useMemo, useState } from "react";
import { useOnboarding } from "@/hooks/useOnboarding";
import { OnboardingFlow } from "./OnboardingFlow";
import { RiskGate } from "./RiskGate";
+import { IntroVideoScreen } from "./IntroVideoScreen";
/**
* Blocking overlay that shows the onboarding flow until it is completed.
@@ -16,6 +17,11 @@ export function OnboardingGate() {
// never touching onboarding/completed state, so it shows once per fresh open
// of an unfinished guide and cannot reintroduce the restart-loop bug.
const [riskAck, setRiskAck] = useState(false);
+ // The tutorial video is the second screen — shown after the risk gate and
+ // before the step flow. Local-state only (like riskAck), so it never touches
+ // onboarding/completed state and re-shows on a fresh open / ?onboarding=force
+ // replay. A null mutation guarantees it cannot reintroduce the restart-loop.
+ const [videoSeen, setVideoSeen] = useState(false);
// Set once the user completes the guide (the "Get started" / complete() path
// dispatches jarvis:onboarding-changed). It dismisses the overlay even under
// ?onboarding=force, so a dev replay closes on finish exactly like a real
@@ -47,7 +53,11 @@ export function OnboardingGate() {
if (!show) return null;
// On a terms version bump for an already-completed install, re-open at terms.
- const initialStep = onb.state.completed && termsOutdated ? "terms" : undefined;
+ const isTermsBumpReopen = Boolean(onb.state.completed && termsOutdated);
+ const initialStep = isTermsBumpReopen ? "terms" : undefined;
+ // Skip the tutorial on a pure terms-bump re-open: that user has already seen
+ // it and is only re-accepting a new Terms version.
+ const showVideo = !videoSeen && !isTermsBumpReopen;
return (
<div
@@ -55,10 +65,12 @@ export function OnboardingGate() {
aria-modal="true"
className="fixed inset-0 z-50 flex items-center justify-center bg-background/90 backdrop-blur-sm"
>
- {riskAck ? (
- <OnboardingFlow onb={onb} initialStep={initialStep} />
- ) : (
+ {!riskAck ? (
<RiskGate onAccept={() => setRiskAck(true)} />
+ ) : showVideo ? (
+ <IntroVideoScreen onContinue={() => setVideoSeen(true)} />
+ ) : (
+ <OnboardingFlow onb={onb} initialStep={initialStep} />
)}
</div>
);
diff --git a/jarvis/ui/web/frontend/src/components/onboarding/steps/ApiKeysStep.tsx b/jarvis/ui/web/frontend/src/components/onboarding/steps/ApiKeysStep.tsx
index c630d8cfb2..3e8c75c3c5 100644
--- a/jarvis/ui/web/frontend/src/components/onboarding/steps/ApiKeysStep.tsx
+++ b/jarvis/ui/web/frontend/src/components/onboarding/steps/ApiKeysStep.tsx
@@ -20,10 +20,13 @@ import type { StepProps } from "../OnboardingFlow";
// (Brain first, then Voice, then Hearing). Rendered as stacked sections inside
// one scroll container so the user can scroll through every class at once —
// mirroring the real API-Keys section — instead of paging one class at a time.
-const TIERS: { tier: ProviderTier; label: string; icon: JSX.Element }[] = [
- { tier: "brain", label: "Brain — reasoning", icon: <Brain className="h-3.5 w-3.5" /> },
- { tier: "tts", label: "Voice — text to speech", icon: <Volume2 className="h-3.5 w-3.5" /> },
- { tier: "stt", label: "Hearing — speech to text", icon: <Mic className="h-3.5 w-3.5" /> },
+// Each provider class gets a plain-language hint so a first-time user
+// understands at a glance that Jarvis takes several *kinds* of keys — not just
+// one for the brain — and what each kind is for.
+const TIERS: { tier: ProviderTier; label: string; hint: string; icon: JSX.Element }[] = [
+ { tier: "brain", label: "Brain", hint: "The model that thinks and writes the answers", icon: <Brain className="h-3.5 w-3.5" /> },
+ { tier: "tts", label: "Voice", hint: "Speaks the answers out loud (text-to-speech)", icon: <Volume2 className="h-3.5 w-3.5" /> },
+ { tier: "stt", label: "Hearing", hint: "Turns what you say into text (speech-to-text)", icon: <Mic className="h-3.5 w-3.5" /> },
];
// Activate (select) a provider by its tier — mirrors the main Settings API-Keys
@@ -78,9 +81,12 @@ export function ApiKeysStep({ goNext, skip }: StepProps) {
if (!list.length) return null;
return (
<section key={meta.tier}>
- <h3 className="mb-2 inline-flex items-center gap-2 text-[10px] uppercase tracking-wider text-muted-foreground">
- {meta.icon} {meta.label}
- </h3>
+ <div className="mb-2">
+ <h3 className="inline-flex items-center gap-2 text-xs font-semibold uppercase tracking-wider text-foreground/80">
+ {meta.icon} {meta.label}
+ </h3>
+ <p className="text-[11px] leading-tight text-muted-foreground">{meta.hint}</p>
+ </div>
<div className="flex flex-col gap-3">
{list.map((p) => (
<ProviderRow
diff --git a/jarvis/ui/web/frontend/src/components/onboarding/steps/SystemStyleStep.test.tsx b/jarvis/ui/web/frontend/src/components/onboarding/steps/SystemStyleStep.test.tsx
index 3b9984743e..73171ebdcc 100644
--- a/jarvis/ui/web/frontend/src/components/onboarding/steps/SystemStyleStep.test.tsx
+++ b/jarvis/ui/web/frontend/src/components/onboarding/steps/SystemStyleStep.test.tsx
@@ -8,14 +8,14 @@ vi.mock("@/components/MascotGigi", () => ({ MascotGigi: () => <div data-testid="
// step must persist the pick through this hook's saveStyle and NEVER restart.
const saveStyle = vi.fn().mockResolvedValue({
ok: true,
- style: "whisper_bar",
+ style: "jarvis_bar",
persisted: true,
applied_live: false, // even when a restart would be "required", onboarding must not restart
restart_required: true,
});
vi.mock("@/hooks/useOverlayStyle", () => ({
useOverlayStyle: () => ({
- config: { style: "whisper_bar", options: ["whisper_bar", "mascot", "none"] },
+ config: { style: "jarvis_bar", options: ["jarvis_bar", "mascot", "none"] },
loading: false,
error: null,
refetch: vi.fn(),
@@ -49,7 +49,7 @@ function renderStep() {
it("renders all three overlay-style options", () => {
renderStep();
expect(
- screen.getByRole("button", { name: "onboarding.system_style.options.whisper_bar" }),
+ screen.getByRole("button", { name: "onboarding.system_style.options.jarvis_bar" }),
).toBeDefined();
expect(
screen.getByRole("button", { name: "onboarding.system_style.options.mascot" }),
@@ -65,7 +65,7 @@ it("pre-selects the Jarvis Bar and labels it Recommended", () => {
expect(screen.getByText("onboarding.system_style.recommended")).toBeDefined();
// The bar card is the pressed/selected one.
const bar = screen.getByRole("button", {
- name: "onboarding.system_style.options.whisper_bar",
+ name: "onboarding.system_style.options.jarvis_bar",
});
expect(bar.getAttribute("aria-pressed")).toBe("true");
});
@@ -125,11 +125,11 @@ it("reverts the optimistic selection when the save fails", async () => {
);
await waitFor(() => expect(saveStyle).toHaveBeenCalledWith("mascot"));
// The pick was not persisted, so the highlighted card snaps back to the
- // last-known persisted value (whisper_bar) and an error is shown.
+ // last-known persisted value (jarvis_bar) and an error is shown.
await waitFor(() =>
expect(
screen
- .getByRole("button", { name: "onboarding.system_style.options.whisper_bar" })
+ .getByRole("button", { name: "onboarding.system_style.options.jarvis_bar" })
.getAttribute("aria-pressed"),
).toBe("true"),
);
diff --git a/jarvis/ui/web/frontend/src/components/onboarding/steps/SystemStyleStep.tsx b/jarvis/ui/web/frontend/src/components/onboarding/steps/SystemStyleStep.tsx
index b8f0be28e0..b198cf8192 100644
--- a/jarvis/ui/web/frontend/src/components/onboarding/steps/SystemStyleStep.tsx
+++ b/jarvis/ui/web/frontend/src/components/onboarding/steps/SystemStyleStep.tsx
@@ -7,7 +7,7 @@ import { cn } from "@/lib/utils";
import type { StepProps } from "../OnboardingFlow";
// The Jarvis Bar is the default + recommended on-screen surface.
-const RECOMMENDED: OverlayStyle = "whisper_bar";
+const RECOMMENDED: OverlayStyle = "jarvis_bar";
/**
* Onboarding step: choose the on-screen "system style" (the Jarvis Bar vs. the
@@ -39,7 +39,7 @@ export function SystemStyleStep({ goNext, skip }: StepProps) {
if (config) setStyle(config.style);
}, [config]);
- const options = config?.options ?? (["whisper_bar", "mascot", "none"] as OverlayStyle[]);
+ const options = config?.options ?? (["jarvis_bar", "mascot", "none"] as OverlayStyle[]);
async function onPick(opt: OverlayStyle) {
if (saving || restarting) return;
diff --git a/jarvis/ui/web/frontend/src/components/overlay/OverlayStylePreviews.tsx b/jarvis/ui/web/frontend/src/components/overlay/OverlayStylePreviews.tsx
index 8c42706bf1..cb559c1626 100644
--- a/jarvis/ui/web/frontend/src/components/overlay/OverlayStylePreviews.tsx
+++ b/jarvis/ui/web/frontend/src/components/overlay/OverlayStylePreviews.tsx
@@ -14,7 +14,7 @@ export function StylePreview({ style }: { style: OverlayStyle }) {
if (style === "mascot") {
return <MascotGigi size={46} reactToVoice={false} enableComments={false} />;
}
- if (style === "whisper_bar") return <BarPreview />;
+ if (style === "jarvis_bar") return <BarPreview />;
return <NonePreview />;
}
diff --git a/jarvis/ui/web/frontend/src/components/sessions/SessionDetail.tsx b/jarvis/ui/web/frontend/src/components/sessions/SessionDetail.tsx
index 29e868a9ae..ecbc77e183 100644
--- a/jarvis/ui/web/frontend/src/components/sessions/SessionDetail.tsx
+++ b/jarvis/ui/web/frontend/src/components/sessions/SessionDetail.tsx
@@ -5,6 +5,7 @@
* Lade-/Empty-/Error-States werden inline gerendert — kein Modal.
*/
import {
+ Code2,
Copy,
Download,
FileCode2,
@@ -12,21 +13,28 @@ import {
FileText,
Loader2,
} from "lucide-react";
-import { useCallback, useMemo } from "react";
+import { useCallback, useMemo, useState } from "react";
import { Badge } from "@/components/ui/badge";
import { Button } from "@/components/ui/button";
import { ScrollArea } from "@/components/ui/scroll-area";
+import { OpenWithDialog } from "@/components/OpenWithDialog";
import { useEventStore } from "@/store/events";
import {
buildSessionFilename,
- downloadAs,
mimeFor,
robustCopy,
+ saveOrDownload,
} from "@/lib/clipboard";
+import { useCapabilities } from "@/hooks/useCapabilities";
+import {
+ useOpeners,
+ usePreferredOpener,
+ useSetPreferredOpener,
+} from "@/hooks/useOutputs";
import { useT } from "@/i18n";
-import { fetchSessionExport } from "./api";
+import { fetchSessionExport, openSessionWith, sessionExportUrl } from "./api";
import { TurnCard } from "./TurnCard";
import type {
SessionDetail as SessionDetailModel,
@@ -50,6 +58,17 @@ interface Props {
export function SessionDetail({ detail, loading, error }: Props) {
const t = useT();
const pushToast = useEventStore((s) => s.pushToast);
+ // Desktop shell? Then save straight to ~/Downloads (browser downloads are
+ // silently dropped by pywebview); otherwise use the normal browser download.
+ const caps = useCapabilities();
+ const native = caps.data?.native_file_actions ?? false;
+ // "Open in editor" — reuses the Outputs view's opener list + remembered
+ // default (shared `[ui] preferred_opener`), so the chosen editor is the same
+ // everywhere. The chooser tracks which format row triggered it.
+ const openers = useOpeners();
+ const preferred = usePreferredOpener();
+ const setPreferred = useSetPreferredOpener();
+ const [editorFormat, setEditorFormat] = useState<ExportFormat | null>(null);
// Group the SpeechSpoken raw events under their turn so each TurnCard can
// render the "Spoken output" track (every voiced non-reply phrase). Hook
@@ -116,8 +135,18 @@ export function SessionDetail({ detail, loading, error }: Props) {
const preview =
detail.turns.find((t) => t.user_text)?.user_text ?? "";
const filename = buildSessionFilename(detail.session, preview, format);
- downloadAs(filename, text, mimeFor(format));
- pushToast("success", `${t("session_detail.downloaded_as")} ${filename}`);
+ const savedPath = await saveOrDownload({
+ filename,
+ text,
+ mime: mimeFor(format),
+ native,
+ });
+ pushToast(
+ "success",
+ savedPath
+ ? `${t("session_detail.saved_to_downloads")} ${savedPath}`
+ : `${t("session_detail.downloaded_as")} ${filename}`,
+ );
} catch (e) {
pushToast(
"error",
@@ -125,7 +154,60 @@ export function SessionDetail({ detail, loading, error }: Props) {
);
}
},
- [detail, pushToast],
+ [detail, pushToast, native],
+ );
+
+ // Launch the transcript in a local app (editor / default / browser).
+ const launchInEditor = useCallback(
+ async (format: ExportFormat, opener: string) => {
+ if (!detail) return;
+ try {
+ const opened = await openSessionWith(detail.session.id, format, opener);
+ pushToast(
+ opened ? "success" : "error",
+ opened
+ ? t("session_detail.opened_in_editor")
+ : t("session_detail.open_failed"),
+ );
+ } catch (e) {
+ pushToast(
+ "error",
+ e instanceof Error ? e.message : t("session_detail.open_failed"),
+ );
+ }
+ },
+ [detail, pushToast, t],
+ );
+
+ const openInEditor = useCallback(
+ (format: ExportFormat) => {
+ if (!detail) return;
+ if (!native) {
+ // Headless VPS / browser: no local apps — open the export in a new tab.
+ window.open(
+ sessionExportUrl(detail.session.id, format),
+ "_blank",
+ "noopener,noreferrer",
+ );
+ return;
+ }
+ const pref = preferred.data ?? "";
+ if (pref) {
+ void launchInEditor(format, pref);
+ } else {
+ setEditorFormat(format); // first time: ask which app via the chooser
+ }
+ },
+ [detail, native, preferred.data, launchInEditor],
+ );
+
+ const pickOpener = useCallback(
+ (opener: string, remember: boolean) => {
+ if (editorFormat) void launchInEditor(editorFormat, opener);
+ if (remember) setPreferred.mutate(opener);
+ setEditorFormat(null);
+ },
+ [editorFormat, launchInEditor, setPreferred],
);
if (loading) {
@@ -207,6 +289,7 @@ export function SessionDetail({ detail, loading, error }: Props) {
label="Text"
onCopy={() => copyAs("plain")}
onDownload={() => downloadAsFormat("plain")}
+ onOpenEditor={() => openInEditor("plain")}
variant="primary"
/>
<ExportRow
@@ -214,6 +297,7 @@ export function SessionDetail({ detail, loading, error }: Props) {
label="Markdown"
onCopy={() => copyAs("markdown")}
onDownload={() => downloadAsFormat("markdown")}
+ onOpenEditor={() => openInEditor("markdown")}
variant="outline"
/>
<ExportRow
@@ -221,12 +305,23 @@ export function SessionDetail({ detail, loading, error }: Props) {
label="JSON"
onCopy={() => copyAs("json")}
onDownload={() => downloadAsFormat("json")}
+ onOpenEditor={() => openInEditor("json")}
variant="outline"
/>
</div>
</div>
</div>
+ {/* "Open with…" chooser — only on the desktop, where local apps exist.
+ editorFormat carries which format row opened it. */}
+ {editorFormat && (
+ <OpenWithDialog
+ openers={openers.data ?? []}
+ onPick={pickOpener}
+ onClose={() => setEditorFormat(null)}
+ />
+ )}
+
{/* Turns */}
<ScrollArea className="min-h-0 flex-1">
<div className="space-y-3 p-5">
@@ -256,18 +351,20 @@ interface ExportRowProps {
label: string;
onCopy: () => void;
onDownload: () => void;
+ onOpenEditor: () => void;
variant: "primary" | "outline";
}
/**
* Eine Zeile pro Export-Format: links das Format-Label (mit Icon),
- * rechts zwei kompakte Action-Buttons (Kopieren / Herunterladen).
+ * rechts drei kompakte Action-Buttons (Kopieren / Herunterladen / In Editor).
*/
function ExportRow({
icon,
label,
onCopy,
onDownload,
+ onOpenEditor,
variant,
}: ExportRowProps) {
const t = useT();
@@ -302,6 +399,16 @@ function ExportRow({
>
<Download className="h-3.5 w-3.5" />
</Button>
+ <Button
+ type="button"
+ size="sm"
+ variant="ghost"
+ onClick={onOpenEditor}
+ className="h-7 w-7 shrink-0 p-0"
+ title={`${t("session_detail.open_editor_action")} ${label}`}
+ >
+ <Code2 className="h-3.5 w-3.5" />
+ </Button>
</div>
);
}
diff --git a/jarvis/ui/web/frontend/src/components/sessions/TurnCard.tsx b/jarvis/ui/web/frontend/src/components/sessions/TurnCard.tsx
index efcfeab412..1f0a84a3ab 100644
--- a/jarvis/ui/web/frontend/src/components/sessions/TurnCard.tsx
+++ b/jarvis/ui/web/frontend/src/components/sessions/TurnCard.tsx
@@ -20,7 +20,8 @@ import { useCallback } from "react";
import { Badge } from "@/components/ui/badge";
import { Button } from "@/components/ui/button";
import { Card, CardContent } from "@/components/ui/card";
-import { downloadAs, robustCopy } from "@/lib/clipboard";
+import { robustCopy, saveOrDownload } from "@/lib/clipboard";
+import { useCapabilities } from "@/hooks/useCapabilities";
import { useEventStore } from "@/store/events";
import { useT } from "@/i18n";
@@ -37,7 +38,7 @@ export const SPOKEN_KIND_LABEL: Record<string, string> = {
stt_unavailable: "Couldn't hear you",
privacy: "Privacy",
completion: "Background result",
- subagent: "Jarvis Sub-Agent / Output",
+ subagent: "Jarvis-Agent / Output",
action_done: "Action confirmed",
backchannel: "Backchannel",
announcement: "Announcement",
@@ -55,10 +56,14 @@ export function TurnCard({ turn, spoken = [] }: Props) {
const t = useT();
const pushToast = useEventStore((s) => s.pushToast);
const assistantName = useEventStore((s) => s.assistantName);
- // Override the subagent label so it follows the configured assistant name.
+ // Desktop shell → save to ~/Downloads via the backend; browser → blob download.
+ const caps = useCapabilities();
+ const native = caps.data?.native_file_actions ?? false;
+ // The Jarvis-Agents brand label is fixed: it names the system, not the
+ // configured assistant, so it does not follow the assistant name.
const kindLabel: Record<string, string> = {
...SPOKEN_KIND_LABEL,
- subagent: `${assistantName} Sub-Agent / Output`,
+ subagent: "Jarvis-Agent / Output",
};
const copyTurn = useCallback(async () => {
@@ -70,16 +75,26 @@ export function TurnCard({ turn, spoken = [] }: Props) {
);
}, [turn, spoken, pushToast, t]);
- const downloadTurn = useCallback(() => {
+ const downloadTurn = useCallback(async () => {
const text = formatTurnPlain(turn, spoken);
const stamp = new Date(turn.started_ms);
const pad = (n: number): string => String(n).padStart(2, "0");
const filename =
`voice-turn-${stamp.getFullYear()}-${pad(stamp.getMonth() + 1)}-${pad(stamp.getDate())}` +
`_${pad(stamp.getHours())}-${pad(stamp.getMinutes())}-${pad(stamp.getSeconds())}.txt`;
- downloadAs(filename, text, "text/plain;charset=utf-8");
- pushToast("success", `${t("turn_card.downloaded_as")} ${filename}`);
- }, [turn, spoken, pushToast, t]);
+ const savedPath = await saveOrDownload({
+ filename,
+ text,
+ mime: "text/plain;charset=utf-8",
+ native,
+ });
+ pushToast(
+ "success",
+ savedPath
+ ? `${t("turn_card.saved_to_downloads")} ${savedPath}`
+ : `${t("turn_card.downloaded_as")} ${filename}`,
+ );
+ }, [turn, spoken, pushToast, t, native]);
const startedAt = new Date(turn.started_ms).toLocaleTimeString("de", {
hour: "2-digit",
diff --git a/jarvis/ui/web/frontend/src/components/sessions/api.ts b/jarvis/ui/web/frontend/src/components/sessions/api.ts
index c691f668e9..b4caaaa759 100644
--- a/jarvis/ui/web/frontend/src/components/sessions/api.ts
+++ b/jarvis/ui/web/frontend/src/components/sessions/api.ts
@@ -31,3 +31,35 @@ export async function fetchSessionExport(
}
return await res.text();
}
+
+/** URL of the raw export — opened in a new browser tab on a headless/VPS host
+ * where there are no local apps to launch. */
+export function sessionExportUrl(
+ id: string,
+ format: "markdown" | "plain" | "json",
+): string {
+ return `/api/sessions/${encodeURIComponent(id)}/export?format=${format}`;
+}
+
+/** Open the session transcript (in the given format) in a local app on the
+ * desktop. ``opener`` is a closed opener id (default | browser | editor key),
+ * resolved + launched by the backend. Returns whether a launcher fired. */
+export async function openSessionWith(
+ id: string,
+ format: "markdown" | "plain" | "json",
+ opener: string,
+): Promise<boolean> {
+ const res = await fetch(
+ `/api/sessions/${encodeURIComponent(id)}/open-with?format=${format}`,
+ {
+ method: "POST",
+ headers: { "Content-Type": "application/json" },
+ body: JSON.stringify({ opener }),
+ },
+ );
+ if (!res.ok) {
+ throw new Error(`HTTP ${res.status} — session open-with`);
+ }
+ const data = (await res.json()) as { opened?: boolean };
+ return data.opened ?? false;
+}
diff --git a/jarvis/ui/web/frontend/src/components/workspace/WorkspaceTerminal.tsx b/jarvis/ui/web/frontend/src/components/workspace/WorkspaceTerminal.tsx
new file mode 100644
index 0000000000..beff1f8b04
--- /dev/null
+++ b/jarvis/ui/web/frontend/src/components/workspace/WorkspaceTerminal.tsx
@@ -0,0 +1,220 @@
+/**
+ * One embedded, interactive agent terminal — xterm.js wired bidirectionally to
+ * the workspace PTY WebSocket (`/api/workspace/pty/{key}`). The agent (Claude
+ * Code / Codex) runs in a real PTY in the Jarvis project folder; keystrokes go
+ * up as `{t:"i"}`, output comes down as `{t:"o"}`, resizes as `{t:"r"}`.
+ *
+ * Conventions copied from PtyTerminal: xterm instance in a ref (never state, or
+ * it rerenders per chunk), dispose() on unmount (WebGL context cap).
+ */
+import { useEffect, useRef, useState } from "react";
+import { Terminal } from "@xterm/xterm";
+import { FitAddon } from "@xterm/addon-fit";
+import { WebLinksAddon } from "@xterm/addon-web-links";
+import "@xterm/xterm/css/xterm.css";
+import { Terminal as TerminalIcon, AlertCircle } from "lucide-react";
+
+type Status = "connecting" | "live" | "exited" | "error";
+
+interface WorkspaceTerminalProps {
+ /** A stable key for this pane (used only as the WS path segment). */
+ paneKey: string;
+ /** Run an agent by name (e.g. "claude"); mutually exclusive with installName. */
+ agentName?: string;
+ /** Run an agent's installer by name; mutually exclusive with agentName. */
+ installName?: string;
+ /** Header label shown above the terminal. */
+ title: string;
+}
+
+async function getToken(): Promise<string> {
+ const injected = (window as unknown as { __JARVIS_TOKEN?: string }).__JARVIS_TOKEN;
+ if (injected) return injected;
+ try {
+ const res = await fetch("/api/missions/auth/token");
+ const body = (await res.json()) as { token?: string };
+ return body.token ?? "";
+ } catch {
+ return "";
+ }
+}
+
+function buildUrl(paneKey: string, params: Record<string, string>): string {
+ const proto = window.location.protocol === "https:" ? "wss" : "ws";
+ const query = new URLSearchParams(params).toString();
+ return `${proto}://${window.location.host}/api/workspace/pty/${encodeURIComponent(
+ paneKey,
+ )}?${query}`;
+}
+
+export function WorkspaceTerminal({
+ paneKey,
+ agentName,
+ installName,
+ title,
+}: WorkspaceTerminalProps) {
+ const containerRef = useRef<HTMLDivElement | null>(null);
+ const [status, setStatus] = useState<Status>("connecting");
+ const [error, setError] = useState<string | null>(null);
+
+ useEffect(() => {
+ const container = containerRef.current;
+ if (!container) return;
+
+ const term = new Terminal({
+ convertEol: false,
+ fontFamily: "'JetBrains Mono', 'Fira Code', Consolas, 'Courier New', monospace",
+ fontSize: 12,
+ lineHeight: 1.15,
+ cursorBlink: true,
+ scrollback: 5000,
+ theme: {
+ background: "#0b0d10",
+ foreground: "#e6e6e6",
+ cursor: "#ffd60a",
+ selectionBackground: "#3a4252",
+ },
+ });
+ const fit = new FitAddon();
+ term.loadAddon(fit);
+ term.loadAddon(new WebLinksAddon());
+ term.open(container);
+ try {
+ fit.fit();
+ } catch {
+ /* container not measured yet — ResizeObserver will fit shortly */
+ }
+
+ let ws: WebSocket | null = null;
+ let disposed = false;
+ let everLive = false;
+
+ const sendResize = () => {
+ try {
+ fit.fit();
+ } catch {
+ return;
+ }
+ if (ws && ws.readyState === WebSocket.OPEN) {
+ ws.send(JSON.stringify({ t: "r", cols: term.cols, rows: term.rows }));
+ }
+ };
+
+ void (async () => {
+ const token = await getToken();
+ if (disposed) return;
+ const params: Record<string, string> = {
+ token,
+ cols: String(term.cols || 80),
+ rows: String(term.rows || 24),
+ };
+ if (agentName) params.agent = agentName;
+ else if (installName) params.install = installName;
+
+ ws = new WebSocket(buildUrl(paneKey, params));
+ ws.onopen = () => {
+ setStatus("connecting");
+ // Push the ACTUAL pane size to the PTY now that we can send. The spawn
+ // used a best-effort size (the mount-time fit often runs before the
+ // grid cell is measured), and resizes fired while the socket was still
+ // connecting were dropped — so without this the agent's full-screen TUI
+ // keeps drawing at the wrong dimensions (cramped / clipped on the
+ // right). A second deferred fit catches any late grid layout.
+ sendResize();
+ requestAnimationFrame(sendResize);
+ };
+ ws.onmessage = (ev) => {
+ let msg: { t?: string; d?: string; code?: number; message?: string };
+ try {
+ msg = JSON.parse(ev.data as string);
+ } catch {
+ return;
+ }
+ if (msg.t === "o") term.write(msg.d ?? "");
+ else if (msg.t === "ready") {
+ everLive = true;
+ setStatus("live");
+ term.focus();
+ } else if (msg.t === "exit") {
+ setStatus("exited");
+ term.write(`\r\n\x1b[33m[process exited: ${msg.code ?? "?"}]\x1b[0m\r\n`);
+ } else if (msg.t === "error") {
+ setStatus("error");
+ setError(msg.message ?? "terminal error");
+ }
+ };
+ ws.onerror = () => {
+ setStatus("error");
+ setError("Connection to the terminal failed.");
+ };
+ ws.onclose = (ev) => {
+ if (everLive) {
+ setStatus("exited");
+ } else if (!disposed) {
+ // Closed during the handshake (e.g. 4401 auth) — surface it honestly
+ // instead of hanging on "connecting" forever (mirrors PtyTerminal).
+ setStatus("error");
+ setError((e) =>
+ e ??
+ (ev.code === 4401
+ ? "Terminal authorization failed — reopen to retry."
+ : `Terminal connection closed (code ${ev.code || "?"}).`),
+ );
+ }
+ };
+
+ term.onData((data) => {
+ if (ws && ws.readyState === WebSocket.OPEN) {
+ ws.send(JSON.stringify({ t: "i", d: data }));
+ }
+ });
+ })();
+
+ window.addEventListener("resize", sendResize);
+ const ro = new ResizeObserver(() => sendResize());
+ ro.observe(container);
+
+ return () => {
+ disposed = true;
+ window.removeEventListener("resize", sendResize);
+ ro.disconnect();
+ try {
+ ws?.close();
+ } catch {
+ /* ignore */
+ }
+ term.dispose();
+ };
+ }, [paneKey, agentName, installName]);
+
+ return (
+ <div className="relative flex h-full w-full flex-col overflow-hidden rounded-lg border border-border bg-[#0b0d10]">
+ <header className="flex items-center justify-between gap-2 border-b border-border bg-card/40 px-3 py-1.5">
+ <div className="flex items-center gap-2 text-xs text-muted-foreground">
+ <TerminalIcon className="h-3.5 w-3.5 text-primary" />
+ <span className="font-mono">{title}</span>
+ </div>
+ <span className="text-[10px] uppercase tracking-wider">
+ {status === "live" ? (
+ <span className="text-emerald-400">live</span>
+ ) : status === "error" ? (
+ <span className="flex items-center gap-1 text-destructive">
+ <AlertCircle className="h-3 w-3" />
+ error
+ </span>
+ ) : status === "exited" ? (
+ <span className="text-muted-foreground">exited</span>
+ ) : (
+ <span className="text-muted-foreground">connecting…</span>
+ )}
+ </span>
+ </header>
+ <div ref={containerRef} className="flex-1 overflow-hidden p-1" />
+ {error && (
+ <div className="border-t border-border bg-destructive/10 px-3 py-1.5 text-[11px] text-destructive">
+ {error}
+ </div>
+ )}
+ </div>
+ );
+}
diff --git a/jarvis/ui/web/frontend/src/hooks/useBrainStatus.ts b/jarvis/ui/web/frontend/src/hooks/useBrainStatus.ts
index cc95fb93f7..ab6f1a1cbd 100644
--- a/jarvis/ui/web/frontend/src/hooks/useBrainStatus.ts
+++ b/jarvis/ui/web/frontend/src/hooks/useBrainStatus.ts
@@ -17,6 +17,7 @@ import { useEventStore } from "@/store/events";
*/
export function useBrainStatus(): void {
const setBrainProvider = useEventStore((s) => s.setBrainProvider);
+ const setBrainModel = useEventStore((s) => s.setBrainModel);
useEffect(() => {
let cancelled = false;
@@ -30,6 +31,12 @@ export function useBrainStatus(): void {
if (typeof data.provider === "string" && data.provider) {
setBrainProvider(data.provider);
}
+ // The endpoint always returns a model; "unknown" means the provider
+ // has no model configured — surface an empty string then so the
+ // sidebar shows only the provider rather than a literal "unknown".
+ if (typeof data.model === "string") {
+ setBrainModel(data.model === "unknown" ? "" : data.model);
+ }
})
.catch(() => {
// Fetch fail (network/timeout) — Store bleibt auf altem Wert,
@@ -50,5 +57,5 @@ export function useBrainStatus(): void {
ctrl.abort();
window.removeEventListener("jarvis:brain-switched", onBrainSwitched);
};
- }, [setBrainProvider]);
+ }, [setBrainProvider, setBrainModel]);
}
diff --git a/jarvis/ui/web/frontend/src/hooks/useCapabilities.ts b/jarvis/ui/web/frontend/src/hooks/useCapabilities.ts
new file mode 100644
index 0000000000..5894befabd
--- /dev/null
+++ b/jarvis/ui/web/frontend/src/hooks/useCapabilities.ts
@@ -0,0 +1,67 @@
+/**
+ * useCapabilities — reports the desktop-shell capabilities the frontend needs
+ * to decide *how* to perform an action.
+ *
+ * `native_file_actions` is true only on a local desktop run (pywebview); false
+ * on a headless VPS reached through a browser. Download buttons use it to choose
+ * between a backend save to the local ~/Downloads (desktop) and a normal browser
+ * download (VPS/browser).
+ *
+ * Implemented without react-query on purpose: this is a cross-cutting capability
+ * consumed by leaf components (TurnCard, ShareDialog) that are rendered — and
+ * unit-tested — outside any QueryClientProvider. A module-level cache + a shared
+ * in-flight promise dedupe the request so many components trigger only one fetch
+ * (the same dedup react-query would give, without the provider requirement).
+ */
+import { useEffect, useState } from "react";
+
+export interface Capabilities {
+ native_file_actions: boolean;
+ platform: "win32" | "darwin" | "linux";
+}
+
+let _cache: Capabilities | null = null;
+let _inflight: Promise<Capabilities> | null = null;
+
+function loadCapabilities(): Promise<Capabilities> {
+ if (_cache) return Promise.resolve(_cache);
+ if (_inflight) return _inflight;
+ // Promise.resolve().then(...) so a missing/relative-URL fetch (e.g. in a unit
+ // test with no server) becomes a rejected promise, never a synchronous throw.
+ _inflight = Promise.resolve()
+ .then(() => fetch("/api/downloads/capabilities"))
+ .then((r) => {
+ if (!r.ok) throw new Error(`HTTP ${r.status}`);
+ return r.json() as Promise<Capabilities>;
+ })
+ .then((c) => {
+ _cache = c;
+ return c;
+ })
+ .catch((e) => {
+ _inflight = null; // allow a retry on the next mount
+ throw e;
+ });
+ return _inflight;
+}
+
+/** Returns `{ data }` (undefined until loaded) — mirrors the react-query hooks
+ * used elsewhere so call sites read `caps.data?.native_file_actions`. */
+export function useCapabilities(): { data: Capabilities | undefined } {
+ const [data, setData] = useState<Capabilities | undefined>(_cache ?? undefined);
+ useEffect(() => {
+ let alive = true;
+ loadCapabilities()
+ .then((c) => {
+ if (alive) setData(c);
+ })
+ .catch(() => {
+ // Treated as "not native" by callers — they fall back to the browser
+ // download, which is the correct behavior outside the desktop shell.
+ });
+ return () => {
+ alive = false;
+ };
+ }, []);
+ return { data };
+}
diff --git a/jarvis/ui/web/frontend/src/hooks/useOutputs.ts b/jarvis/ui/web/frontend/src/hooks/useOutputs.ts
index 32266da13f..cc8c5b2ca4 100644
--- a/jarvis/ui/web/frontend/src/hooks/useOutputs.ts
+++ b/jarvis/ui/web/frontend/src/hooks/useOutputs.ts
@@ -51,6 +51,12 @@ export interface OutputSummary {
started_at?: number;
github_url?: string | null;
error?: string | null;
+ /** When this terminal mission has already been continued/restarted and that
+ * re-run is still running, the full id + slug of that live child. The card
+ * then shows a "running" indicator pointing at the child instead of a
+ * redundant Continue/Restart button. */
+ active_child_id?: string | null;
+ active_child_slug?: string | null;
}
export function useOutputsList() {
diff --git a/jarvis/ui/web/frontend/src/hooks/useOverlayStyle.ts b/jarvis/ui/web/frontend/src/hooks/useOverlayStyle.ts
index fe9994f2f2..f7a686f810 100644
--- a/jarvis/ui/web/frontend/src/hooks/useOverlayStyle.ts
+++ b/jarvis/ui/web/frontend/src/hooks/useOverlayStyle.ts
@@ -2,9 +2,9 @@ import { useCallback, useEffect, useState } from "react";
/**
* On-screen overlay style from GET /api/settings/overlay-style.
- * "whisper_bar" = slim default bar, "mascot" = ghost orb, "none" = hidden.
+ * "jarvis_bar" = slim default bar, "mascot" = ghost orb, "none" = hidden.
*/
-export type OverlayStyle = "whisper_bar" | "mascot" | "none";
+export type OverlayStyle = "jarvis_bar" | "mascot" | "none";
export interface OverlayStyleConfig {
style: OverlayStyle;
@@ -59,7 +59,7 @@ export function useOverlayStyle() {
setConfig((prev) =>
prev
? { ...prev, style: result.style }
- : { style: result.style, options: ["whisper_bar", "mascot", "none"] },
+ : { style: result.style, options: ["jarvis_bar", "mascot", "none"] },
);
return result;
},
diff --git a/jarvis/ui/web/frontend/src/hooks/useProviders.ts b/jarvis/ui/web/frontend/src/hooks/useProviders.ts
index 5b519e2707..644f57e690 100644
--- a/jarvis/ui/web/frontend/src/hooks/useProviders.ts
+++ b/jarvis/ui/web/frontend/src/hooks/useProviders.ts
@@ -94,6 +94,29 @@ export interface AntigravityStatus {
error: string | null;
}
+/**
+ * Mirror of `jarvis/claude_auth.py::ClaudeAuthStatus.to_dict()`. The Anthropic
+ * sibling of `CodexStatus` / `AntigravityStatus`: whether the `claude` CLI is
+ * installed and whether the subagent runs over the Claude Max subscription
+ * (the OAuth login) or an Anthropic API key, plus the connected account email +
+ * subscription tier so the card can show "Connected as <email>".
+ */
+export interface ClaudeStatus {
+ installed: boolean;
+ connected: boolean;
+ mode: string; // "subscription" | "api_key" | "unknown"
+ message: string;
+ version?: string | null;
+ account_label?: string | null;
+ user_email?: string | null;
+ subscription_type?: string | null; // raw tier, e.g. "max"
+ binary_path?: string | null;
+ error?: string | null;
+ /** True when a classic Anthropic API key (sk-ant-api…) is stored — drives the
+ * API-key field's "configured" state on the subagent card. Never the key. */
+ api_key_present?: boolean;
+}
+
interface ProvidersResponse {
providers: ProviderDescriptor[];
}
@@ -159,6 +182,81 @@ export function useProviders() {
return { providers, loading, error, refetch, setActiveOptimistic };
}
+// ── Section health (the at-a-glance API-Keys tab indicators) ────────────────
+// Mirrors SECTION_HEALTH_STATUSES in jarvis/brain/section_health.py and the
+// SectionHealthStatusLiteral in provider_routes.py (five-layer anti-drift; a
+// backend parity test guards the Python↔Pydantic side, this union is the UI
+// mirror). Only "needs_setup" (amber) and "error" (red) draw a dot; "ok" and
+// "unknown" stay silent.
+export type SectionHealthStatus = "ok" | "needs_setup" | "error" | "unknown";
+
+export interface SectionHealth {
+ status: SectionHealthStatus;
+ /** Machine cause (the underlying provider-test status / "not_configured" /
+ * "no_active" / "local" / "ok" / "unknown") — for tooltips + debugging. */
+ reason: string;
+ /** Plain-English one-liner for the hover tooltip. */
+ detail: string;
+}
+
+export interface SectionHealthResponse {
+ sections: Record<string, SectionHealth>;
+ checked_at: number;
+ cached: boolean;
+}
+
+/**
+ * Fetches the per-tab health rollup. `refresh=true` bypasses the server-side
+ * TTL cache — used right after a key save / provider switch so the dot reflects
+ * the change immediately instead of a stale cached result.
+ */
+export async function getSectionHealth(refresh = false): Promise<SectionHealthResponse> {
+ const res = await fetch(
+ `/api/providers/section-health${refresh ? "?refresh=true" : ""}`,
+ );
+ if (!res.ok) throw new Error(`HTTP ${res.status}`);
+ return (await res.json()) as SectionHealthResponse;
+}
+
+/**
+ * Drives the tab status dots in the API-Keys view. Fetches once on mount (the
+ * server runs the REAL connectivity test of each tier's active provider, cached
+ * briefly) and re-fetches with `refresh=true` whenever a key is saved, a provider
+ * is switched, or a manual per-card test completes — so the dot tracks live.
+ *
+ * Health is best-effort: a failed fetch leaves the map empty (no dots), never
+ * breaking the page.
+ */
+export function useSectionHealth() {
+ const [health, setHealth] = useState<Record<string, SectionHealth>>({});
+
+ const reload = useCallback(async (refresh = false) => {
+ try {
+ const data = await getSectionHealth(refresh);
+ setHealth(data.sections ?? {});
+ } catch {
+ // best-effort — keep whatever we last had rather than clearing to nothing
+ }
+ }, []);
+
+ useEffect(() => {
+ void reload(false);
+ const onChange = () => void reload(true);
+ const events = [
+ "jarvis:secret-configured",
+ "jarvis:brain-switched",
+ "jarvis:tts-switched",
+ "jarvis:stt-switched",
+ "jarvis:subagent-switched",
+ "jarvis:provider-tested",
+ ];
+ events.forEach((e) => window.addEventListener(e, onChange));
+ return () => events.forEach((e) => window.removeEventListener(e, onChange));
+ }, [reload]);
+
+ return { health, reload };
+}
+
export async function postSecret(key: string, value: string): Promise<void> {
const res = await fetch(`/api/secrets/${encodeURIComponent(key)}`, {
method: "POST",
@@ -230,6 +328,34 @@ export async function logoutAntigravity(): Promise<void> {
}
}
+/**
+ * Starts the interactive Claude sign-in by driving the `claude` CLI as a
+ * subprocess (POST /api/claude/login). The Anthropic sibling of
+ * `startCodexLogin` — a 409 means no Claude CLI is installed (the detail carries
+ * an install_command).
+ */
+export async function loginClaude(): Promise<void> {
+ const res = await fetch("/api/claude/login", { method: "POST" });
+ const body = await res.json().catch(() => ({}));
+ if (!res.ok) {
+ const detail = body.detail;
+ throw new Error(
+ typeof detail === "object" && detail?.message
+ ? detail.message
+ : detail ?? `HTTP ${res.status}`,
+ );
+ }
+}
+
+/** Disconnects the Claude subscription login (POST /api/claude/logout). */
+export async function logoutClaude(): Promise<void> {
+ const res = await fetch("/api/claude/logout", { method: "POST" });
+ const body = await res.json().catch(() => ({}));
+ if (!res.ok) {
+ throw new Error(body.detail ?? `HTTP ${res.status}`);
+ }
+}
+
export async function setCodexBinaryPath(binaryPath: string): Promise<void> {
const res = await fetch("/api/codex/binary-path", {
method: "POST",
diff --git a/jarvis/ui/web/frontend/src/hooks/useVoiceReadiness.test.tsx b/jarvis/ui/web/frontend/src/hooks/useVoiceReadiness.test.tsx
new file mode 100644
index 0000000000..41eb498ae1
--- /dev/null
+++ b/jarvis/ui/web/frontend/src/hooks/useVoiceReadiness.test.tsx
@@ -0,0 +1,53 @@
+/**
+ * useVoiceReadiness is the single source of truth for "can the user speak yet?".
+ * Before it existed, the sidebar, the warming banner and the chat empty-state
+ * each derived readiness on their own (and the empty-state ignored it), so the
+ * banner could say "starting up" while the centre said "Ready for commands".
+ * These tests lock the four readiness states.
+ */
+import { renderHook, cleanup } from "@testing-library/react";
+import { afterEach, describe, expect, it } from "vitest";
+
+import { useVoiceReadiness } from "@/hooks/useVoiceReadiness";
+import { useEventStore } from "@/store/events";
+
+function set(connected: boolean, wsWarming: boolean, voiceReady: boolean) {
+ useEventStore.setState({ connected, wsWarming, voiceReady });
+}
+
+describe("useVoiceReadiness (single source of truth)", () => {
+ afterEach(() => cleanup());
+
+ it("warms while the socket is up but voice is not ready yet", () => {
+ set(true, false, false);
+ const { result } = renderHook(() => useVoiceReadiness());
+ expect(result.current.warming).toBe(true);
+ expect(result.current.voiceWarming).toBe(true);
+ expect(result.current.bootWarming).toBe(false);
+ expect(result.current.ready).toBe(false);
+ });
+
+ it("warms while the fast-boot socket is still binding (not connected)", () => {
+ set(false, true, false);
+ const { result } = renderHook(() => useVoiceReadiness());
+ expect(result.current.warming).toBe(true);
+ expect(result.current.bootWarming).toBe(true);
+ expect(result.current.voiceWarming).toBe(false);
+ expect(result.current.ready).toBe(false);
+ });
+
+ it("is ready only when connected AND voice is ready", () => {
+ set(true, false, true);
+ const { result } = renderHook(() => useVoiceReadiness());
+ expect(result.current.warming).toBe(false);
+ expect(result.current.ready).toBe(true);
+ });
+
+ it("is offline (not warming, not ready) when disconnected and not warming", () => {
+ set(false, false, false);
+ const { result } = renderHook(() => useVoiceReadiness());
+ expect(result.current.warming).toBe(false);
+ expect(result.current.ready).toBe(false);
+ expect(result.current.connected).toBe(false);
+ });
+});
diff --git a/jarvis/ui/web/frontend/src/hooks/useVoiceReadiness.ts b/jarvis/ui/web/frontend/src/hooks/useVoiceReadiness.ts
new file mode 100644
index 0000000000..4e775fb65d
--- /dev/null
+++ b/jarvis/ui/web/frontend/src/hooks/useVoiceReadiness.ts
@@ -0,0 +1,48 @@
+import { useEventStore } from "@/store/events";
+
+export interface VoiceReadiness {
+ /**
+ * The user cannot speak yet: either the socket is up but the voice stack is
+ * still warming (`connected && !voiceReady`), or the fast-boot backend is
+ * still binding (`!connected && wsWarming`).
+ */
+ warming: boolean;
+ /** Socket up AND the voice stack can really hear + speak. */
+ ready: boolean;
+ /** Welcome-gated socket connection (typing is allowed once this is true). */
+ connected: boolean;
+ /** Connected but the voice stack is not ready yet (drives "Voice starting…"). */
+ voiceWarming: boolean;
+ /** Socket not up yet but the fast-boot backend is warming (drives "Starting…"). */
+ bootWarming: boolean;
+}
+
+/**
+ * Single source of truth for "can the user speak yet?".
+ *
+ * Before 2026-06-29 the Sidebar status line, the VoiceWarmingBanner and the
+ * ChatsView empty-state each derived readiness on their own — and the
+ * empty-state ignored it entirely, so the banner could honestly say "starting
+ * up" while the centre of the screen claimed "Ready for commands". Centralising
+ * the one true derivation here keeps every readiness surface in sync.
+ *
+ * The `warming` expression is the union the banner and sidebar already used:
+ * (connected && !voiceReady) || (!connected && wsWarming)
+ */
+export function useVoiceReadiness(): VoiceReadiness {
+ const connected = useEventStore((s) => s.connected);
+ const wsWarming = useEventStore((s) => s.wsWarming);
+ const voiceReady = useEventStore((s) => s.voiceReady);
+
+ const voiceWarming = connected && !voiceReady;
+ const bootWarming = !connected && wsWarming;
+ const warming = voiceWarming || bootWarming;
+
+ return {
+ warming,
+ ready: connected && voiceReady,
+ connected,
+ voiceWarming,
+ bootWarming,
+ };
+}
diff --git a/jarvis/ui/web/frontend/src/hooks/useWebSocket.test.tsx b/jarvis/ui/web/frontend/src/hooks/useWebSocket.test.tsx
index f8134bcf64..6734ae816b 100644
--- a/jarvis/ui/web/frontend/src/hooks/useWebSocket.test.tsx
+++ b/jarvis/ui/web/frontend/src/hooks/useWebSocket.test.tsx
@@ -103,3 +103,50 @@ describe("useWebSocket VoiceBootStatus handling", () => {
expect(useEventStore.getState().voiceReady).toBe(false);
});
});
+
+describe("useWebSocket connection state (welcome-gated + warming)", () => {
+ const OriginalWS = globalThis.WebSocket;
+
+ beforeEach(() => {
+ (globalThis as unknown as { WebSocket: typeof MockWebSocket }).WebSocket =
+ MockWebSocket;
+ (window as unknown as { location: unknown }).location = {
+ protocol: "http:",
+ host: "localhost:5173",
+ };
+ (window as unknown as { __JARVIS_TOKEN?: string }).__JARVIS_TOKEN = undefined;
+ useEventStore.setState({ connected: false, wsWarming: true });
+ });
+
+ afterEach(() => {
+ cleanup();
+ (globalThis as unknown as { WebSocket: typeof WebSocket }).WebSocket =
+ OriginalWS;
+ MockWebSocket.last = null;
+ });
+
+ it("marks connected only when the welcome frame arrives", async () => {
+ render(<Harness />);
+ await Promise.resolve(); // run the queued "open"
+ // Raw socket open alone must NOT mark connected (the bootstrap also opens).
+ expect(useEventStore.getState().connected).toBe(false);
+ MockWebSocket.last!.deliver({
+ type: "welcome",
+ session_id: "s",
+ version: "0.1.0",
+ token: "t",
+ });
+ expect(useEventStore.getState().connected).toBe(true);
+ expect(useEventStore.getState().wsWarming).toBe(false);
+ });
+
+ it("sets wsWarming on a 1013 close and clears it on a non-1013 close", async () => {
+ render(<Harness />);
+ await Promise.resolve();
+ MockWebSocket.last!.fire("close", { code: 1013 });
+ expect(useEventStore.getState().wsWarming).toBe(true);
+ expect(useEventStore.getState().connected).toBe(false);
+ MockWebSocket.last!.fire("close", { code: 1006 });
+ expect(useEventStore.getState().wsWarming).toBe(false);
+ });
+});
diff --git a/jarvis/ui/web/frontend/src/hooks/useWebSocket.ts b/jarvis/ui/web/frontend/src/hooks/useWebSocket.ts
index 5cac7dace1..f729dcaa6f 100644
--- a/jarvis/ui/web/frontend/src/hooks/useWebSocket.ts
+++ b/jarvis/ui/web/frontend/src/hooks/useWebSocket.ts
@@ -29,6 +29,7 @@ export function getWSClient(): WSClient | null {
export function useWebSocket(): void {
const mounted = useRef(false);
const setConnected = useEventStore((s) => s.setConnected);
+ const setWarming = useEventStore((s) => s.setWarming);
const pushEvent = useEventStore((s) => s.pushEvent);
const setVoice = useEventStore((s) => s.setVoice);
const setVoiceReady = useEventStore((s) => s.setVoiceReady);
@@ -44,11 +45,39 @@ export function useWebSocket(): void {
mounted.current = true;
const client = new WSClient({
- onOpen: () => setConnected(true),
- onClose: () => setConnected(false),
+ // `connected` is welcome-gated (see the welcome branch below), so a raw
+ // socket open must NOT mark connected — the fast-boot bootstrap also
+ // opens then closes with 1013 without ever sending a welcome frame.
+ onOpen: () => {},
+ onClose: (code) => {
+ // 1013 = bootstrap "try again later" → backend still warming, not down.
+ setWarming(code === 1013);
+ setConnected(false);
+ },
onMessage: (raw) => {
const welcome = WSWelcome.safeParse(raw);
- if (welcome.success) return;
+ if (welcome.success) {
+ // The real app sends `welcome` immediately after accepting the socket;
+ // this — not the raw open — is the authoritative "connected" signal.
+ setConnected(true);
+ setWarming(false);
+ // Re-seed voiceReady on EVERY (re)connect. VoiceBootStatus is a
+ // one-shot bus event, so a socket that (re)connects after readiness
+ // already flipped — e.g. the fast-boot 1013 reconnect — or whose
+ // one-time mount-seed (useVoiceStatus) failed would otherwise keep a
+ // stale value and leave the banner stuck on "starting up". This makes
+ // the REST mirror the authoritative source on each connect.
+ void fetch("/api/voice/status")
+ .then((r) => (r.ok ? r.json() : null))
+ .then((data) => {
+ if (data && typeof data.ready === "boolean") setVoiceReady(data.ready);
+ })
+ .catch(() => {
+ // Offline / headless: keep the current value; the live
+ // VoiceBootStatus event still updates it if/when it arrives.
+ });
+ return;
+ }
const parsed = WSEventEnvelope.safeParse(raw);
if (!parsed.success) return;
@@ -188,6 +217,10 @@ export function useWebSocket(): void {
if (typeof p.to_provider === "string") {
setBrainProvider(p.to_provider);
pushToast("success", `Brain → ${p.to_provider}`);
+ // The switch payload carries no model, so re-fetch the authoritative
+ // status (provider + model) — keeps the sidebar model line fresh
+ // after a voice/UI provider switch. useBrainStatus listens for this.
+ window.dispatchEvent(new CustomEvent("jarvis:brain-switched"));
}
}
@@ -253,6 +286,7 @@ export function useWebSocket(): void {
};
}, [
setConnected,
+ setWarming,
pushEvent,
setVoice,
setVoiceReady,
diff --git a/jarvis/ui/web/frontend/src/i18n/index.ts b/jarvis/ui/web/frontend/src/i18n/index.ts
index 5dfa42efe1..029f40897e 100644
--- a/jarvis/ui/web/frontend/src/i18n/index.ts
+++ b/jarvis/ui/web/frontend/src/i18n/index.ts
@@ -14,8 +14,9 @@
* const lang = useUiLanguage(); // "en" | "de" | "es"
* setUiLanguage("de"); // sofort reactive
*
- * Voice-Sprache (was Whisper erkennt) ist ein eigenes Setting:
- * useVoiceLanguage(), setVoiceLanguage("auto" | "en" | "de" | "es")
+ * STT recognition language (what Whisper transcribes the spoken voice INTO) is
+ * its own setting, distinct from the UI and the reply language:
+ * useSttLanguage(), setSttLanguage("auto" | "en" | "de" | "es")
*/
import { create } from "zustand";
import enJson from "./locales/en.json";
@@ -27,10 +28,16 @@ export type UiLanguage = "en" | "de" | "es";
// "auto" mirrors the user's input language; the rest hard-pin the reply language.
// Mirrors jarvis/brain/manager.py::SUPPORTED_REPLY_LANGUAGES (single source of truth).
export type ReplyLanguage = "auto" | "en" | "de" | "es";
+// "auto" lets Whisper detect the spoken language per utterance (bilingual
+// default); a concrete code forces what the recogniser transcribes into.
+// Mirrors jarvis/ui/web/settings_routes.py::_STT_LANGUAGES.
+export type SttLanguage = "auto" | "en" | "de" | "es";
const REPLY_LANGUAGE_ENDPOINT = "/api/settings/reply-language";
const UI_LANGUAGE_ENDPOINT = "/api/settings/ui-language";
+const STT_LANGUAGE_ENDPOINT = "/api/settings/stt-language";
const REPLY_VALUES: readonly ReplyLanguage[] = ["auto", "en", "de", "es"];
+const STT_VALUES: readonly SttLanguage[] = ["auto", "en", "de", "es"];
function isUiLanguage(v: unknown): v is UiLanguage {
return v === "en" || v === "de" || v === "es";
@@ -40,6 +47,10 @@ function isReplyLanguage(v: unknown): v is ReplyLanguage {
return typeof v === "string" && (REPLY_VALUES as readonly string[]).includes(v);
}
+function isSttLanguage(v: unknown): v is SttLanguage {
+ return typeof v === "string" && (STT_VALUES as readonly string[]).includes(v);
+}
+
const RESOURCES: Record<UiLanguage, Record<string, unknown>> = {
en: enJson as Record<string, unknown>,
de: deJson as Record<string, unknown>,
@@ -48,6 +59,7 @@ const RESOURCES: Record<UiLanguage, Record<string, unknown>> = {
const UI_KEY = "jarvis.ui.language";
const REPLY_KEY = "jarvis.reply.language";
+const STT_KEY = "jarvis.stt.language";
function readUi(): UiLanguage {
try {
@@ -69,6 +81,16 @@ function readReply(): ReplyLanguage {
return "auto";
}
+function readStt(): SttLanguage {
+ try {
+ const raw = localStorage.getItem(STT_KEY);
+ if (isSttLanguage(raw)) return raw;
+ } catch {
+ /* ignore */
+ }
+ return "auto";
+}
+
/**
* Push the reply language to the backend BrainManager. Fire-and-forget: the UI
* stays responsive and a transient backend hiccup never blocks the click. The
@@ -107,6 +129,43 @@ export async function hydrateReplyLanguage(): Promise<void> {
}
}
+/**
+ * Push the STT recognition language to the backend. Fire-and-forget. Persists to
+ * jarvis.toml [stt].language; applies on the next voice restart (the STT provider
+ * is built once at voice bootstrap), so the UI hints at a restart after a change.
+ */
+function pushStt(lang: SttLanguage): void {
+ try {
+ void fetch(STT_LANGUAGE_ENDPOINT, {
+ method: "PUT",
+ headers: { "Content-Type": "application/json" },
+ body: JSON.stringify({ language: lang }),
+ }).catch(() => {
+ /* offline / headless — localStorage re-syncs on next mount */
+ });
+ } catch {
+ /* fetch unavailable (SSR / tests without stub) */
+ }
+}
+
+/**
+ * Pull the persisted STT recognition language from the backend and reflect it so
+ * the UI shows the real boot default. Call once on the Languages view mount. On
+ * failure the localStorage value (already in the store) stands.
+ */
+export async function hydrateSttLanguage(): Promise<void> {
+ try {
+ const res = await fetch(STT_LANGUAGE_ENDPOINT);
+ if (!res.ok) return;
+ const body = (await res.json()) as { language?: unknown };
+ if (isSttLanguage(body.language)) {
+ useI18nStore.getState().setStt(body.language, { push: false });
+ }
+ } catch {
+ /* keep the local value */
+ }
+}
+
/**
* Push the interface (display) language to the backend. The UI language is now
* backend-backed (not just localStorage) so a voice command / the Control API
@@ -147,13 +206,16 @@ export async function hydrateUiLanguage(): Promise<void> {
interface I18nState {
ui: UiLanguage;
reply: ReplyLanguage;
+ stt: SttLanguage;
setUi: (lang: UiLanguage, opts?: { push?: boolean }) => void;
setReply: (lang: ReplyLanguage, opts?: { push?: boolean }) => void;
+ setStt: (lang: SttLanguage, opts?: { push?: boolean }) => void;
}
export const useI18nStore = create<I18nState>((set) => ({
ui: readUi(),
reply: readReply(),
+ stt: readStt(),
setUi: (lang, opts) => {
try {
localStorage.setItem(UI_KEY, lang);
@@ -180,6 +242,19 @@ export const useI18nStore = create<I18nState>((set) => ({
pushReply(lang);
}
},
+ setStt: (lang, opts) => {
+ try {
+ localStorage.setItem(STT_KEY, lang);
+ } catch {
+ /* ignore */
+ }
+ set({ stt: lang });
+ // Default: propagate to the backend. Hydrate passes push:false to avoid a
+ // GET→PUT echo loop.
+ if (opts?.push !== false) {
+ pushStt(lang);
+ }
+ },
}));
/**
@@ -250,6 +325,10 @@ export function useReplyLanguage(): ReplyLanguage {
return useI18nStore((s) => s.reply);
}
+export function useSttLanguage(): SttLanguage {
+ return useI18nStore((s) => s.stt);
+}
+
export function setUiLanguage(lang: UiLanguage): void {
useI18nStore.getState().setUi(lang);
}
@@ -257,3 +336,7 @@ export function setUiLanguage(lang: UiLanguage): void {
export function setReplyLanguage(lang: ReplyLanguage): void {
useI18nStore.getState().setReply(lang);
}
+
+export function setSttLanguage(lang: SttLanguage): void {
+ useI18nStore.getState().setStt(lang);
+}
diff --git a/jarvis/ui/web/frontend/src/i18n/locales/de.json b/jarvis/ui/web/frontend/src/i18n/locales/de.json
index 63e96f4632..e69d3b264d 100644
--- a/jarvis/ui/web/frontend/src/i18n/locales/de.json
+++ b/jarvis/ui/web/frontend/src/i18n/locales/de.json
@@ -17,7 +17,7 @@
},
"nav": {
"chats": "Chats",
- "agents": "Agents",
+ "agents": "Jarvis-Agents",
"extensions": "Skills, Plugins & MCPs",
"skills": "Skills",
"plugins": "Plugins",
@@ -41,8 +41,38 @@
"socials": "Socials",
"taskbar": "Taskbar",
"contacts": "Kontakte",
+ "feedback": "Feedback",
+ "personalize": "Mach's zu deinem",
"agent_instructions": "{name}.md"
},
+ "make_it_yours": {
+ "title": "Mach's zu deinem",
+ "subtitle": "Öffne Coding-Agents direkt in deinem Jarvis-Ordner und mach ihn persönlich.",
+ "step_layout": "Wie viele Terminals?",
+ "step_layout_hint": "Wähle ein Layout — eine Kachel pro Terminal-Anzahl.",
+ "step_agents": "Welche Agents?",
+ "step_agents_hint": "Lege fest, wie viele von jedem Agenten deine Terminals füllen. Nur Claude Code und Codex.",
+ "quick_fill": "Schnellwahl",
+ "split_evenly": "Gleichmäßig aufteilen",
+ "all_claude": "Alles Claude Code",
+ "all_codex": "Alles Codex",
+ "installed": "Installiert",
+ "not_installed": "Nicht installiert",
+ "install": "Im Terminal installieren",
+ "installing": "Installer wird im Terminal geöffnet…",
+ "step_confirm": "Bereit zum Start",
+ "folder": "Ordner",
+ "launch": "Starten",
+ "launching": "Wird gestartet…",
+ "back": "Zurück",
+ "next": "Weiter",
+ "no_terminal": "Auf diesem Host läuft kein Terminal (keine Shell bzw. kein PTY-Backend), daher können die Agents hier nicht gestartet werden.",
+ "launched_ok": "Terminals geöffnet",
+ "launch_failed": "Einige Terminals konnten nicht geöffnet werden.",
+ "terminals": "Terminals",
+ "end_session": "Sitzung beenden",
+ "install_done": "Fertig — neu prüfen"
+ },
"agent_instructions": {
"subtitle": "Deine persönlichen Präferenzen, wie der Assistent mit dir arbeitet — Ton, Sprache, Voreinstellungen, dauerhafte Fakten. Getrennt vom System-Prompt und hebelt niemals Sicherheit oder Bestätigungen aus.",
"active_badge": "Aktiv",
@@ -155,7 +185,11 @@
"speaking": "Spricht",
"error": "Fehler",
"offline": "Offline",
- "starting": "Sprachmodul startet…"
+ "booting": "Startet…",
+ "starting": "Sprachmodul startet…",
+ "warming_title": "Jarvis fährt hoch",
+ "warming_hint": "Das Zuhören wird vorbereitet – einen Moment, gleich kannst du sprechen.",
+ "ready_title": "Bereit – du kannst jetzt sprechen"
},
"sidebar": {
"wake_hint": "Sag dein Wake-Word…",
@@ -169,6 +203,8 @@
"thinking_label": "denkt nach…",
"empty_title": "Bereit für Befehle",
"empty_subtitle": "Sag dein Wake-Word oder schreibe unten deine Nachricht. Dein Assistent dirigiert Sub-Agents, ruft Tools auf und gibt dir eine Stimme zurück.",
+ "warming_title": "Macht sich bereit",
+ "warming_subtitle": "Dein Assistent startet gerade. Gleich kannst du sprechen, tippen geht schon jetzt.",
"examples": {
"0": "Zeig die Agents",
"1": "Wechsel Brain auf Gemini",
@@ -212,7 +248,7 @@
"step_cu_settle": "Wartet auf den Bildschirm"
},
"subagents_view": {
- "title": "Sub-Agents",
+ "title": "Jarvis-Agents",
"stat_active": "aktiv",
"stat_total": "gesamt",
"clear": "Leeren",
@@ -220,11 +256,11 @@
"board_title": "Abfahrtstafel",
"active_label": "Aktiv",
"standby_label": "Standby",
- "col_agent": "Agent",
+ "col_agent": "Jarvis-Agent",
"col_target": "Ziel",
"col_status": "Status",
"col_cost": "Kosten",
- "agents_traveling": "Agent(s) unterwegs",
+ "agents_traveling": "Jarvis-Agent(s) unterwegs",
"last_departure": "letzte Abfahrt",
"last_departure_ago": "letzte Abfahrt vor {0}",
"status": {
@@ -302,6 +338,23 @@
"tier_fast": "Schnell",
"tier_auto": "Auto",
"tier_deep": "Stark",
+ "trigger_mode_label": "Auslöser",
+ "mode_schedule": "Zeitplan",
+ "mode_event": "Wenn-Dann",
+ "when_label": "Wenn",
+ "when_mission_succeeded": "Eine Mission ist fertig",
+ "when_mission_failed": "Eine Mission scheitert",
+ "when_mission_cancelled": "Eine Mission wird abgebrochen",
+ "then_label": "Dann",
+ "then_computer_use": "Computer-Use",
+ "then_agent": "Agenten-Aufgabe",
+ "then_notify": "Nur Bescheid sagen",
+ "cu_goal_label": "Was soll Computer-Use tun?",
+ "cu_goal_placeholder": "z. B. Öffne {result_uri} im Browser.",
+ "announce_label": "Bescheid sagen, wenn fertig (optional)",
+ "notify_text_label": "Was soll gesagt werden?",
+ "announce_placeholder": "z. B. Deine Mission ist fertig — ich habe sie im Browser geöffnet.",
+ "when_then_hint": "Wird jedes Mal ausgelöst. Du kannst {result_uri}, {summary_de} oder {mission_id} als Platzhalter im Text oben verwenden.",
"cancel": "Abbrechen",
"save": "Aufgabe erstellen",
"save_error": "Aufgabe konnte nicht erstellt werden."
@@ -655,6 +708,13 @@
"more_to_learn": "{0} weitere offen",
"value_yes": "ja",
"value_no": "nein",
+ "field_edit": "Bearbeiten",
+ "field_clear": "Löschen",
+ "field_remove_item": "Entfernen",
+ "field_add": "Hinzufügen",
+ "field_add_placeholder": "Hinzufügen…",
+ "field_value_placeholder": "Wert…",
+ "field_saved": "Gespeichert",
"review_confirm": "Stimmt",
"review_strike": "Streichen",
"questions": {
@@ -772,7 +832,7 @@
},
"apikeys_view": {
"title": "API-Keys & Provider",
- "subtitle": "Codex nutzt den offiziellen ChatGPT/Codex-Login.",
+ "subtitle": "Verbinde Provider und lege fest, was die einzelnen Teile von Jarvis antreibt.",
"save": "Speichern",
"saved": "Gespeichert",
"missing": "Fehlt",
@@ -785,6 +845,20 @@
"tier_stt": "Voice-Input (STT)",
"tier_subagent": "Subagent (Heavy-Tasks)",
"tier_telephony": "Telefonie",
+ "tab_brain": "Brain",
+ "tab_tts": "Sprachausgabe",
+ "tab_stt": "Spracheingabe",
+ "tab_subagents": "Jarvis-Agents",
+ "tab_advanced": "Erweitert",
+ "cat_brain_desc": "Das Modell, das Chat, Routing und Computer-Use antreibt.",
+ "cat_tts_desc": "Die Stimme, mit der Jarvis spricht.",
+ "cat_stt_desc": "Wie Jarvis deine Sprache in Text umwandelt.",
+ "cat_subagents_title": "Jarvis-Agents",
+ "cat_subagents_desc": "Wähle, welcher Provider schwere Hintergrund-Aufgaben übernimmt.",
+ "advanced_title": "Zugang & Integrationen",
+ "advanced_desc": "Optionale Extras: Control-API-Zugang, der Team-Key-Proxy, Telefonie und der Wissens-Wiki-Provider.",
+ "no_providers_in_tier": "In dieser Kategorie sind keine Provider verfügbar.",
+ "model_picker_activate_hint": "Aktiviere diesen Provider, um seine Stimme oder sein Modell zu wählen.",
"active_tooltip": "Bereits aktiv",
"click_to_activate": "Klick aktiviert diesen Provider",
"needs_codex": "Erst Codex verbinden oder API-Key speichern",
@@ -792,6 +866,9 @@
"needs_key": "Erst API-Key speichern, dann aktivierbar",
"recommended": "Empfohlen",
"recommended_tooltip": "Empfohlenes Modell: {0}",
+ "health_needs_setup": "Einrichtung nötig",
+ "health_error": "Funktioniert nicht",
+ "health_ok": "Funktioniert",
"security_notice": ""
},
"apikeys_test": {
@@ -822,7 +899,8 @@
"load_failed": "Modelle konnten nicht geladen werden",
"source_static": "Standardliste",
"source_static_note": "Live-Katalog nicht erreichbar — gepflegte Standardauswahl.",
- "more_hint": "{0} weitere — Suche verfeinern",
+ "count_hint": "{0} Modelle im Katalog",
+ "open_on_provider": "Auf OpenRouter ansehen",
"choose_placeholder": "Modell wählen…",
"heading_voice": "Stimme",
"choose_voice": "Stimme wählen…",
@@ -946,7 +1024,7 @@
"saved": "Anzeige-Stil gewechselt.",
"restart_required": "Gespeichert — {name} neu starten zum Übernehmen.",
"options": {
- "whisper_bar": "Bar (Standard)",
+ "jarvis_bar": "Bar (Standard)",
"mascot": "Maskottchen-Orb",
"none": "Keins (ausgeblendet)"
}
@@ -1123,6 +1201,7 @@
"restart_label": "Neu starten",
"rerun_starting": "Wird gestartet…",
"rerun_confirm": "Erneut ausführen",
+ "continuation_running": "Fortgesetzt · läuft",
"list_load_error": "Outputs nicht geladen",
"empty_sessions": "Noch keine Sub-Agent-Sessions. Starte einen OpenClaw-Task.",
"select_session": "Wähle eine Session.",
@@ -1292,6 +1371,13 @@
"cta": "Los geht's",
"skip_setup": "Einrichtung vorerst überspringen"
},
+ "tutorial": {
+ "title": "Sieh dir die 2-Minuten-Tour an",
+ "body": "Ein kurzer Überblick, was Personal Jarvis kann und wie die Einrichtung läuft. Du kannst überspringen und sofort loslegen.",
+ "continue": "Weiter",
+ "skip": "Video überspringen",
+ "play": "Tutorial-Video abspielen"
+ },
"risk": {
"title": "Bevor du fortfährst",
"lead": "Personal Jarvis ist mächtige, experimentelle Software.",
@@ -1348,12 +1434,12 @@
"body": "Wie soll dein Assistent auf dem Bildschirm erscheinen? Du kannst das jederzeit in den Einstellungen ändern.",
"recommended": "Empfohlen",
"options": {
- "whisper_bar": "Jarvis-Leiste",
+ "jarvis_bar": "Jarvis-Leiste",
"mascot": "Orb",
"none": "Kein Overlay"
},
"captions": {
- "whisper_bar": "Eine schmale schwebende Sprachleiste, immer griffbereit.",
+ "jarvis_bar": "Eine schmale schwebende Sprachleiste, immer griffbereit.",
"mascot": "Ein schwebender Begleiter-Orb, der auf deine Stimme reagiert.",
"none": "Nur das App-Fenster — kein schwebendes Element auf dem Bildschirm."
},
@@ -1378,6 +1464,8 @@
"ui_hint": "Betrifft jede Beschriftung, Schaltfläche und Nachricht in der App.",
"reply_section": "Antwort-Sprache",
"reply_hint": "In welcher Sprache {name} antwortet. Eigennamen, Code-Bezeichner und Fachbegriffe bleiben in ihrer Originalform.",
+ "stt_section": "Erkennungssprache (Stimme)",
+ "stt_hint": "In welcher Sprache deine gesprochene Stimme erkannt und in Text umgewandelt wird. Automatisch erkennt von selbst, welche Sprache du sprichst.",
"options": {
"auto": {
"label": "Automatisch",
@@ -1401,6 +1489,12 @@
"en": "{name} antwortet auf Englisch.",
"de": "{name} antwortet auf Deutsch.",
"es": "{name} antwortet auf Spanisch."
+ },
+ "stt_options": {
+ "auto": "Erkennt automatisch, welche Sprache du sprichst.",
+ "en": "Erkennt deine Stimme immer als Englisch.",
+ "de": "Erkennt deine Stimme immer als Deutsch.",
+ "es": "Erkennt deine Stimme immer als Spanisch."
}
},
"cli_connect_poller": {
@@ -1489,6 +1583,7 @@
"copy_failed_clipboard": "Kopieren fehlgeschlagen — Clipboard-Zugriff blockiert?",
"copy_failed": "Kopieren fehlgeschlagen",
"downloaded_as": "Heruntergeladen als",
+ "saved_to_downloads": "In Downloads gespeichert:",
"download_failed": "Download fehlgeschlagen",
"loading": "Lade Session…",
"load_error": "Fehler beim Laden",
@@ -1496,13 +1591,17 @@
"turns": "Turns",
"no_turns_suffix": "ohne Folge-Utterance.",
"copy_action": "Kopieren",
- "download_file_action": "Als Datei herunterladen:"
+ "download_file_action": "Als Datei herunterladen:",
+ "open_editor_action": "Im Editor öffnen:",
+ "opened_in_editor": "Im Editor geöffnet",
+ "open_failed": "Konnte nicht im Editor öffnen"
},
"turn_card": {
"turn": "Turn",
"copied": "kopiert",
"copy_failed": "Kopieren fehlgeschlagen",
"downloaded_as": "Heruntergeladen als",
+ "saved_to_downloads": "In Downloads gespeichert:",
"copy_turn": "Diesen Turn kopieren",
"copy": "Kopieren",
"download_turn": "Diesen Turn als Datei herunterladen",
@@ -1950,7 +2049,12 @@
"trigger_placeholder": "z. B. starte die Morgenroutine",
"create": "Skill erstellen",
"create_error": "Skill konnte nicht erstellt werden",
- "name_required": "Bitte einen Namen mit mindestens 3 Zeichen eingeben."
+ "name_required": "Bitte einen Namen mit mindestens 3 Zeichen eingeben.",
+ "needs_instructions": "Bitte beschreibe, was der Skill tun soll — entweder im Feld ganz oben oder in den Anweisungen darunter.",
+ "write_with_ai": "Den ganzen Skill von KI schreiben lassen",
+ "writing": "Die KI schreibt deinen Skill…",
+ "ai_done_review": "Fertig — die KI hat den ganzen Skill unten geschrieben. Prüfe ihn und klicke auf Skill erstellen.",
+ "or_review_edit": "oder prüfen & anpassen"
},
"missions_view": {
"active": "aktiv",
@@ -2044,5 +2148,29 @@
},
"friends_view": {
"subtitle": "Telegram-Bot + lokaler Friend-Registry. Du entscheidest, was Friends sehen."
+ },
+ "feedback": {
+ "discord_cta_title": "Auf unserem Discord melden",
+ "discord_cta_subtitle": "Tritt #bug-reports bei und poste deinen Fehler, deine Idee oder Frage direkt.",
+ "discord_cta_button": "Discord öffnen",
+ "or_send_here": "oder hier direkt senden",
+ "subtitle": "Fehler melden, Ideen teilen oder eine Frage stellen — geht direkt in unseren Discord.",
+ "type_label": "Typ",
+ "type_bug": "Bug",
+ "type_idea": "Idee",
+ "type_question": "Frage",
+ "title_label": "Titel",
+ "title_placeholder": "Kurze Zusammenfassung deines Feedbacks",
+ "description_label": "Beschreibung",
+ "description_placeholder": "Beschreib es genauer — Schritte zur Reproduktion, Kontext, Erwartetes vs. Tatsächliches Verhalten…",
+ "screenshot_label": "Screenshot (optional)",
+ "screenshot_pick": "Klicken, um einen Screenshot anzuhängen",
+ "screenshot_preview_alt": "Screenshot-Vorschau",
+ "screenshot_remove": "Screenshot entfernen",
+ "submit": "Senden",
+ "sending": "Sende…",
+ "result_sent": "Danke — wurde an unseren Discord gesendet!",
+ "result_not_configured": "Feedback-Kanal ist noch nicht eingerichtet — es wurde nichts gesendet.",
+ "result_error": "Discord nicht erreichbar, bitte später erneut versuchen."
}
}
diff --git a/jarvis/ui/web/frontend/src/i18n/locales/en.json b/jarvis/ui/web/frontend/src/i18n/locales/en.json
index 5d97df63d6..79af7bcae1 100644
--- a/jarvis/ui/web/frontend/src/i18n/locales/en.json
+++ b/jarvis/ui/web/frontend/src/i18n/locales/en.json
@@ -17,7 +17,7 @@
},
"nav": {
"chats": "Chats",
- "agents": "Agents",
+ "agents": "Jarvis-Agents",
"extensions": "Skills, Plugins & MCPs",
"skills": "Skills",
"plugins": "Plugins",
@@ -41,8 +41,38 @@
"socials": "Socials",
"taskbar": "Taskbar",
"contacts": "Contacts",
+ "feedback": "Feedback",
+ "personalize": "Make It Yours",
"agent_instructions": "{name}.md"
},
+ "make_it_yours": {
+ "title": "Make It Yours",
+ "subtitle": "Open coding agents right inside your Jarvis folder and personalize it.",
+ "step_layout": "How many terminals?",
+ "step_layout_hint": "Pick a layout — one tile per number of terminals.",
+ "step_agents": "Which agents?",
+ "step_agents_hint": "Choose how many of each agent fill your terminals. Only Claude Code and Codex.",
+ "quick_fill": "Quick fill",
+ "split_evenly": "Split evenly",
+ "all_claude": "All Claude Code",
+ "all_codex": "All Codex",
+ "installed": "Installed",
+ "not_installed": "Not installed",
+ "install": "Install in terminal",
+ "installing": "Opening installer in a terminal…",
+ "step_confirm": "Ready to launch",
+ "folder": "Folder",
+ "launch": "Launch",
+ "launching": "Launching…",
+ "back": "Back",
+ "next": "Next",
+ "no_terminal": "This host can't run a terminal (no shell or PTY backend), so the agents can't be launched here.",
+ "launched_ok": "Terminals opened",
+ "launch_failed": "Some terminals could not be opened.",
+ "terminals": "terminals",
+ "end_session": "End session",
+ "install_done": "Done — re-check"
+ },
"agent_instructions": {
"subtitle": "Your personal preferences for how the assistant works with you — tone, language, defaults, standing facts. Separate from the System Prompt, and it never overrides safety or confirmations.",
"active_badge": "Active",
@@ -155,7 +185,11 @@
"speaking": "Speaking",
"error": "Error",
"offline": "Offline",
- "starting": "Voice starting…"
+ "booting": "Starting…",
+ "starting": "Voice starting…",
+ "warming_title": "Jarvis is starting up",
+ "warming_hint": "Getting ready to listen – one moment, you'll be able to speak shortly.",
+ "ready_title": "Ready – you can speak now"
},
"sidebar": {
"wake_hint": "Say your wake word…",
@@ -169,6 +203,8 @@
"thinking_label": "thinking…",
"empty_title": "Ready for commands",
"empty_subtitle": "Say your wake word or type your message below. Your assistant dispatches sub-agents, calls tools, and gives you a voice back.",
+ "warming_title": "Getting ready",
+ "warming_subtitle": "Your assistant is starting up. You'll be able to speak in a moment, and you can already type below.",
"examples": {
"0": "Show the agents",
"1": "Switch brain to Gemini",
@@ -212,7 +248,7 @@
"step_cu_settle": "Waiting for the screen"
},
"subagents_view": {
- "title": "Sub-Agents",
+ "title": "Jarvis-Agents",
"stat_active": "active",
"stat_total": "total",
"clear": "Clear",
@@ -220,11 +256,11 @@
"board_title": "Departure Board",
"active_label": "Active",
"standby_label": "Standby",
- "col_agent": "Agent",
+ "col_agent": "Jarvis-Agent",
"col_target": "Goal",
"col_status": "Status",
"col_cost": "Cost",
- "agents_traveling": "Agent(s) traveling",
+ "agents_traveling": "Jarvis-Agent(s) traveling",
"last_departure": "last departure",
"last_departure_ago": "last departure {0} ago",
"status": {
@@ -302,6 +338,23 @@
"tier_fast": "Fast",
"tier_auto": "Auto",
"tier_deep": "Deep",
+ "trigger_mode_label": "Trigger",
+ "mode_schedule": "Schedule",
+ "mode_event": "When-Then",
+ "when_label": "When",
+ "when_mission_succeeded": "A mission succeeds",
+ "when_mission_failed": "A mission fails",
+ "when_mission_cancelled": "A mission is cancelled",
+ "then_label": "Then",
+ "then_computer_use": "Computer-Use",
+ "then_agent": "Agent task",
+ "then_notify": "Just notify me",
+ "cu_goal_label": "What should Computer-Use do?",
+ "cu_goal_placeholder": "e.g. Open {result_uri} in the browser.",
+ "announce_label": "Say when done (optional)",
+ "notify_text_label": "What should it say?",
+ "announce_placeholder": "e.g. Your mission is ready — I opened it in the browser.",
+ "when_then_hint": "Fires every time this happens. You can use {result_uri}, {summary_en} or {mission_id} as placeholders in the text above.",
"cancel": "Cancel",
"save": "Create task",
"save_error": "Could not create the task."
@@ -655,6 +708,13 @@
"more_to_learn": "{0} more to learn",
"value_yes": "yes",
"value_no": "no",
+ "field_edit": "Edit",
+ "field_clear": "Clear",
+ "field_remove_item": "Remove",
+ "field_add": "Add",
+ "field_add_placeholder": "Add…",
+ "field_value_placeholder": "Value…",
+ "field_saved": "Saved",
"review_confirm": "Confirm",
"review_strike": "Strike out",
"questions": {
@@ -772,7 +832,7 @@
},
"apikeys_view": {
"title": "API Keys & Providers",
- "subtitle": "Codex uses the official ChatGPT/Codex login.",
+ "subtitle": "Connect providers and choose what powers each part of Jarvis.",
"save": "Save",
"saved": "Saved",
"missing": "Missing",
@@ -785,6 +845,20 @@
"tier_stt": "Voice Input (STT)",
"tier_subagent": "Subagent (heavy tasks)",
"tier_telephony": "Telephony",
+ "tab_brain": "Brain",
+ "tab_tts": "Voice Output",
+ "tab_stt": "Voice Input",
+ "tab_subagents": "Jarvis-Agents",
+ "tab_advanced": "Advanced",
+ "cat_brain_desc": "The model that powers chat, routing, and Computer-Use.",
+ "cat_tts_desc": "The voice Jarvis speaks with.",
+ "cat_stt_desc": "How Jarvis turns your speech into text.",
+ "cat_subagents_title": "Jarvis-Agents",
+ "cat_subagents_desc": "Choose which provider runs heavy background tasks.",
+ "advanced_title": "Access & Integrations",
+ "advanced_desc": "Optional extras: control-API access, the team key proxy, telephony, and the knowledge Wiki provider.",
+ "no_providers_in_tier": "No providers available in this category.",
+ "model_picker_activate_hint": "Activate this provider to choose its voice or model.",
"active_tooltip": "Already active",
"click_to_activate": "Click to activate this provider",
"needs_codex": "First connect Codex or save API key, then activate",
@@ -792,7 +866,11 @@
"needs_key": "First save API key, then activate",
"recommended": "Recommended",
"recommended_tooltip": "Recommended model: {0}",
- "security_notice": ""
+ "health_needs_setup": "Setup needed",
+ "health_error": "Not working",
+ "health_ok": "Working",
+ "security_notice": "",
+ "trademark_notice": "Provider and service names and logos are trademarks of their respective owners, shown only to identify the integrations you can connect. No affiliation or endorsement is implied."
},
"apikeys_test": {
"button": "Test",
@@ -822,7 +900,8 @@
"load_failed": "Could not load models",
"source_static": "default list",
"source_static_note": "Live catalog unavailable — showing the maintained default selection.",
- "more_hint": "{0} more — refine your search",
+ "count_hint": "{0} models in the catalog",
+ "open_on_provider": "View on OpenRouter",
"choose_placeholder": "Choose a model…",
"heading_voice": "Voice",
"choose_voice": "Choose a voice…",
@@ -946,7 +1025,7 @@
"saved": "Display style switched.",
"restart_required": "Saved — restart {name} to apply.",
"options": {
- "whisper_bar": "Bar (default)",
+ "jarvis_bar": "Bar (default)",
"mascot": "Mascot orb",
"none": "None (hidden)"
}
@@ -1123,6 +1202,7 @@
"restart_label": "Restart",
"rerun_starting": "Starting…",
"rerun_confirm": "Confirm re-run",
+ "continuation_running": "Continued · running",
"list_load_error": "Could not load outputs",
"empty_sessions": "No sub-agent sessions yet. Start an OpenClaw task.",
"select_session": "Select a session.",
@@ -1292,6 +1372,13 @@
"cta": "Get started",
"skip_setup": "Skip setup for now"
},
+ "tutorial": {
+ "title": "Watch the 2-minute tour",
+ "body": "A quick walkthrough of what Personal Jarvis does and how setup works. You can skip and start right away.",
+ "continue": "Continue",
+ "skip": "Skip the video",
+ "play": "Play the tutorial video"
+ },
"risk": {
"title": "Before you continue",
"lead": "Personal Jarvis is powerful, experimental software.",
@@ -1348,12 +1435,12 @@
"body": "How should your assistant appear on screen? You can change this any time in Settings.",
"recommended": "Recommended",
"options": {
- "whisper_bar": "Jarvis Bar",
+ "jarvis_bar": "Jarvis Bar",
"mascot": "Orb",
"none": "No overlay"
},
"captions": {
- "whisper_bar": "A slim floating voice bar, always within reach.",
+ "jarvis_bar": "A slim floating voice bar, always within reach.",
"mascot": "A floating companion orb that reacts as you talk.",
"none": "Just the app window — no floating surface on screen."
},
@@ -1378,6 +1465,8 @@
"ui_hint": "Affects every label, button and message in the app.",
"reply_section": "Reply Language",
"reply_hint": "Which language {name} speaks when answering you. Proper names, code identifiers and technical terms stay in their original form.",
+ "stt_section": "Voice Recognition Language",
+ "stt_hint": "Which language your spoken voice is recognised and turned into text. Automatic detects the language you speak on its own.",
"options": {
"auto": {
"label": "Automatic",
@@ -1401,6 +1490,12 @@
"en": "{name} answers in English.",
"de": "{name} antwortet auf Deutsch.",
"es": "{name} responde en español."
+ },
+ "stt_options": {
+ "auto": "Detect the language you speak automatically.",
+ "en": "Always recognise your voice as English.",
+ "de": "Always recognise your voice as German.",
+ "es": "Always recognise your voice as Spanish."
}
},
"cli_connect_poller": {
@@ -1489,6 +1584,7 @@
"copy_failed_clipboard": "Copy failed — clipboard access blocked?",
"copy_failed": "Copy failed",
"downloaded_as": "Downloaded as",
+ "saved_to_downloads": "Saved to Downloads:",
"download_failed": "Download failed",
"loading": "Loading session…",
"load_error": "Failed to load",
@@ -1496,13 +1592,17 @@
"turns": "turns",
"no_turns_suffix": "without a follow-up utterance.",
"copy_action": "Copy",
- "download_file_action": "Download as file:"
+ "download_file_action": "Download as file:",
+ "open_editor_action": "Open in editor:",
+ "opened_in_editor": "Opened in editor",
+ "open_failed": "Couldn't open in editor"
},
"turn_card": {
"turn": "Turn",
"copied": "copied",
"copy_failed": "Copy failed",
"downloaded_as": "Downloaded as",
+ "saved_to_downloads": "Saved to Downloads:",
"copy_turn": "Copy this turn",
"copy": "Copy",
"download_turn": "Download this turn as a file",
@@ -1950,7 +2050,12 @@
"trigger_placeholder": "e.g. start the morning routine",
"create": "Create skill",
"create_error": "Could not create the skill",
- "name_required": "Please enter a name with at least 3 characters."
+ "name_required": "Please enter a name with at least 3 characters.",
+ "needs_instructions": "Please describe what the skill should do — type it in the field at the top, or write the instructions below.",
+ "write_with_ai": "Write the whole skill with AI",
+ "writing": "AI is writing your skill…",
+ "ai_done_review": "Done — the AI wrote the whole skill below. Review it, then click Create skill.",
+ "or_review_edit": "or review & edit"
},
"missions_view": {
"active": "active",
@@ -2044,5 +2149,29 @@
},
"friends_view": {
"subtitle": "Telegram bot + local friend registry. You decide what friends see."
+ },
+ "feedback": {
+ "discord_cta_title": "Report on our Discord",
+ "discord_cta_subtitle": "Join #bug-reports and post your bug, idea, or question directly.",
+ "discord_cta_button": "Open Discord",
+ "or_send_here": "or send it from here",
+ "subtitle": "Report a bug, share an idea, or ask a question — sent straight to our Discord.",
+ "type_label": "Type",
+ "type_bug": "Bug",
+ "type_idea": "Idea",
+ "type_question": "Question",
+ "title_label": "Title",
+ "title_placeholder": "Short summary of your feedback",
+ "description_label": "Description",
+ "description_placeholder": "Tell us more — steps to reproduce, context, expected vs. actual behaviour…",
+ "screenshot_label": "Screenshot (optional)",
+ "screenshot_pick": "Click to attach a screenshot",
+ "screenshot_preview_alt": "Screenshot preview",
+ "screenshot_remove": "Remove screenshot",
+ "submit": "Submit",
+ "sending": "Sending…",
+ "result_sent": "Thanks — sent to our Discord!",
+ "result_not_configured": "Feedback channel isn't set up yet — nothing was sent.",
+ "result_error": "Couldn't reach Discord, please try again later."
}
}
diff --git a/jarvis/ui/web/frontend/src/i18n/locales/es.json b/jarvis/ui/web/frontend/src/i18n/locales/es.json
index d99cc2f228..c8be16d356 100644
--- a/jarvis/ui/web/frontend/src/i18n/locales/es.json
+++ b/jarvis/ui/web/frontend/src/i18n/locales/es.json
@@ -17,7 +17,7 @@
},
"nav": {
"chats": "Chats",
- "agents": "Agentes",
+ "agents": "Jarvis-Agents",
"extensions": "Skills, Plugins & MCPs",
"skills": "Habilidades",
"plugins": "Plugins",
@@ -41,8 +41,38 @@
"socials": "Redes",
"taskbar": "Barra",
"contacts": "Contactos",
+ "feedback": "Comentarios",
+ "personalize": "Hazlo tuyo",
"agent_instructions": "{name}.md"
},
+ "make_it_yours": {
+ "title": "Hazlo tuyo",
+ "subtitle": "Abre agentes de programación dentro de tu carpeta de Jarvis y personalízalo.",
+ "step_layout": "¿Cuántas terminales?",
+ "step_layout_hint": "Elige un diseño — una casilla por número de terminales.",
+ "step_agents": "¿Qué agentes?",
+ "step_agents_hint": "Decide cuántos de cada agente llenan tus terminales. Solo Claude Code y Codex.",
+ "quick_fill": "Relleno rápido",
+ "split_evenly": "Dividir en partes iguales",
+ "all_claude": "Todo Claude Code",
+ "all_codex": "Todo Codex",
+ "installed": "Instalado",
+ "not_installed": "No instalado",
+ "install": "Instalar en la terminal",
+ "installing": "Abriendo el instalador en una terminal…",
+ "step_confirm": "Listo para lanzar",
+ "folder": "Carpeta",
+ "launch": "Lanzar",
+ "launching": "Lanzando…",
+ "back": "Atrás",
+ "next": "Siguiente",
+ "no_terminal": "Este host no puede ejecutar una terminal (sin shell ni backend PTY), así que los agentes no se pueden lanzar aquí.",
+ "launched_ok": "Terminales abiertas",
+ "launch_failed": "Algunas terminales no se pudieron abrir.",
+ "terminals": "terminales",
+ "end_session": "Terminar sesión",
+ "install_done": "Listo — volver a comprobar"
+ },
"agent_instructions": {
"subtitle": "Tus preferencias personales sobre cómo el asistente trabaja contigo — tono, idioma, valores por defecto, hechos permanentes. Separado del System Prompt y nunca anula la seguridad ni las confirmaciones.",
"active_badge": "Activo",
@@ -155,7 +185,11 @@
"speaking": "Hablando",
"error": "Error",
"offline": "Sin conexión",
- "starting": "Iniciando voz…"
+ "booting": "Iniciando…",
+ "starting": "Iniciando voz…",
+ "warming_title": "Jarvis se está iniciando",
+ "warming_hint": "Preparando la escucha – un momento, podrás hablar en breve.",
+ "ready_title": "Listo – ya puedes hablar"
},
"sidebar": {
"wake_hint": "Di tu palabra de activación…",
@@ -169,6 +203,8 @@
"thinking_label": "pensando…",
"empty_title": "Listo para órdenes",
"empty_subtitle": "Di tu palabra de activación o escribe tu mensaje abajo. Tu asistente dirige sub-agentes, llama a herramientas y te devuelve voz.",
+ "warming_title": "Preparándose",
+ "warming_subtitle": "Tu asistente está arrancando. Podrás hablar en un momento, y ya puedes escribir abajo.",
"examples": {
"0": "Muestra los agentes",
"1": "Cambia el cerebro a Gemini",
@@ -212,7 +248,7 @@
"step_cu_settle": "Esperando la pantalla"
},
"subagents_view": {
- "title": "Sub-Agentes",
+ "title": "Jarvis-Agents",
"stat_active": "activos",
"stat_total": "total",
"clear": "Limpiar",
@@ -220,11 +256,11 @@
"board_title": "Tablero de Salidas",
"active_label": "Activo",
"standby_label": "En espera",
- "col_agent": "Agente",
+ "col_agent": "Jarvis-Agent",
"col_target": "Destino",
"col_status": "Estado",
"col_cost": "Coste",
- "agents_traveling": "Agente(s) en camino",
+ "agents_traveling": "Jarvis-Agent(s) en camino",
"last_departure": "última salida",
"last_departure_ago": "última salida hace {0}",
"status": {
@@ -302,6 +338,23 @@
"tier_fast": "Rápido",
"tier_auto": "Auto",
"tier_deep": "Potente",
+ "trigger_mode_label": "Disparador",
+ "mode_schedule": "Programado",
+ "mode_event": "Si-Entonces",
+ "when_label": "Cuando",
+ "when_mission_succeeded": "Una misión termina",
+ "when_mission_failed": "Una misión falla",
+ "when_mission_cancelled": "Una misión se cancela",
+ "then_label": "Entonces",
+ "then_computer_use": "Computer-Use",
+ "then_agent": "Tarea de agente",
+ "then_notify": "Solo avísame",
+ "cu_goal_label": "¿Qué debe hacer Computer-Use?",
+ "cu_goal_placeholder": "p. ej. Abre {result_uri} en el navegador.",
+ "announce_label": "Avisar al terminar (opcional)",
+ "notify_text_label": "¿Qué debe decir?",
+ "announce_placeholder": "p. ej. Tu misión está lista — la abrí en el navegador.",
+ "when_then_hint": "Se activa cada vez que ocurre. Puedes usar {result_uri}, {summary_en} o {mission_id} como variables en el texto de arriba.",
"cancel": "Cancelar",
"save": "Crear tarea",
"save_error": "No se pudo crear la tarea."
@@ -655,6 +708,13 @@
"more_to_learn": "{0} más por aprender",
"value_yes": "sí",
"value_no": "no",
+ "field_edit": "Editar",
+ "field_clear": "Borrar",
+ "field_remove_item": "Quitar",
+ "field_add": "Añadir",
+ "field_add_placeholder": "Añadir…",
+ "field_value_placeholder": "Valor…",
+ "field_saved": "Guardado",
"review_confirm": "Correcto",
"review_strike": "Tachar",
"questions": {
@@ -772,7 +832,7 @@
},
"apikeys_view": {
"title": "Claves API y Proveedores",
- "subtitle": "Codex usa el login oficial de ChatGPT/Codex.",
+ "subtitle": "Conecta proveedores y elige qué impulsa cada parte de Jarvis.",
"save": "Guardar",
"saved": "Guardado",
"missing": "Falta",
@@ -785,6 +845,20 @@
"tier_stt": "Entrada de voz (STT)",
"tier_subagent": "Subagente (tareas pesadas)",
"tier_telephony": "Telefonía",
+ "tab_brain": "IA",
+ "tab_tts": "Salida de voz",
+ "tab_stt": "Entrada de voz",
+ "tab_subagents": "Jarvis-Agents",
+ "tab_advanced": "Avanzado",
+ "cat_brain_desc": "El modelo que impulsa el chat, el enrutamiento y Computer-Use.",
+ "cat_tts_desc": "La voz con la que habla Jarvis.",
+ "cat_stt_desc": "Cómo convierte Jarvis tu voz en texto.",
+ "cat_subagents_title": "Jarvis-Agents",
+ "cat_subagents_desc": "Elige qué proveedor ejecuta las tareas pesadas en segundo plano.",
+ "advanced_title": "Acceso e integraciones",
+ "advanced_desc": "Extras opcionales: acceso a la API de control, el proxy de claves de equipo, telefonía y el proveedor del Wiki de conocimiento.",
+ "no_providers_in_tier": "No hay proveedores disponibles en esta categoría.",
+ "model_picker_activate_hint": "Activa este proveedor para elegir su voz o modelo.",
"active_tooltip": "Ya activo",
"click_to_activate": "Clic para activar este proveedor",
"needs_codex": "Primero conecta Codex o guarda la clave API",
@@ -792,6 +866,9 @@
"needs_key": "Primero guarda la clave API, luego se puede activar",
"recommended": "Recomendado",
"recommended_tooltip": "Modelo recomendado: {0}",
+ "health_needs_setup": "Falta configurar",
+ "health_error": "No funciona",
+ "health_ok": "Funciona",
"security_notice": ""
},
"apikeys_test": {
@@ -822,7 +899,8 @@
"load_failed": "No se pudieron cargar los modelos",
"source_static": "lista predeterminada",
"source_static_note": "Catálogo en vivo no disponible — mostrando la selección predeterminada.",
- "more_hint": "{0} más — refina tu búsqueda",
+ "count_hint": "{0} modelos en el catálogo",
+ "open_on_provider": "Ver en OpenRouter",
"choose_placeholder": "Elige un modelo…",
"heading_voice": "Voz",
"choose_voice": "Elige una voz…",
@@ -946,7 +1024,7 @@
"saved": "Estilo de visualización cambiado.",
"restart_required": "Guardado: reinicia {name} para aplicar.",
"options": {
- "whisper_bar": "Barra (predeterminado)",
+ "jarvis_bar": "Barra (predeterminado)",
"mascot": "Orbe mascota",
"none": "Ninguno (oculto)"
}
@@ -1123,6 +1201,7 @@
"restart_label": "Reiniciar",
"rerun_starting": "Iniciando…",
"rerun_confirm": "Confirmar reejecución",
+ "continuation_running": "Continuado · en curso",
"list_load_error": "No se pudieron cargar las salidas",
"empty_sessions": "Aún no hay sesiones de subagentes. Inicia una tarea de OpenClaw.",
"select_session": "Selecciona una sesión.",
@@ -1292,6 +1371,13 @@
"cta": "Empezar",
"skip_setup": "Omitir la configuración por ahora"
},
+ "tutorial": {
+ "title": "Mira el recorrido de 2 minutos",
+ "body": "Un repaso rápido de lo que hace Personal Jarvis y cómo es la configuración. Puedes omitirlo y empezar enseguida.",
+ "continue": "Continuar",
+ "skip": "Omitir el vídeo",
+ "play": "Reproducir el vídeo del tutorial"
+ },
"risk": {
"title": "Antes de continuar",
"lead": "Personal Jarvis es un software potente y experimental.",
@@ -1348,12 +1434,12 @@
"body": "¿Cómo debería aparecer tu asistente en pantalla? Puedes cambiarlo cuando quieras en Ajustes.",
"recommended": "Recomendado",
"options": {
- "whisper_bar": "Barra de Jarvis",
+ "jarvis_bar": "Barra de Jarvis",
"mascot": "Orbe",
"none": "Sin superposición"
},
"captions": {
- "whisper_bar": "Una barra de voz flotante y delgada, siempre a mano.",
+ "jarvis_bar": "Una barra de voz flotante y delgada, siempre a mano.",
"mascot": "Un orbe acompañante flotante que reacciona cuando hablas.",
"none": "Solo la ventana de la app — sin elementos flotantes en pantalla."
},
@@ -1378,6 +1464,8 @@
"ui_hint": "Afecta cada etiqueta, botón y mensaje en la aplicación.",
"reply_section": "Idioma de Respuesta",
"reply_hint": "En qué idioma habla {name} al responderte. Nombres propios, identificadores de código y términos técnicos se mantienen en su forma original.",
+ "stt_section": "Idioma de Reconocimiento (Voz)",
+ "stt_hint": "En qué idioma se reconoce tu voz hablada y se convierte en texto. Automático detecta por sí solo el idioma que hablas.",
"options": {
"auto": {
"label": "Automático",
@@ -1401,6 +1489,12 @@
"en": "{name} responde en inglés.",
"de": "{name} responde en alemán.",
"es": "{name} responde en español."
+ },
+ "stt_options": {
+ "auto": "Detecta automáticamente el idioma que hablas.",
+ "en": "Reconoce tu voz siempre como inglés.",
+ "de": "Reconoce tu voz siempre como alemán.",
+ "es": "Reconoce tu voz siempre como español."
}
},
"cli_connect_poller": {
@@ -1489,6 +1583,7 @@
"copy_failed_clipboard": "Error al copiar — ¿acceso al portapapeles bloqueado?",
"copy_failed": "Error al copiar",
"downloaded_as": "Descargado como",
+ "saved_to_downloads": "Guardado en Descargas:",
"download_failed": "Error al descargar",
"loading": "Cargando sesión…",
"load_error": "Error al cargar",
@@ -1496,13 +1591,17 @@
"turns": "turnos",
"no_turns_suffix": "sin una intervención posterior.",
"copy_action": "Copiar",
- "download_file_action": "Descargar como archivo:"
+ "download_file_action": "Descargar como archivo:",
+ "open_editor_action": "Abrir en el editor:",
+ "opened_in_editor": "Abierto en el editor",
+ "open_failed": "No se pudo abrir en el editor"
},
"turn_card": {
"turn": "Turno",
"copied": "copiado",
"copy_failed": "Error al copiar",
"downloaded_as": "Descargado como",
+ "saved_to_downloads": "Guardado en Descargas:",
"copy_turn": "Copiar este turno",
"copy": "Copiar",
"download_turn": "Descargar este turno como archivo",
@@ -1950,7 +2049,12 @@
"trigger_placeholder": "p. ej. inicia la rutina matutina",
"create": "Crear habilidad",
"create_error": "No se pudo crear la habilidad",
- "name_required": "Introduce un nombre con al menos 3 caracteres."
+ "name_required": "Introduce un nombre con al menos 3 caracteres.",
+ "needs_instructions": "Describe qué debe hacer la habilidad: escríbelo en el campo de arriba o en las instrucciones de abajo.",
+ "write_with_ai": "Que la IA escriba toda la habilidad",
+ "writing": "La IA está escribiendo tu habilidad…",
+ "ai_done_review": "Listo: la IA escribió toda la habilidad abajo. Revísala y pulsa Crear habilidad.",
+ "or_review_edit": "o revisa y edita"
},
"missions_view": {
"active": "activas",
@@ -2044,5 +2148,29 @@
},
"friends_view": {
"subtitle": "Bot de Telegram + registro local de amigos. Tú decides qué ven los amigos."
+ },
+ "feedback": {
+ "discord_cta_title": "Repórtalo en nuestro Discord",
+ "discord_cta_subtitle": "Únete a #bug-reports y publica tu error, idea o pregunta directamente.",
+ "discord_cta_button": "Abrir Discord",
+ "or_send_here": "o envíalo desde aquí",
+ "subtitle": "Reporta un error, comparte una idea o haz una pregunta — va directo a nuestro Discord.",
+ "type_label": "Tipo",
+ "type_bug": "Error",
+ "type_idea": "Idea",
+ "type_question": "Pregunta",
+ "title_label": "Título",
+ "title_placeholder": "Resumen breve de tus comentarios",
+ "description_label": "Descripción",
+ "description_placeholder": "Cuéntanos más — pasos para reproducir, contexto, comportamiento esperado vs. real…",
+ "screenshot_label": "Captura de pantalla (opcional)",
+ "screenshot_pick": "Haz clic para adjuntar una captura",
+ "screenshot_preview_alt": "Vista previa de la captura",
+ "screenshot_remove": "Eliminar captura",
+ "submit": "Enviar",
+ "sending": "Enviando…",
+ "result_sent": "¡Gracias — enviado a nuestro Discord!",
+ "result_not_configured": "El canal de comentarios aún no está configurado — no se envió nada.",
+ "result_error": "No se pudo llegar a Discord, inténtalo de nuevo más tarde."
}
}
diff --git a/jarvis/ui/web/frontend/src/index.css b/jarvis/ui/web/frontend/src/index.css
index 7dd206390c..4a35b7491f 100644
--- a/jarvis/ui/web/frontend/src/index.css
+++ b/jarvis/ui/web/frontend/src/index.css
@@ -4,6 +4,30 @@
@tailwind components;
@tailwind utilities;
+/* xterm.js viewport scrollbar — PLAIN (non-@layer) CSS on purpose. Tailwind
+ tree-shakes `@layer utilities` by class usage, and `.xterm-viewport` is
+ created by xterm.js at runtime (it never appears in the source), so a rule
+ for it inside a @layer gets PURGED from the build — which is exactly why the
+ embedded "Make It Yours" terminals kept the native light WebView2 scrollbar.
+ Top-level CSS is always emitted. Thin, dark, no arrow buttons. */
+.xterm-viewport::-webkit-scrollbar {
+ width: 8px;
+ height: 8px;
+}
+.xterm-viewport::-webkit-scrollbar-track {
+ background: transparent;
+}
+.xterm-viewport::-webkit-scrollbar-thumb {
+ background: hsl(var(--border));
+ border-radius: 4px;
+}
+.xterm-viewport::-webkit-scrollbar-thumb:hover {
+ background: hsl(var(--muted-foreground));
+}
+.xterm-viewport::-webkit-scrollbar-button {
+ display: none;
+}
+
@layer base {
:root {
/* Jarvis — Schwarz/Gelb Theme (matte, signal-yellow) */
diff --git a/jarvis/ui/web/frontend/src/lib/clipboard.test.ts b/jarvis/ui/web/frontend/src/lib/clipboard.test.ts
new file mode 100644
index 0000000000..1427a82486
--- /dev/null
+++ b/jarvis/ui/web/frontend/src/lib/clipboard.test.ts
@@ -0,0 +1,86 @@
+import { afterEach, beforeEach, describe, expect, it, vi } from "vitest";
+
+import { saveOrDownload } from "./clipboard";
+
+/** jsdom does not define URL.createObjectURL at all, so assign the methods
+ * directly (spyOn would fail) + stub the anchor click so the browser-download
+ * path (downloadAs/downloadBlob) runs without throwing. */
+function stubBrowserDownload() {
+ const u = URL as unknown as Record<string, unknown>;
+ u.createObjectURL = vi.fn(() => "blob:stub");
+ u.revokeObjectURL = vi.fn();
+ const clickSpy = vi
+ .spyOn(HTMLAnchorElement.prototype, "click")
+ .mockImplementation(() => {});
+ return { clickSpy };
+}
+
+describe("saveOrDownload", () => {
+ beforeEach(() => {
+ vi.useRealTimers();
+ });
+ afterEach(() => {
+ vi.restoreAllMocks();
+ vi.unstubAllGlobals();
+ });
+
+ it("posts base64 to the backend on desktop and returns the saved path", async () => {
+ const fetchMock = vi.fn(async () => ({
+ ok: true,
+ json: async () => ({ saved_path: "/home/u/Downloads/note.txt" }),
+ }));
+ vi.stubGlobal("fetch", fetchMock);
+
+ const saved = await saveOrDownload({
+ filename: "note.txt",
+ text: "hi",
+ native: true,
+ });
+
+ expect(saved).toBe("/home/u/Downloads/note.txt");
+ expect(fetchMock).toHaveBeenCalledTimes(1);
+ const [url, init] = fetchMock.mock.calls[0] as unknown as [
+ string,
+ RequestInit,
+ ];
+ expect(url).toBe("/api/downloads/save");
+ const body = JSON.parse(init.body as string) as {
+ filename: string;
+ content_b64: string;
+ };
+ expect(body.filename).toBe("note.txt");
+ expect(body.content_b64.length).toBeGreaterThan(0);
+ });
+
+ it("uses the browser download (no backend call) when not native", async () => {
+ const fetchMock = vi.fn();
+ vi.stubGlobal("fetch", fetchMock);
+ const { clickSpy } = stubBrowserDownload();
+
+ const saved = await saveOrDownload({
+ filename: "note.txt",
+ text: "hi",
+ native: false,
+ });
+
+ expect(saved).toBeNull();
+ expect(fetchMock).not.toHaveBeenCalled();
+ expect(clickSpy).toHaveBeenCalledTimes(1);
+ });
+
+ it("falls back to the browser download when the backend save fails", async () => {
+ const fetchMock = vi.fn(async () => ({ ok: false, status: 500 }));
+ vi.stubGlobal("fetch", fetchMock);
+ const { clickSpy } = stubBrowserDownload();
+
+ const saved = await saveOrDownload({
+ filename: "note.txt",
+ text: "hi",
+ native: true,
+ });
+
+ expect(saved).toBeNull();
+ expect(fetchMock).toHaveBeenCalledTimes(1);
+ expect(clickSpy).toHaveBeenCalledTimes(1);
+ });
+});
diff --git a/jarvis/ui/web/frontend/src/lib/clipboard.ts b/jarvis/ui/web/frontend/src/lib/clipboard.ts
index 1a497b08e5..eb2566109a 100644
--- a/jarvis/ui/web/frontend/src/lib/clipboard.ts
+++ b/jarvis/ui/web/frontend/src/lib/clipboard.ts
@@ -75,11 +75,16 @@ function execCommandCopy(text: string): boolean {
}
/**
- * Triggert einen Datei-Download via Blob + temporaeres ``<a download>``.
+ * Trigger a file download via a Blob + a temporary ``<a download>``.
*
- * Funktioniert in WebView2 (pywebview) — dort wird die Datei in den
- * Default-Downloads-Ordner gelegt (Edge-Verhalten). Im Vite-Dev-Server
- * popt der Browser den Save-Dialog.
+ * WARNING: inside the desktop shell (pywebview/WebView2) such a browser
+ * download is **silently dropped** by default — pywebview ships with
+ * ``settings['ALLOW_DOWNLOADS']=False`` and its EdgeChromium handler aborts
+ * with ``args.Cancel=True`` (no file, no error). On the desktop the save must
+ * therefore go through ``saveOrDownload`` to the backend
+ * (``/api/downloads/save`` → ~/Downloads). This path is correct only in a real
+ * browser (Vite dev / headless VPS), where the browser itself drops the file
+ * into the user's Downloads folder.
*/
export function downloadAs(
filename: string,
@@ -170,3 +175,70 @@ export function mimeFor(format: "markdown" | "plain" | "json"): string {
if (format === "markdown") return "text/markdown;charset=utf-8";
return "text/plain;charset=utf-8";
}
+
+// --- Save-to-Downloads (desktop) vs. browser download ---------------------
+
+/** Base64-encode a Blob's bytes (no data-URL prefix). FileReader handles
+ * binary correctly and avoids large-array `String.fromCharCode` pitfalls. */
+function blobToBase64(blob: Blob): Promise<string> {
+ return new Promise((resolve, reject) => {
+ const reader = new FileReader();
+ reader.onload = () => {
+ const res = String(reader.result);
+ const comma = res.indexOf(",");
+ resolve(comma >= 0 ? res.slice(comma + 1) : res);
+ };
+ reader.onerror = () => reject(reader.error);
+ reader.readAsDataURL(blob);
+ });
+}
+
+export interface SaveOrDownloadArgs {
+ filename: string;
+ /** Text payload (use this OR `blob`). */
+ text?: string;
+ /** Binary payload (use this OR `text`). */
+ blob?: Blob;
+ /** MIME type for the text/browser path. */
+ mime?: string;
+ /** True in the desktop shell — route the save through the backend. */
+ native: boolean;
+}
+
+/**
+ * Save a file so it actually lands in the user's Downloads folder, everywhere.
+ *
+ * - Desktop (`native`): POST the bytes to ``/api/downloads/save``; the backend
+ * writes them into ``~/Downloads`` (pywebview silently cancels browser
+ * downloads, so this is the only path that works there). Returns the saved
+ * absolute path. On any failure it falls back to the browser download — never
+ * worse than before.
+ * - Browser / VPS (`!native`): the normal blob ``<a download>`` — the real
+ * browser saves into the user's own Downloads. Returns null.
+ */
+export async function saveOrDownload(
+ args: SaveOrDownloadArgs,
+): Promise<string | null> {
+ const { filename, native, mime } = args;
+ const mimeType = mime ?? "text/plain;charset=utf-8";
+ if (native) {
+ try {
+ const payload =
+ args.blob ?? new Blob([args.text ?? ""], { type: mimeType });
+ const contentB64 = await blobToBase64(payload);
+ const res = await fetch("/api/downloads/save", {
+ method: "POST",
+ headers: { "Content-Type": "application/json" },
+ body: JSON.stringify({ filename, content_b64: contentB64 }),
+ });
+ if (!res.ok) throw new Error(`HTTP ${res.status}`);
+ const data = (await res.json()) as { saved_path?: string };
+ return data.saved_path ?? filename;
+ } catch {
+ // Fall through to the browser download — never worse than today.
+ }
+ }
+ if (args.blob) downloadBlob(filename, args.blob);
+ else downloadAs(filename, args.text ?? "", mimeType);
+ return null;
+}
diff --git a/jarvis/ui/web/frontend/src/lib/missionDragImage.test.ts b/jarvis/ui/web/frontend/src/lib/missionDragImage.test.ts
index fd6e7c5203..2c9995e248 100644
--- a/jarvis/ui/web/frontend/src/lib/missionDragImage.test.ts
+++ b/jarvis/ui/web/frontend/src/lib/missionDragImage.test.ts
@@ -48,4 +48,23 @@ describe("applyMissionDragImage", () => {
applyMissionDragImage({} as unknown as DataTransfer, "t"),
).not.toThrow();
});
+
+ it("keeps the chip's layout box at the origin (dpr-safe, not -9999px)", () => {
+ // Regression for the 150%-scaled-display bug: a large negative left/top is
+ // multiplied by devicePixelRatio by Chromium/WebView2, detaching the drag
+ // ghost from the cursor by ~5000px. The chip must hide via `transform`
+ // while its layout offset stays at 0, so the error is zero on every dpr.
+ const setDragImage = vi.fn();
+ const dt = { setDragImage } as unknown as DataTransfer;
+
+ applyMissionDragImage(dt, "Build the landing page");
+
+ const node = setDragImage.mock.calls[0][0] as HTMLElement;
+ expect(node.style.left).toBe("0px");
+ expect(node.style.top).toBe("0px");
+ expect(node.style.transform).not.toBe("");
+ // Guard the exact failure mode: no huge negative offset anywhere.
+ expect(node.style.left).not.toContain("-9999");
+ expect(node.style.top).not.toContain("-9999");
+ });
});
diff --git a/jarvis/ui/web/frontend/src/lib/missionDragImage.ts b/jarvis/ui/web/frontend/src/lib/missionDragImage.ts
index 689a027394..a6a3571cb4 100644
--- a/jarvis/ui/web/frontend/src/lib/missionDragImage.ts
+++ b/jarvis/ui/web/frontend/src/lib/missionDragImage.ts
@@ -6,9 +6,18 @@
* large, opaque ghost that looks broken. `setDragImage` swaps that for a small
* "📎 <title>" pill that reads as an intentional, liftable token.
*
- * The chip is appended off-screen (the browser still snapshots it), used as the
- * drag image, then removed on the next frame — by which point the snapshot has
- * been taken.
+ * The chip is appended at the viewport ORIGIN (0,0) and pushed out of sight with
+ * a CSS `transform`, then removed on the next frame — by which point the browser
+ * has snapshotted it.
+ *
+ * Why not the usual `left: -9999px` off-screen trick: Chromium/WebView2 anchor
+ * the drag image from the element's LAYOUT position, multiplied by
+ * `devicePixelRatio`. At a Windows display scale of 150% (dpr 1.5) a -9999px
+ * layout offset becomes a ~5000px error, so the ghost detaches far from the
+ * cursor (forensic 2026-06-28: 150%-scaled desktop, chip stuck top-left while
+ * the cursor was bottom-right). Keeping the layout box at the origin makes that
+ * error zero on every dpr; a `transform` moves only the painted pixels (which
+ * the snapshot still captures), so the chip never flashes on screen.
*/
const ACCENT = "#FFD60A"; // --primary signal-yellow
@@ -32,8 +41,11 @@ export function applyMissionDragImage(dt: DataTransfer, title: string): void {
chip.textContent = `📎 ${truncate(title)}`;
Object.assign(chip.style, {
position: "fixed",
- top: "-9999px",
- left: "-9999px",
+ // Layout box stays at the origin (dpr-safe); `transform` hides it. Never
+ // use a large negative `left`/`top` here — see the file header.
+ top: "0",
+ left: "0",
+ transform: "translateY(-200%)",
display: "inline-flex",
alignItems: "center",
maxWidth: "320px",
diff --git a/jarvis/ui/web/frontend/src/lib/openExternal.ts b/jarvis/ui/web/frontend/src/lib/openExternal.ts
new file mode 100644
index 0000000000..8eee8d4ae8
--- /dev/null
+++ b/jarvis/ui/web/frontend/src/lib/openExternal.ts
@@ -0,0 +1,43 @@
+/**
+ * Open an external URL in the user's *real* browser.
+ *
+ * Why this exists: the desktop app embeds WebView2 (pywebview, `gui:
+ * "edgechromium"`). That shell silently drops `window.open(...)` and
+ * `target="_blank"` — the new tab never appears. So OAuth-authorize and
+ * token-creation pages (plugin "connect") opened to nothing.
+ *
+ * Design — bridge-first, no fragile shell detection. We always ask the backend
+ * to open the URL (`POST /api/settings/open-external`). The backend opens the
+ * OS default browser *only when it has a local display* (the desktop install,
+ * or a browser tab on the same machine) and reports `{opened: true}`. On a
+ * remote/VPS server there is no display, it reports `{opened: false}`, and we
+ * fall back to `window.open` so the URL opens in the user's own remote browser.
+ * This way the desktop shell always reaches a real browser, and remote browsers
+ * keep working — without depending on a shell-detection flag that can be unset.
+ */
+
+function openInThisBrowser(url: string): void {
+ window.open(url, "_blank", "noopener,noreferrer");
+}
+
+/**
+ * Open `url` in the user's browser. Resolves once dispatched; never throws.
+ * Tries the local bridge first, falls back to a `window.open` tab.
+ */
+export async function openExternalUrl(url: string): Promise<void> {
+ if (!url) return;
+ try {
+ const res = await fetch("/api/settings/open-external", {
+ method: "POST",
+ headers: { "Content-Type": "application/json" },
+ body: JSON.stringify({ url }),
+ });
+ if (res.ok) {
+ const data = (await res.json().catch(() => null)) as { opened?: boolean } | null;
+ if (data?.opened) return;
+ }
+ } catch {
+ // Bridge unreachable — fall through to a best-effort window.open.
+ }
+ openInThisBrowser(url);
+}
diff --git a/jarvis/ui/web/frontend/src/lib/workspaceApi.ts b/jarvis/ui/web/frontend/src/lib/workspaceApi.ts
new file mode 100644
index 0000000000..29060d55b4
--- /dev/null
+++ b/jarvis/ui/web/frontend/src/lib/workspaceApi.ts
@@ -0,0 +1,71 @@
+// REST client for the "Make It Yours" multi-agent workspace launcher.
+// Plain fetch, same-origin (no auth header — mirrors chatsApi). `no-store`
+// avoids the WebView2 stale-list cache trap. Terminals are embedded (xterm
+// panes driven by the workspace PTY WebSocket), so launching just returns the
+// per-slot plan — it opens no OS windows.
+
+export interface WorkspaceAgent {
+ name: string;
+ display_name: string;
+ installed: boolean;
+ version: string | null;
+ install_command: string | null;
+ launch_command: string;
+}
+
+export interface AgentsResponse {
+ cwd: string;
+ terminal_available: boolean;
+ layout_choices: number[];
+ agents: WorkspaceAgent[];
+}
+
+export interface Slot {
+ index: number;
+ agent: string;
+ display_name: string;
+}
+
+export interface TrustResult {
+ agent: string;
+ ok: boolean;
+ method: string;
+ detail: string;
+}
+
+export interface LaunchPlan {
+ ok: boolean;
+ cwd: string;
+ slots: Slot[];
+ trust: TrustResult[];
+ detail: string;
+}
+
+export async function fetchWorkspaceAgents(): Promise<AgentsResponse> {
+ const res = await fetch("/api/workspace/agents", { cache: "no-store" });
+ if (!res.ok) throw new Error(`agents request failed: ${res.status}`);
+ return (await res.json()) as AgentsResponse;
+}
+
+export async function launchWorkspace(
+ layout: number,
+ split: Record<string, number>,
+): Promise<LaunchPlan> {
+ const res = await fetch("/api/workspace/launch", {
+ method: "POST",
+ headers: { "Content-Type": "application/json" },
+ body: JSON.stringify({ layout, split }),
+ });
+ if (!res.ok) throw new Error(await extractDetail(res));
+ return (await res.json()) as LaunchPlan;
+}
+
+async function extractDetail(res: Response): Promise<string> {
+ try {
+ const body = (await res.json()) as { detail?: string };
+ if (body?.detail) return body.detail;
+ } catch {
+ /* fall through to status code */
+ }
+ return `request failed: ${res.status}`;
+}
diff --git a/jarvis/ui/web/frontend/src/lib/ws.ts b/jarvis/ui/web/frontend/src/lib/ws.ts
index 2fb5ade3ef..66107d5ba3 100644
--- a/jarvis/ui/web/frontend/src/lib/ws.ts
+++ b/jarvis/ui/web/frontend/src/lib/ws.ts
@@ -13,7 +13,7 @@ export interface WSClientOptions {
url?: string;
onMessage?: WSHandler;
onOpen?: () => void;
- onClose?: () => void;
+ onClose?: (code?: number) => void;
}
declare global {
@@ -32,10 +32,11 @@ export class WSClient {
private pingTimer: ReturnType<typeof setInterval> | null = null;
private reconnectTimer: ReturnType<typeof setTimeout> | null = null;
private stopped = false;
+ private lastCloseCode: number | undefined;
private readonly url: string;
private readonly onMessage?: WSHandler;
private readonly onOpen?: () => void;
- private readonly onClose?: () => void;
+ private readonly onClose?: (code?: number) => void;
private readonly extraSubscribers = new Set<WSHandler>();
constructor(opts: WSClientOptions = {}) {
@@ -89,9 +90,10 @@ export class WSClient {
}
});
- this.ws.addEventListener("close", () => {
+ this.ws.addEventListener("close", (ev) => {
this.stopPing();
- this.onClose?.();
+ this.lastCloseCode = (ev as CloseEvent).code;
+ this.onClose?.(this.lastCloseCode);
if (!this.stopped) this.scheduleReconnect();
});
@@ -120,8 +122,13 @@ export class WSClient {
private scheduleReconnect(): void {
if (this.reconnectTimer) return;
- const delay = this.backoff;
- this.backoff = Math.min(MAX_BACKOFF, this.backoff * 2);
+ // The fast-boot bootstrap closes a warming WS with code 1013 ("try again
+ // later"): the backend is still booting, this is NOT a failure. Retry at a
+ // fixed short interval instead of escalating the backoff, so the window
+ // reconnects within ~1s of the real app becoming ready.
+ const warming = this.lastCloseCode === 1013;
+ const delay = warming ? MIN_BACKOFF : this.backoff;
+ if (!warming) this.backoff = Math.min(MAX_BACKOFF, this.backoff * 2);
this.reconnectTimer = setTimeout(() => {
this.reconnectTimer = null;
this.openSocket();
diff --git a/jarvis/ui/web/frontend/src/store/events.test.ts b/jarvis/ui/web/frontend/src/store/events.test.ts
index 88d51df55a..4d2d9f9cea 100644
--- a/jarvis/ui/web/frontend/src/store/events.test.ts
+++ b/jarvis/ui/web/frontend/src/store/events.test.ts
@@ -64,6 +64,18 @@ describe("voice boot readiness (voiceReady / setVoiceReady)", () => {
});
});
+describe("ws warming state (wsWarming / setWarming)", () => {
+ it("tracks wsWarming and defaults it to true", () => {
+ // Fresh store: warming until proven connected/offline so the first paint
+ // after a restart reads "Starting…", never a scary "OFFLINE".
+ expect(useEventStore.getState().wsWarming).toBe(true);
+ useEventStore.getState().setWarming(false);
+ expect(useEventStore.getState().wsWarming).toBe(false);
+ useEventStore.getState().setWarming(true);
+ expect(useEventStore.getState().wsWarming).toBe(true);
+ });
+});
+
describe("reasoning trace (thinkingSteps / thinkingTraces)", () => {
beforeEach(() => {
useEventStore.setState({
diff --git a/jarvis/ui/web/frontend/src/store/events.ts b/jarvis/ui/web/frontend/src/store/events.ts
index 45384e4b16..3a52722b2e 100644
--- a/jarvis/ui/web/frontend/src/store/events.ts
+++ b/jarvis/ui/web/frontend/src/store/events.ts
@@ -33,6 +33,8 @@ export type SectionId =
| "socials"
| "taskbar"
| "contacts"
+ | "feedback"
+ | "personalize"
| "agent-instructions";
export const SECTION_IDS = [
@@ -59,6 +61,8 @@ export const SECTION_IDS = [
"socials",
"taskbar",
"contacts",
+ "feedback",
+ "personalize",
"agent-instructions",
] as const satisfies readonly SectionId[];
@@ -90,6 +94,8 @@ export const SECTION_LABELS: Record<SectionId, string> = {
socials: "Socials",
taskbar: "Taskbar",
contacts: "Contacts",
+ feedback: "Feedback",
+ personalize: "Make It Yours",
"agent-instructions": "Agent Instructions",
};
@@ -163,6 +169,11 @@ interface EventStore {
// the sidebar "Voice starting…" indicator.
voiceReady: boolean;
connected: boolean;
+ // True while the WS keeps getting closed with code 1013 by the fast-boot
+ // bootstrap (backend still warming up). Distinct from `connected`: drives the
+ // honest "Starting…" indicator instead of "OFFLINE". Defaults true so the
+ // first paint after a restart never flashes "OFFLINE".
+ wsWarming: boolean;
activeSection: SectionId;
transcription: string;
transcriptionFinal: boolean;
@@ -190,6 +201,10 @@ interface EventStore {
// renders as the collapsible "Thought for Xs" disclosure above the reply.
thinkingTraces: Record<string, ThinkingTraceSnapshot>;
brainProvider: string;
+ // The model id the active provider is configured to use (e.g.
+ // "claude-opus-4-8"). Seeded from /api/brain/status on mount and refreshed on
+ // a provider switch. Empty until the first status fetch resolves.
+ brainModel: string;
// How the assistant refers to itself (resolved name: derived from the wake
// phrase with its prefix stripped, else the neutral "Assistant" default —
// [persona].name was removed 2026-06-20). Seeded once at app start by
@@ -218,6 +233,7 @@ interface EventStore {
setVoice: (v: VoiceState) => void;
setVoiceReady: (ready: boolean) => void;
setConnected: (c: boolean) => void;
+ setWarming: (warming: boolean) => void;
clearEvents: () => void;
setActiveSection: (s: SectionId) => void;
setTranscription: (text: string, isFinal: boolean) => void;
@@ -236,6 +252,7 @@ interface EventStore {
/** Turn ended with an assistant reply: snapshot the trace onto that message. */
finishThinking: (messageId: string) => void;
setBrainProvider: (p: string) => void;
+ setBrainModel: (m: string) => void;
setAssistantName: (name: string) => void;
setDictating: (b: boolean) => void;
setDictationInterim: (text: string) => void;
@@ -257,6 +274,7 @@ export const useEventStore = create<EventStore>((set, get) => ({
voiceState: "idle",
voiceReady: false,
connected: false,
+ wsWarming: true,
activeSection: "chats",
transcription: "",
transcriptionFinal: true,
@@ -270,6 +288,7 @@ export const useEventStore = create<EventStore>((set, get) => ({
thinkingStartedTs: null,
thinkingTraces: {},
brainProvider: "unknown",
+ brainModel: "",
assistantName: "Jarvis",
dictating: false,
dictationText: "",
@@ -289,6 +308,7 @@ export const useEventStore = create<EventStore>((set, get) => ({
setVoice: (v) => set({ voiceState: v }),
setVoiceReady: (ready) => set({ voiceReady: ready }),
setConnected: (c) => set({ connected: c }),
+ setWarming: (warming) => set({ wsWarming: warming }),
clearEvents: () => set({ events: [] }),
setActiveSection: (s) => set({ activeSection: s }),
@@ -393,6 +413,7 @@ export const useEventStore = create<EventStore>((set, get) => ({
},
setBrainProvider: (p) => set({ brainProvider: p }),
+ setBrainModel: (m) => set({ brainModel: m }),
setAssistantName: (name) => set({ assistantName: name }),
diff --git a/jarvis/ui/web/frontend/src/store/subAgents.ts b/jarvis/ui/web/frontend/src/store/jarvisAgents.ts
similarity index 100%
rename from jarvis/ui/web/frontend/src/store/subAgents.ts
rename to jarvis/ui/web/frontend/src/store/jarvisAgents.ts
diff --git a/jarvis/ui/web/frontend/src/views/ApiKeysView.antigravity.test.tsx b/jarvis/ui/web/frontend/src/views/ApiKeysView.antigravity.test.tsx
index 8a585b4c37..0b327bad9c 100644
--- a/jarvis/ui/web/frontend/src/views/ApiKeysView.antigravity.test.tsx
+++ b/jarvis/ui/web/frontend/src/views/ApiKeysView.antigravity.test.tsx
@@ -209,16 +209,20 @@ afterEach(() => {
});
describe("ApiKeysView — Antigravity (Google subscription) OAuth card", () => {
- it("renders the compact connected badge with the account email", async () => {
+ it("renders the connected subscription card with email AND a Set-active radio", async () => {
installFetchMock(routesFor(antigravityDescriptor()));
render(<ApiKeysView />);
+ // Antigravity lives in the "Subagents" category tab now; open it first.
+ fireEvent.click(screen.getByRole("tab", { name: /subagents/i }));
await waitFor(() =>
- expect(screen.getByText("Antigravity (Google subscription)")).toBeTruthy(),
+ expect(screen.getByText("Antigravity (Subscription)")).toBeTruthy(),
);
- expect(screen.queryByText("Google subscription login")).toBeNull();
- expect(screen.getByText("Antigravity Google login")).toBeTruthy();
+ // The "Set active" control now lives ON the subscription card, so there is
+ // no longer a separate "Antigravity (Google subscription)" provider card
+ // below it (consolidated — one card per CLI that both connects and selects).
+ expect(screen.queryByText("Antigravity (Google subscription)")).toBeNull();
expect(screen.getByText(/google-user@example\.com/)).toBeTruthy();
expect(screen.getByRole("radio")).toBeTruthy();
});
@@ -226,6 +230,8 @@ describe("ApiKeysView — Antigravity (Google subscription) OAuth card", () => {
it("switches the subagent to Antigravity when connected", async () => {
const { calls } = installFetchMock(routesFor(antigravityDescriptor()));
render(<ApiKeysView />);
+ // Antigravity lives in the "Subagents" category tab now; open it first.
+ fireEvent.click(screen.getByRole("tab", { name: /subagents/i }));
await waitFor(() => screen.getByRole("radio"));
fireEvent.click(screen.getByRole("radio"));
@@ -245,6 +251,8 @@ describe("ApiKeysView — Antigravity (Google subscription) OAuth card", () => {
it("shows the Connect button while not logged in and starts login", async () => {
const { calls } = installFetchMock(routesFor(antigravityNotConnected()));
render(<ApiKeysView />);
+ // Antigravity lives in the "Subagents" category tab now; open it first.
+ fireEvent.click(screen.getByRole("tab", { name: /subagents/i }));
await waitFor(() =>
expect(screen.getByText("Connect")).toBeTruthy(),
@@ -264,6 +272,8 @@ describe("ApiKeysView — Antigravity (Google subscription) OAuth card", () => {
it("disables the Connect button and shows the install hint when no CLI is installed", async () => {
installFetchMock(routesFor(antigravityMissing()));
render(<ApiKeysView />);
+ // Antigravity lives in the "Subagents" category tab now; open it first.
+ fireEvent.click(screen.getByRole("tab", { name: /subagents/i }));
const connectBtn = await waitFor(() =>
screen.getByText("Connect"),
@@ -277,6 +287,8 @@ describe("ApiKeysView — Antigravity (Google subscription) OAuth card", () => {
it("disconnects via POST /api/antigravity/logout", async () => {
const { calls } = installFetchMock(routesFor(antigravityDescriptor()));
render(<ApiKeysView />);
+ // Antigravity lives in the "Subagents" category tab now; open it first.
+ fireEvent.click(screen.getByRole("tab", { name: /subagents/i }));
const disconnect = await waitFor(() => screen.getByText("Disconnect"));
fireEvent.click(disconnect);
diff --git a/jarvis/ui/web/frontend/src/views/ApiKeysView.codex.test.tsx b/jarvis/ui/web/frontend/src/views/ApiKeysView.codex.test.tsx
index e131952ae0..066eb5de88 100644
--- a/jarvis/ui/web/frontend/src/views/ApiKeysView.codex.test.tsx
+++ b/jarvis/ui/web/frontend/src/views/ApiKeysView.codex.test.tsx
@@ -201,8 +201,10 @@ describe("ApiKeysView - Codex is subagent-only", () => {
it("does not render Codex as a Brain provider card", async () => {
installFetchMock(routesFor(codexDescriptor()));
render(<ApiKeysView />);
+ // Codex lives in the "Subagents" category tab now; open it first.
+ fireEvent.click(screen.getByRole("tab", { name: /subagents/i }));
- await waitFor(() => expect(screen.getByText("OpenAI Codex ChatGPT login")).toBeTruthy());
+ await waitFor(() => expect(screen.getByText("OpenAI Codex (Subscription)")).toBeTruthy());
expect(screen.queryByText("ChatGPT / Codex login")).toBeNull();
expect(screen.getByText(/chatgpt-user@example\.com/)).toBeTruthy();
@@ -211,6 +213,8 @@ describe("ApiKeysView - Codex is subagent-only", () => {
it("switches the subagent to Codex without calling brain switch", async () => {
const { calls } = installFetchMock(routesFor(codexDescriptor()));
render(<ApiKeysView />);
+ // Codex lives in the "Subagents" category tab now; open it first.
+ fireEvent.click(screen.getByRole("tab", { name: /subagents/i }));
await waitFor(() => screen.getByRole("radio"));
fireEvent.click(screen.getByRole("radio"));
@@ -231,6 +235,8 @@ describe("ApiKeysView - Codex is subagent-only", () => {
it("shows the Connect button while not logged in and starts login", async () => {
const { calls } = installFetchMock(routesFor(codexDescriptorNotConnected()));
render(<ApiKeysView />);
+ // Codex lives in the "Subagents" category tab now; open it first.
+ fireEvent.click(screen.getByRole("tab", { name: /subagents/i }));
const connect = await waitFor(() => screen.getByText("Connect"));
fireEvent.click(connect);
@@ -247,6 +253,8 @@ describe("ApiKeysView - Codex is subagent-only", () => {
it("disconnects via POST /api/codex/logout", async () => {
const { calls } = installFetchMock(routesFor(codexDescriptor()));
render(<ApiKeysView />);
+ // Codex lives in the "Subagents" category tab now; open it first.
+ fireEvent.click(screen.getByRole("tab", { name: /subagents/i }));
const disconnect = await waitFor(() => screen.getByText("Disconnect"));
fireEvent.click(disconnect);
diff --git a/jarvis/ui/web/frontend/src/views/ApiKeysView.section-health.test.tsx b/jarvis/ui/web/frontend/src/views/ApiKeysView.section-health.test.tsx
new file mode 100644
index 0000000000..69942507a7
--- /dev/null
+++ b/jarvis/ui/web/frontend/src/views/ApiKeysView.section-health.test.tsx
@@ -0,0 +1,99 @@
+/**
+ * Component tests for the API-Keys section-health tab indicators.
+ *
+ * The segmented tab bar shows a corner dot per category: amber when the active
+ * provider of that section still has to be set up ("needs_setup"), red when it
+ * is set up but failing a live check ("error"). "ok" / "unknown" stay silent.
+ * These tests pin that the dot + its plain-language tooltip render from the
+ * /api/providers/section-health rollup.
+ */
+import { afterEach, describe, expect, it, vi } from "vitest";
+import { cleanup, render, screen, waitFor } from "@testing-library/react";
+
+import { ApiKeysView } from "@/views/ApiKeysView";
+
+interface RouteResult {
+ status?: number;
+ body: unknown;
+}
+
+function installFetchMock(routes: Record<string, () => RouteResult>) {
+ const fetchMock = vi.fn(async (input: RequestInfo | URL, init?: RequestInit) => {
+ const url = String(input);
+ const status = (init?.method ?? "GET").toUpperCase();
+ void status;
+ const prefixes = Object.keys(routes).sort((a, b) => b.length - a.length);
+ for (const prefix of prefixes) {
+ if (url.startsWith(prefix)) {
+ const { status: code = 200, body } = routes[prefix]();
+ return {
+ ok: code >= 200 && code < 300,
+ status: code,
+ statusText: code >= 200 && code < 300 ? "OK" : "ERR",
+ json: async () => body,
+ text: async () => JSON.stringify(body),
+ } as Response;
+ }
+ }
+ // SubagentSection fetches /api/{codex,antigravity,claude}/status behind a
+ // .catch — an unmatched route there is harmless. Everything the tabs need is
+ // mocked below.
+ throw new Error(`unexpected fetch ${url}`);
+ });
+ (globalThis as unknown as { fetch: typeof fetch }).fetch =
+ fetchMock as unknown as typeof fetch;
+}
+
+const SECTION_HEALTH = {
+ sections: {
+ brain: { status: "needs_setup", reason: "not_configured", detail: "OpenRouter: no key set" },
+ tts: { status: "ok", reason: "ok", detail: "Gemini Flash: ok" },
+ stt: { status: "error", reason: "bad_key", detail: "Groq STT: key invalid" },
+ subagents: { status: "unknown", reason: "unknown", detail: "" },
+ advanced: { status: "unknown", reason: "unknown", detail: "" },
+ },
+ checked_at: 0,
+ cached: false,
+};
+
+function baseRoutes(overrides: Record<string, () => RouteResult> = {}) {
+ return {
+ "/api/providers/section-health": () => ({ body: SECTION_HEALTH }),
+ "/api/providers": () => ({ body: { providers: [] } }),
+ "/api/openclaw/status": () => ({ body: { mapping: [], brain_primary: "" } }),
+ ...overrides,
+ };
+}
+
+afterEach(() => {
+ cleanup();
+ vi.restoreAllMocks();
+});
+
+describe("ApiKeysView — section-health tab indicators", () => {
+ it("marks a not-set-up tab amber ('Setup needed')", async () => {
+ installFetchMock(baseRoutes());
+ render(<ApiKeysView />);
+ await waitFor(() =>
+ expect(screen.getByRole("tab", { name: /Brain.*Setup needed/i })).toBeTruthy(),
+ );
+ });
+
+ it("marks a broken tab red ('Not working') with the cause in the tooltip", async () => {
+ installFetchMock(baseRoutes());
+ render(<ApiKeysView />);
+ const sttTab = await waitFor(() =>
+ screen.getByRole("tab", { name: /Voice Input.*Not working/i }),
+ );
+ expect(sttTab.getAttribute("title")).toMatch(/key invalid/i);
+ });
+
+ it("leaves a healthy tab without any indicator", async () => {
+ installFetchMock(baseRoutes());
+ render(<ApiKeysView />);
+ // The "Voice Output" tab is ok → no "Setup needed" / "Not working" in its name.
+ await waitFor(() => screen.getByRole("tab", { name: /Brain/i }));
+ const ttsTab = screen.getByRole("tab", { name: /^Voice Output$/i });
+ expect(ttsTab.getAttribute("title")).toBeNull();
+ });
+});
diff --git a/jarvis/ui/web/frontend/src/views/ApiKeysView.telephony.test.tsx b/jarvis/ui/web/frontend/src/views/ApiKeysView.telephony.test.tsx
index b13359dc56..17a6870daf 100644
--- a/jarvis/ui/web/frontend/src/views/ApiKeysView.telephony.test.tsx
+++ b/jarvis/ui/web/frontend/src/views/ApiKeysView.telephony.test.tsx
@@ -123,6 +123,8 @@ describe("ApiKeysView — embedded Telephony tier", () => {
it("renders the Telephony tier header inside the API-Keys view", async () => {
installFetchMock(routes());
render(<ApiKeysView />);
+ // Telephony now lives in the de-emphasized "Advanced" tab; open it first.
+ fireEvent.click(screen.getByRole("tab", { name: /advanced/i }));
// English is the test-default locale; tier_telephony => "Telephony".
await waitFor(() => expect(screen.getByText("Telephony")).toBeTruthy());
@@ -131,6 +133,8 @@ describe("ApiKeysView — embedded Telephony tier", () => {
it("loads live telephony status (Charon voice) from /api/telephony", async () => {
installFetchMock(routes());
render(<ApiKeysView />);
+ // Telephony now lives in the de-emphasized "Advanced" tab; open it first.
+ fireEvent.click(screen.getByRole("tab", { name: /advanced/i }));
await waitFor(() => {
expect(screen.getByTestId("status-tts-voice").textContent).toBe("Charon");
@@ -143,6 +147,8 @@ describe("ApiKeysView — embedded Telephony tier", () => {
it("offers a 'Setup script' button that navigates to the telephony-setup page", async () => {
installFetchMock(routes());
render(<ApiKeysView />);
+ // Telephony now lives in the de-emphasized "Advanced" tab; open it first.
+ fireEvent.click(screen.getByRole("tab", { name: /advanced/i }));
const btn = await waitFor(() =>
screen.getByRole("button", { name: /Setup script/i }),
diff --git a/jarvis/ui/web/frontend/src/views/ApiKeysView.tsx b/jarvis/ui/web/frontend/src/views/ApiKeysView.tsx
index 44e8d6b748..a390f2f700 100644
--- a/jarvis/ui/web/frontend/src/views/ApiKeysView.tsx
+++ b/jarvis/ui/web/frontend/src/views/ApiKeysView.tsx
@@ -1,5 +1,5 @@
import { useState } from "react";
-import { Brain, Check, Copy, KeyRound, LogIn, LogOut, Mic, Phone, PlugZap, Terminal, Volume2, Loader2, AlertCircle, XCircle } from "lucide-react";
+import { AlertCircle, Bot, Brain, Check, Copy, KeyRound, Loader2, LogIn, LogOut, Mic, Phone, PlugZap, SlidersHorizontal, Terminal, Volume2, XCircle } from "lucide-react";
import { ViewHeader } from "@/views/ChatsView";
import { AltCredentialNote } from "@/components/AltCredentialNote";
import { ApiKeyForm } from "@/components/ApiKeyForm";
@@ -9,6 +9,8 @@ import { ProviderBillingBadge } from "@/components/ProviderBillingBadge";
import { SubagentSection } from "@/components/SubagentSection";
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";
import {
codexLogout,
@@ -18,29 +20,73 @@ import {
type ProviderTestResult,
type ProviderTestStatus,
type ProviderTier,
+ type SectionHealth,
startCodexLogin,
switchBrainProvider,
switchSttProvider,
switchTtsProvider,
testProvider,
useProviders,
+ useSectionHealth,
} from "@/hooks/useProviders";
import { useEventStore } from "@/store/events";
import { cn } from "@/lib/utils";
import { useT } from "@/i18n";
-function makeTierMeta(t: (k: string) => string): Record<ProviderTier, { label: string; icon: React.ReactNode }> {
+// The view is organised around exactly four primary categories — Brain, Voice
+// Output (TTS), Voice Input (STT) and Subagents — surfaced as a segmented tab
+// bar. Everything else (Control-API key, team key proxy, telephony, Wiki) lives
+// in a clearly separated, de-emphasized "Advanced" tab so it never competes with
+// the four core categories.
+type CategoryKey = ProviderTier | "subagents" | "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: { label: t("apikeys_view.tier_brain"), icon: <Brain className="h-3.5 w-3.5" /> },
- tts: { label: t("apikeys_view.tier_tts"), icon: <Volume2 className="h-3.5 w-3.5" /> },
- stt: { label: t("apikeys_view.tier_stt"), icon: <Mic className="h-3.5 w-3.5" /> },
+ 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,
+ },
};
}
export function ApiKeysView() {
const t = useT();
- const TIER_META = makeTierMeta(t);
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 } = useSectionHealth();
+ const categories = makeProviderCategories(t);
+ const [active, setActive] = useState<CategoryKey>("brain");
return (
<div className="flex h-full flex-col">
@@ -50,52 +96,310 @@ export function ApiKeysView() {
subtitle={t("apikeys_view.subtitle")}
/>
+ <CategoryTabs active={active} onSelect={setActive} health={health} />
+
<div className="flex-1 overflow-y-auto scrollbar-jarvis p-6">
- {loading && (
- <div className="mt-6 flex items-center gap-2 text-sm text-muted-foreground">
- <Loader2 className="h-4 w-4 animate-spin" /> {t("apikeys_view.loading_providers")}
- </div>
+ {(active === "brain" || active === "tts" || active === "stt") && (
+ <ProviderCategory
+ meta={categories[active]}
+ tier={active}
+ providers={providers}
+ loading={loading}
+ error={error}
+ onChanged={refetch}
+ onActivateOptimistic={setActiveOptimistic}
+ />
)}
+ {active === "subagents" && <SubagentCategory />}
+ {active === "advanced" && <AdvancedCategory />}
+ </div>
+ </div>
+ );
+}
- {error && (
- <div className="mt-6 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={() => refetch()} className="ml-2 underline">{t("apikeys_view.retry")}</button>
- </div>
- </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
+ * neutral (non-gold) styling so it reads as secondary, never competing with the
+ * four primary categories.
+ */
+function CategoryTabs({
+ active,
+ onSelect,
+ health,
+}: {
+ active: CategoryKey;
+ onSelect: (key: CategoryKey) => void;
+ /** Per-tab health rollup keyed by category; absent keys render no dot. */
+ health: Record<string, SectionHealth>;
+}) {
+ const t = useT();
+ const coreTabs: { key: CategoryKey; label: string; icon: LucideIcon }[] = [
+ { key: "brain", label: t("apikeys_view.tab_brain"), icon: Brain },
+ { key: "tts", label: t("apikeys_view.tab_tts"), icon: Volume2 },
+ { key: "stt", label: t("apikeys_view.tab_stt"), icon: Mic },
+ { key: "subagents", label: t("apikeys_view.tab_subagents"), icon: Bot },
+ ];
+ return (
+ <div className="border-b border-border px-6 py-3">
+ <div role="tablist" className="flex flex-wrap items-center gap-1.5">
+ <div className="flex flex-wrap items-center gap-1 rounded-xl border border-border bg-card/40 p-1">
+ {coreTabs.map((tab) => (
+ <TabButton
+ key={tab.key}
+ icon={tab.icon}
+ label={tab.label}
+ selected={active === tab.key}
+ onClick={() => onSelect(tab.key)}
+ health={health[tab.key]}
+ />
+ ))}
+ </div>
+ <span
+ className="mx-1 hidden h-6 w-px bg-border/70 sm:block"
+ aria-hidden="true"
+ />
+ <TabButton
+ icon={SlidersHorizontal}
+ label={t("apikeys_view.tab_advanced")}
+ selected={active === "advanced"}
+ onClick={() => onSelect("advanced")}
+ health={health.advanced}
+ muted
+ />
+ </div>
+ </div>
+ );
+}
+
+function TabButton({
+ icon: Icon,
+ label,
+ selected,
+ onClick,
+ muted = false,
+ health,
+}: {
+ icon: LucideIcon;
+ label: string;
+ selected: boolean;
+ onClick: () => void;
+ /** The de-emphasized "Advanced" tab: neutral fill instead of the gold accent. */
+ muted?: boolean;
+ /** Optional health rollup driving the corner status dot. */
+ health?: SectionHealth;
+}) {
+ const t = useT();
+ // Only the two "needs attention" states draw a dot — amber for "still has to be
+ // set up", red for "set up but not working". `ok` / `unknown` stay silent so the
+ // tab bar is calm and a dot always means "look here".
+ const indicator =
+ health?.status === "error"
+ ? "error"
+ : health?.status === "needs_setup"
+ ? "needs_setup"
+ : null;
+ const statusLabel =
+ indicator === "error"
+ ? t("apikeys_view.health_error")
+ : indicator === "needs_setup"
+ ? t("apikeys_view.health_needs_setup")
+ : "";
+ // Tooltip: the plain-language status plus the backend's one-line detail
+ // (e.g. "Groq STT: key invalid"), so hovering explains exactly what's wrong.
+ const title = indicator
+ ? [statusLabel, health?.detail].filter(Boolean).join(" — ")
+ : undefined;
+
+ return (
+ <button
+ type="button"
+ role="tab"
+ aria-selected={selected}
+ onClick={onClick}
+ title={title}
+ className={cn(
+ "relative inline-flex items-center gap-2 rounded-lg px-3.5 py-2 text-sm font-medium transition-colors",
+ muted
+ ? selected
+ ? "bg-secondary text-foreground ring-1 ring-border"
+ : "text-muted-foreground/70 hover:bg-secondary/50 hover:text-foreground"
+ : selected
+ ? "bg-primary/10 text-primary ring-1 ring-primary/30"
+ : "text-muted-foreground hover:bg-secondary/60 hover:text-foreground",
+ // A faint red outline echoes the "rot umrandet" cue for a broken section,
+ // independent of the selection ring so the two never fight.
+ indicator === "error" && "outline outline-1 outline-destructive/70",
+ )}
+ >
+ <Icon className="h-4 w-4" />
+ {label}
+ {indicator && (
+ <>
+ <span
+ aria-hidden="true"
+ className={cn(
+ "absolute -right-0.5 -top-0.5 h-2.5 w-2.5 rounded-full ring-2 ring-background",
+ indicator === "error" ? "bg-destructive" : "bg-amber-500",
+ )}
+ />
+ <span className="sr-only">{` (${statusLabel})`}</span>
+ </>
+ )}
+ </button>
+ );
+}
+
+/**
+ * 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-6 flex items-start gap-3">
+ <div className="flex h-10 w-10 shrink-0 items-center justify-center rounded-xl border border-border bg-secondary/40 text-primary">
+ <Icon className="h-5 w-5" />
+ </div>
+ <div className="min-w-0 pt-0.5">
+ <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>
+ );
+}
+
+/**
+ * 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,
+}: {
+ meta: CategoryMeta;
+ tier: ProviderTier;
+ providers: ProviderDescriptor[];
+ loading: boolean;
+ error: string | null;
+ onChanged: () => void;
+ onActivateOptimistic: (tier: ProviderTier, id: string) => void;
+}) {
+ const t = useT();
+ const tierProviders = providers.filter(
+ (p) => p.tier === tier && p.brain_switchable !== false,
+ );
- {!loading && providers.length > 0 && (
- <div className="mt-6 space-y-8">
- {(Object.keys(TIER_META) as ProviderTier[]).map((tier) => {
- const tierProviders = providers.filter(
- (p) => p.tier === tier && p.brain_switchable !== false,
- );
- if (!tierProviders.length) return null;
- return (
- <TierSection
- key={tier}
- tier={tier}
- providers={tierProviders}
- onChanged={refetch}
- onActivateOptimistic={setActiveOptimistic}
- />
- );
- })}
- {/* Subagent (OpenClaw) — own data source (/api/openclaw/status),
- rendered as a sibling tier so it shares the card system. */}
- <SubagentSection />
- {/* Telephony — the former standalone "Telephony" screen, folded in
- here as another tier section (own data source /api/telephony/*).
- Same header style as the tiers above; always expanded. */}
- <TelephonySection />
- {/* Wiki — dedicated long-term-memory curator provider/model. Own
- data source (/api/settings/wiki-provider); a thin sibling tier. */}
- <WikiProviderCard />
+ return (
+ <div role="tabpanel">
+ <CategoryHero icon={meta.icon} title={meta.title} description={meta.description} />
+
+ {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}
+ />
+ )}
+ </div>
+ );
+}
+
+/**
+ * The Subagents category — the heavy-task worker selection. `SubagentSection`
+ * owns its own data source (/api/openclaw/status) and card system; the hero band
+ * just frames it consistently with the provider tiers.
+ */
+function SubagentCategory() {
+ const t = useT();
+ return (
+ <div role="tabpanel">
+ <CategoryHero
+ icon={Bot}
+ title={t("apikeys_view.cat_subagents_title")}
+ description={t("apikeys_view.cat_subagents_desc")}
+ />
+ <SubagentSection hideHeader />
+ </div>
+ );
+}
+
+/**
+ * The de-emphasized "Advanced" category — everything that is NOT one of the four
+ * core provider categories: the local Control-API key, the team key proxy,
+ * telephony, and the knowledge-Wiki provider. Each block keeps its own labelled
+ * sub-section header, so the zone reads as a clearly separated list of optional
+ * integrations rather than competing with the four primary categories.
+ */
+function AdvancedCategory() {
+ const t = useT();
+ return (
+ <div role="tabpanel">
+ <CategoryHero
+ icon={SlidersHorizontal}
+ title={t("apikeys_view.advanced_title")}
+ description={t("apikeys_view.advanced_desc")}
+ />
+ <div className="space-y-8">
+ {/* Jarvis access — the local Control-API key (lets local coding agents
+ drive Jarvis over HTTP) and the optional Team key proxy. Both are
+ credential / key-routing management, so they live with the provider
+ keys rather than in the behaviour-focused Settings view. */}
+ <JarvisApiGroup />
+ <TeamProxyGroup />
+ {/* Telephony — the former standalone screen, embedded as a section (own
+ data source /api/telephony/*). */}
+ <TelephonySection />
+ {/* Wiki — dedicated long-term-memory curator provider/model. Own data
+ source (/api/settings/wiki-provider). */}
+ <WikiProviderCard />
+ {/* Nominative-use trademark notice: provider/integration names and logos
+ belong to their owners and are shown only to identify what you connect
+ to. Backs the third-party logos used on plugin cards (see
+ TRADEMARK.md). */}
+ <p className="pt-2 text-[11px] leading-relaxed text-muted-foreground">
+ {t("apikeys_view.trademark_notice")}
+ </p>
</div>
</div>
);
@@ -122,40 +426,33 @@ function TelephonySection() {
);
}
+// 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({
- tier,
providers,
onChanged,
onActivateOptimistic,
}: {
- tier: ProviderTier;
providers: ProviderDescriptor[];
onChanged: () => void;
onActivateOptimistic: (tier: ProviderTier, id: string) => void;
}) {
- const t = useT();
- const meta = makeTierMeta(t)[tier];
- // Wenn niemand in dieser Tier aktiv ist, soll ein frisch gesetzter Key sich
- // selbst aktivieren — der erste konfigurierte Provider gewinnt automatisch.
const tierHasActive = providers.some((p) => p.active);
return (
- <section>
- <h3 className="mb-3 inline-flex items-center gap-2 text-[10px] uppercase tracking-wider text-muted-foreground">
- {meta.icon} {meta.label}
- </h3>
- <ul className="space-y-3">
- {providers.map((p) => (
- <li key={p.id}>
- <ProviderCard
- descriptor={p}
- onChanged={onChanged}
- onActivateOptimistic={onActivateOptimistic}
- autoActivateOnSave={!tierHasActive}
- />
- </li>
- ))}
- </ul>
- </section>
+ <ul className="space-y-3">
+ {providers.map((p) => (
+ <li key={p.id}>
+ <ProviderCard
+ descriptor={p}
+ onChanged={onChanged}
+ onActivateOptimistic={onActivateOptimistic}
+ autoActivateOnSave={!tierHasActive}
+ />
+ </li>
+ ))}
+ </ul>
);
}
@@ -184,7 +481,7 @@ function ProviderCard({
async function activate(assumeConfigured = false) {
if (descriptor.active) return;
if (!isBrainSwitchable) {
- pushToast("warning", `${descriptor.label} is only available for Subagents.`);
+ pushToast("warning", `${descriptor.label} is only available for Jarvis-Agents.`);
return;
}
if (isCodex && !descriptor.codex_brain_ready) {
@@ -281,7 +578,7 @@ function ProviderCard({
descriptor.active
? t("apikeys_view.active_tooltip")
: !isBrainSwitchable
- ? "Available for Subagents only"
+ ? "Available for Jarvis-Agents only"
: descriptor.configured
? t("apikeys_view.click_to_activate")
: descriptor.auth_mode === "codex"
@@ -345,7 +642,7 @@ function ProviderCard({
disabled={!isBrainSwitchable || (isCodex && !descriptor.codex_brain_ready)}
disabledReason={
!isBrainSwitchable
- ? "Available for Subagents only"
+ ? "Available for Jarvis-Agents only"
: isCodex && !descriptor.codex_brain_ready
? t("apikeys_codex.brain_needs_openai_key")
: undefined
@@ -361,16 +658,18 @@ function ProviderCard({
{!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">
- Subagent only. This provider cannot be used as the main Brain or
+ Jarvis-Agent only. This provider cannot be used as the main Brain or
Computer-Use planner because it does not receive screenshots.
</p>
)}
- {/* Model / voice picker. Switchable brain providers
- pick a model from their own live catalog. TTS/STT share a single global
- [tts]/[stt] block, so the picker only appears on the ACTIVE one and sets
- the voice (Grok/Gemini/OpenAI/Google) or model (Cartesia/STT). */}
- {((descriptor.tier === "brain" && descriptor.configured && isBrainSwitchable) ||
+ {/* 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)) && (
@@ -380,6 +679,17 @@ function ProviderCard({
/>
)}
+ {/* 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). */}
{descriptor.tier === "brain" && descriptor.configured && isBrainSwitchable && (
@@ -434,6 +744,9 @@ function ProviderTestControl({ providerId }: { providerId: string }) {
});
} finally {
setRunning(false);
+ // Let the tab indicators re-check: if this was the active provider, its
+ // tab dot should reflect the fresh result instead of a stale cached one.
+ window.dispatchEvent(new Event("jarvis:provider-tested"));
}
}
@@ -558,7 +871,7 @@ function ActiveControl({
disabled={activating || disabled}
className="accent-primary"
/>
- {activating ? "Activating…" : "Set active"}
+ {activating ? "Activating…" : descriptor.active ? "Active" : "Set active"}
</label>
);
}
diff --git a/jarvis/ui/web/frontend/src/views/ChatsView.tsx b/jarvis/ui/web/frontend/src/views/ChatsView.tsx
index 4790c8b546..10c250b04a 100644
--- a/jarvis/ui/web/frontend/src/views/ChatsView.tsx
+++ b/jarvis/ui/web/frontend/src/views/ChatsView.tsx
@@ -13,6 +13,7 @@ import { ThinkingTrace, ThoughtTraceDisclosure } from "@/components/ThinkingTrac
import { cn } from "@/lib/utils";
import { useT } from "@/i18n";
import { useResizablePane } from "@/hooks/useResizablePane";
+import { useVoiceReadiness } from "@/hooks/useVoiceReadiness";
import {
ChatsApiError,
deleteTextConversation,
@@ -489,6 +490,11 @@ function MessageBubble({ message }: { message: ChatMessage }) {
*/
function EmptyState() {
const t = useT();
+ // Honest readiness: while the voice stack is still warming, the centre of the
+ // screen must NOT claim "Ready for commands" while the banner says "starting
+ // up". Both now read the same useVoiceReadiness source. Typing already works
+ // (the input is connected-gated, not voice-gated), so the warming copy says so.
+ const { warming } = useVoiceReadiness();
return (
<div className="flex h-full flex-col items-center justify-center px-6 py-10 text-center">
@@ -499,13 +505,13 @@ function EmptyState() {
className="profile-rise font-display text-3xl font-semibold tracking-tight text-foreground sm:text-4xl"
style={{ animationDelay: "80ms" }}
>
- {t("chats_view.empty_title")}
+ {warming ? t("chats_view.warming_title") : t("chats_view.empty_title")}
</h3>
<p
className="profile-rise mt-3 max-w-md text-sm leading-relaxed text-muted-foreground sm:text-base"
style={{ animationDelay: "160ms" }}
>
- {t("chats_view.empty_subtitle")}
+ {warming ? t("chats_view.warming_subtitle") : t("chats_view.empty_subtitle")}
</p>
</div>
);
diff --git a/jarvis/ui/web/frontend/src/views/DebugView (1).tsx b/jarvis/ui/web/frontend/src/views/DebugView (1).tsx
new file mode 100644
index 0000000000..05d71f2e0a
--- /dev/null
+++ b/jarvis/ui/web/frontend/src/views/DebugView (1).tsx
@@ -0,0 +1,85 @@
+import { Activity, Trash2, Zap } from "lucide-react";
+import { ViewHeader } from "@/views/ChatsView";
+import { EventTimeline } from "@/components/EventTimeline";
+import { ProviderSwitcher } from "@/components/ProviderSwitcher";
+import { Button } from "@/components/ui/button";
+import { useEventStore } from "@/store/events";
+import { useT } from "@/i18n";
+
+export function DebugView() {
+ const t = useT();
+ const pushEvent = useEventStore((s) => s.pushEvent);
+ const clearEvents = useEventStore((s) => s.clearEvents);
+ const events = useEventStore((s) => s.events);
+
+ return (
+ <div className="flex h-full flex-col">
+ <ViewHeader
+ icon={<Activity className="h-4 w-4 text-primary" />}
+ title={t("debug_view.title")}
+ subtitle={`${t("debug_view.subtitle")} · ${events.length} events`}
+ />
+ <div className="grid flex-1 min-h-0 grid-cols-[1fr_320px] gap-0">
+ <div className="flex min-h-0 flex-col border-r border-border">
+ <div className="flex items-center gap-2 border-b border-border px-4 py-2">
+ <span className="text-[10px] uppercase tracking-wider text-muted-foreground">
+ Event-Timeline
+ </span>
+ <div className="ml-auto flex gap-1">
+ <Button
+ size="sm"
+ variant="ghost"
+ onClick={() =>
+ pushEvent({
+ id: `dbg-${Date.now()}`,
+ name: "debug.test_emit",
+ layer: "ui",
+ ts: Date.now(),
+ payload: { note: "manual emit from Debug view" },
+ })
+ }
+ >
+ <Zap className="h-3.5 w-3.5" />
+ <span className="ml-1 text-xs">Emit</span>
+ </Button>
+ <Button size="sm" variant="ghost" onClick={clearEvents}>
+ <Trash2 className="h-3.5 w-3.5" />
+ <span className="ml-1 text-xs">Clear</span>
+ </Button>
+ </div>
+ </div>
+ <div className="flex-1 min-h-0">
+ <EventTimeline />
+ </div>
+ </div>
+
+ <aside className="flex flex-col overflow-y-auto scrollbar-jarvis">
+ <div className="border-b border-border p-4">
+ <h3 className="mb-3 text-[10px] uppercase tracking-wider text-muted-foreground">
+ Brain-Provider wechseln
+ </h3>
+ <ProviderSwitcher />
+ </div>
+ <div className="border-b border-border p-4">
+ <h3 className="mb-2 text-[10px] uppercase tracking-wider text-muted-foreground">
+ Flight-Recorder
+ </h3>
+ <p className="text-xs text-muted-foreground">
+ JSONL-Traces aus{" "}
+ <code className="font-mono">%APPDATA%\Jarvis\traces\</code> —
+ Replay-Player folgt.
+ </p>
+ </div>
+ <div className="p-4">
+ <h3 className="mb-2 text-[10px] uppercase tracking-wider text-muted-foreground">
+ Metrics
+ </h3>
+ <p className="text-xs text-muted-foreground">
+ Latenz / Tokens / Cost pro Provider — live-Charts ab Phase 2.
+ </p>
+ </div>
+ </aside>
+ </div>
+ </div>
+ );
+}
diff --git a/jarvis/ui/web/frontend/src/views/SubAgentsView.tsx b/jarvis/ui/web/frontend/src/views/JarvisAgentsView.tsx
similarity index 98%
rename from jarvis/ui/web/frontend/src/views/SubAgentsView.tsx
rename to jarvis/ui/web/frontend/src/views/JarvisAgentsView.tsx
index b24a46084e..bd5580b712 100644
--- a/jarvis/ui/web/frontend/src/views/SubAgentsView.tsx
+++ b/jarvis/ui/web/frontend/src/views/JarvisAgentsView.tsx
@@ -1,5 +1,5 @@
/**
- * SubAgentsView — Live-Tafel aller aktiven Jarvis-Sub-Agents.
+ * SubAgentsView — Live-Tafel aller aktiven Jarvis-Agents.
*
* Statt einer ReactFlow-Canvas mit Karten rendert die View jetzt eine
* Bahnhofs-Abfahrtstafel (DepartureBoard), die sich kontinuierlich vom
diff --git a/jarvis/ui/web/frontend/src/views/MakeItYoursView.test.tsx b/jarvis/ui/web/frontend/src/views/MakeItYoursView.test.tsx
new file mode 100644
index 0000000000..79e35b16f6
--- /dev/null
+++ b/jarvis/ui/web/frontend/src/views/MakeItYoursView.test.tsx
@@ -0,0 +1,172 @@
+import { cleanup, fireEvent, render, screen, waitFor } from "@testing-library/react";
+import { afterEach, describe, expect, it, vi } from "vitest";
+
+// Identity translator so rendered text equals the i18n key.
+vi.mock("@/i18n", () => ({ useT: () => (key: string) => key }));
+
+vi.mock("@/store/events", () => ({
+ useEventStore: (selector: (s: { pushToast: () => void }) => unknown) =>
+ selector({ pushToast: vi.fn() }),
+}));
+
+// Stub the heavy ChatsView import (we only need ViewHeader).
+vi.mock("@/views/ChatsView", () => ({
+ ViewHeader: ({ title }: { title: string }) => <header>{title}</header>,
+}));
+
+vi.mock("@/lib/workspaceApi", () => ({
+ fetchWorkspaceAgents: vi.fn(),
+ launchWorkspace: vi.fn(),
+}));
+
+// xterm.js needs a real canvas — stub the embedded terminal in jsdom.
+vi.mock("@/components/workspace/WorkspaceTerminal", () => ({
+ WorkspaceTerminal: ({ title }: { title: string }) => (
+ <div data-testid="ws-term">{title}</div>
+ ),
+}));
+
+import { MakeItYoursView } from "./MakeItYoursView";
+import * as api from "@/lib/workspaceApi";
+
+const RESPONSE: api.AgentsResponse = {
+ cwd: "C:/proj",
+ terminal_available: true,
+ layout_choices: [1, 2, 4, 6, 8, 10, 12],
+ agents: [
+ {
+ name: "claude",
+ display_name: "Claude Code",
+ installed: true,
+ version: "2.1.195",
+ install_command: "npm install -g @anthropic-ai/claude-code",
+ launch_command: "claude",
+ },
+ {
+ name: "codex",
+ display_name: "Codex",
+ installed: true,
+ version: "0.142.3",
+ install_command: "npm install -g @openai/codex",
+ launch_command: "codex",
+ },
+ ],
+};
+
+function withResponse(overrides?: Partial<typeof RESPONSE>) {
+ vi.mocked(api.fetchWorkspaceAgents).mockResolvedValue({ ...RESPONSE, ...overrides });
+}
+
+async function renderLoaded(overrides?: Partial<typeof RESPONSE>) {
+ withResponse(overrides);
+ render(<MakeItYoursView />);
+ await waitFor(() => expect(api.fetchWorkspaceAgents).toHaveBeenCalled());
+}
+
+afterEach(() => {
+ cleanup();
+ vi.clearAllMocks();
+});
+
+describe("MakeItYoursView", () => {
+ it("loads agents and shows the layout tiles", async () => {
+ await renderLoaded();
+ expect(screen.getByText("make_it_yours.step_layout")).toBeTruthy();
+ // BridgeSpace-style tiles for each choice.
+ expect(screen.getByRole("button", { name: "8" })).toBeTruthy();
+ expect(screen.getByRole("button", { name: "12" })).toBeTruthy();
+ });
+
+ it("fills the workspace-size meter proportionally to the chosen terminal count", async () => {
+ await renderLoaded();
+ const fill = () => screen.getByTestId("terminal-fill") as HTMLElement;
+
+ // Default layout is 1 → small fill, label "1 / 12".
+ expect(screen.getByText("1 / 12")).toBeTruthy();
+
+ // Pick 6 → meter exactly half.
+ fireEvent.click(screen.getByRole("button", { name: "6" }));
+ expect(screen.getByText("6 / 12")).toBeTruthy();
+ expect(fill().style.width).toBe("50%");
+
+ // Pick 12 → meter full (the bug was: stayed the same length for every count).
+ fireEvent.click(screen.getByRole("button", { name: "12" }));
+ expect(screen.getByText("12 / 12")).toBeTruthy();
+ expect(fill().style.width).toBe("100%");
+ });
+
+ it("disables Next until the agent counts sum to the chosen layout", async () => {
+ await renderLoaded();
+ fireEvent.click(screen.getByRole("button", { name: "8" })); // choose 8
+ fireEvent.click(screen.getByRole("button", { name: "make_it_yours.next" }));
+
+ // Default split fills all 8 with Claude → 8/8 → Next enabled.
+ const next = screen.getByRole("button", { name: "make_it_yours.next" });
+ expect((next as HTMLButtonElement).disabled).toBe(false);
+
+ // Remove one → 7/8 → Next disabled.
+ fireEvent.click(screen.getAllByLabelText("decrease")[0]);
+ expect((next as HTMLButtonElement).disabled).toBe(true);
+
+ // "Split evenly" → 4+4 = 8 → Next enabled again.
+ fireEvent.click(screen.getByText("make_it_yours.split_evenly"));
+ expect((next as HTMLButtonElement).disabled).toBe(false);
+ });
+
+ it("blocks launch and offers install when a chosen agent is missing", async () => {
+ await renderLoaded({
+ agents: [
+ RESPONSE.agents[0],
+ { ...RESPONSE.agents[1], installed: false, version: null },
+ ],
+ });
+ fireEvent.click(screen.getByRole("button", { name: "2" }));
+ fireEvent.click(screen.getByRole("button", { name: "make_it_yours.next" }));
+
+ // Assign both to the not-installed Codex.
+ fireEvent.click(screen.getByText("make_it_yours.all_codex"));
+
+ expect(screen.getByText("make_it_yours.install")).toBeTruthy();
+ const next = screen.getByRole("button", { name: "make_it_yours.next" });
+ expect((next as HTMLButtonElement).disabled).toBe(true);
+ });
+
+ it("shows a summary with the folder on the confirm step", async () => {
+ await renderLoaded();
+ fireEvent.click(screen.getByRole("button", { name: "2" }));
+ fireEvent.click(screen.getByRole("button", { name: "make_it_yours.next" })); // → agents
+ fireEvent.click(screen.getByRole("button", { name: "make_it_yours.next" })); // → confirm
+
+ expect(screen.getByText(/2 × Claude Code/)).toBeTruthy();
+ expect(screen.getByText("C:/proj")).toBeTruthy();
+ expect(screen.getByRole("button", { name: /make_it_yours\.launch/ })).toBeTruthy();
+ });
+
+ it("warns and cannot launch when no desktop terminal is available", async () => {
+ await renderLoaded({ terminal_available: false });
+ expect(screen.getByText("make_it_yours.no_terminal")).toBeTruthy();
+ });
+
+ it("opens an in-app terminal grid after launching", async () => {
+ await renderLoaded();
+ vi.mocked(api.launchWorkspace).mockResolvedValue({
+ ok: true,
+ cwd: "C:/proj",
+ slots: [
+ { index: 0, agent: "claude", display_name: "Claude Code" },
+ { index: 1, agent: "claude", display_name: "Claude Code" },
+ ],
+ trust: [],
+ detail: "",
+ });
+
+ fireEvent.click(screen.getByRole("button", { name: "2" }));
+ fireEvent.click(screen.getByRole("button", { name: "make_it_yours.next" })); // → agents
+ fireEvent.click(screen.getByRole("button", { name: "make_it_yours.next" })); // → confirm
+ fireEvent.click(screen.getByRole("button", { name: /make_it_yours\.launch/ }));
+
+ await waitFor(() => expect(screen.getAllByTestId("ws-term")).toHaveLength(2));
+ expect(screen.getByText("make_it_yours.end_session")).toBeTruthy();
+ expect(api.launchWorkspace).toHaveBeenCalledWith(2, { claude: 2, codex: 0 });
+ });
+});
diff --git a/jarvis/ui/web/frontend/src/views/MakeItYoursView.tsx b/jarvis/ui/web/frontend/src/views/MakeItYoursView.tsx
new file mode 100644
index 0000000000..3060adf3ff
--- /dev/null
+++ b/jarvis/ui/web/frontend/src/views/MakeItYoursView.tsx
@@ -0,0 +1,578 @@
+import { useCallback, useEffect, useMemo, useState } from "react";
+import {
+ Wand2,
+ Terminal,
+ Check,
+ Plus,
+ Minus,
+ Loader2,
+ FolderOpen,
+ RefreshCw,
+ Rocket,
+ AlertCircle,
+ ArrowLeft,
+ ArrowRight,
+ Download,
+ X,
+} from "lucide-react";
+import { ViewHeader } from "@/views/ChatsView";
+import { useEventStore } from "@/store/events";
+import { cn } from "@/lib/utils";
+import { useT } from "@/i18n";
+import { WorkspaceTerminal } from "@/components/workspace/WorkspaceTerminal";
+import {
+ fetchWorkspaceAgents,
+ launchWorkspace,
+ type AgentsResponse,
+ type Slot,
+ type WorkspaceAgent,
+} from "@/lib/workspaceApi";
+
+// Columns used to draw each layout tile's dot-grid preview (mirrors BridgeSpace).
+const TILE_COLS: Record<number, number> = { 1: 1, 2: 2, 4: 2, 6: 3, 8: 4, 10: 5, 12: 4 };
+
+type Counts = Record<string, number>;
+type Step = 0 | 1 | 2;
+type Session =
+ | { kind: "grid"; slots: Slot[]; cwd: string }
+ | { kind: "install"; name: string; display: string }
+ | null;
+
+function gridCols(n: number): number {
+ if (n <= 1) return 1;
+ if (n <= 2) return 2;
+ return Math.min(4, Math.ceil(Math.sqrt(n)));
+}
+
+export function MakeItYoursView() {
+ const t = useT();
+ const pushToast = useEventStore((s) => s.pushToast);
+
+ const [data, setData] = useState<AgentsResponse | null>(null);
+ const [step, setStep] = useState<Step>(0);
+ const [layout, setLayout] = useState(1);
+ const [counts, setCounts] = useState<Counts>({ claude: 1, codex: 0 });
+ const [launching, setLaunching] = useState(false);
+ const [session, setSession] = useState<Session>(null);
+
+ const refresh = useCallback(async () => {
+ try {
+ setData(await fetchWorkspaceAgents());
+ } catch {
+ /* offline / headless — keep prior state */
+ }
+ }, []);
+
+ useEffect(() => {
+ void refresh();
+ }, [refresh]);
+
+ const agentsByName = useMemo(() => {
+ const m: Record<string, WorkspaceAgent> = {};
+ for (const a of data?.agents ?? []) m[a.name] = a;
+ return m;
+ }, [data]);
+
+ const layoutChoices = data?.layout_choices ?? [1, 2, 4, 6, 8, 10, 12];
+ const maxLayout = Math.max(...layoutChoices);
+ const assigned = Object.values(counts).reduce((s, n) => s + n, 0);
+ const selectedNames = Object.keys(counts).filter((n) => counts[n] > 0);
+ const missing = selectedNames.filter((n) => !agentsByName[n]?.installed);
+ const canLaunch =
+ assigned === layout && missing.length === 0 && (data?.terminal_available ?? true);
+
+ const chooseLayout = (n: number) => {
+ setLayout(n);
+ setCounts({ claude: n, codex: 0 }); // default: all Claude, user re-splits
+ };
+
+ const inc = (name: string) =>
+ setCounts((c) => (assigned < layout ? { ...c, [name]: (c[name] ?? 0) + 1 } : c));
+ const dec = (name: string) =>
+ setCounts((c) => ({ ...c, [name]: Math.max(0, (c[name] ?? 0) - 1) }));
+
+ const quickFill = (mode: "even" | "claude" | "codex") => {
+ if (mode === "claude") setCounts({ claude: layout, codex: 0 });
+ else if (mode === "codex") setCounts({ claude: 0, codex: layout });
+ else setCounts({ claude: Math.ceil(layout / 2), codex: Math.floor(layout / 2) });
+ };
+
+ const onInstall = (name: string) => {
+ const a = agentsByName[name];
+ setSession({ kind: "install", name, display: a?.display_name ?? name });
+ };
+
+ const onLaunch = async () => {
+ setLaunching(true);
+ try {
+ const plan = await launchWorkspace(layout, counts);
+ if (plan.ok && plan.slots.length) {
+ setSession({ kind: "grid", slots: plan.slots, cwd: plan.cwd });
+ } else {
+ pushToast("error", plan.detail || t("make_it_yours.launch_failed"));
+ }
+ } catch (e) {
+ pushToast("error", (e as Error).message);
+ } finally {
+ setLaunching(false);
+ }
+ };
+
+ const endSession = () => {
+ const wasInstall = session?.kind === "install";
+ setSession(null);
+ if (wasInstall) void refresh();
+ };
+
+ // ----- Running modes (terminals embedded in-app) -----
+ if (session?.kind === "grid") {
+ return (
+ <RunningGrid t={t} slots={session.slots} cwd={session.cwd} onEnd={endSession} />
+ );
+ }
+ if (session?.kind === "install") {
+ return (
+ <InstallPanel t={t} name={session.name} display={session.display} onDone={endSession} />
+ );
+ }
+
+ // ----- Setup flow -----
+ return (
+ <div className="flex h-full flex-col">
+ <ViewHeader
+ icon={<Wand2 className="h-4 w-4 text-primary" />}
+ title={t("make_it_yours.title")}
+ subtitle={t("make_it_yours.subtitle")}
+ />
+ <div className="flex-1 overflow-y-auto scrollbar-jarvis">
+ <div className="mx-auto flex w-full max-w-3xl flex-col gap-6 p-6">
+ {/* Workspace-size meter: fills with the chosen terminal count (selected / max). */}
+ <div className="flex items-center gap-3">
+ <div className="h-1.5 flex-1 overflow-hidden rounded-full bg-muted">
+ <div
+ data-testid="terminal-fill"
+ className="h-full rounded-full bg-primary transition-all"
+ style={{ width: `${Math.min(100, (layout / maxLayout) * 100)}%` }}
+ />
+ </div>
+ <span className="font-mono text-xs text-muted-foreground">
+ {layout} / {maxLayout}
+ </span>
+ </div>
+
+ {!data?.terminal_available && data != null && (
+ <div className="flex items-start gap-2 rounded-lg border border-destructive/40 bg-destructive/10 px-4 py-3 text-sm text-destructive">
+ <AlertCircle className="mt-0.5 h-4 w-4 shrink-0" />
+ <span>{t("make_it_yours.no_terminal")}</span>
+ </div>
+ )}
+
+ {step === 0 && (
+ <LayoutStep t={t} choices={layoutChoices} selected={layout} onSelect={chooseLayout} />
+ )}
+ {step === 1 && (
+ <AgentsStep
+ t={t}
+ layout={layout}
+ assigned={assigned}
+ counts={counts}
+ agents={data?.agents ?? []}
+ onInc={inc}
+ onDec={dec}
+ onQuickFill={quickFill}
+ onInstall={onInstall}
+ onRecheck={refresh}
+ />
+ )}
+ {step === 2 && (
+ <ConfirmStep t={t} counts={counts} agentsByName={agentsByName} cwd={data?.cwd ?? ""} />
+ )}
+
+ <div className="flex items-center justify-between pt-2">
+ <button
+ type="button"
+ className={cn("btn-ghost", step === 0 && "invisible")}
+ onClick={() => setStep((s) => (s > 0 ? ((s - 1) as Step) : s))}
+ >
+ <ArrowLeft className="h-4 w-4" />
+ {t("make_it_yours.back")}
+ </button>
+
+ {step < 2 ? (
+ <button
+ type="button"
+ className="btn-primary disabled:cursor-not-allowed disabled:opacity-40"
+ disabled={step === 1 && (assigned !== layout || missing.length > 0)}
+ onClick={() => setStep((s) => ((s + 1) as Step))}
+ >
+ {t("make_it_yours.next")}
+ <ArrowRight className="h-4 w-4" />
+ </button>
+ ) : (
+ <button
+ type="button"
+ className="btn-primary disabled:cursor-not-allowed disabled:opacity-40"
+ disabled={!canLaunch || launching}
+ onClick={onLaunch}
+ >
+ {launching ? (
+ <Loader2 className="h-4 w-4 animate-spin" />
+ ) : (
+ <Rocket className="h-4 w-4" />
+ )}
+ {launching ? t("make_it_yours.launching") : t("make_it_yours.launch")}
+ </button>
+ )}
+ </div>
+ </div>
+ </div>
+ </div>
+ );
+}
+
+function RunningGrid({
+ t,
+ slots,
+ cwd,
+ onEnd,
+}: {
+ t: (k: string) => string;
+ slots: Slot[];
+ cwd: string;
+ onEnd: () => void;
+}) {
+ const cols = gridCols(slots.length);
+ // Per-agent numbering for the titles ("Claude Code 1", "Claude Code 2", …).
+ const perAgent: Record<string, number> = {};
+ const titled = slots.map((s) => {
+ perAgent[s.agent] = (perAgent[s.agent] ?? 0) + 1;
+ return { ...s, title: `${s.display_name} ${perAgent[s.agent]}` };
+ });
+
+ return (
+ <div className="flex h-full flex-col">
+ <div className="flex items-center justify-between border-b border-border px-4 py-2">
+ <div className="flex min-w-0 items-center gap-2">
+ <Wand2 className="h-4 w-4 shrink-0 text-primary" />
+ <span className="font-display text-sm font-semibold">
+ {slots.length} {t("make_it_yours.terminals")}
+ </span>
+ <code className="truncate font-mono text-xs text-muted-foreground">{cwd}</code>
+ </div>
+ <button type="button" className="btn-ghost" onClick={onEnd}>
+ <X className="h-4 w-4" />
+ {t("make_it_yours.end_session")}
+ </button>
+ </div>
+ <div
+ className="grid flex-1 gap-2 overflow-hidden p-2"
+ style={{ gridTemplateColumns: `repeat(${cols}, minmax(0, 1fr))`, gridAutoRows: "1fr" }}
+ >
+ {titled.map((s) => (
+ <WorkspaceTerminal
+ key={s.index}
+ paneKey={`slot-${s.index}`}
+ agentName={s.agent}
+ title={s.title}
+ />
+ ))}
+ </div>
+ </div>
+ );
+}
+
+function InstallPanel({
+ t,
+ name,
+ display,
+ onDone,
+}: {
+ t: (k: string) => string;
+ name: string;
+ display: string;
+ onDone: () => void;
+}) {
+ return (
+ <div className="flex h-full flex-col">
+ <div className="flex items-center justify-between border-b border-border px-4 py-2">
+ <div className="flex items-center gap-2">
+ <Download className="h-4 w-4 text-primary" />
+ <span className="font-display text-sm font-semibold">
+ {t("make_it_yours.install")} · {display}
+ </span>
+ </div>
+ <button type="button" className="btn-primary" onClick={onDone}>
+ <Check className="h-4 w-4" />
+ {t("make_it_yours.install_done")}
+ </button>
+ </div>
+ <div className="flex-1 overflow-hidden p-3">
+ <WorkspaceTerminal paneKey={`install-${name}`} installName={name} title={`install ${name}`} />
+ </div>
+ </div>
+ );
+}
+
+function LayoutStep({
+ t,
+ choices,
+ selected,
+ onSelect,
+}: {
+ t: (k: string) => string;
+ choices: number[];
+ selected: number;
+ onSelect: (n: number) => void;
+}) {
+ return (
+ <div className="space-y-4">
+ <div>
+ <h3 className="font-display text-lg font-semibold">{t("make_it_yours.step_layout")}</h3>
+ <p className="text-sm text-muted-foreground">{t("make_it_yours.step_layout_hint")}</p>
+ </div>
+ <div className="grid grid-cols-3 gap-3 sm:grid-cols-4 lg:grid-cols-7">
+ {choices.map((n) => (
+ <button
+ key={n}
+ type="button"
+ aria-pressed={selected === n}
+ onClick={() => onSelect(n)}
+ className={cn(
+ "flex aspect-square flex-col items-center justify-center gap-2 rounded-xl border p-3 transition-colors",
+ selected === n
+ ? "border-primary/50 bg-primary/5 shadow-[0_0_0_1px_hsl(var(--primary)/0.2)]"
+ : "border-border bg-card/60 hover:border-primary/30",
+ )}
+ >
+ <DotGrid n={n} active={selected === n} />
+ <span
+ className={cn(
+ "text-sm font-semibold",
+ selected === n ? "text-primary" : "text-foreground",
+ )}
+ >
+ {n}
+ </span>
+ </button>
+ ))}
+ </div>
+ </div>
+ );
+}
+
+function DotGrid({ n, active }: { n: number; active: boolean }) {
+ const cols = TILE_COLS[n] ?? Math.min(n, 4);
+ return (
+ <div className="grid gap-1" style={{ gridTemplateColumns: `repeat(${cols}, minmax(0, 1fr))` }}>
+ {Array.from({ length: n }).map((_, i) => (
+ <span
+ key={i}
+ className={cn("h-2 w-2 rounded-[3px]", active ? "bg-primary" : "bg-muted-foreground/40")}
+ />
+ ))}
+ </div>
+ );
+}
+
+function AgentsStep({
+ t,
+ layout,
+ assigned,
+ counts,
+ agents,
+ onInc,
+ onDec,
+ onQuickFill,
+ onInstall,
+ onRecheck,
+}: {
+ t: (k: string) => string;
+ layout: number;
+ assigned: number;
+ counts: Counts;
+ agents: WorkspaceAgent[];
+ onInc: (name: string) => void;
+ onDec: (name: string) => void;
+ onQuickFill: (mode: "even" | "claude" | "codex") => void;
+ onInstall: (name: string) => void;
+ onRecheck: () => void;
+}) {
+ return (
+ <div className="space-y-4">
+ <div>
+ <h3 className="font-display text-lg font-semibold">{t("make_it_yours.step_agents")}</h3>
+ <p className="text-sm text-muted-foreground">{t("make_it_yours.step_agents_hint")}</p>
+ </div>
+
+ <div className="flex items-center gap-3">
+ <div className="h-2 flex-1 overflow-hidden rounded-full bg-muted">
+ <div
+ className={cn(
+ "h-full rounded-full transition-all",
+ assigned === layout ? "bg-primary" : "bg-primary/60",
+ )}
+ style={{ width: `${Math.min(100, (assigned / layout) * 100)}%` }}
+ />
+ </div>
+ <span
+ className={cn(
+ "font-mono text-sm",
+ assigned === layout ? "text-primary" : "text-muted-foreground",
+ )}
+ >
+ {assigned} / {layout}
+ </span>
+ </div>
+
+ <div className="flex flex-wrap items-center gap-2">
+ <span className="text-xs uppercase tracking-wide text-muted-foreground">
+ {t("make_it_yours.quick_fill")}
+ </span>
+ <button type="button" className="chip hover:border-primary/40" onClick={() => onQuickFill("even")}>
+ {t("make_it_yours.split_evenly")}
+ </button>
+ <button type="button" className="chip hover:border-primary/40" onClick={() => onQuickFill("claude")}>
+ {t("make_it_yours.all_claude")}
+ </button>
+ <button type="button" className="chip hover:border-primary/40" onClick={() => onQuickFill("codex")}>
+ {t("make_it_yours.all_codex")}
+ </button>
+ </div>
+
+ <div className="grid gap-3 sm:grid-cols-2">
+ {agents.map((a) => (
+ <AgentCard
+ key={a.name}
+ t={t}
+ agent={a}
+ count={counts[a.name] ?? 0}
+ canInc={assigned < layout}
+ onInc={() => onInc(a.name)}
+ onDec={() => onDec(a.name)}
+ onInstall={() => onInstall(a.name)}
+ onRecheck={onRecheck}
+ />
+ ))}
+ </div>
+ </div>
+ );
+}
+
+function AgentCard({
+ t,
+ agent,
+ count,
+ canInc,
+ onInc,
+ onDec,
+ onInstall,
+ onRecheck,
+}: {
+ t: (k: string) => string;
+ agent: WorkspaceAgent;
+ count: number;
+ canInc: boolean;
+ onInc: () => void;
+ onDec: () => void;
+ onInstall: () => void;
+ onRecheck: () => void;
+}) {
+ return (
+ <div
+ className={cn(
+ "flex flex-col gap-3 rounded-xl border p-4",
+ count > 0 ? "border-primary/40 bg-primary/5" : "border-border bg-card/60",
+ )}
+ >
+ <div className="flex items-center justify-between gap-2">
+ <div className="flex items-center gap-2">
+ <Terminal className="h-4 w-4 text-primary" />
+ <span className="font-medium">{agent.display_name}</span>
+ </div>
+ {agent.installed ? (
+ <span className="flex items-center gap-1 text-xs text-emerald-400">
+ <Check className="h-3.5 w-3.5" />
+ {agent.version ?? t("make_it_yours.installed")}
+ </span>
+ ) : (
+ <span className="text-xs text-muted-foreground">{t("make_it_yours.not_installed")}</span>
+ )}
+ </div>
+
+ {agent.installed ? (
+ <div className="flex items-center justify-end gap-2">
+ <button
+ type="button"
+ aria-label="decrease"
+ className="flex h-8 w-8 items-center justify-center rounded-lg border border-border hover:border-primary/40 disabled:opacity-30"
+ disabled={count <= 0}
+ onClick={onDec}
+ >
+ <Minus className="h-4 w-4" />
+ </button>
+ <span className="w-8 text-center font-mono text-base font-semibold">{count}</span>
+ <button
+ type="button"
+ aria-label="increase"
+ className="flex h-8 w-8 items-center justify-center rounded-lg border border-border hover:border-primary/40 disabled:opacity-30"
+ disabled={!canInc}
+ onClick={onInc}
+ >
+ <Plus className="h-4 w-4" />
+ </button>
+ </div>
+ ) : (
+ <div className="flex items-center gap-2">
+ <button type="button" className="btn-ghost flex-1 justify-center" onClick={onInstall}>
+ <Download className="h-4 w-4" />
+ {t("make_it_yours.install")}
+ </button>
+ <button
+ type="button"
+ aria-label="re-check"
+ className="flex h-9 w-9 items-center justify-center rounded-lg border border-border hover:border-primary/40"
+ onClick={onRecheck}
+ >
+ <RefreshCw className="h-4 w-4" />
+ </button>
+ </div>
+ )}
+ </div>
+ );
+}
+
+function ConfirmStep({
+ t,
+ counts,
+ agentsByName,
+ cwd,
+}: {
+ t: (k: string) => string;
+ counts: Counts;
+ agentsByName: Record<string, WorkspaceAgent>;
+ cwd: string;
+}) {
+ const lines = Object.keys(counts)
+ .filter((n) => counts[n] > 0)
+ .map((n) => `${counts[n]} × ${agentsByName[n]?.display_name ?? n}`);
+
+ return (
+ <div className="space-y-4">
+ <h3 className="font-display text-lg font-semibold">{t("make_it_yours.step_confirm")}</h3>
+ <div className="rounded-xl border border-border bg-card/60 p-5">
+ <div className="flex flex-wrap items-center gap-2 text-lg font-medium">
+ {lines.map((l, i) => (
+ <span key={i} className="rounded-lg bg-primary/10 px-3 py-1 text-primary">
+ {l}
+ </span>
+ ))}
+ </div>
+ <div className="mt-4 flex items-center gap-2 text-sm text-muted-foreground">
+ <FolderOpen className="h-4 w-4 shrink-0 text-primary" />
+ <span>{t("make_it_yours.folder")}:</span>
+ <code className="truncate font-mono text-xs text-foreground">{cwd}</code>
+ </div>
+ </div>
+ </div>
+ );
+}
diff --git a/jarvis/ui/web/frontend/src/views/OutputsView.rerun.test.tsx b/jarvis/ui/web/frontend/src/views/OutputsView.rerun.test.tsx
index f673db42c0..9dadaec5e3 100644
--- a/jarvis/ui/web/frontend/src/views/OutputsView.rerun.test.tsx
+++ b/jarvis/ui/web/frontend/src/views/OutputsView.rerun.test.tsx
@@ -127,6 +127,45 @@ describe("OutputsView rerun button gating", () => {
expect(screen.queryByRole("button", { name: "Continue" })).toBeNull();
});
+ it("replaces Continue with a live continuation chip and jumps to the child", async () => {
+ // Forensic 2026-06-28: a cancelled mission that was already "continued"
+ // kept showing a Continue button next to its own running child — the two
+ // cards looked identical, so the user could not tell whether it was
+ // running. With a live child the card shows a "running" chip instead, and
+ // clicking it jumps to the child.
+ installFetchMock([
+ session({
+ slug: "mission_019f0fa6-4ff6",
+ utterance: "Parent task",
+ status: "cancelled",
+ mission_id: "m-parent",
+ active_child_id: "019f0fac-26a3-7c59",
+ active_child_slug: "mission_019f0fac-26a3",
+ }),
+ session({
+ slug: "mission_019f0fac-26a3",
+ utterance: "Child task",
+ status: "running",
+ mission_id: "m-child",
+ }),
+ ]);
+ renderView();
+ await waitFor(() =>
+ expect(
+ screen.getAllByTestId("continuation-chip").length,
+ ).toBeGreaterThan(0),
+ );
+ // The redundant Continue button is gone while the continuation is live.
+ expect(screen.queryByRole("button", { name: "Continue" })).toBeNull();
+ // Clicking the chip selects the running child card.
+ fireEvent.click(screen.getAllByTestId("continuation-chip")[0]);
+ await waitFor(() =>
+ expect(
+ screen.getByRole("heading", { name: "Child task" }),
+ ).toBeDefined(),
+ );
+ });
+
it("shows neither for running or successful missions", async () => {
installFetchMock([
session({ slug: "run-slug", status: "running", mission_id: "m-r" }),
diff --git a/jarvis/ui/web/frontend/src/views/OutputsView.tsx b/jarvis/ui/web/frontend/src/views/OutputsView.tsx
index 4e566bc6bd..9815fd5c0a 100644
--- a/jarvis/ui/web/frontend/src/views/OutputsView.tsx
+++ b/jarvis/ui/web/frontend/src/views/OutputsView.tsx
@@ -56,6 +56,47 @@ function PulseDot() {
);
}
+/**
+ * Shown on a terminal (cancelled / errored) card whose re-run continuation is
+ * still running. Replaces the "Continue"/"Restart" button so the card stops
+ * implying the work is idle and re-runnable — the truth is that it is alive in
+ * a linked child mission. Clicking jumps the selection to that live child card
+ * (forensic 2026-06-28: a cancelled card and its running continuation looked
+ * identical, so the user could not tell whether the mission was running).
+ */
+function ContinuationChip({
+ onJump,
+ size = "sm",
+}: {
+ onJump: () => void;
+ size?: "sm" | "md";
+}) {
+ const t = useT();
+ const sizing =
+ size === "sm" ? "px-1.5 py-0.5 text-[10px]" : "px-2 py-1 text-[11px]";
+ const label = t("outputs_view.continuation_running");
+ return (
+ <button
+ type="button"
+ title={label}
+ aria-label={label}
+ data-testid="continuation-chip"
+ onClick={(e) => {
+ e.stopPropagation();
+ onJump();
+ }}
+ className={cn(
+ "inline-flex shrink-0 select-none items-center gap-1 rounded border font-semibold uppercase tracking-wide transition-colors",
+ "border-primary/40 bg-primary/10 text-primary hover:bg-primary/20",
+ sizing,
+ )}
+ >
+ <PulseDot />
+ <span>{label}</span>
+ </button>
+ );
+}
+
const URL_REGEX = /(https?:\/\/[^\s)]+[^\s.,;:!?)])/g;
/** MIME type carrying a mission reference between a card and the Jarvis dock.
@@ -152,6 +193,7 @@ export function OutputsView() {
isSelected={effectiveSlug === s.slug}
onSelect={() => setSelectedSlug(s.slug)}
onOpenDesktop={() => openOnDesktop(s.slug)}
+ onJumpToSlug={setSelectedSlug}
/>
</li>
))}
@@ -162,7 +204,10 @@ export function OutputsView() {
<section className="flex min-w-0 flex-1 flex-col">
{effectiveSelected ? (
- <SessionDetail meta={effectiveSelected} />
+ <SessionDetail
+ meta={effectiveSelected}
+ onJumpToSlug={setSelectedSlug}
+ />
) : (
<div className="flex flex-1 items-center justify-center text-xs text-muted-foreground">
{t("outputs_view.select_session")}
@@ -179,11 +224,13 @@ function SessionRow({
isSelected,
onSelect,
onOpenDesktop,
+ onJumpToSlug,
}: {
meta: OutputSummary;
isSelected: boolean;
onSelect: () => void;
onOpenDesktop: () => void;
+ onJumpToSlug?: (slug: string) => void;
}) {
const t = useT();
const cancel = useCancelMission();
@@ -192,6 +239,12 @@ function SessionRow({
const ts = meta.completed_at ?? meta.started_at;
const tsLabel = ts ? new Date(ts * 1000).toLocaleString() : "--";
const canAbort = statusKey === "running" && !!meta.mission_id;
+ // A cancelled/errored card whose re-run continuation is still running: show
+ // a live "running" chip (jumps to the child) instead of a "Continue" button.
+ const liveChildSlug =
+ statusKey === "cancelled" || statusKey === "error"
+ ? meta.active_child_slug ?? null
+ : null;
return (
<button
@@ -232,19 +285,28 @@ function SessionRow({
}
/>
)}
- {statusKey === "cancelled" && meta.mission_id && (
- <RerunButton
- missionId={meta.mission_id}
- action="continue"
- size="sm"
- />
- )}
- {statusKey === "error" && meta.mission_id && (
- <RerunButton
- missionId={meta.mission_id}
- action="restart"
+ {liveChildSlug ? (
+ <ContinuationChip
size="sm"
+ onJump={() => onJumpToSlug?.(liveChildSlug)}
/>
+ ) : (
+ <>
+ {statusKey === "cancelled" && meta.mission_id && (
+ <RerunButton
+ missionId={meta.mission_id}
+ action="continue"
+ size="sm"
+ />
+ )}
+ {statusKey === "error" && meta.mission_id && (
+ <RerunButton
+ missionId={meta.mission_id}
+ action="restart"
+ size="sm"
+ />
+ )}
+ </>
)}
<span
className={cn(
@@ -299,13 +361,23 @@ function SessionRow({
);
}
-function SessionDetail({ meta }: { meta: OutputSummary }) {
+function SessionDetail({
+ meta,
+ onJumpToSlug,
+}: {
+ meta: OutputSummary;
+ onJumpToSlug?: (slug: string) => void;
+}) {
const t = useT();
const cancel = useCancelMission();
const plan = usePlanForOutput(meta.slug);
const statusKey = meta.status ?? "unknown";
const badgeClass = STATUS_BADGE[statusKey] ?? STATUS_BADGE.unknown;
const canAbort = statusKey === "running" && !!meta.mission_id;
+ const liveChildSlug =
+ statusKey === "cancelled" || statusKey === "error"
+ ? meta.active_child_slug ?? null
+ : null;
const hasPlan =
!plan.isLoading && plan.data && plan.data.plan !== null;
const isSingleShot =
@@ -354,19 +426,28 @@ function SessionDetail({ meta }: { meta: OutputSummary }) {
</span>
</span>
)}
- {statusKey === "cancelled" && meta.mission_id && (
- <RerunButton
- missionId={meta.mission_id}
- action="continue"
- size="md"
- />
- )}
- {statusKey === "error" && meta.mission_id && (
- <RerunButton
- missionId={meta.mission_id}
- action="restart"
+ {liveChildSlug ? (
+ <ContinuationChip
size="md"
+ onJump={() => onJumpToSlug?.(liveChildSlug)}
/>
+ ) : (
+ <>
+ {statusKey === "cancelled" && meta.mission_id && (
+ <RerunButton
+ missionId={meta.mission_id}
+ action="continue"
+ size="md"
+ />
+ )}
+ {statusKey === "error" && meta.mission_id && (
+ <RerunButton
+ missionId={meta.mission_id}
+ action="restart"
+ size="md"
+ />
+ )}
+ </>
)}
{meta.github_url && (
<a
diff --git a/jarvis/ui/web/frontend/src/views/PluginsView.test.tsx b/jarvis/ui/web/frontend/src/views/PluginsView.test.tsx
index 254b02d8db..3f8d3a759e 100644
--- a/jarvis/ui/web/frontend/src/views/PluginsView.test.tsx
+++ b/jarvis/ui/web/frontend/src/views/PluginsView.test.tsx
@@ -1,8 +1,8 @@
import { QueryClient, QueryClientProvider } from "@tanstack/react-query";
-import { cleanup, render, screen, waitFor } from "@testing-library/react";
+import { act, cleanup, fireEvent, render, screen, waitFor } from "@testing-library/react";
import { afterEach, describe, expect, it, vi } from "vitest";
-import { PluginsView } from "@/views/PluginsView";
+import { ConnectIconButton, PluginsView } from "@/views/PluginsView";
const CATALOG = {
version: 1,
@@ -110,3 +110,60 @@ describe("PluginsView live badge", () => {
expect(screen.getByText("· Live")).toBeDefined();
});
});
+
+// Regression: `/connect/start` takes ~0.6s with no other feedback, so a user
+// clicked the "+" several times and EACH click launched its own OAuth flow — a
+// burst of browser tabs + multiple DCR client registrations. The button must
+// lock itself (and show a spinner) while a connect is in flight, ignoring the
+// extra clicks, then re-enable so a genuine retry still works.
+describe("ConnectIconButton click-lock", () => {
+ it("ignores extra clicks while a connect is in flight", async () => {
+ let release: () => void = () => {};
+ const onConnect = vi.fn(
+ () => new Promise<void>((resolve) => { release = resolve; }),
+ );
+ render(
+ <ConnectIconButton
+ status="not_connected"
+ onConnect={onConnect}
+ onDisconnect={() => {}}
+ />,
+ );
+ const btn = screen.getByRole("button", { name: "Connect plugin" });
+
+ fireEvent.click(btn);
+ fireEvent.click(btn); // second click while the first is still pending
+ fireEvent.click(btn); // third
+
+ // Only the first click started a flow; the rest were swallowed by the lock.
+ expect(onConnect).toHaveBeenCalledTimes(1);
+ await waitFor(() => expect((btn as HTMLButtonElement).disabled).toBe(true));
+
+ await act(async () => {
+ release();
+ });
+ expect((btn as HTMLButtonElement).disabled).toBe(false);
+ });
+
+ it("re-enables after the connect resolves so a retry still works", async () => {
+ const onConnect = vi.fn(() => Promise.resolve());
+ render(
+ <ConnectIconButton
+ status="not_connected"
+ onConnect={onConnect}
+ onDisconnect={() => {}}
+ />,
+ );
+ const btn = screen.getByRole("button", { name: "Connect plugin" });
+
+ await act(async () => {
+ fireEvent.click(btn);
+ });
+ expect((btn as HTMLButtonElement).disabled).toBe(false);
+ await act(async () => {
+ fireEvent.click(btn);
+ });
+
+ expect(onConnect).toHaveBeenCalledTimes(2);
+ });
+});
diff --git a/jarvis/ui/web/frontend/src/views/PluginsView.tsx b/jarvis/ui/web/frontend/src/views/PluginsView.tsx
index f4e4521f9d..ee7bdd136b 100644
--- a/jarvis/ui/web/frontend/src/views/PluginsView.tsx
+++ b/jarvis/ui/web/frontend/src/views/PluginsView.tsx
@@ -9,6 +9,7 @@ import {
RefreshCw,
Plus,
Check,
+ Copy,
Sparkles,
X,
Loader2,
@@ -17,6 +18,8 @@ import { ViewHeader } from "@/views/ChatsView";
import { ScrollArea } from "@/components/ui/scroll-area";
import { Button } from "@/components/ui/button";
import { cn } from "@/lib/utils";
+import { openExternalUrl } from "@/lib/openExternal";
+import { robustCopy } from "@/lib/clipboard";
// Wave hero image restored. The previous "kill image entirely" attempt
// felt too flat; the CSS-only gradient lacked atmospheric depth. Edge
@@ -109,7 +112,14 @@ function resolveLogoUrl(p: { logoUrl?: string; logoSlug: string; logoColor?: str
}
async function fetchCatalog(): Promise<CatalogResponse> {
- const res = await fetch("/api/marketplace/plugins");
+ // `cache: "no-store"` forces the embedded WebView2 (desktop app) to bypass
+ // its HTTP cache on every fetch. The server already sends
+ // `Cache-Control: no-store`, but that only stops NEW caching — it does not
+ // evict an entry WebView2 had already frozen. Result: the desktop window kept
+ // serving a stale plugin list (a freshly-connected plugin still showed as
+ // "not connected") while a normal browser tab showed the truth. Bypassing the
+ // client cache here is the half that actually clears the residual entry.
+ const res = await fetch("/api/marketplace/plugins", { cache: "no-store" });
if (!res.ok) throw new Error(`HTTP ${res.status}`);
return res.json();
}
@@ -267,7 +277,7 @@ export function PluginsView() {
// Auto-open the pre-filled verify URL if available; user lands
// on the consent page with the code already typed in.
if (verifyUrlComplete) {
- window.open(verifyUrlComplete, "_blank", "noopener,noreferrer");
+ void openExternalUrl(verifyUrlComplete);
}
setDeviceSession({
flowId: r.flow_id,
@@ -284,7 +294,7 @@ export function PluginsView() {
alert("Backend returned no open_url — connect aborted.");
return;
}
- window.open(r.open_url, "_blank", "noopener,noreferrer");
+ void openExternalUrl(r.open_url);
setOauthSession({
flowId: r.flow_id,
pluginId: r.plugin_id,
@@ -476,7 +486,10 @@ export function PluginsView() {
// ---------------------------------------------------------------------------
interface ConnectHandlers {
- onConnect: (p: Plugin) => void;
+ // Returns a promise for the in-flight connect so the per-row button can lock
+ // itself (spinner + disabled) until the flow has launched — see
+ // ConnectIconButton. A void return (e.g. pat_paste opening a modal) is fine.
+ onConnect: (p: Plugin) => void | Promise<void>;
onDisconnect: (id: string) => void;
}
@@ -659,6 +672,13 @@ interface CarouselSlide {
}
const SLIDES: CarouselSlide[] = [
+ {
+ pluginId: "google_calendar",
+ pluginName: "Google Calendar",
+ example: "Schedule a meeting for tomorrow at 3pm",
+ iconUrl: "https://cdn.simpleicons.org/googlecalendar/F4F4F5",
+ accent: "border-blue-400/40",
+ },
{
pluginId: "github",
pluginName: "GitHub",
@@ -887,7 +907,7 @@ function PluginRow({
: "border-border hover:border-primary/40 hover:bg-card/70",
)}
>
- <div className="grid h-10 w-10 shrink-0 place-items-center rounded-md border border-border/60 bg-background/60">
+ <div className="grid h-10 w-10 shrink-0 place-items-center rounded-md border border-border/60 bg-white">
<img
src={resolveLogoUrl(plugin)}
alt=""
@@ -931,15 +951,23 @@ function PluginRow({
);
}
-function ConnectIconButton({
+export function ConnectIconButton({
status,
onConnect,
onDisconnect,
}: {
status: PluginStatus;
- onConnect: () => void;
+ onConnect: () => void | Promise<void>;
onDisconnect: () => void;
}) {
+ // `/connect/start` (DCR registration) takes ~0.6s with no other feedback, so
+ // without a lock the user re-clicks and each click launches its OWN OAuth flow
+ // — a burst of browser tabs and stray client registrations. `busyRef` is the
+ // SYNCHRONOUS guard (React state is async and would let a fast double-click
+ // through before the re-render disables the button); `busy` drives the UI.
+ const [busy, setBusy] = useState(false);
+ const busyRef = useRef(false);
+
if (status === "connected") {
return (
<button
@@ -953,14 +981,36 @@ function ConnectIconButton({
</button>
);
}
+
+ const handleClick = async () => {
+ if (busyRef.current) return;
+ busyRef.current = true;
+ setBusy(true);
+ try {
+ await onConnect();
+ } finally {
+ busyRef.current = false;
+ setBusy(false);
+ }
+ };
+
return (
<button
type="button"
- onClick={onConnect}
- className="grid h-7 w-7 shrink-0 place-items-center rounded-full border border-border bg-background/60 text-muted-foreground transition-all hover:border-primary/50 hover:bg-primary/10 hover:text-primary group-hover:scale-105"
+ onClick={handleClick}
+ disabled={busy}
+ aria-busy={busy}
+ className={cn(
+ "grid h-7 w-7 shrink-0 place-items-center rounded-full border border-border bg-background/60 text-muted-foreground transition-all hover:border-primary/50 hover:bg-primary/10 hover:text-primary group-hover:scale-105",
+ busy && "cursor-not-allowed opacity-60 hover:bg-background/60 hover:text-muted-foreground group-hover:scale-100",
+ )}
aria-label="Connect plugin"
>
- <Plus className="h-3.5 w-3.5" />
+ {busy ? (
+ <Loader2 className="h-3.5 w-3.5 animate-spin" />
+ ) : (
+ <Plus className="h-3.5 w-3.5" />
+ )}
</button>
);
}
@@ -1023,6 +1073,47 @@ function ComingSoonStrip({ taken = [] }: { taken?: string[] }) {
// dialog just shows progress + long-polls the backend.
// ---------------------------------------------------------------------------
+// A read-only URL field + Copy button. The manual fallback for every "open a
+// page in your browser" step: when the auto-open didn't reach a browser (the
+// embedded desktop shell drops window.open, or a popup blocker ate it), the
+// user can copy the exact link and paste it into their browser by hand. Uses
+// robustCopy so the copy is reliable inside WebView2.
+function CopyableUrl({ url, hint }: { url: string; hint?: string }) {
+ const [copied, setCopied] = useState(false);
+ const copy = async () => {
+ if (await robustCopy(url)) {
+ setCopied(true);
+ window.setTimeout(() => setCopied(false), 1400);
+ }
+ };
+ return (
+ <div className="w-full text-left">
+ <div className="flex items-stretch gap-2">
+ <input
+ type="text"
+ readOnly
+ value={url}
+ onFocus={(e) => e.currentTarget.select()}
+ aria-label="Authorization link"
+ className="min-w-0 flex-1 rounded-md border border-border bg-background/60 px-2.5 py-1.5 font-mono text-[11px] text-muted-foreground focus:border-primary/40 focus:outline-none"
+ />
+ <button
+ type="button"
+ onClick={copy}
+ className="inline-flex shrink-0 items-center gap-1.5 rounded-md border border-border bg-card px-3 text-[11px] font-medium text-foreground transition-colors hover:border-primary/50 hover:text-primary"
+ title="Copy link"
+ >
+ {copied ? <Check className="h-3 w-3 text-primary" /> : <Copy className="h-3 w-3" />}
+ {copied ? "Copied" : "Copy"}
+ </button>
+ </div>
+ {hint && (
+ <p className="mt-1.5 text-[11px] leading-relaxed text-muted-foreground/80">{hint}</p>
+ )}
+ </div>
+ );
+}
+
function OAuthRedirectDialog({
flowId,
pluginId,
@@ -1043,6 +1134,7 @@ function OAuthRedirectDialog({
queryFn: async () => {
const res = await fetch(
`/api/marketplace/plugins/${pluginId}/connect/poll/${flowId}`,
+ { cache: "no-store" },
);
if (!res.ok) {
const err = await res.json().catch(() => ({ detail: `HTTP ${res.status}` }));
@@ -1124,10 +1216,18 @@ function OAuthRedirectDialog({
href={openUrl}
target="_blank"
rel="noopener noreferrer"
+ onClick={(e) => {
+ e.preventDefault();
+ void openExternalUrl(openUrl);
+ }}
className="text-[11px] uppercase tracking-wider text-muted-foreground/80 underline-offset-4 hover:text-primary hover:underline"
>
Tab didn't open? Click here
</a>
+ <CopyableUrl
+ url={openUrl}
+ hint="Still nothing? Copy this link and paste it into your browser's address bar."
+ />
</div>
)}
@@ -1207,6 +1307,7 @@ function DeviceCodeDialog({
queryFn: async () => {
const res = await fetch(
`/api/marketplace/plugins/${pluginId}/connect/poll/${flowId}`,
+ { cache: "no-store" },
);
if (!res.ok) {
const err = await res.json().catch(() => ({ detail: `HTTP ${res.status}` }));
@@ -1311,15 +1412,21 @@ function DeviceCodeDialog({
href={verificationUriComplete ?? verificationUri}
target="_blank"
rel="noopener noreferrer"
+ onClick={(e) => {
+ e.preventDefault();
+ void openExternalUrl(verificationUriComplete ?? verificationUri);
+ }}
className="mt-2 inline-flex items-center gap-1.5 rounded-full bg-primary px-3.5 py-1.5 text-xs font-semibold text-primary-foreground transition-all hover:bg-primary/90 hover:shadow-[0_0_16px_rgba(255,214,10,0.4)]"
>
Open {pluginName}
<ExternalLink className="h-3 w-3" />
</a>
- <p className="mt-1.5 text-[11px] text-muted-foreground/80">
- Or visit{" "}
- <span className="font-mono">{verificationUri}</span> manually.
- </p>
+ <div className="mt-2">
+ <CopyableUrl
+ url={verificationUri}
+ hint="Or copy this link, open it in your browser, and enter the code above."
+ />
+ </div>
</div>
<div className="flex items-center gap-2 text-[11px] text-muted-foreground">
@@ -1408,7 +1515,7 @@ function DisconnectConfirmDialog({
<div className="relative w-full max-w-sm overflow-hidden rounded-2xl border border-border bg-card shadow-[0_20px_60px_rgba(0,0,0,0.6)]">
<header className="flex items-center justify-between border-b border-border px-5 py-4">
<div className="flex items-center gap-3">
- <div className="grid h-10 w-10 shrink-0 place-items-center rounded-md border border-border/60 bg-background/60">
+ <div className="grid h-10 w-10 shrink-0 place-items-center rounded-md border border-border/60 bg-white">
<img
src={resolveLogoUrl(plugin)}
alt=""
@@ -1539,7 +1646,7 @@ export function PatConnectDialog({
<div className="relative w-full max-w-md overflow-hidden rounded-2xl border border-border bg-card shadow-[0_20px_60px_rgba(0,0,0,0.6)]">
<header className="flex items-center justify-between border-b border-border px-5 py-4">
<div className="flex items-center gap-3">
- <div className="grid h-10 w-10 shrink-0 place-items-center rounded-md border border-border/60 bg-background/60">
+ <div className="grid h-10 w-10 shrink-0 place-items-center rounded-md border border-border/60 bg-white">
<img
src={resolveLogoUrl(plugin)}
alt=""
@@ -1579,11 +1686,21 @@ export function PatConnectDialog({
href={auth.token_creation_url}
target="_blank"
rel="noopener noreferrer"
+ onClick={(e) => {
+ e.preventDefault();
+ void openExternalUrl(auth.token_creation_url);
+ }}
className="mt-2 inline-flex items-center gap-1.5 rounded-full bg-primary px-3.5 py-1.5 text-xs font-semibold text-primary-foreground transition-all hover:bg-primary/90 hover:shadow-[0_0_16px_rgba(255,214,10,0.4)]"
>
Open {plugin.name} tokens
<ExternalLink className="h-3 w-3" />
</a>
+ <div className="mt-2">
+ <CopyableUrl
+ url={auth.token_creation_url}
+ hint="Or copy this link and open it in your browser yourself."
+ />
+ </div>
</Step>
<Step num={2} title="Paste the token below">
diff --git a/jarvis/ui/web/frontend/src/views/ProfileView.tsx b/jarvis/ui/web/frontend/src/views/ProfileView.tsx
index 3290442c3e..c95804457f 100644
--- a/jarvis/ui/web/frontend/src/views/ProfileView.tsx
+++ b/jarvis/ui/web/frontend/src/views/ProfileView.tsx
@@ -15,6 +15,7 @@ import {
ChevronRight,
Lock,
Pencil,
+ Plus,
Save,
Camera,
Trash2,
@@ -37,6 +38,7 @@ import {
collectOpenQuestions,
countFilled,
displayAddress,
+ fieldKind,
isEmptyValue,
type ClusterId,
} from "@/views/profile/ledger";
@@ -472,6 +474,285 @@ function AskCard({ meta }: { meta: Record<string, unknown> }) {
);
}
+// ----------------------------------------------------------------------
+// Inline field editing — a quiet pencil per field, edited in place
+// ----------------------------------------------------------------------
+
+type FieldOp = "set" | "clear" | "append" | "remove";
+
+/** Shared mutation for PATCH /api/profile/field. Invalidates the profile query
+ * on success so the card re-renders with the persisted value. */
+function useFieldEdit() {
+ const queryClient = useQueryClient();
+ const pushToast = useEventStore((s) => s.pushToast);
+ return useMutation({
+ mutationFn: async (body: {
+ cluster: ClusterId;
+ field: string;
+ operation: FieldOp;
+ value?: unknown;
+ }) => {
+ const res = await fetch("/api/profile/field", {
+ method: "PATCH",
+ headers: { "Content-Type": "application/json" },
+ body: JSON.stringify(body),
+ });
+ if (!res.ok) {
+ const data = (await res.json().catch(() => ({}))) as { detail?: string };
+ throw new Error(data.detail ?? `HTTP ${res.status}`);
+ }
+ return res.json();
+ },
+ onSuccess: () => queryClient.invalidateQueries({ queryKey: ["profile"] }),
+ onError: (err: Error) => pushToast("error", err.message),
+ });
+}
+
+function IconBtn({
+ icon: Icon,
+ onClick,
+ title,
+ tone = "muted",
+ disabled,
+}: {
+ icon: typeof Check;
+ onClick: () => void;
+ title: string;
+ tone?: "muted" | "primary" | "danger";
+ disabled?: boolean;
+}) {
+ const toneCls =
+ tone === "primary"
+ ? "text-primary hover:bg-primary/10"
+ : tone === "danger"
+ ? "text-muted-foreground hover:bg-destructive/10 hover:text-destructive"
+ : "text-muted-foreground hover:bg-white/[0.06] hover:text-foreground";
+ return (
+ <button
+ type="button"
+ onClick={onClick}
+ title={title}
+ aria-label={title}
+ disabled={disabled}
+ className={cn(
+ "shrink-0 rounded p-1 outline-none transition-colors focus-visible:ring-1 focus-visible:ring-primary/50 disabled:opacity-40",
+ toneCls,
+ )}
+ >
+ <Icon className="h-3.5 w-3.5" />
+ </button>
+ );
+}
+
+/** One field row with inline editing: a hover-revealed pencil opens an in-place
+ * editor whose shape depends on the field kind (scalar text, yes/no toggle, or
+ * removable chips for lists). Persists through PATCH /api/profile/field. */
+function EditableFieldRow({
+ cid,
+ fieldKey,
+ value,
+}: {
+ cid: ClusterId;
+ fieldKey: string;
+ value: unknown;
+}) {
+ const t = useT();
+ const pushToast = useEventStore((s) => s.pushToast);
+ const edit = useFieldEdit();
+ const kind = fieldKind(fieldKey);
+ const empty = isEmptyValue(value);
+ const label = t(`profile_view.fields.${fieldKey}`);
+
+ const [editing, setEditing] = useState(false);
+ const [draft, setDraft] = useState("");
+ const inputRef = useRef<HTMLInputElement | null>(null);
+
+ useEffect(() => {
+ if (editing) inputRef.current?.focus();
+ }, [editing]);
+
+ const busy = edit.isPending;
+ const toast = () => pushToast("success", t("profile_view.field_saved"));
+
+ const startEdit = () => {
+ setDraft(kind === "scalar" && !empty ? String(value) : "");
+ setEditing(true);
+ };
+ const cancel = () => {
+ setDraft("");
+ setEditing(false);
+ };
+ const mutate = (operation: FieldOp, v?: unknown, opts?: { keepOpen?: boolean; clearDraft?: boolean }) => {
+ edit.mutate(
+ { cluster: cid, field: fieldKey, operation, value: v },
+ {
+ onSuccess: () => {
+ toast();
+ if (opts?.clearDraft) setDraft("");
+ if (opts?.keepOpen) inputRef.current?.focus();
+ else cancel();
+ },
+ },
+ );
+ };
+
+ const saveScalar = () => {
+ const v = draft.trim();
+ if (!v) {
+ mutate("clear");
+ } else {
+ mutate("set", v);
+ }
+ };
+ const addItem = () => {
+ const v = draft.trim();
+ if (v) mutate("append", v, { keepOpen: true, clearDraft: true });
+ };
+
+ // ------------------------------------------------------------------ display
+ if (!editing) {
+ return (
+ <div className="group flex items-baseline justify-between gap-4 border-b border-white/[0.05] py-2 last:border-b-0">
+ <dt className={cn("shrink-0 text-xs", empty ? "text-muted-foreground/60" : "text-muted-foreground")}>
+ {label}
+ </dt>
+ <dd className="flex min-w-0 max-w-[72%] items-center justify-end gap-1">
+ {kind === "list" && !empty ? (
+ <div className="flex flex-wrap justify-end gap-1">
+ {(value as unknown[]).map((item) => (
+ <span
+ key={String(item)}
+ className="rounded-full border border-white/[0.08] bg-white/[0.04] px-2 py-0.5 text-xs font-medium"
+ >
+ {String(item)}
+ </span>
+ ))}
+ </div>
+ ) : (
+ <span
+ className={cn(
+ "leading-snug [overflow-wrap:anywhere]",
+ empty
+ ? "text-xs italic text-muted-foreground/45"
+ : "text-sm font-medium",
+ )}
+ >
+ {empty ? t("profile_view.field_unknown") : renderValue(t, value)}
+ </span>
+ )}
+ {/* Quiet pencil — appears on row hover / keyboard focus only. */}
+ <button
+ type="button"
+ onClick={startEdit}
+ title={t("profile_view.field_edit")}
+ aria-label={`${t("profile_view.field_edit")}: ${label}`}
+ className="shrink-0 rounded p-1 text-muted-foreground opacity-0 outline-none transition-opacity hover:text-primary focus-visible:opacity-100 focus-visible:ring-1 focus-visible:ring-primary/50 group-hover:opacity-100"
+ >
+ <Pencil className="h-3 w-3" />
+ </button>
+ </dd>
+ </div>
+ );
+ }
+
+ // ------------------------------------------------------------------- editing
+ return (
+ <div className="group flex items-baseline justify-between gap-4 border-b border-white/[0.05] py-2 last:border-b-0">
+ <dt className="shrink-0 text-xs text-muted-foreground">{label}</dt>
+ <dd className="flex min-w-0 max-w-[72%] flex-col items-end gap-1.5">
+ {kind === "bool" ? (
+ <div className="flex items-center gap-1">
+ {([true, false] as const).map((b) => (
+ <button
+ key={String(b)}
+ type="button"
+ disabled={busy}
+ onClick={() => mutate("set", b)}
+ className={cn(
+ "rounded-full border px-2.5 py-0.5 text-xs font-medium transition-colors disabled:opacity-40",
+ value === b
+ ? "border-primary/50 bg-primary/[0.12] text-primary"
+ : "border-white/[0.08] bg-white/[0.03] text-muted-foreground hover:border-primary/40",
+ )}
+ >
+ {b ? t("profile_view.value_yes") : t("profile_view.value_no")}
+ </button>
+ ))}
+ <IconBtn icon={X} onClick={cancel} title={t("profile_view.raw_cancel")} disabled={busy} />
+ {!empty && (
+ <IconBtn icon={Trash2} onClick={() => mutate("clear")} title={t("profile_view.field_clear")} tone="danger" disabled={busy} />
+ )}
+ </div>
+ ) : kind === "list" ? (
+ <>
+ {!empty && (
+ <div className="flex flex-wrap justify-end gap-1">
+ {(value as unknown[]).map((item) => (
+ <span
+ key={String(item)}
+ className="inline-flex items-center gap-1 rounded-full border border-white/[0.1] bg-white/[0.05] py-0.5 pl-2 pr-1 text-xs font-medium"
+ >
+ {String(item)}
+ <button
+ type="button"
+ disabled={busy}
+ onClick={() => mutate("remove", String(item), { keepOpen: true })}
+ title={t("profile_view.field_remove_item")}
+ aria-label={`${t("profile_view.field_remove_item")}: ${String(item)}`}
+ className="rounded-full p-0.5 text-muted-foreground outline-none transition-colors hover:bg-destructive/15 hover:text-destructive focus-visible:ring-1 focus-visible:ring-primary/50 disabled:opacity-40"
+ >
+ <X className="h-2.5 w-2.5" />
+ </button>
+ </span>
+ ))}
+ </div>
+ )}
+ <div className="flex items-center gap-1">
+ <input
+ ref={inputRef}
+ value={draft}
+ disabled={busy}
+ onChange={(e) => setDraft(e.target.value)}
+ onKeyDown={(e) => {
+ if (e.key === "Enter") addItem();
+ if (e.key === "Escape") cancel();
+ }}
+ placeholder={t("profile_view.field_add_placeholder")}
+ className="w-32 min-w-0 rounded border border-primary/40 bg-background/60 px-2 py-1 text-sm outline-none focus:border-primary"
+ />
+ <IconBtn icon={Plus} onClick={addItem} title={t("profile_view.field_add")} tone="primary" disabled={busy} />
+ <IconBtn icon={Check} onClick={cancel} title={t("profile_view.raw_save")} disabled={busy} />
+ {!empty && (
+ <IconBtn icon={Trash2} onClick={() => mutate("clear")} title={t("profile_view.field_clear")} tone="danger" disabled={busy} />
+ )}
+ </div>
+ </>
+ ) : (
+ <div className="flex w-full items-center justify-end gap-1">
+ <input
+ ref={inputRef}
+ value={draft}
+ disabled={busy}
+ onChange={(e) => setDraft(e.target.value)}
+ onKeyDown={(e) => {
+ if (e.key === "Enter") saveScalar();
+ if (e.key === "Escape") cancel();
+ }}
+ placeholder={t("profile_view.field_value_placeholder")}
+ className="min-w-0 flex-1 rounded border border-primary/40 bg-background/60 px-2 py-1 text-right text-sm outline-none focus:border-primary"
+ />
+ <IconBtn icon={Check} onClick={saveScalar} title={t("profile_view.raw_save")} tone="primary" disabled={busy} />
+ <IconBtn icon={X} onClick={cancel} title={t("profile_view.raw_cancel")} disabled={busy} />
+ {!empty && (
+ <IconBtn icon={Trash2} onClick={() => mutate("clear")} title={t("profile_view.field_clear")} tone="danger" disabled={busy} />
+ )}
+ </div>
+ )}
+ </dd>
+ </div>
+ );
+}
+
// ----------------------------------------------------------------------
// Cluster cards — quiet rows; learned first, blanks capped at two
// ----------------------------------------------------------------------
@@ -509,34 +790,14 @@ function ClusterCard({
{t(`profile_view.clusters.${cid}.description`)}
</p>
+ {/* Each row carries its own quiet pencil — learned fields can be
+ overwritten or cleared, blank ones filled in, all edited in place. */}
<dl className="mt-3">
{known.map((key) => (
- <div
- key={key}
- className="flex items-baseline justify-between gap-4 border-b border-white/[0.05] py-2 last:border-b-0"
- >
- <dt className="shrink-0 text-xs text-muted-foreground">
- {t(`profile_view.fields.${key}`)}
- </dt>
- <dd className="max-w-[65%] text-right text-sm font-medium leading-snug [overflow-wrap:anywhere]">
- {renderValue(t, data[key])}
- </dd>
- </div>
+ <EditableFieldRow key={key} cid={cid} fieldKey={key} value={data[key]} />
))}
{blanksShown.map((key) => (
- <div
- key={key}
- className="flex items-baseline justify-between gap-4 border-b border-white/[0.05] py-2 last:border-b-0"
- >
- <dt className="shrink-0 text-xs text-muted-foreground/60">
- {t(`profile_view.fields.${key}`)}
- </dt>
- {/* Blank fields stay plainly readable — nothing is concealed,
- they simply haven't been learned yet. */}
- <dd className="text-right text-xs italic text-muted-foreground/45">
- {t("profile_view.field_unknown")}
- </dd>
- </div>
+ <EditableFieldRow key={key} cid={cid} fieldKey={key} value={data[key]} />
))}
</dl>
{blanksHidden > 0 && (
diff --git a/jarvis/ui/web/frontend/src/views/SettingsView.tsx b/jarvis/ui/web/frontend/src/views/SettingsView.tsx
index 3b2df03fd7..0601e43e62 100644
--- a/jarvis/ui/web/frontend/src/views/SettingsView.tsx
+++ b/jarvis/ui/web/frontend/src/views/SettingsView.tsx
@@ -11,9 +11,7 @@ import { OverlayTaskbarGroup } from "@/views/settings/OverlayTaskbarGroup";
import { LanguagesGroup } from "@/views/settings/LanguagesGroup";
import { AppSettingsGroup } from "@/views/settings/AppSettingsGroup";
import { SilenceWindowGroup } from "@/views/settings/SilenceWindowGroup";
-import { JarvisApiGroup } from "@/views/settings/JarvisApiGroup";
import { SystemPromptGroup } from "@/views/settings/SystemPromptGroup";
-import { TeamProxyGroup } from "@/views/settings/TeamProxyGroup";
import { useWakeWord, type WakeWordSaveResult } from "@/hooks/useWakeWord";
import {
useKeybinds,
@@ -64,8 +62,6 @@ export function SettingsView() {
<div className="flex-1 overflow-y-auto scrollbar-jarvis p-6">
<LanguagesGroup />
<AppSettingsGroup />
- <JarvisApiGroup />
- <TeamProxyGroup />
<SystemPromptGroup />
<WakeWordPanel />
<SilenceWindowGroup />
diff --git a/jarvis/ui/web/frontend/src/views/SkillCreateDialog.tsx b/jarvis/ui/web/frontend/src/views/SkillCreateDialog.tsx
index e2f0944c0e..ec4ea48d6e 100644
--- a/jarvis/ui/web/frontend/src/views/SkillCreateDialog.tsx
+++ b/jarvis/ui/web/frontend/src/views/SkillCreateDialog.tsx
@@ -2,22 +2,34 @@
* SkillCreateDialog — create a new user skill from the desktop app.
*
* Two ways in, one robust outcome:
- * - Fill the form (name + instructions) and hit Create. This goes through the
- * deterministic POST /api/skills path — no brain, always works, even on a
- * headless VPS.
- * - Optionally hit "Draft with AI": the creator endpoint turns a free-text
- * intent into a pre-filled draft. If a brain is reachable it fills richer
- * content; if not (or it fails) it returns a deterministic starter template
- * and the form stays fully editable. Either way the user reviews the fields
- * and Create persists exactly what they see.
+ * - "Write the whole skill with AI": you describe what the skill should do and
+ * the AI writes the COMPLETE skill (name, instructions, voice trigger). It
+ * lands fully filled in for a quick review, then one click creates it. If a
+ * brain is reachable it fills rich content; if not it returns a deterministic
+ * starter template and the form stays editable (headless-VPS safe).
+ * - Fill the form yourself and hit Create — the deterministic POST /api/skills
+ * path, no brain needed.
+ * Either way Create persists exactly what you see.
*/
import { useEffect, useState } from "react";
-import { X, Sparkles, Loader2, Plus, AlertTriangle } from "lucide-react";
+import { X, Sparkles, Loader2, Plus, AlertTriangle, Check } from "lucide-react";
import { Button } from "@/components/ui/button";
import { ScrollArea } from "@/components/ui/scroll-area";
import { useT } from "@/i18n";
import { useCreateSkill, useDraftSkill } from "@/hooks/useSkills";
+/**
+ * A body carries real instructions only if it has at least one non-heading,
+ * non-blank line. Mirrors the backend guard (`body_has_instructions`) so the
+ * form refuses a functionless skill before the round trip — the root cause of
+ * the empty "Hallo Hallo Hallo" skill.
+ */
+function bodyHasInstructions(body: string): boolean {
+ return body
+ .split("\n")
+ .some((line) => line.trim() !== "" && !line.trim().startsWith("#"));
+}
+
export function SkillCreateDialog({
open,
onClose,
@@ -39,6 +51,10 @@ export function SkillCreateDialog({
const [trigger, setTrigger] = useState("");
const [error, setError] = useState<string | null>(null);
const [aiNote, setAiNote] = useState<string | null>(null);
+ // True once the AI has written the whole skill into the fields — drives the
+ // "review then create" affordance (success banner + highlighted Create).
+ const [aiDrafted, setAiDrafted] = useState(false);
+ const [aiOk, setAiOk] = useState(false);
// Reset all state whenever the dialog (re)opens, and wire Escape-to-close.
useEffect(() => {
@@ -51,6 +67,8 @@ export function SkillCreateDialog({
setTrigger("");
setError(null);
setAiNote(null);
+ setAiDrafted(false);
+ setAiOk(false);
const onKey = (e: KeyboardEvent) => {
if (e.key === "Escape") onClose();
};
@@ -63,6 +81,7 @@ export function SkillCreateDialog({
const runDraft = async () => {
setError(null);
setAiNote(null);
+ setAiDrafted(false);
try {
const res = await draftSkill.mutateAsync({
intent,
@@ -77,9 +96,11 @@ export function SkillCreateDialog({
setBody(d.body ?? "");
const firstVoice = (d.triggers ?? []).find((tr) => tr.type === "voice");
if (firstVoice?.pattern) setTrigger(firstVoice.pattern);
+ setAiOk(res.brain_used);
+ setAiDrafted(true);
setAiNote(
res.brain_used
- ? t("skill_create_dialog.brain_used")
+ ? t("skill_create_dialog.ai_done_review")
: t("skill_create_dialog.brain_unavailable"),
);
} catch (e) {
@@ -93,12 +114,29 @@ export function SkillCreateDialog({
setError(t("skill_create_dialog.name_required"));
return;
}
+ // The intent describes what the skill should do. If the user typed it but
+ // never drafted/filled the instructions, fold it into the body instead of
+ // losing it — that was the empty-skill trap. Then require real instructions
+ // so a functionless skill can never be created.
+ let finalBody = body.trim();
+ if (!bodyHasInstructions(finalBody) && intent.trim()) {
+ finalBody = `## ${name.trim()}\n\n${intent.trim()}\n`;
+ }
+ if (!bodyHasInstructions(finalBody)) {
+ setError(t("skill_create_dialog.needs_instructions"));
+ return;
+ }
+ // Backfill the description from the intent so the brain can discover the
+ // skill (an empty description makes it effectively invisible in the
+ // AVAILABLE SKILLS listing).
+ const finalDescription =
+ description.trim() || intent.trim().slice(0, 200);
try {
const detail = await createSkill.mutateAsync({
name: name.trim(),
- description: description.trim(),
+ description: finalDescription,
category: category.trim() || "general",
- body: body.trim() ? body : `## ${name.trim()}\n`,
+ body: finalBody,
triggers: trigger.trim()
? [{ type: "voice", pattern: trigger.trim() }]
: [],
@@ -142,9 +180,9 @@ export function SkillCreateDialog({
<ScrollArea className="flex-1">
<div className="space-y-4 px-6 py-5">
- {/* Intent + AI draft */}
- <div>
- <label className="mb-1.5 block text-xs font-medium text-muted-foreground">
+ {/* Describe → let the AI write the whole skill */}
+ <div className="rounded-lg border border-primary/30 bg-primary/[0.04] p-4">
+ <label className="mb-1.5 block text-xs font-medium text-foreground">
{t("skill_create_dialog.intent_label")}
</label>
<textarea
@@ -154,30 +192,48 @@ export function SkillCreateDialog({
placeholder={t("skill_create_dialog.intent_placeholder")}
className="w-full resize-y rounded-md border border-border bg-background px-3 py-2 text-sm focus:border-primary focus:outline-none focus:ring-1 focus:ring-primary"
/>
- <div className="mt-2 flex items-center gap-2">
- <Button
- size="sm"
- variant="outline"
- onClick={() => void runDraft()}
- disabled={busy || intent.trim().length < 3}
- className="gap-1.5"
- >
- {draftSkill.isPending ? (
- <Loader2 className="h-3.5 w-3.5 animate-spin" />
- ) : (
- <Sparkles className="h-3.5 w-3.5" />
- )}
- {t("skill_create_dialog.draft_with_ai")}
- </Button>
- {aiNote && (
- <span className="text-[11px] text-muted-foreground">
- {aiNote}
- </span>
+ <Button
+ onClick={() => void runDraft()}
+ disabled={busy || intent.trim().length < 3}
+ className="mt-2.5 w-full gap-2"
+ >
+ {draftSkill.isPending ? (
+ <>
+ <Loader2 className="h-4 w-4 animate-spin" />
+ {t("skill_create_dialog.writing")}
+ </>
+ ) : (
+ <>
+ <Sparkles className="h-4 w-4" />
+ {t("skill_create_dialog.write_with_ai")}
+ </>
)}
- </div>
+ </Button>
</div>
- <div className="h-px bg-border" />
+ {/* AI result banner */}
+ {aiNote && (
+ <div
+ className={
+ aiOk
+ ? "flex items-start gap-2 rounded-md border border-emerald-500/40 bg-emerald-500/10 p-3 text-xs text-emerald-300"
+ : "flex items-start gap-2 rounded-md border border-amber-500/40 bg-amber-500/10 p-3 text-xs text-amber-300"
+ }
+ >
+ {aiOk ? (
+ <Check className="mt-0.5 h-3.5 w-3.5 flex-shrink-0" />
+ ) : (
+ <AlertTriangle className="mt-0.5 h-3.5 w-3.5 flex-shrink-0" />
+ )}
+ <span>{aiNote}</span>
+ </div>
+ )}
+
+ <div className="flex items-center gap-2 text-[11px] uppercase tracking-wider text-muted-foreground">
+ <div className="h-px flex-1 bg-border" />
+ {t("skill_create_dialog.or_review_edit")}
+ <div className="h-px flex-1 bg-border" />
+ </div>
{/* Name + Category */}
<div className="grid grid-cols-[1fr_180px] gap-3">
@@ -264,7 +320,15 @@ export function SkillCreateDialog({
<Button variant="ghost" onClick={onClose} disabled={busy}>
{t("common.close")}
</Button>
- <Button onClick={() => void runCreate()} disabled={busy} className="gap-1.5">
+ <Button
+ onClick={() => void runCreate()}
+ disabled={busy}
+ className={
+ aiDrafted
+ ? "gap-1.5 ring-2 ring-primary ring-offset-2 ring-offset-card"
+ : "gap-1.5"
+ }
+ >
{createSkill.isPending ? (
<Loader2 className="h-3.5 w-3.5 animate-spin" />
) : (
diff --git a/jarvis/ui/web/frontend/src/views/feedback/FeedbackView.test.tsx b/jarvis/ui/web/frontend/src/views/feedback/FeedbackView.test.tsx
new file mode 100644
index 0000000000..26069804ff
--- /dev/null
+++ b/jarvis/ui/web/frontend/src/views/feedback/FeedbackView.test.tsx
@@ -0,0 +1,57 @@
+/**
+ * Component tests for FeedbackView.
+ *
+ * The Feedback section is Discord-only: a single button forwards the user to the
+ * #bug-reports channel via {@link openExternalUrl}. There is no in-app form.
+ *
+ * Verifies:
+ * - The Discord call-to-action (heading + button) renders.
+ * - Clicking the button opens the Discord invite via the external-open bridge
+ * (openExternalUrl), NOT a bare anchor — this is what makes it work inside
+ * the desktop WebView2 shell, which drops target="_blank".
+ */
+import { afterEach, describe, expect, it, vi } from "vitest";
+import { cleanup, fireEvent, render, screen } from "@testing-library/react";
+
+import { FeedbackView } from "@/views/feedback/FeedbackView";
+import * as openExternal from "@/lib/openExternal";
+
+afterEach(() => {
+ cleanup();
+ vi.restoreAllMocks();
+});
+
+describe("FeedbackView", () => {
+ it("renders the Discord call-to-action with a forward button", () => {
+ render(<FeedbackView />);
+
+ // A button that forwards to Discord must be present.
+ const buttons = screen.getAllByRole("button");
+ expect(buttons.length).toBeGreaterThan(0);
+ // The CTA button text references opening Discord.
+ expect(screen.getByText(/open discord/i)).toBeTruthy();
+ });
+
+ it("does NOT render the old in-app form (Discord-only)", () => {
+ render(<FeedbackView />);
+ // No title/description inputs anymore.
+ expect(screen.queryByLabelText(/title/i)).toBeNull();
+ expect(screen.queryByLabelText(/description/i)).toBeNull();
+ expect(screen.queryByRole("button", { name: /submit/i })).toBeNull();
+ });
+
+ it("clicking the button opens the Discord invite via the external-open bridge", () => {
+ const openSpy = vi
+ .spyOn(openExternal, "openExternalUrl")
+ .mockResolvedValue(undefined);
+
+ render(<FeedbackView />);
+ fireEvent.click(screen.getByText(/open discord/i));
+
+ expect(openSpy).toHaveBeenCalledTimes(1);
+ // Must forward to a discord.gg invite link.
+ expect(openSpy).toHaveBeenCalledWith(
+ expect.stringContaining("discord.gg/"),
+ );
+ });
+});
diff --git a/jarvis/ui/web/frontend/src/views/feedback/FeedbackView.tsx b/jarvis/ui/web/frontend/src/views/feedback/FeedbackView.tsx
new file mode 100644
index 0000000000..ef4b58e327
--- /dev/null
+++ b/jarvis/ui/web/frontend/src/views/feedback/FeedbackView.tsx
@@ -0,0 +1,66 @@
+import { MessageSquareWarning } from "lucide-react";
+
+import { ViewHeader } from "@/views/ChatsView";
+import { useT } from "@/i18n";
+import { openExternalUrl } from "@/lib/openExternal";
+
+/**
+ * The Feedback section — bugs, ideas, and questions are reported exclusively in
+ * the project's Discord #bug-reports channel. The button forwards the user
+ * straight there via a public, never-expiring invite link.
+ *
+ * The button uses {@link openExternalUrl} rather than a bare
+ * `<a target="_blank">`, because the desktop shell (WebView2) silently drops
+ * `target="_blank"` / `window.open` — the new tab never appears. The bridge asks
+ * the backend to open the OS default browser instead (and falls back to
+ * `window.open` on a remote/VPS browser).
+ */
+
+// Public, never-expiring Discord invite that drops the visitor directly into the
+// #bug-reports channel of the PersonalJarvis server. An invite link is meant to
+// be shared, so it is safe to ship in the client.
+const DISCORD_INVITE_URL = "https://discord.gg/9QesfUrtq";
+
+/** The official Discord brand mark (inline so it renders without an asset). */
+function DiscordIcon({ className }: { className?: string }) {
+ return (
+ <svg viewBox="0 0 24 24" fill="currentColor" className={className} aria-hidden="true">
+ <path d="M20.317 4.369a19.79 19.79 0 0 0-4.885-1.515.074.074 0 0 0-.079.037c-.21.375-.444.864-.608 1.249a18.27 18.27 0 0 0-5.487 0 12.6 12.6 0 0 0-.617-1.25.077.077 0 0 0-.079-.036A19.736 19.736 0 0 0 3.677 4.37a.07.07 0 0 0-.032.027C.533 9.046-.32 13.58.099 18.057a.082.082 0 0 0 .031.057 19.9 19.9 0 0 0 5.993 3.03.078.078 0 0 0 .084-.028c.462-.63.874-1.295 1.226-1.994a.076.076 0 0 0-.041-.106 13.1 13.1 0 0 1-1.872-.892.077.077 0 0 1-.008-.128c.126-.094.252-.192.372-.291a.074.074 0 0 1 .077-.01c3.928 1.793 8.18 1.793 12.062 0a.074.074 0 0 1 .078.009c.12.099.246.198.373.292a.077.077 0 0 1-.006.127 12.3 12.3 0 0 1-1.873.892.077.077 0 0 0-.041.107c.36.698.772 1.362 1.225 1.993a.076.076 0 0 0 .084.028 19.84 19.84 0 0 0 6.002-3.03.077.077 0 0 0 .032-.054c.5-5.177-.838-9.674-3.549-13.66a.061.061 0 0 0-.031-.03zM8.02 15.331c-1.183 0-2.157-1.085-2.157-2.419 0-1.333.956-2.419 2.157-2.419 1.21 0 2.176 1.096 2.157 2.42 0 1.333-.956 2.418-2.157 2.418zm7.975 0c-1.183 0-2.157-1.085-2.157-2.419 0-1.333.955-2.419 2.157-2.419 1.21 0 2.176 1.096 2.157 2.42 0 1.333-.946 2.418-2.157 2.418z" />
+ </svg>
+ );
+}
+
+export function FeedbackView() {
+ const t = useT();
+
+ return (
+ <div className="flex h-full flex-col overflow-y-auto scrollbar-jarvis">
+ <ViewHeader
+ icon={<MessageSquareWarning className="h-4 w-4 text-primary" />}
+ title={t("nav.feedback")}
+ subtitle={t("feedback.subtitle")}
+ />
+
+ <div className="flex flex-1 items-center justify-center p-6">
+ <div className="w-full max-w-md rounded-2xl border border-[#5865F2]/40 bg-[#5865F2]/10 p-8 text-center">
+ <div className="mx-auto mb-5 flex h-16 w-16 items-center justify-center rounded-2xl bg-[#5865F2]/20">
+ <DiscordIcon className="h-9 w-9 text-[#5865F2]" />
+ </div>
+ <h2 className="mb-2 text-lg font-semibold text-foreground">
+ {t("feedback.discord_cta_title")}
+ </h2>
+ <p className="mb-6 text-sm text-muted-foreground">
+ {t("feedback.discord_cta_subtitle")}
+ </p>
+ <button
+ type="button"
+ onClick={() => void openExternalUrl(DISCORD_INVITE_URL)}
+ className="w-full rounded-lg bg-[#5865F2] px-4 py-3 text-sm font-semibold text-white transition hover:bg-[#4752c4]"
+ >
+ {t("feedback.discord_cta_button")}
+ </button>
+ </div>
+ </div>
+ </div>
+ );
+}
diff --git a/jarvis/ui/web/frontend/src/views/feedback/api.ts b/jarvis/ui/web/frontend/src/views/feedback/api.ts
new file mode 100644
index 0000000000..cf50d564da
--- /dev/null
+++ b/jarvis/ui/web/frontend/src/views/feedback/api.ts
@@ -0,0 +1,44 @@
+/**
+ * Typed client for the Feedback REST API (jarvis/ui/web/feedback_routes.py).
+ * Plain fetch — mirrors the pattern in views/socials/api.ts.
+ */
+
+export type FeedbackType = "bug" | "idea" | "question";
+
+export interface FeedbackPayload {
+ type: FeedbackType;
+ title: string;
+ description: string;
+ screenshot?: string | null;
+}
+
+export type FeedbackStatus = "sent" | "not_configured" | "discord_error" | "unreachable";
+
+export interface FeedbackResult {
+ ok: boolean;
+ status: FeedbackStatus;
+ detail: string;
+}
+
+const BASE = "/api/feedback";
+
+export async function submitFeedback(payload: FeedbackPayload): Promise<FeedbackResult> {
+ const res = await fetch(BASE, {
+ method: "POST",
+ headers: { "Content-Type": "application/json" },
+ // Prevent WebView2 from serving a cached response for a write endpoint.
+ cache: "no-store",
+ body: JSON.stringify(payload),
+ });
+ if (!res.ok) {
+ let detail = `${res.status} ${res.statusText}`;
+ try {
+ const body = (await res.json()) as { detail?: unknown };
+ if (typeof body.detail === "string") detail = body.detail;
+ } catch {
+ /* non-JSON body — keep the status line */
+ }
+ throw new Error(detail);
+ }
+ return (await res.json()) as FeedbackResult;
+}
diff --git a/jarvis/ui/web/frontend/src/views/profile/ledger.test.ts b/jarvis/ui/web/frontend/src/views/profile/ledger.test.ts
index 2e316cbc42..c794c5e015 100644
--- a/jarvis/ui/web/frontend/src/views/profile/ledger.test.ts
+++ b/jarvis/ui/web/frontend/src/views/profile/ledger.test.ts
@@ -9,14 +9,19 @@ import { describe, expect, it } from "vitest";
import {
ASK_PRIORITY,
+ BOOL_FIELD_KEYS,
CLUSTER_FIELD_KEYS,
CLUSTER_ORDER,
+ LIST_FIELD_KEYS,
TOTAL_FIELDS,
acquaintanceStage,
collectOpenQuestions,
countFilled,
displayAddress,
+ fieldKind,
+ isBoolField,
isEmptyValue,
+ isListField,
} from "@/views/profile/ledger";
// ----------------------------------------------------------------------
@@ -67,6 +72,50 @@ describe("ledger field vocabulary", () => {
});
});
+// ----------------------------------------------------------------------
+// Field kinds — drives the inline editor (text vs. toggle vs. chips)
+// ----------------------------------------------------------------------
+
+describe("field kinds", () => {
+ const allFields = CLUSTER_ORDER.flatMap((cid) => CLUSTER_FIELD_KEYS[cid]);
+
+ it("every list/bool field is part of the known vocabulary", () => {
+ for (const key of LIST_FIELD_KEYS) expect(allFields).toContain(key);
+ for (const key of BOOL_FIELD_KEYS) expect(allFields).toContain(key);
+ });
+
+ it("list and bool field sets do not overlap", () => {
+ for (const key of LIST_FIELD_KEYS) expect(BOOL_FIELD_KEYS.has(key)).toBe(false);
+ });
+
+ it("classifies the six list fields", () => {
+ for (const key of [
+ "languages",
+ "devices",
+ "humor_types",
+ "top_values",
+ "pet_peeves",
+ "motivations",
+ ]) {
+ expect(isListField(key)).toBe(true);
+ expect(fieldKind(key)).toBe("list");
+ }
+ });
+
+ it("classifies emoji_ok as a boolean", () => {
+ expect(isBoolField("emoji_ok")).toBe(true);
+ expect(fieldKind("emoji_ok")).toBe("bool");
+ });
+
+ it("classifies everything else as scalar", () => {
+ for (const key of ["name", "preferred_address", "timezone", "feedback_pref"]) {
+ expect(isListField(key)).toBe(false);
+ expect(isBoolField(key)).toBe(false);
+ expect(fieldKind(key)).toBe("scalar");
+ }
+ });
+});
+
// ----------------------------------------------------------------------
// isEmptyValue / countFilled
// ----------------------------------------------------------------------
diff --git a/jarvis/ui/web/frontend/src/views/profile/ledger.ts b/jarvis/ui/web/frontend/src/views/profile/ledger.ts
index f7aaff3246..7695e6b441 100644
--- a/jarvis/ui/web/frontend/src/views/profile/ledger.ts
+++ b/jarvis/ui/web/frontend/src/views/profile/ledger.ts
@@ -41,6 +41,38 @@ export const CLUSTER_ORDER: ClusterId[] = [
"relationship",
];
+// Field shapes — drive the inline editor. A list field is edited as removable
+// chips (append/remove one item); a bool field as a yes/no toggle; everything
+// else as a single text input. These MUST mirror _LIST_FIELDS / _BOOL_FIELDS in
+// jarvis/plugins/tool/profile_update.py (the backend rejects a mismatched
+// operation with 400) — the parity is pinned by test_profile_update.py.
+export const LIST_FIELD_KEYS: ReadonlySet<string> = new Set([
+ "languages",
+ "devices",
+ "humor_types",
+ "top_values",
+ "pet_peeves",
+ "motivations",
+]);
+
+export const BOOL_FIELD_KEYS: ReadonlySet<string> = new Set(["emoji_ok"]);
+
+export type FieldKind = "scalar" | "list" | "bool";
+
+export function isListField(field: string): boolean {
+ return LIST_FIELD_KEYS.has(field);
+}
+
+export function isBoolField(field: string): boolean {
+ return BOOL_FIELD_KEYS.has(field);
+}
+
+export function fieldKind(field: string): FieldKind {
+ if (LIST_FIELD_KEYS.has(field)) return "list";
+ if (BOOL_FIELD_KEYS.has(field)) return "bool";
+ return "scalar";
+}
+
export const TOTAL_FIELDS: number = CLUSTER_ORDER.reduce(
(acc, cid) => acc + CLUSTER_FIELD_KEYS[cid].length,
0,
diff --git a/jarvis/ui/web/frontend/src/views/settings/AppSettingsGroup.tsx b/jarvis/ui/web/frontend/src/views/settings/AppSettingsGroup.tsx
index 6e7557aa03..7c29ad16d8 100644
--- a/jarvis/ui/web/frontend/src/views/settings/AppSettingsGroup.tsx
+++ b/jarvis/ui/web/frontend/src/views/settings/AppSettingsGroup.tsx
@@ -32,7 +32,7 @@ export function AppSettingsGroup() {
}
/**
- * Label + description on the left, a toggle on the right (a dictation app layout). The
+ * Label + description on the left, a toggle on the right (grouped-card layout). The
* switch reflects the backend's authoritative ``enabled`` once GET resolves and
* is disabled while loading/saving or on an unsupported host.
*/
diff --git a/jarvis/ui/web/frontend/src/views/settings/JarvisApiGroup.tsx b/jarvis/ui/web/frontend/src/views/settings/JarvisApiGroup.tsx
index f786b19e47..67be8f3693 100644
--- a/jarvis/ui/web/frontend/src/views/settings/JarvisApiGroup.tsx
+++ b/jarvis/ui/web/frontend/src/views/settings/JarvisApiGroup.tsx
@@ -50,9 +50,9 @@ export function JarvisApiGroup() {
}
return (
- <div className="mt-8 space-y-4">
- <h3 className="font-display text-xs font-semibold uppercase tracking-wide text-muted-foreground">
- {t("settings_view.jarvis_api.title")}
+ <section className="space-y-3">
+ <h3 className="mb-3 inline-flex items-center gap-2 text-[10px] uppercase tracking-wider text-muted-foreground">
+ <KeyRound className="h-3.5 w-3.5" /> {t("settings_view.jarvis_api.title")}
</h3>
<div className="rounded-lg border border-border bg-card/60 p-4">
<div className="flex items-start gap-3">
@@ -106,6 +106,6 @@ export function JarvisApiGroup() {
</div>
</div>
</div>
- </div>
+ </section>
);
}
diff --git a/jarvis/ui/web/frontend/src/views/settings/LanguagesGroup.tsx b/jarvis/ui/web/frontend/src/views/settings/LanguagesGroup.tsx
index ce7caf12b8..97c93210a5 100644
--- a/jarvis/ui/web/frontend/src/views/settings/LanguagesGroup.tsx
+++ b/jarvis/ui/web/frontend/src/views/settings/LanguagesGroup.tsx
@@ -5,16 +5,21 @@ import {
useT,
useUiLanguage,
useReplyLanguage,
+ useSttLanguage,
setUiLanguage,
setReplyLanguage,
+ setSttLanguage,
hydrateReplyLanguage,
hydrateUiLanguage,
+ hydrateSttLanguage,
type UiLanguage,
type ReplyLanguage,
+ type SttLanguage,
} from "@/i18n";
const UI_OPTIONS: UiLanguage[] = ["en", "de", "es"];
const REPLY_OPTIONS: ReplyLanguage[] = ["auto", "en", "de", "es"];
+const STT_OPTIONS: SttLanguage[] = ["auto", "en", "de", "es"];
/**
* "Languages" group inside the Settings view — the interface-language and
@@ -27,12 +32,14 @@ export function LanguagesGroup() {
const t = useT();
const ui = useUiLanguage();
const reply = useReplyLanguage();
+ const stt = useSttLanguage();
- // Reflect the backend's persisted languages on open (both are backend-backed
+ // Reflect the backend's persisted languages on open (all are backend-backed
// now, so a voice/Control-API change is shown and the choice survives restart).
useEffect(() => {
void hydrateReplyLanguage();
void hydrateUiLanguage();
+ void hydrateSttLanguage();
}, []);
return (
@@ -56,6 +63,21 @@ export function LanguagesGroup() {
))}
</Section>
+ <Section
+ title={t("languages_view.stt_section")}
+ hint={t("languages_view.stt_hint")}
+ >
+ {STT_OPTIONS.map((code) => (
+ <LanguageRow
+ key={`stt-${code}`}
+ active={stt === code}
+ label={t(`languages_view.options.${code}.label`)}
+ description={t(`languages_view.stt_options.${code}`)}
+ onClick={() => setSttLanguage(code)}
+ />
+ ))}
+ </Section>
+
<Section
title={t("languages_view.reply_section")}
hint={t("languages_view.reply_hint")}
diff --git a/jarvis/ui/web/frontend/src/views/settings/OverlayTaskbarGroup.test.tsx b/jarvis/ui/web/frontend/src/views/settings/OverlayTaskbarGroup.test.tsx
index 6b12674a81..6f0ae059da 100644
--- a/jarvis/ui/web/frontend/src/views/settings/OverlayTaskbarGroup.test.tsx
+++ b/jarvis/ui/web/frontend/src/views/settings/OverlayTaskbarGroup.test.tsx
@@ -20,7 +20,7 @@ vi.mock("@/components/MascotGigi", () => ({
// The three data hooks resolve to safe, loaded defaults.
vi.mock("@/hooks/useOverlayStyle", () => ({
useOverlayStyle: () => ({
- config: { style: "whisper_bar", options: ["whisper_bar", "mascot", "none"] },
+ config: { style: "jarvis_bar", options: ["jarvis_bar", "mascot", "none"] },
loading: false,
error: null,
saveStyle: vi.fn(),
@@ -78,7 +78,7 @@ describe("OverlayTaskbarGroup", () => {
it("offers the three overlay-style options", () => {
render(<OverlayTaskbarGroup />);
expect(
- screen.getByText("settings_view.overlay_style.options.whisper_bar"),
+ screen.getByText("settings_view.overlay_style.options.jarvis_bar"),
).toBeDefined();
expect(
screen.getByText("settings_view.overlay_style.options.mascot"),
diff --git a/jarvis/ui/web/frontend/src/views/settings/OverlayTaskbarGroup.tsx b/jarvis/ui/web/frontend/src/views/settings/OverlayTaskbarGroup.tsx
index 37d31cd851..53c5951d41 100644
--- a/jarvis/ui/web/frontend/src/views/settings/OverlayTaskbarGroup.tsx
+++ b/jarvis/ui/web/frontend/src/views/settings/OverlayTaskbarGroup.tsx
@@ -49,7 +49,7 @@ export function OverlayTaskbarGroup() {
);
}
-/** A label + description on the left, a toggle on the right (a dictation app layout). */
+/** A label + description on the left, a toggle on the right (grouped-card layout). */
function ToggleRow({
icon: Icon,
title,
@@ -191,7 +191,7 @@ function OverlayStylePanel() {
const t = useT();
const { config, loading, error, saveStyle } = useOverlayStyle();
const pushToast = useEventStore((s) => s.pushToast);
- const [style, setStyle] = useState<OverlayStyle>("whisper_bar");
+ const [style, setStyle] = useState<OverlayStyle>("jarvis_bar");
const [saving, setSaving] = useState(false);
const [needsRestart, setNeedsRestart] = useState(false);
const [restarting, setRestarting] = useState(false);
@@ -235,7 +235,7 @@ function OverlayStylePanel() {
}
}
- const options = config?.options ?? (["whisper_bar", "mascot", "none"] as OverlayStyle[]);
+ const options = config?.options ?? (["jarvis_bar", "mascot", "none"] as OverlayStyle[]);
async function onPick(opt: OverlayStyle) {
if (saving) return;
diff --git a/jarvis/ui/web/frontend/src/views/settings/TeamProxyGroup.tsx b/jarvis/ui/web/frontend/src/views/settings/TeamProxyGroup.tsx
index 7574dd9913..d16989d45f 100644
--- a/jarvis/ui/web/frontend/src/views/settings/TeamProxyGroup.tsx
+++ b/jarvis/ui/web/frontend/src/views/settings/TeamProxyGroup.tsx
@@ -1,5 +1,5 @@
import { useEffect, useState } from "react";
-import { Check, Loader2 } from "lucide-react";
+import { Check, Loader2, Users } from "lucide-react";
import { cn } from "@/lib/utils";
import { useT } from "@/i18n";
@@ -110,9 +110,9 @@ export function TeamProxyGroup() {
};
return (
- <div className="mb-8 space-y-4">
- <h3 className="font-display text-xs font-semibold uppercase tracking-wide text-muted-foreground">
- {t("settings_view.team_proxy.title")}
+ <section className="space-y-4">
+ <h3 className="mb-3 inline-flex items-center gap-2 text-[10px] uppercase tracking-wider text-muted-foreground">
+ <Users className="h-3.5 w-3.5" /> {t("settings_view.team_proxy.title")}
</h3>
<p className="text-xs text-muted-foreground">
{t("settings_view.team_proxy.hint")}
@@ -202,6 +202,6 @@ export function TeamProxyGroup() {
</button>
{error && <span className="text-xs text-destructive">{error}</span>}
</div>
- </div>
+ </section>
);
}
diff --git a/jarvis/ui/web/frontend/src/views/sub-agents/DepartureBoard.tsx b/jarvis/ui/web/frontend/src/views/sub-agents/DepartureBoard.tsx
index 81ca25593f..ff98554347 100644
--- a/jarvis/ui/web/frontend/src/views/sub-agents/DepartureBoard.tsx
+++ b/jarvis/ui/web/frontend/src/views/sub-agents/DepartureBoard.tsx
@@ -56,12 +56,12 @@ function runtimeLabel(node: SubAgentNode, nowMs: number): string {
// User-facing role label only. The underlying engine, provider and model are
// deliberately NOT surfaced here: from the operator's perspective every node is
-// just one of Jarvis' own sub-agents. `kind` is an internal routing tag
-// (openclaw == top-level mission node, harness == the worker subprocess) and is
+// just one of Jarvis' own Jarvis-Agents. `kind` is an internal routing tag
+// (the top-level mission node vs. harness == the worker subprocess) and is
// never shown raw — see the subtitle below. The concrete "what is it doing"
// lives in the Task/Project column (`taskLabel`).
function displayAgentName(node: SubAgentNode): string {
- return node.kind === "harness" ? "Worker" : "Sub-Agent";
+ return node.kind === "harness" ? "Worker" : "Jarvis-Agent";
}
function taskLabel(node: SubAgentNode): string {
@@ -126,7 +126,7 @@ export function DepartureBoard({ agents = [], snapshotError = null }: Props) {
return (
<div className="flex h-full w-full flex-col overflow-hidden bg-[radial-gradient(circle_at_78%_0%,rgba(255,214,10,0.08),transparent_30%),linear-gradient(rgba(255,214,10,0.016)_1px,transparent_1px),linear-gradient(90deg,rgba(255,214,10,0.012)_1px,transparent_1px)] bg-[length:auto,72px_72px,72px_72px]">
<div className="grid grid-cols-2 gap-px border-b border-zinc-900 bg-zinc-900/70 md:grid-cols-5">
- <Metric label="Subagents" value={agents.length.toString()} icon={Bot} />
+ <Metric label="Jarvis-Agents" value={agents.length.toString()} icon={Bot} />
<Metric label="Active" value={activeCount.toString()} icon={Radio} tone="primary" />
<Metric label="Done" value={doneCount.toString()} icon={CheckCircle2} tone="success" />
<Metric label="Failed" value={failedCount.toString()} icon={Activity} tone={failedCount ? "danger" : "muted"} />
@@ -137,10 +137,10 @@ export function DepartureBoard({ agents = [], snapshotError = null }: Props) {
<div className="mb-3 flex items-center justify-between gap-4">
<div>
<div className="font-mono text-[11px] uppercase tracking-[0.32em] text-primary/80">
- Subagent operations board
+ Jarvis-Agent operations board
</div>
<div className="mt-1 text-xs text-zinc-500">
- Live table from the Sub-Agent backend registry and WebSocket events.
+ Live table from the Jarvis-Agent backend registry and WebSocket events.
</div>
</div>
<div className="flex items-center gap-2 rounded-full border border-primary/20 bg-primary/5 px-3 py-1.5 font-mono text-[10px] uppercase tracking-[0.22em] text-primary">
@@ -152,7 +152,7 @@ export function DepartureBoard({ agents = [], snapshotError = null }: Props) {
{snapshotError && (
<div className="mb-3 flex items-center gap-2 rounded-md border border-destructive/30 bg-destructive/10 px-3 py-2 text-xs text-destructive">
<CircleAlert className="h-4 w-4" />
- Sub-agent snapshot could not be loaded: {snapshotError}
+ Jarvis-Agent snapshot could not be loaded: {snapshotError}
</div>
)}
@@ -217,7 +217,7 @@ function BoardHeader() {
return (
<div className="sticky top-0 z-10 grid grid-cols-[44px_1.4fr_3fr_0.85fr_0.7fr_0.8fr_1.4fr] gap-4 border-b border-zinc-800 bg-zinc-950/95 px-4 py-3 font-mono text-[10px] uppercase tracking-[0.18em] text-zinc-500 backdrop-blur">
<span />
- <span>Subagent</span>
+ <span>Jarvis-Agent</span>
<span>Task / Project</span>
<span>Status</span>
<span>Tools</span>
@@ -233,10 +233,10 @@ function EmptyState() {
<div className="flex min-h-[420px] flex-col items-center justify-center px-8 text-center">
<Bot className="mb-4 h-8 w-8 text-zinc-600" />
<div className="font-display text-base font-semibold text-zinc-200">
- No subagents are running right now.
+ No Jarvis-Agents are running right now.
</div>
<p className="mt-2 max-w-lg text-sm text-zinc-500">
- When {assistantName} starts a real subagent, it will appear here with its task, status,
+ When {assistantName} starts a real Jarvis-Agent, it will appear here with its task, status,
tool calls, runtime and result.
</p>
</div>
@@ -277,7 +277,7 @@ function AgentRow({
<span className="min-w-0">
<span className="block truncate text-zinc-100">{displayAgentName(agent)}</span>
<span className="block truncate text-[10px] uppercase tracking-[0.16em] text-zinc-600">
- {agent.kind === "harness" ? "worker" : "sub-agent"}
+ {agent.kind === "harness" ? "worker" : "jarvis-agent"}
</span>
</span>
<span className="truncate text-zinc-400" title={taskLabel(agent)}>
@@ -315,7 +315,7 @@ function AgentRow({
<div className="min-w-0 rounded-md border border-zinc-800/70 bg-black/30">
<div className="border-b border-zinc-900 px-3 py-2 font-mono text-[10px] uppercase tracking-[0.18em] text-zinc-500">
- Subagent details
+ Jarvis-Agent details
</div>
<div className="space-y-2 px-3 py-3 font-mono text-xs text-zinc-500">
<div className="line-clamp-4">{taskLabel(agent)}</div>
diff --git a/jarvis/ui/web/frontend/src/views/tasks/TaskCreateDialog.tsx b/jarvis/ui/web/frontend/src/views/tasks/TaskCreateDialog.tsx
index 3b66e84a09..08dac2830b 100644
--- a/jarvis/ui/web/frontend/src/views/tasks/TaskCreateDialog.tsx
+++ b/jarvis/ui/web/frontend/src/views/tasks/TaskCreateDialog.tsx
@@ -9,16 +9,25 @@ import {
Plug,
Sparkles,
AlertTriangle,
+ CalendarDays,
+ Zap,
+ MonitorPlay,
+ Bot,
+ Bell,
} from "lucide-react";
import { Button } from "@/components/ui/button";
import { Switch } from "@/components/ui/switch";
import { cn } from "@/lib/utils";
-import { useT } from "@/i18n";
+import { useT, useUiLanguage } from "@/i18n";
import {
buildTaskSpec,
+ defaultAtTimeLocal,
+ formatWatermarkDate,
type ModelTier,
type ScopeValue,
type TaskDraft,
+ type ThenKind,
+ type WhenKey,
} from "./taskSpec";
interface PluginItem {
@@ -34,7 +43,10 @@ interface PluginsResponse {
}
async function fetchPlugins(): Promise<PluginsResponse> {
- const res = await fetch("/api/marketplace/plugins");
+ // `cache: "no-store"` bypasses the embedded WebView2 HTTP cache so the
+ // desktop app never shows a stale connection state for plugins (see the
+ // matching note in PluginsView.fetchCatalog).
+ const res = await fetch("/api/marketplace/plugins", { cache: "no-store" });
if (!res.ok) throw new Error(`HTTP ${res.status}`);
return res.json();
}
@@ -108,15 +120,23 @@ const inputCls =
export function TaskCreateDialog({ onClose }: { onClose: () => void }) {
const t = useT();
+ const uiLang = useUiLanguage();
const qc = useQueryClient();
const [title, setTitle] = useState("");
const [prompt, setPrompt] = useState("");
+ const [triggerMode, setTriggerMode] = useState<"schedule" | "event">("schedule");
+ const [whenKey, setWhenKey] = useState<WhenKey>("mission_succeeded");
+ const [thenKind, setThenKind] = useState<ThenKind>("computer_use");
+ const [cuPrompt, setCuPrompt] = useState("");
+ const [announceText, setAnnounceText] = useState("");
const [scheduleMode, setScheduleMode] = useState<"once" | "recurring">("recurring");
const [onceMode, setOnceMode] = useState<"delay" | "at_time">("at_time");
const [delayValue, setDelayValue] = useState(1);
const [delayUnit, setDelayUnit] = useState<"minutes" | "hours">("hours");
- const [atTimeLocal, setAtTimeLocal] = useState("");
+ // Pre-fill with a real, editable value (now + 1h) so the native picker never
+ // shows the browser's raw, locale-ugly "TT.mm.jjjj --:--" empty placeholder.
+ const [atTimeLocal, setAtTimeLocal] = useState(() => defaultAtTimeLocal());
const [recurringMode, setRecurringMode] = useState<"hourly" | "daily" | "custom">("daily");
const [dailyTime, setDailyTime] = useState("07:00");
const [customValue, setCustomValue] = useState(30);
@@ -139,6 +159,7 @@ export function TaskCreateDialog({ onClose }: { onClose: () => void }) {
() => ({
title,
prompt,
+ triggerMode,
scheduleMode,
onceMode,
delaySeconds: delayValue * (delayUnit === "hours" ? 3600 : 60),
@@ -148,9 +169,14 @@ export function TaskCreateDialog({ onClose }: { onClose: () => void }) {
dailyTime,
modelTier,
grants: Object.entries(grants).map(([plugin_id, scope]) => ({ plugin_id, scope })),
+ whenKey,
+ thenKind,
+ cuPrompt,
+ announceText,
}),
- [title, prompt, scheduleMode, onceMode, delayValue, delayUnit, atTimeLocal,
- recurringMode, customValue, customUnit, dailyTime, modelTier, grants],
+ [title, prompt, triggerMode, scheduleMode, onceMode, delayValue, delayUnit, atTimeLocal,
+ recurringMode, customValue, customUnit, dailyTime, modelTier, grants,
+ whenKey, thenKind, cuPrompt, announceText],
);
const createMut = useMutation({
@@ -161,10 +187,20 @@ export function TaskCreateDialog({ onClose }: { onClose: () => void }) {
},
});
+ // The agent prompt + plugins + model picker only apply to an agentic action:
+ // every time-based task, and an event rule whose "then" is an agent turn.
+ const showAgentConfig = triggerMode === "schedule" || thenKind === "agent";
+
const valid =
title.trim().length > 0 &&
- prompt.trim().length > 0 &&
- (scheduleMode !== "once" || onceMode !== "at_time" || atTimeLocal !== "");
+ (triggerMode === "event"
+ ? thenKind === "computer_use"
+ ? cuPrompt.trim().length > 0
+ : thenKind === "agent"
+ ? prompt.trim().length > 0
+ : announceText.trim().length > 0 // notify
+ : prompt.trim().length > 0 &&
+ (scheduleMode !== "once" || onceMode !== "at_time" || atTimeLocal !== ""));
const hasElevatedGrant = Object.values(grants).some(
(s) => s === "write" || s === "full",
@@ -227,17 +263,94 @@ export function TaskCreateDialog({ onClose }: { onClose: () => void }) {
/>
</Field>
- <Field label={t("tasks_view.create.prompt_label")}>
- <textarea
- className={cn(inputCls, "min-h-[96px] resize-y leading-relaxed")}
- value={prompt}
- onChange={(e) => setPrompt(e.target.value)}
- placeholder={t("tasks_view.create.prompt_placeholder")}
- maxLength={16384}
+ {/* Trigger mode: a time-based schedule vs. an event-driven
+ "When-Then" rule (e.g. when a mission finishes → do X). */}
+ <div className="flex items-center justify-between">
+ <span className="text-[11px] font-medium uppercase tracking-wider text-muted-foreground">
+ {t("tasks_view.create.trigger_mode_label")}
+ </span>
+ <Segmented
+ value={triggerMode}
+ onChange={setTriggerMode}
+ options={[
+ { id: "schedule", label: t("tasks_view.create.mode_schedule"), icon: CalendarDays },
+ { id: "event", label: t("tasks_view.create.mode_event"), icon: Zap },
+ ]}
/>
- </Field>
+ </div>
+
+ {/* When-Then rule: curated "when" event + "then" action */}
+ {triggerMode === "event" && (
+ <div className="space-y-4 rounded-xl border border-border/70 bg-background/30 p-4">
+ <div className="space-y-2">
+ <span className="text-[11px] font-medium uppercase tracking-wider text-muted-foreground">
+ {t("tasks_view.create.when_label")}
+ </span>
+ <div className="flex flex-wrap gap-1.5">
+ <Segmented
+ size="sm"
+ value={whenKey}
+ onChange={setWhenKey}
+ options={[
+ { id: "mission_succeeded", label: t("tasks_view.create.when_mission_succeeded") },
+ { id: "mission_failed", label: t("tasks_view.create.when_mission_failed") },
+ { id: "mission_cancelled", label: t("tasks_view.create.when_mission_cancelled") },
+ ]}
+ />
+ </div>
+ </div>
+
+ <div className="space-y-2">
+ <span className="text-[11px] font-medium uppercase tracking-wider text-muted-foreground">
+ {t("tasks_view.create.then_label")}
+ </span>
+ <Segmented
+ size="sm"
+ value={thenKind}
+ onChange={setThenKind}
+ options={[
+ { id: "computer_use", label: t("tasks_view.create.then_computer_use"), icon: MonitorPlay },
+ { id: "agent", label: t("tasks_view.create.then_agent"), icon: Bot },
+ { id: "notify", label: t("tasks_view.create.then_notify"), icon: Bell },
+ ]}
+ />
+ </div>
+
+ {thenKind === "computer_use" && (
+ <Field label={t("tasks_view.create.cu_goal_label")}>
+ <textarea
+ className={cn(inputCls, "min-h-[72px] resize-y leading-relaxed")}
+ value={cuPrompt}
+ onChange={(e) => setCuPrompt(e.target.value)}
+ placeholder={t("tasks_view.create.cu_goal_placeholder")}
+ maxLength={16384}
+ />
+ </Field>
+ )}
+
+ <Field
+ label={
+ thenKind === "notify"
+ ? t("tasks_view.create.notify_text_label")
+ : t("tasks_view.create.announce_label")
+ }
+ >
+ <input
+ className={inputCls}
+ value={announceText}
+ onChange={(e) => setAnnounceText(e.target.value)}
+ placeholder={t("tasks_view.create.announce_placeholder")}
+ maxLength={2048}
+ />
+ </Field>
+ <p className="text-[11px] leading-relaxed text-muted-foreground">
+ {t("tasks_view.create.when_then_hint")}
+ </p>
+ </div>
+ )}
{/* Schedule */}
+ {triggerMode === "schedule" && (
<div className="space-y-3 rounded-xl border border-border/70 bg-background/30 p-4">
<div className="flex items-center justify-between">
<span className="text-[11px] font-medium uppercase tracking-wider text-muted-foreground">
@@ -265,12 +378,27 @@ export function TaskCreateDialog({ onClose }: { onClose: () => void }) {
]}
/>
{onceMode === "at_time" ? (
- <input
- type="datetime-local"
- className={inputCls}
- value={atTimeLocal}
- onChange={(e) => setAtTimeLocal(e.target.value)}
- />
+ <div className="relative overflow-hidden rounded-lg">
+ {/* The selected date, written out long-form and very faint,
+ sitting behind the picker — "the current date, but a
+ little in the background". It tracks whatever value the
+ picker holds and is purely decorative (no pointer
+ events), so the native control stays fully usable. */}
+ <div
+ aria-hidden
+ className="pointer-events-none absolute inset-y-0 left-3 right-11 flex items-center justify-end"
+ >
+ <span className="truncate text-lg font-semibold leading-none text-foreground/[0.06]">
+ {formatWatermarkDate(atTimeLocal, uiLang)}
+ </span>
+ </div>
+ <input
+ type="datetime-local"
+ className={cn(inputCls, "relative bg-transparent [color-scheme:dark]")}
+ value={atTimeLocal}
+ onChange={(e) => setAtTimeLocal(e.target.value)}
+ />
+ </div>
) : (
<div className="flex items-center gap-2">
<span className="text-xs text-muted-foreground">
@@ -346,7 +474,22 @@ export function TaskCreateDialog({ onClose }: { onClose: () => void }) {
</div>
)}
</div>
+ )}
+ {showAgentConfig && (
+ <Field label={t("tasks_view.create.prompt_label")}>
+ <textarea
+ className={cn(inputCls, "min-h-[96px] resize-y leading-relaxed")}
+ value={prompt}
+ onChange={(e) => setPrompt(e.target.value)}
+ placeholder={t("tasks_view.create.prompt_placeholder")}
+ maxLength={16384}
+ />
+ </Field>
+ )}
+
+ {showAgentConfig && (
+ <>
{/* Plugins */}
<div className="space-y-2.5 rounded-xl border border-border/70 bg-background/30 p-4">
<div className="flex items-center gap-2">
@@ -417,6 +560,8 @@ export function TaskCreateDialog({ onClose }: { onClose: () => void }) {
}))}
/>
</div>
+ </>
+ )}
</div>
</div>
diff --git a/jarvis/ui/web/frontend/src/views/tasks/taskSpec.test.ts b/jarvis/ui/web/frontend/src/views/tasks/taskSpec.test.ts
index 7901b5bbb4..07a7a36e3f 100644
--- a/jarvis/ui/web/frontend/src/views/tasks/taskSpec.test.ts
+++ b/jarvis/ui/web/frontend/src/views/tasks/taskSpec.test.ts
@@ -1,6 +1,8 @@
import { describe, it, expect } from "vitest";
import {
buildTaskSpec,
+ defaultAtTimeLocal,
+ formatWatermarkDate,
nextDailyOccurrence,
type TaskDraft,
} from "./taskSpec";
@@ -9,6 +11,7 @@ function baseDraft(over: Partial<TaskDraft> = {}): TaskDraft {
return {
title: "My Task",
prompt: "Do the thing.",
+ triggerMode: "schedule",
scheduleMode: "once",
onceMode: "delay",
delaySeconds: 3600,
@@ -18,6 +21,10 @@ function baseDraft(over: Partial<TaskDraft> = {}): TaskDraft {
dailyTime: "07:00",
modelTier: "auto",
grants: [],
+ whenKey: "mission_succeeded",
+ thenKind: "computer_use",
+ cuPrompt: "",
+ announceText: "",
...over,
};
}
@@ -71,10 +78,12 @@ describe("buildTaskSpec — agent action mapping", () => {
],
}),
);
- expect(spec.action.kind).toBe("agent");
- expect(spec.action.prompt).toBe("Summarize my inbox.");
- expect(spec.action.model_tier).toBe("deep");
- expect(spec.action.plugin_grants).toEqual([
+ const action = spec.action;
+ expect(action.kind).toBe("agent");
+ if (action.kind !== "agent") return; // narrow the union
+ expect(action.prompt).toBe("Summarize my inbox.");
+ expect(action.model_tier).toBe("deep");
+ expect(action.plugin_grants).toEqual([
{ plugin_id: "gmail", scope: "read" },
{ plugin_id: "buffer", scope: "write" },
]);
@@ -86,6 +95,103 @@ describe("buildTaskSpec — agent action mapping", () => {
});
});
+describe("buildTaskSpec — When-Then event mapping", () => {
+ it("maps a 'mission succeeds → Computer-Use' rule", () => {
+ const spec = buildTaskSpec(
+ baseDraft({
+ triggerMode: "event",
+ whenKey: "mission_succeeded",
+ thenKind: "computer_use",
+ cuPrompt: "Open {result_uri} in the browser",
+ announceText: "Your mission is ready.",
+ }),
+ );
+ expect(spec.trigger).toEqual({
+ type: "on_event",
+ event_name: "MissionCompleted",
+ filter_expr: "status == 'approved'",
+ max_firings: null,
+ });
+ const action = spec.action;
+ expect(action.kind).toBe("harness_dispatch");
+ if (action.kind !== "harness_dispatch") return;
+ expect(action.harness).toBe("screenshot");
+ expect(action.prompt).toBe("Open {result_uri} in the browser");
+ expect(action.allow_computer_use).toBe(true);
+ // CU/agent actions carry the announcement as a separate readback field.
+ expect(spec.announce_on_success).toBe("Your mission is ready.");
+ });
+
+ it("maps the failed/cancelled when-keys to the right filter", () => {
+ const failed = buildTaskSpec(baseDraft({ triggerMode: "event", whenKey: "mission_failed" }));
+ expect((failed.trigger as { filter_expr: string }).filter_expr).toBe("status == 'failed'");
+ const cancelled = buildTaskSpec(
+ baseDraft({ triggerMode: "event", whenKey: "mission_cancelled" }),
+ );
+ expect((cancelled.trigger as { filter_expr: string }).filter_expr).toBe(
+ "status == 'cancelled'",
+ );
+ });
+
+ it("a 'just notify' rule is a speak action with no separate announce field", () => {
+ const spec = buildTaskSpec(
+ baseDraft({
+ triggerMode: "event",
+ thenKind: "notify",
+ announceText: "Mission done.",
+ }),
+ );
+ const action = spec.action;
+ expect(action.kind).toBe("speak");
+ if (action.kind !== "speak") return;
+ expect(action.text).toBe("Mission done.");
+ expect(spec.announce_on_success).toBeUndefined();
+ });
+});
+
+describe("defaultAtTimeLocal", () => {
+ it("returns a local datetime-local string one hour ahead, rounded up to the next quarter hour", () => {
+ // 13:07 -> +1h = 14:07 -> round up to 14:15
+ expect(defaultAtTimeLocal(new Date(2026, 5, 24, 13, 7, 0))).toBe("2026-06-24T14:15");
+ });
+
+ it("rolls the hour over when rounding crosses the top of the hour", () => {
+ // 13:52 -> +1h = 14:52 -> round up to 15:00
+ expect(defaultAtTimeLocal(new Date(2026, 5, 24, 13, 52, 0))).toBe("2026-06-24T15:00");
+ });
+
+ it("leaves a value already on a quarter hour unchanged", () => {
+ // 13:00 -> +1h = 14:00 -> already aligned
+ expect(defaultAtTimeLocal(new Date(2026, 5, 24, 13, 0, 0))).toBe("2026-06-24T14:00");
+ });
+
+ it("always emits a full, non-empty datetime-local shape (never the native placeholder)", () => {
+ const out = defaultAtTimeLocal(new Date(2026, 5, 24, 13, 7));
+ expect(out).toMatch(/^\d{4}-\d{2}-\d{2}T\d{2}:\d{2}$/);
+ expect(out.length).toBe(16);
+ });
+});
+
+describe("formatWatermarkDate", () => {
+ it("writes the selected date long-form in English", () => {
+ const out = formatWatermarkDate("2026-06-24T15:30", "en");
+ expect(out).toContain("June");
+ expect(out).toContain("24");
+ });
+
+ it("localizes the same date to German", () => {
+ const out = formatWatermarkDate("2026-06-24T15:30", "de");
+ expect(out).toContain("Juni");
+ expect(out).toContain("24");
+ });
+
+ it("falls back to `now` for an empty / unparseable field value", () => {
+ const out = formatWatermarkDate("", "en", new Date(2026, 5, 24, 9, 0));
+ expect(out).toContain("June");
+ expect(out).toContain("24");
+ });
+});
+
describe("nextDailyOccurrence", () => {
it("returns today's time when it is still in the future", () => {
const now = new Date("2026-06-17T05:00:00");
diff --git a/jarvis/ui/web/frontend/src/views/tasks/taskSpec.ts b/jarvis/ui/web/frontend/src/views/tasks/taskSpec.ts
index 180b7ee7fa..5d7f628975 100644
--- a/jarvis/ui/web/frontend/src/views/tasks/taskSpec.ts
+++ b/jarvis/ui/web/frontend/src/views/tasks/taskSpec.ts
@@ -14,9 +14,21 @@ export interface DraftPluginGrant {
scope: ScopeValue;
}
+/** Curated "when" events for the When-Then builder. Each maps onto one bus
+ * event class plus a filter_expr — the user never sees raw event names. */
+export type WhenKey =
+ | "mission_succeeded"
+ | "mission_failed"
+ | "mission_cancelled";
+
+/** The "then" action a When-Then rule runs. */
+export type ThenKind = "computer_use" | "agent" | "notify";
+
export interface TaskDraft {
title: string;
prompt: string;
+ // Top-level: a time-based schedule vs. an event-driven When-Then rule.
+ triggerMode: "schedule" | "event";
scheduleMode: "once" | "recurring";
onceMode: "delay" | "at_time";
delaySeconds: number;
@@ -26,12 +38,23 @@ export interface TaskDraft {
dailyTime: string; // "HH:MM"
modelTier: ModelTier;
grants: DraftPluginGrant[];
+ // When-Then fields (only meaningful when triggerMode === "event").
+ whenKey: WhenKey;
+ thenKind: ThenKind;
+ cuPrompt: string; // Computer-Use goal, supports {result_uri} placeholders
+ announceText: string; // spoken confirmation after the action finishes
}
export type TaskTrigger =
| { type: "after_delay"; delay_seconds: number }
| { type: "at_time"; iso_timestamp: string }
- | { type: "every"; interval_seconds: number; start_at?: string };
+ | { type: "every"; interval_seconds: number; start_at?: string }
+ | {
+ type: "on_event";
+ event_name: string;
+ filter_expr?: string | null;
+ max_firings?: number | null;
+ };
export interface AgentActionPayload {
kind: "agent";
@@ -40,10 +63,89 @@ export interface AgentActionPayload {
model_tier: ModelTier;
}
+export interface HarnessDispatchActionPayload {
+ kind: "harness_dispatch";
+ harness: string;
+ prompt: string;
+ allow_computer_use: boolean;
+}
+
+export interface SpeakActionPayload {
+ kind: "speak";
+ text: string;
+}
+
+export type TaskActionPayload =
+ | AgentActionPayload
+ | HarnessDispatchActionPayload
+ | SpeakActionPayload;
+
export interface TaskSpecPayload {
title: string;
trigger: TaskTrigger;
- action: AgentActionPayload;
+ action: TaskActionPayload;
+ announce_on_success?: string;
+ announce_on_failure?: string;
+}
+
+/** Curated "when" → (event class, filter) mapping. The single place that knows
+ * a mission outcome is a `MissionCompleted` filtered by `status`. */
+export const WHEN_FILTERS: Record<WhenKey, string> = {
+ mission_succeeded: "status == 'approved'",
+ mission_failed: "status == 'failed'",
+ mission_cancelled: "status == 'cancelled'",
+};
+
+/** The CU harness name a Computer-Use "then" action dispatches to. */
+export const CU_HARNESS = "screenshot";
+
+function pad2(n: number): string {
+ return String(n).padStart(2, "0");
+}
+
+/**
+ * A sensible default for the "at date/time" picker, formatted for an
+ * `<input type="datetime-local">` (local wall-clock "YYYY-MM-DDTHH:mm", never
+ * UTC): one hour from now, rounded up to the next quarter hour.
+ *
+ * Pre-filling the field is what kills the browser's raw, locale-ugly empty
+ * placeholder ("TT.mm.jjjj --:--" on a German system) — a freshly opened
+ * picker now shows a real, editable value instead of dead grey hint text.
+ */
+export function defaultAtTimeLocal(now: Date = new Date()): string {
+ const d = new Date(now.getTime() + 60 * 60 * 1000);
+ // setMinutes carries overflow: 60 rolls into the next hour cleanly.
+ d.setMinutes(Math.ceil(d.getMinutes() / 15) * 15, 0, 0);
+ return (
+ `${d.getFullYear()}-${pad2(d.getMonth() + 1)}-${pad2(d.getDate())}` +
+ `T${pad2(d.getHours())}:${pad2(d.getMinutes())}`
+ );
+}
+
+/**
+ * The selected date written out long-form for the dialog's faint background
+ * watermark — e.g. "Wednesday, 24 June" / "Mittwoch, 24. Juni". Locale-aware,
+ * date only (the time already shows inside the input, so the watermark stays
+ * calm). Falls back to `now` for an unparseable field value, and to the "en"
+ * locale if the requested one is unavailable in the runtime's ICU data.
+ */
+export function formatWatermarkDate(
+ atTimeLocal: string,
+ locale: string,
+ now: Date = new Date(),
+): string {
+ const parsed = atTimeLocal ? new Date(atTimeLocal) : now;
+ const d = Number.isNaN(parsed.getTime()) ? now : parsed;
+ const opts: Intl.DateTimeFormatOptions = {
+ weekday: "long",
+ day: "numeric",
+ month: "long",
+ };
+ try {
+ return new Intl.DateTimeFormat(locale, opts).format(d);
+ } catch {
+ return new Intl.DateTimeFormat("en", opts).format(d);
+ }
}
/** Next absolute occurrence of an "HH:MM" wall-clock time, as an ISO string. */
@@ -57,7 +159,22 @@ export function nextDailyOccurrence(timeHHMM: string, now: Date): string {
return d.toISOString();
}
+/** A When-Then event trigger: a `MissionCompleted` filtered by the curated
+ * `whenKey`. A standing rule (max_firings null) — it fires for every matching
+ * mission until the user deletes it. */
+export function buildEventTrigger(draft: TaskDraft): TaskTrigger {
+ return {
+ type: "on_event",
+ event_name: "MissionCompleted",
+ filter_expr: WHEN_FILTERS[draft.whenKey] ?? null,
+ max_firings: null,
+ };
+}
+
export function buildTrigger(draft: TaskDraft, now: Date = new Date()): TaskTrigger {
+ if (draft.triggerMode === "event") {
+ return buildEventTrigger(draft);
+ }
if (draft.scheduleMode === "once") {
if (draft.onceMode === "at_time") {
return { type: "at_time", iso_timestamp: new Date(draft.atTimeLocal).toISOString() };
@@ -78,7 +195,45 @@ export function buildTrigger(draft: TaskDraft, now: Date = new Date()): TaskTrig
return { type: "every", interval_seconds: draft.customIntervalSeconds };
}
+/** The "then" action for a When-Then rule, derived from the chosen `thenKind`.
+ * Computer-Use dispatches to the CU harness; "agent" runs a brain turn; "notify"
+ * speaks the announcement as its sole action. */
+export function buildEventAction(draft: TaskDraft): TaskActionPayload {
+ if (draft.thenKind === "computer_use") {
+ return {
+ kind: "harness_dispatch",
+ harness: CU_HARNESS,
+ prompt: draft.cuPrompt.trim() || "Open the mission result in the browser.",
+ allow_computer_use: true,
+ };
+ }
+ if (draft.thenKind === "agent") {
+ return {
+ kind: "agent",
+ prompt: draft.prompt.trim(),
+ plugin_grants: draft.grants,
+ model_tier: draft.modelTier,
+ };
+ }
+ // "notify" — the spoken confirmation IS the action.
+ return { kind: "speak", text: draft.announceText.trim() || "Done." };
+}
+
export function buildTaskSpec(draft: TaskDraft, now: Date = new Date()): TaskSpecPayload {
+ if (draft.triggerMode === "event") {
+ const spec: TaskSpecPayload = {
+ title: draft.title.trim(),
+ trigger: buildTrigger(draft, now),
+ action: buildEventAction(draft),
+ };
+ // For CU/agent actions the announcement is a separate post-action readback;
+ // for "notify" the speak action already says it, so no announce field.
+ const announce = draft.announceText.trim();
+ if (draft.thenKind !== "notify" && announce) {
+ spec.announce_on_success = announce;
+ }
+ return spec;
+ }
return {
title: draft.title.trim(),
trigger: buildTrigger(draft, now),
diff --git a/jarvis/ui/web/frontend/vite.config.js b/jarvis/ui/web/frontend/vite.config.js
index 515108e993..f33e6943b2 100644
--- a/jarvis/ui/web/frontend/vite.config.js
+++ b/jarvis/ui/web/frontend/vite.config.js
@@ -26,7 +26,12 @@ export default defineConfig({
build: {
outDir: "../dist",
emptyOutDir: true,
- sourcemap: true,
+ // No source maps in production builds. They bloat the bundle, expose the
+ // full original source, and bake the absolute build path (e.g. a personal
+ // C:\Users\... home dir) into the .map files — none of which belongs in the
+ // prebuilt dist shipped to the public repo. The Vite dev server keeps its
+ // own inline maps, so local debugging is unaffected.
+ sourcemap: false,
},
test: {
environment: "jsdom",
diff --git a/jarvis/ui/web/frontend/vite.config.ts b/jarvis/ui/web/frontend/vite.config.ts
index 6151ea3398..fc079de05b 100644
--- a/jarvis/ui/web/frontend/vite.config.ts
+++ b/jarvis/ui/web/frontend/vite.config.ts
@@ -27,7 +27,12 @@ export default defineConfig({
build: {
outDir: "../dist",
emptyOutDir: true,
- sourcemap: true,
+ // No source maps in production builds. They bloat the bundle, expose the
+ // full original source, and bake the absolute build path (e.g. a personal
+ // C:\Users\... home dir) into the .map files — none of which belongs in the
+ // prebuilt dist shipped to the public repo. The Vite dev server keeps its
+ // own inline maps, so local debugging is unaffected.
+ sourcemap: false,
},
test: {
environment: "jsdom",
diff --git a/jarvis/ui/web/launcher.py b/jarvis/ui/web/launcher.py
index 63a9ea2572..0a5eda2cd9 100644
--- a/jarvis/ui/web/launcher.py
+++ b/jarvis/ui/web/launcher.py
@@ -151,6 +151,17 @@ def _acquire_primary_lock_for_headless(
return lock
+def _claim_headless_primary_lock(args, *, lock_path=None, meta_path=None):
+ """Claim the headless primary lock unless this is an explicit no-lock run."""
+ if bool(getattr(args, "no_lock", False)):
+ os.environ["JARVIS_PRIMARY_INSTANCE"] = "0"
+ return None
+ return _acquire_primary_lock_for_headless(
+ lock_path=lock_path,
+ meta_path=meta_path,
+ )
+
+
def _direct_filelock_fallback(lock_path=None):
"""Acquire the single-instance lock without importing ``desktop_app``.
@@ -209,6 +220,32 @@ def _fast_admin_port() -> int:
return _DEFAULT_ADMIN_PORT
+def _fast_auth_token_env() -> str:
+ """Read ``[ui].auth_token_env`` raw (no ``load_config``) so the fast-boot
+ desktop path can generate + set the session token BEFORE the heavy config /
+ DesktopApp imports. Falls back to the packaged default ``JARVIS_UI_TOKEN``."""
+ import contextlib
+
+ with contextlib.suppress(Exception):
+ import tomllib
+
+ override = os.environ.get("JARVIS_CONFIG")
+ if override:
+ path = override
+ else:
+ repo_root = os.path.dirname(
+ os.path.dirname(os.path.dirname(os.path.dirname(os.path.abspath(__file__))))
+ )
+ path = os.path.join(repo_root, "jarvis.toml")
+ if os.path.exists(path):
+ with open(path, "rb") as fh:
+ data = tomllib.load(fh)
+ name = data.get("ui", {}).get("auth_token_env")
+ if isinstance(name, str) and name:
+ return name
+ return "JARVIS_UI_TOKEN"
+
+
async def _run_headless(args) -> int:
"""Headless **fast boot** (the "serve first, init behind" contract).
@@ -292,7 +329,18 @@ async def _run_headless(args) -> int:
# 1013 = "try again later" → clients reconnect once the app is up.
await send({"type": "websocket.close", "code": 1013})
- _host = "127.0.0.1"
+ # Cloud-first: a headless VPS / container must be reachable by a remote
+ # browser, which a 127.0.0.1-only listener is not. ``JARVIS_BIND_HOST`` opts
+ # into a non-loopback bind (e.g. ``0.0.0.0`` inside Docker); the default
+ # stays loopback so desktop installs are byte-for-byte unchanged. The
+ # Control-API key is the security boundary on any non-loopback bind, so
+ # ``assert_bind_safe`` fails closed without one — mirroring WebServer.start().
+ _host = (os.environ.get("JARVIS_BIND_HOST") or "127.0.0.1").strip() or "127.0.0.1"
+ if _host not in ("127.0.0.1", "::1", "localhost"):
+ from jarvis.core import control_key as _control_key
+ from jarvis.ui.web.control_auth import assert_bind_safe
+
+ assert_bind_safe(_host, _control_key.get_control_key())
_port = args.port if args.port is not None else _fast_admin_port()
_bootstrap_server = uvicorn.Server(
uvicorn.Config(
@@ -370,7 +418,7 @@ async def _run_headless(args) -> int:
# init below. Deferred off the time-to-serving path (its desktop_app import
# is ~420 ms). After a host crash a stale lock is reclaimed here via the
# PID-sidecar in acquire_single_instance_lock.
- _headless_lock = _acquire_primary_lock_for_headless()
+ _headless_lock = _claim_headless_primary_lock(args)
_lx_mark("lock")
from jarvis.brain.factory import build_default_brain
@@ -739,6 +787,213 @@ def _run_desktop(cfg, use_lock: bool) -> int:
pass
+def _serve_bootstrap_with_retry(
+ loop,
+ host: str,
+ port: int,
+ *,
+ attempts: int = 5,
+ delay: float = 0.4,
+ _factory=None,
+ _sleep=time.sleep,
+):
+ """Bind the serve-first bootstrap, retrying a transient post-restart bind race.
+
+ A bind failure on the admin port immediately after an in-app self-restart is
+ almost always *transient*: the just-exited old process is still releasing the
+ socket, not a live second instance holding it. Treating that first failure as
+ "already running" (and bouncing) is the "shuts down but never comes back" bug
+ — so retry the bind a few times before giving up. The single-instance lock
+ (acquired later in :func:`_desktop_backend_main`) stays the authoritative
+ "is another instance live?" check; this only prevents the transient race from
+ being misread.
+
+ A fresh ``FastBootstrap`` is built per attempt (a failed ``serve`` leaves a
+ spent uvicorn server on the object — never reuse it). Returns the bound
+ bootstrap, or ``None`` if every attempt failed (the caller then maps that to
+ "already running"). The normal start (free port) binds on the first attempt
+ with no delay; only a genuinely, persistently-bound port pays the full backoff.
+ """
+ from jarvis.ui.web.fast_bootstrap import FastBootstrap
+
+ factory = _factory if _factory is not None else FastBootstrap
+ for attempt in range(attempts):
+ bootstrap = factory()
+ try:
+ loop.run_until_complete(bootstrap.serve(host, port))
+ return bootstrap
+ except Exception: # noqa: BLE001 — bind failed; retry then treat as busy
+ if attempt < attempts - 1:
+ _sleep(delay)
+ return None
+
+
+def _desktop_backend_main(args, port: int, token: str, holder: dict, app_ready) -> None:
+ """Backend thread for the fast-boot desktop path.
+
+ Binds the serve-first bootstrap FIRST (light imports only), then does the
+ heavy config + ``DesktopApp`` build and serves the real app behind the
+ bootstrap on the same loop. Communicates back to the main thread via
+ *holder* (``app`` / ``err`` / ``lock`` / ``already_running``) + *app_ready*.
+ On a post-bind failure it frees the port so the classic fallback can bind.
+ """
+ import asyncio as _asyncio
+ import contextlib as _contextlib
+ import threading as _threadmod
+
+ def _t_current():
+ return _threadmod.current_thread()
+
+ loop = _asyncio.new_event_loop()
+ _asyncio.set_event_loop(loop)
+ bootstrap = None
+ try:
+ # A bind failure right after a self-restart is usually the old process
+ # still releasing the port, NOT a live second instance — so retry the
+ # bind before concluding "already running" (the lock below is the real
+ # arbiter). Without this, the fresh restart instance bounces and the app
+ # "shuts down but never comes back".
+ bootstrap = _serve_bootstrap_with_retry(loop, "127.0.0.1", port)
+ if bootstrap is None:
+ holder["already_running"] = True
+ app_ready.set()
+ return
+ if os.environ.get("JARVIS_BOOT_PROFILE") == "1" and _BOOT_PROFILE_T0 is not None:
+ print(
+ f"BOOT_READY_MS={(time.perf_counter() - _BOOT_PROFILE_T0) * 1000.0:.1f}",
+ flush=True,
+ )
+
+ from jarvis.core.config import (
+ ensure_project_root_cwd,
+ load_config,
+ refresh_persisted_env_from_user_registry,
+ )
+
+ ensure_project_root_cwd()
+ refresh_persisted_env_from_user_registry()
+ cfg = load_config()
+ if args.dev:
+ cfg = cfg.model_copy(update={"ui": cfg.ui.model_copy(update={"dev_mode": True})})
+ if args.port is not None:
+ cfg = cfg.model_copy(
+ update={"ui": cfg.ui.model_copy(update={"admin_api_port": args.port})}
+ )
+ try:
+ from jarvis.core import control_key
+
+ control_key.ensure_control_key()
+ except Exception: # noqa: BLE001 — never block boot on key bootstrap
+ pass
+
+ from jarvis.ui.desktop_app import (
+ DesktopApp,
+ SingleInstanceError,
+ acquire_single_instance_lock,
+ )
+
+ if not args.no_lock:
+ try:
+ holder["lock"] = acquire_single_instance_lock()
+ os.environ["JARVIS_PRIMARY_INSTANCE"] = "1"
+ except SingleInstanceError:
+ holder["already_running"] = True
+ with _contextlib.suppress(Exception):
+ loop.run_until_complete(bootstrap.stop())
+ app_ready.set()
+ return
+ else:
+ os.environ["JARVIS_PRIMARY_INSTANCE"] = "0"
+
+ def _reconcile() -> None:
+ try:
+ from jarvis.autostart import reconcile_autostart
+
+ reconcile_autostart(cfg)
+ except Exception: # noqa: BLE001 — defense in depth; never block boot
+ pass
+
+ import threading as _t
+
+ _t.Thread(target=_reconcile, name="autostart-reconcile", daemon=True).start()
+
+ app = DesktopApp(cfg, session_token=token)
+ # Pre-publish the backend handles BEFORE app_ready so the main-thread
+ # window's shutdown path can never observe them as None (the window path
+ # itself only needs cfg + session_token, both set in __init__, so there
+ # is no race there — this is belt-and-suspenders for an early close).
+ app._backend_loop = loop
+ app._bootstrap = bootstrap
+ app._backend_thread = _t_current()
+ holder["app"] = app
+ except Exception as exc: # noqa: BLE001
+ holder["err"] = repr(exc)
+ # Free the port so the classic fallback can bind it.
+ if bootstrap is not None:
+ with _contextlib.suppress(Exception):
+ loop.run_until_complete(bootstrap.stop())
+ with _contextlib.suppress(Exception):
+ loop.close()
+ app_ready.set()
+ return
+ app_ready.set()
+ # Build + serve the real app on this loop, reusing the already-bound bootstrap.
+ app._run_backend(prebound=(loop, bootstrap))
+
+
+def _run_desktop_fast(args) -> int | None:
+ """Fast-boot desktop entry. Returns the exit code on success, or ``None`` on
+ any setup failure so ``main()`` falls back to the classic boot."""
+ import logging as _log
+ import secrets
+ import threading as _threading
+
+ try:
+ _ensure_windows_app_identity() # AUMID before the window (main thread)
+ port = args.port if args.port is not None else _fast_admin_port()
+ token = secrets.token_urlsafe(32)
+ os.environ[_fast_auth_token_env()] = token
+
+ holder: dict = {"app": None, "err": None, "lock": None, "already_running": False}
+ app_ready = _threading.Event()
+ backend = _threading.Thread(
+ target=_desktop_backend_main,
+ args=(args, port, token, holder, app_ready),
+ name="jarvis-backend",
+ daemon=True,
+ )
+ backend.start()
+ if not app_ready.wait(timeout=60.0):
+ _log.getLogger(__name__).error("fast-boot backend did not signal in 60s")
+ return None
+ if holder["already_running"]:
+ from jarvis.ui.desktop_app import focus_existing_instance_robust
+
+ print("Jarvis läuft bereits.", file=sys.stderr)
+ focus_existing_instance_robust()
+ return 3
+ app = holder["app"]
+ if app is None:
+ _log.getLogger(__name__).warning(
+ "fast-boot backend init failed (%s) — classic fallback", holder["err"]
+ )
+ return None
+ app._backend_thread = backend
+ except Exception: # noqa: BLE001
+ _log.getLogger(__name__).exception("fast-boot setup raised — classic fallback")
+ return None
+
+ try:
+ return app.run_window_only()
+ finally:
+ lock = holder.get("lock")
+ if lock is not None:
+ try:
+ lock.release()
+ except Exception: # noqa: BLE001
+ pass
+
+
def main(argv: list[str] | None = None) -> int:
# Stamp the boot-profiling t0 as early as possible (only when opted in) so
# BOOT_READY_MS reflects nearly the full in-process cold-start cost. The
@@ -770,6 +1025,23 @@ def main(argv: list[str] | None = None) -> int:
if args.headless:
return asyncio.run(_run_headless(args))
+ # Desktop boot: CLASSIC path (proven + GUI-safe). The serve-first bootstrap
+ # + static-shell + boot-splash (the black-screen fix) live in
+ # ``DesktopApp._run_backend``, so this path still opens with the real UI
+ # shell and no black screen. The "early-bind" launcher path
+ # (``_run_desktop_fast``) is kept but NOT the default — it was disabled
+ # 2026-06-25 after a no-boot incident under parallel sessions; re-enable only
+ # after a real-desktop window sign-off (set JARVIS_DESKTOP_FASTBOOT=1).
+ if os.environ.get("JARVIS_DESKTOP_FASTBOOT") == "1":
+ _fast_exit = _run_desktop_fast(args)
+ if _fast_exit is not None:
+ return _fast_exit
+ import logging as _flog
+
+ _flog.getLogger(__name__).warning(
+ "fast-boot desktop unavailable — falling back to classic boot"
+ )
+
from jarvis.core.config import (
ensure_project_root_cwd,
load_config,
diff --git a/jarvis/ui/web/marketplace_routes.py b/jarvis/ui/web/marketplace_routes.py
index 707059078b..9a57bc864f 100644
--- a/jarvis/ui/web/marketplace_routes.py
+++ b/jarvis/ui/web/marketplace_routes.py
@@ -144,6 +144,28 @@ _validate_token = _make_validator()
# ----------------------------------------------------------------------
+def _mcp_live(mcp: dict[str, Any]) -> tuple[bool, str | None]:
+ """``(is_live, runtime_missing)`` for an MCP plugin's transport.
+
+ M2 (honest status): a stdio plugin (GitHub=docker, Supabase=npx) is only LIVE if
+ its launcher binary is on PATH — else connecting saves the token but the tools
+ never appear, so a green "Connected · Live" badge is a lie. http transports are
+ always live; ``runtime_missing`` is the absent launcher name for an honest UI hint.
+ """
+ transport = str(mcp.get("transport", "")).lower()
+ if transport == "http":
+ return True, None
+ if transport == "stdio":
+ import shutil
+
+ install = mcp.get("install") or []
+ launcher = str(install[0]) if install else ""
+ if launcher and shutil.which(launcher):
+ return True, None
+ return False, (launcher or None)
+ return False, None
+
+
@router.get("/plugins")
async def list_plugins(response: Response) -> dict[str, Any]:
# Never let an embedded webview (pywebview/WebView2) serve a stale cached
@@ -161,7 +183,9 @@ async def list_plugins(response: Response) -> dict[str, Any]:
status = _plugin_status(spec.id, store)
item["status"] = status
mcp = spec.mcp_server or {}
- mcp_live = str(mcp.get("transport", "")).lower() in ("http", "stdio")
+ mcp_live, runtime_missing = _mcp_live(mcp)
+ if runtime_missing:
+ item["runtime_missing"] = runtime_missing
native_live = False
if spec.native_tool:
try:
@@ -264,12 +288,22 @@ async def connect_pat(plugin_id: str, body: PatConnectBody, request: Request) ->
live_applied = False
if plugin_id in _CHANNEL_PLUGIN_IDS:
live_applied = await apply_channel_live(request.app.state, plugin_id)
- return {
+ result: dict[str, Any] = {
"ok": True,
"plugin_id": plugin_id,
"status": "connected",
"live_applied": live_applied,
}
+ if plugin_id in _CHANNEL_PLUGIN_IDS and not live_applied:
+ # M8 (honest status): the token saved but the channel did NOT start live —
+ # commonly the optional extra is missing (e.g. discord.py for Discord) or an
+ # app restart is needed. Surface it so the UI never implies a working message
+ # path with a green "Live" badge.
+ result["live_note"] = (
+ "Saved, but the channel did not start live. It may need its optional "
+ "extra (pip install '.[channels]' for Discord) or an app restart."
+ )
+ return result
# ----------------------------------------------------------------------
diff --git a/jarvis/ui/web/missions_auth.py b/jarvis/ui/web/missions_auth.py
index 370836af9b..edf91d8f1a 100644
--- a/jarvis/ui/web/missions_auth.py
+++ b/jarvis/ui/web/missions_auth.py
@@ -12,6 +12,7 @@ Single-User-Localhost-Threat-Model.
"""
from __future__ import annotations
+import os
import secrets
from typing import Final
@@ -37,6 +38,34 @@ def validate_token(tok: str) -> bool:
return tok in _TOKENS
+def register_token(tok: str) -> None:
+ """Register an externally-minted token as valid. Idempotent.
+
+ The fast-boot desktop path mints a RAW ``secrets.token_urlsafe`` and injects
+ it into ``window.__JARVIS_TOKEN`` without ever issuing it through
+ ``GET /token`` — so without this it fails ``validate_token`` (close 4401) on
+ every token-gated WebSocket. That is exactly what hung the "Make It Yours"
+ workspace PTY terminals forever on "connecting".
+ """
+ if tok:
+ _TOKENS.add(tok)
+
+
+def register_session_token_from_env(env_var: str) -> str | None:
+ """Read the desktop session token from ``env_var`` and register it as valid.
+
+ Called once at server build with ``cfg.ui.auth_token_env`` so the injected
+ ``window.__JARVIS_TOKEN`` passes ``validate_token``. Returns the token when
+ present, else ``None`` (headless / browser-only boots inject no token and
+ fetch a fresh one via ``GET /token`` instead).
+ """
+ tok = os.environ.get(env_var)
+ if tok:
+ _TOKENS.add(tok)
+ return tok
+ return None
+
+
def revoke_token(tok: str) -> None:
"""Best-effort entfernt den Token. Idempotent."""
_TOKENS.discard(tok)
diff --git a/jarvis/ui/web/outputs_routes.py b/jarvis/ui/web/outputs_routes.py
index be0e342ac3..2a51d4b753 100644
--- a/jarvis/ui/web/outputs_routes.py
+++ b/jarvis/ui/web/outputs_routes.py
@@ -13,6 +13,7 @@ even when the mission row is gone (DB pruned, recovery cleanup).
from __future__ import annotations
import asyncio
+import json
import logging
import mimetypes
import os
@@ -30,6 +31,7 @@ from jarvis.core.process_utils import NO_WINDOW_CREATIONFLAGS
from jarvis.missions.kontrollierer.deliverable_paths import (
is_nondeliverable_scratch,
)
+from jarvis.missions.state_machine import MissionState, is_terminal
from jarvis.platform import detect_platform
from jarvis.ui.web.artifact_view import VIEW_CSP, render_artifact_html
@@ -243,6 +245,67 @@ _STATE_TO_STATUS: dict[str, str] = {
}
+# Terminal mission-state *values* (string form). A re-run child counts as a
+# "live" continuation only while its state is NOT in this set. Single source of
+# truth = the state machine (mirrors ``missions_routes._TERMINAL_STATE_VALUES``).
+_TERMINAL_STATE_VALUES: frozenset[str] = frozenset(
+ s.value for s in MissionState if is_terminal(s)
+)
+
+
+async def _live_continuation_map(request: Request) -> dict[str, str]:
+ """Map a terminal parent-mission-id → its still-running re-run child id.
+
+ The Outputs "Continue"/"Restart" buttons re-dispatch a terminal mission's
+ prompt as a NEW mission linked back via ``parent_mission_id`` (stored only
+ in the child's ``MissionDispatched`` event payload — the ``missions`` header
+ has no parent column). A terminal source card stays re-runnable forever, so
+ without this signal it keeps offering "Continue" even after it has already
+ been continued and that child is actively running. The user then sees a
+ cancelled card sitting next to its own live continuation — both showing the
+ identical stored prompt — and cannot tell whether "the mission" is running
+ (forensic 2026-06-28, missions 019f0fa6 → 019f0fac).
+
+ Returns ``{parent_id: child_id}`` for every parent whose NEWEST re-run child
+ is still non-terminal (live). Best-effort: ``{}`` on a missing manager, an
+ absent ``mission_events`` table, or any DB error — the Outputs view stays
+ functional (mirrors ``_mission_status_lookup``). This is the read-side twin
+ of the rerun endpoint's own ``find_child_missions`` liveness guard.
+ """
+ mgr = getattr(request.app.state, "mission_manager", None)
+ if mgr is None:
+ return {}
+ try:
+ cur = await mgr.store.conn.execute(
+ """
+ SELECT e.mission_id, m.state, e.payload_json
+ FROM mission_events e
+ JOIN missions m ON m.id = e.mission_id
+ WHERE e.event_type = 'MissionDispatched'
+ ORDER BY m.created_ms DESC
+ """
+ )
+ rows = await cur.fetchall()
+ await cur.close()
+ except Exception as exc: # noqa: BLE001
+ logger.debug("outputs: continuation lookup failed: %s", exc)
+ return {}
+
+ out: dict[str, str] = {}
+ for child_id, child_state, payload_json in rows:
+ if str(child_state) in _TERMINAL_STATE_VALUES:
+ continue # only a LIVE child resolves the run/not-run ambiguity
+ try:
+ parent = json.loads(payload_json or "{}").get("parent_mission_id")
+ except (ValueError, TypeError):
+ parent = None
+ if not parent:
+ continue
+ # Rows are newest-first; keep the first (newest) live child per parent.
+ out.setdefault(str(parent), str(child_id))
+ return out
+
+
@router.get("")
async def list_outputs(request: Request) -> dict[str, Any]:
"""List output directories newest-first.
@@ -286,6 +349,10 @@ async def list_outputs(request: Request) -> dict[str, Any]:
all_mission_prefixes.append(prefix)
mission_status = await _mission_status_lookup(request, all_mission_prefixes)
+ # Resolve, in one pass, which terminal missions already have a still-running
+ # re-run child — so a "Continue"/"Restart" card can be shown as live instead
+ # of lying with an idle, re-runnable affordance (forensic 2026-06-28).
+ continuation = await _live_continuation_map(request)
for entry in entries:
# Skip worktree-slug-only dirs (``<ts>__<utterance>__<short>``). Their
@@ -325,11 +392,21 @@ async def list_outputs(request: Request) -> dict[str, Any]:
"duration_s": None,
"github_url": None,
"error": None,
+ # When this (terminal) mission has already been continued/restarted
+ # and that re-run is still live, the full id + slug of the running
+ # child — so the UI shows "running", not a redundant "Continue".
+ "active_child_id": None,
+ "active_child_slug": None,
}
if mission_row is not None:
status = _STATE_TO_STATUS.get(str(mission_row["state"]), "unknown")
summary["status"] = status
summary["mission_id"] = mission_row.get("full_id")
+ full_id = mission_row.get("full_id")
+ child_id = continuation.get(str(full_id)) if full_id else None
+ if child_id:
+ summary["active_child_id"] = child_id
+ summary["active_child_slug"] = f"mission_{child_id[:13]}"
summary["utterance"] = (
summary["utterance"] or mission_row.get("prompt")
)
diff --git a/jarvis/ui/web/profile_routes.py b/jarvis/ui/web/profile_routes.py
index ccc258eb3a..596187826d 100644
--- a/jarvis/ui/web/profile_routes.py
+++ b/jarvis/ui/web/profile_routes.py
@@ -29,12 +29,23 @@ import logging
import os
import tempfile
from pathlib import Path
-from typing import Any
+from typing import Any, Literal
from fastapi import APIRouter, File, HTTPException, Request, UploadFile
from fastapi.responses import FileResponse, Response
from pydantic import BaseModel
+# Single source of truth for the writable field vocabulary + field shapes,
+# shared with the brain's update_profile tool so the inline editor and the brain
+# can never drift on what is writable (the BUG-008 enum-drift class). The parity
+# with the UI's CLUSTER_FIELD_KEYS is pinned by test_profile_update.py.
+from jarvis.plugins.tool.profile_update import (
+ _BOOL_FIELDS,
+ _CANONICAL_FIELDS,
+ _LIST_FIELDS,
+ _coerce_bool,
+)
+
log = logging.getLogger(__name__)
router = APIRouter(prefix="/api/profile", tags=["profile"])
@@ -478,6 +489,143 @@ async def put_raw(request: Request, body: RawWriteBody) -> dict[str, Any]:
}
+class FieldEditBody(BaseModel):
+ """Body for PATCH /api/profile/field — edit one structured profile field.
+
+ ``operation`` decides what happens:
+ - ``set`` — overwrite a scalar field (Chef → König). Rejected on list fields.
+ - ``clear`` — empty any field so it reads back as "not known yet".
+ - ``append`` — add one item to a list field (a chip). Rejected on scalars.
+ - ``remove`` — drop one item from a list field (the chip 'x').
+
+ ``value`` is required for set/append/remove, ignored for clear.
+ """
+
+ cluster: str
+ field: str
+ operation: Literal["set", "clear", "append", "remove"]
+ value: Any = None
+
+
+async def patch_field(request: Request, body: FieldEditBody) -> dict[str, Any]:
+ """Inline single-field edit for the Profile view (the pencil per field).
+
+ Mutates the SAME live ``UserProfile`` the brain renders from, persists it
+ atomically to USER.md, logs an audit observation, and emits ``ProfileUpdated``
+ so any other open view live-syncs. This is the manual-edit sibling of the
+ brain's ``update_profile`` tool; they share the canonical field allow-list so
+ the editor can never write a field the matrix / brain don't know about.
+ """
+ profile = _require_profile(request)
+
+ cluster = body.cluster.strip().lower()
+ field = body.field.strip().lower()
+ op = body.operation
+ value = body.value
+
+ # Validate against the shared allow-list — never write an unknown field.
+ if cluster not in _CANONICAL_FIELDS:
+ raise HTTPException(status_code=400, detail=f"Unknown cluster {cluster!r}.")
+ if field not in _CANONICAL_FIELDS[cluster]:
+ raise HTTPException(
+ status_code=400,
+ detail=f"Unknown field {field!r} for cluster {cluster!r}.",
+ )
+
+ is_list = (cluster, field) in _LIST_FIELDS
+
+ # The operation must match the field shape (a set on a list would clobber it
+ # into a scalar; an append on a scalar makes no sense).
+ if op in ("append", "remove") and not is_list:
+ raise HTTPException(
+ status_code=400,
+ detail=f"{cluster}.{field} is not a list field — use set or clear.",
+ )
+ if op == "set" and is_list:
+ raise HTTPException(
+ status_code=400,
+ detail=f"{cluster}.{field} is a list field — use append or remove.",
+ )
+
+ # value is mandatory except for clear.
+ if op in ("set", "append", "remove"):
+ if value is None or (isinstance(value, str) and not value.strip()):
+ raise HTTPException(status_code=400, detail="Missing 'value'.")
+
+ # Coerce the boolean fields (emoji_ok) from the string the UI may send.
+ if op == "set" and (cluster, field) in _BOOL_FIELDS:
+ coerced = _coerce_bool(value)
+ if coerced is None:
+ raise HTTPException(
+ status_code=400,
+ detail=f"{cluster}.{field} expects a boolean (true/false).",
+ )
+ value = coerced
+ if isinstance(value, str):
+ value = value.strip()
+
+ try:
+ if op == "set":
+ changed = profile.set(cluster, field, value)
+ elif op == "clear":
+ changed = profile.clear(cluster, field)
+ elif op == "append":
+ changed = profile.append_list(cluster, field, value)
+ else: # remove
+ changed = profile.remove_list_item(cluster, field, value)
+ except ValueError as exc: # defensive — allow-list already guards this
+ raise HTTPException(status_code=400, detail=str(exc)) from exc
+
+ if changed:
+ # Audit trail (best-effort — never block the write) mirroring update_profile.
+ try:
+ label = f"{cluster}.{field}"
+ if op == "clear":
+ obs_value = "(cleared)"
+ elif op == "remove":
+ obs_value = f"(removed {value})"
+ else:
+ obs_value = str(value)
+ profile.append_observation(label, obs_value, "manual edit via profile UI")
+ except Exception: # noqa: BLE001
+ log.debug("profile field edit: append_observation failed", exc_info=True)
+
+ try:
+ profile.save()
+ except Exception as exc: # noqa: BLE001
+ log.warning("profile field edit: save failed: %s", exc)
+ raise HTTPException(
+ status_code=500, detail=f"Could not persist profile: {exc}"
+ ) from exc
+
+ # Live-sync any other open view (best-effort — a bus hiccup must never
+ # fail the already-persisted write).
+ bus = getattr(_get_brain(request), "_bus", None)
+ if bus is not None:
+ try:
+ from jarvis.core.events import ProfileUpdated
+
+ await bus.publish(
+ ProfileUpdated(
+ subject="user", cluster=cluster, field=field,
+ operation=op, confidence=1.0,
+ evidence="manual edit via profile UI",
+ )
+ )
+ except Exception: # noqa: BLE001
+ log.debug("profile field edit: ProfileUpdated publish failed", exc_info=True)
+
+ return {
+ "ok": True,
+ "changed": changed,
+ "cluster": cluster,
+ "field": field,
+ "operation": op,
+ "value": profile.get(cluster, field),
+ }
+
+
@router.get("/reviews")
async def get_reviews(request: Request) -> dict[str, Any]:
"""Liefert die Pending-Review-Queue des Curators.
diff --git a/jarvis/ui/web/provider_routes.py b/jarvis/ui/web/provider_routes.py
index 9614302c31..cbed8737a3 100644
--- a/jarvis/ui/web/provider_routes.py
+++ b/jarvis/ui/web/provider_routes.py
@@ -15,13 +15,16 @@ Wird vom WebServer in `_build_app()` eingehängt:
"""
from __future__ import annotations
+import asyncio
import logging
+import time
from typing import Any, Literal, get_args
from fastapi import APIRouter, HTTPException, Request
from pydantic import BaseModel, Field
from jarvis.brain import provider_test as _provider_test
+from jarvis.brain import section_health as _section_health
from jarvis.brain.model_catalog import catalog_spec
from jarvis.codex_auth import CodexAuthService
from jarvis.core import config as cfg_mod
@@ -488,6 +491,236 @@ async def test_provider_connection(
)
+# ----------------------------------------------------------------------
+# Section health — the at-a-glance API-Keys tab indicators
+# ----------------------------------------------------------------------
+
+# Section-health status vocabulary. ``SectionHealthStatusLiteral`` MUST mirror the
+# SSOT in ``jarvis.brain.section_health`` — the runtime assert is the five-layer
+# anti-drift guard (BUG-008 class) and the TS ``SectionHealthStatus`` union in
+# ``useProviders.ts`` is the UI mirror.
+SectionHealthStatusLiteral = Literal["ok", "needs_setup", "error", "unknown"]
+assert set(get_args(SectionHealthStatusLiteral)) == set(
+ _section_health.SECTION_HEALTH_STATUSES
+), "section-health status vocabulary drift (Pydantic Literal vs SSOT)"
+
+# Cache the rollup briefly so opening the API-Keys page / switching tabs does not
+# re-run the REAL connectivity tests on every render. ``?refresh=true`` (used by
+# the UI after a key save / provider switch) bypasses it.
+_SECTION_HEALTH_TTL_S = 45.0
+
+
+class SectionHealth(BaseModel):
+ """One tab's rolled-up health. Only ``needs_setup`` (amber) and ``error``
+ (red) draw a dot in the UI; ``ok`` / ``unknown`` stay silent."""
+
+ status: SectionHealthStatusLiteral = "unknown"
+ # Machine-readable cause for the UI tooltip + debugging: the underlying
+ # provider-test status ("bad_key"/"no_credits"/…), "not_configured",
+ # "no_active", "local", "ok", or "unknown". Not shown verbatim to the user.
+ reason: str = "unknown"
+ # Plain-English one-liner for the hover tooltip (provider label + detail).
+ detail: str = ""
+
+
+class SectionHealthResponse(BaseModel):
+ sections: dict[str, SectionHealth]
+ checked_at: float = 0.0
+ cached: bool = False
+
+
+async def _tier_section_health(cfg: Any, spec: ProviderSpec | None) -> SectionHealth:
+ """Health of one provider tier, derived from its ACTIVE provider only.
+
+ A tier is only as healthy as the single provider currently powering it —
+ deliberately NOT "does any provider here lack a key" (that would paint every
+ tab red, since unused providers are normally left empty).
+ """
+ if spec is None:
+ return SectionHealth(
+ status=_section_health.NEEDS_SETUP,
+ reason="no_active",
+ detail="No active provider selected",
+ )
+ # Local providers (faster-whisper, SAPI) have no key to be invalid; if one is
+ # the active provider it is usable. Skip the real test — it could force a heavy
+ # model load on page open for no signal we don't already have.
+ if getattr(spec, "auth_mode", None) == "none":
+ return SectionHealth(
+ status=_section_health.OK,
+ reason="local",
+ detail=f"{spec.label}: local, no key needed",
+ )
+ try:
+ configured = _is_credential_present(
+ spec, _codex_binary_path() if spec.id == "codex" else None
+ )
+ except Exception: # noqa: BLE001 — a probe failure is "not set up", not a crash
+ configured = False
+ if not configured:
+ return SectionHealth(
+ status=_section_health.NEEDS_SETUP,
+ reason="not_configured",
+ detail=f"{spec.label}: no key set",
+ )
+ try:
+ result = await _provider_test.run_provider_test(spec, cfg)
+ except Exception as exc: # noqa: BLE001
+ log.warning("section-health test for %s failed: %s", spec.id, exc)
+ return SectionHealth(
+ status=_section_health.UNKNOWN, reason="error", detail=f"{spec.label}: check failed"
+ )
+ status = _section_health.section_status_for_test(result.status, configured=True)
+ return SectionHealth(
+ status=status,
+ reason=result.status,
+ detail=f"{spec.label}: {result.detail or result.status}",
+ )
+
+
+def _subagent_worker_usable(provider: str) -> bool:
+ """Best-effort "is the selected heavy-task worker connected/keyed?".
+
+ Provider-agnostic: a CLI login (Codex / Antigravity / Claude) is usable when
+ its auth service reports connected; an API-keyed worker reuses the brain
+ provider's credential. Any probe failure degrades to "not usable" rather than
+ raising (AP-22/23 — never brick on the maintainer's favourite worker).
+ """
+ p = (provider or "").lower()
+ try:
+ if p in _CODEX_SUBAGENT_SLUGS or p in {"codex", "openai-codex"}:
+ connected = bool(CodexAuthService(_codex_binary_path()).status().connected)
+ return connected or _has_openai_brain_credential()
+ if p == "antigravity":
+ from jarvis.google_cli.auth_service import GoogleCliAuthService
+
+ return bool(GoogleCliAuthService().status().connected)
+ if p in {"claude-api", "claude"}:
+ from jarvis.claude_auth import ClaudeAuthService
+
+ st = ClaudeAuthService().status()
+ return bool(
+ getattr(st, "connected", False) or getattr(st, "api_key_present", False)
+ )
+ spec = get_spec(p)
+ return bool(spec is not None and _is_credential_present(spec))
+ except Exception: # noqa: BLE001
+ return False
+
+
+def _subagent_section_health(cfg: Any) -> SectionHealth:
+ """Subagents tab: reflects whether the SELECTED heavy-task worker is usable.
+
+ A real "does it answer" call for a CLI worker is heavy, so v1 reports the
+ connectedness signal — connected/keyed → ok, otherwise needs_setup. It never
+ flags ``error`` (a connected-but-failing CLI worker is out of scope here).
+ """
+ brain = getattr(cfg, "brain", None) if cfg is not None else None
+ if brain is None:
+ return SectionHealth(
+ status=_section_health.NEEDS_SETUP,
+ reason="no_active",
+ detail="No subagent worker selected",
+ )
+ sub = getattr(brain, "sub_jarvis", None)
+ provider = (getattr(sub, "provider", None) if sub else None) or getattr(
+ brain, "primary", None
+ )
+ if not provider:
+ return SectionHealth(
+ status=_section_health.NEEDS_SETUP,
+ reason="no_active",
+ detail="No subagent worker selected",
+ )
+ spec = get_spec(provider)
+ label = spec.label if spec is not None else provider
+ if _subagent_worker_usable(provider):
+ return SectionHealth(
+ status=_section_health.OK, reason="ok", detail=f"Subagent worker: {label}"
+ )
+ return SectionHealth(
+ status=_section_health.NEEDS_SETUP,
+ reason="not_configured",
+ detail=f"Subagent worker '{label}' is not connected",
+ )
+
+
+def _advanced_section_health(request: Request) -> SectionHealth:
+ """Advanced tab: every integration here is OPTIONAL, so it never reports
+ ``needs_setup`` — only ``error`` when something the user actually configured
+ is failing. Today that is telephony's cached reachability check; otherwise the
+ tab stays silent (``unknown``)."""
+ contributions: list[str] = []
+ detail = ""
+ reason = "unknown"
+ tm = getattr(request.app.state, "telephony_manager", None)
+ if tm is not None and getattr(tm, "reachable", None) is False:
+ err = getattr(tm, "reachable_error", None)
+ if err:
+ contributions.append(_section_health.ERROR)
+ detail = f"Telephony unreachable: {err}"
+ reason = "telephony"
+ return SectionHealth(
+ status=_section_health.aggregate(contributions), reason=reason, detail=detail
+ )
+
+
[email protected]("/providers/section-health")
+async def section_health(request: Request, refresh: bool = False) -> SectionHealthResponse:
+ """Per-tab health for the API-Keys segmented tabs ("is this part working?").
+
+ The brain/tts/stt tiers get a REAL connectivity test of their active provider
+ (run in parallel), the Subagents tab reflects whether the selected worker is
+ connected, and the Advanced tab only flags a configured optional integration
+ that is actually failing. The result is cached for a few seconds so opening the
+ page / switching tabs does not re-run the real calls each render;
+ ``?refresh=true`` forces a fresh check after a key save or provider switch.
+ """
+ cache = getattr(request.app.state, "_section_health_cache", None)
+ now = time.time()
+ if (
+ not refresh
+ and isinstance(cache, dict)
+ and now - cache.get("checked_at", 0.0) < _SECTION_HEALTH_TTL_S
+ ):
+ return SectionHealthResponse(
+ sections=cache["payload"], checked_at=cache["checked_at"], cached=True
+ )
+
+ cfg = _resolve_cfg(request)
+ sections: dict[str, SectionHealth] = {}
+
+ if cfg is None:
+ for key in ("brain", "tts", "stt", "subagents", "advanced"):
+ sections[key] = SectionHealth(
+ status=_section_health.UNKNOWN,
+ reason="unavailable",
+ detail="Configuration unavailable",
+ )
+ else:
+ brain_spec = get_spec(_active_brain(request) or "")
+ tts_spec = get_spec(_active_tts(request) or "")
+ stt_spec = get_spec(_active_stt(request) or "")
+ sections["brain"], sections["tts"], sections["stt"] = await asyncio.gather(
+ _tier_section_health(cfg, brain_spec),
+ _tier_section_health(cfg, tts_spec),
+ _tier_section_health(cfg, stt_spec),
+ )
+ try:
+ sections["subagents"] = _subagent_section_health(cfg)
+ except Exception as exc: # noqa: BLE001
+ log.warning("section-health subagent check failed: %s", exc)
+ sections["subagents"] = SectionHealth()
+ try:
+ sections["advanced"] = _advanced_section_health(request)
+ except Exception as exc: # noqa: BLE001
+ log.warning("section-health advanced check failed: %s", exc)
+ sections["advanced"] = SectionHealth()
+
+ request.app.state._section_health_cache = {"checked_at": now, "payload": sections}
+ return SectionHealthResponse(sections=sections, checked_at=now, cached=False)
+
+
# ----------------------------------------------------------------------
# Per-provider model picker (live catalog + pin + honest probe)
# ----------------------------------------------------------------------
@@ -977,6 +1210,16 @@ async def codex_logout(request: Request) -> dict[str, Any]:
return {"ok": True, "message": "Codex wurde getrennt"}
+# M6: STT/TTS engines build ONCE at voice-pipeline bootstrap, so a key feeding them
+# is unused until the next voice start. Surface restart_required so the UI shows the
+# "active from next voice start" hint instead of implying the new key is live now.
+# (Brain provider keys hot-reload, so they are deliberately NOT listed here.)
+_RESTART_REQUIRED_SECRET_KEYS: frozenset[str] = frozenset({
+ "groq_api_key", "deepgram_api_key", # STT
+ "cartesia_api_key", "elevenlabs_api_key", # TTS
+})
+
+
@router.post("/secrets/{key}")
async def set_secret_value(key: str, body: SecretBody, request: Request) -> dict[str, Any]:
if key not in ALLOWED_SECRET_KEYS:
@@ -984,7 +1227,11 @@ async def set_secret_value(key: str, body: SecretBody, request: Request) -> dict
if not cfg_mod.set_secret(key, body.value):
raise HTTPException(status_code=500, detail="Keyring-Write fehlgeschlagen")
await _emit(request, SecretConfigured(key=key, action="set"))
- return {"ok": True, "key": key}
+ return {
+ "ok": True,
+ "key": key,
+ "restart_required": key in _RESTART_REQUIRED_SECRET_KEYS,
+ }
@router.delete("/secrets/{key}")
@@ -1367,12 +1614,19 @@ async def subagent_switch(body: SwitchBody, request: Request) -> dict[str, Any]:
if provider in ANTIGRAVITY_SUBAGENT_SLUGS:
from jarvis.google_cli.auth_service import GoogleCliAuthService
- if not GoogleCliAuthService().status().connected:
+ # Dual billing (mirror of codex): the Google subscription OAuth login OR
+ # a Gemini API key (per token). Either is enough to run the worker.
+ antigravity_connected = GoogleCliAuthService().status().connected
+ antigravity_key = bool(
+ cfg_mod.get_secret("gemini_api_key", env_fallback="GEMINI_API_KEY")
+ )
+ if not (antigravity_connected or antigravity_key):
raise HTTPException(
status_code=409,
detail=(
"Antigravity is not connected — sign in with Google "
- "(install agy or the Gemini CLI and log in), then activate."
+ "(install agy or the Gemini CLI and log in) or set a Gemini "
+ "API key, then activate."
),
)
persisted = False
@@ -1408,9 +1662,19 @@ async def subagent_switch(body: SwitchBody, request: Request) -> dict[str, Any]:
)
# Key-Check — a provider without a stored credential cannot be activated.
- # ``claude-api`` counts the OAuth bearer as present (Claude Max). Reads the
- # same secret store the status endpoint uses for the per-card ``key_set``.
- if not cfg_mod.get_provider_secret(provider):
+ # ``claude-api`` counts the live Claude Max OAuth login (read by the
+ # ClaudeDirectWorker from ~/.claude/.credentials.json) as a credential, so a
+ # fresh Claude-Max user who only ran `claude login` (no stored API key) can
+ # still select it — mirrors the codex/antigravity OAuth branches above.
+ has_credential = bool(cfg_mod.get_provider_secret(provider))
+ if not has_credential and provider == "claude-api":
+ try:
+ from jarvis.missions.isolation.env import read_live_claude_oauth_token
+
+ has_credential = bool(read_live_claude_oauth_token())
+ except Exception: # noqa: BLE001
+ has_credential = False
+ if not has_credential:
raise HTTPException(
status_code=409,
detail=(
diff --git a/jarvis/ui/web/provider_spec.py b/jarvis/ui/web/provider_spec.py
index ca242a7f3a..5af7e53ae1 100644
--- a/jarvis/ui/web/provider_spec.py
+++ b/jarvis/ui/web/provider_spec.py
@@ -75,19 +75,19 @@ class ProviderSpec:
def provider_billing(spec: ProviderSpec) -> Billing:
- """How using *spec* is billed, derived purely from its ``auth_mode``.
+ """How using *spec* is billed — capability-driven, never name-branched
+ (multi-provider mandate, AP-21).
- Capability-driven, never name-branched (multi-provider mandate, AP-21):
-
- * ``antigravity`` → ``"subscription"`` — runs over a Google subscription login.
- * ``codex`` → ``"subscription_or_api"`` — a ChatGPT login OR an OpenAI key.
+ * a subscription-login provider (``codex``/``antigravity``) that ALSO carries
+ an API-key slot → ``"subscription_or_api"`` (a plan login OR per-token key);
+ one with no key slot → ``"subscription"``. The distinction is the presence
+ of ``secret_keys``, not the provider name — so adding a key slot to either
+ flips it without touching this function.
* ``none`` → ``"local"`` — no credential, runs on-device.
* everything else (``api_key``) → ``"api"`` — pay per token on an API account.
"""
- if spec.auth_mode == "antigravity":
- return "subscription"
- if spec.auth_mode == "codex":
- return "subscription_or_api"
+ if spec.auth_mode in ("antigravity", "codex"):
+ return "subscription_or_api" if spec.secret_keys else "subscription"
if spec.auth_mode == "none":
return "local"
return "api"
@@ -179,7 +179,12 @@ PROVIDERS: tuple[ProviderSpec, ...] = (
label="Antigravity (Google subscription)",
tier="brain",
auth_mode="antigravity",
- secret_keys=(),
+ # Dual billing, mirror of Codex: the Google subscription login OR a
+ # Gemini API key (the Google Cloud credential). The key slot reuses the
+ # shared ``gemini_api_key`` — the same key the Gemini provider uses — so
+ # a user who already set it gets per-token Antigravity billing for free.
+ # Carrying a secret_key flips provider_billing → subscription_or_api.
+ secret_keys=("gemini_api_key",),
dashboard_url="https://antigravity.google",
# agy has NO `login` subcommand (verified 2026-06-21) — the bare binary
# drops into the interactive "Sign in with Google" flow. The Connect
@@ -190,9 +195,10 @@ PROVIDERS: tuple[ProviderSpec, ...] = (
brain_switchable=False,
signup_url="https://antigravity.google",
credential_help=(
- "Sign in with your Google account to run the brain over your Google "
- "subscription via the Antigravity/Gemini CLI — no API key, billed to "
- "your subscription, not per token."
+ "Sign in with your Google account to run heavy subagent tasks over "
+ "your Google subscription via the Antigravity/Gemini CLI — no API "
+ "key, billed to your subscription. Or set a Gemini API key to bill "
+ "per token instead."
),
),
ProviderSpec(
diff --git a/jarvis/ui/web/server.py b/jarvis/ui/web/server.py
index cd33fe921b..0455053e9a 100644
--- a/jarvis/ui/web/server.py
+++ b/jarvis/ui/web/server.py
@@ -233,6 +233,7 @@ class WebServer:
from .docs_routes import router as docs_router
from .federation_proxy_routes import router as federation_proxy_router
from .friends_routes import router as friends_router
+ from .frontier_routes import router as frontier_router
from .marketplace_routes import router as marketplace_router
from .mcp_routes import router as mcp_router
from .missions_auth import router as missions_auth_router
@@ -244,17 +245,21 @@ class WebServer:
from .missions_ws_routes import (
router as missions_ws_router,
)
+ from .downloads_routes import router as downloads_router
from .outputs_routes import router as outputs_router
from .preview_routes import router as preview_router
from .antigravity_routes import router as antigravity_router
+ from .claude_routes import router as claude_router
from .profile_routes import router as profile_router
from .provider_routes import router as provider_router
from .review_routes import router as review_router
+ from .self_mod_routes import router as self_mod_router
from .sessions_routes import router as sessions_router
from .settings_routes import router as settings_router
from .setup_routes import router as setup_router
from .onboarding_routes import router as onboarding_router
from .skills_routes import router as skills_router
+ from .feedback_routes import router as feedback_router
from .socials_routes import router as socials_router
from .sub_agents_routes import router as sub_agents_router
from .tasks_routes import router as tasks_router
@@ -263,6 +268,7 @@ class WebServer:
from .wiki_routes import router as wiki_router
from .wiki_ws import router as wiki_ws_router
from .workflows_routes import router as workflows_router
+ from .workspace_routes import router as workspace_router
# Conductor ist ein externes Package im selben Monorepo. Import
# defensiv — wer das Repo ohne conductor checkt aus, kriegt sonst
# hier einen ImportError beim Server-Boot.
@@ -275,9 +281,16 @@ class WebServer:
app.include_router(tools_router)
app.include_router(provider_router)
app.include_router(antigravity_router)
+ app.include_router(claude_router)
app.include_router(control_router)
app.include_router(profile_router)
app.include_router(settings_router)
+ # Frontier auto-switch modal API (GET pending / POST ack) + Self-Mod
+ # read/restore API. Both were the last route modules left unmounted; the
+ # 404 on /api/frontier/pending silently broke the desktop auto-switch
+ # modal too, not just the `jarvis frontier` CLI command.
+ app.include_router(frontier_router)
+ app.include_router(self_mod_router)
app.include_router(tasks_router)
app.include_router(skills_router)
app.include_router(docs_router)
@@ -301,11 +314,15 @@ class WebServer:
app.include_router(browser_voice_router)
app.include_router(sub_agents_router)
app.include_router(outputs_router)
+ app.include_router(downloads_router)
# Socials section — project social-media links (pure file store, no Brain dep).
app.include_router(socials_router)
+ # In-app feedback / bug-report form → Discord webhook.
+ app.include_router(feedback_router)
# Contacts section — user-curated address book (pure file store, no Brain dep).
app.include_router(contacts_router)
app.include_router(workflows_router)
+ app.include_router(workspace_router)
if conductor_router is not None:
app.include_router(conductor_router)
app.include_router(preview_router)
@@ -332,6 +349,15 @@ class WebServer:
# Phase-6 Mission-Stack — Auth-Token vor allen anderen, damit der
# Browser ihn ueberhaupt holen kann; danach REST + WS + PTY.
app.include_router(missions_auth_router)
+ # Seed the desktop session token (injected as window.__JARVIS_TOKEN by
+ # the fast-boot path) into the token store. The fast-boot token is a RAW
+ # secrets.token_urlsafe that is never issued via GET /token, so without
+ # this it fails validate_token → 4401 on every token-gated WebSocket —
+ # which hung the "Make It Yours" workspace PTY terminals forever on
+ # "connecting" (missions survive via the unauthenticated main /ws).
+ from .missions_auth import register_session_token_from_env
+
+ register_session_token_from_env(self.cfg.ui.auth_token_env)
app.include_router(missions_router)
app.include_router(missions_ws_router)
app.include_router(missions_pty_router)
@@ -380,7 +406,18 @@ class WebServer:
# Persist the latest state on this (long-lived) server instance for
# GET /api/voice/status to read — deliberately NOT on app.state, whose
# ASGI lifecycle could outrace the bus subscriber on shutdown.
- self._voice_ready = False
+ #
+ # When the local voice stack is disabled (JARVIS_VOICE=0 — headless,
+ # VPS, browser-mic-only), there is nothing to warm up and the pipeline
+ # never emits VoiceBootStatus, so seed ready=True. Otherwise the
+ # frontend's "starting up" banner would hang forever even though the
+ # user can already type (and use browser voice). A real voice pipeline
+ # starts at ready=False (warmup_start) and flips True via the subscriber
+ # below, so this seed only ever sticks when voice is genuinely off.
+ _voice_disabled = (
+ os.environ.get("JARVIS_VOICE", "").strip().lower() in ("0", "off", "false")
+ )
+ self._voice_ready = _voice_disabled
async def _track_voice_ready(event: VoiceBootStatus) -> None:
# A bus subscriber must never raise (AP-18); setting a plain
@@ -669,9 +706,18 @@ class WebServer:
"""
brain = getattr(app.state, "brain", None)
# BrainManager exposed `active_provider`. MockBrain hat nur `name`.
+ # Fast-boot deferral: the heavy BrainManager build runs in a
+ # background thread, so `app.state.brain` is None for the first
+ # ~850 ms while uvicorn already serves. In that window fall back to
+ # the configured primary provider — it already names the brain that
+ # WILL become active — instead of "unknown", which would freeze the
+ # sidebar footer on a bare "—" until a manual provider switch (the
+ # mount-fetch is one-shot and nothing re-fetches once the build
+ # finishes).
provider = (
getattr(brain, "active_provider", None)
or getattr(brain, "name", None)
+ or cfg.brain.primary
or "unknown"
)
prov_cfg = cfg.brain.providers.get(provider)
@@ -803,6 +849,27 @@ class WebServer:
key_set = bool(get_secret(secret_key, mapping.env_var))
except Exception: # noqa: BLE001
key_set = False
+ # Claude Max users authenticate the subagent via the LIVE OAuth
+ # login in ~/.claude/.credentials.json (read by ClaudeDirectWorker),
+ # not a stored API key — count that as configured so a fresh
+ # Claude-Max user (only ran `claude login`) is not falsely locked.
+ if not key_set and mapping.jarvis == "claude-api":
+ try:
+ from jarvis.missions.isolation.env import (
+ read_live_claude_oauth_token,
+ )
+
+ key_set = bool(read_live_claude_oauth_token())
+ except Exception: # noqa: BLE001
+ key_set = False
+ # claude-api is dual-billed like Codex/Antigravity: the Claude Max
+ # subscription (claude CLI OAuth login) OR an Anthropic API key.
+ # Every other MAPPINGS provider bills per token on an API account.
+ row_billing = (
+ "subscription_or_api"
+ if mapping.jarvis == "claude-api"
+ else "api"
+ )
mapping_rows.append(
{
"jarvis": mapping.jarvis,
@@ -811,6 +878,7 @@ class WebServer:
"env_fallback": mapping.env_fallback,
"key_set": key_set,
"is_active_brain": mapping.jarvis == primary,
+ "billing": row_billing,
}
)
@@ -841,30 +909,38 @@ class WebServer:
"env_fallback": "OPENAI_API_KEY",
"key_set": codex_connected or codex_key,
"is_active_brain": primary == "openai-codex",
+ # ChatGPT subscription OAuth OR an OpenAI API key.
+ "billing": "subscription_or_api",
}
)
# Antigravity is a DIRECT worker (GoogleCliWorker over the official
# agy/Gemini CLI) with no OpenClaw slug, so it is not in MAPPINGS —
- # the Google sibling of Codex. Surface it as an explicit selectable
- # subagent row, backed by the Google subscription OAuth login (no API
- # key): "key_set" is the connected state. Selecting it routes heavy
- # tasks through agy; selecting any other provider routes through that
- # one — the choice is never hardcoded (init._select_subagent_worker_kind).
+ # the Google sibling of Codex. Dual billing, mirror of Codex: the
+ # Google subscription OAuth login OR a Gemini API key (per token).
+ # "key_set" is true when either is present.
try:
from jarvis.google_cli.auth_service import GoogleCliAuthService
antigravity_connected = GoogleCliAuthService().status().connected
except Exception: # noqa: BLE001
antigravity_connected = False
+ try:
+ antigravity_key = bool(
+ get_secret("gemini_api_key", env_fallback="GEMINI_API_KEY")
+ )
+ except Exception: # noqa: BLE001
+ antigravity_key = False
mapping_rows.append(
{
"jarvis": "antigravity",
"openclaw": "agy-cli (direct)",
"env_var": "Google-OAuth",
- "env_fallback": None,
- "key_set": antigravity_connected,
+ "env_fallback": "GEMINI_API_KEY",
+ "key_set": antigravity_connected or antigravity_key,
"is_active_brain": primary == "antigravity",
+ # Google subscription OAuth OR a Gemini API key.
+ "billing": "subscription_or_api",
}
)
@@ -1572,6 +1648,18 @@ class WebServer:
)
_boot_mark("screenshot_retention")
+ # Flight-recorder audit log: attach the wildcard JSONL event recorder so
+ # there is a replayable audit trail of what Jarvis did (every event,
+ # incl. every Computer-Use action). It was defined but never wired at
+ # boot, so telemetry.flight_recorder=true logged nothing (audit #14).
+ try:
+ await self._init_flight_recorder()
+ except Exception as exc: # noqa: BLE001
+ logger.opt(exception=exc).warning(
+ "Flight recorder init failed — the audit log will be inactive"
+ )
+ _boot_mark("flight_recorder")
+
# Phase B5 wiki write-wiring — SessionRollupWorker + WikiCurator.
# Subscribes to IdleEntered; gracefully disabled when wiki_integration
# is not configured or enabled is False.
@@ -1731,11 +1819,17 @@ class WebServer:
self._pending_reloads.clear()
async def _run_deferred_reloads() -> None:
- # Let BOOT_READY emit and the first requests settle before the
- # blocking scans start their worker thread — otherwise the scan
- # CPU contends with the pre-ready window via the start_overlay
- # yield. The views tolerate an empty registry for this brief gap.
- await asyncio.sleep(0.3)
+ # Yield until the wake model is loaded before these blocking disk
+ # scans (DocRegistry FTS build ~5 s) start their worker thread —
+ # otherwise they steal CPU/disk from the custom-wake base/cpu
+ # model load and ~double its time (measured: base load 3.2 s
+ # isolated vs ~8 s racing this scan). NO-OP on headless / voice-off
+ # (returns immediately — no regress); bounded so a stuck wake load
+ # never blocks the scans. The views tolerate an empty registry for
+ # this brief gap.
+ from jarvis.core import runtime_refs as _rr
+
+ await _rr.await_wake_model_ready(timeout=12.0)
for label, registry in pending:
try:
await asyncio.to_thread(registry.reload_sync)
@@ -1825,6 +1919,32 @@ class WebServer:
_boot_sweep_then_retain()
)
+ async def _init_flight_recorder(self) -> None:
+ """Attach the flight-recorder audit log to the EventBus (ADR-0007).
+
+ Writes every event as a JSONL line under ``data/flight_recorder/`` — a
+ replayable audit trail of what Jarvis did, including every Computer-Use
+ action. Gated on ``telemetry.flight_recorder`` (default on); the recorder
+ is held on ``app.state`` for later flush/close on shutdown. The recorder
+ auto-flushes every second, and oversized event blobs land under
+ ``blobs/`` which the screenshot-retention task already prunes.
+ """
+ from jarvis.telemetry.recorder import attach_flight_recorder
+
+ rec = attach_flight_recorder(
+ self.bus,
+ enabled=self.cfg.telemetry.flight_recorder,
+ data_dir=Path("data") / "flight_recorder",
+ )
+ if rec is None:
+ logger.info("Flight recorder disabled (telemetry.flight_recorder=false)")
+ return
+ self._flight_recorder = rec
+ self.app.state.flight_recorder = rec
+ logger.info(
+ "Flight recorder attached — events -> data/flight_recorder/*.jsonl"
+ )
+
async def _init_mission_stack(self) -> None:
"""Phase-6 Production-Wiring: bootstrap_missions() liefert den
kompletten Stack (Manager, Kontrollierer, Budget, Voice-Listener,
@@ -1893,6 +2013,9 @@ class WebServer:
self.app.state.kontrollierer = result["kontrollierer"]
self.app.state.missions_budget = result["budget"]
self.app.state.mission_announcer = result["mission_announcer"]
+ # Mission-Bus -> global-bus bridge that re-publishes terminal missions
+ # as MissionCompleted so the Tasks scheduler can drive When-Then rules.
+ self.app.state.mission_event_bridge = result["mission_event_bridge"]
# outputs_routes.py uses this to render the Outputs view; it would
# otherwise have to re-derive the same WEB_DIR.parent.parent.parent
# walk and would silently drift if the launcher layout changes.
@@ -2445,6 +2568,17 @@ class WebServer:
)
self._screenshot_retention_task = None
+ # Flush + close the flight-recorder audit log so the last buffered events
+ # reach disk before shutdown (it otherwise auto-flushes every ~1s).
+ recorder = getattr(self, "_flight_recorder", None)
+ if recorder is not None:
+ try:
+ await recorder.flush()
+ await recorder.close()
+ except Exception as exc: # noqa: BLE001 — shutdown best-effort
+ logger.opt(exception=exc).debug("Flight recorder close: {}", exc)
+ self._flight_recorder = None
+
# Finalize in-flight missions BEFORE the store closes: a restart used
# to kill the process with missions still running, leaving them
# non-terminal until the recovery re-sweep buried them 30 min later as
diff --git a/jarvis/ui/web/sessions_routes.py b/jarvis/ui/web/sessions_routes.py
index f401bab7ec..db413e30d0 100644
--- a/jarvis/ui/web/sessions_routes.py
+++ b/jarvis/ui/web/sessions_routes.py
@@ -4,7 +4,7 @@ Endpoints:
GET /api/sessions Liste (neueste zuerst, max 100)
GET /api/sessions/{session_id} Detail mit Turns + Roh-Events
GET /api/sessions/{session_id}/export Markdown / Plain-Text fuer Copy
- POST /api/sessions/{session_id}/save Schreibt Datei ins Windows-Downloads-Verz.
+ POST /api/sessions/{session_id}/save Writes a file to the user's Downloads folder
Wird vom WebServer in ``_build_app()`` eingehaengt::
@@ -19,8 +19,10 @@ Loopback-only (Server bindet auf 127.0.0.1) — kein Auth-Token noetig.
"""
from __future__ import annotations
+import asyncio
import logging
import re
+import tempfile
from datetime import datetime
from pathlib import Path
from typing import Literal
@@ -152,16 +154,16 @@ async def save_session_to_downloads(
default="markdown", alias="format"
),
) -> SaveSessionResponse:
- """Schreibt die Session als Datei in den Windows-Downloads-Ordner.
+ """Write the session as a file into the user's Downloads folder.
- Pfad: ``%USERPROFILE%\\Downloads\\voice-session-YYYY-MM-DD_HH-mm-{slug}.{ext}``.
- Bei Kollision wird ein Suffix ``-1``, ``-2``, ... angehaengt — niemals
- ueberschreiben, keine Datenverluste.
+ Path: ``<home>/Downloads/voice-session-YYYY-MM-DD_HH-mm-{slug}.{ext}`` —
+ cross-platform via ``Path.home()`` (Windows, macOS, Linux). On a collision a
+ ``-1``, ``-2`` … suffix is appended — never overwrites, no data loss.
- Begruendung: Browser-Downloads in pywebview/WebView2 landen in einem
- Edge-internen Pfad, nicht zwingend im Windows-Default. Indem das
- Backend direkt schreibt, kontrollieren wir den Zielort und melden
- den vollen absoluten Pfad zurueck — User sieht klar wo die Datei liegt.
+ Rationale: pywebview/WebView2 silently cancels browser downloads unless
+ ``settings['ALLOW_DOWNLOADS']`` is enabled, and even then forces a Save-As
+ dialog. Writing from the backend lands the file directly in Downloads and
+ reports the absolute path back, so the user sees exactly where it is.
"""
store = _require_store(request)
session = store.get_session(session_id)
@@ -203,6 +205,90 @@ async def save_session_to_downloads(
)
+# ----------------------------------------------------------------------
+# Open-in-editor — materialize the transcript to a temp file, then launch
+# the chosen app (System default / Browser / VS Code / Cursor / …).
+# ----------------------------------------------------------------------
+
+
+class OpenWithBody(BaseModel):
+ """Open-in-editor request — the opener id chosen in the chooser dialog."""
+
+ opener: str
+
+
[email protected]("/{session_id}/open-with")
+async def open_session_with(
+ session_id: str,
+ body: OpenWithBody,
+ request: Request,
+ export_format: Literal["markdown", "plain", "json"] = Query(
+ default="markdown", alias="format"
+ ),
+) -> dict:
+ """Open the session transcript in a local app (editor / default / browser).
+
+ Desktop-only — gated on ``native_file_actions`` (a headless VPS would launch
+ on the *server's* desktop; the frontend opens the export URL in a browser tab
+ there instead). The transcript is rendered to a stable file under the OS temp
+ dir (re-opening the same session+format overwrites it — no clutter), then
+ launched via the cross-platform ``open_path`` helpers.
+
+ ``opener`` must be one of the closed opener-id set shared with the Outputs
+ view (``default`` | ``browser`` | an editor key) — never a raw path, so this
+ cannot launch an arbitrary client-supplied binary.
+ """
+ if not getattr(request.app.state, "native_file_actions", False):
+ raise HTTPException(status_code=404, detail="native-file-actions-disabled")
+
+ # Reuse the Outputs view's opener resolver + closed id set (the security
+ # boundary) so the chosen editor/preference is shared across both views.
+ from jarvis.platform import open_path
+ from jarvis.ui.web.outputs_routes import _known_opener_ids, _resolve_opener
+
+ opener = (body.opener or "").strip()
+ if opener not in _known_opener_ids():
+ raise HTTPException(status_code=400, detail=f"unknown opener: {opener}")
+
+ store = _require_store(request)
+ session = store.get_session(session_id)
+ if session is None:
+ raise HTTPException(status_code=404, detail="session-not-found")
+ turns = store.get_turns(session_id)
+ events = store.get_events(session_id)
+
+ if export_format == "markdown":
+ rendered = format_session_markdown(session, turns, events)
+ elif export_format == "plain":
+ rendered = format_session_plain(session, turns, events)
+ else:
+ detail = SessionDetail(session=session, turns=turns, events=events)
+ rendered = detail.model_dump_json(indent=2)
+
+ first_user = next((t.user_text for t in turns if t.user_text), "")
+ filename = _build_filename(session, first_user, export_format)
+ transcripts_dir = Path(tempfile.gettempdir()) / "jarvis-transcripts"
+ transcripts_dir.mkdir(parents=True, exist_ok=True)
+ target = transcripts_dir / filename
+ target.write_text(rendered, encoding="utf-8")
+
+ resolved = _resolve_opener(opener)
+ if resolved is None:
+ raise HTTPException(status_code=409, detail=f"opener not available: {opener}")
+ kind, value = resolved
+ if kind == "default":
+ opened = await asyncio.to_thread(open_path.open_file, target)
+ else:
+ opened = await asyncio.to_thread(
+ open_path.open_file_with, target, kind, value
+ )
+ log.info(
+ "SessionOpenWith: opener=%s format=%s session=%s -> %s (opened=%s)",
+ opener, export_format, session_id, target, opened,
+ )
+ return {"opened": bool(opened), "opener": opener, "path": str(target)}
+
+
# --- Helpers ----------------------------------------------------------
diff --git a/jarvis/ui/web/settings_routes.py b/jarvis/ui/web/settings_routes.py
index a33dc3aa74..948b3bc8cd 100644
--- a/jarvis/ui/web/settings_routes.py
+++ b/jarvis/ui/web/settings_routes.py
@@ -26,6 +26,8 @@ from __future__ import annotations
import asyncio
import logging
+import threading
+from collections.abc import Callable
from typing import TYPE_CHECKING
from fastapi import APIRouter, HTTPException, Request
@@ -250,6 +252,81 @@ async def put_ui_language(body: UiLanguageBody, request: Request) -> dict[str, o
return {"ok": True, "language": lang, "persisted": persisted}
+# ----------------------------------------------------------------------
+# STT recognition language — the language Whisper TRANSCRIBES the user's voice
+# into. Distinct from BOTH the UI language (what the user sees) and the reply
+# language (what Jarvis answers in). ``auto`` lets Whisper detect the spoken
+# language per utterance (the bilingual default); a concrete code forces it.
+# This had NO UI/REST control before — the recognition language was stranded in
+# jarvis.toml, so a user whose voice was mis-recognized had no way to fix it
+# (forensic 2026-06-28: German spoken, English-only model, "Can't you me" garbage).
+# Applies on the next voice bootstrap (a restart); the STT provider is built once.
+# ----------------------------------------------------------------------
+
+_STT_LANGUAGES: tuple[str, ...] = ("auto", "de", "en", "es")
+
+
+class SttLanguageBody(BaseModel):
+ language: str = Field(..., min_length=1)
+ persist: bool = Field(default=True, description="Persist as boot default in jarvis.toml")
+
+
+def _current_stt_language(request: Request) -> str:
+ # Read fresh from disk so a value just written is reflected; fall back to the
+ # boot config, then the "auto" bilingual default.
+ try:
+ from jarvis.core.config import load_config
+
+ return str(getattr(load_config().stt, "language", "auto"))
+ except Exception as exc: # noqa: BLE001 — never 500 a settings read
+ log.debug("stt-language fresh read failed, using boot config: %s", exc)
+ cfg = getattr(request.app.state, "config", None)
+ return str(getattr(getattr(cfg, "stt", None), "language", "auto"))
+
+
[email protected]("/stt-language")
+async def get_stt_language(request: Request) -> dict[str, object]:
+ return {"language": _current_stt_language(request), "options": list(_STT_LANGUAGES)}
+
+
[email protected]("/stt-language")
+async def put_stt_language(body: SttLanguageBody, request: Request) -> dict[str, object]:
+ lang = (body.language or "").strip().lower()
+ if lang not in _STT_LANGUAGES:
+ raise HTTPException(
+ status_code=400,
+ detail=f"Unknown STT language {body.language!r} (allowed: {list(_STT_LANGUAGES)})",
+ )
+
+ persisted = False
+ if body.persist:
+ try:
+ from jarvis.core import config_writer
+ from jarvis.core.config import resolve_config_path
+
+ config_writer.set_stt_language(lang, path=resolve_config_path())
+ persisted = True
+ except Exception as exc: # noqa: BLE001 — persist is best-effort
+ log.warning("stt-language persist failed: %s", exc)
+
+ cfg = getattr(request.app.state, "config", None)
+ if cfg is not None and getattr(cfg, "stt", None) is not None:
+ try:
+ cfg.stt.language = lang # type: ignore[attr-defined]
+ except Exception as exc: # noqa: BLE001 — frozen model is not an error
+ log.debug("in-memory cfg.stt.language update skipped: %s", exc)
+
+ # The STT provider is built once at voice bootstrap, so a live turn keeps the
+ # old language until the next voice restart. ``restart_required`` tells the UI
+ # to surface that hint.
+ return {
+ "ok": True,
+ "language": lang,
+ "persisted": persisted,
+ "restart_required": True,
+ }
+
+
# ---------------------------------------------------------------------------
# Wake word (custom-wake-word feature). GET current + options; PUT to switch.
# Persisted to jarvis.toml [trigger.wake_word]; applies on the next voice
@@ -747,7 +824,7 @@ async def put_autostart(body: AutostartBody, request: Request) -> dict[str, obje
}
-_OVERLAY_STYLES = ("whisper_bar", "mascot", "none")
+_OVERLAY_STYLES = ("jarvis_bar", "mascot", "none")
class OverlayStyleBody(BaseModel):
@@ -760,19 +837,23 @@ async def get_overlay_style(request: Request) -> dict[str, object]:
"""Current on-screen overlay style + the selectable options."""
cfg = _config(request)
ui = getattr(cfg, "ui", None)
- current = getattr(ui, "orb_style", None) or "whisper_bar"
+ current = getattr(ui, "orb_style", None) or "jarvis_bar"
return {"style": current, "options": list(_OVERLAY_STYLES)}
@router.put("/overlay-style")
async def put_overlay_style(body: OverlayStyleBody, request: Request) -> dict[str, object]:
- """Switch the on-screen overlay (whisper_bar / mascot / none).
+ """Switch the on-screen overlay (jarvis_bar / mascot / none).
Persists [ui].orb_style and live-swaps the running surface via the
DesktopApp (app.state.desktop_app.swap_overlay). When no live app is
reachable (headless), the choice is persisted and applies on restart.
"""
style = body.style.strip()
+ # Backwards-compat: accept the legacy "whisper_bar" value (renamed to
+ # "jarvis_bar" to drop a trademarked name) from any not-yet-rebuilt client.
+ if style == "whisper_bar":
+ style = "jarvis_bar"
if style not in _OVERLAY_STYLES:
raise HTTPException(status_code=400, detail=f"Unknown overlay style '{style}'")
@@ -972,6 +1053,45 @@ async def _running_mission_summaries(
return summaries
+async def _run_off_pool(fn: Callable[[], object]) -> object:
+ """Run a quick blocking callable on a fresh, dedicated thread.
+
+ Deliberately does NOT use ``asyncio.to_thread`` / the shared default
+ ``ThreadPoolExecutor``. A restart is the app's recovery path and must keep
+ working precisely *when the app is unhealthy* — including when that shared
+ pool is exhausted by un-cancellable hung threads.
+
+ Forensic 2026-06-29: the custom-wake ctranslate2 transcription hung inside
+ C code; its 8 s ``asyncio.timeout`` cancelled only the *await*, abandoning
+ the pool thread mid-call (a running thread can't be killed in Python). The
+ 8 s re-poll storm leaked one default-pool worker every cycle until every
+ worker was wedged, so ``await asyncio.to_thread(request_restart)`` queued
+ behind the dead pool forever — the restart POST never returned and the
+ button spun "Restarting…" with the window still up. A dedicated thread is
+ immune to that starvation. Cross-platform: pool exhaustion hits any host
+ (a slow CPU-only Whisper on a VPS reaches the same wall as a stuck GPU one).
+ """
+ loop = asyncio.get_running_loop()
+ fut: asyncio.Future[object] = loop.create_future()
+
+ def _runner() -> None:
+ try:
+ result = fn()
+ except BaseException as exc: # noqa: BLE001 — relay verbatim to the awaiter
+ loop.call_soon_threadsafe(_resolve, fut.set_exception, exc)
+ else:
+ loop.call_soon_threadsafe(_resolve, fut.set_result, result)
+
+ def _resolve(setter: Callable[[object], None], value: object) -> None:
+ if not fut.done(): # awaiter may have been cancelled meanwhile
+ setter(value)
+
+ threading.Thread(
+ target=_runner, name="jarvis-restart-trigger", daemon=True
+ ).start()
+ return await fut
+
+
@router.post("/restart-app")
async def restart_app(request: Request, force: bool = False) -> dict[str, object]:
"""Cleanly self-restart the desktop app.
@@ -997,7 +1117,15 @@ async def restart_app(request: Request, force: bool = False) -> dict[str, object
running = list(list_running()) if callable(list_running) else []
if running:
manager = getattr(request.app.state, "mission_manager", None)
- missions = await _running_mission_summaries(manager, running)
+ try:
+ # A wedged mission manager (the very state a user restarts to
+ # escape) must not hang the guard — bound the title lookup and
+ # fall back to id-only summaries so the 409 still reaches the UI.
+ missions = await asyncio.wait_for(
+ _running_mission_summaries(manager, running), timeout=2.0
+ )
+ except TimeoutError:
+ missions = [{"id": mid, "title": ""} for mid in running]
raise HTTPException(
status_code=409,
detail={"error": "missions_running", "missions": missions},
@@ -1009,7 +1137,10 @@ async def restart_app(request: Request, force: bool = False) -> dict[str, object
raise HTTPException(
status_code=503, detail="self-restart unavailable on this host"
)
- scheduled = await asyncio.to_thread(fn)
+ # Off the shared default pool — a restart must survive a pool exhausted by
+ # hung threads (see ``_run_off_pool``). ``asyncio.to_thread`` would queue
+ # behind the dead pool and hang the POST forever.
+ scheduled = await _run_off_pool(fn)
if not scheduled:
raise HTTPException(
status_code=503, detail="no desktop window to restart"
@@ -1017,6 +1148,39 @@ async def restart_app(request: Request, force: bool = False) -> dict[str, object
return {"ok": True, "restarting": True}
+class OpenExternalBody(BaseModel):
+ url: str = Field(min_length=1, max_length=4096)
+
+
[email protected]("/open-external")
+async def open_external(body: OpenExternalBody) -> dict[str, object]:
+ """Open an ``http(s)`` URL in the user's real default browser.
+
+ The desktop shell embeds WebView2, which silently drops ``window.open`` /
+ ``target="_blank"`` — so OAuth-authorize and token-creation pages never
+ reached the browser and plugin connect appeared to "do nothing". The
+ frontend calls this only when it detects the embedded shell (``window
+ .__JARVIS_TOKEN``); a real browser tab opens the URL itself. Returns
+ ``{"opened": false}`` on a headless host (no display) so the caller can
+ fall back to ``window.open``.
+
+ Scheme is validated to ``http``/``https`` here AND in ``open_url`` so no
+ ``file:``/``javascript:``/app-protocol URL can ever be launched.
+ """
+ from urllib.parse import urlparse
+
+ parsed = urlparse(body.url)
+ if parsed.scheme.lower() not in ("http", "https"):
+ raise HTTPException(
+ status_code=400, detail="only http/https URLs may be opened"
+ )
+ from jarvis.platform.open_path import open_url
+
+ opened = await asyncio.to_thread(open_url, body.url)
+ log.info("open-external: opened=%s url=%s", opened, body.url)
+ return {"opened": bool(opened)}
+
+
# ---------------------------------------------------------------------------
# Taskbar section toggles: "Show bar at all times" (bar_persistent, live) and
# "Mute music while dictating" (ducking.enabled, live). Both persist to
diff --git a/jarvis/ui/web/telephony_routes.py b/jarvis/ui/web/telephony_routes.py
index 3b136d620f..162187054e 100644
--- a/jarvis/ui/web/telephony_routes.py
+++ b/jarvis/ui/web/telephony_routes.py
@@ -288,30 +288,46 @@ async def post_test(request: Request) -> JSONResponse:
"error": "twilio package not installed (pip install -e .[telephony])",
}
)
+ # M3: prefer credentials typed in the form body (test-before-save) over the
+ # persisted ones, so clicking Test with fresh creds validates THOSE — not stale
+ # or absent saved values that read as a broken key.
+ try:
+ body = await request.json()
+ if not isinstance(body, dict):
+ body = {}
+ except Exception: # noqa: BLE001 — no/empty body → fall back to persisted
+ body = {}
twilio = _twilio_cfg(request)
- account_sid = getattr(twilio, "account_sid", "") or ""
- token = _auth_token()
+ account_sid = (str(body.get("account_sid") or "").strip()
+ or (getattr(twilio, "account_sid", "") or ""))
+ token = str(body.get("auth_token") or "").strip() or _auth_token()
mgr = _manager(request)
+ # M4: honest five-layer status (PROVIDER_TEST_STATUSES) instead of a binary
+ # ok/failed — bad SID, unfunded/suspended account, and an outage are different.
+ from jarvis.brain.provider_test import classify_provider_error
+
if not account_sid or not token:
mgr.set_reachable(False, "account_sid or auth_token missing")
- return JSONResponse(
- {"ok": False, "reachable": False, "error": "account_sid or auth_token missing"}
- )
+ return JSONResponse({
+ "ok": False, "reachable": False, "status": "not_configured",
+ "error": "account_sid or auth_token missing",
+ })
try:
from jarvis.telephony.provisioning import verify_credentials
info = verify_credentials(account_sid, token)
mgr.set_reachable(True, None)
- return JSONResponse(
- {
- "ok": True,
- "reachable": True,
- "account_status": info.get("account_status", ""),
- }
- )
+ return JSONResponse({
+ "ok": True, "reachable": True, "status": "ok",
+ "account_status": info.get("account_status", ""),
+ })
except Exception as exc: # noqa: BLE001
mgr.set_reachable(False, str(exc))
- return JSONResponse({"ok": False, "reachable": False, "error": str(exc)})
+ return JSONResponse({
+ "ok": False, "reachable": False,
+ "status": classify_provider_error(str(exc)),
+ "error": str(exc),
+ })
# ---------------------------------------------------------------------------
@@ -407,12 +423,25 @@ async def get_scripts(request: Request) -> JSONResponse:
webhook = public_url_for(base, "/api/telephony/voice")
scripts = [
{
- "name": "Public tunnel (dev)",
+ # M7: cross-platform tunnel command (Linux/macOS/Windows) — the
+ # PowerShell script below is Windows-only and was the ONLY option
+ # shown to every OS. Needs `cloudflared` installed.
+ "name": "Public tunnel (portable)",
+ "path": "",
+ "description": (
+ "Start a cloudflared tunnel to the local FastAPI port and copy the "
+ "printed https URL into 'public_base_url'. Works on Linux, macOS and "
+ "Windows (install cloudflared first)."
+ ),
+ "command": f"cloudflared tunnel --url http://localhost:{port}",
+ },
+ {
+ "name": "Public tunnel (Windows dev)",
"path": "scripts/telephony-tunnel.ps1",
"description": (
"Start a cloudflared tunnel to the local FastAPI port and print "
"the public HTTPS URL to paste into 'public_base_url'. Home-PC "
- "development path."
+ "development path (Windows PowerShell)."
),
"command": f"pwsh scripts/telephony-tunnel.ps1 -Port {port}",
},
diff --git a/jarvis/ui/web/workspace_routes.py b/jarvis/ui/web/workspace_routes.py
new file mode 100644
index 0000000000..b7b6cf5cd9
--- /dev/null
+++ b/jarvis/ui/web/workspace_routes.py
@@ -0,0 +1,214 @@
+"""REST + WebSocket API for the "Make It Yours" multi-agent workspace.
+
+The terminals are embedded in the desktop app (xterm panes), so launching does
+not open OS windows — it pre-trusts the folder and returns a per-slot plan; each
+slot then connects to the PTY WebSocket below, which runs the agent in a real
+PTY inside the Jarvis project folder.
+
+Endpoints (prefix ``/api/workspace``):
+- ``GET /agents`` → detect Claude Code + Codex (installed? version?)
+- ``POST /launch`` → validate + pre-trust + return the grid plan (slots)
+- ``WS /pty/{key}`` → interactive PTY running one agent (or its installer)
+"""
+from __future__ import annotations
+
+import asyncio
+import logging
+
+from fastapi import APIRouter, HTTPException, WebSocket, WebSocketDisconnect
+from pydantic import BaseModel, Field
+
+from jarvis.core.paths import repo_root
+from jarvis.terminal.pty_manager import PtyManager
+from jarvis.workspace.agents import (
+ AGENT_NAMES,
+ build_agent_argv,
+ build_install_argv,
+ detect_agents,
+ pty_available,
+)
+from jarvis.workspace.launcher import LAYOUT_CHOICES, plan_workspace, validate_split
+from jarvis.workspace.trust import ensure_trusted
+
+from .missions_auth import validate_token
+
+log = logging.getLogger(__name__)
+
+router = APIRouter(prefix="/api/workspace", tags=["workspace"])
+
+
+# --------------------------------------------------------------------------- #
+# REST #
+# --------------------------------------------------------------------------- #
+class AgentStatusModel(BaseModel):
+ name: str
+ display_name: str
+ installed: bool
+ version: str | None
+ install_command: str | None
+ launch_command: str
+
+
+class AgentsResponse(BaseModel):
+ cwd: str
+ terminal_available: bool
+ layout_choices: list[int]
+ agents: list[AgentStatusModel]
+
+
+class LaunchRequest(BaseModel):
+ layout: int
+ split: dict[str, int] = Field(default_factory=dict)
+
+
[email protected]("/agents", response_model=AgentsResponse)
+async def get_agents() -> AgentsResponse:
+ infos = await detect_agents()
+ return AgentsResponse(
+ cwd=str(repo_root()),
+ terminal_available=pty_available(),
+ layout_choices=list(LAYOUT_CHOICES),
+ agents=[
+ AgentStatusModel(
+ name=i.name,
+ display_name=i.display_name,
+ installed=i.installed,
+ version=i.version,
+ install_command=i.install_command,
+ launch_command=i.launch_command,
+ )
+ for i in infos
+ ],
+ )
+
+
+async def launch(req: LaunchRequest) -> dict:
+ try:
+ validate_split(req.layout, req.split)
+ except ValueError as exc:
+ raise HTTPException(status_code=422, detail=str(exc)) from exc
+ return plan_workspace(req.layout, req.split).to_dict()
+
+
+# --------------------------------------------------------------------------- #
+# PTY WebSocket #
+# --------------------------------------------------------------------------- #
+def _pty_manager(app) -> PtyManager: # noqa: ANN001
+ mgr = getattr(app.state, "workspace_pty", None)
+ if mgr is None:
+ mgr = PtyManager()
+ app.state.workspace_pty = mgr
+ return mgr
+
+
[email protected]("/pty/{key}")
+async def workspace_pty(ws: WebSocket, key: str) -> None:
+ """Run one agent (``?agent=claude``) or its installer (``?install=codex``) in
+ a PTY, bridged bidirectionally to an xterm pane.
+
+ Wire protocol (JSON both ways): client → ``{t:"i",d}`` input,
+ ``{t:"r",cols,rows}`` resize; server → ``{t:"o",d}`` output, ``{t:"ready"}``,
+ ``{t:"exit",code}``, ``{t:"error",message}``."""
+ await ws.accept()
+ qp = ws.query_params
+
+ if not validate_token(qp.get("token", "")):
+ await ws.close(code=4401, reason="unauthorized")
+ return
+
+ agent = qp.get("agent")
+ install = qp.get("install")
+ cols = _safe_int(qp.get("cols"), 80)
+ rows = _safe_int(qp.get("rows"), 24)
+ cwd = str(repo_root())
+
+ if agent:
+ if agent not in AGENT_NAMES:
+ await ws.close(code=4400, reason="unknown agent")
+ return
+ ensure_trusted(repo_root(), [agent]) # idempotent, skips the trust dialog
+ argv = build_agent_argv(agent)
+ elif install:
+ if install not in AGENT_NAMES:
+ await ws.close(code=4400, reason="unknown agent")
+ return
+ argv = build_install_argv(install)
+ else:
+ await ws.close(code=4400, reason="missing agent/install")
+ return
+
+ if argv is None:
+ await ws.send_json({"t": "error", "message": "No shell available on this host."})
+ await ws.close(code=4404, reason="no shell")
+ return
+
+ mgr = _pty_manager(ws.scope["app"])
+ send_lock = asyncio.Lock()
+
+ async def on_output(_tid: str, text: str) -> None:
+ async with send_lock:
+ try:
+ await ws.send_json({"t": "o", "d": text})
+ except Exception: # noqa: BLE001 - client gone; reader will stop
+ pass
+
+ async def on_closed(_tid: str, code: int) -> None:
+ async with send_lock:
+ try:
+ await ws.send_json({"t": "exit", "code": code})
+ except Exception: # noqa: BLE001
+ pass
+
+ try:
+ session = await mgr.spawn(
+ shell_argv=argv,
+ shell_id="workspace",
+ cwd=cwd,
+ cols=cols,
+ rows=rows,
+ on_output=on_output,
+ on_closed=on_closed,
+ )
+ except Exception as exc: # noqa: BLE001
+ await ws.send_json({"t": "error", "message": str(exc)})
+ await ws.close(code=4500, reason="spawn failed")
+ return
+
+ await ws.send_json({"t": "ready"})
+
+ try:
+ while True:
+ try:
+ msg = await ws.receive_json()
+ except WebSocketDisconnect:
+ break
+ except RuntimeError:
+ # AP-20: an unclean teardown raises RuntimeError, not
+ # WebSocketDisconnect — treat any read error as terminal.
+ break
+ except Exception: # noqa: BLE001 - malformed frame; keep the PTY alive
+ continue
+ kind = msg.get("t")
+ if kind == "i":
+ mgr.write(session.terminal_id, str(msg.get("d", "")))
+ elif kind == "r":
+ mgr.resize(
+ session.terminal_id,
+ _safe_int(msg.get("cols"), cols),
+ _safe_int(msg.get("rows"), rows),
+ )
+ # other frames are ignored
+ finally:
+ mgr.close(session.terminal_id)
+
+
+def _safe_int(value: object, default: int) -> int:
+ try:
+ n = int(str(value))
+ return n if n > 0 else default
+ except (TypeError, ValueError):
+ return default
+
+
+__all__ = ["router"]