Dodaios is an open-source agent OS for your desktop: it runs your coding agents, browser and apps by voice or chat, on your own machine. Formerly Personal Jarvis.
Python agent-orchestrationai-agentai-coding-assistantclaude-codecoding-agentcomputer-usedesktop-applocal-firstmcppersonal-jarvisvoice-assistantvoice-coding
feat(marketplace): OAuth token refresh lifecycle + PKCE/token-store hardening
Ruben Lütke039cb1fbf15b
diff --git a/jarvis/marketplace/auth/oauth_pkce_loopback.py b/jarvis/marketplace/auth/oauth_pkce_loopback.pyindex 7c8d725094..d8433e6030 100644--- a/jarvis/marketplace/auth/oauth_pkce_loopback.py+++ b/jarvis/marketplace/auth/oauth_pkce_loopback.py@@ -241,6 +241,14 @@ class PkceLoopbackHandler:scope = payload.get("authed_user", {}).get("scope") or payload.get("scope")if scope:extra["scope"] = scope+ # Bind the refresh token to the exact OAuth client that obtained it.+ # A user can later replace/delete the family-level client secret (or a+ # recovered keyring can expose an older value), but OAuth refresh tokens+ # remain bound to their issuing client. Keeping the pair inside the same+ # protected token blob makes refresh independent of that drift.+ extra["client_id"] = pending.config.client_id+ if pending.config.client_secret:+ extra["client_secret"] = pending.config.client_secretreturn Tokens(access=access, refresh=refresh, expires_at=expires_at, extra=extra)@@ -248,13 +256,25 @@ class PkceLoopbackHandler:async def refresh(self, current: Tokens) -> Tokens:if not current.refresh:raise RuntimeError("no refresh token stored")+ # New grants persist their issuing client in ``extra``. Once that+ # marker exists, the whole pair is authoritative: a missing bound+ # secret means the grant was issued to a public client and a newly+ # configured secret must not be injected. Legacy token blobs have no+ # client_id marker and retain the old config-backed behavior.+ bound_client_id = current.extra.get("client_id")+ if bound_client_id:+ client_id = bound_client_id+ client_secret = current.extra.get("client_secret")+ else:+ client_id = self._config.client_id+ client_secret = self._config.client_secretrefresh_body = {"grant_type": "refresh_token","refresh_token": current.refresh,- "client_id": self._config.client_id,+ "client_id": client_id,}- if self._config.client_secret:- refresh_body["client_secret"] = self._config.client_secret+ if client_secret:+ refresh_body["client_secret"] = client_secretif self._config.resource:refresh_body["resource"] = self._config.resourcetimeout = httpx.Timeout(self._config.timeout_seconds)@@ -294,11 +314,22 @@ class PkceLoopbackHandler:if expires_in is not Noneelse None)+ extra = dict(current.extra)+ if not bound_client_id:+ # A successful legacy refresh proves which currently configured+ # client owns the grant. Persist that pair now so later config or+ # keyring drift cannot break the next refresh. A client_id without+ # a secret deliberately marks a public client.+ extra["client_id"] = client_id+ if client_secret:+ extra["client_secret"] = client_secret+ else:+ extra.pop("client_secret", None)return Tokens(access=access,refresh=new_refresh,expires_at=expires_at,- extra=current.extra,+ extra=extra,)@staticmethoddiff --git a/jarvis/marketplace/plugin_registry.py b/jarvis/marketplace/plugin_registry.pyindex 0722a47c47..33150daf1e 100644--- a/jarvis/marketplace/plugin_registry.py+++ b/jarvis/marketplace/plugin_registry.py@@ -63,6 +63,7 @@ def _deregister_plugin_capability(cap_registry, plugin_id) -> None:# plugin's tools only reached the brain when their connect happened to beat# the last unrelated tool refresh (the intermittent "tool not available" bug)._CONNECT_TIMEOUT_S_DEFAULT = 15.0+_CLIENT_STOP_TIMEOUT_S = 5.0def _connect_needs_reauth(message: str) -> bool:@@ -83,6 +84,12 @@ def _connect_needs_reauth(message: str) -> bool:return "401" in m or "unauthorized" in m or "invalid_token" in m+def _default_refresh_handler(plugin_id: str) -> Any | None:+ from jarvis.marketplace.connect_helpers import build_handler_from_catalog++ return build_handler_from_catalog(plugin_id)++class PluginToolRegistry:def __init__(self,@@ -93,6 +100,7 @@ class PluginToolRegistry:bus: Any = None,default_risk_tier: str = "monitor",connect_timeout_s: float = _CONNECT_TIMEOUT_S_DEFAULT,+ refresh_handler_builder: Callable[[str], Any | None] | None = None,) -> None:self._catalog = catalog or load_catalog()self._store = token_store or TokenStore()@@ -100,6 +108,7 @@ class PluginToolRegistry:self._bus = busself._risk_tier = default_risk_tierself._connect_timeout_s = float(connect_timeout_s)+ self._build_refresh_handler = refresh_handler_builder or _default_refresh_handlerself._clients: dict[str, Any] = {}self._tools: dict[str, MCPToolAdapter] = {}# Last swallowed connect/list_tools error per plugin (honest liveness@@ -175,6 +184,64 @@ class PluginToolRegistry:for pid in list(self._clients):await self._disconnect_plugin(pid)+ async def _open_client(+ self, server_spec: Any, env_overrides: dict[str, str]+ ) -> tuple[Any, list[dict[str, Any]]]:+ """Open one bounded client and clean up any failed attempt."""+ client = self._client_factory(server_spec, env_overrides=env_overrides)+ try:+ tool_defs = await asyncio.wait_for(+ self._start_and_list(client), timeout=self._connect_timeout_s+ )+ except BaseException:+ await self._stop_client_bounded(client, "untracked-connect")+ raise+ return client, tool_defs++ @staticmethod+ async def _stop_client_bounded(client: Any, plugin_id: str) -> None:+ """Stop a client within the cleanup budget without orphaning on cancel.++ The stop runs in a shielded child task. Cancellation of the caller is+ remembered and re-raised only after that bounded cleanup finishes, so+ ownership is never dropped while a live client remains behind.+ """++ async def _stop() -> None:+ await asyncio.wait_for(client.stop(), timeout=_CLIENT_STOP_TIMEOUT_S)++ cleanup = asyncio.create_task(_stop(), name=f"plugin-stop:{plugin_id}")+ pending_cancel: asyncio.CancelledError | None = None+ while not cleanup.done():+ try:+ await asyncio.shield(cleanup)+ except asyncio.CancelledError as exc:+ current = asyncio.current_task()+ if current is not None and current.cancelling():+ pending_cancel = exc+ if cleanup.done():+ break++ try:+ cleanup.result()+ except TimeoutError:+ log.warning("plugin-registry: %s client stop timed out", plugin_id)+ except asyncio.CancelledError:+ log.debug("plugin-registry: %s client stop was cancelled", plugin_id)+ except Exception as exc: # noqa: BLE001 - cleanup stays best-effort+ log.debug("plugin-registry: %s stop failed: %s", plugin_id, exc)++ if pending_cancel is not None:+ raise pending_cancel++ def _connect_error_message(self, exc: Exception) -> str:+ if isinstance(exc, asyncio.TimeoutError):+ return (+ f"connect timed out after {self._connect_timeout_s:.0f}s "+ "(handshake never completed)"+ )+ return str(exc) or type(exc).__name__+async def _connect_plugin(self, plugin: PluginSpec) -> None:if plugin.id in self._clients:# Already connected (e.g. a refresh_plugin ran before bootstrap@@ -199,37 +266,66 @@ class PluginToolRegistry:if resolved is None:returnserver_spec, env_overrides = resolved- client: Any | None = Nonetry:- client = self._client_factory(server_spec, env_overrides=env_overrides)- # Bounded connect: a handshake that never completes (dead host,- # 401-that-hangs) must not stall the caller — see- # _CONNECT_TIMEOUT_S_DEFAULT for the live forensic.- tool_defs = await asyncio.wait_for(- self._start_and_list(client), timeout=self._connect_timeout_s+ client, tool_defs = await self._open_client(server_spec, env_overrides)+ except Exception as exc: # noqa: BLE001 - graceful per-plugin degrade+ message = self._connect_error_message(exc)+ if not _connect_needs_reauth(message):+ log.warning(+ "plugin-registry: %s connect failed: %s", plugin.id, message+ )+ self._last_errors[plugin.id] = message+ return++ from jarvis.marketplace.refresh_scheduler import SKIPPED, refresh_plugin_token++ attempt = await refresh_plugin_token(+ plugin.id,+ self._store,+ self._build_refresh_handler,+ force=True,+ observed_access_token=tokens.access,)- except Exception as exc: # noqa: BLE001 — graceful per-plugin degrade- if isinstance(exc, asyncio.TimeoutError):- msg = (- f"connect timed out after {self._connect_timeout_s:.0f}s "- "(handshake never completed)"+ if not attempt.usable:+ log.warning(+ "plugin-registry: %s connect auth failed; refresh outcome=%s: %s",+ plugin.id,+ attempt.outcome,+ message,)- else:- msg = str(exc) or type(exc).__name__- log.warning("plugin-registry: %s connect failed: %s", plugin.id, msg)- self._last_errors[plugin.id] = msg- self._maybe_mark_needs_reauth(plugin.id, tokens, msg)- if client is not None:- # Best-effort cleanup; a cancelled/hung transport may not- # close cleanly, so the stop itself is bounded too.- try:- await asyncio.wait_for(client.stop(), timeout=5.0)- except Exception: # noqa: BLE001 — cleanup must never raise- log.debug(- "plugin-registry: %s post-failure stop failed", plugin.id,- exc_info=True,+ self._last_errors[plugin.id] = message+ if attempt.outcome == SKIPPED:+ self._maybe_mark_needs_reauth(plugin.id, message)+ return++ fresh_tokens: Any | None = None+ try:+ fresh_tokens = self._store.load(plugin.id)+ fresh_resolved = (+ plugin_to_mcp_server_spec(plugin, fresh_tokens)+ if fresh_tokens is not None+ else None+ )+ if fresh_resolved is None:+ self._last_errors[plugin.id] = message+ return+ server_spec, env_overrides = fresh_resolved+ client, tool_defs = await self._open_client(server_spec, env_overrides)+ except Exception as retry_exc: # noqa: BLE001 - exactly one retry+ retry_message = self._connect_error_message(retry_exc)+ log.warning(+ "plugin-registry: %s connect retry after refresh failed: %s",+ plugin.id,+ retry_message,+ )+ self._last_errors[plugin.id] = retry_message+ if _connect_needs_reauth(retry_message) and fresh_tokens is not None:+ self._maybe_mark_needs_reauth(+ plugin.id,+ retry_message,+ expected_tokens=fresh_tokens,)- return+ returnself._clients[plugin.id] = clientself._last_errors.pop(plugin.id, None)for tool_def in tool_defs:@@ -253,7 +349,13 @@ class PluginToolRegistry:await client.start()return await client.list_tools()- def _maybe_mark_needs_reauth(self, plugin_id: str, tokens: Any, message: str) -> None:+ def _maybe_mark_needs_reauth(+ self,+ plugin_id: str,+ message: str,+ *,+ expected_tokens: Any | None = None,+ ) -> None:"""Flag the stored token after an auth-shaped connect failure.Mirrors the refresh scheduler's marking: later boots then skip the@@ -262,6 +364,16 @@ class PluginToolRegistry:try:if not _connect_needs_reauth(message):return+ tokens = self._store.load(plugin_id)+ if tokens is None:+ return+ if expected_tokens is not None and tokens != expected_tokens:+ log.info(+ "plugin-registry: %s re-auth mark skipped; token changed "+ "during connect retry",+ plugin_id,+ )+ returnself._store.save(plugin_id, dataclasses.replace(tokens, needs_reauth=True))log.warning("plugin-registry: %s connect needs re-auth — marked: %s",@@ -276,12 +388,12 @@ class PluginToolRegistry:async def _disconnect_plugin(self, plugin_id: str) -> None:for name in [n for n in self._tools if n.startswith(f"{plugin_id}/")]:self._tools.pop(name, None)- client = self._clients.pop(plugin_id, None)+ client = self._clients.get(plugin_id)if client is not None:try:- await client.stop()- except Exception as exc: # noqa: BLE001- log.debug("plugin-registry: %s stop failed: %s", plugin_id, exc)+ await self._stop_client_bounded(client, plugin_id)+ finally:+ self._clients.pop(plugin_id, None)try:from jarvis.core.capabilities import get_registry as _get_cap_registrydiff --git a/jarvis/marketplace/refresh_scheduler.py b/jarvis/marketplace/refresh_scheduler.pyindex 4c410ec3da..7eed71f1ac 100644--- a/jarvis/marketplace/refresh_scheduler.py+++ b/jarvis/marketplace/refresh_scheduler.py@@ -1,17 +1,9 @@-"""Token-refresh scheduler for connected marketplace plugins (Wave 2, #3).--OAuth access tokens expire — from ~30 min (HubSpot) to ~24 h (Linear). Without-proactive refresh a long-lived backend silently starts getting 401s mid-session.-This scheduler periodically refreshes tokens nearing expiry via each plugin's-:class:`~jarvis.marketplace.auth.base.AuthHandler` and writes the new tokens-back to the :class:`~jarvis.marketplace.token_store.TokenStore`. A ``revoked``-refresh (auth server returns ``invalid_grant``) drops the entry so the UI can-surface a "Reconnect" prompt rather than looping on a dead token.--The pure core :func:`refresh_due_tokens` takes its dependencies as arguments-(plugin ids, store, handler builder) so it is unit-testable without the real-catalog, keyring, or network. :class:`RefreshScheduler` is the thin loop around-it that the app starts at boot.+"""Coordinated refresh lifecycle for connected Marketplace plugins.++OAuth access tokens are short-lived, while refresh tokens are longer-lived but+can still expire or be revoked. This module keeps access tokens fresh and+serializes all refresh paths for a plugin so scheduler, REST-tool, and registry+retries cannot rotate the same refresh token concurrently."""from __future__ import annotations@@ -19,33 +11,49 @@ from __future__ import annotationsimport asyncioimport dataclassesimport logging+import threading+import weakreffrom collections.abc import Callablefrom contextlib import suppressfrom datetime import UTC, datetimefrom jarvis.marketplace.auth.base import AuthHandler-from jarvis.marketplace.token_store import TokenStore+from jarvis.marketplace.token_store import Tokens, TokenStorelog = logging.getLogger(__name__)HandlerBuilder = Callable[[str], AuthHandler | None]PluginIdsFn = Callable[[], list[str]]-# Per-plugin outcome labels (also the public vocabulary for telemetry/logs).REFRESHED = "refreshed"SKIPPED = "skipped"REVOKED = "revoked"FAILED = "failed"-# Substrings in a refresh RuntimeError message that mean the connection is-# un-healable without the user re-authenticating (or fixing the OAuth client) —-# as opposed to a transient server/network error that should be retried next-# cycle. Google reports OAuth errors via HTTP status + JSON body (not Slack's-# `ok:false` shape), so the handler raises e.g.-# ``RuntimeError("refresh HTTP 401: {...invalid_client...}")`` — the bare-string-# "revoked" check missed every Google failure, leaving needs_reauth False while-# the token rotted (live 2026-06-07 Gmail bug). Matching the canonical OAuth-# error codes + descriptions catches Google, Slack, and generic providers.+[email protected](frozen=True, slots=True)+class RefreshAttempt:+ """Secret-free result from one coordinated refresh attempt."""++ outcome: str+ usable: bool = False+ access_changed: bool = False+++_REFRESH_LOCKS: weakref.WeakKeyDictionary[asyncio.AbstractEventLoop, dict[str, asyncio.Lock]] = (+ weakref.WeakKeyDictionary()+)+_REFRESH_LOCKS_GUARD = threading.Lock()+++def _refresh_lock(plugin_id: str) -> asyncio.Lock:+ """Return the per-plugin lock bound to the current event loop."""+ loop = asyncio.get_running_loop()+ with _REFRESH_LOCKS_GUARD:+ loop_locks = _REFRESH_LOCKS.setdefault(loop, {})+ return loop_locks.setdefault(plugin_id, asyncio.Lock())++_REAUTH_ERROR_MARKERS: tuple[str, ...] = ("revoked","invalid_grant",@@ -53,148 +61,214 @@ _REAUTH_ERROR_MARKERS: tuple[str, ...] = ("unauthorized_client","client was not found","token has been expired",- # Legacy DCR token minted before client_id was persisted — un-refreshable,- # one reconnect heals it (live 2026-06-08 audit: linear)."reconnect required","no stored client_id",)def _refresh_needs_reauth(message: str) -> bool:- """True iff a refresh-failure message indicates an un-healable auth error.-- Conservative on purpose: a generic transient failure (5xx, timeout, network)- contains none of these markers and stays a retryable FAILED, so one flaky- cycle never falsely flags a healthy plugin as needing reconnect."""- m = message.lower()- return any(marker in m for marker in _REAUTH_ERROR_MARKERS)+ """Return whether a refresh failure requires user authentication."""+ lowered = message.lower()+ return any(marker in lowered for marker in _REAUTH_ERROR_MARKERS)def _keep_alive_due(tokens: object, keep_alive_seconds: int | None) -> bool:- """True when a token should be proactively refreshed to stay warm.-- Some providers expire a *refresh* token after a period of inactivity even- while the access token still looks valid (or never carries an expiry at- all). Exercising the refresh token on a fixed cadence keeps the connection- alive indefinitely — the heart of "log in once, stay connected forever".-- Disabled (returns False) when keep_alive_seconds is None, so the plain- near-expiry contract of refresh_due_tokens is unchanged by default."""+ """Return whether a refresh token should be exercised to stay warm."""if keep_alive_seconds is None or not getattr(tokens, "refresh", None):return False- lr = tokens.extra.get("last_refreshed") # type: ignore[attr-defined]- if not lr:- return True # never stamped → refresh once to warm it + record the time+ last_refreshed = tokens.extra.get("last_refreshed") # type: ignore[attr-defined]+ if not last_refreshed:+ return Truetry:- last = datetime.fromisoformat(lr)- except (ValueError, TypeError):+ last = datetime.fromisoformat(last_refreshed)+ except (TypeError, ValueError):return Trueif last.tzinfo is None:last = last.replace(tzinfo=UTC)return (datetime.now(UTC) - last).total_seconds() >= keep_alive_seconds-async def refresh_due_tokens(- plugin_ids: list[str],+def _reload_before_refresh_commit(+ plugin_id: str,+ store: TokenStore,+ original_state: str,+) -> tuple[Tokens | None, RefreshAttempt | None]:+ """Reload the token and reject a stale provider result.++ Disconnect and reconnect do not take the refresh single-flight lock. They+ may therefore replace or delete the stored grant while the provider call+ is awaiting I/O. A refresh result may only be committed when the complete+ stored token state is still the one used to start that provider call.+ """+ try:+ current = store.load(plugin_id)+ except Exception as exc: # noqa: BLE001 - isolate one plugin's storage+ log.warning("plugin %s token reload failed after refresh: %s", plugin_id, exc)+ return None, RefreshAttempt(FAILED)++ if current is not None and current.to_json() == original_state:+ return current, None++ log.info(+ "plugin %s token changed while refresh was in flight; discarded stale result",+ plugin_id,+ )+ if current is None or current.needs_reauth:+ return current, RefreshAttempt(SKIPPED)+ return current, RefreshAttempt(+ SKIPPED,+ usable=True,+ access_changed=current.access != Tokens.from_json(original_state).access,+ )+++async def refresh_plugin_token(+ plugin_id: str,store: TokenStore,build_handler: HandlerBuilder,*,+ force: bool = False,+ observed_access_token: str | None = None,threshold_seconds: int = 600,keep_alive_seconds: int | None = None,- on_refreshed: Callable[[str], None] | None = None,-) -> dict[str, str]:- """Refresh every connected plugin whose token is due.-- A token is *due* when its access token is near expiry OR (when- ``keep_alive_seconds`` is set) it has not been refreshed within that window —- the keep-alive sweep that keeps refresh tokens warm so a connection survives- forever, even for providers whose access token is long-lived / never expires.-- ``on_refreshed``, when given, fires once per plugin id right after its fresh- token is saved — the hook the live MCP session uses to pick up the new token- instead of continuing to 401 with the stale one. A callback failure is- swallowed and logged; a UI-refresh hiccup must never break the token save- that already succeeded, nor take down the rest of the cycle.-- Returns a ``{plugin_id: outcome}`` map (outcomes from the module constants).- Never raises — a single plugin's failure is isolated so one dead connection- cannot stall the whole cycle.+) -> RefreshAttempt:+ """Refresh one plugin under a process-local single-flight lock.++ The token is reloaded after acquiring the lock. If another caller already+ replaced the access token that triggered a 401, the waiting caller reuses+ that token instead of rotating the refresh token a second time."""- outcomes: dict[str, str] = {}- for pid in plugin_ids:+ async with _refresh_lock(plugin_id):try:- tokens = store.load(pid)- except RuntimeError:- # Corrupted blob — surface as FAILED, leave it for the UI to fix.- outcomes[pid] = FAILED- continue-- if tokens is None or not tokens.refresh:- outcomes[pid] = SKIPPED- continue- due = tokens.is_near_expiry(threshold_seconds) or _keep_alive_due(- tokens, keep_alive_seconds- )- if not due:- outcomes[pid] = SKIPPED- continue+ tokens = store.load(plugin_id)+ except Exception as exc: # noqa: BLE001 - isolate one plugin's storage+ log.warning("plugin %s token load failed: %s", plugin_id, exc)+ return RefreshAttempt(FAILED)++ if tokens is None or tokens.needs_reauth:+ return RefreshAttempt(SKIPPED)+ if observed_access_token is not None and tokens.access != observed_access_token:+ return RefreshAttempt(SKIPPED, usable=True, access_changed=True)+ if not tokens.refresh:+ return RefreshAttempt(SKIPPED, usable=not force)++ if not force:+ due = tokens.is_near_expiry(threshold_seconds) or _keep_alive_due(+ tokens, keep_alive_seconds+ )+ if not due:+ return RefreshAttempt(SKIPPED, usable=True)- handler = build_handler(pid)- if handler is None:- outcomes[pid] = SKIPPED- continue+ original_state = tokens.to_json()try:- new_tokens = await handler.refresh(tokens)- except RuntimeError as exc:- if _refresh_needs_reauth(str(exc)):- # Do NOT delete — keep the entry and flag it so the UI shows a- # "Reconnect" prompt. A connected plugin must never silently- # disappear; the only user-visible delete path is an explicit- # DELETE. (Previously this called store.delete(pid).)- try:- store.save(pid, dataclasses.replace(tokens, needs_reauth=True))- outcomes[pid] = REVOKED- log.info(- "plugin %s refresh needs reauth — marked needs_reauth: %s", pid, exc- )- except Exception as save_exc: # noqa: BLE001 — isolate one plugin's store failure- outcomes[pid] = FAILED- log.warning(- "plugin %s needs_reauth save failed, will retry next cycle: %s",- pid,- save_exc,- )- else:- outcomes[pid] = FAILED- log.warning("plugin %s refresh failed (transient, will retry): %s", pid, exc)- continue- except Exception as exc: # noqa: BLE001- outcomes[pid] = FAILED- log.warning("plugin %s refresh errored: %s", pid, exc)- continue-- # A healthy refresh clears any stale needs_reauth flag and stamps the- # refresh time so the keep-alive sweep can skip it until the next window.- merged_extra = {**new_tokens.extra, "last_refreshed": datetime.now(UTC).isoformat()}+ handler = build_handler(plugin_id)+ except Exception as exc: # noqa: BLE001 - configuration must not break the loop+ log.warning("plugin %s refresh handler failed to build: %s", plugin_id, exc)+ return RefreshAttempt(FAILED)+ if handler is None:+ return RefreshAttempt(SKIPPED)+try:- store.save(- pid,- dataclasses.replace(new_tokens, extra=merged_extra, needs_reauth=False),+ refreshed = await handler.refresh(tokens)+ if not refreshed.access:+ raise RuntimeError("refresh returned an empty access token")+ except Exception as exc: # noqa: BLE001 - provider failures are isolated+ if not _refresh_needs_reauth(str(exc)):+ _current, superseded = _reload_before_refresh_commit(+ plugin_id, store, original_state+ )+ if superseded is not None:+ return superseded+ log.warning(+ "plugin %s refresh failed (transient, will retry): %s",+ plugin_id,+ exc,+ )+ return RefreshAttempt(FAILED)++ current, superseded = _reload_before_refresh_commit(plugin_id, store, original_state)+ if superseded is not None:+ return superseded+ assert current is not None++ try:+ store.save(plugin_id, dataclasses.replace(current, needs_reauth=True))+ except Exception as save_exc: # noqa: BLE001 - isolate storage failure+ log.warning(+ "plugin %s needs_reauth save failed, will retry: %s",+ plugin_id,+ save_exc,+ )+ return RefreshAttempt(FAILED)+ log.info(+ "plugin %s refresh needs reauth; marked needs_reauth: %s",+ plugin_id,+ exc,)- outcomes[pid] = REFRESHED- except Exception as exc: # noqa: BLE001 — isolate one plugin's store failure- outcomes[pid] = FAILED+ return RefreshAttempt(REVOKED)++ current, superseded = _reload_before_refresh_commit(plugin_id, store, original_state)+ if superseded is not None:+ return superseded+ assert current is not None++ merged_extra = {+ **current.extra,+ **refreshed.extra,+ "last_refreshed": datetime.now(UTC).isoformat(),+ }+ saved = dataclasses.replace(+ refreshed,+ refresh=refreshed.refresh or current.refresh,+ extra=merged_extra,+ needs_reauth=False,+ )+ try:+ store.save(plugin_id, saved)+ except Exception as exc: # noqa: BLE001 - isolate storage failurelog.warning(- "plugin %s refreshed token save failed, will retry next cycle: %s", pid, exc+ "plugin %s refreshed token save failed, will retry: %s",+ plugin_id,+ exc,)- continue+ return RefreshAttempt(FAILED)+ return RefreshAttempt(+ REFRESHED,+ usable=True,+ access_changed=saved.access != current.access,+ )- if on_refreshed is not None:++async def refresh_due_tokens(+ plugin_ids: list[str],+ store: TokenStore,+ build_handler: HandlerBuilder,+ *,+ threshold_seconds: int = 600,+ keep_alive_seconds: int | None = None,+ on_refreshed: Callable[[str], None] | None = None,+) -> dict[str, str]:+ """Refresh every due plugin without allowing one failure to stop the cycle."""+ outcomes: dict[str, str] = {}+ for plugin_id in plugin_ids:+ attempt = await refresh_plugin_token(+ plugin_id,+ store,+ build_handler,+ threshold_seconds=threshold_seconds,+ keep_alive_seconds=keep_alive_seconds,+ )+ outcomes[plugin_id] = attempt.outcome+ if attempt.outcome == REFRESHED and on_refreshed is not None:try:- on_refreshed(pid)- except Exception as exc: # noqa: BLE001 — a UI-refresh hiccup must not kill the loop- log.warning("refresh: on_refreshed callback failed for %s: %s", pid, exc)+ on_refreshed(plugin_id)+ except Exception as exc: # noqa: BLE001 - callback is best-effort+ log.warning(+ "refresh: on_refreshed callback failed for %s: %s",+ plugin_id,+ exc,+ )return outcomes@@ -209,8 +283,9 @@ class RefreshScheduler:*,interval_seconds: float = 300.0,threshold_seconds: int = 600,- keep_alive_seconds: int | None = 43_200, # 12h — keep refresh tokens warm+ keep_alive_seconds: int | None = 43_200,on_refreshed: Callable[[str], None] | None = None,+ shutdown_drain_timeout_seconds: float = 30.0,) -> None:self._plugin_ids_fn = plugin_ids_fnself._store = store@@ -219,7 +294,10 @@ class RefreshScheduler:self._threshold = threshold_secondsself._keep_alive_seconds = keep_alive_secondsself._on_refreshed = on_refreshed+ self._shutdown_drain_timeout = shutdown_drain_timeout_secondsself._task: asyncio.Task[None] | None = None+ self._cycle_task: asyncio.Task[dict[str, str]] | None = None+ self._stopping = Falseasync def run_once(self) -> dict[str, str]:return await refresh_due_tokens(@@ -232,44 +310,88 @@ class RefreshScheduler:)async def _loop(self) -> None:- while True:+ while not self._stopping:+ cycle = asyncio.create_task(self.run_once(), name="marketplace-refresh-cycle")+ self._cycle_task = cycletry:- outcomes = await self.run_once()+ # A loop cancellation must not propagate into a provider call:+ # rotating providers may already have consumed the old refresh+ # token, and cancelling before the save would lose the new one.+ outcomes = await asyncio.shield(cycle)self._log_cycle(outcomes)- except Exception as exc: # noqa: BLE001+ except asyncio.CancelledError:+ raise+ except Exception as exc: # noqa: BLE001 - keep the background loop alivelog.warning("refresh cycle failed: %s", exc)+ finally:+ if cycle.done() and self._cycle_task is cycle:+ self._cycle_task = None++ if self._stopping:+ breakawait asyncio.sleep(self._interval)@staticmethoddef _log_cycle(outcomes: dict[str, str]) -> None:- """Per-cycle observability: a connection silently rotting forever was the- whole failure mode (live 2026-06-08 audit). Log a one-line summary so the- refresh loop is visibly alive — at INFO when anything changed, else DEBUG."""counts: dict[str, int] = {}for outcome in outcomes.values():counts[outcome] = counts.get(outcome, 0) + 1- summary = ", ".join(f"{k}={v}" for k, v in sorted(counts.items())) or "no plugins"- changed = any(counts.get(k) for k in (REFRESHED, REVOKED, FAILED))+ summary = ", ".join(f"{key}={value}" for key, value in sorted(counts.items()))+ summary = summary or "no plugins"+ changed = any(counts.get(key) for key in (REFRESHED, REVOKED, FAILED))(log.info if changed else log.debug)("token refresh cycle: %s", summary)- # Name dead connections explicitly at WARNING. An anonymous "revoked=1"- # count let a revoked plugin rot unseen (live: linear sat dead ~22 days,- # gmail ~16 days, unnoticed until next use). Only a user reconnect heals- # a revoked refresh token, so surface exactly which plugin needs it.- dead = sorted(pid for pid, outcome in outcomes.items() if outcome == REVOKED)- if dead:+ revoked = sorted(plugin_id for plugin_id, outcome in outcomes.items() if outcome == REVOKED)+ if revoked:log.warning(- "marketplace plugin(s) need reconnect — refresh token revoked: %s",- ", ".join(dead),+ "marketplace plugin(s) need reconnect; refresh token revoked: %s",+ ", ".join(revoked),)def start(self) -> None:- if self._task is None or self._task.done():- self._task = asyncio.create_task(self._loop(), name="marketplace-refresh")+ if self._task is not None and not self._task.done():+ return+ if self._cycle_task is not None and not self._cycle_task.done():+ log.warning("marketplace refresh cannot restart while shutdown is draining")+ return+ self._cycle_task = None+ self._stopping = False+ self._task = asyncio.create_task(self._loop(), name="marketplace-refresh")async def stop(self) -> None:- if self._task is not None:- self._task.cancel()+ self._stopping = True+ cycle = self._cycle_task+ if cycle is not None and not cycle.done():+ try:+ await asyncio.wait_for(+ asyncio.shield(cycle),+ timeout=self._shutdown_drain_timeout,+ )+ except TimeoutError:+ log.warning(+ "marketplace refresh did not drain within %.1fs; cancelling as a last resort",+ self._shutdown_drain_timeout,+ )+ cycle.cancel()+ # Give a cooperative provider one event-loop turn to observe+ # cancellation without making shutdown unbounded again.+ await asyncio.sleep(0)+ if cycle.done():+ with suppress(asyncio.CancelledError, Exception):+ cycle.result()+ except asyncio.CancelledError:+ if not cycle.cancelled():+ raise+ except Exception as exc: # noqa: BLE001 - the loop reports cycle failures+ log.warning("marketplace refresh ended while draining: %s", exc)++ loop_task = self._task+ if loop_task is not None and not loop_task.done():+ # At this point the provider cycle is complete (or hit the bounded+ # last-resort timeout), so cancellation only interrupts idle sleep.+ loop_task.cancel()with suppress(asyncio.CancelledError):- await self._task- self._task = None+ await loop_task+ self._task = None+ if cycle is not None and cycle.done() and self._cycle_task is cycle:+ self._cycle_task = Nonediff --git a/jarvis/marketplace/token_store.py b/jarvis/marketplace/token_store.pyindex 186e3b16b9..6af9a76a82 100644--- a/jarvis/marketplace/token_store.py+++ b/jarvis/marketplace/token_store.py@@ -114,6 +114,15 @@ class KeyringBackend:_CHUNK_SENTINEL = "\x00JCHUNKS\x00" # primary-key header for a chunked value: sentinel + <count>+_CLEANUP_EXTENT_SUFFIX = "__extent" # non-secret exclusive chunk cleanup extent+# Historical production values used 1000-character chunks. A one-mebibyte+# logical token budget is orders of magnitude above every catalog OAuth token+# shape while keeping the one-time legacy-disconnect sweep finite.+_HISTORIC_CHUNK_SIZE = 1000+_LEGACY_TOKEN_SCAN_BUDGET_CHARS = 1024 * 1024+_LEGACY_SPARSE_SCAN_SLOTS = (+ _LEGACY_TOKEN_SCAN_BUDGET_CHARS + _HISTORIC_CHUNK_SIZE - 1+) // _HISTORIC_CHUNK_SIZEclass ChunkedBackend:@@ -130,11 +139,13 @@ class ChunkedBackend:``<key>__0 .. <key>__{n-1}``. A token blob is JSON and always starts with``{``, so a legacy plain value is never mistaken for a header — reads staybackward-compatible with already-stored short tokens (Discord/Telegram).+ A non-secret ``<key>__extent`` sidecar retains the maximum cleanup extent+ only when interrupted or best-effort deletion may have left old chunks."""# Stay well under the observed 1280-char Credential-Manager limit so a few# non-ASCII chars (extra UTF-16 bytes) can't push a single chunk over.- DEFAULT_CHUNK_SIZE = 1000+ DEFAULT_CHUNK_SIZE = _HISTORIC_CHUNK_SIZEdef __init__(self, backend: TokenBackend, chunk_size: int = DEFAULT_CHUNK_SIZE) -> None:if chunk_size < 1:@@ -146,18 +157,152 @@ class ChunkedBackend:def _overflow_key(key: str, index: int) -> str:return f"{key}__{index}"- def _clear_overflow(self, key: str) -> None:- """Delete any ``<key>__i`` pieces left by a previous larger value."""- i = 0- while self._backend.get(self._overflow_key(key, i)) is not None:- self._backend.delete(self._overflow_key(key, i))+ @staticmethod+ def _cleanup_extent_key(key: str) -> str:+ return f"{key}{_CLEANUP_EXTENT_SUFFIX}"++ @staticmethod+ def _manifest_count(key: str, head: str) -> int:+ try:+ count = int(head[len(_CHUNK_SENTINEL) :])+ except ValueError as exc:+ raise RuntimeError(f"invalid chunk manifest for {key!r}") from exc+ if count < 1:+ raise RuntimeError(f"invalid chunk manifest for {key!r}")+ return count++ def _cleanup_extent(self, key: str) -> int:+ raw = self._backend.get(self._cleanup_extent_key(key))+ if raw is None:+ return 0+ try:+ extent = int(raw)+ except ValueError as exc:+ raise RuntimeError(f"invalid cleanup extent for {key!r}") from exc+ if extent < 1:+ raise RuntimeError(f"invalid cleanup extent for {key!r}")+ return extent++ def _persist_cleanup_extent(self, key: str, extent: int) -> None:+ current = self._cleanup_extent(key)+ if current >= extent:+ return+ extent_key = self._cleanup_extent_key(key)+ value = str(extent)+ self._backend.set(extent_key, value)+ if self._backend.get(extent_key) != value:+ raise RuntimeError(f"could not persist cleanup extent for {key!r}")++ def _clear_cleanup_extent_best_effort(self, key: str) -> None:+ try:+ self._backend.delete(self._cleanup_extent_key(key))+ except Exception: # noqa: BLE001 - save already succeeded+ return++ def _clear_cleanup_extent_verified(self, key: str) -> None:+ extent_key = self._cleanup_extent_key(key)+ self._backend.delete(extent_key)+ if self._backend.get(extent_key) is not None:+ raise RuntimeError(f"could not delete cleanup extent for {key!r}")++ def _clear_overflow(self, key: str, *, start_index: int = 0) -> bool:+ """Best-effort delete contiguous ``<key>__i`` overflow pieces.++ ``KeyringBackend.delete`` deliberately cannot raise when its lower-level+ delete fails because this helper also runs after a successful save. A+ backend can therefore leave a chunk readable after ``delete``. Stop at+ that first retained chunk instead of probing an unbounded sequence of+ generated keys, and report whether every discovered chunk was removed.+ Save-time cleanup may ignore this result. Explicit deletion uses the+ persisted cleanup extent below so gaps cannot hide later chunks.+ """+ i = start_index+ while True:+ chunk_key = self._overflow_key(key, i)+ try:+ piece = self._backend.get(chunk_key)+ except Exception: # noqa: BLE001 - keep save-time cleanup best-effort+ return False+ if piece is None:+ return True+ try:+ self._persist_cleanup_extent(key, i + 1)+ except Exception: # noqa: BLE001 - keep save-time cleanup best-effort+ return False+ try:+ self._backend.delete(chunk_key)+ retained = self._backend.get(chunk_key)+ except Exception: # noqa: BLE001 - keep save-time cleanup best-effort+ return False+ if retained is not None:+ return Falsei += 1+ def _clear_indexed_overflow(self, key: str, count: int, *, start_index: int = 0) -> bool:+ """Attempt and verify every chunk named by a manifest or extent."""+ cleared = True+ for i in range(start_index, count):+ chunk_key = self._overflow_key(key, i)+ try:+ piece = self._backend.get(chunk_key)+ except Exception: # noqa: BLE001 - finish the bounded cleanup pass+ cleared = False+ continue+ if piece is None:+ continue+ try:+ self._backend.delete(chunk_key)+ except Exception: # noqa: BLE001 - finish the bounded cleanup pass+ cleared = False+ continue+ try:+ retained = self._backend.get(chunk_key)+ except Exception: # noqa: BLE001 - finish the bounded cleanup pass+ cleared = False+ continue+ if retained is not None:+ cleared = False+ return cleared++ def _clear_sparse_legacy_overflow(self, key: str) -> bool:+ """Bounded sweep for pre-manifest orphan chunks during disconnect.++ Old cleanup could remove ``__0`` and lose the primary header before a+ later deletion silently failed. With neither header nor extent there is+ no exact upper bound left, so explicit legacy disconnect scans the full+ one-mebibyte compatibility budget instead of stopping at the first gap.+ Every discovered index is first recorded in the new durable extent.+ """+ cleared = True+ for i in range(_LEGACY_SPARSE_SCAN_SLOTS):+ chunk_key = self._overflow_key(key, i)+ try:+ piece = self._backend.get(chunk_key)+ except Exception: # noqa: BLE001 - finish the bounded cleanup pass+ cleared = False+ continue+ if piece is None:+ continue+ try:+ self._persist_cleanup_extent(key, i + 1)+ except Exception: # noqa: BLE001 - retain an untracked fragment+ cleared = False+ continue+ try:+ self._backend.delete(chunk_key)+ retained = self._backend.get(chunk_key)+ except Exception: # noqa: BLE001 - finish the bounded cleanup pass+ cleared = False+ continue+ if retained is not None:+ cleared = False+ return cleared+def get(self, key: str) -> str | None:head = self._backend.get(key)if head is None or not head.startswith(_CHUNK_SENTINEL):return head # missing, small, or legacy-plain value- count = int(head[len(_CHUNK_SENTINEL):])+ count = self._manifest_count(key, head)parts: list[str] = []for i in range(count):piece = self._backend.get(self._overflow_key(key, i))@@ -178,17 +323,37 @@ class ChunkedBackend:delete-then-write order did exactly that — a mid-write failure lostthe last good token)."""+ old_head = self._backend.get(key)+ old_active_count = (+ self._manifest_count(key, old_head)+ if old_head is not None and old_head.startswith(_CHUNK_SENTINEL)+ else 0+ )+ prior_cleanup_extent = self._cleanup_extent(key)+ prior_extent = max(old_active_count, prior_cleanup_extent)+if len(value) <= self._chunk_size:+ if prior_extent:+ # Persist the old maximum before replacing its primary header.+ # A partial cleanup can then be completed after a restart.+ self._persist_cleanup_extent(key, prior_extent)# Fits in one entry: no chunks of its own. Write it first, then# drop any old overflow pieces a previous larger value left.self._backend.set(key, value)- self._clear_overflow(key)+ if prior_extent:+ cleanup_complete = self._clear_indexed_overflow(key, prior_extent)+ else:+ cleanup_complete = self._clear_overflow(key)+ if cleanup_complete:+ self._clear_cleanup_extent_best_effort(key)return- chunks = [- value[i : i + self._chunk_size]- for i in range(0, len(value), self._chunk_size)- ]+ chunks = [value[i : i + self._chunk_size] for i in range(0, len(value), self._chunk_size)]+ tracked_extent = max(prior_extent, len(chunks))+ # Record the maximum extent before overwriting any chunk. This also+ # makes rollback cleanup recoverable if a primitive delete silently+ # fails after a partial write.+ self._persist_cleanup_extent(key, tracked_extent)# Snapshot whatever currently sits at each index we're about to# overwrite (old chunk data, or None) so a partial failure can put it# back exactly as it was rather than leaving a gap under the still-@@ -212,13 +377,32 @@ class ChunkedBackend:# The new header is live now — safe to drop old chunks the new value# no longer needs (old_count > new_count leftovers).- i = len(chunks)- while self._backend.get(self._overflow_key(key, i)) is not None:- self._backend.delete(self._overflow_key(key, i))- i += 1+ cleanup_complete = self._clear_indexed_overflow(+ key, tracked_extent, start_index=len(chunks)+ )+ if cleanup_complete:+ self._clear_cleanup_extent_best_effort(key)def delete(self, key: str) -> None:- self._clear_overflow(key)+ # Snapshot the manifest before touching any pieces. A previous partial+ # delete may already have left gaps, so an active chunked value must use+ # its exact persisted count rather than stop at the first missing index.+ head = self._backend.get(key)+ cleanup_extent = self._cleanup_extent(key)+ if head is not None and head.startswith(_CHUNK_SENTINEL):+ active_count = self._manifest_count(key, head)+ cleanup_extent = max(active_count, cleanup_extent)+ if cleanup_extent:+ overflow_cleared = self._clear_indexed_overflow(key, cleanup_extent)+ else:+ # Expensive only for an explicit disconnect of a pre-sidecar value.+ overflow_cleared = self._clear_sparse_legacy_overflow(key)+ if not overflow_cleared:+ raise RuntimeError(f"could not delete every overflow chunk for {key!r}")+ # The extent is the durable retry manifest for small values and old+ # chunks beyond a newer header. Remove it only after every named chunk+ # is verified absent, then remove the primary value/header.+ self._clear_cleanup_extent_verified(key)self._backend.delete(key)@@ -268,9 +452,16 @@ class TokenStore:try:return Tokens.from_json(raw)except (ValueError, KeyError) as exc:- raise RuntimeError(- f"corrupted token blob for plugin {plugin_id!r}: {exc}"- ) from exc+ raise RuntimeError(f"corrupted token blob for plugin {plugin_id!r}: {exc}") from excdef delete(self, plugin_id: str) -> None:- self._backend.delete(_keyring_key(plugin_id))+ key = _keyring_key(plugin_id)+ try:+ self._backend.delete(key)+ remaining = self._backend.get(key)+ except Exception as exc:+ raise RuntimeError(+ f"token deletion could not be verified for plugin {plugin_id!r}"+ ) from exc+ if remaining is not None:+ raise RuntimeError(f"token deletion failed for plugin {plugin_id!r}")diff --git a/jarvis/plugins/tool/gmail_rest.py b/jarvis/plugins/tool/gmail_rest.pyindex 1d190c4d7b..bea280a189 100644--- a/jarvis/plugins/tool/gmail_rest.py+++ b/jarvis/plugins/tool/gmail_rest.py@@ -105,38 +105,26 @@ def _default_token_provider() -> str | None:return tokens.access if tokens is not None else None-async def _default_refresher() -> bool:+async def _default_refresher(observed_access_token: str | None = None) -> bool:"""Refresh the stored Gmail token in place. Returns True on success.On an un-healable failure (revoked / invalid_client / placeholder client)it flags ``needs_reauth`` on the stored token so the Plugins view stopsshowing a green "connected" that lies and offers a Reconnect instead.Best-effort: any error returns False, never raises into the tool."""- import contextlib- import dataclasses-from jarvis.marketplace.connect_helpers import build_handler_from_catalog+ from jarvis.marketplace.refresh_scheduler import refresh_plugin_tokenfrom jarvis.marketplace.token_store import TokenStorestore = TokenStore()- tokens = store.load("gmail")- if tokens is None or not tokens.refresh:- return False- handler = build_handler_from_catalog("gmail")- if handler is None:- return False- try:- new = await handler.refresh(tokens)- except Exception as exc: # noqa: BLE001 — classify, never propagate- # A 401 followed by a failed refresh means the connection is dead;- # surface a Reconnect affordance instead of silently staying "green".- with contextlib.suppress(Exception):- store.save("gmail", dataclasses.replace(tokens, needs_reauth=True))- log.info("gmail token refresh failed, flagged needs_reauth: %s", exc)- return False- store.save("gmail", dataclasses.replace(new, needs_reauth=False))- return True-+ attempt = await refresh_plugin_token(+ "gmail",+ store,+ build_handler_from_catalog,+ force=True,+ observed_access_token=observed_access_token,+ )+ return attempt.usableclass GmailRestTool:name: str = "gmail"@@ -176,7 +164,7 @@ class GmailRestTool:self._token_provider = access_token_provider or _default_token_providerself._transport = transport- self._refresher = token_refresher or _default_refresher+ self._refresher = token_refresher# Keep-alive pool: reuse one client (one warm TLS connection to Gmail)# across list/get/send instead of a fresh handshake per request. The# tool is built once per BrainManager, so the connection stays warm for@@ -211,8 +199,12 @@ class GmailRestTool:if exc.response.status_code != 401:raise# 401 — token likely expired. Try exactly one refresh + retry.+ observed_token = headers["Authorization"].removeprefix("Bearer ")try:- refreshed = bool(await self._refresher())+ if self._refresher is None:+ refreshed = bool(await _default_refresher(observed_token))+ else:+ refreshed = bool(await self._refresher())except Exception: # noqa: BLE001 — refresher must never crash the toolrefreshed = Falseif not refreshed:diff --git a/jarvis/plugins/tool/google_calendar_rest.py b/jarvis/plugins/tool/google_calendar_rest.pyindex 524c117f84..52ba107377 100644--- a/jarvis/plugins/tool/google_calendar_rest.py+++ b/jarvis/plugins/tool/google_calendar_rest.py@@ -118,36 +118,25 @@ def _default_token_provider() -> str | None:return tokens.access if tokens is not None else None-async def _default_refresher() -> bool:+async def _default_refresher(observed_access_token: str | None = None) -> bool:"""Refresh the stored Google Calendar token in place. Returns True on success.Mirrors the Gmail refresher: on an un-healable failure (revoked /invalid_client / placeholder client) it flags ``needs_reauth`` so thePlugins view offers a Reconnect instead of a green status that lies."""- import contextlib- import dataclasses-from jarvis.marketplace.connect_helpers import build_handler_from_catalog+ from jarvis.marketplace.refresh_scheduler import refresh_plugin_tokenfrom jarvis.marketplace.token_store import TokenStorestore = TokenStore()- tokens = store.load("google_calendar")- if tokens is None or not tokens.refresh:- return False- handler = build_handler_from_catalog("google_calendar")- if handler is None:- return False- try:- new = await handler.refresh(tokens)- except Exception as exc: # noqa: BLE001 — classify, never propagate- with contextlib.suppress(Exception):- store.save(- "google_calendar", dataclasses.replace(tokens, needs_reauth=True)- )- log.info("google_calendar token refresh failed, flagged needs_reauth: %s", exc)- return False- store.save("google_calendar", dataclasses.replace(new, needs_reauth=False))- return True+ attempt = await refresh_plugin_token(+ "google_calendar",+ store,+ build_handler_from_catalog,+ force=True,+ observed_access_token=observed_access_token,+ )+ return attempt.usableclass GoogleCalendarRestTool:@@ -209,7 +198,7 @@ class GoogleCalendarRestTool:) -> None:self._token_provider = access_token_provider or _default_token_providerself._node_runner = node_runner or _default_node_runner- self._refresher = token_refresher or _default_refresher+ self._refresher = token_refresher# -- internal: token-aware call with one-shot 401 self-heal ---------------@@ -221,7 +210,10 @@ class GoogleCalendarRestTool:if result.get("ok") is False and result.get("status") == 401:# Access token likely expired — refresh once and retry.try:- refreshed = bool(await self._refresher())+ if self._refresher is None:+ refreshed = bool(await _default_refresher(token))+ else:+ refreshed = bool(await self._refresher())except Exception: # noqa: BLE001 — refresher must never crash the toolrefreshed = Falseif not refreshed:diff --git a/tests/unit/core/test_keyring_backend_recovery.py b/tests/unit/core/test_keyring_backend_recovery.pyindex 28c2692f86..e9bc5bac30 100644--- a/tests/unit/core/test_keyring_backend_recovery.py+++ b/tests/unit/core/test_keyring_backend_recovery.py@@ -4,6 +4,7 @@ An in-app save must not remain trapped in the local file backend after the OScredential store becomes usable again. Otherwise an older platform credentialshadows the newly saved value on the next process start."""+from __future__ import annotationsimport keyring@@ -34,13 +35,25 @@ class _UnavailableBackend(_MemoryBackend):raise RuntimeError("credential service unavailable")+class _ReadOnlyBackend(_MemoryBackend):+ def set_password(self, service: str, username: str, password: str) -> None:+ raise RuntimeError("WinVault write failed with error 1312")+++class _NoDeleteBackend(_MemoryBackend):+ def delete_password(self, service: str, username: str) -> None:+ return None++@pytest.fixturedef _restore_keyring_backend():original = keyring.get_keyring()+ original_platform = cfg._PLATFORM_KEYRING_BACKENDtry:yieldfinally:keyring.set_keyring(original)+ cfg._PLATFORM_KEYRING_BACKEND = original_platformdef test_explicit_save_restores_platform_backend_and_removes_stale_fallback(@@ -55,6 +68,7 @@ def test_explicit_save_restores_platform_backend_and_removes_stale_fallback(monkeypatch.setattr(cfg, "_data_dir_cache", None, raising=False)monkeypatch.setattr(cfg, "_KEYRING_BACKEND_READY", True)monkeypatch.setattr(cfg, "_FILE_BACKEND_ACTIVE", True)+ monkeypatch.setattr(cfg, "_PLATFORM_KEYRING_BACKEND", None)store = cfg._FileCredStore()store.set(cfg.KEYRING_SERVICE, "openrouter_api_key", "new-file-value")@@ -67,14 +81,46 @@ def test_explicit_save_restores_platform_backend_and_removes_stale_fallback(revision_before = cfg.secret_revision("openrouter_api_key")assert cfg.set_secret("openrouter_api_key", "new-file-value") is Trueassert (- platform_backend.get_password(cfg.KEYRING_SERVICE, "openrouter_api_key")- == "new-file-value"+ platform_backend.get_password(cfg.KEYRING_SERVICE, "openrouter_api_key") == "new-file-value")assert store.get(cfg.KEYRING_SERVICE, "openrouter_api_key") is Noneassert cfg._FILE_BACKEND_ACTIVE is Falseassert cfg.secret_revision("openrouter_api_key") == revision_before + 1+def test_platform_save_synchronizes_fallback_when_cleanup_fails(+ monkeypatch: pytest.MonkeyPatch,+ tmp_path,+ _restore_keyring_backend,+) -> None:+ platform_backend = _MemoryBackend()+ keyring.set_keyring(platform_backend)+ monkeypatch.setattr(cfg, "DATA_DIR", tmp_path)+ monkeypatch.setattr(cfg, "_data_dir_cache", None, raising=False)+ monkeypatch.setattr(cfg, "_KEYRING_BACKEND_READY", True)+ monkeypatch.setattr(cfg, "_FILE_BACKEND_ACTIVE", False)+ monkeypatch.setattr(cfg, "_PLATFORM_KEYRING_BACKEND", None)+ monkeypatch.delenv("TEST_GOOGLE_CLIENT_SECRET", raising=False)++ store = cfg._FileCredStore()+ store.set(cfg.KEYRING_SERVICE, "google_client_secret", "stale-file-value")++ def _failed_cleanup(self: cfg._FileCredStore, service: str, username: str) -> None:+ raise RuntimeError("credential fallback cleanup failed")++ monkeypatch.setattr(cfg._FileCredStore, "delete", _failed_cleanup)++ assert cfg.set_secret("google_client_secret", "new-platform-value") is True+ assert (+ platform_backend.get_password(cfg.KEYRING_SERVICE, "google_client_secret")+ == "new-platform-value"+ )+ assert store.get(cfg.KEYRING_SERVICE, "google_client_secret") == "new-platform-value"+ assert (+ cfg.get_secret("google_client_secret", "TEST_GOOGLE_CLIENT_SECRET") == "new-platform-value"+ )++def test_explicit_save_keeps_file_backend_when_platform_store_is_still_unusable(monkeypatch: pytest.MonkeyPatch,_restore_keyring_backend,@@ -84,6 +130,7 @@ def test_explicit_save_keeps_file_backend_when_platform_store_is_still_unusable(keyring.set_keyring(file_backend)monkeypatch.setattr(cfg, "_KEYRING_BACKEND_READY", True)monkeypatch.setattr(cfg, "_FILE_BACKEND_ACTIVE", True)+ monkeypatch.setattr(cfg, "_PLATFORM_KEYRING_BACKEND", None)def _restore_unavailable_platform() -> None:keyring.set_keyring(unavailable)@@ -91,9 +138,191 @@ def test_explicit_save_keeps_file_backend_when_platform_store_is_still_unusable(monkeypatch.setattr(keyring.core, "init_backend", _restore_unavailable_platform)assert cfg.set_secret("openrouter_api_key", "headless-value") is True+ assert file_backend.get_password(cfg.KEYRING_SERVICE, "openrouter_api_key") == "headless-value"+ assert keyring.get_keyring() is file_backend+ assert cfg._FILE_BACKEND_ACTIVE is True+++def test_restart_prefers_newer_file_value_over_stale_platform_value(+ monkeypatch: pytest.MonkeyPatch,+ tmp_path,+ _restore_keyring_backend,+) -> None:+ platform_backend = _MemoryBackend()+ platform_backend.set_password(+ cfg.KEYRING_SERVICE, "google_client_secret", "stale-platform-value"+ )+ keyring.set_keyring(platform_backend)+ monkeypatch.setattr(cfg, "DATA_DIR", tmp_path)+ monkeypatch.setattr(cfg, "_data_dir_cache", None, raising=False)+ monkeypatch.setattr(cfg, "_KEYRING_BACKEND_READY", True)+ monkeypatch.setattr(cfg, "_FILE_BACKEND_ACTIVE", False)+ monkeypatch.setattr(cfg, "_PLATFORM_KEYRING_BACKEND", None)+ monkeypatch.delenv("TEST_GOOGLE_CLIENT_SECRET", raising=False)+ cfg._FileCredStore().set(cfg.KEYRING_SERVICE, "google_client_secret", "new-file-value")++ assert cfg.get_secret("google_client_secret", "TEST_GOOGLE_CLIENT_SECRET") == "new-file-value"+++def test_file_swap_retains_readable_platform_slots(+ monkeypatch: pytest.MonkeyPatch,+ tmp_path,+ _restore_keyring_backend,+) -> None:+ platform_backend = _MemoryBackend()+ platform_backend.set_password(cfg.KEYRING_SERVICE, "untouched_api_key", "platform-value")+ keyring.set_keyring(platform_backend)+ monkeypatch.setattr(cfg, "DATA_DIR", tmp_path)+ monkeypatch.setattr(cfg, "_data_dir_cache", None, raising=False)+ monkeypatch.setattr(cfg, "_KEYRING_BACKEND_READY", True)+ monkeypatch.setattr(cfg, "_FILE_BACKEND_ACTIVE", False)+ monkeypatch.setattr(cfg, "_PLATFORM_KEYRING_BACKEND", None)++ assert cfg._install_file_cred_backend("test platform failure") is True++ assert cfg._PLATFORM_KEYRING_BACKEND is platform_backend+ assert cfg.get_secret("untouched_api_key", "UNSET_TEST_KEY") == "platform-value"+++def test_restore_probe_rejects_readable_but_unwritable_platform_backend(+ monkeypatch: pytest.MonkeyPatch,+ _restore_keyring_backend,+) -> None:+ file_backend = _MemoryBackend()+ read_only_backend = _ReadOnlyBackend()+ read_only_backend.values[(cfg.KEYRING_SERVICE, "existing")] = "still-readable"+ keyring.set_keyring(file_backend)+ monkeypatch.setattr(cfg, "_KEYRING_BACKEND_READY", True)+ monkeypatch.setattr(cfg, "_FILE_BACKEND_ACTIVE", True)+ monkeypatch.setattr(cfg, "_PLATFORM_KEYRING_BACKEND", None)++ def _restore_read_only_platform() -> None:+ keyring.set_keyring(read_only_backend)++ monkeypatch.setattr(keyring.core, "init_backend", _restore_read_only_platform)++ assert cfg.set_secret("google_client_secret", "new-file-value") is True+ assert keyring.get_keyring() is file_backend+ assert cfg._FILE_BACKEND_ACTIVE is True+ assert cfg._PLATFORM_KEYRING_BACKEND is read_only_backendassert (- file_backend.get_password(cfg.KEYRING_SERVICE, "openrouter_api_key")- == "headless-value"+ file_backend.get_password(cfg.KEYRING_SERVICE, "google_client_secret") == "new-file-value")+++def test_restore_probe_rejects_backend_that_cannot_delete(+ monkeypatch: pytest.MonkeyPatch,+ _restore_keyring_backend,+) -> None:+ file_backend = _MemoryBackend()+ no_delete_backend = _NoDeleteBackend()+ keyring.set_keyring(file_backend)+ monkeypatch.setattr(cfg, "_KEYRING_BACKEND_READY", True)+ monkeypatch.setattr(cfg, "_FILE_BACKEND_ACTIVE", True)+ monkeypatch.setattr(cfg, "_PLATFORM_KEYRING_BACKEND", None)++ def _restore_no_delete_platform() -> None:+ keyring.set_keyring(no_delete_backend)++ monkeypatch.setattr(keyring.core, "init_backend", _restore_no_delete_platform)++ assert cfg._try_restore_platform_keyring_backend() is Falseassert keyring.get_keyring() is file_backendassert cfg._FILE_BACKEND_ACTIVE is True+++def test_delete_removes_file_and_retained_platform_copies(+ monkeypatch: pytest.MonkeyPatch,+ tmp_path,+ _restore_keyring_backend,+) -> None:+ platform_backend = _MemoryBackend()+ platform_backend.set_password(+ cfg.KEYRING_SERVICE, "google_client_secret", "stale-platform-value"+ )+ keyring.set_keyring(platform_backend)+ monkeypatch.setattr(cfg, "DATA_DIR", tmp_path)+ monkeypatch.setattr(cfg, "_data_dir_cache", None, raising=False)+ monkeypatch.setattr(cfg, "_KEYRING_BACKEND_READY", True)+ monkeypatch.setattr(cfg, "_FILE_BACKEND_ACTIVE", False)+ monkeypatch.setattr(cfg, "_PLATFORM_KEYRING_BACKEND", None)+ monkeypatch.delenv("TEST_GOOGLE_CLIENT_SECRET", raising=False)+ assert cfg._install_file_cred_backend("test platform failure") is True+ keyring.set_password(cfg.KEYRING_SERVICE, "google_client_secret", "new-file-value")++ assert cfg.delete_secret("google_client_secret") is True+ assert platform_backend.get_password(cfg.KEYRING_SERVICE, "google_client_secret") is None+ assert cfg._FileCredStore().get(cfg.KEYRING_SERVICE, "google_client_secret") is None+ assert cfg.get_secret("google_client_secret", "TEST_GOOGLE_CLIENT_SECRET") is None+++def test_delete_rejects_active_backend_noop(+ monkeypatch: pytest.MonkeyPatch,+ tmp_path,+ _restore_keyring_backend,+) -> None:+ platform_backend = _NoDeleteBackend()+ platform_backend.set_password(+ cfg.KEYRING_SERVICE, "google_client_secret", "stale-platform-value"+ )+ keyring.set_keyring(platform_backend)+ monkeypatch.setattr(cfg, "DATA_DIR", tmp_path)+ monkeypatch.setattr(cfg, "_data_dir_cache", None, raising=False)+ monkeypatch.setattr(cfg, "_KEYRING_BACKEND_READY", True)+ monkeypatch.setattr(cfg, "_FILE_BACKEND_ACTIVE", False)+ monkeypatch.setattr(cfg, "_PLATFORM_KEYRING_BACKEND", None)+ monkeypatch.delenv("TEST_GOOGLE_CLIENT_SECRET", raising=False)+ cfg._FileCredStore().set(cfg.KEYRING_SERVICE, "google_client_secret", "new-file-value")++ assert cfg.delete_secret("google_client_secret") is False+ assert (+ platform_backend.get_password(cfg.KEYRING_SERVICE, "google_client_secret")+ == "stale-platform-value"+ )+ assert cfg._FileCredStore().get(cfg.KEYRING_SERVICE, "google_client_secret") == "new-file-value"+ assert cfg.get_secret("google_client_secret", "TEST_GOOGLE_CLIENT_SECRET") == "new-file-value"+++def test_delete_rejects_file_fallback_noop(+ monkeypatch: pytest.MonkeyPatch,+ tmp_path,+ _restore_keyring_backend,+) -> None:+ platform_backend = _MemoryBackend()+ keyring.set_keyring(platform_backend)+ monkeypatch.setattr(cfg, "DATA_DIR", tmp_path)+ monkeypatch.setattr(cfg, "_data_dir_cache", None, raising=False)+ monkeypatch.setattr(cfg, "_KEYRING_BACKEND_READY", True)+ monkeypatch.setattr(cfg, "_FILE_BACKEND_ACTIVE", False)+ monkeypatch.setattr(cfg, "_PLATFORM_KEYRING_BACKEND", None)++ store = cfg._FileCredStore()+ store.set(cfg.KEYRING_SERVICE, "google_client_secret", "stale-file-value")+ monkeypatch.setattr(cfg._FileCredStore, "delete", lambda *_args: None)++ assert cfg.delete_secret("google_client_secret") is False+ assert store.get(cfg.KEYRING_SERVICE, "google_client_secret") == "stale-file-value"+++def test_failed_retained_platform_delete_preserves_newer_file_copy(+ monkeypatch: pytest.MonkeyPatch,+ tmp_path,+ _restore_keyring_backend,+) -> None:+ platform_backend = _NoDeleteBackend()+ platform_backend.set_password(+ cfg.KEYRING_SERVICE, "google_client_secret", "stale-platform-value"+ )+ keyring.set_keyring(platform_backend)+ monkeypatch.setattr(cfg, "DATA_DIR", tmp_path)+ monkeypatch.setattr(cfg, "_data_dir_cache", None, raising=False)+ monkeypatch.setattr(cfg, "_KEYRING_BACKEND_READY", True)+ monkeypatch.setattr(cfg, "_FILE_BACKEND_ACTIVE", False)+ monkeypatch.setattr(cfg, "_PLATFORM_KEYRING_BACKEND", None)+ monkeypatch.delenv("TEST_GOOGLE_CLIENT_SECRET", raising=False)+ assert cfg._install_file_cred_backend("test platform failure") is True+ keyring.set_password(cfg.KEYRING_SERVICE, "google_client_secret", "new-file-value")++ assert cfg.delete_secret("google_client_secret") is False+ assert cfg._FileCredStore().get(cfg.KEYRING_SERVICE, "google_client_secret") == "new-file-value"+ assert cfg.get_secret("google_client_secret", "TEST_GOOGLE_CLIENT_SECRET") == "new-file-value"diff --git a/tests/unit/core/test_secret_locked_keyring.py b/tests/unit/core/test_secret_locked_keyring.pyindex d48e27bfa6..a177c0e33f 100644--- a/tests/unit/core/test_secret_locked_keyring.py+++ b/tests/unit/core/test_secret_locked_keyring.py@@ -11,6 +11,7 @@ engaged for ``fail.Keyring`` was skipped, ``keyring.set_password`` raisedfailed and nothing persisted. A locked/unusable OS keyring must degrade to thefile store at RUNTIME, keeping the "recoverable in-app" guarantee (CLAUDE.md §3)."""+from __future__ import annotationsimport keyring@@ -81,18 +82,18 @@ def test_delete_secret_reports_failure_on_locked_keyring_without_swapping_backenswapping the process-global backend to the file store and claimingsuccess — a real OS-keyring-held value would otherwise surviveuntouched and reappear once the lock clears (the resurrection bug this- fix closes). The file-store copy (if any) is still removed so a- file-only value never lingers, but the overall result is False because- the OS-keyring side is unconfirmed.+ fix closes). The newer file-store copy is preserved while the OS-keyring+ side is unconfirmed, so it continues to shadow the stale platform value+ and the deletion can be retried later."""store = c._FileCredStore()store.set(c.KEYRING_SERVICE, "del_prior", "y")original_keyring = keyring.get_keyring()assert c.delete_secret("del_prior") is False- # The file copy is gone...- assert c._FileCredStore().get(c.KEYRING_SERVICE, "del_prior") is None- # ...but the failed delete must NOT have swapped the active backend.+ # The failed delete must preserve the fallback and must NOT swap the+ # active backend.+ assert c._FileCredStore().get(c.KEYRING_SERVICE, "del_prior") == "y"assert keyring.get_keyring() is original_keyringassert c._FILE_BACKEND_ACTIVE is False@@ -110,6 +111,7 @@ def test_delete_secret_treats_already_absent_as_success(monkeypatch, tmp_path) -raise PasswordDeleteError("not found")monkeypatch.setattr(keyring, "delete_password", _raise_missing)+ monkeypatch.setattr(keyring, "get_password", lambda *_args: None)assert c.delete_secret("never_stored_key") is True@@ -122,6 +124,7 @@ def test_delete_secret_removes_stale_file_value_when_os_delete_succeeds(monkeypatch.setattr(c, "_KEYRING_BACKEND_READY", True)monkeypatch.setattr(c, "_FILE_BACKEND_ACTIVE", False)monkeypatch.setattr(keyring, "delete_password", lambda *_args: None)+ monkeypatch.setattr(keyring, "get_password", lambda *_args: None)store = c._FileCredStore()store.set(c.KEYRING_SERVICE, "stale_key", "stale-value")diff --git a/tests/unit/marketplace/test_pkce_resource.py b/tests/unit/marketplace/test_pkce_resource.pyindex 403af775bc..3bad189871 100644--- a/tests/unit/marketplace/test_pkce_resource.py+++ b/tests/unit/marketplace/test_pkce_resource.py@@ -123,10 +123,12 @@ async def test_exchange_includes_client_secret_when_configured(assert captured["data"]["client_secret"] == TEST_CLIENT_SECRETassert captured["data"]["code_verifier"] == "verifier"assert tokens.refresh == "refresh"+ assert tokens.extra["client_id"] == "cid"+ assert tokens.extra["client_secret"] == TEST_CLIENT_SECRET@pytest.mark.asyncio-async def test_refresh_includes_client_secret_when_configured(+async def test_refresh_legacy_token_uses_current_client_config(monkeypatch: pytest.MonkeyPatch,):captured: dict = {}@@ -163,3 +165,122 @@ async def test_refresh_includes_client_secret_when_configured(assert captured["data"]["client_secret"] == TEST_CLIENT_SECRETassert captured["data"]["refresh_token"] == OLD_REFRESH_TOKENassert tokens.refresh == OLD_REFRESH_TOKEN+ assert tokens.extra["client_id"] == "cid"+ assert tokens.extra["client_secret"] == TEST_CLIENT_SECRET+++async def test_refresh_legacy_public_client_binds_client_id_without_secret(+ monkeypatch: pytest.MonkeyPatch,+):+ captured: dict = {}++ async def _fake_post(self, url, *args, **kwargs): # noqa: ANN001, ANN002, ANN003+ captured["data"] = kwargs["data"]+ return httpx.Response(+ 200,+ json={"access_token": "new-access", "expires_in": 3600},+ )++ monkeypatch.setattr(httpx.AsyncClient, "post", _fake_post)++ cfg = PkceLoopbackConfig(+ plugin_id="google_drive",+ authorization_url="https://accounts.google.com/o/oauth2/v2/auth",+ token_url="https://oauth2.googleapis.com/token", # noqa: S106+ client_id="public-client",+ callback_port=0,+ scopes=["https://www.googleapis.com/auth/drive.file"],+ )++ tokens = await PkceLoopbackHandler(cfg).refresh(+ Tokens(+ access="old-access",+ refresh=OLD_REFRESH_TOKEN,+ extra={"provider_hint": "google"},+ )+ )++ assert captured["data"]["client_id"] == "public-client"+ assert "client_secret" not in captured["data"]+ assert tokens.extra == {+ "provider_hint": "google",+ "client_id": "public-client",+ }+++async def test_refresh_uses_issuing_client_after_config_drift_and_keyring_loss(+ monkeypatch: pytest.MonkeyPatch,+):+ captured: dict = {}++ async def _fake_post(self, url, *args, **kwargs): # noqa: ANN001, ANN002, ANN003+ captured["data"] = kwargs["data"]+ return httpx.Response(+ 200,+ json={"access_token": "new-access", "expires_in": 3600},+ )++ monkeypatch.setattr(httpx.AsyncClient, "post", _fake_post)++ cfg = PkceLoopbackConfig(+ plugin_id="google_drive",+ authorization_url="https://accounts.google.com/o/oauth2/v2/auth",+ token_url="https://oauth2.googleapis.com/token", # noqa: S106+ client_id="replacement-client",+ callback_port=0,+ scopes=["https://www.googleapis.com/auth/drive.file"],+ )+ current = Tokens(+ access="old-access",+ refresh=OLD_REFRESH_TOKEN,+ extra={+ "client_id": "issuing-client",+ "client_secret": TEST_CLIENT_SECRET,+ },+ )++ tokens = await PkceLoopbackHandler(cfg).refresh(current)++ assert captured["data"]["client_id"] == "issuing-client"+ assert captured["data"]["client_secret"] == TEST_CLIENT_SECRET+ assert tokens.refresh == OLD_REFRESH_TOKEN+ assert tokens.extra["client_id"] == "issuing-client"+ assert tokens.extra["client_secret"] == TEST_CLIENT_SECRET+++async def test_refresh_bound_public_client_ignores_later_configured_secret(+ monkeypatch: pytest.MonkeyPatch,+):+ captured: dict = {}++ async def _fake_post(self, url, *args, **kwargs): # noqa: ANN001, ANN002, ANN003+ captured["data"] = kwargs["data"]+ return httpx.Response(+ 200,+ json={"access_token": "new-access", "expires_in": 3600},+ )++ monkeypatch.setattr(httpx.AsyncClient, "post", _fake_post)++ cfg = PkceLoopbackConfig(+ plugin_id="google_drive",+ authorization_url="https://accounts.google.com/o/oauth2/v2/auth",+ token_url="https://oauth2.googleapis.com/token", # noqa: S106+ client_id="replacement-client",+ client_secret="replacement-secret", # noqa: S106+ callback_port=0,+ scopes=["https://www.googleapis.com/auth/drive.file"],+ )+ current = Tokens(+ access="old-access",+ refresh=OLD_REFRESH_TOKEN,+ extra={"client_id": "issuing-public-client"},+ )++ await PkceLoopbackHandler(cfg).refresh(current)++ assert captured["data"]["client_id"] == "issuing-public-client"+ assert "client_secret" not in captured["data"]diff --git a/tests/unit/marketplace/test_plugin_registry.py b/tests/unit/marketplace/test_plugin_registry.pyindex 0fb6efbfb4..506fa99316 100644--- a/tests/unit/marketplace/test_plugin_registry.py+++ b/tests/unit/marketplace/test_plugin_registry.py@@ -11,8 +11,13 @@ def _calendar_plugin() -> PluginSpec:category="Productivity", logo_slug="googlecalendar",auth={"mode": "pat_paste", "token_creation_url": "x", "token_prefix": "ya29","validation_endpoint": "x", "instruction_md": "x"},- mcp_server={"transport": "http", "url": "https://cal/mcp",- "auth_header_template": "Authorization: Bearer $plugin_google-calendar_access_token"},+ mcp_server={+ "transport": "http",+ "url": "https://cal/mcp",+ "auth_header_template": (+ "Authorization: Bearer $plugin_google-calendar_access_token"+ ),+ },)@@ -279,3 +284,308 @@ async def test_transient_connect_failure_does_not_mark_needs_reauth():assert tokens is not Noneassert tokens.needs_reauth is Falseassert "Connection closed" in (reg.last_connect_error("flaky") or "")+++class _RefreshHandler:+ def __init__(self, *, failure: Exception | None = None) -> None:+ self.failure = failure+ self.calls = 0++ async def refresh(self, current: Tokens) -> Tokens:+ self.calls += 1+ if self.failure is not None:+ raise self.failure+ return Tokens(access="fresh-access", refresh="fresh-refresh")+++async def test_auth_connect_failure_refreshes_and_retries_once() -> None:+ plugin = _plugin("refreshable")+ catalog = PluginCatalog(version=1, schema_version="1", plugins=[plugin])+ store = TokenStore(InMemoryBackend())+ store.save(plugin.id, Tokens(access="stale-access", refresh="refresh-1"))+ handler = _RefreshHandler()+ client_calls = 0++ def client_factory(spec, env_overrides=None): # noqa: ANN001+ nonlocal client_calls+ client_calls += 1+ cls = _FailingClient if client_calls == 1 else _FakeClient+ return cls(spec, env_overrides=env_overrides)++ reg = PluginToolRegistry(+ catalog=catalog,+ token_store=store,+ client_factory=client_factory,+ bus=_RecordingBus(),+ refresh_handler_builder=lambda _plugin_id: handler,+ )++ await reg.bootstrap()++ assert handler.calls == 1+ assert client_calls == 2+ assert store.load(plugin.id).access == "fresh-access"+ assert reg.live_tool_count(plugin.id) == 1+ assert reg.last_connect_error(plugin.id) is None+++async def test_transient_refresh_failure_does_not_poison_token() -> None:+ plugin = _plugin("refresh-transient")+ catalog = PluginCatalog(version=1, schema_version="1", plugins=[plugin])+ store = TokenStore(InMemoryBackend())+ store.save(plugin.id, Tokens(access="stale-access", refresh="refresh-1"))+ handler = _RefreshHandler(failure=RuntimeError("refresh HTTP 503"))+ client_calls = 0++ def client_factory(spec, env_overrides=None): # noqa: ANN001+ nonlocal client_calls+ client_calls += 1+ return _FailingClient(spec, env_overrides=env_overrides)++ reg = PluginToolRegistry(+ catalog=catalog,+ token_store=store,+ client_factory=client_factory,+ bus=_RecordingBus(),+ refresh_handler_builder=lambda _plugin_id: handler,+ )++ await reg.bootstrap()++ assert handler.calls == 1+ assert client_calls == 1+ assert store.load(plugin.id).needs_reauth is False+ assert "401" in (reg.last_connect_error(plugin.id) or "")+++async def test_terminal_refresh_failure_marks_needs_reauth() -> None:+ plugin = _plugin("refresh-revoked")+ catalog = PluginCatalog(version=1, schema_version="1", plugins=[plugin])+ store = TokenStore(InMemoryBackend())+ store.save(plugin.id, Tokens(access="stale-access", refresh="refresh-1"))+ handler = _RefreshHandler(+ failure=RuntimeError('refresh HTTP 400: {"error":"invalid_grant"}')+ )+ reg = PluginToolRegistry(+ catalog=catalog,+ token_store=store,+ client_factory=_FailingClient,+ bus=_RecordingBus(),+ refresh_handler_builder=lambda _plugin_id: handler,+ )++ await reg.bootstrap()++ assert handler.calls == 1+ assert store.load(plugin.id).needs_reauth is True+++async def test_auth_shaped_retry_failure_marks_fresh_token_needs_reauth() -> None:+ plugin = _plugin("retry-rejected")+ catalog = PluginCatalog(version=1, schema_version="1", plugins=[plugin])+ store = TokenStore(InMemoryBackend())+ store.save(plugin.id, Tokens(access="stale-access", refresh="refresh-1"))+ handler = _RefreshHandler()+ client_calls = 0++ def client_factory(spec, env_overrides=None): # noqa: ANN001+ nonlocal client_calls+ client_calls += 1+ return _FailingClient(spec, env_overrides=env_overrides)++ reg = PluginToolRegistry(+ catalog=catalog,+ token_store=store,+ client_factory=client_factory,+ bus=_RecordingBus(),+ refresh_handler_builder=lambda _plugin_id: handler,+ )++ await reg.bootstrap()++ saved = store.load(plugin.id)+ assert handler.calls == 1+ assert client_calls == 2+ assert saved.access == "fresh-access"+ assert saved.needs_reauth is True+++async def test_transient_retry_failure_preserves_fresh_token() -> None:+ class _TransientFailClient(_FakeClient):+ async def start(self) -> None:+ raise RuntimeError("Connection closed")++ plugin = _plugin("retry-transient")+ catalog = PluginCatalog(version=1, schema_version="1", plugins=[plugin])+ store = TokenStore(InMemoryBackend())+ store.save(plugin.id, Tokens(access="stale-access", refresh="refresh-1"))+ handler = _RefreshHandler()+ client_calls = 0++ def client_factory(spec, env_overrides=None): # noqa: ANN001+ nonlocal client_calls+ client_calls += 1+ cls = _FailingClient if client_calls == 1 else _TransientFailClient+ return cls(spec, env_overrides=env_overrides)++ reg = PluginToolRegistry(+ catalog=catalog,+ token_store=store,+ client_factory=client_factory,+ bus=_RecordingBus(),+ refresh_handler_builder=lambda _plugin_id: handler,+ )++ await reg.bootstrap()++ saved = store.load(plugin.id)+ assert handler.calls == 1+ assert client_calls == 2+ assert saved.access == "fresh-access"+ assert saved.needs_reauth is False+ assert "Connection closed" in (reg.last_connect_error(plugin.id) or "")+++async def test_new_grant_during_auth_retry_is_not_marked_needs_reauth() -> None:+ import asyncio++ retry_entered = asyncio.Event()+ release_retry = asyncio.Event()++ class _BlockingAuthFailClient(_FakeClient):+ async def start(self) -> None:+ retry_entered.set()+ await release_retry.wait()+ raise RuntimeError("HTTP 401 unauthorized")++ plugin = _plugin("retry-reconnected")+ catalog = PluginCatalog(version=1, schema_version="1", plugins=[plugin])+ store = TokenStore(InMemoryBackend())+ store.save(plugin.id, Tokens(access="stale-access", refresh="refresh-1"))+ handler = _RefreshHandler()+ client_calls = 0++ def client_factory(spec, env_overrides=None): # noqa: ANN001+ nonlocal client_calls+ client_calls += 1+ cls = _FailingClient if client_calls == 1 else _BlockingAuthFailClient+ return cls(spec, env_overrides=env_overrides)++ reg = PluginToolRegistry(+ catalog=catalog,+ token_store=store,+ client_factory=client_factory,+ bus=_RecordingBus(),+ refresh_handler_builder=lambda _plugin_id: handler,+ )++ bootstrap = asyncio.create_task(reg.bootstrap())+ await asyncio.wait_for(retry_entered.wait(), timeout=1.0)+ store.save(+ plugin.id,+ Tokens(access="new-user-grant", refresh="new-user-refresh"),+ )+ release_retry.set()+ await bootstrap++ saved = store.load(plugin.id)+ assert handler.calls == 1+ assert client_calls == 2+ assert saved.access == "new-user-grant"+ assert saved.needs_reauth is False+++async def test_cancelled_connect_stops_untracked_client_before_propagating() -> None:+ import asyncio++ start_entered = asyncio.Event()+ stop_entered = asyncio.Event()+ release_stop = asyncio.Event()+ clients = []++ class _CancellationClient(_FakeClient):+ def __init__(self, spec, env_overrides=None): # noqa: ANN001+ super().__init__(spec, env_overrides=env_overrides)+ self.open = True+ clients.append(self)++ async def start(self) -> None:+ start_entered.set()+ await asyncio.Event().wait()++ async def stop(self) -> None:+ stop_entered.set()+ await release_stop.wait()+ self.open = False++ plugin = _plugin("cancel-connect")+ catalog = PluginCatalog(version=1, schema_version="1", plugins=[plugin])+ reg = PluginToolRegistry(+ catalog=catalog,+ token_store=_store_for(plugin.id),+ client_factory=_CancellationClient,+ bus=_RecordingBus(),+ )++ bootstrap = asyncio.create_task(reg.bootstrap())+ await asyncio.wait_for(start_entered.wait(), timeout=1.0)+ bootstrap.cancel()+ await asyncio.wait_for(stop_entered.wait(), timeout=1.0)+ await asyncio.sleep(0)+ assert not bootstrap.done()+ release_stop.set()+ with pytest.raises(asyncio.CancelledError):+ await bootstrap++ assert clients and clients[0].open is False+ assert reg._clients == {}+++async def test_cancelled_disconnect_finishes_stop_before_untracking_client() -> None:+ import asyncio++ stop_entered = asyncio.Event()+ release_stop = asyncio.Event()+ clients = []++ class _CancellationClient(_FakeClient):+ def __init__(self, spec, env_overrides=None): # noqa: ANN001+ super().__init__(spec, env_overrides=env_overrides)+ self.open = True+ clients.append(self)++ async def stop(self) -> None:+ stop_entered.set()+ await release_stop.wait()+ self.open = False++ plugin = _plugin("cancel-disconnect")+ catalog = PluginCatalog(version=1, schema_version="1", plugins=[plugin])+ reg = PluginToolRegistry(+ catalog=catalog,+ token_store=_store_for(plugin.id),+ client_factory=_CancellationClient,+ bus=_RecordingBus(),+ )+ await reg.bootstrap()++ shutdown = asyncio.create_task(reg.stop())+ await asyncio.wait_for(stop_entered.wait(), timeout=1.0)+ shutdown.cancel()+ await asyncio.sleep(0)+ assert not shutdown.done()+ assert plugin.id in reg._clients+ release_stop.set()+ with pytest.raises(asyncio.CancelledError):+ await shutdown++ assert clients and clients[0].open is False+ assert plugin.id not in reg._clientsdiff --git a/tests/unit/marketplace/test_refresh_lifecycle.py b/tests/unit/marketplace/test_refresh_lifecycle.pynew file mode 100644index 0000000000..97b8f0a4f1--- /dev/null+++ b/tests/unit/marketplace/test_refresh_lifecycle.py@@ -0,0 +1,165 @@+"""Shared WebServer lifecycle coverage for marketplace OAuth refresh."""++from __future__ import annotations++import asyncio++import pytest++from jarvis.core.bus import EventBus+from jarvis.core.config import JarvisConfig+from jarvis.ui.web.server import WebServer+++class _FakeRefreshScheduler:+ instances: list[_FakeRefreshScheduler] = []++ def __init__(self, *args, **kwargs) -> None: # noqa: ANN002, ANN003+ self.args = args+ self.kwargs = kwargs+ self.start_calls = 0+ self.stop_calls = 0+ self.instances.append(self)++ def start(self) -> None:+ self.start_calls += 1++ async def stop(self) -> None:+ self.stop_calls += 1++[email protected](autouse=True)+def _reset_fake_scheduler() -> None:+ _FakeRefreshScheduler.instances.clear()+++async def test_refresh_scheduler_is_deferred_and_started_exactly_once(+ monkeypatch: pytest.MonkeyPatch,+) -> None:+ from jarvis.marketplace import connect_helpers, refresh_scheduler++ monkeypatch.setattr(refresh_scheduler, "RefreshScheduler", _FakeRefreshScheduler)+ monkeypatch.setattr(connect_helpers, "connected_plugin_ids", lambda _store: [])+ monkeypatch.setattr(connect_helpers, "build_handler_from_catalog", lambda _pid: None)++ server = WebServer(JarvisConfig(), bus=EventBus())+ server._schedule_marketplace_refresh_scheduler()+ server._schedule_marketplace_refresh_scheduler()++ # call_soon keeps catalog/keyring work outside the caller's readiness turn.+ assert _FakeRefreshScheduler.instances == []+ await asyncio.sleep(0)++ assert len(_FakeRefreshScheduler.instances) == 1+ scheduler = _FakeRefreshScheduler.instances[0]+ assert scheduler.start_calls == 1+ assert server.app.state.refresh_scheduler is scheduler++ server._schedule_marketplace_refresh_scheduler()+ await asyncio.sleep(0)+ assert len(_FakeRefreshScheduler.instances) == 1++ await server.stop()+ assert scheduler.stop_calls == 1+ assert server.app.state.refresh_scheduler is None+++async def test_stop_cancels_a_deferred_scheduler_start() -> None:+ server = WebServer(JarvisConfig(), bus=EventBus())+ server._schedule_marketplace_refresh_scheduler()++ await server._stop_marketplace_refresh_scheduler()+ await asyncio.sleep(0)++ assert server._refresh_scheduler is None+ assert server._refresh_scheduler_start_handle is None+ assert server.app.state.refresh_scheduler is None+++async def test_stop_cancels_queued_live_session_refresh(+ monkeypatch: pytest.MonkeyPatch,+) -> None:+ from jarvis.marketplace import connect_helpers, refresh_scheduler++ monkeypatch.setattr(refresh_scheduler, "RefreshScheduler", _FakeRefreshScheduler)+ monkeypatch.setattr(connect_helpers, "connected_plugin_ids", lambda _store: [])+ monkeypatch.setattr(connect_helpers, "build_handler_from_catalog", lambda _pid: None)++ entered = asyncio.Event()+ cancelled = asyncio.Event()++ class _BlockingRegistry:+ calls = 0++ async def refresh_plugin(self, _plugin_id: str) -> None:+ self.calls += 1+ entered.set()+ try:+ await asyncio.Event().wait()+ finally:+ cancelled.set()++ server = WebServer(JarvisConfig(), bus=EventBus())+ registry = _BlockingRegistry()+ server._plugin_registry = registry+ server._schedule_marketplace_refresh_scheduler()+ await asyncio.sleep(0)++ scheduler = _FakeRefreshScheduler.instances[0]+ scheduler.kwargs["on_refreshed"]("gmail")+ await entered.wait()+ assert len(server._refresh_registry_tasks) == 1++ await server._stop_marketplace_refresh_scheduler()++ assert cancelled.is_set()+ assert server._refresh_registry_tasks == set()+ scheduler.kwargs["on_refreshed"]("google_calendar")+ await asyncio.sleep(0)+ assert registry.calls == 1+++async def test_shared_webserver_start_schedules_refresh_after_boot(+ monkeypatch: pytest.MonkeyPatch,+) -> None:+ server = WebServer(JarvisConfig(), bus=EventBus())+ scheduled: list[str] = []++ async def _noop_async() -> None:+ return None++ for name in (+ "_init_mission_stack",+ "_init_screenshot_retention",+ "_init_flight_recorder",+ "_init_wiki_integration",+ "_init_task_stack",+ "_init_channel_stack",+ ):+ monkeypatch.setattr(server, name, _noop_async)+ monkeypatch.setattr(server, "_init_wiki_boot_index", lambda **_kwargs: None)+ monkeypatch.setattr(server, "_init_wiki_watcher", lambda: None)+ monkeypatch.setattr(server, "_init_session_stack", lambda: None)+ monkeypatch.setattr(+ server,+ "_schedule_marketplace_refresh_scheduler",+ lambda: scheduled.append("refresh"),+ )+ server._voice_ready = True+ server._skill_registry = None+ server._doc_registry = None+ server._cli_registry = None+ server._plugin_registry = None+ server._board_aggregator = None+ server._board_evaluator = None+ server._bio_scheduler = None+ server._pending_reloads.clear()++ await server.start(start_serving=False)+ await server._channel_stack_task++ assert scheduled == ["refresh"]diff --git a/tests/unit/marketplace/test_refresh_scheduler.py b/tests/unit/marketplace/test_refresh_scheduler.pyindex 31f4de569f..4c35f5d078 100644--- a/tests/unit/marketplace/test_refresh_scheduler.py+++ b/tests/unit/marketplace/test_refresh_scheduler.py@@ -2,10 +2,12 @@OAuth access tokens expire (30 min HubSpot ... 24 h Linear). The schedulerrefreshes tokens nearing expiry via each plugin's AuthHandler and writes them-back; a `revoked` refresh drops the entry so the UI can prompt a reconnect.+back; a revoked grant is retained and flagged so the UI can prompt a reconnect."""+from __future__ import annotations+import asyncioimport loggingfrom datetime import UTC, datetime, timedelta@@ -18,6 +20,7 @@ from jarvis.marketplace.refresh_scheduler import (SKIPPED,RefreshScheduler,refresh_due_tokens,+ refresh_plugin_token,)from jarvis.marketplace.token_store import InMemoryBackend, Tokens, TokenStore@@ -58,6 +61,23 @@ class _FakeHandler:return {"Authorization": f"Bearer {tokens.access}"}+class _InFlightHandler(_FakeHandler):+ """Pause a provider refresh so a test can mutate the stored grant."""++ def __init__(self, plugin_id: str, new_tokens=None, raise_exc=None) -> None:+ super().__init__(plugin_id, new_tokens=new_tokens, raise_exc=raise_exc)+ self.entered = asyncio.Event()+ self.release = asyncio.Event()++ async def refresh(self, current: Tokens) -> Tokens:+ self.calls += 1+ self.entered.set()+ await self.release.wait()+ if self._raise is not None:+ raise self._raise+ return self._new++@pytest.mark.asyncioasync def test_refreshes_token_near_expiry() -> None:store = _store()@@ -120,17 +140,230 @@ async def test_revoked_refresh_marks_needs_reauth_and_keeps_token() -> None:@pytest.mark.asyncio-async def test_successful_refresh_clears_stale_needs_reauth() -> None:+async def test_needs_reauth_token_is_not_retried_every_cycle() -> None:store = _store()- store.save("notion", Tokens(access="a0", refresh="r0", needs_reauth=True,- expires_at=datetime.now(UTC) + timedelta(seconds=60)))+ store.save(+ "notion",+ Tokens(+ access="a0",+ refresh="r0",+ needs_reauth=True,+ expires_at=datetime.now(UTC) + timedelta(seconds=60),+ ),+ )handler = _FakeHandler("notion", new_tokens=Tokens(access="a1", refresh="r1"))outcomes = await refresh_due_tokens(["notion"], store, lambda pid: handler)- assert outcomes == {"notion": REFRESHED}- healed = store.load("notion")- assert healed.access == "a1" and healed.needs_reauth is False+ assert outcomes == {"notion": SKIPPED}+ kept = store.load("notion")+ assert kept.access == "a0" and kept.needs_reauth is True+ assert handler.calls == 0+++async def test_concurrent_forced_refresh_is_single_flight() -> None:+ store = _store()+ store.save("gmail", Tokens(access="a0", refresh="r0"))+ entered = asyncio.Event()+ release = asyncio.Event()++ class _BlockingHandler(_FakeHandler):+ async def refresh(self, current: Tokens) -> Tokens:+ self.calls += 1+ entered.set()+ await release.wait()+ return Tokens(access="a1", refresh="r1")++ handler = _BlockingHandler("gmail")+ observed = store.load("gmail").access+ first = asyncio.create_task(+ refresh_plugin_token(+ "gmail",+ store,+ lambda _plugin_id: handler,+ force=True,+ observed_access_token=observed,+ )+ )+ await entered.wait()+ second = asyncio.create_task(+ refresh_plugin_token(+ "gmail",+ store,+ lambda _plugin_id: handler,+ force=True,+ observed_access_token=observed,+ )+ )+ release.set()+ attempts = await asyncio.gather(first, second)++ assert handler.calls == 1+ assert {attempt.outcome for attempt in attempts} == {REFRESHED, SKIPPED}+ assert all(attempt.usable for attempt in attempts)+ assert store.load("gmail").access == "a1"+++async def test_successful_refresh_does_not_overwrite_concurrent_reconnect() -> None:+ store = _store()+ store.save("gmail", Tokens(access="old-access", refresh="old-refresh"))+ handler = _InFlightHandler(+ "gmail",+ new_tokens=Tokens(access="stale-refresh-access", refresh="rotated-refresh"),+ )+ task = asyncio.create_task(+ refresh_plugin_token("gmail", store, lambda _plugin_id: handler, force=True)+ )+ await handler.entered.wait()++ new_grant = Tokens(+ access="new-grant-access",+ refresh="new-grant-refresh",+ extra={"grant": "replacement"},+ )+ store.save("gmail", new_grant)+ handler.release.set()+ attempt = await task++ assert attempt.outcome == SKIPPED+ assert attempt.usable is True+ assert attempt.access_changed is True+ assert store.load("gmail") == new_grant+++async def test_successful_refresh_does_not_restore_concurrent_disconnect() -> None:+ store = _store()+ store.save("gmail", Tokens(access="old-access", refresh="old-refresh"))+ handler = _InFlightHandler(+ "gmail",+ new_tokens=Tokens(access="stale-refresh-access", refresh="rotated-refresh"),+ )+ task = asyncio.create_task(+ refresh_plugin_token("gmail", store, lambda _plugin_id: handler, force=True)+ )+ await handler.entered.wait()++ store.delete("gmail")+ handler.release.set()+ attempt = await task++ assert attempt.outcome == SKIPPED+ assert attempt.usable is False+ assert store.load("gmail") is None+++async def test_terminal_refresh_error_does_not_poison_concurrent_reconnect() -> None:+ store = _store()+ store.save("gmail", Tokens(access="old-access", refresh="old-refresh"))+ handler = _InFlightHandler("gmail", raise_exc=RuntimeError("invalid_grant"))+ task = asyncio.create_task(+ refresh_plugin_token("gmail", store, lambda _plugin_id: handler, force=True)+ )+ await handler.entered.wait()++ new_grant = Tokens(access="new-grant-access", refresh="new-grant-refresh")+ store.save("gmail", new_grant)+ handler.release.set()+ attempt = await task++ assert attempt.outcome == SKIPPED+ assert attempt.usable is True+ assert attempt.access_changed is True+ assert store.load("gmail") == new_grant+++async def test_terminal_refresh_error_does_not_restore_concurrent_disconnect() -> None:+ store = _store()+ store.save("gmail", Tokens(access="old-access", refresh="old-refresh"))+ handler = _InFlightHandler("gmail", raise_exc=RuntimeError("invalid_grant"))+ task = asyncio.create_task(+ refresh_plugin_token("gmail", store, lambda _plugin_id: handler, force=True)+ )+ await handler.entered.wait()++ store.delete("gmail")+ handler.release.set()+ attempt = await task++ assert attempt.outcome == SKIPPED+ assert attempt.usable is False+ assert store.load("gmail") is None+++async def test_transient_refresh_error_reuses_concurrent_reconnect() -> None:+ store = _store()+ store.save("gmail", Tokens(access="old-access", refresh="old-refresh"))+ handler = _InFlightHandler("gmail", raise_exc=RuntimeError("HTTP 503"))+ task = asyncio.create_task(+ refresh_plugin_token("gmail", store, lambda _plugin_id: handler, force=True)+ )+ await handler.entered.wait()++ new_grant = Tokens(access="new-grant-access", refresh="new-grant-refresh")+ store.save("gmail", new_grant)+ handler.release.set()+ attempt = await task++ assert attempt.outcome == SKIPPED+ assert attempt.usable is True+ assert attempt.access_changed is True+ assert store.load("gmail") == new_grant+++async def test_transient_refresh_error_observes_concurrent_disconnect() -> None:+ store = _store()+ store.save("gmail", Tokens(access="old-access", refresh="old-refresh"))+ handler = _InFlightHandler("gmail", raise_exc=RuntimeError("HTTP 503"))+ task = asyncio.create_task(+ refresh_plugin_token("gmail", store, lambda _plugin_id: handler, force=True)+ )+ await handler.entered.wait()++ store.delete("gmail")+ handler.release.set()+ attempt = await task++ assert attempt.outcome == SKIPPED+ assert attempt.usable is False+ assert store.load("gmail") is None+++async def test_refresh_preserves_rotating_metadata_and_refresh_token() -> None:+ store = _store()+ store.save(+ "linear",+ Tokens(+ access="a0",+ refresh="r0",+ extra={"client_id": "client-1", "shared": "old"},+ ),+ )+ handler = _FakeHandler(+ "linear",+ new_tokens=Tokens(+ access="a1",+ refresh=None,+ extra={"scope": "read", "shared": "new"},+ ),+ )++ attempt = await refresh_plugin_token("linear", store, lambda _plugin_id: handler, force=True)++ saved = store.load("linear")+ assert attempt.outcome == REFRESHED+ assert saved.refresh == "r0"+ assert saved.extra["client_id"] == "client-1"+ assert saved.extra["scope"] == "read"+ assert saved.extra["shared"] == "new"+ assert "last_refreshed" in saved.extra@pytest.mark.asyncio@@ -142,7 +375,7 @@ async def test_transient_refresh_failure_keeps_entry() -> None:outcomes = await refresh_due_tokens(["gmail"], store, lambda pid: handler)assert outcomes == {"gmail": FAILED}- # Transient failure must NOT delete the token — only `revoked` does.+ # A transient failure must not delete or poison the stored token.assert store.load("gmail") is not None# ...and a transient (server-side) error must NOT falsely flag reauth.assert store.load("gmail").needs_reauth is False@@ -284,6 +517,94 @@ async def test_scheduler_run_once_delegates() -> None:assert outcomes == {"notion": REFRESHED}+async def test_scheduler_stop_drains_rotating_refresh_before_return() -> None:+ store = _store()+ store.save("gmail", _tokens(60))+ handler = _InFlightHandler(+ "gmail", new_tokens=Tokens(access="new-access", refresh="new-refresh")+ )+ scheduler = RefreshScheduler(+ plugin_ids_fn=lambda: ["gmail"],+ store=store,+ build_handler=lambda _plugin_id: handler,+ interval_seconds=3600,+ shutdown_drain_timeout_seconds=1.0,+ )+ scheduler.start()+ await handler.entered.wait()++ stopping = asyncio.create_task(scheduler.stop())+ await asyncio.sleep(0)+ assert stopping.done() is False++ handler.release.set()+ await asyncio.wait_for(stopping, timeout=1.0)++ saved = store.load("gmail")+ assert saved.access == "new-access"+ assert saved.refresh == "new-refresh"+ assert scheduler._task is None+++async def test_scheduler_stop_cancels_cycle_only_after_drain_timeout(caplog) -> None: # noqa: ANN001+ store = _store()+ original = _tokens(60)+ store.save("gmail", original)+ cancelled = asyncio.Event()++ class _CancellationAwareHandler(_InFlightHandler):+ async def refresh(self, current: Tokens) -> Tokens:+ try:+ return await super().refresh(current)+ except asyncio.CancelledError:+ cancelled.set()+ raise++ handler = _CancellationAwareHandler(+ "gmail", new_tokens=Tokens(access="new-access", refresh="new-refresh")+ )+ scheduler = RefreshScheduler(+ plugin_ids_fn=lambda: ["gmail"],+ store=store,+ build_handler=lambda _plugin_id: handler,+ interval_seconds=3600,+ shutdown_drain_timeout_seconds=0.01,+ )+ caplog.set_level(logging.WARNING)+ scheduler.start()+ await handler.entered.wait()++ await asyncio.wait_for(scheduler.stop(), timeout=1.0)++ assert cancelled.is_set()+ assert store.load("gmail") == original+ assert scheduler._task is None+ assert "cancelling as a last resort" in caplog.text+++async def test_scheduler_start_is_idempotent_and_restart_safe() -> None:+ scheduler = RefreshScheduler(+ plugin_ids_fn=list,+ store=_store(),+ build_handler=lambda _plugin_id: None,+ interval_seconds=3600,+ )++ scheduler.start()+ first = scheduler._task+ scheduler.start()+ assert scheduler._task is first+ await scheduler.stop()++ scheduler.start()+ second = scheduler._task+ assert second is not None and second is not first+ await scheduler.stop()++def test_log_cycle_names_dead_plugins_at_warning(caplog) -> None: # noqa: ANN001# A revoked connection must be named at WARNING so it doesn't rot unseen# behind an anonymous "revoked=1" count (live: linear sat dead 22 days@@ -300,9 +621,7 @@ def test_log_cycle_lists_every_dead_plugin(caplog) -> None: # noqa: ANN001caplog.set_level(logging.WARNING)RefreshScheduler._log_cycle({"gmail": REVOKED, "linear": REVOKED, "slack": SKIPPED})- msg = " ".join(- r.getMessage() for r in caplog.records if r.levelno == logging.WARNING- )+ msg = " ".join(r.getMessage() for r in caplog.records if r.levelno == logging.WARNING)assert "gmail" in msg and "linear" in msg@@ -390,9 +709,7 @@ async def test_one_plugins_save_failure_does_not_block_the_next() -> None:"notion": _FakeHandler("notion", new_tokens=Tokens(access="a2", refresh="r2")),}- outcomes = await refresh_due_tokens(- ["gmail", "notion"], store, lambda pid: handlers[pid]- )+ outcomes = await refresh_due_tokens(["gmail", "notion"], store, lambda pid: handlers[pid])assert outcomes == {"gmail": FAILED, "notion": REFRESHED}assert inner.load("notion").access == "a2"diff --git a/tests/unit/marketplace/test_token_store.py b/tests/unit/marketplace/test_token_store.pyindex b07edcb2a6..317df9a86c 100644--- a/tests/unit/marketplace/test_token_store.py+++ b/tests/unit/marketplace/test_token_store.py@@ -36,6 +36,37 @@ class _SizeLimitedFakeBackend:self.store.pop(key, None)+class _SilentDeleteBackend:+ """Backend that reports no error but retains every deleted credential."""++ def __init__(self) -> None:+ self.store: dict[str, str] = {}+ self.overflow_get_calls = 0++ def get(self, key: str) -> str | None:+ if key.rpartition("__")[2].isdigit():+ self.overflow_get_calls += 1+ return "retained-chunk"+ return self.store.get(key)++ def set(self, key: str, value: str) -> None:+ self.store[key] = value++ def delete(self, key: str) -> None:+ return+++class _PartialOverflowDeleteBackend(_SizeLimitedFakeBackend):+ """Silently retains chunk one until the test allows its deletion."""++ allow_chunk_one_delete = False++ def delete(self, key: str) -> None:+ if key.endswith("__1") and not self.allow_chunk_one_delete:+ return+ super().delete(key)++def test_chunked_backend_round_trips_value_larger_than_primitive_limit():# A long Google OAuth token blob exceeds the Credential Manager's hard# per-entry limit. The chunking backend must split it across several@@ -82,6 +113,16 @@ def test_chunked_backend_resave_smaller_clears_stale_chunks():assert list(primitive.store) == ["plugin_gmail_tokens"]+def test_chunked_backend_cleanup_stops_after_silent_delete_failure():+ primitive = _SilentDeleteBackend()+ backend = ChunkedBackend(primitive, chunk_size=20)++ backend.set("plugin_gmail_tokens", "small")++ assert backend.get("plugin_gmail_tokens") == "small"+ assert primitive.overflow_get_calls == 2++class _FailNthSetBackend:"""Mimics a keyring backend whose ``set`` raises on a chosen call number(1-indexed across the object's whole lifetime) — used to simulate a@@ -182,3 +223,123 @@ def test_store_persists_needs_reauth():store.save("p", Tokens(access="a", needs_reauth=True))loaded = store.load("p")assert loaded is not None and loaded.needs_reauth is True+++def test_store_delete_raises_when_backend_silently_retains_token():+ backend = _SilentDeleteBackend()+ store = TokenStore(backend)+ store.save("gmail", Tokens(access="access"))++ with pytest.raises(RuntimeError, match="token deletion failed for plugin 'gmail'"):+ store.delete("gmail")++ assert store.load("gmail") is not None+++def test_store_delete_keeps_manifest_until_every_indexed_chunk_is_removed():+ backend = _PartialOverflowDeleteBackend(limit=1000)+ store = TokenStore(ChunkedBackend(backend, chunk_size=20))+ store.save("gmail", Tokens(access="access" * 20))+ primary_key = "plugin_gmail_tokens"+ manifest = backend.store[primary_key]++ with pytest.raises(+ RuntimeError,+ match="token deletion could not be verified for plugin 'gmail'",+ ):+ store.delete("gmail")++ assert backend.store[primary_key] == manifest+ assert f"{primary_key}__0" not in backend.store+ assert backend.store[f"{primary_key}__1"]++ # The retry must use the retained manifest, skip the already-missing zero+ # index, and still detect chunk one instead of falsely reporting success.+ with pytest.raises(RuntimeError):+ store.delete("gmail")+ assert backend.store[primary_key] == manifest+ assert backend.store[f"{primary_key}__1"]++ backend.allow_chunk_one_delete = True+ store.delete("gmail")++ assert backend.store == {}+++def test_shrink_persists_cleanup_extent_across_restart_until_delete_succeeds():+ backend = _PartialOverflowDeleteBackend(limit=1000)+ key = "plugin_gmail_tokens"+ chunked = ChunkedBackend(backend, chunk_size=20)+ chunked.set(key, "secret" * 20)++ # Shrinking replaces the active chunk header with a plain value. Chunk zero+ # is removed, chunk one silently remains, and later chunks are still tried.+ chunked.set(key, "small")++ assert chunked.get(key) == "small"+ assert f"{key}__0" not in backend.store+ assert backend.store[f"{key}__1"]+ extent = backend.store[f"{key}__extent"]+ assert int(extent) == 6++ # Rebuild both wrappers to model an application restart. Explicit deletion+ # must use the persisted extent rather than stop at the missing zero index.+ restarted_backend = ChunkedBackend(backend, chunk_size=20)+ assert restarted_backend.get(key) == "small"+ restarted = TokenStore(restarted_backend)+ with pytest.raises(RuntimeError):+ restarted.delete("gmail")++ assert backend.store[key] == "small"+ assert backend.store[f"{key}__extent"] == extent+ assert backend.store[f"{key}__1"]++ backend.allow_chunk_one_delete = True+ restarted.delete("gmail")++ assert backend.store == {}+++def test_legacy_sparse_delete_finds_later_chunks_with_no_primary():+ backend = _SizeLimitedFakeBackend(limit=1000)+ key = "plugin_gmail_tokens"+ backend.store[f"{key}__1"] = "legacy-fragment-one"+ backend.store[f"{key}__4"] = "legacy-fragment-four"+ store = TokenStore(ChunkedBackend(backend))++ store.delete("gmail")++ assert backend.store == {}+++def test_legacy_sparse_delete_finds_later_chunks_behind_plain_primary():+ backend = _SizeLimitedFakeBackend(limit=1000)+ key = "plugin_gmail_tokens"+ backend.store[key] = Tokens(access="small").to_json()+ backend.store[f"{key}__2"] = "legacy-fragment-two"+ store = TokenStore(ChunkedBackend(backend))++ store.delete("gmail")++ assert backend.store == {}+++def test_legacy_sparse_delete_retains_primary_and_extent_after_noop():+ backend = _PartialOverflowDeleteBackend(limit=1000)+ key = "plugin_gmail_tokens"+ primary = Tokens(access="small").to_json()+ backend.store[key] = primary+ backend.store[f"{key}__1"] = "legacy-fragment-one"+ store = TokenStore(ChunkedBackend(backend))++ with pytest.raises(RuntimeError):+ store.delete("gmail")++ assert backend.store[key] == primary+ assert backend.store[f"{key}__1"] == "legacy-fragment-one"+ assert backend.store[f"{key}__extent"] == "2"++ backend.allow_chunk_one_delete = True+ store.delete("gmail")++ assert backend.store == {}diff --git a/tests/unit/plugins/tool/test_gmail_rest.py b/tests/unit/plugins/tool/test_gmail_rest.pyindex e42b16a1b0..c5c85220ee 100644--- a/tests/unit/plugins/tool/test_gmail_rest.py+++ b/tests/unit/plugins/tool/test_gmail_rest.py@@ -82,6 +82,35 @@ async def test_list_messages_refreshes_on_401_then_retries():assert calls["http"] == 2 # retried exactly once after a successful refresh+async def test_default_refresh_receives_failed_access_token(monkeypatch) -> None: # noqa: ANN001+ seen: list[str | None] = []+ calls = 0++ def handler(req: httpx.Request) -> httpx.Response:+ nonlocal calls+ calls += 1+ if calls == 1:+ return httpx.Response(401, json={"error": {"code": 401}})+ return httpx.Response(200, json={"messages": []})++ async def refresher(observed_access_token: str | None = None) -> bool:+ seen.append(observed_access_token)+ return True++ monkeypatch.setattr(+ "jarvis.plugins.tool.gmail_rest._default_refresher", refresher+ )+ tool = GmailRestTool(+ access_token_provider=lambda: "failed-access",+ transport=httpx.MockTransport(handler),+ )++ await tool.list_messages()++ assert seen == ["failed-access"]++@pytest.mark.asyncioasync def test_returns_reconnect_error_when_refresh_fails():def handler(req: httpx.Request) -> httpx.Response:diff --git a/tests/unit/plugins/tool/test_google_calendar_rest.py b/tests/unit/plugins/tool/test_google_calendar_rest.pyindex 6559a0dca1..a738927b6a 100644--- a/tests/unit/plugins/tool/test_google_calendar_rest.py+++ b/tests/unit/plugins/tool/test_google_calendar_rest.py@@ -137,6 +137,35 @@ async def test_refreshes_on_401_then_retries():assert calls["n"] == 2 # retried exactly once after a successful refresh+async def test_default_refresh_receives_failed_access_token(monkeypatch) -> None: # noqa: ANN001+ seen: list[str | None] = []+ calls = 0++ async def runner(action, args, token): # noqa: ANN001+ nonlocal calls+ calls += 1+ if calls == 1:+ return {"ok": False, "status": 401, "error": "Calendar API 401"}+ return _ok({"events": []})++ async def refresher(observed_access_token: str | None = None) -> bool:+ seen.append(observed_access_token)+ return True++ monkeypatch.setattr(+ "jarvis.plugins.tool.google_calendar_rest._default_refresher", refresher+ )+ tool = GoogleCalendarRestTool(+ access_token_provider=lambda: "failed-access",+ node_runner=runner,+ )++ await tool.list_events()++ assert seen == ["failed-access"]++@pytest.mark.asyncioasync def test_returns_reconnect_error_when_refresh_fails():async def runner(action, args, token):