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: sync working tree — track in-flight feature modules + fixes

Ruben Lütke779af81142cc
diff --git a/.claude/skills/ship-public-release/references/distribution-denylist.txt b/.claude/skills/ship-public-release/references/distribution-denylist.txt
index 5afeaf70d7..93d30fd3e6 100644
--- a/.claude/skills/ship-public-release/references/distribution-denylist.txt
+++ b/.claude/skills/ship-public-release/references/distribution-denylist.txt
@@ -59,6 +59,11 @@ scripts/_*.py
scripts/config-soll.json
scripts/drift-guard-task.xml
.tmp_research/**
+# Root-level optimization/loop ledgers — internal dev scratchpads (the running
+# notes of a /loop session: measurements, reasoning, file paths). Like the
+# untracked progress.md, they have no downstream product value. boot-progress.md
+# was committed (so it is tracked) and would otherwise ship; withhold it.
+boot-progress.md
# --- Internal dev-process docs: whole subtrees ------------------------------
docs/superpowers/**
diff --git a/.github/workflows/ci.yml b/.github/workflows/ci.yml
index 56ab733ded..421a1fbbca 100644
--- a/.github/workflows/ci.yml
+++ b/.github/workflows/ci.yml
@@ -19,6 +19,15 @@
# * pytest failures -> reported (the floor script warns; pass
# --strict once the suite is fully green to make them blocking).
#
+# Cost policy (added 2026-06-23): macOS runners bill at ~10x the Linux rate, so
+# the macOS leg is OFF for ordinary push/PR runs and ON only for a manual
+# workflow_dispatch (the `include_macos` input, default true). Linux + Windows
+# run on every push/PR and catch almost all cross-platform regressions. A
+# `concurrency` group cancels a superseded in-flight run so a burst of commits
+# can't stack billable minutes. To prove macOS on demand: the Actions tab ->
+# "Run workflow", or `gh workflow run ci.yml`. The `configure` job is the single
+# source of truth for which OS legs run (consumed by both `test` and `jarvisctl`).
+#
# Action SHAs are pinned to 40-char commits already vetted elsewhere in this
# repo's workflows (CVE-2025-30066 hardening).
@@ -30,20 +39,55 @@ on:
- main
- "wip/cross-platform-cloud-first-20260529"
pull_request:
+ workflow_dispatch:
+ inputs:
+ include_macos:
+ description: "Also run the macOS leg (~10x runner cost). On by default for a manual run, since proving macOS is usually the point of dispatching by hand."
+ type: boolean
+ default: true
+
+# Cost control: a new push to the same ref cancels the previous in-flight run,
+# so a burst of commits doesn't stack up billable runner minutes. Keyed on ref
+# so different branches never cancel each other.
+concurrency:
+ group: ci-${{ github.workflow }}-${{ github.ref }}
+ cancel-in-progress: true
permissions:
contents: read
jobs:
+ # Single source of truth for which OS legs run. macOS bills at ~10x the Linux
+ # rate, so it is included ONLY for a manual workflow_dispatch with include_macos
+ # (default true). Every ordinary push/PR runs the cheap Linux + Windows legs,
+ # which catch almost all cross-platform regressions. Both `test` and `jarvisctl`
+ # consume this output so the policy lives in exactly one place.
+ configure:
+ name: configure matrix (cost-aware)
+ runs-on: ubuntu-latest
+ timeout-minutes: 5
+ outputs:
+ os-matrix: ${{ steps.pick.outputs.os-matrix }}
+ steps:
+ - name: Pick OS matrix
+ id: pick
+ shell: bash
+ run: |
+ if [ "${{ github.event_name }}" = "workflow_dispatch" ] && [ "${{ inputs.include_macos }}" = "true" ]; then
+ echo 'os-matrix=["ubuntu-latest","windows-latest","macos-latest"]' >> "$GITHUB_OUTPUT"
+ echo "macOS leg INCLUDED (manual dispatch)."
+ else
+ echo 'os-matrix=["ubuntu-latest","windows-latest"]' >> "$GITHUB_OUTPUT"
+ echo "macOS leg SKIPPED (cheap push/PR run). Dispatch manually to include it."
+ fi
+
test:
name: test (${{ matrix.os }})
+ needs: configure
strategy:
- fail-fast: false # we want to see ALL three OS legs, not just the first red one
+ fail-fast: false # we want to see ALL OS legs, not just the first red one
matrix:
- os:
- - ubuntu-latest
- - macos-latest
- - windows-latest
+ os: ${{ fromJSON(needs.configure.outputs.os-matrix) }}
runs-on: ${{ matrix.os }}
timeout-minutes: 30
@@ -116,13 +160,11 @@ jobs:
# all three OS legs.
jarvisctl:
name: jarvisctl unit (${{ matrix.os }})
+ needs: configure
strategy:
fail-fast: false
matrix:
- os:
- - ubuntu-latest
- - macos-latest
- - windows-latest
+ os: ${{ fromJSON(needs.configure.outputs.os-matrix) }}
runs-on: ${{ matrix.os }}
timeout-minutes: 15
@@ -142,7 +184,10 @@ jobs:
run: |
python -m pip install --upgrade pip
python -m pip install -e ".[dev]" --no-deps
- python -m pip install typer platformdirs httpx rich
+ # pytest is needed to RUN the suite; --no-deps above skips it (and all
+ # of [dev]'s deps), so install the test runner explicitly alongside the
+ # CLI's own runtime deps. Keeps the job light (no torch/heavy deps).
+ python -m pip install typer platformdirs httpx rich pytest pytest-asyncio
- name: pytest (jarvisctl unit suite)
run: python -m pytest tests/unit/cli_ctl/ -v
diff --git a/.github/workflows/dragdrop-verify.yml b/.github/workflows/dragdrop-verify.yml
new file mode 100644
index 0000000000..30e62ef4cd
--- /dev/null
+++ b/.github/workflows/dragdrop-verify.yml
@@ -0,0 +1,70 @@
+# Cross-platform drag-drop verification — proves the overlay drop mechanism
+# (tkdnd load + parse + register + drop chain) actually EXECUTES on Windows,
+# macOS AND Linux, by running the same
+# `scripts/crossplatform/verify_drop_target.py` on each.
+#
+# Cost policy (2026-06-23): macOS runners bill at ~10x the Linux rate, so the
+# macos-latest leg — the autonomous macOS proof that cannot be produced on a
+# Windows dev box — runs ONLY on a manual `workflow_dispatch` (the Actions tab
+# -> "Run workflow", or `gh workflow run dragdrop-verify.yml`). An ordinary
+# push/PR that touches the drop files runs the cheap Linux + Windows legs. The
+# `concurrency` group cancels a superseded in-flight run.
+name: dragdrop-crossplatform-verify
+
+on:
+ push:
+ paths:
+ - "jarvis/overlay/drop_target.py"
+ - "jarvis/overlay/drop_bridge.py"
+ - "scripts/crossplatform/verify_drop_target.py"
+ - ".github/workflows/dragdrop-verify.yml"
+ pull_request:
+ paths:
+ - "jarvis/overlay/drop_target.py"
+ - "jarvis/overlay/drop_bridge.py"
+ - "scripts/crossplatform/verify_drop_target.py"
+ workflow_dispatch: {}
+
+# Cost control: a superseding push to the same ref cancels the in-flight run.
+concurrency:
+ group: dragdrop-${{ github.workflow }}-${{ github.ref }}
+ cancel-in-progress: true
+
+jobs:
+ verify:
+ name: drag-drop (${{ matrix.os }})
+ strategy:
+ fail-fast: false
+ # macOS (~10x cost) only on a manual dispatch; push/PR runs Linux + Windows.
+ matrix:
+ os: ${{ github.event_name == 'workflow_dispatch' && fromJSON('["ubuntu-latest","macos-latest","windows-latest"]') || fromJSON('["ubuntu-latest","windows-latest"]') }}
+ runs-on: ${{ matrix.os }}
+ steps:
+ - uses: actions/checkout@v4
+ - uses: actions/setup-python@v5
+ with:
+ python-version: "3.11"
+ - name: Install tkinterdnd2 (+ Linux X11 runtime libs)
+ shell: bash
+ run: |
+ python -m pip install --upgrade pip
+ # Pin ==0.4.2: from 0.4.4.1 onward the osx-arm64 tkdnd binary is the
+ # Tcl-9 build (libtcl9tkdnd2.9.5.dylib) that fails to load on the
+ # standard Tcl-8.6 Python ("incompatible stubs mechanism"). 0.4.2 is the
+ # highest version whose osx-arm64 binary is the Tcl-8 build
+ # (libtkdnd2.9.3.dylib), which loads on Tcl-8.6 across all three OSes.
+ pip install "tkinterdnd2==0.4.2"
+ if [ "$RUNNER_OS" = "Linux" ]; then
+ sudo apt-get update -qq
+ sudo apt-get install -y --no-install-recommends \
+ python3-tk xvfb libxcursor1 libxrender1 libxext6 \
+ libxft2 libxinerama1 libxi6 libxrandr2
+ fi
+ - name: Verify drag-drop executes on ${{ matrix.os }}
+ shell: bash
+ run: |
+ if [ "$RUNNER_OS" = "Linux" ]; then
+ xvfb-run -a python scripts/crossplatform/verify_drop_target.py
+ else
+ python scripts/crossplatform/verify_drop_target.py
+ fi
diff --git a/CLAUDE.md b/CLAUDE.md
index 37ed9c80b2..3d1341c24b 100644
--- a/CLAUDE.md
+++ b/CLAUDE.md
@@ -183,6 +183,12 @@ Access via `jarvis.core.config.get_secret(key, env_fallback)` only. Hierarchy: W
Multi-provider is mandatory — **never hardcode** Anthropic/Claude. Config under `[brain.providers.*]` in `jarvis.toml`. Runtime switch via voice ("Jarvis, switch to Gemini") is a plan requirement; `BrainManager` must support it. Smart fallback chain in `jarvis/brain/manager.py`. Workers use `claude-cli` backend via Claude Max OAuth (user has no Anthropic API account).
+#### Provider-agnostic features (no provider/model hardcoding) — BINDING
+
+Every feature must work with **whatever brain provider the user has selected/activated**, and across all configured providers — there are five API providers (`claude-api`, `openrouter`, `openai`, `gemini`, `grok`) plus two subscription-CLI brains (`codex` over ChatGPT, `antigravity` over the Google login), and any of them may be the active one. **Never branch on a provider name or a model id to enable or disable behavior** — no `if provider == "grok"`, no hardcoded `grok-4.3`, no provider-specific code path. Gate on a **capability** instead: `supports_vision`, `supports_tools`, the runtime `can_call_tools()` (and codex's runtime `supports_vision`). If the capability you need doesn't exist yet, **add a capability flag — do not name-check the provider**.
+
+When the active/selected provider lacks a needed capability — e.g. a text-only CLI brain (`antigravity` / `codex-CLI`) cannot see images for Computer-Use — fall through to the first **available** provider that *has* the capability, provider-agnostically and never pinned to a favorite; if none is available, degrade gracefully with an honest message. A provider or model literal may appear **only** as a documented default/fallback (a plugin's own `DEFAULT_MODEL`) or behind a runtime capability probe — never as the gate that decides whether a feature runs. The Computer-Use "no vision" incident was a *capability-flag* bug (grok's `supports_vision` was wrongly `False`) — the correct fix was to set the flag, **not** to pin Computer-Use to grok. This generalizes AP-6 (don't hardcode Claude) to **don't hardcode *any* provider** and is the operational form of the multi-provider mandate above (see AP-21).
+
Ack-Brain (`jarvis/brain/ack_brain/`) emits a sub-second butler-style preamble before the deep brain replies. Suppress-if-fast gate at 2000ms keeps it out of the way when the deep brain is already fast.
**Persona / custom system prompt:** the live persona comes from `jarvis/brain/persona_loader.py`. `load_effective_persona_prompt()` returns an editable override (`data/custom_system_prompt.md`, written atomically via the Settings UI / `settings_routes.py`) when present, else the packaged `JARVIS_PERSONA.md`. Edits apply on the **next turn** (no restart); `invalidate_cache()` clears the in-process cache. Never hardcode the persona string elsewhere.
@@ -421,6 +427,7 @@ pytest tests/integration/test_openclaw_lazy_bootstrap.py
| AP-18 | Propagate a subscriber exception from `EventBus._safe_dispatch` | One handler kills the pipeline |
| AP-19 | Reuse a process-global progress counter in a stall/heartbeat watchdog without resetting it per unit of work | BUG-032: watchdog measures the idle gap *between* turns → spuriously aborts a fresh TTS answer before its first frame ("Jarvis listens forever") |
| AP-20 | `continue` (instead of `break`) a WS receive loop on an error that isn't `WebSocketDisconnect` | Unclean client disconnects raise `RuntimeError("WebSocket is not connected")`, not `WebSocketDisconnect` → the loop re-reads a dead socket forever → ~9 MB/s log storm + app self-restart that kills in-flight missions. Catch `RuntimeError` and `break` (`server.py` `_handle_ws`, fixed 1793ceaf) |
+| AP-21 | Pin a feature to a provider **name** or a **model id** (`if provider == "grok"`, hardcoded `grok-4.3`, a provider-specific branch) instead of gating on a **capability** | The feature silently breaks for every other provider and for whatever provider the user selected — the multi-provider mandate (AP-6) generalized to *any* provider. Gate on `supports_vision` / `supports_tools` / `can_call_tools()`; if the flag is wrong or missing, fix/add the capability (e.g. grok's `supports_vision` was wrongly `False` → Computer-Use died "no vision"; the fix was the flag, not pinning CU to grok) |
---
diff --git a/CONTRIBUTING.md b/CONTRIBUTING.md
index 983054cdb3..e904a77211 100644
--- a/CONTRIBUTING.md
+++ b/CONTRIBUTING.md
@@ -1,36 +1,66 @@
-# Contributing to Personal Jarvis
-
-Thank you for contributing to Personal Jarvis! This guide covers everything you need:
-setting up your dev environment, understanding the architecture, deciding what to build,
-and getting your PR merged.
-
-> All artifacts in this repo are **English** — code, comments, docstrings, docs, commit
-> messages, and PR text. (You can talk to us in any language; the assistant speaks de/en/es
-> at runtime — but everything written into the repo is English. CI enforces this.)
+<p align="center">
+ <a href="https://github.com/PersonalJarvis/PersonalJarvis">
+ <img src="assets/brand/banner.png" alt="Personal Jarvis" width="520" />
+ </a>
+</p>
+
+<h1 align="center">Contributing</h1>
+
+<p align="center">
+ Thank you for helping build Personal Jarvis.<br/>
+ This guide covers dev setup, the architecture, what to build, and getting your PR merged.
+</p>
+
+<p align="center">
+ <a href="https://github.com/PersonalJarvis/PersonalJarvis/pulls"><img alt="PRs welcome" src="https://img.shields.io/badge/PRs-welcome-FFD60A?style=flat-square&labelColor=0A0A0A" /></a>
+ <a href="https://github.com/PersonalJarvis/PersonalJarvis/issues?q=is%3Aissue+is%3Aopen+label%3A%22good+first+issue%22"><img alt="Good first issues" src="https://img.shields.io/badge/good%20first%20issues-open-FFD60A?style=flat-square&labelColor=0A0A0A" /></a>
+ <a href="https://discord.gg/UPu6pFWrJ"><img alt="Discord" src="https://img.shields.io/badge/Discord-join-FFD60A?style=flat-square&logo=discord&logoColor=0A0A0A&labelColor=0A0A0A" /></a>
+ <a href="LICENSE"><img alt="License: MIT" src="https://img.shields.io/badge/License-MIT-FFD60A?style=flat-square&labelColor=0A0A0A" /></a>
+</p>
+
+> [!IMPORTANT]
+> **All artifacts in this repo are English** — code, comments, docstrings, docs, commit
+> messages, and PR text. You can talk to us in any language (the assistant itself speaks
+> de/en/es at runtime), but everything written *into the repo* is English. CI enforces this.
+
+---
+
+## Contents
+
+- [Contribution priorities](#contribution-priorities)
+- [Before you start](#before-you-start)
+- [Development environment](#development-environment)
+- [Architecture in 60 seconds](#architecture-in-60-seconds)
+- [Plugin, Tool, or Skill?](#plugin-tool-or-skill)
+- [Conventions](#conventions)
+- [Testing](#testing)
+- [Opening your PR](#opening-your-pr)
+- [Community](#community)
+
+---
## Contribution priorities
We value contributions in this order:
-1. **Bug fixes** — crashes, incorrect behavior, data loss, voice-path regressions. Always top priority.
-2. **Cross-platform compatibility** — Linux, macOS, Windows, and headless servers. A feature
- that only works on one OS is *incomplete*, not "done with a known limitation". See
- [`docs/PHILOSOPHY.md`](docs/PHILOSOPHY.md).
-3. **Security hardening** — prompt injection, the instruction-source boundary, the risk-tier
- policy, path traversal, privilege escalation, secret handling. See [`SECURITY.md`](SECURITY.md).
-4. **Performance & robustness** — voice latency budgets, retry logic, graceful degradation,
- and the "conversation never blocks" contract.
-5. **New providers / plugins** — wake, STT, TTS, brain, harness, tool, or channel plugins.
- Must be provider-agnostic and pass the contract suite.
-6. **New skills** — but only broadly useful ones. Generated skills land as drafts and are
- never auto-activated.
-7. **Documentation** — fixes, clarifications, new examples.
+| # | Priority | What it covers |
+|:---:|---|---|
+| 1 | **Bug fixes** | Crashes, incorrect behavior, data loss, voice-path regressions. Always top priority. |
+| 2 | **Cross-platform** | Linux, macOS, Windows, headless servers. A feature that only works on one OS is *incomplete* — see [`docs/PHILOSOPHY.md`](docs/PHILOSOPHY.md). |
+| 3 | **Security hardening** | Prompt injection, the instruction-source boundary, the risk-tier policy, path traversal, privilege escalation — see [`SECURITY.md`](SECURITY.md). |
+| 4 | **Performance & robustness** | Voice latency budgets, retry logic, graceful degradation, the "conversation never blocks" contract. |
+| 5 | **New providers / plugins** | Wake · STT · TTS · brain · harness · tool · channel. Provider-agnostic, and must pass the contract suite. |
+| 6 | **New skills** | Broadly useful ones only. Generated skills land as drafts and are never auto-activated. |
+| 7 | **Documentation** | Fixes, clarifications, new examples. |
## Before you start
+> [!TIP]
+> For anything non-trivial, **open an issue first** so we can agree on the approach — it
+> saves you from a merged-PR-shaped surprise.
+
- Search existing issues, and say hi on [Discord](https://discord.gg/UPu6pFWrJ).
-- For anything non-trivial, open an issue first so we can agree on the approach.
-- Keep PRs focused — one logical change per PR is much easier to review and merge.
+- Keep each PR focused — one logical change is far easier to review and merge.
## Development environment
@@ -49,59 +79,48 @@ python -m jarvis --wizard # interactive first-run setup
python -m jarvis.ui.web.launcher # run it (add --headless for a server)
```
-- **After editing entry-points** (`pyproject.toml`), re-run `pip install -e . --no-deps` —
- this is what activates new plugins.
-- **Frontend** lives in `jarvis/ui/web/frontend/`: `npm install`, then `npm run dev`
- (`http://localhost:5173`), `npm run build`, `npm run test`.
+> [!NOTE]
+> After editing entry-points in `pyproject.toml`, re-run `pip install -e . --no-deps` — that
+> is what activates new plugins. The frontend lives in `jarvis/ui/web/frontend/`
+> (`npm install`, then `npm run dev` / `npm run build` / `npm run test`).
## Architecture in 60 seconds
Personal Jarvis is an 8-layer system. The rules that matter for contributors:
-- **Higher layers reach lower layers only through protocols** (`jarvis/core/protocols.py`).
- Lateral communication is only via typed, immutable events on the **EventBus**.
-- **Streaming-first** — `Brain`/`STT`/`TTS`/`Harness` methods return `AsyncIterator`;
- non-streaming providers yield exactly one element.
-- **Provider-agnostic** — never hardcode a single brain vendor; `cfg.brain.primary` selects.
-- **Router-Brain dispatches** to interchangeable harnesses; heavy work runs as **missions**
- in isolated `git worktree` branches under a Worker-Critic loop.
-
-For the deep dive, read [`docs/LLM-CONTEXT.md`](docs/LLM-CONTEXT.md) (a dense, self-contained
-engineering snapshot), [`CLAUDE.md`](CLAUDE.md) (binding conventions), and
-[`docs/PHILOSOPHY.md`](docs/PHILOSOPHY.md) (the cross-platform, cloud-first doctrine).
-
-## Should it be a Plugin, a Tool, or a Skill?
-
-This is the most common design question. Pick the smallest thing that fits:
-
-- **Plugin** — a swappable *provider* in one of the seven groups (`wakeword`, `stt`, `tts`,
- `brain`, `harness`, `tool`, `channel`). Plugins live under `jarvis/plugins/<group>/<name>.py`,
- register via `pyproject.toml` entry-points, and **must not import from `jarvis.*`** inside
- the plugin module — only structural Protocol compatibility. New STT/Brain/Tool/Channel
- providers must pass `tests/contract/`.
-- **Tool** — a discrete capability the brain can call *within a turn*. Tools go through the
- `ToolExecutor` and the risk-tier policy. **Never call `Tool.execute()` directly.**
-- **Skill** — a higher-level, authored capability or multi-step workflow. Generated skills
- are created as `draft` and are never auto-activated.
-
-Rule of thumb: a swappable backend → **plugin**; a single brain-callable action → **tool**;
-an authored multi-step workflow → **skill**.
-
-## Conventions that keep the project coherent
-
-- **English artifacts**, always (CI `language-policy` gate).
-- **Risk-tier discipline** — `ToolExecutor.execute()` is the only authorized execution path.
-- **Router discipline** — `ROUTER_TOOLS` is a frozenset; no spawn-tool ever enters a worker
- tool set (it creates a recursion vector).
-- **Enum-drift prevention** — any string crossing module boundaries (a status, a reason)
- uses the five-layer pattern (Python → SQL → Pydantic → TypeScript → UI) plus a parity test.
-- **Atomic config writes** — mutate `jarvis.toml` only through `config_writer` (lock +
- tempfile + BOM-safe).
-- **Subprocess hygiene** — pass `NO_WINDOW_CREATIONFLAGS` from `jarvis/core/process_utils.py`.
-- **Secrets** — only via `get_secret()`; never in code, config, or commits. Voice/chat must
- never accept secrets.
-- **No new hard dependency on Windows- or GPU-specific packages in the base install** — those
- go into the `[desktop]` extras with a graceful no-op fallback elsewhere.
+- **Higher layers reach lower layers only through protocols** (`jarvis/core/protocols.py`); lateral communication is only via typed, immutable events on the **EventBus**.
+- **Streaming-first** — `Brain`/`STT`/`TTS`/`Harness` methods return `AsyncIterator`; non-streaming providers yield exactly one element.
+- **Provider-agnostic** — never hardcode one brain vendor; `cfg.brain.primary` selects.
+- **Router-Brain dispatches** to interchangeable harnesses; heavy work runs as **missions** in isolated `git worktree` branches under a Worker-Critic loop.
+
+For the deep dive, read [`docs/LLM-CONTEXT.md`](docs/LLM-CONTEXT.md) (a dense engineering snapshot), [`CLAUDE.md`](CLAUDE.md) (binding conventions), and [`docs/PHILOSOPHY.md`](docs/PHILOSOPHY.md) (the cross-platform, cloud-first doctrine).
+
+## Plugin, Tool, or Skill?
+
+The most common design question — pick the smallest thing that fits:
+
+| | **Plugin** | **Tool** | **Skill** |
+|---|---|---|---|
+| **What it is** | A swappable *provider* | A brain-callable *action* within a turn | An authored, multi-step *workflow* |
+| **Where it lives** | `jarvis/plugins/<group>/` in one of 7 groups | Registered tool, run via `ToolExecutor` | Authored skill; generated ones start as `draft` |
+| **Golden rule** | No `import jarvis.*` inside the module; new STT/Brain/Tool/Channel must pass `tests/contract/` | **Never** call `Tool.execute()` directly | **Never** auto-activated |
+
+**Rule of thumb:** a swappable backend → **plugin**; a single brain-callable action → **tool**; an authored multi-step workflow → **skill**.
+
+## Conventions
+
+These keep the project coherent — most are enforced in CI:
+
+| Area | The rule |
+|---|---|
+| Language | English artifacts only (CI `language-policy` gate) |
+| Risk tier | `ToolExecutor.execute()` is the **only** authorized execution path |
+| Router | `ROUTER_TOOLS` is a frozenset; no spawn-tool in a worker tool set |
+| Enum drift | Strings crossing module boundaries use the five-layer pattern + a parity test |
+| Config writes | Mutate `jarvis.toml` only via `config_writer` (lock + tempfile + BOM-safe) |
+| Subprocess | Always pass `NO_WINDOW_CREATIONFLAGS` |
+| Secrets | Only via `get_secret()`; never in code, config, or commits |
+| Dependencies | No new Windows-/GPU-specific dependency in the base install — `[desktop]` extras only |
The full anti-pattern register lives in [`docs/LLM-CONTEXT.md`](docs/LLM-CONTEXT.md).
@@ -120,22 +139,29 @@ cd jarvis/ui/web/frontend && npm run test && npm run build
Tests use fakes (in `tests/fakes/`), not mocks. New providers must pass the contract suite.
-## Getting your PR merged
+## Opening your PR
-Before you open a PR, run through this checklist:
+Run through this checklist before you open it:
-- [ ] Tests pass (`pytest`), including `tests/contract/` for new providers.
-- [ ] `ruff` and `mypy` are clean; the frontend builds and `vitest` is green.
-- [ ] All new/changed artifacts are English (the CI language-policy gate is a required check).
-- [ ] New wire-format enums use the five-layer pattern + a parity test.
-- [ ] No new base-install dependency on Windows-/GPU-specific packages (extras only).
-- [ ] User-facing changes update the docs / `CHANGELOG.md`.
+- [ ] Tests pass (`pytest`), including `tests/contract/` for new providers
+- [ ] `ruff` and `mypy` are clean; the frontend builds and `vitest` is green
+- [ ] All new/changed artifacts are English (the CI language-policy gate is required)
+- [ ] New wire-format enums use the five-layer pattern + a parity test
+- [ ] No new base-install dependency on Windows-/GPU-specific packages (extras only)
+- [ ] User-facing changes update the docs / `CHANGELOG.md`
Open a PR with a clear description of *what* changed and *why*, and link the issue it closes.
By contributing, you agree your contribution is licensed under the [MIT License](LICENSE).
## Community
-- **Discord** — [discord.gg/UPu6pFWrJ](https://discord.gg/UPu6pFWrJ)
-- **X** — [@PersonalJarvis](https://x.com/PersonalJarvis)
-- **Issues** — [GitHub issues](https://github.com/PersonalJarvis/PersonalJarvis/issues)
+<p align="center">
+ <a href="https://discord.gg/UPu6pFWrJ"><img alt="Discord" src="https://img.shields.io/badge/Discord-join_the_server-FFD60A?style=for-the-badge&logo=discord&logoColor=0A0A0A&labelColor=0A0A0A" /></a>
+ <a href="https://x.com/PersonalJarvis"><img alt="X" src="https://img.shields.io/badge/X-follow-FFD60A?style=for-the-badge&logo=x&logoColor=0A0A0A&labelColor=0A0A0A" /></a>
+</p>
+
+<p align="center">
+ <a href="https://discord.gg/UPu6pFWrJ">Discord</a> ·
+ <a href="https://x.com/PersonalJarvis">X</a> ·
+ <a href="https://github.com/PersonalJarvis/PersonalJarvis/issues">Issues</a>
+</p>
diff --git a/README.md b/README.md
index 57b611984a..d865381cd0 100644
--- a/README.md
+++ b/README.md
@@ -1,712 +1,204 @@
-# Personal Jarvis
-
-> **Context-drop README.** This file is intentionally dense and self-contained: paste it into a fresh chat (Gemini Web, Claude Web, ChatGPT, Cursor) and the model gets enough context to reason about the project without paging through 30+ files. For the binding source-of-truth, see [`CLAUDE.md`](CLAUDE.md) + the docs linked at the bottom.
-
-**Personal Jarvis** is a voice-driven **Supervisor-Agent meta-orchestrator** — not a classical voice assistant. The core pattern is a fast **Router-Brain** that dispatches work to interchangeable harnesses (OpenClaw subprocess, Codex CLI, Open Interpreter, MCP servers, raw computer-use loops). The voice layer is just the I/O surface; the soul is the dispatcher discipline that keeps the Router-Brain lean and delegates heavy reasoning to specialized subagents under critic-loop + worktree-isolation guard rails. The project is **provider-agnostic by mandate** — the user has no Anthropic API account (Claude Max OAuth is used only inside workers) — and **self-modifying** via an atomic config-writer with a 10-step validate-backup-tempfile-replace-rollback-audit pipeline.
-
-> ### Cloud-First — Read This Before The Install Section
-> **Target runtime is any €5 / month VPS or low-spec laptop** with a modern browser. **The maintainer's RTX 5070 Ti / Windows 11 Pro workstation is not a requirement** — it represents fewer than 0.1 % of the install base this project is being designed for. All Brain / STT / TTS / Vision / Wake providers default to cloud APIs; no GPU, no local models, no Windows APIs, no microphone are required in the base install. Windows-desktop features (tray app, Orb overlay, global hotkey wake, local Whisper, Silero-VAD-in-process, Computer-Use harness, PowerShell drift-guard daemon) are **opt-in `[desktop]` extras**, not requirements. **Binding doctrine: [`docs/PHILOSOPHY.md`](docs/PHILOSOPHY.md)**. On conflict between this README and `PHILOSOPHY.md`, the doctrine wins.
-
-- **Base runtime:** Linux / macOS / Windows with Python 3.11+ and a network connection. Headless VPS + browser UI is a first-class deployment target.
-- **Maintainer's reference machine** (the project is developed on, but **does not require**, this hardware): RTX 5070 Ti, 32 GB RAM, CUDA 12.8, Windows 11 Pro — unlocks the optional `[desktop]` extras.
-- **Repo root** (maintainer's workstation; not relevant to consumers): `C:\Users\Administrator\Desktop\Personal Jarvis`
-- **Binding plan:** `~/.claude/plans/also-er-muss-auch-lexical-pond.md` (plan wins on plan-vs-code conflict).
-- **Binding doctrine:** [`docs/PHILOSOPHY.md`](docs/PHILOSOPHY.md) (cloud-first; wins over the binding plan when the two disagree on hardware assumptions).
-
----
-
-## Hardware — what you actually need
-
-Personal Jarvis ships in two very different shapes with **very different hardware needs**. The cloud-first base install is tiny; only the full desktop power-user profile with local voice models needs real hardware. Find your row below.
-
-**Measured footprint** — maintainer's Windows 11 workstation, full voice + UI mode, cloud Brain/STT/TTS, local openWakeWord, measured 2026-05-29:
-
-| Component | Resident (Working Set) | Committed |
-|---|---|---|
-| Backend (`pythonw -m jarvis.ui.web.launcher` — FastAPI + voice pipeline) | 0.95 GB | 2.2 GB |
-| Desktop UI (pywebview / WebView2 Chromium child processes) | 0.41 GB | — |
-| **Full desktop process tree** | **≈ 1.4 GB** | **≈ 2.6 GB** |
-
-> Budget **~2–2.5 GB of free RAM for the app** in desktop voice mode, not the 1.4 GB resident figure. Python *commits* the ML libraries at boot (chromadb / sentence-transformers embeddings, Silero-VAD, openWakeWord ONNX) even when they aren't all paged in — and under memory pressure, voice latency is the first thing to suffer.
-
-### RAM / CPU by deployment profile
-
-| Profile | What it does | Min system RAM | Min CPU | GPU | Disk |
-|---|---|---|---|---|---|
-| **A · Headless VPS / cloud** | base install, browser UI, all-cloud providers, no local audio | **2 GB** (1 GB boots with swap) | 1 vCPU | none | ~3 GB |
-| **B · Desktop, cloud voice** | pywebview window + mic/speaker + cloud STT/TTS + local wake word | **8 GB** | 2-core | none | ~4 GB |
-| **C · Desktop, full local** | local faster-whisper STT + local screen-vision (`--with-voice-local`) | **16 GB** | 4-core | NVIDIA ≥ 6 GB VRAM *or* Apple Silicon | ~8 GB + models |
-
-Profiles **A and B need no GPU at all** — that is the entire point of the cloud-first doctrine. A GPU only matters for Profile C, where Whisper / Vision run locally instead of calling Groq / Deepgram / Google.
-
-### Recommendation — Apple / macOS
-
-Apple Silicon (arm64) recommended. Intel Macs run, but get no Neural-Engine benefit — budget 16 GB there.
-
-| Use case | Minimum that runs well | Comfortable / recommended |
-|---|---|---|
-| **Cloud voice on a laptop** (Profile B) | MacBook Air **M1 / M2, 8 GB** | MacBook Air **M3 / M4, 16 GB** |
-| **Always-on assistant host, 24/7** (Profile B/C) | Mac mini **M4, 16 GB** (≈ $599–799) | Mac mini **M4, 24–32 GB** |
-| **Local Whisper + Vision** (Profile C) | M-series, **16 GB** unified (covers `whisper-medium`) | M-series, **32 GB** (covers `large-v3` + Vision) |
-
-The **Mac mini M4 (16 GB unified, ≈ $799)** is the sweet spot for a dedicated always-on assistant: silent, ~7 W idle, and unified memory means CPU-side Whisper runs fine without a discrete GPU. On macOS, pywebview uses the native WKWebView, so the UI is *lighter* than the Chromium/WebView2 figures measured above.
-
-### Recommendation — self-built (Linux / Windows)
-
-| Use case | Minimum that runs well | Comfortable / recommended |
-|---|---|---|
-| **VPS / headless** (Profile A) | any **2 vCPU / 2 GB** Linux box | Hetzner **CX22 — 2 vCPU / 4 GB / 40 GB NVMe, ≈ €3.79–4.15 / mo** |
-| **Desktop, cloud voice** (Profile B) | any x86-64, **4-core / 8 GB**, SSD, no GPU | **16 GB**, modern 6-core |
-| **Desktop, full local** (Profile C) | **16 GB** + NVIDIA **RTX 3060 12 GB / 4060** (CUDA 12.x) | **32 GB** + RTX 4070+ / 5070 |
-
-A **Hetzner CX22 at ≈ €4 / month** is the canonical €5-VPS this whole project is designed around — 2 vCPU, 4 GB, 40 GB NVMe, 20 TB traffic — and runs the headless base install + browser UI comfortably. The maintainer's reference desktop (RTX 5070 Ti / 32 GB / CUDA 12.8) is Profile C maxed out, and is explicitly **not** a requirement.
-
-### What runs where (platform capability matrix)
-
-The base + cloud-voice experience is fully cross-platform. The six desktop power-user features that were historically Windows-only are now **cross-platform behind a `jarvis/platform/` seam** (`detect_platform()` + `Capabilities` factories) — each carries an honest per-feature verification badge (see [Verification status](#verification-status) below).
-
-**Badge legend:** ✅ CI-configured = the `ci.yml` matrix is configured to prove this on the ubuntu/macos runners (first green run pending the initial push). 🟡 unverified-on-real-desktop = a live GUI/permission behavior that needs a real macOS/Linux device — not yet signed off (this repo's maintainer has Windows only). ⚙ degrade-by-design = the documented graceful fallback on that OS.
-
-| Capability | Linux | macOS | Windows |
-|---|---|---|---|
-| Headless base + browser UI | ✅ | ✅ | ✅ |
-| Voice (wake → VAD → STT → TTS) | ✅ | ✅ | ✅ |
-| Desktop window (pywebview) + tray | ✅ GTK/Qt | ✅ WKWebView | ✅ WebView2 |
-| Local Whisper STT + screen vision | ✅ | ✅ | ✅ |
-| Computer-Use — screenshot → click → type (vision, pixel coordinates) | ✅ X11 | ✅ | ✅ Win32 |
-| Built-in terminal view (PTY) | ✅ CI-configured (`ptyprocess`) | ✅ CI-configured (`ptyprocess`) | ✅ ConPTY |
-| Launch apps by name | ✅ CI-configured (`xdg-open`/exec) | ✅ CI-configured (`open -a`) | ✅ App Paths |
-| Computer-Use — click by UI-element name | 🟡 unverified-on-real-desktop (AT-SPI; ⚙ pixel fallback) | 🟡 unverified-on-real-desktop (AX; ⚙ pixel fallback) | ✅ UIA |
-| Global-hotkey wake | 🟡 unverified-on-real-desktop (X11 `pynput`; ⚙ Wayland no-op + wake-word) | 🟡 unverified-on-real-desktop (`pynput`) | ✅ |
-| Orb overlay | 🟡 unverified-on-real-desktop (best-effort; ⚙ tray fallback) | 🟡 unverified-on-real-desktop (Tk `-transparentcolor`) | ✅ |
-| Admin-helper / elevation | 🟡 unverified-on-real-desktop (pkexec/sudo; ⚙ NullElevator) | 🟡 unverified-on-real-desktop (Authorization Services) | ✅ UAC |
-
-> macOS / Linux get the full Router-Brain → Worker-Critic → Mission-Manager experience — including voice, local Whisper, and the **screenshot → click → type** Computer-Use loop: the vision model picks pixel targets, and `mss` (screen capture) + `pyautogui` (click / type / scroll) are cross-platform **base** dependencies, not Windows-only. The six former Windows-only desktop features — the built-in terminal, launch-app-by-name, click-by-UI-element-name (UIA / AX / AT-SPI accessibility trees), global-hotkey wake, the Orb overlay, and the admin-helper / elevation — are now **cross-platform behind the `jarvis/platform/` seam** (one per-OS implementation per feature, selected by a `detect_platform()` factory, each degrading to a logged English no-op when its capability is absent). They remain **opt-in `[desktop]` / `[desktop-macos]` extras** (the headless €5-VPS base install ships none of them). Terminal and launch-by-name are fully CI-provable on the ubuntu/macos runners; UI-element-click, global-hotkey capture, the Orb transparency, and the elevation prompt are live GUI/permission behaviors that need a one-time sign-off on a real device (AD-3) — see the per-feature verdicts in [Verification status](#verification-status). See the `[desktop]` extras in [`pyproject.toml`](pyproject.toml), the cloud-first doctrine in [`docs/PHILOSOPHY.md`](docs/PHILOSOPHY.md), and ADR-0020 (cross-platform elevation, supersedes ADR-0001).
-
-#### Verification status
-
-These cross-platform claims are labelled honestly per feature. The full, dated,
-device-attributed verdict log lives in
-[`docs/plans/cross-platform-mac-linux/SIGNOFF-LOG.md`](docs/plans/cross-platform-mac-linux/SIGNOFF-LOG.md),
-with the operator checklist in
-[`LIVE-SIGNOFF-CHECKLIST.md`](docs/plans/cross-platform-mac-linux/LIVE-SIGNOFF-CHECKLIST.md)
-and the 20-scenario benchmark results in
-[`JARVIS-20-RESULTS.md`](docs/plans/cross-platform-mac-linux/JARVIS-20-RESULTS.md).
-As of this writing the maintainer has only a Windows machine and nothing has been
-pushed, so every macOS/Linux **live** GUI/permission row is honestly labelled
-`unverified-on-real-desktop` and the CI matrix is `CI-configured` (its first green
-run is pending the initial push) — *not* "CI-verified" and *not* "live-verified".
-Run [`scripts/crossplatform/signoff_probe.py`](scripts/crossplatform/signoff_probe.py)
-on a real macOS box and a real Linux desktop to convert each row to a dated
-`live-verified` verdict.
-
-**One-line buying advice.** *Just want to try it?* Any laptop you already own (8 GB+) or a €4 Hetzner CX22. *Want a dedicated always-on assistant?* Mac mini M4 (16 GB). *Want everything local, no cloud STT?* 16–32 GB plus an NVIDIA RTX 3060 / 4060 (or better), or an Apple Silicon Mac with 16–32 GB.
-
----
-
-## Table of contents
-
-> ★ **[Hardware — what you actually need](#hardware--what-you-actually-need)** — measured RAM footprint + concrete Mac / Linux / Windows specs. Read this first if you're picking a machine.
-
-1. [Quick install & first-run](#1-quick-install--first-run)
-2. [Runtime modes](#2-runtime-modes)
-3. [8-Layer architecture](#3-8-layer-architecture)
-4. [Plugin system](#4-plugin-system)
-5. [EventBus + streaming contract](#5-eventbus--streaming-contract)
-6. [Brain providers + Ack-Brain](#6-brain-providers--ack-brain)
-7. [Risk-Tier + Router discipline](#7-risk-tier--router-discipline)
-8. [Output filter (voice path)](#8-output-filter-voice-path)
-9. [Configuration & secrets](#9-configuration--secrets)
-10. [Atomic config writes & Self-Mod pipeline](#10-atomic-config-writes--self-mod-pipeline)
-11. [Phase-6 isolation invariants](#11-phase-6-isolation-invariants)
-12. [Phase status table](#12-phase-status-table)
-13. [5-layer anti-drift enum pattern](#13-5-layer-anti-drift-enum-pattern)
-14. [Anti-patterns (AP-1..AP-18)](#14-anti-patterns-ap-1ap-18)
-15. [Recurring bug classes](#15-recurring-bug-classes)
-16. [Desktop App (UI)](#16-desktop-app-ui)
-17. [Testing — buckets, markers, conventions](#17-testing--buckets-markers-conventions)
-18. [Linting & type checking](#18-linting--type-checking)
-19. [Scripts inventory](#19-scripts-inventory)
-20. [External integrations & accounts](#20-external-integrations--accounts)
-21. [ADR + Phase doc index](#21-adr--phase-doc-index)
-22. [Operational rhythms](#22-operational-rhythms)
-23. [Repo hygiene & contribution](#23-repo-hygiene--contribution)
-24. [Key module index](#24-key-module-index)
-25. [Doc-vs-code drift (verified)](#25-doc-vs-code-drift-verified)
-26. [Pointers](#26-pointers)
-27. [Legal](#27-legal)
-
----
-
-## 1. Quick install & first-run
-
-> **Signed one-liner installer — coming in a follow-up release.** A
-> `curl … | bash` / `irm … | iex` one-liner with Sigstore/SLSA signature
-> verification is being finished; until its signing pipeline is wired to this
-> repository it is intentionally not advertised here. Install manually with the
-> steps below — it works on Linux, macOS, and Windows.
-
-**Manual install (works everywhere):**
+<p align="center">
+ <a href="https://github.com/PersonalJarvis/PersonalJarvis">
+ <img src="assets/brand/banner.png" alt="Personal Jarvis — voice-driven meta-orchestrator" width="860" />
+ </a>
+</p>
+
+<p align="center">
+ <a href="LICENSE"><img alt="License: MIT" src="https://img.shields.io/badge/License-MIT-FFD60A?style=flat-square&labelColor=0A0A0A" /></a>
+ <a href="https://discord.gg/UPu6pFWrJ"><img alt="Discord" src="https://img.shields.io/badge/Discord-join-FFD60A?style=flat-square&logo=discord&logoColor=0A0A0A&labelColor=0A0A0A" /></a>
+ <a href="https://x.com/PersonalJarvis"><img alt="X" src="https://img.shields.io/badge/X-@PersonalJarvis-FFD60A?style=flat-square&logo=x&logoColor=0A0A0A&labelColor=0A0A0A" /></a>
+ <img alt="Python 3.11+" src="https://img.shields.io/badge/Python-3.11+-FFD60A?style=flat-square&logo=python&logoColor=0A0A0A&labelColor=0A0A0A" />
+ <img alt="Platforms" src="https://img.shields.io/badge/Linux%20·%20macOS%20·%20Windows-242424?style=flat-square&labelColor=0A0A0A" />
+</p>
+
+<p align="center">
+ <b>A voice-driven meta-orchestrator that turns one spoken request into a fleet of self-checking AI agents.</b>
+</p>
+
+---
+
+Personal Jarvis is not a classical voice assistant. At its core is a fast **Router-Brain**
+that listens, decides, and *delegates* — dispatching heavy work to interchangeable agent
+harnesses (Claude Code, Codex CLI, MCP servers, raw computer-use loops) that run in
+isolation, review each other's output through a critic loop, and report back in your own
+language. It is **provider-agnostic by design** (swap Gemini, Claude, GPT, Grok, or
+OpenRouter with one setting), **self-modifying** (it can safely edit its own configuration
+through an audited, reversible pipeline), and runs everywhere — from a headless server with
+a browser UI to a full desktop with a tray app, an Orb overlay, and global-hotkey wake.
+
+## Why it's different
+
+- **The conversation never blocks.** A sub-second *Ack-Brain* acknowledges you while the
+ deep brain is still thinking, so a spoken exchange stays one smooth, uninterrupted flow.
+- **A meta-orchestrator, not a monolith.** A lean Router-Brain *dispatches* to specialized
+ harnesses instead of trying to do everything in one prompt — the discipline that keeps it
+ fast and lets it scale to heavy, multi-step work.
+- **Self-healing Worker-Critic.** Background missions run in isolated `git worktree`
+ branches; a critic loop reviews their work before you ever hear an answer, and a signed
+ controller decides what gets spoken.
+- **Provider-agnostic.** Gemini, Claude, OpenAI, Grok, OpenRouter — switch the brain by
+ voice or config, with a smart, rate-limit-aware fallback chain. No single vendor lock-in.
+- **Self-modifying, safely.** It can rewrite its own settings through a 10-step
+ validate → backup → atomic-swap → reload → rollback → audit pipeline. Nothing is changed
+ that can't be undone.
+- **Memory that lasts.** A Knowledge Wiki long-term memory, an awareness layer, and a
+ personal "knows-you" board build a deepening model of you across sessions.
+- **Runs anywhere.** Linux, macOS, and Windows; a headless server speaking through the
+ browser's mic and speakers, or a full voice-and-overlay desktop. Local-hardware features
+ are opt-in extras that degrade gracefully when they're absent.
+
+## Quick start
```bash
-git clone https://github.com/PersonalJarvis/PersonalJarvis ~/.personal-jarvis
-cd ~/.personal-jarvis
+git clone https://github.com/PersonalJarvis/PersonalJarvis ~/personal-jarvis
+cd ~/personal-jarvis
+
python -m venv .venv
source .venv/bin/activate # Windows: .\.venv\Scripts\Activate.ps1
-pip install -e . --no-deps # activates entry_points (BUG-006/014 recovery)
-pip install -r requirements.txt # full runtime deps
-pip install -e ".[dev]" # optional: pytest, ruff, mypy, pyinstaller
-
-python -m jarvis --wizard # 7-step Setup-Wizard
-```
-
-Wizard (`jarvis/setup/wizard.py`) is idempotent: hardware analysis → API keys (written to Windows Credential Manager) → mic check → hotkey → external CLI deps (auto-installs `claude` CLI via npm; `node`/`npm` manual) → mascot install → profile.
-
-**Console scripts** (from `[project.scripts]`):
-
-| Script | Purpose |
-|---|---|
-| `jarvis` | Tray app or first-run wizard |
-| `jarvis-ask` | One-shot prompt CLI |
-| `jarvis-review-gc` | Phase 8.5 review-pipeline GC |
-| `jarvis-review-eval` | Phase 8.6 eval harness (`--quick`/`--real`/`--bucket`) |
-
-**Top-level `python -m jarvis` flags** (argparse in `jarvis/__main__.py`): `--version`, `--wizard`, `--check`, `--plugins`, `--debug`, `--phase5-doctor`, `--install-admin-helper`.
-
-### Headless / VPS first-run (no interactive TTY)
-This is the **primary path** for €5 VPS users, Docker containers, and CI environments. The interactive wizard (`setup/wizard.py`) detects when no TTY is attached and skips all prompts automatically. You only need to supply your API keys before launching.
-
-**Step 1 — Provide your API key(s).** Choose one:
-
-```bash
-# Option A: environment variables (recommended for containers and systemd units)
-export GEMINI_API_KEY=your-key-here # or whichever brain provider you use
-export GROQ_API_KEY=your-groq-key # for fast STT (optional)
+pip install -e . --no-deps # activates the plugin entry-points
+pip install -r requirements.txt # runtime dependencies
-# Option B: .env file at the repo root (dev / docker-compose convenience)
-cp .env.example .env
-# edit .env and fill in your keys — full list of names in .env.example
+python -m jarvis --wizard # interactive first-run setup
```
-The full set of recognised ENV variable names is in `.env.example`. Each name
-mirrors the `env_fallback` field in the `SECRETS` list in `jarvis/setup/wizard.py`
-(e.g. `GEMINI_API_KEY`, `ANTHROPIC_API_KEY`, `OPENAI_API_KEY`, `GROQ_API_KEY`,
-`GROK_API_KEY`, `DEEPGRAM_API_KEY`, `CARTESIA_API_KEY`, `ELEVENLABS_API_KEY`, …).
+The wizard walks you through hardware detection, API keys (stored in your OS credential
+manager — never in the repo), microphone, and a wake word.
-**Step 2 — Launch in headless mode:**
+**Run it:**
```bash
-# Preferred: API + WebSocket only, no GUI deps, no audio required.
-python -m jarvis.ui.web.launcher --headless
-```
+# Full desktop: window + voice + Orb overlay
+python -m jarvis.ui.web.launcher
-On first run the wizard fires, detects the missing TTY, skips prompts, writes the
-`data/.setup-complete` marker, and hands off to the app — all automatically.
-You can also force non-interactive mode explicitly:
-
-```bash
-JARVIS_NONINTERACTIVE=1 python -m jarvis.ui.web.launcher --headless
+# Headless server: API + WebSocket + browser UI, no local audio needed
+python -m jarvis.ui.web.launcher --headless
```
-**Step 3 — Open the browser UI.** Navigate to `http://<your-vps-ip>:47821`.
-The full Router-Brain → Worker-Critic → Mission-Manager experience is available
-in the browser, including voice via the browser's microphone (WebRTC).
-
-> **What is NOT needed on a VPS:** no GPU, no audio hardware, no Windows APIs,
-> no microphone, no desktop display. The `[desktop]` extras (tray app, Orb
-> overlay, global-hotkey wake, local Whisper, Computer-Use harness) are
-> optional — a clean `python:3.11-slim` Linux container boots without them.
+Then open **http://localhost:47821** — the full Router-Brain → Worker-Critic →
+Mission-Manager experience lives in the browser, including voice through the browser's
+microphone. For a headless deployment, set your provider key (e.g. `GEMINI_API_KEY`) in the
+environment or a `.env` file; the wizard detects the missing terminal and skips its prompts.
-**Code gap (deliberate, left for orchestrator decision):** the wizard's
-`step_mic_check()`, `step_hotkey_check()`, `step_wake_word_setup()`,
-`step_dependency_check()`, and `step_finalize()` (autostart prompt) are all
-skipped in non-interactive mode together with `step_api_keys()`. A future
-hardening pass could run the TTY-free steps (hardware check, dep check) even
-in non-interactive mode and only gate on the `input()` calls. This is safe
-as-is: all skipped steps are idempotent and can be re-run via
-`python -m jarvis --wizard` from an interactive shell.
+<p align="center">
+ <img src="assets/screenshots/app-home.png" alt="The Personal Jarvis desktop app" width="820" />
+</p>
----
+## Architecture at a glance
-## 2. Runtime modes
-
-`run.bat` is the preferred launcher — it auto-invokes `scripts/check-working-tree.ps1` as pre-boot drift restore.
-
-| Command | Effect |
-|---|---|
-| `run.bat` | `pythonw` + FastAPI + pywebview window + voice + Orb (default; hidden console) |
-| `run.bat --debug` | Console visible, `JARVIS_DEBUG=1`, verbose logging |
-| `run.bat --dev` | Frontend from Vite dev server `:5173`, hot reload (`JARVIS_DEV=1`) |
-| `run.bat --headless` | API + WebSocket only, no window, Mock-Brain wiring for E2E |
-
-Direct launcher: `python -m jarvis.ui.web.launcher [--headless|--dev|--port N|--no-lock]`. `--no-lock` disables the `filelock` single-instance guard for parallel dev sessions. Voice opt-out: `set JARVIS_VOICE=0`.
-
----
-
-## 3. 8-Layer architecture
+Higher layers reach lower layers **only through protocols**; everything else talks over a
+typed, immutable **EventBus**. That strict seam is what lets harnesses, providers, and
+plugins be swapped without rippling through the codebase.
```
-L7 UI/UX Tray, Toasts, Admin-API, Desktop-App (FastAPI+React+pywebview), Orb-Overlay
-L6 Orchestrator State-Machine, Router, BrainManager, Supervisor, Mission-Manager, Kontrollierer
-L5 Harness-Adapter OpenClaw, Codex, Open Interpreter, Python-Script, MCP-Remote
-L4 Brain 5 providers (Claude-API, OpenRouter, OpenAI, Gemini, Grok) + Ack-Brain sub-second tier
-L3 Intent/Risk Classifier, Risk-Tier-Policy, Approval, Rate-Limit-Tracker
-L2 Speech Wake → VAD (Silero) → STT (faster-whisper / Google / Deepgram) → TTS (Gemini Flash / Grok-Voice / SAPI5)
-L1 Audio I/O WASAPI via sounddevice, Device-Routing, Chime-Feedback
-L0 OS/Hardware Win32, CUDA, Mic/Speakers, global-hotkeys
+L7 UI/UX Desktop app (FastAPI + React + pywebview), tray, Orb overlay
+L6 Orchestrator State machine, Router, BrainManager, Mission-Manager, Controller
+L5 Harness adapter Claude Code, Codex, Open Interpreter, MCP, raw computer-use
+L4 Brain Gemini · Claude · OpenAI · Grok · OpenRouter + sub-second Ack-Brain
+L3 Intent / Risk Classifier, four-tier risk policy, approval, rate-limit tracking
+L2 Speech Wake → VAD → STT → TTS (cloud or local, your choice)
+L1 Audio I/O Device routing, chime feedback
+L0 OS / Hardware Mic, speakers, global hotkeys, optional GPU
```
-**Dependency rule (strict):** higher layers reach lower layers **only via Protocols** (`jarvis/core/protocols.py:161-541` — all `runtime_checkable`, structural typing). Lateral communication is **only** via typed events on `EventBus` (`jarvis/core/bus.py`) with `frozen=True` dataclasses carrying `trace_id: UUID` + `timestamp_ns: int`. Subscriber exceptions are swallowed in `_safe_dispatch` (`bus.py:65-76`) and logged — never propagated (AP-18).
-
----
-
-## 4. Plugin system
-
-Seven groups frozen as `PLUGIN_GROUPS` in `jarvis/core/protocols.py:363-371`: `jarvis.wakeword`, `jarvis.stt`, `jarvis.tts`, `jarvis.brain`, `jarvis.harness`, `jarvis.tool`, `jarvis.channel` (plus `jarvis.turn` for end-of-turn detection, declared in `pyproject.toml:104`).
-
-Plugins live under `jarvis/plugins/<group>/<name>.py`, register via `pyproject.toml` `[project.entry-points."jarvis.<group>"]`, and **must not import from `jarvis.*`** — only structural Protocol compatibility (registry at `jarvis/core/registry.py`). After editing entry-points: **`pip install -e . --no-deps`** is mandatory to activate them (this is the fourth layer of BUG-006/014).
-
----
-
-## 5. EventBus + streaming contract
-
-- Events are `frozen=True` slotted dataclasses inheriting from `Event` (`jarvis/core/events.py:29`), with auto-generated `trace_id` + `timestamp_ns`. 100+ subclasses.
-- Immutability enables flight-recorder replay; `bus.subscribe_all(handler)` makes the recorder a wildcard subscriber.
-- **All Brain/STT/TTS/Harness provider methods return `AsyncIterator[...]`** — non-streaming providers yield exactly one element. Consumers always write `async for chunk in provider.xxx()`.
-- `EventBus.publish` (`bus.py:44-62`) parallel-dispatches via `asyncio.gather(..., return_exceptions=True)` and routes each handler through `_safe_dispatch`. **A broken subscriber must never kill the pipeline (AP-18).**
-
----
+A deeper, exhaustive engineering map — anti-pattern register, recurring bug classes,
+phase-by-phase status with `file:line` references — lives in the LLM context drop below.
-## 6. Brain providers + Ack-Brain
+## A guided tour
-Six brain plugins (`pyproject.toml:130-137`): `claude-api`, `openrouter`, `openai`, `gemini`, `grok`, `codex`. Multi-provider is mandatory — **never hardcode** Anthropic/Claude. `cfg.brain.primary` is the master selector; `BrainManager` (`jarvis/brain/manager.py`) owns a smart fallback chain (rate-limit aware, frontier aware) and a `(provider_name, model) → Brain` cache. Voice aliases in `manager.py:100-113` accept `claude/opus/haiku/sonnet/gpt/chatgpt/flash/pro/grok`.
+- **Missions & the Worker-Critic loop** — ask for something non-trivial and Jarvis spawns a
+ background *mission*: an isolated worker does the work, a critic reviews it (up to three
+ correction rounds), and a signed controller approves what's spoken. Every deliverable
+ shows up in **Outputs** as a downloadable artifact.
+- **Knowledge Wiki** — a long-term memory vault (Obsidian-compatible) Jarvis can search,
+ read, and write back to, so it remembers people, projects, and facts across sessions.
+- **Channels & telephony** — talk to Jarvis from the desktop, the browser, Telegram, or
+ Discord; optional Twilio integration places real outbound calls.
+- **Self-mod & skills** — Jarvis can adjust its own configuration safely and author new
+ skills as reviewable drafts (never auto-activated).
-**Ack-Brain** (`jarvis/brain/ack_brain/generator.py`) emits a sub-second butler-style preamble before the deep brain replies. Provider plugins: Gemini, Grok, OpenAI, Ollama. Suppress-if-fast gate at `[ack_brain].suppress_if_brain_faster_than_ms = 2000` (ADR-0014 Flash-Brain). `AckGenerator.run()` is failure-safe across F1–F10 modes and never raises.
+<p align="center">
+ <img src="assets/screenshots/view-outputs.png" alt="Outputs — mission deliverables" width="410" />
+ <img src="assets/screenshots/view-wiki.png" alt="Knowledge Wiki" width="410" />
+</p>
-User context: **No Anthropic API account** (AP-6). Workers use Claude Sonnet via **Claude Max OAuth** through the `claude-cli` backend (`@anthropic-ai/claude-code`, npm-installed by the wizard). Personal Jarvis Brain stays on Gemini by default.
-
----
-
-## 7. Risk-Tier + Router discipline
-
-Four levels: `RiskTier = Literal["safe", "monitor", "ask", "block"]` (`protocols.py:108`). `RiskTierEvaluator.evaluate()` (`jarvis/safety/risk_tier.py:64-100`) applies **blacklist > whitelist > tool default** — blacklist match raises `ActionBlocked`; whitelist match downgrades to `safe` with `approved_by="whitelist"` (the anti-confirmation-fatigue contract). Glob matching via `fnmatch` on `"<tool_name> <serialized_args>"`. **`ToolExecutor.execute()` is the only authorized call path; AP-3 forbids direct `Tool.execute()`.**
-
-**Router discipline (ADR-0011 amended):** the Router-Brain is a **pure dispatcher**. Tool surface is the `ROUTER_TOOLS` frozenset at `jarvis/brain/factory.py:40-77` — 13 tools: `run-shell`, `screen-snapshot`, `dispatch-to-harness`, `multi-spawn`, `spawn-openclaw`, `dispatch-with-review`, `awareness-snapshot`, `awareness-recall`, `run-skill`, `wiki-recall`, `wiki-page-read`, `wiki-ingest`, plus the Self-Mod trio (`list_mutable_settings`, `get_config_value`, `set_config_value`).
-
-Force-spawn heuristic in `BrainManager._should_force_openclaw`:
-- Smalltalk allowlist wins → never spawn.
-- Action verb (`lies/baue/installiere/öffne/mach/zeig` + repair words) → spawn.
-- External-system marker (PR/Repo/GitHub/Issue) → spawn.
-
-**The sub-jarvis tier was deleted in Welle 4** — only `"router"` remains (`factory.py:119-123` raises on unknown tiers). Resurrecting `SUB_TOOLS` or adding `spawn-openclaw`/`dispatch-with-review`/`run-skill` to any worker set breaks the D9 recursion guard (AP-14).
-
----
-
-## 8. Output filter (voice path)
-
-`scrub_for_voice` in `jarvis/brain/output_filter.py` is **regex-only, no LLM calls** (latency mandate, AP-11). Order: stacktrace → fallback phrase early-return → markdown strip → tool-JSON removal (3 forms) → self-reference → echo paraphrase (only `OPENER_BUDGET = 60` chars) → filler-opener → engineering jargon (with hyphen-compound whitelist — `Browser-Provider` stays) → whitespace normalize.
-
-**Sacred whitelist** (`output_filter.py:39-42`): `Datei, Email, Browser, Terminal, Notiz, Termin, Kalender`. Jargon list: `Harness, MCP, Subprocess, Provider`; compound jargon: `Sub-Agent, Supervisor-Agent, Subagent`.
-
-Wired into TTS at two sites:
-- `pipeline.py:1330` — `_handle_utterance` → `_speak()` → `tts.synthesize`
-- `pipeline.py:647` — `_on_announcement` (skill/sub-agent announcements, OpenClaw `summary_de` readback)
-
-40-case test suite at `tests/unit/brain/test_output_filter.py`. ADR-0010 (Output-Filter Pattern-Based).
-
----
-
-## 9. Configuration & secrets
-
-**Secret access** — `jarvis.core.config.get_secret(key, env_fallback)` is the only authorized path. Hierarchy:
-
-1. Windows Credential Manager (service `personal-jarvis`) ← wizard writes here
-2. ENV variable
-3. `.env` (dev fallback)
-4. **NEVER** `jarvis.toml`, code, commits, or `.claude/` files (AP-12)
-
-Voice/chat must never accept secrets (AP-2: STT log leak vector).
-
-**Config drift triple-defense (BUG-010 — parallel Claude sessions silently rolling back provider switches):**
-
-- **ENV overrides** at user scope (e.g. `JARVIS__TTS__PROVIDER=grok-voice`)
-- `jarvis.toml` set OS read-only after edits
-- `scripts/drift-guard-daemon.ps1` — Userland daemon, 5-min cron via `shell:startup` shortcut (UAC-free; Task Scheduler + ScheduledJob both elevated-only). Checks `jarvis.toml` + ENV against `scripts/config-soll.json`, fixes drift, re-locks TOML. Lock file: `logs/drift-guard-daemon.lock`. BOM-safe writes via `UTF8Encoding($false)` (BUG-018 fix).
-
----
+## Documentation
-## 10. Atomic config writes & Self-Mod pipeline
-
-`jarvis/core/config_writer.py` uses `tomlkit` (preserves comments), `_WRITE_LOCK = threading.Lock()`, BOM-aware read/write, tempfile + `os.replace`.
-
-**Phase-7 Self-Mod 10-step pipeline** in `jarvis/core/self_mod/writer.py` is non-negotiable:
-
-1. Allowlist via `SelfModRegistry.require_spec`
-2. `tomlkit` load
-3. Read old value via dotted path
-4. In-memory mutate
-5. **Pre-validate** via `JarvisConfig.model_validate(doc.unwrap())`
-6. Backup to `<config>.parent/.backups/jarvis.toml.<iso>.bak` (**outside watchdog scope, AP-13**)
-7. Tempfile + `os.replace` atomic swap
-8. **Synchronous reload-test** via `ConfigLoader.load()` (AP-14 forbids watchdog-driven verify)
-9. `ConfigReloaded` bus event
-10. Backup GC (FIFO cap + age floor) → audit via `SelfModAudit`
-
-Locking is `ClassVar threading.Lock`. Three router-tier Self-Mod tools: `list_mutable_settings`, `get_config_value`, `set_config_value` (`jarvis/brain/tools/self_mod_tools.py`).
-
----
-
-## 11. Phase-6 isolation invariants
-
-- Every worker runs in a fresh `git worktree add -b agent/<task-slug>` under `<repo_parent>/sub-agents-outputs/` via `WorktreeManager` (`jarvis/missions/isolation/worktree.py`). ≤200-char path cap. No writes to user's working tree.
-- Every worker subprocess is contained for kill-on-crash: Windows via a **Job Object** with `JOB_OBJECT_LIMIT_KILL_ON_JOB_CLOSE` (a kernel guarantee — no zombies even on a hard orchestrator kill); macOS/Linux via a POSIX process-group reaper (`start_new_session` + `os.killpg`-on-close, `jarvis/missions/isolation/job_object.py`) that reaps the whole worker tree on a clean shutdown / cancel / timeout / exception. Being userspace, the POSIX path cannot match the kernel guarantee on a hard `kill -9` of the orchestrator itself (the group reparents to init/launchd and survives) — `PR_SET_PDEATHSIG` is the Linux follow-up; macOS has no equivalent.
-- `MAX_CRITIC_LOOPS: Final[int] = 3` is **hardcoded** at `jarvis/missions/critic/runner.py:50-51` ("Hardcoded per ADR-0009. Not configurable without a new decision record."). Used by `Orchestrator.run_mission` at `jarvis/missions/kontrollierer/orchestrator.py:388`.
-- **Action/Observation invariant (ADR-0009):** the LLM never authors its own Observation. Voice readback reads only the Kontrollierer-signed `MissionApproved.summary_de`, never `correction_instruction` from the Critic-LLM.
-- **Persist-vor-Publish discipline** (`manager.py:8-11`): `upsert_mission(PENDING)` happens before `append_and_publish(MissionDispatched)` — the event log is authoritative.
-
----
-
-## 12. Phase status table
-
-Verified against the actual file tree (not just CLAUDE.md claims):
-
-| Phase | Status | Evidence |
-|---|---|---|
-| 0–4 Foundations | live | Protocols, plugin system, FastAPI/React, speech pipeline, skill system, tool-use loop, harness dispatch, core memory |
-| 5 Vision/Action/Admin/Async/Control + Tiered Routing | live | `jarvis/{vision,admin,tasks,control,telemetry}/`, `ROUTER_TOOLS` frozenset, ADR-0001..0011 |
-| 6 Self-Healing Worker-Critic | live | `jarvis/missions/{manager,kontrollierer,critic,workers,isolation,openclaw,voice,safety}/`. 458 mission tests. Wired via `bootstrap_missions` |
-| 7 Self-Mod (foundation + writer + tools) | live | `jarvis/core/self_mod/` (audit, errors, pending, registry, schema, writer). `spawn-skill-author` **IS** registered at `pyproject.toml:208` (CLAUDE.md says otherwise — see §25) |
-| Awareness A0–A5 | live | `jarvis/awareness/` (state, story, salience, verdichter, working_set, episode, watchers, probes). A1 + A3 router tools registered |
-| Wiki B0/B1/B2/B3/B5/B7/B8/B9 | live | `jarvis/memory/wiki/` (curator, atomic_writer, page, integration, scheduler, session_rollup, voice_bridge, telemetry, vault_index, watcher, search). 3 router tools |
-| Wiki B4 (legacy Curator) | soft-disabled | `factory.py:736-757` gates on `cfg.memory.legacy_curator.enabled` (default `false` since 2026-05-17). `data/workspace/` snapshot stays on disk for 35 reader sites |
-| Wiki B6 | not started | — |
-| OpenClaw bridge Welle 1+4 | done | `jarvis/plugins/harness/openclaw.py` (Mock-Mode), `jarvis/missions/openclaw/` (provider_map, workspace, mcp, setup) |
-| OpenClaw bridge Welle 2 (live default) | open | Mock-Mode in plugin file; live subprocess factory pending |
-| OpenClaw bridge Welle 3 (full live mode) | open | — |
-| Ack-Brain (pre-thinking) | live | `jarvis/brain/ack_brain/` + factory hook (`factory.py:1034`) |
-| CLI catalog + terminal view | live | `jarvis/clis/` (catalog, installer, loader, prober, registry, risk_integration, usage_log) + `jarvis/terminal/` (ConPTY via `pywinpty`). Tools `cli-tools` + `spawn-cli-worker` |
-
-Status drift moves fast. Verify with `git log -- <module>` rather than trusting this table.
-
----
-
-## 13. 5-layer anti-drift enum pattern
-
-Documented in [`docs/anti-drift-three-layer.md`](docs/anti-drift-three-layer.md). Any string crossing module boundaries lives in **five places**: producer Python module → SQLite schema → Pydantic `Literal` → TypeScript union → UI label switch.
-
-**Canonical example `HangupReason`:**
-
-| Layer | File | Role |
-|---|---|---|
-| L0 source of truth | `jarvis/sessions/constants.py` | `HANGUP_REASONS` tuple + symbolic constants (`HANGUP_TURN_COMPLETE`, …) |
-| L1 producers | `jarvis/speech/pipeline.py`, `jarvis/sessions/init.py` | Import symbols — never raw strings |
-| L2 schema | `jarvis/sessions/schema.sql` | Doc-comment listing allowed values |
-| L3 Pydantic | `jarvis/sessions/models.py` | `HangupReason = Literal[...]` + **import-time `RuntimeError`** asserting `get_args(HangupReason) == HANGUP_REASONS` |
-| L4 TS | `jarvis/ui/web/frontend/src/components/sessions/types.ts` | Union type |
-| L5 UI | `jarvis/ui/web/frontend/src/components/sessions/SessionList.tsx` | `hangupLabel(reason)` switch |
-
-**Five defenses (D1–D5):** symbolic constants → import-time assertion → parity test (`tests/unit/sessions/test_hangup_reason_parity.py` regex-extracts all 5 layers and asserts equality) → DB compatibility test (`tests/integration/test_sessions_db_compatibility.py`) → self-defending list endpoint (`SessionStore.list_sessions` wraps per-row Pydantic in `try/except ValidationError`, returns partial list with `hangup_reason_drift_skipped` warning).
-
-**BUG-008 recurred four times** because this scaffolding was missing. Adopt preemptively for any new wire-format enum (`MessageRole` already done 2026-05-16; future candidates: `VoiceTier`, mission status, `SkillLifecycleState`).
-
----
-
-## 14. Anti-patterns (AP-1..AP-18)
-
-The single most important table for an LLM joining cold:
-
-| # | If you do this... | ...you get this bug |
-|---|---|---|
-| AP-1 | Spawn `subprocess.Popen` without `NO_WINDOW_CREATIONFLAGS` | BUG-012 flicker storm under `pythonw.exe` |
-| AP-2 | Accept API keys via voice/chat | STT log leak — credential exfiltration vector |
-| AP-3 | Call `Tool.execute()` directly (bypassing `ToolExecutor`) | Risk-tier/whitelist/plausibility skipped |
-| AP-4 | Add a new `hangup_reason`/mission-status string in one site only | BUG-008 recurrence: HTTP 500, empty UI |
-| AP-5 | Put `spawn-openclaw`/`dispatch-with-review`/`run-skill` in a worker tool set | D9 recursion: worker spawns supervisor, infinite loop |
-| AP-6 | Hardcode `Claude`/`Anthropic` API client | User has no Anthropic API account; breaks `cfg.brain.primary` |
-| AP-7 | Write `jarvis.toml` without `_WRITE_LOCK` + tempfile + BOM handling | BUG-018: BOM-corrupted TOML, backend won't boot |
-| AP-8 | Skip `scripts/preflight.ps1` in a new worktree | BUG-006/014: edits go to a worktree the live Python doesn't import from |
-| AP-9 | Run new awareness/wiki code in the voice critical path | Latency regression — awareness is read-only, off the hot path |
-| AP-10 | Write a worker without `git worktree` + Job Object | Race conditions + zombie processes on crash |
-| AP-11 | Add an LLM call inside `scrub_for_voice` | TTS latency tank |
-| AP-12 | Encode API keys in `jarvis.toml` or commit `.env` | Credential leak; bypasses `keyring` audit trail |
-| AP-13 | Block on watchdog reload for atomic-write verification | Race: file half-applied, no sync rollback |
-| AP-14 | Re-add a Sub-Jarvis tier or `SUB_TOOLS` set | Welle 4 deleted it; resurrection breaks the OpenClaw-bridge contract |
-| AP-15 | Auto-activate generated skills (`state` ≠ `draft`) | Lateral-movement vector; skills run without review |
-| AP-16 | Add `[phase6.*]`/`[memory.wiki.*]` keys without `ConfigDict(extra="allow")` | Pre-validate rejects → boot fails after self-mod |
-| AP-17 | Run Jarvis as a Windows Service | SYSTEM has no mic/headset access |
-| AP-18 | Propagate a subscriber exception from `EventBus._safe_dispatch` | One handler kills the pipeline |
-
----
-
-## 15. Recurring bug classes
-
-Detail in [`docs/BUGS.md`](docs/BUGS.md) (26-entry register). Five classes recur — recognize the signal, apply the defense.
-
-**1. Four-layer restore trap** (BUG-006 → -014 → -015). Signal: fix "works in tests" but Jarvis behavior unchanged after restart. Four layers: stale worktree + outdated frontend `dist/` build + RAM-resident pywebview + **editable-install pin to a deleted clone**. Defense: `pwsh scripts/preflight.ps1` + `python -c "import jarvis; print(jarvis.__file__)"` + frontend rebuild + `taskkill /F /IM pythonw.exe`.
-
-**2. Multi-layer enum drift** (BUG-008, four episodes). Signal: empty UI list while DB has rows, HTTP 500, `literal_error` in Pydantic. Defense: the five-layer pattern from §13 — symbolic constants, import-time assertion, parity test, DB-compat test, self-defending endpoint.
-
-**3. Config drift** (BUG-010 triple-defense). Signal: provider switches silently rolled back, parallel Claude sessions rewriting `jarvis.toml`. Defense: `scripts/drift-guard-daemon.ps1` (5-min) + ENV overrides + OS-read-only TOML + BOM-safe writer.
-
-**4. Subprocess console flicker** (BUG-012). Signal: black/flickering windows under `pythonw.exe`, mascot restart storm. Cause: missing `NO_WINDOW_CREATIONFLAGS` (16 call sites fixed). Defense: every new subprocess call imports from `jarvis.core.process_utils`.
-
-**5. Audio host-API blocking-write trap** (BUG-014). Signal: TTS silent, PortAudio `PaErrorCode -9999`. Cause: auto-resolver picks WDM-KS which PortAudio's blocking write doesn't support. Defense: `_FORBIDDEN_OUTPUT_HOSTAPIS` filter + shortest-unique-token device matching (`"PRO X"`, not full Razer marketing name).
-
----
-
-## 16. Desktop App (UI)
-
-- **Backend:** FastAPI on `localhost:47821` (admin_api_port). Single-instance lock via `filelock`. 25 route modules under `jarvis/ui/web/*_routes.py`: `board`, `cli`, `docs`, `federation_proxy`, `friends`, `frontier`, `marketplace`, `mcp`, `missions`, `missions_pty`, `missions_ws`, `outputs`, `preview`, `profile`, `provider`, `review`, `self_mod`, `sessions`, `setup`, `skills`, `sub_agents`, `tasks`, `tools`, `wiki`, `workflows`. WebSocket events serialized via `EventBus` (`subscribe_all` wildcard for flight recorder).
-- **Frontend:** React 18 + Vite 5 + TypeScript 5 + Tailwind + Radix UI + `@xterm/xterm` (ConPTY terminal view) + `react-force-graph-2d` (wiki graph) + `@xyflow/react` (workflow canvas) + Zustand + TanStack Query. Build output → `jarvis/ui/web/dist/`.
-- **Shell:** `pywebview` loads `dist/index.html` (production) or `http://localhost:5173` (`--dev`).
-- **Orb overlay:** separate `pythonw` subprocess (`jarvis/overlay/`), bus-bridged so mascot-originated events (e.g. mute on double-click) republish to the EventBus.
-
----
-
-## 17. Testing — buckets, markers, conventions
-
-**335 test files.** Bucket counts:
-
-| Bucket | Files | Purpose |
-|---|---|---|
-| `unit/` | 175 | Per-module |
-| `integration/` | 49 | Phase-level E2E |
-| `missions/` | 36 | Phase 6 worker-critic-kontrollierer |
-| `overlay/` | 29 | Orb mascot |
-| `review/` | 17 | Phase 8.4 quality-gate pipeline |
-| `contract/` | 17 | Protocol parametrised tests (mandatory for new providers) |
-| `board/` | 7 | Personal-board sync |
-| `e2e/` | 2 | Self-mod + voice-review |
-| `eval/` | 1 | Golden-query suite |
-| `setup/` | 1 | Wizard / dependencies |
-
-**Markers** (`[tool.pytest.ini_options]`): `phase5`, `e2e`, `voice_latency`, `eval`, `slow`, `skip_ci`, `openclaw_live`. `asyncio_mode = "auto"`. **Fakes (not `unittest.mock`)** live in `tests/fakes/`; audio fixtures `tests/fixtures/audio/`; trace replays `tests/fixtures/traces/`. New STT/Brain/Tool/Channel providers MUST pass `tests/contract/`.
-
-Common runs:
-
-```bash
-pytest tests/ # full suite
-pytest -m "not slow" # fast CI subset
-pytest -m phase5 / -m e2e / -m voice_latency / -m eval / -m openclaw_live
-pytest tests/unit/brain/test_routing.py # 32 router-discipline cases
-pytest tests/unit/brain/test_output_filter.py # 41 voice-scrubber cases
-pytest tests/unit/sessions/test_hangup_reason_parity.py # BUG-008 drift guard
-```
-
----
-
-## 18. Linting & type checking
-
-```bash
-ruff check jarvis/ # rules E,F,I,UP,B,ASYNC,S,A; ignores S101/S603/S607
-ruff format jarvis/
-mypy jarvis/
-
-# Frontend (jarvis/ui/web/frontend/)
-npm install
-npm run dev # http://localhost:5173
-npm run build # tsc -b && vite build --outDir ../dist --emptyOutDir
-npm run test # vitest
-```
-
-Line length 100. Target `py311`. One per-file `E501` exception (`jarvis/awareness/prompts.py` — long few-shot strings).
-
----
-
-## 19. Scripts inventory (`scripts/`)
-
-**Cron daemons (production):**
-- `auto-push-eod.ps1` — nightly tag+push safety net. Skips worktrees with active OpenClaw session (`<30 min` modify time).
-- `install-auto-push-task.ps1 -Time "22:00"` — register Task Scheduler job.
-- `drift-guard-daemon.ps1` — 5-min config drift defense. Singleton-locked, hidden, started via `shell:startup` shortcut.
-- `install-config-drift-guard-task.ps1` — install variant.
-- `jarvis-config-drift-guard.ps1` — actual drift-check pass (called by daemon).
-- `check-working-tree.ps1` — pre-boot restore of any tracked file missing from working tree. Always exits 0; rotating log `data/working-tree-check.log` (10 runs).
-- `cleanup-stale-agent-branches.ps1` — prunes leftover `agent/*` branches after `git worktree remove`.
-
-**One-shot guards / install:**
-- `preflight.ps1` — 5-check worktree health (git worktree assertion, editable-install re-pin, `import jarvis` path, `__editable__*.pth` stale scan, summary). **Mandatory before any new worktree code.**
-- `install_shortcuts.py`, `stop_watchdog.ps1`, `uninstall-auto-push-task.ps1`.
-
-**Smoke / probe (manual):**
-- `smoke_brain_e2e.py`, `smoke_frontier.py`, `smoke_phase6_p{1,2,2_jobkill,3,3_real}.py`, `smoke-test-ack.ps1`.
-- `voice_e2e_probe.py`, `voice_compare.py`, `tts_brain_endtoend.py`, `tts_output_sanity.py`, `warm_keep_bench.py`.
-- `awareness_smoke_a{1,2}.py`, `vision_smoke.py`.
-- `diag_audio_devices.py`, `diag_mic_{live,mute,wasapi}.py`, `verify_orb_{appears,mute_toggle,drag}.py`, `snap_orb.py` — audio/orb debugging.
-
-**Migration / one-time:**
-- `wiki_migrate_v0_to_v1.py`, `migrate_adrs.py`, `shorten_adr_titles.py`, `bulk_translate{,_2,_3}.py`, `rewrite_locales.py`, `find_german_strings.py`, `add_useT_inner.py`, `export_ws_schema.py`, `build_frontend.py`.
-
----
-
-## 20. External integrations & accounts
-
-**Brain providers** (6 plugins):
-
-- **Gemini = primary** (user's main brain; `gemini-3-flash-preview` / `gemini-3.1-pro-preview`).
-- **Grok = fallback** (xAI — primary TTS voice "leo" + Brain fallback). API key reused for both.
-- **Claude-API** plugin exists but **user has NO Anthropic API account** (AP-6). Workers use Claude Sonnet via Claude Max OAuth through the `claude-cli` backend (`@anthropic-ai/claude-code`), auto-installed by wizard via npm.
-- **OpenRouter** universal gateway, **OpenAI** GPT, **Codex** API-key mode.
-- **GitHub Claude Bot:** deployed on 29 private repos via `.github/workflows/claude.yml`. **Public-repo safety gate** baked in (workflow only runs if `repository.private == true`). OAuth tokens auto-synced from `.credentials.json` every 3h.
-
-**STT** (6 plugins): `faster-whisper` (local, GPU), `openai-api`, `groq-api`, `deepgram`, `deepgram-flux` (Phase L.3 streaming), `deepgram-nova3`. **Google Cloud STT** wired 2026-05-15 — `chirp_2` @ `europe-west4`, ~680ms warm latency. SA-key under `~/.config/jarvis/`.
-
-**TTS** (8 plugins): `elevenlabs`, `elevenlabs-flash`, `gemini-flash-tts`, `google-neural2`, `openai-tts`, `piper-local`, `grok-voice` (default; 5 voices, `leo`=Jarvis-Butler), `cartesia-sonic3`.
-
-**Wake** (2): `porcupine` (Picovoice access key), `openwakeword` (local, threshold tuned to 0.10 — BUG-009 lesson).
-
-**Turn detection** (3): `flux-integrated` (default — Phase L.2 AD-L-4), `smart-turn-v3`, `silero-only`.
-
-**Wiki vault:** `wiki/obsidian-vault/`. Subdirs: `00-index`, `10-notes`, `90-attachments`, `99-templates`, `concepts`, `entities`, `projects`, `sessions`, `_archive`, `.obsidian`. Obsidian registration is opt-in via Wiki tab dialog (ADR-0015); supports both `%LOCALAPPDATA%\Obsidian\` and `%PROGRAMFILES%\Obsidian\`.
-
-**Channels** (2): `web` (WS to desktop frontend), `telegram` (`python-telegram-bot 22.x`, long-polling, F1).
-
-**MCP servers:** loaded from `data/mcp.json`, registered via `MCPRegistry`. Tools auto-bridged into the global tool registry through `register_mcp_tools_in_registry`.
-
----
-
-## 21. ADR + Phase doc index
-
-**ADRs in `docs/adr/`** (18 files; duplicate-number cleanup pending):
-
-- ADR-0001 — IPC Named-Pipe HMAC (Admin-Helper)
-- ADR-0002 — UIA Tree Pruning (Vision)
-- ADR-0003 — Task Queue Storage (Phase-5 Async)
-- ADR-0004 — Kill Propagation
-- ADR-0005 — Lightweight Scheduler (croniter, no APScheduler)
-- ADR-0006 — Cost-Budget Hook
-- ADR-0007 — Flight-Recorder JSONL
-- ADR-0008 — Computer-Use Harness In-Process (POAV)
-- ADR-0009 — Awareness Architecture / Self-Healing Worker-Critic *(duplicate number)*
-- ADR-0010 — Output-Filter Pattern-Based / Window-Focus Watcher MsgWait *(duplicate number)*
-- ADR-0011 — Router Pure Dispatcher (amended for Welle 4: SUB_TOOLS deleted)
-- ADR-0012 — Awareness Recall Router-Tier
-- ADR-0013 — Knowledge Wiki Architecture (Karpathy-style structured vault)
-- ADR-0014 — Flash-Brain Suppress-If-Fast / Memory-Trigger Contract *(duplicate number)*
-- ADR-0015 — Obsidian Setup Wizard (B9)
-
-**Phase docs in `docs/`:**
-
-- `phase1a-verify.md` — Desktop App scaffold (FastAPI + pywebview + React)
-- `phase1c-test-results.md` / `phase1c-review-report.md` — Skill system + MCP integration
-- `phase2-integration-test-results.md` — Tool-use loop + risk-tier executor
-- `phase4-integration-test-results.md` — Harness dispatch + core memory
-- `phase5-research.md` / `phase5-integration-test-results.md`
-- `phase6-test-report.md` — 458 mission tests, 5 sub-phases verified
-- `phase6-worker-layer.md` — worktree + Job Object isolation
-- `phase6-prompt-chain.md` — Action/Observation invariant (ADR-0009)
-- `phase6-handoff-2026-04-26.md`
-
-Self-mod writeup: [`docs/self_mod.md`](docs/self_mod.md) — 8 mutable settings (`tts.provider`, `tts.voice_{de,en}`, `tts.speed`, `stt.provider`, `brain.primary`, `ui.theme`, `profile.language`), append-only audit at `data/self_mod.log`.
-
----
-
-## 22. Operational rhythms
-
-- **`run.bat` pre-boot:** `scripts/check-working-tree.ps1` auto-invoked. Always exits 0; surfaces any restored file via banner + rotating log.
-- **Drift-guard daemon:** every 5 min via `shell:startup` shortcut, Userland (no UAC). Singleton-locked.
-- **Auto-push-EOD:** Task Scheduler 22:00 default. Tags `safety/eod-*` per branch, skips active OpenClaw worktrees (modified within last 30 min).
-- **Wiki triggers** (ADR-0014 contract — all classified silent vs loud):
- - `WikiContextInjector` (silent) — runs before every brain turn
- - `VoiceFactBridge` ack path (loud) — `ResponseGenerated` with ack keyword, async via `asyncio.create_task`
- - `VoiceFactBridge` aggressive path (loud, rate-limited 60s default, opt-out `aggressive_mode=false`)
- - `SessionRollupWorker` (loud) — `IdleEntered` past `session_idle_threshold_minutes`, writes one Markdown page per session
-- **Preflight:** mandatory in every new worktree before any code edit.
-
----
-
-## 23. Repo hygiene & contribution
-
-- **Output Language Policy (highest priority):** every artifact in the repo is **English** — code, comments, docstrings, Markdown, commit messages, PR titles/bodies, tests, CLI help, REST descriptions, error responses, audit logs, telemetry, UI i18n source. German stays only for the assistant's user-facing chat reply, TTS at runtime, and already-committed German content.
-- **Plan vs. code:** on conflict, plan wins. Master plan binds: `~/.claude/plans/also-er-muss-auch-lexical-pond.md`. Architecture contracts: [`docs/openclaw-bridge.md`](docs/openclaw-bridge.md), [`docs/anti-drift-three-layer.md`](docs/anti-drift-three-layer.md).
-- **Worktree activation checklist:** **`pwsh scripts/preflight.ps1`** before code in any new worktree. If exit non-zero, fix before proceeding (BUG-006/014, AD-UF23).
-- **Before larger edits:** read [`docs/BUGS.md`](docs/BUGS.md) — every recurring bug class catalogued there.
-- **Plugin contract:** plugin modules MUST NOT import from `jarvis.*` — structural compatibility with Protocol only. After edit: `pip install -e . --no-deps`.
-- **Streaming first:** all Brain/STT/TTS/Harness methods return `AsyncIterator[...]`.
-- **Events:** `frozen=True` dataclasses with `trace_id: UUID` + `timestamp_ns`. Subscriber exceptions never propagate (AP-18).
-- **Worker isolation invariants:** every worker = fresh `git worktree` + Windows Job Object kill-on-close. `MAX_CRITIC_LOOPS=3` hardcoded; changes require new ADR via `/skill phase6-adr-update`.
-
----
-
-## 24. Key module index
-
-| File | Purpose |
+| Document | What's in it |
|---|---|
-| `jarvis/core/protocols.py:161` | All plugin Protocols (`WakeWordProvider`, `STTProvider`, `TTSProvider`, `Brain`, `Harness`, `Tool`, `MemoryStore`, `ChannelAdapter`, `TurnDetector`, `VisionSource`, `CancelToken`, `CostMeter`, `IntentClassifier`). Frozen dataclasses for all wire types. |
-| `jarvis/core/bus.py:23` | `EventBus` — async pub/sub with `_safe_dispatch` exception isolation, wildcard `subscribe_all` for flight recorder. |
-| `jarvis/core/events.py:29` | `Event` base + 100+ subclasses, all `frozen=True` with `trace_id` + `timestamp_ns`. |
-| `jarvis/core/config.py` | `JarvisConfig` Pydantic model + loader + `get_secret(key, env_fallback)`. |
-| `jarvis/core/config_writer.py` | `tomlkit`-based atomic patch with `_WRITE_LOCK`, BOM-aware. |
-| `jarvis/core/self_mod/writer.py` | `AtomicConfigWriter` — 10-step validate/backup/rollback pipeline. |
-| `jarvis/core/process_utils.py:33` | `NO_WINDOW_CREATIONFLAGS` — mandatory for every subprocess call (AP-1). |
-| `jarvis/brain/factory.py:40` | `ROUTER_TOOLS` frozenset + `_phase2_full_brain` builder. |
-| `jarvis/brain/manager.py` | `BrainManager` — provider cache, fallback chain, force-spawn heuristic. |
-| `jarvis/brain/output_filter.py` | `scrub_for_voice` — regex-only TTS scrubber, 40-case test suite. |
-| `jarvis/brain/ack_brain/generator.py` | `AckGenerator` — 11-step pipeline, F1–F10 coverage, never raises. |
-| `jarvis/safety/risk_tier.py:64` | `RiskTierEvaluator` — blacklist>whitelist>tool, fnmatch glob, `ActionBlocked`. |
-| `jarvis/safety/tool_executor.py` | `ToolExecutor` — only authorized call path for `Tool.execute()`. |
-| `jarvis/missions/manager.py:48` | `MissionManager` — SQLite event store, state machine, persist-vor-publish discipline. |
-| `jarvis/missions/kontrollierer/orchestrator.py` | Phase-6 heart — TaskGroup + Semaphore wiring of MissionDecomposer→Worker→Critic→ReflectionMemory→BudgetTracker. |
-| `jarvis/missions/critic/runner.py:50` | `MAX_CRITIC_LOOPS = 3` hardcoded. |
-| `jarvis/missions/workers/{base,claude_direct_worker,codex_worker,gemini_worker,subjarvis_worker,supervisor}.py` | Worker variants — `WorkerProtocol` structural contract. |
-| `jarvis/missions/isolation/{worktree,job_object,env}.py` | Git-worktree manager + Windows Job Object kill-on-close. |
-| `jarvis/plugins/harness/openclaw.py` | OpenClaw bridge plugin (Welle-2 Mock-Mode). |
-| `jarvis/harness/screenshot_only_loop.py` | Screenshot-only POAV loop — the sole `computer_use` engine (vision picks pixel targets; cross-platform `mss` + `pyautogui`). |
-| `jarvis/awareness/manager.py` | `AwarenessManager` — state holder; **never on voice critical path** (AP-9). |
-| `jarvis/memory/wiki/integration.py` | `bootstrap_wiki_integration` — wires SessionRollupWorker (B7) + WikiCurator (B1). |
-| `jarvis/sessions/constants.py` | `HANGUP_REASONS` single source of truth — canonical 5-layer enum example. |
-| `jarvis/speech/pipeline.py` | Voice pipeline — wake→VAD→STT→Brain→TTS, scrub_for_voice at lines 647 and 1330. |
-| `jarvis/ui/web/server.py` | FastAPI app, mission stack bootstrap (`_init_mission_stack`). |
-| `jarvis/clis/loader.py` | Virtual-loader expanding `cli-tools` entry-point into N `cli_<name>` Tool instances. |
-
----
+| [`CLAUDE.md`](CLAUDE.md) | Binding contributor guide — conventions, doctrine, anti-patterns |
+| [`docs/PHILOSOPHY.md`](docs/PHILOSOPHY.md) | Cross-platform, provider-agnostic design doctrine |
+| [`docs/BRAND.md`](docs/BRAND.md) | Brand guidelines — colors, typography, the wordmark |
+| [`docs/openclaw-bridge.md`](docs/openclaw-bridge.md) | The agent-harness contract |
+| [`docs/adr/`](docs/adr/) | Architecture Decision Records |
+| [`docs/BUGS.md`](docs/BUGS.md) | The recurring-bug register |
-## 25. Doc-vs-code drift (verified)
+> 🤖 **Working with an LLM on this codebase?** Paste
+> [`docs/LLM-CONTEXT.md`](docs/LLM-CONTEXT.md) into a fresh chat — it's a dense,
+> self-contained snapshot of the entire project, built for exactly that.
-Two drifts surfaced during the agent audit; flag them before quoting CLAUDE.md to a fresh chat:
+## Community
-1. **`spawn-skill-author` IS registered in `pyproject.toml:208`** as `spawn-skill-author = "jarvis.brain.tools.skill_authoring:SpawnSkillAuthorTool"` (landed 2026-05-17 per inline comment). CLAUDE.md still says "7.5 `spawn_skill_author` not yet registered in `pyproject.toml`" — outdated. The Phase-7.5 self-modifying skill-authoring tool is wired.
+Come build with us — questions, ideas, and showcases all welcome.
-2. **`jarvis/sub_jarvis/` directory still exists** as an **empty placeholder** (no `__init__.py`, no files) despite CLAUDE.md and `docs/openclaw-bridge.md §11` declaring it deleted in Welle 4. Cleanup is structurally complete (no code references), but the empty dir itself is leftover.
+<p align="center">
+ <a href="https://discord.gg/UPu6pFWrJ"><img alt="Discord" src="https://img.shields.io/badge/Discord-join_the_server-FFD60A?style=for-the-badge&logo=discord&logoColor=0A0A0A&labelColor=0A0A0A" /></a>
+ <a href="https://x.com/PersonalJarvis"><img alt="X" src="https://img.shields.io/badge/X-follow-FFD60A?style=for-the-badge&logo=x&logoColor=0A0A0A&labelColor=0A0A0A" /></a>
+</p>
-Neither blocks anything — but a fresh chat parroting CLAUDE.md verbatim will be wrong on point 1, and confused by `ls jarvis/` on point 2.
+- **Discord** — [discord.gg/UPu6pFWrJ](https://discord.gg/UPu6pFWrJ)
+- **X** — [@PersonalJarvis](https://x.com/PersonalJarvis) · [@Ruben_Herz](https://x.com/Ruben_Herz)
+- **Instagram** — [@personaljarvis](https://www.instagram.com/personaljarvis/)
+- **GitHub** — [PersonalJarvis/PersonalJarvis](https://github.com/PersonalJarvis/PersonalJarvis)
----
-
-## 26. Pointers
-
-- [`CLAUDE.md`](CLAUDE.md) — project guidance (highest priority for any agent working in this repo)
-- [`docs/BUGS.md`](docs/BUGS.md) — 26-entry bug register with regression-test pointers
-- [`docs/openclaw-bridge.md`](docs/openclaw-bridge.md) — AD-1..AD-21 OpenClaw harness contract
-- [`docs/anti-drift-three-layer.md`](docs/anti-drift-three-layer.md) — five-layer enum pattern (mandatory for any new wire-format string)
-- [`docs/self_mod.md`](docs/self_mod.md) — Phase 7 self-mod user guide
-- [`docs/obsidian-setup.md`](docs/obsidian-setup.md) — Wiki vault registration walkthrough
-- `~/.claude/plans/also-er-muss-auch-lexical-pond.md` — binding master plan
-- `~/.claude/projects/C--Users-Administrator-Desktop-Personal-Jarvis/memory/MEMORY.md` — auto-memory with stable user preferences (multi-provider brain, no-Anthropic-API, bilingual, anti-confirmation-fatigue, frontier-quality-before-cost)
+## Sponsors & supporters
----
-
-## 27. Legal
+Personal Jarvis is independent and self-funded. If it saves you time, or you just like
+where it's headed, sponsorship keeps the lights on and the roadmap moving — and goes
+straight into provider costs, infrastructure, and development time.
-**License — MIT.** Personal Jarvis is released under the MIT License. The full license text lives in [`LICENSE`](LICENSE) at the repository root and is also declared in `pyproject.toml` (`license = { text = "MIT" }`). In short: you are free to use, copy, modify, merge, publish, distribute, sublicense, and sell copies of the software, including for commercial purposes — provided you comply with the **Attribution & provenance** clause below. The software is provided "as is", without warranty of any kind.
+<p align="center">
+ <a href="https://github.com/sponsors/PersonalJarvis"><img alt="Sponsor" src="https://img.shields.io/badge/Sponsor-♥-FFD60A?style=for-the-badge&logo=githubsponsors&logoColor=0A0A0A&labelColor=0A0A0A" /></a>
+</p>
-**Copyright.** © 2026 Personal Jarvis Maintainers. All contributors retain copyright on their respective contributions; opening a pull request against this repository is taken as agreement that the contribution is licensed under the MIT License above.
+<p align="center">
+ <i>This wall is empty — for now.</i><br/>
+ <a href="https://github.com/sponsors/PersonalJarvis"><b>Become the first sponsor →</b></a>
+</p>
-**Canonical source.** This repository — **[`github.com/PersonalJarvis/PersonalJarvis`](https://github.com/PersonalJarvis/PersonalJarvis)** — is the authoritative upstream of Personal Jarvis. Forks, mirrors, vendored copies, and derivative works are welcome under MIT, but the **original authors are the Personal Jarvis Maintainers**, not whoever is hosting the copy you happened to find. If you encounter Personal Jarvis code outside this URL, you can verify provenance by comparing the git history against the canonical repository.
+| Tier | You get |
+|---|---|
+| **Backer** | Your name in this README + a supporter role on Discord |
+| **Supporter** | The above + a link to your project or profile |
+| **Sponsor** | The above + your logo on the sponsor wall |
+| **Partner** | The above + a seat at the roadmap table |
-**Attribution & provenance (mandatory).** Section 2 of the MIT License is **not decorative** — it requires that *"the above copyright notice and this permission notice shall be included in all copies or substantial portions of the Software."* In plain English: anyone who uses substantial portions of this code in their own project, fork, distribution, product, or training corpus **must retain the `Copyright (c) 2026 Personal Jarvis Maintainers` line and the full MIT permission text in a place where downstream users can find them** (typical conventions: a `LICENSE` / `LICENSES/` / `NOTICE` / `THIRD_PARTY_NOTICES` file at the root of the derivative work, or an "Open Source Licenses" screen reachable from a product's UI). Stripping the notice and republishing the code is **not** a licensing question — it is **copyright infringement**, actionable under copyright law in the 179 Berne-Convention signatory states. We additionally request — though we cannot legally compel beyond MIT — that derivative works include a visible link back to the canonical repository above so users can find the upstream project.
+> Sponsorship is being set up. Want to talk before the page is live? Reach out on
+> [Discord](https://discord.gg/UPu6pFWrJ) or [X](https://x.com/PersonalJarvis).
-**No misrepresentation of authorship.** The MIT License grants broad freedom to modify and redistribute, but it does **not** grant the right to claim original authorship of unmodified portions of this work. Re-uploading substantial parts of this codebase to another repository, package registry, model card, or product page while presenting yourself as the original author — by removing the copyright notice, by removing references to the canonical source, or by adding statements that imply you wrote what you in fact copied — misrepresents the provenance of the work. This is treated as **both a license violation (because the MIT attribution clause was not honored) and as deceptive attribution under most jurisdictions' consumer-protection and unfair-competition law**, independent of the license. If you fork and significantly modify the code, please describe your modifications clearly so users can tell your work apart from the upstream — that is good citizenship, not a legal requirement, but it is how the open-source ecosystem stays trustworthy.
+## Contributing
-**Reporting violations.** If you encounter a project that has copied substantial portions of this codebase without preserving the copyright notice, or that misrepresents authorship of the original Personal Jarvis work, please file a copyright-violation report with the hosting platform — for GitHub, the [DMCA Takedown Policy](https://docs.github.com/en/site-policy/content-removal-policies/dmca-takedown-policy) is the standard route — or open an issue on the canonical repository. The Personal Jarvis Maintainers reserve all rights granted by copyright law.
+Pull requests are welcome — see **[`CONTRIBUTING.md`](CONTRIBUTING.md)** for the full guide
+(dev setup, architecture, the plugin-vs-tool-vs-skill decision, and the PR checklist). The
+short version:
-**Third-party software.** This project bundles, imports, or vendors a number of open-source dependencies, each governed by its own license — notably MIT (React, Vite, Zustand, TanStack Query, `pywebview`, `tomlkit`, `keyring`, `croniter`), Apache 2.0 (`faster-whisper`, `silero-vad`, `onnxruntime`, the OpenAI / Gemini / Grok / Anthropic SDKs), BSD-3-Clause (`numpy`, `sounddevice`, `mss`), and Picovoice's commercial-with-free-tier terms for `pvporcupine`. **No third-party dependency is relicensed by inclusion in this repository**, and the attribution requirement above applies to Personal Jarvis's own code, not to the upstream licenses of bundled dependencies (which carry their own attribution clauses you must also honor).
+- **Artifacts are English** — code, comments, docs, and commit messages. (Conversation can
+ be any language; the assistant speaks de/en/es at runtime.)
+- Read [`CLAUDE.md`](CLAUDE.md) and [`docs/PHILOSOPHY.md`](docs/PHILOSOPHY.md) before larger
+ changes — the binding conventions and the cross-platform doctrine.
+- New providers must pass the contract test suite (`pytest tests/contract/`).
+- Found a security issue? Please report it privately — see [`SECURITY.md`](SECURITY.md).
-**Trademarks.** "Claude", "Anthropic", "OpenAI", "Gemini", "Grok", "Picovoice", "Porcupine", "Obsidian", "GitHub", "Windows", and any other product or company names referenced in this repository are trademarks of their respective owners and are used here for identification purposes only. Their use does not imply endorsement of this project by, or affiliation with, the trademark holder.
+## License
-**Audio, voice, and screen-capture privacy disclosure.** When the `[desktop]` extras are installed, Personal Jarvis can capture microphone audio (STT), play synthesized speech (TTS), take screenshots and read UI element trees (Vision / Computer-Use), and read text from the active window. All of these capabilities are opt-in at install time and run only in the user's session. STT, TTS, and Brain calls are routed through the providers the user configures (Gemini, Grok, OpenAI, Deepgram, ElevenLabs, Google Cloud, etc.) — please review each provider's privacy policy before sending production data through them. The headless VPS base install captures no local audio and no screen content.
+Released under the **MIT License** — free to use, modify, and distribute, including
+commercially, provided the copyright notice is preserved. See [`LICENSE`](LICENSE) for the
+full text, the attribution clause, and the third-party notices.
-**No warranty for self-modifying behaviour.** The Phase-7 self-mod tools (`set_config_value`, `spawn-skill-author`) and the Phase-6 Worker-Critic loop can write to `jarvis.toml`, generate skills (created with `state="draft"`, never auto-activated — AP-15), and create isolated `git worktree` branches under `<repo_parent>/sub-agents-outputs/`. The 10-step atomic-write pipeline (allowlist → pre-validate → backup → tempfile → synchronous reload → rollback → audit) is designed to be safe and reversible, but the MIT "as is" disclaimer applies in full: the maintainers are not liable for any state the system writes on your behalf, on your filesystem or against the third-party APIs you have configured.
+<br/>
-**Contributing.** Pull requests are welcome. By contributing you agree that your contribution is licensed under the MIT License above. See [`CLAUDE.md`](CLAUDE.md) and [`docs/PHILOSOPHY.md`](docs/PHILOSOPHY.md) for the binding output-language policy (English-only artifacts) and the cloud-first design doctrine. The repository's bug register lives at [`docs/BUGS.md`](docs/BUGS.md); architecture decisions are recorded under [`docs/adr/`](docs/adr/).
+<p align="center">
+ <sub>Built by the Personal Jarvis Maintainers · © 2026 · MIT</sub><br/>
+ <sub><a href="https://discord.gg/UPu6pFWrJ">Discord</a> · <a href="https://x.com/PersonalJarvis">X</a> · <a href="https://www.instagram.com/personaljarvis/">Instagram</a></sub>
+</p>
diff --git a/docs/adr/ADR-021-web-search.md b/docs/adr/ADR-021-web-search.md
new file mode 100644
index 0000000000..d41bc0c112
--- /dev/null
+++ b/docs/adr/ADR-021-web-search.md
@@ -0,0 +1,117 @@
+---
+title: "ADR-021: Web-search skill — architecture and risk classification"
+slug: adr-021-web-search
+diataxis: adr
+status: accepted
+date: 2026-05-27
+owner: harald
+phase: skills
+audience: developer
+y_statement: >
+ In the context of building a Gemini-routed web-search skill that the
+ router-tier brain can dispatch from voice and text turns,
+ facing the tension between safety-tier mutability (a TOML-driven risk
+ tier can be silently downgraded by self-mod or by a parallel-session
+ drift) and the need for the skill to live in plain Python so reviewers
+ can grep one place,
+ we decided to hardcode `risk_tier = "monitor"` as a module-level Final
+ constant inside `src/skills/web_search/skill.py` and re-export it from
+ the package `__init__.py`,
+ to achieve a single, greppable source of truth that cannot be flipped
+ at runtime by editing `jarvis.toml`,
+ accepting that changing the risk classification now requires a code
+ edit + ADR amendment rather than a config tweak.
+---
+
+# ADR-021 — Web-search skill (Gemini-routed, monitor-tier)
+
+**Status:** Accepted (2026-05-27, Wave-1)
+**Phase:** Skills — first cloud-search skill
+**Pairs with:** ADR-0011 (Router pure dispatcher), ADR-0010 (Output filter pattern-based)
+
+## Context
+
+The router-tier brain needs a cheap, cloud-only way to answer factual
+"what is X / who is Y / when did Z happen" questions without spawning a
+full OpenClaw mission. A dedicated `web_search` skill — backed by
+Gemini's grounded-search mode — fills that gap.
+
+Two architectural pressures shaped the design:
+
+1. **Safety classification must be tamper-resistant.** The existing
+ risk-tier system (`jarvis/safety/risk_tier.py`) reads tier mappings
+ from configuration. For a skill that fans out to the open web,
+ classification drift via TOML edit (or via the soft-disabled but
+ still-present self-mod allowlist path) is a credible vector. The
+ maintainer's history with config-drift (BUG-010 triple-defense,
+ BUG-018 BOM corruption) makes a config-only safety surface the wrong
+ default for an outbound network skill.
+2. **The voice path has a tighter latency budget than the text path.**
+ The existing voice contract (ADR-OE1, ADR-0010, `scrub_for_voice`)
+ demands sub-second perceived latency and no LLM-side scrubbing. The
+ skill must mirror that contract — strip markdown / URLs from the
+ spoken summary using pure regex, never via a second model call — and
+ apply an asymmetric budget (`VOICE_LATENCY_BUDGET_MS = 2_500`,
+ text = 8_000) when a turn arrives from the voice pipeline.
+
+## Decision
+
+The skill is composed of five small modules under
+`src/skills/web_search/`:
+
+| Module | Responsibility |
+|--------|----------------|
+| `_sanitize.py` | NFKC-normalise, strip control chars, reject prompt-injection tokens, cap length at `MAX_QUERY_LEN = 512`. Total over `str`. Property-tested with Hypothesis. |
+| `_gemini_client.py` | `GeminiClient` `Protocol` + `DefaultGeminiClient` (lazy SDK import) + `FakeGeminiClient` (deterministic test double with controllable simulated latency). |
+| `_voice_override.py` | Frozen `SearchSettings` dataclass + `apply_voice_override` (pure tightening function) + `scrub_for_speech` (regex-only). |
+| `skill.py` | `WebSearchSkill` composer + frozen `SkillResult`. **Hardcodes `SKILL_RISK_TIER: Final[str] = "monitor"`** and re-exports it as `WebSearchSkill.risk_tier`. |
+| `__init__.py` | Public re-exports — `WebSearchSkill`, `FakeGeminiClient`, `SKILL_RISK_TIER`, etc. |
+
+The risk-tier hardcode is the load-bearing decision. The literal `"monitor"`
+appears in exactly one place (`skill.py`) and is verifiable via
+`grep -r "risk_tier" src/skills/web_search/`.
+
+## Consequences
+
+**Positive**
+
+- Safety classification cannot be silently flipped via `jarvis.toml`
+ edit, self-mod allowlist write, or parallel-session drift.
+- One grep gives a complete picture of the skill's safety stance.
+- Reviewers can reason about the skill in isolation — no need to also
+ audit a config file.
+- The skill is fully unit-testable: `FakeGeminiClient` lets the latency
+ test bound wall-clock cost without touching the network.
+
+**Negative**
+
+- Changing the tier (e.g. promoting to `ask` after a real-world
+ incident) requires a code edit + new ADR rather than a config
+ tweak. This is intentional friction.
+- Power-users who want to override the tier in their environment must
+ fork or subclass the skill.
+
+**Neutral**
+
+- The skill is currently *not* wired into `jarvis/plugins/tool/` or
+ `pyproject.toml` entry-points. It lives under `src/skills/` as a
+ standalone artifact. Integration into Jarvis's router-tier
+ `ROUTER_TOOLS` frozenset is deferred to a Wave-2 follow-up ADR.
+
+## Alternatives considered
+
+1. **Config-driven tier** — rejected: see context, drift surface too
+ wide for an outbound network skill.
+2. **Decorator-based registration** (`@skill(risk_tier="monitor")`) —
+ rejected: hides the constant behind one extra layer of indirection
+ and makes `grep` noisier (decorator name + skill name + literal).
+3. **Separate `_risk.py` module** — rejected: split for split's sake;
+ the tier is part of the skill's identity, not a separable concern.
+
+## Verification
+
+- `grep -r "risk_tier" src/skills/web_search/` returns the single
+ hardcoded constant + its re-exports + the class attribute.
+- `tests/skills/test_web_search.py::TestSkillIdentity::test_risk_tier_is_monitor_constant`
+ asserts the literal.
+- Phase-1 report: `docs/reports/web-search-phase-1.md`.
diff --git a/docs/superpowers/plans/2026-06-20-assistant-name-coupled-to-wake-word.md b/docs/superpowers/plans/2026-06-20-assistant-name-coupled-to-wake-word.md
new file mode 100644
index 0000000000..f1a25338d1
--- /dev/null
+++ b/docs/superpowers/plans/2026-06-20-assistant-name-coupled-to-wake-word.md
@@ -0,0 +1,811 @@
+# Couple Assistant Name to Wake Word — Implementation Plan
+
+> **For agentic workers:** REQUIRED SUB-SKILL: Use superpowers:subagent-driven-development (recommended) or superpowers:executing-plans to implement this plan task-by-task. Steps use checkbox (`- [ ]`) syntax for tracking.
+
+**Goal:** Make the assistant's name a pure function of the wake phrase, removing the separate `[persona].name` override from the resolver, config, REST write path, Settings UI, and onboarding — and surface the derived name live where the wake word is set.
+
+**Architecture:** Everything that needs the name already reads one resolver, `resolve_assistant_name(config)`. We cut its first stage (the persona override) so the name always derives from the wake phrase; all downstream consumers (system prompt, the `<Name>.md` agent-instructions file, frontend bylines) inherit the change unchanged. Then we delete the now-dead override entry points and add a live "Your assistant will be called: X" hint mirroring the backend derivation.
+
+**Tech Stack:** Python 3.11, Pydantic v2, FastAPI, tomlkit (`config_writer`); React + TypeScript + Vitest; i18n JSON (en/de/es).
+
+**Spec:** `docs/superpowers/specs/2026-06-20-assistant-name-coupled-to-wake-word-design.md`
+
+**Commit policy for this repo:** The working tree is shared with parallel sessions. Each commit step stages ONLY that task's explicit paths (hunk-isolated) — never `git add -A`. Commits happen only on the maintainer's go; if running unattended, complete the code + tests and leave committing to the maintainer.
+
+---
+
+## Task 1: Simplify the resolver — wake phrase always wins
+
+**Files:**
+- Modify: `jarvis/brain/assistant_name.py`
+- Test: `tests/unit/brain/test_assistant_name.py`
+
+- [ ] **Step 1: Rewrite the override tests to assert the wake phrase wins**
+
+In `tests/unit/brain/test_assistant_name.py`, replace the "Explicit override wins" section (the `test_explicit_persona_name_overrides_wake_phrase` and `test_explicit_name_is_trimmed` tests, lines ~42-53) with tests proving a `[persona].name` value is now IGNORED:
+
+```python
+# ----------------------------------------------------------------------
+# The wake phrase is the single source — a legacy [persona].name is ignored
+# ----------------------------------------------------------------------
+
+def test_legacy_persona_name_is_ignored_in_favor_of_wake_phrase():
+ # A stale override from before the coupling must NOT win anymore.
+ cfg = _cfg(persona_name="Friday", wake_phrase="Hey Computer")
+ assert resolve_assistant_name(cfg) == "Computer"
+
+
+def test_legacy_persona_name_alone_does_not_name_the_assistant():
+ # No wake phrase + a stale persona name → fall back, do not use the override.
+ assert resolve_assistant_name(_cfg(persona_name="Friday", wake_phrase="")) == DEFAULT_ASSISTANT_NAME
+```
+
+The derivation + fallback tests (`test_name_derived_from_wake_phrase`, the four fallback tests, `test_whitespace_only_phrase_falls_back`) stay unchanged and must keep passing.
+
+- [ ] **Step 2: Run the tests to verify the two new ones fail**
+
+Run: `pytest tests/unit/brain/test_assistant_name.py -v`
+Expected: `test_legacy_persona_name_is_ignored_in_favor_of_wake_phrase` and `test_legacy_persona_name_alone_does_not_name_the_assistant` FAIL (resolver still returns "Friday"); all others PASS.
+
+- [ ] **Step 3: Drop stage 1 from the resolver**
+
+In `jarvis/brain/assistant_name.py`, replace the module docstring's resolution list and the `resolve_assistant_name` body so the persona override is gone. The function becomes:
+
+```python
+"""Resolve the assistant's own name (how it refers to itself).
+
+The name is a pure function of the wake phrase — there is no separate name
+setting. Resolution order (first non-empty wins):
+ 1. The wake phrase with its trigger prefix stripped — "Hey Jarvis" -> "Jarvis",
+ "Micron" -> "Micron", "Hey Athena" -> "Athena", "Hey Computer" -> "Computer".
+ 2. ``DEFAULT_ASSISTANT_NAME`` — the neutral shipped fallback when no wake phrase
+ is set (pre-onboarding state). Not "Jarvis", so the product imposes no name.
+
+A legacy ``[persona].name`` key in an old jarvis.toml is intentionally ignored:
+the wake word is the single control (see the 2026-06-20 coupling design).
+
+Capitalisation: the derived name is title-cased token-by-token so a lowercase
+wake phrase ("micron") still yields a proper name ("Micron").
+"""
+from __future__ import annotations
+
+from typing import Any
+
+DEFAULT_ASSISTANT_NAME = "Assistant"
+
+
+def resolve_assistant_name(config: Any) -> str:
+ """Return the assistant's display name from ``config`` (see module docstring)."""
+ # 1. Derive from the wake phrase (prefix stripped, title-cased).
+ trigger = getattr(config, "trigger", None)
+ wake_word = getattr(trigger, "wake_word", None) if trigger is not None else None
+ phrase = (getattr(wake_word, "phrase", "") or "") if wake_word is not None else ""
+ if phrase:
+ try:
+ from jarvis.speech.wake_constants import phrase_core
+
+ core = phrase_core(phrase)
+ except Exception: # noqa: BLE001 — never break name resolution on import/parse
+ core = []
+ if core:
+ return " ".join(tok.capitalize() for tok in core)
+
+ # 2. Historical default / safety fallback.
+ return DEFAULT_ASSISTANT_NAME
+```
+
+- [ ] **Step 4: Run the tests to verify all pass**
+
+Run: `pytest tests/unit/brain/test_assistant_name.py -v`
+Expected: ALL PASS.
+
+- [ ] **Step 5: Commit (on the maintainer's go)**
+
+```bash
+git add jarvis/brain/assistant_name.py tests/unit/brain/test_assistant_name.py
+git commit -m "refactor(name): derive assistant name solely from the wake phrase"
+```
+
+---
+
+## Task 2: Update the system-prompt test BEFORE the config field is removed
+
+**Files:**
+- Test: `tests/unit/brain/test_system_prompt_name.py`
+
+> This must land before Task 3. The helper currently does `cfg.persona.name = persona_name`; once the Pydantic field is gone, that assignment raises. We remove the persona-name path from the test here.
+
+- [ ] **Step 1: Rewrite the helper and the override test**
+
+In `tests/unit/brain/test_system_prompt_name.py`, change `_manager_with_name` to drop the `persona_name` parameter and the `cfg.persona.name` assignment, and replace the "explicit persona name wins" test with one proving the wake phrase wins:
+
+Replace the helper (lines ~14-30):
+
+```python
+def _manager_with_name(*, wake_phrase: str = "Hey Jarvis") -> BrainManager:
+ """A BrainManager with __init__ bypassed — only the attrs the prompt needs."""
+ m = BrainManager.__new__(BrainManager)
+ m._soul = None
+ m._user_profile = None
+ m._people = None
+ m._core_memory = None
+ m._awareness_manager = None
+ m._system_prompt_extra = "ROUTER DISCIPLINE BLOCK"
+ m._wiki_context_suffix = ""
+ m._reply_language = "auto"
+ cfg = load_config()
+ cfg.performance.cache_optimized_prompt = False
+ cfg.trigger.wake_word.phrase = wake_phrase
+ m._config = cfg
+ return m
+```
+
+Replace `test_explicit_persona_name_wins_over_wake_phrase` (lines ~48-53) with:
+
+```python
+def test_wake_phrase_is_the_only_name_source() -> None:
+ # "Hey Computer" wake → the assistant is "Computer"; there is no override.
+ prompt = _manager_with_name(wake_phrase="Hey Computer")._build_system_prompt()
+ assert "Du bist Computer" in prompt
+ assert "DEIN NAME IST COMPUTER" in prompt
+ assert "nicht Jarvis" in prompt
+```
+
+The other two tests (`test_default_name_keeps_jarvis_and_no_identity_directive`,
+`test_wake_phrase_micron_makes_assistant_micron`) stay unchanged.
+
+- [ ] **Step 2: Run the test**
+
+Run: `pytest tests/unit/brain/test_system_prompt_name.py -v`
+Expected: ALL PASS (the resolver from Task 1 already derives from the wake phrase; this test no longer touches `persona.name`).
+
+- [ ] **Step 3: Commit (on the maintainer's go)**
+
+```bash
+git add tests/unit/brain/test_system_prompt_name.py
+git commit -m "test(name): system prompt name comes from the wake phrase only"
+```
+
+---
+
+## Task 3: Remove the `PersonaConfig.name` field
+
+**Files:**
+- Modify: `jarvis/core/config.py:103-114`
+
+> `PersonaConfig` has no `model_config`, so Pydantic v2 defaults to `extra="ignore"`: an old `jarvis.toml` with `[persona] name = "X"` still validates cleanly (the key is dropped). We keep the (now empty) class and the `JarvisConfig.persona` field so no `cfg.persona` reader crashes.
+
+- [ ] **Step 1: Confirm no code reads `persona.name` as a hard attribute**
+
+Run: `git grep -n "persona\.name\|persona_name" -- "jarvis/**/*.py"`
+Expected: the only remaining hits are `getattr(persona, "name", "")` (safe — the GET route, fixed in Task 4) and nothing that does a bare `cfg.persona.name` read. If a bare read exists outside a test, convert it to `getattr(..., "name", "")` in this step.
+
+- [ ] **Step 2: Empty out the class**
+
+In `jarvis/core/config.py`, replace the `PersonaConfig` definition (lines ~103-114) with:
+
+```python
+class PersonaConfig(BaseModel):
+ """Reserved ``[persona]`` table. The assistant's name is no longer stored
+ here — it derives solely from the wake phrase (see
+ ``jarvis.brain.assistant_name.resolve_assistant_name`` and the 2026-06-20
+ coupling design). A legacy ``[persona] name`` key in an existing jarvis.toml
+ is ignored (Pydantic ``extra="ignore"``); the next wake-word save strips it.
+ """
+```
+
+(An empty Pydantic model body needs no `pass` — the docstring is the body.)
+
+- [ ] **Step 3: Verify the config still loads with a legacy key**
+
+Run:
+```bash
+python -c "from jarvis.core.config import PersonaConfig; PersonaConfig.model_validate({'name': 'Josef'}); print('ok: legacy [persona] name ignored')"
+```
+Expected: prints `ok: legacy [persona] name ignored` (no validation error, and the instance has no `name` attribute).
+
+- [ ] **Step 4: Run the brain name tests again (regression)**
+
+Run: `pytest tests/unit/brain/test_assistant_name.py tests/unit/brain/test_system_prompt_name.py -v`
+Expected: ALL PASS.
+
+- [ ] **Step 5: Commit (on the maintainer's go)**
+
+```bash
+git add jarvis/core/config.py
+git commit -m "refactor(config): drop [persona].name — name derives from the wake word"
+```
+
+---
+
+## Task 4: Remove the write path; keep GET read-only; strip the dead key on wake-word save
+
+**Files:**
+- Modify: `jarvis/core/config_writer.py` (remove `set_assistant_name`; extend `set_wake_word`)
+- Modify: `jarvis/ui/web/settings_routes.py:612-671`
+- Test: `tests/unit/core/test_config_writer.py` (add a stripping test if the file exists; otherwise create `tests/unit/core/test_config_writer_persona_strip.py`)
+
+- [ ] **Step 1: Write a failing test for the dead-key strip on wake-word save**
+
+Create `tests/unit/core/test_config_writer_persona_strip.py`:
+
+```python
+"""set_wake_word() removes a stale [persona] name so a legacy override can't linger."""
+from __future__ import annotations
+
+from pathlib import Path
+
+from jarvis.core import config_writer
+
+
+def test_set_wake_word_strips_legacy_persona_name(tmp_path: Path) -> None:
+ toml = tmp_path / "jarvis.toml"
+ toml.write_text(
+ "[persona]\nname = \"Josef\"\n\n[trigger.wake_word]\nphrase = \"Hey Jarvis\"\n",
+ encoding="utf-8",
+ )
+
+ config_writer.set_wake_word("Hey Ruben", path=toml)
+
+ text = toml.read_text(encoding="utf-8")
+ assert "Hey Ruben" in text
+ # The stale identity override is gone; the wake word is now the single source.
+ assert "Josef" not in text
+
+
+def test_set_wake_word_without_persona_table_is_a_noop_strip(tmp_path: Path) -> None:
+ toml = tmp_path / "jarvis.toml"
+ toml.write_text("[trigger.wake_word]\nphrase = \"Hey Jarvis\"\n", encoding="utf-8")
+
+ config_writer.set_wake_word("Hey Nova", path=toml) # must not raise
+
+ assert "Hey Nova" in toml.read_text(encoding="utf-8")
+```
+
+- [ ] **Step 2: Run it to verify failure**
+
+Run: `pytest tests/unit/core/test_config_writer_persona_strip.py -v`
+Expected: `test_set_wake_word_strips_legacy_persona_name` FAILS ("Josef" still present).
+
+- [ ] **Step 3: Remove `set_assistant_name` and strip the key in `set_wake_word`**
+
+In `jarvis/core/config_writer.py`:
+
+(a) Delete the entire `set_assistant_name` function (lines ~233-243).
+
+(b) Add a small private helper next to the other `_patch_*` helpers (e.g. right after `_patch_wake_word_toml`, ~line 1075). It mirrors `_patch_table`'s exact read/BOM/parse/dump/`_atomic_write` shape — reuse the module's `_WRITE_LOCK`, `_BOM`, and `_atomic_write`; do NOT introduce a second TOML I/O path (AP-7):
+
+```python
+def _strip_persona_name(path: Path) -> None:
+ """Remove a stale ``[persona] name`` entry (the legacy assistant-name override).
+
+ The wake word is now the single name source, so a leftover ``[persona] name``
+ from before the 2026-06-20 coupling must not linger. Best-effort: a missing
+ file/table/key is a no-op. Preserves comments and the optional BOM, exactly
+ like :func:`_patch_table`.
+ """
+ if not path.exists():
+ return
+
+ with _WRITE_LOCK:
+ raw = path.read_text(encoding="utf-8")
+ had_bom = raw.startswith(_BOM)
+ if had_bom:
+ raw = raw[len(_BOM):]
+ doc: TOMLDocument = tomlkit.parse(raw)
+ persona = doc.get("persona")
+ if persona is None or "name" not in persona:
+ return
+ del persona["name"]
+ out = tomlkit.dumps(doc)
+ if had_bom:
+ out = _BOM + out
+ _atomic_write(path, out)
+```
+
+Then call it at the end of `set_wake_word` (after the existing `_patch_wake_word_toml(path, values)` line — `_patch_wake_word_toml` releases `_WRITE_LOCK` before returning, so the re-acquire in `_strip_persona_name` is sequential, not nested: no deadlock):
+
+```python
+ _patch_wake_word_toml(path, values)
+ try:
+ _strip_persona_name(path)
+ except Exception as exc: # noqa: BLE001 — cleanup is best-effort, never breaks the save
+ log.debug("persona-name strip skipped: %s", exc)
+```
+
+- [ ] **Step 4: Run the strip tests**
+
+Run: `pytest tests/unit/core/test_config_writer_persona_strip.py -v`
+Expected: BOTH PASS.
+
+- [ ] **Step 5: Slim the REST endpoints**
+
+In `jarvis/ui/web/settings_routes.py`:
+
+(a) Delete the `AssistantNameBody` model (lines ~619-622).
+
+(b) Delete the entire `put_assistant_name` handler (lines ~639-671).
+
+(c) Replace the `get_assistant_name` handler (lines ~625-636) with a read-only version that returns only the resolved name:
+
+```python
[email protected]("/assistant-name")
+async def get_assistant_name(request: Request) -> dict[str, object]:
+ """The assistant's resolved name. Read-only: the name derives from the wake
+ phrase (set via PUT /api/settings/wake-word), there is no separate control."""
+ from jarvis.brain.assistant_name import DEFAULT_ASSISTANT_NAME, resolve_assistant_name
+
+ cfg = _config(request)
+ return {
+ "resolved": resolve_assistant_name(cfg),
+ "default": DEFAULT_ASSISTANT_NAME,
+ }
+```
+
+(d) Update the section comment above it (lines ~612-616) to: `# Assistant name (read-only). The name derives from the wake phrase; GET exposes the resolved name for the frontend bylines. There is no write endpoint.`
+
+- [ ] **Step 6: Verify the backend imports and the route still answers**
+
+Run: `python -c "import jarvis.ui.web.settings_routes as r; print('import ok')"`
+Expected: prints `import ok` (no reference to the deleted `set_assistant_name` / `AssistantNameBody`).
+
+Run: `git grep -n "set_assistant_name\|AssistantNameBody\|put_assistant_name" -- jarvis`
+Expected: no hits.
+
+- [ ] **Step 7: Commit (on the maintainer's go)**
+
+```bash
+git add jarvis/core/config_writer.py jarvis/ui/web/settings_routes.py tests/unit/core/test_config_writer_persona_strip.py
+git commit -m "refactor(settings): remove assistant-name write path; GET stays read-only; strip stale key on wake-word save"
+```
+
+---
+
+## Task 5: Remove the `persona-theme` onboarding step (backend)
+
+**Files:**
+- Modify: `jarvis/setup/onboarding_meta.py:18-28`
+- Test: `tests/unit/setup/test_onboarding_meta.py`
+
+- [ ] **Step 1: Update the parity test first**
+
+In `tests/unit/setup/test_onboarding_meta.py`, replace the step-order assertions (lines ~9-14) with:
+
+```python
+ assert "wake-word" in m.ONBOARDING_STEPS
+ assert "persona-theme" not in m.ONBOARDING_STEPS
+ # The "system-style" overlay chooser now sits right after mic-test and right
+ # before finish (the persona-theme name step was removed 2026-06-20).
+ assert m.ONBOARDING_STEPS.index("system-style") == m.ONBOARDING_STEPS.index("mic-test") + 1
+ assert m.ONBOARDING_STEPS[-2] == "system-style"
+ assert len(m.ONBOARDING_STEPS) == 8
+```
+
+- [ ] **Step 2: Run it to verify failure**
+
+Run: `pytest tests/unit/setup/test_onboarding_meta.py -v`
+Expected: `test_meta_constants` FAILS (`persona-theme` still present, len == 9).
+
+- [ ] **Step 3: Remove the step from the canonical list**
+
+In `jarvis/setup/onboarding_meta.py`, delete the `"persona-theme",` line from `ONBOARDING_STEPS` (line ~25), leaving:
+
+```python
+ONBOARDING_STEPS: list[str] = [
+ "welcome",
+ "terms",
+ "language",
+ "wake-word",
+ "api-keys",
+ "mic-test",
+ "system-style",
+ "finish",
+]
+```
+
+- [ ] **Step 4: Run the test**
+
+Run: `pytest tests/unit/setup/test_onboarding_meta.py -v`
+Expected: ALL PASS.
+
+- [ ] **Step 5: Commit (on the maintainer's go)**
+
+```bash
+git add jarvis/setup/onboarding_meta.py tests/unit/setup/test_onboarding_meta.py
+git commit -m "feat(onboarding): drop the separate persona-name step"
+```
+
+---
+
+## Task 6: Frontend — shared `deriveAssistantName` helper (mirrors the backend)
+
+**Files:**
+- Create: `jarvis/ui/web/frontend/src/lib/deriveAssistantName.ts`
+- Test: `jarvis/ui/web/frontend/src/lib/deriveAssistantName.test.ts`
+
+- [ ] **Step 1: Write the failing test**
+
+Create `jarvis/ui/web/frontend/src/lib/deriveAssistantName.test.ts`:
+
+```typescript
+import { describe, expect, it } from "vitest";
+import { deriveAssistantName } from "./deriveAssistantName";
+
+describe("deriveAssistantName", () => {
+ it("strips a wake prefix and title-cases", () => {
+ expect(deriveAssistantName("Hey Ruben")).toBe("Ruben");
+ expect(deriveAssistantName("hey computer")).toBe("Computer");
+ expect(deriveAssistantName("ok friday")).toBe("Friday");
+ expect(deriveAssistantName("Micron")).toBe("Micron");
+ expect(deriveAssistantName("micron")).toBe("Micron");
+ });
+
+ it("returns empty string for blank input", () => {
+ expect(deriveAssistantName("")).toBe("");
+ expect(deriveAssistantName(" ")).toBe("");
+ });
+
+ it("keeps an all-prefix phrase rather than emptying it", () => {
+ // mirrors backend phrase_core: never returns empty for a non-empty phrase
+ expect(deriveAssistantName("Hey")).toBe("Hey");
+ });
+});
+```
+
+- [ ] **Step 2: Run it to verify failure**
+
+Run (from `jarvis/ui/web/frontend/`): `npm run test -- deriveAssistantName`
+Expected: FAIL ("Cannot find module './deriveAssistantName'").
+
+- [ ] **Step 3: Implement the helper**
+
+Create `jarvis/ui/web/frontend/src/lib/deriveAssistantName.ts`:
+
+```typescript
+/**
+ * Derive the assistant's display name from a wake phrase — the TS mirror of
+ * `jarvis.speech.wake_constants.phrase_core` + the title-casing in
+ * `jarvis.brain.assistant_name.resolve_assistant_name`. Used for the live
+ * "Your assistant will be called: X" hint while the user sets the wake word.
+ *
+ * Keep in lockstep with the backend WAKE_PREFIXES set.
+ */
+const WAKE_PREFIXES = new Set([
+ "hey", "hi", "ok", "okay", "hello", "hallo", "yo", "hej",
+]);
+
+export function deriveAssistantName(phrase: string): string {
+ // normalize_phrase: lower-case, punctuation→space, split (keeps umlauts/ß).
+ const tokens = (phrase || "")
+ .toLowerCase()
+ .replace(/[^0-9a-zäöüß]+/g, " ")
+ .trim()
+ .split(/\s+/)
+ .filter(Boolean);
+ if (tokens.length === 0) return "";
+
+ // phrase_core: drop leading wake prefixes, but never empty a non-empty phrase.
+ let core = [...tokens];
+ while (core.length > 0 && WAKE_PREFIXES.has(core[0])) core.shift();
+ if (core.length === 0) core = tokens;
+
+ return core.map((tok) => tok.charAt(0).toUpperCase() + tok.slice(1)).join(" ");
+}
+```
+
+- [ ] **Step 4: Run the test**
+
+Run (from `jarvis/ui/web/frontend/`): `npm run test -- deriveAssistantName`
+Expected: ALL PASS.
+
+- [ ] **Step 5: Commit (on the maintainer's go)**
+
+```bash
+git add jarvis/ui/web/frontend/src/lib/deriveAssistantName.ts jarvis/ui/web/frontend/src/lib/deriveAssistantName.test.ts
+git commit -m "feat(ui): add deriveAssistantName helper mirroring the backend"
+```
+
+---
+
+## Task 7: Frontend Settings — remove the name panel, add the wake-word live preview
+
+**Files:**
+- Modify: `jarvis/ui/web/frontend/src/views/SettingsView.tsx`
+
+- [ ] **Step 1: Remove the AssistantNamePanel and its usage**
+
+In `SettingsView.tsx`:
+
+(a) Delete the import on line ~33: `import { useAssistantName } from "@/hooks/useAssistantName";`
+
+(b) Delete the `<AssistantNamePanel />` render on line ~70.
+
+(c) Delete the entire `AssistantNamePanel` function (lines ~300-389, the block from its doc-comment through its closing brace).
+
+(d) If `Bot` (the lucide icon used only by that panel) is now unused, remove it from the lucide import to keep `tsc`/lint clean. Verify with a search for `Bot` in the file before removing.
+
+- [ ] **Step 2: Add the live derived-name preview to WakeWordPanel**
+
+In the `WakeWordPanel` function, add the import at the top of the file (near the other `@/lib` imports):
+
+```typescript
+import { deriveAssistantName } from "@/lib/deriveAssistantName";
+```
+
+Then, inside `WakeWordPanel`, compute the derived name from the live `phrase` state and render a hint right after the phrase `<input>` (after line ~194, before the engine `<label>`):
+
+```tsx
+ {(() => {
+ const derived = deriveAssistantName(phrase);
+ return derived ? (
+ <p className="mt-1.5 text-xs text-muted-foreground">
+ {t("settings_view.wake_word.derived_name").replace("{0}", derived)}
+ </p>
+ ) : null;
+ })()}
+```
+
+- [ ] **Step 3: Type-check and build**
+
+Run (from `jarvis/ui/web/frontend/`): `npx tsc -b`
+Expected: no errors (no dangling `useAssistantName` / `AssistantNamePanel` / `Bot` references).
+
+- [ ] **Step 4: Commit (on the maintainer's go)**
+
+```bash
+git add jarvis/ui/web/frontend/src/views/SettingsView.tsx
+git commit -m "feat(settings): drop the assistant-name panel; show derived name under the wake word"
+```
+
+---
+
+## Task 8: Frontend Onboarding — delete the persona step, wire the wake-word preview
+
+**Files:**
+- Delete: `jarvis/ui/web/frontend/src/components/onboarding/steps/PersonaThemeStep.tsx`
+- Delete: `jarvis/ui/web/frontend/src/components/onboarding/steps/PersonaThemeStep.test.tsx`
+- Modify: `jarvis/ui/web/frontend/src/components/onboarding/OnboardingFlow.tsx`
+- Modify: `jarvis/ui/web/frontend/src/components/onboarding/OnboardingFlow.test.tsx`
+- Modify: `jarvis/ui/web/frontend/src/components/onboarding/steps/WakeWordStep.tsx`
+
+- [ ] **Step 1: Delete the persona step files**
+
+```bash
+git rm jarvis/ui/web/frontend/src/components/onboarding/steps/PersonaThemeStep.tsx \
+ jarvis/ui/web/frontend/src/components/onboarding/steps/PersonaThemeStep.test.tsx
+```
+
+- [ ] **Step 2: Remove it from the REGISTRY**
+
+In `OnboardingFlow.tsx`:
+
+(a) Delete the import on line ~11: `import { PersonaThemeStep } from "./steps/PersonaThemeStep";`
+
+(b) Delete the `"persona-theme": PersonaThemeStep,` entry from `REGISTRY` (line ~31). `STEP_KEYS` derives from `REGISTRY`, so it updates automatically.
+
+- [ ] **Step 3: Update the OnboardingFlow parity test**
+
+In `OnboardingFlow.test.tsx`:
+
+(a) Delete the mock on line ~23: `vi.mock("./steps/PersonaThemeStep", () => ({ PersonaThemeStep: dbl("step-persona-theme") }));`
+
+(b) In the "REGISTRY covers exactly the canonical backend steps" test (lines ~81-88), remove `"persona-theme"` from the expected set:
+
+```typescript
+it("REGISTRY covers exactly the canonical backend steps", () => {
+ expect(new Set(STEP_KEYS)).toEqual(
+ new Set([
+ "welcome", "terms", "language", "wake-word",
+ "api-keys", "mic-test", "system-style", "finish",
+ ]),
+ );
+});
+```
+
+- [ ] **Step 4: Add the live preview to the onboarding WakeWordStep**
+
+In `WakeWordStep.tsx`:
+
+(a) Add the import near the top:
+
+```typescript
+import { deriveAssistantName } from "@/lib/deriveAssistantName";
+```
+
+(b) After the phrase input block (the closing `</div>` of the `flex items-center gap-2` row, line ~53), insert the derived-name hint. The onboarding input is the bare word with a fixed "Hey " prefix, so mirror the backend by deriving from the full stored phrase:
+
+```tsx
+ {(() => {
+ const derived = deriveAssistantName(`Hey ${trimmed}`);
+ return trimmed.length >= 2 && derived ? (
+ <p className="text-xs text-muted-foreground">
+ {t("onboarding.wake_word.derived_name").replace("{0}", derived)}
+ </p>
+ ) : null;
+ })()}
+```
+
+- [ ] **Step 5: Add a preview test to WakeWordStep.test.tsx**
+
+`WakeWordStep.test.tsx` mocks `useT` as `(k) => k`, so the rendered hint text is the raw key `onboarding.wake_word.derived_name` (the `.replace("{0}", …)` leaves it untouched — no `{0}` in the key). That lets us assert the conditional rendering without a real translation. Append this test (the exact `deriveAssistantName` output is already covered by `deriveAssistantName.test.ts`):
+
+```typescript
+it("shows the derived-name preview only after a valid word is typed", () => {
+ render(<WakeWordStep onb={onb} goNext={vi.fn()} goBack={vi.fn()} skip={vi.fn()} isFirst={false} isLast={false} />);
+ // No preview before typing.
+ expect(screen.queryByText("onboarding.wake_word.derived_name")).toBeNull();
+ // A valid word (>= 2 chars) surfaces the hint line.
+ fireEvent.change(screen.getByRole("textbox"), { target: { value: "Nova" } });
+ expect(screen.queryByText("onboarding.wake_word.derived_name")).not.toBeNull();
+});
+```
+
+- [ ] **Step 6: Type-check and run the onboarding tests**
+
+Run (from `jarvis/ui/web/frontend/`): `npx tsc -b`
+Expected: no errors.
+
+Run: `npm run test -- onboarding WakeWordStep`
+Expected: ALL PASS (no reference to the deleted PersonaThemeStep; the new preview test passes).
+
+- [ ] **Step 7: Commit (on the maintainer's go)**
+
+```bash
+git add jarvis/ui/web/frontend/src/components/onboarding/
+git commit -m "feat(onboarding): remove persona-name step; preview derived name on the wake-word step"
+```
+
+---
+
+## Task 9: Delete the now-dead `useAssistantName` save hook
+
+**Files:**
+- Delete: `jarvis/ui/web/frontend/src/hooks/useAssistantName.ts`
+
+> `useAssistantNameSeed.ts` stays — it read-only-seeds the resolved name into the store for the bylines and still uses the GET endpoint.
+
+- [ ] **Step 1: Confirm there are no remaining importers**
+
+Run: `git grep -n "useAssistantName\b" -- jarvis/ui/web/frontend/src`
+Expected: no hits (Task 7 removed the only importer). If any hit remains, fix it before deleting.
+
+- [ ] **Step 2: Delete the file**
+
+```bash
+git rm jarvis/ui/web/frontend/src/hooks/useAssistantName.ts
+```
+
+- [ ] **Step 3: Type-check**
+
+Run (from `jarvis/ui/web/frontend/`): `npx tsc -b`
+Expected: no errors.
+
+- [ ] **Step 4: Commit (on the maintainer's go)**
+
+```bash
+git add jarvis/ui/web/frontend/src/hooks/useAssistantName.ts
+git commit -m "chore(ui): remove dead useAssistantName save hook"
+```
+
+---
+
+## Task 10: i18n — remove obsolete keys, add the derived-name hint (en/de/es)
+
+**Files:**
+- Modify: `jarvis/ui/web/frontend/src/i18n/locales/en.json`
+- Modify: `jarvis/ui/web/frontend/src/i18n/locales/de.json`
+- Modify: `jarvis/ui/web/frontend/src/i18n/locales/es.json`
+
+> Per the Output Language Policy, the English value is the source string; de/es are the runtime translations.
+
+- [ ] **Step 1: Remove the obsolete blocks in all three locales**
+
+In each of `en.json`, `de.json`, `es.json`:
+
+(a) Delete the entire `onboarding.persona` block (the object with `title`/`name_label`/`name_placeholder`/`skip` — in `en.json` around line 1329).
+
+(b) Delete the entire `settings_view.assistant_name` block (the object with `title`/`description`/`label`/`current`/`auto_hint`/`save`/`saved`/`restart_required`). Find it with: `git grep -n "assistant_name" -- jarvis/ui/web/frontend/src/i18n`.
+
+> Take care to remove a trailing comma left dangling by the deletion so the JSON stays valid.
+
+- [ ] **Step 2: Add the derived-name hint key in the two wake-word blocks**
+
+In each locale, add a `derived_name` key to BOTH:
+- the `settings_view.wake_word` block (the one with `phrase_label`/`engine_label`), and
+- the `onboarding.wake_word` block (the one with `prefix`/`ack_label`/`references_title`).
+
+Values:
+
+`en.json` — both blocks:
+```json
+"derived_name": "Your assistant will be called: {0}"
+```
+
+`de.json` — both blocks:
+```json
+"derived_name": "Dein Assistent heißt dann: {0}"
+```
+
+`es.json` — both blocks:
+```json
+"derived_name": "Tu asistente se llamará: {0}"
+```
+
+(Add a comma after the preceding key as needed to keep valid JSON.)
+
+- [ ] **Step 3: Validate the JSON and that no obsolete keys remain**
+
+Run:
+```bash
+node -e "for(const l of ['en','de','es']){JSON.parse(require('fs').readFileSync('jarvis/ui/web/frontend/src/i18n/locales/'+l+'.json','utf8'));console.log(l,'valid')}"
+```
+Expected: `en valid`, `de valid`, `es valid`.
+
+Run: `git grep -n "assistant_name\|onboarding\.persona\|\"persona\"" -- jarvis/ui/web/frontend/src/i18n`
+Expected: no hits.
+
+- [ ] **Step 4: Commit (on the maintainer's go)**
+
+```bash
+git add jarvis/ui/web/frontend/src/i18n/locales/
+git commit -m "i18n: drop assistant-name/persona keys, add wake-word derived-name hint (en/de/es)"
+```
+
+---
+
+## Task 11: Full verification
+
+**Files:** none (verification only)
+
+- [ ] **Step 1: Backend — no leftovers and targeted tests green**
+
+Run: `git grep -n "set_assistant_name\|AssistantNameBody\|persona\.name\b" -- jarvis`
+Expected: only safe `getattr(..., "name", ...)` style hits, if any; no write-path or bare-read references.
+
+Run:
+```bash
+pytest tests/unit/brain/test_assistant_name.py tests/unit/brain/test_system_prompt_name.py \
+ tests/unit/core/test_config_writer_persona_strip.py tests/unit/setup/test_onboarding_meta.py -v
+```
+Expected: ALL PASS.
+
+- [ ] **Step 2: Backend — boot import sanity**
+
+Run: `python -c "import jarvis; import jarvis.ui.web.settings_routes; import jarvis.core.config; import jarvis.brain.assistant_name; print('imports ok')"`
+Expected: prints `imports ok`.
+
+- [ ] **Step 3: Lint**
+
+Run: `ruff check jarvis/brain/assistant_name.py jarvis/core/config.py jarvis/core/config_writer.py jarvis/ui/web/settings_routes.py jarvis/setup/onboarding_meta.py`
+Expected: no findings.
+
+- [ ] **Step 4: Frontend — type-check, tests, build**
+
+Run (from `jarvis/ui/web/frontend/`):
+```bash
+npx tsc -b
+npm run test
+npm run build
+```
+Expected: `tsc` clean; all vitest tests pass; build succeeds.
+
+- [ ] **Step 5: Onboarding cross-layer parity (backend ↔ frontend)**
+
+Run: `pytest tests/unit/setup/test_onboarding_meta.py -v` and (from the frontend) `npm run test -- OnboardingFlow`
+Expected: both green — `ONBOARDING_STEPS` (8 steps, no `persona-theme`) matches the frontend `STEP_KEYS`.
+
+- [ ] **Step 6: Manual smoke (maintainer, live app)**
+
+After a `POST /api/settings/restart-app`:
+1. Settings → the "Assistant Name" panel is gone; the Wake-Word panel shows "Your assistant will be called: X" live as the phrase is edited.
+2. Set the wake word to "Hey Ruben"; confirm the Sidebar header / chat byline read "Ruben" after the change propagates.
+3. Replay onboarding via `?onboarding=force`; confirm there is no separate name step and the wake-word step shows the derived-name preview.
+
+---
+
+## Done criteria
+
+- The assistant name is resolved only from the wake phrase; a legacy `[persona].name` is ignored and stripped on the next wake-word save.
+- No assistant-name write endpoint, Settings panel, onboarding step, config field, or writer remains; `GET /api/settings/assistant-name` is read-only and still feeds the bylines.
+- The wake-word surfaces (Settings + onboarding) show the derived name live, localized in en/de/es.
+- All targeted backend tests, the frontend test suite, `tsc`, `ruff`, and `npm run build` are green; onboarding step parity holds at 8 steps.
diff --git a/docs/superpowers/plans/2026-06-23-language-selection-consistency.md b/docs/superpowers/plans/2026-06-23-language-selection-consistency.md
new file mode 100644
index 0000000000..82f66a5654
--- /dev/null
+++ b/docs/superpowers/plans/2026-06-23-language-selection-consistency.md
@@ -0,0 +1,592 @@
+# Language-Selection Consistency Implementation Plan
+
+> **For agentic workers:** REQUIRED SUB-SKILL: Use superpowers:subagent-driven-development (recommended) or superpowers:executing-plans to implement this plan task-by-task. Steps use checkbox (`- [ ]`) syntax for tracking.
+
+**Goal:** Make every user-facing output layer (text reply, spoken answer, announcements, mission readbacks, TTS voice) agree on ONE per-turn language so a German turn is never spoken in English, never half-German/half-English, and never spoken with a foreign-accented voice.
+
+**Architecture:** The codebase already has a single authoritative resolver — `jarvis/core/turn_language.py::resolve_output_language(...)` — but a set of *resolver-blind* layers bypass it (they hardcode `"de"`, default to `"de"`, run their own `de`/`en`-only detector, or pass `language_code=None` to TTS). The fix routes those layers through the same resolver / the same threaded `conversation_language`, consolidates the duplicated BCP-47 mapping, and couples the TTS *voice* (not just the pronunciation pin) to the resolved language so the active Cartesia provider never falls back to its English voice on German text.
+
+**Tech Stack:** Python 3.11, asyncio, `pytest` (asyncio_mode=auto), `ruff`, the EventBus (`jarvis/core/events.py`), Cartesia TTS (`sonic-3.5`), Groq Whisper STT.
+
+---
+
+## Background — why this is happening (read before touching code)
+
+This is not one bug; it is a **family** of bugs around a sound central design that several layers quietly evade. Three independent forensic root causes, confirmed against the current tree by two read-only research agents on 2026-06-23:
+
+1. **The announcement choke point (the screenshot bug).** The user spoke German; the text answer rendered German; the *spoken* output (tagged "ANNOUNCEMENT") came out fully English. Root cause: `jarvis/speech/pipeline.py::_on_announcement` reads `event.language` **verbatim** (`pipeline.py:2442` → `ann_lang = (event.language or "de").lower()`) and never consults `resolve_output_language`, the live `brain.reply_language` pin, or the sticky `conversation_language`. Every emitter that publishes an `AnnouncementRequested` with the wrong (or no) language is therefore spoken in that wrong language. Several emitters either hardcode `"de"`, omit the field (default `"de"` at `jarvis/core/events.py:403`), or — worse for the screenshot — let an *English-composed* brain turn (a scheduled "morning briefing" skill) flow straight to TTS because the emitter never passed the conversation language down to the brain call that wrote the text.
+
+2. **The British accent.** The active TTS provider is **Cartesia** (`jarvis.toml:111`), `language_code = "auto"` (`jarvis.toml:127`). Cartesia's `_resolve_voice` (`jarvis/plugins/tts/cartesia_tts.py:112-139`) picks a per-language native voice from `language_code` — but its final fallback, when the language is `auto`/unknown and the cheap text sniff fails, is the **English voice "Daniel"** (`voice_id` / `voice_id_en`, `jarvis.toml:183/185`) speaking German → an English-accented German. The top-level `[tts] voice_de/voice_en/voice_auto_switch` keys are **dead code** for Cartesia (the factory reads only `voice_de`, and Cartesia reads its own `[tts.cartesia]` block). So the only thing standing between a German turn and an English voice is whether a correct `de-DE` `language_code` actually reaches `synthesize()` on *every* path — and several paths pass `None`/`"de-DE"`-hardcoded/`auto`.
+
+3. **The mid-answer flip.** Generative multilingual TTS (Cartesia, and Gemini in the fallback chain) auto-switches pronunciation **per word** when `language_code` is empty — a German sentence ending on an English loanword ("…Boss.") code-switches its tail. Secondary contributor: if a user ever sets `[stt].language` away from `auto`, Groq/Whisper transcribes cross-language audio into the *wrong-language text*, which the text-first resolver cannot recover. Current live config has `[stt].language` unset → `auto` (safe), so the primary live cause is the unpinned `language_code` on resolver-blind paths.
+
+**Live config facts (verified 2026-06-23, `jarvis.toml`):**
+- `[tts] provider = "cartesia"`, `language_code = "auto"`, `voice_auto_switch = true` (the latter is never read by any plugin).
+- `[tts.cartesia]` generic fallback `voice_id` = Daniel (EN); `voice_id_de` = Sebastian; `voice_id_es` = Pedro; `language = "auto"`.
+- `[brain] reply_language = "auto"` → **no pin**. This is the amplifier: with no pin, the *only* thing holding the layers together is conversation-stickiness + per-turn detection — and the resolver-blind layers bypass even that.
+- `[stt] provider = "groq-api"`, no explicit `language` → `auto` (safe).
+- `[ack_brain] enabled = true`, `preamble_enabled = false` → the blue *preamble* bubble is off, but the **spawn-announcement composer is on** (and is `de`/`en`-only).
+
+**Design decision that governs every task:** the user is bilingual and wants `auto` mode to *work* (output language mirrors input language, consistently across all layers). The fix must make `auto` robust — **do not** rely on setting a hard `de` pin (that would force English turns into German, the opposite of what the user wants). Per the binding CLAUDE.md "Runtime Output Language" doctrine, every spoken/written layer resolves through the one resolver and supports `de`/`en`/`es` equally — no `de`/`en`-only tables, no per-layer re-derivation, no per-layer hardcoded default.
+
+**The recurring trap to respect (CLAUDE.md):** this working tree is shared across parallel sessions and many of the prior language fixes were committed-or-not in flux. **Task 0 verifies what is actually in the tree before changing anything.** Stage hunk-isolated (`git add -p`), never `git add` a whole shared-tree file.
+
+---
+
+## File map (what each task touches)
+
+| Concern | File:line | Task |
+|---|---|---|
+| Announcement passthrough (choke point) | `jarvis/speech/pipeline.py:2442`, `:2486-2490` | T1 |
+| Announcement event default language | `jarvis/core/events.py:403` | T1 |
+| BCP-47 map duplication (4 sites, `:3379` missing `es`) | `jarvis/speech/pipeline.py:2488,3379,5916,6949` | T2 |
+| Cartesia English-voice fallback | `jarvis/plugins/tts/cartesia_tts.py:112-139` | T2 |
+| Hardcoded `language_code="de-DE"` background readback | `jarvis/speech/pipeline.py:2790` | T3 |
+| OpenClaw background-completed readback | `jarvis/speech/pipeline.py:2728,2755` | T3 |
+| Cron-skill announcement (omits language) | `jarvis/speech/pipeline.py:2283-2288` | T3 |
+| Tasks-runner agent-result announcement (omits language) | `jarvis/tasks/runner.py:398-404`, `:293` | T3 |
+| CU progress "Schritt X von Y" hardcoded German | `jarvis/harness/screenshot_only_loop.py:4202-4208` | T3 |
+| CU elevation phrase drops the pin | `jarvis/harness/screenshot_only_loop.py:828` | T3 |
+| MissionAnnouncer `de`/`en`-only, frozen dispatch lang | `jarvis/missions/voice/announcer.py:54,91,174,262`; `jarvis/missions/.../spawn_worker.py:443-465` | T4 |
+| `_spawn_ack_language` forbidden `_looks_german` shortcut | `jarvis/brain/manager.py:4305-4315` | T4 |
+| `_direct_ack_language` default `"de"` (not `DEFAULT_LOCALE`) | `jarvis/brain/manager.py:1966-1978` | T4 |
+| Browser/telephony static per-session language | `jarvis/browser_voice/session.py:147-149,223`; `jarvis/telephony/session.py:126,438` | T5 |
+| Ack-brain `es` persona gap (spec-gated) | `jarvis/brain/ack_brain/{generator,persona_prompt,spawn_announcement}.py` | T6 |
+| STT `auto` regression guard | `jarvis/plugins/stt/{groq_api,fwhisper}.py` | T6 |
+
+---
+
+## Phase ordering
+
+- **Phase 1 — what the user sees (P0):** T0 (verify), T1 (close the announcement choke point), T2 (kill the English-voice fallback / unify BCP-47), T3 (make the announcement *emitters* carry the turn language).
+- **Phase 2 — doctrine consistency (P1):** T4 (mission readback + the `_looks_german` shortcut + default-locale consistency), T5 (browser/telephony per-turn language).
+- **Phase 3 — hardening (P2):** T6 (`es` ack-brain persona — spec-gated; STT auto guard).
+
+Each task is independently shippable and leaves the tree green.
+
+---
+
+### Task 0: Verify the actual state of prior language fixes (no code change)
+
+Prior fixes (central resolver, `GeminiFlashTTS.language_code` pin, `extract_reply_language_directive`, conversation stickiness) were repeatedly recorded as "UNCOMMITTED, shared tree". Confirm which are actually present so we neither re-do nor clobber them.
+
+**Files:** none (read-only).
+
+- [ ] **Step 1: Confirm the resolver and its `conversation_language` param exist**
+
+Run:
+```bash
+grep -n "def resolve_output_language" jarvis/core/turn_language.py
+grep -n "conversation_language" jarvis/core/turn_language.py jarvis/brain/manager.py jarvis/speech/pipeline.py
+```
+Expected: `resolve_output_language` present with `conversation_language=` kwarg; `BrainManager._conversation_language` + `conversation_language` property present; `_output_language` reads `brain.conversation_language`. If ANY are missing, STOP — a prior fix was reverted; restore it before continuing (it is a prerequisite for every task below).
+
+- [ ] **Step 2: Confirm the TTS `language_code` pin reached the providers**
+
+Run:
+```bash
+grep -n "language_code" jarvis/plugins/tts/gemini_flash_tts.py jarvis/plugins/tts/cartesia_tts.py
+grep -n "language_code" jarvis/core/protocols.py
+```
+Expected: `TTSProvider.synthesize` in `protocols.py` declares `language_code`; both plugins accept and *use* it (not `_ = language_code`). Note gaps for T2.
+
+- [ ] **Step 3: Record the baseline test state**
+
+Run:
+```bash
+python -m pytest tests/unit/core/test_turn_language.py tests/unit/speech/test_output_language_pin.py tests/unit/speech/test_phrase_language.py tests/unit/plugins/tts/ tests/unit/brain/ -q
+```
+Expected: a known-green baseline (note any *pre-existing* foreign failures — e.g. `test_contacts_integration`, `test_navigation_intent` — so they are not attributed to this work). Write the failing-test list into the PR description.
+
+- [ ] **Step 4: Snapshot the relevant live config** (for reproduction, not commit)
+
+Run:
+```bash
+grep -nE "reply_language|^\[tts\]|provider|language_code|voice_id|^\[stt\]|preamble_enabled" jarvis.toml
+```
+Expected: matches the "Live config facts" above. If `[stt].language` is pinned or `reply_language` is a hard pin, note it — it changes which hypothesis dominates.
+
+---
+
+### Task 1: Route `_on_announcement` through the resolver (close the choke point)
+
+The single structural fix with the highest leverage: the spoken-announcement handler must resolve the announcement's language through the same `_output_language` resolver instead of trusting `event.language` verbatim. The event's language becomes a *hint* (like the STT tag), but the live pin and the sticky `conversation_language` win — so a German conversation never gets an English-voiced announcement, regardless of which emitter produced it.
+
+**Files:**
+- Modify: `jarvis/speech/pipeline.py:2442` and `:2486-2490`
+- Modify: `jarvis/core/events.py:403` (default language → resolver-neutral)
+- Test: `tests/unit/speech/test_announcement_language.py` (create)
+
+- [ ] **Step 1: Write the failing test**
+
+```python
+# tests/unit/speech/test_announcement_language.py
+"""_on_announcement must resolve language through the pin/conversation, not
+trust event.language verbatim (forensic 2026-06-23: German chat, English
+'ANNOUNCEMENT' spoken)."""
+import pytest
+
+from jarvis.core.events import AnnouncementRequested
+from tests.fakes.speech import make_pipeline_with_fakes # existing helper pattern
+
+
+async def test_announcement_follows_conversation_language_over_event_tag():
+ pipe, tts = make_pipeline_with_fakes()
+ # German conversation established; reply_language=auto (no pin).
+ pipe._brain.conversation_language = "de"
+ pipe._brain.reply_language = "auto"
+ # An emitter stamped EN (or omitted it) on otherwise-German-conversation.
+ await pipe._on_announcement(
+ AnnouncementRequested(text="Guten Morgen, Chef.", language="en", kind="completion")
+ )
+ # The TTS voice/pronunciation pin must be de-DE, not en-US.
+ assert tts.last_language_code == "de-DE"
+
+
+async def test_announcement_honors_hard_pin_over_event_tag():
+ pipe, tts = make_pipeline_with_fakes()
+ pipe._brain.conversation_language = ""
+ pipe._brain.reply_language = "de" # hard pin
+ await pipe._on_announcement(
+ AnnouncementRequested(text="Done.", language="en", kind="completion")
+ )
+ assert tts.last_language_code == "de-DE"
+
+
+async def test_announcement_auto_mirrors_announcement_text_when_no_conv_no_pin():
+ pipe, tts = make_pipeline_with_fakes()
+ pipe._brain.conversation_language = ""
+ pipe._brain.reply_language = "auto"
+ await pipe._on_announcement(
+ AnnouncementRequested(text="Done, the file is ready.", language=None, kind="completion")
+ )
+ assert tts.last_language_code == "en-US"
+```
+
+If `make_pipeline_with_fakes` / `tts.last_language_code` do not exist yet, add a minimal fake TTS that records `language_code` and a pipeline builder, following the pattern already used in `tests/unit/speech/test_output_language_pin.py` (read it first and mirror its fixtures).
+
+- [ ] **Step 2: Run it to verify it fails**
+
+Run: `python -m pytest tests/unit/speech/test_announcement_language.py -v`
+Expected: FAIL — current code maps `en` → `en-US` from the verbatim `event.language`.
+
+- [ ] **Step 3: Implement — resolve, don't trust**
+
+In `jarvis/speech/pipeline.py`, change line 2442 from:
+```python
+ ann_lang = (event.language or "de").lower()
+```
+to:
+```python
+ # Resolve the announcement's language through the ONE authoritative
+ # resolver — the live brain.reply_language pin and the sticky
+ # conversation_language must win over whatever an emitter stamped on the
+ # event (forensic 2026-06-23: a German chat spoke an English
+ # 'ANNOUNCEMENT' because event.language was trusted verbatim). The
+ # event tag is only a hint, passed where the STT tag normally goes.
+ ann_lang = self._output_language(event.language, event.text or "")
+```
+Then change the TTS pin block at `:2486-2490` to reuse `ann_lang` (which is now always a clean `de`/`en`/`es` code) instead of re-deriving from `event.language`:
+```python
+ lang_code = self._bcp47(ann_lang) # helper added in Task 2
+```
+(Until Task 2 lands, inline the existing map: `lang_code = {"de": "de-DE", "en": "en-US", "es": "es-ES"}.get(ann_lang)`.)
+
+Also pass the resolved `ann_lang` (not `event.language`) into `_emit_spoken` at `:2467-2472` so the transcript records the language actually spoken:
+```python
+ self._emit_spoken(
+ scrubbed.cleaned,
+ ann_lang,
+ _announcement_spoken_kind(getattr(event, "kind", None)),
+ getattr(event, "detail", None),
+ )
+```
+
+- [ ] **Step 4: Make the event default resolver-neutral**
+
+In `jarvis/core/events.py:403`, change the `AnnouncementRequested.language` default from `"de"` to `None`. With T1 Step 3, `_on_announcement` now resolves a `None` language to the conversation/pin/detected language instead of silently forcing German. Read the dataclass first; if other consumers rely on the non-None default, keep the field `Optional[str] = None` and confirm `_on_announcement` is the only spoken consumer (the research map says it is).
+
+- [ ] **Step 5: Run the tests to verify they pass**
+
+Run: `python -m pytest tests/unit/speech/test_announcement_language.py tests/unit/speech/test_output_language_pin.py -v`
+Expected: PASS (all three new + the existing pin tests still green).
+
+- [ ] **Step 6: Commit**
+
+```bash
+git add -p jarvis/speech/pipeline.py jarvis/core/events.py tests/unit/speech/test_announcement_language.py
+git commit -m "fix(voice): resolve announcement language through the pin/conversation, not event.language verbatim"
+```
+
+---
+
+### Task 2: One BCP-47 map + kill Cartesia's English-voice fallback (the British accent)
+
+Two coupled changes: (a) DRY the four copies of the `{"de":"de-DE",...}` map into one helper that always covers `es` (the `:3379` prerender copy is missing `es`), so no path can ever pass a stale/None pin; (b) make Cartesia's voice fallback follow the resolved language / conversation language instead of silently defaulting to the English voice on German text.
+
+**Files:**
+- Modify: `jarvis/speech/pipeline.py` (add `_bcp47` helper; replace the 4 inline maps at `:2488`, `:3379`, `:5916`, `:6949`)
+- Modify: `jarvis/plugins/tts/cartesia_tts.py:112-139`
+- Test: `tests/unit/speech/test_bcp47_map.py` (create), extend `tests/unit/plugins/tts/test_cartesia_tts.py`
+
+- [ ] **Step 1: Write the failing test for the helper**
+
+```python
+# tests/unit/speech/test_bcp47_map.py
+from jarvis.speech.pipeline import SpeechPipeline
+
+
+def test_bcp47_covers_all_three_locales():
+ assert SpeechPipeline._bcp47("de") == "de-DE"
+ assert SpeechPipeline._bcp47("en") == "en-US"
+ assert SpeechPipeline._bcp47("es") == "es-ES" # the :3379 copy dropped this
+
+
+def test_bcp47_unknown_returns_none():
+ assert SpeechPipeline._bcp47("xx") is None
+ assert SpeechPipeline._bcp47(None) is None
+ assert SpeechPipeline._bcp47("") is None
+```
+
+- [ ] **Step 2: Run it to verify it fails**
+
+Run: `python -m pytest tests/unit/speech/test_bcp47_map.py -v`
+Expected: FAIL — `_bcp47` does not exist.
+
+- [ ] **Step 3: Add the helper and replace the four inline maps**
+
+Add to `SpeechPipeline` (near `_output_language`):
+```python
+ _BCP47 = {"de": "de-DE", "en": "en-US", "es": "es-ES"}
+
+ @classmethod
+ def _bcp47(cls, lang: object) -> str | None:
+ """Map a de/en/es turn-language code to a TTS BCP-47 locale, else None.
+
+ Single source for the whole pipeline — replaces four hand-copied maps,
+ one of which (the task-ack prerender) had silently dropped ``es``.
+ """
+ return cls._BCP47.get(str(lang or "").lower())
+```
+Replace the inline `{"de": "de-DE", "en": "en-US", "es": "es-ES"}.get(...)` (and the `de`/`en`-only copy at `:3379`) at all four sites with `self._bcp47(<lang_code>)`. Read each site first to pass the right variable (`ann_lang` at `:2488`, the prerender lang at `:3379`, `lang` at `:5916`, `language` at `:6949`).
+
+- [ ] **Step 4: Write the failing Cartesia test**
+
+```python
+# add to tests/unit/plugins/tts/test_cartesia_tts.py
+def test_cartesia_unknown_language_does_not_fall_back_to_english_voice():
+ """A German segment with an unresolved language_code must not be spoken by
+ the English voice (the British-accent symptom). The conversation default
+ drives the fallback instead of a hardcoded EN voice."""
+ tts = _make_cartesia(default_locale="de") # see Step 5 for the new param
+ # language_code unpinned, text that the cheap sniff cannot classify:
+ voice = tts._resolve_voice("Charon.", voice_override=None, language_code="auto")
+ assert voice == tts._voice_by_lang["de"] # Sebastian, not Daniel
+```
+
+- [ ] **Step 5: Run it to verify it fails**
+
+Run: `python -m pytest tests/unit/plugins/tts/test_cartesia_tts.py -k english_voice -v`
+Expected: FAIL — current fallback returns `_voice_by_lang["en"]` (Daniel).
+
+- [ ] **Step 6: Implement the Cartesia fallback fix**
+
+In `jarvis/plugins/tts/cartesia_tts.py`, give the provider a `default_locale` (wired from the resolver's `DEFAULT_LOCALE` / the pipeline's conversation language — passed via the factory) and change the final fallback in `_resolve_voice` (`:138`) from:
+```python
+ # Default English voice keeps the previous single-voice behaviour.
+ return self._voice_by_lang.get("en", self._voice_id)
+```
+to:
+```python
+ # Never silently default to the English voice on un-sniffable text — that
+ # is the British-accent-on-German symptom. Fall back to the configured
+ # default locale's native voice (the conversation/turn language), only
+ # then to the generic voice_id.
+ return self._voice_by_lang.get(self._default_locale, self._voice_id)
+```
+Wire `default_locale` in the factory (`jarvis/plugins/tts/__init__.py`) from `DEFAULT_LOCALE` (import from `turn_language`) — or, better, ensure the pipeline always passes a concrete `language_code` so the fallback is never reached (defense in depth; both are cheap).
+
+**Important non-break note:** the larger root cause is that `language_code` must always arrive resolved. After T1+T2, `_on_announcement`, `_speak`, and `_brain_streaming` all pass a concrete `de-DE`/`en-US`/`es-ES`. The Cartesia fallback then only matters for any path that still passes `auto`/`None` — make it safe rather than English-biased.
+
+- [ ] **Step 7: Run the tests**
+
+Run: `python -m pytest tests/unit/speech/test_bcp47_map.py tests/unit/plugins/tts/test_cartesia_tts.py -v`
+Expected: PASS.
+
+- [ ] **Step 8: Commit**
+
+```bash
+git add -p jarvis/speech/pipeline.py jarvis/plugins/tts/cartesia_tts.py jarvis/plugins/tts/__init__.py tests/unit/speech/test_bcp47_map.py tests/unit/plugins/tts/test_cartesia_tts.py
+git commit -m "fix(tts): one BCP-47 map (incl. es) + Cartesia stops defaulting to the English voice on German text"
+```
+
+---
+
+### Task 3: Make announcement *emitters* carry the turn language (fix the text, not just the voice)
+
+T1 makes the *voice* consistent; this task fixes the *text* — the screenshot's announcement was English because the emitting brain turn (a scheduled skill) ran with no language directive. Every emitter that produces spoken text must pass the current `conversation_language` down to the brain call/composer and onto the event, instead of hardcoding/omitting `"de"`.
+
+**Files:**
+- Modify: `jarvis/speech/pipeline.py:2790` (hardcoded `de-DE`), `:2728,2755` (OpenClaw-bg), `:2283-2288` (cron-skill)
+- Modify: `jarvis/tasks/runner.py:398-404,293`
+- Modify: `jarvis/harness/screenshot_only_loop.py:4202-4208,828`
+- Test: extend `tests/unit/speech/test_announcement_language.py`; add `tests/unit/tasks/test_runner_announcement_language.py`
+
+- [ ] **Step 1: Write failing tests for the emitters**
+
+```python
+# tests/unit/tasks/test_runner_announcement_language.py
+"""A scheduled/agent task that announces its result must stamp the active
+conversation language on the AnnouncementRequested, and must drive the brain
+turn that writes the text with that language directive (forensic 2026-06-23:
+'Good morning, Chef...' spoken in English inside a German chat)."""
+import pytest
+
+from jarvis.core.events import AnnouncementRequested
+
+
+async def test_agent_result_announcement_carries_conversation_language(fake_bus, fake_brain):
+ fake_brain.conversation_language = "de"
+ runner = _make_tasks_runner(bus=fake_bus, brain=fake_brain)
+ await runner._announce_agent_result("Result text")
+ ann = fake_bus.last_event(AnnouncementRequested)
+ assert ann.language == "de"
+```
+
+For the pipeline-side hardcodes, add to `test_announcement_language.py` a test that the background sub-agent readback (`:2790`) and the OpenClaw background-completed readback (`:2728`) stamp the conversation language rather than a fixed `"de"`.
+
+- [ ] **Step 2: Run to verify they fail**
+
+Run: `python -m pytest tests/unit/tasks/test_runner_announcement_language.py -v`
+Expected: FAIL — emitter omits `language` / hardcodes `"de"`.
+
+- [ ] **Step 3: Implement — thread the conversation language to each emitter**
+
+Resolve once at each emitter from the brain's sticky state, e.g.:
+```python
+ lang = self._conversation_language_for_announcement() # see helper below
+ bus.publish(AnnouncementRequested(text=..., language=lang, kind=...))
+```
+Add a tiny pipeline helper (DRY) that mirrors `_output_language` but for the no-utterance announcement case:
+```python
+ def _conversation_language_for_announcement(self) -> str:
+ brain = getattr(self, "_brain", None)
+ pin = getattr(brain, "reply_language", None)
+ conv = getattr(brain, "conversation_language", "")
+ # pin wins; else the established conversation language; else default.
+ return resolve_output_language(pin, None, "", conversation_language=conv)
+```
+Apply at:
+- `pipeline.py:2790` — replace `language_code="de-DE"` with `self._bcp47(lang)` and `_emit_spoken(..., lang, ...)`.
+- `pipeline.py:2728,2755` — replace `language="de"` + the German literals: keep German literals only when `lang == "de"`, otherwise pick the matching localized literal from a small `de`/`en`/`es` table (mirror `action_phrases.py`).
+- `pipeline.py:2283-2288` (cron) and `tasks/runner.py:398-404` — add `language=lang`.
+- `tasks/runner.py:293` — replace `or "de"` with `or self._conversation_language_for_announcement()` (or the runner's brain handle equivalent).
+
+For the brain turn that *writes* the scheduled text (`pipeline.py:2276` synthetic prompt): pass the resolved language into the brain request's reply-language directive so the model writes in `lang`, not English. Read how `_reply_language_directive` is built in `manager.py:2329` and feed the same directive into the scheduled-run request path.
+
+- [ ] **Step 4: CU progress / elevation phrases**
+
+In `jarvis/harness/screenshot_only_loop.py`:
+- `:4202-4208` — replace the hardcoded German "Schritt X von Y erledigt." + `language="de"` with a `de`/`en`/`es` phrase table keyed by the resolved language (the harness already has the turn language in its context — `computer_use_context`; thread it in if not present).
+- `:828` — replace `resolve_phrase_language(None, task_prompt)` with a call that passes the live `reply_language` pin (so the pin is honored), mirroring `_ctx_output_language` in `computer_use_tool`.
+
+- [ ] **Step 5: Run the tests**
+
+Run: `python -m pytest tests/unit/tasks/test_runner_announcement_language.py tests/unit/speech/test_announcement_language.py -v`
+Expected: PASS.
+
+- [ ] **Step 6: Commit**
+
+```bash
+git add -p jarvis/speech/pipeline.py jarvis/tasks/runner.py jarvis/harness/screenshot_only_loop.py tests/unit/tasks/test_runner_announcement_language.py tests/unit/speech/test_announcement_language.py
+git commit -m "fix(voice): announcement emitters carry the conversation language to text + event + TTS"
+```
+
+---
+
+### Task 4: Mission readback + the `_looks_german` shortcut + default-locale consistency
+
+`MissionAnnouncer` is `de`/`en`-only and reads a *frozen* dispatch-time language; `_spawn_ack_language` uses the doctrine-forbidden `de if _looks_german(...) else en` binary (drops `es`); `_direct_ack_language` defaults to `"de"` instead of `DEFAULT_LOCALE`.
+
+**Files:**
+- Modify: `jarvis/missions/voice/announcer.py:54,91,174,262`; `jarvis/missions/.../spawn_worker.py:443-465`
+- Modify: `jarvis/brain/manager.py:4305-4315` (`_spawn_ack_language`), `:1966-1978` (`_direct_ack_language`)
+- Test: `tests/unit/brain/test_spawn_ack_language.py` (extend), `tests/unit/missions/test_announcer_language.py` (create)
+
+- [ ] **Step 1: Write failing tests**
+
+```python
+# tests/unit/brain/test_spawn_ack_language.py (extend)
+def test_spawn_ack_language_honors_es_pin(manager):
+ manager.set_reply_language("es")
+ assert manager._spawn_ack_language("cualquier texto") == "es"
+
+def test_spawn_ack_language_uses_conversation_not_looks_german(manager):
+ manager.set_reply_language("auto")
+ manager._conversation_language = "es"
+ # a thin/ambiguous utterance must inherit es, not collapse to de/en
+ assert manager._spawn_ack_language("ok") == "es"
+```
+```python
+# tests/unit/missions/test_announcer_language.py
+def test_mission_readback_supports_es():
+ ann = _make_announcer(language_default="en")
+ line = ann.summary_line(status="approved", language="es")
+ assert _is_spanish(line) # not a German/English fallback
+```
+
+- [ ] **Step 2: Run to verify they fail**
+
+Run: `python -m pytest tests/unit/brain/test_spawn_ack_language.py tests/unit/missions/test_announcer_language.py -v`
+Expected: FAIL — `_looks_german` collapses `es`; `_Lang = Literal["de","en"]`.
+
+- [ ] **Step 3: Replace `_spawn_ack_language` with the resolver**
+
+In `manager.py:4305-4315`, replace the binary shortcut:
+```python
+ return "de" if _looks_german(user_text) else "en"
+```
+with a resolver call that honors pin + stickiness:
+```python
+ return resolve_output_language(
+ self.reply_language, "unknown", user_text,
+ conversation_language=self._conversation_language,
+ )
+```
+In `_direct_ack_language` (`:1978`), change the local `default="de"` to `default=DEFAULT_LOCALE` and prefer `resolve_output_language` (with `conversation_language`) over `resolve_turn_language` so stickiness applies there too. Import `DEFAULT_LOCALE` from `turn_language`.
+
+- [ ] **Step 4: Extend MissionAnnouncer to de/en/es + live language**
+
+In `jarvis/missions/voice/announcer.py`: widen `_Lang = Literal["de","en"]` → `Literal["de","en","es"]`; add the `es` phrase variants for each summary line; and change `:262` so the readback prefers the **current** conversation language (passed in at readback time from the brain) and only falls back to the frozen `MissionDispatched.language` when no live language is available. Widen `spawn_worker.py:465` `mission_language = turn_language if turn_language in ("de","en") else "de"` to include `"es"`.
+
+- [ ] **Step 5: Run the tests**
+
+Run: `python -m pytest tests/unit/brain/test_spawn_ack_language.py tests/unit/missions/test_announcer_language.py tests/unit/brain/ -q`
+Expected: PASS (and no regression in the brain suite beyond the known foreign failures from T0).
+
+- [ ] **Step 6: Commit**
+
+```bash
+git add -p jarvis/brain/manager.py jarvis/missions/voice/announcer.py jarvis/missions/*/spawn_worker.py tests/unit/brain/test_spawn_ack_language.py tests/unit/missions/test_announcer_language.py
+git commit -m "fix(missions): mission readback + spawn-ack resolve de/en/es via the central resolver (drop _looks_german)"
+```
+
+---
+
+### Task 5: Per-turn language in the browser-voice and telephony sessions
+
+`browser_voice/session.py` and `telephony/session.py` set a **static** `self.language_code` once per session (default `de-DE`) and never re-resolve per turn — so a session that starts German stays German even when the user switches, and vice versa. This is the headless/VPS voice path (first-class per CLOUD.md), so it must honor the resolver too.
+
+**Files:**
+- Modify: `jarvis/browser_voice/session.py:147-149,223,86`
+- Modify: `jarvis/telephony/session.py:126,438`
+- Test: `tests/unit/browser_voice/test_session_language.py` (create)
+
+- [ ] **Step 1: Write the failing test**
+
+```python
+# tests/unit/browser_voice/test_session_language.py
+async def test_browser_session_reresolves_language_per_turn(fake_brain):
+ fake_brain.reply_language = "auto"
+ sess = _make_browser_session(brain=fake_brain, default="de-DE")
+ out = await sess._language_code_for_turn(transcript_lang="en", text="What's the weather?")
+ assert out == "en-US" # not the static de-DE session default
+```
+
+- [ ] **Step 2: Run to verify it fails**
+
+Run: `python -m pytest tests/unit/browser_voice/test_session_language.py -v`
+Expected: FAIL — no per-turn resolution method; `self.language_code` is static.
+
+- [ ] **Step 3: Implement per-turn resolution**
+
+Add a `_language_code_for_turn(transcript_lang, text)` that calls `resolve_output_language(brain.reply_language, transcript_lang, text, conversation_language=brain.conversation_language)` and maps to BCP-47 via the shared helper, and use it at `session.py:223` (and the telephony equivalent at `:438`) instead of `self.language_code`. Keep the `audio_start` control-frame value only as the *seed*/hint, not the per-turn truth.
+
+- [ ] **Step 4: Run the test**
+
+Run: `python -m pytest tests/unit/browser_voice/test_session_language.py -v`
+Expected: PASS.
+
+- [ ] **Step 5: Commit**
+
+```bash
+git add -p jarvis/browser_voice/session.py jarvis/telephony/session.py tests/unit/browser_voice/test_session_language.py
+git commit -m "fix(channels): browser-voice + telephony resolve language per turn, not once per session"
+```
+
+---
+
+### Task 6: Ack-brain `es` persona (spec-gated) + STT `auto` regression guard
+
+Two hardening items. The ack-brain `es` persona is **spec-gated** — `PERSONA_PROMPT_DE/EN` and the spawn persona are locked to `docs/superpowers/specs/2026-05-11-pre-thinking-ack-flash-brain-design.md` (the docstrings forbid a silent rewrite). So this task **amends the spec first**, then adds the constant. The STT guard locks in the safe `auto` default.
+
+**Files:**
+- Modify: `docs/superpowers/specs/2026-05-11-pre-thinking-ack-flash-brain-design.md` (add the `es` persona section)
+- Modify: `jarvis/brain/ack_brain/persona_prompt.py:158-175`, `jarvis/brain/ack_brain/generator.py:96-110`, `jarvis/brain/ack_brain/spawn_announcement.py:176,181`
+- Modify: `jarvis/plugins/stt/groq_api.py`, `jarvis/plugins/stt/fwhisper.py` (guard only)
+- Test: extend `tests/unit/brain/test_ack_brain/`, `tests/unit/speech/test_stt_language_autodetect.py`
+
+- [ ] **Step 1: Amend the flash-brain spec** to define `PERSONA_PROMPT_ES` and the `es` spawn persona (a short section mirroring the DE/EN persona contract). Without this the constant change is a doctrine violation. Get maintainer sign-off on the Spanish persona wording before coding (it is the only step in this whole plan that genuinely needs human input — the persona voice is a product decision).
+
+- [ ] **Step 2: Write failing tests** that `get_persona_prompt("es")` returns a Spanish persona (not the German fallback) and `_detect_language` recognizes Spanish.
+
+- [ ] **Step 3: Run to verify they fail.** Run: `python -m pytest tests/unit/brain/test_ack_brain/ -k es -v`. Expected: FAIL.
+
+- [ ] **Step 4: Add `PERSONA_PROMPT_ES`**, widen `_normalise_language`/`_detect_language`/`_PERSONA_LANGS` to include `es`, per the amended spec.
+
+- [ ] **Step 5: STT auto guard** — add a regression test asserting `build_stt_from_config` maps `language == "auto"` → `None` (no forced language) for both Groq and faster-whisper, so a future edit cannot silently reintroduce the echo bug. The mapping already exists (`pipeline.py:7127`, `build_stt_from_config:45-46`); this only locks it.
+
+- [ ] **Step 6: Run the tests.** Run: `python -m pytest tests/unit/brain/test_ack_brain/ tests/unit/speech/test_stt_language_autodetect.py -v`. Expected: PASS.
+
+- [ ] **Step 7: Commit**
+
+```bash
+git add -p docs/superpowers/specs/2026-05-11-pre-thinking-ack-flash-brain-design.md jarvis/brain/ack_brain/ jarvis/plugins/stt/ tests/
+git commit -m "feat(ack-brain): es persona (spec-amended) + STT auto-language regression guard"
+```
+
+---
+
+## Cross-cutting verification (run after each phase, mandatory before any restart/ship)
+
+- [ ] **Full targeted suite:**
+```bash
+python -m pytest tests/unit/core/test_turn_language.py tests/unit/speech/ tests/unit/plugins/tts/ tests/unit/brain/ tests/unit/missions/ tests/unit/tasks/ -q
+```
+Expected: green except the *known* pre-existing foreign failures recorded in T0 Step 3.
+
+- [ ] **Lint the touched lines only:** `ruff check jarvis/speech/pipeline.py jarvis/plugins/tts/cartesia_tts.py jarvis/brain/manager.py jarvis/missions/voice/announcer.py jarvis/tasks/runner.py jarvis/harness/screenshot_only_loop.py jarvis/browser_voice/session.py` — 0 new findings (pre-existing S110/UP037 noise is foreign).
+
+- [ ] **Deploy:** none of these touch entry points → **no `pip install -e .`**. They are loaded via the editable install but need an app restart to take effect: `POST /api/settings/restart-app` (force=false, only when no mission is running). NOT `Stop-Process`.
+
+- [ ] **Live mic verification (the real proof):** with `reply_language = "auto"`, run four turns and confirm voice + text + announcement all match:
+ 1. German turn → German text, German announcement, German voice (Sebastian, no British accent).
+ 2. English turn ("What's on my calendar?") → English everywhere.
+ 3. German turn ending on a loanword ("…und dann der Boss.") → no English tail.
+ 4. A scheduled/skill announcement while the conversation is German → German announcement (the screenshot scenario).
+
+---
+
+## Risk register ("damit nichts kaputtgeht")
+
+| Risk | Mitigation |
+|---|---|
+| A prior fix was reverted in the shared tree and a task re-introduces a half-state | T0 verifies presence of the resolver, the `language_code` pin, and the directive extractor BEFORE any change |
+| Forcing `conversation_language` voice onto a genuinely other-language announcement text (German voice reads English text) | T1 resolves from `event.text` too (auto path mirrors the text); T3 fixes the *text* upstream so text+voice agree. The mismatch only occurs transiently if an emitter is fixed in T1 but not yet T3 — ship T1→T3 together within Phase 1 |
+| Changing `events.py:403` default breaks a non-spoken consumer | Confirm in T1 Step 4 that `_on_announcement` is the only *spoken* consumer (the research map says so); keep the field `Optional[str] = None` |
+| Cartesia `default_locale` wired wrong → wrong voice for an English user | Default it to `DEFAULT_LOCALE` and prefer always passing a concrete `language_code` (defense in depth); the fallback is only reached when the pipeline failed to resolve |
+| `es` persona constant change boot-fails an `extra="forbid"` ack config | T6 is spec-gated and additive; the new constant has a default, no new required config key |
+| Shared-tree commit sweeps another session's work | Every commit uses `git add -p` / explicit pathspec, never `git add .` or a whole foreign-dirty file |
+
+---
+
+## Self-review notes
+
+- **Spec coverage:** screenshot bug (announcement EN / text DE) → T1+T3; British accent → T2; mid-answer flip → T2 (always-pinned `language_code`) + T6 (STT guard); `es` equality / doctrine → T2/T3/T4/T6; browser+telephony → T5. All three user-reported symptoms map to a task.
+- **Type consistency:** `_bcp47` (T2) is referenced by T1/T3/T5; `resolve_output_language(pin, stt, text, conversation_language=...)` signature is used identically everywhere; `_conversation_language_for_announcement` (T3) reused by every emitter.
+- **Known soft spots requiring a read-first:** the exact fake/fixture names in the speech tests (`make_pipeline_with_fakes`, `tts.last_language_code`) must be confirmed against `tests/unit/speech/test_output_language_pin.py` before writing — mirror what exists rather than inventing helpers.
diff --git a/docs/superpowers/specs/2026-06-20-assistant-name-coupled-to-wake-word-design.md b/docs/superpowers/specs/2026-06-20-assistant-name-coupled-to-wake-word-design.md
new file mode 100644
index 0000000000..b623cc4041
--- /dev/null
+++ b/docs/superpowers/specs/2026-06-20-assistant-name-coupled-to-wake-word-design.md
@@ -0,0 +1,184 @@
+# Couple the Assistant Name to the Wake Word
+
+**Date:** 2026-06-20
+**Status:** Approved design, pending implementation plan
+**Author:** brainstorming session
+
+## Problem
+
+The assistant currently has two independent identity controls:
+
+- `[trigger.wake_word].phrase` — the spoken trigger ("Hey Jarvis").
+- `[persona].name` — an explicit, separate override for how the assistant refers
+ to itself ("Friday"), surfaced as the "Assistant Name" Settings panel and a
+ dedicated onboarding step.
+
+These were deliberately decoupled on 2026-06-19 so a user could wake "Hey
+Computer" while the assistant called itself "Friday". The maintainer has decided
+to reverse that: the assistant name should be **derived solely from the wake
+word**, with no separate name control anywhere. "Hey Ruben" → the assistant is
+called "Ruben". Setting the wake word is the single act that names the assistant.
+
+## Goal
+
+Remove the separate assistant-name override entirely (UI, onboarding, REST write
+path, and config field) and make the assistant name a pure function of the wake
+phrase. Surface the coupling in the UI so the derived name is visible while the
+user sets the wake word.
+
+## Current architecture (what is coupled to what)
+
+Everything that needs the assistant's name reads the single resolver
+`resolve_assistant_name(config)` in `jarvis/brain/assistant_name.py`. Today it
+resolves in three stages (first non-empty wins):
+
+1. `[persona].name` explicit override.
+2. Wake phrase with its trigger prefix stripped (`phrase_core`), title-cased.
+3. `DEFAULT_ASSISTANT_NAME` ("Assistant") fallback.
+
+Consumers (all unchanged by this work — they keep reading the resolver):
+
+- `jarvis/brain/manager.py::_build_system_prompt` (~L1752) injects a name
+ override directive into the system prompt when the resolved name ≠ "Assistant".
+- `jarvis/brain/agent_instructions.py::instructions_filename` names the
+ per-user instructions file `<Name>.md` and auto-migrates it on rename.
+- Frontend bylines: `useAssistantNameSeed` seeds the resolved name into the
+ event store; the Sidebar header, `RunTurnCard`, `TurnCard`,
+ `FrontierSwitchModal`, and i18n interpolation all read it from the store.
+
+Override entry points to be removed:
+
+- Config field: `PersonaConfig.name` (`jarvis/core/config.py` ~L103).
+- Writer: `config_writer.set_assistant_name()` (~L190).
+- REST: `PUT`/`DELETE /api/settings/assistant-name`
+ (`jarvis/ui/web/settings_routes.py` ~L639); `GET` is kept read-only.
+- Settings UI: `AssistantNamePanel` in
+ `frontend/src/views/SettingsView.tsx` (~L306) + the `useAssistantName`
+ (save) hook in `frontend/src/hooks/useAssistantName.ts`.
+- Onboarding: the `persona-theme` step — `PersonaThemeStep.tsx` (+ test) and its
+ key in both `OnboardingFlow.tsx` `REGISTRY`/`STEP_KEYS` and
+ `jarvis/setup/onboarding_meta.py` `ONBOARDING_STEPS`. (Note: despite its name,
+ this step only sets the name; the on-screen theme/overlay is a separate
+ `system-style` step and is untouched.)
+
+## Desired behavior
+
+The single source of the assistant name is the wake phrase. `resolve_assistant_name`
+becomes two stages:
+
+1. Wake phrase with prefix stripped, title-cased ("Hey Ruben" → "Ruben",
+ "micron" → "Micron", "Hey Computer" → "Computer").
+2. `DEFAULT_ASSISTANT_NAME` ("Assistant") when there is no usable wake phrase
+ (pre-onboarding / empty).
+
+There is no way to make the spoken name differ from the wake word. Wake word and
+name are intentionally identical.
+
+## Changes
+
+### Backend (Python)
+
+1. **`jarvis/brain/assistant_name.py`** — Drop stage 1 (the `[persona].name`
+ read). Resolve from the wake phrase, else the fallback. Update the module
+ docstring to describe the two-stage resolution and the removed override.
+
+2. **`jarvis/core/config.py`** — Remove `PersonaConfig.name`. Verify the config
+ model tolerates a now-unknown `[persona] name` key in existing TOML files
+ (Pydantic v2 defaults to `extra="ignore"`; confirm no model on this path sets
+ `extra="forbid"`). If `PersonaConfig` becomes empty and nothing else reads
+ `cfg.persona`, the plan may drop the model and its `JarvisConfig.persona`
+ field; if removal carries boot risk, keep the field as a dead, deprecated,
+ never-read key instead. Decision deferred to the plan after a
+ `grep` for `persona.name` / `.persona\b` readers outside the resolver.
+
+3. **`jarvis/core/config_writer.py`** — Remove `set_assistant_name()`. In
+ `set_wake_word()`, also strip a stale `[persona] name` entry from the TOML so
+ a previously-set override (e.g. the maintainer's current "Josef") does not
+ linger. Keep the existing `_WRITE_LOCK` + tempfile + BOM-safe path (AP-7).
+
+4. **`jarvis/ui/web/settings_routes.py`** — Remove `PUT`/`DELETE
+ /api/settings/assistant-name` and the `AssistantNameBody` model. Keep `GET
+ /api/settings/assistant-name` but return only `resolved` (and `default`); drop
+ the `name`/explicit field from the response. The frontend's
+ `useAssistantNameSeed` keeps using this endpoint to seed the byline name.
+
+5. **`jarvis/setup/onboarding_meta.py`** — Remove `"persona-theme"` from
+ `ONBOARDING_STEPS`.
+
+6. **No changes** to `manager.py::_build_system_prompt` or
+ `agent_instructions.py` — they read the resolver and inherit the new behavior,
+ including the `<Name>.md` auto-rename when the wake word changes.
+
+### Frontend (TypeScript)
+
+7. **`SettingsView.tsx`** — Remove `AssistantNamePanel` and its render site.
+
+8. **`hooks/useAssistantName.ts`** — Remove (the save hook is now dead). Keep
+ `hooks/useAssistantNameSeed.ts` (read-only seed; still needed for bylines).
+
+9. **Onboarding** — Delete `steps/PersonaThemeStep.tsx` and its test; remove
+ `persona-theme`/`PersonaThemeStep` from `OnboardingFlow.tsx` `REGISTRY`
+ (which derives `STEP_KEYS`).
+
+10. **Wake-word live preview (the new visibility)** — In the wake-word surfaces,
+ show a live, derived-name hint as the user types:
+ - Onboarding `steps/WakeWordStep.tsx`: below the "Hey ___" input, render
+ e.g. "Your assistant will be called: **Ruben**". The derivation mirrors
+ the backend (`phrase_core` prefix-strip + title-case); since the onboarding
+ input is the bare word with a fixed "Hey " prefix, the preview is the
+ title-cased trimmed input (empty input → no hint / the neutral fallback).
+ - Settings wake-word panel: the same live hint next to the phrase field.
+ - Add i18n keys (en/de/es source per the Output Language Policy; English is
+ the source string) such as `onboarding.wake_word.derived_name` and
+ `settings.wake_word.derived_name`. The obsolete `onboarding.persona.*` keys
+ are removed.
+
+### Tests
+
+11. **`tests/unit/brain/test_assistant_name.py`** — Invert the override tests:
+ a `[persona].name` value must now be **ignored**; the wake phrase always
+ wins ("Hey Computer" + persona "Friday" → "Computer"). Keep/extend the
+ derivation + fallback cases.
+
+12. **`tests/unit/brain/test_system_prompt_name.py`** — Update the
+ "explicit persona name wins" test to assert the wake phrase wins instead.
+
+13. **Onboarding parity** — Update the cross-layer parity test that asserts
+ frontend `STEP_KEYS` == backend `ONBOARDING_STEPS` for the removed step.
+ Find it via the comment in `OnboardingFlow.tsx` ("cross-layer parity test").
+
+14. **Frontend** — Delete `PersonaThemeStep.test.tsx`; update
+ `OnboardingFlow.test.tsx` if it references the step; add a test for the
+ wake-word live-preview hint (Settings and onboarding).
+
+## Migration / compatibility
+
+- Existing `jarvis.toml` with `[persona] name = "X"`: the key is ignored after
+ this change, and the next wake-word save removes it. The assistant's name
+ becomes whatever the wake word derives to. A user who wants the old name keeps
+ it by setting the wake word accordingly ("Hey X"). We do not auto-rewrite the
+ wake word from the old persona name — the wake word is left untouched.
+- `<Name>.md` agent-instructions file: continues to auto-migrate on the next read
+ when the resolved name changes (existing behavior in `agent_instructions.py`).
+- Onboarding state that already recorded `persona-theme` in `steps`/`current_step`
+ (e.g. a maintainer re-running via `?onboarding=force`): the backend now serves
+ the shorter step list; the frontend renders from `onb.state.steps`, so a stale
+ client step list is the only edge — acceptable, as onboarding is first-run and
+ the maintainer can force-replay.
+
+## Out of scope
+
+- No change to the wake-word engine/sensitivity/fuzzy-match settings.
+- No change to the TTS voice, language resolution, or the system-style/overlay
+ onboarding step.
+- No retroactive rename of already-recorded session bylines in stored history.
+
+## Anti-patterns to respect
+
+- Config writes stay on `config_writer` (`_WRITE_LOCK` + tempfile + BOM-safe) —
+ AP-7.
+- Removing a config field must not trip the pre-validate/boot path — verify
+ `extra` handling rather than assuming (AP-16 is about *adding* keys; this is
+ removal, but the boot-safety concern is the mirror image).
+- Keep frontend/backend onboarding step lists in lockstep — the parity test is
+ the guard (multi-layer drift, BUG-008 family).
diff --git a/docs/superpowers/specs/2026-06-20-onboarding-system-style-step-design.md b/docs/superpowers/specs/2026-06-20-onboarding-system-style-step-design.md
new file mode 100644
index 0000000000..9021e287c8
--- /dev/null
+++ b/docs/superpowers/specs/2026-06-20-onboarding-system-style-step-design.md
@@ -0,0 +1,248 @@
+# Onboarding "System Style" Step — Design Spec
+
+- **Date:** 2026-06-20
+- **Status:** Approved for planning (brainstorming complete)
+- **Topic:** A new first-time-onboarding step that lets the user choose the on-screen
+ "system style" (the Jarvis Bar vs. the Orb vs. no overlay), with the Jarvis Bar as the
+ default + "Recommended" choice.
+
+---
+
+## 1. Context & Goal
+
+The first-time onboarding guide (`docs/superpowers/specs/2026-06-19-first-time-onboarding-guide-design.md`)
+walks a new user through a multi-step setup: `welcome → terms → language → wake-word →
+api-keys → mic-test → persona-theme → finish`. It currently has **no step that lets the
+user choose how Jarvis appears on screen**.
+
+The goal is to add one **"System Style" selection step** where the user picks the primary
+on-screen surface. The **Jarvis Bar** (the slim floating voice bar) is the default and is
+labelled **"Recommended"**, so a fresh install is "Bar-equipped" out of the box.
+
+### Key reuse insight
+
+The on-screen surface is already a fully-built, tested axis in the codebase — it does **not**
+need a new vocabulary:
+
+- **Backend:** `GET/PUT /api/settings/overlay-style` (`jarvis/ui/web/settings_routes.py`),
+ persisted via `config_writer.set_overlay_style` to `ui.orb_style` in `jarvis.toml`. The
+ config default is already `ui.orb_style = "whisper_bar"` (`jarvis/core/config.py:1009`).
+- **Frontend:** the `useOverlayStyle` hook (`hooks/useOverlayStyle.ts`) and the 3-card
+ picker with preview graphics in `views/settings/OverlayTaskbarGroup.tsx`
+ (`BarPreview`, `MascotGigi`, `NonePreview`).
+- **Values:** `whisper_bar` (the Jarvis Bar), `mascot` (the Orb / Gigi ghost), `none`
+ (no overlay — just the app window / browser tab).
+
+This step **surfaces that existing axis inside onboarding**; it adds no new enum and no
+launcher changes.
+
+### Success criteria
+
+1. On the onboarding flow, a new `system-style` step appears after `persona-theme` and
+ before `finish`.
+2. The step shows all three options as preview cards; **`whisper_bar` is pre-selected and
+ carries a visible "Recommended" badge**.
+3. Picking an option persists it (`PUT /api/settings/overlay-style`, `persist: true`) and
+ live-applies it when possible; when a restart is required it offers an explicit
+ **"Restart now"** action (a pick alone never auto-restarts) (see §4).
+4. The step is skippable; "Next" / "Skip" both leave the persisted default (`whisper_bar`)
+ in place.
+5. The backend `ONBOARDING_STEPS` and the frontend `REGISTRY` stay in sync (the existing
+ cross-layer parity test covers the new key).
+6. The developer can verify via `?onboarding=force` without resetting any completed-install
+ state — the maintainer's configured localhost install is never re-onboarded.
+
+### Non-goals
+
+- No new `system_style` enum or config key — we reuse `ui.orb_style` / `overlay-style`.
+- No launcher / headless mode switching at runtime ("browser-only" as a *deployment* mode is
+ out of scope; `none` is the honest in-app representative of "no floating overlay").
+- No change to the existing Settings overlay picker behaviour (`OverlayTaskbarGroup`).
+- No *automatic* app-restart: the restart is always an explicit, opt-in click (never fired by
+ selecting a card).
+
+---
+
+## 2. Architecture
+
+**Chosen approach: a new onboarding step that reuses the existing `overlay-style` system.**
+
+A new step component (`SystemStyleStep.tsx`) renders the same three-option picker as the
+Settings panel, reusing `useOverlayStyle` and the preview graphics, pre-selected on
+`whisper_bar` with a "Recommended" badge. It registers as a new step key `system-style` in
+both the backend step list and the frontend registry.
+
+### Rejected alternatives
+
+- **New `system_style` enum (Bar / Window / Browser) + launcher integration.** A second
+ 3-way vocabulary parallel to the existing `overlay-style`, plus a full five-layer enum
+ (Python ↔ Pydantic ↔ TS ↔ UI) and launcher work to make "browser-only" actually switch
+ at runtime (a headless restart with different flags). Rejected: YAGNI + multi-layer enum
+ drift risk (AP-4); duplicates an axis that already exists.
+- **Purely informational step (display only, no effect).** Stores nothing actionable, so
+ "Recommended" would be a dead label. Rejected: dead-feature risk.
+
+### Component tree (frontend)
+
+```
+OnboardingFlow // stepper shell (unchanged mechanics)
+└─ steps/SystemStyleStep (NEW) // 3-card overlay-style picker, Bar pre-selected + Recommended
+ ├─ reuses hooks/useOverlayStyle.ts
+ └─ reuses preview graphics (BarPreview / MascotGigi / NonePreview)
+```
+
+Preview-graphic reuse is small and targeted, not a refactor: `MascotGigi` is already a
+shared component (`@/components/MascotGigi`) and `NonePreview` is already exported from
+`OverlayTaskbarGroup.tsx`. Only `BarPreview` is currently a private function in that file.
+The clean move is to lift the three previews into one shared module
+(e.g. `components/overlay/OverlayStylePreviews.tsx`) so the onboarding step does not import a
+Settings view, with both call sites importing from there. The `StylePreview` dispatcher
+(maps a style value → its graphic) moves with them. No picker logic changes.
+
+### Data flow
+
+The step calls `useOverlayStyle()` → `GET /api/settings/overlay-style` to read the current
+style and options, pre-selects `whisper_bar`, and on a card click calls `saveStyle(opt)` →
+`PUT /api/settings/overlay-style` with `persist: true`. The onboarding stepper's existing
+`goNext` / `skip` advance the flow. The onboarding step pointer persists through the normal
+`/api/onboarding/step` path (unchanged).
+
+---
+
+## 3. The Step
+
+| Field | Value |
+|---|---|
+| Step key | `system-style` |
+| Position | after `persona-theme`, before `finish` |
+| Mandatory? | No — skippable; default (`whisper_bar`) stands if skipped |
+| Reuses | `useOverlayStyle`, `/api/settings/overlay-style`, overlay preview graphics |
+
+### Options (all three, matching the existing axis)
+
+| Card | `overlay-style` value | Onboarding framing |
+|---|---|---|
+| **Jarvis Bar** | `whisper_bar` | Pre-selected + **"Recommended"** badge. "The slim floating voice bar — always within reach." |
+| **Orb** | `mascot` | "A floating companion orb (Gigi)." |
+| **No overlay** | `none` | "Just the app window / browser tab — no floating surface." |
+
+### Layout
+
+A title + short description, then the three preview cards in a row (reusing the Settings
+visuals), the **Recommended** badge on the Jarvis Bar card, a primary "Next" button, and an
+unobtrusive "Skip" link — matching the structure of `PersonaThemeStep`.
+
+---
+
+## 4. Behaviour: live-apply, else one-click restart
+
+The pick is persisted (`persist: true`) and live-applied when `swap_overlay` can change the
+surface in place. When it can't — a first-time `bar ↔ mascot` swap needs a brand-new Tk root,
+which would cross-thread-abort the process (BUG-031) — the backend returns
+`restart_required: true`. The choice is real (persisted) but invisible until the app
+restarts.
+
+The original design left that to a passive "applies next start" hint and **no** restart
+action. Maintainer feedback (2026-06-20): a selection must actually take effect, not force a
+manual relaunch. So the step now mirrors the Settings `OverlayStylePanel`:
+
+- **On a pick:** persist + attempt live-apply. If `applied_live` → done, no prompt (the
+ common case — keeping `whisper_bar`, the maintainer's current state, is a no-op).
+- **If `restart_required`:** show a **"Restart now to apply"** button that POSTs
+ `/api/settings/restart-app` → the existing `request_restart` relauncher cleanly self-
+ restarts the app so the chosen style is live. The same **409 → force-arm** path as the
+ Settings panel guards running missions (first click warns, second click forces).
+- **Never on the pick itself:** the app only restarts when the user explicitly clicks
+ "Restart now" — picking a card never auto-restarts.
+
+This is a deliberate change from the first draft's no-restart stance; honoring the user's
+choice outweighs avoiding a mid-flow restart, and the restart is opt-in (one explicit click),
+so the flow is never torn down without intent.
+
+---
+
+## 5. Backend
+
+Single change: add `"system-style"` to `ONBOARDING_STEPS` in
+`jarvis/setup/onboarding_meta.py`, positioned between `"persona-theme"` and `"finish"`:
+
+```python
+ONBOARDING_STEPS = [
+ "welcome", "terms", "language", "wake-word",
+ "api-keys", "mic-test", "persona-theme",
+ "system-style", # NEW
+ "finish",
+]
+```
+
+No new route, no new config key, no new enum. The overlay-style endpoint, config writer,
+and `ui.orb_style` default (`"whisper_bar"`) already exist and are unchanged.
+
+---
+
+## 6. Frontend Details
+
+- **Registry:** add `"system-style": SystemStyleStep` to `REGISTRY` in `OnboardingFlow.tsx`
+ (between `persona-theme` and `finish`). `STEP_KEYS` then matches the backend list.
+- **New component:** `steps/SystemStyleStep.tsx` consuming `StepProps`, using
+ `useOverlayStyle`, pre-selecting `whisper_bar`, rendering the Recommended badge, persisting
+ on pick, advancing via `goNext` / `skip`.
+- **Shared previews:** lift `BarPreview` + `NonePreview` + the `StylePreview` dispatcher into
+ `components/overlay/OverlayStylePreviews.tsx` (`MascotGigi` already lives in
+ `@/components/MascotGigi`); update `OverlayTaskbarGroup.tsx` to import from there (no visual
+ change).
+- **i18n:** new keys under `onboarding.system_style.*` — title, description, the three option
+ labels + sub-captions, the "Recommended" badge, the "applies next start" hint, and the
+ skip label. English source in `en.json`, translations in `de.json` / `es.json`
+ (CI language-policy gate compliant). Reuse existing `onboarding.nav.next` / `…back`.
+- **Accessibility:** cards are `<button>` with `aria-pressed`; the Recommended option is the
+ default focus target; keyboard navigable; respects the overlay's existing focus trap.
+
+---
+
+## 7. Testing Strategy
+
+### Automated (TDD)
+
+- **Frontend (vitest)** — `SystemStyleStep.test.tsx`:
+ - Renders three options; `whisper_bar` is pre-selected and shows the "Recommended" badge.
+ - Clicking a card calls `saveStyle` with the right value (mock `useOverlayStyle`).
+ - "Next" advances; "Skip" advances and leaves the default.
+ - A **pick alone** never calls `/api/settings/restart-app` (restart is an explicit,
+ separate click).
+ - When a pick reports `restart_required`, a "Restart now" button appears and clicking it
+ POSTs `/api/settings/restart-app` (with the 409 → force-arm path).
+- **Parity** — the existing frontend↔backend step parity test now includes `system-style`
+ (add the key on both sides so it passes).
+- **Backend (pytest)** — assert `"system-style"` is present in `ONBOARDING_STEPS` in the
+ correct position; the onboarding-state endpoint returns it in `steps`.
+
+### Developer verification (never destroys the configured env)
+
+- **`?onboarding=force`** in the running localhost app (`http://localhost:47821`) to render
+ the flow and walk to the new step without clearing any completed-install state.
+- Final self-check with the **Chrome checkup-loop skill** against the live localhost app, as
+ requested by the maintainer.
+
+---
+
+## 8. Acceptance Criteria
+
+1. A `system-style` step renders after `persona-theme` and before `finish`; the parity test
+ passes (backend + frontend lists agree).
+2. The step shows all three overlay styles as cards; `whisper_bar` is pre-selected and
+ visibly "Recommended".
+3. Selecting an option persists it via `PUT /api/settings/overlay-style` (`persist: true`);
+ no app restart is triggered from onboarding.
+4. The step is skippable; the default (`whisper_bar`) stands when skipped.
+5. The maintainer's configured localhost install is never re-onboarded by this work
+ (verification uses `?onboarding=force` only).
+6. `ruff` clean; vitest + the CI language-policy gate pass (English source strings).
+
+---
+
+## 9. Open Items / Future
+
+- Optionally surface a richer preview (animated bar) later; the static SVG previews ship now.
+- If a real "browser-only / headless" deployment toggle is ever wanted, that is a separate
+ launcher-level feature (out of scope here; `none` covers the in-app "no overlay" case).
diff --git a/docs/superpowers/specs/2026-06-21-dragdrop-files-into-context-design.md b/docs/superpowers/specs/2026-06-21-dragdrop-files-into-context-design.md
new file mode 100644
index 0000000000..7a12f8fef4
--- /dev/null
+++ b/docs/superpowers/specs/2026-06-21-dragdrop-files-into-context-design.md
@@ -0,0 +1,185 @@
+# Drag-and-drop files & content onto Jarvis → proactive reaction in context
+
+**Date:** 2026-06-21
+**Status:** Design approved (maintainer pre-approved the concept; one hard
+condition — works on macOS, Windows AND Linux).
+
+## 1. Goal & user intent
+
+The maintainer wants to drop **anything droppable** — a file, an image, a
+document, selected text, a URL — onto the on-screen Jarvis presence (the bar /
+the mascot ghost) and have the dropped content **become part of Jarvis'
+conversation context**, with Jarvis **reacting proactively** to it. The reaction
+is *decided by the model from the content*, not hard-coded: an image → comment
+on what stands out / "how does this look to you?" / analyse it; a document →
+"let me take a look". In the maintainer's words: trust the model's intelligence,
+and *"it must work across all operating systems — Mac, Windows, Linux."*
+
+This extends the shipped 2026-06-15 *mission*-drop feature
+(`docs/superpowers/specs/2026-06-15-dragdrop-mission-into-context-design.md`)
+from dropping **mission cards** to dropping **arbitrary OS content**.
+
+## 2. Key decision — surfaces (cross-platform is the hard constraint)
+
+The bar / mascot are separate **Tk overlay windows**; a native OS file-drop onto
+a Tk window is platform-specific and historically Windows-fragile. The
+2026-06-15 spec already resolved this for missions by making the **in-app React
+`JarvisDock`** the primary, cloud-first, all-OS drop surface (it mirrors the
+active display style, so it *feels* like dropping onto the bar/ghost). We reuse
+that decision:
+
+- **PRIMARY (must-ship, fully cross-platform): extend `JarvisDock` to accept OS
+ file/content drops via HTML5 `dataTransfer`.** HTML5 drag-and-drop in the
+ pywebview/browser window natively yields files, `text/plain`, `text/uri-list`
+ and images on Windows, macOS, Linux **and** any headless browser. This is the
+ faithful, robust realisation of "drop anything onto Jarvis" and satisfies the
+ hard cross-platform condition by construction.
+- **DESKTOP EXTRA (cross-platform, gated, graceful): native file/text drop on
+ the floating Tk bar + mascot** via the cross-platform `tkdnd` Tcl extension
+ (`tkinterdnd2`), behind the `[desktop]` extra. Gives the literal "drop onto the
+ always-on-top bar" on a desktop install; degrades to a logged no-op where
+ `tkdnd` is unavailable (AD-6). Reuses the **same** backend intake.
+
+Both surfaces feed one shared backend intake. The web dock alone fully delivers
+the feature on every OS; the overlay extra is additive convenience.
+
+## 3. Architecture & data flow
+
+Reuse the entire existing reply pipeline (as mission-drop does): a drop becomes a
+normal `MessageSent(role="user")` brain turn → the brain reacts (chat reply, and
+spoken on the voice build exactly as a typed message is) → the content lands in
+`BrainManager._history`. **No new speech plumbing** (AP-11). The one genuinely
+new mechanic is carrying **images** into that turn so the multimodal brain can
+*see* a dropped picture.
+
+```
+Web dock: [OS drag] → JarvisDock onDrop → FormData(files[], text, thread_id)
+ → POST /api/chat/drop ─┐
+Tk overlay: [OS drag] → drop_target callback (Tk thread) │
+ → marshal to loop → ingest_drop(...) ────────────┤
+ v
+ jarvis/brain/drop_context.py
+ 1. classify each item by MIME → (directive text, ImageBlocks)
+ 2. brain.inject_images_for_turn(trace_id, images) # image seam
+ 3. bus.publish(MessageSent(role="user", trace_id=trace_id,
+ source_layer="ui.drop", text=directive, thread_id))
+ v
+ _on_user_message (desktop_app.py / launcher.py)
+ → brain.generate(text, trace_id, source_layer="ui.drop")
+ → _collect_vision_images(trace_id) pops the injected ImageBlocks
+ (bypassing the screen-vision gate) → dispatcher.dispatch(images=)
+ → reply: chat bubble (+ spoken on the voice build)
+ → directive text now in _history (the context window)
+```
+
+### The image-injection seam (the one new BrainManager mechanic)
+
+`BrainManager` gains a tiny per-turn buffer keyed by `trace_id`:
+
+- `inject_images_for_turn(trace_id: UUID, images: tuple[ImageBlock, ...]) -> None`
+ stores into `self._pending_turn_images: dict[UUID, tuple[ImageBlock, ...]]`.
+- `_collect_vision_images(trace_id=...)` **first** pops
+ `self._pending_turn_images.pop(trace_id, None)`; if present, returns it
+ immediately — **before** the `vision is None / paused / conditional` gate — so a
+ dropped image always reaches the brain even with screen-vision off. Cleared on
+ use; never carries to the next turn. `trace_id` is unique per turn → race-free.
+
+`source_layer = "ui.drop"` is added to `_NON_SPAWN_SOURCE_LAYERS` (parity with
+`mission_inject`) so a dropped file is *reacted to / discussed*, never
+auto-force-spawned into a worker (AP-5/AP-14, anti-doom-loop). The model may
+still choose tools/spawn through normal routing.
+
+### The proactive directive (English artifact; model replies in user's language)
+
+Bounded (hard char cap, reuse the ~4000 mission cap pattern), e.g.:
+
+> 📎 You just dropped these onto me: `report.pdf`, `photo.png`.
+> [report.pdf — text excerpt …] [photo.png — image attached for you to see]
+> Take a look at what I gave you and react naturally: point out what stands out,
+> analyse it, or ask me what I'd like done with it.
+
+Reply language is resolved by the existing output-language path, not the
+directive language (same as mission-drop).
+
+### Content classification (`drop_context.py`, dependency-light)
+
+- `image/*` → `ImageBlock` (base64) for the multimodal brain + a `[image: name]`
+ note. Per-image byte cap (reuse `vision.image_budget.cap_image_b64`).
+- text / code / json / csv / markdown / yaml / toml (by MIME or extension) →
+ decoded UTF-8 text, per-file char cap, inlined.
+- `application/pdf` → best-effort: if `pypdf` imports, extract bounded text; else
+ a `[PDF: name — not extracted]` note. **No new hard dependency.**
+- anything else → `[file: name (type, size)]` note only.
+- total request cap (count + bytes) to protect the token budget / WS broadcast.
+
+## 4. Components & files
+
+**Backend (new):**
+- `jarvis/brain/drop_context.py` — pure classify+compose + `ingest_drop(bus,
+ brain, thread_id, items, dragged_text)`; no FastAPI import.
+- `jarvis/ui/web/drop_routes.py` — `POST /api/chat/drop` (multipart `files[]` +
+ form `thread_id`, `text`, `surface`); reads UploadFiles → items → `ingest_drop`.
+ Mirrors the avatar-upload pattern (size cap, bytes validation).
+- `jarvis/overlay/drop_target.py` — cross-platform `DropTarget` seam: `Protocol`
+ + `tkinterdnd2` impl + null no-op + `make_drop_target()` factory (AD-6 shape,
+ mirrors `jarvis/overlay/surface.py`). Lazy imports; never raises.
+
+**Backend (touched):**
+- `jarvis/brain/manager.py` — `inject_images_for_turn` + the pop in
+ `_collect_vision_images`; add `"ui.drop"` to `_NON_SPAWN_SOURCE_LAYERS`.
+- `jarvis/ui/web/server.py` / route registration — mount `drop_routes`.
+- `ui/orb/overlay.py` + `jarvis/ui/whisperbar/overlay.py` — attach the drop
+ target after the Tk root is built (additive; color-key rendering untouched, AD-7).
+- `jarvis/ui/desktop_app.py` — wire the overlay drop callback → marshal → ingest.
+- `pyproject.toml` — `tkinterdnd2` in the `[desktop]` extra.
+
+**Frontend (touched):**
+- `components/JarvisDock.tsx` — accept native file/content drags (a file-drag
+ `armed` state independent of the mission-drag store; `dataTransfer.files` +
+ `text/uri-list` + `text/plain`); build `FormData`; `POST /api/chat/drop`;
+ reuse the existing bloom/flash/chime feedback.
+- i18n EN source strings for the file-drop affordance.
+
+## 5. Five-layer enum discipline (BUG-008 guard)
+
+`source_layer = "ui.drop"` is the new wire-format string. Single source of truth
+in `drop_context.py`, mirrored in `manager._NON_SPAWN_SOURCE_LAYERS`, guarded by
+a parity test alongside the existing `mission_inject` parity test in
+`tests/unit/brain/test_routing.py`. No new TS enum (REST multipart, not a WS
+action), so no zod mirror needed.
+
+## 6. Error handling & edge cases
+
+- Empty / unparseable drop → ignored, no brain turn (dock `onDrop` guards;
+ route returns 400 with no `MessageSent`).
+- Oversized file → 413, per-file + total caps; never blows the token budget.
+- Non-image binary → name/type note only (no decode attempt).
+- Drop while brain is thinking → queued by the normal path (no special handling,
+ same as a typed message / dropped mission).
+- No brain / headless → chat-only reaction; no crash.
+- `tkdnd` missing (overlay extra) → logged no-op; the web dock still works.
+
+## 7. Testing
+
+- **Backend unit:** `drop_context` classification (image→ImageBlock, text inline,
+ pdf note, binary note, caps); `ingest_drop` publishes a `MessageSent` with the
+ `ui.drop` marker + injects images keyed by trace_id; empty drop → no publish.
+- **BrainManager unit:** `inject_images_for_turn` + `_collect_vision_images`
+ pops the buffer and bypasses the vision gate; clears after one turn.
+- **Routing parity:** `"ui.drop"` exempt from force-spawn.
+- **Route unit:** `POST /api/chat/drop` multipart → ingest called; size cap → 413.
+- **DropTarget seam:** factory returns null no-op without `tkinterdnd2`; never raises.
+- **Frontend vitest:** dock arms on a native file drag; `onDrop` builds the
+ expected `FormData` and POSTs; ignores empty payloads.
+- **Verify:** full pytest of new tests + ruff + `tsc -b` + vitest + a headless
+ import/boot smoke; live chrome-checkup of the dock drop if the extension is up.
+
+## 8. Anti-patterns / doctrine respected
+
+- Cloud-first RULE #1 — web dock is the all-OS primary; overlay extra is gated +
+ graceful (AD-6). Hard cross-platform condition satisfied by the HTML5 surface.
+- AP-11 — no LLM / no new code on the voice scrub path; reuse the reply pipeline.
+- AP-5 / AP-14 — no spawn tool added; `ui.drop` exempt from force-spawn.
+- BUG-008 — `ui.drop` mirrored + parity-tested.
+- AP-1 / subprocess hygiene — n/a (no new subprocess).
+- English-only artifacts (Output Language Policy).
diff --git a/docs/superpowers/specs/2026-06-23-computer-use-smarter-design.md b/docs/superpowers/specs/2026-06-23-computer-use-smarter-design.md
new file mode 100644
index 0000000000..c116c1f1b6
--- /dev/null
+++ b/docs/superpowers/specs/2026-06-23-computer-use-smarter-design.md
@@ -0,0 +1,162 @@
+# Computer-Use: Situational Awareness, Click Precision & Selectable Model
+
+Date: 2026-06-23
+Status: approved (maintainer), implementation in progress
+
+## Problem
+
+Computer-Use (CU) makes "obvious" mistakes that cost extra steps and time. Example:
+OBS is already running and visible in the taskbar; the user says "open OBS and go to
+settings", and CU still plans an `open_app` step (re-launching), because it only sees
+the current screenshot and the single foreground window — it has no knowledge of what
+is already running but minimized/backgrounded.
+
+Root cause: **state blindness, not model weakness.** A minimized OBS is invisible to the
+planning model regardless of model size. The highest-leverage fix is to give CU cheap,
+real state — plus a user-selectable model so power users can trade latency for quality on
+their own terms.
+
+CU runs on the *active brain provider* and uses that provider's `model` (the user's
+configured main model). On the maintainer's box that is `gemini-3.5-flash`. The strong
+tier (`deep_model`) is `gemini-3.1-pro-preview`. Selection is provider-agnostic
+(`manager._fast_model(active_provider)` → `cfg.model`), AP-21-compliant.
+
+## Goals
+
+1. CU stops re-launching apps that are already running; it focuses the existing window.
+2. CU plans with awareness of what is currently open.
+3. CU clicks more precisely (UIA fallback when a pixel click misses).
+4. The CU model is user-selectable per provider, defaulting to the configured `model`.
+5. No existing feature breaks. Cross-platform correct (Win/macOS/Linux + headless).
+
+## Non-goals
+
+- No automatic mid-mission model escalation (explicitly rejected by maintainer — wants
+ explicit control, no surprise latency).
+- No new hard dependency; the headless `python:3.11-slim` base install must still boot.
+
+## Architecture
+
+Four phases, sequential, each independently testable and useful. Lowest risk first.
+
+### Phase 0 — Foundation: reusable window-state utility
+
+New module `jarvis/platform/window_state.py` behind the existing platform seam
+(`detect_platform()` + probes). Public API:
+
+```python
+@dataclass(frozen=True)
+class WindowInfo:
+ title: str
+ minimized: bool = False
+ handle: int | None = None # opaque platform handle (hwnd on Windows; None elsewhere)
+
+def list_windows() -> list[WindowInfo] # all visible top-level windows
+def get_foreground_title() -> str # current foreground window title ("" if unknown)
+def focus_window(title_contains: str) -> tuple[bool, str]
+def is_app_running(app_name: str) -> WindowInfo | None # conservative title match; None = not found
+```
+
+Per-OS implementation:
+- Windows: ctypes `EnumWindows` + `GetWindowTextW` + `IsWindowVisible` (+ `IsIconic` for
+ minimized, `GetForegroundWindow` for foreground). `focus_window` reuses the exact
+ battle-tested logic currently in `switch_window._find_and_focus_windows` (AD-7: behavior
+ unchanged — code is moved, not rewritten; old names re-exported so existing tests pass).
+- macOS: `osascript` / System Events (list + raise), reusing the existing escaped/
+ injection-safe AppleScript path.
+- Linux/X11: `wmctrl -l` (list) + `wmctrl -i -a` (focus). Wayland/headless degrade to an
+ empty list / clear English message (AD-13), never a hard failure.
+- Anything unknown / headless: empty list, `(False, message)`.
+
+`switch_window` is refactored to delegate its focus to `window_state.focus_window`.
+
+`is_app_running` is **conservative**: it only reports a match when an app token clearly
+appears in a window title (case-insensitive substring, with a small alias map for known
+mismatches like `calc`→`calculator`). When uncertain it returns `None`, so the caller
+falls through to the normal launch — a false negative just reproduces today's behavior
+(no regression); a false positive (wrongly focusing instead of launching) is the worse
+error, so we bias against it.
+
+Error handling: every probe swallows its own exceptions to a logged empty result — the
+utility never raises into a caller.
+
+### Phase 1 — Awareness
+
+1a. **State in the prompt.** At each CU step, gather `list_windows()` + `get_foreground_title()`
+and inject a compact line alongside the screenshot, e.g.
+`Currently open windows: OBS Studio (minimized), Chrome — YouTube, Discord. Foreground: Chrome.`
+Gathered cheaply (microseconds), wrapped in try/except → empty string on failure or on a
+platform that returns nothing. Off the critical path concerns do not apply: this is a
+single EnumWindows call, not the heavy awareness layer.
+
+1b. **`open_app` already-running short-circuit.** Before launching, call
+`window_state.is_app_running(app_name)`. If it matches AND the app is not in a small
+multi-instance allowlist (`explorer`, `cmd`, `powershell`, `pwsh`, `wt`, `terminal`,
+`conhost`) AND `reuse_existing` is true → focus the existing window and return
+`"<app> is already running — brought it to the front."` instead of launching. New schema
+field `reuse_existing: bool = True`; an explicit "new window" intent sets it false.
+
+1c. **`switch_window` becomes a CU action.** Add `"switch_window"` to `_VALID_ACTIONS`, add
+a dispatch branch in the action executor, and add it to the planner action schema + the
+system prompt so the model can emit "switch to the OBS window" directly when it sees from
+the window list that OBS is already open.
+
+### Phase 2 — Click precision: UIA snap on a missed pixel click
+
+In `_click_with_refine`, when the existing post-click verification (regional screenshot
+diff) reports "no visible change", attempt a UIA snap **before** the expensive LLM refine
+retry: query `make_ui_tree_source()`, find the clickable element whose bounding box
+contains the guessed `(x, y)` (or is nearest within a small radius), and click its center.
+If UIA finds nothing (or no tree backend is available — headless/Null), fall through to the
+existing refine retry. Purely additive; no existing path is removed.
+
+### Phase 3 — Selectable Computer-Use model (per provider)
+
+- Config: new optional field `cu_model: str | None = None` on the brain provider config
+ model (sibling of `deep_model`).
+- Selection: `BrainManager._cu_model(provider)` = `cfg.cu_model or cfg.model or
+ get_tier_default_model("router", provider)`. The CU loop uses this (via a
+ `_select_cu_model` helper that prefers `_cu_model`, falling back to the existing
+ `_select_fast_model` chain for stubs). Provider-agnostic, AP-21-compliant.
+- Persistence: `config_writer.set_cu_model(provider, model)` (lock + tempfile + BOM-safe).
+- REST: an endpoint to read/write the per-provider CU model (mirrors the existing
+ per-provider model endpoints).
+- UI: a "Computer-Use model" picker per provider in the API-Keys/provider view, reusing
+ the existing searchable per-provider model combobox. Empty = "use my main model".
+
+## Data flow
+
+```
+CU step → ComputerUseContext → screenshot + goal + history + [window-state line]
+ → brain (provider's cu_model) → action JSON
+ → execute: open_app (is_app_running? → focus) | switch_window | click (→ UIA snap on miss) | …
+```
+
+## Testing
+
+Per phase, TDD (RED→GREEN). All cross-platform branches exercised via `detect_platform`/
+probe monkeypatching + faked ctypes/subprocess (seam-level — proves dispatch + parsing,
+NOT real osascript/wmctrl/UIA behavior on real hardware, per SIGNOFF-LOG honesty).
+
+- Phase 0: `tests/unit/platform/test_window_state.py` — list/focus/is_app_running per OS,
+ headless/Wayland degrade, conservative-match guard. Existing `test_switch_window.py`
+ must stay green (regression guard for the delegation).
+- Phase 1: open_app short-circuit (running → focus, multi-instance → still launch, uncertain
+ → still launch, force-new → still launch); awareness-line formatting; switch_window action
+ dispatch + valid-actions parity.
+- Phase 2: missed-click → UIA snap clicks the element; UIA-empty → falls through to refine;
+ no-tree → falls through. Existing click tests stay green.
+- Phase 3: `_cu_model` resolution precedence; config round-trip; route; frontend tsc+build.
+- Full suite + `ruff check` + `mypy` on touched files. No newly-added German lines
+ (language-policy gate).
+
+## Risks / guardrails
+
+- AP-21: never branch on provider name/model id — gate on capability / use provider-agnostic
+ tier lookups.
+- AD-7: Windows window logic moved verbatim, guarded by existing + new tests.
+- AP-1: every subprocess keeps `NO_WINDOW_CREATIONFLAGS`.
+- AP-7: config writes via `config_writer` only.
+- Latency: `EnumWindows` is microseconds; awareness gathering is wrapped + best-effort.
+- Headless VPS base install still boots (window_state degrades to empty; no new hard dep).
+- open_app reuse biases against false positives (uncertain → launch as before).
diff --git a/docs/superpowers/specs/2026-06-23-sound-effects-toggle-design.md b/docs/superpowers/specs/2026-06-23-sound-effects-toggle-design.md
new file mode 100644
index 0000000000..0d64cd018b
--- /dev/null
+++ b/docs/superpowers/specs/2026-06-23-sound-effects-toggle-design.md
@@ -0,0 +1,75 @@
+# Sound-Effects Toggle — Design
+
+**Date:** 2026-06-23
+**Status:** Approved (design)
+**Area:** Settings → Bar & Overlay → Behavior; speech pipeline earcons
+
+## Problem
+
+Jarvis plays four short synthesized tones ("earcons"): the wake-word "ding"
+(also on push-to-talk), a descending hang-up tone, an ascending boot-ready
+tone, and a "still listening" earcon that reuses the wake ding. A user who has
+already disabled the spoken acknowledgment still hears the wake beep on every
+"Hey Jarvis" and wants a single switch to silence all of these effect tones —
+while keeping the spoken TTS voice fully audible.
+
+## Goal
+
+One global **Sound effects** toggle in the Settings → *Behavior* section that
+mutes all four synthesized earcons together. Default **on** (no behavior change
+for existing users). Applies live, no restart.
+
+Non-goal (YAGNI): per-tone granularity; muting the spoken "Ja?" acknowledgment
+(that is voice, not an effect tone, and is gated elsewhere).
+
+## Design
+
+Mirror the existing two Behavior toggles ("Show bar at all times",
+"Mute music while dictating") layer for layer — no new architecture.
+
+| Layer | Change | Mirrors |
+|---|---|---|
+| Config | new field `ui.sound_effects: bool = True` (`UIConfig`) | `startup_chime`, `bar_persistent` |
+| Persistence | `config_writer.set_sound_effects()` → `[ui] sound_effects`, atomic | `set_bar_persistent` |
+| REST | `GET` / `PUT /api/settings/sound-effects` (`BoolToggleBody`) | `/api/settings/mute-music` |
+| Frontend hook | `useSoundEffects.ts` | `useMuteMusic.ts` |
+| UI | third `ToggleRow` in `OverlayTaskbarGroup` Behavior block (icon `Volume2`) | the two existing rows |
+| i18n | `taskbar_view.sound_effects.{title,description,enabled_toast,disabled_toast}` (en/de/es) | `taskbar_view.mute_music.*` |
+| Backend gate | new `SpeechPipeline._play_earcon(pcm, *, sample_rate)` reads `self._config.ui.sound_effects`; the four play sites route through it | — |
+
+### Live-apply mechanism
+
+`DesktopApp` loads one `cfg` and passes the same object to both the FastAPI
+server (`app.state.config`) and the `SpeechPipeline` (`self._config`). The PUT
+route sets `cfg.ui.sound_effects` in memory **and** persists via
+`config_writer`; the pipeline reads the field fresh on every earcon, so the
+switch takes effect on the next tone with no restart — identical to the
+"Mute music" toggle.
+
+### Backend gate detail
+
+The four sites:
+- `_play_ack` (wake / push-to-talk `CHIME_PCM`) — gate only the chime, not the
+ optional spoken ACK that follows it.
+- hang-up `DISCONNECT_PCM`.
+- `_play_ready_cue` (`READY_PCM`).
+- completeness "still listening" earcon (`CHIME_PCM`, fire-and-forget via
+ `asyncio.create_task`).
+
+`_play_earcon` returns early (no playback) when `sound_effects` is false, read
+defensively (`getattr(..., "sound_effects", True)`) so a missing field never
+silences tones. The fire-and-forget site checks the same flag before scheduling
+the task to avoid spawning a no-op coroutine.
+
+## Testing
+
+- Frontend: extend `OverlayTaskbarGroup.test.tsx` — the row renders, toggling
+ issues `PUT /api/settings/sound-effects`, optimistic state flips.
+- Backend: unit test that `_play_earcon` calls `play_pcm` when the flag is true
+ and skips it when false (fake player).
+- Config: `set_sound_effects` round-trips through `config_writer` (TOML patch).
+
+## Rollout
+
+Default `true` everywhere; no migration. Headless/VPS already no-ops on earcons
+(no output device), so the flag is inert there.
diff --git a/jarvis/board/profile.py b/jarvis/board/profile.py
index 50922a7e2c..8e1743dae5 100644
--- a/jarvis/board/profile.py
+++ b/jarvis/board/profile.py
@@ -17,7 +17,7 @@ Multi-provider requirement (memory ``feedback_brain_providers.md`` point 6).
Instead of accepting a fixed ``brain`` parameter, the generator receives
a ``brain_resolver: Callable[[], Brain]`` — called fresh on EVERY
``generate_bio()`` call. This way a provider switch at runtime (user
-switches the UI from Grok to Claude) takes effect immediately.
+switches the UI from Gemini to Claude) takes effect immediately.
Default resolver: ``jarvis.brain.resolver.resolve_frontier_brain(config)``.
diff --git a/jarvis/brain/ack_brain/config.py b/jarvis/brain/ack_brain/config.py
index 47efa7d226..214a3d54d6 100644
--- a/jarvis/brain/ack_brain/config.py
+++ b/jarvis/brain/ack_brain/config.py
@@ -19,7 +19,7 @@ from pydantic import BaseModel, ConfigDict, Field, field_validator
# "gemini" with a warning. Letting users pin a separate flash provider
# stays possible by setting one of the four concrete names.
SUPPORTED_PROVIDERS: tuple[str, ...] = (
- "follow_brain", "gemini", "grok", "openai", "ollama",
+ "follow_brain", "gemini", "openai", "ollama",
)
@@ -39,12 +39,6 @@ class GeminiAckProviderConfig(_ProviderBase):
api_key_secret: str = Field(default="gemini_api_key")
-class GrokAckProviderConfig(_ProviderBase):
- """xAI Grok Flash provider config."""
-
- api_key_secret: str = Field(default="grok_api_key")
-
-
class OpenAIAckProviderConfig(_ProviderBase):
"""OpenAI mini-model provider config."""
@@ -65,11 +59,6 @@ class _ProvidersBundle(BaseModel):
gemini: GeminiAckProviderConfig = Field(
default_factory=lambda: GeminiAckProviderConfig(model="gemini-3.1-flash")
)
- grok: GrokAckProviderConfig = Field(
- # 2026-05-13: "grok-4-flash" returned 400 "Model not found" from
- # xAI live. Valid fast variant is "grok-4-fast-non-reasoning".
- default_factory=lambda: GrokAckProviderConfig(model="grok-4-fast-non-reasoning")
- )
openai: OpenAIAckProviderConfig = Field(
default_factory=lambda: OpenAIAckProviderConfig(model="gpt-5-mini")
)
diff --git a/jarvis/brain/ack_brain/generator.py b/jarvis/brain/ack_brain/generator.py
index 05c13a4b43..ae481ed550 100644
--- a/jarvis/brain/ack_brain/generator.py
+++ b/jarvis/brain/ack_brain/generator.py
@@ -25,7 +25,7 @@ import asyncio
import logging
import re
import time
-from collections.abc import AsyncIterator
+from collections.abc import AsyncIterator, Callable
from typing import TYPE_CHECKING
from jarvis.brain.ack_brain.circuit_breaker import CircuitBreaker
@@ -39,6 +39,25 @@ if TYPE_CHECKING:
log = logging.getLogger(__name__)
+def _augment_with_preferences(
+ base_prompt: str, provider: Callable[[], str] | None
+) -> str:
+ """Append the user's standing-preferences block to a flash persona prompt.
+
+ Shared by the ack preamble and the spawn announcement. ``provider`` returns
+ the (already framed) preferences block, or ``""`` when none is set. A faulty
+ provider must never break the latency-critical flash call, so any exception
+ falls back to the unmodified base prompt (silent-on-failure, US-4).
+ """
+ if provider is None:
+ return base_prompt
+ try:
+ extra = (provider() or "").strip()
+ except Exception: # noqa: BLE001 — a prefs read fault must not mute the ack
+ return base_prompt
+ return f"{base_prompt}\n\n{extra}" if extra else base_prompt
+
+
# ----------------------------------------------------------------------
# Cheap top-100-word language heuristic
# ----------------------------------------------------------------------
@@ -244,13 +263,19 @@ class AckGenerator:
config: AckBrainConfig,
breaker: CircuitBreaker,
fallback: "AckGenerator | None" = None,
+ preferences_provider: Callable[[], str] | None = None,
) -> None:
self._provider = provider
self._config = config
self._breaker = breaker
+ # Returns the user's standing-preferences block (or "") so the ack
+ # preamble honors the user's agent-instructions file on action turns —
+ # the deep brain already injects it, but action turns speak the ack.
+ # Read fresh per call so an edit applies without a restart.
+ self._preferences_provider = preferences_provider
# Derived name for telemetry labels — config.provider is the
# registry-key, not a human-readable label, but they coincide
- # by design ("gemini", "grok", "openai", "ollama").
+ # by design ("gemini", "openai", "ollama").
self._provider_name = config.provider
# Optional failover AckGenerator on a SEPARATE provider/breaker. Used
# only when THIS provider is exhausted (timed out / errored / produced
@@ -289,7 +314,9 @@ class AckGenerator:
_emit_counter("ack_called_total", provider=provider_label)
# (c) persona prompt
- prompt = get_persona_prompt(language)
+ prompt = _augment_with_preferences(
+ get_persona_prompt(language), self._preferences_provider
+ )
# (d) provider call with hard timeout
t_start = time.perf_counter()
@@ -414,7 +441,9 @@ class AckGenerator:
return
_emit_counter("ack_called_total", provider=provider_label)
- prompt = get_persona_prompt(language)
+ prompt = _augment_with_preferences(
+ get_persona_prompt(language), self._preferences_provider
+ )
t_start = time.perf_counter()
buffer = ""
yielded_any = False
diff --git a/jarvis/brain/ack_brain/providers/__init__.py b/jarvis/brain/ack_brain/providers/__init__.py
index a73a1a3171..baca50a622 100644
--- a/jarvis/brain/ack_brain/providers/__init__.py
+++ b/jarvis/brain/ack_brain/providers/__init__.py
@@ -17,13 +17,11 @@ from __future__ import annotations
from jarvis.brain.ack_brain.providers.base import AbstractAckProvider
from jarvis.brain.ack_brain.providers.gemini import GeminiFlashAck
-from jarvis.brain.ack_brain.providers.grok import GrokFlashAck
from jarvis.brain.ack_brain.providers.ollama import OllamaFlashAck
from jarvis.brain.ack_brain.providers.openai import OpenAIMiniAck
REGISTRY: dict[str, type[AbstractAckProvider]] = {
"gemini": GeminiFlashAck,
- "grok": GrokFlashAck,
"openai": OpenAIMiniAck,
"ollama": OllamaFlashAck,
}
@@ -32,7 +30,6 @@ __all__ = [
"REGISTRY",
"AbstractAckProvider",
"GeminiFlashAck",
- "GrokFlashAck",
"OpenAIMiniAck",
"OllamaFlashAck",
]
diff --git a/jarvis/brain/ack_brain/spawn_announcement.py b/jarvis/brain/ack_brain/spawn_announcement.py
index d7d0679966..e767e45bfb 100644
--- a/jarvis/brain/ack_brain/spawn_announcement.py
+++ b/jarvis/brain/ack_brain/spawn_announcement.py
@@ -48,10 +48,12 @@ import logging
import random
import re
from collections import deque
+from collections.abc import Callable
from typing import TYPE_CHECKING
from jarvis.brain.ack_brain.generator import (
_TOKEN_RE,
+ _augment_with_preferences,
_detect_language,
_emit_counter,
)
@@ -366,10 +368,28 @@ class SpawnAnnouncementComposer:
provider: AbstractAckProvider | None = None,
config: AckBrainConfig | None = None,
breaker: CircuitBreaker | None = None,
+ fallback_provider: AbstractAckProvider | None = None,
+ fallback_breaker: CircuitBreaker | None = None,
+ preferences_provider: Callable[[], str] | None = None,
) -> None:
self._provider = provider
self._config = config
self._breaker = breaker
+ # Failover flash provider on a SEPARATE endpoint/key, tried only when
+ # the primary is exhausted (None), times out, errors, or its breaker is
+ # open. Mirrors the pre-thinking ack's Gemini->Grok failover
+ # (jarvis.brain.factory._build_ack_fallback) so a dead primary flash
+ # provider degrades to the live secondary, NOT to the curated pool —
+ # the 2026-06-21 "contextless stock phrase" regression (gemini 429 with
+ # no failover on the spawn path). Its own breaker so a busy primary
+ # never starves both. None => primary-only (legacy behavior).
+ self._fallback_provider = fallback_provider
+ self._fallback_breaker = fallback_breaker
+ # Returns the user's standing-preferences block (or "") so the spoken
+ # spawn announcement honors the user's agent-instructions file. Read
+ # fresh per call so an edit applies without a restart. Only the LLM path
+ # consumes it; the curated fallback pool is fixed strings by design.
+ self._preferences_provider = preferences_provider
# No-repeat memory across BOTH pools — back-to-back spawns must not
# sound identical even when the LLM path is down. maxlen 3 still
# leaves at least one pickable phrase in the smallest (4-item) pool.
@@ -455,20 +475,53 @@ class SpawnAnnouncementComposer:
async def _compose_via_llm(
self, utterance: str, lang: str, action: str, target: str
) -> str | None:
- """One bounded flash-LLM attempt; ``None`` on any failure or reject."""
- if self._provider is None:
- return None
+ """Try the primary flash provider, then the failover; ``None`` if both fail.
+
+ The failover mirrors the pre-thinking ack's Gemini->Grok failover
+ (``jarvis.brain.factory._build_ack_fallback``): when the primary flash
+ provider is exhausted (429 -> ``None``), times out, errors, or its
+ breaker is open, a dead primary must NOT silently degrade the spawn
+ announcement to the generic pool while a healthy second provider is
+ wired. Each provider keeps its OWN breaker so a busy primary never
+ starves both. The first validated announcement wins.
+ """
+ content = self._build_content(utterance, action, target)
+ for provider, breaker in (
+ (self._provider, self._breaker),
+ (self._fallback_provider, self._fallback_breaker),
+ ):
+ if provider is None:
+ continue
+ validated = await self._try_provider(provider, breaker, content, lang)
+ if validated:
+ return validated
+ return None
+
+ @staticmethod
+ def _build_content(utterance: str, action: str, target: str) -> str:
+ """Compose the LLM input once (reused across primary + failover)."""
+ content = (utterance or "").strip()
+ interpreted = " ".join(p for p in (action.strip(), target.strip()) if p)
+ if interpreted:
+ content = (
+ f"{content}\n[Task: {interpreted}]" if content
+ else f"[Task: {interpreted}]"
+ )
+ return content
+
+ async def _try_provider(
+ self,
+ provider: AbstractAckProvider,
+ breaker: CircuitBreaker | None,
+ content: str,
+ lang: str,
+ ) -> str | None:
+ """One bounded flash-LLM attempt against a single provider/breaker."""
try:
- if self._breaker is not None and await self._breaker.is_open():
+ if breaker is not None and await breaker.is_open():
_emit_counter("spawn_ack_breaker_open_total")
return None
- content = (utterance or "").strip()
- interpreted = " ".join(p for p in (action.strip(), target.strip()) if p)
- if interpreted:
- content = f"{content}\n[Task: {interpreted}]" if content else (
- f"[Task: {interpreted}]"
- )
timeout_ms = (
getattr(self._config, "timeout_ms", _DEFAULT_TIMEOUT_MS)
if self._config is not None
@@ -477,27 +530,31 @@ class SpawnAnnouncementComposer:
try:
raw = await asyncio.wait_for(
- self._provider.run(
- content, lang, persona_prompt=get_spawn_persona(lang)
+ provider.run(
+ content,
+ lang,
+ persona_prompt=_augment_with_preferences(
+ get_spawn_persona(lang), self._preferences_provider
+ ),
),
timeout=timeout_ms / 1000.0,
)
except TimeoutError:
_emit_counter("spawn_ack_timeout_total")
- if self._breaker is not None:
- await self._breaker.record_failure()
+ if breaker is not None:
+ await breaker.record_failure()
return None
except Exception as exc: # noqa: BLE001 — adapters should swallow; leak = failure
log.warning("Spawn-announcement provider raised: %s", exc)
_emit_counter("spawn_ack_provider_error_total")
- if self._breaker is not None:
- await self._breaker.record_failure()
+ if breaker is not None:
+ await breaker.record_failure()
return None
- if self._breaker is not None:
+ if breaker is not None:
# The provider answered — it is healthy even if we reject the
# text below (same bookkeeping as AckGenerator.run).
- await self._breaker.record_success()
+ await breaker.record_success()
validated = self._validate(raw or "", lang)
if validated is None and raw and raw.strip():
_emit_counter("spawn_ack_rejected_total")
diff --git a/jarvis/brain/agent_instructions.py b/jarvis/brain/agent_instructions.py
new file mode 100644
index 0000000000..0778706031
--- /dev/null
+++ b/jarvis/brain/agent_instructions.py
@@ -0,0 +1,277 @@
+"""User-editable agent-instructions file — an ``AGENTS.md`` / ``CLAUDE.md`` equivalent.
+
+This is the user's own standing-instructions file: free-text Markdown where the
+user writes personal preferences for *how the assistant should treat them* — tone,
+language, formatting, default choices, standing facts. It is deliberately distinct
+from the packaged persona (``JARVIS_PERSONA.md`` / ``data/custom_system_prompt.md``,
+handled by ``persona_loader``), which defines *who the assistant is and what it may
+do*. Preferences refine behaviour; they never override safety rules, confirmation
+gates, or capabilities.
+
+The file is named after the assistant: assistant "Ruben" -> ``Ruben.md``. The name
+is resolved through :func:`jarvis.brain.assistant_name.resolve_assistant_name`
+(the wake phrase with its prefix stripped, else the neutral ``Assistant`` fallback —
+there is no longer a separate ``[persona].name`` setting) and sanitised to a
+filesystem-safe basename. The
+file lives in its own directory under ``DATA_DIR`` so that a rename can be tracked
+unambiguously: when the assistant is renamed, the next read migrates the single
+existing file to the new name (no content is lost on a rebrand).
+
+Mirrors the ``persona_loader`` custom-prompt seam:
+
+* atomic write (tempfile + ``os.replace``), UTF-8 **without** a BOM, ``newline="\n"``
+ — the AP-7 / BUG-018 defenses;
+* read **fresh** every call (no cache) so an edit takes effect on the next turn
+ with no restart — ``_build_system_prompt`` reassembles each turn anyway;
+* every path helper reads ``core_config.DATA_DIR`` at call time (never bound at
+ import) so the path is CWD-immune (the onboarding-reappears bug class) and tests
+ can redirect ``DATA_DIR``.
+"""
+from __future__ import annotations
+
+import logging
+from pathlib import Path
+from typing import Any
+
+from jarvis.brain.assistant_name import DEFAULT_ASSISTANT_NAME, resolve_assistant_name
+
+log = logging.getLogger(__name__)
+
+_INSTRUCTIONS_DIRNAME = "agent_instructions"
+_DEFAULT_BASENAME = DEFAULT_ASSISTANT_NAME # "Assistant" — when a name sanitises to ""
+_MAX_BASENAME_LEN = 60
+
+# ä/ö/ü/ß transliteration so a German name yields an ASCII-safe, portable filename
+# (e.g. "Jürgen" -> "Juergen.md"). Case-preserving for the common single-cap case.
+_UMLAUTS = {
+ "ä": "ae", "ö": "oe", "ü": "ue", "Ä": "Ae", "Ö": "Oe", "Ü": "Ue", "ß": "ss",
+}
+# Characters that are unsafe in a filename on Windows and/or POSIX.
+_UNSAFE = set('<>:"/\\|?*')
+# Windows reserved device names (case-insensitive) — appended with "_" if matched.
+_RESERVED = {
+ "con", "prn", "aux", "nul",
+ *(f"com{i}" for i in range(1, 10)),
+ *(f"lpt{i}" for i in range(1, 10)),
+}
+
+
+def instructions_dir() -> Path:
+ """Directory holding the agent-instructions file (created lazily on write)."""
+ from jarvis.core import config as core_config
+
+ return core_config.DATA_DIR / _INSTRUCTIONS_DIRNAME
+
+
+def _safe_basename(name: str) -> str:
+ """Sanitise a resolved assistant name into a filesystem-safe basename (no ext).
+
+ Transliterates umlauts, drops control + reserved characters, trims leading/
+ trailing dots and whitespace (Windows strips these), caps length, and guards
+ Windows reserved device names. Falls back to ``Assistant`` when nothing usable
+ remains.
+ """
+ raw = (name or "").strip()
+ out: list[str] = []
+ for ch in raw:
+ if ch in _UMLAUTS:
+ out.append(_UMLAUTS[ch])
+ elif ch in _UNSAFE or ord(ch) < 32:
+ continue
+ else:
+ out.append(ch)
+ cleaned = "".join(out).strip().strip(".").strip()
+ cleaned = cleaned[:_MAX_BASENAME_LEN].strip()
+ if not cleaned:
+ return _DEFAULT_BASENAME
+ if cleaned.lower() in _RESERVED:
+ cleaned = f"{cleaned}_"
+ return cleaned
+
+
+def instructions_filename(config: Any) -> str:
+ """The display/on-disk filename for ``config``'s assistant, e.g. ``Ruben.md``."""
+ return f"{_safe_basename(resolve_assistant_name(config))}.md"
+
+
+def instructions_path(config: Any) -> Path:
+ """Absolute path to the agent-instructions file for ``config``'s assistant."""
+ return instructions_dir() / instructions_filename(config)
+
+
+def _migrate_legacy_if_needed(target: Path) -> None:
+ """Rename a single stray ``*.md`` to ``target`` so the file follows a rename.
+
+ Only acts when ``target`` does not exist and **exactly one** other ``*.md``
+ file is present in the directory (an unambiguous rename). Zero files -> nothing
+ to do; multiple files -> ambiguous, leave them untouched. Best-effort: any OS
+ error is swallowed (a failed migration must never break the brain build).
+ """
+ try:
+ if target.exists():
+ return
+ directory = target.parent
+ if not directory.is_dir():
+ return
+ candidates = [p for p in directory.glob("*.md") if p.is_file()]
+ if len(candidates) == 1 and candidates[0] != target:
+ candidates[0].replace(target)
+ log.info("agent-instructions migrated %s -> %s", candidates[0].name, target.name)
+ except OSError as exc: # noqa: BLE001 — migration is best-effort
+ log.debug("agent-instructions migration skipped: %s", exc)
+
+
+def read_agent_instructions(config: Any) -> str | None:
+ """Return the stored instructions, or ``None`` when there is no usable file.
+
+ A missing, unreadable, or whitespace-only file all count as "no instructions".
+ Triggers a one-shot rename-migration first so the file follows the assistant's
+ current name. Read fresh (no cache) — an edit applies on the next turn.
+ """
+ path = instructions_path(config)
+ _migrate_legacy_if_needed(path)
+ try:
+ text = path.read_text(encoding="utf-8")
+ except FileNotFoundError:
+ return None
+ except OSError as exc: # noqa: BLE001
+ log.warning("agent-instructions not readable (%s) — ignoring.", exc)
+ return None
+ text = text.strip()
+ return text or None
+
+
+def has_agent_instructions(config: Any) -> bool:
+ """True when a non-empty agent-instructions file is in effect."""
+ return read_agent_instructions(config) is not None
+
+
+def save_agent_instructions(config: Any, text: str) -> None:
+ """Persist the instructions atomically (tempfile + ``os.replace``).
+
+ UTF-8 without a BOM (AP-7), ``newline="\n"``, body stripped before writing.
+ """
+ import os
+ import tempfile
+
+ body = (text or "").strip()
+ path = instructions_path(config)
+ path.parent.mkdir(parents=True, exist_ok=True)
+ fd, tmp_name = tempfile.mkstemp(
+ dir=str(path.parent), prefix=".agent_instructions.", suffix=".tmp"
+ )
+ try:
+ with os.fdopen(fd, "w", encoding="utf-8", newline="\n") as fh:
+ fh.write(body)
+ os.replace(tmp_name, path)
+ except BaseException:
+ try:
+ os.unlink(tmp_name)
+ except OSError:
+ pass
+ raise
+
+
+def reset_agent_instructions(config: Any) -> bool:
+ """Delete the agent-instructions file.
+
+ Returns True when a file was removed, False when there was nothing to remove
+ (idempotent — a double reset is not an error).
+ """
+ path = instructions_path(config)
+ try:
+ path.unlink()
+ return True
+ except FileNotFoundError:
+ return False
+
+
+def render_for_prompt(config: Any) -> str:
+ """The system-prompt block for the current user-instructions state.
+
+ The block is framed so the model treats the content as *preferences* — it
+ refines tone/language/defaults but never overrides safety rules, confirmation
+ gates, or capabilities, and never authorises new tools or actions.
+ """
+ content = read_agent_instructions(config)
+ filename = instructions_filename(config)
+ if not content:
+ return (
+ f"USER PREFERENCES & STANDING INSTRUCTIONS (from {filename}):\n"
+ "No active user preferences are currently set in Jarvis.md. "
+ "Ignore any earlier Jarvis.md instructions from previous turns. "
+ "Do not continue, infer, or imitate older style, address, tone, "
+ "language, or wording rules that are absent from this current block.\n\n"
+ "END USER PREFERENCES & STANDING INSTRUCTIONS"
+ )
+ return (
+ f"USER PREFERENCES & STANDING INSTRUCTIONS (from {filename}):\n"
+ "The following are personal preferences written by the user for how you "
+ "should work with them. Only the instructions inside this current block are "
+ "active; ignore any earlier Jarvis.md instructions from previous turns that "
+ "are absent or conflict. Treat the current block as binding for tone, "
+ "language, formatting, default choices, forms of address, and standing facts "
+ "about the user. They override default style/address/tone/language guidance "
+ "where they conflict. "
+ "They never override your safety rules, confirmation gates, or capabilities, "
+ "and never authorise new tools or actions.\n\n"
+ f"{content}\n\n"
+ "END USER PREFERENCES & STANDING INSTRUCTIONS"
+ )
+
+
+def render_for_flash(config: Any) -> str:
+ """A CONCISE preferences block for the latency-critical flash spoken tiers.
+
+ Used by the pre-thinking ack preamble and the spawn-announcement composer.
+ Kept short (one framing sentence + the content) to add minimal tokens to a
+ sub-second call. Frames the content as authoritative for *style* — it
+ OVERRIDES the tier's default address/opener/tone guidance where they
+ conflict (so e.g. a user-requested form of address is used even if the
+ default persona discourages honorifics) — while explicitly NOT overriding
+ the tier's core job, brevity limit, safety rules, or the ban on naming
+ internal components. Returns ``""`` when no file is set.
+ """
+ content = read_agent_instructions(config)
+ if not content:
+ return ""
+ return (
+ "USER STANDING PREFERENCES (the user set these — honor them in your tone, "
+ "form of address, and wording; they OVERRIDE the default style/address/opener "
+ "guidance above where they conflict, including any 'forbidden address' list — "
+ "use the address the user asks for). They do NOT change your core job, your "
+ "brevity limit, the safety rules, or the ban on naming internal components:\n"
+ f"{content}"
+ )
+
+
+def seed_template(config: Any) -> str:
+ """A commented starter template so a first-time editor is not a blank box.
+
+ English source (per the repo Output Language Policy); the user's own content
+ is whatever language they write. The assistant's name is woven in so the file
+ reads as "this is how I work with <name>".
+ """
+ name = resolve_assistant_name(config)
+ return (
+ f"# How {name} should work with me\n"
+ "\n"
+ "# These are your personal preferences. They shape how the assistant talks\n"
+ "# to you and the defaults it picks. Edit freely — changes apply on the\n"
+ "# next message, no restart. (They never override safety or confirmations.)\n"
+ "\n"
+ "## Communication style\n"
+ "- \n"
+ "\n"
+ "## Language & locale\n"
+ "- \n"
+ "\n"
+ "## Do\n"
+ "- \n"
+ "\n"
+ "## Don't\n"
+ "- \n"
+ "\n"
+ "## About me / standing facts\n"
+ "- \n"
+ )
diff --git a/jarvis/brain/app_control.py b/jarvis/brain/app_control.py
index 81a84f7da4..526420779c 100644
--- a/jarvis/brain/app_control.py
+++ b/jarvis/brain/app_control.py
@@ -182,6 +182,13 @@ def is_credential_present(spec: ProviderSpec, binary_path: str | None = None) ->
return CodexAuthService(binary_path).status().connected
except Exception: # noqa: BLE001 — codex CLI absent is just "not present"
return False
+ if spec.auth_mode == "antigravity":
+ try:
+ from jarvis.google_cli.auth_service import GoogleCliAuthService
+
+ return GoogleCliAuthService().status().connected
+ except Exception: # noqa: BLE001 — Google CLI absent is just "not present"
+ return False
return False
@@ -393,6 +400,16 @@ async def apply_provider_switch(
f"Did you mean tier={spec.tier!r}?"
),
}
+ if tier == "brain" and not getattr(spec, "brain_switchable", True):
+ return {
+ "ok": False,
+ "error_kind": "subagent_only",
+ "error": (
+ f"{spec.label} is subagent-only in Jarvis. It cannot be used as "
+ "the main Brain provider because it cannot see Computer-Use "
+ "screenshots. Switch it in the Subagent section instead."
+ ),
+ }
if not is_credential_present(spec):
return {
"ok": False,
@@ -509,6 +526,8 @@ async def _switch_subagent(
) -> dict[str, Any]:
try:
from jarvis.missions.worker_runtime.provider_map import (
+ ANTIGRAVITY_SUBAGENT_CANONICAL,
+ ANTIGRAVITY_SUBAGENT_SLUGS,
CODEX_SUBAGENT_CANONICAL,
CODEX_SUBAGENT_SLUGS,
JARVIS_TO_OPENCLAW,
@@ -564,6 +583,45 @@ async def _switch_subagent(
"requires_restart": True,
}
+ if canon in ANTIGRAVITY_SUBAGENT_SLUGS:
+ try:
+ from jarvis.google_cli.auth_service import GoogleCliAuthService
+
+ antigravity_connected = GoogleCliAuthService().status().connected
+ except Exception: # noqa: BLE001 — Google CLI absent is just "not connected"
+ antigravity_connected = False
+ if not antigravity_connected:
+ return {
+ "ok": False,
+ "error_kind": "missing_credential",
+ "error": (
+ "Antigravity is not connected — sign in with Google "
+ "(install agy or the Gemini CLI and log in), then switch "
+ "the subagent."
+ ),
+ }
+ persisted = (
+ _persist(
+ lambda: _import_writer().set_sub_jarvis_provider(
+ ANTIGRAVITY_SUBAGENT_CANONICAL
+ )
+ )
+ if persist
+ else False
+ )
+ _set_in_memory(
+ cfg, ["brain", "sub_jarvis", "provider"], ANTIGRAVITY_SUBAGENT_CANONICAL
+ )
+ return {
+ "ok": True,
+ "tier": "subagent",
+ "old_provider": old,
+ "new_provider": ANTIGRAVITY_SUBAGENT_CANONICAL,
+ "persisted": persisted,
+ "applied_live": False,
+ "requires_restart": True,
+ }
+
if canon not in JARVIS_TO_OPENCLAW:
known = ", ".join(sorted(JARVIS_TO_OPENCLAW))
return {
diff --git a/jarvis/brain/dispatcher.py b/jarvis/brain/dispatcher.py
index 2a2879cbde..9be8cd2112 100644
--- a/jarvis/brain/dispatcher.py
+++ b/jarvis/brain/dispatcher.py
@@ -151,8 +151,14 @@ class BrainDispatcher:
stream=True,
)
if text_consumer is not None:
+ def _delta_progress(_delta: object) -> None:
+ if on_progress is not None:
+ on_progress()
+
return await aggregate_with_consumer(
- self._brain.complete(req), text_consumer,
+ self._brain.complete(req),
+ text_consumer,
+ delta_consumer=_delta_progress if on_progress is not None else None,
)
from .streaming import aggregate
return await aggregate(self._brain.complete(req))
diff --git a/jarvis/brain/drop_context.py b/jarvis/brain/drop_context.py
new file mode 100644
index 0000000000..055ba52343
--- /dev/null
+++ b/jarvis/brain/drop_context.py
@@ -0,0 +1,259 @@
+"""Capture dragged-and-dropped OS content as SILENT conversation context.
+
+A user drops files / images / text onto the Jarvis presence (the in-app dock or
+the floating overlay). This module is the **shared, surface-agnostic intake**:
+it classifies the dropped items, composes one bounded, human-readable context
+note, and (for images) returns the multimodal :class:`ImageBlock` payloads so the
+brain can later *see* a dropped picture.
+
+**A drop never triggers a brain turn.** The user keeps the normal speaking flow;
+``ingest_drop`` hands the content to ``brain.add_dropped_context``, which keeps
+the text in the conversation context (history) and parks images for the NEXT real
+user turn. Jarvis only reacts when the user next speaks or types — a drop while
+idle is remembered for next time, a drop mid-flow joins the running context.
+
+No FastAPI / no Tk imports here — both the web route and the desktop overlay call
+this module.
+"""
+from __future__ import annotations
+
+import base64
+import mimetypes
+from collections.abc import Sequence
+from dataclasses import dataclass
+from pathlib import Path, PurePosixPath
+from typing import Any
+from uuid import UUID
+
+from jarvis.core.protocols import ImageBlock
+
+#: ``MessageSent.source_layer`` stamped on a drag-drop turn. Mirrored in
+#: ``jarvis.brain.manager._NON_SPAWN_SOURCE_LAYERS`` so a dropped file is
+#: *reacted to / discussed* inline, never auto-force-spawned into a worker
+#: (AP-5/AP-14, anti-doom-loop). Parity test in tests/unit/brain/test_routing.py.
+DROP_SOURCE_LAYER = "ui.drop"
+
+# Defaults (overridable) — bound the per-file text and the whole directive so a
+# huge drop cannot blow the token budget or the WS broadcast circuit-breaker.
+_DEFAULT_MAX_TEXT_CHARS = 8_000
+_DEFAULT_MAX_TOTAL_CHARS = 12_000
+# Per-image budget before it ships to the brain. Anthropic caps a single image at
+# 5 MB; 4 MB keeps headroom. Over-budget images are downscaled/JPEG-encoded by
+# ``cap_image_b64`` (best-effort, never raises, no-op when already small).
+_DEFAULT_MAX_IMAGE_BYTES = 4 * 1024 * 1024
+
+# Extensions we confidently inline as UTF-8 text even when the OS hands us a
+# generic/forged ``application/octet-stream`` MIME (drag-drop MIME is unreliable).
+_TEXT_EXTS = frozenset({
+ ".txt", ".md", ".markdown", ".rst", ".log", ".csv", ".tsv",
+ ".json", ".yaml", ".yml", ".toml", ".ini", ".cfg", ".conf", ".env",
+ ".xml", ".html", ".htm", ".css", ".svg",
+ ".py", ".js", ".jsx", ".ts", ".tsx", ".rs", ".go", ".java", ".kt",
+ ".c", ".h", ".cpp", ".hpp", ".cc", ".cs", ".rb", ".php", ".swift",
+ ".sh", ".bash", ".zsh", ".ps1", ".bat", ".sql", ".r", ".lua", ".pl",
+})
+
+# MIME prefixes/values we treat as inline text regardless of extension.
+_TEXTUAL_MIME_PREFIXES = ("text/",)
+_TEXTUAL_MIMES = frozenset({
+ "application/json", "application/xml", "application/javascript",
+ "application/x-yaml", "application/yaml", "application/toml",
+ "application/x-sh", "application/sql",
+})
+
+
+@dataclass(frozen=True, slots=True)
+class DroppedItem:
+ """One dropped item normalised to (name, MIME, raw bytes).
+
+ The web route builds these from multipart ``UploadFile``s; the desktop
+ overlay builds them by reading dropped paths. ``name`` is a display
+ file name (no directory component is required).
+ """
+
+ name: str
+ mime: str
+ data: bytes
+
+
+#: Default total byte cap when reading dropped file paths (overlay drop). Mirrors
+#: the web route's multipart cap so both surfaces are bounded the same way.
+_DEFAULT_MAX_TOTAL_BYTES = 25 * 1024 * 1024
+
+
+def items_from_paths(
+ paths: Sequence[str],
+ *,
+ max_total_bytes: int = _DEFAULT_MAX_TOTAL_BYTES,
+) -> list[DroppedItem]:
+ """Read dropped file ``paths`` into :class:`DroppedItem`s (overlay drop).
+
+ The native overlay drop hands file *paths*; this reads them (bounded by a
+ total byte cap, MIME guessed from the name) so they feed the same
+ ``ingest_drop`` as the web dock's multipart bytes. Missing/unreadable paths
+ and files that would breach the cap are skipped, never raised.
+ """
+ items: list[DroppedItem] = []
+ total = 0
+ for raw in paths:
+ try:
+ p = Path(raw)
+ if not p.is_file():
+ continue
+ size = p.stat().st_size
+ if total + size > max_total_bytes:
+ continue
+ data = p.read_bytes()
+ except OSError:
+ continue
+ # Exact re-check on the bytes actually read (closes the stat→read TOCTOU
+ # window: a file that grew between stat and read can't breach the cap).
+ if total + len(data) > max_total_bytes:
+ continue
+ total += len(data)
+ name = p.name or "file"
+ mime = mimetypes.guess_type(name)[0] or "application/octet-stream"
+ items.append(DroppedItem(name=name, mime=mime, data=data))
+ return items
+
+
+def _suffix(name: str) -> str:
+ return PurePosixPath(name.replace("\\", "/")).suffix.lower()
+
+
+def _is_image(item: DroppedItem) -> bool:
+ return item.mime.lower().startswith("image/")
+
+
+def _is_textual(item: DroppedItem) -> bool:
+ mime = item.mime.lower()
+ if mime.startswith(_TEXTUAL_MIME_PREFIXES) or mime in _TEXTUAL_MIMES:
+ return True
+ return _suffix(item.name) in _TEXT_EXTS
+
+
+def _is_pdf(item: DroppedItem) -> bool:
+ return item.mime.lower() == "application/pdf" or _suffix(item.name) == ".pdf"
+
+
+def _extract_pdf_text(data: bytes, *, max_chars: int) -> str:
+ """Best-effort PDF text extraction; empty string when unavailable.
+
+ ``pypdf`` is optional — never a hard dependency. Any failure (missing lib,
+ encrypted/garbled PDF) degrades to "" so the caller falls back to a name note.
+ """
+ try:
+ import io
+
+ from pypdf import PdfReader # optional
+
+ reader = PdfReader(io.BytesIO(data))
+ parts: list[str] = []
+ for page in reader.pages:
+ parts.append(page.extract_text() or "")
+ if sum(len(p) for p in parts) >= max_chars:
+ break
+ return "\n".join(parts).strip()[:max_chars]
+ except Exception: # noqa: BLE001 — optional, best-effort
+ return ""
+
+
+def classify_and_compose(
+ items: Sequence[DroppedItem],
+ dragged_text: str | None = None,
+ *,
+ max_text_chars: int = _DEFAULT_MAX_TEXT_CHARS,
+ max_total_chars: int = _DEFAULT_MAX_TOTAL_CHARS,
+ max_image_bytes: int = _DEFAULT_MAX_IMAGE_BYTES,
+) -> tuple[str, tuple[ImageBlock, ...]]:
+ """Classify dropped content into ``(directive_text, images)``.
+
+ ``directive_text`` is ``""`` (and ``images`` empty) when nothing usable was
+ dropped — the caller then dispatches no turn. The directive is English (an
+ artifact); the brain replies in the user's conversation language via the
+ normal output-language path.
+ """
+ notes: list[str] = []
+ images: list[ImageBlock] = []
+ names: list[str] = []
+
+ for item in items:
+ if not item.name:
+ continue
+ names.append(item.name)
+ if _is_image(item):
+ # Cap the per-image payload before it ships (Anthropic's 5 MB/image
+ # limit). cap_image_b64 is a no-op when small, downscales otherwise,
+ # and never raises — falling back to the original on any failure.
+ from jarvis.vision.image_budget import cap_image_b64
+
+ mime, data_b64 = cap_image_b64(
+ item.mime or "image/png",
+ base64.b64encode(item.data).decode("ascii"),
+ max_image_bytes,
+ )
+ images.append(ImageBlock(mime=mime, data_b64=data_b64))
+ notes.append(f"- {item.name} — image attached for you to see")
+ elif _is_textual(item):
+ body = item.data.decode("utf-8", errors="replace")[:max_text_chars]
+ notes.append(f"- {item.name}:\n```\n{body}\n```")
+ elif _is_pdf(item):
+ body = _extract_pdf_text(item.data, max_chars=max_text_chars)
+ if body:
+ notes.append(f"- {item.name} (PDF):\n```\n{body}\n```")
+ else:
+ notes.append(
+ f"- {item.name} — PDF (text not extracted; ask me what you "
+ f"want and I'll open it)"
+ )
+ else:
+ notes.append(
+ f"- {item.name} — file ({item.mime or 'unknown'}, {len(item.data)} bytes)"
+ )
+
+ if dragged_text and dragged_text.strip():
+ notes.append(f"- dragged text:\n```\n{dragged_text.strip()[:max_text_chars]}\n```")
+
+ if not notes and not images:
+ return "", ()
+
+ dropped_list = ", ".join(names) if names else "some content"
+ header = (
+ f"\U0001F4CE (Context — I dropped this into our conversation: {dropped_list}.)"
+ )
+ instruction = (
+ "Keep this in mind for whatever I say next — there's no need to react to "
+ "it on its own."
+ )
+ directive = "\n".join([header, *notes, instruction]).strip()
+ if len(directive) > max_total_chars:
+ directive = directive[: max_total_chars - 2].rstrip() + " …"
+ return directive, tuple(images)
+
+
+async def ingest_drop(
+ *,
+ bus: Any = None, # kept for call-site stability; the silent flow needs no bus
+ brain: Any,
+ thread_id: str = "default", # noqa: ARG001 — kept for call-site stability
+ items: Sequence[DroppedItem],
+ dragged_text: str | None = None,
+ trace_id: UUID | None = None, # noqa: ARG001 — kept for call-site stability
+) -> bool:
+ """Capture dropped content as SILENT conversation context — never a turn.
+
+ A drop must NOT make Jarvis think on its own (the user keeps the normal
+ speaking flow). We stash the classified content on the brain via
+ ``add_dropped_context``: the text joins the conversation context and any
+ images are parked for the NEXT real user turn. Jarvis only reacts when the
+ user next speaks/types. Returns ``True`` when something was captured,
+ ``False`` for an empty drop or when no brain is available to hold context.
+ """
+ directive, images = classify_and_compose(items, dragged_text)
+ if not directive:
+ return False
+ add = getattr(brain, "add_dropped_context", None)
+ if not callable(add):
+ return False
+ add(directive, images)
+ return True
diff --git a/jarvis/brain/factory.py b/jarvis/brain/factory.py
index 7571ce8769..2543f93110 100644
--- a/jarvis/brain/factory.py
+++ b/jarvis/brain/factory.py
@@ -995,6 +995,7 @@ def _phase2_full_brain(
per_step_timeout_s=cu_cfg.per_step_timeout_s,
think_timeout_cap_s=getattr(cu_cfg, "think_timeout_cap_s", 10.0),
image_max_bytes=getattr(cu_cfg, "image_max_bytes", 300_000),
+ image_max_dimension=getattr(cu_cfg, "image_max_dimension", 2048),
settle_scale=getattr(cu_cfg, "settle_scale", 1.0),
fast_step_model=getattr(cu_cfg, "fast_step_model", ""),
plan_model_override=cu_cfg.plan_model,
@@ -1408,6 +1409,26 @@ def build_default_brain(
# Flash-Brain (Pre-Thinking Ack) factory helper
# ----------------------------------------------------------------------
+def _flash_preferences_provider(jcfg: Any) -> Any:
+ """A zero-arg callable returning the user's flash-tier preferences block.
+
+ Wired into the ack preamble and the spawn announcement so the user's
+ agent-instructions file is honored on action turns (where the spoken output
+ comes from these flash tiers, not the deep brain). Reads the file fresh per
+ call (via ``agent_instructions.render_for_flash``) so an edit applies without
+ a restart, and degrades to ``""`` when no file is set.
+ """
+ from jarvis.brain import agent_instructions
+
+ def _provide() -> str:
+ try:
+ return agent_instructions.render_for_flash(jcfg)
+ except Exception: # noqa: BLE001 — never break the flash call on a prefs fault
+ return ""
+
+ return _provide
+
+
def build_ack_brain(jcfg: Any | None = None) -> Any:
"""Build an AckGenerator from cfg.ack_brain, or return ``None`` when disabled.
@@ -1457,9 +1478,14 @@ def build_ack_brain(jcfg: Any | None = None) -> Any:
cooldown_s=ack_cfg.circuit_breaker_cooldown_s,
)
# ack_cfg.provider is now the RESOLVED primary (follow_brain expanded).
- fallback_gen = _build_ack_fallback(ack_cfg)
+ prefs_provider = _flash_preferences_provider(jcfg)
+ fallback_gen = _build_ack_fallback(ack_cfg, preferences_provider=prefs_provider)
ack_gen = AckGenerator(
- provider=provider, config=ack_cfg, breaker=breaker, fallback=fallback_gen
+ provider=provider,
+ config=ack_cfg,
+ breaker=breaker,
+ fallback=fallback_gen,
+ preferences_provider=prefs_provider,
)
log.info(
"Flash-Brain: AckGenerator wired (provider=%s, timeout_ms=%d, fallback=%s).",
@@ -1517,7 +1543,7 @@ def _build_flash_provider(jcfg: Any, ack_cfg: Any) -> Any:
return provider_cls(provider_cfg)
-def _build_ack_fallback(ack_cfg: Any) -> Any:
+def _build_ack_fallback(ack_cfg: Any, preferences_provider: Any = None) -> Any:
"""Build the secondary failover AckGenerator, or ``None``.
Wires ``[ack_brain].fallback_provider`` onto its OWN provider + circuit
@@ -1560,7 +1586,12 @@ def _build_ack_fallback(ack_cfg: Any) -> Any:
threshold=ack_cfg.circuit_breaker_threshold,
cooldown_s=ack_cfg.circuit_breaker_cooldown_s,
)
- return AckGenerator(provider=fb_provider, config=fb_cfg, breaker=fb_breaker)
+ return AckGenerator(
+ provider=fb_provider,
+ config=fb_cfg,
+ breaker=fb_breaker,
+ preferences_provider=preferences_provider,
+ )
except Exception as exc: # noqa: BLE001 — failover must never break wiring
log.warning(
"Flash-Brain: failover provider %r build failed: %s — no failover.",
@@ -1570,6 +1601,51 @@ def _build_ack_fallback(ack_cfg: Any) -> Any:
return None
+def _build_spawn_fallback(ack_cfg: Any) -> tuple[Any, Any]:
+ """Build the spawn announcer's failover ``(provider, breaker)`` or ``(None, None)``.
+
+ Mirrors :func:`_build_ack_fallback`, but yields a bare provider (the
+ ``SpawnAnnouncementComposer`` owns the validate/pool logic, so it needs the
+ provider directly, not a wrapping ``AckGenerator``). Returns ``(None, None)``
+ — composer runs primary-only — when the failover is unset, equal to the
+ already-resolved primary, missing from REGISTRY, or unbuildable. Must never
+ break the announcer wiring.
+
+ Call AFTER ``_build_flash_provider`` so ``ack_cfg.provider`` is the resolved
+ primary (``follow_brain`` expanded) and the ``== primary`` check is accurate.
+ """
+ fb_name = getattr(ack_cfg, "fallback_provider", None)
+ if not fb_name or fb_name == ack_cfg.provider:
+ return None, None
+ try:
+ from jarvis.brain.ack_brain import CircuitBreaker
+ from jarvis.brain.ack_brain.providers import REGISTRY
+
+ provider_cls = REGISTRY.get(fb_name)
+ if provider_cls is None:
+ log.warning(
+ "Spawn-Announcer: fallback_provider %r not in REGISTRY (have %s)"
+ " — no failover wired.",
+ fb_name,
+ sorted(REGISTRY.keys()),
+ )
+ return None, None
+ fb_provider = provider_cls(getattr(ack_cfg.providers, fb_name))
+ fb_breaker = CircuitBreaker(
+ threshold=ack_cfg.circuit_breaker_threshold,
+ cooldown_s=ack_cfg.circuit_breaker_cooldown_s,
+ )
+ log.info("Spawn-Announcer: failover wired (provider=%s).", fb_name)
+ return fb_provider, fb_breaker
+ except Exception as exc: # noqa: BLE001 — failover must never break wiring
+ log.warning(
+ "Spawn-Announcer: failover provider %r build failed: %s — no failover.",
+ fb_name,
+ exc,
+ )
+ return None, None
+
+
def build_spawn_announcer(jcfg: Any | None = None) -> Any:
"""Build the ``SpawnAnnouncementComposer`` for the ``spawn_worker`` tool.
@@ -1619,8 +1695,17 @@ def build_spawn_announcer(jcfg: Any | None = None) -> Any:
"Spawn-Announcer: LLM composition wired (provider=%s).",
ack_cfg.provider,
)
+ # Failover on a separate provider/key so a dead primary flash provider
+ # degrades to the live secondary, not to the canned pool (2026-06-21
+ # regression: gemini 429 with no spawn-path failover -> stock phrases).
+ fb_provider, fb_breaker = _build_spawn_fallback(ack_cfg)
return SpawnAnnouncementComposer(
- provider=provider, config=ack_cfg, breaker=breaker
+ provider=provider,
+ config=ack_cfg,
+ breaker=breaker,
+ fallback_provider=fb_provider,
+ fallback_breaker=fb_breaker,
+ preferences_provider=_flash_preferences_provider(jcfg),
)
except Exception as exc: # noqa: BLE001
log.warning(
diff --git a/jarvis/brain/frontier_autoswitch.py b/jarvis/brain/frontier_autoswitch.py
index 4aa781b648..5a45f8a1f8 100644
--- a/jarvis/brain/frontier_autoswitch.py
+++ b/jarvis/brain/frontier_autoswitch.py
@@ -3,7 +3,7 @@ available and switches automatically (user mandate 2026-04-28).
Procedure:
1. Resolver queries /v1/models per Hauptjarvis provider (claude-api, gemini,
- openai, grok). The former Sub-Jarvis tier (Wave-4 migration: removed) is
+ openai). The former Sub-Jarvis tier (Wave-4 migration: removed) is
explicitly excluded.
2. If new model > old model: mutate ``BrainProviderConfig`` in place
(Pydantic ``extra="allow"`` permits mutation).
@@ -96,9 +96,22 @@ async def apply_frontier_resolution(
``config.brain.providers[<p>].{model,deep_model}`` is updated here.
Returns the list of completed switches (may be empty if already on frontier).
+
+ Gated behind ``[brain] frontier_auto_apply`` (default False, user mandate
+ 2026-06-20 "providers must NOT switch by themselves"): when disabled this is
+ a complete no-op — no /v1/models query, no TOML write, no in-memory mutation,
+ no event — and the configured models are kept verbatim. A newer model is then
+ only ever adopted by an explicit pick in the per-provider model picker.
"""
switches: list[FrontierSwitch] = []
+ if not bool(getattr(config.brain, "frontier_auto_apply", False)):
+ log.debug(
+ "Frontier auto-switch disabled (brain.frontier_auto_apply=False) — "
+ "keeping configured models verbatim."
+ )
+ return switches
+
providers_dict = getattr(config.brain, "providers", None) or {}
for prov_name in SUPPORTED_PROVIDERS:
diff --git a/jarvis/brain/frontier_resolver.py b/jarvis/brain/frontier_resolver.py
index 5cc03760cf..0d8896f5e6 100644
--- a/jarvis/brain/frontier_resolver.py
+++ b/jarvis/brain/frontier_resolver.py
@@ -16,7 +16,6 @@ cached value; if that is also missing → ``None`` (caller keeps its TOML defaul
Tier mapping per provider:
- claude-api : fast=haiku, deep=opus
- gemini : fast=flash, deep=pro
-- grok : fast=*-fast (non-reasoning), deep=full / -reasoning
- openai : fast=gpt-{N} (without -pro/-mini/-nano), deep=gpt-{N}-pro
"""
from __future__ import annotations
@@ -39,7 +38,7 @@ log = logging.getLogger(__name__)
Tier = Literal["fast", "deep"]
DEFAULT_TTL_HOURS = 24
-SUPPORTED_PROVIDERS: tuple[str, ...] = ("claude-api", "gemini", "openai", "grok")
+SUPPORTED_PROVIDERS: tuple[str, ...] = ("claude-api", "gemini", "openai")
# Stale list — models we explicitly NEVER pick as frontier, even if the
# provider API lists them (account tier limits, legacy snapshots).
@@ -219,19 +218,6 @@ class FrontierResolver:
resp.raise_for_status()
return [m["id"] for m in resp.json().get("data", [])]
- if provider == "grok":
- api_key = cfg.get_provider_secret("grok")
- if not api_key:
- raise RuntimeError(
- "Kein xAI-API-Key fuer Frontier-Resolver.",
- )
- resp = await client.get(
- "https://api.x.ai/v1/models",
- headers={"Authorization": f"Bearer {api_key}"},
- )
- resp.raise_for_status()
- return [m["id"] for m in resp.json().get("data", [])]
-
if provider == "gemini":
api_key = cfg.get_provider_secret("gemini")
if not api_key:
@@ -263,8 +249,6 @@ class FrontierResolver:
return _pick_anthropic(models, tier)
if provider == "gemini":
return _pick_gemini(models, tier)
- if provider == "grok":
- return _pick_grok(models, tier)
if provider == "openai":
return _pick_openai(models, tier)
return None
@@ -350,73 +334,6 @@ def _pick_gemini(models: list[str], tier: Tier) -> str | None:
return candidates[0]
-def _pick_grok(models: list[str], tier: Tier) -> str | None:
- """xAI: grok-{major}.{minor} or grok-{major}-fast{-reasoning?}.
-
- Fast=*-fast (non-reasoning), Deep=full/-reasoning. CODE specialised variants
- (grok-code-fast-1) are excluded — the user wants general-purpose frontier, not
- a code model as the default brain. Date snapshots
- (grok-4.20-0309-non-reasoning) are ranked below clean IDs (grok-4.20).
- """
- candidates = [m for m in models if m.startswith("grok-") and m not in STALE_MODELS]
- # Remove specialised variants: general-purpose frontier only. Bug 2026-04-29:
- # user account only listed grok-code-fast-1 and grok-4.20-multi-agent-0309
- # — both are specialists, not what Hauptjarvis needs.
- SPECIALIZED_GROK = ("-code-", "code-fast", "-vision-", "-image-",
- "-multi-agent", "-tts-", "-audio-", "-embed",
- "-thinking-", "-non-reasoning")
- candidates = [
- c for c in candidates
- if not any(spec in c for spec in SPECIALIZED_GROK)
- ]
- if not candidates:
- # If the API list for this user account contains ONLY specialised variants:
- # do NOT downgrade — keep the TOML default (returns None).
- return None
-
- # grok-4.3 (released 2026-04-30) is, according to xAI, both the fastest
- # and most intelligent Grok model. Both tiers (fast + deep) prefer it when
- # the API lists it — otherwise the algorithm falls back to the old
- # Major.Minor sort. Without this short-circuit grok-4.20 (integer minor 20)
- # would beat grok-4.3 (minor 3), even though 4.3 is chronologically newer —
- # xAI does NOT use semver.
- if "grok-4.3" in candidates:
- return "grok-4.3"
-
- if tier == "fast":
- filtered = [
- c for c in candidates
- if "fast" in c and "reasoning" not in c
- ]
- else:
- # Deep: prefer non-fast (full grok-{N}.{M}) or -reasoning.
- filtered = [
- c for c in candidates
- if "fast" not in c or "reasoning" in c
- ]
- if not filtered:
- # Tier match empty — no fallback anchor, return None.
- # Prevents e.g. grok-3.5 (another variant) from being picked as fast
- # even though it is not the "fast" variant.
- return None
-
- def is_dated(m: str) -> bool:
- # grok-4.20-0309-non-reasoning -> date suffix with a 4-digit date component
- return bool(re.search(r"-\d{4,}-", m))
-
- def key(m: str) -> tuple[int, int, int, int]:
- match = re.search(r"grok-(\d+)(?:\.(\d+))?", m)
- major = int(match.group(1)) if match else 0
- minor = int(match.group(2)) if match and match.group(2) else 0
- # Clean IDs > dated. Shorter variant > longer at the same version.
- clean = 1 if not is_dated(m) else 0
- length_penalty = -len(m) # negative → shorter first
- return (major, minor, clean, length_penalty)
-
- filtered.sort(key=key, reverse=True)
- return filtered[0]
-
-
def _pick_openai(models: list[str], tier: Tier) -> str | None:
"""OpenAI: gpt-{major}{.minor}{-pro|-mini|-nano}?.
diff --git a/jarvis/brain/local_action_gate.py b/jarvis/brain/local_action_gate.py
index 6c6fcbf590..ae6236d2bd 100644
--- a/jarvis/brain/local_action_gate.py
+++ b/jarvis/brain/local_action_gate.py
@@ -164,6 +164,27 @@ _DRAG_RE = re.compile(
r"\b(?:fenster|datei|icon|maus|cursor|element|nach\s+(?:links|rechts|oben|unten))\b",
re.IGNORECASE,
)
+# Explicit "use Computer-Use to …" — the user NAMES the harness as the instrument
+# ("mit Computer-Use … abspielen", "per/über Computer-Use", "nutze/benutze/
+# verwende Computer-Use …", "use/with/via/using computer use …"). This is the
+# strongest possible deterministic CU signal: the user said WHICH harness to use,
+# so the command MUST reach the screenshot loop without depending on the LLM
+# talker emitting a computer_use tool_call (the codex CLI talker drops ALL tools
+# and never can — see the broader-CU comment above; live repro 2026-06-21: "mit
+# Computer-Use in Spotify … abspielen" only ACK'd, never acted, because the
+# phrase has no open verb and fell through to the talker). An instrument marker
+# must IMMEDIATELY precede the term (optionally an article), so a how-to/explain
+# mention without a marker ("erklär mir Computer-Use", "was ist Computer-Use")
+# never matches; question-word how-tos are also excluded in
+# _looks_like_desktop_control via _OPEN_INSTRUCTIONAL_RE. Input is pre-_normalize'd
+# (umlauts → ascii: "über" → "ueber"); the literal hyphen in "computer-use"
+# survives normalize, so [-\s]? covers both "computer-use" and "computer use".
+_EXPLICIT_COMPUTER_USE_RE = re.compile(
+ r"\b(?:mit|per|ueber|via|with|using|use|nutz\w*|benutz\w*|verwend\w*)\s+"
+ r"(?:der\s+|die\s+|das\s+|den\s+|the\s+)?"
+ r"computer[-\s]?use\b",
+ re.IGNORECASE,
+)
def _looks_like_desktop_control(text: str) -> bool:
@@ -187,8 +208,12 @@ def _looks_like_desktop_control(text: str) -> bool:
return True
if _OPEN_INSTRUCTIONAL_RE.search(text):
return False
+ # An explicit "use Computer-Use to …" names the harness as the instrument —
+ # the strongest deterministic CU signal. Checked AFTER the instructional
+ # guard so a how-to "wie nutze ich Computer-Use" stays a brain answer.
return bool(
- _NAVIGATE_RE.search(text)
+ _EXPLICIT_COMPUTER_USE_RE.search(text)
+ or _NAVIGATE_RE.search(text)
or _SCREENSHOT_RE.search(text)
or _WINDOW_OP_RE.search(text)
or _DRAG_RE.search(text)
diff --git a/jarvis/brain/manager.py b/jarvis/brain/manager.py
index b6db5129c3..c0f496ec53 100644
--- a/jarvis/brain/manager.py
+++ b/jarvis/brain/manager.py
@@ -14,7 +14,7 @@ Architecture:
- same provider, deep_model (if fast is rate-limited, try deeper)
- `claude-api` (OAuth Max plan)
- `claude-api` (separate quota)
- - `gemini`, `openrouter`, `openai`, `grok` (when keys are present)
+ - `gemini`, `openrouter`, `openai` (when keys are present)
- Ollama was completely removed from the project on 2026-04-21.
4. **Pipeline-Adapter**: `__call__(text) -> str` for `speech/pipeline.py`.
@@ -141,10 +141,20 @@ PROVIDER_ALIASES = {
"gemini": "gemini",
"flash": "gemini",
"pro": "gemini",
- "grok": "grok",
"openrouter": "openrouter",
}
+SUBAGENT_ONLY_BRAIN_PROVIDERS: frozenset[str] = frozenset(
+ {"antigravity", "codex", "openai-codex"}
+)
+
+_MAIN_BRAIN_FALLBACK_PROVIDER_ORDER: tuple[str, ...] = (
+ "gemini",
+ "claude-api",
+ "openai",
+ "openrouter",
+)
+
# Human-readable display names for each brain provider id. Used to tell the
# answering LLM which provider/model it is embodying this turn (the system
# prompt never carried this before, so a "which model are you?" question got a
@@ -162,7 +172,6 @@ _PROVIDER_DISPLAY_NAMES: dict[str, str] = {
"openai-codex": "OpenAI Codex (GPT-5.5)",
"openrouter": "OpenRouter",
"gemini": "Google Gemini",
- "grok": "Grok (xAI)",
"antigravity": "Google Antigravity (Gemini)",
}
@@ -214,8 +223,6 @@ _SECRET_KEY_TO_BRAIN: dict[str, str] = {
"anthropic_api_key": "claude-api",
"openai_api_key": "openai",
"openrouter_api_key": "openrouter",
- "grok_api_key": "grok",
- "xai_api_key": "grok",
}
# ──────────────────────────────────────────────────────────────────
@@ -267,17 +274,6 @@ TIER_DEFAULTS_BY_PROVIDER: dict[str, dict[str, str]] = {
"claude-api": "claude-haiku-4-5-20251001",
"gemini": "gemini-3-flash-preview",
"openai": "gpt-5.5",
- # Codex MUST be listed or `_fast_model("codex")` returns None and
- # `_build_fallback_chain` silently drops codex from the chain (its
- # `if fast:` guard) — so an explicitly-active codex brain never gets
- # called and the turn falls through to a fallback (the live "Gemini
- # answered while Codex was the active brain" bug, 2026-06-09). gpt-5.5
- # is the model `codex exec` itself reports; the CLI (ChatGPT-login) path
- # ignores it, the OpenAI-key path uses it.
- "codex": "gpt-5.5",
- # grok-4.3 (released 2026-04-30) is simultaneously the fastest
- # AND most capable Grok — replaces 4.1-fast in both tiers.
- "grok": "grok-4.3",
"deepseek": "deepseek-chat",
"openrouter": "anthropic/claude-haiku-4.5",
"mistral": "mistral-small-3.1",
@@ -292,10 +288,6 @@ TIER_DEFAULTS_BY_PROVIDER: dict[str, dict[str, str]] = {
"claude-api": "claude-opus-4-8",
"gemini": "gemini-3.1-pro-preview",
"openai": "gpt-5.5-pro",
- # Codex deep-tier anchor (same reason as the router tier above). The CLI
- # path ignores the model; this keeps codex in the deep/code chain too.
- "codex": "gpt-5.5",
- "grok": "grok-4.3",
"deepseek": "deepseek-reasoner",
"openrouter": "anthropic/claude-opus-4.8",
"mistral": "mistral-large-3",
@@ -334,6 +326,23 @@ def get_tier_default_model(tier: str, provider: str) -> str | None:
return TIER_DEFAULTS_BY_PROVIDER.get(tier, {}).get(provider)
+def _coerce_main_brain_provider(provider: str | None, *fallbacks: str | None) -> str:
+ """Return a main-brain-capable provider.
+
+ Some provider integrations exist only for the heavy subagent worker. They
+ must remain present in the codebase for that path, but an old persisted
+ ``brain.primary`` must not make the main router run through them.
+ """
+ candidate = (provider or "").strip()
+ if candidate and candidate not in SUBAGENT_ONLY_BRAIN_PROVIDERS:
+ return candidate
+ for fallback in (*fallbacks, *_MAIN_BRAIN_FALLBACK_PROVIDER_ORDER):
+ value = (fallback or "").strip()
+ if value and value not in SUBAGENT_ONLY_BRAIN_PROVIDERS:
+ return value
+ return _MAIN_BRAIN_FALLBACK_PROVIDER_ORDER[0]
+
+
# ──────────────────────────────────────────────────────────────────
# Force-spawn pattern builder (persona mandate phase 3)
# ──────────────────────────────────────────────────────────────────
@@ -359,8 +368,12 @@ _NEVER_MATCH_RE: re.Pattern[str] = re.compile(r"(?!.*)", re.IGNORECASE)
# empty diff -> critic_loop_exhausted. The doom-loop fixed 2026-06-16: every
# failed mission the user dragged in to discuss spawned another failed mission.
# Keep in sync with ``jarvis.ui.web.mission_inject.MISSION_INJECT_SOURCE_LAYER``
-# (parity test in tests/unit/brain/test_routing.py).
-_NON_SPAWN_SOURCE_LAYERS: frozenset[str] = frozenset({"ui.web.ws.mission_inject"})
+# and ``jarvis.brain.drop_context.DROP_SOURCE_LAYER`` (parity tests in
+# tests/unit/brain/test_routing.py). ``ui.drop`` = a dragged-and-dropped file /
+# image / text: reacted to inline, never auto-dispatched as a worker.
+_NON_SPAWN_SOURCE_LAYERS: frozenset[str] = frozenset(
+ {"ui.web.ws.mission_inject", "ui.drop"}
+)
# Two-turn voice/chat confirmation for a consequential ``ask``-tier tool. Turn N
@@ -404,6 +417,13 @@ _BUILD_VERB_RE: re.Pattern[str] = re.compile(
# A document / artefact NOUN — the thing being built is a file-shaped deliverable.
_DOC_NOUN_RE: re.Pattern[str] = re.compile(
r"\b(report|document|deck|slides?|spreadsheet|presentation|"
+ # build-a-deliverable nouns (a file-shaped result the Worker->Critic
+ # pipeline can verify via git diff): web/app/doc artefacts, DE + EN. A
+ # build VERB is still required by _research_wants_artifact, so a bare
+ # question ("what is an html file") never matches. "summary" is
+ # deliberately EXCLUDED — it is an ANSWER, not a file (discriminator test).
+ r"website|web ?page|webseite|html|app|application|anwendung|"
+ r"dashboard|landing ?page|visuali\w+|script|skript|"
r"bericht|dokument|tabelle|praesentation|präsentation)\b", # i18n-allow: DE artefact nouns
re.IGNORECASE,
)
@@ -488,6 +508,13 @@ _PC_CONTROL_RE: re.Pattern[str] = re.compile(
r"klick|click|tippe|tipp|type|schreib|schreibe|reinschreib|prompt|prompten|"
r"absenden|sende|send|drueck|druecke|drück|drücke|press|taste|hotkey|"
r"browser|fenster|feld|eingabefeld|chatgpt|tab|button|pc|desktop|"
+ # The live SURFACE the user names to act ON — screen / Bildschirm. A request
+ # that points at the screen is computer-use (a worker has no desktop), so
+ # naming it must register here: it keeps the turn OFF the sub-agent path and
+ # marks it an action turn so a tool-incapable talker delegates it to a
+ # tool-capable provider that picks computer_use (user pain 2026-06-21:
+ # "mach es am Bildschirm" / "do it on screen" was not recognized at all).
+ r"bildschirm|screen|"
r"maus|mouse|cursor"
r")\w*\b",
re.IGNORECASE,
@@ -495,7 +522,13 @@ _PC_CONTROL_RE: re.Pattern[str] = re.compile(
_INSTRUCTIONAL_QUESTION_RE: re.Pattern[str] = re.compile(
r"^\s*(?:"
- r"wie\s+(?:kann|koennte|könnte|muss|soll|mach|mache|macht|geht|funktioniert)\s+"
+ # "wie <verb> ich/man …" — a HOW-TO question, never a build request. The
+ # build/create verbs are listed too so "wie erstelle/baue/schreibe ich eine
+ # HTML-Datei" stays an inline answer and is not mistaken for "build me a file"
+ # (live bug 2026-06-21). The English how-to is already caught by "how do/can …".
+ r"wie\s+(?:kann|koennte|könnte|muss|soll|mach|mache|macht|geht|funktioniert"
+ r"|erstell|erstelle|erstellt|baue|bau|baut|schreib|schreibe|schreibt"
+ r"|programmier|programmiere|generier|generiere|implementier|implementiere)\s+"
r"|was\s+(?:ist|bedeutet|heisst|heißt)\s+"
r"|woran\s+erkenne\s+"
r"|warum\s+"
@@ -589,6 +622,34 @@ def _looks_like_pc_control(user_text: str) -> bool:
return bool(_PC_CONTROL_RE.search(user_text or ""))
+# Subset of ``force_spawn_phrases`` that NAMES the execution vehicle (a worker),
+# as opposed to merely describing how THOROUGH the work should be. This is a
+# PARTITION of the existing trigger phrases, not a new detection list: it only
+# decides which matched trigger keeps absolute priority over the computer-use
+# stand-down. Naming the vehicle ("subagent" / "spawn" / "openclaw" / "delegate")
+# is an UNAMBIGUOUS spawn request (mandate 2026-06-15) and wins over everything.
+# A DEPTH marker ("deep dive" / "gründlich" / "umfassend" / …) is ambiguous — it
+# overlaps with computer-use requests ("Mach einen Deep Dive mit Computer Use in
+# meinem Chrome Browser …") — so it must NOT override an explicit on-screen
+# request; that computer-use-vs-spawn call is the LLM router's. Matched as a
+# substring of the trigger the regex returned, so conjugations are covered
+# ("spawne"/"gespawnt" -> "spawn", "delegiert" -> "delegier"). No depth phrase
+# contains any of these stems, so the partition is clean.
+_VEHICLE_NAME_TRIGGER_STEMS: frozenset[str] = frozenset({
+ "openclaw", "open claw", "open-claw",
+ "subagent", "sub-agent", "sub agent",
+ "spawn", "delegier", "delegate",
+})
+
+
+def _trigger_names_vehicle(matched_trigger: str) -> bool:
+ """True iff the matched force-spawn trigger NAMES a worker vehicle (vs. a
+ thoroughness/depth descriptor). Only a vehicle name keeps absolute priority
+ over the computer-use stand-down — a depth marker yields to it."""
+ m = (matched_trigger or "").strip().lower()
+ return any(stem in m for stem in _VEHICLE_NAME_TRIGGER_STEMS)
+
+
def _is_instructional_question(user_text: str) -> bool:
"""True for how-to / explanatory questions that should be answered directly."""
return bool(_INSTRUCTIONAL_QUESTION_RE.search(user_text or ""))
@@ -1075,6 +1136,79 @@ SUPPORTED_REPLY_LANGUAGES: tuple[str, ...] = ("auto", "de", "en", "es")
_REPLY_LANGS: frozenset[str] = frozenset(SUPPORTED_REPLY_LANGUAGES)
_REPLY_LANG_NAMES: dict[str, str] = {"de": "German", "en": "English", "es": "Spanish"}
+# Spoken confirmation for a deterministic reply-language switch (the
+# voice_command_gate "language_switch" path). Keyed by target code and phrased
+# IN that language so — because set_reply_language() runs first — the TTS voice
+# resolves to the new language and the switch is audible. "auto" has no single
+# language, so it confirms in the default locale (German).
+_LANG_SWITCH_CONFIRM: dict[str, str] = {
+ "de": "Erledigt — ich antworte ab jetzt auf Deutsch.",
+ "en": "Done — I'll reply in English from now on.",
+ "es": "Listo — a partir de ahora respondo en español.",
+ "auto": "Erledigt — ich passe meine Sprache ab jetzt automatisch deiner an.",
+}
+
+# Sub-agent (Heavy-Task worker) provider switch — the voice_command_gate
+# "subagent_switch" path. The gate returns the spoken provider word; this maps
+# it to a CANONICAL [brain.sub_jarvis].provider slug (the values are the only
+# accepted ones — this map IS the validation). Persisted via the 3-layer
+# config_writer.set_sub_jarvis_provider so the drift-guard cannot revert it; the
+# running worker re-resolves it per mission (_live_subagent_provider), so the
+# switch applies to the NEXT mission without a restart.
+_SUBAGENT_VOICE_TO_CANONICAL: dict[str, str] = {
+ "openai": "openai", "gpt": "openai",
+ "codex": "openai-codex", "chatgpt": "openai-codex", "openai-codex": "openai-codex",
+ "claude": "claude-api", "anthropic": "claude-api",
+ "gemini": "gemini",
+ "openrouter": "openrouter",
+ "antigravity": "antigravity",
+}
+_SUBAGENT_DISPLAY: dict[str, str] = {
+ "openai": "OpenAI", "openai-codex": "Codex", "claude-api": "Claude",
+ "gemini": "Gemini", "openrouter": "OpenRouter",
+ "antigravity": "Antigravity",
+}
+_SUBAGENT_SWITCH_CONFIRM: dict[str, str] = {
+ "de": "Erledigt — dein Sub-Agent läuft ab der nächsten Mission auf {p}.",
+ "en": "Done — your sub-agent will run on {p} from your next mission.",
+ "es": "Listo — tu sub-agente usará {p} desde tu próxima misión.",
+}
+
+# General self-control (2026-06-22). Not every settings change can have its own
+# deterministic gate — the gates (language, sub-agent) are high-precision
+# guardrails for the common cases; this covers the LONG TAIL generally. When a
+# turn is recognised as a request to change/control Jarvis's OWN configuration,
+# a per-turn directive is injected into the system prompt so WHICHEVER provider
+# handles the turn (the active one, or — for a CLI brain that can't emit
+# tool_calls — the tool-capable provider the intelligent router hands the turn
+# to) reliably uses cli_jarvisctl / set_config_value instead of confabulating a
+# refusal. Detection needs BOTH a change verb AND a Jarvis-settings noun, so a
+# general "change the code" task is not mistaken for self-control. It must NOT
+# rely on the bare word "Jarvis" (the evidence gate filters that wake word).
+_SELF_CONTROL_VERB_RE = re.compile(
+ r"\b(?:änder\w*|aender\w*|umänder\w*|umaender\w*|stell\w*|umstell\w*|umschalt\w*"
+ r"|setz\w*|set|wechsel\w*|wechsle|aktivier\w*|deaktivier\w*|schalt\w*|switch\w*"
+ r"|change\w*|enable\w*|disable\w*|configure\w*|konfigurier\w*|adjust\w*|turn)\b",
+ re.IGNORECASE,
+)
+_SELF_CONTROL_NOUN_RE = re.compile(
+ r"\b(?:einstellung\w*|konfiguration\w*|config\w*|setting\w*|sprache|antwortsprache"
+ r"|stimme|voice|provider|anbieter|modell|model|theme|design|lautstärke|lautstaerke"
+ r"|volume|wake[-\s]?word\w*|hotkey|shortcut|stt|tts|sub[-\s]?agent|subagent"
+ r"|worker)\b",
+ re.IGNORECASE,
+)
+_SELF_CONTROL_DIRECTIVE = (
+ "SELF-CONTROL: The user is asking to change or control Jarvis's OWN settings, "
+ "configuration, providers, voice, language, or behavior. You have full "
+ "control over this. Use the `cli_jarvisctl` tool — it performs ANY Jarvis "
+ "action via the local API (e.g. `jarvisctl brain switch <provider>`, "
+ "`jarvisctl config set <key> <value>`) — or `set_config_value` for a simple "
+ "setting. NEVER say you lack access or permission to change a Jarvis setting, "
+ "and never claim the change without actually calling the tool: call it and "
+ "confirm success only AFTER it returns."
+)
+
def normalize_reply_language(value: object) -> str:
"""Coerce a raw reply-language value to a known code, else ``"auto"``.
@@ -1206,6 +1340,15 @@ class BrainManager:
self._cost_meter = cost_meter
self._curator = curator
self._vision_provider = None
+ # Drag-drop: ad-hoc images attached to ONE upcoming turn, keyed by that
+ # turn's trace_id (see jarvis/brain/drop_context.py). Popped + cleared in
+ # _collect_vision_images, bypassing the screen-vision gate so a dropped
+ # picture reaches the multimodal brain even with screen-vision off.
+ self._pending_turn_images: dict[UUID, tuple[ImageBlock, ...]] = {}
+ # Drag-drop SILENT context: pictures dropped onto the bar/mascot, parked
+ # for the NEXT real turn (a drop never triggers a turn). See
+ # add_dropped_context / generate. Dropped TEXT goes into _history.
+ self._pending_drop_images: tuple[ImageBlock, ...] = ()
# B5 Agent C: wiki context injector. None = no-op (Agent B not merged
# yet, or [wiki_context].enabled = false). Set by factory.py for the
# router tier only; sub-tiers never get wiki injection.
@@ -1258,7 +1401,21 @@ class BrainManager:
self._provider_down_idx: int = 0
self._registry = BrainProviderRegistry()
- self._active_name: str = config.brain.primary
+ raw_primary = getattr(config.brain, "primary", None)
+ router_cfg = getattr(config.brain, "router", None)
+ coerced_primary = _coerce_main_brain_provider(
+ raw_primary,
+ getattr(router_cfg, "provider", None),
+ getattr(config.brain, "deep_brain", None),
+ )
+ if coerced_primary != (raw_primary or "").strip():
+ log.warning(
+ "Brain provider %r is subagent-only; using %r as main brain.",
+ raw_primary,
+ coerced_primary,
+ )
+ config.brain.primary = coerced_primary
+ self._active_name: str = coerced_primary
# The (provider, model) actually answering the CURRENT turn. Set per
# fallback-chain attempt in generate() right before the dispatcher is
# built, consumed by _build_system_prompt to inject the authoritative
@@ -1383,7 +1540,19 @@ class BrainManager:
)
local_config = config.model_copy(deep=True)
- effective_provider = provider_override or tier_cfg.provider
+ requested_provider = provider_override or tier_cfg.provider
+ effective_provider = _coerce_main_brain_provider(
+ requested_provider,
+ tier_cfg.provider,
+ tier_cfg.fallback_provider,
+ getattr(config.brain, "deep_brain", None),
+ )
+ if effective_provider != (requested_provider or "").strip():
+ log.warning(
+ "Brain provider %r is subagent-only; using %r as router brain.",
+ requested_provider,
+ effective_provider,
+ )
local_config.brain.primary = effective_provider
# deep_brain normally mirrors the tier's fallback provider. But when an
# explicit override redirected the active provider away from the tier
@@ -1504,26 +1673,6 @@ class BrainManager:
key_value = None
if not key_value:
manager._dead_providers.add(provider_name)
- # codex-as-BRAIN genuinely needs an OpenAI API key, so disabling
- # it here is correct. But codex-as-SUBAGENT runs on the ChatGPT
- # OAuth login (no API key), so the bare "deaktiviert" line read as
- # "codex is unusable" when the sub-agent still works. Log honestly.
- if provider_name == "codex":
- oauth_ok = False
- try:
- from jarvis.codex_auth import CodexAuthService
-
- st = CodexAuthService().status()
- oauth_ok = bool(st.connected and st.mode == "chatgpt")
- except Exception: # noqa: BLE001
- oauth_ok = False
- if oauth_ok:
- log.info(
- "Pre-Boot-Key-Check: codex hat keinen OpenAI-API-Key -> "
- "als BRAIN-Provider deaktiviert, aber als Sub-Agent "
- "nutzbar (ChatGPT-OAuth-Login)."
- )
- continue
log.info(
"Pre-Boot-Key-Check: kein Key in %s -> Provider '%s' deaktiviert.",
provider_to_slots.get(provider_name, [provider_name]),
@@ -1559,6 +1708,23 @@ class BrainManager:
or get_tier_default_model("deep", name)
)
+ def _cu_model(self, name: str) -> str | None:
+ """Model the Computer-Use loop uses for ``name`` (Phase 3).
+
+ Precedence: the pinned ``cu_model`` -> the provider's main ``model`` ->
+ the router-tier default. Provider-agnostic (AP-21): no provider name or
+ model id is special-cased. When nothing is pinned this equals the model
+ chat already uses, so CU behaviour is unchanged until a CU model is set.
+ """
+ cfg = self._provider_cfg(name)
+ if cfg is None:
+ return get_tier_default_model("router", name)
+ return (
+ getattr(cfg, "cu_model", None)
+ or getattr(cfg, "model", None)
+ or get_tier_default_model("router", name)
+ )
+
def _get_brain(self, name: str, model: str | None = None) -> Brain:
"""Retrieves a Brain instance from the cache, or builds a new one."""
key = (name, model)
@@ -1895,6 +2061,21 @@ class BrainManager:
if persona_block:
parts.append(persona_block)
+ # User's own standing-instructions file (AGENTS.md / CLAUDE.md equivalent),
+ # named after the assistant (e.g. Ruben.md). Distinct from the persona: the
+ # user writes personal preferences here, and the block is framed so they
+ # refine behaviour but never override safety/confirmations. Read fresh each
+ # turn -> an edit applies on the next turn, no restart. A read fault must
+ # never break the prompt build.
+ try:
+ from jarvis.brain import agent_instructions as _agent_instructions
+
+ prefs_block = _agent_instructions.render_for_prompt(getattr(self, "_config", None))
+ if prefs_block:
+ parts.append(prefs_block)
+ except Exception: # noqa: BLE001
+ pass
+
if self._user_profile is not None:
try:
parts.append(self._user_profile.render_for_prompt())
@@ -2043,12 +2224,16 @@ class BrainManager:
if self._evidence_directive:
parts.append(self._evidence_directive)
+ # General self-control directive (settings/config control long tail).
+ if getattr(self, "_self_control_directive", ""):
+ parts.append(self._self_control_directive)
+
if self._system_prompt_extra:
parts.append(self._system_prompt_extra)
base = (
f"Du bist {name}, der persoenliche Meta-Orchestrator dieses Users auf Windows 11. "
- "Stil: trocken, praezise, ein Hauch britischer Butler im Tony-Stark-JARVIS-Stil "
+ "Stil: trocken, praezise, ein Hauch britischer Butler "
"— nie servil, nie beflissen, nie speichelleckerisch. "
"Sprich kurz (1 Satz), natuerlich, KEIN Markdown. "
"STRENG VERBOTEN — generische Greeter-/Smalltalk-Phrasen, jede einzelne. Beispiele: "
@@ -2263,6 +2448,13 @@ class BrainManager:
"""
canonical = PROVIDER_ALIASES.get(provider_name.lower().strip(), provider_name)
async with self._lock:
+ if canonical in SUBAGENT_ONLY_BRAIN_PROVIDERS:
+ log.warning(
+ "Brain provider %r is subagent-only; ignoring main-brain switch.",
+ canonical,
+ )
+ self.last_persist_ok = False
+ return
if canonical == self._active_name:
# Re-activation of the already active provider — reset caches
# so a newly set key takes effect on the next turn (otherwise
@@ -2327,6 +2519,47 @@ class BrainManager:
provider, was_dead, len(keys_to_drop),
)
+ def apply_provider_model(self, provider: str, model: str) -> bool:
+ """Live-apply a model override for a brain provider (no restart).
+
+ The model picker in the API-Keys view persists the choice to jarvis.toml
+ AND calls this so the running brain uses the new model on the next turn.
+ The manager builds its config independently of ``app.state.config``, so
+ mutating that route-level config would NOT reach the brain — this method
+ updates the manager's OWN ``self._config`` and drops cached brain
+ instances for the provider so the next ``_get_brain`` rebuilds with the
+ new model.
+
+ An empty string resets the override to ``None`` (the provider then falls
+ back to its frontier default via ``_fast_model``).
+
+ Returns ``True`` iff ``provider`` is the currently active brain — i.e.
+ the change takes effect immediately. For an inactive provider the
+ override is stored and applies as soon as the user switches to it.
+ """
+ from jarvis.core.config import BrainProviderConfig
+
+ canonical = PROVIDER_ALIASES.get(provider.lower().strip(), provider)
+ new_model = model.strip() or None
+ providers = self._config.brain.providers
+ pc = providers.get(canonical)
+ if pc is None:
+ providers[canonical] = BrainProviderConfig(model=new_model)
+ else:
+ try:
+ pc.model = new_model
+ except Exception: # noqa: BLE001 — frozen/validation: rebuild the block.
+ data = pc.model_dump() if hasattr(pc, "model_dump") else {}
+ data["model"] = new_model
+ providers[canonical] = BrainProviderConfig(**data)
+
+ # Drop cached instances for this provider so the new model is used; lift
+ # any session-level deactivation (mirrors ``reactivate_provider``).
+ for key in [k for k in self._brain_cache if k[0] == canonical]:
+ self._brain_cache.pop(key, None)
+ self._dead_providers.discard(canonical)
+ return canonical == self._active_name
+
@staticmethod
def _persist_primary(name: str) -> bool:
"""Persist ``brain.primary`` to disk (all three layers via config_writer).
@@ -2357,6 +2590,128 @@ class BrainManager:
return None
return match.target
+ def _detect_language_switch_intent(self, text: str) -> str | None:
+ """Strict gate-based reply-language switch detector.
+
+ Delegates to ``voice_command_gate.match_voice_command`` and returns the
+ target code (de/en/es/auto) ONLY for an unambiguous language command
+ like "stell auf Englisch um". A harmless mention ("wie heißt das auf
+ Englisch?") returns None and reaches the brain normally.
+ """
+ match = match_voice_command(text)
+ if match is None or match.kind != "language_switch":
+ return None
+ return match.target
+
+ def _apply_reply_language_switch(self, code: str) -> str:
+ """Execute a recognised reply-language switch deterministically.
+
+ Mirrors the canonical ``PUT /api/settings/reply-language`` path (live
+ set + persist) but is reached in ``generate()`` BEFORE the force-spawn
+ heuristic, so a trivial config change never becomes a worker mission
+ (2026-06-22 forensic: "stell auf Englisch um" was dispatched as a worker
+ and failed, harness down). It runs without the LLM, so it works no
+ matter the active provider's tool-calling capability. Returns the spoken
+ confirmation, or "" for an unknown code (caller falls through).
+ """
+ try:
+ self.set_reply_language(code) # live; ValueError on unknown code
+ except ValueError:
+ return ""
+ lang = self._reply_language
+ # Best-effort in-memory cfg agreement (a frozen model is not an error).
+ try:
+ self._config.brain.reply_language = lang # type: ignore[attr-defined]
+ except Exception as exc: # noqa: BLE001
+ log.debug("in-memory cfg.brain.reply_language update skipped: %s", exc)
+ # Persist as boot default — best-effort: a read-only / locked jarvis.toml
+ # must not break the live switch that already applied.
+ try:
+ from jarvis.core import config_writer
+
+ config_writer.set_reply_language(lang)
+ except Exception as exc: # noqa: BLE001
+ log.warning(
+ "reply-language persist failed (live switch still applied): %s", exc
+ )
+ log.info("reply-language switched to %r via deterministic voice gate", lang)
+ return _LANG_SWITCH_CONFIRM.get(lang, _LANG_SWITCH_CONFIRM["de"])
+
+ def _is_self_control_turn(self, text: str) -> bool:
+ """Broad (class-level, NOT per-command) detector for a request to change
+ or control Jarvis's OWN configuration.
+
+ True only when BOTH a change verb (ändere/stell/wechsle/aktiviere/
+ switch/set/…) AND a Jarvis-settings noun (Einstellung/Sprache/Stimme/
+ Provider/Theme/Lautstärke/STT/TTS/Sub-Agent/…) are present, so a general
+ "change the code" task is never mistaken for self-control. Used only to
+ inject a prompt directive — the LLM still constructs the actual tool
+ call, so any phrasing/setting is covered without a per-command gate.
+ Never raises (getattr-safe); returns False on any error.
+ """
+ try:
+ t = (text or "").lower()
+ return bool(
+ _SELF_CONTROL_VERB_RE.search(t) and _SELF_CONTROL_NOUN_RE.search(t)
+ )
+ except Exception: # noqa: BLE001 — a detector must never break a turn
+ return False
+
+ def _detect_subagent_switch_intent(self, text: str) -> str | None:
+ """Strict gate-based sub-agent (Heavy-Task worker) provider switch.
+
+ Delegates to ``voice_command_gate.match_voice_command``; returns the
+ spoken provider word ONLY for a sub-agent-qualified command like
+ "wechsle den Sub-Agent-Provider auf OpenAI". A bare "switch to gemini"
+ is a main-brain switch (kind=provider_switch) and returns None here.
+ """
+ match = match_voice_command(text)
+ if match is None or match.kind != "subagent_switch":
+ return None
+ return match.target
+
+ def _apply_subagent_provider_switch(self, word: str) -> str:
+ """Execute a recognised sub-agent provider switch deterministically.
+
+ The brain LLM used to escalate "switch the sub-agent provider to X" to a
+ worker mission, because ``brain.sub_jarvis.provider`` has no settable
+ self-mod tool (2026-06-22 forensic). This runs BEFORE the force-spawn /
+ LLM path: map the spoken word to a canonical slug, then persist via the
+ 3-layer ``config_writer.set_sub_jarvis_provider`` (TOML + config-soll pin
+ + ENV) so the drift-guard cannot revert it. The running worker re-resolves
+ the provider per mission (``_live_subagent_provider``), so it applies to
+ the NEXT mission without a restart. Returns the spoken confirmation, or
+ "" for an unknown provider word (caller falls through to the brain).
+ """
+ canonical = _SUBAGENT_VOICE_TO_CANONICAL.get(word.strip().lower())
+ if canonical is None:
+ return ""
+ # Best-effort in-memory cfg agreement (a frozen model is not an error).
+ try:
+ from jarvis.core.config import BrainTierConfig
+
+ self._config.brain.sub_jarvis = BrainTierConfig(provider=canonical)
+ except Exception as exc: # noqa: BLE001
+ log.debug("in-memory cfg.brain.sub_jarvis update skipped: %s", exc)
+ # Persist across all 3 layers (TOML + config-soll drift-pin + ENV) — the
+ # generic TOML-only write would be rolled back by the drift-guard.
+ try:
+ from jarvis.core import config_writer
+
+ config_writer.set_sub_jarvis_provider(canonical)
+ except Exception as exc: # noqa: BLE001
+ log.warning(
+ "sub-agent provider persist failed (in-memory switch applied): %s",
+ exc,
+ )
+ log.info(
+ "sub-agent provider switched to %r via deterministic voice gate",
+ canonical,
+ )
+ lang = self._resolve_turn_lang()
+ template = _SUBAGENT_SWITCH_CONFIRM.get(lang, _SUBAGENT_SWITCH_CONFIRM["de"])
+ return template.format(p=_SUBAGENT_DISPLAY.get(canonical, canonical))
+
def _detect_cancel_intent(self, text: str) -> bool:
"""True when the user wants to cancel a running OpenClaw task."""
match = match_voice_command(text)
@@ -2759,6 +3114,9 @@ class BrainManager:
# allowlist forms). Reset at the start of every generate() turn.
_evidence_directive: str = ""
_evidence_required_tool: str = ""
+ # Per-turn self-control directive (general settings/config control). Reset
+ # at the start of every generate() turn; appended to the system prompt.
+ _self_control_directive: str = ""
def note_skill_trigger(
self, skill_name: str, *, content: str = "", source: str = "trigger"
@@ -3265,21 +3623,43 @@ class BrainManager:
log.info("force-spawn skipped: explicit spawn decline — answer inline")
return False
# User mandate (2026-06-15, "when I say subagent it MUST spawn"): an
- # EXPLICIT heavy-work trigger ("subagent", "spawn", "openclaw",
- # "delegate", "deep dive", …) names the execution vehicle. That is an
- # UNAMBIGUOUS request to dispatch a worker, so it is checked FIRST —
- # ahead of every disambiguation guard below (instructional / pointer /
- # navigation / smalltalk / open-app / skill). Those guards exist only to
- # suppress AMBIGUOUS, implicit spawns; they must never veto a request in
- # which the user literally named the vehicle. Before this hoist, an
- # explicit "Starte OpenClaw" / "Spawne einen Subagenten und zeig …" was
- # swallowed by the open-app / navigation guard and never spawned
- # ("sometimes saying subagent doesn't spawn a subagent"). The fatal
- # preconditions above (no tool/executor, Whisper-FP seed, min length,
- # worker not viable) still win — they mean a spawn is impossible or the
- # transcript is noise, not that the user changed their mind.
- if self._get_force_spawn_pattern().search(t):
- return True
+ # EXPLICIT heavy-work trigger that NAMES the execution vehicle
+ # ("subagent", "spawn", "openclaw", "delegate") is an UNAMBIGUOUS request
+ # to dispatch a worker, so it is checked FIRST — ahead of every
+ # disambiguation guard below (instructional / pointer / navigation /
+ # smalltalk / open-app / skill). Those guards exist only to suppress
+ # AMBIGUOUS, implicit spawns; they must never veto a request in which the
+ # user literally named the vehicle. Before this hoist, an explicit
+ # "Starte OpenClaw" / "Spawne einen Subagenten und zeig …" was swallowed
+ # by the open-app / navigation guard and never spawned ("sometimes saying
+ # subagent doesn't spawn a subagent"). The fatal preconditions above (no
+ # tool/executor, Whisper-FP seed, min length, worker not viable) still
+ # win — they mean a spawn is impossible or the transcript is noise.
+ #
+ # A DEPTH marker ("deep dive", "gründlich", "umfassend", …) is NOT a
+ # vehicle name — it describes thoroughness and OVERLAPS with computer-use
+ # requests. It still force-spawns on its own ("Mach einen Deep Dive in
+ # meine Google Cloud Kosten") BUT it must NOT override an explicit
+ # on-screen / computer / browser request: "Mach einen Deep Dive mit
+ # Computer Use in meinem Chrome Browser …" is a Computer-Use turn, not a
+ # background mission. When the depth marker co-occurs with a pc-control
+ # signal we hand the computer-use-vs-spawn decision to the LLM router (it
+ # owns computer_use + the SYSTEM_PROMPT rule "Bildschirm/Browser bedienen
+ # ist computer_use, kein spawn_worker") instead of letting the keyword
+ # decide. This reuses the existing pc-control detector — no new
+ # signal-word list, no widening of force_spawn_phrases.
+ _trigger = self._get_force_spawn_pattern().search(t)
+ if _trigger is not None:
+ if _trigger_names_vehicle(_trigger.group(0)):
+ return True
+ if not _looks_like_pc_control(t):
+ return True # depth marker, no screen signal → heavy background work
+ log.info(
+ "force-spawn deferred to LLM: depth trigger %r + computer-use "
+ "request — router decides computer_use vs spawn",
+ _trigger.group(0),
+ )
+ return False
verb_re, marker_re, _smalltalk_re = self._get_routing_patterns()
if _is_instructional_question(t):
return False
@@ -3344,7 +3724,13 @@ class BrainManager:
# first; this guard is defense-in-depth so a conjugated open verb
# ("öffnest") can never fall through to a force-spawn (live bug
# 2026-06-08: "Ich möchte, dass du mir Hermes Agent öffnest, also …").
- if is_open_app_intent(t):
+ # BUT a genuine build-a-deliverable request ("build me a website",
+ # "generate a landing page for the product launch") must NOT be vetoed by
+ # an is_open_app_intent false positive (it trips on "launch" / English
+ # phrasings) — building a file/site/app is a mission, not opening an app.
+ # _research_wants_artifact requires a build VERB, so a real "open X"
+ # command (no build verb) still stands down to computer-use here.
+ if is_open_app_intent(t) and not self._research_wants_artifact(t):
return False
# NOTE: the EXPLICIT heavy-work trigger check (AD-S9, 2026-06-10) was
# hoisted to the top of this method (above every disambiguation guard)
@@ -3376,7 +3762,16 @@ class BrainManager:
return False
except Exception: # noqa: BLE001 — capability lookup must never break routing
pass
- if "dispatch_to_harness" in self._tools and _looks_like_pc_control(t):
+ # A pc-control request (incl. an explicit "am Bildschirm / on screen")
+ # is computer-use, not a sub-agent — stand down. BUT a build-a-deliverable
+ # request that merely mentions the screen ("bau mir eine Website und zeig
+ # sie am Bildschirm") must still spawn the mission, so the artifact build
+ # wins over this stand-down (mirrors the open-app guard above).
+ if (
+ "dispatch_to_harness" in self._tools
+ and _looks_like_pc_control(t)
+ and not self._research_wants_artifact(t)
+ ):
return False
# User-Mandate 2026-05-14: strict-mode is the default. The router
# used to spawn on every spawn_verb hit ("schreib", "mach",
@@ -3414,6 +3809,21 @@ class BrainManager:
# dive"/"umfassende"/...) already returned True above (AD-S9 trigger).
if self._is_heavy_research(t):
return self._research_wants_artifact(t)
+ # A request to BUILD a deliverable (an HTML file / website / app /
+ # report / document / visualization) is a sub-agent MISSION even
+ # without a research verb — the Worker->Critic pipeline verifies the
+ # built artefact via git diff. This fires PROVIDER-INDEPENDENTLY: a
+ # tool-incapable talker (Codex/Antigravity subscription CLI) cannot
+ # spawn via an LLM tool_call, so the deterministic gate is its only
+ # spawn path. Live bug 2026-06-21: "build me an HTML file for my
+ # Melbourne vacation" fell to the Antigravity deep brain, which (no
+ # tools) only asked permission instead of building. NOT a Computer-Use
+ # trigger: a build verb is not a screen action — "open/show the file"
+ # stays Computer-Use via match_local_action; a bare question is caught
+ # by the instructional guard above. _research_wants_artifact requires
+ # a build verb, so a pure answer ("write a short summary") stays inline.
+ if self._research_wants_artifact(t):
+ return True
return self._is_generic_subagent_work(t)
if verb_re.search(t):
return True
@@ -3474,7 +3884,7 @@ class BrainManager:
provider talks to the user. A configured worker provider always maps to a
real worker (claude-api -> ClaudeDirectWorker, codex -> CodexDirectWorker,
else the OpenClaw/default path), so it is viable for ANY talker — this is
- what lets the user switch ``brain.primary`` to grok / openai / codex
+ what lets the user switch ``brain.primary`` to gemini / openai / codex
without silencing every action request (AP-6: never couple routing to a
hardcoded talker provider).
@@ -3603,7 +4013,7 @@ class BrainManager:
# Now we launch the harness as a BACKGROUND task and return an
# immediate ACK (AD-OE1); its outcome — success, failure, or timeout
# — is spoken at the next turn boundary via an
- # AnnouncementRequested(kind="subagent") readback (AD-OE5/OE6, zero
+ # AnnouncementRequested(kind="completion") readback (AD-OE5/OE6, zero
# silent drops). Harness identity comes from the gate; fall back to
# the canonical in-process harness name (routes to ComputerUseHarness,
# never a claude-cli worker spawn).
@@ -3705,7 +4115,7 @@ class BrainManager:
Launched fire-and-forget by ``_run_local_action_fast_path`` so the spoken
turn ACKs immediately (AD-OE1) instead of blocking up to ~31 s on the
harness. The outcome — success, failure, or timeout — is ALWAYS surfaced
- as an ``AnnouncementRequested(kind="subagent")`` readback
+ as an ``AnnouncementRequested(kind="completion")`` readback
(AD-OE5/OE6: zero silent drops). Never raises — a background-task crash
must not leak into the event loop.
@@ -3780,9 +4190,9 @@ class BrainManager:
text=text,
priority="normal",
language=lang,
- # A background Computer-Use task reporting its outcome is a
- # spawned sub-agent result → the attributed readback track.
- kind="subagent",
+ # A background Computer-Use task reports the user's requested
+ # desktop action as the turn completion.
+ kind="completion",
detail=diag,
))
except Exception: # noqa: BLE001
@@ -4019,10 +4429,21 @@ class BrainManager:
"language": self._spawn_ack_language(user_text),
}
log.info("Force-Spawn OpenClaw: %r", user_text[:160])
+ # Stamp the turn's resolved output language so spawn_worker drives the
+ # spoken ACK + mission language from the ONE authoritative resolver on
+ # the force-spawn path too (the tool-use loop does this for brain
+ # function-calls; this caller must do it itself or ctx.config is empty
+ # and the language silently falls back — Runtime Output Language).
+ out_lang = resolve_output_language(
+ self._reply_language, "unknown", user_text,
+ default=DEFAULT_LOCALE,
+ conversation_language=self._conversation_language,
+ )
result = await self._tool_executor.execute(
tool,
args,
user_utterance=user_text,
+ config_snapshot={"output_language": out_lang},
trace_id=tid,
)
if not result.success:
@@ -4083,8 +4504,18 @@ class BrainManager:
"Recovered leaked spawn_worker tool-call from brain text "
"(provider function-calling leak): %r", user_text[:160],
)
+ # Same authoritative-language stamping as the force-spawn path: without
+ # a config snapshot ctx.config is empty and spawn_worker's language
+ # falls back instead of honoring the resolver (Runtime Output Language).
+ out_lang = resolve_output_language(
+ self._reply_language, "unknown", user_text,
+ default=DEFAULT_LOCALE,
+ conversation_language=self._conversation_language,
+ )
result = await self._tool_executor.execute(
- tool, args, user_utterance=user_text, trace_id=trace_id,
+ tool, args, user_utterance=user_text,
+ config_snapshot={"output_language": out_lang},
+ trace_id=trace_id,
)
if not result.success:
return result.error or (
@@ -4193,10 +4624,123 @@ class BrainManager:
return RoutingDecision(level="fast", reason="sticky-fast")
return classify(user_text)
+ def _brain_can_call_tools(self, provider: str, model: str | None) -> bool:
+ """Runtime tool-calling capability of a provider, capability-driven.
+
+ A brain may expose ``can_call_tools()`` to report it cannot emit
+ tool_calls right now (the subscription-CLI brains — Codex over the ChatGPT
+ login, Antigravity over the Google login — drop ALL tools). Falls back to
+ the static ``supports_tools`` ceiling, then True. Any error → True so the
+ chain is never blocked by a capability probe."""
+ try:
+ brain = self._get_brain(provider, model)
+ except Exception: # noqa: BLE001
+ return True
+ fn = getattr(brain, "can_call_tools", None)
+ if callable(fn):
+ try:
+ return bool(fn())
+ except Exception: # noqa: BLE001
+ return True
+ return bool(getattr(brain, "supports_tools", True))
+
+ def _active_can_call_tools(self) -> bool:
+ """Whether the ACTIVE talker can emit tool_calls this turn."""
+ return self._brain_can_call_tools(
+ self._active_name, self._fast_model(self._active_name)
+ )
+
+ def _first_tool_capable_provider(
+ self, level: str
+ ) -> tuple[str, str | None] | None:
+ """First AVAILABLE provider that can emit tool_calls — used to lead a
+ tool/action turn when the active talker cannot. deep_brain first, then a
+ stable cross-provider order. Returns (name, model) or None when no
+ tool-capable provider is reachable (then the chain stays unchanged)."""
+ available = set(self._registry.available())
+ order: list[str] = []
+ db = self._config.brain.deep_brain
+ if db:
+ order.append(db)
+ order += ["gemini", "claude-api", "openai", "openrouter"]
+ seen: set[str] = set()
+ for name in order:
+ if name in seen or name == self._active_name or name not in available:
+ continue
+ seen.add(name)
+ model = (
+ self._deep_model(name) if level in ("deep", "code")
+ else self._fast_model(name)
+ ) or self._fast_model(name)
+ if self._brain_can_call_tools(name, model):
+ return (name, model)
+ return None
+
+ def _turn_has_action_intent(self, user_text: str) -> bool:
+ """Best-effort, provider-agnostic 'this turn wants a tool/desktop action'
+ using the EXISTING deterministic detectors (no new signal-word list).
+ Used only to decide whether a tool-incapable active talker should delegate
+ this turn — a pure conversation/knowledge turn returns False and stays on
+ the chosen provider."""
+ t = user_text or ""
+ if is_open_app_intent(t) or _looks_like_pc_control(t):
+ return True
+ try:
+ from jarvis.core.capabilities import get_registry # noqa: PLC0415
+
+ reg = get_registry()
+ if getattr(reg, "all", lambda: ())() and reg.has_action_intent(t):
+ return True
+ except Exception: # noqa: BLE001 — registry must never block routing
+ pass
+ return False
+
def _build_fallback_chain(self, level: str) -> list[tuple[str, str | None]]:
"""Returns a prioritised list of (provider, model) attempts."""
active = self._active_name
chain: list[tuple[str, str | None]] = []
+ # Reset the per-turn router-lead marker every build (a stale value would
+ # make the loop wrongly fall through). Set below only when we prepend an
+ # intelligent-router lead.
+ self._router_lead_key: tuple[str, str | None] | None = None
+
+ # Capability-driven tool delegation (NOT a per-provider hardcode): the
+ # subscription-CLI brains (Codex over the ChatGPT login, Antigravity over
+ # the Google login) cannot emit tool_calls — can_call_tools() == False —
+ # so a tool turn reaching them is dropped/confabulated. We hand tool
+ # selection to a tool-capable provider; any future CLI brain inherits this.
+ if not self._active_can_call_tools():
+ intelligent = bool(
+ getattr(self._config.brain.routing, "intelligent_router", True)
+ )
+ if intelligent and getattr(self, "_turn_substantive", False):
+ # INTELLIGENT ROUTER (2026-06-21 mandate): a tool-capable provider
+ # LEADS every substantive turn and the LLM itself picks the tool
+ # via its tool-use loop + the router system prompt — no signal-word
+ # list decides the tool. If it picks NO tool (pure conversation),
+ # generate()'s chain loop FALLS THROUGH to the chosen talker (see
+ # ``_router_lead_key``), so the user keeps their selected brain's
+ # voice. The deterministic gates stay as high-precision guardrails.
+ helper = self._first_tool_capable_provider(level)
+ if helper is not None and helper[0] != active:
+ log.info(
+ "Intelligent router: %s cannot call tools — %s leads this "
+ "turn and picks the tool (falls through to %s if none).",
+ active, helper[0], active,
+ )
+ self._router_lead_key = helper
+ chain.append(helper)
+ elif getattr(self, "_turn_needs_tools", False):
+ # Flag OFF (kill switch): the narrower action-intent delegation —
+ # delegate ONLY when a deterministic action signal fired, and let
+ # the tool-capable provider answer the whole turn (no fall-through).
+ helper = self._first_tool_capable_provider(level)
+ if helper is not None and helper[0] != active:
+ log.info(
+ "Tool delegation (legacy): %s cannot call tools — leading "
+ "this action turn with %s.", active, helper[0],
+ )
+ chain.append(helper)
# 0. Deep/code intents: dedicated deep_brain first (e.g. gemini via
# subscription — bypasses /v1/messages API quota). Bug fix 2026-04-29:
@@ -4204,13 +4748,12 @@ class BrainManager:
# _fast_model → gemini-3-flash for a deep request instead of
# gemini-3.1-pro-preview).
deep_brain = self._config.brain.deep_brain
- # When the user has explicitly made codex the active brain, codex leads
- # for ALL turns — the deep_brain (e.g. gemini) must NOT jump ahead for
- # deep/code intents, or codex would never actually answer a hard question
- # despite being the chosen brain (it would silently fall through to the
- # deep_brain). codex (gpt-5.5) is itself a frontier model, so there is no
- # capability reason to delegate. Other active brains keep the deep_brain
- # routing unchanged.
+ # When the user has explicitly made a frontier SUBSCRIPTION brain the
+ # active one (codex via ChatGPT),
+ # it leads ALL turns — the deep_brain (e.g. gemini) must NOT jump ahead for
+ # deep/code intents, or the chosen brain would never actually answer a hard
+ # question despite being selected (it would silently fall through to the
+ # deep_brain). Other active brains keep the deep_brain routing unchanged.
if (
level in ("deep", "code")
and deep_brain
@@ -4260,7 +4803,6 @@ class BrainManager:
"gemini", # Google AI Studio
"openrouter", # universal gateway
"openai",
- "grok",
]
for name in cross_order:
if name == active:
@@ -4351,6 +4893,38 @@ class BrainManager:
await self.switch(switch_target)
return ""
+ # Deterministic reply-language switch — runs BEFORE the force-spawn
+ # heuristic so "stell auf Englisch um" sets brain.reply_language
+ # directly (live + persisted) instead of being dispatched as a worker
+ # mission (2026-06-22 forensic). Provider-independent: no LLM tool-call.
+ lang_switch = self._detect_language_switch_intent(user_text)
+ if lang_switch:
+ confirmation = self._apply_reply_language_switch(lang_switch)
+ if confirmation:
+ await self._record_response_side_effects(
+ user_text=user_text,
+ response_text=confirmation,
+ use_history=use_history,
+ trace_id=turn_trace_id,
+ )
+ return confirmation
+
+ # Deterministic sub-agent (Heavy-Task worker) provider switch — same
+ # reasoning as the language switch: runs BEFORE the force-spawn/LLM path
+ # so "switch the sub-agent provider to X" sets brain.sub_jarvis.provider
+ # directly instead of escalating to a worker mission (2026-06-22 forensic).
+ subagent_switch = self._detect_subagent_switch_intent(user_text)
+ if subagent_switch:
+ confirmation = self._apply_subagent_provider_switch(subagent_switch)
+ if confirmation:
+ await self._record_response_side_effects(
+ user_text=user_text,
+ response_text=confirmation,
+ use_history=use_history,
+ trace_id=turn_trace_id,
+ )
+ return confirmation
+
depth_override = self._detect_depth_override(user_text)
if depth_override == "deep":
self._force_level = "deep"
@@ -4417,6 +4991,9 @@ class BrainManager:
# early-returns before the gate runs).
self._evidence_directive = ""
self._evidence_required_tool = ""
+ # General self-control directive — reset here, set below once the
+ # smalltalk classification for this turn is known.
+ self._self_control_directive = ""
# AD-S4: a trigger noted by the speech pipeline / chat hook takes
# precedence — it carries the captured content and the source label.
self._consume_pending_skill_trigger(user_text)
@@ -4435,6 +5012,35 @@ class BrainManager:
getattr(self._skill_turn_match, "name", "?"),
)
self._skill_turn_match = None
+ # Sibling of AD-S9: a plugin/marketplace skill that merely keyword-
+ # matched an APP NAME ("Discord", "Spotify", "Slack") must NOT capture a
+ # turn the deterministic desktop-control gate owns. Computer-Use is the
+ # universal GUI integration — "open Discord and find the post on screen"
+ # must reach it even when the plugin's API/MCP integration is absent,
+ # instead of suppressing the local-action fast path and falling through
+ # to a tool-less CLI talker that hallucinates a permissions refusal.
+ # Live bug 2026-06-21 (sessions.db turn 67276501-…): plugin-discord
+ # matched the bare word "Discord", the antigravity deep brain (a CLI
+ # talker that drops all tools) then said "ich habe keinen Zugriff auf
+ # Discord". The gate decision is authoritative and precise: only a
+ # DIRECT open or a COMPUTER_USE plan stands the skill down — a pure
+ # dispatch ("schick eine Discord-Nachricht", gate → None/UNSUPPORTED)
+ # keeps its skill, and a non-app skill turn ("starte die Morgenroutine",
+ # gate → None) is untouched.
+ if self._skill_turn_match is not None:
+ _gate_plan = match_local_action(user_text)
+ if _gate_plan is not None and _gate_plan.mode in (
+ LocalActionMode.DIRECT,
+ LocalActionMode.COMPUTER_USE,
+ ):
+ log.info(
+ "Skill match %s stands down — the deterministic local-action "
+ "gate claims this turn as %s; Computer-Use owns it "
+ "(universal GUI integration, not a keyword-matched plugin).",
+ getattr(self._skill_turn_match, "name", "?"),
+ _gate_plan.mode.value,
+ )
+ self._skill_turn_match = None
if self._skill_turn_match is not None:
log.info(
"Skill-matched turn: %r → skill %s (fast paths stand down)",
@@ -4605,11 +5211,31 @@ class BrainManager:
user_text[:80],
)
+ # General self-control (the long tail not covered by a deterministic
+ # gate, which runs earlier and returns): inject a directive so whichever
+ # provider handles the turn reliably uses cli_jarvisctl / set_config_value
+ # instead of confabulating a refusal. Substantive turns only.
+ if not is_smalltalk_turn and self._is_self_control_turn(user_text):
+ self._self_control_directive = _SELF_CONTROL_DIRECTIVE
+
# 2. Router: which level applies?
decision = self._picked_level(user_text)
log.debug("Router-Decision: level=%s reason=%s", decision.level, decision.reason)
- # 3. Build fallback chain and try each entry
+ # 3. Build fallback chain and try each entry.
+ # Provider-agnostic tool routing flags (consumed by _build_fallback_chain):
+ # - _turn_substantive: a non-smalltalk turn. With the intelligent router
+ # on, a tool-capable provider LEADS such a turn for a tool-incapable
+ # talker and the LLM picks the tool (or falls through to the talker).
+ # - _turn_needs_tools: the narrower action-intent signal used as the
+ # flag-OFF (kill-switch) delegation. Reuses the deterministic detectors.
+ # Reset _router_lead_key here too so a monkeypatched _build_fallback_chain
+ # (tests / callers that replace it) never leaves a stale fall-through marker.
+ self._router_lead_key = None
+ self._turn_substantive = not is_smalltalk_turn
+ self._turn_needs_tools = (not is_smalltalk_turn) and self._turn_has_action_intent(
+ user_text
+ )
chain = self._build_fallback_chain(decision.level)
if not chain:
# Empty chain means either (a) no providers registered or
@@ -4633,6 +5259,17 @@ class BrainManager:
return await self._provider_down_reply(trace_uuid)
history = self._history if use_history else []
+ _drop_in_hist = sum(
+ 1 for m in history
+ if isinstance(getattr(m, "content", None), str)
+ and "\U0001F4CE" in m.content
+ )
+ if _drop_in_hist:
+ log.info(
+ "📎 DROP CONTEXT present in this turn's history: %d note(s), "
+ "use_history=%s, total history=%d",
+ _drop_in_hist, use_history, len(history),
+ )
last_exc: Exception | None = None
response_text = ""
used_provider: str | None = None
@@ -4733,6 +5370,15 @@ class BrainManager:
f"{turn_context}\n\n{pointer_block}" if turn_context else pointer_block
)
+ # Drag-drop SILENT context: pictures parked by ``add_dropped_context``
+ # (a drop never triggers its own turn) are pulled into THIS real turn,
+ # once — added AFTER vision + AI-Pointer image logic so neither clobbers
+ # them. Cleared on consume; never re-sent on later turns.
+ _dropped_imgs = getattr(self, "_pending_drop_images", ()) or ()
+ if _dropped_imgs:
+ self._pending_drop_images = ()
+ images = tuple(_dropped_imgs) + tuple(images)
+
for idx, (prov_name, model) in enumerate(chain):
# Skip providers already marked dead in THIS turn.
# Example: gemini-fast fails with missing_key → gemini-deep would
@@ -4816,6 +5462,16 @@ class BrainManager:
# provider that genuinely runs this attempt, including a fallback win.
self._active_turn_identity = (prov_name, model)
disp = self._build_dispatcher(brain, tools_override=_turn_tools)
+ # Intelligent router: the router LEAD must NOT stream its conversational
+ # text to TTS. On the streaming path (generate_stream) text_consumer
+ # speaks each chunk live DURING dispatch — so a no-tool router answer
+ # would be spoken and THEN the fall-through talker would speak again
+ # (double answer). Suppress the consumer for the lead: if it picks a
+ # tool, the result is surfaced by generate_stream's final reconciliation
+ # (nothing was yielded → it yields holder["final"]); if it picks none,
+ # the chosen talker streams the answer normally after the fall-through.
+ _is_router_lead = self._router_lead_key == (prov_name, model)
+ _attempt_consumer = None if _is_router_lead else text_consumer
try:
# CostMeter: start per-trace tracking (idempotent if already started).
if self._cost_meter is not None:
@@ -4827,7 +5483,7 @@ class BrainManager:
trace_id=trace_id,
intent_level=decision.level,
evidence_required_tool=self._evidence_required_tool,
- text_consumer=text_consumer,
+ text_consumer=_attempt_consumer,
on_progress=on_progress,
turn_context=turn_context,
reply_language=self._reply_language,
@@ -4880,6 +5536,29 @@ class BrainManager:
))
continue
+ # INTELLIGENT ROUTER fall-through: this attempt is the tool-capable
+ # router LEAD that was prepended for a tool-incapable talker. It got
+ # first crack at tool selection; if it picked NO tool (pure
+ # conversation) and a chosen talker follows in the chain, discard
+ # its answer and fall through so the user keeps their selected
+ # brain's voice. A tool it DID select (tool_calls non-empty) breaks
+ # normally below and IS the turn's result. Placed BEFORE the events
+ # publish below, so the discarded router turn is not recorded as the
+ # turn; its cost was metered above (it genuinely ran). Reversible
+ # via [brain.routing].intelligent_router (then _router_lead_key is
+ # never set, so this never fires).
+ if (
+ self._router_lead_key == (prov_name, model)
+ and not tool_calls_executed
+ and idx < len(chain) - 1
+ ):
+ log.info(
+ "Intelligent router: %s picked no tool — falling through to "
+ "%s for the conversational answer.",
+ prov_name, chain[idx + 1][0],
+ )
+ continue
+
response_text = agg.text
# Record whether THIS (winning) turn was a fire-and-forget
# ``suppress_response`` spawn, so the voice pipeline can stay
@@ -5089,6 +5768,54 @@ class BrainManager:
return response_text
+ def inject_images_for_turn(
+ self, trace_id: UUID, images: tuple[ImageBlock, ...]
+ ) -> None:
+ """Attach ad-hoc ``images`` to the upcoming turn identified by ``trace_id``.
+
+ Used by the drag-drop intake (``jarvis/brain/drop_context.py``) so a
+ dropped picture reaches the multimodal brain. The images are consumed by
+ ``_collect_vision_images`` on that turn and never carry over. A no-op for
+ an empty tuple. ``trace_id`` is unique per turn → race-free.
+ """
+ if not images:
+ return
+ # Defensive: tolerate a manager built via __new__ (some unit tests bypass
+ # __init__), mirroring how _vision_provider is accessed via getattr.
+ if getattr(self, "_pending_turn_images", None) is None:
+ self._pending_turn_images = {}
+ self._pending_turn_images[trace_id] = tuple(images)
+
+ def add_dropped_context(
+ self, text: str, images: tuple[ImageBlock, ...] = ()
+ ) -> None:
+ """Stash drag-and-dropped content as SILENT conversation context.
+
+ A drop must NOT trigger a brain turn — the user keeps the normal speaking
+ flow, and the dropped content is simply remembered and used on the NEXT
+ real turn (a drop while idle is kept for next time; a drop mid-flow joins
+ the running context). The text is appended to history as a user-context
+ message so it is naturally in the next turn's context (and persists for
+ follow-ups); images are parked and consumed once by the next
+ ``generate`` call. getattr-guarded for managers built via ``__new__``.
+ """
+ if text and text.strip():
+ if getattr(self, "_history", None) is None:
+ self._history = []
+ self._history.append(BrainMessage(role="user", content=text.strip()))
+ if len(self._history) > 40:
+ self._history = self._history[-40:]
+ log.info(
+ "📎 DROP CONTEXT stashed: %d text chars, %d images "
+ "(history now %d msgs, pending drop images %d)",
+ len(text or ""), len(images),
+ len(getattr(self, "_history", []) or []),
+ len(getattr(self, "_pending_drop_images", ()) or ()) + len(images),
+ )
+ if images:
+ cur = getattr(self, "_pending_drop_images", ()) or ()
+ self._pending_drop_images = tuple(cur) + tuple(images)
+
async def _collect_vision_images(
self,
*,
@@ -5102,6 +5829,16 @@ class BrainManager:
Without this bridge, blobs were captured but the actual brain call
remained text-only.
"""
+ # Drag-drop: ad-hoc images injected for THIS turn win over (and bypass)
+ # the screen-vision path — a dropped picture matters, not the current
+ # screen, and it must arrive even with screen-vision off. Pop so it is
+ # used exactly once. getattr-guarded for managers built via __new__.
+ pending = getattr(self, "_pending_turn_images", None)
+ if pending:
+ injected = pending.pop(trace_id, None)
+ if injected:
+ return injected
+
vision = getattr(self, "_vision_provider", None)
vision_none = vision is None
paused = (
@@ -5857,7 +6594,6 @@ _PROVIDER_SETUP_HINTS: dict[str, str] = {
"claude-api": "ANTHROPIC_API_KEY setzen",
"openai": "OPENAI_API_KEY setzen",
"openrouter": "OPENROUTER_API_KEY setzen",
- "grok": "XAI_API_KEY setzen",
"ollama-local": "Ollama-Server starten (localhost:11434)",
"ollama-cloud": "Ollama-Cloud-Token setzen",
}
diff --git a/jarvis/brain/model_catalog.py b/jarvis/brain/model_catalog.py
index bb2a6316c0..235039516b 100644
--- a/jarvis/brain/model_catalog.py
+++ b/jarvis/brain/model_catalog.py
@@ -47,7 +47,6 @@ CATALOG_PROVIDERS: tuple[str, ...] = (
"claude-api",
"openai",
"gemini",
- "grok",
"openrouter",
)
@@ -60,7 +59,6 @@ CATALOG_PROVIDERS: tuple[str, ...] = (
_ENDPOINTS: dict[str, tuple[str, str]] = {
"claude-api": ("https://api.anthropic.com/v1/models", "x-api-key"),
"openai": ("https://api.openai.com/v1/models", "bearer"),
- "grok": ("https://api.x.ai/v1/models", "bearer"),
"gemini": (
"https://generativelanguage.googleapis.com/v1beta/models",
"query",
@@ -77,14 +75,145 @@ class ModelInfo:
label: str
+def _curated(pairs: list[tuple[str, str]]) -> list[ModelInfo]:
+ return [ModelInfo(id=i, label=lbl) for i, lbl in pairs]
+
+
+# Curated current model families per provider — the picker's fallback when the
+# live ``/v1/models`` catalog is unreachable (no/invalid key, network down). This
+# is what makes the dropdown useful for providers the user drives WITHOUT an API
+# key: Claude in particular runs via the Max subscription (OAuth), so its live
+# fetch always 401s — the user still expects to pick Fable / Opus / Sonnet /
+# Haiku. Keep these to the *current* frontier families (maintainer mandate: never
+# offer a years-old model); when a valid key exists the live catalog supersedes
+# this entirely, so a new release still shows up automatically there.
+CURATED_MODELS: dict[str, list[ModelInfo]] = {
+ "claude-api": _curated([
+ ("claude-fable-5", "Claude Fable 5"),
+ ("claude-opus-4-8", "Claude Opus 4.8"),
+ ("claude-sonnet-4-6", "Claude Sonnet 4.6"),
+ ("claude-haiku-4-5-20251001", "Claude Haiku 4.5"),
+ ]),
+ "openai": _curated([
+ ("gpt-5.5", "GPT-5.5"),
+ ("gpt-5.5-pro", "GPT-5.5 Pro"),
+ ("gpt-5.5-mini", "GPT-5.5 Mini"),
+ ]),
+ "gemini": _curated([
+ ("gemini-3.1-pro-preview", "Gemini 3.1 Pro"),
+ ("gemini-3-pro", "Gemini 3 Pro"),
+ ("gemini-3-flash-preview", "Gemini 3 Flash"),
+ ("gemini-3.5-flash", "Gemini 3.5 Flash"),
+ ("gemini-flash-lite-latest", "Gemini Flash Lite"),
+ ]),
+ "openrouter": _curated([
+ ("anthropic/claude-opus-4.8", "Claude Opus 4.8"),
+ ("anthropic/claude-sonnet-4.6", "Claude Sonnet 4.6"),
+ ("anthropic/claude-haiku-4.5", "Claude Haiku 4.5"),
+ ("openai/gpt-5.5", "GPT-5.5"),
+ ("google/gemini-3-pro-preview", "Gemini 3 Pro"),
+ ("x-ai/grok-4.3", "Grok 4.3"),
+ ]),
+}
+
+
@dataclass(frozen=True, slots=True)
class CatalogResult:
"""The model list for one provider, with an honest provenance flag."""
provider: str
models: tuple[ModelInfo, ...]
- source: str # "live" | "cache" | "static"
+ source: str # "live" | "cache" | "static" | "curated"
fetched_at: float
+ selects: str = "model" # what the picker writes: "model" | "voice"
+
+
+def _ids(ids: list[str]) -> list[ModelInfo]:
+ return [ModelInfo(id=i, label=i) for i in ids]
+
+
+# TTS catalogs — for most TTS providers the user-facing pick is the VOICE
+# (Gemini Charon/Kore, Grok leo/rex, OpenAI alloy/nova, Google Neural2 names);
+# Cartesia's meaningful pick is its MODEL (sonic-3.5). The ``[tts]`` config is a
+# single block (voice_de/voice_en/model), so the picker only renders on the
+# ACTIVE TTS card and sets the global value.
+TTS_CATALOG: dict[str, tuple[str, list[ModelInfo]]] = {
+ "gemini-flash-tts": ("voice", _ids([
+ "Charon", "Kore", "Aoede", "Orus", "Iapetus",
+ "Rasalgethi", "Algenib", "Algieba", "Fenrir",
+ ])),
+ "grok-voice": ("voice", _ids(["leo", "rex", "sal", "ara", "eve"])),
+ "openai-tts": ("voice", _ids([
+ "alloy", "ash", "ballad", "coral", "echo",
+ "fable", "onyx", "nova", "sage", "shimmer",
+ ])),
+ "google-neural2": ("voice", _ids([
+ "en-US-Neural2-A", "en-US-Neural2-C", "en-US-Neural2-D", "en-US-Neural2-F",
+ "de-DE-Neural2-B", "de-DE-Neural2-C", "de-DE-Neural2-D", "de-DE-Neural2-F",
+ ])),
+ "cartesia": ("model", _ids(["sonic-3.5", "sonic-2", "sonic-turbo"])),
+}
+
+# STT model catalogs (the ``[stt] model`` is a single global value).
+STT_CATALOG: dict[str, list[ModelInfo]] = {
+ "groq-api": _ids(["whisper-large-v3", "whisper-large-v3-turbo", "distil-whisper-large-v3-en"]),
+ "faster-whisper": _ids([
+ "distil-large-v3", "large-v3", "large-v3-turbo", "medium", "small", "base", "tiny",
+ ]),
+ "openai-api": _ids(["gpt-4o-transcribe", "gpt-4o-mini-transcribe", "whisper-1"]),
+ "deepgram": _ids(["nova-3", "nova-2", "nova-2-general", "enhanced", "base"]),
+}
+
+
+@dataclass(frozen=True, slots=True)
+class CatalogSpec:
+ """Per-provider picker spec: which tier, what it selects, the curated list,
+ and whether a live ``/v1/models`` fetch is available (brain providers only)."""
+
+ tier: str # "brain" | "tts" | "stt"
+ selects: str # "model" | "voice"
+ curated: tuple[ModelInfo, ...]
+ live: bool
+
+
+def _build_provider_catalog() -> dict[str, CatalogSpec]:
+ cat: dict[str, CatalogSpec] = {}
+ # The 5 live-fetchable API brains.
+ for p in CATALOG_PROVIDERS:
+ cat[p] = CatalogSpec("brain", "model", tuple(CURATED_MODELS.get(p, ())), live=True)
+ # Codex — subagent model catalog for the ChatGPT-login worker; no /v1/models
+ # over OAuth, so curated only. Its model is the OpenAI/codex gpt-5.5 family.
+ cat["codex"] = CatalogSpec("brain", "model", tuple(_curated([
+ ("gpt-5.5", "GPT-5.5"),
+ ("gpt-5.5-pro", "GPT-5.5 Pro"),
+ ("gpt-5.5-codex", "GPT-5.5 Codex"),
+ ("gpt-5.5-mini", "GPT-5.5 Mini"),
+ ])), live=False)
+ # Antigravity — subagent model catalog for the official agy/gemini CLI
+ # (OAuth login); no /v1/models over OAuth, so curated only. Flash first =
+ # the fast default; Pro is the deep option. Both are valid gemini-CLI ids.
+ # NOTE (verified live 2026-06-21, agy 1.0.10): the agy CLI IGNORES the chosen
+ # model — neither ``--model`` nor ``settings.json model.name`` overrides it
+ # (a bogus name still answers), so agy always runs its IDE-configured default.
+ # The selection here therefore only takes effect on the gemini-CLI fallback
+ # path (and any future agy that honors the flag); for agy it is informational.
+ cat["antigravity"] = CatalogSpec("brain", "model", tuple(_curated([
+ ("gemini-3.5-flash", "Gemini 3.5 Flash"),
+ ("gemini-3.1-pro-preview", "Gemini 3.1 Pro"),
+ ])), live=False)
+ for p, (selects, opts) in TTS_CATALOG.items():
+ cat[p] = CatalogSpec("tts", selects, tuple(opts), live=False)
+ for p, opts in STT_CATALOG.items():
+ cat[p] = CatalogSpec("stt", "model", tuple(opts), live=False)
+ return cat
+
+
+PROVIDER_CATALOG: dict[str, CatalogSpec] = _build_provider_catalog()
+
+
+def catalog_spec(provider: str) -> CatalogSpec | None:
+ """The picker spec for ``provider`` (None if it has no catalog)."""
+ return PROVIDER_CATALOG.get(provider)
# ----------------------------------------------------------------------
@@ -246,19 +375,33 @@ class ModelCatalog:
) -> CatalogResult:
"""Return the catalog for ``provider`` with an honest ``source`` flag.
- Fresh cache → ``cache`` (no network). Otherwise fetch → ``live`` (cache
- updated). Fetch failure → the last cache entry (``cache``, even if stale)
- or, if there is none, a maintained ``static`` fallback so the dropdown is
- never empty.
+ Brain providers with a live endpoint: fresh cache → ``cache`` (no
+ network); else fetch → ``live`` (cache updated); fetch failure → stale
+ cache or the curated ``static`` fallback. TTS/STT providers (and Codex)
+ have no ``/v1/models`` endpoint → the curated catalog (``curated``). The
+ ``selects`` field tells the UI whether it picks a model or a voice.
"""
+ spec = catalog_spec(provider)
+ if spec is None:
+ return CatalogResult(provider, (), "static", 0.0, "model")
+
+ # TTS / STT / Codex: curated list only (no live endpoint). Returned as-is
+ # (no brain-model filtering/sorting — voices and STT models are not brain
+ # models and must keep their curated order).
+ if not spec.live:
+ return CatalogResult(
+ provider=provider,
+ models=tuple(spec.curated),
+ source="curated",
+ fetched_at=0.0,
+ selects=spec.selects,
+ )
+
async with self._lock:
cached = self._cache.get(provider)
if cached and not force_refresh and self._is_fresh(cached[0]):
return CatalogResult(
- provider=provider,
- models=self._present(provider, cached[1]),
- source="cache",
- fetched_at=cached[0],
+ provider, self._present(provider, cached[1]), "cache", cached[0], "model",
)
try:
@@ -267,27 +410,18 @@ class ModelCatalog:
log.info("Model catalog fetch for %s failed: %s", provider, exc)
if cached:
return CatalogResult(
- provider=provider,
- models=self._present(provider, cached[1]),
- source="cache",
- fetched_at=cached[0],
+ provider, self._present(provider, cached[1]), "cache", cached[0], "model",
)
static = self._static_fallback(provider)
return CatalogResult(
- provider=provider,
- models=self._present(provider, static),
- source="static",
- fetched_at=0.0,
+ provider, self._present(provider, static), "static", 0.0, "model",
)
now = time.time()
self._cache[provider] = (now, models)
self._save_cache()
return CatalogResult(
- provider=provider,
- models=self._present(provider, models),
- source="live",
- fetched_at=now,
+ provider, self._present(provider, models), "live", now, "model",
)
# -- network -------------------------------------------------------
@@ -328,11 +462,16 @@ class ModelCatalog:
# -- static fallback ----------------------------------------------
def _static_fallback(self, provider: str) -> list[ModelInfo]:
- """The maintained frontier defaults for ``provider`` (router + deep).
+ """The curated current model family for ``provider``.
- Only used when the live catalog is unreachable AND there is no cache —
- so the picker still shows the known-good models rather than nothing.
+ Used when the live catalog is unreachable AND there is no cache — so the
+ picker still offers a full, useful selection (esp. Claude via Max, whose
+ live fetch always 401s). Falls back to the maintained tier defaults for
+ any provider not in :data:`CURATED_MODELS`.
"""
+ curated = CURATED_MODELS.get(provider)
+ if curated:
+ return list(curated)
try:
from jarvis.brain.manager import TIER_DEFAULTS_BY_PROVIDER
except Exception: # noqa: BLE001
diff --git a/jarvis/brain/resolver.py b/jarvis/brain/resolver.py
index 7ed248b848..2670e9d9cd 100644
--- a/jarvis/brain/resolver.py
+++ b/jarvis/brain/resolver.py
@@ -7,9 +7,9 @@ provider** — dynamically, without hardcoded model names.
Multi-provider requirement (see memory ``feedback_brain_providers.md``):
background generation tasks (BioGenerator, persona descriptions,
skill authoring) MUST respect the provider chosen by the user.
-A user who only has a Grok API key gets a Grok bio. A user who has
-Claude configured gets Opus 4.7. Never hardcode model names such as
-``claude-opus-4-7`` directly in code.
+A user who only has a Gemini API key gets a Gemini bio. A user who has
+Claude configured gets Opus. Never hardcode model names such as
+``claude-opus-4-8`` directly in code.
Fallback order:
diff --git a/jarvis/brain/router.py b/jarvis/brain/router.py
index 1bf252c1ed..5accdf5069 100644
--- a/jarvis/brain/router.py
+++ b/jarvis/brain/router.py
@@ -91,8 +91,9 @@ Du bist der Dispatcher. Du sortierst nach AUFWAND, nicht nach Thema:
- LEICHT — Smalltalk, einfache Fakten, alles in 1-2 Saetzen Beantwortbare:
antworte DIREKT ohne Tool-Call.
- MITTEL — alles, was du mit deinen eigenen Tools in DIESEM Turn erledigen
- kannst (search_web fuer News-/Wissens-/Recherchefragen, Plugin-Tools fuer
- Mail/Kalender-Reads, cli_*-Tools, run_shell, computer_use, wiki-recall):
+ kannst (search_web NUR fuer FRISCHE/aktuelle Fakten wie News/Preise/Wetter,
+ Plugin-Tools fuer Mail/Kalender-Reads, cli_*-Tools, run_shell, computer_use,
+ wiki-recall):
mach es SELBST. Denk ruhig einen Moment nach und mach 2-3 Tool-Calls —
das ist IMMER schneller als eine Hintergrund-Mission. KEIN spawn_worker.
- SCHWER — nur echte Brocken: rufe spawn_worker mit der User-Utterance
@@ -118,13 +119,33 @@ SPAWN-CRITERIA — spawn_worker ist NUR fuer wirklich schwere Aufgaben:
DO-NOT-SPAWN — antworte direkt oder erledige es selbst mit Tools, WENN:
• Greeting, Smalltalk, Zeit/Wetter/Faktenfrage aus dem Gedaechtnis
beantwortbar
- • News-, Wissens- oder einfache Recherchefrage → search_web inline
+ • Evergreen-/Allgemeinwissen (Geografie, Geschichte, "wie funktioniert X",
+ allgemeine Ablaeufe wie "was muss ich beim Auswandern beachten") → direkt
+ aus dem Kopf, OHNE search_web
+ • Frage nach FRISCHEN Fakten (aktuelle News, Preise, Wetter) → search_web inline
• Einzelner Read auf einem verbundenen Dienst (Kalender, Mail, Issue)
• Klarfrage an den User
• Status-Bestaetigung
Eine Hintergrund-Mission braucht MINUTEN; deine Inline-Antwort braucht
Sekunden. Spawne nur, wenn die Aufgabe diese Minuten wirklich wert ist.
+RECHERCHE-DISZIPLIN (search_web — Frische-Grenze, wann NICHT, wann doch):
+Dein eigenes Wissen ist gross. EVERGREEN- und Allgemeinwissen beantwortest du
+DIREKT aus dem Kopf, OHNE search_web: Geografie, Geschichte, Definitionen, "wie
+funktioniert X", allgemeine Ablaeufe und Vorgehensweisen (z.B. "was muss ich
+beim Auswandern nach Melbourne beachten"), Erklaerungen und Vergleiche bekannter
+Dinge. Auch wenn so eine Antwort ein paar Saetze braucht: das ist DEINE Antwort,
+kein Tool-Call.
+search_web rufst du NUR, wenn die Antwort FRISCHE oder volatile Fakten braucht,
+die sich seit deinem Wissensstand geaendert haben koennen: aktuelle News,
+heutige Preise/Boersenkurse, Wetter, Sport-Ergebnisse, laufende Ereignisse,
+"neueste/aktuelle/heute/gerade" — ODER wenn Ruben AUSDRUECKLICH zu suchen bittet
+("such mal", "google das", "recherchier"). Im Zweifel bei einer Wissensfrage:
+erst direkt antworten, nicht reflexhaft suchen. Eine reine "was ist X"- oder
+"erklaer mir X"-Frage ist KEIN automatischer Suchgrund — der Run-Inspector
+zeigt jeden search_web-Call als "Recherche", und unnoetige Recherche bei
+einfachen Fragen ist explizit unerwuenscht.
+
PLUGIN-TOOLS — verbundene Dienste (Tool-Name "<plugin>/<aktion>", z.B.
google-calendar/list_events, notion/search, github/get_issue):
• Lese-Anfragen (Kalender ansehen, Mails/Notizen durchsuchen, Issue lesen)
@@ -238,11 +259,13 @@ Du sortierst jede Ruben-Nachricht in genau eine von drei Kategorien:
- Bildschirm beschreiben: "was siehst du auf meinem Screen" (screenshot)
- "merk dir X": KEIN Tool — beginne deine Antwort mit "Notiert" (siehe
MERKEN-Sektion oben); die Memory-Pipeline speichert es im Hintergrund.
- - News / Wissensfrage / Web-Recherche ("was sind die aktuellsten News",
- "google das mal", "such im Netz", "was ist X"): rufe search_web mit
- einer praezisen query auf und antworte direkt aus den Ergebnissen.
- Reicht ein Suchlauf nicht, verfeinere die query und such noch einmal —
- immer noch KEIN spawn_worker.
+ - FRISCHE/aktuelle Fakten oder ausdrueckliche Web-Suche ("was sind die
+ aktuellsten News", "google das mal", "such im Netz", "aktueller
+ Bitcoin-Preis", "heutiges Wetter"): rufe search_web mit einer praezisen
+ query auf und antworte direkt aus den Ergebnissen. Reicht ein Suchlauf
+ nicht, verfeinere die query und such noch einmal — immer noch KEIN
+ spawn_worker. EVERGREEN-Wissen ("was ist X", "erklaer mir X", allgemeine
+ Ablaeufe) beantwortest du dagegen DIREKT aus deinem Wissen, OHNE search_web.
3. SPAWN_WORKER — NUR fuer wirklich schwere Brocken.
Delegiere, wenn die Aufgabe ein Arbeitsergebnis baut oder viele Schritte
diff --git a/jarvis/brain/streaming.py b/jarvis/brain/streaming.py
index 2920f4cf98..e8db317f85 100644
--- a/jarvis/brain/streaming.py
+++ b/jarvis/brain/streaming.py
@@ -6,6 +6,7 @@ we need an accumulator that collects text + tool-calls + usage.
"""
from __future__ import annotations
+import json
from collections.abc import AsyncIterator, Callable
from dataclasses import dataclass, field
from typing import Any
@@ -51,9 +52,128 @@ async def aggregate(stream: AsyncIterator[BrainDelta]) -> StreamingAggregate:
return agg
+#: Defensive ceiling on the early-stop scan. A CU action / planner response is
+#: bounded by max_tokens (256 / 512 -> a few KB), so this is far above any real
+#: payload; above it we skip the scan (degrade to the full aggregate) so a
+#: misbehaving provider streaming prose before the JSON cannot make the
+#: per-delta scan quadratic.
+_MAX_JSON_SCAN_CHARS = 16_384
+
+
+def _has_complete_json_action(text: str) -> bool:
+ """True when ``text`` already contains a complete, parseable top-level JSON
+ object or array (an early-stop boundary for a Computer-Use action call).
+
+ Scans from the first structural opener (``{`` or ``[``), tolerating any
+ leading ```` ```json ```` fence or prose, and tracks bracket depth while
+ respecting string literals and escapes — so a ``}`` or ``]`` *inside* a
+ string value is never mistaken for the end. The candidate span is then
+ verified with ``json.loads`` so a balanced-but-invalid prefix can never
+ trigger a premature stop. Deterministic, no LLM call.
+
+ Returns ``False`` (no early stop) for text above ``_MAX_JSON_SCAN_CHARS`` —
+ the full aggregate then completes the read. Safe because that ceiling is far
+ above any real action/planner payload.
+ """
+ if len(text) > _MAX_JSON_SCAN_CHARS:
+ return False
+ start = -1
+ for i, ch in enumerate(text):
+ if ch == "{" or ch == "[":
+ start = i
+ break
+ if start < 0:
+ return False
+ depth = 0
+ in_str = False
+ escape = False
+ end = -1
+ for i in range(start, len(text)):
+ ch = text[i]
+ if in_str:
+ if escape:
+ escape = False
+ elif ch == "\\":
+ escape = True
+ elif ch == '"':
+ in_str = False
+ continue
+ if ch == '"':
+ in_str = True
+ elif ch == "{" or ch == "[":
+ depth += 1
+ elif ch == "}" or ch == "]":
+ depth -= 1
+ if depth == 0:
+ end = i
+ break
+ if end < 0:
+ return False
+ try:
+ json.loads(text[start : end + 1])
+ except (ValueError, TypeError):
+ return False
+ return True
+
+
+async def _aclose_quietly(stream: AsyncIterator[BrainDelta]) -> None:
+ """Best-effort close of an async stream after an early stop, so the
+ provider connection/generator is released. Never raises."""
+ aclose = getattr(stream, "aclose", None)
+ if aclose is None:
+ return
+ try:
+ await aclose()
+ except Exception: # noqa: BLE001, S110 — closing must not surface upstream
+ pass
+
+
+async def aggregate_first_json(
+ stream: AsyncIterator[BrainDelta],
+) -> StreamingAggregate:
+ """Like :func:`aggregate`, but stops the moment the accumulated text holds a
+ complete top-level JSON object/array — then closes the stream.
+
+ Computer-Use action/plan calls return a small JSON action; waiting for the
+ provider's terminal ``finish_reason`` (or a rambling tail up to ``max_tokens``)
+ is pure latency on the loop's #1 cost path (THINK). This consumes deltas
+ identically to ``aggregate`` until the first *parseable* JSON boundary, so the
+ returned ``text`` is byte-identical to what ``aggregate`` would have collected
+ up to that point, and the downstream action parser sees the same payload.
+
+ Provider-agnostic (every provider yields ``BrainDelta``), deterministic, no
+ LLM call. If the stream never produces a complete JSON (e.g. a prose refusal),
+ it falls back to draining the whole stream exactly like ``aggregate``.
+
+ Note: a terminal ``finish_reason``/``usage`` delta that arrives *after* the
+ JSON is intentionally not awaited — callers that need usage/cost telemetry on
+ the full generation must use ``aggregate`` instead. The CU action path reads
+ only ``text``.
+ """
+ agg = StreamingAggregate()
+ async for delta in stream:
+ if delta.content:
+ agg.text += delta.content
+ if delta.tool_call:
+ agg.tool_calls.append(dict(delta.tool_call))
+ if delta.finish_reason:
+ agg.finish_reason = delta.finish_reason
+ if delta.usage:
+ for k, v in delta.usage.items():
+ agg.usage[k] = agg.usage.get(k, 0) + int(v)
+ # Only run the O(n) scan when this chunk could have *closed* a structure.
+ if delta.content and ("}" in delta.content or "]" in delta.content):
+ if _has_complete_json_action(agg.text):
+ await _aclose_quietly(stream)
+ break
+ return agg
+
+
async def aggregate_with_consumer(
stream: AsyncIterator[BrainDelta],
text_consumer: Callable[[str], None] | None,
+ *,
+ delta_consumer: Callable[[BrainDelta], None] | None = None,
) -> StreamingAggregate:
"""Like ``aggregate`` — but emits every text chunk live to ``text_consumer``.
@@ -64,6 +184,11 @@ async def aggregate_with_consumer(
"""
agg = StreamingAggregate()
async for delta in stream:
+ if delta_consumer is not None:
+ try:
+ delta_consumer(delta)
+ except Exception: # noqa: BLE001
+ pass
if delta.content:
agg.text += delta.content
if text_consumer is not None:
@@ -135,6 +260,7 @@ def is_length_truncated(finish_reason: str | None, text: str) -> bool:
__all__ = [
"StreamingAggregate",
"aggregate",
+ "aggregate_first_json",
"aggregate_with_consumer",
"tee_text",
"is_length_truncated",
diff --git a/jarvis/brain/tool_use_loop.py b/jarvis/brain/tool_use_loop.py
index 77eaf85945..9040154f5d 100644
--- a/jarvis/brain/tool_use_loop.py
+++ b/jarvis/brain/tool_use_loop.py
@@ -411,6 +411,9 @@ class ToolUseLoop:
except Exception: # noqa: BLE001
log.debug("on_progress callback raised (ignored)", exc_info=True)
+ def _delta_progress(_delta: object) -> None:
+ _progress()
+
while True:
req = BrainRequest(
messages=tuple(current_messages),
@@ -421,7 +424,11 @@ class ToolUseLoop:
)
stream = self._brain.complete(req)
if text_consumer is not None:
- agg = await aggregate_with_consumer(stream, text_consumer)
+ agg = await aggregate_with_consumer(
+ stream,
+ text_consumer,
+ delta_consumer=_delta_progress,
+ )
else:
agg = await aggregate(stream)
# A model round finished — the brain is alive and working. Reset the
diff --git a/jarvis/brain/voice_command_gate.py b/jarvis/brain/voice_command_gate.py
index 1643be53cd..e89019610b 100644
--- a/jarvis/brain/voice_command_gate.py
+++ b/jarvis/brain/voice_command_gate.py
@@ -28,7 +28,6 @@ _PROVIDER_ALIASES = (
"gemini",
"claude",
"openai",
- "grok",
"gpt",
)
@@ -69,15 +68,120 @@ _FAST_PATTERNS = (
"nimm haiku", "use haiku", "schnell-modus", "think fast",
)
+# Reply-language switch (added 2026-06-22, broadened after forensic #2). A
+# config change like "stell auf Englisch um" / "antworte auf Spanisch" /
+# "respond in German" must be a DETERMINISTIC, provider-independent action (set
+# brain.reply_language directly) — not an LLM tool-choice, never a worker
+# mission. A language word ALONE never matches; it needs an intent marker:
+# (a) an unambiguous CHANGE verb (umstell/umänder/wechsel/änder/switch/change),
+# (b) a bare imperative SPEAK verb (sprich/speak <lang>), or
+# (c) an OUTPUT verb (antwort/respond/reply/answer/rede/set/stell/mach) plus a
+# directional preposition (auf/in/zu/to <lang>).
+# So "wie heißt das auf Englisch?", "ich spreche Englisch", "auf Deutsch klingt
+# das besser", "erzähl mir was auf Englisch" still fall through to the brain.
+_LANG_ALIASES: dict[str, str] = {
+ "englisch": "en", "english": "en",
+ "deutsch": "de", "german": "de",
+ "spanisch": "es", "spanish": "es", "español": "es", "espanol": "es", "castellano": "es",
+ "automatisch": "auto", "automatik": "auto", "automatic": "auto", "auto": "auto",
+}
+# (a) Unambiguous change verbs — incl. German separable forms ("umändern",
+# "umstellen") whose "um" prefix breaks a plain "\bänder" boundary.
+_LANG_CHANGE_VERB = re.compile(
+ r"\b(?:um(?:stell|schalt|änder|aender|stellung)\w*|wechsel\w*|wechsle"
+ r"|änder\w*|aender\w*|switch\w*|change\w*)\b",
+ re.IGNORECASE,
+)
+# (b) Imperative speak verbs — match directly (no preposition needed):
+# "sprich Englisch", "speak English". German "spreche/spricht" (statements) are
+# intentionally NOT matched.
+_LANG_IMPERATIVE_SPEAK = re.compile(r"\b(?:sprich|speak\w*)\b", re.IGNORECASE)
+# (c) Output / request verbs — need a directional preposition to anchor the
+# language as the OUTPUT target. "respond in X", "antworte auf X", "rede auf X",
+# "set/stell … auf/to X", "mach … auf X".
+_LANG_OUTPUT_VERB = re.compile(
+ r"\b(?:antwort\w*|respond\w*|repl(?:y|ies)|answer\w*|rede|reden|set|stell\w*"
+ r"|mach\w*)\b",
+ re.IGNORECASE,
+)
+_LANG_PREP = re.compile(r"\b(?:auf|zu|to|in|on)\b", re.IGNORECASE)
+
+
+def _match_language_switch(t: str) -> str | None:
+ code: str | None = None
+ for word, c in _LANG_ALIASES.items():
+ if re.search(rf"\b{re.escape(word)}\b", t):
+ code = c
+ break
+ if code is None:
+ return None
+ if _LANG_CHANGE_VERB.search(t):
+ return code
+ if _LANG_IMPERATIVE_SPEAK.search(t):
+ return code
+ if _LANG_OUTPUT_VERB.search(t) and _LANG_PREP.search(t):
+ return code
+ return None
+
+
+# Sub-agent / Heavy-Task-worker provider switch (added 2026-06-22). Sibling of
+# the main provider_switch, but for [brain.sub_jarvis].provider — the worker
+# that runs heavy missions, NOT the router brain. The gate stays pure: it only
+# recognises the intent + the spoken provider word; the manager handler maps it
+# to a canonical subagent slug, validates, and persists via the 3-layer writer
+# (config-soll pinned) so the drift-guard cannot revert it. A sub-agent
+# QUALIFIER is required, so a bare "switch to gemini" still means the main brain.
+_SUBAGENT_QUALIFIER = re.compile(
+ r"\b(?:sub[-\s]?agent|subagent|sub[-\s]?jarvis|subjarvis|worker|helfer|helper)\b",
+ re.IGNORECASE,
+)
+# Longer variants first so "openai-codex" wins over "openai".
+_SUBAGENT_PROVIDER_WORDS = (
+ "openai-codex", "openrouter", "antigravity", "chatgpt", "anthropic",
+ "claude", "gemini", "openai", "codex", "gpt",
+)
+_SUBAGENT_SWITCH_VERB = re.compile(
+ r"\b(?:wechsel[n]?|wechsle|umstell\w*|umschalt\w*|stell\w*|set|switch|change|nimm|mach)\b",
+ re.IGNORECASE,
+)
+_SUBAGENT_PREP = re.compile(r"\b(?:auf|zu|to)\b", re.IGNORECASE)
+_SUBAGENT_PROVIDER_NOUN = re.compile(r"\b(?:provider|anbieter)\b", re.IGNORECASE)
+
+
+def _match_subagent_switch(t: str) -> str | None:
+ if not _SUBAGENT_QUALIFIER.search(t):
+ return None
+ for word in _SUBAGENT_PROVIDER_WORDS:
+ if re.search(rf"\b{re.escape(word)}\b", t):
+ # An explicit change verb is an unambiguous command. Otherwise accept
+ # only "... provider auf/to <X>" (a noun + preposition) so a STATEMENT
+ # like "der Sub-Agent läuft auf Gemini" (no verb, no 'provider' word)
+ # falls through to the brain instead of silently switching.
+ if _SUBAGENT_SWITCH_VERB.search(t):
+ return word
+ if _SUBAGENT_PREP.search(t) and _SUBAGENT_PROVIDER_NOUN.search(t):
+ return word
+ return None
+ return None
+
@dataclass(frozen=True)
class VoiceCommandMatch:
"""Result of a gate match.
- kind: Class of the recognised command.
- - target: Only populated for provider_switch (provider alias).
+ - target: provider alias (provider_switch), the reply-language code
+ de/en/es/auto (language_switch), or the spoken sub-agent provider word
+ (subagent_switch — the manager maps it to a canonical slug).
"""
- kind: Literal["provider_switch", "cancel", "depth_deep", "depth_fast"]
+ kind: Literal[
+ "provider_switch",
+ "subagent_switch",
+ "language_switch",
+ "cancel",
+ "depth_deep",
+ "depth_fast",
+ ]
target: str = ""
@@ -91,11 +195,23 @@ def match_voice_command(text: str) -> VoiceCommandMatch | None:
if _CANCEL_PATTERN.search(t):
return VoiceCommandMatch(kind="cancel")
+ # Sub-agent provider switch BEFORE the main provider switch: a sub-agent
+ # qualifier ("switch the SUB-AGENT provider to X") must target the worker,
+ # not the router brain.
+ sub = _match_subagent_switch(t)
+ if sub:
+ return VoiceCommandMatch(kind="subagent_switch", target=sub)
+
# Provider-Switch
m = _PROVIDER_PATTERN.search(t)
if m:
return VoiceCommandMatch(kind="provider_switch", target=m.group("provider"))
+ # Reply-language switch (deterministic — never an LLM tool-choice / spawn).
+ lang = _match_language_switch(t)
+ if lang:
+ return VoiceCommandMatch(kind="language_switch", target=lang)
+
# Depth-Override
for p in _DEEP_PATTERNS:
if p in t:
diff --git a/jarvis/cli_ctl/commands/brain.py b/jarvis/cli_ctl/commands/brain.py
index d92421baa4..f8de334f4f 100644
--- a/jarvis/cli_ctl/commands/brain.py
+++ b/jarvis/cli_ctl/commands/brain.py
@@ -17,7 +17,7 @@ app = typer.Typer(
)
_PROVIDER_HELP = (
- "Provider id: claude-api | openrouter | openai | gemini | grok | codex | "
+ "Provider id: claude-api | openrouter | openai | gemini | codex | "
"antigravity (the server validates the value)."
)
diff --git a/jarvis/core/config.py b/jarvis/core/config.py
index c00d0c3e32..6a1bd466fb 100644
--- a/jarvis/core/config.py
+++ b/jarvis/core/config.py
@@ -228,6 +228,17 @@ class STTConfig(BaseModel):
# faster-whisper path also tolerates "cuda" with a no-CUDA runtime fallback.
device: str = "cpu"
compute_type: str = "int8_float16"
+ # The LOCAL wake-match / live-preview Whisper (distinct from ``model``, which
+ # is the post-wake utterance model — often a cloud provider). It only powers
+ # wake-phrase transcript matching + the listening-bubble probe, both
+ # latency-tolerant, so it defaults to a small model on CPU. This matters a
+ # lot for boot: on a Blackwell GPU (RTX 50xx) CTranslate2 JIT-compiles kernels
+ # at model-load, costing ~71 s on CUDA vs ~0.45 s for ``base`` on CPU — the
+ # dominant warm-up cost. CPU is also the cloud-first floor (no GPU assumed).
+ # Power users on an older GPU may set ``wake_device = "cuda"``.
+ wake_model: str = "base"
+ wake_device: str = "cpu"
+ wake_compute_type: str = "int8"
language: str = "auto"
# Vocabulary biasing passed to Whisper's ``prompt`` field — the same
# mechanism dictation tools like a dictation app use to keep proper nouns and
@@ -296,6 +307,8 @@ class TTSConfig(BaseModel):
class BrainProviderConfig(BaseModel):
model: str | None = None
deep_model: str | None = None # Optional: stronger reasoning model
+ cu_model: str | None = None # Optional: model the Computer-Use loop uses
+ # (Phase 3). None -> use this provider's `model`.
auth_mode: str | None = None # "oauth" | "api_key"
base_url: str | None = None
# Latency sprint 1 (2026-04-30): Gemini thinking budget per provider tier.
@@ -436,6 +449,22 @@ class BrainRoutingConfig(BaseModel):
# heuristic. Default is "strict" per user mandate 2026-05-14.
force_spawn_mode: str = "strict"
+ # Intelligent router (2026-06-21 user mandate "Jarvis must choose wisely among
+ # ALL tools, like Claude Code"). When the ACTIVE talker cannot emit tool_calls
+ # at runtime (the subscription-CLI brains — Antigravity over the Google login,
+ # Codex over the ChatGPT login — drop ALL tools), a tool-capable provider
+ # (the deep_brain / router, e.g. Gemini) leads every SUBSTANTIVE turn and the
+ # LLM itself picks the tool via its tool-use loop + the router system prompt —
+ # no signal-word list decides the tool. If the router picks NO tool (pure
+ # conversation), the turn FALLS THROUGH to the chosen talker so the user keeps
+ # their selected brain's voice. Tool-capable talkers are unaffected (they
+ # already pick tools in their own loop). The deterministic gates (force-spawn,
+ # match_local_action, on-screen, build-artifact) remain as HIGH-PRECISION
+ # guardrails for the obvious cases. This flag is the reversible kill switch:
+ # set false → exactly the prior behaviour (the narrower action-intent
+ # delegation). See manager._build_fallback_chain / the router fall-through.
+ intelligent_router: bool = True
+
# Heavy-research force-spawn (live bug 2026-06-14, the Berlin→Melbourne
# turn): a multi-step research/analysis request must be OFFLOADED to a
# background mission, not run inline on the deep brain where it blows the
@@ -654,6 +683,15 @@ class BrainConfig(BaseModel):
default_factory=EvidenceDomainsConfig,
)
healthcheck_on_start: bool = True
+ # Frontier model auto-switch (Phase F.3). When True, the boot hook
+ # ``apply_frontier_resolution`` queries each provider's /v1/models and may
+ # rewrite ``[brain.providers.<p>].model`` to a newer model on every start.
+ # Default False (2026-06-20, user mandate "providers must NOT switch by
+ # themselves"): the boot hook becomes a no-op and the configured models are
+ # kept verbatim. A newer model is only ever adopted by an explicit user pick
+ # in the per-provider model picker. Flip to True to restore the old
+ # auto-frontier behaviour.
+ frontier_auto_apply: bool = False
# Two-turn spoken confirmation (forensic 2026-06-18): on a conversational
# turn a consequential ``ask``-tier tool (e.g. gmail send) is deferred into a
# spoken "Soll ich das wirklich tun? Sag ja." instead of blocking on a UI
@@ -909,7 +947,7 @@ class OpenClawConfig(BaseModel):
Deliberately NO Anthropic lock in the ``model`` default: an empty ``model``
means the bridge resolves the frontier-pro of the active Personal Jarvis
provider (``cfg.brain.primary``) via the provider-slug mapping from AD-6
- (gemini→google/gemini-..., claude-api→anthropic/..., grok→xai/...).
+ (gemini→google/gemini-..., claude-api→anthropic/..., openai→openai/...).
This way OpenClaw automatically follows the user's provider choice.
AD-21 pin-version mandate: ``version`` must be set whenever the block
@@ -989,6 +1027,11 @@ class UIConfig(BaseModel):
tray_enabled: bool = True
admin_api_port: int = 47821
startup_chime: bool = True
+ # Global master switch for all synthesized UI earcons (wake "ding",
+ # hang-up tone, boot-ready tone, "still listening" earcon). The spoken TTS
+ # voice is NOT affected — only the non-verbal effect tones. Default on;
+ # toggled live from Settings → Behavior, persisted to [ui] sound_effects.
+ sound_effects: bool = True
# Interface (display) language of the whole app — every label, button and
# message. The backend home for what used to be a frontend-only localStorage
# value, so a voice command or the Control API can change it and the open UI
@@ -1247,8 +1290,8 @@ class BoardBioConfig(BaseModel):
Important: NO provider/model default. The bio dynamically uses the
frontier model of the currently configured primary provider
(see ``jarvis/brain/resolver.py:resolve_frontier_brain``). A user with
- only a Grok API key gets a Grok bio; a user with Claude configured gets
- Opus 4.7. Multi-provider compliance is mandatory.
+ only a Gemini API key gets a Gemini bio; a user with Claude configured gets
+ Opus. Multi-provider compliance is mandatory.
``override_provider`` / ``override_model`` are power-user fields for
explicitly pinning a model for the bio only. Leave empty in 99% of cases.
@@ -1316,6 +1359,12 @@ class ComputerUseConfig(BaseModel):
# 300_000 (no change); lowering it -- with the cu_bench harness as proof --
# shrinks the vision payload for faster inference, at some grounding risk.
image_max_bytes: int = Field(default=300_000, ge=20_000, le=2_000_000)
+ # L7 (CU speed): per-screenshot longest-side pixel cap sent to the model.
+ # Default keeps 2048 (no change). Vision models resample to ~1568 px
+ # internally, so lowering this -- with the cu_bench harness as proof -- ships
+ # fewer pixels for faster encode + upload + image-token ingest, at some
+ # grounding risk on tiny controls. 0 disables the dimension cap entirely.
+ image_max_dimension: int = Field(default=2048, ge=0, le=8192)
# L8 (CU speed): multiplier on the loop's fixed settle waits (pre-type and
# post-click-verify pauses). Default keeps 1.0 (no change: every settle is
# byte-for-byte the legacy duration); lower it -- with the cu_bench harness
@@ -1889,6 +1938,17 @@ _PERSISTED_PROVIDER_ENV_KEYS: tuple[str, ...] = (
"JARVIS__ACK_BRAIN__ENABLED",
"JARVIS__ACK_BRAIN__PROVIDER",
"JARVIS__ACK_BRAIN__FALLBACK_PROVIDER",
+ # TTS engine selection beyond the provider tier. Forensic 2026-06-22: an
+ # in-app restart inherited a stale env (JARVIS__TTS__USE_VERTEX=true /
+ # MODEL=sonic-2 / VOICE_*=leo) from a pre-change ancestor. PROVIDER above
+ # healed, but these did not, so Gemini-TTS stayed on the wrong Vertex
+ # billing path (the user had topped up the AI-Studio key, which Vertex
+ # ignores) with a bogus model name → 404 on every sentence, silent voice.
+ # Pinning them here makes a restart honour the registry's corrected values.
+ "JARVIS__TTS__MODEL",
+ "JARVIS__TTS__USE_VERTEX",
+ "JARVIS__TTS__VOICE_DE",
+ "JARVIS__TTS__VOICE_EN",
)
diff --git a/jarvis/core/config_writer.py b/jarvis/core/config_writer.py
index 611ecc0599..f8935b3c95 100644
--- a/jarvis/core/config_writer.py
+++ b/jarvis/core/config_writer.py
@@ -182,22 +182,83 @@ def set_stt_provider(name: str, *, path: Path = DEFAULT_CONFIG_FILE) -> None:
_sync_stt_provider_drift_soll(name)
-def set_codex_binary_path(binary_path: str, *, path: Path = DEFAULT_CONFIG_FILE) -> None:
- """Set ``[codex] binary_path`` to work around Windows PATH issues."""
- _patch_table(path, "codex", "binary_path", binary_path)
+def set_tts_voice(voice: str, *, path: Path = DEFAULT_CONFIG_FILE) -> None:
+ """Set the global TTS voice (``[tts] voice_de`` + ``voice_en``).
+
+ The TTS config is a single ``[tts]`` block, so this is the voice of the
+ ACTIVE TTS provider. Most generative voices are multilingual (Gemini Charon,
+ Grok leo …), so both language slots get the same value. ``voice_de`` /
+ ``voice_en`` are pinned in ``config-soll.json`` (like ``tts.provider``), so a
+ TOML-only write would be reverted by the drift-guard — we sync config-soll too.
+ """
+ _patch_table(path, "tts", "voice_de", voice)
+ _patch_table(path, "tts", "voice_en", voice)
+ try:
+ _update_config_soll_section("tts", {"voice_de": voice, "voice_en": voice})
+ except Exception as exc: # noqa: BLE001 — best-effort, must not propagate
+ log.warning("Could not sync tts voice to config-soll.json: %s", exc)
+
+def set_tts_model(model: str, *, path: Path = DEFAULT_CONFIG_FILE) -> None:
+ """Set the global TTS model (``[tts] model``) — e.g. Cartesia ``sonic-3.5``.
+
+ Synced to config-soll (drift-guard pinned, same class as the voice keys).
+ """
+ _patch_table(path, "tts", "model", model)
+ try:
+ _update_config_soll_section("tts", {"model": model})
+ except Exception as exc: # noqa: BLE001 — best-effort, must not propagate
+ log.warning("Could not sync tts.model to config-soll.json: %s", exc)
-def set_assistant_name(name: str, *, path: Path = DEFAULT_CONFIG_FILE) -> None:
- """Persist the assistant's display name to ``[persona] name`` in jarvis.toml.
- Toml-only by design: ``persona.name`` is NOT tracked in ``config-soll.json``,
- so the drift-guard never reverts it (a plain atomic write suffices). Empty
- string means "derive the name from the wake phrase" (see
- ``jarvis.brain.assistant_name.resolve_assistant_name``). Takes effect on the
- next BrainManager build (a Jarvis restart): the system prompt is assembled
- once per manager.
+def set_stt_model(model: str, *, path: Path = DEFAULT_CONFIG_FILE) -> None:
+ """Set the global STT model (``[stt] model``).
+
+ Takes effect on the next SpeechPipeline bootstrap (a voice restart): the STT
+ provider is instantiated once at pipeline start. config-soll synced (the stt
+ block is drift-guard pinned like its provider key).
"""
- _patch_table(path, "persona", "name", name)
+ _patch_table(path, "stt", "model", model)
+ try:
+ _update_config_soll_section("stt", {"model": model})
+ except Exception as exc: # noqa: BLE001 — best-effort, must not propagate
+ log.warning("Could not sync stt.model to config-soll.json: %s", exc)
+
+
+def set_tts_cartesia_model(model: str, *, path: Path = DEFAULT_CONFIG_FILE) -> None:
+ """Set Cartesia's model in its OWN sub-table ``[tts.cartesia] model_id``.
+
+ Cartesia reads its model from this sub-table (default ``sonic-3.5``), NOT the
+ global ``[tts] model`` that Gemini/OpenAI use. ``[tts.cartesia]`` is not pinned
+ in config-soll, so a plain atomic TOML write suffices (no drift-guard revert).
+ """
+ if not path.exists():
+ raise FileNotFoundError(f"Config-Datei fehlt: {path}")
+ with _WRITE_LOCK:
+ raw = path.read_text(encoding="utf-8")
+ had_bom = raw.startswith(_BOM)
+ if had_bom:
+ raw = raw[len(_BOM) :]
+ doc: TOMLDocument = tomlkit.parse(raw)
+ tts = doc.get("tts")
+ if tts is None:
+ tts = tomlkit.table()
+ doc["tts"] = tts
+ cart = tts.get("cartesia")
+ if cart is None:
+ cart = tomlkit.table()
+ tts["cartesia"] = cart
+ cart["model_id"] = model
+ out = tomlkit.dumps(doc)
+ if had_bom:
+ out = _BOM + out
+ _atomic_write(path, out)
+
+
+def set_codex_binary_path(binary_path: str, *, path: Path = DEFAULT_CONFIG_FILE) -> None:
+ """Set ``[codex] binary_path`` to work around Windows PATH issues."""
+ _patch_table(path, "codex", "binary_path", binary_path)
+
# Voice-keybind action vocabulary. Shared with the keybinds API
@@ -366,6 +427,15 @@ def set_mute_music(enabled: bool, *, path: Path = DEFAULT_CONFIG_FILE) -> None:
_patch_table(path, "ducking", "enabled", bool(enabled))
+def set_sound_effects(enabled: bool, *, path: Path = DEFAULT_CONFIG_FILE) -> None:
+ """Persist ``[ui] sound_effects`` (the global earcon master switch).
+
+ TOML-only (not drift-guarded); the Settings route applies it live by
+ mutating the shared in-memory config the speech pipeline reads.
+ """
+ _patch_table(path, "ui", "sound_effects", bool(enabled))
+
+
def set_team_proxy(
enabled: bool,
url: str,
@@ -584,7 +654,7 @@ def set_brain_provider_defaults(
is created with the supplied defaults (typically the tier defaults from
``BrainManager.TIER_DEFAULTS_BY_PROVIDER``).
- Background: providers added after the setup wizard via the UI (e.g. grok)
+ Background: providers added after the setup wizard via the UI (e.g. openrouter)
often lack a ``[brain.providers.<name>]`` block. During a switch-persist we
ensure here that after an app restart the tier-default fallback logic in
BrainManager is not needed again — the block is then cleanly persisted.
@@ -804,21 +874,34 @@ def set_brain_provider_model(
*,
model: str | None = None,
deep_model: str | None = None,
+ cu_model: str | None = None,
path: Path = DEFAULT_CONFIG_FILE,
) -> None:
"""Patch ``[brain.providers.<provider>]`` ``model`` / ``deep_model`` in
the TOML file.
- Used by the frontier auto-switch (Phase F.3, 2026-04-29) so that a detected
- frontier model change is persisted in jarvis.toml — otherwise the switch is
- lost on the next ``cfg.load_config()`` call in ``_phase2_full_brain``.
+ Used by the per-provider model picker (``PUT /api/providers/{id}/model``)
+ and the frontier auto-switch (Phase F.3) so a model change is persisted in
+ jarvis.toml — otherwise the switch is lost on the next ``cfg.load_config()``.
+
+ Three-layer persist (like ``set_brain_primary`` / ``set_sub_jarvis_provider``):
+ ``brain.providers.<p>.model`` / ``deep_model`` are pinned in
+ ``config-soll.json``, so a TOML-only write would be reverted by the
+ drift-guard within 5 minutes (BUG-010 class) — exactly the "I picked a model
+ and it flipped back" symptom. We therefore sync config-soll.json too. No ENV
+ layer is written: per-provider model keys have no effective ``JARVIS__*``
+ override (the boot override only nests on ``__`` and the drift-guard's dotted
+ ``JARVIS__BRAIN.PROVIDERS.*`` vars are inert), so adding one would only create
+ a new stale-override trap. Layer 2 is best-effort (cloud-first): a graceful
+ no-op on a headless Linux VPS, it never raises out of this function nor
+ breaks the TOML write.
Idempotent: if the block is absent it is created; ``None`` values change
nothing.
"""
if not path.exists():
raise FileNotFoundError(f"Config-Datei fehlt: {path}")
- if model is None and deep_model is None:
+ if model is None and deep_model is None and cu_model is None:
return
with _WRITE_LOCK:
@@ -846,12 +929,23 @@ def set_brain_provider_model(
block["model"] = model
if deep_model is not None:
block["deep_model"] = deep_model
+ if cu_model is not None:
+ # "" is a meaningful value (UI "use my main model") distinct from
+ # None ("leave unchanged"), so write whatever non-None was given.
+ block["cu_model"] = cu_model
out = tomlkit.dumps(doc)
if had_bom:
out = _BOM + out
_atomic_write(path, out)
+ # Layer 2 — best-effort drift-soll sync (never raises, never blocks the
+ # TOML write). Only the keys actually written are synced so the guard sees
+ # zero drift across the block.
+ _sync_brain_provider_model_drift_soll(
+ provider, model=model, deep_model=deep_model, cu_model=cu_model
+ )
+
def set_telephony_config(values: dict[str, object], *, path: Path = DEFAULT_CONFIG_FILE) -> None:
"""Patch ``[integrations.twilio]`` with the given non-secret fields.
@@ -1206,6 +1300,37 @@ def _sync_stt_provider_drift_soll(name: str) -> None:
log.warning("Could not sync %s to the User environment: %s", _STT_PROVIDER_ENV, exc)
+def _sync_brain_provider_model_drift_soll(
+ provider: str, *, model: str | None, deep_model: str | None, cu_model: str | None = None
+) -> None:
+ """Best-effort sync of ``brain.providers.<p>`` model keys into the drift-soll.
+
+ NEVER raises and NEVER breaks the (already-completed) TOML write. Only the
+ keys actually written (non-``None``) are synced, so config-soll ends up in
+ agreement with the TOML and the drift-guard reverts nothing. No ENV layer:
+ per-provider model keys have no effective ``JARVIS__*`` boot override (see
+ the docstring of :func:`set_brain_provider_model`). The flat dotted top-level
+ key ``brain.providers.<p>`` is exactly how the soll file stores it.
+ """
+ values: dict[str, object] = {}
+ if model is not None:
+ values["model"] = model
+ if deep_model is not None:
+ values["deep_model"] = deep_model
+ if cu_model is not None:
+ values["cu_model"] = cu_model
+ if not values:
+ return
+ try:
+ _update_config_soll_section(f"brain.providers.{provider}", values)
+ except Exception as exc: # noqa: BLE001 — best-effort, must not propagate
+ log.warning(
+ "Could not sync brain.providers.%s model to config-soll.json: %s",
+ provider,
+ exc,
+ )
+
+
def _update_config_soll_section(top: str, values: dict[str, object]) -> None:
"""Atomically merge ``values`` into ``data[top]`` in config-soll.json.
diff --git a/jarvis/core/protocols.py b/jarvis/core/protocols.py
index cca3240d23..a962c578a7 100644
--- a/jarvis/core/protocols.py
+++ b/jarvis/core/protocols.py
@@ -310,6 +310,13 @@ class Tool(Protocol):
schema: dict[str, Any] # JSON-Schema für LLM-Tool-Use
description: str
risk_tier: RiskTier
+ # Optional extension (recognized by RiskTierEvaluator via getattr, NOT part
+ # of the structural Protocol check): a tool with mixed actions may define
+ # def risk_tier_for_args(self, args: dict[str, Any]) -> RiskTier
+ # to refine its tier per call (e.g. gmail: reads "safe", send "ask"). The
+ # returned value is validated against the RiskTier vocabulary; blacklist and
+ # whitelist still take priority. Returning an unknown value falls back to
+ # the static ``risk_tier`` above.
async def execute(self, args: dict[str, Any], ctx: ExecutionContext) -> ToolResult:
"""Execute the action."""
diff --git a/jarvis/google_cli/pty_runner.py b/jarvis/google_cli/pty_runner.py
new file mode 100644
index 0000000000..16a96d9d2e
--- /dev/null
+++ b/jarvis/google_cli/pty_runner.py
@@ -0,0 +1,212 @@
+"""Drive a TUI agent CLI (Antigravity ``agy``) over a real pseudo-terminal.
+
+Why this exists: ``agy`` is part of the Antigravity IDE suite and behaves like a
+terminal UI. Spawned with ordinary pipes (``asyncio.create_subprocess_exec`` /
+``subprocess.PIPE``) it detects ``!isatty(stdout)`` and emits **zero bytes** —
+the brain then sees no answer. Driven over a ConPTY/PTY it renders the answer
+wrapped in ANSI control sequences + window-title OSC frames; we read that,
+strip the terminal noise, and recover the plain answer.
+
+Cross-platform via the existing AD-6 PTY seam (:func:`jarvis.terminal.backend.
+make_pty_backend` — ConPTY/pywinpty on Windows, ptyprocess on POSIX). On a host
+with no PTY backend (headless VPS) the seam returns a ``NullPtyBackend`` whose
+``spawn`` raises; we surface that as a clean ``error`` result so the brain falls
+back to the next provider instead of crashing (CLOUD.md graceful-degradation).
+
+Google ToS (hard): we only ever drive the official binary; the stored OAuth
+token is never read to make our own HTTP request.
+"""
+from __future__ import annotations
+
+import os
+import re
+import sys
+import time
+from collections.abc import Callable, Mapping
+from contextlib import suppress
+from dataclasses import dataclass
+
+# A wide terminal minimizes hard-wrap artifacts in multi-line answers (agy
+# renders to the PTY width). The brain's answers are short; the worker captures
+# its result from the git diff, not this text, so wrapping there is harmless.
+_COLS = 200
+_ROWS = 50
+_READ_SIZE = 8192
+_POLL_S = 0.05
+
+# OSC = Operating System Command (window titles): ESC ] ... terminated by BEL
+# (\x07) or ST (ESC \). agy emits these for every npm/cmd subprocess it spawns.
+_OSC_RE = re.compile(r"\x1b\][^\x07\x1b]*(?:\x07|\x1b\\)")
+# CSI = Control Sequence Introducer: ESC [ params intermediates final.
+_CSI_RE = re.compile(r"\x1b\[[0-9;?]*[ -/]*[@-~]")
+# Other 2-byte ESC sequences (charset select, keypad mode, lone ESC at EOF).
+_ESC_RE = re.compile(r"\x1b[()][AB0-2]|\x1b[=>]|\x1b")
+# Control chars to drop — everything except TAB (\x09), LF (\x0a), CR (\x0d).
+_CTRL_RE = re.compile(r"[\x00-\x08\x0b\x0c\x0e-\x1f]")
+# Braille glyphs (U+2800-U+28FF) = agy's progress spinner. It rewrites the same
+# line via a leading CR every frame ("\r⠋ Thinking...\r⠙ Thinking..."); a stray
+# glyph may also survive on the final visible line. Never part of a real answer.
+_SPINNER_RE = re.compile(r"[⠀-⣿]")
+
+
+def strip_terminal_noise(raw: str) -> str:
+ """Remove ANSI/OSC/CSI control sequences and stray control bytes.
+
+ Preserves printable text plus TAB/LF/CR; the answer text survives intact.
+ """
+ out = _OSC_RE.sub("", raw)
+ out = _CSI_RE.sub("", out)
+ out = _ESC_RE.sub("", out)
+ out = _CTRL_RE.sub("", out)
+ return out
+
+
+def extract_cli_answer(raw: str) -> str:
+ """Recover the plain answer text from a PTY-rendered CLI transcript.
+
+ Strips terminal noise, honors bare carriage returns as line-overwrites
+ (terminal semantics), drops the resulting blank/spinner lines, and trims —
+ leaving the model's answer (single- or multi-line).
+
+ The CR handling is what removes agy's progress spinner: agy renders it by
+ repeatedly rewriting the same physical line with a leading CR
+ ("\\r⠋ Fetching...\\r⠙ Fetching...\\r<answer>"), so only the text after the
+ last CR on a line survives — the transient "Fetching…"/"Thinking…" frames
+ are overwritten by the real answer and never leak into the spoken text.
+ """
+ cleaned = strip_terminal_noise(raw)
+ cleaned = cleaned.replace("\r\n", "\n") # CRLF first, so it stays a newline
+ lines: list[str] = []
+ for physical in cleaned.split("\n"):
+ # Honor bare-CR overwrites: the last non-empty CR segment is what stays
+ # on screen (a trailing lone CR overwrites nothing).
+ segments = physical.split("\r")
+ visible = next((s for s in reversed(segments) if s.strip()), "")
+ visible = _SPINNER_RE.sub("", visible) # drop any leftover spinner glyph
+ if visible.strip():
+ lines.append(visible.rstrip())
+ return "\n".join(lines).strip()
+
+
+def repair_agy_path(
+ path: str | None,
+ *,
+ is_windows: bool = sys.platform == "win32",
+ system_root: str | None = None,
+ node_dir: str | None = None,
+) -> str:
+ """Ensure the standard Windows system dirs (and optionally Node) are on PATH.
+
+ agy spawns ``cmd.exe`` + ``npm`` internally (it boots MCP servers even in
+ ``--print`` mode). Launched from a degraded environment whose PATH lacks
+ ``System32`` (forensic 2026-06-20: jarvis started by an agent runtime →
+ ``chcp nicht erkannt``), those inner spawns fail. We prepend the missing
+ standard dirs idempotently. No-op on POSIX (chcp/cmd have no analogue and
+ Node resolves via the usual prefixes).
+ """
+ if not is_windows:
+ return path or ""
+ root = system_root or os.environ.get("SystemRoot") or os.environ.get("windir") or r"C:\Windows"
+ needed = [
+ os.path.join(root, "System32"),
+ os.path.join(root, "System32", "Wbem"),
+ root,
+ ]
+ if node_dir:
+ needed.append(node_dir)
+ parts = [p for p in (path or "").split(os.pathsep) if p]
+ have = {p.rstrip("\\").lower() for p in parts}
+ prefix = [d for d in needed if d.rstrip("\\").lower() not in have]
+ if not prefix:
+ return path or ""
+ return os.pathsep.join([*prefix, *parts])
+
+
+@dataclass(frozen=True)
+class PtyRunResult:
+ """Outcome of one PTY-driven CLI run."""
+
+ text: str # extracted, cleaned answer ("" when none / on error)
+ raw: str # full raw terminal transcript (diagnostics)
+ exit_status: int | None
+ timed_out: bool
+ error: str | None # set when no PTY backend / spawn failed (else None)
+
+
+def run_cli_over_pty(
+ argv: tuple[str, ...],
+ *,
+ timeout_s: float,
+ cwd: str | None = None,
+ env: Mapping[str, str] | None = None,
+ backend: object | None = None,
+ on_spawn: Callable[[int], None] | None = None,
+ _now: Callable[[], float] = time.monotonic,
+ _sleep: Callable[[float], None] = time.sleep,
+) -> PtyRunResult:
+ """Spawn ``argv`` over a PTY, read until exit/timeout, return the answer.
+
+ ``on_spawn`` (when given) is invoked once with the child PID right after the
+ spawn — the Phase-6 worker uses it to assign the PID to its kill-on-crash
+ Job Object. ``backend`` / ``_now`` / ``_sleep`` are injectable seams for
+ tests. A missing PTY backend (or a spawn failure) returns a result with
+ ``error`` set and ``text=""`` — never raises — so the caller can fall back
+ cleanly.
+ """
+ if backend is None:
+ from jarvis.terminal.backend import make_pty_backend
+
+ backend = make_pty_backend()
+
+ try:
+ handle = backend.spawn( # type: ignore[attr-defined]
+ argv=tuple(argv), cwd=cwd, cols=_COLS, rows=_ROWS, env=env,
+ )
+ except RuntimeError as exc:
+ return PtyRunResult(text="", raw="", exit_status=None, timed_out=False, error=str(exc))
+
+ if on_spawn is not None:
+ with suppress(Exception):
+ on_spawn(int(getattr(handle, "pid", 0) or 0))
+
+ chunks: list[str] = []
+ deadline = _now() + timeout_s
+ timed_out = False
+ try:
+ while True:
+ if _now() >= deadline:
+ timed_out = True
+ break
+ try:
+ data = handle.read(_READ_SIZE)
+ except EOFError:
+ break
+ if data:
+ chunks.append(data)
+ elif not handle.isalive():
+ break
+ else:
+ _sleep(_POLL_S)
+ finally:
+ if handle.isalive():
+ with suppress(Exception):
+ handle.terminate(force=True)
+
+ raw = "".join(chunks)
+ exit_status = handle.exitstatus
+ return PtyRunResult(
+ text=extract_cli_answer(raw),
+ raw=raw,
+ exit_status=exit_status,
+ timed_out=timed_out,
+ error=None,
+ )
+
+
+__all__ = [
+ "PtyRunResult",
+ "extract_cli_answer",
+ "repair_agy_path",
+ "run_cli_over_pty",
+ "strip_terminal_noise",
+]
diff --git a/jarvis/harness/computer_use_context.py b/jarvis/harness/computer_use_context.py
index 3e4abeb00c..797b094420 100644
--- a/jarvis/harness/computer_use_context.py
+++ b/jarvis/harness/computer_use_context.py
@@ -41,6 +41,7 @@ class ComputerUseContext:
per_step_timeout_s: float = 30.0
think_timeout_cap_s: float = 10.0 # L10: tunable model-call ceiling (sec)
image_max_bytes: int = 300_000 # L7: tunable per-screenshot byte budget
+ image_max_dimension: int = 2048 # L7: tunable per-screenshot longest-side px
settle_scale: float = 1.0 # L8: multiplier on the loop's fixed settle waits
fast_step_model: str = "" # L9: cheaper model id for trivial steps ("" = off)
plan_model_override: str | None = None
@@ -168,6 +169,7 @@ _RELOADABLE_FIELDS: tuple[str, ...] = (
"per_step_timeout_s",
"think_timeout_cap_s",
"image_max_bytes",
+ "image_max_dimension",
"settle_scale",
"fast_step_model",
"max_replans",
diff --git a/jarvis/harness/computer_use_planner.py b/jarvis/harness/computer_use_planner.py
new file mode 100644
index 0000000000..f02d085cbc
--- /dev/null
+++ b/jarvis/harness/computer_use_planner.py
@@ -0,0 +1,221 @@
+"""Provider selection for screenshot-grounded Computer Use planning."""
+from __future__ import annotations
+
+import logging
+from collections.abc import Iterator
+from dataclasses import dataclass, field
+from typing import Any
+
+from jarvis.brain.manager import _classify_provider_error, _is_rate_limit_exc
+
+log = logging.getLogger(__name__)
+
+
+@dataclass(frozen=True)
+class ProviderAttemptError:
+ provider: str
+ model: str | None
+ kind: str
+ detail: str
+
+
+@dataclass
+class ComputerUsePlannerSelector:
+ """Select healthy, vision-capable planner brains for Computer Use."""
+
+ manager: Any
+ chain: list[tuple[str, str | None]]
+ errors: list[ProviderAttemptError] = field(default_factory=list)
+ mission_blocked: set[tuple[str, str | None]] = field(default_factory=set)
+ blind_skipped: int = 0
+
+ def iter_candidates(
+ self, *, images_attached: bool,
+ ) -> Iterator[tuple[int, str, str | None, Any]]:
+ """Yield provider candidates that are usable for this CU brain call."""
+ dead_providers = getattr(self.manager, "_dead_providers", set())
+ rate_tracker = getattr(self.manager, "_rate_tracker", None)
+ is_available = getattr(rate_tracker, "is_available", None)
+
+ for idx, (provider, model) in enumerate(self.chain):
+ key = (provider, model)
+ if provider in dead_providers:
+ self._record(provider, model, "dead", "skipped dead provider")
+ continue
+ if key in self.mission_blocked:
+ self._record(
+ provider,
+ model,
+ "mission_blocked",
+ "skipped after failure earlier in this mission",
+ )
+ continue
+ if callable(is_available) and not is_available(provider, model):
+ self._record(provider, model, "cooldown", "skipped cooldown")
+ continue
+
+ try:
+ brain = self.manager._get_brain(provider, model)
+ if brain is None:
+ raise RuntimeError(
+ f"BrainManager._get_brain({provider!r}, {model!r}) returned None"
+ )
+ except Exception as exc: # noqa: BLE001
+ self.record_failure(provider, model, exc)
+ log.warning(
+ "ComputerUseLoop brain provider %s(%s) failed: %s",
+ provider, model, exc,
+ )
+ continue
+
+ if images_attached and not getattr(brain, "supports_vision", True):
+ self.blind_skipped += 1
+ self._record(
+ provider,
+ model,
+ "blind",
+ "skipped - cannot see the screen (supports_vision=False)",
+ )
+ log.info(
+ "[cu] skipped screenshot-blind provider %s(%s) - "
+ "supports_vision=False; falling through to a "
+ "vision-capable brain",
+ provider, model,
+ )
+ continue
+
+ yield idx, provider, model, brain
+
+ def record_empty(self, provider: str, model: str | None) -> None:
+ self._record(provider, model, "empty", "empty response")
+
+ def record_failure(
+ self, provider: str, model: str | None, exc: Exception,
+ ) -> None:
+ detail = str(exc)
+ kind = self._classify_failure(exc, detail)
+ self._record(provider, model, kind, detail[:200])
+
+ if kind == "rate_limit":
+ rate_tracker = getattr(self.manager, "_rate_tracker", None)
+ mark_rate_limited = getattr(rate_tracker, "mark_rate_limited", None)
+ if callable(mark_rate_limited):
+ mark_rate_limited(provider, model)
+ return
+
+ if kind in ("missing_key", "account_blocked"):
+ dead_providers = getattr(self.manager, "_dead_providers", None)
+ if isinstance(dead_providers, set):
+ dead_providers.add(provider)
+ return
+
+ self.mission_blocked.add((provider, model))
+
+ def error_message(self, *, images_attached: bool, attempted: int) -> str:
+ tail = "; ".join(self._format_error(err) for err in self.errors[-4:])
+ if not tail:
+ tail = "no usable providers"
+ if images_attached and self.blind_skipped and attempted == 0:
+ return (
+ "Computer-Use needs a vision-capable brain, but the active "
+ "provider and its fallbacks cannot see the screen "
+ "(supports_vision=False): "
+ + tail
+ )
+ summary = (
+ f"{self.blind_skipped} provider(s) skipped - no vision; "
+ if self.blind_skipped else ""
+ )
+ return "ComputerUseLoop provider chain failed: " + summary + tail
+
+ def _record(
+ self, provider: str, model: str | None, kind: str, detail: str,
+ ) -> None:
+ self.errors.append(ProviderAttemptError(provider, model, kind, detail))
+
+ @staticmethod
+ def _format_error(err: ProviderAttemptError) -> str:
+ return f"{err.provider}({err.model}): {err.detail}"
+
+ @staticmethod
+ def _classify_failure(exc: Exception, detail: str) -> str:
+ if _is_rate_limit_exc(exc):
+ return "rate_limit"
+ kind = _classify_provider_error(detail, default="call_fail")
+ if kind == "call_fail" and _looks_invalid_auth_error(detail):
+ return "missing_key"
+ return kind
+
+
+def iter_last_resort_vision(
+ manager: Any, *, already_tried: set[tuple[str, str | None]],
+) -> Iterator[tuple[str, str | None, Any]]:
+ """Yield ``(provider, model, brain)`` for every REGISTERED vision-capable
+ provider, IGNORING the manager's transient ``_dead_providers`` / cooldown
+ flags.
+
+ Used only as a LAST RESORT when the normal ``_build_fallback_chain`` reached
+ no vision-capable brain — typically because a stale dead-flag filtered the
+ one vision provider (e.g. grok) out of the chain entirely (live 2026-06-21
+ 18:41: CU gave up "no vision" while grok had a live key). A stale dead-flag
+ on Computer-Use's only eyes must not permanently disable it. Genuinely
+ keyless/broken providers simply raise when dispatched and are skipped by the
+ caller, so this never resurrects a truly-dead provider — it only gives the
+ one that may be wrongly flagged a real attempt.
+
+ Each ``(provider, model)`` already tried in the normal pass is skipped, so a
+ provider that really failed this turn is not retried. Provider-agnostic: the
+ only gate is ``supports_vision``; no provider name is special-cased.
+ """
+ registry = getattr(manager, "_registry", None)
+ available: list[str] = []
+ if registry is not None and hasattr(registry, "available"):
+ try:
+ available = list(registry.available())
+ except Exception: # noqa: BLE001
+ available = []
+ seen = set(already_tried)
+ for provider in available:
+ picker = getattr(manager, "_fast_model", None)
+ model: str | None = None
+ if callable(picker):
+ try:
+ model = picker(provider)
+ except Exception: # noqa: BLE001
+ model = None
+ key = (provider, model)
+ if key in seen:
+ continue
+ seen.add(key)
+ # Last-resort: a provider that cannot even be instantiated is simply
+ # skipped (expected on the failure path; logging each would be noise).
+ try:
+ brain = manager._get_brain(provider, model)
+ except Exception: # noqa: BLE001, S112
+ continue
+ if brain is None:
+ continue
+ if not getattr(brain, "supports_vision", True):
+ continue
+ yield provider, model, brain
+
+
+def _looks_invalid_auth_error(detail: str) -> bool:
+ msg = detail.lower()
+ if "invalid x-api-key" in msg or "invalid api key" in msg:
+ return True
+ if "authentication_error" in msg or "unauthorized" in msg:
+ return True
+ if "401" in msg and any(
+ token in msg
+ for token in (
+ "api-key",
+ "api key",
+ "x-api-key",
+ "invalid",
+ "authentication",
+ "unauthorized",
+ )
+ ):
+ return True
+ return False
diff --git a/jarvis/harness/screenshot_only_loop.py b/jarvis/harness/screenshot_only_loop.py
index 4cd34f8ceb..4b869c1f57 100644
--- a/jarvis/harness/screenshot_only_loop.py
+++ b/jarvis/harness/screenshot_only_loop.py
@@ -37,6 +37,7 @@ Termination paths:
- step budget -> exit_code 4
- tool failure -> exit_code 8
- observe failure -> exit_code 1
+ - elevation unmet -> exit_code 9 (UAC/privilege prompt never confirmed)
- any timeout -> exit_code 124
- cancel token -> exit_code 130
@@ -72,6 +73,7 @@ from jarvis.core.protocols import (
ImageBlock,
Observation,
)
+from jarvis.platform import window_state
if TYPE_CHECKING:
from .computer_use_context import ComputerUseContext
@@ -88,9 +90,23 @@ class CULoopError(RuntimeError):
_VALID_ACTIONS: frozenset[str] = frozenset(
- {"click", "click_element", "type", "key", "scroll", "open_app", "wait", "done", "fail"}
+ {"click", "click_element", "type", "key", "scroll", "drag",
+ "open_app", "switch_window", "wait", "done", "fail"}
)
+# Max windows listed in the per-step awareness line (Phase 1a) — keep the prompt
+# compact; the foreground + a handful of titles is enough signal.
+_MAX_AWARENESS_WINDOWS: int = 12
+
+# UIA snap fallback (Phase 2): on a verified missed pixel click, snap to the
+# nearest clickable accessibility element before the expensive LLM refine retry.
+_UIA_SNAP_TIMEOUT_S: float = 3.0 # tight: a wedged UIA COM call must not stall
+_UIA_SNAP_MAX_DIST_PX: int = 80 # only snap to an element this close to the miss
+
+#: Default drag duration (ms) — slow enough that a map/globe/slider registers the
+#: press-move-release as a real drag gesture rather than a teleport.
+_DEFAULT_DRAG_DURATION_MS: int = 400
+
#: Allowed scroll directions (mirror of ``ScrollTool._VALID_DIRECTIONS``).
_SCROLL_DIRECTIONS: frozenset[str] = frozenset({"up", "down", "left", "right"})
@@ -126,8 +142,20 @@ _BUDGET_EXIT_CODE = 4
_PARSE_EXIT_CODE = 2
_TOOL_EXIT_CODE = 8
_OBSERVE_EXIT_CODE = 1
+_ELEVATION_EXIT_CODE = 9 # waited for an OS elevation confirmation, none came
_CANCEL_EXIT_CODE = 130
+# Elevation pause-and-resume (UAC Secure Desktop & co., 2026-06-23). When a
+# launched app raises a privilege prompt mid-mission, Windows hoists the Secure
+# Desktop; a non-elevated process can neither capture it (BitBlt -> black/raise)
+# nor click it (UIPI). Instead of aborting blind with the misleading "couldn't
+# see the screen" (exit 1), the loop asks the user for the one unavoidable
+# confirmation click and polls until the prompt clears. _WAIT is generous (a
+# human needs time to read + click Yes); _POLL is the cheap OpenInputDesktop
+# re-check cadence. Module-level so they are tunable + test-visible.
+_ELEVATION_WAIT_TIMEOUT_S = 60.0
+_ELEVATION_POLL_S = 0.5
+
# Fail-gate reject budget (completion-enforcement, 2026-06-15). A voluntary
# ``fail`` is the SYMMETRIC sibling of ``done``: it must survive the strict
# feasibility judge (``_verify_fail_justified``) before it ends the mission,
@@ -170,7 +198,11 @@ _SYSTEM_PROMPT = (
" {\"action\": \"key\", \"key\": \"<enter|tab|esc|...>\"}\n"
" {\"action\": \"scroll\", \"direction\": \"<up|down|left|right>\", "
"\"amount\": <int notches, default 3>}\n"
+ " {\"action\": \"drag\", \"x\": <int>, \"y\": <int>, "
+ "\"x2\": <int>, \"y2\": <int>} (press at x,y, hold, drag to x2,y2, release "
+ "-- for rotating a map/globe, panning, or moving a slider; a click cannot)\n"
" {\"action\": \"open_app\", \"name\": \"<app name>\"}\n"
+ " {\"action\": \"switch_window\", \"name\": \"<window title substring>\"}\n"
" {\"action\": \"wait\", \"ms\": <int 0-10000>}\n"
" {\"action\": \"done\"}\n"
" {\"action\": \"fail\", \"reason\": \"<short string>\"}\n\n"
@@ -260,6 +292,12 @@ _SYSTEM_PROMPT = (
"* If the target app is ALREADY VISIBLE in the current screenshot, do "
"NOT call open_app again -- re-launching steals window focus and resets "
"your progress. Interact with the app's existing window instead.\n"
+ "* CHECK THE 'OPEN WINDOWS' LIST (given in the user message when "
+ "available): if the app you need is listed there it is ALREADY RUNNING -- "
+ "even if its window is minimized and NOT visible in the screenshot. Do NOT "
+ "open_app it; emit {\"action\":\"switch_window\",\"name\":\"<a substring of "
+ "its title>\"} to bring its window to the front, then continue. This saves "
+ "a step and avoids a duplicate window.\n"
"* DO NOT type the app name into a focused field hoping it is a search "
"box -- use open_app to launch.\n\n"
"Hard rules:\n"
@@ -414,6 +452,23 @@ def _parse_action(raw: str) -> dict[str, Any]:
if isinstance(amount, bool) or not isinstance(amount, (int, float)):
raise CULoopError("scroll action 'amount' must be a number of wheel notches")
obj["amount"] = max(1, int(amount))
+ elif action == "drag":
+ # Press-and-hold drag (RC#3): two 0-1000 normalized points -- press at
+ # (x,y), drag to (x2,y2), release. For map/globe rotation, panning, and
+ # sliders, which a click cannot do.
+ for _k in ("x", "y", "x2", "y2"):
+ _v = obj.get(_k)
+ if isinstance(_v, bool) or not isinstance(_v, (int, float)):
+ raise CULoopError(
+ "drag action requires integer x, y, x2, y2 (0-1000 normalized "
+ "start and end points; press at x,y and drag to x2,y2)"
+ )
+ obj[_k] = int(_v)
+ _dur = obj.get("duration_ms", _DEFAULT_DRAG_DURATION_MS)
+ if isinstance(_dur, bool) or not isinstance(_dur, (int, float)):
+ raise CULoopError("drag action 'duration_ms' must be a number of ms")
+ obj["duration_ms"] = max(0, min(int(_dur), 3000))
+ _normalize_click_target(obj)
elif action == "open_app":
# Restored 2026-05-27 after observing the loop fall back to ``type
# "calc"`` into the focused chat input when asked to "open Calc" —
@@ -423,6 +478,17 @@ def _parse_action(raw: str) -> dict[str, Any]:
if not isinstance(name, str) or not name.strip():
raise CULoopError("open_app action requires a non-empty string name field")
obj["name"] = name.strip()
+ elif action == "switch_window":
+ # Focus an ALREADY-OPEN window by a title substring (Phase 1c) -- the
+ # model emits this when the awareness line shows the app is running, so
+ # it focuses instead of re-launching. Accept "name" or "title".
+ name = obj.get("name") or obj.get("title")
+ if not isinstance(name, str) or not name.strip():
+ raise CULoopError(
+ "switch_window action requires a non-empty 'name' (or 'title') "
+ "window-title substring"
+ )
+ obj["name"] = name.strip()
elif action == "click_element":
# UIA-grounded click — the user says e.g. ``click_element name="7"``
# and ClickElementTool resolves the exact pixel coords from the
@@ -572,11 +638,38 @@ def _validate_action_dict(obj: Any) -> dict[str, Any]:
if isinstance(amount, bool) or not isinstance(amount, (int, float)):
raise CULoopError("scroll action 'amount' must be a number of wheel notches")
obj["amount"] = max(1, int(amount))
+ elif action == "drag":
+ # Press-and-hold drag (RC#3): two 0-1000 normalized points -- press at
+ # (x,y), drag to (x2,y2), release. For map/globe rotation, panning, and
+ # sliders, which a click cannot do.
+ for _k in ("x", "y", "x2", "y2"):
+ _v = obj.get(_k)
+ if isinstance(_v, bool) or not isinstance(_v, (int, float)):
+ raise CULoopError(
+ "drag action requires integer x, y, x2, y2 (0-1000 normalized "
+ "start and end points; press at x,y and drag to x2,y2)"
+ )
+ obj[_k] = int(_v)
+ _dur = obj.get("duration_ms", _DEFAULT_DRAG_DURATION_MS)
+ if isinstance(_dur, bool) or not isinstance(_dur, (int, float)):
+ raise CULoopError("drag action 'duration_ms' must be a number of ms")
+ obj["duration_ms"] = max(0, min(int(_dur), 3000))
+ _normalize_click_target(obj)
elif action == "open_app":
name = obj.get("name")
if not isinstance(name, str) or not name.strip():
raise CULoopError("open_app action requires a non-empty string name field")
obj["name"] = name.strip()
+ elif action == "switch_window":
+ # Focus an ALREADY-OPEN window by a title substring (Phase 1c). Accept
+ # "name" or "title"; normalise to "name" for the executor.
+ name = obj.get("name") or obj.get("title")
+ if not isinstance(name, str) or not name.strip():
+ raise CULoopError(
+ "switch_window action requires a non-empty 'name' (or 'title') "
+ "window-title substring"
+ )
+ obj["name"] = name.strip()
elif action == "wait":
ms = obj.get("ms")
if isinstance(ms, bool) or not isinstance(ms, (int, float)):
@@ -609,6 +702,19 @@ _UIA_TIMEOUT_S = 3.0
#: case on a 4K monitor is ~1.05s; 3s leaves headroom without letting a
#: wedged GDI call eat the step.
_OBSERVE_TIMEOUT_S = 3.0
+#: How many consecutive observe (screenshot-capture) timeouts a mission
+#: tolerates before giving up. A SINGLE transient timeout must not end the
+#: mission: the capture runs on the shared asyncio loop and can spuriously hit
+#: the `_OBSERVE_TIMEOUT_S` budget when the loop is momentarily saturated by a
+#: concurrent burst (live forensic 2026-06-22: the Spotify CU turn died
+#: "[cu] observe timeout (step 1)" total=3.3s while a degraded-voice TTS
+#: failover + double mic-open contended the loop). Mirror the brain-timeout
+#: retry: retry the observe, only fail after the cap. Provider/OS-agnostic.
+_MAX_OBSERVE_FAILURES = 3
+#: Brief breath before retrying a timed-out observe, so a transient loop
+#: contention spike can clear before the next capture attempt (bounded well
+#: under the per-step budget). Tests monkeypatch this to 0.0.
+_OBSERVE_RETRY_BACKOFF_S = 0.25
#: Single tool execution (click/type/open_app/...). App launches are the slow
#: end; anything beyond this is a wedged tool, not a slow action.
_ACT_TIMEOUT_S = 5.0
@@ -710,6 +816,81 @@ def _publish_announcement_nonblocking(bus: Any, event: Any) -> None:
task.add_done_callback(_ANNOUNCE_TASKS.discard)
+async def _await_privileged_prompt_clearance(
+ ctx: ComputerUseContext,
+ task_prompt: str,
+ step_idx: int,
+ cancel_token: CancelToken | None,
+) -> str:
+ """Pause for an OS elevation prompt (UAC Secure Desktop & co.) and resume.
+
+ A launched app can raise a privilege prompt that Windows shows on the Secure
+ Desktop; a non-elevated process can neither capture it (BitBlt -> black or
+ ScreenShotError) nor send input to it (UIPI). When such a prompt is detected
+ we speak the one-time "please confirm it once" request and poll until it
+ clears, so the mission can continue instead of aborting blind with the
+ misleading "couldn't see the screen" (exit 1).
+
+ Returns one of:
+ ``"no_prompt"`` -- no privileged prompt detected; proceed as before.
+ ``"cleared"`` -- a prompt was up and is now gone; re-observe + resume.
+ ``"timeout"`` -- a prompt stayed up past the wait budget (-> exit 9).
+ ``"cancelled"`` -- the cancel token tripped while waiting.
+
+ Never raises: a missing/raising probe yields ``"no_prompt"`` (behave as
+ before). The probe is ``False`` on headless / macOS / Linux today, so this is
+ a graceful no-op there (AD-6) -- the €5-VPS runtime has no UAC.
+ """
+ def _probe() -> bool:
+ from jarvis.platform.privileged_prompt import ( # noqa: PLC0415
+ privileged_prompt_active,
+ )
+ return privileged_prompt_active()
+
+ try:
+ if not _probe():
+ return "no_prompt"
+ except Exception: # noqa: BLE001 — a missing/raising probe must not end a mission
+ return "no_prompt"
+
+ # A prompt is up: speak the one-time confirmation request. Non-blocking like
+ # the progress announcement -- awaiting the publish would block the loop for
+ # the whole TTS synthesis (BUG-CU-ANNOUNCE-BLOCK). Resolve the language
+ # through the one phrase resolver so de/en/es each get the right wording
+ # (Output-Language doctrine -- never a hardcoded locale).
+ if ctx.bus is not None:
+ from jarvis.voice.action_phrases import ( # noqa: PLC0415
+ action_phrase,
+ resolve_phrase_language,
+ )
+ lang = resolve_phrase_language(None, task_prompt)
+ _publish_announcement_nonblocking(ctx.bus, AnnouncementRequested(
+ text=action_phrase("cu_awaiting_elevation", lang),
+ priority="normal",
+ language=lang,
+ kind="info",
+ ))
+ log.info(
+ "[cu] step %d: privileged prompt up -- awaiting user confirmation",
+ step_idx,
+ )
+
+ deadline = time.monotonic() + _ELEVATION_WAIT_TIMEOUT_S
+ while time.monotonic() < deadline:
+ if cancel_token is not None and cancel_token.is_cancelled():
+ return "cancelled"
+ await asyncio.sleep(_ELEVATION_POLL_S)
+ try:
+ if not _probe():
+ log.info(
+ "[cu] step %d: elevation prompt cleared -- resuming", step_idx
+ )
+ return "cleared"
+ except Exception: # noqa: BLE001 — can't tell anymore; re-observe + decide
+ return "cleared"
+ return "timeout"
+
+
#: Settle probe after a successful open_app (2026-06-10 latency plan Task 6).
#: open_app is a fire-and-forget Popen — observing immediately catches the
#: pre-launch desktop and burns a full observe+think round (~3-5 s) on a
@@ -928,6 +1109,27 @@ def _select_fast_model(manager: Any, provider: Any) -> str | None:
return None
+def _select_cu_model(manager: Any, provider: Any) -> str | None:
+ """Pick the Computer-Use model for ``provider`` (Phase 3).
+
+ Prefers the BrainManager's ``_cu_model`` (cu_model -> main model -> tier
+ default); falls back to ``_select_fast_model`` for stubs that don't expose
+ it. Provider-agnostic (AP-21): the manager owns the per-provider resolution;
+ nothing here name-checks a provider or model. When no CU model is pinned the
+ result equals today's fast model, so the loop is unchanged until a user pins
+ one in Settings.
+ """
+ picker = getattr(manager, "_cu_model", None)
+ if callable(picker):
+ try:
+ model = picker(provider)
+ except Exception: # noqa: BLE001
+ model = None
+ if model:
+ return str(model)
+ return _select_fast_model(manager, provider)
+
+
# ---------------------------------------------------------------------------
# Brain dispatch
# ---------------------------------------------------------------------------
@@ -939,10 +1141,17 @@ def _select_fast_model(manager: Any, provider: Any) -> str | None:
# 2048px longest side and JPEG-encodes toward this budget; on any failure it
# returns the original image, so the vision path never breaks.
_CU_IMAGE_MAX_BYTES = 300_000
+#: Per-screenshot longest-side pixel cap (L7). 2048 keeps the legacy default;
+#: vision models resample to ~1568 px internally, so a lower cap (tuned via
+#: ``[computer_use].image_max_dimension`` + the cu_bench proof gate) ships fewer
+#: pixels for faster encode + upload + ingest. 0 disables the dimension cap.
+_CU_IMAGE_MAX_DIMENSION = 2048
async def _load_observation_image(
- obs: Observation, max_bytes: int = _CU_IMAGE_MAX_BYTES,
+ obs: Observation,
+ max_bytes: int = _CU_IMAGE_MAX_BYTES,
+ max_dimension: int = _CU_IMAGE_MAX_DIMENSION,
) -> ImageBlock | None:
"""Read the observation's screenshot and cap it for the model payload.
@@ -956,9 +1165,49 @@ async def _load_observation_image(
from jarvis.vision.image_budget import cap_image_b64 # noqa: PLC0415
mime, image_b64 = await _read_observation_image_b64(obs)
- mime, image_b64 = cap_image_b64(mime, image_b64, max_bytes)
+ mime, image_b64 = cap_image_b64(mime, image_b64, max_bytes, max_dimension)
return ImageBlock(mime=mime, data_b64=image_b64, source_hash=obs.screenshot_hash)
+def _window_awareness_line(ctx: ComputerUseContext) -> str:
+ """A compact, best-effort "what is already open" line for the CU prompt.
+
+ Lets the fast model focus an already-running app (``switch_window``) instead
+ of re-launching it (the OBS-already-in-the-taskbar case) and plan with real
+ state. Returns "" on failure / headless / a platform that returns nothing —
+ never raises (``list_windows`` is microseconds and self-guards). Opt out per
+ context via ``window_awareness = False``.
+ """
+ if not getattr(ctx, "window_awareness", True):
+ return ""
+ try:
+ windows = window_state.list_windows()
+ foreground = window_state.get_foreground_title()
+ except Exception: # noqa: BLE001
+ return ""
+ labels: list[str] = []
+ for w in windows:
+ label = (w.title or "").strip()
+ if not label:
+ continue
+ if w.minimized:
+ label += " (minimized)"
+ if label not in labels:
+ labels.append(label)
+ if len(labels) >= _MAX_AWARENESS_WINDOWS:
+ break
+ if not labels:
+ return ""
+ line = (
+ "\n\nOPEN WINDOWS (these apps are ALREADY running — to use one, emit "
+ '{"action":"switch_window","name":"<title substring>"} or interact with '
+ "its visible window; do NOT open_app it again): " + "; ".join(labels)
+ )
+ fg = (foreground or "").strip()
+ if fg:
+ line += f"\nFOREGROUND: {fg}"
+ return line
+
+
async def _call_brain(
ctx: ComputerUseContext,
*,
@@ -970,6 +1219,7 @@ async def _call_brain(
frame_b: Observation | None = None,
max_tokens: int = 256,
images_override: list[ImageBlock] | None = None,
+ early_stop_json: bool = False,
) -> str:
"""Send screenshot + goal + history to the active brain, return raw text.
@@ -1001,25 +1251,33 @@ async def _call_brain(
result = await complete_text(system=system_prompt, user=user_message)
return str(result)
- # Production: direct provider dispatch.
+ # Production: provider-chain dispatch. This must mirror the BrainManager's
+ # fallback behavior closely enough for CU: a broken primary desktop brain
+ # must not make the whole screen-control loop fail while chat would have
+ # fallen through to the next provider.
# TODO(L9 live-gated): when ``ctx.fast_step_model`` is set and the chosen
# action is a trivial click_element on a known control label (see
# ``_should_use_fast_step_model``), select that cheaper model here instead
# of the active provider. Not wired yet — it touches BrainManager provider
# routing and is a reliability risk; the knob + pure predicate ship first.
manager = ctx.brain_manager
- if all(hasattr(manager, n) for n in ("_get_brain", "active_provider")):
- from jarvis.brain.streaming import aggregate # noqa: PLC0415
-
- provider = manager.active_provider
- if provider is None:
- raise CULoopError("BrainManager.active_provider is None")
- model = _select_fast_model(manager, provider)
- brain = manager._get_brain(provider, model)
- if brain is None:
- raise CULoopError(
- f"BrainManager._get_brain({provider!r}, {model!r}) returned None"
- )
+ if hasattr(manager, "_get_brain"):
+ from jarvis.brain.streaming import ( # noqa: PLC0415
+ aggregate,
+ aggregate_first_json,
+ )
+
+ # Early-stop the per-step ACTION call at the first complete JSON action —
+ # skip the provider stream's tail (and any rambling past the JSON up to
+ # max_tokens) on the loop's #1 cost path. Verifier / planner calls keep
+ # the full-stream aggregate (early_stop_json=False, the default), so
+ # their free-text proofs are read in full. Provider-agnostic.
+ # NOTE: on the early-stop path a terminal usage/finish_reason delta that
+ # arrives AFTER the JSON is intentionally dropped — _call_brain returns
+ # only the text string and no caller here reads agg.usage/finish_reason.
+ # A future maintainer adding cost tracking to this call must meter via
+ # ``aggregate`` (full stream), not the early-stop variant.
+ _agg = aggregate_first_json if early_stop_json else aggregate
# Attach screenshot(s), capped to the model-payload budget
# (2026-06-09 latency fix). ``frame_b`` lets the two-frame motion
@@ -1038,6 +1296,9 @@ async def _call_brain(
block = await _load_observation_image(
obs,
max_bytes=getattr(ctx, "image_max_bytes", _CU_IMAGE_MAX_BYTES),
+ max_dimension=getattr(
+ ctx, "image_max_dimension", _CU_IMAGE_MAX_DIMENSION,
+ ),
)
if block is None:
continue
@@ -1059,8 +1320,129 @@ async def _call_brain(
max_tokens=max_tokens,
stream=True,
)
- agg = await aggregate(brain.complete(req))
- return agg.text
+
+ # PROVIDER-AGNOSTIC BY DESIGN. The CU loop is NOT pinned to any provider
+ # or model. The candidate order is whatever ``BrainManager`` resolves for
+ # the active/selected provider via ``_build_fallback_chain("fast")`` —
+ # the *active* provider leads, its tier fallbacks follow. Which one is
+ # actually dispatched is decided ONLY by capability + availability below:
+ # skip ``_dead_providers`` (keyless/blocked), skip rate-limit cooldown,
+ # and — when a screenshot rides on the request — skip any brain whose
+ # ``supports_vision`` is False, then use the FIRST remaining brain that
+ # returns text. Never gate on a provider NAME or a model id here: do not
+ # "fix" this into ``if provider == 'grok'`` / ``if model == 'grok-4.3'``.
+ # That an installed key happens to make grok the only live vision brain
+ # is a *credential* fact owned by the manager, not a hardcode here — give
+ # claude-api/openrouter/openai/gemini a key and CU uses them identically.
+ chain: list[tuple[str, str | None]] = []
+ build_chain = getattr(manager, "_build_fallback_chain", None)
+ if callable(build_chain):
+ try:
+ chain = list(build_chain("fast") or [])
+ except Exception: # noqa: BLE001
+ log.debug("ComputerUseLoop fallback-chain build failed", exc_info=True)
+ if not chain and hasattr(manager, "active_provider"):
+ provider = manager.active_provider
+ if provider is None:
+ raise CULoopError("BrainManager.active_provider is None")
+ chain = [(provider, _select_cu_model(manager, provider))]
+ if not chain:
+ raise CULoopError("BrainManager fallback chain is empty")
+
+ # Per-provider Computer-Use model override (Phase 3): the user may pin a
+ # dedicated CU model in Settings (e.g. run CU on a stronger model than
+ # chat). _select_cu_model resolves cu_model -> the provider's main model
+ # -> the tier default, so when nothing is pinned this equals today's fast
+ # model (backward-compatible). Provider-agnostic; applies to every brain
+ # in the chain so a fallback provider also uses ITS configured CU model.
+ if callable(getattr(manager, "_cu_model", None)):
+ chain = [(p, _select_cu_model(manager, p) or m) for (p, m) in chain]
+
+ # Computer-Use is screenshot-grounded: the screenshot is the loop's
+ # SOLE grounding signal. A provider that cannot see the attached image
+ # (supports_vision=False) would plan BLIND. Forensic 2026-06-20: with
+ # the text-only Antigravity Google-CLI brain (supports_vision=False)
+ # active, the CLI silently dropped the screenshot, so the planner
+ # looped on hallucinated ``click_element name='Edit'`` actions and
+ # never grounded. Skip blind providers exactly like dead/cooldown ones
+ # whenever an image rides on the request; fall through to a
+ # vision-capable brain (gemini/claude-api/...), or fail honestly.
+ from jarvis.harness.computer_use_planner import ( # noqa: PLC0415
+ ComputerUsePlannerSelector,
+ )
+
+ images_attached = bool(images)
+ selector = ComputerUsePlannerSelector(manager=manager, chain=chain)
+ attempted = 0
+ for idx, provider, model, brain in selector.iter_candidates(
+ images_attached=images_attached,
+ ):
+ attempted += 1
+ try:
+ agg = await _agg(brain.complete(req))
+ text = (agg.text or "").strip()
+ if not text:
+ selector.record_empty(provider, model)
+ continue
+ if idx > 0:
+ log.info(
+ "ComputerUseLoop fallback hit: %s(%s) after %d skipped provider(s)",
+ provider, model, idx,
+ )
+ return text
+ except Exception as exc: # noqa: BLE001
+ selector.record_failure(provider, model, exc)
+ log.warning(
+ "ComputerUseLoop brain provider %s(%s) failed: %s",
+ provider, model, exc,
+ )
+ continue
+
+ # LAST RESORT (stale dead-flag resilience, live 2026-06-21 18:41): the
+ # normal chain reached no vision-capable brain — usually because a stale
+ # ``_dead_providers`` flag filtered the one vision provider (grok) out of
+ # the chain entirely, leaving CU "no vision" while a live, image-reading
+ # brain existed. Re-try every REGISTERED vision-capable provider once,
+ # IGNORING the transient dead/cooldown flags, deduped against what was
+ # already tried this turn. Provider-agnostic; a truly-dead provider just
+ # raises and is skipped, so this only rescues a wrongly-flagged one.
+ if images_attached:
+ from jarvis.harness.computer_use_planner import ( # noqa: PLC0415
+ iter_last_resort_vision,
+ )
+
+ already_tried = set(chain) | {
+ (err.provider, err.model) for err in selector.errors
+ }
+ for provider, model, brain in iter_last_resort_vision(
+ manager, already_tried=already_tried,
+ ):
+ try:
+ agg = await _agg(brain.complete(req))
+ text = (agg.text or "").strip()
+ if not text:
+ selector.record_empty(provider, model)
+ continue
+ log.warning(
+ "ComputerUseLoop LAST-RESORT vision brain %s(%s) reached "
+ "— normal chain had no vision provider (stale dead-flag?)",
+ provider, model,
+ )
+ return text
+ except Exception as exc: # noqa: BLE001
+ selector.record_failure(provider, model, exc)
+ log.warning(
+ "ComputerUseLoop last-resort provider %s(%s) failed: %s",
+ provider, model, exc,
+ )
+ continue
+
+ raise CULoopError(
+ selector.error_message(
+ images_attached=images_attached,
+ attempted=attempted,
+ )
+ )
# Last-resort callable manager (legacy stub).
if callable(manager):
@@ -1890,6 +2272,7 @@ async def _make_plan(
system_prompt=_PLANNER_SYSTEM_PROMPT,
user_message=user_message,
max_tokens=512,
+ early_stop_json=True,
),
timeout=_think_timeout_s(ctx),
)
@@ -2341,6 +2724,83 @@ async def _dispatch_raw_click(
)
+def _pick_snap_node(nodes: Any, x: int, y: int, max_dist: int) -> Any | None:
+ """Pick the clickable accessibility node to snap a missed click to.
+
+ Preference: the SMALLEST node whose bounds contain ``(x, y)`` (the most
+ specific control under the cursor); otherwise the node whose center is
+ NEAREST ``(x, y)`` within ``max_dist`` pixels. Disabled and zero-area nodes
+ are skipped. Returns the node or ``None`` when nothing is close enough.
+ """
+ containing: list[tuple[int, Any]] = []
+ nearest: Any | None = None
+ nearest_d2 = max_dist * max_dist
+ for n in nodes:
+ if not getattr(n, "enabled", True):
+ continue
+ try:
+ bx, by, bw, bh = n.bounds
+ except Exception: # noqa: BLE001 — a malformed node is simply skipped
+ continue
+ if bw <= 0 or bh <= 0:
+ continue
+ if bx <= x <= bx + bw and by <= y <= by + bh:
+ containing.append((bw * bh, n))
+ continue
+ cx, cy = bx + bw // 2, by + bh // 2
+ d2 = (cx - x) ** 2 + (cy - y) ** 2
+ if d2 <= nearest_d2:
+ nearest_d2 = d2
+ nearest = n
+ if containing:
+ return min(containing, key=lambda t: t[0])[1]
+ return nearest
+
+
+async def _uia_snap_click(
+ ctx: ComputerUseContext,
+ *,
+ executor: Any,
+ tool: Any,
+ x: int,
+ y: int,
+ trace_id: Any,
+) -> tuple[bool, str] | None:
+ """Snap a verified-missed pixel click to the nearest clickable UIA element.
+
+ Returns ``(ok, message)`` when an element was found near ``(x, y)`` and
+ clicked, else ``None`` so the caller falls through to the LLM refine. The
+ fast model often guesses a pixel a few px off a labelled control; the
+ accessibility tree knows the control's true bounds, so this fixes the miss
+ deterministically. Best-effort: a missing tree backend (headless / Null
+ source), no nearby element, a timeout, or any error all return ``None``.
+ Cross-platform via ``make_ui_tree_source`` (UIA / AX / AT-SPI / Null).
+ Disable per context with ``uia_click_fallback = False``.
+ """
+ if not getattr(ctx, "uia_click_fallback", True):
+ return None
+ try:
+ from jarvis.vision.tree_factory import make_ui_tree_source # noqa: PLC0415
+
+ source = make_ui_tree_source()
+ obs = await asyncio.wait_for(source.observe(), timeout=_UIA_SNAP_TIMEOUT_S)
+ except Exception: # noqa: BLE001 — best-effort recovery, never raises
+ return None
+ node = _pick_snap_node(
+ list(getattr(obs, "nodes", ()) or ()), x, y, _UIA_SNAP_MAX_DIST_PX
+ )
+ if node is None:
+ return None
+ try:
+ bx, by, bw, bh = node.bounds
+ cx, cy = bx + bw // 2, by + bh // 2
+ ok, msg = await _dispatch_raw_click(executor, tool, cx, cy, trace_id)
+ except Exception: # noqa: BLE001
+ return None
+ label = (getattr(node, "name", "") or "element").strip() or "element"
+ return ok, f"{msg} (UIA-snapped to '{label[:40]}' at ({cx},{cy}))"
+
+
async def _click_with_refine(
obj: dict[str, Any],
ctx: ComputerUseContext,
@@ -2370,6 +2830,7 @@ async def _click_with_refine(
clicked: list[tuple[int, int]] = []
last_msg = ""
retry_note = ""
+ snapped = False # Phase 2: UIA snap is tried at most once per click action
for _attempt in range(_CLICK_MAX_ATTEMPTS):
refined = None
if clicked:
@@ -2437,6 +2898,22 @@ async def _click_with_refine(
# Something near the click visibly reacted (or we cannot tell) —
# accept; the loop's fresh screenshot judges the semantics.
return ok, last_msg
+ # Verified miss: the click produced no visible change. Before the costly
+ # LLM refine, snap to the nearest clickable accessibility element and
+ # click its true center (Phase 2) — fixes a "guessed a pixel, missed the
+ # button by a few px" thrash deterministically. Tried once per action;
+ # falls through to the refine when no element is near / no tree backend.
+ if not snapped:
+ snapped = True
+ snap = await _uia_snap_click(
+ ctx, executor=executor, tool=tool, x=x, y=y, trace_id=trace_id,
+ )
+ if snap is not None:
+ log.info(
+ "[cu] click at (%d,%d) missed — UIA-snapped: %s",
+ x, y, snap[1][:80],
+ )
+ return snap
log.info(
"[cu] click at (%d,%d) produced no local change — refining for a "
"corrected retry (%d/%d)", x, y, len(clicked), _CLICK_MAX_ATTEMPTS,
@@ -2452,6 +2929,21 @@ async def _click_with_refine(
)
+def _perform_drag(
+ x1: int, y1: int, x2: int, y2: int, duration_s: float = 0.4
+) -> None:
+ """Press the left mouse button at ``(x1, y1)``, drag to ``(x2, y2)``, release.
+
+ The press-and-hold gesture a plain click cannot do — rotating a map/globe,
+ panning, or moving a slider. pyautogui is imported lazily so the module still
+ loads on a non-desktop host (the harness is desktop-gated anyway).
+ """
+ import pyautogui # noqa: PLC0415 — lazy: keeps non-desktop import clean
+
+ pyautogui.moveTo(x1, y1)
+ pyautogui.dragTo(x2, y2, duration=max(0.0, duration_s), button="left")
+
+
async def _execute_action(
obj: dict[str, Any],
ctx: ComputerUseContext,
@@ -2629,6 +3121,30 @@ async def _execute_action(
str(getattr(res, "output", "") or getattr(res, "error", "") or ""),
)
+ if action == "drag":
+ # Press-and-hold drag: resolve BOTH endpoints from the 0-1000 grid to
+ # absolute pixels (same resolver as click), then press-move-release.
+ # Inline like ``wait`` — no separate tool to wire (RC#3, 2026-06-22).
+ start_x, start_y = _resolve_click_pixel(obj, monitor_geom)
+ end_x, end_y = _resolve_click_pixel(
+ {"x": obj["x2"], "y": obj["y2"]}, monitor_geom
+ )
+ duration_s = max(
+ 0.0, float(obj.get("duration_ms", _DEFAULT_DRAG_DURATION_MS)) / 1000.0
+ )
+ try:
+ await asyncio.wait_for(
+ asyncio.to_thread(
+ _perform_drag, start_x, start_y, end_x, end_y, duration_s
+ ),
+ timeout=_ACT_TIMEOUT_S,
+ )
+ except TimeoutError:
+ raise
+ except Exception as exc: # noqa: BLE001
+ return False, f"drag crash: {type(exc).__name__}: {exc}"
+ return True, f"dragged ({start_x},{start_y})->({end_x},{end_y})"
+
if action == "open_app":
tool = tools.get("open_app")
if tool is None:
@@ -2653,6 +3169,24 @@ async def _execute_action(
str(getattr(res, "output", "") or getattr(res, "error", "") or ""),
)
+ if action == "switch_window":
+ # Focus an already-open window by a title substring (Phase 1c). Runs the
+ # cross-platform focus helper directly (best-effort, never raises); no
+ # tool-executor round-trip needed (focus is reversible, monitor-tier).
+ title = str(obj.get("name", "")).strip()
+ if not title:
+ return False, "switch_window requires a window-title substring"
+ try:
+ found, msg = await asyncio.wait_for(
+ asyncio.to_thread(window_state.focus_window, title),
+ timeout=_ACT_TIMEOUT_S,
+ )
+ except TimeoutError:
+ raise
+ except Exception as exc: # noqa: BLE001
+ return False, f"switch_window crash: {type(exc).__name__}: {exc}"
+ return found, msg
+
return False, f"action {action!r} reached _execute_action -- caller bug"
@@ -2738,6 +3272,13 @@ async def _run_screenshot_loop(
# failures per mission end it, with a clean error message.
_MAX_LLM_FAILURES = 3
llm_failures = 0
+ # Observe-timeout retry budget (live forensic 2026-06-22, exit 124): a
+ # single transient screenshot-capture timeout used to END the whole mission
+ # at step 1 (the Spotify "[cu] observe timeout (step 1)" total=3.3s). The
+ # capture shares the asyncio loop and can spuriously hit its budget under a
+ # momentary contention burst, so retry like a brain timeout; only this many
+ # consecutive observe timeouts end the mission.
+ observe_failures = 0
# Done-verification gate (2026-06-09 shippability fix): a model-emitted
# "done" is only accepted once the strict judge confirms the goal on the
# CURRENT screenshot (``ctx.verify_after_each_step`` -- previously a dead
@@ -2794,6 +3335,21 @@ async def _run_screenshot_loop(
recent_click_targets: _deque[tuple[int, int]] = _deque(maxlen=6)
opened_apps: dict[str, int] = {}
toggle_stop_engaged = False
+ # * last_typed_text: the text of the most recent SUCCESSFUL ``type``. A
+ # back-to-back ``type`` of the SAME text is a redundant no-op -- the
+ # field already holds it -- so we suppress it and push the model to the
+ # NEXT step (submit / click a result) instead of mashing the same query
+ # (BUG-CU-RETYPE, live 2026-06-22: "Minecraft" typed into the Microsoft
+ # Store search box in BOTH step 6 and step 7 -- "das ist ja dumm").
+ last_typed_text = ""
+ # * last_stall_nudge_hash: the screenshot hash we last warned the model
+ # about. When the screen is UNCHANGED since the previous step, the last
+ # action had NO visible effect -- we nudge the model ONCE (per distinct
+ # stall) to stop repeating it and re-target, BEFORE the 3-strike stuck
+ # abort. General by design: every action type, every app, pure
+ # screenshot+keyboard+mouse (user mandate 2026-06-22 -- not a per-example
+ # patch).
+ last_stall_nudge_hash = ""
# Cumulative guard-blocked actions this mission (see _MAX_GUARD_HITS).
guard_hits = 0
# On-demand done-verifier: set when a state-change click lands and the goal
@@ -2913,13 +3469,61 @@ async def _run_screenshot_loop(
observation = await _observe(ctx, cancel_token)
except TimeoutError:
labels_task.cancel()
- yield _final(
- stderr=f"[cu] observe timeout (step {step_idx})\n",
- exit_code=_TIMEOUT_EXIT_CODE,
+ observe_failures += 1
+ log.info(
+ "[cu] observe timeout (step %d, failure %d/%d)",
+ step_idx, observe_failures, _MAX_OBSERVE_FAILURES,
)
- return
+ if observe_failures >= _MAX_OBSERVE_FAILURES:
+ yield _final(
+ stderr=(
+ f"[cu] giving up after {observe_failures} observe "
+ f"timeouts (last at step {step_idx})\n"
+ ),
+ exit_code=_TIMEOUT_EXIT_CODE,
+ )
+ return
+ # A single transient capture timeout (shared-loop contention) must
+ # not end the mission -- retry on the next step (mirrors the
+ # brain-timeout retry), after a brief breath so the spike can clear.
+ yield _progress(
+ f"[cu] step {step_idx}: observe timeout -- retrying"
+ )
+ if _OBSERVE_RETRY_BACKOFF_S > 0:
+ await asyncio.sleep(_OBSERVE_RETRY_BACKOFF_S)
+ continue
except Exception as exc: # noqa: BLE001
labels_task.cancel()
+ # An OS elevation prompt (UAC Secure Desktop & co.) blocks BOTH
+ # capture and input for a non-elevated process, so this observe
+ # failure is most likely a UAC prompt, not a generic GDI fault.
+ # Detect it and PAUSE for the user's one unavoidable confirmation
+ # click instead of aborting blind with the misleading "couldn't see
+ # the screen" (exit 1, the live OBS forensic 2026-06-23).
+ clearance = await _await_privileged_prompt_clearance(
+ ctx, task_prompt, step_idx, cancel_token,
+ )
+ if clearance == "cleared":
+ yield _progress(
+ f"[cu] step {step_idx}: elevation prompt cleared -- resuming"
+ )
+ continue
+ if clearance == "timeout":
+ yield _final(
+ stderr=(
+ f"[cu] aborted: elevation prompt not confirmed within "
+ f"{_ELEVATION_WAIT_TIMEOUT_S:.0f}s (step {step_idx})\n"
+ ),
+ exit_code=_ELEVATION_EXIT_CODE,
+ )
+ return
+ if clearance == "cancelled":
+ yield _final(
+ stderr="[cu] cancelled while awaiting elevation confirmation\n",
+ exit_code=_CANCEL_EXIT_CODE,
+ )
+ return
+ # "no_prompt": the original generic observe failure stands.
yield _final(
stderr=f"[cu] observe failed: {exc}\n",
exit_code=_OBSERVE_EXIT_CODE,
@@ -2936,6 +3540,37 @@ async def _run_screenshot_loop(
ctx, phase="observe", step_idx=step_idx, t0=t_observe, acc=phase_ms,
)
+ # Elevation-prompt guard (UAC Secure Desktop & co.): the capture can
+ # SUCCEED yet hand back a black/dimmed frame while a privilege prompt is
+ # up (BitBlt does not always raise). Detect that BEFORE the brain call so
+ # we never feed the model a blind frame and never try to click a window
+ # UIPI blocks us from. Cheap (one OpenInputDesktop read) and a graceful
+ # no-op off Windows / headless. On a detected prompt we pause for the
+ # user's confirmation click, then re-observe and resume.
+ clearance = await _await_privileged_prompt_clearance(
+ ctx, task_prompt, step_idx, cancel_token,
+ )
+ if clearance == "cleared":
+ yield _progress(
+ f"[cu] step {step_idx}: elevation prompt cleared -- resuming"
+ )
+ continue
+ if clearance == "timeout":
+ yield _final(
+ stderr=(
+ f"[cu] aborted: elevation prompt not confirmed within "
+ f"{_ELEVATION_WAIT_TIMEOUT_S:.0f}s (step {step_idx})\n"
+ ),
+ exit_code=_ELEVATION_EXIT_CODE,
+ )
+ return
+ if clearance == "cancelled":
+ yield _final(
+ stderr="[cu] cancelled while awaiting elevation confirmation\n",
+ exit_code=_CANCEL_EXIT_CODE,
+ )
+ return
+
# No-progress guard: if the last _STUCK_LIMIT screenshots are
# byte-identical, nothing on screen changed. Bail with a clear "stuck"
# failure instead of grinding through the rest of the budget.
@@ -2945,10 +3580,68 @@ async def _run_screenshot_loop(
# when no action was guard-blocked is the dead-target reading correct.
if observation.screenshot_hash:
recent_hashes.append(observation.screenshot_hash)
+ # General "no progress -> re-target" nudge (user mandate 2026-06-22:
+ # make the loop GENERALLY recognise a missed target instead of
+ # mashing the same action -- NOT example-specific). The instant the
+ # screen is UNCHANGED since the previous step, the last action had no
+ # visible effect: a missed click, a non-existent element, a no-op
+ # key. Tell the model ONCE -- before the 3-strike stuck abort below --
+ # to STOP repeating it and re-target. Applies to EVERY action type
+ # and every app (pure screenshot+keyboard+mouse, no per-case logic).
+ if (
+ len(recent_hashes) >= 2
+ and recent_hashes[-1] == recent_hashes[-2]
+ and last_stall_nudge_hash != observation.screenshot_hash
+ ):
+ last_stall_nudge_hash = observation.screenshot_hash
+ history.append(
+ "NOTE: the screen did NOT change after your last action -- "
+ "it had NO visible effect (a missed target, a non-existent "
+ "element, or a no-op). Do NOT repeat the same action. "
+ "Re-target: prefer click_element on one of the EXACT labels "
+ "in AVAILABLE CONTROLS, aim a different pixel, or take the "
+ "next concrete step toward the goal."
+ )
+ log.info(
+ "[cu] step %d: screen unchanged since last step — injected "
+ "re-target nudge (no visible effect)", step_idx,
+ )
if (
len(recent_hashes) == _STUCK_LIMIT
and len(set(recent_hashes)) == 1
):
+ # Verify-before-fail (user forensic 2026-06-20): a frozen
+ # screen is ALSO exactly what a FINISHED task looks like -- a
+ # fully-loaded page is static, so the goal-reached state is
+ # byte-identical to a dead-click stall. Hash alone cannot tell
+ # "stuck" from "done". So before declaring the mission stuck,
+ # run the done-verifier ONCE against this stable screenshot. If
+ # the goal is provably achieved, end as a verified success
+ # instead of a false "3 identical screenshots" failure (live:
+ # the @AngelaMerkel profile page was open on screen, yet the
+ # mission reported FAILED because nothing moved). The verifier
+ # never raises (returns (False, "") on any error), so this can
+ # only RESCUE a real success -- it never masks a genuine stall,
+ # which still falls through to the honest failure below.
+ done, proof = await _verify_goal_done(
+ ctx, observation=observation, user_goal=task_prompt,
+ )
+ if done:
+ proof_cap = (
+ _READ_PROOF_MAX
+ if _goal_needs_reading(task_prompt)
+ else 80
+ )
+ log.info(
+ "[cu] no-progress freeze AT the goal -- verifier "
+ "confirms done (proof=%r); ending as success",
+ proof[:80],
+ )
+ yield _final(
+ stdout=f"[cu] done (verified: {proof[:proof_cap]})\n",
+ exit_code=0,
+ )
+ return
cause = (
"recent actions were suppressed by a guard "
"(repeated click / relaunch), so nothing changed"
@@ -3164,6 +3857,19 @@ async def _run_screenshot_loop(
plan_user_message += _SEARCH_DISCIPLINE_BLOCK
else:
plan_user_message += verify_note
+ # Window-state awareness (Phase 1a): tell the model what is ALREADY open
+ # so it focuses an existing window (switch_window) instead of re-launching
+ # it -- the OBS-already-in-the-taskbar case. Best-effort (~microseconds),
+ # never raises; empty on headless / a platform that returns nothing.
+ awareness_hint = _window_awareness_line(ctx)
+ if awareness_hint:
+ if plan_user_message is None:
+ plan_user_message = (
+ f"GOAL: {task_prompt}\n"
+ f"PREVIOUS_STEPS:\n{chr(10).join(history[-12:]) or '(none)'}\n\n"
+ "Inspect the screenshot and emit ONE JSON action."
+ )
+ plan_user_message += awareness_hint
log.info("[cu] step %d phase=think", step_idx)
t_think = time.monotonic()
# Wave 3 hybrid: try the native Gemini computer_use engine first when
@@ -3192,6 +3898,7 @@ async def _run_screenshot_loop(
history_text="\n".join(history[-12:]),
system_prompt=think_system_prompt,
user_message=plan_user_message,
+ early_stop_json=True,
),
timeout=_think_timeout_s(ctx),
)
@@ -3404,6 +4111,42 @@ async def _run_screenshot_loop(
return
break
+ # Repeated-type guard (BUG-CU-RETYPE, live 2026-06-22): re-typing the
+ # SAME text the model just successfully typed is a redundant no-op --
+ # the field already holds it. Do NOT execute it; inject a note that
+ # pushes the model to the next concrete step (submit with Enter, or
+ # click the matching result) instead of mashing the same query. Use
+ # ``continue`` (not ``break``) so a trailing submit key in THIS batch
+ # -- e.g. [click, type(repeat), key=Enter] -- still fires and the
+ # search actually goes through. Parity-safe: the field keeps the
+ # text from the first type.
+ if action == "type":
+ _typed = str(action_obj.get("text", "")).strip()
+ if _typed and _typed == last_typed_text:
+ log.info(
+ "[cu] %s repeated type %r — suppressed (already typed)",
+ tag, _typed[:40],
+ )
+ history.append(
+ f"{tag}: type {_typed!r} SKIPPED — you ALREADY typed this "
+ "exact text and it is in the field. Do NOT type it again. "
+ "Take the NEXT step instead: press Enter to submit, or "
+ "click the matching on-screen result."
+ )
+ guard_hits += 1
+ if guard_hits >= _MAX_GUARD_HITS:
+ yield _final(
+ stderr=(
+ f"[cu] mission is circling: {guard_hits} "
+ "guard-blocked actions this mission (suppressed "
+ "relaunches / repeated clicks / re-types) — no "
+ "productive next action found\n"
+ ),
+ exit_code=_FAIL_EXIT_CODE,
+ )
+ return
+ continue
+
# Telemetry — swallowed on failure to protect the loop.
if ctx.bus is not None:
try:
@@ -3702,12 +4445,25 @@ async def _run_screenshot_loop(
# for play goals (BUG-CU-WRONG-SONG, 2026-05-29).
if action == "type" and str(action_obj.get("text", "")).strip():
typed_query = True
- # Arm the on-demand done-verifier after a state-change click on a
- # play/submit/start-type goal: the NEXT iteration judges the fresh
- # screenshot before planning another (possibly toggle-undoing)
- # action (BUG-CU-TOGGLE).
- if action in ("click", "click_element") and _goal_needs_verification(task_prompt):
- pending_verify = True
+ # Arm the repeated-type guard: a back-to-back type of this exact
+ # text next is a redundant no-op (BUG-CU-RETYPE).
+ last_typed_text = str(action_obj.get("text", "")).strip()
+ # Disarm the repeated-type guard on a click/click_element: a click
+ # RE-FOCUSES / re-targets a field, so a following type of the same
+ # text is a FRESH attempt (e.g. retrying after the first type did not
+ # land in a web input like the Google-Flights city field), NOT a
+ # redundant back-to-back repeat. Without this reset the legitimate
+ # retry is suppressed and the mission dead-ends "in the right field
+ # but nothing typed" (RC#2, 2026-06-22). The guard still catches a
+ # type-immediately-after-type with no click in between.
+ if action in ("click", "click_element"):
+ last_typed_text = ""
+ # Arm the on-demand done-verifier after a state-change click on a
+ # play/submit/start-type goal: the NEXT iteration judges the fresh
+ # screenshot before planning another (possibly toggle-undoing)
+ # action (BUG-CU-TOGGLE).
+ if _goal_needs_verification(task_prompt):
+ pending_verify = True
# End of batch. If the repeated-click guard engaged, inject a
# constrained directive so the next turn VERIFIES instead of clicking
diff --git a/jarvis/memory/wiki/curator_llm.py b/jarvis/memory/wiki/curator_llm.py
index 516bf47755..764880eb78 100644
--- a/jarvis/memory/wiki/curator_llm.py
+++ b/jarvis/memory/wiki/curator_llm.py
@@ -73,7 +73,6 @@ _CHEAP_MODEL_FALLBACK: dict[str, str] = {
"gemini": "gemini-3-flash-preview",
"openai": "gpt-5.5",
"codex": "gpt-5.5",
- "grok": "grok-4.3",
"deepseek": "deepseek-chat",
"openrouter": "anthropic/claude-haiku-4.5",
"mistral": "mistral-small-3.1",
diff --git a/jarvis/missions/init.py b/jarvis/missions/init.py
index e0278ee592..d543189eef 100644
--- a/jarvis/missions/init.py
+++ b/jarvis/missions/init.py
@@ -59,7 +59,7 @@ logger = logging.getLogger(__name__)
# Fire-and-forget boot-time cleanup sweeps keep a strong reference here so the
# event loop does not garbage-collect them mid-run; each self-discards on
# completion. These sweeps are PURE cleanup (git worktree prune + rmtree over
-# stale dirs) whose result nothing downstream consumes — awaiting them only
+# stale dirs) whose result nothing downstream consumes — awaiting them only
# delayed the desktop boot before the voice pipeline could come up.
_BOOT_BACKGROUND_TASKS: set[asyncio.Task[Any]] = set()
@@ -199,12 +199,13 @@ def _select_subagent_worker_kind(
# stripped from the worker env (the OAuth login then bills the subscription).
if sub_jarvis_provider in ANTIGRAVITY_SUBAGENT_SLUGS:
return "antigravity"
- # grok / openai / openrouter run ON their own provider via the in-process
+ # openai / openrouter run ON their own provider via the in-process
# ApiAgentWorker (OpenAI-compatible chat API + tool-use loop writing files
- # into the worktree). Before 2026-06-22 they fell through to "subjarvis" ->
- # ClaudeDirectWorker, so picking "Grok" silently ran the mission on Claude
+ # into the worktree). They used to fall through to "subjarvis" ->
+ # ClaudeDirectWorker, so picking them silently ran the mission on Claude
# (violates the "selected provider must run" mandate). A HARD LOCK like
- # claude-api/antigravity: no per-step model can divert it.
+ # claude-api/antigravity: no per-step model can divert it. (xAI Grok was
+ # removed as a sub-agent provider 2026-06-22 — TTS-only now.)
if sub_jarvis_provider in _API_AGENT_SLUGS:
return "api_agent"
# Explicitly selecting "gemini" routes to the direct GeminiWorker so the
@@ -228,7 +229,7 @@ def subagent_runs_on_claude_fallback(sub_jarvis_provider: str | None) -> bool:
"""True when picking this subagent provider does NOT run heavy missions on
THAT provider but silently falls back to the ClaudeDirectWorker (Opus).
- As of 2026-06-22 grok/openai/openrouter resolve to the ``"api_agent"`` kind
+ As of 2026-06-22 openai/openrouter resolve to the ``"api_agent"`` kind
(the in-process ApiAgentWorker runs them on their OWN provider), so they no
longer report a Claude fallback here — provided an API key is configured. The
only remaining always-Claude case is the legacy ``"subjarvis"`` kind
diff --git a/jarvis/missions/isolation/env.py b/jarvis/missions/isolation/env.py
index a9352b2117..57568e807c 100644
--- a/jarvis/missions/isolation/env.py
+++ b/jarvis/missions/isolation/env.py
@@ -21,10 +21,57 @@ import json
import logging
import os
import shutil
+from collections.abc import Mapping
from pathlib import Path
+from jarvis.missions.workers.process_utils import resolve_node_executable
+
logger = logging.getLogger(__name__)
+
+def _worker_path_repair_is_windows() -> bool:
+ """True on Windows hosts. Extracted so tests can force the POSIX branch."""
+ return os.name == "nt"
+
+
+def _repair_windows_worker_path(
+ path: str, *, environ: Mapping[str, str], node_exe: str | None
+) -> str:
+ """Additively repair a worker PATH so essential dirs are always present.
+
+ The worker env REPLACES os.environ, so it inherits whatever PATH jarvis was
+ launched with. When jarvis is started by an agent runtime with a degraded
+ PATH (live forensic 2026-06-20: the hermes-agent launch had no Node.js dir),
+ the codex worker's ``codex.CMD`` shim resolves bare ``node`` via PATH,
+ cmd.exe fails "'node' is not recognized", and every mission dies in ~25 ms.
+ A missing System32 also breaks ``chcp`` (the Antigravity-brain symptom).
+
+ This APPENDS the essential System32 / Node.js / npm-global dirs when they
+ are absent — it never reorders or drops existing entries, so a binary that
+ was already resolvable keeps its original source. Returns ``path`` unchanged
+ when nothing needs adding.
+ """
+ root = environ.get("SystemRoot") or environ.get("windir") or r"C:\Windows"
+ essentials: list[str] = [
+ os.path.join(root, "System32"),
+ root,
+ os.path.join(root, "System32", "Wbem"),
+ os.path.join(root, "System32", "WindowsPowerShell", "v1.0"),
+ ]
+ if node_exe:
+ essentials.append(str(Path(node_exe).parent))
+ appdata = environ.get("APPDATA")
+ if appdata:
+ # npm-global shims (codex.cmd / claude.cmd / gemini.cmd) live here.
+ essentials.append(os.path.join(appdata, "npm"))
+
+ existing = [p for p in path.split(os.pathsep) if p]
+ seen = {p.rstrip("\\/").lower() for p in existing}
+ additions = [d for d in essentials if d.rstrip("\\/").lower() not in seen]
+ if not additions:
+ return path
+ return os.pathsep.join(existing + additions)
+
# System variables that are ALWAYS forwarded from os.environ (when set).
# - PATH: without it the worker cannot find binaries (git, claude, codex, python).
# - SystemRoot: Windows internals; cmd.exe/python.exe need it.
@@ -95,6 +142,32 @@ def build_worker_env(
env["CLAUDE_CODE_DISABLE_NONESSENTIAL_TRAFFIC"] = "1"
env["CODEX_HOME"] = str(run_dir / ".codex")
+ # ROOT-CAUSE FIX (2026-06-20): jarvis can be launched by an agent runtime
+ # (hermes-agent) with a degraded PATH that lacks the Node.js dir / System32.
+ # Because this env REPLACES os.environ, the worker inherits that broken PATH
+ # verbatim, the codex `codex.CMD` shim can't find `node`, and EVERY mission
+ # dies `task_error` in ~25 ms ("Der Worker ist abgebrochen."). Repair the
+ # PATH additively and forward the Windows shell vars a `.cmd` shim / `chcp`
+ # need, so a worker runs regardless of how jarvis itself was started.
+ if _worker_path_repair_is_windows():
+ env["PATH"] = _repair_windows_worker_path(
+ env.get("PATH", ""),
+ environ=os.environ,
+ node_exe=resolve_node_executable(),
+ )
+ for var in (
+ "ComSpec",
+ "PATHEXT",
+ "windir",
+ "NUMBER_OF_PROCESSORS",
+ "PROCESSOR_ARCHITECTURE",
+ "PROCESSOR_ARCHITEW6432",
+ "TMP",
+ ):
+ value = os.environ.get(var)
+ if value is not None and var not in env:
+ env[var] = value
+
# ROOT-CAUSE FIX (2026-05-29): pin the worker/critic `claude` CLI to an
# ISOLATED config dir so it does NOT load the user's global ~/.claude
# plugins + hooks. A Phase-6 worker runs `claude --print` as the same OS
diff --git a/jarvis/missions/isolation/worktree.py b/jarvis/missions/isolation/worktree.py
index e02f411257..2a0c639ad5 100644
--- a/jarvis/missions/isolation/worktree.py
+++ b/jarvis/missions/isolation/worktree.py
@@ -56,6 +56,29 @@ _SLUG_RE = re.compile(r"[^a-z0-9]+")
# archive dirs is owned by ``cleanup.startup_sweep`` instead.
_RUN_DIR_RE = re.compile(r"^\d{8}T\d{6}__.+__[0-9a-f]{8}$")
+# Regenerable dependency / cache trees a worker may create (npm/pip/yarn/etc.).
+# These are NEVER a deliverable and, on Windows, a fresh `npm install` can drop
+# tens of thousands of files here. Walking them blows the 10 s cap on the
+# per-iteration ``git add -A`` in ``Kontrollierer._capture_diff`` -> empty diff
+# -> "no usable output" -> the worker's REAL build is discarded and rmtree'd
+# (live mission 019ee416, 2026-06-20: a complete Remotion promo video lost this
+# way). Excluding them via the lean repo's ``.git/info/exclude`` makes git skip
+# the whole subtree (it never descends an ignored top-level dir) AND keeps the
+# patterns out of the captured diff. Build-OUTPUT dirs (dist/, build/, out/)
+# are DELIBERATELY not listed — a rendered video or a built site IS a
+# legitimate deliverable and must still reach the Critic.
+_DEPENDENCY_EXCLUDE_DIRS: tuple[str, ...] = (
+ "node_modules/",
+ ".venv/",
+ "venv/",
+ "__pycache__/",
+ ".pnpm-store/",
+ ".yarn/cache/",
+ ".pytest_cache/",
+ ".mypy_cache/",
+ ".ruff_cache/",
+)
+
def _slugify(value: str) -> str:
"""Lowercase, non-alphanum -> '-', trimmed."""
@@ -207,8 +230,42 @@ class WorktreeManager:
],
cwd=workspace,
)
+ # Keep the per-iteration `git add -A` cheap when the worker installs
+ # dependencies (npm/pip) into this lean workspace — see
+ # `_DEPENDENCY_EXCLUDE_DIRS`. Lean only: a full worktree shares the host
+ # repo's `.git/info/exclude` (which already ignores node_modules/) and
+ # its `.git` is a FILE, so there is nothing local to write here.
+ self._write_dependency_excludes(workspace)
return workspace
+ def _write_dependency_excludes(self, workspace: Path) -> None:
+ """Append `_DEPENDENCY_EXCLUDE_DIRS` to the lean repo's
+ ``.git/info/exclude``.
+
+ Local to this throwaway lean repo (never touches the host repo). The
+ patterns make git skip whole dependency subtrees during ``git add -A``,
+ the live cause of the 10 s diff-capture timeout that discarded a
+ finished Remotion build (mission 019ee416).
+
+ Best-effort: a write failure (e.g. a full-mode workspace whose ``.git``
+ is a file) is logged and swallowed — the mission still runs, it just
+ pays the slower add. Never aborts workspace creation.
+ """
+ exclude_file = workspace / ".git" / "info" / "exclude"
+ try:
+ exclude_file.parent.mkdir(parents=True, exist_ok=True)
+ with exclude_file.open("a", encoding="utf-8") as fh:
+ fh.write(
+ "\n# Personal Jarvis: regenerable dependency/cache trees "
+ "(keeps `git add -A` cheap; never a deliverable)\n"
+ )
+ fh.write("\n".join(_DEPENDENCY_EXCLUDE_DIRS) + "\n")
+ except OSError as exc:
+ logger.warning(
+ "could not write dependency excludes to %s: %s",
+ exclude_file, exc,
+ )
+
# BUG-LIVE-05 (2026-05-14) — Retry delays for the Windows file-
# handle race in `git worktree remove`. The OpenClaw subprocess
# may still hold one of its trajectory / SQLite handles for a
diff --git a/jarvis/missions/kontrollierer/deliverable_paths.py b/jarvis/missions/kontrollierer/deliverable_paths.py
index 62ebccc6e3..7788c20aee 100644
--- a/jarvis/missions/kontrollierer/deliverable_paths.py
+++ b/jarvis/missions/kontrollierer/deliverable_paths.py
@@ -36,7 +36,9 @@ as long as the patterns stay tight (guarded by ``test_deliverable_paths.py``).
"""
from __future__ import annotations
+import posixpath
import re
+from collections.abc import Callable, Sequence
from typing import Final
# Directory-segment names whose contents are never worker deliverables: git
@@ -156,7 +158,131 @@ def is_deliverable_path(rel: str, *, managed_files: frozenset[str] = frozenset()
return not is_nondeliverable_scratch(norm)
+# --- Generator / build-script detection (content-aware, cross-file) -----------
+# The predicates above are pure path-string filters. The check below is a
+# different shape: it reads file CONTENT and looks ACROSS the deliverable set to
+# spot a script whose only purpose is to emit ANOTHER deliverable.
+#
+# Live forensic 2026-06-22 (mission_019ef099): the user asked by voice for "one
+# HTML file" and the worker shipped melbourne_guide.html PLUS generate_guide.py
+# — a Python script that embeds the whole page as a string literal and writes
+# the sibling .html — PLUS a hero image. The user opened the .py in a browser,
+# saw "only code", and wanted that process scratch gone ("nur das Hauptding").
+# A path-only denylist cannot catch this: generate_guide.py is a perfectly
+# normal-looking file in artifacts/files/. So this filter inspects content.
+#
+# Safe by construction: a script is only flagged when the document it emits is
+# ALSO in the set, and documents are never script-typed, so the emitted artifact
+# always survives. A standalone script the user actually requested has no
+# emitted sibling in the set and is never flagged.
+
+_GENERATOR_SCRIPT_EXTS: Final[frozenset[str]] = frozenset({
+ ".py", ".js", ".mjs", ".cjs", ".ts", ".rb", ".php", ".sh", ".bash", ".ps1", ".pl",
+})
+
+# Document/markup outputs a build script typically EMITS — things the user looks
+# at, not data formats they post-process (no .csv/.json: a script writing those
+# is more likely a tool the user wanted, so we conservatively keep it).
+_GENERATED_DOC_EXTS: Final[frozenset[str]] = frozenset({
+ ".html", ".htm", ".xhtml", ".md", ".markdown", ".svg", ".xml", ".rss", ".atom", ".pdf",
+})
+
+# A write/emit signal anywhere in the script body. Combined with a reference to
+# the sibling document's basename, this marks "this script writes that file".
+_WRITE_SIGNATURE_RE: Final[re.Pattern[str]] = re.compile(
+ r"open\s*\([^)]*['\"][wa]" # open(..., 'w'|'a' ...)
+ r"|\.write(?:lines)?\s*\(" # .write( / .writelines(
+ r"|\.write_text\s*\(" # pathlib Path.write_text(
+ r"|write_?file(?:sync)?\s*\(" # node writeFile / writeFileSync(
+ r"|\bfs\.write" # node fs.write*
+ r"|Out-File\b|Set-Content\b" # PowerShell
+ r"|>>?\s*['\"]?\S+\.[A-Za-z0-9]+", # shell redirect to a file
+ re.IGNORECASE,
+)
+
+# Markup-literal fingerprints per document extension: a script embedding these
+# is emitting that document even when its write call is obscured (a template
+# engine, an f-string sink, etc.).
+_DOC_LITERAL_SIGNATURES: Final[dict[str, tuple[str, ...]]] = {
+ ".html": ("<!doctype html", "<html"),
+ ".htm": ("<!doctype html", "<html"),
+ ".xhtml": ("<!doctype html", "<html"),
+ ".svg": ("<svg",),
+ ".xml": ("<?xml",),
+ ".rss": ("<?xml", "<rss"),
+ ".atom": ("<?xml", "<feed"),
+}
+
+
+def _ext(rel: str) -> str:
+ return posixpath.splitext(rel.replace("\\", "/"))[1].lower()
+
+
+def _basename(rel: str) -> str:
+ return posixpath.basename(rel.replace("\\", "/").strip("/"))
+
+
+def _script_emits_doc(text: str, doc_rel: str) -> bool:
+ """True iff *text* (a script body) generates the document *doc_rel*.
+
+ Requires the document's basename to appear in the script AND either a write
+ signature or an embedded markup literal for the document's type.
+ """
+ base = _basename(doc_rel)
+ if not base or base not in text:
+ return False
+ if _WRITE_SIGNATURE_RE.search(text):
+ return True
+ low = text.lower()
+ return any(sig in low for sig in _DOC_LITERAL_SIGNATURES.get(_ext(doc_rel), ()))
+
+
+def find_generator_scripts(
+ rels: Sequence[str],
+ read_text: Callable[[str], str],
+) -> frozenset[str]:
+ """Return the subset of *rels* that are generator/build scripts.
+
+ A generator script is one whose sole purpose is to emit ANOTHER document
+ deliverable that is itself in *rels* (e.g. a ``generate_guide.py`` that
+ writes ``melbourne_guide.html``). Such a script is process scratch, not the
+ artifact the user asked for.
+
+ *read_text* maps a worktree-relative path to its text content (injected so
+ this stays pure and testable). Only script-typed files are ever read.
+
+ Safe by construction:
+ * documents are never script-typed, so an emitted document always survives;
+ * a script with no emitted sibling document in the set is never flagged;
+ * if flagging would leave the set empty, nothing is flagged.
+ """
+ items = [r for r in rels if r]
+ docs = [r for r in items if _ext(r) in _GENERATED_DOC_EXTS]
+ if not docs:
+ return frozenset()
+ generators: set[str] = set()
+ for rel in items:
+ if _ext(rel) not in _GENERATOR_SCRIPT_EXTS:
+ continue
+ try:
+ text = read_text(rel) or ""
+ except OSError:
+ continue
+ if not text:
+ continue
+ for doc in docs:
+ if doc != rel and _script_emits_doc(text, doc):
+ generators.add(rel)
+ break
+ # Never leave the user with nothing (defensive — documents always survive,
+ # so this can only trip on a pathological all-script match).
+ if not [r for r in items if r not in generators]:
+ return frozenset()
+ return frozenset(generators)
+
+
__all__ = [
+ "find_generator_scripts",
"is_browser_scratch_segment",
"is_deliverable_path",
"is_nondeliverable_scratch",
diff --git a/jarvis/missions/kontrollierer/orchestrator.py b/jarvis/missions/kontrollierer/orchestrator.py
index 52b8511bcf..13c38cac0e 100644
--- a/jarvis/missions/kontrollierer/orchestrator.py
+++ b/jarvis/missions/kontrollierer/orchestrator.py
@@ -73,7 +73,7 @@ from .deliverable import (
deliver_to_user_folder,
materialize_answer_document,
)
-from .deliverable_paths import is_deliverable_path
+from .deliverable_paths import find_generator_scripts, is_deliverable_path
from ..safety import (
extract_worker_authored_text,
filter_diff_paths,
@@ -83,6 +83,7 @@ from ..safety import (
from ..state_machine import IllegalStateTransition, MissionState
from ..workers.base import WorkerProtocol
from .decomposer import MissionDecomposer, MissionPlan, Step
+from .worker_prompt import compose_worker_prompt
logger = logging.getLogger(__name__)
@@ -206,6 +207,19 @@ def _is_deliverable_path(rel: str) -> bool:
return is_deliverable_path(rel, managed_files=_MANAGED_PERSONA_FILES)
+def _safe_read_text(path: Path) -> str:
+ """Read a worktree file as UTF-8 text, never raising.
+
+ Used by the generator-script filter (:func:`find_generator_scripts`) to
+ inspect a candidate script's body. Only script-typed files reach here, so
+ this never tries to slurp a large binary. Returns "" on any read error.
+ """
+ try:
+ return path.read_text(encoding="utf-8", errors="replace")
+ except OSError:
+ return ""
+
+
def _real_diff_is_empty(diff_text: str) -> bool:
"""True iff the diff carries no foreign hunks after stripping
managed persona files.
@@ -1071,9 +1085,12 @@ class Kontrollierer:
for iteration in range(MAX_CRITIC_LOOPS):
# Per-iteration: render reflections, spawn worker, capture diff+log
prior_block = reflections.render_for_worker_prompt(n=3)
- worker_prompt = (
- prior_block + "\n\n" + step.prompt if prior_block else step.prompt
- )
+ # Lead every worker prompt with the artifact-language directive so
+ # generated code defaults to English regardless of the request
+ # language (the German-request -> German-code leak). This is the one
+ # chokepoint every worker prompt passes through — all decomposition
+ # paths, all worker CLIs, every critic iteration.
+ worker_prompt = compose_worker_prompt(prior_block, step.prompt)
# State-Machine drive-thru:
# iter 0: PENDING/RUNNING -> CRITIQUING (single jump).
@@ -2275,6 +2292,20 @@ class Kontrollierer:
# enumerate, so this filter keeps artifacts/files/ to genuine
# deliverables (no Outputs-UI garbage, the Wave-3 invariant).
untracked = [rel for rel in untracked if _is_deliverable_path(rel)]
+ # Drop generator/build scripts whose only purpose is to emit a
+ # sibling DOCUMENT deliverable that survives in the set (e.g. a
+ # generate_guide.py that writes melbourne_guide.html as an embedded
+ # literal). The script is process scratch the user did not ask for —
+ # live forensic 2026-06-22 (mission_019ef099): a "make me one HTML
+ # file" mission shipped the HTML PLUS its Python generator, which the
+ # user opened and saw "only code". Safe by construction: the emitted
+ # document is never script-typed, so it always survives.
+ if untracked:
+ _generators = find_generator_scripts(
+ untracked, lambda rel: _safe_read_text(worktree / rel)
+ )
+ if _generators:
+ untracked = [r for r in untracked if r not in _generators]
if untracked:
files_root = artifacts / "files"
for rel in untracked:
diff --git a/jarvis/missions/kontrollierer/worker_prompt.py b/jarvis/missions/kontrollierer/worker_prompt.py
new file mode 100644
index 0000000000..e55336ac4f
--- /dev/null
+++ b/jarvis/missions/kontrollierer/worker_prompt.py
@@ -0,0 +1,96 @@
+"""Worker-prompt composition + the artifact-language directive.
+
+This is the single chokepoint that guarantees every dispatched worker is told
+to produce **English code artifacts by default**, regardless of the language the
+user spoke in.
+
+Why a dedicated module
+----------------------
+The mission-dispatch chain is mostly German-flavoured: the user speaks German,
+``spawn_worker._build_mission_prompt`` wraps the request with German labels
+("Aufgabe", "Wortlaut des Nutzers"), and for short missions the verbatim German
+utterance is handed to the worker unchanged (the decomposer's heuristic
+single-step path never rewrites it). With no instruction to the contrary, the
+worker mirrors the request language and writes German identifiers, comments and
+docstrings — a direct violation of the repo Output Language Policy ("every
+artifact an agent produces is English").
+
+The fix is one directive, prepended to the worker prompt at the one place every
+worker prompt is built (``orchestrator._run_iterations``), so it covers all
+decomposition paths (heuristic single-step, LLM multi-step), all worker CLIs
+(Claude / Codex / Gemini), every critic iteration, and any future spawn entry
+point — provider-agnostically.
+
+The directive is deliberately a *default*, not an absolute: it governs the
+*medium* (code), never the *subject matter*. A deliverable whose content is
+meant to be German (a German news page, quoted text, localized copy) stays
+German; only the surrounding code artifacts default to English.
+"""
+from __future__ import annotations
+
+from typing import Final
+
+# Prepended to every worker prompt. Kept provider-agnostic and language-neutral:
+# it must hold no matter what language the request arrived in (the leak was
+# "German request -> German code"), so it can never be a de/en toggle.
+ARTIFACT_LANGUAGE_DIRECTIVE: Final[str] = (
+ "ARTIFACT LANGUAGE - DEFAULT ENGLISH (this is an international repository). "
+ "Write every CODE ARTIFACT in English: identifiers, function/class/variable "
+ "names, comments, docstrings, log and error messages, commit messages, test "
+ "names, and technical documentation. This holds even when this task "
+ "description, the user's words, or the surrounding conversation are in "
+ "another language - do NOT mirror the request language into the code. "
+ "EXCEPTION: keep another language only where that language is the actual "
+ "SUBJECT MATTER rather than the medium - user-facing copy / UI text or "
+ "document content in the language the user asked for, quoted or localized "
+ "text, and test fixtures that assert on non-English input. When the user "
+ "EXPLICITLY requests a specific language for the artifact itself, honor that "
+ "request."
+)
+
+
+# Prepended to every worker prompt, right after the language directive. Root
+# cause (2026-06-22, mission 019ef052): the user asked for a SINGLE HTML file;
+# the worker shipped four (index.html + app.js + styles.css + assets/). The
+# standing _QUALITY_DIRECTIVE ("never downgrade to a minimal version, treat a
+# skeleton hint as a floor not a ceiling") reads a single self-contained file as
+# a forbidden minimal version, so the worker built the "production-quality" norm
+# of a split multi-file project — overriding the user's explicit form constraint.
+# Nothing in the chain told the worker that honoring a requested SHAPE is part of
+# the job. This directive is that missing layer. Kept ASCII / provider- and
+# language-agnostic: a form constraint must be honored no matter the request
+# language or which worker CLI runs.
+OUTPUT_SHAPE_DIRECTIVE: Final[str] = (
+ "OUTPUT SHAPE - HONOR EXPLICIT FORM CONSTRAINTS. When the request fixes the "
+ "SHAPE or packaging of the deliverable - a single self-contained file, one "
+ "HTML file with its CSS and JS inlined, exactly one script, a specific file "
+ "count, or a named output format - treat that as a HARD requirement and "
+ "deliver in EXACTLY that form, even when it means inlining or consolidating "
+ "what you would otherwise split across several files. Honoring a constraint "
+ "the user set is part of satisfying the request; it is NEVER a downgrade, a "
+ "stub, or a minimal version. When the request fixes no shape, use your best "
+ "professional judgment for how to package the result."
+)
+
+
+def compose_worker_prompt(prior_block: str, step_prompt: str) -> str:
+ """Build the full worker prompt: framing directives first.
+
+ Leads with the artifact-language directive and then the output-shape
+ directive, so both frame the whole task before any prior feedback or
+ instruction is read. ``prior_block`` is the (possibly empty) rendered
+ critic-reflection block that carries correction context across iterations.
+ ``step_prompt`` is the task instruction for this step (verbatim user
+ utterance or a decomposed sub-task).
+ """
+ head = f"{ARTIFACT_LANGUAGE_DIRECTIVE}\n\n{OUTPUT_SHAPE_DIRECTIVE}"
+ if prior_block and prior_block.strip():
+ return f"{head}\n\n{prior_block}\n\n{step_prompt}"
+ return f"{head}\n\n{step_prompt}"
+
+
+__all__ = [
+ "ARTIFACT_LANGUAGE_DIRECTIVE",
+ "OUTPUT_SHAPE_DIRECTIVE",
+ "compose_worker_prompt",
+]
diff --git a/jarvis/missions/worker_runtime/provider_map.py b/jarvis/missions/worker_runtime/provider_map.py
index 9faa08257d..54d219cd84 100644
--- a/jarvis/missions/worker_runtime/provider_map.py
+++ b/jarvis/missions/worker_runtime/provider_map.py
@@ -107,7 +107,7 @@ MAPPINGS: Final[tuple[ProviderMapping, ...]] = (
),
ProviderMapping("openai", "openai", "OPENAI_API_KEY"),
ProviderMapping("openrouter", "openrouter", "OPENROUTER_API_KEY"),
- ProviderMapping("grok", "xai", "XAI_API_KEY", "GROK_API_KEY"),
+ # xAI Grok removed as a sub-agent/brain provider 2026-06-22 (TTS-only now).
)
@@ -157,8 +157,8 @@ def to_jarvis_slug(openclaw_provider: str) -> str:
"""OpenClaw-Slug zu Personal-Jarvis-Slug (Reverse-Mapping fuer Telemetrie).
Beispiel:
- >>> to_jarvis_slug("xai")
- 'grok'
+ >>> to_jarvis_slug("google")
+ 'gemini'
Raises:
UnknownOpenclawProviderError: Wenn `openclaw_provider` nicht in MAPPINGS ist.
diff --git a/jarvis/missions/workers/api_agent_tools.py b/jarvis/missions/workers/api_agent_tools.py
index 7d5ccdaf2c..e99946e546 100644
--- a/jarvis/missions/workers/api_agent_tools.py
+++ b/jarvis/missions/workers/api_agent_tools.py
@@ -1,7 +1,7 @@
"""Worktree-scoped file/shell tools for the in-process API-agent worker.
These are the hands of :class:`ApiAgentWorker` — the worker that drives an
-OpenAI-compatible brain (grok / openai / openrouter) in a tool-use loop. The
+OpenAI-compatible brain (openai / openrouter) in a tool-use loop. The
CLI workers (claude / codex / agy) get Write/Edit/Read/Bash from their own
binary; an in-process brain has none, so we supply a minimal, deliberately
small set here.
diff --git a/jarvis/missions/workers/api_agent_worker.py b/jarvis/missions/workers/api_agent_worker.py
index b23ea8a6fd..8aac9cfaf5 100644
--- a/jarvis/missions/workers/api_agent_worker.py
+++ b/jarvis/missions/workers/api_agent_worker.py
@@ -1,9 +1,9 @@
"""ApiAgentWorker — an in-process agentic Phase-6 worker for API brains.
The CLI workers (claude / codex / agy) wrap a vendor binary that ships its own
-agent loop + file tools. The pure-API providers — **grok**, **openai**,
-**openrouter** — have no such CLI, so picking them as the subagent provider used
-to fall through to the Claude worker ("Grok" silently ran on Claude). This worker
+agent loop + file tools. The pure-API providers — **openai**, **openrouter** —
+have no such CLI, so picking them as the subagent provider used to fall through
+to the Claude worker (they silently ran on Claude). This worker
closes that gap: it drives the selected provider's own chat API
(`jarvis.plugins.brain.*`) in a tool-use loop, writing real files into the git
worktree via :mod:`api_agent_tools`, and emits the same claude-shaped stream the
@@ -47,7 +47,6 @@ logger = logging.getLogger(__name__)
# Provider slug -> (module, class). Lazy-imported so a worker for one provider
# never imports another's SDK path. Slugs match jarvis provider ids.
_BRAIN_BY_PROVIDER: dict[str, tuple[str, str]] = {
- "grok": ("jarvis.plugins.brain.grok", "GrokBrain"),
"openai": ("jarvis.plugins.brain.openai", "OpenAIBrain"),
"openrouter": ("jarvis.plugins.brain.openrouter", "OpenRouterBrain"),
}
@@ -55,7 +54,6 @@ _BRAIN_BY_PROVIDER: dict[str, tuple[str, str]] = {
# Per-provider default deep model when the step carries none. Documented
# defaults only — never a gate (AP-21).
_DEFAULT_MODEL: dict[str, str] = {
- "grok": "grok-4.3",
"openai": "gpt-5.5",
"openrouter": "anthropic/claude-opus-4.8",
}
diff --git a/jarvis/missions/workers/claude_direct_worker.py b/jarvis/missions/workers/claude_direct_worker.py
index 44a010e37b..9cde6a8a92 100644
--- a/jarvis/missions/workers/claude_direct_worker.py
+++ b/jarvis/missions/workers/claude_direct_worker.py
@@ -299,23 +299,27 @@ class ClaudeDirectWorker:
# 1. Resolve which claude model this worker runs.
#
- # Post-Welle-4, ClaudeDirectWorker is the UNIVERSAL heavy-worker
- # fallback: the OpenClaw-backed SubJarvisWorker was removed (it caused
- # the ~92% nested-claude hang), so jarvis.missions.init._worker_factory
- # routes EVERY [brain.sub_jarvis].provider that is not
- # openai-codex/chatgpt (grok, gemini, openai, openrouter,
- # openclaw-claude, AND the unset default — whose chain resolver falls
- # back to the ("grok", "grok-4.3") stub) to THIS worker, which always
- # executes on the Claude Max OAuth claude-cli backend.
+ # ClaudeDirectWorker runs the Claude Max OAuth claude-cli backend. The
+ # selected [brain.sub_jarvis].provider is HONORED — a provider with its
+ # own worker runs on THAT provider, picked in
+ # jarvis.missions.init._worker_factory: codex -> CodexDirectWorker,
+ # antigravity -> GoogleCliWorker, gemini -> GeminiWorker,
+ # openai/openrouter -> ApiAgentWorker. This worker is reached only:
+ # 1. when sub_jarvis.provider == "claude-api" (the deliberate choice), or
+ # 2. as the UNIVERSAL FALLBACK when the chosen provider cannot run this
+ # mission — its API key is missing / the codex login is dead — or when
+ # an old/unknown provider is configured (openclaw-claude / unset / the
+ # removed OpenClaw "subjarvis" path that caused the ~92% nested-claude
+ # hang). The factory LOGS every such fallback; the choice is never
+ # silently swapped (anti-silent-fallback mandate).
#
- # The old "refuse unless the resolved provider is claude-api" guard
- # assumed a SubJarvisWorker fall-through that NO LONGER EXISTS — so it
- # turned every non-claude sub_jarvis setting into an INSTANT mission
- # failure (forensic 2026-06-08: missions 019ea82e* / 019ea830* died in
- # ~3 s with "primary provider is grok, expected claude-api"). We now
- # always run on Claude and only LOG when the configured provider
- # differs, so the fallback is legible, never a silent swap
- # (anti-silent-fallback mandate).
+ # So this worker must NOT re-impose a "refuse unless provider==claude-api"
+ # guard: the old guard assumed a SubJarvisWorker fall-through that NO LONGER
+ # EXISTS and turned every non-claude sub_jarvis setting into an INSTANT
+ # mission failure (forensic 2026-06-08: missions 019ea82e* / 019ea830* died
+ # in ~3 s with "primary provider is <X>, expected claude-api"). We resolve
+ # the claude model from the chain, run on Claude here, and only LOG when the
+ # configured provider differs.
chain = _resolve_provider_chain()
primary = chain[0] if chain else None
claude_model = _resolve_claude_model(primary)
diff --git a/jarvis/missions/workers/codex_direct_worker.py b/jarvis/missions/workers/codex_direct_worker.py
index d2a23ef9ef..a3dc7c698c 100644
--- a/jarvis/missions/workers/codex_direct_worker.py
+++ b/jarvis/missions/workers/codex_direct_worker.py
@@ -44,7 +44,7 @@ from contextlib import suppress
from pathlib import Path
from typing import Any, ClassVar, Literal
-from .process_utils import create_worker_subprocess
+from .process_utils import create_worker_subprocess, resolve_node_executable
from .stream_consumer import (
ClaudeAssistantMessage,
ClaudeResult,
@@ -90,7 +90,13 @@ _MISSION_REASONING_EFFORT: str = "medium"
def _resolve_codex_binary() -> str | None:
- """Return the on-PATH ``codex`` binary, considering Windows extensions."""
+ """Return the on-PATH ``codex`` binary, considering Windows extensions.
+
+ Kept for the fallback path in :func:`_resolve_codex_argv_prefix` and for
+ tests that pin a single string. Production spawns should call
+ :func:`_resolve_codex_argv_prefix` instead — it returns the full argv
+ prefix (``node`` + ``bin/codex.js``) that sidesteps the ``codex.CMD`` shim.
+ """
for name in ("codex", "codex.cmd", "codex.exe"):
path = shutil.which(name)
if path:
@@ -98,6 +104,48 @@ def _resolve_codex_binary() -> str | None:
return None
+def _resolve_codex_argv_prefix() -> list[str]:
+ """Return the argv prefix for invoking codex, preferring ``node <codex.js>``.
+
+ On Windows the npm-installed CLI ships as ``codex.CMD`` — a batch shim whose
+ tail line resolves the interpreter as the *bare* command ``node`` via PATH:
+
+ ... || title %COMSPEC% & "%_prog%" "...\\bin\\codex.js" %* (_prog="node")
+
+ When jarvis is launched with a degraded PATH that lacks the Node.js dir
+ (live forensic 2026-06-20: jarvis started by the hermes-agent runtime),
+ cmd.exe dies with ``'node' is not recognized`` and exits 1 in ~25 ms —
+ BEFORE codex starts — so every mission fails ``task_error`` ("Der Worker ist
+ abgebrochen."). Invoking the JS entrypoint with an ABSOLUTE ``node`` path
+ bypasses the .CMD shim, the cmd.exe layer, and the inherited-PATH
+ dependency entirely. Mirrors ``gemini_worker._resolve_gemini_argv_prefix``
+ and ``provider_chain._resolve_worker_argv_prefix`` (same class of fix).
+
+ Falls back to the bare codex binary only when ``node`` + the JS entrypoint
+ cannot be located together — the prompt is passed on stdin, so the cmd.exe
+ metacharacter trap does not apply to that fallback.
+
+ Node is resolved via :func:`resolve_node_executable`, which probes well-known
+ install locations when the inherited PATH is degraded — otherwise the very
+ PATH gap that breaks ``codex.CMD`` would also hide node from this bypass.
+ """
+ node = resolve_node_executable()
+ if node:
+ for name in ("codex", "codex.cmd", "codex.exe"):
+ cli = shutil.which(name)
+ if not cli:
+ continue
+ cli_dir = Path(cli).resolve().parent
+ # npm shim layout: ``<npm-root>/codex.cmd`` →
+ # ``<npm-root>/node_modules/@openai/codex/bin/codex.js``.
+ candidate = (
+ cli_dir / "node_modules" / "@openai" / "codex" / "bin" / "codex.js"
+ )
+ if candidate.is_file():
+ return [node, str(candidate)]
+ return [_resolve_codex_binary() or "codex"]
+
+
def _codex_oauth_available() -> bool:
"""True when the user's global ``~/.codex`` carries a ChatGPT (OAuth) login.
@@ -183,7 +231,7 @@ def _build_codex_direct_cmd(
``--add-dir`` exposes the worktree to codex's filesystem layer.
"""
cmd: list[str] = [
- _resolve_codex_binary() or "codex",
+ *_resolve_codex_argv_prefix(),
"exec",
"--json",
"--skip-git-repo-check",
@@ -745,5 +793,6 @@ class CodexDirectWorker:
__all__ = [
"CodexDirectWorker",
"_build_codex_direct_cmd",
+ "_resolve_codex_argv_prefix",
"_resolve_codex_binary",
]
diff --git a/jarvis/missions/workers/process_utils.py b/jarvis/missions/workers/process_utils.py
index 47e5a47eb9..6bc01bf13b 100644
--- a/jarvis/missions/workers/process_utils.py
+++ b/jarvis/missions/workers/process_utils.py
@@ -3,6 +3,8 @@ from __future__ import annotations
import asyncio
import logging
+import os
+import shutil
import subprocess
import sys
from contextlib import suppress as contextlib_suppress
@@ -14,6 +16,51 @@ logger = logging.getLogger(__name__)
_CREATE_BREAKAWAY_FROM_JOB = 0x01000000
+def _windows_node_dir_candidates() -> list[str]:
+ """Well-known Windows directories that may contain ``node.exe``.
+
+ Probed only when ``shutil.which`` misses node — which happens when jarvis is
+ launched with a degraded PATH that lacks the Node.js dir (live forensic
+ 2026-06-20: jarvis started by the hermes-agent runtime, PATH had no nodejs
+ entry, so the codex worker's ``node`` lookup failed and every mission died).
+ """
+ candidates: list[str] = []
+ for var in ("ProgramFiles", "ProgramW6432", "ProgramFiles(x86)"):
+ base = os.environ.get(var)
+ if base:
+ candidates.append(os.path.join(base, "nodejs"))
+ local = os.environ.get("LOCALAPPDATA")
+ if local:
+ candidates.append(os.path.join(local, "Programs", "nodejs"))
+ appdata = os.environ.get("APPDATA")
+ if appdata:
+ # npm-global shims (codex.cmd etc.) and sometimes a node copy live here.
+ candidates.append(os.path.join(appdata, "npm"))
+ # Hardcoded default install path as a last resort.
+ candidates.append(r"C:\Program Files\nodejs")
+ return candidates
+
+
+def resolve_node_executable() -> str | None:
+ """Return an absolute path to ``node``, robust against a degraded PATH.
+
+ ``shutil.which`` searches the *inherited* PATH; when jarvis is launched with
+ a PATH that lacks the Node.js dir, that returns ``None`` and any node-direct
+ worker spawn would fall back to the fragile ``.cmd`` shim (whose own bare
+ ``node`` lookup ALSO fails) — the 2026-06-20 "alle Missionen scheitern"
+ incident. So when ``which`` misses, probe the well-known install locations.
+ """
+ found = shutil.which("node") or shutil.which("node.exe")
+ if found:
+ return found
+ if sys.platform == "win32":
+ for directory in _windows_node_dir_candidates():
+ candidate = os.path.join(directory, "node.exe")
+ if os.path.isfile(candidate):
+ return candidate
+ return None
+
+
def worker_creationflags() -> int:
"""Return Windows creation flags used for detached worker processes."""
if sys.platform != "win32":
@@ -93,5 +140,6 @@ __all__ = [
"contextlib_suppress",
"create_worker_subprocess",
"drain_stderr",
+ "resolve_node_executable",
"worker_creationflags",
]
diff --git a/jarvis/missions/workers/provider_chain.py b/jarvis/missions/workers/provider_chain.py
index e0ea0b6437..5522a00823 100644
--- a/jarvis/missions/workers/provider_chain.py
+++ b/jarvis/missions/workers/provider_chain.py
@@ -2,11 +2,11 @@
provider-agnostic Phase-6 worker.
SubJarvisWorker delegates to OpenClaw —
-which already supports `xai/grok-*`, `google/gemini-*`, `openai/gpt-*`,
+which already supports `google/gemini-*`, `openai/gpt-*`,
`anthropic/claude-*`, and `openrouter/*` behind a single CLI surface.
The provider+model is resolved from `[brain.sub_jarvis]` in jarvis.toml
-(provider in jarvis-slug form, e.g. "grok"; model in OpenClaw form, e.g.
-"grok-4.3"). The jarvis-to-openclaw slug translation lives in
+(provider in jarvis-slug form, e.g. "gemini"; model in OpenClaw form, e.g.
+"gemini-3.1-pro-preview"). The jarvis-to-openclaw slug translation lives in
`jarvis.missions.worker_runtime.provider_map.to_provider_slug` so this worker
never hardcodes slugs.
@@ -127,8 +127,8 @@ class _FallbackStep:
"""One link in the provider-fallback chain.
Resolved from `[brain.sub_jarvis]` in jarvis.toml. `provider` is the
- jarvis-slug ("grok", "openai", "gemini", "claude-api", "openrouter").
- `model` is the provider-native model id ("grok-4.3", "gpt-5.5-pro",
+ jarvis-slug ("openai", "gemini", "claude-api", "openrouter").
+ `model` is the provider-native model id ("gpt-5.5-pro",
"gemini-3.1-pro-preview", etc.). The OpenClaw slug translation
happens at spawn time via `to_provider_slug`.
"""
@@ -226,8 +226,8 @@ def _resolve_provider_chain(
1. Explicit `requested_provider` / `requested_model` args (the
decomposer can override per-step).
2. `cfg.brain.sub_jarvis.{provider,model}` plus fallback fields.
- 3. Last-ditch fallback to ("grok", "grok-4.3") so a stub config
- still produces a runnable argv in tests.
+ 3. Last-ditch fallback to ("gemini", "gemini-3.1-pro-preview") so a
+ stub config still produces a runnable argv in tests.
"""
chain: list[_FallbackStep] = []
@@ -295,7 +295,7 @@ def _resolve_provider_chain(
chain.append(candidate)
if not chain:
- chain.append(_FallbackStep("grok", "grok-4.3"))
+ chain.append(_FallbackStep("gemini", "gemini-3.1-pro-preview"))
return tuple(chain)
@@ -322,7 +322,7 @@ def _build_openclaw_cmd(
Stable order so the dry-run test can pin it argument-for-argument.
The model arg is `<openclaw_slug>/<model>` — the jarvis-slug must
have been translated to the openclaw-slug by the caller (e.g. via
- `to_provider_slug("grok") -> "xai"`).
+ `to_provider_slug("gemini") -> "google"`).
"""
prefix: list[str] = [binary] if isinstance(binary, str) else list(binary)
cmd: list[str] = [
diff --git a/jarvis/overlay/drop_bridge.py b/jarvis/overlay/drop_bridge.py
new file mode 100644
index 0000000000..5f8071391f
--- /dev/null
+++ b/jarvis/overlay/drop_bridge.py
@@ -0,0 +1,51 @@
+"""Process-global bridge from the Tk overlay drop to the app's brain intake.
+
+The floating overlay (``ui/orb/overlay.py``, ``jarvis/ui/whisperbar/overlay.py``)
+runs its Tk mainloop in a daemon thread and must stay ignorant of the asyncio
+loop, the EventBus and the brain. When a file/text is dropped on it, the overlay
+calls :func:`dispatch_drop` from the Tk thread; the desktop bridge
+(``jarvis/ui/desktop_app.py``) registers the real handler via
+:func:`set_drop_handler` — which marshals onto the asyncio loop and runs
+``jarvis.brain.drop_context.ingest_drop``.
+
+This avoids threading a callback through the surface factory / orb / bar
+constructors (low-touch wiring into fragile GUI code). The handler is a single
+process-global slot — there is one overlay per process.
+"""
+from __future__ import annotations
+
+import logging
+from collections.abc import Callable
+
+log = logging.getLogger(__name__)
+
+#: ``(file_paths, dragged_text)`` — exactly one populated per drop.
+OnDrop = Callable[[list[str], str], None]
+
+_HANDLER: OnDrop | None = None
+
+
+def set_drop_handler(handler: OnDrop | None) -> None:
+ """Register (or clear with ``None``) the overlay-drop handler."""
+ global _HANDLER
+ _HANDLER = handler
+
+
+def dispatch_drop(paths: list[str], text: str) -> bool:
+ """Deliver a drop to the registered handler. Never raises (Tk-thread safe).
+
+ Returns ``True`` if a handler was present (regardless of whether it then
+ failed internally — a handler crash is swallowed so it can't wedge the Tk
+ mainloop), ``False`` if no handler is registered.
+ """
+ handler = _HANDLER
+ if handler is None:
+ return False
+ try:
+ handler(paths, text)
+ except Exception: # noqa: BLE001 — a Tk-thread callback must never propagate.
+ log.debug("overlay drop handler failed", exc_info=True)
+ return True
+
+
+__all__ = ["OnDrop", "set_drop_handler", "dispatch_drop"]
diff --git a/jarvis/overlay/drop_target.py b/jarvis/overlay/drop_target.py
new file mode 100644
index 0000000000..e7880d3b85
--- /dev/null
+++ b/jarvis/overlay/drop_target.py
@@ -0,0 +1,200 @@
+"""Cross-platform drag-drop target for the floating overlay (bar + mascot).
+
+The desktop power-user extra that lets a user drop files / text **directly onto
+the always-on-top Tk bar or mascot** (not just the in-app web dock). It follows
+the AD-6 seam shape used across ``jarvis/overlay/``: a ``DropTarget`` Protocol, a
+real implementation, a graceful null no-op, and a ``make_drop_target()`` factory
+that never raises.
+
+Cross-platform by construction: the real implementation drives the **tkdnd** Tcl
+extension via ``tkinterdnd2`` (bundled binaries for Windows / macOS / Linux,
+verified loading + registering on Windows and Linux), registered onto the
+existing Tk root **without replacing it** (``_require`` on the live root —
+compatible with the cached-root constraint, BUG-031). Where ``tkinterdnd2`` / the
+``tkdnd`` binary fails to load (headless €5-VPS, an arch without a bundled binary,
+or — on Linux — the X11 runtime libs the tkdnd ``.so`` links against are absent),
+``register`` returns ``False`` and the factory/overlay degrade to a logged no-op
+— the web dock (``POST /api/chat/drop``) still carries the feature on every OS,
+so this extra is purely additive.
+
+**Linux runtime note (verified 2026-06-22):** the bundled ``linux-x64``
+``libtkdnd2.9.5.so`` links against X11 libs (``libXcursor.so.1`` et al.). A real
+Linux *desktop* running X11 has these; a bare ``python:3.11-slim`` does not, so
+``register`` returns ``False`` there (correctly — a headless box has no overlay
+anyway). Distro packages: ``libxcursor1 libxrender1 libxext6`` (+ ``python3-tk``).
+
+Import-cleanliness (HN-7): nothing here imports ``tkinterdnd2`` / Tk at module
+scope, so ``import jarvis.overlay.drop_target`` stays clean on a headless host.
+The dropped content is delivered to an ``on_drop(paths, text)`` callback; wiring
+that callback to the brain intake (``jarvis/brain/drop_context.ingest_drop``)
+lives in the desktop bridge, off this module.
+"""
+from __future__ import annotations
+
+import logging
+from collections.abc import Callable
+from typing import Any, Protocol, runtime_checkable
+
+log = logging.getLogger(__name__)
+
+#: ``on_drop`` is called with (file_paths, dragged_text). Exactly one is
+#: populated per drop: a file drop → (paths, ""), a text/URL drop → ([], text).
+OnDrop = Callable[[list[str], str], None]
+
+
+@runtime_checkable
+class DropTarget(Protocol):
+ """Registers OS drag-drop on a Tk widget. ``register`` never raises."""
+
+ def register(self, widget: Any, on_drop: OnDrop) -> bool:
+ """Wire ``on_drop`` to drops on ``widget``; True if actually registered."""
+ ...
+
+
+def _parse_dnd_files(data: str) -> list[str]:
+ """Parse a tkdnd ``<<Drop>>`` file payload into a list of paths.
+
+ tkdnd hands a Tcl list: space-separated paths, with any path that contains a
+ space wrapped in ``{}``. e.g. ``{C:/a b/one.txt} C:/c/two.png``.
+ """
+ s = data.strip()
+ if not s:
+ return []
+ out: list[str] = []
+ i, n = 0, len(s)
+ while i < n:
+ while i < n and s[i].isspace():
+ i += 1
+ if i >= n:
+ break
+ if s[i] == "{":
+ j = s.find("}", i + 1)
+ if j == -1:
+ out.append(s[i + 1 :].strip())
+ break
+ out.append(s[i + 1 : j])
+ i = j + 1
+ else:
+ j = i
+ while j < n and not s[j].isspace():
+ j += 1
+ out.append(s[i:j])
+ i = j
+ return [p for p in out if p]
+
+
+class NullDropTarget:
+ """No-op target — overlay drop is unavailable on this host (logged once)."""
+
+ def register(self, widget: Any, on_drop: OnDrop) -> bool: # noqa: ARG002
+ log.debug("Overlay drop target unavailable (tkdnd absent) — no-op.")
+ return False
+
+
+class TkDnDDropTarget:
+ """Drives the cross-platform ``tkdnd`` extension via ``tkinterdnd2`` (AD-6).
+
+ Registered onto the live Tk root in place (``_require``), so it composes with
+ the overlay's cached-root lifecycle. Any failure (missing binary, Tcl error)
+ degrades to ``False`` — the overlay keeps working, drop is simply off.
+ """
+
+ def register(self, widget: Any, on_drop: OnDrop) -> bool:
+ try:
+ import os
+
+ from tkinterdnd2 import COPY, DND_FILES, DND_TEXT, TkinterDnD # lazy (HN-7)
+
+ root = widget.winfo_toplevel()
+ # Load the tkdnd Tcl package into the EXISTING root — no new Tk root
+ # (BUG-031 cached-root constraint). Idempotent across overlays.
+ TkinterDnD._require(root)
+
+ # Remember the resting opacity so the hover highlight can dim back.
+ try:
+ rest_alpha = float(root.wm_attributes("-alpha"))
+ except Exception: # noqa: BLE001
+ rest_alpha = 0.6
+
+ def _highlight(on: bool) -> None:
+ # Visible drag feedback (window-level only — never fights the
+ # renderer): the pill goes fully opaque while a file hovers, so
+ # the user SEES exactly where the (small, frameless) drop zone is.
+ try:
+ root.wm_attributes("-alpha", 1.0 if on else rest_alpha)
+ except Exception: # noqa: BLE001, S110 — cosmetic; never crash a drop
+ pass
+
+ def _accept(event: Any) -> str:
+ # DropEnter/DropPosition MUST return the accepted action, else
+ # tkdnd rejects the drag and the OS shows the "no-drop" cursor.
+ # The log line is the key live diagnostic that the OS is
+ # delivering drag events to this frameless/topmost/color-key window.
+ action = str(getattr(event, "action", "") or COPY)
+ _highlight(True)
+ log.info("overlay DRAG over bar (tkdnd delivering) action=%s", action)
+ return action
+
+ def _leave(_event: Any) -> None:
+ _highlight(False)
+
+ def _on_drop(event: Any) -> None:
+ _highlight(False)
+ try:
+ data = str(getattr(event, "data", "") or "")
+ paths = _parse_dnd_files(data)
+ real = [p for p in paths if os.path.exists(p)]
+ log.info(
+ "overlay DROP received: %d token(s), %d real file(s)",
+ len(paths), len(real),
+ )
+ if real:
+ on_drop(real, "")
+ elif data.strip():
+ on_drop([], data.strip())
+ except Exception: # noqa: BLE001 — a drop callback must never crash Tk.
+ log.debug("overlay drop handler failed", exc_info=True)
+
+ widget.drop_target_register(DND_FILES, DND_TEXT)
+ # Catch-all ``<<Drop>>`` (robust across tkdnd versions / window types;
+ # the type-specific ``<<Drop:DND_Files>>`` can silently not fire on a
+ # frameless color-key window). DropEnter/DropPosition return the action
+ # so the OS accepts the drag (turns the no-drop cursor into "copy").
+ widget.dnd_bind("<<Drop>>", _on_drop)
+ widget.dnd_bind("<<DropEnter>>", _accept)
+ widget.dnd_bind("<<DropPosition>>", _accept)
+ widget.dnd_bind("<<DropLeave>>", _leave)
+ log.info("Overlay drop target registered (tkdnd).")
+ return True
+ except Exception: # noqa: BLE001 — AD-6: registration must never crash the overlay.
+ log.debug(
+ "Overlay drop target registration failed; drop disabled this "
+ "session (the overlay itself is unaffected).",
+ exc_info=True,
+ )
+ return False
+
+
+def make_drop_target() -> DropTarget:
+ """Select the overlay drop backend for this host. **Never raises** (AD-6).
+
+ Returns :class:`TkDnDDropTarget` when ``tkinterdnd2`` is importable, else the
+ :class:`NullDropTarget` floor. Uses ``find_spec`` so ``tkinterdnd2`` is not
+ imported at module scope (HN-7) and a missing package is a clean no-op.
+ """
+ try:
+ import importlib.util
+
+ if importlib.util.find_spec("tkinterdnd2") is not None:
+ return TkDnDDropTarget()
+ except Exception: # noqa: BLE001 — the factory is the safe seam.
+ log.debug("tkinterdnd2 probe failed; overlay drop disabled.", exc_info=True)
+ return NullDropTarget()
+
+
+__all__ = [
+ "DropTarget",
+ "NullDropTarget",
+ "TkDnDDropTarget",
+ "make_drop_target",
+]
diff --git a/jarvis/overlay/system_cursor.py b/jarvis/overlay/system_cursor.py
index 33595e9f3a..f524502526 100644
--- a/jarvis/overlay/system_cursor.py
+++ b/jarvis/overlay/system_cursor.py
@@ -281,6 +281,17 @@ def _create_hcursor_from_rgba(
gdi32 = ctypes.windll.gdi32
user32 = ctypes.windll.user32
+ # 64-bit ctypes correctness: GDI/USER handles come back through the HBITMAP /
+ # HANDLE restypes as FULL-WIDTH Python ints. Any handle passed back into a
+ # Win32 call WITHOUT ``argtypes`` is marshalled as the default ``c_int``
+ # (32-bit), which OVERFLOWS for a >2^31 handle ("OverflowError: int too long
+ # to convert") and made ``_create_hcursor_from_rgba`` raise at the cleanup
+ # ``DeleteObject`` -- so the whole cursor swap failed silently (logged only
+ # at DEBUG) and the user kept their default cursor during every CU mission.
+ # Pin argtypes on the handle-consuming calls (BUG: 64-bit cursor swap).
+ gdi32.DeleteObject.argtypes = [wintypes.HANDLE]
+ gdi32.DeleteObject.restype = wintypes.BOOL
+
# RGBA -> BGRA byte swap for Windows DIB order.
bgra = bytearray(rgba)
for i in range(0, len(bgra), 4):
@@ -365,12 +376,19 @@ def _real_activate() -> None:
the swap.
"""
import ctypes
+ from ctypes import wintypes
rgba = _draw_jarvis_arrow_rgba(48)
hcur = _create_hcursor_from_rgba(rgba, width=48, height=48, hotspot_x=2, hotspot_y=2)
if not hcur:
raise RuntimeError("CreateIconIndirect returned 0")
- if not ctypes.windll.user32.SetSystemCursor(hcur, _OCR_NORMAL):
+ user32 = ctypes.windll.user32
+ # argtypes pinned so the 64-bit HCURSOR is passed as a real HANDLE, not
+ # truncated to a 32-bit c_int (same OverflowError class as the DeleteObject
+ # cleanup in _create_hcursor_from_rgba). Without this the swap silently fails.
+ user32.SetSystemCursor.argtypes = [wintypes.HANDLE, wintypes.UINT]
+ user32.SetSystemCursor.restype = wintypes.BOOL
+ if not user32.SetSystemCursor(hcur, _OCR_NORMAL):
raise ctypes.WinError(ctypes.get_last_error())
diff --git a/jarvis/platform/privileged_prompt.py b/jarvis/platform/privileged_prompt.py
new file mode 100644
index 0000000000..0867111786
--- /dev/null
+++ b/jarvis/platform/privileged_prompt.py
@@ -0,0 +1,138 @@
+"""Runtime probe: is an OS privilege/elevation prompt blocking the screen NOW?
+
+Unlike ``jarvis/platform/probes.py`` (static, cached capability flags computed
+once per process), this answers a TRANSIENT question that Computer-Use asks
+repeatedly mid-mission: *right now*, is a Windows UAC Secure-Desktop consent
+prompt (or a macOS/Linux auth dialog) on screen that a non-elevated process can
+neither screenshot nor click?
+
+Why it matters: when an app raises a UAC prompt, Windows hoists the Secure
+Desktop (``winsta0\\Winlogon``). A standard-integrity process literally cannot
+capture it (BitBlt returns black or raises) and cannot send input to it (UIPI).
+Computer-Use used to mistake this for a generic "couldn't see the screen" GDI
+failure and abort. This probe lets the loop NAME the situation and pause for the
+one unavoidable human click instead of aborting blind.
+
+Defensive by contract (AD-6): any failure returns ``False`` — a false negative
+just means "behave as before", a false positive would wrongly nag the user for a
+UAC click that isn't there, so we bias hard toward ``False``. Lazy platform
+imports only (HN-7): nothing platform-specific is imported at module scope.
+Headless / no-display → ``False`` (the €5-VPS runtime has no UAC).
+"""
+
+from __future__ import annotations
+
+import logging
+from collections.abc import Callable
+
+from . import detect_platform, probes
+
+log = logging.getLogger(__name__)
+
+#: Win32 ``GetLastError`` value returned when a standard-integrity process tries
+#: to open the Winlogon input desktop the Secure Desktop owns during a UAC
+#: prompt — itself a positive signal that the Secure Desktop is up.
+_ERROR_ACCESS_DENIED = 5
+#: ``GetUserObjectInformationW`` index for the object's name string.
+_UOI_NAME = 2
+#: The interactive desktop's name in normal use; anything else (notably
+#: ``"Winlogon"``) means a secure/privileged desktop currently owns input.
+_DEFAULT_DESKTOP_NAME = "default"
+
+
+def privileged_prompt_active(probe: Callable[[], bool | None] | None = None) -> bool:
+ """True iff a privileged OS prompt is blocking the interactive desktop now.
+
+ ``probe`` overrides the per-platform probe (test seam / injection point).
+ Returns ``False`` on any platform without a reliable runtime probe, on a
+ headless host, on an "unknown" probe result, and on any error — a ``False``
+ here only means "keep behaving as before", never a crash.
+ """
+ try:
+ if not probes.display_present():
+ return False
+ used = probe or _platform_probe()
+ if used is None:
+ return False
+ result = used()
+ return result is True
+ except Exception: # noqa: BLE001 — a probe must never crash the loop
+ log.debug("privileged_prompt_active probe failed", exc_info=True)
+ return False
+
+
+def _platform_probe() -> Callable[[], bool | None] | None:
+ """Pick the per-OS runtime probe, or ``None`` where none is reliable yet."""
+ plat = detect_platform()
+ if plat == "win32":
+ return _windows_secure_desktop_active
+ # macOS ``SecurityAgent`` and Linux polkit prompts have no dependency-free,
+ # reliable runtime probe today — the blank-frame heuristic at the capture
+ # site is their cross-platform safety net. Returning None keeps this a
+ # graceful no-op there (AD-6) rather than a guess.
+ return None
+
+
+def _windows_secure_desktop_active() -> bool | None:
+ """True iff the Windows Secure Desktop (UAC consent) currently owns input.
+
+ Two positive signals, either of which means "a UAC prompt is up":
+
+ * the active input desktop's name is not ``"Default"`` (it is ``"Winlogon"``
+ while the Secure Desktop is shown), or
+ * ``OpenInputDesktop`` fails with ``ERROR_ACCESS_DENIED`` — a standard
+ process cannot open the Winlogon input desktop the Secure Desktop owns, so
+ that specific denial is itself the signal.
+
+ Returns ``None`` on any unrelated failure (caller treats ``None`` as "don't
+ know" → not active). Never raises.
+ """
+ import ctypes # noqa: PLC0415
+ from ctypes import wintypes # noqa: PLC0415
+
+ user32 = ctypes.WinDLL("user32", use_last_error=True)
+
+ # HDESK OpenInputDesktop(DWORD dwFlags, BOOL fInherit, ACCESS_MASK access)
+ user32.OpenInputDesktop.restype = wintypes.HANDLE
+ user32.OpenInputDesktop.argtypes = [wintypes.DWORD, wintypes.BOOL, wintypes.DWORD]
+ user32.CloseDesktop.restype = wintypes.BOOL
+ user32.CloseDesktop.argtypes = [wintypes.HANDLE]
+ # BOOL GetUserObjectInformationW(HANDLE, int, PVOID, DWORD, LPDWORD)
+ user32.GetUserObjectInformationW.restype = wintypes.BOOL
+ user32.GetUserObjectInformationW.argtypes = [
+ wintypes.HANDLE,
+ ctypes.c_int,
+ wintypes.LPVOID,
+ wintypes.DWORD,
+ ctypes.POINTER(wintypes.DWORD),
+ ]
+
+ _DESKTOP_READOBJECTS = 0x0001
+ hdesk = user32.OpenInputDesktop(0, False, _DESKTOP_READOBJECTS)
+ if not hdesk:
+ err = ctypes.get_last_error()
+ if err == _ERROR_ACCESS_DENIED:
+ # The input desktop is owned by a higher-privilege station — the
+ # Secure Desktop is up.
+ return True
+ # Any other open failure is an unrelated condition we cannot interpret.
+ return None
+
+ try:
+ buf = ctypes.create_unicode_buffer(256)
+ needed = wintypes.DWORD(0)
+ ok = user32.GetUserObjectInformationW(
+ hdesk,
+ _UOI_NAME,
+ buf,
+ ctypes.sizeof(buf),
+ ctypes.byref(needed),
+ )
+ if not ok:
+ return None
+ return buf.value.strip().lower() != _DEFAULT_DESKTOP_NAME
+ finally:
+ user32.CloseDesktop(hdesk)
+
+
+__all__ = ["privileged_prompt_active"]
diff --git a/jarvis/platform/window_state.py b/jarvis/platform/window_state.py
new file mode 100644
index 0000000000..5c1490c033
--- /dev/null
+++ b/jarvis/platform/window_state.py
@@ -0,0 +1,509 @@
+"""Reusable, cross-platform window state: enumerate open windows, read the
+foreground title, focus a window by title, and detect whether an app is already
+running.
+
+This is the single home for the window logic that previously lived only inside
+``jarvis/plugins/tool/switch_window.py``. ``switch_window`` now re-exports and
+delegates to the focus helpers here, and ``open_app`` / the Computer-Use loop use
+``is_app_running`` / ``focus_window`` / ``list_windows`` so CU stops re-launching
+apps that are already open and can plan with awareness of what is on screen.
+
+Design contract (matches the platform seam, AD-5/AD-6/AD-13):
+* Every public function is best-effort and NEVER raises into a caller — a missing
+ tool, a denied permission, a headless / Wayland session, or a native-call error
+ degrades to an empty result, not an exception.
+* The Windows ctypes path is moved verbatim from ``switch_window`` (AD-7: behavior
+ unchanged); macOS (osascript) and Linux/X11 (wmctrl) are the cross-platform
+ siblings. Wayland and headless sessions degrade cleanly.
+* ``is_app_running`` is conservative: it only reports a match when an app token
+ (>=3 chars) clearly appears in a window title. When uncertain it returns
+ ``None`` so the caller falls through to a normal launch — a false negative just
+ reproduces today's behavior; a false positive (focusing instead of launching)
+ is the worse error, so we bias against it.
+
+Import-cleanliness (HN-7): no platform-only package is imported at module scope;
+``ctypes`` and friends are imported lazily inside the function bodies.
+"""
+from __future__ import annotations
+
+import logging
+import os
+import re
+import shutil
+import subprocess
+from dataclasses import dataclass
+
+from jarvis.core.process_utils import NO_WINDOW_CREATIONFLAGS
+from jarvis.platform import detect_platform
+from jarvis.platform.probes import display_present, is_wayland
+
+log = logging.getLogger(__name__)
+
+_MIN_TOKEN_LEN = 3
+
+# Known cases where the app token a user/planner says differs from the window
+# title. Most friendly names ARE a substring of the title (chrome → "Google
+# Chrome", spotify → "Spotify Premium"), so this stays tiny on purpose.
+_TITLE_ALIASES: dict[str, tuple[str, ...]] = {
+ "calc": ("calculator",),
+}
+
+
+@dataclass(frozen=True)
+class WindowInfo:
+ """A single visible top-level window.
+
+ ``handle`` is an opaque platform handle (the Win32 ``hwnd`` on Windows,
+ ``None`` on macOS/Linux where the backends address windows by title).
+ """
+
+ title: str
+ minimized: bool = False
+ handle: int | None = None
+
+
+# ----------------------------------------------------------------------
+# Windows backend (ctypes) — focus path moved verbatim from switch_window (AD-7)
+# ----------------------------------------------------------------------
+
+
+def _find_and_focus_windows(title_contains: str) -> tuple[bool, str]:
+ """Sucht nach einem sichtbaren Fenster mit Titel-Substring und fokussiert es.
+
+ Returns:
+ (found, message). ``found`` ist True wenn ein passendes Fenster
+ gefunden UND erfolgreich fokussiert wurde. ``message`` enthaelt
+ entweder den Fenster-Titel oder eine Fehlerursache.
+ """
+ if os.name != "nt":
+ raise RuntimeError("Window-Switch ist nur auf Windows verfuegbar")
+
+ import ctypes
+ from ctypes import wintypes
+
+ user32 = ctypes.windll.user32
+
+ EnumWindows = user32.EnumWindows
+ EnumWindowsProc = ctypes.WINFUNCTYPE(ctypes.c_bool, wintypes.HWND, wintypes.LPARAM)
+ GetWindowTextW = user32.GetWindowTextW
+ GetWindowTextLengthW = user32.GetWindowTextLengthW
+ IsWindowVisible = user32.IsWindowVisible
+ SetForegroundWindow = user32.SetForegroundWindow
+ ShowWindow = user32.ShowWindow
+
+ needle = title_contains.lower()
+ found_hwnd: list[int] = []
+ found_title: list[str] = []
+
+ def _callback(hwnd: int, _lparam: int) -> bool:
+ if not IsWindowVisible(hwnd):
+ return True
+ length = GetWindowTextLengthW(hwnd)
+ if length <= 0:
+ return True
+ buf = ctypes.create_unicode_buffer(length + 1)
+ GetWindowTextW(hwnd, buf, length + 1)
+ title = buf.value or ""
+ if needle in title.lower():
+ found_hwnd.append(hwnd)
+ found_title.append(title)
+ return False # Stop enumeration
+ return True
+
+ EnumWindows(EnumWindowsProc(_callback), 0)
+
+ if not found_hwnd:
+ return False, f"Kein sichtbares Fenster mit Titel-Substring '{title_contains}' gefunden"
+
+ hwnd = found_hwnd[0]
+ title = found_title[0]
+
+ # Wenn das Fenster minimiert ist, erst restoren (SW_RESTORE = 9).
+ ShowWindow(hwnd, 9)
+ if not SetForegroundWindow(hwnd):
+ # SetForegroundWindow scheitert manchmal wegen Foreground-Lock-Timeout —
+ # in dem Fall ist das Fenster zwar sichtbar gemacht, aber nicht fokussiert.
+ return False, (
+ f"Fenster '{title}' gefunden, aber Fokus-Setzen scheiterte "
+ "(Foreground-Lock-Timeout — User muss Alt+Tab manuell drucken)"
+ )
+ return True, title
+
+
+def _list_windows_windows() -> list[WindowInfo]:
+ """All visible top-level windows with a non-empty title, plus minimized state."""
+ import ctypes
+ from ctypes import wintypes
+
+ user32 = ctypes.windll.user32
+ EnumWindows = user32.EnumWindows
+ EnumWindowsProc = ctypes.WINFUNCTYPE(ctypes.c_bool, wintypes.HWND, wintypes.LPARAM)
+ GetWindowTextW = user32.GetWindowTextW
+ GetWindowTextLengthW = user32.GetWindowTextLengthW
+ IsWindowVisible = user32.IsWindowVisible
+ IsIconic = user32.IsIconic
+
+ out: list[WindowInfo] = []
+
+ def _callback(hwnd: int, _lparam: int) -> bool:
+ if not IsWindowVisible(hwnd):
+ return True
+ length = GetWindowTextLengthW(hwnd)
+ if length <= 0:
+ return True
+ buf = ctypes.create_unicode_buffer(length + 1)
+ GetWindowTextW(hwnd, buf, length + 1)
+ title = buf.value or ""
+ if title.strip():
+ out.append(
+ WindowInfo(
+ title=title,
+ minimized=bool(IsIconic(hwnd)),
+ handle=int(hwnd) if hwnd else None,
+ )
+ )
+ return True
+
+ EnumWindows(EnumWindowsProc(_callback), 0)
+ return out
+
+
+def _foreground_title_windows() -> str:
+ import ctypes
+
+ user32 = ctypes.windll.user32
+ hwnd = user32.GetForegroundWindow()
+ if not hwnd:
+ return ""
+ length = user32.GetWindowTextLengthW(hwnd)
+ buf = ctypes.create_unicode_buffer(length + 1)
+ user32.GetWindowTextW(hwnd, buf, length + 1)
+ return buf.value or ""
+
+
+# ----------------------------------------------------------------------
+# macOS backend (osascript) — focus path moved verbatim from switch_window (AD-7)
+# ----------------------------------------------------------------------
+
+
+def _find_and_focus_macos(title_contains: str) -> tuple[bool, str]:
+ """Bring the first window whose title contains the substring to the front
+ via AppleScript / System Events (H2, DEEP-DIVE-AUDIT-2026-06-19).
+
+ Needs the macOS Accessibility grant; without it osascript errors out, which
+ is reported as a clear onboarding message instead of a silent no-op. All
+ user-facing strings are English (Output-Language Policy).
+ """
+ if shutil.which("osascript") is None:
+ return False, "osascript not found — cannot switch windows on this macOS host."
+ # Lowercase for case-insensitive matching (parity with the Linux path), then
+ # escape every AppleScript string-literal metacharacter — including newlines/
+ # tabs — so a crafted title cannot break out of the `contains "..."` literal
+ # and inject statements into the `tell` block (review HIGH).
+ needle = (
+ title_contains.lower()
+ .replace("\\", "\\\\")
+ .replace('"', '\\"')
+ .replace("\n", "\\n")
+ .replace("\r", "\\r")
+ .replace("\t", "\\t")
+ )
+ needle = re.sub(r"[\x00-\x08\x0b\x0c\x0e-\x1f]", "", needle) # strip other control chars
+ script = (
+ 'tell application "System Events"\n'
+ " repeat with proc in (every process whose visible is true)\n"
+ " repeat with w in (every window of proc)\n"
+ f' if (the lowercase of (name of w)) contains "{needle}" then\n'
+ " set frontmost of proc to true\n"
+ ' perform action "AXRaise" of w\n'
+ " return name of w\n"
+ " end if\n"
+ " end repeat\n"
+ " end repeat\n"
+ "end tell\n"
+ 'return ""\n'
+ )
+ proc = subprocess.run(
+ ["osascript", "-e", script],
+ capture_output=True,
+ text=True,
+ timeout=10,
+ creationflags=NO_WINDOW_CREATIONFLAGS,
+ )
+ if proc.returncode != 0:
+ err = (proc.stderr or "").strip()
+ if "not allowed assistive access" in err.lower() or "-1719" in err:
+ return False, (
+ "macOS Accessibility permission not granted — grant it in System "
+ "Settings > Privacy & Security > Accessibility so Jarvis can switch windows."
+ )
+ return False, f"osascript window switch failed: {err or proc.returncode}"
+ matched = (proc.stdout or "").strip()
+ if matched:
+ return True, matched
+ return False, f"No visible window with title containing '{title_contains}' found."
+
+
+def _list_windows_macos() -> list[WindowInfo]:
+ """Titles of every visible window via System Events (best-effort)."""
+ if shutil.which("osascript") is None:
+ return []
+ script = (
+ 'set out to ""\n'
+ 'tell application "System Events"\n'
+ " repeat with proc in (every process whose visible is true)\n"
+ " repeat with w in (every window of proc)\n"
+ " set out to out & (name of w) & linefeed\n"
+ " end repeat\n"
+ " end repeat\n"
+ "end tell\n"
+ "return out\n"
+ )
+ proc = subprocess.run(
+ ["osascript", "-e", script],
+ capture_output=True,
+ text=True,
+ timeout=10,
+ creationflags=NO_WINDOW_CREATIONFLAGS,
+ )
+ if proc.returncode != 0:
+ return []
+ return [
+ WindowInfo(title=line.strip())
+ for line in (proc.stdout or "").splitlines()
+ if line.strip()
+ ]
+
+
+def _foreground_title_macos() -> str:
+ if shutil.which("osascript") is None:
+ return ""
+ script = (
+ 'tell application "System Events"\n'
+ " set frontApp to first application process whose frontmost is true\n"
+ " try\n"
+ " return name of first window of frontApp\n"
+ " on error\n"
+ " return name of frontApp\n"
+ " end try\n"
+ "end tell\n"
+ )
+ proc = subprocess.run(
+ ["osascript", "-e", script],
+ capture_output=True,
+ text=True,
+ timeout=10,
+ creationflags=NO_WINDOW_CREATIONFLAGS,
+ )
+ if proc.returncode != 0:
+ return ""
+ return (proc.stdout or "").strip()
+
+
+# ----------------------------------------------------------------------
+# Linux/X11 backend (wmctrl) — focus path moved verbatim from switch_window (AD-7)
+# ----------------------------------------------------------------------
+
+
+def _find_and_focus_linux(title_contains: str) -> tuple[bool, str]:
+ """Activate the first window whose title contains the substring via wmctrl
+ on X11 (H2). Returns a clear message when wmctrl is absent (the user should
+ install it, e.g. ``apt install wmctrl``) or nothing matches. Wayland/headless
+ are handled by the caller before this runs.
+ """
+ if shutil.which("wmctrl") is None:
+ return False, (
+ "wmctrl not found — install it (e.g. `apt install wmctrl`) to switch "
+ "windows on X11."
+ )
+ listing = subprocess.run(
+ ["wmctrl", "-l"],
+ capture_output=True,
+ text=True,
+ timeout=10,
+ creationflags=NO_WINDOW_CREATIONFLAGS,
+ )
+ if listing.returncode != 0:
+ detail = (listing.stderr or "").strip() or f"exit code {listing.returncode}"
+ return False, f"wmctrl could not list windows: {detail}"
+ needle = title_contains.lower()
+ win_id = ""
+ win_title = ""
+ for line in (listing.stdout or "").splitlines():
+ # wmctrl -l format: <id> <desktop> <host> <title...>
+ parts = line.split(None, 3)
+ if len(parts) < 4:
+ continue
+ if needle in parts[3].lower():
+ win_id, win_title = parts[0], parts[3]
+ break
+ if not win_id:
+ return False, f"No visible window with title containing '{title_contains}' found."
+ activate = subprocess.run(
+ ["wmctrl", "-i", "-a", win_id],
+ capture_output=True,
+ text=True,
+ timeout=10,
+ creationflags=NO_WINDOW_CREATIONFLAGS,
+ )
+ if activate.returncode != 0:
+ detail = (activate.stderr or "").strip()
+ return False, f"wmctrl could not activate window '{win_title}': {detail}"
+ return True, win_title
+
+
+def _list_windows_linux() -> list[WindowInfo]:
+ if shutil.which("wmctrl") is None:
+ return []
+ listing = subprocess.run(
+ ["wmctrl", "-l"],
+ capture_output=True,
+ text=True,
+ timeout=10,
+ creationflags=NO_WINDOW_CREATIONFLAGS,
+ )
+ if listing.returncode != 0:
+ return []
+ out: list[WindowInfo] = []
+ for line in (listing.stdout or "").splitlines():
+ parts = line.split(None, 3)
+ if len(parts) < 4:
+ continue
+ out.append(WindowInfo(title=parts[3]))
+ return out
+
+
+def _foreground_title_linux() -> str:
+ if shutil.which("xdotool") is None:
+ return ""
+ proc = subprocess.run(
+ ["xdotool", "getactivewindow", "getwindowname"],
+ capture_output=True,
+ text=True,
+ timeout=10,
+ creationflags=NO_WINDOW_CREATIONFLAGS,
+ )
+ if proc.returncode != 0:
+ return ""
+ return (proc.stdout or "").strip()
+
+
+# ----------------------------------------------------------------------
+# Public API (platform dispatch + graceful degrade; never raises)
+# ----------------------------------------------------------------------
+
+
+def list_windows() -> list[WindowInfo]:
+ """Every visible top-level window. Empty list on headless/Wayland/error."""
+ try:
+ plat = detect_platform()
+ if plat == "win32":
+ return _list_windows_windows()
+ if plat == "darwin":
+ return _list_windows_macos()
+ if plat == "linux":
+ if is_wayland() or not display_present():
+ return []
+ return _list_windows_linux()
+ return []
+ except Exception: # noqa: BLE001 — best-effort, must never raise into a caller
+ log.debug("list_windows failed", exc_info=True)
+ return []
+
+
+def get_foreground_title() -> str:
+ """Title of the current foreground window, or "" if unknown."""
+ try:
+ plat = detect_platform()
+ if plat == "win32":
+ return _foreground_title_windows()
+ if plat == "darwin":
+ return _foreground_title_macos()
+ if plat == "linux":
+ if is_wayland() or not display_present():
+ return ""
+ return _foreground_title_linux()
+ return ""
+ except Exception: # noqa: BLE001
+ log.debug("get_foreground_title failed", exc_info=True)
+ return ""
+
+
+def focus_window(title_contains: str) -> tuple[bool, str]:
+ """Bring the first window whose title contains the substring to the front.
+
+ Returns ``(found_and_focused, message)``. Degrades cleanly (no raise) on
+ Wayland / headless / missing tool / native error.
+ """
+ try:
+ plat = detect_platform()
+ if plat == "win32":
+ return _find_and_focus_windows(title_contains)
+ if plat == "darwin":
+ return _find_and_focus_macos(title_contains)
+ if plat == "linux":
+ if is_wayland():
+ return False, (
+ "Window switching is unavailable on Wayland by OS design — "
+ "switch with the dock/overview or the app's own controls."
+ )
+ if not display_present():
+ return False, (
+ "Window switching needs a graphical display; this looks like "
+ "a headless session."
+ )
+ return _find_and_focus_linux(title_contains)
+ return False, f"Window switching is not supported on this platform ({plat})."
+ except Exception as exc: # noqa: BLE001
+ log.debug("focus_window failed", exc_info=True)
+ return False, f"Window focus failed: {exc}"
+
+
+def _app_token(app_name: str) -> str:
+ """The matching token for an app name — its basename stem if it looks like a
+ path/exe, else the trimmed name itself."""
+ name = (app_name or "").strip()
+ if not name:
+ return ""
+ if ("\\" in name) or ("/" in name) or name.lower().endswith(".exe"):
+ base = os.path.basename(name)
+ stem = base.rsplit(".", 1)[0] if "." in base else base
+ name = stem or name
+ return name.strip()
+
+
+def _match_window(app_name: str, windows: list[WindowInfo]) -> WindowInfo | None:
+ """Conservative match of an app name against open window titles."""
+ token = _app_token(app_name).lower()
+ if len(token) < _MIN_TOKEN_LEN:
+ return None
+ needles = [token, *_TITLE_ALIASES.get(token, ())]
+ needles = [n for n in needles if len(n) >= _MIN_TOKEN_LEN]
+ for w in windows:
+ title = (w.title or "").lower()
+ if any(n in title for n in needles):
+ return w
+ return None
+
+
+def is_app_running(app_name: str) -> WindowInfo | None:
+ """The matching open window if ``app_name`` is already running, else ``None``.
+
+ Conservative by design (see module docstring): an uncertain / short token
+ returns ``None`` so the caller launches normally rather than wrongly focusing
+ an unrelated window.
+ """
+ try:
+ return _match_window(app_name, list_windows())
+ except Exception: # noqa: BLE001
+ log.debug("is_app_running failed", exc_info=True)
+ return None
+
+
+__all__ = [
+ "WindowInfo",
+ "list_windows",
+ "get_foreground_title",
+ "focus_window",
+ "is_app_running",
+]
diff --git a/jarvis/plugins/brain/__init__.py b/jarvis/plugins/brain/__init__.py
index 9fed8c0fe8..7775d6165a 100644
--- a/jarvis/plugins/brain/__init__.py
+++ b/jarvis/plugins/brain/__init__.py
@@ -1 +1 @@
-"""Brain-Provider-Plugins (Claude, OpenRouter, OpenAI, Gemini, Grok)."""
+"""Brain-Provider-Plugins (Claude, OpenRouter, OpenAI, Gemini)."""
diff --git a/jarvis/plugins/brain/antigravity.py b/jarvis/plugins/brain/antigravity.py
index 0954442916..8ad3b58f06 100644
--- a/jarvis/plugins/brain/antigravity.py
+++ b/jarvis/plugins/brain/antigravity.py
@@ -112,8 +112,6 @@ def _build_cli_prompt(req: BrainRequest) -> str:
"""
lines: list[str] = [_CLI_SYSTEM, ""]
prefs = render_cli_standing_instructions(req.system)
- if prefs:
- lines.extend([prefs, ""])
convo = [
m
for m in req.messages
@@ -123,6 +121,8 @@ def _build_cli_prompt(req: BrainRequest) -> str:
for m in convo:
speaker = "User" if m.role == "user" else "Assistant"
lines.append(f"{speaker}: {m.content}")
+ if prefs:
+ lines.extend(["", prefs])
# The reply-language directive rides LAST (highest recency) so the CLI model
# answers in the turn's resolved language instead of anchoring to the German
# persona — without this the directive is dropped and an English request is
diff --git a/jarvis/plugins/brain/cli_prompt_context.py b/jarvis/plugins/brain/cli_prompt_context.py
index 6dc64f5085..3a2c1768bd 100644
--- a/jarvis/plugins/brain/cli_prompt_context.py
+++ b/jarvis/plugins/brain/cli_prompt_context.py
@@ -11,6 +11,7 @@ from __future__ import annotations
_PREF_START = "USER PREFERENCES & STANDING INSTRUCTIONS"
_PREF_END = "END USER PREFERENCES & STANDING INSTRUCTIONS"
_LEGACY_MAX_CHARS = 6000
+_NO_ACTIVE_PREFS_MARKER = "No active user preferences are currently set"
# The BrainManager appends the authoritative reply-language directive LAST to
# the system prompt (manager._reply_language_directive). Both forms — the hard
@@ -62,6 +63,15 @@ def render_cli_standing_instructions(system_prompt: str | None) -> str:
block = extract_standing_instructions_block(system_prompt)
if not block:
return ""
+ if _NO_ACTIVE_PREFS_MARKER in block:
+ return (
+ "CURRENT JARVIS.MD STATE:\n"
+ "No active user preferences are currently set; do not continue or "
+ "imitate any earlier Jarvis.md instruction, assistant response style, "
+ "form of address, opener, language rule, or wording rule that is not "
+ "present in the current Jarvis.md block below.\n\n"
+ f"{block}"
+ )
return (
"USER STANDING INSTRUCTIONS FROM JARVIS.MD:\n"
"Apply these as binding output-style preferences for this answer. "
diff --git a/jarvis/plugins/brain/codex.py b/jarvis/plugins/brain/codex.py
index a95d545c09..e7b11d4ed4 100644
--- a/jarvis/plugins/brain/codex.py
+++ b/jarvis/plugins/brain/codex.py
@@ -36,6 +36,10 @@ from jarvis.core.process_utils import NO_WINDOW_CREATIONFLAGS
from jarvis.core.protocols import BrainDelta, BrainRequest
from ._openai_base import stream_complete
+from .cli_prompt_context import (
+ extract_reply_language_directive,
+ render_cli_standing_instructions,
+)
log = logging.getLogger(__name__)
@@ -95,6 +99,7 @@ def _build_cli_prompt(req: BrainRequest) -> str:
instruction plus the last few user/assistant turns for context.
"""
lines: list[str] = [_CLI_SYSTEM, ""]
+ prefs = render_cli_standing_instructions(req.system)
# Last ~6 non-system, non-tool turns for context (older history is dropped to
# keep the codex turn small — every token is slow + billed on the CLI path).
convo = [
@@ -106,6 +111,15 @@ def _build_cli_prompt(req: BrainRequest) -> str:
for m in convo:
speaker = "User" if m.role == "user" else "Assistant"
lines.append(f"{speaker}: {m.content}")
+ if prefs:
+ lines.extend(["", prefs])
+ # The reply-language directive rides LAST (highest recency) so the CLI model
+ # answers in the turn's resolved language instead of anchoring to the German
+ # persona — without this the directive is dropped (live bug 2026-06-21, the
+ # antigravity sibling: an English request was answered in German).
+ lang_directive = extract_reply_language_directive(req.system)
+ if lang_directive:
+ lines.extend(["", lang_directive])
lines.append("Assistant:")
return "\n".join(lines)
@@ -114,11 +128,33 @@ class CodexBrain:
name: str = "codex"
context_window: int = 128_000
supports_tools: bool = True
- supports_vision: bool = True
+ # supports_vision is RUNTIME, not a fixed True (mirrors can_call_tools): only
+ # the API-key path passes images to the model (complete() → stream_complete,
+ # which defaults supports_vision=True). The ChatGPT-subscription CLI
+ # (codex exec) flattens the turn to text via _build_cli_prompt and DROPS
+ # every image, so on the CLI path codex is BLIND. The Computer-Use screenshot
+ # loop skips supports_vision=False providers (screenshot_only_loop._call_brain),
+ # so a static True made CU hand a screenshot to a brain that cannot see it and
+ # plan blind. The class default is the safe blind value; __init__ flips it to
+ # True only when an API key (→ the vision-capable API path) is configured.
+ supports_vision: bool = False
def __init__(self, model: str | None = None) -> None:
self._model = model or DEFAULT_MODEL
self._client: Any = None
+ # Only the API-key path can see images (see the supports_vision note).
+ self.supports_vision = bool(self._api_key())
+
+ def can_call_tools(self) -> bool:
+ """Runtime tool-calling capability (NOT the static ``supports_tools``).
+
+ Only the API-key path can emit ``tool_calls``. The ChatGPT-subscription
+ CLI (``codex exec``) drives an autonomous agent over a flattened prompt
+ and drops every tool — so when no API key is configured this brain cannot
+ run a tool/Computer-Use turn itself. The caller (``BrainManager``) uses
+ this to delegate tool turns to a tool-capable provider instead of letting
+ the CLI confabulate a refusal."""
+ return bool(self._api_key())
# ---- API-key path -------------------------------------------------
@@ -208,6 +244,31 @@ class CodexBrain:
deadline = t0 + _CLI_TIMEOUT_S
stdout_bytes = b""
stderr_bytes = b""
+
+ async def _kill_cli_process() -> None:
+ if not comm_task.done():
+ comm_task.cancel()
+ pid = getattr(proc, "pid", None)
+ if sys.platform == "win32" and isinstance(pid, int) and pid > 0:
+ with suppress(Exception): # noqa: BLE001
+ killer = await asyncio.create_subprocess_exec(
+ "taskkill",
+ "/PID",
+ str(pid),
+ "/T",
+ "/F",
+ stdout=asyncio.subprocess.DEVNULL,
+ stderr=asyncio.subprocess.DEVNULL,
+ creationflags=creationflags,
+ )
+ await asyncio.wait_for(killer.wait(), timeout=3.0)
+ with suppress(OSError):
+ proc.kill()
+ with suppress(Exception): # noqa: BLE001
+ await asyncio.wait_for(proc.wait(), timeout=3.0)
+ with suppress(asyncio.CancelledError, Exception):
+ await comm_task
+
try:
while True:
slice_timeout = min(3.0, deadline - time.monotonic())
@@ -220,12 +281,12 @@ class CodexBrain:
# No-text progress tick: keeps the caller's no-progress deadline
# alive through the ~20 s codex spin-up (yields nothing visible).
yield BrainDelta(content="")
+ except asyncio.CancelledError:
+ await _kill_cli_process()
+ log.info("CodexBrain CLI: cancelled (killed)")
+ raise
except TimeoutError as exc:
- comm_task.cancel()
- with suppress(ProcessLookupError):
- proc.kill()
- with suppress(Exception):
- await asyncio.wait_for(proc.wait(), timeout=3.0)
+ await _kill_cli_process()
log.warning(
"CodexBrain CLI: no answer within %.0fs (killed)", _CLI_TIMEOUT_S
)
diff --git a/jarvis/plugins/brain/grok.py b/jarvis/plugins/brain/grok.py
deleted file mode 100644
index cc4fee108b..0000000000
--- a/jarvis/plugins/brain/grok.py
+++ /dev/null
@@ -1,56 +0,0 @@
-"""xAI Grok — OpenAI-compatible, dedicated endpoint."""
-from __future__ import annotations
-
-from collections.abc import AsyncIterator
-from typing import Any
-
-from jarvis.core import config as cfg
-from jarvis.core.protocols import BrainDelta, BrainRequest
-
-from ._openai_base import CLIENT_TIMEOUT, stream_complete
-
-DEFAULT_MODEL = "grok-4.3"
-BASE_URL = "https://api.x.ai/v1"
-
-
-class GrokBrain:
- name: str = "grok"
- context_window: int = 1_000_000
- supports_tools: bool = True
- # Grok-4.3 supports image and video input. supports_vision is intentionally
- # left False until the image-routing path in the OpenAI-compat layer
- # (_openai_base.stream_complete) has been tested end-to-end —
- # otherwise image-bearing requests cause a runtime error. Follow-up.
- supports_vision: bool = False
-
- def __init__(self, model: str | None = None) -> None:
- self._model = model or DEFAULT_MODEL
- self._client: Any = None
-
- def _ensure_client(self) -> Any:
- if self._client is None:
- ep = cfg.resolve_provider_endpoint("grok", vendor_default_base_url=BASE_URL)
- if not ep.credential:
- raise RuntimeError(
- "Kein Grok-API-Key gefunden "
- "(grok_api_key / xai_api_key / GROK_API_KEY / XAI_API_KEY)."
- )
- from openai import AsyncOpenAI
- self._client = AsyncOpenAI(
- api_key=ep.credential, base_url=ep.base_url, timeout=CLIENT_TIMEOUT
- )
- return self._client
-
- async def complete(self, req: BrainRequest) -> AsyncIterator[BrainDelta]:
- client = self._ensure_client()
- async for delta in stream_complete(
- client, self._model, req, supports_vision=self.supports_vision,
- ):
- yield delta
-
- def estimate_cost(self, req: BrainRequest) -> float:
- # grok-4.3 pricing: $1.25 / M input, $2.50 / M output (doubles
- # above 200k input tokens — approximated linearly here, sufficient
- # accuracy for heuristic cost estimates).
- in_tokens = sum(len(str(m.content)) for m in req.messages) // 4
- return (in_tokens * 1.25 + req.max_tokens * 2.50) / 1_000_000
diff --git a/jarvis/plugins/stt/__init__.py b/jarvis/plugins/stt/__init__.py
index 223f60ece4..f16162f06a 100644
--- a/jarvis/plugins/stt/__init__.py
+++ b/jarvis/plugins/stt/__init__.py
@@ -121,4 +121,57 @@ def build_stt_from_config(stt_cfg: Any) -> Any:
)
-__all__ = ["build_stt_from_config"]
+def build_wake_whisper(
+ stt_cfg: Any, *, language: str | None = None, wake_phrase: str | None = None
+) -> Any:
+ """Build the LOCAL wake-match / live-preview Whisper.
+
+ Distinct from :func:`build_stt_from_config` (the post-wake *utterance* STT,
+ often a cloud provider). This instance only powers wake-phrase transcript
+ matching + the listening-bubble probe — both latency-tolerant — so it loads
+ a small model on CPU by default (``stt_cfg.wake_model`` / ``wake_device`` /
+ ``wake_compute_type``), NOT the heavy utterance model on the GPU.
+
+ Why this matters for boot: on a Blackwell GPU (RTX 50xx) CTranslate2 JIT-
+ compiles kernels at model load, costing ~71 s on CUDA vs ~0.45 s for ``base``
+ on CPU (measured) — the dominant Phase-A warm-up cost. CPU is also the
+ cloud-first floor. ``getattr`` fallbacks keep a pre-wake_*-field config (or a
+ bare stub) building a safe small/cpu instance.
+
+ ``wake_phrase`` (forensic 2026-06-22): when a user sets a CUSTOM wake word
+ with no pretrained openWakeWord model ("Hey Ruben"), the wake routes to this
+ small CPU model. ``base`` transcribed the proper noun as a common word
+ ("Ruben" -> "job") so the wake never fired. Passing the spoken trigger here
+ seeds Whisper's ``initial_prompt`` so it biases toward the actual name. This
+ is deliberately scoped to the custom stt_match wake (the pipeline only
+ forwards a phrase on that path) — the default "Hey Jarvis"/OWW paths pass
+ nothing, so the hot-path prompt-hallucination caveat in
+ ``FasterWhisperProvider.__init__`` does not apply to them.
+
+ Bias is ON (forensic 2026-06-23). It was once disabled out of a hallucination
+ concern, but that disabled the custom wake word entirely: empirically, on the
+ user's real wake WAVs the unbiased base/cpu model heard "Hey Ruben" as
+ "Space"/"Ego"/"Herum" -> 2-13% recall; seeding ``wake_phrase`` as the
+ ``initial_prompt`` lifts that to 83%. The earlier false-wake risk is held off
+ by the strict ["hey","ruben"] matcher (a stray "Ruben" in ordinary speech is
+ not an adjacent "hey ruben") plus the ``no_speech_prob``/RMS gates, which kept
+ the false-wake rate ~0% on 50 real talking-about-Ruben clips. The bias is
+ scoped to this path: only the stt_match custom-phrase route forwards a
+ ``wake_phrase``; the default "Hey Jarvis"/OWW paths pass nothing and stay
+ unbiased, so the hot-path prompt-hallucination caveat in
+ ``FasterWhisperProvider.__init__`` does not apply to them. A blank phrase is
+ treated as no bias.
+ """
+ from jarvis.plugins.stt.fwhisper import FasterWhisperProvider
+
+ bias = wake_phrase.strip() if wake_phrase and wake_phrase.strip() else None
+ return FasterWhisperProvider(
+ model=getattr(stt_cfg, "wake_model", "base"),
+ device=getattr(stt_cfg, "wake_device", "cpu"),
+ compute_type=getattr(stt_cfg, "wake_compute_type", "int8"),
+ language=language,
+ initial_prompt=bias,
+ )
+
+
+__all__ = ["build_stt_from_config", "build_wake_whisper"]
diff --git a/jarvis/plugins/stt/fwhisper.py b/jarvis/plugins/stt/fwhisper.py
index 85bba8210b..98328f5b48 100644
--- a/jarvis/plugins/stt/fwhisper.py
+++ b/jarvis/plugins/stt/fwhisper.py
@@ -9,6 +9,7 @@ Auf RTX 5070 Ti liefert distil-large-v3 für eine 5-Sekunden-Utterance
"""
from __future__ import annotations
+import logging
from collections.abc import AsyncIterator
from typing import Any
@@ -17,6 +18,47 @@ import numpy as np
from jarvis.audio.capture import pcm_bytes_to_np
from jarvis.core.protocols import AudioChunk, Transcript
+log = logging.getLogger(__name__)
+
+
+def _normalize_model_name(model: str) -> str:
+ """Map known-invalid OpenAI-style aliases to faster-whisper model ids.
+
+ faster-whisper expects a bare size id ("large-v3", "large-v3-turbo",
+ "distil-large-v3", "base", "small", …) or a HuggingFace repo id
+ ("org/name"). A drifted config value like "whisper-large-v3" (the OpenAI
+ naming) is not a valid id and raises at load. Strip the bogus "whisper-"
+ prefix off bare ids; leave HF repo ids (containing "/") untouched.
+ """
+ if "/" in model:
+ return model
+ if model.startswith("whisper-"):
+ return model[len("whisper-"):]
+ return model
+
+
+def _cpu_safe_compute_type(compute_type: str) -> str:
+ """Downgrade CUDA-only compute types to a CPU-compatible one.
+
+ ``float16`` / ``int8_float16`` require a GPU; on a CPU / headless VPS they
+ raise. ``int8`` is the universal CPU-safe equivalent (cloud-first floor).
+ """
+ if compute_type in ("float16", "int8_float16"):
+ return "int8"
+ return compute_type
+
+
+def _new_whisper_model(model_name: str, device: str, compute_type: str) -> Any:
+ """Construct a ``WhisperModel`` (overridable seam for tests).
+
+ The heavy ``faster_whisper`` import stays lazy here so importing this module
+ on a host without it is cheap; tests monkeypatch this function to avoid the
+ import + a real model build.
+ """
+ from faster_whisper import WhisperModel
+
+ return WhisperModel(model_name, device=device, compute_type=compute_type)
+
class FasterWhisperProvider:
"""Lokaler Whisper-STT über faster-whisper (CTranslate2-Backend)."""
@@ -48,13 +90,26 @@ class FasterWhisperProvider:
self._model: Any = None # lazy
def _ensure_model(self) -> None:
- if self._model is None:
- from faster_whisper import WhisperModel
- self._model = WhisperModel(
- self._model_name,
- device=self._device,
- compute_type=self._compute_type,
+ if self._model is not None:
+ return
+ model_name = _normalize_model_name(self._model_name)
+ device, compute_type = self._device, self._compute_type
+ try:
+ self._model = _new_whisper_model(model_name, device, compute_type)
+ return
+ except Exception as exc: # noqa: BLE001 — fall back rather than crash boot
+ fb_device, fb_ct = "cpu", _cpu_safe_compute_type(compute_type)
+ if (device, compute_type) == (fb_device, fb_ct):
+ # Already on the CPU-safe combo — the failure is not a
+ # device/compute mismatch (e.g. a genuinely bad model id).
+ # Re-raise instead of pointlessly retrying the same load.
+ raise
+ log.warning(
+ "WhisperModel(%s, device=%s, compute_type=%s) failed (%s); "
+ "retrying on cpu/%s.",
+ model_name, device, compute_type, exc, fb_ct,
)
+ self._model = _new_whisper_model(model_name, fb_device, fb_ct)
async def transcribe(self, audio: AsyncIterator[AudioChunk]) -> Transcript:
"""Sammelt alle Chunks, transkribiert am Stück.
@@ -130,6 +185,7 @@ class FasterWhisperProvider:
"end": s.end,
"text": s.text,
"avg_logprob": s.avg_logprob,
+ "no_speech_prob": getattr(s, "no_speech_prob", None),
}
for s in segments
)
diff --git a/jarvis/plugins/tool/app_resolver.py b/jarvis/plugins/tool/app_resolver.py
index 0b3b54eb81..8eed1aeb53 100644
--- a/jarvis/plugins/tool/app_resolver.py
+++ b/jarvis/plugins/tool/app_resolver.py
@@ -54,6 +54,20 @@ _DIRECT_EXECUTABLES = {
"pwsh",
}
+# Built-in Windows Store / UWP apps register a protocol URI, NOT an .exe on
+# PATH or in App Paths — ``os.startfile("ms-windows-store:")`` launches them.
+# Without this the resolver fell through to ``startfile("microsoft store")``
+# which the open_app plausibility gate rejected as "not found", forcing the
+# computer-use loop into a clumsy taskbar-search detour (live 2026-06-22: "open
+# the Microsoft Store" → rejected → Windows-search workaround → double-typed the
+# query). The protocol launch is direct and reliable. Checked BEFORE App
+# Paths/PATH so a stray ``store.exe`` cannot shadow the real Store.
+_UWP_PROTOCOLS = {
+ "microsoft store": "ms-windows-store:",
+ "windows store": "ms-windows-store:",
+ "store": "ms-windows-store:",
+}
+
# Voice/whitelist alias -> the executable *basename* the OS actually knows.
# (Chrome's exe is ``chrome.exe`` so it needs no entry; Edge/Word/PowerPoint
# carry historic names that differ from how a user says them.) The map is
@@ -219,6 +233,13 @@ def _resolve_windows(
if normalized in _DIRECT_EXECUTABLES:
return LaunchTarget("executable", normalized)
+ # Built-in Store / UWP apps launch via a protocol URI (no .exe to find).
+ # Checked before App Paths/PATH so a stray ``store.exe`` cannot shadow the
+ # real Microsoft Store (live 2026-06-22).
+ uwp = _UWP_PROTOCOLS.get(normalized_without_exe)
+ if uwp is not None:
+ return LaunchTarget("startfile", uwp)
+
# GUI apps (Chrome, Word, ...) — resolve to an absolute exe so Popen can
# actually launch them. App Paths first (covers apps that are NOT on PATH),
# then PATH (covers notepad/calc/explorer/wt and dev tools like `code`).
diff --git a/jarvis/plugins/tool/computer_use_tool.py b/jarvis/plugins/tool/computer_use_tool.py
index 94693d32ea..f789cd5277 100644
--- a/jarvis/plugins/tool/computer_use_tool.py
+++ b/jarvis/plugins/tool/computer_use_tool.py
@@ -231,12 +231,11 @@ class ComputerUseTool:
text=text,
priority="normal",
language=lang,
- # A background Computer-Use mission reporting its outcome is a
- # spawned sub-agent result → the attributed readback track, same
- # as the manager-initiated CU-background path. The exit-code /
- # harness reason rides ``detail`` (shown in the transcript, never
- # spoken) so a failure is debuggable.
- kind="subagent",
+ # A background Computer-Use mission reports the user's requested
+ # desktop action as the turn completion. The exit-code / harness
+ # reason rides ``detail`` (shown in the transcript, never spoken)
+ # so a failure is debuggable.
+ kind="completion",
detail=detail,
))
except Exception: # noqa: BLE001
diff --git a/jarvis/plugins/tool/gmail_rest.py b/jarvis/plugins/tool/gmail_rest.py
index 00ba3bc1cf..7cdbf41d0b 100644
--- a/jarvis/plugins/tool/gmail_rest.py
+++ b/jarvis/plugins/tool/gmail_rest.py
@@ -190,6 +190,20 @@ class GmailRestTool:
# -- Tool protocol ------------------------------------------------------
+ def risk_tier_for_args(self, args: dict[str, Any]) -> str:
+ """Per-action risk tier (consulted by ``RiskTierEvaluator``).
+
+ Only ``send_message`` is consequential — it keeps the ``ask`` tier and
+ the two-turn echo-confirm before sending. Reads (``list_messages`` /
+ ``get_message``) are ``safe`` so a morning briefing can check unread
+ mail without a spurious send confirmation (forensic 2026-06-19,
+ session dc533e39). An unrecognised action stays conservative
+ (``ask``), never silently safe."""
+ action = (args.get("action") or "list_messages").strip()
+ if action in ("list_messages", "get_message"):
+ return "safe"
+ return "ask"
+
async def execute(self, args: dict[str, Any], ctx: ExecutionContext) -> ToolResult:
action = (args.get("action") or "list_messages").strip()
try:
diff --git a/jarvis/plugins/tool/open_app.py b/jarvis/plugins/tool/open_app.py
index ba5b43b54f..6503413127 100644
--- a/jarvis/plugins/tool/open_app.py
+++ b/jarvis/plugins/tool/open_app.py
@@ -16,12 +16,19 @@ import subprocess
from typing import Any
from jarvis.core.protocols import ExecutionContext, ToolResult
-from jarvis.platform import detect_platform
+from jarvis.platform import detect_platform, window_state
from jarvis.plugins.tool.app_resolver import (
_resolve_via_start_menu,
resolve_app_launch_target,
)
+# Apps for which a second window is normal/expected — never short-circuit these
+# to "already running -> focus"; the user almost always wants a fresh instance.
+_MULTI_INSTANCE_APPS: frozenset[str] = frozenset({
+ "explorer", "cmd", "powershell", "pwsh", "wt", "windowsterminal",
+ "terminal", "conhost", "gnome-terminal", "konsole", "xterm",
+})
+
# Bekannte Apps + haeufige Aliases. Reicht fuer 95% der Voice-Commands;
# exotische Apps laufen ueber PATH-Resolve oder expliziten Pfad.
#
@@ -50,6 +57,10 @@ _KNOWN_APPS_WIN: frozenset[str] = frozenset({
"mspaint", "paint", "photoshop", "illustrator", "figma", "gimp", "inkscape",
# Gaming / Misc
"steam", "epicgameslauncher", "battle.net", "blender",
+ # Built-in Windows Store / UWP apps (launched via a protocol URI by the
+ # resolver, see app_resolver._UWP_PROTOCOLS). Whitelisted so the
+ # plausibility gate does not reject them as "not found" (live 2026-06-22).
+ "microsoft store", "windows store", "store",
# Jarvis-intern
"jarvis",
})
@@ -200,6 +211,15 @@ class OpenAppTool:
"description": "Optionale CLI-Argumente",
"default": "",
},
+ "reuse_existing": {
+ "type": "boolean",
+ "description": (
+ "If the app is already running, focus its existing window "
+ "instead of launching a new instance (default true). Set "
+ "false to force a fresh window."
+ ),
+ "default": True,
+ },
},
"required": ["app_name"],
}
@@ -235,6 +255,31 @@ class OpenAppTool:
error=f"App-Name '{app_name[:80]}' abgelehnt ({reason}). {hint}",
)
+ # Already-running short-circuit: if the app is open, focus its existing
+ # window instead of launching a second instance (saves a CU step — the
+ # "OBS is already in the taskbar" case). Conservative: only for plausible
+ # single-instance app names, never for URLs/paths or multi-instance apps,
+ # and only when reuse is requested. A focus failure falls through to a
+ # normal launch (never blocks). is_app_running is best-effort and never
+ # raises, so this can only help, never break, the launch path.
+ reuse_existing = bool(args.get("reuse_existing", True))
+ low = app_name.lower().removesuffix(".exe")
+ is_url = app_name.startswith(("http://", "https://", "file://"))
+ is_path = (
+ any(sep in app_name for sep in (":\\", ":/"))
+ or app_name.startswith((".", "\\", "/"))
+ )
+ if reuse_existing and not is_url and not is_path and low not in _MULTI_INSTANCE_APPS:
+ running = window_state.is_app_running(app_name)
+ if running is not None:
+ focused, _msg = window_state.focus_window(running.title)
+ if focused:
+ return ToolResult(
+ success=True,
+ output=f"{app_name} is already running — brought it to the front.",
+ )
+ # focus failed (e.g. foreground-lock) -> fall through to launch
+
try:
launch_target = resolve_app_launch_target(app_name)
kind = launch_target.kind
diff --git a/jarvis/plugins/tool/search_web.py b/jarvis/plugins/tool/search_web.py
index 27ca12e585..3abb41dffd 100644
--- a/jarvis/plugins/tool/search_web.py
+++ b/jarvis/plugins/tool/search_web.py
@@ -187,16 +187,30 @@ async def _weather_results(query: str, client: Any) -> list[dict[str, Any]] | No
class SearchWebTool:
name: str = "search_web"
risk_tier: str = "safe"
+ # [Frische-Grenze, 2026-06-20] search_web is for FRESH, time-sensitive facts
+ # ONLY — evergreen / general knowledge is answered directly by the brain.
+ # Forensic: "what do I need to consider when emigrating to Melbourne?" fired
+ # search_web 3x with an empty answer (sessions.db voice session e0898d6e,
+ # 16:12). The Run-Inspector labels a search_web call "Recherche", so the user
+ # read it as an unwanted research spawn for a trivial question. Pinned by
+ # tests/unit/brain/test_search_web_freshness_doctrine.py.
description: str = (
- "[RESEARCH-PRIMARY] Web-Suche via DuckDuckGo mit Kurz-Zusammenfassung. "
- "NUTZE DIESES TOOL wenn der User über ein Thema recherchieren, analysieren, "
- "erklären, vergleichen oder zusammenfassen möchte — egal ob Firma, Produkt, "
- "Technologie, Konzept oder News. Beispiele: 'recherchiere zu X', 'was ist X', "
- "'vergleiche X mit Y', 'erklär mir X'. "
- "ALSO for weather questions ('weather tomorrow') — include the location "
- "in the query (e.g. 'weather Berlin tomorrow'). "
- "NICHT NUTZEN für Aktionen auf verbundenen Systemen (dafür cli_* oder MCP-Tools) — "
- "'meine X' oder 'starte X' sind NIE Research-Intent."
+ "Web-Suche via DuckDuckGo mit Kurz-Zusammenfassung — fuer FRISCHE, " # i18n-allow
+ "zeitkritische Fakten. NUTZE DIESES TOOL nur wenn die Antwort AKTUELLE " # i18n-allow
+ "oder volatile Information braucht, die sich seit deinem Wissensstand " # i18n-allow
+ "geaendert haben kann: aktuelle News, heutige Preise/Boersenkurse, " # i18n-allow
+ "Wetter, Sport-Ergebnisse, laufende Ereignisse, " # i18n-allow
+ "'neueste/aktuelle/heute/gerade' — ODER wenn der User AUSDRUECKLICH zu " # i18n-allow
+ "suchen bittet ('such mal', 'google das', 'recherchier'). " # i18n-allow
+ "NICHT NUTZEN fuer Evergreen-/Allgemeinwissen, das du selbst direkt " # i18n-allow
+ "beantworten kannst (Geografie, Geschichte, Definitionen, 'wie " # i18n-allow
+ "funktioniert X', allgemeine Ablaeufe / Vorgehensweisen wie 'was muss " # i18n-allow
+ "ich beim Auswandern beachten', bekannte Konzepte) — solche Fragen " # i18n-allow
+ "beantwortest du direkt aus deinem Wissen, ohne Suche. " # i18n-allow
+ "Fuer Wetterfragen die Location in die query schreiben (z.B. 'weather " # i18n-allow
+ "Berlin tomorrow'). " # i18n-allow
+ "NICHT NUTZEN fuer Aktionen auf verbundenen Systemen (dafuer cli_* oder " # i18n-allow
+ "MCP-Tools) — 'meine X' oder 'starte X' sind NIE Such-Intent." # i18n-allow
)
schema: dict[str, Any] = {
"type": "object",
diff --git a/jarvis/plugins/tool/spawn_worker.py b/jarvis/plugins/tool/spawn_worker.py
index d2279a3045..455f5ff149 100644
--- a/jarvis/plugins/tool/spawn_worker.py
+++ b/jarvis/plugins/tool/spawn_worker.py
@@ -123,7 +123,14 @@ _QUALITY_DIRECTIVE: Final[str] = (
"finished artefact; never downgrade the task to a minimal version, and "
'treat any hint (even one that says "Grundgerüst" / "skeleton") as a '
"floor, not a ceiling. This raises the quality of exactly what was asked "
- "— it does not add unrequested features. "
+ "— it does not add unrequested features, and it never overrides an explicit "
+ "constraint the user set on the SHAPE or scope of the deliverable (for "
+ 'example "a single self-contained HTML file" or "one script"): honoring such '
+ "a constraint is part of satisfying the request, not a downgrade. "
+ # Form-constraint carve-out (2026-06-22, mission 019ef052): the "never
+ # downgrade to a minimal version" floor read a single-file request as a
+ # forbidden minimal version, so a "single HTML file" brief shipped four files
+ # (html+js+css+asset). The floor governs QUALITY, never the user's chosen form.
# Honest-impossibility escape (latency 2026-06-14): without this, the "never
# downgrade / build the finished artefact" floor pushes the worker to spiral
# on a task it cannot actually do (e.g. "book a trip" with no booking tool —
@@ -137,6 +144,44 @@ _QUALITY_DIRECTIVE: Final[str] = (
)
+# Trivial/function words carry no topic, so they are ignored when checking
+# whether two utterances describe the SAME turn — a real interpretation keeps a
+# content word (an app name, an object, a verb stem); a bled-in old task shares
+# none. Small, multilingual; not exhaustive (the check is a cheap signal).
+_BLEED_STOPWORDS: frozenset[str] = frozenset({
+ "the", "and", "you", "your", "for", "please", "can", "could", "would",
+ "der", "die", "das", "und", "ich", "mir", "mein", "meine", "bitte", "mal", # i18n-allow
+ "kannst", "kann", "nach", "den", "dem", "ein", "eine", # i18n-allow
+ "los", "las", "una", "por", "para", "que",
+})
+
+
+def _shares_content_word(a: str, b: str) -> bool:
+ """True if ``a`` and ``b`` share a non-trivial content word.
+
+ A cheap signal that ``b`` describes the same turn as ``a`` rather than a
+ bled-in different task. Case-insensitive; ignores digits, sub-3-char tokens
+ and a small multilingual stop-word set.
+
+ Deliberate safe default: when EITHER side has no content word (a short or
+ proper-noun-only turn like "ok" or "Spotify"), there is not enough signal to
+ call it a bleed, so we return ``True`` (treat as matching) — biasing toward
+ NOT dropping the brain's interpretation, since a false bleed-positive would
+ discard a legitimate action.
+ """
+ def _content(s: str) -> set[str]:
+ return {
+ w
+ for w in re.findall(r"[^\W\d_]{3,}", (s or "").lower())
+ if w not in _BLEED_STOPWORDS
+ }
+
+ wa, wb = _content(a), _content(b)
+ if not wa or not wb:
+ return True
+ return bool(wa & wb)
+
+
def _build_mission_prompt(
utterance: str,
action: str,
@@ -372,10 +417,52 @@ class SpawnWorkerTool:
if not utterance:
return ToolResult(success=False, error="empty utterance")
- # Turn language for the spoken acknowledgement. Supplied by the brain
- # tool-call or the force-spawn caller; the composer falls back to its
- # own utterance heuristic when absent.
- ack_language = (args.get("language") or "").strip() or None
+ # Context-bleed guard (forensic 2026-06-20): under a full provider
+ # collapse the turn ran on a degraded fallback model fed a long prior
+ # context, which echoed a PREVIOUS request ("emigrate to Melbourne")
+ # into the spawn args although the user had just said "Mask it up" — the
+ # worker then built an entirely foreign task. ``ctx.user_utterance`` is
+ # the verbatim transcribed turn: the ground truth for what was just
+ # said. When the brain's utterance shares no content word with it, the
+ # whole tool-call belongs to a different turn — fall back to the verbatim
+ # turn and drop the (equally bled) action/target below, so the worker
+ # never executes a task the user did not ask for.
+ turn_text = (getattr(ctx, "user_utterance", "") or "").strip()
+ context_bleed = bool(
+ turn_text and not _shares_content_word(turn_text, utterance)
+ )
+ if context_bleed:
+ log.warning(
+ "spawn_worker: brain utterance %r is unrelated to the spoken "
+ "turn %r — context bleed; using the verbatim turn and dropping "
+ "the interpreted action/target",
+ utterance[:80], turn_text[:80],
+ )
+ utterance = turn_text
+
+ # Turn output language — ONE authoritative source. The tool-use loop
+ # stamps ``ctx.config["output_language"]`` via ``resolve_output_language``
+ # (honors the reply_language pin + conversation stickiness + text
+ # detection), so it wins over the brain's ``language`` tool-call guess,
+ # which can echo a wrong STT tag (forensic 2026-06-20 "Mask it up":
+ # English speech mis-tagged ``German`` resolved to ``en``, yet the ACK
+ # came from the German pool and the mission readback was German — German
+ # text then spoken by the Cartesia English voice = "British accent").
+ # This one value drives BOTH the spoken ACK and the mission dispatch
+ # language so neither diverges from the turn (Runtime Output Language).
+ turn_language = (
+ str(ctx.config.get("output_language") or "").strip().lower()
+ or (args.get("language") or "").strip().lower()
+ or None
+ )
+ ack_language = turn_language
+ # MissionManager.dispatch + the mission voice readback (announcer /
+ # readback) are de/en only — an "es" turn keeps the pre-existing German
+ # readback (bringing the mission voice layer to "es" is the tracked
+ # follow-up). Cap here so we never thread an unsupported value into the
+ # ``Literal["de","en"]`` dispatch contract; the spoken ACK itself stays
+ # fully de/en/es via the composer above.
+ mission_language = turn_language if turn_language in ("de", "en") else "de"
# Spawn cooldown — suppress duplicate spawns while a dispatch is in
# flight AND within _COOLDOWN_SECONDS of the last arm. Live regression
@@ -460,9 +547,11 @@ class SpawnWorkerTool:
),
)
- raw_action = (args.get("action") or "").strip()
+ # On a context bleed the brain's action/target belong to the wrong turn
+ # — drop them so the worker builds only from the verbatim utterance.
+ raw_action = "" if context_bleed else (args.get("action") or "").strip()
action = raw_action or _GENERIC_ACTION_FALLBACK
- target = (args.get("target") or "").strip()
+ target = "" if context_bleed else (args.get("target") or "").strip()
context_hints = args.get("context_hints") or []
# The worker reads ONLY the mission prompt. Enrich the verbatim
# utterance with the brain's interpreted action so a VAD-cut fragment
@@ -499,7 +588,8 @@ class SpawnWorkerTool:
# Listener als OpenClawBackgroundCompleted.
asyncio.create_task(
self._background_dispatch(
- mission_prompt, utterance, manager, kontrollierer
+ mission_prompt, utterance, manager, kontrollierer,
+ mission_language=mission_language,
),
name=f"openclaw-{ctx.trace_id.hex[:8]}",
)
@@ -535,6 +625,8 @@ class SpawnWorkerTool:
utterance: str,
manager: MissionManager,
kontrollierer: Any | None,
+ *,
+ mission_language: str = "de",
) -> None:
"""Laeuft im Background. Dispatched + executes eine Mission.
@@ -571,7 +663,7 @@ class SpawnWorkerTool:
try:
mission_id = await manager.dispatch(
prompt=prompt,
- language="de",
+ language=mission_language,
source_actor="hauptjarvis",
)
if kontrollierer is None:
diff --git a/jarvis/plugins/tool/switch_window.py b/jarvis/plugins/tool/switch_window.py
index ff9fec4790..338ed7e17d 100644
--- a/jarvis/plugins/tool/switch_window.py
+++ b/jarvis/plugins/tool/switch_window.py
@@ -1,8 +1,9 @@
"""switch_window-Tool: bringt ein Fenster nach Titel-Substring in den Vordergrund.
-Win32-Pfad nutzt ``EnumWindows`` + ``GetWindowText`` + ``SetForegroundWindow``.
-Der Caller gibt einen Substring an (case-insensitive), und das erste sichtbare
-Top-Level-Fenster, dessen Titel den Substring enthaelt, wird fokussiert.
+The window enumeration / focus logic now lives in
+``jarvis.platform.window_state`` (so ``open_app`` and the Computer-Use loop can
+reuse it). This tool delegates to the per-OS focus helpers there and keeps its
+exact user-facing readback strings (AD-7: the Windows path is unchanged).
Risk-Tier: ``monitor`` — Fenster-Switches sind reversibel, aber der Fokus-
Wechsel kann ungewollte Aktionen ausloesen, wenn der User gerade tippt.
@@ -10,186 +11,16 @@ Wechsel kann ungewollte Aktionen ausloesen, wenn der User gerade tippt.
from __future__ import annotations
import asyncio
-import os
-import re
-import shutil
-import subprocess
from typing import Any
-from jarvis.core.process_utils import NO_WINDOW_CREATIONFLAGS
from jarvis.core.protocols import ExecutionContext, ToolResult
from jarvis.platform import detect_platform
from jarvis.platform.probes import display_present, is_wayland
-
-
-def _find_and_focus_windows(title_contains: str) -> tuple[bool, str]:
- """Sucht nach einem sichtbaren Fenster mit Titel-Substring und fokussiert es.
-
- Returns:
- (found, message). ``found`` ist True wenn ein passendes Fenster
- gefunden UND erfolgreich fokussiert wurde. ``message`` enthaelt
- entweder den Fenster-Titel oder eine Fehlerursache.
- """
- if os.name != "nt":
- raise RuntimeError("Window-Switch ist nur auf Windows verfuegbar")
-
- import ctypes
- from ctypes import wintypes
-
- user32 = ctypes.windll.user32
-
- EnumWindows = user32.EnumWindows
- EnumWindowsProc = ctypes.WINFUNCTYPE(ctypes.c_bool, wintypes.HWND, wintypes.LPARAM)
- GetWindowTextW = user32.GetWindowTextW
- GetWindowTextLengthW = user32.GetWindowTextLengthW
- IsWindowVisible = user32.IsWindowVisible
- SetForegroundWindow = user32.SetForegroundWindow
- ShowWindow = user32.ShowWindow
-
- needle = title_contains.lower()
- found_hwnd: list[int] = []
- found_title: list[str] = []
-
- def _callback(hwnd: int, _lparam: int) -> bool:
- if not IsWindowVisible(hwnd):
- return True
- length = GetWindowTextLengthW(hwnd)
- if length <= 0:
- return True
- buf = ctypes.create_unicode_buffer(length + 1)
- GetWindowTextW(hwnd, buf, length + 1)
- title = buf.value or ""
- if needle in title.lower():
- found_hwnd.append(hwnd)
- found_title.append(title)
- return False # Stop enumeration
- return True
-
- EnumWindows(EnumWindowsProc(_callback), 0)
-
- if not found_hwnd:
- return False, f"Kein sichtbares Fenster mit Titel-Substring '{title_contains}' gefunden"
-
- hwnd = found_hwnd[0]
- title = found_title[0]
-
- # Wenn das Fenster minimiert ist, erst restoren (SW_RESTORE = 9).
- ShowWindow(hwnd, 9)
- if not SetForegroundWindow(hwnd):
- # SetForegroundWindow scheitert manchmal wegen Foreground-Lock-Timeout —
- # in dem Fall ist das Fenster zwar sichtbar gemacht, aber nicht fokussiert.
- return False, (
- f"Fenster '{title}' gefunden, aber Fokus-Setzen scheiterte "
- "(Foreground-Lock-Timeout — User muss Alt+Tab manuell drucken)"
- )
- return True, title
-
-
-def _find_and_focus_macos(title_contains: str) -> tuple[bool, str]:
- """Bring the first window whose title contains the substring to the front
- via AppleScript / System Events (H2, DEEP-DIVE-AUDIT-2026-06-19).
-
- Needs the macOS Accessibility grant; without it osascript errors out, which
- is reported as a clear onboarding message instead of a silent no-op. New
- non-Windows sibling — the Windows ctypes path is untouched (AD-7). All
- user-facing strings are English (Output-Language Policy).
- """
- if shutil.which("osascript") is None:
- return False, "osascript not found — cannot switch windows on this macOS host."
- # Lowercase for case-insensitive matching (parity with the Linux path), then
- # escape every AppleScript string-literal metacharacter — including newlines/
- # tabs — so a crafted title cannot break out of the `contains "..."` literal
- # and inject statements into the `tell` block (review HIGH).
- needle = (
- title_contains.lower()
- .replace("\\", "\\\\")
- .replace('"', '\\"')
- .replace("\n", "\\n")
- .replace("\r", "\\r")
- .replace("\t", "\\t")
- )
- needle = re.sub(r"[\x00-\x08\x0b\x0c\x0e-\x1f]", "", needle) # strip other control chars
- script = (
- 'tell application "System Events"\n'
- " repeat with proc in (every process whose visible is true)\n"
- " repeat with w in (every window of proc)\n"
- f' if (the lowercase of (name of w)) contains "{needle}" then\n'
- " set frontmost of proc to true\n"
- ' perform action "AXRaise" of w\n'
- " return name of w\n"
- " end if\n"
- " end repeat\n"
- " end repeat\n"
- "end tell\n"
- 'return ""\n'
- )
- proc = subprocess.run(
- ["osascript", "-e", script],
- capture_output=True,
- text=True,
- timeout=10,
- creationflags=NO_WINDOW_CREATIONFLAGS,
- )
- if proc.returncode != 0:
- err = (proc.stderr or "").strip()
- if "not allowed assistive access" in err.lower() or "-1719" in err:
- return False, (
- "macOS Accessibility permission not granted — grant it in System "
- "Settings > Privacy & Security > Accessibility so Jarvis can switch windows."
- )
- return False, f"osascript window switch failed: {err or proc.returncode}"
- matched = (proc.stdout or "").strip()
- if matched:
- return True, matched
- return False, f"No visible window with title containing '{title_contains}' found."
-
-
-def _find_and_focus_linux(title_contains: str) -> tuple[bool, str]:
- """Activate the first window whose title contains the substring via wmctrl
- on X11 (H2). Returns a clear message when wmctrl is absent (the user should
- install it, e.g. ``apt install wmctrl``) or nothing matches. New non-Windows
- sibling — the Windows path is untouched (AD-7). Wayland/headless are handled
- by the caller before this runs.
- """
- if shutil.which("wmctrl") is None:
- return False, (
- "wmctrl not found — install it (e.g. `apt install wmctrl`) to switch "
- "windows on X11."
- )
- listing = subprocess.run(
- ["wmctrl", "-l"],
- capture_output=True,
- text=True,
- timeout=10,
- creationflags=NO_WINDOW_CREATIONFLAGS,
- )
- if listing.returncode != 0:
- detail = (listing.stderr or "").strip() or f"exit code {listing.returncode}"
- return False, f"wmctrl could not list windows: {detail}"
- needle = title_contains.lower()
- win_id = ""
- win_title = ""
- for line in (listing.stdout or "").splitlines():
- # wmctrl -l format: <id> <desktop> <host> <title...>
- parts = line.split(None, 3)
- if len(parts) < 4:
- continue
- if needle in parts[3].lower():
- win_id, win_title = parts[0], parts[3]
- break
- if not win_id:
- return False, f"No visible window with title containing '{title_contains}' found."
- activate = subprocess.run(
- ["wmctrl", "-i", "-a", win_id],
- capture_output=True,
- text=True,
- timeout=10,
- creationflags=NO_WINDOW_CREATIONFLAGS,
- )
- if activate.returncode != 0:
- detail = (activate.stderr or "").strip()
- return False, f"wmctrl could not activate window '{win_title}': {detail}"
- return True, win_title
+from jarvis.platform.window_state import (
+ _find_and_focus_linux,
+ _find_and_focus_macos,
+ _find_and_focus_windows,
+)
class SwitchWindowTool:
diff --git a/jarvis/safety/risk_tier.py b/jarvis/safety/risk_tier.py
index 0d52e23633..eacdd337a4 100644
--- a/jarvis/safety/risk_tier.py
+++ b/jarvis/safety/risk_tier.py
@@ -13,13 +13,22 @@ Matching läuft per `fnmatch`-Glob gegen `"<tool_name> <serialized_args>"`.
from __future__ import annotations
import fnmatch
+import logging
from collections.abc import Callable
from dataclasses import dataclass
-from typing import Any
+from typing import Any, get_args
from jarvis.core.config import SafetyConfig
from jarvis.core.protocols import RiskTier, Tool
+log = logging.getLogger(__name__)
+
+#: Valid RiskTier vocabulary, derived from the Literal (drift-proof) so a hook
+#: return value or a misconfigured static tier is validated before it reaches
+#: the always_block / always_confirm membership checks. An unvalidated string
+#: would miss both checks and behave as the most permissive option silently.
+_VALID_TIERS: frozenset[str] = frozenset(get_args(RiskTier))
+
# Callable that returns (whitelist_patterns, blacklist_patterns). Wird bei jedem
# evaluate() aufgerufen — billig halten. Aktueller Nutzer: CliToolRegistry
# flattened Spec-Patterns pro verbundener CLI in dieses Tupel, damit
@@ -115,8 +124,36 @@ class RiskTierEvaluator:
command_string=cmd,
)
- # 3. Tool-Default (fallback auf Config-Default)
- tier: RiskTier = tool.risk_tier or self._safety.default_tier
+ # 3. Tool default (fallback to the config default), refined by an
+ # optional per-action hook. A tool with mixed actions (e.g. gmail: list/get
+ # read, send consequential) may expose ``risk_tier_for_args`` so a read
+ # call is not forced through the same ask-confirm as a send (forensic
+ # 2026-06-19, session dc533e39). The hook refines ONLY the tool default
+ # — blacklist and whitelist (above) keep priority. Every value (static
+ # or hook) is validated against the RiskTier vocabulary: an invalid
+ # string must never flow into the always_block / always_confirm
+ # membership checks (it would silently act as the most permissive
+ # option). A broken hook must never crash the gate.
+ raw_tier = getattr(tool, "risk_tier", None)
+ tier: RiskTier = raw_tier if raw_tier in _VALID_TIERS else self._safety.default_tier
+ hook = getattr(tool, "risk_tier_for_args", None)
+ if callable(hook):
+ try:
+ dynamic = hook(args)
+ except Exception as exc: # noqa: BLE001 — a broken hook must not break the gate
+ log.warning(
+ "risk_tier_for_args on %r raised %r — falling back to static tier %r",
+ tool.name, exc, tier,
+ )
+ dynamic = None
+ if dynamic in _VALID_TIERS:
+ tier = dynamic
+ elif dynamic is not None:
+ log.warning(
+ "risk_tier_for_args on %r returned unknown tier %r — "
+ "falling back to static tier %r",
+ tool.name, dynamic, tier,
+ )
# block-Tier wird direkt gebounced
if tier in self._safety.always_block_tiers:
diff --git a/jarvis/sessions/formatter.py b/jarvis/sessions/formatter.py
index c0877da240..cdacc66f5b 100644
--- a/jarvis/sessions/formatter.py
+++ b/jarvis/sessions/formatter.py
@@ -180,7 +180,12 @@ def format_session_markdown(
lines.append(f"**🔊 Jarvis sagte** _(de={t.jarvis_lang})_")
lines.append("")
for output in outputs:
- if output.is_reply:
+ if output.is_reply and t.awaiting_confirmation:
+ # The reply is a pending yes/no confirmation, not a normal
+ # answer — tag it like the other english spoken_kind tags so
+ # the transcript does not read it as a settled response.
+ lines.append(f"> _(awaiting confirmation)_ {output.text}")
+ elif output.is_reply:
lines.append(f"> {output.text}")
else:
lines.append(f"> _({output.kind})_ {output.text}")
diff --git a/jarvis/sessions/models.py b/jarvis/sessions/models.py
index 17f6d53e1a..e33c04ddbb 100644
--- a/jarvis/sessions/models.py
+++ b/jarvis/sessions/models.py
@@ -115,6 +115,10 @@ class VoiceTurnRow(BaseModel):
think_ms: int = 0
speak_ms: int = 0
tool_calls: list[str] = Field(default_factory=list)
+ # True when the turn ended on a two-turn voice/chat confirmation
+ # (finish_reason="voice_confirm_pending"): the reply is a pending yes/no
+ # question, not a normal answer, so the transcript labels it distinctly.
+ awaiting_confirmation: bool = False
class VoiceSessionRow(BaseModel):
diff --git a/jarvis/sessions/recorder.py b/jarvis/sessions/recorder.py
index b13d40f969..a3c81e60e8 100644
--- a/jarvis/sessions/recorder.py
+++ b/jarvis/sessions/recorder.py
@@ -133,6 +133,10 @@ class _TurnState:
speaking_started_ms: int = 0
think_ms: int = 0
speak_ms: int = 0
+ # Set when the turn ended on a two-turn voice/chat confirmation
+ # (BrainTurnCompleted.finish_reason == "voice_confirm_pending"): the reply
+ # is a pending yes/no question, not a normal answer.
+ awaiting_confirmation: bool = False
finalized: bool = False
@@ -442,6 +446,7 @@ class SessionRecorder:
tool_calls=t.tool_calls,
think_ms=t.think_ms,
speak_ms=t.speak_ms,
+ awaiting_confirmation=t.awaiting_confirmation,
)
# Aggregate hochzaehlen
self._state.turn_count += 1
@@ -584,6 +589,12 @@ class SessionRecorder:
t.provider = event.provider
if event.model:
t.model = event.model
+ # A consequential ask-tier tool deferred into a two-turn confirmation
+ # ends the turn here; flag it so the transcript labels the reply as a
+ # pending yes/no question rather than a normal answer (forensic
+ # 2026-06-19). Latch True — a later successful round must not clear it.
+ if getattr(event, "finish_reason", "") == "voice_confirm_pending":
+ t.awaiting_confirmation = True
def _on_tool_started(self, event: ToolCallStarted) -> None:
assert self._state is not None
@@ -799,6 +810,18 @@ def _payload_for(event: Event) -> dict[str, Any]:
payload["lang"] = getattr(v, "language", "")
continue
payload[k] = v
+ # ActionProposed.args may hold PII (an email body / recipient, a search
+ # query) — it is deliberately NOT in the whitelist, so the raw dict is never
+ # persisted. Pull only the short, enum-like ``action`` selector so forensics
+ # can tell which operation a mixed read/write tool ran: before this a gmail
+ # read was indistinguishable from a send in the persisted event (forensic
+ # 2026-06-19, session dc533e39). Bounded length keeps a tool from smuggling
+ # a payload through the key.
+ raw_args = getattr(event, "args", None)
+ if isinstance(raw_args, dict):
+ action = raw_args.get("action")
+ if isinstance(action, str) and 0 < len(action) <= 64:
+ payload["action"] = action
return payload
diff --git a/jarvis/sessions/schema.sql b/jarvis/sessions/schema.sql
index 32b10809d5..b7a69e223b 100644
--- a/jarvis/sessions/schema.sql
+++ b/jarvis/sessions/schema.sql
@@ -51,6 +51,11 @@ CREATE TABLE IF NOT EXISTS voice_turns (
-- = wie lang Jarvis gesprochen hat (TTS-Playback-Dauer)
think_ms INTEGER NOT NULL DEFAULT 0,
speak_ms INTEGER NOT NULL DEFAULT 0,
+ -- 1 when the turn ended on a two-turn voice/chat confirmation
+ -- (finish_reason="voice_confirm_pending"): the reply is a pending yes/no
+ -- question, not a settled answer. Also added via _apply_migrations for
+ -- pre-existing DBs (the idempotent PRAGMA-guard makes both paths safe).
+ awaiting_confirmation INTEGER NOT NULL DEFAULT 0,
tool_calls_json TEXT NOT NULL DEFAULT '[]' -- JSON-Array of tool-name strings
);
diff --git a/jarvis/sessions/store.py b/jarvis/sessions/store.py
index e75d57970a..021d7ffce3 100644
--- a/jarvis/sessions/store.py
+++ b/jarvis/sessions/store.py
@@ -88,6 +88,12 @@ class SessionStore:
"ALTER TABLE voice_turns ADD COLUMN speak_ms INTEGER NOT NULL DEFAULT 0"
)
log.info("SessionStore migration: added voice_turns.speak_ms")
+ if "awaiting_confirmation" not in existing:
+ self._conn.execute(
+ "ALTER TABLE voice_turns "
+ "ADD COLUMN awaiting_confirmation INTEGER NOT NULL DEFAULT 0"
+ )
+ log.info("SessionStore migration: added voice_turns.awaiting_confirmation")
def close(self) -> None:
with self._lock:
@@ -209,26 +215,28 @@ class SessionStore:
tool_calls: list[str],
think_ms: int = 0,
speak_ms: int = 0,
+ awaiting_confirmation: bool = False,
) -> None:
with self._lock:
self._c.execute(
"""
UPDATE voice_turns SET
- ended_ms = ?,
- user_text = ?,
- user_lang = ?,
- jarvis_text = ?,
- jarvis_lang = ?,
- tier = ?,
- provider = ?,
- model = ?,
- tokens_in = ?,
- tokens_out = ?,
- cost_usd = ?,
- latency_total_ms = ?,
- think_ms = ?,
- speak_ms = ?,
- tool_calls_json = ?
+ ended_ms = ?,
+ user_text = ?,
+ user_lang = ?,
+ jarvis_text = ?,
+ jarvis_lang = ?,
+ tier = ?,
+ provider = ?,
+ model = ?,
+ tokens_in = ?,
+ tokens_out = ?,
+ cost_usd = ?,
+ latency_total_ms = ?,
+ think_ms = ?,
+ speak_ms = ?,
+ awaiting_confirmation = ?,
+ tool_calls_json = ?
WHERE id = ?
""",
(
@@ -246,6 +254,7 @@ class SessionStore:
latency_total_ms,
think_ms,
speak_ms,
+ 1 if awaiting_confirmation else 0,
json.dumps(tool_calls),
turn_id,
),
@@ -478,6 +487,10 @@ def _row_to_turn(r: sqlite3.Row) -> VoiceTurnRow:
latency_total_ms=r["latency_total_ms"],
think_ms=_safe_col(r, "think_ms", 0),
speak_ms=_safe_col(r, "speak_ms", 0),
+ # SQLite stores this as INTEGER 0/1; bool() is intentional (0 -> False,
+ # 1 -> True). Keep _safe_col's contract at 0/1 — a sentinel like -1 would
+ # break the bool() mapping here.
+ awaiting_confirmation=bool(_safe_col(r, "awaiting_confirmation", 0)),
tool_calls=json.loads(r["tool_calls_json"] or "[]"),
)
diff --git a/jarvis/setup/onboarding_meta.py b/jarvis/setup/onboarding_meta.py
index 74ad038e45..3478347167 100644
--- a/jarvis/setup/onboarding_meta.py
+++ b/jarvis/setup/onboarding_meta.py
@@ -21,8 +21,6 @@ ONBOARDING_STEPS: list[str] = [
"language",
"wake-word",
"api-keys",
- "mic-test",
- "persona-theme",
"finish",
]
diff --git a/jarvis/setup/wizard.py b/jarvis/setup/wizard.py
index e9685320e0..cf8a31527d 100644
--- a/jarvis/setup/wizard.py
+++ b/jarvis/setup/wizard.py
@@ -126,9 +126,9 @@ SECRETS: list[SecretSpec] = [
SecretSpec(
key="grok_api_key",
env_fallback="GROK_API_KEY",
- label="xAI Grok API Key (Brain + Voice/TTS)",
+ label="xAI Grok Voice API Key (TTS)",
help_url="https://console.x.ai/",
- required_for="Brain (Grok) + TTS (Grok Voice — leo/rex/sal/ara/eve) + OpenClaw-Bridge (xai-Provider, ENV XAI_API_KEY)",
+ required_for="TTS (Grok Voice — leo/rex/sal/ara/eve)",
),
SecretSpec(
key="google_tts_credentials_path",
@@ -527,7 +527,6 @@ def step_openclaw_check() -> None:
"openrouter": "openrouter_api_key",
"openai": "openai_api_key",
"gemini": "gemini_api_key",
- "grok": "grok_api_key",
}
for mapping in MAPPINGS:
secret_key = secret_key_overrides.get(
diff --git a/jarvis/skills/authoring/__init__.py b/jarvis/skills/authoring/__init__.py
index 45cdabdc69..3233b79529 100644
--- a/jarvis/skills/authoring/__init__.py
+++ b/jarvis/skills/authoring/__init__.py
@@ -13,6 +13,8 @@ der Worker explizit `active` im Frontmatter angibt.
"""
from __future__ import annotations
+from typing import TYPE_CHECKING
+
from .draft_writer import (
DraftWriteResult,
SlugError,
@@ -20,21 +22,56 @@ from .draft_writer import (
safe_lint_skill_body,
write_draft,
)
-from .runner import (
- AuthoringFailure,
- AuthoringSuccess,
- SkillAuthoringRunner,
-)
from .schema import SkillDraft
+from .service import (
+ SkillAuthoringError,
+ SkillAuthoringService,
+ SkillCreateRequest,
+ render_skill_md,
+ slugify,
+)
+
+# ``runner`` imports ``jarvis.core.self_mod``, which participates in a latent
+# import cycle (self_mod -> config -> brain -> voice.echo_confirmation ->
+# self_mod). Eager-importing it here would drag that cycle into every
+# ``import jarvis.skills.authoring`` — including the cycle-free UI Skill Creator
+# path (``creator_service`` -> ``authoring.service``). Load the runner lazily
+# (PEP 562): the mission pipeline that actually uses it triggers the import on
+# first attribute access, by which point the cycle is warm. ``.service``,
+# ``.draft_writer`` and ``.schema`` carry no self_mod dependency and stay eager.
+_LAZY_RUNNER_EXPORTS = frozenset(
+ {"AuthoringFailure", "AuthoringSuccess", "SkillAuthoringRunner"}
+)
+
+if TYPE_CHECKING: # pragma: no cover — type-checker visibility only
+ from .runner import (
+ AuthoringFailure,
+ AuthoringSuccess,
+ SkillAuthoringRunner,
+ )
+
+
+def __getattr__(name: str):
+ if name in _LAZY_RUNNER_EXPORTS:
+ from . import runner
+
+ return getattr(runner, name)
+ raise AttributeError(f"module {__name__!r} has no attribute {name!r}")
+
__all__ = [
"AuthoringFailure",
"AuthoringSuccess",
"DraftWriteResult",
+ "SkillAuthoringError",
"SkillAuthoringRunner",
+ "SkillAuthoringService",
+ "SkillCreateRequest",
"SkillDraft",
"SlugError",
"UnsafeSkillError",
+ "render_skill_md",
"safe_lint_skill_body",
+ "slugify",
"write_draft",
]
diff --git a/jarvis/skills/authoring/service.py b/jarvis/skills/authoring/service.py
new file mode 100644
index 0000000000..13f03f5c66
--- /dev/null
+++ b/jarvis/skills/authoring/service.py
@@ -0,0 +1,226 @@
+"""Deterministic user-skill authoring for ``POST /api/skills``.
+
+This is the "New skill" form path in the desktop app. It takes a structured
+request (name, description, body, triggers) and writes a SKILL.md
+deterministically — NO brain, no network — so it works on a headless €5 VPS.
+
+It is the sibling of the OpenClaw-author *mission* pipeline
+(``SkillAuthoringRunner`` in ``runner.py``): that one spawns a frontier worker to
+generate a draft from a voice intent and forces ``state=draft``; this one
+persists an explicit, user-reviewed form submission and leaves the skill
+immediately usable (no ``state`` field -> the loader treats it as VALIDATED,
+i.e. "on"). A user who fills the form and hits Create expects a working skill,
+not a draft they then have to flip on. The AI-assisted creator
+(``creator_service.py``) writes through ``commit`` with ``state=draft`` instead,
+because that content is LLM-generated (AP-15).
+"""
+from __future__ import annotations
+
+import logging
+import re
+from dataclasses import dataclass, field
+from pathlib import Path
+from typing import Any
+
+import yaml
+from pydantic import ValidationError
+
+from jarvis.core.paths import user_skills_dir
+from jarvis.skills.builtin import BUILTIN_SKILL_NAMES
+from jarvis.skills.loader import parse_skill
+from jarvis.skills.schema import Skill, SkillCreated, SkillFrontmatter
+
+_LOG = logging.getLogger(__name__)
+
+_SKILL_FILENAME = "SKILL.md"
+# Slug = lowercase kebab-case; everything that is not [a-z0-9] collapses to a
+# single hyphen, leading/trailing hyphens stripped. Mirrors the SkillDraft slug
+# contract (no path separators, no spaces, no dot-dot).
+_SLUG_STRIP_RE = re.compile(r"[^a-z0-9]+")
+
+
+class SkillAuthoringError(Exception):
+ """A create request could not be fulfilled.
+
+ ``status`` is the HTTP status the REST route surfaces: 400 for a malformed
+ request (empty/unslugable name, invalid frontmatter), 409 for a name that
+ collides with an existing skill or a built-in.
+ """
+
+ def __init__(self, message: str, *, status: int = 400) -> None:
+ super().__init__(message)
+ self.status = status
+
+
+@dataclass(frozen=True)
+class SkillCreateRequest:
+ """A structured new-skill request from the desktop form.
+
+ Only ``name`` is required. ``triggers`` is a tuple of plain dicts matching
+ the ``SkillTrigger`` shape (``{"type": "voice", "pattern": "..."}``);
+ ``risk_policy`` matches ``SkillRiskPolicy``.
+ """
+
+ name: str
+ description: str = ""
+ category: str = "general"
+ tags: tuple[str, ...] = ()
+ triggers: tuple[dict[str, Any], ...] = ()
+ requires_tools: tuple[str, ...] = ()
+ risk_policy: dict[str, Any] | None = None
+ body: str = ""
+ homepage_url: str | None = None
+ source_url: str | None = None
+ docs_url: str | None = None
+ author: str = ""
+
+
+def slugify(name: str) -> str:
+ """Kebab-case slug from a display name. Empty string if nothing slugable."""
+ return _SLUG_STRIP_RE.sub("-", name.strip().lower()).strip("-")
+
+
+def _build_frontmatter(req: SkillCreateRequest) -> dict[str, Any]:
+ """Assemble the YAML frontmatter dict, omitting empty optional fields.
+
+ Deliberately omits ``state`` so the loader resolves the skill to VALIDATED
+ ("on") — an explicit user-authored skill is usable immediately.
+ """
+ fm: dict[str, Any] = {
+ "schema_version": "1",
+ "name": req.name.strip(),
+ "version": "0.1.0",
+ "description": req.description,
+ "category": (req.category or "general").strip() or "general",
+ }
+ if req.tags:
+ fm["tags"] = list(req.tags)
+ if req.author:
+ fm["author"] = req.author
+ if req.homepage_url:
+ fm["homepage_url"] = req.homepage_url
+ if req.source_url:
+ fm["source_url"] = req.source_url
+ if req.docs_url:
+ fm["docs_url"] = req.docs_url
+ if req.triggers:
+ fm["triggers"] = [dict(t) for t in req.triggers]
+ if req.requires_tools:
+ fm["requires_tools"] = list(req.requires_tools)
+ if req.risk_policy:
+ fm["risk_policy"] = dict(req.risk_policy)
+ return fm
+
+
+def render_skill_md(req: SkillCreateRequest) -> str:
+ """Render a complete SKILL.md (validated frontmatter + body).
+
+ Raises ``SkillAuthoringError(400)`` when the assembled frontmatter does not
+ pass ``SkillFrontmatter`` validation (e.g. a trigger missing its payload).
+ """
+ fm = _build_frontmatter(req)
+ try:
+ SkillFrontmatter.model_validate(fm)
+ except ValidationError as exc:
+ raise SkillAuthoringError(
+ f"Invalid skill definition: {exc.errors()[0].get('msg', exc)}",
+ status=400,
+ ) from exc
+ yaml_text = yaml.safe_dump(fm, sort_keys=False, allow_unicode=True)
+ body = req.body if req.body.strip() else f"## {req.name.strip()}\n"
+ return f"---\n{yaml_text}---\n\n{body.rstrip()}\n"
+
+
+class SkillAuthoringService:
+ """Creates a user skill on disk and refreshes the registry."""
+
+ def __init__(
+ self,
+ *,
+ registry: Any,
+ bus: Any | None = None,
+ user_skills_root: Path | None = None,
+ ) -> None:
+ self._registry = registry
+ self._bus = bus
+ # Default to the registry's own root so the written skill always lands
+ # where the registry looks; fall back to the canonical user dir.
+ if user_skills_root is not None:
+ self._root = Path(user_skills_root)
+ else:
+ self._root = Path(getattr(registry, "root", user_skills_dir()))
+
+ async def create(self, req: SkillCreateRequest) -> Skill:
+ name = req.name.strip()
+ if not name:
+ raise SkillAuthoringError("Name must not be empty.", status=400)
+
+ slug = slugify(name)
+ if not slug:
+ raise SkillAuthoringError(
+ f"Name '{req.name}' has no usable characters for a skill id.",
+ status=400,
+ )
+
+ # Collision: explicit built-in name, an existing skill, or a slug
+ # directory already on disk.
+ if name in BUILTIN_SKILL_NAMES:
+ raise SkillAuthoringError(
+ f"'{name}' is a built-in skill name.", status=409
+ )
+ existing = {s.name for s in self._registry.list()}
+ if name in existing:
+ raise SkillAuthoringError(
+ f"A skill named '{name}' already exists.", status=409
+ )
+ target_dir = self._root / slug
+ if target_dir.exists():
+ raise SkillAuthoringError(
+ f"A skill folder '{slug}' already exists.", status=409
+ )
+
+ rendered = render_skill_md(req)
+
+ # Atomic write: temp file in the (newly created) slug dir, then replace.
+ target_dir.mkdir(parents=True, exist_ok=True)
+ skill_path = target_dir / _SKILL_FILENAME
+ tmp = skill_path.with_suffix(skill_path.suffix + ".tmp")
+ try:
+ tmp.write_text(rendered, encoding="utf-8")
+ tmp.replace(skill_path)
+ except OSError as exc:
+ raise SkillAuthoringError(
+ f"Could not write skill: {exc}", status=500
+ ) from exc
+
+ # Refresh so the new skill is immediately listable + the response shows
+ # the parsed state. reload_sync is the synchronous path (the watcher
+ # hot-reload would also pick it up, but async).
+ self._registry.reload_sync()
+ try:
+ created = self._registry.get(name)
+ except KeyError:
+ # The file parsed to a different name than requested (shouldn't
+ # happen — frontmatter name == req.name) or failed to load.
+ created = parse_skill(skill_path)
+
+ await self._emit_created(created, req.author)
+ return created
+
+ async def _emit_created(self, skill: Skill, author: str) -> None:
+ bus = self._bus
+ if bus is None or not hasattr(bus, "publish"):
+ return
+ try:
+ await bus.publish(SkillCreated(skill_name=skill.name, author=author))
+ except Exception as exc: # noqa: BLE001 — telemetry must never block create
+ _LOG.warning("SkillCreated publish failed: %s", exc)
+
+
+__all__ = [
+ "SkillAuthoringError",
+ "SkillAuthoringService",
+ "SkillCreateRequest",
+ "render_skill_md",
+ "slugify",
+]
diff --git a/jarvis/skills/creator_service.py b/jarvis/skills/creator_service.py
new file mode 100644
index 0000000000..4e21473c6d
--- /dev/null
+++ b/jarvis/skills/creator_service.py
@@ -0,0 +1,501 @@
+"""AI Skill Creator — backs ``/api/skills/creator/{draft,refine,validate,commit}``.
+
+Turns a free-text intent into a structured SKILL.md draft, optionally with brain
+assistance, and commits the user-reviewed draft as a real skill.
+
+Cloud-first contract: the creator is brain-*assisted*, never brain-*dependent*.
+``draft`` always returns a valid deterministic skeleton; if a brain is reachable
+and returns parseable JSON, the skeleton is replaced by the brain's richer draft
+(``brain_used=True``). A missing brain, a timeout, a refusal, or malformed JSON
+all degrade silently to the skeleton — so the feature works on a headless €5 VPS
+with no provider configured.
+
+``commit`` persists the reviewed draft through the same deterministic writer as
+the manual "New skill" form (``SkillAuthoringService``), so there is one
+code path that touches the registry.
+"""
+from __future__ import annotations
+
+import asyncio
+import json
+import logging
+import re
+from dataclasses import dataclass, field
+from pathlib import Path
+from typing import Any
+
+import yaml
+from pydantic import ValidationError
+
+from jarvis.skills.authoring.service import (
+ SkillAuthoringError,
+ SkillAuthoringService,
+ SkillCreateRequest,
+)
+from jarvis.skills.schema import Skill, SkillFrontmatter
+
+_LOG = logging.getLogger(__name__)
+
+# Bounded brain call — the creator runs from a UI click, not the voice hot path,
+# but we still cap it so a hung provider cannot wedge the request.
+_BRAIN_TIMEOUT_S = 45.0
+_BRAIN_MAX_TOKENS = 1500
+
+_WORD_RE = re.compile(r"[A-Za-z0-9]+")
+
+
+# ----------------------------------------------------------------------
+# Inputs / outputs
+# ----------------------------------------------------------------------
+
+
+@dataclass(frozen=True)
+class SkillCreatorInput:
+ """A creator request. ``intent`` is the user's free-text description; the
+ rest are optional UI hints. ``existing_draft`` + ``feedback`` drive
+ ``refine`` (a revision of a prior draft)."""
+
+ intent: str
+ name_hint: str = ""
+ category: str = "general"
+ trigger_hint: str = ""
+ extra_context: str = ""
+ existing_draft: dict[str, Any] | None = None
+ feedback: str = ""
+
+
+@dataclass(frozen=True)
+class SkillCreatorResult:
+ """What ``draft``/``refine`` return — mirrors the frontend response type."""
+
+ draft: dict[str, Any]
+ skill_md: str
+ validation: dict[str, Any]
+ brain_used: bool
+
+
+# ----------------------------------------------------------------------
+# Draft shape helpers
+# ----------------------------------------------------------------------
+
+
+def _empty_draft() -> dict[str, Any]:
+ return {
+ "name": "",
+ "description": "",
+ "category": "general",
+ "tags": [],
+ "triggers": [],
+ "requires_tools": [],
+ "risk_policy": {"default_tier": "ask"},
+ "body": "",
+ "questions": [],
+ "assumptions": [],
+ "test_prompts": [],
+ }
+
+
+def _title_from_intent(intent: str) -> str:
+ """A short Title-Case name from the first few words of the intent."""
+ words = _WORD_RE.findall(intent)[:5]
+ if not words:
+ return "New Skill"
+ return " ".join(w.capitalize() for w in words)
+
+
+def _skeleton_draft(inp: SkillCreatorInput) -> dict[str, Any]:
+ """A valid deterministic draft from the intent alone — no brain.
+
+ This is the always-available fallback. It is intentionally minimal but
+ complete enough to validate and commit unchanged.
+ """
+ draft = _empty_draft()
+ name = inp.name_hint.strip() or _title_from_intent(inp.intent)
+ draft["name"] = name
+ draft["description"] = inp.intent.strip()[:400] or name
+ draft["category"] = (inp.category or "general").strip() or "general"
+ if inp.trigger_hint.strip():
+ draft["triggers"] = [
+ {"type": "voice", "pattern": inp.trigger_hint.strip()}
+ ]
+ body_lines = [
+ f"## {name}",
+ "",
+ inp.intent.strip() or "Describe what this skill does.",
+ "",
+ "## Steps",
+ "",
+ "1. ...",
+ ]
+ if inp.extra_context.strip():
+ body_lines += ["", "## Notes", "", inp.extra_context.strip()]
+ draft["body"] = "\n".join(body_lines) + "\n"
+ draft["assumptions"] = [
+ "Generated deterministically without a brain — edit before committing."
+ ]
+ return draft
+
+
+def _coerce_brain_draft(
+ data: dict[str, Any], inp: SkillCreatorInput
+) -> dict[str, Any]:
+ """Merge a brain-produced dict onto the empty-draft shape, dropping unknown
+ keys and backfilling required ones from the skeleton."""
+ skeleton = _skeleton_draft(inp)
+ draft = _empty_draft()
+ for key in draft:
+ if key in data and data[key] not in (None, ""):
+ draft[key] = data[key]
+ else:
+ draft[key] = skeleton[key]
+ # Normalise list/dict typed fields defensively.
+ for list_key in (
+ "tags",
+ "triggers",
+ "requires_tools",
+ "questions",
+ "assumptions",
+ "test_prompts",
+ ):
+ if not isinstance(draft[list_key], list):
+ draft[list_key] = []
+ if not isinstance(draft["risk_policy"], dict):
+ draft["risk_policy"] = {"default_tier": "ask"}
+ draft["name"] = str(draft["name"]).strip() or skeleton["name"]
+ draft["body"] = str(draft["body"]).strip() and draft["body"] or skeleton["body"]
+ return draft
+
+
+def _extract_json(text: str) -> dict[str, Any] | None:
+ """Pull the first top-level JSON object out of a brain response."""
+ cleaned = text.strip()
+ fence = re.match(r"```(?:json)?\s*\n?(.*?)```", cleaned, re.DOTALL | re.IGNORECASE)
+ if fence:
+ cleaned = fence.group(1).strip()
+ start = cleaned.find("{")
+ end = cleaned.rfind("}")
+ if start < 0 or end <= start:
+ return None
+ try:
+ data = json.loads(cleaned[start : end + 1])
+ except (ValueError, TypeError):
+ return None
+ return data if isinstance(data, dict) else None
+
+
+# ----------------------------------------------------------------------
+# Render + validate
+# ----------------------------------------------------------------------
+
+
+def _extract_frontmatter(content: str) -> dict[str, Any] | None:
+ """Parse the YAML frontmatter block out of a SKILL.md string.
+
+ Returns ``None`` when there is no ``---``-delimited frontmatter at all.
+ Raises ``ValueError`` when the YAML is malformed.
+ """
+ stripped = content.lstrip()
+ if not stripped.startswith("---"):
+ return None
+ parts = stripped.split("---", 2)
+ if len(parts) < 3:
+ return None
+ try:
+ data = yaml.safe_load(parts[1])
+ except yaml.YAMLError as exc:
+ raise ValueError(f"Malformed YAML frontmatter: {exc}") from exc
+ return data if isinstance(data, dict) else None
+
+
+def render_skill_md(draft: dict[str, Any]) -> str:
+ """Render a SKILL.md string from a creator draft dict (state forced draft).
+
+ Unlike the manual form (which writes a usable VALIDATED skill), the AI
+ creator stamps ``state: draft`` because the content is LLM-generated — but
+ here we only *render* for preview/validate; ``commit`` decides persistence.
+ """
+ fm: dict[str, Any] = {
+ "schema_version": "1",
+ "name": str(draft.get("name", "")).strip(),
+ "version": "0.1.0",
+ "description": str(draft.get("description", "")),
+ "category": str(draft.get("category", "general")) or "general",
+ }
+ if draft.get("tags"):
+ fm["tags"] = list(draft["tags"])
+ if draft.get("triggers"):
+ fm["triggers"] = [dict(t) for t in draft["triggers"]]
+ if draft.get("requires_tools"):
+ fm["requires_tools"] = list(draft["requires_tools"])
+ if draft.get("risk_policy"):
+ fm["risk_policy"] = dict(draft["risk_policy"])
+ yaml_text = yaml.safe_dump(fm, sort_keys=False, allow_unicode=True)
+ body = str(draft.get("body", "")).strip() or f"## {fm['name']}\n"
+ return f"---\n{yaml_text}---\n\n{body.rstrip()}\n"
+
+
+def validate_skill_md(content: str) -> tuple[dict[str, Any], dict[str, Any] | None]:
+ """Validate a SKILL.md string. Returns ``(validation, frontmatter)``.
+
+ ``validation`` is ``{ok, state, errors, warnings, parse_error}``. ``ok`` is
+ True only when the frontmatter both parses and passes ``SkillFrontmatter``.
+ """
+ errors: list[str] = []
+ warnings: list[str] = []
+ parse_error: str | None = None
+
+ try:
+ fm_dict = _extract_frontmatter(content)
+ except ValueError as exc:
+ return (
+ {
+ "ok": False,
+ "state": "draft",
+ "errors": [str(exc)],
+ "warnings": [],
+ "parse_error": str(exc),
+ },
+ None,
+ )
+
+ if not fm_dict:
+ parse_error = "No YAML frontmatter found."
+ return (
+ {
+ "ok": False,
+ "state": "draft",
+ "errors": [parse_error],
+ "warnings": [],
+ "parse_error": parse_error,
+ },
+ None,
+ )
+
+ try:
+ model = SkillFrontmatter.model_validate(fm_dict)
+ except ValidationError as exc:
+ for err in exc.errors():
+ loc = ".".join(str(p) for p in err.get("loc", ()))
+ errors.append(f"{loc}: {err.get('msg', 'invalid')}".lstrip(": "))
+ return (
+ {
+ "ok": False,
+ "state": "draft",
+ "errors": errors,
+ "warnings": warnings,
+ "parse_error": None,
+ },
+ None,
+ )
+
+ # Semantic trigger checks (voice needs a pattern, etc.) → warnings, not hard
+ # errors, so the user can still commit and refine.
+ for trig in model.triggers:
+ warnings.extend(trig.validate_payload())
+
+ return (
+ {
+ "ok": True,
+ "state": "validated",
+ "errors": [],
+ "warnings": warnings,
+ "parse_error": None,
+ },
+ model.model_dump(),
+ )
+
+
+# ----------------------------------------------------------------------
+# Service
+# ----------------------------------------------------------------------
+
+
+class SkillCreatorService:
+ """Brain-assisted skill drafting + deterministic commit."""
+
+ def __init__(
+ self,
+ *,
+ brain: Any | None = None,
+ registry: Any,
+ bus: Any | None = None,
+ config: Any | None = None,
+ user_skills_root: Path | None = None,
+ ) -> None:
+ self._brain = brain
+ self._registry = registry
+ self._bus = bus
+ self._config = config
+ self._user_skills_root = user_skills_root
+
+ async def draft(self, inp: SkillCreatorInput) -> SkillCreatorResult:
+ return await self._draft_or_refine(inp)
+
+ async def refine(self, inp: SkillCreatorInput) -> SkillCreatorResult:
+ return await self._draft_or_refine(inp, refine=True)
+
+ async def commit(self, draft: dict[str, Any]) -> Skill:
+ """Persist a reviewed draft as a real skill via the shared writer."""
+ if not isinstance(draft, dict):
+ raise ValueError("draft must be an object")
+ req = SkillCreateRequest(
+ name=str(draft.get("name", "")).strip(),
+ description=str(draft.get("description", "")),
+ category=str(draft.get("category", "general")) or "general",
+ tags=tuple(draft.get("tags", []) or ()),
+ triggers=tuple(draft.get("triggers", []) or ()),
+ requires_tools=tuple(draft.get("requires_tools", []) or ()),
+ risk_policy=draft.get("risk_policy") or None,
+ body=str(draft.get("body", "")),
+ )
+ service = SkillAuthoringService(
+ registry=self._registry,
+ bus=self._bus,
+ user_skills_root=self._user_skills_root,
+ )
+ return await service.create(req)
+
+ # ------------------------------------------------------------------
+ # Internals
+ # ------------------------------------------------------------------
+
+ async def _draft_or_refine(
+ self, inp: SkillCreatorInput, *, refine: bool = False
+ ) -> SkillCreatorResult:
+ skeleton = _skeleton_draft(inp)
+ draft = skeleton
+ brain_used = False
+
+ brain_draft = await self._try_brain(inp, refine=refine)
+ if brain_draft is not None:
+ draft = _coerce_brain_draft(brain_draft, inp)
+ brain_used = True
+
+ skill_md = render_skill_md(draft)
+ validation, _ = validate_skill_md(skill_md)
+ # If a brain draft somehow failed validation, fall back to the skeleton
+ # (which is constructed to always validate).
+ if not validation["ok"] and brain_used:
+ draft = skeleton
+ brain_used = False
+ skill_md = render_skill_md(draft)
+ validation, _ = validate_skill_md(skill_md)
+
+ return SkillCreatorResult(
+ draft=draft,
+ skill_md=skill_md,
+ validation=validation,
+ brain_used=brain_used,
+ )
+
+ def _resolve_brain(self) -> Any | None:
+ """A brain with a ``.complete()`` method, or None.
+
+ Multi-provider contract (AP-21): follow the user's ACTIVE selection,
+ never a hardcoded frontier favourite. The injected ``brain`` is the live
+ ``BrainManager``; ask it for the provider the user currently has active
+ (e.g. Gemini) rather than letting the frontier resolver pick an unkeyed
+ Claude-API and 401. Order:
+ 1. the BrainManager's active provider (``active_provider`` +
+ ``_get_or_create``),
+ 2. an injected raw provider that already exposes ``.complete``,
+ 3. the frontier resolver from config (only when no usable brain was
+ injected — e.g. the brain hasn't finished building yet).
+ Any failure degrades to ``None`` → deterministic skeleton.
+ """
+ bm = self._brain
+ if bm is not None:
+ getter = getattr(bm, "_get_or_create", None)
+ active = getattr(bm, "active_provider", None)
+ if callable(getter) and isinstance(active, str):
+ try:
+ prov = getter(active)
+ if hasattr(prov, "complete"):
+ return prov
+ except Exception as exc: # noqa: BLE001
+ _LOG.info("creator: active-provider resolve failed (%s)", exc)
+ if hasattr(bm, "complete"):
+ return bm
+ if self._config is not None:
+ try:
+ from jarvis.brain.resolver import resolve_frontier_brain
+
+ resolved = resolve_frontier_brain(self._config, bus=self._bus)
+ if hasattr(resolved, "complete"):
+ return resolved
+ except Exception as exc: # noqa: BLE001
+ _LOG.info("creator: frontier resolve failed (%s)", exc)
+ return None
+
+ async def _try_brain(
+ self, inp: SkillCreatorInput, *, refine: bool
+ ) -> dict[str, Any] | None:
+ brain = self._resolve_brain()
+ if brain is None:
+ return None
+ from jarvis.brain.streaming import aggregate
+ from jarvis.core.protocols import BrainMessage, BrainRequest
+
+ system, user = _build_prompt(inp, refine=refine)
+ request = BrainRequest(
+ messages=(BrainMessage(role="user", content=user),),
+ system=system,
+ max_tokens=_BRAIN_MAX_TOKENS,
+ temperature=0.4,
+ stream=True,
+ )
+ try:
+ agg = await asyncio.wait_for(
+ aggregate(brain.complete(request)), timeout=_BRAIN_TIMEOUT_S
+ )
+ except (TimeoutError, asyncio.TimeoutError):
+ _LOG.warning("creator: brain timed out — using skeleton")
+ return None
+ except Exception as exc: # noqa: BLE001
+ _LOG.warning("creator: brain call failed (%s) — using skeleton", exc)
+ return None
+ return _extract_json(agg.text)
+
+
+# ----------------------------------------------------------------------
+# Prompt
+# ----------------------------------------------------------------------
+
+_SYSTEM_PROMPT = """You are Skill Creator. The user wants a new "skill" — a small \
+instruction card the assistant can trigger. Reply with ONE JSON object and nothing \
+else (no prose, no markdown fence). The object MUST have these keys:
+ name (short Title Case), description (one sentence), category, tags (array of \
+strings), triggers (array of {type:"voice"|"hotkey"|"schedule", pattern/combo/cron}), \
+requires_tools (array of tool names), risk_policy ({default_tier:"safe"|"monitor"|"ask"}), \
+body (Markdown instructions), questions (array), assumptions (array), test_prompts (array).
+Never put executable code with eval/exec/os.system/subprocess(shell=True) in the body."""
+
+
+def _build_prompt(inp: SkillCreatorInput, *, refine: bool) -> tuple[str, str]:
+ parts = [f"Intent: {inp.intent}"]
+ if inp.name_hint:
+ parts.append(f"Preferred name: {inp.name_hint}")
+ if inp.category:
+ parts.append(f"Category hint: {inp.category}")
+ if inp.trigger_hint:
+ parts.append(f"Trigger hint: {inp.trigger_hint}")
+ if inp.extra_context:
+ parts.append(f"Extra context: {inp.extra_context}")
+ if refine and inp.existing_draft:
+ parts.append(
+ "Revise this previous draft:\n"
+ + json.dumps(inp.existing_draft, ensure_ascii=False)
+ )
+ if refine and inp.feedback:
+ parts.append(f"User feedback to apply: {inp.feedback}")
+ parts.append("Return only the JSON object.")
+ return _SYSTEM_PROMPT, "\n".join(parts)
+
+
+__all__ = [
+ "SkillCreatorInput",
+ "SkillCreatorResult",
+ "SkillCreatorService",
+ "render_skill_md",
+ "validate_skill_md",
+]
diff --git a/jarvis/speech/pipeline.py b/jarvis/speech/pipeline.py
index 9c3695b0db..b9a40f26f4 100644
--- a/jarvis/speech/pipeline.py
+++ b/jarvis/speech/pipeline.py
@@ -320,9 +320,9 @@ _STT_UNAVAILABLE_PHRASE: dict[str, str] = {
# pre-empted brain_timeout, so the turn just hung up with no feedback). Short,
# bilingual, TTS-clean (``_speak`` does not scrub).
_BRAIN_TIMEOUT_PHRASE: dict[str, str] = {
- "de": "Das hat gerade zu lange gedauert. Sag es bitte noch einmal.",
- "en": "That took too long just now. Could you say it again?",
- "es": "Eso ha tardado demasiado ahora mismo. ¿Puedes repetirlo, por favor?",
+ "de": "Entschuldige, ich habe die Antwort nicht rechtzeitig fertigbekommen.",
+ "en": "Sorry, I couldn't finish the answer in time.",
+ "es": "Lo siento, no pude terminar la respuesta a tiempo.",
}
# AD-OE6 zero-silent-drop fallback for an ABANDONED incomplete utterance. When
@@ -1382,7 +1382,7 @@ class SpeechPipeline:
self._bus.subscribe(
OpenClawBackgroundCompleted, self._on_background_completed
)
- # Iron-Man-Style Spawn-Ansage: dynamisch aus action/target geformt.
+ # Spawn-Ansage: dynamisch aus action/target geformt.
self._bus.subscribe(OpenClawAnnouncement, self._on_spawn_announcement)
# Mute toggle from any trigger surface (mascot doubleClick,
# future hotkey/REST). The handler flips ``self._muted`` and
@@ -1418,6 +1418,9 @@ class SpeechPipeline:
# path so voice can declare ready early. Kept on the instance so tests
# (and a graceful shutdown) can await it.
self._warmup_background_task: asyncio.Task | None = None
+ # Audible boot-ready cue. It must never sit between ready=True and the
+ # wake loop; slow output devices can block playback for seconds.
+ self._warmup_ready_cue_task: asyncio.Task | None = None
# Deferred wake-non-critical loaders (VAD/STT/TTS) run off the
# wake-ready path so "Hey Jarvis" responds without waiting out the
# 7-24 s starved warm-up (see ``_warmup_phase_a``). Kept on the instance
@@ -1530,18 +1533,19 @@ class SpeechPipeline:
# transcription), so this does not block the caller.
if getattr(plan, "needs_local_whisper", False) and self._stt is None:
try:
+ from jarvis.plugins.stt import build_wake_whisper
+
stt_cfg = getattr(self._config, "stt", None)
- if stt_cfg is not None:
- lang = getattr(stt_cfg, "language", None)
- lang = None if lang in ("", "auto") else lang
- self._stt = FasterWhisperProvider(
- model=getattr(stt_cfg, "model", "distil-large-v3"),
- device=getattr(stt_cfg, "device", "cuda"),
- compute_type=getattr(stt_cfg, "compute_type", "int8_float16"),
- language=lang,
- )
- else:
- self._stt = FasterWhisperProvider()
+ lang = getattr(stt_cfg, "language", None)
+ lang = None if lang in ("", "auto", None) else lang
+ # Small CPU wake model (cfg.stt.wake_*), not the heavy utterance
+ # model — keeps a live wake-word switch fast (Blackwell CUDA load
+ # is ~71 s; base/cpu ~0.45 s, measured). Seed the prompt with the
+ # custom phrase so the small model transcribes the (proper-noun)
+ # wake name instead of a common word — forensic 2026-06-22.
+ self._stt = build_wake_whisper(
+ stt_cfg, language=lang, wake_phrase=getattr(plan, "phrase", None)
+ )
if self._probe_stt is None:
self._probe_stt = self._stt
log.info("Wake-Live-Switch: built local Whisper for custom phrase.")
@@ -3195,7 +3199,11 @@ class SpeechPipeline:
into ``_ack_pcm`` / ``_task_ack_pcm`` after a live TTS-provider switch
already cleared them. Guarded so shutdown never raises.
"""
- for attr in ("_warmup_background_task", "_deferred_warmup_task"):
+ for attr in (
+ "_warmup_background_task",
+ "_warmup_ready_cue_task",
+ "_deferred_warmup_task",
+ ):
task = getattr(self, attr, None)
if task is None:
continue
@@ -3223,10 +3231,14 @@ class SpeechPipeline:
await self._emit_boot_status(ready=True, detail="phase_a_done")
# Audible "ready" cue: tells the user exactly when listening starts
- # after a (cold) boot, closing the warm-up race where "Hey Jarvis"
- # said too early silently does nothing. Until the ACK phrase is cached
- # by Phase B, this chime is the wake feedback (see _on_wake / _ack_pcm).
- await self._play_ready_cue()
+ # after a (cold) boot. It is intentionally fire-and-forget: a slow or
+ # wedged output device must not sit between ready=True and the wake loop.
+ self._warmup_ready_cue_task = asyncio.create_task(
+ self._play_ready_cue(), name="warmup-ready-cue"
+ )
+ self._warmup_ready_cue_task.add_done_callback(
+ self._log_warmup_ready_cue_done
+ )
# --- Phase B: confirmation audio, off the critical path -----------
# Pre-rendering the ACK + ~20 task-ack phrases used to dominate warm-up
@@ -3238,6 +3250,14 @@ class SpeechPipeline:
)
log.info("Warm-up Phase A complete — confirmation audio rendering in background.")
+ def _log_warmup_ready_cue_done(self, task: asyncio.Task) -> None:
+ try:
+ task.result()
+ except asyncio.CancelledError:
+ pass
+ except Exception as exc: # noqa: BLE001
+ log.warning("Warm-up ready cue failed: %s", exc)
+
async def _warmup_phase_a(self) -> None:
"""Bring up ONLY the wake-critical listening path, then return.
@@ -3963,18 +3983,38 @@ class SpeechPipeline:
self._state = PipelineState.IDLE
# Supervisor zurueck auf IDLE — Orb verschwindet
await self._set_turn_state(TurnTakingState.IDLE)
- # Disconnect-Sound als hörbares Hangup-Signal
- try:
- await self._player.play_pcm(
- DISCONNECT_PCM, sample_rate=CHIME_SAMPLE_RATE
- )
- except Exception: # noqa: BLE001
- pass
+ # Disconnect-Sound als hörbares Hangup-Signal (earcon — gated
+ # by the global "Sound effects" switch).
+ await self._play_earcon(DISCONNECT_PCM)
# Cooldown setzen damit Speaker-Echo nicht sofort re-triggert
self._wake_lock_until = time.time() + self._post_hangup_lock_s
log.info("📵 AUFGELEGT — zurück zu IDLE (Wake-Lock %.1fs).",
self._post_hangup_lock_s)
+ def _earcons_enabled(self) -> bool:
+ """Whether synthesized UI earcons may play.
+
+ Read fresh from the shared config object so the Settings → Behavior
+ "Sound effects" master switch applies live (no restart). Defensive
+ default ``True`` — a missing field must never silence tones.
+ """
+ ui = getattr(self._config, "ui", None)
+ return bool(getattr(ui, "sound_effects", True))
+
+ async def _play_earcon(
+ self, pcm: bytes, *, sample_rate: int = CHIME_SAMPLE_RATE
+ ) -> None:
+ """Play a synthesized earcon unless the global "Sound effects" switch
+ is off. Never raises — an earcon failure must not crash a turn (AD-OE6).
+ Does NOT gate the spoken TTS voice, which is not an earcon.
+ """
+ if not self._earcons_enabled():
+ return
+ try:
+ await self._player.play_pcm(pcm, sample_rate=sample_rate)
+ except Exception as exc: # noqa: BLE001
+ log.debug("Earcon playback skipped (%s).", exc)
+
async def _play_ack(self, *, ptt: bool = False) -> None:
"""Chime + pre-rendertes 'Ja?' — Gesamtdauer ~400-600 ms.
@@ -3983,7 +4023,7 @@ class SpeechPipeline:
chime is immediate feedback that recording is live; speech is not.
"""
try:
- await self._player.play_pcm(CHIME_PCM, sample_rate=CHIME_SAMPLE_RATE)
+ await self._play_earcon(CHIME_PCM)
if ptt:
# Chime only, and NO dead-zone: the mic opens the instant this
# returns and the user is already holding the key + talking. The
@@ -5838,9 +5878,11 @@ class SpeechPipeline:
kind, lang, signal_mode, use_earcon,
)
- if use_earcon:
+ if use_earcon and self._earcons_enabled():
# Non-blocking earcon: reuses the same CHIME_PCM that the wake
# acknowledgment uses (imported at the top of this module).
+ # Gated by the global "Sound effects" switch (checked before the
+ # task is scheduled, so a muted run spawns no no-op coroutine).
# play_pcm is async but we fire-and-forget to avoid adding latency
# to the LISTENING re-entry. Failure is swallowed below.
try:
diff --git a/jarvis/speech/rolling_whisper_wake.py b/jarvis/speech/rolling_whisper_wake.py
index ebc9014680..1bc82dca07 100644
--- a/jarvis/speech/rolling_whisper_wake.py
+++ b/jarvis/speech/rolling_whisper_wake.py
@@ -22,6 +22,7 @@ Parameter:
"""
from __future__ import annotations
+import asyncio
import logging
import os
import re
@@ -63,6 +64,38 @@ def _save_wav(pcm_bytes: bytes, sample_rate: int, path: Path) -> None:
wf.writeframes(pcm_bytes)
+def _segment_no_speech_probs(transcript: Any) -> list[float]:
+ probs: list[float] = []
+ for seg in getattr(transcript, "segments", ()) or ():
+ if not isinstance(seg, dict):
+ continue
+ value = seg.get("no_speech_prob")
+ if value is None:
+ continue
+ try:
+ probs.append(float(value))
+ except (TypeError, ValueError):
+ continue
+ return probs
+
+
+def _reliable_wake_transcript(
+ transcript: Any,
+ *,
+ min_confidence: float,
+ max_no_speech_prob: float,
+) -> bool:
+ try:
+ confidence = float(getattr(transcript, "confidence", 0.0) or 0.0)
+ except (TypeError, ValueError):
+ confidence = 0.0
+ if confidence < min_confidence:
+ return False
+ return not any(
+ prob > max_no_speech_prob for prob in _segment_no_speech_probs(transcript)
+ )
+
+
class RollingWhisperWake:
"""Rolling-Window Wake-Detection per Whisper-Transkription."""
@@ -95,6 +128,19 @@ class RollingWhisperWake:
target_peak_dbfs: float = -3.0,
max_gain_db: float = 40.0,
language: str = "de",
+ # faster-whisper's exp(avg_logprob) score is harsh on 1-2 word wake
+ # chunks: live, cleanly-heard custom-name wakes land at ~0.28-0.52 (real
+ # samples 2026-06-23: "Ruben." 0.318, "Hey Ruhm" 0.365, "Hey Ruben" 0.52).
+ # A 0.45 floor rejected EVERY genuine wake (142 rejects / 0 accepts in one
+ # evening). That floor was built to suppress *prompt-bias* hallucinations,
+ # but the bias is now disabled (build_wake_whisper passes initial_prompt
+ # =None), so the pattern itself is the hallucination guard — a random
+ # mis-hear does not match the specific wake phrase — and the
+ # ``max_no_speech_prob`` gate below still rejects silence/noise. Keep only
+ # a low sanity floor that still drops a near-zero-confidence transcript
+ # (regression: a 0.2-confidence match must stay rejected).
+ min_wake_confidence: float = 0.28,
+ max_no_speech_prob: float = 0.6,
) -> None:
self._stt = stt
self._pattern = pattern
@@ -112,6 +158,8 @@ class RollingWhisperWake:
# 1.8s-Chunks kippt oft fälschlich auf EN (User spricht DE, Whisper
# halluziniert "Thank you"). None = auto (nicht empfohlen).
self._language: str | None = language
+ self._min_wake_confidence = min_wake_confidence
+ self._max_no_speech_prob = max_no_speech_prob
# Statistik für Heartbeat
self._chunks_seen = 0
self._total_bytes = 0
@@ -122,121 +170,172 @@ class RollingWhisperWake:
async def detect(
self, chunks: AsyncIterator[AudioChunk]
) -> AsyncIterator[str]:
- """Konsumiert Audio-Chunks, yielded matched-Keyword bei Hit."""
- # Ring-Buffer: float32 samples im [-1, 1] Bereich
+ """Konsumiert Audio-Chunks, yielded matched-Keyword bei Hit.
+
+ The chunk consumer and the (slow, blocking) Whisper transcription run as
+ TWO concurrent tasks. The consumer keeps the rolling ring-buffer pinned
+ to the freshest ``window_s`` of audio; a separate poll loop snapshots the
+ current window every ``poll_interval_s`` and transcribes THAT.
+
+ Why two tasks (forensic 2026-06-22): the old single loop did
+ ``await transcribe_pcm`` *inside* the consume loop, so while a CPU "base"
+ transcription ran for ~0.5-1 s no new chunks were pulled. They backed up
+ in the upstream fanout queue (observed ``wsp_q=100``) and every following
+ transcription ran on ~3 s-stale audio — the "riesige Verzoegerung". With
+ the consumer decoupled, the buffer is always live and the transcription
+ sees the newest window, never a backlog.
+ """
+ # Ring-Buffer: float32 samples im [-1, 1] Bereich. Held in a 1-element
+ # list so the consumer closure mutates it in place without ``nonlocal``.
buffer: deque[np.ndarray] = deque()
- buffer_len = 0
- last_poll_t = time.time()
- last_trigger_t = 0.0
+ buf_len = [0]
+ stopped = asyncio.Event()
- async for chunk in chunks:
- samples = pcm_bytes_to_np(chunk.pcm)
- buffer.append(samples)
- buffer_len += len(samples)
-
- # Heartbeat-Statistik updaten (live RMS pro Chunk)
- self._chunks_seen += 1
- self._total_bytes += len(chunk.pcm)
- chunk_rms = float(np.sqrt(np.mean(samples * samples) + 1e-12))
- if chunk_rms > self._max_rms:
- self._max_rms = chunk_rms
-
- # Heartbeat regelmäßig ausgeben — auch wenn Whisper nichts matched
- now_hb = time.time()
- if now_hb - self._last_heartbeat_t >= self._heartbeat_interval_s:
- dbfs = 20.0 * np.log10(max(self._max_rms, 1e-12))
- log.info(
- "💓 wake-heartbeat: chunks=%d bytes=%dKB max-rms=%.4f (%.1f dBFS) last-transcript=%r",
- self._chunks_seen,
- self._total_bytes // 1024,
- self._max_rms,
- dbfs,
- self._last_transcript[:80],
- )
- self._chunks_seen = 0
- self._total_bytes = 0
- self._max_rms = 0.0
- self._last_heartbeat_t = now_hb
-
- # Ältere Samples rauswerfen wenn Buffer zu lang
- while buffer_len > self._window_samples:
- oldest = buffer[0]
- overflow = buffer_len - self._window_samples
- if len(oldest) <= overflow:
- buffer.popleft()
- buffer_len -= len(oldest)
- else:
- buffer[0] = oldest[overflow:]
- buffer_len -= overflow
-
- # Poll-Intervall abwarten
- now = time.time()
- if now - last_poll_t < self._poll_interval_s:
- continue
- last_poll_t = now
-
- # Cooldown nach letztem Trigger
- if now - last_trigger_t < self._cooldown_s:
- continue
-
- # Noch nicht genug Audio im Buffer
- if buffer_len < self._sample_rate: # mind. 1 Sek
- continue
-
- # Concatenate + Lautstärke-Check (RMS) — kein Whisper-Call bei Stille
- audio_np = np.concatenate(list(buffer))
- rms = float(np.sqrt(np.mean(audio_np * audio_np) + 1e-12))
- if rms < self._min_rms:
- continue
-
- # Peak-Gate: bei reinem Rauschen gar nicht erst Whisper bemühen
- peak = float(np.max(np.abs(audio_np)))
- if peak < self._min_peak:
- # Kein Whisper-Call — zu leise für Sprache
- continue
-
- # Whisper-Call mit Peak-Normalization (dynamischer Gain)
+ async def _consume() -> None:
+ """Drain audio into the rolling window — fast, never blocks on STT."""
try:
- if peak > 1e-6:
- # Gain berechnen um Ziel-Peak zu erreichen, aber cappen
- gain = min(self._target_peak / peak, self._max_gain_factor)
- else:
- gain = 1.0
- boosted = audio_np * gain
- applied_db = 20.0 * np.log10(max(gain, 1e-12))
- pcm_bytes = (
- np.clip(boosted, -1.0, 1.0) * 32767.0
- ).astype(np.int16).tobytes()
- log.debug("whisper-gain applied=%.1f dB (peak-in=%.3f)", applied_db, peak)
- transcript = await self._stt.transcribe_pcm(
- pcm_bytes, language=self._language
- )
- except Exception as exc: # noqa: BLE001
- log.warning("Rolling-Whisper Transkription fehlgeschlagen: %s", exc)
- continue
-
- text = transcript.text.strip()
- self._last_transcript = text
-
- # Watchdog: WAV speichern damit User/ich die Aufnahme nachprüfen können
- if self._save_debug_wavs:
+ async for chunk in chunks:
+ samples = pcm_bytes_to_np(chunk.pcm)
+ buffer.append(samples)
+ buf_len[0] += len(samples)
+
+ # Heartbeat-Statistik updaten (live RMS pro Chunk)
+ self._chunks_seen += 1
+ self._total_bytes += len(chunk.pcm)
+ chunk_rms = float(np.sqrt(np.mean(samples * samples) + 1e-12))
+ if chunk_rms > self._max_rms:
+ self._max_rms = chunk_rms
+
+ # Heartbeat regelmäßig ausgeben — auch wenn Whisper nichts matched
+ now_hb = time.time()
+ if now_hb - self._last_heartbeat_t >= self._heartbeat_interval_s:
+ dbfs = 20.0 * np.log10(max(self._max_rms, 1e-12))
+ log.info(
+ "💓 wake-heartbeat: chunks=%d bytes=%dKB "
+ "max-rms=%.4f (%.1f dBFS) last-transcript=%r",
+ self._chunks_seen,
+ self._total_bytes // 1024,
+ self._max_rms,
+ dbfs,
+ self._last_transcript[:80],
+ )
+ self._chunks_seen = 0
+ self._total_bytes = 0
+ self._max_rms = 0.0
+ self._last_heartbeat_t = now_hb
+
+ # Ältere Samples rauswerfen wenn Buffer zu lang
+ while buf_len[0] > self._window_samples:
+ oldest = buffer[0]
+ overflow = buf_len[0] - self._window_samples
+ if len(oldest) <= overflow:
+ buffer.popleft()
+ buf_len[0] -= len(oldest)
+ else:
+ buffer[0] = oldest[overflow:]
+ buf_len[0] -= overflow
+ finally:
+ stopped.set()
+
+ consumer = asyncio.create_task(_consume(), name="rolling-whisper-consume")
+ last_trigger_t = 0.0
+ try:
+ while not stopped.is_set():
+ # Wall-clock poll cadence — independent of the chunk arrival rate
+ # and, crucially, of how long the previous transcription took.
+ await asyncio.sleep(self._poll_interval_s)
+
+ now = time.time()
+ # Cooldown nach letztem Trigger
+ if now - last_trigger_t < self._cooldown_s:
+ continue
+ # Noch nicht genug Audio im Buffer
+ if buf_len[0] < self._sample_rate: # mind. 1 Sek
+ continue
+
+ # Snapshot the freshest window. ``list(buffer)`` + concat run
+ # synchronously (no await), so the consumer cannot interleave a
+ # mutation mid-snapshot in this single-threaded loop.
+ if not buffer:
+ continue
+ audio_np = np.concatenate(list(buffer))
+ if len(audio_np) < self._sample_rate:
+ continue
+
+ # Lautstärke-Check (RMS) — kein Whisper-Call bei Stille
+ rms = float(np.sqrt(np.mean(audio_np * audio_np) + 1e-12))
+ if rms < self._min_rms:
+ continue
+
+ # Peak-Gate: bei reinem Rauschen gar nicht erst Whisper bemühen
+ peak = float(np.max(np.abs(audio_np)))
+ if peak < self._min_peak:
+ # Kein Whisper-Call — zu leise für Sprache
+ continue
+
+ # Whisper-Call mit Peak-Normalization (dynamischer Gain)
try:
- pcm_bytes_for_wav = (
- np.clip(audio_np, -1.0, 1.0) * 32767.0
+ if peak > 1e-6:
+ # Gain berechnen um Ziel-Peak zu erreichen, aber cappen
+ gain = min(self._target_peak / peak, self._max_gain_factor)
+ else:
+ gain = 1.0
+ boosted = audio_np * gain
+ applied_db = 20.0 * np.log10(max(gain, 1e-12))
+ pcm_bytes = (
+ np.clip(boosted, -1.0, 1.0) * 32767.0
).astype(np.int16).tobytes()
- ts = time.strftime("%H%M%S")
- safe_text = re.sub(r"[^\w\-]+", "_", text[:40]) or "empty"
- wav_path = DEBUG_DIR / f"wake_{ts}_rms{rms:.3f}_{safe_text}.wav"
- _save_wav(pcm_bytes_for_wav, self._sample_rate, wav_path)
+ log.debug("whisper-gain applied=%.1f dB (peak-in=%.3f)", applied_db, peak)
+ transcript = await self._stt.transcribe_pcm(
+ pcm_bytes, language=self._language
+ )
except Exception as exc: # noqa: BLE001
- log.warning("WAV-Save fehlgeschlagen: %s", exc)
+ log.warning("Rolling-Whisper Transkription fehlgeschlagen: %s", exc)
+ continue
+
+ text = transcript.text.strip()
+ self._last_transcript = text
+
+ # Watchdog: WAV speichern damit User/ich die Aufnahme nachprüfen können
+ if self._save_debug_wavs:
+ try:
+ pcm_bytes_for_wav = (
+ np.clip(audio_np, -1.0, 1.0) * 32767.0
+ ).astype(np.int16).tobytes()
+ ts = time.strftime("%H%M%S")
+ safe_text = re.sub(r"[^\w\-]+", "_", text[:40]) or "empty"
+ wav_path = DEBUG_DIR / f"wake_{ts}_rms{rms:.3f}_{safe_text}.wav"
+ _save_wav(pcm_bytes_for_wav, self._sample_rate, wav_path)
+ except Exception as exc: # noqa: BLE001
+ log.warning("WAV-Save fehlgeschlagen: %s", exc)
- if not text:
- log.info("rolling-whisper: rms=%.4f text=<leer>", rms)
- continue
+ if not text:
+ log.info("rolling-whisper: rms=%.4f text=<leer>", rms)
+ continue
- log.info("rolling-whisper: rms=%.4f text=%r", rms, text)
- m = self._pattern.search(text)
- if m:
- last_trigger_t = now
- yield m.group(0)
+ if not _reliable_wake_transcript(
+ transcript,
+ min_confidence=self._min_wake_confidence,
+ max_no_speech_prob=self._max_no_speech_prob,
+ ):
+ log.info(
+ "rolling-whisper: rejected unreliable wake transcript "
+ "rms=%.4f confidence=%.3f no_speech=%r text=%r",
+ rms,
+ float(getattr(transcript, "confidence", 0.0) or 0.0),
+ _segment_no_speech_probs(transcript),
+ text,
+ )
+ continue
+
+ log.info("rolling-whisper: rms=%.4f text=%r", rms, text)
+ m = self._pattern.search(text)
+ if m:
+ last_trigger_t = now
+ yield m.group(0)
+ finally:
+ consumer.cancel()
+ try:
+ await consumer
+ except (asyncio.CancelledError, Exception): # noqa: BLE001, S110
+ pass
diff --git a/jarvis/speech/wake_constants.py b/jarvis/speech/wake_constants.py
index efd6fdb3c0..51638f0a5c 100644
--- a/jarvis/speech/wake_constants.py
+++ b/jarvis/speech/wake_constants.py
@@ -23,6 +23,7 @@ from __future__ import annotations
import importlib.util
import re
+import unicodedata
from pathlib import Path
# ---------------------------------------------------------------------------
@@ -45,8 +46,9 @@ JARVIS_WAKE_PATTERN = re.compile(
re.IGNORECASE,
)
-# Common wake prefixes stripped from the *core* of a custom phrase so that a
-# phrase like "Hey Athena" also fires on a bare "Athena" in the transcript.
+# Common wake prefixes stripped when deriving the phrase *core* for model
+# lookup and canonical keyword names. The matcher may still keep an explicit
+# prefix when the configured phrase includes one.
WAKE_PREFIXES: frozenset[str] = frozenset(
{"hey", "hi", "ok", "okay", "hello", "hallo", "yo", "hej"}
)
@@ -72,6 +74,14 @@ _NON_WAKE_OWW_MODELS: frozenset[str] = frozenset({"timer", "weather"})
INSTANT_WAKE_PHRASES: tuple[str, ...] = ()
_NORMALISE_RE = re.compile(r"[^0-9a-zäöüß]+")
+_MATCH_NORMALISE_RE = re.compile(r"[^0-9a-z]+")
+
+
+def _strip_diacritics(text: str) -> str:
+ """Return an ASCII-ish form for STT matching, not display."""
+ decomposed = unicodedata.normalize("NFKD", text or "")
+ stripped = "".join(ch for ch in decomposed if not unicodedata.combining(ch))
+ return stripped.replace("ß", "ss")
def normalize_phrase(phrase: str) -> list[str]:
@@ -83,6 +93,13 @@ def normalize_phrase(phrase: str) -> list[str]:
return cleaned.split() if cleaned else []
+def normalize_phrase_for_match(phrase: str) -> list[str]:
+ """Tokenise for fuzzy wake matching with accents folded away."""
+ folded = _strip_diacritics(phrase).lower()
+ cleaned = _MATCH_NORMALISE_RE.sub(" ", folded).strip()
+ return cleaned.split() if cleaned else []
+
+
def phrase_core(phrase: str) -> list[str]:
"""Return the phrase tokens with leading wake-prefixes removed.
@@ -97,6 +114,15 @@ def phrase_core(phrase: str) -> list[str]:
return core or tokens
+def phrase_core_for_match(phrase: str) -> list[str]:
+ """Return wake-prefix-stripped tokens for accent-insensitive matching."""
+ tokens = normalize_phrase_for_match(phrase)
+ core = list(tokens)
+ while core and core[0] in WAKE_PREFIXES:
+ core.pop(0)
+ return core or tokens
+
+
def match_known_oww_model(phrase: str) -> str | None:
"""Map a phrase onto a pretrained openWakeWord model name, or ``None``.
@@ -166,7 +192,9 @@ __all__ = [
"KNOWN_OWW_MODELS",
"INSTANT_WAKE_PHRASES",
"normalize_phrase",
+ "normalize_phrase_for_match",
"phrase_core",
+ "phrase_core_for_match",
"match_known_oww_model",
"resolve_oww_model_path",
]
diff --git a/jarvis/speech/wake_phrase.py b/jarvis/speech/wake_phrase.py
index e3c8a83a01..6d9ada34c2 100644
--- a/jarvis/speech/wake_phrase.py
+++ b/jarvis/speech/wake_phrase.py
@@ -33,8 +33,9 @@ from jarvis.speech.wake_constants import (
JARVIS_WAKE_PATTERN,
WAKE_ENGINES,
match_known_oww_model,
- normalize_phrase,
+ normalize_phrase_for_match,
phrase_core,
+ phrase_core_for_match,
resolve_oww_model_path,
)
@@ -82,7 +83,9 @@ class WakeMatcher:
- jarvis-default: wraps the canonical :data:`JARVIS_WAKE_PATTERN`.
- arbitrary phrase: fuzzy token-window match against a normalised
- transcript using ``difflib.SequenceMatcher``.
+ transcript using ``difflib.SequenceMatcher``. A phrase that explicitly
+ starts with a wake prefix ("Hey Athena") must match that prefix too, so a
+ bare core word does not re-trigger the listener.
"""
def __init__(
@@ -108,7 +111,7 @@ class WakeMatcher:
return None
if self._pattern is not None:
return self._pattern.search(text)
- tokens = normalize_phrase(text)
+ tokens = normalize_phrase_for_match(text)
n = len(self._core)
if n == 0 or len(tokens) < n:
return None
@@ -126,12 +129,16 @@ def compile_wake_matcher(phrase: str, *, fuzzy_ratio: float = 0.8) -> WakeMatche
"""Build a :class:`WakeMatcher` for ``phrase``.
The default "Hey Jarvis" (and any jarvis-only phrase) is matched by the
- strict legacy pattern; everything else is fuzzy-matched on its core tokens.
+ strict legacy pattern. Other phrases are fuzzy-matched on their core tokens
+ unless the user explicitly included a wake prefix ("Hey", "Hallo", "Ok",
+ ...), in which case the prefix is part of the match contract.
"""
- core = phrase_core(phrase)
+ tokens = normalize_phrase_for_match(phrase)
+ core = phrase_core_for_match(phrase)
if core == ["jarvis"]:
return WakeMatcher(pattern=JARVIS_WAKE_PATTERN, is_jarvis_default=True)
- return WakeMatcher(core_tokens=core, fuzzy_ratio=fuzzy_ratio)
+ match_tokens = tokens if tokens and core and len(core) < len(tokens) else core
+ return WakeMatcher(core_tokens=match_tokens, fuzzy_ratio=fuzzy_ratio)
def _canonical_keyword(phrase: str) -> str:
diff --git a/jarvis/terminal/backend.py b/jarvis/terminal/backend.py
index 7fe06efed9..22d56cd521 100644
--- a/jarvis/terminal/backend.py
+++ b/jarvis/terminal/backend.py
@@ -29,6 +29,7 @@ installed.
from __future__ import annotations
+from collections.abc import Mapping
from typing import Protocol, runtime_checkable
from jarvis.platform import detect_platform
@@ -78,8 +79,14 @@ class PtyBackend(Protocol):
cwd: str | None,
cols: int,
rows: int,
+ env: Mapping[str, str] | None = None,
) -> PtyHandle:
- """Spawn a PTY running ``argv`` and return a normalized handle."""
+ """Spawn a PTY running ``argv`` and return a normalized handle.
+
+ ``env`` (when given) replaces the child environment; ``None`` inherits
+ the parent's (the integrated-terminal default). Both pywinpty and
+ ptyprocess accept ``env=`` directly.
+ """
# ----------------------------------------------------------------------
@@ -133,6 +140,7 @@ class WinptyBackend:
cwd: str | None,
cols: int,
rows: int,
+ env: Mapping[str, str] | None = None,
) -> PtyHandle:
try:
from winpty import PtyProcess # type: ignore[import-not-found]
@@ -145,6 +153,7 @@ class WinptyBackend:
proc = PtyProcess.spawn(
list(argv),
cwd=cwd,
+ env=dict(env) if env is not None else None,
dimensions=(rows, cols),
)
return _WinptyHandle(proc)
@@ -202,6 +211,7 @@ class UnixPtyBackend:
cwd: str | None,
cols: int,
rows: int,
+ env: Mapping[str, str] | None = None,
) -> PtyHandle:
try:
import ptyprocess # type: ignore[import-not-found]
@@ -215,6 +225,7 @@ class UnixPtyBackend:
proc = ptyprocess.PtyProcess.spawn(
list(argv),
cwd=cwd,
+ env=dict(env) if env is not None else None,
dimensions=(rows, cols),
)
return _UnixPtyHandle(proc)
@@ -239,6 +250,7 @@ class NullPtyBackend:
cwd: str | None,
cols: int,
rows: int,
+ env: Mapping[str, str] | None = None,
) -> PtyHandle:
raise RuntimeError(
"No pseudo-terminal backend available on this host — the integrated "
diff --git a/jarvis/ui/desktop_app.py b/jarvis/ui/desktop_app.py
index d90a27d110..8e45485a25 100644
--- a/jarvis/ui/desktop_app.py
+++ b/jarvis/ui/desktop_app.py
@@ -570,8 +570,8 @@ class DesktopApp:
# Fire the heavy OpenWakeWord/onnxruntime import NOW, in a daemon thread,
# BEFORE the WebServer + brain build + subsystem boot storm grab the
# Python import lock. The wake-critical Phase-A warm-up gates
- # VoiceBootStatus(ready=True) — the UI's "VOICE STARTING…" → listening
- # flip — on the OWW model load, whose dominant cost is this ~3 s import
+ # VoiceBootStatus(ready=True) — the UI's "VOICE STARTING…" → listening
+ # flip — on the OWW model load, whose dominant cost is this ~3 s import
# (not the ~0.1 s parse). Inside the serve-first boot storm it otherwise
# starves on the import lock to 7-24 s. Prefetching it here means Phase A
# finds openwakeword already in sys.modules. No-op on a headless VPS /
@@ -895,6 +895,36 @@ class DesktopApp:
await supervisor.set_state("IDLE")
server.bus.subscribe(MessageSent, _on_user_message)
+
+ # Drag-drop onto the floating overlay (bar/mascot) → a proactive brain
+ # turn, reusing the SAME intake as the web dock (jarvis/brain/
+ # drop_context.ingest_drop). The overlay (Tk thread) calls dispatch_drop;
+ # we marshal here onto the long-running backend loop and run the intake.
+ # A no-op until tkdnd is present (NullDropTarget); brain may be None
+ # (build error) → ingest_drop degrades to a text-only turn.
+ try:
+ from jarvis.brain.drop_context import ingest_drop, items_from_paths
+ from jarvis.overlay.drop_bridge import set_drop_handler
+
+ def _on_overlay_drop(paths: list[str], text: str) -> None:
+ items = items_from_paths(paths) if paths else []
+ dragged = (text or "").strip() or None
+ if not items and dragged is None:
+ return
+ coro = ingest_drop(
+ bus=server.bus,
+ brain=brain,
+ thread_id="default",
+ items=items,
+ dragged_text=dragged,
+ )
+ asyncio.run_coroutine_threadsafe(coro, loop)
+
+ set_drop_handler(_on_overlay_drop)
+ except Exception as exc: # noqa: BLE001 — drop wiring must never block boot.
+ from loguru import logger as _dlog
+ _dlog.opt(exception=exc).debug("overlay drop handler wiring skipped")
+
# Overlay right-click (bar OR mascot) → raise the main desktop window.
# OrbBusBridge publishes ShowWindowRequested from the Tk thread; the
# handler runs on the asyncio loop and pywebview.show() is thread-safe.
@@ -1200,13 +1230,18 @@ class DesktopApp:
logger.opt(exception=exc).warning("Virtual mouse overlay not startable")
self._virtual_cursor = None
- def _build_overlay_surface(self, style: str):
+ def _build_overlay_surface(self, style: str, *, boot: bool = False):
"""Construct (and start) the overlay surface for a display style.
Returns a ``NullOverlay`` for ``"none"`` (no Tk window, no-op surface),
a started ``WhisperBarOverlay`` for ``"whisper_bar"``, or a started
mascot ``OrbOverlay`` for anything else. Shared by boot wiring and the
live ``swap_overlay`` path so the two never drift.
+
+ ``boot=True`` (only the first-boot call) builds the persistent bar
+ WITHDRAWN; the boot wiring then schedules its reveal on
+ ``VoiceBootStatus(ready=True)``. A non-boot caller must leave ``boot``
+ False so the bar maps immediately (it has no reveal task to wait on).
"""
if style == "none":
from jarvis.ui.whisperbar import NullOverlay
@@ -1215,9 +1250,15 @@ class DesktopApp:
if style == "whisper_bar":
from jarvis.ui.whisperbar import WhisperBarOverlay
+ # start_hidden only at boot: a persistent bar must NOT map its window
+ # before the speech pipeline can hear the user — the OrbBusBridge
+ # reveals it on VoiceBootStatus(ready=True). A runtime rebuild
+ # (boot=False) shows immediately; the non-persistent bar starts
+ # hidden regardless (it pops on a session).
surface = WhisperBarOverlay(
persistent=self.cfg.ui.bar_persistent,
accent=self.cfg.ui.bar_accent,
+ start_hidden=boot,
)
else: # "mascot" (and any legacy style value)
from ui.orb.overlay import OrbOverlay
@@ -1416,8 +1457,8 @@ class DesktopApp:
target=_quit_soon, name="jarvis-restart-quit", daemon=True
).start()
logger.info(
- "Self-restart scheduled (relauncher spawned; quitting in ~0.8 s, "
- "hard-exit fallback at ~10 s)."
+ "Self-restart scheduled (relauncher spawned; quitting in ~0.3 s, "
+ "hard-exit fallback at ~2 s)."
)
return True
@@ -1473,8 +1514,9 @@ class DesktopApp:
from ui.orb.bus_bridge import OrbBusBridge
# NullOverlay for "none" still gets a bridge, so a live switch to
- # bar/mascot works without a restart.
- surface = self._build_overlay_surface(orb_style)
+ # bar/mascot works without a restart. boot=True builds the
+ # persistent bar withdrawn — revealed below on voice-ready.
+ surface = self._build_overlay_surface(orb_style, boot=True)
hide_on_idle = (
(not self.cfg.ui.bar_persistent)
if orb_style == "whisper_bar"
@@ -1482,6 +1524,15 @@ class DesktopApp:
)
bridge = OrbBusBridge(bus=bus, orb=surface, hide_on_idle=hide_on_idle)
bridge.attach()
+ # Reveal the (start-hidden) persistent bar only once voice is
+ # ready to listen — gated on VoiceBootStatus(ready=True), with a
+ # bounded fallback so a voice-offline host still gets its bar.
+ # loop.create_task works before run_forever (it just schedules);
+ # the boot surface starts withdrawn, so this never flickers.
+ loop.create_task(
+ bridge.reveal_bar_when_voice_ready(),
+ name="overlay-boot-reveal",
+ )
self._orb = surface
self._bridge = bridge
# Cache the boot surface so a later swap back to it reuses the
@@ -1633,11 +1684,23 @@ class DesktopApp:
# docs/local-wakeword/{RESEARCH-AND-DESIGN,CUSTOM-WAKE-WORD-DESIGN}.md.
stt = None
if self.cfg.trigger.heavy_local_whisper or wake_plan.needs_local_whisper:
- stt = FasterWhisperProvider(
- model=self.cfg.stt.model,
- device=self.cfg.stt.device,
- compute_type=self.cfg.stt.compute_type,
- language=stt_language,
+ # The local wake-match / live-preview Whisper — a SMALL model on
+ # CPU (cfg.stt.wake_*), not the heavy utterance model on the GPU.
+ # On a Blackwell GPU the CUDA model-load JIT cost dominates boot
+ # (~71 s vs ~0.45 s for base/cpu, measured); wake matching is
+ # latency-tolerant and does not need the big model.
+ from jarvis.plugins.stt import build_wake_whisper
+
+ # Seed the wake Whisper's prompt with the custom phrase ONLY on
+ # the stt_match path (a custom name with no OWW model). The
+ # heavy_local_whisper backstop for "Hey Jarvis" keeps its OWW
+ # model as the discriminator and passes no prompt, so the hot-
+ # path prompt-hallucination caveat never applies to it.
+ wake_phrase = (
+ wake_plan.phrase if wake_plan.needs_local_whisper else None
+ )
+ stt = build_wake_whisper(
+ self.cfg.stt, language=stt_language, wake_phrase=wake_phrase
)
tts = build_tts_from_config(self.cfg.tts)
# SpeechPipeline.brain_callback braucht Callable[[str], Awaitable[str]].
diff --git a/jarvis/ui/web/drop_routes.py b/jarvis/ui/web/drop_routes.py
new file mode 100644
index 0000000000..43124348f8
--- /dev/null
+++ b/jarvis/ui/web/drop_routes.py
@@ -0,0 +1,75 @@
+"""``POST /api/chat/drop`` — drag-and-drop intake for the Jarvis dock / overlay.
+
+A dropped file (image, document, code, …) or dragged text is posted here as
+multipart; the route normalises it to :class:`DroppedItem`s and hands it to
+``ingest_drop``, which composes one proactive ``MessageSent`` brain turn (spoken
+on the voice build, shown in chat, landed in ``_history``). Images ride the
+multimodal path so the brain can see a dropped picture.
+
+Mirrors the avatar-upload pattern (multipart + size cap). The reply flows back
+over the normal WS event stream — this route only kicks off the turn.
+"""
+from __future__ import annotations
+
+from typing import Any
+
+from fastapi import APIRouter, File, Form, HTTPException, Request, UploadFile
+
+from jarvis.brain.drop_context import DroppedItem, ingest_drop
+
+router = APIRouter(tags=["chat"])
+
+#: Hard total cap across all dropped files — protects RAM, the token budget and
+#: the WS broadcast circuit-breaker. A single drop is interactive, not a bulk
+#: upload, so 25 MB is generous.
+_MAX_DROP_BYTES = 25 * 1024 * 1024
+
+
[email protected]("/api/chat/drop")
+async def drop_into_context(
+ request: Request,
+ files: list[UploadFile] | None = File(default=None), # noqa: B008
+ thread_id: str = Form(default="default"), # noqa: B008
+ text: str | None = Form(default=None), # noqa: B008
+ surface: str | None = Form(default=None), # noqa: B008
+) -> dict[str, Any]:
+ """Ingest dropped content as a proactive brain turn.
+
+ Returns ``{"dispatched": bool}`` — ``False`` when the drop carried nothing
+ usable (no turn dispatched). 413 when the total payload exceeds the cap.
+ """
+ brain = getattr(request.app.state, "brain", None)
+ if brain is None:
+ raise HTTPException(
+ status_code=503, detail="Brain unavailable to hold dropped context."
+ )
+
+ items: list[DroppedItem] = []
+ total = 0
+ for upload in files or []:
+ data = await upload.read()
+ total += len(data)
+ if total > _MAX_DROP_BYTES:
+ raise HTTPException(
+ status_code=413,
+ detail=f"Dropped content too large (max {_MAX_DROP_BYTES // (1024 * 1024)} MB).",
+ )
+ if not data:
+ continue
+ items.append(
+ DroppedItem(
+ name=upload.filename or "file",
+ mime=upload.content_type or "application/octet-stream",
+ data=data,
+ )
+ )
+
+ captured = await ingest_drop(
+ brain=brain,
+ thread_id=thread_id or "default",
+ items=items,
+ dragged_text=text,
+ )
+ # ``dispatched`` kept as the response key for frontend compatibility; it now
+ # means "captured into context" (a drop never dispatches a turn on its own).
+ return {"dispatched": captured}
diff --git a/jarvis/ui/web/frontend/src/components/BrainModelSelector.test.tsx b/jarvis/ui/web/frontend/src/components/BrainModelSelector.test.tsx
new file mode 100644
index 0000000000..8939e4cb1a
--- /dev/null
+++ b/jarvis/ui/web/frontend/src/components/BrainModelSelector.test.tsx
@@ -0,0 +1,158 @@
+import { cleanup, fireEvent, render, screen, waitFor } from "@testing-library/react";
+import { afterEach, describe, expect, it, vi } from "vitest";
+
+// Identity translator so rendered text equals the i18n key.
+vi.mock("@/i18n", () => ({
+ useT: () => (key: string) => key,
+}));
+
+vi.mock("@/store/events", () => ({
+ useEventStore: (selector: (s: { pushToast: () => void }) => unknown) =>
+ selector({ pushToast: vi.fn() }),
+}));
+
+import { BrainModelSelector } from "./BrainModelSelector";
+
+const MODELS = {
+ provider: "gemini",
+ current_model: "gemini-3-flash-preview",
+ models: [
+ { id: "gemini-3.1-pro-preview", label: "Gemini 3.1 Pro" },
+ { id: "gemini-3-flash-preview", label: "Gemini 3 Flash" },
+ ],
+ source: "live",
+ fetched_at: 1,
+};
+
+function mockFetch(saveBody?: Record<string, unknown>) {
+ return vi.fn().mockImplementation(async (url: string, init?: RequestInit) => {
+ const u = String(url);
+ if (u.includes("/models")) return { ok: true, json: async () => MODELS };
+ if (init?.method === "PUT") {
+ return {
+ ok: true,
+ json: async () =>
+ saveBody ?? {
+ ok: true,
+ provider: "gemini",
+ model: "x",
+ persisted: true,
+ applied_live: true,
+ restart_required: false,
+ probe: { status: "ok", detail: "", latency_ms: 30, integration_ok: true },
+ },
+ };
+ }
+ return { ok: true, json: async () => ({}) };
+ });
+}
+
+async function openDropdown() {
+ const trigger = (await screen.findByLabelText(
+ "apikeys_model.model_label",
+ )) as HTMLElement;
+ fireEvent.click(trigger);
+}
+
+afterEach(() => {
+ cleanup();
+ vi.restoreAllMocks();
+});
+
+describe("BrainModelSelector", () => {
+ it("opens a dropdown listing the provider's models", async () => {
+ vi.stubGlobal("fetch", mockFetch());
+ render(<BrainModelSelector providerId="gemini" currentModel="gemini-3-flash-preview" />);
+ await openDropdown();
+ expect(await screen.findByText("gemini-3.1-pro-preview")).toBeTruthy();
+ expect(screen.getByText("gemini-3-flash-preview")).toBeTruthy();
+ });
+
+ it("filters the list via the search box", async () => {
+ vi.stubGlobal("fetch", mockFetch());
+ render(<BrainModelSelector providerId="gemini" currentModel="" />);
+ await openDropdown();
+ const search = (await screen.findByLabelText(
+ "apikeys_model.search_placeholder",
+ )) as HTMLInputElement;
+ fireEvent.change(search, { target: { value: "pro" } });
+ expect(await screen.findByText("gemini-3.1-pro-preview")).toBeTruthy();
+ expect(screen.queryByText("gemini-3-flash-preview")).toBeNull();
+ });
+
+ it("saves a model picked from the list via PUT", async () => {
+ const fetchMock = mockFetch();
+ vi.stubGlobal("fetch", fetchMock);
+ render(<BrainModelSelector providerId="gemini" currentModel="" />);
+ await openDropdown();
+ fireEvent.click(await screen.findByText("gemini-3.1-pro-preview"));
+ await waitFor(() => {
+ const put = fetchMock.mock.calls.find(
+ (c) => (c[1] as RequestInit | undefined)?.method === "PUT",
+ );
+ expect(put).toBeDefined();
+ expect(String(put![0])).toContain("/api/providers/gemini/model");
+ expect(JSON.parse((put![1] as RequestInit).body as string).model).toBe(
+ "gemini-3.1-pro-preview",
+ );
+ });
+ });
+
+ it("saves a custom model id that is not in the list", async () => {
+ const fetchMock = mockFetch();
+ vi.stubGlobal("fetch", fetchMock);
+ render(<BrainModelSelector providerId="openrouter" currentModel="" />);
+ await openDropdown();
+ const search = (await screen.findByLabelText(
+ "apikeys_model.search_placeholder",
+ )) as HTMLInputElement;
+ fireEvent.change(search, { target: { value: "acme/experimental-9" } });
+ fireEvent.click(screen.getByTestId("use-custom-row"));
+ await waitFor(() => {
+ const put = fetchMock.mock.calls.find(
+ (c) => (c[1] as RequestInit | undefined)?.method === "PUT",
+ );
+ expect(put).toBeDefined();
+ expect(JSON.parse((put![1] as RequestInit).body as string).model).toBe(
+ "acme/experimental-9",
+ );
+ });
+ });
+
+ it("shows an honest probe status chip after saving", async () => {
+ vi.stubGlobal(
+ "fetch",
+ mockFetch({
+ ok: true,
+ provider: "gemini",
+ model: "bogus",
+ persisted: true,
+ applied_live: false,
+ restart_required: false,
+ probe: {
+ status: "model_unavailable",
+ detail: "404 model",
+ latency_ms: 5,
+ integration_ok: true,
+ },
+ }),
+ );
+ render(<BrainModelSelector providerId="gemini" currentModel="" />);
+ await openDropdown();
+ fireEvent.click(await screen.findByText("gemini-3.1-pro-preview"));
+ expect(await screen.findByText("apikeys_test.status_model_unavailable")).toBeTruthy();
+ });
+
+ it("renders safely when the response has no models array", async () => {
+ vi.stubGlobal(
+ "fetch",
+ vi.fn().mockResolvedValue({ ok: true, json: async () => ({ provider: "gemini" }) }),
+ );
+ render(<BrainModelSelector providerId="gemini" currentModel="" />);
+ await openDropdown();
+ // No crash — the search box is present so custom entry still works.
+ expect(
+ await screen.findByLabelText("apikeys_model.search_placeholder"),
+ ).toBeTruthy();
+ });
+});
diff --git a/jarvis/ui/web/frontend/src/components/BrainModelSelector.tsx b/jarvis/ui/web/frontend/src/components/BrainModelSelector.tsx
new file mode 100644
index 0000000000..ac3c1f9b1f
--- /dev/null
+++ b/jarvis/ui/web/frontend/src/components/BrainModelSelector.tsx
@@ -0,0 +1,347 @@
+import { useEffect, useMemo, useRef, useState } from "react";
+import { AlertCircle, Check, ChevronDown, Loader2, RefreshCw, Search, XCircle } from "lucide-react";
+import {
+ getBrainProviderModels,
+ saveBrainProviderModel,
+ type BrainModel,
+ type BrainModelProbe,
+ type BrainModelSaveResult,
+ type ProviderTestStatus,
+} from "@/hooks/useProviders";
+import { useEventStore } from "@/store/events";
+import { cn } from "@/lib/utils";
+import { useT } from "@/i18n";
+
+const MAX_VISIBLE = 80;
+
+// Mirrors TEST_STATUS_TONE in ApiKeysView (kept local to avoid a circular import).
+const STATUS_TONE: Record<ProviderTestStatus, string> = {
+ ok: "border-emerald-500/30 bg-emerald-500/10 text-emerald-600",
+ not_configured: "border-border bg-muted text-muted-foreground",
+ bad_key: "border-amber-500/30 bg-amber-500/10 text-amber-600",
+ no_credits: "border-amber-500/30 bg-amber-500/10 text-amber-600",
+ rate_limited: "border-amber-500/30 bg-amber-500/10 text-amber-600",
+ model_unavailable: "border-amber-500/30 bg-amber-500/10 text-amber-600",
+ unreachable: "border-destructive/30 bg-destructive/10 text-destructive",
+ error: "border-destructive/30 bg-destructive/10 text-destructive",
+};
+
+/**
+ * Searchable per-provider model picker — a click-to-open dropdown that expands
+ * INLINE (in normal flow) rather than floating absolutely.
+ *
+ * Inline-expand is deliberate: an absolutely-positioned panel rendered *behind*
+ * the (semi-transparent) next provider card — a z-stacking artifact that looked
+ * "mushy" with list entries bleeding through. Expanding inline pushes the cards
+ * below down instead, so the panel can never be covered or clipped, and it reads
+ * as a clean, seamless section of the card.
+ *
+ * The list is the provider's OWN live catalog (so a freshly released model shows
+ * up with no code change); when that catalog is unreachable — e.g. Claude on the
+ * Max subscription with no API key — it falls back to the curated current family
+ * (Fable / Opus / Sonnet / Haiku). Pick from the list, or type a brand-new id and
+ * choose "use custom". The choice is pinned + live-applied and verified with a
+ * real 1-token probe whose honest status shows as a chip.
+ */
+export function BrainModelSelector({
+ providerId,
+ currentModel,
+ recommendedModel,
+ onSave,
+ headingLabel,
+ placeholder,
+ controlled,
+}: {
+ providerId: string;
+ currentModel?: string;
+ /**
+ * The maintainer-recommended model id for this provider (e.g.
+ * "gemini-3.5-flash"). When the list contains it, that row gets an
+ * "empfohlen" tag. Presentation only — it never changes the pinned value.
+ */
+ recommendedModel?: string | null;
+ /**
+ * Override the save target. Used by the Subagent card, which persists to its
+ * own endpoint (POST /api/subagent/model) instead of the per-provider model
+ * route. Defaults to ``saveBrainProviderModel(providerId, model)``.
+ */
+ onSave?: (model: string) => Promise<BrainModelSaveResult>;
+ /**
+ * Override the section heading (e.g. "Computer-Use model"). Defaults to the
+ * standard model/voice heading. Presentation only.
+ */
+ headingLabel?: string;
+ /** Override the empty-selection placeholder text on the trigger. */
+ placeholder?: string;
+ /**
+ * Controlled mode: ``pinned`` follows the ``currentModel`` prop (synced on
+ * change) and the live catalog's ``current_model`` NEVER overrides it. Used by
+ * the Computer-Use model picker, whose pinned value is a SEPARATE selection
+ * (cu_model) the parent owns — not the provider's main model that
+ * ``GET /models`` reports. Off by default, so the standard uncontrolled
+ * behaviour (auto-pin from the catalog) is unchanged.
+ */
+ controlled?: boolean;
+}) {
+ const t = useT();
+ const pushToast = useEventStore((s) => s.pushToast);
+ const rootRef = useRef<HTMLDivElement>(null);
+ const [open, setOpen] = useState(false);
+ const [query, setQuery] = useState("");
+ const [models, setModels] = useState<BrainModel[]>([]);
+ const [source, setSource] = useState<"live" | "cache" | "static" | "curated" | null>(null);
+ const [selects, setSelects] = useState<"model" | "voice">("model");
+ const [loading, setLoading] = useState(false);
+ const [saving, setSaving] = useState(false);
+ const [pinned, setPinned] = useState<string>(currentModel ?? "");
+ const [probe, setProbe] = useState<BrainModelProbe | null>(null);
+
+ async function load(refresh = false) {
+ setLoading(true);
+ try {
+ const res = await getBrainProviderModels(providerId, refresh);
+ setModels(Array.isArray(res.models) ? res.models : []);
+ setSource(res.source);
+ setSelects(res.selects === "voice" ? "voice" : "model");
+ // Uncontrolled: adopt the catalog's current selection as the pinned value.
+ // Controlled (CU picker): the parent owns the pinned value (cu_model) —
+ // never overwrite it with the provider's main model from GET /models.
+ if (!controlled && !pinned && res.current_model) setPinned(res.current_model);
+ } catch (e) {
+ pushToast("error", `${t("apikeys_model.load_failed")}: ${(e as Error).message}`);
+ } finally {
+ setLoading(false);
+ }
+ }
+
+ useEffect(() => {
+ void load();
+ // eslint-disable-next-line react-hooks/exhaustive-deps
+ }, [providerId]);
+
+ // Controlled mode: keep the displayed pinned value in sync with the parent's
+ // currentModel (e.g. the CU picker resolves cu_model asynchronously after
+ // mount). No-op in the default uncontrolled mode.
+ useEffect(() => {
+ if (controlled) setPinned(currentModel ?? "");
+ // eslint-disable-next-line react-hooks/exhaustive-deps
+ }, [controlled, currentModel]);
+
+ // Close on an outside click (inline panel needs no fixed backdrop).
+ useEffect(() => {
+ if (!open) return;
+ function onDown(e: MouseEvent) {
+ if (rootRef.current && !rootRef.current.contains(e.target as Node)) {
+ setOpen(false);
+ }
+ }
+ document.addEventListener("mousedown", onDown);
+ return () => document.removeEventListener("mousedown", onDown);
+ }, [open]);
+
+ const matched = useMemo(() => {
+ const list = Array.isArray(models) ? models : [];
+ const q = query.trim().toLowerCase();
+ return q
+ ? list.filter(
+ (m) => m.id.toLowerCase().includes(q) || m.label.toLowerCase().includes(q),
+ )
+ : list;
+ }, [models, query]);
+
+ const trimmed = query.trim();
+ const exactMatch = matched.some((m) => m.id === trimmed);
+ const visible = matched.slice(0, MAX_VISIBLE);
+ const pinnedLabel = models.find((m) => m.id === pinned)?.label ?? pinned;
+
+ async function save(value: string) {
+ const model = value.trim();
+ setSaving(true);
+ setProbe(null);
+ setOpen(false);
+ setQuery("");
+ try {
+ const res = onSave ? await onSave(model) : await saveBrainProviderModel(providerId, model);
+ setPinned(res.model);
+ setProbe(res.probe ?? null);
+ const note = res.restart_required
+ ? ` ${t("apikeys_model.restart_note")}`
+ : res.applied_live
+ ? ` ${t("apikeys_model.live_note")}`
+ : "";
+ pushToast("success", `${t("apikeys_model.saved")}${note}`);
+ } catch (e) {
+ pushToast("error", (e as Error).message);
+ } finally {
+ setSaving(false);
+ }
+ }
+
+ return (
+ <div
+ ref={rootRef}
+ className="space-y-1.5"
+ onClick={(e) => e.stopPropagation()}
+ onDoubleClick={(e) => e.stopPropagation()}
+ >
+ <div className="flex items-center justify-between gap-2">
+ <span className="text-[10px] uppercase tracking-wide text-muted-foreground">
+ {headingLabel ??
+ (selects === "voice" ? t("apikeys_model.heading_voice") : t("apikeys_model.heading"))}
+ </span>
+ <button
+ type="button"
+ onClick={() => void load(true)}
+ disabled={loading}
+ className="inline-flex items-center gap-1 text-[11px] text-muted-foreground hover:text-foreground"
+ title={t("apikeys_model.refresh")}
+ >
+ {loading ? (
+ <Loader2 className="h-3 w-3 animate-spin" />
+ ) : (
+ <RefreshCw className="h-3 w-3" />
+ )}
+ {t("apikeys_model.refresh")}
+ </button>
+ </div>
+
+ {/* Trigger — reads like a <select> */}
+ <button
+ type="button"
+ aria-label={t("apikeys_model.model_label")}
+ aria-expanded={open}
+ onClick={() => setOpen((o) => !o)}
+ disabled={saving}
+ className={cn(
+ "flex w-full items-center justify-between gap-2 rounded-md border bg-background px-3 py-2 text-left transition-colors",
+ open ? "border-primary/50 ring-1 ring-primary/20" : "border-input hover:border-primary/40",
+ )}
+ >
+ <span className={cn("truncate text-xs", !pinned && "text-muted-foreground")}>
+ {pinnedLabel ||
+ placeholder ||
+ (selects === "voice"
+ ? t("apikeys_model.choose_voice")
+ : t("apikeys_model.choose_placeholder"))}
+ </span>
+ {saving ? (
+ <Loader2 className="h-3.5 w-3.5 shrink-0 animate-spin text-muted-foreground" />
+ ) : (
+ <ChevronDown
+ className={cn(
+ "h-3.5 w-3.5 shrink-0 text-muted-foreground transition-transform",
+ open && "rotate-180",
+ )}
+ />
+ )}
+ </button>
+
+ {/* Inline-expanding panel — in normal flow, so it pushes the cards below
+ down instead of floating over (and behind) them. */}
+ {open && (
+ <div className="overflow-hidden rounded-md border border-border bg-popover">
+ <div className="flex items-center gap-2 border-b border-border px-2.5 py-1.5">
+ <Search className="h-3.5 w-3.5 shrink-0 text-muted-foreground" />
+ <input
+ type="text"
+ autoFocus
+ aria-label={t("apikeys_model.search_placeholder")}
+ value={query}
+ placeholder={t("apikeys_model.search_placeholder")}
+ onChange={(e) => setQuery(e.target.value)}
+ className="w-full bg-transparent font-mono text-xs focus:outline-none"
+ />
+ </div>
+
+ <ul className="max-h-56 overflow-y-auto p-1 scrollbar-jarvis">
+ {visible.map((m) => (
+ <li key={m.id}>
+ <button
+ type="button"
+ onClick={() => void save(m.id)}
+ className={cn(
+ "flex w-full items-center justify-between gap-2 rounded px-2 py-1.5 text-left hover:bg-accent",
+ m.id === pinned && "bg-primary/10",
+ )}
+ >
+ <span className="flex min-w-0 items-center gap-1.5 truncate text-xs">
+ {m.label}
+ {recommendedModel && m.id === recommendedModel && (
+ <span className="shrink-0 rounded-full bg-primary/15 px-1.5 py-0.5 text-[9px] uppercase tracking-wide text-primary">
+ {t("apikeys_model.recommended_tag")}
+ </span>
+ )}
+ </span>
+ <span className="shrink-0 font-mono text-[10px] text-muted-foreground">
+ {m.id}
+ </span>
+ </button>
+ </li>
+ ))}
+
+ {trimmed && !exactMatch && (
+ <li>
+ <button
+ type="button"
+ data-testid="use-custom-row"
+ onClick={() => void save(trimmed)}
+ className="flex w-full items-center gap-2 rounded px-2 py-1.5 text-left text-xs hover:bg-accent"
+ >
+ <Check className="h-3 w-3 shrink-0 text-primary" />
+ {t("apikeys_model.use_custom").replace("{0}", trimmed)}
+ </button>
+ </li>
+ )}
+
+ {!visible.length && !trimmed && (
+ <li className="px-2 py-2 text-[11px] text-muted-foreground">
+ {loading ? t("apikeys_model.loading") : t("apikeys_model.no_models")}
+ </li>
+ )}
+ </ul>
+
+ {matched.length > MAX_VISIBLE && (
+ <div className="border-t border-border px-2.5 py-1 text-[10px] text-muted-foreground">
+ {t("apikeys_model.more_hint").replace("{0}", String(matched.length - MAX_VISIBLE))}
+ </div>
+ )}
+ </div>
+ )}
+
+ <div className="flex flex-wrap items-center gap-2">
+ {source === "static" && (
+ <span className="text-[11px] text-amber-600" title={t("apikeys_model.source_static_note")}>
+ {t("apikeys_model.source_static")}
+ </span>
+ )}
+ {probe && <ProbeChip probe={probe} />}
+ </div>
+ </div>
+ );
+}
+
+function ProbeChip({ probe }: { probe: BrainModelProbe }) {
+ const t = useT();
+ const tone = STATUS_TONE[probe.status];
+ return (
+ <span
+ data-testid="brain-model-probe"
+ className={cn(
+ "inline-flex items-center gap-1 rounded-full border px-2 py-0.5 text-[11px]",
+ tone,
+ )}
+ title={[probe.detail, probe.latency_ms ? `${Math.round(probe.latency_ms)} ms` : ""]
+ .filter(Boolean)
+ .join("\n")}
+ >
+ {probe.status === "ok" ? (
+ <Check className="h-3 w-3" />
+ ) : probe.integration_ok ? (
+ <AlertCircle className="h-3 w-3" />
+ ) : (
+ <XCircle className="h-3 w-3" />
+ )}
+ {t(`apikeys_test.status_${probe.status}`)}
+ </span>
+ );
+}
diff --git a/jarvis/ui/web/frontend/src/components/CliConnectCoach.tsx b/jarvis/ui/web/frontend/src/components/CliConnectCoach.tsx
index 7b21ff370a..76120be25a 100644
--- a/jarvis/ui/web/frontend/src/components/CliConnectCoach.tsx
+++ b/jarvis/ui/web/frontend/src/components/CliConnectCoach.tsx
@@ -14,8 +14,10 @@ import { useState } from "react";
import { CheckCircle2, Loader2, X } from "lucide-react";
import { Button } from "@/components/ui/button";
import { useEventStore, type CliConnectCoach as CoachState } from "@/store/events";
+import { useT } from "@/i18n";
export function CliConnectCoach({ coach }: { coach: CoachState }) {
+ const t = useT();
const setCoach = useEventStore((s) => s.setCliConnectCoach);
const [connected] = useState(false);
@@ -24,18 +26,18 @@ export function CliConnectCoach({ coach }: { coach: CoachState }) {
<header className="flex items-start justify-between gap-2 border-b border-border px-4 py-3">
<div className="min-w-0 flex-1">
<div className="font-display text-sm font-semibold">
- {coach.displayName} verbinden
+ {coach.displayName} {t("cli_connect_coach.connect")}
</div>
<div className="mt-0.5 flex items-center gap-1.5 text-[11px]">
{connected ? (
<>
<CheckCircle2 className="h-3 w-3 text-primary" />
- <span className="text-primary">verbunden</span>
+ <span className="text-primary">{t("cli_connect_coach.connected")}</span>
</>
) : (
<>
<Loader2 className="h-3 w-3 animate-spin text-muted-foreground" />
- <span className="text-muted-foreground">warte auf login…</span>
+ <span className="text-muted-foreground">{t("cli_connect_coach.waiting_for_login")}</span>
</>
)}
</div>
@@ -51,20 +53,19 @@ export function CliConnectCoach({ coach }: { coach: CoachState }) {
<div className="space-y-3 p-4 text-xs">
<div>
<div className="mb-1 text-[10px] uppercase tracking-wider text-muted-foreground/70">
- Login-Command
+ {t("cli_connect_coach.login_command")}
</div>
<code className="block break-all rounded-md border border-border bg-background px-2.5 py-1.5 font-mono text-[10px]">
{coach.loginCommand}
</code>
</div>
<p className="text-muted-foreground">
- Folge den Anweisungen im Terminal links. Ich pruefe alle 3 Sekunden,
- ob der Login durch ist.
+ {t("cli_connect_coach.instructions")}
</p>
</div>
<footer className="flex items-center justify-end gap-2 border-t border-border px-4 py-3">
<Button size="sm" variant="ghost" onClick={() => setCoach(null)}>
- {connected ? "Fertig" : "Schliessen"}
+ {connected ? t("cli_connect_coach.done") : t("cli_connect_coach.close")}
</Button>
</footer>
</aside>
diff --git a/jarvis/ui/web/frontend/src/components/CliConnectPoller.tsx b/jarvis/ui/web/frontend/src/components/CliConnectPoller.tsx
index ffa97109dc..c80e91ea4b 100644
--- a/jarvis/ui/web/frontend/src/components/CliConnectPoller.tsx
+++ b/jarvis/ui/web/frontend/src/components/CliConnectPoller.tsx
@@ -22,6 +22,7 @@
import { useEffect, useRef } from "react";
import { useQueryClient } from "@tanstack/react-query";
import { useEventStore } from "@/store/events";
+import { useT } from "@/i18n";
const POLL_INTERVAL_MS = 3_000;
const MAX_ATTEMPTS = 100; // 100 * 3s = 5 Minuten
@@ -31,6 +32,7 @@ export function CliConnectPoller() {
const setCoach = useEventStore((s) => s.setCliConnectCoach);
const pushToast = useEventStore((s) => s.pushToast);
const qc = useQueryClient();
+ const t = useT();
const attemptsRef = useRef(0);
useEffect(() => {
@@ -52,7 +54,7 @@ export function CliConnectPoller() {
const data = (await r.json()) as { connected?: boolean };
if (cancelled) return;
if (data.connected) {
- pushToast("success", `${coach.displayName} verbunden`);
+ pushToast("success", `${coach.displayName} ${t("cli_connect_poller.connected")}`);
qc.invalidateQueries({ queryKey: ["clis"] });
qc.invalidateQueries({ queryKey: ["cli", coach.cliName] });
setCoach(null);
@@ -61,7 +63,7 @@ export function CliConnectPoller() {
if (attemptsRef.current >= MAX_ATTEMPTS) {
pushToast(
"warning",
- `${coach.displayName}: Login nicht abgeschlossen`,
+ `${coach.displayName}: ${t("cli_connect_poller.login_incomplete")}`,
);
setCoach(null);
}
diff --git a/jarvis/ui/web/frontend/src/components/CuModelSelector.test.tsx b/jarvis/ui/web/frontend/src/components/CuModelSelector.test.tsx
new file mode 100644
index 0000000000..0d359e2f26
--- /dev/null
+++ b/jarvis/ui/web/frontend/src/components/CuModelSelector.test.tsx
@@ -0,0 +1,111 @@
+import { cleanup, fireEvent, render, screen, waitFor } from "@testing-library/react";
+import { afterEach, describe, expect, it, vi } from "vitest";
+
+// Identity translator so rendered text equals the i18n key.
+vi.mock("@/i18n", () => ({
+ useT: () => (key: string) => key,
+}));
+
+vi.mock("@/store/events", () => ({
+ useEventStore: (selector: (s: { pushToast: () => void }) => unknown) =>
+ selector({ pushToast: vi.fn() }),
+}));
+
+import { CuModelSelector } from "./CuModelSelector";
+
+const MODELS = {
+ provider: "gemini",
+ current_model: "gemini-3.5-flash",
+ models: [
+ { id: "gemini-3.1-pro-preview", label: "Gemini 3.1 Pro" },
+ { id: "gemini-3.5-flash", label: "Gemini 3.5 Flash" },
+ ],
+ source: "live",
+ fetched_at: 1,
+};
+
+function mockFetch(cuModel = "", opts?: { putRestart?: boolean }) {
+ return vi.fn().mockImplementation(async (url: string, init?: RequestInit) => {
+ const u = String(url);
+ if (u.includes("/cu-model") && (!init || init.method === "GET" || !init.method)) {
+ // GET /cu-model
+ if (!init || init.method !== "PUT") {
+ return {
+ ok: true,
+ json: async () => ({
+ provider: "gemini",
+ cu_model: cuModel,
+ effective_model: cuModel || "gemini-3.5-flash",
+ uses_main: !cuModel,
+ }),
+ };
+ }
+ }
+ if (u.includes("/cu-model") && init?.method === "PUT") {
+ const sent = JSON.parse((init.body as string) || "{}");
+ return {
+ ok: true,
+ json: async () => ({
+ ok: true,
+ provider: "gemini",
+ cu_model: sent.cu_model ?? "",
+ effective_model: sent.cu_model || "gemini-3.5-flash",
+ uses_main: !sent.cu_model,
+ persisted: true,
+ restart_required: opts?.putRestart ?? false,
+ }),
+ };
+ }
+ if (u.includes("/models")) return { ok: true, json: async () => MODELS };
+ return { ok: true, json: async () => ({}) };
+ });
+}
+
+afterEach(() => {
+ cleanup();
+ vi.restoreAllMocks();
+});
+
+describe("CuModelSelector", () => {
+ it("loads the current CU model and shows the 'using main' state when unpinned", async () => {
+ vi.stubGlobal("fetch", mockFetch(""));
+ render(<CuModelSelector providerId="gemini" />);
+ expect(await screen.findByText("apikeys_cu_model.using_main")).toBeTruthy();
+ });
+
+ it("pins a CU model picked from the list via PUT /cu-model", async () => {
+ const fetchMock = mockFetch("");
+ vi.stubGlobal("fetch", fetchMock);
+ render(<CuModelSelector providerId="gemini" />);
+ const trigger = (await screen.findByLabelText("apikeys_model.model_label")) as HTMLElement;
+ fireEvent.click(trigger);
+ fireEvent.click(await screen.findByText("gemini-3.1-pro-preview"));
+ await waitFor(() => {
+ const put = fetchMock.mock.calls.find(
+ (c) => (c[1] as RequestInit | undefined)?.method === "PUT",
+ );
+ expect(put).toBeDefined();
+ expect(String(put![0])).toContain("/api/providers/gemini/cu-model");
+ expect(JSON.parse((put![1] as RequestInit).body as string).cu_model).toBe(
+ "gemini-3.1-pro-preview",
+ );
+ });
+ });
+
+ it("clears back to the main model via the 'use main' button (PUT empty)", async () => {
+ const fetchMock = mockFetch("gemini-3.1-pro-preview");
+ vi.stubGlobal("fetch", fetchMock);
+ render(<CuModelSelector providerId="gemini" />);
+ // When pinned, the dedicated clear button is shown (testid disambiguates it
+ // from the trigger placeholder, which shares the label text).
+ const clearBtn = await screen.findByTestId("cu-use-main");
+ fireEvent.click(clearBtn);
+ await waitFor(() => {
+ const put = fetchMock.mock.calls.find(
+ (c) => (c[1] as RequestInit | undefined)?.method === "PUT",
+ );
+ expect(put).toBeDefined();
+ expect(JSON.parse((put![1] as RequestInit).body as string).cu_model).toBe("");
+ });
+ });
+});
diff --git a/jarvis/ui/web/frontend/src/components/CuModelSelector.tsx b/jarvis/ui/web/frontend/src/components/CuModelSelector.tsx
new file mode 100644
index 0000000000..8df75994f6
--- /dev/null
+++ b/jarvis/ui/web/frontend/src/components/CuModelSelector.tsx
@@ -0,0 +1,99 @@
+import { useEffect, useState } from "react";
+import { BrainModelSelector } from "@/components/BrainModelSelector";
+import { getCuModel, saveCuModel } from "@/hooks/useProviders";
+import { useEventStore } from "@/store/events";
+import { useT } from "@/i18n";
+
+/**
+ * Per-provider "Computer-Use model" picker (Phase 3).
+ *
+ * Computer-Use runs on the provider's main model by default; this lets the user
+ * pin a different (e.g. stronger) model just for CU, without affecting chat and
+ * without any automatic escalation. It reuses the shared {@link BrainModelSelector}
+ * for the searchable dropdown (same live catalog as the main model picker) and
+ * adds a "use my main model" reset. An empty selection means "use my main model".
+ */
+export function CuModelSelector({
+ providerId,
+ recommendedModel,
+}: {
+ providerId: string;
+ recommendedModel?: string | null;
+}) {
+ const t = useT();
+ const pushToast = useEventStore((s) => s.pushToast);
+ const [cuModel, setCuModel] = useState<string>("");
+ const [usesMain, setUsesMain] = useState<boolean>(true);
+ const [effective, setEffective] = useState<string>("");
+ const [clearing, setClearing] = useState(false);
+
+ useEffect(() => {
+ let cancelled = false;
+ void (async () => {
+ try {
+ const r = await getCuModel(providerId);
+ if (cancelled) return;
+ setCuModel(r.cu_model ?? "");
+ setUsesMain(r.uses_main ?? !r.cu_model);
+ setEffective(r.effective_model ?? "");
+ } catch {
+ /* leave defaults — the row degrades to "using main" */
+ }
+ })();
+ return () => {
+ cancelled = true;
+ };
+ }, [providerId]);
+
+ async function clearToMain() {
+ setClearing(true);
+ try {
+ await saveCuModel(providerId, "");
+ setCuModel("");
+ setUsesMain(true);
+ pushToast("success", t("apikeys_cu_model.cleared"));
+ } catch (e) {
+ pushToast("error", (e as Error).message);
+ } finally {
+ setClearing(false);
+ }
+ }
+
+ return (
+ <div className="space-y-1">
+ <BrainModelSelector
+ providerId={providerId}
+ currentModel={cuModel}
+ controlled
+ recommendedModel={recommendedModel}
+ headingLabel={t("apikeys_cu_model.heading")}
+ placeholder={t("apikeys_cu_model.use_main")}
+ onSave={async (model) => {
+ const res = await saveCuModel(providerId, model);
+ setCuModel(model);
+ setUsesMain(!model);
+ setEffective(model || effective);
+ return res;
+ }}
+ />
+ <div className="flex items-center justify-between gap-2">
+ <span className="text-[10px] text-muted-foreground">
+ {usesMain
+ ? t("apikeys_cu_model.using_main")
+ : `${t("apikeys_cu_model.effective")}: ${effective || cuModel}`}
+ </span>
+ {!usesMain && (
+ <button
+ type="button"
+ data-testid="cu-use-main"
+ onClick={() => void clearToMain()}
+ disabled={clearing}
+ className="text-[11px] text-muted-foreground underline hover:text-foreground"
+ >
+ {t("apikeys_cu_model.use_main")}
+ </button>
+ )}
+ </div>
+ </div>
+ );
+}
diff --git a/jarvis/ui/web/frontend/src/components/FrontierSwitchModal.tsx b/jarvis/ui/web/frontend/src/components/FrontierSwitchModal.tsx
index 967bcc848c..070dea2489 100644
--- a/jarvis/ui/web/frontend/src/components/FrontierSwitchModal.tsx
+++ b/jarvis/ui/web/frontend/src/components/FrontierSwitchModal.tsx
@@ -8,6 +8,7 @@ import { useEffect, useState } from "react";
import { Sparkles, ArrowRight } from "lucide-react";
import { cn } from "@/lib/utils";
import { useEventStore } from "@/store/events";
+import { useT } from "@/i18n";
interface FrontierSwitch {
provider: string;
@@ -20,6 +21,7 @@ interface FrontierSwitch {
const POLL_INTERVAL_MS = 30_000;
export function FrontierSwitchModal() {
+ const t = useT();
const assistantName = useEventStore((s) => s.assistantName);
const [pending, setPending] = useState<FrontierSwitch[]>([]);
const [acking, setAcking] = useState(false);
@@ -97,13 +99,12 @@ export function FrontierSwitchModal() {
id="frontier-modal-title"
className="text-base font-semibold text-foreground"
>
- Frontier-Modell{pending.length === 1 ? "" : "e"} aktualisiert
+ {pending.length === 1 ? t("frontier_switch_modal.title_one") : t("frontier_switch_modal.title_many")}
</h2>
</div>
<p className="mb-4 text-sm text-muted-foreground">
- {assistantName} hat beim Start ein neueres Modell beim Anbieter erkannt
- und automatisch gewechselt. Bitte bestaetige.
+ {assistantName} {t("frontier_switch_modal.description")}
</p>
<div className="mb-5 space-y-3">
@@ -150,7 +151,7 @@ export function FrontierSwitchModal() {
"disabled:cursor-not-allowed disabled:opacity-50",
)}
>
- {acking ? "Bestaetige…" : "OK"}
+ {acking ? t("frontier_switch_modal.acking") : "OK"}
</button>
</div>
</div>
diff --git a/jarvis/ui/web/frontend/src/components/JarvisDock.filedrop.test.tsx b/jarvis/ui/web/frontend/src/components/JarvisDock.filedrop.test.tsx
new file mode 100644
index 0000000000..8cd1d713f0
--- /dev/null
+++ b/jarvis/ui/web/frontend/src/components/JarvisDock.filedrop.test.tsx
@@ -0,0 +1,172 @@
+import { describe, expect, it, vi, beforeEach, afterEach } from "vitest";
+import { render, screen, fireEvent, cleanup, waitFor } from "@testing-library/react";
+
+const send = vi.fn();
+const playDropConfirm = vi.fn();
+vi.mock("@/hooks/useWebSocket", () => ({ getWSClient: () => ({ send }) }));
+vi.mock("@/hooks/useOverlayStyle", () => ({
+ useOverlayStyle: () => ({
+ config: { style: "whisper_bar", options: [] },
+ loading: false,
+ error: null,
+ refetch: vi.fn(),
+ saveStyle: vi.fn(),
+ }),
+}));
+vi.mock("@/lib/sound", () => ({ playDropConfirm: () => playDropConfirm() }));
+
+import { JarvisDock, MISSION_DND_MIME } from "./JarvisDock";
+import { useEventStore } from "@/store/events";
+import { useMissionDrag } from "@/store/missionDrag";
+
+/** A minimal DataTransfer stand-in for native (OS) drags. `files` carries real
+ * File parts; `data` backs getData for text/URL drags. `types` mirrors what a
+ * browser exposes so the dock's detection logic sees "Files" / "text/*". */
+function nativeDataTransfer(opts: {
+ files?: File[];
+ data?: Record<string, string>;
+}): DataTransfer {
+ const files = opts.files ?? [];
+ const data = opts.data ?? {};
+ const types: string[] = [];
+ if (files.length) types.push("Files");
+ types.push(...Object.keys(data));
+ return {
+ files: files as unknown as FileList,
+ items: [] as unknown as DataTransferItemList,
+ getData: (mime: string) => data[mime] ?? "",
+ setData: vi.fn(),
+ types,
+ dropEffect: "none",
+ effectAllowed: "all",
+ } as unknown as DataTransfer;
+}
+
+describe("JarvisDock — native OS file/text drop", () => {
+ beforeEach(() => {
+ send.mockClear();
+ playDropConfirm.mockClear();
+ useMissionDrag.getState().end();
+ useEventStore.setState({
+ ensureActiveThread: async () => "thread-9",
+ } as never);
+ global.fetch = vi.fn(async () => ({ ok: true, status: 200 })) as never;
+ });
+ afterEach(() => {
+ cleanup();
+ vi.restoreAllMocks();
+ });
+
+ it("POSTs a dropped file to /api/chat/drop with files + thread_id", async () => {
+ render(<JarvisDock />);
+ const zone = screen.getByTestId("jarvis-dock");
+ const file = new File(["hello"], "note.txt", { type: "text/plain" });
+ fireEvent.drop(zone, {
+ dataTransfer: nativeDataTransfer({ files: [file] }),
+ });
+ await waitFor(() => expect(global.fetch).toHaveBeenCalledTimes(1));
+ const [url, init] = (global.fetch as unknown as ReturnType<typeof vi.fn>).mock
+ .calls[0];
+ expect(url).toBe("/api/chat/drop");
+ expect(init.method).toBe("POST");
+ const body = init.body as FormData;
+ expect(body).toBeInstanceOf(FormData);
+ expect(body.get("files")).toBe(file);
+ expect(body.get("thread_id")).toBe("thread-9");
+ expect(body.get("surface")).toBe("dock");
+ // The WS mission path must NOT fire for a native drop.
+ expect(send).not.toHaveBeenCalled();
+ });
+
+ it("POSTs dragged text/URL with a text field and no files", async () => {
+ render(<JarvisDock />);
+ const zone = screen.getByTestId("jarvis-dock");
+ fireEvent.drop(zone, {
+ dataTransfer: nativeDataTransfer({
+ data: {
+ "text/uri-list": "https://example.com/article",
+ "text/plain": "https://example.com/article",
+ },
+ }),
+ });
+ await waitFor(() => expect(global.fetch).toHaveBeenCalledTimes(1));
+ const [url, init] = (global.fetch as unknown as ReturnType<typeof vi.fn>).mock
+ .calls[0];
+ expect(url).toBe("/api/chat/drop");
+ const body = init.body as FormData;
+ expect(body.get("text")).toBe("https://example.com/article");
+ expect(body.get("files")).toBeNull();
+ expect(body.get("thread_id")).toBe("thread-9");
+ expect(send).not.toHaveBeenCalled();
+ });
+
+ it("plays the confirmation feedback on a successful native drop", async () => {
+ render(<JarvisDock />);
+ const zone = screen.getByTestId("jarvis-dock");
+ const file = new File(["x"], "a.png", { type: "image/png" });
+ fireEvent.drop(zone, {
+ dataTransfer: nativeDataTransfer({ files: [file] }),
+ });
+ await waitFor(() => expect(playDropConfirm).toHaveBeenCalledTimes(1));
+ });
+
+ it("keeps the mission path: a mission-MIME drop sends mission.inject, not fetch", async () => {
+ render(<JarvisDock />);
+ const zone = screen.getByTestId("jarvis-dock");
+ const dt = {
+ getData: (mime: string) =>
+ mime === MISSION_DND_MIME
+ ? JSON.stringify({ slug: "s", utterance: "u" })
+ : "",
+ setData: vi.fn(),
+ files: [] as unknown as FileList,
+ types: [MISSION_DND_MIME],
+ dropEffect: "none",
+ effectAllowed: "all",
+ } as unknown as DataTransfer;
+ fireEvent.drop(zone, { dataTransfer: dt });
+ await waitFor(() => expect(send).toHaveBeenCalledTimes(1));
+ expect(send.mock.calls[0][0].action).toBe("mission.inject");
+ expect(global.fetch).not.toHaveBeenCalled();
+ });
+
+ it("ignores an empty/garbage native drop (no files, no text)", () => {
+ render(<JarvisDock />);
+ const zone = screen.getByTestId("jarvis-dock");
+ fireEvent.drop(zone, { dataTransfer: nativeDataTransfer({}) });
+ expect(global.fetch).not.toHaveBeenCalled();
+ expect(send).not.toHaveBeenCalled();
+ });
+
+ it("blooms (becomes visible) during a native file drag, not just a mission drag", () => {
+ render(<JarvisDock />);
+ const zone = screen.getByTestId("jarvis-dock");
+ expect(zone.className).toContain("opacity-0");
+ fireEvent.dragEnter(zone, {
+ dataTransfer: nativeDataTransfer({
+ files: [new File(["x"], "a.txt")],
+ }),
+ });
+ const live = screen.getByTestId("jarvis-dock");
+ expect(live.className).toContain("opacity-100");
+ expect(live.className).not.toContain("opacity-0");
+ });
+
+ it("accepts a native drop on the full-window catch layer (toss near Jarvis)", async () => {
+ render(<JarvisDock />);
+ const zone = screen.getByTestId("jarvis-dock");
+ // Arm a native drag so the catch layer mounts.
+ fireEvent.dragEnter(zone, {
+ dataTransfer: nativeDataTransfer({ files: [new File(["x"], "a.txt")] }),
+ });
+ const catcher = screen.getByTestId("jarvis-dock-catch");
+ const file = new File(["payload"], "drop.txt", { type: "text/plain" });
+ fireEvent.drop(catcher, {
+ dataTransfer: nativeDataTransfer({ files: [file] }),
+ });
+ await waitFor(() => expect(global.fetch).toHaveBeenCalledTimes(1));
+ expect(
+ (global.fetch as unknown as ReturnType<typeof vi.fn>).mock.calls[0][0],
+ ).toBe("/api/chat/drop");
+ });
+});
diff --git a/jarvis/ui/web/frontend/src/components/JarvisDock.tsx b/jarvis/ui/web/frontend/src/components/JarvisDock.tsx
index 7661a4cd96..38848178a6 100644
--- a/jarvis/ui/web/frontend/src/components/JarvisDock.tsx
+++ b/jarvis/ui/web/frontend/src/components/JarvisDock.tsx
@@ -17,6 +17,24 @@ function hasMission(dt: DataTransfer | null): boolean {
return Array.from(dt.types ?? []).includes(MISSION_DND_MIME);
}
+/** True for a native OS drag carrying files or draggable text/URL — the only
+ * thing the file-drop path acts on. `useMissionDrag` never fires for these. */
+function hasNativePayload(dt: DataTransfer | null): boolean {
+ if (!dt) return false;
+ const types = Array.from(dt.types ?? []);
+ return (
+ types.includes("Files") ||
+ types.includes("text/plain") ||
+ types.includes("text/uri-list")
+ );
+}
+
+/** Either an internal mission card or a native OS payload — anything the dock
+ * should bloom for and accept. */
+function isDroppable(dt: DataTransfer | null): boolean {
+ return hasMission(dt) || hasNativePayload(dt);
+}
+
/**
* A small, always-present "Jarvis presence" dock in the bottom-right corner.
* Drop a mission/output card on it to pull that sub-agent task into the live
@@ -38,6 +56,7 @@ export function JarvisDock() {
const dragging = useMissionDrag((s) => s.dragging);
const endDrag = useMissionDrag((s) => s.end);
const [armed, setArmed] = useState(false); // a card is directly over the dock
+ const [fileArmed, setFileArmed] = useState(false); // a native OS drag is in flight
const [flash, setFlash] = useState(false); // brief post-drop "absorb" burst
const flashTimer = useRef<ReturnType<typeof setTimeout> | null>(null);
const isBar = config?.style === "whisper_bar";
@@ -51,6 +70,36 @@ export function JarvisDock() {
[],
);
+ // A native OS drag that leaves the window (or ends anywhere) must disarm the
+ // dock. The full-window catch layer has no dragleave of its own, so without
+ // this the bloom could stick after the cursor exits the window over the catch
+ // layer. Wired only while a file drag is armed.
+ useEffect(() => {
+ if (!fileArmed) return;
+ const disarm = () => setFileArmed(false);
+ const onWindowDragLeave = (e: DragEvent) => {
+ // relatedTarget === null + a viewport-edge cursor = the drag left the
+ // window entirely (not just moved between elements inside it).
+ if (
+ e.relatedTarget === null &&
+ (e.clientX <= 0 ||
+ e.clientY <= 0 ||
+ e.clientX >= window.innerWidth ||
+ e.clientY >= window.innerHeight)
+ ) {
+ setFileArmed(false);
+ }
+ };
+ window.addEventListener("drop", disarm);
+ window.addEventListener("dragend", disarm);
+ window.addEventListener("dragleave", onWindowDragLeave);
+ return () => {
+ window.removeEventListener("drop", disarm);
+ window.removeEventListener("dragend", disarm);
+ window.removeEventListener("dragleave", onWindowDragLeave);
+ };
+ }, [fileArmed]);
+
/** Parse + dispatch the dropped mission. Shared by the dock and the catch
* layer so a release anywhere near Jarvis behaves identically. */
async function injectFrom(dt: DataTransfer): Promise<boolean> {
@@ -77,29 +126,82 @@ export function JarvisDock() {
return true;
}
+ /** Ship a native OS drop (files or text/URL) to the proactive-reaction
+ * endpoint as multipart/form-data. Returns true when something was sent. */
+ async function dropNative(dt: DataTransfer): Promise<boolean> {
+ const files = Array.from(dt.files ?? []);
+ const text =
+ files.length === 0
+ ? dt.getData("text/uri-list") || dt.getData("text/plain")
+ : "";
+ if (files.length === 0 && !text) return false;
+
+ const form = new FormData();
+ for (const file of files) form.append("files", file);
+ if (text) form.set("text", text);
+ form.set("surface", "dock");
+ try {
+ const threadId = await useEventStore.getState().ensureActiveThread();
+ if (threadId) form.set("thread_id", threadId);
+ } catch {
+ // Tolerate a missing thread — the backend can still react.
+ }
+ try {
+ // No Content-Type header: the browser sets the multipart boundary.
+ const res = await fetch("/api/chat/drop", { method: "POST", body: form });
+ return res.ok;
+ } catch {
+ return false;
+ }
+ }
+
+ function celebrate() {
+ playDropConfirm();
+ setFlash(true);
+ if (flashTimer.current) clearTimeout(flashTimer.current);
+ flashTimer.current = setTimeout(() => setFlash(false), 1100);
+ }
+
async function handleDrop(e: React.DragEvent) {
e.preventDefault();
setArmed(false);
- const ok = await injectFrom(e.dataTransfer);
+ setFileArmed(false);
+ const dt = e.dataTransfer;
+ // Disambiguate: an internal mission card keeps the existing WS path; any
+ // other native payload (files / text / URL) goes to the file-drop endpoint.
+ const ok = hasMission(dt) ? await injectFrom(dt) : await dropNative(dt);
endDrag(); // tear down the bloom whether or not the payload was valid
if (!ok) return;
- playDropConfirm();
- setFlash(true);
- if (flashTimer.current) clearTimeout(flashTimer.current);
- flashTimer.current = setTimeout(() => setFlash(false), 1100);
+ celebrate();
}
function acceptOver(e: React.DragEvent) {
- if (hasMission(e.dataTransfer)) {
+ if (isDroppable(e.dataTransfer)) {
// preventDefault here is what turns the OS cursor from 🚫 into "copy".
e.preventDefault();
e.dataTransfer.dropEffect = "copy";
}
}
+ function handleDragEnter(e: React.DragEvent) {
+ if (hasMission(e.dataTransfer)) setArmed(true);
+ else if (hasNativePayload(e.dataTransfer)) setFileArmed(true);
+ }
+
+ // A drag is "live" for the dock whenever an internal mission card is in
+ // flight OR a native OS payload is hovering — the latter never reaches
+ // `useMissionDrag`, so `fileArmed` is what blooms the dock for OS drops.
+ const live = dragging || fileArmed;
+
// One mutually-exclusive visual state — avoids conflicting Tailwind utilities
// (scale-105 vs scale-110) fighting over which wins in the generated CSS.
- const state = flash ? "flash" : armed ? "armed" : dragging ? "bloom" : "idle";
+ const state = flash
+ ? "flash"
+ : armed || fileArmed
+ ? "armed"
+ : live
+ ? "bloom"
+ : "idle";
const stateClass = {
idle: "border-border bg-card/70",
bloom:
@@ -112,19 +214,20 @@ export function JarvisDock() {
const label = flash
? t("jarvis_dock.dropped")
- : armed || dragging
+ : armed || fileArmed || dragging
? t("jarvis_dock.drop_active")
: null;
- // The dock earns screen space only when a mission card is actually in flight
- // (`dragging`) or has just landed (`flash`, the brief absorb burst). In idle
- // it stays mounted — so the drop handler and catch layer remain wired — but
- // is faded out and non-interactive, so no permanent icon clutters the corner.
- const visible = dragging || flash;
+ // The dock earns screen space only when a drag is actually in flight (a
+ // mission card via `dragging`, or a native OS payload via `fileArmed`) or has
+ // just landed (`flash`, the brief absorb burst). In idle it stays mounted —
+ // so the drop handler and catch layer remain wired — but is faded out and
+ // non-interactive, so no permanent icon clutters the corner.
+ const visible = live || flash;
return (
<>
- {dragging && (
+ {live && (
<div
data-testid="jarvis-dock-catch"
aria-hidden
@@ -140,11 +243,12 @@ export function JarvisDock() {
aria-label={t("jarvis_dock.aria")}
aria-hidden={visible ? undefined : true}
title={t("jarvis_dock.hint")}
- onDragEnter={(e) => {
- if (hasMission(e.dataTransfer)) setArmed(true);
- }}
+ onDragEnter={handleDragEnter}
onDragOver={acceptOver}
- onDragLeave={() => setArmed(false)}
+ onDragLeave={() => {
+ setArmed(false);
+ setFileArmed(false);
+ }}
onDrop={handleDrop}
className={cn(
"fixed bottom-4 right-4 z-50 flex items-center gap-2 rounded-full border px-3 py-2 shadow-lg backdrop-blur transition-all duration-300 ease-out",
diff --git a/jarvis/ui/web/frontend/src/components/MascotGigi.tsx b/jarvis/ui/web/frontend/src/components/MascotGigi.tsx
index 7d1eabe099..5ede967366 100644
--- a/jarvis/ui/web/frontend/src/components/MascotGigi.tsx
+++ b/jarvis/ui/web/frontend/src/components/MascotGigi.tsx
@@ -1,5 +1,6 @@
import { useCallback, useEffect, useRef, useState } from "react";
import { cn } from "@/lib/utils";
+import { translate, useT } from "@/i18n";
import { useEventStore, type VoiceState, type SectionId } from "@/store/events";
type MascotAction =
@@ -51,6 +52,7 @@ export function MascotGigi({
reactToVoice = true,
enableComments = true,
}: Props) {
+ const t = useT();
const [action, setAction] = useState<MascotAction>("idle");
const voiceState = useEventStore((s) => s.voiceState);
const transcription = useEventStore((s) => s.transcription);
@@ -91,7 +93,7 @@ export function MascotGigi({
<div className="gigi-container" style={{ width: size, height: size }}>
<div
className={cn("gigi-root", `gigi-${action}`, voiceClass, className)}
- aria-label="Jarvis-Maskottchen Gigi"
+ aria-label={t("mascot_gigi.aria_label")}
title="Gigi"
>
<svg viewBox="0 0 256 256" xmlns="http://www.w3.org/2000/svg" className="gigi-svg">
@@ -376,7 +378,11 @@ function useMascotComments(enabled: boolean): string | null {
if (!mountedRef.current) return;
if (connected === lastConnectedRef.current) return;
lastConnectedRef.current = connected;
- show(connected ? "wieder online!" : "Verbindung weg …");
+ show(
+ connected
+ ? translate("mascot_gigi.back_online")
+ : translate("mascot_gigi.connection_lost"),
+ );
}, [connected, show]);
// Mount: begrüßen nach Tageszeit.
diff --git a/jarvis/ui/web/frontend/src/components/PlanStepList.tsx b/jarvis/ui/web/frontend/src/components/PlanStepList.tsx
index fcc2cd7ddb..d6f15c1a4c 100644
--- a/jarvis/ui/web/frontend/src/components/PlanStepList.tsx
+++ b/jarvis/ui/web/frontend/src/components/PlanStepList.tsx
@@ -5,6 +5,7 @@
* eine flache Liste die alle Step-Felder als kompakte Karten zeigt.
*/
import { CheckCircle2, Circle, Loader2, XCircle } from "lucide-react";
+import { useT } from "@/i18n";
import { cn } from "@/lib/utils";
import type { PlanStep } from "@/hooks/useOutputs";
@@ -17,10 +18,11 @@ const STATUS_ICON: Record<string, JSX.Element> = {
};
export function PlanStepList({ steps }: { steps: PlanStep[] }) {
+ const t = useT();
if (!steps || steps.length === 0) {
return (
<div className="text-xs text-muted-foreground">
- Kein strukturierter Plan — Single-Shot-Run.
+ {t("plan_step_list.no_plan")}
</div>
);
}
@@ -56,7 +58,7 @@ export function PlanStepList({ steps }: { steps: PlanStep[] }) {
{s.output && s.status === "done" && (
<details className="mt-1">
<summary className="cursor-pointer text-[10px] text-muted-foreground hover:text-foreground">
- Output anzeigen
+ {t("plan_step_list.show_output")}
</summary>
<pre className="mt-1 max-h-40 overflow-auto whitespace-pre-wrap break-words rounded bg-background/40 p-2 font-mono text-[10px]">
{s.output}
diff --git a/jarvis/ui/web/frontend/src/components/ProviderSwitcher.tsx b/jarvis/ui/web/frontend/src/components/ProviderSwitcher.tsx
index 57098ed7be..e2ca091e29 100644
--- a/jarvis/ui/web/frontend/src/components/ProviderSwitcher.tsx
+++ b/jarvis/ui/web/frontend/src/components/ProviderSwitcher.tsx
@@ -11,7 +11,9 @@ import { useEventStore } from "@/store/events";
export function ProviderSwitcher() {
const t = useT();
const { providers, refetch } = useProviders();
- const brainProviders = providers.filter((p) => p.tier === "brain");
+ const brainProviders = providers.filter(
+ (p) => p.tier === "brain" && p.brain_switchable !== false,
+ );
const active = brainProviders.find((p) => p.active) ?? brainProviders[0];
const [target, setTarget] = useState(active?.id ?? "");
const [pending, setPending] = useState(false);
@@ -55,7 +57,7 @@ export function ProviderSwitcher() {
{brainProviders.map((p) => (
<option key={p.id} value={p.id} disabled={!p.configured}>
{p.label}
- {!p.configured && " — kein Credential"}
+ {!p.configured && ` — ${t("provider_switcher.no_credential")}`}
</option>
))}
</select>
@@ -64,7 +66,7 @@ export function ProviderSwitcher() {
</Button>
{active && (
<p className="text-xs text-muted-foreground">
- Aktiv: <code className="font-mono">{active.id}</code>
+ {t("provider_switcher.active")}: <code className="font-mono">{active.id}</code>
</p>
)}
</div>
diff --git a/jarvis/ui/web/frontend/src/components/SubagentSection.model.test.tsx b/jarvis/ui/web/frontend/src/components/SubagentSection.model.test.tsx
index bd02e64b3d..408bfe179b 100644
--- a/jarvis/ui/web/frontend/src/components/SubagentSection.model.test.tsx
+++ b/jarvis/ui/web/frontend/src/components/SubagentSection.model.test.tsx
@@ -30,78 +30,74 @@ const STATUS = {
mapping: [],
};
+const MODELS = {
+ provider: "claude-api",
+ current_model: "claude-sonnet-4-6",
+ models: [
+ { id: "claude-opus-4-8", label: "Claude Opus 4.8" },
+ { id: "claude-sonnet-4-6", label: "Claude Sonnet 4.6" },
+ ],
+ source: "static",
+ fetched_at: 0,
+ selects: "model",
+};
+
+function mockFetch() {
+ return vi.fn().mockImplementation(async (url: string) => {
+ const u = String(url);
+ if (u.includes("/api/openclaw/status")) return { ok: true, json: async () => STATUS };
+ if (u.includes("/models")) return { ok: true, json: async () => MODELS };
+ if (u.includes("/api/subagent/model")) {
+ return {
+ ok: true,
+ json: async () => ({
+ ok: true,
+ model: "claude-opus-4-8",
+ persisted: true,
+ restart_required: true,
+ }),
+ };
+ }
+ return { ok: true, json: async () => ({}) };
+ });
+}
+
afterEach(() => {
cleanup();
vi.restoreAllMocks();
});
-describe("SubagentSection — dedicated subagent LLM model", () => {
- it("shows the model input prefilled with the current override", async () => {
- vi.stubGlobal(
- "fetch",
- vi.fn().mockResolvedValue({ ok: true, json: async () => STATUS }),
- );
+describe("SubagentSection — dedicated subagent LLM dropdown", () => {
+ it("opens a model dropdown for the active subagent provider", async () => {
+ vi.stubGlobal("fetch", mockFetch());
render(<SubagentSection />);
-
- const input = (await screen.findByLabelText(
- "subagent_model.model_label",
- )) as HTMLInputElement;
- expect(input.value).toBe("claude-sonnet-4-6");
+ const trigger = (await screen.findByLabelText(
+ "apikeys_model.model_label",
+ )) as HTMLElement;
+ fireEvent.click(trigger);
+ expect(await screen.findByText("claude-opus-4-8")).toBeTruthy();
});
- it("saves a new model via POST /api/subagent/model", async () => {
- const fetchMock = vi.fn().mockImplementation(async (url: string) => {
- if (String(url).includes("/api/subagent/model")) {
- return {
- ok: true,
- json: async () => ({ ok: true, model: "claude-opus-4-8", persisted: true }),
- };
- }
- return { ok: true, json: async () => STATUS };
- });
+ it("saves a picked model via POST /api/subagent/model", async () => {
+ const fetchMock = mockFetch();
vi.stubGlobal("fetch", fetchMock);
render(<SubagentSection />);
-
- const input = (await screen.findByLabelText(
- "subagent_model.model_label",
- )) as HTMLInputElement;
- fireEvent.change(input, { target: { value: "claude-opus-4-8" } });
- fireEvent.click(screen.getByText("subagent_model.apply"));
+ const trigger = (await screen.findByLabelText(
+ "apikeys_model.model_label",
+ )) as HTMLElement;
+ fireEvent.click(trigger);
+ fireEvent.click(await screen.findByText("claude-opus-4-8"));
await waitFor(() => {
- const call = fetchMock.mock.calls.find(
- (c) => String(c[0]).includes("/api/subagent/model"),
+ const post = fetchMock.mock.calls.find(
+ (c) =>
+ String(c[0]).includes("/api/subagent/model") &&
+ (c[1] as RequestInit | undefined)?.method === "POST",
);
- expect(call).toBeDefined();
- expect(JSON.parse((call![1] as RequestInit).body as string)).toEqual({
- model: "claude-opus-4-8",
- persist: true,
- });
- });
- });
-
- it("empty input is a valid reset to the provider default", async () => {
- const fetchMock = vi.fn().mockImplementation(async (url: string) => {
- if (String(url).includes("/api/subagent/model")) {
- return { ok: true, json: async () => ({ ok: true, model: "", persisted: true }) };
- }
- return { ok: true, json: async () => STATUS };
- });
- vi.stubGlobal("fetch", fetchMock);
- render(<SubagentSection />);
-
- const input = (await screen.findByLabelText(
- "subagent_model.model_label",
- )) as HTMLInputElement;
- fireEvent.change(input, { target: { value: "" } });
- fireEvent.click(screen.getByText("subagent_model.apply"));
-
- await waitFor(() => {
- const call = fetchMock.mock.calls.find(
- (c) => String(c[0]).includes("/api/subagent/model"),
+ expect(post).toBeDefined();
+ expect(JSON.parse((post![1] as RequestInit).body as string).model).toBe(
+ "claude-opus-4-8",
);
- expect(call).toBeDefined();
- expect(JSON.parse((call![1] as RequestInit).body as string).model).toBe("");
});
});
});
diff --git a/jarvis/ui/web/frontend/src/components/SubagentSection.tsx b/jarvis/ui/web/frontend/src/components/SubagentSection.tsx
index 90f46a8f74..7dc2c523df 100644
--- a/jarvis/ui/web/frontend/src/components/SubagentSection.tsx
+++ b/jarvis/ui/web/frontend/src/components/SubagentSection.tsx
@@ -1,16 +1,26 @@
import { useCallback, useEffect, useState } from "react";
-import { Bot, CheckCircle2, XCircle } from "lucide-react";
+import { ArrowUp, Bot, CheckCircle2, Lock, LogIn, LogOut, Terminal, XCircle } from "lucide-react";
import { cn } from "@/lib/utils";
import { useT } from "@/i18n";
import { useEventStore } from "@/store/events";
-import { saveSubagentModel, switchSubagentProvider } from "@/hooks/useProviders";
+import {
+ codexLogout,
+ loginAntigravity,
+ logoutAntigravity,
+ saveSubagentModel,
+ startCodexLogin,
+ switchSubagentProvider,
+ type AntigravityStatus,
+ type CodexStatus,
+} from "@/hooks/useProviders";
+import { BrainModelSelector } from "@/components/BrainModelSelector";
/**
* Subagent tier for the API-Keys view.
*
* Visually a sibling of the brain/tts/stt tiers in `ApiKeysView`: the same
* tier header + `card-outline` cards + identical `StatusBadge` styling. Each
- * provider card carries the same "Als aktiv" radio as the API-key tiers, so
+ * provider card carries the same "Set active" radio as the API-key tiers, so
* the user can switch the Heavy-Task subagent provider seamlessly instead of
* being stuck on one. There is no key input — sub-agent workers reuse the
* brain-provider keys entered above (`key_set` mirrors that state).
@@ -58,25 +68,44 @@ const PROVIDER_LABELS: Record<string, string> = {
"claude-api": "Anthropic Claude",
openai: "OpenAI",
openrouter: "OpenRouter",
- grok: "xAI Grok",
// Codex is a direct worker (ChatGPT subscription / OpenAI key), not an
// OpenClaw-routed provider — surfaced as its own selectable subagent row.
"openai-codex": "OpenAI Codex",
+ // Antigravity drives the Google subscription CLI as a direct worker (OAuth, no
+ // API key), the Google sibling of Codex.
+ antigravity: "Antigravity (Google subscription)",
};
export function SubagentSection() {
const t = useT();
const [bridge, setBridge] = useState<SubagentStatus | null>(null);
+ const [codexStatus, setCodexStatus] = useState<CodexStatus | null>(null);
+ const [antigravityStatus, setAntigravityStatus] =
+ useState<AntigravityStatus | null>(null);
const [error, setError] = useState<string | null>(null);
// Re-fetch on brain-switch / subagent-switch / secret-set so the active
// provider highlight + the per-provider "Key gesetzt" badges track live.
const reload = useCallback(async () => {
try {
- const res = await fetch("/api/openclaw/status");
+ const [res, codexRes, antigravityRes] = await Promise.all([
+ fetch("/api/openclaw/status"),
+ fetch("/api/codex/status").catch(() => null),
+ fetch("/api/antigravity/status").catch(() => null),
+ ]);
if (!res.ok) throw new Error(`HTTP ${res.status}`);
const data: SubagentStatus = await res.json();
setBridge(data);
+ if (codexRes?.ok) {
+ setCodexStatus(await codexRes.json());
+ } else {
+ setCodexStatus(null);
+ }
+ if (antigravityRes?.ok) {
+ setAntigravityStatus(await antigravityRes.json());
+ } else {
+ setAntigravityStatus(null);
+ }
setError(null);
} catch (e) {
setError((e as Error).message);
@@ -100,7 +129,7 @@ export function SubagentSection() {
return (
<section>
<SectionHeader label={t("apikeys_view.tier_subagent")} />
- <p className="text-xs text-destructive">Status nicht ladbar: {error}</p>
+ <p className="text-xs text-destructive">Status unavailable: {error}</p>
</section>
);
}
@@ -110,6 +139,20 @@ export function SubagentSection() {
return (
<section>
<SectionHeader label={t("apikeys_view.tier_subagent")} />
+ {/* The coupling is non-obvious: subagent providers have no key field of
+ their own — they reuse the Brain-provider keys set above. Spell it out
+ so users know where to add the key instead of looking for an input
+ that isn't here. */}
+ <p className="mb-3 flex items-start gap-2 rounded-md border border-primary/25 bg-primary/[0.04] px-3 py-2 text-[11px] leading-relaxed text-muted-foreground">
+ <ArrowUp className="mt-0.5 h-3.5 w-3.5 shrink-0 text-primary" />
+ <span>
+ Most subagents reuse the API keys from the{" "}
+ <strong className="text-foreground">Brain</strong> section above.
+ Codex uses the ChatGPT login here, and Antigravity uses the Google
+ login here. Connect the provider first, then pick which one runs heavy
+ background tasks.
+ </span>
+ </p>
<ul className="space-y-3">
<li>
<BridgeCard status={bridge} />
@@ -117,6 +160,19 @@ export function SubagentSection() {
<li>
<SubagentModelCard status={bridge} onSaved={reload} />
</li>
+ {bridge.mapping.some((row) => row.jarvis === "openai-codex") && (
+ <li>
+ <CodexConnectionCard status={codexStatus} onChanged={reload} />
+ </li>
+ )}
+ {bridge.mapping.some((row) => row.jarvis === "antigravity") && (
+ <li>
+ <AntigravityConnectionCard
+ status={antigravityStatus}
+ onChanged={reload}
+ />
+ </li>
+ )}
{bridge.mapping.map((row) => (
<li key={row.jarvis}>
<SubagentProviderCard row={row} onSwitched={reload} />
@@ -133,6 +189,13 @@ export function SubagentSection() {
* (frontier) model — shown in the hint via `model_resolved` — and a concrete
* id overrides it for every heavy-task worker spawn.
*/
+/**
+ * The dedicated subagent LLM model pin — the SAME dropdown as the brain cards,
+ * showing the active subagent provider's catalog (``brain_primary``) and saving
+ * through the subagent endpoint (POST /api/subagent/model) instead of the
+ * per-provider model route. Empty selection = the provider's deep/frontier model
+ * (shown in the hint via ``model_resolved``).
+ */
function SubagentModelCard({
status,
onSaved,
@@ -141,63 +204,41 @@ function SubagentModelCard({
onSaved: () => void;
}) {
const t = useT();
- const pushToast = useEventStore((s) => s.pushToast);
- const [model, setModel] = useState<string | null>(null);
- const [pending, setPending] = useState(false);
-
- // Controlled value falls back to the server state until the user edits it.
- const value = model ?? status.sub_model_override ?? "";
-
- async function handleApply() {
- setPending(true);
- try {
- const next = await saveSubagentModel(value.trim());
- setModel(null);
- pushToast(
- "success",
- next.restart_required
- ? t("subagent_model.saved_restart")
- : t("subagent_model.saved"),
- );
- window.dispatchEvent(new Event("jarvis:subagent-switched"));
- onSaved();
- } catch (e) {
- pushToast("error", (e as Error).message);
- } finally {
- setPending(false);
- }
- }
-
+ // The subagent worker slug → the catalog provider id (Codex's worker slug
+ // "openai-codex" maps to the catalog's "codex"; all others match 1:1).
+ const catalogProvider =
+ status.brain_primary === "openai-codex" ? "codex" : status.brain_primary;
return (
<div className="card-outline space-y-3 p-4">
<p className="text-[11px] leading-relaxed text-muted-foreground">
{t("subagent_model.description")}
</p>
- <label className="block">
- <span className="mb-1 block text-xs uppercase tracking-wide text-muted-foreground">
- {t("subagent_model.model_label")}
- </span>
- <input
- type="text"
- aria-label={t("subagent_model.model_label")}
- value={value}
- onChange={(e) => setModel(e.target.value)}
- placeholder={t("subagent_model.model_placeholder")}
- className="w-full rounded-md border border-input bg-background px-3 py-2 font-mono text-sm"
+ {catalogProvider ? (
+ <BrainModelSelector
+ providerId={catalogProvider}
+ currentModel={status.sub_model_override ?? ""}
+ onSave={async (model) => {
+ const r = await saveSubagentModel(model);
+ window.dispatchEvent(new Event("jarvis:subagent-switched"));
+ onSaved();
+ return {
+ ok: true,
+ provider: status.brain_primary,
+ model,
+ persisted: r.persisted,
+ applied_live: false,
+ restart_required: r.restart_required,
+ probe: null,
+ };
+ }}
/>
- <span className="mt-1 block text-[11px] text-muted-foreground">
- {t("subagent_model.model_hint")}
- {status.model_resolved ? ` (${status.model_resolved})` : ""}
- </span>
- </label>
- <button
- type="button"
- onClick={handleApply}
- disabled={pending}
- className="w-full rounded-md bg-primary px-3 py-2 text-sm font-medium text-primary-foreground disabled:opacity-50"
- >
- {pending ? t("subagent_model.applying") : t("subagent_model.apply")}
- </button>
+ ) : (
+ <p className="text-[11px] text-muted-foreground">{t("subagent_model.model_hint")}</p>
+ )}
+ <p className="text-[11px] text-muted-foreground">
+ {t("subagent_model.model_hint")}
+ {status.model_resolved ? ` (${status.model_resolved})` : ""}
+ </p>
</div>
);
}
@@ -214,44 +255,44 @@ function SectionHeader({ label }: { label: string }) {
* The subagent bridge meta-card — read-only configuration (engine state, pin,
* active worker, model, time-cap). Shares the active-card highlight with
* the provider cards so the section reads as one system. Engine internals
- * (binary path etc.) are reduced to an "installiert"/"nicht installiert"
+ * (binary path etc.) are reduced to an "installed"/"not installed"
* status — the concrete path is developer noise and is not surfaced.
*/
function BridgeCard({ status }: { status: SubagentStatus }) {
const installed = Boolean(status.binary_detected);
const live = status.enabled && installed;
const stateLabel = !status.configured
- ? "nicht konfiguriert"
+ ? "not configured"
: !installed
- ? "Engine nicht installiert"
+ ? "engine not installed"
: status.enabled
- ? "aktiviert"
- : "deaktiviert (enabled = false)";
+ ? "enabled"
+ : "disabled (enabled = false)";
const modelLabel =
status.model_resolved ??
- (status.provider_slug ? "(folgt brain.primary, kein Modell aufloesbar)" : "—");
+ (status.provider_slug ? "(follows brain.primary, no model resolvable)" : "—");
return (
<div className="card-outline space-y-3 p-4">
<div className="flex items-start justify-between gap-3">
<div className="min-w-0 flex-1">
<div className="flex flex-wrap items-center gap-2">
- <span className="font-medium">Subagent-Bridge</span>
+ <span className="font-medium">Subagent bridge</span>
{live ? (
- <span className="chip-yellow">aktiv</span>
+ <span className="chip-yellow">active</span>
) : (
<span className="rounded-full bg-muted px-2 py-0.5 text-[10px] uppercase tracking-wider text-muted-foreground">
- inaktiv
+ inactive
</span>
)}
</div>
<p className="mt-1 text-[11px] leading-relaxed text-muted-foreground">
- Externer Subagent fuer Heavy-Tasks (lies Repo, baue Feature,
- reproduziere Bug). Nutzt dieselben Brain-Provider-Keys wie unten
- &mdash; kein separates Eingabefeld noetig. Alle registrierten
- MCP-Server werden beim Pre-Boot mit Mission-isoliertem State-Dir an
- den Subagenten weitergegeben.
+ External subagent for heavy tasks (read a repo, build a feature,
+ reproduce a bug). It reuses the same brain-provider keys you set
+ above &mdash; no separate input field needed. Every registered MCP
+ server is handed to the subagent at pre-boot with a mission-isolated
+ state directory.
</p>
</div>
</div>
@@ -268,27 +309,27 @@ function BridgeCard({ status }: { status: SubagentStatus }) {
</dd>
<dt className="text-muted-foreground">Engine</dt>
- <dd className="font-mono">{installed ? "installiert" : "nicht installiert"}</dd>
+ <dd className="font-mono">{installed ? "installed" : "not installed"}</dd>
- <dt className="text-muted-foreground">Pin-Version</dt>
+ <dt className="text-muted-foreground">Pin version</dt>
<dd className="font-mono">{status.version_pin ?? "—"}</dd>
- <dt className="text-muted-foreground">Aktiver Worker</dt>
+ <dt className="text-muted-foreground">Active worker</dt>
<dd className="font-mono">
<strong>{PROVIDER_LABELS[status.brain_primary] ?? status.brain_primary}</strong>
</dd>
- <dt className="text-muted-foreground">Modell</dt>
+ <dt className="text-muted-foreground">Model</dt>
<dd className="break-all font-mono">
{modelLabel}
{status.model_override && (
- <span className="ml-2 text-muted-foreground">(Override aus Config)</span>
+ <span className="ml-2 text-muted-foreground">(override from config)</span>
)}
</dd>
{status.time_cap_min !== null && (
<>
- <dt className="text-muted-foreground">Time-Cap</dt>
+ <dt className="text-muted-foreground">Time cap</dt>
<dd className="font-mono">
{status.time_cap_min} min · max. {status.concurrency} parallel
</dd>
@@ -299,10 +340,205 @@ function BridgeCard({ status }: { status: SubagentStatus }) {
);
}
+function CodexConnectionCard({
+ status,
+ onChanged,
+}: {
+ status: CodexStatus | null;
+ onChanged: () => void | Promise<void>;
+}) {
+ const pushToast = useEventStore((s) => s.pushToast);
+ const [pending, setPending] = useState(false);
+ const connected = Boolean(status?.connected);
+ const installed = status?.installed ?? false;
+ const email =
+ status?.user_email ??
+ status?.account_label ??
+ status?.accountLabel ??
+ null;
+ const detail = connected
+ ? email
+ ? `Connected as ${email}`
+ : status?.message || "Connected via ChatGPT"
+ : status?.message || "ChatGPT login not connected";
+
+ async function connect() {
+ setPending(true);
+ try {
+ await startCodexLogin();
+ pushToast("info", "Codex login started");
+ await onChanged();
+ } catch (e) {
+ pushToast("error", (e as Error).message);
+ } finally {
+ setPending(false);
+ }
+ }
+
+ async function disconnect() {
+ setPending(true);
+ try {
+ await codexLogout();
+ pushToast("info", "Codex login disconnected");
+ await onChanged();
+ } catch (e) {
+ pushToast("error", (e as Error).message);
+ } finally {
+ setPending(false);
+ }
+ }
+
+ return (
+ <div className="card-outline space-y-3 p-4">
+ <div className="flex items-start justify-between gap-3">
+ <div className="min-w-0 flex-1">
+ <div className="flex flex-wrap items-center gap-2">
+ <span className="font-medium">OpenAI Codex ChatGPT login</span>
+ {connected ? (
+ <span className="rounded-full bg-emerald-500/10 px-2 py-0.5 text-[10px] uppercase tracking-wider text-emerald-600">
+ ready
+ </span>
+ ) : (
+ <span className="rounded-full bg-muted px-2 py-0.5 text-[10px] uppercase tracking-wider text-muted-foreground">
+ open
+ </span>
+ )}
+ </div>
+ <p className="mt-1 text-[11px] leading-relaxed text-muted-foreground">
+ {detail}
+ </p>
+ {!installed && (
+ <p className="mt-2 flex items-center gap-1.5 text-[11px] text-amber-600">
+ <Terminal className="h-3 w-3 shrink-0" />
+ <span>Install Codex before connecting.</span>
+ </p>
+ )}
+ </div>
+ {connected ? (
+ <button
+ type="button"
+ onClick={disconnect}
+ disabled={pending}
+ className="inline-flex shrink-0 items-center gap-1.5 rounded-md border border-border px-3 py-1.5 text-xs text-muted-foreground hover:text-foreground disabled:opacity-50"
+ >
+ <LogOut className="h-3.5 w-3.5" />
+ Disconnect
+ </button>
+ ) : (
+ <button
+ type="button"
+ onClick={connect}
+ disabled={pending || !installed}
+ className="inline-flex shrink-0 items-center gap-1.5 rounded-md bg-primary px-3 py-1.5 text-xs font-medium text-primary-foreground disabled:opacity-50"
+ >
+ <LogIn className="h-3.5 w-3.5" />
+ Connect
+ </button>
+ )}
+ </div>
+ </div>
+ );
+}
+
+function AntigravityConnectionCard({
+ status,
+ onChanged,
+}: {
+ status: AntigravityStatus | null;
+ onChanged: () => void | Promise<void>;
+}) {
+ const pushToast = useEventStore((s) => s.pushToast);
+ const [pending, setPending] = useState(false);
+ const connected = Boolean(status?.connected);
+ const installed = status?.installed ?? false;
+ const detail = connected
+ ? status?.user_email
+ ? `Connected as ${status.user_email}`
+ : status?.message || "Connected"
+ : status?.message || "Google login not connected";
+
+ async function connect() {
+ setPending(true);
+ try {
+ await loginAntigravity();
+ pushToast("info", "Google login started");
+ await onChanged();
+ } catch (e) {
+ pushToast("error", (e as Error).message);
+ } finally {
+ setPending(false);
+ }
+ }
+
+ async function disconnect() {
+ setPending(true);
+ try {
+ await logoutAntigravity();
+ pushToast("info", "Google login disconnected");
+ await onChanged();
+ } catch (e) {
+ pushToast("error", (e as Error).message);
+ } finally {
+ setPending(false);
+ }
+ }
+
+ return (
+ <div className="card-outline space-y-3 p-4">
+ <div className="flex items-start justify-between gap-3">
+ <div className="min-w-0 flex-1">
+ <div className="flex flex-wrap items-center gap-2">
+ <span className="font-medium">Antigravity Google login</span>
+ {connected ? (
+ <span className="rounded-full bg-emerald-500/10 px-2 py-0.5 text-[10px] uppercase tracking-wider text-emerald-600">
+ ready
+ </span>
+ ) : (
+ <span className="rounded-full bg-muted px-2 py-0.5 text-[10px] uppercase tracking-wider text-muted-foreground">
+ open
+ </span>
+ )}
+ </div>
+ <p className="mt-1 text-[11px] leading-relaxed text-muted-foreground">
+ {detail}
+ </p>
+ {!installed && (
+ <p className="mt-2 flex items-center gap-1.5 text-[11px] text-amber-600">
+ <Terminal className="h-3 w-3 shrink-0" />
+ <span>Install Antigravity or the Gemini CLI before connecting.</span>
+ </p>
+ )}
+ </div>
+ {connected ? (
+ <button
+ type="button"
+ onClick={disconnect}
+ disabled={pending}
+ className="inline-flex shrink-0 items-center gap-1.5 rounded-md border border-border px-3 py-1.5 text-xs text-muted-foreground hover:text-foreground disabled:opacity-50"
+ >
+ <LogOut className="h-3.5 w-3.5" />
+ Disconnect
+ </button>
+ ) : (
+ <button
+ type="button"
+ onClick={connect}
+ disabled={pending || !installed}
+ className="inline-flex shrink-0 items-center gap-1.5 rounded-md bg-primary px-3 py-1.5 text-xs font-medium text-primary-foreground disabled:opacity-50"
+ >
+ <LogIn className="h-3.5 w-3.5" />
+ Connect
+ </button>
+ )}
+ </div>
+ </div>
+ );
+}
+
/**
* One sub-agent-capable provider, styled to match the `ProviderCard` in
* `ApiKeysView` (header + badge + id·auth sub-line + active highlight + the
- * "Als aktiv" radio). Clicking the card or the radio switches the Heavy-Task
+ * "Set active" radio). Clicking the card or the radio switches the Heavy-Task
* subagent provider via `POST /api/subagent/switch` (3-layer persist). The key
* itself is managed by the brain-provider card above; a provider with no key
* cannot be activated (warning toast instead of a silent no-op).
@@ -323,7 +559,11 @@ function SubagentProviderCard({
if (!row.key_set) {
pushToast(
"warning",
- `${label}: erst den API-Key oben beim Brain-Provider setzen.`,
+ row.jarvis === "openai-codex"
+ ? `${label}: connect the ChatGPT login above first.`
+ : row.jarvis === "antigravity"
+ ? `${label}: connect the Google login above first.`
+ : `${label}: set the API key on the brain provider above first.`,
);
return;
}
@@ -331,7 +571,7 @@ function SubagentProviderCard({
try {
const result = await switchSubagentProvider(row.jarvis);
const note = result.restart_required
- ? " (aktiv ab nächstem Neustart)"
+ ? " (active from next restart)"
: "";
pushToast("success", `Subagent → ${label}${note}`);
window.dispatchEvent(new CustomEvent("jarvis:subagent-switched"));
@@ -359,10 +599,10 @@ function SubagentProviderCard({
onDoubleClick={handleCardActivate}
title={
row.is_active_brain
- ? "Dieser Subagent-Provider ist aktiv"
+ ? "This subagent provider is active"
: row.key_set
- ? "Diesen Subagent-Provider aktivieren"
- : "Erst API-Key setzen"
+ ? "Activate this subagent provider"
+ : "Set an API key first"
}
className={cn(
"card-outline space-y-2 p-4 transition-colors",
@@ -399,9 +639,26 @@ function SubagentProviderCard({
</div>
{!row.key_set && (
- <p className="text-[11px] text-muted-foreground">
- Key fehlt &mdash; oben beim Brain-Provider setzen, dann ist dieser
- Subagent einsatzbereit.
+ <p className="flex items-center gap-1.5 text-[11px] text-amber-600">
+ <Lock className="h-3 w-3 shrink-0" />
+ <span>
+ {row.jarvis === "openai-codex" ? (
+ <>
+ Locked &mdash; connect <strong>{label}</strong> with ChatGPT above
+ to unlock it.
+ </>
+ ) : row.jarvis === "antigravity" ? (
+ <>
+ Locked &mdash; connect <strong>{label}</strong> with Google above
+ to unlock it.
+ </>
+ ) : (
+ <>
+ Locked &mdash; add the <strong>{label}</strong> key in the Brain
+ section above to unlock it.
+ </>
+ )}
+ </span>
</p>
)}
</div>
@@ -426,10 +683,10 @@ function SubagentActiveControl({
onActivate: () => void;
}) {
const labelTitle = row.is_active_brain
- ? "Dieser Subagent-Provider ist aktiv"
+ ? "This subagent provider is active"
: row.key_set
- ? "Diesen Subagent-Provider aktivieren"
- : "Erst API-Key setzen";
+ ? "Activate this subagent provider"
+ : "Set an API key first";
return (
<label
@@ -453,28 +710,28 @@ function SubagentActiveControl({
disabled={activating}
className="accent-primary"
/>
- {activating ? "Aktiviere…" : "Als aktiv"}
+ {activating ? "Activating…" : "Set active"}
</label>
);
}
/**
* Mirrors the three StatusBadge variants from `ApiKeysView` (chip-yellow
- * "aktiv" / emerald "eingerichtet" / muted "offen") so the subagent cards are
+ * "active" / emerald "ready" / muted "open") so the subagent cards are
* visually indistinguishable from the API-key cards above.
*/
function SubagentStatusBadge({ row }: { row: SubagentMappingRow }) {
- if (row.is_active_brain) return <span className="chip-yellow">aktiv</span>;
+ if (row.is_active_brain) return <span className="chip-yellow">active</span>;
if (row.key_set) {
return (
<span className="rounded-full bg-emerald-500/10 px-2 py-0.5 text-[10px] uppercase tracking-wider text-emerald-600">
- eingerichtet
+ ready
</span>
);
}
return (
<span className="rounded-full bg-muted px-2 py-0.5 text-[10px] uppercase tracking-wider text-muted-foreground">
- offen
+ open
</span>
);
}
diff --git a/jarvis/ui/web/frontend/src/components/ViewErrorBoundary.tsx b/jarvis/ui/web/frontend/src/components/ViewErrorBoundary.tsx
index 2ff278cc5d..dc79e1c184 100644
--- a/jarvis/ui/web/frontend/src/components/ViewErrorBoundary.tsx
+++ b/jarvis/ui/web/frontend/src/components/ViewErrorBoundary.tsx
@@ -1,6 +1,7 @@
import { Component, type ErrorInfo, type ReactNode } from "react";
import { AlertTriangle, RotateCcw } from "lucide-react";
import { Button } from "@/components/ui/button";
+import { translate } from "@/i18n";
import { useEventStore } from "@/store/events";
interface ViewErrorBoundaryProps {
@@ -69,10 +70,12 @@ export class ViewErrorBoundary extends Component<
</div>
<div className="min-w-0 flex-1">
<h2 className="font-display text-base font-semibold">
- Ansicht konnte nicht geladen werden
+ {translate("view_error_boundary.title")}
</h2>
<p className="mt-1 text-sm text-muted-foreground">
- {this.props.viewName} ist abgestuerzt. {useEventStore.getState().assistantName} bleibt bedienbar.
+ {this.props.viewName} {translate("view_error_boundary.crashed_prefix")}{" "}
+ {useEventStore.getState().assistantName}{" "}
+ {translate("view_error_boundary.crashed_suffix")}
</p>
{this.state.message && (
<pre className="mt-3 max-h-32 overflow-auto rounded-md border border-border bg-background/80 p-3 text-xs text-muted-foreground">
@@ -81,7 +84,7 @@ export class ViewErrorBoundary extends Component<
)}
<Button className="mt-4" size="sm" onClick={this.recover}>
<RotateCcw className="h-3.5 w-3.5" />
- <span className="ml-1.5">Zurueck zu Chats</span>
+ <span className="ml-1.5">{translate("view_error_boundary.back_to_chats")}</span>
</Button>
</div>
</div>
diff --git a/jarvis/ui/web/frontend/src/components/board/AchievementGrid.tsx b/jarvis/ui/web/frontend/src/components/board/AchievementGrid.tsx
index 67e2e827d9..064614c731 100644
--- a/jarvis/ui/web/frontend/src/components/board/AchievementGrid.tsx
+++ b/jarvis/ui/web/frontend/src/components/board/AchievementGrid.tsx
@@ -2,6 +2,7 @@ import { useEffect } from "react";
import { useQueryClient } from "@tanstack/react-query";
import { Award, Lock, Sparkles } from "lucide-react";
import { useAchievements, type AchievementItem } from "@/hooks/useBoard";
+import { useT } from "@/i18n";
import { cn } from "@/lib/utils";
/**
@@ -10,6 +11,7 @@ import { cn } from "@/lib/utils";
* oeffentlichen Like-Counts); die Wand ist privat, nur der User sieht sie.
*/
export function AchievementGrid() {
+ const t = useT();
const qc = useQueryClient();
const { data, isLoading } = useAchievements();
@@ -41,7 +43,7 @@ export function AchievementGrid() {
<div className="flex-1 min-w-0">
<h3 className="font-display text-sm font-semibold">Achievements</h3>
<p className="text-xs text-muted-foreground">
- {data.unlocked} von {data.total} freigeschaltet. Kein Leaderboard.
+ {`${data.unlocked} ${t("achievement_grid.unlocked_of")} ${data.total} ${t("achievement_grid.unlocked_count")}`}
</p>
</div>
</header>
diff --git a/jarvis/ui/web/frontend/src/components/board/ActivityFeed.tsx b/jarvis/ui/web/frontend/src/components/board/ActivityFeed.tsx
index 150f228d1d..f067ebb360 100644
--- a/jarvis/ui/web/frontend/src/components/board/ActivityFeed.tsx
+++ b/jarvis/ui/web/frontend/src/components/board/ActivityFeed.tsx
@@ -7,8 +7,10 @@ import {
import { ReactionBar } from "@/components/board/ReactionBar";
import { StoryComposer } from "@/components/board/StoryComposer";
import { cn } from "@/lib/utils";
+import { useT } from "@/i18n";
export function ActivityFeed() {
+ const t = useT();
const [sort, setSort] = useState<"interesting" | "latest">("interesting");
const [composerOpen, setComposerOpen] = useState(false);
const feed = useFeed(sort);
@@ -22,13 +24,13 @@ export function ActivityFeed() {
return (
<section className="space-y-4 rounded-xl border border-border bg-card/30 p-5 backdrop-blur">
<header className="flex flex-wrap items-center gap-3">
- <h3 className="font-display text-sm font-semibold flex-1">Activity-Feed</h3>
+ <h3 className="font-display text-sm font-semibold flex-1">{t("activity_feed.title")}</h3>
<SortToggle value={sort} onChange={setSort} />
<button
type="button"
onClick={() => feed.refetch()}
className="inline-flex items-center gap-1 rounded-md border border-border px-2.5 py-1 text-[11px] hover:border-primary/40"
- title="Manueller Refresh"
+ title={t("activity_feed.refresh_tooltip")}
>
<RefreshCw className={cn("h-3 w-3", feed.isFetching && "animate-spin")} />
Refresh
@@ -45,7 +47,7 @@ export function ActivityFeed() {
{feed.isLoading && (
<div className="flex items-center gap-2 text-xs text-muted-foreground">
- <Loader2 className="h-3 w-3 animate-spin" /> Lade Feed…
+ <Loader2 className="h-3 w-3 animate-spin" /> {t("activity_feed.loading")}
</div>
)}
{feed.isError && (
@@ -56,7 +58,7 @@ export function ActivityFeed() {
{feed.data?.items.length === 0 && (
<div className="rounded-md border border-dashed border-border/60 p-4 text-xs text-muted-foreground">
- Noch keine Items. Pair' deinen ersten Friend, oder schreib eine Story.
+ {t("activity_feed.empty")}
</div>
)}
diff --git a/jarvis/ui/web/frontend/src/components/board/FriendsList.tsx b/jarvis/ui/web/frontend/src/components/board/FriendsList.tsx
index 4f1fd5f615..56cb4552a1 100644
--- a/jarvis/ui/web/frontend/src/components/board/FriendsList.tsx
+++ b/jarvis/ui/web/frontend/src/components/board/FriendsList.tsx
@@ -2,6 +2,7 @@ import { useState } from "react";
import { Loader2, Sparkles } from "lucide-react";
import { useFriendsList, useUpdateFriend, type FriendItem } from "@/hooks/useFederation";
import { cn } from "@/lib/utils";
+import { useT } from "@/i18n";
const INTERVAL_PRESETS_S = [60, 120, 300, 900];
@@ -12,6 +13,7 @@ const INTERVAL_PRESETS_S = [60, 120, 300, 900];
* ist 60..3600 s; wir bieten vier sinnvolle Presets statt freiem Input.
*/
export function FriendsList() {
+ const t = useT();
const friends = useFriendsList();
const update = useUpdateFriend();
const [pendingPubkey, setPendingPubkey] = useState<string | null>(null);
@@ -24,7 +26,7 @@ export function FriendsList() {
if (friends.data.friends.length === 0) {
return (
<div className="rounded-md border border-dashed border-border/60 p-3 text-xs text-muted-foreground">
- Noch keine Freunde. Klick „Pair" oben rechts um einen Link zu generieren.
+ {t("friends_list.empty")}
</div>
);
}
@@ -53,6 +55,7 @@ function FriendRow({
isPending: boolean;
onUpdateInterval: (s: number) => void;
}) {
+ const t = useT();
return (
<li className="rounded-md border border-border bg-background/40 p-3 text-xs">
<div className="flex items-start gap-3">
@@ -66,16 +69,16 @@ function FriendRow({
</code>
</div>
<div className="text-right text-[10px] text-muted-foreground">
- <div>seit {new Date(item.paired_at).toLocaleDateString("de-DE")}</div>
+ <div>{`${t("friends_list.since")} ${new Date(item.paired_at).toLocaleDateString("de-DE")}`}</div>
{item.last_pull_at && (
- <div>letzter Pull {timeSince(item.last_pull_at)}</div>
+ <div>{`${t("friends_list.last_pull")} ${timeSince(item.last_pull_at)}`}</div>
)}
</div>
</div>
<div className="mt-2 flex items-center gap-2">
<span className="text-[10px] uppercase tracking-wider text-muted-foreground">
- Pull alle
+ {t("friends_list.pull_every")}
</span>
<div className="flex gap-1">
{INTERVAL_PRESETS_S.map((s) => (
diff --git a/jarvis/ui/web/frontend/src/components/board/PairDialog.tsx b/jarvis/ui/web/frontend/src/components/board/PairDialog.tsx
index 7bec91c905..a7d7fa78bf 100644
--- a/jarvis/ui/web/frontend/src/components/board/PairDialog.tsx
+++ b/jarvis/ui/web/frontend/src/components/board/PairDialog.tsx
@@ -43,7 +43,7 @@ export function PairDialog({ onClose }: PairDialogProps) {
<div className="flex h-8 w-8 items-center justify-center rounded-lg border border-primary/40 bg-primary/10 text-primary">
<KeyRound className="h-4 w-4" />
</div>
- <h3 className="font-display text-base font-semibold flex-1">Friend pairen</h3>
+ <h3 className="font-display text-base font-semibold flex-1">{t("pair_dialog.title")}</h3>
<button type="button" onClick={onClose} aria-label={t("common.close")}
className="text-muted-foreground hover:text-foreground">
<X className="h-4 w-4" />
@@ -57,21 +57,20 @@ export function PairDialog({ onClose }: PairDialogProps) {
"flex-1 rounded px-3 py-1.5 text-xs transition-colors",
mode === "generate" ? "bg-primary/15 text-primary" : "text-muted-foreground"
)}
- >Ich lade ein</button>
+ >{t("pair_dialog.mode_invite")}</button>
<button
onClick={() => setMode("accept")}
className={cn(
"flex-1 rounded px-3 py-1.5 text-xs transition-colors",
mode === "accept" ? "bg-primary/15 text-primary" : "text-muted-foreground"
)}
- >Ich folge einem Link</button>
+ >{t("pair_dialog.mode_follow")}</button>
</div>
{mode === "generate" && (
<div className="space-y-3">
<p className="text-xs text-muted-foreground">
- Erzeuge einen 10-Minuten-Pair-Link und schicke ihn deinem Freund
- uebers Signal/Threema/SMS — irgendeinen privaten Kanal.
+ {t("pair_dialog.generate_hint")}
</p>
<button
type="button"
@@ -80,7 +79,7 @@ export function PairDialog({ onClose }: PairDialogProps) {
className="inline-flex items-center gap-2 rounded-md border border-primary/40 bg-primary/10 px-3 py-1.5 text-xs font-medium text-primary hover:bg-primary/20"
>
{initiate.isPending && <Loader2 className="h-3 w-3 animate-spin" />}
- Link generieren
+ {t("pair_dialog.generate_button")}
</button>
{initiate.data && (
<div className="space-y-3 rounded-lg border border-border bg-background/40 p-3">
@@ -109,17 +108,17 @@ export function PairDialog({ onClose }: PairDialogProps) {
}}
className="inline-flex items-center gap-1 text-[10px] text-muted-foreground hover:text-foreground"
>
- <Copy className="h-3 w-3" />{copied ? "kopiert" : "kopieren"}
+ <Copy className="h-3 w-3" />{copied ? t("pair_dialog.copied") : t("pair_dialog.copy")}
</button>
</div>
<div className="text-[10px] text-muted-foreground">
- Gueltig bis: {new Date(initiate.data.expires_at).toLocaleString("de-DE")}
+ {`${t("pair_dialog.valid_until")} ${new Date(initiate.data.expires_at).toLocaleString("de-DE")}`}
</div>
</div>
)}
{initiate.isError && (
<div className="text-xs text-destructive">
- Fehler: {(initiate.error as Error).message}
+ {`${t("pair_dialog.error_prefix")} ${(initiate.error as Error).message}`}
</div>
)}
</div>
@@ -128,7 +127,7 @@ export function PairDialog({ onClose }: PairDialogProps) {
{mode === "accept" && (
<div className="space-y-3">
<p className="text-xs text-muted-foreground">
- Fuege hier den Pair-Link ein, den dir dein Freund geschickt hat.
+ {t("pair_dialog.accept_hint")}
</p>
<input
type="url"
@@ -144,16 +143,16 @@ export function PairDialog({ onClose }: PairDialogProps) {
className="inline-flex items-center gap-2 rounded-md border border-primary/40 bg-primary/10 px-3 py-1.5 text-xs font-medium text-primary hover:bg-primary/20 disabled:opacity-50"
>
{accept.isPending && <Loader2 className="h-3 w-3 animate-spin" />}
- Pair ausfuehren
+ {t("pair_dialog.accept_button")}
</button>
{accept.data && (
<div className="rounded-md border border-emerald-500/30 bg-emerald-500/5 p-2 text-xs text-emerald-200">
- Gepairt mit {accept.data.owner_display_name}.
+ {`${t("pair_dialog.paired_with")} ${accept.data.owner_display_name}.`}
</div>
)}
{accept.isError && (
<div className="text-xs text-destructive">
- Fehler: {(accept.error as Error).message}
+ {`${t("pair_dialog.error_prefix")} ${(accept.error as Error).message}`}
</div>
)}
</div>
diff --git a/jarvis/ui/web/frontend/src/components/board/StoryComposer.tsx b/jarvis/ui/web/frontend/src/components/board/StoryComposer.tsx
index 3db1e4f57b..e8e3c02ba7 100644
--- a/jarvis/ui/web/frontend/src/components/board/StoryComposer.tsx
+++ b/jarvis/ui/web/frontend/src/components/board/StoryComposer.tsx
@@ -29,7 +29,7 @@ export function StoryComposer({ onClose }: StoryComposerProps) {
>
<header className="mb-3 flex items-center gap-3">
<h3 className="font-display text-sm font-semibold flex-1">
- Story schreiben
+ {t("story_composer.title")}
</h3>
<button type="button" onClick={onClose} aria-label={t("story_composer.close")}
className="text-muted-foreground hover:text-foreground">
@@ -41,13 +41,13 @@ export function StoryComposer({ onClose }: StoryComposerProps) {
value={text}
onChange={(e) => setText(e.target.value.slice(0, MAX_CHARS))}
rows={4}
- placeholder="Was hast du heute gemacht?"
+ placeholder={t("story_composer.placeholder")}
className="w-full resize-none rounded-md border border-border bg-background/40 px-3 py-2 text-sm"
/>
<div className="mt-1 flex items-center justify-between text-[10px] text-muted-foreground">
- <span>Verschwindet nach 24 Stunden.</span>
+ <span>{t("story_composer.expiry_hint")}</span>
<span className={cn(remaining < 30 && "text-amber-400")}>
- {remaining} Zeichen
+ {`${remaining} ${t("story_composer.characters")}`}
</span>
</div>
@@ -59,7 +59,7 @@ export function StoryComposer({ onClose }: StoryComposerProps) {
<button
onClick={onClose}
className="rounded-md px-3 py-1.5 text-xs text-muted-foreground hover:text-foreground"
- >Abbrechen</button>
+ >{t("common.cancel")}</button>
<button
type="button"
disabled={create.isPending || text.trim().length === 0}
@@ -72,12 +72,12 @@ export function StoryComposer({ onClose }: StoryComposerProps) {
className="inline-flex items-center gap-2 rounded-md border border-primary/40 bg-primary/10 px-3 py-1.5 text-xs font-medium text-primary hover:bg-primary/20 disabled:opacity-50"
>
{create.isPending ? <Loader2 className="h-3 w-3 animate-spin" /> : <Send className="h-3 w-3" />}
- Posten
+ {t("story_composer.post")}
</button>
</div>
{create.isError && (
<div className="mt-2 text-xs text-destructive">
- Fehler: {(create.error as Error).message}
+ {`${t("story_composer.error_prefix")} ${(create.error as Error).message}`}
</div>
)}
</div>
@@ -88,10 +88,11 @@ export function StoryComposer({ onClose }: StoryComposerProps) {
export function VisibilityRadios({
value, onChange,
}: { value: Visibility; onChange: (v: Visibility) => void }) {
+ const t = useT();
const opts: { v: Visibility; label: string; hint: string }[] = [
- { v: "private", label: "Privat", hint: "Nur du" },
- { v: "friends", label: "Freunde", hint: "Gepairte Friends" },
- { v: "public", label: "Oeffentlich", hint: "Jeder, der dein Backend kennt" },
+ { v: "private", label: t("story_composer.visibility_private"), hint: t("story_composer.visibility_private_hint") },
+ { v: "friends", label: t("story_composer.visibility_friends"), hint: t("story_composer.visibility_friends_hint") },
+ { v: "public", label: t("story_composer.visibility_public"), hint: t("story_composer.visibility_public_hint") },
];
return (
<div className="grid grid-cols-3 gap-1.5">
diff --git a/jarvis/ui/web/frontend/src/components/docs/DocsContent.tsx b/jarvis/ui/web/frontend/src/components/docs/DocsContent.tsx
index def463cc71..0c7d374b83 100644
--- a/jarvis/ui/web/frontend/src/components/docs/DocsContent.tsx
+++ b/jarvis/ui/web/frontend/src/components/docs/DocsContent.tsx
@@ -215,6 +215,7 @@ function NavCard({
direction: "prev" | "next";
onSelect?: (slug: string) => void;
}) {
+ const t = useT();
if (!doc) return <div />;
const Icon = direction === "prev" ? ChevronLeft : ChevronRight;
const align = direction === "next" ? "text-right items-end" : "items-start";
@@ -226,7 +227,7 @@ function NavCard({
>
<span className="flex items-center gap-1 text-[10px] uppercase tracking-wider text-muted-foreground">
{direction === "prev" ? <Icon className="h-3 w-3" /> : null}
- {direction === "prev" ? "Vorher" : "Naechstes"}
+ {direction === "prev" ? t("docs_content.prev") : t("docs_content.next")}
{direction === "next" ? <Icon className="h-3 w-3" /> : null}
</span>
<span className="text-sm font-medium">{doc.title}</span>
diff --git a/jarvis/ui/web/frontend/src/components/docs/DocsSearchModal.tsx b/jarvis/ui/web/frontend/src/components/docs/DocsSearchModal.tsx
index c47d0b472b..0cb48bbc0d 100644
--- a/jarvis/ui/web/frontend/src/components/docs/DocsSearchModal.tsx
+++ b/jarvis/ui/web/frontend/src/components/docs/DocsSearchModal.tsx
@@ -107,11 +107,11 @@ export function DocsSearchModal({ open, onOpenChange, onSelect }: Props) {
<div className="flex items-center justify-between border-t border-border bg-muted/20 px-3 py-1.5 text-[10px] text-muted-foreground">
<span>
<kbd className="rounded border border-border px-1 font-medium">↑↓</kbd>{" "}
- navigieren
+ {t("docs_search_modal.navigate")}
</span>
<span>
<kbd className="rounded border border-border px-1 font-medium">↵</kbd>{" "}
- oeffnen
+ {t("docs_search_modal.open")}
</span>
</div>
</Command>
diff --git a/jarvis/ui/web/frontend/src/components/docs/DocsSidebar.tsx b/jarvis/ui/web/frontend/src/components/docs/DocsSidebar.tsx
index dc076fa9de..b948dbb4b9 100644
--- a/jarvis/ui/web/frontend/src/components/docs/DocsSidebar.tsx
+++ b/jarvis/ui/web/frontend/src/components/docs/DocsSidebar.tsx
@@ -60,7 +60,7 @@ export function DocsSidebar({ selectedSlug, onSelect, onOpenSearch }: Props) {
<div className="border-b border-border px-3 py-3">
<div className="mb-2 flex items-center justify-between">
<h2 className="text-sm font-semibold tracking-tight">
- Dokumentation
+ {t("docs_sidebar.title")}
</h2>
<button
type="button"
@@ -82,9 +82,9 @@ export function DocsSidebar({ selectedSlug, onSelect, onOpenSearch }: Props) {
/>
<p className="mt-1 text-[11px] text-muted-foreground">
{isLoading
- ? "lade…"
+ ? t("common.loading")
: error
- ? "Fehler"
+ ? t("docs_sidebar.error")
: `${totalCount} Doc${totalCount === 1 ? "" : "s"}`}
</p>
</div>
@@ -97,7 +97,7 @@ export function DocsSidebar({ selectedSlug, onSelect, onOpenSearch }: Props) {
<div className="mb-2">
<div className="flex w-full items-center gap-1 rounded-md px-2 py-1 text-[11px] font-semibold uppercase tracking-wider text-muted-foreground">
<Clock className="h-3 w-3" />
- <span>Zuletzt geoeffnet</span>
+ <span>{t("docs.recent")}</span>
<span className="ml-auto text-[10px] font-normal text-muted-foreground/70">
{recent.length}
</span>
diff --git a/jarvis/ui/web/frontend/src/components/friends/AddFriendMenu.tsx b/jarvis/ui/web/frontend/src/components/friends/AddFriendMenu.tsx
index c70a27bef8..27f366e89f 100644
--- a/jarvis/ui/web/frontend/src/components/friends/AddFriendMenu.tsx
+++ b/jarvis/ui/web/frontend/src/components/friends/AddFriendMenu.tsx
@@ -2,6 +2,7 @@ import { useState, type FormEvent } from "react";
import { Loader2, MessageCircle, Plus, Users, Zap } from "lucide-react";
import { useCreateFriend, useLinkChannel } from "@/hooks/useFriends";
+import { useT } from "@/i18n";
import { cn } from "@/lib/utils";
/**
@@ -25,6 +26,7 @@ export function AddFriendMenu({
onClose: () => void;
onPairOpen: () => void;
}) {
+ const t = useT();
const [mode, setMode] = useState<Mode>("telegram");
const [displayName, setDisplayName] = useState("");
const [handle, setHandle] = useState("");
@@ -47,14 +49,14 @@ export function AddFriendMenu({
const name = displayName.trim();
const value = handle.trim();
if (!name) {
- setError("Bitte einen Namen eintragen.");
+ setError(t("add_friend_menu.error_name_required"));
return;
}
if ((mode === "telegram" || mode === "jarvis_pubkey") && !value) {
setError(
mode === "telegram"
- ? "Telegram-Chat-ID fehlt."
- : "Jarvis-Pubkey fehlt."
+ ? t("add_friend_menu.error_telegram_id_missing")
+ : t("add_friend_menu.error_pubkey_missing")
);
return;
}
@@ -81,7 +83,7 @@ export function AddFriendMenu({
<header className="flex items-center justify-between border-b border-border px-5 py-3">
<h2 className="flex items-center gap-2 font-display text-sm font-semibold">
<Plus className="h-4 w-4 text-primary" />
- Friend hinzufuegen
+ {t("add_friend_menu.title")}
</h2>
<button
type="button"
@@ -91,7 +93,7 @@ export function AddFriendMenu({
}}
className="text-xs text-muted-foreground hover:text-foreground"
>
- schliessen
+ {t("common.close")}
</button>
</header>
@@ -119,8 +121,7 @@ export function AddFriendMenu({
{mode === "link" ? (
<div className="space-y-3 px-5 py-4 text-sm text-muted-foreground">
<p>
- Pair-Link nutzt den bestehenden Pubkey-Pair-Flow ueber das
- board-backend. Tausche Token + URL mit deinem Friend aus.
+ {t("add_friend_menu.link_mode_hint")}
</p>
<button
type="button"
@@ -130,7 +131,7 @@ export function AddFriendMenu({
}}
className="w-full rounded-md border border-primary/40 bg-primary/10 px-3 py-2 text-xs uppercase tracking-wider text-primary hover:bg-primary/20"
>
- Pair-Dialog oeffnen
+ {t("add_friend_menu.open_pair_dialog")}
</button>
</div>
) : (
@@ -141,15 +142,15 @@ export function AddFriendMenu({
value={displayName}
onChange={(e) => setDisplayName(e.target.value)}
className="w-full rounded-md border border-border bg-background px-3 py-2 text-sm focus:border-primary/40 focus:outline-none"
- placeholder="z.B. Daniel"
+ placeholder={t("add_friend_menu.name_placeholder")}
autoFocus
/>
</FieldLabel>
<FieldLabel
label={
mode === "telegram"
- ? "Telegram-Chat-ID"
- : "Jarvis-Pubkey (hex)"
+ ? t("add_friend_menu.label_telegram_id")
+ : t("add_friend_menu.label_pubkey")
}
>
<input
@@ -158,7 +159,9 @@ export function AddFriendMenu({
onChange={(e) => setHandle(e.target.value)}
className="w-full rounded-md border border-border bg-background px-3 py-2 font-mono text-xs focus:border-primary/40 focus:outline-none"
placeholder={
- mode === "telegram" ? "z.B. 123456789" : "z.B. 4f3c2b..."
+ mode === "telegram"
+ ? t("add_friend_menu.telegram_id_placeholder")
+ : t("add_friend_menu.pubkey_placeholder")
}
/>
</FieldLabel>
@@ -175,7 +178,7 @@ export function AddFriendMenu({
{(createFriend.isPending || linkChannel.isPending) && (
<Loader2 className="h-3 w-3 animate-spin" />
)}
- Hinzufuegen
+ {t("add_friend_menu.submit")}
</button>
</form>
)}
diff --git a/jarvis/ui/web/frontend/src/components/friends/ChatThread.tsx b/jarvis/ui/web/frontend/src/components/friends/ChatThread.tsx
index 1ab4525b48..49ae7980f0 100644
--- a/jarvis/ui/web/frontend/src/components/friends/ChatThread.tsx
+++ b/jarvis/ui/web/frontend/src/components/friends/ChatThread.tsx
@@ -2,6 +2,7 @@ import { useEffect, useRef, useState, type FormEvent } from "react";
import { Loader2, Send } from "lucide-react";
import { ScrollArea } from "@/components/ui/scroll-area";
+import { useT } from "@/i18n";
import {
useFriendMessages,
useSendFriendMessage,
@@ -21,6 +22,7 @@ import { cn } from "@/lib/utils";
* Wenn der Friend keinen verknuepften Channel hat, ist der Send-Pfad disabled.
*/
export function ChatThread({ friend }: { friend: FriendDetail }) {
+ const t = useT();
const messages = useFriendMessages(friend.id);
const send = useSendFriendMessage();
const [draft, setDraft] = useState("");
@@ -55,7 +57,7 @@ export function ChatThread({ friend }: { friend: FriendDetail }) {
<SourceBadge channels={friend.channels} />
</div>
<span className="rounded-md border border-border/60 bg-muted/40 px-2 py-0.5 text-[10px] uppercase tracking-wider text-muted-foreground">
- Profil: {friend.permission_profile}
+ {t("chat_thread.profile")}: {friend.permission_profile}
</span>
</header>
@@ -83,8 +85,8 @@ export function ChatThread({ friend }: { friend: FriendDetail }) {
onChange={(e) => setDraft(e.target.value)}
placeholder={
hasChannel
- ? "Nachricht an " + friend.display_name + " ..."
- : "Kein Channel verknuepft - Outbound nicht moeglich"
+ ? `${t("chat_thread.message_to")} ${friend.display_name} ...`
+ : t("chat_thread.no_channel_placeholder")
}
disabled={!hasChannel || send.isPending}
className="flex-1 rounded-md border border-border bg-background px-3 py-2 text-sm focus:border-primary/40 focus:outline-none disabled:opacity-60"
@@ -99,13 +101,13 @@ export function ChatThread({ friend }: { friend: FriendDetail }) {
) : (
<Send className="h-3 w-3" />
)}
- Senden
+ {t("chat_thread.send")}
</button>
</form>
{send.isError && (
<div className="border-t border-destructive/40 bg-destructive/10 px-5 py-2 text-xs text-destructive">
- Senden fehlgeschlagen: {(send.error as Error).message}
+ {t("chat_thread.send_failed")}: {(send.error as Error).message}
</div>
)}
</div>
@@ -140,12 +142,13 @@ function FriendMessageBubble({ message }: { message: FriendMessage }) {
}
function EmptyThread({ hasChannel }: { hasChannel: boolean }) {
+ const t = useT();
return (
<div className="flex h-full flex-col items-center justify-center gap-2 px-8 text-center text-sm text-muted-foreground">
- <span>Noch keine Nachrichten</span>
+ <span>{t("chat_thread.no_messages")}</span>
{!hasChannel && (
<span className="rounded-md border border-dashed border-border/60 px-3 py-1 text-[11px]">
- Verknuepfe einen Channel (Telegram/Jarvis), um zu schreiben
+ {t("chat_thread.link_channel_hint")}
</span>
)}
</div>
diff --git a/jarvis/ui/web/frontend/src/components/layout/MainView.tsx b/jarvis/ui/web/frontend/src/components/layout/MainView.tsx
index 900ca82f65..892bb87db6 100644
--- a/jarvis/ui/web/frontend/src/components/layout/MainView.tsx
+++ b/jarvis/ui/web/frontend/src/components/layout/MainView.tsx
@@ -16,6 +16,7 @@ import { RunInspectorView } from "@/views/RunInspectorView";
import { SessionsView } from "@/views/SessionsView";
import { SocialsView } from "@/views/socials/SocialsView";
import { ContactsView } from "@/views/contacts/ContactsView";
+import { AgentInstructionsView } from "@/views/AgentInstructionsView";
import { TelephonySetupView } from "@/views/TelephonyView";
/**
@@ -96,6 +97,8 @@ function SwitchOnActiveSection({ active }: { active: string }) {
return <SocialsView />;
case "contacts":
return <ContactsView />;
+ case "agent-instructions":
+ return <AgentInstructionsView />;
default:
return <ChatsView />;
}
diff --git a/jarvis/ui/web/frontend/src/components/layout/Sidebar.tsx b/jarvis/ui/web/frontend/src/components/layout/Sidebar.tsx
index 2bc51a6b58..412c9f2df8 100644
--- a/jarvis/ui/web/frontend/src/components/layout/Sidebar.tsx
+++ b/jarvis/ui/web/frontend/src/components/layout/Sidebar.tsx
@@ -15,6 +15,7 @@ import {
Terminal,
Share2,
Contact,
+ ScrollText,
Loader2,
type LucideIcon,
ChevronRight,
@@ -77,6 +78,12 @@ const NAV_GROUPS: NavItem[][] = [
{ id: "memory", labelKey: "nav.wiki", icon: Notebook },
{ id: "contacts", labelKey: "nav.contacts", icon: Contact },
{ id: "profile", labelKey: "nav.profile", icon: UserCircle2 },
+ {
+ id: "agent-instructions",
+ labelKey: "nav.agent_instructions",
+ icon: ScrollText,
+ fallbackLabel: "Instructions",
+ },
{ id: "docs", labelKey: "nav.docs", icon: BookOpen },
],
// 3) Configuration. API Keys now also fronts the former "Telephony" screen —
@@ -291,7 +298,6 @@ function prettyProviderName(id: string): string {
"gemini": "Gemini",
"openai": "OpenAI",
"codex": "Codex",
- "grok": "Grok",
"mock": "Mock-Brain",
"unknown": "—",
};
diff --git a/jarvis/ui/web/frontend/src/components/missions/EventTimeline.tsx b/jarvis/ui/web/frontend/src/components/missions/EventTimeline.tsx
index f471b02783..c3f5d77e0a 100644
--- a/jarvis/ui/web/frontend/src/components/missions/EventTimeline.tsx
+++ b/jarvis/ui/web/frontend/src/components/missions/EventTimeline.tsx
@@ -9,6 +9,7 @@ import { useEffect, useMemo, useRef, useState } from "react";
import { ChevronDown, ChevronRight, Clock } from "lucide-react";
import { useShallow } from "zustand/react/shallow";
import { cn } from "@/lib/utils";
+import { useT } from "@/i18n";
import type { EventEnvelope } from "@/types/missions";
import { useMissionsStore } from "./store";
@@ -22,6 +23,7 @@ const ACTOR_COLOR: Record<string, string> = {
};
export function EventTimeline() {
+ const t = useT();
const events = useMissionsStore(
useShallow((s) => {
if (!s.selectedMissionId) return [] as EventEnvelope[];
@@ -47,7 +49,7 @@ export function EventTimeline() {
return (
<div className="flex h-full flex-col items-center justify-center gap-2 px-6 text-center text-xs text-muted-foreground">
<Clock className="h-7 w-7 text-muted-foreground/50" />
- <p>Noch keine Events fuer diese Mission.</p>
+ <p>{t("missions_view.no_events")}</p>
</div>
);
}
diff --git a/jarvis/ui/web/frontend/src/components/missions/GlobalKillButton.tsx b/jarvis/ui/web/frontend/src/components/missions/GlobalKillButton.tsx
index 7a64ee565f..51acb338df 100644
--- a/jarvis/ui/web/frontend/src/components/missions/GlobalKillButton.tsx
+++ b/jarvis/ui/web/frontend/src/components/missions/GlobalKillButton.tsx
@@ -9,11 +9,13 @@ import { useEffect, useState } from "react";
import { AlertTriangle, Loader2, Skull } from "lucide-react";
import { useMutation, useQueryClient } from "@tanstack/react-query";
import { Button } from "@/components/ui/button";
+import { useT } from "@/i18n";
import { cancelAllMissions } from "./api";
import { selectActiveCount, useMissionsStore } from "./store";
import { useShallow } from "zustand/react/shallow";
export function GlobalKillButton() {
+ const t = useT();
const [open, setOpen] = useState(false);
const qc = useQueryClient();
const activeCount = useMissionsStore(useShallow(selectActiveCount));
@@ -42,7 +44,7 @@ export function GlobalKillButton() {
size="sm"
onClick={() => setOpen(true)}
disabled={activeCount === 0 || mut.isPending}
- title="Alle laufenden Missions abbrechen"
+ title={t("global_kill_button.cancel_all_running")}
>
<Skull className="mr-1.5 h-4 w-4" />
Kill All ({activeCount})
@@ -62,16 +64,14 @@ export function GlobalKillButton() {
</div>
<div className="min-w-0 flex-1">
<h3 className="font-display text-base font-semibold">
- Alle Missions abbrechen?
+ {t("global_kill_button.cancel_all_title")}
</h3>
<p className="mt-1 text-sm text-muted-foreground">
- {activeCount} laufende Mission(s) werden hart gestoppt.
- Worker-Subprocesses werden via Job-Object terminiert; bereits
- geschriebene Diffs bleiben in den Worktrees liegen.
+ {activeCount} {t("global_kill_button.cancel_all_body")}
</p>
{mut.isError && (
<p className="mt-2 rounded border border-destructive/40 bg-destructive/10 p-2 text-xs text-destructive">
- Fehler: {(mut.error as Error).message}
+ {t("global_kill_button.error_prefix")}: {(mut.error as Error).message}
</p>
)}
</div>
@@ -83,7 +83,7 @@ export function GlobalKillButton() {
onClick={() => setOpen(false)}
disabled={mut.isPending}
>
- Abbrechen
+ {t("common.cancel")}
</Button>
<Button
variant="destructive"
@@ -94,12 +94,12 @@ export function GlobalKillButton() {
{mut.isPending ? (
<>
<Loader2 className="mr-1.5 h-4 w-4 animate-spin" />
- Stoppe…
+ {t("global_kill_button.stopping")}
</>
) : (
<>
<Skull className="mr-1.5 h-4 w-4" />
- Ja, alle stoppen
+ {t("global_kill_button.confirm_stop_all")}
</>
)}
</Button>
diff --git a/jarvis/ui/web/frontend/src/components/missions/MissionTree.tsx b/jarvis/ui/web/frontend/src/components/missions/MissionTree.tsx
index 115e04b86b..51c1d8f807 100644
--- a/jarvis/ui/web/frontend/src/components/missions/MissionTree.tsx
+++ b/jarvis/ui/web/frontend/src/components/missions/MissionTree.tsx
@@ -22,6 +22,7 @@ import {
type LucideIcon,
} from "lucide-react";
import { useShallow } from "zustand/react/shallow";
+import { useT } from "@/i18n";
import { cn } from "@/lib/utils";
import {
MISSION_STATE_BADGE,
@@ -89,6 +90,7 @@ function shortPrompt(p: string): string {
}
export function MissionTree() {
+ const t = useT();
const { missions, eventsByMission } = useMissionsStore(
useShallow((s) => ({
missions: selectMissionList(s),
@@ -109,7 +111,7 @@ export function MissionTree() {
return (
<div className="flex h-full flex-col items-center justify-center gap-2 px-6 text-center text-xs text-muted-foreground">
<Target className="h-7 w-7 text-muted-foreground/50" />
- <p>Noch keine Missions. Hauptjarvis dispatched gleich…</p>
+ <p>{t("missions_view.no_missions_yet")}</p>
</div>
);
}
@@ -148,6 +150,7 @@ export function MissionTree() {
}
function NodeRenderer({ node, style, dragHandle }: NodeRendererProps<TreeNode>) {
+ const t = useT();
const data = node.data;
const isMission = data.kind === "mission";
const meta: MissionStateBadgeMeta | null =
@@ -205,7 +208,7 @@ function NodeRenderer({ node, style, dragHandle }: NodeRendererProps<TreeNode>)
meta.className,
)}
>
- {meta.label}
+ {t(meta.labelKey)}
</span>
)}
</div>
diff --git a/jarvis/ui/web/frontend/src/components/missions/OpenClawPanel.tsx b/jarvis/ui/web/frontend/src/components/missions/OpenClawPanel.tsx
index 32ba3721a3..8fc66f5402 100644
--- a/jarvis/ui/web/frontend/src/components/missions/OpenClawPanel.tsx
+++ b/jarvis/ui/web/frontend/src/components/missions/OpenClawPanel.tsx
@@ -13,6 +13,7 @@ import { CircleSlash, Cpu, Copy, ExternalLink } from "lucide-react";
import { useShallow } from "zustand/react/shallow";
import { ScrollArea } from "@/components/ui/scroll-area";
+import { useT } from "@/i18n";
import { cn } from "@/lib/utils";
import type { OpenClawReattachStatus, OpenClawWorkerSnapshot } from "@/types/missions";
@@ -54,6 +55,7 @@ async function copyToClipboard(value: string): Promise<void> {
}
export function OpenClawPanel() {
+ const t = useT();
const workers = useMissionsStore(
useShallow((s) => {
if (!s.selectedMissionId) return [];
@@ -66,7 +68,7 @@ export function OpenClawPanel() {
return (
<div className="flex h-full flex-col items-center justify-center gap-2 px-4 text-center text-xs text-muted-foreground">
<Cpu className="h-7 w-7 text-muted-foreground/40" />
- <p>Mission auswaehlen, um OpenClaw-Worker zu sehen.</p>
+ <p>{t("openclaw_panel.select_mission")}</p>
</div>
);
}
@@ -75,7 +77,7 @@ export function OpenClawPanel() {
return (
<div className="flex h-full flex-col items-center justify-center gap-2 px-4 text-center text-xs text-muted-foreground">
<CircleSlash className="h-7 w-7 text-muted-foreground/40" />
- <p>Keine OpenClaw-Worker in dieser Mission.</p>
+ <p>{t("openclaw_panel.no_workers")}</p>
</div>
);
}
@@ -96,6 +98,7 @@ interface WorkerRowProps {
}
function WorkerRow({ worker }: WorkerRowProps) {
+ const t = useT();
const reattachClass = REATTACH_STYLE[worker.reattach_status] ?? REATTACH_STYLE.unknown;
const reattachLabel = REATTACH_LABEL[worker.reattach_status] ?? "?";
@@ -159,7 +162,7 @@ function WorkerRow({ worker }: WorkerRowProps) {
<span
data-testid="openclaw-state-dir"
className="truncate font-mono text-foreground/80"
- title={worker.state_dir || "(nicht verfuegbar)"}
+ title={worker.state_dir || t("openclaw_panel.not_available")}
>
{worker.state_dir || "—"}
</span>
@@ -167,7 +170,7 @@ function WorkerRow({ worker }: WorkerRowProps) {
<button
type="button"
onClick={() => copyToClipboard(worker.state_dir)}
- title="Pfad kopieren"
+ title={t("openclaw_panel.copy_path")}
className="shrink-0 text-muted-foreground/70 hover:text-foreground"
>
<Copy className="h-3 w-3" />
@@ -180,7 +183,7 @@ function WorkerRow({ worker }: WorkerRowProps) {
<span
data-testid="openclaw-log-path"
className="truncate font-mono text-foreground/80"
- title={worker.log_path || "(nicht verfuegbar)"}
+ title={worker.log_path || t("openclaw_panel.not_available")}
>
{worker.log_path || "—"}
</span>
@@ -189,7 +192,7 @@ function WorkerRow({ worker }: WorkerRowProps) {
<button
type="button"
onClick={() => copyToClipboard(worker.log_path)}
- title="Pfad kopieren"
+ title={t("openclaw_panel.copy_path")}
className="shrink-0 text-muted-foreground/70 hover:text-foreground"
>
<Copy className="h-3 w-3" />
@@ -203,7 +206,7 @@ function WorkerRow({ worker }: WorkerRowProps) {
e.preventDefault();
copyToClipboard(worker.log_path);
}}
- title="file://-Link (Pfad wird kopiert)"
+ title={t("openclaw_panel.file_link_copies_path")}
className="shrink-0 text-muted-foreground/70 hover:text-foreground"
>
<ExternalLink className="h-3 w-3" />
@@ -214,7 +217,7 @@ function WorkerRow({ worker }: WorkerRowProps) {
{worker.ended_reason && (
<>
- <dt className="text-muted-foreground">Ende</dt>
+ <dt className="text-muted-foreground">{t("openclaw_panel.ended_label")}</dt>
<dd
data-testid="openclaw-ended-reason"
className="font-mono text-foreground/70"
diff --git a/jarvis/ui/web/frontend/src/components/missions/PtyTerminal.tsx b/jarvis/ui/web/frontend/src/components/missions/PtyTerminal.tsx
index 01fe8c07f4..8a857deea0 100644
--- a/jarvis/ui/web/frontend/src/components/missions/PtyTerminal.tsx
+++ b/jarvis/ui/web/frontend/src/components/missions/PtyTerminal.tsx
@@ -19,6 +19,7 @@ import { WebLinksAddon } from "@xterm/addon-web-links";
import { SearchAddon } from "@xterm/addon-search";
import "@xterm/xterm/css/xterm.css";
import { AlertCircle, Terminal as TerminalIcon } from "lucide-react";
+import { useT } from "@/i18n";
import {
disposeTerminal,
getTerminal,
@@ -41,6 +42,7 @@ function buildPtyUrl(workerId: string): string {
}
export function PtyTerminal({ workerId }: PtyTerminalProps) {
+ const t = useT();
const containerRef = useRef<HTMLDivElement | null>(null);
const termRef = useRef<Terminal | null>(null);
const fitRef = useRef<FitAddon | null>(null);
@@ -163,17 +165,17 @@ export function PtyTerminal({ workerId }: PtyTerminalProps) {
});
ws.addEventListener("error", () => {
- setStreamError("PTY-Stream nicht erreichbar.");
+ setStreamError(t("pty_terminal.stream_unreachable"));
});
ws.addEventListener("close", (ev) => {
setConnected(false);
if (ev.code !== 1000 && ev.code !== 1001) {
- setStreamError(`Stream getrennt (Code ${ev.code}).`);
+ setStreamError(`${t("pty_terminal.stream_disconnected")} (Code ${ev.code}).`);
}
});
} catch (e) {
- setStreamError(`PTY-Connect fehlgeschlagen: ${(e as Error).message}`);
+ setStreamError(`${t("pty_terminal.connect_failed")}: ${(e as Error).message}`);
}
return () => {
@@ -190,7 +192,7 @@ export function PtyTerminal({ workerId }: PtyTerminalProps) {
termRef.current = null;
fitRef.current = null;
};
- }, [workerId, sendControl]);
+ }, [workerId, sendControl, t]);
return (
<div className="relative flex h-full w-full flex-col overflow-hidden rounded-md border border-border bg-[#0b0d10]">
@@ -208,7 +210,7 @@ export function PtyTerminal({ workerId }: PtyTerminalProps) {
) : connected ? (
<span className="text-emerald-400">live</span>
) : (
- <span className="text-muted-foreground">verbinde…</span>
+ <span className="text-muted-foreground">{t("pty_terminal.connecting")}</span>
)}
</div>
</header>
diff --git a/jarvis/ui/web/frontend/src/components/missions/VerdictPanel.tsx b/jarvis/ui/web/frontend/src/components/missions/VerdictPanel.tsx
index 84b15c6518..fa552a0424 100644
--- a/jarvis/ui/web/frontend/src/components/missions/VerdictPanel.tsx
+++ b/jarvis/ui/web/frontend/src/components/missions/VerdictPanel.tsx
@@ -19,6 +19,7 @@ import {
import { useShallow } from "zustand/react/shallow";
import { ScrollArea } from "@/components/ui/scroll-area";
import { cn } from "@/lib/utils";
+import { useT } from "@/i18n";
import type {
CriticAxisResult,
CriticVerdictReady,
@@ -44,6 +45,7 @@ const VERDICT_STYLE: Record<CriticVerdict, { className: string; label: string }>
};
export function VerdictPanel() {
+ const t = useT();
const verdicts = useMissionsStore(
useShallow((s) => {
if (!s.selectedMissionId) return [] as CriticVerdictReady[];
@@ -55,7 +57,7 @@ export function VerdictPanel() {
return (
<div className="flex h-full flex-col items-center justify-center gap-2 px-6 text-center text-xs text-muted-foreground">
<ListChecks className="h-7 w-7 text-muted-foreground/50" />
- <p>Noch keine Critic-Verdicts fuer diese Mission.</p>
+ <p>{t("missions_view.no_critic_verdicts")}</p>
</div>
);
}
diff --git a/jarvis/ui/web/frontend/src/components/onboarding/IntroClip.tsx b/jarvis/ui/web/frontend/src/components/onboarding/IntroClip.tsx
index 31bc8571c5..9275e2d220 100644
--- a/jarvis/ui/web/frontend/src/components/onboarding/IntroClip.tsx
+++ b/jarvis/ui/web/frontend/src/components/onboarding/IntroClip.tsx
@@ -1,14 +1,26 @@
+import { useState } from "react";
import { IntroSequence } from "./IntroSequence";
+/**
+ * Plays the onboarding intro video when a usable `src` is given — autoplaying
+ * muted (the video carries no audio) with controls so the user can pause or
+ * scrub, and can simply move on with the Welcome CTA below to skip it. Falls
+ * back to the animated IntroSequence when there is no src or the asset fails to
+ * load, so a missing video never blocks onboarding.
+ */
export function IntroClip({ src }: { src?: string }) {
- if (src && src.trim().length > 0) {
+ const [failed, setFailed] = useState(false);
+ if (src && src.trim().length > 0 && !failed) {
return (
<video
className="aspect-video w-full rounded-xl border border-border"
src={src}
controls
+ autoPlay
+ muted
playsInline
preload="metadata"
+ onError={() => setFailed(true)}
/>
);
}
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 ad6023832b..93d6d53198 100644
--- a/jarvis/ui/web/frontend/src/components/onboarding/OnboardingFlow.test.tsx
+++ b/jarvis/ui/web/frontend/src/components/onboarding/OnboardingFlow.test.tsx
@@ -19,8 +19,6 @@ vi.mock("./steps/TermsStep", () => ({ TermsStep: dbl("step-terms") }));
vi.mock("./steps/LanguageStep", () => ({ LanguageStep: dbl("step-language") }));
vi.mock("./steps/WakeWordStep", () => ({ WakeWordStep: dbl("step-wake-word") }));
vi.mock("./steps/ApiKeysStep", () => ({ ApiKeysStep: dbl("step-api-keys") }));
-vi.mock("./steps/MicTestStep", () => ({ MicTestStep: dbl("step-mic-test") }));
-vi.mock("./steps/PersonaThemeStep", () => ({ PersonaThemeStep: dbl("step-persona-theme") }));
vi.mock("./steps/FinishStep", () => ({ FinishStep: dbl("step-finish") }));
import { OnboardingFlow, STEP_KEYS } from "./OnboardingFlow";
@@ -81,7 +79,7 @@ it("REGISTRY covers exactly the canonical backend steps", () => {
expect(new Set(STEP_KEYS)).toEqual(
new Set([
"welcome", "terms", "language", "wake-word",
- "api-keys", "mic-test", "persona-theme", "finish",
+ "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 b264e5e4c9..aaa0b25cc5 100644
--- a/jarvis/ui/web/frontend/src/components/onboarding/OnboardingFlow.tsx
+++ b/jarvis/ui/web/frontend/src/components/onboarding/OnboardingFlow.tsx
@@ -7,8 +7,6 @@ import { TermsStep } from "./steps/TermsStep";
import { LanguageStep } from "./steps/LanguageStep";
import { WakeWordStep } from "./steps/WakeWordStep";
import { ApiKeysStep } from "./steps/ApiKeysStep";
-import { MicTestStep } from "./steps/MicTestStep";
-import { PersonaThemeStep } from "./steps/PersonaThemeStep";
import { FinishStep } from "./steps/FinishStep";
export interface StepProps {
@@ -26,8 +24,6 @@ const REGISTRY: Record<string, (p: StepProps) => JSX.Element> = {
language: LanguageStep,
"wake-word": WakeWordStep,
"api-keys": ApiKeysStep,
- "mic-test": MicTestStep,
- "persona-theme": PersonaThemeStep,
finish: FinishStep,
};
@@ -84,7 +80,7 @@ export function OnboardingFlow({
/>
))}
</div>
- <MascotGigi size={48} reactToVoice={steps[idx] === "mic-test"} enableComments={false} />
+ <MascotGigi size={48} reactToVoice={false} enableComments={false} />
</div>
<StepComp {...props} />
{!props.isFirst && (
diff --git a/jarvis/ui/web/frontend/src/components/onboarding/OnboardingGate.tsx b/jarvis/ui/web/frontend/src/components/onboarding/OnboardingGate.tsx
index 144631fcaa..185c9fc14a 100644
--- a/jarvis/ui/web/frontend/src/components/onboarding/OnboardingGate.tsx
+++ b/jarvis/ui/web/frontend/src/components/onboarding/OnboardingGate.tsx
@@ -1,6 +1,7 @@
-import { useEffect, useMemo } from "react";
+import { useEffect, useMemo, useState } from "react";
import { useOnboarding } from "@/hooks/useOnboarding";
import { OnboardingFlow } from "./OnboardingFlow";
+import { RiskGate } from "./RiskGate";
/**
* Blocking overlay that shows the onboarding flow until it is completed.
@@ -11,9 +12,21 @@ import { OnboardingFlow } from "./OnboardingFlow";
*/
export function OnboardingGate() {
const onb = useOnboarding();
+ // Risk acknowledgement is gated in local state only — never persisted and
+ // never touching onboarding/completed state, so it shows once per fresh open
+ // of an unfinished guide and cannot reintroduce the restart-loop bug.
+ const [riskAck, setRiskAck] = useState(false);
+ // Set once the user completes the guide (the "Get started" / complete() path
+ // dispatches jarvis:onboarding-changed). It dismisses the overlay even under
+ // ?onboarding=force, so a dev replay closes on finish exactly like a real
+ // first run instead of staying stuck open.
+ const [dismissed, setDismissed] = useState(false);
useEffect(() => {
- const onChanged = () => void onb.refetch();
+ const onChanged = () => {
+ void onb.refetch();
+ setDismissed(true);
+ };
window.addEventListener("jarvis:onboarding-changed", onChanged);
return () => window.removeEventListener("jarvis:onboarding-changed", onChanged);
}, [onb]);
@@ -30,7 +43,7 @@ export function OnboardingGate() {
const termsOutdated =
onb.state.terms.accepted &&
onb.state.terms.accepted_version !== onb.state.terms.current_version;
- const show = forced || !onb.state.completed || termsOutdated;
+ const show = (forced || !onb.state.completed || termsOutdated) && !dismissed;
if (!show) return null;
// On a terms version bump for an already-completed install, re-open at terms.
@@ -42,7 +55,11 @@ export function OnboardingGate() {
aria-modal="true"
className="fixed inset-0 z-50 flex items-center justify-center bg-background/90 backdrop-blur-sm"
>
- <OnboardingFlow onb={onb} initialStep={initialStep} />
+ {riskAck ? (
+ <OnboardingFlow onb={onb} initialStep={initialStep} />
+ ) : (
+ <RiskGate onAccept={() => setRiskAck(true)} />
+ )}
</div>
);
}
diff --git a/jarvis/ui/web/frontend/src/components/onboarding/RiskGate.tsx b/jarvis/ui/web/frontend/src/components/onboarding/RiskGate.tsx
new file mode 100644
index 0000000000..f2d7cae11e
--- /dev/null
+++ b/jarvis/ui/web/frontend/src/components/onboarding/RiskGate.tsx
@@ -0,0 +1,40 @@
+import { useState } from "react";
+import { Button } from "@/components/ui/button";
+import { useT } from "@/i18n";
+
+/**
+ * A blocking "use at your own risk" acknowledgement shown once, before the
+ * onboarding flow itself (mirrors the trust prompt CLIs like Claude Code show on
+ * first run). Frontend-only: it gates the flow via local state and never mutates
+ * onboarding/completed state, so it cannot reintroduce the "onboarding reappears
+ * every restart" bug. The user must tick the checkbox before continuing.
+ */
+export function RiskGate({ onAccept }: { onAccept: () => void }) {
+ const t = useT();
+ const [accepted, setAccepted] = useState(false);
+ return (
+ <div className="flex w-full max-w-lg flex-col gap-5 rounded-2xl border border-primary/40 bg-card p-8 shadow-2xl">
+ <div className="flex items-center gap-3">
+ <span className="text-2xl" aria-hidden>
+ ⚠️
+ </span>
+ <h1 className="font-display text-xl font-semibold">{t("onboarding.risk.title")}</h1>
+ </div>
+ <p className="text-sm font-semibold text-foreground">{t("onboarding.risk.lead")}</p>
+ <p className="text-sm leading-relaxed text-muted-foreground">{t("onboarding.risk.body")}</p>
+ <p className="text-sm leading-relaxed text-muted-foreground">{t("onboarding.risk.liability")}</p>
+ <label className="flex items-start gap-2 text-sm">
+ <input
+ type="checkbox"
+ className="mt-1 shrink-0"
+ checked={accepted}
+ onChange={(e) => setAccepted(e.target.checked)}
+ />
+ <span>{t("onboarding.risk.accept_label")}</span>
+ </label>
+ <Button className="w-full" disabled={!accepted} onClick={() => accepted && onAccept()}>
+ {t("onboarding.risk.proceed")}
+ </Button>
+ </div>
+ );
+}
diff --git a/jarvis/ui/web/frontend/src/components/onboarding/steps/ApiKeysStep.test.tsx b/jarvis/ui/web/frontend/src/components/onboarding/steps/ApiKeysStep.test.tsx
index 3576bc6e32..89eda282c5 100644
--- a/jarvis/ui/web/frontend/src/components/onboarding/steps/ApiKeysStep.test.tsx
+++ b/jarvis/ui/web/frontend/src/components/onboarding/steps/ApiKeysStep.test.tsx
@@ -1,8 +1,14 @@
import { cleanup, fireEvent, render, screen, waitFor } from "@testing-library/react";
import { afterEach, expect, it, vi } from "vitest";
-const { switchBrainProvider, switchTtsProvider, switchSttProvider, refetch, PROVIDERS } =
- vi.hoisted(() => {
+const {
+ switchBrainProvider,
+ switchTtsProvider,
+ switchSttProvider,
+ refetch,
+ setActiveOptimistic,
+ PROVIDERS,
+} = vi.hoisted(() => {
const mk = (over: Record<string, unknown>) => ({
id: "x",
label: "X",
@@ -24,6 +30,7 @@ const { switchBrainProvider, switchTtsProvider, switchSttProvider, refetch, PROV
switchTtsProvider: vi.fn().mockResolvedValue({}),
switchSttProvider: vi.fn().mockResolvedValue({}),
refetch: vi.fn(),
+ setActiveOptimistic: vi.fn(),
PROVIDERS: [
mk({ id: "claude-api", label: "Claude", tier: "brain", secret_keys: ["anthropic_api_key"], configured: true }),
mk({ id: "gemini", label: "Gemini", tier: "brain", secret_keys: ["gemini_api_key"], configured: false }),
@@ -39,8 +46,20 @@ vi.mock("@/components/ApiKeyForm", () => ({
<div data-testid="keyform">{secretKey}</div>
),
}));
+// The subagent section fetches /api/openclaw/status on mount, which jsdom has no
+// server for. Stub it so the step renders deterministically; its real behaviour
+// is covered by SubagentSection's own tests.
+vi.mock("@/components/SubagentSection", () => ({
+ SubagentSection: () => <div data-testid="subagent-section" />,
+}));
vi.mock("@/hooks/useProviders", () => ({
- useProviders: () => ({ providers: PROVIDERS, loading: false, error: null, refetch }),
+ useProviders: () => ({
+ providers: PROVIDERS,
+ loading: false,
+ error: null,
+ refetch,
+ setActiveOptimistic,
+ }),
switchBrainProvider,
switchTtsProvider,
switchSttProvider,
@@ -67,24 +86,27 @@ function renderStep(over: Record<string, unknown> = {}) {
return props;
}
-it("pages Brain -> Voice -> Hearing, then advances the flow", () => {
- const props = renderStep();
- const next = () =>
- fireEvent.click(screen.getByRole("button", { name: "onboarding.nav.next" }));
+it("shows every provider class and the subagent section at once", () => {
+ renderStep();
+ // All three tier headers are visible simultaneously — no paging.
expect(screen.getByText("Brain — reasoning")).toBeTruthy();
+ expect(screen.getByText("Voice — text to speech")).toBeTruthy();
+ expect(screen.getByText("Hearing — speech to text")).toBeTruthy();
+
+ // ...and their providers, in order, in the same scroll container.
expect(screen.getByText("Claude")).toBeTruthy();
expect(screen.getByText("anthropic_api_key")).toBeTruthy();
-
- next(); // -> Voice (TTS)
- expect(screen.getByText("Voice — text to speech")).toBeTruthy();
expect(screen.getByText("Cartesia")).toBeTruthy();
+ expect(screen.getByText("Deepgram")).toBeTruthy();
- next(); // -> Hearing (STT)
- expect(screen.getByText("Hearing — speech to text")).toBeTruthy();
- expect(props.goNext).not.toHaveBeenCalled();
+ // The subagent class is folded in below the key tiers.
+ expect(screen.getByTestId("subagent-section")).toBeTruthy();
+});
- next(); // last class -> advance the flow
+it("advances the flow directly on Next (no internal paging)", () => {
+ const props = renderStep();
+ fireEvent.click(screen.getByRole("button", { name: "onboarding.nav.next" }));
expect(props.goNext).toHaveBeenCalledTimes(1);
});
@@ -104,6 +126,16 @@ it("activates a configured provider via its select control", async () => {
await waitFor(() => expect(refetch).toHaveBeenCalled());
});
+it("flips the highlight optimistically before the switch resolves", () => {
+ // A switch that never resolves proves the UI does not wait on the backend.
+ switchBrainProvider.mockReturnValueOnce(new Promise(() => {}));
+ renderStep();
+ fireEvent.click(screen.getByRole("button", { name: /Claude/ }));
+ // The optimistic active-flip fires synchronously on click, ahead of the
+ // (still-pending) switch call and any refetch.
+ expect(setActiveOptimistic).toHaveBeenCalledWith("brain", "claude-api");
+});
+
it("disables selection for an unconfigured cloud provider", () => {
renderStep();
const gemini = screen.getByRole("button", { name: /Gemini/ }) as HTMLButtonElement;
diff --git a/jarvis/ui/web/frontend/src/components/onboarding/steps/FinishStep.tsx b/jarvis/ui/web/frontend/src/components/onboarding/steps/FinishStep.tsx
index ffd187b144..a1d72bb63f 100644
--- a/jarvis/ui/web/frontend/src/components/onboarding/steps/FinishStep.tsx
+++ b/jarvis/ui/web/frontend/src/components/onboarding/steps/FinishStep.tsx
@@ -19,6 +19,10 @@ export function FinishStep({ onb, goNext }: StepProps) {
</ul>
</div>
)}
+ <div className="flex items-start gap-2 rounded-lg border border-primary/30 bg-primary/5 px-3 py-2 text-left text-xs text-muted-foreground">
+ <span aria-hidden className="mt-px text-primary">⏱</span>
+ <span>{t("onboarding.finish.boot_notice")}</span>
+ </div>
<Button className="w-full" onClick={goNext}>{t("onboarding.finish.start_cta")}</Button>
</div>
);
diff --git a/jarvis/ui/web/frontend/src/components/onboarding/steps/PersonaThemeStep.test.tsx b/jarvis/ui/web/frontend/src/components/onboarding/steps/PersonaThemeStep.test.tsx
deleted file mode 100644
index e57fd71c81..0000000000
--- a/jarvis/ui/web/frontend/src/components/onboarding/steps/PersonaThemeStep.test.tsx
+++ /dev/null
@@ -1,23 +0,0 @@
-import { cleanup, fireEvent, render, screen, waitFor } from "@testing-library/react";
-import { afterEach, expect, it, vi } from "vitest";
-vi.mock("@/i18n", () => ({ useT: () => (k: string) => k }));
-import { PersonaThemeStep } from "./PersonaThemeStep";
-afterEach(() => { cleanup(); vi.restoreAllMocks(); });
-
-it("saves the assistant name on blur (PUT, no persist:false)", async () => {
- const calls: Array<[string, RequestInit | undefined]> = [];
- vi.stubGlobal("fetch", vi.fn().mockImplementation((u: string, i?: RequestInit) => {
- calls.push([u, i]);
- return Promise.resolve({ ok: true, json: () => Promise.resolve({}) });
- }));
- render(<PersonaThemeStep onb={{} as never} goNext={vi.fn()} goBack={vi.fn()} skip={vi.fn()} isFirst={false} isLast={false} />);
- const input = screen.getByLabelText("onboarding.persona.name_label");
- fireEvent.change(input, { target: { value: "Nova" } });
- fireEvent.blur(input);
- await waitFor(() =>
- expect(calls.some(([u, i]) => u === "/api/settings/assistant-name" && i?.method === "PUT")).toBe(true),
- );
- const body = JSON.parse(calls.find(([u]) => u === "/api/settings/assistant-name")![1]!.body as string);
- expect(body.name).toBe("Nova");
- expect(body.persist).toBeUndefined(); // never send persist:false
-});
diff --git a/jarvis/ui/web/frontend/src/components/onboarding/steps/PersonaThemeStep.tsx b/jarvis/ui/web/frontend/src/components/onboarding/steps/PersonaThemeStep.tsx
deleted file mode 100644
index 1099c09114..0000000000
--- a/jarvis/ui/web/frontend/src/components/onboarding/steps/PersonaThemeStep.tsx
+++ /dev/null
@@ -1,41 +0,0 @@
-import { useState } from "react";
-import { Button } from "@/components/ui/button";
-import { useT } from "@/i18n";
-import type { StepProps } from "../OnboardingFlow";
-
-export function PersonaThemeStep({ goNext, skip }: StepProps) {
- const t = useT();
- const [name, setName] = useState("");
-
- function saveName() {
- if (!name.trim()) return;
- // Omit `persist` — it defaults to true server-side. NEVER send persist:false here.
- void fetch("/api/settings/assistant-name", {
- method: "PUT",
- headers: { "Content-Type": "application/json" },
- body: JSON.stringify({ name: name.trim() }),
- }).catch(() => undefined);
- }
-
- return (
- <div className="flex flex-col gap-4">
- <h2 className="font-display text-lg font-semibold">{t("onboarding.persona.title")}</h2>
- <label className="text-xs font-medium text-muted-foreground">
- {t("onboarding.persona.name_label")}
- <input
- aria-label={t("onboarding.persona.name_label")}
- type="text"
- value={name}
- maxLength={40}
- onChange={(e) => setName(e.target.value)}
- onBlur={saveName}
- className="mt-1 w-full rounded-md border border-input bg-background px-3 py-2 text-sm"
- />
- </label>
- <Button className="w-full" onClick={goNext}>{t("onboarding.nav.next")}</Button>
- <button className="text-xs text-muted-foreground underline" onClick={skip}>
- {t("onboarding.persona.skip")}
- </button>
- </div>
- );
-}
diff --git a/jarvis/ui/web/frontend/src/components/onboarding/steps/SystemStyleStep.test.tsx b/jarvis/ui/web/frontend/src/components/onboarding/steps/SystemStyleStep.test.tsx
new file mode 100644
index 0000000000..3b9984743e
--- /dev/null
+++ b/jarvis/ui/web/frontend/src/components/onboarding/steps/SystemStyleStep.test.tsx
@@ -0,0 +1,145 @@
+import { cleanup, fireEvent, render, screen, waitFor } from "@testing-library/react";
+import { afterEach, expect, it, vi } from "vitest";
+
+vi.mock("@/i18n", () => ({ useT: () => (k: string) => k }));
+vi.mock("@/components/MascotGigi", () => ({ MascotGigi: () => <div data-testid="gigi" /> }));
+
+// Mock the overlay-style hook so the step has no real network dependency. The
+// step must persist the pick through this hook's saveStyle and NEVER restart.
+const saveStyle = vi.fn().mockResolvedValue({
+ ok: true,
+ style: "whisper_bar",
+ persisted: true,
+ applied_live: false, // even when a restart would be "required", onboarding must not restart
+ restart_required: true,
+});
+vi.mock("@/hooks/useOverlayStyle", () => ({
+ useOverlayStyle: () => ({
+ config: { style: "whisper_bar", options: ["whisper_bar", "mascot", "none"] },
+ loading: false,
+ error: null,
+ refetch: vi.fn(),
+ saveStyle,
+ }),
+}));
+
+import { SystemStyleStep } from "./SystemStyleStep";
+
+afterEach(() => {
+ cleanup();
+ vi.clearAllMocks();
+});
+
+function renderStep() {
+ const goNext = vi.fn();
+ const skip = vi.fn();
+ render(
+ <SystemStyleStep
+ onb={{} as never}
+ goNext={goNext}
+ goBack={vi.fn()}
+ skip={skip}
+ isFirst={false}
+ isLast={false}
+ />,
+ );
+ return { goNext, skip };
+}
+
+it("renders all three overlay-style options", () => {
+ renderStep();
+ expect(
+ screen.getByRole("button", { name: "onboarding.system_style.options.whisper_bar" }),
+ ).toBeDefined();
+ expect(
+ screen.getByRole("button", { name: "onboarding.system_style.options.mascot" }),
+ ).toBeDefined();
+ expect(
+ screen.getByRole("button", { name: "onboarding.system_style.options.none" }),
+ ).toBeDefined();
+});
+
+it("pre-selects the Jarvis Bar and labels it Recommended", () => {
+ renderStep();
+ // Recommended badge is shown.
+ expect(screen.getByText("onboarding.system_style.recommended")).toBeDefined();
+ // The bar card is the pressed/selected one.
+ const bar = screen.getByRole("button", {
+ name: "onboarding.system_style.options.whisper_bar",
+ });
+ expect(bar.getAttribute("aria-pressed")).toBe("true");
+});
+
+it("persists the chosen style via saveStyle on click", async () => {
+ renderStep();
+ fireEvent.click(
+ screen.getByRole("button", { name: "onboarding.system_style.options.mascot" }),
+ );
+ await waitFor(() => expect(saveStyle).toHaveBeenCalledWith("mascot"));
+});
+
+it("does not auto-restart on a pick (restart is a separate, explicit action)", async () => {
+ const fetchSpy = vi.fn((..._args: unknown[]) =>
+ Promise.resolve({ ok: true, status: 200, json: () => Promise.resolve({}) }),
+ );
+ vi.stubGlobal("fetch", fetchSpy);
+ renderStep();
+ fireEvent.click(
+ screen.getByRole("button", { name: "onboarding.system_style.options.mascot" }),
+ );
+ await waitFor(() => expect(saveStyle).toHaveBeenCalled());
+ // Picking alone must never hit the restart endpoint.
+ const restartCalls = fetchSpy.mock.calls.filter(
+ (args) => typeof args[0] === "string" && (args[0] as string).includes("restart-app"),
+ );
+ expect(restartCalls).toHaveLength(0);
+});
+
+it("offers a one-click restart when the pick needs one, and posts restart-app", async () => {
+ const fetchSpy = vi.fn((..._args: unknown[]) =>
+ Promise.resolve({ ok: true, status: 200, json: () => Promise.resolve({}) }),
+ );
+ vi.stubGlobal("fetch", fetchSpy);
+ renderStep();
+ // The mocked saveStyle returns applied_live:false → a restart is needed.
+ fireEvent.click(
+ screen.getByRole("button", { name: "onboarding.system_style.options.mascot" }),
+ );
+ const restartBtn = await screen.findByText("onboarding.system_style.restart_now");
+ fireEvent.click(restartBtn);
+ await waitFor(() =>
+ expect(
+ fetchSpy.mock.calls.some(
+ (args) =>
+ typeof args[0] === "string" && args[0].includes("/api/settings/restart-app"),
+ ),
+ ).toBe(true),
+ );
+});
+
+it("reverts the optimistic selection when the save fails", async () => {
+ saveStyle.mockRejectedValueOnce(new Error("network down"));
+ renderStep();
+ fireEvent.click(
+ screen.getByRole("button", { name: "onboarding.system_style.options.mascot" }),
+ );
+ await waitFor(() => expect(saveStyle).toHaveBeenCalledWith("mascot"));
+ // The pick was not persisted, so the highlighted card snaps back to the
+ // last-known persisted value (whisper_bar) and an error is shown.
+ await waitFor(() =>
+ expect(
+ screen
+ .getByRole("button", { name: "onboarding.system_style.options.whisper_bar" })
+ .getAttribute("aria-pressed"),
+ ).toBe("true"),
+ );
+ expect(screen.getByText("onboarding.system_style.save_error")).toBeDefined();
+});
+
+it("advances on Next and on Skip", () => {
+ const props = renderStep();
+ fireEvent.click(screen.getByText("onboarding.nav.next"));
+ expect(props.goNext).toHaveBeenCalled();
+ fireEvent.click(screen.getByText("onboarding.system_style.skip"));
+ expect(props.skip).toHaveBeenCalled();
+});
diff --git a/jarvis/ui/web/frontend/src/components/onboarding/steps/SystemStyleStep.tsx b/jarvis/ui/web/frontend/src/components/onboarding/steps/SystemStyleStep.tsx
new file mode 100644
index 0000000000..b8f0be28e0
--- /dev/null
+++ b/jarvis/ui/web/frontend/src/components/onboarding/steps/SystemStyleStep.tsx
@@ -0,0 +1,185 @@
+import { useEffect, useState } from "react";
+import { Button } from "@/components/ui/button";
+import { useOverlayStyle, type OverlayStyle } from "@/hooks/useOverlayStyle";
+import { StylePreview } from "@/components/overlay/OverlayStylePreviews";
+import { useT } from "@/i18n";
+import { cn } from "@/lib/utils";
+import type { StepProps } from "../OnboardingFlow";
+
+// The Jarvis Bar is the default + recommended on-screen surface.
+const RECOMMENDED: OverlayStyle = "whisper_bar";
+
+/**
+ * Onboarding step: choose the on-screen "system style" (the Jarvis Bar vs. the
+ * Orb vs. no overlay). Reuses the existing overlay-style axis
+ * (`/api/settings/overlay-style` via `useOverlayStyle`) and the shared preview
+ * graphics, with the Jarvis Bar pre-selected and labelled "Recommended".
+ *
+ * The pick is persisted immediately and live-applied when Tk can swap the
+ * surface in place. When it can't (a `bar <-> mascot` first-time swap needs a
+ * brand-new Tk root — BUG-031 — which would crash the process), the backend
+ * reports `restart_required`; this step then offers a one-click self-restart
+ * (the same `request_restart` relauncher the Settings panel uses) so the choice
+ * actually takes effect instead of leaving the user to relaunch by hand. We
+ * never restart on the *pick* itself — only when the user clicks "Restart now".
+ */
+export function SystemStyleStep({ goNext, skip }: StepProps) {
+ const t = useT();
+ const { config, loading, saveStyle } = useOverlayStyle();
+ const [style, setStyle] = useState<OverlayStyle>(RECOMMENDED);
+ const [saving, setSaving] = useState(false);
+ const [needsRestart, setNeedsRestart] = useState(false);
+ const [showSaveError, setShowSaveError] = useState(false);
+ const [restarting, setRestarting] = useState(false);
+ // Armed after the backend refuses a restart (HTTP 409) because missions are
+ // running; the next click resends with force=true. Mirrors the Settings panel.
+ const [forceArmed, setForceArmed] = useState(false);
+
+ useEffect(() => {
+ if (config) setStyle(config.style);
+ }, [config]);
+
+ const options = config?.options ?? (["whisper_bar", "mascot", "none"] as OverlayStyle[]);
+
+ async function onPick(opt: OverlayStyle) {
+ if (saving || restarting) return;
+ setStyle(opt); // optimistic — reverted below if the save fails
+ setSaving(true);
+ setNeedsRestart(false);
+ setForceArmed(false);
+ setShowSaveError(false);
+ try {
+ const res = await saveStyle(opt);
+ // Live-applied → the surface already changed on screen. Otherwise the
+ // choice is persisted and a restart is needed to deliver it.
+ if (!res.applied_live) setNeedsRestart(true);
+ } catch {
+ // Honest failure: revert the optimistic selection to the last persisted
+ // value so the highlighted card never claims a pick that wasn't saved, and
+ // surface a non-blocking error. The default still stands; the user can
+ // retry or continue.
+ setStyle(config?.style ?? RECOMMENDED);
+ setShowSaveError(true);
+ } finally {
+ setSaving(false);
+ }
+ }
+
+ async function onRestartNow() {
+ if (restarting) return;
+ setRestarting(true);
+ try {
+ const url = forceArmed
+ ? "/api/settings/restart-app?force=true"
+ : "/api/settings/restart-app";
+ const res = await fetch(url, { method: "POST" });
+ if (res.status === 409) {
+ // Live missions would be killed — arm a force restart instead of
+ // killing them silently. The next click resends with force=true.
+ setRestarting(false);
+ setForceArmed(true);
+ return;
+ }
+ if (!res.ok) throw new Error(`restart-failed:${res.status}`);
+ // On success the window goes away as the app relaunches, so we keep
+ // `restarting` true (never cleared here).
+ } catch {
+ // Re-enable the button so the user can retry; the choice is already
+ // persisted, so it still applies on the next manual start either way.
+ setRestarting(false);
+ }
+ }
+
+ return (
+ <div className="flex flex-col gap-4">
+ <div>
+ <h2 className="font-display text-lg font-semibold">
+ {t("onboarding.system_style.title")}
+ </h2>
+ <p className="mt-1 text-xs text-muted-foreground">
+ {t("onboarding.system_style.body")}
+ </p>
+ </div>
+
+ <div className="grid grid-cols-3 gap-3">
+ {options.map((opt) => (
+ <button
+ key={opt}
+ type="button"
+ aria-label={t(`onboarding.system_style.options.${opt}`)}
+ aria-pressed={opt === style}
+ disabled={saving || loading}
+ onClick={() => onPick(opt)}
+ className={cn(
+ "relative flex flex-col items-center gap-2 rounded-lg border p-3 transition-all disabled:opacity-60",
+ opt === style
+ ? "border-primary bg-primary/5 ring-1 ring-primary/50"
+ : "border-border bg-background/40 hover:border-primary/50",
+ )}
+ >
+ {opt === RECOMMENDED && (
+ <span className="absolute -top-2 right-1 rounded-full bg-primary px-1.5 py-0.5 text-[10px] font-semibold text-primary-foreground">
+ {t("onboarding.system_style.recommended")}
+ </span>
+ )}
+ <div className="flex h-16 w-full items-center justify-center overflow-hidden rounded-md bg-card/80">
+ <StylePreview style={opt} />
+ </div>
+ <span
+ className={cn(
+ "text-xs font-medium",
+ opt === style ? "text-primary" : "text-muted-foreground",
+ )}
+ >
+ {t(`onboarding.system_style.options.${opt}`)}
+ </span>
+ </button>
+ ))}
+ </div>
+
+ <p className="text-xs text-muted-foreground">
+ {t(`onboarding.system_style.captions.${style}`)}
+ </p>
+
+ {needsRestart && (
+ <div className="flex flex-col gap-2 rounded-md border border-primary/40 bg-primary/5 p-3">
+ <p className="text-xs text-muted-foreground">
+ {t("onboarding.system_style.needs_restart")}
+ </p>
+ <button
+ type="button"
+ onClick={onRestartNow}
+ disabled={restarting}
+ className="self-start rounded-md border border-primary/50 bg-primary/10 px-3 py-1.5 text-xs font-medium text-primary transition-colors hover:bg-primary/20 disabled:opacity-60"
+ >
+ {restarting
+ ? t("onboarding.system_style.restarting")
+ : forceArmed
+ ? t("topbar.restart_force")
+ : t("onboarding.system_style.restart_now")}
+ </button>
+ {forceArmed && !restarting && (
+ <p className="text-xs text-amber-500">{t("topbar.restart_missions_running")}</p>
+ )}
+ </div>
+ )}
+
+ {showSaveError && (
+ <p className="text-xs text-destructive">
+ {t("onboarding.system_style.save_error")}
+ </p>
+ )}
+
+ <Button className="w-full" onClick={goNext}>
+ {t("onboarding.nav.next")}
+ </Button>
+ <button
+ type="button"
+ className="text-xs text-muted-foreground underline"
+ onClick={skip}
+ >
+ {t("onboarding.system_style.skip")}
+ </button>
+ </div>
+ );
+}
diff --git a/jarvis/ui/web/frontend/src/components/overlay/OverlayStylePreviews.tsx b/jarvis/ui/web/frontend/src/components/overlay/OverlayStylePreviews.tsx
new file mode 100644
index 0000000000..8c42706bf1
--- /dev/null
+++ b/jarvis/ui/web/frontend/src/components/overlay/OverlayStylePreviews.tsx
@@ -0,0 +1,70 @@
+import { MascotGigi } from "@/components/MascotGigi";
+import type { OverlayStyle } from "@/hooks/useOverlayStyle";
+
+/**
+ * Shared visual previews for the on-screen overlay styles (Bar / Mascot / None).
+ *
+ * Lifted out of ``views/settings/OverlayTaskbarGroup.tsx`` so both the Settings
+ * panel and the onboarding "System Style" step can render the same graphics
+ * without one view importing the other. The mascot reuses the real Gigi SVG.
+ */
+
+/** Maps an overlay style to its preview graphic. */
+export function StylePreview({ style }: { style: OverlayStyle }) {
+ if (style === "mascot") {
+ return <MascotGigi size={46} reactToVoice={false} enableComments={false} />;
+ }
+ if (style === "whisper_bar") return <BarPreview />;
+ return <NonePreview />;
+}
+
+export function BarPreview() {
+ const heights = [6, 11, 15, 8, 14, 9, 7];
+ return (
+ <svg viewBox="0 0 100 40" className="w-20" aria-hidden="true">
+ <rect
+ x="6"
+ y="11"
+ width="88"
+ height="18"
+ rx="9"
+ fill="#0e0d0c"
+ stroke="#d7b669"
+ strokeWidth="1.6"
+ />
+ {heights.map((h, i) => (
+ <rect
+ key={`bar-${i}`}
+ x={24 + i * 8}
+ y={20 - h / 2}
+ width="3"
+ height={h}
+ rx="1.5"
+ fill="#e7c46e"
+ />
+ ))}
+ </svg>
+ );
+}
+
+export function NonePreview() {
+ return (
+ <svg viewBox="0 0 100 40" className="w-20 opacity-50" aria-hidden="true">
+ <rect
+ x="6"
+ y="11"
+ width="88"
+ height="18"
+ rx="9"
+ fill="none"
+ stroke="#7c766b"
+ strokeWidth="1.6"
+ strokeDasharray="4 3"
+ />
+ {/* Diagonal "disabled" strike — kept inside the dashed box (y 11..29)
+ and symmetric about its centre (50, 20) so it never juts out as a
+ stub above/below the pill. */}
+ <line x1="25" y1="25" x2="75" y2="15" stroke="#7c766b" strokeWidth="1.6" strokeLinecap="round" />
+ </svg>
+ );
+}
diff --git a/jarvis/ui/web/frontend/src/components/sessions/SessionDetail.tsx b/jarvis/ui/web/frontend/src/components/sessions/SessionDetail.tsx
index cfe87291e2..29e868a9ae 100644
--- a/jarvis/ui/web/frontend/src/components/sessions/SessionDetail.tsx
+++ b/jarvis/ui/web/frontend/src/components/sessions/SessionDetail.tsx
@@ -60,6 +60,10 @@ export function SessionDetail({ detail, loading, error }: Props) {
if (e.kind !== "SpeechSpoken") continue;
const text = String((e.payload as { text?: unknown })?.text ?? "");
if (!text.trim()) continue;
+ // The technical diagnostic rides on the recorded event; it is carried on
+ // the projection for parity with the payload but deliberately NOT rendered
+ // in the transcript (TurnCard) — it is surfaced in the Run Inspector
+ // instead (user request 2026-06-22, reversing the 2026-06-16 ask).
const rawDetail = (e.payload as { detail?: unknown })?.detail;
const detail =
typeof rawDetail === "string" && rawDetail.trim()
@@ -89,14 +93,14 @@ export function SessionDetail({ detail, loading, error }: Props) {
const text = await fetchSessionExport(detail.session.id, format);
const ok = await robustCopy(text);
if (ok) {
- pushToast("success", `Session als ${FORMAT_LABEL[format]} kopiert`);
+ pushToast("success", `${t("session_detail.copied_as")} ${FORMAT_LABEL[format]}`);
} else {
- pushToast("error", "Kopieren fehlgeschlagen — Clipboard-Zugriff blockiert?");
+ pushToast("error", t("session_detail.copy_failed_clipboard"));
}
} catch (e) {
pushToast(
"error",
- e instanceof Error ? e.message : "Kopieren fehlgeschlagen",
+ e instanceof Error ? e.message : t("session_detail.copy_failed"),
);
}
},
@@ -113,11 +117,11 @@ export function SessionDetail({ detail, loading, error }: Props) {
detail.turns.find((t) => t.user_text)?.user_text ?? "";
const filename = buildSessionFilename(detail.session, preview, format);
downloadAs(filename, text, mimeFor(format));
- pushToast("success", `Heruntergeladen als ${filename}`);
+ pushToast("success", `${t("session_detail.downloaded_as")} ${filename}`);
} catch (e) {
pushToast(
"error",
- e instanceof Error ? e.message : "Download fehlgeschlagen",
+ e instanceof Error ? e.message : t("session_detail.download_failed"),
);
}
},
@@ -128,7 +132,7 @@ export function SessionDetail({ detail, loading, error }: Props) {
return (
<div className="flex h-full items-center justify-center text-sm text-muted-foreground">
<Loader2 className="mr-2 h-4 w-4 animate-spin" />
- Lade Session…
+ {t("session_detail.loading")}
</div>
);
}
@@ -137,7 +141,7 @@ export function SessionDetail({ detail, loading, error }: Props) {
return (
<div className="flex h-full items-center justify-center p-6">
<div className="max-w-md rounded-lg border border-destructive/40 bg-destructive/5 p-4 text-sm">
- <div className="font-semibold text-destructive">Fehler beim Laden</div>
+ <div className="font-semibold text-destructive">{t("session_detail.load_error")}</div>
<div className="mt-1 text-muted-foreground">{error.message}</div>
</div>
</div>
@@ -163,14 +167,14 @@ export function SessionDetail({ detail, loading, error }: Props) {
<div className="flex items-start justify-between gap-3">
<div className="min-w-0">
<div className="font-display text-lg font-semibold">
- Voice-Session
+ {t("session_detail.title")}
</div>
<div className="font-mono text-xs text-muted-foreground">
{startedDt.toLocaleString("de")}
{endedDt && ` — ${endedDt.toLocaleTimeString("de")}`}
</div>
<div className="mt-2 flex flex-wrap items-center gap-1.5">
- <Badge variant="secondary">{session.turn_count} Turns</Badge>
+ <Badge variant="secondary">{session.turn_count} {t("session_detail.turns")}</Badge>
<Badge variant="secondary">{session.language}</Badge>
{session.hangup_reason && (
<Badge variant="outline">{session.hangup_reason}</Badge>
@@ -229,7 +233,7 @@ export function SessionDetail({ detail, loading, error }: Props) {
{turns.length === 0 ? (
<div className="rounded-lg border border-dashed border-border p-6 text-center text-sm text-muted-foreground">
{t("sessions.no_turns")}
- ohne Folge-Utterance.
+ {t("session_detail.no_turns_suffix")}
</div>
) : (
turns.map((t) => (
@@ -266,6 +270,7 @@ function ExportRow({
onDownload,
variant,
}: ExportRowProps) {
+ const t = useT();
const labelClass =
variant === "primary"
? "rounded-md border border-primary/40 bg-primary/10 px-2 py-1 text-xs font-medium text-primary"
@@ -283,7 +288,7 @@ function ExportRow({
variant="ghost"
onClick={onCopy}
className="h-7 w-7 shrink-0 p-0"
- title={`${label} kopieren`}
+ title={`${t("session_detail.copy_action")} ${label}`}
>
<Copy className="h-3.5 w-3.5" />
</Button>
@@ -293,7 +298,7 @@ function ExportRow({
variant="ghost"
onClick={onDownload}
className="h-7 w-7 shrink-0 p-0"
- title={`${label} als Datei herunterladen`}
+ title={`${t("session_detail.download_file_action")} ${label}`}
>
<Download className="h-3.5 w-3.5" />
</Button>
diff --git a/jarvis/ui/web/frontend/src/components/sessions/SessionList.tsx b/jarvis/ui/web/frontend/src/components/sessions/SessionList.tsx
index 2aebb4ffcd..b04bef7d48 100644
--- a/jarvis/ui/web/frontend/src/components/sessions/SessionList.tsx
+++ b/jarvis/ui/web/frontend/src/components/sessions/SessionList.tsx
@@ -11,6 +11,7 @@ import { Clock, Loader2, Mic, MicOff } from "lucide-react";
import { Badge } from "@/components/ui/badge";
import { ScrollArea } from "@/components/ui/scroll-area";
+import { translate, useT } from "@/i18n";
import { cn } from "@/lib/utils";
import type { SessionListItem } from "./types";
@@ -23,11 +24,12 @@ interface Props {
}
export function SessionList({ sessions, selectedId, onSelect, loading }: Props) {
+ const t = useT();
if (loading) {
return (
<div className="flex h-full items-center justify-center text-sm text-muted-foreground">
<Loader2 className="mr-2 h-4 w-4 animate-spin" />
- Lade Transkripte…
+ {t("session_list.loading")}
</div>
);
}
@@ -36,9 +38,9 @@ export function SessionList({ sessions, selectedId, onSelect, loading }: Props)
return (
<div className="flex h-full flex-col items-center justify-center gap-2 p-6 text-center text-sm text-muted-foreground">
<MicOff className="h-8 w-8 opacity-40" />
- <div className="font-medium">Noch keine Voice-Sessions</div>
+ <div className="font-medium">{t("session_list.empty_title")}</div>
<div className="text-xs">
- Sage dein Wake-Word — beim Auflegen erscheint die Session hier.
+ {t("session_list.empty_hint")}
</div>
</div>
);
@@ -66,7 +68,7 @@ export function SessionList({ sessions, selectedId, onSelect, loading }: Props)
</span>
{s.ended_ms === null ? (
<Badge variant="default" className="animate-pulse">
- läuft
+ {t("sessions.running")}
</Badge>
) : (
<Badge variant="secondary" className="text-[10px]">
@@ -77,7 +79,7 @@ export function SessionList({ sessions, selectedId, onSelect, loading }: Props)
<div className="line-clamp-2 text-foreground/90">
{s.preview || (
<span className="italic text-muted-foreground/70">
- (kein User-Text aufgezeichnet)
+ {t("session_list.no_user_text")}
</span>
)}
</div>
@@ -86,7 +88,7 @@ export function SessionList({ sessions, selectedId, onSelect, loading }: Props)
<Clock className="h-3 w-3" />
{formatDuration(s.duration_s)}
</span>
- <span>· {s.turn_count} Turns</span>
+ <span>· {s.turn_count} {t("session_list.turns")}</span>
{s.total_cost_usd > 0 && (
<span>· ${s.total_cost_usd.toFixed(4)}</span>
)}
@@ -101,38 +103,52 @@ export function SessionList({ sessions, selectedId, onSelect, loading }: Props)
// --- Helpers ---------------------------------------------------------
+// Compose "vor 5 min" / "5 min ago" / "hace 5 min" from a localized prefix and
+// suffix so the word order stays correct in every language. One side is empty
+// per locale (de/es use a prefix, en uses the "ago" suffix). Joined with a
+// single space and trimmed so the empty side leaves no double gap.
+function ago(value: string): string {
+ const prefix = translate("session_list.ago_prefix");
+ const suffix = translate("session_list.ago_suffix");
+ return [prefix, value, suffix].filter(Boolean).join(" ");
+}
+
function formatRelative(ms: number): string {
const diff = Date.now() - ms;
- if (diff < 60_000) return "gerade eben";
- if (diff < 3_600_000) return `vor ${Math.floor(diff / 60_000)} min`;
- if (diff < 86_400_000) return `vor ${Math.floor(diff / 3_600_000)} h`;
+ if (diff < 60_000) return translate("session_list.just_now");
+ if (diff < 3_600_000)
+ return ago(`${Math.floor(diff / 60_000)} ${translate("session_list.unit_min")}`);
+ if (diff < 86_400_000)
+ return ago(`${Math.floor(diff / 3_600_000)} ${translate("session_list.unit_hour")}`);
const d = new Date(ms);
- return d.toLocaleDateString("de", { day: "2-digit", month: "short" });
+ return d.toLocaleDateString(undefined, { day: "2-digit", month: "short" });
}
function formatDuration(secs: number | null): string {
- if (secs === null) return "läuft";
- if (secs < 60) return `${secs.toFixed(0)} s`;
+ if (secs === null) return translate("session_list.duration_running");
+ if (secs < 60) return `${secs.toFixed(0)} ${translate("session_list.unit_sec")}`;
const mins = Math.floor(secs / 60);
- if (mins < 60) return `${mins} min`;
+ if (mins < 60) return `${mins} ${translate("session_list.unit_min")}`;
const hours = Math.floor(mins / 60);
- return `${hours} h ${mins % 60} min`;
+ return `${hours} ${translate("session_list.unit_hour")} ${mins % 60} ${translate(
+ "session_list.unit_min",
+ )}`;
}
function hangupLabel(reason: string): string {
switch (reason) {
case "voice_pattern":
- return "Auflegen";
+ return translate("session_list.hangup_voice_pattern");
case "hotkey":
- return "Hotkey";
+ return translate("session_list.hangup_hotkey");
case "idle_timeout":
- return "Timeout";
+ return translate("session_list.hangup_idle_timeout");
case "shutdown":
- return "Shutdown";
+ return translate("session_list.hangup_shutdown");
case "error":
- return "Fehler";
+ return translate("session_list.hangup_error");
case "turn_complete":
- return "Antwort fertig";
+ return translate("session_list.hangup_turn_complete");
default:
return reason || "—";
}
diff --git a/jarvis/ui/web/frontend/src/components/sessions/TurnCard.test.tsx b/jarvis/ui/web/frontend/src/components/sessions/TurnCard.test.tsx
index 7177a3f5a0..dc5b34c082 100644
--- a/jarvis/ui/web/frontend/src/components/sessions/TurnCard.test.tsx
+++ b/jarvis/ui/web/frontend/src/components/sessions/TurnCard.test.tsx
@@ -33,6 +33,7 @@ function turn(over: Partial<VoiceTurnRow> = {}): VoiceTurnRow {
think_ms: 0,
speak_ms: 0,
tool_calls: [],
+ awaiting_confirmation: false,
...over,
};
}
@@ -71,9 +72,11 @@ describe("TurnCard spoken track", () => {
expect(screen.queryByText("Spoken output")).toBeNull();
});
- it("renders the technical detail line under a failure readback", () => {
- // The voice is humanized, but the transcript surfaces the exit code + raw
- // harness reason for debugging (user request 2026-06-16).
+ it("does NOT surface the technical detail in the transcript", () => {
+ // The technical diagnostic (exit code + raw harness reason) is still recorded
+ // on the SpeechSpoken event so the Run Inspector can show it, but it must NOT
+ // appear in the Transcription section — the transcript shows only what was
+ // said/spoken (user request 2026-06-22, reversing the 2026-06-16 ask).
render(
<TurnCard
turn={turn()}
@@ -86,14 +89,29 @@ describe("TurnCard spoken track", () => {
]}
/>,
);
+ // The spoken phrase is still shown…
+ expect(screen.getByText("Das am Bildschirm hat nicht geklappt.")).toBeTruthy();
+ // …but the technical detail (and its "detail" label) is not.
expect(
- screen.getByText("exit 5 · 5 guard-blocked actions this mission"),
- ).toBeTruthy();
+ screen.queryByText("exit 5 · 5 guard-blocked actions this mission"),
+ ).toBeNull();
+ expect(screen.queryByText("detail")).toBeNull();
});
- it("shows no detail line when a spoken phrase has no technical detail", () => {
- render(<TurnCard turn={turn()} spoken={[spokenLine()]} />);
- expect(screen.queryByText(/exit \d+/)).toBeNull();
+ it("omits the technical detail from the copied transcript text", () => {
+ // The copy-as-plain-text export is the transcript's textual form, so the
+ // technical detail must not ride along there either — only in the Run Inspector.
+ const copied = formatTurnPlain(turn({ ended_ms: 1_717_780_020_000 }), [
+ spokenLine({
+ ts_ms: 1_717_780_001_000,
+ spoken_kind: "completion",
+ text: "Das am Bildschirm hat nicht geklappt.", // i18n-allow: German voice fixture
+ detail: "exit 5 · 5 guard-blocked actions this mission",
+ }),
+ ]);
+ expect(copied).toContain("Das am Bildschirm hat nicht geklappt.");
+ expect(copied).not.toContain("[DETAIL]");
+ expect(copied).not.toContain("exit 5");
});
it("renders a sub-agent readback with its own label and a distinct colour", () => {
@@ -131,6 +149,34 @@ describe("TurnCard spoken track", () => {
expect(line?.className).not.toContain("violet");
});
+ it("labels a pending two-turn confirmation reply distinctly", () => {
+ render(
+ <TurnCard
+ turn={turn({
+ jarvis_text: "Soll ich die E-Mail wirklich senden? Sag ja oder nein.", // i18n-allow: German voice fixture
+ awaiting_confirmation: true,
+ })}
+ />,
+ );
+ expect(screen.getByText("Awaiting confirmation")).toBeTruthy();
+ });
+
+ it("shows no awaiting label on a normal settled reply", () => {
+ render(
+ <TurnCard
+ turn={turn({ jarvis_text: "Es ist drei Uhr.", awaiting_confirmation: false })} // i18n-allow: German voice fixture
+ />,
+ );
+ expect(screen.queryByText("Awaiting confirmation")).toBeNull();
+ });
+
+ it("marks a pending confirmation in the copied plain text", () => {
+ const copied = formatTurnPlain(
+ turn({ jarvis_text: "Soll ich senden?", awaiting_confirmation: true }), // i18n-allow: German voice fixture
+ );
+ expect(copied).toContain("(awaiting confirmation)");
+ });
+
it("copies spoken preambles before the final Jarvis reply", () => {
const copied = formatTurnPlain(
turn({ ended_ms: 1_717_780_020_000, jarvis_text: "Final answer." }),
diff --git a/jarvis/ui/web/frontend/src/components/sessions/TurnCard.tsx b/jarvis/ui/web/frontend/src/components/sessions/TurnCard.tsx
index 281b122795..efcfeab412 100644
--- a/jarvis/ui/web/frontend/src/components/sessions/TurnCard.tsx
+++ b/jarvis/ui/web/frontend/src/components/sessions/TurnCard.tsx
@@ -22,6 +22,7 @@ import { Button } from "@/components/ui/button";
import { Card, CardContent } from "@/components/ui/card";
import { downloadAs, robustCopy } from "@/lib/clipboard";
import { useEventStore } from "@/store/events";
+import { useT } from "@/i18n";
import type { VoiceSpokenLine, VoiceTurnRow } from "./types";
@@ -51,6 +52,7 @@ interface Props {
}
export function TurnCard({ turn, spoken = [] }: Props) {
+ const t = useT();
const pushToast = useEventStore((s) => s.pushToast);
const assistantName = useEventStore((s) => s.assistantName);
// Override the subagent label so it follows the configured assistant name.
@@ -64,9 +66,9 @@ export function TurnCard({ turn, spoken = [] }: Props) {
const ok = await robustCopy(text);
pushToast(
ok ? "success" : "error",
- ok ? `Turn ${turn.idx + 1} kopiert` : "Kopieren fehlgeschlagen",
+ ok ? `${t("turn_card.turn")} ${turn.idx + 1} ${t("turn_card.copied")}` : t("turn_card.copy_failed"),
);
- }, [turn, spoken, pushToast]);
+ }, [turn, spoken, pushToast, t]);
const downloadTurn = useCallback(() => {
const text = formatTurnPlain(turn, spoken);
@@ -76,8 +78,8 @@ export function TurnCard({ turn, spoken = [] }: Props) {
`voice-turn-${stamp.getFullYear()}-${pad(stamp.getMonth() + 1)}-${pad(stamp.getDate())}` +
`_${pad(stamp.getHours())}-${pad(stamp.getMinutes())}-${pad(stamp.getSeconds())}.txt`;
downloadAs(filename, text, "text/plain;charset=utf-8");
- pushToast("success", `Heruntergeladen als ${filename}`);
- }, [turn, spoken, pushToast]);
+ pushToast("success", `${t("turn_card.downloaded_as")} ${filename}`);
+ }, [turn, spoken, pushToast, t]);
const startedAt = new Date(turn.started_ms).toLocaleTimeString("de", {
hour: "2-digit",
@@ -111,10 +113,10 @@ export function TurnCard({ turn, spoken = [] }: Props) {
size="sm"
onClick={copyTurn}
className="h-7 px-2 text-xs"
- title="Diesen Turn kopieren"
+ title={t("turn_card.copy_turn")}
>
<Copy className="mr-1 h-3 w-3" />
- Kopieren
+ {t("turn_card.copy")}
</Button>
<Button
type="button"
@@ -122,7 +124,7 @@ export function TurnCard({ turn, spoken = [] }: Props) {
size="sm"
onClick={downloadTurn}
className="h-7 w-7 p-0"
- title="Diesen Turn als Datei herunterladen"
+ title={t("turn_card.download_turn")}
>
<Download className="h-3 w-3" />
</Button>
@@ -258,17 +260,12 @@ export function TurnCard({ turn, spoken = [] }: Props) {
{kindLabel[s.spoken_kind] ?? s.spoken_kind}
</Badge>
<div className="min-w-0 flex-1">
+ {/* Only the spoken phrase belongs in the transcript. The
+ technical diagnostic (exit code + raw harness reason)
+ stays on the recorded SpeechSpoken event and is shown
+ in the Run Inspector — never here (user request
+ 2026-06-22, reversing the 2026-06-16 ask). */}
<span className="break-words">{s.text}</span>
- {s.detail && (
- <div className="mt-1 flex items-start gap-1.5 font-mono text-[11px] text-muted-foreground">
- <span className="shrink-0 uppercase tracking-wide text-amber-400/80">
- detail
- </span>
- <span className="min-w-0 flex-1 break-words">
- {s.detail}
- </span>
- </div>
- )}
</div>
</div>
);
@@ -282,14 +279,14 @@ export function TurnCard({ turn, spoken = [] }: Props) {
<div className="grid grid-cols-2 gap-2 border-t border-border/50 pt-2 text-[11px]">
<div className="flex items-center gap-1.5">
<Hourglass className="h-3 w-3 text-amber-300" />
- <span className="text-muted-foreground">Nachgedacht:</span>
+ <span className="text-muted-foreground">{t("turn_card.thought")}</span>
<span className="font-mono text-foreground/90">
{turn.think_ms > 0 ? formatMs(turn.think_ms) : "—"}
</span>
</div>
<div className="flex items-center gap-1.5">
<Volume2 className="h-3 w-3 text-primary" />
- <span className="text-muted-foreground">Gesprochen:</span>
+ <span className="text-muted-foreground">{t("turn_card.spoke")}</span>
<span className="font-mono text-foreground/90">
{turn.speak_ms > 0 ? formatMs(turn.speak_ms) : "—"}
</span>
@@ -342,9 +339,9 @@ export function formatTurnPlain(
}
for (const s of spoken) {
const label = (SPOKEN_KIND_LABEL[s.spoken_kind] ?? s.spoken_kind).toUpperCase();
- const spokenLines = [`[SPOKEN: ${label}] ${s.text}`];
- if (s.detail) spokenLines.push(`[DETAIL] ${s.detail}`);
- jarvisLines.push({ ts_ms: s.ts_ms, lines: spokenLines });
+ // The technical detail is deliberately excluded from the transcript copy —
+ // it lives in the Run Inspector, not in what was said (user request 2026-06-22).
+ jarvisLines.push({ ts_ms: s.ts_ms, lines: [`[SPOKEN: ${label}] ${s.text}`] });
}
jarvisLines
.sort((a, b) => a.ts_ms - b.ts_ms)
diff --git a/jarvis/ui/web/frontend/src/components/sessions/types.ts b/jarvis/ui/web/frontend/src/components/sessions/types.ts
index c9366c77c7..3e69d1fe40 100644
--- a/jarvis/ui/web/frontend/src/components/sessions/types.ts
+++ b/jarvis/ui/web/frontend/src/components/sessions/types.ts
@@ -96,6 +96,10 @@ export interface VoiceTurnRow {
think_ms: number;
speak_ms: number;
tool_calls: string[];
+ // True when the turn ended on a two-turn voice/chat confirmation
+ // (finish_reason="voice_confirm_pending"): the reply is a pending yes/no
+ // question, not a settled answer, so the transcript labels it distinctly.
+ awaiting_confirmation: boolean;
}
export interface VoiceSessionRow {
diff --git a/jarvis/ui/web/frontend/src/components/wiki/BacklinksPanel.tsx b/jarvis/ui/web/frontend/src/components/wiki/BacklinksPanel.tsx
index fba9b1968d..54a5842b71 100644
--- a/jarvis/ui/web/frontend/src/components/wiki/BacklinksPanel.tsx
+++ b/jarvis/ui/web/frontend/src/components/wiki/BacklinksPanel.tsx
@@ -8,6 +8,7 @@
import { useQuery } from "@tanstack/react-query";
import { FileText } from "lucide-react";
+import { useT } from "@/i18n";
import { fetchWikiBacklinks } from "@/lib/wikiApi";
interface BacklinksPanelProps {
@@ -16,6 +17,7 @@ interface BacklinksPanelProps {
}
export function BacklinksPanel({ slug, onSelect }: BacklinksPanelProps) {
+ const t = useT();
const { data, isLoading, isError } = useQuery({
queryKey: ["wiki", "backlinks", slug],
queryFn: () => fetchWikiBacklinks(slug),
@@ -37,12 +39,12 @@ export function BacklinksPanel({ slug, onSelect }: BacklinksPanelProps) {
role="alert"
className="rounded-md border border-destructive/40 bg-destructive/10 px-3 py-2 text-xs text-destructive"
>
- Konnte Backlinks nicht laden.
+ {t("backlinks_panel.load_error")}
</div>
)}
{!isLoading && !isError && backlinks.length === 0 && (
<p className="text-xs text-muted-foreground" data-testid="wiki-backlinks-empty">
- Keine Backlinks.
+ {t("backlinks_panel.empty")}
</p>
)}
{!isLoading && !isError &&
diff --git a/jarvis/ui/web/frontend/src/components/wiki/ObsidianButton.tsx b/jarvis/ui/web/frontend/src/components/wiki/ObsidianButton.tsx
index d812efa395..ea3dbb8a49 100644
--- a/jarvis/ui/web/frontend/src/components/wiki/ObsidianButton.tsx
+++ b/jarvis/ui/web/frontend/src/components/wiki/ObsidianButton.tsx
@@ -3,6 +3,7 @@ import { ExternalLink } from "lucide-react";
import { Button } from "@/components/ui/button";
import { buildObsidianUrl } from "@/lib/obsidian";
import { useEventStore } from "@/store/events";
+import { useT } from "@/i18n";
/**
* Per-page "In Obsidian öffnen" button.
@@ -34,6 +35,7 @@ export function ObsidianButton({
size = "sm",
label,
}: ObsidianButtonProps): JSX.Element {
+ const t = useT();
const pushToast = useEventStore((s) => s.pushToast);
const handleClick = useCallback(() => {
@@ -49,7 +51,7 @@ export function ObsidianButton({
// the toast immediately in that case.
pushToast(
"warning",
- `Obsidian-Link konnte nicht ausgelöst werden: ${vaultRelPath || "Vault"}`,
+ `${t("obsidian_button.trigger_failed")}: ${vaultRelPath || "Vault"}`,
);
return;
}
@@ -62,19 +64,19 @@ export function ObsidianButton({
if (vaultRelPath) {
pushToast(
"info",
- `An Obsidian übergeben: ${vaultRelPath} — falls Obsidian nicht startet, ist es nicht installiert.`,
+ `${t("obsidian_button.handed_over")}: ${vaultRelPath} ${t("obsidian_button.not_installed_hint")}`,
);
} else {
pushToast(
"info",
- "Vault an Obsidian übergeben — falls Obsidian nicht startet, ist es nicht installiert.",
+ `${t("obsidian_button.vault_handed_over")} ${t("obsidian_button.not_installed_hint")}`,
);
}
}, FALLBACK_TOAST_DELAY_MS);
}, [pushToast, vaultRelPath]);
const buttonLabel =
- label ?? (vaultRelPath ? "In Obsidian öffnen" : "Vault in Obsidian öffnen");
+ label ?? (vaultRelPath ? t("obsidian_button.open_in_obsidian") : t("obsidian_button.open_vault_in_obsidian"));
return (
<Button
diff --git a/jarvis/ui/web/frontend/src/components/wiki/ObsidianSetupDialog.tsx b/jarvis/ui/web/frontend/src/components/wiki/ObsidianSetupDialog.tsx
index 78597625da..17f46f1a7e 100644
--- a/jarvis/ui/web/frontend/src/components/wiki/ObsidianSetupDialog.tsx
+++ b/jarvis/ui/web/frontend/src/components/wiki/ObsidianSetupDialog.tsx
@@ -22,8 +22,8 @@ import { Check, ExternalLink, Loader2, X } from "lucide-react";
import { Button } from "@/components/ui/button";
import { cn } from "@/lib/utils";
+import { useT } from "@/i18n";
import type { ObsidianStatus } from "@/types/setup";
-import { useEventStore } from "@/store/events";
export interface ObsidianSetupDialogProps {
/** Whether the dialog is visible. */
@@ -90,10 +90,11 @@ interface HeaderProps {
}
function StepHeader({ current, reached }: HeaderProps): JSX.Element {
+ const t = useT();
const stepLabels: Record<StepId, string> = {
- 1: "Installieren",
- 2: "Verbinden",
- 3: "Live-Test",
+ 1: t("obsidian_setup_dialog.step_install"),
+ 2: t("obsidian_setup_dialog.step_connect"),
+ 3: t("obsidian_setup_dialog.step_live_test"),
};
function stateOf(step: StepId): StepState {
@@ -161,7 +162,7 @@ export function ObsidianSetupDialog({
onComplete,
fetchImpl,
}: ObsidianSetupDialogProps): JSX.Element | null {
- const assistantName = useEventStore((s) => s.assistantName);
+ const t = useT();
const [currentStep, setCurrentStep] = useState<StepId>(() =>
decideInitialStep(initialStatus),
);
@@ -223,18 +224,14 @@ export function ObsidianSetupDialog({
advance(2);
}
} else {
- setInstallRetryHint(
- "Noch nicht erkannt. Vielleicht laeuft der Installer noch — probier es nochmal.",
- );
+ setInstallRetryHint(t("obsidian_setup_dialog.not_detected_hint"));
}
} catch {
- setInstallRetryHint(
- "Status konnte nicht geprueft werden. Versuch es bitte erneut.",
- );
+ setInstallRetryHint(t("obsidian_setup_dialog.status_check_failed"));
} finally {
setRefreshing(false);
}
- }, [advance, onStatusRefresh, vaultPath]);
+ }, [advance, onStatusRefresh, vaultPath, t]);
const handleRegister = useCallback(async () => {
setRegisterHint(null);
@@ -262,15 +259,15 @@ export function ObsidianSetupDialog({
} else {
// Defensive: 200 with an unexpected body — surface as error.
setRegisterError(
- `Konnte nicht registrieren: ${body.error ?? "unbekannter Status"}`,
+ `${t("obsidian_setup_dialog.register_failed")}: ${
+ body.error ?? t("obsidian_setup_dialog.unknown_status")
+ }`,
);
}
return;
}
if (res.status === 409) {
- setRegisterHint(
- "Bitte Obsidian einmal kurz starten und wieder schliessen — danach klick erneut.",
- );
+ setRegisterHint(t("obsidian_setup_dialog.restart_obsidian_hint"));
return;
}
// 500 or anything else: try to extract an error string from the
@@ -291,14 +288,14 @@ export function ObsidianSetupDialog({
} catch {
// Body wasn't JSON — keep HTTP status fallback.
}
- setRegisterError(`Konnte nicht registrieren: ${errMsg}`);
+ setRegisterError(`${t("obsidian_setup_dialog.register_failed")}: ${errMsg}`);
} catch (exc) {
const msg = exc instanceof Error ? exc.message : String(exc);
- setRegisterError(`Konnte nicht registrieren: ${msg}`);
+ setRegisterError(`${t("obsidian_setup_dialog.register_failed")}: ${msg}`);
} finally {
setRegistering(false);
}
- }, [advance]);
+ }, [advance, t]);
const vaultName = useMemo(() => deriveVaultName(vaultPath), [vaultPath]);
@@ -345,7 +342,7 @@ export function ObsidianSetupDialog({
type="button"
onClick={onClose}
className="absolute right-3 top-3 rounded-md p-1 text-muted-foreground hover:bg-secondary/40 hover:text-foreground"
- aria-label="Dialog schliessen"
+ aria-label={t("obsidian_setup_dialog.close_dialog")}
data-testid="obsidian-setup-close"
>
<X className="h-4 w-4" />
@@ -355,10 +352,10 @@ export function ObsidianSetupDialog({
id="obsidian-setup-title"
className="mb-1 text-base font-semibold text-foreground"
>
- Obsidian einrichten
+ {t("obsidian_setup_dialog.title")}
</h2>
<p className="mb-3 text-xs text-muted-foreground">
- Drei kleine Schritte und dein Wiki ist live in Obsidian.
+ {t("obsidian_setup_dialog.subtitle")}
</p>
<StepHeader current={currentStep} reached={reached} />
@@ -373,12 +370,11 @@ export function ObsidianSetupDialog({
id="obsidian-setup-step-1-title"
className="text-sm font-semibold text-foreground"
>
- Obsidian installieren
+ {t("obsidian_setup_dialog.install_heading")}
</h3>
<p className="text-sm text-muted-foreground">
- {assistantName} schreibt das Wiki als Markdown-Dateien auf die Platte.
- Damit du sie wie eine echte Wissensdatenbank durchstoebern und
- bearbeiten kannst, brauchst du den kostenlosen Editor{" "}
+ {t("obsidian_setup_dialog.install_body_1")}{" "}
+ {t("obsidian_setup_dialog.install_body_2")}{" "}
<strong>Obsidian</strong>.
</p>
<a
@@ -389,7 +385,7 @@ export function ObsidianSetupDialog({
data-testid="obsidian-setup-download-link"
>
<ExternalLink className="h-3.5 w-3.5" aria-hidden />
- obsidian.md/download oeffnen
+ {t("obsidian_setup_dialog.download_link")}
</a>
{installRetryHint && (
<p
@@ -408,7 +404,7 @@ export function ObsidianSetupDialog({
onClick={onClose}
data-testid="obsidian-setup-cancel"
>
- Abbrechen
+ {t("common.cancel")}
</Button>
<Button
type="button"
@@ -423,10 +419,10 @@ export function ObsidianSetupDialog({
className="mr-1.5 h-3.5 w-3.5 animate-spin"
aria-hidden
/>
- Pruefe…
+ {t("obsidian_setup_dialog.checking")}
</>
) : (
- "Ich habs installiert — weiter"
+ t("obsidian_setup_dialog.installed_continue")
)}
</Button>
</div>
@@ -443,22 +439,22 @@ export function ObsidianSetupDialog({
id="obsidian-setup-step-2-title"
className="text-sm font-semibold text-foreground"
>
- Vault anbinden
+ {t("obsidian_setup_dialog.connect_heading")}
</h3>
<p className="text-sm text-muted-foreground">
- Jetzt traegt {assistantName} sein Wiki in deine Obsidian-Konfiguration ein.
- Damit erscheint es im Vault-Switcher und das{" "}
+ {t("obsidian_setup_dialog.connect_body_1")}{" "}
+ {t("obsidian_setup_dialog.connect_body_2")}{" "}
<code className="rounded bg-background px-1 py-0.5 font-mono text-[12px]">
obsidian://
- </code>
- -Protokoll funktioniert.
+ </code>{" "}
+ {t("obsidian_setup_dialog.connect_body_3")}
</p>
<p
className="rounded-md border border-border bg-background/40 px-3 py-2 text-xs text-muted-foreground"
data-testid="obsidian-setup-vault-path"
>
<span className="block text-[10px] uppercase tracking-wide text-muted-foreground/70">
- Vault-Pfad
+ {t("obsidian_setup_dialog.vault_path_label")}
</span>
<span className="font-mono text-foreground">{vaultPath}</span>
</p>
@@ -486,7 +482,7 @@ export function ObsidianSetupDialog({
data-testid="obsidian-setup-help-link"
>
<ExternalLink className="h-3 w-3" aria-hidden />
- Hilfe oeffnen
+ {t("obsidian_setup_dialog.open_help")}
</a>
</div>
)}
@@ -498,7 +494,7 @@ export function ObsidianSetupDialog({
onClick={onClose}
data-testid="obsidian-setup-cancel"
>
- Abbrechen
+ {t("common.cancel")}
</Button>
<Button
type="button"
@@ -513,10 +509,10 @@ export function ObsidianSetupDialog({
className="mr-1.5 h-3.5 w-3.5 animate-spin"
aria-hidden
/>
- Registriere…
+ {t("obsidian_setup_dialog.registering")}
</>
) : (
- "Jetzt registrieren"
+ t("obsidian_setup_dialog.register_now")
)}
</Button>
</div>
@@ -533,11 +529,10 @@ export function ObsidianSetupDialog({
id="obsidian-setup-step-3-title"
className="text-sm font-semibold text-foreground"
>
- Live-Test
+ {t("obsidian_setup_dialog.step_live_test")}
</h3>
<p className="text-sm text-muted-foreground">
- Klick den Knopf — dein Browser oeffnet das Vault direkt in
- Obsidian.
+ {t("obsidian_setup_dialog.live_test_body")}
</p>
<div className="flex items-center justify-start gap-2 pt-1">
<Button
@@ -547,7 +542,7 @@ export function ObsidianSetupDialog({
data-testid="obsidian-setup-launch"
>
<ExternalLink className="mr-1.5 h-3.5 w-3.5" aria-hidden />
- In Obsidian oeffnen
+ {t("obsidian_setup_dialog.open_in_obsidian")}
</Button>
</div>
<div className="flex flex-col items-stretch gap-2 pt-2 sm:flex-row sm:items-center sm:justify-end">
@@ -558,7 +553,7 @@ export function ObsidianSetupDialog({
onClick={handleTroubleshoot}
data-testid="obsidian-setup-troubleshoot"
>
- Hat nicht geklappt
+ {t("obsidian_setup_dialog.did_not_work")}
</Button>
<Button
type="button"
@@ -566,7 +561,7 @@ export function ObsidianSetupDialog({
onClick={handleComplete}
data-testid="obsidian-setup-finish"
>
- Hat geklappt — Fertig
+ {t("obsidian_setup_dialog.it_worked")}
</Button>
</div>
</section>
diff --git a/jarvis/ui/web/frontend/src/components/wiki/ObsidianStatus.tsx b/jarvis/ui/web/frontend/src/components/wiki/ObsidianStatus.tsx
index a81e4d4609..3b8079358d 100644
--- a/jarvis/ui/web/frontend/src/components/wiki/ObsidianStatus.tsx
+++ b/jarvis/ui/web/frontend/src/components/wiki/ObsidianStatus.tsx
@@ -17,6 +17,7 @@ import { useCallback, useEffect, useRef, useState } from "react";
import { CheckCircle2, AlertTriangle, Download, HelpCircle } from "lucide-react";
import { cn } from "@/lib/utils";
+import { useT } from "@/i18n";
import type { ObsidianStatus as ObsidianStatusType } from "@/types/setup";
interface Props {
@@ -59,13 +60,15 @@ const VISUAL_STYLE: Record<Visual, string> = {
"border-[#8d94a8]/40 bg-[#8d94a8]/10 text-[#8d94a8] cursor-pointer hover:bg-[#8d94a8]/20",
};
-const VISUAL_LABEL: Record<Visual, string> = {
- loading: "Obsidian: …",
- ok: "Obsidian: verbunden",
- register: "Obsidian: nicht registriert",
- install: "Obsidian: nicht installiert",
- unclear: "Obsidian: Status unklar",
-};
+function visualLabels(t: (key: string) => string): Record<Visual, string> {
+ return {
+ loading: t("obsidian_status.loading"),
+ ok: t("obsidian_status.connected"),
+ register: t("obsidian_status.not_registered"),
+ install: t("obsidian_status.not_installed"),
+ unclear: t("obsidian_status.unclear"),
+ };
+}
function VisualIcon({ visual }: { visual: Visual }): JSX.Element {
if (visual === "ok") {
@@ -105,6 +108,7 @@ export function ObsidianStatus({
fetchImpl,
pollIntervalMs = DEFAULT_POLL_MS,
}: Props): JSX.Element {
+ const t = useT();
const [status, setStatus] = useState<ObsidianStatusType | null>(null);
const [errored, setErrored] = useState(false);
// Initial fetch must show LOADING — track whether at least one fetch
@@ -150,7 +154,7 @@ export function ObsidianStatus({
}, [doFetch, pollIntervalMs]);
const visual: Visual = resolvedOnce ? classify(status, errored) : "loading";
- const label = VISUAL_LABEL[visual];
+ const label = visualLabels(t)[visual];
const tooltip =
visual === "ok" && status
@@ -158,10 +162,10 @@ export function ObsidianStatus({
? `${status.vault_path} · Obsidian ${status.version}`
: status.vault_path
: visual === "loading"
- ? "Status wird geladen…"
+ ? t("obsidian_status.loading_tooltip")
: status?.note
? status.note
- : "Klick für Setup";
+ : t("obsidian_status.click_for_setup");
const handleClick = useCallback(() => {
if (visual === "loading" || visual === "ok") return;
@@ -175,10 +179,10 @@ export function ObsidianStatus({
vault_registered: false,
vault_path: "",
recommended_action: "install_obsidian",
- note: "Status konnte nicht geladen werden.",
+ note: t("obsidian_status.load_failed_note"),
};
onOpenSetup(payload);
- }, [visual, status, errored, onOpenSetup]);
+ }, [visual, status, errored, onOpenSetup, t]);
const interactive = visual !== "ok" && visual !== "loading";
diff --git a/jarvis/ui/web/frontend/src/components/wiki/PageHeader.tsx b/jarvis/ui/web/frontend/src/components/wiki/PageHeader.tsx
index 19d0aa600d..755b34f7d2 100644
--- a/jarvis/ui/web/frontend/src/components/wiki/PageHeader.tsx
+++ b/jarvis/ui/web/frontend/src/components/wiki/PageHeader.tsx
@@ -7,6 +7,7 @@
*/
import { lazy, Suspense } from "react";
+import { useT } from "@/i18n";
import type { WikiKind } from "@/lib/wikiApi";
import { cn } from "@/lib/utils";
@@ -128,6 +129,7 @@ function breadcrumbFromPath(relPath: string): string[] {
}
function ObsidianButtonPlaceholder({ vaultRelPath: _vaultRelPath }: { vaultRelPath: string }) {
+ const t = useT();
return (
<button
type="button"
@@ -137,12 +139,12 @@ function ObsidianButtonPlaceholder({ vaultRelPath: _vaultRelPath }: { vaultRelPa
"px-3.5 py-2 text-sm text-muted-foreground opacity-60",
)}
data-testid="obsidian-button-placeholder"
- title="Wird durch Agent D bereitgestellt"
+ title={t("page_header.placeholder_title")}
>
<span className="grid h-4 w-4 place-items-center rounded-sm bg-[#b48cf2] text-[10px] font-bold text-background">
O
</span>
- In Obsidian öffnen
+ {t("page_header.open_in_obsidian")}
</button>
);
}
diff --git a/jarvis/ui/web/frontend/src/components/wiki/PageRenderer.tsx b/jarvis/ui/web/frontend/src/components/wiki/PageRenderer.tsx
index e876cd5d7e..5d4177c969 100644
--- a/jarvis/ui/web/frontend/src/components/wiki/PageRenderer.tsx
+++ b/jarvis/ui/web/frontend/src/components/wiki/PageRenderer.tsx
@@ -23,6 +23,7 @@ import {
type WikiTreeResponse,
} from "@/lib/wikiApi";
import { cn } from "@/lib/utils";
+import { useT } from "@/i18n";
import { PageHeader } from "./PageHeader";
@@ -38,6 +39,7 @@ const WIKILINK_PREFIX = "#wiki:";
const WIKILINK_RE = /\[\[([^\]|\n]+)(?:\|([^\]\n]+))?\]\]/g;
export function PageRenderer({ slug, onWikilinkClick }: PageRendererProps) {
+ const t = useT();
const qc = useQueryClient();
const pageQuery = useQuery({
queryKey: ["wiki", "page", slug],
@@ -74,7 +76,7 @@ export function PageRenderer({ slug, onWikilinkClick }: PageRendererProps) {
role="alert"
className="rounded-md border border-destructive/40 bg-destructive/10 px-4 py-3 text-sm text-destructive"
>
- Seite konnte nicht geladen werden.
+ {t("page_renderer.load_error")}
</div>
</div>
);
@@ -88,7 +90,7 @@ export function PageRenderer({ slug, onWikilinkClick }: PageRendererProps) {
role="alert"
className="rounded-md border border-destructive/40 bg-destructive/10 px-4 py-3 text-sm text-destructive"
>
- {page?.error ?? "Seite nicht gefunden."}
+ {page?.error ?? t("page_renderer.not_found")}
</div>
</div>
);
diff --git a/jarvis/ui/web/frontend/src/components/wiki/TreeSidebar.tsx b/jarvis/ui/web/frontend/src/components/wiki/TreeSidebar.tsx
index 7db2350273..621a3bfd0a 100644
--- a/jarvis/ui/web/frontend/src/components/wiki/TreeSidebar.tsx
+++ b/jarvis/ui/web/frontend/src/components/wiki/TreeSidebar.tsx
@@ -12,6 +12,7 @@ import { useQuery } from "@tanstack/react-query";
import { cn } from "@/lib/utils";
import { fetchWikiTree, type WikiTreeFolder } from "@/lib/wikiApi";
+import { useT } from "@/i18n";
interface TreeSidebarProps {
selectedSlug: string | null;
@@ -29,6 +30,7 @@ const FOLDER_SWATCH: Record<string, string> = {
const DEFAULT_OPEN = new Set(["entities", "projects"]);
export function TreeSidebar({ selectedSlug, onSelect }: TreeSidebarProps) {
+ const t = useT();
const { data, isLoading, isError } = useQuery({
queryKey: ["wiki", "tree"],
queryFn: fetchWikiTree,
@@ -104,7 +106,7 @@ export function TreeSidebar({ selectedSlug, onSelect }: TreeSidebarProps) {
role="alert"
className="m-2 rounded-md border border-destructive/40 bg-destructive/10 px-3 py-2 text-xs text-destructive"
>
- Konnte das Wiki nicht laden.
+ {t("tree_sidebar.load_error")}
</div>
)}
@@ -193,7 +195,7 @@ export function TreeSidebar({ selectedSlug, onSelect }: TreeSidebarProps) {
<span className="text-foreground">{stats.total_links}</span>
</div>
<div className="flex justify-between">
- <span>Letzte Änderung</span>
+ <span>{t("tree_sidebar.last_change")}</span>
<span className="text-foreground">{lastChangedLabel}</span>
</div>
</div>
diff --git a/jarvis/ui/web/frontend/src/components/wiki/WikiGraph.tsx b/jarvis/ui/web/frontend/src/components/wiki/WikiGraph.tsx
index bba9534e15..e678b3568a 100644
--- a/jarvis/ui/web/frontend/src/components/wiki/WikiGraph.tsx
+++ b/jarvis/ui/web/frontend/src/components/wiki/WikiGraph.tsx
@@ -24,13 +24,10 @@ import {
type WikiGraphPayload,
} from "@/lib/wikiGraph";
import { useEventStore } from "@/store/events";
+import { useT } from "@/i18n";
const GRAPH_QUERY_KEY = ["wiki", "graph"] as const;
-function emptyStateDe(name: string): string {
- return `Dein Memory-Graph ist noch leer. Sobald ${name} Notizen anlegt, verbinden sich die Knoten hier automatisch.`;
-}
-
async function fetchGraph(): Promise<WikiGraphPayload> {
const res = await fetch("/api/wiki/graph");
if (!res.ok) throw new Error(`HTTP ${res.status}`);
@@ -50,6 +47,7 @@ export interface WikiGraphProps {
*/
export function WikiGraph({ onNodeClick, highlightSlug }: WikiGraphProps): JSX.Element {
const assistantName = useEventStore((s) => s.assistantName);
+ const t = useT();
const { data, isLoading, isError } = useQuery({
queryKey: GRAPH_QUERY_KEY,
queryFn: fetchGraph,
@@ -195,7 +193,7 @@ export function WikiGraph({ onNodeClick, highlightSlug }: WikiGraphProps): JSX.E
data-testid="wiki-graph-loading"
className="flex h-full items-center justify-center text-sm text-muted-foreground"
>
- Lade Graph…
+ {t("wiki_graph.loading")}
</div>
);
}
@@ -206,7 +204,7 @@ export function WikiGraph({ onNodeClick, highlightSlug }: WikiGraphProps): JSX.E
data-testid="wiki-graph-error"
className="flex h-full items-center justify-center text-sm text-muted-foreground"
>
- Graph konnte nicht geladen werden.
+ {t("wiki_graph.load_error")}
</div>
);
}
@@ -217,7 +215,9 @@ export function WikiGraph({ onNodeClick, highlightSlug }: WikiGraphProps): JSX.E
data-testid="wiki-graph-empty"
className="flex h-full items-center justify-center px-8 text-center text-sm text-muted-foreground"
>
- {emptyStateDe(assistantName)}
+ {t("wiki_graph.empty_prefix")}
+ {assistantName}
+ {t("wiki_graph.empty_suffix")}
</div>
);
}
@@ -300,9 +300,9 @@ export function WikiGraph({ onNodeClick, highlightSlug }: WikiGraphProps): JSX.E
onClick={handleResetView}
data-testid="wiki-graph-reset-view"
className="absolute top-3 right-3 z-10 rounded-md border border-border bg-card/80 px-3 py-1.5 text-xs text-muted-foreground backdrop-blur transition hover:text-foreground hover:bg-card"
- title="Zoom auf alle Knoten zurücksetzen"
+ title={t("wiki_graph.reset_view_title")}
>
- Zentrieren
+ {t("wiki_graph.center")}
</button>
{/* Hidden DOM mirror — keeps the canvas-based graph testable without a
full canvas mock. The visible canvas remains the source of truth for
diff --git a/jarvis/ui/web/frontend/src/components/wiki/WikiSearch.tsx b/jarvis/ui/web/frontend/src/components/wiki/WikiSearch.tsx
index f00c069f33..7aef5d1901 100644
--- a/jarvis/ui/web/frontend/src/components/wiki/WikiSearch.tsx
+++ b/jarvis/ui/web/frontend/src/components/wiki/WikiSearch.tsx
@@ -17,6 +17,7 @@ import { Command } from "cmdk";
import { useQuery, useQueryClient } from "@tanstack/react-query";
import { colourForKind } from "@/lib/wikiGraph";
+import { useT } from "@/i18n";
const SEARCH_DEBOUNCE_MS = 200;
const SEARCH_LIMIT = 8;
@@ -135,6 +136,7 @@ export const WikiSearch = forwardRef<WikiSearchHandle, WikiSearchProps>(function
{ onResultClick },
ref,
): JSX.Element {
+ const t = useT();
const [open, setOpen] = useState(false);
const [rawQuery, setRawQuery] = useState("");
const [debouncedQuery, setDebouncedQuery] = useState("");
@@ -197,23 +199,23 @@ export const WikiSearch = forwardRef<WikiSearchHandle, WikiSearchProps>(function
<Command.Dialog
open={open}
onOpenChange={setOpen}
- label="Wiki-Suche"
+ label={t("wiki_search.dialog_label")}
data-testid="wiki-search-dialog"
contentClassName="fixed left-1/2 top-[20vh] z-50 w-[min(640px,90vw)] -translate-x-1/2 rounded-xl border border-border bg-background shadow-2xl"
overlayClassName="fixed inset-0 z-40 bg-black/40 backdrop-blur-sm"
>
{/* Screen-reader-only title and description — required by Radix Dialog's
a11y contract; visually hidden so the palette UI stays clean. */}
- <h2 className="sr-only">Wiki-Suche</h2>
+ <h2 className="sr-only">{t("wiki_search.dialog_label")}</h2>
<p className="sr-only" id="wiki-search-description">
- Volltext-Suche im Vault. Tippe einen Begriff oder navigiere mit den Pfeiltasten.
+ {t("wiki_search.dialog_description")}
</p>
<div className="flex items-center gap-2 border-b border-border px-3 py-2">
<span aria-hidden="true" className="text-muted-foreground">⌕</span>
<Command.Input
value={rawQuery}
onValueChange={setRawQuery}
- placeholder="Volltext-Suche im Vault…"
+ placeholder={t("wiki_search.input_placeholder")}
data-testid="wiki-search-input"
className="flex-1 bg-transparent text-sm outline-none placeholder:text-muted-foreground"
autoFocus
@@ -228,10 +230,10 @@ export const WikiSearch = forwardRef<WikiSearchHandle, WikiSearchProps>(function
className="max-h-[60vh] overflow-y-auto p-2 text-sm"
>
{debouncedQuery.length === 0 ? (
- <Command.Group heading="Zuletzt geändert" data-testid="wiki-search-recent">
+ <Command.Group heading={t("wiki_search.recent_heading")} data-testid="wiki-search-recent">
{recent.length === 0 ? (
<div className="px-2 py-3 text-muted-foreground" data-testid="wiki-search-recent-empty">
- Noch keine Seiten im Vault.
+ {t("wiki_search.no_pages")}
</div>
) : (
recent.map((entry) => (
@@ -256,28 +258,28 @@ export const WikiSearch = forwardRef<WikiSearchHandle, WikiSearchProps>(function
</Command.Group>
) : isFetching ? (
<div className="px-2 py-3 text-muted-foreground" data-testid="wiki-search-loading">
- Suche läuft…
+ {t("wiki_search.searching")}
</div>
) : isError || !data?.ok ? (
<div
className="flex flex-col items-start gap-2 px-2 py-3 text-muted-foreground"
data-testid="wiki-search-error"
>
- <span>Suche gerade nicht verfügbar.</span>
+ <span>{t("wiki_search.unavailable")}</span>
<button
type="button"
onClick={() => refetch()}
className="text-xs underline hover:text-foreground"
>
- Erneut versuchen
+ {t("common.retry")}
</button>
</div>
) : data.hits.length === 0 ? (
<Command.Empty data-testid="wiki-search-empty">
- Keine Treffer für &quot;{debouncedQuery}&quot;. Versuche andere Stichworte oder schau in den Graph.
+ {t("wiki_search.no_hits_prefix")}&quot;{debouncedQuery}&quot;{t("wiki_search.no_hits_suffix")}
</Command.Empty>
) : (
- <Command.Group heading="Treffer" data-testid="wiki-search-hits">
+ <Command.Group heading={t("wiki_search.hits_heading")} data-testid="wiki-search-hits">
{data.hits.map((hit) => (
<Command.Item
key={hit.slug}
diff --git a/jarvis/ui/web/frontend/src/hooks/useAgentInstructions.ts b/jarvis/ui/web/frontend/src/hooks/useAgentInstructions.ts
new file mode 100644
index 0000000000..6ecdc3ec65
--- /dev/null
+++ b/jarvis/ui/web/frontend/src/hooks/useAgentInstructions.ts
@@ -0,0 +1,89 @@
+import { useCallback, useEffect, useState } from "react";
+
+/**
+ * Agent-instructions config from GET /api/settings/agent-instructions.
+ *
+ * This is the user's own standing-instructions file (an AGENTS.md / CLAUDE.md
+ * equivalent), named after the assistant (`filename`, e.g. "Ruben.md"). `content`
+ * is the current text ("" when none), `exists` drives the Active/Empty badge, and
+ * `template` is a starter the UI can load into an empty editor.
+ */
+export interface AgentInstructionsConfig {
+ content: string;
+ exists: boolean;
+ filename: string;
+ template: string;
+ char_count: number;
+}
+
+export interface AgentInstructionsSaveResult extends AgentInstructionsConfig {
+ ok: boolean;
+ removed?: boolean;
+ restart_required: boolean;
+}
+
+/**
+ * Loads /api/settings/agent-instructions and exposes save()/reset(). Mirrors
+ * useSystemPrompt. The file applies on the assistant's next turn (no restart),
+ * so there is no restart plumbing here.
+ */
+export function useAgentInstructions() {
+ const [config, setConfig] = useState<AgentInstructionsConfig | null>(null);
+ const [loading, setLoading] = useState(true);
+ const [error, setError] = useState<string | null>(null);
+
+ const refetch = useCallback(async () => {
+ setError(null);
+ try {
+ const res = await fetch("/api/settings/agent-instructions");
+ if (!res.ok) throw new Error(`HTTP ${res.status}`);
+ const data: AgentInstructionsConfig = await res.json();
+ setConfig(data);
+ } catch (e) {
+ setError((e as Error).message);
+ } finally {
+ setLoading(false);
+ }
+ }, []);
+
+ useEffect(() => {
+ void refetch();
+ }, [refetch]);
+
+ const save = useCallback(
+ async (content: string): Promise<AgentInstructionsSaveResult> => {
+ const isClearing = content.trim().length === 0;
+ const res = await fetch(
+ "/api/settings/agent-instructions",
+ isClearing
+ ? { method: "DELETE" }
+ : {
+ method: "PUT",
+ headers: { "Content-Type": "application/json" },
+ body: JSON.stringify({ content }),
+ },
+ );
+ const body = await res.json().catch(() => ({}));
+ if (!res.ok) {
+ throw new Error(body.detail ?? `HTTP ${res.status}`);
+ }
+ const result = body as AgentInstructionsSaveResult;
+ setConfig(result);
+ return result;
+ },
+ [],
+ );
+
+ const reset = useCallback(async (): Promise<AgentInstructionsSaveResult> => {
+ const res = await fetch("/api/settings/agent-instructions", { method: "DELETE" });
+ const body = await res.json().catch(() => ({}));
+ if (!res.ok) {
+ throw new Error(body.detail ?? `HTTP ${res.status}`);
+ }
+ const result = body as AgentInstructionsSaveResult;
+ setConfig(result);
+ return result;
+ }, []);
+
+ return { config, loading, error, refetch, save, reset };
+}
diff --git a/jarvis/ui/web/frontend/src/hooks/useProviders.ts b/jarvis/ui/web/frontend/src/hooks/useProviders.ts
index 696c004274..5b519e2707 100644
--- a/jarvis/ui/web/frontend/src/hooks/useProviders.ts
+++ b/jarvis/ui/web/frontend/src/hooks/useProviders.ts
@@ -39,6 +39,12 @@ export interface ProviderDescriptor {
signup_url: string | null;
/** How using this provider is billed. */
billing: Billing;
+ /** Maintainer-recommended pick for this tier — renders a "Recommended" badge
+ * on the provider card (brain tier only today). Presentation hint only. */
+ recommended?: boolean;
+ /** The model the recommendation points at (e.g. "gemini-3.5-flash"), shown as
+ * an "empfohlen" marker in the model picker. null = provider-level only. */
+ recommended_model?: string | null;
/** Gemini's Vertex alternative; null for single-path providers. */
alt_credential: AltCredential | null;
/**
@@ -465,3 +471,57 @@ export async function saveBrainProviderModel(
return body as BrainModelSaveResult;
}
+// Phase 3: per-provider Computer-Use model. CU runs on the provider's main
+// `model` by default; a pinned `cu_model` lets the user run CU on a different
+// (e.g. stronger) model than chat. `cu_model === ""` means "use my main model".
+export interface CuModelResult {
+ ok?: boolean;
+ provider: string;
+ cu_model: string; // the pinned value ("" = use the main model)
+ effective_model: string; // what Computer-Use would actually run
+ uses_main: boolean; // true when nothing is pinned
+ persisted?: boolean;
+ restart_required?: boolean;
+}
+
+/** Reads the per-provider Computer-Use model selection. */
+export async function getCuModel(providerId: string): Promise<CuModelResult> {
+ const res = await fetch(`/api/providers/${encodeURIComponent(providerId)}/cu-model`);
+ const body = await res.json().catch(() => ({}));
+ if (!res.ok) {
+ throw new Error(body.detail ?? `HTTP ${res.status}`);
+ }
+ return body as CuModelResult;
+}
+
+/**
+ * Pins (or clears with "") the per-provider Computer-Use model. Returns a
+ * BrainModelSaveResult shape so it can drive the shared BrainModelSelector's
+ * `onSave`. No live probe — CU validates the model lazily on its next dispatch.
+ */
+export async function saveCuModel(
+ providerId: string,
+ cuModel: string,
+ persist = true,
+): Promise<BrainModelSaveResult> {
+ const res = await fetch(`/api/providers/${encodeURIComponent(providerId)}/cu-model`, {
+ method: "PUT",
+ headers: { "Content-Type": "application/json" },
+ body: JSON.stringify({ cu_model: cuModel, persist }),
+ });
+ const body = await res.json().catch(() => ({}));
+ if (!res.ok) {
+ throw new Error(body.detail ?? `HTTP ${res.status}`);
+ }
+ const r = body as CuModelResult;
+ return {
+ ok: r.ok ?? true,
+ provider: r.provider,
+ model: r.cu_model,
+ persisted: r.persisted ?? false,
+ applied_live: !(r.restart_required ?? false),
+ restart_required: r.restart_required ?? false,
+ probe: null,
+ };
+}
+
diff --git a/jarvis/ui/web/frontend/src/hooks/useSoundEffects.ts b/jarvis/ui/web/frontend/src/hooks/useSoundEffects.ts
new file mode 100644
index 0000000000..96b245fb37
--- /dev/null
+++ b/jarvis/ui/web/frontend/src/hooks/useSoundEffects.ts
@@ -0,0 +1,52 @@
+import { useCallback, useEffect, useState } from "react";
+
+/** Global "Sound effects" master switch (ui.sound_effects). Mutes/unmutes all
+ * synthesized earcons (wake chime, hang-up tone, boot-ready cue) at once. The
+ * spoken voice is unaffected. */
+export interface SoundEffectsResult {
+ ok: boolean;
+ enabled: boolean;
+ persisted: boolean;
+ applied_live: boolean;
+}
+
+export function useSoundEffects() {
+ const [enabled, setEnabledState] = useState<boolean | null>(null);
+ const [loading, setLoading] = useState(true);
+ const [error, setError] = useState<string | null>(null);
+
+ const refetch = useCallback(async () => {
+ setError(null);
+ try {
+ const res = await fetch("/api/settings/sound-effects");
+ if (!res.ok) throw new Error(`HTTP ${res.status}`);
+ const data = await res.json();
+ setEnabledState(Boolean(data.enabled));
+ } catch (e) {
+ setError((e as Error).message);
+ } finally {
+ setLoading(false);
+ }
+ }, []);
+
+ useEffect(() => {
+ void refetch();
+ }, [refetch]);
+
+ const setEnabled = useCallback(
+ async (next: boolean): Promise<SoundEffectsResult> => {
+ const res = await fetch("/api/settings/sound-effects", {
+ method: "PUT",
+ headers: { "Content-Type": "application/json" },
+ body: JSON.stringify({ enabled: next }),
+ });
+ const body = await res.json().catch(() => ({}));
+ if (!res.ok) throw new Error(body.detail ?? `HTTP ${res.status}`);
+ setEnabledState(Boolean(body.enabled));
+ return body as SoundEffectsResult;
+ },
+ [],
+ );
+
+ return { enabled, loading, error, refetch, setEnabled };
+}
diff --git a/jarvis/ui/web/frontend/src/hooks/useWebSocket.ts b/jarvis/ui/web/frontend/src/hooks/useWebSocket.ts
index ce339028c1..5cac7dace1 100644
--- a/jarvis/ui/web/frontend/src/hooks/useWebSocket.ts
+++ b/jarvis/ui/web/frontend/src/hooks/useWebSocket.ts
@@ -9,7 +9,7 @@ import {
} from "@/store/events";
import { useSubAgentStore, SUB_AGENT_EVENT_NAMES } from "@/store/subAgents";
import { WSEventEnvelope, WSWelcome } from "@/schema/ws";
-import { useI18nStore, hydrateUiLanguage, hydrateReplyLanguage } from "@/i18n";
+import { useI18nStore, hydrateUiLanguage, hydrateReplyLanguage, translate } from "@/i18n";
let singleton: WSClient | null = null;
@@ -176,7 +176,10 @@ export function useWebSocket(): void {
const p = env.payload as { section?: string };
if (isSectionId(p.section)) {
setActiveSection(p.section);
- pushToast("info", `Jarvis oeffnete ${SECTION_LABELS[p.section]}`);
+ pushToast(
+ "info",
+ `${translate("use_web_socket.jarvis_opened")} ${SECTION_LABELS[p.section]}`,
+ );
}
}
diff --git a/jarvis/ui/web/frontend/src/i18n/index.ts b/jarvis/ui/web/frontend/src/i18n/index.ts
index 601c8e587e..5dfa42efe1 100644
--- a/jarvis/ui/web/frontend/src/i18n/index.ts
+++ b/jarvis/ui/web/frontend/src/i18n/index.ts
@@ -218,6 +218,21 @@ export function interpolateName(text: string, name: string): string {
return text.replace(NAME_TOKEN, name);
}
+/**
+ * Imperative, non-hook translate accessor.
+ *
+ * `useT` is a React hook and is illegal outside a component body (class
+ * components, module-level helpers). This reads the current UI language from
+ * the store directly — the same pattern the codebase already uses via
+ * `useEventStore.getState()`. It interpolates the assistant name too, so the
+ * `{name}` token works the same as in `useT`.
+ */
+export function translate(key: string): string {
+ const lang = useI18nStore.getState().ui;
+ const name = useEventStore.getState().assistantName;
+ return interpolateName(resolve(lang, key), name);
+}
+
export function useT(): (key: string) => string {
const lang = useI18nStore((s) => s.ui);
// Reactive: every t() consumer re-renders when the assistant name changes,
diff --git a/jarvis/ui/web/frontend/src/i18n/locales/de.json b/jarvis/ui/web/frontend/src/i18n/locales/de.json
index 9ca3764ec0..63e96f4632 100644
--- a/jarvis/ui/web/frontend/src/i18n/locales/de.json
+++ b/jarvis/ui/web/frontend/src/i18n/locales/de.json
@@ -41,16 +41,7 @@
"socials": "Socials",
"taskbar": "Taskbar",
"contacts": "Kontakte",
- "agent_instructions": "{name}.md",
- "browser_voice": "Browser-Sprache"
- },
- "browser_voice": {
- "title": "Browser-Sprache",
- "subtitle": "Sprich mit Jarvis über das Mikrofon und die Lautsprecher deines Browsers — ohne Desktop-Installation. Erfordert einen sicheren Kontext (localhost oder https).",
- "start": "Sprache starten",
- "stop": "Stopp",
- "listening": "Höre zu …",
- "speaking": "Spreche …"
+ "agent_instructions": "{name}.md"
},
"agent_instructions": {
"subtitle": "Deine persönlichen Präferenzen, wie der Assistent mit dir arbeitet — Ton, Sprache, Voreinstellungen, dauerhafte Fakten. Getrennt vom System-Prompt und hebelt niemals Sicherheit oder Bestätigungen aus.",
@@ -59,10 +50,11 @@
"editor_label": "Deine Anweisungen (Markdown)",
"placeholder": "Schreibe deine persönlichen Präferenzen…",
"chars": "{0} Zeichen",
- "empty_hint": "Leer — lade die Vorlage, um zu starten.",
+ "empty_hint": "Leer - Speichern leert die Datei, oder lade die Vorlage.",
"save": "Anweisungen speichern",
"saving": "Speichern…",
"saved": "Anweisungen gespeichert",
+ "revert": "Verwerfen",
"reset": "Leeren",
"reset_done": "Anweisungen geleert",
"load_template": "Mit Vorlage starten",
@@ -89,6 +81,12 @@
"description": "Andere Apps (Spotify, Browser …) werden stumm, während du mit deinem Assistenten sprichst, und danach wiederhergestellt. Die eigene Stimme des Assistenten wird nie gemutet.",
"enabled_toast": "Musik wird stumm, während du mit deinem Assistenten sprichst.",
"disabled_toast": "Musik-Stummschaltung deaktiviert."
+ },
+ "sound_effects": {
+ "title": "Soundeffekte",
+ "description": "Spielt die kurzen Töne von Jarvis ab — den Piepton beim Wake-Word, den Auflege-Ton und den Hochfahr-Ton. Aus: lautlos; die gesprochene Stimme ist nie betroffen.",
+ "enabled_toast": "Soundeffekte an.",
+ "disabled_toast": "Soundeffekte stummgeschaltet."
}
},
"socials": {
@@ -307,7 +305,14 @@
"cancel": "Abbrechen",
"save": "Aufgabe erstellen",
"save_error": "Aufgabe konnte nicht erstellt werden."
- }
+ },
+ "untitled": "(ohne Titel)",
+ "loading_details": "Lade Details…",
+ "waiting_for_event": "wartet auf Event",
+ "running_now": "läuft gerade",
+ "done_at": "fertig",
+ "in_prefix": "in",
+ "due_now": "fällig"
},
"skills_view": {
"title": "Skills",
@@ -336,7 +341,31 @@
"select_all": "Alle auswählen",
"selected": "ausgewählt",
"bulk_delete_title": "Skills löschen?",
- "bulk_delete_body": "Diese Skills werden dauerhaft entfernt:"
+ "bulk_delete_body": "Diese Skills werden dauerhaft entfernt:",
+ "new_skill": "Neuer Skill",
+ "find_skill": "Skill suchen",
+ "clear_search": "Suche leeren",
+ "filter_all": "Alle",
+ "filter_mine": "Meine",
+ "all_categories": "Alle Kategorien",
+ "reset_filters": "Zurücksetzen",
+ "matches": "Treffer",
+ "ai_ranked": "KI-geranked",
+ "loading": "Lade Skills…",
+ "load_error": "Konnte Skills nicht laden",
+ "select_from_list": "Wähle einen Skill aus der Liste.",
+ "loading_skill": "Lade Skill…",
+ "validation_error": "Validierungsfehler",
+ "builtin_admin_needed": "Builtin — Admin-Passwort zum Speichern nötig",
+ "admin_password": "Admin-Passwort",
+ "admin_password_hint_a": "Builtin-Skills sind geschützt. Gib das in",
+ "admin_password_hint_b": "unter gesetzte Admin-Passwort ein.",
+ "unlock": "Entsperren",
+ "empty_list_title": "Noch keine Skills da.",
+ "empty_list_body_a": "Beim ersten Start kopiert",
+ "empty_list_body_b": "die Builtin-Skills nach",
+ "empty_list_body_c": "Passiert das nicht, check die Backend-Logs.",
+ "search_no_hits": "Keine Treffer. Probier einen anderen Begriff oder entferne einen Filter."
},
"run_inspector": {
"title": "Run Inspector",
@@ -367,7 +396,12 @@
"user": "Du",
"assistant": "Assistent",
"hangup": "Aufgelegt",
- "duration": "Dauer"
+ "duration": "Dauer",
+ "unknown_error": "Unbekannter Fehler",
+ "recorder_disabled": "Session-Recorder ist deaktiviert.",
+ "recorder_hint_a": "In",
+ "recorder_hint_b": "die Sektion",
+ "recorder_hint_c": "und neu starten:"
},
"docs_view": {
"title": "Docs",
@@ -754,7 +788,10 @@
"active_tooltip": "Bereits aktiv",
"click_to_activate": "Klick aktiviert diesen Provider",
"needs_codex": "Erst Codex verbinden oder API-Key speichern",
+ "needs_login": "Erst mit Google anmelden, dann aktivierbar",
"needs_key": "Erst API-Key speichern, dann aktivierbar",
+ "recommended": "Empfohlen",
+ "recommended_tooltip": "Empfohlenes Modell: {0}",
"security_notice": ""
},
"apikeys_test": {
@@ -774,6 +811,7 @@
},
"apikeys_model": {
"heading": "Modell",
+ "recommended_tag": "Empfohlen",
"model_label": "Modell",
"search_placeholder": "Modell suchen oder ID eintippen…",
"apply": "Übernehmen",
@@ -782,9 +820,22 @@
"live_note": "(ab sofort aktiv)",
"restart_note": "(aktiv ab nächstem Start)",
"load_failed": "Modelle konnten nicht geladen werden",
- "source_static": "Offline-Liste",
- "source_static_note": "Live-Katalog nicht erreichbar — gepflegte Fallback-Liste.",
- "more_hint": "{0} weitere — Suche verfeinern"
+ "source_static": "Standardliste",
+ "source_static_note": "Live-Katalog nicht erreichbar — gepflegte Standardauswahl.",
+ "more_hint": "{0} weitere — Suche verfeinern",
+ "choose_placeholder": "Modell wählen…",
+ "heading_voice": "Stimme",
+ "choose_voice": "Stimme wählen…",
+ "use_custom": "\"{0}\" verwenden",
+ "no_models": "Keine Modelle gefunden",
+ "loading": "Lädt…"
+ },
+ "apikeys_cu_model": {
+ "heading": "Modell für Computer-Use",
+ "use_main": "Mein Hauptmodell verwenden",
+ "using_main": "Verwendet dein Hauptmodell",
+ "effective": "Computer-Use nutzt",
+ "cleared": "Computer-Use-Modell auf dein Hauptmodell zurückgesetzt"
},
"settings_view": {
"silence_window": {
@@ -845,7 +896,7 @@
},
"wake_word": {
"title": "Wake-Word",
- "description": "Die Phrase, die du laut aussprichst, um den Sprachmodus zu aktivieren — dein gesprochenes Trigger-Wort. Tippe deine eigene ein.",
+ "description": "Aktivierungsphrase für den Sprachmodus. Tippe deine eigene ein.",
"phrase_label": "Aktivierungsphrase",
"phrase_placeholder": "z. B. Jonas",
"engine_label": "Erkennungs-Engine",
@@ -1072,6 +1123,21 @@
"restart_label": "Neu starten",
"rerun_starting": "Wird gestartet…",
"rerun_confirm": "Erneut ausführen",
+ "list_load_error": "Outputs nicht geladen",
+ "empty_sessions": "Noch keine Sub-Agent-Sessions. Starte einen OpenClaw-Task.",
+ "select_session": "Wähle eine Session.",
+ "loading_plan": "Lade Plan…",
+ "plan_load_error": "Plan konnte nicht geladen werden",
+ "single_shot_no_plan": "Single-Shot-Run — kein strukturierter Plan für diese Session.",
+ "results": "Ergebnisse",
+ "file": "Datei",
+ "files": "Dateien",
+ "loading_artifacts": "Lade Artefakte…",
+ "artifacts_load_error": "Artefakte nicht geladen",
+ "no_files": "Diese Session hat keine gespeicherten Dateien.",
+ "binary_file_hint": "Binärdatei — öffne den Ordner auf dem Desktop, um sie anzuzeigen.",
+ "loading_file": "Lade Datei…",
+ "file_truncated": "Datei gekürzt auf 1 MiB — Rest im Datei-Manager anzeigen.",
"open_action": "Öffnen",
"open_with_title": "Öffnen mit…",
"open_with_remember": "Als Standard merken",
@@ -1101,7 +1167,8 @@
"open_in_editor": "Markdown-Datei im OS-Standard-Editor öffnen",
"running": "läuft",
"saving": "Speichere…",
- "error": "Fehler"
+ "error": "Fehler",
+ "status": "Status"
},
"docs": {
"search_placeholder": "Titel/Tag filtern…",
@@ -1189,6 +1256,14 @@
"brain_needs_openai_key": "Codex als Hirn braucht einen OpenAI-API-Key — das ChatGPT-Login treibt nur den Codex-Arbeiter. Trag einen OpenAI-Key ein (z. B. beim OpenAI-Provider), dann kannst du Codex hier auswählen.",
"brain_key_hint": "Um Codex auch als Hirn zu nutzen, trag einen OpenAI-API-Key ein (kostenpflichtig, getrennt vom ChatGPT-Login — der treibt nur den Arbeiter). Nach dem Speichern entsperrt sich der „Als aktiv\"-Schalter oben."
},
+ "apikeys_antigravity": {
+ "login_started": "Die Google-Anmeldung wurde im Terminal gestartet",
+ "disconnected": "Antigravity (Google) wurde getrennt",
+ "status_loading": "Google-Anmeldestatus wird geladen",
+ "connected": "Verbunden über dein Google-Abo.",
+ "connected_as": "Verbunden über Google ({0}).",
+ "needs_login_full": "{0}: erst mit Google anmelden, dann aktivieren."
+ },
"mcps_toast": {
"connected": "{0} verbunden"
},
@@ -1213,15 +1288,23 @@
},
"welcome": {
"title": "Willkommen bei Personal Jarvis",
- "subtitle": "Dein lokaler, privater Sprachassistent. Lass uns alles einrichten.",
+ "subtitle": "Dein sprachgesteuerter KI-Assistent. Lass uns alles einrichten.",
"cta": "Los geht's",
"skip_setup": "Einrichtung vorerst überspringen"
},
+ "risk": {
+ "title": "Bevor du fortfährst",
+ "lead": "Personal Jarvis ist mächtige, experimentelle Software.",
+ "body": "Sie kann deinen Computer steuern, Befehle ausführen, Apps öffnen, Nachrichten senden und Dateien in deinem Namen verändern — und sie kann Fehler machen. Sie kann ungewollte oder sogar zerstörerische Dinge tun.",
+ "liability": "Die Nutzung erfolgt vollständig auf eigenes Risiko. Die Entwickler übernehmen keine Haftung für Schäden, Datenverlust oder andere Folgen. Fahre nur fort, wenn du das verstehst und akzeptierst.",
+ "accept_label": "Ich verstehe die Risiken und akzeptiere, dass ich Personal Jarvis auf eigenes Risiko nutze.",
+ "proceed": "Verstanden — fortfahren"
+ },
"intro": {
- "scene_1": "Das ist {name} — dein Sprachassistent.",
- "scene_2": "Sprich einfach. {name} hört zu und handelt.",
+ "scene_1": "Triff deinen sprachgesteuerten Assistenten.",
+ "scene_2": "Sprich einfach — er hört zu und handelt.",
"scene_3": "Er arbeitet im Hintergrund weiter, wenn du es nicht tust.",
- "scene_4": "Und er läuft lokal — deine Daten bleiben deine."
+ "scene_4": "Deine Schlüssel, deine Daten, deine Regeln."
},
"terms": {
"title": "Nutzungsbedingungen & Haftungsausschluss",
@@ -1236,7 +1319,7 @@
},
"wake_word": {
"title": "Wähle dein Aktivierungswort",
- "body": "Wähle das Wort, das {name} aufweckt. \"Hey\" bleibt fest — den Rest bestimmst du.",
+ "body": "Wähle das Wort, das deinen Assistenten aufweckt. \"Hey\" bleibt fest — den Rest bestimmst du.",
"prefix": "Hey",
"input_label": "Dein Aktivierungswort",
"placeholder": "z. B. Nova",
@@ -1245,7 +1328,8 @@
"references_caveat": "Diese Referenzen dienen nur zur Information und können unvollständig oder veraltet sein — sie ersetzen nicht deine eigene Prüfung.",
"ack_label": "Ich habe die Informationen zu geschützten Namen gesichtet und akzeptiere, dass ich allein für das gewählte Aktivierungswort verantwortlich bin.",
"cta": "Aktivierungswort speichern",
- "saving": "Speichern…"
+ "saving": "Speichern…",
+ "derived_name": "Dein Assistent heißt dann: {0}"
},
"api_keys": {
"title": "Verbinde deine KI-Dienste (optional)",
@@ -1255,19 +1339,13 @@
},
"mic_test": {
"title": "Mikrofon-Check",
- "body": "Stellen wir sicher, dass {name} dich hören kann.",
- "no_mic": "Kein Mikrofon erkannt. Du kannst trotzdem per Text oder über einen Kanal wie Telegram mit {name} sprechen.",
+ "body": "Stellen wir sicher, dass dein Assistent dich hören kann.",
+ "no_mic": "Kein Mikrofon erkannt. Du kannst trotzdem per Text oder über einen Kanal wie Telegram sprechen.",
"skip": "Mikrofon-Check überspringen"
},
- "persona": {
- "title": "Mach es zu deinem (optional)",
- "name_label": "Wie soll sich der Assistent nennen?",
- "name_placeholder": "Namen eingeben…",
- "skip": "Personalisierung überspringen"
- },
"system_style": {
"title": "Wähle deinen Stil",
- "body": "Wie soll {name} auf dem Bildschirm erscheinen? Du kannst das jederzeit in den Einstellungen ändern.",
+ "body": "Wie soll dein Assistent auf dem Bildschirm erscheinen? Du kannst das jederzeit in den Einstellungen ändern.",
"recommended": "Empfohlen",
"options": {
"whisper_bar": "Jarvis-Leiste",
@@ -1287,10 +1365,10 @@
},
"finish": {
"title": "Alles bereit!",
- "body": "{name} ist startklar. Sag dein Aktivierungswort oder tippe einen Befehl, um zu beginnen.",
+ "body": "Dein Assistent ist startklar. Sag dein Aktivierungswort oder tippe einen Befehl, um zu beginnen.",
"skipped_title": "Du hast übersprungen — jederzeit in den Einstellungen nachholbar:",
- "start_cta": "{name} verwenden",
- "boot_notice": "Hinweis: Der erste Start dauert etwa 10 Sekunden, während {name} hochfährt — das ist völlig normal."
+ "start_cta": "Loslegen",
+ "boot_notice": "Hinweis: Der erste Start dauert etwa 10 Sekunden, während dein Assistent hochfährt — das ist völlig normal."
}
},
"languages_view": {
@@ -1396,7 +1474,15 @@
"ago_prefix": "vor",
"hangup_voice_pattern": "Auflegen",
"hangup_error": "Fehler",
- "hangup_turn_complete": "Antwort fertig"
+ "hangup_turn_complete": "Antwort fertig",
+ "ago_suffix": "",
+ "unit_sec": "s",
+ "unit_min": "min",
+ "unit_hour": "h",
+ "duration_running": "läuft",
+ "hangup_hotkey": "Hotkey",
+ "hangup_idle_timeout": "Timeout",
+ "hangup_shutdown": "Shutdown"
},
"session_detail": {
"copied_as": "Session kopiert als",
@@ -1656,7 +1742,16 @@
"empty_all": "Kein CLI matched die Filter.",
"empty_connected": "Keine CLI ist gerade verbunden.",
"empty_installed": "Keine CLI ist installiert.",
- "empty_custom": "Noch keine Custom-CLI registriert — klick 'Add Custom' oben rechts."
+ "empty_custom": "Noch keine Custom-CLI registriert — klick 'Add Custom' oben rechts.",
+ "loading_short": "Lade…",
+ "field_name_id": "Name (id, lowercase)",
+ "field_display_name": "Display-Name",
+ "risk_tier_label": "Risk-Tier",
+ "risk_monitor": "monitor (execute + log)",
+ "top_commands": "Top-Commands",
+ "just_now": "gerade eben",
+ "ago_prefix": "vor",
+ "ago_suffix": ""
},
"cli_test_hub_view": {
"subtitle_tell": "Sag",
@@ -1716,7 +1811,19 @@
"never_run": "Noch nie ausgeführt.",
"loading_run_details": "Lade Run-Details…",
"empty_title": "Noch keine Workflows — beim ersten Start werden 3 Beispiele geseedet.",
- "empty_hint_pre": "Ist das Backend frisch? Schau in"
+ "empty_hint_pre": "Ist das Backend frisch? Schau in",
+ "load_error": "Workflows konnten nicht geladen werden",
+ "partial_token_ok": "Token ✓",
+ "partial_chat_id_missing": "Chat-ID fehlt",
+ "partial_chat_id_ok": "Chat-ID ✓",
+ "partial_token_missing": "Token fehlt",
+ "prompt_url_to_summarize": "URL zum Zusammenfassen:",
+ "deactivate": "Deaktivieren",
+ "activate": "Aktivieren",
+ "empty_hint_prefix": "Ist das Backend frisch? Schau in",
+ "step_speak": "Sprich",
+ "now": "jetzt",
+ "ago_suffix": "her"
},
"conductor_view": {
"new_job": "Neuer Job",
@@ -1731,7 +1838,8 @@
"empty_jobs": "Noch keine Jobs. Drücke \"Neuer Job\" oben rechts.",
"empty_jobs_hint": "Beim ersten Start werden 3 Demo-Jobs geseedet.",
"empty_timeline": "Noch keine Runs — klick auf Play bei einem Job.",
- "json_syntax_error": "JSON-Syntaxfehler"
+ "json_syntax_error": "JSON-Syntaxfehler",
+ "now": "jetzt"
},
"chat_tab": {
"loading_friends": "Friends laden …",
@@ -1768,5 +1876,173 @@
},
"use_web_socket": {
"jarvis_opened": "{name} öffnete"
+ },
+ "chat_thread": {
+ "message_to": "Nachricht an",
+ "no_channel_placeholder": "Kein Channel verknüpft – Outbound nicht möglich",
+ "send": "Senden",
+ "send_failed": "Senden fehlgeschlagen",
+ "no_messages": "Noch keine Nachrichten",
+ "link_channel_hint": "Verknüpfe einen Channel (Telegram/Jarvis), um zu schreiben",
+ "profile": "Profil"
+ },
+ "add_friend_menu": {
+ "error_name_required": "Bitte einen Namen eintragen.",
+ "error_telegram_id_missing": "Telegram-Chat-ID fehlt.",
+ "error_pubkey_missing": "Jarvis-Pubkey fehlt.",
+ "title": "Friend hinzufügen",
+ "link_mode_hint": "Pair-Link nutzt den bestehenden Pubkey-Pair-Flow über das board-backend. Tausche Token + URL mit deinem Friend aus.",
+ "open_pair_dialog": "Pair-Dialog öffnen",
+ "name_placeholder": "z.B. Daniel",
+ "label_telegram_id": "Telegram-Chat-ID",
+ "label_pubkey": "Jarvis-Pubkey (hex)",
+ "telegram_id_placeholder": "z.B. 123456789",
+ "pubkey_placeholder": "z.B. 4f3c2b…",
+ "submit": "Hinzufügen"
+ },
+ "permission_matrix": {
+ "subline_minimal": "Nur online/offline",
+ "subline_standard": "+ Mission-Titel",
+ "subline_detailed": "+ OpenClaw-Summary",
+ "aria_label": "Sharing-Profil"
+ },
+ "self_mod_view": {
+ "all_actors": "Alle Actors",
+ "actor_main": "Haupt-Jarvis",
+ "successful_only": "Nur erfolgreiche",
+ "sensitive_path_notice": "Sensitiver Pfad — Werte serverseitig redacted (Plan-§AP-2).",
+ "intro_a": "Read-only-Sicht auf Audit-Trail, mutierbare Settings und Backups.",
+ "intro_b": "Mutationen erfolgen ausschließlich via Voice/Chat — diese View zeigt nur, was",
+ "intro_c": "an sich selbst geändert hat."
+ },
+ "wiki_view": {
+ "page_not_found": "Seite nicht gefunden",
+ "loading_vault": "Lade Vault…",
+ "vault_empty": "Vault ist leer",
+ "pages": "Seiten",
+ "wikilinks": "Wikilinks",
+ "load_error": "Wiki-Daten konnten nicht geladen werden. Läuft der Backend-Server?",
+ "no_selection_hint": "Wähle links eine Seite aus oder klick auf einen Knoten in der Memory Map.",
+ "backlinks_hint": "Backlinks erscheinen hier, sobald eine Seite ausgewählt ist.",
+ "empty_title": "Dein Wiki ist noch leer.",
+ "empty_body_a": "Sobald",
+ "empty_body_b": "in einem Gespräch etwas Wichtiges aufschnappt, landet es hier — Personen, Projekte, Vorlieben, Termine.",
+ "manual_a": "Du kannst auch jederzeit selbst eine",
+ "manual_b": "-Datei in",
+ "manual_c": "ablegen."
+ },
+ "skill_create_dialog": {
+ "title": "Skill erstellen",
+ "subtitle": "Beschreibe, was der Skill tun soll — per KI entwerfen oder das Formular selbst ausfüllen.",
+ "intent_label": "Was soll dieser Skill tun?",
+ "intent_placeholder": "z. B. „Meine offenen Browser-Tabs zusammenfassen“, „Meine Morgenroutine starten“…",
+ "draft_with_ai": "Mit KI entwerfen",
+ "brain_used": "KI-Entwurf übernommen — unten prüfen und anpassen.",
+ "brain_unavailable": "KI nicht verfügbar — eine Vorlage zum Bearbeiten eingefügt.",
+ "name_label": "Name",
+ "name_placeholder": "Skill-Name",
+ "category_label": "Kategorie",
+ "description_label": "Beschreibung",
+ "description_placeholder": "Ein Satz dazu, was er macht",
+ "body_label": "Anweisungen (Markdown)",
+ "body_placeholder": "## Mein Skill\n\nWas der Assistent tun soll…",
+ "trigger_label": "Sprach-Trigger (optional)",
+ "trigger_placeholder": "z. B. starte die Morgenroutine",
+ "create": "Skill erstellen",
+ "create_error": "Skill konnte nicht erstellt werden",
+ "name_required": "Bitte einen Namen mit mindestens 3 Zeichen eingeben."
+ },
+ "missions_view": {
+ "active": "aktiv",
+ "select_worker_hint": "Worker im Tree links auswählen, um den Live-Stream zu sehen.",
+ "select_mission_hint": "Mission auswählen, um Details zu laden.",
+ "loading_terminal": "Lade Terminal…",
+ "no_reasoning_notes": "Keine Reasoning-Notes verfügbar.",
+ "no_plan_published": "Noch kein Plan veröffentlicht.",
+ "expected_output": "Erwartete Ausgabe",
+ "not_specified": "(nicht spezifiziert)",
+ "steps": "Schritte",
+ "workers": "Worker",
+ "title": "Missions",
+ "subtitle": "Phase 6 — Worker/Critic-Loop. Live-Bus, PTY-Streams, Verdicts.",
+ "tree_label": "Mission-Tree",
+ "timeline_label": "Event-Timeline",
+ "no_events": "Noch keine Events für diese Mission.",
+ "no_critic_verdicts": "Noch keine Critic-Verdicts für diese Mission.",
+ "no_missions_yet": "Noch keine Missions. Hauptjarvis dispatched gleich…"
+ },
+ "skill_finder_dialog": {
+ "install_failed": "Installation fehlgeschlagen",
+ "title": "Skill-Finder",
+ "subtitle": "Beschreibe, was du brauchst — der Mini-Agent sucht im Katalog und rankt per KI.",
+ "brain_ranking_active": "Brain-Ranking aktiv",
+ "query_placeholder": "z.B. \"PDFs zusammenfassen\", \"Git-Workflow automatisieren\", \"Meeting-Notizen\"...",
+ "search": "Suchen",
+ "filter_trust": "Vertrauensstufe",
+ "opt_all": "Alle",
+ "hint_no_filter": "kein Filter",
+ "opt_official_only": "Nur offiziell",
+ "opt_verified_plus": "Verifiziert+",
+ "hint_verified_plus": "offiziell + 3k+ Stars",
+ "opt_community_plus": "Community+",
+ "hint_actively_maintained": "aktiv gewartet",
+ "opt_everything": "Alles, auch Prototypen",
+ "hint_risk_ok": "Risiko ok",
+ "filter_stars": "GitHub-Stars",
+ "opt_any": "Egal",
+ "filter_category": "Kategorie",
+ "filter_risk": "Risiko-Grenze",
+ "opt_safe_only": "Nur safe",
+ "opt_up_to_monitor": "Bis monitor",
+ "opt_up_to_ask": "Bis ask (nachfragen ok)",
+ "filter_language": "Sprache",
+ "lang_de": "Deutsch",
+ "lang_en": "Englisch",
+ "skills_in_catalog": "Skills im Katalog",
+ "loading_catalog": "Lade Katalog…",
+ "trust_official": "offiziell",
+ "trust_verified": "verifiziert",
+ "trust_community": "community",
+ "trust_experimental": "experimentell",
+ "installed": "installiert",
+ "no_direct_download": "Kein Direkt-Download verfügbar — manuell installieren",
+ "install_to_skills_dir": "In %LOCALAPPDATA%/Jarvis/skills installieren",
+ "manual": "Manuell",
+ "install": "Installieren",
+ "source": "Quelle",
+ "no_hits": "Keine Treffer. Andere Filter probieren?",
+ "empty_prompt": "Beschreib, was du brauchst — die Suche rankt per KI.",
+ "example_1": "„erstell Skill der meine Emails priorisiert“",
+ "example_2": "„Git-Workflow vereinfachen“",
+ "example_3": "„PDF zu strukturiertem Markdown“"
+ },
+ "missions": {
+ "state_critiquing": "Critic prüft",
+ "state_looping": "Korrektur"
+ },
+ "mission_state": {
+ "pending": "wartet",
+ "running": "läuft",
+ "critiquing": "Critic prüft",
+ "looping": "Korrektur",
+ "approved": "fertig",
+ "failed": "Fehler",
+ "cancelled": "abgebrochen",
+ "timed_out": "Timeout"
+ },
+ "mascot_gigi": {
+ "aria_label": "{name}-Maskottchen Gigi",
+ "back_online": "wieder online!",
+ "connection_lost": "Verbindung weg …"
+ },
+ "agents_view": {
+ "subtitle": "Laufende Sub-Agents — Rolle, Status, Output.",
+ "empty_title": "Keine aktiven Agents",
+ "empty_body_a": "Wenn",
+ "empty_body_b": "einen Sub-Agent startet, erscheint er hier als Live-Kachel mit Streaming-Output und Kill-Button.",
+ "phase4_notice": "Wird mit Phase 4 (Harness-Integration) aktiviert."
+ },
+ "friends_view": {
+ "subtitle": "Telegram-Bot + lokaler Friend-Registry. Du entscheidest, was Friends sehen."
}
}
diff --git a/jarvis/ui/web/frontend/src/i18n/locales/en.json b/jarvis/ui/web/frontend/src/i18n/locales/en.json
index 6080a3e085..5d97df63d6 100644
--- a/jarvis/ui/web/frontend/src/i18n/locales/en.json
+++ b/jarvis/ui/web/frontend/src/i18n/locales/en.json
@@ -41,16 +41,7 @@
"socials": "Socials",
"taskbar": "Taskbar",
"contacts": "Contacts",
- "agent_instructions": "{name}.md",
- "browser_voice": "Browser Voice"
- },
- "browser_voice": {
- "title": "Browser Voice",
- "subtitle": "Talk to Jarvis using your browser's microphone and speakers — no desktop install. Requires a secure context (localhost or https).",
- "start": "Start voice",
- "stop": "Stop",
- "listening": "Listening…",
- "speaking": "Speaking…"
+ "agent_instructions": "{name}.md"
},
"agent_instructions": {
"subtitle": "Your personal preferences for how the assistant works with you — tone, language, defaults, standing facts. Separate from the System Prompt, and it never overrides safety or confirmations.",
@@ -59,10 +50,11 @@
"editor_label": "Your instructions (Markdown)",
"placeholder": "Write your personal preferences…",
"chars": "{0} characters",
- "empty_hint": "Empty — load the template to get started.",
+ "empty_hint": "Empty - save to clear the file, or start from the template.",
"save": "Save instructions",
"saving": "Saving…",
"saved": "Instructions saved",
+ "revert": "Revert changes",
"reset": "Clear",
"reset_done": "Instructions cleared",
"load_template": "Start from template",
@@ -89,6 +81,12 @@
"description": "Mute other apps (Spotify, browser…) while you talk to your assistant, then restore them after. The assistant's own voice is never muted.",
"enabled_toast": "Music will mute while you talk to your assistant.",
"disabled_toast": "Music mute disabled."
+ },
+ "sound_effects": {
+ "title": "Sound effects",
+ "description": "Play Jarvis's short tones — the chime when you say the wake word, the hang-up tone, and the boot-ready cue. Off: silent; the spoken voice is never affected.",
+ "enabled_toast": "Sound effects on.",
+ "disabled_toast": "Sound effects muted."
}
},
"socials": {
@@ -307,7 +305,14 @@
"cancel": "Cancel",
"save": "Create task",
"save_error": "Could not create the task."
- }
+ },
+ "untitled": "(untitled)",
+ "loading_details": "Loading details…",
+ "waiting_for_event": "waiting for event",
+ "running_now": "running now",
+ "done_at": "done",
+ "in_prefix": "in",
+ "due_now": "due"
},
"skills_view": {
"title": "Skills",
@@ -336,7 +341,31 @@
"select_all": "Select all",
"selected": "selected",
"bulk_delete_title": "Delete skills?",
- "bulk_delete_body": "These skills will be permanently removed:"
+ "bulk_delete_body": "These skills will be permanently removed:",
+ "new_skill": "New skill",
+ "find_skill": "Find skill",
+ "clear_search": "Clear search",
+ "filter_all": "All",
+ "filter_mine": "Mine",
+ "all_categories": "All categories",
+ "reset_filters": "Reset",
+ "matches": "matches",
+ "ai_ranked": "AI-ranked",
+ "loading": "Loading skills…",
+ "load_error": "Could not load skills",
+ "select_from_list": "Select a skill from the list.",
+ "loading_skill": "Loading skill…",
+ "validation_error": "Validation error",
+ "builtin_admin_needed": "Built-in — admin password required to save",
+ "admin_password": "Admin password",
+ "admin_password_hint_a": "Built-in skills are protected. Enter the admin password set in",
+ "admin_password_hint_b": "under",
+ "unlock": "Unlock",
+ "empty_list_title": "No skills yet.",
+ "empty_list_body_a": "On first launch,",
+ "empty_list_body_b": "copies the built-in skills to",
+ "empty_list_body_c": "If that doesn't happen, check the backend logs.",
+ "search_no_hits": "No matches. Try a different term or remove a filter."
},
"run_inspector": {
"title": "Run Inspector",
@@ -367,7 +396,12 @@
"user": "You",
"assistant": "Assistant",
"hangup": "Hung up",
- "duration": "Duration"
+ "duration": "Duration",
+ "unknown_error": "Unknown error",
+ "recorder_disabled": "Session recorder is disabled.",
+ "recorder_hint_a": "Enable the",
+ "recorder_hint_b": "section in",
+ "recorder_hint_c": "and restart"
},
"docs_view": {
"title": "Docs",
@@ -754,7 +788,10 @@
"active_tooltip": "Already active",
"click_to_activate": "Click to activate this provider",
"needs_codex": "First connect Codex or save API key, then activate",
+ "needs_login": "First sign in with Google, then activate",
"needs_key": "First save API key, then activate",
+ "recommended": "Recommended",
+ "recommended_tooltip": "Recommended model: {0}",
"security_notice": ""
},
"apikeys_test": {
@@ -774,6 +811,7 @@
},
"apikeys_model": {
"heading": "Model",
+ "recommended_tag": "Recommended",
"model_label": "Model",
"search_placeholder": "Search models or type a custom id…",
"apply": "Apply",
@@ -782,9 +820,22 @@
"live_note": "(active now)",
"restart_note": "(active from next start)",
"load_failed": "Could not load models",
- "source_static": "offline list",
- "source_static_note": "Live catalog unavailable — showing the maintained fallback list.",
- "more_hint": "{0} more — refine your search"
+ "source_static": "default list",
+ "source_static_note": "Live catalog unavailable — showing the maintained default selection.",
+ "more_hint": "{0} more — refine your search",
+ "choose_placeholder": "Choose a model…",
+ "heading_voice": "Voice",
+ "choose_voice": "Choose a voice…",
+ "use_custom": "Use \"{0}\"",
+ "no_models": "No models found",
+ "loading": "Loading…"
+ },
+ "apikeys_cu_model": {
+ "heading": "Computer-Use model",
+ "use_main": "Use my main model",
+ "using_main": "Using your main model",
+ "effective": "Computer-Use runs",
+ "cleared": "Computer-Use model reset to your main model"
},
"settings_view": {
"silence_window": {
@@ -845,7 +896,7 @@
},
"wake_word": {
"title": "Wake Word",
- "description": "The phrase you say out loud to activate voice mode — your spoken trigger. Type your own.",
+ "description": "Activation phrase for voice mode. Type your own.",
"phrase_label": "Wake phrase",
"phrase_placeholder": "e.g. Jonas",
"engine_label": "Detection engine",
@@ -1072,6 +1123,21 @@
"restart_label": "Restart",
"rerun_starting": "Starting…",
"rerun_confirm": "Confirm re-run",
+ "list_load_error": "Could not load outputs",
+ "empty_sessions": "No sub-agent sessions yet. Start an OpenClaw task.",
+ "select_session": "Select a session.",
+ "loading_plan": "Loading plan…",
+ "plan_load_error": "Could not load plan",
+ "single_shot_no_plan": "Single-shot run — no structured plan for this session.",
+ "results": "Results",
+ "file": "file",
+ "files": "files",
+ "loading_artifacts": "Loading artifacts…",
+ "artifacts_load_error": "Could not load artifacts",
+ "no_files": "This session has no saved files.",
+ "binary_file_hint": "Binary file — open the folder on the desktop to view it.",
+ "loading_file": "Loading file…",
+ "file_truncated": "File truncated to 1 MiB — view the rest in the file manager.",
"open_action": "Open",
"open_with_title": "Open with…",
"open_with_remember": "Remember as default",
@@ -1101,7 +1167,8 @@
"open_in_editor": "Open Markdown file in OS default editor",
"running": "running",
"saving": "Saving…",
- "error": "Error"
+ "error": "Error",
+ "status": "Status"
},
"docs": {
"search_placeholder": "Filter title/tag…",
@@ -1189,6 +1256,14 @@
"brain_needs_openai_key": "Codex as a brain needs an OpenAI API key — the ChatGPT login only powers the Codex worker. Add an OpenAI key (e.g. on the OpenAI provider), then select Codex here.",
"brain_key_hint": "To use Codex as a brain too, add an OpenAI API key (paid, separate from your ChatGPT login — which only powers the worker). Saving it unlocks the brain toggle above."
},
+ "apikeys_antigravity": {
+ "login_started": "Google login was started in the terminal",
+ "disconnected": "Antigravity (Google) disconnected",
+ "status_loading": "Loading Google login status",
+ "connected": "Connected via your Google subscription.",
+ "connected_as": "Connected via Google ({0}).",
+ "needs_login_full": "{0}: first sign in with Google, then activate."
+ },
"mcps_toast": {
"connected": "{0} connected"
},
@@ -1213,15 +1288,23 @@
},
"welcome": {
"title": "Welcome to Personal Jarvis",
- "subtitle": "Your local, private voice assistant. Let's get you set up.",
+ "subtitle": "Your voice-first AI assistant. Let's get you set up.",
"cta": "Get started",
"skip_setup": "Skip setup for now"
},
+ "risk": {
+ "title": "Before you continue",
+ "lead": "Personal Jarvis is powerful, experimental software.",
+ "body": "It can control your computer, run commands, open apps, send messages, and change files on your behalf — and it can make mistakes. It may do unintended or even destructive things.",
+ "liability": "You use it entirely at your own risk. The developers accept no liability for any damage, data loss, or other consequences. Only continue if you understand and accept this.",
+ "accept_label": "I understand the risks and accept that I use Personal Jarvis at my own risk.",
+ "proceed": "I understand — continue"
+ },
"intro": {
- "scene_1": "Meet {name} — your voice-first assistant.",
- "scene_2": "Just talk. {name} listens and acts.",
+ "scene_1": "Meet your voice-first assistant.",
+ "scene_2": "Just talk — it listens and acts.",
"scene_3": "It keeps working in the background while you don't.",
- "scene_4": "And it runs locally — your data stays yours."
+ "scene_4": "Your keys, your data, your rules."
},
"terms": {
"title": "Terms & Disclaimer",
@@ -1236,7 +1319,7 @@
},
"wake_word": {
"title": "Pick your wake word",
- "body": "Choose the word that wakes {name}. \"Hey\" stays fixed — you pick the rest.",
+ "body": "Choose the word that wakes your assistant. \"Hey\" stays fixed — you pick the rest.",
"prefix": "Hey",
"input_label": "Your wake word",
"placeholder": "e.g. Nova",
@@ -1245,7 +1328,8 @@
"references_caveat": "These references are informational and may be incomplete or out of date — they are not a substitute for your own check.",
"ack_label": "I have reviewed the information on protected names and accept that I am solely responsible for the activation word I choose.",
"cta": "Save wake word",
- "saving": "Saving…"
+ "saving": "Saving…",
+ "derived_name": "Your assistant will be called: {0}"
},
"api_keys": {
"title": "Connect your AI services (optional)",
@@ -1255,19 +1339,13 @@
},
"mic_test": {
"title": "Microphone check",
- "body": "Let's make sure {name} can hear you.",
- "no_mic": "No microphone detected. You can still talk to {name} by text or through a channel like Telegram.",
+ "body": "Let's make sure your assistant can hear you.",
+ "no_mic": "No microphone detected. You can still talk by text or through a channel like Telegram.",
"skip": "Skip microphone check"
},
- "persona": {
- "title": "Make it yours (optional)",
- "name_label": "What should the assistant call itself?",
- "name_placeholder": "Type a name…",
- "skip": "Skip personalization"
- },
"system_style": {
"title": "Choose your style",
- "body": "How should {name} appear on screen? You can change this any time in Settings.",
+ "body": "How should your assistant appear on screen? You can change this any time in Settings.",
"recommended": "Recommended",
"options": {
"whisper_bar": "Jarvis Bar",
@@ -1287,10 +1365,10 @@
},
"finish": {
"title": "You're all set!",
- "body": "{name} is ready. Try saying your wake word, or type a command to begin.",
+ "body": "Your assistant is ready. Try saying your wake word, or type a command to begin.",
"skipped_title": "You skipped — set up anytime in Settings:",
- "start_cta": "Start using {name}",
- "boot_notice": "Heads up: the first launch takes about 10 seconds while {name} warms up — that's completely normal."
+ "start_cta": "Get started",
+ "boot_notice": "Heads up: the first launch takes about 10 seconds while your assistant warms up — that's completely normal."
}
},
"languages_view": {
@@ -1396,7 +1474,15 @@
"ago_prefix": "",
"hangup_voice_pattern": "Hung up",
"hangup_error": "Error",
- "hangup_turn_complete": "Reply done"
+ "hangup_turn_complete": "Reply done",
+ "ago_suffix": "ago",
+ "unit_sec": "s",
+ "unit_min": "min",
+ "unit_hour": "h",
+ "duration_running": "running",
+ "hangup_hotkey": "Hotkey",
+ "hangup_idle_timeout": "Timeout",
+ "hangup_shutdown": "Shutdown"
},
"session_detail": {
"copied_as": "Session copied as",
@@ -1656,7 +1742,16 @@
"empty_all": "No CLI matches the filter.",
"empty_connected": "No CLI is currently connected.",
"empty_installed": "No CLI is installed.",
- "empty_custom": "No custom CLI registered yet — click 'Add Custom' at the top right."
+ "empty_custom": "No custom CLI registered yet — click 'Add Custom' at the top right.",
+ "loading_short": "Loading…",
+ "field_name_id": "Name (id, lowercase)",
+ "field_display_name": "Display name",
+ "risk_tier_label": "Risk tier",
+ "risk_monitor": "monitor (execute + log)",
+ "top_commands": "Top commands",
+ "just_now": "just now",
+ "ago_prefix": "",
+ "ago_suffix": "ago"
},
"cli_test_hub_view": {
"subtitle_tell": "Tell",
@@ -1716,7 +1811,19 @@
"never_run": "Never run yet.",
"loading_run_details": "Loading run details…",
"empty_title": "No workflows yet — 3 examples are seeded on first launch.",
- "empty_hint_pre": "Is the backend fresh? Check"
+ "empty_hint_pre": "Is the backend fresh? Check",
+ "load_error": "Could not load workflows",
+ "partial_token_ok": "Token ✓",
+ "partial_chat_id_missing": "Chat ID missing",
+ "partial_chat_id_ok": "Chat ID ✓",
+ "partial_token_missing": "Token missing",
+ "prompt_url_to_summarize": "URL to summarize:",
+ "deactivate": "Deactivate",
+ "activate": "Activate",
+ "empty_hint_prefix": "Is the backend fresh? Check",
+ "step_speak": "Speak",
+ "now": "now",
+ "ago_suffix": "ago"
},
"conductor_view": {
"new_job": "New job",
@@ -1731,7 +1838,8 @@
"empty_jobs": "No jobs yet. Click \"New job\" in the top right.",
"empty_jobs_hint": "3 demo jobs are seeded on first launch.",
"empty_timeline": "No runs yet — click Play on a job.",
- "json_syntax_error": "JSON syntax error"
+ "json_syntax_error": "JSON syntax error",
+ "now": "now"
},
"chat_tab": {
"loading_friends": "Loading friends …",
@@ -1768,5 +1876,173 @@
},
"use_web_socket": {
"jarvis_opened": "{name} opened"
+ },
+ "chat_thread": {
+ "message_to": "Message to",
+ "no_channel_placeholder": "No channel linked — outbound not possible",
+ "send": "Send",
+ "send_failed": "Send failed",
+ "no_messages": "No messages yet",
+ "link_channel_hint": "Link a channel (Telegram/Jarvis) to start writing",
+ "profile": "Profile"
+ },
+ "add_friend_menu": {
+ "error_name_required": "Please enter a name.",
+ "error_telegram_id_missing": "Telegram chat ID is missing.",
+ "error_pubkey_missing": "Jarvis public key is missing.",
+ "title": "Add friend",
+ "link_mode_hint": "Pair-Link uses the existing public-key pairing flow via the board backend. Exchange the token + URL with your friend.",
+ "open_pair_dialog": "Open pair dialog",
+ "name_placeholder": "e.g. Daniel",
+ "label_telegram_id": "Telegram chat ID",
+ "label_pubkey": "Jarvis public key (hex)",
+ "telegram_id_placeholder": "e.g. 123456789",
+ "pubkey_placeholder": "e.g. 4f3c2b…",
+ "submit": "Add"
+ },
+ "permission_matrix": {
+ "subline_minimal": "Online/offline only",
+ "subline_standard": "+ Mission title",
+ "subline_detailed": "+ OpenClaw summary",
+ "aria_label": "Sharing profile"
+ },
+ "self_mod_view": {
+ "all_actors": "All actors",
+ "actor_main": "Main Jarvis",
+ "successful_only": "Successful only",
+ "sensitive_path_notice": "Sensitive path — values redacted server-side (Plan §AP-2).",
+ "intro_a": "Read-only view of the audit trail, mutable settings and backups.",
+ "intro_b": "Mutations happen only via voice/chat — this view shows only what",
+ "intro_c": "changed about itself."
+ },
+ "wiki_view": {
+ "page_not_found": "Page not found",
+ "loading_vault": "Loading vault…",
+ "vault_empty": "Vault is empty",
+ "pages": "pages",
+ "wikilinks": "wikilinks",
+ "load_error": "Could not load wiki data. Is the backend server running?",
+ "no_selection_hint": "Pick a page on the left or click a node in the Memory Map.",
+ "backlinks_hint": "Backlinks appear here once a page is selected.",
+ "empty_title": "Your wiki is still empty.",
+ "empty_body_a": "Whenever",
+ "empty_body_b": "picks up something important in a conversation, it lands here — people, projects, preferences, appointments.",
+ "manual_a": "You can also drop a",
+ "manual_b": "file into",
+ "manual_c": "yourself at any time."
+ },
+ "skill_create_dialog": {
+ "title": "Create skill",
+ "subtitle": "Describe what the skill should do — draft it with AI or fill the form yourself.",
+ "intent_label": "What should this skill do?",
+ "intent_placeholder": "e.g. \"Summarize my open browser tabs\", \"Start my morning routine\"…",
+ "draft_with_ai": "Draft with AI",
+ "brain_used": "AI draft applied — review and edit below.",
+ "brain_unavailable": "AI unavailable — filled a starter template you can edit.",
+ "name_label": "Name",
+ "name_placeholder": "Skill name",
+ "category_label": "Category",
+ "description_label": "Description",
+ "description_placeholder": "One sentence about what it does",
+ "body_label": "Instructions (Markdown)",
+ "body_placeholder": "## My Skill\n\nWhat the assistant should do…",
+ "trigger_label": "Voice trigger (optional)",
+ "trigger_placeholder": "e.g. start the morning routine",
+ "create": "Create skill",
+ "create_error": "Could not create the skill",
+ "name_required": "Please enter a name with at least 3 characters."
+ },
+ "missions_view": {
+ "active": "active",
+ "select_worker_hint": "Select a worker in the tree on the left to see the live stream.",
+ "select_mission_hint": "Select a mission to load details.",
+ "loading_terminal": "Loading terminal…",
+ "no_reasoning_notes": "No reasoning notes available.",
+ "no_plan_published": "No plan published yet.",
+ "expected_output": "Expected output",
+ "not_specified": "(not specified)",
+ "steps": "Steps",
+ "workers": "workers",
+ "title": "Missions",
+ "subtitle": "Phase 6 — Worker/Critic loop. Live bus, PTY streams, verdicts.",
+ "tree_label": "Mission tree",
+ "timeline_label": "Event timeline",
+ "no_events": "No events for this mission yet.",
+ "no_critic_verdicts": "No critic verdicts for this mission yet.",
+ "no_missions_yet": "No missions yet. Main Jarvis will dispatch one shortly…"
+ },
+ "skill_finder_dialog": {
+ "install_failed": "Installation failed",
+ "title": "Skill Finder",
+ "subtitle": "Describe what you need — the mini-agent searches the catalog and ranks with AI.",
+ "brain_ranking_active": "Brain ranking active",
+ "query_placeholder": "e.g. \"summarize PDFs\", \"automate Git workflow\", \"meeting notes\"...",
+ "search": "Search",
+ "filter_trust": "Trust level",
+ "opt_all": "All",
+ "hint_no_filter": "no filter",
+ "opt_official_only": "Official only",
+ "opt_verified_plus": "Verified+",
+ "hint_verified_plus": "official + 3k+ stars",
+ "opt_community_plus": "Community+",
+ "hint_actively_maintained": "actively maintained",
+ "opt_everything": "Everything, including prototypes",
+ "hint_risk_ok": "risk ok",
+ "filter_stars": "GitHub stars",
+ "opt_any": "Any",
+ "filter_category": "Category",
+ "filter_risk": "Risk limit",
+ "opt_safe_only": "Safe only",
+ "opt_up_to_monitor": "Up to monitor",
+ "opt_up_to_ask": "Up to ask (confirmation ok)",
+ "filter_language": "Language",
+ "lang_de": "German",
+ "lang_en": "English",
+ "skills_in_catalog": "skills in catalog",
+ "loading_catalog": "Loading catalog…",
+ "trust_official": "official",
+ "trust_verified": "verified",
+ "trust_community": "community",
+ "trust_experimental": "experimental",
+ "installed": "installed",
+ "no_direct_download": "No direct download available — install manually",
+ "install_to_skills_dir": "Install into %LOCALAPPDATA%/Jarvis/skills",
+ "manual": "Manual",
+ "install": "Install",
+ "source": "Source",
+ "no_hits": "No matches. Try different filters?",
+ "empty_prompt": "Describe what you need — the search ranks with AI.",
+ "example_1": "“build a skill that prioritizes my emails”",
+ "example_2": "“simplify the Git workflow”",
+ "example_3": "“PDF to structured Markdown”"
+ },
+ "missions": {
+ "state_critiquing": "critic reviewing",
+ "state_looping": "correcting"
+ },
+ "mission_state": {
+ "pending": "waiting",
+ "running": "running",
+ "critiquing": "critic reviewing",
+ "looping": "correcting",
+ "approved": "done",
+ "failed": "error",
+ "cancelled": "cancelled",
+ "timed_out": "timeout"
+ },
+ "mascot_gigi": {
+ "aria_label": "{name} mascot Gigi",
+ "back_online": "back online!",
+ "connection_lost": "connection lost …"
+ },
+ "agents_view": {
+ "subtitle": "Running sub-agents — role, status, output.",
+ "empty_title": "No active agents",
+ "empty_body_a": "When",
+ "empty_body_b": "starts a sub-agent, it appears here as a live tile with streaming output and a kill button.",
+ "phase4_notice": "Activated with Phase 4 (harness integration)."
+ },
+ "friends_view": {
+ "subtitle": "Telegram bot + local friend registry. You decide what friends see."
}
}
diff --git a/jarvis/ui/web/frontend/src/i18n/locales/es.json b/jarvis/ui/web/frontend/src/i18n/locales/es.json
index 40f3bbec63..d99cc2f228 100644
--- a/jarvis/ui/web/frontend/src/i18n/locales/es.json
+++ b/jarvis/ui/web/frontend/src/i18n/locales/es.json
@@ -41,16 +41,7 @@
"socials": "Redes",
"taskbar": "Barra",
"contacts": "Contactos",
- "agent_instructions": "{name}.md",
- "browser_voice": "Voz del navegador"
- },
- "browser_voice": {
- "title": "Voz del navegador",
- "subtitle": "Habla con Jarvis usando el micrófono y los altavoces de tu navegador, sin instalación de escritorio. Requiere un contexto seguro (localhost o https).",
- "start": "Iniciar voz",
- "stop": "Detener",
- "listening": "Escuchando…",
- "speaking": "Hablando…"
+ "agent_instructions": "{name}.md"
},
"agent_instructions": {
"subtitle": "Tus preferencias personales sobre cómo el asistente trabaja contigo — tono, idioma, valores por defecto, hechos permanentes. Separado del System Prompt y nunca anula la seguridad ni las confirmaciones.",
@@ -59,10 +50,11 @@
"editor_label": "Tus instrucciones (Markdown)",
"placeholder": "Escribe tus preferencias personales…",
"chars": "{0} caracteres",
- "empty_hint": "Vacío — carga la plantilla para empezar.",
+ "empty_hint": "Vacío - guarda para vaciar el archivo o carga la plantilla.",
"save": "Guardar instrucciones",
"saving": "Guardando…",
"saved": "Instrucciones guardadas",
+ "revert": "Descartar cambios",
"reset": "Vaciar",
"reset_done": "Instrucciones vaciadas",
"load_template": "Empezar con plantilla",
@@ -89,6 +81,12 @@
"description": "Silencia otras apps (Spotify, navegador…) mientras hablas con tu asistente y las restaura después. La voz del asistente nunca se silencia.",
"enabled_toast": "La música se silenciará mientras hablas con tu asistente.",
"disabled_toast": "Silenciado de música desactivado."
+ },
+ "sound_effects": {
+ "title": "Efectos de sonido",
+ "description": "Reproduce los tonos breves de Jarvis: el tono al decir la palabra de activación, el tono de colgado y el tono de arranque. Apagado: en silencio; la voz hablada nunca se ve afectada.",
+ "enabled_toast": "Efectos de sonido activados.",
+ "disabled_toast": "Efectos de sonido silenciados."
}
},
"socials": {
@@ -307,7 +305,14 @@
"cancel": "Cancelar",
"save": "Crear tarea",
"save_error": "No se pudo crear la tarea."
- }
+ },
+ "untitled": "(sin título)",
+ "loading_details": "Cargando los detalles…",
+ "waiting_for_event": "esperando un evento",
+ "running_now": "en ejecución",
+ "done_at": "listo",
+ "in_prefix": "en",
+ "due_now": "pendiente"
},
"skills_view": {
"title": "Habilidades",
@@ -336,7 +341,31 @@
"select_all": "Seleccionar todo",
"selected": "seleccionadas",
"bulk_delete_title": "¿Eliminar habilidades?",
- "bulk_delete_body": "Estas habilidades se eliminarán permanentemente:"
+ "bulk_delete_body": "Estas habilidades se eliminarán permanentemente:",
+ "new_skill": "Nueva habilidad",
+ "find_skill": "Buscar habilidad",
+ "clear_search": "Borrar la búsqueda",
+ "filter_all": "Todas",
+ "filter_mine": "Mías",
+ "all_categories": "Todas las categorías",
+ "reset_filters": "Restablecer",
+ "matches": "coincidencias",
+ "ai_ranked": "Clasificado por IA",
+ "loading": "Cargando habilidades…",
+ "load_error": "No se pudieron cargar las habilidades",
+ "select_from_list": "Selecciona una habilidad de la lista.",
+ "loading_skill": "Cargando la habilidad…",
+ "validation_error": "Error de validación",
+ "builtin_admin_needed": "Integrada: se requiere la contraseña de administrador para guardar",
+ "admin_password": "Contraseña de administrador",
+ "admin_password_hint_a": "Las habilidades integradas están protegidas. Introduce la contraseña de administrador definida en",
+ "admin_password_hint_b": "en",
+ "unlock": "Desbloquear",
+ "empty_list_title": "Aún no hay habilidades.",
+ "empty_list_body_a": "En el primer arranque,",
+ "empty_list_body_b": "copia las habilidades integradas en",
+ "empty_list_body_c": "Si eso no ocurre, revisa los registros del backend.",
+ "search_no_hits": "Sin coincidencias. Prueba con otro término o quita un filtro."
},
"run_inspector": {
"title": "Run Inspector",
@@ -367,7 +396,12 @@
"user": "Tú",
"assistant": "Asistente",
"hangup": "Colgado",
- "duration": "Duración"
+ "duration": "Duración",
+ "unknown_error": "Error desconocido",
+ "recorder_disabled": "El grabador de sesiones está desactivado.",
+ "recorder_hint_a": "Activa la sección",
+ "recorder_hint_b": "en",
+ "recorder_hint_c": "y reinicia"
},
"docs_view": {
"title": "Documentos",
@@ -754,7 +788,10 @@
"active_tooltip": "Ya activo",
"click_to_activate": "Clic para activar este proveedor",
"needs_codex": "Primero conecta Codex o guarda la clave API",
+ "needs_login": "Primero inicia sesión con Google, luego se puede activar",
"needs_key": "Primero guarda la clave API, luego se puede activar",
+ "recommended": "Recomendado",
+ "recommended_tooltip": "Modelo recomendado: {0}",
"security_notice": ""
},
"apikeys_test": {
@@ -774,6 +811,7 @@
},
"apikeys_model": {
"heading": "Modelo",
+ "recommended_tag": "Recomendado",
"model_label": "Modelo",
"search_placeholder": "Busca modelos o escribe un id…",
"apply": "Aplicar",
@@ -782,9 +820,22 @@
"live_note": "(activo ahora)",
"restart_note": "(activo en el próximo inicio)",
"load_failed": "No se pudieron cargar los modelos",
- "source_static": "lista sin conexión",
- "source_static_note": "Catálogo en vivo no disponible — mostrando la lista de respaldo.",
- "more_hint": "{0} más — refina tu búsqueda"
+ "source_static": "lista predeterminada",
+ "source_static_note": "Catálogo en vivo no disponible — mostrando la selección predeterminada.",
+ "more_hint": "{0} más — refina tu búsqueda",
+ "choose_placeholder": "Elige un modelo…",
+ "heading_voice": "Voz",
+ "choose_voice": "Elige una voz…",
+ "use_custom": "Usar \"{0}\"",
+ "no_models": "Sin modelos",
+ "loading": "Cargando…"
+ },
+ "apikeys_cu_model": {
+ "heading": "Modelo para Computer-Use",
+ "use_main": "Usar mi modelo principal",
+ "using_main": "Usando tu modelo principal",
+ "effective": "Computer-Use usa",
+ "cleared": "Modelo de Computer-Use restablecido a tu modelo principal"
},
"settings_view": {
"silence_window": {
@@ -845,7 +896,7 @@
},
"wake_word": {
"title": "Palabra de activación",
- "description": "La frase que dices en voz alta para activar el modo de voz — tu disparador hablado. Escribe la tuya.",
+ "description": "Frase de activación para el modo de voz. Escribe la tuya.",
"phrase_label": "Frase de activación",
"phrase_placeholder": "p. ej. Jonas",
"engine_label": "Motor de detección",
@@ -1072,6 +1123,21 @@
"restart_label": "Reiniciar",
"rerun_starting": "Iniciando…",
"rerun_confirm": "Confirmar reejecución",
+ "list_load_error": "No se pudieron cargar las salidas",
+ "empty_sessions": "Aún no hay sesiones de subagentes. Inicia una tarea de OpenClaw.",
+ "select_session": "Selecciona una sesión.",
+ "loading_plan": "Cargando el plan…",
+ "plan_load_error": "No se pudo cargar el plan",
+ "single_shot_no_plan": "Ejecución de un solo paso: sin plan estructurado para esta sesión.",
+ "results": "Resultados",
+ "file": "archivo",
+ "files": "archivos",
+ "loading_artifacts": "Cargando artefactos…",
+ "artifacts_load_error": "No se pudieron cargar los artefactos",
+ "no_files": "Esta sesión no tiene archivos guardados.",
+ "binary_file_hint": "Archivo binario: abre la carpeta en el escritorio para verlo.",
+ "loading_file": "Cargando el archivo…",
+ "file_truncated": "Archivo truncado a 1 MiB: ver el resto en el gestor de archivos.",
"open_action": "Abrir",
"open_with_title": "Abrir con…",
"open_with_remember": "Recordar como predeterminado",
@@ -1101,7 +1167,8 @@
"open_in_editor": "Abrir archivo Markdown en el editor predeterminado",
"running": "en ejecución",
"saving": "Guardando…",
- "error": "Error"
+ "error": "Error",
+ "status": "Estado"
},
"docs": {
"search_placeholder": "Filtrar título/etiqueta…",
@@ -1189,6 +1256,14 @@
"brain_needs_openai_key": "Codex como cerebro necesita una clave API de OpenAI — el inicio de sesión de ChatGPT solo impulsa el trabajador de Codex. Añade una clave de OpenAI (p. ej. en el proveedor OpenAI) y luego selecciona Codex aquí.",
"brain_key_hint": "Para usar Codex también como cerebro, añade una clave API de OpenAI (de pago, independiente de tu inicio de sesión de ChatGPT — que solo impulsa el trabajador). Al guardarla se desbloquea el interruptor de arriba."
},
+ "apikeys_antigravity": {
+ "login_started": "El inicio de sesión de Google se inició en el terminal",
+ "disconnected": "Antigravity (Google) desconectado",
+ "status_loading": "Cargando estado del inicio de sesión de Google",
+ "connected": "Conectado a través de tu suscripción de Google.",
+ "connected_as": "Conectado a través de Google ({0}).",
+ "needs_login_full": "{0}: primero inicia sesión con Google, luego activa."
+ },
"mcps_toast": {
"connected": "{0} conectado"
},
@@ -1213,15 +1288,23 @@
},
"welcome": {
"title": "Bienvenido a Personal Jarvis",
- "subtitle": "Tu asistente de voz local y privado. Vamos a configurarlo.",
+ "subtitle": "Tu asistente de IA por voz. Vamos a configurarlo.",
"cta": "Empezar",
"skip_setup": "Omitir la configuración por ahora"
},
+ "risk": {
+ "title": "Antes de continuar",
+ "lead": "Personal Jarvis es un software potente y experimental.",
+ "body": "Puede controlar tu ordenador, ejecutar comandos, abrir aplicaciones, enviar mensajes y modificar archivos en tu nombre, y puede cometer errores. Podría hacer cosas no deseadas o incluso destructivas.",
+ "liability": "Lo usas completamente bajo tu propia responsabilidad. Los desarrolladores no aceptan responsabilidad alguna por daños, pérdida de datos u otras consecuencias. Continúa solo si lo entiendes y lo aceptas.",
+ "accept_label": "Entiendo los riesgos y acepto que uso Personal Jarvis bajo mi propia responsabilidad.",
+ "proceed": "Lo entiendo — continuar"
+ },
"intro": {
- "scene_1": "Te presentamos a {name}, tu asistente de voz.",
- "scene_2": "Solo habla. {name} escucha y actúa.",
+ "scene_1": "Te presentamos a tu asistente de voz.",
+ "scene_2": "Solo habla: escucha y actúa.",
"scene_3": "Sigue trabajando en segundo plano cuando tú no.",
- "scene_4": "Y funciona en local: tus datos siguen siendo tuyos."
+ "scene_4": "Tus claves, tus datos, tus reglas."
},
"terms": {
"title": "Términos y descargo de responsabilidad",
@@ -1236,7 +1319,7 @@
},
"wake_word": {
"title": "Elige tu palabra de activación",
- "body": "Elige la palabra que despierta a {name}. \"Hey\" queda fija — tú eliges el resto.",
+ "body": "Elige la palabra que activa tu asistente. \"Hey\" queda fija — tú eliges el resto.",
"prefix": "Hey",
"input_label": "Tu palabra de activación",
"placeholder": "p. ej. Nova",
@@ -1245,7 +1328,8 @@
"references_caveat": "Estas referencias son informativas y pueden estar incompletas o desactualizadas; no sustituyen tu propia comprobación.",
"ack_label": "He revisado la información sobre nombres protegidos y acepto que soy el único responsable de la palabra de activación que elija.",
"cta": "Guardar palabra de activación",
- "saving": "Guardando…"
+ "saving": "Guardando…",
+ "derived_name": "Tu asistente se llamará: {0}"
},
"api_keys": {
"title": "Conecta tus servicios de IA (opcional)",
@@ -1255,19 +1339,13 @@
},
"mic_test": {
"title": "Comprobación del micrófono",
- "body": "Asegurémonos de que {name} puede oírte.",
- "no_mic": "No se detectó ningún micrófono. Aún puedes hablar con {name} por texto o a través de un canal como Telegram.",
+ "body": "Asegurémonos de que tu asistente pueda oírte.",
+ "no_mic": "No se detectó ningún micrófono. Aún puedes hablar por texto o a través de un canal como Telegram.",
"skip": "Omitir la comprobación del micrófono"
},
- "persona": {
- "title": "Hazlo tuyo (opcional)",
- "name_label": "¿Cómo debería llamarse el asistente?",
- "name_placeholder": "Escribe un nombre…",
- "skip": "Omitir la personalización"
- },
"system_style": {
"title": "Elige tu estilo",
- "body": "¿Cómo debería aparecer {name} en pantalla? Puedes cambiarlo cuando quieras en Ajustes.",
+ "body": "¿Cómo debería aparecer tu asistente en pantalla? Puedes cambiarlo cuando quieras en Ajustes.",
"recommended": "Recomendado",
"options": {
"whisper_bar": "Barra de Jarvis",
@@ -1287,10 +1365,10 @@
},
"finish": {
"title": "¡Todo listo!",
- "body": "{name} está listo. Di tu palabra de activación o escribe un comando para empezar.",
+ "body": "Tu asistente está listo. Di tu palabra de activación o escribe un comando para empezar.",
"skipped_title": "Omitiste — configúralo cuando quieras en Ajustes:",
- "start_cta": "Empezar a usar {name}",
- "boot_notice": "Nota: el primer inicio tarda unos 10 segundos mientras {name} se inicia — es completamente normal."
+ "start_cta": "Empezar",
+ "boot_notice": "Nota: el primer inicio tarda unos 10 segundos mientras tu asistente se inicia — es completamente normal."
}
},
"languages_view": {
@@ -1396,7 +1474,15 @@
"ago_prefix": "hace",
"hangup_voice_pattern": "Colgado",
"hangup_error": "Error",
- "hangup_turn_complete": "Respuesta lista"
+ "hangup_turn_complete": "Respuesta lista",
+ "ago_suffix": "",
+ "unit_sec": "s",
+ "unit_min": "min",
+ "unit_hour": "h",
+ "duration_running": "en curso",
+ "hangup_hotkey": "Atajo",
+ "hangup_idle_timeout": "Tiempo de espera",
+ "hangup_shutdown": "Apagado"
},
"session_detail": {
"copied_as": "Sesión copiada como",
@@ -1656,7 +1742,16 @@
"empty_all": "Ninguna CLI coincide con el filtro.",
"empty_connected": "No hay ninguna CLI conectada actualmente.",
"empty_installed": "No hay ninguna CLI instalada.",
- "empty_custom": "Aún no hay ninguna CLI personalizada registrada — haz clic en 'Add Custom' en la parte superior derecha."
+ "empty_custom": "Aún no hay ninguna CLI personalizada registrada — haz clic en 'Add Custom' en la parte superior derecha.",
+ "loading_short": "Cargando…",
+ "field_name_id": "Nombre (id, minúsculas)",
+ "field_display_name": "Nombre visible",
+ "risk_tier_label": "Nivel de riesgo",
+ "risk_monitor": "monitor (ejecutar + registrar)",
+ "top_commands": "Comandos principales",
+ "just_now": "ahora mismo",
+ "ago_prefix": "hace",
+ "ago_suffix": ""
},
"cli_test_hub_view": {
"subtitle_tell": "Dile a",
@@ -1716,7 +1811,19 @@
"never_run": "Nunca se ha ejecutado.",
"loading_run_details": "Cargando detalles de la ejecución…",
"empty_title": "Aún no hay flujos de trabajo: se incluyen 3 ejemplos en el primer arranque.",
- "empty_hint_pre": "¿El backend está recién instalado? Revisa"
+ "empty_hint_pre": "¿El backend está recién instalado? Revisa",
+ "load_error": "No se pudieron cargar los workflows",
+ "partial_token_ok": "Token ✓",
+ "partial_chat_id_missing": "Falta el ID de chat",
+ "partial_chat_id_ok": "ID de chat ✓",
+ "partial_token_missing": "Falta el token",
+ "prompt_url_to_summarize": "URL para resumir:",
+ "deactivate": "Desactivar",
+ "activate": "Activar",
+ "empty_hint_prefix": "¿El backend está recién creado? Mira en",
+ "step_speak": "Hablar",
+ "now": "ahora",
+ "ago_suffix": "atrás"
},
"conductor_view": {
"new_job": "Nuevo trabajo",
@@ -1731,7 +1838,8 @@
"empty_jobs": "Aún no hay trabajos. Pulsa \"Nuevo trabajo\" arriba a la derecha.",
"empty_jobs_hint": "Se incluyen 3 trabajos de demostración en el primer arranque.",
"empty_timeline": "Aún no hay ejecuciones: pulsa Play en un trabajo.",
- "json_syntax_error": "Error de sintaxis JSON"
+ "json_syntax_error": "Error de sintaxis JSON",
+ "now": "ahora"
},
"chat_tab": {
"loading_friends": "Cargando friends …",
@@ -1768,5 +1876,173 @@
},
"use_web_socket": {
"jarvis_opened": "{name} abrió"
+ },
+ "chat_thread": {
+ "message_to": "Mensaje a",
+ "no_channel_placeholder": "Ningún canal vinculado: el envío no es posible",
+ "send": "Enviar",
+ "send_failed": "Error al enviar",
+ "no_messages": "Aún no hay mensajes",
+ "link_channel_hint": "Vincula un canal (Telegram/Jarvis) para empezar a escribir",
+ "profile": "Perfil"
+ },
+ "add_friend_menu": {
+ "error_name_required": "Introduce un nombre.",
+ "error_telegram_id_missing": "Falta el ID de chat de Telegram.",
+ "error_pubkey_missing": "Falta la clave pública de Jarvis.",
+ "title": "Añadir amigo",
+ "link_mode_hint": "Pair-Link usa el flujo de emparejamiento por clave pública existente a través del board backend. Intercambia el token y la URL con tu amigo.",
+ "open_pair_dialog": "Abrir diálogo de emparejamiento",
+ "name_placeholder": "p. ej. Daniel",
+ "label_telegram_id": "ID de chat de Telegram",
+ "label_pubkey": "Clave pública de Jarvis (hex)",
+ "telegram_id_placeholder": "p. ej. 123456789",
+ "pubkey_placeholder": "p. ej. 4f3c2b…",
+ "submit": "Añadir"
+ },
+ "permission_matrix": {
+ "subline_minimal": "Solo en línea/sin conexión",
+ "subline_standard": "+ Título de la misión",
+ "subline_detailed": "+ Resumen de OpenClaw",
+ "aria_label": "Perfil de uso compartido"
+ },
+ "self_mod_view": {
+ "all_actors": "Todos los actores",
+ "actor_main": "Jarvis principal",
+ "successful_only": "Solo correctos",
+ "sensitive_path_notice": "Ruta sensible: valores ocultados en el servidor (Plan §AP-2).",
+ "intro_a": "Vista de solo lectura del registro de auditoría, los ajustes modificables y las copias de seguridad.",
+ "intro_b": "Las mutaciones solo ocurren por voz/chat: esta vista solo muestra lo que",
+ "intro_c": "ha cambiado de sí mismo."
+ },
+ "wiki_view": {
+ "page_not_found": "Página no encontrada",
+ "loading_vault": "Cargando la bóveda…",
+ "vault_empty": "La bóveda está vacía",
+ "pages": "páginas",
+ "wikilinks": "wikienlaces",
+ "load_error": "No se pudieron cargar los datos del wiki. ¿Está el servidor backend en ejecución?",
+ "no_selection_hint": "Elige una página a la izquierda o haz clic en un nodo del Memory Map.",
+ "backlinks_hint": "Los retroenlaces aparecen aquí cuando se selecciona una página.",
+ "empty_title": "Tu wiki todavía está vacío.",
+ "empty_body_a": "Cuando",
+ "empty_body_b": "capta algo importante en una conversación, aparece aquí: personas, proyectos, preferencias y citas.",
+ "manual_a": "También puedes colocar un archivo",
+ "manual_b": "en",
+ "manual_c": "tú mismo en cualquier momento."
+ },
+ "skill_create_dialog": {
+ "title": "Crear habilidad",
+ "subtitle": "Describe qué debe hacer la habilidad: créala con IA o rellena el formulario tú mismo.",
+ "intent_label": "¿Qué debe hacer esta habilidad?",
+ "intent_placeholder": "p. ej. «Resumir mis pestañas abiertas», «Iniciar mi rutina matutina»…",
+ "draft_with_ai": "Crear con IA",
+ "brain_used": "Borrador de IA aplicado: revisa y edita abajo.",
+ "brain_unavailable": "IA no disponible: se rellenó una plantilla que puedes editar.",
+ "name_label": "Nombre",
+ "name_placeholder": "Nombre de la habilidad",
+ "category_label": "Categoría",
+ "description_label": "Descripción",
+ "description_placeholder": "Una frase sobre lo que hace",
+ "body_label": "Instrucciones (Markdown)",
+ "body_placeholder": "## Mi habilidad\n\nLo que debe hacer el asistente…",
+ "trigger_label": "Activación por voz (opcional)",
+ "trigger_placeholder": "p. ej. inicia la rutina matutina",
+ "create": "Crear habilidad",
+ "create_error": "No se pudo crear la habilidad",
+ "name_required": "Introduce un nombre con al menos 3 caracteres."
+ },
+ "missions_view": {
+ "active": "activas",
+ "select_worker_hint": "Selecciona un trabajador en el árbol de la izquierda para ver la transmisión en vivo.",
+ "select_mission_hint": "Selecciona una misión para cargar los detalles.",
+ "loading_terminal": "Cargando la terminal…",
+ "no_reasoning_notes": "No hay notas de razonamiento disponibles.",
+ "no_plan_published": "Aún no se ha publicado ningún plan.",
+ "expected_output": "Salida esperada",
+ "not_specified": "(sin especificar)",
+ "steps": "Pasos",
+ "workers": "trabajadores",
+ "title": "Misiones",
+ "subtitle": "Fase 6 — Bucle Worker/Critic. Bus en vivo, flujos PTY, veredictos.",
+ "tree_label": "Árbol de misiones",
+ "timeline_label": "Cronología de eventos",
+ "no_events": "Aún no hay eventos para esta misión.",
+ "no_critic_verdicts": "Aún no hay veredictos del crítico para esta misión.",
+ "no_missions_yet": "Aún no hay misiones. Jarvis principal enviará una en breve…"
+ },
+ "skill_finder_dialog": {
+ "install_failed": "La instalación falló",
+ "title": "Buscador de habilidades",
+ "subtitle": "Describe lo que necesitas: el miniagente busca en el catálogo y clasifica con IA.",
+ "brain_ranking_active": "Clasificación por IA activa",
+ "query_placeholder": "p. ej. \"resumir PDFs\", \"automatizar el flujo de Git\", \"notas de reunión\"...",
+ "search": "Buscar",
+ "filter_trust": "Nivel de confianza",
+ "opt_all": "Todos",
+ "hint_no_filter": "sin filtro",
+ "opt_official_only": "Solo oficiales",
+ "opt_verified_plus": "Verificadas+",
+ "hint_verified_plus": "oficiales + más de 3k estrellas",
+ "opt_community_plus": "Comunidad+",
+ "hint_actively_maintained": "mantenidas activamente",
+ "opt_everything": "Todo, incluidos los prototipos",
+ "hint_risk_ok": "riesgo aceptable",
+ "filter_stars": "Estrellas de GitHub",
+ "opt_any": "Cualquiera",
+ "filter_category": "Categoría",
+ "filter_risk": "Límite de riesgo",
+ "opt_safe_only": "Solo seguras",
+ "opt_up_to_monitor": "Hasta monitor",
+ "opt_up_to_ask": "Hasta ask (confirmación aceptable)",
+ "filter_language": "Idioma",
+ "lang_de": "Alemán",
+ "lang_en": "Inglés",
+ "skills_in_catalog": "habilidades en el catálogo",
+ "loading_catalog": "Cargando el catálogo…",
+ "trust_official": "oficial",
+ "trust_verified": "verificada",
+ "trust_community": "comunidad",
+ "trust_experimental": "experimental",
+ "installed": "instalada",
+ "no_direct_download": "No hay descarga directa disponible: instalar manualmente",
+ "install_to_skills_dir": "Instalar en %LOCALAPPDATA%/Jarvis/skills",
+ "manual": "Manual",
+ "install": "Instalar",
+ "source": "Fuente",
+ "no_hits": "Sin coincidencias. ¿Probar otros filtros?",
+ "empty_prompt": "Describe lo que necesitas: la búsqueda clasifica con IA.",
+ "example_1": "«crear una habilidad que priorice mis correos»",
+ "example_2": "«simplificar el flujo de trabajo de Git»",
+ "example_3": "«PDF a Markdown estructurado»"
+ },
+ "missions": {
+ "state_critiquing": "el crítico revisa",
+ "state_looping": "corrigiendo"
+ },
+ "mission_state": {
+ "pending": "en espera",
+ "running": "en curso",
+ "critiquing": "el crítico revisa",
+ "looping": "corrigiendo",
+ "approved": "listo",
+ "failed": "error",
+ "cancelled": "cancelado",
+ "timed_out": "tiempo agotado"
+ },
+ "mascot_gigi": {
+ "aria_label": "Mascota Gigi de {name}",
+ "back_online": "¡de vuelta en línea!",
+ "connection_lost": "conexión perdida …"
+ },
+ "agents_view": {
+ "subtitle": "Subagentes en ejecución — rol, estado, salida.",
+ "empty_title": "No hay agentes activos",
+ "empty_body_a": "Cuando",
+ "empty_body_b": "inicia un subagente, aparece aquí como un panel en vivo con salida en streaming y un botón para detenerlo.",
+ "phase4_notice": "Se activa con la Fase 4 (integración del harness)."
+ },
+ "friends_view": {
+ "subtitle": "Bot de Telegram + registro local de amigos. Tú decides qué ven los amigos."
}
}
diff --git a/jarvis/ui/web/frontend/src/lib/thinkingSteps.test.ts b/jarvis/ui/web/frontend/src/lib/thinkingSteps.test.ts
index 027298f529..d47166e630 100644
--- a/jarvis/ui/web/frontend/src/lib/thinkingSteps.test.ts
+++ b/jarvis/ui/web/frontend/src/lib/thinkingSteps.test.ts
@@ -44,7 +44,7 @@ describe("reduceThinkingSteps", () => {
it("closes the previous brain attempt when the fallback chain restarts", () => {
const steps = run([
- ["BrainTurnStarted", { provider: "grok" }, T0],
+ ["BrainTurnStarted", { provider: "openai" }, T0],
["BrainTurnStarted", { provider: "claude-api" }, T0 + 500],
]);
expect(steps).toHaveLength(2);
diff --git a/jarvis/ui/web/frontend/src/store/events.ts b/jarvis/ui/web/frontend/src/store/events.ts
index cf4e554b9a..45384e4b16 100644
--- a/jarvis/ui/web/frontend/src/store/events.ts
+++ b/jarvis/ui/web/frontend/src/store/events.ts
@@ -32,7 +32,8 @@ export type SectionId =
| "outputs"
| "socials"
| "taskbar"
- | "contacts";
+ | "contacts"
+ | "agent-instructions";
export const SECTION_IDS = [
"chats",
@@ -58,6 +59,7 @@ export const SECTION_IDS = [
"socials",
"taskbar",
"contacts",
+ "agent-instructions",
] as const satisfies readonly SectionId[];
export function isSectionId(value: unknown): value is SectionId {
@@ -71,23 +73,24 @@ export const SECTION_LABELS: Record<SectionId, string> = {
plugins: "Plugins",
docs: "Docs",
mcps: "MCPs",
- tasks: "Aufgaben",
- sessions: "Transkription",
+ tasks: "Tasks",
+ sessions: "Transcription",
run_inspector: "Run Inspector",
clis: "CLIs",
"cli-test-hub": "CLI Test Hub",
board: "Board",
- languages: "Sprachen",
- profile: "Profil",
- memory: "Notizen",
- apikeys: "API-Keys",
- settings: "Einstellungen",
- telephony: "Telefonie",
- "telephony-setup": "Telefonie-Setup",
+ languages: "Languages",
+ profile: "Profile",
+ memory: "Notes",
+ apikeys: "API Keys",
+ settings: "Settings",
+ telephony: "Telephony",
+ "telephony-setup": "Telephony setup",
outputs: "Outputs",
socials: "Socials",
taskbar: "Taskbar",
contacts: "Contacts",
+ "agent-instructions": "Agent Instructions",
};
export interface EventItem {
diff --git a/jarvis/ui/web/frontend/src/types/missions.ts b/jarvis/ui/web/frontend/src/types/missions.ts
index ec083ac650..e32c574013 100644
--- a/jarvis/ui/web/frontend/src/types/missions.ts
+++ b/jarvis/ui/web/frontend/src/types/missions.ts
@@ -252,7 +252,13 @@ export interface MissionDetail {
}
export interface MissionStateBadgeMeta {
- label: string;
+ /**
+ * i18n key for the human-readable badge label. The label is resolved at
+ * render time (via `translate()` in the consumer) so a UI-language switch
+ * updates it live — a module-level `translate()` here would freeze the label
+ * to the language active at first import.
+ */
+ labelKey: string;
className: string;
iconName:
| "Loader2"
@@ -267,42 +273,42 @@ export interface MissionStateBadgeMeta {
export const MISSION_STATE_BADGE: Record<MissionState, MissionStateBadgeMeta> = {
PENDING: {
- label: "wartet",
+ labelKey: "mission_state.pending",
className: "border-border text-muted-foreground bg-background/40",
iconName: "Clock",
},
RUNNING: {
- label: "laeuft",
+ labelKey: "mission_state.running",
className: "border-primary/40 bg-primary/15 text-primary",
iconName: "Loader2",
},
CRITIQUING: {
- label: "Critic prueft",
+ labelKey: "mission_state.critiquing",
className: "border-sky-400/40 bg-sky-400/10 text-sky-300",
iconName: "Search",
},
LOOPING: {
- label: "Korrektur",
+ labelKey: "mission_state.looping",
className: "border-amber-400/40 bg-amber-400/10 text-amber-300",
iconName: "RotateCcw",
},
APPROVED: {
- label: "fertig",
+ labelKey: "mission_state.approved",
className: "border-emerald-400/40 bg-emerald-400/10 text-emerald-300",
iconName: "CheckCircle2",
},
FAILED: {
- label: "fehler",
+ labelKey: "mission_state.failed",
className: "border-destructive/50 bg-destructive/15 text-destructive",
iconName: "XCircle",
},
CANCELLED: {
- label: "abgebrochen",
+ labelKey: "mission_state.cancelled",
className: "border-border text-muted-foreground bg-background/40",
iconName: "XCircle",
},
TIMED_OUT: {
- label: "timeout",
+ labelKey: "mission_state.timed_out",
className: "border-amber-500/40 bg-amber-500/10 text-amber-300",
iconName: "Skull",
},
diff --git a/jarvis/ui/web/frontend/src/views/AgentInstructionsView.test.tsx b/jarvis/ui/web/frontend/src/views/AgentInstructionsView.test.tsx
new file mode 100644
index 0000000000..5e761bad3c
--- /dev/null
+++ b/jarvis/ui/web/frontend/src/views/AgentInstructionsView.test.tsx
@@ -0,0 +1,122 @@
+import { fireEvent, render, screen, waitFor } from "@testing-library/react";
+import { afterEach, describe, expect, it, vi } from "vitest";
+import { AgentInstructionsView } from "./AgentInstructionsView";
+
+const STATE = {
+ content: "Be terse.",
+ exists: true,
+ filename: "Ruben.md",
+ template: "# How Ruben works with me\n## Do\n- ",
+ char_count: 9,
+};
+
+const EMPTY_STATE = {
+ content: "",
+ exists: false,
+ filename: "Ruben.md",
+ template: "# How Ruben works with me\n## Do\n- ",
+ char_count: 0,
+};
+
+afterEach(() => vi.restoreAllMocks());
+
+describe("AgentInstructionsView", () => {
+ it("renders the dynamic filename and loads the content", async () => {
+ vi.stubGlobal(
+ "fetch",
+ vi.fn().mockResolvedValue({ ok: true, json: async () => STATE }),
+ );
+ render(<AgentInstructionsView />);
+ await waitFor(() =>
+ expect(
+ (screen.getByTestId("agent-instructions-editor") as HTMLTextAreaElement).value,
+ ).toBe("Be terse."),
+ );
+ expect(screen.getByText("Ruben.md").textContent).toBe("Ruben.md");
+ });
+
+ it("PUTs the draft on save", async () => {
+ const fetchMock = vi
+ .fn()
+ .mockResolvedValueOnce({ ok: true, json: async () => STATE })
+ .mockResolvedValueOnce({
+ ok: true,
+ json: async () => ({ ...STATE, content: "New rules.", ok: true, restart_required: false }),
+ });
+ vi.stubGlobal("fetch", fetchMock);
+ render(<AgentInstructionsView />);
+ const editor = await screen.findByTestId("agent-instructions-editor");
+ fireEvent.change(editor, { target: { value: "New rules." } });
+ fireEvent.click(screen.getByText("Save instructions"));
+ await waitFor(() => {
+ const put = fetchMock.mock.calls.find(([, opts]) => opts?.method === "PUT");
+ expect(put).toBeTruthy();
+ expect(put![0]).toBe("/api/settings/agent-instructions");
+ expect(JSON.parse((put![1] as RequestInit).body as string)).toEqual({
+ content: "New rules.",
+ });
+ });
+ });
+
+ it("clears saved instructions only when the empty draft is saved", async () => {
+ const fetchMock = vi
+ .fn()
+ .mockResolvedValueOnce({ ok: true, json: async () => STATE })
+ .mockResolvedValueOnce({
+ ok: true,
+ json: async () => ({ ...EMPTY_STATE, ok: true, removed: true, restart_required: false }),
+ });
+ vi.stubGlobal("fetch", fetchMock);
+ render(<AgentInstructionsView />);
+ const editor = await screen.findByTestId("agent-instructions-editor");
+ fireEvent.change(editor, { target: { value: "" } });
+
+ const save = screen.getByText("Save instructions").closest("button") as HTMLButtonElement;
+ expect(save.disabled).toBe(false);
+ fireEvent.click(save);
+
+ await waitFor(() => {
+ const del = fetchMock.mock.calls.find(([, opts]) => opts?.method === "DELETE");
+ expect(del).toBeTruthy();
+ expect(del![0]).toBe("/api/settings/agent-instructions");
+ });
+ });
+
+ it("loads the starter template into an empty editor", async () => {
+ vi.stubGlobal(
+ "fetch",
+ vi.fn().mockResolvedValue({ ok: true, json: async () => EMPTY_STATE }),
+ );
+ render(<AgentInstructionsView />);
+ await screen.findByTestId("agent-instructions-editor");
+ fireEvent.click(screen.getByText("Start from template"));
+ await waitFor(() =>
+ expect(
+ (screen.getByTestId("agent-instructions-editor") as HTMLTextAreaElement).value,
+ ).toBe(EMPTY_STATE.template),
+ );
+ });
+
+ it("reverts unsaved changes without deleting the saved instructions", async () => {
+ const fetchMock = vi.fn().mockResolvedValueOnce({ ok: true, json: async () => STATE });
+ vi.stubGlobal("fetch", fetchMock);
+ render(<AgentInstructionsView />);
+ const editor = await screen.findByTestId("agent-instructions-editor");
+ fireEvent.change(editor, { target: { value: "Changed then regret" } });
+ fireEvent.click(screen.getByText("Revert changes"));
+
+ expect((editor as HTMLTextAreaElement).value).toBe("Be terse.");
+ expect(fetchMock.mock.calls.some(([, opts]) => opts?.method === "DELETE")).toBe(false);
+ });
+
+ it("disables Save until the draft changes", async () => {
+ vi.stubGlobal(
+ "fetch",
+ vi.fn().mockResolvedValue({ ok: true, json: async () => STATE }),
+ );
+ render(<AgentInstructionsView />);
+ await screen.findByTestId("agent-instructions-editor");
+ const save = screen.getByText("Save instructions").closest("button") as HTMLButtonElement;
+ expect(save.disabled).toBe(true);
+ });
+});
diff --git a/jarvis/ui/web/frontend/src/views/AgentInstructionsView.tsx b/jarvis/ui/web/frontend/src/views/AgentInstructionsView.tsx
new file mode 100644
index 0000000000..19c095d6fb
--- /dev/null
+++ b/jarvis/ui/web/frontend/src/views/AgentInstructionsView.tsx
@@ -0,0 +1,150 @@
+import { useEffect, useState } from "react";
+import { FilePlus2, RotateCcw, Save, ScrollText } from "lucide-react";
+import { Button } from "@/components/ui/button";
+import { useAgentInstructions } from "@/hooks/useAgentInstructions";
+import { useEventStore } from "@/store/events";
+import { useT } from "@/i18n";
+
+/**
+ * AgentInstructionsView — full-page editor for the user's personal
+ * standing-instructions file (an AGENTS.md / CLAUDE.md equivalent). The file is
+ * named after the assistant (the heading shows the dynamic `<Name>.md`, e.g.
+ * "Ruben.md"). It is distinct from the System Prompt: here the user writes their
+ * own preferences for how the assistant works with them. Changes apply on the
+ * assistant's next message — no restart.
+ *
+ * Backed by /api/settings/agent-instructions (GET/PUT/DELETE) via
+ * useAgentInstructions.
+ */
+export function AgentInstructionsView() {
+ const t = useT();
+ const { config, loading, error, save } = useAgentInstructions();
+ const pushToast = useEventStore((s) => s.pushToast);
+
+ const [draft, setDraft] = useState("");
+ const [saving, setSaving] = useState(false);
+
+ // Reflect the server value on load and after every save. Coalesce a
+ // missing `content` to "" so a malformed response degrades instead of crashing.
+ useEffect(() => {
+ if (config) setDraft(config.content ?? "");
+ }, [config]);
+
+ const filename = config?.filename ?? "…";
+ const exists = !!config?.exists;
+ const dirty = !!config && draft !== (config.content ?? "");
+ const canRevert = dirty;
+ const trimmedEmpty = draft.trim().length === 0;
+
+ async function onSave() {
+ if (!dirty) return;
+ setSaving(true);
+ try {
+ await save(draft);
+ pushToast("success", t("agent_instructions.saved"));
+ } catch (e) {
+ pushToast("error", (e as Error).message);
+ } finally {
+ setSaving(false);
+ }
+ }
+
+ function onRevert() {
+ if (config) setDraft(config.content ?? "");
+ }
+
+ function onLoadTemplate() {
+ if (config?.template) setDraft(config.template);
+ }
+
+ return (
+ <div className="flex h-full flex-col gap-4 overflow-y-auto p-6">
+ <div className="flex items-start gap-3">
+ <ScrollText className="mt-1 h-5 w-5 shrink-0 text-primary" />
+ <div className="min-w-0 flex-1">
+ <div className="flex items-center gap-2">
+ <h1 className="font-display text-xl font-semibold">{filename}</h1>
+ <span
+ className={`rounded-full px-2 py-0.5 text-[10px] font-medium uppercase tracking-wide ${
+ exists
+ ? "border border-primary/40 bg-primary/10 text-primary"
+ : "border border-border bg-muted/60 text-muted-foreground"
+ }`}
+ >
+ {exists
+ ? t("agent_instructions.active_badge")
+ : t("agent_instructions.empty_badge")}
+ </span>
+ </div>
+ <p className="mt-1 max-w-prose text-sm text-muted-foreground">
+ {t("agent_instructions.subtitle")}
+ </p>
+ </div>
+ </div>
+
+ {error && <p className="text-xs text-destructive">{error}</p>}
+
+ <div>
+ <label className="block text-xs font-medium text-muted-foreground">
+ {t("agent_instructions.editor_label")}
+ </label>
+ <textarea
+ data-testid="agent-instructions-editor"
+ value={draft}
+ onChange={(e) => setDraft(e.target.value)}
+ disabled={loading}
+ spellCheck={false}
+ rows={18}
+ placeholder={t("agent_instructions.placeholder")}
+ className="mt-1 w-full resize-y rounded-md border border-input bg-background px-3 py-2 font-mono text-xs leading-relaxed focus:outline-none focus:ring-1 focus:ring-primary disabled:opacity-50"
+ />
+ <div className="mt-1.5 flex items-center justify-between">
+ <span className="font-mono text-[11px] text-muted-foreground">
+ {t("agent_instructions.chars").replace("{0}", String(draft.length))}
+ </span>
+ {trimmedEmpty && (
+ <span className="text-[11px] text-amber-500">
+ {t("agent_instructions.empty_hint")}
+ </span>
+ )}
+ </div>
+ </div>
+
+ <div className="flex flex-wrap items-center gap-3">
+ <Button
+ size="sm"
+ onClick={onSave}
+ disabled={saving || loading || !dirty}
+ className="gap-1.5"
+ >
+ <Save className="h-3.5 w-3.5" />
+ {saving ? t("agent_instructions.saving") : t("agent_instructions.save")}
+ </Button>
+ <Button
+ size="sm"
+ variant="outline"
+ onClick={onLoadTemplate}
+ disabled={loading || !config?.template}
+ className="gap-1.5"
+ >
+ <FilePlus2 className="h-3.5 w-3.5" />
+ {t("agent_instructions.load_template")}
+ </Button>
+ <Button
+ size="sm"
+ variant="outline"
+ onClick={onRevert}
+ disabled={loading || !canRevert}
+ className="gap-1.5"
+ >
+ <RotateCcw className="h-3.5 w-3.5" />
+ {t("agent_instructions.revert")}
+ </Button>
+ </div>
+
+ <p className="text-[11px] text-muted-foreground">
+ {t("agent_instructions.applies_next_turn")}
+ </p>
+ </div>
+ );
+}
diff --git a/jarvis/ui/web/frontend/src/views/AgentsView.tsx b/jarvis/ui/web/frontend/src/views/AgentsView.tsx
index 1842e755cc..052cdd470f 100644
--- a/jarvis/ui/web/frontend/src/views/AgentsView.tsx
+++ b/jarvis/ui/web/frontend/src/views/AgentsView.tsx
@@ -1,15 +1,17 @@
import { Users, Inbox } from "lucide-react";
import { ViewHeader } from "@/views/ChatsView";
+import { useT } from "@/i18n";
import { useEventStore } from "@/store/events";
export function AgentsView() {
+ const t = useT();
const assistantName = useEventStore((s) => s.assistantName);
return (
<div className="flex h-full flex-col">
<ViewHeader
icon={<Users className="h-4 w-4 text-primary" />}
title="Agent-Team"
- subtitle="Laufende Sub-Agents — Rolle, Status, Output."
+ subtitle={t("agents_view.subtitle")}
/>
<div className="flex flex-1 items-center justify-center p-8">
<div className="max-w-md text-center">
@@ -17,14 +19,14 @@ export function AgentsView() {
<Inbox className="h-6 w-6 text-muted-foreground" />
</div>
<h3 className="font-display text-lg font-semibold tracking-tight">
- Keine aktiven Agents
+ {t("agents_view.empty_title")}
</h3>
<p className="mt-2 text-sm text-muted-foreground">
- Wenn {assistantName} einen Sub-Agent startet, erscheint er hier als
- Live-Kachel mit Streaming-Output und Kill-Button.
+ {t("agents_view.empty_body_a")} {assistantName}{" "}
+ {t("agents_view.empty_body_b")}
</p>
<p className="mt-4 text-xs italic text-muted-foreground/70">
- Wird Phase 4 (Harness-Integration) aktiviert.
+ {t("agents_view.phase4_notice")}
</p>
</div>
</div>
diff --git a/jarvis/ui/web/frontend/src/views/ApiKeysView.antigravity.test.tsx b/jarvis/ui/web/frontend/src/views/ApiKeysView.antigravity.test.tsx
new file mode 100644
index 0000000000..8a585b4c37
--- /dev/null
+++ b/jarvis/ui/web/frontend/src/views/ApiKeysView.antigravity.test.tsx
@@ -0,0 +1,293 @@
+/**
+ * Component tests for Antigravity in ApiKeysView.
+ *
+ * Antigravity is a Google-subscription worker for Subagents only. It must not
+ * render as an activatable main Brain card; the Google login and active toggle
+ * live in the Subagent section.
+ */
+import { afterEach, describe, expect, it, vi } from "vitest";
+import {
+ cleanup,
+ fireEvent,
+ render,
+ screen,
+ waitFor,
+} from "@testing-library/react";
+
+import { ApiKeysView } from "@/views/ApiKeysView";
+
+interface RouteResult {
+ status?: number;
+ body: unknown;
+}
+
+function installFetchMock(routes: Record<string, () => RouteResult>) {
+ const calls: { url: string; method: string; body: unknown }[] = [];
+ const fetchMock = vi.fn(async (input: RequestInfo | URL, init?: RequestInit) => {
+ const url = String(input);
+ const method = (init?.method ?? "GET").toUpperCase();
+ let body: unknown = null;
+ if (typeof init?.body === "string") {
+ try {
+ body = JSON.parse(init.body);
+ } catch {
+ body = init.body;
+ }
+ }
+ calls.push({ url, method, body });
+ const prefixes = Object.keys(routes).sort((a, b) => b.length - a.length);
+ for (const prefix of prefixes) {
+ if (url.startsWith(prefix)) {
+ const { status = 200, body: resBody } = routes[prefix]();
+ return {
+ ok: status >= 200 && status < 300,
+ status,
+ statusText: status >= 200 && status < 300 ? "OK" : "ERR",
+ json: async () => resBody,
+ text: async () => JSON.stringify(resBody),
+ } as Response;
+ }
+ }
+ throw new Error(`unexpected fetch ${url}`);
+ });
+ (globalThis as unknown as { fetch: typeof fetch }).fetch =
+ fetchMock as unknown as typeof fetch;
+ Object.assign(navigator, {
+ clipboard: { writeText: vi.fn(async () => undefined) },
+ });
+ return { fetchMock, calls };
+}
+
+function antigravityDescriptor(overrides: Record<string, unknown> = {}) {
+ return {
+ id: "antigravity",
+ label: "Antigravity (Google subscription)",
+ tier: "brain",
+ auth_mode: "antigravity",
+ secret_keys: [],
+ secrets_set: {},
+ dashboard_url: "https://antigravity.google",
+ login_cli: ["agy"],
+ install_hint: "Install Antigravity (agy) or sign in with the Gemini CLI",
+ credential_path_hint: "~/.gemini/oauth_creds.json",
+ configured: true, // connected -> configured mirrors it
+ active: false,
+ brain_switchable: false,
+ cli_installed: true,
+ antigravity_status: {
+ installed: true,
+ connected: true,
+ mode: "oauth-personal",
+ cli_kind: "agy",
+ message: "Connected via your Google subscription.",
+ version: "agy 0.1.0",
+ user_email: "[email protected]",
+ binary_path: "agy",
+ error: null,
+ },
+ ...overrides,
+ };
+}
+
+function antigravityNotConnected() {
+ return antigravityDescriptor({
+ configured: false,
+ antigravity_status: {
+ installed: true,
+ connected: false,
+ mode: "unknown",
+ cli_kind: "agy",
+ message: "Installed but not logged in — run the Google login.",
+ version: "agy 0.1.0",
+ user_email: null,
+ binary_path: "agy",
+ error: null,
+ },
+ });
+}
+
+function antigravityMissing() {
+ return antigravityDescriptor({
+ configured: false,
+ cli_installed: false,
+ antigravity_status: {
+ installed: false,
+ connected: false,
+ mode: "unknown",
+ cli_kind: null,
+ message: "No Google CLI found.",
+ version: null,
+ user_email: null,
+ binary_path: "",
+ error: "no google cli binary",
+ },
+ });
+}
+
+const OPENCLAW_EMPTY = {
+ configured: true,
+ enabled: false,
+ binary_path: "",
+ binary_detected: null,
+ version_pin: null,
+ time_cap_min: null,
+ concurrency: null,
+ state_dir_root: null,
+ brain_primary: "gemini",
+ provider_slug: null,
+ model_override: null,
+ model_resolved: null,
+ mapping: [
+ {
+ jarvis: "antigravity",
+ openclaw: "agy-cli (direct)",
+ env_var: "Google-OAuth",
+ env_fallback: null,
+ key_set: true,
+ is_active_brain: false,
+ },
+ ],
+};
+
+// The Telephony section mounts inside ApiKeysView, so stub its four endpoints.
+const TELEPHONY_STATUS_EMPTY = {
+ available: false,
+ configured: false,
+ enabled: false,
+ account_sid_masked: "",
+ phone_number: "",
+ public_base_url: "",
+ webhook_url: "",
+ auth_token_set: false,
+ twilio_reachable: false,
+ twilio_error: null,
+ tts_provider: "",
+ tts_voice: "",
+ active_calls: 0,
+ max_call_seconds: 600,
+};
+const TELEPHONY_CONFIG_EMPTY = {
+ enabled: false,
+ account_sid: "",
+ phone_number: "",
+ public_base_url: "",
+ greeting: "",
+ language_code: "de-DE",
+ fallback_mode: "media",
+ max_call_seconds: 600,
+ auth_token_set: false,
+};
+
+function routesFor(
+ provider: Record<string, unknown>,
+): Record<string, () => RouteResult> {
+ return {
+ "/api/providers": () => ({ body: { providers: [provider] } }),
+ "/api/openclaw/status": () => ({ body: OPENCLAW_EMPTY }),
+ "/api/antigravity/status": () => ({
+ body: provider.antigravity_status ?? {},
+ }),
+ "/api/subagent/switch": () => ({
+ body: { ok: true, active: "antigravity", persisted: true },
+ }),
+ "/api/antigravity/login": () => ({
+ body: { ok: true, pid: 123, message: "Google login was started" },
+ }),
+ "/api/antigravity/logout": () => ({
+ body: { ok: true, message: "Antigravity (Google) was disconnected" },
+ }),
+ "/api/telephony/status": () => ({ body: TELEPHONY_STATUS_EMPTY }),
+ "/api/telephony/config": () => ({ body: TELEPHONY_CONFIG_EMPTY }),
+ "/api/telephony/scripts": () => ({ body: { scripts: [] } }),
+ "/api/telephony/calls": () => ({ body: { calls: [] } }),
+ };
+}
+
+afterEach(() => {
+ cleanup();
+ vi.restoreAllMocks();
+});
+
+describe("ApiKeysView — Antigravity (Google subscription) OAuth card", () => {
+ it("renders the compact connected badge with the account email", async () => {
+ installFetchMock(routesFor(antigravityDescriptor()));
+ render(<ApiKeysView />);
+
+ await waitFor(() =>
+ expect(screen.getByText("Antigravity (Google subscription)")).toBeTruthy(),
+ );
+
+ expect(screen.queryByText("Google subscription login")).toBeNull();
+ expect(screen.getByText("Antigravity Google login")).toBeTruthy();
+ expect(screen.getByText(/google-user@example\.com/)).toBeTruthy();
+ expect(screen.getByRole("radio")).toBeTruthy();
+ });
+
+ it("switches the subagent to Antigravity when connected", async () => {
+ const { calls } = installFetchMock(routesFor(antigravityDescriptor()));
+ render(<ApiKeysView />);
+
+ await waitFor(() => screen.getByRole("radio"));
+ fireEvent.click(screen.getByRole("radio"));
+
+ await waitFor(() =>
+ expect(
+ calls.some(
+ (c) =>
+ c.url.startsWith("/api/subagent/switch") &&
+ c.method === "POST" &&
+ (c.body as { provider?: string })?.provider === "antigravity",
+ ),
+ ).toBe(true),
+ );
+ });
+
+ it("shows the Connect button while not logged in and starts login", async () => {
+ const { calls } = installFetchMock(routesFor(antigravityNotConnected()));
+ render(<ApiKeysView />);
+
+ await waitFor(() =>
+ expect(screen.getByText("Connect")).toBeTruthy(),
+ );
+
+ fireEvent.click(screen.getByText("Connect"));
+ await waitFor(() =>
+ expect(
+ calls.some(
+ (c) =>
+ c.url.startsWith("/api/antigravity/login") && c.method === "POST",
+ ),
+ ).toBe(true),
+ );
+ });
+
+ it("disables the Connect button and shows the install hint when no CLI is installed", async () => {
+ installFetchMock(routesFor(antigravityMissing()));
+ render(<ApiKeysView />);
+
+ const connectBtn = await waitFor(() =>
+ screen.getByText("Connect"),
+ );
+ expect((connectBtn.closest("button") as HTMLButtonElement).disabled).toBe(true);
+ expect(
+ screen.getByText("Install Antigravity or the Gemini CLI before connecting."),
+ ).toBeTruthy();
+ });
+
+ it("disconnects via POST /api/antigravity/logout", async () => {
+ const { calls } = installFetchMock(routesFor(antigravityDescriptor()));
+ render(<ApiKeysView />);
+
+ const disconnect = await waitFor(() => screen.getByText("Disconnect"));
+ fireEvent.click(disconnect);
+
+ await waitFor(() =>
+ expect(
+ calls.some(
+ (c) =>
+ c.url.startsWith("/api/antigravity/logout") && c.method === "POST",
+ ),
+ ).toBe(true),
+ );
+ });
+});
diff --git a/jarvis/ui/web/frontend/src/views/ApiKeysView.codex.test.tsx b/jarvis/ui/web/frontend/src/views/ApiKeysView.codex.test.tsx
index aabaaae749..e131952ae0 100644
--- a/jarvis/ui/web/frontend/src/views/ApiKeysView.codex.test.tsx
+++ b/jarvis/ui/web/frontend/src/views/ApiKeysView.codex.test.tsx
@@ -1,15 +1,9 @@
/**
- * Component tests for the Codex provider card in ApiKeysView.
+ * Component tests for Codex in ApiKeysView.
*
- * Design (2026-06-08): Codex is a connection-only card (ChatGPT login → compact
- * "connected" badge, no OpenAI API-key field on the card). It IS selectable as
- * a brain like every other brain provider — but a chat brain needs an OpenAI API
- * key, which the ChatGPT login cannot back. So:
- * - the Codex card shows a brain "activate" radio (parity with Gemini),
- * - the radio is gated on `codex_brain_ready` (any OpenAI key present): with a
- * key, clicking it switches the brain to Codex; without one, it warns
- * honestly instead of a silent first-turn failure,
- * - it still collapses to a compact connected badge once logged in.
+ * Codex is a ChatGPT/Codex-login worker for Subagents only. It must not render
+ * as an activatable main Brain card; the login and active toggle live in the
+ * Subagent section.
*/
import { afterEach, describe, expect, it, vi } from "vitest";
import {
@@ -61,7 +55,22 @@ function installFetchMock(routes: Record<string, () => RouteResult>) {
Object.assign(navigator, {
clipboard: { writeText: vi.fn(async () => undefined) },
});
- return { fetchMock, calls };
+ return { calls };
+}
+
+function codexStatus(overrides: Record<string, unknown> = {}) {
+ return {
+ installed: true,
+ connected: true,
+ mode: "chatgpt",
+ message: "Connected via ChatGPT ([email protected]).",
+ version: "codex-cli 0.137.0",
+ account_label: "ChatGPT/Codex-Login",
+ user_email: "[email protected]",
+ binary_path: "codex",
+ error: null,
+ ...overrides,
+ };
}
function codexDescriptor(overrides: Record<string, unknown> = {}) {
@@ -76,21 +85,12 @@ function codexDescriptor(overrides: Record<string, unknown> = {}) {
login_cli: ["codex", "login"],
install_hint: "npm i -g @openai/codex",
credential_path_hint: null,
- configured: true, // OAuth present -> is_credential_present() is true
+ configured: true,
active: false,
+ brain_switchable: false,
cli_installed: true,
- codex_brain_ready: false, // no OpenAI key -> cannot be a brain yet
- codex_status: {
- installed: true,
- connected: true,
- mode: "chatgpt",
- message: "Connected via ChatGPT ([email protected]).",
- version: "codex-cli 0.137.0",
- account_label: "ChatGPT/Codex-Login",
- user_email: "[email protected]",
- binary_path: "codex",
- error: null,
- },
+ codex_brain_ready: true,
+ codex_status: codexStatus(),
...overrides,
};
}
@@ -98,21 +98,17 @@ function codexDescriptor(overrides: Record<string, unknown> = {}) {
function codexDescriptorNotConnected() {
return codexDescriptor({
configured: false,
- codex_status: {
- installed: true,
+ codex_status: codexStatus({
connected: false,
- mode: "unknown",
- message: "Codex is installed but not logged in — run 'codex login'.",
- version: "codex-cli 0.137.0",
+ mode: "not_connected",
+ message: "Codex is installed but not logged in.",
account_label: null,
user_email: null,
- binary_path: "codex",
- error: null,
- },
+ }),
});
}
-const OPENCLAW_EMPTY = {
+const OPENCLAW_CODEX = {
configured: true,
enabled: false,
binary_path: "",
@@ -124,14 +120,20 @@ const OPENCLAW_EMPTY = {
brain_primary: "gemini",
provider_slug: null,
model_override: null,
+ sub_model_override: null,
model_resolved: null,
- mapping: [],
+ mapping: [
+ {
+ jarvis: "openai-codex",
+ openclaw: "codex-cli (direct)",
+ env_var: "ChatGPT-OAuth",
+ env_fallback: "OPENAI_API_KEY",
+ key_set: true,
+ is_active_brain: false,
+ },
+ ],
};
-// The Telephony section now lives inside ApiKeysView (a tier section below the
-// Subagent tier), so mounting the view fires the telephony panel's load(). Stub
-// the four telephony endpoints with a graceful not-available/not-configured
-// shape so the per-route fetch mock never throws on them.
const TELEPHONY_STATUS_EMPTY = {
available: false,
configured: false,
@@ -165,8 +167,24 @@ function routesFor(
): Record<string, () => RouteResult> {
return {
"/api/providers": () => ({ body: { providers: [provider] } }),
- "/api/openclaw/status": () => ({ body: OPENCLAW_EMPTY }),
- "/api/brain/switch": () => ({ body: { ok: true, active: "codex", persisted: true } }),
+ "/api/openclaw/status": () => ({ body: OPENCLAW_CODEX }),
+ "/api/codex/status": () => ({
+ body: provider.codex_status ?? {},
+ }),
+ "/api/antigravity/status": () => ({ body: {} }),
+ "/api/subagent/switch": () => ({
+ body: { ok: true, active: "openai-codex", persisted: true },
+ }),
+ "/api/codex/login": () => ({
+ body: { ok: true, pid: 123, message: "Codex login was started" },
+ }),
+ "/api/codex/logout": () => ({
+ body: { ok: true, message: "Codex was disconnected" },
+ }),
+ "/api/brain/switch": () => ({
+ status: 500,
+ body: { detail: "Codex must not use brain switch" },
+ }),
"/api/telephony/status": () => ({ body: TELEPHONY_STATUS_EMPTY }),
"/api/telephony/config": () => ({ body: TELEPHONY_CONFIG_EMPTY }),
"/api/telephony/scripts": () => ({ body: { scripts: [] } }),
@@ -179,67 +197,66 @@ afterEach(() => {
vi.restoreAllMocks();
});
-describe("ApiKeysView — Codex is a selectable brain (parity with Gemini)", () => {
- it("renders a brain 'activate' selector on the Codex card", async () => {
+describe("ApiKeysView - Codex is subagent-only", () => {
+ it("does not render Codex as a Brain provider card", async () => {
installFetchMock(routesFor(codexDescriptor()));
render(<ApiKeysView />);
- await waitFor(() => expect(screen.getByText("OpenAI Codex")).toBeTruthy());
+ await waitFor(() => expect(screen.getByText("OpenAI Codex ChatGPT login")).toBeTruthy());
- // The card is selectable like every other brain provider.
- expect(screen.getByRole("radio")).toBeTruthy();
- // Compact connected badge for the ChatGPT login...
- expect(screen.getByTestId("codex-connected")).toBeTruthy();
- // No OpenAI key field on the card — Codex works as a brain over the ChatGPT
- // login (the OpenAI key, if any, lives on the separate "OpenAI" provider).
- expect(screen.queryByTestId("codex-brain-key")).toBeNull();
+ expect(screen.queryByText("ChatGPT / Codex login")).toBeNull();
+ expect(screen.getByText(/chatgpt-user@example\.com/)).toBeTruthy();
});
- it("disables the brain radio (no error popup, no switch) when Codex has no OpenAI key", async () => {
- const { calls } = installFetchMock(routesFor(codexDescriptor())); // codex_brain_ready: false
+ it("switches the subagent to Codex without calling brain switch", async () => {
+ const { calls } = installFetchMock(routesFor(codexDescriptor()));
render(<ApiKeysView />);
- const radio = await waitFor(() => screen.getByRole("radio"));
- // Disabled until an OpenAI key is saved (the key field below unlocks it),
- // so we disable instead of firing a warning toast.
- expect((radio as HTMLInputElement).disabled).toBe(true);
+ await waitFor(() => screen.getByRole("radio"));
+ fireEvent.click(screen.getByRole("radio"));
- fireEvent.click(radio);
+ await waitFor(() =>
+ expect(
+ calls.some(
+ (c) =>
+ c.url.startsWith("/api/subagent/switch") &&
+ c.method === "POST" &&
+ (c.body as { provider?: string })?.provider === "openai-codex",
+ ),
+ ).toBe(true),
+ );
expect(calls.some((c) => c.url.startsWith("/api/brain/switch"))).toBe(false);
});
- it("switches the brain to Codex when an OpenAI key is present", async () => {
- const { calls } = installFetchMock(
- routesFor(codexDescriptor({ codex_brain_ready: true })),
- );
+ it("shows the Connect button while not logged in and starts login", async () => {
+ const { calls } = installFetchMock(routesFor(codexDescriptorNotConnected()));
render(<ApiKeysView />);
- await waitFor(() => screen.getByRole("radio"));
- fireEvent.click(screen.getByRole("radio"));
+ const connect = await waitFor(() => screen.getByText("Connect"));
+ fireEvent.click(connect);
await waitFor(() =>
expect(
calls.some(
- (c) =>
- c.url.startsWith("/api/brain/switch") &&
- c.method === "POST" &&
- (c.body as { provider?: string })?.provider === "codex",
+ (c) => c.url.startsWith("/api/codex/login") && c.method === "POST",
),
).toBe(true),
);
});
- it("shows the connect button while not logged in (selector still present, greyed)", async () => {
- installFetchMock(routesFor(codexDescriptorNotConnected()));
+ it("disconnects via POST /api/codex/logout", async () => {
+ const { calls } = installFetchMock(routesFor(codexDescriptor()));
render(<ApiKeysView />);
- await waitFor(() => expect(screen.getByText("OpenAI Codex")).toBeTruthy());
+ const disconnect = await waitFor(() => screen.getByText("Disconnect"));
+ fireEvent.click(disconnect);
- expect(screen.getByText("Mit ChatGPT verbinden")).toBeTruthy();
- expect(screen.queryByTestId("codex-connected")).toBeNull();
- // Selector stays present for parity with the other brain providers.
- expect(screen.getByRole("radio")).toBeTruthy();
- // No OpenAI key field on the card (Codex is a brain over the ChatGPT login).
- expect(screen.queryByTestId("codex-brain-key")).toBeNull();
+ await waitFor(() =>
+ expect(
+ calls.some(
+ (c) => c.url.startsWith("/api/codex/logout") && c.method === "POST",
+ ),
+ ).toBe(true),
+ );
});
});
diff --git a/jarvis/ui/web/frontend/src/views/ApiKeysView.tsx b/jarvis/ui/web/frontend/src/views/ApiKeysView.tsx
index 8ca7e395dd..44e8d6b748 100644
--- a/jarvis/ui/web/frontend/src/views/ApiKeysView.tsx
+++ b/jarvis/ui/web/frontend/src/views/ApiKeysView.tsx
@@ -4,6 +4,7 @@ import { ViewHeader } from "@/views/ChatsView";
import { AltCredentialNote } from "@/components/AltCredentialNote";
import { ApiKeyForm } from "@/components/ApiKeyForm";
import { BrainModelSelector } from "@/components/BrainModelSelector";
+import { CuModelSelector } from "@/components/CuModelSelector";
import { ProviderBillingBadge } from "@/components/ProviderBillingBadge";
import { SubagentSection } from "@/components/SubagentSection";
import { TelephonyPanel } from "@/views/TelephonyView";
@@ -305,6 +306,21 @@ function ProviderCard({
<div className="flex flex-wrap items-center gap-2">
<span className="font-medium">{descriptor.label}</span>
<StatusBadge descriptor={descriptor} />
+ {descriptor.recommended && (
+ <span
+ className="rounded-full border border-primary/40 bg-primary/10 px-2 py-0.5 text-[10px] uppercase tracking-wider text-primary"
+ title={
+ descriptor.recommended_model
+ ? t("apikeys_view.recommended_tooltip").replace(
+ "{0}",
+ descriptor.recommended_model,
+ )
+ : undefined
+ }
+ >
+ {t("apikeys_view.recommended")}
+ </span>
+ )}
</div>
<p className="mt-0.5 text-[11px] text-muted-foreground">
<code className="font-mono">{descriptor.id}</code>
@@ -358,7 +374,19 @@ function ProviderCard({
((descriptor.tier === "tts" || descriptor.tier === "stt") &&
descriptor.active &&
descriptor.configured)) && (
- <BrainModelSelector providerId={descriptor.id} />
+ <BrainModelSelector
+ providerId={descriptor.id}
+ recommendedModel={descriptor.recommended_model}
+ />
+ )}
+
+ {/* Phase 3: a dedicated Computer-Use model, selectable per brain provider
+ (defaults to the provider's main model — no automatic escalation). */}
+ {descriptor.tier === "brain" && descriptor.configured && isBrainSwitchable && (
+ <CuModelSelector
+ providerId={descriptor.id}
+ recommendedModel={descriptor.recommended_model}
+ />
)}
<ProviderTestControl providerId={descriptor.id} />
diff --git a/jarvis/ui/web/frontend/src/views/CliTestHubView.tsx b/jarvis/ui/web/frontend/src/views/CliTestHubView.tsx
index b7ed6c4b05..c89dfcc4fb 100644
--- a/jarvis/ui/web/frontend/src/views/CliTestHubView.tsx
+++ b/jarvis/ui/web/frontend/src/views/CliTestHubView.tsx
@@ -11,8 +11,8 @@
* POST /api/clis/test-run (see useCliTestRun / the design spec)
* GET /api/clis (connected-CLI list, via useClisList)
*
- * UI strings are German for consistency with the rest of the desktop app;
- * all code-level identifiers stay English per project policy.
+ * UI strings route through the in-house i18n system (English source, with de/es
+ * translations); all code-level identifiers stay English per project policy.
*/
import { useMemo, useState } from "react";
import {
@@ -32,6 +32,7 @@ import { ViewHeader } from "@/views/ChatsView";
import { ScrollArea } from "@/components/ui/scroll-area";
import { Button } from "@/components/ui/button";
import { cn } from "@/lib/utils";
+import { useT } from "@/i18n";
import { useEventStore } from "@/store/events";
import {
useCliTestRun,
@@ -83,6 +84,7 @@ const RISK_STYLES: Record<RiskTier, RiskStyle> = {
};
function RiskBadge({ tier }: { tier: RiskTier | null }) {
+ const t = useT();
if (!tier || !(tier in RISK_STYLES)) {
return (
<span
@@ -90,7 +92,7 @@ function RiskBadge({ tier }: { tier: RiskTier | null }) {
data-risk="unknown"
className="inline-flex items-center gap-1.5 rounded-md border border-border px-2.5 py-0.5 text-[11px] font-semibold text-muted-foreground"
>
- kein Risk-Tier
+ {t("cli_test_hub_view.no_risk_tier")}
</span>
);
}
@@ -116,6 +118,7 @@ function RiskBadge({ tier }: { tier: RiskTier | null }) {
// ---------------------------------------------------------------------------
export function CliTestHubView() {
+ const t = useT();
const assistantName = useEventStore((s) => s.assistantName);
const { data, isLoading: listLoading, error: listError } = useClisList();
const testRun = useCliTestRun();
@@ -144,7 +147,7 @@ export function CliTestHubView() {
<ViewHeader
icon={<Wand2 className="h-4 w-4 text-primary" />}
title="CLI Test Hub"
- subtitle={`Sag ${assistantName} in natürlicher Sprache, was es mit deinen CLIs tun soll`}
+ subtitle={`${t("cli_test_hub_view.subtitle_tell")} ${assistantName} ${t("cli_test_hub_view.subtitle_rest")}`}
/>
<ScrollArea className="flex-1">
@@ -194,6 +197,7 @@ function ConnectedClisPanel({
isLoading: boolean;
error: Error | null;
}) {
+ const t = useT();
const setActiveSection = useEventStore((s) => s.setActiveSection);
const assistantName = useEventStore((s) => s.assistantName);
@@ -201,11 +205,11 @@ function ConnectedClisPanel({
<section className="rounded-xl border border-border bg-card/40 p-4">
<div className="mb-3 flex items-center justify-between gap-2">
<h3 className="text-[10px] uppercase tracking-wider text-muted-foreground/70">
- Verbundene CLIs
+ {t("cli_test_hub_view.connected_clis")}
</h3>
{clis.length > 0 && (
<span className="rounded-full border border-primary/30 bg-primary/10 px-2 py-0.5 text-[10px] font-semibold text-primary">
- {clis.length} verfügbar
+ {clis.length} {t("cli_test_hub_view.available")}
</span>
)}
</div>
@@ -213,7 +217,7 @@ function ConnectedClisPanel({
{isLoading && (
<div className="flex items-center gap-2 text-xs text-muted-foreground">
<Loader2 className="h-3.5 w-3.5 animate-spin" />
- Lade verbundene CLIs…
+ {t("cli_test_hub_view.loading_connected")}
</div>
)}
@@ -222,7 +226,7 @@ function ConnectedClisPanel({
data-testid="clis-load-error"
className="rounded-md border border-destructive/40 border-l-[3px] border-l-destructive bg-destructive/10 p-3 text-xs text-destructive"
>
- CLI-Liste konnte nicht geladen werden: {error.message}
+ {t("cli_test_hub_view.list_load_failed")}: {error.message}
</div>
)}
@@ -233,12 +237,10 @@ function ConnectedClisPanel({
>
<div className="flex items-center gap-2 text-sm font-medium">
<Terminal className="h-4 w-4 text-muted-foreground" />
- Keine CLI verbunden
+ {t("cli_test_hub_view.no_cli_connected")}
</div>
<p className="text-xs leading-relaxed text-muted-foreground">
- {assistantName} kann erst dann ein Tool aufrufen, wenn mindestens eine CLI
- verbunden ist (z.B. gcloud, gh, docker). Verbinde eine CLI in der
- CLIs-Sektion — sie erscheint dann hier automatisch.
+ {assistantName} {t("cli_test_hub_view.no_cli_help")}
</p>
<Button
size="sm"
@@ -246,7 +248,7 @@ function ConnectedClisPanel({
className="border border-primary/30 text-primary hover:bg-primary/10"
onClick={() => setActiveSection("clis")}
>
- Zu den CLIs
+ {t("cli_test_hub_view.go_to_clis")}
<ArrowRight className="ml-1.5 h-3.5 w-3.5" />
</Button>
</div>
@@ -301,6 +303,7 @@ function PromptPanel({
isPending: boolean;
onRun: () => void;
}) {
+ const t = useT();
const assistantName = useEventStore((s) => s.assistantName);
// Ctrl/Cmd+Enter submits — a textarea swallows plain Enter for multi-line.
const handleKeyDown = (e: React.KeyboardEvent<HTMLTextAreaElement>) => {
@@ -314,7 +317,7 @@ function PromptPanel({
<section className="rounded-xl border border-border bg-card/40 p-4">
<label htmlFor="cli-test-instruction" className="block">
<span className="mb-1.5 block text-[10px] uppercase tracking-wider text-muted-foreground/70">
- Anweisung
+ {t("cli_test_hub_view.instruction_label")}
</span>
<textarea
id="cli-test-instruction"
@@ -323,8 +326,8 @@ function PromptPanel({
onKeyDown={handleKeyDown}
disabled={isPending}
rows={3}
- aria-label={`Anweisung an ${assistantName}`}
- placeholder={`Sag ${assistantName}, was es mit deinen CLIs tun soll…`}
+ aria-label={`${t("cli_test_hub_view.instruction_to")} ${assistantName}`}
+ placeholder={`${t("cli_test_hub_view.subtitle_tell")} ${assistantName}, ${t("cli_test_hub_view.placeholder_rest")}`}
className="w-full resize-y rounded-md border border-input bg-background px-3 py-2 text-sm leading-relaxed focus-visible:outline-none focus-visible:ring-1 focus-visible:ring-ring disabled:opacity-60"
/>
</label>
@@ -332,17 +335,17 @@ function PromptPanel({
<div className="mt-3 flex flex-wrap items-end justify-between gap-3">
<label htmlFor="cli-test-hint" className="block">
<span className="mb-1 block text-[10px] uppercase tracking-wider text-muted-foreground/70">
- CLI-Hinweis (optional)
+ {t("cli_test_hub_view.cli_hint_label")}
</span>
<select
id="cli-test-hint"
value={cliHint}
onChange={(e) => onCliHintChange(e.target.value)}
disabled={isPending}
- aria-label="CLI-Hinweis"
+ aria-label={t("cli_test_hub_view.cli_hint_aria")}
className="min-w-[180px] rounded-md border border-input bg-background px-3 py-1.5 text-xs focus-visible:outline-none focus-visible:ring-1 focus-visible:ring-ring disabled:opacity-60"
>
- <option value="">{assistantName} entscheiden lassen</option>
+ <option value="">{assistantName} {t("cli_test_hub_view.let_decide")}</option>
{connectedClis.map((cli) => (
<option key={cli.name} value={cli.name}>
{cli.name}
@@ -353,24 +356,24 @@ function PromptPanel({
<div className="flex items-center gap-3">
<span className="hidden text-[10px] text-muted-foreground/60 sm:inline">
- Strg/Cmd + Enter
+ {t("cli_test_hub_view.ctrl_cmd_enter")}
</span>
<Button
type="button"
className="btn-primary"
disabled={!canRun}
onClick={onRun}
- aria-label="Anweisung ausführen"
+ aria-label={t("cli_test_hub_view.run_instruction")}
>
{isPending ? (
<>
<Loader2 className="h-3.5 w-3.5 animate-spin" />
- <span className="ml-1.5">Läuft…</span>
+ <span className="ml-1.5">{t("cli_test_hub_view.running")}</span>
</>
) : (
<>
<Play className="h-3.5 w-3.5" />
- <span className="ml-1.5">Ausführen</span>
+ <span className="ml-1.5">{t("cli_test_hub_view.run")}</span>
</>
)}
</Button>
@@ -385,6 +388,7 @@ function PromptPanel({
// ---------------------------------------------------------------------------
function ResultSkeleton() {
+ const t = useT();
const assistantName = useEventStore((s) => s.assistantName);
return (
<section
@@ -394,7 +398,7 @@ function ResultSkeleton() {
>
<div className="flex items-center gap-2 text-sm text-muted-foreground">
<Loader2 className="h-4 w-4 animate-spin text-primary" />
- {assistantName} wählt ein Tool und führt den Befehl aus…
+ {assistantName} {t("cli_test_hub_view.picking_tool")}
</div>
<div className="h-3 w-2/3 animate-jarvis-pulse rounded bg-muted-foreground/15" />
<div className="h-3 w-1/2 animate-jarvis-pulse rounded bg-muted-foreground/15" />
@@ -408,18 +412,20 @@ function ResultSkeleton() {
// ---------------------------------------------------------------------------
function RequestErrorPanel({ error }: { error: Error }) {
+ const t = useT();
return (
<section
data-testid="request-error"
className="rounded-xl border border-destructive/40 border-l-[3px] border-l-destructive bg-destructive/10 p-5"
>
<h3 className="mb-1 text-sm font-semibold text-destructive">
- Anfrage fehlgeschlagen
+ {t("cli_test_hub_view.request_failed")}
</h3>
<p className="break-words text-xs text-destructive/90">{error.message}</p>
<p className="mt-2 text-[11px] text-muted-foreground">
- Läuft der Backend-Server und ist der Endpunkt
- <code className="mx-1 font-mono">/api/clis/test-run</code> verfügbar?
+ {t("cli_test_hub_view.backend_check_prefix")}
+ <code className="mx-1 font-mono">/api/clis/test-run</code>{" "}
+ {t("cli_test_hub_view.backend_check_suffix")}
</p>
</section>
);
@@ -430,6 +436,7 @@ function RequestErrorPanel({ error }: { error: Error }) {
// ---------------------------------------------------------------------------
function ResultPanel({ result }: { result: TestRunResponse }) {
+ const t = useT();
const assistantName = useEventStore((s) => s.assistantName);
const failed = result.ok === false || Boolean(result.error);
// Severity stroke for the whole panel: failures dominate, otherwise the
@@ -454,13 +461,13 @@ function ResultPanel({ result }: { result: TestRunResponse }) {
<div>
<div className="mb-1 flex items-center gap-2 text-[10px] uppercase tracking-wider text-muted-foreground/70">
<Wand2 className="h-3 w-3 text-primary" />
- {assistantName} sagt
+ {assistantName} {t("cli_test_hub_view.says")}
</div>
<p
data-testid="result-summary"
className="font-display text-base leading-relaxed text-foreground"
>
- {result.summary || (failed ? "Der Befehl ist fehlgeschlagen." : "—")}
+ {result.summary || (failed ? t("cli_test_hub_view.command_failed") : "—")}
</p>
</div>
@@ -474,7 +481,7 @@ function ResultPanel({ result }: { result: TestRunResponse }) {
<RiskBadge tier={result.risk_tier} />
<ExitCodeBadge code={result.exit_code} />
{typeof result.duration_ms === "number" && (
- <MetaChip label="Dauer">
+ <MetaChip label={t("cli_test_hub_view.duration")}>
<span data-testid="result-duration" className="tabular-nums">
{result.duration_ms} ms
</span>
@@ -486,7 +493,7 @@ function ResultPanel({ result }: { result: TestRunResponse }) {
{result.command && (
<div>
<div className="mb-1 text-[10px] uppercase tracking-wider text-muted-foreground/70">
- Befehl
+ {t("cli_test_hub_view.command_label")}
</div>
<pre
data-testid="result-command"
@@ -529,7 +536,7 @@ function ResultPanel({ result }: { result: TestRunResponse }) {
{hasSteps && (
<div>
<div className="mb-1.5 text-[10px] uppercase tracking-wider text-muted-foreground/70">
- Schritte ({result.steps.length})
+ {t("cli_test_hub_view.steps")} ({result.steps.length})
</div>
<ol data-testid="result-steps" className="space-y-1.5">
{result.steps.map((step, idx) => (
@@ -560,8 +567,7 @@ function ResultPanel({ result }: { result: TestRunResponse }) {
{!result.tool_called && !result.command && !result.error && (
<div className="flex items-center gap-2 rounded-md border border-border border-l-[3px] border-l-primary/40 bg-background/40 px-3 py-2 text-xs text-muted-foreground">
<ExternalLink className="h-3.5 w-3.5" />
- {assistantName} hat kein passendes CLI-Tool gefunden. Formuliere die Anweisung
- konkreter oder gib einen CLI-Hinweis an.
+ {assistantName} {t("cli_test_hub_view.no_tool_found")}
</div>
)}
</section>
diff --git a/jarvis/ui/web/frontend/src/views/ClisView.tsx b/jarvis/ui/web/frontend/src/views/ClisView.tsx
index b96c4370c6..165b6bf5f8 100644
--- a/jarvis/ui/web/frontend/src/views/ClisView.tsx
+++ b/jarvis/ui/web/frontend/src/views/ClisView.tsx
@@ -38,34 +38,43 @@ import {
type CliStatus,
type CliSummary,
} from "@/hooks/useClis";
+import { translate, useT } from "@/i18n";
import { useEventStore } from "@/store/events";
-type StatusLabel = "verbunden" | "getrennt" | "nicht installiert" | "fehler" | "prüfe…";
-
-const STATUS_STYLES: Record<CliStatus, { label: StatusLabel; color: string; dotClass: string }> = {
+// Colour + dot styling per status (locale-independent). The human-readable
+// label is resolved separately through `statusLabel` so it can be translated.
+const STATUS_STYLES: Record<CliStatus, { labelKey: string; color: string; dotClass: string }> = {
connected: {
- label: "verbunden",
+ labelKey: "clis_view.status_connected",
color: "text-primary",
dotClass: "bg-primary shadow-[0_0_8px_rgba(255,214,10,0.6)]",
},
disconnected: {
- label: "getrennt",
+ labelKey: "clis_view.status_disconnected",
color: "text-muted-foreground",
dotClass: "bg-muted-foreground/40",
},
not_installed: {
- label: "nicht installiert",
+ labelKey: "clis_view.status_not_installed",
color: "text-muted-foreground/70",
dotClass: "bg-muted-foreground/20",
},
- error: { label: "fehler", color: "text-destructive", dotClass: "bg-destructive" },
+ error: {
+ labelKey: "clis_view.status_error",
+ color: "text-destructive",
+ dotClass: "bg-destructive",
+ },
checking: {
- label: "prüfe…",
+ labelKey: "clis_view.status_checking",
color: "text-muted-foreground",
dotClass: "bg-muted-foreground animate-jarvis-pulse",
},
};
+function statusLabel(status: CliStatus): string {
+ return translate(STATUS_STYLES[status].labelKey);
+}
+
const ICONS_BY_CATEGORY: Record<string, React.ComponentType<{ className?: string }>> = {
cloud: Cloud,
paas: Cloud,
@@ -82,19 +91,28 @@ function iconForCli(cli: CliSummary) {
return <Icon className="h-4 w-4 text-muted-foreground/80 shrink-0" />;
}
+// Wrap a compact "5m"/"3h"/"2d" delta with the localized "ago" marker. The
+// unit letters are locale-neutral; only the surrounding word differs (de "vor X",
+// en "X ago", es "hace X"). Empty parts are dropped so word order stays correct.
+function ago(value: string): string {
+ const prefix = translate("clis_view.ago_prefix");
+ const suffix = translate("clis_view.ago_suffix");
+ return [prefix, value, suffix].filter(Boolean).join(" ");
+}
+
function formatRelativeTime(ts: number | null): string {
if (!ts) return "—";
const diff = Math.max(0, Date.now() - ts);
const mins = Math.floor(diff / 60_000);
- if (mins < 1) return "gerade eben";
- if (mins < 60) return `vor ${mins}m`;
+ if (mins < 1) return translate("clis_view.just_now");
+ if (mins < 60) return ago(`${mins}m`);
const hrs = Math.floor(mins / 60);
- if (hrs < 24) return `vor ${hrs}h`;
- return `vor ${Math.floor(hrs / 24)}d`;
+ if (hrs < 24) return ago(`${hrs}h`);
+ return ago(`${Math.floor(hrs / 24)}d`);
}
function formatDateTime(ts: number): string {
- return new Date(ts).toLocaleString("de-DE", {
+ return new Date(ts).toLocaleString(undefined, {
day: "2-digit", month: "2-digit", year: "2-digit",
hour: "2-digit", minute: "2-digit", second: "2-digit",
});
@@ -103,6 +121,7 @@ function formatDateTime(ts: number): string {
type FilterTab = "all" | "connected" | "installed" | "custom";
export function ClisView() {
+ const t = useT();
const assistantName = useEventStore((s) => s.assistantName);
const { data, isLoading, error, refetch } = useClisList();
const [filter, setFilter] = useState<FilterTab>("all");
@@ -129,8 +148,8 @@ export function ClisView() {
title="CLIs"
subtitle={
data
- ? `${data.connected} verbunden · ${data.installed} installiert · ${data.total} im Katalog`
- : "Laden…"
+ ? `${data.connected} ${t("clis_view.subtitle_connected")} · ${data.installed} ${t("clis_view.subtitle_installed")} · ${data.total} ${t("clis_view.subtitle_in_catalog")}`
+ : t("common.loading")
}
right={
<div className="flex items-center gap-1">
@@ -138,12 +157,12 @@ export function ClisView() {
size="sm"
variant="ghost"
onClick={() => setShowWizard(true)}
- title="Custom CLI hinzufügen"
+ title={t("clis_view.add_custom_cli_title")}
>
<Plus className="h-3.5 w-3.5" />
<span className="ml-1.5 text-xs">Add Custom</span>
</Button>
- <Button size="sm" variant="ghost" onClick={() => refetch()} title="Neu laden">
+ <Button size="sm" variant="ghost" onClick={() => refetch()} title={t("clis_view.reload")}>
<RefreshCw className="h-3.5 w-3.5" />
</Button>
</div>
@@ -153,9 +172,9 @@ export function ClisView() {
<div className="flex flex-wrap items-center gap-2 border-b border-border px-6 py-3">
{(
[
- ["all", `Alle (${data?.total ?? 0})`],
- ["connected", `Verbunden (${data?.connected ?? 0})`],
- ["installed", `Installiert (${data?.installed ?? 0})`],
+ ["all", `${t("clis_view.filter_all")} (${data?.total ?? 0})`],
+ ["connected", `${t("clis_view.filter_connected")} (${data?.connected ?? 0})`],
+ ["installed", `${t("clis_view.filter_installed")} (${data?.installed ?? 0})`],
[
"custom",
`Custom (${data?.clis.filter((c) => c.is_custom).length ?? 0})`,
@@ -179,7 +198,7 @@ export function ClisView() {
{data && data.categories.length > 0 && (
<div className="ml-auto flex items-center gap-1.5">
- <span className="text-xs text-muted-foreground/70">Kategorie:</span>
+ <span className="text-xs text-muted-foreground/70">{t("clis_view.category_label")}</span>
<button
type="button"
onClick={() => setCategoryFilter(null)}
@@ -190,7 +209,7 @@ export function ClisView() {
: "border-border text-muted-foreground hover:text-foreground",
)}
>
- alle
+ {t("clis_view.category_all")}
</button>
{data.categories.map((cat) => (
<button
@@ -215,7 +234,7 @@ export function ClisView() {
<ScrollArea className="flex-1">
<div className="p-6">
- {isLoading && <div className="text-sm text-muted-foreground">Lade…</div>}
+ {isLoading && <div className="text-sm text-muted-foreground">{t("common.loading")}</div>}
{error && (
<div className="rounded-lg border border-destructive/40 bg-destructive/10 p-4 text-sm text-destructive">
@@ -230,9 +249,9 @@ export function ClisView() {
{filtered.length > 0 && (
<>
<p className="mb-4 max-w-2xl text-xs leading-relaxed text-muted-foreground">
- {assistantName} kann diese CLIs als Tools aufrufen. Nur{" "}
- <span className="text-primary">verbundene</span> CLIs erscheinen
- im Brain-Tool-Katalog.
+ {assistantName} {t("clis_view.intro_can_call")}{" "}
+ <span className="text-primary">{t("clis_view.intro_connected_word")}</span>{" "}
+ {t("clis_view.intro_appear")}
</p>
<ul className="space-y-1.5">
{filtered.map((cli) => (
@@ -278,6 +297,7 @@ function CliRow({
onSelect: () => void;
onShowUsage: () => void;
}) {
+ const t = useT();
const style = STATUS_STYLES[cli.status];
return (
<li>
@@ -316,7 +336,7 @@ function CliRow({
{cli.version ?? "—"}
</span>
<span className={cn("hidden w-24 text-right text-[11px] tabular-nums sm:inline", style.color)}>
- {style.label}
+ {statusLabel(cli.status)}
</span>
{cli.usage_count_7d > 0 ? (
<button
@@ -326,7 +346,7 @@ function CliRow({
onShowUsage();
}}
className="hidden w-24 text-right text-[11px] text-muted-foreground/70 tabular-nums hover:text-primary md:inline"
- title="Usage-History öffnen"
+ title={t("clis_view.open_usage_history")}
>
{cli.usage_count_7d}×/7d
</button>
@@ -361,6 +381,7 @@ function DetailPanel({
onClose: () => void;
onShowUsage: () => void;
}) {
+ const t = useT();
const { data, isLoading, error } = useCliDetail(name);
const check = useCheckCli();
const disconnect = useDisconnectCli();
@@ -385,11 +406,11 @@ function DetailPanel({
onClick={() =>
check.mutate(name, {
onError: (err) =>
- pushToast("error", `Status-Check fehlgeschlagen: ${(err as Error).message}`),
+ pushToast("error", `${t("clis_view.status_check_failed")}: ${(err as Error).message}`),
})
}
- title="Status neu prüfen"
- aria-label="Status neu prüfen"
+ title={t("clis_view.recheck_status")}
+ aria-label={t("clis_view.recheck_status")}
disabled={check.isPending}
>
<RefreshCw className={cn("h-3.5 w-3.5", check.isPending && "animate-spin")} />
@@ -397,8 +418,8 @@ function DetailPanel({
<button
type="button" onClick={onClose}
className="ml-1 text-muted-foreground hover:text-foreground"
- title="Schließen"
- aria-label="Detail-Panel schließen"
+ title={t("common.close")}
+ aria-label={t("clis_view.close_detail_panel")}
>
×
</button>
@@ -406,7 +427,7 @@ function DetailPanel({
<ScrollArea className="flex-1">
<div className="space-y-4 p-5 text-xs">
- {isLoading && <div className="text-muted-foreground">Lade Details…</div>}
+ {isLoading && <div className="text-muted-foreground">{t("clis_view.loading_details")}</div>}
{error && (
<div className="rounded-md border border-destructive/40 bg-destructive/10 p-2 text-destructive">
{(error as Error).message}
@@ -422,7 +443,7 @@ function DetailPanel({
onClick={() => setInstallDialog(true)}
>
<Play className="h-3.5 w-3.5" />
- <span className="ml-1.5">Installieren</span>
+ <span className="ml-1.5">{t("clis_view.install")}</span>
</Button>
)}
{data.installed && !data.connected && data.auth_mode === "oauth_cli" && (
@@ -440,7 +461,7 @@ function DetailPanel({
onClick={() => setApiKeyDialog(true)}
>
<LogIn className="h-3.5 w-3.5" />
- <span className="ml-1.5">API-Key setzen</span>
+ <span className="ml-1.5">{t("clis_view.set_api_key")}</span>
</Button>
)}
{data.connected && data.auth_mode !== "none" && data.auth_mode !== "config_file" && (
@@ -451,19 +472,19 @@ function DetailPanel({
disconnect.mutate(name, {
onSuccess: (res) => {
if (res.ok) {
- pushToast("success", `${name} getrennt`);
+ pushToast("success", `${name} ${t("clis_view.disconnected_suffix")}`);
} else {
- pushToast("error", res.error || "Trennen fehlgeschlagen");
+ pushToast("error", res.error || t("clis_view.disconnect_failed"));
}
},
onError: (err) =>
- pushToast("error", `Trennen fehlgeschlagen: ${(err as Error).message}`),
+ pushToast("error", `${t("clis_view.disconnect_failed")}: ${(err as Error).message}`),
})
}
disabled={disconnect.isPending}
>
<LogOut className="h-3.5 w-3.5" />
- <span className="ml-1.5">Trennen</span>
+ <span className="ml-1.5">{t("clis_view.disconnect")}</span>
</Button>
)}
<Button size="sm" variant="ghost" onClick={onShowUsage}>
@@ -474,18 +495,22 @@ function DetailPanel({
<Button
size="sm"
variant="ghost"
- aria-label={`Custom-CLI ${name} entfernen`}
- title="Custom-CLI entfernen"
+ aria-label={`${t("clis_view.remove_custom_cli_prefix")} ${name} ${t("clis_view.remove_custom_cli_suffix")}`}
+ title={t("clis_view.remove_custom_cli")}
disabled={deleteCustom.isPending}
onClick={() => {
- if (window.confirm(`Custom-CLI "${name}" wirklich entfernen?`)) {
+ if (
+ window.confirm(
+ `${t("clis_view.confirm_remove_custom_prefix")} "${name}" ${t("clis_view.confirm_remove_custom_suffix")}`,
+ )
+ ) {
deleteCustom.mutate(name, {
onSuccess: () => {
- pushToast("success", `${name} entfernt`);
+ pushToast("success", `${name} ${t("clis_view.removed_suffix")}`);
onClose();
},
onError: (err) =>
- pushToast("error", `Fehler: ${(err as Error).message}`),
+ pushToast("error", `${t("common.error")}: ${(err as Error).message}`),
});
}
}}
@@ -498,11 +523,11 @@ function DetailPanel({
<Section title="Status">
<KeyVal k="Binary" v={data.binary_name} />
- <KeyVal k="Pfad" v={data.binary_path ?? "nicht gefunden"} />
+ <KeyVal k={t("clis_view.kv_path")} v={data.binary_path ?? t("clis_view.not_found")} />
<KeyVal k="Version" v={data.version ?? "—"} />
<KeyVal k="Auth-Mode" v={data.auth_mode} />
- <KeyVal k="Status" v={STATUS_STYLES[data.status].label} />
- {data.error && <KeyVal k="Fehler" v={data.error} tone="error" />}
+ <KeyVal k="Status" v={statusLabel(data.status)} />
+ {data.error && <KeyVal k={t("common.error")} v={data.error} tone="error" />}
</Section>
<Section title="Commands">
@@ -513,12 +538,12 @@ function DetailPanel({
</Section>
{data.secret_keys.length > 0 && (
- <Section title="Secrets (API-Key-Auth)">
+ <Section title={t("clis_view.section_secrets")}>
{data.secret_keys.map((sk) => (
<KeyVal
key={sk.name}
k={sk.env_var}
- v={data.secrets_set[sk.name] ? "●●●●● gesetzt" : "(nicht gesetzt)"}
+ v={data.secrets_set[sk.name] ? `●●●●● ${t("clis_view.secret_set")}` : t("clis_view.secret_unset")}
tone={data.secrets_set[sk.name] ? "ok" : "muted"}
/>
))}
@@ -558,7 +583,7 @@ function DetailPanel({
</Section>
{data.tool_schema_examples.length > 0 && (
- <Section title="Tool-Beispiele (für Brain)">
+ <Section title={t("clis_view.section_tool_examples")}>
<ul className="space-y-1">
{data.tool_schema_examples.map((e) => (
<li key={e} className="font-mono text-[10px] text-muted-foreground/90">
@@ -576,7 +601,7 @@ function DetailPanel({
rel="noopener noreferrer"
className="flex items-center gap-1 text-[11px] text-primary hover:underline"
>
- Dokumentation
+ {t("clis_view.documentation")}
<ExternalLink className="h-3 w-3" />
</a>
)}
@@ -619,6 +644,7 @@ function ConnectOAuthButton({
// und setzt den Coach-State zurueck wenn der Login durch ist. Damit
// erscheint der Toast "X ist verbunden" und die CLIs-Liste refreshed
// automatisch, egal in welcher Sektion der User gerade ist.
+ const t = useT();
const spawn = useSpawnExternalTerminal();
const pushToast = useEventStore((s) => s.pushToast);
const setCoach = useEventStore((s) => s.setCliConnectCoach);
@@ -643,10 +669,10 @@ function ConnectOAuthButton({
});
pushToast(
"info",
- `Terminal geoeffnet (${res.method}) — folge dem Browser-Login. Status wird automatisch geprueft.`,
+ `${t("clis_view.terminal_opened")} (${res.method}) — ${t("clis_view.follow_browser_login")}`,
);
} else {
- pushToast("error", res.error || "Terminal-Spawn fehlgeschlagen");
+ pushToast("error", res.error || t("clis_view.terminal_spawn_failed"));
}
},
onError: (err) => pushToast("error", (err as Error).message),
@@ -655,7 +681,7 @@ function ConnectOAuthButton({
}
>
<LogIn className="h-3.5 w-3.5" />
- <span className="ml-1.5">Browser-Login</span>
+ <span className="ml-1.5">{t("clis_view.browser_login")}</span>
</Button>
);
}
@@ -671,6 +697,7 @@ function ApiKeyDialog({
detail: CliDetail;
onClose: () => void;
}) {
+ const t = useT();
const connect = useConnectCli();
const pushToast = useEventStore((s) => s.pushToast);
const [values, setValues] = useState<Record<string, string>>({});
@@ -682,11 +709,10 @@ function ApiKeyDialog({
<div className="flex items-start justify-between gap-4 border-b border-border p-5">
<div className="min-w-0 flex-1">
<h3 className="font-display text-base font-semibold">
- {detail.display_name} — API-Key setzen
+ {detail.display_name} — {t("clis_view.set_api_key")}
</h3>
<p className="mt-1 text-[11px] text-muted-foreground">
- Keys werden im Windows Credential Manager gespeichert und beim
- Aufruf als ENV-Variable injiziert.
+ {t("clis_view.api_key_help")}
</p>
</div>
<button type="button" onClick={onClose} className="text-muted-foreground hover:text-foreground">
@@ -708,7 +734,7 @@ function ApiKeyDialog({
onChange={(e) => setValues((v) => ({ ...v, [sk.name]: e.target.value }))}
className="w-full rounded-md border border-input bg-background px-3 py-1.5 font-mono text-xs focus-visible:outline-none focus-visible:ring-1 focus-visible:ring-ring"
placeholder={
- detail.secrets_set[sk.name] ? "●●●●● (bereits gesetzt — überschreiben)" : "API-Key eingeben"
+ detail.secrets_set[sk.name] ? `●●●●● ${t("clis_view.api_key_already_set")}` : t("clis_view.api_key_enter")
}
/>
</label>
@@ -723,7 +749,7 @@ function ApiKeyDialog({
<div className="flex items-center justify-end gap-2 border-t border-border p-4">
<Button type="button" variant="ghost" onClick={onClose} disabled={connect.isPending}>
- Abbrechen
+ {t("common.cancel")}
</Button>
<Button
type="button"
@@ -736,10 +762,10 @@ function ApiKeyDialog({
{
onSuccess: (res) => {
if (res.ok) {
- pushToast("success", `${detail.name} verbunden`);
+ pushToast("success", `${detail.name} ${t("clis_view.connected_suffix")}`);
onClose();
} else {
- setError(res.error || "Validation fehlgeschlagen");
+ setError(res.error || t("clis_view.validation_failed"));
}
},
onError: (err) => setError((err as Error).message),
@@ -747,7 +773,7 @@ function ApiKeyDialog({
);
}}
>
- {connect.isPending ? "Validiere…" : "Speichern & Validieren"}
+ {connect.isPending ? t("clis_view.validating") : t("clis_view.save_and_validate")}
</Button>
</div>
</div>
@@ -771,6 +797,7 @@ function InstallDialog({
// bleibt im Repo erhalten fuer headless/Voice-Pfade — UI-seitig haben
// wir aber explizit das externe Terminal, weil der User sehen will
// wie der Install in einer "echten" PowerShell laeuft.
+ const t = useT();
const spawn = useSpawnExternalTerminal();
const pushToast = useEventStore((s) => s.pushToast);
const [selected, setSelected] = useState<string>(
@@ -784,11 +811,10 @@ function InstallDialog({
<div className="flex items-start justify-between gap-4 border-b border-border p-5">
<div className="min-w-0 flex-1">
<h3 className="font-display text-base font-semibold">
- {detail.display_name} installieren
+ {detail.display_name}{t("clis_view.install_lowercase")}
</h3>
<p className="mt-1 text-[11px] text-muted-foreground">
- Oeffnet ein externes Windows Terminal mit dem Install-Command.
- Der Status wird automatisch geprueft sobald das Terminal fertig ist.
+ {t("clis_view.install_help")}
</p>
</div>
<button type="button" onClick={onClose} className="text-muted-foreground hover:text-foreground">
@@ -799,7 +825,7 @@ function InstallDialog({
<div className="space-y-3 p-5">
<div>
<div className="mb-1.5 text-[10px] uppercase tracking-wider text-muted-foreground/70">
- Methode wählen
+ {t("clis_view.choose_method")}
</div>
<div className="space-y-1">
{detail.install_methods.map((m) => (
@@ -823,7 +849,7 @@ function InstallDialog({
<span className="text-xs font-medium">{m.manager}</span>
{m.manager === detail.recommended_install && (
<span className="rounded-full border border-primary/40 bg-primary/10 px-1.5 py-0.5 text-[9px] text-primary">
- empfohlen
+ {t("clis_view.recommended")}
</span>
)}
</label>
@@ -834,7 +860,7 @@ function InstallDialog({
{selectedMethod && (
<div>
<div className="mb-1.5 text-[10px] uppercase tracking-wider text-muted-foreground/70">
- Befehl
+ {t("clis_view.command_label")}
</div>
<code className="block break-all rounded-md border border-border bg-background px-3 py-2 font-mono text-[10px]">
{selectedMethod.command}
@@ -845,7 +871,7 @@ function InstallDialog({
<div className="flex items-center justify-end gap-2 border-t border-border p-4">
<Button type="button" variant="ghost" onClick={onClose}>
- Abbrechen
+ {t("common.cancel")}
</Button>
<Button
type="button"
@@ -866,11 +892,11 @@ function InstallDialog({
if (res.ok) {
pushToast(
"info",
- `Externes Terminal geoeffnet (${res.method}) — Install laeuft. Status wird automatisch aktualisiert.`,
+ `${t("clis_view.external_terminal_opened")} (${res.method}) — ${t("clis_view.install_running")}`,
);
onClose();
} else {
- pushToast("error", res.error || "Terminal-Spawn fehlgeschlagen");
+ pushToast("error", res.error || t("clis_view.terminal_spawn_failed"));
}
},
onError: (err) => pushToast("error", (err as Error).message),
@@ -878,7 +904,7 @@ function InstallDialog({
);
}}
>
- {spawn.isPending ? "Spawne…" : selected === "manual" ? "Öffnen" : "Im Terminal installieren"}
+ {spawn.isPending ? t("clis_view.spawning") : selected === "manual" ? t("clis_view.open") : t("clis_view.install_in_terminal")}
</Button>
</div>
</div>
@@ -891,6 +917,7 @@ function InstallDialog({
// ---------------------------------------------------------------------------
function CustomCliWizard({ onClose }: { onClose: () => void }) {
+ const t = useT();
const register = useRegisterCustomCli();
const pushToast = useEventStore((s) => s.pushToast);
const [step, setStep] = useState(1);
@@ -949,7 +976,7 @@ function CustomCliWizard({ onClose }: { onClose: () => void }) {
};
register.mutate(payload, {
onSuccess: () => {
- pushToast("success", `${form.name} registriert`);
+ pushToast("success", `${form.name} ${t("clis_view.registered_suffix")}`);
onClose();
},
onError: (err) => setError((err as Error).message),
@@ -962,13 +989,13 @@ function CustomCliWizard({ onClose }: { onClose: () => void }) {
<div className="flex items-start justify-between gap-4 border-b border-border p-5">
<div className="min-w-0 flex-1">
<h3 className="font-display text-base font-semibold">
- Custom CLI hinzufügen · Schritt {step}/4
+ {t("clis_view.add_custom_cli_title")} · {t("clis_view.step")} {step}/4
</h3>
<p className="mt-1 text-[11px] text-muted-foreground">
- {step === 1 && "Identität der CLI"}
- {step === 2 && "Check + Version"}
- {step === 3 && "Auth-Konfiguration"}
- {step === 4 && "Risk-Tier + Patterns"}
+ {step === 1 && t("clis_view.wizard_step1_identity")}
+ {step === 2 && t("clis_view.wizard_step2_check")}
+ {step === 3 && t("clis_view.wizard_step3_auth")}
+ {step === 4 && t("clis_view.wizard_step4_risk")}
</p>
</div>
<button type="button" onClick={onClose} className="text-muted-foreground hover:text-foreground">
@@ -981,30 +1008,30 @@ function CustomCliWizard({ onClose }: { onClose: () => void }) {
<>
<TextField label="Name (id, lowercase)" val={form.name}
onChange={(v) => setForm({ ...form, name: v.toLowerCase() })}
- placeholder="z.B. mytool" />
+ placeholder={t("clis_view.eg_mytool")} />
<TextField label="Display-Name" val={form.display_name}
onChange={(v) => setForm({ ...form, display_name: v })}
- placeholder="z.B. My Tool CLI" />
- <TextField label="Binary-Name (was im PATH liegt)" val={form.binary_name}
+ placeholder={t("clis_view.eg_my_tool_cli")} />
+ <TextField label={t("clis_view.field_binary_name")} val={form.binary_name}
onChange={(v) => setForm({ ...form, binary_name: v })}
- placeholder="z.B. mytool" />
- <TextField label="Beschreibung" val={form.description}
+ placeholder={t("clis_view.eg_mytool")} />
+ <TextField label={t("clis_view.field_description")} val={form.description}
onChange={(v) => setForm({ ...form, description: v })}
- placeholder="Was macht die CLI?" />
- <TextField label="Kategorie" val={form.category}
+ placeholder={t("clis_view.what_does_cli_do")} />
+ <TextField label={t("clis_view.field_category")} val={form.category}
onChange={(v) => setForm({ ...form, category: v })}
placeholder="cloud / git / payments / other" />
- <TextField label="Homepage-URL" val={form.homepage}
+ <TextField label={t("clis_view.field_homepage_url")} val={form.homepage}
onChange={(v) => setForm({ ...form, homepage: v })}
placeholder="https://..." />
</>
)}
{step === 2 && (
<>
- <TextField label="Check-Command" val={form.check_command}
+ <TextField label={t("clis_view.field_check_command")} val={form.check_command}
onChange={(v) => setForm({ ...form, check_command: v })}
placeholder="mytool --version" mono />
- <TextField label="Version-Regex (eine Capture-Group)" val={form.version_parse_regex}
+ <TextField label={t("clis_view.field_version_regex")} val={form.version_parse_regex}
onChange={(v) => setForm({ ...form, version_parse_regex: v })}
placeholder="v(\\S+)" mono />
</>
@@ -1013,35 +1040,35 @@ function CustomCliWizard({ onClose }: { onClose: () => void }) {
<>
<label className="block">
<div className="mb-1 text-[10px] uppercase tracking-wider text-muted-foreground/70">
- Auth-Mode
+ {t("clis_view.auth_mode_label")}
</div>
<select
value={form.auth_mode}
onChange={(e) => setForm({ ...form, auth_mode: e.target.value as typeof form.auth_mode })}
className="w-full rounded-md border border-input bg-background px-3 py-1.5 text-xs"
>
- <option value="none">none (keine Auth)</option>
- <option value="oauth_cli">oauth_cli (CLI-eigener Login)</option>
- <option value="api_key">api_key (Keyring + ENV-Injection)</option>
- <option value="config_file">config_file (fremdverwaltet)</option>
+ <option value="none">{t("clis_view.auth_none")}</option>
+ <option value="oauth_cli">{t("clis_view.auth_oauth_cli")}</option>
+ <option value="api_key">{t("clis_view.auth_api_key")}</option>
+ <option value="config_file">{t("clis_view.auth_config_file")}</option>
</select>
</label>
{(form.auth_mode === "oauth_cli") && (
- <TextField label="Login-Command" val={form.login_command}
+ <TextField label={t("clis_view.field_login_command")} val={form.login_command}
onChange={(v) => setForm({ ...form, login_command: v })}
placeholder="mytool login" mono />
)}
{form.auth_mode !== "none" && (
- <TextField label="Status-Command" val={form.status_command}
+ <TextField label={t("clis_view.field_status_command")} val={form.status_command}
onChange={(v) => setForm({ ...form, status_command: v })}
placeholder="mytool whoami" mono />
)}
{form.auth_mode === "api_key" && (
<>
- <TextField label="Secret-Keys (comma-separated)" val={form.secret_keys}
+ <TextField label={t("clis_view.field_secret_keys")} val={form.secret_keys}
onChange={(v) => setForm({ ...form, secret_keys: v })}
placeholder="mytool_api_key" mono />
- <TextField label="ENV-Vars (comma-separated, 1:1 Reihenfolge)" val={form.env_vars}
+ <TextField label={t("clis_view.field_env_vars")} val={form.env_vars}
onChange={(v) => setForm({ ...form, env_vars: v })}
placeholder="MYTOOL_API_KEY" mono />
</>
@@ -1059,16 +1086,16 @@ function CustomCliWizard({ onClose }: { onClose: () => void }) {
onChange={(e) => setForm({ ...form, risk_tier: e.target.value as typeof form.risk_tier })}
className="w-full rounded-md border border-input bg-background px-3 py-1.5 text-xs"
>
- <option value="safe">safe (läuft ohne Nachfrage)</option>
+ <option value="safe">{t("clis_view.risk_safe")}</option>
<option value="monitor">monitor (execute + log)</option>
- <option value="ask">ask (Bestätigung pro Call)</option>
- <option value="block">block (komplett blockiert)</option>
+ <option value="ask">{t("clis_view.risk_ask")}</option>
+ <option value="block">{t("clis_view.risk_block")}</option>
</select>
</label>
- <TextArea label="Allow-Patterns (eins pro Zeile)" val={form.allow_patterns}
+ <TextArea label={t("clis_view.field_allow_patterns")} val={form.allow_patterns}
onChange={(v) => setForm({ ...form, allow_patterns: v })}
placeholder="mytool get *&#10;mytool list*" />
- <TextArea label="Deny-Patterns (eins pro Zeile)" val={form.deny_patterns}
+ <TextArea label={t("clis_view.field_deny_patterns")} val={form.deny_patterns}
onChange={(v) => setForm({ ...form, deny_patterns: v })}
placeholder="mytool delete *&#10;mytool rm *" />
</>
@@ -1083,12 +1110,12 @@ function CustomCliWizard({ onClose }: { onClose: () => void }) {
<div className="flex items-center justify-between gap-2 border-t border-border p-4">
<div className="text-[10px] text-muted-foreground">
- {step < 4 ? "Schritte können übersprungen werden via 'Speichern'" : "Fertig!"}
+ {step < 4 ? t("clis_view.steps_skippable") : t("clis_view.done")}
</div>
<div className="flex items-center gap-2">
{step > 1 && (
<Button variant="ghost" onClick={() => setStep(step - 1)}>
- Zurück
+ {t("common.back")}
</Button>
)}
{step < 4 ? (
@@ -1097,11 +1124,11 @@ function CustomCliWizard({ onClose }: { onClose: () => void }) {
disabled={!canNext()}
onClick={() => setStep(step + 1)}
>
- Weiter
+ {t("clis_view.next")}
</Button>
) : (
<Button className="btn-primary" onClick={submit} disabled={register.isPending}>
- {register.isPending ? "Speichert…" : "Speichern"}
+ {register.isPending ? t("common.saving") : t("common.save")}
</Button>
)}
</div>
@@ -1160,6 +1187,7 @@ function TextArea({
// ---------------------------------------------------------------------------
function UsageDrawer({ name, onClose }: { name: string; onClose: () => void }) {
+ const t = useT();
const [page, setPage] = useState(1);
const [successOnly, setSuccessOnly] = useState(false);
const [search, setSearch] = useState("");
@@ -1213,10 +1241,10 @@ function UsageDrawer({ name, onClose }: { name: string; onClose: () => void }) {
<ScrollArea className="flex-1">
<div className="p-5 text-xs">
- {!usage && <div className="text-muted-foreground">Lade…</div>}
+ {!usage && <div className="text-muted-foreground">{t("common.loading")}</div>}
{usage && usage.entries.length === 0 && (
<div className="py-8 text-center text-muted-foreground">
- Keine Einträge {search && `(suche: "${search}")`}
+ {t("clis_view.no_entries")} {search && `(${t("clis_view.search_word")}: "${search}")`}
</div>
)}
{usage && usage.entries.length > 0 && (
@@ -1284,9 +1312,13 @@ function UsageDrawer({ name, onClose }: { name: string; onClose: () => void }) {
variant="ghost" size="sm"
disabled={clear.isPending}
onClick={() => {
- if (window.confirm(`Komplette History von "${name}" löschen?`)) {
+ if (
+ window.confirm(
+ `${t("clis_view.confirm_clear_history_prefix")} "${name}" ${t("clis_view.confirm_clear_history_suffix")}`,
+ )
+ ) {
clear.mutate(name, {
- onSuccess: (res) => pushToast("success", `${res.deleted} Einträge gelöscht`),
+ onSuccess: (res) => pushToast("success", `${res.deleted} ${t("clis_view.entries_deleted")}`),
onError: (err) => pushToast("error", (err as Error).message),
});
}
@@ -1364,6 +1396,7 @@ function KeyVal({
}
function EmptyState({ hasAny, filter }: { hasAny: boolean; filter: FilterTab }) {
+ const t = useT();
if (!hasAny) {
return (
<div className="flex flex-col items-center justify-center gap-5 py-16 text-center">
@@ -1372,17 +1405,17 @@ function EmptyState({ hasAny, filter }: { hasAny: boolean; filter: FilterTab })
</div>
<div className="max-w-lg space-y-3">
<h3 className="font-display text-xl font-semibold tracking-tight">
- Keine CLIs im Katalog
+ {t("clis_view.empty_no_clis")}
</h3>
</div>
</div>
);
}
const messages: Record<FilterTab, string> = {
- all: "Kein CLI matched die Filter.",
- connected: "Keine CLI ist gerade verbunden.",
- installed: "Keine CLI ist installiert.",
- custom: "Noch keine Custom-CLI registriert — klick 'Add Custom' oben rechts.",
+ all: t("clis_view.empty_all"),
+ connected: t("clis_view.empty_connected"),
+ installed: t("clis_view.empty_installed"),
+ custom: t("clis_view.empty_custom"),
};
return (
<div className="py-12 text-center text-sm text-muted-foreground">
diff --git a/jarvis/ui/web/frontend/src/views/ConductorView.tsx b/jarvis/ui/web/frontend/src/views/ConductorView.tsx
index 465d197f18..0ec7ba0377 100644
--- a/jarvis/ui/web/frontend/src/views/ConductorView.tsx
+++ b/jarvis/ui/web/frontend/src/views/ConductorView.tsx
@@ -23,6 +23,7 @@ import { Button } from "@/components/ui/button";
import { Badge } from "@/components/ui/badge";
import { Switch } from "@/components/ui/switch";
import { cn } from "@/lib/utils";
+import { translate, useT } from "@/i18n";
import {
useConductorDashboard,
useCreateConductorJob,
@@ -61,6 +62,7 @@ const SCHED_ICON: Record<string, typeof Clock> = {
// ---------------------------------------------------------------------
export function ConductorView() {
+ const t = useT();
const { data, isLoading, error, refetch, isRefetching } =
useConductorDashboard();
const [editorOpen, setEditorOpen] = useState(false);
@@ -88,7 +90,7 @@ export function ConductorView() {
onClick={() => setEditorOpen(true)}
>
<Plus className="mr-1 h-4 w-4" />
- Neuer Job
+ {t("conductor_view.new_job")}
</Button>
<Button
size="sm"
@@ -115,11 +117,11 @@ export function ConductorView() {
<ScrollArea className="flex-1">
<div className="space-y-2 px-5 pb-6">
{isLoading && (
- <div className="text-sm text-muted-foreground">Lade Jobs…</div>
+ <div className="text-sm text-muted-foreground">{t("conductor_view.loading_jobs")}</div>
)}
{error && (
<div className="rounded-lg border border-destructive/40 bg-destructive/10 p-4 text-sm text-destructive">
- Conductor-API antwortet nicht: {(error as Error).message}
+ {t("conductor_view.api_unreachable")}: {(error as Error).message}
</div>
)}
{!isLoading && !error && jobs.length === 0 && <EmptyJobs />}
@@ -171,6 +173,7 @@ function SummaryBar({
jobCount: number;
runCount: number;
}) {
+ const t = useT();
return (
<div className="flex items-center gap-3 border-b border-border bg-background/30 px-5 py-2.5">
<StatChip
@@ -180,7 +183,7 @@ function SummaryBar({
/>
<StatChip
icon={<Play className="h-3.5 w-3.5 text-emerald-400" />}
- label="Aktiv"
+ label={t("conductor_view.stat_active")}
value={String(summary?.enabled ?? 0)}
/>
<StatChip
@@ -199,7 +202,7 @@ function SummaryBar({
value={String(summary?.by_type?.shell ?? 0)}
/>
<div className="ml-auto text-xs text-muted-foreground">
- {runCount} Runs (letzte 30)
+ {runCount} {t("conductor_view.runs_last_30")}
</div>
</div>
);
@@ -230,6 +233,7 @@ function StatChip({
// ---------------------------------------------------------------------
function JobCard({ job }: { job: JobSummary }) {
+ const t = useT();
const runMut = useRunConductorJob();
const toggleMut = useToggleConductorJob();
const deleteMut = useDeleteConductorJob();
@@ -268,12 +272,12 @@ function JobCard({ job }: { job: JobSummary }) {
</p>
{job.tags.length > 0 && (
<div className="mt-1.5 flex flex-wrap gap-1">
- {job.tags.map((t) => (
+ {job.tags.map((tag) => (
<span
- key={t}
+ key={tag}
className="rounded-full border border-border bg-background/60 px-2 py-0.5 text-[10px] text-muted-foreground"
>
- #{t}
+ #{tag}
</span>
))}
</div>
@@ -303,11 +307,17 @@ function JobCard({ job }: { job: JobSummary }) {
size="sm"
variant="ghost"
onClick={() => {
- if (window.confirm(`Job "${job.name}" wirklich löschen?`))
+ if (
+ window.confirm(
+ `${t("conductor_view.delete_confirm_prefix")} "${job.name}" ${t(
+ "conductor_view.delete_confirm_suffix",
+ )}`,
+ )
+ )
deleteMut.mutate(job.id);
}}
disabled={deleteMut.isPending}
- title="Löschen"
+ title={t("common.delete")}
>
<Trash2 className="h-4 w-4" />
</Button>
@@ -476,6 +486,7 @@ const EXAMPLE_SHELL_JSON = `{
}`;
function JobEditorModal({ onClose }: { onClose: () => void }) {
+ const t = useT();
const [text, setText] = useState(EXAMPLE_SHELL_JSON);
const [err, setErr] = useState<string | null>(null);
const createMut = useCreateConductorJob();
@@ -486,7 +497,7 @@ function JobEditorModal({ onClose }: { onClose: () => void }) {
try {
parsed = JSON.parse(text);
} catch (e) {
- setErr("JSON-Syntaxfehler: " + (e as Error).message);
+ setErr(`${t("conductor_view.json_syntax_error")}: ${(e as Error).message}`);
return;
}
try {
@@ -509,7 +520,7 @@ function JobEditorModal({ onClose }: { onClose: () => void }) {
<div className="flex items-center justify-between border-b border-border px-5 py-3">
<div className="flex items-center gap-2">
<Sparkles className="h-4 w-4 text-primary" />
- <h2 className="text-sm font-semibold">Neuer Job</h2>
+ <h2 className="text-sm font-semibold">{t("conductor_view.new_job")}</h2>
<Badge variant="outline" className="text-[10px]">
JSON
</Badge>
@@ -524,7 +535,7 @@ function JobEditorModal({ onClose }: { onClose: () => void }) {
</div>
<div className="flex-1 overflow-auto p-4">
<p className="mb-3 text-xs text-muted-foreground">
- Jobs sind JSON — kopierbar, diffbar, git-friendly. Drei Types:{" "}
+ {t("conductor_view.editor_intro")}{" "}
<code className="rounded bg-background/60 px-1">shell</code>,{" "}
<code className="rounded bg-background/60 px-1">http</code>,{" "}
<code className="rounded bg-background/60 px-1">agent</code>.
@@ -548,7 +559,7 @@ function JobEditorModal({ onClose }: { onClose: () => void }) {
</div>
<div className="flex items-center justify-end gap-2 border-t border-border bg-background/30 px-4 py-3">
<Button variant="ghost" size="sm" onClick={onClose}>
- Abbrechen
+ {t("common.cancel")}
</Button>
<Button size="sm" onClick={submit} disabled={createMut.isPending}>
{createMut.isPending ? (
@@ -556,7 +567,7 @@ function JobEditorModal({ onClose }: { onClose: () => void }) {
) : (
<Plus className="mr-1 h-3.5 w-3.5" />
)}
- Anlegen
+ {t("conductor_view.create")}
</Button>
</div>
</div>
@@ -569,25 +580,27 @@ function JobEditorModal({ onClose }: { onClose: () => void }) {
// ---------------------------------------------------------------------
function EmptyJobs() {
+ const t = useT();
return (
<div className="flex flex-col items-center justify-center gap-2 rounded-lg border border-dashed border-border/60 bg-background/30 p-8 text-center">
<Orbit className="h-6 w-6 text-muted-foreground/50" />
<p className="text-sm text-muted-foreground">
- Noch keine Jobs. Drücke "Neuer Job" oben rechts.
+ {t("conductor_view.empty_jobs")}
</p>
<p className="text-xs text-muted-foreground/60">
- Beim ersten Start werden 3 Demo-Jobs geseedet.
+ {t("conductor_view.empty_jobs_hint")}
</p>
</div>
);
}
function EmptyTimeline() {
+ const t = useT();
return (
<div className="flex flex-col items-center justify-center gap-2 rounded-lg border border-dashed border-border/60 bg-background/30 p-8 text-center">
<Clock className="h-6 w-6 text-muted-foreground/50" />
<p className="text-sm text-muted-foreground">
- Noch keine Runs — klick auf Play bei einem Job.
+ {t("conductor_view.empty_timeline")}
</p>
</div>
);
@@ -599,7 +612,7 @@ function EmptyTimeline() {
function formatDeltaPast(ns: number): string {
const delta = Date.now() * 1e6 - ns;
- if (delta <= 0) return "jetzt";
+ if (delta <= 0) return translate("conductor_view.now");
const sec = Math.round(delta / 1e9);
if (sec < 60) return `${sec}s`;
const min = Math.round(sec / 60);
diff --git a/jarvis/ui/web/frontend/src/views/FriendsView.tsx b/jarvis/ui/web/frontend/src/views/FriendsView.tsx
index 2e25996ef3..11e74bd0ba 100644
--- a/jarvis/ui/web/frontend/src/views/FriendsView.tsx
+++ b/jarvis/ui/web/frontend/src/views/FriendsView.tsx
@@ -7,6 +7,7 @@ import { AddFriendMenu } from "@/components/friends/AddFriendMenu";
import { ChatTab } from "@/views/friends/ChatTab";
import { StatusTab } from "@/views/friends/StatusTab";
import { cn } from "@/lib/utils";
+import { useT } from "@/i18n";
/**
* Phase F2 — zwei Tabs auf diesem Branch:
@@ -20,6 +21,7 @@ import { cn } from "@/lib/utils";
type Tab = "chat" | "status";
export function FriendsView() {
+ const t = useT();
const [tab, setTab] = useState<Tab>("chat");
const [addOpen, setAddOpen] = useState(false);
@@ -28,14 +30,14 @@ export function FriendsView() {
<ViewHeader
icon={<Users className="h-4 w-4 text-primary" />}
title="Friends"
- subtitle="Telegram-Bot + lokaler Friend-Registry. Du entscheidest, was Friends sehen."
+ subtitle={t("friends_view.subtitle")}
right={
<button
type="button"
onClick={() => setAddOpen(true)}
className="inline-flex items-center gap-1 rounded-md border border-primary/40 bg-primary/10 px-2.5 py-1 text-[11px] text-primary hover:bg-primary/20"
>
- <Plus className="h-3 w-3" /> Friend hinzufuegen
+ <Plus className="h-3 w-3" /> {t("add_friend_menu.title")}
</button>
}
/>
diff --git a/jarvis/ui/web/frontend/src/views/MissionsView.tsx b/jarvis/ui/web/frontend/src/views/MissionsView.tsx
index 1425e8ac04..6d8ab4d4b7 100644
--- a/jarvis/ui/web/frontend/src/views/MissionsView.tsx
+++ b/jarvis/ui/web/frontend/src/views/MissionsView.tsx
@@ -46,6 +46,7 @@ import {
useMissionsStore,
} from "@/components/missions/store";
import { useMissionWebSocket } from "@/components/missions/useMissionWebSocket";
+import { useT } from "@/i18n";
import type { MissionPlanReady } from "@/types/missions";
const PtyTerminal = lazy(() =>
@@ -55,6 +56,7 @@ const PtyTerminal = lazy(() =>
);
export function MissionsView() {
+ const t = useT();
useMissionWebSocket();
const setMissions = useMissionsStore((s) => s.setMissions);
@@ -97,8 +99,8 @@ export function MissionsView() {
<div className="flex h-full flex-col">
<ViewHeader
icon={<Target className="h-4 w-4 text-primary" />}
- title="Missions"
- subtitle="Phase 6 — Worker/Critic-Loop. Live-Bus, PTY-Streams, Verdicts."
+ title={t("missions_view.title")}
+ subtitle={t("missions_view.subtitle")}
right={
<div className="flex items-center gap-3">
<ConnectionBadge connected={connected} />
@@ -109,7 +111,7 @@ export function MissionsView() {
variant={activeCount > 0 ? "default" : "outline"}
className="font-mono text-[10px]"
>
- {activeCount} aktiv
+ {activeCount} {t("missions_view.active")}
</Badge>
<GlobalKillButton />
</div>
@@ -120,7 +122,7 @@ export function MissionsView() {
{/* Linke Pane */}
<div className="flex h-full flex-col overflow-hidden border-r border-border bg-card/20">
<div className="border-b border-border px-3 py-2 text-[10px] uppercase tracking-wider text-muted-foreground">
- Mission-Tree
+ {t("missions_view.tree_label")}
</div>
<div className="flex-1 overflow-hidden">
<MissionTree />
@@ -143,7 +145,7 @@ export function MissionsView() {
</div>
<div className="overflow-hidden bg-card/20">
<div className="border-b border-border px-3 py-1.5 text-[10px] uppercase tracking-wider text-muted-foreground">
- Event-Timeline
+ {t("missions_view.timeline_label")}
</div>
<div className="h-[calc(100%-28px)]">
<EventTimeline />
@@ -217,17 +219,18 @@ function ConnectionBadge({ connected }: { connected: boolean }) {
}
function SelectionPlaceholder({ hasMission }: { hasMission: boolean }) {
+ const t = useT();
return (
<div className="flex h-full flex-col items-center justify-center gap-2 rounded-md border border-dashed border-border/60 bg-background/20 text-center text-sm text-muted-foreground">
{hasMission ? (
<>
<CableCar className="h-8 w-8 text-muted-foreground/40" />
- <p>Worker im Tree links auswaehlen, um den Live-Stream zu sehen.</p>
+ <p>{t("missions_view.select_worker_hint")}</p>
</>
) : (
<>
<Cable className="h-8 w-8 text-muted-foreground/40" />
- <p>Mission auswaehlen, um Details zu laden.</p>
+ <p>{t("missions_view.select_mission_hint")}</p>
</>
)}
</div>
@@ -235,14 +238,16 @@ function SelectionPlaceholder({ hasMission }: { hasMission: boolean }) {
}
function TerminalFallback() {
+ const t = useT();
return (
<div className="flex h-full items-center justify-center text-xs text-muted-foreground">
- Lade Terminal…
+ {t("missions_view.loading_terminal")}
</div>
);
}
function ReasoningPanel() {
+ const t = useT();
const events = useMissionsStore(
useShallow((s) => {
if (!s.selectedMissionId) return [];
@@ -258,7 +263,7 @@ function ReasoningPanel() {
return (
<div className="flex h-full flex-col items-center justify-center gap-2 px-4 text-center text-xs text-muted-foreground">
<CircleSlash className="h-7 w-7 text-muted-foreground/40" />
- <p>Keine Reasoning-Notes verfuegbar.</p>
+ <p>{t("missions_view.no_reasoning_notes")}</p>
</div>
);
}
@@ -307,6 +312,7 @@ function ReasoningPanel() {
}
function PlanPanel() {
+ const t = useT();
const planEnv = useMissionsStore(
useShallow((s) => {
if (!s.selectedMissionId) return null;
@@ -324,7 +330,7 @@ function PlanPanel() {
return (
<div className="flex h-full flex-col items-center justify-center gap-2 px-4 text-center text-xs text-muted-foreground">
<MapIcon className="h-7 w-7 text-muted-foreground/40" />
- <p>Noch kein Plan veroeffentlicht.</p>
+ <p>{t("missions_view.no_plan_published")}</p>
</div>
);
}
@@ -334,14 +340,14 @@ function PlanPanel() {
<div className="space-y-3 p-3">
<div className="rounded border border-border/60 bg-card/30 p-2 text-xs">
<div className="text-[10px] uppercase tracking-wider text-muted-foreground">
- Erwartete Ausgabe
+ {t("missions_view.expected_output")}
</div>
<p className="mt-1 text-foreground/90">
- {planEnv.expected_output || "(nicht spezifiziert)"}
+ {planEnv.expected_output || t("missions_view.not_specified")}
</p>
</div>
<div className="text-[10px] uppercase tracking-wider text-muted-foreground">
- Schritte ({planEnv.n_workers} Worker)
+ {t("missions_view.steps")} ({planEnv.n_workers} {t("missions_view.workers")})
</div>
<ol className="space-y-2">
{planEnv.plan.map((step, idx) => (
diff --git a/jarvis/ui/web/frontend/src/views/OutputsView.rerun.test.tsx b/jarvis/ui/web/frontend/src/views/OutputsView.rerun.test.tsx
index 044137469e..f673db42c0 100644
--- a/jarvis/ui/web/frontend/src/views/OutputsView.rerun.test.tsx
+++ b/jarvis/ui/web/frontend/src/views/OutputsView.rerun.test.tsx
@@ -7,7 +7,7 @@
* - status "running" / "success" / no mission_id → neither.
*/
import { afterEach, describe, expect, it, vi } from "vitest";
-import { cleanup, render, screen, waitFor } from "@testing-library/react";
+import { cleanup, fireEvent, render, screen, waitFor } from "@testing-library/react";
import { QueryClient, QueryClientProvider } from "@tanstack/react-query";
import { OutputsView } from "@/views/OutputsView";
@@ -27,6 +27,11 @@ afterEach(() => {
function installFetchMock(
sessions: OutputSummary[],
artifacts: ArtifactSummary[] = [],
+ openers = [
+ { id: "default", label: "System default app" },
+ { id: "code", label: "VS Code" },
+ ],
+ preferredOpener = "",
) {
const fetchMock = vi.fn(async (input: RequestInfo | URL) => {
const url = String(input);
@@ -54,16 +59,15 @@ function installFetchMock(
return {
ok: true,
status: 200,
- json: async () => ({
- openers: [
- { id: "default", label: "System default app" },
- { id: "code", label: "VS Code" },
- ],
- }),
+ json: async () => ({ openers }),
};
}
if (url.includes("/preferred-opener")) {
- return { ok: true, status: 200, json: async () => ({ opener: "" }) };
+ return {
+ ok: true,
+ status: 200,
+ json: async () => ({ opener: preferredOpener }),
+ };
}
if (url.includes("/api/outputs")) {
return { ok: true, status: 200, json: async () => ({ sessions }) };
@@ -172,4 +176,85 @@ describe("OutputsView artifact actions", () => {
expect(screen.getByTitle("Reveal in folder")).toBeDefined();
expect(screen.queryByTitle("Open in browser")).toBeNull();
});
+
+ it("opens the browser chooser option via the rendered artifact URL", async () => {
+ const fetchMock = installFetchMock(
+ [session({ slug: "artifact-slug", status: "success", mission_id: "m-a" })],
+ [
+ {
+ path: "tasks/019edf/artifacts/files/report.md",
+ size: 34_700,
+ mtime: 1_750_000_000,
+ is_text: true,
+ preview: "# Report",
+ },
+ ],
+ [
+ { id: "default", label: "System default app" },
+ { id: "browser", label: "Browser" },
+ { id: "code", label: "VS Code" },
+ ],
+ );
+ const openSpy = vi.spyOn(window, "open").mockImplementation(() => null);
+
+ renderView();
+
+ await waitFor(() =>
+ expect(
+ screen.getByText("tasks/019edf/artifacts/files/report.md"),
+ ).toBeDefined(),
+ );
+
+ fireEvent.click(screen.getByTitle("Change how this opens"));
+ fireEvent.click(await screen.findByText("Browser"));
+
+ expect(openSpy).toHaveBeenCalledWith(
+ "/api/outputs/artifact-slug/files/tasks/019edf/artifacts/files/report.md/view",
+ "_blank",
+ "noopener,noreferrer",
+ );
+ expect(
+ fetchMock.mock.calls.some(([input]) => String(input).includes("/open-with")),
+ ).toBe(false);
+ });
+
+ it("opens a remembered browser preference via the rendered artifact URL", async () => {
+ const fetchMock = installFetchMock(
+ [session({ slug: "artifact-slug", status: "success", mission_id: "m-a" })],
+ [
+ {
+ path: "tasks/019edf/artifacts/files/report.md",
+ size: 34_700,
+ mtime: 1_750_000_000,
+ is_text: true,
+ preview: "# Report",
+ },
+ ],
+ [
+ { id: "default", label: "System default app" },
+ { id: "browser", label: "Browser" },
+ ],
+ "browser",
+ );
+ const openSpy = vi.spyOn(window, "open").mockImplementation(() => null);
+
+ renderView();
+
+ await waitFor(() =>
+ expect(
+ screen.getByText("tasks/019edf/artifacts/files/report.md"),
+ ).toBeDefined(),
+ );
+
+ fireEvent.click(screen.getByTitle("Open"));
+
+ expect(openSpy).toHaveBeenCalledWith(
+ "/api/outputs/artifact-slug/files/tasks/019edf/artifacts/files/report.md/view",
+ "_blank",
+ "noopener,noreferrer",
+ );
+ expect(
+ fetchMock.mock.calls.some(([input]) => String(input).includes("/open-with")),
+ ).toBe(false);
+ });
});
diff --git a/jarvis/ui/web/frontend/src/views/OutputsView.tsx b/jarvis/ui/web/frontend/src/views/OutputsView.tsx
index 61932651c3..4e566bc6bd 100644
--- a/jarvis/ui/web/frontend/src/views/OutputsView.tsx
+++ b/jarvis/ui/web/frontend/src/views/OutputsView.tsx
@@ -136,11 +136,11 @@ export function OutputsView() {
</div>
) : error ? (
<div className="p-4 text-xs text-destructive">
- Outputs nicht geladen: {String(error)}
+ {t("outputs_view.list_load_error")}: {String(error)}
</div>
) : sessions.length === 0 ? (
<div className="flex flex-1 items-center justify-center p-6 text-center text-xs text-muted-foreground">
- Noch keine Sub-Agent-Sessions. Starte einen OpenClaw-Task.
+ {t("outputs_view.empty_sessions")}
</div>
) : (
<ScrollArea className="flex-1">
@@ -165,7 +165,7 @@ export function OutputsView() {
<SessionDetail meta={effectiveSelected} />
) : (
<div className="flex flex-1 items-center justify-center text-xs text-muted-foreground">
- Waehle eine Session.
+ {t("outputs_view.select_session")}
</div>
)}
</section>
@@ -399,7 +399,7 @@ function SessionDetail({ meta }: { meta: OutputSummary }) {
{meta.error && (
<section className="rounded-xl border border-destructive/30 bg-destructive/5 p-4">
<div className="mb-1 text-[10px] font-semibold uppercase tracking-wide text-destructive">
- Fehler
+ {t("common.error")}
</div>
<pre className="whitespace-pre-wrap text-xs text-destructive/90">
{meta.error}
@@ -426,16 +426,16 @@ function SessionDetail({ meta }: { meta: OutputSummary }) {
{plan.isLoading ? (
<div className="flex items-center gap-2 text-xs text-muted-foreground">
<Loader2 className="h-3 w-3 animate-spin" />
- Lade Plan...
+ {t("outputs_view.loading_plan")}
</div>
) : plan.isError ? (
<div className="text-xs text-destructive">
- Plan konnte nicht geladen werden: {String(plan.error)}
+ {t("outputs_view.plan_load_error")}: {String(plan.error)}
</div>
) : isSingleShot ? (
<div className="flex items-center gap-2 rounded-lg border border-border bg-background/50 p-3 text-xs text-muted-foreground">
<FileQuestion className="h-4 w-4" />
- Single-Shot-Run — kein strukturierter Plan fuer diese Session.
+ {t("outputs_view.single_shot_no_plan")}
</div>
) : hasPlan && plan.data ? (
<>
@@ -467,6 +467,7 @@ function isPlumbingArtifact(path: string): boolean {
}
function ArtifactsSection({ slug }: { slug: string }) {
+ const t = useT();
const q = useArtifactsForOutput(slug);
const caps = useOutputsCapabilities();
const nativeActions = caps.data?.native_file_actions ?? false;
@@ -491,15 +492,15 @@ function ArtifactsSection({ slug }: { slug: string }) {
{q.isLoading ? (
<div className="flex items-center gap-2 text-xs text-muted-foreground">
<Loader2 className="h-3 w-3 animate-spin" />
- Lade Artefakte...
+ {t("outputs_view.loading_artifacts")}
</div>
) : q.isError ? (
<div className="text-xs text-destructive">
- Artefakte nicht geladen: {String(q.error)}
+ {t("outputs_view.artifacts_load_error")}: {String(q.error)}
</div>
) : files.length === 0 ? (
<div className="text-xs text-muted-foreground">
- Diese Session hat keine gespeicherten Dateien.
+ {t("outputs_view.no_files")}
</div>
) : (
<ul className="flex flex-col gap-1">
@@ -535,10 +536,18 @@ function ArtifactRow({
const preferred = usePreferredOpener();
const setPreferred = useSetPreferredOpener();
+ const openWithOpener = (opener: string) => {
+ if (opener === "browser" && openUrl) {
+ window.open(openUrl, "_blank", "noopener,noreferrer");
+ return;
+ }
+ void openArtifactWith(slug, file.path, opener).catch(() => {});
+ };
+
// Open the file with a specific app (desktop). Remembering persists the
// choice so the next "Open" click skips the chooser.
const pickOpener = (opener: string, remember: boolean) => {
- void openArtifactWith(slug, file.path, opener).catch(() => {});
+ openWithOpener(opener);
if (remember) setPreferred.mutate(opener);
setChooserOpen(false);
};
@@ -552,7 +561,7 @@ function ArtifactRow({
}
const pref = preferred.data ?? "";
if (pref) {
- void openArtifactWith(slug, file.path, pref).catch(() => {});
+ openWithOpener(pref);
} else {
setChooserOpen(true); // first time: ask which app
}
@@ -655,7 +664,7 @@ function ArtifactRow({
</pre>
{full.data?.truncated && (
<div className="mt-1 text-[10px] text-muted-foreground">
- Datei gekürzt auf 1 MiB — Rest im Datei-Manager anzeigen.
+ {t("outputs_view.file_truncated")}
</div>
)}
</>
diff --git a/jarvis/ui/web/frontend/src/views/SelfModView.tsx b/jarvis/ui/web/frontend/src/views/SelfModView.tsx
index 0eff6e3bae..333fe7ddc3 100644
--- a/jarvis/ui/web/frontend/src/views/SelfModView.tsx
+++ b/jarvis/ui/web/frontend/src/views/SelfModView.tsx
@@ -9,6 +9,7 @@
import { useEffect, useMemo, useState } from "react";
import { useEventStore } from "@/store/events";
+import { useT } from "@/i18n";
type AuditEvent = {
ts: string;
@@ -219,6 +220,7 @@ function AuditEventDetail({
event: AuditEvent;
onClose: () => void;
}) {
+ const t = useT();
const sensitive = isSensitivePath(event.path);
// Server hat schon redacted; clientseitig markieren wir das visuell.
const display = useMemo(() => {
@@ -244,12 +246,12 @@ function AuditEventDetail({
}}
>
<button onClick={onClose} style={{ marginBottom: 12 }}>
- × Schließen
+ × {t("common.close")}
</button>
<h3>Audit-Event</h3>
{sensitive && (
<p style={{ color: "#fa0" }}>
- ⚠ Sensitive Pfad — Werte serverseitig redacted (Plan-§AP-2).
+ ⚠ {t("self_mod_view.sensitive_path_notice")}
</p>
)}
<pre style={{ fontSize: 11, background: "#000", padding: 8 }}>
@@ -353,31 +355,31 @@ function BackupsList() {
// ----------------------------------------------------------------------
export default function SelfModView() {
+ const t = useT();
const assistantName = useEventStore((s) => s.assistantName);
const [tab, setTab] = useState<Tab>("history");
return (
<div style={{ padding: 16 }}>
<h2>Self-Modification</h2>
<p style={{ fontSize: 13, color: "#aaa" }}>
- Read-only Sicht auf Audit-Trail, mutierbare Settings und Backups.
- Mutationen erfolgen ausschließlich via Voice/Chat — diese View
- zeigt nur, was {assistantName} an sich selbst geändert hat.
+ {t("self_mod_view.intro_a")} {t("self_mod_view.intro_b")}{" "}
+ {assistantName} {t("self_mod_view.intro_c")}
</p>
<nav style={{ display: "flex", gap: 8, marginBottom: 16 }}>
- {(["history", "mutable", "backups"] as Tab[]).map((t) => (
+ {(["history", "mutable", "backups"] as Tab[]).map((tabId) => (
<button
- key={t}
- onClick={() => setTab(t)}
+ key={tabId}
+ onClick={() => setTab(tabId)}
style={{
padding: "6px 12px",
- background: tab === t ? "#444" : "#222",
+ background: tab === tabId ? "#444" : "#222",
color: "#fff",
border: "none",
borderRadius: 4,
cursor: "pointer",
}}
>
- {t === "history" ? "History" : t === "mutable" ? "Settings" : "Backups"}
+ {tabId === "history" ? "History" : tabId === "mutable" ? "Settings" : "Backups"}
</button>
))}
</nav>
diff --git a/jarvis/ui/web/frontend/src/views/SessionsView.tsx b/jarvis/ui/web/frontend/src/views/SessionsView.tsx
index 4f7198f4a0..bfcfbb865f 100644
--- a/jarvis/ui/web/frontend/src/views/SessionsView.tsx
+++ b/jarvis/ui/web/frontend/src/views/SessionsView.tsx
@@ -44,7 +44,7 @@ export function SessionsView() {
const errorMessage = sessionsQuery.error
? sessionsQuery.error instanceof Error
? sessionsQuery.error.message
- : "Unbekannter Fehler"
+ : t("sessions_view.unknown_error")
: null;
return (
@@ -57,12 +57,14 @@ export function SessionsView() {
{errorMessage && /HTTP 503/.test(errorMessage) && (
<div className="border-b border-amber-400/30 bg-amber-400/10 px-5 py-3 text-sm text-amber-200">
- <div className="font-medium">Session-Recorder ist deaktiviert.</div>
+ <div className="font-medium">{t("sessions_view.recorder_disabled")}</div>
<div className="mt-0.5 text-xs text-amber-200/80">
- In <code className="font-mono">jarvis.toml</code> die Sektion{" "}
- <code className="font-mono">[sessions]</code> aktivieren
- (<code className="font-mono">enabled = true</code>) und {assistantName} neu
- starten.
+ {t("sessions_view.recorder_hint_a")}{" "}
+ <code className="font-mono">[sessions]</code>{" "}
+ {t("sessions_view.recorder_hint_b")}{" "}
+ <code className="font-mono">jarvis.toml</code>{" "}
+ (<code className="font-mono">enabled = true</code>){" "}
+ {t("sessions_view.recorder_hint_c")} {assistantName}.
</div>
</div>
)}
diff --git a/jarvis/ui/web/frontend/src/views/SkillCreateDialog.tsx b/jarvis/ui/web/frontend/src/views/SkillCreateDialog.tsx
index 5124146a45..e2f0944c0e 100644
--- a/jarvis/ui/web/frontend/src/views/SkillCreateDialog.tsx
+++ b/jarvis/ui/web/frontend/src/views/SkillCreateDialog.tsx
@@ -1,44 +1,276 @@
/**
- * SkillCreateDialog — Stub nach Filesystem-Reset 2026-04-25.
- * Vollstaendige Implementation folgt; aktuell minimaler Close-only-Dialog
- * damit der TS-Build durchlaeuft und die SkillsView nicht crasht.
+ * SkillCreateDialog — create a new user skill from the desktop app.
+ *
+ * Two ways in, one robust outcome:
+ * - Fill the form (name + instructions) and hit Create. This goes through the
+ * deterministic POST /api/skills path — no brain, always works, even on a
+ * headless VPS.
+ * - Optionally hit "Draft with AI": the creator endpoint turns a free-text
+ * intent into a pre-filled draft. If a brain is reachable it fills richer
+ * content; if not (or it fails) it returns a deterministic starter template
+ * and the form stays fully editable. Either way the user reviews the fields
+ * and Create persists exactly what they see.
*/
-import { X } from "lucide-react";
+import { useEffect, useState } from "react";
+import { X, Sparkles, Loader2, Plus, AlertTriangle } 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";
export function SkillCreateDialog({
open,
onClose,
+ onCreated,
}: {
open: boolean;
onClose: () => void;
onCreated?: (name: string) => void;
}) {
+ const t = useT();
+ const draftSkill = useDraftSkill();
+ const createSkill = useCreateSkill();
+
+ const [intent, setIntent] = useState("");
+ const [name, setName] = useState("");
+ const [category, setCategory] = useState("general");
+ const [description, setDescription] = useState("");
+ const [body, setBody] = useState("");
+ const [trigger, setTrigger] = useState("");
+ const [error, setError] = useState<string | null>(null);
+ const [aiNote, setAiNote] = useState<string | null>(null);
+
+ // Reset all state whenever the dialog (re)opens, and wire Escape-to-close.
+ useEffect(() => {
+ if (!open) return;
+ setIntent("");
+ setName("");
+ setCategory("general");
+ setDescription("");
+ setBody("");
+ setTrigger("");
+ setError(null);
+ setAiNote(null);
+ const onKey = (e: KeyboardEvent) => {
+ if (e.key === "Escape") onClose();
+ };
+ window.addEventListener("keydown", onKey);
+ return () => window.removeEventListener("keydown", onKey);
+ }, [open, onClose]);
+
if (!open) return null;
+
+ const runDraft = async () => {
+ setError(null);
+ setAiNote(null);
+ try {
+ const res = await draftSkill.mutateAsync({
+ intent,
+ name_hint: name,
+ category,
+ trigger_hint: trigger,
+ });
+ const d = res.draft;
+ setName(d.name ?? name);
+ setDescription(d.description ?? "");
+ setCategory(d.category ?? category);
+ setBody(d.body ?? "");
+ const firstVoice = (d.triggers ?? []).find((tr) => tr.type === "voice");
+ if (firstVoice?.pattern) setTrigger(firstVoice.pattern);
+ setAiNote(
+ res.brain_used
+ ? t("skill_create_dialog.brain_used")
+ : t("skill_create_dialog.brain_unavailable"),
+ );
+ } catch (e) {
+ setError((e as Error).message);
+ }
+ };
+
+ const runCreate = async () => {
+ setError(null);
+ if (name.trim().length < 3) {
+ setError(t("skill_create_dialog.name_required"));
+ return;
+ }
+ try {
+ const detail = await createSkill.mutateAsync({
+ name: name.trim(),
+ description: description.trim(),
+ category: category.trim() || "general",
+ body: body.trim() ? body : `## ${name.trim()}\n`,
+ triggers: trigger.trim()
+ ? [{ type: "voice", pattern: trigger.trim() }]
+ : [],
+ });
+ onCreated?.(detail.name);
+ onClose();
+ } catch (e) {
+ setError((e as Error).message);
+ }
+ };
+
+ const busy = draftSkill.isPending || createSkill.isPending;
+
return (
- <div className="fixed inset-0 z-50 flex items-center justify-center bg-black/60 backdrop-blur-sm">
- <div className="flex w-full max-w-md flex-col rounded-xl border border-border bg-card shadow-lg">
- <div className="flex items-start justify-between gap-4 border-b border-border p-5">
- <div className="min-w-0 flex-1">
- <h3 className="font-display text-base font-semibold">
- Skill erstellen
- </h3>
- <p className="mt-1 text-[11px] text-muted-foreground">
- Diese Funktion wird gerade neu aufgebaut. Bis dahin Skills bitte
- direkt als YAML-Dateien in <code>~/.jarvis/skills/</code> ablegen.
- </p>
+ <div
+ className="fixed inset-0 z-50 flex items-center justify-center bg-black/70 p-4"
+ onClick={(e) => {
+ if (e.target === e.currentTarget) onClose();
+ }}
+ >
+ <div className="flex max-h-[88vh] w-[640px] max-w-full flex-col overflow-hidden rounded-xl border border-border bg-card shadow-2xl">
+ {/* Header */}
+ <div className="flex items-center justify-between border-b border-border px-6 py-4">
+ <div className="flex items-center gap-3">
+ <div className="rounded-md bg-primary/10 p-2">
+ <Plus className="h-5 w-5 text-primary" />
+ </div>
+ <div>
+ <h2 className="text-lg font-semibold">
+ {t("skill_create_dialog.title")}
+ </h2>
+ <p className="text-xs text-muted-foreground">
+ {t("skill_create_dialog.subtitle")}
+ </p>
+ </div>
</div>
- <button
- type="button"
- onClick={onClose}
- className="text-muted-foreground hover:text-foreground"
- >
+ <Button size="icon" variant="ghost" onClick={onClose}>
<X className="h-4 w-4" />
- </button>
+ </Button>
</div>
- <div className="flex items-center justify-end gap-2 border-t border-border p-4">
- <Button type="button" variant="ghost" onClick={onClose}>
- Schliessen
+
+ <ScrollArea className="flex-1">
+ <div className="space-y-4 px-6 py-5">
+ {/* Intent + AI draft */}
+ <div>
+ <label className="mb-1.5 block text-xs font-medium text-muted-foreground">
+ {t("skill_create_dialog.intent_label")}
+ </label>
+ <textarea
+ value={intent}
+ onChange={(e) => setIntent(e.target.value)}
+ rows={2}
+ placeholder={t("skill_create_dialog.intent_placeholder")}
+ className="w-full resize-y rounded-md border border-border bg-background px-3 py-2 text-sm focus:border-primary focus:outline-none focus:ring-1 focus:ring-primary"
+ />
+ <div className="mt-2 flex items-center gap-2">
+ <Button
+ size="sm"
+ variant="outline"
+ onClick={() => void runDraft()}
+ disabled={busy || intent.trim().length < 3}
+ className="gap-1.5"
+ >
+ {draftSkill.isPending ? (
+ <Loader2 className="h-3.5 w-3.5 animate-spin" />
+ ) : (
+ <Sparkles className="h-3.5 w-3.5" />
+ )}
+ {t("skill_create_dialog.draft_with_ai")}
+ </Button>
+ {aiNote && (
+ <span className="text-[11px] text-muted-foreground">
+ {aiNote}
+ </span>
+ )}
+ </div>
+ </div>
+
+ <div className="h-px bg-border" />
+
+ {/* Name + Category */}
+ <div className="grid grid-cols-[1fr_180px] gap-3">
+ <div>
+ <label className="mb-1.5 block text-xs font-medium text-muted-foreground">
+ {t("skill_create_dialog.name_label")}
+ </label>
+ <input
+ type="text"
+ value={name}
+ onChange={(e) => setName(e.target.value)}
+ placeholder={t("skill_create_dialog.name_placeholder")}
+ className="w-full rounded-md border border-border bg-background px-3 py-2 text-sm focus:border-primary focus:outline-none focus:ring-1 focus:ring-primary"
+ />
+ </div>
+ <div>
+ <label className="mb-1.5 block text-xs font-medium text-muted-foreground">
+ {t("skill_create_dialog.category_label")}
+ </label>
+ <input
+ type="text"
+ value={category}
+ onChange={(e) => setCategory(e.target.value)}
+ className="w-full rounded-md border border-border bg-background px-3 py-2 text-sm focus:border-primary focus:outline-none focus:ring-1 focus:ring-primary"
+ />
+ </div>
+ </div>
+
+ {/* Description */}
+ <div>
+ <label className="mb-1.5 block text-xs font-medium text-muted-foreground">
+ {t("skill_create_dialog.description_label")}
+ </label>
+ <input
+ type="text"
+ value={description}
+ onChange={(e) => setDescription(e.target.value)}
+ placeholder={t("skill_create_dialog.description_placeholder")}
+ className="w-full rounded-md border border-border bg-background px-3 py-2 text-sm focus:border-primary focus:outline-none focus:ring-1 focus:ring-primary"
+ />
+ </div>
+
+ {/* Body */}
+ <div>
+ <label className="mb-1.5 block text-xs font-medium text-muted-foreground">
+ {t("skill_create_dialog.body_label")}
+ </label>
+ <textarea
+ value={body}
+ onChange={(e) => setBody(e.target.value)}
+ rows={7}
+ placeholder={t("skill_create_dialog.body_placeholder")}
+ className="w-full resize-y rounded-md border border-border bg-background px-3 py-2 font-mono text-xs focus:border-primary focus:outline-none focus:ring-1 focus:ring-primary"
+ />
+ </div>
+
+ {/* Voice trigger */}
+ <div>
+ <label className="mb-1.5 block text-xs font-medium text-muted-foreground">
+ {t("skill_create_dialog.trigger_label")}
+ </label>
+ <input
+ type="text"
+ value={trigger}
+ onChange={(e) => setTrigger(e.target.value)}
+ placeholder={t("skill_create_dialog.trigger_placeholder")}
+ className="w-full rounded-md border border-border bg-background px-3 py-2 text-sm focus:border-primary focus:outline-none focus:ring-1 focus:ring-primary"
+ />
+ </div>
+
+ {error && (
+ <div className="flex items-start gap-2 rounded-md border border-destructive/40 bg-destructive/10 p-3 text-xs text-destructive">
+ <AlertTriangle className="mt-0.5 h-3.5 w-3.5 flex-shrink-0" />
+ <span>
+ {t("skill_create_dialog.create_error")}: {error}
+ </span>
+ </div>
+ )}
+ </div>
+ </ScrollArea>
+
+ {/* Footer */}
+ <div className="flex items-center justify-end gap-2 border-t border-border px-6 py-4">
+ <Button variant="ghost" onClick={onClose} disabled={busy}>
+ {t("common.close")}
+ </Button>
+ <Button onClick={() => void runCreate()} disabled={busy} className="gap-1.5">
+ {createSkill.isPending ? (
+ <Loader2 className="h-3.5 w-3.5 animate-spin" />
+ ) : (
+ <Plus className="h-3.5 w-3.5" />
+ )}
+ {t("skill_create_dialog.create")}
</Button>
</div>
</div>
diff --git a/jarvis/ui/web/frontend/src/views/SkillFinderDialog.tsx b/jarvis/ui/web/frontend/src/views/SkillFinderDialog.tsx
index 1ff43d2a1d..b9d286a3cb 100644
--- a/jarvis/ui/web/frontend/src/views/SkillFinderDialog.tsx
+++ b/jarvis/ui/web/frontend/src/views/SkillFinderDialog.tsx
@@ -16,6 +16,7 @@ import { Button } from "@/components/ui/button";
import { Badge } from "@/components/ui/badge";
import { ScrollArea } from "@/components/ui/scroll-area";
import { cn } from "@/lib/utils";
+import { useT } from "@/i18n";
import {
useSkillSearch,
useSkillInstall,
@@ -40,6 +41,7 @@ interface SkillFinderDialogProps {
* auf Backend-Filter (trust, min_stars, category, language, max_risk).
*/
export function SkillFinderDialog({ open, onClose }: SkillFinderDialogProps) {
+ const t = useT();
const [query, setQuery] = useState("");
const [trust, setTrust] = useState<TrustFilter>("any");
const [minStars, setMinStars] = useState<number | null>(null);
@@ -99,7 +101,7 @@ export function SkillFinderDialog({ open, onClose }: SkillFinderDialogProps) {
await install.mutateAsync(c);
setInstalledNames((s) => new Set(s).add(c.name));
} catch (e) {
- alert(`Installation fehlgeschlagen: ${(e as Error).message}`);
+ alert(`${t("skill_finder_dialog.install_failed")}: ${(e as Error).message}`);
}
};
@@ -167,44 +169,44 @@ export function SkillFinderDialog({ open, onClose }: SkillFinderDialogProps) {
{/* Dropdowns — interaktive Fragen */}
<div className="grid grid-cols-2 gap-3 md:grid-cols-4">
<DropdownPicker
- label="Vertrauensstufe"
+ label={t("skill_finder_dialog.filter_trust")}
icon={<Shield className="h-3.5 w-3.5" />}
value={trust}
onChange={(v) => setTrust(v as TrustFilter)}
options={[
- { value: "any", label: "Alle", hint: "kein Filter" },
+ { value: "any", label: t("skill_finder_dialog.opt_all"), hint: t("skill_finder_dialog.hint_no_filter") },
{
value: "official",
- label: "Nur offiziell",
+ label: t("skill_finder_dialog.opt_official_only"),
hint: "Anthropic, OpenAI",
},
{
value: "verified",
- label: "Verifiziert+",
- hint: "offiziell + 3k+ Stars",
+ label: t("skill_finder_dialog.opt_verified_plus"),
+ hint: t("skill_finder_dialog.hint_verified_plus"),
},
{
value: "community",
- label: "Community+",
- hint: "aktiv gewartet",
+ label: t("skill_finder_dialog.opt_community_plus"),
+ hint: t("skill_finder_dialog.hint_actively_maintained"),
},
{
value: "experimental",
- label: "Alles, auch Prototypen",
- hint: "Risiko ok",
+ label: t("skill_finder_dialog.opt_everything"),
+ hint: t("skill_finder_dialog.hint_risk_ok"),
},
]}
/>
<DropdownPicker
- label="GitHub-Stars"
+ label={t("skill_finder_dialog.filter_stars")}
icon={<Star className="h-3.5 w-3.5" />}
value={minStars === null ? "any" : String(minStars)}
onChange={(v) =>
setMinStars(v === "any" ? null : parseInt(v, 10))
}
options={[
- { value: "any", label: "Egal" },
+ { value: "any", label: t("skill_finder_dialog.opt_any") },
{ value: "500", label: "500+" },
{ value: "1000", label: "1.000+" },
{ value: "3000", label: "3.000+" },
@@ -213,12 +215,12 @@ export function SkillFinderDialog({ open, onClose }: SkillFinderDialogProps) {
/>
<DropdownPicker
- label="Kategorie"
+ label={t("skill_finder_dialog.filter_category")}
icon={<Search className="h-3.5 w-3.5" />}
value={category ?? "any"}
onChange={(v) => setCategory(v === "any" ? null : v)}
options={[
- { value: "any", label: "Alle" },
+ { value: "any", label: t("skill_finder_dialog.opt_all") },
...(meta.data?.categories ?? []).map((c) => ({
value: c,
label: c,
@@ -227,38 +229,38 @@ export function SkillFinderDialog({ open, onClose }: SkillFinderDialogProps) {
/>
<DropdownPicker
- label="Risiko-Grenze"
+ label={t("skill_finder_dialog.filter_risk")}
icon={<AlertTriangle className="h-3.5 w-3.5" />}
value={maxRisk ?? "any"}
onChange={(v) =>
setMaxRisk(v === "any" ? null : (v as RiskFilter))
}
options={[
- { value: "any", label: "Beliebig" },
- { value: "safe", label: "Nur safe" },
- { value: "monitor", label: "Bis monitor" },
- { value: "ask", label: "Bis ask (nachfragen ok)" },
+ { value: "any", label: t("skill_finder_dialog.opt_any") },
+ { value: "safe", label: t("skill_finder_dialog.opt_safe_only") },
+ { value: "monitor", label: t("skill_finder_dialog.opt_up_to_monitor") },
+ { value: "ask", label: t("skill_finder_dialog.opt_up_to_ask") },
]}
/>
</div>
<div className="flex items-center gap-3">
<DropdownPicker
- label="Sprache"
+ label={t("skill_finder_dialog.filter_language")}
icon={<Globe className="h-3.5 w-3.5" />}
value={language ?? "any"}
onChange={(v) => setLanguage(v === "any" ? null : v)}
options={[
- { value: "any", label: "Alle" },
- { value: "de", label: "Deutsch" },
- { value: "en", label: "Englisch" },
+ { value: "any", label: t("skill_finder_dialog.opt_all") },
+ { value: "de", label: t("skill_finder_dialog.lang_de") },
+ { value: "en", label: t("skill_finder_dialog.lang_en") },
]}
/>
<div className="flex-1" />
<span className="text-xs text-muted-foreground">
{meta.data
- ? `${meta.data.total} Skills im Katalog`
- : "Lade Katalog…"}
+ ? `${meta.data.total} ${t("skill_finder_dialog.skills_in_catalog")}`
+ : t("skill_finder_dialog.loading_catalog")}
</span>
</div>
</div>
@@ -417,6 +419,7 @@ function CandidateCard({
installing: boolean;
onInstall: () => void;
}) {
+ const t = useT();
const noDirect = !candidate.raw_url;
return (
<div className="rounded-lg border border-border bg-background p-4 transition-colors hover:border-primary/30">
@@ -472,7 +475,7 @@ function CandidateCard({
{installed ? (
<Badge className="gap-1" variant="default">
<Check className="h-3 w-3" />
- installiert
+ {t("skill_finder_dialog.installed")}
</Badge>
) : (
<Button
@@ -481,8 +484,8 @@ function CandidateCard({
disabled={installing || noDirect}
title={
noDirect
- ? "Kein Direkt-Download verfuegbar — manuell installieren"
- : "In %LOCALAPPDATA%/Jarvis/skills installieren"
+ ? t("skill_finder_dialog.no_direct_download")
+ : t("skill_finder_dialog.install_to_skills_dir")
}
>
{installing ? (
@@ -490,7 +493,7 @@ function CandidateCard({
) : (
<>
<Download className="mr-1 h-3.5 w-3.5" />
- {noDirect ? "Manuell" : "Installieren"}
+ {noDirect ? t("skill_finder_dialog.manual") : t("skill_finder_dialog.install")}
</>
)}
</Button>
@@ -503,7 +506,7 @@ function CandidateCard({
className="flex items-center gap-1 text-[10px] text-muted-foreground hover:text-primary"
>
<ExternalLink className="h-3 w-3" />
- Quelle
+ {t("skill_finder_dialog.source")}
</a>
)}
</div>
@@ -518,19 +521,20 @@ function formatStars(n: number): string {
}
function EmptyState({ hasQueried }: { hasQueried: boolean }) {
+ const t = useT();
return (
<div className="flex flex-col items-center justify-center py-16 text-center">
<Sparkles className="mb-3 h-8 w-8 text-muted-foreground/50" />
<p className="text-sm text-muted-foreground">
{hasQueried
- ? "Keine Treffer. Andere Filter probieren?"
- : "Beschreib, was du brauchst — die Suche rankt per KI."}
+ ? t("skill_finder_dialog.no_hits")
+ : t("skill_finder_dialog.empty_prompt")}
</p>
{!hasQueried && (
<ul className="mt-4 space-y-1 text-xs text-muted-foreground/80">
- <li>„erstell Skill der meine Emails priorisiert“</li>
- <li>„Git-Workflow vereinfachen“</li>
- <li>„PDF zu strukturiertem Markdown“</li>
+ <li>{t("skill_finder_dialog.example_1")}</li>
+ <li>{t("skill_finder_dialog.example_2")}</li>
+ <li>{t("skill_finder_dialog.example_3")}</li>
</ul>
)}
</div>
diff --git a/jarvis/ui/web/frontend/src/views/SkillsView.tsx b/jarvis/ui/web/frontend/src/views/SkillsView.tsx
index 7ce35736cc..30a660a698 100644
--- a/jarvis/ui/web/frontend/src/views/SkillsView.tsx
+++ b/jarvis/ui/web/frontend/src/views/SkillsView.tsx
@@ -39,7 +39,7 @@ import { Button } from "@/components/ui/button";
import { Badge } from "@/components/ui/badge";
import { Switch } from "@/components/ui/switch";
import { cn } from "@/lib/utils";
-import { useT } from "@/i18n";
+import { translate, useT } from "@/i18n";
import {
useSkillsList,
useSkillDetail,
@@ -64,12 +64,20 @@ import {
} from "@/hooks/useSkills";
import { useEventStore } from "@/store/events";
-const STATE_LABEL: Record<SkillState, string> = {
- active: "aktiv",
- validated: "bereit",
- draft: "fehler",
- disabled: "aus",
-};
+function stateLabel(state: SkillState): string {
+ switch (state) {
+ case "active":
+ return translate("skills_view.active_badge");
+ case "validated":
+ return translate("skills_view.validated_badge");
+ case "draft":
+ return translate("skills_view.draft_badge");
+ case "disabled":
+ return translate("skills_view.disabled_badge");
+ default:
+ return state;
+ }
+}
const STATE_VARIANT: Record<
SkillState,
@@ -432,11 +440,11 @@ export function SkillsView() {
<ScrollArea className="flex-1">
<div className="space-y-3 p-4">
{isLoading && (
- <div className="text-sm text-muted-foreground">Lade Skills…</div>
+ <div className="text-sm text-muted-foreground">{t("skills_view.loading")}</div>
)}
{error && (
<div className="rounded-lg border border-destructive/40 bg-destructive/10 p-3 text-sm text-destructive">
- Konnte Skills nicht laden: {(error as Error).message}
+ {t("skills_view.load_error")}: {(error as Error).message}
</div>
)}
{searchActive ? (
@@ -484,7 +492,7 @@ export function SkillsView() {
<SkillDetailPanel name={selected} />
) : (
<div className="flex h-full items-center justify-center text-sm text-muted-foreground">
- Waehle einen Skill aus der Liste.
+ {t("skills_view.select_from_list")}
</div>
)}
</div>
@@ -939,7 +947,7 @@ function SkillDetailPanel({ name }: { name: string }) {
if (error) {
return (
<div className="p-6 text-sm text-destructive">
- Fehler: {(error as Error).message}
+ {t("common.error")}: {(error as Error).message}
</div>
);
}
@@ -955,7 +963,7 @@ function SkillDetailPanel({ name }: { name: string }) {
<div className="flex items-center gap-2">
<h2 className="truncate text-lg font-semibold">{data.name}</h2>
<Badge variant={STATE_VARIANT[data.state]}>
- {STATE_LABEL[data.state]}
+ {stateLabel(data.state)}
</Badge>
{data.is_builtin && (
<Badge variant="outline" className="gap-1">
@@ -993,14 +1001,14 @@ function SkillDetailPanel({ name }: { name: string }) {
disabled={!dirty || save.isPending}
>
<Save className="mr-1.5 h-3.5 w-3.5" />
- {save.isPending ? "Speichert…" : "Speichern"}
+ {save.isPending ? t("common.saving") : t("common.save")}
</Button>
</div>
</div>
{data.error && (
<div className="mt-3 rounded-md border border-destructive/40 bg-destructive/10 p-2.5 text-xs text-destructive">
- Validation-Fehler: {data.error}
+ {t("skills_view.validation_error")}: {data.error}
</div>
)}
{saveError && !showAdminDialog && (
@@ -1025,7 +1033,7 @@ function SkillDetailPanel({ name }: { name: string }) {
</span>
{data.is_builtin && (
<span className="text-[10px] text-muted-foreground">
- Builtin — Admin-Password zum Speichern noetig
+ {t("skills_view.builtin_admin_needed")}
</span>
)}
</div>
@@ -1100,16 +1108,18 @@ function AdminPassDialog({
setPassInput: (v: string) => void;
errorHint: string | null;
}) {
+ const t = useT();
return (
<div className="fixed inset-0 z-50 flex items-center justify-center bg-black/60">
<div className="w-[400px] rounded-lg border border-border bg-card p-6 shadow-xl">
<h3 className="flex items-center gap-2 text-base font-semibold">
<Lock className="h-4 w-4" />
- Admin-Password
+ {t("skills_view.admin_password")}
</h3>
<p className="mt-2 text-sm text-muted-foreground">
- Builtin-Skills sind geschuetzt. Gib das in <code>jarvis.toml</code> unter
- <code> [security]</code> gesetzte Admin-Password ein.
+ {t("skills_view.admin_password_hint_a")} <code>jarvis.toml</code>{" "}
+ {t("skills_view.admin_password_hint_b")}
+ <code> [security]</code>.
</p>
<input
type="password"
@@ -1128,14 +1138,14 @@ function AdminPassDialog({
)}
<div className="mt-5 flex justify-end gap-2">
<Button size="sm" variant="ghost" onClick={onCancel}>
- Abbrechen
+ {t("common.cancel")}
</Button>
<Button
size="sm"
disabled={!passInput}
onClick={() => onConfirm(passInput)}
>
- Entsperren
+ {t("skills_view.unlock")}
</Button>
</div>
</div>
@@ -1336,7 +1346,7 @@ function ResourceViewer({
</Button>
</div>
{isLoading && (
- <div className="p-4 text-xs text-muted-foreground">Laedt…</div>
+ <div className="p-4 text-xs text-muted-foreground">{t("skills_view.loading_skill")}</div>
)}
{error && (
<div className="p-4 text-xs text-destructive">
@@ -1355,15 +1365,17 @@ function ResourceViewer({
}
function EmptyList() {
+ const t = useT();
const assistantName = useEventStore((s) => s.assistantName);
return (
<div className="space-y-3 text-sm text-muted-foreground">
- <p>Noch keine Skills da.</p>
+ <p>{t("skills_view.empty_list_title")}</p>
<p className="text-xs">
- Beim ersten Start kopiert {assistantName} die Builtin-Skills nach
+ {t("skills_view.empty_list_body_a")} {assistantName}{" "}
+ {t("skills_view.empty_list_body_b")}
<br />
- <code>%LOCALAPPDATA%\Jarvis\skills</code>. Passiert das nicht, check
- die Backend-Logs.
+ <code>%LOCALAPPDATA%\Jarvis\skills</code>.{" "}
+ {t("skills_view.empty_list_body_c")}
</p>
</div>
);
@@ -1485,6 +1497,7 @@ function SearchResults({
selected: string | null;
onSelect: (name: string) => void;
}) {
+ const t = useT();
if (isPending && results.length === 0) {
return <div className="text-xs text-muted-foreground">Searching…</div>;
}
@@ -1498,7 +1511,7 @@ function SearchResults({
if (results.length === 0) {
return (
<div className="rounded-lg border border-border p-3 text-xs text-muted-foreground">
- Keine Treffer. Probier einen anderen Begriff oder entferne einen Filter.
+ {t("skills_view.search_no_hits")}
</div>
);
}
diff --git a/jarvis/ui/web/frontend/src/views/TasksView.tsx b/jarvis/ui/web/frontend/src/views/TasksView.tsx
index da0571825f..0ee50caca8 100644
--- a/jarvis/ui/web/frontend/src/views/TasksView.tsx
+++ b/jarvis/ui/web/frontend/src/views/TasksView.tsx
@@ -306,7 +306,7 @@ function TaskCard({
</div>
<div className="min-w-0 flex-1">
<div className="flex items-center gap-2">
- <h3 className="truncate text-sm font-semibold">{task.title || "(ohne Titel)"}</h3>
+ <h3 className="truncate text-sm font-semibold">{task.title || t("tasks_view.untitled")}</h3>
<Badge variant={STATE_VARIANT[task.state]}>{STATE_LABEL[task.state]}</Badge>
{task.attempts > 1 && (
<span className="text-[10px] font-mono text-muted-foreground">
@@ -357,6 +357,7 @@ function TaskCard({
}
function TaskDetailBody({ taskId }: { taskId: string }) {
+ const t = useT();
const { data, isLoading, error } = useQuery({
queryKey: ["tasks", "detail", taskId],
queryFn: () => fetchTask(taskId),
@@ -366,14 +367,14 @@ function TaskDetailBody({ taskId }: { taskId: string }) {
if (isLoading) {
return (
<div className="border-t border-border bg-background/30 px-5 py-3 text-xs text-muted-foreground">
- Lade Details…
+ {t("tasks_view.loading_details")}
</div>
);
}
if (error) {
return (
<div className="border-t border-border bg-destructive/10 px-5 py-3 text-xs text-destructive">
- Fehler: {(error as Error).message}
+ {t("common.error")}: {(error as Error).message}
</div>
);
}
@@ -399,7 +400,7 @@ function TaskDetailBody({ taskId }: { taskId: string }) {
Timeline ({steps.length})
</div>
{steps.length === 0 ? (
- <div className="text-xs text-muted-foreground">Noch keine Steps aufgezeichnet.</div>
+ <div className="text-xs text-muted-foreground">{t("tasks_view.no_steps")}</div>
) : (
<ul className="space-y-1.5">
{steps.map((s) => (
@@ -422,25 +423,27 @@ function TaskDetailBody({ taskId }: { taskId: string }) {
}
function TriggerWhen({ task }: { task: TaskSummary }) {
+ const t = useT();
const [tick, setTick] = useState(0);
useEffect(() => {
- const t = setInterval(() => setTick((x) => x + 1), 1000);
- return () => clearInterval(t);
+ const timer = setInterval(() => setTick((x) => x + 1), 1000);
+ return () => clearInterval(timer);
}, []);
const label = useMemo(() => {
- if (task.trigger_type === "on_event") return "wartet auf Event";
- if (task.state === "running") return "läuft gerade";
- if (task.finished_at_ns) return `fertig ${formatWhen(task.finished_at_ns)}`;
+ if (task.trigger_type === "on_event") return t("tasks_view.waiting_for_event");
+ if (task.state === "running") return t("tasks_view.running_now");
+ if (task.finished_at_ns)
+ return `${t("tasks_view.done_at")} ${formatWhen(task.finished_at_ns)}`;
if (task.due_at_ns) {
const delta = task.due_at_ns - Date.now() * 1e6;
- if (delta > 0) return `in ${formatDelta(delta)}`;
- return "fällig";
+ if (delta > 0) return `${t("tasks_view.in_prefix")} ${formatDelta(delta)}`;
+ return t("tasks_view.due_now");
}
return "—";
- // `tick` erzwingt Re-Render fuer den Countdown
+ // `tick` forces a re-render for the countdown
// eslint-disable-next-line react-hooks/exhaustive-deps
- }, [task, tick]);
+ }, [task, tick, t]);
return <span>{label}</span>;
}
diff --git a/jarvis/ui/web/frontend/src/views/WikiView.tsx b/jarvis/ui/web/frontend/src/views/WikiView.tsx
index e9c1aef711..a35a5daa11 100644
--- a/jarvis/ui/web/frontend/src/views/WikiView.tsx
+++ b/jarvis/ui/web/frontend/src/views/WikiView.tsx
@@ -19,6 +19,7 @@ import { useQuery } from "@tanstack/react-query";
import { ViewHeader } from "@/views/ChatsView";
import { cn } from "@/lib/utils";
+import { useT } from "@/i18n";
import { useEventStore } from "@/store/events";
import { fetchWikiTree } from "@/lib/wikiApi";
@@ -46,6 +47,7 @@ interface WikiToast {
}
export function WikiView(): JSX.Element {
+ const t = useT();
const [selectedSlug, setSelectedSlug] = useState<string | null>(null);
const [centreTab, setCentreTab] = useState<CentreTab>("graph");
const [toast, setToast] = useState<WikiToast | null>(null);
@@ -131,7 +133,7 @@ export function WikiView(): JSX.Element {
const handleSelect = useCallback(
(slug: string) => {
if (knownSlugs.size > 0 && !knownSlugs.has(slug)) {
- showToast("Page nicht gefunden");
+ showToast(t("wiki_view.page_not_found"));
return;
}
setSelectedSlug(slug);
@@ -142,10 +144,10 @@ export function WikiView(): JSX.Element {
);
const subtitle = treeQuery.isLoading
- ? "Lade Vault…"
+ ? t("wiki_view.loading_vault")
: totalPages === 0
- ? "Vault ist leer"
- : `${totalPages} Seiten · ${totalLinks} Wikilinks`;
+ ? t("wiki_view.vault_empty")
+ : `${totalPages} ${t("wiki_view.pages")} · ${totalLinks} ${t("wiki_view.wikilinks")}`;
return (
<div className="flex h-full min-h-0 flex-col" data-testid="wiki-view">
@@ -195,7 +197,7 @@ export function WikiView(): JSX.Element {
className="max-w-md rounded-md border border-destructive/40 bg-destructive/10 px-4 py-3 text-sm text-destructive"
data-testid="wiki-tree-error"
>
- Wiki-Daten konnten nicht geladen werden. Läuft der Backend-Server?
+ {t("wiki_view.load_error")}
</div>
</div>
) : !treeQuery.isLoading && totalPages === 0 ? (
@@ -250,7 +252,7 @@ export function WikiView(): JSX.Element {
className="px-7 py-10 text-center text-sm text-muted-foreground"
data-testid="wiki-page-no-selection"
>
- Wähle links eine Seite aus oder klick auf einen Knoten in der Memory Map.
+ {t("wiki_view.no_selection_hint")}
</div>
)}
</>
@@ -263,7 +265,7 @@ export function WikiView(): JSX.Element {
) : (
<aside className="flex h-full w-[380px] shrink-0 flex-col border-l border-border bg-card/40 p-4">
<div className="rounded-lg border border-border bg-secondary/30 p-4 text-xs text-muted-foreground">
- Backlinks erscheinen hier, sobald eine Seite ausgewählt ist.
+ {t("wiki_view.backlinks_hint")}
</div>
</aside>
)}
@@ -318,6 +320,7 @@ function TabButton({
}
function EmptyState() {
+ const t = useT();
const assistantName = useEventStore((s) => s.assistantName);
return (
<div className="flex flex-1 items-center justify-center p-6">
@@ -327,22 +330,21 @@ function EmptyState() {
>
<Notebook className="mx-auto mb-3 h-8 w-8 text-muted-foreground" />
<h3 className="mb-2 text-base font-semibold text-foreground">
- Dein Wiki ist noch leer.
+ {t("wiki_view.empty_title")}
</h3>
<p className="mb-2 text-sm text-muted-foreground">
- Sobald {assistantName} in einem Gespräch etwas Wichtiges aufschnappt, landet
- es hier — Personen, Projekte, Vorlieben, Termine.
+ {t("wiki_view.empty_body_a")} {assistantName} {t("wiki_view.empty_body_b")}
</p>
<p className="text-sm text-muted-foreground">
- Du kannst auch jederzeit selbst eine{" "}
+ {t("wiki_view.manual_a")}{" "}
<code className="rounded bg-background px-1 py-0.5 font-mono text-[12px]">
.md
</code>
- -Datei in{" "}
+ {t("wiki_view.manual_b")}{" "}
<code className="rounded bg-background px-1 py-0.5 font-mono text-[12px]">
wiki/obsidian-vault/entities/
</code>{" "}
- ablegen.
+ {t("wiki_view.manual_c")}
</p>
</div>
</div>
diff --git a/jarvis/ui/web/frontend/src/views/WorkflowsView.tsx b/jarvis/ui/web/frontend/src/views/WorkflowsView.tsx
index b25803cd19..367d70c55c 100644
--- a/jarvis/ui/web/frontend/src/views/WorkflowsView.tsx
+++ b/jarvis/ui/web/frontend/src/views/WorkflowsView.tsx
@@ -28,6 +28,7 @@ import { Button } from "@/components/ui/button";
import { Badge } from "@/components/ui/badge";
import { Switch } from "@/components/ui/switch";
import { cn } from "@/lib/utils";
+import { translate, useT } from "@/i18n";
import {
useDeleteWorkflow,
useIntegrations,
@@ -55,20 +56,34 @@ const STEP_ICON: Record<string, typeof Clock> = {
telegram_send: Send,
};
-const STEP_LABEL: Record<string, string> = {
- brain_prompt: "Brain",
- harness_dispatch: "Harness",
- speak: "Sprich",
- tool_call: "Tool",
- shell_cmd: "Shell",
- telegram_send: "Telegram",
-};
+// Most step labels are proper nouns / loanwords (Brain, Harness, Tool, Shell,
+// Telegram) and stay as-is across locales; only "speak" carries a translatable
+// verb, resolved through the one i18n accessor.
+function stepLabel(kind: string): string {
+ switch (kind) {
+ case "brain_prompt":
+ return "Brain";
+ case "harness_dispatch":
+ return "Harness";
+ case "speak":
+ return translate("workflows_view.step_speak");
+ case "tool_call":
+ return "Tool";
+ case "shell_cmd":
+ return "Shell";
+ case "telegram_send":
+ return "Telegram";
+ default:
+ return kind;
+ }
+}
// ---------------------------------------------------------------------
// View
// ---------------------------------------------------------------------
export function WorkflowsView() {
+ const t = useT();
const [expanded, setExpanded] = useState<Record<string, boolean>>({});
const { data, isLoading, error, refetch, isRefetching } = useWorkflows();
const { data: integrations } = useIntegrations();
@@ -81,7 +96,7 @@ export function WorkflowsView() {
<ViewHeader
icon={<Workflow className="h-4 w-4 text-primary" />}
title="Workflows"
- subtitle="Deine gehosteten AI-Agent-Pipelines — cron-getriggert oder auf Knopfdruck."
+ subtitle={t("workflows_view.subtitle")}
right={
<Button
size="sm"
@@ -103,12 +118,12 @@ export function WorkflowsView() {
<div className="space-y-3 p-6">
{isLoading && (
<div className="text-sm text-muted-foreground">
- Lade Workflows…
+ {t("workflows_view.loading")}
</div>
)}
{error && (
<div className="rounded-lg border border-destructive/40 bg-destructive/10 p-4 text-sm text-destructive">
- Workflows konnten nicht geladen werden: {(error as Error).message}
+ {t("workflows_view.load_failed")}: {(error as Error).message}
</div>
)}
{!isLoading && !error && workflows.length === 0 && (
@@ -139,6 +154,7 @@ function IntegrationsBanner({
}: {
integrations: IntegrationsResponse | undefined;
}) {
+ const t = useT();
const [dismissed, setDismissed] = useState(false);
if (!integrations || dismissed) return null;
@@ -147,12 +163,16 @@ function IntegrationsBanner({
if (!integrations.telegram.configured) {
let partial: string | undefined;
if (integrations.telegram.has_token && !integrations.telegram.has_chat_id) {
- partial = "Token ✓ — Chat-ID fehlt";
+ partial = `${t("workflows_view.partial_token_ok")} — ${t(
+ "workflows_view.partial_chat_id_missing",
+ )}`;
} else if (
!integrations.telegram.has_token &&
integrations.telegram.has_chat_id
) {
- partial = "Chat-ID ✓ — Token fehlt";
+ partial = `${t("workflows_view.partial_chat_id_ok")} — ${t(
+ "workflows_view.partial_token_missing",
+ )}`;
}
issues.push({
name: "Telegram",
@@ -175,7 +195,7 @@ function IntegrationsBanner({
<Info className="mt-0.5 h-4 w-4 shrink-0 text-primary" />
<div className="flex-1 min-w-0">
<div className="text-xs font-semibold text-foreground">
- Integrationen brauchen Setup ({issues.length})
+ {t("workflows_view.integrations_need_setup")} ({issues.length})
</div>
<ul className="mt-1 space-y-1.5 text-[11px] text-muted-foreground">
{issues.map((iss) => (
@@ -197,7 +217,7 @@ function IntegrationsBanner({
type="button"
onClick={() => setDismissed(true)}
className="text-xs text-muted-foreground hover:text-foreground"
- aria-label="Banner schließen"
+ aria-label={t("workflows_view.dismiss_banner")}
>
×
</button>
@@ -220,6 +240,7 @@ function DashboardStats({
next_run_at_ns: number | null;
};
}) {
+ const t = useT();
const [tick, setTick] = useState(0);
useEffect(() => {
const id = setInterval(() => setTick((x) => x + 1), 1000);
@@ -240,7 +261,7 @@ function DashboardStats({
/>
<StatBadge
icon={<Power className="h-3.5 w-3.5 text-emerald-400" />}
- label="Aktiv"
+ label={t("workflows_view.stat_active")}
value={String(summary?.enabled ?? 0)}
/>
<StatBadge
@@ -250,7 +271,7 @@ function DashboardStats({
/>
<StatBadge
icon={<Clock className="h-3.5 w-3.5 text-muted-foreground" />}
- label="Nächster Lauf"
+ label={t("workflows_view.stat_next_run")}
value={nextRunLabel}
/>
</div>
@@ -292,6 +313,7 @@ function WorkflowCard({
isExpanded: boolean;
onToggleExpand: () => void;
}) {
+ const t = useT();
const runMut = useRunWorkflow();
const toggleMut = useToggleWorkflow();
const deleteMut = useDeleteWorkflow();
@@ -307,14 +329,14 @@ function WorkflowCard({
// Seed) schlaegt dann mit "URL leer" fehl, was akzeptabel ist als MVP.
let input: Record<string, unknown> = {};
if (workflow.name.toLowerCase().includes("url")) {
- const url = window.prompt("URL zum Zusammenfassen:", "https://");
+ const url = window.prompt(t("workflows_view.url_to_summarize"), "https://");
if (url === null) return;
input = { url };
}
try {
await runMut.mutateAsync({ id: workflow.id, input });
} catch (exc) {
- window.alert(`Run fehlgeschlagen: ${(exc as Error).message}`);
+ window.alert(`${t("workflows_view.run_failed")}: ${(exc as Error).message}`);
}
};
@@ -330,7 +352,7 @@ function WorkflowCard({
type="button"
onClick={onToggleExpand}
className="mt-0.5 rounded-md p-1 text-muted-foreground transition-colors hover:bg-background/60 hover:text-foreground"
- aria-label={isExpanded ? "Einklappen" : "Ausklappen"}
+ aria-label={isExpanded ? t("workflows_view.collapse") : t("workflows_view.expand")}
>
{isExpanded ? (
<ChevronDown className="h-4 w-4" />
@@ -355,7 +377,7 @@ function WorkflowCard({
)}
</div>
<p className="mt-1 line-clamp-2 text-xs text-muted-foreground">
- {workflow.description || "Keine Beschreibung."}
+ {workflow.description || t("workflows_view.no_description")}
</p>
<div className="mt-2 flex flex-wrap items-center gap-2 text-[11px] text-muted-foreground">
<span>
@@ -378,14 +400,14 @@ function WorkflowCard({
toggleMut.mutate({ id: workflow.id, enabled: v })
}
disabled={toggleMut.isPending}
- aria-label={workflow.enabled ? "Deaktivieren" : "Aktivieren"}
+ aria-label={workflow.enabled ? t("workflows_view.deactivate") : t("workflows_view.activate")}
/>
<Button
size="sm"
variant="ghost"
onClick={handleRun}
disabled={isRunning}
- title="Jetzt ausführen"
+ title={t("workflows_view.run_now")}
>
{isRunning ? (
<Loader2 className="h-4 w-4 animate-spin" />
@@ -399,13 +421,17 @@ function WorkflowCard({
variant="ghost"
onClick={() => {
if (
- window.confirm(`Workflow "${workflow.name}" wirklich löschen?`)
+ window.confirm(
+ `${t("workflows_view.delete_confirm_prefix")} "${workflow.name}" ${t(
+ "workflows_view.delete_confirm_suffix",
+ )}`,
+ )
) {
deleteMut.mutate(workflow.id);
}
}}
disabled={deleteMut.isPending}
- title="Löschen"
+ title={t("common.delete")}
>
<Trash2 className="h-4 w-4" />
</Button>
@@ -423,19 +449,20 @@ function WorkflowCard({
// ---------------------------------------------------------------------
function WorkflowDetailBody({ workflowId }: { workflowId: string }) {
+ const t = useT();
const { data, isLoading, error } = useWorkflowDetail(workflowId);
if (isLoading) {
return (
<div className="border-t border-border bg-background/30 px-5 py-3 text-xs text-muted-foreground">
- Lade Details…
+ {t("workflows_view.loading_details")}
</div>
);
}
if (error) {
return (
<div className="border-t border-border bg-destructive/10 px-5 py-3 text-xs text-destructive">
- Fehler: {(error as Error).message}
+ {t("workflows_view.error_label")}: {(error as Error).message}
</div>
);
}
@@ -458,8 +485,7 @@ function WorkflowDetailBody({ workflowId }: { workflowId: string }) {
const label =
s.label ||
(s.prompt ? s.prompt.slice(0, 80) : s.text?.slice(0, 80)) ||
- STEP_LABEL[s.kind] ||
- s.kind;
+ stepLabel(s.kind);
return (
<li
key={idx}
@@ -470,7 +496,7 @@ function WorkflowDetailBody({ workflowId }: { workflowId: string }) {
</span>
<Icon className="h-3.5 w-3.5 shrink-0 text-primary" />
<span className="w-20 text-primary">
- {STEP_LABEL[s.kind] ?? s.kind}
+ {stepLabel(s.kind)}
</span>
<span className="flex-1 truncate text-muted-foreground">
{label}
@@ -483,11 +509,11 @@ function WorkflowDetailBody({ workflowId }: { workflowId: string }) {
<div>
<div className="mb-2 text-[10px] uppercase tracking-wider text-muted-foreground">
- Letzte Runs ({data.recent_runs.length})
+ {t("workflows_view.recent_runs")} ({data.recent_runs.length})
</div>
{data.recent_runs.length === 0 ? (
<div className="text-xs text-muted-foreground">
- Noch nie ausgeführt.
+ {t("workflows_view.never_run")}
</div>
) : (
<div className="space-y-2">
@@ -538,11 +564,12 @@ function RunRow({ run }: { run: WorkflowRun }) {
}
function RunStepsDetail({ runId }: { runId: string }) {
+ const t = useT();
const { data, isLoading } = useRunDetail(runId);
if (isLoading) {
return (
<div className="border-t border-border/60 p-2 text-[11px] text-muted-foreground">
- Lade Run-Details…
+ {t("workflows_view.loading_run_details")}
</div>
);
}
@@ -632,14 +659,15 @@ function NextRunLabel({ ns }: { ns: number | null }) {
}
function EmptyState() {
+ const t = useT();
return (
<div className="flex flex-col items-center justify-center gap-2 rounded-lg border border-dashed border-border/60 bg-background/30 p-10 text-center">
<Workflow className="h-7 w-7 text-muted-foreground/50" />
<p className="text-sm text-muted-foreground">
- Noch keine Workflows — beim ersten Start werden 3 Beispiele geseedet.
+ {t("workflows_view.empty_title")}
</p>
<p className="text-xs text-muted-foreground/60">
- Ist das Backend frisch? Schau in <code>data/workflows.sqlite</code>.
+ {t("workflows_view.empty_hint_pre")} <code>data/workflows.sqlite</code>.
</p>
</div>
);
@@ -651,14 +679,14 @@ function EmptyState() {
function formatFutureDelta(ns: number): string {
const delta = ns - Date.now() * 1e6;
- if (delta <= 0) return "jetzt";
+ if (delta <= 0) return translate("workflows_view.now");
return formatDelta(delta);
}
function formatPastDelta(ns: number): string {
const delta = Date.now() * 1e6 - ns;
- if (delta <= 0) return "jetzt";
- return formatDelta(delta) + " her";
+ if (delta <= 0) return translate("workflows_view.now");
+ return `${formatDelta(delta)} ${translate("workflows_view.ago_suffix")}`;
}
function formatDelta(ns: number): string {
diff --git a/jarvis/ui/web/frontend/src/views/friends/ChatTab.tsx b/jarvis/ui/web/frontend/src/views/friends/ChatTab.tsx
index a4e9cacbd8..c589475f63 100644
--- a/jarvis/ui/web/frontend/src/views/friends/ChatTab.tsx
+++ b/jarvis/ui/web/frontend/src/views/friends/ChatTab.tsx
@@ -4,6 +4,7 @@ import { Loader2 } from "lucide-react";
import { ChatThread } from "@/components/friends/ChatThread";
import { FriendListItem } from "@/components/friends/FriendListItem";
import { useFriend, useFriends } from "@/hooks/useFriends";
+import { useT } from "@/i18n";
/**
* Master-Detail-Layout fuer den Chat-Tab.
@@ -11,6 +12,7 @@ import { useFriend, useFriends } from "@/hooks/useFriends";
* Rechts: ChatThread fuer den ausgewaehlten Friend
*/
export function ChatTab() {
+ const t = useT();
const friends = useFriends();
const [selectedId, setSelectedId] = useState<string | null>(null);
const detail = useFriend(selectedId);
@@ -26,19 +28,19 @@ export function ChatTab() {
<aside className="flex w-72 flex-shrink-0 flex-col rounded-xl border border-border bg-card/30 p-2">
{friends.isLoading && (
<div className="flex items-center justify-center py-6 text-sm text-muted-foreground">
- <Loader2 className="mr-2 h-4 w-4 animate-spin" /> Friends laden ...
+ <Loader2 className="mr-2 h-4 w-4 animate-spin" /> {t("chat_tab.loading_friends")}
</div>
)}
{friends.isError && (
<div className="rounded-md border border-destructive/40 bg-destructive/10 px-3 py-2 text-xs text-destructive">
- Friends konnten nicht geladen werden:{" "}
+ {t("chat_tab.load_failed")}{" "}
{(friends.error as Error).message}
</div>
)}
{friends.data && friends.data.length === 0 && (
<div className="rounded-md border border-dashed border-border/60 px-3 py-4 text-center text-xs text-muted-foreground">
- Noch keine Friends. Klick oben rechts auf{" "}
- <strong>+ Friend hinzufuegen</strong>.
+ {t("chat_tab.empty_hint")}{" "}
+ <strong>{t("chat_tab.add_friend")}</strong>.
</div>
)}
<div className="mt-1 flex-1 space-y-1 overflow-y-auto scrollbar-jarvis pr-1">
@@ -56,12 +58,12 @@ export function ChatTab() {
<section className="flex-1 min-w-0 rounded-xl border border-border bg-card/20">
{selectedId === null && (
<div className="flex h-full items-center justify-center text-sm text-muted-foreground">
- Waehle einen Friend aus der Liste links.
+ {t("chat_tab.select_hint")}
</div>
)}
{selectedId !== null && detail.isLoading && (
<div className="flex h-full items-center justify-center text-sm text-muted-foreground">
- <Loader2 className="mr-2 h-4 w-4 animate-spin" /> Lade ...
+ <Loader2 className="mr-2 h-4 w-4 animate-spin" /> {t("common.loading")}
</div>
)}
{selectedId !== null && detail.data && (
diff --git a/jarvis/ui/web/frontend/src/views/friends/StatusTab.tsx b/jarvis/ui/web/frontend/src/views/friends/StatusTab.tsx
index a39ab0898a..2ae3eb58df 100644
--- a/jarvis/ui/web/frontend/src/views/friends/StatusTab.tsx
+++ b/jarvis/ui/web/frontend/src/views/friends/StatusTab.tsx
@@ -1,6 +1,7 @@
// === F-FRIENDS [F4] · feature/friends-section · ruben-2026-05-01 ===
import { Loader2, Radio, ShieldAlert } from "lucide-react";
import { useEventStore } from "@/store/events";
+import { useT } from "@/i18n";
import { PermissionMatrix } from "@/components/friends/PermissionMatrix";
import {
@@ -22,6 +23,7 @@ import {
* Memory-Updates verlassen die Maschine NIE — egal welches Profile aktiv ist.
*/
export function StatusTab() {
+ const t = useT();
const assistantName = useEventStore((s) => s.assistantName);
const friends = useFriends();
@@ -30,12 +32,12 @@ export function StatusTab() {
<div className="rounded-xl border border-border bg-card/30 p-5">
<div className="flex items-center gap-2 font-display text-sm font-semibold text-foreground">
<Radio className="h-4 w-4 text-primary" />
- Status-Sharing
+ {t("status_tab.heading")}
</div>
<p className="mt-2 text-xs text-muted-foreground">
- Du entscheidest pro Friend, wie viel von deinem {assistantName}-Status
- ausgespielt wird. Privacy-First: Default ist <strong>minimal</strong>{" "}
- (nur online/offline), Aenderungen wirken sofort.
+ {t("status_tab.intro_part1")} {assistantName}{" "}
+ {t("status_tab.intro_part2")} <strong>minimal</strong>{" "}
+ {t("status_tab.intro_part3")}
</p>
</div>
@@ -43,21 +45,21 @@ export function StatusTab() {
{friends.isLoading && (
<div className="flex items-center justify-center rounded-md border border-border bg-card/20 py-6 text-sm text-muted-foreground">
- <Loader2 className="mr-2 h-4 w-4 animate-spin" /> Friends laden ...
+ <Loader2 className="mr-2 h-4 w-4 animate-spin" /> {t("status_tab.loading_permission")}
</div>
)}
{friends.isError && (
<div className="rounded-md border border-destructive/40 bg-destructive/10 px-3 py-2 text-xs text-destructive">
- Friends konnten nicht geladen werden:{" "}
+ {t("status_tab.error_prefix")}:{" "}
{(friends.error as Error).message}
</div>
)}
{friends.data && friends.data.length === 0 && (
<div className="rounded-md border border-dashed border-border/60 px-3 py-4 text-center text-xs text-muted-foreground">
- Noch keine Friends. Wechsle auf den Chat-Tab und klicke{" "}
- <strong>+ Friend hinzufuegen</strong>.
+ {t("status_tab.empty_hint")}{" "}
+ <strong>{t("add_friend_menu.title")}</strong>.
</div>
)}
@@ -72,12 +74,10 @@ export function StatusTab() {
<div className="rounded-md border border-amber-400/40 bg-amber-400/10 px-4 py-3 text-[11px] text-amber-100">
<div className="flex items-center gap-2 font-display text-xs font-semibold text-amber-300">
<ShieldAlert className="h-3.5 w-3.5" />
- Hard-Blacklist (immer blockiert)
+ {t("status_tab.hard_blacklist_title")}
</div>
<p className="mt-1 text-amber-100/90">
- Rohe Utterances, Tool-Args, Stacktraces, Memory-Updates,
- Window-Titles. Diese verlassen deine Maschine NIE - egal welches
- Profile aktiv ist und egal was eine Custom-Whitelist sagt.
+ {t("status_tab.hard_blacklist_body")}
</p>
</div>
</div>
@@ -85,6 +85,7 @@ export function StatusTab() {
}
function FriendPermissionRow({ friend }: { friend: FriendItem }) {
+ const t = useT();
const permission = useFriendPermission(friend.id);
const update = useUpdatePermission();
@@ -111,12 +112,12 @@ function FriendPermissionRow({ friend }: { friend: FriendItem }) {
</span>
{update.isPending && (
<span className="flex items-center gap-1 text-[10px] text-muted-foreground">
- <Loader2 className="h-3 w-3 animate-spin" /> speichern ...
+ <Loader2 className="h-3 w-3 animate-spin" /> {t("common.saving")}
</span>
)}
{update.isError && (
<span className="text-[10px] text-destructive">
- Fehler: {(update.error as Error).message}
+ {t("status_tab.error_prefix")}: {(update.error as Error).message}
</span>
)}
</div>
@@ -132,7 +133,7 @@ function FriendPermissionRow({ friend }: { friend: FriendItem }) {
{permission.isLoading ? (
<div className="flex items-center text-[11px] text-muted-foreground">
<Loader2 className="mr-1.5 h-3 w-3 animate-spin" />
- Permission laden ...
+ {t("status_tab.loading_permission")}
</div>
) : (
<PermissionMatrix
@@ -148,23 +149,24 @@ function FriendPermissionRow({ friend }: { friend: FriendItem }) {
}
function ProfileLegend() {
+ const t = useT();
return (
<div className="grid gap-3 sm:grid-cols-3">
<ProfileCard
name="minimal"
- subline="Nur online/offline"
- description="Friend sieht: Voice-Session aktiv ja/nein, Dauer. Keine Inhalte."
+ subline={t("status_tab.profile_minimal_subline")}
+ description={t("status_tab.profile_minimal_desc")}
isDefault
/>
<ProfileCard
name="standard"
- subline="+ Mission-Titel"
- description="Friend sieht zusaetzlich: Welche Missions/Tasks gerade laufen, Erfolg, Dauer."
+ subline={t("status_tab.profile_standard_subline")}
+ description={t("status_tab.profile_standard_desc")}
/>
<ProfileCard
name="detailed"
- subline="+ OpenClaw-Summary"
- description="Friend sieht zusaetzlich: Signierte OpenClaw-Summaries (KEINE Utterances)."
+ subline={t("status_tab.profile_detailed_subline")}
+ description={t("status_tab.profile_detailed_desc")}
/>
</div>
);
diff --git a/jarvis/ui/web/frontend/src/views/settings/OverlayTaskbarGroup.test.tsx b/jarvis/ui/web/frontend/src/views/settings/OverlayTaskbarGroup.test.tsx
index 5d0359873b..6b12674a81 100644
--- a/jarvis/ui/web/frontend/src/views/settings/OverlayTaskbarGroup.test.tsx
+++ b/jarvis/ui/web/frontend/src/views/settings/OverlayTaskbarGroup.test.tsx
@@ -1,4 +1,4 @@
-import { cleanup, render, screen } from "@testing-library/react";
+import { cleanup, fireEvent, render, screen } from "@testing-library/react";
import { afterEach, describe, expect, it, vi } from "vitest";
// Identity translator so assertions can match exact i18n keys.
@@ -32,11 +32,17 @@ vi.mock("@/hooks/useBarPersistent", () => ({
vi.mock("@/hooks/useMuteMusic", () => ({
useMuteMusic: () => ({ enabled: false, loading: false, setEnabled: vi.fn() }),
}));
+const setSoundEffects = vi.fn().mockResolvedValue({ ok: true, enabled: false });
+vi.mock("@/hooks/useSoundEffects", () => ({
+ useSoundEffects: () => ({
+ enabled: true,
+ loading: false,
+ setEnabled: setSoundEffects,
+ }),
+}));
-import {
- OverlayTaskbarGroup,
- NonePreview,
-} from "@/views/settings/OverlayTaskbarGroup";
+import { OverlayTaskbarGroup } from "@/views/settings/OverlayTaskbarGroup";
+import { NonePreview } from "@/components/overlay/OverlayStylePreviews";
afterEach(() => {
cleanup();
@@ -53,11 +59,20 @@ describe("OverlayTaskbarGroup", () => {
expect(screen.getByText("taskbar_view.behavior_title")).toBeDefined();
});
- it("renders the overlay-style panel and both dictation toggles", () => {
+ it("renders the overlay-style panel and all three behavior toggles", () => {
render(<OverlayTaskbarGroup />);
expect(screen.getByText("settings_view.overlay_style.title")).toBeDefined();
expect(screen.getByText("taskbar_view.bar_persistent.title")).toBeDefined();
expect(screen.getByText("taskbar_view.mute_music.title")).toBeDefined();
+ expect(screen.getByText("taskbar_view.sound_effects.title")).toBeDefined();
+ });
+
+ it("toggling the sound-effects switch calls the hook with the new value", () => {
+ render(<OverlayTaskbarGroup />);
+ // Behavior block order: bar_persistent, mute_music, sound_effects.
+ const switches = screen.getAllByRole("switch");
+ fireEvent.click(switches[switches.length - 1]);
+ expect(setSoundEffects).toHaveBeenCalledWith(false);
});
it("offers the three overlay-style options", () => {
diff --git a/jarvis/ui/web/frontend/src/views/settings/OverlayTaskbarGroup.tsx b/jarvis/ui/web/frontend/src/views/settings/OverlayTaskbarGroup.tsx
index 6ee830be06..37d31cd851 100644
--- a/jarvis/ui/web/frontend/src/views/settings/OverlayTaskbarGroup.tsx
+++ b/jarvis/ui/web/frontend/src/views/settings/OverlayTaskbarGroup.tsx
@@ -1,10 +1,11 @@
import { useEffect, useState } from "react";
-import { Monitor, Eye, Volume2 } from "lucide-react";
+import { Monitor, Eye, Volume2, Bell } from "lucide-react";
import { Switch } from "@/components/ui/switch";
-import { MascotGigi } from "@/components/MascotGigi";
import { useOverlayStyle, type OverlayStyle } from "@/hooks/useOverlayStyle";
+import { StylePreview } from "@/components/overlay/OverlayStylePreviews";
import { useBarPersistent } from "@/hooks/useBarPersistent";
import { useMuteMusic } from "@/hooks/useMuteMusic";
+import { useSoundEffects } from "@/hooks/useSoundEffects";
import { useEventStore } from "@/store/events";
import { useT } from "@/i18n";
import { cn } from "@/lib/utils";
@@ -40,6 +41,8 @@ export function OverlayTaskbarGroup() {
<BarPersistentRow />
<div className="mx-4 border-t border-border/60" />
<MuteMusicRow />
+ <div className="mx-4 border-t border-border/60" />
+ <SoundEffectsRow />
</div>
</section>
</div>
@@ -144,6 +147,41 @@ function MuteMusicRow() {
);
}
+function SoundEffectsRow() {
+ const t = useT();
+ const { enabled, loading, setEnabled } = useSoundEffects();
+ const pushToast = useEventStore((s) => s.pushToast);
+ const [saving, setSaving] = useState(false);
+
+ async function onToggle(next: boolean) {
+ setSaving(true);
+ try {
+ await setEnabled(next);
+ pushToast(
+ "success",
+ next
+ ? t("taskbar_view.sound_effects.enabled_toast")
+ : t("taskbar_view.sound_effects.disabled_toast"),
+ );
+ } catch (e) {
+ pushToast("error", (e as Error).message);
+ } finally {
+ setSaving(false);
+ }
+ }
+
+ return (
+ <ToggleRow
+ icon={Bell}
+ title={t("taskbar_view.sound_effects.title")}
+ description={t("taskbar_view.sound_effects.description")}
+ checked={enabled ?? true}
+ disabled={loading || saving}
+ onToggle={onToggle}
+ />
+ );
+}
+
/**
* On-screen overlay style selector (Bar / Mascot / None). Reuses the
* settings_view.overlay_style.* i18n. A bar <-> mascot switch cannot apply live
@@ -287,63 +325,3 @@ function OverlayStylePanel() {
</div>
);
}
-
-/** Visual preview for each overlay style (mascot reuses the real Gigi SVG). */
-function StylePreview({ style }: { style: OverlayStyle }) {
- if (style === "mascot") {
- return <MascotGigi size={46} reactToVoice={false} enableComments={false} />;
- }
- if (style === "whisper_bar") return <BarPreview />;
- return <NonePreview />;
-}
-
-function BarPreview() {
- const heights = [6, 11, 15, 8, 14, 9, 7];
- return (
- <svg viewBox="0 0 100 40" className="w-20" aria-hidden="true">
- <rect
- x="6"
- y="11"
- width="88"
- height="18"
- rx="9"
- fill="#0e0d0c"
- stroke="#d7b669"
- strokeWidth="1.6"
- />
- {heights.map((h, i) => (
- <rect
- key={i}
- x={24 + i * 8}
- y={20 - h / 2}
- width="3"
- height={h}
- rx="1.5"
- fill="#e7c46e"
- />
- ))}
- </svg>
- );
-}
-
-export function NonePreview() {
- return (
- <svg viewBox="0 0 100 40" className="w-20 opacity-50" aria-hidden="true">
- <rect
- x="6"
- y="11"
- width="88"
- height="18"
- rx="9"
- fill="none"
- stroke="#7c766b"
- strokeWidth="1.6"
- strokeDasharray="4 3"
- />
- {/* Diagonal "disabled" strike — kept inside the dashed box (y 11..29)
- and symmetric about its centre (50, 20) so it never juts out as a
- stub above/below the pill. */}
- <line x1="25" y1="25" x2="75" y2="15" stroke="#7c766b" strokeWidth="1.6" strokeLinecap="round" />
- </svg>
- );
-}
diff --git a/jarvis/ui/web/frontend/src/views/settings/TeamProxyGroup.tsx b/jarvis/ui/web/frontend/src/views/settings/TeamProxyGroup.tsx
index 1b1440fa54..7574dd9913 100644
--- a/jarvis/ui/web/frontend/src/views/settings/TeamProxyGroup.tsx
+++ b/jarvis/ui/web/frontend/src/views/settings/TeamProxyGroup.tsx
@@ -13,7 +13,6 @@ const PROXIABLE_PROVIDERS = [
"claude-api",
"openai",
"openrouter",
- "grok",
"gemini",
"groq-api",
] as const;
diff --git a/jarvis/ui/web/frontend/src/views/settings/WikiProviderCard.test.tsx b/jarvis/ui/web/frontend/src/views/settings/WikiProviderCard.test.tsx
index 2a6e7ffda4..71d7bc8355 100644
--- a/jarvis/ui/web/frontend/src/views/settings/WikiProviderCard.test.tsx
+++ b/jarvis/ui/web/frontend/src/views/settings/WikiProviderCard.test.tsx
@@ -21,7 +21,7 @@ const INITIAL = {
model: "",
available: [
{ provider: "gemini", models: ["gemini-3-flash-preview", "gemini-3.1-pro-preview"] },
- { provider: "grok", models: ["grok-4.3"] },
+ { provider: "openai", models: ["gpt-5.5"] },
],
};
@@ -72,15 +72,15 @@ describe("WikiProviderCard", () => {
// "Same as brain" provider → only the cheap-default model option.
expect(within(modelSelect).queryByText("gemini-3-flash-preview")).toBeNull();
- // Picking gemini surfaces gemini's models; grok's stay hidden.
+ // Picking gemini surfaces gemini's models; openai's stay hidden.
fireEvent.change(providerSelect, { target: { value: "gemini" } });
expect(within(modelSelect).getByText("gemini-3-flash-preview")).toBeDefined();
expect(within(modelSelect).getByText("gemini-3.1-pro-preview")).toBeDefined();
- expect(within(modelSelect).queryByText("grok-4.3")).toBeNull();
+ expect(within(modelSelect).queryByText("gpt-5.5")).toBeNull();
- // Switching to grok swaps the model options.
- fireEvent.change(providerSelect, { target: { value: "grok" } });
- expect(within(modelSelect).getByText("grok-4.3")).toBeDefined();
+ // Switching to openai swaps the model options.
+ fireEvent.change(providerSelect, { target: { value: "openai" } });
+ expect(within(modelSelect).getByText("gpt-5.5")).toBeDefined();
expect(within(modelSelect).queryByText("gemini-3-flash-preview")).toBeNull();
});
diff --git a/jarvis/ui/web/frontend/src/views/sub-agents/ToolsCanvas.tsx b/jarvis/ui/web/frontend/src/views/sub-agents/ToolsCanvas.tsx
index af43192903..34a65c372e 100644
--- a/jarvis/ui/web/frontend/src/views/sub-agents/ToolsCanvas.tsx
+++ b/jarvis/ui/web/frontend/src/views/sub-agents/ToolsCanvas.tsx
@@ -25,6 +25,7 @@ import { ArrowLeft, Brain, Sparkles } from "lucide-react";
import { useCallback, useEffect, useMemo, useState } from "react";
import { ScrollArea } from "@/components/ui/scroll-area";
+import { useT } from "@/i18n";
import type { SubAgentNode, ToolCallEntry } from "@/store/subAgents";
import { getToolAppearance, type ToolAppearance } from "./tool-icons";
@@ -99,6 +100,7 @@ export function ToolsCanvas({
agent: SubAgentNode;
onBack: () => void;
}) {
+ const t = useT();
const toolCalls = agent.tool_calls;
// Layout: Tools in einem Grid, bis zu 4 pro Zeile.
@@ -181,10 +183,10 @@ export function ToolsCanvas({
<button
onClick={onBack}
className="text-zinc-400 hover:text-zinc-100 p-1.5 rounded hover:bg-zinc-800 flex items-center gap-1.5 text-xs"
- title="Zurück zur Agents-Übersicht"
+ title={t("tools_canvas.back_tooltip")}
>
<ArrowLeft className="h-4 w-4" />
- Zurück
+ {t("common.back")}
</button>
<div className="h-6 w-px bg-zinc-800" />
<div className="flex items-center gap-2 min-w-0">
@@ -194,7 +196,8 @@ export function ToolsCanvas({
{agent.name}
</div>
<div className="text-[11px] text-zinc-500 truncate">
- {toolCalls.length} Tool-Calls · {runningCount} aktiv
+ {toolCalls.length} {t("tools_canvas.tool_calls")} · {runningCount}{" "}
+ {t("tools_canvas.active")}
{agent.utterance && <> · „{agent.utterance}"</>}
</div>
</div>
@@ -264,6 +267,7 @@ function ToolDetailSheet({
appearance: ToolAppearance;
onClose: () => void;
}) {
+ const t = useT();
const { Icon } = appearance;
return (
<motion.div
@@ -293,16 +297,19 @@ function ToolDetailSheet({
onClick={onClose}
className="text-zinc-400 hover:text-zinc-100 text-xs px-2 py-1 rounded hover:bg-zinc-800"
>
- schließen
+ {t("common.close")}
</button>
</header>
<ScrollArea className="flex-1">
<div className="p-4 text-xs text-zinc-300 space-y-3">
<div className="flex flex-wrap gap-3">
- <KV label="Status" value={tool.status} />
+ <KV label={t("common.status")} value={tool.status} />
{tool.duration_ms !== undefined && (
- <KV label="Dauer" value={`${(tool.duration_ms / 1000).toFixed(2)}s`} />
+ <KV
+ label={t("tools_canvas.duration")}
+ value={`${(tool.duration_ms / 1000).toFixed(2)}s`}
+ />
)}
</div>
@@ -311,7 +318,7 @@ function ToolDetailSheet({
Arguments
</div>
<pre className="rounded bg-zinc-800/60 p-2 text-[11px] whitespace-pre-wrap text-zinc-200 break-all">
- {tool.args_preview || "(leer)"}
+ {tool.args_preview || t("tools_canvas.empty")}
</pre>
</div>
@@ -347,17 +354,17 @@ function KV({ label, value }: { label: string; value: string }) {
}
function EmptyTools({ agentName }: { agentName: string }) {
+ const t = useT();
return (
<div className="h-full flex flex-col items-center justify-center text-center px-8 gap-3">
<div className="rounded-full bg-zinc-900 border border-zinc-800 p-4">
<Sparkles className="h-8 w-8 text-violet-400" />
</div>
<h2 className="text-base font-medium text-zinc-100">
- {agentName} hat noch keine Tools aufgerufen.
+ {agentName} {t("tools_canvas.no_tools_yet")}
</h2>
<p className="max-w-md text-sm text-zinc-500">
- Sobald der OpenClaw-Worker ein Tool triggert (z.&nbsp;B. dispatch_to_harness,
- run_shell, screenshot), erscheint es hier als Icon-Node.
+ {t("tools_canvas.no_tools_explainer")}
</p>
</div>
);
diff --git a/jarvis/ui/web/provider_routes.py b/jarvis/ui/web/provider_routes.py
index 16ad5bb6f0..9614302c31 100644
--- a/jarvis/ui/web/provider_routes.py
+++ b/jarvis/ui/web/provider_routes.py
@@ -156,6 +156,25 @@ class BrainModelSaveResponse(BaseModel):
probe: BrainModelProbe | None = None
+# Phase 3: selectable Computer-Use model per provider. CU runs on the provider's
+# main ``model`` by default; a pinned ``cu_model`` lets the user run CU on a
+# different (e.g. stronger) model than chat. ``cu_model == ""`` means "use my
+# main model". Separate from the model endpoints so those stay untouched.
+class CuModelBody(BaseModel):
+ cu_model: str = Field(default="", max_length=200) # "" -> use the main model
+ persist: bool = Field(default=True)
+
+
+class CuModelResponse(BaseModel):
+ ok: bool = True
+ provider: str
+ cu_model: str # the pinned value ("" = use the main model)
+ effective_model: str # the model Computer-Use would actually run
+ uses_main: bool # True when nothing is pinned (effective == main model)
+ persisted: bool = False
+ restart_required: bool = False
+
+
# ----------------------------------------------------------------------
# Helper
# ----------------------------------------------------------------------
@@ -268,6 +287,10 @@ def _spec_to_payload(
"credential_help": spec.credential_help,
"signup_url": spec.signup_url,
"billing": provider_billing(spec),
+ # Maintainer-recommended pick for this tier (UI badge) + the model it
+ # points at. Presentation only — never gates behavior (AP-21).
+ "recommended": spec.recommended,
+ "recommended_model": spec.recommended_model,
# Gemini's AI-Studio-vs-Vertex split; None for single-path providers.
"alt_credential": (
{
@@ -502,6 +525,30 @@ def _current_brain_model(cfg: Any, provider: str) -> str:
return model or get_tier_default_model("router", provider) or ""
+def _provider_cu_model(cfg: Any, provider: str) -> str:
+ """The pinned Computer-Use model for ``provider`` ("" when none is set)."""
+ providers = getattr(getattr(cfg, "brain", None), "providers", None)
+ pc = providers.get(provider) if isinstance(providers, dict) else None
+ return (getattr(pc, "cu_model", None) or "") if pc is not None else ""
+
+
+def _set_cu_model_in_memory(cfg: Any, provider: str, value: str) -> None:
+ """Update ``cfg.brain.providers[provider].cu_model`` live so the next CU
+ mission uses it without a restart (the loop reads cfg fresh each mission).
+ Best-effort: a frozen/detached cfg is not an error."""
+ try:
+ providers = cfg.brain.providers
+ pc = providers.get(provider)
+ if pc is None:
+ from jarvis.core.config import BrainProviderConfig
+
+ pc = BrainProviderConfig()
+ providers[provider] = pc
+ pc.cu_model = value
+ except Exception as exc: # noqa: BLE001 — frozen/detached cfg is acceptable
+ log.debug("In-memory cu_model update skipped for %s: %s", provider, exc)
+
+
async def _probe_brain_model(
provider: str, model: str, *, timeout_s: float = 20.0
) -> _provider_test.ProviderTestResult:
@@ -793,6 +840,81 @@ async def set_brain_model(
return _apply_stt_model(provider_id, value, body, request)
[email protected]("/providers/{provider_id}/cu-model")
+async def get_cu_model(provider_id: str, request: Request) -> CuModelResponse:
+ """Return the per-provider Computer-Use model selection (Phase 3).
+
+ ``cu_model`` is the pinned value ("" = use the provider's main model);
+ ``effective_model`` is what CU would actually run. The dropdown options reuse
+ the existing ``GET /providers/{id}/models`` catalog.
+ """
+ _spec, cat = _require_catalog_provider(provider_id)
+ if cat.tier != "brain":
+ raise HTTPException(
+ status_code=400,
+ detail="A Computer-Use model only applies to brain providers.",
+ )
+ cfg = _resolve_cfg(request)
+ pinned = _provider_cu_model(cfg, provider_id)
+ effective = pinned or _current_brain_model(cfg, provider_id)
+ return CuModelResponse(
+ provider=provider_id,
+ cu_model=pinned,
+ effective_model=effective,
+ uses_main=not bool(pinned),
+ )
+
+
[email protected]("/providers/{provider_id}/cu-model")
+async def set_cu_model(
+ provider_id: str, body: CuModelBody, request: Request
+) -> CuModelResponse:
+ """Pin (or clear with "") the per-provider Computer-Use model (Phase 3).
+
+ Persists to ``[brain.providers.<id>].cu_model`` (+ drift-soll) and updates the
+ in-memory config so the next CU mission uses it with no restart. No live brain
+ probe — the model is validated lazily the next time CU dispatches.
+ """
+ _spec, cat = _require_catalog_provider(provider_id)
+ if cat.tier != "brain":
+ raise HTTPException(
+ status_code=400,
+ detail="A Computer-Use model only applies to brain providers.",
+ )
+ value = body.cu_model.strip()
+
+ persisted = False
+ if body.persist:
+ try:
+ from jarvis.core.config_writer import set_brain_provider_model
+
+ set_brain_provider_model(provider_id, cu_model=value)
+ persisted = True
+ except FileNotFoundError as exc:
+ raise HTTPException(status_code=500, detail=str(exc)) from exc
+ except Exception as exc: # noqa: BLE001
+ raise HTTPException(
+ status_code=500, detail=f"TOML-Write fehlgeschlagen: {exc}"
+ ) from exc
+
+ cfg = _resolve_cfg(request)
+ _set_cu_model_in_memory(cfg, provider_id, value)
+ await _emit(
+ request,
+ SecretConfigured(key=f"brain.providers.{provider_id}.cu_model", action="set"),
+ )
+ effective = value or _current_brain_model(cfg, provider_id)
+ return CuModelResponse(
+ ok=True,
+ provider=provider_id,
+ cu_model=value,
+ effective_model=effective,
+ uses_main=not bool(value),
+ persisted=persisted,
+ restart_required=False,
+ )
+
+
@router.get("/codex/status")
async def codex_status(request: Request) -> dict[str, Any]:
return CodexAuthService(_codex_binary_path(request)).status().to_dict()
diff --git a/jarvis/ui/web/provider_spec.py b/jarvis/ui/web/provider_spec.py
index 9cfa0d0db6..ca242a7f3a 100644
--- a/jarvis/ui/web/provider_spec.py
+++ b/jarvis/ui/web/provider_spec.py
@@ -62,6 +62,16 @@ class ProviderSpec:
# Alternative credential path (Gemini AI Studio vs Vertex). ``None`` =
# single path.
alt_credential: AltCredential | None = None
+ # Maintainer-recommended pick for this tier (UI badge). Set on exactly the
+ # provider the maintainer wants users to default to — currently the Gemini
+ # brain (best real-world experience, 2026-06-22). This is a presentation
+ # hint only: it never gates behavior, never branches a code path on a
+ # provider name (AP-21), and only the *brain* tier carries it today.
+ recommended: bool = False
+ # The specific model the recommendation points at (e.g. ``gemini-3.5-flash``),
+ # surfaced as an "empfohlen" marker in the model picker. ``None`` = the badge
+ # stands for the provider as a whole with no model preference.
+ recommended_model: str | None = None
def provider_billing(spec: ProviderSpec) -> Billing:
@@ -198,19 +208,15 @@ PROVIDERS: tuple[ProviderSpec, ...] = (
"service-account path instead — it bills a different account."
),
alt_credential=_GEMINI_VERTEX,
+ # Maintainer-recommended brain (2026-06-22): best real-world experience.
+ # Badge on the brain card; the model picker highlights gemini-3.5-flash.
+ recommended=True,
+ recommended_model="gemini-3.5-flash",
),
- ProviderSpec(
- id="grok",
- label="xAI Grok",
- tier="brain",
- auth_mode="api_key",
- secret_keys=("grok_api_key",),
- dashboard_url="https://console.x.ai/",
- credential_help=(
- "xAI API key (starts with xai-). Billed per token. Shared by the "
- "Grok brain and Grok Voice TTS."
- ),
- ),
+ # xAI Grok was removed as a BRAIN and SUB-AGENT provider on 2026-06-22
+ # (maintainer decision: Grok stays only as a TTS voice). The `grok-voice`
+ # TTS spec below is intentionally kept, and the `grok_api_key` credential it
+ # shares with the (now TTS-only) xAI key remains.
# Ollama-Provider 2026-04-21 entfernt — reine API-Provider-Chain.
# ── TTS ───────────────────────────────────────────────────────────────
ProviderSpec(
@@ -259,7 +265,7 @@ PROVIDERS: tuple[ProviderSpec, ...] = (
secret_keys=("grok_api_key",),
dashboard_url="https://console.x.ai/",
credential_help=(
- "Uses your xAI key (shared with the Grok brain). Voices: leo, rex, "
+ "xAI API key (starts with xai-) for Grok Voice. Voices: leo, rex, "
"sal, ara, eve."
),
),
diff --git a/jarvis/ui/web/server.py b/jarvis/ui/web/server.py
index 38a8c53c2e..cd33fe921b 100644
--- a/jarvis/ui/web/server.py
+++ b/jarvis/ui/web/server.py
@@ -227,6 +227,7 @@ class WebServer:
)
from .chats_routes import router as chats_router
from .cli_routes import router as cli_router
+ from .drop_routes import router as drop_router
from .contacts_routes import router as contacts_router
from .control_routes import router as control_router
from .docs_routes import router as docs_router
@@ -245,6 +246,7 @@ class WebServer:
)
from .outputs_routes import router as outputs_router
from .preview_routes import router as preview_router
+ from .antigravity_routes import router as antigravity_router
from .profile_routes import router as profile_router
from .provider_routes import router as provider_router
from .review_routes import router as review_router
@@ -272,6 +274,7 @@ class WebServer:
app.include_router(mcp_router)
app.include_router(tools_router)
app.include_router(provider_router)
+ app.include_router(antigravity_router)
app.include_router(control_router)
app.include_router(profile_router)
app.include_router(settings_router)
@@ -322,6 +325,7 @@ class WebServer:
# "Speak in this conversation". Reuses chat_store + session_store +
# brain + speech_pipeline from app.state (graceful 503s when absent).
app.include_router(chats_router)
+ app.include_router(drop_router)
# Default: kein Recorder verdrahtet — _init_session_stack() in start()
# setzt das beim Erfolg um.
app.state.session_store = None
@@ -789,7 +793,6 @@ class WebServer:
"openrouter": "openrouter_api_key",
"openai": "openai_api_key",
"gemini": "gemini_api_key",
- "grok": "grok_api_key",
}
mapping_rows = []
for mapping in MAPPINGS:
@@ -842,12 +845,12 @@ class WebServer:
)
# Antigravity is a DIRECT worker (GoogleCliWorker over the official
- # agy/Gemini CLI) with no OpenClaw slug, so it is not in MAPPINGS —
+ # agy/Gemini CLI) with no OpenClaw slug, so it is not in MAPPINGS —
# the Google sibling of Codex. Surface it as an explicit selectable
# subagent row, backed by the Google subscription OAuth login (no API
# key): "key_set" is the connected state. Selecting it routes heavy
# tasks through agy; selecting any other provider routes through that
- # one — the choice is never hardcoded (init._select_subagent_worker_kind).
+ # one — the choice is never hardcoded (init._select_subagent_worker_kind).
try:
from jarvis.google_cli.auth_service import GoogleCliAuthService
diff --git a/jarvis/ui/web/settings_routes.py b/jarvis/ui/web/settings_routes.py
index 6a1607e3bc..a33dc3aa74 100644
--- a/jarvis/ui/web/settings_routes.py
+++ b/jarvis/ui/web/settings_routes.py
@@ -1111,6 +1111,45 @@ async def put_mute_music(body: BoolToggleBody, request: Request) -> dict[str, ob
return {"ok": True, "enabled": enabled, "persisted": persisted, "applied_live": applied_live}
[email protected]("/sound-effects")
+async def get_sound_effects(request: Request) -> dict[str, object]:
+ cfg = _config(request)
+ ui = getattr(cfg, "ui", None)
+ return {"enabled": bool(getattr(ui, "sound_effects", True))}
+
+
[email protected]("/sound-effects")
+async def put_sound_effects(body: BoolToggleBody, request: Request) -> dict[str, object]:
+ """Global earcon master switch. Persists to [ui] sound_effects and applies
+ live: the in-memory UI config is the same object the speech pipeline reads
+ before every earcon, so the next tone honors the new value with no restart.
+ """
+ enabled = bool(body.enabled)
+ cfg = _config(request)
+ ui = getattr(cfg, "ui", None)
+ applied_live = False
+ if ui is not None:
+ try:
+ ui.sound_effects = enabled # type: ignore[attr-defined]
+ applied_live = True
+ except Exception as exc: # noqa: BLE001
+ log.debug("in-memory sound_effects update skipped: %s", exc)
+ persisted = False
+ try:
+ from jarvis.core import config_writer
+
+ config_writer.set_sound_effects(enabled)
+ persisted = True
+ except Exception as exc: # noqa: BLE001
+ log.warning("sound_effects persist failed (live apply still attempted): %s", exc)
+ return {
+ "ok": True,
+ "enabled": enabled,
+ "persisted": persisted,
+ "applied_live": applied_live,
+ }
+
+
# ---------------------------------------------------------------------------
# Wiki curator model picker. GET current + selectable providers/models; PUT to
# change. The dedicated long-term-memory LLM is provider-agnostic: an empty
diff --git a/jarvis/ui/web/skills_routes.py b/jarvis/ui/web/skills_routes.py
index d1f38ae68e..0370cb7177 100644
--- a/jarvis/ui/web/skills_routes.py
+++ b/jarvis/ui/web/skills_routes.py
@@ -349,7 +349,8 @@ async def create_skill_draft(
reg = _require_registry(request)
brain = getattr(request.app.state, "brain", None)
bus = getattr(request.app.state, "bus", None)
- service = SkillCreatorService(brain=brain, registry=reg, bus=bus)
+ config = getattr(request.app.state, "config", None)
+ service = SkillCreatorService(brain=brain, registry=reg, bus=bus, config=config)
result = await service.draft(
SkillCreatorInput(
intent=body.intent,
@@ -379,7 +380,8 @@ async def refine_skill_draft(
reg = _require_registry(request)
brain = getattr(request.app.state, "brain", None)
bus = getattr(request.app.state, "bus", None)
- service = SkillCreatorService(brain=brain, registry=reg, bus=bus)
+ config = getattr(request.app.state, "config", None)
+ service = SkillCreatorService(brain=brain, registry=reg, bus=bus, config=config)
result = await service.refine(
SkillCreatorInput(
intent=body.intent,
@@ -430,7 +432,8 @@ async def commit_skill_draft(
reg = _require_registry(request)
brain = getattr(request.app.state, "brain", None)
bus = getattr(request.app.state, "bus", None)
- service = SkillCreatorService(brain=brain, registry=reg, bus=bus)
+ config = getattr(request.app.state, "config", None)
+ service = SkillCreatorService(brain=brain, registry=reg, bus=bus, config=config)
try:
created = await service.commit(body.draft)
except SkillAuthoringError as exc:
diff --git a/jarvis/ui/whisperbar/interaction.py b/jarvis/ui/whisperbar/interaction.py
index 311be59c10..224d916a63 100644
--- a/jarvis/ui/whisperbar/interaction.py
+++ b/jarvis/ui/whisperbar/interaction.py
@@ -28,33 +28,64 @@ def classify_release(*, moved: bool) -> str:
return "drag" if moved else "click"
-def click_action(mode: str) -> str:
- """What a quick click should do, given the bar's current state.
-
- While a session is active (listen / think / speak) a click HANGS UP; from
- the idle/standby state it starts a session (TALK). Unknown states default
- to "talk" (safe — never hangs up something that isn't running).
- """
- return "hangup" if mode in ("listen", "think", "speak") else "talk"
-
-
-def resolve_click(x: float, width: int, mode: str) -> str:
+# NOTE: there is intentionally no coarse `click_action(mode)` helper. A bar
+# click is resolved ONLY through `resolve_click`, which gates the destructive
+# hang-up on the close-X hit-box. A "any active click = hangup" shortcut was
+# exactly the silent-hangup bug (2026-06-19) and must not be re-introduced.
+
+# Minimum tap radius (px) around the close-X glyph, so the hit-box stays
+# fingertip-tappable even when the pill is tiny. The effective radius also
+# scales with the pill width (``_CLOSE_X_HIT_FRAC``) so it tracks the glyph the
+# renderer actually draws (``renderer._draw_close_x`` at ``cx - 0.42*pw``).
+_CLOSE_X_HIT_PX: float = 10.0
+_CLOSE_X_HIT_FRAC: float = 0.14
+_CLOSE_X_CENTRE_FRAC: float = 0.42 # X centre offset from pill centre (mirror of renderer)
+
+
+def resolve_click(
+ x: float,
+ width: int,
+ mode: str,
+ *,
+ hovered: bool = False,
+ pill_w: float | None = None,
+) -> str:
"""Resolve a click on the bar into an action by its horizontal zone + state.
- The bar is split into thirds: the LEFT third is the X (hang up — only while
- a session is live), the RIGHT third is the square (toggle endpoint-free
- dictation: start / submit), the MIDDLE starts a normal session when idle.
Returns one of ``"hangup"`` / ``"dictate"`` / ``"talk"`` / ``"none"``.
+
+ The RIGHT zone is the square (toggle endpoint-free dictation — non-
+ destructive, so it keeps a generous zone). When IDLE, a click anywhere
+ starts a normal session.
+
+ The hang-up X is different: it ENDS the session, so its hit-box is
+ deliberately narrow and must match what the user can see. The renderer draws
+ the close-X ONLY while the bar is ``hovered`` (and as a small glyph at
+ ``cx - 0.42*pw``), so a hang-up fires ONLY when (a) the controls are shown
+ (``hovered``) AND (b) the click lands on the X glyph itself. A low-intent
+ click on the active bar's body — where no X is visible — returns ``"none"``
+ instead of silently hanging up. This closes the "Jarvis hangs up by itself"
+ trap (live bug 2026-06-19): the old code hung up on ANY click in the left
+ 40% of the bar, decoupled from the visible affordance.
"""
frac = x / max(1, width)
active = mode in ("listen", "think", "speak")
- if frac >= 0.60: # right zone → the square (always available)
+ if frac >= 0.60: # right zone → the square (non-destructive)
return "dictate"
- if frac < 0.40 and active: # left zone → the X (only closes a live session)
- return "hangup"
if not active: # idle middle/left → start a normal session
return "talk"
- return "none" # active middle → nothing
+ # Active session: the ONLY destructive bar action is the close-X hang-up,
+ # which must be a deliberate click ON the visible X glyph.
+ if hovered:
+ # In production `pill_w` is always the active pill width (ACTIVE_W); the
+ # caller only passes None for idle mode, which returns above before this
+ # branch. The `width` fallback is just a sane default for direct callers.
+ pw = float(pill_w) if pill_w is not None else float(width)
+ x_glyph = width / 2.0 - _CLOSE_X_CENTRE_FRAC * pw # mirror renderer._draw_close_x
+ hit = max(_CLOSE_X_HIT_PX, _CLOSE_X_HIT_FRAC * pw)
+ if abs(x - x_glyph) <= hit:
+ return "hangup"
+ return "none" # active body / no visible X → nothing
def default_bottom_center(
diff --git a/jarvis/ui/whisperbar/overlay.py b/jarvis/ui/whisperbar/overlay.py
index e9ac937514..e34517d38e 100644
--- a/jarvis/ui/whisperbar/overlay.py
+++ b/jarvis/ui/whisperbar/overlay.py
@@ -83,10 +83,17 @@ class WhisperBarOverlay:
persistent: bool = True,
accent: str = "#e7c46e",
opacity: float = BAR_ALPHA,
+ start_hidden: bool = False,
) -> None:
self._persistent = persistent
self._accent = accent
self._opacity = max(0.2, min(1.0, float(opacity))) # clamp to sane range
+ # Boot gate: when set, the bar starts WITHDRAWN even if persistent, so it
+ # does not appear before the speech pipeline is ready to listen (the
+ # "looks ready but isn't" boot confusion). The boot wiring reveals it via
+ # show("idle") once VoiceBootStatus(ready=True) arrives. Default False
+ # keeps every other caller (live swap / set_bar_persistent) unchanged.
+ self._start_hidden = bool(start_hidden)
self._mode = "idle"
self._ext_level = 0.0
# perf_counter() of the last set_level() that carried real sound
@@ -170,6 +177,15 @@ class WhisperBarOverlay:
# ------------------------------------------------------------------ #
# Lifecycle #
# ------------------------------------------------------------------ #
+ def _should_start_withdrawn(self) -> bool:
+ """True when ``start()`` must withdraw the window instead of mapping it.
+
+ A non-persistent bar always starts hidden (it pops on a session). A
+ persistent bar normally maps immediately, but the boot gate
+ (``start_hidden=True``) keeps it hidden until voice is ready.
+ """
+ return (not self._persistent) or self._start_hidden
+
def start_in_thread(self, timeout: float = 3.0) -> None:
def _run() -> None:
try:
@@ -227,8 +243,27 @@ class WhisperBarOverlay:
self._canvas.bind("<Enter>", self._on_enter)
self._canvas.bind("<Leave>", self._on_leave)
- if not self._persistent:
- root.withdraw() # only-when-active variant starts hidden
+ # Drag-drop onto the bar (desktop extra, cross-platform via tkdnd).
+ # TEMPORARILY DISABLED 2026-06-23 (wake-fix session): on this frameless
+ # color-key topmost window, tkdnd's ``_require(root)`` + drop_target_register
+ # injected PHANTOM mouse press/release events on every turn mode-switch,
+ # which the click handler read as a close-X click -> a ``request_hangup``
+ # STORM (6+/turn) that aborted every voice answer mid-thought (Hangup during
+ # thinking). The file-drop-onto-bar feature is purely additive — the web
+ # dock (POST /api/chat/drop) carries it on every OS — so disabling JUST the
+ # bar registration restores voice without losing the capability. Re-enable
+ # once the tkdnd phantom-event issue on the color-key window is resolved.
+ if False: # noqa: SIM223 — intentional kill-switch (see note above)
+ try:
+ from jarvis.overlay.drop_bridge import dispatch_drop
+ from jarvis.overlay.drop_target import make_drop_target
+
+ make_drop_target().register(self._canvas, dispatch_drop)
+ except Exception: # noqa: BLE001 — drop is optional; never block bar boot.
+ log.debug("bar drop target registration skipped", exc_info=True)
+
+ if self._should_start_withdrawn():
+ root.withdraw() # only-when-active variant / boot gate starts hidden
try:
from jarvis.audio import level_tap
@@ -372,12 +407,19 @@ class WhisperBarOverlay:
# Drag (reposition) + click (start a voice session) #
# ------------------------------------------------------------------ #
def _on_press(self, event: Any) -> None:
+ # A press on the canvas means the pointer IS over the bar, so the close-X
+ # controls are (and visually become) available even if <Enter> was missed
+ # — e.g. the bar deiconified under a stationary cursor. resolve_click then
+ # still gates the hang-up on the X-glyph hit-box, so this only makes a
+ # DELIBERATE X-click reliable; it never widens the accidental-hangup zone.
+ self._hovered = True
self._drag = {
"sx": event.x_root,
"sy": event.y_root,
"ox": event.x_root - self._x,
"oy": event.y_root - self._y,
"cx": event.x, # canvas-relative x → which control zone was clicked
+ "hovered": True, # press-time hover (the pointer IS on the bar now)
"moved": False,
}
@@ -403,7 +445,10 @@ class WhisperBarOverlay:
if d is None:
return
if interaction.classify_release(moved=bool(d["moved"])) == "click":
- self._on_click(d.get("cx", renderer.WIN_W / 2))
+ # Use the PRESS-time hover (consistent with the press-time cx): a
+ # deliberate click that started on the bar registers even if a stray
+ # <Leave> flickered _hovered before release.
+ self._on_click(d.get("cx", renderer.WIN_W / 2), hovered=bool(d.get("hovered")))
return
try:
sw = int(self._root.winfo_screenwidth())
@@ -437,7 +482,7 @@ class WhisperBarOverlay:
except Exception: # noqa: BLE001
log.debug("whisperbar show-window callback failed", exc_info=True)
- def _on_click(self, click_x: float | None = None) -> None:
+ def _on_click(self, click_x: float | None = None, *, hovered: bool = False) -> None:
# Zone-routed: LEFT X → hang up (active only), RIGHT square → toggle
# endpoint-free dictation, MIDDLE (idle) → start a normal session. All
# entries are thread-safe from the Tk thread.
@@ -449,7 +494,16 @@ class WhisperBarOverlay:
pipeline = get_speech_pipeline()
if pipeline is None:
return
- action = interaction.resolve_click(click_x, renderer.WIN_W, self._mode)
+ # Hang-up must be a deliberate click on the VISIBLE close-X glyph
+ # (the X is only drawn while hovered), never the wide left dead-zone
+ # — see interaction.resolve_click + the silent-hangup forensic. The
+ # active pill is ACTIVE_W, so the X glyph sits at WIN_W/2-0.42*pw.
+ active = self._mode in ("listen", "think", "speak")
+ pill_w = renderer.ACTIVE_W if active else None
+ action = interaction.resolve_click(
+ click_x, renderer.WIN_W, self._mode,
+ hovered=hovered, pill_w=pill_w,
+ )
if action == "dictate":
toggle = getattr(pipeline, "request_ptt_toggle", None)
if callable(toggle):
diff --git a/jarvis/vision/image_budget.py b/jarvis/vision/image_budget.py
index 2e851a46ef..9b2b02425e 100644
--- a/jarvis/vision/image_budget.py
+++ b/jarvis/vision/image_budget.py
@@ -25,13 +25,25 @@ _DEFAULT_JPEG_QUALITY = 85
_MIN_JPEG_QUALITY = 35
-def cap_image_b64(mime: str, data_b64: str, max_bytes: int) -> tuple[str, str]:
+def cap_image_b64(
+ mime: str,
+ data_b64: str,
+ max_bytes: int,
+ max_dimension: int = _MAX_DIMENSION,
+) -> tuple[str, str]:
"""Return ``(mime, base64)`` capped to roughly ``max_bytes``.
No-op when the encoded image is already within budget. Otherwise the image
- is downscaled to ``_MAX_DIMENSION`` longest side and JPEG-encoded, reducing
- quality toward ``_MIN_JPEG_QUALITY`` to approach the budget (best-effort).
- On any failure the original ``(mime, data_b64)`` is returned unchanged.
+ is downscaled to ``max_dimension`` longest side (default ``_MAX_DIMENSION``,
+ 2048 px) and JPEG-encoded, reducing quality toward ``_MIN_JPEG_QUALITY`` to
+ approach the budget (best-effort). On any failure the original
+ ``(mime, data_b64)`` is returned unchanged.
+
+ ``max_dimension`` (L7 CU-speed lever) is tunable: vision models resample to
+ ~1568 px internally, so a smaller longest side ships fewer pixels for faster
+ encode + upload + ingest. ``<= 0`` disables the dimension cap (byte budget
+ only). The default keeps the legacy 2048 px, so existing callers are
+ byte-for-byte unchanged.
"""
if max_bytes <= 0:
return mime, data_b64
@@ -48,8 +60,8 @@ def cap_image_b64(mime: str, data_b64: str, max_bytes: int) -> tuple[str, str]:
img = img.convert("RGB")
w, h = img.size
longest = max(w, h)
- if longest > _MAX_DIMENSION:
- scale = _MAX_DIMENSION / longest
+ if max_dimension > 0 and longest > max_dimension:
+ scale = max_dimension / longest
img = img.resize(
(max(1, round(w * scale)), max(1, round(h * scale))),
resample=Image.Resampling.LANCZOS,
diff --git a/jarvis/voice/action_phrases.py b/jarvis/voice/action_phrases.py
index 9865f47859..a9e282061c 100644
--- a/jarvis/voice/action_phrases.py
+++ b/jarvis/voice/action_phrases.py
@@ -62,7 +62,7 @@ _PHRASES: dict[str, dict[str, str]] = {
# didn't work on screen: exit 5" and the user asked "what is the exit file?".
# Exit-code semantics are documented at the top of
# jarvis/harness/screenshot_only_loop.py (5=`fail`, 1=observe, 2=parse,
- # 4=step budget, 8=tool failure, 124=timeout, 130=cancel).
+ # 4=step budget, 8=tool failure, 9=elevation unmet, 124=timeout, 130=cancel).
"cu_exit_gave_up": { # exit 5 — the model's `fail` action
"de": "Ich habe es am Bildschirm versucht, aber nicht hinbekommen.", # i18n-allow
"en": "I tried it on screen but couldn't get it done.",
@@ -73,10 +73,10 @@ _PHRASES: dict[str, dict[str, str]] = {
"en": "I couldn't see the screen properly, so I stopped.",
"es": "No pude ver bien la pantalla, así que lo detuve.",
},
- "cu_exit_confused": { # exit 2 — parse error
- "de": "Ich bin am Bildschirm durcheinandergekommen und habe abgebrochen.", # i18n-allow
- "en": "I got confused on screen and had to stop.",
- "es": "Me confundí en la pantalla y tuve que detenerme.",
+ "cu_exit_confused": { # exit 2 — invalid model / parse response
+ "de": "Ich konnte keine gueltige Bildschirm-Antwort bekommen und habe gestoppt.", # i18n-allow
+ "en": "I couldn't get a valid screen-control response, so I stopped.",
+ "es": "No pude obtener una respuesta valida para controlar la pantalla, asi que me detuve.",
},
"cu_exit_too_many_steps": { # exit 4 — step budget exhausted
"de": "Es hat am Bildschirm zu viele Schritte gebraucht, ich habe " # i18n-allow
@@ -94,6 +94,12 @@ _PHRASES: dict[str, dict[str, str]] = {
"en": "The action on screen was cancelled.",
"es": "La acción en la pantalla se canceló.",
},
+ "cu_exit_needs_elevation": { # exit 9 — waited for admin confirmation, none came
+ "de": "Ich habe auf die Administrator-Bestaetigung gewartet, aber es kam " # i18n-allow
+ "keine -- ich habe gestoppt.", # i18n-allow
+ "en": "I waited for the administrator confirmation, but none came, so I stopped.",
+ "es": "Esperé la confirmación de administrador, pero no llegó, así que me detuve.",
+ },
"cu_timeout": {
"de": "Das am Bildschirm hat zu lange gedauert " # i18n-allow
"(ueber {secs} Sekunden) und wurde abgebrochen.", # i18n-allow
@@ -107,6 +113,19 @@ _PHRASES: dict[str, dict[str, str]] = {
"en": "On it — I'll handle that on screen and let you know when it's done.",
"es": "Voy — lo hago directamente en la pantalla y te aviso cuando termine.",
},
+ # Computer-use pause: an OS elevation prompt (Windows Secure Desktop & co.)
+ # is up. A non-elevated process can neither see nor click it (UIPI), so we
+ # ask the user for the one unavoidable confirmation click and then continue.
+ # Phrased OS-neutrally ("security prompt") — the Windows path is the only one
+ # that triggers it today, but macOS/Linux detection may join later.
+ "cu_awaiting_elevation": {
+ "de": "Das verlangt gerade Administrator-Rechte. Bitte bestaetige die " # i18n-allow
+ "Sicherheitsabfrage einmal, dann mache ich weiter.", # i18n-allow
+ "en": "This needs administrator rights. Please confirm the security "
+ "prompt once, then I'll keep going.",
+ "es": "Esto requiere permisos de administrador. Confirma el aviso de "
+ "seguridad una vez y continúo.",
+ },
# Cost / budget guards on the computer-use branch.
"cost_cooldown": {
"de": "Cost-Cooldown aktiv — Tagesbudget erschoepft. " # i18n-allow
@@ -171,6 +190,7 @@ _EXIT_CODE_PHRASE: dict[int, str] = {
4: "cu_exit_too_many_steps",
5: "cu_exit_gave_up",
8: "cu_exit_action_failed",
+ 9: "cu_exit_needs_elevation",
130: "cu_exit_cancelled",
}
#: Strip the loop's "[cu] <verb> at <tag>: " prefix so the human reason the
@@ -179,6 +199,95 @@ _EXIT_CODE_PHRASE: dict[int, str] = {
_CU_REASON_PREFIX_RE = re.compile(
r"^\s*\[cu\][^:]*:\s*", re.IGNORECASE,
)
+#: Internal computer-use DIAGNOSTIC / telemetry markers. A stderr fragment
+#: carrying any of these is loop instrumentation — the no-progress guard, the
+#: anti-oscillation / toggle guards, or the latency "mission profile" summary —
+#: NOT the model's human ``fail`` reason. It must never be forwarded into a
+#: spoken/displayed readback. Live bug 2026-06-20 (Angela-Merkel x.com mission):
+#: the user heard "Das am Bildschirm hat nicht geklappt: 3 identical screenshots
+#: in a row at step 9 -- the click ..." followed by the raw
+#: "[cu] mission profile: steps=9 ..." telemetry line. The exit-code phrases
+#: (``cu_exit_*``) exist precisely so these cases degrade to a plain sentence.
+_CU_DIAGNOSTIC_RE = re.compile(
+ r"\[cu\]" # any engineering-prefixed loop line
+ r"|identical\s+screenshots?" # no-progress guard
+ r"|mission\s+profile" # latency telemetry summary
+ r"|guard-blocked" # anti-oscillation / modal guards
+ r"|toggle-stop", # repeated-click toggle guard
+ re.IGNORECASE,
+)
+#: A raw VERIFIER OBSERVATION dump, as opposed to a clean user-facing answer.
+#: The read-goal verifier (``_READ_VERIFIER_SYSTEM_PROMPT`` in
+#: ``screenshot_only_loop.py``) is a STRICT completion judge: it often PROVES the
+#: goal by describing the UI structurally ("Foreground window (...): title '...',
+#: content starts '...', followed by bullet points ..., Bottom status bar: ...")
+#: rather than answering the user in plain language. Such a proof is an internal
+#: evidence artifact (the spirit of ADR-0009 — the voice readback speaks only a
+#: clean summary, never the raw signed observation), so it must never be spoken
+#: verbatim. Live bug 2026-06-21 (Melbourne HTML turn): a "look at my screen and
+#: tell me which app is open" mission read out the full structural dump, INCLUDING
+#: the verbatim content of an unrelated parallel Claude-Code AskUserQuestion box
+#: ("Eine Detail-Erkenntnis ... Der Melbourne-Guide rendert ..."). A genuine
+#: content answer ("the browser is open showing tab 'Gmail'", "newest messages:
+#: Alice 'hi'") carries none of these structural markers and is still forwarded.
+_CU_VERIFIER_DUMP_RE = re.compile(
+ r"\b(?:fore|back)ground\s+window\b" # window-layer vocabulary
+ r"|\bactive\s+window\b"
+ r"|\bvordergrundfenster\b" # i18n-allow: DE verifier
+ r"|\b(?:status|title|menu|tool|task|side|scroll|address)[\s-]?bars?\b"
+ r"|(?:status|titel|men[üu]|symbol|seiten|bildlauf|adress|task|werkzeug)" # i18n-allow
+ r"[\s-]?leisten?\b" # i18n-allow: Status-/Titel-/Symbolleiste
+ r"|\bcontent\s+(?:starts?|reads?|begins?|shows?|says?)\b"
+ r"|\bfollowed\s+by\s+bullet"
+ r"|\bbullet\s+points?\b"
+ r"|\bwindow\s+(?:title|content|titled)\b",
+ re.IGNORECASE,
+)
+#: The latency "mission profile" line is a run of numeric ``key=value`` telemetry
+#: tokens: "steps=3 total=9.5s act=3.0s observe=0.3s plan=1.6s think=4.6s". The
+#: FAILURE path strips the "[cu] mission profile:" PREFIX (via
+#: ``_CU_REASON_PREFIX_RE``) before the speakability gate runs, which deletes the
+#: very "[cu]"/"mission profile" markers ``_CU_DIAGNOSTIC_RE`` keys on — so the
+#: BARE profile sailed straight through and was spoken (live bug 2026-06-22, the
+#: Ed-Sheeran "Perfect" turn: 'That didn't work on screen: steps=3 total=9.5s
+#: act=3.0s observe=0.3s plan=1.6s think=4.6s'). Detect the profile STRUCTURALLY
+#: instead — independent of any prefix: any of the named phase keys, or two or
+#: more numeric ``key=value`` tokens in a row, is a machine stats dump, never a
+#: human sentence. A lone "HTTP 403" / "2 attempts" carries no ``=`` and survives.
+_CU_TELEMETRY_RE = re.compile(
+ r"\b(?:steps|total|act|observe|plan|think|verify)=\d" # a named profile stat
+ r"|(?:\b[A-Za-z_][\w-]*=\d[\d.]*\w*\b\s*){2,}", # >=2 numeric key=value
+ re.IGNORECASE,
+)
+#: A filesystem path or screenshot-artifact filename that leaked into a readback.
+#: The harness temp capture ("C:\\…\\pythonw_xxxx.png") rode the failure ``detail``
+#: into the spoken text on the same 2026-06-22 turn. A spoken answer never names a
+#: path or an image file, so any of these forces the generic phrase. The image
+#: extension is matched cross-platform (the screenshot leak is identical on a
+#: headless Linux VPS, where the path would be POSIX).
+_CU_PATH_ARTIFACT_RE = re.compile(
+ r"[A-Za-z]:[\\/]" # a Windows drive-letter path
+ r"|\b[\w-]+\.(?:png|jpe?g|gif|bmp|webp|tiff?)\b", # a screenshot / image file
+ re.IGNORECASE,
+)
+
+
+def _is_diagnostic_noise(text: str) -> bool:
+ """True if ``text`` is internal machine noise that must never be spoken.
+
+ The shared, structural junk-detector behind both speakability gates. Covers
+ the named loop markers (``_CU_DIAGNOSTIC_RE``), the bare latency ``mission
+ profile`` stats run (``_CU_TELEMETRY_RE`` — matched by SHAPE so it still trips
+ after the "[cu] mission profile:" prefix has been stripped off), and a leaked
+ filesystem / screenshot path (``_CU_PATH_ARTIFACT_RE``). Pure regex, no LLM
+ (AP-11): the answer is "is this a sentence a butler would say, or a developer
+ log line?" — the user's "if you see that junk, you know not to speak it".
+ """
+ return bool(
+ _CU_DIAGNOSTIC_RE.search(text)
+ or _CU_TELEMETRY_RE.search(text)
+ or _CU_PATH_ARTIFACT_RE.search(text)
+ )
def _looks_human(text: str) -> bool:
@@ -199,6 +308,43 @@ def _looks_human(text: str) -> bool:
return True
+def _is_speakable_reason(text: str | None) -> bool:
+ """True if ``text`` is a real, user-facing reason — safe to forward verbatim.
+
+ Stricter than :func:`_looks_human`: besides rejecting bare ``exit N`` /
+ numeric / empty tokens, it rejects internal computer-use DIAGNOSTIC and
+ telemetry strings (the no-progress guard, the anti-oscillation / toggle
+ guards, the bare latency ``mission profile`` stats run, and a leaked
+ screenshot path). Those are developer instrumentation written to the harness
+ ``stderr`` — never the model's human ``fail`` reason — so they must never
+ reach a spoken/displayed readback. A blocked string degrades to the generic,
+ localized exit-code phrase instead.
+ """
+ if not _looks_human(text or ""):
+ return False
+ return not _is_diagnostic_noise(text or "")
+
+
+def _is_speakable_observation(text: str | None) -> bool:
+ """True if ``text`` is a clean, user-facing observation — safe to speak.
+
+ The SUCCESS sibling of :func:`_is_speakable_reason`. Besides rejecting bare
+ ``exit N`` / numeric / empty tokens, internal diagnostic markers, the bare
+ telemetry profile, and a leaked screenshot path (all via
+ :func:`_is_diagnostic_noise`), it also rejects a raw VERIFIER UI-STRUCTURE
+ dump (``_CU_VERIFIER_DUMP_RE``): a "Foreground window (...): title '...',
+ content starts '...'" proof is the judge's internal evidence, not the answer
+ the user asked for, and leaks whatever happened to be on screen (incl.
+ unrelated windows). A blocked observation degrades to the generic, localized
+ ``cu_done`` phrase instead.
+ """
+ if not _looks_human(text or ""):
+ return False
+ if _is_diagnostic_noise(text or ""):
+ return False
+ return _CU_VERIFIER_DUMP_RE.search(text or "") is None
+
+
def cu_failure_readback(
lang: str,
*,
@@ -225,11 +371,11 @@ def cu_failure_readback(
# 1) The harness detail string may carry the model's verified reason.
if detail:
candidate = _CU_REASON_PREFIX_RE.sub("", detail).strip()
- if _looks_human(candidate):
+ if _is_speakable_reason(candidate):
return action_phrase("cu_failed_reason", lang, error=candidate)
# 2) A human reason already on the error field is forwarded verbatim.
- if _looks_human(error or ""):
+ if _is_speakable_reason(error):
return action_phrase("cu_failed_reason", lang, error=str(error).strip())
# 3) Opaque / empty error -> map the exit code to a human phrase.
@@ -275,11 +421,12 @@ def cu_success_readback(lang: str, *, stdout: str | None) -> str:
downstream like every other spoken phrase.
Falls back to the plain localized ``cu_done`` phrase when the mission left
- no usable observation (no ``(verified: ...)`` segment, or an empty/opaque
- proof).
+ no usable observation (no ``(verified: ...)`` segment, an empty/opaque
+ proof, or — via :func:`_is_speakable_observation` — a raw verifier UI
+ STRUCTURE dump that describes the screen instead of answering the user).
"""
proof = _extract_cu_proof(stdout or "")
- if proof and _looks_human(proof):
+ if proof and _is_speakable_observation(proof):
return action_phrase("cu_done_detail", lang, detail=proof)
return action_phrase("cu_done", lang)
diff --git a/jarvis/voice/tool_confirmation.py b/jarvis/voice/tool_confirmation.py
index 1f049aacfa..634757e9c1 100644
--- a/jarvis/voice/tool_confirmation.py
+++ b/jarvis/voice/tool_confirmation.py
@@ -4,9 +4,9 @@ through the two-turn confirmation flow.
Why this exists (forensic 2026-06-18, session 2995997b): an ``ask``-tier tool
(gmail send) invoked on the voice path blocks in ``ApprovalWorkflow.wait()`` for a
UI approval the voice user never gives. The 20 s no-first-frame ceiling then
-beheads the working turn and Jarvis speaks the misleading "Das hat gerade zu lange
-gedauert. Sag es bitte noch einmal." There is no voice/chat path to APPROVE a
-consequential action today (``jarvis/speech`` never publishes ``ActionApproved``).
+beheads the working turn and Jarvis speaks the brain-timeout fallback. There is
+no voice/chat path to APPROVE a consequential action today (``jarvis/speech``
+never publishes ``ActionApproved``).
Instead of hanging, the brain now SPEAKS a short confirmation question on turn N
and the user's next "ja"/"nein" (classified by ``echo_confirmation.classify_
diff --git a/pyproject.toml b/pyproject.toml
index 16e61df285..94065dae69 100644
--- a/pyproject.toml
+++ b/pyproject.toml
@@ -155,6 +155,17 @@ desktop = [
# no-op when they are absent.
"pyautogui>=0.9.54",
"mss>=10.0",
+ # Drag-drop ONTO the floating overlay (bar/mascot): the cross-platform tkdnd
+ # Tcl extension, with bundled binaries for Windows / macOS / Linux. Registered
+ # onto the live Tk root in place (jarvis/overlay/drop_target.py). All-platform
+ # desktop dep; absent → the overlay drop degrades to a logged no-op while the
+ # in-app web dock (POST /api/chat/drop) still carries the feature everywhere.
+ # PIN ==0.4.2 (verified on real Windows/macOS-arm64/Linux GitHub runners,
+ # 2026-06-22): from 0.4.4.1 onward the osx-arm64 binary is the Tcl-9 build
+ # (libtcl9tkdnd2.9.5.dylib) which fails to load on the standard Tcl-8.6 Python
+ # ("incompatible stubs mechanism") — breaking the overlay drop on Apple
+ # Silicon. 0.4.2 ships the Tcl-8 osx-arm64 binary that loads on all three OSes.
+ "tkinterdnd2==0.4.2",
]
# macOS accessibility / overlay extras (Wave 2, AD-14). pyobjc frameworks back
# the macOS AX-tree UI-element-click source (Wave 2.1) and are macOS-only, so
@@ -231,9 +242,9 @@ claude-api = "jarvis.plugins.brain.claude_api:ClaudeAPIBrain"
openrouter = "jarvis.plugins.brain.openrouter:OpenRouterBrain"
openai = "jarvis.plugins.brain.openai:OpenAIBrain"
gemini = "jarvis.plugins.brain.gemini:GeminiBrain"
-grok = "jarvis.plugins.brain.grok:GrokBrain"
codex = "jarvis.plugins.brain.codex:CodexBrain"
antigravity = "jarvis.plugins.brain.antigravity:AntigravityBrain"
+# xAI Grok removed as a brain provider 2026-06-22 (TTS-only — see grok-voice).
# Ollama-Provider 2026-04-21 entfernt — User-Entscheidung (reine API-Provider-Chain).
[project.entry-points."jarvis.harness"]
diff --git a/scripts/config-soll.json b/scripts/config-soll.json
index 26782cd6c8..bcd055dc0b 100644
--- a/scripts/config-soll.json
+++ b/scripts/config-soll.json
@@ -1,16 +1,16 @@
{
"_comment": "Desired-state values for jarvis.toml. The config-drift-guard reads THIS file every 5 minutes and corrects any jarvis.toml value (and JARVIS__* User-scope ENV override) that drifts away from what is pinned here. This file is the moving source of truth: the guard only READS it, it never writes it. IMPORTANT (changed 2026-05-28): brain.primary is now ALSO written automatically by the desktop app's provider switch (the API/Settings section in the UI). When you switch the active Brain provider in the UI, the app writes all three layers at once -- jarvis.toml [brain].primary, this config-soll.json brain.primary, and the JARVIS__BRAIN__PRIMARY User-scope ENV var -- so all three agree on the new value and the drift-guard sees NO drift and will NOT revert your choice. Editing brain.primary here by hand still works, but the UI provider switch is the normal way to change the active provider. The drift-guard's job is to PROTECT whatever value is set here against rogue parallel sessions (which only touch jarvis.toml, not this file). Keys use dot-notation, exactly as the TOML section header reads. Paths in Punkt-Notation, exakt wie in der TOML.",
- "_updated": "2026-06-10",
- "_reason": "2026-06-14: heavy tier moved from claude-fable-5 to claude-opus-4-8 (explicit model id, the configured frontier) — the Claude Max subscription lost CLI access to Fable ('Claude Fable 5 is currently unavailable', approved-access-only), so every worker AND critic spawn wasted ~2s probing the unavailable model before the adaptive retry fell back to the CLI default (which IS opus-4-8). Maintainer approved the direct opus-4-8 pin on 2026-06-14; the worker/critic keep the retry-without-model safety net if opus ever becomes inaccessible too. PRIOR 2026-06-10: heavy tier pinned to claude-fable-5 (user mandate: no automatic claude-opus-* fallback anywhere). brain.providers.claude-api.deep_model=claude-fable-5; brain.sub_jarvis switched openai-codex -> claude-api with an explicit model pin claude-fable-5 so worker AND critic (same chain resolver) run fable via the Claude Max OAuth claude CLI. EARLIER 2026-05-28: sub-agent heavy-worker LLM upgraded Opus 4.7 -> 4.8 (current Anthropic frontier; both verified live under Claude Max OAuth). Pinned brain.providers.claude-api.deep_model=claude-opus-4-8 here so the drift-guard enforces it (it was previously unpinned). 2026-05-28: brain.primary is now ALSO written by the desktop-app UI provider switch as a three-layer sync (jarvis.toml [brain].primary + this config-soll.json brain.primary + the JARVIS__BRAIN__PRIMARY User-scope env var) so the drift-guard sees no drift and never reverts a deliberate switch; the guard was hardened to be a true no-op when all three layers already agree, and a latent PowerShell foreach scope-leak that left the ENV-drift check inert was fixed. 2026-05-27: Cartesia.ai Sonic 3.5 added as a selectable TTS provider with per-language native voice mapping (Sebastian/Daniel/Pedro for DE/EN/ES) synced to the reply_language pin + per-utterance auto-detect. Earlier 2026-05-26 (Vertex AI): tts.use_vertex + vertex_project + vertex_location + service_account_path added — routes Gemini Flash TTS through Vertex AI on the user's billed GCP project instead of Google AI Studio. AI Studio enforces a 100-RPD cap on the Preview model gemini-3.1-flash-tts-preview that is independent of Pay-as-you-go billing; once hit, the Sibling-Bridge auto-switches to gemini-2.5-flash-preview-tts and the perceived Charon voice shifts mid-session, breaking the 2026-05-24 single-voice user mandate. Vertex AI on a billed project does not have the Preview RPD cap. Auth runs via a service-account JSON at ~/.config/jarvis/vertex-sa.json (dedicated SA, role roles/aiplatform.user, key on disk). The plugin strips GOOGLE_API_KEY + GEMINI_API_KEY at client-build time so the AI-Studio path cannot be accidentally re-routed when both auth modes are present. The Sibling-Bridge stays wired as defence-in-depth but will not trigger on Vertex. Earlier 2026-05-26: stt.bias_prompt added — Whisper-prompt vocabulary biasing for the Groq cloud STT plugin. Without it, Whisper falls onto phonetically nearby everyday words for proper nouns and tech vocabulary. The prompt is a comma-separated word list (NOT full sentences — Whisper would re-emit those verbatim on silent tail audio) and is capped to 1024 chars inside the plugin. Earlier 2026-05-26: computer_use.show_virtual_cursor pinned to false after the black-screen incident. Earlier 2026-05-24: trigger.single_turn_mode switched true -> false (USER mandate). EARLIER 2026-05-20: brain.sub_jarvis.provider switched from chatgpt back to claude-api. Earlier 2026-05-20: main Jarvis voice brain switched to Gemini 3.5 Flash (GA, model id `gemini-3.5-flash`, 1M-token context). Earlier 2026-05-18: voice single-turn mandate. Earlier 2026-05-15: all brain layers on Gemini.",
+ "_updated": "2026-06-21",
+ "_reason": "2026-06-21: ack_brain re-aligned after the spawn-announcement 'contextless stock phrase' report. The grounded LLM-composed spawn announcement was speaking generic pool phrases ('Hab ich. Das ist etwas umfangreicher...') instead of context-aware text. Root cause: ack_brain.enabled was pinned false (to silence the separate speculative PREAMBLE, which now has its own preamble_enabled sub-switch), but enabled is the SUBSYSTEM MASTER that also gates the grounded spawn announcer; and ack_brain.provider was pinned to gemini, which is billing-exhausted (429 RESOURCE_EXHAUSTED). Fix: enabled=true (restores the grounded spawn announcer; the speculative preamble stays off via preamble_enabled=false default), provider=grok (live, grok-4-fast-non-reasoning, ~0.8-1.6s, verified context-aware), fallback_provider=gemini (auto-recovers when credits return; consumed by the now-wired spawn-path failover). 2026-06-14: heavy tier moved from claude-fable-5 to claude-opus-4-8 (explicit model id, the configured frontier) — the Claude Max subscription lost CLI access to Fable ('Claude Fable 5 is currently unavailable', approved-access-only), so every worker AND critic spawn wasted ~2s probing the unavailable model before the adaptive retry fell back to the CLI default (which IS opus-4-8). Maintainer approved the direct opus-4-8 pin on 2026-06-14; the worker/critic keep the retry-without-model safety net if opus ever becomes inaccessible too. PRIOR 2026-06-10: heavy tier pinned to claude-fable-5 (user mandate: no automatic claude-opus-* fallback anywhere). brain.providers.claude-api.deep_model=claude-fable-5; brain.sub_jarvis switched openai-codex -> claude-api with an explicit model pin claude-fable-5 so worker AND critic (same chain resolver) run fable via the Claude Max OAuth claude CLI. EARLIER 2026-05-28: sub-agent heavy-worker LLM upgraded Opus 4.7 -> 4.8 (current Anthropic frontier; both verified live under Claude Max OAuth). Pinned brain.providers.claude-api.deep_model=claude-opus-4-8 here so the drift-guard enforces it (it was previously unpinned). 2026-05-28: brain.primary is now ALSO written by the desktop-app UI provider switch as a three-layer sync (jarvis.toml [brain].primary + this config-soll.json brain.primary + the JARVIS__BRAIN__PRIMARY User-scope env var) so the drift-guard sees no drift and never reverts a deliberate switch; the guard was hardened to be a true no-op when all three layers already agree, and a latent PowerShell foreach scope-leak that left the ENV-drift check inert was fixed. 2026-05-27: Cartesia.ai Sonic 3.5 added as a selectable TTS provider with per-language native voice mapping (Sebastian/Daniel/Pedro for DE/EN/ES) synced to the reply_language pin + per-utterance auto-detect. Earlier 2026-05-26 (Vertex AI): tts.use_vertex + vertex_project + vertex_location + service_account_path added — routes Gemini Flash TTS through Vertex AI on the user's billed GCP project instead of Google AI Studio. AI Studio enforces a 100-RPD cap on the Preview model gemini-3.1-flash-tts-preview that is independent of Pay-as-you-go billing; once hit, the Sibling-Bridge auto-switches to gemini-2.5-flash-preview-tts and the perceived Charon voice shifts mid-session, breaking the 2026-05-24 single-voice user mandate. Vertex AI on a billed project does not have the Preview RPD cap. Auth runs via a service-account JSON at ~/.config/jarvis/vertex-sa.json (dedicated SA, role roles/aiplatform.user, key on disk). The plugin strips GOOGLE_API_KEY + GEMINI_API_KEY at client-build time so the AI-Studio path cannot be accidentally re-routed when both auth modes are present. The Sibling-Bridge stays wired as defence-in-depth but will not trigger on Vertex. Earlier 2026-05-26: stt.bias_prompt added — Whisper-prompt vocabulary biasing for the Groq cloud STT plugin. Without it, Whisper falls onto phonetically nearby everyday words for proper nouns and tech vocabulary. The prompt is a comma-separated word list (NOT full sentences — Whisper would re-emit those verbatim on silent tail audio) and is capped to 1024 chars inside the plugin. Earlier 2026-05-26: computer_use.show_virtual_cursor pinned to false after the black-screen incident. Earlier 2026-05-24: trigger.single_turn_mode switched true -> false (USER mandate). EARLIER 2026-05-20: brain.sub_jarvis.provider switched from chatgpt back to claude-api. Earlier 2026-05-20: main Jarvis voice brain switched to Gemini 3.5 Flash (GA, model id `gemini-3.5-flash`, 1M-token context). Earlier 2026-05-18: voice single-turn mandate. Earlier 2026-05-15: all brain layers on Gemini.",
"trigger": {
"single_turn_mode": false
},
"tts": {
- "provider": "gemini-flash-tts",
+ "provider": "cartesia",
"fallback": "grok-voice",
"voice_de": "Charon",
"voice_en": "Charon",
- "language_code": "de-DE",
+ "language_code": "auto",
"chunk_by_sentence": false,
"seed": 7,
"temperature": 0.7,
@@ -62,13 +62,15 @@
},
"stt": {
"provider": "groq-api",
- "model": "large-v3-turbo",
+ "model": "whisper-large-v3",
"bias_prompt": "Jarvis, OpenClaw, Codex, Gemini, Grok, Claude, Anthropic, OpenAI, OpenRouter, Whisper, a dictation app, Subagent, Sub-Agent, Mission-Manager, Critic-Loop, Critic, Worker, Router-Brain, Router, Kontrollierer, Voice-Pipeline, Wake-Word, Silero, VAD, TTS, STT, Telemetry, Transkript, Token, Provider, Plugin, Sprechblase, Orb, Mascot, Quip, Browser, Terminal, Repository, Branch, Commit, Push, Pull-Request, Issue, Merge, Refactor, Deployment, Screenshot, Debuggen, Workflow, Microservice, Container, Docker, Kubernetes, FastAPI, React, TypeScript, Python, JSON, Markdown, Logfile, Konfiguration, Endpoint, Webhook, API-Key, Service-Account, Cloud, Google Cloud, Vertex AI, BigQuery, GitHub, Twilio, ElevenLabs, OAuth, Credential Manager, Frontend, Backend, Skript, Daemon, Hangup, Auflegen, Denkpause, submitted, distanziert, erkennt"
},
"ack_brain": {
+ "enabled": true,
"provider": "gemini",
- "fallback_provider": "grok",
- "timeout_ms": 4000
+ "fallback_provider": "gemini",
+ "timeout_ms": 4000,
+ "preamble_enabled": false
},
"memory.legacy_curator": {
"enabled": false
@@ -81,5 +83,8 @@
"enabled": true,
"log_jsonl": true,
"log_path": "state/latency_log.jsonl"
+ },
+ "brain.providers.antigravity": {
+ "model": "gemini-3.5-flash"
}
}
diff --git a/scripts/crossplatform/verify_drop_target.py b/scripts/crossplatform/verify_drop_target.py
new file mode 100644
index 0000000000..f58afd482f
--- /dev/null
+++ b/scripts/crossplatform/verify_drop_target.py
@@ -0,0 +1,114 @@
+"""Cross-platform drag-drop verification — runs on Windows, macOS AND Linux.
+
+Proves, on the host it runs on, that the overlay drag-drop mechanism actually
+works at the OS level:
+
+ 1. ``tkinterdnd2`` loads this OS's bundled ``tkdnd`` binary, so the factory
+ returns the real :class:`TkDnDDropTarget` (not the null fallback).
+ 2. The path parser handles this OS's path style.
+ 3. ``register`` succeeds on a real Tk window (overrideredirect + color-key,
+ the live-overlay window type).
+ 4. A ``<<Drop>>`` event runs the full chain through the process-global bridge
+ to the registered handler.
+
+Run in CI on a real ``macos-latest`` runner this is the autonomous macOS proof
+that cannot be produced on a Windows dev box (no macOS container exists). Exits
+non-zero on any failure so a CI step goes red.
+
+On Linux a display is required (the workflow wraps this in ``xvfb-run``) plus the
+X11 runtime libs the tkdnd ``.so`` links against (``libxcursor1`` …).
+"""
+from __future__ import annotations
+
+import importlib.util
+import os
+import sys
+import tkinter as tk
+
+_HERE = os.path.dirname(os.path.abspath(__file__))
+_ROOT = os.path.abspath(os.path.join(_HERE, "..", ".."))
+
+
+def _load(name: str, relpath: str):
+ spec = importlib.util.spec_from_file_location(name, os.path.join(_ROOT, relpath))
+ assert spec and spec.loader, f"cannot load {relpath}"
+ mod = importlib.util.module_from_spec(spec)
+ sys.modules[name] = mod
+ spec.loader.exec_module(mod)
+ return mod
+
+
+def main() -> int:
+ dt = _load("dt_verify", "jarvis/overlay/drop_target.py")
+ db = _load("db_verify", "jarvis/overlay/drop_bridge.py")
+
+ print(f"platform: {sys.platform} python: {sys.version.split()[0]}")
+
+ # 1. the factory must pick the REAL target (tkdnd binary loaded for this OS)
+ target = dt.make_drop_target()
+ tname = type(target).__name__
+ print(f"factory -> {tname}")
+ if tname != "TkDnDDropTarget":
+ print("FAIL: tkdnd did not load on this OS (got the null fallback).")
+ return 2
+
+ # 2. the path parser
+ parsed = dt._parse_dnd_files("{/a b/x.txt} /c/y.png")
+ print(f"parser -> {parsed}")
+ assert parsed == ["/a b/x.txt", "/c/y.png"], parsed
+
+ # 3. + 4. register on a real bar-like Tk window, then fire the drop chain
+ got: list[tuple] = []
+ db.set_drop_handler(lambda paths, text: got.append((paths, text)))
+ root = tk.Tk()
+ root.overrideredirect(True)
+ try:
+ root.wm_attributes("-transparentcolor", "#ff00ff")
+ except tk.TclError:
+ pass # macOS/Linux may not support color-key; the window is still valid
+ canvas = tk.Canvas(root, width=220, height=44, highlightthickness=0)
+ canvas.pack(fill="both", expand=True)
+ root.update_idletasks()
+ root.update()
+
+ registered = target.register(canvas, db.dispatch_drop)
+ print(f"register -> {registered}")
+ if not registered:
+ # Surface the swallowed tkdnd error so a CI failure is diagnosable
+ # (register() must never raise in production, so it logs at DEBUG).
+ print("register returned False — raw tkdnd diagnostic:")
+ try:
+ import tkinter as _tk
+
+ from tkinterdnd2 import DND_FILES, TkinterDnD
+
+ print(f" Tcl/Tk patchlevel: {root.tk.call('info', 'patchlevel')}")
+ TkinterDnD._require(root)
+ print(" _require OK; trying drop_target_register ...")
+ canvas.drop_target_register(DND_FILES)
+ print(" drop_target_register OK (unexpected success)")
+ except Exception as exc: # noqa: BLE001 — diagnostic only
+ import traceback
+
+ traceback.print_exc()
+ print(f" RAW tkdnd error: {type(exc).__name__}: {exc}")
+ print("FAIL: tkdnd registration failed on this OS.")
+ root.destroy()
+ return 3
+
+ canvas.event_generate("<<Drop>>", data="/etc/hostname")
+ root.update()
+ root.destroy()
+ db.set_drop_handler(None)
+
+ print(f"drop chain fired -> handler got {len(got)} call(s): {got}")
+ if not got:
+ print("FAIL: the <<Drop>> chain did not reach the handler.")
+ return 4
+
+ print("OK: drag-drop works on this OS (load + parse + register + chain).")
+ return 0
+
+
+if __name__ == "__main__":
+ raise SystemExit(main())
diff --git a/scripts/cu_bench.py b/scripts/cu_bench.py
index 25f40037a4..cdf8395124 100644
--- a/scripts/cu_bench.py
+++ b/scripts/cu_bench.py
@@ -25,6 +25,18 @@ Run:
python scripts/cu_bench.py # full curated set
python scripts/cu_bench.py --list # list task ids, run nothing
python scripts/cu_bench.py --only open_terminal,open_calc_compute
+
+A/B latency tuning (the "meter before the dials" — measure, never assume):
+ # 1. Baseline: run once with no overrides, keep the JSON report.
+ python scripts/cu_bench.py
+ # 2. Tuned: lower a knob and re-run; compare wall-clock AND pass-rate.
+ python scripts/cu_bench.py --image-max-dimension 1568 # L7: smaller frames
+ python scripts/cu_bench.py --settle-scale 0.5 # L8: trim settle waits
+ python scripts/cu_bench.py --think-timeout-cap 5.0 # L10: tighter ceiling
+ # ACCEPT a knob only if wall-clock drops AND the pass-rate does NOT (a
+ # faster-but-flakier knob is a regression). The JSON report records the
+ # knob values under "knobs" so two runs are directly comparable. Promote a
+ # validated knob by setting it under [computer_use] in jarvis.toml.
"""
from __future__ import annotations
@@ -427,9 +439,16 @@ def _write_report(results: list[BenchResult], native: bool) -> Path:
return out
-def _write_json_report(results: list[BenchResult], native: bool) -> Path:
+def _write_json_report(
+ results: list[BenchResult], native: bool,
+ knobs: dict[str, object] | None = None,
+) -> Path:
"""Machine-readable run record — the baseline/regression artifact the
- frontier-speed plan's promotion gate compares against."""
+ frontier-speed plan's promotion gate compares against.
+
+ ``knobs`` records the live latency-knob values so a tuned run's JSON is
+ directly comparable against the baseline's (which knob produced the delta).
+ """
all_spans = [s for r in results for s in r.spans]
all_steps = sorted(d for r in results for d in r.step_durations_s)
@@ -440,6 +459,7 @@ def _write_json_report(results: list[BenchResult], native: bool) -> Path:
payload = {
"engine": "native" if native else "hand-rolled-v1",
+ "knobs": knobs or {},
"slo": {"step_p50_s": SLO_STEP_P50_S, "step_p95_s": SLO_STEP_P95_S},
"aggregate": {
"step_p50_s": statistics.median(all_steps) if all_steps else None,
@@ -492,6 +512,48 @@ def _assert_slo(results: list[BenchResult]) -> list[str]:
return violations
+#: CU latency knobs the bench can override on the live context for A/B tuning.
+#: Maps a CLI arg name -> the ComputerUseContext attribute it overrides.
+_KNOB_OVERRIDES: tuple[tuple[str, str], ...] = (
+ ("image_max_dimension", "image_max_dimension"), # L7 longest-side px
+ ("image_max_bytes", "image_max_bytes"), # L7 byte budget
+ ("settle_scale", "settle_scale"), # L8 settle multiplier
+ ("think_timeout_cap", "think_timeout_cap_s"), # L10 model-call ceiling
+)
+
+
+def apply_knob_overrides(ctx: object, args: object) -> list[str]:
+ """Apply ``--<knob>`` CLI overrides onto the live CU context for A/B tuning.
+
+ The ComputerUseContext is a mutable dataclass whose latency knobs the loop
+ reads per mission, so setting them here makes the whole bench run use the
+ tuned value. Returns a human-readable list of the overrides applied (empty
+ when none were given, i.e. a baseline run). Pure + side-effecting only on
+ ``ctx``; unit-testable with a stub ctx/args.
+ """
+ applied: list[str] = []
+ for arg_name, attr in _KNOB_OVERRIDES:
+ value = getattr(args, arg_name, None)
+ if value is None:
+ continue
+ old = getattr(ctx, attr, None)
+ setattr(ctx, attr, value)
+ applied.append(f"{attr}: {old} -> {value}")
+ return applied
+
+
+def _knob_snapshot(ctx: object) -> dict[str, object]:
+ """The live latency-knob values, recorded in the JSON report so two runs
+ (baseline vs. tuned) are comparable."""
+ return {
+ "image_max_dimension": getattr(ctx, "image_max_dimension", None),
+ "image_max_bytes": getattr(ctx, "image_max_bytes", None),
+ "settle_scale": getattr(ctx, "settle_scale", None),
+ "think_timeout_cap_s": getattr(ctx, "think_timeout_cap_s", None),
+ "fast_step_model": getattr(ctx, "fast_step_model", None),
+ }
+
+
async def main() -> int:
parser = argparse.ArgumentParser(description="Everyday Computer-Use benchmark")
parser.add_argument("--list", action="store_true", help="list task ids and exit")
@@ -501,6 +563,25 @@ async def main() -> int:
help="exit non-zero when the frontier-speed SLOs are violated "
"(step p50/p95 + per-task wall-clock budgets)",
)
+ # CU latency knob overrides (A/B tuning vs. the baseline trace). Each is a
+ # ComputerUseContext field the loop reads per mission; lower them, re-run,
+ # and compare wall-clock AND success-rate against the unmodified baseline.
+ parser.add_argument(
+ "--image-max-dimension", type=int, default=None,
+ help="L7: longest-side px cap on the screenshot (e.g. 1568; default 2048)",
+ )
+ parser.add_argument(
+ "--image-max-bytes", type=int, default=None,
+ help="L7: per-screenshot byte budget (e.g. 200000; default 300000)",
+ )
+ parser.add_argument(
+ "--settle-scale", type=float, default=None,
+ help="L8: multiplier on fixed settle waits (e.g. 0.5; default 1.0)",
+ )
+ parser.add_argument(
+ "--think-timeout-cap", type=float, default=None,
+ help="L10: ceiling on a single model call in s (e.g. 5.0; default 10.0)",
+ )
args = parser.parse_args()
catalog = _catalog()
@@ -535,6 +616,12 @@ async def main() -> int:
native = getattr(ctx, "native_cu", None) is not None
print(f"[1] CU tools: {sorted((ctx.tools or {}).keys())}")
print(f"[1] native Gemini engine: {'ENABLED' if native else 'off (hand-rolled)'}")
+ overrides = apply_knob_overrides(ctx, args)
+ if overrides:
+ print(f"[1] knob overrides (A/B tuning): {'; '.join(overrides)}")
+ else:
+ print("[1] knobs: baseline (no overrides)")
+ knobs = _knob_snapshot(ctx)
harness = ComputerUseHarness()
if not await harness.health():
@@ -548,7 +635,7 @@ async def main() -> int:
passed = sum(1 for r in results if r.passed)
report = _write_report(results, native)
- json_report = _write_json_report(results, native)
+ json_report = _write_json_report(results, native, knobs)
print("\n" + "=" * 66)
print(f"SCORE: {passed}/{len(results)} passed (report: {report})")
print(f"JSON: {json_report}")
diff --git a/tests/contract/test_ack_provider_protocol.py b/tests/contract/test_ack_provider_protocol.py
index 416b8d4fec..860f52546c 100644
--- a/tests/contract/test_ack_provider_protocol.py
+++ b/tests/contract/test_ack_provider_protocol.py
@@ -28,7 +28,6 @@ import pytest
from jarvis.brain.ack_brain.config import (
GeminiAckProviderConfig,
- GrokAckProviderConfig,
OllamaAckProviderConfig,
OpenAIAckProviderConfig,
)
@@ -36,7 +35,6 @@ from jarvis.brain.ack_brain.providers import (
REGISTRY,
AbstractAckProvider,
GeminiFlashAck,
- GrokFlashAck,
OllamaFlashAck,
OpenAIMiniAck,
)
@@ -53,11 +51,6 @@ def _config_for(provider_name: str) -> Any:
return GeminiAckProviderConfig(
model="gemini-3.1-flash", max_output_tokens=_MAX_TOKENS_FIXTURE
)
- if provider_name == "grok":
- return GrokAckProviderConfig(
- model="grok-4-fast-non-reasoning",
- max_output_tokens=_MAX_TOKENS_FIXTURE,
- )
if provider_name == "openai":
return OpenAIAckProviderConfig(
model="gpt-5-mini", max_output_tokens=_MAX_TOKENS_FIXTURE
@@ -181,8 +174,8 @@ class _FakeAsyncHTTPClient:
def _install_openai_fake(monkeypatch: pytest.MonkeyPatch) -> _FakeOpenAIClient:
"""Install a fake ``openai.AsyncOpenAI`` module-level constructor.
- Both the Grok adapter and the OpenAI adapter import
- ``from openai import AsyncOpenAI`` lazily inside ``_ensure_client``.
+ The OpenAI adapter imports ``from openai import AsyncOpenAI`` lazily
+ inside ``_ensure_client``.
"""
fake_client = _FakeOpenAIClient()
@@ -283,7 +276,7 @@ def _wire_adapter(
else None
),
)
- if provider_name in ("grok", "openai"):
+ if provider_name == "openai":
fake = _install_openai_fake(monkeypatch)
_install_secret_fake(monkeypatch)
adapter = cls(config)
@@ -344,7 +337,7 @@ def test_every_adapter_satisfies_abstract_protocol(
def test_registry_contains_all_known_adapter_classes() -> None:
"""Adapter classes are also directly importable — sanity guard against
accidental removal from the package ``__all__``."""
- expected = {GeminiFlashAck, GrokFlashAck, OpenAIMiniAck, OllamaFlashAck}
+ expected = {GeminiFlashAck, OpenAIMiniAck, OllamaFlashAck}
assert set(REGISTRY.values()) == expected
diff --git a/tests/fakes/fake_pty_backend.py b/tests/fakes/fake_pty_backend.py
index 7ca8160684..c51d23485f 100644
--- a/tests/fakes/fake_pty_backend.py
+++ b/tests/fakes/fake_pty_backend.py
@@ -86,9 +86,10 @@ class FakePtyBackend:
cwd: str | None,
cols: int,
rows: int,
+ env: object | None = None,
) -> FakePtyHandle:
self.spawn_calls.append(
- {"argv": argv, "cwd": cwd, "cols": cols, "rows": rows}
+ {"argv": argv, "cwd": cwd, "cols": cols, "rows": rows, "env": env}
)
handle = FakePtyHandle(pid=self._pid, exitstatus=self._exitstatus)
self.last_handle = handle
@@ -116,12 +117,13 @@ class FakeBytesPtyProcess:
self._alive = True
@classmethod
- def spawn(cls, argv, cwd=None, dimensions=None): # noqa: ANN001
+ def spawn(cls, argv, cwd=None, dimensions=None, env=None): # noqa: ANN001
inst = cls()
FakeBytesPtyProcess.last_spawn = {
"argv": argv,
"cwd": cwd,
"dimensions": dimensions,
+ "env": env,
}
return inst
diff --git a/tests/integration/test_ack_provider_swap.py b/tests/integration/test_ack_provider_swap.py
index 769d21bb4f..e11bd24d18 100644
--- a/tests/integration/test_ack_provider_swap.py
+++ b/tests/integration/test_ack_provider_swap.py
@@ -5,7 +5,7 @@ The Flash-Brain provider is chosen at startup via
``brain.primary`` via the ``"follow_brain"`` meta-value). These tests
cover the spec's §8 "Provider swap" cases:
-1. Config change ``gemini`` → ``grok`` → next ack uses the Grok adapter.
+1. Config change ``gemini`` → ``openai`` → next ack uses the OpenAI adapter.
2. Provider with missing API key surfaces a clear error path: the
adapter returns ``None`` and the AckGenerator increments the
``ack_provider_error_total`` counter.
@@ -52,11 +52,11 @@ def _jcfg(
# ---------------------------------------------------------------------------
-# Case 1: gemini → grok config swap
+# Case 1: gemini → openai config swap
# ---------------------------------------------------------------------------
-def test_config_swap_gemini_to_grok_rebuilds_with_grok_adapter() -> None:
+def test_config_swap_gemini_to_openai_rebuilds_with_openai_adapter() -> None:
"""A second build_ack_brain() call with a new provider rebuilds the
AckGenerator around the new adapter class — no stale adapter instance."""
first = build_ack_brain(_jcfg(provider="gemini"))
@@ -64,11 +64,11 @@ def test_config_swap_gemini_to_grok_rebuilds_with_grok_adapter() -> None:
assert first._provider_name == "gemini"
assert type(first._provider).__name__ == "GeminiFlashAck"
- # User edits jarvis.toml: [ack_brain].provider = "grok"
- second = build_ack_brain(_jcfg(provider="grok"))
+ # User edits jarvis.toml: [ack_brain].provider = "openai"
+ second = build_ack_brain(_jcfg(provider="openai"))
assert second is not None
- assert second._provider_name == "grok"
- assert type(second._provider).__name__ == "GrokFlashAck"
+ assert second._provider_name == "openai"
+ assert type(second._provider).__name__ == "OpenAIMiniAck"
# The two builds returned distinct AckGenerator instances.
assert first is not second
@@ -83,14 +83,14 @@ def test_follow_brain_tracks_primary_provider_swap(caplog: pytest.LogCaptureFixt
)
jcfg_b = SimpleNamespace(
ack_brain=make_ack_config(provider="follow_brain"),
- brain=SimpleNamespace(primary="grok"),
+ brain=SimpleNamespace(primary="openai"),
)
with caplog.at_level(logging.INFO):
ack_a = build_ack_brain(jcfg_a)
ack_b = build_ack_brain(jcfg_b)
assert ack_a is not None and ack_b is not None
assert ack_a._provider_name == "gemini"
- assert ack_b._provider_name == "grok"
+ assert ack_b._provider_name == "openai"
# ---------------------------------------------------------------------------
diff --git a/tests/integration/test_agent_instructions_routes.py b/tests/integration/test_agent_instructions_routes.py
new file mode 100644
index 0000000000..cb4bec2e9f
--- /dev/null
+++ b/tests/integration/test_agent_instructions_routes.py
@@ -0,0 +1,91 @@
+"""Integration tests for /api/settings/agent-instructions.
+
+The "Agent Instructions" view reads the user's standing-instructions file, saves
+it, and clears it through these three endpoints. The file is named after the
+assistant (e.g. Ruben.md); reset is a delete.
+"""
+from __future__ import annotations
+
+from collections.abc import Iterator
+
+import pytest
+from fastapi.testclient import TestClient
+
+import jarvis.core.config as core_config
+from jarvis.brain import agent_instructions
+from jarvis.core.bus import EventBus
+from jarvis.core.config import JarvisConfig
+from jarvis.ui.web.server import WebServer
+
+
[email protected](autouse=True)
+def _isolate_data_dir(tmp_path, monkeypatch: pytest.MonkeyPatch) -> None:
+ monkeypatch.setattr(core_config, "DATA_DIR", tmp_path)
+
+
+def server() -> Iterator[WebServer]:
+ cfg = JarvisConfig()
+ cfg.ui.dev_mode = True
+ bus = EventBus()
+ s = WebServer(cfg, bus=bus)
+ s.app.state.config = cfg
+ s.app.state.bus = bus
+ yield s
+
+
+def _expected_filename(server: WebServer) -> str:
+ return agent_instructions.instructions_filename(server.app.state.config)
+
+
+def test_get_returns_empty_with_filename_and_template(server: WebServer) -> None:
+ with TestClient(server.app) as client:
+ resp = client.get("/api/settings/agent-instructions")
+ assert resp.status_code == 200
+ body = resp.json()
+ assert body["exists"] is False
+ assert body["content"] == ""
+ assert body["filename"] == _expected_filename(server)
+ assert body["filename"].endswith(".md")
+ assert body["template"].strip() # a starter template is offered
+ assert body["char_count"] == 0
+
+
+def test_put_saves_and_get_reflects_it(server: WebServer) -> None:
+ with TestClient(server.app) as client:
+ resp = client.put(
+ "/api/settings/agent-instructions",
+ json={"content": "Be terse. Answer in German."},
+ )
+ assert resp.status_code == 200
+ assert resp.json()["exists"] is True
+ assert resp.json()["restart_required"] is False
+
+ got = client.get("/api/settings/agent-instructions").json()
+ assert got["exists"] is True
+ assert got["content"] == "Be terse. Answer in German."
+ assert got["char_count"] == len("Be terse. Answer in German.")
+
+
+def test_put_rejects_empty_content(server: WebServer) -> None:
+ with TestClient(server.app) as client:
+ resp = client.put("/api/settings/agent-instructions", json={"content": " \n "})
+ assert resp.status_code == 400
+ assert agent_instructions.has_agent_instructions(server.app.state.config) is False
+
+
+def test_delete_clears_and_is_idempotent(server: WebServer) -> None:
+ with TestClient(server.app) as client:
+ client.put("/api/settings/agent-instructions", json={"content": "rules"})
+ assert agent_instructions.has_agent_instructions(server.app.state.config) is True
+
+ resp = client.delete("/api/settings/agent-instructions")
+ assert resp.status_code == 200
+ body = resp.json()
+ assert body["exists"] is False
+ assert body["removed"] is True
+ assert agent_instructions.has_agent_instructions(server.app.state.config) is False
+
+ again = client.delete("/api/settings/agent-instructions")
+ assert again.status_code == 200
+ assert again.json()["removed"] is False
diff --git a/tests/integration/test_frontier_autoswitch.py b/tests/integration/test_frontier_autoswitch.py
index 6515b06d3a..da278bd7d2 100644
--- a/tests/integration/test_frontier_autoswitch.py
+++ b/tests/integration/test_frontier_autoswitch.py
@@ -21,12 +21,7 @@ from jarvis.brain.frontier_autoswitch import (
get_pending_switches,
)
from jarvis.core.bus import EventBus
-from jarvis.core.config import (
- BrainConfig,
- BrainProviderConfig,
- BrainTierConfig,
- JarvisConfig,
-)
+from jarvis.core.config import JarvisConfig
from jarvis.core.events import FrontierModelSwitched
@@ -54,12 +49,15 @@ def _make_config_with_old_models() -> JarvisConfig:
cfg = JarvisConfig.model_validate({
"brain": {
"primary": "claude-api",
+ # The auto-switch is opt-in (default False); these tests exercise the
+ # enabled apply path, so turn it on explicitly.
+ "frontier_auto_apply": True,
"providers": {
"gemini": {
"model": "gemini-2.5-flash",
"deep_model": "gemini-2.5-pro",
},
- "grok": {"model": "grok-3"},
+ "openai": {"model": "gpt-5"},
"claude-api": {
"model": "claude-sonnet-4-6",
"deep_model": "claude-opus-4-7",
@@ -110,7 +108,7 @@ async def test_apply_switches_when_resolver_returns_newer_models(
resolver = _StubResolver({
("gemini", "fast"): "gemini-3-flash",
("gemini", "deep"): "gemini-3.1-pro-preview",
- ("grok", "fast"): "grok-4.1-fast",
+ ("openai", "fast"): "gpt-5.5",
("claude-api", "fast"): "claude-sonnet-4-6", # unverändert
("claude-api", "deep"): "claude-opus-4-7", # unverändert
})
@@ -123,19 +121,19 @@ async def test_apply_switches_when_resolver_returns_newer_models(
# Verifiziere dass TOML-Persist auch gerufen wurde (3 Switches → 3 Calls).
assert len(_mock_toml_persist) == 3
persist_providers = {p for p, _ in _mock_toml_persist}
- assert persist_providers == {"gemini", "grok"}
+ assert persist_providers == {"gemini", "openai"}
- # 3 Switches: gemini/fast, gemini/deep, grok/fast.
+ # 3 Switches: gemini/fast, gemini/deep, openai/fast.
assert len(switches) == 3
providers_switched = {(s.provider, s.tier) for s in switches}
assert providers_switched == {
- ("gemini", "fast"), ("gemini", "deep"), ("grok", "fast"),
+ ("gemini", "fast"), ("gemini", "deep"), ("openai", "fast"),
}
# Config tatsaechlich mutiert
assert cfg.brain.providers["gemini"].model == "gemini-3-flash"
assert cfg.brain.providers["gemini"].deep_model == "gemini-3.1-pro-preview"
- assert cfg.brain.providers["grok"].model == "grok-4.1-fast"
+ assert cfg.brain.providers["openai"].model == "gpt-5.5"
# Sub-Jarvis-Override unangetastet
assert cfg.brain.sub_jarvis is not None
@@ -157,13 +155,46 @@ async def test_apply_switches_when_resolver_returns_newer_models(
assert len(pending) == 3
+async def test_disabled_by_default_is_noop(
+ _mock_toml_persist: list[tuple[str, dict[str, str | None]]],
+) -> None:
+ """With ``brain.frontier_auto_apply`` unset (default False) the boot hook is
+ a complete no-op: no resolver call, no TOML/soll persist, no mutation, no
+ event, no pending — even though newer models are available. User mandate
+ 2026-06-20: providers/models must NOT switch by themselves.
+ """
+ cfg = _make_config_with_old_models()
+ # Flip the flag back off — the default the user actually runs with.
+ cfg.brain.frontier_auto_apply = False
+ resolver = _StubResolver({
+ ("gemini", "fast"): "gemini-3-flash",
+ ("gemini", "deep"): "gemini-3.1-pro-preview",
+ ("openai", "fast"): "gpt-5.5",
+ })
+ bus = EventBus()
+ received: list[FrontierModelSwitched] = []
+ bus.subscribe(FrontierModelSwitched, lambda e: received.append(e))
+
+ switches = await apply_frontier_resolution(cfg, resolver, bus)
+
+ assert switches == []
+ assert resolver.calls == [] # resolver never queried
+ assert _mock_toml_persist == [] # nothing persisted to TOML/soll
+ assert cfg.brain.providers["gemini"].model == "gemini-2.5-flash" # unmutated
+ assert get_pending_switches() == []
+ import asyncio
+ await asyncio.sleep(0.01)
+ assert received == []
+
+
@pytest.mark.asyncio
async def test_no_switch_when_models_unchanged() -> None:
cfg = _make_config_with_old_models()
resolver = _StubResolver({
("gemini", "fast"): "gemini-2.5-flash", # gleich
("gemini", "deep"): "gemini-2.5-pro", # gleich
- ("grok", "fast"): "grok-3", # gleich
+ ("openai", "fast"): "gpt-5", # gleich
("claude-api", "fast"): "claude-sonnet-4-6",
("claude-api", "deep"): "claude-opus-4-7",
})
@@ -182,7 +213,7 @@ async def test_no_switch_when_models_unchanged() -> None:
@pytest.mark.asyncio
async def test_resolver_crash_does_not_mutate_config() -> None:
cfg = _make_config_with_old_models()
- original_grok = cfg.brain.providers["grok"].model
+ original_openai = cfg.brain.providers["openai"].model
resolver = _CrashingResolver()
bus = EventBus()
@@ -191,7 +222,7 @@ async def test_resolver_crash_does_not_mutate_config() -> None:
assert switches == []
# Config unveraendert
- assert cfg.brain.providers["grok"].model == original_grok
+ assert cfg.brain.providers["openai"].model == original_openai
@pytest.mark.asyncio
@@ -203,16 +234,16 @@ async def test_resolver_returns_none_no_switch() -> None:
resolver = _StubResolver({
("gemini", "fast"): None, # kein Key
("gemini", "deep"): None,
- ("grok", "fast"): "grok-4.1-fast", # OK
+ ("openai", "fast"): "gpt-5.5", # OK
("claude-api", "fast"): "claude-sonnet-4-6",
("claude-api", "deep"): "claude-opus-4-7",
})
bus = EventBus()
switches = await apply_frontier_resolution(cfg, resolver, bus)
- # Nur grok/fast hat geswitcht
+ # Nur openai/fast hat geswitcht
assert len(switches) == 1
- assert switches[0].provider == "grok"
+ assert switches[0].provider == "openai"
# Gemini unangetastet
assert cfg.brain.providers["gemini"].model == "gemini-2.5-flash"
@@ -223,7 +254,7 @@ async def test_ack_clears_pending() -> None:
resolver = _StubResolver({
("gemini", "fast"): "gemini-3-flash",
("gemini", "deep"): None,
- ("grok", "fast"): None,
+ ("openai", "fast"): None,
("claude-api", "fast"): None,
("claude-api", "deep"): None,
})
diff --git a/tests/integration/test_provider_model_routes.py b/tests/integration/test_provider_model_routes.py
new file mode 100644
index 0000000000..528ecf1e77
--- /dev/null
+++ b/tests/integration/test_provider_model_routes.py
@@ -0,0 +1,314 @@
+"""Integration tests for the per-provider model picker endpoints:
+
+ GET /api/providers/{id}/models — the searchable model list (live catalog)
+ PUT /api/providers/{id}/model — pin a model, live-apply + honest probe
+
+Hermetic: the catalog is an injected fake (no network), the live probe is
+monkeypatched, and the TOML writer is patched so no disk write happens.
+"""
+from __future__ import annotations
+
+from collections.abc import Iterator
+from typing import Any
+
+import pytest
+from fastapi.testclient import TestClient
+
+from jarvis.brain.model_catalog import CatalogResult, ModelInfo
+from jarvis.core.bus import EventBus
+from jarvis.core.config import JarvisConfig
+from jarvis.ui.web.server import WebServer
+
+
+class _FakeCatalog:
+ def __init__(self) -> None:
+ self.calls: list[tuple[str, bool]] = []
+
+ async def list_models(self, provider: str, *, force_refresh: bool = False) -> CatalogResult:
+ self.calls.append((provider, force_refresh))
+ return CatalogResult(
+ provider=provider,
+ models=(
+ ModelInfo(id="gemini-3.1-pro-preview", label="Gemini 3.1 Pro"),
+ ModelInfo(id="gemini-3-flash-preview", label="Gemini 3 Flash"),
+ ),
+ source="live",
+ fetched_at=123.0,
+ )
+
+
+class _FakeBrain:
+ def __init__(self, active: str = "gemini") -> None:
+ self.active_provider = active
+ self.applied: list[tuple[str, str]] = []
+
+ def apply_provider_model(self, provider: str, model: str) -> bool:
+ self.applied.append((provider, model))
+ return provider == self.active_provider
+
+
+def server() -> Iterator[WebServer]:
+ cfg = JarvisConfig()
+ cfg.ui.dev_mode = True
+ srv = WebServer(cfg, bus=EventBus())
+ srv.app.state.config = cfg
+ srv.app.state.model_catalog = _FakeCatalog()
+ srv.app.state.brain = _FakeBrain(active="gemini")
+ yield srv
+
+
+# ── GET /models ──────────────────────────────────────────────────────────────
+
+def test_get_models_returns_catalog(server: WebServer) -> None:
+ with TestClient(server.app) as client:
+ resp = client.get("/api/providers/gemini/models")
+ assert resp.status_code == 200
+ body = resp.json()
+ assert body["provider"] == "gemini"
+ assert body["source"] == "live"
+ ids = [m["id"] for m in body["models"]]
+ assert "gemini-3.1-pro-preview" in ids
+ # current_model falls back to the frontier default when unset.
+ assert body["current_model"]
+
+
+def test_get_models_passes_refresh_flag(server: WebServer) -> None:
+ with TestClient(server.app) as client:
+ client.get("/api/providers/gemini/models?refresh=true")
+ catalog: _FakeCatalog = server.app.state.model_catalog
+ assert catalog.calls[-1] == ("gemini", True)
+
+
+def test_get_models_unknown_provider_404(server: WebServer) -> None:
+ with TestClient(server.app) as client:
+ assert client.get("/api/providers/nope/models").status_code == 404
+
+
+def test_get_models_stt_provider_now_has_catalog(server: WebServer) -> None:
+ with TestClient(server.app) as client:
+ # deepgram is an STT provider — it now exposes a model catalog.
+ resp = client.get("/api/providers/deepgram/models")
+ assert resp.status_code == 200
+
+
+def test_get_models_codex_now_has_catalog(server: WebServer) -> None:
+ with TestClient(server.app) as client:
+ # codex (subscription brain) now exposes a curated model catalog.
+ assert client.get("/api/providers/codex/models").status_code == 200
+
+
+# ── PUT /model ───────────────────────────────────────────────────────────────
+
+def test_put_model_persists_applies_and_probes(
+ server: WebServer, monkeypatch: pytest.MonkeyPatch
+) -> None:
+ writes: list[tuple[str, str | None]] = []
+
+ def _fake_writer(provider: str, *, model: str | None = None, **_k: Any) -> None:
+ writes.append((provider, model))
+
+ monkeypatch.setattr(
+ "jarvis.core.config_writer.set_brain_provider_model", _fake_writer
+ )
+
+ from jarvis.brain import provider_test as pt
+
+ async def _fake_probe(provider: str, model: str, *, timeout_s: float = 20.0):
+ return pt.ProviderTestResult(provider, pt.OK, "", 42.0)
+
+ monkeypatch.setattr("jarvis.ui.web.provider_routes._probe_brain_model", _fake_probe)
+
+ with TestClient(server.app) as client:
+ resp = client.put(
+ "/api/providers/gemini/model",
+ json={"model": "gemini-3.1-pro-preview", "persist": True},
+ )
+ assert resp.status_code == 200
+ body = resp.json()
+ assert body["ok"] is True
+ assert body["model"] == "gemini-3.1-pro-preview"
+ assert body["persisted"] is True
+ assert body["applied_live"] is True # gemini is the active brain
+ assert body["restart_required"] is False
+ assert body["probe"]["status"] == "ok"
+ assert body["probe"]["integration_ok"] is True
+
+ # Persisted to TOML and live-applied to the running brain.
+ assert ("gemini", "gemini-3.1-pro-preview") in writes
+ brain: _FakeBrain = server.app.state.brain
+ assert ("gemini", "gemini-3.1-pro-preview") in brain.applied
+
+
+def test_put_model_inactive_provider_not_live(
+ server: WebServer, monkeypatch: pytest.MonkeyPatch
+) -> None:
+ monkeypatch.setattr(
+ "jarvis.core.config_writer.set_brain_provider_model",
+ lambda *a, **k: None,
+ )
+ from jarvis.brain import provider_test as pt
+
+ async def _fake_probe(provider: str, model: str, *, timeout_s: float = 20.0):
+ return pt.ProviderTestResult(provider, pt.OK, "", 10.0)
+
+ monkeypatch.setattr("jarvis.ui.web.provider_routes._probe_brain_model", _fake_probe)
+
+ with TestClient(server.app) as client:
+ resp = client.put(
+ "/api/providers/openai/model", # active brain is gemini
+ json={"model": "gpt-5.5", "persist": True},
+ )
+ assert resp.status_code == 200
+ body = resp.json()
+ assert body["applied_live"] is False
+ assert body["restart_required"] is False # applies on switch
+
+
+def test_put_model_headless_requires_restart(
+ server: WebServer, monkeypatch: pytest.MonkeyPatch
+) -> None:
+ server.app.state.brain = None # headless: no running brain
+ monkeypatch.setattr(
+ "jarvis.core.config_writer.set_brain_provider_model",
+ lambda *a, **k: None,
+ )
+ from jarvis.brain import provider_test as pt
+
+ async def _fake_probe(provider: str, model: str, *, timeout_s: float = 20.0):
+ return pt.ProviderTestResult(provider, pt.MODEL_UNAVAILABLE, "404 model", 5.0)
+
+ monkeypatch.setattr("jarvis.ui.web.provider_routes._probe_brain_model", _fake_probe)
+
+ with TestClient(server.app) as client:
+ resp = client.put(
+ "/api/providers/gemini/model",
+ json={"model": "gemini-bogus", "persist": True},
+ )
+ assert resp.status_code == 200
+ body = resp.json()
+ assert body["applied_live"] is False
+ assert body["restart_required"] is True
+ # The probe is honest about a non-existent model — saved anyway.
+ assert body["probe"]["status"] == "model_unavailable"
+
+
+def test_put_tts_voice_persists_no_probe(
+ server: WebServer, monkeypatch: pytest.MonkeyPatch
+) -> None:
+ voices: list[str] = []
+ monkeypatch.setattr(
+ "jarvis.core.config_writer.set_tts_voice", lambda v, **k: voices.append(v)
+ )
+ with TestClient(server.app) as client:
+ resp = client.put(
+ "/api/providers/grok-voice/model", # a TTS voice provider
+ json={"model": "rex", "persist": True},
+ )
+ assert resp.status_code == 200
+ body = resp.json()
+ assert body["persisted"] is True
+ assert body["restart_required"] is True # no live pipeline in the test
+ assert body["probe"] is None # TTS does not run a brain probe
+ assert voices == ["rex"]
+
+
+def test_put_stt_model_requires_restart(
+ server: WebServer, monkeypatch: pytest.MonkeyPatch
+) -> None:
+ models: list[str] = []
+ monkeypatch.setattr(
+ "jarvis.core.config_writer.set_stt_model", lambda m, **k: models.append(m)
+ )
+ with TestClient(server.app) as client:
+ resp = client.put(
+ "/api/providers/deepgram/model",
+ json={"model": "nova-3", "persist": True},
+ )
+ assert resp.status_code == 200
+ body = resp.json()
+ assert body["persisted"] is True
+ assert body["restart_required"] is True
+ assert body["probe"] is None
+ assert models == ["nova-3"]
+
+
+# ── GET/PUT /cu-model (Phase 3: selectable Computer-Use model) ────────────────
+
+
+def test_get_cu_model_defaults_to_main(server: WebServer) -> None:
+ with TestClient(server.app) as client:
+ resp = client.get("/api/providers/gemini/cu-model")
+ assert resp.status_code == 200
+ body = resp.json()
+ assert body["provider"] == "gemini"
+ assert body["cu_model"] == "" # nothing pinned
+ assert body["uses_main"] is True
+ assert body["effective_model"] # the model CU would actually use
+
+
+def test_put_cu_model_persists_and_updates_live(
+ server: WebServer, monkeypatch: pytest.MonkeyPatch
+) -> None:
+ writes: list[tuple[str, str | None]] = []
+
+ def _fake_writer(provider: str, *, cu_model: str | None = None, **_k: Any) -> None:
+ writes.append((provider, cu_model))
+
+ monkeypatch.setattr(
+ "jarvis.core.config_writer.set_brain_provider_model", _fake_writer
+ )
+
+ with TestClient(server.app) as client:
+ resp = client.put(
+ "/api/providers/gemini/cu-model",
+ json={"cu_model": "gemini-3.1-pro-preview", "persist": True},
+ )
+ assert resp.status_code == 200
+ body = resp.json()
+ assert body["ok"] is True
+ assert body["cu_model"] == "gemini-3.1-pro-preview"
+ assert body["uses_main"] is False
+ assert body["persisted"] is True
+ assert body["restart_required"] is False
+
+ assert ("gemini", "gemini-3.1-pro-preview") in writes
+ # In-memory cfg updated so the next CU mission uses it without a restart.
+ pc = server.app.state.config.brain.providers["gemini"]
+ assert pc.cu_model == "gemini-3.1-pro-preview"
+
+
+def test_put_cu_model_empty_clears_to_main(
+ server: WebServer, monkeypatch: pytest.MonkeyPatch
+) -> None:
+ from jarvis.core.config import BrainProviderConfig
+
+ server.app.state.config.brain.providers["gemini"] = BrainProviderConfig(
+ model="gemini-3.5-flash", cu_model="gemini-3.1-pro-preview"
+ )
+ writes: list[tuple[str, str | None]] = []
+ monkeypatch.setattr(
+ "jarvis.core.config_writer.set_brain_provider_model",
+ lambda provider, *, cu_model=None, **_k: writes.append((provider, cu_model)),
+ )
+
+ with TestClient(server.app) as client:
+ resp = client.put(
+ "/api/providers/gemini/cu-model", json={"cu_model": "", "persist": True}
+ )
+ assert resp.status_code == 200
+ assert resp.json()["uses_main"] is True
+
+ assert ("gemini", "") in writes
+
+
+def test_cu_model_rejected_for_non_brain_provider(server: WebServer) -> None:
+ with TestClient(server.app) as client:
+ # grok-voice is a TTS provider — Computer-Use model does not apply.
+ assert client.get("/api/providers/grok-voice/cu-model").status_code == 400
+ assert (
+ client.put(
+ "/api/providers/grok-voice/cu-model", json={"cu_model": "x"}
+ ).status_code
+ == 400
+ )
diff --git a/tests/missions/kontrollierer/test_deliverable_paths.py b/tests/missions/kontrollierer/test_deliverable_paths.py
index f5031b853c..ebe2cffed7 100644
--- a/tests/missions/kontrollierer/test_deliverable_paths.py
+++ b/tests/missions/kontrollierer/test_deliverable_paths.py
@@ -19,6 +19,7 @@ from __future__ import annotations
import pytest
from jarvis.missions.kontrollierer.deliverable_paths import (
+ find_generator_scripts,
is_nondeliverable_scratch,
)
@@ -109,3 +110,86 @@ def test_other_browser_profile_roots() -> None:
def test_empty_and_root_paths() -> None:
assert is_nondeliverable_scratch("") is False
assert is_nondeliverable_scratch("/") is False
+
+
+# --- find_generator_scripts: the 2026-06-22 generator-script leak --------------
+# Live forensic (mission_019ef099): the user asked by voice for "one HTML file"
+# and got THREE deliverables — melbourne_guide.html PLUS its Python generator
+# generate_guide.py (which embeds the whole HTML as a string literal and writes
+# the sibling .html) PLUS a hero image. The user opened the .py and "only saw
+# code". A generator/build script is process scratch, not the thing asked for.
+# This filter drops it — but only when the document it emits SURVIVES, so a
+# script the user actually requested is never removed.
+
+
+def _reader(mapping: dict[str, str]):
+ return lambda rel: mapping.get(rel, "")
+
+
+def test_generator_script_emitting_sibling_html_is_detected() -> None:
+ files = ["generate_guide.py", "melbourne_guide.html", "melbourne_hero.jpg"]
+ text = {
+ "generate_guide.py": (
+ 'html_content = """<!DOCTYPE html><html lang="de">...</html>"""\n'
+ 'with open("melbourne_guide.html", "w", encoding="utf-8") as f:\n'
+ " f.write(html_content)\n"
+ ),
+ }
+ assert find_generator_scripts(files, _reader(text)) == frozenset(
+ {"generate_guide.py"}
+ )
+
+
+def test_emitted_doc_and_its_asset_are_never_dropped() -> None:
+ files = ["generate_guide.py", "melbourne_guide.html", "melbourne_hero.jpg"]
+ text = {
+ "generate_guide.py": (
+ '<!DOCTYPE html>\nopen("melbourne_guide.html", "w").write(page)\n'
+ )
+ }
+ gen = find_generator_scripts(files, _reader(text))
+ assert "melbourne_guide.html" not in gen # the real deliverable survives
+ assert "melbourne_hero.jpg" not in gen # its asset survives
+
+
+def test_standalone_script_with_no_sibling_doc_is_kept() -> None:
+ # The user asked FOR a script — nothing it emits is in the set, so it must
+ # never be classified as scratch (the never-drop-a-deliverable guarantee).
+ files = ["scraper.py", "requirements.txt"]
+ text = {"scraper.py": 'import requests\nopen("out.txt", "w").write(r.text)\n'}
+ assert find_generator_scripts(files, _reader(text)) == frozenset()
+
+
+def test_script_only_reading_a_doc_is_not_a_generator() -> None:
+ # Reading an HTML (mode 'r') is not generating it.
+ files = ["lint.py", "page.html"]
+ text = {"lint.py": 'open("page.html", "r").read() # validate markup\n'}
+ assert find_generator_scripts(files, _reader(text)) == frozenset()
+
+
+def test_two_scripts_importing_each_other_are_kept() -> None:
+ files = ["main.py", "utils.py"]
+ text = {"main.py": "import utils\nutils.run()\n", "utils.py": "def run():\n pass\n"}
+ assert find_generator_scripts(files, _reader(text)) == frozenset()
+
+
+def test_generator_detected_via_embedded_markup_literal() -> None:
+ # A build.js that references index.html and embeds the doctype literal is a
+ # generator even when the write call is obscured (template engine, etc.).
+ files = ["build.js", "index.html"]
+ text = {"build.js": "const page = `<!DOCTYPE html><html></html>`; // index.html\n"}
+ assert find_generator_scripts(files, _reader(text)) == frozenset({"build.js"})
+
+
+def test_no_document_in_set_means_no_generators() -> None:
+ # Without any document target, there is nothing to generate -> empty result,
+ # never leaving the user with nothing.
+ files = ["only.py", "data.bin"]
+ text = {"only.py": 'open("only.html", "w").write("<html>")'}
+ assert find_generator_scripts(files, _reader(text)) == frozenset()
+
+
+def test_windows_backslash_rels_are_handled() -> None:
+ files = [r"src\gen.py", r"out\report.html"]
+ text = {r"src\gen.py": '<!DOCTYPE html>\nopen("report.html", "w").write(x)\n'}
+ assert find_generator_scripts(files, _reader(text)) == frozenset({r"src\gen.py"})
diff --git a/tests/missions/kontrollierer/test_loop.py b/tests/missions/kontrollierer/test_loop.py
index f35c4034a0..86b3d18020 100644
--- a/tests/missions/kontrollierer/test_loop.py
+++ b/tests/missions/kontrollierer/test_loop.py
@@ -28,6 +28,7 @@ from jarvis.missions.kontrollierer.orchestrator import (
Kontrollierer,
TaskOutcome,
)
+from jarvis.missions.kontrollierer.worker_prompt import ARTIFACT_LANGUAGE_DIRECTIVE
from jarvis.missions.manager import MissionManager
from jarvis.missions.state_machine import MissionState
from jarvis.missions.workers.base import SpawnedWorker
@@ -1394,3 +1395,37 @@ async def test_desktop_launch_evidence_reaches_critic_as_nonempty_diff(
assert "(command succeeded; no output captured)" in reviewed_diff
# And that augmented diff is NOT considered empty (no blind veto).
assert not _real_diff_is_empty(reviewed_diff)
+
+
+async def test_worker_prompt_carries_artifact_language_directive(
+ manager: MissionManager, tmp_path: Path
+) -> None:
+ """Every dispatched worker prompt leads with the English-artifact directive.
+
+ Root-cause guard (2026-06-22): a German mission used to hand the worker a
+ purely German prompt, so the worker wrote German code. The orchestrator must
+ prepend ARTIFACT_LANGUAGE_DIRECTIVE to the worker prompt for EVERY step,
+ while keeping the step instruction intact (the directive is additive)."""
+ worker = FakeWorker()
+ critic = FakeCriticRunner(_make_approve_verdict())
+ plan = MissionPlan(
+ steps=[Step(slug="html", prompt="Erstelle eine HTML-Seite namens test.html")],
+ n_workers=1,
+ expected_output="x",
+ )
+ k = _make_kontrollierer(
+ manager=manager,
+ tmp_path=tmp_path,
+ critic=critic,
+ worker_factory_fn=lambda step: worker,
+ decomposer_plan=plan,
+ )
+ mid = await manager.dispatch(prompt="Erstelle eine HTML-Seite namens test.html")
+ await k.run_mission(mid)
+
+ assert worker.spawn_calls, "worker was never spawned"
+ prompt = worker.spawn_calls[0]["prompt"]
+ assert ARTIFACT_LANGUAGE_DIRECTIVE in prompt
+ # The step instruction survives — the directive is prepended, not a replacement.
+ assert "test.html" in prompt
diff --git a/tests/missions/kontrollierer/test_worker_prompt.py b/tests/missions/kontrollierer/test_worker_prompt.py
new file mode 100644
index 0000000000..47f1b88105
--- /dev/null
+++ b/tests/missions/kontrollierer/test_worker_prompt.py
@@ -0,0 +1,132 @@
+"""Tests for the worker-prompt composer + the artifact-language directive.
+
+Root cause (2026-06-22): nothing in the mission-dispatch chain ever told the
+worker to produce English code artifacts. The mission prompt is mostly German
+(the user speaks German, ``spawn_worker`` wraps it with German labels), so the
+worker naturally wrote German identifiers/comments/docstrings — violating the
+repo Output Language Policy ("every artifact an agent produces is English").
+
+The fix injects ``ARTIFACT_LANGUAGE_DIRECTIVE`` at the single guaranteed
+chokepoint (``orchestrator._run_iterations`` builds the ``worker_prompt`` for
+every worker, every iteration, every decomposition path) via
+``compose_worker_prompt``. These tests pin that composer's contract.
+"""
+from __future__ import annotations
+
+from jarvis.missions.kontrollierer.worker_prompt import (
+ ARTIFACT_LANGUAGE_DIRECTIVE,
+ OUTPUT_SHAPE_DIRECTIVE,
+ compose_worker_prompt,
+)
+
+# --- The directive itself -----------------------------------------------------
+
+
+def test_directive_mandates_english_for_code_artifacts() -> None:
+ text = ARTIFACT_LANGUAGE_DIRECTIVE.lower()
+ assert "english" in text
+ # It must name the code-artifact surfaces it governs, not just "be English".
+ assert "comment" in text
+ assert "identifier" in text or "docstring" in text
+
+
+def test_directive_is_language_independent_not_a_de_en_toggle() -> None:
+ # The leak was: German request -> German code. The directive must hold
+ # REGARDLESS of the request language, so it cannot be a "de/en" branch.
+ text = ARTIFACT_LANGUAGE_DIRECTIVE.lower()
+ assert "even" in text or "regardless" in text
+
+
+def test_directive_preserves_user_facing_content_exception() -> None:
+ # The user explicitly said: sometimes German is correct. A generated
+ # German news page or quoted text must stay German — only code artifacts
+ # default to English.
+ text = ARTIFACT_LANGUAGE_DIRECTIVE.lower()
+ assert "user-facing" in text or "content" in text
+ assert "explicit" in text or "request" in text
+
+
+# --- OUTPUT_SHAPE_DIRECTIVE ---------------------------------------------------
+# Root cause (2026-06-22, mission 019ef052): the user asked for a SINGLE HTML
+# file; the worker shipped four (index.html + app.js + styles.css + assets/).
+# The standing _QUALITY_DIRECTIVE ("never downgrade to a minimal version,
+# skeleton is a floor not a ceiling") reads a single self-contained file as a
+# forbidden minimal version, so the worker built the "production-quality" norm
+# of a split multi-file project. Nothing in the chain told the worker to honor
+# an explicit form/shape constraint. This directive is that missing layer.
+
+
+def test_shape_directive_honors_explicit_single_file_constraint() -> None:
+ text = OUTPUT_SHAPE_DIRECTIVE.lower()
+ # The canonical case that broke: "a single (HTML) file".
+ assert "single" in text
+ assert "file" in text
+ # It must frame the requested shape as a requirement to follow exactly,
+ # not an optional preference.
+ assert "honor" in text or "honour" in text or "exactly" in text
+
+
+def test_shape_directive_says_honoring_a_constraint_is_not_a_downgrade() -> None:
+ # The whole point: neutralize the _QUALITY_DIRECTIVE's "never downgrade to
+ # minimal" pull, which otherwise treats a single-file deliverable as a
+ # forbidden minimal/stub version.
+ text = OUTPUT_SHAPE_DIRECTIVE.lower()
+ assert "downgrade" in text
+ assert "stub" in text or "minimal" in text
+
+
+def test_shape_directive_is_a_default_keeping_judgment_when_unconstrained() -> None:
+ # No explicit shape constraint -> the worker keeps professional judgment for
+ # packaging; the directive must NOT force everything into one file always.
+ text = OUTPUT_SHAPE_DIRECTIVE.lower()
+ assert "judgment" in text or "judgement" in text
+
+
+def test_shape_directive_is_provider_and_language_agnostic() -> None:
+ # Like the language directive, it must hold regardless of request language /
+ # which worker CLI runs — no de/en toggle, no provider name.
+ text = OUTPUT_SHAPE_DIRECTIVE.lower()
+ for banned in ("claude", "gemini", "codex", "grok", "anthropic", "openai"):
+ assert banned not in text
+
+
+def test_compose_includes_output_shape_directive() -> None:
+ out = compose_worker_prompt("", "Make a single HTML file about moving to SF")
+ assert OUTPUT_SHAPE_DIRECTIVE in out
+
+
+def test_compose_orders_both_directives_before_the_step() -> None:
+ step = "Mach mir eine einzige, in sich geschlossene HTML-Datei."
+ out = compose_worker_prompt("", step)
+ assert OUTPUT_SHAPE_DIRECTIVE in out
+ assert ARTIFACT_LANGUAGE_DIRECTIVE in out
+ assert out.index(OUTPUT_SHAPE_DIRECTIVE) < out.index(step)
+ assert out.index(ARTIFACT_LANGUAGE_DIRECTIVE) < out.index(step)
+
+
+# --- compose_worker_prompt ----------------------------------------------------
+
+
+def test_compose_puts_directive_before_the_step_prompt() -> None:
+ step = "Erstelle ein sinnvolles HTML-Grundgeruest."
+ out = compose_worker_prompt("", step)
+ assert ARTIFACT_LANGUAGE_DIRECTIVE in out
+ assert step in out
+ assert out.index(ARTIFACT_LANGUAGE_DIRECTIVE) < out.index(step)
+
+
+def test_compose_keeps_prior_reflections_and_orders_directive_first() -> None:
+ prior = "PRIOR CRITIC FEEDBACK: the previous attempt left a stub."
+ step = "Finish the deliverable."
+ out = compose_worker_prompt(prior, step)
+ # All three present, directive first, step last.
+ assert ARTIFACT_LANGUAGE_DIRECTIVE in out
+ assert prior in out
+ assert step in out
+ assert out.index(ARTIFACT_LANGUAGE_DIRECTIVE) < out.index(prior) < out.index(step)
+
+
+def test_compose_without_prior_block_has_no_dangling_separator() -> None:
+ out = compose_worker_prompt("", "do the thing")
+ assert "\n\n\n" not in out
+ assert out.strip() == out
diff --git a/tests/missions/test_env.py b/tests/missions/test_env.py
index e45a0cee95..4434d72fb9 100644
--- a/tests/missions/test_env.py
+++ b/tests/missions/test_env.py
@@ -41,10 +41,12 @@ def test_allowlist_vars_passed_through(tmp_path: Path) -> None:
with patch.dict("os.environ", fake_env, clear=True):
env = build_worker_env(run_dir=tmp_path)
- for key in (
- "PATH", "SystemRoot", "TEMP", "USERPROFILE", "LOCALAPPDATA", "APPDATA",
- ):
+ for key in ("SystemRoot", "TEMP", "USERPROFILE", "LOCALAPPDATA", "APPDATA"):
assert env[key] == fake_env[key]
+ # PATH is forwarded but may be additively repaired on Windows (essential
+ # System32 / Node.js dirs appended when missing). The original entries are
+ # always preserved, in order, at the front — never dropped or reordered.
+ assert env["PATH"].startswith(fake_env["PATH"])
def test_appdata_is_passed_through(tmp_path: Path) -> None:
@@ -529,3 +531,97 @@ def test_classic_api_key_does_not_set_claude_code_oauth_token(tmp_path: Path) ->
)
assert "CLAUDE_CODE_OAUTH_TOKEN" not in env
assert env.get("ANTHROPIC_API_KEY") == "sk-ant-api03-classic1234567890"
+
+
+# --- DEGRADED-LAUNCH PATH REPAIR (live incident 2026-06-20) -----------------
+#
+# jarvis was launched by an agent runtime (hermes-agent) with a PATH that did
+# NOT contain the Node.js dir. build_worker_env forwarded that broken PATH
+# verbatim, so the codex worker's `codex.CMD` shim resolved bare `node` via PATH,
+# cmd.exe failed "'node' is not recognized" and exited 1 in ~25 ms — every
+# mission died `task_error` ("Der Worker ist abgebrochen."). The env builder must
+# ADDITIVELY repair the worker PATH (never reorder/drop) so essential System32 /
+# Node.js dirs are always present, and forward ComSpec/PATHEXT so .cmd shims and
+# `chcp` resolve regardless of how jarvis itself was launched.
+
+import sys # noqa: E402
+
+from jarvis.missions.isolation.env import _repair_windows_worker_path # noqa: E402
+
+
+def test_repair_path_appends_system32_when_missing() -> None:
+ repaired = _repair_windows_worker_path(
+ r"C:\some\dir", environ={"SystemRoot": r"C:\Windows"}, node_exe=None
+ )
+ parts = [p.rstrip("\\").lower() for p in repaired.split(";")]
+ assert r"c:\windows\system32" in parts, repaired
+
+
+def test_repair_path_appends_node_dir_when_missing() -> None:
+ repaired = _repair_windows_worker_path(
+ r"C:\some\dir",
+ environ={"SystemRoot": r"C:\Windows"},
+ node_exe=r"C:\Program Files\nodejs\node.exe",
+ )
+ assert r"c:\program files\nodejs" in repaired.lower(), repaired
+
+
+def test_repair_path_is_additive_and_preserves_leading_entries() -> None:
+ repaired = _repair_windows_worker_path(
+ r"C:\keep\me;C:\and\me", environ={"SystemRoot": r"C:\Windows"}, node_exe=None
+ )
+ assert repaired.startswith(r"C:\keep\me;C:\and\me"), repaired
+
+
+def test_repair_path_does_not_duplicate_existing_system32() -> None:
+ p = r"C:\Windows\System32;C:\other"
+ repaired = _repair_windows_worker_path(
+ p, environ={"SystemRoot": r"C:\Windows"}, node_exe=None
+ )
+ count = sum(
+ 1 for x in repaired.split(";") if x.rstrip("\\").lower() == r"c:\windows\system32"
+ )
+ assert count == 1, repaired
+
+
[email protected](sys.platform != "win32", reason="Windows PATH repair only")
+def test_build_worker_env_repairs_broken_path_and_forwards_comspec(
+ tmp_path: Path, monkeypatch
+) -> None:
+ """End-to-end: a degraded inherited PATH (no System32, no node) yields a
+ worker PATH that DOES contain both, plus ComSpec/PATHEXT forwarded."""
+ from jarvis.missions.isolation import env as env_mod
+
+ monkeypatch.setattr(
+ env_mod, "resolve_node_executable",
+ lambda: r"C:\Program Files\nodejs\node.exe",
+ )
+ fake = {
+ "PATH": r"C:\Users\X\AppData\Local\hermes\bin",
+ "SystemRoot": r"C:\Windows",
+ "APPDATA": r"C:\Users\X\AppData\Roaming",
+ "ComSpec": r"C:\Windows\System32\cmd.exe",
+ "PATHEXT": ".COM;.EXE;.BAT;.CMD",
+ }
+ with patch.dict("os.environ", fake, clear=True):
+ env = build_worker_env(run_dir=tmp_path)
+
+ pl = env["PATH"].lower()
+ assert r"\windows\system32" in pl, env["PATH"]
+ assert r"\nodejs" in pl, env["PATH"]
+ assert env["PATH"].startswith(fake["PATH"]), "original PATH must stay at front"
+ assert env.get("ComSpec") == r"C:\Windows\System32\cmd.exe"
+ assert env.get("PATHEXT") == ".COM;.EXE;.BAT;.CMD"
+
+
+def test_build_worker_env_leaves_posix_path_untouched(
+ tmp_path: Path, monkeypatch
+) -> None:
+ """Cross-platform doctrine: the Windows-shaped PATH repair must NOT run on
+ POSIX (a Linux VPS PATH must arrive verbatim)."""
+ from jarvis.missions.isolation import env as env_mod
+
+ monkeypatch.setattr(env_mod, "_worker_path_repair_is_windows", lambda: False)
+ with patch.dict("os.environ", {"PATH": "/usr/bin:/bin"}, clear=True):
+ env = build_worker_env(run_dir=tmp_path)
+ assert env["PATH"] == "/usr/bin:/bin"
diff --git a/tests/missions/test_provider_chain_argv.py b/tests/missions/test_provider_chain_argv.py
index 9d3b737b76..8b866f6b86 100644
--- a/tests/missions/test_provider_chain_argv.py
+++ b/tests/missions/test_provider_chain_argv.py
@@ -110,8 +110,8 @@ def test_build_openclaw_cmd_accepts_string_binary_legacy() -> None:
"Create hello.py",
binary="C:/npm/openclaw.cmd",
session_id="s-1",
- openclaw_slug="xai",
- model="grok-4.3",
+ openclaw_slug="google",
+ model="gemini-3.1-pro-preview",
timeout_s=600.0,
)
@@ -120,7 +120,7 @@ def test_build_openclaw_cmd_accepts_string_binary_legacy() -> None:
assert "--message" in cmd
assert cmd[cmd.index("--message") + 1] == "Create hello.py"
assert "--model" in cmd
- assert cmd[cmd.index("--model") + 1] == "xai/grok-4.3"
+ assert cmd[cmd.index("--model") + 1] == "google/gemini-3.1-pro-preview"
def test_build_openclaw_cmd_accepts_argv_prefix_list() -> None:
@@ -131,8 +131,8 @@ def test_build_openclaw_cmd_accepts_argv_prefix_list() -> None:
"Create hello.py with print('hi')",
binary=["C:/Program Files/nodejs/node.exe", "C:/npm/openclaw.mjs"],
session_id="s-2",
- openclaw_slug="xai",
- model="grok-4.3",
+ openclaw_slug="google",
+ model="gemini-3.1-pro-preview",
timeout_s=600.0,
)
@@ -151,8 +151,8 @@ def test_build_openclaw_cmd_extra_args_appended_after_timeout() -> None:
"p",
binary=["node", "openclaw.mjs"],
session_id="s",
- openclaw_slug="xai",
- model="grok-4.3",
+ openclaw_slug="google",
+ model="gemini-3.1-pro-preview",
timeout_s=10.0,
extra_args=("--verbose", "--max-tokens", "4096"),
)
diff --git a/tests/missions/test_worktree.py b/tests/missions/test_worktree.py
index 54ad12c5fa..2df3466934 100644
--- a/tests/missions/test_worktree.py
+++ b/tests/missions/test_worktree.py
@@ -175,6 +175,71 @@ def test_lean_workspace_written_file_shows_in_capture_diff_sequence(
assert "Headlines" in diff.stdout
+def test_lean_workspace_excludes_node_modules_from_diff_capture(
+ manager: WorktreeManager,
+) -> None:
+ """Regenerable dependency trees (node_modules/) MUST be excluded from the
+ lean workspace so the per-iteration ``git add -A .`` does not have to stat
+ tens of thousands of files.
+
+ Live forensic (mission 019ee416, 2026-06-20): a worker installed Remotion
+ into the lean workspace, built a complete promo video, but every
+ ``_capture_diff`` call ran ``git add -A`` into a 10 s timeout walking
+ node_modules -> empty diff -> "no usable output" -> the finished build was
+ discarded and rmtree-d. Excluding node_modules keeps the add cheap; the
+ real deliverable still shows up.
+ """
+ workspace = manager.create(
+ mission_slug="vid", task_id="01-video", needs_repo=False
+ )
+ # Simulate `npm install`: a dependency tree the worker created.
+ nm = workspace / "node_modules" / "remotion"
+ nm.mkdir(parents=True)
+ (nm / "index.js").write_text("module.exports = {}\n", encoding="utf-8")
+ # A real deliverable written next to it.
+ (workspace / "Root.tsx").write_text(
+ "export const Root = () => null\n", encoding="utf-8"
+ )
+
+ add = _git_out(["add", "-A", "."], workspace)
+ assert add.returncode == 0, f"git add failed: {add.stderr!r}"
+ diff = _git_out(["diff", "--cached", "HEAD"], workspace)
+ assert diff.returncode == 0, f"git diff failed: {diff.stderr!r}"
+ # The deliverable is captured for the Critic...
+ assert "Root.tsx" in diff.stdout, f"deliverable missing: {diff.stdout!r}"
+ # ...but the regenerable dependency tree is NOT staged.
+ assert "node_modules" not in diff.stdout, (
+ f"node_modules leaked into the diff: {diff.stdout!r}"
+ )
+
+
+def test_lean_workspace_excludes_python_and_build_caches(
+ manager: WorktreeManager,
+) -> None:
+ """The same exclusion covers the other regenerable heavyweights a worker
+ can spawn (Python venvs, bytecode caches, package-manager stores) so a
+ `pip install` / `npm ci` task does not hit the same git-add timeout."""
+ workspace = manager.create(
+ mission_slug="py", task_id="01-pytask", needs_repo=False
+ )
+ for rel in (
+ ".venv/lib/site.py",
+ "venv/lib/site.py",
+ "__pycache__/mod.cpython-311.pyc",
+ ".pnpm-store/x/index.js",
+ ):
+ p = workspace / rel
+ p.parent.mkdir(parents=True, exist_ok=True)
+ p.write_text("x\n", encoding="utf-8")
+ (workspace / "report.md").write_text("# done\n", encoding="utf-8")
+
+ assert _git_out(["add", "-A", "."], workspace).returncode == 0
+ diff = _git_out(["diff", "--cached", "HEAD"], workspace)
+ assert "report.md" in diff.stdout
+ for token in (".venv", "venv/", "__pycache__", ".pnpm-store"):
+ assert token not in diff.stdout, f"{token} leaked into diff"
+
+
def test_lean_cleanup_via_remove_does_not_error(manager: WorktreeManager) -> None:
"""`remove()` must tear down a lean workspace without calling
`git worktree remove` (which would fail: it is not a registered worktree).
diff --git a/tests/missions/worker_runtime/test_provider_map.py b/tests/missions/worker_runtime/test_provider_map.py
index 0fdb443725..6a0f13dfa9 100644
--- a/tests/missions/worker_runtime/test_provider_map.py
+++ b/tests/missions/worker_runtime/test_provider_map.py
@@ -35,14 +35,21 @@ from jarvis.missions.worker_runtime.provider_map import (
("claude-api", "claude-cli"),
("openai", "openai"),
("openrouter", "openrouter"),
- ("grok", "xai"),
],
)
def test_to_provider_slug_known_providers(jarvis_slug: str, openclaw_slug: str) -> None:
- """Alle 5 dokumentierten Provider mappen wie in AD-6 Amendment-Tabelle."""
+ """Alle dokumentierten Provider mappen wie in AD-6 Amendment-Tabelle."""
assert to_provider_slug(jarvis_slug) == openclaw_slug
+def test_to_provider_slug_grok_removed_raises() -> None:
+ """Grok was removed as a brain/worker provider — its mapping is gone, so
+ the slug no longer resolves (only the grok-voice TTS + credential remain,
+ which never route through this provider map)."""
+ with pytest.raises(UnknownJarvisProviderError):
+ to_provider_slug("grok")
+
+
def test_to_provider_slug_unknown_raises() -> None:
with pytest.raises(UnknownJarvisProviderError) as exc_info:
to_provider_slug("ollama-local")
@@ -73,7 +80,6 @@ def test_to_provider_slug_case_sensitive() -> None:
("claude-cli", "claude-api"),
("openai", "openai"),
("openrouter", "openrouter"),
- ("xai", "grok"),
],
)
def test_to_jarvis_slug_round_trip(openclaw_slug: str, jarvis_slug: str) -> None:
@@ -101,7 +107,6 @@ def test_round_trip_jarvis_openclaw_jarvis() -> None:
("claude-api", ("ANTHROPIC_OAUTH_TOKEN", "ANTHROPIC_API_KEY")),
("openai", ("OPENAI_API_KEY",)),
("openrouter", ("OPENROUTER_API_KEY",)),
- ("grok", ("XAI_API_KEY", "GROK_API_KEY")),
],
)
def test_env_vars_for_known_providers(
@@ -126,7 +131,7 @@ def test_env_vars_primary_always_first() -> None:
def test_validate_configured_providers_all_mapped_returns_empty() -> None:
- configured = ["gemini", "claude-api", "openai", "grok"]
+ configured = ["gemini", "claude-api", "openai", "openrouter"]
assert validate_configured_providers(configured) == []
@@ -182,8 +187,12 @@ def test_provider_mapping_is_frozen() -> None:
def test_ad6_table_is_complete() -> None:
- """AD-6 Amendment listet exakt 5 Provider — Drift-Schutz gegen versehentliches Loeschen."""
- expected_jarvis_slugs = {"gemini", "claude-api", "openai", "openrouter", "grok"}
+ """AD-6 Amendment listet exakt 4 Provider — Drift-Schutz gegen versehentliches Loeschen.
+
+ Grok was removed as a brain/worker provider, so its ``grok->xai`` row is
+ gone from the table (only grok-voice TTS + the credential remain, neither of
+ which routes through this map)."""
+ expected_jarvis_slugs = {"gemini", "claude-api", "openai", "openrouter"}
actual = {m.jarvis for m in MAPPINGS}
assert actual == expected_jarvis_slugs, (
"AD-6 Amendment-Tabelle weicht ab — bitte docs/openclaw-bridge.md "
diff --git a/tests/missions/workers/test_api_agent_worker.py b/tests/missions/workers/test_api_agent_worker.py
index 9a6fa6b6cd..d145d8fb6e 100644
--- a/tests/missions/workers/test_api_agent_worker.py
+++ b/tests/missions/workers/test_api_agent_worker.py
@@ -1,4 +1,4 @@
-"""Tests for ApiAgentWorker — the in-process agentic worker for grok/openai/
+"""Tests for ApiAgentWorker — the in-process agentic worker for openai/
openrouter. Uses a scripted FakeBrain so no network call is made; the real
provider is exercised by the live probe, not the unit suite."""
from __future__ import annotations
@@ -49,9 +49,10 @@ async def _drain(worker: ApiAgentWorker, **kw): # noqa: ANN003
def test_supports_api_agent_worker() -> None:
- assert supports_api_agent_worker("grok")
assert supports_api_agent_worker("openai")
assert supports_api_agent_worker("openrouter")
+ # grok was removed as a brain/worker provider — no longer an api-agent slug.
+ assert not supports_api_agent_worker("grok")
assert not supports_api_agent_worker("claude-api")
assert not supports_api_agent_worker("antigravity")
assert not supports_api_agent_worker(None)
@@ -75,12 +76,12 @@ async def test_worker_writes_file_and_emits_critic_readable_stream(
]
fake = FakeBrain(turns)
_patch_brain(monkeypatch, fake)
- worker = ApiAgentWorker("grok")
+ worker = ApiAgentWorker("openai")
log_dir = tmp_path / "_logs"
events = await _drain(
worker, prompt="make out.txt", worktree=tmp_path, env={}, job=None,
- worker_id="m::0", log_dir=log_dir, model="grok-4.3",
+ worker_id="m::0", log_dir=log_dir, model="gpt-5.5",
)
kinds = [type(e).__name__ for e in events]
@@ -111,7 +112,7 @@ async def test_worker_tool_error_is_fed_back_not_fatal(
[BrainDelta(content="Could not read; done."), BrainDelta(finish_reason="end_turn")],
]
_patch_brain(monkeypatch, FakeBrain(turns))
- worker = ApiAgentWorker("grok")
+ worker = ApiAgentWorker("openai")
events = await _drain(
worker, prompt="x", worktree=tmp_path, env={}, job=None,
worker_id="m::0", log_dir=tmp_path / "_logs",
@@ -146,7 +147,7 @@ async def test_stream_jsonl_is_valid_ndjson(
[BrainDelta(content="done"), BrainDelta(finish_reason="end_turn")],
]
_patch_brain(monkeypatch, FakeBrain(turns))
- worker = ApiAgentWorker("grok")
+ worker = ApiAgentWorker("openai")
log_dir = tmp_path / "_logs"
await _drain(worker, prompt="x", worktree=tmp_path, env={}, job=None,
worker_id="m::0", log_dir=log_dir)
diff --git a/tests/missions/workers/test_claude_direct_provider_fallback.py b/tests/missions/workers/test_claude_direct_provider_fallback.py
index f16a53aaac..0bb95d8ca6 100644
--- a/tests/missions/workers/test_claude_direct_provider_fallback.py
+++ b/tests/missions/workers/test_claude_direct_provider_fallback.py
@@ -98,8 +98,7 @@ _RESULT_LINE = (
@pytest.mark.parametrize("provider,model", [
- ("grok", "grok-4.3"), # unset sub_jarvis -> chain stub default
- ("gemini", "gemini-3.1-pro-preview"),
+ ("gemini", "gemini-3.1-pro-preview"), # unset sub_jarvis -> chain stub default
("openai", "gpt-5.5-pro"),
("openrouter", "some/model"),
])
@@ -160,9 +159,9 @@ async def test_non_claude_provider_runs_on_claude_not_refused(
def test_resolve_claude_model_never_returns_foreign_slug() -> None:
"""_resolve_claude_model must map any non-claude primary to a claude model,
honour a claude-api primary verbatim, and survive a None primary."""
- # Foreign provider -> a claude model, never the grok slug.
- m = cdw._resolve_claude_model(_FallbackStep("grok", "grok-4.3"))
- assert m != "grok-4.3"
+ # Foreign provider -> a claude model, never the foreign slug.
+ m = cdw._resolve_claude_model(_FallbackStep("gemini", "gemini-3.1-pro-preview"))
+ assert m != "gemini-3.1-pro-preview"
assert m.startswith("claude") or m in {"opus", "sonnet", "haiku"}
# claude-api primary with a model -> honoured verbatim.
assert (
diff --git a/tests/missions/workers/test_codex_argv_prefix.py b/tests/missions/workers/test_codex_argv_prefix.py
new file mode 100644
index 0000000000..f12bb09174
--- /dev/null
+++ b/tests/missions/workers/test_codex_argv_prefix.py
@@ -0,0 +1,150 @@
+"""CodexDirectWorker must not depend on the fragile ``codex.CMD`` shim.
+
+Live forensic 2026-06-20 (missions 019ee554 / 019ee555 / 019ee558, the
+"alle Subagent-Missionen schlagen fehl" incident): jarvis was launched by an
+agent runtime (hermes-agent) with a PATH that did NOT contain the Node.js
+directory. The worker invoked ``codex.CMD`` — an npm batch shim whose tail line
+resolves the interpreter as the *bare* command ``node`` via PATH:
+
+ ... || title %COMSPEC% & "%_prog%" "...\\bin\\codex.js" %* (_prog == "node")
+
+With ``node`` off the inherited PATH, cmd.exe died with
+``Der Befehl "node" ... konnte nicht gefunden werden`` and exited 1 in ~25 ms —
+BEFORE codex ever started. Every mission then failed ``task_error`` →
+"Der Worker ist abgebrochen." (reproduced: codex.CMD + node-less PATH → exit 1
+wall_ms=24; ``node`` + absolute path + same PATH → exit 0).
+
+The fix mirrors the existing ``gemini_worker._resolve_gemini_argv_prefix`` and
+``provider_chain._resolve_worker_argv_prefix``: invoke ``node <bin/codex.js>``
+with an ABSOLUTE node path, bypassing the .CMD shim, the cmd.exe layer, and the
+inherited-PATH dependency entirely.
+"""
+from __future__ import annotations
+
+import shutil
+from pathlib import Path
+
+from jarvis.missions.workers.codex_direct_worker import (
+ _build_codex_direct_cmd,
+ _resolve_codex_argv_prefix,
+)
+
+
+def _fake_npm_layout(tmp_path: Path) -> tuple[Path, Path]:
+ """Create a fake npm-global layout: codex.cmd + .../bin/codex.js."""
+ npm = tmp_path / "npm"
+ npm.mkdir()
+ cmd_shim = npm / "codex.cmd"
+ cmd_shim.write_text("@echo off\n", encoding="utf-8")
+ codex_js = npm / "node_modules" / "@openai" / "codex" / "bin" / "codex.js"
+ codex_js.parent.mkdir(parents=True)
+ codex_js.write_text("#!/usr/bin/env node\n", encoding="utf-8")
+ return cmd_shim, codex_js
+
+
+def test_argv_prefix_uses_node_and_codex_js_when_available(
+ tmp_path: Path, monkeypatch
+) -> None:
+ """With node + the codex.js entrypoint locatable, the prefix is
+ ``[<abs node>, <abs codex.js>]`` — never the bare .CMD shim."""
+ cmd_shim, codex_js = _fake_npm_layout(tmp_path)
+ fake_node = tmp_path / "nodejs" / "node.exe"
+ fake_node.parent.mkdir()
+ fake_node.write_text("", encoding="utf-8")
+
+ def fake_which(name: str, *a, **k) -> str | None:
+ low = name.lower()
+ if low in ("node", "node.exe"):
+ return str(fake_node)
+ if low in ("codex", "codex.cmd", "codex.exe"):
+ return str(cmd_shim)
+ return None
+
+ monkeypatch.setattr(shutil, "which", fake_which)
+
+ prefix = _resolve_codex_argv_prefix()
+ assert prefix == [str(fake_node), str(codex_js)], (
+ f"expected [node, codex.js], got {prefix}"
+ )
+
+
+def test_build_cmd_drives_node_not_cmd_shim_when_node_available(
+ tmp_path: Path, monkeypatch
+) -> None:
+ """The full argv must START with node (not codex.CMD) so a degraded
+ inherited PATH lacking the Node.js dir can no longer kill the worker."""
+ cmd_shim, codex_js = _fake_npm_layout(tmp_path)
+ fake_node = tmp_path / "nodejs" / "node.exe"
+ fake_node.parent.mkdir()
+ fake_node.write_text("", encoding="utf-8")
+
+ def fake_which(name: str, *a, **k) -> str | None:
+ low = name.lower()
+ if low in ("node", "node.exe"):
+ return str(fake_node)
+ if low in ("codex", "codex.cmd", "codex.exe"):
+ return str(cmd_shim)
+ return None
+
+ monkeypatch.setattr(shutil, "which", fake_which)
+
+ cmd = _build_codex_direct_cmd(worktree=tmp_path / "wt", model=None)
+ assert cmd[0] == str(fake_node), f"argv[0] must be node, got {cmd[0]!r}"
+ assert cmd[1] == str(codex_js), f"argv[1] must be codex.js, got {cmd[1]!r}"
+ assert not cmd[0].lower().endswith(".cmd"), "must not invoke the .cmd shim"
+ # The codex sub-command + discipline flags still follow the prefix.
+ assert "exec" in cmd
+ assert "multi_agent" in cmd # D9 guard preserved
+
+
+def test_argv_prefix_falls_back_to_binary_when_node_missing(
+ tmp_path: Path, monkeypatch
+) -> None:
+ """When node cannot be located, fall back to the bare codex binary so a
+ node-less-but-codex-present host still runs (prompt is on stdin, so the
+ cmd.exe metachar trap does not apply to this fallback)."""
+ cmd_shim, _ = _fake_npm_layout(tmp_path)
+
+ def fake_which(name: str, *a, **k) -> str | None:
+ low = name.lower()
+ if low in ("node", "node.exe"):
+ return None # node not found
+ if low in ("codex", "codex.cmd", "codex.exe"):
+ return str(cmd_shim)
+ return None
+
+ monkeypatch.setattr(shutil, "which", fake_which)
+ # Force the robust finder to miss too (no node anywhere on this host),
+ # otherwise it would discover the real Node.js install via a well-known dir.
+ from jarvis.missions.workers import codex_direct_worker as cdw
+ monkeypatch.setattr(cdw, "resolve_node_executable", lambda: None)
+
+ prefix = _resolve_codex_argv_prefix()
+ assert prefix == [str(cmd_shim)], f"expected [codex shim], got {prefix}"
+
+
+def test_argv_prefix_uses_node_from_wellknown_when_path_broken(
+ tmp_path: Path, monkeypatch
+) -> None:
+ """The production scenario: node is OFF the inherited PATH (shutil.which
+ misses) but the robust finder locates it via a well-known dir — the prefix
+ must STILL be node-direct, not the .CMD shim."""
+ cmd_shim, codex_js = _fake_npm_layout(tmp_path)
+ wellknown_node = tmp_path / "nodejs" / "node.exe"
+ wellknown_node.parent.mkdir()
+ wellknown_node.write_text("", encoding="utf-8")
+
+ def fake_which(name: str, *a, **k) -> str | None:
+ low = name.lower()
+ if low in ("node", "node.exe"):
+ return None # node NOT on PATH (the degraded-launch condition)
+ if low in ("codex", "codex.cmd", "codex.exe"):
+ return str(cmd_shim)
+ return None
+
+ monkeypatch.setattr(shutil, "which", fake_which)
+ from jarvis.missions.workers import codex_direct_worker as cdw
+ monkeypatch.setattr(cdw, "resolve_node_executable", lambda: str(wellknown_node))
+
+ prefix = _resolve_codex_argv_prefix()
+ assert prefix == [str(wellknown_node), str(codex_js)], prefix
diff --git a/tests/missions/workers/test_codex_model_normalization.py b/tests/missions/workers/test_codex_model_normalization.py
index d011eb8ba7..aa66cb724a 100644
--- a/tests/missions/workers/test_codex_model_normalization.py
+++ b/tests/missions/workers/test_codex_model_normalization.py
@@ -84,7 +84,7 @@ def test_empty_inputs_normalize_to_empty(empty: str | None) -> None:
# Unknown providers should pass through so future provider plugins
# are not silently muted.
"gemini-3.1-pro-preview",
- "grok-4.3",
+ "gpt-5.5",
])
def test_non_anthropic_models_pass_through_unchanged(model: str) -> None:
"""Anything that is not a Claude alias or claude-/anthropic-prefixed
diff --git a/tests/missions/workers/test_node_resolution.py b/tests/missions/workers/test_node_resolution.py
new file mode 100644
index 0000000000..438fbdecc6
--- /dev/null
+++ b/tests/missions/workers/test_node_resolution.py
@@ -0,0 +1,55 @@
+"""Robust Node.js resolution for worker spawns.
+
+Live forensic 2026-06-20: jarvis was launched (by the hermes-agent runtime) with
+a PATH that did NOT contain the Node.js directory. ``shutil.which("node")`` —
+which searches the inherited PATH — therefore returned None, so any node-direct
+spawn fell back to the fragile ``codex.CMD`` shim (whose own bare-``node``
+lookup ALSO failed) and every mission died ``task_error``.
+
+``resolve_node_executable`` must look BEYOND the inherited PATH: when
+``shutil.which`` misses, probe the well-known Windows Node.js install locations
+so a degraded launch environment can no longer hide node from the worker.
+"""
+from __future__ import annotations
+
+import os
+import shutil
+import sys
+from pathlib import Path
+
+import pytest
+
+from jarvis.missions.workers.process_utils import resolve_node_executable
+
+
+def test_resolve_node_prefers_which(tmp_path: Path, monkeypatch) -> None:
+ """When node is on PATH, return exactly what shutil.which finds."""
+ fake = tmp_path / "node.exe"
+ fake.write_text("", encoding="utf-8")
+ monkeypatch.setattr(shutil, "which", lambda n, *a, **k: str(fake) if "node" in n.lower() else None)
+ assert resolve_node_executable() == str(fake)
+
+
[email protected](sys.platform != "win32", reason="well-known dirs are Windows-specific")
+def test_resolve_node_via_wellknown_when_which_fails(tmp_path: Path, monkeypatch) -> None:
+ """The crux of the 2026-06-20 incident: node off the inherited PATH.
+ shutil.which returns None, but a well-known Node.js dir holds node.exe —
+ resolution must still succeed (else the worker falls back to the broken
+ .CMD shim)."""
+ node_dir = tmp_path / "nodejs"
+ node_dir.mkdir()
+ (node_dir / "node.exe").write_text("", encoding="utf-8")
+
+ monkeypatch.setattr(shutil, "which", lambda *a, **k: None)
+ from jarvis.missions.workers import process_utils as pu
+ monkeypatch.setattr(pu, "_windows_node_dir_candidates", lambda: [str(node_dir)])
+
+ assert resolve_node_executable() == str(node_dir / "node.exe")
+
+
+def test_resolve_node_returns_none_when_nowhere(monkeypatch) -> None:
+ """No node anywhere → None (caller degrades to the bare binary fallback)."""
+ monkeypatch.setattr(shutil, "which", lambda *a, **k: None)
+ from jarvis.missions.workers import process_utils as pu
+ monkeypatch.setattr(pu, "_windows_node_dir_candidates", lambda: [])
+ assert resolve_node_executable() is None
diff --git a/tests/overlay/test_system_cursor.py b/tests/overlay/test_system_cursor.py
index ed75aa6675..bbe4101bf7 100644
--- a/tests/overlay/test_system_cursor.py
+++ b/tests/overlay/test_system_cursor.py
@@ -9,6 +9,7 @@ CI box this project's cloud-first doctrine targets.
from __future__ import annotations
import asyncio
+import sys
import pytest
@@ -141,6 +142,36 @@ def test_activate_failure_keeps_state_inactive() -> None:
assert restores == [] # nothing to restore — activation never succeeded
[email protected](sys.platform != "win32", reason="real Win32 HCURSOR build is Windows-only")
+def test_create_hcursor_does_not_overflow_on_64bit_handles() -> None:
+ """Regression (2026-06-22): the gdi32/user32 handle args were passed to
+ ctypes WITHOUT ``argtypes``, so on 64-bit Windows a >2^31 HBITMAP overflowed
+ the default ``c_int`` marshalling ("OverflowError: int too long to convert")
+ at the cleanup ``DeleteObject``. ``_real_activate`` therefore raised on EVERY
+ Computer-Use mission, the failure was swallowed at DEBUG by
+ ``JarvisSystemCursor.ping``, and the user kept their default cursor instead of
+ the gold Jarvis one. Building the cursor must NOT raise and must return a
+ real non-zero HCURSOR. (Builds + destroys an icon only — does NOT swap the
+ live system cursor, so it is safe to run in the suite.)"""
+ import ctypes
+ from ctypes import wintypes
+
+ from jarvis.overlay.system_cursor import _create_hcursor_from_rgba
+
+ rgba = bytes(48 * 48 * 4) # synthetic transparent RGBA; no Pillow needed
+ hcur = _create_hcursor_from_rgba(
+ rgba, width=48, height=48, hotspot_x=2, hotspot_y=2,
+ )
+ assert hcur != 0, "HCURSOR build returned 0 (DIB / CreateIconIndirect failed)"
+
+ # Clean up the HICON/HCURSOR we just built (argtypes pinned for the same
+ # 64-bit-handle reason the fix is about).
+ user32 = ctypes.windll.user32
+ user32.DestroyIcon.argtypes = [wintypes.HANDLE]
+ user32.DestroyIcon.restype = wintypes.BOOL
+ user32.DestroyIcon(hcur)
+
+
def test_ping_jarvis_cursor_helper_is_safe_when_none_set() -> None:
from jarvis.overlay.system_cursor import (
ping_jarvis_cursor,
diff --git a/tests/unit/brain/test_ack_brain/conftest.py b/tests/unit/brain/test_ack_brain/conftest.py
index fd8a8d56eb..8ea089cf2c 100644
--- a/tests/unit/brain/test_ack_brain/conftest.py
+++ b/tests/unit/brain/test_ack_brain/conftest.py
@@ -20,7 +20,6 @@ import pytest
from jarvis.brain.ack_brain.config import (
AckBrainConfig,
GeminiAckProviderConfig,
- GrokAckProviderConfig,
OllamaAckProviderConfig,
OpenAIAckProviderConfig,
_ProvidersBundle,
@@ -129,9 +128,6 @@ def make_ack_config(
gemini=GeminiAckProviderConfig(
model="gemini-3.1-flash", max_output_tokens=max_output_tokens
),
- grok=GrokAckProviderConfig(
- model="grok-4-fast-non-reasoning", max_output_tokens=max_output_tokens
- ),
openai=OpenAIAckProviderConfig(
model="gpt-5-mini", max_output_tokens=max_output_tokens
),
diff --git a/tests/unit/brain/test_ack_brain/test_preferences.py b/tests/unit/brain/test_ack_brain/test_preferences.py
new file mode 100644
index 0000000000..6f14a1b08d
--- /dev/null
+++ b/tests/unit/brain/test_ack_brain/test_preferences.py
@@ -0,0 +1,119 @@
+"""User standing-preferences must reach the flash spoken tiers.
+
+The deep brain already injects the user's agent-instructions file. These lock
+that the two OTHER LLM-generated spoken surfaces — the pre-thinking ack preamble
+(AckGenerator) and the spawn announcement (SpawnAnnouncementComposer) — also
+receive the preferences via their ``preferences_provider`` hook, so a preference
+like "start every sentence with 'Chef'" is honored on action turns too (where
+the spoken output comes from these tiers, not the deep brain).
+
+Deterministic surfaces (the curated spawn fallback pool, CU readbacks, canned
+status phrases) are fixed strings and intentionally NOT covered here.
+"""
+from __future__ import annotations
+
+import types
+
+from jarvis.brain.ack_brain import AckGenerator, CircuitBreaker
+from jarvis.brain.ack_brain.persona_prompt import get_persona_prompt
+from jarvis.brain.ack_brain.spawn_announcement import (
+ SpawnAnnouncementComposer,
+ get_spawn_persona,
+)
+
+
+class _RecordingProvider:
+ """Minimal AbstractAckProvider that records the persona_prompt it receives."""
+
+ def __init__(self, reply: str = "Chef, ich schaue gleich in dein Gmail.") -> None:
+ self.reply = reply
+ self.persona_prompts: list[str] = []
+
+ async def run(self, utterance: str, language: str, *, persona_prompt: str) -> str:
+ self.persona_prompts.append(persona_prompt)
+ return self.reply
+
+
+def _ack_config() -> types.SimpleNamespace:
+ # AckGenerator.run only touches .timeout_ms; __init__ only reads .provider.
+ return types.SimpleNamespace(timeout_ms=1500, provider="fake")
+
+
+# --------------------------------------------------------------------------- #
+# Ack preamble (AckGenerator) #
+# --------------------------------------------------------------------------- #
+
+
+async def test_ack_prompt_includes_user_preferences_when_set() -> None:
+ provider = _RecordingProvider()
+ gen = AckGenerator(
+ provider=provider,
+ config=_ack_config(),
+ breaker=CircuitBreaker(threshold=3, cooldown_s=60),
+ preferences_provider=lambda: "PREFS-MARKER-XYZZY",
+ )
+ await gen.run("öffne mein Gmail und räum auf", language="de")
+ assert provider.persona_prompts, "the provider should have been called"
+ prompt = provider.persona_prompts[0]
+ assert "PREFS-MARKER-XYZZY" in prompt
+ assert "JARVIS" in prompt # base persona still present
+
+
+async def test_ack_prompt_is_base_persona_when_no_preferences() -> None:
+ provider = _RecordingProvider()
+ gen = AckGenerator(
+ provider=provider,
+ config=_ack_config(),
+ breaker=CircuitBreaker(threshold=3, cooldown_s=60),
+ preferences_provider=lambda: "",
+ )
+ await gen.run("such Flüge nach Berlin", language="de")
+ assert provider.persona_prompts[0] == get_persona_prompt("de")
+
+
+async def test_ack_prompt_unaffected_when_provider_raises() -> None:
+ # A faulty preferences hook must never break the ack (silent-on-failure).
+ def _boom() -> str:
+ raise RuntimeError("disk gone")
+
+ provider = _RecordingProvider()
+ gen = AckGenerator(
+ provider=provider,
+ config=_ack_config(),
+ breaker=CircuitBreaker(threshold=3, cooldown_s=60),
+ preferences_provider=_boom,
+ )
+ await gen.run("such Flüge nach Berlin", language="de")
+ assert provider.persona_prompts[0] == get_persona_prompt("de")
+
+
+# --------------------------------------------------------------------------- #
+# Spawn announcement (SpawnAnnouncementComposer) #
+# --------------------------------------------------------------------------- #
+
+
+async def test_spawn_llm_prompt_includes_user_preferences_when_set() -> None:
+ provider = _RecordingProvider(reply="Chef, ich schaue gründlich in dein Gmail.")
+ composer = SpawnAnnouncementComposer(
+ provider=provider,
+ config=_ack_config(),
+ breaker=None,
+ preferences_provider=lambda: "SPAWN-PREFS-MARKER",
+ )
+ await composer.compose(utterance="öffne mein Gmail und räum auf", language="de")
+ assert provider.persona_prompts, "the LLM path should have been taken"
+ prompt = provider.persona_prompts[0]
+ assert "SPAWN-PREFS-MARKER" in prompt
+ assert prompt.startswith(get_spawn_persona("de")[:40]) # base spawn persona present
+
+
+async def test_spawn_llm_prompt_is_base_persona_when_no_preferences() -> None:
+ provider = _RecordingProvider(reply="Ich schaue gründlich in dein Gmail.")
+ composer = SpawnAnnouncementComposer(
+ provider=provider,
+ config=_ack_config(),
+ breaker=None,
+ preferences_provider=lambda: "",
+ )
+ await composer.compose(utterance="öffne mein Gmail und räum auf", language="de")
+ assert provider.persona_prompts[0] == get_spawn_persona("de")
diff --git a/tests/unit/brain/test_agent_instructions.py b/tests/unit/brain/test_agent_instructions.py
new file mode 100644
index 0000000000..07022839e0
--- /dev/null
+++ b/tests/unit/brain/test_agent_instructions.py
@@ -0,0 +1,217 @@
+"""Unit tests for the user-editable agent-instructions file.
+
+The agent-instructions feature is an ``AGENTS.md`` / ``CLAUDE.md`` equivalent: a
+user-owned Markdown file of personal standing instructions, named dynamically
+after the assistant (assistant "Ruben" -> ``Ruben.md``), injected into the brain
+system prompt as a block that is distinct from the packaged persona.
+
+These tests mirror ``test_custom_system_prompt.py``: an autouse fixture redirects
+``DATA_DIR`` to a tmp dir, and the path helpers read ``core_config.DATA_DIR``
+fresh so the redirect takes effect.
+"""
+from __future__ import annotations
+
+import types
+
+import pytest
+
+from jarvis.brain import agent_instructions
+from jarvis.core import config as core_config
+
+
[email protected](autouse=True)
+def _isolate_data_dir(tmp_path, monkeypatch):
+ monkeypatch.setattr(core_config, "DATA_DIR", tmp_path)
+ # This module's contract is "given a RESOLVED assistant name -> <name>.md".
+ # *Which* config field yields that name (persona.name vs. wake phrase) is
+ # ``resolve_assistant_name``'s concern — a separate module whose semantics
+ # evolve independently. Pin the resolver to the config's ``persona.name`` so
+ # these tests exercise THIS module's filename/IO logic deterministically,
+ # without coupling to (or breaking on) the resolver's current behaviour.
+ monkeypatch.setattr(
+ agent_instructions,
+ "resolve_assistant_name",
+ lambda cfg: (getattr(getattr(cfg, "persona", None), "name", "") or "") or "Assistant",
+ )
+ return tmp_path
+
+
+def make_config(name: str = "", phrase: str = ""):
+ """A minimal stand-in for ``JarvisConfig`` (only the fields the resolver reads)."""
+ return types.SimpleNamespace(
+ persona=types.SimpleNamespace(name=name),
+ trigger=types.SimpleNamespace(wake_word=types.SimpleNamespace(phrase=phrase)),
+ )
+
+
+# --------------------------------------------------------------------------- #
+# Filename derivation #
+# --------------------------------------------------------------------------- #
+
+
+def test_filename_follows_persona_name():
+ assert agent_instructions.instructions_filename(make_config(name="Ruben")) == "Ruben.md"
+
+
+def test_filename_falls_back_to_assistant_when_unset():
+ assert agent_instructions.instructions_filename(make_config()) == "Assistant.md"
+
+
+def test_filename_transliterates_umlauts():
+ assert agent_instructions.instructions_filename(make_config(name="Jürgen")) == "Juergen.md"
+
+
+def test_filename_strips_path_separators_and_unsafe_chars():
+ fn = agent_instructions.instructions_filename(make_config(name='a/b:c*?"<>|'))
+ base = fn[:-3] # drop ".md"
+ for bad in '/\\:*?"<>|':
+ assert bad not in base
+ assert fn.endswith(".md")
+
+
+def test_filename_guards_windows_reserved_device_name():
+ assert agent_instructions.instructions_filename(make_config(name="CON")) == "CON_.md"
+ assert agent_instructions.instructions_filename(make_config(name="com1")) == "com1_.md"
+
+
+def test_filename_falls_back_when_empty_after_sanitize():
+ assert agent_instructions.instructions_filename(make_config(name="...")) == "Assistant.md"
+
+
+# --------------------------------------------------------------------------- #
+# Read / save / reset round-trips #
+# --------------------------------------------------------------------------- #
+
+
+def test_no_file_reads_as_none():
+ cfg = make_config(name="Ruben")
+ assert agent_instructions.read_agent_instructions(cfg) is None
+ assert agent_instructions.has_agent_instructions(cfg) is False
+
+
+def test_render_for_prompt_without_file_emits_current_empty_state():
+ cfg = make_config(name="Ruben")
+ block = agent_instructions.render_for_prompt(cfg)
+ assert "Ruben.md" in block
+ assert "No active user preferences are currently set" in block
+ assert "Ignore any earlier Jarvis.md instructions" in block
+ assert "END USER PREFERENCES & STANDING INSTRUCTIONS" in block
+
+
+def test_save_then_read_roundtrips_and_strips():
+ cfg = make_config(name="Ruben")
+ agent_instructions.save_agent_instructions(cfg, " Be concise. ")
+ assert agent_instructions.read_agent_instructions(cfg) == "Be concise."
+ assert agent_instructions.has_agent_instructions(cfg) is True
+
+
+def test_save_writes_to_the_named_file(_isolate_data_dir):
+ cfg = make_config(name="Ruben")
+ agent_instructions.save_agent_instructions(cfg, "x")
+ assert (_isolate_data_dir / "agent_instructions" / "Ruben.md").exists()
+
+
+def test_whitespace_only_reads_as_none():
+ cfg = make_config(name="Ruben")
+ agent_instructions.save_agent_instructions(cfg, " \n\t ")
+ assert agent_instructions.read_agent_instructions(cfg) is None
+
+
+def test_save_is_utf8_without_bom_and_roundtrips_unicode(_isolate_data_dir):
+ cfg = make_config(name="Ruben")
+ text = "Grüße — café ✓ 日本語"
+ agent_instructions.save_agent_instructions(cfg, text)
+ raw = (_isolate_data_dir / "agent_instructions" / "Ruben.md").read_bytes()
+ assert raw.startswith(b"\xef\xbb\xbf") is False # no BOM (AP-7)
+ assert agent_instructions.read_agent_instructions(cfg) == text
+
+
+def test_reset_deletes_and_is_idempotent():
+ cfg = make_config(name="Ruben")
+ agent_instructions.save_agent_instructions(cfg, "x")
+ assert agent_instructions.reset_agent_instructions(cfg) is True
+ assert agent_instructions.read_agent_instructions(cfg) is None
+ assert agent_instructions.reset_agent_instructions(cfg) is False
+
+
+# --------------------------------------------------------------------------- #
+# Prompt rendering #
+# --------------------------------------------------------------------------- #
+
+
+def test_render_for_prompt_wraps_content_with_filename_and_guardrail():
+ cfg = make_config(name="Ruben")
+ agent_instructions.save_agent_instructions(cfg, "Always answer in German.")
+ block = agent_instructions.render_for_prompt(cfg)
+ assert "Ruben.md" in block
+ assert "Always answer in German." in block
+ assert "END USER PREFERENCES & STANDING INSTRUCTIONS" in block
+ assert "Only the instructions inside this current block are active" in block
+ assert "override default style" in block.lower()
+ # The block must frame the content as preferences that never override safety.
+ assert "never override" in block.lower()
+
+
+# --------------------------------------------------------------------------- #
+# Rename-follows-the-name migration #
+# --------------------------------------------------------------------------- #
+
+
+def test_read_migrates_a_single_stray_file_to_the_current_name(_isolate_data_dir):
+ # User wrote rules while the assistant was "Ruben", then renamed it to "Tony".
+ agent_instructions.save_agent_instructions(make_config(name="Ruben"), "My rules.")
+ cfg_tony = make_config(name="Tony")
+ assert agent_instructions.read_agent_instructions(cfg_tony) == "My rules."
+ d = _isolate_data_dir / "agent_instructions"
+ assert (d / "Tony.md").exists()
+ assert (d / "Ruben.md").exists() is False
+
+
+def test_no_migration_when_multiple_files_present(_isolate_data_dir):
+ d = _isolate_data_dir / "agent_instructions"
+ d.mkdir(parents=True)
+ (d / "Ruben.md").write_text("a", encoding="utf-8")
+ (d / "Tony.md").write_text("b", encoding="utf-8")
+ cfg_new = make_config(name="Steve")
+ assert agent_instructions.read_agent_instructions(cfg_new) is None
+ assert (d / "Steve.md").exists() is False
+
+
+# --------------------------------------------------------------------------- #
+# Seed template #
+# --------------------------------------------------------------------------- #
+
+
+def test_seed_template_is_nonempty_and_mentions_the_assistant_name():
+ tpl = agent_instructions.seed_template(make_config(name="Ruben"))
+ assert tpl.strip()
+ assert "Ruben" in tpl
+
+
+# --------------------------------------------------------------------------- #
+# Flash-tier rendering (ack preamble + spawn announcement) #
+# --------------------------------------------------------------------------- #
+
+
+def test_render_for_flash_is_empty_without_a_file():
+ assert agent_instructions.render_for_flash(make_config(name="Ruben")) == ""
+
+
+def test_render_for_flash_carries_content_with_override_framing():
+ cfg = make_config(name="Ruben")
+ agent_instructions.save_agent_instructions(cfg, "Always start every sentence with 'Chef'.")
+ block = agent_instructions.render_for_flash(cfg)
+ assert "Always start every sentence with 'Chef'." in block
+ # The flash block must authorise overriding the default style/address guidance.
+ assert "override" in block.lower()
+ # ...while keeping the hard invariants (brevity / safety / no internal names).
+ assert "safety" in block.lower()
+
+
+def test_render_for_flash_is_concise_relative_to_deep_block():
+ cfg = make_config(name="Ruben")
+ agent_instructions.save_agent_instructions(cfg, "Be terse.")
+ flash = agent_instructions.render_for_flash(cfg)
+ deep = agent_instructions.render_for_prompt(cfg)
+ # The flash framing must be shorter than the deep-brain framing (latency-tier).
+ assert len(flash) < len(deep)
diff --git a/tests/unit/brain/test_agent_instructions_in_manager.py b/tests/unit/brain/test_agent_instructions_in_manager.py
new file mode 100644
index 0000000000..ff9b965702
--- /dev/null
+++ b/tests/unit/brain/test_agent_instructions_in_manager.py
@@ -0,0 +1,58 @@
+"""The agent-instructions file must actually reach the brain's system prompt.
+
+Companion to test_agent_instructions.py (which locks the file/IO layer). This
+proves the wiring: ``BrainManager._build_system_prompt`` injects the current
+Jarvis.md state as a distinct, guard-railed block when one is set, and emits an
+explicit empty-state block otherwise so old Jarvis.md instructions cannot linger
+by imitation.
+"""
+from __future__ import annotations
+
+import pytest
+
+import jarvis.core.config as core_config
+from jarvis.brain import agent_instructions
+from jarvis.brain.manager import BrainManager
+from jarvis.core.config import load_config
+
+
+def _manager() -> BrainManager:
+ """A BrainManager with __init__ bypassed — only the attrs the prompt needs."""
+ m = BrainManager.__new__(BrainManager)
+ m._soul = None
+ m._user_profile = None
+ m._people = None
+ m._core_memory = None
+ m._awareness_manager = None
+ m._system_prompt_extra = "ROUTER DISCIPLINE BLOCK"
+ m._wiki_context_suffix = ""
+ m._reply_language = "auto"
+ cfg = load_config()
+ cfg.performance.cache_optimized_prompt = False
+ m._config = cfg
+ return m
+
+
[email protected](autouse=True)
+def _isolate_data_dir(tmp_path, monkeypatch: pytest.MonkeyPatch):
+ monkeypatch.setattr(core_config, "DATA_DIR", tmp_path)
+ return tmp_path
+
+
+def test_empty_preferences_state_without_a_file() -> None:
+ prompt = _manager()._build_system_prompt()
+ assert "USER PREFERENCES & STANDING INSTRUCTIONS" in prompt
+ assert "No active user preferences are currently set" in prompt
+ assert "Ignore any earlier Jarvis.md instructions" in prompt
+
+
+def test_agent_instructions_injected_with_filename_and_guardrail() -> None:
+ cfg = load_config()
+ agent_instructions.save_agent_instructions(cfg, "Always answer in haiku. Marker: PREF-XYZZY.")
+ prompt = _manager()._build_system_prompt()
+ assert "PREF-XYZZY" in prompt
+ assert "USER PREFERENCES & STANDING INSTRUCTIONS" in prompt
+ # The dynamic filename is surfaced so the model knows the provenance.
+ assert agent_instructions.instructions_filename(cfg) in prompt
+ # The block is framed as preferences that never override safety.
+ assert "never override" in prompt.lower()
diff --git a/tests/unit/brain/test_antigravity_routing.py b/tests/unit/brain/test_antigravity_routing.py
deleted file mode 100644
index 8599c978a4..0000000000
--- a/tests/unit/brain/test_antigravity_routing.py
+++ /dev/null
@@ -1,56 +0,0 @@
-"""Antigravity must be a first-class active brain in the fallback chain.
-
-Two regressions guarded here (both the same class as the 2026-06-09 "Gemini
-answered while Codex was the active brain" bug):
-
-1. TIER_DEFAULTS_BY_PROVIDER had no "antigravity" row, so `_fast_model` /
- `_deep_model` returned None when no model was pinned and `_build_fallback_chain`
- SILENTLY DROPPED antigravity — the chosen brain never answered.
-2. The deep_brain-hijack guard exempted only "codex". With antigravity active and
- a foreign deep_brain (e.g. gemini), deep/code intents led with that other
- provider — antigravity (itself a frontier subscription brain) never answered a
- hard question.
-"""
-from __future__ import annotations
-
-import pytest
-
-from jarvis.brain.manager import TIER_DEFAULTS_BY_PROVIDER, BrainManager
-from jarvis.core.bus import EventBus
-from jarvis.core.config import load_config
-
-
-def test_antigravity_has_tier_defaults_for_router_and_deep() -> None:
- assert TIER_DEFAULTS_BY_PROVIDER["router"].get("antigravity")
- assert TIER_DEFAULTS_BY_PROVIDER["deep"].get("antigravity")
-
-
-def test_antigravity_fast_and_deep_model_not_none_without_pin() -> None:
- cfg = load_config()
- cfg.brain.primary = "antigravity"
- cfg.brain.router.provider = "antigravity"
- cfg.brain.router.fallback_provider = "antigravity"
- if "antigravity" in cfg.brain.providers:
- cfg.brain.providers["antigravity"].model = "" # unpinned
- mgr = BrainManager.from_tier_config(
- "router", cfg, EventBus(), provider_override="antigravity"
- )
- # Tier default kicks in → antigravity is not dropped from the chain.
- assert mgr._fast_model("antigravity")
- assert mgr._deep_model("antigravity")
-
-
-def test_antigravity_active_leads_deep_not_foreign_deep_brain(monkeypatch) -> None:
- cfg = load_config()
- cfg.brain.primary = "antigravity"
- cfg.brain.router.provider = "antigravity"
- cfg.brain.router.fallback_provider = "gemini" # deliberate cross-provider split
- mgr = BrainManager.from_tier_config(
- "router", cfg, EventBus(), provider_override="antigravity"
- )
- # Force both eligible so step-0 (deep_brain) is genuinely in play.
- monkeypatch.setattr(mgr._registry, "available", lambda: ["antigravity", "gemini"])
- assert mgr._config.brain.deep_brain == "gemini" # explicit split preserved
- deep_chain = mgr._build_fallback_chain("deep")
- # antigravity (a frontier subscription brain) leads deep/code, NOT gemini.
- assert deep_chain[0][0] == "antigravity"
diff --git a/tests/unit/brain/test_antigravity_subagent_only.py b/tests/unit/brain/test_antigravity_subagent_only.py
new file mode 100644
index 0000000000..d0d4f38a33
--- /dev/null
+++ b/tests/unit/brain/test_antigravity_subagent_only.py
@@ -0,0 +1,105 @@
+"""Screenshot-blind CLI providers are subagent-only, not the main Brain."""
+from __future__ import annotations
+
+import asyncio
+
+from jarvis.brain.manager import (
+ SUBAGENT_ONLY_BRAIN_PROVIDERS,
+ TIER_DEFAULTS_BY_PROVIDER,
+ BrainManager,
+)
+from jarvis.core.bus import EventBus
+from jarvis.core.config import BrainTierConfig, JarvisConfig
+
+
+def test_antigravity_is_not_a_main_brain_tier_default() -> None:
+ assert "antigravity" in SUBAGENT_ONLY_BRAIN_PROVIDERS
+ assert "antigravity" not in TIER_DEFAULTS_BY_PROVIDER["router"]
+ assert "antigravity" not in TIER_DEFAULTS_BY_PROVIDER["deep"]
+
+
+def test_codex_is_not_a_main_brain_tier_default() -> None:
+ assert "codex" in SUBAGENT_ONLY_BRAIN_PROVIDERS
+ assert "openai-codex" in SUBAGENT_ONLY_BRAIN_PROVIDERS
+ assert "codex" not in TIER_DEFAULTS_BY_PROVIDER["router"]
+ assert "codex" not in TIER_DEFAULTS_BY_PROVIDER["deep"]
+
+
+def test_antigravity_startup_override_falls_back_to_router_provider() -> None:
+ cfg = JarvisConfig()
+ cfg.brain.primary = "antigravity"
+ cfg.brain.router = BrainTierConfig(
+ provider="openai",
+ fallback_provider="gemini",
+ )
+
+ mgr = BrainManager.from_tier_config(
+ "router",
+ cfg,
+ EventBus(),
+ provider_override="antigravity",
+ )
+
+ assert mgr.active_provider == "openai"
+ assert mgr._config.brain.primary == "openai"
+
+
+def test_codex_startup_override_falls_back_to_router_provider() -> None:
+ cfg = JarvisConfig()
+ cfg.brain.primary = "codex"
+ cfg.brain.router = BrainTierConfig(
+ provider="openai",
+ fallback_provider="gemini",
+ )
+
+ mgr = BrainManager.from_tier_config(
+ "router",
+ cfg,
+ EventBus(),
+ provider_override="codex",
+ )
+
+ assert mgr.active_provider == "openai"
+ assert mgr._config.brain.primary == "openai"
+
+
+def test_antigravity_direct_manager_config_falls_back_to_router_provider() -> None:
+ cfg = JarvisConfig()
+ cfg.brain.primary = "antigravity"
+ cfg.brain.router = BrainTierConfig(
+ provider="gemini",
+ fallback_provider="openai",
+ )
+
+ mgr = BrainManager(config=cfg, bus=EventBus(), tools={})
+
+ assert mgr.active_provider == "gemini"
+ assert cfg.brain.primary == "gemini"
+
+
+def test_codex_direct_manager_config_falls_back_to_router_provider() -> None:
+ cfg = JarvisConfig()
+ cfg.brain.primary = "codex"
+ cfg.brain.router = BrainTierConfig(
+ provider="gemini",
+ fallback_provider="openai",
+ )
+
+ mgr = BrainManager(config=cfg, bus=EventBus(), tools={})
+
+ assert mgr.active_provider == "gemini"
+ assert cfg.brain.primary == "gemini"
+
+
+def test_runtime_switch_rejects_subagent_only_provider() -> None:
+ cfg = JarvisConfig()
+ cfg.brain.primary = "gemini"
+ mgr = BrainManager(config=cfg, bus=EventBus(), tools={})
+
+ asyncio.run(mgr.switch("codex", persist=True))
+ asyncio.run(mgr.switch("openai-codex", persist=True))
+ asyncio.run(mgr.switch("antigravity", persist=True))
+
+ assert mgr.active_provider == "gemini"
+ assert cfg.brain.primary == "gemini"
+ assert mgr.last_persist_ok is False
diff --git a/tests/unit/brain/test_apply_provider_model.py b/tests/unit/brain/test_apply_provider_model.py
new file mode 100644
index 0000000000..d961190564
--- /dev/null
+++ b/tests/unit/brain/test_apply_provider_model.py
@@ -0,0 +1,86 @@
+"""BrainManager.apply_provider_model — live in-memory model override.
+
+The API-Keys model picker writes the chosen model to jarvis.toml (durable) AND
+calls this method so the running brain uses it on the very next turn without a
+restart. The method mutates the manager's OWN config (the brain builds its config
+separately from app.state.config) and drops cached brain instances for that
+provider so the new model is instantiated. It returns whether the provider is the
+currently active brain — the route reports that as ``applied_live``.
+"""
+from __future__ import annotations
+
+from typing import Any
+
+from jarvis.brain.manager import BrainManager
+from jarvis.core.bus import EventBus
+from jarvis.core.config import BrainProviderConfig, JarvisConfig
+
+
+class _FakeTool:
+ name = "noop"
+ schema: dict[str, Any] = {}
+
+
+class _InertExecutor:
+ async def execute(self, *_a: Any, **_k: Any) -> Any: # pragma: no cover
+ raise AssertionError("executor must not run here")
+
+
+def _manager(primary: str = "gemini") -> BrainManager:
+ config = JarvisConfig()
+ config.brain.primary = primary
+ return BrainManager(
+ config=config,
+ bus=EventBus(),
+ tools={},
+ tool_executor=_InertExecutor(), # type: ignore[arg-type]
+ )
+
+
+def test_active_provider_returns_true_and_sets_model() -> None:
+ mgr = _manager(primary="gemini")
+ is_active = mgr.apply_provider_model("gemini", "gemini-3.1-pro-preview")
+ assert is_active is True
+ assert mgr._config.brain.providers["gemini"].model == "gemini-3.1-pro-preview"
+
+
+def test_inactive_provider_returns_false_but_still_persists_in_memory() -> None:
+ mgr = _manager(primary="gemini")
+ is_active = mgr.apply_provider_model("openai", "gpt-5.5")
+ assert is_active is False
+ assert mgr._config.brain.providers["openai"].model == "gpt-5.5"
+
+
+def test_creates_provider_block_when_absent() -> None:
+ mgr = _manager(primary="gemini")
+ assert "openrouter" not in mgr._config.brain.providers
+ mgr.apply_provider_model("openrouter", "openai/gpt-5.5")
+ assert mgr._config.brain.providers["openrouter"].model == "openai/gpt-5.5"
+
+
+def test_existing_block_is_updated_not_replaced_fields() -> None:
+ mgr = _manager(primary="gemini")
+ mgr._config.brain.providers["gemini"] = BrainProviderConfig(
+ model="old", deep_model="keep-me"
+ )
+ mgr.apply_provider_model("gemini", "gemini-3-flash-preview")
+ pc = mgr._config.brain.providers["gemini"]
+ assert pc.model == "gemini-3-flash-preview"
+ assert pc.deep_model == "keep-me" # untouched
+
+
+def test_empty_model_resets_to_none() -> None:
+ mgr = _manager(primary="gemini")
+ mgr._config.brain.providers["gemini"] = BrainProviderConfig(model="pinned")
+ mgr.apply_provider_model("gemini", "")
+ assert mgr._config.brain.providers["gemini"].model is None
+
+
+def test_drops_cached_brain_instances_for_that_provider() -> None:
+ mgr = _manager(primary="gemini")
+ mgr._brain_cache[("gemini", "old-model")] = object() # type: ignore[assignment]
+ mgr._brain_cache[("openai", "gpt-5.5")] = object() # type: ignore[assignment]
+ mgr.apply_provider_model("gemini", "gemini-3-flash-preview")
+ assert not any(k[0] == "gemini" for k in mgr._brain_cache)
+ # Other providers' caches are left alone.
+ assert ("openai", "gpt-5.5") in mgr._brain_cache
diff --git a/tests/unit/brain/test_artifact_build_routing.py b/tests/unit/brain/test_artifact_build_routing.py
new file mode 100644
index 0000000000..f581b8a106
--- /dev/null
+++ b/tests/unit/brain/test_artifact_build_routing.py
@@ -0,0 +1,113 @@
+"""Build-a-deliverable requests must route to a sub-agent MISSION, not the brain.
+
+Live bug 2026-06-21 (voice session 19:13): "I would like you to build me an HTML
+file ... visualize ... how I can prepare my vacation to Melbourne" fell through to
+the deep brain (Antigravity, a tool-incapable CLI) which — unable to call any tool
+— just asked permission ("should I create the file on your disk?") instead of
+building anything. A build-a-deliverable request (HTML/website/app/report/
+document/visualization/file) is a sub-agent mission: the Worker->Critic pipeline
+verifies the built artifact via git diff.
+
+The fix must be PROVIDER-INDEPENDENT (the deterministic force-spawn gate), because
+a tool-incapable talker (Codex/Antigravity over a subscription CLI) cannot spawn
+via an LLM tool_call at all — the gate is the only spawn path for it. It must NOT
+over-trigger: a build verb is not a screen action, so "open/show the file" stays
+Computer-Use and pure questions/answers stay inline.
+
+Deterministic — no LLM, no real brain.
+"""
+from __future__ import annotations
+
+from typing import Any
+
+import pytest
+
+from jarvis.brain.manager import BrainManager
+from jarvis.core.bus import EventBus
+from jarvis.core.config import JarvisConfig
+
+
+class _FakeTool:
+ name = "spawn_worker"
+ schema: dict[str, Any] = {}
+
+
+class _Inert:
+ async def execute(self, *_a: Any, **_k: Any) -> Any: # pragma: no cover
+ raise AssertionError("no exec in a classification test")
+
+
+def _manager() -> BrainManager:
+ config = JarvisConfig()
+ config.brain.routing.force_spawn_mode = "strict" # production default
+ return BrainManager(
+ config=config,
+ bus=EventBus(),
+ tools={"spawn_worker": _FakeTool()},
+ tool_executor=_Inert(), # type: ignore[arg-type]
+ )
+
+
+# The exact failing utterance (English, no research verb, "HTML file" as a word).
+FAILING = (
+ "I would like you to build me an HTML file. I would like you to write all "
+ "important stuff in it. I would really make it visualized, visual, so I can "
+ "see everything in a great visualization. I would like you to help me with "
+ "this HTML file how I can prepare my vacation to Melbourne."
+)
+
+
+def test_build_an_html_file_routes_to_a_mission() -> None:
+ assert _manager()._should_force_spawn(FAILING) is True, (
+ "a build-an-HTML-file request must force-spawn a sub-agent mission, not "
+ "fall through to the (tool-incapable) talker that just asks permission"
+ )
+
+
+# A build-a-deliverable request is a mission — DE + EN, even without a research verb.
+_BUILD_DELIVERABLE = [
+ "Build me a website about my startup",
+ "Create a PDF report about the AI market",
+ "Bau mir eine Webseite über meinen Urlaub",
+ "Erstell mir ein interaktives Dashboard mit den wichtigsten Zahlen",
+ "Write me an HTML page that visualizes my expenses",
+ "Generate a landing page for the product launch",
+]
+
+
[email protected]("utterance", _BUILD_DELIVERABLE)
+def test_build_deliverable_force_spawns(utterance: str) -> None:
+ assert _manager()._should_force_spawn(utterance) is True, (
+ f"build-a-deliverable request {utterance!r} should route to a mission"
+ )
+
+
+# Must NOT over-trigger: these are NOT build-a-deliverable missions.
+_NOT_A_BUILD_MISSION = [
+ # knowledge / instructional — answered inline
+ "What is an HTML file?",
+ "Wie erstelle ich eine HTML-Datei?",
+ # an ANSWER deliverable (pinned by the artefact discriminator) — inline
+ "research X and write a short summary",
+ # smalltalk
+ "Hallo",
+ "Danke",
+]
+
+
[email protected]("utterance", _NOT_A_BUILD_MISSION)
+def test_non_build_requests_do_not_force_spawn(utterance: str) -> None:
+ assert _manager()._should_force_spawn(utterance) is False, (
+ f"{utterance!r} is not a build-a-deliverable mission and must not spawn"
+ )
+
+
+def test_artifact_discriminator_recognises_html_file() -> None:
+ """The shared artifact detector must treat 'an HTML file' as a deliverable —
+ without requiring a literal dotted extension."""
+ assert BrainManager._research_wants_artifact(None, FAILING) is True # type: ignore[arg-type]
+ # but a bare answer-summary is still NOT an artifact (discriminator contract)
+ assert (
+ BrainManager._research_wants_artifact(None, "write a short summary") # type: ignore[arg-type]
+ is False
+ )
diff --git a/tests/unit/brain/test_backup_provider_timeouts.py b/tests/unit/brain/test_backup_provider_timeouts.py
index 890cc13a41..25bf371d96 100644
--- a/tests/unit/brain/test_backup_provider_timeouts.py
+++ b/tests/unit/brain/test_backup_provider_timeouts.py
@@ -1,8 +1,8 @@
"""Wave-3 latency fix: bound the openai-SDK backup providers' read timeout.
-``openai``/``grok``/``openrouter`` are built on the openai SDK, whose DEFAULT
-read timeout is 600 s. A hung backup provider on the fallback chain could hold
-the brain coroutine far longer than intended. Cap read at 30 s (well under the
+``openai``/``openrouter`` are built on the openai SDK, whose DEFAULT read
+timeout is 600 s. A hung backup provider on the fallback chain could hold the
+brain coroutine far longer than intended. Cap read at 30 s (well under the
brain stall guard) while keeping connect snappy (5 s) for fast-fail on a dead
endpoint.
"""
@@ -11,12 +11,11 @@ from __future__ import annotations
import pytest
import jarvis.core.config as cfg
-from jarvis.plugins.brain.grok import GrokBrain
from jarvis.plugins.brain.openai import OpenAIBrain
from jarvis.plugins.brain.openrouter import OpenRouterBrain
[email protected]("brain_cls", [OpenAIBrain, GrokBrain, OpenRouterBrain])
[email protected]("brain_cls", [OpenAIBrain, OpenRouterBrain])
def test_backup_provider_client_has_bounded_timeout(brain_cls, monkeypatch) -> None:
monkeypatch.setattr(cfg, "get_provider_secret", lambda *a, **k: "test-key")
brain = brain_cls()
diff --git a/tests/unit/brain/test_codex_brain.py b/tests/unit/brain/test_codex_brain.py
index 6637817055..0b5820fb59 100644
--- a/tests/unit/brain/test_codex_brain.py
+++ b/tests/unit/brain/test_codex_brain.py
@@ -7,9 +7,14 @@ plain ``openai`` provider, so the user can run e.g. brain=codex + subagent=gemin
"""
from __future__ import annotations
+import asyncio
+from collections.abc import AsyncIterator
+from pathlib import Path
+
import pytest
-from jarvis.plugins.brain.codex import CodexBrain
+from jarvis.core.protocols import BrainDelta, BrainMessage, BrainRequest
+from jarvis.plugins.brain.codex import CodexBrain, _build_cli_prompt
def test_name_and_capabilities() -> None:
@@ -18,15 +23,103 @@ def test_name_and_capabilities() -> None:
assert brain.supports_tools is True
-def test_ensure_client_raises_without_any_key(monkeypatch: pytest.MonkeyPatch) -> None:
+def _system_with_standing_instructions() -> str:
+ return (
+ "STATIC PERSONA BLOCK\n\n"
+ "USER PREFERENCES & STANDING INSTRUCTIONS (from Jarvis.md):\n"
+ "The following are personal preferences written by the user.\n\n"
+ "Always start every sentence with schef.\n\n"
+ "END USER PREFERENCES & STANDING INSTRUCTIONS\n\n"
+ "REGISTRIERTE WERKZEUGE (vollstaendige Liste):\n"
+ "- search_web\n"
+ )
+
+
+def _system_with_empty_standing_instructions() -> str:
+ return (
+ "STATIC PERSONA BLOCK\n\n"
+ "USER PREFERENCES & STANDING INSTRUCTIONS (from Jarvis.md):\n"
+ "No active user preferences are currently set in Jarvis.md. "
+ "Ignore any earlier Jarvis.md instructions from previous turns.\n\n"
+ "END USER PREFERENCES & STANDING INSTRUCTIONS\n\n"
+ "REGISTRIERTE WERKZEUGE (vollstaendige Liste):\n"
+ "- search_web\n"
+ )
+
+
+def test_cli_prompt_includes_standing_instructions_without_heavy_router_prompt() -> None:
+ req = BrainRequest(
+ messages=(BrainMessage(role="user", content="Was ist das wertvollste Unternehmen?"),),
+ system=_system_with_standing_instructions(),
+ )
+
+ prompt = _build_cli_prompt(req)
+
+ assert "Always start every sentence with schef." in prompt
+ assert "Jarvis.md" in prompt
+ assert "REGISTRIERTE WERKZEUGE" not in prompt
+ assert "STATIC PERSONA BLOCK" not in prompt
+
+
+def test_cli_prompt_carries_reply_language_directive() -> None:
+ """The authoritative reply-language directive (appended LAST to the system
+ prompt by BrainManager) must reach the flattened CLI prompt.
+
+ Mirrors the antigravity brain: dropping the trailing "REPLY LANGUAGE"
+ directive lets the codex subscription model answer in the wrong language
+ (live bug 2026-06-21, antigravity sibling). The shared
+ ``cli_prompt_context`` helper re-surfaces it for both CLI brains.
+ """
+ directive = (
+ "REPLY LANGUAGE — MANDATORY: Always reply in English, no matter which "
+ "language the user writes or speaks in."
+ )
+ req = BrainRequest(
+ messages=(BrainMessage(role="user", content="Build me an HTML file please."),),
+ system=_system_with_standing_instructions() + "\n\n" + directive,
+ )
+
+ prompt = _build_cli_prompt(req)
+
+ assert "Always reply in English" in prompt
+ assert "Always start every sentence with schef." in prompt
+
+
+def test_cli_prompt_puts_current_empty_state_after_stale_history() -> None:
+ req = BrainRequest(
+ messages=(
+ BrainMessage(role="user", content="Wasketup"),
+ BrainMessage(role="assistant", content="schef, alles laeuft."),
+ BrainMessage(role="user", content="Du musst das nicht mehr sagen."),
+ ),
+ system=_system_with_empty_standing_instructions(),
+ )
+
+ prompt = _build_cli_prompt(req)
+
+ assert "CURRENT JARVIS.MD STATE" in prompt
+ assert "No active user preferences are currently set" in prompt
+ assert "do not continue or imitate" in prompt
+ assert prompt.rfind("No active user preferences") > prompt.rfind("Assistant: schef")
+ assert "REGISTRIERTE WERKZEUGE" not in prompt
+
+
+async def test_complete_raises_without_any_key_or_oauth(
+ monkeypatch: pytest.MonkeyPatch,
+) -> None:
monkeypatch.setattr("jarvis.core.config.get_provider_secret", lambda _p: None)
monkeypatch.setattr("jarvis.core.config.get_secret", lambda *_a, **_k: None)
+ monkeypatch.setattr("jarvis.plugins.brain.codex._codex_oauth_connected", lambda: False)
brain = CodexBrain()
- with pytest.raises(RuntimeError):
- brain._ensure_client()
+ req = BrainRequest(messages=(BrainMessage(role="user", content="hello"),))
+
+ with pytest.raises(RuntimeError, match="No Codex auth found"):
+ async for _delta in brain.complete(req):
+ pass
-def test_ensure_client_uses_codex_key(monkeypatch: pytest.MonkeyPatch) -> None:
+def test_ensure_client_uses_given_key(monkeypatch: pytest.MonkeyPatch) -> None:
captured: dict[str, str] = {}
class _FakeAsyncOpenAI:
@@ -36,11 +129,86 @@ def test_ensure_client_uses_codex_key(monkeypatch: pytest.MonkeyPatch) -> None:
import openai
monkeypatch.setattr(openai, "AsyncOpenAI", _FakeAsyncOpenAI)
- # codex slot resolves first
+ brain = CodexBrain()
+ brain._ensure_client("sk-codex-key")
+ assert captured["api_key"] == "sk-codex-key"
+
+
+class _FakeStdin:
+ def __init__(self) -> None:
+ self.data = b""
+ self.closed = False
+
+ def write(self, data: bytes) -> None:
+ self.data += data
+
+ async def drain(self) -> None:
+ return None
+
+ def close(self) -> None:
+ self.closed = True
+
+
+class _FakeProcess:
+ def __init__(self) -> None:
+ self.stdin = _FakeStdin()
+ self.returncode: int | None = None
+ self.communicate_started = asyncio.Event()
+ self._release = asyncio.Event()
+ self.killed = False
+ self.waited = False
+
+ async def communicate(self) -> tuple[bytes, bytes]:
+ self.communicate_started.set()
+ await self._release.wait()
+ return b"", b""
+
+ def kill(self) -> None:
+ self.killed = True
+ self.returncode = -9
+ self._release.set()
+
+ async def wait(self) -> int | None:
+ self.waited = True
+ return self.returncode
+
+
+async def test_cli_subprocess_is_killed_when_stream_is_cancelled(
+ monkeypatch: pytest.MonkeyPatch,
+ tmp_path: Path,
+) -> None:
+ proc = _FakeProcess()
+
+ async def fake_create_subprocess_exec(*_args, **_kwargs) -> _FakeProcess:
+ return proc
+
+ monkeypatch.setattr(
+ "jarvis.plugins.brain.codex._resolve_codex_binary",
+ lambda: "codex",
+ )
+ monkeypatch.setattr(
+ "jarvis.plugins.brain.codex.tempfile.mkdtemp",
+ lambda prefix: str(tmp_path),
+ )
monkeypatch.setattr(
- "jarvis.core.config.get_provider_secret",
- lambda p: "sk-codex-key" if p == "codex" else None,
+ "jarvis.plugins.brain.codex.shutil.rmtree",
+ lambda *_a, **_k: None,
)
+ monkeypatch.setattr(
+ "jarvis.plugins.brain.codex.asyncio.create_subprocess_exec",
+ fake_create_subprocess_exec,
+ )
+
brain = CodexBrain()
- brain._ensure_client()
- assert captured["api_key"] == "sk-codex-key"
+ req = BrainRequest(messages=(BrainMessage(role="user", content="hello"),))
+ stream: AsyncIterator[BrainDelta] = brain._complete_via_cli(req)
+ task = asyncio.create_task(stream.__anext__())
+
+ await asyncio.wait_for(proc.communicate_started.wait(), timeout=1.0)
+ task.cancel()
+ with pytest.raises(asyncio.CancelledError):
+ await task
+
+ assert proc.killed is True
+ assert proc.waited is True
diff --git a/tests/unit/brain/test_cu_model_selection.py b/tests/unit/brain/test_cu_model_selection.py
new file mode 100644
index 0000000000..c95814a365
--- /dev/null
+++ b/tests/unit/brain/test_cu_model_selection.py
@@ -0,0 +1,91 @@
+"""Phase 3: a user-selectable Computer-Use model per provider.
+
+CU runs on the provider's main ``model`` by default; a pinned ``cu_model`` lets
+the user run CU on a different (e.g. stronger) model than chat, with no automatic
+escalation. Resolution is provider-agnostic (AP-21): cu_model -> the provider's
+main model -> the router-tier default.
+"""
+from __future__ import annotations
+
+from jarvis.brain.manager import BrainManager, get_tier_default_model
+from jarvis.core.bus import EventBus
+from jarvis.core.config import BrainProviderConfig, load_config
+from jarvis.harness import screenshot_only_loop as sol
+
+
+# --- config field -----------------------------------------------------------
+
+
+def test_brain_provider_config_has_cu_model():
+ c = BrainProviderConfig(model="gemini-3.5-flash", cu_model="gemini-3.1-pro-preview")
+ assert c.cu_model == "gemini-3.1-pro-preview"
+
+
+def test_brain_provider_config_cu_model_defaults_none():
+ assert BrainProviderConfig().cu_model is None
+
+
+# --- BrainManager._cu_model precedence --------------------------------------
+
+
+def test_cu_model_prefers_pinned_cu_model():
+ cfg = load_config()
+ cfg.brain.router.provider = "gemini"
+ cfg.brain.providers["gemini"].model = "gemini-3.5-flash"
+ cfg.brain.providers["gemini"].cu_model = "gemini-3.1-pro-preview"
+ mgr = BrainManager.from_tier_config("router", cfg, EventBus())
+ assert mgr._cu_model("gemini") == "gemini-3.1-pro-preview"
+
+
+def test_cu_model_falls_back_to_main_model_when_unset():
+ cfg = load_config()
+ cfg.brain.router.provider = "gemini"
+ cfg.brain.providers["gemini"].model = "gemini-3.5-flash"
+ cfg.brain.providers["gemini"].cu_model = None
+ mgr = BrainManager.from_tier_config("router", cfg, EventBus())
+ assert mgr._cu_model("gemini") == "gemini-3.5-flash"
+
+
+def test_cu_model_falls_back_to_router_default_for_absent_provider():
+ cfg = load_config()
+ cfg.brain.router.provider = "gemini"
+ mgr = BrainManager.from_tier_config("router", cfg, EventBus())
+ # A provider with no [brain.providers.<p>] block resolves to the router default.
+ assert mgr._cu_model("openrouter") == (
+ cfg.brain.providers.get("openrouter").cu_model
+ or cfg.brain.providers.get("openrouter").model
+ or get_tier_default_model("router", "openrouter")
+ )
+
+
+# --- _select_cu_model helper (loop-side, provider-agnostic) ------------------
+
+
+def test_select_cu_model_prefers_cu_model():
+ class _M:
+ def _cu_model(self, p):
+ return "cu-model-x"
+
+ def _fast_model(self, p):
+ return "fast-model-x"
+
+ assert sol._select_cu_model(_M(), "gemini") == "cu-model-x"
+
+
+def test_select_cu_model_falls_back_to_fast_when_no_cu_model():
+ class _M:
+ def _fast_model(self, p):
+ return "fast-model-x"
+
+ assert sol._select_cu_model(_M(), "gemini") == "fast-model-x"
+
+
+def test_select_cu_model_falls_back_when_cu_model_returns_empty():
+ class _M:
+ def _cu_model(self, p):
+ return None
+
+ def _fast_model(self, p):
+ return "fast-model-x"
+
+ assert sol._select_cu_model(_M(), "gemini") == "fast-model-x"
diff --git a/tests/unit/brain/test_cu_vs_spawn_routing.py b/tests/unit/brain/test_cu_vs_spawn_routing.py
new file mode 100644
index 0000000000..2269a5d39c
--- /dev/null
+++ b/tests/unit/brain/test_cu_vs_spawn_routing.py
@@ -0,0 +1,175 @@
+"""Computer-Use-vs-sub-agent-spawn routing (force-spawn depth-marker overlap).
+
+Live bug: "Mach einen Deep Dive mit Computer Use in meinem Chrome Browser und
+such mir den neuesten Post von Elon Musk raus" was force-spawned into a
+background sub-agent mission instead of reaching the Computer-Use path.
+
+Root cause (evidence, not guess): ``BrainManager._should_force_spawn`` hoists any
+``force_spawn_phrases`` match to an immediate ``True`` BEFORE the LLM router ever
+sees the turn. That phrase list mixes two semantically different things:
+
+* **vehicle names** (``subagent`` / ``spawn`` / ``openclaw`` / ``delegate``) —
+ the user named the worker. Unambiguous; absolute priority (mandate 2026-06-15).
+* **depth markers** (``deep dive`` / ``gründlich`` / ``umfassend`` / …) — these
+ describe thoroughness, NOT a vehicle, and OVERLAP with computer-use requests.
+
+A depth marker must not override an explicit on-screen/computer/browser request:
+the computer-use-vs-spawn call is the LLM router's (it owns ``computer_use`` plus
+the SYSTEM_PROMPT rule "Bildschirm/Browser bedienen ist computer_use, kein
+spawn_worker"). The deterministic gate only decides whether to FORCE a spawn —
+for an ambiguous depth marker + a computer-use request it must stand down and let
+the LLM decide. A genuine depth/research request WITHOUT a screen signal still
+force-spawns; a turn that NAMES the vehicle always force-spawns.
+
+These tests are fully deterministic — no LLM, no real brain — they exercise
+``_should_force_spawn`` directly.
+"""
+from __future__ import annotations
+
+from typing import Any
+
+import pytest
+
+from jarvis.brain.manager import BrainManager, _looks_like_pc_control
+from jarvis.core.bus import EventBus
+from jarvis.core.config import JarvisConfig
+
+
+class _FakeSpawnTool:
+ name = "spawn_worker"
+ schema: dict[str, Any] = {}
+
+
+class _FakeDispatchTool:
+ name = "dispatch_to_harness"
+ schema: dict[str, Any] = {}
+
+
+class _InertExecutor:
+ async def execute(self, *_a: Any, **_k: Any) -> Any: # pragma: no cover
+ raise AssertionError("executor must not run in a classification test")
+
+
+def _manager() -> BrainManager:
+ """Strict-mode (production default) manager with spawn_worker AND the
+ computer-use harness wired — the realistic gate path."""
+ config = JarvisConfig()
+ config.brain.routing.force_spawn_mode = "strict"
+ return BrainManager(
+ config=config,
+ bus=EventBus(),
+ tools={
+ "spawn_worker": _FakeSpawnTool(),
+ "dispatch_to_harness": _FakeDispatchTool(),
+ },
+ tool_executor=_InertExecutor(), # type: ignore[arg-type]
+ )
+
+
+# The live failure: a depth marker ("Deep Dive") wrapping an explicit
+# computer-use / browser request. Must NOT force-spawn — it routes to the LLM
+# router which picks computer_use.
+FAILING_UTTERANCE = (
+ "Mach einen Deep Dive mit Computer Use in meinem Chrome Browser und "
+ "such mir den neuesten Post von Elon Musk raus"
+)
+
+
+def test_explicit_computer_use_request_does_not_force_spawn() -> None:
+ """The reported bug: a 'Deep Dive ... mit Computer Use ... Chrome Browser'
+ turn must reach Computer-Use, never a sub-agent spawn."""
+ manager = _manager()
+ assert manager._should_force_spawn(FAILING_UTTERANCE) is False, (
+ "explicit Computer-Use request was force-spawned into a sub-agent mission "
+ "— the depth keyword 'Deep Dive' overrode the on-screen/browser intent"
+ )
+
+
+def test_failing_utterance_is_recognised_as_computer_use() -> None:
+ """Sanity pin for the routing contract: the failing turn IS an on-screen /
+ browser request, so once the deterministic gate stands down the LLM router
+ (which owns computer_use) is the one that decides — i.e. it routes to CU."""
+ assert _looks_like_pc_control(FAILING_UTTERANCE) is True
+
+
+def test_computer_use_is_reachable_by_the_router() -> None:
+ """The LLM router can only pick Computer-Use if the tool is in its set."""
+ from jarvis.brain.factory import ROUTER_TOOLS
+
+ assert "computer-use" in ROUTER_TOOLS
+
+
+# --------------------------------------------------------------------------
+# Balanced scenario matrix.
+# --------------------------------------------------------------------------
+
+# Explicit on-screen / computer / browser requests — even when wrapped in a
+# depth marker — must NOT force-spawn (they reach the LLM router -> computer_use).
+_REACH_COMPUTER_USE = [
+ FAILING_UTTERANCE,
+ # depth marker ("gründliche") + explicit screen control ("Bildschirm"/"klick")
+ "Mach eine gründliche Analyse auf meinem Bildschirm und klick dich durch",
+ # English depth marker + browser
+ "Do a deep dive in my browser and click through the open tabs",
+ # a plain pc-control request (no depth marker at all) must also stay off the
+ # spawn path
+ "Schreib ABC in das ChatGPT Eingabefeld",
+]
+
+
[email protected]("utterance", _REACH_COMPUTER_USE)
+def test_on_screen_intents_do_not_force_spawn(utterance: str) -> None:
+ manager = _manager()
+ assert manager._should_force_spawn(utterance) is False, (
+ f"on-screen/computer/browser request {utterance!r} was wrongly force-spawned"
+ )
+
+
+# Genuine heavy background work must STILL force-spawn deterministically.
+_STILL_SPAWNS = [
+ # depth marker WITHOUT a screen signal (the test_cli_capability_routing
+ # contract: 'deep dive' over a CLI capability still spawns)
+ "Mach einen Deep Dive in meine Google Cloud Kosten",
+ # depth research, no screen signal
+ "Mach eine umfassende Recherche über die KI-News der letzten Woche",
+ # explicit vehicle name — absolute priority (mandate 2026-06-15)
+ "Spawne einen Subagenten der die Logs analysiert",
+ "Delegier das an einen Subagenten",
+ # explicit vehicle name DESPITE a screen signal — naming the vehicle wins
+ # over the computer-use stand-down (the mandate must survive the fix)
+ "Spawne einen Subagenten der in Chrome klickt und mir einen Report baut",
+]
+
+
[email protected]("utterance", _STILL_SPAWNS)
+def test_genuine_background_work_still_force_spawns(utterance: str) -> None:
+ manager = _manager()
+ assert manager._should_force_spawn(utterance) is True, (
+ f"genuine heavy/explicit work {utterance!r} should still force-spawn"
+ )
+
+
+# Smalltalk never spawns.
+_SMALLTALK = ["Hallo", "Wie geht's?", "Danke", "Was ist die Hauptstadt von Frankreich?"]
+
+
[email protected]("utterance", _SMALLTALK)
+def test_smalltalk_never_force_spawns(utterance: str) -> None:
+ manager = _manager()
+ assert manager._should_force_spawn(utterance) is False, (
+ f"smalltalk {utterance!r} wrongly force-spawned"
+ )
+
+
+def test_vehicle_plus_screen_signal_distinguishes_from_depth_plus_screen() -> None:
+ """The crux of the fix: a VEHICLE name + screen signal still spawns, while a
+ DEPTH marker + the same screen signal stands down. Proves the decision is not
+ a blanket keyword match but a vehicle-vs-depth distinction that hands the
+ ambiguous case to the LLM."""
+ manager = _manager()
+ vehicle = "Spawne einen Subagenten der in Chrome klickt und mir einen Report baut"
+ depth = "Mach einen Deep Dive und klick dich durch Chrome"
+ assert _looks_like_pc_control(vehicle) is True
+ assert _looks_like_pc_control(depth) is True
+ assert manager._should_force_spawn(vehicle) is True, "vehicle name must still spawn"
+ assert manager._should_force_spawn(depth) is False, "depth + screen must reach CU"
diff --git a/tests/unit/brain/test_deep_brain_follows_active.py b/tests/unit/brain/test_deep_brain_follows_active.py
index f3cf28236a..95d6571091 100644
--- a/tests/unit/brain/test_deep_brain_follows_active.py
+++ b/tests/unit/brain/test_deep_brain_follows_active.py
@@ -1,10 +1,10 @@
"""deep_brain must follow the user's chosen active provider.
-User mandate 2026-06-20: "Grok for everything." Forensic: with primary=grok but
+User mandate: "<provider> for everything." Forensic: with primary=openai but
[brain.router].{provider,fallback_provider}=gemini, the startup override moved the
-ACTIVE provider to grok (factory.py:817) while deep_brain stayed pinned to the
+ACTIVE provider to openai (factory.py:817) while deep_brain stayed pinned to the
tier's orphaned fallback (gemini). Result: deep/code intents led with Gemini
-(gemini-3.1-pro) even though the user picked Grok — chain[deep][0] == ("gemini", …).
+(gemini-3.1-pro) even though the user picked OpenAI — chain[deep][0] == ("gemini", …).
These lock that deep_brain follows the active provider both at boot (override) and
on a runtime switch, UNLESS there is a deliberate cross-provider deep split
@@ -28,41 +28,44 @@ def _cfg(*, primary: str, provider: str, fallback_provider: str | None):
def test_deep_brain_follows_override_when_no_explicit_split() -> None:
- # primary=grok overrides the tier default gemini; fallback==provider means
- # there is NO deliberate cross-provider deep split → deep must follow grok.
- cfg = _cfg(primary="grok", provider="gemini", fallback_provider="gemini")
- mgr = BrainManager.from_tier_config("router", cfg, EventBus(), provider_override="grok")
-
- assert mgr.active_provider == "grok"
- assert mgr._config.brain.deep_brain == "grok"
+ # primary=claude-api overrides the tier default gemini; fallback==provider
+ # means there is NO deliberate cross-provider deep split → deep must follow
+ # claude-api. (claude-api is used because the chain builder drops providers
+ # without a configured key; claude-api is keyed in this environment.)
+ cfg = _cfg(primary="claude-api", provider="gemini", fallback_provider="gemini")
+ mgr = BrainManager.from_tier_config("router", cfg, EventBus(), provider_override="claude-api")
+
+ assert mgr.active_provider == "claude-api"
+ assert mgr._config.brain.deep_brain == "claude-api"
deep_chain = mgr._build_fallback_chain("deep")
- # Grok leads deep/code, NOT Gemini (the exact regression).
- assert deep_chain[0][0] == "grok"
+ # The override provider leads deep/code, NOT Gemini (the exact regression).
+ assert deep_chain[0][0] == "claude-api"
assert deep_chain[0][0] != "gemini"
def test_code_intent_also_led_by_override_provider() -> None:
- cfg = _cfg(primary="grok", provider="gemini", fallback_provider="gemini")
- mgr = BrainManager.from_tier_config("router", cfg, EventBus(), provider_override="grok")
- assert mgr._build_fallback_chain("code")[0][0] == "grok"
+ cfg = _cfg(primary="claude-api", provider="gemini", fallback_provider="gemini")
+ mgr = BrainManager.from_tier_config("router", cfg, EventBus(), provider_override="claude-api")
+ assert mgr._build_fallback_chain("code")[0][0] == "claude-api"
def test_explicit_cross_provider_deep_split_is_preserved() -> None:
# fallback_provider != provider is a deliberate "delegate deep elsewhere"
# split — an override of the fast provider must NOT erase it.
- cfg = _cfg(primary="grok", provider="gemini", fallback_provider="claude-api")
- mgr = BrainManager.from_tier_config("router", cfg, EventBus(), provider_override="grok")
- assert mgr.active_provider == "grok"
- assert mgr._config.brain.deep_brain == "claude-api"
+ cfg = _cfg(primary="claude-api", provider="gemini", fallback_provider="openai")
+ mgr = BrainManager.from_tier_config("router", cfg, EventBus(), provider_override="claude-api")
+ assert mgr.active_provider == "claude-api"
+ assert mgr._config.brain.deep_brain == "openai"
def test_deep_brain_follows_override_when_no_fallback_configured() -> None:
# A minimal toml ([brain.router] provider only, no fallback_provider) must
- # NOT strand deep_brain at None when an override is active — it follows grok.
- cfg = _cfg(primary="grok", provider="gemini", fallback_provider=None)
- mgr = BrainManager.from_tier_config("router", cfg, EventBus(), provider_override="grok")
- assert mgr._config.brain.deep_brain == "grok"
- assert mgr._build_fallback_chain("deep")[0][0] == "grok"
+ # NOT strand deep_brain at None when an override is active — it follows the
+ # override provider.
+ cfg = _cfg(primary="claude-api", provider="gemini", fallback_provider=None)
+ mgr = BrainManager.from_tier_config("router", cfg, EventBus(), provider_override="claude-api")
+ assert mgr._config.brain.deep_brain == "claude-api"
+ assert mgr._build_fallback_chain("deep")[0][0] == "claude-api"
def test_deep_brain_stable_across_two_boots() -> None:
@@ -70,13 +73,13 @@ def test_deep_brain_stable_across_two_boots() -> None:
# so deep_brain must be identical after a simulated restart (no persistence of
# deep_brain itself needed). Load-bearing safety assumption — lock it.
def boot():
- cfg = _cfg(primary="grok", provider="gemini", fallback_provider="gemini")
+ cfg = _cfg(primary="claude-api", provider="gemini", fallback_provider="gemini")
return BrainManager.from_tier_config(
- "router", cfg, EventBus(), provider_override="grok"
+ "router", cfg, EventBus(), provider_override="claude-api"
)._config.brain.deep_brain
- assert boot() == "grok"
- assert boot() == "grok"
+ assert boot() == "claude-api"
+ assert boot() == "claude-api"
def test_no_override_keeps_tier_fallback_as_deep() -> None:
@@ -89,17 +92,17 @@ def test_no_override_keeps_tier_fallback_as_deep() -> None:
@pytest.mark.asyncio
async def test_runtime_switch_carries_deep_brain() -> None:
- # Boot on gemini (deep_brain=gemini), then switch to grok at runtime: deep
+ # Boot on gemini (deep_brain=gemini), then switch to openai at runtime: deep
# must follow so a frontier switch leads ALL intents, not just fast ones.
cfg = _cfg(primary="gemini", provider="gemini", fallback_provider="gemini")
mgr = BrainManager.from_tier_config("router", cfg, EventBus())
assert mgr._config.brain.deep_brain == "gemini"
- await mgr.switch("grok")
+ await mgr.switch("openai")
- assert mgr.active_provider == "grok"
- assert mgr._config.brain.deep_brain == "grok"
- assert mgr._build_fallback_chain("deep")[0][0] == "grok"
+ assert mgr.active_provider == "openai"
+ assert mgr._config.brain.deep_brain == "openai"
+ assert mgr._build_fallback_chain("deep")[0][0] == "openai"
@pytest.mark.asyncio
@@ -109,9 +112,9 @@ async def test_runtime_switch_promotes_none_deep_brain() -> None:
cfg = _cfg(primary="gemini", provider="gemini", fallback_provider=None)
mgr = BrainManager.from_tier_config("router", cfg, EventBus())
assert mgr._config.brain.deep_brain is None
- await mgr.switch("grok")
- assert mgr.active_provider == "grok"
- assert mgr._config.brain.deep_brain == "grok"
+ await mgr.switch("openai")
+ assert mgr.active_provider == "openai"
+ assert mgr._config.brain.deep_brain == "openai"
@pytest.mark.asyncio
@@ -122,7 +125,7 @@ async def test_runtime_switch_preserves_explicit_split() -> None:
mgr = BrainManager.from_tier_config("router", cfg, EventBus())
assert mgr._config.brain.deep_brain == "claude-api"
- await mgr.switch("grok")
+ await mgr.switch("openai")
- assert mgr.active_provider == "grok"
+ assert mgr.active_provider == "openai"
assert mgr._config.brain.deep_brain == "claude-api"
diff --git a/tests/unit/brain/test_drop_content_types.py b/tests/unit/brain/test_drop_content_types.py
new file mode 100644
index 0000000000..a8c29dd16b
--- /dev/null
+++ b/tests/unit/brain/test_drop_content_types.py
@@ -0,0 +1,115 @@
+"""Exhaustive content-type coverage for the drag-drop classifier.
+
+The user requires "all possible things you can drag-and-drop" to work. This
+parametrises ``classify_and_compose`` over every droppable kind — documents,
+code, data, markup, images, PDFs, archives/binaries, dragged text + URLs, and
+mixed multi-file drops — asserting each is routed correctly:
+ * image/* -> a multimodal ImageBlock (the brain can SEE it)
+ * text/code/data/markup -> inlined into the directive (the brain can READ it)
+ * pdf -> noted (extracted when pypdf can, named otherwise)
+ * unknown binary -> named only, never decoded
+ * dragged text / URL -> inlined
+"""
+from __future__ import annotations
+
+import base64
+
+import pytest
+
+from jarvis.brain.drop_context import DroppedItem, classify_and_compose
+
+# (name, mime) pairs the OS realistically hands us for a dropped file.
+_TEXTUAL = [
+ ("notes.txt", "text/plain"),
+ ("README.md", "text/markdown"),
+ ("data.json", "application/json"),
+ ("table.csv", "text/csv"),
+ ("conf.yaml", "application/x-yaml"),
+ ("pyproject.toml", "application/octet-stream"), # by extension
+ ("page.html", "text/html"),
+ ("style.css", "text/css"),
+ ("doc.xml", "application/xml"),
+ ("script.py", "text/x-python"),
+ ("app.js", "application/javascript"),
+ ("comp.tsx", "application/octet-stream"), # by extension
+ ("main.rs", "application/octet-stream"), # by extension
+ ("Main.java", "application/octet-stream"), # by extension
+ ("query.sql", "application/sql"),
+ ("run.sh", "application/x-sh"),
+ ("notes.log", "text/plain"),
+]
+
+_IMAGES = [
+ ("photo.png", "image/png"),
+ ("pic.jpg", "image/jpeg"),
+ ("anim.gif", "image/gif"),
+ ("shot.webp", "image/webp"),
+ ("logo.bmp", "image/bmp"),
+]
+
+_BINARY = [
+ ("archive.zip", "application/zip"),
+ ("tool.exe", "application/octet-stream"),
+ ("song.mp3", "audio/mpeg"),
+ ("clip.mp4", "video/mp4"),
+]
+
+
[email protected]("name,mime", _TEXTUAL)
+def test_textual_kinds_are_inlined(name: str, mime: str) -> None:
+ body = "UNIQUE_TOKEN_42 content body"
+ text, images = classify_and_compose([DroppedItem(name, mime, body.encode())])
+ assert images == ()
+ assert name in text
+ assert "UNIQUE_TOKEN_42" in text, f"{name} ({mime}) should be inlined as text"
+
+
[email protected]("name,mime", _IMAGES)
+def test_image_kinds_become_imageblocks(name: str, mime: str) -> None:
+ raw = b"\x00\x01\x02 fake-image-bytes"
+ text, images = classify_and_compose([DroppedItem(name, mime, raw)])
+ assert len(images) == 1
+ assert images[0].mime == mime
+ assert base64.b64decode(images[0].data_b64) == raw
+ assert name in text
+
+
[email protected]("name,mime", _BINARY)
+def test_binary_kinds_are_named_not_decoded(name: str, mime: str) -> None:
+ text, images = classify_and_compose([DroppedItem(name, mime, b"\x00\xffraw\x00bytes")])
+ assert images == ()
+ assert name in text
+ assert "raw\x00bytes" not in text
+
+
+def test_dragged_url_is_inlined() -> None:
+ text, images = classify_and_compose([], dragged_text="https://example.com/path?q=1")
+ assert images == ()
+ assert "https://example.com/path?q=1" in text
+
+
+def test_dragged_plain_text_is_inlined() -> None:
+ text, _ = classify_and_compose([], dragged_text="some selected paragraph of text")
+ assert "some selected paragraph of text" in text
+
+
+def test_mixed_multi_file_drop() -> None:
+ items = [
+ DroppedItem("a.png", "image/png", b"img1"),
+ DroppedItem("b.txt", "text/plain", b"text body B"),
+ DroppedItem("c.zip", "application/zip", b"PK\x03\x04"),
+ DroppedItem("d.jpg", "image/jpeg", b"img2"),
+ ]
+ text, images = classify_and_compose(items)
+ assert len(images) == 2 # both pictures
+ for n in ("a.png", "b.txt", "c.zip", "d.jpg"):
+ assert n in text
+ assert "text body B" in text
+
+
+def test_files_plus_dragged_text_together() -> None:
+ text, images = classify_and_compose(
+ [DroppedItem("x.png", "image/png", b"i")], dragged_text="https://ref.example"
+ )
+ assert len(images) == 1
+ assert "x.png" in text and "https://ref.example" in text
diff --git a/tests/unit/brain/test_drop_context.py b/tests/unit/brain/test_drop_context.py
new file mode 100644
index 0000000000..1630315d9f
--- /dev/null
+++ b/tests/unit/brain/test_drop_context.py
@@ -0,0 +1,139 @@
+"""Unit tests for the drag-drop content classifier/composer (``drop_context``).
+
+The pure ``classify_and_compose`` turns dropped OS items (files, dragged text)
+into (directive_text, ImageBlocks) for a proactive ``MessageSent`` brain turn.
+Images ride the multimodal path; text/code is inlined (bounded); unknown binary
+is named only. See docs/superpowers/specs/2026-06-21-dragdrop-files-into-context-design.md.
+"""
+from __future__ import annotations
+
+import base64
+
+from jarvis.brain.drop_context import (
+ DROP_SOURCE_LAYER,
+ DroppedItem,
+ classify_and_compose,
+)
+
+
+def test_drop_source_layer_constant() -> None:
+ """The wire-format marker is stable and namespaced."""
+ assert DROP_SOURCE_LAYER == "ui.drop"
+
+
+def test_image_item_becomes_imageblock_and_directive_note() -> None:
+ item = DroppedItem(name="photo.png", mime="image/png", data=b"\x89PNGfake-bytes")
+ text, images = classify_and_compose([item])
+
+ assert len(images) == 1
+ assert images[0].mime == "image/png"
+ assert base64.b64decode(images[0].data_b64) == b"\x89PNGfake-bytes"
+ assert "photo.png" in text
+ # The directive must instruct the model to react, not stay silent.
+ assert text.strip() != ""
+
+
+def test_text_item_is_inlined_into_directive() -> None:
+ body = "def hello():\n return 'hi'\n"
+ item = DroppedItem(name="snippet.py", mime="text/x-python", data=body.encode())
+ text, images = classify_and_compose([item])
+
+ assert images == ()
+ assert "snippet.py" in text
+ assert "return 'hi'" in text
+
+
+def test_text_item_classified_by_extension_when_mime_is_generic() -> None:
+ """A forged/empty octet-stream MIME still inlines for a known text suffix."""
+ item = DroppedItem(
+ name="notes.md", mime="application/octet-stream", data=b"# Title\nhello"
+ )
+ text, images = classify_and_compose([item])
+
+ assert images == ()
+ assert "hello" in text
+
+
+def test_pdf_without_extraction_is_noted_not_crashed() -> None:
+ item = DroppedItem(name="report.pdf", mime="application/pdf", data=b"%PDF-1.4 noise")
+ text, images = classify_and_compose([item])
+
+ assert images == ()
+ assert "report.pdf" in text # named, even if content not extracted
+
+
+def test_unknown_binary_is_named_only() -> None:
+ item = DroppedItem(name="archive.zip", mime="application/zip", data=b"PK\x03\x04rest")
+ text, images = classify_and_compose([item])
+
+ assert images == ()
+ assert "archive.zip" in text
+ # Raw binary is never decoded into the directive.
+ assert "PK\x03\x04" not in text
+
+
+def test_empty_drop_yields_no_turn() -> None:
+ text, images = classify_and_compose([], dragged_text=None)
+ assert text == ""
+ assert images == ()
+
+
+def test_dragged_text_only_is_inlined() -> None:
+ text, images = classify_and_compose([], dragged_text="https://example.com/x")
+ assert images == ()
+ assert "https://example.com/x" in text
+
+
+def test_text_file_is_capped() -> None:
+ huge = "A" * 50_000
+ item = DroppedItem(name="big.txt", mime="text/plain", data=huge.encode())
+ text, _images = classify_and_compose([item], max_text_chars=1000)
+
+ assert "big.txt" in text
+ # The 50k body must be truncated well below its original size.
+ assert text.count("A") <= 1100
+
+
+def test_oversized_image_is_capped() -> None:
+ """A large dropped image is downscaled below the per-image budget so it can't
+ blow the LLM API's per-image limit (spec §3 — reuse cap_image_b64)."""
+ import io
+ import os
+
+ from PIL import Image
+
+ buf = io.BytesIO()
+ # Random noise so PNG cannot compress it away — a genuinely large payload.
+ Image.frombytes("RGB", (1200, 1200), os.urandom(1200 * 1200 * 3)).save(
+ buf, format="PNG"
+ )
+ big = buf.getvalue()
+ assert len(big) > 60_000 # the source really is over the test budget
+
+ item = DroppedItem(name="huge.png", mime="image/png", data=big)
+ _text, images = classify_and_compose([item], max_image_bytes=50_000)
+
+ assert len(images) == 1
+ decoded = base64.b64decode(images[0].data_b64)
+ # The cap engaged: the over-budget PNG was re-encoded (JPEG) and shrank.
+ assert images[0].mime == "image/jpeg"
+ assert len(decoded) < len(big), "capped image must be smaller than the original"
+
+
+def test_small_image_within_budget_is_untouched() -> None:
+ item = DroppedItem(name="tiny.png", mime="image/png", data=b"\x89PNGsmall")
+ _text, images = classify_and_compose([item], max_image_bytes=10_000_000)
+ assert base64.b64decode(images[0].data_b64) == b"\x89PNGsmall"
+
+
+def test_multiple_items_mixed() -> None:
+ items = [
+ DroppedItem(name="a.png", mime="image/png", data=b"img"),
+ DroppedItem(name="b.txt", mime="text/plain", data=b"plain body"),
+ ]
+ text, images = classify_and_compose(items)
+
+ assert len(images) == 1
+ assert "a.png" in text
+ assert "b.txt" in text
+ assert "plain body" in text
diff --git a/tests/unit/brain/test_drop_ingest.py b/tests/unit/brain/test_drop_ingest.py
new file mode 100644
index 0000000000..2b58232378
--- /dev/null
+++ b/tests/unit/brain/test_drop_ingest.py
@@ -0,0 +1,84 @@
+"""``ingest_drop`` — capture dropped content as SILENT context (never a turn).
+
+A drop must NOT trigger a brain turn. ``ingest_drop`` classifies the content and
+hands it to ``brain.add_dropped_context``; it does not publish any turn-triggering
+event. Jarvis reacts only on the user's next real turn.
+"""
+from __future__ import annotations
+
+import pytest
+
+from jarvis.brain.drop_context import DroppedItem, ingest_drop
+
+
+class _FakeBrain:
+ def __init__(self) -> None:
+ self.dropped: list[tuple] = []
+
+ def add_dropped_context(self, text, images=()) -> None:
+ self.dropped.append((text, images))
+
+
+class _FakeBus:
+ def __init__(self) -> None:
+ self.published: list[object] = []
+
+ async def publish(self, event: object) -> None:
+ self.published.append(event)
+
+
+async def test_ingest_drop_adds_context_and_triggers_no_turn() -> None:
+ brain = _FakeBrain()
+ bus = _FakeBus()
+ items = [
+ DroppedItem("a.png", "image/png", b"img"),
+ DroppedItem("b.txt", "text/plain", b"hello body"),
+ ]
+
+ ok = await ingest_drop(bus=bus, brain=brain, thread_id="t1", items=items)
+
+ assert ok is True
+ # Captured as context...
+ assert len(brain.dropped) == 1
+ text, images = brain.dropped[0]
+ assert "a.png" in text and "b.txt" in text and "hello body" in text
+ assert len(images) == 1
+ # ...and NOTHING was published that could trigger a turn.
+ assert bus.published == []
+
+
+async def test_ingest_empty_drop_captures_nothing() -> None:
+ brain = _FakeBrain()
+ ok = await ingest_drop(brain=brain, thread_id="t1", items=[])
+ assert ok is False
+ assert brain.dropped == []
+
+
+async def test_ingest_dragged_text_only_is_captured() -> None:
+ brain = _FakeBrain()
+ ok = await ingest_drop(
+ brain=brain, thread_id="t3", items=[], dragged_text="https://example.com/x"
+ )
+ assert ok is True
+ assert "example.com" in brain.dropped[0][0]
+
+
+async def test_ingest_without_brain_returns_false() -> None:
+ ok = await ingest_drop(
+ brain=None, thread_id="t1", items=[DroppedItem("b.txt", "text/plain", b"hi")]
+ )
+ assert ok is False
+
+
+async def test_ingest_text_only_drop_carries_no_images() -> None:
+ brain = _FakeBrain()
+ await ingest_drop(
+ brain=brain, thread_id="t1", items=[DroppedItem("b.txt", "text/plain", b"hello")]
+ )
+ _text, images = brain.dropped[0]
+ assert images == ()
diff --git a/tests/unit/brain/test_drop_paths.py b/tests/unit/brain/test_drop_paths.py
new file mode 100644
index 0000000000..7a66b28bc7
--- /dev/null
+++ b/tests/unit/brain/test_drop_paths.py
@@ -0,0 +1,45 @@
+"""``items_from_paths`` — read dropped file PATHS (overlay drop) into DroppedItems.
+
+The web dock posts bytes (multipart); the native overlay drop hands file PATHS.
+This shared reader normalises paths → DroppedItem(name, mime, bytes) with a total
+byte cap, so both surfaces feed the same ``ingest_drop``.
+"""
+from __future__ import annotations
+
+from jarvis.brain.drop_context import DroppedItem, items_from_paths
+
+
+def test_reads_a_real_file(tmp_path) -> None:
+ p = tmp_path / "hello.txt"
+ p.write_bytes(b"hi there")
+ items = items_from_paths([str(p)])
+ assert items == [DroppedItem(name="hello.txt", mime="text/plain", data=b"hi there")]
+
+
+def test_guesses_image_mime_from_extension(tmp_path) -> None:
+ p = tmp_path / "pic.png"
+ p.write_bytes(b"\x89PNGxx")
+ items = items_from_paths([str(p)])
+ assert len(items) == 1
+ assert items[0].mime == "image/png"
+
+
+def test_skips_nonexistent_paths(tmp_path) -> None:
+ real = tmp_path / "a.txt"
+ real.write_bytes(b"a")
+ items = items_from_paths([str(tmp_path / "ghost.txt"), str(real)])
+ assert [i.name for i in items] == ["a.txt"]
+
+
+def test_total_byte_cap_stops_reading(tmp_path) -> None:
+ a = tmp_path / "a.bin"
+ a.write_bytes(b"x" * 1000)
+ b = tmp_path / "b.bin"
+ b.write_bytes(b"y" * 1000)
+ items = items_from_paths([str(a), str(b)], max_total_bytes=1500)
+ # First file fits; the second would breach the cap → not included.
+ assert [i.name for i in items] == ["a.bin"]
+
+
+def test_empty_paths_yield_no_items() -> None:
+ assert items_from_paths([]) == []
diff --git a/tests/unit/brain/test_drop_silent_context.py b/tests/unit/brain/test_drop_silent_context.py
new file mode 100644
index 0000000000..b76a3cca06
--- /dev/null
+++ b/tests/unit/brain/test_drop_silent_context.py
@@ -0,0 +1,102 @@
+"""Dropped content is SILENT context, never an immediate brain turn.
+
+The user's contract: dragging something onto the bar/mascot must NOT make Jarvis
+think right away — it is remembered and used on the NEXT time the user actually
+speaks/types (the normal conversation flow). A drop while idle is kept for next
+time; a drop mid-conversation joins the running context. Either way: no turn is
+triggered by the drop itself.
+"""
+from __future__ import annotations
+
+from collections.abc import AsyncIterator
+from uuid import uuid4
+
+import pytest
+
+from jarvis.brain.manager import BrainManager
+from jarvis.brain.streaming import StreamingAggregate
+from jarvis.core.bus import EventBus
+from jarvis.core.config import JarvisConfig
+from jarvis.core.protocols import BrainDelta, BrainRequest, ImageBlock
+
+
+class _FakeBrain:
+ name = "fake"
+ context_window = 8192
+ supports_tools = True
+ supports_vision = True
+
+ async def complete(self, req: BrainRequest) -> AsyncIterator[BrainDelta]:
+ yield BrainDelta(content="ok")
+ yield BrainDelta(finish_reason="stop")
+
+
+class _RecordingDispatcher:
+ def __init__(self) -> None:
+ self.calls: list[dict] = []
+
+ async def dispatch(self, user_text, *, images=(), history=None, **_kwargs):
+ self.calls.append({"user_text": user_text, "images": images, "history": history})
+ agg = StreamingAggregate()
+ agg.text = "reply"
+ agg.finish_reason = "stop"
+ return agg
+
+
+def _manager() -> tuple[BrainManager, _RecordingDispatcher]:
+ cfg = JarvisConfig()
+ cfg.brain.primary = "fake"
+ m = BrainManager(config=cfg, bus=EventBus(), tools={})
+ rec = _RecordingDispatcher()
+ m._build_fallback_chain = lambda _l: [("fake", "fake-model")] # type: ignore[method-assign]
+ m._get_brain = lambda _n, _mo: _FakeBrain() # type: ignore[method-assign]
+ m._build_dispatcher = lambda _b, *, tools_override=None: rec # type: ignore[method-assign]
+ return m, rec
+
+
+_IMG = ImageBlock(mime="image/png", data_b64="ZmFrZQ==")
+
+
+async def test_drop_does_not_trigger_a_turn() -> None:
+ m, rec = _manager()
+ m.add_dropped_context("[dropped report.pdf: SECRET_TOKEN_99]", (_IMG,))
+ # The drop alone must NOT have generated anything.
+ assert rec.calls == []
+
+
+async def test_dropped_text_is_in_context_on_next_turn() -> None:
+ m, rec = _manager()
+ m.add_dropped_context("[dropped report.pdf: SECRET_TOKEN_99]", ())
+
+ await m.generate("summarize this", trace_id=uuid4(), use_history=True)
+
+ assert len(rec.calls) == 1
+ hist = rec.calls[0]["history"] or []
+ joined = " ".join(str(getattr(msg, "content", "")) for msg in hist)
+ assert "SECRET_TOKEN_99" in joined, "the dropped text must be in the turn's context"
+
+
+async def test_dropped_image_reaches_next_turn_only() -> None:
+ m, rec = _manager()
+ m.add_dropped_context("[dropped photo.png]", (_IMG,))
+
+ await m.generate("what is this", trace_id=uuid4(), use_history=True)
+ await m.generate("and now", trace_id=uuid4(), use_history=True)
+
+ assert _IMG in rec.calls[0]["images"] # consumed on the first real turn
+ assert _IMG not in rec.calls[1]["images"] # not re-sent on the next turn
+
+
+async def test_multiple_drops_accumulate() -> None:
+ m, rec = _manager()
+ m.add_dropped_context("[dropped a.txt: AAA]", ())
+ m.add_dropped_context("[dropped b.txt: BBB]", ())
+
+ await m.generate("go", trace_id=uuid4(), use_history=True)
+
+ hist = " ".join(str(getattr(msg, "content", "")) for msg in (rec.calls[0]["history"] or []))
+ assert "AAA" in hist and "BBB" in hist
diff --git a/tests/unit/brain/test_explicit_computer_use_routing.py b/tests/unit/brain/test_explicit_computer_use_routing.py
new file mode 100644
index 0000000000..e397125569
--- /dev/null
+++ b/tests/unit/brain/test_explicit_computer_use_routing.py
@@ -0,0 +1,196 @@
+"""Explicit "use Computer-Use" requests must reach the screenshot harness.
+
+Live repro (user, 2026-06-21): "Kannst du für mich bitte mit Computer-Use in
+Spotify das Lied Perfect von Ed Sheeran abspielen?" was only ACKNOWLEDGED
+("Ich schau gerade in Spotify nach dem Lied …") — the Computer-Use action never
+dispatched or executed.
+
+Root cause: the deterministic ``match_local_action`` gate had no pattern for an
+EXPLICITLY-named Computer-Use request that lacks an open verb. The phrase
+returned ``None``, fell through to the LLM talker, and the talker only emitted a
+free-text acknowledgement (the gate's own comments already warn "never depend on
+the LLM talker calling computer_use" — ``local_action_gate.py``). The strongest
+deterministic CU signal of all — the user NAMING the harness — must route to the
+harness without depending on the LLM.
+
+These tests pin BOTH halves with no LLM:
+ 1. routing — ``match_local_action`` returns a COMPUTER_USE plan for the repro
+ phrase and other explicit-CU phrasings (de + en);
+ 2. dispatch — driving the real gate through
+ ``BrainManager._run_local_action_fast_path`` actually CALLS the tool
+ executor with the screenshot harness and announces a completion (genuinely
+ dispatched + executed, not merely acknowledged).
+
+Precision guards keep how-to / explain / negated mentions OFF the harness.
+"""
+from __future__ import annotations
+
+import asyncio
+from types import SimpleNamespace
+
+import pytest
+
+from jarvis.brain.local_action_gate import (
+ HARNESS_NAME,
+ LocalActionMode,
+ match_local_action,
+)
+
+# The exact live utterance that broke, plus adjacent explicit-CU phrasings that
+# carry NO open verb (so the open-app fallback can never save them).
+REPRO_PHRASE = (
+ "Kannst du für mich bitte mit Computer-Use in Spotify das Lied Perfect "
+ "von Ed Sheeran abspielen?"
+)
+
+_EXPLICIT_CU_UTTERANCES = [
+ REPRO_PHRASE,
+ "Spiel mit Computer-Use das nächste Lied",
+ "Mach das per Computer-Use",
+ "Erledige das über Computer-Use",
+ "Nutze Computer-Use und like den obersten Post",
+ "Benutze die Computer-Use Funktion dafür",
+ "Verwende Computer-Use um durch mein Spotify zu blättern",
+ "Use computer use to skip to the next track in Spotify",
+ "Do it with computer use",
+ "Using computer use, pause the music",
+]
+
+
[email protected]("utterance", _EXPLICIT_CU_UTTERANCES)
+def test_explicit_computer_use_request_routes_to_harness(utterance: str) -> None:
+ """An explicitly-named Computer-Use request routes DETERMINISTICALLY to the
+ screenshot harness — never falls through to the (possibly tool-less) talker.
+
+ ``_registry=None`` keeps the gate hermetic (no production capability-registry
+ singleton touch). Before the fix the repro phrase returned ``None``.
+ """
+ plan = match_local_action(utterance, _registry=None)
+ assert plan is not None, (
+ f"{utterance!r} fell through to the brain — explicit Computer-Use "
+ "request was not routed to the harness"
+ )
+ assert plan.mode is LocalActionMode.COMPUTER_USE, (
+ f"{utterance!r} → {plan.mode}, want COMPUTER_USE"
+ )
+ assert plan.harness == HARNESS_NAME, f"{utterance!r} → harness {plan.harness!r}"
+ # The full request (including the song / action) must reach the harness, not
+ # a stripped fragment.
+ assert plan.prompt == utterance.strip()
+
+
+ "utterance",
+ [
+ # How-to / explain mentions are NOT a command to drive the screen.
+ "Was ist Computer-Use?",
+ "Wie funktioniert Computer-Use?",
+ "Erklär mir Computer-Use",
+ "What is computer use",
+ # No harness mention at all — unaffected normal answers.
+ "schreib mir ein Gedicht über den Herbst",
+ "was ist die Hauptstadt von Frankreich",
+ ],
+)
+def test_non_command_computer_use_mentions_do_not_route_to_harness(
+ utterance: str,
+) -> None:
+ """Precision guard: a question/explanation that merely names Computer-Use, or
+ a phrase that does not name it at all, must NOT be hijacked onto the harness.
+ """
+ plan = match_local_action(utterance, _registry=None)
+ if plan is not None:
+ assert plan.mode is not LocalActionMode.COMPUTER_USE, (
+ f"{utterance!r} wrongly routed to COMPUTER_USE: {plan}"
+ )
+
+
+# ---------------------------------------------------------------------------
+# End-to-end dispatch: driving the REAL gate through the fast path must actually
+# call the tool executor with the screenshot harness AND announce a completion —
+# proving the action is genuinely dispatched + executed, not merely acknowledged.
+# Mirrors the harness in tests/unit/brain/test_computer_use_offload.py.
+# ---------------------------------------------------------------------------
+
+
+class _FakeBus:
+ def __init__(self) -> None:
+ self.published: list = []
+
+ async def publish(self, event) -> None: # noqa: ANN001
+ self.published.append(event)
+
+
+class _RecordingHarnessExecutor:
+ """tool_executor stand-in that records the harness it was dispatched to."""
+
+ def __init__(self) -> None:
+ self.calls: list[dict] = []
+
+ async def execute(self, tool, args, *, user_utterance, trace_id): # noqa: ANN001
+ self.calls.append(dict(args))
+ return SimpleNamespace(success=True, output="[cu] done (verified)", error=None)
+
+
+def _make_manager(executor, bus):
+ from jarvis.brain.manager import BrainManager
+
+ mgr = BrainManager.__new__(BrainManager)
+ mgr._config = SimpleNamespace(
+ local_action=SimpleNamespace(
+ enabled=True, harness_timeout_s=30.0, direct_timeout_s=3.0
+ )
+ )
+ mgr._bus = bus
+ mgr._tool_executor = executor
+ mgr._local_action_tools = {"dispatch_to_harness": object()}
+ mgr._cost_meter = None
+ mgr._reply_language = "auto"
+ return mgr
+
+
+async def test_repro_phrase_actually_dispatches_and_executes_harness(
+ monkeypatch,
+) -> None:
+ """The live repro phrase, driven through the REAL gate + fast path, must
+ actually dispatch and execute the screenshot harness and announce the
+ completion — not merely return an acknowledgement.
+ """
+ from jarvis.brain.local_action_gate import (
+ match_local_action as real_match_local_action,
+ )
+
+ # Use the REAL routing logic, pinned hermetic (no capability-registry singleton).
+ monkeypatch.setattr(
+ "jarvis.brain.manager.match_local_action",
+ lambda text: real_match_local_action(text, _registry=None),
+ )
+
+ bus = _FakeBus()
+ executor = _RecordingHarnessExecutor()
+ mgr = _make_manager(executor, bus)
+
+ ack = await mgr._run_local_action_fast_path(REPRO_PHRASE)
+
+ # The turn ACKs immediately (not None — None would re-route to the talker).
+ assert ack, "explicit Computer-Use request must yield an immediate dispatch ACK"
+
+ # Drain the background mission spawned by the fast path.
+ await asyncio.gather(*getattr(mgr, "_cu_background_tasks", set()))
+
+ # GENUINELY dispatched + executed: the executor was called with the
+ # screenshot harness and the user's request as the prompt.
+ assert executor.calls, "the harness was never dispatched (acknowledged but never acted)"
+ assert executor.calls[0]["harness"] == HARNESS_NAME, (
+ f"dispatched to {executor.calls[0]['harness']!r}, want {HARNESS_NAME!r}"
+ )
+ assert "Perfect" in executor.calls[0]["prompt"], (
+ "the user's request must reach the harness verbatim"
+ )
+
+ # The outcome is announced (AD-OE6 zero silent drops).
+ completions = [
+ e for e in bus.published if getattr(e, "kind", None) == "completion"
+ ]
+ assert completions, "the Computer-Use outcome must be announced as a completion"
diff --git a/tests/unit/brain/test_frontier_resolver.py b/tests/unit/brain/test_frontier_resolver.py
index bc4875450c..14a8043050 100644
--- a/tests/unit/brain/test_frontier_resolver.py
+++ b/tests/unit/brain/test_frontier_resolver.py
@@ -19,7 +19,6 @@ from jarvis.brain.frontier_resolver import (
FrontierResolver,
_pick_anthropic,
_pick_gemini,
- _pick_grok,
_pick_openai,
)
@@ -90,51 +89,6 @@ class TestPickGemini:
assert _pick_gemini(models, "fast") == "gemini-3-flash"
-class TestPickGrok:
- def test_fast_picks_fast_variant(self) -> None:
- models = [
- "grok-3",
- "grok-4",
- "grok-4.1-fast",
- "grok-4-fast-reasoning",
- "grok-4.20",
- ]
- # Fast-Tier: nur "fast" ohne "reasoning". Hoechste Major.Minor → 4.1
- assert _pick_grok(models, "fast") == "grok-4.1-fast"
-
- def test_deep_picks_full_version(self) -> None:
- models = [
- "grok-3",
- "grok-4",
- "grok-4.1-fast",
- "grok-4.20",
- ]
- # Deep-Tier: kein "fast" oder mit "reasoning". 4.20 > 4 > 3.
- assert _pick_grok(models, "deep") == "grok-4.20"
-
- def test_deep_returns_none_when_only_fast_available(self) -> None:
- # 2026-04-29 Update: Notanker entfernt. Wenn die API-Liste nur
- # fast-Varianten kennt, returnt Picker None — TOML-Default gewinnt.
- # Verhindert dass grok-fast als deep-Pick gilt obwohl es nicht passt.
- models = ["grok-3-fast", "grok-4-fast"]
- assert _pick_grok(models, "deep") is None
-
- def test_grok_4_3_wins_both_tiers_when_listed(self) -> None:
- # 2026-04-30: grok-4.3 ist laut xAI gleichzeitig schnellstes UND
- # intelligentestes Grok — Short-Circuit, beide Tiers bekommen 4.3
- # statt der naiven Major.Minor-Sortierung (die 4.20 > 4.3 ergaebe).
- models = ["grok-3", "grok-4.1-fast", "grok-4.20", "grok-4.3"]
- assert _pick_grok(models, "fast") == "grok-4.3"
- assert _pick_grok(models, "deep") == "grok-4.3"
-
- def test_falls_back_when_grok_4_3_absent(self) -> None:
- # Wenn der User-Account 4.3 noch nicht freigeschaltet hat,
- # bleibt die alte Sortierlogik aktiv.
- models = ["grok-3", "grok-4.1-fast", "grok-4.20"]
- assert _pick_grok(models, "fast") == "grok-4.1-fast"
- assert _pick_grok(models, "deep") == "grok-4.20"
-
-
class TestPickOpenAI:
def test_fast_picks_newest_non_pro(self) -> None:
models = [
@@ -191,15 +145,15 @@ class TestCache:
def test_save_cache_persists_to_disk(self, tmp_path: Path) -> None:
cache_path = tmp_path / "frontier_cache.json"
resolver = FrontierResolver(cache_path=cache_path)
- resolver._cache["grok"] = {
+ resolver._cache["openai"] = {
"fast": FrontierModel(
- provider="grok", tier="fast",
- model_id="grok-4.1-fast", fetched_at=time.time(),
+ provider="openai", tier="fast",
+ model_id="gpt-5.5", fetched_at=time.time(),
),
}
resolver._save_cache()
loaded = json.loads(cache_path.read_text())
- assert loaded["grok"]["fast"]["model_id"] == "grok-4.1-fast"
+ assert loaded["openai"]["fast"]["model_id"] == "gpt-5.5"
def test_is_fresh_within_ttl(self, tmp_path: Path) -> None:
resolver = FrontierResolver(cache_path=tmp_path / "c.json", ttl_hours=24)
diff --git a/tests/unit/brain/test_intelligent_router.py b/tests/unit/brain/test_intelligent_router.py
new file mode 100644
index 0000000000..7b2d5f9441
--- /dev/null
+++ b/tests/unit/brain/test_intelligent_router.py
@@ -0,0 +1,172 @@
+"""Intelligent router (2026-06-21 mandate: "choose wisely among ALL tools").
+
+When the ACTIVE talker cannot emit tool_calls (for example a provider/model
+path without tool-call support), a tool-capable provider LEADS every
+substantive turn and the LLM picks the tool via its tool-use loop + system
+prompt (no signal-word list decides the tool). If the router picks NO tool (pure
+conversation), the turn FALLS THROUGH to the chosen talker so the user keeps
+their selected brain's voice. Tool-capable talkers are unaffected.
+
+Gated by `[brain.routing].intelligent_router` (default True; the reversible kill
+switch → false restores the prior narrow action-intent delegation).
+
+Unit tests pin `_build_fallback_chain` (chain ordering + the router-lead marker);
+one integration test drives `generate()` to prove the fall-through.
+"""
+from __future__ import annotations
+
+from typing import Any
+
+import pytest
+
+from jarvis.brain.manager import BrainManager
+from jarvis.core.bus import EventBus
+from jarvis.core.config import BrainProviderConfig, JarvisConfig
+from tests.fixtures.brain.fake_brain import FakeBrain
+
+TALKER_PROVIDER = "openrouter"
+TALKER_MODEL = "openrouter-model"
+
+
+class _FakeSpawn:
+ name = "spawn_worker"
+ schema: dict[str, Any] = {}
+
+
+class _Inert:
+ async def execute(self, *_a: Any, **_k: Any) -> Any: # pragma: no cover
+ raise AssertionError("no exec in a chain-building test")
+
+
+def _manager(*, intelligent: bool = True) -> BrainManager:
+ cfg = JarvisConfig()
+ cfg.brain.routing.intelligent_router = intelligent
+ mgr = BrainManager(
+ config=cfg, bus=EventBus(),
+ tools={"spawn_worker": _FakeSpawn()}, tool_executor=_Inert(), # type: ignore[arg-type]
+ )
+ mgr._active_name = TALKER_PROVIDER # type: ignore[attr-defined]
+ mgr._active_can_call_tools = lambda: False # type: ignore[assignment]
+ mgr._first_tool_capable_provider = ( # type: ignore[assignment]
+ lambda level: ("gemini", "gemini-3.5-flash")
+ )
+ return mgr
+
+
+# --------------------------------------------------------------------------
+# Chain build: the router lead.
+# --------------------------------------------------------------------------
+
+def test_substantive_turn_on_tool_incapable_talker_leads_with_router() -> None:
+ mgr = _manager(intelligent=True)
+ mgr._turn_substantive = True
+ chain = mgr._build_fallback_chain("deep")
+ assert chain[0] == ("gemini", "gemini-3.5-flash"), "tool-capable router must lead"
+ assert mgr._router_lead_key == ("gemini", "gemini-3.5-flash"), (
+ "the router lead must be marked so the loop can fall through if it picks no tool"
+ )
+
+
+def test_smalltalk_turn_does_not_get_a_router_lead() -> None:
+ mgr = _manager(intelligent=True)
+ mgr._turn_substantive = False # smalltalk → chosen talker answers directly
+ chain = mgr._build_fallback_chain("deep")
+ assert chain[0][0] == TALKER_PROVIDER
+ assert mgr._router_lead_key is None
+
+
+def test_tool_capable_talker_keeps_its_own_loop() -> None:
+ mgr = _manager(intelligent=True)
+ mgr._active_can_call_tools = lambda: True # type: ignore[assignment]
+ mgr._turn_substantive = True
+ chain = mgr._build_fallback_chain("deep")
+ assert chain[0][0] == TALKER_PROVIDER, "a tool-capable talker is not pre-empted"
+ assert mgr._router_lead_key is None
+
+
+def test_flag_off_falls_back_to_narrow_action_intent_delegation() -> None:
+ mgr = _manager(intelligent=False)
+ mgr._turn_substantive = True
+ # flag off: a NON-action substantive turn must NOT get a router lead...
+ mgr._turn_needs_tools = False
+ chain_conv = mgr._build_fallback_chain("deep")
+ assert chain_conv[0][0] == TALKER_PROVIDER
+ assert mgr._router_lead_key is None
+ # ...but an action-intent turn still delegates (legacy), with no fall-through.
+ mgr._turn_needs_tools = True
+ chain_action = mgr._build_fallback_chain("deep")
+ assert chain_action[0] == ("gemini", "gemini-3.5-flash")
+ assert mgr._router_lead_key is None, "legacy delegation has no fall-through marker"
+
+
+# --------------------------------------------------------------------------
+# Fall-through: router picks no tool → chosen talker answers (its voice).
+# --------------------------------------------------------------------------
+
+async def test_router_with_no_tool_falls_through_to_chosen_talker() -> None:
+ """End-to-end: the router lead gets first crack; on a pure-conversation turn
+ it picks no tool, so the chosen (tool-incapable) talker produces the answer —
+ the user keeps their selected brain's voice."""
+ cfg = JarvisConfig()
+ cfg.brain.routing.intelligent_router = True
+ cfg.brain.primary = TALKER_PROVIDER
+ cfg.brain.providers[TALKER_PROVIDER] = BrainProviderConfig(
+ model=TALKER_MODEL, deep_model=TALKER_MODEL
+ )
+ mgr = BrainManager(config=cfg, bus=EventBus(), tools={})
+ mgr._registry._loaded = True
+ mgr._active_can_call_tools = lambda: False # type: ignore[assignment]
+ mgr._first_tool_capable_provider = ( # type: ignore[assignment]
+ lambda level: ("gemini", "gemini-flash")
+ )
+
+ router = FakeBrain(text_response="ROUTER_TALKED") # plain text, no tool
+ talker = FakeBrain(text_response="TALKER_ANSWER")
+ mgr._brain_cache[("gemini", "gemini-flash")] = router
+ mgr._brain_cache[(TALKER_PROVIDER, TALKER_MODEL)] = talker
+
+ reply = await mgr.generate(
+ "Erzähl mir bitte etwas über die Geschichte von Rom", use_history=False
+ )
+
+ assert "TALKER_ANSWER" in reply, "must fall through to the chosen talker's voice"
+ assert "ROUTER_TALKED" not in reply, "the router's no-tool answer is discarded"
+ assert len(router.calls) == 1, "the router must get first crack at tool selection"
+ assert len(talker.calls) == 1, "the chosen talker must produce the final answer"
+
+
+async def test_streaming_path_does_not_double_speak_the_router_lead() -> None:
+ """Regression (reviewer-found): on the STREAMING voice path the router lead's
+ plaintext is streamed to TTS token-by-token DURING dispatch — so a no-tool
+ router answer would be spoken, THEN the fall-through talker would speak again
+ (double answer). The router lead must NOT stream its conversational text; only
+ the chosen talker's answer reaches TTS."""
+ cfg = JarvisConfig()
+ cfg.brain.routing.intelligent_router = True
+ cfg.brain.primary = TALKER_PROVIDER
+ cfg.brain.providers[TALKER_PROVIDER] = BrainProviderConfig(
+ model=TALKER_MODEL, deep_model=TALKER_MODEL
+ )
+ mgr = BrainManager(config=cfg, bus=EventBus(), tools={})
+ mgr._registry._loaded = True
+ mgr._active_can_call_tools = lambda: False # type: ignore[assignment]
+ mgr._first_tool_capable_provider = ( # type: ignore[assignment]
+ lambda level: ("gemini", "gemini-flash")
+ )
+ mgr._brain_cache[("gemini", "gemini-flash")] = FakeBrain(text_response="ROUTER_TALKED")
+ mgr._brain_cache[(TALKER_PROVIDER, TALKER_MODEL)] = FakeBrain(text_response="TALKER_ANSWER")
+
+ chunks: list[str] = []
+ async for c in mgr.generate_stream(
+ "Erzähl mir bitte etwas über die Geschichte von Rom", use_history=False
+ ):
+ chunks.append(c)
+ streamed = "".join(chunks)
+
+ assert "TALKER_ANSWER" in streamed, "the chosen talker's answer must be spoken"
+ assert "ROUTER_TALKED" not in streamed, (
+ "the router lead's conversational text must NOT be streamed to TTS "
+ "(double-speak regression)"
+ )
diff --git a/tests/unit/brain/test_leaked_spawn_recovery.py b/tests/unit/brain/test_leaked_spawn_recovery.py
index 3a05c20d10..75b27854f6 100644
--- a/tests/unit/brain/test_leaked_spawn_recovery.py
+++ b/tests/unit/brain/test_leaked_spawn_recovery.py
@@ -67,7 +67,7 @@ def _manager_with_fake_spawn(captured: dict) -> BrainManager:
cfg.brain.primary = "fake"
class _FakeExecutor:
- async def execute(self, tool, args, *, user_utterance, trace_id): # type: ignore[no-untyped-def]
+ async def execute(self, tool, args, *, user_utterance, trace_id, config_snapshot=None): # type: ignore[no-untyped-def]
captured["args"] = args
captured["tool"] = tool
captured["user_utterance"] = user_utterance
@@ -150,7 +150,7 @@ def _manager_with_fake_tool(captured: dict, *, name: str, output: object) -> Bra
cfg.brain.primary = "fake"
class _FakeExecutor:
- async def execute(self, tool, args, *, user_utterance, trace_id): # type: ignore[no-untyped-def]
+ async def execute(self, tool, args, *, user_utterance, trace_id, config_snapshot=None): # type: ignore[no-untyped-def]
captured["args"] = args
captured["tool"] = tool
return SimpleNamespace(success=True, output=output, error=None)
@@ -266,7 +266,7 @@ def _manager_with_failing_tool(
cfg.brain.primary = "fake"
class _FailingExecutor:
- async def execute(self, tool, args, *, user_utterance, trace_id): # type: ignore[no-untyped-def]
+ async def execute(self, tool, args, *, user_utterance, trace_id, config_snapshot=None): # type: ignore[no-untyped-def]
captured["args"] = args
return SimpleNamespace(success=False, output=output, error=error)
diff --git a/tests/unit/brain/test_manager_drop_images.py b/tests/unit/brain/test_manager_drop_images.py
new file mode 100644
index 0000000000..5279ccc927
--- /dev/null
+++ b/tests/unit/brain/test_manager_drop_images.py
@@ -0,0 +1,135 @@
+"""Per-turn ad-hoc image injection for the drag-drop feature.
+
+A dropped image must reach the multimodal brain for ONE specific turn, keyed by
+that turn's trace_id, bypassing the screen-vision gate (so it works even with
+vision off / no vision provider) and clearing after the turn so it never carries
+over. See docs/superpowers/specs/2026-06-21-dragdrop-files-into-context-design.md.
+"""
+from __future__ import annotations
+
+from collections.abc import AsyncIterator
+from uuid import uuid4
+
+import pytest
+
+from jarvis.brain.manager import BrainManager
+from jarvis.brain.streaming import StreamingAggregate
+from jarvis.core.bus import EventBus
+from jarvis.core.config import JarvisConfig
+from jarvis.core.protocols import BrainDelta, BrainRequest, ImageBlock
+
+
+class _FakeBrain:
+ name = "fake"
+ context_window = 8192
+ supports_tools = True
+ supports_vision = True
+
+ async def complete(self, req: BrainRequest) -> AsyncIterator[BrainDelta]:
+ yield BrainDelta(content="ok")
+ yield BrainDelta(finish_reason="stop")
+
+
+class _RecordingDispatcher:
+ def __init__(self) -> None:
+ self.calls: list[dict] = []
+
+ async def dispatch(self, user_text, *, images=(), trace_id=None, **_kwargs):
+ self.calls.append({"images": images, "trace_id": trace_id})
+ agg = StreamingAggregate()
+ agg.text = "reacting to the drop"
+ agg.finish_reason = "stop"
+ return agg
+
+
+def _manager_with_recorder() -> tuple[BrainManager, _RecordingDispatcher]:
+ cfg = JarvisConfig()
+ cfg.brain.primary = "fake"
+ manager = BrainManager(config=cfg, bus=EventBus(), tools={})
+ recorder = _RecordingDispatcher()
+ manager._build_fallback_chain = lambda _level: [("fake", "fake-model")] # type: ignore[method-assign]
+ manager._get_brain = lambda _name, _model: _FakeBrain() # type: ignore[method-assign]
+ manager._build_dispatcher = lambda _brain, *, tools_override=None: recorder # type: ignore[method-assign]
+ return manager, recorder
+
+
+_IMG = ImageBlock(mime="image/png", data_b64="ZmFrZQ==") # "fake"
+
+
+async def test_injected_images_reach_dispatcher_without_vision_provider() -> None:
+ manager, recorder = _manager_with_recorder()
+ # No vision provider at all → the normal screen-vision path returns ().
+ assert getattr(manager, "_vision_provider", None) is None
+
+ trace = uuid4()
+ manager.inject_images_for_turn(trace, (_IMG,))
+ await manager.generate("react to this", trace_id=trace, use_history=False)
+
+ assert len(recorder.calls) == 1
+ assert recorder.calls[0]["images"] == (_IMG,)
+
+
+async def test_injected_images_cleared_after_one_turn() -> None:
+ manager, recorder = _manager_with_recorder()
+ trace = uuid4()
+ manager.inject_images_for_turn(trace, (_IMG,))
+
+ await manager.generate("first", trace_id=trace, use_history=False)
+ await manager.generate("second", trace_id=trace, use_history=False)
+
+ assert recorder.calls[0]["images"] == (_IMG,)
+ assert recorder.calls[1]["images"] == () # buffer consumed, not carried over
+
+
+async def test_no_injection_leaves_images_empty() -> None:
+ manager, recorder = _manager_with_recorder()
+ await manager.generate("plain turn", trace_id=uuid4(), use_history=False)
+ assert recorder.calls[0]["images"] == ()
+
+
+# --- Direct _collect_vision_images seam tests (no dispatcher) ----------------
+
+
+def _bare_manager() -> BrainManager:
+ """A manager built via __new__ (no __init__) — the minimal surface
+ _collect_vision_images touches with screen-vision off."""
+ mgr = BrainManager.__new__(BrainManager)
+ mgr._vision_provider = None
+ mgr._config = object()
+ mgr._bus = None
+ mgr._active_name = "x"
+ return mgr
+
+
+async def test_collect_pops_injected_and_clears() -> None:
+ mgr = _bare_manager()
+ trace = uuid4()
+ mgr.inject_images_for_turn(trace, (_IMG,))
+
+ first = await mgr._collect_vision_images(trace_id=trace, user_text="hi")
+ second = await mgr._collect_vision_images(trace_id=trace, user_text="hi")
+
+ assert first == (_IMG,) # injected images bypass the (absent) vision provider
+ assert second == () # popped once, not carried over
+
+
+async def test_collect_different_trace_does_not_consume() -> None:
+ mgr = _bare_manager()
+ injected_trace, other_trace = uuid4(), uuid4()
+ mgr.inject_images_for_turn(injected_trace, (_IMG,))
+
+ # A different turn must not consume another turn's injected images.
+ assert await mgr._collect_vision_images(trace_id=other_trace) == ()
+ # The injected entry is still there for its own trace.
+ assert await mgr._collect_vision_images(trace_id=injected_trace) == (_IMG,)
+
+
+def test_inject_on_new_constructed_manager_does_not_raise() -> None:
+ mgr = BrainManager.__new__(BrainManager) # no __init__ → no buffer attr
+ mgr.inject_images_for_turn(uuid4(), (_IMG,)) # defensive guard creates it
+ assert mgr._pending_turn_images # populated, no AttributeError
diff --git a/tests/unit/brain/test_model_catalog.py b/tests/unit/brain/test_model_catalog.py
new file mode 100644
index 0000000000..c598200cfa
--- /dev/null
+++ b/tests/unit/brain/test_model_catalog.py
@@ -0,0 +1,406 @@
+"""Tests for jarvis.brain.model_catalog.
+
+The model catalog backs the per-provider model picker in the API-Keys view.
+Three concerns:
+1. Pure response parsing per provider (Anthropic/OpenAI share the OpenAI
+ ``data[].id`` shape; Gemini uses ``models[].name``; OpenRouter adds a human
+ ``name``).
+2. Cache TTL — a fresh cache entry skips the network; ``force_refresh`` bypasses.
+3. Honest source labelling — live fetch → ``live``; served from a still-fresh
+ cache → ``cache``; fetch fails with no usable cache → ``static`` fallback.
+"""
+from __future__ import annotations
+
+import json
+import time
+from pathlib import Path
+
+import pytest
+
+from jarvis.brain.model_catalog import (
+ CATALOG_PROVIDERS,
+ PROVIDER_CATALOG,
+ CatalogResult,
+ ModelCatalog,
+ ModelInfo,
+ catalog_spec,
+ filter_brain_models,
+ parse_models_response,
+ sort_models,
+)
+
+# ----------------------------------------------------------------------
+# Generalized provider catalog — brain/subagent model catalogs + tts + stt
+# ----------------------------------------------------------------------
+
+class TestProviderCatalog:
+ def test_codex_catalog_is_available_for_subagent_model_picker(self) -> None:
+ spec = catalog_spec("codex")
+ assert spec is not None
+ assert spec.tier == "brain"
+ assert spec.selects == "model"
+ assert any("gpt-5.5" in m.id for m in spec.curated)
+
+ def test_antigravity_is_curated_brain_provider(self) -> None:
+ spec = catalog_spec("antigravity")
+ assert spec is not None
+ assert spec.tier == "brain"
+ assert spec.selects == "model"
+ assert spec.live is False # OAuth CLI has no /v1/models endpoint
+ assert "antigravity" not in CATALOG_PROVIDERS # never live-fetched
+ ids = [m.id for m in spec.curated]
+ # Flash (the fast default) is offered first; Pro is the deep option.
+ assert ids[0] == "gemini-3.5-flash"
+ assert "gemini-3.1-pro-preview" in ids
+ # No phantom ids that aren't real gemini-CLI models.
+ assert "gemini-3-pro" not in ids
+ assert "gemini-3-flash-preview" not in ids
+
+ def test_grok_voice_is_a_tts_voice_provider(self) -> None:
+ spec = catalog_spec("grok-voice")
+ assert spec.tier == "tts"
+ assert spec.selects == "voice"
+ ids = {m.id for m in spec.curated}
+ assert {"leo", "rex", "sal", "ara", "eve"} <= ids
+
+ def test_gemini_tts_lists_charon_voice(self) -> None:
+ spec = catalog_spec("gemini-flash-tts")
+ assert spec.tier == "tts"
+ assert spec.selects == "voice"
+ assert any(m.id == "Charon" for m in spec.curated)
+
+ def test_cartesia_selects_a_model(self) -> None:
+ spec = catalog_spec("cartesia")
+ assert spec.tier == "tts"
+ assert spec.selects == "model"
+ assert any("sonic" in m.id for m in spec.curated)
+
+ def test_stt_providers_select_a_model(self) -> None:
+ for p in ("groq-api", "faster-whisper", "openai-api", "deepgram"):
+ spec = catalog_spec(p)
+ assert spec is not None, p
+ assert spec.tier == "stt"
+ assert spec.selects == "model"
+ assert spec.curated, p
+
+ def test_unknown_provider_has_no_spec(self) -> None:
+ assert catalog_spec("nonexistent") is None
+
+ @pytest.mark.asyncio
+ async def test_list_models_for_tts_returns_voices(self, tmp_path: Path) -> None:
+ cat = ModelCatalog(cache_path=tmp_path / "c.json")
+ result = await cat.list_models("grok-voice")
+ assert result.selects == "voice"
+ assert any(m.id == "leo" for m in result.models)
+
+ @pytest.mark.asyncio
+ async def test_list_models_for_stt_returns_models(self, tmp_path: Path) -> None:
+ cat = ModelCatalog(cache_path=tmp_path / "c.json")
+ result = await cat.list_models("deepgram")
+ assert result.selects == "model"
+ assert any("nova" in m.id for m in result.models)
+
+ def test_brain_catalog_providers_unchanged(self) -> None:
+ # The brain-only CATALOG_PROVIDERS tuple stays the 4 API brains.
+ for p in ("claude-api", "openai", "gemini", "openrouter"):
+ assert p in CATALOG_PROVIDERS
+ assert PROVIDER_CATALOG["claude-api"].tier == "brain"
+
+
+# ----------------------------------------------------------------------
+# parse_models_response — pure per-provider parser
+# ----------------------------------------------------------------------
+
+class TestParseModelsResponse:
+ def test_openai_shape(self) -> None:
+ payload = {"data": [{"id": "gpt-5.5"}, {"id": "gpt-5.5-pro"}]}
+ models = parse_models_response("openai", payload)
+ assert ModelInfo(id="gpt-5.5", label="gpt-5.5") in models
+ assert ModelInfo(id="gpt-5.5-pro", label="gpt-5.5-pro") in models
+
+ def test_anthropic_shape(self) -> None:
+ payload = {"data": [{"id": "claude-opus-4-8"}, {"id": "claude-haiku-4-5"}]}
+ ids = [m.id for m in parse_models_response("claude-api", payload)]
+ assert ids == ["claude-opus-4-8", "claude-haiku-4-5"]
+
+ def test_gemini_strips_models_prefix_and_uses_display_name(self) -> None:
+ payload = {
+ "models": [
+ {"name": "models/gemini-3-flash", "displayName": "Gemini 3 Flash"},
+ {"name": "models/gemini-3.1-pro-preview"},
+ ]
+ }
+ models = parse_models_response("gemini", payload)
+ assert ModelInfo(id="gemini-3-flash", label="Gemini 3 Flash") in models
+ # No displayName → label falls back to the id.
+ assert ModelInfo(id="gemini-3.1-pro-preview", label="gemini-3.1-pro-preview") in models
+
+ def test_openrouter_uses_human_name_as_label(self) -> None:
+ payload = {
+ "data": [
+ {"id": "anthropic/claude-opus-4.8", "name": "Anthropic: Claude Opus 4.8"},
+ {"id": "openai/gpt-5.5"}, # missing name → label = id
+ ]
+ }
+ models = parse_models_response("openrouter", payload)
+ assert ModelInfo(
+ id="anthropic/claude-opus-4.8", label="Anthropic: Claude Opus 4.8"
+ ) in models
+ assert ModelInfo(id="openai/gpt-5.5", label="openai/gpt-5.5") in models
+
+ def test_empty_payload_yields_empty_list(self) -> None:
+ assert parse_models_response("openai", {}) == []
+ assert parse_models_response("gemini", {}) == []
+
+ def test_skips_entries_without_id(self) -> None:
+ payload = {"data": [{"id": ""}, {"foo": "bar"}, {"id": "gpt-5.5"}]}
+ assert [m.id for m in parse_models_response("openai", payload)] == ["gpt-5.5"]
+
+
+# ----------------------------------------------------------------------
+# sort_models — newest/frontier first, stale demoted
+# ----------------------------------------------------------------------
+
+class TestSortModels:
+ def test_stale_models_sink_below_frontier(self) -> None:
+ models = [
+ ModelInfo(id="gpt-4o", label="gpt-4o"), # stale (EOL)
+ ModelInfo(id="gpt-5.5", label="gpt-5.5"), # frontier
+ ]
+ ordered = sort_models("openai", models)
+ assert ordered[0].id == "gpt-5.5"
+ assert ordered[-1].id == "gpt-4o"
+
+ def test_openrouter_stale_detected_by_suffix(self) -> None:
+ models = [
+ ModelInfo(id="openai/gpt-4o", label="x"), # stale via suffix
+ ModelInfo(id="openai/gpt-5.5", label="y"), # frontier
+ ]
+ ordered = sort_models("openrouter", models)
+ assert ordered[0].id == "openai/gpt-5.5"
+ assert ordered[-1].id == "openai/gpt-4o"
+
+
+# ----------------------------------------------------------------------
+# filter_brain_models — drop non-text / generative-media models
+# ----------------------------------------------------------------------
+
+class TestFilterBrainModels:
+ def test_drops_gemini_media_and_embedding_models(self) -> None:
+ models = [
+ ModelInfo(id="gemini-3.5-flash", label="Gemini 3.5 Flash"),
+ ModelInfo(id="gemini-3.1-pro-preview", label="Gemini 3.1 Pro"),
+ ModelInfo(id="veo-3.1-generate-preview", label="Veo 3.1"),
+ ModelInfo(id="imagen-4.0-ultra-generate", label="Imagen 4"),
+ ModelInfo(id="lyria-3-pro-preview", label="Lyria 3"),
+ ModelInfo(id="nano-banana-pro-preview", label="Nano Banana"),
+ ModelInfo(id="gemini-embedding-001", label="Embedding"),
+ ModelInfo(id="gemini-2.5-flash-tts", label="Flash TTS"),
+ ModelInfo(id="gemini-2.5-flash-image", label="Flash Image"),
+ ]
+ ids = {m.id for m in filter_brain_models(models)}
+ assert "gemini-3.5-flash" in ids
+ assert "gemini-3.1-pro-preview" in ids
+ assert "veo-3.1-generate-preview" not in ids
+ assert "imagen-4.0-ultra-generate" not in ids
+ assert "lyria-3-pro-preview" not in ids
+ assert "nano-banana-pro-preview" not in ids
+ assert "gemini-embedding-001" not in ids
+ assert "gemini-2.5-flash-tts" not in ids
+ assert "gemini-2.5-flash-image" not in ids
+
+ def test_drops_openai_media_and_audio_models(self) -> None:
+ models = [
+ ModelInfo(id="gpt-5.5", label="gpt-5.5"),
+ ModelInfo(id="gpt-image-1", label="image"),
+ ModelInfo(id="dall-e-3", label="dalle"),
+ ModelInfo(id="whisper-1", label="whisper"),
+ ModelInfo(id="tts-1-hd", label="tts"),
+ ModelInfo(id="text-embedding-3-large", label="embed"),
+ ModelInfo(id="sora-2", label="sora"),
+ ]
+ ids = {m.id for m in filter_brain_models(models)}
+ assert ids == {"gpt-5.5"}
+
+ def test_keeps_all_anthropic_chat_models(self) -> None:
+ models = [
+ ModelInfo(id="claude-opus-4-8", label="Opus"),
+ ModelInfo(id="claude-haiku-4-5", label="Haiku"),
+ ]
+ assert len(filter_brain_models(models)) == 2
+
+ def test_keeps_namespaced_openrouter_chat_models(self) -> None:
+ models = [
+ ModelInfo(id="anthropic/claude-opus-4.8", label="Opus"),
+ ModelInfo(id="openai/gpt-5.5", label="gpt"),
+ ]
+ assert len(filter_brain_models(models)) == 2
+
+
+# ----------------------------------------------------------------------
+# Cache I/O + TTL
+# ----------------------------------------------------------------------
+
+class TestCache:
+ def test_round_trip(self, tmp_path: Path) -> None:
+ cache_path = tmp_path / "model_catalog_cache.json"
+ cat = ModelCatalog(cache_path=cache_path)
+ cat._cache["gemini"] = (
+ time.time(),
+ [ModelInfo(id="gemini-3-flash", label="Gemini 3 Flash")],
+ )
+ cat._save_cache()
+ reloaded = ModelCatalog(cache_path=cache_path)
+ ts, models = reloaded._cache["gemini"]
+ assert models[0].id == "gemini-3-flash"
+ assert models[0].label == "Gemini 3 Flash"
+
+ def test_corrupt_cache_is_discarded(self, tmp_path: Path) -> None:
+ cache_path = tmp_path / "model_catalog_cache.json"
+ cache_path.write_text("{ not json", encoding="utf-8")
+ cat = ModelCatalog(cache_path=cache_path)
+ assert cat._cache == {}
+
+
+# ----------------------------------------------------------------------
+# list_models — fetch / cache / fallback orchestration
+# ----------------------------------------------------------------------
+
+class TestListModels:
+ @pytest.mark.asyncio
+ async def test_fresh_cache_skips_fetch(self, tmp_path: Path, monkeypatch) -> None:
+ cat = ModelCatalog(cache_path=tmp_path / "c.json", ttl_hours=6)
+ cat._cache["gemini"] = (
+ time.time(),
+ [ModelInfo(id="gemini-3-flash", label="Gemini 3 Flash")],
+ )
+
+ async def _boom(provider: str) -> list[ModelInfo]:
+ raise AssertionError("must not fetch on a fresh cache hit")
+
+ monkeypatch.setattr(cat, "_fetch_raw", _boom)
+ result = await cat.list_models("gemini")
+ assert isinstance(result, CatalogResult)
+ assert result.source == "cache"
+ assert result.models[0].id == "gemini-3-flash"
+
+ @pytest.mark.asyncio
+ async def test_fetch_success_is_live_and_cached(
+ self, tmp_path: Path, monkeypatch
+ ) -> None:
+ cache_path = tmp_path / "c.json"
+ cat = ModelCatalog(cache_path=cache_path, ttl_hours=6)
+
+ async def _fetch(provider: str) -> list[ModelInfo]:
+ return [ModelInfo(id="gpt-5.5", label="gpt-5.5")]
+
+ monkeypatch.setattr(cat, "_fetch_raw", _fetch)
+ result = await cat.list_models("openai")
+ assert result.source == "live"
+ assert [m.id for m in result.models] == ["gpt-5.5"]
+ # Cache persisted for the next call.
+ assert json.loads(cache_path.read_text(encoding="utf-8"))["openai"]
+
+ @pytest.mark.asyncio
+ async def test_force_refresh_bypasses_fresh_cache(
+ self, tmp_path: Path, monkeypatch
+ ) -> None:
+ cat = ModelCatalog(cache_path=tmp_path / "c.json", ttl_hours=6)
+ cat._cache["openai"] = (time.time(), [ModelInfo(id="old", label="old")])
+
+ async def _fetch(provider: str) -> list[ModelInfo]:
+ return [ModelInfo(id="gpt-5.5", label="gpt-5.5")]
+
+ monkeypatch.setattr(cat, "_fetch_raw", _fetch)
+ result = await cat.list_models("openai", force_refresh=True)
+ assert result.source == "live"
+ assert [m.id for m in result.models] == ["gpt-5.5"]
+
+ @pytest.mark.asyncio
+ async def test_fetch_failure_falls_back_to_stale_cache(
+ self, tmp_path: Path, monkeypatch
+ ) -> None:
+ cat = ModelCatalog(cache_path=tmp_path / "c.json", ttl_hours=0) # all stale
+ cat._cache["openrouter"] = (
+ time.time() - 99999,
+ [ModelInfo(id="openai/gpt-5.5", label="openai/gpt-5.5")],
+ )
+
+ async def _fail(provider: str) -> list[ModelInfo]:
+ raise RuntimeError("network down")
+
+ monkeypatch.setattr(cat, "_fetch_raw", _fail)
+ result = await cat.list_models("openrouter")
+ assert result.source == "cache"
+ assert result.models[0].id == "openai/gpt-5.5"
+
+ @pytest.mark.asyncio
+ async def test_fetch_failure_no_cache_yields_static(
+ self, tmp_path: Path, monkeypatch
+ ) -> None:
+ cat = ModelCatalog(cache_path=tmp_path / "c.json", ttl_hours=6)
+
+ async def _fail(provider: str) -> list[ModelInfo]:
+ raise RuntimeError("no key")
+
+ monkeypatch.setattr(cat, "_fetch_raw", _fail)
+ result = await cat.list_models("gemini")
+ assert result.source == "static"
+ # The static fallback must still surface at least the maintained
+ # frontier default so the dropdown is never empty.
+ assert any("gemini" in m.id for m in result.models)
+
+ @pytest.mark.asyncio
+ async def test_list_models_filters_out_media_models(
+ self, tmp_path: Path, monkeypatch
+ ) -> None:
+ cat = ModelCatalog(cache_path=tmp_path / "c.json", ttl_hours=6)
+
+ async def _fetch(provider: str) -> list[ModelInfo]:
+ return [
+ ModelInfo(id="gemini-3.5-flash", label="Gemini 3.5 Flash"),
+ ModelInfo(id="veo-3.1-generate-preview", label="Veo 3.1"),
+ ModelInfo(id="imagen-4.0-ultra", label="Imagen"),
+ ]
+
+ monkeypatch.setattr(cat, "_fetch_raw", _fetch)
+ result = await cat.list_models("gemini")
+ ids = [m.id for m in result.models]
+ assert ids == ["gemini-3.5-flash"]
+
+ @pytest.mark.asyncio
+ async def test_static_fallback_shows_full_claude_family(
+ self, tmp_path: Path, monkeypatch
+ ) -> None:
+ # Claude is driven via the Max subscription (no API key), so the live
+ # /v1/models fetch always 401s — the picker must still offer the full
+ # curated family (Fable / Opus / Sonnet / Haiku), not just 2 defaults.
+ cat = ModelCatalog(cache_path=tmp_path / "c.json", ttl_hours=6)
+
+ async def _fail(provider: str) -> list[ModelInfo]:
+ raise RuntimeError("401")
+
+ monkeypatch.setattr(cat, "_fetch_raw", _fail)
+ result = await cat.list_models("claude-api")
+ assert result.source == "static"
+ ids = {m.id for m in result.models}
+ assert any("fable" in i for i in ids)
+ assert any("opus" in i for i in ids)
+ assert any("sonnet" in i for i in ids)
+ assert any("haiku" in i for i in ids)
+
+ def test_every_catalog_provider_has_a_curated_family(self) -> None:
+ from jarvis.brain.model_catalog import CURATED_MODELS
+
+ for provider in CATALOG_PROVIDERS:
+ assert CURATED_MODELS.get(provider), f"{provider} needs a curated list"
+ # Curated ids must survive the brain-model filter (no media/embeds).
+ assert filter_brain_models(CURATED_MODELS[provider]) == CURATED_MODELS[provider]
+
+ def test_catalog_providers_are_the_four_api_brain_providers(self) -> None:
+ assert set(CATALOG_PROVIDERS) == {
+ "claude-api",
+ "openai",
+ "gemini",
+ "openrouter",
+ }
diff --git a/tests/unit/brain/test_on_screen_routing.py b/tests/unit/brain/test_on_screen_routing.py
new file mode 100644
index 0000000000..6a87b580de
--- /dev/null
+++ b/tests/unit/brain/test_on_screen_routing.py
@@ -0,0 +1,96 @@
+"""Explicit "do it on screen / in the browser" must reach Computer-Use, reliably.
+
+User pain (2026-06-21): "mach es am Bildschirm" / "do it on screen" sometimes
+spawned a sub-agent mission or didn't reliably reach Computer-Use, because the
+screen surface ("Bildschirm" / "screen") was not recognized as a pc-control
+signal at all. This fix makes an explicit screen request:
+
+* never force-spawn a sub-agent (a worker has no desktop), AND
+* count as an action turn so a tool-incapable talker (Antigravity/Codex CLI)
+ delegates it to a tool-capable provider, which picks computer_use.
+
+It must NOT hijack a build-a-deliverable request that merely mentions the screen
+("build me a website and show it on screen" still spawns a mission), and it must
+not over-trigger on a knowledge question.
+
+Deterministic — no LLM, no real brain.
+"""
+from __future__ import annotations
+
+from typing import Any
+
+import pytest
+
+from jarvis.brain.manager import BrainManager, _looks_like_pc_control
+from jarvis.core.bus import EventBus
+from jarvis.core.config import JarvisConfig
+
+
+class _FakeSpawn:
+ name = "spawn_worker"
+ schema: dict[str, Any] = {}
+
+
+class _FakeDispatch:
+ name = "dispatch_to_harness"
+ schema: dict[str, Any] = {}
+
+
+class _Inert:
+ async def execute(self, *_a: Any, **_k: Any) -> Any: # pragma: no cover
+ raise AssertionError("no exec in a classification test")
+
+
+def _manager() -> BrainManager:
+ cfg = JarvisConfig()
+ cfg.brain.routing.force_spawn_mode = "strict"
+ return BrainManager(
+ config=cfg,
+ bus=EventBus(),
+ tools={"spawn_worker": _FakeSpawn(), "dispatch_to_harness": _FakeDispatch()},
+ tool_executor=_Inert(), # type: ignore[arg-type]
+ )
+
+
+_ON_SCREEN = [
+ "Mach das für mich am Bildschirm",
+ "Mach es auf dem Bildschirm",
+ "Bediene das am Bildschirm für mich",
+ "Do it on screen for me",
+ "On my screen, find the latest post",
+]
+
+
[email protected]("utterance", _ON_SCREEN)
+def test_explicit_screen_is_recognised_as_pc_control(utterance: str) -> None:
+ """The screen surface must register as a pc-control signal (so the turn is an
+ action turn → delegated to a tool-capable provider → computer_use)."""
+ assert _looks_like_pc_control(utterance) is True, (
+ f"explicit screen request {utterance!r} not recognised as pc-control"
+ )
+
+
[email protected]("utterance", _ON_SCREEN)
+def test_explicit_screen_is_an_action_turn(utterance: str) -> None:
+ assert _manager()._turn_has_action_intent(utterance) is True, (
+ f"explicit screen request {utterance!r} not flagged as an action turn"
+ )
+
+
[email protected]("utterance", _ON_SCREEN)
+def test_explicit_screen_never_force_spawns(utterance: str) -> None:
+ assert _manager()._should_force_spawn(utterance) is False, (
+ f"explicit screen request {utterance!r} wrongly force-spawned a worker"
+ )
+
+
+def test_build_and_show_on_screen_still_spawns_a_mission() -> None:
+ """A build-a-deliverable request that ALSO mentions the screen must still
+ spawn the mission — the build wins over the pc-control stand-down."""
+ assert _manager()._should_force_spawn(
+ "Bau mir eine Website und zeig sie mir am Bildschirm"
+ ) is True
+
+
+def test_screen_knowledge_question_does_not_force_spawn() -> None:
+ assert _manager()._should_force_spawn("Was ist ein Bildschirm?") is False
diff --git a/tests/unit/brain/test_provider_test.py b/tests/unit/brain/test_provider_test.py
index a4b0955ebb..9180f512b1 100644
--- a/tests/unit/brain/test_provider_test.py
+++ b/tests/unit/brain/test_provider_test.py
@@ -8,7 +8,8 @@ stored, never that the provider answers — and a 401/403 proves the integration
reached the provider and only the credential/account was rejected.
Error strings below are VERBATIM from live probes against the real providers
-(Anthropic 401, xAI 403 out-of-credits, OpenAI missing-key RuntimeError).
+(Anthropic 401, an OpenAI-compatible 403 out-of-credits, OpenAI missing-key
+RuntimeError).
"""
from __future__ import annotations
@@ -42,7 +43,7 @@ def test_anthropic_401_invalid_key_is_bad_key() -> None:
assert classify_provider_error(msg) == "bad_key"
-def test_xai_403_out_of_credits_is_no_credits() -> None:
+def test_403_out_of_credits_is_no_credits() -> None:
msg = (
"PermissionDeniedError: Error code: 403 - {'code': 'permission-denied', "
"'error': 'Your team e6d8 has either used all available credits or reached "
diff --git a/tests/unit/brain/test_routing.py b/tests/unit/brain/test_routing.py
index 6b55315c3a..9cbe1bdcf6 100644
--- a/tests/unit/brain/test_routing.py
+++ b/tests/unit/brain/test_routing.py
@@ -548,11 +548,11 @@ def _manager_with_worker_provider(
@pytest.mark.parametrize(
- "brain_primary", ["grok", "openai", "openai-codex", "openrouter", "ollama"]
+ "brain_primary", ["mistral", "openai", "openai-codex", "openrouter", "ollama"]
)
def test_force_spawn_follows_worker_provider_not_talker(brain_primary: str) -> None:
"""With a configured claude-api worker, switching the talker to
- grok/openai/codex must NOT block force-spawn — viability follows the WORKER,
+ mistral/openai/codex must NOT block force-spawn — viability follows the WORKER,
not the talker."""
manager, _executor = _manager_with_worker_provider(
brain_primary=brain_primary, worker_provider="claude-api",
@@ -564,15 +564,14 @@ def test_force_spawn_follows_worker_provider_not_talker(brain_primary: str) -> N
def test_force_spawn_codex_worker_with_codex_talker() -> None:
- """A Codex talker + Codex worker must still force-spawn (the user's
- Codex-as-brain switch must not disable delegation)."""
+ """A legacy Codex primary + Codex worker must still force-spawn."""
manager, _executor = _manager_with_worker_provider(
brain_primary="openai-codex", worker_provider="openai-codex",
)
assert manager._should_force_spawn("Bau eine Landingpage") is True
[email protected]("brain_primary", ["grok", "openai", "ollama"])
[email protected]("brain_primary", ["mistral", "openai", "ollama"])
def test_force_spawn_blocked_when_no_worker_and_nonviable_talker(
brain_primary: str,
) -> None:
@@ -2782,6 +2781,32 @@ def test_mission_inject_source_layer_parity() -> None:
assert MISSION_INJECT_SOURCE_LAYER in _NON_SPAWN_SOURCE_LAYERS
+def test_drop_source_layer_parity() -> None:
+ """Anti-drift: a dropped file/content directive (ui.drop) must be exempt
+ from force-spawn — it is reacted to inline, never auto-dispatched as a
+ worker (parity with mission_inject; AP-5/AP-14, anti-doom-loop)."""
+ from jarvis.brain.drop_context import DROP_SOURCE_LAYER
+ from jarvis.brain.manager import _NON_SPAWN_SOURCE_LAYERS
+
+ assert DROP_SOURCE_LAYER in _NON_SPAWN_SOURCE_LAYERS
+
+
+def test_dropped_file_directive_is_never_force_spawned() -> None:
+ """A drop directive carrying an action verb must still be discussed inline
+ when stamped with the ui.drop source marker."""
+ from jarvis.brain.drop_context import DROP_SOURCE_LAYER
+
+ manager, _ = _manager_with_spawn(force_spawn_mode="permissive")
+ directive = "Open this file and fix the bug you find in it."
+ # Precondition: WITHOUT the drop source this DOES force-spawn.
+ assert manager._should_force_spawn(directive) is True
+ # WITH the drop source it must be answered inline, never spawned.
+ assert (
+ manager._should_force_spawn(directive, source_layer=DROP_SOURCE_LAYER)
+ is False
+ ), "a dropped-file directive must be reacted to inline, never re-dispatched"
+
+
def test_dropped_mission_recap_is_never_force_spawned() -> None:
"""A mission.inject recap directive must not trip the force-spawn heuristic."""
from jarvis.ui.web.mission_inject import compose_mission_inject_text
diff --git a/tests/unit/brain/test_search_web_freshness_doctrine.py b/tests/unit/brain/test_search_web_freshness_doctrine.py
new file mode 100644
index 0000000000..4563666fc6
--- /dev/null
+++ b/tests/unit/brain/test_search_web_freshness_doctrine.py
@@ -0,0 +1,82 @@
+"""Regression guard: the router answers evergreen knowledge DIRECTLY and reserves
+``search_web`` for genuinely fresh / volatile facts (or an explicit search
+request) — the "Frische-Grenze" mandate.
+
+Live forensic 2026-06-20 (voice session e0898d6e, 16:12): a plain knowledge
+question — "Kannst du mir sagen, was ich alles beachten muss, wenn ich nach
+Melbourne auswandern moechte?" — made the router LLM fire ``search_web`` THREE
+times (proven from sessions.db voice_events: 3x ``ActionProposed search_web``,
+``jarvis_text`` empty) instead of just answering. The Run-Inspector labels a
+``search_web`` call "Recherche"; the user read that as an unwanted
+sub-agent / research spawn for a trivial question.
+
+The deterministic force-spawn gate behaved correctly (it did NOT spawn — that
+path is covered by ``test_routing.py``). The over-eager choice came from the
+router prompt + the ``search_web`` tool description, which both told the model
+to search for ANY "Wissensfrage / was ist X / erklaer mir X".
+
+Mandate ("Frische-Grenze"): evergreen / general knowledge is answered from the
+model's own knowledge; ``search_web`` fires only for fresh / volatile facts
+(news, prices, weather, "aktuell / heute / neueste") or an explicit search
+request.
+"""
+from __future__ import annotations
+
+from jarvis.brain.router import SYSTEM_PROMPT
+from jarvis.plugins.tool.search_web import SearchWebTool
+
+
+def test_search_web_description_reserved_for_fresh_facts() -> None:
+ """The tool's own function declaration must scope it to fresh facts.
+
+ This is the highest-leverage lever — the LLM sees ``SearchWebTool.description``
+ on every turn as the search_web function declaration, independent of which
+ system-prompt path (capability block vs. fallback) is active.
+ """
+ desc = SearchWebTool.description.lower()
+ # The fresh / volatile doctrine must be present.
+ assert "aktuell" in desc, (
+ "search_web description must restrict the tool to current/fresh facts"
+ )
+ # The evergreen carve-out must be present so the model answers general
+ # knowledge directly instead of searching it.
+ assert "evergreen" in desc or "allgemeinwissen" in desc, (
+ "search_web description must tell the model NOT to search evergreen "
+ "knowledge it can answer directly"
+ )
+ # The old over-eager evergreen triggers must be gone — these turned a plain
+ # "explain X" / "what is X" question into a web search (Melbourne forensic).
+ assert "erklär mir x" not in desc and "erklaer mir x" not in desc, (
+ "search_web description still advertises evergreen 'explain X' as a "
+ "primary trigger — that is the over-eager research bug"
+ )
+
+
+def test_router_prompt_answers_evergreen_knowledge_directly() -> None:
+ """The router doctrine must answer evergreen knowledge directly."""
+ low = SYSTEM_PROMPT.lower()
+ assert "evergreen" in low, (
+ "router prompt is missing the evergreen-knowledge-answered-directly "
+ "doctrine (Frische-Grenze, 2026-06-20)"
+ )
+ assert "frische" in low, (
+ "router prompt must reserve search_web for fresh / volatile facts"
+ )
+ # search_web must STILL be advertised for genuinely fresh queries (news) —
+ # never regress to the 'spawn a worker / never search' extreme.
+ assert "search_web" in low and "news" in low
+
+
+def test_router_prompt_pins_the_emigration_forensic_as_direct_answer() -> None:
+ """Anchor the exact forensic: an emigration-basics question is evergreen
+ knowledge answered directly, NOT a search_web case.
+
+ This is the established pinning style in this codebase (the prompt pins
+ 'einstein' / 'hauptstadt' / 'news' as category examples). Pinning the
+ Melbourne case keeps the doctrine from silently regressing.
+ """
+ low = SYSTEM_PROMPT.lower()
+ assert "auswander" in low, (
+ "pin the Melbourne forensic: an emigration-basics question is "
+ "evergreen knowledge answered directly, not searched"
+ )
diff --git a/tests/unit/brain/test_skill_routing_guard.py b/tests/unit/brain/test_skill_routing_guard.py
index d47931f921..d097faa3e4 100644
--- a/tests/unit/brain/test_skill_routing_guard.py
+++ b/tests/unit/brain/test_skill_routing_guard.py
@@ -10,6 +10,7 @@ See docs/superpowers/specs/2026-06-09-skill-system-rebuild-design.md.
"""
from __future__ import annotations
+import asyncio
from pathlib import Path
from typing import Any
@@ -355,3 +356,157 @@ async def test_no_skill_match_keeps_local_action_fast_path() -> None:
reply = await m.generate("starte die Morgenroutine")
assert reply == "LOCAL_ACTION_SENTINEL"
assert m.local_action_calls == ["starte die Morgenroutine"]
+
+
+# ----------------------------------------------------------------------
+# A plugin skill that only keyword-matched an app name ("Discord",
+# "Spotify") must NOT capture a desktop-control / open-app turn —
+# Computer-Use is the universal GUI integration and owns "open Discord and
+# find the post on screen", even when the plugin's API/MCP integration is
+# absent.
+#
+# Live bug 2026-06-21 (sessions.db turn 67276501-…): the marketplace
+# `plugin-discord` skill matched the bare word "Discord", suppressed the
+# deterministic Computer-Use fast path, and the turn fell through to a
+# tool-less CLI talker (antigravity) that hallucinated a permissions refusal
+# ("ich habe keinen Zugriff auf Discord"). The user wanted it driven on
+# screen — exactly what Computer-Use exists for. The fix: when the
+# deterministic local-action gate claims the turn as DIRECT/COMPUTER_USE,
+# the keyword-matched plugin skill stands down (sibling of the AD-S9
+# explicit-heavy-work stand-down above).
+# ----------------------------------------------------------------------
+
+
+def _seed_plugin_skill(tmp_path: Path, name: str, pattern: str) -> None:
+ _write_skill(tmp_path, name, pattern)
+ registry = SkillRegistry(root=tmp_path)
+ registry.reload_sync()
+ set_skill_context(SkillContext(registry=registry, runner=_StubRunner())) # type: ignore[arg-type]
+
+
+async def test_open_app_compound_stands_down_plugin_skill(tmp_path: Path) -> None:
+ """'Discord öffnen und ... raussuchen' is a Computer-Use intent: the
+ plugin-discord keyword match stands down so the local-action fast path
+ (the COMPUTER_USE dispatch) runs instead of falling to the talker."""
+ _seed_plugin_skill(tmp_path, "plugin-discord", "(discord)")
+ m = _make_probe_manager()
+ utterance = (
+ "Kannst du bitte für mich Discord öffnen und den letzten Post " # i18n-allow
+ "von BridgeMind raussuchen?"
+ )
+ # Premise: the collision is real — the plugin skill DOES match.
+ assert m._match_skill_for_turn(utterance) is not None
+ reply = await m.generate(utterance)
+ assert m._skill_turn_match is None
+ assert reply == "LOCAL_ACTION_SENTINEL"
+ assert m.local_action_calls == [utterance]
+
+
+async def test_plain_open_app_stands_down_plugin_skill(tmp_path: Path) -> None:
+ """Even a plain 'öffne Discord' (a DIRECT open) is owned by the
+ deterministic gate, not the keyword-matched plugin skill."""
+ _seed_plugin_skill(tmp_path, "plugin-discord", "(discord)")
+ m = _make_probe_manager()
+ utterance = "öffne Discord" # i18n-allow: German voice command exercising the open-app routing
+ assert m._match_skill_for_turn(utterance) is not None
+ reply = await m.generate(utterance)
+ assert m._skill_turn_match is None
+ assert reply == "LOCAL_ACTION_SENTINEL"
+ assert m.local_action_calls == [utterance]
+
+
+async def test_open_and_operate_stands_down_plugin_skill(tmp_path: Path) -> None:
+ """'öffne Spotify und spiel ...' is a compound open-and-operate
+ Computer-Use intent — the plugin-spotify keyword match stands down."""
+ _seed_plugin_skill(tmp_path, "plugin-spotify", "(spotify)")
+ m = _make_probe_manager()
+ utterance = "öffne Spotify und spiel Shape of You" # i18n-allow
+ assert m._match_skill_for_turn(utterance) is not None
+ reply = await m.generate(utterance)
+ assert m._skill_turn_match is None
+ assert reply == "LOCAL_ACTION_SENTINEL"
+ assert m.local_action_calls == [utterance]
+
+
+async def test_pure_dispatch_keeps_plugin_skill(tmp_path: Path) -> None:
+ """A pure dispatch with NO open/desktop-control verb ('schick eine
+ Discord-Nachricht') is genuine plugin work — the skill KEEPS the turn,
+ the local-action fast path does NOT run (the stand-down is precise: it
+ only fires when the gate would handle the turn as DIRECT/COMPUTER_USE)."""
+ _seed_plugin_skill(tmp_path, "plugin-discord", "(discord)")
+ m = _make_probe_manager()
+ utterance = "schick eine Discord-Nachricht an Max" # i18n-allow
+ assert m._match_skill_for_turn(utterance) is not None
+ reply = await m.generate(utterance)
+ assert m._skill_turn_match is not None
+ assert reply != "LOCAL_ACTION_SENTINEL"
+ assert m.local_action_calls == []
+
+
+# ----------------------------------------------------------------------
+# End-to-end: the EXACT live-bug utterance, through the REAL local-action
+# fast path, must DISPATCH a Computer-Use mission — never fall to the
+# (tool-less) talker that refuses. This is the closing proof for the
+# 2026-06-21 Discord bug: with no brain providers wired, a fall-through
+# would surface a provider-down refusal and the harness would never be
+# called; the test asserts the opposite.
+# ----------------------------------------------------------------------
+
+
+class _HarnessDispatchExecutor:
+ """tool_executor stand-in that records dispatch_to_harness calls."""
+
+ def __init__(self) -> None:
+ self.harness_calls: list[tuple[str, dict[str, Any], str]] = []
+
+ async def execute(
+ self,
+ tool: Any,
+ args: dict[str, Any],
+ *,
+ user_utterance: str = "",
+ trace_id: Any = None,
+ **_: Any,
+ ) -> ToolResult:
+ self.harness_calls.append((getattr(tool, "name", "?"), args, user_utterance))
+ return ToolResult(
+ success=True,
+ output="Discord ist offen — der letzte BridgeMind-Post ist da.", # i18n-allow
+ )
+
+
+class _FakeHarnessTool:
+ name = "dispatch_to_harness"
+ schema: dict[str, Any] = {}
+
+
+async def test_open_discord_e2e_dispatches_computer_use_not_refusal(
+ tmp_path: Path,
+) -> None:
+ _seed_plugin_skill(tmp_path, "plugin-discord", "(discord)")
+ executor = _HarnessDispatchExecutor()
+ config = JarvisConfig()
+ config.brain.routing.force_spawn_mode = "permissive"
+ m = BrainManager(
+ config=config,
+ bus=EventBus(),
+ tools={"spawn_worker": _FakeSpawnTool(), "run-skill": _FakeRunSkillTool()},
+ tool_executor=executor, # type: ignore[arg-type]
+ local_action_tools={"dispatch_to_harness": _FakeHarnessTool()},
+ )
+ # No brain providers: a fall-through to the talker would return a
+ # provider-down refusal AND never touch the harness. Prove neither.
+ m._build_fallback_chain = lambda level: [] # type: ignore[assignment,method-assign]
+ utterance = (
+ "Kannst du bitte für mich Discord öffnen und den letzten Post " # i18n-allow
+ "von BridgeMind raussuchen?"
+ )
+ reply = await m.generate(utterance)
+ # The Computer-Use harness runs as a background task — drain it.
+ await asyncio.gather(*getattr(m, "_cu_background_tasks", set()))
+
+ assert m._skill_turn_match is None
+ assert any(
+ name == "dispatch_to_harness" for name, *_ in executor.harness_calls
+ ), f"Computer-Use was never dispatched; calls={executor.harness_calls}"
+ assert reply, "the turn must speak an immediate ACK, not stay silent"
diff --git a/tests/unit/brain/test_spawn_announcement.py b/tests/unit/brain/test_spawn_announcement.py
index f3ae000cf1..a66add49f1 100644
--- a/tests/unit/brain/test_spawn_announcement.py
+++ b/tests/unit/brain/test_spawn_announcement.py
@@ -422,6 +422,120 @@ async def test_open_breaker_skips_provider() -> None:
assert out in _FALLBACK_SPAWN["de"]
+# --------------------------------------------------------------------------- #
+# Failover provider (primary exhausted → live secondary, not the pool) #
+# --------------------------------------------------------------------------- #
+# Mirrors the pre-thinking ack's Gemini→Grok failover
+# (jarvis.brain.factory._build_ack_fallback). Root cause of the 2026-06-21
+# "contextless stock phrase" report: the primary flash provider (gemini) was
+# billing-exhausted (429 → None) and the spawn announcer had NO failover, so it
+# degraded straight to the generic pool while a healthy grok was available.
+
+
+def _composer_with_fallback(
+ primary: _FakeProvider,
+ fallback: _FakeProvider,
+ *,
+ timeout_ms: int = 1500,
+ primary_breaker: CircuitBreaker | None = None,
+) -> SpawnAnnouncementComposer:
+ cfg = AckBrainConfig(timeout_ms=timeout_ms)
+ return SpawnAnnouncementComposer(
+ provider=primary,
+ config=cfg,
+ breaker=primary_breaker or CircuitBreaker(threshold=3, cooldown_s=60),
+ fallback_provider=fallback,
+ fallback_breaker=CircuitBreaker(threshold=3, cooldown_s=60),
+ )
+
+
+async def test_fallback_provider_used_when_primary_exhausted() -> None:
+ """Primary returns nothing (e.g. a 429-exhausted adapter yields None) →
+ the live failover provider's context-aware text is spoken, NOT a canned
+ pool phrase. Without this, a dead primary silently degrades every spawn
+ announcement to a generic stock line."""
+ primary = _FakeProvider(reply=None)
+ fallback = _FakeProvider(
+ reply="Ich gebe das Thema Gmail gerade an meinen Helfer weiter."
+ )
+ composer = _composer_with_fallback(primary, fallback)
+ out = await composer.compose(
+ utterance="Schau bitte in mein Gmail rein.", language="de"
+ )
+ assert "Gmail" in out
+ assert out not in _FALLBACK_SPAWN["de"]
+ assert len(primary.calls) == 1
+ assert len(fallback.calls) == 1
+
+
+async def test_fallback_provider_used_when_primary_errors() -> None:
+ primary = _FakeProvider(raises=True)
+ fallback = _FakeProvider(reply="Ich kümmere mich gleich um dein Gmail.")
+ composer = _composer_with_fallback(primary, fallback)
+ out = await composer.compose(
+ utterance="Schau in mein Gmail.", language="de"
+ )
+ assert out == "Ich kümmere mich gleich um dein Gmail."
+ assert len(fallback.calls) == 1
+
+
+async def test_fallback_provider_used_when_primary_times_out() -> None:
+ primary = _FakeProvider(reply="Ich schaue in dein Gmail.", delay_s=0.5)
+ fallback = _FakeProvider(reply="Ich nehme mir dein Gmail gleich vor.")
+ composer = _composer_with_fallback(primary, fallback, timeout_ms=100)
+ out = await composer.compose(
+ utterance="Schau in mein Gmail.", language="de"
+ )
+ assert out == "Ich nehme mir dein Gmail gleich vor."
+
+
+async def test_primary_success_skips_fallback() -> None:
+ primary = _FakeProvider(reply="Ich schaue gleich in dein Gmail.")
+ fallback = _FakeProvider(reply="should never be reached")
+ composer = _composer_with_fallback(primary, fallback)
+ out = await composer.compose(
+ utterance="Schau in mein Gmail.", language="de"
+ )
+ assert out == "Ich schaue gleich in dein Gmail."
+ assert fallback.calls == []
+
+
+async def test_both_providers_dead_falls_back_to_pool() -> None:
+ primary = _FakeProvider(reply=None)
+ fallback = _FakeProvider(reply=None)
+ composer = _composer_with_fallback(primary, fallback)
+ out = await composer.compose(
+ utterance="Schau in mein Gmail.", language="de"
+ )
+ assert out in _FALLBACK_SPAWN["de"]
+ assert len(primary.calls) == 1
+ assert len(fallback.calls) == 1
+
+
+async def test_open_primary_breaker_still_consults_fallback() -> None:
+ """An open primary breaker (dead provider already tripped it) must not kill
+ the context-aware path — the failover is still consulted before the pool."""
+ primary = _FakeProvider(reply="primary text")
+ fallback = _FakeProvider(reply="Ich nehme mir dein Gmail gleich vor.")
+ primary_breaker = CircuitBreaker(threshold=1, cooldown_s=60)
+ await primary_breaker.record_failure() # opens immediately at threshold=1
+ composer = _composer_with_fallback(
+ primary, fallback, primary_breaker=primary_breaker
+ )
+ out = await composer.compose(
+ utterance="Schau in mein Gmail.", language="de"
+ )
+ assert primary.calls == [] # primary skipped (breaker open)
+ assert out == "Ich nehme mir dein Gmail gleich vor."
+ assert len(fallback.calls) == 1
+
+
# --------------------------------------------------------------------------- #
# Brain-supplied candidate (spoken_ack from the router tool-call) #
# --------------------------------------------------------------------------- #
diff --git a/tests/unit/brain/test_tier_model_resolution.py b/tests/unit/brain/test_tier_model_resolution.py
index dcc741fdb8..73e3e21750 100644
--- a/tests/unit/brain/test_tier_model_resolution.py
+++ b/tests/unit/brain/test_tier_model_resolution.py
@@ -14,7 +14,7 @@ import pytest
from jarvis.brain.manager import BrainManager
from jarvis.core.bus import EventBus
-from jarvis.core.config import load_config
+from jarvis.core.config import BrainTierConfig, JarvisConfig, load_config
# One representative non-default frontier model per configured brain provider.
# Gemini is only one row — model selection must resolve for EVERY provider.
@@ -23,7 +23,6 @@ PROVIDER_FAST_DEEP_CASES = [
("openrouter", "anthropic/claude-sonnet-4.6", "anthropic/claude-opus-4.8"),
("openai", "gpt-5.5", "gpt-5.5-pro"),
("gemini", "gemini-3.5-flash", "gemini-3.1-pro-preview"),
- ("grok", "grok-4.3", "grok-4.3"),
]
@@ -71,6 +70,32 @@ def test_router_caps_thinking_budget_without_touching_global_config() -> None:
assert cfg.brain.providers["gemini"].thinking_budget is None # global untouched
+def test_codex_chatgpt_login_does_not_make_codex_a_main_brain(
+ monkeypatch: pytest.MonkeyPatch,
+) -> None:
+ """Codex OAuth unlocks the subagent only; the main router falls back."""
+ monkeypatch.setattr("jarvis.core.config.get_secret_any", lambda *_a, **_k: None)
+
+ class _ConnectedCodexAuth:
+ def status(self):
+ class _Status:
+ connected = True
+ mode = "chatgpt"
+
+ return _Status()
+
+ monkeypatch.setattr("jarvis.codex_auth.CodexAuthService", _ConnectedCodexAuth)
+
+ cfg = JarvisConfig()
+ cfg.brain.router = BrainTierConfig(provider="codex", fallback_provider="gemini")
+
+ mgr = BrainManager.from_tier_config("router", cfg, EventBus())
+
+ assert mgr.active_provider == "gemini"
+ assert mgr._config.brain.primary == "gemini"
+ assert "codex" not in [provider for provider, _model in mgr._build_fallback_chain("fast")]
+
+
def test_user_selected_deep_model_drives_the_deep_chain() -> None:
"""Per-user model selection (2026-06-20): the model the user picks for the
DEEP tier of a provider must be the one a deep/code turn actually runs on —
diff --git a/tests/unit/brain/test_tool_incapable_provider_delegation.py b/tests/unit/brain/test_tool_incapable_provider_delegation.py
new file mode 100644
index 0000000000..b2cd5d23ab
--- /dev/null
+++ b/tests/unit/brain/test_tool_incapable_provider_delegation.py
@@ -0,0 +1,118 @@
+"""Provider-agnostic tool delegation when the active talker can't call tools.
+
+Some brain providers cannot emit tool_calls at runtime — the subscription-CLI
+brains (Codex over the ChatGPT login, Antigravity over the Google login) drive a
+CLI agent and drop ALL tools. A feature that depends on the talker emitting a
+tool_call (Computer-Use, plugin reads, …) therefore breaks for whatever provider
+the user happens to select. The fix is capability-driven, not a per-provider
+hardcode:
+
+* each brain reports its RUNTIME tool-calling capability via ``can_call_tools()``;
+* when the active talker can't call tools AND a turn needs a tool/action, the
+ fallback chain leads with a tool-capable provider so the action actually runs,
+ while the tool-incapable provider stays as the conversational fallback.
+
+These tests are deterministic — no live provider, no network.
+"""
+from __future__ import annotations
+
+from typing import Any
+
+from jarvis.brain.manager import BrainManager
+from jarvis.core.bus import EventBus
+from jarvis.core.config import JarvisConfig
+from jarvis.plugins.brain.antigravity import AntigravityBrain
+from jarvis.plugins.brain.codex import CodexBrain
+
+
+# --------------------------------------------------------------------------
+# Runtime capability: the subscription-CLI brains can't call tools.
+# --------------------------------------------------------------------------
+
+def test_codex_can_call_tools_only_with_api_key(monkeypatch) -> None:
+ brain = CodexBrain()
+ monkeypatch.setattr(brain, "_api_key", lambda: None)
+ assert brain.can_call_tools() is False # ChatGPT-login CLI path drops tools
+ monkeypatch.setattr(brain, "_api_key", lambda: "sk-test-key")
+ assert brain.can_call_tools() is True # API-key path can emit tool_calls
+
+
+def test_antigravity_cannot_call_tools() -> None:
+ # The Google-subscription CLI (agy / gemini-cli) always drops tools.
+ assert AntigravityBrain().can_call_tools() is False
+
+
+# --------------------------------------------------------------------------
+# Fallback-chain delegation.
+# --------------------------------------------------------------------------
+
+class _FakeTool:
+ name = "spawn_worker"
+ schema: dict[str, Any] = {}
+
+
+class _Inert:
+ async def execute(self, *_a: Any, **_k: Any) -> Any: # pragma: no cover
+ raise AssertionError("no exec in a chain-building test")
+
+
+def _manager() -> BrainManager:
+ config = JarvisConfig()
+ return BrainManager(
+ config=config,
+ bus=EventBus(),
+ tools={"spawn_worker": _FakeTool()},
+ tool_executor=_Inert(), # type: ignore[arg-type]
+ )
+
+
+def test_chain_leads_with_tool_capable_provider_when_active_cant_and_turn_needs_tools() -> None:
+ """When the active talker can't call tools AND the turn needs a tool, the
+ chain must LEAD with a tool-capable provider so the action runs."""
+ mgr = _manager()
+ mgr._active_name = "codex" # type: ignore[attr-defined]
+ mgr._active_can_call_tools = lambda: False # type: ignore[assignment]
+ mgr._first_tool_capable_provider = ( # type: ignore[assignment]
+ lambda level: ("gemini", "gemini-3.5-flash")
+ )
+ mgr._turn_needs_tools = True
+ chain = mgr._build_fallback_chain("deep")
+ assert chain, "chain must not be empty"
+ assert chain[0] == ("gemini", "gemini-3.5-flash"), (
+ f"a tool-capable provider must lead a tool turn; got {chain[0]!r}"
+ )
+
+
+def test_chain_unchanged_for_pure_conversation_even_if_active_cant_call_tools() -> None:
+ """A pure-conversation turn (no tool needed) must NOT be hijacked — the
+ chosen provider keeps its voice. Delegation only triggers on tool turns."""
+ mgr = _manager()
+ mgr._active_name = "codex" # type: ignore[attr-defined]
+ mgr._active_can_call_tools = lambda: False # type: ignore[assignment]
+ mgr._first_tool_capable_provider = ( # type: ignore[assignment]
+ lambda level: ("gemini", "gemini-3.5-flash")
+ )
+ mgr._turn_needs_tools = False
+ chain = mgr._build_fallback_chain("deep")
+ assert chain, "chain must not be empty"
+ assert chain[0][0] == "codex", (
+ f"a non-tool turn must keep the active provider leading; got {chain[0]!r}"
+ )
+
+
+def test_chain_unchanged_when_active_is_tool_capable() -> None:
+ """A tool-capable active provider never delegates — even on a tool turn."""
+ mgr = _manager()
+ mgr._active_name = "gemini" # type: ignore[attr-defined]
+ mgr._active_can_call_tools = lambda: True # type: ignore[assignment]
+ called = {"hit": False}
+
+ def _should_not_run(_level): # noqa: ANN001
+ called["hit"] = True
+ return ("claude-api", "x")
+
+ mgr._first_tool_capable_provider = _should_not_run # type: ignore[assignment]
+ mgr._turn_needs_tools = True
+ chain = mgr._build_fallback_chain("deep")
+ assert chain[0][0] == "gemini"
+ assert called["hit"] is False, "must not look for a helper when active is capable"
diff --git a/tests/unit/brain/test_tool_use_progress.py b/tests/unit/brain/test_tool_use_progress.py
index 9be6b7d948..b2cd90a2ed 100644
--- a/tests/unit/brain/test_tool_use_progress.py
+++ b/tests/unit/brain/test_tool_use_progress.py
@@ -9,6 +9,7 @@ making progress at the round/tool boundaries that bracket the long silent gaps
"""
from __future__ import annotations
+import asyncio
from collections.abc import AsyncIterator
from typing import Any
@@ -47,6 +48,21 @@ class _ToolThenAnswerBrain:
yield BrainDelta(finish_reason="stop")
+class _HeartbeatThenAnswerBrain:
+ """Yields an invisible heartbeat before the model round completes."""
+
+ def __init__(self) -> None:
+ self.heartbeat_seen = asyncio.Event()
+ self.release = asyncio.Event()
+
+ async def complete(self, req: BrainRequest) -> AsyncIterator[BrainDelta]: # noqa: ARG002
+ yield BrainDelta(content="")
+ self.heartbeat_seen.set()
+ await self.release.wait()
+ yield BrainDelta(content="Done.")
+ yield BrainDelta(finish_reason="stop")
+
+
@pytest.mark.asyncio
async def test_run_pings_on_progress_across_rounds_and_tools() -> None:
brain = _ToolThenAnswerBrain()
@@ -75,6 +91,40 @@ async def test_run_pings_on_progress_across_rounds_and_tools() -> None:
assert pings >= 3, f"expected >=3 progress pings, got {pings}"
+async def test_empty_provider_heartbeat_pings_progress_before_round_finishes() -> None:
+ brain = _HeartbeatThenAnswerBrain()
+ loop = ToolUseLoop(
+ brain,
+ {"gmail/list_messages": _NeutralTool()},
+ _ExecOK(), # type: ignore[arg-type]
+ )
+ pings = 0
+
+ def _on_progress() -> None:
+ nonlocal pings
+ pings += 1
+
+ task = asyncio.create_task(
+ loop.run(
+ [],
+ user_utterance="say hi",
+ text_consumer=lambda _chunk: None,
+ on_progress=_on_progress,
+ )
+ )
+
+ await asyncio.wait_for(brain.heartbeat_seen.wait(), timeout=1.0)
+ await asyncio.sleep(0)
+
+ assert not task.done()
+ assert pings >= 1
+
+ brain.release.set()
+ result = await asyncio.wait_for(task, timeout=1.0)
+ assert result.text == "Done."
+
+
@pytest.mark.asyncio
async def test_run_without_on_progress_is_unchanged() -> None:
"""Default (no callback) must behave exactly as before — additive only."""
diff --git a/tests/unit/brain/test_voice_command_gate.py b/tests/unit/brain/test_voice_command_gate.py
index d2c92e3da4..b3080a1649 100644
--- a/tests/unit/brain/test_voice_command_gate.py
+++ b/tests/unit/brain/test_voice_command_gate.py
@@ -19,7 +19,7 @@ from jarvis.brain.voice_command_gate import match_voice_command
[
# existing, must keep working
("wechsel auf gemini", "gemini"),
- ("switch to grok", "grok"),
+ ("switch to openai", "openai"),
("nutze openai", "openai"),
("wechsle zu claude", "claude"),
("use openrouter", "openrouter"),
@@ -27,7 +27,7 @@ from jarvis.brain.voice_command_gate import match_voice_command
("switch the brain provider to gemini", "gemini"),
("wechsel den Brain-Provider auf gemini", "gemini"),
("wechsel den Provider auf openrouter", "openrouter"),
- ("wechsle den Anbieter zu grok", "grok"),
+ ("wechsle den Anbieter zu openrouter", "openrouter"),
("switch provider to claude", "claude"),
("switch the provider to openai", "openai"),
("wechsel deinen Provider auf gemini", "gemini"),
@@ -45,6 +45,11 @@ def test_provider_switch_matches(text: str, target: str) -> None:
"ich gehe auf meinem Weg",
"wie spät ist es",
"erzähl mir was über gemini", # a mention, not a switch command
+ # Grok was removed as a brain provider (only grok-voice TTS + the
+ # grok_api_key credential remain), so it is no longer a recognized
+ # brain/provider switch target — "switch to grok" must NOT match.
+ "switch to grok",
+ "wechsle den Anbieter zu grok",
],
)
def test_harmless_does_not_match_provider(text: str) -> None:
diff --git a/tests/unit/cli_ctl/test_commands_brain.py b/tests/unit/cli_ctl/test_commands_brain.py
index 0722131f92..d08529a8ed 100644
--- a/tests/unit/cli_ctl/test_commands_brain.py
+++ b/tests/unit/cli_ctl/test_commands_brain.py
@@ -31,8 +31,8 @@ def test_switch_proceeds_without_yes(capture_api):
def test_switch_no_persist(capture_api):
- runner.invoke(app, ["brain", "switch", "grok", "--no-persist"])
- assert capture_api["calls"][-1]["body"] == {"provider": "grok", "persist": False}
+ runner.invoke(app, ["brain", "switch", "openai", "--no-persist"])
+ assert capture_api["calls"][-1]["body"] == {"provider": "openai", "persist": False}
def test_switch_dry_run_sends_nothing(capture_api):
@@ -50,9 +50,9 @@ def test_subagent_switch(capture_api):
def test_test_provider(capture_api):
- runner.invoke(app, ["brain", "test", "grok"])
+ runner.invoke(app, ["brain", "test", "openai"])
call = capture_api["calls"][-1]
- assert call["method"] == "POST" and call["path"] == "/api/providers/grok/test"
+ assert call["method"] == "POST" and call["path"] == "/api/providers/openai/test"
def test_deep_model(capture_api):
diff --git a/tests/unit/core/test_config_writer_tts_stt_model.py b/tests/unit/core/test_config_writer_tts_stt_model.py
new file mode 100644
index 0000000000..c45089123a
--- /dev/null
+++ b/tests/unit/core/test_config_writer_tts_stt_model.py
@@ -0,0 +1,66 @@
+"""Writers for the TTS voice/model + STT model pickers.
+
+The TTS config is a single ``[tts]`` block (voice_de / voice_en / model) and the
+STT config a single ``[stt]`` block (model) — so these set the GLOBAL value for
+the active provider. config-soll/ENV sync is best-effort and a no-op here (no
+repo config-soll in the tmp path), which must not break the TOML write.
+"""
+from __future__ import annotations
+
+from pathlib import Path
+
+import pytest
+
+from jarvis.core import config_writer
+
+
+def _toml(tmp_path: Path) -> Path:
+ p = tmp_path / "jarvis.toml"
+ p.write_text(
+ "[tts]\nprovider = \"gemini-flash-tts\"\nvoice_de = \"Charon\"\nvoice_en = \"Charon\"\n\n"
+ "[stt]\nprovider = \"groq-api\"\nmodel = \"distil-large-v3\"\n",
+ encoding="utf-8",
+ )
+ return p
+
+
+def test_set_tts_voice_writes_both_languages(tmp_path: Path) -> None:
+ p = _toml(tmp_path)
+ config_writer.set_tts_voice("Kore", path=p)
+ body = p.read_text(encoding="utf-8")
+ assert 'voice_de = "Kore"' in body
+ assert 'voice_en = "Kore"' in body
+
+
+def test_set_tts_model_writes_model(tmp_path: Path) -> None:
+ p = _toml(tmp_path)
+ config_writer.set_tts_model("sonic-2", path=p)
+ assert 'model = "sonic-2"' in p.read_text(encoding="utf-8")
+
+
+def test_set_stt_model_writes_model(tmp_path: Path) -> None:
+ p = _toml(tmp_path)
+ config_writer.set_stt_model("whisper-large-v3", path=p)
+ assert 'model = "whisper-large-v3"' in p.read_text(encoding="utf-8")
+
+
+def test_set_tts_cartesia_model_writes_subtable(tmp_path: Path) -> None:
+ # Cartesia reads [tts.cartesia].model_id, NOT the global [tts].model.
+ p = _toml(tmp_path)
+ config_writer.set_tts_cartesia_model("sonic-2", path=p)
+ body = p.read_text(encoding="utf-8")
+ assert "[tts.cartesia]" in body
+ assert 'model_id = "sonic-2"' in body
+ # Must NOT touch the global model.
+ import tomllib
+
+ data = tomllib.loads(body)
+ assert data["tts"]["cartesia"]["model_id"] == "sonic-2"
+
+
+def test_writers_raise_when_config_missing(tmp_path: Path) -> None:
+ missing = tmp_path / "nope.toml"
+ with pytest.raises(FileNotFoundError):
+ config_writer.set_tts_voice("Kore", path=missing)
+ with pytest.raises(FileNotFoundError):
+ config_writer.set_stt_model("whisper-large-v3", path=missing)
diff --git a/tests/unit/core/test_persisted_provider_env_refresh.py b/tests/unit/core/test_persisted_provider_env_refresh.py
index 1aaba0cbd8..4eb7c37acb 100644
--- a/tests/unit/core/test_persisted_provider_env_refresh.py
+++ b/tests/unit/core/test_persisted_provider_env_refresh.py
@@ -82,25 +82,60 @@ def test_refresh_covers_all_persistent_provider_keys() -> None:
"JARVIS__ACK_BRAIN__ENABLED",
"JARVIS__ACK_BRAIN__PROVIDER",
"JARVIS__ACK_BRAIN__FALLBACK_PROVIDER",
+ # TTS engine selection beyond the provider tier. Forensic 2026-06-22: an
+ # in-app restart inherited a stale env (use_vertex=true / model=sonic-2 /
+ # voice=leo) from a pre-change ancestor; PROVIDER healed but these did
+ # not, leaving Gemini-TTS on the wrong Vertex billing path with a bogus
+ # model even after the registry was corrected to the AI-Studio key path.
+ "JARVIS__TTS__MODEL",
+ "JARVIS__TTS__USE_VERTEX",
+ "JARVIS__TTS__VOICE_DE",
+ "JARVIS__TTS__VOICE_EN",
} <= keys
+def test_refresh_heals_stale_tts_vertex_model_and_voice(
+ monkeypatch: pytest.MonkeyPatch,
+) -> None:
+ """The exact 2026-06-22 regression: a stale inherited TTS env (Vertex on, a
+ bogus model, the wrong voice) is healed to the registry's AI-Studio values
+ so a restart actually switches Gemini-TTS back to the topped-up key path."""
+ monkeypatch.setenv("JARVIS__TTS__USE_VERTEX", "true") # stale inherited
+ monkeypatch.setenv("JARVIS__TTS__MODEL", "sonic-2") # stale, wrong engine
+ monkeypatch.setenv("JARVIS__TTS__VOICE_DE", "leo") # stale
+ monkeypatch.setenv("JARVIS__TTS__VOICE_EN", "leo") # stale
+ reg = {
+ "JARVIS__TTS__USE_VERTEX": "false",
+ "JARVIS__TTS__MODEL": "gemini-3.1-flash-tts-preview",
+ "JARVIS__TTS__VOICE_DE": "Charon",
+ "JARVIS__TTS__VOICE_EN": "Charon",
+ }
+
+ changed = config.refresh_persisted_env_from_user_registry(read=reg.get)
+
+ assert os.environ["JARVIS__TTS__USE_VERTEX"] == "false"
+ assert os.environ["JARVIS__TTS__MODEL"] == "gemini-3.1-flash-tts-preview"
+ assert os.environ["JARVIS__TTS__VOICE_DE"] == "Charon"
+ assert os.environ["JARVIS__TTS__VOICE_EN"] == "Charon"
+ assert changed["JARVIS__TTS__USE_VERTEX"] == "false"
+
+
def test_refresh_heals_stale_ack_brain_enabled(monkeypatch: pytest.MonkeyPatch) -> None:
"""The exact 2026-06-21 regression: a stale inherited enabled=false is healed
to the registry's true, so the spawn announcer's LLM path is wired on boot."""
monkeypatch.setenv("JARVIS__ACK_BRAIN__ENABLED", "false") # stale inherited
- monkeypatch.setenv("JARVIS__ACK_BRAIN__PROVIDER", "gemini") # stale, dead provider
+ monkeypatch.setenv("JARVIS__ACK_BRAIN__PROVIDER", "openai") # stale, dead provider
reg = {
"JARVIS__ACK_BRAIN__ENABLED": "true",
- "JARVIS__ACK_BRAIN__PROVIDER": "grok",
+ "JARVIS__ACK_BRAIN__PROVIDER": "gemini",
}
changed = config.refresh_persisted_env_from_user_registry(read=reg.get)
assert os.environ["JARVIS__ACK_BRAIN__ENABLED"] == "true"
- assert os.environ["JARVIS__ACK_BRAIN__PROVIDER"] == "grok"
+ assert os.environ["JARVIS__ACK_BRAIN__PROVIDER"] == "gemini"
assert changed["JARVIS__ACK_BRAIN__ENABLED"] == "true"
- assert changed["JARVIS__ACK_BRAIN__PROVIDER"] == "grok"
+ assert changed["JARVIS__ACK_BRAIN__PROVIDER"] == "gemini"
def test_refresh_default_reader_is_noop_off_win32(monkeypatch: pytest.MonkeyPatch) -> None:
diff --git a/tests/unit/core/test_provider_endpoint.py b/tests/unit/core/test_provider_endpoint.py
index eedb8d48bd..f4220beb28 100644
--- a/tests/unit/core/test_provider_endpoint.py
+++ b/tests/unit/core/test_provider_endpoint.py
@@ -19,10 +19,12 @@ def _cfg_with(provider_id: str, base_url: str | None) -> JarvisConfig:
def test_returns_vendor_default_when_no_override(monkeypatch):
monkeypatch.setattr(cfg, "get_provider_secret", lambda pid: "sk-real")
res = resolve_provider_endpoint(
- "grok", vendor_default_base_url="https://api.x.ai/v1", config=JarvisConfig()
+ "gemini",
+ vendor_default_base_url="https://generativelanguage.googleapis.com/v1beta",
+ config=JarvisConfig(),
)
assert isinstance(res, ResolvedEndpoint)
- assert res.base_url == "https://api.x.ai/v1"
+ assert res.base_url == "https://generativelanguage.googleapis.com/v1beta"
assert res.credential == "sk-real"
assert res.via_proxy is False
@@ -30,11 +32,11 @@ def test_returns_vendor_default_when_no_override(monkeypatch):
def test_explicit_override_wins(monkeypatch):
monkeypatch.setattr(cfg, "get_provider_secret", lambda pid: "sk-real")
res = resolve_provider_endpoint(
- "grok",
- vendor_default_base_url="https://api.x.ai/v1",
- config=_cfg_with("grok", "https://proxy.example/p/grok/v1"),
+ "gemini",
+ vendor_default_base_url="https://generativelanguage.googleapis.com/v1beta",
+ config=_cfg_with("gemini", "https://proxy.example/p/gemini/v1"),
)
- assert res.base_url == "https://proxy.example/p/grok/v1"
+ assert res.base_url == "https://proxy.example/p/gemini/v1"
assert res.credential == "sk-real"
@@ -65,11 +67,11 @@ def test_team_mode_routes_through_proxy(monkeypatch):
monkeypatch.setattr(cfg, "get_provider_secret", lambda pid: "sk-real")
monkeypatch.setattr(cfg, "get_secret", lambda key, env=None: "tok-123")
res = resolve_provider_endpoint(
- "grok",
- vendor_default_base_url="https://api.x.ai/v1",
+ "gemini",
+ vendor_default_base_url="https://generativelanguage.googleapis.com/v1beta",
config=_team_cfg("https://keys.acme.dev"),
)
- assert res.base_url == "https://keys.acme.dev/p/grok"
+ assert res.base_url == "https://keys.acme.dev/p/gemini"
assert res.credential == "tok-123"
assert res.via_proxy is True
@@ -95,9 +97,9 @@ def test_team_mode_local_provider_stays_direct(monkeypatch):
def test_team_mode_disabled_stays_direct(monkeypatch):
monkeypatch.setattr(cfg, "get_provider_secret", lambda pid: "sk-real")
res = resolve_provider_endpoint(
- "grok",
- vendor_default_base_url="https://api.x.ai/v1",
+ "gemini",
+ vendor_default_base_url="https://generativelanguage.googleapis.com/v1beta",
config=_team_cfg("https://keys.acme.dev", enabled=False),
)
assert res.via_proxy is False
- assert res.base_url == "https://api.x.ai/v1"
+ assert res.base_url == "https://generativelanguage.googleapis.com/v1beta"
diff --git a/tests/unit/harness/test_cu_awareness_and_switch.py b/tests/unit/harness/test_cu_awareness_and_switch.py
new file mode 100644
index 0000000000..32ed236233
--- /dev/null
+++ b/tests/unit/harness/test_cu_awareness_and_switch.py
@@ -0,0 +1,142 @@
+"""Phase 1a + 1c: window-state awareness line + switch_window CU action.
+
+1a — the CU prompt gets a compact "what is already open" line so the model stops
+re-launching apps that are already running (the OBS-in-the-taskbar case).
+1c — ``switch_window`` becomes a CU action so the model can focus an existing
+window directly.
+
+Unit-level: window_state.list_windows/get_foreground_title/focus_window are
+monkeypatched, so these are deterministic regardless of the host's open windows.
+The full run_cu_loop integration is covered by the existing harness suite as a
+regression guard.
+"""
+from __future__ import annotations
+
+import pytest
+
+from jarvis.harness.computer_use_context import ComputerUseContext
+from jarvis.harness.screenshot_only_loop import (
+ _VALID_ACTIONS,
+ CULoopError,
+ _execute_action,
+ _parse_action,
+ _validate_action_dict,
+ _window_awareness_line,
+)
+from jarvis.platform.window_state import WindowInfo
+
+
+def _ctx() -> ComputerUseContext:
+ return ComputerUseContext(
+ vision_engine=None, brain_manager=None, tool_executor=object(), tools={}
+ )
+
+
+# --- switch_window as a CU action -------------------------------------------
+
+
+def test_switch_window_in_valid_actions():
+ assert "switch_window" in _VALID_ACTIONS
+
+
+def test_parse_action_switch_window_ok():
+ obj = _parse_action('{"action":"switch_window","name":"OBS"}')
+ assert obj["action"] == "switch_window"
+ assert obj["name"] == "OBS"
+
+
+def test_parse_action_switch_window_accepts_title_key():
+ obj = _parse_action('{"action":"switch_window","title":"OBS"}')
+ assert obj["name"] == "OBS"
+
+
+def test_parse_action_switch_window_requires_name():
+ with pytest.raises(CULoopError):
+ _parse_action('{"action":"switch_window"}')
+
+
+def test_validate_action_dict_switch_window_normalizes_name():
+ obj = _validate_action_dict({"action": "switch_window", "name": " OBS "})
+ assert obj["name"] == "OBS"
+
+
+def test_validate_action_dict_switch_window_requires_name():
+ with pytest.raises(CULoopError):
+ _validate_action_dict({"action": "switch_window", "name": " "})
+
+
+async def test_execute_switch_window_focuses(monkeypatch):
+ monkeypatch.setattr(
+ "jarvis.platform.window_state.focus_window", lambda t: (True, f"focused:{t}")
+ )
+ ok, msg = await _execute_action(
+ {"action": "switch_window", "name": "OBS"}, _ctx(), trace_id=None, user_goal="x"
+ )
+ assert ok is True
+ assert "OBS" in msg
+
+
+async def test_execute_switch_window_reports_not_found(monkeypatch):
+ monkeypatch.setattr(
+ "jarvis.platform.window_state.focus_window", lambda t: (False, "no window")
+ )
+ ok, msg = await _execute_action(
+ {"action": "switch_window", "name": "Ghost"}, _ctx(), trace_id=None, user_goal="x"
+ )
+ assert ok is False
+
+
+async def test_execute_switch_window_empty_name_fails(monkeypatch):
+ ok, msg = await _execute_action(
+ {"action": "switch_window", "name": ""}, _ctx(), trace_id=None, user_goal="x"
+ )
+ assert ok is False
+
+
+# --- awareness line ---------------------------------------------------------
+
+
+def test_awareness_line_lists_open_windows(monkeypatch):
+ monkeypatch.setattr(
+ "jarvis.platform.window_state.list_windows",
+ lambda: [WindowInfo("OBS 30", minimized=True), WindowInfo("Google Chrome")],
+ )
+ monkeypatch.setattr(
+ "jarvis.platform.window_state.get_foreground_title", lambda: "Google Chrome"
+ )
+ line = _window_awareness_line(_ctx())
+ assert "OBS 30 (minimized)" in line
+ assert "Google Chrome" in line
+ assert "FOREGROUND: Google Chrome" in line
+
+
+def test_awareness_line_empty_when_no_windows(monkeypatch):
+ monkeypatch.setattr("jarvis.platform.window_state.list_windows", lambda: [])
+ assert _window_awareness_line(_ctx()) == ""
+
+
+def test_awareness_line_never_raises(monkeypatch):
+ def boom():
+ raise RuntimeError("enum blew up")
+
+ monkeypatch.setattr("jarvis.platform.window_state.list_windows", boom)
+ assert _window_awareness_line(_ctx()) == ""
+
+
+def test_awareness_line_respects_disable_flag(monkeypatch):
+ monkeypatch.setattr(
+ "jarvis.platform.window_state.list_windows", lambda: [WindowInfo("X")]
+ )
+ ctx = _ctx()
+ ctx.window_awareness = False
+ assert _window_awareness_line(ctx) == ""
+
+
+def test_awareness_line_dedupes_and_caps(monkeypatch):
+ many = [WindowInfo(f"App {i}") for i in range(50)] + [WindowInfo("App 0")]
+ monkeypatch.setattr("jarvis.platform.window_state.list_windows", lambda: many)
+ monkeypatch.setattr("jarvis.platform.window_state.get_foreground_title", lambda: "")
+ line = _window_awareness_line(_ctx())
+ # capped well below 51 entries; "App 0" appears once despite the duplicate
+ assert line.count("App 0") == 1
+ assert line.count(";") < 20
diff --git a/tests/unit/harness/test_cu_click_refine.py b/tests/unit/harness/test_cu_click_refine.py
index 3842a505bd..b701a79e59 100644
--- a/tests/unit/harness/test_cu_click_refine.py
+++ b/tests/unit/harness/test_cu_click_refine.py
@@ -168,6 +168,11 @@ class FakeCtx:
self.bus = None
self.per_step_timeout_s = 5.0
self.verify_after_each_step = verify
+ # These tests isolate the LLM refine path; the Phase-2 UIA snap (which
+ # would otherwise fire first on a verified miss and query the real host
+ # accessibility tree) is turned off so the refine behaviour is tested in
+ # isolation. The snap itself is covered by tests/unit/harness/test_cu_uia_snap.py.
+ self.uia_click_fallback = False
class FakeObservation:
diff --git a/tests/unit/harness/test_cu_elevation_pause.py b/tests/unit/harness/test_cu_elevation_pause.py
new file mode 100644
index 0000000000..8b01c8adb9
--- /dev/null
+++ b/tests/unit/harness/test_cu_elevation_pause.py
@@ -0,0 +1,149 @@
+"""Computer-Use pause-and-resume on an OS elevation prompt (UAC Secure Desktop).
+
+When a launched app raises a UAC prompt, Windows hoists the Secure Desktop. A
+non-elevated process can neither screenshot it nor click it (UIPI), so the loop
+used to abort blind with the misleading "couldn't see the screen" (exit 1).
+
+These pin the new behavior: detect the privileged prompt, ask the user for the
+one unavoidable confirmation click, poll until it clears, then RESUME — or, if
+no confirmation comes within the wait budget, stop with the honest
+elevation-specific message (exit 9).
+"""
+
+from __future__ import annotations
+
+import asyncio
+from types import SimpleNamespace
+
+import pytest
+
+from jarvis.harness import screenshot_only_loop as loop
+from jarvis.voice.action_phrases import action_phrase
+
+
+class _RecordingBus:
+ def __init__(self) -> None:
+ self.events: list = []
+
+ async def publish(self, event: object) -> None:
+ self.events.append(event)
+
+
+class _FakeToken:
+ def __init__(self, cancelled: bool = False) -> None:
+ self._cancelled = cancelled
+
+ def is_cancelled(self) -> bool:
+ return self._cancelled
+
+
[email protected](autouse=True)
+def _fast_elevation_timings(monkeypatch):
+ # Keep the poll loop sub-second so the timeout test does not sleep 60s.
+ monkeypatch.setattr(loop, "_ELEVATION_WAIT_TIMEOUT_S", 0.05)
+ monkeypatch.setattr(loop, "_ELEVATION_POLL_S", 0.005)
+
+
+def _set_probe(monkeypatch, fn) -> None:
+ monkeypatch.setattr(
+ "jarvis.platform.privileged_prompt.privileged_prompt_active", fn
+ )
+
+
+async def test_no_prompt_returns_no_prompt_without_announcing(monkeypatch):
+ _set_probe(monkeypatch, lambda: False)
+ bus = _RecordingBus()
+ ctx = SimpleNamespace(bus=bus)
+
+ result = await loop._await_privileged_prompt_clearance(
+ ctx, "open OBS and record", 1, None
+ )
+
+ assert result == "no_prompt"
+ assert bus.events == [] # a normal step must never speak the elevation ask
+
+
+async def test_cleared_when_prompt_disappears(monkeypatch):
+ calls = {"n": 0}
+
+ def _probe() -> bool:
+ calls["n"] += 1
+ return calls["n"] < 2 # up on the first check, gone afterwards
+
+ _set_probe(monkeypatch, _probe)
+ ctx = SimpleNamespace(bus=_RecordingBus())
+
+ result = await loop._await_privileged_prompt_clearance(
+ ctx, "open OBS", 3, None
+ )
+
+ assert result == "cleared"
+
+
+async def test_timeout_when_prompt_persists(monkeypatch):
+ _set_probe(monkeypatch, lambda: True)
+ ctx = SimpleNamespace(bus=_RecordingBus())
+
+ result = await loop._await_privileged_prompt_clearance(
+ ctx, "open OBS", 3, None
+ )
+
+ assert result == "timeout"
+
+
+async def test_cancelled_while_waiting(monkeypatch):
+ _set_probe(monkeypatch, lambda: True)
+ ctx = SimpleNamespace(bus=_RecordingBus())
+
+ result = await loop._await_privileged_prompt_clearance(
+ ctx, "open OBS", 3, _FakeToken(cancelled=True)
+ )
+
+ assert result == "cancelled"
+
+
+async def test_announces_request_in_turn_language(monkeypatch):
+ _set_probe(monkeypatch, lambda: True)
+ bus = _RecordingBus()
+ ctx = SimpleNamespace(bus=bus)
+
+ await loop._await_privileged_prompt_clearance(
+ ctx, "Kannst du bitte eine Aufnahme starten?", 1, None
+ )
+ await asyncio.sleep(0.01) # let the detached announcement task run
+
+ texts = [getattr(e, "text", "") for e in bus.events]
+ assert action_phrase("cu_awaiting_elevation", "de") in texts
+
+
+async def test_announces_request_in_english_for_english_turn(monkeypatch):
+ _set_probe(monkeypatch, lambda: True)
+ bus = _RecordingBus()
+ ctx = SimpleNamespace(bus=bus)
+
+ await loop._await_privileged_prompt_clearance(
+ ctx, "Could you start a recording for me?", 1, None
+ )
+ await asyncio.sleep(0.01)
+
+ texts = [getattr(e, "text", "") for e in bus.events]
+ assert action_phrase("cu_awaiting_elevation", "en") in texts
+
+
+async def test_probe_failure_treated_as_no_prompt(monkeypatch):
+ def _boom() -> bool:
+ raise OSError("probe blew up")
+
+ _set_probe(monkeypatch, _boom)
+ ctx = SimpleNamespace(bus=_RecordingBus())
+
+ result = await loop._await_privileged_prompt_clearance(ctx, "open OBS", 1, None)
+
+ assert result == "no_prompt" # never crash the loop on a probe fault
diff --git a/tests/unit/harness/test_cu_grok_vision.py b/tests/unit/harness/test_cu_grok_vision.py
new file mode 100644
index 0000000000..aa4bb69467
--- /dev/null
+++ b/tests/unit/harness/test_cu_grok_vision.py
@@ -0,0 +1,314 @@
+"""Computer-Use must reach a vision-capable provider — provider-agnostically.
+
+Live forensic 2026-06-21 18:41: a "open Chrome with computer use …" command
+DID dispatch to the screenshot harness (routing fixed), but the harness gave up:
+
+ exit 2 · [cu] giving up after 3 model failures … ComputerUseLoop provider
+ chain failed: 3 provider(s) skipped — no vision; claude-api(haiku):
+ incomplete chunked read; openrouter(opus-4.8): Kein O…
+
+Root cause: ``screenshot_only_loop._call_brain`` skips every provider whose
+``supports_vision`` is False when a screenshot is attached, and the one live
+vision-capable provider had been filtered out of the chain by a stale
+``_dead_providers`` flag. CU must not be permanently disabled by a transient
+dead-flag on its only eyes.
+
+The fix is PROVIDER-AGNOSTIC (AP-21): the CU loop dispatches the screenshot to
+whichever vision-capable provider leads the chain, falls through a blind active
+provider to the next vision-capable one, and — as a last resort —
+``computer_use_planner.iter_last_resort_vision`` tries every registered
+vision-capable provider IGNORING the transient dead/cooldown flags. The only
+gate anywhere is ``supports_vision`` — never a provider name.
+
+(Grok was the live example in the original forensic; it has since been removed
+as a brain provider. These tests therefore pin the generic mechanism across the
+remaining vision-capable providers, which is what AP-21 actually mandates.)
+"""
+from __future__ import annotations
+
+import time
+from typing import Any
+from uuid import uuid4
+
+import pytest
+
+from jarvis.core.protocols import (
+ ImageBlock,
+ Observation,
+)
+from jarvis.harness.screenshot_only_loop import CULoopError, _call_brain
+
+# Reuse the loop-test fakes (FakeBrain shim, ctx builder, host isolation fixture).
+from tests.unit.harness.test_cu_loop_robustness import ( # noqa: E402
+ FakeBrain,
+ _StreamingBrain,
+ make_ctx,
+)
+
+# Pull in the autouse _isolate_host fixture so these tests never touch the
+# real desktop (UIA / monitor probing) either.
+from tests.unit.harness.test_cu_loop_robustness import _isolate_host # noqa: E402,F401
+
+
+# ---------------------------------------------------------------------------
+# 1. The sibling CLI brain (codex) must report vision per RUNTIME path: the
+# ChatGPT-CLI path drops images (blind) → supports_vision must be False so
+# the CU loop skips it and reaches a vision-capable provider; the API-key
+# path can see → True. A static True made CU dispatch a screenshot to the
+# blind CLI brain.
+# ---------------------------------------------------------------------------
+
+
+def test_codex_is_blind_on_the_cli_path(monkeypatch: pytest.MonkeyPatch) -> None:
+ from jarvis.plugins.brain.codex import CodexBrain
+
+ monkeypatch.setattr(CodexBrain, "_api_key", lambda self: None)
+ brain = CodexBrain(model="gpt-5.5")
+ assert brain.supports_vision is False, (
+ "codex on the ChatGPT-CLI path drops images — it must report blind so "
+ "the CU loop skips it and reaches a vision-capable provider"
+ )
+
+
+def test_codex_sees_on_the_api_key_path(monkeypatch: pytest.MonkeyPatch) -> None:
+ from jarvis.plugins.brain.codex import CodexBrain
+
+ monkeypatch.setattr(CodexBrain, "_api_key", lambda self: "sk-test-key")
+ brain = CodexBrain(model="gpt-5.5")
+ assert brain.supports_vision is True, (
+ "with an API key codex uses the vision-capable API path"
+ )
+
+
+# ---------------------------------------------------------------------------
+# 2. PROVIDER-AGNOSTIC proof: CU is not pinned to any provider. For EACH
+# vision-capable provider set as the active/leading brain, ``_call_brain``
+# must dispatch the screenshot to THAT provider. The selection is
+# capability-gated, never provider-name-gated.
+# ---------------------------------------------------------------------------
+
+
+_VISION_PROVIDERS = ("claude-api", "openrouter", "openai", "gemini")
+
+
+class _SingleProviderManager:
+ """BrainManager-shaped fake whose chain leads with one named provider.
+
+ ``_get_brain`` returns the SAME vision-capable streaming brain regardless of
+ name, so the test proves selection is driven purely by the chain order +
+ capability gate — not by any provider-name special-case in ``_call_brain``.
+ """
+
+ def __init__(self, lead_provider: str, brain: _StreamingBrain) -> None:
+ self.active_provider = lead_provider
+ self._lead = lead_provider
+ self._brain = brain
+ self.requested: list[tuple[str, str | None]] = []
+
+ def _build_fallback_chain(self, level: str) -> list[tuple[str, str | None]]:
+ # The active provider leads; a second distinct vision provider follows
+ # so the test also proves the LEADER is the one dispatched (not a
+ # blind fallthrough to position 1).
+ other = "gemini" if self._lead != "gemini" else "claude-api"
+ return [(self._lead, f"{self._lead}-model"), (other, f"{other}-model")]
+
+ def _get_brain(self, name: str, model: str | None = None) -> _StreamingBrain:
+ self.requested.append((name, model))
+ return self._brain
+
+
[email protected]("lead_provider", _VISION_PROVIDERS)
+async def test_cu_dispatches_screenshot_to_active_vision_provider(
+ lead_provider: str,
+) -> None:
+ """For EACH vision-capable provider, when it is the active/leading brain the
+ CU loop dispatches the screenshot to IT — not to any hardcoded provider.
+ This is the provider-agnosticism guarantee."""
+ brain = _StreamingBrain(text='{"action": "done"}', supports_vision=True)
+ manager = _SingleProviderManager(lead_provider, brain)
+ ctx = make_ctx(FakeBrain())
+ ctx.brain_manager = manager
+ obs = Observation(
+ trace_id=uuid4(), timestamp_ns=time.time_ns(),
+ screenshot_path=None, screenshot_hash="x",
+ )
+ img = ImageBlock(mime="image/jpeg", data_b64="QQ==", source_hash="x")
+
+ raw = await _call_brain(
+ ctx, observation=obs, user_goal="open chrome with computer use",
+ history_text="", images_override=[img],
+ )
+
+ assert raw == '{"action": "done"}'
+ # The leading provider was the FIRST (and only) brain dispatched.
+ assert brain.calls == 1
+ assert manager.requested[0] == (lead_provider, f"{lead_provider}-model")
+
+
[email protected]("vision_provider", _VISION_PROVIDERS)
+async def test_cu_falls_through_blind_active_to_any_vision_provider(
+ vision_provider: str,
+) -> None:
+ """A blind active provider (codex-like, ``supports_vision=False``)
+ must be skipped and the screenshot must fall through to WHICHEVER
+ vision-capable provider is next — proving the fallthrough is generic, not
+ pinned to one provider."""
+ blind = _StreamingBrain(
+ text='{"action": "click", "x": 1, "y": 1}', supports_vision=False,
+ )
+ seeing = _StreamingBrain(text='{"action": "done"}', supports_vision=True)
+
+ class _BlindThenVisionManager:
+ active_provider = "codex"
+
+ def __init__(self) -> None:
+ self.requested: list[tuple[str, str | None]] = []
+
+ def _build_fallback_chain(self, level: str) -> list[tuple[str, str | None]]:
+ return [
+ ("codex", "gpt-5.5"),
+ (vision_provider, f"{vision_provider}-model"),
+ ]
+
+ def _get_brain(self, name: str, model: str | None = None) -> _StreamingBrain:
+ self.requested.append((name, model))
+ return blind if name == "codex" else seeing
+
+ manager = _BlindThenVisionManager()
+ ctx = make_ctx(FakeBrain())
+ ctx.brain_manager = manager
+ obs = Observation(
+ trace_id=uuid4(), timestamp_ns=time.time_ns(),
+ screenshot_path=None, screenshot_hash="x",
+ )
+ img = ImageBlock(mime="image/jpeg", data_b64="QQ==", source_hash="x")
+
+ raw = await _call_brain(
+ ctx, observation=obs, user_goal="open chrome", history_text="",
+ images_override=[img],
+ )
+
+ assert raw == '{"action": "done"}'
+ assert blind.calls == 0, "the blind active provider must never be dispatched"
+ assert seeing.calls == 1, "the screenshot must reach the vision-capable brain"
+ assert (vision_provider, f"{vision_provider}-model") in manager.requested
+
+
+# ---------------------------------------------------------------------------
+# 3. STALE DEAD-FLAG RESILIENCE (live forensic 2026-06-21 18:41, exit 2):
+# "[cu] giving up after 3 model failures … provider chain failed: 3
+# provider(s) skipped — no vision". The ONE live, vision-capable brain was
+# NOT even in the tail: it had been filtered out of the chain entirely by a
+# stale ``_dead_providers`` flag (a recurring "spuriously flagged dead" bug).
+# With every other vision provider keyless/throttled and the live one
+# filtered out, CU had no vision brain and gave up. CU must not be
+# permanently disabled by a stale dead-flag on its only eyes.
+# ---------------------------------------------------------------------------
+
+
+async def test_cu_reaches_vision_brain_despite_stale_dead_flag() -> None:
+ """The blind active provider leads and the one vision-capable provider
+ (here gemini) was filtered out of the chain by a stale ``_dead_providers``
+ flag, so the normal chain reaches NO vision brain. As a last resort CU must
+ try every registered vision-capable provider IGNORING the transient dead/
+ cooldown flags, and reach gemini — instead of failing "no vision"."""
+ seeing = _StreamingBrain(text='{"action": "done"}', supports_vision=True)
+ blind = _StreamingBrain(
+ text='{"action": "click", "x": 1, "y": 1}', supports_vision=False,
+ )
+
+ class _Registry:
+ def available(self) -> list[str]:
+ return ["codex", "gemini"]
+
+ class _DeadFlaggedVisionManager:
+ active_provider = "codex"
+
+ def __init__(self) -> None:
+ self._dead_providers = {"gemini"} # stale flag on the only vision brain
+ self._registry = _Registry()
+ self.requested: list[tuple[str, str | None]] = []
+
+ def _build_fallback_chain(self, level: str) -> list[tuple[str, str | None]]:
+ # The real builder filters dead providers OUT, so gemini is gone and
+ # only the blind active provider survives → no vision brain in chain.
+ return [("codex", "gpt-5.5"), ("codex", "gpt-5.5-pro")]
+
+ def _fast_model(self, name: str) -> str | None:
+ return {"codex": "gpt-5.5", "gemini": "gemini-3.1-pro-preview"}.get(name)
+
+ def _get_brain(self, name: str, model: str | None = None) -> Any:
+ self.requested.append((name, model))
+ if name == "codex":
+ return blind
+ if name == "gemini":
+ return seeing
+ raise AssertionError(f"unexpected provider {name!r}")
+
+ manager = _DeadFlaggedVisionManager()
+ ctx = make_ctx(FakeBrain())
+ ctx.brain_manager = manager
+ obs = Observation(
+ trace_id=uuid4(), timestamp_ns=time.time_ns(),
+ screenshot_path=None, screenshot_hash="x",
+ )
+ img = ImageBlock(mime="image/jpeg", data_b64="QQ==", source_hash="x")
+
+ raw = await _call_brain(
+ ctx, observation=obs, user_goal="open chrome with computer use",
+ history_text="", images_override=[img],
+ )
+
+ assert raw == '{"action": "done"}', (
+ "CU gave up 'no vision' despite a live, vision-capable provider behind a "
+ "stale dead-flag"
+ )
+ assert blind.calls == 0, "the blind active provider must never plan a screenshot"
+ assert seeing.calls == 1, "the last-resort must reach the vision-capable brain"
+ assert ("gemini", "gemini-3.1-pro-preview") in manager.requested
+
+
+async def test_cu_still_fails_honestly_when_no_vision_provider_exists() -> None:
+ """When there is genuinely NO vision-capable provider anywhere (active blind,
+ none else registered), CU still fails honestly with a 'vision' message — the
+ last-resort must not invent a provider, loop, or hang."""
+ blind = _StreamingBrain(
+ text='{"action": "click", "x": 1, "y": 1}', supports_vision=False,
+ )
+
+ class _Registry:
+ def available(self) -> list[str]:
+ return ["codex"]
+
+ class _OnlyBlindManager:
+ active_provider = "codex"
+
+ def __init__(self) -> None:
+ self._dead_providers: set[str] = set()
+ self._registry = _Registry()
+
+ def _build_fallback_chain(self, level: str) -> list[tuple[str, str | None]]:
+ return [("codex", "gpt-5.5")]
+
+ def _fast_model(self, name: str) -> str | None:
+ return "gpt-5.5"
+
+ def _get_brain(self, name: str, model: str | None = None) -> Any:
+ return blind
+
+ manager = _OnlyBlindManager()
+ ctx = make_ctx(FakeBrain())
+ ctx.brain_manager = manager
+ obs = Observation(
+ trace_id=uuid4(), timestamp_ns=time.time_ns(),
+ screenshot_path=None, screenshot_hash="x",
+ )
+ img = ImageBlock(mime="image/jpeg", data_b64="QQ==", source_hash="x")
+
+ with pytest.raises(CULoopError) as excinfo:
+ await _call_brain(
+ ctx, observation=obs, user_goal="open chrome",
+ history_text="", images_override=[img],
+ )
+ assert "vision" in str(excinfo.value).lower()
+ assert blind.calls == 0
diff --git a/tests/unit/harness/test_cu_loop_robustness.py b/tests/unit/harness/test_cu_loop_robustness.py
index 222106a876..d17217dc9a 100644
--- a/tests/unit/harness/test_cu_loop_robustness.py
+++ b/tests/unit/harness/test_cu_loop_robustness.py
@@ -22,7 +22,13 @@ from uuid import uuid4
import pytest
import jarvis.harness.screenshot_only_loop as loop_mod
-from jarvis.core.protocols import HarnessResult, HarnessTask, Observation
+from jarvis.core.protocols import (
+ BrainDelta,
+ HarnessResult,
+ HarnessTask,
+ ImageBlock,
+ Observation,
+)
from jarvis.harness.computer_use_context import ComputerUseContext
from jarvis.harness.screenshot_only_loop import (
CULoopError,
@@ -126,6 +132,71 @@ class FakeExecutor:
return FakeToolResult()
+class _StreamingBrain:
+ """Minimal provider-shaped brain for CU provider-chain tests."""
+
+ name = "streaming-brain"
+ context_window = 8192
+ supports_tools = False
+ supports_vision = True
+
+ def __init__(self, *, text: str = "", exc: Exception | None = None,
+ supports_vision: bool = True) -> None:
+ self.text = text
+ self.exc = exc
+ self.calls = 0
+ self.supports_vision = supports_vision
+
+ async def complete(self, req: Any): # type: ignore[no-untyped-def]
+ self.calls += 1
+ if self.exc is not None:
+ raise self.exc
+ if self.text:
+ yield BrainDelta(content=self.text)
+ yield BrainDelta(finish_reason="stop")
+
+ def estimate_cost(self, req: Any) -> float:
+ return 0.0
+
+
+class _FallbackChainManager:
+ """BrainManager-shaped fake that exposes a configured provider chain."""
+
+ active_provider = "primary"
+
+ def __init__(self) -> None:
+ self.primary = _StreamingBrain(exc=RuntimeError("primary down"))
+ self.fallback = _StreamingBrain(text='{"action": "done"}')
+ self.requested: list[tuple[str, str | None]] = []
+
+ def _build_fallback_chain(self, level: str) -> list[tuple[str, str | None]]:
+ return [("primary", "bad-model"), ("fallback", "good-model")]
+
+ def _get_brain(self, name: str, model: str | None = None) -> _StreamingBrain:
+ self.requested.append((name, model))
+ if name == "primary":
+ return self.primary
+ if name == "fallback":
+ return self.fallback
+ raise AssertionError(f"unexpected provider {name!r}")
+
+
+class _RateTrackerProbe:
+ def __init__(self) -> None:
+ self.marked: list[tuple[str, str | None]] = []
+ self.blocked: set[tuple[str, str | None]] = set()
+
+ def is_available(self, provider: str, model: str | None = None) -> bool:
+ return (provider, model) not in self.blocked
+
+ def mark_rate_limited(
+ self, provider: str, model: str | None = None,
+ cooldown_s: float | None = None,
+ ) -> None:
+ self.marked.append((provider, model))
+ self.blocked.add((provider, model))
+
+
def make_ctx(brain: FakeBrain, *, titles: list[str] | None = None,
verify: bool = False, step_budget: int = 10,
bus: Any = None, announce_progress: bool = False,
@@ -169,6 +240,13 @@ def _isolate_host(monkeypatch: pytest.MonkeyPatch) -> None:
monkeypatch.setattr(
loop_mod, "_capture_monitor_geometry", lambda: (0, 0, 1920, 1080),
)
+ # Default the privileged-prompt probe to "no prompt" so the loop never makes
+ # the real OpenInputDesktop Win32 call from a test; the elevation tests
+ # override this with their own injected sequence.
+ monkeypatch.setattr(
+ "jarvis.platform.privileged_prompt.privileged_prompt_active",
+ lambda: False,
+ )
# Keep the UI-tree-source singleton hermetic between tests.
monkeypatch.setattr(loop_mod, "_UI_TREE_SOURCE", None, raising=False)
# Neutralize the post-open_app settle probe suite-wide (it sleeps up to
@@ -281,6 +359,244 @@ async def test_call_brain_raises_on_unusable_manager() -> None:
await _call_brain(ctx, observation=obs, user_goal="g", history_text="")
+async def test_call_brain_uses_provider_fallback_chain() -> None:
+ """CU must not bypass BrainManager fallbacks.
+
+ Live regression 2026-06-20: the normal chat turn fell back from a broken
+ Antigravity CLI provider to Grok, but Computer-Use called only
+ ``active_provider``. The CU loop then retried the same broken provider
+ three times and exited with parse/confusion instead of using the configured
+ fallback provider.
+ """
+ manager = _FallbackChainManager()
+ ctx = make_ctx(FakeBrain())
+ ctx.brain_manager = manager
+ obs = Observation(
+ trace_id=uuid4(),
+ timestamp_ns=time.time_ns(),
+ screenshot_path=None,
+ screenshot_hash="x",
+ )
+
+ raw = await _call_brain(ctx, observation=obs, user_goal="open chrome", history_text="")
+
+ assert raw == '{"action": "done"}'
+ assert manager.primary.calls == 1
+ assert manager.fallback.calls == 1
+ assert manager.requested == [
+ ("primary", "bad-model"),
+ ("fallback", "good-model"),
+ ]
+
+
+# ---------------------------------------------------------------------------
+# Vision-grounding — a screenshot-blind provider must never plan a CU step
+# ---------------------------------------------------------------------------
+
+
+async def test_call_brain_skips_blind_provider_when_screenshot_attached() -> None:
+ """CU is screenshot-grounded: a provider that cannot see the image (a
+ text-only CLI brain such as Antigravity, ``supports_vision=False``) would
+ plan blind. The dispatch must SKIP it and fall through to the next
+ vision-capable provider.
+
+ Forensic 2026-06-20: with a screenshot-blind CLI brain active, the CU planner
+ ran blind — the CLI provider silently dropped the attached screenshot, so
+ the model looped on hallucinated ``click_element name='Edit'`` actions and
+ never grounded on the real screen.
+ """
+ manager = _FallbackChainManager()
+ # Active provider answers, but blind (text-only). It must never be
+ # dispatched while a screenshot is attached.
+ manager.primary = _StreamingBrain(
+ text='{"action": "click", "x": 5, "y": 5}', supports_vision=False,
+ )
+ ctx = make_ctx(FakeBrain())
+ ctx.brain_manager = manager
+ obs = Observation(
+ trace_id=uuid4(), timestamp_ns=time.time_ns(),
+ screenshot_path=None, screenshot_hash="x",
+ )
+ img = ImageBlock(mime="image/jpeg", data_b64="QQ==", source_hash="x")
+
+ raw = await _call_brain(
+ ctx, observation=obs, user_goal="open chrome", history_text="",
+ images_override=[img],
+ )
+
+ assert raw == '{"action": "done"}' # the vision-capable fallback answered
+ assert manager.primary.calls == 0 # blind provider never dispatched
+ assert manager.fallback.calls == 1
+
+
+async def test_call_brain_raises_when_all_providers_blind_for_screenshot() -> None:
+ """When every provider in the chain is text-only and a screenshot is
+ attached, CU must fail with a clear vision error rather than dispatch a
+ blind provider that hallucinates clicks."""
+ manager = _FallbackChainManager()
+ manager.primary = _StreamingBrain(text='{"action": "done"}', supports_vision=False)
+ manager.fallback = _StreamingBrain(text='{"action": "done"}', supports_vision=False)
+ ctx = make_ctx(FakeBrain())
+ ctx.brain_manager = manager
+ obs = Observation(
+ trace_id=uuid4(), timestamp_ns=time.time_ns(),
+ screenshot_path=None, screenshot_hash="x",
+ )
+ img = ImageBlock(mime="image/jpeg", data_b64="QQ==", source_hash="x")
+
+ with pytest.raises(CULoopError) as excinfo:
+ await _call_brain(
+ ctx, observation=obs, user_goal="g", history_text="",
+ images_override=[img],
+ )
+
+ msg = str(excinfo.value).lower()
+ assert "vision" in msg or "see the screen" in msg
+ assert manager.primary.calls == 0
+ assert manager.fallback.calls == 0
+
+
+async def test_call_brain_text_only_call_still_uses_active_provider() -> None:
+ """A CU sub-call with NO screenshot attached (e.g. a pure-text decision)
+ must NOT be vision-filtered — the active provider answers as before, even
+ if it is text-only. The skip is strictly gated on an attached image."""
+ manager = _FallbackChainManager()
+ manager.primary = _StreamingBrain(text='{"action": "done"}', supports_vision=False)
+ ctx = make_ctx(FakeBrain())
+ ctx.brain_manager = manager
+ obs = Observation(
+ trace_id=uuid4(), timestamp_ns=time.time_ns(),
+ screenshot_path=None, screenshot_hash="x",
+ )
+
+ raw = await _call_brain(
+ ctx, observation=obs, user_goal="g", history_text="",
+ )
+
+ assert raw == '{"action": "done"}'
+ assert manager.primary.calls == 1
+ assert manager.fallback.calls == 0
+
+
+async def test_call_brain_mixed_blind_and_failed_surfaces_both_in_error() -> None:
+ """A blind active provider + a vision-capable fallback that is DOWN must
+ surface BOTH facts in the failure: the fallback's real outage AND that a
+ provider was skipped for having no vision. Otherwise an operator reads only
+ "fallback down" and chases the wrong root cause, when the real story is
+ "the active brain is blind, so a fallback was hit and it happened to be
+ down". (Guards the truncation-proof blind-skip summary in the generic
+ chain-failure error.)"""
+ manager = _FallbackChainManager()
+ manager.primary = _StreamingBrain(text='{"action": "done"}', supports_vision=False)
+ manager.fallback = _StreamingBrain(
+ exc=RuntimeError("fallback down"), supports_vision=True,
+ )
+ ctx = make_ctx(FakeBrain())
+ ctx.brain_manager = manager
+ obs = Observation(
+ trace_id=uuid4(), timestamp_ns=time.time_ns(),
+ screenshot_path=None, screenshot_hash="x",
+ )
+ img = ImageBlock(mime="image/jpeg", data_b64="QQ==", source_hash="x")
+
+ with pytest.raises(CULoopError) as excinfo:
+ await _call_brain(
+ ctx, observation=obs, user_goal="g", history_text="",
+ images_override=[img],
+ )
+
+ msg = str(excinfo.value).lower()
+ assert "fallback down" in msg # the genuine fallback outage
+ assert "vision" in msg or "skipped" in msg # AND the blind-skip signal
+ assert manager.primary.calls == 0 # blind provider never dispatched
+ assert manager.fallback.calls == 1 # vision fallback was attempted
+
+
+async def test_call_brain_marks_rate_limited_provider_and_skips_next_call() -> None:
+ manager = _FallbackChainManager()
+ manager._rate_tracker = _RateTrackerProbe()
+ manager._dead_providers = set()
+ manager.primary = _StreamingBrain(exc=RuntimeError("429 Too Many Requests"))
+ manager.fallback = _StreamingBrain(text='{"action": "done"}')
+ ctx = make_ctx(FakeBrain())
+ ctx.brain_manager = manager
+ obs = Observation(
+ trace_id=uuid4(), timestamp_ns=time.time_ns(),
+ screenshot_path=None, screenshot_hash="x",
+ )
+ img = ImageBlock(mime="image/jpeg", data_b64="QQ==", source_hash="x")
+
+ raw = await _call_brain(
+ ctx, observation=obs, user_goal="g", history_text="",
+ images_override=[img],
+ )
+ assert raw == '{"action": "done"}'
+ assert manager._rate_tracker.marked == [("primary", "bad-model")]
+
+ manager.primary.calls = 0
+ raw = await _call_brain(
+ ctx, observation=obs, user_goal="g", history_text="",
+ images_override=[img],
+ )
+ assert raw == '{"action": "done"}'
+ assert manager.primary.calls == 0
+
+
+async def test_call_brain_marks_invalid_key_provider_dead() -> None:
+ manager = _FallbackChainManager()
+ manager._rate_tracker = _RateTrackerProbe()
+ manager._dead_providers = set()
+ manager.primary = _StreamingBrain(
+ exc=RuntimeError("Error code: 401 - invalid x-api-key")
+ )
+ manager.fallback = _StreamingBrain(text='{"action": "done"}')
+ ctx = make_ctx(FakeBrain())
+ ctx.brain_manager = manager
+ obs = Observation(
+ trace_id=uuid4(), timestamp_ns=time.time_ns(),
+ screenshot_path=None, screenshot_hash="x",
+ )
+ img = ImageBlock(mime="image/jpeg", data_b64="QQ==", source_hash="x")
+
+ raw = await _call_brain(
+ ctx, observation=obs, user_goal="g", history_text="",
+ images_override=[img],
+ )
+ assert raw == '{"action": "done"}'
+ assert "primary" in manager._dead_providers
+
+ manager.primary.calls = 0
+ raw = await _call_brain(
+ ctx, observation=obs, user_goal="g", history_text="",
+ images_override=[img],
+ )
+ assert raw == '{"action": "done"}'
+ assert manager.primary.calls == 0
+
+
+async def test_call_brain_does_not_mark_transient_5xx_dead() -> None:
+ manager = _FallbackChainManager()
+ manager._rate_tracker = _RateTrackerProbe()
+ manager._dead_providers = set()
+ manager.primary = _StreamingBrain(exc=RuntimeError("502 Bad Gateway"))
+ manager.fallback = _StreamingBrain(text='{"action": "done"}')
+ ctx = make_ctx(FakeBrain())
+ ctx.brain_manager = manager
+ obs = Observation(
+ trace_id=uuid4(), timestamp_ns=time.time_ns(),
+ screenshot_path=None, screenshot_hash="x",
+ )
+ img = ImageBlock(mime="image/jpeg", data_b64="QQ==", source_hash="x")
+
+ raw = await _call_brain(
+ ctx, observation=obs, user_goal="g", history_text="",
+ images_override=[img],
+ )
+ assert raw == '{"action": "done"}'
+ assert manager._dead_providers == set()
+ assert manager._rate_tracker.marked == []
+
+
def test_decide_native_batch_defined_only_once() -> None:
"""Guard against the duplicated-function merge accident: the module must
define _decide_native_batch exactly once."""
@@ -866,3 +1182,431 @@ async def test_verify_first_directive_after_state_changing_action() -> None:
_system, user = brain.executor_calls[1]
assert "VERIFY FIRST" in user
assert "open_app" in user
+
+
+# ---------------------------------------------------------------------------
+# Observe-timeout RETRY (live forensic 2026-06-22, exit 124): the Spotify CU
+# turn ran exactly ONE step and died "[cu] observe timeout (step 1)" total=3.3s.
+# The screenshot capture timed out because the shared asyncio loop was momentarily
+# saturated by a concurrent degraded-voice burst (Cartesia 402 -> Gemini-TTS 429
+# failover + double mic-open) -- NOT because the desktop was uncapturable. A
+# single transient observe timeout must NOT kill the whole mission at step 1;
+# it must retry (mirrors the existing brain-timeout retry) and only give up after
+# the cap. Provider/OS-agnostic: pure loop control, no platform code.
+# ---------------------------------------------------------------------------
+
+
+class _FlakyObserveEngine:
+ """Vision engine whose ``observe`` raises ``TimeoutError`` the first
+ ``fail_count`` calls (simulating a transient capture/loop-contention
+ timeout), then returns fresh unique observations like FakeVisionEngine."""
+
+ def __init__(self, fail_count: int) -> None:
+ self.fail_count = fail_count
+ self.calls = 0
+ self.probe_calls = 0
+ self.probe_titles: list[str] = []
+
+ def _guess_active_app_hint(self, window_title_filter: str | None = None) -> str:
+ return ""
+
+ async def observe(self, *, mode: str = "auto", cancel_token: Any = None,
+ window_title_filter: str | None = None) -> Observation:
+ idx = self.calls
+ self.calls += 1
+ if idx < self.fail_count:
+ raise TimeoutError("observe budget elapsed (test-injected)")
+ return Observation(
+ trace_id=uuid4(),
+ timestamp_ns=time.time_ns(),
+ screenshot_path=None,
+ screenshot_hash=f"hash-{idx}",
+ nodes=(),
+ window_title="",
+ active_pid=0,
+ source="screenshot_only",
+ pruning_stats={},
+ )
+
+
+async def test_single_observe_timeout_retries_and_recovers(
+ monkeypatch: pytest.MonkeyPatch,
+) -> None:
+ """One transient observe timeout must NOT end the mission -- the loop
+ retries on the next step and completes (exit 0). This is the exact
+ 2026-06-22 Spotify failure shape: it died at step 1 with exit 124."""
+ monkeypatch.setattr(loop_mod, "_OBSERVE_RETRY_BACKOFF_S", 0.0, raising=False)
+ brain = FakeBrain(script=[
+ '{"action": "open_app", "name": "chrome"}',
+ '{"action": "done"}',
+ ])
+ ctx = make_ctx(brain)
+ ctx.vision_engine = _FlakyObserveEngine(fail_count=1)
+
+ chunks = await run_loop(ctx, "oeffne chrome")
+
+ assert chunks[-1].exit_code == 0, (
+ "a single transient observe timeout killed the mission instead of retrying"
+ )
+ # The mission recovered and actually drove the brain (it did not die before
+ # the first plan).
+ assert len(brain.requests) >= 1
+
+
+async def test_persistent_observe_timeout_fails_after_cap_not_at_step_1(
+ monkeypatch: pytest.MonkeyPatch,
+) -> None:
+ """If observe keeps timing out it still fails honestly with exit 124 --
+ but only AFTER retrying past step 1, never an instant step-1 give-up."""
+ monkeypatch.setattr(loop_mod, "_OBSERVE_RETRY_BACKOFF_S", 0.0, raising=False)
+ brain = FakeBrain(script=['{"action": "done"}'])
+ ctx = make_ctx(brain)
+ # Always time out (fail_count huge).
+ ctx.vision_engine = _FlakyObserveEngine(fail_count=10_000)
+
+ chunks = await run_loop(ctx, "oeffne chrome")
+
+ assert chunks[-1].exit_code == loop_mod._TIMEOUT_EXIT_CODE
+ # It must have RETRIED before giving up -- more than one observe attempt.
+ assert ctx.vision_engine.calls >= 2, (
+ "persistent observe timeout gave up at step 1 without retrying"
+ )
+ stderr = chunks[-1].stderr
+ assert "observe timeout" in stderr
+
+
+# ---------------------------------------------------------------------------
+# Repeated-type guard (live forensic 2026-06-22, Microsoft-Store/Minecraft
+# turn): the model typed the SAME query "Minecraft" into the Store search box
+# TWICE in a row (steps 6.3 + 7.3) because it could not tell the first type had
+# landed -- "das ist ja dumm". A back-to-back identical type into a field that
+# already holds the text is a redundant no-op. Suppress the repeat (like the
+# click toggle-stop) and push the model to the NEXT step instead of mashing the
+# same query. Provider/OS-agnostic: pure loop control.
+# ---------------------------------------------------------------------------
+
+
+async def test_repeated_type_of_same_text_is_suppressed() -> None:
+ """The exact 2026-06-22 dumbness: ``type 'Minecraft'`` twice in a row. The
+ SECOND identical type must be suppressed -- the executor must run a
+ type-with-text='Minecraft' only ONCE -- and the mission still completes."""
+ brain = FakeBrain(script=[
+ '{"action": "type", "text": "Minecraft"}',
+ '{"action": "type", "text": "Minecraft"}', # redundant back-to-back repeat
+ '{"action": "done"}',
+ ])
+ ctx = make_ctx(brain)
+ chunks = await run_loop(ctx, "tippe Minecraft in die Suche")
+
+ typed = [
+ c for c in ctx.tool_executor.calls
+ if str(c[1].get("text", "")) == "Minecraft"
+ ]
+ assert len(typed) == 1, (
+ f"'Minecraft' was typed {len(typed)}x -- the back-to-back repeat must "
+ "be suppressed, not executed again"
+ )
+ assert chunks[-1].exit_code == 0
+
+
+async def test_typing_a_different_text_is_not_suppressed() -> None:
+ """The guard is precise: typing a DIFFERENT text after the first is a real
+ new action and must execute (no false positive)."""
+ brain = FakeBrain(script=[
+ '{"action": "type", "text": "Minecraft"}',
+ '{"action": "type", "text": "Roblox"}', # different query -> must run
+ '{"action": "done"}',
+ ])
+ ctx = make_ctx(brain)
+ await run_loop(ctx, "suche zwei spiele")
+
+ texts = [
+ str(c[1].get("text", "")) for c in ctx.tool_executor.calls
+ if c[1].get("text")
+ ]
+ assert "Minecraft" in texts and "Roblox" in texts, (
+ f"a distinct second type was wrongly suppressed (typed: {texts})"
+ )
+
+
+async def test_type_after_a_click_is_not_suppressed() -> None:
+ """RC#2 (Google-Flights, 2026-06-22): a click RE-FOCUSES / re-targets the
+ field, so a following type of the SAME text is a fresh retry (the first type
+ did not land in the web input), NOT a redundant back-to-back repeat. The
+ intervening click must clear the repeat-type guard so the retry executes --
+ otherwise the mission dead-ends 'in the right field but nothing typed'."""
+ brain = FakeBrain(script=[
+ '{"action": "type", "text": "Tokyo"}',
+ '{"action": "click", "x": 114, "y": 162, "target": "destination field"}',
+ '{"action": "type", "text": "Tokyo"}', # retry after re-focus -> must run
+ '{"action": "done"}',
+ ])
+ ctx = make_ctx(brain)
+ await run_loop(ctx, "tippe Tokyo in das Zielfeld")
+
+ typed = [
+ c for c in ctx.tool_executor.calls
+ if str(c[1].get("text", "")) == "Tokyo"
+ ]
+ assert len(typed) == 2, (
+ f"'Tokyo' was typed {len(typed)}x -- a re-type AFTER a re-focusing click "
+ "must NOT be suppressed; the repeat-type guard must reset on a click"
+ )
+
+
+# ---------------------------------------------------------------------------
+# RC#3 (2026-06-22): a DRAG action -- press the mouse at (x,y), move to
+# (x2,y2), release -- so the agent can rotate a map/globe, pan, or move a
+# slider. A plain click cannot do this; before this action the vocabulary had
+# no press-and-hold-move primitive at all.
+# ---------------------------------------------------------------------------
+
+
+async def test_drag_action_performs_press_move_release(monkeypatch) -> None:
+ """A drag action must reach the mouse layer with both endpoints resolved."""
+ calls: list = []
+ monkeypatch.setattr(
+ "jarvis.harness.screenshot_only_loop._perform_drag",
+ lambda *a, **k: calls.append((a, k)),
+ )
+ brain = FakeBrain(script=[
+ '{"action": "drag", "x": 500, "y": 500, "x2": 700, "y2": 300}',
+ '{"action": "done"}',
+ ])
+ ctx = make_ctx(brain)
+ chunks = await run_loop(ctx, "rotate the globe to the right")
+
+ assert len(calls) == 1, "the drag action never reached the mouse layer"
+ # 4 coordinate args (start_x, start_y, end_x, end_y) plus a duration.
+ assert len(calls[0][0]) >= 4, f"drag called with too few args: {calls[0]}"
+ assert chunks[-1].exit_code == 0
+
+
+def test_drag_is_in_the_action_vocabulary() -> None:
+ from jarvis.harness import screenshot_only_loop as loop
+
+ assert "drag" in loop._VALID_ACTIONS
+ assert "drag" in loop._SYSTEM_PROMPT # the model is told the shape exists
+
+
+# ---------------------------------------------------------------------------
+# General "no progress -> re-target" nudge (user mandate 2026-06-22: the loop
+# must GENERALLY recognise a missed target instead of mashing the same action --
+# "das war nur ein Beispiel ... ich möchte nicht dass es nur auf dieses eine
+# Beispiel bezogen ist ... unsere Mechanik ist Screenshot/Tastatur/Maus, das
+# bleibt"). The instant an action leaves the screen UNCHANGED, the loop tells
+# the model -- for ANY action type, ANY app -- that it had no effect and to
+# re-target, BEFORE the 3-strike stuck abort.
+# ---------------------------------------------------------------------------
+
+
+class _HashSeqEngine:
+ """Vision engine returning a fixed screenshot-hash sequence, to drive the
+ stall / no-progress logic deterministically."""
+
+ def __init__(self, hashes: list[str]) -> None:
+ self._hashes = hashes
+ self.calls = 0
+ self.probe_calls = 0
+ self.probe_titles: list[str] = []
+
+ def _guess_active_app_hint(self, window_title_filter: str | None = None) -> str:
+ return ""
+
+ async def observe(self, *, mode: str = "auto", cancel_token: Any = None,
+ window_title_filter: str | None = None) -> Observation:
+ idx = self.calls
+ self.calls += 1
+ h = self._hashes[min(idx, len(self._hashes) - 1)]
+ return Observation(
+ trace_id=uuid4(), timestamp_ns=time.time_ns(),
+ screenshot_path=None, screenshot_hash=h, nodes=(),
+ window_title="", active_pid=0, source="screenshot_only",
+ pruning_stats={},
+ )
+
+
+async def test_unchanged_screen_nudges_model_to_retarget() -> None:
+ """A no-op action (screen unchanged) must make the loop tell the model to
+ STOP repeating and re-target -- generically, via plain click actions (not a
+ type/app special case)."""
+ brain = FakeBrain(script=[
+ '{"action": "click", "x": 10, "y": 10}',
+ '{"action": "click", "x": 20, "y": 20}',
+ '{"action": "done"}',
+ ])
+ ctx = make_ctx(brain)
+ ctx.vision_engine = _HashSeqEngine(["A", "A", "B"]) # no change after step 1
+
+ chunks = await run_loop(ctx, "klick etwas an")
+
+ assert any(
+ "did NOT change after your last action" in req[1]
+ for req in brain.requests
+ ), "the loop never warned the model that the screen was unchanged"
+ assert chunks[-1].exit_code == 0
+
+
+async def test_no_retarget_nudge_when_screen_keeps_changing() -> None:
+ """No false nudge on a healthy mission: every step changes the screen, so
+ the model must never be told 'no visible effect'."""
+ brain = FakeBrain(script=[
+ '{"action": "click", "x": 10, "y": 10}',
+ '{"action": "click", "x": 20, "y": 20}',
+ '{"action": "done"}',
+ ])
+ ctx = make_ctx(brain)
+ ctx.vision_engine = _HashSeqEngine(["A", "B", "C"]) # always changing
+
+ await run_loop(ctx, "klick etwas an")
+
+ assert not any(
+ "did NOT change after your last action" in req[1]
+ for req in brain.requests
+ ), "the re-target nudge fired even though the screen kept changing"
+
+
+# ---------------------------------------------------------------------------
+# Elevation pause-and-resume (UAC Secure Desktop, 2026-06-23). When a launched
+# app raises a privilege prompt mid-mission, a non-elevated process can neither
+# see (BitBlt -> black/raise) nor click (UIPI) the Secure Desktop. The loop must
+# PAUSE for the human's one confirmation click and resume, instead of aborting
+# blind with the misleading exit 1 "couldn't see the screen". The
+# privileged-prompt probe is injected here (no real Win32).
+# ---------------------------------------------------------------------------
+
+
+class _ObserveFailsThenWorks:
+ """VisionEngine whose observe() raises CULoopError (the Secure-Desktop
+ BitBlt failure) on the first ``fail_times`` calls, then yields frames."""
+
+ def __init__(self, fail_times: int) -> None:
+ self.fail_times = fail_times
+ self.calls = 0
+
+ def _guess_active_app_hint(self, window_title_filter: str | None = None) -> str:
+ return ""
+
+ async def observe(self, *, mode: str = "auto", cancel_token: Any = None,
+ window_title_filter: str | None = None) -> Observation:
+ n = self.calls
+ self.calls += 1
+ if n < self.fail_times:
+ raise CULoopError(
+ "screenshot capture returned no frame (transient GDI failure)"
+ )
+ return Observation(
+ trace_id=uuid4(), timestamp_ns=time.time_ns(),
+ screenshot_path=None, screenshot_hash=f"hash-{n}",
+ nodes=(), window_title="", active_pid=0,
+ source="screenshot_only", pruning_stats={},
+ )
+
+
+class _RecordingBus:
+ def __init__(self) -> None:
+ self.events: list[Any] = []
+
+ async def publish(self, event: Any) -> None:
+ self.events.append(event)
+
+
+def _patch_prompt_probe(monkeypatch: pytest.MonkeyPatch, seq: Any) -> None:
+ """Patch privileged_prompt_active to a constant bool or a per-call sequence
+ of bools (the last value repeats)."""
+ if isinstance(seq, bool):
+ monkeypatch.setattr(
+ "jarvis.platform.privileged_prompt.privileged_prompt_active",
+ lambda: seq,
+ )
+ return
+ values = list(seq)
+ state = {"i": 0}
+
+ def _probe() -> bool:
+ v = values[min(state["i"], len(values) - 1)]
+ state["i"] += 1
+ return v
+
+ monkeypatch.setattr(
+ "jarvis.platform.privileged_prompt.privileged_prompt_active", _probe
+ )
+
+
+def _fast_elevation(monkeypatch: pytest.MonkeyPatch) -> None:
+ monkeypatch.setattr(loop_mod, "_ELEVATION_WAIT_TIMEOUT_S", 0.05)
+ monkeypatch.setattr(loop_mod, "_ELEVATION_POLL_S", 0.005)
+
+
+async def test_observe_failure_during_uac_pauses_and_resumes(
+ monkeypatch: pytest.MonkeyPatch, _fast_elevation: None,
+) -> None:
+ # Mode A: observe raises (Secure Desktop), prompt is up then cleared → the
+ # mission RESUMES and completes (exit 0), never the blind exit 1.
+ _patch_prompt_probe(monkeypatch, [True, False])
+ bus = _RecordingBus()
+ brain = FakeBrain(script=['{"action": "done"}'])
+ ctx = make_ctx(brain, bus=bus)
+ ctx.vision_engine = _ObserveFailsThenWorks(fail_times=1)
+
+ chunks = await run_loop(ctx, "Kannst du eine Aufnahme starten?")
+
+ assert chunks[-1].exit_code == 0
+ from jarvis.voice.action_phrases import action_phrase
+ texts = [getattr(e, "text", "") for e in bus.events]
+ assert action_phrase("cu_awaiting_elevation", "de") in texts
+
+
+async def test_uac_never_confirmed_aborts_with_elevation_exit_not_no_view(
+ monkeypatch: pytest.MonkeyPatch, _fast_elevation: None,
+) -> None:
+ # Mode A: observe raises, prompt stays up forever → exit 9 (needs
+ # elevation), NEVER exit 1 (the misleading "couldn't see the screen").
+ _patch_prompt_probe(monkeypatch, True)
+ brain = FakeBrain(script=['{"action": "done"}'])
+ ctx = make_ctx(brain)
+ ctx.vision_engine = _ObserveFailsThenWorks(fail_times=99)
+
+ chunks = await run_loop(ctx, "open OBS and record")
+
+ assert chunks[-1].exit_code == loop_mod._ELEVATION_EXIT_CODE
+ assert chunks[-1].exit_code != loop_mod._OBSERVE_EXIT_CODE
+
+
+async def test_observe_failure_without_uac_still_aborts_exit_1(
+ monkeypatch: pytest.MonkeyPatch,
+) -> None:
+ # No regression: observe raises and NO prompt is up → the original generic
+ # observe failure (exit 1). The probe must never invent a prompt.
+ _patch_prompt_probe(monkeypatch, False)
+ brain = FakeBrain(script=['{"action": "done"}'])
+ ctx = make_ctx(brain)
+ ctx.vision_engine = _ObserveFailsThenWorks(fail_times=99)
+
+ chunks = await run_loop(ctx, "do something on screen")
+
+ assert chunks[-1].exit_code == loop_mod._OBSERVE_EXIT_CODE
+
+
+async def test_uac_detected_before_brain_call_skips_blind_step(
+ monkeypatch: pytest.MonkeyPatch, _fast_elevation: None,
+) -> None:
+ # Mode B: observe SUCCEEDS (e.g. a black frame) but the prompt is up — the
+ # loop must detect it BEFORE the brain call and pause, never feed the model a
+ # blind frame. After it clears, the mission resumes and completes; the model
+ # is consulted only once (the paused step made no brain call).
+ _patch_prompt_probe(monkeypatch, [True, False, False, False])
+ bus = _RecordingBus()
+ brain = FakeBrain(script=['{"action": "done"}'])
+ ctx = make_ctx(brain, bus=bus)
+
+ chunks = await run_loop(ctx, "open OBS and record")
+
+ assert chunks[-1].exit_code == 0
+ assert len(brain.requests) == 1
+ # The goal is English, so the spoken ask resolves to English (Output-Language
+ # doctrine: never a hardcoded locale).
+ from jarvis.voice.action_phrases import action_phrase
+ texts = [getattr(e, "text", "") for e in bus.events]
+ assert action_phrase("cu_awaiting_elevation", "en") in texts
diff --git a/tests/unit/harness/test_cu_runaway_guards.py b/tests/unit/harness/test_cu_runaway_guards.py
index ba17662d94..3fe283d02c 100644
--- a/tests/unit/harness/test_cu_runaway_guards.py
+++ b/tests/unit/harness/test_cu_runaway_guards.py
@@ -397,3 +397,97 @@ async def test_no_progress_message_blames_dead_target_when_nothing_suppressed()
assert "no progress" in final.stderr
assert "off-screen" in final.stderr
assert "suppressed" not in final.stderr
+
+
+# ---------------------------------------------------------------------------
+# No-progress abort: verify BEFORE failing (user forensic 2026-06-20)
+# ---------------------------------------------------------------------------
+# A fully-loaded page is static, so the very thing a SUCCESS looks like —
+# three byte-identical screenshots — is indistinguishable, by hash alone,
+# from a stuck session. Live forensic: "open x.com and the Angela Merkel
+# profile" actually reached the open profile page, but the frozen screen
+# tripped the no-progress guard and the mission was reported FAILED. Before
+# aborting, the loop must run the done-verifier ONCE against the current
+# screenshot: a proven goal ends as a verified success, not a stuck failure.
+
+
+def _verify_at_freeze_handler(*, verdict_done: bool) -> Any:
+ """Brain shim: trivial plan, repeated click, and a scripted completion
+ verdict whenever a STRICT-judge prompt arrives (its unique marker is the
+ verdict format ``"done": true|false``, which never appears in the
+ executor system prompt)."""
+
+ proof = (
+ "the @AngelaMerkel profile page is open on screen"
+ if verdict_done
+ else "only an empty page frame is visible, no profile loaded"
+ )
+
+ def handler(system: str, user: str) -> str:
+ if "desktop-automation planner" in system:
+ return '{"plan": []}'
+ if '"done": true|false' in system: # any completion judge
+ return json.dumps({"done": verdict_done, "proof": proof})
+ return json.dumps(
+ {"action": "click", "x": 500, "y": 500, "target": "page"}
+ )
+
+ return handler
+
+
+async def test_no_progress_at_an_achieved_goal_verifies_as_success() -> None:
+ # The fix: when the screen freezes but the verifier confirms the goal IS
+ # achieved on the current screenshot, the mission ends as a clean success
+ # (exit 0 with the proof), NOT a "3 identical screenshots" failure.
+ brain = FakeBrain(_verify_at_freeze_handler(verdict_done=True))
+ ctx = make_ctx_with_engine(brain, _SequencedVisionEngine(distinct=2))
+
+ chunks = await run_loop(ctx, "navigate to the angela merkel profile on x.com")
+
+ final = chunks[-1]
+ assert final.exit_code == 0, (
+ f"a frozen screen AT the achieved goal must verify as success, not "
+ f"abort as stuck; got exit {final.exit_code}: {final.stderr!r}"
+ )
+ assert "no progress" not in final.stderr
+ assert "done" in final.stdout.lower()
+
+
+async def test_no_progress_still_fails_when_verifier_rejects_the_goal() -> None:
+ # The other half of the contract: a frozen screen where the goal is NOT
+ # achieved (verifier says done:false) must still end as an honest failure.
+ # The verify-before-fail gate may only RESCUE a real success, never paper
+ # over a genuine stall.
+ brain = FakeBrain(_verify_at_freeze_handler(verdict_done=False))
+ ctx = make_ctx_with_engine(brain, _SequencedVisionEngine(distinct=2))
+
+ chunks = await run_loop(ctx, "navigate to the angela merkel profile on x.com")
+
+ final = chunks[-1]
+ assert final.exit_code == loop_mod._FAIL_EXIT_CODE
+ assert "no progress" in final.stderr
+
+
+async def test_no_progress_does_not_rescue_a_frozen_play_goal(
+ monkeypatch: pytest.MonkeyPatch,
+) -> None:
+ # Safety guard for the verify-before-fail gate: a GENUINE play/submit stall
+ # must NOT be falsely rescued. For a media goal (matches _VERIFY_GOAL_RE)
+ # the done-verifier uses the two-frame MOTION check; on a frozen screen
+ # Frame A and Frame B are byte-identical, so it short-circuits to
+ # (False, "screen frozen ...") WITHOUT ever asking the judge. So even though
+ # this handler would answer the judge "done", that judge call never happens
+ # and the mission still ends as an honest failure. This pins the structural
+ # reason a real play-stall cannot be rescued by the new gate.
+ monkeypatch.setattr(loop_mod, "_VERIFY_FRAME_GAP_S", 0.0, raising=False)
+ brain = FakeBrain(_verify_at_freeze_handler(verdict_done=True))
+ ctx = make_ctx_with_engine(brain, _SequencedVisionEngine(distinct=2))
+
+ chunks = await run_loop(ctx, "play the angela merkel video on x.com")
+
+ final = chunks[-1]
+ assert final.exit_code == loop_mod._FAIL_EXIT_CODE, (
+ f"a frozen PLAY goal must stay a failure (two-frame motion gate), got "
+ f"exit {final.exit_code}: {final.stdout!r}"
+ )
+ assert "no progress" in final.stderr
diff --git a/tests/unit/harness/test_cu_uia_snap.py b/tests/unit/harness/test_cu_uia_snap.py
new file mode 100644
index 0000000000..67160aa2cf
--- /dev/null
+++ b/tests/unit/harness/test_cu_uia_snap.py
@@ -0,0 +1,185 @@
+"""Phase 2: UIA snap fallback on a missed pixel click.
+
+When the post-click verification detects no visible change, the loop snaps to the
+nearest clickable UIA element (by bounding box) and clicks its center BEFORE the
+expensive LLM refine retry — fixing the "guessed a pixel, missed the button by a
+few px" thrash. Falls through to the existing refine when no element is near or
+no UI-tree backend is available (headless / Null source).
+
+Unit-level: the UI-tree source and the raw click dispatch are monkeypatched, so
+these are deterministic and exercise the pure picker + the snap helper directly.
+"""
+from __future__ import annotations
+
+from types import SimpleNamespace
+
+from jarvis.harness import screenshot_only_loop as sol
+from jarvis.harness.computer_use_context import ComputerUseContext
+
+
+def _ctx() -> ComputerUseContext:
+ return ComputerUseContext(
+ vision_engine=None, brain_manager=None, tool_executor=object(), tools={}
+ )
+
+
+def _node(x, y, w, h, *, enabled=True, name="n"):
+ return SimpleNamespace(bounds=(x, y, w, h), enabled=enabled, name=name)
+
+
+# --- pure picker ------------------------------------------------------------
+
+
+def test_pick_snap_node_prefers_smallest_containing():
+ nodes = [_node(0, 0, 100, 100, name="big"), _node(40, 40, 20, 20, name="small")]
+ picked = sol._pick_snap_node(nodes, 50, 50, 80)
+ assert picked.name == "small"
+
+
+def test_pick_snap_node_nearest_when_not_contained():
+ nodes = [_node(100, 100, 20, 20, name="near")] # center (110,110)
+ picked = sol._pick_snap_node(nodes, 130, 130, 80)
+ assert picked is not None
+ assert picked.name == "near"
+
+
+def test_pick_snap_node_none_when_too_far():
+ nodes = [_node(0, 0, 10, 10, name="far")] # center (5,5)
+ assert sol._pick_snap_node(nodes, 500, 500, 80) is None
+
+
+def test_pick_snap_node_skips_disabled():
+ nodes = [_node(40, 40, 20, 20, enabled=False, name="disabled")]
+ assert sol._pick_snap_node(nodes, 50, 50, 80) is None
+
+
+def test_pick_snap_node_skips_zero_area():
+ nodes = [_node(40, 40, 0, 0, name="zero")]
+ assert sol._pick_snap_node(nodes, 40, 40, 80) is None
+
+
+def test_pick_snap_node_empty():
+ assert sol._pick_snap_node([], 10, 10, 80) is None
+
+
+# --- snap helper ------------------------------------------------------------
+
+
+class _FakeSource:
+ def __init__(self, nodes):
+ self._nodes = nodes
+
+ async def observe(self, **_kw):
+ return SimpleNamespace(nodes=self._nodes)
+
+
+async def test_uia_snap_clicks_element_center(monkeypatch):
+ monkeypatch.setattr(
+ "jarvis.vision.tree_factory.make_ui_tree_source",
+ lambda: _FakeSource([_node(40, 40, 20, 20, name="OK button")]),
+ )
+ clicks: list = []
+
+ async def fake_dispatch(executor, tool, cx, cy, tid):
+ clicks.append((cx, cy))
+ return True, "clicked"
+
+ monkeypatch.setattr(sol, "_dispatch_raw_click", fake_dispatch)
+ res = await sol._uia_snap_click(
+ _ctx(), executor=object(), tool=object(), x=50, y=50, trace_id=None
+ )
+ assert res is not None
+ ok, msg = res
+ assert ok is True
+ assert clicks == [(50, 50)] # center of (40,40,20,20)
+ assert "OK button" in msg
+
+
+async def test_uia_snap_none_when_no_node(monkeypatch):
+ monkeypatch.setattr(
+ "jarvis.vision.tree_factory.make_ui_tree_source", lambda: _FakeSource([])
+ )
+ res = await sol._uia_snap_click(
+ _ctx(), executor=object(), tool=object(), x=5, y=5, trace_id=None
+ )
+ assert res is None
+
+
+async def test_uia_snap_respects_disable_flag(monkeypatch):
+ ctx = _ctx()
+ ctx.uia_click_fallback = False
+ called: list = []
+ monkeypatch.setattr(
+ "jarvis.vision.tree_factory.make_ui_tree_source",
+ lambda: called.append(1) or _FakeSource([]),
+ )
+ res = await sol._uia_snap_click(
+ ctx, executor=object(), tool=object(), x=5, y=5, trace_id=None
+ )
+ assert res is None
+ assert called == [] # source never even built
+
+
+async def test_uia_snap_none_when_observe_raises(monkeypatch):
+ class _Boom:
+ async def observe(self, **_kw):
+ raise RuntimeError("COM dead")
+
+ monkeypatch.setattr("jarvis.vision.tree_factory.make_ui_tree_source", lambda: _Boom())
+ res = await sol._uia_snap_click(
+ _ctx(), executor=object(), tool=object(), x=5, y=5, trace_id=None
+ )
+ assert res is None
+
+
+# --- integration: snap fires inside _click_with_refine on a verified miss ----
+
+
+class _RecordingExecutor:
+ def __init__(self):
+ self.clicks: list = []
+
+ async def execute(self, tool, args, *, user_utterance="", trace_id=None):
+ self.clicks.append((args["x"], args["y"]))
+ return SimpleNamespace(success=True, output="clicked", error="")
+
+
+class _FakeClickTool:
+ name = "click"
+ risk_tier = "monitor"
+ schema = {"type": "object", "properties": {"x": {}, "y": {}}}
+
+
+class _FakeObs:
+ screenshot_path = "X:/fake/shot.jpg"
+ screenshot_hash = "h"
+ trace_id = None
+
+
+async def test_snap_fires_inside_click_with_refine_on_miss(monkeypatch):
+ # pre == post (same bytes) -> verified miss -> the snap path runs before the
+ # LLM refine and clicks the nearest UIA element's center.
+ monkeypatch.setattr(sol, "_grab_region_jpeg", lambda bbox: b"same")
+ monkeypatch.setattr(sol, "_CLICK_VERIFY_SETTLE_S", 0.0)
+ monkeypatch.setattr(
+ "jarvis.vision.tree_factory.make_ui_tree_source",
+ lambda: _FakeSource([_node(460, 460, 40, 40, name="Submit")]), # center (480,480)
+ )
+ ctx = ComputerUseContext(
+ vision_engine=None,
+ brain_manager=None,
+ tool_executor=_RecordingExecutor(),
+ tools={"click": _FakeClickTool()},
+ verify_after_each_step=True,
+ )
+ ok, msg = await sol._execute_action(
+ {"action": "click", "x": 500, "y": 500, "target": "submit"},
+ ctx,
+ trace_id=None,
+ user_goal="x",
+ monitor_geom=(0, 0, 1000, 1000),
+ observation=_FakeObs(),
+ )
+ assert ctx.tool_executor.clicks == [(500, 500), (480, 480)]
+ assert "UIA-snapped" in msg
+ assert "Submit" in msg
diff --git a/tests/unit/harness/test_screenshot_only_loop.py b/tests/unit/harness/test_screenshot_only_loop.py
index f9de9d891b..682daced7f 100644
--- a/tests/unit/harness/test_screenshot_only_loop.py
+++ b/tests/unit/harness/test_screenshot_only_loop.py
@@ -519,6 +519,124 @@ class _DummyObs:
window_title = ""
+# ---------------------------------------------------------------------------
+# _call_brain early-stop wiring: the per-step action call must stop consuming
+# the provider stream the moment a complete JSON action is parseable, while the
+# default (verifier/plan) path still drains the whole stream.
+# ---------------------------------------------------------------------------
+
+
+class _StreamBrain:
+ """Production-path fake: yields a BrainDelta stream and records how many
+ deltas were actually consumed (so an early stop is observable)."""
+
+ supports_vision = True
+
+ def __init__(self, deltas, consumed) -> None:
+ self._deltas = deltas
+ self._consumed = consumed
+
+ async def complete(self, req): # noqa: ANN001
+ for i, d in enumerate(self._deltas):
+ self._consumed.append(i)
+ yield d
+
+
+class _StreamManager:
+ """Minimal BrainManager stand-in driving the production (_get_brain) path —
+ deliberately has NO complete_text, so _call_brain uses aggregate()."""
+
+ def __init__(self, brain) -> None:
+ self._brain = brain
+ self._dead_providers: set = set()
+ self._rate_tracker = None
+
+ def _build_fallback_chain(self, tier): # noqa: ANN001
+ return [("fake", "m")]
+
+ def _get_brain(self, provider, model): # noqa: ANN001
+ return self._brain
+
+ def _fast_model(self, provider): # noqa: ANN001
+ return "m"
+
+
+class _StreamCtx:
+ def __init__(self, brain) -> None:
+ self.brain_manager = brain
+ self.per_step_timeout_s = 5.0
+
+
+def _action_stream_deltas():
+ from jarvis.core.protocols import BrainDelta
+
+ return [
+ BrainDelta(content='{"action": '),
+ BrainDelta(content='"done"}'),
+ BrainDelta(content=" rambling tail the model kept generating"),
+ BrainDelta(finish_reason="stop"),
+ ]
+
+
+def test_call_brain_early_stops_on_complete_json_action() -> None:
+ import json as _json
+
+ from jarvis.harness.screenshot_only_loop import _call_brain
+
+ consumed: list[int] = []
+ brain = _StreamBrain(_action_stream_deltas(), consumed)
+ ctx = _StreamCtx(_StreamManager(brain))
+ text = asyncio.run(
+ _call_brain(
+ ctx,
+ observation=_DummyObs(),
+ user_goal="x",
+ history_text="",
+ early_stop_json=True,
+ )
+ )
+ assert _json.loads(text)["action"] == "done"
+ assert consumed == [0, 1] # tail + finish delta never consumed
+
+
+def test_call_brain_default_drains_whole_stream() -> None:
+ from jarvis.harness.screenshot_only_loop import _call_brain
+
+ consumed: list[int] = []
+ brain = _StreamBrain(_action_stream_deltas(), consumed)
+ ctx = _StreamCtx(_StreamManager(brain))
+ text = asyncio.run(
+ _call_brain(
+ ctx,
+ observation=_DummyObs(),
+ user_goal="x",
+ history_text="",
+ )
+ )
+ # Default (verifier) path is unchanged: the entire stream is read.
+ assert consumed == [0, 1, 2, 3]
+ assert "rambling tail" in text
+
+
+def test_make_plan_early_stops_at_complete_json() -> None:
+ """The planner call (max 512 out tokens) also early-stops at the plan JSON."""
+ from jarvis.core.protocols import BrainDelta
+ from jarvis.harness.screenshot_only_loop import _make_plan
+
+ consumed: list[int] = []
+ deltas = [
+ BrainDelta(content='{"plan": [{"intent":"open Spotify","success":"win"}]'),
+ BrainDelta(content="}"),
+ BrainDelta(content=" rambling tail after the plan object"),
+ BrainDelta(finish_reason="stop"),
+ ]
+ brain = _StreamBrain(deltas, consumed)
+ ctx = _StreamCtx(_StreamManager(brain))
+ plan = asyncio.run(_make_plan(ctx, observation=_DummyObs(), user_goal="x"))
+ assert plan and plan[0]["intent"] == "open Spotify"
+ assert consumed == [0, 1] # tail never consumed
+
+
# ---------------------------------------------------------------------------
# key action (BUG-CU-NO-PLAN): "press Enter" must dispatch to the hotkey tool
# with a keys list -- without it, search flows could never submit.
diff --git a/tests/unit/overlay/test_drop_bridge.py b/tests/unit/overlay/test_drop_bridge.py
new file mode 100644
index 0000000000..77d476acf9
--- /dev/null
+++ b/tests/unit/overlay/test_drop_bridge.py
@@ -0,0 +1,41 @@
+"""Process-global overlay→app drop bridge.
+
+The Tk overlay runs in a daemon thread and must not know about the asyncio loop
+or the brain. It calls ``dispatch_drop`` (from the Tk thread); the desktop bridge
+registers the real handler via ``set_drop_handler``. Decoupling, no constructor
+threading through the fragile GUI layers.
+"""
+from __future__ import annotations
+
+from jarvis.overlay.drop_bridge import (
+ dispatch_drop,
+ set_drop_handler,
+)
+
+
+def teardown_function() -> None:
+ set_drop_handler(None) # never leak a handler across tests
+
+
+def test_dispatch_calls_registered_handler() -> None:
+ seen: list[tuple] = []
+ set_drop_handler(lambda paths, text: seen.append((paths, text)))
+
+ handled = dispatch_drop(["C:/a.txt"], "")
+
+ assert handled is True
+ assert seen == [(["C:/a.txt"], "")]
+
+
+def test_dispatch_without_handler_is_safe_noop() -> None:
+ set_drop_handler(None)
+ assert dispatch_drop(["C:/a.txt"], "") is False
+
+
+def test_handler_exception_is_swallowed() -> None:
+ def _boom(paths, text):
+ raise RuntimeError("handler blew up")
+
+ set_drop_handler(_boom)
+ # Must not propagate — a Tk-thread callback crashing would wedge the overlay.
+ assert dispatch_drop([], "some text") is True
diff --git a/tests/unit/overlay/test_drop_target.py b/tests/unit/overlay/test_drop_target.py
new file mode 100644
index 0000000000..4414d020ff
--- /dev/null
+++ b/tests/unit/overlay/test_drop_target.py
@@ -0,0 +1,50 @@
+"""Cross-platform overlay DropTarget seam (files/text dropped on the bar/mascot).
+
+GUI-free tests: the TkDND path parser is pure, and the factory must degrade to a
+no-op (never raise) when ``tkinterdnd2`` / the ``tkdnd`` binary is absent — the
+web dock still carries the feature on every OS, so the overlay extra is gated.
+See docs/superpowers/specs/2026-06-21-dragdrop-files-into-context-design.md.
+"""
+from __future__ import annotations
+
+from jarvis.overlay.drop_target import (
+ NullDropTarget,
+ _parse_dnd_files,
+ make_drop_target,
+)
+
+
+def test_parse_single_plain_path() -> None:
+ assert _parse_dnd_files("C:/Users/a/file.txt") == ["C:/Users/a/file.txt"]
+
+
+def test_parse_brace_wrapped_path_with_spaces() -> None:
+ # TkDND wraps a path containing spaces in braces.
+ assert _parse_dnd_files("{C:/Users/a b/file name.txt}") == [
+ "C:/Users/a b/file name.txt"
+ ]
+
+
+def test_parse_mixed_multiple_paths() -> None:
+ data = "{C:/a b/one.txt} C:/c/two.png {D:/x y/three.pdf}"
+ assert _parse_dnd_files(data) == [
+ "C:/a b/one.txt",
+ "C:/c/two.png",
+ "D:/x y/three.pdf",
+ ]
+
+
+def test_parse_empty_is_empty_list() -> None:
+ assert _parse_dnd_files("") == []
+ assert _parse_dnd_files(" ") == []
+
+
+def test_factory_returns_a_drop_target_and_never_raises() -> None:
+ dt = make_drop_target()
+ assert hasattr(dt, "register")
+
+
+def test_null_drop_target_register_is_a_safe_noop() -> None:
+ null = NullDropTarget()
+ # Registering against a dummy "widget" must not raise and reports no-op.
+ assert null.register(object(), lambda paths, text: None) is False
diff --git a/tests/unit/overlay/test_overlay_drop_to_brain.py b/tests/unit/overlay/test_overlay_drop_to_brain.py
new file mode 100644
index 0000000000..e9e7956001
--- /dev/null
+++ b/tests/unit/overlay/test_overlay_drop_to_brain.py
@@ -0,0 +1,104 @@
+"""End-to-end (GUI-free) proof of the OVERLAY (bar/mascot) drop → brain context.
+
+The bar's tkdnd ``<<Drop>>`` handler calls ``drop_bridge.dispatch_drop(paths, text)``
+(OS delivery of that event is proven separately on Windows + Linux). This test
+proves the rest of the chain exactly as ``desktop_app`` wires it: dispatch_drop →
+the registered ``_on_overlay_drop`` handler → ``ingest_drop`` → the brain's
+SILENT context → and that the user's NEXT real turn actually uses it. No Tk, no
+cursor — pure wiring.
+"""
+from __future__ import annotations
+
+import asyncio
+from collections.abc import AsyncIterator
+from uuid import uuid4
+
+import pytest
+
+from jarvis.brain.drop_context import ingest_drop, items_from_paths
+from jarvis.brain.manager import BrainManager
+from jarvis.brain.streaming import StreamingAggregate
+from jarvis.core.bus import EventBus
+from jarvis.core.config import JarvisConfig
+from jarvis.core.protocols import BrainDelta, BrainRequest
+from jarvis.overlay import drop_bridge
+
+
+class _FakeBrain:
+ name = "fake"
+ context_window = 8192
+ supports_tools = True
+ supports_vision = True
+
+ async def complete(self, req: BrainRequest) -> AsyncIterator[BrainDelta]:
+ yield BrainDelta(content="ok")
+ yield BrainDelta(finish_reason="stop")
+
+
+class _RecordingDispatcher:
+ def __init__(self) -> None:
+ self.calls: list[dict] = []
+
+ async def dispatch(self, user_text, *, images=(), history=None, **_kwargs):
+ self.calls.append({"history": history})
+ agg = StreamingAggregate()
+ agg.text = "reply"
+ agg.finish_reason = "stop"
+ return agg
+
+
+def _manager() -> tuple[BrainManager, _RecordingDispatcher]:
+ cfg = JarvisConfig()
+ cfg.brain.primary = "fake"
+ m = BrainManager(config=cfg, bus=EventBus(), tools={})
+ rec = _RecordingDispatcher()
+ m._build_fallback_chain = lambda _l: [("fake", "fake-model")] # type: ignore[method-assign]
+ m._get_brain = lambda _n, _mo: _FakeBrain() # type: ignore[method-assign]
+ m._build_dispatcher = lambda _b, *, tools_override=None: rec # type: ignore[method-assign]
+ return m, rec
+
+
+def teardown_function() -> None:
+ drop_bridge.set_drop_handler(None)
+
+
+async def test_bar_drop_reaches_brain_and_next_turn_uses_it(tmp_path) -> None:
+ manager, rec = _manager()
+ loop = asyncio.get_running_loop()
+ done = asyncio.Event()
+
+ # Wire the overlay drop EXACTLY as jarvis/ui/desktop_app.py does.
+ def _on_overlay_drop(paths: list[str], text: str) -> None:
+ items = items_from_paths(paths) if paths else []
+ dragged = (text or "").strip() or None
+ if not items and dragged is None:
+ return
+
+ async def _run() -> None:
+ await ingest_drop(
+ brain=manager, thread_id="default", items=items, dragged_text=dragged
+ )
+ done.set()
+
+ asyncio.run_coroutine_threadsafe(_run(), loop)
+
+ drop_bridge.set_drop_handler(_on_overlay_drop)
+
+ # A real dropped file, as the bar would hand over a path.
+ f = tmp_path / "report.txt"
+ f.write_text("the bar marker is BAR_TOKEN_777, remember it")
+
+ # This is precisely what the bar's tkdnd <<Drop>> handler calls.
+ handled = drop_bridge.dispatch_drop([str(f)], "")
+ assert handled is True
+ await asyncio.wait_for(done.wait(), timeout=5)
+
+ # The dropped content is now SILENT context on the brain (no turn happened).
+ assert rec.calls == []
+ assert any("BAR_TOKEN_777" in str(m.content) for m in manager._history)
+
+ # The user's NEXT real turn (voice or chat → generate) USES it.
+ await manager.generate("what is the marker?", trace_id=uuid4(), use_history=True)
+ hist = " ".join(str(getattr(m, "content", "")) for m in (rec.calls[0]["history"] or []))
+ assert "BAR_TOKEN_777" in hist
diff --git a/tests/unit/platform/test_privileged_prompt.py b/tests/unit/platform/test_privileged_prompt.py
new file mode 100644
index 0000000000..ce463de782
--- /dev/null
+++ b/tests/unit/platform/test_privileged_prompt.py
@@ -0,0 +1,80 @@
+"""Tests for the runtime privileged-prompt probe (UAC Secure-Desktop & co.).
+
+These cover the platform dispatch + defensive contract WITHOUT touching the real
+Win32 path (headless-CI doctrine, mirrors test_system_cursor.py): the actual
+``OpenInputDesktop`` probe is injected via the ``probe`` seam, and the live
+Windows path is verified on a real desktop separately.
+"""
+
+from __future__ import annotations
+
+import pytest
+
+from jarvis.platform import privileged_prompt
+
+
[email protected](autouse=True)
+def _display_present(monkeypatch):
+ """Default every test to a host that HAS a display, so the headless guard
+ does not short-circuit the dispatch under test. The headless case has its
+ own explicit test that overrides this."""
+ monkeypatch.setattr(
+ "jarvis.platform.probes.display_present", lambda: True
+ )
+
+
+def test_active_when_probe_reports_true():
+ assert privileged_prompt.privileged_prompt_active(probe=lambda: True) is True
+
+
+def test_inactive_when_probe_reports_false():
+ assert privileged_prompt.privileged_prompt_active(probe=lambda: False) is False
+
+
+def test_inactive_when_probe_reports_unknown_none():
+ # None = "could not determine" — must NEVER claim a prompt is up.
+ assert privileged_prompt.privileged_prompt_active(probe=lambda: None) is False
+
+
+def test_inactive_when_probe_raises():
+ def _boom():
+ raise OSError("win32 call failed")
+
+ assert privileged_prompt.privileged_prompt_active(probe=_boom) is False
+
+
+def test_inactive_on_platform_without_runtime_probe(monkeypatch):
+ # macOS/Linux have no reliable dependency-free runtime probe yet → False
+ # (the blank-frame heuristic at the capture site covers them).
+ monkeypatch.setattr(
+ "jarvis.platform.privileged_prompt.detect_platform", lambda: "linux"
+ )
+ assert privileged_prompt.privileged_prompt_active() is False
+
+
+def test_inactive_when_headless_even_if_probe_true(monkeypatch):
+ # No display → graceful no-op regardless of what a probe would say.
+ monkeypatch.setattr(
+ "jarvis.platform.probes.display_present", lambda: False
+ )
+ assert privileged_prompt.privileged_prompt_active(probe=lambda: True) is False
+
+
+def test_windows_dispatch_selects_secure_desktop_probe(monkeypatch):
+ # On Windows with no override, the real Secure-Desktop probe is selected.
+ monkeypatch.setattr(
+ "jarvis.platform.privileged_prompt.detect_platform", lambda: "win32"
+ )
+ sentinel = object()
+ captured = {}
+
+ def _fake_secure_desktop():
+ captured["called"] = True
+ return True
+
+ monkeypatch.setattr(
+ privileged_prompt, "_windows_secure_desktop_active", _fake_secure_desktop
+ )
+ assert privileged_prompt.privileged_prompt_active() is True
+ assert captured.get("called") is True
+ del sentinel
diff --git a/tests/unit/platform/test_window_state.py b/tests/unit/platform/test_window_state.py
new file mode 100644
index 0000000000..98b317c265
--- /dev/null
+++ b/tests/unit/platform/test_window_state.py
@@ -0,0 +1,208 @@
+"""Phase 0: jarvis/platform/window_state.py — reusable, cross-platform window
+enumeration / focus / already-running detection behind the platform seam.
+
+Seam-level only: the platform is forced via detect_platform/probes and the
+ctypes/osascript/wmctrl backends are faked or monkeypatched — this proves the
+dispatch + parsing + matching logic, NOT that real OS APIs behave as assumed on
+real hardware (SIGNOFF-LOG honesty).
+"""
+from __future__ import annotations
+
+import subprocess
+import types
+
+import pytest
+
+from jarvis.platform import window_state as ws
+from jarvis.platform.window_state import WindowInfo
+
+
+def _cp(returncode: int, stdout: str = "", stderr: str = ""):
+ return types.SimpleNamespace(returncode=returncode, stdout=stdout, stderr=stderr)
+
+
+# --- WindowInfo basics ------------------------------------------------------
+
+
+def test_windowinfo_defaults():
+ w = WindowInfo("Some Title")
+ assert w.title == "Some Title"
+ assert w.minimized is False
+ assert w.handle is None
+
+
+# --- is_app_running (pure matching over list_windows) -----------------------
+
+
+def test_is_app_running_matches_title_substring(monkeypatch):
+ monkeypatch.setattr(
+ ws, "list_windows",
+ lambda: [WindowInfo("OBS 30.0.0 - Profil: Stream"), WindowInfo("Chrome")],
+ )
+ hit = ws.is_app_running("obs")
+ assert hit is not None
+ assert "OBS" in hit.title
+
+
+def test_is_app_running_returns_none_when_no_match(monkeypatch):
+ monkeypatch.setattr(ws, "list_windows", lambda: [WindowInfo("New Tab - Google Chrome")])
+ assert ws.is_app_running("obs") is None
+
+
+def test_is_app_running_alias_calc_to_calculator(monkeypatch):
+ monkeypatch.setattr(ws, "list_windows", lambda: [WindowInfo("Calculator")])
+ assert ws.is_app_running("calc") is not None
+
+
+def test_is_app_running_short_token_is_not_fuzzy_matched(monkeypatch):
+ # A 1-2 char app token must not match arbitrary titles (false-positive guard:
+ # wrongly focusing instead of launching is the worse error).
+ monkeypatch.setattr(ws, "list_windows", lambda: [WindowInfo("Notepad")])
+ assert ws.is_app_running("n") is None
+
+
+def test_is_app_running_keeps_handle_for_focus(monkeypatch):
+ monkeypatch.setattr(ws, "list_windows", lambda: [WindowInfo("OBS 30", handle=4242)])
+ hit = ws.is_app_running("obs")
+ assert hit is not None
+ assert hit.handle == 4242
+
+
+def test_is_app_running_accepts_exe_path_basename(monkeypatch):
+ # app_name may arrive as a path/exe; the basename stem is used as the token.
+ monkeypatch.setattr(ws, "list_windows", lambda: [WindowInfo("Discord")])
+ assert ws.is_app_running(r"C:\Users\x\AppData\Local\Discord\Discord.exe") is not None
+
+
+def test_is_app_running_empty_name_is_none(monkeypatch):
+ monkeypatch.setattr(ws, "list_windows", lambda: [WindowInfo("Anything")])
+ assert ws.is_app_running("") is None
+ assert ws.is_app_running(" ") is None
+
+
+# --- focus_window dispatch --------------------------------------------------
+
+
+def test_focus_window_dispatches_windows(monkeypatch):
+ monkeypatch.setattr(ws, "detect_platform", lambda: "win32")
+ monkeypatch.setattr(ws, "_find_and_focus_windows", lambda t: (True, "Notepad"))
+ assert ws.focus_window("Notepad") == (True, "Notepad")
+
+
+def test_focus_window_dispatches_macos(monkeypatch):
+ monkeypatch.setattr(ws, "detect_platform", lambda: "darwin")
+ monkeypatch.setattr(ws, "_find_and_focus_macos", lambda t: (True, "My Editor"))
+ assert ws.focus_window("Editor") == (True, "My Editor")
+
+
+def test_focus_window_wayland_degrades(monkeypatch):
+ monkeypatch.setattr(ws, "detect_platform", lambda: "linux")
+ monkeypatch.setattr(ws, "is_wayland", lambda: True)
+ ok, msg = ws.focus_window("Editor")
+ assert ok is False
+ assert "Wayland" in msg
+
+
+def test_focus_window_headless_linux_degrades(monkeypatch):
+ monkeypatch.setattr(ws, "detect_platform", lambda: "linux")
+ monkeypatch.setattr(ws, "is_wayland", lambda: False)
+ monkeypatch.setattr(ws, "display_present", lambda: False)
+ ok, msg = ws.focus_window("Editor")
+ assert ok is False
+ assert "display" in msg.lower()
+
+
+def test_focus_window_never_raises(monkeypatch):
+ monkeypatch.setattr(ws, "detect_platform", lambda: "win32")
+
+ def boom(_t):
+ raise RuntimeError("ctypes blew up")
+
+ monkeypatch.setattr(ws, "_find_and_focus_windows", boom)
+ ok, msg = ws.focus_window("X")
+ assert ok is False
+ assert "X" in msg or "failed" in msg.lower() or msg
+
+
+# --- list_windows dispatch + parsing ----------------------------------------
+
+
+def test_list_windows_windows_dispatch(monkeypatch):
+ monkeypatch.setattr(ws, "detect_platform", lambda: "win32")
+ monkeypatch.setattr(
+ ws, "_list_windows_windows",
+ lambda: [WindowInfo("OBS 30", minimized=True), WindowInfo("Chrome")],
+ )
+ titles = [w.title for w in ws.list_windows()]
+ assert titles == ["OBS 30", "Chrome"]
+ assert ws.list_windows()[0].minimized is True
+
+
+def test_list_windows_linux_parses_wmctrl(monkeypatch):
+ monkeypatch.setattr(ws, "detect_platform", lambda: "linux")
+ monkeypatch.setattr(ws, "is_wayland", lambda: False)
+ monkeypatch.setattr(ws, "display_present", lambda: True)
+ monkeypatch.setattr("shutil.which", lambda n: f"/usr/bin/{n}")
+ monkeypatch.setattr(
+ subprocess, "run",
+ lambda *a, **k: _cp(0, stdout="0x01 0 host My Editor — file.py\n0x02 0 host Terminal\n"),
+ )
+ titles = [w.title for w in ws.list_windows()]
+ assert "My Editor — file.py" in titles
+ assert "Terminal" in titles
+
+
+def test_list_windows_macos_parses_osascript(monkeypatch):
+ monkeypatch.setattr(ws, "detect_platform", lambda: "darwin")
+ monkeypatch.setattr("shutil.which", lambda n: f"/usr/bin/{n}")
+ # newline-separated window titles, one per line
+ monkeypatch.setattr(subprocess, "run", lambda *a, **k: _cp(0, stdout="OBS\nSafari — Apple\n"))
+ titles = [w.title for w in ws.list_windows()]
+ assert "OBS" in titles
+ assert "Safari — Apple" in titles
+
+
+def test_list_windows_headless_linux_is_empty(monkeypatch):
+ monkeypatch.setattr(ws, "detect_platform", lambda: "linux")
+ monkeypatch.setattr(ws, "is_wayland", lambda: False)
+ monkeypatch.setattr(ws, "display_present", lambda: False)
+ assert ws.list_windows() == []
+
+
+def test_list_windows_never_raises(monkeypatch):
+ monkeypatch.setattr(ws, "detect_platform", lambda: "win32")
+
+ def boom():
+ raise RuntimeError("enum blew up")
+
+ monkeypatch.setattr(ws, "_list_windows_windows", boom)
+ assert ws.list_windows() == []
+
+
+# --- get_foreground_title ---------------------------------------------------
+
+
+def test_get_foreground_title_never_raises(monkeypatch):
+ monkeypatch.setattr(ws, "detect_platform", lambda: "win32")
+
+ def boom():
+ raise RuntimeError("foreground blew up")
+
+ monkeypatch.setattr(ws, "_foreground_title_windows", boom)
+ assert ws.get_foreground_title() == ""
+
+
+def test_get_foreground_title_macos_empty_without_tool(monkeypatch):
+ monkeypatch.setattr(ws, "detect_platform", lambda: "darwin")
+ monkeypatch.setattr("shutil.which", lambda n: None)
+ assert ws.get_foreground_title() == ""
+
+
+# --- real smoke on the host platform (non-deterministic, just must not crash)
+
+
+def test_list_windows_smoke_does_not_crash():
+ # On the real host this exercises the actual backend; result shape only.
+ result = ws.list_windows()
+ assert isinstance(result, list)
+ assert all(isinstance(w, WindowInfo) for w in result)
diff --git a/tests/unit/plugins/brain/test_antigravity_brain.py b/tests/unit/plugins/brain/test_antigravity_brain.py
index 0eb94a02c0..d8c8b0208c 100644
--- a/tests/unit/plugins/brain/test_antigravity_brain.py
+++ b/tests/unit/plugins/brain/test_antigravity_brain.py
@@ -44,6 +44,18 @@ def _system_with_standing_instructions() -> str:
)
+def _system_with_empty_standing_instructions() -> str:
+ return (
+ "STATIC PERSONA BLOCK\n\n"
+ "USER PREFERENCES & STANDING INSTRUCTIONS (from Jarvis.md):\n"
+ "No active user preferences are currently set in Jarvis.md. "
+ "Ignore any earlier Jarvis.md instructions from previous turns.\n\n"
+ "END USER PREFERENCES & STANDING INSTRUCTIONS\n\n"
+ "REGISTRIERTE WERKZEUGE (vollstaendige Liste):\n"
+ "- search_web\n"
+ )
+
+
def test_cli_prompt_includes_standing_instructions_without_heavy_router_prompt():
req = BrainRequest(
messages=(BrainMessage(role="user", content="Was ist das wertvollste Unternehmen?"),),
@@ -83,6 +95,25 @@ def test_cli_prompt_carries_reply_language_directive():
assert "Always start every sentence with schef." in prompt
+def test_cli_prompt_puts_current_empty_state_after_stale_history():
+ req = BrainRequest(
+ messages=(
+ BrainMessage(role="user", content="Wasketup"),
+ BrainMessage(role="assistant", content="schef, alles laeuft."),
+ BrainMessage(role="user", content="Du musst das nicht mehr sagen."),
+ ),
+ system=_system_with_empty_standing_instructions(),
+ )
+
+ prompt = _build_cli_prompt(req)
+
+ assert "CURRENT JARVIS.MD STATE" in prompt
+ assert "No active user preferences are currently set" in prompt
+ assert "do not continue or imitate" in prompt
+ assert prompt.rfind("No active user preferences") > prompt.rfind("Assistant: schef")
+ assert "REGISTRIERTE WERKZEUGE" not in prompt
+
+
def test_parse_json_response():
assert _parse_cli_answer('{"response": "OK"}') == "OK"
diff --git a/tests/unit/plugins/brain/test_cli_prompt_context.py b/tests/unit/plugins/brain/test_cli_prompt_context.py
index c8f8fe2858..fd4810edda 100644
--- a/tests/unit/plugins/brain/test_cli_prompt_context.py
+++ b/tests/unit/plugins/brain/test_cli_prompt_context.py
@@ -13,6 +13,7 @@ from __future__ import annotations
from jarvis.plugins.brain.cli_prompt_context import (
extract_reply_language_directive,
+ render_cli_standing_instructions,
)
_MANDATORY = (
@@ -32,6 +33,15 @@ def _system_with_directive() -> str:
)
+def _empty_state_block() -> str:
+ return (
+ "USER PREFERENCES & STANDING INSTRUCTIONS (from Jarvis.md):\n"
+ "No active user preferences are currently set in Jarvis.md. "
+ "Ignore any earlier Jarvis.md instructions from previous turns.\n\n"
+ "END USER PREFERENCES & STANDING INSTRUCTIONS"
+ )
+
+
def test_extracts_trailing_mandatory_directive() -> None:
assert extract_reply_language_directive(_system_with_directive()) == _MANDATORY
@@ -57,3 +67,11 @@ def test_takes_last_occurrence() -> None:
# the real directive is the one BrainManager appends last.
text = "Some text mentioning REPLY LANGUAGE in passing.\n\n" + _MANDATORY
assert extract_reply_language_directive(text) == _MANDATORY
+
+
+def test_renders_empty_state_as_current_state_not_binding_preferences() -> None:
+ rendered = render_cli_standing_instructions(_empty_state_block())
+ assert "CURRENT JARVIS.MD STATE" in rendered
+ assert "No active user preferences are currently set" in rendered
+ assert "do not continue or imitate" in rendered
+ assert "Apply these as binding output-style preferences" not in rendered
diff --git a/tests/unit/plugins/stt/test_fwhisper_robust_load.py b/tests/unit/plugins/stt/test_fwhisper_robust_load.py
new file mode 100644
index 0000000000..f2b209e694
--- /dev/null
+++ b/tests/unit/plugins/stt/test_fwhisper_robust_load.py
@@ -0,0 +1,115 @@
+"""Robust local-Whisper model load: cross-platform compute_type + model-name
+normalization.
+
+Two boot landmines this guards against:
+ 1. A drifted `[stt].model = "whisper-large-v3"` is NOT a valid faster-whisper
+ id (the bare id is "large-v3"); loading it raises. A clean boot reading the
+ TOML would crash the "Hey Josef" wake path.
+ 2. `compute_type="int8_float16"` is CUDA-only. On a CPU / headless VPS the load
+ raises — violating the cloud-first "must boot on python:3.11-slim" rule.
+
+The provider now normalizes known-bad aliases and self-heals to a CPU-safe combo
+when the configured device/compute_type fails to load.
+"""
+from __future__ import annotations
+
+from jarvis.plugins.stt import fwhisper
+from jarvis.plugins.stt.fwhisper import (
+ FasterWhisperProvider,
+ _cpu_safe_compute_type,
+ _normalize_model_name,
+)
+
+
+def test_normalize_strips_invalid_whisper_prefix() -> None:
+ assert _normalize_model_name("whisper-large-v3") == "large-v3"
+ assert _normalize_model_name("whisper-tiny") == "tiny"
+
+
+def test_normalize_passes_valid_ids_through() -> None:
+ for m in ("large-v3", "large-v3-turbo", "distil-large-v3", "base", "small"):
+ assert _normalize_model_name(m) == m
+
+
+def test_normalize_leaves_hf_repo_ids_untouched() -> None:
+ # An org/name HF repo id is valid and may legitimately contain 'whisper-'.
+ assert (
+ _normalize_model_name("Systran/faster-whisper-large-v3")
+ == "Systran/faster-whisper-large-v3"
+ )
+
+
+def test_cpu_safe_compute_type_downgrades_cuda_only() -> None:
+ assert _cpu_safe_compute_type("int8_float16") == "int8"
+ assert _cpu_safe_compute_type("float16") == "int8"
+
+
+def test_cpu_safe_compute_type_keeps_cpu_compatible() -> None:
+ for ct in ("int8", "float32", "int16"):
+ assert _cpu_safe_compute_type(ct) == ct
+
+
+def test_ensure_model_falls_back_to_cpu_safe_on_failure(monkeypatch) -> None:
+ calls: list[tuple[str, str, str]] = []
+
+ def fake_factory(model_name: str, device: str, compute_type: str):
+ calls.append((model_name, device, compute_type))
+ # Simulate a no-CUDA host: cuda / *_float16 unsupported.
+ if device == "cuda" or compute_type in ("float16", "int8_float16"):
+ raise ValueError("CUDA driver not found")
+ return object()
+
+ monkeypatch.setattr(fwhisper, "_new_whisper_model", fake_factory)
+
+ p = FasterWhisperProvider(
+ model="whisper-large-v3", device="cuda", compute_type="int8_float16"
+ )
+ p._ensure_model()
+
+ assert p._model is not None
+ # First attempt: normalized name + the configured cuda/int8_float16 combo.
+ assert calls[0] == ("large-v3", "cuda", "int8_float16")
+ # Self-healed fallback: cpu + a cpu-safe compute type.
+ assert calls[-1] == ("large-v3", "cpu", "int8")
+
+
+def test_ensure_model_uses_configured_combo_when_it_works(monkeypatch) -> None:
+ calls: list[tuple[str, str, str]] = []
+
+ def fake_factory(model_name: str, device: str, compute_type: str):
+ calls.append((model_name, device, compute_type))
+ return object()
+
+ monkeypatch.setattr(fwhisper, "_new_whisper_model", fake_factory)
+
+ p = FasterWhisperProvider(
+ model="large-v3-turbo", device="cuda", compute_type="int8_float16"
+ )
+ p._ensure_model()
+
+ assert len(calls) == 1 # worked first try → no fallback
+ assert calls[0] == ("large-v3-turbo", "cuda", "int8_float16")
+
+
+def test_ensure_model_does_not_retry_when_already_cpu_safe(monkeypatch) -> None:
+ # A genuinely bad model name on an already-cpu-safe combo must raise once,
+ # not pointlessly retry the identical combo (which would re-hit the network).
+ calls: list[tuple[str, str, str]] = []
+
+ def fake_factory(model_name: str, device: str, compute_type: str):
+ calls.append((model_name, device, compute_type))
+ raise ValueError("model not found")
+
+ monkeypatch.setattr(fwhisper, "_new_whisper_model", fake_factory)
+
+ p = FasterWhisperProvider(
+ model="nonexistent-model", device="cpu", compute_type="int8"
+ )
+ try:
+ p._ensure_model()
+ raised = False
+ except ValueError:
+ raised = True
+
+ assert raised
+ assert len(calls) == 1 # no second attempt — the combo was already cpu-safe
diff --git a/tests/unit/plugins/stt/test_wake_whisper_build.py b/tests/unit/plugins/stt/test_wake_whisper_build.py
new file mode 100644
index 0000000000..0ccc31cddd
--- /dev/null
+++ b/tests/unit/plugins/stt/test_wake_whisper_build.py
@@ -0,0 +1,80 @@
+"""The local wake-match Whisper must be small + CPU, independent of the
+utterance STT model.
+
+Measured on the maintainer's Blackwell GPU (RTX 5070 Ti): loading the utterance
+model on CUDA cost ~71 s (CTranslate2 kernel JIT for the new arch), while the
+SAME model on CPU loads in 3.45 s and a `base` model on CPU in 0.45 s. The local
+Whisper only powers wake-phrase transcript matching + the live-preview probe
+(both latency-tolerant; utterance STT is separate — cloud or `stt.model`), so it
+loads a small model on CPU by default. This collapses Phase-A warm-up from ~71 s
+to a few seconds.
+"""
+from __future__ import annotations
+
+from jarvis.core.config import STTConfig
+from jarvis.plugins.stt import build_wake_whisper
+from jarvis.plugins.stt.fwhisper import FasterWhisperProvider
+
+
+def test_stt_config_wake_defaults_small_and_cpu() -> None:
+ cfg = STTConfig()
+ assert cfg.wake_model == "base"
+ assert cfg.wake_device == "cpu"
+ assert cfg.wake_compute_type == "int8"
+
+
+def test_build_wake_whisper_uses_wake_fields_not_utterance_model() -> None:
+ cfg = STTConfig(
+ model="large-v3-turbo",
+ device="cuda",
+ compute_type="int8_float16",
+ wake_model="base",
+ wake_device="cpu",
+ wake_compute_type="int8",
+ )
+ p = build_wake_whisper(cfg)
+
+ assert isinstance(p, FasterWhisperProvider)
+ # The wake instance must NOT inherit the heavy utterance model / cuda.
+ assert p._model_name == "base"
+ assert p._device == "cpu"
+ assert p._compute_type == "int8"
+
+
+def test_build_wake_whisper_passes_language() -> None:
+ p = build_wake_whisper(STTConfig(), language="de")
+ assert p._language == "de"
+
+
+def test_build_wake_whisper_tolerates_missing_wake_fields() -> None:
+ # A config object predating the wake_* fields falls back to small/cpu/int8.
+ class _Bare:
+ pass
+
+ p = build_wake_whisper(_Bare())
+ assert p._model_name == "base"
+ assert p._device == "cpu"
+ assert p._compute_type == "int8"
+
+
+def test_build_wake_whisper_biases_prompt_with_custom_phrase() -> None:
+ # A custom wake word ("Hey Ruben") routes to the stt_match path, where the
+ # small base/cpu model otherwise mis-hears the proper noun. Empirical
+ # 2026-06-23 on the user's real wake WAVs: WITHOUT the bias the live model
+ # heard "Hey Ruben" as "Space"/"Ego"/"Herum" -> 2-13% recall (effectively a
+ # dead wake word); WITH the spoken phrase as initial_prompt -> 83% recall.
+ # The earlier hallucination concern is held off by the strict ["hey","ruben"]
+ # matcher (a stray "Ruben" in speech is not an adjacent "hey ruben") plus the
+ # no_speech_prob/RMS gates: false-wake stayed ~0% on real speech. So the bias
+ # is re-enabled on this path. It is scoped to the custom phrase only -- the
+ # OWW/"Hey Jarvis" paths pass no phrase and stay unbiased (test below).
+ p = build_wake_whisper(STTConfig(), language="de", wake_phrase="Hey Ruben")
+ assert p._initial_prompt == "Hey Ruben"
+
+
+def test_build_wake_whisper_default_has_no_prompt_bias() -> None:
+ p = build_wake_whisper(STTConfig(), language="de")
+ assert p._initial_prompt is None
+
+ p_blank = build_wake_whisper(STTConfig(), language="de", wake_phrase=" ")
+ assert p_blank._initial_prompt is None
diff --git a/tests/unit/plugins/tool/test_app_control_tools.py b/tests/unit/plugins/tool/test_app_control_tools.py
index a021f70415..370b42ac50 100644
--- a/tests/unit/plugins/tool/test_app_control_tools.py
+++ b/tests/unit/plugins/tool/test_app_control_tools.py
@@ -167,6 +167,85 @@ async def test_switch_wrong_tier(configured_keys):
assert res["error_kind"] == "wrong_tier"
+async def test_switch_antigravity_rejected_as_main_brain(configured_keys):
+ from jarvis.brain.app_control import apply_provider_switch
+
+ fake = FakeBrainManager(active="grok")
+ runtime_refs.set_brain_manager(fake)
+
+ res = await apply_provider_switch(
+ "brain", "antigravity", cfg=make_cfg(), persist=False,
+ )
+
+ assert res["ok"] is False
+ assert res["error_kind"] == "subagent_only"
+ assert fake.switch_calls == []
+
+
+async def test_switch_codex_rejected_as_main_brain(configured_keys):
+ from jarvis.brain.app_control import apply_provider_switch
+
+ fake = FakeBrainManager(active="grok")
+ runtime_refs.set_brain_manager(fake)
+
+ res = await apply_provider_switch(
+ "brain", "codex", cfg=make_cfg(), persist=False,
+ )
+
+ assert res["ok"] is False
+ assert res["error_kind"] == "subagent_only"
+ assert fake.switch_calls == []
+
+
+async def test_switch_antigravity_allowed_as_subagent(monkeypatch, no_keys):
+ from jarvis.brain.app_control import apply_provider_switch
+
+ class _Status:
+ connected = True
+
+ class _FakeGoogleCliAuthService:
+ def status(self):
+ return _Status()
+
+ monkeypatch.setattr(
+ "jarvis.google_cli.auth_service.GoogleCliAuthService",
+ _FakeGoogleCliAuthService,
+ )
+
+ cfg = make_cfg(sub="gemini")
+ res = await apply_provider_switch(
+ "subagent", "antigravity", cfg=cfg, persist=False,
+ )
+
+ assert res["ok"] is True
+ assert res["tier"] == "subagent"
+ assert res["new_provider"] == "antigravity"
+ assert cfg.brain.sub_jarvis.provider == "antigravity"
+
+
+async def test_switch_codex_allowed_as_subagent(monkeypatch, no_keys):
+ from jarvis.brain.app_control import apply_provider_switch
+
+ class _Status:
+ connected = True
+
+ class _FakeCodexAuthService:
+ def status(self):
+ return _Status()
+
+ monkeypatch.setattr("jarvis.codex_auth.CodexAuthService", _FakeCodexAuthService)
+
+ cfg = make_cfg(sub="gemini")
+ res = await apply_provider_switch(
+ "subagent", "openai-codex", cfg=cfg, persist=False,
+ )
+
+ assert res["ok"] is True
+ assert res["tier"] == "subagent"
+ assert res["new_provider"] == "openai-codex"
+ assert cfg.brain.sub_jarvis.provider == "openai-codex"
+
+
async def test_switch_unknown_tier(configured_keys):
from jarvis.brain.app_control import apply_provider_switch
diff --git a/tests/unit/plugins/tool/test_app_resolver.py b/tests/unit/plugins/tool/test_app_resolver.py
index fc7df73aca..c8680093b0 100644
--- a/tests/unit/plugins/tool/test_app_resolver.py
+++ b/tests/unit/plugins/tool/test_app_resolver.py
@@ -32,6 +32,30 @@ def test_windows_terminal_aliases_resolve_to_wt_executable(name: str) -> None:
assert resolve_app_launch_target(name) == LaunchTarget("executable", "wt")
[email protected]("name", ["Microsoft Store", "microsoft store", "windows store", "store"])
+def test_microsoft_store_resolves_to_uwp_protocol(
+ name: str, monkeypatch: pytest.MonkeyPatch,
+) -> None:
+ """The Microsoft Store is a UWP app: no .exe on PATH or App Paths, only the
+ ``ms-windows-store:`` protocol URI. Live 2026-06-22: open_app('Microsoft
+ Store') was rejected as "not found", forcing the computer-use loop into a
+ clumsy Windows-search detour. It must resolve to the protocol so os.startfile
+ launches the Store directly."""
+ monkeypatch.setattr(app_resolver, "detect_platform", lambda: "win32")
+ assert resolve_app_launch_target(name) == LaunchTarget(
+ "startfile", "ms-windows-store:"
+ )
+
+
+def test_microsoft_store_is_in_the_windows_app_whitelist() -> None:
+ """The plausibility gate must accept 'Microsoft Store' (else open_app rejects
+ it before the resolver ever runs)."""
+ from jarvis.plugins.tool.open_app import _KNOWN_APPS_WIN
+
+ assert "microsoft store" in _KNOWN_APPS_WIN
+ assert "store" in _KNOWN_APPS_WIN
+
+
@pytest.mark.parametrize("name", ["powershell", "pwsh", "cmd"])
def test_shell_names_remain_direct_executable_targets(name: str) -> None:
assert resolve_app_launch_target(name) == LaunchTarget("executable", name)
diff --git a/tests/unit/plugins/tool/test_gmail_rest.py b/tests/unit/plugins/tool/test_gmail_rest.py
index 127fe74714..521049562b 100644
--- a/tests/unit/plugins/tool/test_gmail_rest.py
+++ b/tests/unit/plugins/tool/test_gmail_rest.py
@@ -150,5 +150,38 @@ async def test_non_401_error_is_not_retried():
def test_tool_contract_shape():
tool = GmailRestTool()
assert tool.name == "gmail"
- assert tool.risk_tier == "ask" # send is consequential
+ assert tool.risk_tier == "ask" # conservative static fallback; send is consequential
assert "schema" in dir(tool)
+
+
+# ----------------------------------------------------------------------
+# Per-action risk (forensic 2026-06-19, session dc533e39): "Was habe ich
+# heute auf dem Plan?" → morning-routine → gmail action=list_messages
+# (read) was forced through the ask-tier confirm and Jarvis spoke "Soll
+# ich die E-Mail wirklich senden?". Only send_message is consequential;
+# reads must stay safe so the morning briefing can check unread mail
+# without a spurious send confirmation.
+# ----------------------------------------------------------------------
+
+
+def test_risk_tier_for_args_read_actions_are_safe():
+ tool = GmailRestTool(access_token_provider=lambda: "x")
+ assert tool.risk_tier_for_args({"action": "list_messages"}) == "safe"
+ assert tool.risk_tier_for_args({"action": "get_message"}) == "safe"
+
+
+def test_risk_tier_for_args_send_is_ask():
+ tool = GmailRestTool(access_token_provider=lambda: "x")
+ assert tool.risk_tier_for_args({"action": "send_message"}) == "ask"
+
+
+def test_risk_tier_for_args_default_action_is_safe():
+ # No action key → defaults to list_messages (a read) → safe.
+ tool = GmailRestTool(access_token_provider=lambda: "x")
+ assert tool.risk_tier_for_args({}) == "safe"
+
+
+def test_risk_tier_for_args_unknown_action_is_conservative():
+ # An unrecognised action stays conservative (ask), never silently safe.
+ tool = GmailRestTool(access_token_provider=lambda: "x")
+ assert tool.risk_tier_for_args({"action": "purge_everything"}) == "ask"
diff --git a/tests/unit/plugins/tool/test_open_app_reuse.py b/tests/unit/plugins/tool/test_open_app_reuse.py
new file mode 100644
index 0000000000..f836169ebd
--- /dev/null
+++ b/tests/unit/plugins/tool/test_open_app_reuse.py
@@ -0,0 +1,102 @@
+"""Phase 1b: open_app already-running short-circuit.
+
+When the requested app is already open, focus its window instead of launching a
+second instance (saves a Computer-Use step — the OBS-already-in-the-taskbar
+case). Conservative: never for URLs/paths or multi-instance apps, never when
+reuse is disabled, and a focus failure falls through to a normal launch.
+
+Seam-level: window_state.is_app_running / focus_window are monkeypatched, and the
+launch is stubbed, so the test is deterministic regardless of the host's open
+windows.
+"""
+from __future__ import annotations
+
+import types
+from uuid import uuid4
+
+from jarvis.core.protocols import ExecutionContext
+from jarvis.platform.window_state import WindowInfo
+from jarvis.plugins.tool import open_app as oa
+from jarvis.plugins.tool.open_app import OpenAppTool
+
+
+def _ctx() -> ExecutionContext:
+ return ExecutionContext(
+ trace_id=uuid4(), user_utterance="t", config={}, memory_read=None, approved_by="auto"
+ )
+
+
+def _stub_launch(monkeypatch) -> list:
+ """Stub resolve + Popen so no real process starts; return the Popen call log."""
+ calls: list = []
+ monkeypatch.setattr(
+ oa, "resolve_app_launch_target",
+ lambda n: types.SimpleNamespace(kind="executable", value=r"C:\fake\obs.exe"),
+ )
+ monkeypatch.setattr(oa.subprocess, "Popen", lambda *a, **k: calls.append((a, k)))
+ return calls
+
+
+async def test_focuses_when_already_running(monkeypatch):
+ calls = _stub_launch(monkeypatch)
+ monkeypatch.setattr(oa.window_state, "is_app_running", lambda n: WindowInfo("OBS 30.0.0"))
+ focused: list = []
+ monkeypatch.setattr(
+ oa.window_state, "focus_window", lambda t: (focused.append(t), (True, t))[1]
+ )
+ res = await OpenAppTool().execute({"app_name": "obs"}, _ctx())
+ assert res.success is True
+ assert "already running" in (res.output or "").lower()
+ assert calls == [] # never launched a second instance
+ assert focused # focus was attempted
+
+
+async def test_launches_when_not_running(monkeypatch):
+ calls = _stub_launch(monkeypatch)
+ monkeypatch.setattr(oa.window_state, "is_app_running", lambda n: None)
+ res = await OpenAppTool().execute({"app_name": "obs"}, _ctx())
+ assert res.success is True
+ assert "Gestartet" in (res.output or "")
+ assert len(calls) == 1
+
+
+async def test_multi_instance_app_always_launches(monkeypatch):
+ calls = _stub_launch(monkeypatch)
+ monkeypatch.setattr(oa.window_state, "is_app_running", lambda n: WindowInfo("File Explorer"))
+ focused: list = []
+ monkeypatch.setattr(
+ oa.window_state, "focus_window", lambda t: (focused.append(t), (True, t))[1]
+ )
+ res = await OpenAppTool().execute({"app_name": "explorer"}, _ctx())
+ assert res.success is True
+ assert len(calls) == 1 # explorer is multi-instance -> launch anyway
+ assert focused == [] # short-circuit skipped, never focused
+
+
+async def test_reuse_existing_false_always_launches(monkeypatch):
+ calls = _stub_launch(monkeypatch)
+ monkeypatch.setattr(oa.window_state, "is_app_running", lambda n: WindowInfo("OBS 30"))
+ res = await OpenAppTool().execute({"app_name": "obs", "reuse_existing": False}, _ctx())
+ assert res.success is True
+ assert len(calls) == 1
+
+
+async def test_focus_failure_falls_through_to_launch(monkeypatch):
+ calls = _stub_launch(monkeypatch)
+ monkeypatch.setattr(oa.window_state, "is_app_running", lambda n: WindowInfo("OBS 30"))
+ monkeypatch.setattr(oa.window_state, "focus_window", lambda t: (False, "lock timeout"))
+ res = await OpenAppTool().execute({"app_name": "obs"}, _ctx())
+ assert res.success is True
+ assert "Gestartet" in (res.output or "") # launched after focus failed
+ assert len(calls) == 1
+
+
+async def test_url_is_not_short_circuited(monkeypatch):
+ calls = _stub_launch(monkeypatch)
+ seen: list = []
+ monkeypatch.setattr(
+ oa.window_state, "is_app_running", lambda n: (seen.append(n), WindowInfo("x"))[1]
+ )
+ res = await OpenAppTool().execute({"app_name": "https://example.com"}, _ctx())
+ assert res.success is True
+ assert seen == [] # URL must not be treated as an app to focus
diff --git a/tests/unit/plugins/tool/test_spawn_worker_ack.py b/tests/unit/plugins/tool/test_spawn_worker_ack.py
index c7b29e064f..8fabbc33b6 100644
--- a/tests/unit/plugins/tool/test_spawn_worker_ack.py
+++ b/tests/unit/plugins/tool/test_spawn_worker_ack.py
@@ -259,6 +259,158 @@ async def test_no_announcement_contains_the_banned_template_wording() -> None:
await _drain_background_tasks()
+async def test_resolved_output_language_drives_mission_and_ack() -> None:
+ """The turn's resolved ``ctx.config['output_language']`` — not a hardcoded
+ 'de' and not the STT tag — decides BOTH the mission dispatch language and
+ the spoken ACK language.
+
+ Forensic 2026-06-20 ("Mask it up"): an English turn (STT mis-tagged
+ German) resolved to output_language='en', but the mission was dispatched
+ language='de' and the ACK pulled the German fallback pool. The mission-fail
+ phrase then came out German, and the German ACK text was spoken by the
+ Cartesia *English* voice = "British accent on a German sentence". Both
+ spoken surfaces must follow the one authoritative resolver.
+ """
+ mgr = _FakeMissionManager()
+ announcer = _FakeAnnouncer()
+ tool = SpawnWorkerTool(bus=EventBus(), manager=mgr, announcer=announcer)
+
+ ctx = ExecutionContext(
+ trace_id=uuid4(),
+ user_utterance="Mask it up",
+ config={"output_language": "en"},
+ memory_read=None,
+ )
+ # No "language" arg from the brain — exactly the live "Mask it up" turn.
+ await tool.execute({"utterance": "Mask it up", "action": ""}, ctx)
+ await _drain_background_tasks()
+
+ assert announcer.calls[0]["language"] == "en"
+ assert mgr.dispatch_calls[0]["language"] == "en"
+
+
+async def test_ctx_output_language_overrides_stale_brain_arg() -> None:
+ """The authoritative resolved language wins over a conflicting tool-call arg.
+
+ The brain's ``language`` argument is a guess (it can echo a wrong STT tag);
+ ``ctx.config['output_language']`` is the single resolver's verdict and must
+ win, so no layer re-derives the language on its own terms (Runtime Output
+ Language doctrine).
+ """
+ mgr = _FakeMissionManager()
+ announcer = _FakeAnnouncer()
+ tool = SpawnWorkerTool(bus=EventBus(), manager=mgr, announcer=announcer)
+
+ ctx = ExecutionContext(
+ trace_id=uuid4(),
+ user_utterance="Mask it up",
+ config={"output_language": "en"},
+ memory_read=None,
+ )
+ await tool.execute(
+ {"utterance": "Mask it up", "action": "", "language": "de"}, ctx
+ )
+ await _drain_background_tasks()
+
+ assert announcer.calls[0]["language"] == "en"
+ assert mgr.dispatch_calls[0]["language"] == "en"
+
+
+async def test_spanish_turn_caps_mission_language_to_de_but_acks_in_es() -> None:
+ """An "es" turn must not thread "es" into the de/en-only mission contract.
+
+ MissionManager.dispatch + the mission voice readback are de/en only, so the
+ mission language is capped to "de" for a Spanish turn (the spoken ACK itself
+ is still Spanish via the composer). Threading "es" into dispatch would
+ violate its Literal["de","en"] contract and the completion readback has no
+ "es" template.
+ """
+ mgr = _FakeMissionManager()
+ announcer = _FakeAnnouncer()
+ tool = SpawnWorkerTool(bus=EventBus(), manager=mgr, announcer=announcer)
+ utter = "Abre mi Gmail y busca facturas nuevas"
+ ctx = ExecutionContext(
+ trace_id=uuid4(),
+ user_utterance=utter,
+ config={"output_language": "es"},
+ memory_read=None,
+ )
+ await tool.execute({"utterance": utter, "action": "revisa el Gmail"}, ctx)
+ await _drain_background_tasks()
+
+ assert announcer.calls[0]["language"] == "es"
+ assert mgr.dispatch_calls[0]["language"] == "de"
+
+
+async def test_context_bleed_utterance_falls_back_to_verbatim_turn() -> None:
+ """The worker must carry the REAL spoken turn, never an echoed old task.
+
+ Forensic 2026-06-20: under a full provider collapse the turn ran on a
+ degraded fallback model fed a long prior context. For the spoken turn
+ "Mask it up" it called spawn_worker carrying a PREVIOUS request
+ ("emigrate to Melbourne") in both the utterance and action args — the
+ worker then built an entirely foreign task. ctx.user_utterance is the
+ ground truth for this turn; when the brain's utterance shares no content
+ word with it, the verbatim turn wins and the (equally bled) action/target
+ are dropped.
+ """
+ mgr = _FakeMissionManager()
+ tool = SpawnWorkerTool(bus=EventBus(), manager=mgr, announcer=_FakeAnnouncer())
+ ctx = ExecutionContext(
+ trace_id=uuid4(),
+ user_utterance="Mask it up",
+ config={"output_language": "en"},
+ memory_read=None,
+ )
+ await tool.execute(
+ {
+ "utterance": "research everything I need to emigrate to Melbourne",
+ "action": "prepare a detailed Melbourne emigration report",
+ "target": "Melbourne emigration checklist",
+ },
+ ctx,
+ )
+ await _drain_background_tasks()
+
+ prompt = mgr.dispatch_calls[0]["prompt"]
+ assert "Mask it up" in prompt
+ assert "Melbourne" not in prompt
+
+
+async def test_related_interpretation_is_preserved() -> None:
+ """A genuine interpretation of the SAME turn keeps the brain's action.
+
+ Guard against over-correction: when the brain's utterance shares content
+ with the spoken turn, it is a real interpretation (possibly enriched), so
+ the action/target must survive — only an unrelated (bled) call is dropped.
+ """
+ mgr = _FakeMissionManager()
+ tool = SpawnWorkerTool(bus=EventBus(), manager=mgr, announcer=_FakeAnnouncer())
+ ctx = ExecutionContext(
+ trace_id=uuid4(),
+ user_utterance="Schau in mein Gmail nach neuen Rechnungen",
+ config={"output_language": "de"},
+ memory_read=None,
+ )
+ await tool.execute(
+ {
+ "utterance": "Schau in mein Gmail nach neuen Rechnungen",
+ "action": "durchsucht das Gmail-Postfach nach Rechnungen",
+ "target": "",
+ },
+ ctx,
+ )
+ await _drain_background_tasks()
+
+ prompt = mgr.dispatch_calls[0]["prompt"]
+ assert "durchsucht das Gmail-Postfach nach Rechnungen" in prompt
+
+
def test_schema_offers_spoken_ack_and_language() -> None:
"""The router brain must be invited to phrase the announcement itself."""
props = SpawnWorkerTool.schema["properties"]
diff --git a/tests/unit/plugins/tool/test_spawn_worker_cooldown.py b/tests/unit/plugins/tool/test_spawn_worker_cooldown.py
index f75392cfe7..0dc5d78625 100644
--- a/tests/unit/plugins/tool/test_spawn_worker_cooldown.py
+++ b/tests/unit/plugins/tool/test_spawn_worker_cooldown.py
@@ -35,9 +35,13 @@ from jarvis.plugins.tool.spawn_worker import (
)
# The suppress ACK is composed by SpawnAnnouncementComposer in its
-# deterministic "already_running" mode — bilingual pools, no LLM.
-_SUPPRESS_POOL = set(_FALLBACK_ALREADY_RUNNING["de"]) | set(
- _FALLBACK_ALREADY_RUNNING["en"]
+# deterministic "already_running" mode — de/en/es pools, no LLM. All three
+# supported languages are included so a Spanish suppress ACK never false-fails
+# the pool assertions (the composer's _resolve_language can return "es").
+_SUPPRESS_POOL = (
+ set(_FALLBACK_ALREADY_RUNNING["de"])
+ | set(_FALLBACK_ALREADY_RUNNING["en"])
+ | set(_FALLBACK_ALREADY_RUNNING["es"])
)
@@ -302,9 +306,10 @@ def test_suppress_acks_are_short_and_unique() -> None:
assert len(pool) >= 3, "need variety to avoid robot repetition"
assert len(set(pool)) == len(pool)
in_flight_markers = {
- # German marker words below are the data under test.
+ # German/Spanish marker words below are the data under test.
"de": ("schon", "läuft", "dabei", "dran", "bereits", "arbeit"), # i18n-allow
"en": ("already", "still", "running", "working", "progress"),
+ "es": ("marcha", "sigo", "proceso", "está"), # i18n-allow
}[lang]
for ack in pool:
assert 5 <= len(ack) <= 60, (
diff --git a/tests/unit/plugins/tool/test_spawn_worker_mission_prompt.py b/tests/unit/plugins/tool/test_spawn_worker_mission_prompt.py
index 87a9fc983f..22477cfae7 100644
--- a/tests/unit/plugins/tool/test_spawn_worker_mission_prompt.py
+++ b/tests/unit/plugins/tool/test_spawn_worker_mission_prompt.py
@@ -241,3 +241,24 @@ def test_quality_directive_has_honest_impossibility_escape() -> None:
assert "do not simulate" in low or "do not simulate," in low or "not simulate" in low
# The anti-stub floor must still be present (regression guard).
assert "production-quality" in low
+
+
+def test_quality_directive_respects_explicit_form_constraint() -> None:
+ """Live incident 2026-06-22 (mission 019ef052): the user asked for a SINGLE
+ HTML file, the worker shipped four (index.html + app.js + styles.css +
+ assets/), and the mission passed. The 'never downgrade to a minimal version /
+ skeleton is a floor not a ceiling' clause read a single self-contained file
+ as a forbidden minimal version. The directive must carve out an explicit
+ user constraint on the SHAPE/SCOPE of the deliverable: honoring it is part of
+ satisfying the request, never a downgrade."""
+ prompt = _build_mission_prompt(
+ utterance="mach mir bitte eine einzige, in sich geschlossene HTML-Datei",
+ action="",
+ )
+ low = prompt.lower()
+ # The new carve-out names an explicit user constraint on form/scope.
+ assert "constraint" in low, "the quality floor must defer to an explicit user constraint"
+ # Regression: the anti-stub quality floor and impossibility escape survive.
+ assert "production-quality" in low
+ assert "skeleton" in low or "stub" in low or "placeholder" in low
+ assert "cannot be completed with the tools available" in low
diff --git a/tests/unit/safety/test_tool_executor_voice_confirm.py b/tests/unit/safety/test_tool_executor_voice_confirm.py
index 10b3845e28..57c52f60fb 100644
--- a/tests/unit/safety/test_tool_executor_voice_confirm.py
+++ b/tests/unit/safety/test_tool_executor_voice_confirm.py
@@ -167,6 +167,54 @@ async def test_safe_tier_is_not_deferred_even_with_voice_confirm() -> None:
assert result.error != VOICE_CONFIRM_SENTINEL
+async def test_gmail_read_is_not_deferred_for_voice_confirm() -> None:
+ """Repro 2026-06-19 (session dc533e39): a read-only gmail call (the
+ morning-routine "check unread mail" step) must NOT trigger the send
+ confirmation on a voice turn. Before the per-action risk fix the whole
+ gmail tool was ask-tier, so "Was habe ich heute auf dem Plan?" produced
+ "Soll ich die E-Mail wirklich senden?"."""
+ import httpx
+
+ from jarvis.plugins.tool.gmail_rest import GmailRestTool
+
+ executor, approval, _bus = _executor()
+ tool = GmailRestTool(
+ access_token_provider=lambda: "at_x",
+ transport=httpx.MockTransport(
+ lambda req: httpx.Response(200, json={"messages": []})
+ ),
+ )
+ result = await executor.execute(
+ tool,
+ args={"action": "list_messages"},
+ config_snapshot={"voice_confirm": True},
+ trace_id=uuid4(),
+ )
+ # A read runs straight through — never deferred, never blocked.
+ assert result.error != VOICE_CONFIRM_SENTINEL
+ assert result.success is True
+ assert approval.wait_calls == 0
+
+
+async def test_gmail_send_still_defers_for_voice_confirm() -> None:
+ """Sending stays consequential: it must still confirm before sending."""
+ from jarvis.plugins.tool.gmail_rest import GmailRestTool
+
+ executor, approval, _bus = _executor()
+ tool = GmailRestTool(access_token_provider=lambda: "at_x")
+ result = await executor.execute(
+ tool,
+ args={"action": "send_message", "to": "[email protected]", "body": "hi"},
+ config_snapshot={"voice_confirm": True},
+ trace_id=uuid4(),
+ )
+ assert result.error == VOICE_CONFIRM_SENTINEL
+ assert result.output["tool_name"] == "gmail"
+ assert approval.wait_calls == 0 # deferred for two-turn confirm, not blocked
+
+
async def _drain(bus: EventBus) -> None:
import asyncio
await asyncio.sleep(0)
diff --git a/tests/unit/sessions/test_formatter.py b/tests/unit/sessions/test_formatter.py
index fb177c27df..21bf764b8d 100644
--- a/tests/unit/sessions/test_formatter.py
+++ b/tests/unit/sessions/test_formatter.py
@@ -129,6 +129,28 @@ def test_plain_has_no_developer_tags() -> None:
assert tag not in out
+def test_markdown_labels_awaiting_confirmation_reply() -> None:
+ # A turn that ended on a two-turn confirmation tags its reply as a pending
+ # yes/no question — consistent with the english spoken_kind tags (preamble,
+ # clarify) the markdown renderer already uses (forensic 2026-06-19: the
+ # confirmation question was indistinguishable from a normal reply).
+ turn = _turn(
+ 0,
+ "schick eine Mail an Tom",
+ "Soll ich die E-Mail wirklich senden? Sag ja oder nein.",
+ awaiting_confirmation=True,
+ )
+ out = format_session_markdown(_session(), [turn])
+ assert "awaiting confirmation" in out
+ assert "Soll ich die E-Mail wirklich senden" in out
+
+
+def test_markdown_normal_reply_has_no_awaiting_label() -> None:
+ turn = _turn(0, "wie spät ist es", "Es ist 15 Uhr.")
+ out = format_session_markdown(_session(), [turn])
+ assert "awaiting confirmation" not in out
+
+
def test_plain_has_no_telemetry() -> None:
out = format_session_plain(_session(), _example_turns())
# No tokens / cost / provider / tier / latency clutter, and none of the
diff --git a/tests/unit/sessions/test_recorder_lifecycle.py b/tests/unit/sessions/test_recorder_lifecycle.py
index 38007c70de..ea2d03bd52 100644
--- a/tests/unit/sessions/test_recorder_lifecycle.py
+++ b/tests/unit/sessions/test_recorder_lifecycle.py
@@ -4,7 +4,9 @@ import pytest
from jarvis.core.bus import EventBus
from jarvis.core.events import (
+ BrainTurnCompleted,
ListeningStarted,
+ ResponseGenerated,
SystemStateChanged,
TranscriptFinal,
VoiceSessionEnded,
@@ -152,6 +154,143 @@ async def test_multiple_transcript_finals_in_suppressed_session_keep_each_uttera
store.close()
+async def test_voice_confirm_pending_turn_is_flagged_awaiting_confirmation(
+ tmp_path,
+) -> None:
+ """A consequential ask-tier tool deferred into a two-turn voice/chat
+ confirmation ends the turn with ``finish_reason='voice_confirm_pending'``.
+ The persisted turn must carry ``awaiting_confirmation=True`` so the
+ transcript can label the reply as a pending yes/no question instead of an
+ ordinary answer (forensic 2026-06-19: "Soll ich die E-Mail senden?" was
+ indistinguishable from a normal reply in the transcript)."""
+ store = SessionStore(tmp_path / "sessions.db")
+ store.open()
+ try:
+ bus = EventBus()
+ SessionRecorder(store).attach(bus)
+ await bus.publish(
+ VoiceSessionStarted(
+ source_layer="speech.pipeline",
+ session_id="s-confirm",
+ wake_keyword="hey_jarvis",
+ language="de",
+ )
+ )
+ await bus.publish(ListeningStarted(source_layer="speech"))
+ await bus.publish(_final("schick eine Mail an Tom"))
+ await bus.publish(
+ ResponseGenerated(
+ source_layer="brain",
+ text="Soll ich die E-Mail wirklich senden? Sag ja oder nein.",
+ language="de",
+ )
+ )
+ await bus.publish(
+ BrainTurnCompleted(
+ source_layer="brain", finish_reason="voice_confirm_pending"
+ )
+ )
+ await bus.publish(
+ VoiceSessionEnded(
+ source_layer="speech.pipeline",
+ session_id="s-confirm",
+ hangup_reason="voice_pattern",
+ )
+ )
+ turns = store.get_turns("s-confirm")
+ assert len(turns) == 1
+ assert turns[0].awaiting_confirmation is True
+ finally:
+ store.close()
+
+
+async def test_awaiting_confirmation_latch_survives_a_later_completed(
+ tmp_path,
+) -> None:
+ """One-way latch regression guard: once a turn is flagged
+ awaiting_confirmation, a later BrainTurnCompleted in the SAME turn (e.g. a
+ multi-step tool loop emitting a second completion with finish_reason='stop')
+ must NOT clear it. Guards against a refactor to
+ ``t.awaiting_confirmation = (finish_reason == 'voice_confirm_pending')``
+ that would silently break the invariant."""
+ store = SessionStore(tmp_path / "sessions.db")
+ store.open()
+ try:
+ bus = EventBus()
+ SessionRecorder(store).attach(bus)
+ await bus.publish(
+ VoiceSessionStarted(
+ source_layer="speech.pipeline",
+ session_id="s-latch",
+ wake_keyword="hey_jarvis",
+ language="de",
+ )
+ )
+ await bus.publish(ListeningStarted(source_layer="speech"))
+ await bus.publish(_final("schick eine Mail an Tom"))
+ await bus.publish(
+ BrainTurnCompleted(
+ source_layer="brain", finish_reason="voice_confirm_pending"
+ )
+ )
+ # A later completion in the same turn must not reset the latch.
+ await bus.publish(
+ BrainTurnCompleted(source_layer="brain", finish_reason="stop")
+ )
+ await bus.publish(
+ VoiceSessionEnded(
+ source_layer="speech.pipeline",
+ session_id="s-latch",
+ hangup_reason="voice_pattern",
+ )
+ )
+ turns = store.get_turns("s-latch")
+ assert len(turns) == 1
+ assert turns[0].awaiting_confirmation is True
+ finally:
+ store.close()
+
+
+async def test_normal_turn_is_not_flagged_awaiting_confirmation(tmp_path) -> None:
+ """A normal reply (any other finish_reason) leaves the flag False."""
+ store = SessionStore(tmp_path / "sessions.db")
+ store.open()
+ try:
+ bus = EventBus()
+ SessionRecorder(store).attach(bus)
+ await bus.publish(
+ VoiceSessionStarted(
+ source_layer="speech.pipeline",
+ session_id="s-normal",
+ wake_keyword="hey_jarvis",
+ language="de",
+ )
+ )
+ await bus.publish(ListeningStarted(source_layer="speech"))
+ await bus.publish(_final("wie spät ist es"))
+ await bus.publish(
+ ResponseGenerated(source_layer="brain", text="Es ist 15 Uhr.", language="de")
+ )
+ await bus.publish(
+ BrainTurnCompleted(source_layer="brain", finish_reason="stop")
+ )
+ await bus.publish(
+ VoiceSessionEnded(
+ source_layer="speech.pipeline",
+ session_id="s-normal",
+ hangup_reason="voice_pattern",
+ )
+ )
+ turns = store.get_turns("s-normal")
+ assert len(turns) == 1
+ assert turns[0].awaiting_confirmation is False
+ finally:
+ store.close()
+
+
@pytest.mark.asyncio
async def test_transcript_final_event_payload_contains_text(tmp_path) -> None:
"""Regression: ``_payload_for`` had ``"transcript"`` missing from
diff --git a/tests/unit/sessions/test_recorder_whitelist.py b/tests/unit/sessions/test_recorder_whitelist.py
index 3990e7d6a2..4a8ae95464 100644
--- a/tests/unit/sessions/test_recorder_whitelist.py
+++ b/tests/unit/sessions/test_recorder_whitelist.py
@@ -35,3 +35,47 @@ def test_payload_carries_latency_and_error_fields():
message="provider chain unreachable", recoverable=False))
assert e["layer"] == "brain" and e["error_type"] == "Timeout"
assert e["message"].startswith("provider") and e["recoverable"] is False
+
+
+def test_payload_extracts_safe_action_but_never_pii_args():
+ # ActionProposed.args may hold PII (recipient, subject, body, search query).
+ # Only the short enum-like `action` selector is persisted so forensics can
+ # tell e.g. a gmail read from a send — the raw args must NEVER reach the DB
+ # (forensic 2026-06-19: the action was unrecoverable from the persisted
+ # event, which is itself the bug being closed here).
+ p = _payload_for(ActionProposed(
+ tool_name="gmail", risk_tier="ask",
+ args={
+ "action": "send_message",
+ "subject": "secret subject",
+ "body": "private body text",
+ },
+ ))
+ assert p["action"] == "send_message"
+ assert p["tool_name"] == "gmail"
+ # No raw args dict, no PII fields, no PII values anywhere in the payload.
+ assert "args" not in p
+ assert "to" not in p and "subject" not in p and "body" not in p
+ blob = str(p)
+ assert "[email protected]" not in blob
+ assert "private body text" not in blob
+ assert "secret subject" not in blob
+
+
+def test_payload_omits_action_when_args_have_no_action():
+ # A tool call without an `action` key adds no action field (no empty noise),
+ # and a PII-ish free-text arg like a search query is never persisted.
+ p = _payload_for(ActionProposed(tool_name="search_web", args={"query": "my private search"}))
+ assert "action" not in p
+ assert "query" not in p
+ assert "my private search" not in str(p)
+
+
+def test_payload_ignores_non_string_or_oversized_action():
+ # Defensive: a non-string or absurdly long `action` is not persisted, so a
+ # tool that overloads the key cannot smuggle a payload into the DB.
+ p = _payload_for(ActionProposed(tool_name="weird", args={"action": 12345}))
+ assert "action" not in p
+ p2 = _payload_for(ActionProposed(tool_name="weird", args={"action": "x" * 500}))
+ assert "action" not in p2
diff --git a/tests/unit/setup/test_onboarding_meta.py b/tests/unit/setup/test_onboarding_meta.py
index 7ce087a73c..24f1ea9e7b 100644
--- a/tests/unit/setup/test_onboarding_meta.py
+++ b/tests/unit/setup/test_onboarding_meta.py
@@ -7,7 +7,13 @@ def test_meta_constants():
assert m.ONBOARDING_STEPS[1] == "terms"
assert m.ONBOARDING_STEPS[-1] == "finish"
assert "wake-word" in m.ONBOARDING_STEPS
- assert len(m.ONBOARDING_STEPS) == 8
+ assert "persona-theme" not in m.ONBOARDING_STEPS
+ # Persona-name, overlay-style and the mic check were moved out of onboarding
+ # to keep first-run short; it ends at api-keys → finish (removed 2026-06-20).
+ 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) == 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/skills/test_authoring_service.py b/tests/unit/skills/test_authoring_service.py
new file mode 100644
index 0000000000..f5dc84cc71
--- /dev/null
+++ b/tests/unit/skills/test_authoring_service.py
@@ -0,0 +1,154 @@
+"""Tests for the deterministic user-skill authoring service.
+
+``SkillAuthoringService`` backs ``POST /api/skills`` — the "New skill" form in
+the desktop app. Unlike the OpenClaw-author *mission* pipeline
+(``SkillAuthoringRunner``), this path takes a structured request (name,
+description, body, triggers) and writes a SKILL.md deterministically, with NO
+brain involved, so it works on a headless €5 VPS.
+
+Contract:
+- ``create`` writes ``<user_skills_root>/<slug>/SKILL.md`` and reloads the
+ registry so the new skill is immediately listable.
+- A name colliding with an existing skill or a built-in is refused with status
+ 409. An empty/too-short name is refused with 400.
+- The slug is derived kebab-case from the name; triggers land in the
+ frontmatter.
+"""
+from __future__ import annotations
+
+from pathlib import Path
+
+import pytest
+import yaml
+
+from jarvis.skills import prefs
+from jarvis.skills.authoring import (
+ SkillAuthoringError,
+ SkillAuthoringService,
+ SkillCreateRequest,
+)
+from jarvis.skills.registry import SkillRegistry
+from jarvis.skills.schema import SkillLifecycleState
+
+
+def skills_root(tmp_path: Path) -> Path:
+ root = tmp_path / "skills"
+ root.mkdir()
+ return root
+
+
+def registry(skills_root: Path) -> SkillRegistry:
+ reg = SkillRegistry(
+ skills_root, bus=None, state_prefs_loader=prefs.load_state_overrides
+ )
+ reg.reload_sync()
+ return reg
+
+
+def _service(registry: SkillRegistry, skills_root: Path) -> SkillAuthoringService:
+ return SkillAuthoringService(registry=registry, user_skills_root=skills_root)
+
+
+async def test_create_writes_skill_md_and_appears_in_registry(
+ registry: SkillRegistry, skills_root: Path
+) -> None:
+ svc = _service(registry, skills_root)
+ created = await svc.create(
+ SkillCreateRequest(
+ name="My Cool Skill",
+ description="Does a cool thing",
+ body="## My Cool Skill\n\nStep one.\n",
+ )
+ )
+ assert created.name == "My Cool Skill"
+ # File on disk under the kebab-case slug
+ skill_md = skills_root / "my-cool-skill" / "SKILL.md"
+ assert skill_md.exists()
+ fm = yaml.safe_load(skill_md.read_text(encoding="utf-8").split("---", 2)[1])
+ assert fm["name"] == "My Cool Skill"
+ assert fm["description"] == "Does a cool thing"
+ # Registry now lists it
+ assert registry.get("My Cool Skill").name == "My Cool Skill"
+
+
+async def test_create_skill_is_on_by_default(
+ registry: SkillRegistry, skills_root: Path
+) -> None:
+ """A user who fills the form and hits Create expects an active skill —
+ not a draft they have to flip on. No explicit state → VALIDATED ("on")."""
+ svc = _service(registry, skills_root)
+ await svc.create(SkillCreateRequest(name="Active One", body="## x\n"))
+ skill = registry.get("Active One")
+ assert skill.state in (
+ SkillLifecycleState.VALIDATED,
+ SkillLifecycleState.ACTIVE,
+ )
+
+
+async def test_create_persists_voice_trigger(
+ registry: SkillRegistry, skills_root: Path
+) -> None:
+ svc = _service(registry, skills_root)
+ await svc.create(
+ SkillCreateRequest(
+ name="Trigger Skill",
+ body="## x\n",
+ triggers=({"type": "voice", "pattern": "^do the thing"},),
+ )
+ )
+ fm = registry.get("Trigger Skill").frontmatter
+ assert fm is not None
+ assert len(fm.triggers) == 1
+ assert fm.triggers[0].type == "voice"
+ assert fm.triggers[0].pattern == "^do the thing"
+
+
+async def test_create_rejects_duplicate_name(
+ registry: SkillRegistry, skills_root: Path
+) -> None:
+ svc = _service(registry, skills_root)
+ await svc.create(SkillCreateRequest(name="Dup Skill", body="## x\n"))
+ with pytest.raises(SkillAuthoringError) as exc:
+ await svc.create(SkillCreateRequest(name="Dup Skill", body="## y\n"))
+ assert exc.value.status == 409
+
+
+async def test_create_rejects_builtin_name(
+ registry: SkillRegistry, skills_root: Path
+) -> None:
+ from jarvis.skills.builtin import BUILTIN_SKILL_NAMES
+
+ builtin = sorted(BUILTIN_SKILL_NAMES)[0]
+ svc = _service(registry, skills_root)
+ with pytest.raises(SkillAuthoringError) as exc:
+ await svc.create(SkillCreateRequest(name=builtin, body="## x\n"))
+ assert exc.value.status == 409
+
+
+async def test_create_rejects_empty_name(
+ registry: SkillRegistry, skills_root: Path
+) -> None:
+ svc = _service(registry, skills_root)
+ with pytest.raises(SkillAuthoringError) as exc:
+ await svc.create(SkillCreateRequest(name=" ", body="## x\n"))
+ assert exc.value.status == 400
+
+
+async def test_create_rejects_name_that_slugs_to_nothing(
+ registry: SkillRegistry, skills_root: Path
+) -> None:
+ """A name with no slug-able characters (e.g. only punctuation) is a 400,
+ not a path-traversal or an empty-dir write."""
+ svc = _service(registry, skills_root)
+ with pytest.raises(SkillAuthoringError) as exc:
+ await svc.create(SkillCreateRequest(name="!!!", body="## x\n"))
+ assert exc.value.status == 400
diff --git a/tests/unit/skills/test_creator_service.py b/tests/unit/skills/test_creator_service.py
new file mode 100644
index 0000000000..58eb73d93f
--- /dev/null
+++ b/tests/unit/skills/test_creator_service.py
@@ -0,0 +1,233 @@
+"""Tests for the AI Skill Creator service (``/api/skills/creator/*``).
+
+The creator turns a free-text intent into a structured SKILL.md draft. It is
+brain-assisted but MUST degrade gracefully: with no brain (headless VPS, brain
+not yet built, provider down) ``draft`` still returns a valid deterministic
+skeleton so the user can edit and commit it. ``commit`` persists the reviewed
+draft through the same deterministic writer as the manual form.
+
+Contract (mirrors the frontend types in ``useSkills.ts``):
+- ``draft(SkillCreatorInput) -> SkillCreatorResult(draft, skill_md, validation,
+ brain_used)``; ``draft`` is a dict with name/description/category/tags/
+ triggers/requires_tools/risk_policy/body/questions/assumptions/test_prompts.
+- ``validate_skill_md(content) -> (validation, frontmatter)`` where validation is
+ ``{ok, state, errors, warnings, parse_error}``.
+- ``commit(draft) -> Skill`` that appears in the registry.
+"""
+from __future__ import annotations
+
+from pathlib import Path
+
+import pytest
+
+from jarvis.core.protocols import BrainDelta
+from jarvis.skills import prefs
+from jarvis.skills.creator_service import (
+ SkillCreatorInput,
+ SkillCreatorService,
+ render_skill_md,
+ validate_skill_md,
+)
+from jarvis.skills.registry import SkillRegistry
+
+
+# ----------------------------------------------------------------------
+# Fixtures
+# ----------------------------------------------------------------------
+
+
+def skills_root(tmp_path: Path) -> Path:
+ root = tmp_path / "skills"
+ root.mkdir()
+ return root
+
+
+def registry(skills_root: Path) -> SkillRegistry:
+ reg = SkillRegistry(
+ skills_root, bus=None, state_prefs_loader=prefs.load_state_overrides
+ )
+ reg.reload_sync()
+ return reg
+
+
+class _FakeBrain:
+ """Minimal brain stub: ``complete`` streams one delta with fixed text."""
+
+ def __init__(self, text: str) -> None:
+ self._text = text
+
+ def complete(self, request): # noqa: ANN001 — duck-typed
+ async def _gen():
+ yield BrainDelta(content=self._text, finish_reason="stop")
+
+ return _gen()
+
+
+class _FakeBrainManager:
+ """Mimics the live BrainManager: exposes the user's ACTIVE provider via
+ ``active_provider`` + ``_get_or_create`` (the multi-provider contract — the
+ creator must use the provider the user selected, not a frontier favourite)."""
+
+ def __init__(self, provider, name: str = "gemini") -> None:
+ self._provider = provider
+ self.active_provider = name
+ self.requested: list[str] = []
+
+ def _get_or_create(self, name: str): # noqa: ANN001
+ self.requested.append(name)
+ return self._provider
+
+
+_GOOD_BRAIN_JSON = """{
+ "name": "Brain Made Skill",
+ "description": "A skill the brain designed.",
+ "category": "automation",
+ "tags": ["ai"],
+ "triggers": [{"type": "voice", "pattern": "^do brain thing"}],
+ "requires_tools": ["run-shell"],
+ "risk_policy": {"default_tier": "ask"},
+ "body": "## Brain Made Skill\\n\\nDo the brain thing.\\n"
+}"""
+
+
+def _service(registry, *, brain=None) -> SkillCreatorService:
+ return SkillCreatorService(brain=brain, registry=registry)
+
+
+# ----------------------------------------------------------------------
+# validate_skill_md / render_skill_md
+# ----------------------------------------------------------------------
+
+
+def test_validate_accepts_valid_skill_md() -> None:
+ content = (
+ "---\n"
+ 'schema_version: "1"\n'
+ "name: Good Skill\n"
+ "description: fine\n"
+ "---\n\n## Body\n"
+ )
+ validation, frontmatter = validate_skill_md(content)
+ assert validation["ok"] is True
+ assert validation["errors"] == []
+ assert frontmatter is not None
+ assert frontmatter["name"] == "Good Skill"
+
+
+def test_validate_rejects_missing_name() -> None:
+ content = "---\nschema_version: \"1\"\ndescription: no name\n---\n\n## Body\n"
+ validation, frontmatter = validate_skill_md(content)
+ assert validation["ok"] is False
+ assert validation["errors"]
+
+
+def test_validate_reports_parse_error_for_garbage() -> None:
+ validation, frontmatter = validate_skill_md("not a skill at all")
+ assert validation["ok"] is False
+ assert validation["parse_error"]
+ assert frontmatter is None
+
+
+def test_render_draft_produces_parseable_skill_md() -> None:
+ draft = {
+ "name": "Rendered Skill",
+ "description": "desc",
+ "category": "general",
+ "tags": [],
+ "triggers": [],
+ "requires_tools": [],
+ "risk_policy": {"default_tier": "ask"},
+ "body": "## Rendered Skill\n\nHello.\n",
+ }
+ skill_md = render_skill_md(draft)
+ assert "Rendered Skill" in skill_md
+ validation, _ = validate_skill_md(skill_md)
+ assert validation["ok"] is True
+
+
+# ----------------------------------------------------------------------
+# draft() — deterministic fallback + brain path
+# ----------------------------------------------------------------------
+
+
+async def test_draft_without_brain_is_deterministic_and_valid(registry) -> None:
+ svc = _service(registry, brain=None)
+ result = await svc.draft(
+ SkillCreatorInput(
+ intent="pause spotify when I start talking",
+ name_hint="Spotify Pause",
+ )
+ )
+ assert result.brain_used is False
+ assert result.draft["name"] # non-empty name
+ assert result.draft["body"].strip() # non-empty body
+ assert result.validation["ok"] is True
+
+
+async def test_draft_with_brain_uses_brain_output(registry) -> None:
+ svc = _service(registry, brain=_FakeBrain(_GOOD_BRAIN_JSON))
+ result = await svc.draft(
+ SkillCreatorInput(intent="something", name_hint="ignored hint")
+ )
+ assert result.brain_used is True
+ assert result.draft["name"] == "Brain Made Skill"
+ assert result.draft["requires_tools"] == ["run-shell"]
+ assert result.validation["ok"] is True
+
+
+async def test_draft_uses_active_provider_of_brain_manager(registry) -> None:
+ """When the injected brain is the live BrainManager, the creator must use
+ the user's ACTIVE provider — never a frontier favourite (which on this user's
+ box is an unkeyed Claude-API → 401). AP-21: follow the user's selection."""
+ provider = _FakeBrain(_GOOD_BRAIN_JSON)
+ bm = _FakeBrainManager(provider, name="gemini")
+ svc = SkillCreatorService(brain=bm, registry=registry)
+ result = await svc.draft(SkillCreatorInput(intent="something"))
+ assert result.brain_used is True
+ assert result.draft["name"] == "Brain Made Skill"
+ assert bm.requested == ["gemini"] # used the active provider
+
+
+async def test_draft_falls_back_when_brain_returns_garbage(registry) -> None:
+ svc = _service(registry, brain=_FakeBrain("I cannot help with that."))
+ result = await svc.draft(
+ SkillCreatorInput(intent="make a thing", name_hint="My Thing")
+ )
+ # Garbage brain output → deterministic skeleton, brain_used False.
+ assert result.brain_used is False
+ assert result.draft["name"]
+ assert result.validation["ok"] is True
+
+
+# ----------------------------------------------------------------------
+# commit()
+# ----------------------------------------------------------------------
+
+
+async def test_commit_persists_draft_to_registry(registry, skills_root) -> None:
+ svc = SkillCreatorService(
+ brain=None, registry=registry, user_skills_root=skills_root
+ )
+ draft = {
+ "name": "Committed Skill",
+ "description": "desc",
+ "category": "general",
+ "tags": ["x"],
+ "triggers": [{"type": "voice", "pattern": "^go"}],
+ "requires_tools": ["run-shell"],
+ "risk_policy": {"default_tier": "ask"},
+ "body": "## Committed Skill\n\nDo it.\n",
+ }
+ created = await svc.commit(draft)
+ assert created.name == "Committed Skill"
+ fetched = registry.get("Committed Skill")
+ assert fetched.frontmatter is not None
+ assert "run-shell" in fetched.frontmatter.requires_tools
+ assert (skills_root / "committed-skill" / "SKILL.md").exists()
diff --git a/tests/unit/speech/test_pipeline_sound_effects.py b/tests/unit/speech/test_pipeline_sound_effects.py
new file mode 100644
index 0000000000..f625b71cf6
--- /dev/null
+++ b/tests/unit/speech/test_pipeline_sound_effects.py
@@ -0,0 +1,88 @@
+"""Unit tests for the global "Sound effects" earcon master switch.
+
+The Settings → Behavior toggle persists ``[ui] sound_effects`` and the speech
+pipeline reads it fresh before every synthesized earcon (wake chime, hang-up
+tone, boot-ready cue, "still listening" earcon). When off, those tones are
+silenced; the spoken TTS voice is never affected. Default on — a missing field
+must never silence tones.
+"""
+from __future__ import annotations
+
+from collections.abc import AsyncIterator
+from types import SimpleNamespace
+
+from jarvis.audio.chime import CHIME_PCM, READY_PCM
+from jarvis.speech.pipeline import SpeechPipeline
+
+_MISSING = object()
+
+
+class _FakeTTS:
+ name = "fake-tts"
+ supports_streaming = False
+
+ async def synthesize( # type: ignore[no-untyped-def]
+ self, text, language_code=None
+ ) -> AsyncIterator[bytes]: # pragma: no cover
+ if False:
+ yield b""
+
+
+class _RecordingPlayer:
+ def __init__(self) -> None:
+ self.plays: list[bytes] = []
+
+ async def play_pcm(self, pcm, sample_rate=None): # noqa: ANN001
+ self.plays.append(pcm)
+
+
+def _make_pipeline(sound_effects: object) -> SpeechPipeline:
+ pipe = SpeechPipeline(tts=_FakeTTS(), bus=None, enable_whisper_wake=False)
+ pipe._player = _RecordingPlayer() # type: ignore[assignment]
+ ui = SimpleNamespace() if sound_effects is _MISSING else SimpleNamespace(
+ sound_effects=sound_effects
+ )
+ pipe._config = SimpleNamespace(ui=ui)
+ return pipe
+
+
+async def test_earcon_plays_when_enabled():
+ pipe = _make_pipeline(True)
+ await pipe._play_earcon(CHIME_PCM)
+ assert pipe._player.plays == [CHIME_PCM] # type: ignore[attr-defined]
+
+
+async def test_earcon_muted_when_disabled():
+ pipe = _make_pipeline(False)
+ await pipe._play_earcon(CHIME_PCM)
+ assert pipe._player.plays == [] # type: ignore[attr-defined]
+
+
+async def test_earcon_default_on_when_field_missing():
+ pipe = _make_pipeline(_MISSING)
+ await pipe._play_earcon(CHIME_PCM)
+ assert pipe._player.plays == [CHIME_PCM] # type: ignore[attr-defined]
+
+
+async def test_ready_cue_respects_switch():
+ on = _make_pipeline(True)
+ await on._play_ready_cue()
+ assert on._player.plays == [READY_PCM] # type: ignore[attr-defined]
+
+ off = _make_pipeline(False)
+ await off._play_ready_cue()
+ assert off._player.plays == [] # type: ignore[attr-defined]
+
+
+async def test_wake_chime_muted_but_spoken_ack_still_plays(monkeypatch):
+ """A muted wake path plays no chime, but the spoken ACK that follows is NOT
+ an earcon and must still reach the player — only effect tones are gated."""
+ pipe = _make_pipeline(False)
+ pipe._ack_pcm = b"\x00\x00" * 100 # type: ignore[attr-defined]
+
+ async def _fast_sleep(_secs): # noqa: ANN001, ANN202
+ return None
+
+ monkeypatch.setattr("jarvis.speech.pipeline.asyncio.sleep", _fast_sleep)
+ await pipe._play_ack(ptt=False)
+ assert pipe._player.plays == [pipe._ack_pcm] # type: ignore[attr-defined]
diff --git a/tests/unit/speech/test_pipeline_wake_plan.py b/tests/unit/speech/test_pipeline_wake_plan.py
index b7030635e3..c7d477ffaf 100644
--- a/tests/unit/speech/test_pipeline_wake_plan.py
+++ b/tests/unit/speech/test_pipeline_wake_plan.py
@@ -11,6 +11,10 @@ from collections.abc import AsyncIterator
from dataclasses import dataclass
from types import SimpleNamespace
+import pytest
+
+from jarvis.speech import wake_constants as wc
+from jarvis.speech import wake_phrase as wp
from jarvis.speech.pipeline import SpeechPipeline
from jarvis.speech.wake_phrase import resolve_wake_plan
@@ -39,6 +43,21 @@ def _wake_cfg(**kw: object) -> SimpleNamespace:
return SimpleNamespace(**base)
+def _pretend_oww_models_exist(
+ monkeypatch: pytest.MonkeyPatch, *model_names: str
+) -> None:
+ models = set(model_names)
+ original_resolve = wc.resolve_oww_model_path
+
+ def fake_resolve(model_name: str) -> str | None:
+ if model_name in models:
+ return f"C:/fake-openwakeword/{model_name}_v0.1.onnx"
+ return original_resolve(model_name)
+
+ monkeypatch.setattr(wc, "resolve_oww_model_path", fake_resolve)
+ monkeypatch.setattr(wp, "resolve_oww_model_path", fake_resolve)
+
+
def _pipe(wake_plan: object | None) -> SpeechPipeline:
return SpeechPipeline(
tts=_FakeTTS(),
@@ -58,7 +77,11 @@ def test_no_plan_keeps_matcher_none_legacy_behaviour() -> None:
assert pipe._wake._keywords == ("hey_jarvis",)
-def test_plan_builds_oww_from_pretrained_model() -> None:
+def test_plan_builds_oww_from_pretrained_model(
+ monkeypatch: pytest.MonkeyPatch,
+) -> None:
+ _pretend_oww_models_exist(monkeypatch, "alexa")
+
plan = resolve_wake_plan(_wake_cfg(phrase="Alexa"), local_whisper_available=False)
pipe = _pipe(plan)
assert pipe._wake_matcher is plan.matcher
@@ -67,7 +90,11 @@ def test_plan_builds_oww_from_pretrained_model() -> None:
assert pipe._wake._threshold == plan.threshold
-def test_plan_matcher_drives_prefix_verifier_phrase() -> None:
+def test_plan_matcher_drives_prefix_verifier_phrase(
+ monkeypatch: pytest.MonkeyPatch,
+) -> None:
+ _pretend_oww_models_exist(monkeypatch, "alexa")
+
plan = resolve_wake_plan(_wake_cfg(phrase="Alexa"), local_whisper_available=False)
pipe = _pipe(plan)
# The verifier matcher now confirms "alexa", not "jarvis".
diff --git a/tests/unit/speech/test_rolling_whisper_wake.py b/tests/unit/speech/test_rolling_whisper_wake.py
new file mode 100644
index 0000000000..c15ce70d2e
--- /dev/null
+++ b/tests/unit/speech/test_rolling_whisper_wake.py
@@ -0,0 +1,403 @@
+"""Regression tests for the rolling-whisper wake backstop (custom phrases).
+
+Forensic 2026-06-22 (branch feat/fast-boot-bootstrap): a user who sets a custom
+wake word ("Hey Ruben") falls onto the ``stt_match`` path = RollingWhisperWake.
+Two live symptoms — "riesige Verzoegerung" + "manchmal gar nicht":
+
+- LATENCY (this file): ``detect`` used to ``await transcribe_pcm`` *inside* the
+ chunk-consume loop, so while a (CPU "base") transcription ran for ~0.5-1 s the
+ loop could not pull new chunks. They piled up (observed ``wsp_q=100``) and the
+ detector trailed seconds behind live audio. The consumer must keep draining
+ audio while a transcription is in flight, and each transcription must run on
+ the *freshest* window, not a stale FIFO backlog.
+"""
+from __future__ import annotations
+
+import asyncio
+
+import numpy as np
+
+from jarvis.core.protocols import AudioChunk, Transcript
+from jarvis.speech.rolling_whisper_wake import RollingWhisperWake
+
+
+def _loud_chunk(marker: int, n: int = 1600) -> AudioChunk:
+ """A 100 ms @ 16 kHz chunk, loud enough to pass the rms/peak gates.
+
+ ``marker`` is encoded in the (constant) sample value so a test STT can read
+ back which slice of audio it was handed.
+ """
+ val = 12000 + (marker % 80) * 100 # stays < 32767, well above min_peak
+ arr = np.full(n, val, dtype=np.int16)
+ return AudioChunk(pcm=arr.tobytes(), sample_rate=16000, timestamp_ns=0)
+
+
+class _GatedSTT:
+ """``transcribe_pcm`` blocks on an event until the test releases it."""
+
+ def __init__(self) -> None:
+ self.calls = 0
+ self.first_call_started = asyncio.Event()
+ self.release = asyncio.Event()
+
+ async def transcribe_pcm(
+ self, pcm: bytes, sample_rate: int = 16000, language: str | None = None
+ ) -> Transcript:
+ self.calls += 1
+ self.first_call_started.set()
+ await self.release.wait()
+ return Transcript(text="nothing here", language="de", confidence=0.9)
+
+
+class _NeverMatch:
+ """A matcher that never fires, so ``detect`` loops forever (no early yield)."""
+
+ def search(self, text: str): # noqa: ANN001 - duck-typed re.Pattern
+ return None
+
+
+class _PhraseSTT:
+ """Always transcribes the same (matching) phrase."""
+
+ def __init__(
+ self,
+ phrase: str,
+ *,
+ confidence: float = 0.9,
+ no_speech_prob: float | None = None,
+ ) -> None:
+ self._phrase = phrase
+ self._confidence = confidence
+ self._no_speech_prob = no_speech_prob
+
+ async def transcribe_pcm(
+ self, pcm: bytes, sample_rate: int = 16000, language: str | None = None
+ ) -> Transcript:
+ segments = ()
+ if self._no_speech_prob is not None:
+ segments = ({"no_speech_prob": self._no_speech_prob},)
+ return Transcript(
+ text=self._phrase,
+ language="de",
+ confidence=self._confidence,
+ segments=segments,
+ )
+
+
+async def _feed_until(src: asyncio.Queue, stop: asyncio.Event) -> None:
+ i = 0
+ while not stop.is_set():
+ await src.put(_loud_chunk(i))
+ i += 1
+ await asyncio.sleep(0.002)
+
+
+async def test_detect_yields_keyword_when_transcript_matches() -> None:
+ """Refactor guard: a real wake (matching transcript) still yields."""
+ import re
+
+ wake = RollingWhisperWake(
+ _PhraseSTT("hey ruben"),
+ pattern=re.compile(r"ruben"),
+ poll_interval_s=0.01,
+ cooldown_s=0.0,
+ save_debug_wavs=False,
+ min_rms=0.0,
+ min_peak=0.0,
+ )
+
+ src: asyncio.Queue = asyncio.Queue()
+ stop_feed = asyncio.Event()
+
+ async def _iter():
+ while True:
+ chunk = await src.get()
+ if chunk is None:
+ return
+ yield chunk
+
+ async def _first_keyword() -> str:
+ async for kw in wake.detect(_iter()):
+ return kw
+ return ""
+
+ feeder = asyncio.create_task(_feed_until(src, stop_feed))
+ try:
+ kw = await asyncio.wait_for(_first_keyword(), timeout=3.0)
+ assert kw == "ruben"
+ finally:
+ stop_feed.set()
+ await src.put(None)
+ feeder.cancel()
+ try:
+ await feeder
+ except (asyncio.CancelledError, Exception): # noqa: BLE001, S110
+ pass
+
+
+async def test_detect_accepts_short_live_wake_phrase_confidence() -> None:
+ """Live two-word wake phrases can score below the generic 0.55 gate."""
+ import re
+
+ wake = RollingWhisperWake(
+ _PhraseSTT("Hey Ruben!", confidence=0.499, no_speech_prob=0.05734),
+ pattern=re.compile(r"hey\W+ruben", re.IGNORECASE),
+ poll_interval_s=0.01,
+ cooldown_s=0.0,
+ save_debug_wavs=False,
+ min_rms=0.0,
+ min_peak=0.0,
+ )
+
+ src: asyncio.Queue = asyncio.Queue()
+ stop_feed = asyncio.Event()
+
+ async def _iter():
+ while True:
+ chunk = await src.get()
+ if chunk is None:
+ return
+ yield chunk
+
+ async def _first_keyword() -> str:
+ async for kw in wake.detect(_iter()):
+ return kw
+ return ""
+
+ feeder = asyncio.create_task(_feed_until(src, stop_feed))
+ try:
+ kw = await asyncio.wait_for(_first_keyword(), timeout=3.0)
+ assert kw.lower() == "hey ruben"
+ finally:
+ stop_feed.set()
+ await src.put(None)
+ feeder.cancel()
+ try:
+ await feeder
+ except (asyncio.CancelledError, Exception): # noqa: BLE001, S110
+ pass
+
+
+async def test_detect_accepts_real_world_low_confidence_wake() -> None:
+ """The live base/cpu model scores a real, cleanly-heard wake well below 0.45.
+
+ Forensic 2026-06-23 (running app, branch feat/fast-boot-bootstrap): the
+ rolling-whisper wake rejected a CORRECTLY transcribed "Ruben." at confidence
+ 0.318 — and 141 more like it (142 rejects / 0 accepts in a whole evening). The
+ old ``min_wake_confidence=0.45`` gate, built to suppress *prompt-bias*
+ hallucinations, also kills genuine quiet wakes (the bias is now disabled, so
+ the gate guards a problem that no longer exists). A matching transcript with
+ real-speech ``no_speech_prob`` at the live-observed confidence must wake.
+ """
+ import re
+
+ wake = RollingWhisperWake(
+ _PhraseSTT("Hey Ruben", confidence=0.318, no_speech_prob=0.05),
+ pattern=re.compile(r"hey\W+ruben", re.IGNORECASE),
+ poll_interval_s=0.01,
+ cooldown_s=0.0,
+ save_debug_wavs=False,
+ min_rms=0.0,
+ min_peak=0.0,
+ )
+
+ src: asyncio.Queue = asyncio.Queue()
+ stop_feed = asyncio.Event()
+
+ async def _iter():
+ while True:
+ chunk = await src.get()
+ if chunk is None:
+ return
+ yield chunk
+
+ async def _first_keyword() -> str:
+ async for kw in wake.detect(_iter()):
+ return kw
+ return ""
+
+ feeder = asyncio.create_task(_feed_until(src, stop_feed))
+ try:
+ kw = await asyncio.wait_for(_first_keyword(), timeout=3.0)
+ assert kw.lower() == "hey ruben"
+ finally:
+ stop_feed.set()
+ await src.put(None)
+ feeder.cancel()
+ try:
+ await feeder
+ except (asyncio.CancelledError, Exception): # noqa: BLE001, S110
+ pass
+
+
+async def test_detect_rejects_matching_low_confidence_transcript() -> None:
+ """A prompt-biased or mumbled window may hallucinate the wake phrase.
+
+ Matching text alone is not enough: the wake backstop must fail closed when
+ Whisper itself reports the transcript as unreliable.
+ """
+ import re
+
+ wake = RollingWhisperWake(
+ _PhraseSTT("hey ruben", confidence=0.2),
+ pattern=re.compile(r"hey\W+ruben", re.IGNORECASE),
+ poll_interval_s=0.01,
+ cooldown_s=0.0,
+ save_debug_wavs=False,
+ min_rms=0.0,
+ min_peak=0.0,
+ )
+
+ src: asyncio.Queue = asyncio.Queue()
+ stop_feed = asyncio.Event()
+
+ async def _iter():
+ while True:
+ chunk = await src.get()
+ if chunk is None:
+ return
+ yield chunk
+
+ async def _first_keyword() -> str:
+ async for kw in wake.detect(_iter()):
+ return kw
+ return ""
+
+ feeder = asyncio.create_task(_feed_until(src, stop_feed))
+ try:
+ try:
+ kw = await asyncio.wait_for(_first_keyword(), timeout=0.7)
+ except asyncio.TimeoutError:
+ kw = ""
+ assert kw == ""
+ finally:
+ stop_feed.set()
+ await src.put(None)
+ feeder.cancel()
+ try:
+ await feeder
+ except (asyncio.CancelledError, Exception): # noqa: BLE001, S110
+ pass
+
+
+async def test_detect_rejects_matching_high_no_speech_transcript() -> None:
+ """faster-whisper exposes per-segment no_speech_prob for silence/noise.
+
+ If that says the window probably contains no speech, a text match must not
+ wake the assistant.
+ """
+ import re
+
+ wake = RollingWhisperWake(
+ _PhraseSTT("hey ruben", confidence=0.9, no_speech_prob=0.95),
+ pattern=re.compile(r"hey\W+ruben", re.IGNORECASE),
+ poll_interval_s=0.01,
+ cooldown_s=0.0,
+ save_debug_wavs=False,
+ min_rms=0.0,
+ min_peak=0.0,
+ )
+
+ src: asyncio.Queue = asyncio.Queue()
+ stop_feed = asyncio.Event()
+
+ async def _iter():
+ while True:
+ chunk = await src.get()
+ if chunk is None:
+ return
+ yield chunk
+
+ async def _first_keyword() -> str:
+ async for kw in wake.detect(_iter()):
+ return kw
+ return ""
+
+ feeder = asyncio.create_task(_feed_until(src, stop_feed))
+ try:
+ try:
+ kw = await asyncio.wait_for(_first_keyword(), timeout=0.7)
+ except asyncio.TimeoutError:
+ kw = ""
+ assert kw == ""
+ finally:
+ stop_feed.set()
+ await src.put(None)
+ feeder.cancel()
+ try:
+ await feeder
+ except (asyncio.CancelledError, Exception): # noqa: BLE001, S110
+ pass
+
+
+async def test_consumer_keeps_draining_while_transcription_is_in_flight() -> None:
+ stt = _GatedSTT()
+ wake = RollingWhisperWake(
+ stt,
+ pattern=_NeverMatch(),
+ poll_interval_s=0.02,
+ cooldown_s=0.0,
+ save_debug_wavs=False,
+ min_rms=0.0,
+ min_peak=0.0,
+ )
+
+ src: asyncio.Queue = asyncio.Queue()
+ consumed = 0
+ stop_feed = asyncio.Event()
+
+ async def _iter():
+ nonlocal consumed
+ while True:
+ chunk = await src.get()
+ if chunk is None:
+ return
+ consumed += 1
+ yield chunk
+
+ async def _feeder() -> None:
+ # Emulate a live mic stream: chunks keep arriving regardless of how slow
+ # the STT is. A real mic never pauses for the transcriber.
+ i = 0
+ while not stop_feed.is_set():
+ await src.put(_loud_chunk(i))
+ i += 1
+ await asyncio.sleep(0.002)
+
+ async def _drive() -> None:
+ async for _kw in wake.detect(_iter()):
+ pass
+
+ feeder = asyncio.create_task(_feeder())
+ detect_task = asyncio.create_task(_drive())
+ try:
+ # Wait until the first (now-blocked) transcription is in flight.
+ await asyncio.wait_for(stt.first_call_started.wait(), timeout=3.0)
+ consumed_when_blocked = consumed
+
+ # The mic keeps streaming while the transcription is stuck.
+ await asyncio.sleep(0.3)
+ progressed = consumed - consumed_when_blocked
+
+ # Coupled (buggy) code is stuck on ``await transcribe`` and cannot pull
+ # from the iterator -> progressed ~= 0 (the queue just backs up, exactly
+ # the observed wsp_q=100). Decoupled (fixed) code keeps draining audio
+ # while the transcription runs -> progressed is large.
+ assert progressed >= 30, (
+ f"consumer blocked on in-flight transcription: progressed={progressed} "
+ f"chunks while a transcription was stuck (consumed={consumed}, "
+ f"was {consumed_when_blocked} when the transcribe started)"
+ )
+ # And it must not fire overlapping transcriptions while one is in flight.
+ assert stt.calls == 1, f"overlapping transcriptions in flight: {stt.calls}"
+ finally:
+ stop_feed.set()
+ stt.release.set()
+ await src.put(None)
+ feeder.cancel()
+ detect_task.cancel()
+ for t in (feeder, detect_task):
+ try:
+ await t
+ except (asyncio.CancelledError, Exception): # noqa: BLE001, S110
+ pass
diff --git a/tests/unit/speech/test_wake_live_apply.py b/tests/unit/speech/test_wake_live_apply.py
index 313d91b3c3..03fd1b33b4 100644
--- a/tests/unit/speech/test_wake_live_apply.py
+++ b/tests/unit/speech/test_wake_live_apply.py
@@ -13,6 +13,10 @@ from collections.abc import AsyncIterator
from dataclasses import dataclass
from types import SimpleNamespace
+import pytest
+
+from jarvis.speech import wake_constants as wc
+from jarvis.speech import wake_phrase as wp
from jarvis.speech.pipeline import SpeechPipeline
from jarvis.speech.wake_phrase import resolve_wake_plan
@@ -50,6 +54,21 @@ def _cfg(**kw: object) -> SimpleNamespace:
return SimpleNamespace(**base)
+def _pretend_oww_models_exist(
+ monkeypatch: pytest.MonkeyPatch, *model_names: str
+) -> None:
+ models = set(model_names)
+ original_resolve = wc.resolve_oww_model_path
+
+ def fake_resolve(model_name: str) -> str | None:
+ if model_name in models:
+ return f"C:/fake-openwakeword/{model_name}_v0.1.onnx"
+ return original_resolve(model_name)
+
+ monkeypatch.setattr(wc, "resolve_oww_model_path", fake_resolve)
+ monkeypatch.setattr(wp, "resolve_oww_model_path", fake_resolve)
+
+
def _pipe() -> SpeechPipeline:
return SpeechPipeline(
tts=_FakeTTS(), bus=None,
@@ -121,8 +140,11 @@ async def test_verify_oww_hit_still_verifies_jarvis() -> None:
# set_wake_plan — live reconfiguration (no restart)
# --------------------------------------------------------------------------
-def test_set_wake_plan_live_swaps_to_pretrained_model() -> None:
+def test_set_wake_plan_live_swaps_to_pretrained_model(
+ monkeypatch: pytest.MonkeyPatch,
+) -> None:
pipe = _pipe()
+ _pretend_oww_models_exist(monkeypatch, "alexa")
plan = resolve_wake_plan(_cfg(phrase="Alexa"), local_whisper_available=False)
pipe.set_wake_plan(plan)
diff --git a/tests/unit/speech/test_wake_phrase.py b/tests/unit/speech/test_wake_phrase.py
index b8c8795a8d..b721208389 100644
--- a/tests/unit/speech/test_wake_phrase.py
+++ b/tests/unit/speech/test_wake_phrase.py
@@ -16,6 +16,7 @@ from types import SimpleNamespace
import pytest
from jarvis.speech import wake_constants as wc
+from jarvis.speech import wake_phrase as wp
from jarvis.speech.wake_phrase import (
WakeMatcher,
compile_wake_matcher,
@@ -106,10 +107,18 @@ def test_arbitrary_phrase_tolerates_transcription_drift() -> None:
assert m.search("hey athena") is not None
-def test_prefix_phrase_strips_prefix_so_core_word_alone_matches() -> None:
- # "Hey Athena" -> core is "athena"; bare "athena" in the transcript fires.
+def test_arbitrary_phrase_tolerates_diacritic_transcription_drift() -> None:
+ # Cloud/local STT may add or remove accents for names. A typed wake word
+ # like "Ruben" must still fire when the transcript comes back as "Rubén".
+ m = compile_wake_matcher("Ruben")
+ assert m.search("hey rubén") is not None
+
+
+def test_prefix_phrase_requires_prefix_before_core_word() -> None:
+ # "Hey Athena" must not fire on bare "athena". Otherwise a name mention in
+ # ambient speech or Jarvis output re-triggers the listener without wake-up.
m = compile_wake_matcher("Hey Athena")
- assert m.search("athena") is not None
+ assert m.search("athena") is None
assert m.search("hey athena") is not None
@@ -164,6 +173,22 @@ def _cfg(**kw: object) -> SimpleNamespace:
return SimpleNamespace(**base)
+def _pretend_oww_models_exist(
+ monkeypatch: pytest.MonkeyPatch, *model_names: str
+) -> None:
+ """Make package-model tests independent of the local openwakeword install."""
+ models = set(model_names)
+ original_resolve = wc.resolve_oww_model_path
+
+ def fake_resolve(model_name: str) -> str | None:
+ if model_name in models:
+ return f"C:/fake-openwakeword/{model_name}_v0.1.onnx"
+ return original_resolve(model_name)
+
+ monkeypatch.setattr(wc, "resolve_oww_model_path", fake_resolve)
+ monkeypatch.setattr(wp, "resolve_oww_model_path", fake_resolve)
+
+
def _cfg_blank(**kw: object) -> SimpleNamespace:
"""Config with empty phrase — the new shipped default pre-onboarding state."""
base = dict(
@@ -187,7 +212,11 @@ def test_default_phrase_resolves_to_bundled_hey_jarvis_oww() -> None:
assert plan.degraded is False
-def test_known_pretrained_phrase_resolves_to_that_model() -> None:
+def test_known_pretrained_phrase_resolves_to_that_model(
+ monkeypatch: pytest.MonkeyPatch,
+) -> None:
+ _pretend_oww_models_exist(monkeypatch, "alexa")
+
plan = resolve_wake_plan(_cfg(phrase="Alexa"), local_whisper_available=False)
assert plan.engine == "openwakeword"
assert plan.oww_keyword == "alexa"
@@ -197,7 +226,11 @@ def test_known_pretrained_phrase_resolves_to_that_model() -> None:
assert plan.degraded is False
-def test_mycroft_and_rhasspy_resolve_to_pretrained_models() -> None:
+def test_mycroft_and_rhasspy_resolve_to_pretrained_models(
+ monkeypatch: pytest.MonkeyPatch,
+) -> None:
+ _pretend_oww_models_exist(monkeypatch, "hey_mycroft")
+
p1 = resolve_wake_plan(_cfg(phrase="Hey Mycroft"), local_whisper_available=False)
assert p1.oww_keyword == "hey_mycroft"
p2 = resolve_wake_plan(_cfg(phrase="Rhasspy"), local_whisper_available=False)
diff --git a/tests/unit/speech/test_warmup_timings.py b/tests/unit/speech/test_warmup_timings.py
new file mode 100644
index 0000000000..48088b1354
--- /dev/null
+++ b/tests/unit/speech/test_warmup_timings.py
@@ -0,0 +1,42 @@
+"""Per-loader timing for Phase A warm-up.
+
+The Phase A `asyncio.gather` hides which loader dominates, so a 28–52 s warm-up
+gave no signal about WHERE the time went. ``_gather_timed`` records each named
+loader's wall-clock so the boot can log per-loader ms (and tests/diagnostics can
+read it), even when a loader fails.
+"""
+from __future__ import annotations
+
+import asyncio
+
+from jarvis.speech.pipeline import _gather_timed
+
+
+async def test_gather_timed_records_each_task_duration() -> None:
+ async def fast() -> str:
+ return "f"
+
+ async def slow() -> str:
+ await asyncio.sleep(0.05)
+ return "s"
+
+ timings, results = await _gather_timed([("fast", fast), ("slow", slow)])
+
+ assert set(timings) == {"fast", "slow"}
+ assert timings["slow"] >= timings["fast"]
+ assert results == ["f", "s"] # order preserved
+
+
+async def test_gather_timed_records_duration_even_on_failure() -> None:
+ async def ok() -> int:
+ return 1
+
+ async def boom() -> None:
+ raise ValueError("x")
+
+ timings, results = await _gather_timed([("ok", ok), ("boom", boom)])
+
+ # Timing is captured for the failing task too (recorded in finally).
+ assert set(timings) == {"ok", "boom"}
+ assert results[0] == 1
+ assert isinstance(results[1], Exception) # gather(return_exceptions=True)
diff --git a/tests/unit/speech/test_warmup_two_phase.py b/tests/unit/speech/test_warmup_two_phase.py
index 5ea6612601..3b25e22455 100644
--- a/tests/unit/speech/test_warmup_two_phase.py
+++ b/tests/unit/speech/test_warmup_two_phase.py
@@ -275,10 +275,45 @@ async def test_ready_cue_played_after_phase_a(monkeypatch) -> None:
pipe = _new_pipe(monkeypatch, bus=FakeBus())
await pipe._warmup()
+ task = pipe._warmup_ready_cue_task
+ assert task is not None
+ await task
assert (READY_PCM, CHIME_SAMPLE_RATE) in pipe._player.play_pcm_calls
+async def test_ready_cue_does_not_block_wake_loop_start(monkeypatch) -> None:
+ """The ready chime must not sit between ready=True and the wake loop.
+
+ Live logs showed Phase A completing quickly, then ``_play_ready_cue`` holding
+ ``_warmup()`` for several seconds before ``Pipeline bereit`` and the wake
+ listener started. A wedged/slow output device must not keep the wake word
+ dead after the critical listening path is ready.
+ """
+ bus = FakeBus()
+ pipe = _new_pipe(monkeypatch, bus=bus)
+ cue_started = asyncio.Event()
+ cue_release = asyncio.Event()
+
+ async def _blocking_ready_cue() -> None:
+ cue_started.set()
+ await cue_release.wait()
+
+ pipe._play_ready_cue = _blocking_ready_cue # type: ignore[method-assign]
+
+ await asyncio.wait_for(pipe._warmup(), timeout=0.5)
+
+ boot_events = [e for e in bus.published if isinstance(e, VoiceBootStatus)]
+ assert any(e.ready for e in boot_events), "ready=True must be emitted"
+ await asyncio.wait_for(cue_started.wait(), timeout=0.5)
+
+ task = pipe._warmup_ready_cue_task
+ assert task is not None and not task.done()
+ cue_release.set()
+ await asyncio.wait_for(task, timeout=0.5)
+
+
@pytest.mark.asyncio
async def test_warmup_never_raises_without_bus(monkeypatch) -> None:
"""Headless / no-bus boot: emitting boot status is a guarded no-op."""
diff --git a/tests/unit/terminal/test_unix_pty.py b/tests/unit/terminal/test_unix_pty.py
index 33a5735c49..959abe9aba 100644
--- a/tests/unit/terminal/test_unix_pty.py
+++ b/tests/unit/terminal/test_unix_pty.py
@@ -129,9 +129,27 @@ def test_unix_backend_spawn_threads_args_through_to_ptyprocess(monkeypatch):
"argv": ["bash"],
"cwd": "/home/x",
"dimensions": (24, 80), # ptyprocess takes (rows, cols)
+ "env": None, # no env supplied -> inherit
}
+def test_unix_backend_threads_env_through(monkeypatch):
+ """A caller-supplied env must reach ptyprocess.PtyProcess.spawn(env=...).
+
+ The Antigravity brain/worker hardens the child PATH + drops API keys, so the
+ seam must forward env, not silently inherit os.environ.
+ """
+ fake_module = type(sys)("ptyprocess")
+ fake_module.PtyProcess = FakeBytesPtyProcess # type: ignore[attr-defined]
+ monkeypatch.setitem(sys.modules, "ptyprocess", fake_module)
+
+ backend = UnixPtyBackend()
+ backend.spawn(
+ argv=("agy",), cwd=None, cols=80, rows=24, env={"PATH": "/safe"}
+ )
+ assert FakeBytesPtyProcess.last_spawn["env"] == {"PATH": "/safe"}
+
+
def test_unix_backend_decodes_bytes_to_str_on_read():
"""ptyprocess.read returns bytes -> handle.read must return str."""
from jarvis.terminal.backend import _UnixPtyHandle
@@ -242,7 +260,7 @@ def test_fake_backend_records_spawn_args_and_echoes():
backend = FakePtyBackend(pid=321)
handle = backend.spawn(argv=("zsh", "-i"), cwd="/home", cols=100, rows=30)
assert backend.spawn_calls == [
- {"argv": ("zsh", "-i"), "cwd": "/home", "cols": 100, "rows": 30}
+ {"argv": ("zsh", "-i"), "cwd": "/home", "cols": 100, "rows": 30, "env": None}
]
assert handle.pid == 321
handle.write("echo round-trip")
diff --git a/tests/unit/test_config_writer_brain_provider_model_sync.py b/tests/unit/test_config_writer_brain_provider_model_sync.py
new file mode 100644
index 0000000000..b8ffb150c3
--- /dev/null
+++ b/tests/unit/test_config_writer_brain_provider_model_sync.py
@@ -0,0 +1,213 @@
+"""Tests for the two-layer ``[brain.providers.<p>]`` model persistence sync.
+
+Per-provider model pins (``model`` / ``deep_model``) are pinned in
+config-soll.json under the flat dotted key ``"brain.providers.<p>"``, so a
+model picked in the per-provider model selector that wrote only the TOML would
+be rolled back by the drift-guard within 5 minutes — the same BUG-010 class
+that hit ``brain.primary``. ``set_brain_provider_model`` must therefore write:
+
+ 1. ``jarvis.toml`` ``[brain.providers.<p>] model/deep_model`` (TOML)
+ 2. ``scripts/config-soll.json`` ``brain.providers.<p>`` (drift-soll)
+
+There is intentionally NO ENV layer: per-provider model keys have no effective
+``JARVIS__*`` boot override (the override parser only nests on ``__``, and the
+drift-guard's dotted ``JARVIS__BRAIN.PROVIDERS.*`` vars are inert), so adding
+one would only create a new stale-override trap.
+
+Layer 2 is best-effort (cloud-first): graceful no-op on a headless VPS, never
+raises out of ``set_brain_provider_model``, never breaks the TOML write.
+
+Uses TEMP files + monkeypatch only — never touches the live config.
+"""
+from __future__ import annotations
+
+import json
+from pathlib import Path
+
+import pytest
+
+from jarvis.core import config_writer
+
+
+def sample_toml(tmp_path: Path) -> Path:
+ p = tmp_path / "jarvis.toml"
+ p.write_text(
+ """\
+# Personal Jarvis config
+[brain]
+primary = "gemini"
+
+[brain.providers.gemini]
+model = "gemini-2.5-flash"
+deep_model = "gemini-2.5-pro"
+""",
+ encoding="utf-8",
+ )
+ return p
+
+
+def sample_soll(tmp_path: Path) -> Path:
+ p = tmp_path / "config-soll.json"
+ p.write_text(
+ json.dumps(
+ {
+ "_comment": "do not lose me",
+ "_updated": "2026-06-20",
+ "brain": {"primary": "gemini"},
+ "brain.providers.gemini": {
+ "model": "gemini-2.5-flash",
+ "deep_model": "gemini-2.5-pro",
+ },
+ "tts": {"provider": "cartesia"},
+ },
+ indent=2,
+ ),
+ encoding="utf-8",
+ )
+ return p
+
+
+def test_writes_toml_and_soll_no_env(
+ sample_toml: Path, sample_soll: Path, monkeypatch: pytest.MonkeyPatch
+) -> None:
+ monkeypatch.setattr(config_writer, "_config_soll_path", lambda: sample_soll)
+ env_calls: list[tuple[str, str]] = []
+ monkeypatch.setattr(
+ config_writer, "_set_user_env_var",
+ lambda name, value: env_calls.append((name, value)),
+ )
+
+ config_writer.set_brain_provider_model(
+ "gemini", model="gemini-3.5-flash", deep_model="gemini-3.1-pro-preview",
+ path=sample_toml,
+ )
+
+ # Layer 1: TOML.
+ toml_raw = sample_toml.read_text(encoding="utf-8")
+ assert 'model = "gemini-3.5-flash"' in toml_raw
+ assert 'deep_model = "gemini-3.1-pro-preview"' in toml_raw
+
+ # Layer 2: config-soll.json flat "brain.providers.gemini" key.
+ soll = json.loads(sample_soll.read_text(encoding="utf-8"))
+ assert soll["brain.providers.gemini"]["model"] == "gemini-3.5-flash"
+ assert soll["brain.providers.gemini"]["deep_model"] == "gemini-3.1-pro-preview"
+
+ # NO ENV layer for per-provider model keys.
+ assert env_calls == []
+
+
+def test_only_written_keys_are_synced(
+ sample_toml: Path, sample_soll: Path, monkeypatch: pytest.MonkeyPatch
+) -> None:
+ """Writing only ``model`` leaves the soll ``deep_model`` untouched."""
+ monkeypatch.setattr(config_writer, "_config_soll_path", lambda: sample_soll)
+ monkeypatch.setattr(config_writer, "_set_user_env_var", lambda name, value: None)
+
+ config_writer.set_brain_provider_model(
+ "gemini", model="gemini-3.5-flash", path=sample_toml,
+ )
+
+ soll = json.loads(sample_soll.read_text(encoding="utf-8"))
+ assert soll["brain.providers.gemini"]["model"] == "gemini-3.5-flash"
+ # deep_model in the soll block is NOT changed (only model was written).
+ assert soll["brain.providers.gemini"]["deep_model"] == "gemini-2.5-pro"
+
+
+def test_config_soll_preserves_other_keys(
+ sample_toml: Path, sample_soll: Path, monkeypatch: pytest.MonkeyPatch
+) -> None:
+ monkeypatch.setattr(config_writer, "_config_soll_path", lambda: sample_soll)
+ monkeypatch.setattr(config_writer, "_set_user_env_var", lambda name, value: None)
+
+ config_writer.set_brain_provider_model(
+ "gemini", model="gemini-3.5-flash", path=sample_toml,
+ )
+
+ soll = json.loads(sample_soll.read_text(encoding="utf-8"))
+ assert soll["_comment"] == "do not lose me"
+ assert soll["brain"]["primary"] == "gemini"
+ assert soll["tts"]["provider"] == "cartesia"
+
+
+def test_creates_soll_block_if_missing(
+ sample_toml: Path, sample_soll: Path, monkeypatch: pytest.MonkeyPatch
+) -> None:
+ """A provider with no soll block yet gets one created (not an error)."""
+ monkeypatch.setattr(config_writer, "_config_soll_path", lambda: sample_soll)
+ monkeypatch.setattr(config_writer, "_set_user_env_var", lambda name, value: None)
+
+ config_writer.set_brain_provider_model(
+ "claude-api", deep_model="claude-opus-4-8", path=sample_toml,
+ )
+
+ soll = json.loads(sample_soll.read_text(encoding="utf-8"))
+ assert soll["brain.providers.claude-api"]["deep_model"] == "claude-opus-4-8"
+
+
+def test_missing_config_soll_does_not_break_toml(
+ sample_toml: Path, tmp_path: Path, monkeypatch: pytest.MonkeyPatch
+) -> None:
+ nonexistent = tmp_path / "no-such-config-soll.json"
+ monkeypatch.setattr(config_writer, "_config_soll_path", lambda: nonexistent)
+ monkeypatch.setattr(config_writer, "_set_user_env_var", lambda name, value: None)
+
+ config_writer.set_brain_provider_model(
+ "gemini", model="gemini-3.5-flash", path=sample_toml,
+ )
+
+ assert 'model = "gemini-3.5-flash"' in sample_toml.read_text(encoding="utf-8")
+ assert not nonexistent.exists()
+
+
+def test_noop_when_both_none(
+ sample_toml: Path, sample_soll: Path, monkeypatch: pytest.MonkeyPatch
+) -> None:
+ """Both ``None`` → nothing written anywhere (idempotent early return)."""
+ monkeypatch.setattr(config_writer, "_config_soll_path", lambda: sample_soll)
+ monkeypatch.setattr(config_writer, "_set_user_env_var", lambda name, value: None)
+ before_toml = sample_toml.read_text(encoding="utf-8")
+ before_soll = sample_soll.read_text(encoding="utf-8")
+
+ config_writer.set_brain_provider_model("gemini", path=sample_toml)
+
+ assert sample_toml.read_text(encoding="utf-8") == before_toml
+ assert sample_soll.read_text(encoding="utf-8") == before_soll
+
+
+def test_writes_cu_model_to_toml_and_soll(
+ sample_toml: Path, sample_soll: Path, monkeypatch: pytest.MonkeyPatch
+) -> None:
+ """Phase 3: the per-provider Computer-Use model persists like model/deep_model."""
+ monkeypatch.setattr(config_writer, "_config_soll_path", lambda: sample_soll)
+ monkeypatch.setattr(config_writer, "_set_user_env_var", lambda name, value: None)
+
+ config_writer.set_brain_provider_model(
+ "gemini", cu_model="gemini-3.1-pro-preview", path=sample_toml,
+ )
+
+ toml_raw = sample_toml.read_text(encoding="utf-8")
+ assert 'cu_model = "gemini-3.1-pro-preview"' in toml_raw
+ # Untouched sibling keys remain.
+ assert 'model = "gemini-2.5-flash"' in toml_raw
+
+ soll = json.loads(sample_soll.read_text(encoding="utf-8"))
+ assert soll["brain.providers.gemini"]["cu_model"] == "gemini-3.1-pro-preview"
+ # Only cu_model synced — model/deep_model in the soll block stay as they were.
+ assert soll["brain.providers.gemini"]["model"] == "gemini-2.5-flash"
+ assert soll["brain.providers.gemini"]["deep_model"] == "gemini-2.5-pro"
+
+
+def test_cu_model_cleared_with_empty_string(
+ sample_toml: Path, sample_soll: Path, monkeypatch: pytest.MonkeyPatch
+) -> None:
+ """An empty cu_model writes "" (UI 'use my main model') — distinct from None
+ which means 'leave unchanged'."""
+ monkeypatch.setattr(config_writer, "_config_soll_path", lambda: sample_soll)
+ monkeypatch.setattr(config_writer, "_set_user_env_var", lambda name, value: None)
+
+ config_writer.set_brain_provider_model("gemini", cu_model="", path=sample_toml)
+
+ toml_raw = sample_toml.read_text(encoding="utf-8")
+ assert 'cu_model = ""' in toml_raw
diff --git a/tests/unit/test_grok_removal.py b/tests/unit/test_grok_removal.py
new file mode 100644
index 0000000000..473c7b2a2a
--- /dev/null
+++ b/tests/unit/test_grok_removal.py
@@ -0,0 +1,135 @@
+"""Regression guard: xAI Grok is removed as a BRAIN and SUB-AGENT provider and
+from the Ack-Brain, while Grok Voice (TTS) and the xAI credential stay (2026-06-22
+maintainer decision). Also pins Gemini as the recommended brain.
+
+The whole point of this file is that a future change which reintroduces Grok as a
+selectable/default/fallback brain or sub-agent — or which accidentally drops Grok
+Voice / the credential — fails loudly here instead of silently shipping.
+"""
+from __future__ import annotations
+
+
+def test_grok_is_not_a_selectable_brain_provider():
+ from jarvis.ui.web.provider_spec import PROVIDERS
+
+ brain_ids = {s.id for s in PROVIDERS if s.tier == "brain"}
+ assert "grok" not in brain_ids, brain_ids
+
+
+def test_grok_voice_tts_provider_and_credential_are_kept():
+ from jarvis.ui.web.provider_spec import PROVIDERS, all_secret_keys, get_spec
+
+ tts_ids = {s.id for s in PROVIDERS if s.tier == "tts"}
+ assert "grok-voice" in tts_ids, tts_ids
+ # The xAI key the Grok Voice plugin reads must still be a declared slot.
+ assert "grok_api_key" in all_secret_keys()
+ # And its help text must no longer advertise a (removed) Grok brain.
+ spec = get_spec("grok-voice")
+ assert spec is not None
+ assert "brain" not in (spec.credential_help or "").lower()
+
+
+def test_grok_absent_from_brain_model_catalog_but_tts_voice_kept():
+ from jarvis.brain.model_catalog import CATALOG_PROVIDERS, CURATED_MODELS, TTS_CATALOG
+
+ assert "grok" not in CATALOG_PROVIDERS
+ assert "grok" not in CURATED_MODELS
+ assert "grok-voice" in TTS_CATALOG # Grok Voice stays a selectable TTS voice
+
+
+def test_grok_absent_from_subagent_mapping():
+ from jarvis.missions.worker_runtime.provider_map import (
+ JARVIS_TO_OPENCLAW,
+ MAPPINGS,
+ OPENCLAW_TO_JARVIS,
+ )
+
+ assert "grok" not in {m.jarvis for m in MAPPINGS}
+ assert "grok" not in JARVIS_TO_OPENCLAW
+ assert "xai" not in OPENCLAW_TO_JARVIS
+
+
+def test_grok_absent_from_api_agent_subagent_slugs():
+ from jarvis.missions.init import _API_AGENT_SLUGS
+
+ assert "grok" not in _API_AGENT_SLUGS
+
+
+def test_grok_absent_from_ack_brain():
+ from jarvis.brain.ack_brain.config import SUPPORTED_PROVIDERS
+ from jarvis.brain.ack_brain.providers import REGISTRY
+
+ assert "grok" not in SUPPORTED_PROVIDERS
+ assert "grok" not in REGISTRY
+
+
+def test_grok_absent_from_frontier_resolver():
+ from jarvis.brain.frontier_resolver import SUPPORTED_PROVIDERS
+
+ assert "grok" not in SUPPORTED_PROVIDERS
+
+
+def test_grok_absent_from_brain_manager_tables():
+ from jarvis.brain.manager import (
+ _MAIN_BRAIN_FALLBACK_PROVIDER_ORDER,
+ _PROVIDER_DISPLAY_NAMES,
+ TIER_DEFAULTS_BY_PROVIDER,
+ )
+
+ assert "grok" not in TIER_DEFAULTS_BY_PROVIDER["router"]
+ assert "grok" not in TIER_DEFAULTS_BY_PROVIDER["deep"]
+ assert "grok" not in _MAIN_BRAIN_FALLBACK_PROVIDER_ORDER
+ assert "grok" not in _PROVIDER_DISPLAY_NAMES
+
+
+def test_grok_brain_entrypoint_removed_grok_voice_tts_kept():
+ from importlib.metadata import entry_points
+
+ brain = {e.name for e in entry_points(group="jarvis.brain")}
+ tts = {e.name for e in entry_points(group="jarvis.tts")}
+ assert "grok" not in brain, brain
+ assert "grok-voice" in tts, tts
+
+
+def test_gemini_is_the_recommended_brain():
+ from jarvis.ui.web.provider_spec import get_spec
+
+ gem = get_spec("gemini")
+ assert gem is not None
+ assert gem.tier == "brain"
+ assert gem.recommended is True
+ assert gem.recommended_model == "gemini-3.5-flash"
+ # The recommendation must be exclusive: no other provider carries the badge.
+ from jarvis.ui.web.provider_spec import PROVIDERS
+
+ recommended = {s.id for s in PROVIDERS if s.recommended}
+ assert recommended == {"gemini"}, recommended
+
+
+def test_provider_chain_last_ditch_fallback_is_no_longer_grok():
+ """The SubJarvisWorker last-ditch fallback used to be ('grok','grok-4.3').
+ With Grok out of MAPPINGS that hardcoded stub would crash ``to_provider_slug``
+ at spawn time, so the OpenClaw-routed fallback must no longer mention grok and
+ must use a provider that still maps to an OpenClaw slug.
+
+ (Note: a *configured* sub-agent provider can legitimately be a direct-worker
+ slug like ``antigravity``/``codex`` that has no OpenClaw mapping — that is the
+ worker factory's job, not this fallback's. This test only pins the hardcoded
+ last-ditch stub, which IS OpenClaw-routed.)
+ """
+ import inspect
+
+ import pytest
+
+ from jarvis.missions.worker_runtime.provider_map import (
+ UnknownJarvisProviderError,
+ to_provider_slug,
+ )
+ from jarvis.missions.workers import provider_chain
+
+ src = inspect.getsource(provider_chain)
+ assert "grok" not in src.lower(), "grok still referenced in provider_chain.py"
+ # The remaining gemini stub maps cleanly; the old grok stub would have raised.
+ to_provider_slug("gemini")
+ with pytest.raises(UnknownJarvisProviderError):
+ to_provider_slug("grok")
diff --git a/tests/unit/test_risk_tier.py b/tests/unit/test_risk_tier.py
index 1aa2eb7953..beb32dac16 100644
--- a/tests/unit/test_risk_tier.py
+++ b/tests/unit/test_risk_tier.py
@@ -1,6 +1,8 @@
"""Unit-Tests für RiskTierEvaluator."""
from __future__ import annotations
+import logging
+
import pytest
from jarvis.core.config import (
@@ -86,3 +88,122 @@ def test_needs_confirmation_whitelist_skips():
tool = _StubTool("delete_file", risk_tier="ask")
decision = ev.evaluate(tool, {"path": "/tmp/x"})
assert ev.needs_user_confirmation(decision) is False
+
+
+# ----------------------------------------------------------------------
+# Per-action risk (forensic 2026-06-19, session dc533e39): a read-only
+# ``gmail action=list_messages`` (the morning-routine "check unread mail"
+# step) was forced through the ask-tier confirmation and Jarvis spoke
+# "Soll ich die E-Mail wirklich senden?" for a calendar question. The
+# whole gmail tool declared risk_tier="ask" and ``evaluate`` only ever
+# looked at ``tool.risk_tier``, never at the action. A tool may now expose
+# an optional ``risk_tier_for_args(args)`` hook so reads stay ``safe`` and
+# only ``send_message`` is consequential.
+# ----------------------------------------------------------------------
+
+
+class _ActionTool:
+ """Stub tool with an optional per-action risk hook."""
+
+ def __init__(
+ self,
+ name: str,
+ risk_tier: str = "ask",
+ tiers: dict[str, str] | None = None,
+ ) -> None:
+ self.name = name
+ self.risk_tier = risk_tier
+ self.schema: dict = {}
+ self.description = ""
+ self._tiers = tiers or {}
+
+ def risk_tier_for_args(self, args):
+ return self._tiers.get((args.get("action") or "").strip())
+
+ async def execute(self, args, ctx): # pragma: no cover - stub
+ raise NotImplementedError
+
+
+def test_per_action_hook_downgrades_read_action():
+ ev = RiskTierEvaluator(_make_safety())
+ tool = _ActionTool(
+ "gmail", risk_tier="ask",
+ tiers={"list_messages": "safe", "send_message": "ask"},
+ )
+ decision = ev.evaluate(tool, {"action": "list_messages"})
+ assert decision.tier == "safe"
+ assert ev.needs_user_confirmation(decision) is False
+
+
+def test_per_action_hook_keeps_send_action_ask():
+ ev = RiskTierEvaluator(_make_safety())
+ tool = _ActionTool(
+ "gmail", risk_tier="ask",
+ tiers={"list_messages": "safe", "send_message": "ask"},
+ )
+ decision = ev.evaluate(tool, {"action": "send_message"})
+ assert decision.tier == "ask"
+ assert ev.needs_user_confirmation(decision) is True
+
+
+def test_per_action_hook_none_falls_back_to_static_tier():
+ # Hook returns None for an unmapped action → static tool tier wins.
+ ev = RiskTierEvaluator(_make_safety())
+ tool = _ActionTool("gmail", risk_tier="ask", tiers={})
+ decision = ev.evaluate(tool, {"action": "whatever"})
+ assert decision.tier == "ask"
+
+
+def test_per_action_hook_blacklist_still_wins():
+ # Blacklist is evaluated before the per-action hook can downgrade.
+ ev = RiskTierEvaluator(_make_safety(blacklist=["gmail send_message*"]))
+ tool = _ActionTool("gmail", risk_tier="ask", tiers={"send_message": "safe"})
+ with pytest.raises(ActionBlocked):
+ ev.evaluate(tool, {"action": "send_message"})
+
+
+def test_per_action_hook_exception_is_safe_and_falls_back(caplog):
+ class _BrokenTool(_ActionTool):
+ def risk_tier_for_args(self, args):
+ raise RuntimeError("boom")
+
+ ev = RiskTierEvaluator(_make_safety())
+ tool = _BrokenTool("gmail", risk_tier="ask")
+ with caplog.at_level(logging.WARNING):
+ decision = ev.evaluate(tool, {"action": "list_messages"})
+ # A broken hook must never crash the gate — it falls back to the
+ # conservative static tier, AND the anomaly is observable (not a silent
+ # swallow on the safety path).
+ assert decision.tier == "ask"
+ assert any("boom" in r.message or "raised" in r.message.lower() for r in caplog.records)
+
+
+def test_per_action_hook_invalid_tier_is_rejected_and_warns(caplog):
+ # A hook returning a value outside the RiskTier vocabulary (typo, wrong
+ # casing) must NOT be assigned silently — otherwise it would miss both the
+ # always_block and always_confirm membership checks and behave as the most
+ # permissive option with no signal. It is rejected → static tier wins.
+ ev = RiskTierEvaluator(_make_safety())
+ tool = _ActionTool("gmail", risk_tier="ask", tiers={"list_messages": "SAFE"})
+ with caplog.at_level(logging.WARNING):
+ decision = ev.evaluate(tool, {"action": "list_messages"})
+ assert decision.tier == "ask"
+ assert ev.needs_user_confirmation(decision) is True
+ assert any("SAFE" in r.message or "unknown tier" in r.message.lower()
+ for r in caplog.records)
+
+
+def test_invalid_static_risk_tier_falls_back_to_default():
+ # A misconfigured plugin with a truthy-but-invalid static tier must fall
+ # back to the config default, never carry the bogus value forward.
+ ev = RiskTierEvaluator(_make_safety(default_tier="monitor"))
+ tool = _StubTool("weird", risk_tier="bogus")
+ decision = ev.evaluate(tool, {})
+ assert decision.tier == "monitor"
+
+
+def test_tool_without_hook_is_unchanged():
+ ev = RiskTierEvaluator(_make_safety())
+ tool = _StubTool("delete_file", risk_tier="ask")
+ decision = ev.evaluate(tool, {"path": "x"})
+ assert decision.tier == "ask"
diff --git a/tests/unit/test_streaming_aggregate.py b/tests/unit/test_streaming_aggregate.py
index 4fa2a1978b..bd8dfb9fd7 100644
--- a/tests/unit/test_streaming_aggregate.py
+++ b/tests/unit/test_streaming_aggregate.py
@@ -6,6 +6,7 @@ from collections.abc import AsyncIterator
import pytest
from jarvis.brain import aggregate, tee_text
+from jarvis.brain.streaming import aggregate_first_json
from jarvis.core.protocols import BrainDelta
@@ -57,3 +58,117 @@ async def test_tee_text_only_yields_content():
])
out = [t async for t in tee_text(stream)]
assert out == ["A", "B"]
+
+
+# ---------------------------------------------------------------------------
+# aggregate_first_json — early-stop the moment a complete JSON action is seen.
+# Computer-Use action calls return a small JSON object/array; waiting for the
+# whole stream (finish_reason) wastes the tail latency on the #1 cost path.
+# ---------------------------------------------------------------------------
+
+
+async def test_aggregate_first_json_early_stops_on_complete_object():
+ """Closes the stream the instant a complete top-level object is parseable."""
+ consumed: list[str] = []
+
+ async def _src() -> AsyncIterator[BrainDelta]:
+ consumed.append("a"); yield BrainDelta(content='{"action": ')
+ consumed.append("b"); yield BrainDelta(content='"done"}')
+ consumed.append("c"); yield BrainDelta(content=" extra tokens the model rambled on")
+ consumed.append("d"); yield BrainDelta(finish_reason="stop")
+
+ agg = await aggregate_first_json(_src())
+ assert agg.text == '{"action": "done"}'
+ assert consumed == ["a", "b"] # closed right after the complete object
+
+
+async def test_aggregate_first_json_early_stops_on_complete_array():
+ """A batch (JSON array) closes only at its terminal ']'."""
+ consumed: list[str] = []
+
+ async def _src() -> AsyncIterator[BrainDelta]:
+ consumed.append("a"); yield BrainDelta(content='[{"action":"click","x":1,"y":2},')
+ consumed.append("b"); yield BrainDelta(content='{"action":"wait","ms":100}]')
+ consumed.append("c"); yield BrainDelta(content="\n```")
+
+ agg = await aggregate_first_json(_src())
+ assert agg.text.endswith("]")
+ assert consumed == ["a", "b"]
+
+
+async def test_aggregate_first_json_ignores_brackets_inside_strings():
+ """A '}' or ']' inside a string value must not be read as the end."""
+ consumed: list[str] = []
+
+ async def _src() -> AsyncIterator[BrainDelta]:
+ consumed.append("a"); yield BrainDelta(content='{"text": "a}b]c')
+ consumed.append("b"); yield BrainDelta(content='d", "action": "type"}')
+ consumed.append("c"); yield BrainDelta(content=" trailing")
+
+ agg = await aggregate_first_json(_src())
+ assert agg.text == '{"text": "a}b]cd", "action": "type"}'
+ assert consumed == ["a", "b"]
+
+
+async def test_aggregate_first_json_handles_fence_prefix():
+ """A leading ```json fence before the object is tolerated (scan starts at '{')."""
+ consumed: list[str] = []
+
+ async def _src() -> AsyncIterator[BrainDelta]:
+ consumed.append("a"); yield BrainDelta(content='```json\n{"action":"wait",')
+ consumed.append("b"); yield BrainDelta(content='"ms":50}\n```')
+ consumed.append("c"); yield BrainDelta(content="should not be read")
+
+ agg = await aggregate_first_json(_src())
+ assert '"ms":50}' in agg.text
+ assert consumed == ["a", "b"]
+
+
+async def test_aggregate_first_json_falls_back_to_full_stream_for_prose():
+ """No complete JSON -> behaves exactly like aggregate (reads the whole stream)."""
+ consumed: list[str] = []
+
+ async def _src() -> AsyncIterator[BrainDelta]:
+ consumed.append("a"); yield BrainDelta(content="I cannot ")
+ consumed.append("b"); yield BrainDelta(content="do that.")
+ consumed.append("c"); yield BrainDelta(finish_reason="stop")
+
+ agg = await aggregate_first_json(_src())
+ assert agg.text == "I cannot do that."
+ assert agg.finish_reason == "stop"
+ assert consumed == ["a", "b", "c"]
+
+
+def test_has_complete_json_action_caps_scan_on_oversized_text():
+ """Defensive bound: above a generous size cap (far over the action/planner
+ max_tokens), the scan is skipped (returns False -> the full aggregate takes
+ over) so a misbehaving provider streaming prose before the JSON cannot make
+ the per-delta scan quadratic. A normal-size action still early-stops."""
+ from jarvis.brain.streaming import _has_complete_json_action
+
+ assert _has_complete_json_action('{"action": "done"}') is True
+ # A *valid* but absurdly large object (>> any real 256/512-token response):
+ # not early-stopped, degrades safely to the full-stream aggregate.
+ oversized = '{"action":"type","text":"' + ("x" * 20000) + '"}'
+ assert _has_complete_json_action(oversized) is False
+
+
+async def test_aggregate_first_json_does_not_stop_on_empty_object_braces():
+ """'{}' is balanced but not a usable action; an empty {} alone is still
+ returned (parseable JSON) — the action parser rejects it downstream. This
+ documents that the early-stop fires on the first *parseable* top-level JSON."""
+ consumed: list[str] = []
+
+ async def _src() -> AsyncIterator[BrainDelta]:
+ consumed.append("a"); yield BrainDelta(content="{}")
+ consumed.append("b"); yield BrainDelta(content="more")
+
+ agg = await aggregate_first_json(_src())
+ assert agg.text == "{}"
+ assert consumed == ["a"]
diff --git a/tests/unit/test_tier_defaults.py b/tests/unit/test_tier_defaults.py
index 8da5eb3309..f25faba8f2 100644
--- a/tests/unit/test_tier_defaults.py
+++ b/tests/unit/test_tier_defaults.py
@@ -12,7 +12,7 @@ from jarvis.brain.manager import (
class TestTierDefaultsCatalog:
def test_all_known_providers_have_router_defaults(self):
- required = {"claude-api", "gemini", "openai", "grok"}
+ required = {"claude-api", "gemini", "openai"}
assert required <= set(TIER_DEFAULTS_BY_PROVIDER["router"])
def test_all_known_providers_have_deep_defaults(self):
@@ -23,23 +23,19 @@ class TestTierDefaultsCatalog:
# 2026-04-29 Update: GPT-5.5 hat keine -mini-Variante released; OpenAI
# sagt selbst "GPT-5.5 hat per-token-Latenz wie GPT-5.4". Fast-Tier-
# Heuristik akzeptiert daher auch Frontier-Hauptmodelle.
- # 2026-04-30 Update: xAI hat grok-4.3 als gleichzeitig schnellstes
- # UND intelligentestes Grok released — keine -fast-Variante mehr.
# Siehe TIER_DEFAULTS_BY_PROVIDER-Doc in jarvis/brain/manager.py.
for provider, model in TIER_DEFAULTS_BY_PROVIDER["router"].items():
if provider == "gemini":
continue # hat keinen Fast-Mode
if provider == "openai" and model in {"gpt-5.5", "gpt-5"}:
continue # Frontier-Hauptmodell ohne -mini-Suffix
- if provider == "grok" and model.startswith("grok-4"):
- continue # Frontier-Hauptmodell ohne -fast-Suffix
assert any(tag in model.lower() for tag in ("haiku", "flash", "mini", "fast", "chat", "small")), \
f"{provider}: {model} sieht nicht nach Fast-Tier aus"
def test_sub_models_look_frontier(self):
for provider, model in TIER_DEFAULTS_BY_PROVIDER["deep"].items():
assert any(tag in model.lower() for tag in
- ("fable", "opus", "pro", "large", "reasoner", "gpt-4", "gpt-5", "grok-4")), \
+ ("fable", "opus", "pro", "large", "reasoner", "gpt-4", "gpt-5")), \
f"{provider}: {model} sieht nicht nach Frontier-Tier aus"
def test_claude_deep_tier_is_reachable_opus_never_fable(self):
diff --git a/tests/unit/ui/test_orb_bus_bridge.py b/tests/unit/ui/test_orb_bus_bridge.py
index 5468afff4c..ecf47c4873 100644
--- a/tests/unit/ui/test_orb_bus_bridge.py
+++ b/tests/unit/ui/test_orb_bus_bridge.py
@@ -1,5 +1,6 @@
from __future__ import annotations
+import asyncio
import sys
from pathlib import Path
@@ -35,6 +36,8 @@ from jarvis.core.events import (
ResponseGenerated,
SystemStateChanged,
TranscriptionUpdate,
+ WakeWordDetected,
+ VoiceBootStatus,
VoiceSessionEnded,
VoiceSessionStarted,
)
@@ -45,6 +48,14 @@ class _FakeBus:
pass
+class _RecordingBus:
+ def __init__(self) -> None:
+ self.subscriptions = []
+
+ def subscribe(self, event_type, handler) -> None:
+ self.subscriptions.append((event_type, handler))
+
+
class _FakeOrb:
def __init__(self) -> None:
self.calls: list[tuple[str, str | None]] = []
@@ -567,6 +578,87 @@ async def test_reply_is_reset_between_turns() -> None:
assert ("show_listening_transcript", "Antwort aus Turn 1.") not in orb.calls
+# --- Boot readiness gate: the persistent bar stays hidden until voice is ready.
+# The persistent WhisperBar used to map its window the instant its mainloop ran,
+# i.e. during backend boot — seconds before the speech pipeline could actually
+# hear "Hey Jarvis". The user saw the bar and assumed Jarvis was listening when
+# it was not. The bridge now reveals the persistent bar only on the existing
+# VoiceBootStatus(ready=True) signal (with a bounded fallback so a voice-offline
+# host still gets its bar).
+
+
+async def test_persistent_bar_waits_for_voice_ready_then_reveals_once() -> None:
+ orb = _FakeOrb()
+ bridge = OrbBusBridge( # type: ignore[arg-type]
+ bus=_FakeBus(), orb=orb, idle_animations_enabled=False, hide_on_idle=False
+ )
+
+ task = asyncio.create_task(bridge.reveal_bar_when_voice_ready(timeout_s=5.0))
+ await asyncio.sleep(0.05)
+ # No ready signal yet → the persistent bar must NOT be shown.
+ assert ("show", "idle") not in orb.calls
+
+ await bridge._on_voice_boot_status(VoiceBootStatus(ready=True)) # noqa: SLF001
+ await asyncio.wait_for(task, timeout=1.0)
+
+ # Revealed exactly once.
+ assert orb.calls.count(("show", "idle")) == 1
+
+
+async def test_voice_boot_status_not_ready_does_not_reveal_bar() -> None:
+ orb = _FakeOrb()
+ bridge = OrbBusBridge( # type: ignore[arg-type]
+ bus=_FakeBus(), orb=orb, idle_animations_enabled=False, hide_on_idle=False
+ )
+
+ # ready=False is emitted at warm-up start — it must not reveal the bar.
+ await bridge._on_voice_boot_status(VoiceBootStatus(ready=False)) # noqa: SLF001
+ assert ("show", "idle") not in orb.calls
+
+
+async def test_persistent_bar_revealed_by_timeout_when_ready_never_comes() -> None:
+ """A voice-offline host (pipeline crashed at startup, no mic) never emits
+ ready=True. The bar must still appear after a bounded fallback so the user
+ is not left with no bar at all — just a few seconds late instead of never."""
+ orb = _FakeOrb()
+ bridge = OrbBusBridge( # type: ignore[arg-type]
+ bus=_FakeBus(), orb=orb, idle_animations_enabled=False, hide_on_idle=False
+ )
+
+ await bridge.reveal_bar_when_voice_ready(timeout_s=0.05)
+
+ assert ("show", "idle") in orb.calls
+
+
+async def test_non_persistent_surface_not_revealed_on_voice_ready() -> None:
+ """A non-persistent bar / the mascot (hide_on_idle=True) is hidden at idle
+ by design — it pops on a real session. The boot-ready reveal must leave it
+ untouched."""
+ orb = _FakeOrb()
+ bridge = OrbBusBridge( # type: ignore[arg-type]
+ bus=_FakeBus(), orb=orb, idle_animations_enabled=False, hide_on_idle=True
+ )
+
+ await bridge._on_voice_boot_status(VoiceBootStatus(ready=True)) # noqa: SLF001
+ await bridge.reveal_bar_when_voice_ready(timeout_s=0.05)
+
+ assert ("show", "idle") not in orb.calls
+
+
+async def test_boot_reveal_is_idempotent_across_ready_and_timeout() -> None:
+ orb = _FakeOrb()
+ bridge = OrbBusBridge( # type: ignore[arg-type]
+ bus=_FakeBus(), orb=orb, idle_animations_enabled=False, hide_on_idle=False
+ )
+
+ await bridge._on_voice_boot_status(VoiceBootStatus(ready=True)) # noqa: SLF001
+ await bridge.reveal_bar_when_voice_ready(timeout_s=1.0)
+ # A second invocation (e.g. a stray late call) must not show the bar twice.
+ await bridge.reveal_bar_when_voice_ready(timeout_s=0.05)
+
+ assert orb.calls.count(("show", "idle")) == 1
+
+
async def test_listening_bubble_mirrors_pipeline_snapshot_one_to_one() -> None:
"""Pendel-Episode 3 regression (2026-05-27).
@@ -767,6 +859,33 @@ async def test_session_start_shows_listening_when_listening_state_is_deduped() -
assert ("show_listening_transcript", "") in orb.calls
+async def test_confirmed_wake_word_pops_orb_before_session_start() -> None:
+ """The first visual response should be tied to the confirmed wake event.
+
+ ``VoiceSessionStarted`` is published by the state loop after wake handling.
+ Waiting for it adds a small but visible delay after the selected wake phrase.
+ ``WakeWordDetected`` is already emitted only after wake verification, so it
+ is the earliest safe signal for the orb to appear.
+ """
+ orb = _FakeOrb()
+ bridge = OrbBusBridge(bus=_FakeBus(), orb=orb, idle_animations_enabled=False) # type: ignore[arg-type]
+
+ await bridge._on_wake_word_detected(WakeWordDetected(keyword="hey_ruben")) # noqa: SLF001
+
+ assert ("show", "listen") in orb.calls
+ assert ("show_listening_transcript", "") not in orb.calls
+
+
+def test_attach_subscribes_to_confirmed_wake_word_for_immediate_pop() -> None:
+ bus = _RecordingBus()
+ orb = _FakeOrb()
+ bridge = OrbBusBridge(bus=bus, orb=orb, idle_animations_enabled=False) # type: ignore[arg-type]
+
+ bridge.attach()
+
+ assert (WakeWordDetected, bridge._on_wake_word_detected) in bus.subscriptions # noqa: SLF001
+
+
async def test_session_start_drives_mic_equalizer_immediately() -> None:
"""The bar's equalizer reacts to mic loudness only while the bridge
considers the state LISTENING. After a session starts (even when the
diff --git a/tests/unit/ui/test_provider_spec_antigravity.py b/tests/unit/ui/test_provider_spec_antigravity.py
index 62c6e44899..08f146588a 100644
--- a/tests/unit/ui/test_provider_spec_antigravity.py
+++ b/tests/unit/ui/test_provider_spec_antigravity.py
@@ -15,6 +15,7 @@ def test_antigravity_provider_spec():
spec = get_spec("antigravity")
assert spec is not None
assert spec.tier == "brain"
+ assert spec.brain_switchable is False
assert spec.auth_mode == "antigravity"
assert spec.secret_keys == () # OAuth-only, no API-key slot
assert spec.login_cli is not None
@@ -25,3 +26,12 @@ def test_antigravity_provider_spec():
def test_antigravity_excluded_from_live_catalog():
# No /v1/models endpoint over OAuth — must not be live-fetched.
assert "antigravity" not in model_catalog.CATALOG_PROVIDERS
+
+
+def test_codex_provider_spec_is_subagent_only():
+ spec = get_spec("codex")
+ assert spec is not None
+ assert spec.tier == "brain"
+ assert spec.brain_switchable is False
+ assert spec.auth_mode == "codex"
+ assert spec.login_cli == ("codex", "login")
diff --git a/tests/unit/ui/test_wake_word_route.py b/tests/unit/ui/test_wake_word_route.py
index 1ed2ad95c3..f412f1b82c 100644
--- a/tests/unit/ui/test_wake_word_route.py
+++ b/tests/unit/ui/test_wake_word_route.py
@@ -7,6 +7,8 @@ from fastapi import FastAPI
from fastapi.testclient import TestClient
from jarvis.core.config import WakeWordConfig
+from jarvis.speech import wake_constants as wc
+from jarvis.speech import wake_phrase as wp
from jarvis.ui.web.settings_routes import router
@@ -34,6 +36,19 @@ def _client(
return TestClient(app)
+def _pretend_oww_models_exist(monkeypatch, *model_names: str) -> None:
+ models = set(model_names)
+ original_resolve = wc.resolve_oww_model_path
+
+ def fake_resolve(model_name: str) -> str | None:
+ if model_name in models:
+ return f"C:/fake-openwakeword/{model_name}_v0.1.onnx"
+ return original_resolve(model_name)
+
+ monkeypatch.setattr(wc, "resolve_oww_model_path", fake_resolve)
+ monkeypatch.setattr(wp, "resolve_oww_model_path", fake_resolve)
+
+
def test_get_returns_current_and_options() -> None:
body = _client().get("/api/settings/wake-word").json()
assert body["phrase"] == ""
@@ -43,7 +58,9 @@ def test_get_returns_current_and_options() -> None:
assert isinstance(body["local_whisper_available"], bool)
-def test_put_known_phrase_resolves_to_openwakeword() -> None:
+def test_put_known_phrase_resolves_to_openwakeword(monkeypatch) -> None:
+ _pretend_oww_models_exist(monkeypatch, "alexa")
+
resp = _client().put(
"/api/settings/wake-word",
json={"phrase": "Alexa", "engine": "auto", "persist": False},
@@ -57,9 +74,10 @@ def test_put_known_phrase_resolves_to_openwakeword() -> None:
assert body["persisted"] is False
-def test_put_live_applies_to_running_pipeline() -> None:
+def test_put_live_applies_to_running_pipeline(monkeypatch) -> None:
# The fix for "only Hey Jarvis works": a save must reconfigure the live
# pipeline (no restart) when one is running.
+ _pretend_oww_models_exist(monkeypatch, "alexa")
pipe = _FakePipeline()
resp = _client(pipeline=pipe).put(
"/api/settings/wake-word",
diff --git a/tests/unit/ui/web/test_drop_routes.py b/tests/unit/ui/web/test_drop_routes.py
new file mode 100644
index 0000000000..75e1924d20
--- /dev/null
+++ b/tests/unit/ui/web/test_drop_routes.py
@@ -0,0 +1,121 @@
+"""REST-route tests for the drag-drop intake (`POST /api/chat/drop`).
+
+The dock / overlay POSTs dropped files (+ optional dragged text) as multipart;
+the route captures them as SILENT context via ``brain.add_dropped_context`` — it
+never triggers a brain turn. Mirrors the avatar-upload pattern (size cap).
+"""
+from __future__ import annotations
+
+from fastapi import FastAPI
+from fastapi.testclient import TestClient
+
+from jarvis.ui.web.drop_routes import router as drop_router
+
+
+class _FakeBrain:
+ def __init__(self) -> None:
+ self.dropped: list[tuple] = []
+
+ def add_dropped_context(self, text, images=()) -> None:
+ self.dropped.append((text, images))
+
+
+class _FakeBus:
+ def __init__(self) -> None:
+ self.published: list[object] = []
+
+ async def publish(self, event: object) -> None:
+ self.published.append(event)
+
+
+def _client(brain: object, bus: _FakeBus | None = None) -> TestClient:
+ app = FastAPI()
+ app.include_router(drop_router)
+ app.state.brain = brain
+ app.state.bus = bus or _FakeBus()
+ return app, TestClient(app)
+
+
+def test_drop_file_captures_context_no_turn() -> None:
+ brain = _FakeBrain()
+ bus = _FakeBus()
+ app, client = _client(brain, bus)
+
+ resp = client.post(
+ "/api/chat/drop",
+ files=[("files", ("notes.txt", b"hello from a dropped file", "text/plain"))],
+ data={"thread_id": "t1"},
+ )
+
+ assert resp.status_code == 200
+ assert resp.json()["dispatched"] is True
+ assert len(brain.dropped) == 1
+ assert "notes.txt" in brain.dropped[0][0]
+ # No turn-triggering event published.
+ assert bus.published == []
+
+
+def test_drop_image_captured_as_context_image() -> None:
+ brain = _FakeBrain()
+ _app, client = _client(brain)
+
+ resp = client.post(
+ "/api/chat/drop",
+ files=[("files", ("pic.png", b"\x89PNGdata", "image/png"))],
+ data={"thread_id": "t2"},
+ )
+
+ assert resp.status_code == 200
+ assert len(brain.dropped) == 1
+ _text, images = brain.dropped[0]
+ assert len(images) == 1
+
+
+def test_drop_dragged_text_only_captured() -> None:
+ brain = _FakeBrain()
+ _app, client = _client(brain)
+
+ resp = client.post(
+ "/api/chat/drop",
+ data={"thread_id": "t3", "text": "https://example.com/page"},
+ )
+
+ assert resp.status_code == 200
+ assert resp.json()["dispatched"] is True
+ assert "example.com" in brain.dropped[0][0]
+
+
+def test_empty_drop_captures_nothing() -> None:
+ brain = _FakeBrain()
+ _app, client = _client(brain)
+
+ resp = client.post("/api/chat/drop", data={"thread_id": "t4"})
+
+ assert resp.status_code == 200
+ assert resp.json()["dispatched"] is False
+ assert brain.dropped == []
+
+
+def test_no_brain_returns_503() -> None:
+ _app, client = _client(None)
+ resp = client.post(
+ "/api/chat/drop",
+ files=[("files", ("notes.txt", b"hi", "text/plain"))],
+ data={"thread_id": "t1"},
+ )
+ assert resp.status_code == 503
+
+
+def test_oversized_drop_is_rejected() -> None:
+ brain = _FakeBrain()
+ _app, client = _client(brain)
+ huge = b"x" * (30 * 1024 * 1024) # 30 MB > cap
+
+ resp = client.post(
+ "/api/chat/drop",
+ files=[("files", ("big.bin", huge, "application/octet-stream"))],
+ data={"thread_id": "t5"},
+ )
+
+ assert resp.status_code == 413
+ assert brain.dropped == []
diff --git a/tests/unit/ui/web/test_skills_routes.py b/tests/unit/ui/web/test_skills_routes.py
index fbdc73716a..7914fd5830 100644
--- a/tests/unit/ui/web/test_skills_routes.py
+++ b/tests/unit/ui/web/test_skills_routes.py
@@ -218,34 +218,81 @@ def test_bulk_delete_prunes_prefs(skills_root: Path) -> None:
assert "beta" not in overrides
-# --- optional-module route guards (Skill Creator / link-health) -------------
-# These features depend on optional modules (``jarvis.skills.creator_service``,
-# ``jarvis.skills.link_health``) that are not shipped in every build. When the
-# module is absent the route must answer a clean ``501 Not Implemented`` with an
-# honest message — never leak an unhandled ``ModuleNotFoundError`` as a 500. The
-# tests assert the absent-module behaviour that holds while those modules ship
-# separately; once a module is present its route is expected to work and these
-# guards become inert.
+# --- Skill Creator routes (deterministic, no brain in tests) ----------------
+# ``jarvis.skills.creator_service`` is now shipped, so the creator routes work.
+# With no brain wired on ``app.state`` they return the deterministic skeleton
+# draft (``brain_used`` False) — the cloud-first fallback that must always work.
+# The ``link-health`` route still 501s while its optional module is absent.
-def test_creator_draft_returns_clean_501_when_service_module_absent(
+def test_creator_draft_returns_valid_skeleton_without_brain(
skills_root: Path,
) -> None:
client, _reg = _client(skills_root)
- res = client.post("/api/skills/creator/draft", json={"intent": "make a thing"})
- assert res.status_code == 501, res.text
- assert "not available" in res.json()["detail"].lower()
+ res = client.post(
+ "/api/skills/creator/draft",
+ json={"intent": "pause spotify when I talk", "name_hint": "Spotify Pause"},
+ )
+ assert res.status_code == 200, res.text
+ body = res.json()
+ assert body["brain_used"] is False
+ assert body["draft"]["name"]
+ assert body["validation"]["ok"] is True
-def test_creator_validate_returns_clean_501_when_service_module_absent(
- skills_root: Path,
-) -> None:
+def test_creator_validate_checks_skill_md(skills_root: Path) -> None:
+ client, _reg = _client(skills_root)
+ ok = client.post(
+ "/api/skills/creator/validate",
+ json={"skill_md": '---\nschema_version: "1"\nname: X\n---\n\n## B\n'},
+ )
+ assert ok.status_code == 200, ok.text
+ assert ok.json()["validation"]["ok"] is True
+
+ bad = client.post(
+ "/api/skills/creator/validate",
+ json={"skill_md": "no frontmatter here"},
+ )
+ assert bad.status_code == 200, bad.text
+ assert bad.json()["validation"]["ok"] is False
+
+
+def test_create_skill_endpoint_writes_and_lists(skills_root: Path) -> None:
client, _reg = _client(skills_root)
res = client.post(
- "/api/skills/creator/validate", json={"skill_md": "---\nname: x\n---\n"}
+ "/api/skills",
+ json={"name": "Form Made Skill", "description": "from the form", "body": "## x\n"},
)
- assert res.status_code == 501, res.text
- assert "not available" in res.json()["detail"].lower()
+ assert res.status_code == 200, res.text
+ assert res.json()["name"] == "Form Made Skill"
+ names = [s["name"] for s in client.get("/api/skills").json()["skills"]]
+ assert "Form Made Skill" in names
+
+
+def test_create_skill_endpoint_rejects_duplicate(skills_root: Path) -> None:
+ client, _reg = _client(skills_root)
+ client.post("/api/skills", json={"name": "Dup", "body": "## x\n"})
+ res = client.post("/api/skills", json={"name": "Dup", "body": "## y\n"})
+ assert res.status_code == 409, res.text
+
+
+def test_creator_commit_persists_reviewed_draft(skills_root: Path) -> None:
+ client, _reg = _client(skills_root)
+ draft = {
+ "name": "Committed Via Route",
+ "description": "desc",
+ "category": "general",
+ "tags": [],
+ "triggers": [],
+ "requires_tools": [],
+ "risk_policy": {"default_tier": "ask"},
+ "body": "## Committed Via Route\n\nDo it.\n",
+ }
+ res = client.post("/api/skills/creator/commit", json={"draft": draft})
+ assert res.status_code == 200, res.text
+ assert res.json()["name"] == "Committed Via Route"
+ names = [s["name"] for s in client.get("/api/skills").json()["skills"]]
+ assert "Committed Via Route" in names
def test_link_health_returns_clean_501_when_module_absent(skills_root: Path) -> None:
diff --git a/tests/unit/ui/whisperbar/test_interaction.py b/tests/unit/ui/whisperbar/test_interaction.py
index e59d35ab53..2b7b71bfef 100644
--- a/tests/unit/ui/whisperbar/test_interaction.py
+++ b/tests/unit/ui/whisperbar/test_interaction.py
@@ -2,6 +2,7 @@
from __future__ import annotations
from jarvis.ui.whisperbar import interaction as I
+from jarvis.ui.whisperbar import renderer as R
def test_is_drag_threshold():
@@ -15,27 +16,65 @@ def test_classify_release():
assert I.classify_release(moved=True) == "drag"
-def test_click_action_talk_when_idle_hangup_when_active():
- assert I.click_action("idle") == "talk"
- assert I.click_action("listen") == "hangup"
- assert I.click_action("think") == "hangup"
- assert I.click_action("speak") == "hangup"
- assert I.click_action("bogus") == "talk" # unknown → safe default (talk)
-
-
-def test_resolve_click_zones():
+def test_resolve_click_idle_and_dictate_zones():
W = 100
- # right third → the square → dictate (toggle), regardless of state
+ # right zone → the square → dictate (non-destructive), regardless of state
assert I.resolve_click(90, W, "idle") == "dictate"
assert I.resolve_click(90, W, "listen") == "dictate"
- # left third → the X → hangup ONLY while a session is active
- assert I.resolve_click(10, W, "listen") == "hangup"
+ # idle → a click anywhere starts a normal session
assert I.resolve_click(10, W, "idle") == "talk" # idle left → start normal session
- # middle → start a normal session when idle, nothing when active
assert I.resolve_click(50, W, "idle") == "talk"
+ # active middle (no control there) → nothing
assert I.resolve_click(50, W, "speak") == "none"
+def test_active_bar_body_click_does_not_hang_up():
+ """REGRESSION — the silent-hangup trap (live bug 2026-06-19).
+
+ A low-intent click on the BODY of an active bar — where the user sees only
+ the equalizer / orbital-core and NO close-X (the X is drawn only on hover,
+ renderer.py) — must NOT end the session. The old code treated the whole
+ left 40% of the bar as the hang-up X, so any such click silently hung up
+ ("Jarvis legt von selbst auf, ich hab nichts von Auflegen gesagt").
+ """
+ W, PW = 100, 100
+ # Left-of-centre body, past the X glyph (centre ≈ cx - 0.42*pw = 8) → none,
+ # even with the controls shown and across every active state.
+ assert I.resolve_click(35, W, "speak", hovered=True, pill_w=PW) == "none"
+ assert I.resolve_click(35, W, "listen", hovered=True, pill_w=PW) == "none"
+ assert I.resolve_click(35, W, "think", hovered=True, pill_w=PW) == "none"
+
+
+def test_hangup_requires_visible_close_x():
+ """A hang-up fires only when the close-X is actually shown (hovered) AND the
+ click lands on the X glyph — so behaviour matches the visible affordance."""
+ W, PW = 100, 100
+ # X glyph centre ≈ cx - 0.42*pw = 8 for these dimensions.
+ # On the X, controls visible → hang up (the deliberate gesture still works).
+ assert I.resolve_click(8, W, "speak", hovered=True, pill_w=PW) == "hangup"
+ # Same spot, but the controls are NOT shown (not hovered) → no hang up.
+ assert I.resolve_click(8, W, "speak", hovered=False, pill_w=PW) == "none"
+ # Hovered, but the click is far from the X (centre of the bar) → no hang up.
+ assert I.resolve_click(50, W, "speak", hovered=True, pill_w=PW) == "none"
+
+
+def test_hangup_hitbox_at_real_bar_geometry():
+ """Anchor the contract to the ACTUAL deployed pill, not just W=PW=100.
+
+ At the real dims the close-X glyph sits at WIN_W/2 - 0.42*ACTIVE_W, the
+ equalizer bars start ~24px in, and the bar window is only ~107px wide — so a
+ centre click (over the bars) must NOT hang up while a click on the X does.
+ """
+ W, PW = R.WIN_W, R.ACTIVE_W
+ x_glyph = round(W / 2.0 - 0.42 * PW) # mirror renderer._draw_close_x centre
+ # Deliberate click on the visible X glyph, controls shown → hang up.
+ assert I.resolve_click(x_glyph, W, "speak", hovered=True, pill_w=PW) == "hangup"
+ # The bar's centre (where the live equalizer is drawn) → never a hang up.
+ assert I.resolve_click(round(W / 2.0), W, "speak", hovered=True, pill_w=PW) == "none"
+ # Controls not shown → even the X spot is inert.
+ assert I.resolve_click(x_glyph, W, "speak", hovered=False, pill_w=PW) == "none"
+
+
def test_default_bottom_center_placement():
x, y = I.default_bottom_center(
screen_w=1920, screen_h=1080, bar_w=300, bar_h=72, margin=12
diff --git a/tests/unit/ui/whisperbar/test_start_hidden.py b/tests/unit/ui/whisperbar/test_start_hidden.py
new file mode 100644
index 0000000000..601cc3eea0
--- /dev/null
+++ b/tests/unit/ui/whisperbar/test_start_hidden.py
@@ -0,0 +1,34 @@
+"""A persistent WhisperBar must be able to start HIDDEN at boot.
+
+The persistent bar normally maps its Tk window the moment the mainloop runs
+(no ``withdraw``), so on boot it appears seconds before the speech pipeline can
+actually hear the user — the "looks ready but isn't" boot confusion. The boot
+wiring opts the persistent bar into ``start_hidden=True`` and only reveals it
+once voice is ready; these tests pin the start-withdrawn decision so the boot
+path stays headless-testable (no real Tk window needed).
+"""
+from __future__ import annotations
+
+from jarvis.ui.whisperbar.overlay import WhisperBarOverlay
+
+
+def test_persistent_bar_with_start_hidden_starts_withdrawn() -> None:
+ bar = WhisperBarOverlay(persistent=True, start_hidden=True)
+ assert bar._start_hidden is True
+ assert bar._should_start_withdrawn() is True
+
+
+def test_persistent_bar_default_does_not_start_withdrawn() -> None:
+ # Backward compatibility: without start_hidden a persistent bar is mapped
+ # immediately, exactly as before (e.g. the live swap / set_bar_persistent
+ # paths that explicitly show it after construction).
+ bar = WhisperBarOverlay(persistent=True)
+ assert bar._start_hidden is False
+ assert bar._should_start_withdrawn() is False
+
+
+def test_non_persistent_bar_starts_withdrawn_regardless() -> None:
+ # The non-persistent bar already starts hidden (pops on a session); the new
+ # flag must not change that.
+ bar = WhisperBarOverlay(persistent=False)
+ assert bar._should_start_withdrawn() is True
diff --git a/tests/unit/vision/test_image_budget.py b/tests/unit/vision/test_image_budget.py
index 660e21df4e..20e3e9e97b 100644
--- a/tests/unit/vision/test_image_budget.py
+++ b/tests/unit/vision/test_image_budget.py
@@ -47,3 +47,27 @@ def test_undecodable_input_falls_back_to_original() -> None:
# Telemetry/robustness: a bad image must never break the vision path.
bad = ("image/png", "not-valid-base64-image!!")
assert cap_image_b64(*bad, max_bytes=10) == bad
+
+
+def test_custom_max_dimension_downscales_further() -> None:
+ # L7 (CU speed): a smaller longest-side cap shrinks the payload more. Vision
+ # models resample to ~1568 px internally, so 2048 ships pixels they discard.
+ mime, b64 = _png_b64(2200, 1500)
+ out_mime, out_b64 = cap_image_b64(
+ mime, b64, max_bytes=200_000, max_dimension=1280,
+ )
+ from PIL import Image
+
+ img = Image.open(io.BytesIO(base64.b64decode(out_b64)))
+ assert out_mime == "image/jpeg"
+ assert max(img.size) <= 1280 # honours the custom longest-side cap
+
+
+def test_default_max_dimension_is_2048() -> None:
+ # No-regression: the default longest-side cap is unchanged (2048 px).
+ mime, b64 = _png_b64(2600, 1700)
+ _, out_b64 = cap_image_b64(mime, b64, max_bytes=200_000)
+ from PIL import Image
+
+ img = Image.open(io.BytesIO(base64.b64decode(out_b64)))
+ assert 2048 - 2 <= max(img.size) <= 2048 # still capped at the legacy 2048
diff --git a/tests/unit/voice/test_action_phrases.py b/tests/unit/voice/test_action_phrases.py
index 02ee78b1a4..795dce5cc2 100644
--- a/tests/unit/voice/test_action_phrases.py
+++ b/tests/unit/voice/test_action_phrases.py
@@ -79,6 +79,14 @@ class TestCuFailureReadback:
out = cu_failure_readback("en", error="exit 5", exit_code=5)
assert "screen" in out.lower()
+ def test_exit_2_names_invalid_model_response_not_screen_confusion(self) -> None:
+ # Live 2026-06-20: the CU brain provider chain returned no valid action
+ # response, but the user heard "I got confused on screen". Exit 2 is a
+ # model/parse failure; the readback must name that class honestly.
+ out = cu_failure_readback("en", error="exit 2", exit_code=2)
+ assert "confused" not in out.lower(), out
+ assert "valid screen-control response" in out.lower(), out
+
def test_exit_124_timeout_phrase_distinct_from_gave_up(self) -> None:
timed_out = cu_failure_readback("en", error="exit 124", exit_code=124)
gave_up = cu_failure_readback("en", error="exit 5", exit_code=5)
@@ -115,6 +123,150 @@ class TestCuFailureReadback:
assert "BridgeMind has no news channel" in out
assert not _EXIT_TOKEN_RE.search(out), out
+ def test_no_progress_guard_diagnostic_is_not_spoken(self) -> None:
+ # Live bug 2026-06-20 (Angela-Merkel x.com mission): the user heard
+ # "Das am Bildschirm hat nicht geklappt: 3 identical screenshots in a
+ # row at step 9 -- the click target is unreactive or off-screen."
+ # The no-progress guard writes a developer DIAGNOSTIC to stderr — it is
+ # loop instrumentation, not the model's human reason — so it must never
+ # be forwarded as the spoken reason. Fall back to the generic, localized
+ # exit-code phrase (exit 5 == the model gave up).
+ detail = (
+ "[cu] no progress: 3 identical screenshots in a row at step 9 -- "
+ "the click target is unreactive or off-screen."
+ )
+ out = cu_failure_readback("de", error="exit 5", exit_code=5, detail=detail)
+ assert "identical screenshots" not in out.lower(), out
+ assert "step 9" not in out.lower(), out
+ assert out == action_phrase("cu_exit_gave_up", "de")
+
+ def test_mission_profile_telemetry_never_reaches_readback(self) -> None:
+ # The latency profiler appends "[cu] mission profile: ..." to stderr on
+ # every _final; _cu_failure_detail forwards the WHOLE stderr block, so
+ # the telemetry rode along into the spoken readback. It must never be
+ # spoken or displayed.
+ detail = (
+ "[cu] no progress: 3 identical screenshots in a row at step 9 -- "
+ "the click target is unreactive or off-screen.\n"
+ "[cu] mission profile: steps=9 total=53.2s act=10.8s observe=2.1s "
+ "plan=5.2s think=27.6s verify=7.2s"
+ )
+ out = cu_failure_readback("de", error="exit 5", exit_code=5, detail=detail)
+ assert "mission profile" not in out.lower(), out
+ assert "[cu]" not in out.lower(), out
+ assert "steps=9" not in out, out
+
+ def test_anti_oscillation_guard_diagnostic_is_not_spoken(self) -> None:
+ # The toggle/guard family ("N guard-blocked actions this mission",
+ # "toggle-stop") is internal instrumentation too — not a spoken reason.
+ detail = "5 guard-blocked actions this mission (toggle-stop)"
+ out = cu_failure_readback("de", error="exit 5", exit_code=5, detail=detail)
+ assert "guard-blocked" not in out.lower(), out
+ assert out == action_phrase("cu_exit_gave_up", "de")
+
+ def test_internal_diagnostic_on_error_field_is_not_spoken(self) -> None:
+ # The same diagnostic arriving via the ``error`` field (path 2) must be
+ # rejected just like the ``detail`` path, not forwarded verbatim.
+ err = "3 identical screenshots in a row at step 9 -- the click target"
+ out = cu_failure_readback("de", error=err, exit_code=5)
+ assert "identical screenshots" not in out.lower(), out
+ assert out == action_phrase("cu_exit_gave_up", "de")
+
+ def test_bare_mission_profile_line_alone_is_not_spoken(self) -> None:
+ # Live bug 2026-06-22 (Ed-Sheeran "Perfect" turn): the spoken readback was
+ # "That didn't work on screen: steps=3 total=9.5s act=3.0s observe=0.3s
+ # plan=1.6s think=4.6s".
+ # When the detail is ONLY the "[cu] mission profile:" line (no preceding
+ # diagnostic line), _CU_REASON_PREFIX_RE strips the "[cu] mission profile:"
+ # PREFIX — deleting the very "[cu]"/"mission profile" markers the diagnostic
+ # gate keys on — so the BARE telemetry stats sailed through and were spoken.
+ # The profile is machine telemetry; detect it STRUCTURALLY and degrade to
+ # the generic exit-code phrase.
+ detail = (
+ "[cu] mission profile: steps=3 total=9.5s act=3.0s observe=0.3s "
+ "plan=1.6s think=4.6s"
+ )
+ out = cu_failure_readback("en", error="exit 5", exit_code=5, detail=detail)
+ assert "steps=" not in out, out
+ assert "total=" not in out, out
+ assert "9.5s" not in out, out
+ assert out == action_phrase("cu_exit_gave_up", "en")
+
+ def test_screenshot_path_never_reaches_readback(self) -> None:
+ # The harness temp capture path ("C:\\...\\pythonw_xxxx.png") rode the
+ # failure detail into the spoken text on the same 2026-06-22 turn. A spoken
+ # answer must never contain a filesystem path or an image filename.
+ detail = (
+ "steps=3 total=9.5s act=3.0s observe=0.3s plan=1.6s think=4.6s\n"
+ "'C:\\Users\\Administrator\\Desktop\\Personal Jarvis\\pythonw_TPMHbe4vdZ.png'"
+ )
+ out = cu_failure_readback("en", error="exit 5", exit_code=5, detail=detail)
+ assert ".png" not in out.lower(), out
+ assert "C:\\" not in out, out
+ assert "pythonw" not in out.lower(), out
+ assert out == action_phrase("cu_exit_gave_up", "en")
+
+ def test_telemetry_on_error_field_is_not_spoken(self) -> None:
+ # The bare profile arriving via the ``error`` field (path 2) is rejected
+ # too — same structural detection, with no "[cu]" prefix to strip.
+ err = "steps=6 total=30.1s act=5.0s observe=1.4s plan=3.0s think=7.2s"
+ out = cu_failure_readback("de", error=err, exit_code=5)
+ assert "steps=" not in out, out
+ assert out == action_phrase("cu_exit_gave_up", "de")
+
+ def test_real_reason_with_a_number_is_still_forwarded(self) -> None:
+ # False-positive guard: a genuine human reason that merely contains a
+ # number (but no key=value telemetry run and no path) must still be
+ # forwarded verbatim — the structural gate must not eat real answers.
+ reason = "The login form returned HTTP 403 after 2 attempts."
+ out = cu_failure_readback("en", error=reason, exit_code=5)
+ assert reason in out
+
+
+class TestElevationPausePhrases:
+ """Phrases for the UAC / privilege-prompt pause-and-resume flow.
+
+ When Computer-Use hits an OS elevation prompt (Windows Secure Desktop & co.)
+ it can neither see nor click it (UIPI). Instead of the misleading generic
+ "couldn't see the screen" abort (exit 1), it asks the user for the one
+ unavoidable confirmation click and continues — or, if no confirmation comes,
+ stops with an HONEST elevation-specific message (exit 9). Both surfaces must
+ exist in all supported languages.
+ """
+
+ def test_awaiting_elevation_localized_and_distinct(self) -> None:
+ de = action_phrase("cu_awaiting_elevation", "de")
+ en = action_phrase("cu_awaiting_elevation", "en")
+ es = action_phrase("cu_awaiting_elevation", "es")
+ for text in (de, en, es):
+ assert len(text) > 10
+ assert de != en != es
+ # It must tell the user WHAT to do: confirm an admin/security prompt.
+ assert "admin" in en.lower()
+
+ def test_awaiting_elevation_unknown_language_falls_back_to_german(self) -> None:
+ assert action_phrase("cu_awaiting_elevation", "fr") == action_phrase(
+ "cu_awaiting_elevation", "de"
+ )
+
+ def test_exit_9_is_the_needs_elevation_phrase(self) -> None:
+ # exit 9 == waited for the admin confirmation, none came. It must be an
+ # elevation-specific human sentence — NOT the generic "didn't work" and
+ # NOT the misleading "couldn't see the screen" (exit 1).
+ for lang in ("de", "en", "es"):
+ out = cu_failure_readback(lang, error="exit 9", exit_code=9)
+ assert not _EXIT_TOKEN_RE.search(out), out
+ assert out == action_phrase("cu_exit_needs_elevation", lang)
+ assert out != action_phrase("cu_failed", lang)
+ assert out != action_phrase("cu_exit_no_view", lang)
+
+ def test_exit_9_distinct_from_no_view_and_gave_up(self) -> None:
+ needs_elev = cu_failure_readback("en", error="exit 9", exit_code=9)
+ no_view = cu_failure_readback("en", error="exit 1", exit_code=1)
+ gave_up = cu_failure_readback("en", error="exit 5", exit_code=5)
+ assert needs_elev != no_view != gave_up
+ assert needs_elev != gave_up
+
class TestCuSuccessReadback:
"""The SUCCESS sibling of cu_failure_readback (live bug 2026-06-18, session
@@ -159,3 +311,60 @@ class TestCuSuccessReadback:
assert cu_success_readback(
"es", stdout="[cu] done at step 2 (verified: )\n"
) == action_phrase("cu_done", "es")
+
+ def test_blocks_raw_verifier_ui_structure_dump(self) -> None:
+ """The read-goal verifier sometimes PROVES done by describing the UI
+ structurally instead of answering the user. Such a dump is an internal
+ evidence artifact — it must NOT be spoken verbatim. Live bug 2026-06-21
+ (Melbourne HTML turn): "look at my screen and tell me which app is open"
+ read out the full structural dump, including the verbatim content of an
+ unrelated parallel Claude-Code AskUserQuestion box.
+ """
+ from jarvis.voice.action_phrases import action_phrase, cu_success_readback
+
+ stdout = (
+ "[cu] done at step 2.1 (verified: Foreground window (right, orange "
+ "border, on top): title 'Eine Detail-Erkenntnis (deine Entscheidung)', "
+ "content starts 'Der Melbourne-Guide rendert unter der strengen "
+ "Sicherheits-CSP inhaltlich und optisch vollstaendig. Nur ein kleines "
+ "inline-<script>...' followed by bullet points on CSP, JS, and 'Die "
+ "Aenderungen sind uncommitted...'. Bottom status bar: 'Personal "
+ "Jarvis % main Opus 4.8 (1M context)')\n"
+ )
+ out = cu_success_readback("de", stdout=stdout)
+ # The dump (and the leaked foreign box content) must NOT be spoken.
+ assert out == action_phrase("cu_done", "de"), out
+ assert "Detail-Erkenntnis" not in out
+ assert "Foreground window" not in out
+ assert "status bar" not in out.lower()
+
+ def test_blocks_individual_ui_structure_markers(self) -> None:
+ from jarvis.voice.action_phrases import action_phrase, cu_success_readback
+
+ done_de = action_phrase("cu_done", "de")
+ for proof in (
+ "Foreground window shows the settings page",
+ "The active window is the editor",
+ "Bottom status bar: Ready",
+ "Statusleiste zeigt Bereit",
+ "title 'X', content starts with a heading and a paragraph",
+ "a list followed by bullet points on three topics",
+ ):
+ stdout = f"[cu] done at step 1 (verified: {proof})\n"
+ assert cu_success_readback("de", stdout=stdout) == done_de, proof
+
+ def test_blocks_bare_telemetry_profile_and_paths_on_success(self) -> None:
+ """The user reported the giant dump on SUCCESS too. The shared structural
+ gate must protect the success readback: a verified-proof that is really a
+ telemetry profile, or that carries a leaked screenshot path, degrades to
+ the plain done phrase instead of being spoken."""
+ from jarvis.voice.action_phrases import action_phrase, cu_success_readback
+
+ done_en = action_phrase("cu_done", "en")
+ for proof in (
+ "steps=3 total=9.5s act=3.0s observe=0.3s plan=1.6s think=4.6s",
+ "saved C:\\Users\\Administrator\\Desktop\\Personal Jarvis\\pythonw_x.png",
+ "see screenshot pythonw_TPMHbe4vdZ.png",
+ ):
+ stdout = f"[cu] done at step 3 (verified: {proof})\n"
+ assert cu_success_readback("en", stdout=stdout) == done_en, proof
diff --git a/tests/unit/voice/test_tool_confirmation.py b/tests/unit/voice/test_tool_confirmation.py
index ee2ab0fb7e..2d82755195 100644
--- a/tests/unit/voice/test_tool_confirmation.py
+++ b/tests/unit/voice/test_tool_confirmation.py
@@ -5,9 +5,9 @@ through the two-turn confirmation flow.
Root cause this module is part of (2026-06-18, session 2995997b): an ``ask``-tier
tool (gmail) invoked on the voice path blocks in ``ApprovalWorkflow.wait()`` for a
UI approval the voice user never gives; the 20 s no-first-frame ceiling then
-beheads the turn and speaks the misleading "Das hat gerade zu lange gedauert. Sag
-es bitte noch einmal." Instead of hanging, Jarvis now SPEAKS a short confirmation
-question and the next "ja"/"nein" resolves it.
+beheads the turn and speaks the brain-timeout fallback. Instead of hanging,
+Jarvis now SPEAKS a short confirmation question and the next "ja"/"nein" resolves
+it.
Runtime Output Language doctrine: every spoken phrase carries de/en/es.
"""
diff --git a/ui/orb/bus_bridge.py b/ui/orb/bus_bridge.py
index 4cb512caf2..c71cabdf74 100644
--- a/ui/orb/bus_bridge.py
+++ b/ui/orb/bus_bridge.py
@@ -45,6 +45,8 @@ from jarvis.core.events import (
SystemStateChanged,
TranscriptionUpdate,
UserVisibleFeedback,
+ WakeWordDetected,
+ VoiceBootStatus,
VoiceMuteToggleRequested,
VoiceSessionEnded,
VoiceSessionStarted,
@@ -201,11 +203,25 @@ class OrbBusBridge:
# drives _on_state without publishing VoiceSession events (and the
# very first session before any end-event) behaves exactly as before.
self._suppress_show_until_session: bool = False
+ # Boot-readiness gate. The persistent bar must not appear before the
+ # speech pipeline can actually hear the user — otherwise the user sees
+ # the bar on boot and assumes Jarvis is listening when warm-up is still
+ # running. ``reveal_bar_when_voice_ready`` waits for this event (set on
+ # VoiceBootStatus(ready=True)) and then reveals the persistent bar once.
+ # ``_boot_reveal_done`` makes the reveal idempotent across the ready
+ # signal and the fallback timeout. asyncio.Event() is loop-agnostic at
+ # construction (Py3.10+ dropped the loop param; project minimum is
+ # 3.11), so it is safe to build off the running loop.
+ self._voice_ready_event = asyncio.Event()
+ self._boot_reveal_done: bool = False
def attach(self) -> None:
"""Subscribt die Bridge auf SystemStateChanged. Idempotent."""
try:
self._bus.subscribe(SystemStateChanged, self._on_state)
+ # Earliest safe visual wake cue: WakeWordDetected is emitted only
+ # after wake verification, before the later session/state events.
+ self._bus.subscribe(WakeWordDetected, self._on_wake_word_detected)
# Voice-session lifecycle: the orb tracks SESSION boundaries, not
# just raw turn-states, so a late in-flight turn after a hangup
# cannot resurrect the mascot (orb-resurrection bug 2026-05-29).
@@ -216,6 +232,9 @@ class OrbBusBridge:
self._bus.subscribe(ResponseGenerated, self._on_response_generated)
self._bus.subscribe(OpenClawBackgroundCompleted, self._on_background_completed)
self._bus.subscribe(AudioOutFirst, self._on_audio_out_first)
+ # Boot-readiness gate: the persistent bar is revealed only once the
+ # speech pipeline signals it can actually hear the user.
+ self._bus.subscribe(VoiceBootStatus, self._on_voice_boot_status)
# ADR-0016 L2 — voice-driven recovery from "orb lost on screen".
# The local_action_gate publishes OrbResetRequested when the
# user says "Orb zurück" / "wo bist du" / "reset orb".
@@ -369,6 +388,18 @@ class OrbBusBridge:
except RuntimeError as exc:
log.warning("show-window publish dropped: %s", exc)
+ async def _on_wake_word_detected(self, event: WakeWordDetected) -> None:
+ """Pop the orb on the earliest confirmed wake signal."""
+ log.info("OrbBridge._on_wake_word_detected: keyword=%s", event.keyword)
+ prev_state = self._last_state
+ self._last_state_trace_id = str(event.trace_id)
+ self._suppress_show_until_session = False
+ self._last_state = "LISTENING"
+ self._orb.show(mode="listen")
+ if prev_state in ("IDLE", "ERROR", "PAUSED"):
+ self._orb.play_animation("wave")
+ self._cancel_idle_scheduler()
+
async def _on_session_started(self, event: VoiceSessionStarted) -> None:
"""A genuine new voice session began (wake-word / hotkey / call).
@@ -431,6 +462,49 @@ class OrbBusBridge:
)
self._suppress_show_until_session = True
+ async def _on_voice_boot_status(self, event: VoiceBootStatus) -> None:
+ """Track the speech-pipeline boot readiness.
+
+ ``ready=True`` (emitted once Phase A of warm-up is live — audio + VAD +
+ wake + STT + TTS client) releases the boot gate so the persistent bar is
+ revealed. ``ready=False`` (warm-up start) is ignored — the bar stays
+ hidden until voice can genuinely hear the user.
+ """
+ if event.ready:
+ self._voice_ready_event.set()
+
+ async def reveal_bar_when_voice_ready(self, *, timeout_s: float = 30.0) -> None:
+ """Keep the persistent bar hidden until voice is ready, then reveal it.
+
+ Scheduled once on the event loop at boot. Waits for
+ ``VoiceBootStatus(ready=True)``; if it never arrives within ``timeout_s``
+ (voice offline / pipeline crashed at startup), the bar is revealed anyway
+ so a degraded host is not left with no bar at all — a few seconds late
+ instead of never. A non-persistent bar / the mascot (``hide_on_idle``)
+ is left untouched: it pops on a real session, not at boot.
+ """
+ reason = "timeout-fallback"
+ try:
+ await asyncio.wait_for(self._voice_ready_event.wait(), timeout_s)
+ reason = "voice-ready"
+ except TimeoutError:
+ pass
+ self._reveal_persistent_bar(reason)
+
+ def _reveal_persistent_bar(self, reason: str) -> None:
+ """Show the persistent bar's idle pill exactly once. Idempotent."""
+ if self._boot_reveal_done:
+ return
+ self._boot_reveal_done = True
+ if self._hide_on_idle:
+ # Non-persistent bar / mascot: stays hidden until a voice session.
+ return
+ try:
+ self._orb.show("idle")
+ log.info("Persistent overlay revealed after boot (%s).", reason)
+ except Exception: # noqa: BLE001
+ log.debug("persistent bar boot reveal failed", exc_info=True)
+
async def _on_state(self, event: SystemStateChanged) -> None:
state = event.new_state
# ADR-0016: remember the trace_id so the next visibility snapshot
diff --git a/ui/orb/overlay.py b/ui/orb/overlay.py
index fc35f610bb..6636b75974 100644
--- a/ui/orb/overlay.py
+++ b/ui/orb/overlay.py
@@ -1453,6 +1453,21 @@ class OrbOverlay:
self._canvas.bind("<Button-3>", self._on_right_click)
self._canvas.bind("<Button-2>", self._on_reset_double_click)
+ # Drag-drop onto the mascot (desktop extra, cross-platform via tkdnd).
+ # Pure addition, fully guarded: a no-op when tkinterdnd2 is absent
+ # (NullDropTarget) so the live overlay is never destabilised. Dropped
+ # paths/text go to the process-global bridge, which the desktop app
+ # marshals to the brain intake (jarvis/brain/drop_context.ingest_drop).
+ try:
+ from jarvis.overlay.drop_bridge import dispatch_drop
+ from jarvis.overlay.drop_target import make_drop_target
+
+ make_drop_target().register(self._canvas, dispatch_drop)
+ except Exception: # noqa: BLE001 — drop is optional; never block orb boot.
+ logging.getLogger("jarvis.orb").debug(
+ "mascot drop target registration skipped", exc_info=True
+ )
+
self._comment_bubble = OrbCommentBubble(
parent=self._root,
orb_x=anchor.x,