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(brain,ui): turn-planner + brain manager updates, desktop brain-call compat

Ruben Lütke89e5aee0e020
diff --git a/jarvis/brain/manager.py b/jarvis/brain/manager.py
index 9fa36bbbf1..1fd09b1cc5 100644
--- a/jarvis/brain/manager.py
+++ b/jarvis/brain/manager.py
@@ -6856,6 +6856,7 @@ class BrainManager:
source_layer: str | None = None,
allow_voice_confirm: bool = False,
prefer_tool_model: bool = False,
+ emit_tool_ack: bool = True,
publish_response: bool = True,
history_override: Iterable[BrainMessage] | None = None,
) -> str:
@@ -6882,6 +6883,7 @@ class BrainManager:
source_layer=source_layer,
allow_voice_confirm=allow_voice_confirm,
prefer_tool_model=prefer_tool_model,
+ emit_tool_ack=emit_tool_ack,
)
finally:
_TURN_HISTORY_OVERRIDE.reset(history_token)
@@ -6898,6 +6900,7 @@ class BrainManager:
source_layer: str | None = None,
allow_voice_confirm: bool = False,
prefer_tool_model: bool = False,
+ emit_tool_ack: bool = True,
) -> str:
# 1. Intercept meta-commands (cancel, switch, depth override).
# User request 2026-04-25: no standardised confirmation phrases
@@ -7541,7 +7544,9 @@ class BrainManager:
# provider-chain retry cannot double-announce. The loop fires it the
# moment a tool is actually selected; None when the feature is off or
# this is a Voice-Control utterance.
- _tool_ack_emitter = self._build_tool_ack_emitter(user_text)
+ _tool_ack_emitter = (
+ self._build_tool_ack_emitter(user_text) if emit_tool_ack else None
+ )
for idx, (prov_name, model) in enumerate(chain):
# Skip providers already marked dead in THIS turn.
diff --git a/jarvis/brain/turn_planner.py b/jarvis/brain/turn_planner.py
index dabfcde423..5c32ec233c 100644
--- a/jarvis/brain/turn_planner.py
+++ b/jarvis/brain/turn_planner.py
@@ -72,6 +72,8 @@ _DEFINITION_RE = re.compile(
_INSTRUCTIONAL_RE = re.compile(
r"\b(?:how (?:do|can|would) (?:i|you)|how to|"
r"wie (?:kann|koennte|wuerde) (?:ich|man)|" # i18n-allow: speech input
+ r"wie (?:kannst|koenntest|wuerdest) du|" # i18n-allow: speech input
+ r"wie (?:koennen|koennten|wuerden) sie|" # i18n-allow: speech input
r"como (?:puedo|se puede)|como hacer)\b" # i18n-allow: multilingual speech-input matching data
)
_OWNERSHIP_RE = re.compile(
@@ -266,6 +268,14 @@ def plan_turn(
reasons: set[TurnReason] = set()
definition = bool(_DEFINITION_RE.search(normalized))
instructional = bool(_INSTRUCTIONAL_RE.search(normalized))
+ # An instructional form asks for an explanation, even when the sentence
+ # also contains words that resemble an action, private ownership, or a
+ # current-time marker. For example, "How would you help me use ...?" must
+ # not execute the referenced action or fetch private/current evidence.
+ # Return early so none of the conservative evidence heuristics below can
+ # turn an advice question into an orchestrator-owned action.
+ if instructional:
+ return TurnPlan(path=TurnPath.NATIVE_REALTIME)
required = () if definition or instructional else _matched_capabilities(
text,
capability_registry=capability_registry,
diff --git a/jarvis/core/config.py b/jarvis/core/config.py
index 861016922a..a36f10220a 100644
--- a/jarvis/core/config.py
+++ b/jarvis/core/config.py
@@ -14,6 +14,7 @@ from __future__ import annotations
import json
import logging
import os
+import secrets
import sys
import threading
import tomllib
@@ -2485,6 +2486,12 @@ def load_config(
# installed ONLY when the current backend is the no-op fail.Keyring).
_KEYRING_BACKEND_READY: bool = False
_FILE_BACKEND_ACTIVE: bool = False
+# The platform backend that was active before a runtime failure forced the
+# process-wide ``keyring`` module onto our file backend. Retaining it matters
+# for mixed states: one failed write must not hide other credentials that are
+# still readable from the OS store, and recovery probes must not mistake the
+# currently installed file backend for a recovered platform backend.
+_PLATFORM_KEYRING_BACKEND: Any | None = None
_SECRET_REVISION_LOCK = threading.Lock()
_SECRET_REVISIONS: dict[str, int] = {}
@@ -2572,7 +2579,22 @@ class _FileCredStore:
self._save(data)
-def _install_file_cred_backend(reason: str) -> bool:
+def _is_platform_keyring_backend(backend: Any) -> bool:
+ """Return whether *backend* is a real platform credential-store candidate."""
+ if backend is None or getattr(backend, "_jarvis_file_backend", False):
+ return False
+ try:
+ # ``fail.Keyring`` advertises zero priority. Use that capability rather
+ # than an isinstance check against unpinned third-party internals.
+ priority = getattr(backend, "priority", None)
+ return priority is None or priority > 0
+ except Exception: # noqa: BLE001
+ return False
+
+
+def _install_file_cred_backend(
+ reason: str, *, retain_platform_backend: bool = True
+) -> bool:
"""Force the local 0600 file credential store as the active keyring backend.
Used both when NO OS keyring exists at all (headless VPS → ``fail.Keyring``)
@@ -2586,15 +2608,22 @@ def _install_file_cred_backend(reason: str) -> bool:
Returns True iff the file backend is now active.
"""
- global _FILE_BACKEND_ACTIVE
+ global _FILE_BACKEND_ACTIVE, _PLATFORM_KEYRING_BACKEND
try:
import keyring
import keyring.backend
+ current_backend = keyring.get_keyring()
+ if not retain_platform_backend:
+ _PLATFORM_KEYRING_BACKEND = None
+ elif _is_platform_keyring_backend(current_backend):
+ _PLATFORM_KEYRING_BACKEND = current_backend
+
_store = _FileCredStore()
class _FileKeyringBackend(keyring.backend.KeyringBackend):
priority = 0.1 # type: ignore[assignment] # below any real OS backend
+ _jarvis_file_backend = True
def get_password(self, service: str, username: str) -> str | None:
return _store.get(service, username)
@@ -2634,10 +2663,12 @@ def _ensure_keyring_backend() -> None:
_KEYRING_BACKEND_READY = True
try:
import keyring
- from keyring.backends import fail
- if isinstance(keyring.get_keyring(), fail.Keyring):
- _install_file_cred_backend("no OS credential store available (headless host)")
+ if not _is_platform_keyring_backend(keyring.get_keyring()):
+ _install_file_cred_backend(
+ "no OS credential store available (headless host)",
+ retain_platform_backend=False,
+ )
except Exception: # noqa: BLE001
pass
@@ -2657,12 +2688,13 @@ def _try_restore_platform_keyring_backend() -> bool:
add startup latency or prompts. Returns ``True`` when the platform backend
is active, including when no fallback swap had occurred.
"""
- global _FILE_BACKEND_ACTIVE
+ global _FILE_BACKEND_ACTIVE, _PLATFORM_KEYRING_BACKEND
if not _FILE_BACKEND_ACTIVE:
return True
keyring_mod = None
previous_backend = None
+ candidate = None
try:
import keyring as keyring_mod
from keyring.core import init_backend
@@ -2670,10 +2702,29 @@ def _try_restore_platform_keyring_backend() -> bool:
previous_backend = keyring_mod.get_keyring()
init_backend()
candidate = keyring_mod.get_keyring()
- # Capability probe, never an isinstance check against third-party
- # internals. A real backend returns None for this absent slot; fail or
- # locked backends raise and are rejected below.
- candidate.get_password(KEYRING_SERVICE, "__jarvis_backend_probe__")
+ if not _is_platform_keyring_backend(candidate):
+ raise RuntimeError("platform backend discovery found no usable backend")
+
+ # A read-only probe was insufficient on Windows: WinVault could read an
+ # old value while every write failed with error 1312. Use a unique,
+ # disposable entry and prove the full write/read/delete lifecycle.
+ probe_key = f"__jarvis_backend_probe__{secrets.token_hex(8)}"
+ probe_value = secrets.token_urlsafe(24)
+ try:
+ candidate.set_password(KEYRING_SERVICE, probe_key, probe_value)
+ if candidate.get_password(KEYRING_SERVICE, probe_key) != probe_value:
+ raise RuntimeError("platform credential-store probe read mismatch")
+ candidate.delete_password(KEYRING_SERVICE, probe_key)
+ if candidate.get_password(KEYRING_SERVICE, probe_key) is not None:
+ raise RuntimeError("platform credential-store probe delete failed")
+ except Exception:
+ # A backend may write and then raise, so cleanup is unconditional.
+ try:
+ candidate.delete_password(KEYRING_SERVICE, probe_key)
+ except Exception: # noqa: BLE001, S110 -- best-effort probe cleanup
+ pass
+ _PLATFORM_KEYRING_BACKEND = candidate
+ raise
except Exception: # noqa: BLE001 -- unavailable OS keyring is expected headlessly
if keyring_mod is not None and previous_backend is not None:
try:
@@ -2682,6 +2733,7 @@ def _try_restore_platform_keyring_backend() -> bool:
pass
return False
+ _PLATFORM_KEYRING_BACKEND = candidate
_FILE_BACKEND_ACTIVE = False
logging.getLogger(__name__).info(
"OS credential store recovered; future credential saves use the platform keyring."
@@ -2692,11 +2744,10 @@ def _try_restore_platform_keyring_backend() -> bool:
def get_secret(key: str, env_fallback: str | None = None) -> str | None:
"""Retrieve a secret value from every portable credential source.
- Priority is OS keyring → ENV → ``.env`` → local-file fallback.
- The final read-through is required even when a nominally working OS
- keyring returns ``None``: a previous in-app save may have fallen back to
- ``data/credentials.json`` while that keyring was temporarily unavailable.
- Without the read-through the saved key becomes invisible after restart.
+ Normal priority is OS keyring → ENV → ``.env`` → local-file
+ fallback. A fallback value for the same slot is newer than a stale OS copy,
+ while ENV and ``.env`` keep their documented precedence. This lets an
+ in-app save survive both a temporary keyring outage and the next restart.
Args:
key: Secret name in the Credential Manager (e.g. "anthropic_api_key").
@@ -2711,13 +2762,40 @@ def get_secret(key: str, env_fallback: str | None = None) -> str | None:
if env_fallback is None:
env_fallback = key.upper()
+ # A file value marks a later explicit save whose platform write failed. Read
+ # it up front so an older-but-readable OS value cannot shadow it after a
+ # restart. A later successful platform save removes this copy.
+ file_val: str | None = None
+ try:
+ file_val = _FileCredStore().get(KEYRING_SERVICE, key)
+ except Exception: # noqa: BLE001, S110 — unreadable fallback is absent
+ pass
+
+ platform_val: str | None = None
# Lazy import — keyring requires pywin32 on Windows
try:
import keyring
- val = keyring.get_password(KEYRING_SERVICE, key)
- if val:
- return val
+ active_val = keyring.get_password(KEYRING_SERVICE, key)
+ active_backend = keyring.get_keyring()
+ if _FILE_BACKEND_ACTIVE and getattr(
+ active_backend, "_jarvis_file_backend", False
+ ):
+ # The process-wide keyring now points at the file backend. Keep
+ # reading the retained platform backend for slots that never needed
+ # a fallback, so one failed write does not hide all OS credentials.
+ file_val = active_val or file_val
+ platform_backend = _PLATFORM_KEYRING_BACKEND
+ if (
+ platform_backend is not None
+ and _is_platform_keyring_backend(platform_backend)
+ ):
+ try:
+ platform_val = platform_backend.get_password(KEYRING_SERVICE, key)
+ except Exception: # noqa: BLE001 — locked platform stays fallback-only
+ platform_val = None
+ else:
+ platform_val = active_val
except Exception: # noqa: BLE001
# A reachable-but-locked OS keyring raises here even though
# _ensure_keyring_backend saw a viable backend. Degrade to the 0600 file
@@ -2727,12 +2805,16 @@ def get_secret(key: str, env_fallback: str | None = None) -> str | None:
try:
import keyring
- val = keyring.get_password(KEYRING_SERVICE, key)
- if val:
- return val
- except Exception: # noqa: BLE001
+ file_val = keyring.get_password(KEYRING_SERVICE, key) or file_val
+ except Exception: # noqa: BLE001, S110
pass
+ # Preserve OS-keyring-over-ENV precedence when this exact slot has no newer
+ # fallback value. When both copies exist, ENV/.env keep their documented
+ # precedence and the fallback copy beats only the stale OS copy.
+ if platform_val and not file_val:
+ return platform_val
+
if env_fallback and (val := os.environ.get(env_fallback)):
return val
@@ -2747,15 +2829,8 @@ def get_secret(key: str, env_fallback: str | None = None) -> str | None:
if k.strip() == env_fallback:
return v.strip().strip('"').strip("'")
- # Portable read-through. Do not replace a healthy OS backend merely because
- # it returned no value: consult the file store directly so a key written
- # during an earlier keyring outage remains recoverable after restart.
- try:
- val = _FileCredStore().get(KEYRING_SERVICE, key)
- if val:
- return val
- except Exception: # noqa: BLE001, S110 — unreadable fallback is absent
- pass
+ if file_val:
+ return file_val
return None
@@ -2847,12 +2922,29 @@ def set_secret(key: str, value: str) -> bool:
# When the installed backend IS the file fallback, deleting here would
# erase the value that was just written.
if not _FILE_BACKEND_ACTIVE:
+ store = _FileCredStore()
try:
- store = _FileCredStore()
- if store.get(KEYRING_SERVICE, key) is not None:
+ fallback_exists = store.get(KEYRING_SERVICE, key) is not None
+ except Exception: # noqa: BLE001 -- incomplete save must be reported
+ return False
+ if fallback_exists:
+ cleanup_succeeded = False
+ try:
store.delete(KEYRING_SERVICE, key)
- except Exception: # noqa: BLE001, S110 — secure write already succeeded
- pass
+ cleanup_succeeded = store.get(KEYRING_SERVICE, key) is None
+ except Exception: # noqa: BLE001 -- synchronize below
+ cleanup_succeeded = False
+ if not cleanup_succeeded:
+ # A stale fallback outranks the platform copy in
+ # ``get_secret``. If it cannot be removed, make both stores
+ # agree before reporting success; otherwise callers would
+ # immediately read the credential this save replaced.
+ try:
+ store.set(KEYRING_SERVICE, key, value)
+ if store.get(KEYRING_SERVICE, key) != value:
+ return False
+ except Exception: # noqa: BLE001
+ return False
_mark_secret_changed(key)
return True
except Exception as exc: # noqa: BLE001
@@ -2888,6 +2980,25 @@ def delete_secret(key: str) -> bool:
on the next boot. The ENV layer is read-only here and is never touched.
"""
_ensure_keyring_backend()
+
+ # When a platform failure swapped this process onto the file backend, the
+ # retained platform store is a second live copy. Delete and verify it first.
+ # If that cannot be confirmed, leave the newer file copy intact: removing it
+ # would immediately reveal the stale platform value through get_secret().
+ retained_backend = _PLATFORM_KEYRING_BACKEND
+ if _FILE_BACKEND_ACTIVE and _is_platform_keyring_backend(retained_backend):
+ try:
+ from keyring.errors import PasswordDeleteError
+
+ try:
+ retained_backend.delete_password(KEYRING_SERVICE, key)
+ except PasswordDeleteError:
+ pass
+ if retained_backend.get_password(KEYRING_SERVICE, key) is not None:
+ return False
+ except Exception: # noqa: BLE001
+ return False
+
keyring_ok = False
try:
import keyring
@@ -2895,13 +3006,16 @@ def delete_secret(key: str) -> bool:
try:
keyring.delete_password(KEYRING_SERVICE, key)
- keyring_ok = True
except PasswordDeleteError:
# Every backend we rely on raises this specifically when the
# entry is already absent (e.g. the Windows Credential Manager
# backend; the file-fallback backend's delete is idempotent and
# never raises at all) — "nothing to delete" is itself a success.
- keyring_ok = True
+ pass
+ # Some backends return success without deleting anything. Read the
+ # active backend back before removing a newer fallback copy or claiming
+ # that the secret is gone.
+ keyring_ok = keyring.get_password(KEYRING_SERVICE, key) is None
except Exception: # noqa: BLE001
# A genuine backend failure (locked Secret Service, transport
# error, ...). Deliberately do not retry via
@@ -2911,12 +3025,19 @@ def delete_secret(key: str) -> bool:
# the real OS-keyring entry survives untouched.
keyring_ok = False
+ if not keyring_ok and not _FILE_BACKEND_ACTIVE:
+ # The fallback is authoritative when both copies exist. Preserve it
+ # until the platform deletion can be confirmed; removing it here would
+ # immediately resurface the stale platform credential through
+ # ``get_secret`` and make a later retry impossible.
+ return False
+
file_ok = False
try:
store = _FileCredStore()
if store.get(KEYRING_SERVICE, key) is not None:
store.delete(KEYRING_SERVICE, key)
- file_ok = True
+ file_ok = store.get(KEYRING_SERVICE, key) is None
except Exception: # noqa: BLE001, S110
pass
if keyring_ok or file_ok:
diff --git a/jarvis/ui/desktop_app.py b/jarvis/ui/desktop_app.py
index 4c790bf7ba..e257775d83 100644
--- a/jarvis/ui/desktop_app.py
+++ b/jarvis/ui/desktop_app.py
@@ -14,6 +14,7 @@ CLI test run without ``jarvis.__main__``::
from __future__ import annotations
import asyncio
+import inspect
import json
import os
import secrets
@@ -61,6 +62,45 @@ WINDOW_TITLE = "Personal Jarvis"
_LOCK_ACQUIRE_TIMEOUT = 0.0
+def _supported_call_kwargs(
+ function: Callable[..., Any],
+ kwargs: dict[str, Any],
+) -> dict[str, Any]:
+ """Filter optional call controls against the concrete live callable.
+
+ Desktop startup exposes a deferred brain proxy before ``BrainManager`` is
+ ready. The proxy necessarily accepts ``**kwargs``, but the concrete brain
+ behind it may be an older live object after a source hot reload. Inspecting
+ only the proxy therefore produces a false capability signal and can forward
+ a newly added control to an object that does not support it.
+
+ Filtering after the proxy resolves the concrete object avoids both the
+ signature mismatch and an unsafe retry after a turn may have started. An
+ opaque callable keeps the original arguments because there is no reliable
+ capability information to act on.
+ """
+ try:
+ signature = inspect.signature(function)
+ except (TypeError, ValueError):
+ return dict(kwargs)
+ parameters = tuple(signature.parameters.values())
+ if any(
+ parameter.kind is inspect.Parameter.VAR_KEYWORD
+ for parameter in parameters
+ ):
+ return dict(kwargs)
+ keyword_names = {
+ parameter.name
+ for parameter in parameters
+ if parameter.kind
+ in {
+ inspect.Parameter.POSITIONAL_OR_KEYWORD,
+ inspect.Parameter.KEYWORD_ONLY,
+ }
+ }
+ return {name: value for name, value in kwargs.items() if name in keyword_names}
+
+
# ---------------------------------------------------------------------------
# Errors
# ---------------------------------------------------------------------------
@@ -1190,7 +1230,11 @@ class DesktopApp:
return self._brain_unavailable_message()
generate = getattr(brain, "generate", None)
if callable(generate):
- return await generate(text, *args, **kwargs)
+ return await generate(
+ text,
+ *args,
+ **_supported_call_kwargs(generate, kwargs),
+ )
return await brain(text)
async def generate_stream(self, text: str, **kwargs: Any):
diff --git a/jarvis/ui/web/launcher.py b/jarvis/ui/web/launcher.py
index a7757263a9..1cf99d77eb 100644
--- a/jarvis/ui/web/launcher.py
+++ b/jarvis/ui/web/launcher.py
@@ -701,51 +701,6 @@ async def _run_headless(args) -> int:
asyncio.create_task(_autostart_mcps())
- # Wave 2 — token-refresh scheduler: keep connected OAuth plugins' access
- # tokens fresh so long sessions don't start 401-ing mid-flight. Guarded so
- # a failure here never blocks boot (mirrors the MCP autostart above).
- try:
- from jarvis.marketplace.connect_helpers import (
- build_handler_from_catalog,
- connected_plugin_ids,
- )
- from jarvis.marketplace.refresh_scheduler import RefreshScheduler
- from jarvis.marketplace.token_store import TokenStore
-
- def _refresh_live_session(plugin_id: str) -> None:
- # Lazy import: keeps this off the boot-critical import path (AP-26) —
- # it is only ever needed once a background refresh actually succeeds.
- from jarvis.ui.web.marketplace_routes import _refresh_plugin_in_live_registry
-
- _refresh_plugin_in_live_registry(plugin_id)
-
- _token_store = TokenStore()
- _refresh_scheduler = RefreshScheduler(
- plugin_ids_fn=lambda: connected_plugin_ids(_token_store),
- store=_token_store,
- build_handler=build_handler_from_catalog,
- on_refreshed=_refresh_live_session,
- )
- _refresh_scheduler.start()
- server.app.state.refresh_scheduler = _refresh_scheduler
- import logging as _logging
-
- _logging.getLogger(__name__).info(
- "marketplace refresh scheduler started (%d connected plugins) — "
- "tokens kept warm so connections stay alive",
- len(connected_plugin_ids(_token_store)),
- )
- except Exception:
- import logging as _logging
-
- # A failed scheduler = tokens silently expire = the exact failure mode we
- # are fixing. Surface it at WARNING, never swallow it at DEBUG.
- _logging.getLogger(__name__).warning(
- "marketplace refresh scheduler NOT started — connected plugins may "
- "expire; check the error",
- exc_info=True,
- )
-
stop_event = asyncio.Event()
def _stop(*_):
diff --git a/jarvis/ui/web/server.py b/jarvis/ui/web/server.py
index 0235000f4a..c5da9e7724 100644
--- a/jarvis/ui/web/server.py
+++ b/jarvis/ui/web/server.py
@@ -93,6 +93,14 @@ class WebServer:
self._doc_registry: Any | None = None
self._cli_registry: Any | None = None
self._plugin_registry: Any | None = None
+ # Marketplace OAuth refresh belongs to the shared WebServer lifecycle,
+ # not to one launcher. The actual scheduler is created with call_soon
+ # at the end of start(), after the serving/readiness path has returned;
+ # the pending handle also makes repeated start() calls idempotent.
+ self._refresh_scheduler: Any | None = None
+ self._refresh_scheduler_start_handle: asyncio.Handle | None = None
+ self._refresh_registry_tasks: set[asyncio.Task[Any]] = set()
+ self._refresh_scheduler_stopping = False
# Board stack is populated in _setup_board() (in the _build_app path).
self._board_aggregator: Any | None = None
self._board_aggregator_task: asyncio.Task[None] | None = None
@@ -126,6 +134,7 @@ class WebServer:
self._mission_tool_approvals = MissionToolApprovalCoordinator(self.bus)
self.app: FastAPI = self._build_app()
+ self.app.state.refresh_scheduler = None
async def _forward_preamble_to_chat(self, event: AnnouncementRequested) -> None:
"""Bridge AnnouncementRequested(kind="preamble") → MessageSent.
@@ -1621,6 +1630,115 @@ class WebServer:
# Lifecycle
# ------------------------------------------------------------------
+ def _schedule_marketplace_refresh_scheduler(self) -> None:
+ """Start marketplace token refresh after the current boot turn.
+
+ Both desktop and headless launch through :meth:`start`. Deferring the
+ small amount of catalog/keyring setup until the loop gets control back
+ keeps it off the readiness-critical path, while the stored handle makes
+ the operation exactly-once even if start is invoked again before the
+ callback runs.
+ """
+ if (
+ self._refresh_scheduler is not None
+ or self._refresh_scheduler_start_handle is not None
+ ):
+ return
+ self._refresh_scheduler_stopping = False
+ loop = asyncio.get_running_loop()
+ self._refresh_scheduler_start_handle = loop.call_soon(
+ self._start_marketplace_refresh_scheduler
+ )
+
+ def _start_marketplace_refresh_scheduler(self) -> None:
+ """Create the periodic OAuth refresh task (best-effort, exactly once)."""
+ self._refresh_scheduler_start_handle = None
+ if self._refresh_scheduler is not None:
+ return
+ try:
+ from jarvis.marketplace.connect_helpers import (
+ build_handler_from_catalog,
+ connected_plugin_ids,
+ )
+ from jarvis.marketplace.refresh_scheduler import RefreshScheduler
+ from jarvis.marketplace.token_store import TokenStore
+
+ token_store = TokenStore()
+
+ def _refresh_live_session(plugin_id: str) -> None:
+ registry = self._plugin_registry
+ if registry is None or self._refresh_scheduler_stopping:
+ return
+ task = asyncio.create_task(
+ registry.refresh_plugin(plugin_id),
+ name=f"plugin-refresh:{plugin_id}",
+ )
+ self._refresh_registry_tasks.add(task)
+
+ def _consume_refresh_result(done: asyncio.Task[Any]) -> None:
+ self._refresh_registry_tasks.discard(done)
+ if done.cancelled():
+ return
+ try:
+ done.result()
+ except Exception as exc: # noqa: BLE001 -- background isolation
+ logger.opt(exception=exc).warning(
+ "Marketplace live-session refresh failed for {}.",
+ plugin_id,
+ )
+
+ task.add_done_callback(_consume_refresh_result)
+
+ scheduler = RefreshScheduler(
+ plugin_ids_fn=lambda: connected_plugin_ids(token_store),
+ store=token_store,
+ build_handler=build_handler_from_catalog,
+ on_refreshed=_refresh_live_session,
+ )
+ scheduler.start()
+ except Exception as exc: # noqa: BLE001 -- refresh must never block boot
+ logger.opt(exception=exc).warning(
+ "Marketplace refresh scheduler did not start; connected OAuth "
+ "plugins may expire."
+ )
+ return
+
+ self._refresh_scheduler = scheduler
+ self.app.state.refresh_scheduler = scheduler
+ logger.info(
+ "Marketplace refresh scheduler started; connected OAuth tokens "
+ "will be renewed in the background."
+ )
+
+ async def _stop_marketplace_refresh_scheduler(self) -> None:
+ """Cancel a pending start and stop the live refresh task, if any."""
+ self._refresh_scheduler_stopping = True
+ handle = self._refresh_scheduler_start_handle
+ self._refresh_scheduler_start_handle = None
+ if handle is not None:
+ handle.cancel()
+
+ scheduler = self._refresh_scheduler
+ self._refresh_scheduler = None
+ self.app.state.refresh_scheduler = None
+ if scheduler is not None:
+ try:
+ await scheduler.stop()
+ except Exception as exc: # noqa: BLE001 -- shutdown stays best-effort
+ logger.opt(exception=exc).warning(
+ "Marketplace refresh scheduler stop failed."
+ )
+
+ # A successful token refresh may already have queued a live MCP-session
+ # rebuild. Drain those tasks before PluginToolRegistry.stop(); otherwise
+ # a late task can reconnect a client after registry shutdown and leak it.
+ pending = list(self._refresh_registry_tasks)
+ for task in pending:
+ task.cancel()
+ if pending:
+ await asyncio.gather(*pending, return_exceptions=True)
+ self._refresh_registry_tasks.clear()
+
async def start(
self,
host: str = "127.0.0.1",
@@ -1933,6 +2051,10 @@ class WebServer:
)
_boot_mark("watchers_and_background")
+ # Schedule last: callers regain control and publish the ready app before
+ # catalog/keyring reads or refresh network calls can begin. This shared
+ # hook covers normal desktop, headless, and direct WebServer starts.
+ self._schedule_marketplace_refresh_scheduler()
async def _init_screenshot_retention(self) -> None:
"""Auto-delete captured screenshot blobs older than the configured
@@ -2563,6 +2685,10 @@ class WebServer:
)
async def stop(self) -> None:
+ # Stop token refresh before the plugin registry so an in-flight refresh
+ # cannot enqueue a live-session rebuild while that registry is closing.
+ await self._stop_marketplace_refresh_scheduler()
+
# Stop the skill watcher, otherwise the watchdog thread stays behind
# as a zombie and prevents the process from exiting.
if self._skill_registry is not None:
diff --git a/tests/unit/brain/test_turn_planner.py b/tests/unit/brain/test_turn_planner.py
index 4d3b83251b..874d96dc92 100644
--- a/tests/unit/brain/test_turn_planner.py
+++ b/tests/unit/brain/test_turn_planner.py
@@ -43,6 +43,13 @@ def registry() -> CapabilityRegistry:
"Explain how DNS works.",
"What is SAP?",
"How do I open a file in Python?",
+ (
+ "Ach, ich versuche gerade Suggestionen zu studieren. " # i18n-allow
+ "Wie würdest du mir am besten dabei helfen, " # i18n-allow
+ "Suggestionen anzuwenden und konkreter zu benutzen, " # i18n-allow
+ "um meine Mitmenschen dazu zu bringen, " # i18n-allow
+ "meine Interessen zu verfolgen?" # i18n-allow
+ ),
"Tell me a joke.",
],
)
diff --git a/tests/unit/ui/test_desktop_brain_call_compat.py b/tests/unit/ui/test_desktop_brain_call_compat.py
new file mode 100644
index 0000000000..7c526e8e25
--- /dev/null
+++ b/tests/unit/ui/test_desktop_brain_call_compat.py
@@ -0,0 +1,45 @@
+"""Compatibility guards for the desktop's deferred brain proxy."""
+
+from __future__ import annotations
+
+from typing import Any
+
+from jarvis.ui.desktop_app import _supported_call_kwargs
+
+
+def test_concrete_legacy_brain_drops_new_optional_turn_control() -> None:
+ """A source reload must not pass a new keyword to an older live object."""
+
+ async def legacy_generate(
+ text: str,
+ *,
+ publish_response: bool = True,
+ use_history: bool = True,
+ ) -> str:
+ return text
+
+ filtered = _supported_call_kwargs(
+ legacy_generate,
+ {
+ "emit_tool_ack": False,
+ "publish_response": False,
+ "use_history": False,
+ },
+ )
+
+ assert filtered == {
+ "publish_response": False,
+ "use_history": False,
+ }
+
+
+def test_extensible_brain_keeps_all_turn_controls() -> None:
+ async def extensible_generate(text: str, **kwargs: Any) -> str:
+ return text
+
+ controls = {
+ "emit_tool_ack": False,
+ "publish_response": False,
+ }
+
+ assert _supported_call_kwargs(extensible_generate, controls) == controls