Skip to content

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

feat(ui): onboarding + socials + settings polish, ws schema updates, cli_ctl refinements

Ruben Lütke2eec597ef007
diff --git a/jarvis/cli_ctl/__main__.py b/jarvis/cli_ctl/__main__.py
index b68fd351ba..5c374604b7 100644
--- a/jarvis/cli_ctl/__main__.py
+++ b/jarvis/cli_ctl/__main__.py
@@ -33,6 +33,7 @@ from jarvis.cli_ctl.commands import marketplace as marketplace_cmd
from jarvis.cli_ctl.commands import mcps as mcps_cmd
from jarvis.cli_ctl.commands import missions as missions_cmd
from jarvis.cli_ctl.commands import outputs as outputs_cmd
+from jarvis.cli_ctl.commands import permissions as permissions_cmd
from jarvis.cli_ctl.commands import sessions as sessions_cmd
from jarvis.cli_ctl.commands import skills as skills_cmd
from jarvis.cli_ctl.commands import socials as socials_cmd
@@ -112,6 +113,7 @@ app.add_typer(wiki_cmd.app, name="wiki")
app.add_typer(sessions_cmd.app, name="sessions")
app.add_typer(skills_cmd.app, name="skills")
app.add_typer(outputs_cmd.app, name="outputs")
+app.add_typer(permissions_cmd.app, name="permissions")
app.add_typer(board_cmd.app, name="board")
app.add_typer(workflows_cmd.app, name="workflows")
app.add_typer(conductor_cmd.app, name="conductor")
@@ -132,9 +134,15 @@ def _in_completion() -> bool:
return any(k.endswith("_COMPLETE") for k in os.environ)
-def _dynamic_runner(method, path, params, body):
+def _dynamic_runner(method, path, params, body, *, timeout_s=None):
with make_client() as client:
- return client.request(method, path, params=params, json=body)
+ return client.request(
+ method,
+ path,
+ params=params,
+ json=body,
+ timeout_s=timeout_s,
+ )
# Root options that consume the NEXT argv token as their value; skipped when
diff --git a/jarvis/cli_ctl/client.py b/jarvis/cli_ctl/client.py
index 0f26fbd153..a93fb89172 100644
--- a/jarvis/cli_ctl/client.py
+++ b/jarvis/cli_ctl/client.py
@@ -45,6 +45,7 @@ class JarvisClient:
)
self.base_url = base_url
self.has_auth = bool(control_key)
+ self._connect_timeout = min(connect_timeout, timeout)
def request(
self,
@@ -53,11 +54,17 @@ class JarvisClient:
*,
params: dict[str, Any] | None = None,
json: Any | None = None,
+ timeout_s: float | None = None,
) -> Any:
try:
- resp = self._client.request(
- method.upper(), path, params=params, json=json
- )
+ request_kwargs: dict[str, Any] = {"params": params, "json": json}
+ if timeout_s is not None:
+ bounded_timeout = max(0.1, float(timeout_s))
+ request_kwargs["timeout"] = httpx.Timeout(
+ bounded_timeout,
+ connect=min(self._connect_timeout, bounded_timeout),
+ )
+ resp = self._client.request(method.upper(), path, **request_kwargs)
except (httpx.ConnectError, httpx.ConnectTimeout) as exc:
# Deliberately terse: the CLI layers replace this with the
# cause-specific doctor.unreachable_message (running-but-booting /
diff --git a/jarvis/cli_ctl/config.py b/jarvis/cli_ctl/config.py
index c34132ccd4..8ed2cec1b2 100644
--- a/jarvis/cli_ctl/config.py
+++ b/jarvis/cli_ctl/config.py
@@ -2,8 +2,7 @@
A 'profile' is a (base_url, control_key) pair. Resolution is per-field:
base_url: JARVISCTL_BASE_URL -> config.json -> live session file -> default
- control_key: JARVISCTL_CONTROL_KEY -> config.json -> live session file ->
- jarvis.core.control_key
+ control_key: JARVISCTL_CONTROL_KEY -> config.json -> jarvis.core.control_key
The live session file (written by the running desktop app, see
``jarvis.cli_ctl.discovery``) gives zero-config discovery of a locally running
instance even on a non-default port. The local control_key fallback only helps
@@ -60,7 +59,6 @@ def resolve_profile() -> Profile:
resolved_key = (
os.environ.get("JARVISCTL_CONTROL_KEY")
or data.get("control_key")
- or (session.token if session else None)
or _local_control_key()
)
return Profile(base_url=base_url, control_key=resolved_key)
diff --git a/jarvis/cli_ctl/dynamic.py b/jarvis/cli_ctl/dynamic.py
index 5acb2a617c..9c1fb6b9bc 100644
--- a/jarvis/cli_ctl/dynamic.py
+++ b/jarvis/cli_ctl/dynamic.py
@@ -17,7 +17,7 @@ import click
_log = logging.getLogger(__name__)
-Runner = Callable[[str, str, dict[str, Any], Any], Any]
+Runner = Callable[..., Any]
_HTTP_METHODS = {"get", "post", "put", "patch", "delete"}
_CLICK_TYPE = {
@@ -94,6 +94,28 @@ def _build_command(
help="Print the request that would be sent and exit without sending.",
)
)
+ timeout_default: float | None = None
+ if "request_timeout" not in existing_kwargs:
+ declared_timeout = op.get("x-jarvis-timeout-seconds")
+ try:
+ timeout_default = (
+ max(0.1, float(declared_timeout))
+ if declared_timeout is not None
+ else None
+ )
+ except (TypeError, ValueError):
+ timeout_default = None
+ params.append(
+ click.Option(
+ ["--request-timeout"],
+ type=click.FloatRange(min=0.1),
+ default=timeout_default,
+ help=(
+ "HTTP read timeout in seconds; defaults to route metadata "
+ "or the normal client timeout."
+ ),
+ )
+ )
# Server-declared danger metadata (route `openapi_extra`): the authoritative
# signal for the safety gate. `None` (absent) falls back to the method+path
@@ -104,6 +126,7 @@ def _build_command(
def callback(**kwargs: Any) -> None:
assume_yes = bool(kwargs.pop("yes", False))
dry_run = bool(kwargs.pop("dry_run", False))
+ request_timeout = kwargs.pop("request_timeout", timeout_default)
body = None
raw = kwargs.pop("json_body", None)
if raw is not None:
@@ -132,7 +155,13 @@ def _build_command(
from jarvis.cli_ctl.client import ApiError
try:
- result = runner(method, url_path, query, body)
+ result = runner(
+ method,
+ url_path,
+ query,
+ body,
+ timeout_s=request_timeout,
+ )
except ApiError as exc:
# Same clean failure contract as the curated commands (invoke.run):
# no raw traceback; transport failures get the cause-specific
diff --git a/jarvis/cli_ctl/invoke.py b/jarvis/cli_ctl/invoke.py
index fd61fb7f1e..083df4f8df 100644
--- a/jarvis/cli_ctl/invoke.py
+++ b/jarvis/cli_ctl/invoke.py
@@ -8,6 +8,7 @@ the result honoring the global ``--json`` flag. Curated command modules call
"""
from __future__ import annotations
+from collections.abc import Callable
from typing import Any
import typer
@@ -25,6 +26,8 @@ def run(
assume_yes: bool = False,
dry_run: bool = False,
dangerous: bool | None = None,
+ before_request: Callable[[], None] | None = None,
+ request_timeout_s: float | None = None,
) -> None:
"""Resolve client, gate mutations, send the request, render the result.
@@ -32,6 +35,7 @@ def run(
provider switch is reversible → False; ``config set`` / a phone call →
True). When None, the method+path heuristic in ``safety.is_dangerous``
decides — which is what the generic dynamic ``api`` layer relies on.
+ ``before_request`` runs only after confirmation and never during a dry run.
"""
# Local import avoids a load-time cycle with __main__ (which imports the
# command modules that import this helper).
@@ -52,8 +56,16 @@ def run(
)
if not proceed:
return # dry run: preview already printed, nothing sent
+ if before_request is not None:
+ before_request()
try:
- out = client.request(method, path, params=params, json=body)
+ out = client.request(
+ method,
+ path,
+ params=params,
+ json=body,
+ timeout_s=request_timeout_s,
+ )
except ApiError as exc:
if exc.status_code is None:
# Transport failure: replace the terse core message with the
diff --git a/jarvis/cli_ctl/reserved.py b/jarvis/cli_ctl/reserved.py
index 4acf30657c..00bde377a4 100644
--- a/jarvis/cli_ctl/reserved.py
+++ b/jarvis/cli_ctl/reserved.py
@@ -33,6 +33,7 @@ RESERVED_CONTROL_NAMES: frozenset[str] = frozenset(
"sessions",
"skills",
"outputs",
+ "permissions",
"board",
"workflows",
"conductor",
diff --git a/jarvis/setup/onboarding_meta.py b/jarvis/setup/onboarding_meta.py
index a4885e74b2..7810c19dc2 100644
--- a/jarvis/setup/onboarding_meta.py
+++ b/jarvis/setup/onboarding_meta.py
@@ -22,6 +22,7 @@ CURRENT_TERMS_VERSION = "1.0"
ONBOARDING_STEPS: list[str] = [
"welcome",
"language",
+ "permissions",
"wake-word",
"api-keys",
"finish",
diff --git a/jarvis/setup/wizard.py b/jarvis/setup/wizard.py
index 76a4af6c63..dd55cae509 100644
--- a/jarvis/setup/wizard.py
+++ b/jarvis/setup/wizard.py
@@ -114,17 +114,14 @@ class SecretSpec:
SECRETS: list[SecretSpec] = [
- # Brain providers that SIMULTANEOUSLY enable the Jarvis-Agent worker harness.
- # The harness reads the standard provider ENV vars (see the AD-6 mapping in
- # docs/jarvis-agents-bridge.md §2). There is NO separate per-harness namespace
- # — the wizard maintains one key, the harness uses it on subprocess spawn.
- # Full mapping table: jarvis/missions/worker_runtime/provider_map.py.
+ # General provider credentials. Dedicated Realtime and Jarvis-Agent slots
+ # are declared below; these remain compatibility fallbacks for upgrades.
SecretSpec(
key="anthropic_api_key",
env_fallback="ANTHROPIC_API_KEY",
label="Anthropic API Key (Claude)",
help_url="https://console.anthropic.com/settings/keys",
- required_for="Brain (Claude via API key) + Jarvis-Agent harness (anthropic provider)",
+ required_for="Brain (Claude via API key)",
optional=True,
section="brain",
),
@@ -133,7 +130,7 @@ SECRETS: list[SecretSpec] = [
env_fallback="OPENROUTER_API_KEY",
label="OpenRouter API Key (universal gateway)",
help_url="https://openrouter.ai/keys",
- required_for="Brain (universal: access to all models via one key) + Jarvis-Agent harness (openrouter provider)",
+ required_for="Brain (universal: access to all models via one key)",
section="brain",
),
SecretSpec(
@@ -141,7 +138,7 @@ SECRETS: list[SecretSpec] = [
env_fallback="NVIDIA_API_KEY",
label="NVIDIA API Key (NIM — build.nvidia.com, nvapi-)",
help_url="https://build.nvidia.com/settings/api-keys",
- required_for="Brain (NVIDIA NIM: Nemotron/Llama/DeepSeek) + Jarvis-Agent worker (nvidia)",
+ required_for="Brain (NVIDIA NIM: Nemotron/Llama/DeepSeek)",
section="brain",
),
SecretSpec(
@@ -149,7 +146,7 @@ SECRETS: list[SecretSpec] = [
env_fallback="OPENAI_API_KEY",
label="OpenAI API Key",
help_url="https://platform.openai.com/api-keys",
- required_for="Brain (GPT), Whisper API (STT), TTS + Jarvis-Agent harness (openai provider)",
+ required_for="Brain (GPT), Whisper API (STT), and TTS",
section="brain",
),
SecretSpec(
@@ -165,7 +162,7 @@ SECRETS: list[SecretSpec] = [
env_fallback="GEMINI_API_KEY",
label="Google AI Studio / Gemini API Key",
help_url="https://aistudio.google.com/app/apikey",
- required_for="Brain (Gemini) + Jarvis-Agent harness (google provider)",
+ required_for="Brain (Gemini)",
section="brain",
),
SecretSpec(
@@ -173,9 +170,86 @@ SECRETS: list[SecretSpec] = [
env_fallback="GROK_API_KEY",
label="xAI Grok API Key",
help_url="https://console.x.ai/",
- required_for="Grok Brain, Realtime Voice, Jarvis-Agents, and xAI TTS",
+ required_for="Grok Brain and xAI TTS",
section="brain",
),
+ # Scoped Realtime credentials. They are app-only fields in the Realtime tab,
+ # not extra first-run questions. Generic credentials remain compatibility
+ # fallbacks for existing installations.
+ SecretSpec(
+ key="realtime_openai_api_key",
+ env_fallback="JARVIS_REALTIME_OPENAI_API_KEY",
+ label="OpenAI Realtime API Key",
+ help_url="https://platform.openai.com/api-keys",
+ required_for="Realtime Voice (OpenAI)",
+ prompt=False,
+ ),
+ SecretSpec(
+ key="realtime_gemini_api_key",
+ env_fallback="JARVIS_REALTIME_GEMINI_API_KEY",
+ label="Gemini Live API Key",
+ help_url="https://aistudio.google.com/app/apikey",
+ required_for="Realtime Voice (Gemini Live)",
+ prompt=False,
+ ),
+ SecretSpec(
+ key="realtime_grok_api_key",
+ env_fallback="JARVIS_REALTIME_GROK_API_KEY",
+ label="Grok Realtime API Key",
+ help_url="https://console.x.ai/",
+ required_for="Realtime Voice (Grok)",
+ prompt=False,
+ ),
+ # Scoped Jarvis-Agent credentials. These slots never become Brain or
+ # Realtime credentials; the old generic slots are fallback-only.
+ SecretSpec(
+ key="jarvis_agent_anthropic_api_key",
+ env_fallback="JARVIS_AGENT_ANTHROPIC_API_KEY",
+ label="Anthropic API Key for Jarvis-Agents",
+ help_url="https://console.anthropic.com/settings/keys",
+ required_for="Jarvis-Agents (Claude API)",
+ prompt=False,
+ ),
+ SecretSpec(
+ key="jarvis_agent_openai_api_key",
+ env_fallback="JARVIS_AGENT_OPENAI_API_KEY",
+ label="OpenAI API Key for Jarvis-Agents",
+ help_url="https://platform.openai.com/api-keys",
+ required_for="Jarvis-Agents (OpenAI)",
+ prompt=False,
+ ),
+ SecretSpec(
+ key="jarvis_agent_gemini_api_key",
+ env_fallback="JARVIS_AGENT_GEMINI_API_KEY",
+ label="Gemini API Key for Jarvis-Agents",
+ help_url="https://aistudio.google.com/app/apikey",
+ required_for="Jarvis-Agents (Gemini)",
+ prompt=False,
+ ),
+ SecretSpec(
+ key="jarvis_agent_openrouter_api_key",
+ env_fallback="JARVIS_AGENT_OPENROUTER_API_KEY",
+ label="OpenRouter API Key for Jarvis-Agents",
+ help_url="https://openrouter.ai/keys",
+ required_for="Jarvis-Agents (OpenRouter)",
+ prompt=False,
+ ),
+ SecretSpec(
+ key="jarvis_agent_grok_api_key",
+ env_fallback="JARVIS_AGENT_GROK_API_KEY",
+ label="Grok API Key for Jarvis-Agents",
+ help_url="https://console.x.ai/",
+ required_for="Jarvis-Agents (Grok)",
+ prompt=False,
+ ),
+ SecretSpec(
+ key="jarvis_agent_nvidia_api_key",
+ env_fallback="JARVIS_AGENT_NVIDIA_API_KEY",
+ label="NVIDIA API Key for Jarvis-Agents",
+ help_url="https://build.nvidia.com/settings/api-keys",
+ required_for="Jarvis-Agents (NVIDIA NIM)",
+ prompt=False,
+ ),
SecretSpec(
key="google_tts_credentials_path",
env_fallback="GOOGLE_APPLICATION_CREDENTIALS",
diff --git a/jarvis/ui/web/claude_routes.py b/jarvis/ui/web/claude_routes.py
index 6144a768ed..5d29fe6c5b 100644
--- a/jarvis/ui/web/claude_routes.py
+++ b/jarvis/ui/web/claude_routes.py
@@ -43,9 +43,9 @@ def _real_api_key_present() -> bool:
API key flips the service into ``api_key`` mode.
"""
try:
- from jarvis.core.config import get_secret
+ from jarvis.core.config import get_jarvis_agent_secret
- key = get_secret("anthropic_api_key", env_fallback="ANTHROPIC_API_KEY")
+ key = get_jarvis_agent_secret("claude-api")
except Exception: # noqa: BLE001
return False
return bool(key) and not str(key).startswith("sk-ant-oat")
diff --git a/jarvis/ui/web/fast_bootstrap.py b/jarvis/ui/web/fast_bootstrap.py
index 4c0c1d6f60..eba72047cb 100644
--- a/jarvis/ui/web/fast_bootstrap.py
+++ b/jarvis/ui/web/fast_bootstrap.py
@@ -24,10 +24,13 @@ from __future__ import annotations
import asyncio
import mimetypes
+import secrets
from contextlib import suppress
from pathlib import Path
from typing import Any
+from .surface_security import SurfaceSecurity
+
# The built React frontend lives next to this module (jarvis/ui/web/dist),
# the same directory the real FastAPI app serves it from. Resolving it here —
# with NO config / FastAPI import — lets the bootstrap serve the UI shell from
@@ -40,7 +43,12 @@ class FastBootstrap:
"""Hold-and-delegate ASGI bootstrap server. See module docstring."""
def __init__(
- self, *, hold_timeout: float = 120.0, dist_dir: Path | None = None
+ self,
+ *,
+ hold_timeout: float = 120.0,
+ dist_dir: Path | None = None,
+ session_token: str | None = None,
+ vite_dev_url: str | None = None,
) -> None:
self._full: dict[str, Any] = {"app": None}
self._ready = asyncio.Event()
@@ -48,6 +56,12 @@ class FastBootstrap:
self._server: Any = None
self._task: asyncio.Task | None = None
self._dist_dir = (dist_dir or _DEFAULT_DIST_DIR).resolve()
+ self._session_token = session_token or secrets.token_urlsafe(32)
+ self._secured_app = SurfaceSecurity(
+ self._asgi,
+ vite_dev_url=vite_dev_url,
+ bootstrap_tokens=(self._session_token,),
+ )
# Listener self-healing (see the "lifecycle" section). The bootstrap
# OWNS the listening socket for the whole process lifetime (it delegates
# to the real app via set_app but never hands off the socket), so when a
@@ -74,7 +88,14 @@ class FastBootstrap:
@property
def app(self) -> Any:
"""The bootstrap ASGI app (handed to uvicorn / driven directly in tests)."""
- return self._asgi
+ return self._entry_app
+
+ async def _entry_app(self, scope: dict, receive: Any, send: Any) -> None:
+ """Guard warm-up, then delegate directly to the secured full app."""
+ if self._ready.is_set() and self._full["app"] is not None:
+ await self._full["app"](scope, receive, send)
+ return
+ await self._secured_app(scope, receive, send)
async def _asgi(self, scope: dict, receive: Any, send: Any) -> None:
kind = scope["type"]
@@ -313,6 +334,7 @@ class FastBootstrap:
docstring) so the readiness event is set loop-locally.
"""
self._full["app"] = app
+ self._secured_app.sync_local_tokens()
self._ready.set()
async def serve(
diff --git a/jarvis/ui/web/frontend/src/__tests__/ws.test.ts b/jarvis/ui/web/frontend/src/__tests__/ws.test.ts
index c2396d165f..b1f24815d5 100644
--- a/jarvis/ui/web/frontend/src/__tests__/ws.test.ts
+++ b/jarvis/ui/web/frontend/src/__tests__/ws.test.ts
@@ -84,6 +84,16 @@ describe("WSClient", () => {
client.close();
});
+ it("never places an injected session token in the socket URL", () => {
+ window.__JARVIS_TOKEN = "session-secret";
+ const client = new WSClient();
+ client.connect();
+
+ expect(MockWebSocket.last!.url).toBe("ws://localhost:5173/ws");
+ expect(MockWebSocket.last!.url).not.toContain("session-secret");
+ client.close();
+ });
+
it("passes the close code to onClose", async () => {
const onClose = vi.fn();
const client = new WSClient({ onClose });
diff --git a/jarvis/ui/web/frontend/src/components/ApiKeyForm.tsx b/jarvis/ui/web/frontend/src/components/ApiKeyForm.tsx
index 4d507d54b8..8cbf6704d8 100644
--- a/jarvis/ui/web/frontend/src/components/ApiKeyForm.tsx
+++ b/jarvis/ui/web/frontend/src/components/ApiKeyForm.tsx
@@ -104,6 +104,7 @@ export function ApiKeyForm({ secretKey, dashboardUrl, configured, credentialHelp
variant="ghost"
onClick={handleDelete}
disabled={pending}
+ aria-label={`Delete ${secretKey}`}
className="text-destructive hover:text-destructive"
>
<Trash2 className="h-3.5 w-3.5" />
@@ -123,6 +124,7 @@ export function ApiKeyForm({ secretKey, dashboardUrl, configured, credentialHelp
<div className="relative flex-1">
<input
type={reveal ? "text" : "password"}
+ aria-label={`Enter ${secretKey}`}
value={value}
onChange={(e) => setValue(e.target.value)}
placeholder={`Enter ${secretKey}…`}
diff --git a/jarvis/ui/web/frontend/src/components/onboarding/OnboardingFlow.test.tsx b/jarvis/ui/web/frontend/src/components/onboarding/OnboardingFlow.test.tsx
index 852320d4ff..1c6be53bd1 100644
--- a/jarvis/ui/web/frontend/src/components/onboarding/OnboardingFlow.test.tsx
+++ b/jarvis/ui/web/frontend/src/components/onboarding/OnboardingFlow.test.tsx
@@ -16,6 +16,7 @@ const { dbl } = vi.hoisted(() => {
});
vi.mock("./steps/WelcomeStep", () => ({ WelcomeStep: dbl("step-welcome") }));
vi.mock("./steps/LanguageStep", () => ({ LanguageStep: dbl("step-language") }));
+vi.mock("./steps/PermissionsStep", () => ({ PermissionsStep: dbl("step-permissions") }));
vi.mock("./steps/WakeWordStep", () => ({ WakeWordStep: dbl("step-wake-word") }));
vi.mock("./steps/ApiKeysStep", () => ({ ApiKeysStep: dbl("step-api-keys") }));
vi.mock("./steps/FinishStep", () => ({ FinishStep: dbl("step-finish") }));
@@ -79,7 +80,7 @@ it("skip accumulates the skipped step", () => {
it("REGISTRY covers exactly the canonical backend steps", () => {
expect(new Set(STEP_KEYS)).toEqual(
new Set([
- "welcome", "language", "wake-word",
+ "welcome", "language", "permissions", "wake-word",
"api-keys", "finish",
]),
);
diff --git a/jarvis/ui/web/frontend/src/components/onboarding/OnboardingFlow.tsx b/jarvis/ui/web/frontend/src/components/onboarding/OnboardingFlow.tsx
index 772b262b01..2dbe0f4b80 100644
--- a/jarvis/ui/web/frontend/src/components/onboarding/OnboardingFlow.tsx
+++ b/jarvis/ui/web/frontend/src/components/onboarding/OnboardingFlow.tsx
@@ -4,6 +4,7 @@ import { useT } from "@/i18n";
import type { useOnboarding } from "@/hooks/useOnboarding";
import { WelcomeStep } from "./steps/WelcomeStep";
import { LanguageStep } from "./steps/LanguageStep";
+import { PermissionsStep } from "./steps/PermissionsStep";
import { WakeWordStep } from "./steps/WakeWordStep";
import { ApiKeysStep } from "./steps/ApiKeysStep";
import { FinishStep } from "./steps/FinishStep";
@@ -20,6 +21,7 @@ export interface StepProps {
const REGISTRY: Record<string, (p: StepProps) => JSX.Element> = {
welcome: WelcomeStep,
language: LanguageStep,
+ permissions: PermissionsStep,
"wake-word": WakeWordStep,
"api-keys": ApiKeysStep,
finish: FinishStep,
diff --git a/jarvis/ui/web/frontend/src/components/onboarding/steps/WakeWordStep.test.tsx b/jarvis/ui/web/frontend/src/components/onboarding/steps/WakeWordStep.test.tsx
index 029214b71a..df1b0a1eff 100644
--- a/jarvis/ui/web/frontend/src/components/onboarding/steps/WakeWordStep.test.tsx
+++ b/jarvis/ui/web/frontend/src/components/onboarding/steps/WakeWordStep.test.tsx
@@ -185,3 +185,30 @@ it("wake-word path: mic-check reports a neutral no-device state on a headless ho
expect(screen.getByText("onboarding.wake_word.mic_check.no_device")).toBeDefined(),
);
});
+
+it("wake-word path: mic-check directs a blocked macOS user to Permissions", async () => {
+ vi.stubGlobal(
+ "fetch",
+ vi.fn(() =>
+ Promise.resolve({
+ ok: true,
+ status: 200,
+ json: () =>
+ Promise.resolve({
+ max_dbfs: -120.0,
+ no_device: false,
+ too_quiet: false,
+ permission_required: true,
+ }),
+ }),
+ ),
+ );
+ renderStep();
+ selectWakeMode();
+
+ fireEvent.click(screen.getByRole("button", { name: "onboarding.wake_word.mic_check.test_button" }));
+
+ expect(
+ await screen.findByText("onboarding.wake_word.mic_check.permission_required"),
+ ).toBeDefined();
+});
diff --git a/jarvis/ui/web/frontend/src/components/onboarding/steps/WakeWordStep.tsx b/jarvis/ui/web/frontend/src/components/onboarding/steps/WakeWordStep.tsx
index 8890e2b303..6417ecd0b1 100644
--- a/jarvis/ui/web/frontend/src/components/onboarding/steps/WakeWordStep.tsx
+++ b/jarvis/ui/web/frontend/src/components/onboarding/steps/WakeWordStep.tsx
@@ -12,6 +12,7 @@ interface MicLevelResult {
max_dbfs: number;
no_device: boolean;
too_quiet: boolean;
+ permission_required?: boolean;
}
type MicCheckState = "idle" | "checking" | "done";
@@ -246,7 +247,9 @@ export function WakeWordStep({ onb, goNext }: StepProps) {
<p className="text-xs text-amber-500">{t("onboarding.wake_word.mic_check.error")}</p>
)}
{micCheck.state === "done" && micCheck.result && (
- micCheck.result.no_device ? (
+ micCheck.result.permission_required ? (
+ <p className="text-xs text-amber-500">{t("onboarding.wake_word.mic_check.permission_required")}</p>
+ ) : micCheck.result.no_device ? (
<p className="text-xs text-muted-foreground">{t("onboarding.wake_word.mic_check.no_device")}</p>
) : micCheck.result.too_quiet ? (
<p className="text-xs text-amber-500">{t("onboarding.wake_word.mic_check.too_quiet")}</p>
diff --git a/jarvis/ui/web/frontend/src/components/runs/RunDetail.tsx b/jarvis/ui/web/frontend/src/components/runs/RunDetail.tsx
index 78667ce3ff..84a4f10f01 100644
--- a/jarvis/ui/web/frontend/src/components/runs/RunDetail.tsx
+++ b/jarvis/ui/web/frontend/src/components/runs/RunDetail.tsx
@@ -7,10 +7,11 @@ import { RunTurnCard } from "@/components/runs/RunTurnCard";
import { OutcomeBadge } from "@/components/runs/OutcomeBadge";
import { FeatureBadges } from "@/components/runs/FeatureBadges";
import { MetricsPanel } from "@/components/runs/MetricsPanel";
-import { useT } from "@/i18n";
+import { useT, useUiLanguage } from "@/i18n";
export function RunDetail({ sessionId }: { sessionId: string }) {
const t = useT();
+ const locale = localeForUiLanguage(useUiLanguage());
const { data: run, isLoading } = useRunDetail(sessionId);
const [showMetrics, setShowMetrics] = useState(false);
if (isLoading || !run) {
@@ -35,8 +36,8 @@ export function RunDetail({ sessionId }: { sessionId: string }) {
<div className="flex items-center gap-2">
<OutcomeBadge outcome={run.outcome} />
<span className="font-mono text-xs text-muted-foreground">
- {started.toLocaleString("de")}
- {ended && ` — ${ended.toLocaleTimeString("de")}`}
+ {started.toLocaleString(locale)}
+ {ended && ` — ${ended.toLocaleTimeString(locale)}`}
</span>
</div>
<div className="flex flex-wrap items-center gap-1.5">
@@ -49,7 +50,7 @@ export function RunDetail({ sessionId }: { sessionId: string }) {
)}
{tokens > 0 && (
<Badge variant="outline" className="text-[10px]">
- {tokens.toLocaleString("de")} tok
+ {tokens.toLocaleString(locale)} tok
</Badge>
)}
{run.session.hangup_reason && (
@@ -95,6 +96,12 @@ export function RunDetail({ sessionId }: { sessionId: string }) {
);
}
+function localeForUiLanguage(language: string): string {
+ if (language === "de") return "de-DE";
+ if (language === "es") return "es-ES";
+ return "en-US";
+}
+
function LatencyChip({ status }: { status: string }) {
if (status === "ok") return null;
const cls =
diff --git a/jarvis/ui/web/frontend/src/hooks/useWebSocket.test.tsx b/jarvis/ui/web/frontend/src/hooks/useWebSocket.test.tsx
index 5b049f31d5..0f5b06deec 100644
--- a/jarvis/ui/web/frontend/src/hooks/useWebSocket.test.tsx
+++ b/jarvis/ui/web/frontend/src/hooks/useWebSocket.test.tsx
@@ -6,6 +6,7 @@
* VoiceBootStatus frame flips `voiceReady` in the store.
*/
import { cleanup, render } from "@testing-library/react";
+import { QueryClient, QueryClientProvider } from "@tanstack/react-query";
import { afterEach, beforeEach, describe, expect, it, vi } from "vitest";
import { useWebSocket } from "@/hooks/useWebSocket";
@@ -60,11 +61,23 @@ function envelope(eventName: string, payload: Record<string, unknown>) {
};
}
-function Harness() {
+const queryClient = new QueryClient({
+ defaultOptions: { queries: { retry: false } },
+});
+
+function WebSocketHarness() {
useWebSocket();
return null;
}
+function Harness() {
+ return (
+ <QueryClientProvider client={queryClient}>
+ <WebSocketHarness />
+ </QueryClientProvider>
+ );
+}
+
describe("useWebSocket VoiceBootStatus handling", () => {
const OriginalWS = globalThis.WebSocket;
@@ -77,6 +90,7 @@ describe("useWebSocket VoiceBootStatus handling", () => {
};
useEventStore.setState({ voiceReady: false, toasts: [] });
useI18nStore.getState().setUi("en", { push: false });
+ queryClient.clear();
});
afterEach(() => {
@@ -123,6 +137,18 @@ describe("useWebSocket VoiceBootStatus handling", () => {
expect(toast.message).toContain("mission-42");
expect(toast.message).not.toContain("private content");
});
+
+ it("invalidates every documentation query after a registry reload", async () => {
+ const invalidate = vi.spyOn(queryClient, "invalidateQueries");
+ render(<Harness />);
+ await Promise.resolve();
+
+ MockWebSocket.last!.deliver(
+ envelope("DocIndexReloaded", { total: 42, by_diataxis: {}, errors: 0 }),
+ );
+
+ expect(invalidate).toHaveBeenCalledWith({ queryKey: ["docs"] });
+ });
});
describe("useWebSocket connection state (welcome-gated + warming)", () => {
diff --git a/jarvis/ui/web/frontend/src/hooks/useWebSocket.ts b/jarvis/ui/web/frontend/src/hooks/useWebSocket.ts
index 9be48b049d..6e259d1b32 100644
--- a/jarvis/ui/web/frontend/src/hooks/useWebSocket.ts
+++ b/jarvis/ui/web/frontend/src/hooks/useWebSocket.ts
@@ -1,4 +1,6 @@
import { useEffect, useRef } from "react";
+import { useQueryClient } from "@tanstack/react-query";
+
import { WSClient } from "@/lib/ws";
import {
SECTION_LABELS,
@@ -28,6 +30,7 @@ export function getWSClient(): WSClient | null {
*/
export function useWebSocket(): void {
const mounted = useRef(false);
+ const queryClient = useQueryClient();
const setConnected = useEventStore((s) => s.setConnected);
const setWarming = useEventStore((s) => s.setWarming);
const pushEvent = useEventStore((s) => s.pushEvent);
@@ -259,6 +262,13 @@ export function useWebSocket(): void {
}
}
+ if (env.event_name === "DocIndexReloaded") {
+ // The registry can reload while the reader is not mounted. Invalidate
+ // the complete docs cache here so navigation, details, and search all
+ // reflect the same index the next time they are shown.
+ void queryClient.invalidateQueries({ queryKey: ["docs"] });
+ }
+
if (env.event_name === "ActionApprovalRequired") {
const p = env.payload as {
mission_id?: unknown;
@@ -319,6 +329,7 @@ export function useWebSocket(): void {
setActiveSection,
setBrainProvider,
pushToast,
+ queryClient,
]);
}
diff --git a/jarvis/ui/web/frontend/src/i18n/locales/de.json b/jarvis/ui/web/frontend/src/i18n/locales/de.json
index 7172d9de4d..46231d56ae 100644
--- a/jarvis/ui/web/frontend/src/i18n/locales/de.json
+++ b/jarvis/ui/web/frontend/src/i18n/locales/de.json
@@ -1,4 +1,15 @@
{
+ "auth_gate": {
+ "checking": "Zugriff wird geprüft…",
+ "title": "Personal Jarvis entsperren",
+ "subtitle": "Gib den Control Key dieser Jarvis-Instanz ein.",
+ "control_key": "Control Key",
+ "placeholder": "Control Key einfügen",
+ "submit": "Entsperren",
+ "submitting": "Wird geprüft…",
+ "invalid": "Dieser Control Key wurde nicht akzeptiert.",
+ "unavailable": "Jarvis ist nicht erreichbar. Versuch es erneut."
+ },
"file_toast": {
"show_in_folder": "Im Ordner zeigen",
"open": "Öffnen",
@@ -107,7 +118,7 @@
"socials": {
"subtitle": "Links zu unserer Community und unseren Profilen.",
"add": "Link hinzufügen",
- "empty": "Noch keine Social-Links — füge den ersten hinzu.",
+ "empty": "Es sind keine Social-Links verfügbar.",
"edit": "Bearbeiten",
"delete": "Löschen",
"open": "Öffnen",
@@ -176,7 +187,7 @@
"added": "„{0}\" wurde ins Wörterbuch aufgenommen.",
"saved": "Wörterbuch-Eintrag gespeichert.",
"deleted": "„{0}\" wurde aus dem Wörterbuch entfernt.",
- "applies_note": "Änderungen gelten ab deiner nächsten Äußerung — kein Neustart nötig.",
+ "applies_note": "Änderungen gelten ab der nächsten Pipeline-Transkription — kein Neustart nötig. Im Realtime-Modus werden Wörterbuchkorrekturen nicht verwendet.",
"dialog_add_title": "Zum Wortschatz hinzufügen",
"dialog_edit_title": "Wörterbuch-Eintrag bearbeiten",
"correction_toggle": "Falsch Erkanntes korrigieren",
@@ -478,6 +489,12 @@
"errors": "Fehler"
}
},
+ "voice_mode": {
+ "label": "Modus",
+ "realtime": "Realtime",
+ "pipeline": "Pipeline",
+ "unknown": "Unbekannt"
+ },
"sessions_view": {
"title": "Transkription",
"subtitle": "Letzte Voice-Sessions, Turn für Turn.",
@@ -907,7 +924,7 @@
"runtime_realtime": "Aktuelle Session: Realtime",
"runtime_pipeline": "Aktuelle Session: Pipeline",
"runtime_fallback_pipeline": "Die aktuelle Session ist auf die Pipeline zurückgefallen; Realtime bedient diesen Anruf nicht.",
- "cat_brain_desc": "Das Modell, das Chat, Routing und Computer-Use antreibt.",
+ "cat_brain_desc": "Das Modell, das deine Chat- und Sprachantworten formuliert. Aktionen und Computer-Use übernimmt das separate Tool-Modell.",
"cat_tts_desc": "Die Stimme, mit der Jarvis spricht.",
"cat_stt_desc": "Wie Jarvis deine Sprache in Text umwandelt.",
"cat_realtime_desc": "Vollduplex-Sprache-zu-Sprache über jeden eingerichteten Realtime-Provider, auf dem Desktop oder im Browser.",
@@ -1009,6 +1026,38 @@
"cleared": "Tool Model auf dein Hauptmodell zurückgesetzt",
"vision_note": "Es werden nur Modelle angezeigt, die Bilder verstehen - Computer-Use liest den Bildschirm über Screenshots, ein reines Text-Modell kann es nicht steuern."
},
+ "permissions": {
+ "group_title": "Datenschutz-Berechtigungen",
+ "title": "macOS-Berechtigungen",
+ "description": "Erteile nur die Systemzugriffe, die für Sprache, Computer-Use, globale Kurzbefehle und Fenstersteuerung nötig sind. Jarvis verändert niemals die macOS-Datenschutzdatenbank.",
+ "loading": "Systemberechtigungen werden geprüft…",
+ "load_failed": "Der aktuelle Berechtigungsstatus konnte nicht gelesen werden.",
+ "refresh": "Erneut prüfen",
+ "not_required": "Auf diesem Betriebssystem sind keine zusätzlichen Desktop-Datenschutzberechtigungen nötig.",
+ "identity_warning": "Starte Personal Jarvis aus seinem App-Bundle, bevor du Zugriff erlaubst. macOS bindet Berechtigungen an die genaue App-Identität.",
+ "restart_required": "Starte Personal Jarvis neu, bevor du den neu erlaubten Zugriff verwendest.",
+ "restart_now": "Jetzt neu starten",
+ "restarting": "Neustart…",
+ "restart_failed": "Personal Jarvis konnte nicht neu starten. Beende und öffne es manuell erneut.",
+ "request": "Erlauben",
+ "open_settings": "Einstellungen öffnen",
+ "status": {
+ "granted": "Erlaubt",
+ "not_determined": "Nicht angefragt",
+ "denied": "Abgelehnt",
+ "restricted": "Eingeschränkt",
+ "not_granted": "Nicht erlaubt",
+ "unavailable": "Nicht verfügbar",
+ "not_required": "Nicht erforderlich"
+ },
+ "items": {
+ "microphone": { "title": "Mikrofon", "description": "Erforderlich für Aktivierungswort und lokale Spracheingabe." },
+ "screen_recording": { "title": "Bildschirmaufnahme", "description": "Erforderlich, damit Computer-Use alle verbundenen Bildschirme sehen kann." },
+ "accessibility": { "title": "Bedienungshilfen", "description": "Erforderlich für zuverlässige Klicks, Eingaben, Fokus und Fenstersteuerung." },
+ "input_monitoring": { "title": "Eingabeüberwachung", "description": "Erforderlich für globale Push-to-Talk- und Tastaturkurzbefehle." },
+ "event_posting": { "title": "Eingabesteuerung", "description": "Erforderlich, damit Computer-Use Maus- und Tastaturereignisse senden kann." }
+ }
+ },
"settings_view": {
"silence_window": {
"title": "Denkpause",
@@ -1115,7 +1164,7 @@
"derived_name": "Dein Assistent heißt dann: {0}",
"engine_options": {
"auto": "Automatisch (empfohlen)",
- "openwakeword": "openWakeWord (eingebaute Phrasen)",
+ "openwakeword": "openWakeWord (benutzerdefiniertes Modell)",
"vosk_kws": "Keyword-Spotting (beliebige Phrase, überall gleich)",
"stt_match": "STT-Abgleich (beliebige Phrase, braucht lokales Whisper)",
"custom_onnx": "Eigenes ONNX-Modell"
@@ -1400,6 +1449,8 @@
"search_modal_placeholder": "Docs durchsuchen…",
"search_hint": "Tippe einen Begriff zum Suchen…",
"search_loading": "Suche…",
+ "search_failed": "Die Suche konnte nicht geladen werden.",
+ "search_retry": "Erneut versuchen",
"no_results": "Keine Treffer für \"{0}\"",
"for_fulltext": "für die Volltextsuche.",
"could_not_load": "Konnte Doc nicht laden.",
@@ -1553,6 +1604,13 @@
"ui_label": "Oberflächensprache",
"reply_label": "Antwortsprache"
},
+ "permissions": {
+ "title": "Zugriff auf diesem Mac erlauben",
+ "body": "macOS lässt jede Funktion einzeln bestätigen. Nutze die Schaltflächen unten und kehre danach hierher zurück; der Status wird automatisch aktualisiert.",
+ "privacy_note": "Diese Abfragen kommen von macOS. Das Installationsprogramm kann sie nicht stillschweigend freigeben, und Personal Jarvis umgeht niemals die Systemeinstellungen.",
+ "continue": "Weiter",
+ "text_only": "Nur mit Text fortfahren"
+ },
"wake_word": {
"choice_title": "Wie möchtest du {name} aktivieren?",
"choice_body": "Wähle, was zu deiner Arbeitsweise passt — du kannst das später in den Einstellungen ändern.",
@@ -1561,7 +1619,7 @@
"mode_shortcut_title": "Tastenkombination",
"mode_shortcut_body": "Kein Aktivierungswort — halte eine Taste gedrückt, um zu sprechen, lass los zum Senden (Push-to-Talk).",
"back_to_choice": "Zurück",
- "shortcut_note": "Du aktivierst {name} stattdessen über eine Tastenkombination statt über ein Aktivierungswort. Die genaue Taste kannst du jederzeit in den Einstellungen → Wake-Word festlegen.",
+ "shortcut_note": "Du aktivierst {name} stattdessen über eine Tastenkombination statt über ein Aktivierungswort. Die genaue Taste kannst du jederzeit unter Einstellungen → Sprach-Tastenkürzel festlegen.",
"shortcut_cta": "Weiter",
"title": "Wähle dein Aktivierungswort",
"body": "Wähle das Wort, das deinen Assistenten aufweckt. \"Hey\" bleibt fest — den Rest bestimmst du.",
@@ -1586,6 +1644,7 @@
"good": "Klingt gut — dein Mikrofon hat deine Stimme klar aufgenommen.",
"too_quiet": "Das war sehr leise. Erhöhe die Mikrofonlautstärke oder rücke näher heran und versuche es erneut.",
"no_device": "Kein Mikrofon erkannt — du kannst die Einrichtung trotzdem abschließen und das später in den Einstellungen beheben.",
+ "permission_required": "Erteile unter Berechtigungen zuerst den Mikrofonzugriff, bevor du diesen Check startest.",
"error": "Das Mikrofon konnte gerade nicht geprüft werden."
}
},
@@ -1646,7 +1705,7 @@
"reply_section": "Antwort-Sprache",
"reply_hint": "In welcher Sprache {name} antwortet. Eigennamen, Code-Bezeichner und Fachbegriffe bleiben in ihrer Originalform.",
"stt_section": "Erkennungssprache (Stimme)",
- "stt_hint": "In welcher Sprache deine gesprochene Stimme erkannt und in Text umgewandelt wird. Automatisch erkennt von selbst, welche Sprache du sprichst.",
+ "stt_hint": "In welcher Sprache deine Stimme erkannt und in Text umgewandelt wird. Automatisch erkennt sie selbst. Beende nach einer Änderung jeden Realtime-Anruf und starte Jarvis für den Pipeline-Modus neu.",
"options": {
"auto": {
"label": "Automatisch",
@@ -1810,7 +1869,12 @@
"loading": "Lade Graph…",
"load_error": "Graph konnte nicht geladen werden.",
"reset_view_title": "Zoom auf alle Knoten zurücksetzen",
- "center": "Zentrieren"
+ "center": "Zentrieren",
+ "relationship_graph": "Wiki-Beziehungsgraph",
+ "node_details": "{0} ({1}) · {2} {3}",
+ "backlink_one": "Backlink",
+ "backlink_many": "Backlinks",
+ "unresolved": "nicht aufgelöst"
},
"tree_sidebar": {
"load_error": "Konnte das Wiki nicht laden.",
@@ -1890,11 +1954,43 @@
},
"docs_sidebar": {
"title": "Dokumentation",
- "error": "Fehler"
+ "error": "Fehler",
+ "indexing": "Lokaler Index wird erstellt…",
+ "retry": "Erneut versuchen",
+ "documents": "Dokumente",
+ "no_results": "Keine passenden Dokumente"
},
"docs_content": {
"prev": "Vorher",
- "next": "Nächstes"
+ "next": "Nächstes",
+ "breadcrumb": "Dokumentation",
+ "related_guides": "Verwandte Anleitungen",
+ "last_reviewed": "Zuletzt geprüft:",
+ "review_unavailable": "Prüfdatum nicht verfügbar",
+ "on_this_page": "Auf dieser Seite",
+ "copy_code": "Code kopieren",
+ "code_copied": "Code kopiert",
+ "skip_to_content": "Zum Dokumentationsinhalt springen"
+ },
+ "docs_overview": {
+ "eyebrow": "Dokumentation",
+ "title": "Personal Jarvis Docs",
+ "description": "Alles von der ersten Einrichtung bis zur Architektur hinter der Sprachsteuerung. Durchsuche die vollständige lokale Bibliothek oder öffne die neu gestaltete öffentliche Dokumentation.",
+ "online_docs": "Neu gestaltete Online-Docs öffnen",
+ "load_failed_title": "Die Dokumentation konnte nicht geladen werden",
+ "load_failed_description": "Der lokale Index wurde nicht rechtzeitig bereit. Versuch es erneut, ohne die App neu zu starten.",
+ "retry": "Erneut versuchen",
+ "empty_title": "Keine lokalen Dokumente gefunden",
+ "empty_description": "Die Online-Dokumentation ist weiterhin über die Schaltfläche oben erreichbar.",
+ "local_library": "In der lokalen Bibliothek starten",
+ "local_library_description": "Schneller Offline-Zugriff auf die Dokumentation dieser Installation.",
+ "indexing_title": "Deine Dokumentation wird vorbereitet",
+ "indexing_description": "Die lokale Markdown-Bibliothek wird gelesen und die Volltextsuche aufgebaut. Das dauert normalerweise nur einen Moment.",
+ "loading_page": "Dokument wird geladen…",
+ "browse_by_topic": "Nach Thema durchsuchen",
+ "browse_description": "Folge einem Lernpfad oder springe direkt zum benötigten Feature.",
+ "guide": "Anleitung",
+ "guides": "Anleitungen"
},
"docs_search_modal": {
"navigate": "navigieren",
@@ -2226,6 +2322,22 @@
"manual_c": "ablegen."
},
"wiki_health": {
+ "capture_aria": "Wiki-Erfassungsfunnel der letzten {0} Stunden",
+ "capture_window": "Erfassung letzte {0} h",
+ "capture_reviewed": "Geprüft",
+ "capture_candidate_reviews": "Prüfungen mit Kandidaten",
+ "capture_candidate_facts": "Kandidaten",
+ "capture_writes": "Schreibvorgänge",
+ "capture_noop": "Ohne Änderung",
+ "capture_rejected": "Abgelehnt",
+ "capture_skipped": "Übersprungen",
+ "capture_pending": "Ausstehend",
+ "capture_filtered": "Vorgefiltert",
+ "capture_empty": "Leer",
+ "capture_failed": "Fehlgeschlagen",
+ "capture_in_progress": "In Arbeit",
+ "capture_session_sweeps": "Sitzungsprüfungen",
+ "capture_store_unavailable": "Erfassungsdatenbank nicht verfügbar",
"checking": "Wiki-Zustand wird geprüft…",
"unavailable": "Wiki-Zustandsprüfung nicht verfügbar",
"vault_prefix": "Vault: {0}",
@@ -2398,10 +2510,11 @@
},
"feedback": {
"discord_cta_title": "Auf unserem Discord melden",
- "discord_cta_subtitle": "Tritt #bug-reports bei und poste deinen Fehler, deine Idee oder Frage direkt.",
- "discord_cta_button": "Discord öffnen",
+ "discord_cta_subtitle": "Öffne #report-a-bug und poste deinen Fehler, deine Idee oder Frage direkt.",
+ "discord_cta_button": "#report-a-bug öffnen",
+ "discord_join_button": "Zuerst Discord beitreten",
"or_send_here": "oder hier direkt senden",
- "subtitle": "Fehler melden, Ideen teilen oder eine Frage stellen — geht direkt in unseren Discord.",
+ "subtitle": "Öffne unseren Discord, um Fehler zu melden, Ideen zu teilen oder Fragen zu stellen.",
"type_label": "Typ",
"type_bug": "Bug",
"type_idea": "Idee",
diff --git a/jarvis/ui/web/frontend/src/i18n/locales/en.json b/jarvis/ui/web/frontend/src/i18n/locales/en.json
index 3defc808df..2e3596eb96 100644
--- a/jarvis/ui/web/frontend/src/i18n/locales/en.json
+++ b/jarvis/ui/web/frontend/src/i18n/locales/en.json
@@ -1,4 +1,15 @@
{
+ "auth_gate": {
+ "checking": "Checking access…",
+ "title": "Unlock Personal Jarvis",
+ "subtitle": "Enter the control key configured for this Jarvis instance.",
+ "control_key": "Control key",
+ "placeholder": "Paste your control key",
+ "submit": "Unlock",
+ "submitting": "Checking…",
+ "invalid": "That control key was not accepted.",
+ "unavailable": "Could not reach Jarvis. Try again."
+ },
"file_toast": {
"show_in_folder": "Show in folder",
"open": "Open",
@@ -107,7 +118,7 @@
"socials": {
"subtitle": "Links to our community and profiles.",
"add": "Add link",
- "empty": "No social links yet — add your first one.",
+ "empty": "No social links are available.",
"edit": "Edit",
"delete": "Delete",
"open": "Open",
@@ -176,7 +187,7 @@
"added": "\"{0}\" added to the dictionary.",
"saved": "Dictionary entry saved.",
"deleted": "\"{0}\" removed from the dictionary.",
- "applies_note": "Changes apply to the next thing you say — no restart needed.",
+ "applies_note": "Changes apply to your next Pipeline transcription — no restart needed. Realtime mode does not use Dictionary corrections.",
"dialog_add_title": "Add to your vocabulary",
"dialog_edit_title": "Edit dictionary entry",
"correction_toggle": "Fix a misrecognition",
@@ -478,6 +489,12 @@
"errors": "Errors"
}
},
+ "voice_mode": {
+ "label": "Mode",
+ "realtime": "Realtime",
+ "pipeline": "Pipeline",
+ "unknown": "Unknown"
+ },
"sessions_view": {
"title": "Transcription",
"subtitle": "Recent voice sessions, turn by turn.",
@@ -907,7 +924,7 @@
"runtime_realtime": "Current session: Realtime",
"runtime_pipeline": "Current session: Pipeline",
"runtime_fallback_pipeline": "Current session fell back to Pipeline; Realtime is not serving this call.",
- "cat_brain_desc": "The model that powers chat, routing, and Computer-Use.",
+ "cat_brain_desc": "The model that writes your chat and voice answers. The separate Tool Model handles actions and Computer Use.",
"cat_tts_desc": "The voice Jarvis speaks with.",
"cat_stt_desc": "How Jarvis turns your speech into text.",
"cat_realtime_desc": "Full-duplex speech-to-speech through any configured Realtime provider, on desktop or in the browser.",
@@ -1010,6 +1027,38 @@
"cleared": "Tool Model reset to your main model",
"vision_note": "Only models that can see images are listed - Computer-Use reads the screen from screenshots, so a text-only model cannot run it."
},
+ "permissions": {
+ "group_title": "Privacy permissions",
+ "title": "macOS permissions",
+ "description": "Grant only the system access needed for voice, Computer-Use, global shortcuts, and window control. Jarvis never edits the macOS privacy database.",
+ "loading": "Checking system permissions…",
+ "load_failed": "Could not read the current permission status.",
+ "refresh": "Check again",
+ "not_required": "No extra desktop privacy permissions are required on this operating system.",
+ "identity_warning": "Launch Personal Jarvis from its app bundle before granting access. macOS attaches permissions to the exact app identity.",
+ "restart_required": "Restart Personal Jarvis before using the newly granted access.",
+ "restart_now": "Restart now",
+ "restarting": "Restarting…",
+ "restart_failed": "Personal Jarvis could not restart. Quit and reopen it manually.",
+ "request": "Allow",
+ "open_settings": "Open Settings",
+ "status": {
+ "granted": "Allowed",
+ "not_determined": "Not requested",
+ "denied": "Denied",
+ "restricted": "Restricted",
+ "not_granted": "Not allowed",
+ "unavailable": "Unavailable",
+ "not_required": "Not required"
+ },
+ "items": {
+ "microphone": { "title": "Microphone", "description": "Required for wake-word and local voice input." },
+ "screen_recording": { "title": "Screen Recording", "description": "Required for Computer-Use to see every connected display." },
+ "accessibility": { "title": "Accessibility", "description": "Required for reliable clicks, typing, focus, and window control." },
+ "input_monitoring": { "title": "Input Monitoring", "description": "Required for global push-to-talk and keyboard shortcuts." },
+ "event_posting": { "title": "Input control", "description": "Required for Computer-Use to send mouse and keyboard events." }
+ }
+ },
"settings_view": {
"silence_window": {
"title": "Thinking pause",
@@ -1116,7 +1165,7 @@
"derived_name": "Your assistant will be called: {0}",
"engine_options": {
"auto": "Auto (recommended)",
- "openwakeword": "openWakeWord (built-in phrases)",
+ "openwakeword": "openWakeWord (custom model)",
"vosk_kws": "Keyword spotting (any phrase, same on every device)",
"stt_match": "STT match (any phrase, needs local Whisper)",
"custom_onnx": "Custom ONNX model"
@@ -1401,6 +1450,8 @@
"search_modal_placeholder": "Search docs…",
"search_hint": "Type a term to search…",
"search_loading": "Searching…",
+ "search_failed": "Search could not be loaded.",
+ "search_retry": "Try again",
"no_results": "No results for \"{0}\"",
"for_fulltext": "for full-text search.",
"could_not_load": "Could not load doc.",
@@ -1554,6 +1605,13 @@
"ui_label": "Interface language",
"reply_label": "Reply language"
},
+ "permissions": {
+ "title": "Allow access on this Mac",
+ "body": "macOS asks you to approve each capability separately. Use the buttons below, then return here; the status updates automatically.",
+ "privacy_note": "These prompts come from macOS. The installer cannot silently approve them, and Personal Jarvis never bypasses System Settings.",
+ "continue": "Continue",
+ "text_only": "Continue with text only"
+ },
"wake_word": {
"choice_title": "How do you want to activate {name}?",
"choice_body": "Pick whichever fits how you work — you can change this later in Settings.",
@@ -1562,7 +1620,7 @@
"mode_shortcut_title": "Keyboard shortcut",
"mode_shortcut_body": "No wake word — hold a key to talk, release to send (push-to-talk).",
"back_to_choice": "Back",
- "shortcut_note": "You'll activate {name} with a keyboard shortcut instead of a wake word. You can set up the exact key anytime in Settings → Wake Word.",
+ "shortcut_note": "You'll activate {name} with a keyboard shortcut instead of a wake word. You can set up the exact key anytime in Settings → Voice Keybinds.",
"shortcut_cta": "Continue",
"title": "Pick your wake word",
"body": "Choose the word that wakes your assistant. \"Hey\" stays fixed — you pick the rest.",
@@ -1587,6 +1645,7 @@
"good": "Sounds good — your microphone picked up your voice clearly.",
"too_quiet": "That was very quiet. Turn up your microphone volume or move closer, then try again.",
"no_device": "No microphone detected — you can still finish setup and fix this later in Settings.",
+ "permission_required": "Grant Microphone access in Permissions before running this check.",
"error": "Could not check the microphone right now."
}
},
@@ -1647,7 +1706,7 @@
"reply_section": "Reply Language",
"reply_hint": "Which language {name} speaks when answering you. Proper names, code identifiers and technical terms stay in their original form.",
"stt_section": "Voice Recognition Language",
- "stt_hint": "Which language your spoken voice is recognised and turned into text. Automatic detects the language you speak on its own.",
+ "stt_hint": "Which language your spoken voice is recognised and turned into text. Automatic detects it for you. After changing this, end any Realtime call and restart Jarvis for Pipeline mode.",
"options": {
"auto": {
"label": "Automatic",
@@ -1811,7 +1870,12 @@
"loading": "Loading graph…",
"load_error": "Could not load the graph.",
"reset_view_title": "Reset zoom to all nodes",
- "center": "Center"
+ "center": "Center",
+ "relationship_graph": "Wiki relationship graph",
+ "node_details": "{0} ({1}) · {2} {3}",
+ "backlink_one": "backlink",
+ "backlink_many": "backlinks",
+ "unresolved": "unresolved"
},
"tree_sidebar": {
"load_error": "Could not load the wiki.",
@@ -1891,11 +1955,43 @@
},
"docs_sidebar": {
"title": "Documentation",
- "error": "Error"
+ "error": "Error",
+ "indexing": "Building local index…",
+ "retry": "Try again",
+ "documents": "documents",
+ "no_results": "No matching documents"
},
"docs_content": {
"prev": "Previous",
- "next": "Next"
+ "next": "Next",
+ "breadcrumb": "Documentation",
+ "related_guides": "Related Guides",
+ "last_reviewed": "Last reviewed:",
+ "review_unavailable": "Review date unavailable",
+ "on_this_page": "On this page",
+ "copy_code": "Copy code",
+ "code_copied": "Code copied",
+ "skip_to_content": "Skip to documentation content"
+ },
+ "docs_overview": {
+ "eyebrow": "Documentation",
+ "title": "Personal Jarvis docs",
+ "description": "Everything from first setup to the architecture behind the voice. Browse the complete local library or open the redesigned public documentation.",
+ "online_docs": "Open redesigned online docs",
+ "load_failed_title": "Documentation could not be loaded",
+ "load_failed_description": "The local index did not become ready in time. Try again without restarting the app.",
+ "retry": "Try again",
+ "empty_title": "No local documents found",
+ "empty_description": "The online documentation is still available from the button above.",
+ "local_library": "Start in the local library",
+ "local_library_description": "Fast, offline access to the documentation shipped with this installation.",
+ "indexing_title": "Preparing your documentation",
+ "indexing_description": "Scanning the local Markdown library and building full-text search. This usually takes only a moment.",
+ "loading_page": "Loading document…",
+ "browse_by_topic": "Browse by Topic",
+ "browse_description": "Follow a learning path or jump to the feature you need.",
+ "guide": "guide",
+ "guides": "guides"
},
"docs_search_modal": {
"navigate": "navigate",
@@ -2227,6 +2323,22 @@
"manual_c": "yourself at any time."
},
"wiki_health": {
+ "capture_aria": "Wiki capture funnel for the last {0} hours",
+ "capture_window": "Last {0}h capture",
+ "capture_reviewed": "Reviewed",
+ "capture_candidate_reviews": "Productive reviews",
+ "capture_candidate_facts": "Candidates",
+ "capture_writes": "Writes",
+ "capture_noop": "No change",
+ "capture_rejected": "Rejected",
+ "capture_skipped": "Skipped",
+ "capture_pending": "Pending",
+ "capture_filtered": "Filtered",
+ "capture_empty": "Empty",
+ "capture_failed": "Failed",
+ "capture_in_progress": "In progress",
+ "capture_session_sweeps": "Session sweeps",
+ "capture_store_unavailable": "Capture store unavailable",
"checking": "Checking wiki health…",
"unavailable": "Wiki health check unavailable",
"vault_prefix": "Vault: {0}",
@@ -2399,10 +2511,11 @@
},
"feedback": {
"discord_cta_title": "Report on our Discord",
- "discord_cta_subtitle": "Join #bug-reports and post your bug, idea, or question directly.",
- "discord_cta_button": "Open Discord",
+ "discord_cta_subtitle": "Open #report-a-bug and post your bug, idea, or question directly.",
+ "discord_cta_button": "Open #report-a-bug",
+ "discord_join_button": "Join Discord first",
"or_send_here": "or send it from here",
- "subtitle": "Report a bug, share an idea, or ask a question — sent straight to our Discord.",
+ "subtitle": "Open our Discord to report a bug, share an idea, or ask a question.",
"type_label": "Type",
"type_bug": "Bug",
"type_idea": "Idea",
diff --git a/jarvis/ui/web/frontend/src/i18n/locales/es.json b/jarvis/ui/web/frontend/src/i18n/locales/es.json
index 1348c42e43..f24c5d913a 100644
--- a/jarvis/ui/web/frontend/src/i18n/locales/es.json
+++ b/jarvis/ui/web/frontend/src/i18n/locales/es.json
@@ -1,4 +1,15 @@
{
+ "auth_gate": {
+ "checking": "Comprobando el acceso…",
+ "title": "Desbloquear Personal Jarvis",
+ "subtitle": "Introduce la clave de control configurada para esta instancia de Jarvis.",
+ "control_key": "Clave de control",
+ "placeholder": "Pega tu clave de control",
+ "submit": "Desbloquear",
+ "submitting": "Comprobando…",
+ "invalid": "La clave de control no ha sido aceptada.",
+ "unavailable": "No se pudo conectar con Jarvis. Inténtalo de nuevo."
+ },
"file_toast": {
"show_in_folder": "Mostrar en la carpeta",
"open": "Abrir",
@@ -107,7 +118,7 @@
"socials": {
"subtitle": "Enlaces a nuestra comunidad y perfiles.",
"add": "Añadir enlace",
- "empty": "Aún no hay enlaces — añade el primero.",
+ "empty": "No hay enlaces sociales disponibles.",
"edit": "Editar",
"delete": "Eliminar",
"open": "Abrir",
@@ -176,7 +187,7 @@
"added": "«{0}» se añadió al diccionario.",
"saved": "Entrada del diccionario guardada.",
"deleted": "«{0}» se eliminó del diccionario.",
- "applies_note": "Los cambios se aplican a tu próxima frase — no hace falta reiniciar.",
+ "applies_note": "Los cambios se aplican desde la siguiente transcripción de Pipeline — no hace falta reiniciar. El modo Realtime no usa las correcciones del diccionario.",
"dialog_add_title": "Añadir a tu vocabulario",
"dialog_edit_title": "Editar entrada del diccionario",
"correction_toggle": "Corregir un error de reconocimiento",
@@ -478,6 +489,12 @@
"errors": "Errores"
}
},
+ "voice_mode": {
+ "label": "Modo",
+ "realtime": "Tiempo real",
+ "pipeline": "Pipeline",
+ "unknown": "Desconocido"
+ },
"sessions_view": {
"title": "Transcripción",
"subtitle": "Sesiones de voz recientes, turno por turno.",
@@ -907,7 +924,7 @@
"runtime_realtime": "Sesión actual: Tiempo real",
"runtime_pipeline": "Sesión actual: Pipeline",
"runtime_fallback_pipeline": "La sesión actual volvió a Pipeline; Tiempo real no está atendiendo esta llamada.",
- "cat_brain_desc": "El modelo que impulsa el chat, el enrutamiento y Computer-Use.",
+ "cat_brain_desc": "El modelo que redacta tus respuestas de chat y voz. El modelo de herramientas independiente gestiona las acciones y Computer Use.",
"cat_tts_desc": "La voz con la que habla Jarvis.",
"cat_stt_desc": "Cómo convierte Jarvis tu voz en texto.",
"cat_realtime_desc": "Voz a voz dúplex completo mediante cualquier proveedor de tiempo real configurado, en escritorio o navegador.",
@@ -1009,6 +1026,38 @@
"cleared": "Tool Model restablecido a tu modelo principal",
"vision_note": "Solo se muestran modelos que entienden imágenes: Computer-Use lee la pantalla mediante capturas, un modelo de solo texto no puede controlarlo."
},
+ "permissions": {
+ "group_title": "Permisos de privacidad",
+ "title": "Permisos de macOS",
+ "description": "Concede solo el acceso del sistema necesario para voz, Computer-Use, atajos globales y control de ventanas. Jarvis nunca modifica la base de datos de privacidad de macOS.",
+ "loading": "Comprobando los permisos del sistema…",
+ "load_failed": "No se pudo leer el estado actual de los permisos.",
+ "refresh": "Comprobar de nuevo",
+ "not_required": "Este sistema operativo no requiere permisos de privacidad de escritorio adicionales.",
+ "identity_warning": "Inicia Personal Jarvis desde su paquete de aplicación antes de conceder acceso. macOS vincula los permisos a la identidad exacta de la aplicación.",
+ "restart_required": "Reinicia Personal Jarvis antes de usar el acceso recién concedido.",
+ "restart_now": "Reiniciar ahora",
+ "restarting": "Reiniciando…",
+ "restart_failed": "Personal Jarvis no pudo reiniciarse. Ciérralo y ábrelo de nuevo manualmente.",
+ "request": "Permitir",
+ "open_settings": "Abrir Ajustes",
+ "status": {
+ "granted": "Permitido",
+ "not_determined": "No solicitado",
+ "denied": "Denegado",
+ "restricted": "Restringido",
+ "not_granted": "No permitido",
+ "unavailable": "No disponible",
+ "not_required": "No requerido"
+ },
+ "items": {
+ "microphone": { "title": "Micrófono", "description": "Necesario para la palabra de activación y la entrada de voz local." },
+ "screen_recording": { "title": "Grabación de pantalla", "description": "Necesario para que Computer-Use vea todas las pantallas conectadas." },
+ "accessibility": { "title": "Accesibilidad", "description": "Necesario para clics, escritura, enfoque y control de ventanas fiables." },
+ "input_monitoring": { "title": "Monitorización de entrada", "description": "Necesario para pulsar para hablar y atajos de teclado globales." },
+ "event_posting": { "title": "Control de entrada", "description": "Necesario para que Computer-Use envíe eventos de ratón y teclado." }
+ }
+ },
"settings_view": {
"silence_window": {
"title": "Pausa para pensar",
@@ -1115,7 +1164,7 @@
"derived_name": "Tu asistente se llamará: {0}",
"engine_options": {
"auto": "Automático (recomendado)",
- "openwakeword": "openWakeWord (frases integradas)",
+ "openwakeword": "openWakeWord (modelo personalizado)",
"vosk_kws": "Detección de palabras clave (cualquier frase, igual en todos los equipos)",
"stt_match": "Coincidencia STT (cualquier frase, requiere Whisper local)",
"custom_onnx": "Modelo ONNX personalizado"
@@ -1400,6 +1449,8 @@
"search_modal_placeholder": "Buscar documentos…",
"search_hint": "Escribe un término para buscar…",
"search_loading": "Buscando…",
+ "search_failed": "No se pudo cargar la búsqueda.",
+ "search_retry": "Volver a intentar",
"no_results": "Sin resultados para \"{0}\"",
"for_fulltext": "para la búsqueda completa.",
"could_not_load": "No se pudo cargar el documento.",
@@ -1553,6 +1604,13 @@
"ui_label": "Idioma de la interfaz",
"reply_label": "Idioma de respuesta"
},
+ "permissions": {
+ "title": "Permite el acceso en este Mac",
+ "body": "macOS pide aprobar cada capacidad por separado. Usa los botones de abajo y vuelve aquí; el estado se actualizará automáticamente.",
+ "privacy_note": "Estos avisos proceden de macOS. El instalador no puede aprobarlos de forma silenciosa y Personal Jarvis nunca elude Ajustes del Sistema.",
+ "continue": "Continuar",
+ "text_only": "Continuar solo con texto"
+ },
"wake_word": {
"choice_title": "¿Cómo quieres activar a {name}?",
"choice_body": "Elige lo que mejor se adapte a tu forma de trabajar — puedes cambiarlo después en Ajustes.",
@@ -1561,7 +1619,7 @@
"mode_shortcut_title": "Atajo de teclado",
"mode_shortcut_body": "Sin palabra de activación — mantén pulsada una tecla para hablar y suéltala para enviar (pulsar para hablar).",
"back_to_choice": "Atrás",
- "shortcut_note": "Activarás a {name} con un atajo de teclado en lugar de una palabra de activación. Puedes configurar la tecla exacta en cualquier momento en Ajustes → Palabra de activación.",
+ "shortcut_note": "Activarás a {name} con un atajo de teclado en lugar de una palabra de activación. Puedes configurar la tecla exacta en cualquier momento en Ajustes → Atajos de voz.",
"shortcut_cta": "Continuar",
"title": "Elige tu palabra de activación",
"body": "Elige la palabra que activa tu asistente. \"Hey\" queda fija — tú eliges el resto.",
@@ -1586,6 +1644,7 @@
"good": "Suena bien — tu micrófono captó tu voz con claridad.",
"too_quiet": "Eso sonó muy bajo. Sube el volumen del micrófono o acércate y vuelve a intentarlo.",
"no_device": "No se detectó ningún micrófono — puedes terminar la configuración igualmente y solucionarlo más tarde en Ajustes.",
+ "permission_required": "Concede acceso al micrófono en Permisos antes de ejecutar esta comprobación.",
"error": "No se pudo comprobar el micrófono en este momento."
}
},
@@ -1646,7 +1705,7 @@
"reply_section": "Idioma de Respuesta",
"reply_hint": "En qué idioma habla {name} al responderte. Nombres propios, identificadores de código y términos técnicos se mantienen en su forma original.",
"stt_section": "Idioma de Reconocimiento (Voz)",
- "stt_hint": "En qué idioma se reconoce tu voz hablada y se convierte en texto. Automático detecta por sí solo el idioma que hablas.",
+ "stt_hint": "En qué idioma se reconoce tu voz y se convierte en texto. Automático lo detecta por ti. Tras cambiarlo, termina cualquier llamada Realtime y reinicia Jarvis para el modo Pipeline.",
"options": {
"auto": {
"label": "Automático",
@@ -1810,7 +1869,12 @@
"loading": "Cargando grafo…",
"load_error": "No se pudo cargar el grafo.",
"reset_view_title": "Restablecer el zoom a todos los nodos",
- "center": "Centrar"
+ "center": "Centrar",
+ "relationship_graph": "Grafo de relaciones del wiki",
+ "node_details": "{0} ({1}) · {2} {3}",
+ "backlink_one": "retroenlace",
+ "backlink_many": "retroenlaces",
+ "unresolved": "sin resolver"
},
"tree_sidebar": {
"load_error": "No se pudo cargar el wiki.",
@@ -1890,11 +1954,43 @@
},
"docs_sidebar": {
"title": "Documentación",
- "error": "Error"
+ "error": "Error",
+ "indexing": "Creando el índice local…",
+ "retry": "Intentar de nuevo",
+ "documents": "documentos",
+ "no_results": "No hay documentos coincidentes"
},
"docs_content": {
"prev": "Anterior",
- "next": "Siguiente"
+ "next": "Siguiente",
+ "breadcrumb": "Documentación",
+ "related_guides": "Guías relacionadas",
+ "last_reviewed": "Última revisión:",
+ "review_unavailable": "Fecha de revisión no disponible",
+ "on_this_page": "En esta página",
+ "copy_code": "Copiar código",
+ "code_copied": "Código copiado",
+ "skip_to_content": "Saltar al contenido de la documentación"
+ },
+ "docs_overview": {
+ "eyebrow": "Documentación",
+ "title": "Documentación de Personal Jarvis",
+ "description": "Todo, desde la configuración inicial hasta la arquitectura de la voz. Explora la biblioteca local completa o abre la documentación pública rediseñada.",
+ "online_docs": "Abrir la documentación web rediseñada",
+ "load_failed_title": "No se pudo cargar la documentación",
+ "load_failed_description": "El índice local no estuvo listo a tiempo. Inténtalo de nuevo sin reiniciar la aplicación.",
+ "retry": "Intentar de nuevo",
+ "empty_title": "No se encontraron documentos locales",
+ "empty_description": "La documentación web sigue disponible mediante el botón de arriba.",
+ "local_library": "Empieza en la biblioteca local",
+ "local_library_description": "Acceso rápido y sin conexión a la documentación incluida en esta instalación.",
+ "indexing_title": "Preparando tu documentación",
+ "indexing_description": "Se está leyendo la biblioteca Markdown local y creando la búsqueda de texto completo. Normalmente solo tarda un momento.",
+ "loading_page": "Cargando documento…",
+ "browse_by_topic": "Explorar por tema",
+ "browse_description": "Sigue una ruta de aprendizaje o ve directamente a la función que necesitas.",
+ "guide": "guía",
+ "guides": "guías"
},
"docs_search_modal": {
"navigate": "navegar",
@@ -2226,6 +2322,22 @@
"manual_c": "tú mismo en cualquier momento."
},
"wiki_health": {
+ "capture_aria": "Embudo de captura del wiki de las últimas {0} horas",
+ "capture_window": "Captura de las últimas {0} h",
+ "capture_reviewed": "Revisadas",
+ "capture_candidate_reviews": "Revisiones productivas",
+ "capture_candidate_facts": "Candidatos",
+ "capture_writes": "Escrituras",
+ "capture_noop": "Sin cambios",
+ "capture_rejected": "Rechazados",
+ "capture_skipped": "Omitidos",
+ "capture_pending": "Pendientes",
+ "capture_filtered": "Filtrados",
+ "capture_empty": "Vacíos",
+ "capture_failed": "Fallidos",
+ "capture_in_progress": "En curso",
+ "capture_session_sweeps": "Revisiones de sesión",
+ "capture_store_unavailable": "Almacén de captura no disponible",
"checking": "Comprobando el estado del wiki…",
"unavailable": "Comprobación del estado del wiki no disponible",
"vault_prefix": "Bóveda: {0}",
@@ -2398,10 +2510,11 @@
},
"feedback": {
"discord_cta_title": "Repórtalo en nuestro Discord",
- "discord_cta_subtitle": "Únete a #bug-reports y publica tu error, idea o pregunta directamente.",
- "discord_cta_button": "Abrir Discord",
+ "discord_cta_subtitle": "Abre #report-a-bug y publica tu error, idea o pregunta directamente.",
+ "discord_cta_button": "Abrir #report-a-bug",
+ "discord_join_button": "Unirse primero a Discord",
"or_send_here": "o envíalo desde aquí",
- "subtitle": "Reporta un error, comparte una idea o haz una pregunta — va directo a nuestro Discord.",
+ "subtitle": "Abre nuestro Discord para reportar un error, compartir una idea o hacer una pregunta.",
"type_label": "Tipo",
"type_bug": "Error",
"type_idea": "Idea",
diff --git a/jarvis/ui/web/frontend/src/lib/keyFormat.test.ts b/jarvis/ui/web/frontend/src/lib/keyFormat.test.ts
index a4cd7c6f90..aaebbeb65d 100644
--- a/jarvis/ui/web/frontend/src/lib/keyFormat.test.ts
+++ b/jarvis/ui/web/frontend/src/lib/keyFormat.test.ts
@@ -50,6 +50,9 @@ describe("expectedKindForSecret", () => {
expect(expectedKindForSecret("grok_api_key")).toBe("xai");
expect(expectedKindForSecret("cartesia_api_key")).toBe("cartesia");
expect(expectedKindForSecret("elevenlabs_api_key")).toBe("elevenlabs");
+ expect(expectedKindForSecret("jarvis_agent_openai_api_key")).toBe("openai");
+ expect(expectedKindForSecret("jarvis_agent_gemini_api_key")).toBe("google-aistudio");
+ expect(expectedKindForSecret("realtime_grok_api_key")).toBe("xai");
});
it("returns null for slots without a known key format", () => {
diff --git a/jarvis/ui/web/frontend/src/lib/keyFormat.ts b/jarvis/ui/web/frontend/src/lib/keyFormat.ts
index 653f816535..8d9eafa344 100644
--- a/jarvis/ui/web/frontend/src/lib/keyFormat.ts
+++ b/jarvis/ui/web/frontend/src/lib/keyFormat.ts
@@ -77,17 +77,26 @@ export function detectKeyFormat(value: string): KeyFormatHint | null {
export function expectedKindForSecret(secretKey: string): KeyFormatKind | null {
switch (secretKey) {
case "gemini_api_key":
+ case "realtime_gemini_api_key":
+ case "jarvis_agent_gemini_api_key":
return "google-aistudio";
case "anthropic_api_key":
+ case "jarvis_agent_anthropic_api_key":
return "anthropic";
case "openai_api_key":
case "codex_openai_api_key":
+ case "realtime_openai_api_key":
+ case "jarvis_agent_openai_api_key":
return "openai";
case "openrouter_api_key":
+ case "jarvis_agent_openrouter_api_key":
return "openrouter";
case "nvidia_api_key":
+ case "jarvis_agent_nvidia_api_key":
return "nvidia";
case "grok_api_key":
+ case "realtime_grok_api_key":
+ case "jarvis_agent_grok_api_key":
return "xai";
case "cartesia_api_key":
return "cartesia";
diff --git a/jarvis/ui/web/frontend/src/lib/ws.ts b/jarvis/ui/web/frontend/src/lib/ws.ts
index f40cd450a1..ab43022fb2 100644
--- a/jarvis/ui/web/frontend/src/lib/ws.ts
+++ b/jarvis/ui/web/frontend/src/lib/ws.ts
@@ -1,6 +1,6 @@
/**
* WebSocket client with exponential-backoff reconnect (500ms → 10s cap).
- * Ping/Pong every 30s. Token via window.__JARVIS_TOKEN as query param.
+ * Ping/Pong every 30s. Authentication uses the same-origin HttpOnly cookie.
*
* Aside from the singleton onMessage callback (used by useWebSocket for the
* Zustand store), additional consumers can attach via subscribe() — needed by
@@ -16,12 +16,6 @@ export interface WSClientOptions {
onClose?: (code?: number) => void;
}
-declare global {
- interface Window {
- __JARVIS_TOKEN?: string;
- }
-}
-
const MIN_BACKOFF = 500;
const MAX_BACKOFF = 10_000;
const PING_INTERVAL = 30_000;
@@ -49,9 +43,7 @@ export class WSClient {
private defaultUrl(): string {
const proto = window.location.protocol === "https:" ? "wss" : "ws";
const host = window.location.host;
- const token = window.__JARVIS_TOKEN;
- const query = token ? `?token=${encodeURIComponent(token)}` : "";
- return `${proto}://${host}/ws${query}`;
+ return `${proto}://${host}/ws`;
}
connect(): void {
diff --git a/jarvis/ui/web/frontend/src/main.tsx b/jarvis/ui/web/frontend/src/main.tsx
index cdf7fa11f4..45cd5e38d3 100644
--- a/jarvis/ui/web/frontend/src/main.tsx
+++ b/jarvis/ui/web/frontend/src/main.tsx
@@ -4,6 +4,7 @@ import { QueryClient, QueryClientProvider } from "@tanstack/react-query";
import App from "./App";
import { ThemeProvider } from "./hooks/useTheme";
import { ViewErrorBoundary } from "./components/ViewErrorBoundary";
+import { AuthGate } from "./components/AuthGate";
import "./index.css";
// When the frontend is rebuilt while a tab is open, the old main bundle still
@@ -39,7 +40,9 @@ ReactDOM.createRoot(document.getElementById("root")!).render(
resetKey="root"
onRecover={() => window.location.reload()}
>
- <App />
+ <AuthGate>
+ <App />
+ </AuthGate>
</ViewErrorBoundary>
</ThemeProvider>
</QueryClientProvider>
diff --git a/jarvis/ui/web/frontend/src/schema/ws.test.ts b/jarvis/ui/web/frontend/src/schema/ws.test.ts
index 46fcfe9ec2..c398c2b995 100644
--- a/jarvis/ui/web/frontend/src/schema/ws.test.ts
+++ b/jarvis/ui/web/frontend/src/schema/ws.test.ts
@@ -1,5 +1,5 @@
import { describe, expect, it } from "vitest";
-import { WSCommand } from "./ws";
+import { WSCommand, WSWelcome } from "./ws";
describe("WSCommand mission.inject", () => {
it("validates a mission.inject command", () => {
@@ -11,3 +11,21 @@ describe("WSCommand mission.inject", () => {
expect(parsed.action).toBe("mission.inject");
});
});
+
+describe("WSWelcome", () => {
+ it("does not retain legacy session tokens", () => {
+ const parsed = WSWelcome.parse({
+ type: "welcome",
+ session_id: "session-1",
+ version: "1.0.0",
+ token: "must-not-reach-the-client",
+ });
+
+ expect(parsed).toEqual({
+ type: "welcome",
+ session_id: "session-1",
+ version: "1.0.0",
+ });
+ expect("token" in parsed).toBe(false);
+ });
+});
diff --git a/jarvis/ui/web/frontend/src/schema/ws.ts b/jarvis/ui/web/frontend/src/schema/ws.ts
index bd69b3aa62..a8f35efe96 100644
--- a/jarvis/ui/web/frontend/src/schema/ws.ts
+++ b/jarvis/ui/web/frontend/src/schema/ws.ts
@@ -20,7 +20,6 @@ export const WSWelcome = z.object({
type: z.literal("welcome"),
session_id: z.string(),
version: z.string().optional(),
- token: z.string().nullable().optional(),
});
export type WSWelcomeT = z.infer<typeof WSWelcome>;
diff --git a/jarvis/ui/web/frontend/src/store/events.test.ts b/jarvis/ui/web/frontend/src/store/events.test.ts
index 62e8fdfa15..9847f8a7bb 100644
--- a/jarvis/ui/web/frontend/src/store/events.test.ts
+++ b/jarvis/ui/web/frontend/src/store/events.test.ts
@@ -11,7 +11,18 @@
* otherwise a single answer renders as two identical bubbles.
*/
import { beforeEach, describe, expect, it } from "vitest";
-import { useEventStore, type ChatMessage } from "@/store/events";
+import {
+ initialSectionFromSearch,
+ useEventStore,
+ type ChatMessage,
+} from "@/store/events";
+
+describe("initial section deep links", () => {
+ it("opens Docs when a guide slug is present", () => {
+ expect(initialSectionFromSearch("?doc=voice-conversations")).toBe("docs");
+ expect(initialSectionFromSearch("")).toBe("chats");
+ });
+});
function msg(
id: string,
diff --git a/jarvis/ui/web/frontend/src/store/events.ts b/jarvis/ui/web/frontend/src/store/events.ts
index 6ab2fc8725..0ab0703b59 100644
--- a/jarvis/ui/web/frontend/src/store/events.ts
+++ b/jarvis/ui/web/frontend/src/store/events.ts
@@ -71,6 +71,10 @@ export function isSectionId(value: unknown): value is SectionId {
return typeof value === "string" && SECTION_IDS.includes(value as SectionId);
}
+export function initialSectionFromSearch(search: string): SectionId {
+ return new URLSearchParams(search).has("doc") ? "docs" : "chats";
+}
+
export const SECTION_LABELS: Record<SectionId, string> = {
chats: "Chats",
agents: "Agents",
@@ -294,7 +298,9 @@ export const useEventStore = create<EventStore>((set, get) => ({
voiceReady: false,
connected: false,
wsWarming: true,
- activeSection: "chats",
+ activeSection: initialSectionFromSearch(
+ typeof window === "undefined" ? "" : window.location.search,
+ ),
transcription: "",
transcriptionFinal: true,
toasts: [],
diff --git a/jarvis/ui/web/frontend/src/views/SettingsView.tsx b/jarvis/ui/web/frontend/src/views/SettingsView.tsx
index 85951fca5b..ae63888896 100644
--- a/jarvis/ui/web/frontend/src/views/SettingsView.tsx
+++ b/jarvis/ui/web/frontend/src/views/SettingsView.tsx
@@ -15,6 +15,7 @@ import { Button } from "@/components/ui/button";
import { OverlayTaskbarGroup } from "@/views/settings/OverlayTaskbarGroup";
import { LanguagesGroup } from "@/views/settings/LanguagesGroup";
import { AppSettingsGroup } from "@/views/settings/AppSettingsGroup";
+import { PermissionsPanel } from "@/views/settings/PermissionsPanel";
import { RealtimeVoiceGroup } from "@/views/settings/RealtimeVoiceGroup";
import { SilenceWindowGroup } from "@/views/settings/SilenceWindowGroup";
import { VolumeGroup } from "@/views/settings/VolumeGroup";
@@ -99,6 +100,7 @@ export function SettingsView() {
<div className="flex-1 overflow-y-auto scrollbar-jarvis p-6">
<LanguagesGroup />
<AppSettingsGroup />
+ <PermissionsPanel />
<RealtimeVoiceGroup />
<SystemPromptGroup />
<WakeWordPanel />
diff --git a/jarvis/ui/web/frontend/src/views/SkillCreateDialog.test.tsx b/jarvis/ui/web/frontend/src/views/SkillCreateDialog.test.tsx
new file mode 100644
index 0000000000..4c89374de2
--- /dev/null
+++ b/jarvis/ui/web/frontend/src/views/SkillCreateDialog.test.tsx
@@ -0,0 +1,190 @@
+import { QueryClient, QueryClientProvider } from "@tanstack/react-query";
+import {
+ cleanup,
+ fireEvent,
+ render,
+ screen,
+ waitFor,
+} from "@testing-library/react";
+import { afterEach, beforeEach, describe, expect, it, vi } from "vitest";
+
+import { setUiLanguage } from "@/i18n";
+import { SkillCreateDialog } from "@/views/SkillCreateDialog";
+
+function response(body: unknown, status = 200): Response {
+ return {
+ ok: status >= 200 && status < 300,
+ status,
+ json: async () => body,
+ } as Response;
+}
+
+function renderDialog(onClose = vi.fn(), onCreated = vi.fn()) {
+ const client = new QueryClient({
+ defaultOptions: {
+ queries: { retry: false },
+ mutations: { retry: false },
+ },
+ });
+ render(
+ <QueryClientProvider client={client}>
+ <SkillCreateDialog
+ open
+ onClose={onClose}
+ onCreated={onCreated}
+ />
+ </QueryClientProvider>,
+ );
+ return { onClose, onCreated };
+}
+
+beforeEach(() => {
+ setUiLanguage("en");
+});
+
+afterEach(() => {
+ cleanup();
+ vi.unstubAllGlobals();
+ vi.restoreAllMocks();
+});
+
+describe("SkillCreateDialog creation routes", () => {
+ it("commits an AI-generated skill through the draft-enforcing creator route", async () => {
+ const draft = {
+ name: "AI Routine",
+ description: "Original description",
+ category: "productivity",
+ tags: ["routine"],
+ triggers: [
+ { type: "schedule", cron: "0 8 * * *" },
+ { type: "voice", pattern: "start routine" },
+ ],
+ requires_tools: ["calendar.read"],
+ risk_policy: { default_tier: "ask" },
+ body: "## AI Routine\n\nRun the reviewed routine.\n",
+ questions: [],
+ assumptions: ["A calendar is connected."],
+ test_prompts: ["Start my routine"],
+ frontmatter: { state: "active" },
+ };
+ const fetchMock = vi.fn(
+ async (input: RequestInfo | URL, init?: RequestInit) => {
+ const url = String(input);
+ if (url === "/api/skills/creator/draft") {
+ return response({
+ draft,
+ skill_md: "---\nstate: draft\n---\n",
+ validation: {
+ ok: true,
+ state: "validated",
+ errors: [],
+ warnings: [],
+ },
+ brain_used: true,
+ });
+ }
+ if (url === "/api/skills/creator/commit") {
+ return response({ name: "Reviewed Routine", state: "draft" });
+ }
+ throw new Error(`Unexpected ${init?.method ?? "GET"} ${url}`);
+ },
+ );
+ vi.stubGlobal("fetch", fetchMock);
+ const { onClose, onCreated } = renderDialog();
+
+ fireEvent.change(
+ screen.getByPlaceholderText(/Summarize my open browser tabs/i),
+ { target: { value: "Build a safe morning routine" } },
+ );
+ fireEvent.click(
+ screen.getByRole("button", { name: "Write the whole skill with AI" }),
+ );
+
+ await screen.findByDisplayValue("AI Routine");
+ fireEvent.change(screen.getByPlaceholderText("Skill name"), {
+ target: { value: "Reviewed Routine" },
+ });
+ fireEvent.change(
+ screen.getByPlaceholderText("One sentence about what it does"),
+ { target: { value: "Reviewed description" } },
+ );
+ fireEvent.change(screen.getByPlaceholderText(/## My Skill/), {
+ target: { value: "## Reviewed Routine\n\nRun only reviewed steps.\n" },
+ });
+ fireEvent.change(
+ screen.getByPlaceholderText("e.g. start the morning routine"),
+ { target: { value: "run reviewed routine" } },
+ );
+ fireEvent.click(
+ screen.getByRole("button", { name: "Create skill" }),
+ );
+
+ await waitFor(() => expect(onCreated).toHaveBeenCalledWith("Reviewed Routine"));
+ expect(onClose).toHaveBeenCalledOnce();
+
+ const draftCall = fetchMock.mock.calls.find(
+ ([url]) => String(url) === "/api/skills/creator/draft",
+ );
+ expect(draftCall?.[1]).toEqual(expect.objectContaining({ method: "POST" }));
+ const commitCall = fetchMock.mock.calls.find(
+ ([url]) => String(url) === "/api/skills/creator/commit",
+ );
+ expect(commitCall).toBeDefined();
+ expect(commitCall?.[1]).toEqual(expect.objectContaining({ method: "POST" }));
+ const commitBody = JSON.parse(
+ String((commitCall?.[1] as RequestInit | undefined)?.body),
+ );
+ expect(commitBody.draft).toEqual(
+ expect.objectContaining({
+ name: "Reviewed Routine",
+ description: "Reviewed description",
+ body: "## Reviewed Routine\n\nRun only reviewed steps.",
+ tags: ["routine"],
+ requires_tools: ["calendar.read"],
+ risk_policy: { default_tier: "ask" },
+ triggers: [
+ { type: "schedule", cron: "0 8 * * *" },
+ { type: "voice", pattern: "run reviewed routine" },
+ ],
+ }),
+ );
+ expect(
+ fetchMock.mock.calls.some(([url]) => String(url) === "/api/skills"),
+ ).toBe(false);
+ });
+
+ it("keeps manual creation on the manual endpoint", async () => {
+ const fetchMock = vi.fn(
+ async (input: RequestInfo | URL, init?: RequestInit) => {
+ const url = String(input);
+ if (url === "/api/skills") {
+ return response({ name: "Manual Skill", state: "validated" });
+ }
+ throw new Error(`Unexpected ${init?.method ?? "GET"} ${url}`);
+ },
+ );
+ vi.stubGlobal("fetch", fetchMock);
+ const { onCreated } = renderDialog();
+
+ fireEvent.change(screen.getByPlaceholderText("Skill name"), {
+ target: { value: "Manual Skill" },
+ });
+ fireEvent.change(screen.getByPlaceholderText(/## My Skill/), {
+ target: { value: "## Manual Skill\n\nFollow the manual instructions.\n" },
+ });
+ fireEvent.click(
+ screen.getByRole("button", { name: "Create skill" }),
+ );
+
+ await waitFor(() => expect(onCreated).toHaveBeenCalledWith("Manual Skill"));
+ expect(fetchMock).toHaveBeenCalledWith(
+ "/api/skills",
+ expect.objectContaining({ method: "POST" }),
+ );
+ expect(
+ fetchMock.mock.calls.some(([url]) =>
+ String(url).startsWith("/api/skills/creator/"),
+ ),
+ ).toBe(false);
+ });
+});
diff --git a/jarvis/ui/web/frontend/src/views/SkillCreateDialog.tsx b/jarvis/ui/web/frontend/src/views/SkillCreateDialog.tsx
index ec4ea48d6e..091f61f0c1 100644
--- a/jarvis/ui/web/frontend/src/views/SkillCreateDialog.tsx
+++ b/jarvis/ui/web/frontend/src/views/SkillCreateDialog.tsx
@@ -4,19 +4,26 @@
* Two ways in, one robust outcome:
* - "Write the whole skill with AI": you describe what the skill should do and
* the AI writes the COMPLETE skill (name, instructions, voice trigger). It
- * lands fully filled in for a quick review, then one click creates it. If a
- * brain is reachable it fills rich content; if not it returns a deterministic
- * starter template and the form stays editable (headless-VPS safe).
+ * lands fully filled in for a quick review, then one click commits it as an
+ * inactive draft through the creator service. If a brain is reachable it
+ * fills rich content; if not it returns a deterministic starter template and
+ * the form stays editable (headless-VPS safe).
* - Fill the form yourself and hit Create — the deterministic POST /api/skills
* path, no brain needed.
- * Either way Create persists exactly what you see.
+ * Visible form edits are preserved on both paths. Creator metadata that is not
+ * shown in this compact form stays attached to an AI draft.
*/
import { useEffect, useState } from "react";
import { X, Sparkles, Loader2, Plus, AlertTriangle, Check } from "lucide-react";
import { Button } from "@/components/ui/button";
import { ScrollArea } from "@/components/ui/scroll-area";
import { useT } from "@/i18n";
-import { useCreateSkill, useDraftSkill } from "@/hooks/useSkills";
+import {
+ type SkillCreatorDraft,
+ useCommitSkillDraft,
+ useCreateSkill,
+ useDraftSkill,
+} from "@/hooks/useSkills";
/**
* A body carries real instructions only if it has at least one non-heading,
@@ -41,6 +48,7 @@ export function SkillCreateDialog({
}) {
const t = useT();
const draftSkill = useDraftSkill();
+ const commitSkillDraft = useCommitSkillDraft();
const createSkill = useCreateSkill();
const [intent, setIntent] = useState("");
@@ -51,10 +59,10 @@ export function SkillCreateDialog({
const [trigger, setTrigger] = useState("");
const [error, setError] = useState<string | null>(null);
const [aiNote, setAiNote] = useState<string | null>(null);
- // True once the AI has written the whole skill into the fields — drives the
- // "review then create" affordance (success banner + highlighted Create).
- const [aiDrafted, setAiDrafted] = useState(false);
+ const [aiDraft, setAiDraft] = useState<SkillCreatorDraft | null>(null);
const [aiOk, setAiOk] = useState(false);
+ // Drives the "review then create" affordance without duplicating state.
+ const aiDrafted = aiDraft !== null;
// Reset all state whenever the dialog (re)opens, and wire Escape-to-close.
useEffect(() => {
@@ -67,7 +75,7 @@ export function SkillCreateDialog({
setTrigger("");
setError(null);
setAiNote(null);
- setAiDrafted(false);
+ setAiDraft(null);
setAiOk(false);
const onKey = (e: KeyboardEvent) => {
if (e.key === "Escape") onClose();
@@ -81,7 +89,7 @@ export function SkillCreateDialog({
const runDraft = async () => {
setError(null);
setAiNote(null);
- setAiDrafted(false);
+ setAiDraft(null);
try {
const res = await draftSkill.mutateAsync({
intent,
@@ -90,6 +98,7 @@ export function SkillCreateDialog({
trigger_hint: trigger,
});
const d = res.draft;
+ setAiDraft(d);
setName(d.name ?? name);
setDescription(d.description ?? "");
setCategory(d.category ?? category);
@@ -97,7 +106,6 @@ export function SkillCreateDialog({
const firstVoice = (d.triggers ?? []).find((tr) => tr.type === "voice");
if (firstVoice?.pattern) setTrigger(firstVoice.pattern);
setAiOk(res.brain_used);
- setAiDrafted(true);
setAiNote(
res.brain_used
? t("skill_create_dialog.ai_done_review")
@@ -132,15 +140,27 @@ export function SkillCreateDialog({
const finalDescription =
description.trim() || intent.trim().slice(0, 200);
try {
- const detail = await createSkill.mutateAsync({
+ const visibleFields = {
name: name.trim(),
description: finalDescription,
category: category.trim() || "general",
body: finalBody,
triggers: trigger.trim()
- ? [{ type: "voice", pattern: trigger.trim() }]
+ ? [{ type: "voice" as const, pattern: trigger.trim() }]
: [],
- });
+ };
+ const detail = aiDraft
+ ? await commitSkillDraft.mutateAsync({
+ ...aiDraft,
+ ...visibleFields,
+ // The form reviews one voice trigger. Preserve any non-voice
+ // triggers generated by the creator while replacing that field.
+ triggers: [
+ ...aiDraft.triggers.filter((item) => item.type !== "voice"),
+ ...visibleFields.triggers,
+ ],
+ })
+ : await createSkill.mutateAsync(visibleFields);
onCreated?.(detail.name);
onClose();
} catch (e) {
@@ -148,7 +168,10 @@ export function SkillCreateDialog({
}
};
- const busy = draftSkill.isPending || createSkill.isPending;
+ const busy =
+ draftSkill.isPending ||
+ commitSkillDraft.isPending ||
+ createSkill.isPending;
return (
<div
@@ -329,7 +352,7 @@ export function SkillCreateDialog({
: "gap-1.5"
}
>
- {createSkill.isPending ? (
+ {createSkill.isPending || commitSkillDraft.isPending ? (
<Loader2 className="h-3.5 w-3.5 animate-spin" />
) : (
<Plus className="h-3.5 w-3.5" />
diff --git a/jarvis/ui/web/frontend/src/views/feedback/FeedbackView.test.tsx b/jarvis/ui/web/frontend/src/views/feedback/FeedbackView.test.tsx
index 26069804ff..1d772c0655 100644
--- a/jarvis/ui/web/frontend/src/views/feedback/FeedbackView.test.tsx
+++ b/jarvis/ui/web/frontend/src/views/feedback/FeedbackView.test.tsx
@@ -2,7 +2,8 @@
* Component tests for FeedbackView.
*
* The Feedback section is Discord-only: a single button forwards the user to the
- * #bug-reports channel via {@link openExternalUrl}. There is no in-app form.
+ * #report-a-bug forum via {@link openExternalUrl}. A separate permanent invite
+ * is available for people who have not joined the server yet.
*
* Verifies:
* - The Discord call-to-action (heading + button) renders.
@@ -25,11 +26,12 @@ describe("FeedbackView", () => {
it("renders the Discord call-to-action with a forward button", () => {
render(<FeedbackView />);
- // A button that forwards to Discord must be present.
- const buttons = screen.getAllByRole("button");
- expect(buttons.length).toBeGreaterThan(0);
- // The CTA button text references opening Discord.
- expect(screen.getByText(/open discord/i)).toBeTruthy();
+ expect(
+ screen.getByRole("button", { name: "Open #report-a-bug" }),
+ ).toBeTruthy();
+ expect(
+ screen.getByRole("button", { name: "Join Discord first" }),
+ ).toBeTruthy();
});
it("does NOT render the old in-app form (Discord-only)", () => {
@@ -40,18 +42,33 @@ describe("FeedbackView", () => {
expect(screen.queryByRole("button", { name: /submit/i })).toBeNull();
});
- it("clicking the button opens the Discord invite via the external-open bridge", () => {
+ it("opens the bug forum directly via the external-open bridge", () => {
const openSpy = vi
.spyOn(openExternal, "openExternalUrl")
.mockResolvedValue(undefined);
render(<FeedbackView />);
- fireEvent.click(screen.getByText(/open discord/i));
+ fireEvent.click(
+ screen.getByRole("button", { name: "Open #report-a-bug" }),
+ );
expect(openSpy).toHaveBeenCalledTimes(1);
- // Must forward to a discord.gg invite link.
expect(openSpy).toHaveBeenCalledWith(
- expect.stringContaining("discord.gg/"),
+ "https://discord.com/channels/1511102439066177656/1521522036709789736",
);
});
+
+ it("keeps a permanent server invite for people who have not joined yet", () => {
+ const openSpy = vi
+ .spyOn(openExternal, "openExternalUrl")
+ .mockResolvedValue(undefined);
+
+ render(<FeedbackView />);
+ fireEvent.click(
+ screen.getByRole("button", { name: "Join Discord first" }),
+ );
+
+ expect(openSpy).toHaveBeenCalledTimes(1);
+ expect(openSpy).toHaveBeenCalledWith("https://discord.gg/x7USduHxbc");
+ });
});
diff --git a/jarvis/ui/web/frontend/src/views/feedback/FeedbackView.tsx b/jarvis/ui/web/frontend/src/views/feedback/FeedbackView.tsx
index ef4b58e327..a05521a833 100644
--- a/jarvis/ui/web/frontend/src/views/feedback/FeedbackView.tsx
+++ b/jarvis/ui/web/frontend/src/views/feedback/FeedbackView.tsx
@@ -6,8 +6,9 @@ import { openExternalUrl } from "@/lib/openExternal";
/**
* The Feedback section — bugs, ideas, and questions are reported exclusively in
- * the project's Discord #bug-reports channel. The button forwards the user
- * straight there via a public, never-expiring invite link.
+ * the project's Discord #report-a-bug forum. The primary button opens the forum
+ * directly; a separate permanent invite remains available for people who have
+ * not joined the server yet.
*
* The button uses {@link openExternalUrl} rather than a bare
* `<a target="_blank">`, because the desktop shell (WebView2) silently drops
@@ -16,10 +17,14 @@ import { openExternalUrl } from "@/lib/openExternal";
* `window.open` on a remote/VPS browser).
*/
-// Public, never-expiring Discord invite that drops the visitor directly into the
-// #bug-reports channel of the PersonalJarvis server. An invite link is meant to
-// be shared, so it is safe to ship in the client.
-const DISCORD_INVITE_URL = "https://discord.gg/9QesfUrtq";
+// Discord's Community onboarding redirects invite links to #welcome even when
+// the invite was created for a different channel. Existing members therefore
+// need the canonical channel URL for a guaranteed direct hop to the bug forum.
+const DISCORD_BUG_FORUM_URL =
+ "https://discord.com/channels/1511102439066177656/1521522036709789736";
+
+// Public, never-expiring server invite for people who are not members yet.
+const DISCORD_INVITE_URL = "https://discord.gg/x7USduHxbc";
/** The official Discord brand mark (inline so it renders without an asset). */
function DiscordIcon({ className }: { className?: string }) {
@@ -52,13 +57,22 @@ export function FeedbackView() {
<p className="mb-6 text-sm text-muted-foreground">
{t("feedback.discord_cta_subtitle")}
</p>
- <button
- type="button"
- onClick={() => void openExternalUrl(DISCORD_INVITE_URL)}
- className="w-full rounded-lg bg-[#5865F2] px-4 py-3 text-sm font-semibold text-white transition hover:bg-[#4752c4]"
- >
- {t("feedback.discord_cta_button")}
- </button>
+ <div className="space-y-3">
+ <button
+ type="button"
+ onClick={() => void openExternalUrl(DISCORD_BUG_FORUM_URL)}
+ className="w-full rounded-lg bg-[#5865F2] px-4 py-3 text-sm font-semibold text-white transition hover:bg-[#4752c4]"
+ >
+ {t("feedback.discord_cta_button")}
+ </button>
+ <button
+ type="button"
+ onClick={() => void openExternalUrl(DISCORD_INVITE_URL)}
+ className="w-full rounded-lg border border-[#5865F2]/40 px-4 py-2.5 text-sm font-medium text-[#8b94ff] transition hover:border-[#5865F2]/70 hover:bg-[#5865F2]/10"
+ >
+ {t("feedback.discord_join_button")}
+ </button>
+ </div>
</div>
</div>
</div>
diff --git a/jarvis/ui/web/frontend/src/views/socials/SocialLinkRow.tsx b/jarvis/ui/web/frontend/src/views/socials/SocialLinkRow.tsx
index 8a0a0cbfb0..12d375f9cc 100644
--- a/jarvis/ui/web/frontend/src/views/socials/SocialLinkRow.tsx
+++ b/jarvis/ui/web/frontend/src/views/socials/SocialLinkRow.tsx
@@ -1,5 +1,6 @@
import { ExternalLink } from "lucide-react";
+import { openExternalUrl } from "@/lib/openExternal";
import type { SocialEntry } from "./api";
/**
@@ -12,9 +13,12 @@ export function SocialLinkRow({ entry }: { entry: SocialEntry }) {
return (
<a
href={entry.url}
- target="_blank"
+ onClick={(event) => {
+ event.preventDefault();
+ void openExternalUrl(entry.url);
+ }}
rel="noopener noreferrer"
- className="group flex items-center gap-4 rounded-xl border border-border bg-card/40 p-4 transition-all hover:border-primary/40 hover:bg-card/60 focus:outline-none"
+ className="group flex items-center gap-4 rounded-xl border border-border bg-card/40 p-4 transition-all hover:border-primary/40 hover:bg-card/60 focus-visible:outline-none focus-visible:ring-2 focus-visible:ring-ring"
>
<span className="flex min-w-0 flex-1 flex-col">
<span className="flex items-center gap-1.5 truncate font-medium text-foreground">
diff --git a/jarvis/ui/web/frontend/src/views/socials/SocialTile.tsx b/jarvis/ui/web/frontend/src/views/socials/SocialTile.tsx
index 40963c094b..15f5e2e1b1 100644
--- a/jarvis/ui/web/frontend/src/views/socials/SocialTile.tsx
+++ b/jarvis/ui/web/frontend/src/views/socials/SocialTile.tsx
@@ -2,6 +2,7 @@ import { ChevronRight, ExternalLink } from "lucide-react";
import { cn } from "@/lib/utils";
import { useT } from "@/i18n";
+import { openExternalUrl } from "@/lib/openExternal";
import { BrandIcon } from "./BrandIcon";
import { BRANDS, platformLabel } from "./brands";
import type { SocialEntry } from "./api";
@@ -59,9 +60,15 @@ export function SocialTile({
return (
<a
href={single.url}
- target="_blank"
+ onClick={(event) => {
+ event.preventDefault();
+ void openExternalUrl(single.url);
+ }}
rel="noopener noreferrer"
- className={cn(shell, "focus:outline-none")}
+ className={cn(
+ shell,
+ "focus-visible:outline-none focus-visible:ring-2 focus-visible:ring-ring",
+ )}
>
{glow}
{inner}
@@ -75,7 +82,10 @@ export function SocialTile({
type="button"
onClick={() => onOpenDetail(group.platform)}
aria-label={`${name}, ${group.entries.length} ${t("socials.links")}`}
- className={cn(shell, "text-left")}
+ className={cn(
+ shell,
+ "text-left focus-visible:outline-none focus-visible:ring-2 focus-visible:ring-ring",
+ )}
>
{glow}
{inner}
diff --git a/jarvis/ui/web/frontend/src/views/socials/SocialsView.test.tsx b/jarvis/ui/web/frontend/src/views/socials/SocialsView.test.tsx
index d9ebe9c38a..2912d91a1a 100644
--- a/jarvis/ui/web/frontend/src/views/socials/SocialsView.test.tsx
+++ b/jarvis/ui/web/frontend/src/views/socials/SocialsView.test.tsx
@@ -11,6 +11,7 @@ import { afterEach, describe, expect, it, vi } from "vitest";
import { cleanup, fireEvent, render, screen } from "@testing-library/react";
import { SocialsView } from "@/views/socials/SocialsView";
+import * as openExternal from "@/lib/openExternal";
interface RouteResult {
status?: number;
@@ -51,7 +52,7 @@ const DISCORD = {
id: "d1",
platform: "discord",
label: "Discord",
- url: "https://discord.gg/UPu6pFWrJ",
+ url: "https://discord.gg/x7USduHxbc",
enabled: true,
order: 0,
};
@@ -79,20 +80,27 @@ afterEach(() => {
describe("SocialsView (grouped, read-only)", () => {
it("a single-link platform is a direct link; a multi-link platform is a button", async () => {
+ const openSpy = vi
+ .spyOn(openExternal, "openExternalUrl")
+ .mockResolvedValue(undefined);
installFetchMock({
"GET /api/socials": () => ({ body: { entries: [DISCORD, GITHUB_REPO, GITHUB_PROFILE] } }),
});
render(<SocialsView />);
const discord = (await screen.findByRole("link", { name: /discord/i })) as HTMLAnchorElement;
- expect(discord.href).toContain("discord.gg/UPu6pFWrJ");
- expect(discord.target).toBe("_blank");
+ expect(discord.href).toContain("discord.gg/x7USduHxbc");
+ fireEvent.click(discord);
+ expect(openSpy).toHaveBeenCalledWith(DISCORD.url);
expect(screen.queryByRole("link", { name: /github/i })).toBeNull();
expect(screen.getByRole("button", { name: /github/i })).toBeTruthy();
});
it("clicking a multi-link platform opens a detail page listing all its links", async () => {
+ const openSpy = vi
+ .spyOn(openExternal, "openExternalUrl")
+ .mockResolvedValue(undefined);
installFetchMock({
"GET /api/socials": () => ({ body: { entries: [DISCORD, GITHUB_REPO, GITHUB_PROFILE] } }),
});
@@ -104,8 +112,9 @@ describe("SocialsView (grouped, read-only)", () => {
const profile = screen.getByRole("link", { name: /profile/i }) as HTMLAnchorElement;
expect(repo.href).toContain("PersonalJarvis");
expect(profile.href).toContain("github.com/PersonalJarvis");
- expect(repo.target).toBe("_blank");
expect(repo.rel).toContain("noopener");
+ fireEvent.click(repo);
+ expect(openSpy).toHaveBeenCalledWith(GITHUB_REPO.url);
});
it("is read-only: no add tile and no edit/delete controls (grid or detail)", async () => {
diff --git a/jarvis/ui/web/frontend/src/views/socials/SocialsView.tsx b/jarvis/ui/web/frontend/src/views/socials/SocialsView.tsx
index e2caacbd63..2deed07a1d 100644
--- a/jarvis/ui/web/frontend/src/views/socials/SocialsView.tsx
+++ b/jarvis/ui/web/frontend/src/views/socials/SocialsView.tsx
@@ -65,7 +65,10 @@ export function SocialsView() {
<div className="mx-auto w-full max-w-4xl p-6">
{loading ? (
<div className="flex items-center justify-center py-20 text-muted-foreground">
- <Loader2 className="h-5 w-5 animate-spin" />
+ <Loader2
+ className="h-5 w-5 animate-spin motion-reduce:animate-none"
+ aria-hidden="true"
+ />
</div>
) : error ? (
<p className="py-20 text-center text-sm text-destructive">{error}</p>
diff --git a/jarvis/ui/web/launcher.py b/jarvis/ui/web/launcher.py
index 1cf99d77eb..a343089572 100644
--- a/jarvis/ui/web/launcher.py
+++ b/jarvis/ui/web/launcher.py
@@ -259,6 +259,33 @@ def _fast_auth_token_env() -> str:
return "JARVIS_UI_TOKEN"
+def _fast_vite_dev_url(force_dev: bool) -> str | None:
+ """Read the trusted Vite origin without loading the full config graph."""
+ import contextlib
+
+ configured_dev = False
+ vite_url = "http://localhost:5173"
+ with contextlib.suppress(Exception):
+ import tomllib
+
+ override = os.environ.get("JARVIS_CONFIG")
+ if override:
+ path = override
+ else:
+ repo_root = os.path.dirname(
+ os.path.dirname(os.path.dirname(os.path.dirname(os.path.abspath(__file__))))
+ )
+ path = os.path.join(repo_root, "jarvis.toml")
+ if os.path.exists(path):
+ with open(path, "rb") as fh:
+ ui = tomllib.load(fh).get("ui", {})
+ configured_dev = bool(ui.get("dev_mode", False))
+ value = ui.get("vite_dev_url")
+ if isinstance(value, str) and value:
+ vite_url = value
+ return vite_url if force_dev or configured_dev else None
+
+
async def _run_headless(args) -> int:
"""Headless **fast boot** (the "serve first, init behind" contract).
@@ -786,6 +813,8 @@ def _serve_bootstrap_with_retry(
host: str,
port: int,
*,
+ session_token: str | None = None,
+ vite_dev_url: str | None = None,
attempts: int = 5,
delay: float = 0.4,
_factory=None,
@@ -812,7 +841,11 @@ def _serve_bootstrap_with_retry(
factory = _factory if _factory is not None else FastBootstrap
for attempt in range(attempts):
- bootstrap = factory()
+ bootstrap = (
+ factory(session_token=session_token, vite_dev_url=vite_dev_url)
+ if session_token is not None
+ else factory()
+ )
try:
loop.run_until_complete(bootstrap.serve(host, port))
return bootstrap
@@ -847,7 +880,13 @@ def _desktop_backend_main(args, port: int, token: str, holder: dict, app_ready)
# bind before concluding "already running" (the lock below is the real
# arbiter). Without this, the fresh restart instance bounces and the app
# "shuts down but never comes back".
- bootstrap = _serve_bootstrap_with_retry(loop, "127.0.0.1", port)
+ bootstrap = _serve_bootstrap_with_retry(
+ loop,
+ "127.0.0.1",
+ port,
+ session_token=token,
+ vite_dev_url=_fast_vite_dev_url(bool(args.dev)),
+ )
if bootstrap is None:
holder["already_running"] = True
app_ready.set()
diff --git a/jarvis/ui/web/outputs_routes.py b/jarvis/ui/web/outputs_routes.py
index 5cbca45fb3..5e3a2d0f5e 100644
--- a/jarvis/ui/web/outputs_routes.py
+++ b/jarvis/ui/web/outputs_routes.py
@@ -10,6 +10,7 @@ abstraction one level deeper (the `tasks/<mission_id>/workspace/` subdir).
Keeping the dir listing as the primary index lets users open the worktree
even when the mission row is gone (DB pruned, recovery cleanup).
"""
+
from __future__ import annotations
import asyncio
@@ -38,9 +39,7 @@ logger = logging.getLogger(__name__)
router = APIRouter(prefix="/api/outputs", tags=["outputs"])
-_SLUG_RE = re.compile(
- r"^(?P<ts>\d{8}T\d{6})__(?P<utterance>.+?)__(?P<short>[0-9a-f]{6,16})$"
-)
+_SLUG_RE = re.compile(r"^(?P<ts>\d{8}T\d{6})__(?P<utterance>.+?)__(?P<short>[0-9a-f]{6,16})$")
# 2026-05-16: Mission-Manager also creates persistent state directories named
# `mission_<8-char-hex>` (the short-prefix of the UUID). These are NOT the
@@ -63,6 +62,7 @@ def _outputs_root(request: Request) -> Path:
if cached is not None:
return Path(cached)
from jarvis.missions.isolation.worktree import resolve_outputs_root
+
here = Path(__file__).resolve()
repo_root = here.parent.parent.parent.parent
return resolve_outputs_root(repo_root)
@@ -85,9 +85,7 @@ def _parse_slug(name: str) -> dict[str, Any]:
try:
from datetime import datetime, timezone
- dt = datetime.strptime(ts, "%Y%m%dT%H%M%S").replace(
- tzinfo=timezone.utc
- )
+ dt = datetime.strptime(ts, "%Y%m%dT%H%M%S").replace(tzinfo=timezone.utc)
started_at: float | None = dt.timestamp()
except ValueError:
started_at = None
@@ -204,9 +202,7 @@ async def _mission_status_lookup(
row = await cur.fetchone()
await cur.close()
except Exception as exc: # noqa: BLE001
- logger.debug(
- "outputs: mission DB lookup failed for %s: %s", prefix, exc
- )
+ logger.debug("outputs: mission DB lookup failed for %s: %s", prefix, exc)
continue
if row is None:
continue
@@ -248,9 +244,7 @@ _STATE_TO_STATUS: dict[str, str] = {
# Terminal mission-state *values* (string form). A re-run child counts as a
# "live" continuation only while its state is NOT in this set. Single source of
# truth = the state machine (mirrors ``missions_routes._TERMINAL_STATE_VALUES``).
-_TERMINAL_STATE_VALUES: frozenset[str] = frozenset(
- s.value for s in MissionState if is_terminal(s)
-)
+_TERMINAL_STATE_VALUES: frozenset[str] = frozenset(s.value for s in MissionState if is_terminal(s))
async def _live_continuation_map(request: Request) -> dict[str, str]:
@@ -330,9 +324,7 @@ async def list_outputs(request: Request) -> dict[str, Any]:
)
except OSError as exc:
logger.warning("outputs: listdir failed for %s: %s", root, exc)
- raise HTTPException(
- status_code=500, detail=f"Outputs root not readable: {exc}"
- ) from exc
+ raise HTTPException(status_code=500, detail=f"Outputs root not readable: {exc}") from exc
sessions: list[dict[str, Any]] = []
# Map dir-name → mission-id prefix derived from the dir-name itself.
@@ -407,9 +399,7 @@ async def list_outputs(request: Request) -> dict[str, Any]:
if child_id:
summary["active_child_id"] = child_id
summary["active_child_slug"] = f"mission_{child_id[:13]}"
- summary["utterance"] = (
- summary["utterance"] or mission_row.get("prompt")
- )
+ summary["utterance"] = summary["utterance"] or mission_row.get("prompt")
# Running missions tick wall-clock from created_ms: right after
# dispatch created_ms == updated_ms, so updated-minus-created
# rendered a frozen "RUNNING 0.0s" until the next mission event
@@ -421,9 +411,7 @@ async def list_outputs(request: Request) -> dict[str, Any]:
if mission_row["updated_ms"] and not running:
summary["completed_at"] = mission_row["updated_ms"] / 1000.0
if mission_row["created_ms"]:
- end_ms = (
- time.time() * 1000.0 if running else mission_row["updated_ms"]
- )
+ end_ms = time.time() * 1000.0 if running else mission_row["updated_ms"]
if end_ms:
summary["duration_s"] = max(
0.0,
@@ -501,11 +489,7 @@ def _is_deliverable_relpath(rel_parts: tuple[str, ...]) -> bool:
# Shortest valid deliverable: tasks/<id>/artifacts/files/<name> (5 parts).
if len(rel_parts) < 5:
return False
- if not (
- rel_parts[0] == "tasks"
- and rel_parts[2] == "artifacts"
- and rel_parts[3] == "files"
- ):
+ if not (rel_parts[0] == "tasks" and rel_parts[2] == "artifacts" and rel_parts[3] == "files"):
return False
# Defence-in-depth (2026-06-21): hide tool-scratch the archive's --ignored
# union may have re-imported on a PRE-FIX mission — a browser/QA worker's
@@ -535,9 +519,7 @@ def _resolve_artifact_target(request: Request, slug: str, path: str) -> Path:
try:
rel_parts = target.relative_to(base).parts
except ValueError as exc:
- raise HTTPException(
- status_code=404, detail=f"unknown file: {path}"
- ) from exc
+ raise HTTPException(status_code=404, detail=f"unknown file: {path}") from exc
if not _is_deliverable_relpath(rel_parts):
raise HTTPException(status_code=404, detail=f"unknown file: {path}")
if not target.is_file():
@@ -548,11 +530,36 @@ def _resolve_artifact_target(request: Request, slug: str, path: str) -> Path:
def _is_text_filename(name: str) -> bool:
"""Heuristic — file extensions whose contents are safe to inline-preview."""
lower = name.lower()
- return lower.endswith((
- ".md", ".txt", ".json", ".jsonl", ".yaml", ".yml", ".toml",
- ".log", ".patch", ".diff", ".py", ".ts", ".tsx", ".js", ".jsx",
- ".html", ".css", ".csv", ".env", ".cfg", ".ini", ".sh", ".ps1",
- )) or "." not in lower
+ return (
+ lower.endswith(
+ (
+ ".md",
+ ".txt",
+ ".json",
+ ".jsonl",
+ ".yaml",
+ ".yml",
+ ".toml",
+ ".log",
+ ".patch",
+ ".diff",
+ ".py",
+ ".ts",
+ ".tsx",
+ ".js",
+ ".jsx",
+ ".html",
+ ".css",
+ ".csv",
+ ".env",
+ ".cfg",
+ ".ini",
+ ".sh",
+ ".ps1",
+ )
+ )
+ or "." not in lower
+ )
@router.get("/{slug}/artifacts")
@@ -623,9 +630,7 @@ async def list_output_artifacts(slug: str, request: Request) -> dict[str, Any]:
}
if entry["is_text"] and stat.st_size <= _ARTIFACT_PREVIEW_BYTES * 4:
try:
- preview = child.read_text(
- encoding="utf-8", errors="replace"
- )
+ preview = child.read_text(encoding="utf-8", errors="replace")
if len(preview) > _ARTIFACT_PREVIEW_BYTES:
preview = preview[:_ARTIFACT_PREVIEW_BYTES] + "\n…"
entry["preview"] = preview
@@ -636,18 +641,14 @@ async def list_output_artifacts(slug: str, request: Request) -> dict[str, Any]:
break
except OSError as exc:
logger.warning("outputs: rglob failed for %s: %s", target, exc)
- raise HTTPException(
- status_code=500, detail=f"artifact listing failed: {exc}"
- ) from exc
+ raise HTTPException(status_code=500, detail=f"artifact listing failed: {exc}") from exc
files.sort(key=lambda f: f["mtime"], reverse=True)
return {"files": files}
@router.get("/{slug}/files/{path:path}/raw")
-async def get_output_artifact_raw(
- slug: str, path: str, request: Request
-) -> dict[str, Any]:
+async def get_output_artifact_raw(slug: str, path: str, request: Request) -> dict[str, Any]:
"""Return the full UTF-8 decoded contents of a single artifact file.
Sandboxed to `<outputs_root>/<slug>/`. Returns JSON `{path, size,
@@ -665,9 +666,7 @@ async def get_output_artifact_raw(
try:
rel_parts = target.relative_to(base).parts
except ValueError as exc:
- raise HTTPException(
- status_code=400, detail="path escapes session dir"
- ) from exc
+ raise HTTPException(status_code=400, detail="path escapes session dir") from exc
# Defense-in-depth: serve ONLY genuine deliverables, mirroring the listing
# endpoint's `_is_deliverable_relpath` allowlist. The listing no longer
# surfaces claude_config/.codex/diff/log paths, so the UI never links to
@@ -682,9 +681,7 @@ async def get_output_artifact_raw(
try:
size = target.stat().st_size
except OSError as exc:
- raise HTTPException(
- status_code=500, detail=f"stat failed: {exc}"
- ) from exc
+ raise HTTPException(status_code=500, detail=f"stat failed: {exc}") from exc
# 1 MiB hard ceiling on inline text fetch — anything bigger should be
# opened on the desktop (the UI offers that path).
@@ -692,15 +689,11 @@ async def get_output_artifact_raw(
truncated = size > max_inline
try:
if _is_text_filename(target.name):
- text = target.read_text(
- encoding="utf-8", errors="replace"
- )[:max_inline]
+ text = target.read_text(encoding="utf-8", errors="replace")[:max_inline]
else:
text = f"<binary file, {size} bytes — open on desktop>"
except OSError as exc:
- raise HTTPException(
- status_code=500, detail=f"read failed: {exc}"
- ) from exc
+ raise HTTPException(status_code=500, detail=f"read failed: {exc}") from exc
return {
"path": path,
"size": size,
@@ -725,10 +718,11 @@ async def download_output_artifact(
target = _resolve_artifact_target(request, slug, path)
media_type, _ = mimetypes.guess_type(target.name)
headers = {"X-Content-Type-Options": "nosniff"}
- # Serving an HTML artifact inline renders it in the app origin; lock it down
- # with the same no-script CSP the /view route uses so a worker-authored .html
- # can't execute JS against the app.
- if disposition == "inline" and (media_type or "").startswith("text/html"):
+ # HTML and SVG are active document formats when rendered inline in the app
+ # origin. Apply the same no-script CSP used by the /view route so a
+ # worker-authored artifact cannot execute code against the app.
+ active_document_types = {"text/html", "image/svg+xml"}
+ if disposition == "inline" and media_type in active_document_types:
headers["Content-Security-Policy"] = VIEW_CSP
return FileResponse(
target,
@@ -740,9 +734,7 @@ async def download_output_artifact(
@router.get("/{slug}/files/{path:path}/view")
-async def view_output_artifact(
- slug: str, path: str, request: Request
-) -> HTMLResponse:
+async def view_output_artifact(slug: str, path: str, request: Request) -> HTMLResponse:
"""Render a text/markdown artifact as a standalone styled HTML page.
Markdown is rendered to HTML; other text is shown escaped in <pre>. Carries a
@@ -762,9 +754,7 @@ async def view_output_artifact(
try:
text = target.read_text(encoding="utf-8", errors="replace")
except OSError as exc:
- raise HTTPException(
- status_code=500, detail=f"read failed: {exc}"
- ) from exc
+ raise HTTPException(status_code=500, detail=f"read failed: {exc}") from exc
return HTMLResponse(
render_artifact_html(target.name, text),
headers={
@@ -775,9 +765,7 @@ async def view_output_artifact(
@router.post("/{slug}/files/{path:path}/reveal")
-async def reveal_output_artifact(
- slug: str, path: str, request: Request
-) -> dict[str, Any]:
+async def reveal_output_artifact(slug: str, path: str, request: Request) -> dict[str, Any]:
"""Open the OS file manager with the artifact selected. Local desktop only."""
if not getattr(request.app.state, "native_file_actions", False):
raise HTTPException(status_code=404, detail="native file actions unavailable")
@@ -789,9 +777,7 @@ async def reveal_output_artifact(
@router.post("/{slug}/files/{path:path}/open-native")
-async def open_output_artifact_native(
- slug: str, path: str, request: Request
-) -> dict[str, Any]:
+async def open_output_artifact_native(slug: str, path: str, request: Request) -> dict[str, Any]:
"""Open the artifact with the OS default application. Local desktop only."""
if not getattr(request.app.state, "native_file_actions", False):
raise HTTPException(status_code=404, detail="native file actions unavailable")
@@ -823,7 +809,12 @@ _OPENER_EDITORS: list[tuple[str, str]] = [
# Browsers tried, in order, for the "browser" opener (first installed wins).
_BROWSER_CANDIDATES: tuple[str, ...] = (
- "chrome", "msedge", "firefox", "brave", "opera", "vivaldi",
+ "chrome",
+ "msedge",
+ "firefox",
+ "brave",
+ "opera",
+ "vivaldi",
)
@@ -955,9 +946,7 @@ def get_preferred_opener(request: Request) -> dict[str, Any]:
@router.put("/preferred-opener")
-def put_preferred_opener(
- body: PreferredOpenerBody, request: Request
-) -> dict[str, Any]:
+def put_preferred_opener(body: PreferredOpenerBody, request: Request) -> dict[str, Any]:
"""Persist the remembered opener id (or ``""`` to clear it).
Validated against the closed opener set — never a raw path. Persists to
@@ -1002,18 +991,14 @@ async def open_artifact_with(
target = _resolve_artifact_target(request, slug, path)
resolved = _resolve_opener(opener)
if resolved is None:
- raise HTTPException(
- status_code=409, detail=f"opener not available: {opener}"
- )
+ raise HTTPException(status_code=409, detail=f"opener not available: {opener}")
from jarvis.platform import open_path
kind, value = resolved
if kind == "default":
opened = await asyncio.to_thread(open_path.open_file, target)
else:
- opened = await asyncio.to_thread(
- open_path.open_file_with, target, kind, value
- )
+ opened = await asyncio.to_thread(open_path.open_file_with, target, kind, value)
return {"opened": bool(opened), "opener": opener}
diff --git a/jarvis/ui/web/profile_routes.py b/jarvis/ui/web/profile_routes.py
index 09ea94035b..0711d6ee3f 100644
--- a/jarvis/ui/web/profile_routes.py
+++ b/jarvis/ui/web/profile_routes.py
@@ -225,7 +225,7 @@ async def get_profile(request: Request) -> dict[str, Any]:
"user": {
"name": profile.name,
"meta": profile.meta,
- "path": str(profile.path),
+ "path": profile.path.name,
},
"people": people_list,
"reviews_count": reviews_count,
@@ -355,7 +355,7 @@ async def get_raw(request: Request) -> dict[str, Any]:
Shape:
{
"content": str, # full Markdown content
- "path": str, # absolute path (display purpose)
+ "path": str, # safe display name, never a user directory
"mtime_ms": int|null, # filesystem modification time (UI cache-bust)
"size_bytes": int # display helper
}
@@ -373,7 +373,7 @@ async def get_raw(request: Request) -> dict[str, Any]:
except FileNotFoundError:
return {
"content": "",
- "path": str(path),
+ "path": path.name,
"mtime_ms": None,
"size_bytes": 0,
}
@@ -383,7 +383,7 @@ async def get_raw(request: Request) -> dict[str, Any]:
return {
"content": content,
- "path": str(path),
+ "path": path.name,
"mtime_ms": int(stat.st_mtime * 1000),
"size_bytes": stat.st_size,
}
@@ -481,7 +481,7 @@ async def put_raw(request: Request, body: RawWriteBody) -> dict[str, Any]:
return {
"ok": True,
- "path": str(path),
+ "path": path.name,
"mtime_ms": mtime_ms,
"size_bytes": size_bytes,
"reparsed": reparsed,
diff --git a/jarvis/ui/web/provider_routes.py b/jarvis/ui/web/provider_routes.py
index 5700662739..fc0797c959 100644
--- a/jarvis/ui/web/provider_routes.py
+++ b/jarvis/ui/web/provider_routes.py
@@ -70,12 +70,12 @@ ALLOWED_SECRET_KEYS: frozenset[str] = frozenset(s.key for s in WIZARD_SECRETS)
class SecretBody(BaseModel):
- value: str = Field(..., min_length=1, description="Roher Secret-Wert (API-Key, Token, ...)")
+ value: str = Field(..., min_length=1, description="Raw secret value (API key, token, etc.)")
class SwitchBody(BaseModel):
provider: str = Field(..., min_length=1)
- persist: bool = Field(default=True, description="In jarvis.toml schreiben")
+ persist: bool = Field(default=True, description="Write the selection to jarvis.toml")
class CodexBinaryPathBody(BaseModel):
@@ -788,22 +788,32 @@ def _worker_usable(provider: str) -> bool:
"""
p = (provider or "").lower()
try:
+ from jarvis.core.config import get_jarvis_agent_secret
+
if p in _CODEX_SUBAGENT_SLUGS or p in {"codex", "openai-codex"}:
- connected = bool(CodexAuthService(_codex_binary_path()).status().connected)
- return connected or _has_openai_brain_credential()
+ status = CodexAuthService(_codex_binary_path()).status()
+ has_key = bool(
+ cfg_mod.get_secret(
+ "codex_openai_api_key", env_fallback="CODEX_OPENAI_API_KEY"
+ )
+ )
+ return bool(status.connected or (status.installed and has_key))
if p == "antigravity":
from jarvis.google_cli.auth_service import GoogleCliAuthService
- return bool(GoogleCliAuthService().status().connected)
+ return bool(
+ GoogleCliAuthService().status().connected
+ or get_jarvis_agent_secret("gemini")
+ )
if p in {"claude-api", "claude"}:
from jarvis.claude_auth import ClaudeAuthService
st = ClaudeAuthService().status()
return bool(
- getattr(st, "connected", False) or getattr(st, "api_key_present", False)
+ getattr(st, "connected", False)
+ or get_jarvis_agent_secret("claude-api")
)
- spec = get_spec(p)
- return bool(spec is not None and _is_credential_present(spec))
+ return bool(get_jarvis_agent_secret(p))
except Exception: # noqa: BLE001
return False
@@ -1927,7 +1937,14 @@ async def set_secret_value(key: str, body: SecretBody, request: Request) -> dict
async def delete_secret_value(key: str, request: Request) -> dict[str, Any]:
if key not in ALLOWED_SECRET_KEYS:
raise HTTPException(status_code=404, detail=f"Unknown secret key: {key}")
- cfg_mod.delete_secret(key) # Idempotent when no value exists.
+ if not cfg_mod.delete_secret(key):
+ raise HTTPException(
+ status_code=500,
+ detail=(
+ "Credential deletion could not be verified. The platform "
+ "credential store may be locked or unavailable."
+ ),
+ )
await _emit(request, SecretConfigured(key=key, action="delete"))
_invalidate_section_health_state(request)
return {"ok": True, "key": key}
@@ -2012,7 +2029,8 @@ async def brain_switch(body: SwitchBody, request: Request) -> dict[str, Any]:
from jarvis.google_cli.auth_service import GoogleCliAuthService
def _antigravity_connected() -> bool:
- return GoogleCliAuthService().status().connected
+ status = GoogleCliAuthService().status()
+ return status.connected and status.mode == "oauth-personal"
if not await asyncio.to_thread(_antigravity_connected):
raise HTTPException(
@@ -2667,14 +2685,24 @@ async def jarvis_agent_switch(body: SwitchBody, request: Request) -> dict[str, A
# it is not in JARVIS_TO_WORKER_SLUG. Handle it explicitly: it can be backed by
# the ChatGPT subscription (OAuth, ``codex login``) OR an OpenAI API key.
if provider in _CODEX_SUBAGENT_SLUGS:
- def _codex_connected() -> bool:
- return CodexAuthService(_codex_binary_path(request)).status().connected
+ def _codex_status(): # noqa: ANN202
+ return CodexAuthService(_codex_binary_path(request)).status()
- codex_connected = await asyncio.to_thread(_codex_connected)
+ codex_status = await asyncio.to_thread(_codex_status)
+ codex_connected = bool(codex_status.connected)
has_key = bool(
- cfg_mod.get_secret("codex_openai_api_key")
- or cfg_mod.get_provider_secret("codex")
+ cfg_mod.get_secret(
+ "codex_openai_api_key", env_fallback="CODEX_OPENAI_API_KEY"
+ )
)
+ if not codex_status.installed:
+ raise HTTPException(
+ status_code=409,
+ detail=(
+ "Codex CLI is not installed. Install it or choose the OpenAI "
+ "Jarvis-Agent card for key-only, in-process execution."
+ ),
+ )
if not (codex_connected or has_key):
raise HTTPException(
status_code=409,
@@ -2720,12 +2748,11 @@ async def jarvis_agent_switch(body: SwitchBody, request: Request) -> dict[str, A
# Dual billing (mirror of codex): the Google subscription OAuth login OR
# a Gemini API key (per token). Either is enough to run the worker.
def _antigravity_connected() -> bool:
- return GoogleCliAuthService().status().connected
+ status = GoogleCliAuthService().status()
+ return status.connected and status.mode == "oauth-personal"
antigravity_connected = await asyncio.to_thread(_antigravity_connected)
- antigravity_key = bool(
- cfg_mod.get_secret("gemini_api_key", env_fallback="GEMINI_API_KEY")
- )
+ antigravity_key = bool(cfg_mod.get_jarvis_agent_secret("gemini"))
if not (antigravity_connected or antigravity_key):
raise HTTPException(
status_code=409,
@@ -2773,7 +2800,7 @@ async def jarvis_agent_switch(body: SwitchBody, request: Request) -> dict[str, A
# ClaudeDirectWorker from ~/.claude/.credentials.json) as a credential, so a
# fresh Claude-Max user who only ran `claude login` (no stored API key) can
# still select it — mirrors the codex/antigravity OAuth branches above.
- has_credential = bool(cfg_mod.get_provider_secret(provider))
+ has_credential = bool(cfg_mod.get_jarvis_agent_secret(provider))
if not has_credential and provider == "claude-api":
try:
from jarvis.missions.isolation.env import read_live_claude_oauth_token
@@ -2786,7 +2813,7 @@ async def jarvis_agent_switch(body: SwitchBody, request: Request) -> dict[str, A
status_code=409,
detail=(
f"{provider} has no stored credential. "
- "Add the key on its Brain provider card before activating it."
+ "Add a key on its Jarvis-Agent card before activating it."
),
)
diff --git a/jarvis/ui/web/provider_spec.py b/jarvis/ui/web/provider_spec.py
index 16f0782a8f..1abfa98efc 100644
--- a/jarvis/ui/web/provider_spec.py
+++ b/jarvis/ui/web/provider_spec.py
@@ -410,13 +410,12 @@ PROVIDERS: tuple[ProviderSpec, ...] = (
label="OpenAI Realtime",
tier="realtime",
auth_mode="api_key",
- secret_keys=("openai_api_key",),
+ secret_keys=("realtime_openai_api_key",),
dashboard_url="https://platform.openai.com/api-keys",
credential_help=(
- "Uses your OpenAI API key (shared with the GPT brain / Whisper STT) "
- "to power the realtime voice mode — one model that listens, thinks and "
- "speaks over a single connection. Available in the browser and in the "
- "desktop voice runtime; the desktop path is intentionally half-duplex."
+ "OpenAI API key dedicated to Realtime Voice. It is not reused by "
+ "Brain, STT, or Jarvis-Agents. Existing shared OpenAI credentials "
+ "remain a compatibility fallback until a dedicated key is saved."
),
),
ProviderSpec(
@@ -424,12 +423,12 @@ PROVIDERS: tuple[ProviderSpec, ...] = (
label="Gemini Live",
tier="realtime",
auth_mode="api_key",
- secret_keys=("gemini_api_key",),
+ secret_keys=("realtime_gemini_api_key",),
dashboard_url="https://aistudio.google.com/app/apikey",
credential_help=(
- "Google AI Studio key (AIza/AQ.), shared with the Gemini brain, to "
- "power Google's Live realtime voice in the browser and desktop runtime. "
- "This adapter currently uses API-key authentication."
+ "Google AI Studio key dedicated to Gemini Live. It is not reused by "
+ "the Gemini Brain or Jarvis-Agents. Existing shared Gemini credentials "
+ "remain a compatibility fallback until a dedicated key is saved."
),
),
ProviderSpec(
@@ -437,13 +436,13 @@ PROVIDERS: tuple[ProviderSpec, ...] = (
label="xAI Grok Realtime",
tier="realtime",
auth_mode="api_key",
- secret_keys=("grok_api_key",),
+ secret_keys=("realtime_grok_api_key",),
dashboard_url="https://console.x.ai/",
signup_url="https://grok.com/",
credential_help=(
- "Uses your xAI API key (starts with xai-), shared with the Grok "
- "brain and xAI Text to Speech, to power Grok's full-duplex Voice "
- "Agent API. API usage is billed separately through the xAI Console."
+ "xAI API key dedicated to Grok Realtime Voice. It is not reused by "
+ "the Grok Brain, TTS, or Jarvis-Agents. Existing shared xAI credentials "
+ "remain a compatibility fallback until a dedicated key is saved."
),
),
)
diff --git a/jarvis/ui/web/schema.py b/jarvis/ui/web/schema.py
index 92ea0e423b..eec48ae6c9 100644
--- a/jarvis/ui/web/schema.py
+++ b/jarvis/ui/web/schema.py
@@ -44,7 +44,6 @@ class WSWelcome(BaseModel):
type: Literal["welcome"] = "welcome"
session_id: str
version: str
- token: str | None = None
# ----------------------------------------------------------------------
diff --git a/jarvis/ui/web/server.py b/jarvis/ui/web/server.py
index c5da9e7724..0152725c02 100644
--- a/jarvis/ui/web/server.py
+++ b/jarvis/ui/web/server.py
@@ -50,6 +50,7 @@ from .schema import (
WSWelcome,
event_to_ws_envelope,
)
+from .surface_security import SurfaceSecurity
if TYPE_CHECKING:
import uvicorn
@@ -180,12 +181,38 @@ class WebServer:
# CORS only for the Vite dev server — production serves the frontend
# from dist/ and needs no cross-origin requests.
+ vite_dev_url = self.cfg.ui.vite_dev_url if self.cfg.ui.dev_mode else None
+ if vite_dev_url:
+ app.add_middleware(
+ CORSMiddleware,
+ allow_origins=[vite_dev_url],
+ allow_credentials=True,
+ allow_methods=["*"],
+ allow_headers=["*"],
+ )
+
+ twilio_cfg = getattr(
+ getattr(self.cfg, "integrations", None), "twilio", None
+ )
+ public_urls = tuple(
+ value
+ for value in (
+ getattr(twilio_cfg, "public_base_url", ""),
+ getattr(
+ getattr(self.cfg, "marketplace", None),
+ "public_callback_base_url",
+ "",
+ ),
+ )
+ if value
+ )
+ # The security boundary must wrap every router and both HTTP and WS.
+ # It is added after CORS so Starlette places it outside the CORS layer:
+ # hostile Host/Origin values never reach route code or preflight logic.
app.add_middleware(
- CORSMiddleware,
- allow_origins=[self.cfg.ui.vite_dev_url],
- allow_credentials=True,
- allow_methods=["*"],
- allow_headers=["*"],
+ SurfaceSecurity,
+ vite_dev_url=vite_dev_url,
+ public_urls=public_urls,
)
self._register_rest_routes(app)
@@ -195,8 +222,9 @@ class WebServer:
# (``reload_sync`` — globbing + FTS indexing, ~hundreds of ms) off the
# boot critical path. The scans run after uvicorn is listening (see
# ``start()``); nothing at BOOT_READY needs the skill/doc lists (the
- # brain builds its own skill context; the Skills/Docs views tolerate an
- # empty registry until the reload lands). Each entry is (label, registry).
+ # brain builds its own skill context; the Skills view tolerates an empty
+ # registry, while Docs can trigger its own shared on-demand load). Each
+ # entry is (label, registry).
self._pending_reloads: list[tuple[str, Any]] = []
# Skill-registry setup: bootstrap (copy builtin skills) + create the
@@ -204,7 +232,7 @@ class WebServer:
# watchdog watcher is only activated in ``start()``.
self._setup_skill_registry(app)
- # Doc registry: Markdown discovery under ``docs/`` + siblings,
+ # Doc registry: curated reader-guide discovery under ``docs/product/``,
# FTS5 index. The watchdog is likewise only activated in ``start()``.
self._setup_doc_registry(app)
@@ -266,6 +294,7 @@ class WebServer:
)
from .onboarding_routes import router as onboarding_router
from .outputs_routes import router as outputs_router
+ from .permissions_routes import router as permissions_router
from .preview_routes import router as preview_router
from .profile_routes import router as profile_router
from .provider_routes import router as provider_router
@@ -306,6 +335,7 @@ class WebServer:
app.include_router(control_router)
app.include_router(profile_router)
app.include_router(settings_router)
+ app.include_router(permissions_router)
# In-app updater (GET status / POST apply). Managed-install only — see
# jarvis/ui/web/update_routes.py; refuses to self-reset a dev checkout.
app.include_router(update_router)
@@ -377,18 +407,9 @@ class WebServer:
# Default: no recorder wired up — _init_session_stack() in start()
# sets this once it succeeds.
app.state.session_store = None
- # Phase-6 mission stack — the auth token before all others, so the
- # browser can even fetch it; then REST + WS + PTY.
+ # Phase-6 mission stack — token issuance is behind SurfaceSecurity;
+ # mission WS and PTY then perform their narrower hello-frame auth too.
app.include_router(missions_auth_router)
- # Seed the desktop session token (injected as window.__JARVIS_TOKEN by
- # the fast-boot path) into the token store. The fast-boot token is a RAW
- # secrets.token_urlsafe that is never issued via GET /token, so without
- # this it fails validate_token → 4401 on every token-gated WebSocket —
- # which hung the "Make It Yours" workspace PTY terminals forever on
- # "connecting" (missions survive via the unauthenticated main /ws).
- from .missions_auth import register_session_token_from_env
-
- register_session_token_from_env(self.cfg.ui.auth_token_env)
app.include_router(missions_router)
app.include_router(missions_ws_router)
app.include_router(missions_pty_router)
@@ -650,7 +671,7 @@ class WebServer:
The index DB lives under ``user_data_dir()/data/docs_index.sqlite``.
Failure cases (read-only FS, index-DB lock) are not fatal — the UI
- then shows "No docs available" instead of crashing.
+ surfaces a retryable load error instead of crashing.
"""
try:
from jarvis.core.paths import default_doc_roots, docs_index_db_path
@@ -664,9 +685,8 @@ class WebServer:
)
self._doc_registry = registry
app.state.doc_registry = registry
- # reload_sync() (glob 200+ docs + FTS index build, ~hundreds of ms)
- # is deferred off the boot critical path — run after uvicorn is
- # listening (start()).
+ # The initial Markdown scan + FTS index build is deferred off the
+ # boot critical path and runs after uvicorn is listening (start()).
self._pending_reloads.append(("DocRegistry", registry))
logger.info(
"DocRegistry created (scan deferred) for {} roots", len(roots)
@@ -910,36 +930,41 @@ class WebServer:
binary_detected = cand
break
- from jarvis.core.config import get_secret
+ from jarvis.core.config import (
+ get_jarvis_agent_secret,
+ get_provider_secret,
+ get_secret,
+ jarvis_agent_secret_slot,
+ )
+ from jarvis.ui.web.provider_spec import get_spec
- secret_key_overrides = {
- "claude-api": "anthropic_api_key",
- "openrouter": "openrouter_api_key",
- "openai": "openai_api_key",
- "gemini": "gemini_api_key",
- }
mapping_rows = []
for mapping in MAPPINGS:
- secret_key = secret_key_overrides.get(
- mapping.jarvis, f"{mapping.jarvis}_api_key"
- )
+ slot = jarvis_agent_secret_slot(mapping.jarvis)
+ secret_key = slot[0] if slot else None
try:
- key_set = bool(get_secret(secret_key, mapping.env_var))
+ dedicated_key_set = bool(
+ slot and get_secret(slot[0], env_fallback=slot[1])
+ )
+ shared_key_set = bool(get_provider_secret(mapping.jarvis))
except Exception: # noqa: BLE001
- key_set = False
+ dedicated_key_set = False
+ shared_key_set = False
+ api_key_set = dedicated_key_set or shared_key_set
+ oauth_connected = False
# Claude Max users authenticate the subagent via the LIVE OAuth
# login in ~/.claude/.credentials.json (read by ClaudeDirectWorker),
# not a stored API key — count that as configured so a fresh
# Claude-Max user (only ran `claude login`) is not falsely locked.
- if not key_set and mapping.jarvis == "claude-api":
+ if mapping.jarvis == "claude-api":
try:
from jarvis.missions.isolation.env import (
read_live_claude_oauth_token,
)
- key_set = bool(read_live_claude_oauth_token())
+ oauth_connected = bool(read_live_claude_oauth_token())
except Exception: # noqa: BLE001
- key_set = False
+ oauth_connected = False
# claude-api is dual-billed like Codex/Antigravity: the Claude Max
# subscription (claude CLI OAuth login) OR an Anthropic API key.
# Every other MAPPINGS provider bills per token on an API account.
@@ -948,13 +973,36 @@ class WebServer:
if mapping.jarvis == "claude-api"
else "api"
)
+ spec = get_spec(mapping.jarvis)
+ credential_source = (
+ "dedicated"
+ if dedicated_key_set
+ else "legacy_shared"
+ if shared_key_set
+ else "oauth"
+ if oauth_connected
+ else "none"
+ )
mapping_rows.append(
{
"jarvis": mapping.jarvis,
"worker_slug": mapping.worker_slug,
"env_var": mapping.env_var,
"env_fallback": mapping.env_fallback,
- "key_set": key_set,
+ "key_set": api_key_set or oauth_connected,
+ "api_key_set": api_key_set,
+ "dedicated_key_set": dedicated_key_set,
+ "shared_key_set": shared_key_set,
+ "oauth_connected": oauth_connected,
+ "credential_source": credential_source,
+ "secret_key": secret_key,
+ "dashboard_url": spec.dashboard_url if spec else None,
+ "credential_help": (
+ f"Dedicated Jarvis-Agent key for {spec.label}. "
+ "It is not used by Brain or Realtime."
+ if spec
+ else "Dedicated Jarvis-Agent API key."
+ ),
"is_active_brain": mapping.jarvis == primary,
"billing": row_billing,
}
@@ -970,12 +1018,18 @@ class WebServer:
codex_bin = (
getattr(getattr(cfg, "codex", None), "binary_path", "") or None
)
- codex_connected = CodexAuthService(codex_bin).status().connected
+ codex_status = CodexAuthService(codex_bin).status()
+ codex_connected = codex_status.connected
+ codex_installed = codex_status.installed
except Exception: # noqa: BLE001
codex_connected = False
+ codex_installed = False
try:
codex_key = bool(
- get_secret("codex_openai_api_key", env_fallback="OPENAI_API_KEY")
+ get_secret(
+ "codex_openai_api_key",
+ env_fallback="CODEX_OPENAI_API_KEY",
+ )
)
except Exception: # noqa: BLE001
codex_key = False
@@ -985,7 +1039,20 @@ class WebServer:
"openclaw": "codex-cli (direct)",
"env_var": "ChatGPT-OAuth",
"env_fallback": "OPENAI_API_KEY",
- "key_set": codex_connected or codex_key,
+ "key_set": codex_connected or (codex_installed and codex_key),
+ "api_key_set": codex_key,
+ "dedicated_key_set": codex_key,
+ "shared_key_set": False,
+ "oauth_connected": codex_connected,
+ "credential_source": (
+ "oauth" if codex_connected else "dedicated" if codex_key else "none"
+ ),
+ "secret_key": "codex_openai_api_key",
+ "dashboard_url": "https://platform.openai.com/api-keys",
+ "credential_help": (
+ "Dedicated OpenAI key for the Codex Jarvis-Agent. "
+ "It is not used by Brain or Realtime."
+ ),
"is_active_brain": primary == "openai-codex",
# ChatGPT subscription OAuth OR an OpenAI API key.
"billing": "subscription_or_api",
@@ -1000,13 +1067,15 @@ class WebServer:
try:
from jarvis.google_cli.auth_service import GoogleCliAuthService
- antigravity_connected = GoogleCliAuthService().status().connected
+ antigravity_status = GoogleCliAuthService().status()
+ antigravity_connected = (
+ antigravity_status.connected
+ and antigravity_status.mode == "oauth-personal"
+ )
except Exception: # noqa: BLE001
antigravity_connected = False
try:
- antigravity_key = bool(
- get_secret("gemini_api_key", env_fallback="GEMINI_API_KEY")
- )
+ antigravity_key = bool(get_jarvis_agent_secret("gemini"))
except Exception: # noqa: BLE001
antigravity_key = False
mapping_rows.append(
@@ -1016,6 +1085,20 @@ class WebServer:
"env_var": "Google-OAuth",
"env_fallback": "GEMINI_API_KEY",
"key_set": antigravity_connected or antigravity_key,
+ "api_key_set": antigravity_key,
+ "dedicated_key_set": False,
+ "shared_key_set": False,
+ "oauth_connected": antigravity_connected,
+ "credential_source": (
+ "oauth"
+ if antigravity_connected
+ else "gemini_agent_key"
+ if antigravity_key
+ else "none"
+ ),
+ "secret_key": None,
+ "dashboard_url": None,
+ "credential_help": None,
"is_active_brain": primary == "antigravity",
# Google subscription OAuth OR a Gemini API key.
"billing": "subscription_or_api",
@@ -1124,8 +1207,7 @@ class WebServer:
session_id = str(uuid4())
self._clients[session_id] = ws
- token = os.environ.get(self.cfg.ui.auth_token_env)
- welcome = WSWelcome(session_id=session_id, version=__version__, token=token)
+ welcome = WSWelcome(session_id=session_id, version=__version__)
send_lock = asyncio.Lock()
@@ -2021,22 +2103,29 @@ class WebServer:
if self._pending_reloads:
pending = list(self._pending_reloads)
self._pending_reloads.clear()
+ # Docs are user-facing and can be opened immediately after the
+ # shell appears. Keep the scans sequential, but put Docs ahead of
+ # the authoring-only skill catalog once the wake gate releases.
+ pending.sort(key=lambda item: item[0] != "DocRegistry")
async def _run_deferred_reloads() -> None:
# Yield until the wake model is loaded before these blocking disk
- # scans (DocRegistry FTS build ~5 s) start their worker thread —
+ # scans start their worker thread —
# otherwise they steal CPU/disk from the custom-wake base/cpu
- # model load and ~double its time (measured: base load 3.2 s
- # isolated vs ~8 s racing this scan). NO-OP on headless / voice-off
- # (returns immediately — no regress); bounded so a stuck wake load
- # never blocks the scans. The views tolerate an empty registry for
- # this brief gap.
+ # model load and can extend its time. NO-OP on headless / voice-off
+ # (returns immediately); bounded so a stuck wake load never blocks
+ # the scans. The Docs view can request the same load immediately.
from jarvis.core import runtime_refs as _rr
await _rr.await_wake_model_ready(timeout=12.0)
for label, registry in pending:
try:
- await asyncio.to_thread(registry.reload_sync)
+ if label == "DocRegistry":
+ # Shares the on-demand route lock: if the user
+ # already opened Docs this becomes an instant no-op.
+ await registry.ensure_loaded()
+ else:
+ await asyncio.to_thread(registry.reload_sync)
logger.info(
"{} deferred scan complete ({} entries)",
label, len(registry.list()),
diff --git a/jarvis/ui/web/settings_routes.py b/jarvis/ui/web/settings_routes.py
index e5d47a81bd..7ece3d8dfa 100644
--- a/jarvis/ui/web/settings_routes.py
+++ b/jarvis/ui/web/settings_routes.py
@@ -26,6 +26,7 @@ from __future__ import annotations
import asyncio
import logging
+import sys
import threading
from collections.abc import Callable
from typing import TYPE_CHECKING
@@ -121,7 +122,21 @@ async def put_reply_language(body: ReplyLanguageBody, request: Request) -> dict[
except Exception as exc: # noqa: BLE001
log.warning("reply-language persist failed (live switch still applied): %s", exc)
- return {"ok": True, "language": lang, "persisted": persisted}
+ # Gemini fixes its system instruction at connect time, while other
+ # providers may already be generating the current turn. A controlled
+ # reconnect is the only provider-neutral way to make the new reply policy
+ # authoritative immediately for an active desktop Realtime call.
+ from jarvis.ui.web.voice_runtime import reconnect_realtime
+
+ session_restarted = reconnect_realtime(
+ request, reason=f"reply_language:{lang}"
+ )
+ return {
+ "ok": True,
+ "language": lang,
+ "persisted": persisted,
+ "session_restarted": session_restarted,
+ }
# ---------------------------------------------------------------------------
@@ -508,6 +523,30 @@ def _config(request: Request):
)
+def _local_microphone_capture_ready(request: Request) -> bool:
+ """Non-prompting runtime gate for local macOS microphone diagnostics."""
+ if sys.platform != "darwin":
+ return True
+ try:
+ from jarvis.platform.permissions import PermissionId, get_system_permission_port
+
+ port = getattr(request.app.state, "system_permission_port", None)
+ if port is None:
+ port = get_system_permission_port()
+ return bool(port.runtime_access_granted(PermissionId.MICROPHONE))
+ except Exception: # noqa: BLE001 - protected diagnostics must fail closed
+ return False
+
+
+def _blocked_mic_level_result() -> dict[str, object]:
+ return {
+ "max_dbfs": -120.0,
+ "no_device": False,
+ "too_quiet": False,
+ "permission_required": True,
+ }
+
+
def _local_whisper_available() -> bool:
import importlib.util
@@ -868,6 +907,23 @@ async def wake_word_self_test(request: Request) -> dict[str, object]:
language=language,
)
+ if not _local_microphone_capture_ready(request):
+ return {
+ "ok": False,
+ "phrase": phrase,
+ "engine": plan.engine,
+ "language": language,
+ "wake_available": bool(plan.wake_available),
+ "degraded": bool(plan.degraded),
+ "phrase_in_vocab": None,
+ "max_dbfs": -120.0,
+ "mic_ok": False,
+ "no_device": False,
+ "permission_required": True,
+ "message": "Microphone access is not ready for Personal Jarvis.",
+ "hint": "Grant Microphone access in Settings > Permissions, then retry.",
+ }
+
# Vocabulary check only makes sense for the grammar (vosk_kws) engine.
phrase_in_vocab: bool | None = None
if plan.engine == "vosk_kws":
@@ -888,6 +944,22 @@ async def wake_word_self_test(request: Request) -> dict[str, object]:
max_dbfs = await measure_mic_dbfs(duration_s=2.0)
except Exception: # noqa: BLE001 — treat a failed measurement as no device
max_dbfs = -120.0
+ if not _local_microphone_capture_ready(request):
+ return {
+ "ok": False,
+ "phrase": phrase,
+ "engine": plan.engine,
+ "language": language,
+ "wake_available": bool(plan.wake_available),
+ "degraded": bool(plan.degraded),
+ "phrase_in_vocab": phrase_in_vocab,
+ "max_dbfs": -120.0,
+ "mic_ok": False,
+ "no_device": False,
+ "permission_required": True,
+ "message": "Microphone access changed during the self-test.",
+ "hint": "Review Microphone access in Settings > Permissions, then retry.",
+ }
mic_ok = max_dbfs > -40.0
no_device = max_dbfs <= -119.9
@@ -922,13 +994,14 @@ async def wake_word_self_test(request: Request) -> dict[str, object]:
"max_dbfs": max_dbfs,
"mic_ok": mic_ok,
"no_device": no_device,
+ "permission_required": False,
"message": message,
"hint": hint,
}
@router.get("/wake-word/mic-level")
-async def wake_mic_level() -> dict[str, object]:
+async def wake_mic_level(request: Request) -> dict[str, object]:
"""Live mic dBFS for the onboarding wake step (Task 7: mic + spoken-word
verification before ``acknowledgeWakeWord``). Never 500s — a headless/no-mic
host reports ``no_device=True`` rather than raising. Warn threshold −40 dBFS
@@ -937,14 +1010,19 @@ async def wake_mic_level() -> dict[str, object]:
"""
from jarvis.speech.diagnose import measure_mic_dbfs
+ if not _local_microphone_capture_ready(request):
+ return _blocked_mic_level_result()
try:
max_dbfs = await measure_mic_dbfs(duration_s=3.0)
except Exception: # noqa: BLE001 — defensive guard: if measurement fails, treat as no device
max_dbfs = -120.0
+ if not _local_microphone_capture_ready(request):
+ return _blocked_mic_level_result()
return {
"max_dbfs": max_dbfs,
"no_device": max_dbfs <= -119.9,
"too_quiet": -119.9 < max_dbfs < -40.0,
+ "permission_required": False,
}
diff --git a/jarvis/ui/web/socials_routes.py b/jarvis/ui/web/socials_routes.py
index f4f7c03369..f0271773ff 100644
--- a/jarvis/ui/web/socials_routes.py
+++ b/jarvis/ui/web/socials_routes.py
@@ -71,7 +71,7 @@ def _seed_entries() -> list[dict[str, Any]]:
real handle via the UI — the org page is a sane stand-in until then.
"""
raw = [
- ("discord", "Discord", "https://discord.gg/UPu6pFWrJ"),
+ ("discord", "Discord", "https://discord.gg/x7USduHxbc"),
("github", "GitHub (Repo)", "https://github.com/PersonalJarvis/PersonalJarvis"),
("github", "GitHub (Profile)", "https://github.com/PersonalJarvis"),
# X: the official project account. The first-run seed ships ONLY the
diff --git a/tests/conftest.py b/tests/conftest.py
index 2d5834d7b6..7e17dbe51c 100644
--- a/tests/conftest.py
+++ b/tests/conftest.py
@@ -3,6 +3,7 @@ from __future__ import annotations
import sys
from pathlib import Path
+from urllib.parse import urlsplit
# Add the repo root to sys.path so tests can import top-level modules like
# `ui.orb` (pytest doesn't add the repo root to sys.path by default).
@@ -10,10 +11,56 @@ _REPO_ROOT = Path(__file__).resolve().parent.parent
if str(_REPO_ROOT) not in sys.path:
sys.path.insert(0, str(_REPO_ROOT))
-import pytest
-import pytest_asyncio
+import pytest # noqa: E402
+import pytest_asyncio # noqa: E402
-from jarvis.core.bus import EventBus, reset_default_bus
+from jarvis.core.bus import EventBus, reset_default_bus # noqa: E402
+
+
+def pytest_configure(config) -> None: # noqa: ANN001
+ config.addinivalue_line(
+ "markers",
+ "no_auto_web_auth: use explicit credentials against the production web boundary",
+ )
+
+
[email protected](autouse=True)
+def _authenticated_test_clients(request, monkeypatch): # noqa: ANN001
+ """Give legacy TestClient suites a real authenticated browser session.
+
+ Security-boundary tests opt out with ``no_auto_web_auth`` and present their
+ own credentials. This fixture changes only test clients: production still
+ has no loopback, dev-mode, or pytest bypass.
+ """
+ if request.node.get_closest_marker("no_auto_web_auth") is not None:
+ yield
+ return
+
+ from fastapi.testclient import TestClient
+
+ from jarvis.ui.web.missions_auth import register_token, revoke_token
+ from jarvis.ui.web.surface_security import COOKIE_NAME
+
+ token = "jarvis-pytest-browser-session" # noqa: S105
+ monkeypatch.setenv("JARVIS_TRUSTED_HOSTS", "testserver,test")
+ original_init = TestClient.__init__
+
+ def authenticated_init(client, *args, **kwargs): # noqa: ANN001
+ base_url = str(kwargs.get("base_url", "http://testserver"))
+ parsed = urlsplit(base_url)
+ origin = f"{parsed.scheme or 'http'}://{parsed.netloc or 'testserver'}"
+ headers = dict(kwargs.get("headers") or {})
+ headers.setdefault("origin", origin)
+ kwargs["headers"] = headers
+ register_token(token)
+ original_init(client, *args, **kwargs)
+ client.cookies.set(COOKIE_NAME, token)
+
+ monkeypatch.setattr(TestClient, "__init__", authenticated_init)
+ try:
+ yield
+ finally:
+ revoke_token(token)
@pytest.fixture(autouse=True)
@@ -26,7 +73,7 @@ def _reset_bus():
@pytest_asyncio.fixture
async def fresh_bus():
- """Frischer EventBus pro Test."""
+ """Fresh EventBus for each test."""
bus = EventBus()
yield bus
diff --git a/tests/contract/test_ws_schema.py b/tests/contract/test_ws_schema.py
index a6b84921b1..a54c5b9435 100644
--- a/tests/contract/test_ws_schema.py
+++ b/tests/contract/test_ws_schema.py
@@ -52,9 +52,10 @@ def test_command_unknown_action_rejected() -> None:
WSCommand.model_validate(raw)
-def test_welcome_serializable() -> None:
- w = WSWelcome(session_id="s1", version="0.1.0", token=None)
+def test_welcome_serializable_without_credentials() -> None:
+ w = WSWelcome(session_id="s1", version="0.1.0")
encoded = json.loads(w.model_dump_json())
assert encoded["type"] == "welcome"
assert encoded["session_id"] == "s1"
assert encoded["version"] == "0.1.0"
+ assert "token" not in encoded
diff --git a/tests/unit/cli_ctl/test_config.py b/tests/unit/cli_ctl/test_config.py
index 4abccbdb92..dc05de75d0 100644
--- a/tests/unit/cli_ctl/test_config.py
+++ b/tests/unit/cli_ctl/test_config.py
@@ -54,17 +54,19 @@ def test_save_login_persists_and_chmods(monkeypatch, tmp_path):
assert data == {"base_url": "http://h:2", "control_key": "jctl_saved"}
-def test_session_file_used_when_no_env_or_config(monkeypatch, tmp_path):
+def test_session_file_is_discovery_only_not_a_control_credential(monkeypatch, tmp_path):
sess = tmp_path / "session.json"
sess.write_text(
json.dumps({"port": 48999, "token": "jctl_sess", "pid": os.getpid()}),
encoding="utf-8",
)
monkeypatch.setenv("JARVIS_CLI_SESSION_FILE", str(sess))
- monkeypatch.setattr("jarvis.cli_ctl.config._local_control_key", lambda: None)
+ monkeypatch.setattr(
+ "jarvis.cli_ctl.config._local_control_key", lambda: "jctl_localkey"
+ )
prof = cfg.resolve_profile()
assert prof.base_url == "http://127.0.0.1:48999"
- assert prof.control_key == "jctl_sess"
+ assert prof.control_key == "jctl_localkey"
def test_config_file_beats_session(monkeypatch, tmp_path):
diff --git a/tests/unit/cli_ctl/test_danger_metadata.py b/tests/unit/cli_ctl/test_danger_metadata.py
index 3c9f16f171..604c76959c 100644
--- a/tests/unit/cli_ctl/test_danger_metadata.py
+++ b/tests/unit/cli_ctl/test_danger_metadata.py
@@ -54,7 +54,7 @@ def _spec_with_flag(flagged: bool) -> dict:
def _invoke(spec: dict, args: list[str]):
calls: list[tuple] = []
- def runner(method, path, params, body):
+ def runner(method, path, params, body, *, timeout_s=None):
calls.append((method, path))
return {"ok": True}
diff --git a/tests/unit/cli_ctl/test_doctor.py b/tests/unit/cli_ctl/test_doctor.py
index 5f96833647..10e7ac9988 100644
--- a/tests/unit/cli_ctl/test_doctor.py
+++ b/tests/unit/cli_ctl/test_doctor.py
@@ -90,7 +90,7 @@ def test_dynamic_api_layer_fails_clean_with_diagnosis(monkeypatch) -> None:
"summary": "Ping"}}},
}
- def runner(method, path, params, body):
+ def runner(method, path, params, body, *, timeout_s=None):
raise ApiError(
"Jarvis at http://127.0.0.1:47821 is unreachable.",
None, base_url="http://127.0.0.1:47821",
diff --git a/tests/unit/cli_ctl/test_dynamic.py b/tests/unit/cli_ctl/test_dynamic.py
index 0f3e0c500f..48ede1f7bd 100644
--- a/tests/unit/cli_ctl/test_dynamic.py
+++ b/tests/unit/cli_ctl/test_dynamic.py
@@ -55,8 +55,14 @@ SPEC = {
def test_builds_group_per_tag_with_commands():
captured = {}
- def runner(method, path, params, body):
- captured.update(method=method, path=path, params=params, body=body)
+ def runner(method, path, params, body, *, timeout_s=None):
+ captured.update(
+ method=method,
+ path=path,
+ params=params,
+ body=body,
+ timeout_s=timeout_s,
+ )
return {"ok": True}
grp = dynamic.build_api_group(SPEC, runner)
@@ -70,11 +76,46 @@ def test_builds_group_per_tag_with_commands():
def test_path_param_substituted_and_query_passed():
captured = {}
- def runner(method, path, params, body):
- captured.update(method=method, path=path, params=params, body=body)
+ def runner(method, path, params, body, *, timeout_s=None):
+ captured.update(
+ method=method,
+ path=path,
+ params=params,
+ body=body,
+ timeout_s=timeout_s,
+ )
return {}
grp = dynamic.build_api_group(SPEC, runner)
cmd = grp.get_command(None, "tasks").get_command(None, "get-task")
cmd.callback(task_id="abc")
assert captured["path"] == "/api/tasks/{task_id}".replace("{task_id}", "abc")
+
+
+def test_route_timeout_metadata_and_cli_override_reach_runner():
+ captured = {}
+ spec = {
+ "openapi": "3.1.0",
+ "info": {"version": "1"},
+ "paths": {
+ "/api/wiki/backfill": {
+ "post": {
+ "tags": ["wiki"],
+ "operationId": "backfill_wiki",
+ "x-jarvis-timeout-seconds": 21600,
+ }
+ }
+ },
+ }
+
+ def runner(method, path, params, body, *, timeout_s=None):
+ captured["timeout_s"] = timeout_s
+ return {}
+
+ group = dynamic.build_api_group(spec, runner)
+ command = group.get_command(None, "wiki").get_command(None, "backfill-wiki")
+ command.callback(request_timeout=123.0, yes=True)
+ assert captured["timeout_s"] == 123.0
+
+ command.callback(yes=True)
+ assert captured["timeout_s"] == 21600.0
diff --git a/tests/unit/setup/test_onboarding_meta.py b/tests/unit/setup/test_onboarding_meta.py
index c56bfc6b36..83f9c350b4 100644
--- a/tests/unit/setup/test_onboarding_meta.py
+++ b/tests/unit/setup/test_onboarding_meta.py
@@ -8,6 +8,8 @@ def test_meta_constants():
# gate + MIT-license disclaimer carry the legal posture now.
assert "terms" not in m.ONBOARDING_STEPS
assert m.ONBOARDING_STEPS[1] == "language"
+ assert m.ONBOARDING_STEPS[2] == "permissions"
+ assert m.ONBOARDING_STEPS.index("permissions") < m.ONBOARDING_STEPS.index("wake-word")
assert m.ONBOARDING_STEPS[-1] == "finish"
assert "wake-word" in m.ONBOARDING_STEPS
assert "persona-theme" not in m.ONBOARDING_STEPS
@@ -16,7 +18,7 @@ def test_meta_constants():
assert "system-style" not in m.ONBOARDING_STEPS
assert "mic-test" not in m.ONBOARDING_STEPS
assert m.ONBOARDING_STEPS[-2] == "api-keys"
- assert len(m.ONBOARDING_STEPS) == 5
+ assert len(m.ONBOARDING_STEPS) == 6
assert len(m.WAKE_WORD_LEGAL_REFERENCES) >= 3
for ref in m.WAKE_WORD_LEGAL_REFERENCES:
assert ref["label"] and ref["url"].startswith("https://")
diff --git a/tests/unit/ui/test_fast_bootstrap_onboarding.py b/tests/unit/ui/test_fast_bootstrap_onboarding.py
index b5277c5575..6d7c36c458 100644
--- a/tests/unit/ui/test_fast_bootstrap_onboarding.py
+++ b/tests/unit/ui/test_fast_bootstrap_onboarding.py
@@ -1,7 +1,11 @@
"""While warming, the bootstrap must answer /api/onboarding/* itself."""
import json
+from http.cookies import SimpleCookie
from jarvis.ui.web.fast_bootstrap import FastBootstrap
+from jarvis.ui.web.surface_security import COOKIE_NAME
+
+_TOKEN = "fast-bootstrap-onboarding-session" # noqa: S105
def _collector():
@@ -17,14 +21,47 @@ async def _receive_empty():
return {"type": "http.request", "body": b"", "more_body": False}
+def _scope(path: str, method: str = "GET", *, cookie: str | None = None) -> dict:
+ headers = [
+ (b"host", b"127.0.0.1:47821"),
+ (b"origin", b"http://127.0.0.1:47821"),
+ ]
+ if cookie is not None:
+ headers.append((b"cookie", f"{COOKIE_NAME}={cookie}".encode("ascii")))
+ return {
+ "type": "http",
+ "method": method,
+ "path": path,
+ "scheme": "http",
+ "client": ("127.0.0.1", 50000),
+ "headers": headers,
+ }
+
+
+async def _exchange(boot: FastBootstrap) -> str:
+ body = json.dumps({"session_token": _TOKEN}).encode("utf-8")
+ sent, send = _collector()
+
+ async def receive() -> dict:
+ return {"type": "http.request", "body": body, "more_body": False}
+
+ await boot.app(_scope("/api/ui/session", "POST"), receive, send)
+ assert sent[0]["status"] == 204
+ raw_cookie = next(value for key, value in sent[0]["headers"] if key == b"set-cookie")
+ parsed = SimpleCookie()
+ parsed.load(raw_cookie.decode("latin-1"))
+ return parsed[COOKIE_NAME].value
+
+
async def test_onboarding_state_answers_while_warming(tmp_path, monkeypatch) -> None:
from jarvis.setup import onboarding_fastpath as fp
monkeypatch.setattr(fp, "_STATE_PATH_OVERRIDE", tmp_path / "setup_state.json")
- boot = FastBootstrap(dist_dir=tmp_path / "no-dist")
+ boot = FastBootstrap(dist_dir=tmp_path / "no-dist", session_token=_TOKEN)
+ cookie = await _exchange(boot)
sent, send = _collector()
await boot.app(
- {"type": "http", "method": "GET", "path": "/api/onboarding/state"},
+ _scope("/api/onboarding/state", cookie=cookie),
_receive_empty,
send,
)
@@ -37,10 +74,11 @@ async def test_onboarding_complete_persists_while_warming(tmp_path, monkeypatch)
from jarvis.setup import state as st
monkeypatch.setattr(fp, "_STATE_PATH_OVERRIDE", tmp_path / "setup_state.json")
- boot = FastBootstrap(dist_dir=tmp_path / "no-dist")
+ boot = FastBootstrap(dist_dir=tmp_path / "no-dist", session_token=_TOKEN)
+ cookie = await _exchange(boot)
sent, send = _collector()
await boot.app(
- {"type": "http", "method": "POST", "path": "/api/onboarding/complete"},
+ _scope("/api/onboarding/complete", "POST", cookie=cookie),
_receive_empty,
send,
)
@@ -49,10 +87,13 @@ async def test_onboarding_complete_persists_while_warming(tmp_path, monkeypatch)
async def test_other_api_routes_still_held(tmp_path) -> None:
- boot = FastBootstrap(hold_timeout=0.05, dist_dir=tmp_path / "no-dist")
+ boot = FastBootstrap(
+ hold_timeout=0.05, dist_dir=tmp_path / "no-dist", session_token=_TOKEN
+ )
+ cookie = await _exchange(boot)
sent, send = _collector()
await boot.app(
- {"type": "http", "method": "GET", "path": "/api/settings"},
+ _scope("/api/settings", cookie=cookie),
_receive_empty,
send,
)
@@ -71,11 +112,11 @@ async def test_real_app_owns_onboarding_after_set_app(tmp_path, monkeypatch) ->
await send({"type": "http.response.start", "status": 200, "headers": []})
await send({"type": "http.response.body", "body": b"real"})
- boot = FastBootstrap(dist_dir=tmp_path / "no-dist")
+ boot = FastBootstrap(dist_dir=tmp_path / "no-dist", session_token=_TOKEN)
boot.set_app(real_app)
sent, send = _collector()
await boot.app(
- {"type": "http", "method": "GET", "path": "/api/onboarding/state"},
+ _scope("/api/onboarding/state"),
_receive_empty,
send,
)
diff --git a/tests/unit/ui/test_profile_raw_write.py b/tests/unit/ui/test_profile_raw_write.py
index c0672bb9a8..fa886d8221 100644
--- a/tests/unit/ui/test_profile_raw_write.py
+++ b/tests/unit/ui/test_profile_raw_write.py
@@ -54,6 +54,7 @@ def client(tmp_path: Path) -> TestClient:
def test_put_raw_writes_and_reloads(client: TestClient) -> None:
raw = client.get("/api/profile/raw").json()
assert raw["content"].startswith("---")
+ assert raw["path"] == "USER.md"
new_content = raw["content"].replace("name: Alt", "name: Neu")
res = client.put(
@@ -65,6 +66,7 @@ def test_put_raw_writes_and_reloads(client: TestClient) -> None:
assert payload["ok"] is True
assert payload["frontmatter_ok"] is True
assert payload["reparsed"] is True
+ assert payload["path"] == "USER.md"
# File on disk reflects the edit…
assert client.get("/api/profile/raw").json()["content"] == new_content
diff --git a/tests/unit/ui/test_socials_routes.py b/tests/unit/ui/test_socials_routes.py
index b230b4ae55..f4bd14a3c5 100644
--- a/tests/unit/ui/test_socials_routes.py
+++ b/tests/unit/ui/test_socials_routes.py
@@ -26,7 +26,7 @@ import pytest
from fastapi import FastAPI
from fastapi.testclient import TestClient
-DISCORD_URL = "https://discord.gg/UPu6pFWrJ"
+DISCORD_URL = "https://discord.gg/x7USduHxbc"
REPO_URL = "https://github.com/PersonalJarvis/PersonalJarvis"
PROFILE_URL = "https://github.com/PersonalJarvis"
JARVIS_X_URL = "https://x.com/PersonalJarvis"
diff --git a/tests/unit/ui/web/test_fast_bootstrap.py b/tests/unit/ui/web/test_fast_bootstrap.py
index 1d207a7214..8422e0719b 100644
--- a/tests/unit/ui/web/test_fast_bootstrap.py
+++ b/tests/unit/ui/web/test_fast_bootstrap.py
@@ -11,34 +11,67 @@ the ASGI callable directly (no socket) to prove that behavior.
from __future__ import annotations
import asyncio
+import json
+from http.cookies import SimpleCookie
from pathlib import Path
from typing import Any
import pytest
from jarvis.ui.web.fast_bootstrap import FastBootstrap
+from jarvis.ui.web.surface_security import COOKIE_NAME, SurfaceSecurity
+_TOKEN = "fast-bootstrap-test-session" # noqa: S105
-async def _drive(app: Any, scope: dict) -> list[dict]:
+
+async def _drive(app: Any, scope: dict, body: bytes = b"") -> list[dict]:
sent: list[dict] = []
async def send(msg: dict) -> None:
sent.append(msg)
async def receive() -> dict:
- return {"type": "http.request", "body": b"", "more_body": False}
+ return {"type": "http.request", "body": body, "more_body": False}
await app(scope, receive, send)
return sent
-def _http(path: str, method: str = "GET") -> dict:
- return {"type": "http", "method": method, "path": path, "headers": []}
+def _http(path: str, method: str = "GET", *, cookie: str | None = None) -> dict:
+ headers = [
+ (b"host", b"127.0.0.1:47821"),
+ (b"origin", b"http://127.0.0.1:47821"),
+ ]
+ if cookie is not None:
+ headers.append((b"cookie", f"{COOKIE_NAME}={cookie}".encode("ascii")))
+ return {
+ "type": "http",
+ "method": method,
+ "path": path,
+ "scheme": "http",
+ "client": ("127.0.0.1", 50000),
+ "headers": headers,
+ }
+
+
+async def _exchange(bs: FastBootstrap, token: str = _TOKEN) -> str:
+ body = json.dumps({"session_token": token}).encode("utf-8")
+ sent = await _drive(
+ bs.app,
+ _http("/api/ui/session", method="POST"),
+ body,
+ )
+ start = next(message for message in sent if message["type"] == "http.response.start")
+ assert start["status"] == 204
+ raw_cookie = next(value for key, value in start["headers"] if key == b"set-cookie")
+ parsed = SimpleCookie()
+ parsed.load(raw_cookie.decode("latin-1"))
+ return parsed[COOKIE_NAME].value
@pytest.mark.asyncio
async def test_health_returns_200_before_real_app_set() -> None:
- bs = FastBootstrap()
+ bs = FastBootstrap(session_token=_TOKEN)
sent = await _drive(bs.app, _http("/api/health"))
start = next(m for m in sent if m["type"] == "http.response.start")
assert start["status"] == 200
@@ -46,7 +79,8 @@ async def test_health_returns_200_before_real_app_set() -> None:
@pytest.mark.asyncio
async def test_non_health_request_holds_until_app_set_then_delegates() -> None:
- bs = FastBootstrap()
+ bs = FastBootstrap(session_token=_TOKEN)
+ cookie = await _exchange(bs)
seen: dict[str, str] = {}
async def real_app(scope: dict, receive: Any, send: Any) -> None:
@@ -54,7 +88,9 @@ async def test_non_health_request_holds_until_app_set_then_delegates() -> None:
await send({"type": "http.response.start", "status": 201, "headers": []})
await send({"type": "http.response.body", "body": b"real"})
- task = asyncio.create_task(_drive(bs.app, _http("/api/missions")))
+ task = asyncio.create_task(
+ _drive(bs.app, _http("/api/missions", cookie=cookie))
+ )
await asyncio.sleep(0.02)
assert not task.done(), "request must be held while the real app is warming"
@@ -68,7 +104,7 @@ async def test_non_health_request_holds_until_app_set_then_delegates() -> None:
@pytest.mark.asyncio
async def test_health_delegates_to_real_app_once_ready() -> None:
- bs = FastBootstrap()
+ bs = FastBootstrap(session_token=_TOKEN)
calls: list[str] = []
async def real_app(scope: dict, receive: Any, send: Any) -> None:
@@ -83,16 +119,24 @@ async def test_health_delegates_to_real_app_once_ready() -> None:
@pytest.mark.asyncio
async def test_held_request_times_out_to_503_when_app_never_arrives() -> None:
- bs = FastBootstrap(hold_timeout=0.05)
- sent = await _drive(bs.app, _http("/api/missions"))
+ bs = FastBootstrap(hold_timeout=0.05, session_token=_TOKEN)
+ cookie = await _exchange(bs)
+ sent = await _drive(bs.app, _http("/api/missions", cookie=cookie))
start = next(m for m in sent if m["type"] == "http.response.start")
assert start["status"] == 503
@pytest.mark.asyncio
async def test_websocket_held_then_closed_on_timeout() -> None:
- bs = FastBootstrap(hold_timeout=0.05)
- scope = {"type": "websocket", "path": "/ws", "headers": []}
+ bs = FastBootstrap(hold_timeout=0.05, session_token=_TOKEN)
+ cookie = await _exchange(bs)
+ scope = {
+ "type": "websocket",
+ "path": "/ws",
+ "scheme": "ws",
+ "client": ("127.0.0.1", 50000),
+ "headers": _http("/", cookie=cookie)["headers"],
+ }
sent = await _drive(bs.app, scope)
assert any(m["type"] == "websocket.close" for m in sent)
@@ -124,15 +168,47 @@ def _status(sent: list[dict]) -> int:
async def test_serves_index_html_immediately_before_app_ready(tmp_path) -> None:
# The whole point: GET / returns the REAL index.html while warming, so the
# desktop window shows the UI shell instead of a black screen.
- bs = FastBootstrap(dist_dir=_seed_dist(tmp_path))
+ bs = FastBootstrap(dist_dir=_seed_dist(tmp_path), session_token=_TOKEN)
sent = await _drive(bs.app, _http("/"))
assert _status(sent) == 200
assert b"<div id=root>" in _body(sent)
+ headers = next(
+ message["headers"]
+ for message in sent
+ if message["type"] == "http.response.start"
+ )
+ assert all(key != b"set-cookie" for key, _value in headers)
+
+
+async def test_bootstrap_token_only_exchanges_once_across_app_handoff() -> None:
+ bs = FastBootstrap(session_token=_TOKEN)
+
+ async def protected_app(scope: dict, receive: Any, send: Any) -> None:
+ await send({"type": "http.response.start", "status": 200, "headers": []})
+ await send({"type": "http.response.body", "body": b"protected"})
+
+ # The raw WebView credential is not itself an authenticated cookie.
+ rejected = await _drive(bs.app, _http("/api/config", cookie=_TOKEN))
+ assert _status(rejected) == 401
+
+ # Build the normal secured app before React receives the injected token.
+ bs.set_app(SurfaceSecurity(protected_app))
+ cookie = await _exchange(bs)
+ replay = await _drive(
+ bs.app,
+ _http("/api/ui/session", method="POST"),
+ json.dumps({"session_token": _TOKEN}).encode("utf-8"),
+ )
+ assert _status(replay) == 401
+
+ protected = await _drive(bs.app, _http("/api/config", cookie=cookie))
+ assert _status(protected) == 200
@pytest.mark.asyncio
async def test_serves_static_asset_immediately_before_app_ready(tmp_path) -> None:
- bs = FastBootstrap(dist_dir=_seed_dist(tmp_path))
+ bs = FastBootstrap(dist_dir=_seed_dist(tmp_path), session_token=_TOKEN)
sent = await _drive(bs.app, _http("/assets/app.js"))
assert _status(sent) == 200
assert b"jarvis ui" in _body(sent)
@@ -147,7 +223,7 @@ async def test_serves_static_asset_immediately_before_app_ready(tmp_path) -> Non
async def test_spa_fallback_serves_index_for_unknown_route(tmp_path) -> None:
# A deep-link to a client-side route (no real file) must fall back to
# index.html so the SPA router can take over — NOT be held or 404'd.
- bs = FastBootstrap(dist_dir=_seed_dist(tmp_path))
+ bs = FastBootstrap(dist_dir=_seed_dist(tmp_path), session_token=_TOKEN)
sent = await _drive(bs.app, _http("/wiki/some/page"))
assert _status(sent) == 200
assert b"<div id=root>" in _body(sent)
@@ -157,8 +233,11 @@ async def test_spa_fallback_serves_index_for_unknown_route(tmp_path) -> None:
async def test_api_request_is_still_held_not_served_as_static(tmp_path) -> None:
# /api/* must NOT be served as static — it is the dynamic surface and must
# be held until the real app is ready.
- bs = FastBootstrap(dist_dir=_seed_dist(tmp_path), hold_timeout=0.05)
- sent = await _drive(bs.app, _http("/api/missions"))
+ bs = FastBootstrap(
+ dist_dir=_seed_dist(tmp_path), hold_timeout=0.05, session_token=_TOKEN
+ )
+ cookie = await _exchange(bs)
+ sent = await _drive(bs.app, _http("/api/missions", cookie=cookie))
assert _status(sent) == 503 # held → warming timeout, never a static 200
@@ -166,7 +245,7 @@ async def test_api_request_is_still_held_not_served_as_static(tmp_path) -> None:
async def test_shell_served_event_fires_after_js_bundle(tmp_path) -> None:
# The backend defers its GIL-heavy build until the entry JS bundle is out,
# so the UI paints first. index.html alone (blank #root) must NOT satisfy it.
- bs = FastBootstrap(dist_dir=_seed_dist(tmp_path))
+ bs = FastBootstrap(dist_dir=_seed_dist(tmp_path), session_token=_TOKEN)
await _drive(bs.app, _http("/")) # index.html → not enough on its own
assert not await bs.wait_shell_served(timeout=0.05)
await _drive(bs.app, _http("/assets/app.js")) # entry bundle → now ready
@@ -178,7 +257,7 @@ async def test_shell_paint_requires_browser_ack_not_just_js_bytes(tmp_path) -> N
# Sending the bundle does not prove the browser painted it. The desktop
# backend must stay clear of heavy imports until the boot page confirms a
# visual frame through the dedicated warm-up endpoint.
- bs = FastBootstrap(dist_dir=_seed_dist(tmp_path))
+ bs = FastBootstrap(dist_dir=_seed_dist(tmp_path), session_token=_TOKEN)
await _drive(bs.app, _http("/"))
await _drive(bs.app, _http("/assets/app.js"))
assert not await bs.wait_shell_painted(timeout=0.05)
@@ -235,7 +314,7 @@ async def _port_open(host: str, port: int, timeout: float = 1.0) -> bool: # noq
@pytest.mark.asyncio
async def test_serve_starts_a_listener_that_answers_health() -> None:
port = _free_port()
- bs = FastBootstrap()
+ bs = FastBootstrap(session_token=_TOKEN)
await bs.serve("127.0.0.1", port, supervise=False)
try:
assert await _port_open("127.0.0.1", port)
@@ -250,7 +329,7 @@ async def test_supervisor_rebinds_listener_after_socket_death() -> None:
# ``sock.close()`` does on WinError 64). The supervisor must detect the dead
# port and re-bind, so the port comes back WITHOUT a process restart.
port = _free_port()
- bs = FastBootstrap()
+ bs = FastBootstrap(session_token=_TOKEN)
await bs.serve("127.0.0.1", port, supervise=True, supervise_interval=0.2)
try:
assert await _port_open("127.0.0.1", port), "listener must be up after serve"
@@ -276,7 +355,7 @@ async def test_rebind_preserves_registered_real_app() -> None:
# A re-bind after a socket death must keep delegating to the already
# registered real app — the warm-up state survives the listener swap.
port = _free_port()
- bs = FastBootstrap()
+ bs = FastBootstrap(session_token=_TOKEN)
async def real_app(scope: dict, receive: Any, send: Any) -> None:
if scope["type"] == "lifespan":
diff --git a/tests/unit/ui/web/test_fast_bootstrap_ws.py b/tests/unit/ui/web/test_fast_bootstrap_ws.py
index a9a75f5e10..ed0fe83564 100644
--- a/tests/unit/ui/web/test_fast_bootstrap_ws.py
+++ b/tests/unit/ui/web/test_fast_bootstrap_ws.py
@@ -12,17 +12,22 @@ import websockets
from jarvis.ui.web.fast_bootstrap import FastBootstrap
+_TOKEN = "fast-bootstrap-websocket-session" # noqa: S105
+
@pytest.mark.asyncio
async def test_warming_ws_is_fast_closed_with_1013() -> None:
logging.disable(logging.CRITICAL)
- bs = FastBootstrap()
+ bs = FastBootstrap(session_token=_TOKEN)
await bs.serve("127.0.0.1", 47995) # NOT set_app -> warming
try:
# Must connect quickly (handshake accepted) -- the old hold made this
# time out. open_timeout well under the old 120s hold proves no-hold.
async with websockets.connect(
- "ws://127.0.0.1:47995/ws", open_timeout=3
+ "ws://127.0.0.1:47995/ws",
+ open_timeout=3,
+ origin="http://127.0.0.1:47995",
+ additional_headers={"Cookie": f"jarvis_session={_TOKEN}"},
) as ws:
with pytest.raises(websockets.ConnectionClosed) as exc:
await asyncio.wait_for(ws.recv(), timeout=3)
diff --git a/tests/unit/ui/web/test_outputs_routes.py b/tests/unit/ui/web/test_outputs_routes.py
index 3674fea98a..d852d46120 100644
--- a/tests/unit/ui/web/test_outputs_routes.py
+++ b/tests/unit/ui/web/test_outputs_routes.py
@@ -15,6 +15,7 @@ the DB, and that worktree slug-style dirs stay un-enriched (their
embedded random ``hex[:8]`` is decoupled from any mission UUID by
design).
"""
+
from __future__ import annotations
import time
@@ -110,9 +111,7 @@ def _make_mission_dir(root: Path, mission_id: str) -> Path:
return d
-def _make_worktree_dir(
- root: Path, utterance: str = "test-task", short: str | None = None
-) -> Path:
+def _make_worktree_dir(root: Path, utterance: str = "test-task", short: str | None = None) -> Path:
"""Create a worktree slug-style dir as ``WorktreeManager.create`` does."""
short = short or "deadbeef"
ts = time.strftime("%Y%m%dT%H%M%S")
@@ -146,8 +145,7 @@ async def _insert_mission(
created_ms = created_ms or int(time.time() * 1000) - 5000
updated_ms = updated_ms or int(time.time() * 1000)
await conn.execute(
- "INSERT INTO missions (id, prompt, state, created_ms, updated_ms) "
- "VALUES (?, ?, ?, ?, ?)",
+ "INSERT INTO missions (id, prompt, state, created_ms, updated_ms) VALUES (?, ?, ?, ?, ?)",
(mission_id, prompt, state, created_ms, updated_ms),
)
@@ -176,8 +174,7 @@ async def _insert_dispatch_event(
}
)
await conn.execute(
- "INSERT INTO mission_events (mission_id, event_type, payload_json) "
- "VALUES (?, ?, ?)",
+ "INSERT INTO mission_events (mission_id, event_type, payload_json) VALUES (?, ?, ?)",
(child_id, "MissionDispatched", payload),
)
@@ -206,19 +203,12 @@ def test_parse_slug_unknown_returns_nones() -> None:
def test_mission_id_prefix_for_persistent_dir() -> None:
"""The mission_<short> dir-name yields its short as the LIKE-prefix."""
- assert (
- _mission_id_prefix_for_dir("mission_019e3600-a84e") == "019e3600-a84e"
- )
+ assert _mission_id_prefix_for_dir("mission_019e3600-a84e") == "019e3600-a84e"
def test_mission_id_prefix_for_worktree_dir_is_none() -> None:
"""Worktree slug dirs embed a random hex[:8] — no mission-id mapping."""
- assert (
- _mission_id_prefix_for_dir(
- "20260518T120000__refactor-router__deadbeef"
- )
- is None
- )
+ assert _mission_id_prefix_for_dir("20260518T120000__refactor-router__deadbeef") is None
def test_mission_id_prefix_for_random_dir_is_none() -> None:
@@ -462,9 +452,7 @@ async def test_list_outputs_terminal_mission_duration_frozen(
r = client.get("/api/outputs")
sess = r.json()["sessions"][0]
assert sess["duration_s"] == pytest.approx(100.0, abs=5.0)
- assert sess["completed_at"] == pytest.approx(
- (now_ms - 200_000) / 1000.0, abs=5.0
- )
+ assert sess["completed_at"] == pytest.approx((now_ms - 200_000) / 1000.0, abs=5.0)
@pytest.mark.asyncio
@@ -483,9 +471,7 @@ async def test_list_outputs_mission_dir_no_db_row_falls_back_to_unknown(
@pytest.mark.asyncio
-async def test_list_outputs_hides_worktree_slug_dirs(
- app: FastAPI, tmp_path: Path
-) -> None:
+async def test_list_outputs_hides_worktree_slug_dirs(app: FastAPI, tmp_path: Path) -> None:
"""Worktree slug dirs (``<ts>__<utterance>__<short>``) are temporary scaffolding
created and torn down by ``WorktreeManager``. They have no mission-id mapping
so their status would always render as ``unknown`` — together with the
@@ -542,12 +528,8 @@ async def test_list_outputs_multiple_mission_dirs(
mid_b = "019e3600-bbbb-7000-8000-000000000011"
_make_mission_dir(tmp_path, mid_a)
_make_mission_dir(tmp_path, mid_b)
- await _insert_mission(
- db_conn, mission_id=mid_a, state="APPROVED", prompt="task A"
- )
- await _insert_mission(
- db_conn, mission_id=mid_b, state="FAILED", prompt="task B"
- )
+ await _insert_mission(db_conn, mission_id=mid_a, state="APPROVED", prompt="task A")
+ await _insert_mission(db_conn, mission_id=mid_b, state="FAILED", prompt="task B")
with TestClient(app) as client:
r = client.get("/api/outputs")
@@ -587,9 +569,7 @@ async def test_list_outputs_mission_dir_ignores_task_subdir_names(
prompt="WRONG ROW — should not appear",
)
# And the correct mission row.
- await _insert_mission(
- db_conn, mission_id=mission_id, state="APPROVED", prompt="correct row"
- )
+ await _insert_mission(db_conn, mission_id=mission_id, state="APPROVED", prompt="correct row")
with TestClient(app) as client:
r = client.get("/api/outputs")
@@ -626,9 +606,7 @@ async def test_list_outputs_without_mission_manager_stays_functional(
@pytest.mark.asyncio
-async def test_get_output_plan_returns_empty_stub(
- app: FastAPI, tmp_path: Path
-) -> None:
+async def test_get_output_plan_returns_empty_stub(app: FastAPI, tmp_path: Path) -> None:
"""The Plan tab is intentionally a placeholder (Welle-4 not plumbed).
Confirmed as out-of-scope per the B1 brief: returns ``{plan: null,
@@ -637,9 +615,7 @@ async def test_get_output_plan_returns_empty_stub(
"""
_make_mission_dir(tmp_path, "019e3600-eeee-7000-8000-000000000040")
with TestClient(app) as client:
- r = client.get(
- "/api/outputs/mission_019e3600-eeee/plan"
- )
+ r = client.get("/api/outputs/mission_019e3600-eeee/plan")
assert r.status_code == 200
assert r.json() == {"plan": None, "steps": []}
@@ -662,20 +638,12 @@ async def test_get_output_plan_404_for_unknown_slug(app: FastAPI) -> None:
def test_is_deliverable_relpath() -> None:
"""The allowlist predicate: only ``tasks/<id>/artifacts/files/<rel>`` wins."""
- assert _is_deliverable_relpath(
- ("tasks", "019e0000", "artifacts", "files", "out.html")
- )
- assert _is_deliverable_relpath(
- ("tasks", "019e0000", "artifacts", "files", "sub", "deep.css")
- )
+ assert _is_deliverable_relpath(("tasks", "019e0000", "artifacts", "files", "out.html"))
+ assert _is_deliverable_relpath(("tasks", "019e0000", "artifacts", "files", "sub", "deep.css"))
# Forensic + scaffolding paths are all rejected.
- assert not _is_deliverable_relpath(
- ("tasks", "019e0000", "artifacts", "diff.patch")
- )
+ assert not _is_deliverable_relpath(("tasks", "019e0000", "artifacts", "diff.patch"))
assert not _is_deliverable_relpath(("claude_config", "settings.json"))
- assert not _is_deliverable_relpath(
- ("claude_config", "sessions", "45552.json")
- )
+ assert not _is_deliverable_relpath(("claude_config", "sessions", "45552.json"))
assert not _is_deliverable_relpath((".codex", "auth.json"))
assert not _is_deliverable_relpath(("openclaw_state", "openclaw.json"))
assert not _is_deliverable_relpath(("reflections.md",))
@@ -697,8 +665,14 @@ def test_is_deliverable_relpath_excludes_browser_scratch() -> None:
(*base, "qa-artifacts", "chrome-profile-dd6355b8", "Last Browser")
)
assert not _is_deliverable_relpath(
- (*base, "qa-artifacts", "chrome-profile-dd6355b8", "Default",
- "Shared Dictionary", "db-journal")
+ (
+ *base,
+ "qa-artifacts",
+ "chrome-profile-dd6355b8",
+ "Default",
+ "Shared Dictionary",
+ "db-journal",
+ )
)
# Genuine deliverables — including one INSIDE qa-artifacts/ next to junk.
assert _is_deliverable_relpath((*base, "index.html"))
@@ -706,9 +680,7 @@ def test_is_deliverable_relpath_excludes_browser_scratch() -> None:
@pytest.mark.asyncio
-async def test_list_artifacts_lists_only_deliverables(
- app: FastAPI, tmp_path: Path
-) -> None:
+async def test_list_artifacts_lists_only_deliverables(app: FastAPI, tmp_path: Path) -> None:
"""Only genuine deliverables are listed; the forensic ``diff.patch`` one
level up in ``artifacts/`` is excluded (contract change 2026-05-30)."""
d = _make_mission_dir(tmp_path, "019e3288abcd")
@@ -723,9 +695,7 @@ async def test_list_artifacts_lists_only_deliverables(
@pytest.mark.asyncio
-async def test_list_artifacts_skips_claude_config_scaffolding(
- app: FastAPI, tmp_path: Path
-) -> None:
+async def test_list_artifacts_skips_claude_config_scaffolding(app: FastAPI, tmp_path: Path) -> None:
"""The isolated ``CLAUDE_CONFIG_DIR`` (``run_dir/claude_config/``) seeded by
``build_worker_env`` must never leak into the Outputs view."""
d = _make_mission_dir(tmp_path, "019e3288abcd")
@@ -752,9 +722,7 @@ async def test_list_artifacts_skips_claude_config_scaffolding(
@pytest.mark.asyncio
-async def test_list_artifacts_skips_codex_and_forensics(
- app: FastAPI, tmp_path: Path
-) -> None:
+async def test_list_artifacts_skips_codex_and_forensics(app: FastAPI, tmp_path: Path) -> None:
"""``.codex/`` (CODEX_HOME), worker ``logs/`` and ``reflections.md`` are
internal scaffolding — only the deliverable survives the listing filter."""
d = _make_mission_dir(tmp_path, "019e3288abcd")
@@ -773,9 +741,7 @@ async def test_list_artifacts_skips_codex_and_forensics(
@pytest.mark.asyncio
-async def test_list_artifacts_lists_nested_deliverables(
- app: FastAPI, tmp_path: Path
-) -> None:
+async def test_list_artifacts_lists_nested_deliverables(app: FastAPI, tmp_path: Path) -> None:
"""Deliverables in nested sub-dirs under ``artifacts/files/`` are kept."""
d = _make_mission_dir(tmp_path, "019e3288abcd")
_seed(
@@ -793,14 +759,9 @@ async def test_list_artifacts_lists_nested_deliverables(
async def test_raw_serves_deliverable(app: FastAPI, tmp_path: Path) -> None:
"""The raw-file endpoint returns the contents of a genuine deliverable."""
d = _make_mission_dir(tmp_path, "019e3288abcd")
- _seed(
- d / "tasks" / "019e0000" / "artifacts" / "files" / "out.txt", "payload"
- )
+ _seed(d / "tasks" / "019e0000" / "artifacts" / "files" / "out.txt", "payload")
with TestClient(app) as client:
- r = client.get(
- f"/api/outputs/{d.name}/files/"
- "tasks/019e0000/artifacts/files/out.txt/raw"
- )
+ r = client.get(f"/api/outputs/{d.name}/files/tasks/019e0000/artifacts/files/out.txt/raw")
assert r.status_code == 200
assert r.json()["text"] == "payload"
@@ -813,9 +774,7 @@ async def test_raw_404s_for_scaffolding(app: FastAPI, tmp_path: Path) -> None:
d = _make_mission_dir(tmp_path, "019e3288abcd")
_seed(d / "claude_config" / ".claude.json", '{"secret":"x"}')
with TestClient(app) as client:
- r = client.get(
- f"/api/outputs/{d.name}/files/claude_config/.claude.json/raw"
- )
+ r = client.get(f"/api/outputs/{d.name}/files/claude_config/.claude.json/raw")
assert r.status_code == 404
@@ -825,8 +784,7 @@ async def test_raw_404s_for_scaffolding(app: FastAPI, tmp_path: Path) -> None:
def _make_deliverable(root: Path, mission_id: str, name: str, content: str) -> str:
"""Create tasks/<tid>/artifacts/files/<name> under mission_<id>; return rel path."""
files_dir = (
- root / f"mission_{mission_id[:13]}" / "tasks" / "019edeadbeef"
- / "artifacts" / "files"
+ root / f"mission_{mission_id[:13]}" / "tasks" / "019edeadbeef" / "artifacts" / "files"
)
files_dir.mkdir(parents=True, exist_ok=True)
(files_dir / name).write_text(content, encoding="utf-8")
@@ -847,14 +805,22 @@ def test_download_sets_attachment_disposition(app):
assert r.text == "# Hi"
-def test_download_inline_disposition(app):
+ ("filename", "content"),
+ [
+ ("page.html", "<p>x</p>"),
+ ("image.svg", "<svg><script>bad()</script></svg>"),
+ ],
+)
+def test_download_inline_active_document_has_csp(app, filename, content):
root = Path(app.state.outputs_root)
slug = "mission_019ed2dfd0fab"
- rel = _make_deliverable(root, "019ed2dfd0fab1234", "page.html", "<p>x</p>")
+ rel = _make_deliverable(root, "019ed2dfd0fab1234", filename, content)
client = TestClient(app)
r = client.get(f"/api/outputs/{slug}/files/{rel}/download?disposition=inline")
assert r.status_code == 200
assert r.headers["content-disposition"].startswith("inline")
+ assert "default-src 'none'" in r.headers["content-security-policy"]
def test_download_blocks_non_deliverable(app):
@@ -931,9 +897,7 @@ def test_open_session_folder_calls_reveal_in_folder(app):
target = root / slug
target.mkdir(parents=True, exist_ok=True)
client = TestClient(app)
- with patch(
- "jarvis.platform.open_path.reveal_in_folder", return_value=True
- ) as rev:
+ with patch("jarvis.platform.open_path.reveal_in_folder", return_value=True) as rev:
r = client.post(f"/api/outputs/{slug}/open")
assert r.status_code == 200
assert r.json() == {"opened": True, "path": str(target.resolve())}
@@ -1023,6 +987,7 @@ def test_download_attachment_html_no_csp_needed(app):
def test_view_rejects_oversize_file(app, monkeypatch):
import jarvis.ui.web.outputs_routes as oroutes
+
monkeypatch.setattr(oroutes, "_VIEW_MAX_BYTES", 4)
root = Path(app.state.outputs_root)
slug = "mission_019ed2dfd0fab"
@@ -1045,10 +1010,12 @@ def _fake_resolver_only(*installed: str):
"""Return a resolve_app_launch_target stub where only *installed* keys map
to a real executable; everything else returns the raw-name startfile
fallback (= 'not installed')."""
+
def _resolve(name: str) -> LaunchTarget:
if name in installed:
return LaunchTarget("executable", rf"C:\apps\{name}.exe")
return LaunchTarget("startfile", name)
+
return _resolve
@@ -1062,11 +1029,12 @@ def test_openers_native_disabled_returns_empty(app):
def test_openers_always_includes_default(app):
app.state.native_file_actions = True
- with patch(
- "jarvis.plugins.tool.app_resolver.resolve_app_launch_target",
- side_effect=_fake_resolver_only(),
- ), patch(
- "jarvis.ui.web.outputs_routes._resolve_browser_target", return_value=None
+ with (
+ patch(
+ "jarvis.plugins.tool.app_resolver.resolve_app_launch_target",
+ side_effect=_fake_resolver_only(),
+ ),
+ patch("jarvis.ui.web.outputs_routes._resolve_browser_target", return_value=None),
):
client = TestClient(app)
r = client.get("/api/outputs/openers")
@@ -1076,11 +1044,12 @@ def test_openers_always_includes_default(app):
def test_openers_detects_installed_editor_only(app):
app.state.native_file_actions = True
- with patch(
- "jarvis.plugins.tool.app_resolver.resolve_app_launch_target",
- side_effect=_fake_resolver_only("code"),
- ), patch(
- "jarvis.ui.web.outputs_routes._resolve_browser_target", return_value=None
+ with (
+ patch(
+ "jarvis.plugins.tool.app_resolver.resolve_app_launch_target",
+ side_effect=_fake_resolver_only("code"),
+ ),
+ patch("jarvis.ui.web.outputs_routes._resolve_browser_target", return_value=None),
):
client = TestClient(app)
r = client.get("/api/outputs/openers")
@@ -1098,10 +1067,9 @@ def test_openers_result_is_memoized(app):
app.state.native_file_actions = True
resolver = MagicMock(side_effect=_fake_resolver_only("code"))
- with patch(
- "jarvis.plugins.tool.app_resolver.resolve_app_launch_target", resolver
- ), patch(
- "jarvis.ui.web.outputs_routes._resolve_browser_target", return_value=None
+ with (
+ patch("jarvis.plugins.tool.app_resolver.resolve_app_launch_target", resolver),
+ patch("jarvis.ui.web.outputs_routes._resolve_browser_target", return_value=None),
):
client = TestClient(app)
first = client.get("/api/outputs/openers")
@@ -1119,9 +1087,7 @@ def test_open_with_404_when_native_disabled(app):
rel = _make_deliverable(root, "019ed2dfd0fab1234", "report.md", "# Hi")
app.state.native_file_actions = False
client = TestClient(app)
- r = client.post(
- f"/api/outputs/{slug}/files/{rel}/open-with", json={"opener": "default"}
- )
+ r = client.post(f"/api/outputs/{slug}/files/{rel}/open-with", json={"opener": "default"})
assert r.status_code == 404
@@ -1147,12 +1113,13 @@ def test_open_with_editor_calls_open_file_with(app):
rel = _make_deliverable(root, "019ed2dfd0fab1234", "report.md", "# Hi")
app.state.native_file_actions = True
client = TestClient(app)
- with patch(
- "jarvis.plugins.tool.app_resolver.resolve_app_launch_target",
- side_effect=_fake_resolver_only("code"),
- ), patch(
- "jarvis.platform.open_path.open_file_with", return_value=True
- ) as opn:
+ with (
+ patch(
+ "jarvis.plugins.tool.app_resolver.resolve_app_launch_target",
+ side_effect=_fake_resolver_only("code"),
+ ),
+ patch("jarvis.platform.open_path.open_file_with", return_value=True) as opn,
+ ):
r = client.post(
f"/api/outputs/{slug}/files/{rel}/open-with",
json={"opener": "code"},
@@ -1215,12 +1182,8 @@ def test_get_preferred_opener_defaults_empty(app):
def test_put_preferred_opener_persists_and_updates(app):
app.state.config = SimpleNamespace(ui=SimpleNamespace(preferred_opener=""))
client = TestClient(app)
- with patch(
- "jarvis.core.config_writer.set_preferred_opener"
- ) as setter:
- r = client.put(
- "/api/outputs/preferred-opener", json={"opener": "code"}
- )
+ with patch("jarvis.core.config_writer.set_preferred_opener") as setter:
+ r = client.put("/api/outputs/preferred-opener", json={"opener": "code"})
assert r.status_code == 200
setter.assert_called_once_with("code")
assert app.state.config.ui.preferred_opener == "code"
@@ -1228,7 +1191,5 @@ def test_put_preferred_opener_persists_and_updates(app):
def test_put_preferred_opener_rejects_unknown(app):
client = TestClient(app)
- r = client.put(
- "/api/outputs/preferred-opener", json={"opener": "../../evil"}
- )
+ r = client.put("/api/outputs/preferred-opener", json={"opener": "../../evil"})
assert r.status_code == 400