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.

fix(agents): harden Grok Build logout, voice alias, and ready-state

Haraldf888ceb78b88
diff --git a/jarvis/brain/manager.py b/jarvis/brain/manager.py
index fbb6ba1f02..29863d3b35 100644
--- a/jarvis/brain/manager.py
+++ b/jarvis/brain/manager.py
@@ -2103,6 +2103,7 @@ _SUBAGENT_VOICE_TO_CANONICAL: dict[str, str] = {
"nvidia": "nvidia", "nim": "nvidia", "nemotron": "nvidia",
"antigravity": "antigravity",
"grok-build": "grok-build",
+ "grok build": "grok-build",
"grokbuild": "grok-build",
"grok-cli": "grok-build",
}
diff --git a/jarvis/brain/voice_command_gate.py b/jarvis/brain/voice_command_gate.py
index 02175b03ed..48bf693915 100644
--- a/jarvis/brain/voice_command_gate.py
+++ b/jarvis/brain/voice_command_gate.py
@@ -198,9 +198,9 @@ _SUBAGENT_QUALIFIER = re.compile(
)
# Longer variants first so "openai-codex" wins over "openai".
_SUBAGENT_PROVIDER_WORDS = (
- "openai-codex", "openrouter", "antigravity", "grok-build", "grokbuild",
- "grok-cli", "chatgpt", "anthropic", "claude", "gemini", "openai", "grok",
- "codex", "gpt",
+ "openai-codex", "openrouter", "antigravity", "grok-build", "grok build",
+ "grokbuild", "grok-cli", "chatgpt", "anthropic", "claude", "gemini",
+ "openai", "grok", "codex", "gpt",
)
_SUBAGENT_SWITCH_VERB = re.compile(
r"\b(?:wechsel[n]?|wechsle|umstell\w*|umschalt\w*|stell\w*|set|switch|change|nimm|mach)\b",
diff --git a/jarvis/grok_build_auth.py b/jarvis/grok_build_auth.py
index 3a12f6e986..48d0ec9e6a 100644
--- a/jarvis/grok_build_auth.py
+++ b/jarvis/grok_build_auth.py
@@ -27,6 +27,7 @@ import shutil
import subprocess
import sys
import threading
+from contextlib import suppress
from dataclasses import dataclass
from pathlib import Path
from typing import Any
@@ -98,9 +99,11 @@ def _read_json(path: Path) -> dict[str, Any] | None:
def _derive_auth(auth: dict[str, Any] | None) -> tuple[bool, str]:
"""Return ``(connected, mode)`` from a parsed ``auth.json`` dict.
- Tolerant by design: Grok Build's on-disk shape may evolve; any recognised
- subscription token or account identity is ``subscription``, a stored API
- key field is ``api_key``, and anything else degrades to disconnected.
+ Tolerant by design: Grok Build's on-disk shape may evolve; a recognised
+ subscription token is ``subscription``, a stored API key field is
+ ``api_key``, and anything else degrades to disconnected. Account identity
+ (email / user id) is display-only — leftover profile JSON after ``grok
+ logout`` must not paint the card Ready.
"""
if not isinstance(auth, dict):
return False, "unknown"
@@ -120,14 +123,6 @@ def _derive_auth(auth: dict[str, Any] | None) -> tuple[bool, str]:
value = auth.get(key)
if isinstance(value, str) and value.strip():
return True, "subscription"
- user = auth.get("user") if isinstance(auth.get("user"), dict) else None
- account = auth.get("account") if isinstance(auth.get("account"), dict) else None
- identity = user or account
- if isinstance(identity, dict) and any(
- isinstance(identity.get(k), str) and identity.get(k).strip()
- for k in ("email", "user_id", "id", "username")
- ):
- return True, "subscription"
for key in ("XAI_API_KEY", "xai_api_key", "api_key"):
value = auth.get(key)
if isinstance(value, str) and value.strip():
@@ -192,6 +187,13 @@ def _latest_login_mtime(home: Path) -> float | None:
return None
+def _wipe_isolated_login(dest: Path) -> None:
+ """Drop stale auth copies so a logout is visible under the redirected home."""
+ for name in (*_LOGIN_FILES, _ISO_HOME_MARKER):
+ with suppress(OSError):
+ (dest / name).unlink(missing_ok=True)
+
+
def prepare_worker_home(
*, src_home: Path | None = None, dest_root: Path | None = None
) -> Path | None:
@@ -199,11 +201,15 @@ def prepare_worker_home(
Returns the isolated home path, or ``None`` when there is no login to copy.
User hooks, plugins and interactive sessions stay in the real ``~/.grok``.
+ A missing source login wipes any leftover copy so Disconnect cannot leave
+ a live SuperGrok token under ``DATA_DIR``.
"""
src = src_home if src_home is not None else grok_home()
dest = dest_root if dest_root is not None else iso_home_root()
mtime = _latest_login_mtime(src)
if mtime is None:
+ with _ISO_HOME_LOCK:
+ _wipe_isolated_login(dest)
return None
with _ISO_HOME_LOCK:
dest.mkdir(parents=True, exist_ok=True)
@@ -384,14 +390,17 @@ class GrokBuildAuthService:
except (OSError, subprocess.SubprocessError) as exc:
log.debug("grok logout spawn failed, falling back to file unlink: %s", exc)
else:
- if proc.returncode == 0:
- return True, None
- log.debug(
- "grok logout exited %s; falling back to auth.json unlink",
- proc.returncode,
- )
+ if proc.returncode != 0:
+ log.debug(
+ "grok logout exited %s; falling back to auth.json unlink",
+ proc.returncode,
+ )
try:
(self._home_dir() / "auth.json").unlink(missing_ok=True)
- return True, None
except OSError as exc:
return False, str(exc)
+ try:
+ prepare_worker_home(src_home=self._home_dir())
+ except Exception as exc: # noqa: BLE001 — wipe is best-effort after logout
+ log.debug("Grok Build isolated-home wipe after logout failed: %s", exc)
+ return True, None
diff --git a/jarvis/missions/workers/grok_build_direct_worker.py b/jarvis/missions/workers/grok_build_direct_worker.py
index 8a1ed4fcba..abe88e0eea 100644
--- a/jarvis/missions/workers/grok_build_direct_worker.py
+++ b/jarvis/missions/workers/grok_build_direct_worker.py
@@ -217,7 +217,18 @@ def _event_looks_like_tool(obj: dict[str, Any]) -> str | None:
class GrokBuildDirectWorker:
- """Heavy worker that calls ``grok -p`` over the SuperGrok subscription."""
+ """Heavy worker that calls ``grok -p`` over the SuperGrok subscription.
+
+ ``cli`` is declared ``"codex"`` so the Phase-6 telemetry schema needs no
+ migration (same reason as GoogleCliWorker). The synthetic init event's
+ ``model`` field carries ``grok-build/<model>`` so debugging stays unambiguous.
+
+ Broker grant: issued and closed for a truthful capability report. Grok
+ Build's isolated worker home deliberately does not ingest user hooks or
+ plugins; the official CLI has no documented equivalent of Codex's
+ ``-c mcp_servers.*`` injection, so marketplace MCP is an honest
+ degradation (reported unavailable unless a future grok MCP write lands).
+ """
cli: ClassVar[Literal["claude", "codex", "python", "browser"]] = "codex"
@@ -253,7 +264,55 @@ class GrokBuildDirectWorker:
**_unused: Any,
) -> AsyncIterator[Any]:
del allowed_tools, permission_mode, max_turns, allow_backend_fallback
- del mission_id, _broker_binding
+ broker_binding = _broker_binding
+ issued_here = broker_binding is None
+ if issued_here:
+ broker_binding = self.capability_inventory.bind_broker(
+ ttl_s=timeout_s + _HARDCAP_GRACE_S + 60.0,
+ mission_id=mission_id or None,
+ worker_id=worker_id,
+ )
+ try:
+ async for event in self._spawn_bound(
+ prompt,
+ worktree=worktree,
+ env=env,
+ job=job,
+ worker_id=worker_id,
+ log_dir=log_dir,
+ model=model,
+ resume_session_id=resume_session_id,
+ extra_args=extra_args,
+ timeout_s=timeout_s,
+ first_output_timeout_s=first_output_timeout_s,
+ broker_binding=broker_binding,
+ ):
+ yield event
+ finally:
+ if issued_here and broker_binding is not None:
+ try:
+ broker_binding.close()
+ except Exception: # noqa: BLE001 - cleanup must not mask cancellation
+ logger.exception(
+ "GrokBuildDirectWorker: broker binding cleanup failed"
+ )
+
+ async def _spawn_bound(
+ self,
+ prompt: str,
+ *,
+ worktree: Path,
+ env: dict[str, str],
+ job: Any,
+ worker_id: str,
+ log_dir: Path,
+ model: str = "",
+ resume_session_id: str | None = None,
+ extra_args: tuple[str, ...] = (),
+ timeout_s: float = _DEFAULT_TIMEOUT_S,
+ first_output_timeout_s: float = _DEFAULT_FIRST_OUTPUT_TIMEOUT_S,
+ broker_binding: Any | None = None,
+ ) -> AsyncIterator[Any]:
log_dir.mkdir(parents=True, exist_ok=True) # noqa: ASYNC240
stdout_log = log_dir / "stream.jsonl"
stderr_log = log_dir / "stderr.log"
@@ -270,7 +329,9 @@ class GrokBuildDirectWorker:
model=f"grok-build/{effective_model}",
tools=[],
cwd=str(worktree),
- external_capabilities=self.capability_inventory.report_for("grok-build"),
+ external_capabilities=self.capability_inventory.report_for(
+ "grok-build", binding=broker_binding
+ ),
)
if binary is None:
yield ClaudeResult(
@@ -290,6 +351,8 @@ class GrokBuildDirectWorker:
extra_args=extra_args,
)
env_for_grok = _build_grok_build_env(env)
+ if broker_binding is not None:
+ env_for_grok = broker_binding.apply_environment(env_for_grok)
logger.info(
"GrokBuildDirectWorker[%s] spawn: cwd=%s model=%s argv=%s",
worker_id,
diff --git a/jarvis/ui/web/frontend/src/components/JarvisAgentSection.tsx b/jarvis/ui/web/frontend/src/components/JarvisAgentSection.tsx
index bf8b619235..ef9bc0d8b1 100644
--- a/jarvis/ui/web/frontend/src/components/JarvisAgentSection.tsx
+++ b/jarvis/ui/web/frontend/src/components/JarvisAgentSection.tsx
@@ -130,8 +130,17 @@ const PROVIDER_LABELS: Record<string, string> = {
async function pollStatusUntilConnected(
statusUrl: string,
onTick: () => void | Promise<void>,
- { maxMs = 120_000, intervalMs = 2_500 }: { maxMs?: number; intervalMs?: number } = {},
+ {
+ maxMs = 120_000,
+ intervalMs = 2_500,
+ isReady,
+ }: {
+ maxMs?: number;
+ intervalMs?: number;
+ isReady?: (data: { connected?: boolean; mode?: string }) => boolean;
+ } = {},
): Promise<boolean> {
+ const ready = isReady ?? ((data) => Boolean(data?.connected));
const deadline = Date.now() + maxMs;
while (Date.now() < deadline) {
await new Promise((r) => setTimeout(r, intervalMs));
@@ -140,7 +149,7 @@ async function pollStatusUntilConnected(
const res = await fetch(statusUrl);
if (res.ok) {
const data = await res.json();
- if (data?.connected) return true;
+ if (ready(data)) return true;
}
} catch {
// transient (app restarting / network blip) — keep polling
@@ -1278,7 +1287,10 @@ function GrokBuildConnectionCard({
await loginGrokBuild();
pushToast("info", "Grok Build login started — finish it in the browser window");
await onChanged();
- void pollStatusUntilConnected("/api/grok-build/status", onChanged).then((ok) => {
+ void pollStatusUntilConnected("/api/grok-build/status", onChanged, {
+ isReady: (data) =>
+ Boolean(data?.connected && data?.mode === "subscription"),
+ }).then((ok) => {
if (ok) {
pushToast("success", `Grok Build connected — now selectable as a ${agentBrandNow()}`);
}
@@ -1315,7 +1327,7 @@ function GrokBuildConnectionCard({
warning={
!installed && (
<CardHint icon={Terminal}>
- Install Grok Build before connecting (irm https://x.ai/cli/install.ps1 | iex).
+ {status?.message || "Install Grok Build before connecting."}
</CardHint>
)
}
diff --git a/tests/unit/brain/voice_command_cases.py b/tests/unit/brain/voice_command_cases.py
index 1fbb435662..692c04a7f1 100644
--- a/tests/unit/brain/voice_command_cases.py
+++ b/tests/unit/brain/voice_command_cases.py
@@ -19,6 +19,8 @@ RECOGNITION_CASES: list[tuple[str, str, str]] = [
# subagent_switch
("stell den subagent provider auf gemini", "subagent_switch", "gemini"), # i18n-allow: fixture
("stell den subagent provider von antigravity auf codex um", "subagent_switch", "codex"), # i18n-allow: fixture
+ ("switch the sub-agent to grok build", "subagent_switch", "grok build"),
+ ("switch the sub-agent to grok", "subagent_switch", "grok"),
# language_switch
("stell auf Englisch um", "language_switch", "en"), # i18n-allow: fixture
("antworte auf deutsch und englisch", "language_switch", "de"), # i18n-allow: fixture
diff --git a/tests/unit/test_grok_build_auth.py b/tests/unit/test_grok_build_auth.py
index 467d17271e..1021f026db 100644
--- a/tests/unit/test_grok_build_auth.py
+++ b/tests/unit/test_grok_build_auth.py
@@ -35,6 +35,15 @@ def test_derive_auth_empty() -> None:
assert _derive_auth(None) == (False, "unknown")
+def test_derive_auth_identity_without_token_is_disconnected() -> None:
+ """Leftover profile JSON after logout must not paint Ready."""
+ assert _derive_auth({"user": {"email": "[email protected]"}}) == (False, "unknown")
+ assert _derive_auth({"account": {"id": "u1", "username": "ada"}}) == (
+ False,
+ "unknown",
+ )
+
+
def test_email_from_user_object() -> None:
assert _email_from_auth({"user": {"email": "[email protected]"}}) == "[email protected]"
@@ -92,6 +101,22 @@ def test_prepare_worker_home_copies_auth_not_hooks(tmp_path: Path) -> None:
assert "[cli]" in (dest / "config.toml").read_text(encoding="utf-8")
+def test_prepare_worker_home_wipes_stale_copy_after_logout(tmp_path: Path) -> None:
+ src = tmp_path / "src"
+ dest = tmp_path / "dest"
+ src.mkdir()
+ dest.mkdir()
+ (dest / "auth.json").write_text(
+ json.dumps({"tokens": {"access_token": "stale"}}),
+ encoding="utf-8",
+ )
+ (dest / ".jarvis_src_mtime").write_text("1.0", encoding="utf-8")
+ isolated = prepare_worker_home(src_home=src, dest_root=dest)
+ assert isolated is None
+ assert not (dest / "auth.json").exists()
+ assert not (dest / ".jarvis_src_mtime").exists()
+
+
def test_status_not_installed(monkeypatch, tmp_path: Path) -> None:
service = GrokBuildAuthService(binary_path="grok-missing-binary", grok_home_dir=tmp_path)
monkeypatch.setattr(service, "_resolve_binary", lambda: None)