Skip to content

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

feat(marketplace): explain and self-heal a plugin that needs reconnecting

rubenluetke10-beepfa2cc9394132
diff --git a/jarvis/marketplace/plugin_registry.py b/jarvis/marketplace/plugin_registry.py
index 33150daf1e..ed04d52916 100644
--- a/jarvis/marketplace/plugin_registry.py
+++ b/jarvis/marketplace/plugin_registry.py
@@ -10,10 +10,10 @@ Never raises out of bootstrap()/refresh_plugin(): one broken plugin degrades
to "no tools for that plugin" instead of blocking the whole brain (cloud-first
graceful-degradation doctrine).
"""
+
from __future__ import annotations
import asyncio
-import dataclasses
import logging
from collections.abc import Callable
from typing import Any
@@ -66,22 +66,38 @@ _CONNECT_TIMEOUT_S_DEFAULT = 15.0
_CLIENT_STOP_TIMEOUT_S = 5.0
-def _connect_needs_reauth(message: str) -> bool:
- """True iff a connect failure indicates a dead credential, not a flaky host.
+def _connect_reauth_reason(message: str) -> str | None:
+ """The reason code for a connect failure, or ``None`` for a flaky host.
Reuses the refresh scheduler's canonical OAuth marker list and adds the
connect-time shapes (an HTTP 401/unauthorized on the MCP endpoint itself).
Conservative on purpose: 'Connection closed', timeouts, and 5xx stay
- retryable so one flaky boot never flags a healthy plugin."""
+ retryable so one flaky boot never flags a healthy plugin.
+
+ Returns the CODE, not a bool, so a connection flagged here carries the same
+ explanation as one flagged by the scheduler — the plugins view has only one
+ story to tell either way."""
try:
- from jarvis.marketplace.refresh_scheduler import _refresh_needs_reauth
+ from jarvis.marketplace.refresh_scheduler import reauth_reason_for
- if _refresh_needs_reauth(message):
- return True
+ reason = reauth_reason_for(message)
+ if reason is not None:
+ return reason
except Exception: # noqa: BLE001 — classifier is best-effort
log.debug("connect reauth classifier unavailable", exc_info=True)
m = message.lower()
- return "401" in m or "unauthorized" in m or "invalid_token" in m
+ if "401" in m or "unauthorized" in m or "invalid_token" in m:
+ # The endpoint refused the credential itself. Indistinguishable at this
+ # layer from an expired grant, and the user's move is the same either way.
+ from jarvis.marketplace.token_store import REAUTH_PROVIDER_REJECTED
+
+ return REAUTH_PROVIDER_REJECTED
+ return None
+
+
+def _connect_needs_reauth(message: str) -> bool:
+ """Boolean view of :func:`_connect_reauth_reason` for the control-flow gates."""
+ return _connect_reauth_reason(message) is not None
def _default_refresh_handler(plugin_id: str) -> Any | None:
@@ -271,9 +287,7 @@ class PluginToolRegistry:
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
- )
+ log.warning("plugin-registry: %s connect failed: %s", plugin.id, message)
self._last_errors[plugin.id] = message
return
@@ -337,9 +351,7 @@ class PluginToolRegistry:
_ctx = try_get_skill_context()
if _ctx is not None:
- _register_plugin_capability(
- _get_cap_registry(), plugin.id, _ctx.registry.list()
- )
+ _register_plugin_capability(_get_cap_registry(), plugin.id, _ctx.registry.list())
except Exception as exc: # noqa: BLE001 — capability is best-effort
log.debug("paired cap register failed for %s: %s", plugin.id, exc)
@@ -362,27 +374,32 @@ class PluginToolRegistry:
doomed connect (no repeated timeout cost) and the plugins view shows
the Reconnect affordance instead of a silent per-boot failure."""
try:
- if not _connect_needs_reauth(message):
+ reason = _connect_reauth_reason(message)
+ if reason is None:
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-registry: %s re-auth mark skipped; token changed during connect retry",
plugin_id,
)
return
- self._store.save(plugin_id, dataclasses.replace(tokens, needs_reauth=True))
+ from jarvis.marketplace.refresh_scheduler import flag_for_reauth
+
+ self._store.save(plugin_id, flag_for_reauth(tokens, reason))
log.warning(
- "plugin-registry: %s connect needs re-auth — marked: %s",
- plugin_id, message,
+ "plugin-registry: %s connect needs re-auth (%s) — marked: %s",
+ plugin_id,
+ reason,
+ message,
)
except Exception as exc: # noqa: BLE001 — marking is best-effort
log.debug(
"plugin-registry: needs_reauth save failed for %s: %s",
- plugin_id, exc,
+ plugin_id,
+ exc,
)
async def _disconnect_plugin(self, plugin_id: str) -> None:
diff --git a/jarvis/marketplace/refresh_scheduler.py b/jarvis/marketplace/refresh_scheduler.py
index 6587f40f87..c97a2031a6 100644
--- a/jarvis/marketplace/refresh_scheduler.py
+++ b/jarvis/marketplace/refresh_scheduler.py
@@ -18,7 +18,14 @@ from contextlib import suppress
from datetime import UTC, datetime
from jarvis.marketplace.auth.base import AuthHandler
-from jarvis.marketplace.token_store import Tokens, TokenStore
+from jarvis.marketplace.token_store import (
+ REAUTH_CLIENT_MISSING,
+ REAUTH_CLIENT_REJECTED,
+ REAUTH_PROVIDER_REJECTED,
+ REAUTH_ROTATION_LOST,
+ Tokens,
+ TokenStore,
+)
log = logging.getLogger(__name__)
@@ -54,22 +61,65 @@ def _refresh_lock(plugin_id: str) -> asyncio.Lock:
return loop_locks.setdefault(plugin_id, asyncio.Lock())
-_REAUTH_ERROR_MARKERS: tuple[str, ...] = (
- "revoked",
- "invalid_grant",
- "invalid_client",
- "unauthorized_client",
- "client was not found",
- "token has been expired",
- "reconnect required",
- "no stored client_id",
+# Ordered most-specific first: a DCR handler raises "no stored client_id —
+# reconnect required", which matches two markers, and the FIRST match wins. The
+# marker itself is our own literal, so classifying this way keeps every persisted
+# reason free of provider text (which can quote a token back at us).
+_REAUTH_ERROR_MARKERS: tuple[tuple[str, str], ...] = (
+ ("no stored client_id", REAUTH_CLIENT_MISSING),
+ ("client was not found", REAUTH_CLIENT_REJECTED),
+ ("unauthorized_client", REAUTH_CLIENT_REJECTED),
+ ("invalid_client", REAUTH_CLIENT_REJECTED),
+ ("invalid_grant", REAUTH_PROVIDER_REJECTED),
+ ("token has been expired", REAUTH_PROVIDER_REJECTED),
+ ("reconnect required", REAUTH_PROVIDER_REJECTED),
+ ("revoked", REAUTH_PROVIDER_REJECTED),
)
-def _refresh_needs_reauth(message: str) -> bool:
- """Return whether a refresh failure requires user authentication."""
+def reauth_reason_for(message: str) -> str | None:
+ """Classify a refresh failure, or return ``None`` when it is transient.
+
+ ``None`` means "retry on the next cycle"; any code means the grant cannot be
+ healed without the user. Returning the CODE rather than a bool is what lets
+ the UI say which of the two happened days later.
+ """
lowered = message.lower()
- return any(marker in lowered for marker in _REAUTH_ERROR_MARKERS)
+ for marker, reason in _REAUTH_ERROR_MARKERS:
+ if marker in lowered:
+ return reason
+ return None
+
+
+def _self_heal_due(tokens: Tokens, retry_seconds: int | None) -> bool:
+ """Whether a reauth-flagged connection may be probed once more.
+
+ The flag can be wrong. A provider outage answering ``invalid_client``, or a
+ momentary DNS failure surfacing as a hard rejection, strands a grant whose
+ refresh token is still perfectly good — and nothing ever retried it, so the
+ connection stayed dead until the user noticed and reconnected by hand. The
+ flag therefore decays: every ``retry_seconds`` the connection gets ONE more
+ attempt, and a success clears it (``needs_reauth=False`` on the saved token).
+
+ ``REAUTH_ROTATION_LOST`` is the one exception and never retries. There the
+ provider has already retired the token we hold, so presenting it again is
+ exactly the replay that some providers treat as theft and answer by revoking
+ every token on the account. A stranded connection costs one sign-in; that
+ mistake costs the whole account.
+
+ A probe is cheap — one request per dead plugin per day — and the failure it
+ repairs is otherwise permanent.
+ """
+ if retry_seconds is None or not tokens.refresh:
+ return False
+ if tokens.reauth_reason == REAUTH_ROTATION_LOST:
+ return False
+ last_try = tokens.reauth_retry_at or tokens.reauth_at
+ if last_try is None:
+ # Flagged before this field existed: probe on the next cycle, then the
+ # written `reauth_retry_at` puts it on the normal cadence.
+ return True
+ return (datetime.now(UTC) - last_try).total_seconds() >= retry_seconds
def _keep_alive_due(tokens: object, keep_alive_seconds: int | None) -> bool:
@@ -88,6 +138,20 @@ def _keep_alive_due(tokens: object, keep_alive_seconds: int | None) -> bool:
return (datetime.now(UTC) - last).total_seconds() >= keep_alive_seconds
+def flag_for_reauth(tokens: Tokens, reason: str) -> Tokens:
+ """Flag a grant for reconnect, recording WHY and WHEN it first failed.
+
+ ``reauth_at`` is preserved across repeated failures so it keeps meaning "when
+ this connection died" rather than "when we last confirmed it is still dead".
+ """
+ return dataclasses.replace(
+ tokens,
+ needs_reauth=True,
+ reauth_reason=reason,
+ reauth_at=tokens.reauth_at or datetime.now(UTC),
+ )
+
+
def _reload_before_refresh_commit(
plugin_id: str,
store: TokenStore,
@@ -190,7 +254,7 @@ def _handle_lost_rotation(
exc,
)
try:
- store.save(plugin_id, dataclasses.replace(current, needs_reauth=True))
+ store.save(plugin_id, flag_for_reauth(current, REAUTH_ROTATION_LOST))
except Exception as mark_exc: # noqa: BLE001 - the store is evidently broken
# Nothing durable can be written at all. Say so loudly rather than
# leave a retry loop that would keep replaying the retired token.
@@ -212,12 +276,18 @@ async def refresh_plugin_token(
observed_access_token: str | None = None,
threshold_seconds: int = 600,
keep_alive_seconds: int | None = None,
+ reauth_retry_seconds: int | None = None,
) -> 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.
+
+ ``reauth_retry_seconds`` opts into self-healing: a connection already
+ flagged for reconnect is probed once per that interval instead of being
+ skipped forever. Left ``None`` (the default) a flagged connection is never
+ touched, so a direct caller keeps the old behaviour verbatim.
"""
async with _refresh_lock(plugin_id):
try:
@@ -226,14 +296,39 @@ async def refresh_plugin_token(
log.warning("plugin %s token load failed: %s", plugin_id, exc)
return RefreshAttempt(FAILED)
- if tokens is None or tokens.needs_reauth:
+ if tokens is None:
return RefreshAttempt(SKIPPED)
+
+ self_heal = False
+ if tokens.needs_reauth:
+ if not _self_heal_due(tokens, reauth_retry_seconds):
+ return RefreshAttempt(SKIPPED)
+ self_heal = True
+ # Stamp the attempt BEFORE calling the provider. If that call hangs,
+ # or the process dies mid-flight, this stamp is the only thing
+ # stopping the next cycle five minutes later from probing again --
+ # a dead plugin would otherwise hammer the provider forever.
+ stamped = dataclasses.replace(tokens, reauth_retry_at=datetime.now(UTC))
+ try:
+ store.save(plugin_id, stamped)
+ except Exception as exc: # noqa: BLE001 - isolate one plugin's storage
+ log.warning(
+ "plugin %s self-heal stamp failed, skipping this cycle: %s",
+ plugin_id,
+ exc,
+ )
+ return RefreshAttempt(FAILED)
+ tokens = stamped
+ log.info("plugin %s: retrying a connection flagged for reconnect", plugin_id)
+
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:
+ # A self-heal probe is due by definition -- its access token expired long
+ # ago, and the whole point is to test the refresh token behind it.
+ if not force and not self_heal:
due = tokens.is_near_expiry(threshold_seconds) or _keep_alive_due(
tokens, keep_alive_seconds
)
@@ -255,7 +350,8 @@ async def refresh_plugin_token(
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)):
+ reason = reauth_reason_for(str(exc))
+ if reason is None:
_current, superseded = _reload_before_refresh_commit(
plugin_id, store, original_state
)
@@ -274,7 +370,7 @@ async def refresh_plugin_token(
assert current is not None
try:
- store.save(plugin_id, dataclasses.replace(current, needs_reauth=True))
+ store.save(plugin_id, flag_for_reauth(current, reason))
except Exception as save_exc: # noqa: BLE001 - isolate storage failure
log.warning(
"plugin %s needs_reauth save failed, will retry: %s",
@@ -283,8 +379,9 @@ async def refresh_plugin_token(
)
return RefreshAttempt(FAILED)
log.info(
- "plugin %s refresh needs reauth; marked needs_reauth: %s",
+ "plugin %s refresh needs reauth (%s): %s",
plugin_id,
+ reason,
exc,
)
return RefreshAttempt(REVOKED)
@@ -303,8 +400,21 @@ async def refresh_plugin_token(
refreshed,
refresh=refreshed.refresh or current.refresh,
extra=merged_extra,
+ # A working refresh clears the whole reconnect story, not just the
+ # flag: a stale reason left behind would keep explaining a failure
+ # that no longer exists. Set explicitly rather than relying on the
+ # handler having returned a pristine Tokens.
needs_reauth=False,
+ reauth_reason=None,
+ reauth_at=None,
+ reauth_retry_at=None,
)
+ if current.needs_reauth:
+ log.info(
+ "plugin %s: self-heal succeeded, connection is live again (was flagged %s)",
+ plugin_id,
+ current.reauth_reason or "for an unrecorded reason",
+ )
rotated = bool(refreshed.refresh) and refreshed.refresh != current.refresh
try:
await _save_with_retries(store, plugin_id, saved, rotated=rotated)
@@ -334,6 +444,7 @@ async def refresh_due_tokens(
*,
threshold_seconds: int = 600,
keep_alive_seconds: int | None = None,
+ reauth_retry_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."""
@@ -345,6 +456,7 @@ async def refresh_due_tokens(
build_handler,
threshold_seconds=threshold_seconds,
keep_alive_seconds=keep_alive_seconds,
+ reauth_retry_seconds=reauth_retry_seconds,
)
outcomes[plugin_id] = attempt.outcome
if attempt.outcome == REFRESHED and on_refreshed is not None:
@@ -371,6 +483,10 @@ class RefreshScheduler:
interval_seconds: float = 300.0,
threshold_seconds: int = 600,
keep_alive_seconds: int | None = 43_200,
+ # Once a day. Frequent enough that a connection stranded by a provider
+ # outage repairs itself well before the user next looks, rare enough
+ # that a genuinely revoked grant costs one request a day.
+ reauth_retry_seconds: int | None = 86_400,
on_refreshed: Callable[[str], None] | None = None,
shutdown_drain_timeout_seconds: float = 30.0,
) -> None:
@@ -380,6 +496,7 @@ class RefreshScheduler:
self._interval = interval_seconds
self._threshold = threshold_seconds
self._keep_alive_seconds = keep_alive_seconds
+ self._reauth_retry_seconds = reauth_retry_seconds
self._on_refreshed = on_refreshed
self._shutdown_drain_timeout = shutdown_drain_timeout_seconds
self._task: asyncio.Task[None] | None = None
@@ -393,6 +510,7 @@ class RefreshScheduler:
self._build_handler,
threshold_seconds=self._threshold,
keep_alive_seconds=self._keep_alive_seconds,
+ reauth_retry_seconds=self._reauth_retry_seconds,
on_refreshed=self._on_refreshed,
)
diff --git a/jarvis/marketplace/token_store.py b/jarvis/marketplace/token_store.py
index 68d9c85105..321e5b32be 100644
--- a/jarvis/marketplace/token_store.py
+++ b/jarvis/marketplace/token_store.py
@@ -26,6 +26,30 @@ from dataclasses import dataclass, field
from datetime import UTC, datetime, timedelta
from typing import Any, Protocol
+# Stable reason codes for a connection the refresh path could not heal. These
+# four strings are the ONLY thing ever persisted about a failure: a provider's
+# raw error body can echo a token back at us, so it must never reach storage or
+# the UI. Each code is matched from our own marker list, never from provider text.
+REAUTH_PROVIDER_REJECTED = "provider_rejected"
+"""The grant itself is gone — expired, revoked, or withdrawn by the provider."""
+REAUTH_CLIENT_REJECTED = "client_rejected"
+"""The OAuth client the grant belongs to was refused or no longer exists."""
+REAUTH_CLIENT_MISSING = "client_missing"
+"""Stored before we persisted the issuing client_id; unrefreshable by design."""
+REAUTH_ROTATION_LOST = "rotation_lost"
+"""A rotated refresh token could not be stored. NEVER retried — see below."""
+
+
+def _parse_utc(raw: object) -> datetime | None:
+ """Parse an ISO timestamp from storage, tolerating a naive one as UTC."""
+ if not isinstance(raw, str) or not raw:
+ return None
+ try:
+ parsed = datetime.fromisoformat(raw)
+ except ValueError:
+ return None
+ return parsed if parsed.tzinfo is not None else parsed.replace(tzinfo=UTC)
+
@dataclass(frozen=True, slots=True)
class Tokens:
@@ -39,6 +63,16 @@ class Tokens:
# un-healable). The entry is KEPT (never deleted) so the plugin stays
# visible with a "Reconnect" affordance instead of silently disappearing.
needs_reauth: bool = False
+ # WHY it needs reauth, and since when. Without these the flag is a bare
+ # yes/no: "Google withdrew the grant" and "the network blipped once" look
+ # identical to the user days later, once the log line has rotated away.
+ # One of the REAUTH_* codes above, or None on a healthy token.
+ reauth_reason: str | None = None
+ reauth_at: datetime | None = None
+ # Last automatic self-heal probe. Separate from `reauth_at` so retrying
+ # never overwrites when the connection actually died — that timestamp is
+ # the one the user is shown.
+ reauth_retry_at: datetime | None = None
def is_near_expiry(self, threshold_seconds: int = 600) -> bool:
if self.expires_at is None:
@@ -52,6 +86,9 @@ class Tokens:
"expires_at": self.expires_at.isoformat() if self.expires_at else None,
"extra": dict(self.extra),
"needs_reauth": self.needs_reauth,
+ "reauth_reason": self.reauth_reason,
+ "reauth_at": self.reauth_at.isoformat() if self.reauth_at else None,
+ "reauth_retry_at": (self.reauth_retry_at.isoformat() if self.reauth_retry_at else None),
}
return json.dumps(payload, separators=(",", ":"))
@@ -64,12 +101,19 @@ class Tokens:
expires_at = datetime.fromisoformat(expires_raw)
if expires_at.tzinfo is None:
expires_at = expires_at.replace(tzinfo=UTC)
+ reason = data.get("reauth_reason")
return cls(
access=data["access"],
refresh=data.get("refresh"),
expires_at=expires_at,
extra=dict(data.get("extra") or {}),
needs_reauth=bool(data.get("needs_reauth", False)),
+ # A token written before these fields existed simply has no reason.
+ # It stays flagged and still self-heals — an unknown cause is not a
+ # reason to strand it, only to say "unknown" honestly in the UI.
+ reauth_reason=reason if isinstance(reason, str) and reason else None,
+ reauth_at=_parse_utc(data.get("reauth_at")),
+ reauth_retry_at=_parse_utc(data.get("reauth_retry_at")),
)
diff --git a/jarvis/ui/web/frontend/src/components/ProviderSwitcher.tsx b/jarvis/ui/web/frontend/src/components/ProviderSwitcher.tsx
index a93fe18266..ddcf48dd54 100644
--- a/jarvis/ui/web/frontend/src/components/ProviderSwitcher.tsx
+++ b/jarvis/ui/web/frontend/src/components/ProviderSwitcher.tsx
@@ -1,6 +1,5 @@
import { useState } from "react";
import { Button } from "@/components/ui/button";
-import { BrandedSelect } from "@/components/ui/select";
import { switchBrainProvider, useProviders } from "@/hooks/useProviders";
import { useT } from "@/i18n";
import { useEventStore } from "@/store/events";
@@ -50,20 +49,18 @@ export function ProviderSwitcher() {
<label className="text-xs uppercase tracking-wide text-muted-foreground">
Active Brain
</label>
- <BrandedSelect
+ <select
value={choice}
- onValueChange={setTarget}
- ariaLabel="Active Brain"
- options={brainProviders.map((provider) => ({
- value: provider.id,
- label: `${provider.label}${
- provider.configured
- ? ""
- : ` — ${t("provider_switcher.no_credential")}`
- }`,
- disabled: !provider.configured,
- }))}
- />
+ onChange={(e) => setTarget(e.target.value)}
+ className="w-full rounded-md border border-input bg-background px-3 py-2 text-sm"
+ >
+ {brainProviders.map((p) => (
+ <option key={p.id} value={p.id} disabled={!p.configured}>
+ {p.label}
+ {!p.configured && ` — ${t("provider_switcher.no_credential")}`}
+ </option>
+ ))}
+ </select>
<Button onClick={handleApply} disabled={pending} className="w-full">
{pending ? "Switching…" : "Apply"}
</Button>
diff --git a/jarvis/ui/web/frontend/src/components/agentic/AgentAllocation.test.tsx b/jarvis/ui/web/frontend/src/components/agentic/AgentAllocation.test.tsx
index 9e9803ab5f..7ae32b8a10 100644
--- a/jarvis/ui/web/frontend/src/components/agentic/AgentAllocation.test.tsx
+++ b/jarvis/ui/web/frontend/src/components/agentic/AgentAllocation.test.tsx
@@ -230,14 +230,14 @@ describe("AgentAllocation", () => {
expect(screen.getByText("2 / 5")).toBeTruthy();
});
- it("applies one selected subscription to every terminal of an agent", async () => {
+ it("applies one selected subscription to every terminal of an agent", () => {
render(<Harness count={3} accounts={ACCOUNTS} />);
fireEvent.click(screen.getAllByRole("button", { name: "All" })[0]);
- fireEvent.click(
+ fireEvent.change(
screen.getByRole("combobox", { name: "Subscription for Claude Code" }),
+ { target: { value: "claude:work" } },
);
- fireEvent.click(await screen.findByText("Work seat"));
expect(plan().map((pane) => pane.account)).toEqual([
"claude:work",
diff --git a/jarvis/ui/web/frontend/src/components/agentic/AgentAllocation.tsx b/jarvis/ui/web/frontend/src/components/agentic/AgentAllocation.tsx
index 52f50652ca..982fc38e2b 100644
--- a/jarvis/ui/web/frontend/src/components/agentic/AgentAllocation.tsx
+++ b/jarvis/ui/web/frontend/src/components/agentic/AgentAllocation.tsx
@@ -8,8 +8,7 @@ import { cn } from "@/lib/utils";
import type { AgentAccount } from "@/lib/agentAccountsApi";
import type { AgentStatus } from "@/lib/agenticIdeApi";
import { AgentMark } from "./AgentMark";
-import { Button, SectionLabel } from "./controls";
-import { BrandedSelect } from "@/components/ui/select";
+import { Button, Select, SectionLabel } from "./controls";
export interface PlannedTerminal {
agent: string;
@@ -306,32 +305,31 @@ export function AgentAllocation({
{accounts.length >= 2 && count > 0 && (
<label className="mt-2 flex max-w-sm items-center gap-2 text-[11px] text-muted-foreground">
<span>{t("workspace_launcher.agents.account")}</span>
- <BrandedSelect
+ <Select
value={selectedAccount}
- ariaLabel={t(
+ aria-label={t(
"workspace_launcher.agents.account_for",
).replace("{0}", agent.display_name)}
- onValueChange={(value) =>
- setAccount(agent.name, value || undefined)
+ onChange={(event) =>
+ setAccount(
+ agent.name,
+ event.target.value || undefined,
+ )
}
className="h-7 min-w-0 flex-1 text-xs"
- options={[
- {
- value: "",
- label: t(
- "workspace_launcher.agents.active_account",
- ),
- },
- ...accounts.map((account) => ({
- value: account.id,
- label: `${account.label}${
- account.connected
- ? ""
- : ` (${t("workspace_launcher.agents.not_signed_in")})`
- }`,
- })),
- ]}
- />
+ >
+ <option value="">
+ {t("workspace_launcher.agents.active_account")}
+ </option>
+ {accounts.map((account) => (
+ <option key={account.id} value={account.id}>
+ {account.label}
+ {account.connected
+ ? ""
+ : ` (${t("workspace_launcher.agents.not_signed_in")})`}
+ </option>
+ ))}
+ </Select>
</label>
)}
</div>
diff --git a/jarvis/ui/web/frontend/src/components/agentic/controls.tsx b/jarvis/ui/web/frontend/src/components/agentic/controls.tsx
index b6cf386f9e..bc94a67074 100644
--- a/jarvis/ui/web/frontend/src/components/agentic/controls.tsx
+++ b/jarvis/ui/web/frontend/src/components/agentic/controls.tsx
@@ -136,6 +136,34 @@ export const Field = forwardRef<
);
});
+/**
+ * A native select at the same scale.
+ *
+ * Native rather than a custom menu because the two places it is used — which
+ * coding CLI runs in a pane, which subscription it opens on — are short lists
+ * where the OS control is better than anything worth reimplementing: it is
+ * keyboard-navigable, it scrolls, and on a phone it becomes the platform picker.
+ */
+export const Select = forwardRef<
+ HTMLSelectElement,
+ React.SelectHTMLAttributes<HTMLSelectElement>
+>(function Select({ className, children, ...rest }, ref) {
+ return (
+ <select
+ ref={ref}
+ className={cn(
+ "h-8 max-w-full rounded-control border border-border bg-background px-2 text-sm " +
+ "text-foreground outline-none transition-colors focus:border-primary/60 " +
+ "disabled:cursor-not-allowed disabled:opacity-40",
+ className,
+ )}
+ {...rest}
+ >
+ {children}
+ </select>
+ );
+});
+
/**
* A panel — the one container shape this section uses.
*
diff --git a/jarvis/ui/web/frontend/src/components/onboarding/steps/LanguageStep.test.tsx b/jarvis/ui/web/frontend/src/components/onboarding/steps/LanguageStep.test.tsx
index 3202a98efa..10660786aa 100644
--- a/jarvis/ui/web/frontend/src/components/onboarding/steps/LanguageStep.test.tsx
+++ b/jarvis/ui/web/frontend/src/components/onboarding/steps/LanguageStep.test.tsx
@@ -11,11 +11,10 @@ vi.mock("@/i18n", () => ({
import { LanguageStep } from "./LanguageStep";
afterEach(() => { cleanup(); setUiLanguage.mockClear(); });
-it("changes UI language and advances", async () => {
+it("changes UI language and advances", () => {
const goNext = vi.fn();
render(<LanguageStep onb={{} as never} goNext={goNext} goBack={vi.fn()} skip={vi.fn()} isFirst={false} isLast={false} />);
- fireEvent.click(screen.getByLabelText("onboarding.language.ui_label"));
- fireEvent.click(await screen.findByText("Deutsch"));
+ fireEvent.change(screen.getByLabelText("onboarding.language.ui_label"), { target: { value: "de" } });
expect(setUiLanguage).toHaveBeenCalledWith("de");
fireEvent.click(screen.getByRole("button", { name: "onboarding.nav.next" }));
expect(goNext).toHaveBeenCalled();
diff --git a/jarvis/ui/web/frontend/src/components/onboarding/steps/LanguageStep.tsx b/jarvis/ui/web/frontend/src/components/onboarding/steps/LanguageStep.tsx
index 4af70fa6a6..14f1deb7ff 100644
--- a/jarvis/ui/web/frontend/src/components/onboarding/steps/LanguageStep.tsx
+++ b/jarvis/ui/web/frontend/src/components/onboarding/steps/LanguageStep.tsx
@@ -1,5 +1,4 @@
import { Button } from "@/components/ui/button";
-import { BrandedSelect } from "@/components/ui/select";
import {
useT,
useUiLanguage,
@@ -20,32 +19,30 @@ export function LanguageStep({ goNext }: StepProps) {
<h2 className="font-display text-lg font-semibold">{t("onboarding.language.title")}</h2>
<label className="text-sm">
{t("onboarding.language.ui_label")}
- <BrandedSelect
- ariaLabel={t("onboarding.language.ui_label")}
+ <select
+ aria-label={t("onboarding.language.ui_label")}
value={ui}
- onValueChange={(value) => setUiLanguage(value as UiLanguage)}
- options={[
- { value: "en", label: "English" },
- { value: "de", label: "Deutsch" },
- { value: "es", label: "Español" },
- ]}
- className="mt-1"
- />
+ onChange={(e) => setUiLanguage(e.target.value as UiLanguage)}
+ className="mt-1 w-full rounded-md border border-input bg-background px-3 py-2 text-sm"
+ >
+ <option value="en">English</option>
+ <option value="de">Deutsch</option>
+ <option value="es">Español</option>
+ </select>
</label>
<label className="text-sm">
{t("onboarding.language.reply_label")}
- <BrandedSelect
- ariaLabel={t("onboarding.language.reply_label")}
+ <select
+ aria-label={t("onboarding.language.reply_label")}
value={reply}
- onValueChange={(value) => setReplyLanguage(value as ReplyLanguage)}
- options={[
- { value: "auto", label: "Auto" },
- { value: "en", label: "English" },
- { value: "de", label: "Deutsch" },
- { value: "es", label: "Español" },
- ]}
- className="mt-1"
- />
+ onChange={(e) => setReplyLanguage(e.target.value as ReplyLanguage)}
+ className="mt-1 w-full rounded-md border border-input bg-background px-3 py-2 text-sm"
+ >
+ <option value="auto">Auto</option>
+ <option value="en">English</option>
+ <option value="de">Deutsch</option>
+ <option value="es">Español</option>
+ </select>
</label>
<Button className="w-full" onClick={goNext}>{t("onboarding.nav.next")}</Button>
</div>
diff --git a/jarvis/ui/web/frontend/src/components/providers/ProviderTierSection.test.tsx b/jarvis/ui/web/frontend/src/components/providers/ProviderTierSection.test.tsx
index 1824732f85..9d16054cfa 100644
--- a/jarvis/ui/web/frontend/src/components/providers/ProviderTierSection.test.tsx
+++ b/jarvis/ui/web/frontend/src/components/providers/ProviderTierSection.test.tsx
@@ -20,9 +20,14 @@ import { act, cleanup, fireEvent, render, screen, waitFor } from "@testing-libra
import {
PROVIDER_STATE_CHIPS,
ProviderCard,
+ managedRuntimeBadge,
type ProviderStateChip,
} from "@/components/providers/ProviderTierSection";
-import type { ProviderDescriptor, ProviderTestResult } from "@/hooks/useProviders";
+import type {
+ ManagedServerRuntime,
+ ProviderDescriptor,
+ ProviderTestResult,
+} from "@/hooks/useProviders";
import { useI18nStore, type UiLanguage } from "@/i18n";
import enLocale from "@/i18n/locales/en.json";
@@ -1087,11 +1092,10 @@ describe("managed local realtime model setup", () => {
expect(screen.getByText("Browse the full Ollama catalog")).toBeTruthy();
expect(screen.getByText("Browse open-source speech models")).toBeTruthy();
expect(screen.getByText("Advanced connection settings")).toBeTruthy();
- fireEvent.click(screen.getByRole("combobox", { name: "Speak" }));
- const unavailable = await screen.findByRole("option", {
+ const unavailable = screen.getByRole("option", {
name: /ChatTTS.*not voice-tested yet/,
- });
- expect(unavailable.getAttribute("aria-disabled")).toBe("true");
+ }) as HTMLOptionElement;
+ expect(unavailable.disabled).toBe(true);
expect(calls.some((call) => call.url.endsWith("/model-catalog"))).toBe(true);
fireEvent.click(screen.getByText("Browse open-source speech models"));
@@ -1107,3 +1111,89 @@ describe("managed local realtime model setup", () => {
expect(screen.getByText("Integration pending")).toBeTruthy();
});
});
+
+describe("managed server badge", () => {
+ /** A pool snapshot with the fields the rule actually reads. */
+ function pool(inUse: number, available: number) {
+ return {
+ size: inUse + available,
+ in_use: inUse,
+ available,
+ active: inUse,
+ draining: 0,
+ stuck: 0,
+ };
+ }
+
+ function runtime(overrides: Partial<ManagedServerRuntime>): ManagedServerRuntime {
+ return {
+ reachable: true,
+ ready: true,
+ available: true,
+ pool: pool(0, 1),
+ port: 8765,
+ pid: 4242,
+ owned: true,
+ stale: false,
+ ...overrides,
+ };
+ }
+
+ it("calls a server with a free pipeline running", () => {
+ expect(managedRuntimeBadge(runtime({}), true)?.key).toBe(
+ "apikeys_view.managed_server_running",
+ );
+ });
+
+ it("calls a busy-but-healthy server running, not broken", () => {
+ const busy = runtime({ available: false, pool: pool(1, 0) });
+ expect(managedRuntimeBadge(busy, true)?.key).toBe(
+ "apikeys_view.managed_server_running",
+ );
+ });
+
+ it("stops claiming 'running' while the model pool is still cold", () => {
+ // The live defect: the port answered, so the card stayed green through a
+ // ~60 s model load while every call failed on the same server.
+ const loading = runtime({ ready: false, available: false, pool: null });
+ const badge = managedRuntimeBadge(loading, true);
+ expect(badge?.key).toBe("apikeys_view.managed_server_starting");
+ expect(badge?.tone).toBe("warn");
+ });
+
+ it("flags a wedged pool that serves nobody", () => {
+ const wedged = runtime({ available: false, pool: pool(0, 0) });
+ expect(managedRuntimeBadge(wedged, true)?.key).toBe(
+ "apikeys_view.managed_server_no_capacity",
+ );
+ });
+
+ it("keeps a foreign listener a port conflict, never ours", () => {
+ const foreign = runtime({ owned: false });
+ expect(managedRuntimeBadge(foreign, false)?.key).toBe(
+ "apikeys_view.managed_server_port_conflict",
+ );
+ });
+
+ it("trusts an older backend that reports no readiness fields", () => {
+ const legacy: ManagedServerRuntime = {
+ reachable: true,
+ port: 8765,
+ pid: 1,
+ owned: true,
+ stale: false,
+ };
+ expect(managedRuntimeBadge(legacy, true)?.key).toBe(
+ "apikeys_view.managed_server_running",
+ );
+ });
+
+ it("reads an unreachable owned process as starting, and none as stopped", () => {
+ expect(
+ managedRuntimeBadge(runtime({ reachable: false }), true)?.key,
+ ).toBe("apikeys_view.managed_server_starting");
+ expect(
+ managedRuntimeBadge(runtime({ reachable: false, owned: false }), false)?.key,
+ ).toBe("apikeys_view.managed_server_stopped");
+ });
+});
diff --git a/jarvis/ui/web/frontend/src/components/providers/ProviderTierSection.tsx b/jarvis/ui/web/frontend/src/components/providers/ProviderTierSection.tsx
index af2d2d6c81..76968dafb8 100644
--- a/jarvis/ui/web/frontend/src/components/providers/ProviderTierSection.tsx
+++ b/jarvis/ui/web/frontend/src/components/providers/ProviderTierSection.tsx
@@ -8,7 +8,6 @@ import { CuModelSelector } from "@/components/CuModelSelector";
import { RealtimeOptionsControl } from "@/components/RealtimeOptionsControl";
import { ProviderBillingBadge } from "@/components/ProviderBillingBadge";
import { Button } from "@/components/ui/button";
-import { BrandedSelect } from "@/components/ui/select";
import {
codexLogout,
loginAntigravity,
@@ -1905,6 +1904,51 @@ function LocalRuntimePanel({
);
}
+export type ManagedRuntimeBadge = {
+ key: string;
+ tone: "ok" | "warn" | "muted";
+};
+
+/**
+ * The live server verdict, in one place because it is a RULE, not decoration.
+ *
+ * Honest about ownership: reachable-and-not-ours is a port conflict (or an
+ * orphan of a removed install), never claimed as ours. Honest about
+ * readiness: "running" means the server could take a call, not merely that a
+ * socket answers. The old port-only badge stayed green through the whole
+ * model load, so the card said "Server running" while every call died on a
+ * cold pool (live 2026-08-09 11:50:47).
+ *
+ * A pool with every slot in use is still healthy — that is a busy server, not
+ * a broken one. Backends older than this rule omit `ready`/`available`;
+ * treating only an explicit `false` as bad keeps the badge exactly as honest
+ * as its input instead of inventing a warning from a missing field.
+ */
+export function managedRuntimeBadge(
+ runtime: ManagedServerRuntime | null,
+ installReady: boolean,
+): ManagedRuntimeBadge | null {
+ if (runtime === null) return null;
+ const ours = runtime.owned || installReady;
+ const serving = (runtime.pool?.in_use ?? 0) > 0;
+ const canTakeACall =
+ runtime.ready !== false && (runtime.available !== false || serving);
+ if (runtime.reachable && ours) {
+ if (canTakeACall) {
+ return { key: "apikeys_view.managed_server_running", tone: "ok" };
+ }
+ return runtime.ready === false
+ ? { key: "apikeys_view.managed_server_starting", tone: "warn" }
+ : { key: "apikeys_view.managed_server_no_capacity", tone: "warn" };
+ }
+ if (runtime.reachable) {
+ return { key: "apikeys_view.managed_server_port_conflict", tone: "warn" };
+ }
+ return runtime.owned
+ ? { key: "apikeys_view.managed_server_starting", tone: "warn" }
+ : { key: "apikeys_view.managed_server_stopped", tone: "muted" };
+}
+
/**
* One-click managed install for the self-hosted realtime server (the card
* that used to require a terminal, a venv, and a hand-written launch
@@ -2202,18 +2246,7 @@ function ManagedServerPanel({
}
};
- // Live server verdict, honest about ownership: reachable-and-not-ours is a
- // port conflict (or an orphan of a removed install), never claimed as ours.
- const runtimeBadge =
- runtime === null
- ? null
- : runtime.reachable && (runtime.owned || status.ready)
- ? { key: "apikeys_view.managed_server_running", tone: "ok" as const }
- : runtime.reachable
- ? { key: "apikeys_view.managed_server_port_conflict", tone: "warn" as const }
- : runtime.owned
- ? { key: "apikeys_view.managed_server_starting", tone: "warn" as const }
- : { key: "apikeys_view.managed_server_stopped", tone: "muted" as const };
+ const runtimeBadge = managedRuntimeBadge(runtime, status.ready);
const failed = progress?.phase === "error";
const normalizedVoiceQuery = voiceQuery.trim().toLocaleLowerCase();
@@ -2328,26 +2361,21 @@ function ManagedServerPanel({
<Brain className="h-3.5 w-3.5 text-muted-foreground" />
{t("apikeys_view.managed_thinking_title")}
</span>
- <BrandedSelect
- ariaLabel={t("apikeys_view.managed_thinking_title")}
+ <select
+ aria-label={t("apikeys_view.managed_thinking_title")}
value={selectedBrain}
- onValueChange={setSelectedBrain}
+ onChange={(event) => setSelectedBrain(event.target.value)}
disabled={setupBusy}
- className="h-8 px-2 text-xs"
- options={catalog.brain.models.map((choice) => ({
- value: choice.id,
- label: `${choice.label} · ~${choice.size_gb} GB${
- choice.recommended
- ? ` · ${t("apikeys_view.managed_brain_recommended")}`
- : ""
- }${
- choice.fits
- ? ""
- : ` · ${t("apikeys_view.managed_brain_no_fit")}`
- }`,
- disabled: !choice.fits,
- }))}
- />
+ className="h-8 w-full rounded-md border border-border bg-background px-2 text-xs"
+ >
+ {catalog.brain.models.map((choice) => (
+ <option key={choice.id} value={choice.id} disabled={!choice.fits}>
+ {choice.label} · ~{choice.size_gb} GB
+ {choice.recommended ? ` · ${t("apikeys_view.managed_brain_recommended")}` : ""}
+ {!choice.fits ? ` · ${t("apikeys_view.managed_brain_no_fit")}` : ""}
+ </option>
+ ))}
+ </select>
</label>
<label className="space-y-1 rounded-md border border-border/60 bg-background/50 p-2">
@@ -2355,28 +2383,29 @@ function ManagedServerPanel({
<Volume2 className="h-3.5 w-3.5 text-muted-foreground" />
{t("apikeys_view.managed_speaking_title")}
</span>
- <BrandedSelect
- ariaLabel={t("apikeys_view.managed_speaking_title")}
+ <select
+ aria-label={t("apikeys_view.managed_speaking_title")}
value={selectedVoice}
- onValueChange={setSelectedVoice}
+ onChange={(event) => setSelectedVoice(event.target.value)}
disabled={setupBusy}
- className="h-8 px-2 text-xs"
- options={catalog.models.map((choice) => ({
- value: choice.id,
- label: `${choice.label}${
- choice.recommended
- ? ` · ${t("apikeys_view.managed_brain_recommended")}`
- : ""
- }${
- !choice.selectable
+ className="h-8 w-full rounded-md border border-border bg-background px-2 text-xs"
+ >
+ {catalog.models.map((choice) => (
+ <option
+ key={choice.id}
+ value={choice.id}
+ disabled={!choice.selectable}
+ >
+ {choice.label}
+ {choice.recommended ? ` · ${t("apikeys_view.managed_brain_recommended")}` : ""}
+ {!choice.selectable
? ` · ${t("apikeys_view.managed_voice_unavailable")}`
: choice.runtime_ready === false
? ` · ${t("apikeys_view.managed_voice_install_required")}`
- : ""
- }`,
- disabled: !choice.selectable,
- }))}
- />
+ : ""}
+ </option>
+ ))}
+ </select>
</label>
</div>
diff --git a/jarvis/ui/web/frontend/src/components/ui/combobox.tsx b/jarvis/ui/web/frontend/src/components/ui/combobox.tsx
index 031deb5b7f..7cd14ebf1e 100644
--- a/jarvis/ui/web/frontend/src/components/ui/combobox.tsx
+++ b/jarvis/ui/web/frontend/src/components/ui/combobox.tsx
@@ -43,8 +43,6 @@ export interface ComboboxOption {
/** Extra text a matcher may search but that is never rendered. */
searchText?: string;
icon?: ReactNode;
- /** Listed for context, but cannot be selected. */
- disabled?: boolean;
}
export interface ComboboxGroup {
@@ -70,8 +68,6 @@ export interface ComboboxProps {
matches?: (option: ComboboxOption, query: string) => boolean;
disabled?: boolean;
className?: string;
- id?: string;
- ariaDescribedBy?: string;
/** Lands on the trigger button; the panel gets `${testId}-panel`. */
testId?: string;
}
@@ -117,8 +113,6 @@ export function Combobox({
matches = defaultMatches,
disabled = false,
className,
- id,
- ariaDescribedBy,
testId,
}: ComboboxProps) {
const [open, setOpen] = useState(false);
@@ -169,10 +163,6 @@ export function Combobox({
() => visibleGroups.flatMap((group) => group.options),
[visibleGroups],
);
- const enabled = useMemo(
- () => flat.filter((option) => !option.disabled),
- [flat],
- );
const measure = useCallback(() => {
const trigger = triggerRef.current;
@@ -244,7 +234,7 @@ export function Combobox({
// Open on the current value so the list starts where the user left it.
useEffect(() => {
if (!open) return;
- const index = enabled.findIndex((option) => option.value === value);
+ const index = flat.findIndex((option) => option.value === value);
setActiveIndex(index >= 0 ? index : 0);
// Only on open: while typing, the query effect below owns the highlight.
// eslint-disable-next-line react-hooks/exhaustive-deps
@@ -285,7 +275,6 @@ export function Combobox({
}, [open, close]);
function commit(option: ComboboxOption) {
- if (option.disabled) return;
close();
if (option.value !== value) onChange(option.value);
}
@@ -302,23 +291,19 @@ export function Combobox({
}
if (event.key === "ArrowDown" || event.key === "ArrowUp") {
event.preventDefault();
- if (!enabled.length) return;
+ if (!flat.length) return;
const step = event.key === "ArrowDown" ? 1 : -1;
- setActiveIndex(
- (index) => (index + step + enabled.length) % enabled.length,
- );
+ setActiveIndex((index) => (index + step + flat.length) % flat.length);
return;
}
if (event.key === "Home" || event.key === "End") {
event.preventDefault();
- setActiveIndex(
- event.key === "Home" ? 0 : Math.max(0, enabled.length - 1),
- );
+ setActiveIndex(event.key === "Home" ? 0 : Math.max(0, flat.length - 1));
return;
}
if (event.key === "Enter") {
event.preventDefault();
- const option = enabled[activeIndex];
+ const option = flat[activeIndex];
if (option) commit(option);
}
}
@@ -331,30 +316,27 @@ export function Combobox({
}
const triggerLabel = selected?.label ?? fallbackLabel ?? value;
- const activeOption = enabled[activeIndex];
+ const activeOption = flat[activeIndex];
return (
<>
<button
ref={triggerRef}
- id={id}
type="button"
role="combobox"
aria-haspopup="listbox"
aria-expanded={open}
aria-controls={open ? listId : undefined}
aria-label={ariaLabel}
- aria-describedby={ariaDescribedBy}
disabled={disabled}
data-testid={testId}
data-value={value}
onClick={() => !disabled && setOpen((wasOpen) => !wasOpen)}
onKeyDown={onTriggerKeyDown}
className={cn(
- "flex w-full items-center gap-2 rounded-md border border-input bg-background px-3 py-2 text-left text-sm",
- "shadow-[inset_0_1px_0_hsl(var(--foreground)/0.04)] transition-[border-color,background-color,box-shadow]",
- "hover:border-primary/40 hover:bg-muted/20 focus:outline-none focus-visible:border-primary/60 focus-visible:ring-1 focus-visible:ring-primary/70",
- open && "border-primary/60 bg-primary/[0.03] ring-1 ring-primary/70",
+ "flex w-full items-center gap-2 rounded-md border border-input bg-background px-3 py-2 text-left text-sm transition-colors",
+ "hover:border-primary/40 focus:outline-none focus-visible:border-primary/60 focus-visible:ring-1 focus-visible:ring-primary",
+ open && "border-primary/60 ring-1 ring-primary",
disabled && "cursor-not-allowed opacity-50",
className,
)}
@@ -388,7 +370,7 @@ export function Combobox({
maxHeight: position.maxHeight,
}}
onKeyDown={onKeyDown}
- className="fixed z-[70] flex flex-col overflow-hidden rounded-lg border border-primary/25 bg-popover/95 shadow-[0_22px_55px_-16px_rgba(0,0,0,0.9),inset_0_1px_0_hsl(var(--foreground)/0.05)] backdrop-blur-xl"
+ className="fixed z-[70] flex flex-col overflow-hidden rounded-lg border border-border bg-popover shadow-[0_18px_40px_-12px_rgba(0,0,0,0.85)]"
>
{searchable && (
<div className="flex items-center gap-2 border-b border-border/70 px-3 py-2">
@@ -446,24 +428,19 @@ export function Combobox({
id={`${listId}-${option.value}`}
role="option"
aria-selected={isSelected}
- aria-disabled={option.disabled || undefined}
data-active={isActive}
data-value={option.value}
// Pointer, not mouse: the highlight has to follow a
// pen or touch drag as well, and `onMouseMove` never
// fires for either.
- onPointerMove={() => {
- if (!option.disabled) {
- setActiveIndex(enabled.indexOf(option));
- }
- }}
+ onPointerMove={() =>
+ setActiveIndex(flat.indexOf(option))
+ }
onClick={() => commit(option)}
className={cn(
- "relative flex cursor-pointer items-center gap-2 rounded-md border border-transparent px-3 py-1.5 text-sm transition-colors",
- isActive && "border-primary/15 bg-primary/10 text-foreground",
- isSelected && "bg-primary/15 font-medium text-primary",
- option.disabled &&
- "cursor-not-allowed text-muted-foreground/45",
+ "flex cursor-pointer items-center gap-2 rounded-md px-3 py-1.5 text-sm",
+ isActive && "bg-primary/10 text-foreground",
+ isSelected && "font-medium",
)}
>
{option.icon}
diff --git a/jarvis/ui/web/frontend/src/components/ui/no-native-selects.test.ts b/jarvis/ui/web/frontend/src/components/ui/no-native-selects.test.ts
deleted file mode 100644
index 79c5ca71bf..0000000000
--- a/jarvis/ui/web/frontend/src/components/ui/no-native-selects.test.ts
+++ /dev/null
@@ -1,51 +0,0 @@
-import { readdirSync, readFileSync } from "node:fs";
-import { join, relative } from "node:path";
-import * as ts from "typescript";
-import { describe, expect, it } from "vitest";
-
-const SOURCE_ROOT = join(process.cwd(), "src");
-
-function sourceFiles(directory: string): string[] {
- return readdirSync(directory, { withFileTypes: true }).flatMap((entry) => {
- const path = join(directory, entry.name);
- if (entry.isDirectory()) return sourceFiles(path);
- if (!entry.name.endsWith(".tsx") || entry.name.includes(".test.")) return [];
- return [path];
- });
-}
-
-describe("dropdown design guard", () => {
- it("keeps operating-system select popups out of product code", () => {
- const violations: string[] = [];
-
- for (const path of sourceFiles(SOURCE_ROOT)) {
- const source = ts.createSourceFile(
- path,
- readFileSync(path, "utf8"),
- ts.ScriptTarget.Latest,
- true,
- ts.ScriptKind.TSX,
- );
-
- function visit(node: ts.Node): void {
- if (
- (ts.isJsxOpeningElement(node) || ts.isJsxSelfClosingElement(node)) &&
- node.tagName.getText(source) === "select"
- ) {
- const position = source.getLineAndCharacterOfPosition(node.getStart(source));
- violations.push(
- `${relative(SOURCE_ROOT, path)}:${position.line + 1}`,
- );
- }
- ts.forEachChild(node, visit);
- }
-
- visit(source);
- }
-
- expect(
- violations,
- "Use BrandedSelect or Combobox so the opened menu follows the app theme.",
- ).toEqual([]);
- });
-});
diff --git a/jarvis/ui/web/frontend/src/components/ui/select.test.tsx b/jarvis/ui/web/frontend/src/components/ui/select.test.tsx
deleted file mode 100644
index dc2fdd4851..0000000000
--- a/jarvis/ui/web/frontend/src/components/ui/select.test.tsx
+++ /dev/null
@@ -1,55 +0,0 @@
-import { fireEvent, render, screen } from "@testing-library/react";
-import { describe, expect, it, vi } from "vitest";
-
-import { BrandedSelect } from "@/components/ui/select";
-
-describe("BrandedSelect", () => {
- it("renders the app-owned panel and selects with the keyboard", async () => {
- const onValueChange = vi.fn();
- render(
- <BrandedSelect
- value="fast"
- onValueChange={onValueChange}
- ariaLabel="Model"
- testId="model-select"
- options={[
- { value: "fast", label: "Fast" },
- { value: "offline", label: "Unavailable", disabled: true },
- { value: "frontier", label: "Frontier" },
- ]}
- />,
- );
-
- fireEvent.click(screen.getByTestId("model-select"));
- const panel = await screen.findByTestId("model-select-panel");
- expect(panel.className).toContain("bg-popover");
-
- const unavailable = screen.getByRole("option", { name: "Unavailable" });
- expect(unavailable.getAttribute("aria-disabled")).toBe("true");
- fireEvent.click(unavailable);
- expect(onValueChange).not.toHaveBeenCalled();
-
- fireEvent.keyDown(panel, { key: "ArrowDown" });
- fireEvent.keyDown(panel, { key: "Enter" });
- expect(onValueChange).toHaveBeenCalledWith("frontier");
- });
-
- it("keeps the selected value on the trigger for forms and tests", () => {
- render(
- <BrandedSelect
- value="voice-b"
- onValueChange={() => {}}
- ariaLabel="Voice"
- testId="voice-select"
- options={[
- { value: "voice-a", label: "Voice A" },
- { value: "voice-b", label: "Voice B" },
- ]}
- />,
- );
-
- const trigger = screen.getByTestId("voice-select");
- expect(trigger.getAttribute("data-value")).toBe("voice-b");
- expect(trigger.textContent).toContain("Voice B");
- });
-});
diff --git a/jarvis/ui/web/frontend/src/components/ui/select.tsx b/jarvis/ui/web/frontend/src/components/ui/select.tsx
deleted file mode 100644
index 0a91b8b059..0000000000
--- a/jarvis/ui/web/frontend/src/components/ui/select.tsx
+++ /dev/null
@@ -1,69 +0,0 @@
-import { useMemo } from "react";
-
-import {
- Combobox,
- type ComboboxGroup,
- type ComboboxOption,
-} from "@/components/ui/combobox";
-
-export type BrandedSelectOption = ComboboxOption;
-
-export interface BrandedSelectProps {
- value: string;
- options: readonly BrandedSelectOption[];
- onValueChange: (value: string) => void;
- ariaLabel: string;
- placeholder?: string;
- disabled?: boolean;
- className?: string;
- id?: string;
- ariaDescribedBy?: string;
- testId?: string;
- searchPlaceholder?: string;
- emptyLabel?: string;
-}
-
-/**
- * The app-wide replacement for a native `<select>`.
- *
- * Browser and operating-system option popups cannot be styled reliably, so a
- * native select always risks inserting foreign grey chrome into the warm dark
- * interface. This adapter keeps short, non-searchable choices on the same
- * accessible, portalled listbox foundation as the larger searchable pickers.
- */
-export function BrandedSelect({
- value,
- options,
- onValueChange,
- ariaLabel,
- placeholder,
- disabled = false,
- className,
- id,
- ariaDescribedBy,
- testId,
- searchPlaceholder,
- emptyLabel,
-}: BrandedSelectProps) {
- const groups = useMemo<ComboboxGroup[]>(
- () => [{ id: "options", options: [...options] }],
- [options],
- );
-
- return (
- <Combobox
- value={value}
- groups={groups}
- onChange={onValueChange}
- ariaLabel={ariaLabel}
- fallbackLabel={placeholder ?? value}
- searchPlaceholder={searchPlaceholder}
- emptyLabel={emptyLabel}
- disabled={disabled}
- className={className}
- id={id}
- ariaDescribedBy={ariaDescribedBy}
- testId={testId}
- />
- );
-}
diff --git a/jarvis/ui/web/frontend/src/components/ultrawiki/ActivationWizard.tsx b/jarvis/ui/web/frontend/src/components/ultrawiki/ActivationWizard.tsx
index c70abb6fa0..81653f31d6 100644
--- a/jarvis/ui/web/frontend/src/components/ultrawiki/ActivationWizard.tsx
+++ b/jarvis/ui/web/frontend/src/components/ultrawiki/ActivationWizard.tsx
@@ -28,7 +28,6 @@ import {
import { useQuery } from "@tanstack/react-query";
import { Button } from "@/components/ui/button";
-import { BrandedSelect } from "@/components/ui/select";
import { cn } from "@/lib/utils";
import { useT } from "@/i18n";
import { useEventStore } from "@/store/events";
@@ -494,6 +493,8 @@ function OptionalStep({
rerankOptions: UltraWikiProviderOption[];
}): JSX.Element {
const t = useT();
+ const selectCls =
+ "w-full rounded-lg border border-border bg-background px-3 py-2 text-sm text-foreground focus-visible:outline-none focus-visible:ring-1 focus-visible:ring-primary/40";
return (
<div className="space-y-4">
<p className="text-sm text-muted-foreground">
@@ -503,19 +504,15 @@ function OptionalStep({
<span className="mb-1.5 block text-[10px] uppercase tracking-wider text-muted-foreground">
{t("ultrawiki.wizard.distill_label")}
</span>
- <BrandedSelect
+ <select
value={distill}
- onValueChange={onDistill}
- ariaLabel={t("ultrawiki.wizard.distill_label")}
- testId="ultrawiki-wizard-distill"
- options={[
- { value: "", label: t("ultrawiki.wizard.distill_auto") },
- {
- value: "ollama",
- label: t("ultrawiki.wizard.distill_local"),
- },
- ]}
- />
+ onChange={(e) => onDistill(e.target.value)}
+ className={selectCls}
+ data-testid="ultrawiki-wizard-distill"
+ >
+ <option value="">{t("ultrawiki.wizard.distill_auto")}</option>
+ <option value="ollama">{t("ultrawiki.wizard.distill_local")}</option>
+ </select>
<span className="mt-1 block text-[11px] text-muted-foreground">
{t("ultrawiki.wizard.distill_privacy_hint")}
</span>
@@ -524,24 +521,26 @@ function OptionalStep({
<span className="mb-1.5 block text-[10px] uppercase tracking-wider text-muted-foreground">
{t("ultrawiki.wizard.rerank_label")}
</span>
- <BrandedSelect
+ <select
value={rerank}
- onValueChange={onRerank}
- ariaLabel={t("ultrawiki.wizard.rerank_label")}
- testId="ultrawiki-wizard-rerank"
- options={[
- { value: "", label: t("ultrawiki.wizard.rerank_off") },
- ...rerankOptions.map((option) => ({
- value: option.name,
- label: `${option.name}${
- option.ready
- ? ""
- : ` (${t("ultrawiki.slots.not_ready_suffix")})`
- }`,
- disabled: !option.ready,
- })),
- ]}
- />
+ onChange={(e) => onRerank(e.target.value)}
+ className={selectCls}
+ data-testid="ultrawiki-wizard-rerank"
+ >
+ <option value="">{t("ultrawiki.wizard.rerank_off")}</option>
+ {rerankOptions.map((option) => (
+ <option
+ key={option.name}
+ value={option.name}
+ disabled={!option.ready}
+ >
+ {option.name}
+ {!option.ready
+ ? ` (${t("ultrawiki.slots.not_ready_suffix")})`
+ : ""}
+ </option>
+ ))}
+ </select>
</label>
</div>
);
diff --git a/jarvis/ui/web/frontend/src/components/ultrawiki/ContentsPanel.test.tsx b/jarvis/ui/web/frontend/src/components/ultrawiki/ContentsPanel.test.tsx
index 69e3771c39..460523366c 100644
--- a/jarvis/ui/web/frontend/src/components/ultrawiki/ContentsPanel.test.tsx
+++ b/jarvis/ui/web/frontend/src/components/ultrawiki/ContentsPanel.test.tsx
@@ -161,14 +161,9 @@ describe("ContentsPanel", () => {
expect(screen.getByTestId("ultrawiki-item-1")).toBeDefined();
});
- fireEvent.click(screen.getByTestId("ultrawiki-contents-state-filter"));
- const panel = await screen.findByTestId(
- "ultrawiki-contents-state-filter-panel",
- );
- const failed = [...panel.querySelectorAll('[role="option"]')].find(
- (option) => option.getAttribute("data-value") === "failed",
- );
- fireEvent.click(failed!);
+ fireEvent.change(screen.getByTestId("ultrawiki-contents-state-filter"), {
+ target: { value: "failed" },
+ });
await waitFor(() => {
expect(seen.some((url) => url.includes("state=failed"))).toBe(true);
diff --git a/jarvis/ui/web/frontend/src/components/ultrawiki/ContentsPanel.tsx b/jarvis/ui/web/frontend/src/components/ultrawiki/ContentsPanel.tsx
index 891c4266fa..7f2bec06b8 100644
--- a/jarvis/ui/web/frontend/src/components/ultrawiki/ContentsPanel.tsx
+++ b/jarvis/ui/web/frontend/src/components/ultrawiki/ContentsPanel.tsx
@@ -15,7 +15,6 @@ import { useCallback, useEffect, useState } from "react";
import { AlertCircle, Database, ExternalLink, Loader2 } from "lucide-react";
import { Button } from "@/components/ui/button";
-import { BrandedSelect } from "@/components/ui/select";
import { cn } from "@/lib/utils";
import { useT } from "@/i18n";
import { formatRelativeTime } from "@/components/ultrawiki/relativeTime";
@@ -130,37 +129,35 @@ export function ContentsPanel({
<div className="flex flex-wrap gap-2">
<label className="flex items-center gap-1.5 text-[11px] text-muted-foreground">
{t("ultrawiki.contents.filter_source")}
- <BrandedSelect
+ <select
value={sourceId}
- onValueChange={setSourceId}
- ariaLabel={t("ultrawiki.contents.filter_source")}
- className="w-auto min-w-40 px-2 py-1 text-xs"
- testId="ultrawiki-contents-source-filter"
- options={[
- { value: "", label: t("ultrawiki.contents.all_sources") },
- ...status.sources.map((source) => ({
- value: source.id,
- label: source.label,
- })),
- ]}
- />
+ onChange={(e) => setSourceId(e.target.value)}
+ className="rounded-lg border border-border bg-background px-2 py-1 text-xs text-foreground"
+ data-testid="ultrawiki-contents-source-filter"
+ >
+ <option value="">{t("ultrawiki.contents.all_sources")}</option>
+ {status.sources.map((source) => (
+ <option key={source.id} value={source.id}>
+ {source.label}
+ </option>
+ ))}
+ </select>
</label>
<label className="flex items-center gap-1.5 text-[11px] text-muted-foreground">
{t("ultrawiki.contents.filter_state")}
- <BrandedSelect
+ <select
value={state}
- onValueChange={setState}
- ariaLabel={t("ultrawiki.contents.filter_state")}
- className="w-auto min-w-40 px-2 py-1 text-xs"
- testId="ultrawiki-contents-state-filter"
- options={[
- { value: "", label: t("ultrawiki.contents.all_states") },
- ...STATE_FILTERS.map(([key, labelKey]) => ({
- value: key,
- label: t(labelKey),
- })),
- ]}
- />
+ onChange={(e) => setState(e.target.value)}
+ className="rounded-lg border border-border bg-background px-2 py-1 text-xs text-foreground"
+ data-testid="ultrawiki-contents-state-filter"
+ >
+ <option value="">{t("ultrawiki.contents.all_states")}</option>
+ {STATE_FILTERS.map(([key, labelKey]) => (
+ <option key={key} value={key}>
+ {t(labelKey)}
+ </option>
+ ))}
+ </select>
</label>
</div>
diff --git a/jarvis/ui/web/frontend/src/components/ultrawiki/SupabaseConnect.tsx b/jarvis/ui/web/frontend/src/components/ultrawiki/SupabaseConnect.tsx
index 40318908a4..1f6e12418e 100644
--- a/jarvis/ui/web/frontend/src/components/ultrawiki/SupabaseConnect.tsx
+++ b/jarvis/ui/web/frontend/src/components/ultrawiki/SupabaseConnect.tsx
@@ -24,7 +24,6 @@ import { CheckCircle2, ExternalLink, Loader2, RefreshCw } from "lucide-react";
import { ApiKeyForm } from "@/components/ApiKeyForm";
import { Button } from "@/components/ui/button";
-import { BrandedSelect } from "@/components/ui/select";
import { useT } from "@/i18n";
import { useEventStore } from "@/store/events";
import {
@@ -144,29 +143,25 @@ export function SupabaseConnect({
<div className="flex flex-wrap items-end gap-2">
<div className="min-w-[14rem] flex-1">
<SettingsField label={t("ultrawiki.supabase.project_label")}>
- <BrandedSelect
+ <select
value={projectRef}
- onValueChange={setProjectRef}
- ariaLabel={t("ultrawiki.supabase.project_label")}
+ onChange={(e) => setProjectRef(e.target.value)}
disabled={!projects || projects.length === 0}
className={settingsInputCls}
- testId="ultrawiki-supabase-project"
- options={[
- {
- value: "",
- label:
- projects === null
- ? t("ultrawiki.supabase.load_first")
- : t("ultrawiki.supabase.choose_project"),
- },
- ...(projects ?? []).map((project) => ({
- value: project.ref,
- label: `${project.name}${
- project.region ? ` · ${project.region}` : ""
- }`,
- })),
- ]}
- />
+ data-testid="ultrawiki-supabase-project"
+ >
+ <option value="">
+ {projects === null
+ ? t("ultrawiki.supabase.load_first")
+ : t("ultrawiki.supabase.choose_project")}
+ </option>
+ {(projects ?? []).map((project) => (
+ <option key={project.ref} value={project.ref}>
+ {project.name}
+ {project.region ? ` · ${project.region}` : ""}
+ </option>
+ ))}
+ </select>
</SettingsField>
</div>
<Button
diff --git a/jarvis/ui/web/frontend/src/components/wiki/ObsidianSetupDialog.test.tsx b/jarvis/ui/web/frontend/src/components/wiki/ObsidianSetupDialog.test.tsx
index 96684dc857..9afc3aa49d 100644
--- a/jarvis/ui/web/frontend/src/components/wiki/ObsidianSetupDialog.test.tsx
+++ b/jarvis/ui/web/frontend/src/components/wiki/ObsidianSetupDialog.test.tsx
@@ -394,14 +394,10 @@ describe("ObsidianSetupDialog", () => {
});
fireEvent.click(screen.getByTestId("obsidian-setup-mode-existing"));
- fireEvent.click(screen.getByTestId("obsidian-setup-vault-select"));
- const panel = await screen.findByTestId(
- "obsidian-setup-vault-select-panel",
- );
- const vault = [...panel.querySelectorAll('[role="option"]')].find(
- (option) => option.getAttribute("data-value") === VAULTS[1].path,
- );
- fireEvent.click(vault!);
+ const select = screen.getByTestId(
+ "obsidian-setup-vault-select",
+ ) as HTMLSelectElement;
+ fireEvent.change(select, { target: { value: VAULTS[1].path } });
fireEvent.click(screen.getByTestId("obsidian-setup-register"));
@@ -465,14 +461,10 @@ describe("ObsidianSetupDialog", () => {
).toBe(false);
});
fireEvent.click(screen.getByTestId("obsidian-setup-mode-existing"));
- fireEvent.click(screen.getByTestId("obsidian-setup-vault-select"));
- const panel = await screen.findByTestId(
- "obsidian-setup-vault-select-panel",
- );
- const vault = [...panel.querySelectorAll('[role="option"]')].find(
- (option) => option.getAttribute("data-value") === VAULTS[1].path,
+ fireEvent.change(
+ screen.getByTestId("obsidian-setup-vault-select") as HTMLSelectElement,
+ { target: { value: VAULTS[1].path } },
);
- fireEvent.click(vault!);
fireEvent.click(screen.getByTestId("obsidian-setup-register"));
await waitFor(() => {
diff --git a/jarvis/ui/web/frontend/src/components/wiki/ObsidianSetupDialog.tsx b/jarvis/ui/web/frontend/src/components/wiki/ObsidianSetupDialog.tsx
index f311fd370c..2e5817627b 100644
--- a/jarvis/ui/web/frontend/src/components/wiki/ObsidianSetupDialog.tsx
+++ b/jarvis/ui/web/frontend/src/components/wiki/ObsidianSetupDialog.tsx
@@ -29,7 +29,6 @@ import { useCallback, useEffect, useRef, useState } from "react";
import { Check, ExternalLink, Loader2, X } from "lucide-react";
import { Button } from "@/components/ui/button";
-import { BrandedSelect } from "@/components/ui/select";
import { cn } from "@/lib/utils";
import { useT } from "@/i18n";
import { useEventStore } from "@/store/events";
@@ -599,17 +598,19 @@ export function ObsidianSetupDialog({
</button>
{registerMode === "existing" && vaults.length > 0 && (
- <BrandedSelect
- ariaLabel={t("obsidian_setup_dialog.vault_select_label")}
+ <select
+ aria-label={t("obsidian_setup_dialog.vault_select_label")}
value={selectedVaultPath ?? ""}
- onValueChange={setSelectedVaultPath}
- testId="obsidian-setup-vault-select"
- options={vaults.map((vault) => ({
- value: vault.path,
- label: vault.name,
- hint: vault.path,
- }))}
- />
+ onChange={(e) => setSelectedVaultPath(e.target.value)}
+ data-testid="obsidian-setup-vault-select"
+ className="w-full rounded-md border border-input bg-background px-3 py-2 text-sm"
+ >
+ {vaults.map((v) => (
+ <option key={v.path} value={v.path} title={v.path}>
+ {v.name}
+ </option>
+ ))}
+ </select>
)}
</div>
diff --git a/jarvis/ui/web/frontend/src/hooks/useProviders.ts b/jarvis/ui/web/frontend/src/hooks/useProviders.ts
index ec7e44c48d..500c6ebc07 100644
--- a/jarvis/ui/web/frontend/src/hooks/useProviders.ts
+++ b/jarvis/ui/web/frontend/src/hooks/useProviders.ts
@@ -834,6 +834,23 @@ export interface ManagedServerStatus {
export interface ManagedServerRuntime {
/** Something answers on the configured port right now. */
reachable: boolean;
+ /**
+ * The model pool answers — the first moment a call can actually be taken.
+ * An open port only proves a socket exists, so `reachable` alone used to
+ * badge a still-loading server as running while every call failed.
+ */
+ ready?: boolean;
+ /** At least one pipeline is free for a NEW call. */
+ available?: boolean;
+ /** Sanitized pool snapshot; `in_use > 0` means healthy-and-serving. */
+ pool?: {
+ size: number;
+ in_use: number;
+ available: number;
+ active: number;
+ draining: number;
+ stuck: number;
+ } | null;
port: number;
pid: number | null;
/** The recorded server process verifiably runs (PID-reuse safe). */
diff --git a/jarvis/ui/web/frontend/src/i18n/locales/de.json b/jarvis/ui/web/frontend/src/i18n/locales/de.json
index 04c9032d3d..9adb02a34d 100644
--- a/jarvis/ui/web/frontend/src/i18n/locales/de.json
+++ b/jarvis/ui/web/frontend/src/i18n/locales/de.json
@@ -1178,6 +1178,7 @@
"managed_server_stopped": "Server gestoppt",
"managed_server_starting": "Server startet — Sprachmodelle werden geladen…",
"managed_server_port_conflict": "Ein anderer Prozess belegt diesen Port",
+ "managed_server_no_capacity": "Server antwortet, hat aber keine freie Sprach-Pipeline",
"managed_start_cta": "Server starten",
"managed_stop_cta": "Server stoppen",
"managed_brain_setup_note": "Richtet zuerst das lokale Denkmodell ein: installiert bei Bedarf Ollama und lädt das Modell herunter (mehrere zusätzliche GB).",
diff --git a/jarvis/ui/web/frontend/src/i18n/locales/en.json b/jarvis/ui/web/frontend/src/i18n/locales/en.json
index 323f6b7306..1165f6676d 100644
--- a/jarvis/ui/web/frontend/src/i18n/locales/en.json
+++ b/jarvis/ui/web/frontend/src/i18n/locales/en.json
@@ -1178,6 +1178,7 @@
"managed_server_stopped": "Server stopped",
"managed_server_starting": "Server starting — loading voice models…",
"managed_server_port_conflict": "Another process is serving this port",
+ "managed_server_no_capacity": "Server answers but has no free voice pipeline",
"managed_start_cta": "Start server",
"managed_stop_cta": "Stop server",
"managed_brain_setup_note": "Also sets up the local brain first: installs Ollama if needed and downloads the brain model (several extra GB).",
diff --git a/jarvis/ui/web/frontend/src/i18n/locales/es.json b/jarvis/ui/web/frontend/src/i18n/locales/es.json
index c55e6233b6..e559ae3bd2 100644
--- a/jarvis/ui/web/frontend/src/i18n/locales/es.json
+++ b/jarvis/ui/web/frontend/src/i18n/locales/es.json
@@ -1178,6 +1178,7 @@
"managed_server_stopped": "Servidor detenido",
"managed_server_starting": "Servidor iniciándose — cargando los modelos de voz…",
"managed_server_port_conflict": "Otro proceso está sirviendo en este puerto",
+ "managed_server_no_capacity": "El servidor responde pero no tiene ninguna canalización de voz libre",
"managed_start_cta": "Iniciar servidor",
"managed_stop_cta": "Detener servidor",
"managed_brain_setup_note": "Primero configura el cerebro local: instala Ollama si hace falta y descarga el modelo (varios GB adicionales).",
diff --git a/jarvis/ui/web/frontend/src/views/CliTestHubView.tsx b/jarvis/ui/web/frontend/src/views/CliTestHubView.tsx
index 7f37354e1c..c89dfcc4fb 100644
--- a/jarvis/ui/web/frontend/src/views/CliTestHubView.tsx
+++ b/jarvis/ui/web/frontend/src/views/CliTestHubView.tsx
@@ -31,7 +31,6 @@ import {
import { ViewHeader } from "@/views/ChatsView";
import { ScrollArea } from "@/components/ui/scroll-area";
import { Button } from "@/components/ui/button";
-import { BrandedSelect } from "@/components/ui/select";
import { cn } from "@/lib/utils";
import { useT } from "@/i18n";
import { useEventStore } from "@/store/events";
@@ -338,24 +337,21 @@ function PromptPanel({
<span className="mb-1 block text-[10px] uppercase tracking-wider text-muted-foreground/70">
{t("cli_test_hub_view.cli_hint_label")}
</span>
- <BrandedSelect
+ <select
id="cli-test-hint"
value={cliHint}
- onValueChange={onCliHintChange}
+ onChange={(e) => onCliHintChange(e.target.value)}
disabled={isPending}
- ariaLabel={t("cli_test_hub_view.cli_hint_aria")}
- className="min-w-[180px] py-1.5 text-xs"
- options={[
- {
- value: "",
- label: `${assistantName} ${t("cli_test_hub_view.let_decide")}`,
- },
- ...connectedClis.map((cli) => ({
- value: cli.name,
- label: cli.name,
- })),
- ]}
- />
+ aria-label={t("cli_test_hub_view.cli_hint_aria")}
+ className="min-w-[180px] rounded-md border border-input bg-background px-3 py-1.5 text-xs focus-visible:outline-none focus-visible:ring-1 focus-visible:ring-ring disabled:opacity-60"
+ >
+ <option value="">{assistantName} {t("cli_test_hub_view.let_decide")}</option>
+ {connectedClis.map((cli) => (
+ <option key={cli.name} value={cli.name}>
+ {cli.name}
+ </option>
+ ))}
+ </select>
</label>
<div className="flex items-center gap-3">
diff --git a/jarvis/ui/web/frontend/src/views/ClisView.tsx b/jarvis/ui/web/frontend/src/views/ClisView.tsx
index 7a6c5080a3..57efa93f85 100644
--- a/jarvis/ui/web/frontend/src/views/ClisView.tsx
+++ b/jarvis/ui/web/frontend/src/views/ClisView.tsx
@@ -21,7 +21,6 @@ import {
import { ViewHeader } from "@/views/ChatsView";
import { ScrollArea } from "@/components/ui/scroll-area";
import { Button } from "@/components/ui/button";
-import { BrandedSelect } from "@/components/ui/select";
import { cn } from "@/lib/utils";
import {
useCheckCli,
@@ -1043,23 +1042,16 @@ function CustomCliWizard({ onClose }: { onClose: () => void }) {
<div className="mb-1 text-[10px] uppercase tracking-wider text-muted-foreground/70">
{t("clis_view.auth_mode_label")}
</div>
- <BrandedSelect
+ <select
value={form.auth_mode}
- onValueChange={(value) =>
- setForm({
- ...form,
- auth_mode: value as typeof form.auth_mode,
- })
- }
- ariaLabel={t("clis_view.auth_mode_label")}
- className="py-1.5 text-xs"
- options={[
- { value: "none", label: t("clis_view.auth_none") },
- { value: "oauth_cli", label: t("clis_view.auth_oauth_cli") },
- { value: "api_key", label: t("clis_view.auth_api_key") },
- { value: "config_file", label: t("clis_view.auth_config_file") },
- ]}
- />
+ onChange={(e) => setForm({ ...form, auth_mode: e.target.value as typeof form.auth_mode })}
+ className="w-full rounded-md border border-input bg-background px-3 py-1.5 text-xs"
+ >
+ <option value="none">{t("clis_view.auth_none")}</option>
+ <option value="oauth_cli">{t("clis_view.auth_oauth_cli")}</option>
+ <option value="api_key">{t("clis_view.auth_api_key")}</option>
+ <option value="config_file">{t("clis_view.auth_config_file")}</option>
+ </select>
</label>
{(form.auth_mode === "oauth_cli") && (
<TextField label={t("clis_view.field_login_command")} val={form.login_command}
@@ -1089,23 +1081,16 @@ function CustomCliWizard({ onClose }: { onClose: () => void }) {
<div className="mb-1 text-[10px] uppercase tracking-wider text-muted-foreground/70">
Risk-Tier
</div>
- <BrandedSelect
+ <select
value={form.risk_tier}
- onValueChange={(value) =>
- setForm({
- ...form,
- risk_tier: value as typeof form.risk_tier,
- })
- }
- ariaLabel="Risk tier"
- className="py-1.5 text-xs"
- options={[
- { value: "safe", label: t("clis_view.risk_safe") },
- { value: "monitor", label: "monitor (execute + log)" },
- { value: "ask", label: t("clis_view.risk_ask") },
- { value: "block", label: t("clis_view.risk_block") },
- ]}
- />
+ onChange={(e) => setForm({ ...form, risk_tier: e.target.value as typeof form.risk_tier })}
+ className="w-full rounded-md border border-input bg-background px-3 py-1.5 text-xs"
+ >
+ <option value="safe">{t("clis_view.risk_safe")}</option>
+ <option value="monitor">monitor (execute + log)</option>
+ <option value="ask">{t("clis_view.risk_ask")}</option>
+ <option value="block">{t("clis_view.risk_block")}</option>
+ </select>
</label>
<TextArea label={t("clis_view.field_allow_patterns")} val={form.allow_patterns}
onChange={(v) => setForm({ ...form, allow_patterns: v })}
diff --git a/jarvis/ui/web/frontend/src/views/PluginsView.test.tsx b/jarvis/ui/web/frontend/src/views/PluginsView.test.tsx
index 16527bb577..9c1730f942 100644
--- a/jarvis/ui/web/frontend/src/views/PluginsView.test.tsx
+++ b/jarvis/ui/web/frontend/src/views/PluginsView.test.tsx
@@ -486,7 +486,6 @@ describe("PluginsView category sections are data-driven", () => {
});
expect(screen.getByText("mystery")).toBeDefined();
// The filter menu is fed by the same data, so it offers the new category too.
- fireEvent.click(screen.getByRole("combobox", { name: "Plugin category" }));
expect(
screen.getByRole("option", { name: "Something Brand New" }),
).toBeDefined();
diff --git a/jarvis/ui/web/frontend/src/views/PluginsView.tsx b/jarvis/ui/web/frontend/src/views/PluginsView.tsx
index e89fdd6068..854ca96555 100644
--- a/jarvis/ui/web/frontend/src/views/PluginsView.tsx
+++ b/jarvis/ui/web/frontend/src/views/PluginsView.tsx
@@ -19,7 +19,6 @@ import {
import { ViewHeader } from "@/views/ChatsView";
import { ScrollArea } from "@/components/ui/scroll-area";
import { Button } from "@/components/ui/button";
-import { BrandedSelect } from "@/components/ui/select";
import { cn } from "@/lib/utils";
import { openExternalUrl } from "@/lib/openExternal";
import { robustCopy } from "@/lib/clipboard";
@@ -902,20 +901,22 @@ function FilterMenu({ filter, setFilter }: { filter: FilterId; setFilter: (f: Fi
const { data } = useQuery({ queryKey: ["marketplace-plugins"], queryFn: fetchCatalog });
const categories = orderedCategories(data, (data?.plugins ?? []).map(adapt));
return (
- <div>
- <BrandedSelect
+ <div className="relative">
+ <select
value={filter}
- onValueChange={(value) => setFilter(value as FilterId)}
- ariaLabel="Plugin category"
- className="h-9 w-auto rounded-full bg-card/60 px-4 text-xs font-medium"
- options={[
- { value: "all", label: "All" },
- ...categories.map((category) => ({
- value: category,
- label: category,
- })),
- ]}
- />
+ onChange={(e) => setFilter(e.target.value as FilterId)}
+ className="h-9 cursor-pointer appearance-none rounded-full border border-border bg-card/60 px-4 pr-7 text-xs font-medium text-foreground hover:border-primary/40 focus:border-primary/40 focus:outline-none"
+ >
+ <option value="all">All</option>
+ {categories.map((c) => (
+ <option key={c} value={c}>
+ {c}
+ </option>
+ ))}
+ </select>
+ <span className="pointer-events-none absolute right-2.5 top-1/2 -translate-y-1/2 text-[9px] text-muted-foreground">
+ ▾
+ </span>
</div>
);
}
diff --git a/jarvis/ui/web/frontend/src/views/SelfModView.tsx b/jarvis/ui/web/frontend/src/views/SelfModView.tsx
index c7f9a3f3ce..af82fcd764 100644
--- a/jarvis/ui/web/frontend/src/views/SelfModView.tsx
+++ b/jarvis/ui/web/frontend/src/views/SelfModView.tsx
@@ -10,7 +10,6 @@
import { useEffect, useMemo, useState } from "react";
import { useEventStore } from "@/store/events";
import { useT } from "@/i18n";
-import { BrandedSelect } from "@/components/ui/select";
type AuditEvent = {
ts: string;
@@ -114,24 +113,20 @@ function AuditFilters({
filter: { actor?: string; action?: string; success_only: boolean };
onChange: (f: { actor?: string; action?: string; success_only: boolean }) => void;
}) {
- const t = useT();
return (
<div style={{ display: "flex", gap: 12, marginBottom: 12 }}>
- <BrandedSelect
+ <select
value={filter.actor ?? ""}
- onValueChange={(value) =>
- onChange({ ...filter, actor: value || undefined })
+ onChange={(e) =>
+ onChange({ ...filter, actor: e.target.value || undefined })
}
- ariaLabel={t("self_mod_view.all_actors")}
- className="w-44 py-1.5 text-xs"
- options={[
- { value: "", label: t("self_mod_view.all_actors") },
- { value: "hauptjarvis", label: t("self_mod_view.actor_main") },
- { value: "openclaw", label: "OpenClaw" },
- { value: "user", label: "User" },
- { value: "system", label: "System" },
- ]}
- />
+ >
+ <option value="">Alle Actors</option>
+ <option value="hauptjarvis">Hauptjarvis</option>
+ <option value="openclaw">OpenClaw</option>
+ <option value="user">User</option>
+ <option value="system">System</option>
+ </select>
<label>
<input
type="checkbox"
@@ -140,7 +135,7 @@ function AuditFilters({
onChange({ ...filter, success_only: e.target.checked })
}
/>
- {t("self_mod_view.successful_only")}
+ Nur erfolgreiche
</label>
</div>
);
diff --git a/jarvis/ui/web/frontend/src/views/SettingsView.tsx b/jarvis/ui/web/frontend/src/views/SettingsView.tsx
index 34895ce0f5..b2d96ddd77 100644
--- a/jarvis/ui/web/frontend/src/views/SettingsView.tsx
+++ b/jarvis/ui/web/frontend/src/views/SettingsView.tsx
@@ -1,15 +1,16 @@
-import { useEffect, useState } from "react";
+import { useEffect, useRef, useState } from "react";
import {
Settings,
Mic,
Keyboard,
Loader2,
Languages,
+ ChevronDown,
+ Check,
} from "lucide-react";
import { ViewHeader } from "@/views/ChatsView";
import { Switch } from "@/components/ui/switch";
import { Button } from "@/components/ui/button";
-import { BrandedSelect } from "@/components/ui/select";
import { OverlayTaskbarGroup } from "@/views/settings/OverlayTaskbarGroup";
import { LanguagesGroup } from "@/views/settings/LanguagesGroup";
import { AppSettingsGroup } from "@/views/settings/AppSettingsGroup";
@@ -191,19 +192,75 @@ function LanguageDropdown({
onChange: (code: WakeLanguage) => void;
disabled?: boolean;
}) {
+ const [open, setOpen] = useState(false);
+ const ref = useRef<HTMLDivElement>(null);
+ useEffect(() => {
+ if (!open) return;
+ const onDoc = (e: MouseEvent) => {
+ if (ref.current && !ref.current.contains(e.target as Node)) setOpen(false);
+ };
+ const onKey = (e: KeyboardEvent) => {
+ if (e.key === "Escape") setOpen(false);
+ };
+ document.addEventListener("mousedown", onDoc);
+ document.addEventListener("keydown", onKey);
+ return () => {
+ document.removeEventListener("mousedown", onDoc);
+ document.removeEventListener("keydown", onKey);
+ };
+ }, [open]);
+
+ const selected = (options as string[]).includes(value)
+ ? labelFor(value as WakeLanguage)
+ : null;
+
return (
- <BrandedSelect
- value={value}
- onValueChange={(code) => onChange(code as WakeLanguage)}
- ariaLabel={placeholder}
- placeholder={placeholder}
- disabled={disabled}
- className="border-primary/40"
- options={options.map((code) => ({
- value: code,
- label: labelFor(code),
- }))}
- />
+ <div ref={ref} className="relative">
+ <button
+ type="button"
+ disabled={disabled}
+ onClick={() => setOpen((o) => !o)}
+ aria-haspopup="listbox"
+ aria-expanded={open}
+ className="flex w-full items-center justify-between rounded-md border border-primary/40 bg-background px-3 py-2 text-sm transition-colors hover:border-primary focus:outline-none focus:ring-1 focus:ring-primary disabled:opacity-50"
+ >
+ <span className={selected ? "text-foreground" : "text-muted-foreground"}>
+ {selected ?? placeholder}
+ </span>
+ <ChevronDown
+ className={`h-4 w-4 shrink-0 text-primary transition-transform ${open ? "rotate-180" : ""}`}
+ />
+ </button>
+ {open && (
+ <ul
+ role="listbox"
+ className="absolute z-50 mt-1 w-full overflow-hidden rounded-md border border-primary/40 bg-card shadow-lg shadow-scrim/50"
+ >
+ {options.map((code) => {
+ const active = code === value;
+ return (
+ <li key={code} role="option" aria-selected={active}>
+ <button
+ type="button"
+ onClick={() => {
+ onChange(code);
+ setOpen(false);
+ }}
+ className={`flex w-full items-center justify-between px-3 py-2 text-left text-sm transition-colors ${
+ active
+ ? "bg-primary/15 font-medium text-primary"
+ : "text-foreground hover:bg-primary/10 hover:text-primary"
+ }`}
+ >
+ {labelFor(code)}
+ {active && <Check className="h-4 w-4 shrink-0 text-primary" />}
+ </button>
+ </li>
+ );
+ })}
+ </ul>
+ )}
+ </div>
);
}
@@ -485,17 +542,18 @@ function WakeWordPanel() {
<label className="mt-4 block text-xs font-medium text-muted-foreground">
{t("settings_view.wake_word.engine_label")}
</label>
- <BrandedSelect
+ <select
value={engine}
- onValueChange={setEngine}
- ariaLabel={t("settings_view.wake_word.engine_label")}
+ onChange={(e) => setEngine(e.target.value)}
disabled={loading}
- className="mt-1"
- options={WAKE_ENGINES.map((wakeEngine) => ({
- value: wakeEngine,
- label: t(WAKE_ENGINE_I18N_KEY[wakeEngine]),
- }))}
- />
+ className="mt-1 w-full rounded-md border border-input bg-background px-3 py-2 text-sm focus:outline-none focus:ring-1 focus:ring-primary disabled:opacity-50"
+ >
+ {WAKE_ENGINES.map((eng) => (
+ <option key={eng} value={eng}>
+ {t(WAKE_ENGINE_I18N_KEY[eng])}
+ </option>
+ ))}
+ </select>
{/* Custom ONNX model path */}
{engine === "custom_onnx" && (
diff --git a/jarvis/ui/web/frontend/src/views/SkillsView.tsx b/jarvis/ui/web/frontend/src/views/SkillsView.tsx
index baf6979fb4..fdc130dceb 100644
--- a/jarvis/ui/web/frontend/src/views/SkillsView.tsx
+++ b/jarvis/ui/web/frontend/src/views/SkillsView.tsx
@@ -38,7 +38,6 @@ import { ScrollArea } from "@/components/ui/scroll-area";
import { Button } from "@/components/ui/button";
import { Badge } from "@/components/ui/badge";
import { Switch } from "@/components/ui/switch";
-import { BrandedSelect } from "@/components/ui/select";
import { cn } from "@/lib/utils";
import { translate, useT } from "@/i18n";
import {
@@ -394,22 +393,18 @@ export function SkillsView() {
onClick={() => setOwnerFilter("builtin")}
/>
{categoryOptions.length > 0 && (
- <BrandedSelect
+ <select
value={categoryFilter ?? ""}
- onValueChange={(value) => setCategoryFilter(value || null)}
- ariaLabel={t("skills_view.all_categories")}
- className="w-auto rounded-full px-2 py-0.5 text-[10px]"
- options={[
- {
- value: "",
- label: t("skills_view.all_categories"),
- },
- ...categoryOptions.map((category) => ({
- value: category,
- label: category,
- })),
- ]}
- />
+ onChange={(e) => setCategoryFilter(e.target.value || null)}
+ className="rounded-full border border-border bg-background px-2 py-0.5 text-[10px] focus:outline-none focus:ring-1 focus:ring-primary"
+ >
+ <option value="">Alle Kategorien</option>
+ {categoryOptions.map((c) => (
+ <option key={c} value={c}>
+ {c}
+ </option>
+ ))}
+ </select>
)}
{searchActive && (
<button
@@ -417,7 +412,7 @@ export function SkillsView() {
onClick={clearFilters}
className="ml-auto text-[10px] text-muted-foreground underline hover:text-foreground"
>
- {t("skills_view.reset_filters")}
+ Zuruecksetzen
</button>
)}
</div>
diff --git a/jarvis/ui/web/frontend/src/views/contacts/ContactEditDialog.tsx b/jarvis/ui/web/frontend/src/views/contacts/ContactEditDialog.tsx
index 575d17be32..f1069f8528 100644
--- a/jarvis/ui/web/frontend/src/views/contacts/ContactEditDialog.tsx
+++ b/jarvis/ui/web/frontend/src/views/contacts/ContactEditDialog.tsx
@@ -2,7 +2,6 @@ import { useState } from "react";
import { Loader2, Plus, X } from "lucide-react";
import { useT } from "@/i18n";
import { cn } from "@/lib/utils";
-import { BrandedSelect } from "@/components/ui/select";
import { RELATIONSHIPS, relationshipLabel, type Relationship } from "./constants";
import {
createContact,
@@ -127,21 +126,18 @@ export function ContactEditDialog({
</Labeled>
<Labeled label={t("contacts.relationship")}>
- <BrandedSelect
+ <select
value={relationship}
- onValueChange={(value) =>
- setRelationship(value as Relationship | "")
- }
- ariaLabel={t("contacts.relationship")}
+ onChange={(e) => setRelationship(e.target.value as Relationship | "")}
className={inputClass}
- options={[
- { value: "", label: "—" },
- ...RELATIONSHIPS.map((item) => ({
- value: item,
- label: relationshipLabel(t, item),
- })),
- ]}
- />
+ >
+ <option value="">—</option>
+ {RELATIONSHIPS.map((r) => (
+ <option key={r} value={r}>
+ {relationshipLabel(t, r)}
+ </option>
+ ))}
+ </select>
</Labeled>
<ListField
diff --git a/jarvis/ui/web/frontend/src/views/settings/AudioDevicesGroup.test.tsx b/jarvis/ui/web/frontend/src/views/settings/AudioDevicesGroup.test.tsx
index 7dc0b7c290..62ebf53b27 100644
--- a/jarvis/ui/web/frontend/src/views/settings/AudioDevicesGroup.test.tsx
+++ b/jarvis/ui/web/frontend/src/views/settings/AudioDevicesGroup.test.tsx
@@ -45,14 +45,17 @@ describe("AudioDevicesGroup", () => {
expect(screen.getByText("Audio devices")).toBeTruthy();
await waitFor(() => {
- const output = screen.getByTestId("audio-output-select");
- expect(output.getAttribute("data-value")).toBe("PRO X Gaming Headset");
- const input = screen.getByTestId("audio-input-select");
- expect(input.getAttribute("data-value")).toBe("auto-headset");
+ const output = screen.getByTestId(
+ "audio-output-select",
+ ) as HTMLSelectElement;
+ expect(output.value).toBe("PRO X Gaming Headset");
+ const input = screen.getByTestId(
+ "audio-input-select",
+ ) as HTMLSelectElement;
+ expect(input.value).toBe("auto-headset");
});
// The OS default entry is labeled, the automatic option is first.
- fireEvent.click(screen.getByTestId("audio-output-select"));
expect(screen.getByText(/Speakers \(Realtek HD Audio\)/)).toBeTruthy();
const autoOptions = screen.getAllByText("Automatic (recommended)");
expect(autoOptions.length).toBe(2);
@@ -78,11 +81,12 @@ describe("AudioDevicesGroup", () => {
vi.stubGlobal("fetch", fetchMock);
render(<AudioDevicesGroup />);
- const output = await waitFor(() =>
+ const output = (await waitFor(() =>
screen.getByTestId("audio-output-select"),
- );
- fireEvent.click(output);
- fireEvent.click(screen.getByText(/Speakers \(Realtek HD Audio\)/));
+ )) as HTMLSelectElement;
+ fireEvent.change(output, {
+ target: { value: "Speakers (Realtek HD Audio)" },
+ });
await waitFor(() => {
const putCall = fetchMock.mock.calls.find(
@@ -125,8 +129,10 @@ describe("AudioDevicesGroup", () => {
render(<AudioDevicesGroup />);
await waitFor(() => {
- const output = screen.getByTestId("audio-output-select");
- expect(output.getAttribute("data-value")).toBe("Jabra Evolve2 65");
+ const output = screen.getByTestId(
+ "audio-output-select",
+ ) as HTMLSelectElement;
+ expect(output.value).toBe("Jabra Evolve2 65");
});
});
diff --git a/jarvis/ui/web/frontend/src/views/settings/AudioDevicesGroup.tsx b/jarvis/ui/web/frontend/src/views/settings/AudioDevicesGroup.tsx
index 6e9ba2d016..043c328840 100644
--- a/jarvis/ui/web/frontend/src/views/settings/AudioDevicesGroup.tsx
+++ b/jarvis/ui/web/frontend/src/views/settings/AudioDevicesGroup.tsx
@@ -6,7 +6,6 @@ import {
} from "@/hooks/useAudioDevices";
import { useEventStore } from "@/store/events";
import { useT } from "@/i18n";
-import { BrandedSelect } from "@/components/ui/select";
/**
* "Audio devices" card inside the Settings view: one dropdown for the OUTPUT
@@ -150,24 +149,21 @@ function DevicePicker({
{icon}
{label}
</label>
- <BrandedSelect
- testId={testId}
+ <select
+ data-testid={testId}
value={selected}
- onValueChange={onSelect}
- ariaLabel={label}
+ onChange={(e) => onSelect(e.target.value)}
disabled={disabled}
- className="mt-1"
- options={[
- { value: autoValue, label: autoLabel },
- ...devices.map((device) => ({
- value: device.name,
- label: device.is_default
- ? `${device.name} ${defaultSuffix}`
- : device.name,
- })),
- ...(showOrphan ? [{ value: selected, label: selected }] : []),
- ]}
- />
+ className="mt-1 w-full rounded-md border border-input bg-background px-3 py-2 text-sm focus:outline-none focus:ring-1 focus:ring-primary disabled:opacity-50"
+ >
+ <option value={autoValue}>{autoLabel}</option>
+ {devices.map((d) => (
+ <option key={d.name} value={d.name}>
+ {d.is_default ? `${d.name} ${defaultSuffix}` : d.name}
+ </option>
+ ))}
+ {showOrphan && <option value={selected}>{selected}</option>}
+ </select>
</>
);
}
diff --git a/jarvis/ui/web/frontend/src/views/settings/WikiProviderCard.test.tsx b/jarvis/ui/web/frontend/src/views/settings/WikiProviderCard.test.tsx
index 96badeb924..0f4f29fd58 100644
--- a/jarvis/ui/web/frontend/src/views/settings/WikiProviderCard.test.tsx
+++ b/jarvis/ui/web/frontend/src/views/settings/WikiProviderCard.test.tsx
@@ -155,9 +155,7 @@ describe("WikiProviderCard", () => {
stubFetch();
render(<WikiProviderCard />);
- fireEvent.click(
- await screen.findByLabelText("wiki_provider.provider_label"),
- );
+ await screen.findByLabelText("wiki_provider.provider_label");
expect(
screen.getByText("codex — wiki_provider.option_agent_suffix"),
).toBeDefined();
@@ -180,16 +178,12 @@ describe("WikiProviderCard", () => {
const fetchMock = stubFetch();
render(<WikiProviderCard />);
- const providerSelect = await screen.findByLabelText(
+ const providerSelect = (await screen.findByLabelText(
"wiki_provider.provider_label",
- );
+ )) as HTMLSelectElement;
// Picking codex mounts the shared model picker fed by codex's catalog.
- fireEvent.click(providerSelect);
- const codexOption = (await screen.findAllByRole("option")).find(
- (option) => option.getAttribute("data-value") === "codex",
- );
- fireEvent.click(codexOption!);
+ fireEvent.change(providerSelect, { target: { value: "codex" } });
const trigger = await screen.findByLabelText("apikeys_model.model_label");
fireEvent.click(trigger);
@@ -212,15 +206,11 @@ describe("WikiProviderCard", () => {
const fetchMock = stubFetch();
render(<WikiProviderCard />);
- const providerSelect = await screen.findByLabelText(
+ const providerSelect = (await screen.findByLabelText(
"wiki_provider.provider_label",
- );
+ )) as HTMLSelectElement;
- fireEvent.click(providerSelect);
- const geminiOption = (await screen.findAllByRole("option")).find(
- (option) => option.getAttribute("data-value") === "gemini",
- );
- fireEvent.click(geminiOption!);
+ fireEvent.change(providerSelect, { target: { value: "gemini" } });
fireEvent.click(screen.getByRole("button", { name: "wiki_provider.apply" }));
await waitFor(() => {
diff --git a/jarvis/ui/web/frontend/src/views/settings/WikiProviderCard.tsx b/jarvis/ui/web/frontend/src/views/settings/WikiProviderCard.tsx
index 57a53940f4..c39bccb468 100644
--- a/jarvis/ui/web/frontend/src/views/settings/WikiProviderCard.tsx
+++ b/jarvis/ui/web/frontend/src/views/settings/WikiProviderCard.tsx
@@ -1,7 +1,6 @@
import { useState } from "react";
import { BookOpen, ChevronDown, Info, Loader2 } from "lucide-react";
import { Button } from "@/components/ui/button";
-import { BrandedSelect } from "@/components/ui/select";
import { cn } from "@/lib/utils";
import { BrainModelSelector } from "@/components/BrainModelSelector";
import type { BrainModelSaveResult } from "@/hooks/useProviders";
@@ -20,7 +19,7 @@ const FOLLOW_PRIMARY = "";
* dedicated Wiki-curator provider + (optional) model via
* `GET/PUT /api/settings/wiki-provider`.
*
- * The provider picker is fed by the endpoint's `available` matrix (agent
+ * The provider `<select>` is fed by the endpoint's `available` matrix (agent
* providers such as Codex are labelled, keyless ones flagged). The model pick
* uses the shared searchable {@link BrainModelSelector} against the chosen
* provider's live catalog (`GET /api/providers/{id}/models`) — the same picker
@@ -154,24 +153,21 @@ export function WikiProviderCard() {
<div className="grid gap-4 sm:grid-cols-2">
<SettingsField label={t("wiki_provider.provider_label")}>
- <BrandedSelect
- ariaLabel={t("wiki_provider.provider_label")}
+ <select
+ aria-label={t("wiki_provider.provider_label")}
value={providerValue}
- onValueChange={handleProviderChange}
+ onChange={(e) => handleProviderChange(e.target.value)}
className={settingsInputCls}
- options={[
- {
- value: FOLLOW_PRIMARY,
- label: t("wiki_provider.follow_primary"),
- },
- ...data.available
- .filter((item) => item.provider !== FOLLOW_PRIMARY)
- .map((item) => ({
- value: item.provider,
- label: providerOptionLabel(item),
- })),
- ]}
- />
+ >
+ <option value={FOLLOW_PRIMARY}>{t("wiki_provider.follow_primary")}</option>
+ {data.available
+ .filter((p) => p.provider !== FOLLOW_PRIMARY)
+ .map((p) => (
+ <option key={p.provider} value={p.provider}>
+ {providerOptionLabel(p)}
+ </option>
+ ))}
+ </select>
</SettingsField>
{providerValue === FOLLOW_PRIMARY ? (
diff --git a/jarvis/ui/web/marketplace_routes.py b/jarvis/ui/web/marketplace_routes.py
index 8da7da0ba1..96b2eb4d1b 100644
--- a/jarvis/ui/web/marketplace_routes.py
+++ b/jarvis/ui/web/marketplace_routes.py
@@ -12,6 +12,7 @@ from __future__ import annotations
import asyncio
import logging
+from dataclasses import dataclass
from pathlib import Path
from typing import Any
@@ -99,30 +100,51 @@ def _live_plugin_registry() -> Any:
# ----------------------------------------------------------------------
-def _plugin_status_meta(
- plugin_id: str, store: TokenStore
-) -> tuple[str, str | None, str | None]:
- """Return ``(status, expires_at_iso, last_refreshed_iso)`` from ONE token load.
+@dataclass(frozen=True, slots=True)
+class _PluginStatusMeta:
+ """Everything the plugins view needs about one grant, from ONE token load."""
+
+ status: str
+ expires_at: str | None = None
+ last_refreshed: str | None = None
+ # Why the connection is flagged, and since when. Both stay ``None`` on a
+ # healthy grant and on one flagged before these fields existed — the view
+ # then says "unknown" rather than inventing a cause.
+ reauth_reason: str | None = None
+ reauth_at: str | None = None
+
+
+def _plugin_status_meta(plugin_id: str, store: TokenStore) -> _PluginStatusMeta:
+ """Return the plugin's stored auth state from ONE token load.
``expires_at`` / ``last_refreshed`` are surfaced so the UI can show an honest
"auto-refreshing / expiring soon" hint without re-deriving it. Both are
``None`` for a token that carries no expiry (e.g. a PAT) or was never
refreshed — never a fabricated timestamp.
+
+ ``reauth_reason`` is one of the ``REAUTH_*`` codes and is the ONLY failure
+ detail that leaves this layer: a provider's raw error body can echo a token
+ back, so it is never stored and never served.
"""
try:
tokens = store.load(plugin_id)
except RuntimeError:
- return "error", None, None
+ return _PluginStatusMeta("error")
if tokens is None:
- return "not_connected", None, None
- expires_at = tokens.expires_at.isoformat() if tokens.expires_at else None
- last_refreshed = tokens.extra.get("last_refreshed") or None
- status = "needs_reauth" if tokens.needs_reauth else "connected"
- return status, expires_at, last_refreshed
+ return _PluginStatusMeta("not_connected")
+ return _PluginStatusMeta(
+ status="needs_reauth" if tokens.needs_reauth else "connected",
+ expires_at=tokens.expires_at.isoformat() if tokens.expires_at else None,
+ last_refreshed=tokens.extra.get("last_refreshed") or None,
+ reauth_reason=tokens.reauth_reason if tokens.needs_reauth else None,
+ reauth_at=(
+ tokens.reauth_at.isoformat() if tokens.needs_reauth and tokens.reauth_at else None
+ ),
+ )
def _plugin_status(plugin_id: str, store: TokenStore) -> str:
- return _plugin_status_meta(plugin_id, store)[0]
+ return _plugin_status_meta(plugin_id, store).status
def _build_dcr_handler(plugin_id: str, auth: HostedMcpOAuthDcrAuth) -> HostedMcpDcrHandler:
@@ -207,11 +229,7 @@ def _mcp_live(
if transport == "http":
if status == "connected":
reg = _live_plugin_registry() # the same accessor refresh uses
- if (
- reg is not None
- and reg.is_bootstrapped()
- and reg.live_tool_count(plugin_id) == 0
- ):
+ if reg is not None and reg.is_bootstrapped() and reg.live_tool_count(plugin_id) == 0:
hint = reg.last_connect_error(plugin_id) or "no tools loaded — reconnect"
return False, hint
return True, None
@@ -240,10 +258,28 @@ async def list_plugins(response: Response) -> dict[str, Any]:
connected = 0
for spec in catalog.plugins:
item = spec.model_dump(mode="json")
- status, expires_at, last_refreshed = _plugin_status_meta(spec.id, store)
+ meta = _plugin_status_meta(spec.id, store)
+ status = meta.status
item["status"] = status
- item["expires_at"] = expires_at
- item["last_refreshed"] = last_refreshed
+ item["expires_at"] = meta.expires_at
+ item["last_refreshed"] = meta.last_refreshed
+ item["reauth_reason"] = meta.reauth_reason
+ item["reauth_at"] = meta.reauth_at
+ if isinstance(spec.auth, OAuthPkceLoopbackAuth):
+ from jarvis.marketplace.connect_helpers import (
+ is_placeholder_client_id,
+ resolve_pkce_client,
+ )
+
+ effective_client_id, _ = resolve_pkce_client(
+ spec.id, spec.auth.client_id, spec.auth.client_secret
+ )
+ # Configuration state is safe to expose; the client id and secret
+ # themselves never leave the backend. The dialog uses this to stop
+ # placeholder-only installs before they launch a doomed OAuth tab.
+ item["oauth_client_configured"] = not is_placeholder_client_id(
+ effective_client_id
+ )
mcp = spec.mcp_server or {}
mcp_live, runtime_missing = _mcp_live(mcp, plugin_id=spec.id, status=status)
if runtime_missing:
@@ -523,7 +559,15 @@ async def connect_start(plugin_id: str, background: BackgroundTasks) -> dict[str
result = await handler.await_completion(session)
except Exception as exc: # noqa: BLE001
log.warning("plugin %s connect/await failed: %s", plugin_id, exc)
- slot.result = FlowResult(tokens=None, error=str(exc))
+ if registry.get(session.flow_id) is slot:
+ slot.result = FlowResult(tokens=None, error=str(exc))
+ return
+ # Closing the browser-login dialog is a real cancellation, not
+ # merely a UI hide. Never let a late provider callback replace the
+ # existing grant (especially a needs_reauth grant) after the user
+ # cancelled the reconnect.
+ if registry.get(session.flow_id) is not slot:
+ log.info("plugin %s connect flow cancelled", plugin_id)
return
if result.tokens is not None:
# Persist BEFORE publishing the result: connect_poll reads
@@ -557,6 +601,17 @@ async def connect_start(plugin_id: str, background: BackgroundTasks) -> dict[str
}
[email protected]("/plugins/{plugin_id}/connect/{flow_id}")
+async def cancel_connect(plugin_id: str, flow_id: str) -> dict[str, str]:
+ """Cancel a pending OAuth flow without touching the stored grant."""
+ registry = get_registry()
+ slot = registry.get(flow_id)
+ if slot is not None and slot.session.plugin_id != plugin_id:
+ raise HTTPException(status_code=404, detail="unknown flow_id for plugin")
+ registry.drop(flow_id)
+ return {"state": "cancelled", "flow_id": flow_id, "plugin_id": plugin_id}
+
+
@router.get("/plugins/{plugin_id}/connect/poll/{flow_id}")
async def connect_poll(plugin_id: str, flow_id: str) -> dict[str, Any]:
"""Returns `{state: "pending"|"connected"|"error", ...}`."""
diff --git a/tests/unit/marketplace/test_reauth_self_heal.py b/tests/unit/marketplace/test_reauth_self_heal.py
new file mode 100644
index 0000000000..250183306d
--- /dev/null
+++ b/tests/unit/marketplace/test_reauth_self_heal.py
@@ -0,0 +1,326 @@
+"""Reconnect reasons, and the daily self-heal probe that undoes a wrong flag.
+
+Two failures motivated this: a connection could die and never say WHY (the
+reason lived only in a rotating log), and once flagged it was never retried, so
+a provider outage misread as a hard rejection stranded a perfectly good grant
+until the user noticed by hand.
+"""
+
+from __future__ import annotations
+
+from dataclasses import replace
+from datetime import UTC, datetime, timedelta
+
+import pytest
+
+from jarvis.marketplace.refresh_scheduler import (
+ FAILED,
+ REFRESHED,
+ REVOKED,
+ SKIPPED,
+ refresh_plugin_token,
+)
+from jarvis.marketplace.token_store import (
+ REAUTH_CLIENT_MISSING,
+ REAUTH_CLIENT_REJECTED,
+ REAUTH_PROVIDER_REJECTED,
+ REAUTH_ROTATION_LOST,
+ InMemoryBackend,
+ Tokens,
+ TokenStore,
+)
+
+DAY = 86_400
+
+
+def _store() -> TokenStore:
+ return TokenStore(InMemoryBackend())
+
+
+def _expired(refresh: str | None = "r0") -> Tokens:
+ return Tokens(
+ access="a0",
+ refresh=refresh,
+ expires_at=datetime.now(UTC) - timedelta(hours=1),
+ )
+
+
+class _Handler:
+ """Minimal AuthHandler: either returns fresh tokens or raises."""
+
+ def __init__(self, new_tokens: Tokens | None = None, raise_exc: Exception | None = None):
+ self._new = new_tokens
+ self._raise = raise_exc
+ self.calls = 0
+
+ async def refresh(self, current: Tokens) -> Tokens:
+ self.calls += 1
+ if self._raise is not None:
+ raise self._raise
+ assert self._new is not None
+ return self._new
+
+ async def start(self, plugin_spec): # noqa: ANN001, ANN201 (protocol stub)
+ raise NotImplementedError
+
+ async def await_completion(self, session): # noqa: ANN001, ANN201
+ raise NotImplementedError
+
+ def auth_header(self, tokens: Tokens) -> dict[str, str]:
+ return {"Authorization": f"Bearer {tokens.access}"}
+
+
+# ---------------------------------------------------------------------------
+# The reason is recorded, and it is the right one
+# ---------------------------------------------------------------------------
+
+
+ ("error", "expected"),
+ [
+ ("refresh HTTP 400: invalid_grant", REAUTH_PROVIDER_REJECTED),
+ ("revoked", REAUTH_PROVIDER_REJECTED),
+ ("token has been expired or revoked", REAUTH_PROVIDER_REJECTED),
+ ("refresh HTTP 401: invalid_client", REAUTH_CLIENT_REJECTED),
+ ("unauthorized_client", REAUTH_CLIENT_REJECTED),
+ ("client was not found", REAUTH_CLIENT_REJECTED),
+ # The DCR handler's message matches TWO markers; the specific one wins.
+ (
+ "refresh: no stored client_id — reconnect required to heal this connection",
+ REAUTH_CLIENT_MISSING,
+ ),
+ ],
+)
+async def test_records_the_reason_it_was_flagged(error: str, expected: str) -> None:
+ store = _store()
+ store.save("p", _expired())
+ handler = _Handler(raise_exc=RuntimeError(error))
+
+ attempt = await refresh_plugin_token("p", store, lambda pid: handler)
+
+ assert attempt.outcome == REVOKED
+ saved = store.load("p")
+ assert saved is not None
+ assert saved.needs_reauth is True
+ assert saved.reauth_reason == expected
+ assert saved.reauth_at is not None
+
+
+async def test_transient_failure_records_no_reason_and_stays_connected() -> None:
+ """A DNS blip must not look like a revocation — it is retried, not flagged."""
+ store = _store()
+ store.save("p", _expired())
+ handler = _Handler(raise_exc=RuntimeError("[Errno 11001] getaddrinfo failed"))
+
+ attempt = await refresh_plugin_token("p", store, lambda pid: handler)
+
+ assert attempt.outcome == FAILED
+ saved = store.load("p")
+ assert saved is not None
+ assert saved.needs_reauth is False
+ assert saved.reauth_reason is None
+
+
+async def test_reauth_at_survives_repeated_failures() -> None:
+ """The timestamp means "when it died", not "when we last checked"."""
+ store = _store()
+ died = datetime.now(UTC) - timedelta(days=9)
+ store.save(
+ "p",
+ replace(
+ _expired(),
+ needs_reauth=True,
+ reauth_reason=REAUTH_PROVIDER_REJECTED,
+ reauth_at=died,
+ reauth_retry_at=died,
+ ),
+ )
+ handler = _Handler(raise_exc=RuntimeError("invalid_grant"))
+
+ await refresh_plugin_token("p", store, lambda pid: handler, reauth_retry_seconds=DAY)
+
+ saved = store.load("p")
+ assert saved is not None
+ assert saved.reauth_at == died
+ # ...while the retry stamp moved forward, putting the next probe a day out.
+ assert saved.reauth_retry_at is not None
+ assert saved.reauth_retry_at > died
+
+
+# ---------------------------------------------------------------------------
+# The self-heal probe
+# ---------------------------------------------------------------------------
+
+
+async def test_flagged_connection_is_not_probed_before_the_interval() -> None:
+ store = _store()
+ store.save(
+ "p",
+ replace(
+ _expired(),
+ needs_reauth=True,
+ reauth_reason=REAUTH_PROVIDER_REJECTED,
+ reauth_at=datetime.now(UTC) - timedelta(days=3),
+ reauth_retry_at=datetime.now(UTC) - timedelta(hours=2),
+ ),
+ )
+ handler = _Handler(new_tokens=Tokens(access="a1", refresh="r1"))
+
+ attempt = await refresh_plugin_token("p", store, lambda pid: handler, reauth_retry_seconds=DAY)
+
+ assert attempt.outcome == SKIPPED
+ assert handler.calls == 0
+
+
+async def test_flagged_connection_heals_itself_once_the_interval_passes() -> None:
+ """The whole point: a wrongly-flagged grant comes back without the user."""
+ store = _store()
+ store.save(
+ "p",
+ replace(
+ _expired(),
+ needs_reauth=True,
+ reauth_reason=REAUTH_CLIENT_REJECTED,
+ reauth_at=datetime.now(UTC) - timedelta(days=10),
+ reauth_retry_at=datetime.now(UTC) - timedelta(days=2),
+ ),
+ )
+ handler = _Handler(new_tokens=Tokens(access="a1", refresh="r1"))
+
+ attempt = await refresh_plugin_token("p", store, lambda pid: handler, reauth_retry_seconds=DAY)
+
+ assert attempt.outcome == REFRESHED
+ assert handler.calls == 1
+ saved = store.load("p")
+ assert saved is not None
+ assert saved.access == "a1"
+ # The entire reconnect story is cleared, not just the flag — a leftover
+ # reason would keep explaining a failure that no longer exists.
+ assert saved.needs_reauth is False
+ assert saved.reauth_reason is None
+ assert saved.reauth_at is None
+ assert saved.reauth_retry_at is None
+
+
+async def test_rotation_lost_is_never_probed_again() -> None:
+ """Replaying a retired token can cost the whole account. Never retry it."""
+ store = _store()
+ store.save(
+ "p",
+ replace(
+ _expired(),
+ needs_reauth=True,
+ reauth_reason=REAUTH_ROTATION_LOST,
+ reauth_at=datetime.now(UTC) - timedelta(days=400),
+ reauth_retry_at=None,
+ ),
+ )
+ handler = _Handler(new_tokens=Tokens(access="a1", refresh="r1"))
+
+ attempt = await refresh_plugin_token("p", store, lambda pid: handler, reauth_retry_seconds=DAY)
+
+ assert attempt.outcome == SKIPPED
+ assert handler.calls == 0
+
+
+async def test_self_heal_is_opt_in() -> None:
+ """Without the interval a flagged plugin behaves exactly as it used to."""
+ store = _store()
+ store.save("p", replace(_expired(), needs_reauth=True))
+ handler = _Handler(new_tokens=Tokens(access="a1", refresh="r1"))
+
+ attempt = await refresh_plugin_token("p", store, lambda pid: handler)
+
+ assert attempt.outcome == SKIPPED
+ assert handler.calls == 0
+
+
+async def test_probe_is_stamped_before_the_provider_call() -> None:
+ """A hung or crashing provider call must not re-probe every five minutes."""
+ store = _store()
+ store.save(
+ "p",
+ replace(
+ _expired(),
+ needs_reauth=True,
+ reauth_reason=REAUTH_PROVIDER_REJECTED,
+ reauth_at=datetime.now(UTC) - timedelta(days=5),
+ ),
+ )
+ stamps: list[datetime | None] = []
+
+ class _Recording(_Handler):
+ async def refresh(self, current: Tokens) -> Tokens:
+ # What is on disk at the moment the provider is called.
+ saved = store.load("p")
+ stamps.append(saved.reauth_retry_at if saved else None)
+ raise RuntimeError("boom")
+
+ await refresh_plugin_token("p", store, lambda pid: _Recording(), reauth_retry_seconds=DAY)
+
+ assert stamps and stamps[0] is not None, "retry stamp must be persisted before the call"
+
+
+async def test_flagged_token_without_refresh_is_never_probed() -> None:
+ store = _store()
+ store.save("p", replace(_expired(refresh=None), needs_reauth=True))
+ handler = _Handler(new_tokens=Tokens(access="a1"))
+
+ attempt = await refresh_plugin_token("p", store, lambda pid: handler, reauth_retry_seconds=DAY)
+
+ assert attempt.outcome == SKIPPED
+ assert handler.calls == 0
+
+
+async def test_legacy_flag_without_timestamps_is_probed_once() -> None:
+ """Gmail/Drive/Linear were flagged before these fields existed."""
+ store = _store()
+ store.save("p", replace(_expired(), needs_reauth=True))
+ handler = _Handler(new_tokens=Tokens(access="a1", refresh="r1"))
+
+ attempt = await refresh_plugin_token("p", store, lambda pid: handler, reauth_retry_seconds=DAY)
+
+ assert attempt.outcome == REFRESHED
+ assert handler.calls == 1
+
+
+# ---------------------------------------------------------------------------
+# Storage round-trip
+# ---------------------------------------------------------------------------
+
+
+def test_reason_survives_a_storage_round_trip() -> None:
+ flagged_at = datetime.now(UTC) - timedelta(days=2)
+ tokens = Tokens(
+ access="a",
+ refresh="r",
+ needs_reauth=True,
+ reauth_reason=REAUTH_PROVIDER_REJECTED,
+ reauth_at=flagged_at,
+ reauth_retry_at=flagged_at,
+ )
+
+ restored = Tokens.from_json(tokens.to_json())
+
+ assert restored == tokens
+
+
+def test_a_token_written_before_these_fields_still_loads() -> None:
+ legacy = '{"access":"a","refresh":"r","expires_at":null,"extra":{},"needs_reauth":true}'
+
+ restored = Tokens.from_json(legacy)
+
+ assert restored.needs_reauth is True
+ assert restored.reauth_reason is None
+ assert restored.reauth_at is None
+ assert restored.reauth_retry_at is None